diff --git a/go.mod b/go.mod index 0a3df4ff7..83c338ddc 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/fortytw2/leaktest v1.3.0 github.com/go-kit/kit v0.12.0 github.com/golang/protobuf v1.5.3 - github.com/google/uuid v1.3.0 + github.com/google/uuid v1.5.0 github.com/gorilla/mux v1.8.0 github.com/grafana/regexp v0.0.0-20221122212121-6b5c0a4cb7fd github.com/influxdata/influxdb v1.8.5 @@ -20,122 +20,125 @@ require ( github.com/json-iterator/go v1.1.12 github.com/onsi/ginkgo v1.16.5 github.com/onsi/gomega v1.28.0 - github.com/prometheus/client_golang v1.17.0 - github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 - github.com/prometheus/common v0.45.0 - github.com/prometheus/prometheus v0.44.0 + github.com/prometheus/client_golang v1.18.0 + github.com/prometheus/client_model v0.5.0 + github.com/prometheus/common v0.46.0 + github.com/prometheus/prometheus v0.50.1 go.uber.org/atomic v1.11.0 go.uber.org/zap v1.26.0 - golang.org/x/net v0.17.0 - golang.org/x/sys v0.13.0 - google.golang.org/grpc v1.56.3 + golang.org/x/net v0.20.0 + golang.org/x/sys v0.16.0 + google.golang.org/grpc v1.61.0 gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v3 v3.0.1 sigs.k8s.io/yaml v1.3.0 ) require ( - cloud.google.com/go/compute v1.20.1 // indirect + cloud.google.com/go/compute v1.23.3 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect code.cloudfoundry.org/rfc5424 v0.0.0-20180905210152-236a6d29298a // indirect collectd.org v0.5.0 // indirect - github.com/Azure/azure-sdk-for-go v65.0.0+incompatible // indirect + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.4.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 v4.3.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect - github.com/Azure/go-autorest v14.2.0+incompatible // indirect - github.com/Azure/go-autorest/autorest v0.11.28 // indirect github.com/Azure/go-autorest/autorest/adal v0.9.23 // indirect - github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect - github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect - github.com/Azure/go-autorest/autorest/validation v0.3.1 // indirect - github.com/Azure/go-autorest/logger v0.2.1 // indirect - github.com/Azure/go-autorest/tracing v0.6.0 // indirect - github.com/Microsoft/go-winio v0.6.0 // indirect - github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect - github.com/apache/arrow/go/v11 v11.0.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 // indirect + github.com/Code-Hex/go-generics-cache v1.3.1 // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect + github.com/alecthomas/units v0.0.0-20231202071711-9a357b53e9c9 // indirect + github.com/apache/arrow/go/v12 v12.0.1 // indirect github.com/armon/go-metrics v0.4.1 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/aws/aws-sdk-go v1.44.245 // indirect + github.com/aws/aws-sdk-go v1.50.0 // indirect + github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect - github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/cncf/xds/go v0.0.0-20231109132714-523115ebc101 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dennwc/varint v1.0.0 // indirect github.com/dgryski/go-bitstream v0.0.0-20180413035011-3522498ce2c8 // indirect - github.com/digitalocean/godo v1.98.0 // indirect - github.com/docker/distribution v2.8.2+incompatible // indirect - github.com/docker/docker v24.0.7+incompatible // indirect + github.com/digitalocean/godo v1.108.0 // indirect + github.com/distribution/reference v0.5.0 // indirect + github.com/docker/docker v25.0.0+incompatible // indirect github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.5.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect github.com/edsrzf/mmap-go v1.1.0 // indirect - github.com/emicklei/go-restful/v3 v3.10.1 // indirect - github.com/envoyproxy/go-control-plane v0.11.1-0.20230524094728-9239064ad72f // indirect - github.com/envoyproxy/protoc-gen-validate v0.10.1 // indirect - github.com/fatih/color v1.14.1 // indirect - github.com/felixge/httpsnoop v1.0.3 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/envoyproxy/go-control-plane v0.12.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.0.4 // indirect + github.com/facette/natsort v0.0.0-20181210072756-2cd4dd1e2dcb // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/glycerine/go-unsnap-stream v0.0.0-20190901134440-81cf024a9e0a // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect - github.com/go-logr/logr v1.2.4 // indirect + github.com/go-logr/logr v1.4.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/analysis v0.21.4 // indirect - github.com/go-openapi/errors v0.20.3 // indirect - github.com/go-openapi/jsonpointer v0.19.6 // indirect + github.com/go-openapi/errors v0.21.0 // indirect + github.com/go-openapi/jsonpointer v0.20.0 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/loads v0.21.2 // indirect - github.com/go-openapi/spec v0.20.8 // indirect - github.com/go-openapi/strfmt v0.21.7 // indirect - github.com/go-openapi/swag v0.22.3 // indirect + github.com/go-openapi/spec v0.20.9 // indirect + github.com/go-openapi/strfmt v0.22.0 // indirect + github.com/go-openapi/swag v0.22.4 // indirect github.com/go-openapi/validate v0.22.1 // indirect - github.com/go-resty/resty/v2 v2.7.0 // indirect + github.com/go-resty/resty/v2 v2.11.0 // indirect github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect github.com/go-zookeeper/zk v1.0.3 // indirect github.com/goccy/go-json v0.9.11 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang-jwt/jwt/v4 v4.5.0 // indirect + github.com/golang-jwt/jwt/v5 v5.2.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/snappy v0.0.4 // indirect - github.com/google/gnostic v0.6.9 // indirect - github.com/google/go-cmp v0.5.9 // indirect + github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/go-cmp v0.6.0 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/gofuzz v1.2.0 // indirect - github.com/google/pprof v0.0.0-20230406165453-00490a63f317 // indirect - github.com/google/s2a-go v0.1.4 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect - github.com/googleapis/gax-go/v2 v2.11.0 // indirect - github.com/gophercloud/gophercloud v1.3.0 // indirect + github.com/google/pprof v0.0.0-20240117000934-35fc243c5815 // indirect + github.com/google/s2a-go v0.1.7 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect + github.com/googleapis/gax-go/v2 v2.12.0 // indirect + github.com/gophercloud/gophercloud v1.8.0 // indirect github.com/gorilla/websocket v1.5.0 // indirect - github.com/hashicorp/consul/api v1.20.0 // indirect - github.com/hashicorp/cronexpr v1.1.1 // indirect + github.com/hashicorp/consul/api v1.27.0 // indirect + github.com/hashicorp/cronexpr v1.1.2 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect - github.com/hashicorp/go-hclog v1.4.0 // indirect + github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-retryablehttp v0.7.2 // indirect + github.com/hashicorp/go-retryablehttp v0.7.4 // indirect github.com/hashicorp/go-rootcerts v1.0.2 // indirect + github.com/hashicorp/go-version v1.6.0 // indirect github.com/hashicorp/golang-lru v0.6.0 // indirect - github.com/hashicorp/nomad/api v0.0.0-20230418003350-3067191c5197 // indirect + github.com/hashicorp/nomad/api v0.0.0-20230721134942-515895c7690c // indirect github.com/hashicorp/serf v0.10.1 // indirect - github.com/hetznercloud/hcloud-go v1.42.0 // indirect - github.com/imdario/mergo v0.3.13 // indirect + github.com/hetznercloud/hcloud-go/v2 v2.6.0 // indirect + github.com/imdario/mergo v0.3.16 // indirect github.com/influxdata/flux v0.194.1 // indirect github.com/influxdata/roaring v0.4.13-0.20180809181101-fc520f41fab6 // indirect - github.com/ionos-cloud/sdk-go/v6 v6.1.6 // indirect + github.com/ionos-cloud/sdk-go/v6 v6.1.11 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/jpillora/backoff v1.0.0 // indirect github.com/jsternberg/zap-logfmt v1.2.0 // indirect github.com/julienschmidt/httprouter v1.3.0 // indirect github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef // indirect - github.com/klauspost/compress v1.15.9 // indirect + github.com/klauspost/compress v1.17.4 // indirect github.com/kolo/xmlrpc v0.0.0-20220921171641-a4b6fa1dd06b // indirect - github.com/linode/linodego v1.16.1 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/linode/linodego v1.27.1 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.17 // indirect - github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect - github.com/miekg/dns v1.1.53 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/miekg/dns v1.1.58 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect @@ -149,15 +152,16 @@ require ( github.com/onsi/ginkgo/v2 v2.12.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.0.2 // indirect - github.com/ovh/go-ovh v1.4.1 // indirect + github.com/ovh/go-ovh v1.4.3 // indirect github.com/philhofer/fwd v1.0.0 // indirect github.com/pierrec/lz4/v4 v4.1.15 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/alertmanager v0.25.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/alertmanager v0.26.0 // indirect github.com/prometheus/common/sigv4 v0.1.0 // indirect - github.com/prometheus/procfs v0.11.1 // indirect - github.com/scaleway/scaleway-sdk-go v1.0.0-beta.15 // indirect + github.com/prometheus/procfs v0.12.0 // indirect + github.com/scaleway/scaleway-sdk-go v1.0.0-beta.22 // indirect github.com/sergi/go-diff v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/testify v1.8.4 // indirect @@ -165,40 +169,43 @@ require ( github.com/vultr/govultr/v2 v2.17.2 // indirect github.com/willf/bitset v1.1.10 // indirect github.com/xlab/treeprint v1.1.0 // indirect - go.mongodb.org/mongo-driver v1.11.3 // indirect + go.mongodb.org/mongo-driver v1.13.1 // indirect go.opencensus.io v0.24.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.44.0 // indirect - go.opentelemetry.io/otel v1.18.0 // indirect - go.opentelemetry.io/otel/metric v1.18.0 // indirect - go.opentelemetry.io/otel/trace v1.18.0 // indirect - go.uber.org/goleak v1.2.1 // indirect - go.uber.org/multierr v1.10.0 // indirect - golang.org/x/crypto v0.14.0 // indirect - golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect - golang.org/x/mod v0.12.0 // indirect - golang.org/x/oauth2 v0.12.0 // indirect - golang.org/x/sync v0.3.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 - google.golang.org/api v0.126.0 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20230530153820-e85fd2cbaebc // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc // indirect - google.golang.org/protobuf v1.31.0 // indirect + go.opentelemetry.io/collector/featuregate v1.0.1 // indirect + go.opentelemetry.io/collector/pdata v1.0.1 // indirect + go.opentelemetry.io/collector/semconv v0.93.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.47.0 // indirect + go.opentelemetry.io/otel v1.22.0 // indirect + go.opentelemetry.io/otel/metric v1.22.0 // indirect + go.opentelemetry.io/otel/trace v1.22.0 // indirect + go.uber.org/goleak v1.3.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/crypto v0.18.0 // indirect + golang.org/x/exp v0.0.0-20240119083558-1b970713d09a // indirect + golang.org/x/mod v0.14.0 // indirect + golang.org/x/oauth2 v0.16.0 // indirect + golang.org/x/sync v0.6.0 // indirect + golang.org/x/term v0.16.0 // indirect + golang.org/x/text v0.14.0 // indirect + golang.org/x/time v0.5.0 // indirect + golang.org/x/tools v0.17.0 // indirect + google.golang.org/api v0.157.0 // indirect + google.golang.org/appengine v1.6.8 // indirect + google.golang.org/genproto v0.0.0-20240102182953-50ed04b92917 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20240116215550-a9fa1716bcac // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac // indirect + google.golang.org/protobuf v1.32.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect - k8s.io/api v0.26.2 // indirect - k8s.io/apimachinery v0.26.2 // indirect - k8s.io/client-go v0.26.2 // indirect - k8s.io/klog/v2 v2.90.1 // indirect - k8s.io/kube-openapi v0.0.0-20230303024457-afdc3dddf62d // indirect - k8s.io/utils v0.0.0-20230308161112-d77c459e9343 // indirect + k8s.io/api v0.28.6 // indirect + k8s.io/apimachinery v0.28.6 // indirect + k8s.io/client-go v0.28.6 // indirect + k8s.io/klog/v2 v2.120.1 // indirect + k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect + k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect ) replace github.com/influxdata/influxdb => github.com/attack/influxdb v1.8.4-0.20230516101340-aeacf4fd10d8 diff --git a/go.sum b/go.sum index d02eb5e46..6b2b2ff17 100644 --- a/go.sum +++ b/go.sum @@ -37,7 +37,7 @@ cloud.google.com/go v0.102.1/go.mod h1:XZ77E9qnTEnrgEOvr4xzfdX5TRo7fB4T2F4O6+34h cloud.google.com/go v0.104.0/go.mod h1:OO6xxXdJyvuJPcEPBLN9BJPD+jep5G1+2U5B5gkRYtA= cloud.google.com/go v0.105.0/go.mod h1:PrLgOJNe5nfE9UMxKxgXj4mD3voiP+YQ6gdt6KMFOKM= cloud.google.com/go v0.107.0/go.mod h1:wpc2eNrD7hXUTy8EKS10jkxpZBjASrORK7goS+3YX2I= -cloud.google.com/go v0.110.2 h1:sdFPBr6xG9/wkBbfhmUz/JmZC7X6LavQgcrVINrKiVA= +cloud.google.com/go v0.111.0 h1:YHLKNupSD1KqjDbQ3+LVdQ81h/UJbJyZG203cEfnQgM= cloud.google.com/go/accessapproval v1.4.0/go.mod h1:zybIuC3KpDOvotz59lFe5qxRZx6C75OtwbisN56xYB4= cloud.google.com/go/accessapproval v1.5.0/go.mod h1:HFy3tuiGvMdcd/u+Cu5b9NkO1pEICJ46IR82PoUdplw= cloud.google.com/go/accesscontextmanager v1.3.0/go.mod h1:TgCBehyr5gNMz7ZaH9xubp+CE8dkrszb4oK9CWyvD4o= @@ -88,7 +88,7 @@ cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM7 cloud.google.com/go/bigquery v1.42.0/go.mod h1:8dRTJxhtG+vwBKzE5OseQn/hiydoQN3EedCaOdYmxRA= cloud.google.com/go/bigquery v1.43.0/go.mod h1:ZMQcXHsl+xmU1z36G2jNGZmKp9zNY5BUua5wDgmNCfw= cloud.google.com/go/bigquery v1.44.0/go.mod h1:0Y33VqXTEsbamHJvJHdFmtqHvMIY28aK1+dFsvaChGc= -cloud.google.com/go/bigquery v1.50.0 h1:RscMV6LbnAmhAzD893Lv9nXXy2WCaJmbxYPWDLbGqNQ= +cloud.google.com/go/bigquery v1.57.1 h1:FiULdbbzUxWD0Y4ZGPSVCDLvqRSyCIO6zKV7E2nf5uA= cloud.google.com/go/bigtable v1.2.0/go.mod h1:JcVAOl45lrTmQfLj7T6TxyMzIN/3FGGcFm+2xVAli2o= cloud.google.com/go/bigtable v1.10.1 h1:QKcRHeAsraxIlrdCZ3LLobXKBvITqcOEnSbHG2rzL9g= cloud.google.com/go/billing v1.4.0/go.mod h1:g9IdKBEFlItS8bTtlrZdVLWSSdSyFUZKXNS02zKMOZY= @@ -123,8 +123,8 @@ cloud.google.com/go/compute v1.12.1/go.mod h1:e8yNOBcBONZU1vJKCvCoDw/4JQsA0dpM4x cloud.google.com/go/compute v1.13.0/go.mod h1:5aPTS0cUNMIc1CE546K+Th6weJUNQErARyZtRXDJ8GE= cloud.google.com/go/compute v1.14.0/go.mod h1:YfLtxrj9sU4Yxv+sXzZkyPjEyPBZfXHUvjxega5vAdo= cloud.google.com/go/compute v1.15.1/go.mod h1:bjjoF/NtFUrkD/urWfdHaKuOPDR5nWIs63rR+SXhcpA= -cloud.google.com/go/compute v1.20.1 h1:6aKEtlUiwEpJzM001l0yFkpXmUVXaN8W+fbkb2AZNbg= -cloud.google.com/go/compute v1.20.1/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= +cloud.google.com/go/compute v1.23.3 h1:6sVlXXBmbd7jNX0Ipq0trII3e4n1/MsADLK6a+aiVlk= +cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI= cloud.google.com/go/compute/metadata v0.1.0/go.mod h1:Z1VN+bulIf6bt4P/C37K4DyZYZEXYonfTBHHFPO/4UU= cloud.google.com/go/compute/metadata v0.2.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= cloud.google.com/go/compute/metadata v0.2.1/go.mod h1:jgHgmJd2RKBGzXqF5LR2EZMGxBkeanZ9wwa75XHJgOM= @@ -214,7 +214,7 @@ cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3Q cloud.google.com/go/iam v0.6.0/go.mod h1:+1AH33ueBne5MzYccyMHtEKqLE4/kJOibtffMHDMFMc= cloud.google.com/go/iam v0.7.0/go.mod h1:H5Br8wRaDGNc8XP3keLc4unfUUZeyH3Sfl9XpQEYOeg= cloud.google.com/go/iam v0.8.0/go.mod h1:lga0/y3iH6CX7sYqypWJ33hf7kkfXJag67naqGESjkE= -cloud.google.com/go/iam v0.13.0 h1:+CmB+K0J/33d0zSQ9SlFWUeCCEn5XJA0ZMZ3pHE9u8k= +cloud.google.com/go/iam v1.1.5 h1:1jTsCu4bcsNsE4iiqNT5SHwrDRCfRmIaaaVFhRveTJI= cloud.google.com/go/iap v1.4.0/go.mod h1:RGFwRJdihTINIe4wZ2iCP0zF/qu18ZwyKxrhMhygBEc= cloud.google.com/go/iap v1.5.0/go.mod h1:UH/CGgKd4KyohZL5Pt0jSKE4m3FR51qg6FKQ/z/Ix9A= cloud.google.com/go/ids v1.1.0/go.mod h1:WIuwCaYVOzHIj2OhN9HAwvW+DBdmUAdcWlFxRl+KubM= @@ -233,7 +233,7 @@ cloud.google.com/go/lifesciences v0.6.0/go.mod h1:ddj6tSX/7BOnhxCSd3ZcETvtNr8NZ6 cloud.google.com/go/logging v1.6.1/go.mod h1:5ZO0mHHbvm8gEmeEUHrmDlTDSu5imF6MUP9OfilNXBw= cloud.google.com/go/longrunning v0.1.1/go.mod h1:UUFxuDWkv22EuY93jjmDMFT5GPQKeFVJBIF6QlTqdsE= cloud.google.com/go/longrunning v0.3.0/go.mod h1:qth9Y41RRSUE69rDcOn6DdK3HfQfsUI0YSmW3iIlLJc= -cloud.google.com/go/longrunning v0.4.1 h1:v+yFJOfKC3yZdY6ZUI933pIYdhyhV8S3NpWrXWmg7jM= +cloud.google.com/go/longrunning v0.5.4 h1:w8xEcbZodnA2BbW6sVirkkoC+1gP8wS57EUUgGS0GVg= cloud.google.com/go/managedidentities v1.3.0/go.mod h1:UzlW3cBOiPrzucO5qWkNkh0w33KFtBJU281hacNvsdE= cloud.google.com/go/managedidentities v1.4.0/go.mod h1:NWSBYbEMgqmbZsLIyKvxrYbtqOsxY1ZrGM+9RgDqInM= cloud.google.com/go/maps v0.1.0/go.mod h1:BQM97WGyfw9FWEmQMpZ5T6cpovXXSd1cGmFma94eubI= @@ -414,6 +414,18 @@ filippo.io/edwards25519 v1.0.0-rc.1 h1:m0VOOB23frXZvAOK44usCgLWvtsxIoMCTBGJZlpmG github.com/Azure/azure-pipeline-go v0.2.3 h1:7U9HBg1JFK3jHl5qmo4CTZKFTVgMwdFHMVtCdfBE21U= github.com/Azure/azure-sdk-for-go v65.0.0+incompatible h1:HzKLt3kIwMm4KeJYTdx9EbjRYTySD/t8i1Ee/W5EGXw= github.com/Azure/azure-sdk-for-go v65.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 h1:lGlwhPtrX6EVml1hO0ivjkUxsSyl4dsiw9qcA1k/3IQ= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1/go.mod h1:RKUqNu35KJYcVG/fqTRqmuXJZYNhYkBrnC/hX7yGbTA= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 h1:sO0/P7g68FrryJzljemN+6GTssUXdANk6aJ7T1ZxnsQ= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1/go.mod h1:h8hyGFDsU5HMivxiS2iYFZsgDbU9OnnJ163x5UGVKYo= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 h1:6oNBlSdi1QqM1PNW7FPA6xOGA5UNsXnkaYZz9vdPGhA= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.4.0 h1:QfV5XZt6iNa2aWMAt96CZEbfJ7kgG/qYIpq465Shr5E= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.4.0/go.mod h1:uYt4CfhkJA9o0FN7jfE5minm/i4nUE4MjGUJkzB6Zs8= +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/network/armnetwork/v4 v4.3.0 h1:bXwSugBiSbgtz7rOtbfGf+woewp4f06orW9OP5BjHLA= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 v4.3.0/go.mod h1:Y/HgrePTmGy9HjdSGTqZNa+apUpTVIEVKXJyARP2lrk= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.1.1 h1:7CBQ+Ei8SP2c6ydQTGCCrS35bDxgTMfoP2miAwK++OU= github.com/Azure/azure-storage-blob-go v0.14.0 h1:1BCg74AmVdYwO3dlKwtFU1V0wU2PZdREkXvAmZJRUlM= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= @@ -431,19 +443,20 @@ github.com/Azure/go-autorest/autorest/azure/cli v0.4.2 h1:dMOmEJfkLKW/7JsokJqkyo github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= -github.com/Azure/go-autorest/autorest/mocks v0.4.2 h1:PGN4EDXnuQbojHbU0UWoNvmu9AGVwYHG9/fkDYhtAfw= github.com/Azure/go-autorest/autorest/mocks v0.4.2/go.mod h1:Vy7OitM9Kei0i1Oj+LvyAWMXJHeKH1MVlzFugfVrmyU= -github.com/Azure/go-autorest/autorest/to v0.4.0 h1:oXVqrxakqqV1UZdSazDOPOLvOIz+XA683u8EctwboHk= github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE= -github.com/Azure/go-autorest/autorest/validation v0.3.1 h1:AgyqjAd94fwNAoTjl/WQXg4VvFeRFpO+UhNyRXqF1ac= github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg= github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/Code-Hex/go-generics-cache v1.3.1 h1:i8rLwyhoyhaerr7JpjtYjJZUcCbWOdiYO3fZXLiEC4g= +github.com/Code-Hex/go-generics-cache v1.3.1/go.mod h1:qxcC9kRVrct9rHeiYpFWSoW1vxyillCVzX13KZG8dl4= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/DATA-DOG/go-sqlmock v1.4.1 h1:ThlnYciV1iM/V0OSF/dtkqWb6xo5qITT1TJBG1MRDJM= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= @@ -458,8 +471,8 @@ github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF0 github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Microsoft/go-winio v0.5.1/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= -github.com/Microsoft/go-winio v0.6.0 h1:slsWYD/zyx7lCXoZVlvQrj0hPTM1HI4+v1sIda2yDvg= -github.com/Microsoft/go-winio v0.6.0/go.mod h1:cTAf44im0RAYeL23bpB+fzCyDH2MJiz2BO69KH/soAE= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= @@ -477,16 +490,17 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/alecthomas/units v0.0.0-20231202071711-9a357b53e9c9 h1:ez/4by2iGztzR4L0zgAOR8lTQK9VlyBVVd7G4omaOQs= +github.com/alecthomas/units v0.0.0-20231202071711-9a357b53e9c9/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/apache/arrow/go/arrow v0.0.0-20191024131854-af6fa24be0db/go.mod h1:VTxUBvSJ3s3eHAg65PNgrsn5BtqCRPdmyXh6rAfdxN0= github.com/apache/arrow/go/arrow v0.0.0-20211112161151-bc219186db40 h1:q4dksr6ICHXqG5hm0ZW5IHyeEJXoIJSOZeBLmWPNeIQ= -github.com/apache/arrow/go/v11 v11.0.0 h1:hqauxvFQxww+0mEU/2XHG6LT7eZternCZq+A5Yly2uM= -github.com/apache/arrow/go/v11 v11.0.0/go.mod h1:Eg5OsL5H+e299f7u5ssuXsuHQVEGC4xei5aX110hRiI= +github.com/apache/arrow/go/v12 v12.0.1 h1:JsR2+hzYYjgSUkBSaahpqCetqZMr76djX80fF/DiJbg= +github.com/apache/arrow/go/v12 v12.0.1/go.mod h1:weuTY7JvTG/HDPtMQxEUp7pU73vkLWMLpY67QwZ/WWw= github.com/apache/arrow/go/v7 v7.0.1 h1:WpCfq+AQxvXaI6/KplHE27MPMFx5av0o5NbPCTAGfy4= github.com/apache/thrift v0.16.0 h1:qEy6UW60iVOlUy+b9ZR0d5WzUWYGOo4HfopoyBaNmoY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= @@ -509,8 +523,8 @@ github.com/aws/aws-sdk-go v1.38.35/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2z github.com/aws/aws-sdk-go v1.40.45/go.mod h1:585smgzpB/KqRA+K3y/NL/oYRqQvpNJYvLm+LY1U59Q= github.com/aws/aws-sdk-go v1.44.156/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aws/aws-sdk-go v1.44.187/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= -github.com/aws/aws-sdk-go v1.44.245 h1:KtY2s4q31/kn33AdV63R5t77mdxsI7rq3YT7Mgo805M= -github.com/aws/aws-sdk-go v1.44.245/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= +github.com/aws/aws-sdk-go v1.50.0 h1:HBtrLeO+QyDKnc3t1+5DR1RxodOHCGr8ZcrHudpv7jI= +github.com/aws/aws-sdk-go v1.50.0/go.mod h1:LF8svs817+Nz+DmiMQKTO3ubZ/6IaTpq3TjupRn3Eqk= github.com/aws/aws-sdk-go-v2 v1.9.1/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= github.com/aws/aws-sdk-go-v2 v1.11.0 h1:HxyD62DyNhCfiFGUHqJ/xITD6rAjJ7Dm/2nLxLmO4Ag= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.0.0 h1:yVUAwvJC/0WNPbyl0nA3j1L6CW1CN8wBubCRqtG7JLI= @@ -525,6 +539,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.9.0 h1:0BOlTqnNnrEO04o github.com/aws/aws-sdk-go-v2/service/s3 v1.19.0 h1:5mRAms4TjSTOGYsqKYte5kHr1PzpMJSyLThjF3J+hw0= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= github.com/aws/smithy-go v1.9.0 h1:c7FUdEqrQA1/UVKKCNDFQPNKGp4FQg3YW4Ck5SLTG58= +github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3 h1:6df1vn4bBlDDo4tARvBm7l6KA9iVMnE3NWizDeWSrps= +github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3/go.mod h1:CIWtjkly68+yqLPbvwwR/fjNJA/idrtULjZWh2v1ys0= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/immutable v0.3.0 h1:TVRhuZx2wG9SZ0LRdqlbs9S5BZ6Y24hJEHTCgWHZEIw= @@ -540,12 +556,12 @@ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kB github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40 h1:y4B3+GPxKlrigF1ha5FFErxK+sr6sWxQovRMzwMhejo= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= github.com/bonitoo-io/go-sql-bigquery v0.3.4-1.4.0 h1:MaVh0h9+KaMnJcoDvvIGp+O3fefdWm+8MBUX6ELTJTM= -github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/c-bata/go-prompt v0.2.2 h1:uyKRz6Z6DUyj49QVijyM339UJV9yhbr70gESwbNU3e0= github.com/c-bata/go-prompt v0.2.2/go.mod h1:VzqtzE2ksDBcdln8G7mk2RX9QyGjH+OVqOCSiVIqS34= github.com/casbin/casbin/v2 v2.37.0/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg= github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= @@ -577,8 +593,9 @@ github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20220314180256-7f1daf1720fc/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20230105202645-06c439db220b/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4 h1:/inchEIKaYC1Akx+H+gqO04wryn5h75LSazbRlnya1k= -github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20231109132714-523115ebc101 h1:7To3pQ+pZo0i3dsWEbinPNFs5gPSBOsJtx3wTT94VBY= +github.com/cncf/xds/go v0.0.0-20231109132714-523115ebc101/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/go-systemd/v22 v22.4.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= @@ -586,8 +603,9 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= 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= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/deepmap/oapi-codegen v1.6.0 h1:w/d1ntwh91XI0b/8ja7+u5SvA4IFfM0UNNLmiDR1gg0= github.com/denisenkom/go-mssqldb v0.10.0 h1:QykgLZBorFE95+gO3u9esLd0BmbvpWp0/waNNZfHBM8= github.com/dennwc/varint v1.0.0 h1:kGNFFSSw8ToIy3obO/kKr8U9GZYUAxQEVuix4zfDWzE= @@ -598,25 +616,26 @@ github.com/dgryski/go-bitstream v0.0.0-20180413035011-3522498ce2c8 h1:akOQj8IVgo github.com/dgryski/go-bitstream v0.0.0-20180413035011-3522498ce2c8/go.mod h1:VMaSuZ+SZcx/wljOQKvp5srsbCiKDEb6K2wC4+PiBmQ= github.com/dgryski/go-sip13 v0.0.0-20200911182023-62edffca9245/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/digitalocean/godo v1.95.0/go.mod h1:NRpFznZFvhHjBoqZAaOD3khVzsJ3EibzKqFL4R60dmA= -github.com/digitalocean/godo v1.98.0 h1:potyC1eD0N9n5/P4/WmJuKgg+OGYZOBWEW+/aKTX6QQ= -github.com/digitalocean/godo v1.98.0/go.mod h1:NRpFznZFvhHjBoqZAaOD3khVzsJ3EibzKqFL4R60dmA= +github.com/digitalocean/godo v1.108.0 h1:fWyMENvtxpCpva1UbKzOFnyAS04N1FNuBWWfPeTGquQ= +github.com/digitalocean/godo v1.108.0/go.mod h1:R6EmmWI8CT1+fCtjWY9UCB+L5uufuZH13wk3YhxycCs= github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TRo4= +github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0= +github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= -github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/docker v20.10.23+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/docker v24.0.7+incompatible h1:Wo6l37AuwP3JaMnZa226lzVXGA3F9Ig1seQen0cKYlM= -github.com/docker/docker v24.0.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v25.0.0+incompatible h1:g9b6wZTblhMgzOT2tspESstfw6ySZ9kdm94BLDKaZac= +github.com/docker/docker v25.0.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM= github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU= github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= @@ -630,8 +649,8 @@ github.com/edsrzf/mmap-go v1.1.0/go.mod h1:19H/e8pUPLicwkyNgOykDXkJ9F0MHE+Z52B8E github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= github.com/emicklei/go-restful/v3 v3.8.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/emicklei/go-restful/v3 v3.10.1 h1:rc42Y5YTp7Am7CS630D7JmhRjq4UlEUuEKfrDac4bSQ= -github.com/emicklei/go-restful/v3 v3.10.1/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= +github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -644,25 +663,27 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.m github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/go-control-plane v0.10.3/go.mod h1:fJJn/j26vwOu972OllsvAgJJM//w9BV6Fxbg2LuVd34= -github.com/envoyproxy/go-control-plane v0.11.1-0.20230524094728-9239064ad72f h1:7T++XKzy4xg7PKy+bM+Sa9/oe1OC88yz2hXQUISoXfA= -github.com/envoyproxy/go-control-plane v0.11.1-0.20230524094728-9239064ad72f/go.mod h1:sfYdkwUW4BA3PbKjySwjJy+O4Pu0h62rlqCMHNk+K+Q= +github.com/envoyproxy/go-control-plane v0.12.0 h1:4X+VP1GHd1Mhj6IB5mMeGbLCleqxjletLK6K0rbxyZI= +github.com/envoyproxy/go-control-plane v0.12.0/go.mod h1:ZBTaoJ23lqITozF0M6G4/IragXCQKCnYbmlmtHvwRG0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.6.7/go.mod h1:dyJXwwfPK2VSqiB9Klm1J6romD608Ba7Hij42vrOBCo= github.com/envoyproxy/protoc-gen-validate v0.9.1/go.mod h1:OKNgG7TCp5pF4d6XftA0++PMirau2/yoOwVac3AbF2w= -github.com/envoyproxy/protoc-gen-validate v0.10.1 h1:c0g45+xCJhdgFGw7a5QAfdS4byAbud7miNWJ1WwEVf8= -github.com/envoyproxy/protoc-gen-validate v0.10.1/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= -github.com/evanphx/json-patch v4.12.0+incompatible h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84= +github.com/envoyproxy/protoc-gen-validate v1.0.4 h1:gVPz/FMfvh57HdSJQyvBtF00j8JU4zdyUgIUNhlgg0A= +github.com/envoyproxy/protoc-gen-validate v1.0.4/go.mod h1:qys6tmnRsYrQqIhm2bvKZH4Blx/1gTIZ2UKVY1M+Yew= 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/facette/natsort v0.0.0-20181210072756-2cd4dd1e2dcb h1:IT4JYU7k4ikYg1SCxNI1/Tieq/NFvh6dzLdgi7eu0tM= +github.com/facette/natsort v0.0.0-20181210072756-2cd4dd1e2dcb/go.mod h1:bH6Xx7IW64qjjJq8M2u4dxNaBiDfKK+z/3eGDpXEQhc= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w= -github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg= -github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/flowstack/go-jsonschema v0.1.1/go.mod h1:yL7fNggx1o8rm9RlgXv7hTBWxdBM0rVwpMwimd3F3N0= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/form3tech-oss/jwt-go v3.2.5+incompatible h1:/l4kBbb4/vGSsdtB5nUe8L7B9mImVMaBPw9L/0TBHU8= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= @@ -673,8 +694,9 @@ github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUork 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.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= -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/gabriel-vasile/mimetype v1.4.0 h1:Cn9dkdYsMIu56tGho+fqzh7XmvY2YyGU0FnbhiOsEro= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE= @@ -704,8 +726,8 @@ github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTg github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= -github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/analysis v0.21.2/go.mod h1:HZwRk4RRisyG8vx2Oe6aqeSQcoxRp47Xkp3+K6q+LdY= @@ -714,12 +736,14 @@ github.com/go-openapi/analysis v0.21.4/go.mod h1:4zQ35W4neeZTqh3ol0rv/O8JBbka9Qy github.com/go-openapi/errors v0.19.8/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= github.com/go-openapi/errors v0.19.9/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= github.com/go-openapi/errors v0.20.2/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= -github.com/go-openapi/errors v0.20.3 h1:rz6kiC84sqNQoqrtulzaL/VERgkoCyB6WdEkc2ujzUc= github.com/go-openapi/errors v0.20.3/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= +github.com/go-openapi/errors v0.21.0 h1:FhChC/duCnfoLj1gZ0BgaBmzhJC2SL/sJr8a2vAobSY= +github.com/go-openapi/errors v0.21.0/go.mod h1:jxNTMUxRCKj65yb/okJGEtahVd7uvWnuWfj53bse4ho= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonpointer v0.20.0 h1:ESKJdU9ASRfaPNOPRx12IUyA1vn3R9GiE3KYD14BXdQ= +github.com/go-openapi/jsonpointer v0.20.0/go.mod h1:6PGzBjjIIumbLYysB73Klnms1mwnU4G3YHOECG3CedA= github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= @@ -732,20 +756,21 @@ github.com/go-openapi/runtime v0.25.0/go.mod h1:Ux6fikcHXyyob6LNWxtE96hWwjBPYF0D github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= github.com/go-openapi/spec v0.20.7/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= -github.com/go-openapi/spec v0.20.8 h1:ubHmXNY3FCIOinT8RNrrPfGc9t7I1qhPtdOGoG2AxRU= -github.com/go-openapi/spec v0.20.8/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= +github.com/go-openapi/spec v0.20.9 h1:xnlYNQAwKd2VQRRfwTEI0DcK+2cbuvI/0c7jx3gA8/8= +github.com/go-openapi/spec v0.20.9/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= github.com/go-openapi/strfmt v0.21.0/go.mod h1:ZRQ409bWMj+SOgXofQAGTIo2Ebu72Gs+WaRADcS5iNg= github.com/go-openapi/strfmt v0.21.1/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= github.com/go-openapi/strfmt v0.21.2/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= github.com/go-openapi/strfmt v0.21.3/go.mod h1:k+RzNO0Da+k3FrrynSNN8F7n/peCmQQqbbXjtDfvmGg= -github.com/go-openapi/strfmt v0.21.7 h1:rspiXgNWgeUzhjo1YU01do6qsahtJNByjLVbPLNHb8k= -github.com/go-openapi/strfmt v0.21.7/go.mod h1:adeGTkxE44sPyLk0JV235VQAO/ZXUr8KAzYjclFs3ew= +github.com/go-openapi/strfmt v0.22.0 h1:Ew9PnEYc246TwrEspvBdDHS4BVKXy/AOVsfqGDgAcaI= +github.com/go-openapi/strfmt v0.22.0/go.mod h1:HzJ9kokGIju3/K6ap8jL+OlGAbjpSv27135Yr9OivU4= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU= +github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-openapi/validate v0.21.0/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= github.com/go-openapi/validate v0.22.0/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= github.com/go-openapi/validate v0.22.1 h1:G+c2ub6q47kfX1sOBLwIQwzBVt8qmOAARyo/9Fqs9NU= @@ -755,8 +780,8 @@ github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTM github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= github.com/go-resty/resty/v2 v2.1.1-0.20191201195748-d7b97669fe48/go.mod h1:dZGr0i9PLlaaTD4H/hoZIDjQ+r6xq8mgbRzHZf7f2J8= -github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY= -github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I= +github.com/go-resty/resty/v2 v2.11.0 h1:i7jMfNOJYMp69lq7qozJP+bjgzfAzeOhuGlyDrqxT/8= +github.com/go-resty/resty/v2 v2.11.0/go.mod h1:iiP/OpA0CkcL3IGt1O0+/SIItFUbkkyw5BGXiVdTu+A= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= @@ -796,8 +821,8 @@ github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MG github.com/goccy/go-yaml v1.9.5/go.mod h1:U/jl18uSupI5rdI2jmuCswEA2htH9eXfferR3KfscvA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gofrs/uuid v4.3.1+incompatible h1:0/KbAdpx3UXAx1kEOWHJeOkpbgRFGHVgv+CFIY7dBJI= github.com/gofrs/uuid v4.3.1+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= @@ -806,6 +831,8 @@ github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzw github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw= +github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/geo v0.0.0-20190916061304-5b978397cfec h1:lJwO/92dFXWeXOZdoGXgptLmNLwynMSHUmU6besqtiw= @@ -857,8 +884,8 @@ github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9 github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= github.com/google/flatbuffers v22.9.30-0.20221019131441-5792623df42e+incompatible h1:Bqgl5d9t2UlT8pv9Oc/lkkI8yYk0jCwHkZKkHzbxEsc= github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= -github.com/google/gnostic v0.6.9 h1:ZK/5VhkoX835RikCHpSUJV9a+S3e1zLh59YnyWeBW+0= -github.com/google/gnostic v0.6.9/go.mod h1:Nm8234We1lq6iB9OmlgNv3nH91XLLVZHCDayfA3xq+E= +github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= +github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -873,8 +900,9 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -902,22 +930,23 @@ github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20230111200839-76d1ae5aea2b/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= -github.com/google/pprof v0.0.0-20230406165453-00490a63f317 h1:hFhpt7CTmR3DX+b4R19ydQFtofxT0Sv3QsKNMVQYTMQ= -github.com/google/pprof v0.0.0-20230406165453-00490a63f317/go.mod h1:79YE0hCXdHag9sBkw2o+N/YnZtTkXi0UT9Nnixa5eYk= +github.com/google/pprof v0.0.0-20240117000934-35fc243c5815 h1:WzfWbQz/Ze8v6l++GGbGNFZnUShVpP/0xffCPLL+ax8= +github.com/google/pprof v0.0.0-20240117000934-35fc243c5815/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= -github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= +github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= +github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= 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.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= +github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.0.0-20220520183353-fd19c99a87aa/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= github.com/googleapis/enterprise-certificate-proxy v0.1.0/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= github.com/googleapis/enterprise-certificate-proxy v0.2.0/go.mod h1:8C0jb7/mgJe/9KK8Lm7X9ctZC2t60YyIpYEI16jx0Qg= github.com/googleapis/enterprise-certificate-proxy v0.2.1/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= -github.com/googleapis/enterprise-certificate-proxy v0.2.3 h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k= -github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= +github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= +github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= 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/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= @@ -928,13 +957,13 @@ github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK github.com/googleapis/gax-go/v2 v2.5.1/go.mod h1:h6B0KMMFNtI2ddbGJn3T3ZbwkeT6yqEF02fYlzkUCyo= github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= github.com/googleapis/gax-go/v2 v2.7.0/go.mod h1:TEop28CZZQ2y+c0VxMUmu1lV+fQx57QpBWsYpwqHJx8= -github.com/googleapis/gax-go/v2 v2.11.0 h1:9V9PWXEsWnPpQhu/PeQIkS4eGzMlTLGgt80cUUI8Ki4= -github.com/googleapis/gax-go/v2 v2.11.0/go.mod h1:DxmR61SGKkGLa2xigwuZIQpkCI2S5iydzRfb3peWZJI= +github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= +github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gophercloud/gophercloud v1.1.1/go.mod h1:aAVqcocTSXh2vYFZ1JTvx4EQmfgzxRcNupUfxZbBNDM= -github.com/gophercloud/gophercloud v1.3.0 h1:RUKyCMiZoQR3VlVR5E3K7PK1AC3/qppsWYo6dtBiqs8= -github.com/gophercloud/gophercloud v1.3.0/go.mod h1:aAVqcocTSXh2vYFZ1JTvx4EQmfgzxRcNupUfxZbBNDM= +github.com/gophercloud/gophercloud v1.8.0 h1:TM3Jawprb2NrdOnvcHhWJalmKmAmOGgfZElM/3oBYCk= +github.com/gophercloud/gophercloud v1.8.0/go.mod h1:aAVqcocTSXh2vYFZ1JTvx4EQmfgzxRcNupUfxZbBNDM= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= @@ -948,20 +977,23 @@ github.com/grafana/regexp v0.0.0-20221122212121-6b5c0a4cb7fd h1:PpuIBO5P3e9hpqBD github.com/grafana/regexp v0.0.0-20221122212121-6b5c0a4cb7fd/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks= github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.1/go.mod h1:G+WkljZi4mflcqVxYSgvt8MNctRQHjEH8ubKtt1Ka3w= github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.3/go.mod h1:o//XUCC/F+yRGJoPO/VU0GSB0f8Nhgmxx0VIRUvaC0w= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 h1:YBftPWNWd4WwGqtY2yeZL2ef8rHAxPBD8KFhJpmcqms= github.com/hashicorp/consul/api v1.10.1/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M= github.com/hashicorp/consul/api v1.12.0/go.mod h1:6pVBMo0ebnYdt2S3H87XhekM/HHrUoTD2XXb/VrZVy0= github.com/hashicorp/consul/api v1.18.0/go.mod h1:owRRGJ9M5xReDC5nfT8FTJrNAPbT4NM6p/k+d03q2v4= -github.com/hashicorp/consul/api v1.20.0 h1:9IHTjNVSZ7MIwjlW3N3a7iGiykCMDpxZu8jsxFJh0yc= -github.com/hashicorp/consul/api v1.20.0/go.mod h1:nR64eD44KQ59Of/ECwt2vUmIK2DKsDzAwTmwmLl8Wpo= +github.com/hashicorp/consul/api v1.27.0 h1:gmJ6DPKQog1426xsdmgk5iqDyoRiNc+ipBdJOqKQFjc= +github.com/hashicorp/consul/api v1.27.0/go.mod h1:JkekNRSou9lANFdt+4IKx3Za7XY0JzzpQjEb4Ivo1c8= github.com/hashicorp/consul/sdk v0.8.0/go.mod h1:GBvyrGALthsZObzUGsfgHZQDXjg4lOjagTIwIR1vPms= github.com/hashicorp/consul/sdk v0.13.0/go.mod h1:0hs/l5fOVhJy/VdcoaNqUSi2AUs95eF5WKtv+EYIQqE= -github.com/hashicorp/consul/sdk v0.13.1 h1:EygWVWWMczTzXGpO93awkHFzfUka6hLYJ0qhETd+6lY= -github.com/hashicorp/cronexpr v1.1.1 h1:NJZDd87hGXjoZBdvyCF9mX4DCq5Wy7+A/w+A7q0wn6c= +github.com/hashicorp/consul/sdk v0.15.1 h1:kKIGxc7CZtflcF5DLfHeq7rOQmRq3vk7kwISN9bif8Q= github.com/hashicorp/cronexpr v1.1.1/go.mod h1:P4wA0KBl9C5q2hABiMO7cp6jcIg96CDh1Efb3g1PWA4= +github.com/hashicorp/cronexpr v1.1.2 h1:wG/ZYIKT+RT3QkOdgYc+xsKWVRgnxJ1OJtjjy84fJ9A= +github.com/hashicorp/cronexpr v1.1.2/go.mod h1:P4wA0KBl9C5q2hABiMO7cp6jcIg96CDh1Efb3g1PWA4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -973,21 +1005,21 @@ github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrj github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v0.16.2/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-hclog v1.4.0 h1:ctuWFGrhFha8BnnzxqeRGidlEcQkDyL5u8J8t5eA11I= -github.com/hashicorp/go-hclog v1.4.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c= +github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqkZzoD4= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-retryablehttp v0.7.1/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= -github.com/hashicorp/go-retryablehttp v0.7.2 h1:AcYqCvkpalPnPF2pn0KamgwamS42TqUDDYFRKq/RAd0= -github.com/hashicorp/go-retryablehttp v0.7.2/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8= +github.com/hashicorp/go-retryablehttp v0.7.4 h1:ZQgVdpTdAL7WpMIwLzCfbalOcSUdkDZnpUv3/+BxzFA= +github.com/hashicorp/go-retryablehttp v0.7.4/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8= github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= @@ -996,10 +1028,11 @@ github.com/hashicorp/go-sockaddr v1.0.2/go.mod h1:rB4wwRAUzs07qva3c5SdrY/NEtAUjG github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.2 h1:cfejS+Tpcp13yd5nYHWDI6qVCny6wyX2Mt5SGur2IGE= github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-version v1.2.1 h1:zEfKbn2+PDgroKdiOzqiE8rsmLqU2uwi5PB5pBJ3TkI= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= +github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= @@ -1014,16 +1047,16 @@ github.com/hashicorp/memberlist v0.3.0/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOn github.com/hashicorp/memberlist v0.5.0 h1:EtYPN8DpAURiapus508I4n9CzHs2W+8NZGbmmR/prTM= github.com/hashicorp/memberlist v0.5.0/go.mod h1:yvyXLpo0QaGE59Y7hDTsTzDD25JYBZ4mHgHUZ8lrOI0= github.com/hashicorp/nomad/api v0.0.0-20230124213148-69fd1a0e4bf7/go.mod h1:xYYd4dybIhRhhzDemKx7Ddt8CvCosgrEek8YM7/cF0A= -github.com/hashicorp/nomad/api v0.0.0-20230418003350-3067191c5197 h1:I5xhKLePXpXgM6pZ4xZNTiurLLS3sGuZrZFFzAbM67A= -github.com/hashicorp/nomad/api v0.0.0-20230418003350-3067191c5197/go.mod h1:2TCrNvonL09r7EiQ6M2rNt+Cmjbn1QbzchFoTWJFpj4= +github.com/hashicorp/nomad/api v0.0.0-20230721134942-515895c7690c h1:Nc3Mt2BAnq0/VoLEntF/nipX+K1S7pG+RgwiitSv6v0= +github.com/hashicorp/nomad/api v0.0.0-20230721134942-515895c7690c/go.mod h1:O23qLAZuCx4htdY9zBaO4cJPXgleSFEdq6D/sezGgYE= github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= github.com/hashicorp/serf v0.9.6/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY= github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4= github.com/hetznercloud/hcloud-go v1.39.0/go.mod h1:mepQwR6va27S3UQthaEPGS86jtzSY9xWL1e9dyxXpgA= -github.com/hetznercloud/hcloud-go v1.42.0 h1:Es/CDOForQN3nOOP5Vxh1N/YHjpCg386iYEX5zCgi+A= -github.com/hetznercloud/hcloud-go v1.42.0/go.mod h1:YADL8AbmQYH0Eo+1lkuyoc8LutT0UeMvaKP47nNUb+Y= +github.com/hetznercloud/hcloud-go/v2 v2.6.0 h1:RJOA2hHZ7rD1pScA4O1NF6qhkHyUdbbxjHgFNot8928= +github.com/hetznercloud/hcloud-go/v2 v2.6.0/go.mod h1:4J1cSE57+g0WS93IiHLV7ubTHItcp+awzeBp5bM9mfA= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= @@ -1034,8 +1067,8 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1: github.com/ianlancetaylor/demangle v0.0.0-20220319035150-800ac71e25c2/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= -github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= +github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= +github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/flux v0.65.1/go.mod h1:J754/zds0vvpfwuq7Gc2wRdVwEodfpCFM7mYlOw2LqY= github.com/influxdata/flux v0.194.1 h1:px4QX33389KC4GGgkB4QjQHzBMEtGr3WBYYBmUq5fjM= @@ -1060,8 +1093,8 @@ github.com/influxdata/tdigest v0.0.2-0.20210216194612-fc98d27c9e8b h1:i44CesU68Z github.com/influxdata/usage-client v0.0.0-20160829180054-6d3895376368 h1:+TUUmaFa4YD1Q+7bH9o5NCHQGPMqZCYJiNW6lIIS9z4= github.com/influxdata/usage-client v0.0.0-20160829180054-6d3895376368/go.mod h1:Wbbw6tYNvwa5dlB6304Sd+82Z3f7PmVZHVKU637d4po= github.com/ionos-cloud/sdk-go/v6 v6.1.3/go.mod h1:Ox3W0iiEz0GHnfY9e5LmAxwklsxguuNFEUSu0gVRTME= -github.com/ionos-cloud/sdk-go/v6 v6.1.6 h1:0n4irdqNska+1s3YMCRhrAqKbibEgQ7SwwhAlHzYT5A= -github.com/ionos-cloud/sdk-go/v6 v6.1.6/go.mod h1:EzEgRIDxBELvfoa/uBN0kOQaqovLjUWEB7iW4/Q+t4k= +github.com/ionos-cloud/sdk-go/v6 v6.1.11 h1:J/uRN4UWO3wCyGOeDdMKv8LWRzKu6UIkLEaes38Kzh8= +github.com/ionos-cloud/sdk-go/v6 v6.1.11/go.mod h1:EzEgRIDxBELvfoa/uBN0kOQaqovLjUWEB7iW4/Q+t4k= github.com/jarcoal/httpmock v1.3.0 h1:2RJ8GP0IIaWwcC9Fp2BmVi8Kog3v2Hn7VXM3fTd+nuc= github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -1100,8 +1133,8 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o github.com/klauspost/asmfmt v1.3.2 h1:4Ri7ox3EwapiOjCki+hw14RyKk201CN4rzyCJRFLpK4= github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY= -github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= +github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= +github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/crc32 v0.0.0-20161016154125-cb6bfca970f6/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg= github.com/klauspost/pgzip v1.0.2-0.20170402124221-0bf5dcad4ada/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= @@ -1122,13 +1155,14 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/linode/linodego v1.12.0/go.mod h1:NJlzvlNtdMRRkXb0oN6UWzUkj6t+IBsyveHgZ5Ppjyk= -github.com/linode/linodego v1.16.1 h1:5otq57M4PdHycPERRfSFZ0s1yz1ETVWGjCp3hh7+F9w= -github.com/linode/linodego v1.16.1/go.mod h1:aESRAbpLY9R6IA1WGAWHikRI9DU9Lhesapv1MhKmPHM= +github.com/linode/linodego v1.27.1 h1:KoQm5g2fppw8qIClJqUEL0yKH0+f+7te3Mewagb5QKE= +github.com/linode/linodego v1.27.1/go.mod h1:5oAsx+uinHtVo6U77nXXXtox7MWzUW6aEkTOKXxA9uo= github.com/lyft/protoc-gen-star v0.6.0/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= github.com/lyft/protoc-gen-star v0.6.1/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= @@ -1156,8 +1190,9 @@ github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOA github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.3 h1:a+kO+98RDGEfo6asOGMmpodZq4FNtnGP54yps8BzLR4= github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= @@ -1167,16 +1202,14 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5 github.com/matttproud/golang_protobuf_extensions v1.0.2/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg= -github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k= github.com/maxatome/go-testdeep v1.12.0 h1:Ql7Go8Tg0C1D/uMMX59LAoYK7LffeJQ6X2T04nTH68g= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4= github.com/miekg/dns v1.1.50/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME= -github.com/miekg/dns v1.1.53 h1:ZBkuHr5dxHtB1caEOlZTLPo7D3L3TWckgUUs/RHfDxw= -github.com/miekg/dns v1.1.53/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY= +github.com/miekg/dns v1.1.58 h1:ca2Hdkz+cDg/7eNF6V56jjzuZ4aCAE+DbVkILdQWG/4= +github.com/miekg/dns v1.1.58/go.mod h1:Ypv+3b/KadlvW9vJfXOTf300O4UqaHFzFCuHz+rPkBY= github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 h1:AMFGa4R4MiIpspGNG7Z948v4n35fFGB3RR3G/ry4FWs= github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 h1:+n/aFZefKZp7spd8DFdX7uMikMLXX4oubIzJF4kv/wI= github.com/minio/highwayhash v1.0.1/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= @@ -1277,8 +1310,8 @@ github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+ github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/openzipkin/zipkin-go v0.2.5/go.mod h1:KpXfKdgRDnnhsxw4pNIH9Md5lyFqKUa4YDFlwRYAMyE= github.com/ovh/go-ovh v1.3.0/go.mod h1:AxitLZ5HBRPyUd+Zl60Ajaag+rNTdVXWIkzfrVuTXWA= -github.com/ovh/go-ovh v1.4.1 h1:VBGa5wMyQtTP7Zb+w97zRCh9sLtM/2YKRyy+MEJmWaM= -github.com/ovh/go-ovh v1.4.1/go.mod h1:6bL6pPyUT7tBfI0pqOegJgRjgjuO+mOo+MyXd1EEC0M= +github.com/ovh/go-ovh v1.4.3 h1:Gs3V823zwTFpzgGLZNI6ILS4rmxZgJwJCz54Er9LwD0= +github.com/ovh/go-ovh v1.4.3/go.mod h1:AkPXVtgwB6xlKblMjRKJJmjRp+ogrE7fz2lVgcQY8SY= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= @@ -1295,7 +1328,8 @@ github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0 github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0= github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= -github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -1306,14 +1340,15 @@ github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZ github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= github.com/pkg/term v0.0.0-20180730021639-bffc007b7fd5 h1:tFwafIEMf0B7NlcxV/zJ6leBIa81D3hgGSgsE5hCkOQ= github.com/pkg/term v0.0.0-20180730021639-bffc007b7fd5/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= github.com/prometheus/alertmanager v0.25.0/go.mod h1:MEZ3rFVHqKZsw7IcNS/m4AWZeXThmJhumpiWR4eHU/w= -github.com/prometheus/alertmanager v0.25.1 h1:LGBNMspOfv8h7brb+LWj2wnwBCg2ZuuKWTh6CAVw2/Y= -github.com/prometheus/alertmanager v0.25.1/go.mod h1:MEZ3rFVHqKZsw7IcNS/m4AWZeXThmJhumpiWR4eHU/w= +github.com/prometheus/alertmanager v0.26.0 h1:uOMJWfIwJguc3NaM3appWNbbrh6G/OjvaHMk22aBBYc= +github.com/prometheus/alertmanager v0.26.0/go.mod h1:rVcnARltVjavgVaNnmevxK7kOn7IZavyf0KNgHkbEpU= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= @@ -1324,15 +1359,15 @@ github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrb github.com/prometheus/client_golang v1.13.0/go.mod h1:vTeo+zgvILHsnnj/39Ou/1fPN5nJFOEMgftOUOmlvYQ= github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= -github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q= -github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY= +github.com/prometheus/client_golang v1.18.0 h1:HzFfmkOzH5Q8L8G+kSJKUx5dtG87sewO+FoDDqP5Tbk= +github.com/prometheus/client_golang v1.18.0/go.mod h1:T+GXkCk5wSJyOqMIzVgvvjFDlkOQntgjkJWKrN5txjA= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= -github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 h1:v7DLqVdK4VrYkVD5diGdl4sxJurKJEMnODWRJlxV9oM= -github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16/go.mod h1:oMQmHW1/JoDwqLtg57MGgP/Fb1CJEYF2imWWhWtMkYU= +github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= +github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= @@ -1345,8 +1380,8 @@ github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJ github.com/prometheus/common v0.38.0/go.mod h1:MBXfmBQZrK5XpbCkjofnXs96LD2QQ7fEq4C0xjC/yec= github.com/prometheus/common v0.39.0/go.mod h1:6XBZ7lYdLCbkAVhwRsWTZn+IN5AB9F/NXd5w0BbEX0Y= github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= -github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lneoxM= -github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY= +github.com/prometheus/common v0.46.0 h1:doXzt5ybi1HBKpsZOL0sSkaNHJJqkyfEWZGGqqScV0Y= +github.com/prometheus/common v0.46.0/go.mod h1:Tp0qkxpb9Jsg54QMe+EAmqXkSV7Evdy1BTn+g2pa/hQ= github.com/prometheus/common/assets v0.2.0/go.mod h1:D17UVUE12bHbim7HzwUvtqm6gwBEaDQ0F+hIGbFbccI= github.com/prometheus/common/sigv4 v0.1.0 h1:qoVebwtwwEhS85Czm2dSROY5fTo2PAPEVdDeppTwGX4= github.com/prometheus/common/sigv4 v0.1.0/go.mod h1:2Jkxxk9yYvCkE5G1sQT7GuEXm57JrvHu9k5YwTjsNtI= @@ -1359,11 +1394,11 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1 github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4= github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY= -github.com/prometheus/procfs v0.11.1 h1:xRC8Iq1yyca5ypa9n1EZnWZkt7dwcoRPQwX/5gwaUuI= -github.com/prometheus/procfs v0.11.1/go.mod h1:eesXgaPo1q7lBpVMoMy0ZOFTth9hBn4W/y0/p/ScXhY= +github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= +github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= github.com/prometheus/prometheus v0.42.0/go.mod h1:Pfqb/MLnnR2KK+0vchiaH39jXxvLMBk+3lnIGP4N7Vk= -github.com/prometheus/prometheus v0.44.0 h1:sgn8Fdx+uE5tHQn0/622swlk2XnIj6udoZCnbVjHIgc= -github.com/prometheus/prometheus v0.44.0/go.mod h1:aPsmIK3py5XammeTguyqTmuqzX/jeCdyOWWobLHNKQg= +github.com/prometheus/prometheus v0.50.1 h1:N2L+DYrxqPh4WZStU+o1p/gQlBaqFbcLBTjlp3vpdXw= +github.com/prometheus/prometheus v0.50.1/go.mod h1:FvE8dtQ1Ww63IlyKBn1V4s+zMwF9kHkVNkQBR1pM4CU= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/retailnext/hllpp v1.0.1-0.20180308014038-101a6d2f8b52/go.mod h1:RDpi1RftBQPUCDRw6SmxeaREsAaRKnOclghuzp/WRzc= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= @@ -1372,14 +1407,14 @@ github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sagikazarmark/crypt v0.6.0/go.mod h1:U8+INwJo3nBv1m6A/8OBXAq7Jnpspk5AxSgDyEQcea8= github.com/scaleway/scaleway-sdk-go v1.0.0-beta.12/go.mod h1:fCa7OJZ/9DRTnOKmxvT6pn+LPWUptQAmHF/SBJUGEcg= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.15 h1:Y7xOFbD+3jaPw+VN7lkakNJ/pa+ZSQVFp1ONtJaBxns= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.15/go.mod h1:fCa7OJZ/9DRTnOKmxvT6pn+LPWUptQAmHF/SBJUGEcg= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.22 h1:wJrcTdddKOI8TFxs8cemnhKP2EmKy3yfUKHj3ZdfzYo= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.22/go.mod h1:fCa7OJZ/9DRTnOKmxvT6pn+LPWUptQAmHF/SBJUGEcg= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= @@ -1389,7 +1424,7 @@ github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAm github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shoenig/test v0.6.0/go.mod h1:xYtyGBC5Q3kzCNyJg/SjgNpfAa2kvmgA0i5+lQso8x0= -github.com/shoenig/test v0.6.3 h1:GVXWJFk9PiOjN0KoJ7VrJGH6uLPnqxR7/fe3HUPfE0c= +github.com/shoenig/test v0.6.6 h1:Oe8TPH9wAbv++YPNDKJWUnI8Q4PPWCx3UbOfH+FxiMU= github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= @@ -1398,8 +1433,8 @@ github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMB github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= @@ -1445,7 +1480,6 @@ github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= -github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tinylib/msgp v1.0.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= github.com/tinylib/msgp v1.1.2 h1:gWmO7n0Ys2RBEb7GPYB9Ujq8Mk5p2U08lRnmMcGy6BQ= @@ -1464,11 +1498,10 @@ github.com/willf/bitset v1.1.10/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPy github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/xhit/go-str2duration v1.2.0/go.mod h1:3cPSlfZlUHVlneIVfePFWcJZsuwf+P1v2SRTV4cUmp4= github.com/xlab/treeprint v1.1.0 h1:G/1DjNkPpfZCFt9CSh6b5/nY4VimlbHF3Rh4obvtzDk= github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= @@ -1494,8 +1527,8 @@ go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4x go.mongodb.org/mongo-driver v1.8.3/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY= go.mongodb.org/mongo-driver v1.10.0/go.mod h1:wsihk0Kdgv8Kqu1Anit4sfK+22vSFbUrAVEYRhCXrA8= go.mongodb.org/mongo-driver v1.11.0/go.mod h1:s7p5vEtfbeR1gYi6pnj3c3/urpbLv2T5Sfd6Rp2HBB8= -go.mongodb.org/mongo-driver v1.11.3 h1:Ql6K6qYHEzB6xvu4+AU0BoRoqf9vFPcc4o7MUIdPW8Y= -go.mongodb.org/mongo-driver v1.11.3/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g= +go.mongodb.org/mongo-driver v1.13.1 h1:YIc7HTYsKndGK4RFzJ3covLz1byri52x0IoMB0Pt/vk= +go.mongodb.org/mongo-driver v1.13.1/go.mod h1:wcDf1JBCXy2mOW0bWHwO/IOYqdca1MPCwDtFu/Z9+eo= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -1505,29 +1538,40 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/collector/featuregate v1.0.1 h1:ok//hLSXttBbyu4sSV1pTx1nKdr5udSmrWy5sFMIIbM= +go.opentelemetry.io/collector/featuregate v1.0.1/go.mod h1:QQXjP4etmJQhkQ20j4P/rapWuItYxoFozg/iIwuKnYg= +go.opentelemetry.io/collector/pdata v1.0.1 h1:dGX2h7maA6zHbl5D3AsMnF1c3Nn+3EUftbVCLzeyNvA= +go.opentelemetry.io/collector/pdata v1.0.1/go.mod h1:jutXeu0QOXYY8wcZ/hege+YAnSBP3+jpTqYU1+JTI5Y= +go.opentelemetry.io/collector/semconv v0.93.0 h1:eBlMcVNTwYYsVdAsCVDs4wvVYs75K1xcIDpqj16PG4c= +go.opentelemetry.io/collector/semconv v0.93.0/go.mod h1:gZ0uzkXsN+J5NpiRcdp9xOhNGQDDui8Y62p15sKrlzo= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.46.1 h1:SpGay3w+nEwMpfVnbqOLH5gY52/foP8RE8UzTZ1pdSE= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.37.0/go.mod h1:+ARmXlUlc51J7sZeCBkBJNdHGySrdOzgzxp6VWRWM1U= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.44.0 h1:KfYpVmrjI7JuToy5k8XV3nkapjWx48k4E4JOtVstzQI= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.44.0/go.mod h1:SeQhzAEccGVZVEy7aH87Nh0km+utSpo1pTv6eMMop48= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.47.0 h1:sv9kVfal0MK0wBMCOGr+HeJm9v803BkJxGrk2au7j08= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.47.0/go.mod h1:SK2UL73Zy1quvRPonmOmRDiWk1KBV3LyIeeIxcEApWw= go.opentelemetry.io/otel v1.11.1/go.mod h1:1nNhXBbWSD0nsL38H6btgnFN2k4i0sNLHNNMZMSbUGE= go.opentelemetry.io/otel v1.11.2/go.mod h1:7p4EUV+AqgdlNV9gL97IgUZiVR3yrFXYo53f9BM3tRI= -go.opentelemetry.io/otel v1.18.0 h1:TgVozPGZ01nHyDZxK5WGPFB9QexeTMXEH7+tIClWfzs= -go.opentelemetry.io/otel v1.18.0/go.mod h1:9lWqYO0Db579XzVuCKFNPDl4s73Voa+zEck3wHaAYQI= +go.opentelemetry.io/otel v1.22.0 h1:xS7Ku+7yTFvDfDraDIJVpw7XPyuHlB9MCiqqX5mcJ6Y= +go.opentelemetry.io/otel v1.22.0/go.mod h1:eoV4iAi3Ea8LkAEI9+GFT44O6T/D0GWAVFyZVCC6pMI= go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.2/go.mod h1:rqbht/LlhVBgn5+k3M5QK96K5Xb0DvXpMJ5SFQpY6uw= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.2/go.mod h1:5Qn6qvgkMsLDX+sYK64rHb1FPhpn0UtxF+ouX1uhyJE= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.22.0 h1:9M3+rhx7kZCIQQhQRYaZCdNu1V73tm4TvXs2ntl98C4= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.2/go.mod h1:jWZUM2MWhWCJ9J9xVbRx7tzK1mXKpAlze4CeulycwVY= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.11.2/go.mod h1:GZWSQQky8AgdJj50r1KJm8oiQiIPaAX7uZCFQX9GzC8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.22.0 h1:FyjCyI9jVEfqhUh2MoSkmolPjfh5fp2hnV0b0irxH4Q= go.opentelemetry.io/otel/metric v0.34.0/go.mod h1:ZFuI4yQGNCupurTXCwkeD/zHBt+C2bR7bw5JqUm/AP8= -go.opentelemetry.io/otel/metric v1.18.0 h1:JwVzw94UYmbx3ej++CwLUQZxEODDj/pOuTCvzhtRrSQ= -go.opentelemetry.io/otel/metric v1.18.0/go.mod h1:nNSpsVDjWGfb7chbRLUNW+PBNdcSTHD4Uu5pfFMOI0k= +go.opentelemetry.io/otel/metric v1.22.0 h1:lypMQnGyJYeuYPhOM/bgjbFM6WE44W1/T45er4d8Hhg= +go.opentelemetry.io/otel/metric v1.22.0/go.mod h1:evJGjVpZv0mQ5QBRJoBF64yMuOf4xCWdXjK8pzFvliY= go.opentelemetry.io/otel/sdk v1.11.1/go.mod h1:/l3FE4SupHJ12TduVjUkZtlfFqDCQJlOlithYrdktys= go.opentelemetry.io/otel/sdk v1.11.2/go.mod h1:wZ1WxImwpq+lVRo4vsmSOxdd+xwoUJ6rqyLc3SyX9aU= +go.opentelemetry.io/otel/sdk v1.22.0 h1:6coWHw9xw7EfClIC/+O31R8IY3/+EiRFHevmHafB2Gw= go.opentelemetry.io/otel/trace v1.11.1/go.mod h1:f/Q9G7vzk5u91PhbmKbg1Qn0rzH1LJ4vbPHFGkTPtOk= go.opentelemetry.io/otel/trace v1.11.2/go.mod h1:4N+yC7QEz7TTsG9BSRLNAa63eg5E06ObSbKPmxQ/pKA= -go.opentelemetry.io/otel/trace v1.18.0 h1:NY+czwbHbmndxojTEKiSMHkG2ClNH2PwmcHrdo0JY10= -go.opentelemetry.io/otel/trace v1.18.0/go.mod h1:T2+SGJGuYZY3bjj5rgh/hN7KIrlpWC5nS8Mjvzckz+0= +go.opentelemetry.io/otel/trace v1.22.0 h1:Hg6pPujv0XG9QaVbGOBVHunyuLcCC3jN7WEhPx83XD0= +go.opentelemetry.io/otel/trace v1.22.0/go.mod h1:RbbHXVqKES9QhzZq/fE5UnOSILqRt40a21sPw2He1xo= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.opentelemetry.io/proto/otlp v0.15.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= +go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lIVU/I= go.step.sm/crypto v0.16.2 h1:Pr9aazTwWBBZNogUsOqhOrPSdwAa9pPs+lMB602lnDA= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= @@ -1540,14 +1584,14 @@ go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0 go.uber.org/automaxprocs v1.5.1/go.mod h1:BF4eumQw0P9GtnuxxovUd06vwm1o18oMzFtK66vU6XU= go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= -go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= -go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.4.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= -go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= -go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= @@ -1574,7 +1618,6 @@ golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20210915214749-c084706c2272/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= @@ -1583,8 +1626,9 @@ golang.org/x/crypto v0.0.0-20221012134737-56aed061732a/go.mod h1:IxCIyHEi3zRg3s0 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.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= -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.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= +golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -1600,8 +1644,8 @@ golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EH golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20230108222341-4b8118a2686a/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/exp v0.0.0-20230124195608-d38c7dcee874/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= -golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug= -golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= +golang.org/x/exp v0.0.0-20240119083558-1b970713d09a h1:Q8/wZp0KX97QFTc2ywcOE0YRjZPVIx+MXInMzdvQqcA= +golang.org/x/exp v0.0.0-20240119083558-1b970713d09a/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -1635,8 +1679,8 @@ golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI= 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.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.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= +golang.org/x/mod v0.14.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= @@ -1686,11 +1730,9 @@ golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= @@ -1718,8 +1760,10 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1750,8 +1794,8 @@ golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri golang.org/x/oauth2 v0.3.0/go.mod h1:rQrIauxkUhJ6CuwEXwymO2/eh4xz2ZWF1nBkcxS+tGk= golang.org/x/oauth2 v0.4.0/go.mod h1:RznEsdpjGAINPTOF0UH/t+xJ75L18YO3Ho6Pyn+uRec= golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= -golang.org/x/oauth2 v0.12.0 h1:smVPGxink+n1ZI5pkQa8y6fZT0RW0MgCO5bFpepy4B4= -golang.org/x/oauth2 v0.12.0/go.mod h1:A74bZ3aGXgCY0qaIC9Ahg6Lglin4AMAco8cIv9baba4= +golang.org/x/oauth2 v0.16.0 h1:aDkGMBSYxElaoP81NpoUoz2oo2R2wHdZpGToUxfyQrQ= +golang.org/x/oauth2 v0.16.0/go.mod h1:hqZ+0LWXsiVoZpeld6jVt06P3adbS2Uu911W1SsJv2o= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1769,8 +1813,8 @@ golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 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= @@ -1884,8 +1928,10 @@ golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -1896,8 +1942,10 @@ golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= 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.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.16.0 h1:m+B6fahuftsE9qjo0VWp2FW0mB3MTJvR0BaMQrq0pmE= +golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 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= @@ -1914,8 +1962,9 @@ 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= @@ -1924,8 +1973,9 @@ golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20220922220347-f3bd1da661af/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.1.0/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.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 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= @@ -2004,8 +2054,8 @@ golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= golang.org/x/tools v0.5.0/go.mod h1:N+Kgy78s5I24c24dU8OfWNEotWjutIs8SnJvn5IDq+k= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 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.17.0 h1:FvmRgNOcs3kOa+T20R1uhfP9F6HgG2mfxDv1vrx1Htc= +golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps= 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= @@ -2076,16 +2126,17 @@ google.golang.org/api v0.100.0/go.mod h1:ZE3Z2+ZOr87Rx7dqFsdRQkRBk36kDtp/h+QpHbB google.golang.org/api v0.102.0/go.mod h1:3VFl6/fzoA+qNuS1N1/VfXY4LjoXN/wzeIp7TweWwGo= google.golang.org/api v0.103.0/go.mod h1:hGtW6nK1AC+d9si/UBhw8Xli+QMOf6xyNAyJw4qU9w0= google.golang.org/api v0.108.0/go.mod h1:2Ts0XTHNVWxypznxWOYUeI4g3WdP9Pk2Qk58+a/O9MY= -google.golang.org/api v0.126.0 h1:q4GJq+cAdMAC7XP7njvQ4tvohGLiSlytuL4BQxbIZ+o= -google.golang.org/api v0.126.0/go.mod h1:mBwVAtz+87bEN6CbA1GtZPDOqY2R5ONPqJeIlvyo4Aw= +google.golang.org/api v0.157.0 h1:ORAeqmbrrozeyw5NjnMxh7peHO0UzV4wWYSwZeCUb20= +google.golang.org/api v0.157.0/go.mod h1:+z4v4ufbZ1WEpld6yMGHyggs+PmAHiaLNj5ytP3N01g= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -2155,7 +2206,6 @@ google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ6 google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211221195035-429b39de9b1c/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20220107163113-42d7afdf6368/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20220126215142-9970aeb2e350/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20220207164111-0872dc986b00/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20220218161850-94dd64e39d7c/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= @@ -2209,12 +2259,12 @@ google.golang.org/genproto v0.0.0-20221202195650-67e5cbc046fd/go.mod h1:cTsE614G google.golang.org/genproto v0.0.0-20221227171554-f9683d7f8bef/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= google.golang.org/genproto v0.0.0-20230124163310-31e0e69b6fc2/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= -google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc h1:8DyZCyvI8mE1IdLy/60bS+52xfymkE72wv1asokgtao= -google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:xZnkP7mREFX5MORlOPEzLMr+90PPZQ2QWzrVTWfAq64= -google.golang.org/genproto/googleapis/api v0.0.0-20230530153820-e85fd2cbaebc h1:kVKPf/IiYSBWEWtkIn6wZXwWGCnLKcC8oWfZvXjsGnM= -google.golang.org/genproto/googleapis/api v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc h1:XSJ8Vk1SWuNr8S18z1NZSziL0CPIXLCCMDOEFtHBOFc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA= +google.golang.org/genproto v0.0.0-20240102182953-50ed04b92917 h1:nz5NESFLZbJGPFxDT/HCn+V1mZ8JGNoY4nUpmW/Y2eg= +google.golang.org/genproto v0.0.0-20240102182953-50ed04b92917/go.mod h1:pZqR+glSb11aJ+JQcczCvgf47+duRuzNSKqE8YAQnV0= +google.golang.org/genproto/googleapis/api v0.0.0-20240116215550-a9fa1716bcac h1:OZkkudMUu9LVQMCoRUbI/1p5VCo9BOrlvkqMvWtqa6s= +google.golang.org/genproto/googleapis/api v0.0.0-20240116215550-a9fa1716bcac/go.mod h1:B5xPO//w8qmBDjGReYLpR6UJPnkldGkCSMoH/2vxJeg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac h1:nUQEQmH/csSvFECKYRv6HWEyypysidKl2I6Qpsglq/0= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac/go.mod h1:daQN87bsDqDoe316QbbvX60nMoJQa4r6Ds0ZuoAe5yA= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -2254,8 +2304,8 @@ google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCD google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww= google.golang.org/grpc v1.52.1/go.mod h1:pu6fVzoFb+NBYNAvQL08ic+lvB2IojljRYuun5vorUY= google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= -google.golang.org/grpc v1.56.3 h1:8I4C0Yq1EjstUzUJzpcRVbuYA2mODtEmpWiQoN/b2nc= -google.golang.org/grpc v1.56.3/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= +google.golang.org/grpc v1.61.0 h1:TOvOcuXn30kRao+gfcvsebNEa5iZIiLkisYEkf7R7o0= +google.golang.org/grpc v1.61.0/go.mod h1:VUbo7IFqmF1QtCAstipjG0GIoq49KvMe9+h1jFLBNJs= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= @@ -2273,8 +2323,8 @@ google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= +google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -2309,7 +2359,6 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= @@ -2323,30 +2372,30 @@ honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= k8s.io/api v0.26.1/go.mod h1:xd/GBNgR0f707+ATNyPmQ1oyKSgndzXij81FzWGsejg= -k8s.io/api v0.26.2 h1:dM3cinp3PGB6asOySalOZxEG4CZ0IAdJsrYZXE/ovGQ= -k8s.io/api v0.26.2/go.mod h1:1kjMQsFE+QHPfskEcVNgL3+Hp88B80uj0QtSOlj8itU= +k8s.io/api v0.28.6 h1:yy6u9CuIhmg55YvF/BavPBBXB+5QicB64njJXxVnzLo= +k8s.io/api v0.28.6/go.mod h1:AM6Ys6g9MY3dl/XNaNfg/GePI0FT7WBGu8efU/lirAo= k8s.io/apimachinery v0.26.1/go.mod h1:tnPmbONNJ7ByJNz9+n9kMjNP8ON+1qoAIIC70lztu74= -k8s.io/apimachinery v0.26.2 h1:da1u3D5wfR5u2RpLhE/ZtZS2P7QvDgLZTi9wrNZl/tQ= -k8s.io/apimachinery v0.26.2/go.mod h1:ats7nN1LExKHvJ9TmwootT00Yz05MuYqPXEXaVeOy5I= +k8s.io/apimachinery v0.28.6 h1:RsTeR4z6S07srPg6XYrwXpTJVMXsjPXn0ODakMytSW0= +k8s.io/apimachinery v0.28.6/go.mod h1:QFNX/kCl/EMT2WTSz8k4WLCv2XnkOLMaL8GAVRMdpsA= k8s.io/client-go v0.26.1/go.mod h1:IWNSglg+rQ3OcvDkhY6+QLeasV4OYHDjdqeWkDQZwGE= -k8s.io/client-go v0.26.2 h1:s1WkVujHX3kTp4Zn4yGNFK+dlDXy1bAAkIl+cFAiuYI= -k8s.io/client-go v0.26.2/go.mod h1:u5EjOuSyBa09yqqyY7m3abZeovO/7D/WehVVlZ2qcqU= +k8s.io/client-go v0.28.6 h1:Gge6ziyIdafRchfoBKcpaARuz7jfrK1R1azuwORIsQI= +k8s.io/client-go v0.28.6/go.mod h1:+nu0Yp21Oeo/cBCsprNVXB2BfJTV51lFfe5tXl2rUL8= k8s.io/gengo v0.0.0-20210813121822-485abfe95c7c/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= -k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= +k8s.io/klog/v2 v2.120.1 h1:QXU6cPEOIslTGvZaXvFWiP9VKyeet3sawzTOvdXb4Vw= +k8s.io/klog/v2 v2.120.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280/go.mod h1:+Axhij7bCpeqhklhUTe3xmOn6bWxolyZEeyaFpjGtl4= k8s.io/kube-openapi v0.0.0-20221207184640-f3cff1453715/go.mod h1:+Axhij7bCpeqhklhUTe3xmOn6bWxolyZEeyaFpjGtl4= -k8s.io/kube-openapi v0.0.0-20230303024457-afdc3dddf62d h1:VcFq5n7wCJB2FQMCIHfC+f+jNcGgNMar1uKd6rVlifU= -k8s.io/kube-openapi v0.0.0-20230303024457-afdc3dddf62d/go.mod h1:y5VtZWM9sHHc2ZodIH/6SHzXj+TPU5USoA8lcIeKEKY= +k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 h1:aVUu9fTY98ivBPKR9Y5w/AuzbMm96cd3YHRTU83I780= +k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00/go.mod h1:AsvuZPBlUDVuCdzJ87iajxtXuR9oktsTctW/R9wwouA= k8s.io/utils v0.0.0-20210802155522-efc7438f0176/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20221107191617-1a15be271d1d/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= k8s.io/utils v0.0.0-20221128185143-99ec85e7a448/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -k8s.io/utils v0.0.0-20230308161112-d77c459e9343 h1:m7tbIjXGcGIAtpmQr7/NAi7RsWoW3E7Zcm4jI1HicTc= -k8s.io/utils v0.0.0-20230308161112-d77c459e9343/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= @@ -2354,8 +2403,9 @@ rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= 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/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4= +sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08= 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= diff --git a/vendor/cloud.google.com/go/compute/internal/version.go b/vendor/cloud.google.com/go/compute/internal/version.go index e939b9f5e..540ad16ac 100644 --- a/vendor/cloud.google.com/go/compute/internal/version.go +++ b/vendor/cloud.google.com/go/compute/internal/version.go @@ -15,4 +15,4 @@ package internal // Version is the current tagged release of the library. -const Version = "1.20.1" +const Version = "1.23.3" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/LICENSE.txt deleted file mode 100644 index 05b0ebf5b..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Microsoft Corporation. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/NOTICE.txt b/vendor/github.com/Azure/azure-sdk-for-go/NOTICE.txt deleted file mode 100644 index a338672ec..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/NOTICE.txt +++ /dev/null @@ -1,29 +0,0 @@ -NOTICES AND INFORMATION -Do Not Translate or Localize - -This software incorporates material from third parties. Microsoft makes certain -open source code available at https://3rdpartysource.microsoft.com, or you may -send a check or money order for US $5.00, including the product name, the open -source component name, and version number, to: - -Source Code Compliance Team -Microsoft Corporation -One Microsoft Way -Redmond, WA 98052 -USA - -Notwithstanding any other terms, you may reverse engineer this software to the -extent required to debug changes to any libraries licensed under the GNU Lesser -General Public License. - ------------------------------------------------------------------------------- - -Azure SDK for Go uses third-party libraries or other resources that may be -distributed under licenses different than the Azure SDK for Go software. - -In the event that we accidentally failed to list a required notice, please -bring it to our attention. Post an issue or email us: - - azgosdkhelp@microsoft.com - -The attached notices are provided for information only. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md new file mode 100644 index 000000000..5c8411cb5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md @@ -0,0 +1,735 @@ +# Release History + +## 1.9.1 (2023-12-11) + +### Bugs Fixed + +* The `retry-after-ms` and `x-ms-retry-after-ms` headers weren't being checked during retries. + +### Other Changes + +* Update dependencies. + +## 1.9.0 (2023-11-06) + +### Breaking Changes +> These changes affect only code written against previous beta versions of `v1.7.0` and `v1.8.0` +* The function `NewTokenCredential` has been removed from the `fake` package. Use a literal `&fake.TokenCredential{}` instead. +* The field `TracingNamespace` in `runtime.PipelineOptions` has been replaced by `TracingOptions`. + +### Bugs Fixed + +* Fixed an issue that could cause some allowed HTTP header values to not show up in logs. +* Include error text instead of error type in traces when the transport returns an error. +* Fixed an issue that could cause an HTTP/2 request to hang when the TCP connection becomes unresponsive. +* Block key and SAS authentication for non TLS protected endpoints. +* Passing a `nil` credential value will no longer cause a panic. Instead, the authentication is skipped. +* Calling `Error` on a zero-value `azcore.ResponseError` will no longer panic. +* Fixed an issue in `fake.PagerResponder[T]` that would cause a trailing error to be omitted when iterating over pages. +* Context values created by `azcore` will no longer flow across disjoint HTTP requests. + +### Other Changes + +* Skip generating trace info for no-op tracers. +* The `clientName` paramater in client constructors has been renamed to `moduleName`. + +## 1.9.0-beta.1 (2023-10-05) + +### Other Changes + +* The beta features for tracing and fakes have been reinstated. + +## 1.8.0 (2023-10-05) + +### Features Added + +* This includes the following features from `v1.8.0-beta.N` releases. + * Claims and CAE for authentication. + * New `messaging` package. + * Various helpers in the `runtime` package. + * Deprecation of `runtime.With*` funcs and their replacements in the `policy` package. +* Added types `KeyCredential` and `SASCredential` to the `azcore` package. + * Includes their respective constructor functions. +* Added types `KeyCredentialPolicy` and `SASCredentialPolicy` to the `azcore/runtime` package. + * Includes their respective constructor functions and options types. + +### Breaking Changes +> These changes affect only code written against beta versions of `v1.8.0` +* The beta features for tracing and fakes have been omitted for this release. + +### Bugs Fixed + +* Fixed an issue that could cause some ARM RPs to not be automatically registered. +* Block bearer token authentication for non TLS protected endpoints. + +### Other Changes + +* Updated dependencies. + +## 1.8.0-beta.3 (2023-09-07) + +### Features Added + +* Added function `FetcherForNextLink` and `FetcherForNextLinkOptions` to the `runtime` package to centralize creation of `Pager[T].Fetcher` from a next link URL. + +### Bugs Fixed + +* Suppress creating spans for nested SDK API calls. The HTTP span will be a child of the outer API span. + +### Other Changes + +* The following functions in the `runtime` package are now exposed from the `policy` package, and the `runtime` versions have been deprecated. + * `WithCaptureResponse` + * `WithHTTPHeader` + * `WithRetryOptions` + +## 1.7.2 (2023-09-06) + +### Bugs Fixed + +* Fix default HTTP transport to work in WASM modules. + +## 1.8.0-beta.2 (2023-08-14) + +### Features Added + +* Added function `SanitizePagerPollerPath` to the `server` package to centralize sanitization and formalize the contract. +* Added `TokenRequestOptions.EnableCAE` to indicate whether to request a CAE token. + +### Breaking Changes + +> This change affects only code written against beta version `v1.8.0-beta.1`. +* `messaging.CloudEvent` deserializes JSON objects as `[]byte`, instead of `json.RawMessage`. See the documentation for CloudEvent.Data for more information. + +> This change affects only code written against beta versions `v1.7.0-beta.2` and `v1.8.0-beta.1`. +* Removed parameter from method `Span.End()` and its type `tracing.SpanEndOptions`. This API GA'ed in `v1.2.0` so we cannot change it. + +### Bugs Fixed + +* Propagate any query parameters when constructing a fake poller and/or injecting next links. + +## 1.7.1 (2023-08-14) + +## Bugs Fixed + +* Enable TLS renegotiation in the default transport policy. + +## 1.8.0-beta.1 (2023-07-12) + +### Features Added + +- `messaging/CloudEvent` allows you to serialize/deserialize CloudEvents, as described in the CloudEvents 1.0 specification: [link](https://github.com/cloudevents/spec) + +### Other Changes + +* The beta features for CAE, tracing, and fakes have been reinstated. + +## 1.7.0 (2023-07-12) + +### Features Added +* Added method `WithClientName()` to type `azcore.Client` to support shallow cloning of a client with a new name used for tracing. + +### Breaking Changes +> These changes affect only code written against beta versions v1.7.0-beta.1 or v1.7.0-beta.2 +* The beta features for CAE, tracing, and fakes have been omitted for this release. + +## 1.7.0-beta.2 (2023-06-06) + +### Breaking Changes +> These changes affect only code written against beta version v1.7.0-beta.1 +* Method `SpanFromContext()` on type `tracing.Tracer` had the `bool` return value removed. + * This includes the field `SpanFromContext` in supporting type `tracing.TracerOptions`. +* Method `AddError()` has been removed from type `tracing.Span`. +* Method `Span.End()` now requires an argument of type `*tracing.SpanEndOptions`. + +## 1.6.1 (2023-06-06) + +### Bugs Fixed +* Fixed an issue in `azcore.NewClient()` and `arm.NewClient()` that could cause an incorrect module name to be used in telemetry. + +### Other Changes +* This version contains all bug fixes from `v1.7.0-beta.1` + +## 1.7.0-beta.1 (2023-05-24) + +### Features Added +* Restored CAE support for ARM clients. +* Added supporting features to enable distributed tracing. + * Added func `runtime.StartSpan()` for use by SDKs to start spans. + * Added method `WithContext()` to `runtime.Request` to support shallow cloning with a new context. + * Added field `TracingNamespace` to `runtime.PipelineOptions`. + * Added field `Tracer` to `runtime.NewPollerOptions` and `runtime.NewPollerFromResumeTokenOptions` types. + * Added field `SpanFromContext` to `tracing.TracerOptions`. + * Added methods `Enabled()`, `SetAttributes()`, and `SpanFromContext()` to `tracing.Tracer`. + * Added supporting pipeline policies to include HTTP spans when creating clients. +* Added package `fake` to support generated fakes packages in SDKs. + * The package contains public surface area exposed by fake servers and supporting APIs intended only for use by the fake server implementations. + * Added an internal fake poller implementation. + +### Bugs Fixed +* Retry policy always clones the underlying `*http.Request` before invoking the next policy. +* Added some non-standard error codes to the list of error codes for unregistered resource providers. + +## 1.6.0 (2023-05-04) + +### Features Added +* Added support for ARM cross-tenant authentication. Set the `AuxiliaryTenants` field of `arm.ClientOptions` to enable. +* Added `TenantID` field to `policy.TokenRequestOptions`. + +## 1.5.0 (2023-04-06) + +### Features Added +* Added `ShouldRetry` to `policy.RetryOptions` for finer-grained control over when to retry. + +### Breaking Changes +> These changes affect only code written against a beta version such as v1.5.0-beta.1 +> These features will return in v1.6.0-beta.1. +* Removed `TokenRequestOptions.Claims` and `.TenantID` +* Removed ARM client support for CAE and cross-tenant auth. + +### Bugs Fixed +* Added non-conformant LRO terminal states `Cancelled` and `Completed`. + +### Other Changes +* Updated to latest `internal` module. + +## 1.5.0-beta.1 (2023-03-02) + +### Features Added +* This release includes the features added in v1.4.0-beta.1 + +## 1.4.0 (2023-03-02) +> This release doesn't include features added in v1.4.0-beta.1. They will return in v1.5.0-beta.1. + +### Features Added +* Add `Clone()` method for `arm/policy.ClientOptions`. + +### Bugs Fixed +* ARM's RP registration policy will no longer swallow unrecognized errors. +* Fixed an issue in `runtime.NewPollerFromResumeToken()` when resuming a `Poller` with a custom `PollingHandler`. +* Fixed wrong policy copy in `arm/runtime.NewPipeline()`. + +## 1.4.0-beta.1 (2023-02-02) + +### Features Added +* Added support for ARM cross-tenant authentication. Set the `AuxiliaryTenants` field of `arm.ClientOptions` to enable. +* Added `Claims` and `TenantID` fields to `policy.TokenRequestOptions`. +* ARM bearer token policy handles CAE challenges. + +## 1.3.1 (2023-02-02) + +### Other Changes +* Update dependencies to latest versions. + +## 1.3.0 (2023-01-06) + +### Features Added +* Added `BearerTokenOptions.AuthorizationHandler` to enable extending `runtime.BearerTokenPolicy` + with custom authorization logic +* Added `Client` types and matching constructors to the `azcore` and `arm` packages. These represent a basic client for HTTP and ARM respectively. + +### Other Changes +* Updated `internal` module to latest version. +* `policy/Request.SetBody()` allows replacing a request's body with an empty one + +## 1.2.0 (2022-11-04) + +### Features Added +* Added `ClientOptions.APIVersion` field, which overrides the default version a client + requests of the service, if the client supports this (all ARM clients do). +* Added package `tracing` that contains the building blocks for distributed tracing. +* Added field `TracingProvider` to type `policy.ClientOptions` that will be used to set the per-client tracing implementation. + +### Bugs Fixed +* Fixed an issue in `runtime.SetMultipartFormData` to properly handle slices of `io.ReadSeekCloser`. +* Fixed the MaxRetryDelay default to be 60s. +* Failure to poll the state of an LRO will now return an `*azcore.ResponseError` for poller types that require this behavior. +* Fixed a bug in `runtime.NewPipeline` that would cause pipeline-specified allowed headers and query parameters to be lost. + +### Other Changes +* Retain contents of read-only fields when sending requests. + +## 1.1.4 (2022-10-06) + +### Bugs Fixed +* Don't retry a request if the `Retry-After` delay is greater than the configured `RetryOptions.MaxRetryDelay`. +* `runtime.JoinPaths`: do not unconditionally add a forward slash before the query string + +### Other Changes +* Removed logging URL from retry policy as it's redundant. +* Retry policy logs when it exits due to a non-retriable status code. + +## 1.1.3 (2022-09-01) + +### Bugs Fixed +* Adjusted the initial retry delay to 800ms per the Azure SDK guidelines. + +## 1.1.2 (2022-08-09) + +### Other Changes +* Fixed various doc bugs. + +## 1.1.1 (2022-06-30) + +### Bugs Fixed +* Avoid polling when a RELO LRO synchronously terminates. + +## 1.1.0 (2022-06-03) + +### Other Changes +* The one-second floor for `Frequency` when calling `PollUntilDone()` has been removed when running tests. + +## 1.0.0 (2022-05-12) + +### Features Added +* Added interface `runtime.PollingHandler` to support custom poller implementations. + * Added field `PollingHandler` of this type to `runtime.NewPollerOptions[T]` and `runtime.NewPollerFromResumeTokenOptions[T]`. + +### Breaking Changes +* Renamed `cloud.Configuration.LoginEndpoint` to `.ActiveDirectoryAuthorityHost` +* Renamed `cloud.AzurePublicCloud` to `cloud.AzurePublic` +* Removed `AuxiliaryTenants` field from `arm/ClientOptions` and `arm/policy/BearerTokenOptions` +* Removed `TokenRequestOptions.TenantID` +* `Poller[T].PollUntilDone()` now takes an `options *PollUntilDoneOptions` param instead of `freq time.Duration` +* Removed `arm/runtime.Poller[T]`, `arm/runtime.NewPoller[T]()` and `arm/runtime.NewPollerFromResumeToken[T]()` +* Removed `arm/runtime.FinalStateVia` and related `const` values +* Renamed `runtime.PageProcessor` to `runtime.PagingHandler` +* The `arm/runtime.ProviderRepsonse` and `arm/runtime.Provider` types are no longer exported. +* Renamed `NewRequestIdPolicy()` to `NewRequestIDPolicy()` +* `TokenCredential.GetToken` now returns `AccessToken` by value. + +### Bugs Fixed +* When per-try timeouts are enabled, only cancel the context after the body has been read and closed. +* The `Operation-Location` poller now properly handles `final-state-via` values. +* Improvements in `runtime.Poller[T]` + * `Poll()` shouldn't cache errors, allowing for additional retries when in a non-terminal state. + * `Result()` will cache the terminal result or error but not transient errors, allowing for additional retries. + +### Other Changes +* Updated to latest `internal` module and absorbed breaking changes. + * Use `temporal.Resource` and deleted copy. +* The internal poller implementation has been refactored. + * The implementation in `internal/pollers/poller.go` has been merged into `runtime/poller.go` with some slight modification. + * The internal poller types had their methods updated to conform to the `runtime.PollingHandler` interface. + * The creation of resume tokens has been refactored so that implementers of `runtime.PollingHandler` don't need to know about it. +* `NewPipeline()` places policies from `ClientOptions` after policies from `PipelineOptions` +* Default User-Agent headers no longer include `azcore` version information + +## 0.23.1 (2022-04-14) + +### Bugs Fixed +* Include XML header when marshalling XML content. +* Handle XML namespaces when searching for error code. +* Handle `odata.error` when searching for error code. + +## 0.23.0 (2022-04-04) + +### Features Added +* Added `runtime.Pager[T any]` and `runtime.Poller[T any]` supporting types for central, generic, implementations. +* Added `cloud` package with a new API for cloud configuration +* Added `FinalStateVia` field to `runtime.NewPollerOptions[T any]` type. + +### Breaking Changes +* Removed the `Poller` type-alias to the internal poller implementation. +* Added `Ptr[T any]` and `SliceOfPtrs[T any]` in the `to` package and removed all non-generic implementations. +* `NullValue` and `IsNullValue` now take a generic type parameter instead of an interface func parameter. +* Replaced `arm.Endpoint` with `cloud` API + * Removed the `endpoint` parameter from `NewRPRegistrationPolicy()` + * `arm/runtime.NewPipeline()` and `.NewRPRegistrationPolicy()` now return an `error` +* Refactored `NewPoller` and `NewPollerFromResumeToken` funcs in `arm/runtime` and `runtime` packages. + * Removed the `pollerID` parameter as it's no longer required. + * Created optional parameter structs and moved optional parameters into them. +* Changed `FinalStateVia` field to a `const` type. + +### Other Changes +* Converted expiring resource and dependent types to use generics. + +## 0.22.0 (2022-03-03) + +### Features Added +* Added header `WWW-Authenticate` to the default allow-list of headers for logging. +* Added a pipeline policy that enables the retrieval of HTTP responses from API calls. + * Added `runtime.WithCaptureResponse` to enable the policy at the API level (off by default). + +### Breaking Changes +* Moved `WithHTTPHeader` and `WithRetryOptions` from the `policy` package to the `runtime` package. + +## 0.21.1 (2022-02-04) + +### Bugs Fixed +* Restore response body after reading in `Poller.FinalResponse()`. (#16911) +* Fixed bug in `NullValue` that could lead to incorrect comparisons for empty maps/slices (#16969) + +### Other Changes +* `BearerTokenPolicy` is more resilient to transient authentication failures. (#16789) + +## 0.21.0 (2022-01-11) + +### Features Added +* Added `AllowedHeaders` and `AllowedQueryParams` to `policy.LogOptions` to control which headers and query parameters are written to the logger. +* Added `azcore.ResponseError` type which is returned from APIs when a non-success HTTP status code is received. + +### Breaking Changes +* Moved `[]policy.Policy` parameters of `arm/runtime.NewPipeline` and `runtime.NewPipeline` into a new struct, `runtime.PipelineOptions` +* Renamed `arm/ClientOptions.Host` to `.Endpoint` +* Moved `Request.SkipBodyDownload` method to function `runtime.SkipBodyDownload` +* Removed `azcore.HTTPResponse` interface type +* `arm.NewPoller()` and `runtime.NewPoller()` no longer require an `eu` parameter +* `runtime.NewResponseError()` no longer requires an `error` parameter + +## 0.20.0 (2021-10-22) + +### Breaking Changes +* Removed `arm.Connection` +* Removed `azcore.Credential` and `.NewAnonymousCredential()` + * `NewRPRegistrationPolicy` now requires an `azcore.TokenCredential` +* `runtime.NewPipeline` has a new signature that simplifies implementing custom authentication +* `arm/runtime.RegistrationOptions` embeds `policy.ClientOptions` +* Contents in the `log` package have been slightly renamed. +* Removed `AuthenticationOptions` in favor of `policy.BearerTokenOptions` +* Changed parameters for `NewBearerTokenPolicy()` +* Moved policy config options out of `arm/runtime` and into `arm/policy` + +### Features Added +* Updating Documentation +* Added string typdef `arm.Endpoint` to provide a hint toward expected ARM client endpoints +* `azcore.ClientOptions` contains common pipeline configuration settings +* Added support for multi-tenant authorization in `arm/runtime` +* Require one second minimum when calling `PollUntilDone()` + +### Bug Fixes +* Fixed a potential panic when creating the default Transporter. +* Close LRO initial response body when creating a poller. +* Fixed a panic when recursively cloning structs that contain time.Time. + +## 0.19.0 (2021-08-25) + +### Breaking Changes +* Split content out of `azcore` into various packages. The intent is to separate content based on its usage (common, uncommon, SDK authors). + * `azcore` has all core functionality. + * `log` contains facilities for configuring in-box logging. + * `policy` is used for configuring pipeline options and creating custom pipeline policies. + * `runtime` contains various helpers used by SDK authors and generated content. + * `streaming` has helpers for streaming IO operations. +* `NewTelemetryPolicy()` now requires module and version parameters and the `Value` option has been removed. + * As a result, the `Request.Telemetry()` method has been removed. +* The telemetry policy now includes the SDK prefix `azsdk-go-` so callers no longer need to provide it. +* The `*http.Request` in `runtime.Request` is no longer anonymously embedded. Use the `Raw()` method to access it. +* The `UserAgent` and `Version` constants have been made internal, `Module` and `Version` respectively. + +### Bug Fixes +* Fixed an issue in the retry policy where the request body could be overwritten after a rewind. + +### Other Changes +* Moved modules `armcore` and `to` content into `arm` and `to` packages respectively. + * The `Pipeline()` method on `armcore.Connection` has been replaced by `NewPipeline()` in `arm.Connection`. It takes module and version parameters used by the telemetry policy. +* Poller logic has been consolidated across ARM and core implementations. + * This required some changes to the internal interfaces for core pollers. +* The core poller types have been improved, including more logging and test coverage. + +## 0.18.1 (2021-08-20) + +### Features Added +* Adds an `ETag` type for comparing etags and handling etags on requests +* Simplifies the `requestBodyProgess` and `responseBodyProgress` into a single `progress` object + +### Bugs Fixed +* `JoinPaths` will preserve query parameters encoded in the `root` url. + +### Other Changes +* Bumps dependency on `internal` module to the latest version (v0.7.0) + +## 0.18.0 (2021-07-29) +### Features Added +* Replaces methods from Logger type with two package methods for interacting with the logging functionality. +* `azcore.SetClassifications` replaces `azcore.Logger().SetClassifications` +* `azcore.SetListener` replaces `azcore.Logger().SetListener` + +### Breaking Changes +* Removes `Logger` type from `azcore` + + +## 0.17.0 (2021-07-27) +### Features Added +* Adding TenantID to TokenRequestOptions (https://github.com/Azure/azure-sdk-for-go/pull/14879) +* Adding AuxiliaryTenants to AuthenticationOptions (https://github.com/Azure/azure-sdk-for-go/pull/15123) + +### Breaking Changes +* Rename `AnonymousCredential` to `NewAnonymousCredential` (https://github.com/Azure/azure-sdk-for-go/pull/15104) +* rename `AuthenticationPolicyOptions` to `AuthenticationOptions` (https://github.com/Azure/azure-sdk-for-go/pull/15103) +* Make Header constants private (https://github.com/Azure/azure-sdk-for-go/pull/15038) + + +## 0.16.2 (2021-05-26) +### Features Added +* Improved support for byte arrays [#14715](https://github.com/Azure/azure-sdk-for-go/pull/14715) + + +## 0.16.1 (2021-05-19) +### Features Added +* Add license.txt to azcore module [#14682](https://github.com/Azure/azure-sdk-for-go/pull/14682) + + +## 0.16.0 (2021-05-07) +### Features Added +* Remove extra `*` in UnmarshalAsByteArray() [#14642](https://github.com/Azure/azure-sdk-for-go/pull/14642) + + +## 0.15.1 (2021-05-06) +### Features Added +* Cache the original request body on Request [#14634](https://github.com/Azure/azure-sdk-for-go/pull/14634) + + +## 0.15.0 (2021-05-05) +### Features Added +* Add support for null map and slice +* Export `Response.Payload` method + +### Breaking Changes +* remove `Response.UnmarshalError` as it's no longer required + + +## 0.14.5 (2021-04-23) +### Features Added +* Add `UnmarshalError()` on `azcore.Response` + + +## 0.14.4 (2021-04-22) +### Features Added +* Support for basic LRO polling +* Added type `LROPoller` and supporting types for basic polling on long running operations. +* rename poller param and added doc comment + +### Bugs Fixed +* Fixed content type detection bug in logging. + + +## 0.14.3 (2021-03-29) +### Features Added +* Add support for multi-part form data +* Added method `WriteMultipartFormData()` to Request. + + +## 0.14.2 (2021-03-17) +### Features Added +* Add support for encoding JSON null values +* Adds `NullValue()` and `IsNullValue()` functions for setting and detecting sentinel values used for encoding a JSON null. +* Documentation fixes + +### Bugs Fixed +* Fixed improper error wrapping + + +## 0.14.1 (2021-02-08) +### Features Added +* Add `Pager` and `Poller` interfaces to azcore + + +## 0.14.0 (2021-01-12) +### Features Added +* Accept zero-value options for default values +* Specify zero-value options structs to accept default values. +* Remove `DefaultXxxOptions()` methods. +* Do not silently change TryTimeout on negative values +* make per-try timeout opt-in + + +## 0.13.4 (2020-11-20) +### Features Added +* Include telemetry string in User Agent + + +## 0.13.3 (2020-11-20) +### Features Added +* Updating response body handling on `azcore.Response` + + +## 0.13.2 (2020-11-13) +### Features Added +* Remove implementation of stateless policies as first-class functions. + + +## 0.13.1 (2020-11-05) +### Features Added +* Add `Telemetry()` method to `azcore.Request()` + + +## 0.13.0 (2020-10-14) +### Features Added +* Rename `log` to `logger` to avoid name collision with the log package. +* Documentation improvements +* Simplified `DefaultHTTPClientTransport()` implementation + + +## 0.12.1 (2020-10-13) +### Features Added +* Update `internal` module dependence to `v0.5.0` + + +## 0.12.0 (2020-10-08) +### Features Added +* Removed storage specific content +* Removed internal content to prevent API clutter +* Refactored various policy options to conform with our options pattern + + +## 0.11.0 (2020-09-22) +### Features Added + +* Removed `LogError` and `LogSlowResponse`. +* Renamed `options` in `RequestLogOptions`. +* Updated `NewRequestLogPolicy()` to follow standard pattern for options. +* Refactored `requestLogPolicy.Do()` per above changes. +* Cleaned up/added logging in retry policy. +* Export `NewResponseError()` +* Fix `RequestLogOptions` comment + + +## 0.10.1 (2020-09-17) +### Features Added +* Add default console logger +* Default console logger writes to stderr. To enable it, set env var `AZURE_SDK_GO_LOGGING` to the value 'all'. +* Added `Logger.Writef()` to reduce the need for `ShouldLog()` checks. +* Add `LogLongRunningOperation` + + +## 0.10.0 (2020-09-10) +### Features Added +* The `request` and `transport` interfaces have been refactored to align with the patterns in the standard library. +* `NewRequest()` now uses `http.NewRequestWithContext()` and performs additional validation, it also requires a context parameter. +* The `Policy` and `Transport` interfaces have had their context parameter removed as the context is associated with the underlying `http.Request`. +* `Pipeline.Do()` will validate the HTTP request before sending it through the pipeline, avoiding retries on a malformed request. +* The `Retrier` interface has been replaced with the `NonRetriableError` interface, and the retry policy updated to test for this. +* `Request.SetBody()` now requires a content type parameter for setting the request's MIME type. +* moved path concatenation into `JoinPaths()` func + + +## 0.9.6 (2020-08-18) +### Features Added +* Improvements to body download policy +* Always download the response body for error responses, i.e. HTTP status codes >= 400. +* Simplify variable declarations + + +## 0.9.5 (2020-08-11) +### Features Added +* Set the Content-Length header in `Request.SetBody` + + +## 0.9.4 (2020-08-03) +### Features Added +* Fix cancellation of per try timeout +* Per try timeout is used to ensure that an HTTP operation doesn't take too long, e.g. that a GET on some URL doesn't take an inordinant amount of time. +* Once the HTTP request returns, the per try timeout should be cancelled, not when the response has been read to completion. +* Do not drain response body if there are no more retries +* Do not retry non-idempotent operations when body download fails + + +## 0.9.3 (2020-07-28) +### Features Added +* Add support for custom HTTP request headers +* Inserts an internal policy into the pipeline that can extract HTTP header values from the caller's context, adding them to the request. +* Use `azcore.WithHTTPHeader` to add HTTP headers to a context. +* Remove method specific to Go 1.14 + + +## 0.9.2 (2020-07-28) +### Features Added +* Omit read-only content from request payloads +* If any field in a payload's object graph contains `azure:"ro"`, make a clone of the object graph, omitting all fields with this annotation. +* Verify no fields were dropped +* Handle embedded struct types +* Added test for cloning by value +* Add messages to failures + + +## 0.9.1 (2020-07-22) +### Features Added +* Updated dependency on internal module to fix race condition. + + +## 0.9.0 (2020-07-09) +### Features Added +* Add `HTTPResponse` interface to be used by callers to access the raw HTTP response from an error in the event of an API call failure. +* Updated `sdk/internal` dependency to latest version. +* Rename package alias + + +## 0.8.2 (2020-06-29) +### Features Added +* Added missing documentation comments + +### Bugs Fixed +* Fixed a bug in body download policy. + + +## 0.8.1 (2020-06-26) +### Features Added +* Miscellaneous clean-up reported by linters + + +## 0.8.0 (2020-06-01) +### Features Added +* Differentiate between standard and URL encoding. + + +## 0.7.1 (2020-05-27) +### Features Added +* Add support for for base64 encoding and decoding of payloads. + + +## 0.7.0 (2020-05-12) +### Features Added +* Change `RetryAfter()` to a function. + + +## 0.6.0 (2020-04-29) +### Features Added +* Updating `RetryAfter` to only return the detaion in the RetryAfter header + + +## 0.5.0 (2020-03-23) +### Features Added +* Export `TransportFunc` + +### Breaking Changes +* Removed `IterationDone` + + +## 0.4.1 (2020-02-25) +### Features Added +* Ensure per-try timeout is properly cancelled +* Explicitly call cancel the per-try timeout when the response body has been read/closed by the body download policy. +* When the response body is returned to the caller for reading/closing, wrap it in a `responseBodyReader` that will cancel the timeout when the body is closed. +* `Logger.Should()` will return false if no listener is set. + + +## 0.4.0 (2020-02-18) +### Features Added +* Enable custom `RetryOptions` to be specified per API call +* Added `WithRetryOptions()` that adds a custom `RetryOptions` to the provided context, allowing custom settings per API call. +* Remove 429 from the list of default HTTP status codes for retry. +* Change StatusCodesForRetry to a slice so consumers can append to it. +* Added support for retry-after in HTTP-date format. +* Cleaned up some comments specific to storage. +* Remove `Request.SetQueryParam()` +* Renamed `MaxTries` to `MaxRetries` + +## 0.3.0 (2020-01-16) +### Features Added +* Added `DefaultRetryOptions` to create initialized default options. + +### Breaking Changes +* Removed `Response.CheckStatusCode()` + + +## 0.2.0 (2020-01-15) +### Features Added +* Add support for marshalling and unmarshalling JSON +* Removed `Response.Payload` field +* Exit early when unmarsahlling if there is no payload + + +## 0.1.0 (2020-01-10) +### Features Added +* Initial release diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/LICENSE.txt new file mode 100644 index 000000000..48ea6616b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/README.md new file mode 100644 index 000000000..35a74e18d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/README.md @@ -0,0 +1,39 @@ +# Azure Core Client Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/azcore)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore) +[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/go/go%20-%20azcore%20-%20ci?branchName=main)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=1843&branchName=main) +[![Code Coverage](https://img.shields.io/azure-devops/coverage/azure-sdk/public/1843/main)](https://img.shields.io/azure-devops/coverage/azure-sdk/public/1843/main) + +The `azcore` module provides a set of common interfaces and types for Go SDK client modules. +These modules follow the [Azure SDK Design Guidelines for Go](https://azure.github.io/azure-sdk/golang_introduction.html). + +## Getting started + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Typically, you will not need to explicitly install `azcore` as it will be installed as a client module dependency. +To add the latest version to your `go.mod` file, execute the following command. + +```bash +go get github.com/Azure/azure-sdk-for-go/sdk/azcore +``` + +General documentation and examples can be found on [pkg.go.dev](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## 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. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/client.go new file mode 100644 index 000000000..c373cc43f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/client.go @@ -0,0 +1,72 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package arm + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +// ClientOptions contains configuration settings for a client's pipeline. +type ClientOptions = armpolicy.ClientOptions + +// Client is a HTTP client for use with ARM endpoints. It consists of an endpoint, pipeline, and tracing provider. +type Client struct { + ep string + pl runtime.Pipeline + tr tracing.Tracer +} + +// NewClient creates a new Client instance with the provided values. +// This client is intended to be used with Azure Resource Manager endpoints. +// - moduleName - the fully qualified name of the module where the client is defined; used by the telemetry policy and tracing provider. +// - moduleVersion - the semantic version of the module; used by the telemetry policy and tracing provider. +// - cred - the TokenCredential used to authenticate the request +// - options - optional client configurations; pass nil to accept the default values +func NewClient(moduleName, moduleVersion string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error) { + if options == nil { + options = &ClientOptions{} + } + + if !options.Telemetry.Disabled { + if err := shared.ValidateModVer(moduleVersion); err != nil { + return nil, err + } + } + + ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint + if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok { + ep = c.Endpoint + } + pl, err := armruntime.NewPipeline(moduleName, moduleVersion, cred, runtime.PipelineOptions{}, options) + if err != nil { + return nil, err + } + + tr := options.TracingProvider.NewTracer(moduleName, moduleVersion) + return &Client{ep: ep, pl: pl, tr: tr}, nil +} + +// Endpoint returns the service's base URL for this client. +func (c *Client) Endpoint() string { + return c.ep +} + +// Pipeline returns the pipeline for this client. +func (c *Client) Pipeline() runtime.Pipeline { + return c.pl +} + +// Tracer returns the tracer for this client. +func (c *Client) Tracer() tracing.Tracer { + return c.tr +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/doc.go new file mode 100644 index 000000000..1bdd16a3d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/doc.go @@ -0,0 +1,9 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package arm contains functionality specific to Azure Resource Manager clients. +package arm diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource/resource_identifier.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource/resource_identifier.go new file mode 100644 index 000000000..187fe82b9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource/resource_identifier.go @@ -0,0 +1,224 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package resource + +import ( + "fmt" + "strings" +) + +const ( + providersKey = "providers" + subscriptionsKey = "subscriptions" + resourceGroupsLowerKey = "resourcegroups" + locationsKey = "locations" + builtInResourceNamespace = "Microsoft.Resources" +) + +// RootResourceID defines the tenant as the root parent of all other ResourceID. +var RootResourceID = &ResourceID{ + Parent: nil, + ResourceType: TenantResourceType, + Name: "", +} + +// ResourceID represents a resource ID such as `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg`. +// Don't create this type directly, use ParseResourceID instead. +type ResourceID struct { + // Parent is the parent ResourceID of this instance. + // Can be nil if there is no parent. + Parent *ResourceID + + // SubscriptionID is the subscription ID in this resource ID. + // The value can be empty if the resource ID does not contain a subscription ID. + SubscriptionID string + + // ResourceGroupName is the resource group name in this resource ID. + // The value can be empty if the resource ID does not contain a resource group name. + ResourceGroupName string + + // Provider represents the provider name in this resource ID. + // This is only valid when the resource ID represents a resource provider. + // Example: `/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.Insights` + Provider string + + // Location is the location in this resource ID. + // The value can be empty if the resource ID does not contain a location name. + Location string + + // ResourceType represents the type of this resource ID. + ResourceType ResourceType + + // Name is the resource name of this resource ID. + Name string + + isChild bool + stringValue string +} + +// ParseResourceID parses a string to an instance of ResourceID +func ParseResourceID(id string) (*ResourceID, error) { + if len(id) == 0 { + return nil, fmt.Errorf("invalid resource ID: id cannot be empty") + } + + if !strings.HasPrefix(id, "/") { + return nil, fmt.Errorf("invalid resource ID: resource id '%s' must start with '/'", id) + } + + parts := splitStringAndOmitEmpty(id, "/") + + if len(parts) < 2 { + return nil, fmt.Errorf("invalid resource ID: %s", id) + } + + if !strings.EqualFold(parts[0], subscriptionsKey) && !strings.EqualFold(parts[0], providersKey) { + return nil, fmt.Errorf("invalid resource ID: %s", id) + } + + return appendNext(RootResourceID, parts, id) +} + +// String returns the string of the ResourceID +func (id *ResourceID) String() string { + if len(id.stringValue) > 0 { + return id.stringValue + } + + if id.Parent == nil { + return "" + } + + builder := strings.Builder{} + builder.WriteString(id.Parent.String()) + + if id.isChild { + builder.WriteString(fmt.Sprintf("/%s", id.ResourceType.lastType())) + if len(id.Name) > 0 { + builder.WriteString(fmt.Sprintf("/%s", id.Name)) + } + } else { + builder.WriteString(fmt.Sprintf("/providers/%s/%s/%s", id.ResourceType.Namespace, id.ResourceType.Type, id.Name)) + } + + id.stringValue = builder.String() + + return id.stringValue +} + +func newResourceID(parent *ResourceID, resourceTypeName string, resourceName string) *ResourceID { + id := &ResourceID{} + id.init(parent, chooseResourceType(resourceTypeName, parent), resourceName, true) + return id +} + +func newResourceIDWithResourceType(parent *ResourceID, resourceType ResourceType, resourceName string) *ResourceID { + id := &ResourceID{} + id.init(parent, resourceType, resourceName, true) + return id +} + +func newResourceIDWithProvider(parent *ResourceID, providerNamespace, resourceTypeName, resourceName string) *ResourceID { + id := &ResourceID{} + id.init(parent, NewResourceType(providerNamespace, resourceTypeName), resourceName, false) + return id +} + +func chooseResourceType(resourceTypeName string, parent *ResourceID) ResourceType { + if strings.EqualFold(resourceTypeName, resourceGroupsLowerKey) { + return ResourceGroupResourceType + } else if strings.EqualFold(resourceTypeName, subscriptionsKey) && parent != nil && parent.ResourceType.String() == TenantResourceType.String() { + return SubscriptionResourceType + } + + return parent.ResourceType.AppendChild(resourceTypeName) +} + +func (id *ResourceID) init(parent *ResourceID, resourceType ResourceType, name string, isChild bool) { + if parent != nil { + id.Provider = parent.Provider + id.SubscriptionID = parent.SubscriptionID + id.ResourceGroupName = parent.ResourceGroupName + id.Location = parent.Location + } + + if resourceType.String() == SubscriptionResourceType.String() { + id.SubscriptionID = name + } + + if resourceType.lastType() == locationsKey { + id.Location = name + } + + if resourceType.String() == ResourceGroupResourceType.String() { + id.ResourceGroupName = name + } + + if resourceType.String() == ProviderResourceType.String() { + id.Provider = name + } + + if parent == nil { + id.Parent = RootResourceID + } else { + id.Parent = parent + } + id.isChild = isChild + id.ResourceType = resourceType + id.Name = name +} + +func appendNext(parent *ResourceID, parts []string, id string) (*ResourceID, error) { + if len(parts) == 0 { + return parent, nil + } + + if len(parts) == 1 { + // subscriptions and resourceGroups are not valid ids without their names + if strings.EqualFold(parts[0], subscriptionsKey) || strings.EqualFold(parts[0], resourceGroupsLowerKey) { + return nil, fmt.Errorf("invalid resource ID: %s", id) + } + + // resourceGroup must contain either child or provider resource type + if parent.ResourceType.String() == ResourceGroupResourceType.String() { + return nil, fmt.Errorf("invalid resource ID: %s", id) + } + + return newResourceID(parent, parts[0], ""), nil + } + + if strings.EqualFold(parts[0], providersKey) && (len(parts) == 2 || strings.EqualFold(parts[2], providersKey)) { + //provider resource can only be on a tenant or a subscription parent + if parent.ResourceType.String() != SubscriptionResourceType.String() && parent.ResourceType.String() != TenantResourceType.String() { + return nil, fmt.Errorf("invalid resource ID: %s", id) + } + + return appendNext(newResourceIDWithResourceType(parent, ProviderResourceType, parts[1]), parts[2:], id) + } + + if len(parts) > 3 && strings.EqualFold(parts[0], providersKey) { + return appendNext(newResourceIDWithProvider(parent, parts[1], parts[2], parts[3]), parts[4:], id) + } + + if len(parts) > 1 && !strings.EqualFold(parts[0], providersKey) { + return appendNext(newResourceID(parent, parts[0], parts[1]), parts[2:], id) + } + + return nil, fmt.Errorf("invalid resource ID: %s", id) +} + +func splitStringAndOmitEmpty(v, sep string) []string { + r := make([]string, 0) + for _, s := range strings.Split(v, sep) { + if len(s) == 0 { + continue + } + r = append(r, s) + } + + return r +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource/resource_type.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource/resource_type.go new file mode 100644 index 000000000..ca03ac971 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource/resource_type.go @@ -0,0 +1,114 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package resource + +import ( + "fmt" + "strings" +) + +// SubscriptionResourceType is the ResourceType of a subscription +var SubscriptionResourceType = NewResourceType(builtInResourceNamespace, "subscriptions") + +// ResourceGroupResourceType is the ResourceType of a resource group +var ResourceGroupResourceType = NewResourceType(builtInResourceNamespace, "resourceGroups") + +// TenantResourceType is the ResourceType of a tenant +var TenantResourceType = NewResourceType(builtInResourceNamespace, "tenants") + +// ProviderResourceType is the ResourceType of a provider +var ProviderResourceType = NewResourceType(builtInResourceNamespace, "providers") + +// ResourceType represents an Azure resource type, e.g. "Microsoft.Network/virtualNetworks/subnets". +// Don't create this type directly, use ParseResourceType or NewResourceType instead. +type ResourceType struct { + // Namespace is the namespace of the resource type. + // e.g. "Microsoft.Network" in resource type "Microsoft.Network/virtualNetworks/subnets" + Namespace string + + // Type is the full type name of the resource type. + // e.g. "virtualNetworks/subnets" in resource type "Microsoft.Network/virtualNetworks/subnets" + Type string + + // Types is the slice of all the sub-types of this resource type. + // e.g. ["virtualNetworks", "subnets"] in resource type "Microsoft.Network/virtualNetworks/subnets" + Types []string + + stringValue string +} + +// String returns the string of the ResourceType +func (t ResourceType) String() string { + return t.stringValue +} + +// IsParentOf returns true when the receiver is the parent resource type of the child. +func (t ResourceType) IsParentOf(child ResourceType) bool { + if !strings.EqualFold(t.Namespace, child.Namespace) { + return false + } + if len(t.Types) >= len(child.Types) { + return false + } + for i := range t.Types { + if !strings.EqualFold(t.Types[i], child.Types[i]) { + return false + } + } + + return true +} + +// AppendChild creates an instance of ResourceType using the receiver as the parent with childType appended to it. +func (t ResourceType) AppendChild(childType string) ResourceType { + return NewResourceType(t.Namespace, fmt.Sprintf("%s/%s", t.Type, childType)) +} + +// NewResourceType creates an instance of ResourceType using a provider namespace +// such as "Microsoft.Network" and type such as "virtualNetworks/subnets". +func NewResourceType(providerNamespace, typeName string) ResourceType { + return ResourceType{ + Namespace: providerNamespace, + Type: typeName, + Types: splitStringAndOmitEmpty(typeName, "/"), + stringValue: fmt.Sprintf("%s/%s", providerNamespace, typeName), + } +} + +// ParseResourceType parses the ResourceType from a resource type string (e.g. Microsoft.Network/virtualNetworks/subsets) +// or a resource identifier string. +// e.g. /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/mySubnet) +func ParseResourceType(resourceIDOrType string) (ResourceType, error) { + // split the path into segments + parts := splitStringAndOmitEmpty(resourceIDOrType, "/") + + // There must be at least a namespace and type name + if len(parts) < 1 { + return ResourceType{}, fmt.Errorf("invalid resource ID or type: %s", resourceIDOrType) + } + + // if the type is just subscriptions, it is a built-in type in the Microsoft.Resources namespace + if len(parts) == 1 { + // Simple resource type + return NewResourceType(builtInResourceNamespace, parts[0]), nil + } else if strings.Contains(parts[0], ".") { + // Handle resource types (Microsoft.Compute/virtualMachines, Microsoft.Network/virtualNetworks/subnets) + // it is a full type name + return NewResourceType(parts[0], strings.Join(parts[1:], "/")), nil + } else { + // Check if ResourceID + id, err := ParseResourceID(resourceIDOrType) + if err != nil { + return ResourceType{}, err + } + return NewResourceType(id.ResourceType.Namespace, id.ResourceType.Type), nil + } +} + +func (t ResourceType) lastType() string { + return t.Types[len(t.Types)-1] +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy/policy.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy/policy.go new file mode 100644 index 000000000..83cf91e3e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy/policy.go @@ -0,0 +1,98 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package policy + +import ( + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// BearerTokenOptions configures the bearer token policy's behavior. +type BearerTokenOptions struct { + // AuxiliaryTenants are additional tenant IDs for authenticating cross-tenant requests. + // The policy will add a token from each of these tenants to every request. The + // authenticating user or service principal must be a guest in these tenants, and the + // policy's credential must support multitenant authentication. + AuxiliaryTenants []string + + // Scopes contains the list of permission scopes required for the token. + Scopes []string +} + +// RegistrationOptions configures the registration policy's behavior. +// All zero-value fields will be initialized with their default values. +type RegistrationOptions struct { + policy.ClientOptions + + // MaxAttempts is the total number of times to attempt automatic registration + // in the event that an attempt fails. + // The default value is 3. + // Set to a value less than zero to disable the policy. + MaxAttempts int + + // PollingDelay is the amount of time to sleep between polling intervals. + // The default value is 15 seconds. + // A value less than zero means no delay between polling intervals (not recommended). + PollingDelay time.Duration + + // PollingDuration is the amount of time to wait before abandoning polling. + // The default valule is 5 minutes. + // NOTE: Setting this to a small value might cause the policy to prematurely fail. + PollingDuration time.Duration +} + +// ClientOptions contains configuration settings for a client's pipeline. +type ClientOptions struct { + policy.ClientOptions + + // AuxiliaryTenants are additional tenant IDs for authenticating cross-tenant requests. + // The client will add a token from each of these tenants to every request. The + // authenticating user or service principal must be a guest in these tenants, and the + // client's credential must support multitenant authentication. + AuxiliaryTenants []string + + // DisableRPRegistration disables the auto-RP registration policy. Defaults to false. + DisableRPRegistration bool +} + +// Clone return a deep copy of the current options. +func (o *ClientOptions) Clone() *ClientOptions { + if o == nil { + return nil + } + copiedOptions := *o + copiedOptions.Cloud.Services = copyMap(copiedOptions.Cloud.Services) + copiedOptions.Logging.AllowedHeaders = copyArray(copiedOptions.Logging.AllowedHeaders) + copiedOptions.Logging.AllowedQueryParams = copyArray(copiedOptions.Logging.AllowedQueryParams) + copiedOptions.Retry.StatusCodes = copyArray(copiedOptions.Retry.StatusCodes) + copiedOptions.PerRetryPolicies = copyArray(copiedOptions.PerRetryPolicies) + copiedOptions.PerCallPolicies = copyArray(copiedOptions.PerCallPolicies) + return &copiedOptions +} + +// copyMap return a new map with all the key value pair in the src map +func copyMap[K comparable, V any](src map[K]V) map[K]V { + if src == nil { + return nil + } + copiedMap := make(map[K]V) + for k, v := range src { + copiedMap[k] = v + } + return copiedMap +} + +// copyMap return a new array with all the elements in the src array +func copyArray[T any](src []T) []T { + if src == nil { + return nil + } + copiedArray := make([]T, len(src)) + copy(copiedArray, src) + return copiedArray +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/resource_identifier.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/resource_identifier.go new file mode 100644 index 000000000..d35d6374f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/resource_identifier.go @@ -0,0 +1,23 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package arm + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource" +) + +// RootResourceID defines the tenant as the root parent of all other ResourceID. +var RootResourceID = resource.RootResourceID + +// ResourceID represents a resource ID such as `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg`. +// Don't create this type directly, use ParseResourceID instead. +type ResourceID = resource.ResourceID + +// ParseResourceID parses a string to an instance of ResourceID +func ParseResourceID(id string) (*ResourceID, error) { + return resource.ParseResourceID(id) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/resource_type.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/resource_type.go new file mode 100644 index 000000000..fc7fbffd2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/resource_type.go @@ -0,0 +1,40 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package arm + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource" +) + +// SubscriptionResourceType is the ResourceType of a subscription +var SubscriptionResourceType = resource.SubscriptionResourceType + +// ResourceGroupResourceType is the ResourceType of a resource group +var ResourceGroupResourceType = resource.ResourceGroupResourceType + +// TenantResourceType is the ResourceType of a tenant +var TenantResourceType = resource.TenantResourceType + +// ProviderResourceType is the ResourceType of a provider +var ProviderResourceType = resource.ProviderResourceType + +// ResourceType represents an Azure resource type, e.g. "Microsoft.Network/virtualNetworks/subnets". +// Don't create this type directly, use ParseResourceType or NewResourceType instead. +type ResourceType = resource.ResourceType + +// NewResourceType creates an instance of ResourceType using a provider namespace +// such as "Microsoft.Network" and type such as "virtualNetworks/subnets". +func NewResourceType(providerNamespace, typeName string) ResourceType { + return resource.NewResourceType(providerNamespace, typeName) +} + +// ParseResourceType parses the ResourceType from a resource type string (e.g. Microsoft.Network/virtualNetworks/subsets) +// or a resource identifier string. +// e.g. /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/mySubnet) +func ParseResourceType(resourceIDOrType string) (ResourceType, error) { + return resource.ParseResourceType(resourceIDOrType) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/pipeline.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/pipeline.go new file mode 100644 index 000000000..302c19cd4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/pipeline.go @@ -0,0 +1,65 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "errors" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// NewPipeline creates a pipeline from connection options. Policies from ClientOptions are +// placed after policies from PipelineOptions. The telemetry policy, when enabled, will +// use the specified module and version info. +func NewPipeline(module, version string, cred azcore.TokenCredential, plOpts azruntime.PipelineOptions, options *armpolicy.ClientOptions) (azruntime.Pipeline, error) { + if options == nil { + options = &armpolicy.ClientOptions{} + } + conf, err := getConfiguration(&options.ClientOptions) + if err != nil { + return azruntime.Pipeline{}, err + } + authPolicy := NewBearerTokenPolicy(cred, &armpolicy.BearerTokenOptions{ + AuxiliaryTenants: options.AuxiliaryTenants, + Scopes: []string{conf.Audience + "/.default"}, + }) + perRetry := make([]azpolicy.Policy, len(plOpts.PerRetry), len(plOpts.PerRetry)+1) + copy(perRetry, plOpts.PerRetry) + plOpts.PerRetry = append(perRetry, authPolicy, exported.PolicyFunc(httpTraceNamespacePolicy)) + if !options.DisableRPRegistration { + regRPOpts := armpolicy.RegistrationOptions{ClientOptions: options.ClientOptions} + regPolicy, err := NewRPRegistrationPolicy(cred, ®RPOpts) + if err != nil { + return azruntime.Pipeline{}, err + } + perCall := make([]azpolicy.Policy, len(plOpts.PerCall), len(plOpts.PerCall)+1) + copy(perCall, plOpts.PerCall) + plOpts.PerCall = append(perCall, regPolicy) + } + if plOpts.APIVersion.Name == "" { + plOpts.APIVersion.Name = "api-version" + } + return azruntime.NewPipeline(module, version, plOpts, &options.ClientOptions), nil +} + +func getConfiguration(o *azpolicy.ClientOptions) (cloud.ServiceConfiguration, error) { + c := cloud.AzurePublic + if !reflect.ValueOf(o.Cloud).IsZero() { + c = o.Cloud + } + if conf, ok := c.Services[cloud.ResourceManager]; ok && conf.Endpoint != "" && conf.Audience != "" { + return conf, nil + } else { + return conf, errors.New("provided Cloud field is missing Azure Resource Manager configuration") + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_bearer_token.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_bearer_token.go new file mode 100644 index 000000000..54b3bb78d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_bearer_token.go @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "encoding/base64" + "fmt" + "net/http" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/internal/temporal" +) + +const headerAuxiliaryAuthorization = "x-ms-authorization-auxiliary" + +// acquiringResourceState holds data for an auxiliary token request +type acquiringResourceState struct { + ctx context.Context + p *BearerTokenPolicy + tenant string +} + +// acquireAuxToken acquires a token from an auxiliary tenant. Only one thread/goroutine at a time ever calls this function. +func acquireAuxToken(state acquiringResourceState) (newResource azcore.AccessToken, newExpiration time.Time, err error) { + tk, err := state.p.cred.GetToken(state.ctx, azpolicy.TokenRequestOptions{ + EnableCAE: true, + Scopes: state.p.scopes, + TenantID: state.tenant, + }) + if err != nil { + return azcore.AccessToken{}, time.Time{}, err + } + return tk, tk.ExpiresOn, nil +} + +// BearerTokenPolicy authorizes requests with bearer tokens acquired from a TokenCredential. +type BearerTokenPolicy struct { + auxResources map[string]*temporal.Resource[azcore.AccessToken, acquiringResourceState] + btp *azruntime.BearerTokenPolicy + cred azcore.TokenCredential + scopes []string +} + +// NewBearerTokenPolicy creates a policy object that authorizes requests with bearer tokens. +// cred: an azcore.TokenCredential implementation such as a credential object from azidentity +// opts: optional settings. Pass nil to accept default values; this is the same as passing a zero-value options. +func NewBearerTokenPolicy(cred azcore.TokenCredential, opts *armpolicy.BearerTokenOptions) *BearerTokenPolicy { + if opts == nil { + opts = &armpolicy.BearerTokenOptions{} + } + p := &BearerTokenPolicy{cred: cred} + p.auxResources = make(map[string]*temporal.Resource[azcore.AccessToken, acquiringResourceState], len(opts.AuxiliaryTenants)) + for _, t := range opts.AuxiliaryTenants { + p.auxResources[t] = temporal.NewResource(acquireAuxToken) + } + p.scopes = make([]string, len(opts.Scopes)) + copy(p.scopes, opts.Scopes) + p.btp = azruntime.NewBearerTokenPolicy(cred, opts.Scopes, &azpolicy.BearerTokenOptions{ + AuthorizationHandler: azpolicy.AuthorizationHandler{ + OnChallenge: p.onChallenge, + OnRequest: p.onRequest, + }, + }) + return p +} + +func (b *BearerTokenPolicy) onChallenge(req *azpolicy.Request, res *http.Response, authNZ func(azpolicy.TokenRequestOptions) error) error { + challenge := res.Header.Get(shared.HeaderWWWAuthenticate) + claims, err := parseChallenge(challenge) + if err != nil { + // the challenge contains claims we can't parse + return err + } else if claims != "" { + // request a new token having the specified claims, send the request again + return authNZ(azpolicy.TokenRequestOptions{Claims: claims, EnableCAE: true, Scopes: b.scopes}) + } + // auth challenge didn't include claims, so this is a simple authorization failure + return azruntime.NewResponseError(res) +} + +// onRequest authorizes requests with one or more bearer tokens +func (b *BearerTokenPolicy) onRequest(req *azpolicy.Request, authNZ func(azpolicy.TokenRequestOptions) error) error { + // authorize the request with a token for the primary tenant + err := authNZ(azpolicy.TokenRequestOptions{EnableCAE: true, Scopes: b.scopes}) + if err != nil || len(b.auxResources) == 0 { + return err + } + // add tokens for auxiliary tenants + as := acquiringResourceState{ + ctx: req.Raw().Context(), + p: b, + } + auxTokens := make([]string, 0, len(b.auxResources)) + for tenant, er := range b.auxResources { + as.tenant = tenant + auxTk, err := er.Get(as) + if err != nil { + return err + } + auxTokens = append(auxTokens, fmt.Sprintf("%s%s", shared.BearerTokenPrefix, auxTk.Token)) + } + req.Raw().Header.Set(headerAuxiliaryAuthorization, strings.Join(auxTokens, ", ")) + return nil +} + +// Do authorizes a request with a bearer token +func (b *BearerTokenPolicy) Do(req *azpolicy.Request) (*http.Response, error) { + return b.btp.Do(req) +} + +// parseChallenge parses claims from an authentication challenge issued by ARM so a client can request a token +// that will satisfy conditional access policies. It returns a non-nil error when the given value contains +// claims it can't parse. If the value contains no claims, it returns an empty string and a nil error. +func parseChallenge(wwwAuthenticate string) (string, error) { + claims := "" + var err error + for _, param := range strings.Split(wwwAuthenticate, ",") { + if _, after, found := strings.Cut(param, "claims="); found { + if claims != "" { + // The header contains multiple challenges, at least two of which specify claims. The specs allow this + // but it's unclear what a client should do in this case and there's as yet no concrete example of it. + err = fmt.Errorf("found multiple claims challenges in %q", wwwAuthenticate) + break + } + // trim stuff that would get an error from RawURLEncoding; claims may or may not be padded + claims = strings.Trim(after, `\"=`) + // we don't return this error because it's something unhelpful like "illegal base64 data at input byte 42" + if b, decErr := base64.RawURLEncoding.DecodeString(claims); decErr == nil { + claims = string(b) + } else { + err = fmt.Errorf("failed to parse claims from %q", wwwAuthenticate) + break + } + } + } + return claims, err +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_register_rp.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_register_rp.go new file mode 100644 index 000000000..83e15949a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_register_rp.go @@ -0,0 +1,347 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +const ( + // LogRPRegistration entries contain information specific to the automatic registration of an RP. + // Entries of this classification are written IFF the policy needs to take any action. + LogRPRegistration log.Event = "RPRegistration" +) + +// init sets any default values +func setDefaults(r *armpolicy.RegistrationOptions) { + if r.MaxAttempts == 0 { + r.MaxAttempts = 3 + } else if r.MaxAttempts < 0 { + r.MaxAttempts = 0 + } + if r.PollingDelay == 0 { + r.PollingDelay = 15 * time.Second + } else if r.PollingDelay < 0 { + r.PollingDelay = 0 + } + if r.PollingDuration == 0 { + r.PollingDuration = 5 * time.Minute + } +} + +// NewRPRegistrationPolicy creates a policy object configured using the specified options. +// The policy controls whether an unregistered resource provider should automatically be +// registered. See https://aka.ms/rps-not-found for more information. +func NewRPRegistrationPolicy(cred azcore.TokenCredential, o *armpolicy.RegistrationOptions) (azpolicy.Policy, error) { + if o == nil { + o = &armpolicy.RegistrationOptions{} + } + conf, err := getConfiguration(&o.ClientOptions) + if err != nil { + return nil, err + } + authPolicy := NewBearerTokenPolicy(cred, &armpolicy.BearerTokenOptions{Scopes: []string{conf.Audience + "/.default"}}) + p := &rpRegistrationPolicy{ + endpoint: conf.Endpoint, + pipeline: runtime.NewPipeline(shared.Module, shared.Version, runtime.PipelineOptions{PerRetry: []azpolicy.Policy{authPolicy}}, &o.ClientOptions), + options: *o, + } + // init the copy + setDefaults(&p.options) + return p, nil +} + +type rpRegistrationPolicy struct { + endpoint string + pipeline runtime.Pipeline + options armpolicy.RegistrationOptions +} + +func (r *rpRegistrationPolicy) Do(req *azpolicy.Request) (*http.Response, error) { + if r.options.MaxAttempts == 0 { + // policy is disabled + return req.Next() + } + const registeredState = "Registered" + var rp string + var resp *http.Response + for attempts := 0; attempts < r.options.MaxAttempts; attempts++ { + var err error + // make the original request + resp, err = req.Next() + // getting a 409 is the first indication that the RP might need to be registered, check error response + if err != nil || resp.StatusCode != http.StatusConflict { + return resp, err + } + var reqErr requestError + if err = runtime.UnmarshalAsJSON(resp, &reqErr); err != nil { + return resp, err + } + if reqErr.ServiceError == nil { + // missing service error info. just return the response + // to the caller so its error unmarshalling will kick in + return resp, err + } + if !isUnregisteredRPCode(reqErr.ServiceError.Code) { + // not a 409 due to unregistered RP. just return the response + // to the caller so its error unmarshalling will kick in + return resp, err + } + // RP needs to be registered. start by getting the subscription ID from the original request + subID, err := getSubscription(req.Raw().URL.Path) + if err != nil { + return resp, err + } + // now get the RP from the error + rp, err = getProvider(reqErr) + if err != nil { + return resp, err + } + logRegistrationExit := func(v interface{}) { + log.Writef(LogRPRegistration, "END registration for %s: %v", rp, v) + } + log.Writef(LogRPRegistration, "BEGIN registration for %s", rp) + // create client and make the registration request + // we use the scheme and host from the original request + rpOps := &providersOperations{ + p: r.pipeline, + u: r.endpoint, + subID: subID, + } + if _, err = rpOps.Register(&shared.ContextWithDeniedValues{Context: req.Raw().Context()}, rp); err != nil { + logRegistrationExit(err) + return resp, err + } + + // RP was registered, however we need to wait for the registration to complete + pollCtx, pollCancel := context.WithTimeout(&shared.ContextWithDeniedValues{Context: req.Raw().Context()}, r.options.PollingDuration) + var lastRegState string + for { + // get the current registration state + getResp, err := rpOps.Get(pollCtx, rp) + if err != nil { + pollCancel() + logRegistrationExit(err) + return resp, err + } + if getResp.Provider.RegistrationState != nil && !strings.EqualFold(*getResp.Provider.RegistrationState, lastRegState) { + // registration state has changed, or was updated for the first time + lastRegState = *getResp.Provider.RegistrationState + log.Writef(LogRPRegistration, "registration state is %s", lastRegState) + } + if strings.EqualFold(lastRegState, registeredState) { + // registration complete + pollCancel() + logRegistrationExit(lastRegState) + break + } + // wait before trying again + select { + case <-time.After(r.options.PollingDelay): + // continue polling + case <-pollCtx.Done(): + pollCancel() + logRegistrationExit(pollCtx.Err()) + return resp, pollCtx.Err() + } + } + // RP was successfully registered, retry the original request + err = req.RewindBody() + if err != nil { + return resp, err + } + } + // if we get here it means we exceeded the number of attempts + return resp, fmt.Errorf("exceeded attempts to register %s", rp) +} + +var unregisteredRPCodes = []string{ + "MissingSubscriptionRegistration", + "MissingRegistrationForResourceProvider", + "Subscription Not Registered", + "SubscriptionNotRegistered", +} + +func isUnregisteredRPCode(errorCode string) bool { + for _, code := range unregisteredRPCodes { + if strings.EqualFold(errorCode, code) { + return true + } + } + return false +} + +func getSubscription(path string) (string, error) { + parts := strings.Split(path, "/") + for i, v := range parts { + if v == "subscriptions" && (i+1) < len(parts) { + return parts[i+1], nil + } + } + return "", fmt.Errorf("failed to obtain subscription ID from %s", path) +} + +func getProvider(re requestError) (string, error) { + if len(re.ServiceError.Details) > 0 { + return re.ServiceError.Details[0].Target, nil + } + return "", errors.New("unexpected empty Details") +} + +// minimal error definitions to simplify detection +type requestError struct { + ServiceError *serviceError `json:"error"` +} + +type serviceError struct { + Code string `json:"code"` + Details []serviceErrorDetails `json:"details"` +} + +type serviceErrorDetails struct { + Code string `json:"code"` + Target string `json:"target"` +} + +/////////////////////////////////////////////////////////////////////////////////////////////// +// the following code was copied from module armresources, providers.go and models.go +// only the minimum amount of code was copied to get this working and some edits were made. +/////////////////////////////////////////////////////////////////////////////////////////////// + +type providersOperations struct { + p runtime.Pipeline + u string + subID string +} + +// Get - Gets the specified resource provider. +func (client *providersOperations) Get(ctx context.Context, resourceProviderNamespace string) (providerResponse, error) { + req, err := client.getCreateRequest(ctx, resourceProviderNamespace) + if err != nil { + return providerResponse{}, err + } + resp, err := client.p.Do(req) + if err != nil { + return providerResponse{}, err + } + result, err := client.getHandleResponse(resp) + if err != nil { + return providerResponse{}, err + } + return result, nil +} + +// getCreateRequest creates the Get request. +func (client *providersOperations) getCreateRequest(ctx context.Context, resourceProviderNamespace string) (*azpolicy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}" + urlPath = strings.ReplaceAll(urlPath, "{resourceProviderNamespace}", url.PathEscape(resourceProviderNamespace)) + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.u, urlPath)) + if err != nil { + return nil, err + } + query := req.Raw().URL.Query() + query.Set("api-version", "2019-05-01") + req.Raw().URL.RawQuery = query.Encode() + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *providersOperations) getHandleResponse(resp *http.Response) (providerResponse, error) { + if !runtime.HasStatusCode(resp, http.StatusOK) { + return providerResponse{}, exported.NewResponseError(resp) + } + result := providerResponse{RawResponse: resp} + err := runtime.UnmarshalAsJSON(resp, &result.Provider) + if err != nil { + return providerResponse{}, err + } + return result, err +} + +// Register - Registers a subscription with a resource provider. +func (client *providersOperations) Register(ctx context.Context, resourceProviderNamespace string) (providerResponse, error) { + req, err := client.registerCreateRequest(ctx, resourceProviderNamespace) + if err != nil { + return providerResponse{}, err + } + resp, err := client.p.Do(req) + if err != nil { + return providerResponse{}, err + } + result, err := client.registerHandleResponse(resp) + if err != nil { + return providerResponse{}, err + } + return result, nil +} + +// registerCreateRequest creates the Register request. +func (client *providersOperations) registerCreateRequest(ctx context.Context, resourceProviderNamespace string) (*azpolicy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register" + urlPath = strings.ReplaceAll(urlPath, "{resourceProviderNamespace}", url.PathEscape(resourceProviderNamespace)) + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.u, urlPath)) + if err != nil { + return nil, err + } + query := req.Raw().URL.Query() + query.Set("api-version", "2019-05-01") + req.Raw().URL.RawQuery = query.Encode() + return req, nil +} + +// registerHandleResponse handles the Register response. +func (client *providersOperations) registerHandleResponse(resp *http.Response) (providerResponse, error) { + if !runtime.HasStatusCode(resp, http.StatusOK) { + return providerResponse{}, exported.NewResponseError(resp) + } + result := providerResponse{RawResponse: resp} + err := runtime.UnmarshalAsJSON(resp, &result.Provider) + if err != nil { + return providerResponse{}, err + } + return result, err +} + +// ProviderResponse is the response envelope for operations that return a Provider type. +type providerResponse struct { + // Resource provider information. + Provider *provider + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// Provider - Resource provider information. +type provider struct { + // The provider ID. + ID *string `json:"id,omitempty"` + + // The namespace of the resource provider. + Namespace *string `json:"namespace,omitempty"` + + // The registration policy of the resource provider. + RegistrationPolicy *string `json:"registrationPolicy,omitempty"` + + // The registration state of the resource provider. + RegistrationState *string `json:"registrationState,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_trace_namespace.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_trace_namespace.go new file mode 100644 index 000000000..6cea18424 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/policy_trace_namespace.go @@ -0,0 +1,30 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +// httpTraceNamespacePolicy is a policy that adds the az.namespace attribute to the current Span +func httpTraceNamespacePolicy(req *policy.Request) (resp *http.Response, err error) { + rawTracer := req.Raw().Context().Value(shared.CtxWithTracingTracer{}) + if tracer, ok := rawTracer.(tracing.Tracer); ok && tracer.Enabled() { + rt, err := resource.ParseResourceType(req.Raw().URL.Path) + if err == nil { + // add the namespace attribute to the current span + span := tracer.SpanFromContext(req.Raw().Context()) + span.SetAttributes(tracing.Attribute{Key: shared.TracingNamespaceAttrName, Value: rt.Namespace}) + } + } + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/runtime.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/runtime.go new file mode 100644 index 000000000..1400d4379 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime/runtime.go @@ -0,0 +1,24 @@ +//go:build go1.16 +// +build go1.16 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + +func init() { + cloud.AzureChina.Services[cloud.ResourceManager] = cloud.ServiceConfiguration{ + Audience: "https://management.core.chinacloudapi.cn", + Endpoint: "https://management.chinacloudapi.cn", + } + cloud.AzureGovernment.Services[cloud.ResourceManager] = cloud.ServiceConfiguration{ + Audience: "https://management.core.usgovcloudapi.net", + Endpoint: "https://management.usgovcloudapi.net", + } + cloud.AzurePublic.Services[cloud.ResourceManager] = cloud.ServiceConfiguration{ + Audience: "https://management.core.windows.net/", + Endpoint: "https://management.azure.com", + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/ci.yml new file mode 100644 index 000000000..aab921853 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/ci.yml @@ -0,0 +1,29 @@ +# 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/azcore/ + - eng/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/azcore/ + - eng/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: azcore diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/cloud.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/cloud.go new file mode 100644 index 000000000..9d077a3e1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/cloud.go @@ -0,0 +1,44 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package cloud + +var ( + // AzureChina contains configuration for Azure China. + AzureChina = Configuration{ + ActiveDirectoryAuthorityHost: "https://login.chinacloudapi.cn/", Services: map[ServiceName]ServiceConfiguration{}, + } + // AzureGovernment contains configuration for Azure Government. + AzureGovernment = Configuration{ + ActiveDirectoryAuthorityHost: "https://login.microsoftonline.us/", Services: map[ServiceName]ServiceConfiguration{}, + } + // AzurePublic contains configuration for Azure Public Cloud. + AzurePublic = Configuration{ + ActiveDirectoryAuthorityHost: "https://login.microsoftonline.com/", Services: map[ServiceName]ServiceConfiguration{}, + } +) + +// ServiceName identifies a cloud service. +type ServiceName string + +// ResourceManager is a global constant identifying Azure Resource Manager. +const ResourceManager ServiceName = "resourceManager" + +// ServiceConfiguration configures a specific cloud service such as Azure Resource Manager. +type ServiceConfiguration struct { + // Audience is the audience the client will request for its access tokens. + Audience string + // Endpoint is the service's base URL. + Endpoint string +} + +// Configuration configures a cloud. +type Configuration struct { + // ActiveDirectoryAuthorityHost is the base URL of the cloud's Azure Active Directory. + ActiveDirectoryAuthorityHost string + // Services contains configuration for the cloud's services. + Services map[ServiceName]ServiceConfiguration +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/doc.go new file mode 100644 index 000000000..985b1bde2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/doc.go @@ -0,0 +1,53 @@ +//go:build go1.16 +// +build go1.16 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/* +Package cloud implements a configuration API for applications deployed to sovereign or private Azure clouds. + +Azure SDK client configuration defaults are appropriate for Azure Public Cloud (sometimes referred to as +"Azure Commercial" or simply "Microsoft Azure"). This package enables applications deployed to other +Azure Clouds to configure clients appropriately. + +This package contains predefined configuration for well-known sovereign clouds such as Azure Government and +Azure China. Azure SDK clients accept this configuration via the Cloud field of azcore.ClientOptions. For +example, configuring a credential and ARM client for Azure Government: + + opts := azcore.ClientOptions{Cloud: cloud.AzureGovernment} + cred, err := azidentity.NewDefaultAzureCredential( + &azidentity.DefaultAzureCredentialOptions{ClientOptions: opts}, + ) + handle(err) + + client, err := armsubscription.NewClient( + cred, &arm.ClientOptions{ClientOptions: opts}, + ) + handle(err) + +Applications deployed to a private cloud such as Azure Stack create a Configuration object with +appropriate values: + + c := cloud.Configuration{ + ActiveDirectoryAuthorityHost: "https://...", + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "...", + Endpoint: "https://...", + }, + }, + } + opts := azcore.ClientOptions{Cloud: c} + + cred, err := azidentity.NewDefaultAzureCredential( + &azidentity.DefaultAzureCredentialOptions{ClientOptions: opts}, + ) + handle(err) + + client, err := armsubscription.NewClient( + cred, &arm.ClientOptions{ClientOptions: opts}, + ) + handle(err) +*/ +package cloud diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/core.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/core.go new file mode 100644 index 000000000..8eef8633a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/core.go @@ -0,0 +1,154 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcore + +import ( + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +// AccessToken represents an Azure service bearer access token with expiry information. +type AccessToken = exported.AccessToken + +// TokenCredential represents a credential capable of providing an OAuth token. +type TokenCredential = exported.TokenCredential + +// KeyCredential contains an authentication key used to authenticate to an Azure service. +type KeyCredential = exported.KeyCredential + +// NewKeyCredential creates a new instance of [KeyCredential] with the specified values. +// - key is the authentication key +func NewKeyCredential(key string) *KeyCredential { + return exported.NewKeyCredential(key) +} + +// SASCredential contains a shared access signature used to authenticate to an Azure service. +type SASCredential = exported.SASCredential + +// NewSASCredential creates a new instance of [SASCredential] with the specified values. +// - sas is the shared access signature +func NewSASCredential(sas string) *SASCredential { + return exported.NewSASCredential(sas) +} + +// holds sentinel values used to send nulls +var nullables map[reflect.Type]interface{} = map[reflect.Type]interface{}{} + +// NullValue is used to send an explicit 'null' within a request. +// This is typically used in JSON-MERGE-PATCH operations to delete a value. +func NullValue[T any]() T { + t := shared.TypeOfT[T]() + v, found := nullables[t] + if !found { + var o reflect.Value + if k := t.Kind(); k == reflect.Map { + o = reflect.MakeMap(t) + } else if k == reflect.Slice { + // empty slices appear to all point to the same data block + // which causes comparisons to become ambiguous. so we create + // a slice with len/cap of one which ensures a unique address. + o = reflect.MakeSlice(t, 1, 1) + } else { + o = reflect.New(t.Elem()) + } + v = o.Interface() + nullables[t] = v + } + // return the sentinel object + return v.(T) +} + +// IsNullValue returns true if the field contains a null sentinel value. +// This is used by custom marshallers to properly encode a null value. +func IsNullValue[T any](v T) bool { + // see if our map has a sentinel object for this *T + t := reflect.TypeOf(v) + if o, found := nullables[t]; found { + o1 := reflect.ValueOf(o) + v1 := reflect.ValueOf(v) + // we found it; return true if v points to the sentinel object. + // NOTE: maps and slices can only be compared to nil, else you get + // a runtime panic. so we compare addresses instead. + return o1.Pointer() == v1.Pointer() + } + // no sentinel object for this *t + return false +} + +// ClientOptions contains optional settings for a client's pipeline. +// Instances can be shared across calls to SDK client constructors when uniform configuration is desired. +// Zero-value fields will have their specified default values applied during use. +type ClientOptions = policy.ClientOptions + +// Client is a basic HTTP client. It consists of a pipeline and tracing provider. +type Client struct { + pl runtime.Pipeline + tr tracing.Tracer + + // cached on the client to support shallow copying with new values + tp tracing.Provider + modVer string + namespace string +} + +// NewClient creates a new Client instance with the provided values. +// - moduleName - the fully qualified name of the module where the client is defined; used by the telemetry policy and tracing provider. +// - moduleVersion - the semantic version of the module; used by the telemetry policy and tracing provider. +// - plOpts - pipeline configuration options; can be the zero-value +// - options - optional client configurations; pass nil to accept the default values +func NewClient(moduleName, moduleVersion string, plOpts runtime.PipelineOptions, options *ClientOptions) (*Client, error) { + if options == nil { + options = &ClientOptions{} + } + + if !options.Telemetry.Disabled { + if err := shared.ValidateModVer(moduleVersion); err != nil { + return nil, err + } + } + + pl := runtime.NewPipeline(moduleName, moduleVersion, plOpts, options) + + tr := options.TracingProvider.NewTracer(moduleName, moduleVersion) + if tr.Enabled() && plOpts.Tracing.Namespace != "" { + tr.SetAttributes(tracing.Attribute{Key: shared.TracingNamespaceAttrName, Value: plOpts.Tracing.Namespace}) + } + + return &Client{ + pl: pl, + tr: tr, + tp: options.TracingProvider, + modVer: moduleVersion, + namespace: plOpts.Tracing.Namespace, + }, nil +} + +// Pipeline returns the pipeline for this client. +func (c *Client) Pipeline() runtime.Pipeline { + return c.pl +} + +// Tracer returns the tracer for this client. +func (c *Client) Tracer() tracing.Tracer { + return c.tr +} + +// WithClientName returns a shallow copy of the Client with its tracing client name changed to clientName. +// Note that the values for module name and version will be preserved from the source Client. +// - clientName - the fully qualified name of the client ("package.Client"); this is used by the tracing provider when creating spans +func (c *Client) WithClientName(clientName string) *Client { + tr := c.tp.NewTracer(clientName, c.modVer) + if tr.Enabled() && c.namespace != "" { + tr.SetAttributes(tracing.Attribute{Key: shared.TracingNamespaceAttrName, Value: c.namespace}) + } + return &Client{pl: c.pl, tr: tr, tp: c.tp, modVer: c.modVer, namespace: c.namespace} +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/doc.go new file mode 100644 index 000000000..654a5f404 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/doc.go @@ -0,0 +1,264 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +/* +Package azcore implements an HTTP request/response middleware pipeline used by Azure SDK clients. + +The middleware consists of three components. + + - One or more Policy instances. + - A Transporter instance. + - A Pipeline instance that combines the Policy and Transporter instances. + +# Implementing the Policy Interface + +A Policy can be implemented in two ways; as a first-class function for a stateless Policy, or as +a method on a type for a stateful Policy. Note that HTTP requests made via the same pipeline share +the same Policy instances, so if a Policy mutates its state it MUST be properly synchronized to +avoid race conditions. + +A Policy's Do method is called when an HTTP request wants to be sent over the network. The Do method can +perform any operation(s) it desires. For example, it can log the outgoing request, mutate the URL, headers, +and/or query parameters, inject a failure, etc. Once the Policy has successfully completed its request +work, it must call the Next() method on the *policy.Request instance in order to pass the request to the +next Policy in the chain. + +When an HTTP response comes back, the Policy then gets a chance to process the response/error. The Policy instance +can log the response, retry the operation if it failed due to a transient error or timeout, unmarshal the response +body, etc. Once the Policy has successfully completed its response work, it must return the *http.Response +and error instances to its caller. + +Template for implementing a stateless Policy: + + type policyFunc func(*policy.Request) (*http.Response, error) + + // Do implements the Policy interface on policyFunc. + func (pf policyFunc) Do(req *policy.Request) (*http.Response, error) { + return pf(req) + } + + func NewMyStatelessPolicy() policy.Policy { + return policyFunc(func(req *policy.Request) (*http.Response, error) { + // TODO: mutate/process Request here + + // forward Request to next Policy & get Response/error + resp, err := req.Next() + + // TODO: mutate/process Response/error here + + // return Response/error to previous Policy + return resp, err + }) + } + +Template for implementing a stateful Policy: + + type MyStatefulPolicy struct { + // TODO: add configuration/setting fields here + } + + // TODO: add initialization args to NewMyStatefulPolicy() + func NewMyStatefulPolicy() policy.Policy { + return &MyStatefulPolicy{ + // TODO: initialize configuration/setting fields here + } + } + + func (p *MyStatefulPolicy) Do(req *policy.Request) (resp *http.Response, err error) { + // TODO: mutate/process Request here + + // forward Request to next Policy & get Response/error + resp, err := req.Next() + + // TODO: mutate/process Response/error here + + // return Response/error to previous Policy + return resp, err + } + +# Implementing the Transporter Interface + +The Transporter interface is responsible for sending the HTTP request and returning the corresponding +HTTP response or error. The Transporter is invoked by the last Policy in the chain. The default Transporter +implementation uses a shared http.Client from the standard library. + +The same stateful/stateless rules for Policy implementations apply to Transporter implementations. + +# Using Policy and Transporter Instances Via a Pipeline + +To use the Policy and Transporter instances, an application passes them to the runtime.NewPipeline function. + + func NewPipeline(transport Transporter, policies ...Policy) Pipeline + +The specified Policy instances form a chain and are invoked in the order provided to NewPipeline +followed by the Transporter. + +Once the Pipeline has been created, create a runtime.Request instance and pass it to Pipeline's Do method. + + func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) + + func (p Pipeline) Do(req *Request) (*http.Request, error) + +The Pipeline.Do method sends the specified Request through the chain of Policy and Transporter +instances. The response/error is then sent through the same chain of Policy instances in reverse +order. For example, assuming there are Policy types PolicyA, PolicyB, and PolicyC along with +TransportA. + + pipeline := NewPipeline(TransportA, PolicyA, PolicyB, PolicyC) + +The flow of Request and Response looks like the following: + + policy.Request -> PolicyA -> PolicyB -> PolicyC -> TransportA -----+ + | + HTTP(S) endpoint + | + caller <--------- PolicyA <- PolicyB <- PolicyC <- http.Response-+ + +# Creating a Request Instance + +The Request instance passed to Pipeline's Do method is a wrapper around an *http.Request. It also +contains some internal state and provides various convenience methods. You create a Request instance +by calling the runtime.NewRequest function: + + func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) + +If the Request should contain a body, call the SetBody method. + + func (req *Request) SetBody(body ReadSeekCloser, contentType string) error + +A seekable stream is required so that upon retry, the retry Policy instance can seek the stream +back to the beginning before retrying the network request and re-uploading the body. + +# Sending an Explicit Null + +Operations like JSON-MERGE-PATCH send a JSON null to indicate a value should be deleted. + + { + "delete-me": null + } + +This requirement conflicts with the SDK's default marshalling that specifies "omitempty" as +a means to resolve the ambiguity between a field to be excluded and its zero-value. + + type Widget struct { + Name *string `json:",omitempty"` + Count *int `json:",omitempty"` + } + +In the above example, Name and Count are defined as pointer-to-type to disambiguate between +a missing value (nil) and a zero-value (0) which might have semantic differences. + +In a PATCH operation, any fields left as nil are to have their values preserved. When updating +a Widget's count, one simply specifies the new value for Count, leaving Name nil. + +To fulfill the requirement for sending a JSON null, the NullValue() function can be used. + + w := Widget{ + Count: azcore.NullValue[*int](), + } + +This sends an explict "null" for Count, indicating that any current value for Count should be deleted. + +# Processing the Response + +When the HTTP response is received, the *http.Response is returned directly. Each Policy instance +can inspect/mutate the *http.Response. + +# Built-in Logging + +To enable logging, set environment variable AZURE_SDK_GO_LOGGING to "all" before executing your program. + +By default the logger writes to stderr. This can be customized by calling log.SetListener, providing +a callback that writes to the desired location. Any custom logging implementation MUST provide its +own synchronization to handle concurrent invocations. + +See the docs for the log package for further details. + +# Pageable Operations + +Pageable operations return potentially large data sets spread over multiple GET requests. The result of +each GET is a "page" of data consisting of a slice of items. + +Pageable operations can be identified by their New*Pager naming convention and return type of *runtime.Pager[T]. + + func (c *WidgetClient) NewListWidgetsPager(o *Options) *runtime.Pager[PageResponse] + +The call to WidgetClient.NewListWidgetsPager() returns an instance of *runtime.Pager[T] for fetching pages +and determining if there are more pages to fetch. No IO calls are made until the NextPage() method is invoked. + + pager := widgetClient.NewListWidgetsPager(nil) + for pager.More() { + page, err := pager.NextPage(context.TODO()) + // handle err + for _, widget := range page.Values { + // process widget + } + } + +# Long-Running Operations + +Long-running operations (LROs) are operations consisting of an initial request to start the operation followed +by polling to determine when the operation has reached a terminal state. An LRO's terminal state is one +of the following values. + + - Succeeded - the LRO completed successfully + - Failed - the LRO failed to complete + - Canceled - the LRO was canceled + +LROs can be identified by their Begin* prefix and their return type of *runtime.Poller[T]. + + func (c *WidgetClient) BeginCreateOrUpdate(ctx context.Context, w Widget, o *Options) (*runtime.Poller[Response], error) + +When a call to WidgetClient.BeginCreateOrUpdate() returns a nil error, it means that the LRO has started. +It does _not_ mean that the widget has been created or updated (or failed to be created/updated). + +The *runtime.Poller[T] provides APIs for determining the state of the LRO. To wait for the LRO to complete, +call the PollUntilDone() method. + + poller, err := widgetClient.BeginCreateOrUpdate(context.TODO(), Widget{}, nil) + // handle err + result, err := poller.PollUntilDone(context.TODO(), nil) + // handle err + // use result + +The call to PollUntilDone() will block the current goroutine until the LRO has reached a terminal state or the +context is canceled/timed out. + +Note that LROs can take anywhere from several seconds to several minutes. The duration is operation-dependent. Due to +this variant behavior, pollers do _not_ have a preconfigured time-out. Use a context with the appropriate cancellation +mechanism as required. + +# Resume Tokens + +Pollers provide the ability to serialize their state into a "resume token" which can be used by another process to +recreate the poller. This is achieved via the runtime.Poller[T].ResumeToken() method. + + token, err := poller.ResumeToken() + // handle error + +Note that a token can only be obtained for a poller that's in a non-terminal state. Also note that any subsequent calls +to poller.Poll() might change the poller's state. In this case, a new token should be created. + +After the token has been obtained, it can be used to recreate an instance of the originating poller. + + poller, err := widgetClient.BeginCreateOrUpdate(nil, Widget{}, &Options{ + ResumeToken: token, + }) + +When resuming a poller, no IO is performed, and zero-value arguments can be used for everything but the Options.ResumeToken. + +Resume tokens are unique per service client and operation. Attempting to resume a poller for LRO BeginB() with a token from LRO +BeginA() will result in an error. + +# 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. +*/ +package azcore diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/errors.go new file mode 100644 index 000000000..17bd50c67 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/errors.go @@ -0,0 +1,14 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcore + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + +// ResponseError is returned when a request is made to a service and +// the service returns a non-success HTTP status code. +// Use errors.As() to access this type in the error chain. +type ResponseError = exported.ResponseError diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/etag.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/etag.go new file mode 100644 index 000000000..23ea7e7c8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/etag.go @@ -0,0 +1,48 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcore + +import ( + "strings" +) + +// ETag is a property used for optimistic concurrency during updates +// ETag is a validator based on https://tools.ietf.org/html/rfc7232#section-2.3.2 +// An ETag can be empty (""). +type ETag string + +// ETagAny is an ETag that represents everything, the value is "*" +const ETagAny ETag = "*" + +// Equals does a strong comparison of two ETags. Equals returns true when both +// ETags are not weak and the values of the underlying strings are equal. +func (e ETag) Equals(other ETag) bool { + return !e.IsWeak() && !other.IsWeak() && e == other +} + +// WeakEquals does a weak comparison of two ETags. Two ETags are equivalent if their opaque-tags match +// character-by-character, regardless of either or both being tagged as "weak". +func (e ETag) WeakEquals(other ETag) bool { + getStart := func(e1 ETag) int { + if e1.IsWeak() { + return 2 + } + return 0 + } + aStart := getStart(e) + bStart := getStart(other) + + aVal := e[aStart:] + bVal := other[bStart:] + + return aVal == bVal +} + +// IsWeak specifies whether the ETag is strong or weak. +func (e ETag) IsWeak() bool { + return len(e) >= 4 && strings.HasPrefix(string(e), "W/\"") && strings.HasSuffix(string(e), "\"") +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go new file mode 100644 index 000000000..f2b296b6d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go @@ -0,0 +1,175 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "context" + "encoding/base64" + "fmt" + "io" + "net/http" + "sync/atomic" + "time" +) + +type nopCloser struct { + io.ReadSeeker +} + +func (n nopCloser) Close() error { + return nil +} + +// NopCloser returns a ReadSeekCloser with a no-op close method wrapping the provided io.ReadSeeker. +// Exported as streaming.NopCloser(). +func NopCloser(rs io.ReadSeeker) io.ReadSeekCloser { + return nopCloser{rs} +} + +// HasStatusCode returns true if the Response's status code is one of the specified values. +// Exported as runtime.HasStatusCode(). +func HasStatusCode(resp *http.Response, statusCodes ...int) bool { + if resp == nil { + return false + } + for _, sc := range statusCodes { + if resp.StatusCode == sc { + return true + } + } + return false +} + +// AccessToken represents an Azure service bearer access token with expiry information. +// Exported as azcore.AccessToken. +type AccessToken struct { + Token string + ExpiresOn time.Time +} + +// TokenRequestOptions contain specific parameter that may be used by credentials types when attempting to get a token. +// Exported as policy.TokenRequestOptions. +type TokenRequestOptions struct { + // Claims are any additional claims required for the token to satisfy a conditional access policy, such as a + // service may return in a claims challenge following an authorization failure. If a service returned the + // claims value base64 encoded, it must be decoded before setting this field. + Claims string + + // EnableCAE indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. When true, + // azidentity credentials request CAE tokens for resource APIs supporting CAE. Clients are responsible for + // handling CAE challenges. If a client that doesn't handle CAE challenges receives a CAE token, it may end up + // in a loop retrying an API call with a token that has been revoked due to CAE. + EnableCAE bool + + // Scopes contains the list of permission scopes required for the token. + Scopes []string + + // TenantID identifies the tenant from which to request the token. azidentity credentials authenticate in + // their configured default tenants when this field isn't set. + TenantID string +} + +// TokenCredential represents a credential capable of providing an OAuth token. +// Exported as azcore.TokenCredential. +type TokenCredential interface { + // GetToken requests an access token for the specified set of scopes. + GetToken(ctx context.Context, options TokenRequestOptions) (AccessToken, error) +} + +// DecodeByteArray will base-64 decode the provided string into v. +// Exported as runtime.DecodeByteArray() +func DecodeByteArray(s string, v *[]byte, format Base64Encoding) error { + if len(s) == 0 { + return nil + } + payload := string(s) + if payload[0] == '"' { + // remove surrounding quotes + payload = payload[1 : len(payload)-1] + } + switch format { + case Base64StdFormat: + decoded, err := base64.StdEncoding.DecodeString(payload) + if err == nil { + *v = decoded + return nil + } + return err + case Base64URLFormat: + // use raw encoding as URL format should not contain any '=' characters + decoded, err := base64.RawURLEncoding.DecodeString(payload) + if err == nil { + *v = decoded + return nil + } + return err + default: + return fmt.Errorf("unrecognized byte array format: %d", format) + } +} + +// KeyCredential contains an authentication key used to authenticate to an Azure service. +// Exported as azcore.KeyCredential. +type KeyCredential struct { + cred *keyCredential +} + +// NewKeyCredential creates a new instance of [KeyCredential] with the specified values. +// - key is the authentication key +func NewKeyCredential(key string) *KeyCredential { + return &KeyCredential{cred: newKeyCredential(key)} +} + +// Update replaces the existing key with the specified value. +func (k *KeyCredential) Update(key string) { + k.cred.Update(key) +} + +// SASCredential contains a shared access signature used to authenticate to an Azure service. +// Exported as azcore.SASCredential. +type SASCredential struct { + cred *keyCredential +} + +// NewSASCredential creates a new instance of [SASCredential] with the specified values. +// - sas is the shared access signature +func NewSASCredential(sas string) *SASCredential { + return &SASCredential{cred: newKeyCredential(sas)} +} + +// Update replaces the existing shared access signature with the specified value. +func (k *SASCredential) Update(sas string) { + k.cred.Update(sas) +} + +// KeyCredentialGet returns the key for cred. +func KeyCredentialGet(cred *KeyCredential) string { + return cred.cred.Get() +} + +// SASCredentialGet returns the shared access sig for cred. +func SASCredentialGet(cred *SASCredential) string { + return cred.cred.Get() +} + +type keyCredential struct { + key atomic.Value // string +} + +func newKeyCredential(key string) *keyCredential { + keyCred := keyCredential{} + keyCred.key.Store(key) + return &keyCred +} + +func (k *keyCredential) Get() string { + return k.key.Load().(string) +} + +func (k *keyCredential) Update(key string) { + k.key.Store(key) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/pipeline.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/pipeline.go new file mode 100644 index 000000000..e45f831ed --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/pipeline.go @@ -0,0 +1,77 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "errors" + "net/http" +) + +// Policy represents an extensibility point for the Pipeline that can mutate the specified +// Request and react to the received Response. +// Exported as policy.Policy. +type Policy interface { + // Do applies the policy to the specified Request. When implementing a Policy, mutate the + // request before calling req.Next() to move on to the next policy, and respond to the result + // before returning to the caller. + Do(req *Request) (*http.Response, error) +} + +// Pipeline represents a primitive for sending HTTP requests and receiving responses. +// Its behavior can be extended by specifying policies during construction. +// Exported as runtime.Pipeline. +type Pipeline struct { + policies []Policy +} + +// Transporter represents an HTTP pipeline transport used to send HTTP requests and receive responses. +// Exported as policy.Transporter. +type Transporter interface { + // Do sends the HTTP request and returns the HTTP response or error. + Do(req *http.Request) (*http.Response, error) +} + +// used to adapt a TransportPolicy to a Policy +type transportPolicy struct { + trans Transporter +} + +func (tp transportPolicy) Do(req *Request) (*http.Response, error) { + if tp.trans == nil { + return nil, errors.New("missing transporter") + } + resp, err := tp.trans.Do(req.Raw()) + if err != nil { + return nil, err + } else if resp == nil { + // there was no response and no error (rare but can happen) + // this ensures the retry policy will retry the request + return nil, errors.New("received nil response") + } + return resp, nil +} + +// NewPipeline creates a new Pipeline object from the specified Policies. +// Not directly exported, but used as part of runtime.NewPipeline(). +func NewPipeline(transport Transporter, policies ...Policy) Pipeline { + // transport policy must always be the last in the slice + policies = append(policies, transportPolicy{trans: transport}) + return Pipeline{ + policies: policies, + } +} + +// Do is called for each and every HTTP request. It passes the request through all +// the Policy objects (which can transform the Request's URL/query parameters/headers) +// and ultimately sends the transformed HTTP request over the network. +func (p Pipeline) Do(req *Request) (*http.Response, error) { + if req == nil { + return nil, errors.New("request cannot be nil") + } + req.policies = p.policies + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go new file mode 100644 index 000000000..659f2a7d2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go @@ -0,0 +1,213 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "net/http" + "reflect" + "strconv" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// Base64Encoding is usesd to specify which base-64 encoder/decoder to use when +// encoding/decoding a slice of bytes to/from a string. +// Exported as runtime.Base64Encoding +type Base64Encoding int + +const ( + // Base64StdFormat uses base64.StdEncoding for encoding and decoding payloads. + Base64StdFormat Base64Encoding = 0 + + // Base64URLFormat uses base64.RawURLEncoding for encoding and decoding payloads. + Base64URLFormat Base64Encoding = 1 +) + +// EncodeByteArray will base-64 encode the byte slice v. +// Exported as runtime.EncodeByteArray() +func EncodeByteArray(v []byte, format Base64Encoding) string { + if format == Base64URLFormat { + return base64.RawURLEncoding.EncodeToString(v) + } + return base64.StdEncoding.EncodeToString(v) +} + +// Request is an abstraction over the creation of an HTTP request as it passes through the pipeline. +// Don't use this type directly, use NewRequest() instead. +// Exported as policy.Request. +type Request struct { + req *http.Request + body io.ReadSeekCloser + policies []Policy + values opValues +} + +type opValues map[reflect.Type]interface{} + +// Set adds/changes a value +func (ov opValues) set(value interface{}) { + ov[reflect.TypeOf(value)] = value +} + +// Get looks for a value set by SetValue first +func (ov opValues) get(value interface{}) bool { + v, ok := ov[reflect.ValueOf(value).Elem().Type()] + if ok { + reflect.ValueOf(value).Elem().Set(reflect.ValueOf(v)) + } + return ok +} + +// NewRequest creates a new Request with the specified input. +// Exported as runtime.NewRequest(). +func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) { + req, err := http.NewRequestWithContext(ctx, httpMethod, endpoint, nil) + if err != nil { + return nil, err + } + if req.URL.Host == "" { + return nil, errors.New("no Host in request URL") + } + if !(req.URL.Scheme == "http" || req.URL.Scheme == "https") { + return nil, fmt.Errorf("unsupported protocol scheme %s", req.URL.Scheme) + } + return &Request{req: req}, nil +} + +// Body returns the original body specified when the Request was created. +func (req *Request) Body() io.ReadSeekCloser { + return req.body +} + +// Raw returns the underlying HTTP request. +func (req *Request) Raw() *http.Request { + return req.req +} + +// Next calls the next policy in the pipeline. +// If there are no more policies, nil and an error are returned. +// This method is intended to be called from pipeline policies. +// To send a request through a pipeline call Pipeline.Do(). +func (req *Request) Next() (*http.Response, error) { + if len(req.policies) == 0 { + return nil, errors.New("no more policies") + } + nextPolicy := req.policies[0] + nextReq := *req + nextReq.policies = nextReq.policies[1:] + return nextPolicy.Do(&nextReq) +} + +// SetOperationValue adds/changes a mutable key/value associated with a single operation. +func (req *Request) SetOperationValue(value interface{}) { + if req.values == nil { + req.values = opValues{} + } + req.values.set(value) +} + +// OperationValue looks for a value set by SetOperationValue(). +func (req *Request) OperationValue(value interface{}) bool { + if req.values == nil { + return false + } + return req.values.get(value) +} + +// SetBody sets the specified ReadSeekCloser as the HTTP request body, and sets Content-Type and Content-Length +// accordingly. If the ReadSeekCloser is nil or empty, Content-Length won't be set. If contentType is "", +// Content-Type won't be set. +// Use streaming.NopCloser to turn an io.ReadSeeker into an io.ReadSeekCloser. +func (req *Request) SetBody(body io.ReadSeekCloser, contentType string) error { + var err error + var size int64 + if body != nil { + size, err = body.Seek(0, io.SeekEnd) // Seek to the end to get the stream's size + if err != nil { + return err + } + } + if size == 0 { + // treat an empty stream the same as a nil one: assign req a nil body + body = nil + // RFC 9110 specifies a client shouldn't set Content-Length on a request containing no content + // (Del is a no-op when the header has no value) + req.req.Header.Del(shared.HeaderContentLength) + } else { + _, err = body.Seek(0, io.SeekStart) + if err != nil { + return err + } + req.req.Header.Set(shared.HeaderContentLength, strconv.FormatInt(size, 10)) + req.Raw().GetBody = func() (io.ReadCloser, error) { + _, err := body.Seek(0, io.SeekStart) // Seek back to the beginning of the stream + return body, err + } + } + // keep a copy of the body argument. this is to handle cases + // where req.Body is replaced, e.g. httputil.DumpRequest and friends. + req.body = body + req.req.Body = body + req.req.ContentLength = size + if contentType == "" { + // Del is a no-op when the header has no value + req.req.Header.Del(shared.HeaderContentType) + } else { + req.req.Header.Set(shared.HeaderContentType, contentType) + } + return nil +} + +// RewindBody seeks the request's Body stream back to the beginning so it can be resent when retrying an operation. +func (req *Request) RewindBody() error { + if req.body != nil { + // Reset the stream back to the beginning and restore the body + _, err := req.body.Seek(0, io.SeekStart) + req.req.Body = req.body + return err + } + return nil +} + +// Close closes the request body. +func (req *Request) Close() error { + if req.body == nil { + return nil + } + return req.body.Close() +} + +// Clone returns a deep copy of the request with its context changed to ctx. +func (req *Request) Clone(ctx context.Context) *Request { + r2 := *req + r2.req = req.req.Clone(ctx) + return &r2 +} + +// WithContext returns a shallow copy of the request with its context changed to ctx. +func (req *Request) WithContext(ctx context.Context) *Request { + r2 := new(Request) + *r2 = *req + r2.req = r2.req.WithContext(ctx) + return r2 +} + +// not exported but dependent on Request + +// PolicyFunc is a type that implements the Policy interface. +// Use this type when implementing a stateless policy as a first-class function. +type PolicyFunc func(*Request) (*http.Response, error) + +// Do implements the Policy interface on policyFunc. +func (pf PolicyFunc) Do(req *Request) (*http.Response, error) { + return pf(req) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/response_error.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/response_error.go new file mode 100644 index 000000000..f24355288 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/response_error.go @@ -0,0 +1,157 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "regexp" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/internal/exported" +) + +// NewResponseError creates a new *ResponseError from the provided HTTP response. +// Exported as runtime.NewResponseError(). +func NewResponseError(resp *http.Response) error { + respErr := &ResponseError{ + StatusCode: resp.StatusCode, + RawResponse: resp, + } + + // prefer the error code in the response header + if ec := resp.Header.Get(shared.HeaderXMSErrorCode); ec != "" { + respErr.ErrorCode = ec + return respErr + } + + // if we didn't get x-ms-error-code, check in the response body + body, err := exported.Payload(resp, nil) + if err != nil { + return err + } + + if len(body) > 0 { + if code := extractErrorCodeJSON(body); code != "" { + respErr.ErrorCode = code + } else if code := extractErrorCodeXML(body); code != "" { + respErr.ErrorCode = code + } + } + + return respErr +} + +func extractErrorCodeJSON(body []byte) string { + var rawObj map[string]interface{} + if err := json.Unmarshal(body, &rawObj); err != nil { + // not a JSON object + return "" + } + + // check if this is a wrapped error, i.e. { "error": { ... } } + // if so then unwrap it + if wrapped, ok := rawObj["error"]; ok { + unwrapped, ok := wrapped.(map[string]interface{}) + if !ok { + return "" + } + rawObj = unwrapped + } else if wrapped, ok := rawObj["odata.error"]; ok { + // check if this a wrapped odata error, i.e. { "odata.error": { ... } } + unwrapped, ok := wrapped.(map[string]any) + if !ok { + return "" + } + rawObj = unwrapped + } + + // now check for the error code + code, ok := rawObj["code"] + if !ok { + return "" + } + codeStr, ok := code.(string) + if !ok { + return "" + } + return codeStr +} + +func extractErrorCodeXML(body []byte) string { + // regular expression is much easier than dealing with the XML parser + rx := regexp.MustCompile(`<(?:\w+:)?[c|C]ode>\s*(\w+)\s*<\/(?:\w+:)?[c|C]ode>`) + res := rx.FindStringSubmatch(string(body)) + if len(res) != 2 { + return "" + } + // first submatch is the entire thing, second one is the captured error code + return res[1] +} + +// ResponseError is returned when a request is made to a service and +// the service returns a non-success HTTP status code. +// Use errors.As() to access this type in the error chain. +// Exported as azcore.ResponseError. +type ResponseError struct { + // ErrorCode is the error code returned by the resource provider if available. + ErrorCode string + + // StatusCode is the HTTP status code as defined in https://pkg.go.dev/net/http#pkg-constants. + StatusCode int + + // RawResponse is the underlying HTTP response. + RawResponse *http.Response +} + +// Error implements the error interface for type ResponseError. +// Note that the message contents are not contractual and can change over time. +func (e *ResponseError) Error() string { + const separator = "--------------------------------------------------------------------------------" + // write the request method and URL with response status code + msg := &bytes.Buffer{} + if e.RawResponse != nil { + if e.RawResponse.Request != nil { + fmt.Fprintf(msg, "%s %s://%s%s\n", e.RawResponse.Request.Method, e.RawResponse.Request.URL.Scheme, e.RawResponse.Request.URL.Host, e.RawResponse.Request.URL.Path) + } else { + fmt.Fprintln(msg, "Request information not available") + } + fmt.Fprintln(msg, separator) + fmt.Fprintf(msg, "RESPONSE %d: %s\n", e.RawResponse.StatusCode, e.RawResponse.Status) + } else { + fmt.Fprintln(msg, "Missing RawResponse") + fmt.Fprintln(msg, separator) + } + if e.ErrorCode != "" { + fmt.Fprintf(msg, "ERROR CODE: %s\n", e.ErrorCode) + } else { + fmt.Fprintln(msg, "ERROR CODE UNAVAILABLE") + } + if e.RawResponse != nil { + fmt.Fprintln(msg, separator) + body, err := exported.Payload(e.RawResponse, nil) + if err != nil { + // this really shouldn't fail at this point as the response + // body is already cached (it was read in NewResponseError) + fmt.Fprintf(msg, "Error reading response body: %v", err) + } else if len(body) > 0 { + if err := json.Indent(msg, body, "", " "); err != nil { + // failed to pretty-print so just dump it verbatim + fmt.Fprint(msg, string(body)) + } + // the standard library doesn't have a pretty-printer for XML + fmt.Fprintln(msg) + } else { + fmt.Fprintln(msg, "Response contained no body") + } + } + fmt.Fprintln(msg, separator) + + return msg.String() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log/log.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log/log.go new file mode 100644 index 000000000..0684cb317 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log/log.go @@ -0,0 +1,38 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// This is an internal helper package to combine the complete logging APIs. +package log + +import ( + azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +type Event = log.Event + +const ( + EventRequest = azlog.EventRequest + EventResponse = azlog.EventResponse + EventRetryPolicy = azlog.EventRetryPolicy + EventLRO = azlog.EventLRO +) + +func Write(cls log.Event, msg string) { + log.Write(cls, msg) +} + +func Writef(cls log.Event, format string, a ...interface{}) { + log.Writef(cls, format, a...) +} + +func SetListener(lst func(Event, string)) { + log.SetListener(lst) +} + +func Should(cls log.Event) bool { + return log.Should(cls) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async/async.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async/async.go new file mode 100644 index 000000000..b05bd8b38 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async/async.go @@ -0,0 +1,159 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package async + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/internal/poller" +) + +// see https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md + +// Applicable returns true if the LRO is using Azure-AsyncOperation. +func Applicable(resp *http.Response) bool { + return resp.Header.Get(shared.HeaderAzureAsync) != "" +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + _, ok := token["asyncURL"] + return ok +} + +// Poller is an LRO poller that uses the Azure-AsyncOperation pattern. +type Poller[T any] struct { + pl exported.Pipeline + + resp *http.Response + + // The URL from Azure-AsyncOperation header. + AsyncURL string `json:"asyncURL"` + + // The URL from Location header. + LocURL string `json:"locURL"` + + // The URL from the initial LRO request. + OrigURL string `json:"origURL"` + + // The HTTP method from the initial LRO request. + Method string `json:"method"` + + // The value of final-state-via from swagger, can be the empty string. + FinalState pollers.FinalStateVia `json:"finalState"` + + // The LRO's current state. + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response and final-state type. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response, finalState pollers.FinalStateVia) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Azure-AsyncOperation poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Azure-AsyncOperation poller.") + asyncURL := resp.Header.Get(shared.HeaderAzureAsync) + if asyncURL == "" { + return nil, errors.New("response is missing Azure-AsyncOperation header") + } + if !poller.IsValidURL(asyncURL) { + return nil, fmt.Errorf("invalid polling URL %s", asyncURL) + } + // check for provisioning state. if the operation is a RELO + // and terminates synchronously this will prevent extra polling. + // it's ok if there's no provisioning state. + state, _ := poller.GetProvisioningState(resp) + if state == "" { + state = poller.StatusInProgress + } + p := &Poller[T]{ + pl: pl, + resp: resp, + AsyncURL: asyncURL, + LocURL: resp.Header.Get(shared.HeaderLocation), + OrigURL: resp.Request.URL.String(), + Method: resp.Request.Method, + FinalState: finalState, + CurState: state, + } + return p, nil +} + +// Done returns true if the LRO is in a terminal state. +func (p *Poller[T]) Done() bool { + return poller.IsTerminalState(p.CurState) +} + +// Poll retrieves the current state of the LRO. +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.AsyncURL, p.pl, func(resp *http.Response) (string, error) { + if !poller.StatusCodeValid(resp) { + p.resp = resp + return "", exported.NewResponseError(resp) + } + state, err := poller.GetStatus(resp) + if err != nil { + return "", err + } else if state == "" { + return "", errors.New("the response did not contain a status") + } + p.resp = resp + p.CurState = state + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + if p.resp.StatusCode == http.StatusNoContent { + return nil + } else if poller.Failed(p.CurState) { + return exported.NewResponseError(p.resp) + } + var req *exported.Request + var err error + if p.Method == http.MethodPatch || p.Method == http.MethodPut { + // for PATCH and PUT, the final GET is on the original resource URL + req, err = exported.NewRequest(ctx, http.MethodGet, p.OrigURL) + } else if p.Method == http.MethodPost { + if p.FinalState == pollers.FinalStateViaAzureAsyncOp { + // no final GET required + } else if p.FinalState == pollers.FinalStateViaOriginalURI { + req, err = exported.NewRequest(ctx, http.MethodGet, p.OrigURL) + } else if p.LocURL != "" { + // ideally FinalState would be set to "location" but it isn't always. + // must check last due to more permissive condition. + req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL) + } + } + if err != nil { + return err + } + + // if a final GET request has been created, execute it + if req != nil { + resp, err := p.pl.Do(req) + if err != nil { + return err + } + p.resp = resp + } + + return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body/body.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body/body.go new file mode 100644 index 000000000..2bb9e105b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body/body.go @@ -0,0 +1,135 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package body + +import ( + "context" + "errors" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/internal/poller" +) + +// Kind is the identifier of this type in a resume token. +const kind = "body" + +// Applicable returns true if the LRO is using no headers, just provisioning state. +// This is only applicable to PATCH and PUT methods and assumes no polling headers. +func Applicable(resp *http.Response) bool { + // we can't check for absense of headers due to some misbehaving services + // like redis that return a Location header but don't actually use that protocol + return resp.Request.Method == http.MethodPatch || resp.Request.Method == http.MethodPut +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + t, ok := token["type"] + if !ok { + return false + } + tt, ok := t.(string) + if !ok { + return false + } + return tt == kind +} + +// Poller is an LRO poller that uses the Body pattern. +type Poller[T any] struct { + pl exported.Pipeline + + resp *http.Response + + // The poller's type, used for resume token processing. + Type string `json:"type"` + + // The URL for polling. + PollURL string `json:"pollURL"` + + // The LRO's current state. + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Body poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Body poller.") + p := &Poller[T]{ + pl: pl, + resp: resp, + Type: kind, + PollURL: resp.Request.URL.String(), + } + // default initial state to InProgress. depending on the HTTP + // status code and provisioning state, we might change the value. + curState := poller.StatusInProgress + provState, err := poller.GetProvisioningState(resp) + if err != nil && !errors.Is(err, poller.ErrNoBody) { + return nil, err + } + if resp.StatusCode == http.StatusCreated && provState != "" { + // absense of provisioning state is ok for a 201, means the operation is in progress + curState = provState + } else if resp.StatusCode == http.StatusOK { + if provState != "" { + curState = provState + } else if provState == "" { + // for a 200, absense of provisioning state indicates success + curState = poller.StatusSucceeded + } + } else if resp.StatusCode == http.StatusNoContent { + curState = poller.StatusSucceeded + } + p.CurState = curState + return p, nil +} + +func (p *Poller[T]) Done() bool { + return poller.IsTerminalState(p.CurState) +} + +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.PollURL, p.pl, func(resp *http.Response) (string, error) { + if !poller.StatusCodeValid(resp) { + p.resp = resp + return "", exported.NewResponseError(resp) + } + if resp.StatusCode == http.StatusNoContent { + p.resp = resp + p.CurState = poller.StatusSucceeded + return p.CurState, nil + } + state, err := poller.GetProvisioningState(resp) + if errors.Is(err, poller.ErrNoBody) { + // a missing response body in non-204 case is an error + return "", err + } else if state == "" { + // a response body without provisioning state is considered terminal success + state = poller.StatusSucceeded + } else if err != nil { + return "", err + } + p.resp = resp + p.CurState = state + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/fake/fake.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/fake/fake.go new file mode 100644 index 000000000..259834718 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/fake/fake.go @@ -0,0 +1,133 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package fake + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/internal/poller" +) + +// Applicable returns true if the LRO is a fake. +func Applicable(resp *http.Response) bool { + return resp.Header.Get(shared.HeaderFakePollerStatus) != "" +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + _, ok := token["fakeURL"] + return ok +} + +// Poller is an LRO poller that uses the Core-Fake-Poller pattern. +type Poller[T any] struct { + pl exported.Pipeline + + resp *http.Response + + // The API name from CtxAPINameKey + APIName string `json:"apiName"` + + // The URL from Core-Fake-Poller header. + FakeURL string `json:"fakeURL"` + + // The LRO's current state. + FakeStatus string `json:"status"` +} + +// lroStatusURLSuffix is the URL path suffix for a faked LRO. +const lroStatusURLSuffix = "/get/fake/status" + +// New creates a new Poller from the provided initial response. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Core-Fake-Poller poller.") + return &Poller[T]{pl: pl}, nil + } + + log.Write(log.EventLRO, "Using Core-Fake-Poller poller.") + fakeStatus := resp.Header.Get(shared.HeaderFakePollerStatus) + if fakeStatus == "" { + return nil, errors.New("response is missing Fake-Poller-Status header") + } + + ctxVal := resp.Request.Context().Value(shared.CtxAPINameKey{}) + if ctxVal == nil { + return nil, errors.New("missing value for CtxAPINameKey") + } + + apiName, ok := ctxVal.(string) + if !ok { + return nil, fmt.Errorf("expected string for CtxAPINameKey, the type was %T", ctxVal) + } + + qp := "" + if resp.Request.URL.RawQuery != "" { + qp = "?" + resp.Request.URL.RawQuery + } + + p := &Poller[T]{ + pl: pl, + resp: resp, + APIName: apiName, + // NOTE: any changes to this path format MUST be reflected in SanitizePollerPath() + FakeURL: fmt.Sprintf("%s://%s%s%s%s", resp.Request.URL.Scheme, resp.Request.URL.Host, resp.Request.URL.Path, lroStatusURLSuffix, qp), + FakeStatus: fakeStatus, + } + return p, nil +} + +// Done returns true if the LRO is in a terminal state. +func (p *Poller[T]) Done() bool { + return poller.IsTerminalState(p.FakeStatus) +} + +// Poll retrieves the current state of the LRO. +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + ctx = context.WithValue(ctx, shared.CtxAPINameKey{}, p.APIName) + err := pollers.PollHelper(ctx, p.FakeURL, p.pl, func(resp *http.Response) (string, error) { + if !poller.StatusCodeValid(resp) { + p.resp = resp + return "", exported.NewResponseError(resp) + } + fakeStatus := resp.Header.Get(shared.HeaderFakePollerStatus) + if fakeStatus == "" { + return "", errors.New("response is missing Fake-Poller-Status header") + } + p.resp = resp + p.FakeStatus = fakeStatus + return p.FakeStatus, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + if p.resp.StatusCode == http.StatusNoContent { + return nil + } else if poller.Failed(p.FakeStatus) { + return exported.NewResponseError(p.resp) + } + + return pollers.ResultHelper(p.resp, poller.Failed(p.FakeStatus), out) +} + +// SanitizePollerPath removes any fake-appended suffix from a URL's path. +func SanitizePollerPath(path string) string { + return strings.TrimSuffix(path, lroStatusURLSuffix) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc/loc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc/loc.go new file mode 100644 index 000000000..d6be89876 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc/loc.go @@ -0,0 +1,119 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package loc + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/internal/poller" +) + +// Kind is the identifier of this type in a resume token. +const kind = "loc" + +// Applicable returns true if the LRO is using Location. +func Applicable(resp *http.Response) bool { + return resp.Header.Get(shared.HeaderLocation) != "" +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + t, ok := token["type"] + if !ok { + return false + } + tt, ok := t.(string) + if !ok { + return false + } + return tt == kind +} + +// Poller is an LRO poller that uses the Location pattern. +type Poller[T any] struct { + pl exported.Pipeline + resp *http.Response + + Type string `json:"type"` + PollURL string `json:"pollURL"` + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Location poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Location poller.") + locURL := resp.Header.Get(shared.HeaderLocation) + if locURL == "" { + return nil, errors.New("response is missing Location header") + } + if !poller.IsValidURL(locURL) { + return nil, fmt.Errorf("invalid polling URL %s", locURL) + } + // check for provisioning state. if the operation is a RELO + // and terminates synchronously this will prevent extra polling. + // it's ok if there's no provisioning state. + state, _ := poller.GetProvisioningState(resp) + if state == "" { + state = poller.StatusInProgress + } + return &Poller[T]{ + pl: pl, + resp: resp, + Type: kind, + PollURL: locURL, + CurState: state, + }, nil +} + +func (p *Poller[T]) Done() bool { + return poller.IsTerminalState(p.CurState) +} + +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.PollURL, p.pl, func(resp *http.Response) (string, error) { + // location polling can return an updated polling URL + if h := resp.Header.Get(shared.HeaderLocation); h != "" { + p.PollURL = h + } + // if provisioning state is available, use that. this is only + // for some ARM LRO scenarios (e.g. DELETE with a Location header) + // so if it's missing then use HTTP status code. + provState, _ := poller.GetProvisioningState(resp) + p.resp = resp + if provState != "" { + p.CurState = provState + } else if resp.StatusCode == http.StatusAccepted { + p.CurState = poller.StatusInProgress + } else if resp.StatusCode > 199 && resp.StatusCode < 300 { + // any 2xx other than a 202 indicates success + p.CurState = poller.StatusSucceeded + } else { + p.CurState = poller.StatusFailed + } + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op/op.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op/op.go new file mode 100644 index 000000000..1bc7ad0ac --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op/op.go @@ -0,0 +1,145 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package op + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/internal/poller" +) + +// Applicable returns true if the LRO is using Operation-Location. +func Applicable(resp *http.Response) bool { + return resp.Header.Get(shared.HeaderOperationLocation) != "" +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + _, ok := token["oplocURL"] + return ok +} + +// Poller is an LRO poller that uses the Operation-Location pattern. +type Poller[T any] struct { + pl exported.Pipeline + resp *http.Response + + OpLocURL string `json:"oplocURL"` + LocURL string `json:"locURL"` + OrigURL string `json:"origURL"` + Method string `json:"method"` + FinalState pollers.FinalStateVia `json:"finalState"` + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response, finalState pollers.FinalStateVia) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Operation-Location poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Operation-Location poller.") + opURL := resp.Header.Get(shared.HeaderOperationLocation) + if opURL == "" { + return nil, errors.New("response is missing Operation-Location header") + } + if !poller.IsValidURL(opURL) { + return nil, fmt.Errorf("invalid Operation-Location URL %s", opURL) + } + locURL := resp.Header.Get(shared.HeaderLocation) + // Location header is optional + if locURL != "" && !poller.IsValidURL(locURL) { + return nil, fmt.Errorf("invalid Location URL %s", locURL) + } + // default initial state to InProgress. if the + // service sent us a status then use that instead. + curState := poller.StatusInProgress + status, err := poller.GetStatus(resp) + if err != nil && !errors.Is(err, poller.ErrNoBody) { + return nil, err + } + if status != "" { + curState = status + } + + return &Poller[T]{ + pl: pl, + resp: resp, + OpLocURL: opURL, + LocURL: locURL, + OrigURL: resp.Request.URL.String(), + Method: resp.Request.Method, + FinalState: finalState, + CurState: curState, + }, nil +} + +func (p *Poller[T]) Done() bool { + return poller.IsTerminalState(p.CurState) +} + +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.OpLocURL, p.pl, func(resp *http.Response) (string, error) { + if !poller.StatusCodeValid(resp) { + p.resp = resp + return "", exported.NewResponseError(resp) + } + state, err := poller.GetStatus(resp) + if err != nil { + return "", err + } else if state == "" { + return "", errors.New("the response did not contain a status") + } + p.resp = resp + p.CurState = state + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + var req *exported.Request + var err error + if p.FinalState == pollers.FinalStateViaLocation && p.LocURL != "" { + req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL) + } else if p.FinalState == pollers.FinalStateViaOpLocation && p.Method == http.MethodPost { + // no final GET required, terminal response should have it + } else if rl, rlErr := poller.GetResourceLocation(p.resp); rlErr != nil && !errors.Is(rlErr, poller.ErrNoBody) { + return rlErr + } else if rl != "" { + req, err = exported.NewRequest(ctx, http.MethodGet, rl) + } else if p.Method == http.MethodPatch || p.Method == http.MethodPut { + req, err = exported.NewRequest(ctx, http.MethodGet, p.OrigURL) + } else if p.Method == http.MethodPost && p.LocURL != "" { + req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL) + } + if err != nil { + return err + } + + // if a final GET request has been created, execute it + if req != nil { + resp, err := p.pl.Do(req) + if err != nil { + return err + } + p.resp = resp + } + + return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/poller.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/poller.go new file mode 100644 index 000000000..37ed647f4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/poller.go @@ -0,0 +1,24 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package pollers + +// FinalStateVia is the enumerated type for the possible final-state-via values. +type FinalStateVia string + +const ( + // FinalStateViaAzureAsyncOp indicates the final payload comes from the Azure-AsyncOperation URL. + FinalStateViaAzureAsyncOp FinalStateVia = "azure-async-operation" + + // FinalStateViaLocation indicates the final payload comes from the Location URL. + FinalStateViaLocation FinalStateVia = "location" + + // FinalStateViaOriginalURI indicates the final payload comes from the original URL. + FinalStateViaOriginalURI FinalStateVia = "original-uri" + + // FinalStateViaOpLocation indicates the final payload comes from the Operation-Location URL. + FinalStateViaOpLocation FinalStateVia = "operation-location" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/util.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/util.go new file mode 100644 index 000000000..d8d86a46c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/util.go @@ -0,0 +1,187 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package pollers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "reflect" + + azexported "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/internal/poller" +) + +// getTokenTypeName creates a type name from the type parameter T. +func getTokenTypeName[T any]() (string, error) { + tt := shared.TypeOfT[T]() + var n string + if tt.Kind() == reflect.Pointer { + n = "*" + tt = tt.Elem() + } + n += tt.Name() + if n == "" { + return "", errors.New("nameless types are not allowed") + } + return n, nil +} + +type resumeTokenWrapper[T any] struct { + Type string `json:"type"` + Token T `json:"token"` +} + +// NewResumeToken creates a resume token from the specified type. +// An error is returned if the generic type has no name (e.g. struct{}). +func NewResumeToken[TResult, TSource any](from TSource) (string, error) { + n, err := getTokenTypeName[TResult]() + if err != nil { + return "", err + } + b, err := json.Marshal(resumeTokenWrapper[TSource]{ + Type: n, + Token: from, + }) + if err != nil { + return "", err + } + return string(b), nil +} + +// ExtractToken returns the poller-specific token information from the provided token value. +func ExtractToken(token string) ([]byte, error) { + raw := map[string]json.RawMessage{} + if err := json.Unmarshal([]byte(token), &raw); err != nil { + return nil, err + } + // this is dependent on the type resumeTokenWrapper[T] + tk, ok := raw["token"] + if !ok { + return nil, errors.New("missing token value") + } + return tk, nil +} + +// IsTokenValid returns an error if the specified token isn't applicable for generic type T. +func IsTokenValid[T any](token string) error { + raw := map[string]interface{}{} + if err := json.Unmarshal([]byte(token), &raw); err != nil { + return err + } + t, ok := raw["type"] + if !ok { + return errors.New("missing type value") + } + tt, ok := t.(string) + if !ok { + return fmt.Errorf("invalid type format %T", t) + } + n, err := getTokenTypeName[T]() + if err != nil { + return err + } + if tt != n { + return fmt.Errorf("cannot resume from this poller token. token is for type %s, not %s", tt, n) + } + return nil +} + +// used if the operation synchronously completed +type NopPoller[T any] struct { + resp *http.Response + result T +} + +// NewNopPoller creates a NopPoller from the provided response. +// It unmarshals the response body into an instance of T. +func NewNopPoller[T any](resp *http.Response) (*NopPoller[T], error) { + np := &NopPoller[T]{resp: resp} + if resp.StatusCode == http.StatusNoContent { + return np, nil + } + payload, err := exported.Payload(resp, nil) + if err != nil { + return nil, err + } + if len(payload) == 0 { + return np, nil + } + if err = json.Unmarshal(payload, &np.result); err != nil { + return nil, err + } + return np, nil +} + +func (*NopPoller[T]) Done() bool { + return true +} + +func (p *NopPoller[T]) Poll(context.Context) (*http.Response, error) { + return p.resp, nil +} + +func (p *NopPoller[T]) Result(ctx context.Context, out *T) error { + *out = p.result + return nil +} + +// PollHelper creates and executes the request, calling update() with the response. +// If the request fails, the update func is not called. +// The update func returns the state of the operation for logging purposes or an error +// if it fails to extract the required state from the response. +func PollHelper(ctx context.Context, endpoint string, pl azexported.Pipeline, update func(resp *http.Response) (string, error)) error { + req, err := azexported.NewRequest(ctx, http.MethodGet, endpoint) + if err != nil { + return err + } + resp, err := pl.Do(req) + if err != nil { + return err + } + state, err := update(resp) + if err != nil { + return err + } + log.Writef(log.EventLRO, "State %s", state) + return nil +} + +// ResultHelper processes the response as success or failure. +// In the success case, it unmarshals the payload into either a new instance of T or out. +// In the failure case, it creates an *azcore.Response error from the response. +func ResultHelper[T any](resp *http.Response, failed bool, out *T) error { + // short-circuit the simple success case with no response body to unmarshal + if resp.StatusCode == http.StatusNoContent { + return nil + } + + defer resp.Body.Close() + if !poller.StatusCodeValid(resp) || failed { + // the LRO failed. unmarshall the error and update state + return azexported.NewResponseError(resp) + } + + // success case + payload, err := exported.Payload(resp, nil) + if err != nil { + return err + } + if len(payload) == 0 { + return nil + } + + if err = json.Unmarshal(payload, out); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go new file mode 100644 index 000000000..bb93daee6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go @@ -0,0 +1,44 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package shared + +const ( + ContentTypeAppJSON = "application/json" + ContentTypeAppXML = "application/xml" + ContentTypeTextPlain = "text/plain" +) + +const ( + HeaderAuthorization = "Authorization" + HeaderAuxiliaryAuthorization = "x-ms-authorization-auxiliary" + HeaderAzureAsync = "Azure-AsyncOperation" + HeaderContentLength = "Content-Length" + HeaderContentType = "Content-Type" + HeaderFakePollerStatus = "Fake-Poller-Status" + HeaderLocation = "Location" + HeaderOperationLocation = "Operation-Location" + HeaderRetryAfter = "Retry-After" + HeaderRetryAfterMS = "Retry-After-Ms" + HeaderUserAgent = "User-Agent" + HeaderWWWAuthenticate = "WWW-Authenticate" + HeaderXMSClientRequestID = "x-ms-client-request-id" + HeaderXMSRequestID = "x-ms-request-id" + HeaderXMSErrorCode = "x-ms-error-code" + HeaderXMSRetryAfterMS = "x-ms-retry-after-ms" +) + +const BearerTokenPrefix = "Bearer " + +const TracingNamespaceAttrName = "az.namespace" + +const ( + // Module is the name of the calling module used in telemetry data. + Module = "azcore" + + // Version is the semantic version (see http://semver.org) of this module. + Version = "v1.9.1" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/shared.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/shared.go new file mode 100644 index 000000000..d3da2c5fd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/shared.go @@ -0,0 +1,149 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package shared + +import ( + "context" + "fmt" + "net/http" + "reflect" + "regexp" + "strconv" + "time" +) + +// NOTE: when adding a new context key type, it likely needs to be +// added to the deny-list of key types in ContextWithDeniedValues + +// CtxWithHTTPHeaderKey is used as a context key for adding/retrieving http.Header. +type CtxWithHTTPHeaderKey struct{} + +// CtxWithRetryOptionsKey is used as a context key for adding/retrieving RetryOptions. +type CtxWithRetryOptionsKey struct{} + +// CtxWithCaptureResponse is used as a context key for retrieving the raw response. +type CtxWithCaptureResponse struct{} + +// CtxWithTracingTracer is used as a context key for adding/retrieving tracing.Tracer. +type CtxWithTracingTracer struct{} + +// CtxAPINameKey is used as a context key for adding/retrieving the API name. +type CtxAPINameKey struct{} + +// Delay waits for the duration to elapse or the context to be cancelled. +func Delay(ctx context.Context, delay time.Duration) error { + select { + case <-time.After(delay): + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// RetryAfter returns non-zero if the response contains one of the headers with a "retry after" value. +// Headers are checked in the following order: retry-after-ms, x-ms-retry-after-ms, retry-after +func RetryAfter(resp *http.Response) time.Duration { + if resp == nil { + return 0 + } + + type retryData struct { + header string + units time.Duration + + // custom is used when the regular algorithm failed and is optional. + // the returned duration is used verbatim (units is not applied). + custom func(string) time.Duration + } + + nop := func(string) time.Duration { return 0 } + + // the headers are listed in order of preference + retries := []retryData{ + { + header: HeaderRetryAfterMS, + units: time.Millisecond, + custom: nop, + }, + { + header: HeaderXMSRetryAfterMS, + units: time.Millisecond, + custom: nop, + }, + { + header: HeaderRetryAfter, + units: time.Second, + + // retry-after values are expressed in either number of + // seconds or an HTTP-date indicating when to try again + custom: func(ra string) time.Duration { + t, err := time.Parse(time.RFC1123, ra) + if err != nil { + return 0 + } + return time.Until(t) + }, + }, + } + + for _, retry := range retries { + v := resp.Header.Get(retry.header) + if v == "" { + continue + } + if retryAfter, _ := strconv.Atoi(v); retryAfter > 0 { + return time.Duration(retryAfter) * retry.units + } else if d := retry.custom(v); d > 0 { + return d + } + } + + return 0 +} + +// TypeOfT returns the type of the generic type param. +func TypeOfT[T any]() reflect.Type { + // you can't, at present, obtain the type of + // a type parameter, so this is the trick + return reflect.TypeOf((*T)(nil)).Elem() +} + +// TransportFunc is a helper to use a first-class func to satisfy the Transporter interface. +type TransportFunc func(*http.Request) (*http.Response, error) + +// Do implements the Transporter interface for the TransportFunc type. +func (pf TransportFunc) Do(req *http.Request) (*http.Response, error) { + return pf(req) +} + +// ValidateModVer verifies that moduleVersion is a valid semver 2.0 string. +func ValidateModVer(moduleVersion string) error { + modVerRegx := regexp.MustCompile(`^v\d+\.\d+\.\d+(?:-[a-zA-Z0-9_.-]+)?$`) + if !modVerRegx.MatchString(moduleVersion) { + return fmt.Errorf("malformed moduleVersion param value %s", moduleVersion) + } + return nil +} + +// ContextWithDeniedValues wraps an existing [context.Context], denying access to certain context values. +// Pipeline policies that create new requests to be sent down their own pipeline MUST wrap the caller's +// context with an instance of this type. This is to prevent context values from flowing across disjoint +// requests which can have unintended side-effects. +type ContextWithDeniedValues struct { + context.Context +} + +// Value implements part of the [context.Context] interface. +// It acts as a deny-list for certain context keys. +func (c *ContextWithDeniedValues) Value(key any) any { + switch key.(type) { + case CtxAPINameKey, CtxWithCaptureResponse, CtxWithHTTPHeaderKey, CtxWithRetryOptionsKey, CtxWithTracingTracer: + return nil + default: + return c.Context.Value(key) + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/doc.go new file mode 100644 index 000000000..2f3901bff --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/doc.go @@ -0,0 +1,10 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package log contains functionality for configuring logging behavior. +// Default logging to stderr can be enabled by setting environment variable AZURE_SDK_GO_LOGGING to "all". +package log diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/log.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/log.go new file mode 100644 index 000000000..7bde29d0a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/log.go @@ -0,0 +1,50 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Package log provides functionality for configuring logging facilities. +package log + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +// Event is used to group entries. Each group can be toggled on or off. +type Event = log.Event + +const ( + // EventRequest entries contain information about HTTP requests. + // This includes information like the URL, query parameters, and headers. + EventRequest Event = "Request" + + // EventResponse entries contain information about HTTP responses. + // This includes information like the HTTP status code, headers, and request URL. + EventResponse Event = "Response" + + // EventRetryPolicy entries contain information specific to the retry policy in use. + EventRetryPolicy Event = "Retry" + + // EventLRO entries contain information specific to long-running operations. + // This includes information like polling location, operation state, and sleep intervals. + EventLRO Event = "LongRunningOperation" +) + +// SetEvents is used to control which events are written to +// the log. By default all log events are writen. +// NOTE: this is not goroutine safe and should be called before using SDK clients. +func SetEvents(cls ...Event) { + log.SetEvents(cls...) +} + +// SetListener will set the Logger to write to the specified Listener. +// NOTE: this is not goroutine safe and should be called before using SDK clients. +func SetListener(lst func(Event, string)) { + log.SetListener(lst) +} + +// for testing purposes +func resetEvents() { + log.TestResetEvents() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/doc.go new file mode 100644 index 000000000..fad2579ed --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/doc.go @@ -0,0 +1,10 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package policy contains the definitions needed for configuring in-box pipeline policies +// and creating custom policies. +package policy diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/policy.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/policy.go new file mode 100644 index 000000000..d934f1dc5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/policy.go @@ -0,0 +1,187 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package policy + +import ( + "context" + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +// Policy represents an extensibility point for the Pipeline that can mutate the specified +// Request and react to the received Response. +type Policy = exported.Policy + +// Transporter represents an HTTP pipeline transport used to send HTTP requests and receive responses. +type Transporter = exported.Transporter + +// Request is an abstraction over the creation of an HTTP request as it passes through the pipeline. +// Don't use this type directly, use runtime.NewRequest() instead. +type Request = exported.Request + +// ClientOptions contains optional settings for a client's pipeline. +// Instances can be shared across calls to SDK client constructors when uniform configuration is desired. +// Zero-value fields will have their specified default values applied during use. +type ClientOptions struct { + // APIVersion overrides the default version requested of the service. + // Set with caution as this package version has not been tested with arbitrary service versions. + APIVersion string + + // Cloud specifies a cloud for the client. The default is Azure Public Cloud. + Cloud cloud.Configuration + + // Logging configures the built-in logging policy. + Logging LogOptions + + // Retry configures the built-in retry policy. + Retry RetryOptions + + // Telemetry configures the built-in telemetry policy. + Telemetry TelemetryOptions + + // TracingProvider configures the tracing provider. + // It defaults to a no-op tracer. + TracingProvider tracing.Provider + + // Transport sets the transport for HTTP requests. + Transport Transporter + + // PerCallPolicies contains custom policies to inject into the pipeline. + // Each policy is executed once per request. + PerCallPolicies []Policy + + // PerRetryPolicies contains custom policies to inject into the pipeline. + // Each policy is executed once per request, and for each retry of that request. + PerRetryPolicies []Policy +} + +// LogOptions configures the logging policy's behavior. +type LogOptions struct { + // IncludeBody indicates if request and response bodies should be included in logging. + // The default value is false. + // NOTE: enabling this can lead to disclosure of sensitive information, use with care. + IncludeBody bool + + // AllowedHeaders is the slice of headers to log with their values intact. + // All headers not in the slice will have their values REDACTED. + // Applies to request and response headers. + AllowedHeaders []string + + // AllowedQueryParams is the slice of query parameters to log with their values intact. + // All query parameters not in the slice will have their values REDACTED. + AllowedQueryParams []string +} + +// RetryOptions configures the retry policy's behavior. +// Zero-value fields will have their specified default values applied during use. +// This allows for modification of a subset of fields. +type RetryOptions struct { + // MaxRetries specifies the maximum number of attempts a failed operation will be retried + // before producing an error. + // The default value is three. A value less than zero means one try and no retries. + MaxRetries int32 + + // TryTimeout indicates the maximum time allowed for any single try of an HTTP request. + // This is disabled by default. Specify a value greater than zero to enable. + // NOTE: Setting this to a small value might cause premature HTTP request time-outs. + TryTimeout time.Duration + + // RetryDelay specifies the initial amount of delay to use before retrying an operation. + // The value is used only if the HTTP response does not contain a Retry-After header. + // The delay increases exponentially with each retry up to the maximum specified by MaxRetryDelay. + // The default value is four seconds. A value less than zero means no delay between retries. + RetryDelay time.Duration + + // MaxRetryDelay specifies the maximum delay allowed before retrying an operation. + // Typically the value is greater than or equal to the value specified in RetryDelay. + // The default Value is 60 seconds. A value less than zero means there is no cap. + MaxRetryDelay time.Duration + + // StatusCodes specifies the HTTP status codes that indicate the operation should be retried. + // A nil slice will use the following values. + // http.StatusRequestTimeout 408 + // http.StatusTooManyRequests 429 + // http.StatusInternalServerError 500 + // http.StatusBadGateway 502 + // http.StatusServiceUnavailable 503 + // http.StatusGatewayTimeout 504 + // Specifying values will replace the default values. + // Specifying an empty slice will disable retries for HTTP status codes. + StatusCodes []int + + // ShouldRetry evaluates if the retry policy should retry the request. + // When specified, the function overrides comparison against the list of + // HTTP status codes and error checking within the retry policy. Context + // and NonRetriable errors remain evaluated before calling ShouldRetry. + // The *http.Response and error parameters are mutually exclusive, i.e. + // if one is nil, the other is not nil. + // A return value of true means the retry policy should retry. + ShouldRetry func(*http.Response, error) bool +} + +// TelemetryOptions configures the telemetry policy's behavior. +type TelemetryOptions struct { + // ApplicationID is an application-specific identification string to add to the User-Agent. + // It has a maximum length of 24 characters and must not contain any spaces. + ApplicationID string + + // Disabled will prevent the addition of any telemetry data to the User-Agent. + Disabled bool +} + +// TokenRequestOptions contain specific parameter that may be used by credentials types when attempting to get a token. +type TokenRequestOptions = exported.TokenRequestOptions + +// BearerTokenOptions configures the bearer token policy's behavior. +type BearerTokenOptions struct { + // AuthorizationHandler allows SDK developers to run client-specific logic when BearerTokenPolicy must authorize a request. + // When this field isn't set, the policy follows its default behavior of authorizing every request with a bearer token from + // its given credential. + AuthorizationHandler AuthorizationHandler +} + +// AuthorizationHandler allows SDK developers to insert custom logic that runs when BearerTokenPolicy must authorize a request. +type AuthorizationHandler struct { + // OnRequest is called each time the policy receives a request. Its func parameter authorizes the request with a token + // from the policy's given credential. Implementations that need to perform I/O should use the Request's context, + // available from Request.Raw().Context(). When OnRequest returns an error, the policy propagates that error and doesn't + // send the request. When OnRequest is nil, the policy follows its default behavior, authorizing the request with a + // token from its credential according to its configuration. + OnRequest func(*Request, func(TokenRequestOptions) error) error + + // OnChallenge is called when the policy receives a 401 response, allowing the AuthorizationHandler to re-authorize the + // request according to an authentication challenge (the Response's WWW-Authenticate header). OnChallenge is responsible + // for parsing parameters from the challenge. Its func parameter will authorize the request with a token from the policy's + // given credential. Implementations that need to perform I/O should use the Request's context, available from + // Request.Raw().Context(). When OnChallenge returns nil, the policy will send the request again. When OnChallenge is nil, + // the policy will return any 401 response to the client. + OnChallenge func(*Request, *http.Response, func(TokenRequestOptions) error) error +} + +// WithCaptureResponse applies the HTTP response retrieval annotation to the parent context. +// The resp parameter will contain the HTTP response after the request has completed. +func WithCaptureResponse(parent context.Context, resp **http.Response) context.Context { + return context.WithValue(parent, shared.CtxWithCaptureResponse{}, resp) +} + +// WithHTTPHeader adds the specified http.Header to the parent context. +// Use this to specify custom HTTP headers at the API-call level. +// Any overlapping headers will have their values replaced with the values specified here. +func WithHTTPHeader(parent context.Context, header http.Header) context.Context { + return context.WithValue(parent, shared.CtxWithHTTPHeaderKey{}, header) +} + +// WithRetryOptions adds the specified RetryOptions to the parent context. +// Use this to specify custom RetryOptions at the API-call level. +func WithRetryOptions(parent context.Context, options RetryOptions) context.Context { + return context.WithValue(parent, shared.CtxWithRetryOptionsKey{}, options) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/doc.go new file mode 100644 index 000000000..c9cfa438c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/doc.go @@ -0,0 +1,10 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package runtime contains various facilities for creating requests and handling responses. +// The content is intended for SDK authors. +package runtime diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/errors.go new file mode 100644 index 000000000..6d03b291e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/errors.go @@ -0,0 +1,19 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" +) + +// NewResponseError creates an *azcore.ResponseError from the provided HTTP response. +// Call this when a service request returns a non-successful status code. +func NewResponseError(resp *http.Response) error { + return exported.NewResponseError(resp) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pager.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pager.go new file mode 100644 index 000000000..cffe692d7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pager.go @@ -0,0 +1,128 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +// PagingHandler contains the required data for constructing a Pager. +type PagingHandler[T any] struct { + // More returns a boolean indicating if there are more pages to fetch. + // It uses the provided page to make the determination. + More func(T) bool + + // Fetcher fetches the first and subsequent pages. + Fetcher func(context.Context, *T) (T, error) + + // Tracer contains the Tracer from the client that's creating the Pager. + Tracer tracing.Tracer +} + +// Pager provides operations for iterating over paged responses. +type Pager[T any] struct { + current *T + handler PagingHandler[T] + tracer tracing.Tracer + firstPage bool +} + +// NewPager creates an instance of Pager using the specified PagingHandler. +// Pass a non-nil T for firstPage if the first page has already been retrieved. +func NewPager[T any](handler PagingHandler[T]) *Pager[T] { + return &Pager[T]{ + handler: handler, + tracer: handler.Tracer, + firstPage: true, + } +} + +// More returns true if there are more pages to retrieve. +func (p *Pager[T]) More() bool { + if p.current != nil { + return p.handler.More(*p.current) + } + return true +} + +// NextPage advances the pager to the next page. +func (p *Pager[T]) NextPage(ctx context.Context) (T, error) { + if p.current != nil { + if p.firstPage { + // we get here if it's an LRO-pager, we already have the first page + p.firstPage = false + return *p.current, nil + } else if !p.handler.More(*p.current) { + return *new(T), errors.New("no more pages") + } + } else { + // non-LRO case, first page + p.firstPage = false + } + + var err error + ctx, endSpan := StartSpan(ctx, fmt.Sprintf("%s.NextPage", shortenTypeName(reflect.TypeOf(*p).Name())), p.tracer, nil) + defer func() { endSpan(err) }() + + resp, err := p.handler.Fetcher(ctx, p.current) + if err != nil { + return *new(T), err + } + p.current = &resp + return *p.current, nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for Pager[T]. +func (p *Pager[T]) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &p.current) +} + +// FetcherForNextLinkOptions contains the optional values for [FetcherForNextLink]. +type FetcherForNextLinkOptions struct { + // NextReq is the func to be called when requesting subsequent pages. + // Used for paged operations that have a custom next link operation. + NextReq func(context.Context, string) (*policy.Request, error) +} + +// FetcherForNextLink is a helper containing boilerplate code to simplify creating a PagingHandler[T].Fetcher from a next link URL. +// - ctx is the [context.Context] controlling the lifetime of the HTTP operation +// - pl is the [Pipeline] used to dispatch the HTTP request +// - nextLink is the URL used to fetch the next page. the empty string indicates the first page is to be requested +// - firstReq is the func to be called when creating the request for the first page +// - options contains any optional parameters, pass nil to accept the default values +func FetcherForNextLink(ctx context.Context, pl Pipeline, nextLink string, firstReq func(context.Context) (*policy.Request, error), options *FetcherForNextLinkOptions) (*http.Response, error) { + var req *policy.Request + var err error + if nextLink == "" { + req, err = firstReq(ctx) + } else if nextLink, err = EncodeQueryParams(nextLink); err == nil { + if options != nil && options.NextReq != nil { + req, err = options.NextReq(ctx, nextLink) + } else { + req, err = NewRequest(ctx, http.MethodGet, nextLink) + } + } + if err != nil { + return nil, err + } + resp, err := pl.Do(req) + if err != nil { + return nil, err + } + if !HasStatusCode(resp, http.StatusOK) { + return nil, NewResponseError(resp) + } + return resp, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pipeline.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pipeline.go new file mode 100644 index 000000000..6b1f5c083 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pipeline.go @@ -0,0 +1,94 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// PipelineOptions contains Pipeline options for SDK developers +type PipelineOptions struct { + // AllowedHeaders is the slice of headers to log with their values intact. + // All headers not in the slice will have their values REDACTED. + // Applies to request and response headers. + AllowedHeaders []string + + // AllowedQueryParameters is the slice of query parameters to log with their values intact. + // All query parameters not in the slice will have their values REDACTED. + AllowedQueryParameters []string + + // APIVersion overrides the default version requested of the service. + // Set with caution as this package version has not been tested with arbitrary service versions. + APIVersion APIVersionOptions + + // PerCall contains custom policies to inject into the pipeline. + // Each policy is executed once per request. + PerCall []policy.Policy + + // PerRetry contains custom policies to inject into the pipeline. + // Each policy is executed once per request, and for each retry of that request. + PerRetry []policy.Policy + + // Tracing contains options used to configure distributed tracing. + Tracing TracingOptions +} + +// TracingOptions contains tracing options for SDK developers. +type TracingOptions struct { + // Namespace contains the value to use for the az.namespace span attribute. + Namespace string +} + +// Pipeline represents a primitive for sending HTTP requests and receiving responses. +// Its behavior can be extended by specifying policies during construction. +type Pipeline = exported.Pipeline + +// NewPipeline creates a pipeline from connection options, with any additional policies as specified. +// Policies from ClientOptions are placed after policies from PipelineOptions. +// The module and version parameters are used by the telemetry policy, when enabled. +func NewPipeline(module, version string, plOpts PipelineOptions, options *policy.ClientOptions) Pipeline { + cp := policy.ClientOptions{} + if options != nil { + cp = *options + } + if len(plOpts.AllowedHeaders) > 0 { + headers := make([]string, len(plOpts.AllowedHeaders)+len(cp.Logging.AllowedHeaders)) + copy(headers, plOpts.AllowedHeaders) + headers = append(headers, cp.Logging.AllowedHeaders...) + cp.Logging.AllowedHeaders = headers + } + if len(plOpts.AllowedQueryParameters) > 0 { + qp := make([]string, len(plOpts.AllowedQueryParameters)+len(cp.Logging.AllowedQueryParams)) + copy(qp, plOpts.AllowedQueryParameters) + qp = append(qp, cp.Logging.AllowedQueryParams...) + cp.Logging.AllowedQueryParams = qp + } + // we put the includeResponsePolicy at the very beginning so that the raw response + // is populated with the final response (some policies might mutate the response) + policies := []policy.Policy{exported.PolicyFunc(includeResponsePolicy)} + if cp.APIVersion != "" { + policies = append(policies, newAPIVersionPolicy(cp.APIVersion, &plOpts.APIVersion)) + } + if !cp.Telemetry.Disabled { + policies = append(policies, NewTelemetryPolicy(module, version, &cp.Telemetry)) + } + policies = append(policies, plOpts.PerCall...) + policies = append(policies, cp.PerCallPolicies...) + policies = append(policies, NewRetryPolicy(&cp.Retry)) + policies = append(policies, plOpts.PerRetry...) + policies = append(policies, cp.PerRetryPolicies...) + policies = append(policies, exported.PolicyFunc(httpHeaderPolicy)) + policies = append(policies, newHTTPTracePolicy(cp.Logging.AllowedQueryParams)) + policies = append(policies, NewLogPolicy(&cp.Logging)) + policies = append(policies, exported.PolicyFunc(bodyDownloadPolicy)) + transport := cp.Transport + if transport == nil { + transport = defaultHTTPClient + } + return exported.NewPipeline(transport, policies...) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_api_version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_api_version.go new file mode 100644 index 000000000..e5309aa6c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_api_version.go @@ -0,0 +1,75 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// APIVersionOptions contains options for API versions +type APIVersionOptions struct { + // Location indicates where to set the version on a request, for example in a header or query param + Location APIVersionLocation + // Name is the name of the header or query parameter, for example "api-version" + Name string +} + +// APIVersionLocation indicates which part of a request identifies the service version +type APIVersionLocation int + +const ( + // APIVersionLocationQueryParam indicates a query parameter + APIVersionLocationQueryParam = 0 + // APIVersionLocationHeader indicates a header + APIVersionLocationHeader = 1 +) + +// newAPIVersionPolicy constructs an APIVersionPolicy. If version is "", Do will be a no-op. If version +// isn't empty and opts.Name is empty, Do will return an error. +func newAPIVersionPolicy(version string, opts *APIVersionOptions) *apiVersionPolicy { + if opts == nil { + opts = &APIVersionOptions{} + } + return &apiVersionPolicy{location: opts.Location, name: opts.Name, version: version} +} + +// apiVersionPolicy enables users to set the API version of every request a client sends. +type apiVersionPolicy struct { + // location indicates whether "name" refers to a query parameter or header. + location APIVersionLocation + + // name of the query param or header whose value should be overridden; provided by the client. + name string + + // version is the value (provided by the user) that replaces the default version value. + version string +} + +// Do sets the request's API version, if the policy is configured to do so, replacing any prior value. +func (a *apiVersionPolicy) Do(req *policy.Request) (*http.Response, error) { + if a.version != "" { + if a.name == "" { + // user set ClientOptions.APIVersion but the client ctor didn't set PipelineOptions.APIVersionOptions + return nil, errors.New("this client doesn't support overriding its API version") + } + switch a.location { + case APIVersionLocationHeader: + req.Raw().Header.Set(a.name, a.version) + case APIVersionLocationQueryParam: + q := req.Raw().URL.Query() + q.Set(a.name, a.version) + req.Raw().URL.RawQuery = q.Encode() + default: + return nil, fmt.Errorf("unknown APIVersionLocation %d", a.location) + } + } + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go new file mode 100644 index 000000000..f0f280355 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "errors" + "net/http" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" + "github.com/Azure/azure-sdk-for-go/sdk/internal/temporal" +) + +// BearerTokenPolicy authorizes requests with bearer tokens acquired from a TokenCredential. +type BearerTokenPolicy struct { + // mainResource is the resource to be retreived using the tenant specified in the credential + mainResource *temporal.Resource[exported.AccessToken, acquiringResourceState] + // the following fields are read-only + authzHandler policy.AuthorizationHandler + cred exported.TokenCredential + scopes []string +} + +type acquiringResourceState struct { + req *policy.Request + p *BearerTokenPolicy + tro policy.TokenRequestOptions +} + +// acquire acquires or updates the resource; only one +// thread/goroutine at a time ever calls this function +func acquire(state acquiringResourceState) (newResource exported.AccessToken, newExpiration time.Time, err error) { + tk, err := state.p.cred.GetToken(&shared.ContextWithDeniedValues{Context: state.req.Raw().Context()}, state.tro) + if err != nil { + return exported.AccessToken{}, time.Time{}, err + } + return tk, tk.ExpiresOn, nil +} + +// NewBearerTokenPolicy creates a policy object that authorizes requests with bearer tokens. +// cred: an azcore.TokenCredential implementation such as a credential object from azidentity +// scopes: the list of permission scopes required for the token. +// opts: optional settings. Pass nil to accept default values; this is the same as passing a zero-value options. +func NewBearerTokenPolicy(cred exported.TokenCredential, scopes []string, opts *policy.BearerTokenOptions) *BearerTokenPolicy { + if opts == nil { + opts = &policy.BearerTokenOptions{} + } + return &BearerTokenPolicy{ + authzHandler: opts.AuthorizationHandler, + cred: cred, + scopes: scopes, + mainResource: temporal.NewResource(acquire), + } +} + +// authenticateAndAuthorize returns a function which authorizes req with a token from the policy's credential +func (b *BearerTokenPolicy) authenticateAndAuthorize(req *policy.Request) func(policy.TokenRequestOptions) error { + return func(tro policy.TokenRequestOptions) error { + as := acquiringResourceState{p: b, req: req, tro: tro} + tk, err := b.mainResource.Get(as) + if err != nil { + return err + } + req.Raw().Header.Set(shared.HeaderAuthorization, shared.BearerTokenPrefix+tk.Token) + return nil + } +} + +// Do authorizes a request with a bearer token +func (b *BearerTokenPolicy) Do(req *policy.Request) (*http.Response, error) { + // skip adding the authorization header if no TokenCredential was provided. + // this prevents a panic that might be hard to diagnose and allows testing + // against http endpoints that don't require authentication. + if b.cred == nil { + return req.Next() + } + + if err := checkHTTPSForAuth(req); err != nil { + return nil, err + } + + var err error + if b.authzHandler.OnRequest != nil { + err = b.authzHandler.OnRequest(req, b.authenticateAndAuthorize(req)) + } else { + err = b.authenticateAndAuthorize(req)(policy.TokenRequestOptions{Scopes: b.scopes}) + } + if err != nil { + return nil, errorinfo.NonRetriableError(err) + } + + res, err := req.Next() + if err != nil { + return nil, err + } + + if res.StatusCode == http.StatusUnauthorized { + b.mainResource.Expire() + if res.Header.Get("WWW-Authenticate") != "" && b.authzHandler.OnChallenge != nil { + if err = b.authzHandler.OnChallenge(req, res, b.authenticateAndAuthorize(req)); err == nil { + res, err = req.Next() + } + } + } + if err != nil { + err = errorinfo.NonRetriableError(err) + } + return res, err +} + +func checkHTTPSForAuth(req *policy.Request) error { + if strings.ToLower(req.Raw().URL.Scheme) != "https" { + return errorinfo.NonRetriableError(errors.New("authenticated requests are not permitted for non TLS protected (https) endpoints")) + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_body_download.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_body_download.go new file mode 100644 index 000000000..99dc029f0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_body_download.go @@ -0,0 +1,72 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "fmt" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" +) + +// bodyDownloadPolicy creates a policy object that downloads the response's body to a []byte. +func bodyDownloadPolicy(req *policy.Request) (*http.Response, error) { + resp, err := req.Next() + if err != nil { + return resp, err + } + var opValues bodyDownloadPolicyOpValues + // don't skip downloading error response bodies + if req.OperationValue(&opValues); opValues.Skip && resp.StatusCode < 400 { + return resp, err + } + // Either bodyDownloadPolicyOpValues was not specified (so skip is false) + // or it was specified and skip is false: don't skip downloading the body + _, err = Payload(resp) + if err != nil { + return resp, newBodyDownloadError(err, req) + } + return resp, err +} + +// bodyDownloadPolicyOpValues is the struct containing the per-operation values +type bodyDownloadPolicyOpValues struct { + Skip bool +} + +type bodyDownloadError struct { + err error +} + +func newBodyDownloadError(err error, req *policy.Request) error { + // on failure, only retry the request for idempotent operations. + // we currently identify them as DELETE, GET, and PUT requests. + if m := strings.ToUpper(req.Raw().Method); m == http.MethodDelete || m == http.MethodGet || m == http.MethodPut { + // error is safe for retry + return err + } + // wrap error to avoid retries + return &bodyDownloadError{ + err: err, + } +} + +func (b *bodyDownloadError) Error() string { + return fmt.Sprintf("body download policy: %s", b.err.Error()) +} + +func (b *bodyDownloadError) NonRetriable() { + // marker method +} + +func (b *bodyDownloadError) Unwrap() error { + return b.err +} + +var _ errorinfo.NonRetriable = (*bodyDownloadError)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_header.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_header.go new file mode 100644 index 000000000..c230af0af --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_header.go @@ -0,0 +1,40 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// newHTTPHeaderPolicy creates a policy object that adds custom HTTP headers to a request +func httpHeaderPolicy(req *policy.Request) (*http.Response, error) { + // check if any custom HTTP headers have been specified + if header := req.Raw().Context().Value(shared.CtxWithHTTPHeaderKey{}); header != nil { + for k, v := range header.(http.Header) { + // use Set to replace any existing value + // it also canonicalizes the header key + req.Raw().Header.Set(k, v[0]) + // add any remaining values + for i := 1; i < len(v); i++ { + req.Raw().Header.Add(k, v[i]) + } + } + } + return req.Next() +} + +// WithHTTPHeader adds the specified http.Header to the parent context. +// Use this to specify custom HTTP headers at the API-call level. +// Any overlapping headers will have their values replaced with the values specified here. +// Deprecated: use [policy.WithHTTPHeader] instead. +func WithHTTPHeader(parent context.Context, header http.Header) context.Context { + return policy.WithHTTPHeader(parent, header) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_trace.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_trace.go new file mode 100644 index 000000000..3df1c1218 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_trace.go @@ -0,0 +1,143 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +const ( + attrHTTPMethod = "http.method" + attrHTTPURL = "http.url" + attrHTTPUserAgent = "http.user_agent" + attrHTTPStatusCode = "http.status_code" + + attrAZClientReqID = "az.client_request_id" + attrAZServiceReqID = "az.service_request_id" + + attrNetPeerName = "net.peer.name" +) + +// newHTTPTracePolicy creates a new instance of the httpTracePolicy. +// - allowedQueryParams contains the user-specified query parameters that don't need to be redacted from the trace +func newHTTPTracePolicy(allowedQueryParams []string) exported.Policy { + return &httpTracePolicy{allowedQP: getAllowedQueryParams(allowedQueryParams)} +} + +// httpTracePolicy is a policy that creates a trace for the HTTP request and its response +type httpTracePolicy struct { + allowedQP map[string]struct{} +} + +// Do implements the pipeline.Policy interfaces for the httpTracePolicy type. +func (h *httpTracePolicy) Do(req *policy.Request) (resp *http.Response, err error) { + rawTracer := req.Raw().Context().Value(shared.CtxWithTracingTracer{}) + if tracer, ok := rawTracer.(tracing.Tracer); ok && tracer.Enabled() { + attributes := []tracing.Attribute{ + {Key: attrHTTPMethod, Value: req.Raw().Method}, + {Key: attrHTTPURL, Value: getSanitizedURL(*req.Raw().URL, h.allowedQP)}, + {Key: attrNetPeerName, Value: req.Raw().URL.Host}, + } + + if ua := req.Raw().Header.Get(shared.HeaderUserAgent); ua != "" { + attributes = append(attributes, tracing.Attribute{Key: attrHTTPUserAgent, Value: ua}) + } + if reqID := req.Raw().Header.Get(shared.HeaderXMSClientRequestID); reqID != "" { + attributes = append(attributes, tracing.Attribute{Key: attrAZClientReqID, Value: reqID}) + } + + ctx := req.Raw().Context() + ctx, span := tracer.Start(ctx, "HTTP "+req.Raw().Method, &tracing.SpanOptions{ + Kind: tracing.SpanKindClient, + Attributes: attributes, + }) + + defer func() { + if resp != nil { + span.SetAttributes(tracing.Attribute{Key: attrHTTPStatusCode, Value: resp.StatusCode}) + if resp.StatusCode > 399 { + span.SetStatus(tracing.SpanStatusError, resp.Status) + } + if reqID := resp.Header.Get(shared.HeaderXMSRequestID); reqID != "" { + span.SetAttributes(tracing.Attribute{Key: attrAZServiceReqID, Value: reqID}) + } + } else if err != nil { + var urlErr *url.Error + if errors.As(err, &urlErr) { + // calling *url.Error.Error() will include the unsanitized URL + // which we don't want. in addition, we already have the HTTP verb + // and sanitized URL in the trace so we aren't losing any info + err = urlErr.Err + } + span.SetStatus(tracing.SpanStatusError, err.Error()) + } + span.End() + }() + + req = req.WithContext(ctx) + } + resp, err = req.Next() + return +} + +// StartSpanOptions contains the optional values for StartSpan. +type StartSpanOptions struct { + // for future expansion +} + +// StartSpan starts a new tracing span. +// You must call the returned func to terminate the span. Pass the applicable error +// if the span will exit with an error condition. +// - ctx is the parent context of the newly created context +// - name is the name of the span. this is typically the fully qualified name of an API ("Client.Method") +// - tracer is the client's Tracer for creating spans +// - options contains optional values. pass nil to accept any default values +func StartSpan(ctx context.Context, name string, tracer tracing.Tracer, options *StartSpanOptions) (context.Context, func(error)) { + if !tracer.Enabled() { + return ctx, func(err error) {} + } + + // we MUST propagate the active tracer before returning so that the trace policy can access it + ctx = context.WithValue(ctx, shared.CtxWithTracingTracer{}, tracer) + + const newSpanKind = tracing.SpanKindInternal + if activeSpan := ctx.Value(ctxActiveSpan{}); activeSpan != nil { + // per the design guidelines, if a SDK method Foo() calls SDK method Bar(), + // then the span for Bar() must be suppressed. however, if Bar() makes a REST + // call, then Bar's HTTP span must be a child of Foo's span. + // however, there is an exception to this rule. if the SDK method Foo() is a + // messaging producer/consumer, and it takes a callback that's a SDK method + // Bar(), then the span for Bar() must _not_ be suppressed. + if kind := activeSpan.(tracing.SpanKind); kind == tracing.SpanKindClient || kind == tracing.SpanKindInternal { + return ctx, func(err error) {} + } + } + ctx, span := tracer.Start(ctx, name, &tracing.SpanOptions{ + Kind: newSpanKind, + }) + ctx = context.WithValue(ctx, ctxActiveSpan{}, newSpanKind) + return ctx, func(err error) { + if err != nil { + errType := strings.Replace(fmt.Sprintf("%T", err), "*exported.", "*azcore.", 1) + span.SetStatus(tracing.SpanStatusError, fmt.Sprintf("%s:\n%s", errType, err.Error())) + } + span.End() + } +} + +// ctxActiveSpan is used as a context key for indicating a SDK client span is in progress. +type ctxActiveSpan struct{} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_include_response.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_include_response.go new file mode 100644 index 000000000..bb00f6c2f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_include_response.go @@ -0,0 +1,35 @@ +//go:build go1.16 +// +build go1.16 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// includeResponsePolicy creates a policy that retrieves the raw HTTP response upon request +func includeResponsePolicy(req *policy.Request) (*http.Response, error) { + resp, err := req.Next() + if resp == nil { + return resp, err + } + if httpOutRaw := req.Raw().Context().Value(shared.CtxWithCaptureResponse{}); httpOutRaw != nil { + httpOut := httpOutRaw.(**http.Response) + *httpOut = resp + } + return resp, err +} + +// WithCaptureResponse applies the HTTP response retrieval annotation to the parent context. +// The resp parameter will contain the HTTP response after the request has completed. +// Deprecated: use [policy.WithCaptureResponse] instead. +func WithCaptureResponse(parent context.Context, resp **http.Response) context.Context { + return policy.WithCaptureResponse(parent, resp) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_key_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_key_credential.go new file mode 100644 index 000000000..6f577fa7a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_key_credential.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// KeyCredentialPolicy authorizes requests with a [azcore.KeyCredential]. +type KeyCredentialPolicy struct { + cred *exported.KeyCredential + header string + prefix string +} + +// KeyCredentialPolicyOptions contains the optional values configuring [KeyCredentialPolicy]. +type KeyCredentialPolicyOptions struct { + // Prefix is used if the key requires a prefix before it's inserted into the HTTP request. + Prefix string +} + +// NewKeyCredentialPolicy creates a new instance of [KeyCredentialPolicy]. +// - cred is the [azcore.KeyCredential] used to authenticate with the service +// - header is the name of the HTTP request header in which the key is placed +// - options contains optional configuration, pass nil to accept the default values +func NewKeyCredentialPolicy(cred *exported.KeyCredential, header string, options *KeyCredentialPolicyOptions) *KeyCredentialPolicy { + if options == nil { + options = &KeyCredentialPolicyOptions{} + } + return &KeyCredentialPolicy{ + cred: cred, + header: header, + prefix: options.Prefix, + } +} + +// Do implementes the Do method on the [policy.Polilcy] interface. +func (k *KeyCredentialPolicy) Do(req *policy.Request) (*http.Response, error) { + // skip adding the authorization header if no KeyCredential was provided. + // this prevents a panic that might be hard to diagnose and allows testing + // against http endpoints that don't require authentication. + if k.cred != nil { + if err := checkHTTPSForAuth(req); err != nil { + return nil, err + } + val := exported.KeyCredentialGet(k.cred) + if k.prefix != "" { + val = k.prefix + val + } + req.Raw().Header.Add(k.header, val) + } + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_logging.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_logging.go new file mode 100644 index 000000000..f048d7fb5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_logging.go @@ -0,0 +1,264 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/diag" +) + +type logPolicy struct { + includeBody bool + allowedHeaders map[string]struct{} + allowedQP map[string]struct{} +} + +// NewLogPolicy creates a request/response logging policy object configured using the specified options. +// Pass nil to accept the default values; this is the same as passing a zero-value options. +func NewLogPolicy(o *policy.LogOptions) policy.Policy { + if o == nil { + o = &policy.LogOptions{} + } + // construct default hash set of allowed headers + allowedHeaders := map[string]struct{}{ + "accept": {}, + "cache-control": {}, + "connection": {}, + "content-length": {}, + "content-type": {}, + "date": {}, + "etag": {}, + "expires": {}, + "if-match": {}, + "if-modified-since": {}, + "if-none-match": {}, + "if-unmodified-since": {}, + "last-modified": {}, + "ms-cv": {}, + "pragma": {}, + "request-id": {}, + "retry-after": {}, + "server": {}, + "traceparent": {}, + "transfer-encoding": {}, + "user-agent": {}, + "www-authenticate": {}, + "x-ms-request-id": {}, + "x-ms-client-request-id": {}, + "x-ms-return-client-request-id": {}, + } + // add any caller-specified allowed headers to the set + for _, ah := range o.AllowedHeaders { + allowedHeaders[strings.ToLower(ah)] = struct{}{} + } + // now do the same thing for query params + allowedQP := getAllowedQueryParams(o.AllowedQueryParams) + return &logPolicy{ + includeBody: o.IncludeBody, + allowedHeaders: allowedHeaders, + allowedQP: allowedQP, + } +} + +// getAllowedQueryParams merges the default set of allowed query parameters +// with a custom set (usually comes from client options). +func getAllowedQueryParams(customAllowedQP []string) map[string]struct{} { + allowedQP := map[string]struct{}{ + "api-version": {}, + } + for _, qp := range customAllowedQP { + allowedQP[strings.ToLower(qp)] = struct{}{} + } + return allowedQP +} + +// logPolicyOpValues is the struct containing the per-operation values +type logPolicyOpValues struct { + try int32 + start time.Time +} + +func (p *logPolicy) Do(req *policy.Request) (*http.Response, error) { + // Get the per-operation values. These are saved in the Message's map so that they persist across each retry calling into this policy object. + var opValues logPolicyOpValues + if req.OperationValue(&opValues); opValues.start.IsZero() { + opValues.start = time.Now() // If this is the 1st try, record this operation's start time + } + opValues.try++ // The first try is #1 (not #0) + req.SetOperationValue(opValues) + + // Log the outgoing request as informational + if log.Should(log.EventRequest) { + b := &bytes.Buffer{} + fmt.Fprintf(b, "==> OUTGOING REQUEST (Try=%d)\n", opValues.try) + p.writeRequestWithResponse(b, req, nil, nil) + var err error + if p.includeBody { + err = writeReqBody(req, b) + } + log.Write(log.EventRequest, b.String()) + if err != nil { + return nil, err + } + } + + // Set the time for this particular retry operation and then Do the operation. + tryStart := time.Now() + response, err := req.Next() // Make the request + tryEnd := time.Now() + tryDuration := tryEnd.Sub(tryStart) + opDuration := tryEnd.Sub(opValues.start) + + if log.Should(log.EventResponse) { + // We're going to log this; build the string to log + b := &bytes.Buffer{} + fmt.Fprintf(b, "==> REQUEST/RESPONSE (Try=%d/%v, OpTime=%v) -- ", opValues.try, tryDuration, opDuration) + if err != nil { // This HTTP request did not get a response from the service + fmt.Fprint(b, "REQUEST ERROR\n") + } else { + fmt.Fprint(b, "RESPONSE RECEIVED\n") + } + + p.writeRequestWithResponse(b, req, response, err) + if err != nil { + // skip frames runtime.Callers() and runtime.StackTrace() + b.WriteString(diag.StackTrace(2, 32)) + } else if p.includeBody { + err = writeRespBody(response, b) + } + log.Write(log.EventResponse, b.String()) + } + return response, err +} + +const redactedValue = "REDACTED" + +// getSanitizedURL returns a sanitized string for the provided url.URL +func getSanitizedURL(u url.URL, allowedQueryParams map[string]struct{}) string { + // redact applicable query params + qp := u.Query() + for k := range qp { + if _, ok := allowedQueryParams[strings.ToLower(k)]; !ok { + qp.Set(k, redactedValue) + } + } + u.RawQuery = qp.Encode() + return u.String() +} + +// writeRequestWithResponse appends a formatted HTTP request into a Buffer. If request and/or err are +// not nil, then these are also written into the Buffer. +func (p *logPolicy) writeRequestWithResponse(b *bytes.Buffer, req *policy.Request, resp *http.Response, err error) { + // Write the request into the buffer. + fmt.Fprint(b, " "+req.Raw().Method+" "+getSanitizedURL(*req.Raw().URL, p.allowedQP)+"\n") + p.writeHeader(b, req.Raw().Header) + if resp != nil { + fmt.Fprintln(b, " --------------------------------------------------------------------------------") + fmt.Fprint(b, " RESPONSE Status: "+resp.Status+"\n") + p.writeHeader(b, resp.Header) + } + if err != nil { + fmt.Fprintln(b, " --------------------------------------------------------------------------------") + fmt.Fprint(b, " ERROR:\n"+err.Error()+"\n") + } +} + +// formatHeaders appends an HTTP request's or response's header into a Buffer. +func (p *logPolicy) writeHeader(b *bytes.Buffer, header http.Header) { + if len(header) == 0 { + b.WriteString(" (no headers)\n") + return + } + keys := make([]string, 0, len(header)) + // Alphabetize the headers + for k := range header { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + // don't use Get() as it will canonicalize k which might cause a mismatch + value := header[k][0] + // redact all header values not in the allow-list + if _, ok := p.allowedHeaders[strings.ToLower(k)]; !ok { + value = redactedValue + } + fmt.Fprintf(b, " %s: %+v\n", k, value) + } +} + +// returns true if the request/response body should be logged. +// this is determined by looking at the content-type header value. +func shouldLogBody(b *bytes.Buffer, contentType string) bool { + contentType = strings.ToLower(contentType) + if strings.HasPrefix(contentType, "text") || + strings.Contains(contentType, "json") || + strings.Contains(contentType, "xml") { + return true + } + fmt.Fprintf(b, " Skip logging body for %s\n", contentType) + return false +} + +// writes to a buffer, used for logging purposes +func writeReqBody(req *policy.Request, b *bytes.Buffer) error { + if req.Raw().Body == nil { + fmt.Fprint(b, " Request contained no body\n") + return nil + } + if ct := req.Raw().Header.Get(shared.HeaderContentType); !shouldLogBody(b, ct) { + return nil + } + body, err := io.ReadAll(req.Raw().Body) + if err != nil { + fmt.Fprintf(b, " Failed to read request body: %s\n", err.Error()) + return err + } + if err := req.RewindBody(); err != nil { + return err + } + logBody(b, body) + return nil +} + +// writes to a buffer, used for logging purposes +func writeRespBody(resp *http.Response, b *bytes.Buffer) error { + ct := resp.Header.Get(shared.HeaderContentType) + if ct == "" { + fmt.Fprint(b, " Response contained no body\n") + return nil + } else if !shouldLogBody(b, ct) { + return nil + } + body, err := Payload(resp) + if err != nil { + fmt.Fprintf(b, " Failed to read response body: %s\n", err.Error()) + return err + } + if len(body) > 0 { + logBody(b, body) + } else { + fmt.Fprint(b, " Response contained no body\n") + } + return nil +} + +func logBody(b *bytes.Buffer, body []byte) { + fmt.Fprintln(b, " --------------------------------------------------------------------------------") + fmt.Fprintln(b, string(body)) + fmt.Fprintln(b, " --------------------------------------------------------------------------------") +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_request_id.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_request_id.go new file mode 100644 index 000000000..360a7f211 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_request_id.go @@ -0,0 +1,34 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/uuid" +) + +type requestIDPolicy struct{} + +// NewRequestIDPolicy returns a policy that add the x-ms-client-request-id header +func NewRequestIDPolicy() policy.Policy { + return &requestIDPolicy{} +} + +func (r *requestIDPolicy) Do(req *policy.Request) (*http.Response, error) { + if req.Raw().Header.Get(shared.HeaderXMSClientRequestID) == "" { + id, err := uuid.New() + if err != nil { + return nil, err + } + req.Raw().Header.Set(shared.HeaderXMSClientRequestID, id.String()) + } + + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_retry.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_retry.go new file mode 100644 index 000000000..04d7bb4ec --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_retry.go @@ -0,0 +1,255 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "errors" + "io" + "math" + "math/rand" + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" + "github.com/Azure/azure-sdk-for-go/sdk/internal/exported" +) + +const ( + defaultMaxRetries = 3 +) + +func setDefaults(o *policy.RetryOptions) { + if o.MaxRetries == 0 { + o.MaxRetries = defaultMaxRetries + } else if o.MaxRetries < 0 { + o.MaxRetries = 0 + } + + // SDK guidelines specify the default MaxRetryDelay is 60 seconds + if o.MaxRetryDelay == 0 { + o.MaxRetryDelay = 60 * time.Second + } else if o.MaxRetryDelay < 0 { + // not really an unlimited cap, but sufficiently large enough to be considered as such + o.MaxRetryDelay = math.MaxInt64 + } + if o.RetryDelay == 0 { + o.RetryDelay = 800 * time.Millisecond + } else if o.RetryDelay < 0 { + o.RetryDelay = 0 + } + if o.StatusCodes == nil { + // NOTE: if you change this list, you MUST update the docs in policy/policy.go + o.StatusCodes = []int{ + http.StatusRequestTimeout, // 408 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 + } + } +} + +func calcDelay(o policy.RetryOptions, try int32) time.Duration { // try is >=1; never 0 + delay := time.Duration((1< o.MaxRetryDelay { + delay = o.MaxRetryDelay + } + return delay +} + +// NewRetryPolicy creates a policy object configured using the specified options. +// Pass nil to accept the default values; this is the same as passing a zero-value options. +func NewRetryPolicy(o *policy.RetryOptions) policy.Policy { + if o == nil { + o = &policy.RetryOptions{} + } + p := &retryPolicy{options: *o} + return p +} + +type retryPolicy struct { + options policy.RetryOptions +} + +func (p *retryPolicy) Do(req *policy.Request) (resp *http.Response, err error) { + options := p.options + // check if the retry options have been overridden for this call + if override := req.Raw().Context().Value(shared.CtxWithRetryOptionsKey{}); override != nil { + options = override.(policy.RetryOptions) + } + setDefaults(&options) + // Exponential retry algorithm: ((2 ^ attempt) - 1) * delay * random(0.8, 1.2) + // When to retry: connection failure or temporary/timeout. + var rwbody *retryableRequestBody + if req.Body() != nil { + // wrap the body so we control when it's actually closed. + // do this outside the for loop so defers don't accumulate. + rwbody = &retryableRequestBody{body: req.Body()} + defer rwbody.realClose() + } + try := int32(1) + for { + resp = nil // reset + log.Writef(log.EventRetryPolicy, "=====> Try=%d", try) + + // For each try, seek to the beginning of the Body stream. We do this even for the 1st try because + // the stream may not be at offset 0 when we first get it and we want the same behavior for the + // 1st try as for additional tries. + err = req.RewindBody() + if err != nil { + return + } + // RewindBody() restores Raw().Body to its original state, so set our rewindable after + if rwbody != nil { + req.Raw().Body = rwbody + } + + if options.TryTimeout == 0 { + clone := req.Clone(req.Raw().Context()) + resp, err = clone.Next() + } else { + // Set the per-try time for this particular retry operation and then Do the operation. + tryCtx, tryCancel := context.WithTimeout(req.Raw().Context(), options.TryTimeout) + clone := req.Clone(tryCtx) + resp, err = clone.Next() // Make the request + // if the body was already downloaded or there was an error it's safe to cancel the context now + if err != nil { + tryCancel() + } else if exported.PayloadDownloaded(resp) { + tryCancel() + } else { + // must cancel the context after the body has been read and closed + resp.Body = &contextCancelReadCloser{cf: tryCancel, body: resp.Body} + } + } + if err == nil { + log.Writef(log.EventRetryPolicy, "response %d", resp.StatusCode) + } else { + log.Writef(log.EventRetryPolicy, "error %v", err) + } + + if ctxErr := req.Raw().Context().Err(); ctxErr != nil { + // don't retry if the parent context has been cancelled or its deadline exceeded + err = ctxErr + log.Writef(log.EventRetryPolicy, "abort due to %v", err) + return + } + + // check if the error is not retriable + var nre errorinfo.NonRetriable + if errors.As(err, &nre) { + // the error says it's not retriable so don't retry + log.Writef(log.EventRetryPolicy, "non-retriable error %T", nre) + return + } + + if options.ShouldRetry != nil { + // a non-nil ShouldRetry overrides our HTTP status code check + if !options.ShouldRetry(resp, err) { + // predicate says we shouldn't retry + log.Write(log.EventRetryPolicy, "exit due to ShouldRetry") + return + } + } else if err == nil && !HasStatusCode(resp, options.StatusCodes...) { + // if there is no error and the response code isn't in the list of retry codes then we're done. + log.Write(log.EventRetryPolicy, "exit due to non-retriable status code") + return + } + + if try == options.MaxRetries+1 { + // max number of tries has been reached, don't sleep again + log.Writef(log.EventRetryPolicy, "MaxRetries %d exceeded", options.MaxRetries) + return + } + + // use the delay from retry-after if available + delay := shared.RetryAfter(resp) + if delay <= 0 { + delay = calcDelay(options, try) + } else if delay > options.MaxRetryDelay { + // the retry-after delay exceeds the the cap so don't retry + log.Writef(log.EventRetryPolicy, "Retry-After delay %s exceeds MaxRetryDelay of %s", delay, options.MaxRetryDelay) + return + } + + // drain before retrying so nothing is leaked + Drain(resp) + + log.Writef(log.EventRetryPolicy, "End Try #%d, Delay=%v", try, delay) + select { + case <-time.After(delay): + try++ + case <-req.Raw().Context().Done(): + err = req.Raw().Context().Err() + log.Writef(log.EventRetryPolicy, "abort due to %v", err) + return + } + } +} + +// WithRetryOptions adds the specified RetryOptions to the parent context. +// Use this to specify custom RetryOptions at the API-call level. +// Deprecated: use [policy.WithRetryOptions] instead. +func WithRetryOptions(parent context.Context, options policy.RetryOptions) context.Context { + return policy.WithRetryOptions(parent, options) +} + +// ********** The following type/methods implement the retryableRequestBody (a ReadSeekCloser) + +// This struct is used when sending a body to the network +type retryableRequestBody struct { + body io.ReadSeeker // Seeking is required to support retries +} + +// Read reads a block of data from an inner stream and reports progress +func (b *retryableRequestBody) Read(p []byte) (n int, err error) { + return b.body.Read(p) +} + +func (b *retryableRequestBody) Seek(offset int64, whence int) (offsetFromStart int64, err error) { + return b.body.Seek(offset, whence) +} + +func (b *retryableRequestBody) Close() error { + // We don't want the underlying transport to close the request body on transient failures so this is a nop. + // The retry policy closes the request body upon success. + return nil +} + +func (b *retryableRequestBody) realClose() error { + if c, ok := b.body.(io.Closer); ok { + return c.Close() + } + return nil +} + +// ********** The following type/methods implement the contextCancelReadCloser + +// contextCancelReadCloser combines an io.ReadCloser with a cancel func. +// it ensures the cancel func is invoked once the body has been read and closed. +type contextCancelReadCloser struct { + cf context.CancelFunc + body io.ReadCloser +} + +func (rc *contextCancelReadCloser) Read(p []byte) (n int, err error) { + return rc.body.Read(p) +} + +func (rc *contextCancelReadCloser) Close() error { + err := rc.body.Close() + rc.cf() + return err +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_sas_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_sas_credential.go new file mode 100644 index 000000000..ebe2b7772 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_sas_credential.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// SASCredentialPolicy authorizes requests with a [azcore.SASCredential]. +type SASCredentialPolicy struct { + cred *exported.SASCredential + header string +} + +// SASCredentialPolicyOptions contains the optional values configuring [SASCredentialPolicy]. +type SASCredentialPolicyOptions struct { + // placeholder for future optional values +} + +// NewSASCredentialPolicy creates a new instance of [SASCredentialPolicy]. +// - cred is the [azcore.SASCredential] used to authenticate with the service +// - header is the name of the HTTP request header in which the shared access signature is placed +// - options contains optional configuration, pass nil to accept the default values +func NewSASCredentialPolicy(cred *exported.SASCredential, header string, options *SASCredentialPolicyOptions) *SASCredentialPolicy { + return &SASCredentialPolicy{ + cred: cred, + header: header, + } +} + +// Do implementes the Do method on the [policy.Polilcy] interface. +func (k *SASCredentialPolicy) Do(req *policy.Request) (*http.Response, error) { + // skip adding the authorization header if no SASCredential was provided. + // this prevents a panic that might be hard to diagnose and allows testing + // against http endpoints that don't require authentication. + if k.cred != nil { + if err := checkHTTPSForAuth(req); err != nil { + return nil, err + } + req.Raw().Header.Add(k.header, exported.SASCredentialGet(k.cred)) + } + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_telemetry.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_telemetry.go new file mode 100644 index 000000000..80a903546 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_telemetry.go @@ -0,0 +1,83 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "fmt" + "net/http" + "os" + "runtime" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +type telemetryPolicy struct { + telemetryValue string +} + +// NewTelemetryPolicy creates a telemetry policy object that adds telemetry information to outgoing HTTP requests. +// The format is [ ]azsdk-go-/ . +// Pass nil to accept the default values; this is the same as passing a zero-value options. +func NewTelemetryPolicy(mod, ver string, o *policy.TelemetryOptions) policy.Policy { + if o == nil { + o = &policy.TelemetryOptions{} + } + tp := telemetryPolicy{} + if o.Disabled { + return &tp + } + b := &bytes.Buffer{} + // normalize ApplicationID + if o.ApplicationID != "" { + o.ApplicationID = strings.ReplaceAll(o.ApplicationID, " ", "/") + if len(o.ApplicationID) > 24 { + o.ApplicationID = o.ApplicationID[:24] + } + b.WriteString(o.ApplicationID) + b.WriteRune(' ') + } + // mod might be the fully qualified name. in that case, we just want the package name + if i := strings.LastIndex(mod, "/"); i > -1 { + mod = mod[i+1:] + } + b.WriteString(formatTelemetry(mod, ver)) + b.WriteRune(' ') + b.WriteString(platformInfo) + tp.telemetryValue = b.String() + return &tp +} + +func formatTelemetry(comp, ver string) string { + return fmt.Sprintf("azsdk-go-%s/%s", comp, ver) +} + +func (p telemetryPolicy) Do(req *policy.Request) (*http.Response, error) { + if p.telemetryValue == "" { + return req.Next() + } + // preserve the existing User-Agent string + if ua := req.Raw().Header.Get(shared.HeaderUserAgent); ua != "" { + p.telemetryValue = fmt.Sprintf("%s %s", p.telemetryValue, ua) + } + req.Raw().Header.Set(shared.HeaderUserAgent, p.telemetryValue) + return req.Next() +} + +// NOTE: the ONLY function that should write to this variable is this func +var platformInfo = func() string { + operatingSystem := runtime.GOOS // Default OS string + switch operatingSystem { + case "windows": + operatingSystem = os.Getenv("OS") // Get more specific OS information + case "linux": // accept default OS info + case "freebsd": // accept default OS info + } + return fmt.Sprintf("(%s; %s)", runtime.Version(), operatingSystem) +}() diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/poller.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/poller.go new file mode 100644 index 000000000..c373f6896 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/poller.go @@ -0,0 +1,384 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "net/http" + "reflect" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" + "github.com/Azure/azure-sdk-for-go/sdk/internal/poller" +) + +// FinalStateVia is the enumerated type for the possible final-state-via values. +type FinalStateVia = pollers.FinalStateVia + +const ( + // FinalStateViaAzureAsyncOp indicates the final payload comes from the Azure-AsyncOperation URL. + FinalStateViaAzureAsyncOp = pollers.FinalStateViaAzureAsyncOp + + // FinalStateViaLocation indicates the final payload comes from the Location URL. + FinalStateViaLocation = pollers.FinalStateViaLocation + + // FinalStateViaOriginalURI indicates the final payload comes from the original URL. + FinalStateViaOriginalURI = pollers.FinalStateViaOriginalURI + + // FinalStateViaOpLocation indicates the final payload comes from the Operation-Location URL. + FinalStateViaOpLocation = pollers.FinalStateViaOpLocation +) + +// NewPollerOptions contains the optional parameters for NewPoller. +type NewPollerOptions[T any] struct { + // FinalStateVia contains the final-state-via value for the LRO. + FinalStateVia FinalStateVia + + // Response contains a preconstructed response type. + // The final payload will be unmarshaled into it and returned. + Response *T + + // Handler[T] contains a custom polling implementation. + Handler PollingHandler[T] + + // Tracer contains the Tracer from the client that's creating the Poller. + Tracer tracing.Tracer +} + +// NewPoller creates a Poller based on the provided initial response. +func NewPoller[T any](resp *http.Response, pl exported.Pipeline, options *NewPollerOptions[T]) (*Poller[T], error) { + if options == nil { + options = &NewPollerOptions[T]{} + } + result := options.Response + if result == nil { + result = new(T) + } + if options.Handler != nil { + return &Poller[T]{ + op: options.Handler, + resp: resp, + result: result, + tracer: options.Tracer, + }, nil + } + + defer resp.Body.Close() + // this is a back-stop in case the swagger is incorrect (i.e. missing one or more status codes for success). + // ideally the codegen should return an error if the initial response failed and not even create a poller. + if !poller.StatusCodeValid(resp) { + return nil, errors.New("the operation failed or was cancelled") + } + + // determine the polling method + var opr PollingHandler[T] + var err error + if fake.Applicable(resp) { + opr, err = fake.New[T](pl, resp) + } else if async.Applicable(resp) { + // async poller must be checked first as it can also have a location header + opr, err = async.New[T](pl, resp, options.FinalStateVia) + } else if op.Applicable(resp) { + // op poller must be checked before loc as it can also have a location header + opr, err = op.New[T](pl, resp, options.FinalStateVia) + } else if loc.Applicable(resp) { + opr, err = loc.New[T](pl, resp) + } else if body.Applicable(resp) { + // must test body poller last as it's a subset of the other pollers. + // TODO: this is ambiguous for PATCH/PUT if it returns a 200 with no polling headers (sync completion) + opr, err = body.New[T](pl, resp) + } else if m := resp.Request.Method; resp.StatusCode == http.StatusAccepted && (m == http.MethodDelete || m == http.MethodPost) { + // if we get here it means we have a 202 with no polling headers. + // for DELETE and POST this is a hard error per ARM RPC spec. + return nil, errors.New("response is missing polling URL") + } else { + opr, err = pollers.NewNopPoller[T](resp) + } + + if err != nil { + return nil, err + } + return &Poller[T]{ + op: opr, + resp: resp, + result: result, + tracer: options.Tracer, + }, nil +} + +// NewPollerFromResumeTokenOptions contains the optional parameters for NewPollerFromResumeToken. +type NewPollerFromResumeTokenOptions[T any] struct { + // Response contains a preconstructed response type. + // The final payload will be unmarshaled into it and returned. + Response *T + + // Handler[T] contains a custom polling implementation. + Handler PollingHandler[T] + + // Tracer contains the Tracer from the client that's creating the Poller. + Tracer tracing.Tracer +} + +// NewPollerFromResumeToken creates a Poller from a resume token string. +func NewPollerFromResumeToken[T any](token string, pl exported.Pipeline, options *NewPollerFromResumeTokenOptions[T]) (*Poller[T], error) { + if options == nil { + options = &NewPollerFromResumeTokenOptions[T]{} + } + result := options.Response + if result == nil { + result = new(T) + } + + if err := pollers.IsTokenValid[T](token); err != nil { + return nil, err + } + raw, err := pollers.ExtractToken(token) + if err != nil { + return nil, err + } + var asJSON map[string]interface{} + if err := json.Unmarshal(raw, &asJSON); err != nil { + return nil, err + } + + opr := options.Handler + // now rehydrate the poller based on the encoded poller type + if fake.CanResume(asJSON) { + opr, _ = fake.New[T](pl, nil) + } else if opr != nil { + log.Writef(log.EventLRO, "Resuming custom poller %T.", opr) + } else if async.CanResume(asJSON) { + opr, _ = async.New[T](pl, nil, "") + } else if body.CanResume(asJSON) { + opr, _ = body.New[T](pl, nil) + } else if loc.CanResume(asJSON) { + opr, _ = loc.New[T](pl, nil) + } else if op.CanResume(asJSON) { + opr, _ = op.New[T](pl, nil, "") + } else { + return nil, fmt.Errorf("unhandled poller token %s", string(raw)) + } + if err := json.Unmarshal(raw, &opr); err != nil { + return nil, err + } + return &Poller[T]{ + op: opr, + result: result, + tracer: options.Tracer, + }, nil +} + +// PollingHandler[T] abstracts the differences among poller implementations. +type PollingHandler[T any] interface { + // Done returns true if the LRO has reached a terminal state. + Done() bool + + // Poll fetches the latest state of the LRO. + Poll(context.Context) (*http.Response, error) + + // Result is called once the LRO has reached a terminal state. It populates the out parameter + // with the result of the operation. + Result(ctx context.Context, out *T) error +} + +// Poller encapsulates a long-running operation, providing polling facilities until the operation reaches a terminal state. +type Poller[T any] struct { + op PollingHandler[T] + resp *http.Response + err error + result *T + tracer tracing.Tracer + done bool +} + +// PollUntilDoneOptions contains the optional values for the Poller[T].PollUntilDone() method. +type PollUntilDoneOptions struct { + // Frequency is the time to wait between polling intervals in absence of a Retry-After header. Allowed minimum is one second. + // Pass zero to accept the default value (30s). + Frequency time.Duration +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached, an error is received, or the context expires. +// It internally uses Poll(), Done(), and Result() in its polling loop, sleeping for the specified duration between intervals. +// options: pass nil to accept the default values. +// NOTE: the default polling frequency is 30 seconds which works well for most operations. However, some operations might +// benefit from a shorter or longer duration. +func (p *Poller[T]) PollUntilDone(ctx context.Context, options *PollUntilDoneOptions) (res T, err error) { + if options == nil { + options = &PollUntilDoneOptions{} + } + cp := *options + if cp.Frequency == 0 { + cp.Frequency = 30 * time.Second + } + + ctx, endSpan := StartSpan(ctx, fmt.Sprintf("%s.PollUntilDone", shortenTypeName(reflect.TypeOf(*p).Name())), p.tracer, nil) + defer func() { endSpan(err) }() + + // skip the floor check when executing tests so they don't take so long + if isTest := flag.Lookup("test.v"); isTest == nil && cp.Frequency < time.Second { + err = errors.New("polling frequency minimum is one second") + return + } + + start := time.Now() + logPollUntilDoneExit := func(v interface{}) { + log.Writef(log.EventLRO, "END PollUntilDone() for %T: %v, total time: %s", p.op, v, time.Since(start)) + } + log.Writef(log.EventLRO, "BEGIN PollUntilDone() for %T", p.op) + if p.resp != nil { + // initial check for a retry-after header existing on the initial response + if retryAfter := shared.RetryAfter(p.resp); retryAfter > 0 { + log.Writef(log.EventLRO, "initial Retry-After delay for %s", retryAfter.String()) + if err = shared.Delay(ctx, retryAfter); err != nil { + logPollUntilDoneExit(err) + return + } + } + } + // begin polling the endpoint until a terminal state is reached + for { + var resp *http.Response + resp, err = p.Poll(ctx) + if err != nil { + logPollUntilDoneExit(err) + return + } + if p.Done() { + logPollUntilDoneExit("succeeded") + res, err = p.Result(ctx) + return + } + d := cp.Frequency + if retryAfter := shared.RetryAfter(resp); retryAfter > 0 { + log.Writef(log.EventLRO, "Retry-After delay for %s", retryAfter.String()) + d = retryAfter + } else { + log.Writef(log.EventLRO, "delay for %s", d.String()) + } + if err = shared.Delay(ctx, d); err != nil { + logPollUntilDoneExit(err) + return + } + } +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If Poll succeeds, the poller's state is updated and the HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the last HTTP response. +func (p *Poller[T]) Poll(ctx context.Context) (resp *http.Response, err error) { + if p.Done() { + // the LRO has reached a terminal state, don't poll again + resp = p.resp + return + } + + ctx, endSpan := StartSpan(ctx, fmt.Sprintf("%s.Poll", shortenTypeName(reflect.TypeOf(*p).Name())), p.tracer, nil) + defer func() { endSpan(err) }() + + resp, err = p.op.Poll(ctx) + if err != nil { + return + } + p.resp = resp + return +} + +// Done returns true if the LRO has reached a terminal state. +// Once a terminal state is reached, call Result(). +func (p *Poller[T]) Done() bool { + return p.op.Done() +} + +// Result returns the result of the LRO and is meant to be used in conjunction with Poll and Done. +// If the LRO completed successfully, a populated instance of T is returned. +// If the LRO failed or was canceled, an *azcore.ResponseError error is returned. +// Calling this on an LRO in a non-terminal state will return an error. +func (p *Poller[T]) Result(ctx context.Context) (res T, err error) { + if !p.Done() { + err = errors.New("poller is in a non-terminal state") + return + } + if p.done { + // the result has already been retrieved, return the cached value + if p.err != nil { + err = p.err + return + } + res = *p.result + return + } + + ctx, endSpan := StartSpan(ctx, fmt.Sprintf("%s.Result", shortenTypeName(reflect.TypeOf(*p).Name())), p.tracer, nil) + defer func() { endSpan(err) }() + + err = p.op.Result(ctx, p.result) + var respErr *exported.ResponseError + if errors.As(err, &respErr) { + // the LRO failed. record the error + p.err = err + } else if err != nil { + // the call to Result failed, don't cache anything in this case + return + } + p.done = true + if p.err != nil { + err = p.err + return + } + res = *p.result + return +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +// The token's format should be considered opaque and is subject to change. +// Calling this on an LRO in a terminal state will return an error. +func (p *Poller[T]) ResumeToken() (string, error) { + if p.Done() { + return "", errors.New("poller is in a terminal state") + } + tk, err := pollers.NewResumeToken[T](p.op) + if err != nil { + return "", err + } + return tk, err +} + +// extracts the type name from the string returned from reflect.Value.Name() +func shortenTypeName(s string) string { + // the value is formatted as follows + // Poller[module/Package.Type].Method + // we want to shorten the generic type parameter string to Type + // anything we don't recognize will be left as-is + begin := strings.Index(s, "[") + end := strings.Index(s, "]") + if begin == -1 || end == -1 { + return s + } + + typeName := s[begin+1 : end] + if i := strings.LastIndex(typeName, "."); i > -1 { + typeName = typeName[i+1:] + } + return s[:begin+1] + typeName + s[end:] +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go new file mode 100644 index 000000000..e97223da2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go @@ -0,0 +1,177 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "mime/multipart" + "net/url" + "path" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// Base64Encoding is usesd to specify which base-64 encoder/decoder to use when +// encoding/decoding a slice of bytes to/from a string. +type Base64Encoding = exported.Base64Encoding + +const ( + // Base64StdFormat uses base64.StdEncoding for encoding and decoding payloads. + Base64StdFormat Base64Encoding = exported.Base64StdFormat + + // Base64URLFormat uses base64.RawURLEncoding for encoding and decoding payloads. + Base64URLFormat Base64Encoding = exported.Base64URLFormat +) + +// NewRequest creates a new policy.Request with the specified input. +// The endpoint MUST be properly encoded before calling this function. +func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*policy.Request, error) { + return exported.NewRequest(ctx, httpMethod, endpoint) +} + +// EncodeQueryParams will parse and encode any query parameters in the specified URL. +func EncodeQueryParams(u string) (string, error) { + before, after, found := strings.Cut(u, "?") + if !found { + return u, nil + } + qp, err := url.ParseQuery(after) + if err != nil { + return "", err + } + return before + "?" + qp.Encode(), nil +} + +// JoinPaths concatenates multiple URL path segments into one path, +// inserting path separation characters as required. JoinPaths will preserve +// query parameters in the root path +func JoinPaths(root string, paths ...string) string { + if len(paths) == 0 { + return root + } + + qps := "" + if strings.Contains(root, "?") { + splitPath := strings.Split(root, "?") + root, qps = splitPath[0], splitPath[1] + } + + p := path.Join(paths...) + // path.Join will remove any trailing slashes. + // if one was provided, preserve it. + if strings.HasSuffix(paths[len(paths)-1], "/") && !strings.HasSuffix(p, "/") { + p += "/" + } + + if qps != "" { + p = p + "?" + qps + } + + if strings.HasSuffix(root, "/") && strings.HasPrefix(p, "/") { + root = root[:len(root)-1] + } else if !strings.HasSuffix(root, "/") && !strings.HasPrefix(p, "/") { + p = "/" + p + } + return root + p +} + +// EncodeByteArray will base-64 encode the byte slice v. +func EncodeByteArray(v []byte, format Base64Encoding) string { + return exported.EncodeByteArray(v, format) +} + +// MarshalAsByteArray will base-64 encode the byte slice v, then calls SetBody. +// The encoded value is treated as a JSON string. +func MarshalAsByteArray(req *policy.Request, v []byte, format Base64Encoding) error { + // send as a JSON string + encode := fmt.Sprintf("\"%s\"", EncodeByteArray(v, format)) + return req.SetBody(exported.NopCloser(strings.NewReader(encode)), shared.ContentTypeAppJSON) +} + +// MarshalAsJSON calls json.Marshal() to get the JSON encoding of v then calls SetBody. +func MarshalAsJSON(req *policy.Request, v interface{}) error { + b, err := json.Marshal(v) + if err != nil { + return fmt.Errorf("error marshalling type %T: %s", v, err) + } + return req.SetBody(exported.NopCloser(bytes.NewReader(b)), shared.ContentTypeAppJSON) +} + +// MarshalAsXML calls xml.Marshal() to get the XML encoding of v then calls SetBody. +func MarshalAsXML(req *policy.Request, v interface{}) error { + b, err := xml.Marshal(v) + if err != nil { + return fmt.Errorf("error marshalling type %T: %s", v, err) + } + // inclue the XML header as some services require it + b = []byte(xml.Header + string(b)) + return req.SetBody(exported.NopCloser(bytes.NewReader(b)), shared.ContentTypeAppXML) +} + +// SetMultipartFormData writes the specified keys/values as multi-part form +// fields with the specified value. File content must be specified as a ReadSeekCloser. +// All other values are treated as string values. +func SetMultipartFormData(req *policy.Request, formData map[string]interface{}) error { + body := bytes.Buffer{} + writer := multipart.NewWriter(&body) + + writeContent := func(fieldname, filename string, src io.Reader) error { + fd, err := writer.CreateFormFile(fieldname, filename) + if err != nil { + return err + } + // copy the data to the form file + if _, err = io.Copy(fd, src); err != nil { + return err + } + return nil + } + + for k, v := range formData { + if rsc, ok := v.(io.ReadSeekCloser); ok { + if err := writeContent(k, k, rsc); err != nil { + return err + } + continue + } else if rscs, ok := v.([]io.ReadSeekCloser); ok { + for _, rsc := range rscs { + if err := writeContent(k, k, rsc); err != nil { + return err + } + } + continue + } + // ensure the value is in string format + s, ok := v.(string) + if !ok { + s = fmt.Sprintf("%v", v) + } + if err := writer.WriteField(k, s); err != nil { + return err + } + } + if err := writer.Close(); err != nil { + return err + } + return req.SetBody(exported.NopCloser(bytes.NewReader(body.Bytes())), writer.FormDataContentType()) +} + +// SkipBodyDownload will disable automatic downloading of the response body. +func SkipBodyDownload(req *policy.Request) { + req.SetOperationValue(bodyDownloadPolicyOpValues{Skip: true}) +} + +// CtxAPINameKey is used as a context key for adding/retrieving the API name. +type CtxAPINameKey = shared.CtxAPINameKey diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/response.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/response.go new file mode 100644 index 000000000..003c875b1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/response.go @@ -0,0 +1,109 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/http" + + azexported "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/internal/exported" +) + +// Payload reads and returns the response body or an error. +// On a successful read, the response body is cached. +// Subsequent reads will access the cached value. +func Payload(resp *http.Response) ([]byte, error) { + return exported.Payload(resp, nil) +} + +// HasStatusCode returns true if the Response's status code is one of the specified values. +func HasStatusCode(resp *http.Response, statusCodes ...int) bool { + return exported.HasStatusCode(resp, statusCodes...) +} + +// UnmarshalAsByteArray will base-64 decode the received payload and place the result into the value pointed to by v. +func UnmarshalAsByteArray(resp *http.Response, v *[]byte, format Base64Encoding) error { + p, err := Payload(resp) + if err != nil { + return err + } + return DecodeByteArray(string(p), v, format) +} + +// UnmarshalAsJSON calls json.Unmarshal() to unmarshal the received payload into the value pointed to by v. +func UnmarshalAsJSON(resp *http.Response, v interface{}) error { + payload, err := Payload(resp) + if err != nil { + return err + } + // TODO: verify early exit is correct + if len(payload) == 0 { + return nil + } + err = removeBOM(resp) + if err != nil { + return err + } + err = json.Unmarshal(payload, v) + if err != nil { + err = fmt.Errorf("unmarshalling type %T: %s", v, err) + } + return err +} + +// UnmarshalAsXML calls xml.Unmarshal() to unmarshal the received payload into the value pointed to by v. +func UnmarshalAsXML(resp *http.Response, v interface{}) error { + payload, err := Payload(resp) + if err != nil { + return err + } + // TODO: verify early exit is correct + if len(payload) == 0 { + return nil + } + err = removeBOM(resp) + if err != nil { + return err + } + err = xml.Unmarshal(payload, v) + if err != nil { + err = fmt.Errorf("unmarshalling type %T: %s", v, err) + } + return err +} + +// Drain reads the response body to completion then closes it. The bytes read are discarded. +func Drain(resp *http.Response) { + if resp != nil && resp.Body != nil { + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } +} + +// removeBOM removes any byte-order mark prefix from the payload if present. +func removeBOM(resp *http.Response) error { + _, err := exported.Payload(resp, &exported.PayloadOptions{ + BytesModifier: func(b []byte) []byte { + // UTF8 + return bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")) + }, + }) + if err != nil { + return err + } + return nil +} + +// DecodeByteArray will base-64 decode the provided string into v. +func DecodeByteArray(s string, v *[]byte, format Base64Encoding) error { + return azexported.DecodeByteArray(s, v, format) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_dialer_other.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_dialer_other.go new file mode 100644 index 000000000..1c75d771f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_dialer_other.go @@ -0,0 +1,15 @@ +//go:build !wasm + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "net" +) + +func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { + return dialer.DialContext +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_dialer_wasm.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_dialer_wasm.go new file mode 100644 index 000000000..3dc9eeecd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_dialer_wasm.go @@ -0,0 +1,15 @@ +//go:build (js && wasm) || wasip1 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "net" +) + +func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_http_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_http_client.go new file mode 100644 index 000000000..2124c1d48 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_http_client.go @@ -0,0 +1,48 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "crypto/tls" + "net" + "net/http" + "time" + + "golang.org/x/net/http2" +) + +var defaultHTTPClient *http.Client + +func init() { + defaultTransport := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: defaultTransportDialContext(&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }), + ForceAttemptHTTP2: true, + MaxIdleConns: 100, + MaxIdleConnsPerHost: 10, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + Renegotiation: tls.RenegotiateFreelyAsClient, + }, + } + // TODO: evaluate removing this once https://github.com/golang/go/issues/59690 has been fixed + if http2Transport, err := http2.ConfigureTransports(defaultTransport); err == nil { + // if the connection has been idle for 10 seconds, send a ping frame for a health check + http2Transport.ReadIdleTimeout = 10 * time.Second + // if there's no response to the ping within the timeout, the connection will be closed + http2Transport.PingTimeout = 5 * time.Second + } + defaultHTTPClient = &http.Client{ + Transport: defaultTransport, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/doc.go new file mode 100644 index 000000000..cadaef3d5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/doc.go @@ -0,0 +1,9 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package streaming contains helpers for streaming IO operations and progress reporting. +package streaming diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/progress.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/progress.go new file mode 100644 index 000000000..fbcd48311 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/progress.go @@ -0,0 +1,75 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package streaming + +import ( + "io" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" +) + +type progress struct { + rc io.ReadCloser + rsc io.ReadSeekCloser + pr func(bytesTransferred int64) + offset int64 +} + +// NopCloser returns a ReadSeekCloser with a no-op close method wrapping the provided io.ReadSeeker. +// In addition to adding a Close method to an io.ReadSeeker, this can also be used to wrap an +// io.ReadSeekCloser with a no-op Close method to allow explicit control of when the io.ReedSeekCloser +// has its underlying stream closed. +func NopCloser(rs io.ReadSeeker) io.ReadSeekCloser { + return exported.NopCloser(rs) +} + +// NewRequestProgress adds progress reporting to an HTTP request's body stream. +func NewRequestProgress(body io.ReadSeekCloser, pr func(bytesTransferred int64)) io.ReadSeekCloser { + return &progress{ + rc: body, + rsc: body, + pr: pr, + offset: 0, + } +} + +// NewResponseProgress adds progress reporting to an HTTP response's body stream. +func NewResponseProgress(body io.ReadCloser, pr func(bytesTransferred int64)) io.ReadCloser { + return &progress{ + rc: body, + rsc: nil, + pr: pr, + offset: 0, + } +} + +// Read reads a block of data from an inner stream and reports progress +func (p *progress) Read(b []byte) (n int, err error) { + n, err = p.rc.Read(b) + if err != nil && err != io.EOF { + return + } + p.offset += int64(n) + // Invokes the user's callback method to report progress + p.pr(p.offset) + return +} + +// Seek only expects a zero or from beginning. +func (p *progress) Seek(offset int64, whence int) (int64, error) { + // This should only ever be called with offset = 0 and whence = io.SeekStart + n, err := p.rsc.Seek(offset, whence) + if err == nil { + p.offset = int64(n) + } + return n, err +} + +// requestBodyProgress supports Close but the underlying stream may not; if it does, Close will close it. +func (p *progress) Close() error { + return p.rc.Close() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/to/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/to/doc.go new file mode 100644 index 000000000..faa98c9dc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/to/doc.go @@ -0,0 +1,9 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package to contains various type-conversion helper functions. +package to diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/to/to.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/to/to.go new file mode 100644 index 000000000..e0e4817b9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/to/to.go @@ -0,0 +1,21 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package to + +// Ptr returns a pointer to the provided value. +func Ptr[T any](v T) *T { + return &v +} + +// SliceOfPtrs returns a slice of *T from the specified values. +func SliceOfPtrs[T any](vv ...T) []*T { + slc := make([]*T, len(vv)) + for i := range vv { + slc[i] = Ptr(vv[i]) + } + return slc +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/constants.go new file mode 100644 index 000000000..80282d4ab --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/constants.go @@ -0,0 +1,41 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package tracing + +// SpanKind represents the role of a Span inside a Trace. Often, this defines how a Span will be processed and visualized by various backends. +type SpanKind int + +const ( + // SpanKindInternal indicates the span represents an internal operation within an application. + SpanKindInternal SpanKind = 1 + + // SpanKindServer indicates the span covers server-side handling of a request. + SpanKindServer SpanKind = 2 + + // SpanKindClient indicates the span describes a request to a remote service. + SpanKindClient SpanKind = 3 + + // SpanKindProducer indicates the span was created by a messaging producer. + SpanKindProducer SpanKind = 4 + + // SpanKindConsumer indicates the span was created by a messaging consumer. + SpanKindConsumer SpanKind = 5 +) + +// SpanStatus represents the status of a span. +type SpanStatus int + +const ( + // SpanStatusUnset is the default status code. + SpanStatusUnset SpanStatus = 0 + + // SpanStatusError indicates the operation contains an error. + SpanStatusError SpanStatus = 1 + + // SpanStatusOK indicates the operation completed successfully. + SpanStatusOK SpanStatus = 2 +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/tracing.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/tracing.go new file mode 100644 index 000000000..1ade7c560 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/tracing.go @@ -0,0 +1,191 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Package tracing contains the definitions needed to support distributed tracing. +package tracing + +import ( + "context" +) + +// ProviderOptions contains the optional values when creating a Provider. +type ProviderOptions struct { + // for future expansion +} + +// NewProvider creates a new Provider with the specified values. +// - newTracerFn is the underlying implementation for creating Tracer instances +// - options contains optional values; pass nil to accept the default value +func NewProvider(newTracerFn func(name, version string) Tracer, options *ProviderOptions) Provider { + return Provider{ + newTracerFn: newTracerFn, + } +} + +// Provider is the factory that creates Tracer instances. +// It defaults to a no-op provider. +type Provider struct { + newTracerFn func(name, version string) Tracer +} + +// NewTracer creates a new Tracer for the specified module name and version. +// - module - the fully qualified name of the module +// - version - the version of the module +func (p Provider) NewTracer(module, version string) (tracer Tracer) { + if p.newTracerFn != nil { + tracer = p.newTracerFn(module, version) + } + return +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// TracerOptions contains the optional values when creating a Tracer. +type TracerOptions struct { + // SpanFromContext contains the implementation for the Tracer.SpanFromContext method. + SpanFromContext func(context.Context) Span +} + +// NewTracer creates a Tracer with the specified values. +// - newSpanFn is the underlying implementation for creating Span instances +// - options contains optional values; pass nil to accept the default value +func NewTracer(newSpanFn func(ctx context.Context, spanName string, options *SpanOptions) (context.Context, Span), options *TracerOptions) Tracer { + if options == nil { + options = &TracerOptions{} + } + return Tracer{ + newSpanFn: newSpanFn, + spanFromContextFn: options.SpanFromContext, + } +} + +// Tracer is the factory that creates Span instances. +type Tracer struct { + attrs []Attribute + newSpanFn func(ctx context.Context, spanName string, options *SpanOptions) (context.Context, Span) + spanFromContextFn func(ctx context.Context) Span +} + +// Start creates a new span and a context.Context that contains it. +// - ctx is the parent context for this span. If it contains a Span, the newly created span will be a child of that span, else it will be a root span +// - spanName identifies the span within a trace, it's typically the fully qualified API name +// - options contains optional values for the span, pass nil to accept any defaults +func (t Tracer) Start(ctx context.Context, spanName string, options *SpanOptions) (context.Context, Span) { + if t.newSpanFn != nil { + opts := SpanOptions{} + if options != nil { + opts = *options + } + opts.Attributes = append(opts.Attributes, t.attrs...) + return t.newSpanFn(ctx, spanName, &opts) + } + return ctx, Span{} +} + +// SetAttributes sets attrs to be applied to each Span. If a key from attrs +// already exists for an attribute of the Span it will be overwritten with +// the value contained in attrs. +func (t *Tracer) SetAttributes(attrs ...Attribute) { + t.attrs = append(t.attrs, attrs...) +} + +// Enabled returns true if this Tracer is capable of creating Spans. +func (t Tracer) Enabled() bool { + return t.newSpanFn != nil +} + +// SpanFromContext returns the Span associated with the current context. +// If the provided context has no Span, false is returned. +func (t Tracer) SpanFromContext(ctx context.Context) Span { + if t.spanFromContextFn != nil { + return t.spanFromContextFn(ctx) + } + return Span{} +} + +// SpanOptions contains optional settings for creating a span. +type SpanOptions struct { + // Kind indicates the kind of Span. + Kind SpanKind + + // Attributes contains key-value pairs of attributes for the span. + Attributes []Attribute +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// SpanImpl abstracts the underlying implementation for Span, +// allowing it to work with various tracing implementations. +// Any zero-values will have their default, no-op behavior. +type SpanImpl struct { + // End contains the implementation for the Span.End method. + End func() + + // SetAttributes contains the implementation for the Span.SetAttributes method. + SetAttributes func(...Attribute) + + // AddEvent contains the implementation for the Span.AddEvent method. + AddEvent func(string, ...Attribute) + + // SetStatus contains the implementation for the Span.SetStatus method. + SetStatus func(SpanStatus, string) +} + +// NewSpan creates a Span with the specified implementation. +func NewSpan(impl SpanImpl) Span { + return Span{ + impl: impl, + } +} + +// Span is a single unit of a trace. A trace can contain multiple spans. +// A zero-value Span provides a no-op implementation. +type Span struct { + impl SpanImpl +} + +// End terminates the span and MUST be called before the span leaves scope. +// Any further updates to the span will be ignored after End is called. +func (s Span) End() { + if s.impl.End != nil { + s.impl.End() + } +} + +// SetAttributes sets the specified attributes on the Span. +// Any existing attributes with the same keys will have their values overwritten. +func (s Span) SetAttributes(attrs ...Attribute) { + if s.impl.SetAttributes != nil { + s.impl.SetAttributes(attrs...) + } +} + +// AddEvent adds a named event with an optional set of attributes to the span. +func (s Span) AddEvent(name string, attrs ...Attribute) { + if s.impl.AddEvent != nil { + s.impl.AddEvent(name, attrs...) + } +} + +// SetStatus sets the status on the span along with a description. +func (s Span) SetStatus(code SpanStatus, desc string) { + if s.impl.SetStatus != nil { + s.impl.SetStatus(code, desc) + } +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Attribute is a key-value pair. +type Attribute struct { + // Key is the name of the attribute. + Key string + + // Value is the attribute's value. + // Types that are natively supported include int64, float64, int, bool, string. + // Any other type will be formatted per rules of fmt.Sprintf("%v"). + Value any +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md new file mode 100644 index 000000000..71dcb5f3e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md @@ -0,0 +1,490 @@ +# Release History + +## 1.5.1 (2024-01-17) + +### Bugs Fixed +* `InteractiveBrowserCredential` handles `AdditionallyAllowedTenants` correctly + +## 1.5.0 (2024-01-16) + +### Breaking Changes +> These changes affect only code written against a beta version such as v1.5.0-beta.1 +* Removed persistent token caching. It will return in v1.6.0-beta.1 + +### Bugs Fixed +* Credentials now preserve MSAL headers e.g. X-Client-Sku + +### Other Changes +* Upgraded dependencies + +## 1.5.0-beta.2 (2023-11-07) + +### Features Added +* `DefaultAzureCredential` and `ManagedIdentityCredential` support Azure ML managed identity +* Added spans for distributed tracing. + +## 1.5.0-beta.1 (2023-10-10) + +### Features Added +* Optional persistent token caching for most credentials. Set `TokenCachePersistenceOptions` + on a credential's options to enable and configure this. See the package documentation for + this version and [TOKEN_CACHING.md](https://aka.ms/azsdk/go/identity/caching) for more + details. +* `AzureDeveloperCLICredential` authenticates with the Azure Developer CLI (`azd`). This + credential is also part of the `DefaultAzureCredential` authentication flow. + +## 1.4.0 (2023-10-10) + +### Bugs Fixed +* `ManagedIdentityCredential` will now retry when IMDS responds 410 or 503 + +## 1.4.0-beta.5 (2023-09-12) + +### Features Added +* Service principal credentials can request CAE tokens + +### Breaking Changes +> These changes affect only code written against a beta version such as v1.4.0-beta.4 +* Whether `GetToken` requests a CAE token is now determined by `TokenRequestOptions.EnableCAE`. Azure + SDK clients which support CAE will set this option automatically. Credentials no longer request CAE + tokens by default or observe the environment variable "AZURE_IDENTITY_DISABLE_CP1". + +### Bugs Fixed +* Credential chains such as `DefaultAzureCredential` now try their next credential, if any, when + managed identity authentication fails in a Docker Desktop container + ([#21417](https://github.com/Azure/azure-sdk-for-go/issues/21417)) + +## 1.4.0-beta.4 (2023-08-16) + +### Other Changes +* Upgraded dependencies + +## 1.3.1 (2023-08-16) + +### Other Changes +* Upgraded dependencies + +## 1.4.0-beta.3 (2023-08-08) + +### Bugs Fixed +* One invocation of `AzureCLICredential.GetToken()` and `OnBehalfOfCredential.GetToken()` + can no longer make two authentication attempts + +## 1.4.0-beta.2 (2023-07-14) + +### Other Changes +* `DefaultAzureCredentialOptions.TenantID` applies to workload identity authentication +* Upgraded dependencies + +## 1.4.0-beta.1 (2023-06-06) + +### Other Changes +* Re-enabled CAE support as in v1.3.0-beta.3 + +## 1.3.0 (2023-05-09) + +### Breaking Changes +> These changes affect only code written against a beta version such as v1.3.0-beta.5 +* Renamed `NewOnBehalfOfCredentialFromCertificate` to `NewOnBehalfOfCredentialWithCertificate` +* Renamed `NewOnBehalfOfCredentialFromSecret` to `NewOnBehalfOfCredentialWithSecret` + +### Other Changes +* Upgraded to MSAL v1.0.0 + +## 1.3.0-beta.5 (2023-04-11) + +### Breaking Changes +> These changes affect only code written against a beta version such as v1.3.0-beta.4 +* Moved `NewWorkloadIdentityCredential()` parameters into `WorkloadIdentityCredentialOptions`. + The constructor now reads default configuration from environment variables set by the Azure + workload identity webhook by default. + ([#20478](https://github.com/Azure/azure-sdk-for-go/pull/20478)) +* Removed CAE support. It will return in v1.4.0-beta.1 + ([#20479](https://github.com/Azure/azure-sdk-for-go/pull/20479)) + +### Bugs Fixed +* Fixed an issue in `DefaultAzureCredential` that could cause the managed identity endpoint check to fail in rare circumstances. + +## 1.3.0-beta.4 (2023-03-08) + +### Features Added +* Added `WorkloadIdentityCredentialOptions.AdditionallyAllowedTenants` and `.DisableInstanceDiscovery` + +### Bugs Fixed +* Credentials now synchronize within `GetToken()` so a single instance can be shared among goroutines + ([#20044](https://github.com/Azure/azure-sdk-for-go/issues/20044)) + +### Other Changes +* Upgraded dependencies + +## 1.2.2 (2023-03-07) + +### Other Changes +* Upgraded dependencies + +## 1.3.0-beta.3 (2023-02-07) + +### Features Added +* By default, credentials set client capability "CP1" to enable support for + [Continuous Access Evaluation (CAE)](https://docs.microsoft.com/azure/active-directory/develop/app-resilience-continuous-access-evaluation). + This indicates to Microsoft Entra ID that your application can handle CAE claims challenges. + You can disable this behavior by setting the environment variable "AZURE_IDENTITY_DISABLE_CP1" to "true". +* `InteractiveBrowserCredentialOptions.LoginHint` enables pre-populating the login + prompt with a username ([#15599](https://github.com/Azure/azure-sdk-for-go/pull/15599)) +* Service principal and user credentials support ADFS authentication on Azure Stack. + Specify "adfs" as the credential's tenant. +* Applications running in private or disconnected clouds can prevent credentials from + requesting Microsoft Entra instance metadata by setting the `DisableInstanceDiscovery` + field on credential options. +* Many credentials can now be configured to authenticate in multiple tenants. The + options types for these credentials have an `AdditionallyAllowedTenants` field + that specifies additional tenants in which the credential may authenticate. + +## 1.3.0-beta.2 (2023-01-10) + +### Features Added +* Added `OnBehalfOfCredential` to support the on-behalf-of flow + ([#16642](https://github.com/Azure/azure-sdk-for-go/issues/16642)) + +### Bugs Fixed +* `AzureCLICredential` reports token expiration in local time (should be UTC) + +### Other Changes +* `AzureCLICredential` imposes its default timeout only when the `Context` + passed to `GetToken()` has no deadline +* Added `NewCredentialUnavailableError()`. This function constructs an error indicating + a credential can't authenticate and an encompassing `ChainedTokenCredential` should + try its next credential, if any. + +## 1.3.0-beta.1 (2022-12-13) + +### Features Added +* `WorkloadIdentityCredential` and `DefaultAzureCredential` support + Workload Identity Federation on Kubernetes. `DefaultAzureCredential` + support requires environment variable configuration as set by the + Workload Identity webhook. + ([#15615](https://github.com/Azure/azure-sdk-for-go/issues/15615)) + +## 1.2.0 (2022-11-08) + +### Other Changes +* This version includes all fixes and features from 1.2.0-beta.* + +## 1.2.0-beta.3 (2022-10-11) + +### Features Added +* `ManagedIdentityCredential` caches tokens in memory + +### Bugs Fixed +* `ClientCertificateCredential` sends only the leaf cert for SNI authentication + +## 1.2.0-beta.2 (2022-08-10) + +### Features Added +* Added `ClientAssertionCredential` to enable applications to authenticate + with custom client assertions + +### Other Changes +* Updated AuthenticationFailedError with links to TROUBLESHOOTING.md for relevant errors +* Upgraded `microsoft-authentication-library-for-go` requirement to v0.6.0 + +## 1.2.0-beta.1 (2022-06-07) + +### Features Added +* `EnvironmentCredential` reads certificate passwords from `AZURE_CLIENT_CERTIFICATE_PASSWORD` + ([#17099](https://github.com/Azure/azure-sdk-for-go/pull/17099)) + +## 1.1.0 (2022-06-07) + +### Features Added +* `ClientCertificateCredential` and `ClientSecretCredential` support ESTS-R. First-party + applications can set environment variable `AZURE_REGIONAL_AUTHORITY_NAME` with a + region name. + ([#15605](https://github.com/Azure/azure-sdk-for-go/issues/15605)) + +## 1.0.1 (2022-06-07) + +### Other Changes +* Upgrade `microsoft-authentication-library-for-go` requirement to v0.5.1 + ([#18176](https://github.com/Azure/azure-sdk-for-go/issues/18176)) + +## 1.0.0 (2022-05-12) + +### Features Added +* `DefaultAzureCredential` reads environment variable `AZURE_CLIENT_ID` for the + client ID of a user-assigned managed identity + ([#17293](https://github.com/Azure/azure-sdk-for-go/pull/17293)) + +### Breaking Changes +* Removed `AuthorizationCodeCredential`. Use `InteractiveBrowserCredential` instead + to authenticate a user with the authorization code flow. +* Instances of `AuthenticationFailedError` are now returned by pointer. +* `GetToken()` returns `azcore.AccessToken` by value + +### Bugs Fixed +* `AzureCLICredential` panics after receiving an unexpected error type + ([#17490](https://github.com/Azure/azure-sdk-for-go/issues/17490)) + +### Other Changes +* `GetToken()` returns an error when the caller specifies no scope +* Updated to the latest versions of `golang.org/x/crypto`, `azcore` and `internal` + +## 0.14.0 (2022-04-05) + +### Breaking Changes +* This module now requires Go 1.18 +* Removed `AuthorityHost`. Credentials are now configured for sovereign or private + clouds with the API in `azcore/cloud`, for example: + ```go + // before + opts := azidentity.ClientSecretCredentialOptions{AuthorityHost: azidentity.AzureGovernment} + cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, &opts) + + // after + import "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + + opts := azidentity.ClientSecretCredentialOptions{} + opts.Cloud = cloud.AzureGovernment + cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, &opts) + ``` + +## 0.13.2 (2022-03-08) + +### Bugs Fixed +* Prevented a data race in `DefaultAzureCredential` and `ChainedTokenCredential` + ([#17144](https://github.com/Azure/azure-sdk-for-go/issues/17144)) + +### Other Changes +* Upgraded App Service managed identity version from 2017-09-01 to 2019-08-01 + ([#17086](https://github.com/Azure/azure-sdk-for-go/pull/17086)) + +## 0.13.1 (2022-02-08) + +### Features Added +* `EnvironmentCredential` supports certificate SNI authentication when + `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN` is "true". + ([#16851](https://github.com/Azure/azure-sdk-for-go/pull/16851)) + +### Bugs Fixed +* `ManagedIdentityCredential.GetToken()` now returns an error when configured for + a user assigned identity in Azure Cloud Shell (which doesn't support such identities) + ([#16946](https://github.com/Azure/azure-sdk-for-go/pull/16946)) + +### Other Changes +* `NewDefaultAzureCredential()` logs non-fatal errors. These errors are also included in the + error returned by `DefaultAzureCredential.GetToken()` when it's unable to acquire a token + from any source. ([#15923](https://github.com/Azure/azure-sdk-for-go/issues/15923)) + +## 0.13.0 (2022-01-11) + +### Breaking Changes +* Replaced `AuthenticationFailedError.RawResponse()` with a field having the same name +* Unexported `CredentialUnavailableError` +* Instances of `ChainedTokenCredential` will now skip looping through the list of source credentials and re-use the first successful credential on subsequent calls to `GetToken`. + * If `ChainedTokenCredentialOptions.RetrySources` is true, `ChainedTokenCredential` will continue to try all of the originally provided credentials each time the `GetToken` method is called. + * `ChainedTokenCredential.successfulCredential` will contain a reference to the last successful credential. + * `DefaultAzureCredenial` will also re-use the first successful credential on subsequent calls to `GetToken`. + * `DefaultAzureCredential.chain.successfulCredential` will also contain a reference to the last successful credential. + +### Other Changes +* `ManagedIdentityCredential` no longer probes IMDS before requesting a token + from it. Also, an error response from IMDS no longer disables a credential + instance. Following an error, a credential instance will continue to send + requests to IMDS as necessary. +* Adopted MSAL for user and service principal authentication +* Updated `azcore` requirement to 0.21.0 + +## 0.12.0 (2021-11-02) +### Breaking Changes +* Raised minimum go version to 1.16 +* Removed `NewAuthenticationPolicy()` from credentials. Clients should instead use azcore's + `runtime.NewBearerTokenPolicy()` to construct a bearer token authorization policy. +* The `AuthorityHost` field in credential options structs is now a custom type, + `AuthorityHost`, with underlying type `string` +* `NewChainedTokenCredential` has a new signature to accommodate a placeholder + options struct: + ```go + // before + cred, err := NewChainedTokenCredential(credA, credB) + + // after + cred, err := NewChainedTokenCredential([]azcore.TokenCredential{credA, credB}, nil) + ``` +* Removed `ExcludeAzureCLICredential`, `ExcludeEnvironmentCredential`, and `ExcludeMSICredential` + from `DefaultAzureCredentialOptions` +* `NewClientCertificateCredential` requires a `[]*x509.Certificate` and `crypto.PrivateKey` instead of + a path to a certificate file. Added `ParseCertificates` to simplify getting these in common cases: + ```go + // before + cred, err := NewClientCertificateCredential("tenant", "client-id", "/cert.pem", nil) + + // after + certData, err := os.ReadFile("/cert.pem") + certs, key, err := ParseCertificates(certData, password) + cred, err := NewClientCertificateCredential(tenantID, clientID, certs, key, nil) + ``` +* Removed `InteractiveBrowserCredentialOptions.ClientSecret` and `.Port` +* Removed `AADAuthenticationFailedError` +* Removed `id` parameter of `NewManagedIdentityCredential()`. User assigned identities are now + specified by `ManagedIdentityCredentialOptions.ID`: + ```go + // before + cred, err := NewManagedIdentityCredential("client-id", nil) + // or, for a resource ID + opts := &ManagedIdentityCredentialOptions{ID: ResourceID} + cred, err := NewManagedIdentityCredential("/subscriptions/...", opts) + + // after + clientID := ClientID("7cf7db0d-...") + opts := &ManagedIdentityCredentialOptions{ID: clientID} + // or, for a resource ID + resID: ResourceID("/subscriptions/...") + opts := &ManagedIdentityCredentialOptions{ID: resID} + cred, err := NewManagedIdentityCredential(opts) + ``` +* `DeviceCodeCredentialOptions.UserPrompt` has a new type: `func(context.Context, DeviceCodeMessage) error` +* Credential options structs now embed `azcore.ClientOptions`. In addition to changing literal initialization + syntax, this change renames `HTTPClient` fields to `Transport`. +* Renamed `LogCredential` to `EventCredential` +* `AzureCLICredential` no longer reads the environment variable `AZURE_CLI_PATH` +* `NewManagedIdentityCredential` no longer reads environment variables `AZURE_CLIENT_ID` and + `AZURE_RESOURCE_ID`. Use `ManagedIdentityCredentialOptions.ID` instead. +* Unexported `AuthenticationFailedError` and `CredentialUnavailableError` structs. In their place are two + interfaces having the same names. + +### Bugs Fixed +* `AzureCLICredential.GetToken` no longer mutates its `opts.Scopes` + +### Features Added +* Added connection configuration options to `DefaultAzureCredentialOptions` +* `AuthenticationFailedError.RawResponse()` returns the HTTP response motivating the error, + if available + +### Other Changes +* `NewDefaultAzureCredential()` returns `*DefaultAzureCredential` instead of `*ChainedTokenCredential` +* Added `TenantID` field to `DefaultAzureCredentialOptions` and `AzureCLICredentialOptions` + +## 0.11.0 (2021-09-08) +### Breaking Changes +* Unexported `AzureCLICredentialOptions.TokenProvider` and its type, + `AzureCLITokenProvider` + +### Bug Fixes +* `ManagedIdentityCredential.GetToken` returns `CredentialUnavailableError` + when IMDS has no assigned identity, signaling `DefaultAzureCredential` to + try other credentials + + +## 0.10.0 (2021-08-30) +### Breaking Changes +* Update based on `azcore` refactor [#15383](https://github.com/Azure/azure-sdk-for-go/pull/15383) + +## 0.9.3 (2021-08-20) + +### Bugs Fixed +* `ManagedIdentityCredential.GetToken` no longer mutates its `opts.Scopes` + +### Other Changes +* Bumps version of `azcore` to `v0.18.1` + + +## 0.9.2 (2021-07-23) +### Features Added +* Adding support for Service Fabric environment in `ManagedIdentityCredential` +* Adding an option for using a resource ID instead of client ID in `ManagedIdentityCredential` + + +## 0.9.1 (2021-05-24) +### Features Added +* Add LICENSE.txt and bump version information + + +## 0.9.0 (2021-05-21) +### Features Added +* Add support for authenticating in Azure Stack environments +* Enable user assigned identities for the IMDS scenario in `ManagedIdentityCredential` +* Add scope to resource conversion in `GetToken()` on `ManagedIdentityCredential` + + +## 0.8.0 (2021-01-20) +### Features Added +* Updating documentation + + +## 0.7.1 (2021-01-04) +### Features Added +* Adding port option to `InteractiveBrowserCredential` + + +## 0.7.0 (2020-12-11) +### Features Added +* Add `redirectURI` parameter back to authentication code flow + + +## 0.6.1 (2020-12-09) +### Features Added +* Updating query parameter in `ManagedIdentityCredential` and updating datetime string for parsing managed identity access tokens. + + +## 0.6.0 (2020-11-16) +### Features Added +* Remove `RedirectURL` parameter from auth code flow to align with the MSAL implementation which relies on the native client redirect URL. + + +## 0.5.0 (2020-10-30) +### Features Added +* Flattening credential options + + +## 0.4.3 (2020-10-21) +### Features Added +* Adding Azure Arc support in `ManagedIdentityCredential` + + +## 0.4.2 (2020-10-16) +### Features Added +* Typo fixes + + +## 0.4.1 (2020-10-16) +### Features Added +* Ensure authority hosts are only HTTPs + + +## 0.4.0 (2020-10-16) +### Features Added +* Adding options structs for credentials + + +## 0.3.0 (2020-10-09) +### Features Added +* Update `DeviceCodeCredential` callback + + +## 0.2.2 (2020-10-09) +### Features Added +* Add `AuthorizationCodeCredential` + + +## 0.2.1 (2020-10-06) +### Features Added +* Add `InteractiveBrowserCredential` + + +## 0.2.0 (2020-09-11) +### Features Added +* Refactor `azidentity` on top of `azcore` refactor +* Updated policies to conform to `policy.Policy` interface changes. +* Updated non-retriable errors to conform to `azcore.NonRetriableError`. +* Fixed calls to `Request.SetBody()` to include content type. +* Switched endpoints to string types and removed extra parsing code. + + +## 0.1.1 (2020-09-02) +### Features Added +* Add `AzureCLICredential` to `DefaultAzureCredential` chain + + +## 0.1.0 (2020-07-23) +### Features Added +* Initial Release. Azure Identity library that provides Microsoft Entra token authentication support for the SDK. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/LICENSE.txt new file mode 100644 index 000000000..48ea6616b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md new file mode 100644 index 000000000..1a6492023 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md @@ -0,0 +1,307 @@ +# Migrating from autorest/adal to azidentity + +`azidentity` provides Microsoft Entra ID ([formerly Azure Active Directory](https://learn.microsoft.com/azure/active-directory/fundamentals/new-name)) authentication for the newest Azure SDK modules (`github.com/azure-sdk-for-go/sdk/...`). Older Azure SDK packages (`github.com/azure-sdk-for-go/services/...`) use types from `github.com/go-autorest/autorest/adal` instead. + +This guide shows common authentication code using `autorest/adal` and its equivalent using `azidentity`. + +## Table of contents + +- [Acquire a token](#acquire-a-token) +- [Client certificate authentication](#client-certificate-authentication) +- [Client secret authentication](#client-secret-authentication) +- [Configuration](#configuration) +- [Device code authentication](#device-code-authentication) +- [Managed identity](#managed-identity) +- [Use azidentity credentials with older packages](#use-azidentity-credentials-with-older-packages) + +## Configuration + +### `autorest/adal` + +Token providers require a token audience (resource identifier) and an instance of `adal.OAuthConfig`, which requires a Microsoft Entra endpoint and tenant: + +```go +import "github.com/Azure/go-autorest/autorest/adal" + +oauthCfg, err := adal.NewOAuthConfig("https://login.chinacloudapi.cn", tenantID) +handle(err) + +spt, err := adal.NewServicePrincipalTokenWithSecret( + *oauthCfg, clientID, "https://management.chinacloudapi.cn/", &adal.ServicePrincipalTokenSecret{ClientSecret: secret}, +) +``` + +### `azidentity` + +A credential instance can acquire tokens for any audience. The audience for each token is determined by the client requesting it. Credentials require endpoint configuration only for sovereign or private clouds. The `azcore/cloud` package has predefined configuration for sovereign clouds such as Azure China: + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" +) + +clientOpts := azcore.ClientOptions{Cloud: cloud.AzureChina} + +cred, err := azidentity.NewClientSecretCredential( + tenantID, clientID, secret, &azidentity.ClientSecretCredentialOptions{ClientOptions: clientOpts}, +) +handle(err) +``` + +## Client secret authentication + +### `autorest/adal` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) + +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) +spt, err := adal.NewServicePrincipalTokenWithSecret( + *oauthCfg, clientID, "https://management.azure.com/", &adal.ServicePrincipalTokenSecret{ClientSecret: secret}, +) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil) +handle(err) + +client, err := armsubscriptions.NewClient(cred, nil) +handle(err) +``` + +## Client certificate authentication + +### `autorest/adal` + +```go +import ( + "os" + + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) +certData, err := os.ReadFile("./example.pfx") +handle(err) + +certificate, rsaPrivateKey, err := decodePkcs12(certData, "") +handle(err) + +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) + +spt, err := adal.NewServicePrincipalTokenFromCertificate( + *oauthConfig, clientID, certificate, rsaPrivateKey, "https://management.azure.com/", +) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "os" + + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +certData, err := os.ReadFile("./example.pfx") +handle(err) + +certs, key, err := azidentity.ParseCertificates(certData, nil) +handle(err) + +cred, err = azidentity.NewClientCertificateCredential(tenantID, clientID, certs, key, nil) +handle(err) + +client, err := armsubscriptions.NewClient(cred, nil) +handle(err) +``` + +## Managed identity + +### `autorest/adal` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) + +spt, err := adal.NewServicePrincipalTokenFromManagedIdentity("https://management.azure.com/", nil) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +cred, err := azidentity.NewManagedIdentityCredential(nil) +handle(err) + +client, err := armsubscriptions.NewClient(cred, nil) +handle(err) +``` + +### User-assigned identities + +`autorest/adal`: + +```go +import "github.com/Azure/go-autorest/autorest/adal" + +opts := &adal.ManagedIdentityOptions{ClientID: "..."} +spt, err := adal.NewServicePrincipalTokenFromManagedIdentity("https://management.azure.com/") +handle(err) +``` + +`azidentity`: + +```go +import "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + +opts := azidentity.ManagedIdentityCredentialOptions{ID: azidentity.ClientID("...")} +cred, err := azidentity.NewManagedIdentityCredential(&opts) +handle(err) +``` + +## Device code authentication + +### `autorest/adal` + +```go +import ( + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) + +oauthClient := &http.Client{} +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) +resource := "https://management.azure.com/" +deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthCfg, clientID, resource) +handle(err) + +// display instructions, wait for the user to authenticate +fmt.Println(*deviceCode.Message) +token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) +handle(err) + +spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthCfg, clientID, resource, *token) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +cred, err := azidentity.NewDeviceCodeCredential(nil) +handle(err) + +client, err := armsubscriptions.NewSubscriptionsClient(cred, nil) +handle(err) +``` + +`azidentity.DeviceCodeCredential` will guide a user through authentication, printing instructions to the console by default. The user prompt is customizable. For more information, see the [package documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DeviceCodeCredential). + +## Acquire a token + +### `autorest/adal` + +```go +import "github.com/Azure/go-autorest/autorest/adal" + +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) + +spt, err := adal.NewServicePrincipalTokenWithSecret( + *oauthCfg, clientID, "https://vault.azure.net", &adal.ServicePrincipalTokenSecret{ClientSecret: secret}, +) + +err = spt.Refresh() +if err == nil { + token := spt.Token +} +``` + +### `azidentity` + +In ordinary usage, application code doesn't need to request tokens from credentials directly. Azure SDK clients handle token acquisition and refreshing internally. However, applications may call `GetToken()` to do so. All credential types have this method. + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" +) + +cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil) +handle(err) + +tk, err := cred.GetToken( + context.TODO(), policy.TokenRequestOptions{Scopes: []string{"https://vault.azure.net/.default"}}, +) +if err == nil { + token := tk.Token +} +``` + +Note that `azidentity` credentials use the Microsoft Entra endpoint, which requires OAuth 2 scopes instead of the resource identifiers `autorest/adal` expects. For more information, see [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/permissions-consent-overview). + +## Use azidentity credentials with older packages + +The [azidext module](https://pkg.go.dev/github.com/jongio/azidext/go/azidext) provides an adapter for `azidentity` credential types. The adapter enables using the credential types with older Azure SDK clients. For example: + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/jongio/azidext/go/azidext" +) + +cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = azidext.NewTokenCredentialAdapter(cred, []string{"https://management.azure.com//.default"}) +``` + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FMIGRATION.png) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md new file mode 100644 index 000000000..b6ad2d39f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md @@ -0,0 +1,257 @@ +# Azure Identity Client Module for Go + +The Azure Identity module provides Microsoft Entra ID ([formerly Azure Active Directory](https://learn.microsoft.com/azure/active-directory/fundamentals/new-name)) token authentication support across the Azure SDK. It includes a set of `TokenCredential` implementations, which can be used with Azure SDK clients supporting token authentication. + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/azidentity)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) +| [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/) +| [Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity) + +# Getting started + +## Install the module + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Identity module: + +```sh +go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity +``` + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.18 + +### Authenticating during local development + +When debugging and executing code locally, developers typically use their own accounts to authenticate calls to Azure services. The `azidentity` module supports authenticating through developer tools to simplify local development. + +#### Authenticating via the Azure CLI + +`DefaultAzureCredential` and `AzureCLICredential` can authenticate as the user +signed in to the [Azure CLI](https://docs.microsoft.com/cli/azure). To sign in to the Azure CLI, run `az login`. On a system with a default web browser, the Azure CLI will launch the browser to authenticate a user. + +When no default browser is available, `az login` will use the device code +authentication flow. This can also be selected manually by running `az login --use-device-code`. + +#### Authenticate via the Azure Developer CLI + +Developers coding outside of an IDE can also use the [Azure Developer CLI](https://aka.ms/azure-dev) to authenticate. Applications using the `DefaultAzureCredential` or the `AzureDeveloperCLICredential` can use the account logged in to the Azure Developer CLI to authenticate calls in their application when running locally. + +To authenticate with the Azure Developer CLI, run `azd auth login`. On a system with a default web browser, `azd` will launch the browser to authenticate. On systems without a default web browser, run `azd auth login --use-device-code` to use the device code authentication flow. + +## Key concepts + +### Credentials + +A credential is a type which contains or can obtain the data needed for a +service client to authenticate requests. Service clients across the Azure SDK +accept a credential instance when they are constructed, and use that credential +to authenticate requests. + +The `azidentity` module focuses on OAuth authentication with Microsoft Entra ID. It offers a variety of credential types capable of acquiring a Microsoft Entra access token. See [Credential Types](#credential-types "Credential Types") for a list of this module's credential types. + +### DefaultAzureCredential + +`DefaultAzureCredential` is appropriate for most apps that will be deployed to Azure. It combines common production credentials with development credentials. It attempts to authenticate via the following mechanisms in this order, stopping when one succeeds: + +![DefaultAzureCredential authentication flow](img/mermaidjs/DefaultAzureCredentialAuthFlow.svg) + +1. **Environment** - `DefaultAzureCredential` will read account information specified via [environment variables](#environment-variables) and use it to authenticate. +1. **Workload Identity** - If the app is deployed on Kubernetes with environment variables set by the workload identity webhook, `DefaultAzureCredential` will authenticate the configured identity. +1. **Managed Identity** - If the app is deployed to an Azure host with managed identity enabled, `DefaultAzureCredential` will authenticate with it. +1. **Azure CLI** - If a user or service principal has authenticated via the Azure CLI `az login` command, `DefaultAzureCredential` will authenticate that identity. +1. **Azure Developer CLI** - If the developer has authenticated via the Azure Developer CLI `azd auth login` command, the `DefaultAzureCredential` will authenticate with that account. + +> Note: `DefaultAzureCredential` is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types. + +## Managed Identity + +`DefaultAzureCredential` and `ManagedIdentityCredential` support +[managed identity authentication](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview) +in any hosting environment which supports managed identities, such as (this list is not exhaustive): +* [Azure App Service](https://docs.microsoft.com/azure/app-service/overview-managed-identity) +* [Azure Arc](https://docs.microsoft.com/azure/azure-arc/servers/managed-identity-authentication) +* [Azure Cloud Shell](https://docs.microsoft.com/azure/cloud-shell/msi-authorization) +* [Azure Kubernetes Service](https://docs.microsoft.com/azure/aks/use-managed-identity) +* [Azure Service Fabric](https://docs.microsoft.com/azure/service-fabric/concepts-managed-identity) +* [Azure Virtual Machines](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token) + +## Examples + +- [Authenticate with DefaultAzureCredential](#authenticate-with-defaultazurecredential "Authenticate with DefaultAzureCredential") +- [Define a custom authentication flow with ChainedTokenCredential](#define-a-custom-authentication-flow-with-chainedtokencredential "Define a custom authentication flow with ChainedTokenCredential") +- [Specify a user-assigned managed identity for DefaultAzureCredential](#specify-a-user-assigned-managed-identity-for-defaultazurecredential) + +### Authenticate with DefaultAzureCredential + +This example demonstrates authenticating a client from the `armresources` module with `DefaultAzureCredential`. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +if err != nil { + // handle error +} + +client := armresources.NewResourceGroupsClient("subscription ID", cred, nil) +``` + +### Specify a user-assigned managed identity for DefaultAzureCredential + +To configure `DefaultAzureCredential` to authenticate a user-assigned managed identity, set the environment variable `AZURE_CLIENT_ID` to the identity's client ID. + +### Define a custom authentication flow with `ChainedTokenCredential` + +`DefaultAzureCredential` is generally the quickest way to get started developing apps for Azure. For more advanced scenarios, `ChainedTokenCredential` links multiple credential instances to be tried sequentially when authenticating. It will try each chained credential in turn until one provides a token or fails to authenticate due to an error. + +The following example demonstrates creating a credential, which will attempt to authenticate using managed identity. It will fall back to authenticating via the Azure CLI when a managed identity is unavailable. + +```go +managed, err := azidentity.NewManagedIdentityCredential(nil) +if err != nil { + // handle error +} +azCLI, err := azidentity.NewAzureCLICredential(nil) +if err != nil { + // handle error +} +chain, err := azidentity.NewChainedTokenCredential([]azcore.TokenCredential{managed, azCLI}, nil) +if err != nil { + // handle error +} + +client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) +``` + +## Credential Types + +### Authenticating Azure Hosted Applications + +|Credential|Usage +|-|- +|[DefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential)|Simplified authentication experience for getting started developing Azure apps +|[ChainedTokenCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ChainedTokenCredential)|Define custom authentication flows, composing multiple credentials +|[EnvironmentCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)|Authenticate a service principal or user configured by environment variables +|[ManagedIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ManagedIdentityCredential)|Authenticate the managed identity of an Azure resource +|[WorkloadIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#WorkloadIdentityCredential)|Authenticate a workload identity on Kubernetes + +### Authenticating Service Principals + +|Credential|Usage +|-|- +|[ClientAssertionCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientAssertionCredential)|Authenticate a service principal with a signed client assertion +|[ClientCertificateCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientCertificateCredential)|Authenticate a service principal with a certificate +|[ClientSecretCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientSecretCredential)|Authenticate a service principal with a secret + +### Authenticating Users + +|Credential|Usage +|-|- +|[InteractiveBrowserCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#InteractiveBrowserCredential)|Interactively authenticate a user with the default web browser +|[DeviceCodeCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DeviceCodeCredential)|Interactively authenticate a user on a device with limited UI +|[UsernamePasswordCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#UsernamePasswordCredential)|Authenticate a user with a username and password + +### Authenticating via Development Tools + +|Credential|Usage +|-|- +|[AzureCLICredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureCLICredential)|Authenticate as the user signed in to the Azure CLI +|[`AzureDeveloperCLICredential`](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureDeveloperCLICredential)|Authenticates as the user signed in to the Azure Developer CLI + +## Environment Variables + +`DefaultAzureCredential` and `EnvironmentCredential` can be configured with environment variables. Each type of authentication requires values for specific variables: + +#### Service principal with secret + +|variable name|value +|-|- +|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application +|`AZURE_TENANT_ID`|ID of the application's Microsoft Entra tenant +|`AZURE_CLIENT_SECRET`|one of the application's client secrets + +#### Service principal with certificate + +|variable name|value +|-|- +|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application +|`AZURE_TENANT_ID`|ID of the application's Microsoft Entra tenant +|`AZURE_CLIENT_CERTIFICATE_PATH`|path to a certificate file including private key +|`AZURE_CLIENT_CERTIFICATE_PASSWORD`|password of the certificate file, if any + +#### Username and password + +|variable name|value +|-|- +|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application +|`AZURE_USERNAME`|a username (usually an email address) +|`AZURE_PASSWORD`|that user's password + +Configuration is attempted in the above order. For example, if values for a +client secret and certificate are both present, the client secret will be used. + +## Token caching + +Token caching is an `azidentity` feature that allows apps to: + +* Cache tokens in memory (default) or on disk (opt-in). +* Improve resilience and performance. +* Reduce the number of requests made to Microsoft Entra ID to obtain access tokens. + +For more details, see the [token caching documentation](https://aka.ms/azsdk/go/identity/caching). + +## Troubleshooting + +### Error Handling + +Credentials return an `error` when they fail to authenticate or lack data they require to authenticate. For guidance on resolving errors from specific credential types, see the [troubleshooting guide](https://aka.ms/azsdk/go/identity/troubleshoot). + +For more details on handling specific Microsoft Entra errors, see the Microsoft Entra [error code documentation](https://learn.microsoft.com/azure/active-directory/develop/reference-error-codes). + +### Logging + +This module uses the classification-based logging implementation in `azcore`. To enable console logging for all SDK modules, set `AZURE_SDK_GO_LOGGING` to `all`. Use the `azcore/log` package to control log event output or to enable logs for `azidentity` only. For example: +```go +import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log" + +// print log output to stdout +azlog.SetListener(func(event azlog.Event, s string) { + fmt.Println(s) +}) + +// include only azidentity credential logs +azlog.SetEvents(azidentity.EventAuthentication) +``` + +Credentials log basic information only, such as `GetToken` success or failure and errors. These log entries don't contain authentication secrets but may contain sensitive information. + +## Next steps + +Client and management modules listed on the [Azure SDK releases page](https://azure.github.io/azure-sdk/releases/latest/go.html) support authenticating with `azidentity` credential types. You can learn more about using these libraries in their documentation, which is linked from the release page. + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues). + +## 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. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FREADME.png) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD new file mode 100644 index 000000000..c0d660146 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD @@ -0,0 +1,70 @@ +## Token caching in the Azure Identity client module + +*Token caching* is a feature provided by the Azure Identity library that allows apps to: + +- Improve their resilience and performance. +- Reduce the number of requests made to Microsoft Entra ID to obtain access tokens. +- Reduce the number of times the user is prompted to authenticate. + +When an app needs to access a protected Azure resource, it typically needs to obtain an access token from Entra ID. Obtaining that token involves sending a request to Entra ID and may also involve prompting the user. Entra ID then validates the credentials provided in the request and issues an access token. + +Token caching, via the Azure Identity library, allows the app to store this access token [in memory](#in-memory-token-caching), where it's accessible to the current process, or [on disk](#persistent-token-caching) where it can be accessed across application or process invocations. The token can then be retrieved quickly and easily the next time the app needs to access the same resource. The app can avoid making another request to Entra ID, which reduces network traffic and improves resilience. Additionally, in scenarios where the app is authenticating users, token caching also avoids prompting the user each time new tokens are requested. + +### In-memory token caching + +*In-memory token caching* is the default option provided by the Azure Identity library. This caching approach allows apps to store access tokens in memory. With in-memory token caching, the library first determines if a valid access token for the requested resource is already stored in memory. If a valid token is found, it's returned to the app without the need to make another request to Entra ID. If a valid token isn't found, the library will automatically acquire a token by sending a request to Entra ID. The in-memory token cache provided by the Azure Identity library is thread-safe. + +**Note:** When Azure Identity library credentials are used with Azure service libraries (for example, Azure Blob Storage), the in-memory token caching is active in the `Pipeline` layer as well. All `TokenCredential` implementations are supported there, including custom implementations external to the Azure Identity library. + +#### Caching cannot be disabled + +As there are many levels of caching, it's not possible disable in-memory caching. However, the in-memory cache may be cleared by creating a new credential instance. + +### Persistent token caching + +> Only azidentity v1.5.0-beta versions support persistent token caching + +*Persistent disk token caching* is an opt-in feature in the Azure Identity library. The feature allows apps to cache access tokens in an encrypted, persistent storage mechanism. As indicated in the following table, the storage mechanism differs across operating systems. + +| Operating system | Storage mechanism | +|------------------|---------------------------------------| +| Linux | kernel key retention service (keyctl) | +| macOS | Keychain | +| Windows | DPAPI | + +By default the token cache will protect any data which is persisted using the user data protection APIs available on the current platform. +However, there are cases where no data protection is available, and applications may choose to allow storing the token cache in an unencrypted state by setting `TokenCachePersistenceOptions.AllowUnencryptedStorage` to `true`. This allows a credential to fall back to unencrypted storage if it can't encrypt the cache. However, we do not recommend using this storage method due to its significantly lower security measures. In addition, tokens are not encrypted solely to the current user, which could potentially allow unauthorized access to the cache by individuals with machine access. + +With persistent disk token caching enabled, the library first determines if a valid access token for the requested resource is already stored in the persistent cache. If a valid token is found, it's returned to the app without the need to make another request to Entra ID. Additionally, the tokens are preserved across app runs, which: + +- Makes the app more resilient to failures. +- Ensures the app can continue to function during an Entra ID outage or disruption. +- Avoids having to prompt users to authenticate each time the process is restarted. + +>IMPORTANT! The token cache contains sensitive data and **MUST** be protected to prevent compromising accounts. All application decisions regarding the persistence of the token cache must consider that a breach of its content will fully compromise all the accounts it contains. + +#### Example code + +See the [package documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity@v1.5.0-beta.1#pkg-overview) for code examples demonstrating how to configure persistent caching and access cached data. + +### Credentials supporting token caching + +The following table indicates the state of in-memory and persistent caching in each credential type. + +**Note:** In-memory caching is activated by default. Persistent token caching needs to be enabled as shown in [this example](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity@v1.5.0-beta.1#example-package-PersistentCache). + +| Credential | In-memory token caching | Persistent token caching | +|--------------------------------|---------------------------------------------------------------------|--------------------------| +| `AzureCLICredential` | Not Supported | Not Supported | +| `AzureDeveloperCLICredential` | Not Supported | Not Supported | +| `ClientAssertionCredential` | Supported | Supported | +| `ClientCertificateCredential` | Supported | Supported | +| `ClientSecretCredential` | Supported | Supported | +| `DefaultAzureCredential` | Supported if the target credential in the default chain supports it | Not Supported | +| `DeviceCodeCredential` | Supported | Supported | +| `EnvironmentCredential` | Supported | Not Supported | +| `InteractiveBrowserCredential` | Supported | Supported | +| `ManagedIdentityCredential` | Supported | Not Supported | +| `OnBehalfOfCredential` | Supported | Supported | +| `UsernamePasswordCredential` | Supported | Supported | +| `WorkloadIdentityCredential` | Supported | Supported | diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md new file mode 100644 index 000000000..832c599eb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md @@ -0,0 +1,231 @@ +# Troubleshoot Azure Identity authentication issues + +This troubleshooting guide covers failure investigation techniques, common errors for the credential types in the `azidentity` module, and mitigation steps to resolve these errors. + +## Table of contents + +- [Handle azidentity errors](#handle-azidentity-errors) + - [Permission issues](#permission-issues) +- [Find relevant information in errors](#find-relevant-information-in-errors) +- [Enable and configure logging](#enable-and-configure-logging) +- [Troubleshoot AzureCLICredential authentication issues](#troubleshoot-azureclicredential-authentication-issues) +- [Troubleshoot AzureDeveloperCLICredential authentication issues](#troubleshoot-azuredeveloperclicredential-authentication-issues) +- [Troubleshoot ClientCertificateCredential authentication issues](#troubleshoot-clientcertificatecredential-authentication-issues) +- [Troubleshoot ClientSecretCredential authentication issues](#troubleshoot-clientsecretcredential-authentication-issues) +- [Troubleshoot DefaultAzureCredential authentication issues](#troubleshoot-defaultazurecredential-authentication-issues) +- [Troubleshoot EnvironmentCredential authentication issues](#troubleshoot-environmentcredential-authentication-issues) +- [Troubleshoot ManagedIdentityCredential authentication issues](#troubleshoot-managedidentitycredential-authentication-issues) + - [Azure App Service and Azure Functions managed identity](#azure-app-service-and-azure-functions-managed-identity) + - [Azure Kubernetes Service managed identity](#azure-kubernetes-service-managed-identity) + - [Azure Virtual Machine managed identity](#azure-virtual-machine-managed-identity) +- [Troubleshoot UsernamePasswordCredential authentication issues](#troubleshoot-usernamepasswordcredential-authentication-issues) +- [Troubleshoot WorkloadIdentityCredential authentication issues](#troubleshoot-workloadidentitycredential-authentication-issues) +- [Get additional help](#get-additional-help) + +## Handle azidentity errors + +Any service client method that makes a request to the service may return an error due to authentication failure. This is because the credential authenticates on the first call to the service and on any subsequent call that needs to refresh an access token. Authentication errors include a description of the failure and possibly an error message from Microsoft Entra ID. Depending on the application, these errors may or may not be recoverable. + +### Permission issues + +Service client errors with a status code of 401 or 403 often indicate that authentication succeeded but the caller doesn't have permission to access the specified API. Check the service documentation to determine which RBAC roles are needed for the request, and ensure the authenticated user or service principal has the appropriate role assignments. + +## Find relevant information in errors + +Authentication errors can include responses from Microsoft Entra ID and often contain information helpful in diagnosis. Consider the following error message: + +``` +ClientSecretCredential authentication failed +POST https://login.microsoftonline.com/3c631bb7-a9f7-4343-a5ba-a615913/oauth2/v2.0/token +-------------------------------------------------------------------------------- +RESPONSE 401 Unauthorized +-------------------------------------------------------------------------------- +{ + "error": "invalid_client", + "error_description": "AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value, not the client secret ID, for a secret added to app '86be4c01-505b-45e9-bfc0-9b825fd84'.\r\nTrace ID: 03da4b8e-5ffe-48ca-9754-aff4276f0100\r\nCorrelation ID: 7b12f9bb-2eef-42e3-ad75-eee69ec9088d\r\nTimestamp: 2022-03-02 18:25:26Z", + "error_codes": [ + 7000215 + ], + "timestamp": "2022-03-02 18:25:26Z", + "trace_id": "03da4b8e-5ffe-48ca-9754-aff4276f0100", + "correlation_id": "7b12f9bb-2eef-42e3-ad75-eee69ec9088d", + "error_uri": "https://login.microsoftonline.com/error?code=7000215" +} +-------------------------------------------------------------------------------- +``` + +This error contains several pieces of information: + +- __Failing Credential Type__: The type of credential that failed to authenticate. This can be helpful when diagnosing issues with chained credential types such as `DefaultAzureCredential` or `ChainedTokenCredential`. + +- __Microsoft Entra ID Error Code and Message__: The error code and message returned by Microsoft Entra ID. This can give insight into the specific reason the request failed. For instance, in this case authentication failed because the provided client secret is incorrect. [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/reference-error-codes#aadsts-error-codes) has more information on AADSTS error codes. + +- __Correlation ID and Timestamp__: The correlation ID and timestamp identify the request in server-side logs. This information can be useful to support engineers diagnosing unexpected Microsoft Entra failures. + +### Enable and configure logging + +`azidentity` provides the same logging capabilities as the rest of the Azure SDK. The simplest way to see the logs to help debug authentication issues is to print credential logs to the console. +```go +import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log" + +// print log output to stdout +azlog.SetListener(func(event azlog.Event, s string) { + fmt.Println(s) +}) + +// include only azidentity credential logs +azlog.SetEvents(azidentity.EventAuthentication) +``` + + +## Troubleshoot DefaultAzureCredential authentication issues + +| Error |Description| Mitigation | +|---|---|---| +|"DefaultAzureCredential failed to acquire a token"|No credential in the `DefaultAzureCredential` chain provided a token|
  • [Enable logging](#enable-and-configure-logging) to get further diagnostic information.
  • Consult the troubleshooting guide for underlying credential types for more information.
    • [EnvironmentCredential](#troubleshoot-environmentcredential-authentication-issues)
    • [ManagedIdentityCredential](#troubleshoot-managedidentitycredential-authentication-issues)
    • [AzureCLICredential](#troubleshoot-azureclicredential-authentication-issues)
    | +|Error from the client with a status code of 401 or 403|Authentication succeeded but the authorizing Azure service responded with a 401 (Unauthorized), or 403 (Forbidden) status code|
    • [Enable logging](#enable-and-configure-logging) to determine which credential in the chain returned the authenticating token.
    • If an unexpected credential is returning a token, check application configuration such as environment variables.
    • Ensure the correct role is assigned to the authenticated identity. For example, a service specific role rather than the subscription Owner role.
    | +|"managed identity timed out"|`DefaultAzureCredential` sets a short timeout on its first managed identity authentication attempt to prevent very long timeouts during local development when no managed identity is available. That timeout causes this error in production when an application requests a token before the hosting environment is ready to provide one.|Use [ManagedIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ManagedIdentityCredential) directly, at least in production. It doesn't set a timeout on its authentication attempts.| + +## Troubleshoot EnvironmentCredential authentication issues + +| Error Message |Description| Mitigation | +|---|---|---| +|Missing or incomplete environment variable configuration|A valid combination of environment variables wasn't set|Ensure the appropriate environment variables are set for the intended authentication method as described in the [module documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)| + + +## Troubleshoot ClientSecretCredential authentication issues + +| Error Code | Issue | Mitigation | +|---|---|---| +|AADSTS7000215|An invalid client secret was provided.|Ensure the secret provided to the credential constructor is valid. If unsure, create a new client secret using the Azure portal. Details on creating a new client secret are in [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| +|AADSTS7000222|An expired client secret was provided.|Create a new client secret using the Azure portal. Details on creating a new client secret are in [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| +|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Microsoft Entra ID instructions](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| + + +## Troubleshoot ClientCertificateCredential authentication issues + +| Error Code | Description | Mitigation | +|---|---|---| +|AADSTS700027|Client assertion contains an invalid signature.|Ensure the specified certificate has been uploaded to the application registration as described in [Microsoft Entra ID documentation](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-1-upload-a-certificate).| +|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Microsoft Entra ID instructions](https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| + + +## Troubleshoot UsernamePasswordCredential authentication issues + +| Error Code | Issue | Mitigation | +|---|---|---| +|AADSTS50126|The provided username or password is invalid.|Ensure the username and password provided to the credential constructor are valid.| + + +## Troubleshoot ManagedIdentityCredential authentication issues + +`ManagedIdentityCredential` is designed to work on a variety of Azure hosts support managed identity. Configuration and troubleshooting vary from host to host. The below table lists the Azure hosts that can be assigned a managed identity and are supported by `ManagedIdentityCredential`. + +|Host Environment| | | +|---|---|---| +|Azure Virtual Machines and Scale Sets|[Configuration](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm)|[Troubleshooting](#azure-virtual-machine-managed-identity)| +|Azure App Service and Azure Functions|[Configuration](https://docs.microsoft.com/azure/app-service/overview-managed-identity)|[Troubleshooting](#azure-app-service-and-azure-functions-managed-identity)| +|Azure Kubernetes Service|[Configuration](https://azure.github.io/aad-pod-identity/docs/)|[Troubleshooting](#azure-kubernetes-service-managed-identity)| +|Azure Arc|[Configuration](https://docs.microsoft.com/azure/azure-arc/servers/managed-identity-authentication)|| +|Azure Service Fabric|[Configuration](https://docs.microsoft.com/azure/service-fabric/concepts-managed-identity)|| + +### Azure Virtual Machine managed identity + +| Error Message |Description| Mitigation | +|---|---|---| +|The requested identity hasn’t been assigned to this resource.|The IMDS endpoint responded with a status code of 400, indicating the requested identity isn’t assigned to the VM.|If using a user assigned identity, ensure the specified ID is correct.

    If using a system assigned identity, make sure it has been enabled as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm#enable-system-assigned-managed-identity-on-an-existing-vm).| +|The request failed due to a gateway error.|The request to the IMDS endpoint failed due to a gateway error, 502 or 504 status code.|IMDS doesn't support requests via proxy or gateway. Disable proxies or gateways running on the VM for requests to the IMDS endpoint `http://169.254.169.254`| +|No response received from the managed identity endpoint.|No response was received for the request to IMDS or the request timed out.|

    • Ensure the VM is configured for managed identity as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm).
    • Verify the IMDS endpoint is reachable on the VM. See [below](#verify-imds-is-available-on-the-vm) for instructions.
    | +|Multiple attempts failed to obtain a token from the managed identity endpoint.|The credential has exhausted its retries for a token request.|
    • Refer to the error message for more details on specific failures.
    • Ensure the VM is configured for managed identity as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm).
    • Verify the IMDS endpoint is reachable on the VM. See [below](#verify-imds-is-available-on-the-vm) for instructions.
    | + +#### Verify IMDS is available on the VM + +If you have access to the VM, you can use `curl` to verify the managed identity endpoint is available. + +```sh +curl 'http://169.254.169.254/metadata/identity/oauth2/token?resource=https://management.core.windows.net&api-version=2018-02-01' -H "Metadata: true" +``` + +> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security. + +### Azure App Service and Azure Functions managed identity + +| Error Message |Description| Mitigation | +|---|---|---| +|Get "`http://169.254.169.254/...`" i/o timeout|The App Service host hasn't set environment variables for managed identity configuration.|
    • Ensure the App Service is configured for managed identity as described in [App Service documentation](https://docs.microsoft.com/azure/app-service/overview-managed-identity).
    • Verify the App Service environment is properly configured and the managed identity endpoint is available. See [below](#verify-the-app-service-managed-identity-endpoint-is-available) for instructions.
    | + +#### Verify the App Service managed identity endpoint is available + +If you can SSH into the App Service, you can verify managed identity is available in the environment. First ensure the environment variables `IDENTITY_ENDPOINT` and `IDENTITY_SECRET` are set. Then you can verify the managed identity endpoint is available using `curl`. + +```sh +curl "$IDENTITY_ENDPOINT?resource=https://management.core.windows.net&api-version=2019-08-01" -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" +``` + +> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security. + +### Azure Kubernetes Service managed identity + +#### Pod Identity + +| Error Message |Description| Mitigation | +|---|---|---| +|"no azure identity found for request clientID"|The application attempted to authenticate before an identity was assigned to its pod|Verify the pod is labeled correctly. This also occurs when a correctly labeled pod authenticates before the identity is ready. To prevent initialization races, configure NMI to set the Retry-After header in its responses as described in [Pod Identity documentation](https://azure.github.io/aad-pod-identity/docs/configure/feature_flags/#set-retry-after-header-in-nmi-response). + + +## Troubleshoot AzureCLICredential authentication issues + +| Error Message |Description| Mitigation | +|---|---|---| +|Azure CLI not found on path|The Azure CLI isn’t installed or isn't on the application's path.|
    • Ensure the Azure CLI is installed as described in [Azure CLI documentation](https://docs.microsoft.com/cli/azure/install-azure-cli).
    • Validate the installation location is in the application's `PATH` environment variable.
    | +|Please run 'az login' to set up account|No account is currently logged into the Azure CLI, or the login has expired.|
    • Run `az login` to log into the Azure CLI. More information about Azure CLI authentication is available in the [Azure CLI documentation](https://docs.microsoft.com/cli/azure/authenticate-azure-cli).
    • Verify that the Azure CLI can obtain tokens. See [below](#verify-the-azure-cli-can-obtain-tokens) for instructions.
    | + +#### Verify the Azure CLI can obtain tokens + +You can manually verify that the Azure CLI can authenticate and obtain tokens. First, use the `account` command to verify the logged in account. + +```azurecli +az account show +``` + +Once you've verified the Azure CLI is using the correct account, you can validate that it's able to obtain tokens for that account. + +```azurecli +az account get-access-token --output json --resource https://management.core.windows.net +``` + +> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security. + + +## Troubleshoot AzureDeveloperCLICredential authentication issues + +| Error Message |Description| Mitigation | +|---|---|---| +|Azure Developer CLI not found on path|The Azure Developer CLI isn't installed or couldn't be found.|
    • Ensure the Azure Developer CLI is properly installed. See the installation instructions at [Install or update the Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd).
    • Validate the installation location has been added to the `PATH` environment variable.
    | +|Please run "azd auth login"|No account is logged into the Azure Developer CLI, or the login has expired.|
    • Log in to the Azure Developer CLI using the `azd login` command.
    • Validate that the Azure Developer CLI can obtain tokens. For instructions, see [Verify the Azure Developer CLI can obtain tokens](#verify-the-azure-developer-cli-can-obtain-tokens).
    | + +#### Verify the Azure Developer CLI can obtain tokens + +You can manually verify that the Azure Developer CLI is properly authenticated and can obtain tokens. First, use the `config` command to verify the account that is currently logged in to the Azure Developer CLI. + +```sh +azd config list +``` + +Once you've verified the Azure Developer CLI is using correct account, you can validate that it's able to obtain tokens for this account. + +```sh +azd auth token --output json --scope https://management.core.windows.net/.default +``` +>Note that output of this command will contain a valid access token, and SHOULD NOT BE SHARED to avoid compromising account security. + + +## Troubleshoot `WorkloadIdentityCredential` authentication issues + +| Error Message |Description| Mitigation | +|---|---|---| +|no client ID/tenant ID/token file specified|Incomplete configuration|In most cases these values are provided via environment variables set by Azure Workload Identity.
    • If your application runs on Azure Kubernetes Servide (AKS) or a cluster that has deployed the Azure Workload Identity admission webhook, check pod labels and service account configuration. See the [AKS documentation](https://learn.microsoft.com/azure/aks/workload-identity-deploy-cluster#disable-workload-identity) and [Azure Workload Identity troubleshooting guide](https://azure.github.io/azure-workload-identity/docs/troubleshooting.html) for more details.
    • If your application isn't running on AKS or your cluster hasn't deployed the Workload Identity admission webhook, set these values in `WorkloadIdentityCredentialOptions` + +## Get additional help + +Additional information on ways to reach out for support can be found in [SUPPORT.md](https://github.com/Azure/azure-sdk-for-go/blob/main/SUPPORT.md). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json new file mode 100644 index 000000000..173ce2b3c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "go", + "TagPrefix": "go/azidentity", + "Tag": "go/azidentity_db4a26f583" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/authentication_record.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/authentication_record.go new file mode 100644 index 000000000..ada4d6501 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/authentication_record.go @@ -0,0 +1,95 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" +) + +var supportedAuthRecordVersions = []string{"1.0"} + +// authenticationRecord is non-secret account information about an authenticated user that user credentials such as +// [DeviceCodeCredential] and [InteractiveBrowserCredential] can use to access previously cached authentication +// data. Call these credentials' Authenticate method to get an authenticationRecord for a user. +type authenticationRecord struct { + // Authority is the URL of the authority that issued the token. + Authority string `json:"authority"` + + // ClientID is the ID of the application that authenticated the user. + ClientID string `json:"clientId"` + + // HomeAccountID uniquely identifies the account. + HomeAccountID string `json:"homeAccountId"` + + // TenantID identifies the tenant in which the user authenticated. + TenantID string `json:"tenantId"` + + // Username is the user's preferred username. + Username string `json:"username"` + + // Version of the AuthenticationRecord. + Version string `json:"version"` +} + +// UnmarshalJSON implements json.Unmarshaler for AuthenticationRecord +func (a *authenticationRecord) UnmarshalJSON(b []byte) error { + // Default unmarshaling is fine but we want to return an error if the record's version isn't supported i.e., we + // want to inspect the unmarshalled values before deciding whether to return an error. Unmarshaling a formally + // different type enables this by assigning all the fields without recursing into this method. + type r authenticationRecord + err := json.Unmarshal(b, (*r)(a)) + if err != nil { + return err + } + if a.Version == "" { + return errors.New("AuthenticationRecord must have a version") + } + for _, v := range supportedAuthRecordVersions { + if a.Version == v { + return nil + } + } + return fmt.Errorf("unsupported AuthenticationRecord version %q. This module supports %v", a.Version, supportedAuthRecordVersions) +} + +// account returns the AuthenticationRecord as an MSAL Account. The account is zero-valued when the AuthenticationRecord is zero-valued. +func (a *authenticationRecord) account() public.Account { + return public.Account{ + Environment: a.Authority, + HomeAccountID: a.HomeAccountID, + PreferredUsername: a.Username, + } +} + +func newAuthenticationRecord(ar public.AuthResult) (authenticationRecord, error) { + u, err := url.Parse(ar.IDToken.Issuer) + if err != nil { + return authenticationRecord{}, fmt.Errorf("Authenticate expected a URL issuer but got %q", ar.IDToken.Issuer) + } + tenant := ar.IDToken.TenantID + if tenant == "" { + tenant = strings.Trim(u.Path, "/") + } + username := ar.IDToken.PreferredUsername + if username == "" { + username = ar.IDToken.UPN + } + return authenticationRecord{ + Authority: fmt.Sprintf("%s://%s", u.Scheme, u.Host), + ClientID: ar.IDToken.Audience, + HomeAccountID: ar.Account.HomeAccountID, + TenantID: tenant, + Username: username, + Version: "1.0", + }, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go new file mode 100644 index 000000000..c3bcfb56c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go @@ -0,0 +1,187 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" +) + +const ( + azureAdditionallyAllowedTenants = "AZURE_ADDITIONALLY_ALLOWED_TENANTS" + azureAuthorityHost = "AZURE_AUTHORITY_HOST" + azureClientCertificatePassword = "AZURE_CLIENT_CERTIFICATE_PASSWORD" + azureClientCertificatePath = "AZURE_CLIENT_CERTIFICATE_PATH" + azureClientID = "AZURE_CLIENT_ID" + azureClientSecret = "AZURE_CLIENT_SECRET" + azureFederatedTokenFile = "AZURE_FEDERATED_TOKEN_FILE" + azurePassword = "AZURE_PASSWORD" + azureRegionalAuthorityName = "AZURE_REGIONAL_AUTHORITY_NAME" + azureTenantID = "AZURE_TENANT_ID" + azureUsername = "AZURE_USERNAME" + + organizationsTenantID = "organizations" + developerSignOnClientID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" + defaultSuffix = "/.default" + + traceNamespace = "Microsoft.Entra" + traceOpGetToken = "GetToken" + traceOpAuthenticate = "Authenticate" +) + +var ( + // capability CP1 indicates the client application is capable of handling CAE claims challenges + cp1 = []string{"CP1"} + errInvalidTenantID = errors.New("invalid tenantID. You can locate your tenantID by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names") +) + +// tokenCachePersistenceOptions contains options for persistent token caching +type tokenCachePersistenceOptions = internal.TokenCachePersistenceOptions + +// setAuthorityHost initializes the authority host for credentials. Precedence is: +// 1. cloud.Configuration.ActiveDirectoryAuthorityHost value set by user +// 2. value of AZURE_AUTHORITY_HOST +// 3. default: Azure Public Cloud +func setAuthorityHost(cc cloud.Configuration) (string, error) { + host := cc.ActiveDirectoryAuthorityHost + if host == "" { + if len(cc.Services) > 0 { + return "", errors.New("missing ActiveDirectoryAuthorityHost for specified cloud") + } + host = cloud.AzurePublic.ActiveDirectoryAuthorityHost + if envAuthorityHost := os.Getenv(azureAuthorityHost); envAuthorityHost != "" { + host = envAuthorityHost + } + } + u, err := url.Parse(host) + if err != nil { + return "", err + } + if u.Scheme != "https" { + return "", errors.New("cannot use an authority host without https") + } + return host, nil +} + +// resolveAdditionalTenants returns a copy of tenants, simplified when tenants contains a wildcard +func resolveAdditionalTenants(tenants []string) []string { + if len(tenants) == 0 { + return nil + } + for _, t := range tenants { + // a wildcard makes all other values redundant + if t == "*" { + return []string{"*"} + } + } + cp := make([]string, len(tenants)) + copy(cp, tenants) + return cp +} + +// resolveTenant returns the correct tenant for a token request +func resolveTenant(defaultTenant, specified, credName string, additionalTenants []string) (string, error) { + if specified == "" || specified == defaultTenant { + return defaultTenant, nil + } + if defaultTenant == "adfs" { + return "", errors.New("ADFS doesn't support tenants") + } + if !validTenantID(specified) { + return "", errInvalidTenantID + } + for _, t := range additionalTenants { + if t == "*" || t == specified { + return specified, nil + } + } + return "", fmt.Errorf(`%s isn't configured to acquire tokens for tenant %q. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add "*" to allow acquiring tokens for any tenant`, credName, specified) +} + +func alphanumeric(r rune) bool { + return ('0' <= r && r <= '9') || ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') +} + +func validTenantID(tenantID string) bool { + for _, r := range tenantID { + if !(alphanumeric(r) || r == '.' || r == '-') { + return false + } + } + return true +} + +func doForClient(client *azcore.Client, r *http.Request) (*http.Response, error) { + req, err := runtime.NewRequest(r.Context(), r.Method, r.URL.String()) + if err != nil { + return nil, err + } + if r.Body != nil && r.Body != http.NoBody { + // create a rewindable body from the existing body as required + var body io.ReadSeekCloser + if rsc, ok := r.Body.(io.ReadSeekCloser); ok { + body = rsc + } else { + b, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + body = streaming.NopCloser(bytes.NewReader(b)) + } + err = req.SetBody(body, r.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + } + + // copy headers to the new request, ignoring any for which the new request has a value + h := req.Raw().Header + for key, vals := range r.Header { + if _, has := h[key]; !has { + for _, val := range vals { + h.Add(key, val) + } + } + } + + resp, err := client.Pipeline().Do(req) + if err != nil { + return nil, err + } + return resp, err +} + +// enables fakes for test scenarios +type msalConfidentialClient interface { + AcquireTokenSilent(ctx context.Context, scopes []string, options ...confidential.AcquireSilentOption) (confidential.AuthResult, error) + AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, options ...confidential.AcquireByAuthCodeOption) (confidential.AuthResult, error) + AcquireTokenByCredential(ctx context.Context, scopes []string, options ...confidential.AcquireByCredentialOption) (confidential.AuthResult, error) + AcquireTokenOnBehalfOf(ctx context.Context, userAssertion string, scopes []string, options ...confidential.AcquireOnBehalfOfOption) (confidential.AuthResult, error) +} + +// enables fakes for test scenarios +type msalPublicClient interface { + AcquireTokenSilent(ctx context.Context, scopes []string, options ...public.AcquireSilentOption) (public.AuthResult, error) + AcquireTokenByUsernamePassword(ctx context.Context, scopes []string, username string, password string, options ...public.AcquireByUsernamePasswordOption) (public.AuthResult, error) + AcquireTokenByDeviceCode(ctx context.Context, scopes []string, options ...public.AcquireByDeviceCodeOption) (public.DeviceCode, error) + AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, options ...public.AcquireByAuthCodeOption) (public.AuthResult, error) + AcquireTokenInteractive(ctx context.Context, scopes []string, options ...public.AcquireInteractiveOption) (public.AuthResult, error) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go new file mode 100644 index 000000000..43577ab3c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go @@ -0,0 +1,195 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +const credNameAzureCLI = "AzureCLICredential" + +type azTokenProvider func(ctx context.Context, scopes []string, tenant, subscription string) ([]byte, error) + +// AzureCLICredentialOptions contains optional parameters for AzureCLICredential. +type AzureCLICredentialOptions struct { + // AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition + // to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the + // logged in account can access. + AdditionallyAllowedTenants []string + + // subscription is the name or ID of a subscription. Set this to acquire tokens for an account other + // than the Azure CLI's current account. + subscription string + + // TenantID identifies the tenant the credential should authenticate in. + // Defaults to the CLI's default tenant, which is typically the home tenant of the logged in user. + TenantID string + + // inDefaultChain is true when the credential is part of DefaultAzureCredential + inDefaultChain bool + // tokenProvider is used by tests to fake invoking az + tokenProvider azTokenProvider +} + +// init returns an instance of AzureCLICredentialOptions initialized with default values. +func (o *AzureCLICredentialOptions) init() { + if o.tokenProvider == nil { + o.tokenProvider = defaultAzTokenProvider + } +} + +// AzureCLICredential authenticates as the identity logged in to the Azure CLI. +type AzureCLICredential struct { + mu *sync.Mutex + opts AzureCLICredentialOptions +} + +// NewAzureCLICredential constructs an AzureCLICredential. Pass nil to accept default options. +func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredential, error) { + cp := AzureCLICredentialOptions{} + if options != nil { + cp = *options + } + for _, r := range cp.subscription { + if !(alphanumeric(r) || r == '-' || r == '_' || r == ' ' || r == '.') { + return nil, fmt.Errorf("%s: invalid Subscription %q", credNameAzureCLI, cp.subscription) + } + } + if cp.TenantID != "" && !validTenantID(cp.TenantID) { + return nil, errInvalidTenantID + } + cp.init() + cp.AdditionallyAllowedTenants = resolveAdditionalTenants(cp.AdditionallyAllowedTenants) + return &AzureCLICredential{mu: &sync.Mutex{}, opts: cp}, nil +} + +// GetToken requests a token from the Azure CLI. This credential doesn't cache tokens, so every call invokes the CLI. +// This method is called automatically by Azure SDK clients. +func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + at := azcore.AccessToken{} + if len(opts.Scopes) != 1 { + return at, errors.New(credNameAzureCLI + ": GetToken() requires exactly one scope") + } + if !validScope(opts.Scopes[0]) { + return at, fmt.Errorf("%s.GetToken(): invalid scope %q", credNameAzureCLI, opts.Scopes[0]) + } + tenant, err := resolveTenant(c.opts.TenantID, opts.TenantID, credNameAzureCLI, c.opts.AdditionallyAllowedTenants) + if err != nil { + return at, err + } + c.mu.Lock() + defer c.mu.Unlock() + b, err := c.opts.tokenProvider(ctx, opts.Scopes, tenant, c.opts.subscription) + if err == nil { + at, err = c.createAccessToken(b) + } + if err != nil { + err = unavailableIfInChain(err, c.opts.inDefaultChain) + return at, err + } + msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", credNameAzureCLI, strings.Join(opts.Scopes, ", ")) + log.Write(EventAuthentication, msg) + return at, nil +} + +// defaultAzTokenProvider invokes the Azure CLI to acquire a token. It assumes +// callers have verified that all string arguments are safe to pass to the CLI. +var defaultAzTokenProvider azTokenProvider = func(ctx context.Context, scopes []string, tenantID, subscription string) ([]byte, error) { + // pass the CLI a Microsoft Entra ID v1 resource because we don't know which CLI version is installed and older ones don't support v2 scopes + resource := strings.TrimSuffix(scopes[0], defaultSuffix) + // set a default timeout for this authentication iff the application hasn't done so already + var cancel context.CancelFunc + if _, hasDeadline := ctx.Deadline(); !hasDeadline { + ctx, cancel = context.WithTimeout(ctx, cliTimeout) + defer cancel() + } + commandLine := "az account get-access-token -o json --resource " + resource + if tenantID != "" { + commandLine += " --tenant " + tenantID + } + if subscription != "" { + // subscription needs quotes because it may contain spaces + commandLine += ` --subscription "` + subscription + `"` + } + var cliCmd *exec.Cmd + if runtime.GOOS == "windows" { + dir := os.Getenv("SYSTEMROOT") + if dir == "" { + return nil, newCredentialUnavailableError(credNameAzureCLI, "environment variable 'SYSTEMROOT' has no value") + } + cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine) + cliCmd.Dir = dir + } else { + cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine) + cliCmd.Dir = "/bin" + } + cliCmd.Env = os.Environ() + var stderr bytes.Buffer + cliCmd.Stderr = &stderr + + output, err := cliCmd.Output() + if err != nil { + msg := stderr.String() + var exErr *exec.ExitError + if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'az' is not recognized") { + msg = "Azure CLI not found on path" + } + if msg == "" { + msg = err.Error() + } + return nil, newCredentialUnavailableError(credNameAzureCLI, msg) + } + + return output, nil +} + +func (c *AzureCLICredential) createAccessToken(tk []byte) (azcore.AccessToken, error) { + t := struct { + AccessToken string `json:"accessToken"` + Authority string `json:"_authority"` + ClientID string `json:"_clientId"` + ExpiresOn string `json:"expiresOn"` + IdentityProvider string `json:"identityProvider"` + IsMRRT bool `json:"isMRRT"` + RefreshToken string `json:"refreshToken"` + Resource string `json:"resource"` + TokenType string `json:"tokenType"` + UserID string `json:"userId"` + }{} + err := json.Unmarshal(tk, &t) + if err != nil { + return azcore.AccessToken{}, err + } + + // the Azure CLI's "expiresOn" is local time + exp, err := time.ParseInLocation("2006-01-02 15:04:05.999999", t.ExpiresOn, time.Local) + if err != nil { + return azcore.AccessToken{}, fmt.Errorf("Error parsing token expiration time %q: %v", t.ExpiresOn, err) + } + + converted := azcore.AccessToken{ + Token: t.AccessToken, + ExpiresOn: exp.UTC(), + } + return converted, nil +} + +var _ azcore.TokenCredential = (*AzureCLICredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go new file mode 100644 index 000000000..cbe7c4c2d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go @@ -0,0 +1,169 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +const credNameAzureDeveloperCLI = "AzureDeveloperCLICredential" + +type azdTokenProvider func(ctx context.Context, scopes []string, tenant string) ([]byte, error) + +// AzureDeveloperCLICredentialOptions contains optional parameters for AzureDeveloperCLICredential. +type AzureDeveloperCLICredentialOptions struct { + // AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition + // to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the + // logged in account can access. + AdditionallyAllowedTenants []string + + // TenantID identifies the tenant the credential should authenticate in. Defaults to the azd environment, + // which is the tenant of the selected Azure subscription. + TenantID string + + // inDefaultChain is true when the credential is part of DefaultAzureCredential + inDefaultChain bool + // tokenProvider is used by tests to fake invoking azd + tokenProvider azdTokenProvider +} + +// AzureDeveloperCLICredential authenticates as the identity logged in to the [Azure Developer CLI]. +// +// [Azure Developer CLI]: https://learn.microsoft.com/azure/developer/azure-developer-cli/overview +type AzureDeveloperCLICredential struct { + mu *sync.Mutex + opts AzureDeveloperCLICredentialOptions +} + +// NewAzureDeveloperCLICredential constructs an AzureDeveloperCLICredential. Pass nil to accept default options. +func NewAzureDeveloperCLICredential(options *AzureDeveloperCLICredentialOptions) (*AzureDeveloperCLICredential, error) { + cp := AzureDeveloperCLICredentialOptions{} + if options != nil { + cp = *options + } + if cp.TenantID != "" && !validTenantID(cp.TenantID) { + return nil, errInvalidTenantID + } + if cp.tokenProvider == nil { + cp.tokenProvider = defaultAzdTokenProvider + } + return &AzureDeveloperCLICredential{mu: &sync.Mutex{}, opts: cp}, nil +} + +// GetToken requests a token from the Azure Developer CLI. This credential doesn't cache tokens, so every call invokes azd. +// This method is called automatically by Azure SDK clients. +func (c *AzureDeveloperCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + at := azcore.AccessToken{} + if len(opts.Scopes) == 0 { + return at, errors.New(credNameAzureDeveloperCLI + ": GetToken() requires at least one scope") + } + for _, scope := range opts.Scopes { + if !validScope(scope) { + return at, fmt.Errorf("%s.GetToken(): invalid scope %q", credNameAzureDeveloperCLI, scope) + } + } + tenant, err := resolveTenant(c.opts.TenantID, opts.TenantID, credNameAzureDeveloperCLI, c.opts.AdditionallyAllowedTenants) + if err != nil { + return at, err + } + c.mu.Lock() + defer c.mu.Unlock() + b, err := c.opts.tokenProvider(ctx, opts.Scopes, tenant) + if err == nil { + at, err = c.createAccessToken(b) + } + if err != nil { + err = unavailableIfInChain(err, c.opts.inDefaultChain) + return at, err + } + msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", credNameAzureDeveloperCLI, strings.Join(opts.Scopes, ", ")) + log.Write(EventAuthentication, msg) + return at, nil +} + +// defaultAzTokenProvider invokes the Azure Developer CLI to acquire a token. It assumes +// callers have verified that all string arguments are safe to pass to the CLI. +var defaultAzdTokenProvider azdTokenProvider = func(ctx context.Context, scopes []string, tenant string) ([]byte, error) { + // set a default timeout for this authentication iff the application hasn't done so already + var cancel context.CancelFunc + if _, hasDeadline := ctx.Deadline(); !hasDeadline { + ctx, cancel = context.WithTimeout(ctx, cliTimeout) + defer cancel() + } + commandLine := "azd auth token -o json" + if tenant != "" { + commandLine += " --tenant-id " + tenant + } + for _, scope := range scopes { + commandLine += " --scope " + scope + } + var cliCmd *exec.Cmd + if runtime.GOOS == "windows" { + dir := os.Getenv("SYSTEMROOT") + if dir == "" { + return nil, newCredentialUnavailableError(credNameAzureDeveloperCLI, "environment variable 'SYSTEMROOT' has no value") + } + cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine) + cliCmd.Dir = dir + } else { + cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine) + cliCmd.Dir = "/bin" + } + cliCmd.Env = os.Environ() + var stderr bytes.Buffer + cliCmd.Stderr = &stderr + output, err := cliCmd.Output() + if err != nil { + msg := stderr.String() + var exErr *exec.ExitError + if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'azd' is not recognized") { + msg = "Azure Developer CLI not found on path" + } else if strings.Contains(msg, "azd auth login") { + msg = `please run "azd auth login" from a command prompt to authenticate before using this credential` + } + if msg == "" { + msg = err.Error() + } + return nil, newCredentialUnavailableError(credNameAzureDeveloperCLI, msg) + } + return output, nil +} + +func (c *AzureDeveloperCLICredential) createAccessToken(tk []byte) (azcore.AccessToken, error) { + t := struct { + AccessToken string `json:"token"` + ExpiresOn string `json:"expiresOn"` + }{} + err := json.Unmarshal(tk, &t) + if err != nil { + return azcore.AccessToken{}, err + } + exp, err := time.Parse("2006-01-02T15:04:05Z", t.ExpiresOn) + if err != nil { + return azcore.AccessToken{}, fmt.Errorf("error parsing token expiration time %q: %v", t.ExpiresOn, err) + } + return azcore.AccessToken{ + ExpiresOn: exp.UTC(), + Token: t.AccessToken, + }, nil +} + +var _ azcore.TokenCredential = (*AzureDeveloperCLICredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go new file mode 100644 index 000000000..dc855edf7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go @@ -0,0 +1,138 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +// ChainedTokenCredentialOptions contains optional parameters for ChainedTokenCredential. +type ChainedTokenCredentialOptions struct { + // RetrySources configures how the credential uses its sources. When true, the credential always attempts to + // authenticate through each source in turn, stopping when one succeeds. When false, the credential authenticates + // only through this first successful source--it never again tries the sources which failed. + RetrySources bool +} + +// ChainedTokenCredential links together multiple credentials and tries them sequentially when authenticating. By default, +// it tries all the credentials until one authenticates, after which it always uses that credential. +type ChainedTokenCredential struct { + cond *sync.Cond + iterating bool + name string + retrySources bool + sources []azcore.TokenCredential + successfulCredential azcore.TokenCredential +} + +// NewChainedTokenCredential creates a ChainedTokenCredential. Pass nil for options to accept defaults. +func NewChainedTokenCredential(sources []azcore.TokenCredential, options *ChainedTokenCredentialOptions) (*ChainedTokenCredential, error) { + if len(sources) == 0 { + return nil, errors.New("sources must contain at least one TokenCredential") + } + for _, source := range sources { + if source == nil { // cannot have a nil credential in the chain or else the application will panic when GetToken() is called on nil + return nil, errors.New("sources cannot contain nil") + } + } + cp := make([]azcore.TokenCredential, len(sources)) + copy(cp, sources) + if options == nil { + options = &ChainedTokenCredentialOptions{} + } + return &ChainedTokenCredential{ + cond: sync.NewCond(&sync.Mutex{}), + name: "ChainedTokenCredential", + retrySources: options.RetrySources, + sources: cp, + }, nil +} + +// GetToken calls GetToken on the chained credentials in turn, stopping when one returns a token. +// This method is called automatically by Azure SDK clients. +func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if !c.retrySources { + // ensure only one goroutine at a time iterates the sources and perhaps sets c.successfulCredential + c.cond.L.Lock() + for { + if c.successfulCredential != nil { + c.cond.L.Unlock() + return c.successfulCredential.GetToken(ctx, opts) + } + if !c.iterating { + c.iterating = true + // allow other goroutines to wait while this one iterates + c.cond.L.Unlock() + break + } + c.cond.Wait() + } + } + + var ( + err error + errs []error + successfulCredential azcore.TokenCredential + token azcore.AccessToken + unavailableErr *credentialUnavailableError + ) + for _, cred := range c.sources { + token, err = cred.GetToken(ctx, opts) + if err == nil { + log.Writef(EventAuthentication, "%s authenticated with %s", c.name, extractCredentialName(cred)) + successfulCredential = cred + break + } + errs = append(errs, err) + // continue to the next source iff this one returned credentialUnavailableError + if !errors.As(err, &unavailableErr) { + break + } + } + if c.iterating { + c.cond.L.Lock() + // this is nil when all credentials returned an error + c.successfulCredential = successfulCredential + c.iterating = false + c.cond.L.Unlock() + c.cond.Broadcast() + } + // err is the error returned by the last GetToken call. It will be nil when that call succeeds + if err != nil { + // return credentialUnavailableError iff all sources did so; return AuthenticationFailedError otherwise + msg := createChainedErrorMessage(errs) + if errors.As(err, &unavailableErr) { + err = newCredentialUnavailableError(c.name, msg) + } else { + res := getResponseFromError(err) + err = newAuthenticationFailedError(c.name, msg, res, err) + } + } + return token, err +} + +func createChainedErrorMessage(errs []error) string { + msg := "failed to acquire a token.\nAttempted credentials:" + for _, err := range errs { + msg += fmt.Sprintf("\n\t%s", err.Error()) + } + return msg +} + +func extractCredentialName(credential azcore.TokenCredential) string { + return strings.TrimPrefix(fmt.Sprintf("%T", credential), "*azidentity.") +} + +var _ azcore.TokenCredential = (*ChainedTokenCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml new file mode 100644 index 000000000..d077682c5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml @@ -0,0 +1,35 @@ +# 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/azidentity/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/azidentity/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + RunLiveTests: true + UsePipelineProxy: false + ServiceDirectory: 'azidentity' + CloudConfig: + Public: + SubscriptionConfigurations: + - $(sub-config-azure-cloud-test-resources) + # Contains alternate tenant, AAD app and cert info for testing + - $(sub-config-identity-test-resources) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go new file mode 100644 index 000000000..fc3df68eb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go @@ -0,0 +1,85 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const credNameAssertion = "ClientAssertionCredential" + +// ClientAssertionCredential authenticates an application with assertions provided by a callback function. +// This credential is for advanced scenarios. [ClientCertificateCredential] has a more convenient API for +// the most common assertion scenario, authenticating a service principal with a certificate. See +// [Microsoft Entra ID documentation] for details of the assertion format. +// +// [Microsoft Entra ID documentation]: https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#assertion-format +type ClientAssertionCredential struct { + client *confidentialClient +} + +// ClientAssertionCredentialOptions contains optional parameters for ClientAssertionCredential. +type ClientAssertionCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. + // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the + // application is registered. + AdditionallyAllowedTenants []string + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions +} + +// NewClientAssertionCredential constructs a ClientAssertionCredential. The getAssertion function must be thread safe. Pass nil for options to accept defaults. +func NewClientAssertionCredential(tenantID, clientID string, getAssertion func(context.Context) (string, error), options *ClientAssertionCredentialOptions) (*ClientAssertionCredential, error) { + if getAssertion == nil { + return nil, errors.New("getAssertion must be a function that returns assertions") + } + if options == nil { + options = &ClientAssertionCredentialOptions{} + } + cred := confidential.NewCredFromAssertionCallback( + func(ctx context.Context, _ confidential.AssertionRequestOptions) (string, error) { + return getAssertion(ctx) + }, + ) + msalOpts := confidentialClientOptions{ + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + tokenCachePersistenceOptions: options.tokenCachePersistenceOptions, + } + c, err := newConfidentialClient(tenantID, clientID, credNameAssertion, cred, msalOpts) + if err != nil { + return nil, err + } + return &ClientAssertionCredential{client: c}, nil +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (c *ClientAssertionCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameAssertion+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err +} + +var _ azcore.TokenCredential = (*ClientAssertionCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go new file mode 100644 index 000000000..607533f48 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go @@ -0,0 +1,171 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "crypto" + "crypto/x509" + "encoding/pem" + "errors" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" + "golang.org/x/crypto/pkcs12" +) + +const credNameCert = "ClientCertificateCredential" + +// ClientCertificateCredentialOptions contains optional parameters for ClientCertificateCredential. +type ClientCertificateCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. + // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the + // application is registered. + AdditionallyAllowedTenants []string + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + + // SendCertificateChain controls whether the credential sends the public certificate chain in the x5c + // header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. + // Defaults to False. + SendCertificateChain bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions +} + +// ClientCertificateCredential authenticates a service principal with a certificate. +type ClientCertificateCredential struct { + client *confidentialClient +} + +// NewClientCertificateCredential constructs a ClientCertificateCredential. Pass nil for options to accept defaults. +func NewClientCertificateCredential(tenantID string, clientID string, certs []*x509.Certificate, key crypto.PrivateKey, options *ClientCertificateCredentialOptions) (*ClientCertificateCredential, error) { + if len(certs) == 0 { + return nil, errors.New("at least one certificate is required") + } + if options == nil { + options = &ClientCertificateCredentialOptions{} + } + cred, err := confidential.NewCredFromCert(certs, key) + if err != nil { + return nil, err + } + msalOpts := confidentialClientOptions{ + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + SendX5C: options.SendCertificateChain, + tokenCachePersistenceOptions: options.tokenCachePersistenceOptions, + } + c, err := newConfidentialClient(tenantID, clientID, credNameCert, cred, msalOpts) + if err != nil { + return nil, err + } + return &ClientCertificateCredential{client: c}, nil +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameCert+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err +} + +// ParseCertificates loads certificates and a private key, in PEM or PKCS12 format, for use with NewClientCertificateCredential. +// Pass nil for password if the private key isn't encrypted. This function can't decrypt keys in PEM format. +func ParseCertificates(certData []byte, password []byte) ([]*x509.Certificate, crypto.PrivateKey, error) { + var blocks []*pem.Block + var err error + if len(password) == 0 { + blocks, err = loadPEMCert(certData) + } + if len(blocks) == 0 || err != nil { + blocks, err = loadPKCS12Cert(certData, string(password)) + } + if err != nil { + return nil, nil, err + } + var certs []*x509.Certificate + var pk crypto.PrivateKey + for _, block := range blocks { + switch block.Type { + case "CERTIFICATE": + c, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, nil, err + } + certs = append(certs, c) + case "PRIVATE KEY": + if pk != nil { + return nil, nil, errors.New("certData contains multiple private keys") + } + pk, err = x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + pk, err = x509.ParsePKCS1PrivateKey(block.Bytes) + } + if err != nil { + return nil, nil, err + } + case "RSA PRIVATE KEY": + if pk != nil { + return nil, nil, errors.New("certData contains multiple private keys") + } + pk, err = x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, nil, err + } + } + } + if len(certs) == 0 { + return nil, nil, errors.New("found no certificate") + } + if pk == nil { + return nil, nil, errors.New("found no private key") + } + return certs, pk, nil +} + +func loadPEMCert(certData []byte) ([]*pem.Block, error) { + blocks := []*pem.Block{} + for { + var block *pem.Block + block, certData = pem.Decode(certData) + if block == nil { + break + } + blocks = append(blocks, block) + } + if len(blocks) == 0 { + return nil, errors.New("didn't find any PEM blocks") + } + return blocks, nil +} + +func loadPKCS12Cert(certData []byte, password string) ([]*pem.Block, error) { + blocks, err := pkcs12.ToPEM(certData, password) + if err != nil { + return nil, err + } + if len(blocks) == 0 { + // not mentioning PKCS12 in this message because we end up here when certData is garbage + return nil, errors.New("didn't find any certificate content") + } + return blocks, err +} + +var _ azcore.TokenCredential = (*ClientCertificateCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go new file mode 100644 index 000000000..9e6772e9b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go @@ -0,0 +1,75 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const credNameSecret = "ClientSecretCredential" + +// ClientSecretCredentialOptions contains optional parameters for ClientSecretCredential. +type ClientSecretCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. + // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the + // application is registered. + AdditionallyAllowedTenants []string + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions +} + +// ClientSecretCredential authenticates an application with a client secret. +type ClientSecretCredential struct { + client *confidentialClient +} + +// NewClientSecretCredential constructs a ClientSecretCredential. Pass nil for options to accept defaults. +func NewClientSecretCredential(tenantID string, clientID string, clientSecret string, options *ClientSecretCredentialOptions) (*ClientSecretCredential, error) { + if options == nil { + options = &ClientSecretCredentialOptions{} + } + cred, err := confidential.NewCredFromSecret(clientSecret) + if err != nil { + return nil, err + } + msalOpts := confidentialClientOptions{ + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + tokenCachePersistenceOptions: options.tokenCachePersistenceOptions, + } + c, err := newConfidentialClient(tenantID, clientID, credNameSecret, cred, msalOpts) + if err != nil { + return nil, err + } + return &ClientSecretCredential{client: c}, nil +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (c *ClientSecretCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameSecret+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err +} + +var _ azcore.TokenCredential = (*ClientSecretCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go new file mode 100644 index 000000000..854267bdb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go @@ -0,0 +1,184 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "strings" + "sync" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +type confidentialClientOptions struct { + azcore.ClientOptions + + AdditionallyAllowedTenants []string + // Assertion for on-behalf-of authentication + Assertion string + DisableInstanceDiscovery, SendX5C bool + tokenCachePersistenceOptions *tokenCachePersistenceOptions +} + +// confidentialClient wraps the MSAL confidential client +type confidentialClient struct { + cae, noCAE msalConfidentialClient + caeMu, noCAEMu, clientMu *sync.Mutex + clientID, tenantID string + cred confidential.Credential + host string + name string + opts confidentialClientOptions + region string + azClient *azcore.Client +} + +func newConfidentialClient(tenantID, clientID, name string, cred confidential.Credential, opts confidentialClientOptions) (*confidentialClient, error) { + if !validTenantID(tenantID) { + return nil, errInvalidTenantID + } + host, err := setAuthorityHost(opts.Cloud) + if err != nil { + return nil, err + } + client, err := azcore.NewClient(module, version, runtime.PipelineOptions{ + Tracing: runtime.TracingOptions{ + Namespace: traceNamespace, + }, + }, &opts.ClientOptions) + if err != nil { + return nil, err + } + opts.AdditionallyAllowedTenants = resolveAdditionalTenants(opts.AdditionallyAllowedTenants) + return &confidentialClient{ + caeMu: &sync.Mutex{}, + clientID: clientID, + clientMu: &sync.Mutex{}, + cred: cred, + host: host, + name: name, + noCAEMu: &sync.Mutex{}, + opts: opts, + region: os.Getenv(azureRegionalAuthorityName), + tenantID: tenantID, + azClient: client, + }, nil +} + +// GetToken requests an access token from MSAL, checking the cache first. +func (c *confidentialClient) GetToken(ctx context.Context, tro policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(tro.Scopes) < 1 { + return azcore.AccessToken{}, fmt.Errorf("%s.GetToken() requires at least one scope", c.name) + } + // we don't resolve the tenant for managed identities because they acquire tokens only from their home tenants + if c.name != credNameManagedIdentity { + tenant, err := c.resolveTenant(tro.TenantID) + if err != nil { + return azcore.AccessToken{}, err + } + tro.TenantID = tenant + } + client, mu, err := c.client(ctx, tro) + if err != nil { + return azcore.AccessToken{}, err + } + mu.Lock() + defer mu.Unlock() + var ar confidential.AuthResult + if c.opts.Assertion != "" { + ar, err = client.AcquireTokenOnBehalfOf(ctx, c.opts.Assertion, tro.Scopes, confidential.WithClaims(tro.Claims), confidential.WithTenantID(tro.TenantID)) + } else { + ar, err = client.AcquireTokenSilent(ctx, tro.Scopes, confidential.WithClaims(tro.Claims), confidential.WithTenantID(tro.TenantID)) + if err != nil { + ar, err = client.AcquireTokenByCredential(ctx, tro.Scopes, confidential.WithClaims(tro.Claims), confidential.WithTenantID(tro.TenantID)) + } + } + if err != nil { + // We could get a credentialUnavailableError from managed identity authentication because in that case the error comes from our code. + // We return it directly because it affects the behavior of credential chains. Otherwise, we return AuthenticationFailedError. + var unavailableErr *credentialUnavailableError + if !errors.As(err, &unavailableErr) { + res := getResponseFromError(err) + err = newAuthenticationFailedError(c.name, err.Error(), res, err) + } + } else { + msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", c.name, strings.Join(ar.GrantedScopes, ", ")) + log.Write(EventAuthentication, msg) + } + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +func (c *confidentialClient) client(ctx context.Context, tro policy.TokenRequestOptions) (msalConfidentialClient, *sync.Mutex, error) { + c.clientMu.Lock() + defer c.clientMu.Unlock() + if tro.EnableCAE { + if c.cae == nil { + client, err := c.newMSALClient(true) + if err != nil { + return nil, nil, err + } + c.cae = client + } + return c.cae, c.caeMu, nil + } + if c.noCAE == nil { + client, err := c.newMSALClient(false) + if err != nil { + return nil, nil, err + } + c.noCAE = client + } + return c.noCAE, c.noCAEMu, nil +} + +func (c *confidentialClient) newMSALClient(enableCAE bool) (msalConfidentialClient, error) { + cache, err := internal.NewCache(c.opts.tokenCachePersistenceOptions, enableCAE) + if err != nil { + return nil, err + } + authority := runtime.JoinPaths(c.host, c.tenantID) + o := []confidential.Option{ + confidential.WithAzureRegion(c.region), + confidential.WithCache(cache), + confidential.WithHTTPClient(c), + } + if enableCAE { + o = append(o, confidential.WithClientCapabilities(cp1)) + } + if c.opts.SendX5C { + o = append(o, confidential.WithX5C()) + } + if c.opts.DisableInstanceDiscovery || strings.ToLower(c.tenantID) == "adfs" { + o = append(o, confidential.WithInstanceDiscovery(false)) + } + return confidential.New(authority, c.clientID, c.cred, o...) +} + +// resolveTenant returns the correct WithTenantID() argument for a token request given the client's +// configuration, or an error when that configuration doesn't allow the specified tenant +func (c *confidentialClient) resolveTenant(specified string) (string, error) { + return resolveTenant(c.tenantID, specified, c.name, c.opts.AdditionallyAllowedTenants) +} + +// these methods satisfy the MSAL ops.HTTPClient interface + +func (c *confidentialClient) CloseIdleConnections() { + // do nothing +} + +func (c *confidentialClient) Do(r *http.Request) (*http.Response, error) { + return doForClient(c.azClient, r) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go new file mode 100644 index 000000000..35aeef867 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go @@ -0,0 +1,208 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "os" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +// DefaultAzureCredentialOptions contains optional parameters for DefaultAzureCredential. +// These options may not apply to all credentials in the chain. +type DefaultAzureCredentialOptions struct { + // ClientOptions has additional options for credentials that use an Azure SDK HTTP pipeline. These options don't apply + // to credential types that authenticate via external tools such as the Azure CLI. + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. Add + // the wildcard value "*" to allow the credential to acquire tokens for any tenant. This value can also be + // set as a semicolon delimited list of tenants in the environment variable AZURE_ADDITIONALLY_ALLOWED_TENANTS. + AdditionallyAllowedTenants []string + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + // TenantID sets the default tenant for authentication via the Azure CLI and workload identity. + TenantID string +} + +// DefaultAzureCredential is a default credential chain for applications that will deploy to Azure. +// It combines credentials suitable for deployment with credentials suitable for local development. +// It attempts to authenticate with each of these credential types, in the following order, stopping +// when one provides a token: +// +// - [EnvironmentCredential] +// - [WorkloadIdentityCredential], if environment variable configuration is set by the Azure workload +// identity webhook. Use [WorkloadIdentityCredential] directly when not using the webhook or needing +// more control over its configuration. +// - [ManagedIdentityCredential] +// - [AzureCLICredential] +// - [AzureDeveloperCLICredential] +// +// Consult the documentation for these credential types for more information on how they authenticate. +// Once a credential has successfully authenticated, DefaultAzureCredential will use that credential for +// every subsequent authentication. +type DefaultAzureCredential struct { + chain *ChainedTokenCredential +} + +// NewDefaultAzureCredential creates a DefaultAzureCredential. Pass nil for options to accept defaults. +func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*DefaultAzureCredential, error) { + var creds []azcore.TokenCredential + var errorMessages []string + + if options == nil { + options = &DefaultAzureCredentialOptions{} + } + additionalTenants := options.AdditionallyAllowedTenants + if len(additionalTenants) == 0 { + if tenants := os.Getenv(azureAdditionallyAllowedTenants); tenants != "" { + additionalTenants = strings.Split(tenants, ";") + } + } + + envCred, err := NewEnvironmentCredential(&EnvironmentCredentialOptions{ + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + additionallyAllowedTenants: additionalTenants, + }) + if err == nil { + creds = append(creds, envCred) + } else { + errorMessages = append(errorMessages, "EnvironmentCredential: "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: "EnvironmentCredential", err: err}) + } + + wic, err := NewWorkloadIdentityCredential(&WorkloadIdentityCredentialOptions{ + AdditionallyAllowedTenants: additionalTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + TenantID: options.TenantID, + }) + if err == nil { + creds = append(creds, wic) + } else { + errorMessages = append(errorMessages, credNameWorkloadIdentity+": "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: credNameWorkloadIdentity, err: err}) + } + + o := &ManagedIdentityCredentialOptions{ClientOptions: options.ClientOptions} + if ID, ok := os.LookupEnv(azureClientID); ok { + o.ID = ClientID(ID) + } + miCred, err := NewManagedIdentityCredential(o) + if err == nil { + creds = append(creds, &timeoutWrapper{mic: miCred, timeout: time.Second}) + } else { + errorMessages = append(errorMessages, credNameManagedIdentity+": "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: credNameManagedIdentity, err: err}) + } + + cliCred, err := NewAzureCLICredential(&AzureCLICredentialOptions{AdditionallyAllowedTenants: additionalTenants, TenantID: options.TenantID}) + if err == nil { + creds = append(creds, cliCred) + } else { + errorMessages = append(errorMessages, credNameAzureCLI+": "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: credNameAzureCLI, err: err}) + } + + azdCred, err := NewAzureDeveloperCLICredential(&AzureDeveloperCLICredentialOptions{ + AdditionallyAllowedTenants: additionalTenants, + TenantID: options.TenantID, + }) + if err == nil { + creds = append(creds, azdCred) + } else { + errorMessages = append(errorMessages, credNameAzureDeveloperCLI+": "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: credNameAzureDeveloperCLI, err: err}) + } + + if len(errorMessages) > 0 { + log.Writef(EventAuthentication, "NewDefaultAzureCredential failed to initialize some credentials:\n\t%s", strings.Join(errorMessages, "\n\t")) + } + + chain, err := NewChainedTokenCredential(creds, nil) + if err != nil { + return nil, err + } + chain.name = "DefaultAzureCredential" + return &DefaultAzureCredential{chain: chain}, nil +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (c *DefaultAzureCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + return c.chain.GetToken(ctx, opts) +} + +var _ azcore.TokenCredential = (*DefaultAzureCredential)(nil) + +// defaultCredentialErrorReporter is a substitute for credentials that couldn't be constructed. +// Its GetToken method always returns a credentialUnavailableError having the same message as +// the error that prevented constructing the credential. This ensures the message is present +// in the error returned by ChainedTokenCredential.GetToken() +type defaultCredentialErrorReporter struct { + credType string + err error +} + +func (d *defaultCredentialErrorReporter) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if _, ok := d.err.(*credentialUnavailableError); ok { + return azcore.AccessToken{}, d.err + } + return azcore.AccessToken{}, newCredentialUnavailableError(d.credType, d.err.Error()) +} + +var _ azcore.TokenCredential = (*defaultCredentialErrorReporter)(nil) + +// timeoutWrapper prevents a potentially very long timeout when managed identity isn't available +type timeoutWrapper struct { + mic *ManagedIdentityCredential + // timeout applies to all auth attempts until one doesn't time out + timeout time.Duration +} + +// GetToken wraps DefaultAzureCredential's initial managed identity auth attempt with a short timeout +// because managed identity may not be available and connecting to IMDS can take several minutes to time out. +func (w *timeoutWrapper) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var tk azcore.AccessToken + var err error + // no need to synchronize around this value because it's written only within ChainedTokenCredential's critical section + if w.timeout > 0 { + c, cancel := context.WithTimeout(ctx, w.timeout) + defer cancel() + tk, err = w.mic.GetToken(c, opts) + if isAuthFailedDueToContext(err) { + err = newCredentialUnavailableError(credNameManagedIdentity, "managed identity timed out. See https://aka.ms/azsdk/go/identity/troubleshoot#dac for more information") + } else { + // some managed identity implementation is available, so don't apply the timeout to future calls + w.timeout = 0 + } + } else { + tk, err = w.mic.GetToken(ctx, opts) + } + return tk, err +} + +// unwraps nested AuthenticationFailedErrors to get the root error +func isAuthFailedDueToContext(err error) bool { + for { + var authFailedErr *AuthenticationFailedError + if !errors.As(err, &authFailedErr) { + break + } + err = authFailedErr.err + } + return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/developer_credential_util.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/developer_credential_util.go new file mode 100644 index 000000000..d8b952f53 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/developer_credential_util.go @@ -0,0 +1,38 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "errors" + "time" +) + +// cliTimeout is the default timeout for authentication attempts via CLI tools +const cliTimeout = 10 * time.Second + +// unavailableIfInChain returns err or, if the credential was invoked by DefaultAzureCredential, a +// credentialUnavailableError having the same message. This ensures DefaultAzureCredential will try +// the next credential in its chain (another developer credential). +func unavailableIfInChain(err error, inDefaultChain bool) error { + if err != nil && inDefaultChain { + var unavailableErr *credentialUnavailableError + if !errors.As(err, &unavailableErr) { + err = newCredentialUnavailableError(credNameAzureDeveloperCLI, err.Error()) + } + } + return err +} + +// validScope is for credentials authenticating via external tools. The authority validates scopes for all other credentials. +func validScope(scope string) bool { + for _, r := range scope { + if !(alphanumeric(r) || r == '.' || r == '-' || r == '_' || r == '/' || r == ':') { + return false + } + } + return true +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go new file mode 100644 index 000000000..1b7a28370 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go @@ -0,0 +1,138 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "fmt" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +const credNameDeviceCode = "DeviceCodeCredential" + +// DeviceCodeCredentialOptions contains optional parameters for DeviceCodeCredential. +type DeviceCodeCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire + // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. + AdditionallyAllowedTenants []string + + // authenticationRecord returned by a call to a credential's Authenticate method. Set this option + // to enable the credential to use data from a previous authentication. + authenticationRecord authenticationRecord + + // ClientID is the ID of the application users will authenticate to. + // Defaults to the ID of an Azure development application. + ClientID string + + // disableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate. + // When this option is true, [DeviceCodeCredential.GetToken] will return [ErrAuthenticationRequired] when user + // interaction is necessary to acquire a token. + disableAutomaticAuthentication bool + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + + // TenantID is the Microsoft Entra tenant the credential authenticates in. Defaults to the + // "organizations" tenant, which can authenticate work and school accounts. Required for single-tenant + // applications. + TenantID string + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions + + // UserPrompt controls how the credential presents authentication instructions. The credential calls + // this function with authentication details when it receives a device code. By default, the credential + // prints these details to stdout. + UserPrompt func(context.Context, DeviceCodeMessage) error +} + +func (o *DeviceCodeCredentialOptions) init() { + if o.TenantID == "" { + o.TenantID = organizationsTenantID + } + if o.ClientID == "" { + o.ClientID = developerSignOnClientID + } + if o.UserPrompt == nil { + o.UserPrompt = func(ctx context.Context, dc DeviceCodeMessage) error { + fmt.Println(dc.Message) + return nil + } + } +} + +// DeviceCodeMessage contains the information a user needs to complete authentication. +type DeviceCodeMessage struct { + // UserCode is the user code returned by the service. + UserCode string `json:"user_code"` + // VerificationURL is the URL at which the user must authenticate. + VerificationURL string `json:"verification_uri"` + // Message is user instruction from Microsoft Entra ID. + Message string `json:"message"` +} + +// DeviceCodeCredential acquires tokens for a user via the device code flow, which has the +// user browse to a Microsoft Entra URL, enter a code, and authenticate. It's useful +// for authenticating a user in an environment without a web browser, such as an SSH session. +// If a web browser is available, [InteractiveBrowserCredential] is more convenient because it +// automatically opens a browser to the login page. +type DeviceCodeCredential struct { + client *publicClient +} + +// NewDeviceCodeCredential creates a DeviceCodeCredential. Pass nil to accept default options. +func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeCredential, error) { + cp := DeviceCodeCredentialOptions{} + if options != nil { + cp = *options + } + cp.init() + msalOpts := publicClientOptions{ + AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants, + ClientOptions: cp.ClientOptions, + DeviceCodePrompt: cp.UserPrompt, + DisableAutomaticAuthentication: cp.disableAutomaticAuthentication, + DisableInstanceDiscovery: cp.DisableInstanceDiscovery, + Record: cp.authenticationRecord, + TokenCachePersistenceOptions: cp.tokenCachePersistenceOptions, + } + c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameDeviceCode, msalOpts) + if err != nil { + return nil, err + } + c.name = credNameDeviceCode + return &DeviceCodeCredential{client: c}, nil +} + +// Authenticate a user via the device code flow. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. +func (c *DeviceCodeCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameDeviceCode+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.Authenticate(ctx, opts) + return tk, err +} + +// GetToken requests an access token from Microsoft Entra ID. It will begin the device code flow and poll until the user completes authentication. +// This method is called automatically by Azure SDK clients. +func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameDeviceCode+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err +} + +var _ azcore.TokenCredential = (*DeviceCodeCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go new file mode 100644 index 000000000..42f84875e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go @@ -0,0 +1,164 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +const envVarSendCertChain = "AZURE_CLIENT_SEND_CERTIFICATE_CHAIN" + +// EnvironmentCredentialOptions contains optional parameters for EnvironmentCredential +type EnvironmentCredentialOptions struct { + azcore.ClientOptions + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + // additionallyAllowedTenants is used only by NewDefaultAzureCredential() to enable that constructor's explicit + // option to override the value of AZURE_ADDITIONALLY_ALLOWED_TENANTS. Applications using EnvironmentCredential + // directly should set that variable instead. This field should remain unexported to preserve this credential's + // unambiguous "all configuration from environment variables" design. + additionallyAllowedTenants []string +} + +// EnvironmentCredential authenticates a service principal with a secret or certificate, or a user with a password, depending +// on environment variable configuration. It reads configuration from these variables, in the following order: +// +// # Service principal with client secret +// +// AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID. +// +// AZURE_CLIENT_ID: the service principal's client ID +// +// AZURE_CLIENT_SECRET: one of the service principal's client secrets +// +// # Service principal with certificate +// +// AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID. +// +// AZURE_CLIENT_ID: the service principal's client ID +// +// AZURE_CLIENT_CERTIFICATE_PATH: path to a PEM or PKCS12 certificate file including the private key. +// +// AZURE_CLIENT_CERTIFICATE_PASSWORD: (optional) password for the certificate file. +// +// # User with username and password +// +// AZURE_TENANT_ID: (optional) tenant to authenticate in. Defaults to "organizations". +// +// AZURE_CLIENT_ID: client ID of the application the user will authenticate to +// +// AZURE_USERNAME: a username (usually an email address) +// +// AZURE_PASSWORD: the user's password +// +// # Configuration for multitenant applications +// +// To enable multitenant authentication, set AZURE_ADDITIONALLY_ALLOWED_TENANTS with a semicolon delimited list of tenants +// the credential may request tokens from in addition to the tenant specified by AZURE_TENANT_ID. Set +// AZURE_ADDITIONALLY_ALLOWED_TENANTS to "*" to enable the credential to request a token from any tenant. +type EnvironmentCredential struct { + cred azcore.TokenCredential +} + +// NewEnvironmentCredential creates an EnvironmentCredential. Pass nil to accept default options. +func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*EnvironmentCredential, error) { + if options == nil { + options = &EnvironmentCredentialOptions{} + } + tenantID := os.Getenv(azureTenantID) + if tenantID == "" { + return nil, errors.New("missing environment variable AZURE_TENANT_ID") + } + clientID := os.Getenv(azureClientID) + if clientID == "" { + return nil, errors.New("missing environment variable " + azureClientID) + } + // tenants set by NewDefaultAzureCredential() override the value of AZURE_ADDITIONALLY_ALLOWED_TENANTS + additionalTenants := options.additionallyAllowedTenants + if len(additionalTenants) == 0 { + if tenants := os.Getenv(azureAdditionallyAllowedTenants); tenants != "" { + additionalTenants = strings.Split(tenants, ";") + } + } + if clientSecret := os.Getenv(azureClientSecret); clientSecret != "" { + log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientSecretCredential") + o := &ClientSecretCredentialOptions{ + AdditionallyAllowedTenants: additionalTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + } + cred, err := NewClientSecretCredential(tenantID, clientID, clientSecret, o) + if err != nil { + return nil, err + } + return &EnvironmentCredential{cred: cred}, nil + } + if certPath := os.Getenv(azureClientCertificatePath); certPath != "" { + log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientCertificateCredential") + certData, err := os.ReadFile(certPath) + if err != nil { + return nil, fmt.Errorf(`failed to read certificate file "%s": %v`, certPath, err) + } + var password []byte + if v := os.Getenv(azureClientCertificatePassword); v != "" { + password = []byte(v) + } + certs, key, err := ParseCertificates(certData, password) + if err != nil { + return nil, fmt.Errorf(`failed to load certificate from "%s": %v`, certPath, err) + } + o := &ClientCertificateCredentialOptions{ + AdditionallyAllowedTenants: additionalTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + } + if v, ok := os.LookupEnv(envVarSendCertChain); ok { + o.SendCertificateChain = v == "1" || strings.ToLower(v) == "true" + } + cred, err := NewClientCertificateCredential(tenantID, clientID, certs, key, o) + if err != nil { + return nil, err + } + return &EnvironmentCredential{cred: cred}, nil + } + if username := os.Getenv(azureUsername); username != "" { + if password := os.Getenv(azurePassword); password != "" { + log.Write(EventAuthentication, "EnvironmentCredential will authenticate with UsernamePasswordCredential") + o := &UsernamePasswordCredentialOptions{ + AdditionallyAllowedTenants: additionalTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + } + cred, err := NewUsernamePasswordCredential(tenantID, clientID, username, password, o) + if err != nil { + return nil, err + } + return &EnvironmentCredential{cred: cred}, nil + } + return nil, errors.New("no value for AZURE_PASSWORD") + } + return nil, errors.New("incomplete environment variable configuration. Only AZURE_TENANT_ID and AZURE_CLIENT_ID are set") +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (c *EnvironmentCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + return c.cred.GetToken(ctx, opts) +} + +var _ azcore.TokenCredential = (*EnvironmentCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go new file mode 100644 index 000000000..335d2b7dc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go @@ -0,0 +1,140 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" + msal "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" +) + +// errAuthenticationRequired indicates a credential's Authenticate method must be called to acquire a token +// because user interaction is required and the credential is configured not to automatically prompt the user. +var errAuthenticationRequired error = &credentialUnavailableError{"can't acquire a token without user interaction. Call Authenticate to interactively authenticate a user"} + +// getResponseFromError retrieves the response carried by +// an AuthenticationFailedError or MSAL CallErr, if any +func getResponseFromError(err error) *http.Response { + var a *AuthenticationFailedError + var c msal.CallErr + var res *http.Response + if errors.As(err, &c) { + res = c.Resp + } else if errors.As(err, &a) { + res = a.RawResponse + } + return res +} + +// AuthenticationFailedError indicates an authentication request has failed. +type AuthenticationFailedError struct { + // RawResponse is the HTTP response motivating the error, if available. + RawResponse *http.Response + + credType string + message string + err error +} + +func newAuthenticationFailedError(credType string, message string, resp *http.Response, err error) error { + return &AuthenticationFailedError{credType: credType, message: message, RawResponse: resp, err: err} +} + +// Error implements the error interface. Note that the message contents are not contractual and can change over time. +func (e *AuthenticationFailedError) Error() string { + if e.RawResponse == nil { + return e.credType + ": " + e.message + } + msg := &bytes.Buffer{} + fmt.Fprintf(msg, e.credType+" authentication failed\n") + if e.RawResponse.Request != nil { + fmt.Fprintf(msg, "%s %s://%s%s\n", e.RawResponse.Request.Method, e.RawResponse.Request.URL.Scheme, e.RawResponse.Request.URL.Host, e.RawResponse.Request.URL.Path) + } else { + // this happens when the response is created from a custom HTTP transporter, + // which doesn't guarantee to bind the original request to the response + fmt.Fprintln(msg, "Request information not available") + } + fmt.Fprintln(msg, "--------------------------------------------------------------------------------") + fmt.Fprintf(msg, "RESPONSE %s\n", e.RawResponse.Status) + fmt.Fprintln(msg, "--------------------------------------------------------------------------------") + body, err := runtime.Payload(e.RawResponse) + switch { + case err != nil: + fmt.Fprintf(msg, "Error reading response body: %v", err) + case len(body) > 0: + if err := json.Indent(msg, body, "", " "); err != nil { + // failed to pretty-print so just dump it verbatim + fmt.Fprint(msg, string(body)) + } + default: + fmt.Fprint(msg, "Response contained no body") + } + fmt.Fprintln(msg, "\n--------------------------------------------------------------------------------") + var anchor string + switch e.credType { + case credNameAzureCLI: + anchor = "azure-cli" + case credNameAzureDeveloperCLI: + anchor = "azd" + case credNameCert: + anchor = "client-cert" + case credNameSecret: + anchor = "client-secret" + case credNameManagedIdentity: + anchor = "managed-id" + case credNameUserPassword: + anchor = "username-password" + case credNameWorkloadIdentity: + anchor = "workload" + } + if anchor != "" { + fmt.Fprintf(msg, "To troubleshoot, visit https://aka.ms/azsdk/go/identity/troubleshoot#%s", anchor) + } + return msg.String() +} + +// NonRetriable indicates the request which provoked this error shouldn't be retried. +func (*AuthenticationFailedError) NonRetriable() { + // marker method +} + +var _ errorinfo.NonRetriable = (*AuthenticationFailedError)(nil) + +// credentialUnavailableError indicates a credential can't attempt authentication because it lacks required +// data or state +type credentialUnavailableError struct { + message string +} + +// newCredentialUnavailableError is an internal helper that ensures consistent error message formatting +func newCredentialUnavailableError(credType, message string) error { + msg := fmt.Sprintf("%s: %s", credType, message) + return &credentialUnavailableError{msg} +} + +// NewCredentialUnavailableError constructs an error indicating a credential can't attempt authentication +// because it lacks required data or state. When [ChainedTokenCredential] receives this error it will try +// its next credential, if any. +func NewCredentialUnavailableError(message string) error { + return &credentialUnavailableError{message} +} + +// Error implements the error interface. Note that the message contents are not contractual and can change over time. +func (e *credentialUnavailableError) Error() string { + return e.message +} + +// NonRetriable is a marker method indicating this error should not be retried. It has no implementation. +func (e *credentialUnavailableError) NonRetriable() {} + +var _ errorinfo.NonRetriable = (*credentialUnavailableError)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work new file mode 100644 index 000000000..04ea962b4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work @@ -0,0 +1,6 @@ +go 1.18 + +use ( + . + ./cache +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work.sum b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work.sum new file mode 100644 index 000000000..7cd86b001 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work.sum @@ -0,0 +1,39 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0-beta.1 h1:ODs3brnqQM99Tq1PffODpAViYv3Bf8zOg464MU7p5ew= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0-beta.1/go.mod h1:3Ug6Qzto9anB6mGlEdgYMDF5zHQ+wwhEaYR4s17PHMw= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0 h1:fb8kj/Dh4CSwgsOzHeZY4Xh68cFVbzXx+ONXGMY//4w= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0/go.mod h1:uReU2sSxZExRPBAg3qKzmAucSi51+SP1OhohieR821Q= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA= +github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +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.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go new file mode 100644 index 000000000..bd8296983 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go @@ -0,0 +1,118 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +const credNameBrowser = "InteractiveBrowserCredential" + +// InteractiveBrowserCredentialOptions contains optional parameters for InteractiveBrowserCredential. +type InteractiveBrowserCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire + // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. + AdditionallyAllowedTenants []string + + // authenticationRecord returned by a call to a credential's Authenticate method. Set this option + // to enable the credential to use data from a previous authentication. + authenticationRecord authenticationRecord + + // ClientID is the ID of the application users will authenticate to. + // Defaults to the ID of an Azure development application. + ClientID string + + // disableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate. + // When this option is true, [InteractiveBrowserCredential.GetToken] will return [ErrAuthenticationRequired] when + // user interaction is necessary to acquire a token. + disableAutomaticAuthentication bool + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + + // LoginHint pre-populates the account prompt with a username. Users may choose to authenticate a different account. + LoginHint string + + // RedirectURL is the URL Microsoft Entra ID will redirect to with the access token. This is required + // only when setting ClientID, and must match a redirect URI in the application's registration. + // Applications which have registered "http://localhost" as a redirect URI need not set this option. + RedirectURL string + + // TenantID is the Microsoft Entra tenant the credential authenticates in. Defaults to the + // "organizations" tenant, which can authenticate work and school accounts. + TenantID string + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions +} + +func (o *InteractiveBrowserCredentialOptions) init() { + if o.TenantID == "" { + o.TenantID = organizationsTenantID + } + if o.ClientID == "" { + o.ClientID = developerSignOnClientID + } +} + +// InteractiveBrowserCredential opens a browser to interactively authenticate a user. +type InteractiveBrowserCredential struct { + client *publicClient +} + +// NewInteractiveBrowserCredential constructs a new InteractiveBrowserCredential. Pass nil to accept default options. +func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOptions) (*InteractiveBrowserCredential, error) { + cp := InteractiveBrowserCredentialOptions{} + if options != nil { + cp = *options + } + cp.init() + msalOpts := publicClientOptions{ + AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants, + ClientOptions: cp.ClientOptions, + DisableAutomaticAuthentication: cp.disableAutomaticAuthentication, + DisableInstanceDiscovery: cp.DisableInstanceDiscovery, + LoginHint: cp.LoginHint, + Record: cp.authenticationRecord, + RedirectURL: cp.RedirectURL, + TokenCachePersistenceOptions: cp.tokenCachePersistenceOptions, + } + c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameBrowser, msalOpts) + if err != nil { + return nil, err + } + return &InteractiveBrowserCredential{client: c}, nil +} + +// Authenticate a user via the default browser. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. +func (c *InteractiveBrowserCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameBrowser+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.Authenticate(ctx, opts) + return tk, err +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameBrowser+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err +} + +var _ azcore.TokenCredential = (*InteractiveBrowserCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/exported.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/exported.go new file mode 100644 index 000000000..b1b4d5c8b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/exported.go @@ -0,0 +1,18 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package internal + +// TokenCachePersistenceOptions contains options for persistent token caching +type TokenCachePersistenceOptions struct { + // AllowUnencryptedStorage controls whether the cache should fall back to storing its data in plain text + // when encryption isn't possible. Setting this true doesn't disable encryption. The cache always attempts + // encryption before falling back to plaintext storage. + AllowUnencryptedStorage bool + + // Name identifies the cache. Set this to isolate data from other applications. + Name string +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/internal.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/internal.go new file mode 100644 index 000000000..c1498b464 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal/internal.go @@ -0,0 +1,31 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package internal + +import ( + "errors" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" +) + +var errMissingImport = errors.New("import github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache to enable persistent caching") + +// NewCache constructs a persistent token cache when "o" isn't nil. Applications that intend to +// use a persistent cache must first import the cache module, which will replace this function +// with a platform-specific implementation. +var NewCache = func(o *TokenCachePersistenceOptions, enableCAE bool) (cache.ExportReplace, error) { + if o == nil { + return nil, nil + } + return nil, errMissingImport +} + +// CacheFilePath returns the path to the cache file for the given name. +// Defining it in this package makes it available to azidentity tests. +var CacheFilePath = func(name string) (string, error) { + return "", errMissingImport +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/logging.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/logging.go new file mode 100644 index 000000000..1aa1e0fc7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/logging.go @@ -0,0 +1,14 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import "github.com/Azure/azure-sdk-for-go/sdk/internal/log" + +// EventAuthentication entries contain information about authentication. +// This includes information like the names of environment variables +// used when obtaining credentials and the type of credential used. +const EventAuthentication log.Event = "Authentication" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go new file mode 100644 index 000000000..7c25cb8bd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go @@ -0,0 +1,446 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const ( + arcIMDSEndpoint = "IMDS_ENDPOINT" + defaultIdentityClientID = "DEFAULT_IDENTITY_CLIENT_ID" + identityEndpoint = "IDENTITY_ENDPOINT" + identityHeader = "IDENTITY_HEADER" + identityServerThumbprint = "IDENTITY_SERVER_THUMBPRINT" + headerMetadata = "Metadata" + imdsEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" + msiEndpoint = "MSI_ENDPOINT" + msiSecret = "MSI_SECRET" + imdsAPIVersion = "2018-02-01" + azureArcAPIVersion = "2019-08-15" + serviceFabricAPIVersion = "2019-07-01-preview" + + qpClientID = "client_id" + qpResID = "mi_res_id" +) + +type msiType int + +const ( + msiTypeAppService msiType = iota + msiTypeAzureArc + msiTypeAzureML + msiTypeCloudShell + msiTypeIMDS + msiTypeServiceFabric +) + +// managedIdentityClient provides the base for authenticating in managed identity environments +// This type includes an runtime.Pipeline and TokenCredentialOptions. +type managedIdentityClient struct { + azClient *azcore.Client + msiType msiType + endpoint string + id ManagedIDKind +} + +type wrappedNumber json.Number + +func (n *wrappedNumber) UnmarshalJSON(b []byte) error { + c := string(b) + if c == "\"\"" { + return nil + } + return json.Unmarshal(b, (*json.Number)(n)) +} + +// setIMDSRetryOptionDefaults sets zero-valued fields to default values appropriate for IMDS +func setIMDSRetryOptionDefaults(o *policy.RetryOptions) { + if o.MaxRetries == 0 { + o.MaxRetries = 5 + } + if o.MaxRetryDelay == 0 { + o.MaxRetryDelay = 1 * time.Minute + } + if o.RetryDelay == 0 { + o.RetryDelay = 2 * time.Second + } + if o.StatusCodes == nil { + o.StatusCodes = []int{ + // IMDS docs recommend retrying 404, 410, 429 and 5xx + // https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#error-handling + http.StatusNotFound, // 404 + http.StatusGone, // 410 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusNotImplemented, // 501 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 + http.StatusHTTPVersionNotSupported, // 505 + http.StatusVariantAlsoNegotiates, // 506 + http.StatusInsufficientStorage, // 507 + http.StatusLoopDetected, // 508 + http.StatusNotExtended, // 510 + http.StatusNetworkAuthenticationRequired, // 511 + } + } + if o.TryTimeout == 0 { + o.TryTimeout = 1 * time.Minute + } +} + +// newManagedIdentityClient creates a new instance of the ManagedIdentityClient with the ManagedIdentityCredentialOptions +// that are passed into it along with a default pipeline. +// options: ManagedIdentityCredentialOptions configure policies for the pipeline and the authority host that +// will be used to retrieve tokens and authenticate +func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*managedIdentityClient, error) { + if options == nil { + options = &ManagedIdentityCredentialOptions{} + } + cp := options.ClientOptions + c := managedIdentityClient{id: options.ID, endpoint: imdsEndpoint, msiType: msiTypeIMDS} + env := "IMDS" + if endpoint, ok := os.LookupEnv(identityEndpoint); ok { + if _, ok := os.LookupEnv(identityHeader); ok { + if _, ok := os.LookupEnv(identityServerThumbprint); ok { + env = "Service Fabric" + c.endpoint = endpoint + c.msiType = msiTypeServiceFabric + } else { + env = "App Service" + c.endpoint = endpoint + c.msiType = msiTypeAppService + } + } else if _, ok := os.LookupEnv(arcIMDSEndpoint); ok { + env = "Azure Arc" + c.endpoint = endpoint + c.msiType = msiTypeAzureArc + } + } else if endpoint, ok := os.LookupEnv(msiEndpoint); ok { + c.endpoint = endpoint + if _, ok := os.LookupEnv(msiSecret); ok { + env = "Azure ML" + c.msiType = msiTypeAzureML + } else { + env = "Cloud Shell" + c.msiType = msiTypeCloudShell + } + } else { + setIMDSRetryOptionDefaults(&cp.Retry) + } + + client, err := azcore.NewClient(module, version, runtime.PipelineOptions{ + Tracing: runtime.TracingOptions{ + Namespace: traceNamespace, + }, + }, &cp) + if err != nil { + return nil, err + } + c.azClient = client + + if log.Should(EventAuthentication) { + log.Writef(EventAuthentication, "Managed Identity Credential will use %s managed identity", env) + } + + return &c, nil +} + +// provideToken acquires a token for MSAL's confidential.Client, which caches the token +func (c *managedIdentityClient) provideToken(ctx context.Context, params confidential.TokenProviderParameters) (confidential.TokenProviderResult, error) { + result := confidential.TokenProviderResult{} + tk, err := c.authenticate(ctx, c.id, params.Scopes) + if err == nil { + result.AccessToken = tk.Token + result.ExpiresInSeconds = int(time.Until(tk.ExpiresOn).Seconds()) + } + return result, err +} + +// authenticate acquires an access token +func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKind, scopes []string) (azcore.AccessToken, error) { + msg, err := c.createAuthRequest(ctx, id, scopes) + if err != nil { + return azcore.AccessToken{}, err + } + + resp, err := c.azClient.Pipeline().Do(msg) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, err.Error(), nil, err) + } + + if runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return c.createAccessToken(resp) + } + + if c.msiType == msiTypeIMDS { + switch resp.StatusCode { + case http.StatusBadRequest: + if id != nil { + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "the requested identity isn't assigned to this resource", resp, nil) + } + msg := "failed to authenticate a system assigned identity" + if body, err := runtime.Payload(resp); err == nil && len(body) > 0 { + msg += fmt.Sprintf(". The endpoint responded with %s", body) + } + return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, msg) + case http.StatusForbidden: + // Docker Desktop runs a proxy that responds 403 to IMDS token requests. If we get that response, + // we return credentialUnavailableError so credential chains continue to their next credential + body, err := runtime.Payload(resp) + if err == nil && strings.Contains(string(body), "A socket operation was attempted to an unreachable network") { + return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, fmt.Sprintf("unexpected response %q", string(body))) + } + } + } + + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "authentication failed", resp, nil) +} + +func (c *managedIdentityClient) createAccessToken(res *http.Response) (azcore.AccessToken, error) { + value := struct { + // these are the only fields that we use + Token string `json:"access_token,omitempty"` + RefreshToken string `json:"refresh_token,omitempty"` + ExpiresIn wrappedNumber `json:"expires_in,omitempty"` // this field should always return the number of seconds for which a token is valid + ExpiresOn interface{} `json:"expires_on,omitempty"` // the value returned in this field varies between a number and a date string + }{} + if err := runtime.UnmarshalAsJSON(res, &value); err != nil { + return azcore.AccessToken{}, fmt.Errorf("internal AccessToken: %v", err) + } + if value.ExpiresIn != "" { + expiresIn, err := json.Number(value.ExpiresIn).Int64() + if err != nil { + return azcore.AccessToken{}, err + } + return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Now().Add(time.Second * time.Duration(expiresIn)).UTC()}, nil + } + switch v := value.ExpiresOn.(type) { + case float64: + return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(v), 0).UTC()}, nil + case string: + if expiresOn, err := strconv.Atoi(v); err == nil { + return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(expiresOn), 0).UTC()}, nil + } + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "unexpected expires_on value: "+v, res, nil) + default: + msg := fmt.Sprintf("unsupported type received in expires_on: %T, %v", v, v) + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, msg, res, nil) + } +} + +func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + switch c.msiType { + case msiTypeIMDS: + return c.createIMDSAuthRequest(ctx, id, scopes) + case msiTypeAppService: + return c.createAppServiceAuthRequest(ctx, id, scopes) + case msiTypeAzureArc: + // need to perform preliminary request to retreive the secret key challenge provided by the HIMDS service + key, err := c.getAzureArcSecretKey(ctx, scopes) + if err != nil { + msg := fmt.Sprintf("failed to retreive secret key from the identity endpoint: %v", err) + return nil, newAuthenticationFailedError(credNameManagedIdentity, msg, nil, err) + } + return c.createAzureArcAuthRequest(ctx, id, scopes, key) + case msiTypeAzureML: + return c.createAzureMLAuthRequest(ctx, id, scopes) + case msiTypeServiceFabric: + return c.createServiceFabricAuthRequest(ctx, id, scopes) + case msiTypeCloudShell: + return c.createCloudShellAuthRequest(ctx, id, scopes) + default: + return nil, newCredentialUnavailableError(credNameManagedIdentity, "managed identity isn't supported in this environment") + } +} + +func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set(headerMetadata, "true") + q := request.Raw().URL.Query() + q.Add("api-version", imdsAPIVersion) + q.Add("resource", strings.Join(scopes, " ")) + if id != nil { + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader)) + q := request.Raw().URL.Query() + q.Add("api-version", "2019-08-01") + q.Add("resource", scopes[0]) + if id != nil { + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) createAzureMLAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set("secret", os.Getenv(msiSecret)) + q := request.Raw().URL.Query() + q.Add("api-version", "2017-09-01") + q.Add("resource", strings.Join(scopes, " ")) + q.Add("clientid", os.Getenv(defaultIdentityClientID)) + if id != nil { + if id.idKind() == miResourceID { + log.Write(EventAuthentication, "WARNING: Azure ML doesn't support specifying a managed identity by resource ID") + q.Set("clientid", "") + q.Set(qpResID, id.String()) + } else { + q.Set("clientid", id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + q := request.Raw().URL.Query() + request.Raw().Header.Set("Accept", "application/json") + request.Raw().Header.Set("Secret", os.Getenv(identityHeader)) + q.Add("api-version", serviceFabricAPIVersion) + q.Add("resource", strings.Join(scopes, " ")) + if id != nil { + log.Write(EventAuthentication, "WARNING: Service Fabric doesn't support selecting a user-assigned identity at runtime") + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resources []string) (string, error) { + // create the request to retreive the secret key challenge provided by the HIMDS service + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return "", err + } + request.Raw().Header.Set(headerMetadata, "true") + q := request.Raw().URL.Query() + q.Add("api-version", azureArcAPIVersion) + q.Add("resource", strings.Join(resources, " ")) + request.Raw().URL.RawQuery = q.Encode() + // send the initial request to get the short-lived secret key + response, err := c.azClient.Pipeline().Do(request) + if err != nil { + return "", err + } + // the endpoint is expected to return a 401 with the WWW-Authenticate header set to the location + // of the secret key file. Any other status code indicates an error in the request. + if response.StatusCode != 401 { + msg := fmt.Sprintf("expected a 401 response, received %d", response.StatusCode) + return "", newAuthenticationFailedError(credNameManagedIdentity, msg, response, nil) + } + header := response.Header.Get("WWW-Authenticate") + if len(header) == 0 { + return "", errors.New("did not receive a value from WWW-Authenticate header") + } + // the WWW-Authenticate header is expected in the following format: Basic realm=/some/file/path.key + pos := strings.LastIndex(header, "=") + if pos == -1 { + return "", fmt.Errorf("did not receive a correct value from WWW-Authenticate header: %s", header) + } + key, err := os.ReadFile(header[pos+1:]) + if err != nil { + return "", fmt.Errorf("could not read file (%s) contents: %v", header[pos+1:], err) + } + return string(key), nil +} + +func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, id ManagedIDKind, resources []string, key string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set(headerMetadata, "true") + request.Raw().Header.Set("Authorization", fmt.Sprintf("Basic %s", key)) + q := request.Raw().URL.Query() + q.Add("api-version", azureArcAPIVersion) + q.Add("resource", strings.Join(resources, " ")) + if id != nil { + log.Write(EventAuthentication, "WARNING: Azure Arc doesn't support user-assigned managed identities") + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodPost, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set(headerMetadata, "true") + data := url.Values{} + data.Set("resource", strings.Join(scopes, " ")) + dataEncoded := data.Encode() + body := streaming.NopCloser(strings.NewReader(dataEncoded)) + if err := request.SetBody(body, "application/x-www-form-urlencoded"); err != nil { + return nil, err + } + if id != nil { + log.Write(EventAuthentication, "WARNING: Cloud Shell doesn't support user-assigned managed identities") + q := request.Raw().URL.Query() + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + return request, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go new file mode 100644 index 000000000..dcd278bef --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go @@ -0,0 +1,121 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "fmt" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const credNameManagedIdentity = "ManagedIdentityCredential" + +type managedIdentityIDKind int + +const ( + miClientID managedIdentityIDKind = 0 + miResourceID managedIdentityIDKind = 1 +) + +// ManagedIDKind identifies the ID of a managed identity as either a client or resource ID +type ManagedIDKind interface { + fmt.Stringer + idKind() managedIdentityIDKind +} + +// ClientID is the client ID of a user-assigned managed identity. +type ClientID string + +func (ClientID) idKind() managedIdentityIDKind { + return miClientID +} + +// String returns the string value of the ID. +func (c ClientID) String() string { + return string(c) +} + +// ResourceID is the resource ID of a user-assigned managed identity. +type ResourceID string + +func (ResourceID) idKind() managedIdentityIDKind { + return miResourceID +} + +// String returns the string value of the ID. +func (r ResourceID) String() string { + return string(r) +} + +// ManagedIdentityCredentialOptions contains optional parameters for ManagedIdentityCredential. +type ManagedIdentityCredentialOptions struct { + azcore.ClientOptions + + // ID is the ID of a managed identity the credential should authenticate. Set this field to use a specific identity + // instead of the hosting environment's default. The value may be the identity's client ID or resource ID, but note that + // some platforms don't accept resource IDs. + ID ManagedIDKind +} + +// ManagedIdentityCredential authenticates an Azure managed identity in any hosting environment supporting managed identities. +// This credential authenticates a system-assigned identity by default. Use ManagedIdentityCredentialOptions.ID to specify a +// user-assigned identity. See Microsoft Entra ID documentation for more information about managed identities: +// https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview +type ManagedIdentityCredential struct { + client *confidentialClient + mic *managedIdentityClient +} + +// NewManagedIdentityCredential creates a ManagedIdentityCredential. Pass nil to accept default options. +func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*ManagedIdentityCredential, error) { + if options == nil { + options = &ManagedIdentityCredentialOptions{} + } + mic, err := newManagedIdentityClient(options) + if err != nil { + return nil, err + } + cred := confidential.NewCredFromTokenProvider(mic.provideToken) + + // It's okay to give MSAL an invalid client ID because MSAL will use it only as part of a cache key. + // ManagedIdentityClient handles all the details of authentication and won't receive this value from MSAL. + clientID := "SYSTEM-ASSIGNED-MANAGED-IDENTITY" + if options.ID != nil { + clientID = options.ID.String() + } + // similarly, it's okay to give MSAL an incorrect tenant because MSAL won't use the value + c, err := newConfidentialClient("common", clientID, credNameManagedIdentity, cred, confidentialClientOptions{ + ClientOptions: options.ClientOptions, + }) + if err != nil { + return nil, err + } + return &ManagedIdentityCredential{client: c, mic: mic}, nil +} + +// GetToken requests an access token from the hosting environment. This method is called automatically by Azure SDK clients. +func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameManagedIdentity+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + + if len(opts.Scopes) != 1 { + err = fmt.Errorf("%s.GetToken() requires exactly one scope", credNameManagedIdentity) + return azcore.AccessToken{}, err + } + // managed identity endpoints require a Microsoft Entra ID v1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here + opts.Scopes = []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)} + tk, err := c.client.GetToken(ctx, opts) + return tk, err +} + +var _ azcore.TokenCredential = (*ManagedIdentityCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/on_behalf_of_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/on_behalf_of_credential.go new file mode 100644 index 000000000..5e67cf021 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/on_behalf_of_credential.go @@ -0,0 +1,99 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "crypto" + "crypto/x509" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const credNameOBO = "OnBehalfOfCredential" + +// OnBehalfOfCredential authenticates a service principal via the on-behalf-of flow. This is typically used by +// middle-tier services that authorize requests to other services with a delegated user identity. Because this +// is not an interactive authentication flow, an application using it must have admin consent for any delegated +// permissions before requesting tokens for them. See [Microsoft Entra ID documentation] for more details. +// +// [Microsoft Entra ID documentation]: https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow +type OnBehalfOfCredential struct { + client *confidentialClient +} + +// OnBehalfOfCredentialOptions contains optional parameters for OnBehalfOfCredential +type OnBehalfOfCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. + // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the + // application is registered. + AdditionallyAllowedTenants []string + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + + // SendCertificateChain applies only when the credential is configured to authenticate with a certificate. + // This setting controls whether the credential sends the public certificate chain in the x5c header of each + // token request's JWT. This is required for, and only used in, Subject Name/Issuer (SNI) authentication. + SendCertificateChain bool +} + +// NewOnBehalfOfCredentialWithCertificate constructs an OnBehalfOfCredential that authenticates with a certificate. +// See [ParseCertificates] for help loading a certificate. +func NewOnBehalfOfCredentialWithCertificate(tenantID, clientID, userAssertion string, certs []*x509.Certificate, key crypto.PrivateKey, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error) { + cred, err := confidential.NewCredFromCert(certs, key) + if err != nil { + return nil, err + } + return newOnBehalfOfCredential(tenantID, clientID, userAssertion, cred, options) +} + +// NewOnBehalfOfCredentialWithSecret constructs an OnBehalfOfCredential that authenticates with a client secret. +func NewOnBehalfOfCredentialWithSecret(tenantID, clientID, userAssertion, clientSecret string, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error) { + cred, err := confidential.NewCredFromSecret(clientSecret) + if err != nil { + return nil, err + } + return newOnBehalfOfCredential(tenantID, clientID, userAssertion, cred, options) +} + +func newOnBehalfOfCredential(tenantID, clientID, userAssertion string, cred confidential.Credential, options *OnBehalfOfCredentialOptions) (*OnBehalfOfCredential, error) { + if options == nil { + options = &OnBehalfOfCredentialOptions{} + } + opts := confidentialClientOptions{ + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + Assertion: userAssertion, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + SendX5C: options.SendCertificateChain, + } + c, err := newConfidentialClient(tenantID, clientID, credNameOBO, cred, opts) + if err != nil { + return nil, err + } + return &OnBehalfOfCredential{c}, nil +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (o *OnBehalfOfCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameOBO+"."+traceOpGetToken, o.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := o.client.GetToken(ctx, opts) + return tk, err +} + +var _ azcore.TokenCredential = (*OnBehalfOfCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go new file mode 100644 index 000000000..63c31190d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go @@ -0,0 +1,273 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" + + // this import ensures well-known configurations in azcore/cloud have ARM audiences for Authenticate() + _ "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +type publicClientOptions struct { + azcore.ClientOptions + + AdditionallyAllowedTenants []string + DeviceCodePrompt func(context.Context, DeviceCodeMessage) error + DisableAutomaticAuthentication bool + DisableInstanceDiscovery bool + LoginHint, RedirectURL string + Record authenticationRecord + TokenCachePersistenceOptions *tokenCachePersistenceOptions + Username, Password string +} + +// publicClient wraps the MSAL public client +type publicClient struct { + cae, noCAE msalPublicClient + caeMu, noCAEMu, clientMu *sync.Mutex + clientID, tenantID string + defaultScope []string + host string + name string + opts publicClientOptions + record authenticationRecord + azClient *azcore.Client +} + +var errScopeRequired = errors.New("authenticating in this environment requires specifying a scope in TokenRequestOptions") + +func newPublicClient(tenantID, clientID, name string, o publicClientOptions) (*publicClient, error) { + if !validTenantID(tenantID) { + return nil, errInvalidTenantID + } + host, err := setAuthorityHost(o.Cloud) + if err != nil { + return nil, err + } + // if the application specified a cloud configuration, use its ARM audience as the default scope for Authenticate() + audience := o.Cloud.Services[cloud.ResourceManager].Audience + if audience == "" { + // no cloud configuration, or no ARM audience, specified; try to map the host to a well-known one (all of which have a trailing slash) + if !strings.HasSuffix(host, "/") { + host += "/" + } + switch host { + case cloud.AzureChina.ActiveDirectoryAuthorityHost: + audience = cloud.AzureChina.Services[cloud.ResourceManager].Audience + case cloud.AzureGovernment.ActiveDirectoryAuthorityHost: + audience = cloud.AzureGovernment.Services[cloud.ResourceManager].Audience + case cloud.AzurePublic.ActiveDirectoryAuthorityHost: + audience = cloud.AzurePublic.Services[cloud.ResourceManager].Audience + } + } + // if we didn't come up with an audience, the application will have to specify a scope for Authenticate() + var defaultScope []string + if audience != "" { + defaultScope = []string{audience + defaultSuffix} + } + client, err := azcore.NewClient(module, version, runtime.PipelineOptions{ + Tracing: runtime.TracingOptions{ + Namespace: traceNamespace, + }, + }, &o.ClientOptions) + if err != nil { + return nil, err + } + o.AdditionallyAllowedTenants = resolveAdditionalTenants(o.AdditionallyAllowedTenants) + return &publicClient{ + caeMu: &sync.Mutex{}, + clientID: clientID, + clientMu: &sync.Mutex{}, + defaultScope: defaultScope, + host: host, + name: name, + noCAEMu: &sync.Mutex{}, + opts: o, + record: o.Record, + tenantID: tenantID, + azClient: client, + }, nil +} + +func (p *publicClient) Authenticate(ctx context.Context, tro *policy.TokenRequestOptions) (authenticationRecord, error) { + if tro == nil { + tro = &policy.TokenRequestOptions{} + } + if len(tro.Scopes) == 0 { + if p.defaultScope == nil { + return authenticationRecord{}, errScopeRequired + } + tro.Scopes = p.defaultScope + } + client, mu, err := p.client(*tro) + if err != nil { + return authenticationRecord{}, err + } + mu.Lock() + defer mu.Unlock() + _, err = p.reqToken(ctx, client, *tro) + if err == nil { + scope := strings.Join(tro.Scopes, ", ") + msg := fmt.Sprintf("%s.Authenticate() acquired a token for scope %q", p.name, scope) + log.Write(EventAuthentication, msg) + } + return p.record, err +} + +// GetToken requests an access token from MSAL, checking the cache first. +func (p *publicClient) GetToken(ctx context.Context, tro policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(tro.Scopes) < 1 { + return azcore.AccessToken{}, fmt.Errorf("%s.GetToken() requires at least one scope", p.name) + } + tenant, err := p.resolveTenant(tro.TenantID) + if err != nil { + return azcore.AccessToken{}, err + } + client, mu, err := p.client(tro) + if err != nil { + return azcore.AccessToken{}, err + } + mu.Lock() + defer mu.Unlock() + ar, err := client.AcquireTokenSilent(ctx, tro.Scopes, public.WithSilentAccount(p.record.account()), public.WithClaims(tro.Claims), public.WithTenantID(tenant)) + if err == nil { + return p.token(ar, err) + } + if p.opts.DisableAutomaticAuthentication { + return azcore.AccessToken{}, errAuthenticationRequired + } + at, err := p.reqToken(ctx, client, tro) + if err == nil { + msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", p.name, strings.Join(ar.GrantedScopes, ", ")) + log.Write(EventAuthentication, msg) + } + return at, err +} + +// reqToken requests a token from the MSAL public client. It's separate from GetToken() to enable Authenticate() to bypass the cache. +func (p *publicClient) reqToken(ctx context.Context, c msalPublicClient, tro policy.TokenRequestOptions) (azcore.AccessToken, error) { + tenant, err := p.resolveTenant(tro.TenantID) + if err != nil { + return azcore.AccessToken{}, err + } + var ar public.AuthResult + switch p.name { + case credNameBrowser: + ar, err = c.AcquireTokenInteractive(ctx, tro.Scopes, + public.WithClaims(tro.Claims), + public.WithLoginHint(p.opts.LoginHint), + public.WithRedirectURI(p.opts.RedirectURL), + public.WithTenantID(tenant), + ) + case credNameDeviceCode: + dc, e := c.AcquireTokenByDeviceCode(ctx, tro.Scopes, public.WithClaims(tro.Claims), public.WithTenantID(tenant)) + if e != nil { + return azcore.AccessToken{}, e + } + err = p.opts.DeviceCodePrompt(ctx, DeviceCodeMessage{ + Message: dc.Result.Message, + UserCode: dc.Result.UserCode, + VerificationURL: dc.Result.VerificationURL, + }) + if err == nil { + ar, err = dc.AuthenticationResult(ctx) + } + case credNameUserPassword: + ar, err = c.AcquireTokenByUsernamePassword(ctx, tro.Scopes, p.opts.Username, p.opts.Password, public.WithClaims(tro.Claims), public.WithTenantID(tenant)) + default: + return azcore.AccessToken{}, fmt.Errorf("unknown credential %q", p.name) + } + return p.token(ar, err) +} + +func (p *publicClient) client(tro policy.TokenRequestOptions) (msalPublicClient, *sync.Mutex, error) { + p.clientMu.Lock() + defer p.clientMu.Unlock() + if tro.EnableCAE { + if p.cae == nil { + client, err := p.newMSALClient(true) + if err != nil { + return nil, nil, err + } + p.cae = client + } + return p.cae, p.caeMu, nil + } + if p.noCAE == nil { + client, err := p.newMSALClient(false) + if err != nil { + return nil, nil, err + } + p.noCAE = client + } + return p.noCAE, p.noCAEMu, nil +} + +func (p *publicClient) newMSALClient(enableCAE bool) (msalPublicClient, error) { + cache, err := internal.NewCache(p.opts.TokenCachePersistenceOptions, enableCAE) + if err != nil { + return nil, err + } + o := []public.Option{ + public.WithAuthority(runtime.JoinPaths(p.host, p.tenantID)), + public.WithCache(cache), + public.WithHTTPClient(p), + } + if enableCAE { + o = append(o, public.WithClientCapabilities(cp1)) + } + if p.opts.DisableInstanceDiscovery || strings.ToLower(p.tenantID) == "adfs" { + o = append(o, public.WithInstanceDiscovery(false)) + } + return public.New(p.clientID, o...) +} + +func (p *publicClient) token(ar public.AuthResult, err error) (azcore.AccessToken, error) { + if err == nil { + p.record, err = newAuthenticationRecord(ar) + } else { + res := getResponseFromError(err) + err = newAuthenticationFailedError(p.name, err.Error(), res, err) + } + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +// resolveTenant returns the correct WithTenantID() argument for a token request given the client's +// configuration, or an error when that configuration doesn't allow the specified tenant +func (p *publicClient) resolveTenant(specified string) (string, error) { + t, err := resolveTenant(p.tenantID, specified, p.name, p.opts.AdditionallyAllowedTenants) + if t == p.tenantID { + // callers pass this value to MSAL's WithTenantID(). There's no need to redundantly specify + // the client's default tenant and doing so is an error when that tenant is "organizations" + t = "" + } + return t, err +} + +// these methods satisfy the MSAL ops.HTTPClient interface + +func (p *publicClient) CloseIdleConnections() { + // do nothing +} + +func (p *publicClient) Do(r *http.Request) (*http.Response, error) { + return doForClient(p.azClient, r) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources-pre.ps1 b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources-pre.ps1 new file mode 100644 index 000000000..fe0183add --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources-pre.ps1 @@ -0,0 +1,36 @@ +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] +param ( + # Captures any arguments from eng/New-TestResources.ps1 not declared here (no parameter errors). + [Parameter(ValueFromRemainingArguments = $true)] + $RemainingArguments +) + +if (!$CI) { + # TODO: Remove this once auto-cloud config downloads are supported locally + Write-Host "Skipping cert setup in local testing mode" + return +} + +if ($EnvironmentVariables -eq $null -or $EnvironmentVariables.Count -eq 0) { + throw "EnvironmentVariables must be set in the calling script New-TestResources.ps1" +} + +$tmp = $env:TEMP ? $env:TEMP : [System.IO.Path]::GetTempPath() +$pfxPath = Join-Path $tmp "test.pfx" +$pemPath = Join-Path $tmp "test.pem" +$sniPath = Join-Path $tmp "testsni.pfx" + +Write-Host "Creating identity test files: $pfxPath $pemPath $sniPath" + +[System.Convert]::FromBase64String($EnvironmentVariables['PFX_CONTENTS']) | Set-Content -Path $pfxPath -AsByteStream +Set-Content -Path $pemPath -Value $EnvironmentVariables['PEM_CONTENTS'] +[System.Convert]::FromBase64String($EnvironmentVariables['SNI_CONTENTS']) | Set-Content -Path $sniPath -AsByteStream + +# Set for pipeline +Write-Host "##vso[task.setvariable variable=IDENTITY_SP_CERT_PFX;]$pfxPath" +Write-Host "##vso[task.setvariable variable=IDENTITY_SP_CERT_PEM;]$pemPath" +Write-Host "##vso[task.setvariable variable=IDENTITY_SP_CERT_SNI;]$sniPath" +# Set for local +$env:IDENTITY_SP_CERT_PFX = $pfxPath +$env:IDENTITY_SP_CERT_PEM = $pemPath +$env:IDENTITY_SP_CERT_SNI = $sniPath diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources.bicep b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources.bicep new file mode 100644 index 000000000..b3490d3b5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources.bicep @@ -0,0 +1 @@ +param baseName string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go new file mode 100644 index 000000000..294ed81e9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go @@ -0,0 +1,90 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +const credNameUserPassword = "UsernamePasswordCredential" + +// UsernamePasswordCredentialOptions contains optional parameters for UsernamePasswordCredential. +type UsernamePasswordCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. + // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the + // application is registered. + AdditionallyAllowedTenants []string + + // authenticationRecord returned by a call to a credential's Authenticate method. Set this option + // to enable the credential to use data from a previous authentication. + authenticationRecord authenticationRecord + + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + + // tokenCachePersistenceOptions enables persistent token caching when not nil. + tokenCachePersistenceOptions *tokenCachePersistenceOptions +} + +// UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication, +// because it's less secure than other authentication flows. This credential is not interactive, so it isn't compatible +// with any form of multi-factor authentication, and the application must already have user or admin consent. +// This credential can only authenticate work and school accounts; it can't authenticate Microsoft accounts. +type UsernamePasswordCredential struct { + client *publicClient +} + +// NewUsernamePasswordCredential creates a UsernamePasswordCredential. clientID is the ID of the application the user +// will authenticate to. Pass nil for options to accept defaults. +func NewUsernamePasswordCredential(tenantID string, clientID string, username string, password string, options *UsernamePasswordCredentialOptions) (*UsernamePasswordCredential, error) { + if options == nil { + options = &UsernamePasswordCredentialOptions{} + } + opts := publicClientOptions{ + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + Password: password, + Record: options.authenticationRecord, + TokenCachePersistenceOptions: options.tokenCachePersistenceOptions, + Username: username, + } + c, err := newPublicClient(tenantID, clientID, credNameUserPassword, opts) + if err != nil { + return nil, err + } + return &UsernamePasswordCredential{client: c}, err +} + +// Authenticate the user. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. +func (c *UsernamePasswordCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameUserPassword+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.Authenticate(ctx, opts) + return tk, err +} + +// GetToken requests an access token from Microsoft Entra ID. This method is called automatically by Azure SDK clients. +func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameUserPassword+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := c.client.GetToken(ctx, opts) + return tk, err +} + +var _ azcore.TokenCredential = (*UsernamePasswordCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go new file mode 100644 index 000000000..e8caeea71 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go @@ -0,0 +1,18 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +const ( + // UserAgent is the string to be used in the user agent string when making requests. + component = "azidentity" + + // module is the fully qualified name of the module used in telemetry and distributed tracing. + module = "github.com/Azure/azure-sdk-for-go/sdk/" + component + + // Version is the semantic version (see http://semver.org) of this module. + version = "v1.5.1" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/workload_identity.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/workload_identity.go new file mode 100644 index 000000000..3e43e788e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/workload_identity.go @@ -0,0 +1,131 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "os" + "sync" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +const credNameWorkloadIdentity = "WorkloadIdentityCredential" + +// WorkloadIdentityCredential supports Azure workload identity on Kubernetes. +// See [Azure Kubernetes Service documentation] for more information. +// +// [Azure Kubernetes Service documentation]: https://learn.microsoft.com/azure/aks/workload-identity-overview +type WorkloadIdentityCredential struct { + assertion, file string + cred *ClientAssertionCredential + expires time.Time + mtx *sync.RWMutex +} + +// WorkloadIdentityCredentialOptions contains optional parameters for WorkloadIdentityCredential. +type WorkloadIdentityCredentialOptions struct { + azcore.ClientOptions + + // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. + // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the + // application is registered. + AdditionallyAllowedTenants []string + // ClientID of the service principal. Defaults to the value of the environment variable AZURE_CLIENT_ID. + ClientID string + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or + // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata + // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making + // the application responsible for ensuring the configured authority is valid and trustworthy. + DisableInstanceDiscovery bool + // TenantID of the service principal. Defaults to the value of the environment variable AZURE_TENANT_ID. + TenantID string + // TokenFilePath is the path of a file containing a Kubernetes service account token. Defaults to the value of the + // environment variable AZURE_FEDERATED_TOKEN_FILE. + TokenFilePath string +} + +// NewWorkloadIdentityCredential constructs a WorkloadIdentityCredential. Service principal configuration is read +// from environment variables as set by the Azure workload identity webhook. Set options to override those values. +func NewWorkloadIdentityCredential(options *WorkloadIdentityCredentialOptions) (*WorkloadIdentityCredential, error) { + if options == nil { + options = &WorkloadIdentityCredentialOptions{} + } + ok := false + clientID := options.ClientID + if clientID == "" { + if clientID, ok = os.LookupEnv(azureClientID); !ok { + return nil, errors.New("no client ID specified. Check pod configuration or set ClientID in the options") + } + } + file := options.TokenFilePath + if file == "" { + if file, ok = os.LookupEnv(azureFederatedTokenFile); !ok { + return nil, errors.New("no token file specified. Check pod configuration or set TokenFilePath in the options") + } + } + tenantID := options.TenantID + if tenantID == "" { + if tenantID, ok = os.LookupEnv(azureTenantID); !ok { + return nil, errors.New("no tenant ID specified. Check pod configuration or set TenantID in the options") + } + } + w := WorkloadIdentityCredential{file: file, mtx: &sync.RWMutex{}} + caco := ClientAssertionCredentialOptions{ + AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + } + cred, err := NewClientAssertionCredential(tenantID, clientID, w.getAssertion, &caco) + if err != nil { + return nil, err + } + // we want "WorkloadIdentityCredential" in log messages, not "ClientAssertionCredential" + cred.client.name = credNameWorkloadIdentity + w.cred = cred + return &w, nil +} + +// GetToken requests an access token from Microsoft Entra ID. Azure SDK clients call this method automatically. +func (w *WorkloadIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, credNameWorkloadIdentity+"."+traceOpGetToken, w.cred.client.azClient.Tracer(), nil) + defer func() { endSpan(err) }() + tk, err := w.cred.GetToken(ctx, opts) + return tk, err +} + +// getAssertion returns the specified file's content, which is expected to be a Kubernetes service account token. +// Kubernetes is responsible for updating the file as service account tokens expire. +func (w *WorkloadIdentityCredential) getAssertion(context.Context) (string, error) { + w.mtx.RLock() + if w.expires.Before(time.Now()) { + // ensure only one goroutine at a time updates the assertion + w.mtx.RUnlock() + w.mtx.Lock() + defer w.mtx.Unlock() + // double check because another goroutine may have acquired the write lock first and done the update + if now := time.Now(); w.expires.Before(now) { + content, err := os.ReadFile(w.file) + if err != nil { + return "", err + } + w.assertion = string(content) + // Kubernetes rotates service account tokens when they reach 80% of their total TTL. The shortest TTL + // is 1 hour. That implies the token we just read is valid for at least 12 minutes (20% of 1 hour), + // but we add some margin for safety. + w.expires = now.Add(10 * time.Minute) + } + } else { + defer w.mtx.RUnlock() + } + return w.assertion, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/LICENSE.txt new file mode 100644 index 000000000..48ea6616b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/diag.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/diag.go new file mode 100644 index 000000000..245af7d2b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/diag.go @@ -0,0 +1,51 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package diag + +import ( + "fmt" + "runtime" + "strings" +) + +// Caller returns the file and line number of a frame on the caller's stack. +// If the funtion fails an empty string is returned. +// skipFrames - the number of frames to skip when determining the caller. +// Passing a value of 0 will return the immediate caller of this function. +func Caller(skipFrames int) string { + if pc, file, line, ok := runtime.Caller(skipFrames + 1); ok { + // the skipFrames + 1 is to skip ourselves + frame := runtime.FuncForPC(pc) + return fmt.Sprintf("%s()\n\t%s:%d", frame.Name(), file, line) + } + return "" +} + +// StackTrace returns a formatted stack trace string. +// If the funtion fails an empty string is returned. +// skipFrames - the number of stack frames to skip before composing the trace string. +// totalFrames - the maximum number of stack frames to include in the trace string. +func StackTrace(skipFrames, totalFrames int) string { + pcCallers := make([]uintptr, totalFrames) + if frames := runtime.Callers(skipFrames, pcCallers); frames == 0 { + return "" + } + frames := runtime.CallersFrames(pcCallers) + sb := strings.Builder{} + for { + frame, more := frames.Next() + sb.WriteString(frame.Function) + sb.WriteString("()\n\t") + sb.WriteString(frame.File) + sb.WriteRune(':') + sb.WriteString(fmt.Sprintf("%d\n", frame.Line)) + if !more { + break + } + } + return sb.String() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/doc.go new file mode 100644 index 000000000..66bf13e5f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package diag diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/doc.go new file mode 100644 index 000000000..8c6eacb61 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package errorinfo diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/errorinfo.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/errorinfo.go new file mode 100644 index 000000000..8ee66b526 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/errorinfo.go @@ -0,0 +1,46 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package errorinfo + +// NonRetriable represents a non-transient error. This works in +// conjunction with the retry policy, indicating that the error condition +// is idempotent, so no retries will be attempted. +// Use errors.As() to access this interface in the error chain. +type NonRetriable interface { + error + NonRetriable() +} + +// NonRetriableError marks the specified error as non-retriable. +// This function takes an error as input and returns a new error that is marked as non-retriable. +func NonRetriableError(err error) error { + return &nonRetriableError{err} +} + +// nonRetriableError is a struct that embeds the error interface. +// It is used to represent errors that should not be retried. +type nonRetriableError struct { + error +} + +// Error method for nonRetriableError struct. +// It returns the error message of the embedded error. +func (p *nonRetriableError) Error() string { + return p.error.Error() +} + +// NonRetriable is a marker method for nonRetriableError struct. +// Non-functional and indicates that the error is non-retriable. +func (*nonRetriableError) NonRetriable() { + // marker method +} + +// Unwrap method for nonRetriableError struct. +// It returns the original error that was marked as non-retriable. +func (p *nonRetriableError) Unwrap() error { + return p.error +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/exported/exported.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/exported/exported.go new file mode 100644 index 000000000..d4ed6ccc8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/exported/exported.go @@ -0,0 +1,124 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "errors" + "io" + "net/http" +) + +// HasStatusCode returns true if the Response's status code is one of the specified values. +// Exported as runtime.HasStatusCode(). +func HasStatusCode(resp *http.Response, statusCodes ...int) bool { + if resp == nil { + return false + } + for _, sc := range statusCodes { + if resp.StatusCode == sc { + return true + } + } + return false +} + +// PayloadOptions contains the optional values for the Payload func. +// NOT exported but used by azcore. +type PayloadOptions struct { + // BytesModifier receives the downloaded byte slice and returns an updated byte slice. + // Use this to modify the downloaded bytes in a payload (e.g. removing a BOM). + BytesModifier func([]byte) []byte +} + +// Payload reads and returns the response body or an error. +// On a successful read, the response body is cached. +// Subsequent reads will access the cached value. +// Exported as runtime.Payload() WITHOUT the opts parameter. +func Payload(resp *http.Response, opts *PayloadOptions) ([]byte, error) { + modifyBytes := func(b []byte) []byte { return b } + if opts != nil && opts.BytesModifier != nil { + modifyBytes = opts.BytesModifier + } + + // r.Body won't be a nopClosingBytesReader if downloading was skipped + if buf, ok := resp.Body.(*nopClosingBytesReader); ok { + bytesBody := modifyBytes(buf.Bytes()) + buf.Set(bytesBody) + return bytesBody, nil + } + + bytesBody, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + return nil, err + } + + bytesBody = modifyBytes(bytesBody) + resp.Body = &nopClosingBytesReader{s: bytesBody} + return bytesBody, nil +} + +// PayloadDownloaded returns true if the response body has already been downloaded. +// This implies that the Payload() func above has been previously called. +// NOT exported but used by azcore. +func PayloadDownloaded(resp *http.Response) bool { + _, ok := resp.Body.(*nopClosingBytesReader) + return ok +} + +// nopClosingBytesReader is an io.ReadSeekCloser around a byte slice. +// It also provides direct access to the byte slice to avoid rereading. +type nopClosingBytesReader struct { + s []byte + i int64 +} + +// Bytes returns the underlying byte slice. +func (r *nopClosingBytesReader) Bytes() []byte { + return r.s +} + +// Close implements the io.Closer interface. +func (*nopClosingBytesReader) Close() error { + return nil +} + +// Read implements the io.Reader interface. +func (r *nopClosingBytesReader) Read(b []byte) (n int, err error) { + if r.i >= int64(len(r.s)) { + return 0, io.EOF + } + n = copy(b, r.s[r.i:]) + r.i += int64(n) + return +} + +// Set replaces the existing byte slice with the specified byte slice and resets the reader. +func (r *nopClosingBytesReader) Set(b []byte) { + r.s = b + r.i = 0 +} + +// Seek implements the io.Seeker interface. +func (r *nopClosingBytesReader) Seek(offset int64, whence int) (int64, error) { + var i int64 + switch whence { + case io.SeekStart: + i = offset + case io.SeekCurrent: + i = r.i + offset + case io.SeekEnd: + i = int64(len(r.s)) + offset + default: + return 0, errors.New("nopClosingBytesReader: invalid whence") + } + if i < 0 { + return 0, errors.New("nopClosingBytesReader: negative position") + } + r.i = i + return i, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/doc.go new file mode 100644 index 000000000..d7876d297 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package log diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go new file mode 100644 index 000000000..4f1dcf1b7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go @@ -0,0 +1,104 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package log + +import ( + "fmt" + "os" + "time" +) + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// NOTE: The following are exported as public surface area from azcore. DO NOT MODIFY +/////////////////////////////////////////////////////////////////////////////////////////////////// + +// Event is used to group entries. Each group can be toggled on or off. +type Event string + +// SetEvents is used to control which events are written to +// the log. By default all log events are writen. +func SetEvents(cls ...Event) { + log.cls = cls +} + +// SetListener will set the Logger to write to the specified listener. +func SetListener(lst func(Event, string)) { + log.lst = lst +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// END PUBLIC SURFACE AREA +/////////////////////////////////////////////////////////////////////////////////////////////////// + +// Should returns true if the specified log event should be written to the log. +// By default all log events will be logged. Call SetEvents() to limit +// the log events for logging. +// If no listener has been set this will return false. +// Calling this method is useful when the message to log is computationally expensive +// and you want to avoid the overhead if its log event is not enabled. +func Should(cls Event) bool { + if log.lst == nil { + return false + } + if log.cls == nil || len(log.cls) == 0 { + return true + } + for _, c := range log.cls { + if c == cls { + return true + } + } + return false +} + +// Write invokes the underlying listener with the specified event and message. +// If the event shouldn't be logged or there is no listener then Write does nothing. +func Write(cls Event, message string) { + if !Should(cls) { + return + } + log.lst(cls, message) +} + +// Writef invokes the underlying listener with the specified event and formatted message. +// If the event shouldn't be logged or there is no listener then Writef does nothing. +func Writef(cls Event, format string, a ...interface{}) { + if !Should(cls) { + return + } + log.lst(cls, fmt.Sprintf(format, a...)) +} + +// TestResetEvents is used for TESTING PURPOSES ONLY. +func TestResetEvents() { + log.cls = nil +} + +// logger controls which events to log and writing to the underlying log. +type logger struct { + cls []Event + lst func(Event, string) +} + +// the process-wide logger +var log logger + +func init() { + initLogging() +} + +// split out for testing purposes +func initLogging() { + if cls := os.Getenv("AZURE_SDK_GO_LOGGING"); cls == "all" { + // cls could be enhanced to support a comma-delimited list of log events + log.lst = func(cls Event, msg string) { + // simple console logger, it writes to stderr in the following format: + // [time-stamp] Event: message + fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", time.Now().Format(time.StampMicro), cls, msg) + } + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/poller/util.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/poller/util.go new file mode 100644 index 000000000..db8269627 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/poller/util.go @@ -0,0 +1,155 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package poller + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/internal/exported" +) + +// the well-known set of LRO status/provisioning state values. +const ( + StatusSucceeded = "Succeeded" + StatusCanceled = "Canceled" + StatusFailed = "Failed" + StatusInProgress = "InProgress" +) + +// these are non-conformant states that we've seen in the wild. +// we support them for back-compat. +const ( + StatusCancelled = "Cancelled" + StatusCompleted = "Completed" +) + +// IsTerminalState returns true if the LRO's state is terminal. +func IsTerminalState(s string) bool { + return Failed(s) || Succeeded(s) +} + +// Failed returns true if the LRO's state is terminal failure. +func Failed(s string) bool { + return strings.EqualFold(s, StatusFailed) || strings.EqualFold(s, StatusCanceled) || strings.EqualFold(s, StatusCancelled) +} + +// Succeeded returns true if the LRO's state is terminal success. +func Succeeded(s string) bool { + return strings.EqualFold(s, StatusSucceeded) || strings.EqualFold(s, StatusCompleted) +} + +// returns true if the LRO response contains a valid HTTP status code +func StatusCodeValid(resp *http.Response) bool { + return exported.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusCreated, http.StatusNoContent) +} + +// IsValidURL verifies that the URL is valid and absolute. +func IsValidURL(s string) bool { + u, err := url.Parse(s) + return err == nil && u.IsAbs() +} + +// ErrNoBody is returned if the response didn't contain a body. +var ErrNoBody = errors.New("the response did not contain a body") + +// GetJSON reads the response body into a raw JSON object. +// It returns ErrNoBody if there was no content. +func GetJSON(resp *http.Response) (map[string]any, error) { + body, err := exported.Payload(resp, nil) + if err != nil { + return nil, err + } + if len(body) == 0 { + return nil, ErrNoBody + } + // unmarshall the body to get the value + var jsonBody map[string]any + if err = json.Unmarshal(body, &jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// provisioningState returns the provisioning state from the response or the empty string. +func provisioningState(jsonBody map[string]any) string { + jsonProps, ok := jsonBody["properties"] + if !ok { + return "" + } + props, ok := jsonProps.(map[string]any) + if !ok { + return "" + } + rawPs, ok := props["provisioningState"] + if !ok { + return "" + } + ps, ok := rawPs.(string) + if !ok { + return "" + } + return ps +} + +// status returns the status from the response or the empty string. +func status(jsonBody map[string]any) string { + rawStatus, ok := jsonBody["status"] + if !ok { + return "" + } + status, ok := rawStatus.(string) + if !ok { + return "" + } + return status +} + +// GetStatus returns the LRO's status from the response body. +// Typically used for Azure-AsyncOperation flows. +// If there is no status in the response body the empty string is returned. +func GetStatus(resp *http.Response) (string, error) { + jsonBody, err := GetJSON(resp) + if err != nil { + return "", err + } + return status(jsonBody), nil +} + +// GetProvisioningState returns the LRO's state from the response body. +// If there is no state in the response body the empty string is returned. +func GetProvisioningState(resp *http.Response) (string, error) { + jsonBody, err := GetJSON(resp) + if err != nil { + return "", err + } + return provisioningState(jsonBody), nil +} + +// GetResourceLocation returns the LRO's resourceLocation value from the response body. +// Typically used for Operation-Location flows. +// If there is no resourceLocation in the response body the empty string is returned. +func GetResourceLocation(resp *http.Response) (string, error) { + jsonBody, err := GetJSON(resp) + if err != nil { + return "", err + } + v, ok := jsonBody["resourceLocation"] + if !ok { + // it might be ok if the field doesn't exist, the caller must make that determination + return "", nil + } + vv, ok := v.(string) + if !ok { + return "", fmt.Errorf("the resourceLocation value %v was not in string format", v) + } + return vv, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go new file mode 100644 index 000000000..238ef42ed --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go @@ -0,0 +1,123 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package temporal + +import ( + "sync" + "time" +) + +// AcquireResource abstracts a method for refreshing a temporal resource. +type AcquireResource[TResource, TState any] func(state TState) (newResource TResource, newExpiration time.Time, err error) + +// Resource is a temporal resource (usually a credential) that requires periodic refreshing. +type Resource[TResource, TState any] struct { + // cond is used to synchronize access to the shared resource embodied by the remaining fields + cond *sync.Cond + + // acquiring indicates that some thread/goroutine is in the process of acquiring/updating the resource + acquiring bool + + // resource contains the value of the shared resource + resource TResource + + // expiration indicates when the shared resource expires; it is 0 if the resource was never acquired + expiration time.Time + + // lastAttempt indicates when a thread/goroutine last attempted to acquire/update the resource + lastAttempt time.Time + + // acquireResource is the callback function that actually acquires the resource + acquireResource AcquireResource[TResource, TState] +} + +// NewResource creates a new Resource that uses the specified AcquireResource for refreshing. +func NewResource[TResource, TState any](ar AcquireResource[TResource, TState]) *Resource[TResource, TState] { + return &Resource[TResource, TState]{cond: sync.NewCond(&sync.Mutex{}), acquireResource: ar} +} + +// Get returns the underlying resource. +// If the resource is fresh, no refresh is performed. +func (er *Resource[TResource, TState]) Get(state TState) (TResource, error) { + // If the resource is expiring within this time window, update it eagerly. + // This allows other threads/goroutines to keep running by using the not-yet-expired + // resource value while one thread/goroutine updates the resource. + const window = 5 * time.Minute // This example updates the resource 5 minutes prior to expiration + const backoff = 30 * time.Second // Minimum wait time between eager update attempts + + now, acquire, expired := time.Now(), false, false + + // acquire exclusive lock + er.cond.L.Lock() + resource := er.resource + + for { + expired = er.expiration.IsZero() || er.expiration.Before(now) + if expired { + // The resource was never acquired or has expired + if !er.acquiring { + // If another thread/goroutine is not acquiring/updating the resource, this thread/goroutine will do it + er.acquiring, acquire = true, true + break + } + // Getting here means that this thread/goroutine will wait for the updated resource + } else if er.expiration.Add(-window).Before(now) { + // The resource is valid but is expiring within the time window + if !er.acquiring && er.lastAttempt.Add(backoff).Before(now) { + // If another thread/goroutine is not acquiring/renewing the resource, and none has attempted + // to do so within the last 30 seconds, this thread/goroutine will do it + er.acquiring, acquire = true, true + break + } + // This thread/goroutine will use the existing resource value while another updates it + resource = er.resource + break + } else { + // The resource is not close to expiring, this thread/goroutine should use its current value + resource = er.resource + break + } + // If we get here, wait for the new resource value to be acquired/updated + er.cond.Wait() + } + er.cond.L.Unlock() // Release the lock so no threads/goroutines are blocked + + var err error + if acquire { + // This thread/goroutine has been selected to acquire/update the resource + var expiration time.Time + var newValue TResource + er.lastAttempt = now + newValue, expiration, err = er.acquireResource(state) + + // Atomically, update the shared resource's new value & expiration. + er.cond.L.Lock() + if err == nil { + // Update resource & expiration, return the new value + resource = newValue + er.resource, er.expiration = resource, expiration + } else if !expired { + // An eager update failed. Discard the error and return the current--still valid--resource value + err = nil + } + er.acquiring = false // Indicate that no thread/goroutine is currently acquiring the resource + + // Wake up any waiting threads/goroutines since there is a resource they can ALL use + er.cond.L.Unlock() + er.cond.Broadcast() + } + return resource, err // Return the resource this thread/goroutine can use +} + +// Expire marks the resource as expired, ensuring it's refreshed on the next call to Get(). +func (er *Resource[TResource, TState]) Expire() { + er.cond.L.Lock() + defer er.cond.L.Unlock() + + // Reset the expiration as if we never got this resource to begin with + er.expiration = time.Time{} +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/doc.go new file mode 100644 index 000000000..a3824bee8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package uuid diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/uuid.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/uuid.go new file mode 100644 index 000000000..278ac9cd1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/uuid.go @@ -0,0 +1,76 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package uuid + +import ( + "crypto/rand" + "errors" + "fmt" + "strconv" +) + +// The UUID reserved variants. +const ( + reservedRFC4122 byte = 0x40 +) + +// A UUID representation compliant with specification in RFC4122 document. +type UUID [16]byte + +// New returns a new UUID using the RFC4122 algorithm. +func New() (UUID, error) { + u := UUID{} + // Set all bits to pseudo-random values. + // NOTE: this takes a process-wide lock + _, err := rand.Read(u[:]) + if err != nil { + return u, err + } + u[8] = (u[8] | reservedRFC4122) & 0x7F // u.setVariant(ReservedRFC4122) + + var version byte = 4 + u[6] = (u[6] & 0xF) | (version << 4) // u.setVersion(4) + return u, nil +} + +// String returns the UUID in "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" format. +func (u UUID) String() string { + return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) +} + +// Parse parses a string formatted as "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +// or "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" into a UUID. +func Parse(s string) (UUID, error) { + var uuid UUID + // ensure format + switch len(s) { + case 36: + // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 38: + // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + s = s[1:37] + default: + return uuid, errors.New("invalid UUID format") + } + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return uuid, errors.New("invalid UUID format") + } + // parse chunks + for i, x := range [16]int{ + 0, 2, 4, 6, + 9, 11, + 14, 16, + 19, 21, + 24, 26, 28, 30, 32, 34} { + b, err := strconv.ParseUint(s[x:x+2], 16, 8) + if err != nil { + return uuid, fmt.Errorf("invalid UUID format: %s", err) + } + uuid[i] = byte(b) + } + return uuid, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/CHANGELOG.md new file mode 100644 index 000000000..b19244d46 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/CHANGELOG.md @@ -0,0 +1,386 @@ +# Release History + +## 5.4.0 (2023-12-22) +### Features Added + +- New value `ConfidentialVMEncryptionTypeNonPersistedTPM` added to enum type `ConfidentialVMEncryptionType` +- New value `ReplicationStatusTypesUefiSettings` added to enum type `ReplicationStatusTypes` +- New value `SecurityEncryptionTypesNonPersistedTPM` added to enum type `SecurityEncryptionTypes` +- New enum type `Mode` with values `ModeAudit`, `ModeEnforce` +- New enum type `SSHEncryptionTypes` with values `SSHEncryptionTypesEd25519`, `SSHEncryptionTypesRSA` +- New enum type `UefiKeyType` with values `UefiKeyTypeSHA256`, `UefiKeyTypeX509` +- New enum type `UefiSignatureTemplateName` with values `UefiSignatureTemplateNameMicrosoftUefiCertificateAuthorityTemplate`, `UefiSignatureTemplateNameMicrosoftWindowsTemplate`, `UefiSignatureTemplateNameNoSignatureTemplate` +- New function `*DedicatedHostsClient.BeginRedeploy(context.Context, string, string, string, *DedicatedHostsClientBeginRedeployOptions) (*runtime.Poller[DedicatedHostsClientRedeployResponse], error)` +- New function `*VirtualMachineScaleSetVMsClient.BeginApproveRollingUpgrade(context.Context, string, string, string, *VirtualMachineScaleSetVMsClientBeginApproveRollingUpgradeOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientApproveRollingUpgradeResponse], error)` +- New function `*VirtualMachineScaleSetVMsClient.BeginAttachDetachDataDisks(context.Context, string, string, string, AttachDetachDataDisksRequest, *VirtualMachineScaleSetVMsClientBeginAttachDetachDataDisksOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientAttachDetachDataDisksResponse], error)` +- New function `*VirtualMachineScaleSetsClient.BeginApproveRollingUpgrade(context.Context, string, string, *VirtualMachineScaleSetsClientBeginApproveRollingUpgradeOptions) (*runtime.Poller[VirtualMachineScaleSetsClientApproveRollingUpgradeResponse], error)` +- New function `*VirtualMachinesClient.BeginAttachDetachDataDisks(context.Context, string, string, AttachDetachDataDisksRequest, *VirtualMachinesClientBeginAttachDetachDataDisksOptions) (*runtime.Poller[VirtualMachinesClientAttachDetachDataDisksResponse], error)` +- New struct `AttachDetachDataDisksRequest` +- New struct `CommunityGalleryMetadata` +- New struct `CommunityGalleryProperties` +- New struct `DataDisksToAttach` +- New struct `DataDisksToDetach` +- New struct `EncryptionIdentity` +- New struct `GalleryImageVersionUefiSettings` +- New struct `ImageVersionSecurityProfile` +- New struct `ProxyAgentSettings` +- New struct `ResiliencyPolicy` +- New struct `ResilientVMCreationPolicy` +- New struct `ResilientVMDeletionPolicy` +- New struct `ResourceSharingProfile` +- New struct `SSHGenerateKeyPairInputParameters` +- New struct `SharedGalleryProperties` +- New struct `UefiKey` +- New struct `UefiKeySignatures` +- New field `OSRollingUpgradeDeferral` in struct `AutomaticOSUpgradePolicy` +- New field `SharedSubscriptionIDs` in struct `CapacityReservationGroupInstanceView` +- New field `SharingProfile` in struct `CapacityReservationGroupProperties` +- New field `Properties` in struct `CommunityGallery` +- New field `ArtifactTags`, `Disclaimer` in struct `CommunityGalleryImageProperties` +- New field `ArtifactTags`, `Disclaimer` in struct `CommunityGalleryImageVersionProperties` +- New field `SecurityProfile` in struct `GalleryImageVersionProperties` +- New field `DiskControllerType` in struct `RestorePointSourceVMStorageProfile` +- New field `Parameters` in struct `SSHPublicKeysClientGenerateKeyPairOptions` +- New field `EncryptionIdentity`, `ProxyAgentSettings` in struct `SecurityProfile` +- New field `Properties` in struct `SharedGallery` +- New field `ArtifactTags` in struct `SharedGalleryImageProperties` +- New field `ArtifactTags` in struct `SharedGalleryImageVersionProperties` +- New field `Etag`, `ManagedBy` in struct `VirtualMachine` +- New field `IsVMInStandbyPool` in struct `VirtualMachineInstanceView` +- New field `Etag` in struct `VirtualMachineScaleSet` +- New field `ResiliencyPolicy` in struct `VirtualMachineScaleSetProperties` +- New field `ResiliencyPolicy` in struct `VirtualMachineScaleSetUpdateProperties` +- New field `Etag` in struct `VirtualMachineScaleSetVM` +- New field `TimeCreated` in struct `VirtualMachineScaleSetVMProfile` +- New field `IfMatch`, `IfNoneMatch` in struct `VirtualMachineScaleSetVMsClientBeginUpdateOptions` +- New field `IfMatch`, `IfNoneMatch` in struct `VirtualMachineScaleSetsClientBeginCreateOrUpdateOptions` +- New field `IfMatch`, `IfNoneMatch` in struct `VirtualMachineScaleSetsClientBeginUpdateOptions` +- New field `IfMatch`, `IfNoneMatch` in struct `VirtualMachinesClientBeginCreateOrUpdateOptions` +- New field `IfMatch`, `IfNoneMatch` in struct `VirtualMachinesClientBeginUpdateOptions` + + +## 5.3.0 (2023-11-24) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + + +## 5.3.0-beta.2 (2023-10-30) + +### Other Changes + +- Updated with latest code generator to fix a few issues in fakes. + +## 5.3.0-beta.1 (2023-10-09) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + +## 5.2.0 (2023-09-22) +### Features Added + +- New value `DiskCreateOptionCopyFromSanSnapshot` added to enum type `DiskCreateOption` +- New enum type `DomainNameLabelScopeTypes` with values `DomainNameLabelScopeTypesNoReuse`, `DomainNameLabelScopeTypesResourceGroupReuse`, `DomainNameLabelScopeTypesSubscriptionReuse`, `DomainNameLabelScopeTypesTenantReuse` +- New enum type `NetworkInterfaceAuxiliaryMode` with values `NetworkInterfaceAuxiliaryModeAcceleratedConnections`, `NetworkInterfaceAuxiliaryModeFloating`, `NetworkInterfaceAuxiliaryModeNone` +- New enum type `NetworkInterfaceAuxiliarySKU` with values `NetworkInterfaceAuxiliarySKUA1`, `NetworkInterfaceAuxiliarySKUA2`, `NetworkInterfaceAuxiliarySKUA4`, `NetworkInterfaceAuxiliarySKUA8`, `NetworkInterfaceAuxiliarySKUNone` +- New field `ElasticSanResourceID` in struct `CreationData` +- New field `LastOwnershipUpdateTime` in struct `DiskProperties` +- New field `AuxiliaryMode`, `AuxiliarySKU` in struct `VirtualMachineNetworkInterfaceConfigurationProperties` +- New field `DomainNameLabelScope` in struct `VirtualMachinePublicIPAddressDNSSettingsConfiguration` +- New field `AuxiliaryMode`, `AuxiliarySKU` in struct `VirtualMachineScaleSetNetworkConfigurationProperties` +- New field `DomainNameLabelScope` in struct `VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings` +- New field `AuxiliaryMode`, `AuxiliarySKU` in struct `VirtualMachineScaleSetUpdateNetworkConfigurationProperties` +- New field `TimeCreated` in struct `VirtualMachineScaleSetVMProperties` + + +## 5.1.0 (2023-07-28) +### Features Added + +- New enum type `FileFormat` with values `FileFormatVHD`, `FileFormatVHDX` +- New field `FileFormat` in struct `GrantAccessData` + + +## 5.0.0 (2023-05-26) +### Breaking Changes + +- Type of `CommunityGalleryImageProperties.Identifier` has been changed from `*GalleryImageIdentifier` to `*CommunityGalleryImageIdentifier` +- Type of `GalleryTargetExtendedLocation.StorageAccountType` has been changed from `*StorageAccountType` to `*EdgeZoneStorageAccountType` +- Type of `RestorePointSourceVMDataDisk.DiskRestorePoint` has been changed from `*APIEntityReference` to `*DiskRestorePointAttributes` +- Type of `RestorePointSourceVMOSDisk.DiskRestorePoint` has been changed from `*APIEntityReference` to `*DiskRestorePointAttributes` +- `StorageAccountTypeStandardSSDLRS` from enum `StorageAccountType` has been removed +- Field `ID` of struct `VirtualMachineScaleSetIPConfiguration` has been removed +- Field `ID` of struct `VirtualMachineScaleSetNetworkConfiguration` has been removed +- Field `ID` of struct `VirtualMachineScaleSetUpdateIPConfiguration` has been removed +- Field `ID` of struct `VirtualMachineScaleSetUpdateNetworkConfiguration` has been removed + +### Features Added + +- New enum type `EdgeZoneStorageAccountType` with values `EdgeZoneStorageAccountTypePremiumLRS`, `EdgeZoneStorageAccountTypeStandardLRS`, `EdgeZoneStorageAccountTypeStandardSSDLRS`, `EdgeZoneStorageAccountTypeStandardZRS` +- New enum type `ExpandTypeForListVMs` with values `ExpandTypeForListVMsInstanceView` +- New enum type `ExpandTypesForListVMs` with values `ExpandTypesForListVMsInstanceView` +- New enum type `RestorePointEncryptionType` with values `RestorePointEncryptionTypeEncryptionAtRestWithCustomerKey`, `RestorePointEncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys`, `RestorePointEncryptionTypeEncryptionAtRestWithPlatformKey` +- New function `*DedicatedHostsClient.NewListAvailableSizesPager(string, string, string, *DedicatedHostsClientListAvailableSizesOptions) *runtime.Pager[DedicatedHostsClientListAvailableSizesResponse]` +- New function `*VirtualMachineScaleSetsClient.BeginReapply(context.Context, string, string, *VirtualMachineScaleSetsClientBeginReapplyOptions) (*runtime.Poller[VirtualMachineScaleSetsClientReapplyResponse], error)` +- New struct `CommunityGalleryImageIdentifier` +- New struct `DedicatedHostSizeListResult` +- New struct `DiskRestorePointAttributes` +- New struct `RestorePointEncryption` +- New struct `RunCommandManagedIdentity` +- New struct `SecurityPostureReference` +- New field `SKU` in struct `DedicatedHostUpdate` +- New field `BypassPlatformSafetyChecksOnUserSchedule` in struct `LinuxVMGuestPatchAutomaticByPlatformSettings` +- New field `HyperVGeneration` in struct `RestorePointSourceMetadata` +- New field `WriteAcceleratorEnabled` in struct `RestorePointSourceVMDataDisk` +- New field `WriteAcceleratorEnabled` in struct `RestorePointSourceVMOSDisk` +- New field `ProvisionAfterExtensions` in struct `VirtualMachineExtensionProperties` +- New field `ErrorBlobManagedIdentity`, `OutputBlobManagedIdentity`, `TreatFailureAsDeploymentFailure` in struct `VirtualMachineRunCommandProperties` +- New field `ScriptURIManagedIdentity` in struct `VirtualMachineRunCommandScriptSource` +- New field `PriorityMixPolicy`, `SpotRestorePolicy` in struct `VirtualMachineScaleSetUpdateProperties` +- New field `Location` in struct `VirtualMachineScaleSetVMExtension` +- New field `SecurityPostureReference` in struct `VirtualMachineScaleSetVMProfile` +- New field `Hibernate` in struct `VirtualMachineScaleSetsClientBeginDeallocateOptions` +- New field `Expand` in struct `VirtualMachinesClientListAllOptions` +- New field `Expand` in struct `VirtualMachinesClientListOptions` +- New field `BypassPlatformSafetyChecksOnUserSchedule` in struct `WindowsVMGuestPatchAutomaticByPlatformSettings` + + +## 4.2.1 (2023-04-14) +### Bug Fixes + +- Fix serialization bug of empty value of `any` type. + + +## 4.2.0 (2023-03-27) +### Features Added + +- New struct `ClientFactory` which is a client factory used to create any client in this module +- New value `StorageAccountTypeStandardSSDLRS` added to enum type `StorageAccountType` +- New field `ComputerName` in struct `VirtualMachineScaleSetVMInstanceView` +- New field `HyperVGeneration` in struct `VirtualMachineScaleSetVMInstanceView` +- New field `OSName` in struct `VirtualMachineScaleSetVMInstanceView` +- New field `OSVersion` in struct `VirtualMachineScaleSetVMInstanceView` + + +## 4.1.0 (2023-01-27) +### Features Added + +- New type alias `AlternativeType` with values `AlternativeTypeNone`, `AlternativeTypeOffer`, `AlternativeTypePlan` +- New type alias `ImageState` with values `ImageStateActive`, `ImageStateDeprecated`, `ImageStateScheduledForDeprecation` +- New struct `AlternativeOption` +- New struct `ImageDeprecationStatus` +- New struct `OSImageNotificationProfile` +- New struct `OSProfileProvisioningData` +- New struct `ServiceArtifactReference` +- New field `Zones` in struct `CloudService` +- New field `UserData` in struct `RestorePointSourceMetadata` +- New field `MaxSurge` in struct `RollingUpgradePolicy` +- New field `RollbackFailedInstancesOnPolicyBreach` in struct `RollingUpgradePolicy` +- New field `OSImageNotificationProfile` in struct `ScheduledEventsProfile` +- New field `ImageDeprecationStatus` in struct `VirtualMachineImageProperties` +- New field `ExactVersion` in struct `VirtualMachineReimageParameters` +- New field `OSProfile` in struct `VirtualMachineReimageParameters` +- New field `RequireGuestProvisionSignal` in struct `VirtualMachineScaleSetOSProfile` +- New field `ConstrainedMaximumCapacity` in struct `VirtualMachineScaleSetProperties` +- New field `ExactVersion` in struct `VirtualMachineScaleSetReimageParameters` +- New field `OSProfile` in struct `VirtualMachineScaleSetReimageParameters` +- New field `ServiceArtifactReference` in struct `VirtualMachineScaleSetVMProfile` +- New field `ExactVersion` in struct `VirtualMachineScaleSetVMReimageParameters` +- New field `OSProfile` in struct `VirtualMachineScaleSetVMReimageParameters` + + +## 4.0.0 (2022-10-04) +### Breaking Changes + +- Type of `GalleryImageVersionStorageProfile.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryArtifactVersionFullSource` +- Type of `SharingProfile.CommunityGalleryInfo` has been changed from `interface{}` to `*CommunityGalleryInfo` +- Type of `VirtualMachineExtensionUpdateProperties.ProtectedSettingsFromKeyVault` has been changed from `interface{}` to `*KeyVaultSecretReference` +- Type of `GalleryOSDiskImage.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryDiskImageSource` +- Type of `GalleryDiskImage.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryDiskImageSource` +- Type of `GalleryDataDiskImage.Source` has been changed from `*GalleryArtifactVersionSource` to `*GalleryDiskImageSource` +- Type of `VirtualMachineScaleSetExtensionProperties.ProtectedSettingsFromKeyVault` has been changed from `interface{}` to `*KeyVaultSecretReference` +- Type of `VirtualMachineExtensionProperties.ProtectedSettingsFromKeyVault` has been changed from `interface{}` to `*KeyVaultSecretReference` +- Field `URI` of struct `GalleryArtifactVersionSource` has been removed + +### Features Added + +- New const `DiskControllerTypesSCSI` +- New const `PolicyViolationCategoryImageFlaggedUnsafe` +- New const `GalleryApplicationCustomActionParameterTypeConfigurationDataBlob` +- New const `PolicyViolationCategoryIPTheft` +- New const `PolicyViolationCategoryCopyrightValidation` +- New const `PolicyViolationCategoryOther` +- New const `GalleryApplicationCustomActionParameterTypeString` +- New const `DiskControllerTypesNVMe` +- New const `GalleryApplicationCustomActionParameterTypeLogOutputBlob` +- New type alias `DiskControllerTypes` +- New type alias `PolicyViolationCategory` +- New type alias `GalleryApplicationCustomActionParameterType` +- New function `PossiblePolicyViolationCategoryValues() []PolicyViolationCategory` +- New function `PossibleGalleryApplicationCustomActionParameterTypeValues() []GalleryApplicationCustomActionParameterType` +- New function `PossibleDiskControllerTypesValues() []DiskControllerTypes` +- New struct `GalleryApplicationCustomAction` +- New struct `GalleryApplicationCustomActionParameter` +- New struct `GalleryApplicationVersionSafetyProfile` +- New struct `GalleryArtifactSafetyProfileBase` +- New struct `GalleryArtifactVersionFullSource` +- New struct `GalleryDiskImageSource` +- New struct `GalleryImageVersionSafetyProfile` +- New struct `LatestGalleryImageVersion` +- New struct `PolicyViolation` +- New struct `PriorityMixPolicy` +- New field `DiskControllerType` in struct `VirtualMachineScaleSetUpdateStorageProfile` +- New field `HardwareProfile` in struct `VirtualMachineScaleSetUpdateVMProfile` +- New field `CustomActions` in struct `GalleryApplicationProperties` +- New field `DisableTCPStateTracking` in struct `VirtualMachineScaleSetNetworkConfigurationProperties` +- New field `DiskControllerType` in struct `StorageProfile` +- New field `OptimizedForFrequentAttach` in struct `DiskProperties` +- New field `BurstingEnabledTime` in struct `DiskProperties` +- New field `DiskControllerTypes` in struct `SupportedCapabilities` +- New field `DisableTCPStateTracking` in struct `VirtualMachineNetworkInterfaceConfigurationProperties` +- New field `EnableVMAgentPlatformUpdates` in struct `WindowsConfiguration` +- New field `PerformancePlus` in struct `CreationData` +- New field `IncrementalSnapshotFamilyID` in struct `SnapshotProperties` +- New field `OptimizedForFrequentAttach` in struct `DiskUpdateProperties` +- New field `DisableTCPStateTracking` in struct `VirtualMachineScaleSetUpdateNetworkConfigurationProperties` +- New field `ExcludeFromLatest` in struct `TargetRegion` +- New field `PrivacyStatementURI` in struct `SharedGalleryImageProperties` +- New field `Eula` in struct `SharedGalleryImageProperties` +- New field `SafetyProfile` in struct `GalleryApplicationVersionProperties` +- New field `SafetyProfile` in struct `GalleryImageVersionProperties` +- New field `EnableVMAgentPlatformUpdates` in struct `LinuxConfiguration` +- New field `CurrentCapacity` in struct `CapacityReservationUtilization` +- New field `PriorityMixPolicy` in struct `VirtualMachineScaleSetProperties` +- New field `CustomActions` in struct `GalleryApplicationVersionPublishingProfile` +- New field `PlatformFaultDomainCount` in struct `CapacityReservationProperties` +- New field `DiskControllerType` in struct `VirtualMachineScaleSetStorageProfile` + + +## 3.0.1 (2022-07-29) +### Other Changes +- Fix wrong module import for live test + +## 3.0.0 (2022-06-24) +### Breaking Changes + +- Function `*CloudServicesClient.BeginCreateOrUpdate` parameter(s) have been changed from `(context.Context, string, string, *CloudServicesClientBeginCreateOrUpdateOptions)` to `(context.Context, string, string, CloudService, *CloudServicesClientBeginCreateOrUpdateOptions)` +- Function `*CloudServicesClient.BeginUpdate` parameter(s) have been changed from `(context.Context, string, string, *CloudServicesClientBeginUpdateOptions)` to `(context.Context, string, string, CloudServiceUpdate, *CloudServicesClientBeginUpdateOptions)` +- Function `*CloudServicesUpdateDomainClient.BeginWalkUpdateDomain` parameter(s) have been changed from `(context.Context, string, string, int32, *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions)` to `(context.Context, string, string, int32, UpdateDomain, *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions)` +- Type of `CloudServiceExtensionProperties.Settings` has been changed from `*string` to `interface{}` +- Type of `CloudServiceExtensionProperties.ProtectedSettings` has been changed from `*string` to `interface{}` +- Field `Parameters` of struct `CloudServicesClientBeginUpdateOptions` has been removed +- Field `Parameters` of struct `CloudServicesClientBeginCreateOrUpdateOptions` has been removed +- Field `Parameters` of struct `CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions` has been removed + +### Features Added + +- New const `CloudServiceSlotTypeProduction` +- New const `CloudServiceSlotTypeStaging` +- New function `*VirtualMachineImagesClient.ListByEdgeZone(context.Context, string, string, *VirtualMachineImagesClientListByEdgeZoneOptions) (VirtualMachineImagesClientListByEdgeZoneResponse, error)` +- New function `PossibleCloudServiceSlotTypeValues() []CloudServiceSlotType` +- New struct `SystemData` +- New struct `VMImagesInEdgeZoneListResult` +- New struct `VirtualMachineImagesClientListByEdgeZoneOptions` +- New struct `VirtualMachineImagesClientListByEdgeZoneResponse` +- New field `SystemData` in struct `CloudService` +- New field `SlotType` in struct `CloudServiceNetworkProfile` + + +## 2.0.0 (2022-06-02) +### Breaking Changes + +- Type of `GalleryProperties.ProvisioningState` has been changed from `*GalleryPropertiesProvisioningState` to `*GalleryProvisioningState` +- Type of `GalleryImageVersionProperties.ProvisioningState` has been changed from `*GalleryImageVersionPropertiesProvisioningState` to `*GalleryProvisioningState` +- Type of `GalleryImageProperties.ProvisioningState` has been changed from `*GalleryImagePropertiesProvisioningState` to `*GalleryProvisioningState` +- Type of `GalleryApplicationVersionProperties.ProvisioningState` has been changed from `*GalleryApplicationVersionPropertiesProvisioningState` to `*GalleryProvisioningState` +- Type of `VirtualMachineScaleSetIdentity.UserAssignedIdentities` has been changed from `map[string]*VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue` to `map[string]*UserAssignedIdentitiesValue` +- Const `GalleryImagePropertiesProvisioningStateFailed` has been removed +- Const `GalleryImagePropertiesProvisioningStateMigrating` has been removed +- Const `GalleryImageVersionPropertiesProvisioningStateCreating` has been removed +- Const `GalleryImageVersionPropertiesProvisioningStateMigrating` has been removed +- Const `GalleryApplicationVersionPropertiesProvisioningStateFailed` has been removed +- Const `GalleryPropertiesProvisioningStateMigrating` has been removed +- Const `GalleryApplicationVersionPropertiesProvisioningStateDeleting` has been removed +- Const `GalleryPropertiesProvisioningStateDeleting` has been removed +- Const `GalleryApplicationVersionPropertiesProvisioningStateCreating` has been removed +- Const `GalleryImageVersionPropertiesProvisioningStateSucceeded` has been removed +- Const `GalleryImagePropertiesProvisioningStateCreating` has been removed +- Const `GalleryImagePropertiesProvisioningStateUpdating` has been removed +- Const `GalleryImageVersionPropertiesProvisioningStateDeleting` has been removed +- Const `GalleryPropertiesProvisioningStateFailed` has been removed +- Const `SharingProfileGroupTypesCommunity` has been removed +- Const `GalleryApplicationVersionPropertiesProvisioningStateSucceeded` has been removed +- Const `GalleryApplicationVersionPropertiesProvisioningStateMigrating` has been removed +- Const `GalleryPropertiesProvisioningStateUpdating` has been removed +- Const `GalleryImageVersionPropertiesProvisioningStateFailed` has been removed +- Const `GalleryImagePropertiesProvisioningStateDeleting` has been removed +- Const `GalleryImageVersionPropertiesProvisioningStateUpdating` has been removed +- Const `GalleryPropertiesProvisioningStateCreating` has been removed +- Const `GalleryApplicationVersionPropertiesProvisioningStateUpdating` has been removed +- Const `GalleryImagePropertiesProvisioningStateSucceeded` has been removed +- Const `GalleryPropertiesProvisioningStateSucceeded` has been removed +- Function `PossibleGalleryPropertiesProvisioningStateValues` has been removed +- Function `PossibleGalleryImageVersionPropertiesProvisioningStateValues` has been removed +- Function `PossibleGalleryImagePropertiesProvisioningStateValues` has been removed +- Function `PossibleGalleryApplicationVersionPropertiesProvisioningStateValues` has been removed +- Struct `VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue` has been removed + +### Features Added + +- New const `GallerySharingPermissionTypesCommunity` +- New const `GalleryProvisioningStateUpdating` +- New const `SharedGalleryHostCachingReadOnly` +- New const `SharedGalleryHostCachingNone` +- New const `GalleryProvisioningStateSucceeded` +- New const `GalleryProvisioningStateFailed` +- New const `SharedGalleryHostCachingReadWrite` +- New const `GalleryProvisioningStateCreating` +- New const `DiskEncryptionSetIdentityTypeUserAssigned` +- New const `GalleryProvisioningStateMigrating` +- New const `DiskEncryptionSetIdentityTypeSystemAssignedUserAssigned` +- New const `CopyCompletionErrorReasonCopySourceNotFound` +- New const `GalleryProvisioningStateDeleting` +- New const `DiskStorageAccountTypesPremiumV2LRS` +- New function `PossibleCopyCompletionErrorReasonValues() []CopyCompletionErrorReason` +- New function `PossibleSharedGalleryHostCachingValues() []SharedGalleryHostCaching` +- New function `PossibleGalleryProvisioningStateValues() []GalleryProvisioningState` +- New function `EncryptionSetIdentity.MarshalJSON() ([]byte, error)` +- New function `*CommunityGalleryImagesClient.NewListPager(string, string, *CommunityGalleryImagesClientListOptions) *runtime.Pager[CommunityGalleryImagesClientListResponse]` +- New function `*CommunityGalleryImageVersionsClient.NewListPager(string, string, string, *CommunityGalleryImageVersionsClientListOptions) *runtime.Pager[CommunityGalleryImageVersionsClientListResponse]` +- New struct `CommunityGalleryImageList` +- New struct `CommunityGalleryImageVersionList` +- New struct `CommunityGalleryImageVersionsClientListOptions` +- New struct `CommunityGalleryImageVersionsClientListResponse` +- New struct `CommunityGalleryImagesClientListOptions` +- New struct `CommunityGalleryImagesClientListResponse` +- New struct `CopyCompletionError` +- New struct `SharedGalleryDataDiskImage` +- New struct `SharedGalleryDiskImage` +- New struct `SharedGalleryImageVersionStorageProfile` +- New struct `SharedGalleryOSDiskImage` +- New struct `UserArtifactSettings` +- New field `SharedGalleryImageID` in struct `ImageDiskReference` +- New field `CommunityGalleryImageID` in struct `ImageDiskReference` +- New field `AdvancedSettings` in struct `GalleryApplicationVersionPublishingProfile` +- New field `Settings` in struct `GalleryApplicationVersionPublishingProfile` +- New field `CopyCompletionError` in struct `SnapshotProperties` +- New field `ExcludeFromLatest` in struct `SharedGalleryImageVersionProperties` +- New field `StorageProfile` in struct `SharedGalleryImageVersionProperties` +- New field `ExcludeFromLatest` in struct `CommunityGalleryImageVersionProperties` +- New field `StorageProfile` in struct `CommunityGalleryImageVersionProperties` +- New field `Architecture` in struct `SharedGalleryImageProperties` +- New field `UserAssignedIdentities` in struct `EncryptionSetIdentity` +- New field `Eula` in struct `CommunityGalleryImageProperties` +- New field `PrivacyStatementURI` in struct `CommunityGalleryImageProperties` +- New field `Architecture` in struct `CommunityGalleryImageProperties` +- New field `FederatedClientID` in struct `DiskEncryptionSetUpdateProperties` +- New field `FederatedClientID` in struct `EncryptionSetProperties` +- New field `SecurityProfile` in struct `DiskRestorePointProperties` + + +## 1.0.0 (2022-05-16) + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute` 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). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/LICENSE.txt new file mode 100644 index 000000000..dc0c2ffb3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/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/compute/armcompute/v5/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/README.md new file mode 100644 index 000000000..7c8d1e3e1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/README.md @@ -0,0 +1,113 @@ +# Azure Compute Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5) + +The `armcompute` module provides operations for working with Azure Compute. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/compute/armcompute) + +# 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 Compute module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Compute. 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 Compute 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 := armcompute.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 := armcompute.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.NewLogAnalyticsClient() +``` + +## 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 + +- [Availability Set](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/availabilityset) +- [Creating a Fake](https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/resourcemanager/compute/armcompute/fake_example_test.go) +- [Virtual Machine](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/create_vm) +- [Dedicated Host](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/dedicated_host) +- [Disk](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/disk) +- [Gallery](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/gallery) +- [Proximity Placement Group](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/proximity) +- [Snapshot](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/snapshot) +- [Virtual Machine Scale Set](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/vmscaleset) + +## Major Version Upgrade + +Go uses [semantic import versioning](https://github.com/golang/go/wiki/Modules#semantic-import-versioning) to ensure a good backward compatibility for modules. For Azure Go management SDK, we usually upgrade module version according to cooresponding service's API version. Regarding it could be a complicated experience for major version upgrade, we will try our best to keep the SDK API stable and release new version in backward compatible way. However, if any unavoidable breaking changes and a new major version releases for SDK modules, you could use these commands under your module folder to upgrade: + +```sh +go install github.com/icholy/gomajor@latest +gomajor get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute@latest +``` + +## 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 `Compute` 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. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/assets.json new file mode 100644 index 000000000..1feae4c5c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "go", + "TagPrefix": "go/resourcemanager/compute/armcompute", + "Tag": "go/resourcemanager/compute/armcompute_323718962d" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/autorest.md new file mode 100644 index 000000000..9d88c8a6d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/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/60679ee3db06e93eb73faa0587fed93ed843d6dc/specification/compute/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/60679ee3db06e93eb73faa0587fed93ed843d6dc/specification/compute/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 5.4.0 +tag: package-2023-09-01 +``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/availabilitysets_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/availabilitysets_client.go new file mode 100644 index 000000000..3b568f54a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/availabilitysets_client.go @@ -0,0 +1,485 @@ +//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 armcompute + +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" +) + +// AvailabilitySetsClient contains the methods for the AvailabilitySets group. +// Don't use this type directly, use NewAvailabilitySetsClient() instead. +type AvailabilitySetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAvailabilitySetsClient creates a new instance of AvailabilitySetsClient 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 NewAvailabilitySetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AvailabilitySetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AvailabilitySetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create or update an availability set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - availabilitySetName - The name of the availability set. +// - parameters - Parameters supplied to the Create Availability Set operation. +// - options - AvailabilitySetsClientCreateOrUpdateOptions contains the optional parameters for the AvailabilitySetsClient.CreateOrUpdate +// method. +func (client *AvailabilitySetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySet, options *AvailabilitySetsClientCreateOrUpdateOptions) (AvailabilitySetsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "AvailabilitySetsClient.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, availabilitySetName, parameters, options) + if err != nil { + return AvailabilitySetsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AvailabilitySetsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AvailabilitySetsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AvailabilitySetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySet, options *AvailabilitySetsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if availabilitySetName == "" { + return nil, errors.New("parameter availabilitySetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName)) + 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-09-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 *AvailabilitySetsClient) createOrUpdateHandleResponse(resp *http.Response) (AvailabilitySetsClientCreateOrUpdateResponse, error) { + result := AvailabilitySetsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySet); err != nil { + return AvailabilitySetsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete an availability set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - availabilitySetName - The name of the availability set. +// - options - AvailabilitySetsClientDeleteOptions contains the optional parameters for the AvailabilitySetsClient.Delete method. +func (client *AvailabilitySetsClient) Delete(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientDeleteOptions) (AvailabilitySetsClientDeleteResponse, error) { + var err error + const operationName = "AvailabilitySetsClient.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, availabilitySetName, options) + if err != nil { + return AvailabilitySetsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AvailabilitySetsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return AvailabilitySetsClientDeleteResponse{}, err + } + return AvailabilitySetsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AvailabilitySetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if availabilitySetName == "" { + return nil, errors.New("parameter availabilitySetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about an availability set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - availabilitySetName - The name of the availability set. +// - options - AvailabilitySetsClientGetOptions contains the optional parameters for the AvailabilitySetsClient.Get method. +func (client *AvailabilitySetsClient) Get(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientGetOptions) (AvailabilitySetsClientGetResponse, error) { + var err error + const operationName = "AvailabilitySetsClient.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, availabilitySetName, options) + if err != nil { + return AvailabilitySetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AvailabilitySetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AvailabilitySetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AvailabilitySetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if availabilitySetName == "" { + return nil, errors.New("parameter availabilitySetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AvailabilitySetsClient) getHandleResponse(resp *http.Response) (AvailabilitySetsClientGetResponse, error) { + result := AvailabilitySetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySet); err != nil { + return AvailabilitySetsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all availability sets in a resource group. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - AvailabilitySetsClientListOptions contains the optional parameters for the AvailabilitySetsClient.NewListPager +// method. +func (client *AvailabilitySetsClient) NewListPager(resourceGroupName string, options *AvailabilitySetsClientListOptions) *runtime.Pager[AvailabilitySetsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailabilitySetsClientListResponse]{ + More: func(page AvailabilitySetsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailabilitySetsClientListResponse) (AvailabilitySetsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailabilitySetsClient.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, options) + }, nil) + if err != nil { + return AvailabilitySetsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AvailabilitySetsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *AvailabilitySetsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AvailabilitySetsClient) listHandleResponse(resp *http.Response) (AvailabilitySetsClientListResponse, error) { + result := AvailabilitySetsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySetListResult); err != nil { + return AvailabilitySetsClientListResponse{}, err + } + return result, nil +} + +// NewListAvailableSizesPager - Lists all available virtual machine sizes that can be used to create a new virtual machine +// in an existing availability set. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - availabilitySetName - The name of the availability set. +// - options - AvailabilitySetsClientListAvailableSizesOptions contains the optional parameters for the AvailabilitySetsClient.NewListAvailableSizesPager +// method. +func (client *AvailabilitySetsClient) NewListAvailableSizesPager(resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientListAvailableSizesOptions) *runtime.Pager[AvailabilitySetsClientListAvailableSizesResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailabilitySetsClientListAvailableSizesResponse]{ + More: func(page AvailabilitySetsClientListAvailableSizesResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *AvailabilitySetsClientListAvailableSizesResponse) (AvailabilitySetsClientListAvailableSizesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailabilitySetsClient.NewListAvailableSizesPager") + req, err := client.listAvailableSizesCreateRequest(ctx, resourceGroupName, availabilitySetName, options) + if err != nil { + return AvailabilitySetsClientListAvailableSizesResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AvailabilitySetsClientListAvailableSizesResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AvailabilitySetsClientListAvailableSizesResponse{}, runtime.NewResponseError(resp) + } + return client.listAvailableSizesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAvailableSizesCreateRequest creates the ListAvailableSizes request. +func (client *AvailabilitySetsClient) listAvailableSizesCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, options *AvailabilitySetsClientListAvailableSizesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}/vmSizes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if availabilitySetName == "" { + return nil, errors.New("parameter availabilitySetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableSizesHandleResponse handles the ListAvailableSizes response. +func (client *AvailabilitySetsClient) listAvailableSizesHandleResponse(resp *http.Response) (AvailabilitySetsClientListAvailableSizesResponse, error) { + result := AvailabilitySetsClientListAvailableSizesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineSizeListResult); err != nil { + return AvailabilitySetsClientListAvailableSizesResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists all availability sets in a subscription. +// +// Generated from API version 2023-09-01 +// - options - AvailabilitySetsClientListBySubscriptionOptions contains the optional parameters for the AvailabilitySetsClient.NewListBySubscriptionPager +// method. +func (client *AvailabilitySetsClient) NewListBySubscriptionPager(options *AvailabilitySetsClientListBySubscriptionOptions) *runtime.Pager[AvailabilitySetsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailabilitySetsClientListBySubscriptionResponse]{ + More: func(page AvailabilitySetsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailabilitySetsClientListBySubscriptionResponse) (AvailabilitySetsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailabilitySetsClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return AvailabilitySetsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *AvailabilitySetsClient) listBySubscriptionCreateRequest(ctx context.Context, options *AvailabilitySetsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/availabilitySets" + 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-09-01") + 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 +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *AvailabilitySetsClient) listBySubscriptionHandleResponse(resp *http.Response) (AvailabilitySetsClientListBySubscriptionResponse, error) { + result := AvailabilitySetsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySetListResult); err != nil { + return AvailabilitySetsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Update an availability set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - availabilitySetName - The name of the availability set. +// - parameters - Parameters supplied to the Update Availability Set operation. +// - options - AvailabilitySetsClientUpdateOptions contains the optional parameters for the AvailabilitySetsClient.Update method. +func (client *AvailabilitySetsClient) Update(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySetUpdate, options *AvailabilitySetsClientUpdateOptions) (AvailabilitySetsClientUpdateResponse, error) { + var err error + const operationName = "AvailabilitySetsClient.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, availabilitySetName, parameters, options) + if err != nil { + return AvailabilitySetsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AvailabilitySetsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AvailabilitySetsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *AvailabilitySetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySetUpdate, options *AvailabilitySetsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if availabilitySetName == "" { + return nil, errors.New("parameter availabilitySetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{availabilitySetName}", url.PathEscape(availabilitySetName)) + 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-09-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 *AvailabilitySetsClient) updateHandleResponse(resp *http.Response) (AvailabilitySetsClientUpdateResponse, error) { + result := AvailabilitySetsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilitySet); err != nil { + return AvailabilitySetsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/build.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/build.go new file mode 100644 index 000000000..f88d006f4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/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 -alwaysSetBodyParamRequired resourcemanager/compute/armcompute + +package armcompute diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/capacityreservationgroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/capacityreservationgroups_client.go new file mode 100644 index 000000000..96e32e966 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/capacityreservationgroups_client.go @@ -0,0 +1,434 @@ +//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 armcompute + +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" +) + +// CapacityReservationGroupsClient contains the methods for the CapacityReservationGroups group. +// Don't use this type directly, use NewCapacityReservationGroupsClient() instead. +type CapacityReservationGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCapacityReservationGroupsClient creates a new instance of CapacityReservationGroupsClient 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 NewCapacityReservationGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CapacityReservationGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CapacityReservationGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - The operation to create or update a capacity reservation group. When updating a capacity reservation group, +// only tags and sharing profile may be modified. Please refer to +// https://aka.ms/CapacityReservation for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - parameters - Parameters supplied to the Create capacity reservation Group. +// - options - CapacityReservationGroupsClientCreateOrUpdateOptions contains the optional parameters for the CapacityReservationGroupsClient.CreateOrUpdate +// method. +func (client *CapacityReservationGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroup, options *CapacityReservationGroupsClientCreateOrUpdateOptions) (CapacityReservationGroupsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "CapacityReservationGroupsClient.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, capacityReservationGroupName, parameters, options) + if err != nil { + return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *CapacityReservationGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroup, options *CapacityReservationGroupsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + 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-09-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 *CapacityReservationGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (CapacityReservationGroupsClientCreateOrUpdateResponse, error) { + result := CapacityReservationGroupsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroup); err != nil { + return CapacityReservationGroupsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - The operation to delete a capacity reservation group. This operation is allowed only if all the associated resources +// are disassociated from the reservation group and all capacity reservations under +// the reservation group have also been deleted. Please refer to https://aka.ms/CapacityReservation for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - options - CapacityReservationGroupsClientDeleteOptions contains the optional parameters for the CapacityReservationGroupsClient.Delete +// method. +func (client *CapacityReservationGroupsClient) Delete(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientDeleteOptions) (CapacityReservationGroupsClientDeleteResponse, error) { + var err error + const operationName = "CapacityReservationGroupsClient.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, capacityReservationGroupName, options) + if err != nil { + return CapacityReservationGroupsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CapacityReservationGroupsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CapacityReservationGroupsClientDeleteResponse{}, err + } + return CapacityReservationGroupsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CapacityReservationGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - The operation that retrieves information about a capacity reservation group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - options - CapacityReservationGroupsClientGetOptions contains the optional parameters for the CapacityReservationGroupsClient.Get +// method. +func (client *CapacityReservationGroupsClient) Get(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientGetOptions) (CapacityReservationGroupsClientGetResponse, error) { + var err error + const operationName = "CapacityReservationGroupsClient.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, capacityReservationGroupName, options) + if err != nil { + return CapacityReservationGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CapacityReservationGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CapacityReservationGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CapacityReservationGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CapacityReservationGroupsClient) getHandleResponse(resp *http.Response) (CapacityReservationGroupsClientGetResponse, error) { + result := CapacityReservationGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroup); err != nil { + return CapacityReservationGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all of the capacity reservation groups in the specified resource group. Use the nextLink +// property in the response to get the next page of capacity reservation groups. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - CapacityReservationGroupsClientListByResourceGroupOptions contains the optional parameters for the CapacityReservationGroupsClient.NewListByResourceGroupPager +// method. +func (client *CapacityReservationGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *CapacityReservationGroupsClientListByResourceGroupOptions) *runtime.Pager[CapacityReservationGroupsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CapacityReservationGroupsClientListByResourceGroupResponse]{ + More: func(page CapacityReservationGroupsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CapacityReservationGroupsClientListByResourceGroupResponse) (CapacityReservationGroupsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CapacityReservationGroupsClient.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 CapacityReservationGroupsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *CapacityReservationGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *CapacityReservationGroupsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups" + 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-09-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 +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *CapacityReservationGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (CapacityReservationGroupsClientListByResourceGroupResponse, error) { + result := CapacityReservationGroupsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroupListResult); err != nil { + return CapacityReservationGroupsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists all of the capacity reservation groups in the subscription. Use the nextLink property +// in the response to get the next page of capacity reservation groups. +// +// Generated from API version 2023-09-01 +// - options - CapacityReservationGroupsClientListBySubscriptionOptions contains the optional parameters for the CapacityReservationGroupsClient.NewListBySubscriptionPager +// method. +func (client *CapacityReservationGroupsClient) NewListBySubscriptionPager(options *CapacityReservationGroupsClientListBySubscriptionOptions) *runtime.Pager[CapacityReservationGroupsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CapacityReservationGroupsClientListBySubscriptionResponse]{ + More: func(page CapacityReservationGroupsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CapacityReservationGroupsClientListBySubscriptionResponse) (CapacityReservationGroupsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CapacityReservationGroupsClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CapacityReservationGroupsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *CapacityReservationGroupsClient) listBySubscriptionCreateRequest(ctx context.Context, options *CapacityReservationGroupsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/capacityReservationGroups" + 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-09-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 +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *CapacityReservationGroupsClient) listBySubscriptionHandleResponse(resp *http.Response) (CapacityReservationGroupsClientListBySubscriptionResponse, error) { + result := CapacityReservationGroupsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroupListResult); err != nil { + return CapacityReservationGroupsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - The operation to update a capacity reservation group. When updating a capacity reservation group, only tags and +// sharing profile may be modified. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - parameters - Parameters supplied to the Update capacity reservation Group operation. +// - options - CapacityReservationGroupsClientUpdateOptions contains the optional parameters for the CapacityReservationGroupsClient.Update +// method. +func (client *CapacityReservationGroupsClient) Update(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroupUpdate, options *CapacityReservationGroupsClientUpdateOptions) (CapacityReservationGroupsClientUpdateResponse, error) { + var err error + const operationName = "CapacityReservationGroupsClient.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, capacityReservationGroupName, parameters, options) + if err != nil { + return CapacityReservationGroupsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CapacityReservationGroupsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CapacityReservationGroupsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *CapacityReservationGroupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, parameters CapacityReservationGroupUpdate, options *CapacityReservationGroupsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + 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-09-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 *CapacityReservationGroupsClient) updateHandleResponse(resp *http.Response) (CapacityReservationGroupsClientUpdateResponse, error) { + result := CapacityReservationGroupsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationGroup); err != nil { + return CapacityReservationGroupsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/capacityreservations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/capacityreservations_client.go new file mode 100644 index 000000000..951b0ac91 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/capacityreservations_client.go @@ -0,0 +1,443 @@ +//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 armcompute + +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" +) + +// CapacityReservationsClient contains the methods for the CapacityReservations group. +// Don't use this type directly, use NewCapacityReservationsClient() instead. +type CapacityReservationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCapacityReservationsClient creates a new instance of CapacityReservationsClient 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 NewCapacityReservationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CapacityReservationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CapacityReservationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update a capacity reservation. Please note some properties can be set +// only during capacity reservation creation. Please refer to https://aka.ms/CapacityReservation for more +// details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - capacityReservationName - The name of the capacity reservation. +// - parameters - Parameters supplied to the Create capacity reservation. +// - options - CapacityReservationsClientBeginCreateOrUpdateOptions contains the optional parameters for the CapacityReservationsClient.BeginCreateOrUpdate +// method. +func (client *CapacityReservationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservation, options *CapacityReservationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[CapacityReservationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CapacityReservationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CapacityReservationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update a capacity reservation. Please note some properties can be set only +// during capacity reservation creation. Please refer to https://aka.ms/CapacityReservation for more +// details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *CapacityReservationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservation, options *CapacityReservationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CapacityReservationsClient.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, capacityReservationGroupName, capacityReservationName, 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 *CapacityReservationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservation, options *CapacityReservationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + if capacityReservationName == "" { + return nil, errors.New("parameter capacityReservationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName)) + 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-09-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 - The operation to delete a capacity reservation. This operation is allowed only when all the associated resources +// are disassociated from the capacity reservation. Please refer to +// https://aka.ms/CapacityReservation for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - capacityReservationName - The name of the capacity reservation. +// - options - CapacityReservationsClientBeginDeleteOptions contains the optional parameters for the CapacityReservationsClient.BeginDelete +// method. +func (client *CapacityReservationsClient) BeginDelete(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientBeginDeleteOptions) (*runtime.Poller[CapacityReservationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CapacityReservationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CapacityReservationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete a capacity reservation. This operation is allowed only when all the associated resources +// are disassociated from the capacity reservation. Please refer to +// https://aka.ms/CapacityReservation for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *CapacityReservationsClient) deleteOperation(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CapacityReservationsClient.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, capacityReservationGroupName, capacityReservationName, 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 *CapacityReservationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + if capacityReservationName == "" { + return nil, errors.New("parameter capacityReservationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - The operation that retrieves information about the capacity reservation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - capacityReservationName - The name of the capacity reservation. +// - options - CapacityReservationsClientGetOptions contains the optional parameters for the CapacityReservationsClient.Get +// method. +func (client *CapacityReservationsClient) Get(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientGetOptions) (CapacityReservationsClientGetResponse, error) { + var err error + const operationName = "CapacityReservationsClient.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, capacityReservationGroupName, capacityReservationName, options) + if err != nil { + return CapacityReservationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CapacityReservationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CapacityReservationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CapacityReservationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + if capacityReservationName == "" { + return nil, errors.New("parameter capacityReservationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CapacityReservationsClient) getHandleResponse(resp *http.Response) (CapacityReservationsClientGetResponse, error) { + result := CapacityReservationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservation); err != nil { + return CapacityReservationsClientGetResponse{}, err + } + return result, nil +} + +// NewListByCapacityReservationGroupPager - Lists all of the capacity reservations in the specified capacity reservation group. +// Use the nextLink property in the response to get the next page of capacity reservations. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - options - CapacityReservationsClientListByCapacityReservationGroupOptions contains the optional parameters for the CapacityReservationsClient.NewListByCapacityReservationGroupPager +// method. +func (client *CapacityReservationsClient) NewListByCapacityReservationGroupPager(resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationsClientListByCapacityReservationGroupOptions) *runtime.Pager[CapacityReservationsClientListByCapacityReservationGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CapacityReservationsClientListByCapacityReservationGroupResponse]{ + More: func(page CapacityReservationsClientListByCapacityReservationGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CapacityReservationsClientListByCapacityReservationGroupResponse) (CapacityReservationsClientListByCapacityReservationGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CapacityReservationsClient.NewListByCapacityReservationGroupPager") + 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.listByCapacityReservationGroupCreateRequest(ctx, resourceGroupName, capacityReservationGroupName, options) + }, nil) + if err != nil { + return CapacityReservationsClientListByCapacityReservationGroupResponse{}, err + } + return client.listByCapacityReservationGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCapacityReservationGroupCreateRequest creates the ListByCapacityReservationGroup request. +func (client *CapacityReservationsClient) listByCapacityReservationGroupCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, options *CapacityReservationsClientListByCapacityReservationGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCapacityReservationGroupHandleResponse handles the ListByCapacityReservationGroup response. +func (client *CapacityReservationsClient) listByCapacityReservationGroupHandleResponse(resp *http.Response) (CapacityReservationsClientListByCapacityReservationGroupResponse, error) { + result := CapacityReservationsClientListByCapacityReservationGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapacityReservationListResult); err != nil { + return CapacityReservationsClientListByCapacityReservationGroupResponse{}, err + } + return result, nil +} + +// BeginUpdate - The operation to update a capacity reservation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - capacityReservationGroupName - The name of the capacity reservation group. +// - capacityReservationName - The name of the capacity reservation. +// - parameters - Parameters supplied to the Update capacity reservation operation. +// - options - CapacityReservationsClientBeginUpdateOptions contains the optional parameters for the CapacityReservationsClient.BeginUpdate +// method. +func (client *CapacityReservationsClient) BeginUpdate(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsClientBeginUpdateOptions) (*runtime.Poller[CapacityReservationsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, capacityReservationGroupName, capacityReservationName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CapacityReservationsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CapacityReservationsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - The operation to update a capacity reservation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *CapacityReservationsClient) update(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CapacityReservationsClient.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, capacityReservationGroupName, capacityReservationName, 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 *CapacityReservationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, parameters CapacityReservationUpdate, options *CapacityReservationsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if capacityReservationGroupName == "" { + return nil, errors.New("parameter capacityReservationGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationGroupName}", url.PathEscape(capacityReservationGroupName)) + if capacityReservationName == "" { + return nil, errors.New("parameter capacityReservationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capacityReservationName}", url.PathEscape(capacityReservationName)) + 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-09-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/compute/armcompute/v5/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/ci.yml new file mode 100644 index 000000000..084ed1b49 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/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/compute/armcompute/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/compute/armcompute/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + IncludeRelease: true + ServiceDirectory: 'resourcemanager/compute/armcompute' diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/client_factory.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/client_factory.go new file mode 100644 index 000000000..b8600b614 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/client_factory.go @@ -0,0 +1,333 @@ +//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 armcompute + +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, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, credential: credential, + options: options.Clone(), + }, nil +} + +// NewAvailabilitySetsClient creates a new instance of AvailabilitySetsClient. +func (c *ClientFactory) NewAvailabilitySetsClient() *AvailabilitySetsClient { + subClient, _ := NewAvailabilitySetsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCapacityReservationGroupsClient creates a new instance of CapacityReservationGroupsClient. +func (c *ClientFactory) NewCapacityReservationGroupsClient() *CapacityReservationGroupsClient { + subClient, _ := NewCapacityReservationGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCapacityReservationsClient creates a new instance of CapacityReservationsClient. +func (c *ClientFactory) NewCapacityReservationsClient() *CapacityReservationsClient { + subClient, _ := NewCapacityReservationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCloudServiceOperatingSystemsClient creates a new instance of CloudServiceOperatingSystemsClient. +func (c *ClientFactory) NewCloudServiceOperatingSystemsClient() *CloudServiceOperatingSystemsClient { + subClient, _ := NewCloudServiceOperatingSystemsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCloudServiceRoleInstancesClient creates a new instance of CloudServiceRoleInstancesClient. +func (c *ClientFactory) NewCloudServiceRoleInstancesClient() *CloudServiceRoleInstancesClient { + subClient, _ := NewCloudServiceRoleInstancesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCloudServiceRolesClient creates a new instance of CloudServiceRolesClient. +func (c *ClientFactory) NewCloudServiceRolesClient() *CloudServiceRolesClient { + subClient, _ := NewCloudServiceRolesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCloudServicesClient creates a new instance of CloudServicesClient. +func (c *ClientFactory) NewCloudServicesClient() *CloudServicesClient { + subClient, _ := NewCloudServicesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCloudServicesUpdateDomainClient creates a new instance of CloudServicesUpdateDomainClient. +func (c *ClientFactory) NewCloudServicesUpdateDomainClient() *CloudServicesUpdateDomainClient { + subClient, _ := NewCloudServicesUpdateDomainClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCommunityGalleriesClient creates a new instance of CommunityGalleriesClient. +func (c *ClientFactory) NewCommunityGalleriesClient() *CommunityGalleriesClient { + subClient, _ := NewCommunityGalleriesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCommunityGalleryImageVersionsClient creates a new instance of CommunityGalleryImageVersionsClient. +func (c *ClientFactory) NewCommunityGalleryImageVersionsClient() *CommunityGalleryImageVersionsClient { + subClient, _ := NewCommunityGalleryImageVersionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCommunityGalleryImagesClient creates a new instance of CommunityGalleryImagesClient. +func (c *ClientFactory) NewCommunityGalleryImagesClient() *CommunityGalleryImagesClient { + subClient, _ := NewCommunityGalleryImagesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDedicatedHostGroupsClient creates a new instance of DedicatedHostGroupsClient. +func (c *ClientFactory) NewDedicatedHostGroupsClient() *DedicatedHostGroupsClient { + subClient, _ := NewDedicatedHostGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDedicatedHostsClient creates a new instance of DedicatedHostsClient. +func (c *ClientFactory) NewDedicatedHostsClient() *DedicatedHostsClient { + subClient, _ := NewDedicatedHostsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDiskAccessesClient creates a new instance of DiskAccessesClient. +func (c *ClientFactory) NewDiskAccessesClient() *DiskAccessesClient { + subClient, _ := NewDiskAccessesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDiskEncryptionSetsClient creates a new instance of DiskEncryptionSetsClient. +func (c *ClientFactory) NewDiskEncryptionSetsClient() *DiskEncryptionSetsClient { + subClient, _ := NewDiskEncryptionSetsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDiskRestorePointClient creates a new instance of DiskRestorePointClient. +func (c *ClientFactory) NewDiskRestorePointClient() *DiskRestorePointClient { + subClient, _ := NewDiskRestorePointClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDisksClient creates a new instance of DisksClient. +func (c *ClientFactory) NewDisksClient() *DisksClient { + subClient, _ := NewDisksClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewGalleriesClient creates a new instance of GalleriesClient. +func (c *ClientFactory) NewGalleriesClient() *GalleriesClient { + subClient, _ := NewGalleriesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewGalleryApplicationVersionsClient creates a new instance of GalleryApplicationVersionsClient. +func (c *ClientFactory) NewGalleryApplicationVersionsClient() *GalleryApplicationVersionsClient { + subClient, _ := NewGalleryApplicationVersionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewGalleryApplicationsClient creates a new instance of GalleryApplicationsClient. +func (c *ClientFactory) NewGalleryApplicationsClient() *GalleryApplicationsClient { + subClient, _ := NewGalleryApplicationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewGalleryImageVersionsClient creates a new instance of GalleryImageVersionsClient. +func (c *ClientFactory) NewGalleryImageVersionsClient() *GalleryImageVersionsClient { + subClient, _ := NewGalleryImageVersionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewGalleryImagesClient creates a new instance of GalleryImagesClient. +func (c *ClientFactory) NewGalleryImagesClient() *GalleryImagesClient { + subClient, _ := NewGalleryImagesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewGallerySharingProfileClient creates a new instance of GallerySharingProfileClient. +func (c *ClientFactory) NewGallerySharingProfileClient() *GallerySharingProfileClient { + subClient, _ := NewGallerySharingProfileClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewImagesClient creates a new instance of ImagesClient. +func (c *ClientFactory) NewImagesClient() *ImagesClient { + subClient, _ := NewImagesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLogAnalyticsClient creates a new instance of LogAnalyticsClient. +func (c *ClientFactory) NewLogAnalyticsClient() *LogAnalyticsClient { + subClient, _ := NewLogAnalyticsClient(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 +} + +// NewProximityPlacementGroupsClient creates a new instance of ProximityPlacementGroupsClient. +func (c *ClientFactory) NewProximityPlacementGroupsClient() *ProximityPlacementGroupsClient { + subClient, _ := NewProximityPlacementGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewResourceSKUsClient creates a new instance of ResourceSKUsClient. +func (c *ClientFactory) NewResourceSKUsClient() *ResourceSKUsClient { + subClient, _ := NewResourceSKUsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRestorePointCollectionsClient creates a new instance of RestorePointCollectionsClient. +func (c *ClientFactory) NewRestorePointCollectionsClient() *RestorePointCollectionsClient { + subClient, _ := NewRestorePointCollectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRestorePointsClient creates a new instance of RestorePointsClient. +func (c *ClientFactory) NewRestorePointsClient() *RestorePointsClient { + subClient, _ := NewRestorePointsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSSHPublicKeysClient creates a new instance of SSHPublicKeysClient. +func (c *ClientFactory) NewSSHPublicKeysClient() *SSHPublicKeysClient { + subClient, _ := NewSSHPublicKeysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSharedGalleriesClient creates a new instance of SharedGalleriesClient. +func (c *ClientFactory) NewSharedGalleriesClient() *SharedGalleriesClient { + subClient, _ := NewSharedGalleriesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSharedGalleryImageVersionsClient creates a new instance of SharedGalleryImageVersionsClient. +func (c *ClientFactory) NewSharedGalleryImageVersionsClient() *SharedGalleryImageVersionsClient { + subClient, _ := NewSharedGalleryImageVersionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSharedGalleryImagesClient creates a new instance of SharedGalleryImagesClient. +func (c *ClientFactory) NewSharedGalleryImagesClient() *SharedGalleryImagesClient { + subClient, _ := NewSharedGalleryImagesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSnapshotsClient creates a new instance of SnapshotsClient. +func (c *ClientFactory) NewSnapshotsClient() *SnapshotsClient { + subClient, _ := NewSnapshotsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewUsageClient creates a new instance of UsageClient. +func (c *ClientFactory) NewUsageClient() *UsageClient { + subClient, _ := NewUsageClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineExtensionImagesClient creates a new instance of VirtualMachineExtensionImagesClient. +func (c *ClientFactory) NewVirtualMachineExtensionImagesClient() *VirtualMachineExtensionImagesClient { + subClient, _ := NewVirtualMachineExtensionImagesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineExtensionsClient creates a new instance of VirtualMachineExtensionsClient. +func (c *ClientFactory) NewVirtualMachineExtensionsClient() *VirtualMachineExtensionsClient { + subClient, _ := NewVirtualMachineExtensionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineImagesClient creates a new instance of VirtualMachineImagesClient. +func (c *ClientFactory) NewVirtualMachineImagesClient() *VirtualMachineImagesClient { + subClient, _ := NewVirtualMachineImagesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineImagesEdgeZoneClient creates a new instance of VirtualMachineImagesEdgeZoneClient. +func (c *ClientFactory) NewVirtualMachineImagesEdgeZoneClient() *VirtualMachineImagesEdgeZoneClient { + subClient, _ := NewVirtualMachineImagesEdgeZoneClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineRunCommandsClient creates a new instance of VirtualMachineRunCommandsClient. +func (c *ClientFactory) NewVirtualMachineRunCommandsClient() *VirtualMachineRunCommandsClient { + subClient, _ := NewVirtualMachineRunCommandsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineScaleSetExtensionsClient creates a new instance of VirtualMachineScaleSetExtensionsClient. +func (c *ClientFactory) NewVirtualMachineScaleSetExtensionsClient() *VirtualMachineScaleSetExtensionsClient { + subClient, _ := NewVirtualMachineScaleSetExtensionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineScaleSetRollingUpgradesClient creates a new instance of VirtualMachineScaleSetRollingUpgradesClient. +func (c *ClientFactory) NewVirtualMachineScaleSetRollingUpgradesClient() *VirtualMachineScaleSetRollingUpgradesClient { + subClient, _ := NewVirtualMachineScaleSetRollingUpgradesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineScaleSetVMExtensionsClient creates a new instance of VirtualMachineScaleSetVMExtensionsClient. +func (c *ClientFactory) NewVirtualMachineScaleSetVMExtensionsClient() *VirtualMachineScaleSetVMExtensionsClient { + subClient, _ := NewVirtualMachineScaleSetVMExtensionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineScaleSetVMRunCommandsClient creates a new instance of VirtualMachineScaleSetVMRunCommandsClient. +func (c *ClientFactory) NewVirtualMachineScaleSetVMRunCommandsClient() *VirtualMachineScaleSetVMRunCommandsClient { + subClient, _ := NewVirtualMachineScaleSetVMRunCommandsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineScaleSetVMsClient creates a new instance of VirtualMachineScaleSetVMsClient. +func (c *ClientFactory) NewVirtualMachineScaleSetVMsClient() *VirtualMachineScaleSetVMsClient { + subClient, _ := NewVirtualMachineScaleSetVMsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineScaleSetsClient creates a new instance of VirtualMachineScaleSetsClient. +func (c *ClientFactory) NewVirtualMachineScaleSetsClient() *VirtualMachineScaleSetsClient { + subClient, _ := NewVirtualMachineScaleSetsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachineSizesClient creates a new instance of VirtualMachineSizesClient. +func (c *ClientFactory) NewVirtualMachineSizesClient() *VirtualMachineSizesClient { + subClient, _ := NewVirtualMachineSizesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualMachinesClient creates a new instance of VirtualMachinesClient. +func (c *ClientFactory) NewVirtualMachinesClient() *VirtualMachinesClient { + subClient, _ := NewVirtualMachinesClient(c.subscriptionID, c.credential, c.options) + return subClient +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceoperatingsystems_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceoperatingsystems_client.go new file mode 100644 index 000000000..bd0cda902 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceoperatingsystems_client.go @@ -0,0 +1,301 @@ +//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 armcompute + +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" +) + +// CloudServiceOperatingSystemsClient contains the methods for the CloudServiceOperatingSystems group. +// Don't use this type directly, use NewCloudServiceOperatingSystemsClient() instead. +type CloudServiceOperatingSystemsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudServiceOperatingSystemsClient creates a new instance of CloudServiceOperatingSystemsClient 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 NewCloudServiceOperatingSystemsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServiceOperatingSystemsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudServiceOperatingSystemsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetOSFamily - Gets properties of a guest operating system family that can be specified in the XML service configuration +// (.cscfg) for a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - location - Name of the location that the OS family pertains to. +// - osFamilyName - Name of the OS family. +// - options - CloudServiceOperatingSystemsClientGetOSFamilyOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.GetOSFamily +// method. +func (client *CloudServiceOperatingSystemsClient) GetOSFamily(ctx context.Context, location string, osFamilyName string, options *CloudServiceOperatingSystemsClientGetOSFamilyOptions) (CloudServiceOperatingSystemsClientGetOSFamilyResponse, error) { + var err error + const operationName = "CloudServiceOperatingSystemsClient.GetOSFamily" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getOSFamilyCreateRequest(ctx, location, osFamilyName, options) + if err != nil { + return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err + } + resp, err := client.getOSFamilyHandleResponse(httpResp) + return resp, err +} + +// getOSFamilyCreateRequest creates the GetOSFamily request. +func (client *CloudServiceOperatingSystemsClient) getOSFamilyCreateRequest(ctx context.Context, location string, osFamilyName string, options *CloudServiceOperatingSystemsClientGetOSFamilyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsFamilies/{osFamilyName}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if osFamilyName == "" { + return nil, errors.New("parameter osFamilyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{osFamilyName}", url.PathEscape(osFamilyName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getOSFamilyHandleResponse handles the GetOSFamily response. +func (client *CloudServiceOperatingSystemsClient) getOSFamilyHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientGetOSFamilyResponse, error) { + result := CloudServiceOperatingSystemsClientGetOSFamilyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OSFamily); err != nil { + return CloudServiceOperatingSystemsClientGetOSFamilyResponse{}, err + } + return result, nil +} + +// GetOSVersion - Gets properties of a guest operating system version that can be specified in the XML service configuration +// (.cscfg) for a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - location - Name of the location that the OS version pertains to. +// - osVersionName - Name of the OS version. +// - options - CloudServiceOperatingSystemsClientGetOSVersionOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.GetOSVersion +// method. +func (client *CloudServiceOperatingSystemsClient) GetOSVersion(ctx context.Context, location string, osVersionName string, options *CloudServiceOperatingSystemsClientGetOSVersionOptions) (CloudServiceOperatingSystemsClientGetOSVersionResponse, error) { + var err error + const operationName = "CloudServiceOperatingSystemsClient.GetOSVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getOSVersionCreateRequest(ctx, location, osVersionName, options) + if err != nil { + return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err + } + resp, err := client.getOSVersionHandleResponse(httpResp) + return resp, err +} + +// getOSVersionCreateRequest creates the GetOSVersion request. +func (client *CloudServiceOperatingSystemsClient) getOSVersionCreateRequest(ctx context.Context, location string, osVersionName string, options *CloudServiceOperatingSystemsClientGetOSVersionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsVersions/{osVersionName}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if osVersionName == "" { + return nil, errors.New("parameter osVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{osVersionName}", url.PathEscape(osVersionName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getOSVersionHandleResponse handles the GetOSVersion response. +func (client *CloudServiceOperatingSystemsClient) getOSVersionHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientGetOSVersionResponse, error) { + result := CloudServiceOperatingSystemsClientGetOSVersionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OSVersion); err != nil { + return CloudServiceOperatingSystemsClientGetOSVersionResponse{}, err + } + return result, nil +} + +// NewListOSFamiliesPager - Gets a list of all guest operating system families available to be specified in the XML service +// configuration (.cscfg) for a cloud service. Use nextLink property in the response to get the next page +// of OS Families. Do this till nextLink is null to fetch all the OS Families. +// +// Generated from API version 2022-09-04 +// - location - Name of the location that the OS families pertain to. +// - options - CloudServiceOperatingSystemsClientListOSFamiliesOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.NewListOSFamiliesPager +// method. +func (client *CloudServiceOperatingSystemsClient) NewListOSFamiliesPager(location string, options *CloudServiceOperatingSystemsClientListOSFamiliesOptions) *runtime.Pager[CloudServiceOperatingSystemsClientListOSFamiliesResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudServiceOperatingSystemsClientListOSFamiliesResponse]{ + More: func(page CloudServiceOperatingSystemsClientListOSFamiliesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudServiceOperatingSystemsClientListOSFamiliesResponse) (CloudServiceOperatingSystemsClientListOSFamiliesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceOperatingSystemsClient.NewListOSFamiliesPager") + 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.listOSFamiliesCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return CloudServiceOperatingSystemsClientListOSFamiliesResponse{}, err + } + return client.listOSFamiliesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listOSFamiliesCreateRequest creates the ListOSFamilies request. +func (client *CloudServiceOperatingSystemsClient) listOSFamiliesCreateRequest(ctx context.Context, location string, options *CloudServiceOperatingSystemsClientListOSFamiliesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsFamilies" + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listOSFamiliesHandleResponse handles the ListOSFamilies response. +func (client *CloudServiceOperatingSystemsClient) listOSFamiliesHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientListOSFamiliesResponse, error) { + result := CloudServiceOperatingSystemsClientListOSFamiliesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OSFamilyListResult); err != nil { + return CloudServiceOperatingSystemsClientListOSFamiliesResponse{}, err + } + return result, nil +} + +// NewListOSVersionsPager - Gets a list of all guest operating system versions available to be specified in the XML service +// configuration (.cscfg) for a cloud service. Use nextLink property in the response to get the next page +// of OS versions. Do this till nextLink is null to fetch all the OS versions. +// +// Generated from API version 2022-09-04 +// - location - Name of the location that the OS versions pertain to. +// - options - CloudServiceOperatingSystemsClientListOSVersionsOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.NewListOSVersionsPager +// method. +func (client *CloudServiceOperatingSystemsClient) NewListOSVersionsPager(location string, options *CloudServiceOperatingSystemsClientListOSVersionsOptions) *runtime.Pager[CloudServiceOperatingSystemsClientListOSVersionsResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudServiceOperatingSystemsClientListOSVersionsResponse]{ + More: func(page CloudServiceOperatingSystemsClientListOSVersionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudServiceOperatingSystemsClientListOSVersionsResponse) (CloudServiceOperatingSystemsClientListOSVersionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceOperatingSystemsClient.NewListOSVersionsPager") + 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.listOSVersionsCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return CloudServiceOperatingSystemsClientListOSVersionsResponse{}, err + } + return client.listOSVersionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listOSVersionsCreateRequest creates the ListOSVersions request. +func (client *CloudServiceOperatingSystemsClient) listOSVersionsCreateRequest(ctx context.Context, location string, options *CloudServiceOperatingSystemsClientListOSVersionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/cloudServiceOsVersions" + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listOSVersionsHandleResponse handles the ListOSVersions response. +func (client *CloudServiceOperatingSystemsClient) listOSVersionsHandleResponse(resp *http.Response) (CloudServiceOperatingSystemsClientListOSVersionsResponse, error) { + result := CloudServiceOperatingSystemsClientListOSVersionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OSVersionListResult); err != nil { + return CloudServiceOperatingSystemsClientListOSVersionsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceroleinstances_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceroleinstances_client.go new file mode 100644 index 000000000..b84530166 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceroleinstances_client.go @@ -0,0 +1,648 @@ +//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 armcompute + +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" +) + +// CloudServiceRoleInstancesClient contains the methods for the CloudServiceRoleInstances group. +// Don't use this type directly, use NewCloudServiceRoleInstancesClient() instead. +type CloudServiceRoleInstancesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudServiceRoleInstancesClient creates a new instance of CloudServiceRoleInstancesClient 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 NewCloudServiceRoleInstancesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServiceRoleInstancesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudServiceRoleInstancesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginDelete - Deletes a role instance from a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleInstanceName - Name of the role instance. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientBeginDeleteOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginDelete +// method. +func (client *CloudServiceRoleInstancesClient) BeginDelete(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginDeleteOptions) (*runtime.Poller[CloudServiceRoleInstancesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a role instance from a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServiceRoleInstancesClient) deleteOperation(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CloudServiceRoleInstancesClient.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, roleInstanceName, resourceGroupName, cloudServiceName, 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 *CloudServiceRoleInstancesClient) deleteCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}" + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a role instance from a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleInstanceName - Name of the role instance. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientGetOptions contains the optional parameters for the CloudServiceRoleInstancesClient.Get +// method. +func (client *CloudServiceRoleInstancesClient) Get(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetOptions) (CloudServiceRoleInstancesClientGetResponse, error) { + var err error + const operationName = "CloudServiceRoleInstancesClient.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, roleInstanceName, resourceGroupName, cloudServiceName, options) + if err != nil { + return CloudServiceRoleInstancesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServiceRoleInstancesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServiceRoleInstancesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudServiceRoleInstancesClient) getCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}" + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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 +} + +// getHandleResponse handles the Get response. +func (client *CloudServiceRoleInstancesClient) getHandleResponse(resp *http.Response) (CloudServiceRoleInstancesClientGetResponse, error) { + result := CloudServiceRoleInstancesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RoleInstance); err != nil { + return CloudServiceRoleInstancesClientGetResponse{}, err + } + return result, nil +} + +// GetInstanceView - Retrieves information about the run-time state of a role instance in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleInstanceName - Name of the role instance. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientGetInstanceViewOptions contains the optional parameters for the CloudServiceRoleInstancesClient.GetInstanceView +// method. +func (client *CloudServiceRoleInstancesClient) GetInstanceView(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetInstanceViewOptions) (CloudServiceRoleInstancesClientGetInstanceViewResponse, error) { + var err error + const operationName = "CloudServiceRoleInstancesClient.GetInstanceView" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getInstanceViewCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options) + if err != nil { + return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err + } + resp, err := client.getInstanceViewHandleResponse(httpResp) + return resp, err +} + +// getInstanceViewCreateRequest creates the GetInstanceView request. +func (client *CloudServiceRoleInstancesClient) getInstanceViewCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetInstanceViewOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/instanceView" + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getInstanceViewHandleResponse handles the GetInstanceView response. +func (client *CloudServiceRoleInstancesClient) getInstanceViewHandleResponse(resp *http.Response) (CloudServiceRoleInstancesClientGetInstanceViewResponse, error) { + result := CloudServiceRoleInstancesClientGetInstanceViewResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RoleInstanceView); err != nil { + return CloudServiceRoleInstancesClientGetInstanceViewResponse{}, err + } + return result, nil +} + +// GetRemoteDesktopFile - Gets a remote desktop file for a role instance in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleInstanceName - Name of the role instance. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions contains the optional parameters for the CloudServiceRoleInstancesClient.GetRemoteDesktopFile +// method. +func (client *CloudServiceRoleInstancesClient) GetRemoteDesktopFile(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions) (CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse, error) { + var err error + const operationName = "CloudServiceRoleInstancesClient.GetRemoteDesktopFile" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getRemoteDesktopFileCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options) + if err != nil { + return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{}, err + } + return CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse{Body: httpResp.Body}, nil +} + +// getRemoteDesktopFileCreateRequest creates the GetRemoteDesktopFile request. +func (client *CloudServiceRoleInstancesClient) getRemoteDesktopFileCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/remoteDesktopFile" + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/x-rdp"} + return req, nil +} + +// NewListPager - Gets the list of all role instances in a cloud service. Use nextLink property in the response to get the +// next page of role instances. Do this till nextLink is null to fetch all the role instances. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientListOptions contains the optional parameters for the CloudServiceRoleInstancesClient.NewListPager +// method. +func (client *CloudServiceRoleInstancesClient) NewListPager(resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientListOptions) *runtime.Pager[CloudServiceRoleInstancesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudServiceRoleInstancesClientListResponse]{ + More: func(page CloudServiceRoleInstancesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudServiceRoleInstancesClientListResponse) (CloudServiceRoleInstancesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceRoleInstancesClient.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, cloudServiceName, options) + }, nil) + if err != nil { + return CloudServiceRoleInstancesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CloudServiceRoleInstancesClient) listCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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 +} + +// listHandleResponse handles the List response. +func (client *CloudServiceRoleInstancesClient) listHandleResponse(resp *http.Response) (CloudServiceRoleInstancesClientListResponse, error) { + result := CloudServiceRoleInstancesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RoleInstanceListResult); err != nil { + return CloudServiceRoleInstancesClientListResponse{}, err + } + return result, nil +} + +// BeginRebuild - The Rebuild Role Instance asynchronous operation reinstalls the operating system on instances of web roles +// or worker roles and initializes the storage resources that are used by them. If you do not +// want to initialize storage resources, you can use Reimage Role Instance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleInstanceName - Name of the role instance. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientBeginRebuildOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginRebuild +// method. +func (client *CloudServiceRoleInstancesClient) BeginRebuild(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRebuildOptions) (*runtime.Poller[CloudServiceRoleInstancesClientRebuildResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.rebuild(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientRebuildResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientRebuildResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Rebuild - The Rebuild Role Instance asynchronous operation reinstalls the operating system on instances of web roles or +// worker roles and initializes the storage resources that are used by them. If you do not +// want to initialize storage resources, you can use Reimage Role Instance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServiceRoleInstancesClient) rebuild(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRebuildOptions) (*http.Response, error) { + var err error + const operationName = "CloudServiceRoleInstancesClient.BeginRebuild" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rebuildCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, 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 +} + +// rebuildCreateRequest creates the Rebuild request. +func (client *CloudServiceRoleInstancesClient) rebuildCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRebuildOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/rebuild" + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginReimage - The Reimage Role Instance asynchronous operation reinstalls the operating system on instances of web roles +// or worker roles. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleInstanceName - Name of the role instance. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientBeginReimageOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginReimage +// method. +func (client *CloudServiceRoleInstancesClient) BeginReimage(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginReimageOptions) (*runtime.Poller[CloudServiceRoleInstancesClientReimageResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reimage(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reimage - The Reimage Role Instance asynchronous operation reinstalls the operating system on instances of web roles or +// worker roles. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServiceRoleInstancesClient) reimage(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginReimageOptions) (*http.Response, error) { + var err error + const operationName = "CloudServiceRoleInstancesClient.BeginReimage" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, 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 +} + +// reimageCreateRequest creates the Reimage request. +func (client *CloudServiceRoleInstancesClient) reimageCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginReimageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/reimage" + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginRestart - The Reboot Role Instance asynchronous operation requests a reboot of a role instance in the cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleInstanceName - Name of the role instance. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRoleInstancesClientBeginRestartOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginRestart +// method. +func (client *CloudServiceRoleInstancesClient) BeginRestart(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRestartOptions) (*runtime.Poller[CloudServiceRoleInstancesClientRestartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restart(ctx, roleInstanceName, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServiceRoleInstancesClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServiceRoleInstancesClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restart - The Reboot Role Instance asynchronous operation requests a reboot of a role instance in the cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServiceRoleInstancesClient) restart(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRestartOptions) (*http.Response, error) { + var err error + const operationName = "CloudServiceRoleInstancesClient.BeginRestart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restartCreateRequest(ctx, roleInstanceName, resourceGroupName, cloudServiceName, 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 +} + +// restartCreateRequest creates the Restart request. +func (client *CloudServiceRoleInstancesClient) restartCreateRequest(ctx context.Context, roleInstanceName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRoleInstancesClientBeginRestartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/restart" + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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/compute/armcompute/v5/cloudserviceroles_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceroles_client.go new file mode 100644 index 000000000..a4572cf14 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudserviceroles_client.go @@ -0,0 +1,180 @@ +//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 armcompute + +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" +) + +// CloudServiceRolesClient contains the methods for the CloudServiceRoles group. +// Don't use this type directly, use NewCloudServiceRolesClient() instead. +type CloudServiceRolesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudServiceRolesClient creates a new instance of CloudServiceRolesClient 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 NewCloudServiceRolesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServiceRolesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudServiceRolesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets a role from a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - roleName - Name of the role. +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRolesClientGetOptions contains the optional parameters for the CloudServiceRolesClient.Get method. +func (client *CloudServiceRolesClient) Get(ctx context.Context, roleName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientGetOptions) (CloudServiceRolesClientGetResponse, error) { + var err error + const operationName = "CloudServiceRolesClient.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, roleName, resourceGroupName, cloudServiceName, options) + if err != nil { + return CloudServiceRolesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServiceRolesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServiceRolesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudServiceRolesClient) getCreateRequest(ctx context.Context, roleName string, resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roles/{roleName}" + if roleName == "" { + return nil, errors.New("parameter roleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleName}", url.PathEscape(roleName)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudServiceRolesClient) getHandleResponse(resp *http.Response) (CloudServiceRolesClientGetResponse, error) { + result := CloudServiceRolesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudServiceRole); err != nil { + return CloudServiceRolesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of all roles in a cloud service. Use nextLink property in the response to get the next page +// of roles. Do this till nextLink is null to fetch all the roles. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServiceRolesClientListOptions contains the optional parameters for the CloudServiceRolesClient.NewListPager +// method. +func (client *CloudServiceRolesClient) NewListPager(resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientListOptions) *runtime.Pager[CloudServiceRolesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudServiceRolesClientListResponse]{ + More: func(page CloudServiceRolesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudServiceRolesClientListResponse) (CloudServiceRolesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServiceRolesClient.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, cloudServiceName, options) + }, nil) + if err != nil { + return CloudServiceRolesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CloudServiceRolesClient) listCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServiceRolesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roles" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CloudServiceRolesClient) listHandleResponse(resp *http.Response) (CloudServiceRolesClientListResponse, error) { + result := CloudServiceRolesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudServiceRoleListResult); err != nil { + return CloudServiceRolesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudservices_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudservices_client.go new file mode 100644 index 000000000..283d3a6fe --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudservices_client.go @@ -0,0 +1,1013 @@ +//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 armcompute + +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" +) + +// CloudServicesClient contains the methods for the CloudServices group. +// Don't use this type directly, use NewCloudServicesClient() instead. +type CloudServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudServicesClient creates a new instance of CloudServicesClient 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 NewCloudServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a cloud service. Please note some properties can be set only during cloud service +// creation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - parameters - The cloud service object. +// - options - CloudServicesClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudServicesClient.BeginCreateOrUpdate +// method. +func (client *CloudServicesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, cloudServiceName string, parameters CloudService, options *CloudServicesClientBeginCreateOrUpdateOptions) (*runtime.Poller[CloudServicesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, cloudServiceName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a cloud service. Please note some properties can be set only during cloud service creation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) createOrUpdate(ctx context.Context, resourceGroupName string, cloudServiceName string, parameters CloudService, options *CloudServicesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.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, cloudServiceName, 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 *CloudServicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, parameters CloudService, options *CloudServicesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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 a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientBeginDeleteOptions contains the optional parameters for the CloudServicesClient.BeginDelete +// method. +func (client *CloudServicesClient) BeginDelete(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginDeleteOptions) (*runtime.Poller[CloudServicesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) deleteOperation(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.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, cloudServiceName, 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 *CloudServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDeleteInstances - Deletes role instances in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientBeginDeleteInstancesOptions contains the optional parameters for the CloudServicesClient.BeginDeleteInstances +// method. +func (client *CloudServicesClient) BeginDeleteInstances(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginDeleteInstancesOptions) (*runtime.Poller[CloudServicesClientDeleteInstancesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteInstances(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientDeleteInstancesResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientDeleteInstancesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeleteInstances - Deletes role instances in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) deleteInstances(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginDeleteInstancesOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.BeginDeleteInstances" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteInstancesCreateRequest(ctx, resourceGroupName, cloudServiceName, 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 +} + +// deleteInstancesCreateRequest creates the DeleteInstances request. +func (client *CloudServicesClient) deleteInstancesCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginDeleteInstancesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/delete" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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 +} + +// Get - Display information about a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientGetOptions contains the optional parameters for the CloudServicesClient.Get method. +func (client *CloudServicesClient) Get(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientGetOptions) (CloudServicesClientGetResponse, error) { + var err error + const operationName = "CloudServicesClient.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, cloudServiceName, options) + if err != nil { + return CloudServicesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServicesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServicesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudServicesClient) getHandleResponse(resp *http.Response) (CloudServicesClientGetResponse, error) { + result := CloudServicesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudService); err != nil { + return CloudServicesClientGetResponse{}, err + } + return result, nil +} + +// GetInstanceView - Gets the status of a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientGetInstanceViewOptions contains the optional parameters for the CloudServicesClient.GetInstanceView +// method. +func (client *CloudServicesClient) GetInstanceView(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientGetInstanceViewOptions) (CloudServicesClientGetInstanceViewResponse, error) { + var err error + const operationName = "CloudServicesClient.GetInstanceView" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getInstanceViewCreateRequest(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return CloudServicesClientGetInstanceViewResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServicesClientGetInstanceViewResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServicesClientGetInstanceViewResponse{}, err + } + resp, err := client.getInstanceViewHandleResponse(httpResp) + return resp, err +} + +// getInstanceViewCreateRequest creates the GetInstanceView request. +func (client *CloudServicesClient) getInstanceViewCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientGetInstanceViewOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/instanceView" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getInstanceViewHandleResponse handles the GetInstanceView response. +func (client *CloudServicesClient) getInstanceViewHandleResponse(resp *http.Response) (CloudServicesClientGetInstanceViewResponse, error) { + result := CloudServicesClientGetInstanceViewResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudServiceInstanceView); err != nil { + return CloudServicesClientGetInstanceViewResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of all cloud services under a resource group. Use nextLink property in the response to get the +// next page of Cloud Services. Do this till nextLink is null to fetch all the Cloud Services. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - options - CloudServicesClientListOptions contains the optional parameters for the CloudServicesClient.NewListPager method. +func (client *CloudServicesClient) NewListPager(resourceGroupName string, options *CloudServicesClientListOptions) *runtime.Pager[CloudServicesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudServicesClientListResponse]{ + More: func(page CloudServicesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudServicesClientListResponse) (CloudServicesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServicesClient.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, options) + }, nil) + if err != nil { + return CloudServicesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CloudServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *CloudServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices" + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CloudServicesClient) listHandleResponse(resp *http.Response) (CloudServicesClientListResponse, error) { + result := CloudServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudServiceListResult); err != nil { + return CloudServicesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets a list of all cloud services in the subscription, regardless of the associated resource group. Use +// nextLink property in the response to get the next page of Cloud Services. Do this till nextLink +// is null to fetch all the Cloud Services. +// +// Generated from API version 2022-09-04 +// - options - CloudServicesClientListAllOptions contains the optional parameters for the CloudServicesClient.NewListAllPager +// method. +func (client *CloudServicesClient) NewListAllPager(options *CloudServicesClientListAllOptions) *runtime.Pager[CloudServicesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudServicesClientListAllResponse]{ + More: func(page CloudServicesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudServicesClientListAllResponse) (CloudServicesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServicesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return CloudServicesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *CloudServicesClient) listAllCreateRequest(ctx context.Context, options *CloudServicesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/cloudServices" + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *CloudServicesClient) listAllHandleResponse(resp *http.Response) (CloudServicesClientListAllResponse, error) { + result := CloudServicesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudServiceListResult); err != nil { + return CloudServicesClientListAllResponse{}, err + } + return result, nil +} + +// BeginPowerOff - Power off the cloud service. Note that resources are still attached and you are getting charged for the +// resources. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientBeginPowerOffOptions contains the optional parameters for the CloudServicesClient.BeginPowerOff +// method. +func (client *CloudServicesClient) BeginPowerOff(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginPowerOffOptions) (*runtime.Poller[CloudServicesClientPowerOffResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.powerOff(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PowerOff - Power off the cloud service. Note that resources are still attached and you are getting charged for the resources. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) powerOff(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginPowerOffOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.BeginPowerOff" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.powerOffCreateRequest(ctx, resourceGroupName, cloudServiceName, 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 +} + +// powerOffCreateRequest creates the PowerOff request. +func (client *CloudServicesClient) powerOffCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginPowerOffOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/poweroff" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginRebuild - Rebuild Role Instances reinstalls the operating system on instances of web roles or worker roles and initializes +// the storage resources that are used by them. If you do not want to initialize storage +// resources, you can use Reimage Role Instances. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientBeginRebuildOptions contains the optional parameters for the CloudServicesClient.BeginRebuild +// method. +func (client *CloudServicesClient) BeginRebuild(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginRebuildOptions) (*runtime.Poller[CloudServicesClientRebuildResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.rebuild(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientRebuildResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientRebuildResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Rebuild - Rebuild Role Instances reinstalls the operating system on instances of web roles or worker roles and initializes +// the storage resources that are used by them. If you do not want to initialize storage +// resources, you can use Reimage Role Instances. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) rebuild(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginRebuildOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.BeginRebuild" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rebuildCreateRequest(ctx, resourceGroupName, cloudServiceName, 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 +} + +// rebuildCreateRequest creates the Rebuild request. +func (client *CloudServicesClient) rebuildCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginRebuildOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/rebuild" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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 +} + +// BeginReimage - Reimage asynchronous operation reinstalls the operating system on instances of web roles or worker roles. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientBeginReimageOptions contains the optional parameters for the CloudServicesClient.BeginReimage +// method. +func (client *CloudServicesClient) BeginReimage(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginReimageOptions) (*runtime.Poller[CloudServicesClientReimageResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reimage(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reimage - Reimage asynchronous operation reinstalls the operating system on instances of web roles or worker roles. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) reimage(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginReimageOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.BeginReimage" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageCreateRequest(ctx, resourceGroupName, cloudServiceName, 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 +} + +// reimageCreateRequest creates the Reimage request. +func (client *CloudServicesClient) reimageCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginReimageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/reimage" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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 +} + +// BeginRestart - Restarts one or more role instances in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientBeginRestartOptions contains the optional parameters for the CloudServicesClient.BeginRestart +// method. +func (client *CloudServicesClient) BeginRestart(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginRestartOptions) (*runtime.Poller[CloudServicesClientRestartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restart(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restart - Restarts one or more role instances in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) restart(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginRestartOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.BeginRestart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restartCreateRequest(ctx, resourceGroupName, cloudServiceName, 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 +} + +// restartCreateRequest creates the Restart request. +func (client *CloudServicesClient) restartCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginRestartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/restart" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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 +} + +// BeginStart - Starts the cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesClientBeginStartOptions contains the optional parameters for the CloudServicesClient.BeginStart +// method. +func (client *CloudServicesClient) BeginStart(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginStartOptions) (*runtime.Poller[CloudServicesClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, cloudServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - Starts the cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) start(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, cloudServiceName, 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 +} + +// startCreateRequest creates the Start request. +func (client *CloudServicesClient) startCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/start" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Update a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - parameters - The cloud service object. +// - options - CloudServicesClientBeginUpdateOptions contains the optional parameters for the CloudServicesClient.BeginUpdate +// method. +func (client *CloudServicesClient) BeginUpdate(ctx context.Context, resourceGroupName string, cloudServiceName string, parameters CloudServiceUpdate, options *CloudServicesClientBeginUpdateOptions) (*runtime.Poller[CloudServicesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, cloudServiceName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesClient) update(ctx context.Context, resourceGroupName string, cloudServiceName string, parameters CloudServiceUpdate, options *CloudServicesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesClient.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, cloudServiceName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CloudServicesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, parameters CloudServiceUpdate, options *CloudServicesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + 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/compute/armcompute/v5/cloudservicesupdatedomain_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudservicesupdatedomain_client.go new file mode 100644 index 000000000..a4bd1e7b1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/cloudservicesupdatedomain_client.go @@ -0,0 +1,263 @@ +//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 armcompute + +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" +) + +// CloudServicesUpdateDomainClient contains the methods for the CloudServicesUpdateDomain group. +// Don't use this type directly, use NewCloudServicesUpdateDomainClient() instead. +type CloudServicesUpdateDomainClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudServicesUpdateDomainClient creates a new instance of CloudServicesUpdateDomainClient 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 NewCloudServicesUpdateDomainClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudServicesUpdateDomainClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudServicesUpdateDomainClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetUpdateDomain - Gets the specified update domain of a cloud service. Use nextLink property in the response to get the +// next page of update domains. Do this till nextLink is null to fetch all the update domains. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - updateDomain - Specifies an integer value that identifies the update domain. Update domains are identified with a zero-based +// index: the first update domain has an ID of 0, the second has an ID of 1, and so on. +// - options - CloudServicesUpdateDomainClientGetUpdateDomainOptions contains the optional parameters for the CloudServicesUpdateDomainClient.GetUpdateDomain +// method. +func (client *CloudServicesUpdateDomainClient) GetUpdateDomain(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, options *CloudServicesUpdateDomainClientGetUpdateDomainOptions) (CloudServicesUpdateDomainClientGetUpdateDomainResponse, error) { + var err error + const operationName = "CloudServicesUpdateDomainClient.GetUpdateDomain" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getUpdateDomainCreateRequest(ctx, resourceGroupName, cloudServiceName, updateDomain, options) + if err != nil { + return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err + } + resp, err := client.getUpdateDomainHandleResponse(httpResp) + return resp, err +} + +// getUpdateDomainCreateRequest creates the GetUpdateDomain request. +func (client *CloudServicesUpdateDomainClient) getUpdateDomainCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, options *CloudServicesUpdateDomainClientGetUpdateDomainOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/updateDomains/{updateDomain}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + urlPath = strings.ReplaceAll(urlPath, "{updateDomain}", url.PathEscape(strconv.FormatInt(int64(updateDomain), 10))) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getUpdateDomainHandleResponse handles the GetUpdateDomain response. +func (client *CloudServicesUpdateDomainClient) getUpdateDomainHandleResponse(resp *http.Response) (CloudServicesUpdateDomainClientGetUpdateDomainResponse, error) { + result := CloudServicesUpdateDomainClientGetUpdateDomainResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UpdateDomain); err != nil { + return CloudServicesUpdateDomainClientGetUpdateDomainResponse{}, err + } + return result, nil +} + +// NewListUpdateDomainsPager - Gets a list of all update domains in a cloud service. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - options - CloudServicesUpdateDomainClientListUpdateDomainsOptions contains the optional parameters for the CloudServicesUpdateDomainClient.NewListUpdateDomainsPager +// method. +func (client *CloudServicesUpdateDomainClient) NewListUpdateDomainsPager(resourceGroupName string, cloudServiceName string, options *CloudServicesUpdateDomainClientListUpdateDomainsOptions) *runtime.Pager[CloudServicesUpdateDomainClientListUpdateDomainsResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudServicesUpdateDomainClientListUpdateDomainsResponse]{ + More: func(page CloudServicesUpdateDomainClientListUpdateDomainsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudServicesUpdateDomainClientListUpdateDomainsResponse) (CloudServicesUpdateDomainClientListUpdateDomainsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudServicesUpdateDomainClient.NewListUpdateDomainsPager") + 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.listUpdateDomainsCreateRequest(ctx, resourceGroupName, cloudServiceName, options) + }, nil) + if err != nil { + return CloudServicesUpdateDomainClientListUpdateDomainsResponse{}, err + } + return client.listUpdateDomainsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listUpdateDomainsCreateRequest creates the ListUpdateDomains request. +func (client *CloudServicesUpdateDomainClient) listUpdateDomainsCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *CloudServicesUpdateDomainClientListUpdateDomainsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/updateDomains" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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", "2022-09-04") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listUpdateDomainsHandleResponse handles the ListUpdateDomains response. +func (client *CloudServicesUpdateDomainClient) listUpdateDomainsHandleResponse(resp *http.Response) (CloudServicesUpdateDomainClientListUpdateDomainsResponse, error) { + result := CloudServicesUpdateDomainClientListUpdateDomainsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UpdateDomainListResult); err != nil { + return CloudServicesUpdateDomainClientListUpdateDomainsResponse{}, err + } + return result, nil +} + +// BeginWalkUpdateDomain - Updates the role instances in the specified update domain. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +// - resourceGroupName - Name of the resource group. +// - cloudServiceName - Name of the cloud service. +// - updateDomain - Specifies an integer value that identifies the update domain. Update domains are identified with a zero-based +// index: the first update domain has an ID of 0, the second has an ID of 1, and so on. +// - parameters - The update domain object. +// - options - CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions contains the optional parameters for the CloudServicesUpdateDomainClient.BeginWalkUpdateDomain +// method. +func (client *CloudServicesUpdateDomainClient) BeginWalkUpdateDomain(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, parameters UpdateDomain, options *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions) (*runtime.Poller[CloudServicesUpdateDomainClientWalkUpdateDomainResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.walkUpdateDomain(ctx, resourceGroupName, cloudServiceName, updateDomain, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudServicesUpdateDomainClientWalkUpdateDomainResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudServicesUpdateDomainClientWalkUpdateDomainResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// WalkUpdateDomain - Updates the role instances in the specified update domain. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-09-04 +func (client *CloudServicesUpdateDomainClient) walkUpdateDomain(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, parameters UpdateDomain, options *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions) (*http.Response, error) { + var err error + const operationName = "CloudServicesUpdateDomainClient.BeginWalkUpdateDomain" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.walkUpdateDomainCreateRequest(ctx, resourceGroupName, cloudServiceName, updateDomain, 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 +} + +// walkUpdateDomainCreateRequest creates the WalkUpdateDomain request. +func (client *CloudServicesUpdateDomainClient) walkUpdateDomainCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, updateDomain int32, parameters UpdateDomain, options *CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/updateDomains/{updateDomain}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + urlPath = strings.ReplaceAll(urlPath, "{updateDomain}", url.PathEscape(strconv.FormatInt(int64(updateDomain), 10))) + 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", "2022-09-04") + 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/compute/armcompute/v5/communitygalleries_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleries_client.go new file mode 100644 index 000000000..2bfc798f3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleries_client.go @@ -0,0 +1,109 @@ +//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 armcompute + +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" +) + +// CommunityGalleriesClient contains the methods for the CommunityGalleries group. +// Don't use this type directly, use NewCommunityGalleriesClient() instead. +type CommunityGalleriesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCommunityGalleriesClient creates a new instance of CommunityGalleriesClient 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 NewCommunityGalleriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityGalleriesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CommunityGalleriesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a community gallery by gallery public name. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - publicGalleryName - The public name of the community gallery. +// - options - CommunityGalleriesClientGetOptions contains the optional parameters for the CommunityGalleriesClient.Get method. +func (client *CommunityGalleriesClient) Get(ctx context.Context, location string, publicGalleryName string, options *CommunityGalleriesClientGetOptions) (CommunityGalleriesClientGetResponse, error) { + var err error + const operationName = "CommunityGalleriesClient.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, location, publicGalleryName, options) + if err != nil { + return CommunityGalleriesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommunityGalleriesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CommunityGalleriesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CommunityGalleriesClient) getCreateRequest(ctx context.Context, location string, publicGalleryName string, options *CommunityGalleriesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}" + 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 publicGalleryName == "" { + return nil, errors.New("parameter publicGalleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CommunityGalleriesClient) getHandleResponse(resp *http.Response) (CommunityGalleriesClientGetResponse, error) { + result := CommunityGalleriesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGallery); err != nil { + return CommunityGalleriesClientGetResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleryimages_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleryimages_client.go new file mode 100644 index 000000000..25b118f07 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleryimages_client.go @@ -0,0 +1,180 @@ +//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 armcompute + +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" +) + +// CommunityGalleryImagesClient contains the methods for the CommunityGalleryImages group. +// Don't use this type directly, use NewCommunityGalleryImagesClient() instead. +type CommunityGalleryImagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCommunityGalleryImagesClient creates a new instance of CommunityGalleryImagesClient 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 NewCommunityGalleryImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityGalleryImagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CommunityGalleryImagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a community gallery image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - publicGalleryName - The public name of the community gallery. +// - galleryImageName - The name of the community gallery image definition. +// - options - CommunityGalleryImagesClientGetOptions contains the optional parameters for the CommunityGalleryImagesClient.Get +// method. +func (client *CommunityGalleryImagesClient) Get(ctx context.Context, location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImagesClientGetOptions) (CommunityGalleryImagesClientGetResponse, error) { + var err error + const operationName = "CommunityGalleryImagesClient.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, location, publicGalleryName, galleryImageName, options) + if err != nil { + return CommunityGalleryImagesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommunityGalleryImagesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CommunityGalleryImagesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CommunityGalleryImagesClient) getCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImagesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}" + 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 publicGalleryName == "" { + return nil, errors.New("parameter publicGalleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CommunityGalleryImagesClient) getHandleResponse(resp *http.Response) (CommunityGalleryImagesClientGetResponse, error) { + result := CommunityGalleryImagesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImage); err != nil { + return CommunityGalleryImagesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List community gallery images inside a gallery. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - publicGalleryName - The public name of the community gallery. +// - options - CommunityGalleryImagesClientListOptions contains the optional parameters for the CommunityGalleryImagesClient.NewListPager +// method. +func (client *CommunityGalleryImagesClient) NewListPager(location string, publicGalleryName string, options *CommunityGalleryImagesClientListOptions) *runtime.Pager[CommunityGalleryImagesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CommunityGalleryImagesClientListResponse]{ + More: func(page CommunityGalleryImagesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommunityGalleryImagesClientListResponse) (CommunityGalleryImagesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommunityGalleryImagesClient.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, location, publicGalleryName, options) + }, nil) + if err != nil { + return CommunityGalleryImagesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CommunityGalleryImagesClient) listCreateRequest(ctx context.Context, location string, publicGalleryName string, options *CommunityGalleryImagesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images" + 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 publicGalleryName == "" { + return nil, errors.New("parameter publicGalleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CommunityGalleryImagesClient) listHandleResponse(resp *http.Response) (CommunityGalleryImagesClientListResponse, error) { + result := CommunityGalleryImagesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageList); err != nil { + return CommunityGalleryImagesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleryimageversions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleryimageversions_client.go new file mode 100644 index 000000000..5e382b36d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/communitygalleryimageversions_client.go @@ -0,0 +1,192 @@ +//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 armcompute + +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" +) + +// CommunityGalleryImageVersionsClient contains the methods for the CommunityGalleryImageVersions group. +// Don't use this type directly, use NewCommunityGalleryImageVersionsClient() instead. +type CommunityGalleryImageVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCommunityGalleryImageVersionsClient creates a new instance of CommunityGalleryImageVersionsClient 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 NewCommunityGalleryImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityGalleryImageVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CommunityGalleryImageVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a community gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - publicGalleryName - The public name of the community gallery. +// - galleryImageName - The name of the community gallery image definition. +// - galleryImageVersionName - The name of the community gallery image version. Needs to follow semantic version name pattern: +// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer. +// Format: .. +// - options - CommunityGalleryImageVersionsClientGetOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.Get +// method. +func (client *CommunityGalleryImageVersionsClient) Get(ctx context.Context, location string, publicGalleryName string, galleryImageName string, galleryImageVersionName string, options *CommunityGalleryImageVersionsClientGetOptions) (CommunityGalleryImageVersionsClientGetResponse, error) { + var err error + const operationName = "CommunityGalleryImageVersionsClient.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, location, publicGalleryName, galleryImageName, galleryImageVersionName, options) + if err != nil { + return CommunityGalleryImageVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommunityGalleryImageVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CommunityGalleryImageVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CommunityGalleryImageVersionsClient) getCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, galleryImageVersionName string, options *CommunityGalleryImageVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}" + 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 publicGalleryName == "" { + return nil, errors.New("parameter publicGalleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + if galleryImageVersionName == "" { + return nil, errors.New("parameter galleryImageVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CommunityGalleryImageVersionsClient) getHandleResponse(resp *http.Response) (CommunityGalleryImageVersionsClientGetResponse, error) { + result := CommunityGalleryImageVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageVersion); err != nil { + return CommunityGalleryImageVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List community gallery image versions inside an image. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - publicGalleryName - The public name of the community gallery. +// - galleryImageName - The name of the community gallery image definition. +// - options - CommunityGalleryImageVersionsClientListOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.NewListPager +// method. +func (client *CommunityGalleryImageVersionsClient) NewListPager(location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImageVersionsClientListOptions) *runtime.Pager[CommunityGalleryImageVersionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CommunityGalleryImageVersionsClientListResponse]{ + More: func(page CommunityGalleryImageVersionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommunityGalleryImageVersionsClientListResponse) (CommunityGalleryImageVersionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommunityGalleryImageVersionsClient.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, location, publicGalleryName, galleryImageName, options) + }, nil) + if err != nil { + return CommunityGalleryImageVersionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CommunityGalleryImageVersionsClient) listCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImageVersionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}/versions" + 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 publicGalleryName == "" { + return nil, errors.New("parameter publicGalleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CommunityGalleryImageVersionsClient) listHandleResponse(resp *http.Response) (CommunityGalleryImageVersionsClientListResponse, error) { + result := CommunityGalleryImageVersionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageVersionList); err != nil { + return CommunityGalleryImageVersionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/constants.go new file mode 100644 index 000000000..d635d4f51 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/constants.go @@ -0,0 +1,2783 @@ +//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 armcompute + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute" + moduleVersion = "v5.4.0" +) + +type AccessLevel string + +const ( + AccessLevelNone AccessLevel = "None" + AccessLevelRead AccessLevel = "Read" + AccessLevelWrite AccessLevel = "Write" +) + +// PossibleAccessLevelValues returns the possible values for the AccessLevel const type. +func PossibleAccessLevelValues() []AccessLevel { + return []AccessLevel{ + AccessLevelNone, + AccessLevelRead, + AccessLevelWrite, + } +} + +// AggregatedReplicationState - This is the aggregated replication status based on all the regional replication status flags. +type AggregatedReplicationState string + +const ( + AggregatedReplicationStateCompleted AggregatedReplicationState = "Completed" + AggregatedReplicationStateFailed AggregatedReplicationState = "Failed" + AggregatedReplicationStateInProgress AggregatedReplicationState = "InProgress" + AggregatedReplicationStateUnknown AggregatedReplicationState = "Unknown" +) + +// PossibleAggregatedReplicationStateValues returns the possible values for the AggregatedReplicationState const type. +func PossibleAggregatedReplicationStateValues() []AggregatedReplicationState { + return []AggregatedReplicationState{ + AggregatedReplicationStateCompleted, + AggregatedReplicationStateFailed, + AggregatedReplicationStateInProgress, + AggregatedReplicationStateUnknown, + } +} + +// AlternativeType - Describes the type of the alternative option. +type AlternativeType string + +const ( + AlternativeTypeNone AlternativeType = "None" + AlternativeTypeOffer AlternativeType = "Offer" + AlternativeTypePlan AlternativeType = "Plan" +) + +// PossibleAlternativeTypeValues returns the possible values for the AlternativeType const type. +func PossibleAlternativeTypeValues() []AlternativeType { + return []AlternativeType{ + AlternativeTypeNone, + AlternativeTypeOffer, + AlternativeTypePlan, + } +} + +// Architecture - The architecture of the image. Applicable to OS disks only. +type Architecture string + +const ( + ArchitectureArm64 Architecture = "Arm64" + ArchitectureX64 Architecture = "x64" +) + +// PossibleArchitectureValues returns the possible values for the Architecture const type. +func PossibleArchitectureValues() []Architecture { + return []Architecture{ + ArchitectureArm64, + ArchitectureX64, + } +} + +// ArchitectureTypes - Specifies the Architecture Type +type ArchitectureTypes string + +const ( + ArchitectureTypesArm64 ArchitectureTypes = "Arm64" + ArchitectureTypesX64 ArchitectureTypes = "x64" +) + +// PossibleArchitectureTypesValues returns the possible values for the ArchitectureTypes const type. +func PossibleArchitectureTypesValues() []ArchitectureTypes { + return []ArchitectureTypes{ + ArchitectureTypesArm64, + ArchitectureTypesX64, + } +} + +// AvailabilitySetSKUTypes - Specifies the sku of an Availability Set. Use 'Aligned' for virtual machines with managed disks +// and 'Classic' for virtual machines with unmanaged disks. Default value is 'Classic'. +type AvailabilitySetSKUTypes string + +const ( + AvailabilitySetSKUTypesAligned AvailabilitySetSKUTypes = "Aligned" + AvailabilitySetSKUTypesClassic AvailabilitySetSKUTypes = "Classic" +) + +// PossibleAvailabilitySetSKUTypesValues returns the possible values for the AvailabilitySetSKUTypes const type. +func PossibleAvailabilitySetSKUTypesValues() []AvailabilitySetSKUTypes { + return []AvailabilitySetSKUTypes{ + AvailabilitySetSKUTypesAligned, + AvailabilitySetSKUTypesClassic, + } +} + +// CachingTypes - Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default values are: +// None for Standard storage. ReadOnly for Premium storage +type CachingTypes string + +const ( + CachingTypesNone CachingTypes = "None" + CachingTypesReadOnly CachingTypes = "ReadOnly" + CachingTypesReadWrite CachingTypes = "ReadWrite" +) + +// PossibleCachingTypesValues returns the possible values for the CachingTypes const type. +func PossibleCachingTypesValues() []CachingTypes { + return []CachingTypes{ + CachingTypesNone, + CachingTypesReadOnly, + CachingTypesReadWrite, + } +} + +type CapacityReservationGroupInstanceViewTypes string + +const ( + CapacityReservationGroupInstanceViewTypesInstanceView CapacityReservationGroupInstanceViewTypes = "instanceView" +) + +// PossibleCapacityReservationGroupInstanceViewTypesValues returns the possible values for the CapacityReservationGroupInstanceViewTypes const type. +func PossibleCapacityReservationGroupInstanceViewTypesValues() []CapacityReservationGroupInstanceViewTypes { + return []CapacityReservationGroupInstanceViewTypes{ + CapacityReservationGroupInstanceViewTypesInstanceView, + } +} + +type CapacityReservationInstanceViewTypes string + +const ( + CapacityReservationInstanceViewTypesInstanceView CapacityReservationInstanceViewTypes = "instanceView" +) + +// PossibleCapacityReservationInstanceViewTypesValues returns the possible values for the CapacityReservationInstanceViewTypes const type. +func PossibleCapacityReservationInstanceViewTypesValues() []CapacityReservationInstanceViewTypes { + return []CapacityReservationInstanceViewTypes{ + CapacityReservationInstanceViewTypesInstanceView, + } +} + +// CloudServiceSlotType - Slot type for the cloud service. Possible values are +// Production +// Staging +// If not specified, the default value is Production. +type CloudServiceSlotType string + +const ( + CloudServiceSlotTypeProduction CloudServiceSlotType = "Production" + CloudServiceSlotTypeStaging CloudServiceSlotType = "Staging" +) + +// PossibleCloudServiceSlotTypeValues returns the possible values for the CloudServiceSlotType const type. +func PossibleCloudServiceSlotTypeValues() []CloudServiceSlotType { + return []CloudServiceSlotType{ + CloudServiceSlotTypeProduction, + CloudServiceSlotTypeStaging, + } +} + +// CloudServiceUpgradeMode - Update mode for the cloud service. Role instances are allocated to update domains when the service +// is deployed. Updates can be initiated manually in each update domain or initiated automatically in +// all update domains. Possible Values are +// Auto +// Manual +// Simultaneous +// If not specified, the default value is Auto. If set to Manual, PUT UpdateDomain must be called to apply the update. If +// set to Auto, the update is automatically applied to each update domain in +// sequence. +type CloudServiceUpgradeMode string + +const ( + CloudServiceUpgradeModeAuto CloudServiceUpgradeMode = "Auto" + CloudServiceUpgradeModeManual CloudServiceUpgradeMode = "Manual" + CloudServiceUpgradeModeSimultaneous CloudServiceUpgradeMode = "Simultaneous" +) + +// PossibleCloudServiceUpgradeModeValues returns the possible values for the CloudServiceUpgradeMode const type. +func PossibleCloudServiceUpgradeModeValues() []CloudServiceUpgradeMode { + return []CloudServiceUpgradeMode{ + CloudServiceUpgradeModeAuto, + CloudServiceUpgradeModeManual, + CloudServiceUpgradeModeSimultaneous, + } +} + +// ConfidentialVMEncryptionType - confidential VM encryption types +type ConfidentialVMEncryptionType string + +const ( + ConfidentialVMEncryptionTypeEncryptedVMGuestStateOnlyWithPmk ConfidentialVMEncryptionType = "EncryptedVMGuestStateOnlyWithPmk" + ConfidentialVMEncryptionTypeEncryptedWithCmk ConfidentialVMEncryptionType = "EncryptedWithCmk" + ConfidentialVMEncryptionTypeEncryptedWithPmk ConfidentialVMEncryptionType = "EncryptedWithPmk" + ConfidentialVMEncryptionTypeNonPersistedTPM ConfidentialVMEncryptionType = "NonPersistedTPM" +) + +// PossibleConfidentialVMEncryptionTypeValues returns the possible values for the ConfidentialVMEncryptionType const type. +func PossibleConfidentialVMEncryptionTypeValues() []ConfidentialVMEncryptionType { + return []ConfidentialVMEncryptionType{ + ConfidentialVMEncryptionTypeEncryptedVMGuestStateOnlyWithPmk, + ConfidentialVMEncryptionTypeEncryptedWithCmk, + ConfidentialVMEncryptionTypeEncryptedWithPmk, + ConfidentialVMEncryptionTypeNonPersistedTPM, + } +} + +// ConsistencyModeTypes - ConsistencyMode of the RestorePoint. Can be specified in the input while creating a restore point. +// For now, only CrashConsistent is accepted as a valid input. Please refer to +// https://aka.ms/RestorePoints for more details. +type ConsistencyModeTypes string + +const ( + ConsistencyModeTypesApplicationConsistent ConsistencyModeTypes = "ApplicationConsistent" + ConsistencyModeTypesCrashConsistent ConsistencyModeTypes = "CrashConsistent" + ConsistencyModeTypesFileSystemConsistent ConsistencyModeTypes = "FileSystemConsistent" +) + +// PossibleConsistencyModeTypesValues returns the possible values for the ConsistencyModeTypes const type. +func PossibleConsistencyModeTypesValues() []ConsistencyModeTypes { + return []ConsistencyModeTypes{ + ConsistencyModeTypesApplicationConsistent, + ConsistencyModeTypesCrashConsistent, + ConsistencyModeTypesFileSystemConsistent, + } +} + +// CopyCompletionErrorReason - Indicates the error code if the background copy of a resource created via the CopyStart operation +// fails. +type CopyCompletionErrorReason string + +const ( + // CopyCompletionErrorReasonCopySourceNotFound - Indicates that the source snapshot was deleted while the background copy + // of the resource created via CopyStart operation was in progress. + CopyCompletionErrorReasonCopySourceNotFound CopyCompletionErrorReason = "CopySourceNotFound" +) + +// PossibleCopyCompletionErrorReasonValues returns the possible values for the CopyCompletionErrorReason const type. +func PossibleCopyCompletionErrorReasonValues() []CopyCompletionErrorReason { + return []CopyCompletionErrorReason{ + CopyCompletionErrorReasonCopySourceNotFound, + } +} + +// DataAccessAuthMode - Additional authentication requirements when exporting or uploading to a disk or snapshot. +type DataAccessAuthMode string + +const ( + // DataAccessAuthModeAzureActiveDirectory - When export/upload URL is used, the system checks if the user has an identity + // in Azure Active Directory and has necessary permissions to export/upload the data. Please refer to aka.ms/DisksAzureADAuth. + DataAccessAuthModeAzureActiveDirectory DataAccessAuthMode = "AzureActiveDirectory" + // DataAccessAuthModeNone - No additional authentication would be performed when accessing export/upload URL. + DataAccessAuthModeNone DataAccessAuthMode = "None" +) + +// PossibleDataAccessAuthModeValues returns the possible values for the DataAccessAuthMode const type. +func PossibleDataAccessAuthModeValues() []DataAccessAuthMode { + return []DataAccessAuthMode{ + DataAccessAuthModeAzureActiveDirectory, + DataAccessAuthModeNone, + } +} + +// DedicatedHostLicenseTypes - Specifies the software license type that will be applied to the VMs deployed on the dedicated +// host. Possible values are: None, WindowsServerHybrid, WindowsServerPerpetual. The default value is: None. +type DedicatedHostLicenseTypes string + +const ( + DedicatedHostLicenseTypesNone DedicatedHostLicenseTypes = "None" + DedicatedHostLicenseTypesWindowsServerHybrid DedicatedHostLicenseTypes = "Windows_Server_Hybrid" + DedicatedHostLicenseTypesWindowsServerPerpetual DedicatedHostLicenseTypes = "Windows_Server_Perpetual" +) + +// PossibleDedicatedHostLicenseTypesValues returns the possible values for the DedicatedHostLicenseTypes const type. +func PossibleDedicatedHostLicenseTypesValues() []DedicatedHostLicenseTypes { + return []DedicatedHostLicenseTypes{ + DedicatedHostLicenseTypesNone, + DedicatedHostLicenseTypesWindowsServerHybrid, + DedicatedHostLicenseTypesWindowsServerPerpetual, + } +} + +// DeleteOptions - Specify what happens to the network interface when the VM is deleted +type DeleteOptions string + +const ( + DeleteOptionsDelete DeleteOptions = "Delete" + DeleteOptionsDetach DeleteOptions = "Detach" +) + +// PossibleDeleteOptionsValues returns the possible values for the DeleteOptions const type. +func PossibleDeleteOptionsValues() []DeleteOptions { + return []DeleteOptions{ + DeleteOptionsDelete, + DeleteOptionsDetach, + } +} + +// DiffDiskOptions - Specifies the ephemeral disk option for operating system disk. +type DiffDiskOptions string + +const ( + DiffDiskOptionsLocal DiffDiskOptions = "Local" +) + +// PossibleDiffDiskOptionsValues returns the possible values for the DiffDiskOptions const type. +func PossibleDiffDiskOptionsValues() []DiffDiskOptions { + return []DiffDiskOptions{ + DiffDiskOptionsLocal, + } +} + +// DiffDiskPlacement - Specifies the ephemeral disk placement for operating system disk. This property can be used by user +// in the request to choose the location i.e, cache disk or resource disk space for Ephemeral OS disk +// provisioning. For more information on Ephemeral OS disk size requirements, please refer Ephemeral OS disk size requirements +// for Windows VM at +// https://docs.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VM at +// https://docs.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements +type DiffDiskPlacement string + +const ( + DiffDiskPlacementCacheDisk DiffDiskPlacement = "CacheDisk" + DiffDiskPlacementResourceDisk DiffDiskPlacement = "ResourceDisk" +) + +// PossibleDiffDiskPlacementValues returns the possible values for the DiffDiskPlacement const type. +func PossibleDiffDiskPlacementValues() []DiffDiskPlacement { + return []DiffDiskPlacement{ + DiffDiskPlacementCacheDisk, + DiffDiskPlacementResourceDisk, + } +} + +// DiskControllerTypes - Specifies the disk controller type configured for the VM and VirtualMachineScaleSet. This property +// is only supported for virtual machines whose operating system disk and VM sku supports Generation 2 +// (https://docs.microsoft.com/en-us/azure/virtual-machines/generation-2), please check the HyperVGenerations capability returned +// as part of VM sku capabilities in the response of Microsoft.Compute SKUs +// api for the region contains V2 (https://docs.microsoft.com/rest/api/compute/resourceskus/list). For more information about +// Disk Controller Types supported please refer to +// https://aka.ms/azure-diskcontrollertypes. +type DiskControllerTypes string + +const ( + DiskControllerTypesNVMe DiskControllerTypes = "NVMe" + DiskControllerTypesSCSI DiskControllerTypes = "SCSI" +) + +// PossibleDiskControllerTypesValues returns the possible values for the DiskControllerTypes const type. +func PossibleDiskControllerTypesValues() []DiskControllerTypes { + return []DiskControllerTypes{ + DiskControllerTypesNVMe, + DiskControllerTypesSCSI, + } +} + +// DiskCreateOption - This enumerates the possible sources of a disk's creation. +type DiskCreateOption string + +const ( + // DiskCreateOptionAttach - Disk will be attached to a VM. + DiskCreateOptionAttach DiskCreateOption = "Attach" + // DiskCreateOptionCopy - Create a new disk or snapshot by copying from a disk or snapshot specified by the given sourceResourceId. + DiskCreateOptionCopy DiskCreateOption = "Copy" + // DiskCreateOptionCopyFromSanSnapshot - Create a new disk by exporting from elastic san volume snapshot + DiskCreateOptionCopyFromSanSnapshot DiskCreateOption = "CopyFromSanSnapshot" + // DiskCreateOptionCopyStart - Create a new disk by using a deep copy process, where the resource creation is considered complete + // only after all data has been copied from the source. + DiskCreateOptionCopyStart DiskCreateOption = "CopyStart" + // DiskCreateOptionEmpty - Create an empty data disk of a size given by diskSizeGB. + DiskCreateOptionEmpty DiskCreateOption = "Empty" + // DiskCreateOptionFromImage - Create a new disk from a platform image specified by the given imageReference or galleryImageReference. + DiskCreateOptionFromImage DiskCreateOption = "FromImage" + // DiskCreateOptionImport - Create a disk by importing from a blob specified by a sourceUri in a storage account specified + // by storageAccountId. + DiskCreateOptionImport DiskCreateOption = "Import" + // DiskCreateOptionImportSecure - Similar to Import create option. Create a new Trusted Launch VM or Confidential VM supported + // disk by importing additional blob for VM guest state specified by securityDataUri in storage account specified by storageAccountId + DiskCreateOptionImportSecure DiskCreateOption = "ImportSecure" + // DiskCreateOptionRestore - Create a new disk by copying from a backup recovery point. + DiskCreateOptionRestore DiskCreateOption = "Restore" + // DiskCreateOptionUpload - Create a new disk by obtaining a write token and using it to directly upload the contents of the + // disk. + DiskCreateOptionUpload DiskCreateOption = "Upload" + // DiskCreateOptionUploadPreparedSecure - Similar to Upload create option. Create a new Trusted Launch VM or Confidential + // VM supported disk and upload using write token in both disk and VM guest state + DiskCreateOptionUploadPreparedSecure DiskCreateOption = "UploadPreparedSecure" +) + +// PossibleDiskCreateOptionValues returns the possible values for the DiskCreateOption const type. +func PossibleDiskCreateOptionValues() []DiskCreateOption { + return []DiskCreateOption{ + DiskCreateOptionAttach, + DiskCreateOptionCopy, + DiskCreateOptionCopyFromSanSnapshot, + DiskCreateOptionCopyStart, + DiskCreateOptionEmpty, + DiskCreateOptionFromImage, + DiskCreateOptionImport, + DiskCreateOptionImportSecure, + DiskCreateOptionRestore, + DiskCreateOptionUpload, + DiskCreateOptionUploadPreparedSecure, + } +} + +// DiskCreateOptionTypes - Specifies how the virtual machine should be created. Possible values are: Attach. This value is +// used when you are using a specialized disk to create the virtual machine. FromImage. This value is used +// when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference +// element described above. If you are using a marketplace image, you also +// use the plan element previously described. +type DiskCreateOptionTypes string + +const ( + DiskCreateOptionTypesAttach DiskCreateOptionTypes = "Attach" + DiskCreateOptionTypesEmpty DiskCreateOptionTypes = "Empty" + DiskCreateOptionTypesFromImage DiskCreateOptionTypes = "FromImage" +) + +// PossibleDiskCreateOptionTypesValues returns the possible values for the DiskCreateOptionTypes const type. +func PossibleDiskCreateOptionTypesValues() []DiskCreateOptionTypes { + return []DiskCreateOptionTypes{ + DiskCreateOptionTypesAttach, + DiskCreateOptionTypesEmpty, + DiskCreateOptionTypesFromImage, + } +} + +// DiskDeleteOptionTypes - Specifies the behavior of the managed disk when the VM gets deleted, for example whether the managed +// disk is deleted or detached. Supported values are: Delete. If this value is used, the managed disk +// is deleted when VM gets deleted. Detach. If this value is used, the managed disk is retained after VM gets deleted. Minimum +// api-version: 2021-03-01. +type DiskDeleteOptionTypes string + +const ( + DiskDeleteOptionTypesDelete DiskDeleteOptionTypes = "Delete" + DiskDeleteOptionTypesDetach DiskDeleteOptionTypes = "Detach" +) + +// PossibleDiskDeleteOptionTypesValues returns the possible values for the DiskDeleteOptionTypes const type. +func PossibleDiskDeleteOptionTypesValues() []DiskDeleteOptionTypes { + return []DiskDeleteOptionTypes{ + DiskDeleteOptionTypesDelete, + DiskDeleteOptionTypesDetach, + } +} + +// DiskDetachOptionTypes - Specifies the detach behavior to be used while detaching a disk or which is already in the process +// of detachment from the virtual machine. Supported values are: ForceDetach. detachOption: ForceDetach +// is applicable only for managed data disks. If a previous detachment attempt of the data disk did not complete due to an +// unexpected failure from the virtual machine and the disk is still not released +// then use force-detach as a last resort option to detach the disk forcibly from the VM. All writes might not have been flushed +// when using this detach behavior. This feature is still in preview mode and +// is not supported for VirtualMachineScaleSet. To force-detach a data disk update toBeDetached to 'true' along with setting +// detachOption: 'ForceDetach'. +type DiskDetachOptionTypes string + +const ( + DiskDetachOptionTypesForceDetach DiskDetachOptionTypes = "ForceDetach" +) + +// PossibleDiskDetachOptionTypesValues returns the possible values for the DiskDetachOptionTypes const type. +func PossibleDiskDetachOptionTypesValues() []DiskDetachOptionTypes { + return []DiskDetachOptionTypes{ + DiskDetachOptionTypesForceDetach, + } +} + +// DiskEncryptionSetIdentityType - The type of Managed Identity used by the DiskEncryptionSet. Only SystemAssigned is supported +// for new creations. Disk Encryption Sets can be updated with Identity type None during migration of +// subscription to a new Azure Active Directory tenant; it will cause the encrypted resources to lose access to the keys. +type DiskEncryptionSetIdentityType string + +const ( + DiskEncryptionSetIdentityTypeNone DiskEncryptionSetIdentityType = "None" + DiskEncryptionSetIdentityTypeSystemAssigned DiskEncryptionSetIdentityType = "SystemAssigned" + DiskEncryptionSetIdentityTypeSystemAssignedUserAssigned DiskEncryptionSetIdentityType = "SystemAssigned, UserAssigned" + DiskEncryptionSetIdentityTypeUserAssigned DiskEncryptionSetIdentityType = "UserAssigned" +) + +// PossibleDiskEncryptionSetIdentityTypeValues returns the possible values for the DiskEncryptionSetIdentityType const type. +func PossibleDiskEncryptionSetIdentityTypeValues() []DiskEncryptionSetIdentityType { + return []DiskEncryptionSetIdentityType{ + DiskEncryptionSetIdentityTypeNone, + DiskEncryptionSetIdentityTypeSystemAssigned, + DiskEncryptionSetIdentityTypeSystemAssignedUserAssigned, + DiskEncryptionSetIdentityTypeUserAssigned, + } +} + +// DiskEncryptionSetType - The type of key used to encrypt the data of the disk. +type DiskEncryptionSetType string + +const ( + // DiskEncryptionSetTypeConfidentialVMEncryptedWithCustomerKey - Confidential VM supported disk and VM guest state would be + // encrypted with customer managed key. + DiskEncryptionSetTypeConfidentialVMEncryptedWithCustomerKey DiskEncryptionSetType = "ConfidentialVmEncryptedWithCustomerKey" + // DiskEncryptionSetTypeEncryptionAtRestWithCustomerKey - Resource using diskEncryptionSet would be encrypted at rest with + // Customer managed key that can be changed and revoked by a customer. + DiskEncryptionSetTypeEncryptionAtRestWithCustomerKey DiskEncryptionSetType = "EncryptionAtRestWithCustomerKey" + // DiskEncryptionSetTypeEncryptionAtRestWithPlatformAndCustomerKeys - Resource using diskEncryptionSet would be encrypted + // at rest with two layers of encryption. One of the keys is Customer managed and the other key is Platform managed. + DiskEncryptionSetTypeEncryptionAtRestWithPlatformAndCustomerKeys DiskEncryptionSetType = "EncryptionAtRestWithPlatformAndCustomerKeys" +) + +// PossibleDiskEncryptionSetTypeValues returns the possible values for the DiskEncryptionSetType const type. +func PossibleDiskEncryptionSetTypeValues() []DiskEncryptionSetType { + return []DiskEncryptionSetType{ + DiskEncryptionSetTypeConfidentialVMEncryptedWithCustomerKey, + DiskEncryptionSetTypeEncryptionAtRestWithCustomerKey, + DiskEncryptionSetTypeEncryptionAtRestWithPlatformAndCustomerKeys, + } +} + +// DiskSecurityTypes - Specifies the SecurityType of the VM. Applicable for OS disks only. +type DiskSecurityTypes string + +const ( + // DiskSecurityTypesConfidentialVMDiskEncryptedWithCustomerKey - Indicates Confidential VM disk with both OS disk and VM guest + // state encrypted with a customer managed key + DiskSecurityTypesConfidentialVMDiskEncryptedWithCustomerKey DiskSecurityTypes = "ConfidentialVM_DiskEncryptedWithCustomerKey" + // DiskSecurityTypesConfidentialVMDiskEncryptedWithPlatformKey - Indicates Confidential VM disk with both OS disk and VM guest + // state encrypted with a platform managed key + DiskSecurityTypesConfidentialVMDiskEncryptedWithPlatformKey DiskSecurityTypes = "ConfidentialVM_DiskEncryptedWithPlatformKey" + // DiskSecurityTypesConfidentialVMVmguestStateOnlyEncryptedWithPlatformKey - Indicates Confidential VM disk with only VM guest + // state encrypted + DiskSecurityTypesConfidentialVMVmguestStateOnlyEncryptedWithPlatformKey DiskSecurityTypes = "ConfidentialVM_VMGuestStateOnlyEncryptedWithPlatformKey" + // DiskSecurityTypesTrustedLaunch - Trusted Launch provides security features such as secure boot and virtual Trusted Platform + // Module (vTPM) + DiskSecurityTypesTrustedLaunch DiskSecurityTypes = "TrustedLaunch" +) + +// PossibleDiskSecurityTypesValues returns the possible values for the DiskSecurityTypes const type. +func PossibleDiskSecurityTypesValues() []DiskSecurityTypes { + return []DiskSecurityTypes{ + DiskSecurityTypesConfidentialVMDiskEncryptedWithCustomerKey, + DiskSecurityTypesConfidentialVMDiskEncryptedWithPlatformKey, + DiskSecurityTypesConfidentialVMVmguestStateOnlyEncryptedWithPlatformKey, + DiskSecurityTypesTrustedLaunch, + } +} + +// DiskState - This enumerates the possible state of the disk. +type DiskState string + +const ( + // DiskStateActiveSAS - The disk currently has an Active SAS Uri associated with it. + DiskStateActiveSAS DiskState = "ActiveSAS" + // DiskStateActiveSASFrozen - The disk is attached to a VM in hibernated state and has an active SAS URI associated with it. + DiskStateActiveSASFrozen DiskState = "ActiveSASFrozen" + // DiskStateActiveUpload - A disk is created for upload and a write token has been issued for uploading to it. + DiskStateActiveUpload DiskState = "ActiveUpload" + // DiskStateAttached - The disk is currently attached to a running VM. + DiskStateAttached DiskState = "Attached" + // DiskStateFrozen - The disk is attached to a VM which is in hibernated state. + DiskStateFrozen DiskState = "Frozen" + // DiskStateReadyToUpload - A disk is ready to be created by upload by requesting a write token. + DiskStateReadyToUpload DiskState = "ReadyToUpload" + // DiskStateReserved - The disk is attached to a stopped-deallocated VM. + DiskStateReserved DiskState = "Reserved" + // DiskStateUnattached - The disk is not being used and can be attached to a VM. + DiskStateUnattached DiskState = "Unattached" +) + +// PossibleDiskStateValues returns the possible values for the DiskState const type. +func PossibleDiskStateValues() []DiskState { + return []DiskState{ + DiskStateActiveSAS, + DiskStateActiveSASFrozen, + DiskStateActiveUpload, + DiskStateAttached, + DiskStateFrozen, + DiskStateReadyToUpload, + DiskStateReserved, + DiskStateUnattached, + } +} + +// DiskStorageAccountTypes - The sku name. +type DiskStorageAccountTypes string + +const ( + // DiskStorageAccountTypesPremiumLRS - Premium SSD locally redundant storage. Best for production and performance sensitive + // workloads. + DiskStorageAccountTypesPremiumLRS DiskStorageAccountTypes = "Premium_LRS" + // DiskStorageAccountTypesPremiumV2LRS - Premium SSD v2 locally redundant storage. Best for production and performance-sensitive + // workloads that consistently require low latency and high IOPS and throughput. + DiskStorageAccountTypesPremiumV2LRS DiskStorageAccountTypes = "PremiumV2_LRS" + // DiskStorageAccountTypesPremiumZRS - Premium SSD zone redundant storage. Best for the production workloads that need storage + // resiliency against zone failures. + DiskStorageAccountTypesPremiumZRS DiskStorageAccountTypes = "Premium_ZRS" + // DiskStorageAccountTypesStandardLRS - Standard HDD locally redundant storage. Best for backup, non-critical, and infrequent + // access. + DiskStorageAccountTypesStandardLRS DiskStorageAccountTypes = "Standard_LRS" + // DiskStorageAccountTypesStandardSSDLRS - Standard SSD locally redundant storage. Best for web servers, lightly used enterprise + // applications and dev/test. + DiskStorageAccountTypesStandardSSDLRS DiskStorageAccountTypes = "StandardSSD_LRS" + // DiskStorageAccountTypesStandardSSDZRS - Standard SSD zone redundant storage. Best for web servers, lightly used enterprise + // applications and dev/test that need storage resiliency against zone failures. + DiskStorageAccountTypesStandardSSDZRS DiskStorageAccountTypes = "StandardSSD_ZRS" + // DiskStorageAccountTypesUltraSSDLRS - Ultra SSD locally redundant storage. Best for IO-intensive workloads such as SAP HANA, + // top tier databases (for example, SQL, Oracle), and other transaction-heavy workloads. + DiskStorageAccountTypesUltraSSDLRS DiskStorageAccountTypes = "UltraSSD_LRS" +) + +// PossibleDiskStorageAccountTypesValues returns the possible values for the DiskStorageAccountTypes const type. +func PossibleDiskStorageAccountTypesValues() []DiskStorageAccountTypes { + return []DiskStorageAccountTypes{ + DiskStorageAccountTypesPremiumLRS, + DiskStorageAccountTypesPremiumV2LRS, + DiskStorageAccountTypesPremiumZRS, + DiskStorageAccountTypesStandardLRS, + DiskStorageAccountTypesStandardSSDLRS, + DiskStorageAccountTypesStandardSSDZRS, + DiskStorageAccountTypesUltraSSDLRS, + } +} + +// DomainNameLabelScopeTypes - The Domain name label scope.The concatenation of the hashed domain name label that generated +// according to the policy from domain name label scope and vm index will be the domain name labels of the +// PublicIPAddress resources that will be created +type DomainNameLabelScopeTypes string + +const ( + DomainNameLabelScopeTypesNoReuse DomainNameLabelScopeTypes = "NoReuse" + DomainNameLabelScopeTypesResourceGroupReuse DomainNameLabelScopeTypes = "ResourceGroupReuse" + DomainNameLabelScopeTypesSubscriptionReuse DomainNameLabelScopeTypes = "SubscriptionReuse" + DomainNameLabelScopeTypesTenantReuse DomainNameLabelScopeTypes = "TenantReuse" +) + +// PossibleDomainNameLabelScopeTypesValues returns the possible values for the DomainNameLabelScopeTypes const type. +func PossibleDomainNameLabelScopeTypesValues() []DomainNameLabelScopeTypes { + return []DomainNameLabelScopeTypes{ + DomainNameLabelScopeTypesNoReuse, + DomainNameLabelScopeTypesResourceGroupReuse, + DomainNameLabelScopeTypesSubscriptionReuse, + DomainNameLabelScopeTypesTenantReuse, + } +} + +// EdgeZoneStorageAccountType - Specifies the storage account type to be used to store the image. This property is not updatable. +type EdgeZoneStorageAccountType string + +const ( + EdgeZoneStorageAccountTypePremiumLRS EdgeZoneStorageAccountType = "Premium_LRS" + EdgeZoneStorageAccountTypeStandardLRS EdgeZoneStorageAccountType = "Standard_LRS" + EdgeZoneStorageAccountTypeStandardSSDLRS EdgeZoneStorageAccountType = "StandardSSD_LRS" + EdgeZoneStorageAccountTypeStandardZRS EdgeZoneStorageAccountType = "Standard_ZRS" +) + +// PossibleEdgeZoneStorageAccountTypeValues returns the possible values for the EdgeZoneStorageAccountType const type. +func PossibleEdgeZoneStorageAccountTypeValues() []EdgeZoneStorageAccountType { + return []EdgeZoneStorageAccountType{ + EdgeZoneStorageAccountTypePremiumLRS, + EdgeZoneStorageAccountTypeStandardLRS, + EdgeZoneStorageAccountTypeStandardSSDLRS, + EdgeZoneStorageAccountTypeStandardZRS, + } +} + +// EncryptionType - The type of key used to encrypt the data of the disk. +type EncryptionType string + +const ( + // EncryptionTypeEncryptionAtRestWithCustomerKey - Disk is encrypted at rest with Customer managed key that can be changed + // and revoked by a customer. + EncryptionTypeEncryptionAtRestWithCustomerKey EncryptionType = "EncryptionAtRestWithCustomerKey" + // EncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys - Disk is encrypted at rest with 2 layers of encryption. One + // of the keys is Customer managed and the other key is Platform managed. + EncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys EncryptionType = "EncryptionAtRestWithPlatformAndCustomerKeys" + // EncryptionTypeEncryptionAtRestWithPlatformKey - Disk is encrypted at rest with Platform managed key. It is the default + // encryption type. This is not a valid encryption type for disk encryption sets. + EncryptionTypeEncryptionAtRestWithPlatformKey EncryptionType = "EncryptionAtRestWithPlatformKey" +) + +// PossibleEncryptionTypeValues returns the possible values for the EncryptionType const type. +func PossibleEncryptionTypeValues() []EncryptionType { + return []EncryptionType{ + EncryptionTypeEncryptionAtRestWithCustomerKey, + EncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys, + EncryptionTypeEncryptionAtRestWithPlatformKey, + } +} + +// ExecutionState - Script execution status. +type ExecutionState string + +const ( + ExecutionStateCanceled ExecutionState = "Canceled" + ExecutionStateFailed ExecutionState = "Failed" + ExecutionStatePending ExecutionState = "Pending" + ExecutionStateRunning ExecutionState = "Running" + ExecutionStateSucceeded ExecutionState = "Succeeded" + ExecutionStateTimedOut ExecutionState = "TimedOut" + ExecutionStateUnknown ExecutionState = "Unknown" +) + +// PossibleExecutionStateValues returns the possible values for the ExecutionState const type. +func PossibleExecutionStateValues() []ExecutionState { + return []ExecutionState{ + ExecutionStateCanceled, + ExecutionStateFailed, + ExecutionStatePending, + ExecutionStateRunning, + ExecutionStateSucceeded, + ExecutionStateTimedOut, + ExecutionStateUnknown, + } +} + +type ExpandTypeForListVMs string + +const ( + ExpandTypeForListVMsInstanceView ExpandTypeForListVMs = "instanceView" +) + +// PossibleExpandTypeForListVMsValues returns the possible values for the ExpandTypeForListVMs const type. +func PossibleExpandTypeForListVMsValues() []ExpandTypeForListVMs { + return []ExpandTypeForListVMs{ + ExpandTypeForListVMsInstanceView, + } +} + +type ExpandTypesForGetCapacityReservationGroups string + +const ( + ExpandTypesForGetCapacityReservationGroupsVirtualMachineScaleSetVMsRef ExpandTypesForGetCapacityReservationGroups = "virtualMachineScaleSetVMs/$ref" + ExpandTypesForGetCapacityReservationGroupsVirtualMachinesRef ExpandTypesForGetCapacityReservationGroups = "virtualMachines/$ref" +) + +// PossibleExpandTypesForGetCapacityReservationGroupsValues returns the possible values for the ExpandTypesForGetCapacityReservationGroups const type. +func PossibleExpandTypesForGetCapacityReservationGroupsValues() []ExpandTypesForGetCapacityReservationGroups { + return []ExpandTypesForGetCapacityReservationGroups{ + ExpandTypesForGetCapacityReservationGroupsVirtualMachineScaleSetVMsRef, + ExpandTypesForGetCapacityReservationGroupsVirtualMachinesRef, + } +} + +type ExpandTypesForGetVMScaleSets string + +const ( + ExpandTypesForGetVMScaleSetsUserData ExpandTypesForGetVMScaleSets = "userData" +) + +// PossibleExpandTypesForGetVMScaleSetsValues returns the possible values for the ExpandTypesForGetVMScaleSets const type. +func PossibleExpandTypesForGetVMScaleSetsValues() []ExpandTypesForGetVMScaleSets { + return []ExpandTypesForGetVMScaleSets{ + ExpandTypesForGetVMScaleSetsUserData, + } +} + +type ExpandTypesForListVMs string + +const ( + ExpandTypesForListVMsInstanceView ExpandTypesForListVMs = "instanceView" +) + +// PossibleExpandTypesForListVMsValues returns the possible values for the ExpandTypesForListVMs const type. +func PossibleExpandTypesForListVMsValues() []ExpandTypesForListVMs { + return []ExpandTypesForListVMs{ + ExpandTypesForListVMsInstanceView, + } +} + +// ExtendedLocationType - The type of the extended location. +type ExtendedLocationType string + +const ( + ExtendedLocationTypeEdgeZone ExtendedLocationType = "EdgeZone" +) + +// PossibleExtendedLocationTypeValues returns the possible values for the ExtendedLocationType const type. +func PossibleExtendedLocationTypeValues() []ExtendedLocationType { + return []ExtendedLocationType{ + ExtendedLocationTypeEdgeZone, + } +} + +// 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, + } +} + +// FileFormat - Used to specify the file format when making request for SAS on a VHDX file format snapshot +type FileFormat string + +const ( + // FileFormatVHD - A VHD file is a disk image file in the Virtual Hard Disk file format. + FileFormatVHD FileFormat = "VHD" + // FileFormatVHDX - A VHDX file is a disk image file in the Virtual Hard Disk v2 file format. + FileFormatVHDX FileFormat = "VHDX" +) + +// PossibleFileFormatValues returns the possible values for the FileFormat const type. +func PossibleFileFormatValues() []FileFormat { + return []FileFormat{ + FileFormatVHD, + FileFormatVHDX, + } +} + +// GalleryApplicationCustomActionParameterType - Specifies the type of the custom action parameter. Possible values are: String, +// ConfigurationDataBlob or LogOutputBlob +type GalleryApplicationCustomActionParameterType string + +const ( + GalleryApplicationCustomActionParameterTypeConfigurationDataBlob GalleryApplicationCustomActionParameterType = "ConfigurationDataBlob" + GalleryApplicationCustomActionParameterTypeLogOutputBlob GalleryApplicationCustomActionParameterType = "LogOutputBlob" + GalleryApplicationCustomActionParameterTypeString GalleryApplicationCustomActionParameterType = "String" +) + +// PossibleGalleryApplicationCustomActionParameterTypeValues returns the possible values for the GalleryApplicationCustomActionParameterType const type. +func PossibleGalleryApplicationCustomActionParameterTypeValues() []GalleryApplicationCustomActionParameterType { + return []GalleryApplicationCustomActionParameterType{ + GalleryApplicationCustomActionParameterTypeConfigurationDataBlob, + GalleryApplicationCustomActionParameterTypeLogOutputBlob, + GalleryApplicationCustomActionParameterTypeString, + } +} + +type GalleryExpandParams string + +const ( + GalleryExpandParamsSharingProfileGroups GalleryExpandParams = "SharingProfile/Groups" +) + +// PossibleGalleryExpandParamsValues returns the possible values for the GalleryExpandParams const type. +func PossibleGalleryExpandParamsValues() []GalleryExpandParams { + return []GalleryExpandParams{ + GalleryExpandParamsSharingProfileGroups, + } +} + +// GalleryExtendedLocationType - It is type of the extended location. +type GalleryExtendedLocationType string + +const ( + GalleryExtendedLocationTypeEdgeZone GalleryExtendedLocationType = "EdgeZone" + GalleryExtendedLocationTypeUnknown GalleryExtendedLocationType = "Unknown" +) + +// PossibleGalleryExtendedLocationTypeValues returns the possible values for the GalleryExtendedLocationType const type. +func PossibleGalleryExtendedLocationTypeValues() []GalleryExtendedLocationType { + return []GalleryExtendedLocationType{ + GalleryExtendedLocationTypeEdgeZone, + GalleryExtendedLocationTypeUnknown, + } +} + +// GalleryProvisioningState - The provisioning state, which only appears in the response. +type GalleryProvisioningState string + +const ( + GalleryProvisioningStateCreating GalleryProvisioningState = "Creating" + GalleryProvisioningStateDeleting GalleryProvisioningState = "Deleting" + GalleryProvisioningStateFailed GalleryProvisioningState = "Failed" + GalleryProvisioningStateMigrating GalleryProvisioningState = "Migrating" + GalleryProvisioningStateSucceeded GalleryProvisioningState = "Succeeded" + GalleryProvisioningStateUpdating GalleryProvisioningState = "Updating" +) + +// PossibleGalleryProvisioningStateValues returns the possible values for the GalleryProvisioningState const type. +func PossibleGalleryProvisioningStateValues() []GalleryProvisioningState { + return []GalleryProvisioningState{ + GalleryProvisioningStateCreating, + GalleryProvisioningStateDeleting, + GalleryProvisioningStateFailed, + GalleryProvisioningStateMigrating, + GalleryProvisioningStateSucceeded, + GalleryProvisioningStateUpdating, + } +} + +// GallerySharingPermissionTypes - This property allows you to specify the permission of sharing gallery. Possible values +// are: Private, Groups, Community. +type GallerySharingPermissionTypes string + +const ( + GallerySharingPermissionTypesCommunity GallerySharingPermissionTypes = "Community" + GallerySharingPermissionTypesGroups GallerySharingPermissionTypes = "Groups" + GallerySharingPermissionTypesPrivate GallerySharingPermissionTypes = "Private" +) + +// PossibleGallerySharingPermissionTypesValues returns the possible values for the GallerySharingPermissionTypes const type. +func PossibleGallerySharingPermissionTypesValues() []GallerySharingPermissionTypes { + return []GallerySharingPermissionTypes{ + GallerySharingPermissionTypesCommunity, + GallerySharingPermissionTypesGroups, + GallerySharingPermissionTypesPrivate, + } +} + +// HostCaching - The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' +type HostCaching string + +const ( + HostCachingNone HostCaching = "None" + HostCachingReadOnly HostCaching = "ReadOnly" + HostCachingReadWrite HostCaching = "ReadWrite" +) + +// PossibleHostCachingValues returns the possible values for the HostCaching const type. +func PossibleHostCachingValues() []HostCaching { + return []HostCaching{ + HostCachingNone, + HostCachingReadOnly, + HostCachingReadWrite, + } +} + +// HyperVGeneration - The hypervisor generation of the Virtual Machine. Applicable to OS disks only. +type HyperVGeneration string + +const ( + HyperVGenerationV1 HyperVGeneration = "V1" + HyperVGenerationV2 HyperVGeneration = "V2" +) + +// PossibleHyperVGenerationValues returns the possible values for the HyperVGeneration const type. +func PossibleHyperVGenerationValues() []HyperVGeneration { + return []HyperVGeneration{ + HyperVGenerationV1, + HyperVGenerationV2, + } +} + +// HyperVGenerationType - Specifies the HyperVGeneration Type associated with a resource +type HyperVGenerationType string + +const ( + HyperVGenerationTypeV1 HyperVGenerationType = "V1" + HyperVGenerationTypeV2 HyperVGenerationType = "V2" +) + +// PossibleHyperVGenerationTypeValues returns the possible values for the HyperVGenerationType const type. +func PossibleHyperVGenerationTypeValues() []HyperVGenerationType { + return []HyperVGenerationType{ + HyperVGenerationTypeV1, + HyperVGenerationTypeV2, + } +} + +// HyperVGenerationTypes - Specifies the HyperVGeneration Type +type HyperVGenerationTypes string + +const ( + HyperVGenerationTypesV1 HyperVGenerationTypes = "V1" + HyperVGenerationTypesV2 HyperVGenerationTypes = "V2" +) + +// PossibleHyperVGenerationTypesValues returns the possible values for the HyperVGenerationTypes const type. +func PossibleHyperVGenerationTypesValues() []HyperVGenerationTypes { + return []HyperVGenerationTypes{ + HyperVGenerationTypesV1, + HyperVGenerationTypesV2, + } +} + +// IPVersion - Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or +// IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. +type IPVersion string + +const ( + IPVersionIPv4 IPVersion = "IPv4" + IPVersionIPv6 IPVersion = "IPv6" +) + +// PossibleIPVersionValues returns the possible values for the IPVersion const type. +func PossibleIPVersionValues() []IPVersion { + return []IPVersion{ + IPVersionIPv4, + IPVersionIPv6, + } +} + +// IPVersions - Available from Api-Version 2019-07-01 onwards, it represents whether the specific ipconfiguration is IPv4 +// or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. +type IPVersions string + +const ( + IPVersionsIPv4 IPVersions = "IPv4" + IPVersionsIPv6 IPVersions = "IPv6" +) + +// PossibleIPVersionsValues returns the possible values for the IPVersions const type. +func PossibleIPVersionsValues() []IPVersions { + return []IPVersions{ + IPVersionsIPv4, + IPVersionsIPv6, + } +} + +// ImageState - Describes the state of the image. +type ImageState string + +const ( + ImageStateActive ImageState = "Active" + ImageStateDeprecated ImageState = "Deprecated" + ImageStateScheduledForDeprecation ImageState = "ScheduledForDeprecation" +) + +// PossibleImageStateValues returns the possible values for the ImageState const type. +func PossibleImageStateValues() []ImageState { + return []ImageState{ + ImageStateActive, + ImageStateDeprecated, + ImageStateScheduledForDeprecation, + } +} + +type InstanceViewTypes string + +const ( + InstanceViewTypesInstanceView InstanceViewTypes = "instanceView" + InstanceViewTypesUserData InstanceViewTypes = "userData" +) + +// PossibleInstanceViewTypesValues returns the possible values for the InstanceViewTypes const type. +func PossibleInstanceViewTypesValues() []InstanceViewTypes { + return []InstanceViewTypes{ + InstanceViewTypesInstanceView, + InstanceViewTypesUserData, + } +} + +// IntervalInMins - Interval value in minutes used to create LogAnalytics call rate logs. +type IntervalInMins string + +const ( + IntervalInMinsFiveMins IntervalInMins = "FiveMins" + IntervalInMinsSixtyMins IntervalInMins = "SixtyMins" + IntervalInMinsThirtyMins IntervalInMins = "ThirtyMins" + IntervalInMinsThreeMins IntervalInMins = "ThreeMins" +) + +// PossibleIntervalInMinsValues returns the possible values for the IntervalInMins const type. +func PossibleIntervalInMinsValues() []IntervalInMins { + return []IntervalInMins{ + IntervalInMinsFiveMins, + IntervalInMinsSixtyMins, + IntervalInMinsThirtyMins, + IntervalInMinsThreeMins, + } +} + +// LinuxPatchAssessmentMode - Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine. +// Possible values are: +// ImageDefault - You control the timing of patch assessments on a virtual machine. +// AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true. +type LinuxPatchAssessmentMode string + +const ( + LinuxPatchAssessmentModeAutomaticByPlatform LinuxPatchAssessmentMode = "AutomaticByPlatform" + LinuxPatchAssessmentModeImageDefault LinuxPatchAssessmentMode = "ImageDefault" +) + +// PossibleLinuxPatchAssessmentModeValues returns the possible values for the LinuxPatchAssessmentMode const type. +func PossibleLinuxPatchAssessmentModeValues() []LinuxPatchAssessmentMode { + return []LinuxPatchAssessmentMode{ + LinuxPatchAssessmentModeAutomaticByPlatform, + LinuxPatchAssessmentModeImageDefault, + } +} + +// LinuxVMGuestPatchAutomaticByPlatformRebootSetting - Specifies the reboot setting for all AutomaticByPlatform patch installation +// operations. +type LinuxVMGuestPatchAutomaticByPlatformRebootSetting string + +const ( + LinuxVMGuestPatchAutomaticByPlatformRebootSettingAlways LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "Always" + LinuxVMGuestPatchAutomaticByPlatformRebootSettingIfRequired LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "IfRequired" + LinuxVMGuestPatchAutomaticByPlatformRebootSettingNever LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "Never" + LinuxVMGuestPatchAutomaticByPlatformRebootSettingUnknown LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "Unknown" +) + +// PossibleLinuxVMGuestPatchAutomaticByPlatformRebootSettingValues returns the possible values for the LinuxVMGuestPatchAutomaticByPlatformRebootSetting const type. +func PossibleLinuxVMGuestPatchAutomaticByPlatformRebootSettingValues() []LinuxVMGuestPatchAutomaticByPlatformRebootSetting { + return []LinuxVMGuestPatchAutomaticByPlatformRebootSetting{ + LinuxVMGuestPatchAutomaticByPlatformRebootSettingAlways, + LinuxVMGuestPatchAutomaticByPlatformRebootSettingIfRequired, + LinuxVMGuestPatchAutomaticByPlatformRebootSettingNever, + LinuxVMGuestPatchAutomaticByPlatformRebootSettingUnknown, + } +} + +// LinuxVMGuestPatchMode - Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated +// to virtual machine scale set with OrchestrationMode as Flexible. +// Possible values are: +// ImageDefault - The virtual machine's default patching configuration is used. +// AutomaticByPlatform - The virtual machine will be automatically updated by the platform. The property provisionVMAgent +// must be true +type LinuxVMGuestPatchMode string + +const ( + LinuxVMGuestPatchModeAutomaticByPlatform LinuxVMGuestPatchMode = "AutomaticByPlatform" + LinuxVMGuestPatchModeImageDefault LinuxVMGuestPatchMode = "ImageDefault" +) + +// PossibleLinuxVMGuestPatchModeValues returns the possible values for the LinuxVMGuestPatchMode const type. +func PossibleLinuxVMGuestPatchModeValues() []LinuxVMGuestPatchMode { + return []LinuxVMGuestPatchMode{ + LinuxVMGuestPatchModeAutomaticByPlatform, + LinuxVMGuestPatchModeImageDefault, + } +} + +// MaintenanceOperationResultCodeTypes - The Last Maintenance Operation Result Code. +type MaintenanceOperationResultCodeTypes string + +const ( + MaintenanceOperationResultCodeTypesMaintenanceAborted MaintenanceOperationResultCodeTypes = "MaintenanceAborted" + MaintenanceOperationResultCodeTypesMaintenanceCompleted MaintenanceOperationResultCodeTypes = "MaintenanceCompleted" + MaintenanceOperationResultCodeTypesNone MaintenanceOperationResultCodeTypes = "None" + MaintenanceOperationResultCodeTypesRetryLater MaintenanceOperationResultCodeTypes = "RetryLater" +) + +// PossibleMaintenanceOperationResultCodeTypesValues returns the possible values for the MaintenanceOperationResultCodeTypes const type. +func PossibleMaintenanceOperationResultCodeTypesValues() []MaintenanceOperationResultCodeTypes { + return []MaintenanceOperationResultCodeTypes{ + MaintenanceOperationResultCodeTypesMaintenanceAborted, + MaintenanceOperationResultCodeTypesMaintenanceCompleted, + MaintenanceOperationResultCodeTypesNone, + MaintenanceOperationResultCodeTypesRetryLater, + } +} + +// Mode - Specifies the mode that ProxyAgent will execute on if the feature is enabled. ProxyAgent will start to audit or +// monitor but not enforce access control over requests to host endpoints in Audit mode, +// while in Enforce mode it will enforce access control. The default value is Enforce mode. +type Mode string + +const ( + ModeAudit Mode = "Audit" + ModeEnforce Mode = "Enforce" +) + +// PossibleModeValues returns the possible values for the Mode const type. +func PossibleModeValues() []Mode { + return []Mode{ + ModeAudit, + ModeEnforce, + } +} + +// NetworkAPIVersion - specifies the Microsoft.Network API version used when creating networking resources in the Network +// Interface Configurations +type NetworkAPIVersion string + +const ( + NetworkAPIVersionTwoThousandTwenty1101 NetworkAPIVersion = "2020-11-01" +) + +// PossibleNetworkAPIVersionValues returns the possible values for the NetworkAPIVersion const type. +func PossibleNetworkAPIVersionValues() []NetworkAPIVersion { + return []NetworkAPIVersion{ + NetworkAPIVersionTwoThousandTwenty1101, + } +} + +// NetworkAccessPolicy - Policy for accessing the disk via network. +type NetworkAccessPolicy string + +const ( + // NetworkAccessPolicyAllowAll - The disk can be exported or uploaded to from any network. + NetworkAccessPolicyAllowAll NetworkAccessPolicy = "AllowAll" + // NetworkAccessPolicyAllowPrivate - The disk can be exported or uploaded to using a DiskAccess resource's private endpoints. + NetworkAccessPolicyAllowPrivate NetworkAccessPolicy = "AllowPrivate" + // NetworkAccessPolicyDenyAll - The disk cannot be exported. + NetworkAccessPolicyDenyAll NetworkAccessPolicy = "DenyAll" +) + +// PossibleNetworkAccessPolicyValues returns the possible values for the NetworkAccessPolicy const type. +func PossibleNetworkAccessPolicyValues() []NetworkAccessPolicy { + return []NetworkAccessPolicy{ + NetworkAccessPolicyAllowAll, + NetworkAccessPolicyAllowPrivate, + NetworkAccessPolicyDenyAll, + } +} + +// NetworkInterfaceAuxiliaryMode - Specifies whether the Auxiliary mode is enabled for the Network Interface resource. +type NetworkInterfaceAuxiliaryMode string + +const ( + NetworkInterfaceAuxiliaryModeAcceleratedConnections NetworkInterfaceAuxiliaryMode = "AcceleratedConnections" + NetworkInterfaceAuxiliaryModeFloating NetworkInterfaceAuxiliaryMode = "Floating" + NetworkInterfaceAuxiliaryModeNone NetworkInterfaceAuxiliaryMode = "None" +) + +// PossibleNetworkInterfaceAuxiliaryModeValues returns the possible values for the NetworkInterfaceAuxiliaryMode const type. +func PossibleNetworkInterfaceAuxiliaryModeValues() []NetworkInterfaceAuxiliaryMode { + return []NetworkInterfaceAuxiliaryMode{ + NetworkInterfaceAuxiliaryModeAcceleratedConnections, + NetworkInterfaceAuxiliaryModeFloating, + NetworkInterfaceAuxiliaryModeNone, + } +} + +// NetworkInterfaceAuxiliarySKU - Specifies whether the Auxiliary sku is enabled for the Network Interface resource. +type NetworkInterfaceAuxiliarySKU string + +const ( + NetworkInterfaceAuxiliarySKUA1 NetworkInterfaceAuxiliarySKU = "A1" + NetworkInterfaceAuxiliarySKUA2 NetworkInterfaceAuxiliarySKU = "A2" + NetworkInterfaceAuxiliarySKUA4 NetworkInterfaceAuxiliarySKU = "A4" + NetworkInterfaceAuxiliarySKUA8 NetworkInterfaceAuxiliarySKU = "A8" + NetworkInterfaceAuxiliarySKUNone NetworkInterfaceAuxiliarySKU = "None" +) + +// PossibleNetworkInterfaceAuxiliarySKUValues returns the possible values for the NetworkInterfaceAuxiliarySKU const type. +func PossibleNetworkInterfaceAuxiliarySKUValues() []NetworkInterfaceAuxiliarySKU { + return []NetworkInterfaceAuxiliarySKU{ + NetworkInterfaceAuxiliarySKUA1, + NetworkInterfaceAuxiliarySKUA2, + NetworkInterfaceAuxiliarySKUA4, + NetworkInterfaceAuxiliarySKUA8, + NetworkInterfaceAuxiliarySKUNone, + } +} + +// OperatingSystemStateTypes - This property allows the user to specify whether the virtual machines created under this image +// are 'Generalized' or 'Specialized'. +type OperatingSystemStateTypes string + +const ( + OperatingSystemStateTypesGeneralized OperatingSystemStateTypes = "Generalized" + OperatingSystemStateTypesSpecialized OperatingSystemStateTypes = "Specialized" +) + +// PossibleOperatingSystemStateTypesValues returns the possible values for the OperatingSystemStateTypes const type. +func PossibleOperatingSystemStateTypesValues() []OperatingSystemStateTypes { + return []OperatingSystemStateTypes{ + OperatingSystemStateTypesGeneralized, + OperatingSystemStateTypesSpecialized, + } +} + +// OperatingSystemType - Gets the Operating System type. +type OperatingSystemType string + +const ( + OperatingSystemTypeLinux OperatingSystemType = "Linux" + OperatingSystemTypeWindows OperatingSystemType = "Windows" +) + +// PossibleOperatingSystemTypeValues returns the possible values for the OperatingSystemType const type. +func PossibleOperatingSystemTypeValues() []OperatingSystemType { + return []OperatingSystemType{ + OperatingSystemTypeLinux, + OperatingSystemTypeWindows, + } +} + +// OperatingSystemTypes - This property allows you to specify the supported type of the OS that application is built for. +// Possible values are: Windows, Linux. +type OperatingSystemTypes string + +const ( + OperatingSystemTypesLinux OperatingSystemTypes = "Linux" + OperatingSystemTypesWindows OperatingSystemTypes = "Windows" +) + +// PossibleOperatingSystemTypesValues returns the possible values for the OperatingSystemTypes const type. +func PossibleOperatingSystemTypesValues() []OperatingSystemTypes { + return []OperatingSystemTypes{ + OperatingSystemTypesLinux, + OperatingSystemTypesWindows, + } +} + +// OrchestrationMode - Specifies the orchestration mode for the virtual machine scale set. +type OrchestrationMode string + +const ( + OrchestrationModeFlexible OrchestrationMode = "Flexible" + OrchestrationModeUniform OrchestrationMode = "Uniform" +) + +// PossibleOrchestrationModeValues returns the possible values for the OrchestrationMode const type. +func PossibleOrchestrationModeValues() []OrchestrationMode { + return []OrchestrationMode{ + OrchestrationModeFlexible, + OrchestrationModeUniform, + } +} + +// OrchestrationServiceNames - The name of the service. +type OrchestrationServiceNames string + +const ( + OrchestrationServiceNamesAutomaticRepairs OrchestrationServiceNames = "AutomaticRepairs" +) + +// PossibleOrchestrationServiceNamesValues returns the possible values for the OrchestrationServiceNames const type. +func PossibleOrchestrationServiceNamesValues() []OrchestrationServiceNames { + return []OrchestrationServiceNames{ + OrchestrationServiceNamesAutomaticRepairs, + } +} + +// OrchestrationServiceState - The current state of the service. +type OrchestrationServiceState string + +const ( + OrchestrationServiceStateNotRunning OrchestrationServiceState = "NotRunning" + OrchestrationServiceStateRunning OrchestrationServiceState = "Running" + OrchestrationServiceStateSuspended OrchestrationServiceState = "Suspended" +) + +// PossibleOrchestrationServiceStateValues returns the possible values for the OrchestrationServiceState const type. +func PossibleOrchestrationServiceStateValues() []OrchestrationServiceState { + return []OrchestrationServiceState{ + OrchestrationServiceStateNotRunning, + OrchestrationServiceStateRunning, + OrchestrationServiceStateSuspended, + } +} + +// OrchestrationServiceStateAction - The action to be performed. +type OrchestrationServiceStateAction string + +const ( + OrchestrationServiceStateActionResume OrchestrationServiceStateAction = "Resume" + OrchestrationServiceStateActionSuspend OrchestrationServiceStateAction = "Suspend" +) + +// PossibleOrchestrationServiceStateActionValues returns the possible values for the OrchestrationServiceStateAction const type. +func PossibleOrchestrationServiceStateActionValues() []OrchestrationServiceStateAction { + return []OrchestrationServiceStateAction{ + OrchestrationServiceStateActionResume, + OrchestrationServiceStateActionSuspend, + } +} + +// PatchAssessmentState - Describes the availability of a given patch. +type PatchAssessmentState string + +const ( + PatchAssessmentStateAvailable PatchAssessmentState = "Available" + PatchAssessmentStateUnknown PatchAssessmentState = "Unknown" +) + +// PossiblePatchAssessmentStateValues returns the possible values for the PatchAssessmentState const type. +func PossiblePatchAssessmentStateValues() []PatchAssessmentState { + return []PatchAssessmentState{ + PatchAssessmentStateAvailable, + PatchAssessmentStateUnknown, + } +} + +// PatchInstallationState - The state of the patch after the installation operation completed. +type PatchInstallationState string + +const ( + PatchInstallationStateExcluded PatchInstallationState = "Excluded" + PatchInstallationStateFailed PatchInstallationState = "Failed" + PatchInstallationStateInstalled PatchInstallationState = "Installed" + PatchInstallationStateNotSelected PatchInstallationState = "NotSelected" + PatchInstallationStatePending PatchInstallationState = "Pending" + PatchInstallationStateUnknown PatchInstallationState = "Unknown" +) + +// PossiblePatchInstallationStateValues returns the possible values for the PatchInstallationState const type. +func PossiblePatchInstallationStateValues() []PatchInstallationState { + return []PatchInstallationState{ + PatchInstallationStateExcluded, + PatchInstallationStateFailed, + PatchInstallationStateInstalled, + PatchInstallationStateNotSelected, + PatchInstallationStatePending, + PatchInstallationStateUnknown, + } +} + +// PatchOperationStatus - The overall success or failure status of the operation. It remains "InProgress" until the operation +// completes. At that point it will become "Unknown", "Failed", "Succeeded", or +// "CompletedWithWarnings." +type PatchOperationStatus string + +const ( + PatchOperationStatusCompletedWithWarnings PatchOperationStatus = "CompletedWithWarnings" + PatchOperationStatusFailed PatchOperationStatus = "Failed" + PatchOperationStatusInProgress PatchOperationStatus = "InProgress" + PatchOperationStatusSucceeded PatchOperationStatus = "Succeeded" + PatchOperationStatusUnknown PatchOperationStatus = "Unknown" +) + +// PossiblePatchOperationStatusValues returns the possible values for the PatchOperationStatus const type. +func PossiblePatchOperationStatusValues() []PatchOperationStatus { + return []PatchOperationStatus{ + PatchOperationStatusCompletedWithWarnings, + PatchOperationStatusFailed, + PatchOperationStatusInProgress, + PatchOperationStatusSucceeded, + PatchOperationStatusUnknown, + } +} + +// PolicyViolationCategory - Describes the nature of the policy violation. +type PolicyViolationCategory string + +const ( + PolicyViolationCategoryCopyrightValidation PolicyViolationCategory = "CopyrightValidation" + PolicyViolationCategoryIPTheft PolicyViolationCategory = "IpTheft" + PolicyViolationCategoryImageFlaggedUnsafe PolicyViolationCategory = "ImageFlaggedUnsafe" + PolicyViolationCategoryOther PolicyViolationCategory = "Other" +) + +// PossiblePolicyViolationCategoryValues returns the possible values for the PolicyViolationCategory const type. +func PossiblePolicyViolationCategoryValues() []PolicyViolationCategory { + return []PolicyViolationCategory{ + PolicyViolationCategoryCopyrightValidation, + PolicyViolationCategoryIPTheft, + PolicyViolationCategoryImageFlaggedUnsafe, + PolicyViolationCategoryOther, + } +} + +// 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, + } +} + +// ProtocolTypes - Specifies the protocol of WinRM listener. Possible values are: http, https. +type ProtocolTypes string + +const ( + ProtocolTypesHTTP ProtocolTypes = "Http" + ProtocolTypesHTTPS ProtocolTypes = "Https" +) + +// PossibleProtocolTypesValues returns the possible values for the ProtocolTypes const type. +func PossibleProtocolTypesValues() []ProtocolTypes { + return []ProtocolTypes{ + ProtocolTypesHTTP, + ProtocolTypesHTTPS, + } +} + +// ProximityPlacementGroupType - Specifies the type of the proximity placement group. Possible values are: Standard : Co-locate +// resources within an Azure region or Availability Zone. Ultra : For future use. +type ProximityPlacementGroupType string + +const ( + ProximityPlacementGroupTypeStandard ProximityPlacementGroupType = "Standard" + ProximityPlacementGroupTypeUltra ProximityPlacementGroupType = "Ultra" +) + +// PossibleProximityPlacementGroupTypeValues returns the possible values for the ProximityPlacementGroupType const type. +func PossibleProximityPlacementGroupTypeValues() []ProximityPlacementGroupType { + return []ProximityPlacementGroupType{ + ProximityPlacementGroupTypeStandard, + ProximityPlacementGroupTypeUltra, + } +} + +// PublicIPAddressSKUName - Specify public IP sku name +type PublicIPAddressSKUName string + +const ( + PublicIPAddressSKUNameBasic PublicIPAddressSKUName = "Basic" + PublicIPAddressSKUNameStandard PublicIPAddressSKUName = "Standard" +) + +// PossiblePublicIPAddressSKUNameValues returns the possible values for the PublicIPAddressSKUName const type. +func PossiblePublicIPAddressSKUNameValues() []PublicIPAddressSKUName { + return []PublicIPAddressSKUName{ + PublicIPAddressSKUNameBasic, + PublicIPAddressSKUNameStandard, + } +} + +// PublicIPAddressSKUTier - Specify public IP sku tier +type PublicIPAddressSKUTier string + +const ( + PublicIPAddressSKUTierGlobal PublicIPAddressSKUTier = "Global" + PublicIPAddressSKUTierRegional PublicIPAddressSKUTier = "Regional" +) + +// PossiblePublicIPAddressSKUTierValues returns the possible values for the PublicIPAddressSKUTier const type. +func PossiblePublicIPAddressSKUTierValues() []PublicIPAddressSKUTier { + return []PublicIPAddressSKUTier{ + PublicIPAddressSKUTierGlobal, + PublicIPAddressSKUTierRegional, + } +} + +// PublicIPAllocationMethod - Specify the public IP allocation type +type PublicIPAllocationMethod string + +const ( + PublicIPAllocationMethodDynamic PublicIPAllocationMethod = "Dynamic" + PublicIPAllocationMethodStatic PublicIPAllocationMethod = "Static" +) + +// PossiblePublicIPAllocationMethodValues returns the possible values for the PublicIPAllocationMethod const type. +func PossiblePublicIPAllocationMethodValues() []PublicIPAllocationMethod { + return []PublicIPAllocationMethod{ + PublicIPAllocationMethodDynamic, + PublicIPAllocationMethodStatic, + } +} + +// PublicNetworkAccess - Policy for controlling export on the disk. +type PublicNetworkAccess string + +const ( + // PublicNetworkAccessDisabled - You cannot access the underlying data of the disk publicly on the internet even when NetworkAccessPolicy + // is set to AllowAll. You can access the data via the SAS URI only from your trusted Azure VNET when NetworkAccessPolicy + // is set to AllowPrivate. + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + // PublicNetworkAccessEnabled - You can generate a SAS URI to access the underlying data of the disk publicly on the internet + // when NetworkAccessPolicy is set to AllowAll. You can access the data via the SAS URI only from your trusted Azure VNET + // when NetworkAccessPolicy is set to AllowPrivate. + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// RepairAction - Type of repair action (replace, restart, reimage) that will be used for repairing unhealthy virtual machines +// in the scale set. Default value is replace. +type RepairAction string + +const ( + RepairActionReimage RepairAction = "Reimage" + RepairActionReplace RepairAction = "Replace" + RepairActionRestart RepairAction = "Restart" +) + +// PossibleRepairActionValues returns the possible values for the RepairAction const type. +func PossibleRepairActionValues() []RepairAction { + return []RepairAction{ + RepairActionReimage, + RepairActionReplace, + RepairActionRestart, + } +} + +// ReplicationMode - Optional parameter which specifies the mode to be used for replication. This property is not updatable. +type ReplicationMode string + +const ( + ReplicationModeFull ReplicationMode = "Full" + ReplicationModeShallow ReplicationMode = "Shallow" +) + +// PossibleReplicationModeValues returns the possible values for the ReplicationMode const type. +func PossibleReplicationModeValues() []ReplicationMode { + return []ReplicationMode{ + ReplicationModeFull, + ReplicationModeShallow, + } +} + +// ReplicationState - This is the regional replication state. +type ReplicationState string + +const ( + ReplicationStateCompleted ReplicationState = "Completed" + ReplicationStateFailed ReplicationState = "Failed" + ReplicationStateReplicating ReplicationState = "Replicating" + ReplicationStateUnknown ReplicationState = "Unknown" +) + +// PossibleReplicationStateValues returns the possible values for the ReplicationState const type. +func PossibleReplicationStateValues() []ReplicationState { + return []ReplicationState{ + ReplicationStateCompleted, + ReplicationStateFailed, + ReplicationStateReplicating, + ReplicationStateUnknown, + } +} + +type ReplicationStatusTypes string + +const ( + ReplicationStatusTypesReplicationStatus ReplicationStatusTypes = "ReplicationStatus" + ReplicationStatusTypesUefiSettings ReplicationStatusTypes = "UefiSettings" +) + +// PossibleReplicationStatusTypesValues returns the possible values for the ReplicationStatusTypes const type. +func PossibleReplicationStatusTypesValues() []ReplicationStatusTypes { + return []ReplicationStatusTypes{ + ReplicationStatusTypesReplicationStatus, + ReplicationStatusTypesUefiSettings, + } +} + +// ResourceIdentityType - The type of identity used for the virtual machine scale set. The type 'SystemAssigned, UserAssigned' +// includes both an implicitly created identity and a set of user assigned identities. The type 'None' +// will remove any identities from the virtual machine scale set. +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, + } +} + +// ResourceSKUCapacityScaleType - The scale type applicable to the sku. +type ResourceSKUCapacityScaleType string + +const ( + ResourceSKUCapacityScaleTypeAutomatic ResourceSKUCapacityScaleType = "Automatic" + ResourceSKUCapacityScaleTypeManual ResourceSKUCapacityScaleType = "Manual" + ResourceSKUCapacityScaleTypeNone ResourceSKUCapacityScaleType = "None" +) + +// PossibleResourceSKUCapacityScaleTypeValues returns the possible values for the ResourceSKUCapacityScaleType const type. +func PossibleResourceSKUCapacityScaleTypeValues() []ResourceSKUCapacityScaleType { + return []ResourceSKUCapacityScaleType{ + ResourceSKUCapacityScaleTypeAutomatic, + ResourceSKUCapacityScaleTypeManual, + ResourceSKUCapacityScaleTypeNone, + } +} + +// ResourceSKURestrictionsReasonCode - The reason for restriction. +type ResourceSKURestrictionsReasonCode string + +const ( + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription ResourceSKURestrictionsReasonCode = "NotAvailableForSubscription" + ResourceSKURestrictionsReasonCodeQuotaID ResourceSKURestrictionsReasonCode = "QuotaId" +) + +// PossibleResourceSKURestrictionsReasonCodeValues returns the possible values for the ResourceSKURestrictionsReasonCode const type. +func PossibleResourceSKURestrictionsReasonCodeValues() []ResourceSKURestrictionsReasonCode { + return []ResourceSKURestrictionsReasonCode{ + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription, + ResourceSKURestrictionsReasonCodeQuotaID, + } +} + +// ResourceSKURestrictionsType - The type of restrictions. +type ResourceSKURestrictionsType string + +const ( + ResourceSKURestrictionsTypeLocation ResourceSKURestrictionsType = "Location" + ResourceSKURestrictionsTypeZone ResourceSKURestrictionsType = "Zone" +) + +// PossibleResourceSKURestrictionsTypeValues returns the possible values for the ResourceSKURestrictionsType const type. +func PossibleResourceSKURestrictionsTypeValues() []ResourceSKURestrictionsType { + return []ResourceSKURestrictionsType{ + ResourceSKURestrictionsTypeLocation, + ResourceSKURestrictionsTypeZone, + } +} + +type RestorePointCollectionExpandOptions string + +const ( + RestorePointCollectionExpandOptionsRestorePoints RestorePointCollectionExpandOptions = "restorePoints" +) + +// PossibleRestorePointCollectionExpandOptionsValues returns the possible values for the RestorePointCollectionExpandOptions const type. +func PossibleRestorePointCollectionExpandOptionsValues() []RestorePointCollectionExpandOptions { + return []RestorePointCollectionExpandOptions{ + RestorePointCollectionExpandOptionsRestorePoints, + } +} + +// RestorePointEncryptionType - The type of key used to encrypt the data of the disk restore point. +type RestorePointEncryptionType string + +const ( + // RestorePointEncryptionTypeEncryptionAtRestWithCustomerKey - Disk Restore Point is encrypted at rest with Customer managed + // key that can be changed and revoked by a customer. + RestorePointEncryptionTypeEncryptionAtRestWithCustomerKey RestorePointEncryptionType = "EncryptionAtRestWithCustomerKey" + // RestorePointEncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys - Disk Restore Point is encrypted at rest with 2 + // layers of encryption. One of the keys is Customer managed and the other key is Platform managed. + RestorePointEncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys RestorePointEncryptionType = "EncryptionAtRestWithPlatformAndCustomerKeys" + // RestorePointEncryptionTypeEncryptionAtRestWithPlatformKey - Disk Restore Point is encrypted at rest with Platform managed + // key. + RestorePointEncryptionTypeEncryptionAtRestWithPlatformKey RestorePointEncryptionType = "EncryptionAtRestWithPlatformKey" +) + +// PossibleRestorePointEncryptionTypeValues returns the possible values for the RestorePointEncryptionType const type. +func PossibleRestorePointEncryptionTypeValues() []RestorePointEncryptionType { + return []RestorePointEncryptionType{ + RestorePointEncryptionTypeEncryptionAtRestWithCustomerKey, + RestorePointEncryptionTypeEncryptionAtRestWithPlatformAndCustomerKeys, + RestorePointEncryptionTypeEncryptionAtRestWithPlatformKey, + } +} + +type RestorePointExpandOptions string + +const ( + RestorePointExpandOptionsInstanceView RestorePointExpandOptions = "instanceView" +) + +// PossibleRestorePointExpandOptionsValues returns the possible values for the RestorePointExpandOptions const type. +func PossibleRestorePointExpandOptionsValues() []RestorePointExpandOptions { + return []RestorePointExpandOptions{ + RestorePointExpandOptionsInstanceView, + } +} + +// RollingUpgradeActionType - The last action performed on the rolling upgrade. +type RollingUpgradeActionType string + +const ( + RollingUpgradeActionTypeCancel RollingUpgradeActionType = "Cancel" + RollingUpgradeActionTypeStart RollingUpgradeActionType = "Start" +) + +// PossibleRollingUpgradeActionTypeValues returns the possible values for the RollingUpgradeActionType const type. +func PossibleRollingUpgradeActionTypeValues() []RollingUpgradeActionType { + return []RollingUpgradeActionType{ + RollingUpgradeActionTypeCancel, + RollingUpgradeActionTypeStart, + } +} + +// RollingUpgradeStatusCode - Code indicating the current status of the upgrade. +type RollingUpgradeStatusCode string + +const ( + RollingUpgradeStatusCodeCancelled RollingUpgradeStatusCode = "Cancelled" + RollingUpgradeStatusCodeCompleted RollingUpgradeStatusCode = "Completed" + RollingUpgradeStatusCodeFaulted RollingUpgradeStatusCode = "Faulted" + RollingUpgradeStatusCodeRollingForward RollingUpgradeStatusCode = "RollingForward" +) + +// PossibleRollingUpgradeStatusCodeValues returns the possible values for the RollingUpgradeStatusCode const type. +func PossibleRollingUpgradeStatusCodeValues() []RollingUpgradeStatusCode { + return []RollingUpgradeStatusCode{ + RollingUpgradeStatusCodeCancelled, + RollingUpgradeStatusCodeCompleted, + RollingUpgradeStatusCodeFaulted, + RollingUpgradeStatusCodeRollingForward, + } +} + +// SSHEncryptionTypes - The encryption type of the SSH keys to be generated. See SshEncryptionTypes for possible set of values. +// If not provided, will default to RSA +type SSHEncryptionTypes string + +const ( + SSHEncryptionTypesEd25519 SSHEncryptionTypes = "Ed25519" + SSHEncryptionTypesRSA SSHEncryptionTypes = "RSA" +) + +// PossibleSSHEncryptionTypesValues returns the possible values for the SSHEncryptionTypes const type. +func PossibleSSHEncryptionTypesValues() []SSHEncryptionTypes { + return []SSHEncryptionTypes{ + SSHEncryptionTypesEd25519, + SSHEncryptionTypesRSA, + } +} + +// SecurityEncryptionTypes - Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for encryption +// of the managed disk along with VMGuestState blob, VMGuestStateOnly for encryption of just the +// VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the VMGuestState blob.. Note: It can be set +// for only Confidential VMs. +type SecurityEncryptionTypes string + +const ( + SecurityEncryptionTypesDiskWithVMGuestState SecurityEncryptionTypes = "DiskWithVMGuestState" + SecurityEncryptionTypesNonPersistedTPM SecurityEncryptionTypes = "NonPersistedTPM" + SecurityEncryptionTypesVMGuestStateOnly SecurityEncryptionTypes = "VMGuestStateOnly" +) + +// PossibleSecurityEncryptionTypesValues returns the possible values for the SecurityEncryptionTypes const type. +func PossibleSecurityEncryptionTypesValues() []SecurityEncryptionTypes { + return []SecurityEncryptionTypes{ + SecurityEncryptionTypesDiskWithVMGuestState, + SecurityEncryptionTypesNonPersistedTPM, + SecurityEncryptionTypesVMGuestStateOnly, + } +} + +// SecurityTypes - Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. +// The default behavior is: UefiSettings will not be enabled unless this property is +// set. +type SecurityTypes string + +const ( + SecurityTypesConfidentialVM SecurityTypes = "ConfidentialVM" + SecurityTypesTrustedLaunch SecurityTypes = "TrustedLaunch" +) + +// PossibleSecurityTypesValues returns the possible values for the SecurityTypes const type. +func PossibleSecurityTypesValues() []SecurityTypes { + return []SecurityTypes{ + SecurityTypesConfidentialVM, + SecurityTypesTrustedLaunch, + } +} + +type SelectPermissions string + +const ( + SelectPermissionsPermissions SelectPermissions = "Permissions" +) + +// PossibleSelectPermissionsValues returns the possible values for the SelectPermissions const type. +func PossibleSelectPermissionsValues() []SelectPermissions { + return []SelectPermissions{ + SelectPermissionsPermissions, + } +} + +// SettingNames - Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands +// and AutoLogon. +type SettingNames string + +const ( + SettingNamesAutoLogon SettingNames = "AutoLogon" + SettingNamesFirstLogonCommands SettingNames = "FirstLogonCommands" +) + +// PossibleSettingNamesValues returns the possible values for the SettingNames const type. +func PossibleSettingNamesValues() []SettingNames { + return []SettingNames{ + SettingNamesAutoLogon, + SettingNamesFirstLogonCommands, + } +} + +// SharedGalleryHostCaching - The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' +type SharedGalleryHostCaching string + +const ( + SharedGalleryHostCachingNone SharedGalleryHostCaching = "None" + SharedGalleryHostCachingReadOnly SharedGalleryHostCaching = "ReadOnly" + SharedGalleryHostCachingReadWrite SharedGalleryHostCaching = "ReadWrite" +) + +// PossibleSharedGalleryHostCachingValues returns the possible values for the SharedGalleryHostCaching const type. +func PossibleSharedGalleryHostCachingValues() []SharedGalleryHostCaching { + return []SharedGalleryHostCaching{ + SharedGalleryHostCachingNone, + SharedGalleryHostCachingReadOnly, + SharedGalleryHostCachingReadWrite, + } +} + +type SharedToValues string + +const ( + SharedToValuesTenant SharedToValues = "tenant" +) + +// PossibleSharedToValuesValues returns the possible values for the SharedToValues const type. +func PossibleSharedToValuesValues() []SharedToValues { + return []SharedToValues{ + SharedToValuesTenant, + } +} + +// SharingProfileGroupTypes - This property allows you to specify the type of sharing group. Possible values are: Subscriptions, +// AADTenants. +type SharingProfileGroupTypes string + +const ( + SharingProfileGroupTypesAADTenants SharingProfileGroupTypes = "AADTenants" + SharingProfileGroupTypesSubscriptions SharingProfileGroupTypes = "Subscriptions" +) + +// PossibleSharingProfileGroupTypesValues returns the possible values for the SharingProfileGroupTypes const type. +func PossibleSharingProfileGroupTypesValues() []SharingProfileGroupTypes { + return []SharingProfileGroupTypes{ + SharingProfileGroupTypesAADTenants, + SharingProfileGroupTypesSubscriptions, + } +} + +// SharingState - The sharing state of the gallery, which only appears in the response. +type SharingState string + +const ( + SharingStateFailed SharingState = "Failed" + SharingStateInProgress SharingState = "InProgress" + SharingStateSucceeded SharingState = "Succeeded" + SharingStateUnknown SharingState = "Unknown" +) + +// PossibleSharingStateValues returns the possible values for the SharingState const type. +func PossibleSharingStateValues() []SharingState { + return []SharingState{ + SharingStateFailed, + SharingStateInProgress, + SharingStateSucceeded, + SharingStateUnknown, + } +} + +// SharingUpdateOperationTypes - This property allows you to specify the operation type of gallery sharing update. Possible +// values are: Add, Remove, Reset. +type SharingUpdateOperationTypes string + +const ( + SharingUpdateOperationTypesAdd SharingUpdateOperationTypes = "Add" + SharingUpdateOperationTypesEnableCommunity SharingUpdateOperationTypes = "EnableCommunity" + SharingUpdateOperationTypesRemove SharingUpdateOperationTypes = "Remove" + SharingUpdateOperationTypesReset SharingUpdateOperationTypes = "Reset" +) + +// PossibleSharingUpdateOperationTypesValues returns the possible values for the SharingUpdateOperationTypes const type. +func PossibleSharingUpdateOperationTypesValues() []SharingUpdateOperationTypes { + return []SharingUpdateOperationTypes{ + SharingUpdateOperationTypesAdd, + SharingUpdateOperationTypesEnableCommunity, + SharingUpdateOperationTypesRemove, + SharingUpdateOperationTypesReset, + } +} + +// SnapshotStorageAccountTypes - The sku name. +type SnapshotStorageAccountTypes string + +const ( + // SnapshotStorageAccountTypesPremiumLRS - Premium SSD locally redundant storage + SnapshotStorageAccountTypesPremiumLRS SnapshotStorageAccountTypes = "Premium_LRS" + // SnapshotStorageAccountTypesStandardLRS - Standard HDD locally redundant storage + SnapshotStorageAccountTypesStandardLRS SnapshotStorageAccountTypes = "Standard_LRS" + // SnapshotStorageAccountTypesStandardZRS - Standard zone redundant storage + SnapshotStorageAccountTypesStandardZRS SnapshotStorageAccountTypes = "Standard_ZRS" +) + +// PossibleSnapshotStorageAccountTypesValues returns the possible values for the SnapshotStorageAccountTypes const type. +func PossibleSnapshotStorageAccountTypesValues() []SnapshotStorageAccountTypes { + return []SnapshotStorageAccountTypes{ + SnapshotStorageAccountTypesPremiumLRS, + SnapshotStorageAccountTypesStandardLRS, + SnapshotStorageAccountTypesStandardZRS, + } +} + +// StatusLevelTypes - The level code. +type StatusLevelTypes string + +const ( + StatusLevelTypesError StatusLevelTypes = "Error" + StatusLevelTypesInfo StatusLevelTypes = "Info" + StatusLevelTypesWarning StatusLevelTypes = "Warning" +) + +// PossibleStatusLevelTypesValues returns the possible values for the StatusLevelTypes const type. +func PossibleStatusLevelTypesValues() []StatusLevelTypes { + return []StatusLevelTypes{ + StatusLevelTypesError, + StatusLevelTypesInfo, + StatusLevelTypesWarning, + } +} + +// StorageAccountType - Specifies the storage account type to be used to store the image. This property is not updatable. +type StorageAccountType string + +const ( + StorageAccountTypePremiumLRS StorageAccountType = "Premium_LRS" + StorageAccountTypeStandardLRS StorageAccountType = "Standard_LRS" + StorageAccountTypeStandardZRS StorageAccountType = "Standard_ZRS" +) + +// PossibleStorageAccountTypeValues returns the possible values for the StorageAccountType const type. +func PossibleStorageAccountTypeValues() []StorageAccountType { + return []StorageAccountType{ + StorageAccountTypePremiumLRS, + StorageAccountTypeStandardLRS, + StorageAccountTypeStandardZRS, + } +} + +// StorageAccountTypes - Specifies the storage account type for the managed disk. Managed OS disk storage account type can +// only be set when you create the scale set. NOTE: UltraSSDLRS can only be used with data disks. It +// cannot be used with OS Disk. StandardLRS uses Standard HDD. StandardSSDLRS uses Standard SSD. PremiumLRS uses Premium SSD. +// UltraSSDLRS uses Ultra disk. PremiumZRS uses Premium SSD zone redundant +// storage. StandardSSD_ZRS uses Standard SSD zone redundant storage. For more information regarding disks supported for Windows +// Virtual Machines, refer to +// https://docs.microsoft.com/azure/virtual-machines/windows/disks-types and, for Linux Virtual Machines, refer to https://docs.microsoft.com/azure/virtual-machines/linux/disks-types +type StorageAccountTypes string + +const ( + StorageAccountTypesPremiumLRS StorageAccountTypes = "Premium_LRS" + StorageAccountTypesPremiumV2LRS StorageAccountTypes = "PremiumV2_LRS" + StorageAccountTypesPremiumZRS StorageAccountTypes = "Premium_ZRS" + StorageAccountTypesStandardLRS StorageAccountTypes = "Standard_LRS" + StorageAccountTypesStandardSSDLRS StorageAccountTypes = "StandardSSD_LRS" + StorageAccountTypesStandardSSDZRS StorageAccountTypes = "StandardSSD_ZRS" + StorageAccountTypesUltraSSDLRS StorageAccountTypes = "UltraSSD_LRS" +) + +// PossibleStorageAccountTypesValues returns the possible values for the StorageAccountTypes const type. +func PossibleStorageAccountTypesValues() []StorageAccountTypes { + return []StorageAccountTypes{ + StorageAccountTypesPremiumLRS, + StorageAccountTypesPremiumV2LRS, + StorageAccountTypesPremiumZRS, + StorageAccountTypesStandardLRS, + StorageAccountTypesStandardSSDLRS, + StorageAccountTypesStandardSSDZRS, + StorageAccountTypesUltraSSDLRS, + } +} + +// UefiKeyType - The type of key signature. +type UefiKeyType string + +const ( + UefiKeyTypeSHA256 UefiKeyType = "sha256" + UefiKeyTypeX509 UefiKeyType = "x509" +) + +// PossibleUefiKeyTypeValues returns the possible values for the UefiKeyType const type. +func PossibleUefiKeyTypeValues() []UefiKeyType { + return []UefiKeyType{ + UefiKeyTypeSHA256, + UefiKeyTypeX509, + } +} + +// UefiSignatureTemplateName - The name of the signature template that contains default UEFI keys. +type UefiSignatureTemplateName string + +const ( + UefiSignatureTemplateNameMicrosoftUefiCertificateAuthorityTemplate UefiSignatureTemplateName = "MicrosoftUefiCertificateAuthorityTemplate" + UefiSignatureTemplateNameMicrosoftWindowsTemplate UefiSignatureTemplateName = "MicrosoftWindowsTemplate" + UefiSignatureTemplateNameNoSignatureTemplate UefiSignatureTemplateName = "NoSignatureTemplate" +) + +// PossibleUefiSignatureTemplateNameValues returns the possible values for the UefiSignatureTemplateName const type. +func PossibleUefiSignatureTemplateNameValues() []UefiSignatureTemplateName { + return []UefiSignatureTemplateName{ + UefiSignatureTemplateNameMicrosoftUefiCertificateAuthorityTemplate, + UefiSignatureTemplateNameMicrosoftWindowsTemplate, + UefiSignatureTemplateNameNoSignatureTemplate, + } +} + +// UpgradeMode - Specifies the mode of an upgrade to virtual machines in the scale set. +// Possible values are: +// Manual - You control the application of updates to virtual machines in the scale set. You do this by using the manualUpgrade +// action. +// Automatic - All virtual machines in the scale set are automatically updated at the same time. +type UpgradeMode string + +const ( + UpgradeModeAutomatic UpgradeMode = "Automatic" + UpgradeModeManual UpgradeMode = "Manual" + UpgradeModeRolling UpgradeMode = "Rolling" +) + +// PossibleUpgradeModeValues returns the possible values for the UpgradeMode const type. +func PossibleUpgradeModeValues() []UpgradeMode { + return []UpgradeMode{ + UpgradeModeAutomatic, + UpgradeModeManual, + UpgradeModeRolling, + } +} + +// UpgradeOperationInvoker - Invoker of the Upgrade Operation +type UpgradeOperationInvoker string + +const ( + UpgradeOperationInvokerPlatform UpgradeOperationInvoker = "Platform" + UpgradeOperationInvokerUnknown UpgradeOperationInvoker = "Unknown" + UpgradeOperationInvokerUser UpgradeOperationInvoker = "User" +) + +// PossibleUpgradeOperationInvokerValues returns the possible values for the UpgradeOperationInvoker const type. +func PossibleUpgradeOperationInvokerValues() []UpgradeOperationInvoker { + return []UpgradeOperationInvoker{ + UpgradeOperationInvokerPlatform, + UpgradeOperationInvokerUnknown, + UpgradeOperationInvokerUser, + } +} + +// UpgradeState - Code indicating the current status of the upgrade. +type UpgradeState string + +const ( + UpgradeStateCancelled UpgradeState = "Cancelled" + UpgradeStateCompleted UpgradeState = "Completed" + UpgradeStateFaulted UpgradeState = "Faulted" + UpgradeStateRollingForward UpgradeState = "RollingForward" +) + +// PossibleUpgradeStateValues returns the possible values for the UpgradeState const type. +func PossibleUpgradeStateValues() []UpgradeState { + return []UpgradeState{ + UpgradeStateCancelled, + UpgradeStateCompleted, + UpgradeStateFaulted, + UpgradeStateRollingForward, + } +} + +// VMDiskTypes - VM disk types which are disallowed. +type VMDiskTypes string + +const ( + VMDiskTypesNone VMDiskTypes = "None" + VMDiskTypesUnmanaged VMDiskTypes = "Unmanaged" +) + +// PossibleVMDiskTypesValues returns the possible values for the VMDiskTypes const type. +func PossibleVMDiskTypesValues() []VMDiskTypes { + return []VMDiskTypes{ + VMDiskTypesNone, + VMDiskTypesUnmanaged, + } +} + +type VMGuestPatchClassificationLinux string + +const ( + VMGuestPatchClassificationLinuxCritical VMGuestPatchClassificationLinux = "Critical" + VMGuestPatchClassificationLinuxOther VMGuestPatchClassificationLinux = "Other" + VMGuestPatchClassificationLinuxSecurity VMGuestPatchClassificationLinux = "Security" +) + +// PossibleVMGuestPatchClassificationLinuxValues returns the possible values for the VMGuestPatchClassificationLinux const type. +func PossibleVMGuestPatchClassificationLinuxValues() []VMGuestPatchClassificationLinux { + return []VMGuestPatchClassificationLinux{ + VMGuestPatchClassificationLinuxCritical, + VMGuestPatchClassificationLinuxOther, + VMGuestPatchClassificationLinuxSecurity, + } +} + +type VMGuestPatchClassificationWindows string + +const ( + VMGuestPatchClassificationWindowsCritical VMGuestPatchClassificationWindows = "Critical" + VMGuestPatchClassificationWindowsDefinition VMGuestPatchClassificationWindows = "Definition" + VMGuestPatchClassificationWindowsFeaturePack VMGuestPatchClassificationWindows = "FeaturePack" + VMGuestPatchClassificationWindowsSecurity VMGuestPatchClassificationWindows = "Security" + VMGuestPatchClassificationWindowsServicePack VMGuestPatchClassificationWindows = "ServicePack" + VMGuestPatchClassificationWindowsTools VMGuestPatchClassificationWindows = "Tools" + VMGuestPatchClassificationWindowsUpdateRollUp VMGuestPatchClassificationWindows = "UpdateRollUp" + VMGuestPatchClassificationWindowsUpdates VMGuestPatchClassificationWindows = "Updates" +) + +// PossibleVMGuestPatchClassificationWindowsValues returns the possible values for the VMGuestPatchClassificationWindows const type. +func PossibleVMGuestPatchClassificationWindowsValues() []VMGuestPatchClassificationWindows { + return []VMGuestPatchClassificationWindows{ + VMGuestPatchClassificationWindowsCritical, + VMGuestPatchClassificationWindowsDefinition, + VMGuestPatchClassificationWindowsFeaturePack, + VMGuestPatchClassificationWindowsSecurity, + VMGuestPatchClassificationWindowsServicePack, + VMGuestPatchClassificationWindowsTools, + VMGuestPatchClassificationWindowsUpdateRollUp, + VMGuestPatchClassificationWindowsUpdates, + } +} + +// VMGuestPatchRebootBehavior - Describes the reboot requirements of the patch. +type VMGuestPatchRebootBehavior string + +const ( + VMGuestPatchRebootBehaviorAlwaysRequiresReboot VMGuestPatchRebootBehavior = "AlwaysRequiresReboot" + VMGuestPatchRebootBehaviorCanRequestReboot VMGuestPatchRebootBehavior = "CanRequestReboot" + VMGuestPatchRebootBehaviorNeverReboots VMGuestPatchRebootBehavior = "NeverReboots" + VMGuestPatchRebootBehaviorUnknown VMGuestPatchRebootBehavior = "Unknown" +) + +// PossibleVMGuestPatchRebootBehaviorValues returns the possible values for the VMGuestPatchRebootBehavior const type. +func PossibleVMGuestPatchRebootBehaviorValues() []VMGuestPatchRebootBehavior { + return []VMGuestPatchRebootBehavior{ + VMGuestPatchRebootBehaviorAlwaysRequiresReboot, + VMGuestPatchRebootBehaviorCanRequestReboot, + VMGuestPatchRebootBehaviorNeverReboots, + VMGuestPatchRebootBehaviorUnknown, + } +} + +// VMGuestPatchRebootSetting - Defines when it is acceptable to reboot a VM during a software update operation. +type VMGuestPatchRebootSetting string + +const ( + VMGuestPatchRebootSettingAlways VMGuestPatchRebootSetting = "Always" + VMGuestPatchRebootSettingIfRequired VMGuestPatchRebootSetting = "IfRequired" + VMGuestPatchRebootSettingNever VMGuestPatchRebootSetting = "Never" +) + +// PossibleVMGuestPatchRebootSettingValues returns the possible values for the VMGuestPatchRebootSetting const type. +func PossibleVMGuestPatchRebootSettingValues() []VMGuestPatchRebootSetting { + return []VMGuestPatchRebootSetting{ + VMGuestPatchRebootSettingAlways, + VMGuestPatchRebootSettingIfRequired, + VMGuestPatchRebootSettingNever, + } +} + +// VMGuestPatchRebootStatus - The reboot state of the VM following completion of the operation. +type VMGuestPatchRebootStatus string + +const ( + VMGuestPatchRebootStatusCompleted VMGuestPatchRebootStatus = "Completed" + VMGuestPatchRebootStatusFailed VMGuestPatchRebootStatus = "Failed" + VMGuestPatchRebootStatusNotNeeded VMGuestPatchRebootStatus = "NotNeeded" + VMGuestPatchRebootStatusRequired VMGuestPatchRebootStatus = "Required" + VMGuestPatchRebootStatusStarted VMGuestPatchRebootStatus = "Started" + VMGuestPatchRebootStatusUnknown VMGuestPatchRebootStatus = "Unknown" +) + +// PossibleVMGuestPatchRebootStatusValues returns the possible values for the VMGuestPatchRebootStatus const type. +func PossibleVMGuestPatchRebootStatusValues() []VMGuestPatchRebootStatus { + return []VMGuestPatchRebootStatus{ + VMGuestPatchRebootStatusCompleted, + VMGuestPatchRebootStatusFailed, + VMGuestPatchRebootStatusNotNeeded, + VMGuestPatchRebootStatusRequired, + VMGuestPatchRebootStatusStarted, + VMGuestPatchRebootStatusUnknown, + } +} + +// VirtualMachineEvictionPolicyTypes - Specifies the eviction policy for the Azure Spot VM/VMSS +type VirtualMachineEvictionPolicyTypes string + +const ( + VirtualMachineEvictionPolicyTypesDeallocate VirtualMachineEvictionPolicyTypes = "Deallocate" + VirtualMachineEvictionPolicyTypesDelete VirtualMachineEvictionPolicyTypes = "Delete" +) + +// PossibleVirtualMachineEvictionPolicyTypesValues returns the possible values for the VirtualMachineEvictionPolicyTypes const type. +func PossibleVirtualMachineEvictionPolicyTypesValues() []VirtualMachineEvictionPolicyTypes { + return []VirtualMachineEvictionPolicyTypes{ + VirtualMachineEvictionPolicyTypesDeallocate, + VirtualMachineEvictionPolicyTypesDelete, + } +} + +// VirtualMachinePriorityTypes - Specifies the priority for a standalone virtual machine or the virtual machines in the scale +// set. 'Low' enum will be deprecated in the future, please use 'Spot' as the enum to deploy Azure Spot +// VM/VMSS. +type VirtualMachinePriorityTypes string + +const ( + VirtualMachinePriorityTypesLow VirtualMachinePriorityTypes = "Low" + VirtualMachinePriorityTypesRegular VirtualMachinePriorityTypes = "Regular" + VirtualMachinePriorityTypesSpot VirtualMachinePriorityTypes = "Spot" +) + +// PossibleVirtualMachinePriorityTypesValues returns the possible values for the VirtualMachinePriorityTypes const type. +func PossibleVirtualMachinePriorityTypesValues() []VirtualMachinePriorityTypes { + return []VirtualMachinePriorityTypes{ + VirtualMachinePriorityTypesLow, + VirtualMachinePriorityTypesRegular, + VirtualMachinePriorityTypesSpot, + } +} + +// VirtualMachineScaleSetSKUScaleType - The scale type applicable to the sku. +type VirtualMachineScaleSetSKUScaleType string + +const ( + VirtualMachineScaleSetSKUScaleTypeAutomatic VirtualMachineScaleSetSKUScaleType = "Automatic" + VirtualMachineScaleSetSKUScaleTypeNone VirtualMachineScaleSetSKUScaleType = "None" +) + +// PossibleVirtualMachineScaleSetSKUScaleTypeValues returns the possible values for the VirtualMachineScaleSetSKUScaleType const type. +func PossibleVirtualMachineScaleSetSKUScaleTypeValues() []VirtualMachineScaleSetSKUScaleType { + return []VirtualMachineScaleSetSKUScaleType{ + VirtualMachineScaleSetSKUScaleTypeAutomatic, + VirtualMachineScaleSetSKUScaleTypeNone, + } +} + +type VirtualMachineScaleSetScaleInRules string + +const ( + VirtualMachineScaleSetScaleInRulesDefault VirtualMachineScaleSetScaleInRules = "Default" + VirtualMachineScaleSetScaleInRulesNewestVM VirtualMachineScaleSetScaleInRules = "NewestVM" + VirtualMachineScaleSetScaleInRulesOldestVM VirtualMachineScaleSetScaleInRules = "OldestVM" +) + +// PossibleVirtualMachineScaleSetScaleInRulesValues returns the possible values for the VirtualMachineScaleSetScaleInRules const type. +func PossibleVirtualMachineScaleSetScaleInRulesValues() []VirtualMachineScaleSetScaleInRules { + return []VirtualMachineScaleSetScaleInRules{ + VirtualMachineScaleSetScaleInRulesDefault, + VirtualMachineScaleSetScaleInRulesNewestVM, + VirtualMachineScaleSetScaleInRulesOldestVM, + } +} + +// VirtualMachineSizeTypes - Specifies the size of the virtual machine. The enum data type is currently deprecated and will +// be removed by December 23rd 2023. The recommended way to get the list of available sizes is using these +// APIs: List all available virtual machine sizes in an availability set [https://docs.microsoft.com/rest/api/compute/availabilitysets/listavailablesizes], +// List all available virtual machine sizes in a +// region [https://docs.microsoft.com/rest/api/compute/resourceskus/list], List all available virtual machine sizes for resizing +// [https://docs.microsoft.com/rest/api/compute/virtualmachines/listavailablesizes]. For more information about virtual machine +// sizes, see Sizes for virtual machines +// [https://docs.microsoft.com/azure/virtual-machines/sizes]. The available VM sizes depend on region and availability set. +type VirtualMachineSizeTypes string + +const ( + VirtualMachineSizeTypesBasicA0 VirtualMachineSizeTypes = "Basic_A0" + VirtualMachineSizeTypesBasicA1 VirtualMachineSizeTypes = "Basic_A1" + VirtualMachineSizeTypesBasicA2 VirtualMachineSizeTypes = "Basic_A2" + VirtualMachineSizeTypesBasicA3 VirtualMachineSizeTypes = "Basic_A3" + VirtualMachineSizeTypesBasicA4 VirtualMachineSizeTypes = "Basic_A4" + VirtualMachineSizeTypesStandardA0 VirtualMachineSizeTypes = "Standard_A0" + VirtualMachineSizeTypesStandardA1 VirtualMachineSizeTypes = "Standard_A1" + VirtualMachineSizeTypesStandardA10 VirtualMachineSizeTypes = "Standard_A10" + VirtualMachineSizeTypesStandardA11 VirtualMachineSizeTypes = "Standard_A11" + VirtualMachineSizeTypesStandardA1V2 VirtualMachineSizeTypes = "Standard_A1_v2" + VirtualMachineSizeTypesStandardA2 VirtualMachineSizeTypes = "Standard_A2" + VirtualMachineSizeTypesStandardA2MV2 VirtualMachineSizeTypes = "Standard_A2m_v2" + VirtualMachineSizeTypesStandardA2V2 VirtualMachineSizeTypes = "Standard_A2_v2" + VirtualMachineSizeTypesStandardA3 VirtualMachineSizeTypes = "Standard_A3" + VirtualMachineSizeTypesStandardA4 VirtualMachineSizeTypes = "Standard_A4" + VirtualMachineSizeTypesStandardA4MV2 VirtualMachineSizeTypes = "Standard_A4m_v2" + VirtualMachineSizeTypesStandardA4V2 VirtualMachineSizeTypes = "Standard_A4_v2" + VirtualMachineSizeTypesStandardA5 VirtualMachineSizeTypes = "Standard_A5" + VirtualMachineSizeTypesStandardA6 VirtualMachineSizeTypes = "Standard_A6" + VirtualMachineSizeTypesStandardA7 VirtualMachineSizeTypes = "Standard_A7" + VirtualMachineSizeTypesStandardA8 VirtualMachineSizeTypes = "Standard_A8" + VirtualMachineSizeTypesStandardA8MV2 VirtualMachineSizeTypes = "Standard_A8m_v2" + VirtualMachineSizeTypesStandardA8V2 VirtualMachineSizeTypes = "Standard_A8_v2" + VirtualMachineSizeTypesStandardA9 VirtualMachineSizeTypes = "Standard_A9" + VirtualMachineSizeTypesStandardB1Ms VirtualMachineSizeTypes = "Standard_B1ms" + VirtualMachineSizeTypesStandardB1S VirtualMachineSizeTypes = "Standard_B1s" + VirtualMachineSizeTypesStandardB2Ms VirtualMachineSizeTypes = "Standard_B2ms" + VirtualMachineSizeTypesStandardB2S VirtualMachineSizeTypes = "Standard_B2s" + VirtualMachineSizeTypesStandardB4Ms VirtualMachineSizeTypes = "Standard_B4ms" + VirtualMachineSizeTypesStandardB8Ms VirtualMachineSizeTypes = "Standard_B8ms" + VirtualMachineSizeTypesStandardD1 VirtualMachineSizeTypes = "Standard_D1" + VirtualMachineSizeTypesStandardD11 VirtualMachineSizeTypes = "Standard_D11" + VirtualMachineSizeTypesStandardD11V2 VirtualMachineSizeTypes = "Standard_D11_v2" + VirtualMachineSizeTypesStandardD12 VirtualMachineSizeTypes = "Standard_D12" + VirtualMachineSizeTypesStandardD12V2 VirtualMachineSizeTypes = "Standard_D12_v2" + VirtualMachineSizeTypesStandardD13 VirtualMachineSizeTypes = "Standard_D13" + VirtualMachineSizeTypesStandardD13V2 VirtualMachineSizeTypes = "Standard_D13_v2" + VirtualMachineSizeTypesStandardD14 VirtualMachineSizeTypes = "Standard_D14" + VirtualMachineSizeTypesStandardD14V2 VirtualMachineSizeTypes = "Standard_D14_v2" + VirtualMachineSizeTypesStandardD15V2 VirtualMachineSizeTypes = "Standard_D15_v2" + VirtualMachineSizeTypesStandardD16SV3 VirtualMachineSizeTypes = "Standard_D16s_v3" + VirtualMachineSizeTypesStandardD16V3 VirtualMachineSizeTypes = "Standard_D16_v3" + VirtualMachineSizeTypesStandardD1V2 VirtualMachineSizeTypes = "Standard_D1_v2" + VirtualMachineSizeTypesStandardD2 VirtualMachineSizeTypes = "Standard_D2" + VirtualMachineSizeTypesStandardD2SV3 VirtualMachineSizeTypes = "Standard_D2s_v3" + VirtualMachineSizeTypesStandardD2V2 VirtualMachineSizeTypes = "Standard_D2_v2" + VirtualMachineSizeTypesStandardD2V3 VirtualMachineSizeTypes = "Standard_D2_v3" + VirtualMachineSizeTypesStandardD3 VirtualMachineSizeTypes = "Standard_D3" + VirtualMachineSizeTypesStandardD32SV3 VirtualMachineSizeTypes = "Standard_D32s_v3" + VirtualMachineSizeTypesStandardD32V3 VirtualMachineSizeTypes = "Standard_D32_v3" + VirtualMachineSizeTypesStandardD3V2 VirtualMachineSizeTypes = "Standard_D3_v2" + VirtualMachineSizeTypesStandardD4 VirtualMachineSizeTypes = "Standard_D4" + VirtualMachineSizeTypesStandardD4SV3 VirtualMachineSizeTypes = "Standard_D4s_v3" + VirtualMachineSizeTypesStandardD4V2 VirtualMachineSizeTypes = "Standard_D4_v2" + VirtualMachineSizeTypesStandardD4V3 VirtualMachineSizeTypes = "Standard_D4_v3" + VirtualMachineSizeTypesStandardD5V2 VirtualMachineSizeTypes = "Standard_D5_v2" + VirtualMachineSizeTypesStandardD64SV3 VirtualMachineSizeTypes = "Standard_D64s_v3" + VirtualMachineSizeTypesStandardD64V3 VirtualMachineSizeTypes = "Standard_D64_v3" + VirtualMachineSizeTypesStandardD8SV3 VirtualMachineSizeTypes = "Standard_D8s_v3" + VirtualMachineSizeTypesStandardD8V3 VirtualMachineSizeTypes = "Standard_D8_v3" + VirtualMachineSizeTypesStandardDS1 VirtualMachineSizeTypes = "Standard_DS1" + VirtualMachineSizeTypesStandardDS11 VirtualMachineSizeTypes = "Standard_DS11" + VirtualMachineSizeTypesStandardDS11V2 VirtualMachineSizeTypes = "Standard_DS11_v2" + VirtualMachineSizeTypesStandardDS12 VirtualMachineSizeTypes = "Standard_DS12" + VirtualMachineSizeTypesStandardDS12V2 VirtualMachineSizeTypes = "Standard_DS12_v2" + VirtualMachineSizeTypesStandardDS13 VirtualMachineSizeTypes = "Standard_DS13" + VirtualMachineSizeTypesStandardDS132V2 VirtualMachineSizeTypes = "Standard_DS13-2_v2" + VirtualMachineSizeTypesStandardDS134V2 VirtualMachineSizeTypes = "Standard_DS13-4_v2" + VirtualMachineSizeTypesStandardDS13V2 VirtualMachineSizeTypes = "Standard_DS13_v2" + VirtualMachineSizeTypesStandardDS14 VirtualMachineSizeTypes = "Standard_DS14" + VirtualMachineSizeTypesStandardDS144V2 VirtualMachineSizeTypes = "Standard_DS14-4_v2" + VirtualMachineSizeTypesStandardDS148V2 VirtualMachineSizeTypes = "Standard_DS14-8_v2" + VirtualMachineSizeTypesStandardDS14V2 VirtualMachineSizeTypes = "Standard_DS14_v2" + VirtualMachineSizeTypesStandardDS15V2 VirtualMachineSizeTypes = "Standard_DS15_v2" + VirtualMachineSizeTypesStandardDS1V2 VirtualMachineSizeTypes = "Standard_DS1_v2" + VirtualMachineSizeTypesStandardDS2 VirtualMachineSizeTypes = "Standard_DS2" + VirtualMachineSizeTypesStandardDS2V2 VirtualMachineSizeTypes = "Standard_DS2_v2" + VirtualMachineSizeTypesStandardDS3 VirtualMachineSizeTypes = "Standard_DS3" + VirtualMachineSizeTypesStandardDS3V2 VirtualMachineSizeTypes = "Standard_DS3_v2" + VirtualMachineSizeTypesStandardDS4 VirtualMachineSizeTypes = "Standard_DS4" + VirtualMachineSizeTypesStandardDS4V2 VirtualMachineSizeTypes = "Standard_DS4_v2" + VirtualMachineSizeTypesStandardDS5V2 VirtualMachineSizeTypes = "Standard_DS5_v2" + VirtualMachineSizeTypesStandardE16SV3 VirtualMachineSizeTypes = "Standard_E16s_v3" + VirtualMachineSizeTypesStandardE16V3 VirtualMachineSizeTypes = "Standard_E16_v3" + VirtualMachineSizeTypesStandardE2SV3 VirtualMachineSizeTypes = "Standard_E2s_v3" + VirtualMachineSizeTypesStandardE2V3 VirtualMachineSizeTypes = "Standard_E2_v3" + VirtualMachineSizeTypesStandardE3216V3 VirtualMachineSizeTypes = "Standard_E32-16_v3" + VirtualMachineSizeTypesStandardE328SV3 VirtualMachineSizeTypes = "Standard_E32-8s_v3" + VirtualMachineSizeTypesStandardE32SV3 VirtualMachineSizeTypes = "Standard_E32s_v3" + VirtualMachineSizeTypesStandardE32V3 VirtualMachineSizeTypes = "Standard_E32_v3" + VirtualMachineSizeTypesStandardE4SV3 VirtualMachineSizeTypes = "Standard_E4s_v3" + VirtualMachineSizeTypesStandardE4V3 VirtualMachineSizeTypes = "Standard_E4_v3" + VirtualMachineSizeTypesStandardE6416SV3 VirtualMachineSizeTypes = "Standard_E64-16s_v3" + VirtualMachineSizeTypesStandardE6432SV3 VirtualMachineSizeTypes = "Standard_E64-32s_v3" + VirtualMachineSizeTypesStandardE64SV3 VirtualMachineSizeTypes = "Standard_E64s_v3" + VirtualMachineSizeTypesStandardE64V3 VirtualMachineSizeTypes = "Standard_E64_v3" + VirtualMachineSizeTypesStandardE8SV3 VirtualMachineSizeTypes = "Standard_E8s_v3" + VirtualMachineSizeTypesStandardE8V3 VirtualMachineSizeTypes = "Standard_E8_v3" + VirtualMachineSizeTypesStandardF1 VirtualMachineSizeTypes = "Standard_F1" + VirtualMachineSizeTypesStandardF16 VirtualMachineSizeTypes = "Standard_F16" + VirtualMachineSizeTypesStandardF16S VirtualMachineSizeTypes = "Standard_F16s" + VirtualMachineSizeTypesStandardF16SV2 VirtualMachineSizeTypes = "Standard_F16s_v2" + VirtualMachineSizeTypesStandardF1S VirtualMachineSizeTypes = "Standard_F1s" + VirtualMachineSizeTypesStandardF2 VirtualMachineSizeTypes = "Standard_F2" + VirtualMachineSizeTypesStandardF2S VirtualMachineSizeTypes = "Standard_F2s" + VirtualMachineSizeTypesStandardF2SV2 VirtualMachineSizeTypes = "Standard_F2s_v2" + VirtualMachineSizeTypesStandardF32SV2 VirtualMachineSizeTypes = "Standard_F32s_v2" + VirtualMachineSizeTypesStandardF4 VirtualMachineSizeTypes = "Standard_F4" + VirtualMachineSizeTypesStandardF4S VirtualMachineSizeTypes = "Standard_F4s" + VirtualMachineSizeTypesStandardF4SV2 VirtualMachineSizeTypes = "Standard_F4s_v2" + VirtualMachineSizeTypesStandardF64SV2 VirtualMachineSizeTypes = "Standard_F64s_v2" + VirtualMachineSizeTypesStandardF72SV2 VirtualMachineSizeTypes = "Standard_F72s_v2" + VirtualMachineSizeTypesStandardF8 VirtualMachineSizeTypes = "Standard_F8" + VirtualMachineSizeTypesStandardF8S VirtualMachineSizeTypes = "Standard_F8s" + VirtualMachineSizeTypesStandardF8SV2 VirtualMachineSizeTypes = "Standard_F8s_v2" + VirtualMachineSizeTypesStandardG1 VirtualMachineSizeTypes = "Standard_G1" + VirtualMachineSizeTypesStandardG2 VirtualMachineSizeTypes = "Standard_G2" + VirtualMachineSizeTypesStandardG3 VirtualMachineSizeTypes = "Standard_G3" + VirtualMachineSizeTypesStandardG4 VirtualMachineSizeTypes = "Standard_G4" + VirtualMachineSizeTypesStandardG5 VirtualMachineSizeTypes = "Standard_G5" + VirtualMachineSizeTypesStandardGS1 VirtualMachineSizeTypes = "Standard_GS1" + VirtualMachineSizeTypesStandardGS2 VirtualMachineSizeTypes = "Standard_GS2" + VirtualMachineSizeTypesStandardGS3 VirtualMachineSizeTypes = "Standard_GS3" + VirtualMachineSizeTypesStandardGS4 VirtualMachineSizeTypes = "Standard_GS4" + VirtualMachineSizeTypesStandardGS44 VirtualMachineSizeTypes = "Standard_GS4-4" + VirtualMachineSizeTypesStandardGS48 VirtualMachineSizeTypes = "Standard_GS4-8" + VirtualMachineSizeTypesStandardGS5 VirtualMachineSizeTypes = "Standard_GS5" + VirtualMachineSizeTypesStandardGS516 VirtualMachineSizeTypes = "Standard_GS5-16" + VirtualMachineSizeTypesStandardGS58 VirtualMachineSizeTypes = "Standard_GS5-8" + VirtualMachineSizeTypesStandardH16 VirtualMachineSizeTypes = "Standard_H16" + VirtualMachineSizeTypesStandardH16M VirtualMachineSizeTypes = "Standard_H16m" + VirtualMachineSizeTypesStandardH16Mr VirtualMachineSizeTypes = "Standard_H16mr" + VirtualMachineSizeTypesStandardH16R VirtualMachineSizeTypes = "Standard_H16r" + VirtualMachineSizeTypesStandardH8 VirtualMachineSizeTypes = "Standard_H8" + VirtualMachineSizeTypesStandardH8M VirtualMachineSizeTypes = "Standard_H8m" + VirtualMachineSizeTypesStandardL16S VirtualMachineSizeTypes = "Standard_L16s" + VirtualMachineSizeTypesStandardL32S VirtualMachineSizeTypes = "Standard_L32s" + VirtualMachineSizeTypesStandardL4S VirtualMachineSizeTypes = "Standard_L4s" + VirtualMachineSizeTypesStandardL8S VirtualMachineSizeTypes = "Standard_L8s" + VirtualMachineSizeTypesStandardM12832Ms VirtualMachineSizeTypes = "Standard_M128-32ms" + VirtualMachineSizeTypesStandardM12864Ms VirtualMachineSizeTypes = "Standard_M128-64ms" + VirtualMachineSizeTypesStandardM128Ms VirtualMachineSizeTypes = "Standard_M128ms" + VirtualMachineSizeTypesStandardM128S VirtualMachineSizeTypes = "Standard_M128s" + VirtualMachineSizeTypesStandardM6416Ms VirtualMachineSizeTypes = "Standard_M64-16ms" + VirtualMachineSizeTypesStandardM6432Ms VirtualMachineSizeTypes = "Standard_M64-32ms" + VirtualMachineSizeTypesStandardM64Ms VirtualMachineSizeTypes = "Standard_M64ms" + VirtualMachineSizeTypesStandardM64S VirtualMachineSizeTypes = "Standard_M64s" + VirtualMachineSizeTypesStandardNC12 VirtualMachineSizeTypes = "Standard_NC12" + VirtualMachineSizeTypesStandardNC12SV2 VirtualMachineSizeTypes = "Standard_NC12s_v2" + VirtualMachineSizeTypesStandardNC12SV3 VirtualMachineSizeTypes = "Standard_NC12s_v3" + VirtualMachineSizeTypesStandardNC24 VirtualMachineSizeTypes = "Standard_NC24" + VirtualMachineSizeTypesStandardNC24R VirtualMachineSizeTypes = "Standard_NC24r" + VirtualMachineSizeTypesStandardNC24RsV2 VirtualMachineSizeTypes = "Standard_NC24rs_v2" + VirtualMachineSizeTypesStandardNC24RsV3 VirtualMachineSizeTypes = "Standard_NC24rs_v3" + VirtualMachineSizeTypesStandardNC24SV2 VirtualMachineSizeTypes = "Standard_NC24s_v2" + VirtualMachineSizeTypesStandardNC24SV3 VirtualMachineSizeTypes = "Standard_NC24s_v3" + VirtualMachineSizeTypesStandardNC6 VirtualMachineSizeTypes = "Standard_NC6" + VirtualMachineSizeTypesStandardNC6SV2 VirtualMachineSizeTypes = "Standard_NC6s_v2" + VirtualMachineSizeTypesStandardNC6SV3 VirtualMachineSizeTypes = "Standard_NC6s_v3" + VirtualMachineSizeTypesStandardND12S VirtualMachineSizeTypes = "Standard_ND12s" + VirtualMachineSizeTypesStandardND24Rs VirtualMachineSizeTypes = "Standard_ND24rs" + VirtualMachineSizeTypesStandardND24S VirtualMachineSizeTypes = "Standard_ND24s" + VirtualMachineSizeTypesStandardND6S VirtualMachineSizeTypes = "Standard_ND6s" + VirtualMachineSizeTypesStandardNV12 VirtualMachineSizeTypes = "Standard_NV12" + VirtualMachineSizeTypesStandardNV24 VirtualMachineSizeTypes = "Standard_NV24" + VirtualMachineSizeTypesStandardNV6 VirtualMachineSizeTypes = "Standard_NV6" +) + +// PossibleVirtualMachineSizeTypesValues returns the possible values for the VirtualMachineSizeTypes const type. +func PossibleVirtualMachineSizeTypesValues() []VirtualMachineSizeTypes { + return []VirtualMachineSizeTypes{ + VirtualMachineSizeTypesBasicA0, + VirtualMachineSizeTypesBasicA1, + VirtualMachineSizeTypesBasicA2, + VirtualMachineSizeTypesBasicA3, + VirtualMachineSizeTypesBasicA4, + VirtualMachineSizeTypesStandardA0, + VirtualMachineSizeTypesStandardA1, + VirtualMachineSizeTypesStandardA10, + VirtualMachineSizeTypesStandardA11, + VirtualMachineSizeTypesStandardA1V2, + VirtualMachineSizeTypesStandardA2, + VirtualMachineSizeTypesStandardA2MV2, + VirtualMachineSizeTypesStandardA2V2, + VirtualMachineSizeTypesStandardA3, + VirtualMachineSizeTypesStandardA4, + VirtualMachineSizeTypesStandardA4MV2, + VirtualMachineSizeTypesStandardA4V2, + VirtualMachineSizeTypesStandardA5, + VirtualMachineSizeTypesStandardA6, + VirtualMachineSizeTypesStandardA7, + VirtualMachineSizeTypesStandardA8, + VirtualMachineSizeTypesStandardA8MV2, + VirtualMachineSizeTypesStandardA8V2, + VirtualMachineSizeTypesStandardA9, + VirtualMachineSizeTypesStandardB1Ms, + VirtualMachineSizeTypesStandardB1S, + VirtualMachineSizeTypesStandardB2Ms, + VirtualMachineSizeTypesStandardB2S, + VirtualMachineSizeTypesStandardB4Ms, + VirtualMachineSizeTypesStandardB8Ms, + VirtualMachineSizeTypesStandardD1, + VirtualMachineSizeTypesStandardD11, + VirtualMachineSizeTypesStandardD11V2, + VirtualMachineSizeTypesStandardD12, + VirtualMachineSizeTypesStandardD12V2, + VirtualMachineSizeTypesStandardD13, + VirtualMachineSizeTypesStandardD13V2, + VirtualMachineSizeTypesStandardD14, + VirtualMachineSizeTypesStandardD14V2, + VirtualMachineSizeTypesStandardD15V2, + VirtualMachineSizeTypesStandardD16SV3, + VirtualMachineSizeTypesStandardD16V3, + VirtualMachineSizeTypesStandardD1V2, + VirtualMachineSizeTypesStandardD2, + VirtualMachineSizeTypesStandardD2SV3, + VirtualMachineSizeTypesStandardD2V2, + VirtualMachineSizeTypesStandardD2V3, + VirtualMachineSizeTypesStandardD3, + VirtualMachineSizeTypesStandardD32SV3, + VirtualMachineSizeTypesStandardD32V3, + VirtualMachineSizeTypesStandardD3V2, + VirtualMachineSizeTypesStandardD4, + VirtualMachineSizeTypesStandardD4SV3, + VirtualMachineSizeTypesStandardD4V2, + VirtualMachineSizeTypesStandardD4V3, + VirtualMachineSizeTypesStandardD5V2, + VirtualMachineSizeTypesStandardD64SV3, + VirtualMachineSizeTypesStandardD64V3, + VirtualMachineSizeTypesStandardD8SV3, + VirtualMachineSizeTypesStandardD8V3, + VirtualMachineSizeTypesStandardDS1, + VirtualMachineSizeTypesStandardDS11, + VirtualMachineSizeTypesStandardDS11V2, + VirtualMachineSizeTypesStandardDS12, + VirtualMachineSizeTypesStandardDS12V2, + VirtualMachineSizeTypesStandardDS13, + VirtualMachineSizeTypesStandardDS132V2, + VirtualMachineSizeTypesStandardDS134V2, + VirtualMachineSizeTypesStandardDS13V2, + VirtualMachineSizeTypesStandardDS14, + VirtualMachineSizeTypesStandardDS144V2, + VirtualMachineSizeTypesStandardDS148V2, + VirtualMachineSizeTypesStandardDS14V2, + VirtualMachineSizeTypesStandardDS15V2, + VirtualMachineSizeTypesStandardDS1V2, + VirtualMachineSizeTypesStandardDS2, + VirtualMachineSizeTypesStandardDS2V2, + VirtualMachineSizeTypesStandardDS3, + VirtualMachineSizeTypesStandardDS3V2, + VirtualMachineSizeTypesStandardDS4, + VirtualMachineSizeTypesStandardDS4V2, + VirtualMachineSizeTypesStandardDS5V2, + VirtualMachineSizeTypesStandardE16SV3, + VirtualMachineSizeTypesStandardE16V3, + VirtualMachineSizeTypesStandardE2SV3, + VirtualMachineSizeTypesStandardE2V3, + VirtualMachineSizeTypesStandardE3216V3, + VirtualMachineSizeTypesStandardE328SV3, + VirtualMachineSizeTypesStandardE32SV3, + VirtualMachineSizeTypesStandardE32V3, + VirtualMachineSizeTypesStandardE4SV3, + VirtualMachineSizeTypesStandardE4V3, + VirtualMachineSizeTypesStandardE6416SV3, + VirtualMachineSizeTypesStandardE6432SV3, + VirtualMachineSizeTypesStandardE64SV3, + VirtualMachineSizeTypesStandardE64V3, + VirtualMachineSizeTypesStandardE8SV3, + VirtualMachineSizeTypesStandardE8V3, + VirtualMachineSizeTypesStandardF1, + VirtualMachineSizeTypesStandardF16, + VirtualMachineSizeTypesStandardF16S, + VirtualMachineSizeTypesStandardF16SV2, + VirtualMachineSizeTypesStandardF1S, + VirtualMachineSizeTypesStandardF2, + VirtualMachineSizeTypesStandardF2S, + VirtualMachineSizeTypesStandardF2SV2, + VirtualMachineSizeTypesStandardF32SV2, + VirtualMachineSizeTypesStandardF4, + VirtualMachineSizeTypesStandardF4S, + VirtualMachineSizeTypesStandardF4SV2, + VirtualMachineSizeTypesStandardF64SV2, + VirtualMachineSizeTypesStandardF72SV2, + VirtualMachineSizeTypesStandardF8, + VirtualMachineSizeTypesStandardF8S, + VirtualMachineSizeTypesStandardF8SV2, + VirtualMachineSizeTypesStandardG1, + VirtualMachineSizeTypesStandardG2, + VirtualMachineSizeTypesStandardG3, + VirtualMachineSizeTypesStandardG4, + VirtualMachineSizeTypesStandardG5, + VirtualMachineSizeTypesStandardGS1, + VirtualMachineSizeTypesStandardGS2, + VirtualMachineSizeTypesStandardGS3, + VirtualMachineSizeTypesStandardGS4, + VirtualMachineSizeTypesStandardGS44, + VirtualMachineSizeTypesStandardGS48, + VirtualMachineSizeTypesStandardGS5, + VirtualMachineSizeTypesStandardGS516, + VirtualMachineSizeTypesStandardGS58, + VirtualMachineSizeTypesStandardH16, + VirtualMachineSizeTypesStandardH16M, + VirtualMachineSizeTypesStandardH16Mr, + VirtualMachineSizeTypesStandardH16R, + VirtualMachineSizeTypesStandardH8, + VirtualMachineSizeTypesStandardH8M, + VirtualMachineSizeTypesStandardL16S, + VirtualMachineSizeTypesStandardL32S, + VirtualMachineSizeTypesStandardL4S, + VirtualMachineSizeTypesStandardL8S, + VirtualMachineSizeTypesStandardM12832Ms, + VirtualMachineSizeTypesStandardM12864Ms, + VirtualMachineSizeTypesStandardM128Ms, + VirtualMachineSizeTypesStandardM128S, + VirtualMachineSizeTypesStandardM6416Ms, + VirtualMachineSizeTypesStandardM6432Ms, + VirtualMachineSizeTypesStandardM64Ms, + VirtualMachineSizeTypesStandardM64S, + VirtualMachineSizeTypesStandardNC12, + VirtualMachineSizeTypesStandardNC12SV2, + VirtualMachineSizeTypesStandardNC12SV3, + VirtualMachineSizeTypesStandardNC24, + VirtualMachineSizeTypesStandardNC24R, + VirtualMachineSizeTypesStandardNC24RsV2, + VirtualMachineSizeTypesStandardNC24RsV3, + VirtualMachineSizeTypesStandardNC24SV2, + VirtualMachineSizeTypesStandardNC24SV3, + VirtualMachineSizeTypesStandardNC6, + VirtualMachineSizeTypesStandardNC6SV2, + VirtualMachineSizeTypesStandardNC6SV3, + VirtualMachineSizeTypesStandardND12S, + VirtualMachineSizeTypesStandardND24Rs, + VirtualMachineSizeTypesStandardND24S, + VirtualMachineSizeTypesStandardND6S, + VirtualMachineSizeTypesStandardNV12, + VirtualMachineSizeTypesStandardNV24, + VirtualMachineSizeTypesStandardNV6, + } +} + +// WindowsPatchAssessmentMode - Specifies the mode of VM Guest patch assessment for the IaaS virtual machine. +// Possible values are: +// ImageDefault - You control the timing of patch assessments on a virtual machine. +// AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true. +type WindowsPatchAssessmentMode string + +const ( + WindowsPatchAssessmentModeAutomaticByPlatform WindowsPatchAssessmentMode = "AutomaticByPlatform" + WindowsPatchAssessmentModeImageDefault WindowsPatchAssessmentMode = "ImageDefault" +) + +// PossibleWindowsPatchAssessmentModeValues returns the possible values for the WindowsPatchAssessmentMode const type. +func PossibleWindowsPatchAssessmentModeValues() []WindowsPatchAssessmentMode { + return []WindowsPatchAssessmentMode{ + WindowsPatchAssessmentModeAutomaticByPlatform, + WindowsPatchAssessmentModeImageDefault, + } +} + +// WindowsVMGuestPatchAutomaticByPlatformRebootSetting - Specifies the reboot setting for all AutomaticByPlatform patch installation +// operations. +type WindowsVMGuestPatchAutomaticByPlatformRebootSetting string + +const ( + WindowsVMGuestPatchAutomaticByPlatformRebootSettingAlways WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "Always" + WindowsVMGuestPatchAutomaticByPlatformRebootSettingIfRequired WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "IfRequired" + WindowsVMGuestPatchAutomaticByPlatformRebootSettingNever WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "Never" + WindowsVMGuestPatchAutomaticByPlatformRebootSettingUnknown WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "Unknown" +) + +// PossibleWindowsVMGuestPatchAutomaticByPlatformRebootSettingValues returns the possible values for the WindowsVMGuestPatchAutomaticByPlatformRebootSetting const type. +func PossibleWindowsVMGuestPatchAutomaticByPlatformRebootSettingValues() []WindowsVMGuestPatchAutomaticByPlatformRebootSetting { + return []WindowsVMGuestPatchAutomaticByPlatformRebootSetting{ + WindowsVMGuestPatchAutomaticByPlatformRebootSettingAlways, + WindowsVMGuestPatchAutomaticByPlatformRebootSettingIfRequired, + WindowsVMGuestPatchAutomaticByPlatformRebootSettingNever, + WindowsVMGuestPatchAutomaticByPlatformRebootSettingUnknown, + } +} + +// WindowsVMGuestPatchMode - Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated +// to virtual machine scale set with OrchestrationMode as Flexible. +// Possible values are: +// Manual - You control the application of patches to a virtual machine. You do this by applying patches manually inside the +// VM. In this mode, automatic updates are disabled; the property +// WindowsConfiguration.enableAutomaticUpdates must be false +// AutomaticByOS - The virtual machine will automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates +// must be true. +// AutomaticByPlatform - the virtual machine will automatically updated by the platform. The properties provisionVMAgent and +// WindowsConfiguration.enableAutomaticUpdates must be true +type WindowsVMGuestPatchMode string + +const ( + WindowsVMGuestPatchModeAutomaticByOS WindowsVMGuestPatchMode = "AutomaticByOS" + WindowsVMGuestPatchModeAutomaticByPlatform WindowsVMGuestPatchMode = "AutomaticByPlatform" + WindowsVMGuestPatchModeManual WindowsVMGuestPatchMode = "Manual" +) + +// PossibleWindowsVMGuestPatchModeValues returns the possible values for the WindowsVMGuestPatchMode const type. +func PossibleWindowsVMGuestPatchModeValues() []WindowsVMGuestPatchMode { + return []WindowsVMGuestPatchMode{ + WindowsVMGuestPatchModeAutomaticByOS, + WindowsVMGuestPatchModeAutomaticByPlatform, + WindowsVMGuestPatchModeManual, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/dedicatedhostgroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/dedicatedhostgroups_client.go new file mode 100644 index 000000000..99434bfab --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/dedicatedhostgroups_client.go @@ -0,0 +1,423 @@ +//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 armcompute + +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" +) + +// DedicatedHostGroupsClient contains the methods for the DedicatedHostGroups group. +// Don't use this type directly, use NewDedicatedHostGroupsClient() instead. +type DedicatedHostGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDedicatedHostGroupsClient creates a new instance of DedicatedHostGroupsClient 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 NewDedicatedHostGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DedicatedHostGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DedicatedHostGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create or update a dedicated host group. For details of Dedicated Host and Dedicated Host Groups please +// see Dedicated Host Documentation [https://go.microsoft.com/fwlink/?linkid=2082596] +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - parameters - Parameters supplied to the Create Dedicated Host Group. +// - options - DedicatedHostGroupsClientCreateOrUpdateOptions contains the optional parameters for the DedicatedHostGroupsClient.CreateOrUpdate +// method. +func (client *DedicatedHostGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroup, options *DedicatedHostGroupsClientCreateOrUpdateOptions) (DedicatedHostGroupsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "DedicatedHostGroupsClient.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, hostGroupName, parameters, options) + if err != nil { + return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DedicatedHostGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroup, options *DedicatedHostGroupsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + 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-09-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 *DedicatedHostGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (DedicatedHostGroupsClientCreateOrUpdateResponse, error) { + result := DedicatedHostGroupsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroup); err != nil { + return DedicatedHostGroupsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a dedicated host group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - options - DedicatedHostGroupsClientDeleteOptions contains the optional parameters for the DedicatedHostGroupsClient.Delete +// method. +func (client *DedicatedHostGroupsClient) Delete(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientDeleteOptions) (DedicatedHostGroupsClientDeleteResponse, error) { + var err error + const operationName = "DedicatedHostGroupsClient.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, hostGroupName, options) + if err != nil { + return DedicatedHostGroupsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DedicatedHostGroupsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DedicatedHostGroupsClientDeleteResponse{}, err + } + return DedicatedHostGroupsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DedicatedHostGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a dedicated host group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - options - DedicatedHostGroupsClientGetOptions contains the optional parameters for the DedicatedHostGroupsClient.Get method. +func (client *DedicatedHostGroupsClient) Get(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientGetOptions) (DedicatedHostGroupsClientGetResponse, error) { + var err error + const operationName = "DedicatedHostGroupsClient.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, hostGroupName, options) + if err != nil { + return DedicatedHostGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DedicatedHostGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DedicatedHostGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DedicatedHostGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DedicatedHostGroupsClient) getHandleResponse(resp *http.Response) (DedicatedHostGroupsClientGetResponse, error) { + result := DedicatedHostGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroup); err != nil { + return DedicatedHostGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all of the dedicated host groups in the specified resource group. Use the nextLink +// property in the response to get the next page of dedicated host groups. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - DedicatedHostGroupsClientListByResourceGroupOptions contains the optional parameters for the DedicatedHostGroupsClient.NewListByResourceGroupPager +// method. +func (client *DedicatedHostGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *DedicatedHostGroupsClientListByResourceGroupOptions) *runtime.Pager[DedicatedHostGroupsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DedicatedHostGroupsClientListByResourceGroupResponse]{ + More: func(page DedicatedHostGroupsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DedicatedHostGroupsClientListByResourceGroupResponse) (DedicatedHostGroupsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostGroupsClient.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 DedicatedHostGroupsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *DedicatedHostGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DedicatedHostGroupsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *DedicatedHostGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (DedicatedHostGroupsClientListByResourceGroupResponse, error) { + result := DedicatedHostGroupsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroupListResult); err != nil { + return DedicatedHostGroupsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists all of the dedicated host groups in the subscription. Use the nextLink property in the +// response to get the next page of dedicated host groups. +// +// Generated from API version 2023-09-01 +// - options - DedicatedHostGroupsClientListBySubscriptionOptions contains the optional parameters for the DedicatedHostGroupsClient.NewListBySubscriptionPager +// method. +func (client *DedicatedHostGroupsClient) NewListBySubscriptionPager(options *DedicatedHostGroupsClientListBySubscriptionOptions) *runtime.Pager[DedicatedHostGroupsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[DedicatedHostGroupsClientListBySubscriptionResponse]{ + More: func(page DedicatedHostGroupsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DedicatedHostGroupsClientListBySubscriptionResponse) (DedicatedHostGroupsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostGroupsClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return DedicatedHostGroupsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *DedicatedHostGroupsClient) listBySubscriptionCreateRequest(ctx context.Context, options *DedicatedHostGroupsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/hostGroups" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *DedicatedHostGroupsClient) listBySubscriptionHandleResponse(resp *http.Response) (DedicatedHostGroupsClientListBySubscriptionResponse, error) { + result := DedicatedHostGroupsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroupListResult); err != nil { + return DedicatedHostGroupsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Update an dedicated host group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - parameters - Parameters supplied to the Update Dedicated Host Group operation. +// - options - DedicatedHostGroupsClientUpdateOptions contains the optional parameters for the DedicatedHostGroupsClient.Update +// method. +func (client *DedicatedHostGroupsClient) Update(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroupUpdate, options *DedicatedHostGroupsClientUpdateOptions) (DedicatedHostGroupsClientUpdateResponse, error) { + var err error + const operationName = "DedicatedHostGroupsClient.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, hostGroupName, parameters, options) + if err != nil { + return DedicatedHostGroupsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DedicatedHostGroupsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DedicatedHostGroupsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *DedicatedHostGroupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, parameters DedicatedHostGroupUpdate, options *DedicatedHostGroupsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + 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-09-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 *DedicatedHostGroupsClient) updateHandleResponse(resp *http.Response) (DedicatedHostGroupsClientUpdateResponse, error) { + result := DedicatedHostGroupsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostGroup); err != nil { + return DedicatedHostGroupsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/dedicatedhosts_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/dedicatedhosts_client.go new file mode 100644 index 000000000..b50a3ec65 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/dedicatedhosts_client.go @@ -0,0 +1,680 @@ +//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 armcompute + +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" +) + +// DedicatedHostsClient contains the methods for the DedicatedHosts group. +// Don't use this type directly, use NewDedicatedHostsClient() instead. +type DedicatedHostsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDedicatedHostsClient creates a new instance of DedicatedHostsClient 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 NewDedicatedHostsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DedicatedHostsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DedicatedHostsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a dedicated host . +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - hostName - The name of the dedicated host . +// - parameters - Parameters supplied to the Create Dedicated Host. +// - options - DedicatedHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the DedicatedHostsClient.BeginCreateOrUpdate +// method. +func (client *DedicatedHostsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHost, options *DedicatedHostsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DedicatedHostsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, hostGroupName, hostName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a dedicated host . +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *DedicatedHostsClient) createOrUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHost, options *DedicatedHostsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHostsClient.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, hostGroupName, hostName, 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 *DedicatedHostsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHost, options *DedicatedHostsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + if hostName == "" { + return nil, errors.New("parameter hostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName)) + 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-09-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 - Delete a dedicated host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - hostName - The name of the dedicated host. +// - options - DedicatedHostsClientBeginDeleteOptions contains the optional parameters for the DedicatedHostsClient.BeginDelete +// method. +func (client *DedicatedHostsClient) BeginDelete(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginDeleteOptions) (*runtime.Poller[DedicatedHostsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, hostGroupName, hostName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a dedicated host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *DedicatedHostsClient) deleteOperation(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHostsClient.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, hostGroupName, hostName, 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 *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + if hostName == "" { + return nil, errors.New("parameter hostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a dedicated host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - hostName - The name of the dedicated host. +// - options - DedicatedHostsClientGetOptions contains the optional parameters for the DedicatedHostsClient.Get method. +func (client *DedicatedHostsClient) Get(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientGetOptions) (DedicatedHostsClientGetResponse, error) { + var err error + const operationName = "DedicatedHostsClient.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, hostGroupName, hostName, options) + if err != nil { + return DedicatedHostsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DedicatedHostsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DedicatedHostsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DedicatedHostsClient) getCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + if hostName == "" { + return nil, errors.New("parameter hostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DedicatedHostsClient) getHandleResponse(resp *http.Response) (DedicatedHostsClientGetResponse, error) { + result := DedicatedHostsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHost); err != nil { + return DedicatedHostsClientGetResponse{}, err + } + return result, nil +} + +// NewListAvailableSizesPager - Lists all available dedicated host sizes to which the specified dedicated host can be resized. +// NOTE: The dedicated host sizes provided can be used to only scale up the existing dedicated host. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - hostName - The name of the dedicated host. +// - options - DedicatedHostsClientListAvailableSizesOptions contains the optional parameters for the DedicatedHostsClient.NewListAvailableSizesPager +// method. +func (client *DedicatedHostsClient) NewListAvailableSizesPager(resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientListAvailableSizesOptions) *runtime.Pager[DedicatedHostsClientListAvailableSizesResponse] { + return runtime.NewPager(runtime.PagingHandler[DedicatedHostsClientListAvailableSizesResponse]{ + More: func(page DedicatedHostsClientListAvailableSizesResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *DedicatedHostsClientListAvailableSizesResponse) (DedicatedHostsClientListAvailableSizesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostsClient.NewListAvailableSizesPager") + req, err := client.listAvailableSizesCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, options) + if err != nil { + return DedicatedHostsClientListAvailableSizesResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DedicatedHostsClientListAvailableSizesResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return DedicatedHostsClientListAvailableSizesResponse{}, runtime.NewResponseError(resp) + } + return client.listAvailableSizesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAvailableSizesCreateRequest creates the ListAvailableSizes request. +func (client *DedicatedHostsClient) listAvailableSizesCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientListAvailableSizesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}/hostSizes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + if hostName == "" { + return nil, errors.New("parameter hostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableSizesHandleResponse handles the ListAvailableSizes response. +func (client *DedicatedHostsClient) listAvailableSizesHandleResponse(resp *http.Response) (DedicatedHostsClientListAvailableSizesResponse, error) { + result := DedicatedHostsClientListAvailableSizesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostSizeListResult); err != nil { + return DedicatedHostsClientListAvailableSizesResponse{}, err + } + return result, nil +} + +// NewListByHostGroupPager - Lists all of the dedicated hosts in the specified dedicated host group. Use the nextLink property +// in the response to get the next page of dedicated hosts. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - options - DedicatedHostsClientListByHostGroupOptions contains the optional parameters for the DedicatedHostsClient.NewListByHostGroupPager +// method. +func (client *DedicatedHostsClient) NewListByHostGroupPager(resourceGroupName string, hostGroupName string, options *DedicatedHostsClientListByHostGroupOptions) *runtime.Pager[DedicatedHostsClientListByHostGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DedicatedHostsClientListByHostGroupResponse]{ + More: func(page DedicatedHostsClientListByHostGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DedicatedHostsClientListByHostGroupResponse) (DedicatedHostsClientListByHostGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHostsClient.NewListByHostGroupPager") + 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.listByHostGroupCreateRequest(ctx, resourceGroupName, hostGroupName, options) + }, nil) + if err != nil { + return DedicatedHostsClientListByHostGroupResponse{}, err + } + return client.listByHostGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByHostGroupCreateRequest creates the ListByHostGroup request. +func (client *DedicatedHostsClient) listByHostGroupCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, options *DedicatedHostsClientListByHostGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByHostGroupHandleResponse handles the ListByHostGroup response. +func (client *DedicatedHostsClient) listByHostGroupHandleResponse(resp *http.Response) (DedicatedHostsClientListByHostGroupResponse, error) { + result := DedicatedHostsClientListByHostGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHostListResult); err != nil { + return DedicatedHostsClientListByHostGroupResponse{}, err + } + return result, nil +} + +// BeginRedeploy - Redeploy the dedicated host. The operation will complete successfully once the dedicated host has migrated +// to a new node and is running. To determine the health of VMs deployed on the dedicated host +// after the redeploy check the Resource Health Center in the Azure Portal. Please refer to https://docs.microsoft.com/azure/service-health/resource-health-overview +// for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - hostName - The name of the dedicated host. +// - options - DedicatedHostsClientBeginRedeployOptions contains the optional parameters for the DedicatedHostsClient.BeginRedeploy +// method. +func (client *DedicatedHostsClient) BeginRedeploy(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRedeployOptions) (*runtime.Poller[DedicatedHostsClientRedeployResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.redeploy(ctx, resourceGroupName, hostGroupName, hostName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Redeploy - Redeploy the dedicated host. The operation will complete successfully once the dedicated host has migrated to +// a new node and is running. To determine the health of VMs deployed on the dedicated host +// after the redeploy check the Resource Health Center in the Azure Portal. Please refer to https://docs.microsoft.com/azure/service-health/resource-health-overview +// for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *DedicatedHostsClient) redeploy(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRedeployOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHostsClient.BeginRedeploy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.redeployCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, 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 +} + +// redeployCreateRequest creates the Redeploy request. +func (client *DedicatedHostsClient) redeployCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRedeployOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}/redeploy" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + if hostName == "" { + return nil, errors.New("parameter hostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginRestart - Restart the dedicated host. The operation will complete successfully once the dedicated host has restarted +// and is running. To determine the health of VMs deployed on the dedicated host after the +// restart check the Resource Health Center in the Azure Portal. Please refer to https://docs.microsoft.com/azure/service-health/resource-health-overview +// for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - hostName - The name of the dedicated host. +// - options - DedicatedHostsClientBeginRestartOptions contains the optional parameters for the DedicatedHostsClient.BeginRestart +// method. +func (client *DedicatedHostsClient) BeginRestart(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRestartOptions) (*runtime.Poller[DedicatedHostsClientRestartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restart(ctx, resourceGroupName, hostGroupName, hostName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restart - Restart the dedicated host. The operation will complete successfully once the dedicated host has restarted and +// is running. To determine the health of VMs deployed on the dedicated host after the +// restart check the Resource Health Center in the Azure Portal. Please refer to https://docs.microsoft.com/azure/service-health/resource-health-overview +// for more details. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *DedicatedHostsClient) restart(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRestartOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHostsClient.BeginRestart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restartCreateRequest(ctx, resourceGroupName, hostGroupName, hostName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// restartCreateRequest creates the Restart request. +func (client *DedicatedHostsClient) restartCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsClientBeginRestartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}/restart" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + if hostName == "" { + return nil, errors.New("parameter hostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Update a dedicated host . +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - hostGroupName - The name of the dedicated host group. +// - hostName - The name of the dedicated host . +// - parameters - Parameters supplied to the Update Dedicated Host operation. +// - options - DedicatedHostsClientBeginUpdateOptions contains the optional parameters for the DedicatedHostsClient.BeginUpdate +// method. +func (client *DedicatedHostsClient) BeginUpdate(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsClientBeginUpdateOptions) (*runtime.Poller[DedicatedHostsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, hostGroupName, hostName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHostsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHostsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a dedicated host . +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *DedicatedHostsClient) update(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHostsClient.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, hostGroupName, hostName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *DedicatedHostsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, parameters DedicatedHostUpdate, options *DedicatedHostsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hostGroupName == "" { + return nil, errors.New("parameter hostGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostGroupName}", url.PathEscape(hostGroupName)) + if hostName == "" { + return nil, errors.New("parameter hostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hostName}", url.PathEscape(hostName)) + 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-09-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/compute/armcompute/v5/diskaccesses_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskaccesses_client.go new file mode 100644 index 000000000..b189a0340 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskaccesses_client.go @@ -0,0 +1,846 @@ +//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 armcompute + +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" +) + +// DiskAccessesClient contains the methods for the DiskAccesses group. +// Don't use this type directly, use NewDiskAccessesClient() instead. +type DiskAccessesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDiskAccessesClient creates a new instance of DiskAccessesClient 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 NewDiskAccessesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiskAccessesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DiskAccessesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a disk access resource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - diskAccess - disk access object supplied in the body of the Put disk access operation. +// - options - DiskAccessesClientBeginCreateOrUpdateOptions contains the optional parameters for the DiskAccessesClient.BeginCreateOrUpdate +// method. +func (client *DiskAccessesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccess, options *DiskAccessesClientBeginCreateOrUpdateOptions) (*runtime.Poller[DiskAccessesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, diskAccessName, diskAccess, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a disk access resource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskAccessesClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccess, options *DiskAccessesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DiskAccessesClient.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, diskAccessName, diskAccess, 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 *DiskAccessesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccess, options *DiskAccessesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}" + 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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, diskAccess); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - options - DiskAccessesClientBeginDeleteOptions contains the optional parameters for the DiskAccessesClient.BeginDelete +// method. +func (client *DiskAccessesClient) BeginDelete(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientBeginDeleteOptions) (*runtime.Poller[DiskAccessesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, diskAccessName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskAccessesClient) deleteOperation(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DiskAccessesClient.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, diskAccessName, 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 *DiskAccessesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}" + 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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDeleteAPrivateEndpointConnection - Deletes a private endpoint connection under a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - privateEndpointConnectionName - The name of the private endpoint connection. +// - options - DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.BeginDeleteAPrivateEndpointConnection +// method. +func (client *DiskAccessesClient) BeginDeleteAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions) (*runtime.Poller[DiskAccessesClientDeleteAPrivateEndpointConnectionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteAPrivateEndpointConnection(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientDeleteAPrivateEndpointConnectionResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientDeleteAPrivateEndpointConnectionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeleteAPrivateEndpointConnection - Deletes a private endpoint connection under a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskAccessesClient) deleteAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions) (*http.Response, error) { + var err error + const operationName = "DiskAccessesClient.BeginDeleteAPrivateEndpointConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteAPrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, diskAccessName, 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 +} + +// deleteAPrivateEndpointConnectionCreateRequest creates the DeleteAPrivateEndpointConnection request. +func (client *DiskAccessesClient) deleteAPrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - options - DiskAccessesClientGetOptions contains the optional parameters for the DiskAccessesClient.Get method. +func (client *DiskAccessesClient) Get(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetOptions) (DiskAccessesClientGetResponse, error) { + var err error + const operationName = "DiskAccessesClient.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, diskAccessName, options) + if err != nil { + return DiskAccessesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiskAccessesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DiskAccessesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DiskAccessesClient) getCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}" + 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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DiskAccessesClient) getHandleResponse(resp *http.Response) (DiskAccessesClientGetResponse, error) { + result := DiskAccessesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskAccess); err != nil { + return DiskAccessesClientGetResponse{}, err + } + return result, nil +} + +// GetAPrivateEndpointConnection - Gets information about a private endpoint connection under a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - privateEndpointConnectionName - The name of the private endpoint connection. +// - options - DiskAccessesClientGetAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.GetAPrivateEndpointConnection +// method. +func (client *DiskAccessesClient) GetAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientGetAPrivateEndpointConnectionOptions) (DiskAccessesClientGetAPrivateEndpointConnectionResponse, error) { + var err error + const operationName = "DiskAccessesClient.GetAPrivateEndpointConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAPrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, options) + if err != nil { + return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err + } + resp, err := client.getAPrivateEndpointConnectionHandleResponse(httpResp) + return resp, err +} + +// getAPrivateEndpointConnectionCreateRequest creates the GetAPrivateEndpointConnection request. +func (client *DiskAccessesClient) getAPrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, options *DiskAccessesClientGetAPrivateEndpointConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAPrivateEndpointConnectionHandleResponse handles the GetAPrivateEndpointConnection response. +func (client *DiskAccessesClient) getAPrivateEndpointConnectionHandleResponse(resp *http.Response) (DiskAccessesClientGetAPrivateEndpointConnectionResponse, error) { + result := DiskAccessesClientGetAPrivateEndpointConnectionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return DiskAccessesClientGetAPrivateEndpointConnectionResponse{}, err + } + return result, nil +} + +// GetPrivateLinkResources - Gets the private link resources possible under disk access resource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - options - DiskAccessesClientGetPrivateLinkResourcesOptions contains the optional parameters for the DiskAccessesClient.GetPrivateLinkResources +// method. +func (client *DiskAccessesClient) GetPrivateLinkResources(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetPrivateLinkResourcesOptions) (DiskAccessesClientGetPrivateLinkResourcesResponse, error) { + var err error + const operationName = "DiskAccessesClient.GetPrivateLinkResources" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPrivateLinkResourcesCreateRequest(ctx, resourceGroupName, diskAccessName, options) + if err != nil { + return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err + } + resp, err := client.getPrivateLinkResourcesHandleResponse(httpResp) + return resp, err +} + +// getPrivateLinkResourcesCreateRequest creates the GetPrivateLinkResources request. +func (client *DiskAccessesClient) getPrivateLinkResourcesCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientGetPrivateLinkResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getPrivateLinkResourcesHandleResponse handles the GetPrivateLinkResources response. +func (client *DiskAccessesClient) getPrivateLinkResourcesHandleResponse(resp *http.Response) (DiskAccessesClientGetPrivateLinkResourcesResponse, error) { + result := DiskAccessesClientGetPrivateLinkResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return DiskAccessesClientGetPrivateLinkResourcesResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the disk access resources under a subscription. +// +// Generated from API version 2023-04-02 +// - options - DiskAccessesClientListOptions contains the optional parameters for the DiskAccessesClient.NewListPager method. +func (client *DiskAccessesClient) NewListPager(options *DiskAccessesClientListOptions) *runtime.Pager[DiskAccessesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DiskAccessesClientListResponse]{ + More: func(page DiskAccessesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiskAccessesClientListResponse) (DiskAccessesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskAccessesClient.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 DiskAccessesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DiskAccessesClient) listCreateRequest(ctx context.Context, options *DiskAccessesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/diskAccesses" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DiskAccessesClient) listHandleResponse(resp *http.Response) (DiskAccessesClientListResponse, error) { + result := DiskAccessesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskAccessList); err != nil { + return DiskAccessesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the disk access resources under a resource group. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - options - DiskAccessesClientListByResourceGroupOptions contains the optional parameters for the DiskAccessesClient.NewListByResourceGroupPager +// method. +func (client *DiskAccessesClient) NewListByResourceGroupPager(resourceGroupName string, options *DiskAccessesClientListByResourceGroupOptions) *runtime.Pager[DiskAccessesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DiskAccessesClientListByResourceGroupResponse]{ + More: func(page DiskAccessesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiskAccessesClientListByResourceGroupResponse) (DiskAccessesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskAccessesClient.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 DiskAccessesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *DiskAccessesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DiskAccessesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *DiskAccessesClient) listByResourceGroupHandleResponse(resp *http.Response) (DiskAccessesClientListByResourceGroupResponse, error) { + result := DiskAccessesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskAccessList); err != nil { + return DiskAccessesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListPrivateEndpointConnectionsPager - List information about private endpoint connections under a disk access resource +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - options - DiskAccessesClientListPrivateEndpointConnectionsOptions contains the optional parameters for the DiskAccessesClient.NewListPrivateEndpointConnectionsPager +// method. +func (client *DiskAccessesClient) NewListPrivateEndpointConnectionsPager(resourceGroupName string, diskAccessName string, options *DiskAccessesClientListPrivateEndpointConnectionsOptions) *runtime.Pager[DiskAccessesClientListPrivateEndpointConnectionsResponse] { + return runtime.NewPager(runtime.PagingHandler[DiskAccessesClientListPrivateEndpointConnectionsResponse]{ + More: func(page DiskAccessesClientListPrivateEndpointConnectionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiskAccessesClientListPrivateEndpointConnectionsResponse) (DiskAccessesClientListPrivateEndpointConnectionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskAccessesClient.NewListPrivateEndpointConnectionsPager") + 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.listPrivateEndpointConnectionsCreateRequest(ctx, resourceGroupName, diskAccessName, options) + }, nil) + if err != nil { + return DiskAccessesClientListPrivateEndpointConnectionsResponse{}, err + } + return client.listPrivateEndpointConnectionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPrivateEndpointConnectionsCreateRequest creates the ListPrivateEndpointConnections request. +func (client *DiskAccessesClient) listPrivateEndpointConnectionsCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, options *DiskAccessesClientListPrivateEndpointConnectionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPrivateEndpointConnectionsHandleResponse handles the ListPrivateEndpointConnections response. +func (client *DiskAccessesClient) listPrivateEndpointConnectionsHandleResponse(resp *http.Response) (DiskAccessesClientListPrivateEndpointConnectionsResponse, error) { + result := DiskAccessesClientListPrivateEndpointConnectionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return DiskAccessesClientListPrivateEndpointConnectionsResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates (patches) a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - diskAccess - disk access object supplied in the body of the Patch disk access operation. +// - options - DiskAccessesClientBeginUpdateOptions contains the optional parameters for the DiskAccessesClient.BeginUpdate +// method. +func (client *DiskAccessesClient) BeginUpdate(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccessUpdate, options *DiskAccessesClientBeginUpdateOptions) (*runtime.Poller[DiskAccessesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, diskAccessName, diskAccess, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates (patches) a disk access resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskAccessesClient) update(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccessUpdate, options *DiskAccessesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DiskAccessesClient.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, diskAccessName, diskAccess, 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 *DiskAccessesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, diskAccess DiskAccessUpdate, options *DiskAccessesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}" + 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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, diskAccess); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdateAPrivateEndpointConnection - Approve or reject a private endpoint connection under disk access resource, this +// can't be used to create a new private endpoint connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskAccessName - The name of the disk access resource that is being created. The name can't be changed after the disk encryption +// set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The +// maximum name length is 80 characters. +// - privateEndpointConnectionName - The name of the private endpoint connection. +// - privateEndpointConnection - private endpoint connection object supplied in the body of the Put private endpoint connection +// operation. +// - options - DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.BeginUpdateAPrivateEndpointConnection +// method. +func (client *DiskAccessesClient) BeginUpdateAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions) (*runtime.Poller[DiskAccessesClientUpdateAPrivateEndpointConnectionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateAPrivateEndpointConnection(ctx, resourceGroupName, diskAccessName, privateEndpointConnectionName, privateEndpointConnection, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskAccessesClientUpdateAPrivateEndpointConnectionResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskAccessesClientUpdateAPrivateEndpointConnectionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateAPrivateEndpointConnection - Approve or reject a private endpoint connection under disk access resource, this can't +// be used to create a new private endpoint connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskAccessesClient) updateAPrivateEndpointConnection(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions) (*http.Response, error) { + var err error + const operationName = "DiskAccessesClient.BeginUpdateAPrivateEndpointConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateAPrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, diskAccessName, 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.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateAPrivateEndpointConnectionCreateRequest creates the UpdateAPrivateEndpointConnection request. +func (client *DiskAccessesClient) updateAPrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, diskAccessName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskAccesses/{diskAccessName}/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 diskAccessName == "" { + return nil, errors.New("parameter diskAccessName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskAccessName}", url.PathEscape(diskAccessName)) + 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-04-02") + 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 +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskencryptionsets_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskencryptionsets_client.go new file mode 100644 index 000000000..9306f9c0d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskencryptionsets_client.go @@ -0,0 +1,535 @@ +//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 armcompute + +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" +) + +// DiskEncryptionSetsClient contains the methods for the DiskEncryptionSets group. +// Don't use this type directly, use NewDiskEncryptionSetsClient() instead. +type DiskEncryptionSetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDiskEncryptionSetsClient creates a new instance of DiskEncryptionSetsClient 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 NewDiskEncryptionSetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiskEncryptionSetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DiskEncryptionSetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a disk encryption set +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the +// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum +// name length is 80 characters. +// - diskEncryptionSet - disk encryption set object supplied in the body of the Put disk encryption set operation. +// - options - DiskEncryptionSetsClientBeginCreateOrUpdateOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginCreateOrUpdate +// method. +func (client *DiskEncryptionSetsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSet, options *DiskEncryptionSetsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DiskEncryptionSetsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, diskEncryptionSetName, diskEncryptionSet, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskEncryptionSetsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskEncryptionSetsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a disk encryption set +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskEncryptionSetsClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSet, options *DiskEncryptionSetsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DiskEncryptionSetsClient.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, diskEncryptionSetName, diskEncryptionSet, 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 *DiskEncryptionSetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSet, options *DiskEncryptionSetsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}" + 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 diskEncryptionSetName == "" { + return nil, errors.New("parameter diskEncryptionSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, diskEncryptionSet); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a disk encryption set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the +// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum +// name length is 80 characters. +// - options - DiskEncryptionSetsClientBeginDeleteOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginDelete +// method. +func (client *DiskEncryptionSetsClient) BeginDelete(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientBeginDeleteOptions) (*runtime.Poller[DiskEncryptionSetsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, diskEncryptionSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskEncryptionSetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskEncryptionSetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a disk encryption set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskEncryptionSetsClient) deleteOperation(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DiskEncryptionSetsClient.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, diskEncryptionSetName, 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 *DiskEncryptionSetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}" + 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 diskEncryptionSetName == "" { + return nil, errors.New("parameter diskEncryptionSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about a disk encryption set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the +// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum +// name length is 80 characters. +// - options - DiskEncryptionSetsClientGetOptions contains the optional parameters for the DiskEncryptionSetsClient.Get method. +func (client *DiskEncryptionSetsClient) Get(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientGetOptions) (DiskEncryptionSetsClientGetResponse, error) { + var err error + const operationName = "DiskEncryptionSetsClient.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, diskEncryptionSetName, options) + if err != nil { + return DiskEncryptionSetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiskEncryptionSetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DiskEncryptionSetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DiskEncryptionSetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}" + 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 diskEncryptionSetName == "" { + return nil, errors.New("parameter diskEncryptionSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DiskEncryptionSetsClient) getHandleResponse(resp *http.Response) (DiskEncryptionSetsClientGetResponse, error) { + result := DiskEncryptionSetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskEncryptionSet); err != nil { + return DiskEncryptionSetsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the disk encryption sets under a subscription. +// +// Generated from API version 2023-04-02 +// - options - DiskEncryptionSetsClientListOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListPager +// method. +func (client *DiskEncryptionSetsClient) NewListPager(options *DiskEncryptionSetsClientListOptions) *runtime.Pager[DiskEncryptionSetsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DiskEncryptionSetsClientListResponse]{ + More: func(page DiskEncryptionSetsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiskEncryptionSetsClientListResponse) (DiskEncryptionSetsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskEncryptionSetsClient.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 DiskEncryptionSetsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DiskEncryptionSetsClient) listCreateRequest(ctx context.Context, options *DiskEncryptionSetsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/diskEncryptionSets" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DiskEncryptionSetsClient) listHandleResponse(resp *http.Response) (DiskEncryptionSetsClientListResponse, error) { + result := DiskEncryptionSetsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskEncryptionSetList); err != nil { + return DiskEncryptionSetsClientListResponse{}, err + } + return result, nil +} + +// NewListAssociatedResourcesPager - Lists all resources that are encrypted with this disk encryption set. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the +// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum +// name length is 80 characters. +// - options - DiskEncryptionSetsClientListAssociatedResourcesOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListAssociatedResourcesPager +// method. +func (client *DiskEncryptionSetsClient) NewListAssociatedResourcesPager(resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientListAssociatedResourcesOptions) *runtime.Pager[DiskEncryptionSetsClientListAssociatedResourcesResponse] { + return runtime.NewPager(runtime.PagingHandler[DiskEncryptionSetsClientListAssociatedResourcesResponse]{ + More: func(page DiskEncryptionSetsClientListAssociatedResourcesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiskEncryptionSetsClientListAssociatedResourcesResponse) (DiskEncryptionSetsClientListAssociatedResourcesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskEncryptionSetsClient.NewListAssociatedResourcesPager") + 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.listAssociatedResourcesCreateRequest(ctx, resourceGroupName, diskEncryptionSetName, options) + }, nil) + if err != nil { + return DiskEncryptionSetsClientListAssociatedResourcesResponse{}, err + } + return client.listAssociatedResourcesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAssociatedResourcesCreateRequest creates the ListAssociatedResources request. +func (client *DiskEncryptionSetsClient) listAssociatedResourcesCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, options *DiskEncryptionSetsClientListAssociatedResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}/associatedResources" + 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 diskEncryptionSetName == "" { + return nil, errors.New("parameter diskEncryptionSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAssociatedResourcesHandleResponse handles the ListAssociatedResources response. +func (client *DiskEncryptionSetsClient) listAssociatedResourcesHandleResponse(resp *http.Response) (DiskEncryptionSetsClientListAssociatedResourcesResponse, error) { + result := DiskEncryptionSetsClientListAssociatedResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceURIList); err != nil { + return DiskEncryptionSetsClientListAssociatedResourcesResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the disk encryption sets under a resource group. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - options - DiskEncryptionSetsClientListByResourceGroupOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListByResourceGroupPager +// method. +func (client *DiskEncryptionSetsClient) NewListByResourceGroupPager(resourceGroupName string, options *DiskEncryptionSetsClientListByResourceGroupOptions) *runtime.Pager[DiskEncryptionSetsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DiskEncryptionSetsClientListByResourceGroupResponse]{ + More: func(page DiskEncryptionSetsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiskEncryptionSetsClientListByResourceGroupResponse) (DiskEncryptionSetsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskEncryptionSetsClient.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 DiskEncryptionSetsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *DiskEncryptionSetsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DiskEncryptionSetsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *DiskEncryptionSetsClient) listByResourceGroupHandleResponse(resp *http.Response) (DiskEncryptionSetsClientListByResourceGroupResponse, error) { + result := DiskEncryptionSetsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskEncryptionSetList); err != nil { + return DiskEncryptionSetsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates (patches) a disk encryption set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskEncryptionSetName - The name of the disk encryption set that is being created. The name can't be changed after the +// disk encryption set is created. Supported characters for the name are a-z, A-Z, 0-9, _ and -. The maximum +// name length is 80 characters. +// - diskEncryptionSet - disk encryption set object supplied in the body of the Patch disk encryption set operation. +// - options - DiskEncryptionSetsClientBeginUpdateOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginUpdate +// method. +func (client *DiskEncryptionSetsClient) BeginUpdate(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsClientBeginUpdateOptions) (*runtime.Poller[DiskEncryptionSetsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, diskEncryptionSetName, diskEncryptionSet, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskEncryptionSetsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskEncryptionSetsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates (patches) a disk encryption set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskEncryptionSetsClient) update(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DiskEncryptionSetsClient.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, diskEncryptionSetName, diskEncryptionSet, 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 *DiskEncryptionSetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskEncryptionSetName string, diskEncryptionSet DiskEncryptionSetUpdate, options *DiskEncryptionSetsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/diskEncryptionSets/{diskEncryptionSetName}" + 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 diskEncryptionSetName == "" { + return nil, errors.New("parameter diskEncryptionSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskEncryptionSetName}", url.PathEscape(diskEncryptionSetName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, diskEncryptionSet); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskrestorepoint_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskrestorepoint_client.go new file mode 100644 index 000000000..54b576957 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/diskrestorepoint_client.go @@ -0,0 +1,367 @@ +//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 armcompute + +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" +) + +// DiskRestorePointClient contains the methods for the DiskRestorePoint group. +// Don't use this type directly, use NewDiskRestorePointClient() instead. +type DiskRestorePointClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDiskRestorePointClient creates a new instance of DiskRestorePointClient 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 NewDiskRestorePointClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiskRestorePointClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DiskRestorePointClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get disk restorePoint resource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. +// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. +// - diskRestorePointName - The name of the disk restore point created. +// - options - DiskRestorePointClientGetOptions contains the optional parameters for the DiskRestorePointClient.Get method. +func (client *DiskRestorePointClient) Get(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientGetOptions) (DiskRestorePointClientGetResponse, error) { + var err error + const operationName = "DiskRestorePointClient.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, restorePointCollectionName, vmRestorePointName, diskRestorePointName, options) + if err != nil { + return DiskRestorePointClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiskRestorePointClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DiskRestorePointClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DiskRestorePointClient) getCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints/{diskRestorePointName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + if vmRestorePointName == "" { + return nil, errors.New("parameter vmRestorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName)) + if diskRestorePointName == "" { + return nil, errors.New("parameter diskRestorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskRestorePointName}", url.PathEscape(diskRestorePointName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DiskRestorePointClient) getHandleResponse(resp *http.Response) (DiskRestorePointClientGetResponse, error) { + result := DiskRestorePointClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskRestorePoint); err != nil { + return DiskRestorePointClientGetResponse{}, err + } + return result, nil +} + +// BeginGrantAccess - Grants access to a diskRestorePoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. +// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. +// - diskRestorePointName - The name of the disk restore point created. +// - grantAccessData - Access data object supplied in the body of the get disk access operation. +// - options - DiskRestorePointClientBeginGrantAccessOptions contains the optional parameters for the DiskRestorePointClient.BeginGrantAccess +// method. +func (client *DiskRestorePointClient) BeginGrantAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, grantAccessData GrantAccessData, options *DiskRestorePointClientBeginGrantAccessOptions) (*runtime.Poller[DiskRestorePointClientGrantAccessResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.grantAccess(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, grantAccessData, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskRestorePointClientGrantAccessResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskRestorePointClientGrantAccessResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GrantAccess - Grants access to a diskRestorePoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskRestorePointClient) grantAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, grantAccessData GrantAccessData, options *DiskRestorePointClientBeginGrantAccessOptions) (*http.Response, error) { + var err error + const operationName = "DiskRestorePointClient.BeginGrantAccess" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.grantAccessCreateRequest(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, grantAccessData, 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 +} + +// grantAccessCreateRequest creates the GrantAccess request. +func (client *DiskRestorePointClient) grantAccessCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, grantAccessData GrantAccessData, options *DiskRestorePointClientBeginGrantAccessOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints/{diskRestorePointName}/beginGetAccess" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + if vmRestorePointName == "" { + return nil, errors.New("parameter vmRestorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName)) + if diskRestorePointName == "" { + return nil, errors.New("parameter diskRestorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskRestorePointName}", url.PathEscape(diskRestorePointName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil { + return nil, err + } + return req, nil +} + +// NewListByRestorePointPager - Lists diskRestorePoints under a vmRestorePoint. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. +// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. +// - options - DiskRestorePointClientListByRestorePointOptions contains the optional parameters for the DiskRestorePointClient.NewListByRestorePointPager +// method. +func (client *DiskRestorePointClient) NewListByRestorePointPager(resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, options *DiskRestorePointClientListByRestorePointOptions) *runtime.Pager[DiskRestorePointClientListByRestorePointResponse] { + return runtime.NewPager(runtime.PagingHandler[DiskRestorePointClientListByRestorePointResponse]{ + More: func(page DiskRestorePointClientListByRestorePointResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiskRestorePointClientListByRestorePointResponse) (DiskRestorePointClientListByRestorePointResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiskRestorePointClient.NewListByRestorePointPager") + 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.listByRestorePointCreateRequest(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, options) + }, nil) + if err != nil { + return DiskRestorePointClientListByRestorePointResponse{}, err + } + return client.listByRestorePointHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByRestorePointCreateRequest creates the ListByRestorePoint request. +func (client *DiskRestorePointClient) listByRestorePointCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, options *DiskRestorePointClientListByRestorePointOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + if vmRestorePointName == "" { + return nil, errors.New("parameter vmRestorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByRestorePointHandleResponse handles the ListByRestorePoint response. +func (client *DiskRestorePointClient) listByRestorePointHandleResponse(resp *http.Response) (DiskRestorePointClientListByRestorePointResponse, error) { + result := DiskRestorePointClientListByRestorePointResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskRestorePointList); err != nil { + return DiskRestorePointClientListByRestorePointResponse{}, err + } + return result, nil +} + +// BeginRevokeAccess - Revokes access to a diskRestorePoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection that the disk restore point belongs. +// - vmRestorePointName - The name of the vm restore point that the disk disk restore point belongs. +// - diskRestorePointName - The name of the disk restore point created. +// - options - DiskRestorePointClientBeginRevokeAccessOptions contains the optional parameters for the DiskRestorePointClient.BeginRevokeAccess +// method. +func (client *DiskRestorePointClient) BeginRevokeAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientBeginRevokeAccessOptions) (*runtime.Poller[DiskRestorePointClientRevokeAccessResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.revokeAccess(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiskRestorePointClientRevokeAccessResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiskRestorePointClientRevokeAccessResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RevokeAccess - Revokes access to a diskRestorePoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DiskRestorePointClient) revokeAccess(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientBeginRevokeAccessOptions) (*http.Response, error) { + var err error + const operationName = "DiskRestorePointClient.BeginRevokeAccess" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.revokeAccessCreateRequest(ctx, resourceGroupName, restorePointCollectionName, vmRestorePointName, diskRestorePointName, 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 +} + +// revokeAccessCreateRequest creates the RevokeAccess request. +func (client *DiskRestorePointClient) revokeAccessCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, vmRestorePointName string, diskRestorePointName string, options *DiskRestorePointClientBeginRevokeAccessOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{vmRestorePointName}/diskRestorePoints/{diskRestorePointName}/endGetAccess" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + if vmRestorePointName == "" { + return nil, errors.New("parameter vmRestorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmRestorePointName}", url.PathEscape(vmRestorePointName)) + if diskRestorePointName == "" { + return nil, errors.New("parameter diskRestorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskRestorePointName}", url.PathEscape(diskRestorePointName)) + 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-04-02") + 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/compute/armcompute/v5/disks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/disks_client.go new file mode 100644 index 000000000..854a8ffd6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/disks_client.go @@ -0,0 +1,623 @@ +//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 armcompute + +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" +) + +// DisksClient contains the methods for the Disks group. +// Don't use this type directly, use NewDisksClient() instead. +type DisksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDisksClient creates a new instance of DisksClient 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 NewDisksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DisksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DisksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported +// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 +// characters. +// - disk - Disk object supplied in the body of the Put disk operation. +// - options - DisksClientBeginCreateOrUpdateOptions contains the optional parameters for the DisksClient.BeginCreateOrUpdate +// method. +func (client *DisksClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, diskName string, disk Disk, options *DisksClientBeginCreateOrUpdateOptions) (*runtime.Poller[DisksClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, diskName, disk, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DisksClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskName string, disk Disk, options *DisksClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DisksClient.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, diskName, disk, 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 *DisksClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, diskName string, disk Disk, options *DisksClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}" + 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 diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, disk); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported +// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 +// characters. +// - options - DisksClientBeginDeleteOptions contains the optional parameters for the DisksClient.BeginDelete method. +func (client *DisksClient) BeginDelete(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginDeleteOptions) (*runtime.Poller[DisksClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, diskName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DisksClient) deleteOperation(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DisksClient.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, diskName, 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 *DisksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}" + 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 diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Gets information about a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported +// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 +// characters. +// - options - DisksClientGetOptions contains the optional parameters for the DisksClient.Get method. +func (client *DisksClient) Get(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientGetOptions) (DisksClientGetResponse, error) { + var err error + const operationName = "DisksClient.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, diskName, options) + if err != nil { + return DisksClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DisksClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DisksClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DisksClient) getCreateRequest(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}" + 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 diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DisksClient) getHandleResponse(resp *http.Response) (DisksClientGetResponse, error) { + result := DisksClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Disk); err != nil { + return DisksClientGetResponse{}, err + } + return result, nil +} + +// BeginGrantAccess - Grants access to a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported +// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 +// characters. +// - grantAccessData - Access data object supplied in the body of the get disk access operation. +// - options - DisksClientBeginGrantAccessOptions contains the optional parameters for the DisksClient.BeginGrantAccess method. +func (client *DisksClient) BeginGrantAccess(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData, options *DisksClientBeginGrantAccessOptions) (*runtime.Poller[DisksClientGrantAccessResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.grantAccess(ctx, resourceGroupName, diskName, grantAccessData, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientGrantAccessResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientGrantAccessResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GrantAccess - Grants access to a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DisksClient) grantAccess(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData, options *DisksClientBeginGrantAccessOptions) (*http.Response, error) { + var err error + const operationName = "DisksClient.BeginGrantAccess" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.grantAccessCreateRequest(ctx, resourceGroupName, diskName, grantAccessData, 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 +} + +// grantAccessCreateRequest creates the GrantAccess request. +func (client *DisksClient) grantAccessCreateRequest(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData, options *DisksClientBeginGrantAccessOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/beginGetAccess" + 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 diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil { + return nil, err + } + return req, nil +} + +// NewListPager - Lists all the disks under a subscription. +// +// Generated from API version 2023-04-02 +// - options - DisksClientListOptions contains the optional parameters for the DisksClient.NewListPager method. +func (client *DisksClient) NewListPager(options *DisksClientListOptions) *runtime.Pager[DisksClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DisksClientListResponse]{ + More: func(page DisksClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DisksClientListResponse) (DisksClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DisksClient.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 DisksClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DisksClient) listCreateRequest(ctx context.Context, options *DisksClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/disks" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DisksClient) listHandleResponse(resp *http.Response) (DisksClientListResponse, error) { + result := DisksClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskList); err != nil { + return DisksClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the disks under a resource group. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - options - DisksClientListByResourceGroupOptions contains the optional parameters for the DisksClient.NewListByResourceGroupPager +// method. +func (client *DisksClient) NewListByResourceGroupPager(resourceGroupName string, options *DisksClientListByResourceGroupOptions) *runtime.Pager[DisksClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DisksClientListByResourceGroupResponse]{ + More: func(page DisksClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DisksClientListByResourceGroupResponse) (DisksClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DisksClient.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 DisksClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *DisksClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DisksClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *DisksClient) listByResourceGroupHandleResponse(resp *http.Response) (DisksClientListByResourceGroupResponse, error) { + result := DisksClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiskList); err != nil { + return DisksClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginRevokeAccess - Revokes access to a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported +// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 +// characters. +// - options - DisksClientBeginRevokeAccessOptions contains the optional parameters for the DisksClient.BeginRevokeAccess method. +func (client *DisksClient) BeginRevokeAccess(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginRevokeAccessOptions) (*runtime.Poller[DisksClientRevokeAccessResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.revokeAccess(ctx, resourceGroupName, diskName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientRevokeAccessResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientRevokeAccessResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RevokeAccess - Revokes access to a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DisksClient) revokeAccess(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginRevokeAccessOptions) (*http.Response, error) { + var err error + const operationName = "DisksClient.BeginRevokeAccess" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.revokeAccessCreateRequest(ctx, resourceGroupName, diskName, 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 +} + +// revokeAccessCreateRequest creates the RevokeAccess request. +func (client *DisksClient) revokeAccessCreateRequest(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientBeginRevokeAccessOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/endGetAccess" + 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 diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// BeginUpdate - Updates (patches) a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - diskName - The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported +// characters for the name are a-z, A-Z, 0-9, _ and -. The maximum name length is 80 +// characters. +// - disk - Disk object supplied in the body of the Patch disk operation. +// - options - DisksClientBeginUpdateOptions contains the optional parameters for the DisksClient.BeginUpdate method. +func (client *DisksClient) BeginUpdate(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate, options *DisksClientBeginUpdateOptions) (*runtime.Poller[DisksClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, diskName, disk, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates (patches) a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *DisksClient) update(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate, options *DisksClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DisksClient.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, diskName, disk, 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 *DisksClient) updateCreateRequest(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate, options *DisksClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}" + 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 diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, disk); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleries_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleries_client.go new file mode 100644 index 000000000..8fac494c7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleries_client.go @@ -0,0 +1,465 @@ +//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 armcompute + +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" +) + +// GalleriesClient contains the methods for the Galleries group. +// Don't use this type directly, use NewGalleriesClient() instead. +type GalleriesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGalleriesClient creates a new instance of GalleriesClient 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 NewGalleriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleriesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GalleriesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a Shared Image Gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery. The allowed characters are alphabets and numbers with dots and periods +// allowed in the middle. The maximum length is 80 characters. +// - gallery - Parameters supplied to the create or update Shared Image Gallery operation. +// - options - GalleriesClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleriesClient.BeginCreateOrUpdate +// method. +func (client *GalleriesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery, options *GalleriesClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleriesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, gallery, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleriesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleriesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a Shared Image Gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleriesClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery, options *GalleriesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleriesClient.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, galleryName, gallery, 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, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *GalleriesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery, options *GalleriesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, gallery); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a Shared Image Gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery to be deleted. +// - options - GalleriesClientBeginDeleteOptions contains the optional parameters for the GalleriesClient.BeginDelete method. +func (client *GalleriesClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientBeginDeleteOptions) (*runtime.Poller[GalleriesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleriesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleriesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a Shared Image Gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleriesClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "GalleriesClient.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, galleryName, 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 *GalleriesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a Shared Image Gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery. +// - options - GalleriesClientGetOptions contains the optional parameters for the GalleriesClient.Get method. +func (client *GalleriesClient) Get(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientGetOptions) (GalleriesClientGetResponse, error) { + var err error + const operationName = "GalleriesClient.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, galleryName, options) + if err != nil { + return GalleriesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GalleriesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GalleriesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GalleriesClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleriesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + 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", "2022-08-03") + if options != nil && options.Select != nil { + reqQP.Set("$select", string(*options.Select)) + } + 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 +} + +// getHandleResponse handles the Get response. +func (client *GalleriesClient) getHandleResponse(resp *http.Response) (GalleriesClientGetResponse, error) { + result := GalleriesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Gallery); err != nil { + return GalleriesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List galleries under a subscription. +// +// Generated from API version 2022-08-03 +// - options - GalleriesClientListOptions contains the optional parameters for the GalleriesClient.NewListPager method. +func (client *GalleriesClient) NewListPager(options *GalleriesClientListOptions) *runtime.Pager[GalleriesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[GalleriesClientListResponse]{ + More: func(page GalleriesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GalleriesClientListResponse) (GalleriesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleriesClient.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 GalleriesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *GalleriesClient) listCreateRequest(ctx context.Context, options *GalleriesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/galleries" + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *GalleriesClient) listHandleResponse(resp *http.Response) (GalleriesClientListResponse, error) { + result := GalleriesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryList); err != nil { + return GalleriesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List galleries under a resource group. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - options - GalleriesClientListByResourceGroupOptions contains the optional parameters for the GalleriesClient.NewListByResourceGroupPager +// method. +func (client *GalleriesClient) NewListByResourceGroupPager(resourceGroupName string, options *GalleriesClientListByResourceGroupOptions) *runtime.Pager[GalleriesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[GalleriesClientListByResourceGroupResponse]{ + More: func(page GalleriesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GalleriesClientListByResourceGroupResponse) (GalleriesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleriesClient.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 GalleriesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *GalleriesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *GalleriesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries" + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *GalleriesClient) listByResourceGroupHandleResponse(resp *http.Response) (GalleriesClientListByResourceGroupResponse, error) { + result := GalleriesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryList); err != nil { + return GalleriesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a Shared Image Gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery. The allowed characters are alphabets and numbers with dots and periods +// allowed in the middle. The maximum length is 80 characters. +// - gallery - Parameters supplied to the update Shared Image Gallery operation. +// - options - GalleriesClientBeginUpdateOptions contains the optional parameters for the GalleriesClient.BeginUpdate method. +func (client *GalleriesClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, gallery GalleryUpdate, options *GalleriesClientBeginUpdateOptions) (*runtime.Poller[GalleriesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, galleryName, gallery, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleriesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleriesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a Shared Image Gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleriesClient) update(ctx context.Context, resourceGroupName string, galleryName string, gallery GalleryUpdate, options *GalleriesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleriesClient.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, galleryName, gallery, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *GalleriesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, gallery GalleryUpdate, options *GalleriesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, gallery); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryapplications_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryapplications_client.go new file mode 100644 index 000000000..1ebec623b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryapplications_client.go @@ -0,0 +1,434 @@ +//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 armcompute + +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" +) + +// GalleryApplicationsClient contains the methods for the GalleryApplications group. +// Don't use this type directly, use NewGalleryApplicationsClient() instead. +type GalleryApplicationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGalleryApplicationsClient creates a new instance of GalleryApplicationsClient 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 NewGalleryApplicationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryApplicationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GalleryApplicationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a gallery Application Definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition is to be created. +// - galleryApplicationName - The name of the gallery Application Definition to be created or updated. The allowed characters +// are alphabets and numbers with dots, dashes, and periods allowed in the middle. The maximum length is 80 +// characters. +// - galleryApplication - Parameters supplied to the create or update gallery Application operation. +// - options - GalleryApplicationsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryApplicationsClient.BeginCreateOrUpdate +// method. +func (client *GalleryApplicationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplication, options *GalleryApplicationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryApplicationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplication, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a gallery Application Definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryApplicationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplication, options *GalleryApplicationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryApplicationsClient.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, galleryName, galleryApplicationName, galleryApplication, 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, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *GalleryApplicationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplication, options *GalleryApplicationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryApplication); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a gallery Application. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition is to be deleted. +// - galleryApplicationName - The name of the gallery Application Definition to be deleted. +// - options - GalleryApplicationsClientBeginDeleteOptions contains the optional parameters for the GalleryApplicationsClient.BeginDelete +// method. +func (client *GalleryApplicationsClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientBeginDeleteOptions) (*runtime.Poller[GalleryApplicationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryApplicationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a gallery Application. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryApplicationsClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "GalleryApplicationsClient.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, galleryName, galleryApplicationName, 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 *GalleryApplicationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a gallery Application Definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery from which the Application Definitions are to be retrieved. +// - galleryApplicationName - The name of the gallery Application Definition to be retrieved. +// - options - GalleryApplicationsClientGetOptions contains the optional parameters for the GalleryApplicationsClient.Get method. +func (client *GalleryApplicationsClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientGetOptions) (GalleryApplicationsClientGetResponse, error) { + var err error + const operationName = "GalleryApplicationsClient.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, galleryName, galleryApplicationName, options) + if err != nil { + return GalleryApplicationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GalleryApplicationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GalleryApplicationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GalleryApplicationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *GalleryApplicationsClient) getHandleResponse(resp *http.Response) (GalleryApplicationsClientGetResponse, error) { + result := GalleryApplicationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplication); err != nil { + return GalleryApplicationsClientGetResponse{}, err + } + return result, nil +} + +// NewListByGalleryPager - List gallery Application Definitions in a gallery. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery from which Application Definitions are to be listed. +// - options - GalleryApplicationsClientListByGalleryOptions contains the optional parameters for the GalleryApplicationsClient.NewListByGalleryPager +// method. +func (client *GalleryApplicationsClient) NewListByGalleryPager(resourceGroupName string, galleryName string, options *GalleryApplicationsClientListByGalleryOptions) *runtime.Pager[GalleryApplicationsClientListByGalleryResponse] { + return runtime.NewPager(runtime.PagingHandler[GalleryApplicationsClientListByGalleryResponse]{ + More: func(page GalleryApplicationsClientListByGalleryResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GalleryApplicationsClientListByGalleryResponse) (GalleryApplicationsClientListByGalleryResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryApplicationsClient.NewListByGalleryPager") + 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.listByGalleryCreateRequest(ctx, resourceGroupName, galleryName, options) + }, nil) + if err != nil { + return GalleryApplicationsClientListByGalleryResponse{}, err + } + return client.listByGalleryHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByGalleryCreateRequest creates the ListByGallery request. +func (client *GalleryApplicationsClient) listByGalleryCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleryApplicationsClientListByGalleryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByGalleryHandleResponse handles the ListByGallery response. +func (client *GalleryApplicationsClient) listByGalleryHandleResponse(resp *http.Response) (GalleryApplicationsClientListByGalleryResponse, error) { + result := GalleryApplicationsClientListByGalleryResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplicationList); err != nil { + return GalleryApplicationsClientListByGalleryResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a gallery Application Definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition is to be updated. +// - galleryApplicationName - The name of the gallery Application Definition to be updated. The allowed characters are alphabets +// and numbers with dots, dashes, and periods allowed in the middle. The maximum length is 80 +// characters. +// - galleryApplication - Parameters supplied to the update gallery Application operation. +// - options - GalleryApplicationsClientBeginUpdateOptions contains the optional parameters for the GalleryApplicationsClient.BeginUpdate +// method. +func (client *GalleryApplicationsClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplicationUpdate, options *GalleryApplicationsClientBeginUpdateOptions) (*runtime.Poller[GalleryApplicationsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplication, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a gallery Application Definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryApplicationsClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplicationUpdate, options *GalleryApplicationsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryApplicationsClient.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, galleryName, galleryApplicationName, galleryApplication, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *GalleryApplicationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplication GalleryApplicationUpdate, options *GalleryApplicationsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryApplication); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryapplicationversions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryapplicationversions_client.go new file mode 100644 index 000000000..3d885cb93 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryapplicationversions_client.go @@ -0,0 +1,464 @@ +//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 armcompute + +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" +) + +// GalleryApplicationVersionsClient contains the methods for the GalleryApplicationVersions group. +// Don't use this type directly, use NewGalleryApplicationVersionsClient() instead. +type GalleryApplicationVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGalleryApplicationVersionsClient creates a new instance of GalleryApplicationVersionsClient 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 NewGalleryApplicationVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryApplicationVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GalleryApplicationVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a gallery Application Version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides. +// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version is to be created. +// - galleryApplicationVersionName - The name of the gallery Application Version to be created. Needs to follow semantic version +// name pattern: The allowed characters are digit and period. Digits must be within the range of a 32-bit +// integer. Format: .. +// - galleryApplicationVersion - Parameters supplied to the create or update gallery Application Version operation. +// - options - GalleryApplicationVersionsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginCreateOrUpdate +// method. +func (client *GalleryApplicationVersionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersion, options *GalleryApplicationVersionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryApplicationVersionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationVersionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationVersionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a gallery Application Version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryApplicationVersionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersion, options *GalleryApplicationVersionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryApplicationVersionsClient.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, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, 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, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *GalleryApplicationVersionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersion, options *GalleryApplicationVersionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + if galleryApplicationVersionName == "" { + return nil, errors.New("parameter galleryApplicationVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryApplicationVersion); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a gallery Application Version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides. +// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version resides. +// - galleryApplicationVersionName - The name of the gallery Application Version to be deleted. +// - options - GalleryApplicationVersionsClientBeginDeleteOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginDelete +// method. +func (client *GalleryApplicationVersionsClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientBeginDeleteOptions) (*runtime.Poller[GalleryApplicationVersionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationVersionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationVersionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a gallery Application Version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryApplicationVersionsClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "GalleryApplicationVersionsClient.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, galleryName, galleryApplicationName, galleryApplicationVersionName, 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 *GalleryApplicationVersionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + if galleryApplicationVersionName == "" { + return nil, errors.New("parameter galleryApplicationVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a gallery Application Version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides. +// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version resides. +// - galleryApplicationVersionName - The name of the gallery Application Version to be retrieved. +// - options - GalleryApplicationVersionsClientGetOptions contains the optional parameters for the GalleryApplicationVersionsClient.Get +// method. +func (client *GalleryApplicationVersionsClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientGetOptions) (GalleryApplicationVersionsClientGetResponse, error) { + var err error + const operationName = "GalleryApplicationVersionsClient.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, galleryName, galleryApplicationName, galleryApplicationVersionName, options) + if err != nil { + return GalleryApplicationVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GalleryApplicationVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GalleryApplicationVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GalleryApplicationVersionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, options *GalleryApplicationVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + if galleryApplicationVersionName == "" { + return nil, errors.New("parameter galleryApplicationVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *GalleryApplicationVersionsClient) getHandleResponse(resp *http.Response) (GalleryApplicationVersionsClientGetResponse, error) { + result := GalleryApplicationVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplicationVersion); err != nil { + return GalleryApplicationVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByGalleryApplicationPager - List gallery Application Versions in a gallery Application Definition. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides. +// - galleryApplicationName - The name of the Shared Application Gallery Application Definition from which the Application Versions +// are to be listed. +// - options - GalleryApplicationVersionsClientListByGalleryApplicationOptions contains the optional parameters for the GalleryApplicationVersionsClient.NewListByGalleryApplicationPager +// method. +func (client *GalleryApplicationVersionsClient) NewListByGalleryApplicationPager(resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationVersionsClientListByGalleryApplicationOptions) *runtime.Pager[GalleryApplicationVersionsClientListByGalleryApplicationResponse] { + return runtime.NewPager(runtime.PagingHandler[GalleryApplicationVersionsClientListByGalleryApplicationResponse]{ + More: func(page GalleryApplicationVersionsClientListByGalleryApplicationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GalleryApplicationVersionsClientListByGalleryApplicationResponse) (GalleryApplicationVersionsClientListByGalleryApplicationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryApplicationVersionsClient.NewListByGalleryApplicationPager") + 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.listByGalleryApplicationCreateRequest(ctx, resourceGroupName, galleryName, galleryApplicationName, options) + }, nil) + if err != nil { + return GalleryApplicationVersionsClientListByGalleryApplicationResponse{}, err + } + return client.listByGalleryApplicationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByGalleryApplicationCreateRequest creates the ListByGalleryApplication request. +func (client *GalleryApplicationVersionsClient) listByGalleryApplicationCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, options *GalleryApplicationVersionsClientListByGalleryApplicationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByGalleryApplicationHandleResponse handles the ListByGalleryApplication response. +func (client *GalleryApplicationVersionsClient) listByGalleryApplicationHandleResponse(resp *http.Response) (GalleryApplicationVersionsClientListByGalleryApplicationResponse, error) { + result := GalleryApplicationVersionsClientListByGalleryApplicationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryApplicationVersionList); err != nil { + return GalleryApplicationVersionsClientListByGalleryApplicationResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a gallery Application Version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Application Gallery in which the Application Definition resides. +// - galleryApplicationName - The name of the gallery Application Definition in which the Application Version is to be updated. +// - galleryApplicationVersionName - The name of the gallery Application Version to be updated. Needs to follow semantic version +// name pattern: The allowed characters are digit and period. Digits must be within the range of a 32-bit +// integer. Format: .. +// - galleryApplicationVersion - Parameters supplied to the update gallery Application Version operation. +// - options - GalleryApplicationVersionsClientBeginUpdateOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginUpdate +// method. +func (client *GalleryApplicationVersionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersionUpdate, options *GalleryApplicationVersionsClientBeginUpdateOptions) (*runtime.Poller[GalleryApplicationVersionsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryApplicationVersionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryApplicationVersionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a gallery Application Version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryApplicationVersionsClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersionUpdate, options *GalleryApplicationVersionsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryApplicationVersionsClient.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, galleryName, galleryApplicationName, galleryApplicationVersionName, galleryApplicationVersion, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *GalleryApplicationVersionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryApplicationName string, galleryApplicationVersionName string, galleryApplicationVersion GalleryApplicationVersionUpdate, options *GalleryApplicationVersionsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{galleryApplicationName}/versions/{galleryApplicationVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryApplicationName == "" { + return nil, errors.New("parameter galleryApplicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationName}", url.PathEscape(galleryApplicationName)) + if galleryApplicationVersionName == "" { + return nil, errors.New("parameter galleryApplicationVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryApplicationVersionName}", url.PathEscape(galleryApplicationVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryApplicationVersion); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryimages_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryimages_client.go new file mode 100644 index 000000000..6a684b3ed --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryimages_client.go @@ -0,0 +1,433 @@ +//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 armcompute + +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" +) + +// GalleryImagesClient contains the methods for the GalleryImages group. +// Don't use this type directly, use NewGalleryImagesClient() instead. +type GalleryImagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGalleryImagesClient creates a new instance of GalleryImagesClient 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 NewGalleryImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryImagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GalleryImagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a gallery image definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition is to be created. +// - galleryImageName - The name of the gallery image definition to be created or updated. The allowed characters are alphabets +// and numbers with dots, dashes, and periods allowed in the middle. The maximum length is 80 +// characters. +// - galleryImage - Parameters supplied to the create or update gallery image operation. +// - options - GalleryImagesClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryImagesClient.BeginCreateOrUpdate +// method. +func (client *GalleryImagesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage, options *GalleryImagesClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryImagesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryImageName, galleryImage, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImagesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImagesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a gallery image definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryImagesClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage, options *GalleryImagesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryImagesClient.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, galleryName, galleryImageName, galleryImage, 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, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *GalleryImagesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage, options *GalleryImagesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryImage); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a gallery image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition is to be deleted. +// - galleryImageName - The name of the gallery image definition to be deleted. +// - options - GalleryImagesClientBeginDeleteOptions contains the optional parameters for the GalleryImagesClient.BeginDelete +// method. +func (client *GalleryImagesClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientBeginDeleteOptions) (*runtime.Poller[GalleryImagesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryImageName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImagesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImagesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a gallery image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryImagesClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "GalleryImagesClient.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, galleryName, galleryImageName, 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 *GalleryImagesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a gallery image definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery from which the Image Definitions are to be retrieved. +// - galleryImageName - The name of the gallery image definition to be retrieved. +// - options - GalleryImagesClientGetOptions contains the optional parameters for the GalleryImagesClient.Get method. +func (client *GalleryImagesClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientGetOptions) (GalleryImagesClientGetResponse, error) { + var err error + const operationName = "GalleryImagesClient.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, galleryName, galleryImageName, options) + if err != nil { + return GalleryImagesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GalleryImagesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GalleryImagesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GalleryImagesClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImagesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *GalleryImagesClient) getHandleResponse(resp *http.Response) (GalleryImagesClientGetResponse, error) { + result := GalleryImagesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImage); err != nil { + return GalleryImagesClientGetResponse{}, err + } + return result, nil +} + +// NewListByGalleryPager - List gallery image definitions in a gallery. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery from which Image Definitions are to be listed. +// - options - GalleryImagesClientListByGalleryOptions contains the optional parameters for the GalleryImagesClient.NewListByGalleryPager +// method. +func (client *GalleryImagesClient) NewListByGalleryPager(resourceGroupName string, galleryName string, options *GalleryImagesClientListByGalleryOptions) *runtime.Pager[GalleryImagesClientListByGalleryResponse] { + return runtime.NewPager(runtime.PagingHandler[GalleryImagesClientListByGalleryResponse]{ + More: func(page GalleryImagesClientListByGalleryResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GalleryImagesClientListByGalleryResponse) (GalleryImagesClientListByGalleryResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryImagesClient.NewListByGalleryPager") + 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.listByGalleryCreateRequest(ctx, resourceGroupName, galleryName, options) + }, nil) + if err != nil { + return GalleryImagesClientListByGalleryResponse{}, err + } + return client.listByGalleryHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByGalleryCreateRequest creates the ListByGallery request. +func (client *GalleryImagesClient) listByGalleryCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, options *GalleryImagesClientListByGalleryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByGalleryHandleResponse handles the ListByGallery response. +func (client *GalleryImagesClient) listByGalleryHandleResponse(resp *http.Response) (GalleryImagesClientListByGalleryResponse, error) { + result := GalleryImagesClientListByGalleryResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImageList); err != nil { + return GalleryImagesClientListByGalleryResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a gallery image definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition is to be updated. +// - galleryImageName - The name of the gallery image definition to be updated. The allowed characters are alphabets and numbers +// with dots, dashes, and periods allowed in the middle. The maximum length is 80 characters. +// - galleryImage - Parameters supplied to the update gallery image operation. +// - options - GalleryImagesClientBeginUpdateOptions contains the optional parameters for the GalleryImagesClient.BeginUpdate +// method. +func (client *GalleryImagesClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImageUpdate, options *GalleryImagesClientBeginUpdateOptions) (*runtime.Poller[GalleryImagesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, galleryName, galleryImageName, galleryImage, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImagesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImagesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a gallery image definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryImagesClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImageUpdate, options *GalleryImagesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryImagesClient.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, galleryName, galleryImageName, galleryImage, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *GalleryImagesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImageUpdate, options *GalleryImagesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryImage); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryimageversions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryimageversions_client.go new file mode 100644 index 000000000..05f3cf352 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/galleryimageversions_client.go @@ -0,0 +1,463 @@ +//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 armcompute + +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" +) + +// GalleryImageVersionsClient contains the methods for the GalleryImageVersions group. +// Don't use this type directly, use NewGalleryImageVersionsClient() instead. +type GalleryImageVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGalleryImageVersionsClient creates a new instance of GalleryImageVersionsClient 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 NewGalleryImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GalleryImageVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GalleryImageVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides. +// - galleryImageName - The name of the gallery image definition in which the Image Version is to be created. +// - galleryImageVersionName - The name of the gallery image version to be created. Needs to follow semantic version name pattern: +// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer. +// Format: .. +// - galleryImageVersion - Parameters supplied to the create or update gallery image version operation. +// - options - GalleryImageVersionsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryImageVersionsClient.BeginCreateOrUpdate +// method. +func (client *GalleryImageVersionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion, options *GalleryImageVersionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[GalleryImageVersionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImageVersionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImageVersionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryImageVersionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion, options *GalleryImageVersionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryImageVersionsClient.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, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, 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, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *GalleryImageVersionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion, options *GalleryImageVersionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + if galleryImageVersionName == "" { + return nil, errors.New("parameter galleryImageVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryImageVersion); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides. +// - galleryImageName - The name of the gallery image definition in which the Image Version resides. +// - galleryImageVersionName - The name of the gallery image version to be deleted. +// - options - GalleryImageVersionsClientBeginDeleteOptions contains the optional parameters for the GalleryImageVersionsClient.BeginDelete +// method. +func (client *GalleryImageVersionsClient) BeginDelete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientBeginDeleteOptions) (*runtime.Poller[GalleryImageVersionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImageVersionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImageVersionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryImageVersionsClient) deleteOperation(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "GalleryImageVersionsClient.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, galleryName, galleryImageName, galleryImageVersionName, 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 *GalleryImageVersionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + if galleryImageVersionName == "" { + return nil, errors.New("parameter galleryImageVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides. +// - galleryImageName - The name of the gallery image definition in which the Image Version resides. +// - galleryImageVersionName - The name of the gallery image version to be retrieved. +// - options - GalleryImageVersionsClientGetOptions contains the optional parameters for the GalleryImageVersionsClient.Get +// method. +func (client *GalleryImageVersionsClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientGetOptions) (GalleryImageVersionsClientGetResponse, error) { + var err error + const operationName = "GalleryImageVersionsClient.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, galleryName, galleryImageName, galleryImageVersionName, options) + if err != nil { + return GalleryImageVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GalleryImageVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GalleryImageVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GalleryImageVersionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, options *GalleryImageVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + if galleryImageVersionName == "" { + return nil, errors.New("parameter galleryImageVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *GalleryImageVersionsClient) getHandleResponse(resp *http.Response) (GalleryImageVersionsClientGetResponse, error) { + result := GalleryImageVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImageVersion); err != nil { + return GalleryImageVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByGalleryImagePager - List gallery image versions in a gallery image definition. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides. +// - galleryImageName - The name of the Shared Image Gallery Image Definition from which the Image Versions are to be listed. +// - options - GalleryImageVersionsClientListByGalleryImageOptions contains the optional parameters for the GalleryImageVersionsClient.NewListByGalleryImagePager +// method. +func (client *GalleryImageVersionsClient) NewListByGalleryImagePager(resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImageVersionsClientListByGalleryImageOptions) *runtime.Pager[GalleryImageVersionsClientListByGalleryImageResponse] { + return runtime.NewPager(runtime.PagingHandler[GalleryImageVersionsClientListByGalleryImageResponse]{ + More: func(page GalleryImageVersionsClientListByGalleryImageResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GalleryImageVersionsClientListByGalleryImageResponse) (GalleryImageVersionsClientListByGalleryImageResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GalleryImageVersionsClient.NewListByGalleryImagePager") + 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.listByGalleryImageCreateRequest(ctx, resourceGroupName, galleryName, galleryImageName, options) + }, nil) + if err != nil { + return GalleryImageVersionsClientListByGalleryImageResponse{}, err + } + return client.listByGalleryImageHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByGalleryImageCreateRequest creates the ListByGalleryImage request. +func (client *GalleryImageVersionsClient) listByGalleryImageCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImageVersionsClientListByGalleryImageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByGalleryImageHandleResponse handles the ListByGalleryImage response. +func (client *GalleryImageVersionsClient) listByGalleryImageHandleResponse(resp *http.Response) (GalleryImageVersionsClientListByGalleryImageResponse, error) { + result := GalleryImageVersionsClientListByGalleryImageResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GalleryImageVersionList); err != nil { + return GalleryImageVersionsClientListByGalleryImageResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery in which the Image Definition resides. +// - galleryImageName - The name of the gallery image definition in which the Image Version is to be updated. +// - galleryImageVersionName - The name of the gallery image version to be updated. Needs to follow semantic version name pattern: +// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer. +// Format: .. +// - galleryImageVersion - Parameters supplied to the update gallery image version operation. +// - options - GalleryImageVersionsClientBeginUpdateOptions contains the optional parameters for the GalleryImageVersionsClient.BeginUpdate +// method. +func (client *GalleryImageVersionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersionUpdate, options *GalleryImageVersionsClientBeginUpdateOptions) (*runtime.Poller[GalleryImageVersionsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GalleryImageVersionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GalleryImageVersionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a gallery image version. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GalleryImageVersionsClient) update(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersionUpdate, options *GalleryImageVersionsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GalleryImageVersionsClient.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, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *GalleryImageVersionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersionUpdate, options *GalleryImageVersionsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + if galleryImageVersionName == "" { + return nil, errors.New("parameter galleryImageVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, galleryImageVersion); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/gallerysharingprofile_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/gallerysharingprofile_client.go new file mode 100644 index 000000000..28d024e97 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/gallerysharingprofile_client.go @@ -0,0 +1,125 @@ +//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 armcompute + +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" +) + +// GallerySharingProfileClient contains the methods for the GallerySharingProfile group. +// Don't use this type directly, use NewGallerySharingProfileClient() instead. +type GallerySharingProfileClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGallerySharingProfileClient creates a new instance of GallerySharingProfileClient 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 NewGallerySharingProfileClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GallerySharingProfileClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GallerySharingProfileClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginUpdate - Update sharing profile of a gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - resourceGroupName - The name of the resource group. +// - galleryName - The name of the Shared Image Gallery. +// - sharingUpdate - Parameters supplied to the update gallery sharing profile. +// - options - GallerySharingProfileClientBeginUpdateOptions contains the optional parameters for the GallerySharingProfileClient.BeginUpdate +// method. +func (client *GallerySharingProfileClient) BeginUpdate(ctx context.Context, resourceGroupName string, galleryName string, sharingUpdate SharingUpdate, options *GallerySharingProfileClientBeginUpdateOptions) (*runtime.Poller[GallerySharingProfileClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, galleryName, sharingUpdate, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GallerySharingProfileClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GallerySharingProfileClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update sharing profile of a gallery. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +func (client *GallerySharingProfileClient) update(ctx context.Context, resourceGroupName string, galleryName string, sharingUpdate SharingUpdate, options *GallerySharingProfileClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "GallerySharingProfileClient.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, galleryName, sharingUpdate, 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 *GallerySharingProfileClient) updateCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, sharingUpdate SharingUpdate, options *GallerySharingProfileClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/share" + 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 galleryName == "" { + return nil, errors.New("parameter galleryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryName}", url.PathEscape(galleryName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, sharingUpdate); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/images_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/images_client.go new file mode 100644 index 000000000..5c5ab8a93 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/images_client.go @@ -0,0 +1,462 @@ +//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 armcompute + +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" +) + +// ImagesClient contains the methods for the Images group. +// Don't use this type directly, use NewImagesClient() instead. +type ImagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewImagesClient creates a new instance of ImagesClient 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 NewImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ImagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ImagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update an image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - imageName - The name of the image. +// - parameters - Parameters supplied to the Create Image operation. +// - options - ImagesClientBeginCreateOrUpdateOptions contains the optional parameters for the ImagesClient.BeginCreateOrUpdate +// method. +func (client *ImagesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, imageName string, parameters Image, options *ImagesClientBeginCreateOrUpdateOptions) (*runtime.Poller[ImagesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, imageName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ImagesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ImagesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update an image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *ImagesClient) createOrUpdate(ctx context.Context, resourceGroupName string, imageName string, parameters Image, options *ImagesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ImagesClient.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, imageName, 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 *ImagesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, imageName string, parameters Image, options *ImagesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if imageName == "" { + return nil, errors.New("parameter imageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName)) + 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-09-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 an Image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - imageName - The name of the image. +// - options - ImagesClientBeginDeleteOptions contains the optional parameters for the ImagesClient.BeginDelete method. +func (client *ImagesClient) BeginDelete(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientBeginDeleteOptions) (*runtime.Poller[ImagesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, imageName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ImagesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ImagesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes an Image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *ImagesClient) deleteOperation(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ImagesClient.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, imageName, 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 *ImagesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if imageName == "" { + return nil, errors.New("parameter imageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets an image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - imageName - The name of the image. +// - options - ImagesClientGetOptions contains the optional parameters for the ImagesClient.Get method. +func (client *ImagesClient) Get(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientGetOptions) (ImagesClientGetResponse, error) { + var err error + const operationName = "ImagesClient.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, imageName, options) + if err != nil { + return ImagesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ImagesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ImagesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ImagesClient) getCreateRequest(ctx context.Context, resourceGroupName string, imageName string, options *ImagesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if imageName == "" { + return nil, errors.New("parameter imageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ImagesClient) getHandleResponse(resp *http.Response) (ImagesClientGetResponse, error) { + result := ImagesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Image); err != nil { + return ImagesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the list of Images in the subscription. Use nextLink property in the response to get the next page +// of Images. Do this till nextLink is null to fetch all the Images. +// +// Generated from API version 2023-09-01 +// - options - ImagesClientListOptions contains the optional parameters for the ImagesClient.NewListPager method. +func (client *ImagesClient) NewListPager(options *ImagesClientListOptions) *runtime.Pager[ImagesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ImagesClientListResponse]{ + More: func(page ImagesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ImagesClientListResponse) (ImagesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ImagesClient.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 ImagesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ImagesClient) listCreateRequest(ctx context.Context, options *ImagesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/images" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ImagesClient) listHandleResponse(resp *http.Response) (ImagesClientListResponse, error) { + result := ImagesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ImageListResult); err != nil { + return ImagesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets the list of images under a resource group. Use nextLink property in the response to +// get the next page of Images. Do this till nextLink is null to fetch all the Images. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - ImagesClientListByResourceGroupOptions contains the optional parameters for the ImagesClient.NewListByResourceGroupPager +// method. +func (client *ImagesClient) NewListByResourceGroupPager(resourceGroupName string, options *ImagesClientListByResourceGroupOptions) *runtime.Pager[ImagesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ImagesClientListByResourceGroupResponse]{ + More: func(page ImagesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ImagesClientListByResourceGroupResponse) (ImagesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ImagesClient.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 ImagesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ImagesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ImagesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ImagesClient) listByResourceGroupHandleResponse(resp *http.Response) (ImagesClientListByResourceGroupResponse, error) { + result := ImagesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ImageListResult); err != nil { + return ImagesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update an image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - imageName - The name of the image. +// - parameters - Parameters supplied to the Update Image operation. +// - options - ImagesClientBeginUpdateOptions contains the optional parameters for the ImagesClient.BeginUpdate method. +func (client *ImagesClient) BeginUpdate(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate, options *ImagesClientBeginUpdateOptions) (*runtime.Poller[ImagesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, imageName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ImagesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ImagesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update an image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *ImagesClient) update(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate, options *ImagesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ImagesClient.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, imageName, 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 +} + +// updateCreateRequest creates the Update request. +func (client *ImagesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate, options *ImagesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if imageName == "" { + return nil, errors.New("parameter imageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName)) + 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-09-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/compute/armcompute/v5/loganalytics_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/loganalytics_client.go new file mode 100644 index 000000000..a48766ffd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/loganalytics_client.go @@ -0,0 +1,200 @@ +//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 armcompute + +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" +) + +// LogAnalyticsClient contains the methods for the LogAnalytics group. +// Don't use this type directly, use NewLogAnalyticsClient() instead. +type LogAnalyticsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLogAnalyticsClient creates a new instance of LogAnalyticsClient 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 NewLogAnalyticsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LogAnalyticsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LogAnalyticsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginExportRequestRateByInterval - Export logs that show Api requests made by this subscription in the given time window +// to show throttling activities. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The location upon which virtual-machine-sizes is queried. +// - parameters - Parameters supplied to the LogAnalytics getRequestRateByInterval Api. +// - options - LogAnalyticsClientBeginExportRequestRateByIntervalOptions contains the optional parameters for the LogAnalyticsClient.BeginExportRequestRateByInterval +// method. +func (client *LogAnalyticsClient) BeginExportRequestRateByInterval(ctx context.Context, location string, parameters RequestRateByIntervalInput, options *LogAnalyticsClientBeginExportRequestRateByIntervalOptions) (*runtime.Poller[LogAnalyticsClientExportRequestRateByIntervalResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.exportRequestRateByInterval(ctx, location, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LogAnalyticsClientExportRequestRateByIntervalResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LogAnalyticsClientExportRequestRateByIntervalResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ExportRequestRateByInterval - Export logs that show Api requests made by this subscription in the given time window to +// show throttling activities. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *LogAnalyticsClient) exportRequestRateByInterval(ctx context.Context, location string, parameters RequestRateByIntervalInput, options *LogAnalyticsClientBeginExportRequestRateByIntervalOptions) (*http.Response, error) { + var err error + const operationName = "LogAnalyticsClient.BeginExportRequestRateByInterval" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportRequestRateByIntervalCreateRequest(ctx, location, 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 +} + +// exportRequestRateByIntervalCreateRequest creates the ExportRequestRateByInterval request. +func (client *LogAnalyticsClient) exportRequestRateByIntervalCreateRequest(ctx context.Context, location string, parameters RequestRateByIntervalInput, options *LogAnalyticsClientBeginExportRequestRateByIntervalOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getRequestRateByInterval" + 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-09-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 +} + +// BeginExportThrottledRequests - Export logs that show total throttled Api requests for this subscription in the given time +// window. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The location upon which virtual-machine-sizes is queried. +// - parameters - Parameters supplied to the LogAnalytics getThrottledRequests Api. +// - options - LogAnalyticsClientBeginExportThrottledRequestsOptions contains the optional parameters for the LogAnalyticsClient.BeginExportThrottledRequests +// method. +func (client *LogAnalyticsClient) BeginExportThrottledRequests(ctx context.Context, location string, parameters ThrottledRequestsInput, options *LogAnalyticsClientBeginExportThrottledRequestsOptions) (*runtime.Poller[LogAnalyticsClientExportThrottledRequestsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.exportThrottledRequests(ctx, location, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LogAnalyticsClientExportThrottledRequestsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LogAnalyticsClientExportThrottledRequestsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ExportThrottledRequests - Export logs that show total throttled Api requests for this subscription in the given time window. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *LogAnalyticsClient) exportThrottledRequests(ctx context.Context, location string, parameters ThrottledRequestsInput, options *LogAnalyticsClientBeginExportThrottledRequestsOptions) (*http.Response, error) { + var err error + const operationName = "LogAnalyticsClient.BeginExportThrottledRequests" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportThrottledRequestsCreateRequest(ctx, location, 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 +} + +// exportThrottledRequestsCreateRequest creates the ExportThrottledRequests request. +func (client *LogAnalyticsClient) exportThrottledRequestsCreateRequest(ctx context.Context, location string, parameters ThrottledRequestsInput, options *LogAnalyticsClientBeginExportThrottledRequestsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getThrottledRequests" + 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-09-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/compute/armcompute/v5/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models.go new file mode 100644 index 000000000..5b5a3197b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models.go @@ -0,0 +1,8563 @@ +//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 armcompute + +import "time" + +// APIEntityReference - The API entity reference. +type APIEntityReference struct { + // The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/… + ID *string +} + +// APIError - Api error. +type APIError struct { + // The error code. + Code *string + + // The Api error details + Details []*APIErrorBase + + // The Api inner error + Innererror *InnerError + + // The error message. + Message *string + + // The target of the particular error. + Target *string +} + +// APIErrorBase - Api error base. +type APIErrorBase struct { + // The error code. + Code *string + + // The error message. + Message *string + + // The target of the particular error. + Target *string +} + +// AccessURI - A disk access SAS uri. +type AccessURI struct { + // READ-ONLY; A SAS uri for accessing a disk. + AccessSAS *string + + // READ-ONLY; A SAS uri for accessing a VM guest state. + SecurityDataAccessSAS *string +} + +// AdditionalCapabilities - Enables or disables a capability on the virtual machine or virtual machine scale set. +type AdditionalCapabilities struct { + // The flag that enables or disables hibernation capability on the VM. + HibernationEnabled *bool + + // The flag that enables or disables a capability to have one or more managed data disks with UltraSSDLRS storage account + // type on the VM or VMSS. Managed disks with storage account type UltraSSDLRS can + // be added to a virtual machine or virtual machine scale set only if this property is enabled. + UltraSSDEnabled *bool +} + +// AdditionalUnattendContent - Specifies additional XML formatted information that can be included in the Unattend.xml file, +// which is used by Windows Setup. Contents are defined by setting name, component name, and the pass in +// which the content is applied. +type AdditionalUnattendContent struct { + // The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup. + ComponentName *string + + // Specifies the XML formatted content that is added to the unattend.xml file for the specified path and component. The XML + // must be less than 4KB and must include the root element for the setting or + // feature that is being inserted. + Content *string + + // The pass name. Currently, the only allowable value is OobeSystem. + PassName *string + + // Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon. + SettingName *SettingNames +} + +// AlternativeOption - Describes the alternative option specified by the Publisher for this image when this image is deprecated. +type AlternativeOption struct { + // Describes the type of the alternative option. + Type *AlternativeType + + // Indicates the alternative option value specified by the Publisher. This is the Offer name when the type is Offer or the + // Plan name when the type is Plan. + Value *string +} + +// ApplicationProfile - Contains the list of gallery applications that should be made available to the VM/VMSS +type ApplicationProfile struct { + // Specifies the gallery applications that should be made available to the VM/VMSS + GalleryApplications []*VMGalleryApplication +} + +// AttachDetachDataDisksRequest - Specifies the input for attaching and detaching a list of managed data disks. +type AttachDetachDataDisksRequest struct { + // The list of managed data disks to be attached. + DataDisksToAttach []*DataDisksToAttach + + // The list of managed data disks to be detached. + DataDisksToDetach []*DataDisksToDetach +} + +// AutomaticOSUpgradePolicy - The configuration parameters used for performing automatic OS upgrade. +type AutomaticOSUpgradePolicy struct { + // Whether OS image rollback feature should be disabled. Default value is false. + DisableAutomaticRollback *bool + + // Indicates whether OS upgrades should automatically be applied to scale set instances in a rolling fashion when a newer + // version of the OS image becomes available. Default value is false. If this is set + // to true for Windows based scale sets, enableAutomaticUpdates + // [https://docs.microsoft.com/dotnet/api/microsoft.azure.management.compute.models.windowsconfiguration.enableautomaticupdates?view=azure-dotnet] + // is automatically set to false and cannot be set to true. + EnableAutomaticOSUpgrade *bool + + // Indicates whether Auto OS Upgrade should undergo deferral. Deferred OS upgrades will send advanced notifications on a per-VM + // basis that an OS upgrade from rolling upgrades is incoming, via the IMDS + // tag 'Platform.PendingOSUpgrade'. The upgrade then defers until the upgrade is approved via an ApproveRollingUpgrade call. + OSRollingUpgradeDeferral *bool + + // Indicates whether rolling upgrade policy should be used during Auto OS Upgrade. Default value is false. Auto OS Upgrade + // will fallback to the default policy if no policy is defined on the VMSS. + UseRollingUpgradePolicy *bool +} + +// AutomaticOSUpgradeProperties - Describes automatic OS upgrade properties on the image. +type AutomaticOSUpgradeProperties struct { + // REQUIRED; Specifies whether automatic OS upgrade is supported on the image. + AutomaticOSUpgradeSupported *bool +} + +// AutomaticRepairsPolicy - Specifies the configuration parameters for automatic repairs on the virtual machine scale set. +type AutomaticRepairsPolicy struct { + // Specifies whether automatic repairs should be enabled on the virtual machine scale set. The default value is false. + Enabled *bool + + // The amount of time for which automatic repairs are suspended due to a state change on VM. The grace time starts after the + // state change has completed. This helps avoid premature or accidental repairs. + // The time duration should be specified in ISO 8601 format. The minimum allowed grace period is 10 minutes (PT10M), which + // is also the default value. The maximum allowed grace period is 90 minutes + // (PT90M). + GracePeriod *string + + // Type of repair action (replace, restart, reimage) that will be used for repairing unhealthy virtual machines in the scale + // set. Default value is replace. + RepairAction *RepairAction +} + +// AvailabilitySet - Specifies information about the availability set that the virtual machine should be assigned to. Virtual +// machines specified in the same availability set are allocated to different nodes to maximize +// availability. For more information about availability sets, see Availability sets overview [https://docs.microsoft.com/azure/virtual-machines/availability-set-overview]. +// For more information on Azure +// planned maintenance, see Maintenance and updates for Virtual Machines in Azure [https://docs.microsoft.com/azure/virtual-machines/maintenance-and-updates]. +// Currently, a VM can only be added to an +// availability set at creation time. An existing VM cannot be added to an availability set. +type AvailabilitySet struct { + // REQUIRED; Resource location + Location *string + + // The instance view of a resource. + Properties *AvailabilitySetProperties + + // Sku of the availability set, only name is required to be set. See AvailabilitySetSkuTypes for possible set of values. Use + // 'Aligned' for virtual machines with managed disks and 'Classic' for virtual + // machines with unmanaged disks. Default value is 'Classic'. + SKU *SKU + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// AvailabilitySetListResult - The List Availability Set operation response. +type AvailabilitySetListResult struct { + // REQUIRED; The list of availability sets + Value []*AvailabilitySet + + // The URI to fetch the next page of AvailabilitySets. Call ListNext() with this URI to fetch the next page of AvailabilitySets. + NextLink *string +} + +// AvailabilitySetProperties - The instance view of a resource. +type AvailabilitySetProperties struct { + // Fault Domain count. + PlatformFaultDomainCount *int32 + + // Update Domain count. + PlatformUpdateDomainCount *int32 + + // Specifies information about the proximity placement group that the availability set should be assigned to. Minimum api-version: + // 2018-04-01. + ProximityPlacementGroup *SubResource + + // A list of references to all virtual machines in the availability set. + VirtualMachines []*SubResource + + // READ-ONLY; The resource status information. + Statuses []*InstanceViewStatus +} + +// AvailabilitySetUpdate - Specifies information about the availability set that the virtual machine should be assigned to. +// Only tags may be updated. +type AvailabilitySetUpdate struct { + // The instance view of a resource. + Properties *AvailabilitySetProperties + + // Sku of the availability set + SKU *SKU + + // Resource tags + Tags map[string]*string +} + +// AvailablePatchSummary - Describes the properties of an virtual machine instance view for available patch summary. +type AvailablePatchSummary struct { + // READ-ONLY; The activity ID of the operation that produced this result. It is used to correlate across CRP and extension + // logs. + AssessmentActivityID *string + + // READ-ONLY; The number of critical or security patches that have been detected as available and not yet installed. + CriticalAndSecurityPatchCount *int32 + + // READ-ONLY; The errors that were encountered during execution of the operation. The details array contains the list of them. + Error *APIError + + // READ-ONLY; The UTC timestamp when the operation began. + LastModifiedTime *time.Time + + // READ-ONLY; The number of all available patches excluding critical and security. + OtherPatchCount *int32 + + // READ-ONLY; The overall reboot status of the VM. It will be true when partially installed patches require a reboot to complete + // installation but the reboot has not yet occurred. + RebootPending *bool + + // READ-ONLY; The UTC timestamp when the operation began. + StartTime *time.Time + + // READ-ONLY; The overall success or failure status of the operation. It remains "InProgress" until the operation completes. + // At that point it will become "Unknown", "Failed", "Succeeded", or + // "CompletedWithWarnings." + Status *PatchOperationStatus +} + +// BillingProfile - Specifies the billing related details of a Azure Spot VM or VMSS. Minimum api-version: 2019-03-01. +type BillingProfile struct { + // Specifies the maximum price you are willing to pay for a Azure Spot VM/VMSS. This price is in US Dollars. + // This price will be compared with the current Azure Spot price for the VM size. Also, the prices are compared at the time + // of create/update of Azure Spot VM/VMSS and the operation will only succeed if + // the maxPrice is greater than the current Azure Spot price. + // The maxPrice will also be used for evicting a Azure Spot VM/VMSS if the current Azure Spot price goes beyond the maxPrice + // after creation of VM/VMSS. + // Possible values are: + // - Any decimal value greater than zero. Example: 0.01538 + // -1 – indicates default price to be up-to on-demand. + // You can set the maxPrice to -1 to indicate that the Azure Spot VM/VMSS should not be evicted for price reasons. Also, the + // default max price is -1 if it is not provided by you. + // Minimum api-version: 2019-03-01. + MaxPrice *float64 +} + +// BootDiagnostics - Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose +// VM status. You can easily view the output of your console log. Azure also enables you to see +// a screenshot of the VM from the hypervisor. +type BootDiagnostics struct { + // Whether boot diagnostics should be enabled on the Virtual Machine. + Enabled *bool + + // Uri of the storage account to use for placing the console output and screenshot. If storageUri is not specified while enabling + // boot diagnostics, managed storage will be used. + StorageURI *string +} + +// BootDiagnosticsInstanceView - The instance view of a virtual machine boot diagnostics. +type BootDiagnosticsInstanceView struct { + // READ-ONLY; The console screenshot blob URI. Note: This will not be set if boot diagnostics is currently enabled with managed + // storage. + ConsoleScreenshotBlobURI *string + + // READ-ONLY; The serial console log blob Uri. Note: This will not be set if boot diagnostics is currently enabled with managed + // storage. + SerialConsoleLogBlobURI *string + + // READ-ONLY; The boot diagnostics status information for the VM. Note: It will be set only if there are errors encountered + // in enabling boot diagnostics. + Status *InstanceViewStatus +} + +// CapacityReservation - Specifies information about the capacity reservation. +type CapacityReservation struct { + // REQUIRED; Resource location + Location *string + + // REQUIRED; SKU of the resource for which capacity needs be reserved. The SKU name and capacity is required to be set. Currently + // VM Skus with the capability called 'CapacityReservationSupported' set to true are + // supported. Refer to List Microsoft.Compute SKUs in a region (https://docs.microsoft.com/rest/api/compute/resourceskus/list) + // for supported values. + SKU *SKU + + // Properties of the Capacity reservation. + Properties *CapacityReservationProperties + + // Resource tags + Tags map[string]*string + + // Availability Zone to use for this capacity reservation. The zone has to be single value and also should be part for the + // list of zones specified during the capacity reservation group creation. The zone + // can be assigned only during creation. If not provided, the reservation supports only non-zonal deployments. If provided, + // enforces VM/VMSS using this capacity reservation to be in same zone. + Zones []*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// CapacityReservationGroup - Specifies information about the capacity reservation group that the capacity reservations should +// be assigned to. Currently, a capacity reservation can only be added to a capacity reservation group at +// creation time. An existing capacity reservation cannot be added or moved to another capacity reservation group. +type CapacityReservationGroup struct { + // REQUIRED; Resource location + Location *string + + // capacity reservation group Properties. + Properties *CapacityReservationGroupProperties + + // Resource tags + Tags map[string]*string + + // Availability Zones to use for this capacity reservation group. The zones can be assigned only during creation. If not provided, + // the group supports only regional resources in the region. If provided, + // enforces each capacity reservation in the group to be in one of the zones. + Zones []*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +type CapacityReservationGroupInstanceView struct { + // READ-ONLY; List of instance view of the capacity reservations under the capacity reservation group. + CapacityReservations []*CapacityReservationInstanceViewWithName + + // READ-ONLY; List of the subscriptions that the capacity reservation group is shared with. Note: Minimum api-version: 2023-09-01. + // Please refer to https://aka.ms/computereservationsharing for more details. + SharedSubscriptionIDs []*SubResourceReadOnly +} + +// CapacityReservationGroupListResult - The List capacity reservation group with resource group response. +type CapacityReservationGroupListResult struct { + // REQUIRED; The list of capacity reservation groups + Value []*CapacityReservationGroup + + // The URI to fetch the next page of capacity reservation groups. Call ListNext() with this URI to fetch the next page of + // capacity reservation groups. + NextLink *string +} + +// CapacityReservationGroupProperties - capacity reservation group Properties. +type CapacityReservationGroupProperties struct { + // Specifies the settings to enable sharing across subscriptions for the capacity reservation group resource. Pls. keep in + // mind the capacity reservation group resource generally can be shared across + // subscriptions belonging to a single azure AAD tenant or cross AAD tenant if there is a trust relationship established between + // the AAD tenants. Note: Minimum api-version: 2023-09-01. Please refer to + // https://aka.ms/computereservationsharing for more details. + SharingProfile *ResourceSharingProfile + + // READ-ONLY; A list of all capacity reservation resource ids that belong to capacity reservation group. + CapacityReservations []*SubResourceReadOnly + + // READ-ONLY; The capacity reservation group instance view which has the list of instance views for all the capacity reservations + // that belong to the capacity reservation group. + InstanceView *CapacityReservationGroupInstanceView + + // READ-ONLY; A list of references to all virtual machines associated to the capacity reservation group. + VirtualMachinesAssociated []*SubResourceReadOnly +} + +// CapacityReservationGroupUpdate - Specifies information about the capacity reservation group. Only tags can be updated. +type CapacityReservationGroupUpdate struct { + // capacity reservation group Properties. + Properties *CapacityReservationGroupProperties + + // Resource tags + Tags map[string]*string +} + +// CapacityReservationInstanceView - The instance view of a capacity reservation that provides as snapshot of the runtime +// properties of the capacity reservation that is managed by the platform and can change outside of control plane +// operations. +type CapacityReservationInstanceView struct { + // The resource status information. + Statuses []*InstanceViewStatus + + // Unutilized capacity of the capacity reservation. + UtilizationInfo *CapacityReservationUtilization +} + +// CapacityReservationInstanceViewWithName - The instance view of a capacity reservation that includes the name of the capacity +// reservation. It is used for the response to the instance view of a capacity reservation group. +type CapacityReservationInstanceViewWithName struct { + // The resource status information. + Statuses []*InstanceViewStatus + + // Unutilized capacity of the capacity reservation. + UtilizationInfo *CapacityReservationUtilization + + // READ-ONLY; The name of the capacity reservation. + Name *string +} + +// CapacityReservationListResult - The list capacity reservation operation response. +type CapacityReservationListResult struct { + // REQUIRED; The list of capacity reservations + Value []*CapacityReservation + + // The URI to fetch the next page of capacity reservations. Call ListNext() with this URI to fetch the next page of capacity + // reservations. + NextLink *string +} + +// CapacityReservationProfile - The parameters of a capacity reservation Profile. +type CapacityReservationProfile struct { + // Specifies the capacity reservation group resource id that should be used for allocating the virtual machine or scaleset + // vm instances provided enough capacity has been reserved. Please refer to + // https://aka.ms/CapacityReservation for more details. + CapacityReservationGroup *SubResource +} + +// CapacityReservationProperties - Properties of the Capacity reservation. +type CapacityReservationProperties struct { + // READ-ONLY; The Capacity reservation instance view. + InstanceView *CapacityReservationInstanceView + + // READ-ONLY; Specifies the value of fault domain count that Capacity Reservation supports for requested VM size. Note: The + // fault domain count specified for a resource (like virtual machines scale set) must be less + // than or equal to this value if it deploys using capacity reservation. Minimum api-version: 2022-08-01. + PlatformFaultDomainCount *int32 + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string + + // READ-ONLY; The date time when the capacity reservation was last updated. + ProvisioningTime *time.Time + + // READ-ONLY; A unique id generated and assigned to the capacity reservation by the platform which does not change throughout + // the lifetime of the resource. + ReservationID *string + + // READ-ONLY; Specifies the time at which the Capacity Reservation resource was created. Minimum api-version: 2021-11-01. + TimeCreated *time.Time + + // READ-ONLY; A list of all virtual machine resource ids that are associated with the capacity reservation. + VirtualMachinesAssociated []*SubResourceReadOnly +} + +// CapacityReservationUpdate - Specifies information about the capacity reservation. Only tags and sku.capacity can be updated. +type CapacityReservationUpdate struct { + // Properties of the Capacity reservation. + Properties *CapacityReservationProperties + + // SKU of the resource for which capacity needs be reserved. The SKU name and capacity is required to be set. Currently VM + // Skus with the capability called 'CapacityReservationSupported' set to true are + // supported. Refer to List Microsoft.Compute SKUs in a region (https://docs.microsoft.com/rest/api/compute/resourceskus/list) + // for supported values. + SKU *SKU + + // Resource tags + Tags map[string]*string +} + +// CapacityReservationUtilization - Represents the capacity reservation utilization in terms of resources allocated. +type CapacityReservationUtilization struct { + // READ-ONLY; The value provides the current capacity of the VM size which was reserved successfully and for which the customer + // is getting billed. Minimum api-version: 2022-08-01. + CurrentCapacity *int32 + + // READ-ONLY; A list of all virtual machines resource ids allocated against the capacity reservation. + VirtualMachinesAllocated []*SubResourceReadOnly +} + +// CloudService - Describes the cloud service. +type CloudService struct { + // REQUIRED; Resource location. + Location *string + + // Cloud service properties + Properties *CloudServiceProperties + + // The system meta data relating to this resource. + SystemData *SystemData + + // Resource tags. + Tags map[string]*string + + // List of logical availability zone of the resource. List should contain only 1 zone where cloud service should be provisioned. + // This field is optional. + Zones []*string + + // READ-ONLY; Resource Id. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// CloudServiceExtensionProfile - Describes a cloud service extension profile. +type CloudServiceExtensionProfile struct { + // List of extensions for the cloud service. + Extensions []*Extension +} + +// CloudServiceExtensionProperties - Extension Properties. +type CloudServiceExtensionProperties struct { + // Explicitly specify whether platform can automatically upgrade typeHandlerVersion to higher minor versions when they become + // available. + AutoUpgradeMinorVersion *bool + + // Tag to force apply the provided public and protected settings. Changing the tag value allows for re-running the extension + // without changing any of the public or protected settings. If forceUpdateTag is + // not changed, updates to public or protected settings would still be applied by the handler. If neither forceUpdateTag nor + // any of public or protected settings change, extension would flow to the role + // instance with the same sequence-number, and it is up to handler implementation whether to re-run it or not + ForceUpdateTag *string + + // Protected settings for the extension which are encrypted before sent to the role instance. + ProtectedSettings any + + // Protected settings for the extension, referenced using KeyVault which are encrypted before sent to the role instance. + ProtectedSettingsFromKeyVault *CloudServiceVaultAndSecretReference + + // The name of the extension handler publisher. + Publisher *string + + // Optional list of roles to apply this extension. If property is not specified or '*' is specified, extension is applied + // to all roles in the cloud service. + RolesAppliedTo []*string + + // Public settings for the extension. For JSON extensions, this is the JSON settings for the extension. For XML Extension + // (like RDP), this is the XML setting for the extension. + Settings any + + // Specifies the type of the extension. + Type *string + + // Specifies the version of the extension. Specifies the version of the extension. If this element is not specified or an + // asterisk (*) is used as the value, the latest version of the extension is used. + // If the value is specified with a major version number and an asterisk as the minor version number (X.), the latest minor + // version of the specified major version is selected. If a major version number + // and a minor version number are specified (X.Y), the specific extension version is selected. If a version is specified, + // an auto-upgrade is performed on the role instance. + TypeHandlerVersion *string + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string +} + +// CloudServiceInstanceView - InstanceView of CloudService as a whole +type CloudServiceInstanceView struct { + // Instance view statuses. + RoleInstance *InstanceViewStatusesSummary + + // READ-ONLY; Specifies a list of unique identifiers generated internally for the cloud service. + // NOTE: If you are using Azure Diagnostics extension, this property can be used as 'DeploymentId' for querying details. + PrivateIDs []*string + + // READ-ONLY; The version of the SDK that was used to generate the package for the cloud service. + SdkVersion *string + + // READ-ONLY + Statuses []*ResourceInstanceViewStatus +} + +// CloudServiceListResult - The list operation result. +type CloudServiceListResult struct { + // REQUIRED; The list of resources. + Value []*CloudService + + // The URI to fetch the next page of resources. Use this to get the next page of resources. Do this till nextLink is null + // to fetch all the resources. + NextLink *string +} + +// CloudServiceNetworkProfile - Network Profile for the cloud service. +type CloudServiceNetworkProfile struct { + // List of Load balancer configurations. Cloud service can have up to two load balancer configurations, corresponding to a + // Public Load Balancer and an Internal Load Balancer. + LoadBalancerConfigurations []*LoadBalancerConfiguration + + // Slot type for the cloud service. Possible values are + // Production + // Staging + // If not specified, the default value is Production. + SlotType *CloudServiceSlotType + + // The id reference of the cloud service containing the target IP with which the subject cloud service can perform a swap. + // This property cannot be updated once it is set. The swappable cloud service + // referred by this id must be present otherwise an error will be thrown. + SwappableCloudService *SubResource +} + +// CloudServiceOsProfile - Describes the OS profile for the cloud service. +type CloudServiceOsProfile struct { + // Specifies set of certificates that should be installed onto the role instances. + Secrets []*CloudServiceVaultSecretGroup +} + +// CloudServiceProperties - Cloud service properties +type CloudServiceProperties struct { + // (Optional) Indicates whether the role sku properties (roleProfile.roles.sku) specified in the model/template should override + // the role instance count and vm size specified in the .cscfg and .csdef + // respectively. The default value is false. + AllowModelOverride *bool + + // Specifies the XML service configuration (.cscfg) for the cloud service. + Configuration *string + + // Specifies a URL that refers to the location of the service configuration in the Blob service. The service package URL can + // be Shared Access Signature (SAS) URI from any storage account. This is a + // write-only property and is not returned in GET calls. + ConfigurationURL *string + + // Describes a cloud service extension profile. + ExtensionProfile *CloudServiceExtensionProfile + + // Network Profile for the cloud service. + NetworkProfile *CloudServiceNetworkProfile + + // Describes the OS profile for the cloud service. + OSProfile *CloudServiceOsProfile + + // Specifies a URL that refers to the location of the service package in the Blob service. The service package URL can be + // Shared Access Signature (SAS) URI from any storage account. This is a write-only + // property and is not returned in GET calls. + PackageURL *string + + // Describes the role profile for the cloud service. + RoleProfile *CloudServiceRoleProfile + + // (Optional) Indicates whether to start the cloud service immediately after it is created. The default value is true. If + // false, the service model is still deployed, but the code is not run immediately. + // Instead, the service is PoweredOff until you call Start, at which time the service will be started. A deployed service + // still incurs charges, even if it is poweredoff. + StartCloudService *bool + + // Update mode for the cloud service. Role instances are allocated to update domains when the service is deployed. Updates + // can be initiated manually in each update domain or initiated automatically in + // all update domains. Possible Values are + // Auto + // Manual + // Simultaneous + // If not specified, the default value is Auto. If set to Manual, PUT UpdateDomain must be called to apply the update. If + // set to Auto, the update is automatically applied to each update domain in + // sequence. + UpgradeMode *CloudServiceUpgradeMode + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string + + // READ-ONLY; The unique identifier for the cloud service. + UniqueID *string +} + +// CloudServiceRole - Describes a role of the cloud service. +type CloudServiceRole struct { + // The cloud service role properties. + Properties *CloudServiceRoleProperties + + // Describes the cloud service role sku. + SKU *CloudServiceRoleSKU + + // READ-ONLY; Resource id + ID *string + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// CloudServiceRoleListResult - The list operation result. +type CloudServiceRoleListResult struct { + // REQUIRED; The list of resources. + Value []*CloudServiceRole + + // The URI to fetch the next page of resources. Use this to get the next page of resources. Do this till nextLink is null + // to fetch all the resources. + NextLink *string +} + +// CloudServiceRoleProfile - Describes the role profile for the cloud service. +type CloudServiceRoleProfile struct { + // List of roles for the cloud service. + Roles []*CloudServiceRoleProfileProperties +} + +// CloudServiceRoleProfileProperties - Describes the role properties. +type CloudServiceRoleProfileProperties struct { + // Resource name. + Name *string + + // Describes the cloud service role sku. + SKU *CloudServiceRoleSKU +} + +// CloudServiceRoleProperties - The cloud service role properties. +type CloudServiceRoleProperties struct { + // READ-ONLY; Specifies the ID which uniquely identifies a cloud service role. + UniqueID *string +} + +// CloudServiceRoleSKU - Describes the cloud service role sku. +type CloudServiceRoleSKU struct { + // Specifies the number of role instances in the cloud service. + Capacity *int64 + + // The sku name. NOTE: If the new SKU is not supported on the hardware the cloud service is currently on, you need to delete + // and recreate the cloud service or move back to the old sku. + Name *string + + // Specifies the tier of the cloud service. Possible Values are + // Standard + // Basic + Tier *string +} + +type CloudServiceUpdate struct { + // Resource tags + Tags map[string]*string +} + +// CloudServiceVaultAndSecretReference - Protected settings for the extension, referenced using KeyVault which are encrypted +// before sent to the role instance. +type CloudServiceVaultAndSecretReference struct { + // Secret URL which contains the protected settings of the extension + SecretURL *string + + // The ARM Resource ID of the Key Vault + SourceVault *SubResource +} + +// CloudServiceVaultCertificate - Describes a single certificate reference in a Key Vault, and where the certificate should +// reside on the role instance. +type CloudServiceVaultCertificate struct { + // This is the URL of a certificate that has been uploaded to Key Vault as a secret. + CertificateURL *string +} + +// CloudServiceVaultSecretGroup - Describes a set of certificates which are all in the same Key Vault. +type CloudServiceVaultSecretGroup struct { + // The relative URL of the Key Vault containing all of the certificates in VaultCertificates. + SourceVault *SubResource + + // The list of key vault references in SourceVault which contain certificates. + VaultCertificates []*CloudServiceVaultCertificate +} + +// CommunityGallery - Specifies information about the Community Gallery that you want to create or update. +type CommunityGallery struct { + // The identifier information of community gallery. + Identifier *CommunityGalleryIdentifier + + // Describes the properties of a community gallery. + Properties *CommunityGalleryProperties + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// CommunityGalleryIdentifier - The identifier information of community gallery. +type CommunityGalleryIdentifier struct { + // The unique id of this community gallery. + UniqueID *string +} + +// CommunityGalleryImage - Specifies information about the gallery image definition that you want to create or update. +type CommunityGalleryImage struct { + // The identifier information of community gallery. + Identifier *CommunityGalleryIdentifier + + // Describes the properties of a gallery image definition. + Properties *CommunityGalleryImageProperties + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// CommunityGalleryImageIdentifier - This is the community gallery image definition identifier. +type CommunityGalleryImageIdentifier struct { + // The name of the gallery image definition offer. + Offer *string + + // The name of the gallery image definition publisher. + Publisher *string + + // The name of the gallery image definition SKU. + SKU *string +} + +// CommunityGalleryImageList - The List Community Gallery Images operation response. +type CommunityGalleryImageList struct { + // REQUIRED; A list of community gallery images. + Value []*CommunityGalleryImage + + // The URI to fetch the next page of community gallery images. Call ListNext() with this to fetch the next page of community + // gallery images. + NextLink *string +} + +// CommunityGalleryImageProperties - Describes the properties of a gallery image definition. +type CommunityGalleryImageProperties struct { + // REQUIRED; This is the community gallery image definition identifier. + Identifier *CommunityGalleryImageIdentifier + + // REQUIRED; This property allows the user to specify whether the virtual machines created under this image are 'Generalized' + // or 'Specialized'. + OSState *OperatingSystemStateTypes + + // REQUIRED; This property allows you to specify the type of the OS that is included in the disk when creating a VM from a + // managed image. Possible values are: Windows, Linux. + OSType *OperatingSystemTypes + + // The architecture of the image. Applicable to OS disks only. + Architecture *Architecture + + // The artifact tags of a community gallery resource. + ArtifactTags map[string]*string + + // Describes the disallowed disk types. + Disallowed *Disallowed + + // The disclaimer for a community gallery resource. + Disclaimer *string + + // The end of life date of the gallery image definition. This property can be used for decommissioning purposes. This property + // is updatable. + EndOfLifeDate *time.Time + + // The end-user license agreement for the current community gallery image. + Eula *string + + // A list of gallery image features. + Features []*GalleryImageFeature + + // The hypervisor generation of the Virtual Machine. Applicable to OS disks only. + HyperVGeneration *HyperVGeneration + + // Privacy statement URI for the current community gallery image. + PrivacyStatementURI *string + + // Describes the gallery image definition purchase plan. This is used by marketplace images. + PurchasePlan *ImagePurchasePlan + + // The properties describe the recommended machine configuration for this Image Definition. These properties are updatable. + Recommended *RecommendedMachineConfiguration +} + +// CommunityGalleryImageVersion - Specifies information about the gallery image version that you want to create or update. +type CommunityGalleryImageVersion struct { + // The identifier information of community gallery. + Identifier *CommunityGalleryIdentifier + + // Describes the properties of a gallery image version. + Properties *CommunityGalleryImageVersionProperties + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// CommunityGalleryImageVersionList - The List Community Gallery Image versions operation response. +type CommunityGalleryImageVersionList struct { + // REQUIRED; A list of community gallery image versions. + Value []*CommunityGalleryImageVersion + + // The URI to fetch the next page of community gallery image versions. Call ListNext() with this to fetch the next page of + // community gallery image versions. + NextLink *string +} + +// CommunityGalleryImageVersionProperties - Describes the properties of a gallery image version. +type CommunityGalleryImageVersionProperties struct { + // The artifact tags of a community gallery resource. + ArtifactTags map[string]*string + + // The disclaimer for a community gallery resource. + Disclaimer *string + + // The end of life date of the gallery image version Definition. This property can be used for decommissioning purposes. This + // property is updatable. + EndOfLifeDate *time.Time + + // If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. + ExcludeFromLatest *bool + + // The published date of the gallery image version Definition. This property can be used for decommissioning purposes. This + // property is updatable. + PublishedDate *time.Time + + // Describes the storage profile of the image version. + StorageProfile *SharedGalleryImageVersionStorageProfile +} + +// CommunityGalleryInfo - Information of community gallery if current gallery is shared to community +type CommunityGalleryInfo struct { + // End-user license agreement for community gallery image. + Eula *string + + // The prefix of the gallery name that will be displayed publicly. Visible to all users. + PublicNamePrefix *string + + // Community gallery publisher support email. The email address of the publisher. Visible to all users. + PublisherContact *string + + // The link to the publisher website. Visible to all users. + PublisherURI *string + + // READ-ONLY; Contains info about whether community gallery sharing is enabled. + CommunityGalleryEnabled *bool + + // READ-ONLY; Community gallery public name list. + PublicNames []*string +} + +// CommunityGalleryMetadata - The metadata of community gallery. +type CommunityGalleryMetadata struct { + // REQUIRED; A list of public names the gallery has. + PublicNames []*string + + // REQUIRED; The publisher email id of this community gallery. + PublisherContact *string + + // The end-user license agreement for this community gallery. + Eula *string + + // The link for the privacy statement of this community gallery from the gallery publisher. + PrivacyStatementURI *string + + // The publisher URI of this community gallery. + PublisherURI *string +} + +// CommunityGalleryProperties - Describes the properties of a community gallery. +type CommunityGalleryProperties struct { + // The artifact tags of a community gallery resource. + ArtifactTags map[string]*string + + // The metadata of community gallery. + CommunityMetadata *CommunityGalleryMetadata + + // The disclaimer for a community gallery resource. + Disclaimer *string +} + +// CopyCompletionError - Indicates the error details if the background copy of a resource created via the CopyStart operation +// fails. +type CopyCompletionError struct { + // REQUIRED; Indicates the error code if the background copy of a resource created via the CopyStart operation fails. + ErrorCode *CopyCompletionErrorReason + + // REQUIRED; Indicates the error message if the background copy of a resource created via the CopyStart operation fails. + ErrorMessage *string +} + +// CreationData - Data used when creating a disk. +type CreationData struct { + // REQUIRED; This enumerates the possible sources of a disk's creation. + CreateOption *DiskCreateOption + + // Required if createOption is CopyFromSanSnapshot. This is the ARM id of the source elastic san volume snapshot. + ElasticSanResourceID *string + + // Required if creating from a Gallery Image. The id/sharedGalleryImageId/communityGalleryImageId of the ImageDiskReference + // will be the ARM id of the shared galley image version from which to create a + // disk. + GalleryImageReference *ImageDiskReference + + // Disk source information for PIR or user images. + ImageReference *ImageDiskReference + + // Logical sector size in bytes for Ultra disks. Supported values are 512 ad 4096. 4096 is the default. + LogicalSectorSize *int32 + + // Set this flag to true to get a boost on the performance target of the disk deployed, see here on the respective performance + // target. This flag can only be set on disk creation time and cannot be + // disabled after enabled. + PerformancePlus *bool + + // If createOption is ImportSecure, this is the URI of a blob to be imported into VM guest state. + SecurityDataURI *string + + // If createOption is Copy, this is the ARM id of the source snapshot or disk. + SourceResourceID *string + + // If createOption is Import, this is the URI of a blob to be imported into a managed disk. + SourceURI *string + + // Required if createOption is Import. The Azure Resource Manager identifier of the storage account containing the blob to + // import as a disk. + StorageAccountID *string + + // If createOption is Upload, this is the size of the contents of the upload including the VHD footer. This value should be + // between 20972032 (20 MiB + 512 bytes for the VHD footer) and 35183298347520 + // bytes (32 TiB + 512 bytes for the VHD footer). + UploadSizeBytes *int64 + + // READ-ONLY; If this field is set, this is the unique id identifying the source of this resource. + SourceUniqueID *string +} + +// DataDisk - Describes a data disk. +type DataDisk struct { + // REQUIRED; Specifies how the virtual machine should be created. Possible values are: Attach. This value is used when you + // are using a specialized disk to create the virtual machine. FromImage. This value is used + // when you are using an image to create the virtual machine. If you are using a platform image, you should also use the imageReference + // element described above. If you are using a marketplace image, you + // should also use the plan element previously described. + CreateOption *DiskCreateOptionTypes + + // REQUIRED; Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and + // therefore must be unique for each data disk attached to a VM. + Lun *int32 + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for + // Standard storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies whether data disk should be deleted or detached upon VM deletion. Possible values are: Delete. If this value + // is used, the data disk is deleted when VM is deleted. Detach. If this value is + // used, the data disk is retained after VM is deleted. The default value is set to Detach. + DeleteOption *DiskDeleteOptionTypes + + // Specifies the detach behavior to be used while detaching a disk or which is already in the process of detachment from the + // virtual machine. Supported values: ForceDetach. detachOption: ForceDetach is + // applicable only for managed data disks. If a previous detachment attempt of the data disk did not complete due to an unexpected + // failure from the virtual machine and the disk is still not released then + // use force-detach as a last resort option to detach the disk forcibly from the VM. All writes might not have been flushed + // when using this detach behavior. This feature is still in preview mode and is + // not supported for VirtualMachineScaleSet. To force-detach a data disk update toBeDetached to 'true' along with setting + // detachOption: 'ForceDetach'. + DetachOption *DiskDetachOptionTypes + + // Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a + // virtual machine image. The property 'diskSizeGB' is the number of bytes x 1024^3 + // for the disk and the value cannot be larger than 1023. + DiskSizeGB *int32 + + // The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. + // If SourceImage is provided, the destination virtual hard drive must not + // exist. + Image *VirtualHardDisk + + // The managed disk parameters. + ManagedDisk *ManagedDiskParameters + + // The disk name. + Name *string + + // Specifies whether the data disk is in process of detachment from the VirtualMachine/VirtualMachineScaleset + ToBeDetached *bool + + // The virtual hard disk. + Vhd *VirtualHardDisk + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool + + // READ-ONLY; Specifies the Read-Write IOPS for the managed disk when StorageAccountType is UltraSSD_LRS. Returned only for + // VirtualMachine ScaleSet VM disks. Can be updated only via updates to the VirtualMachine + // Scale Set. + DiskIOPSReadWrite *int64 + + // READ-ONLY; Specifies the bandwidth in MB per second for the managed disk when StorageAccountType is UltraSSD_LRS. Returned + // only for VirtualMachine ScaleSet VM disks. Can be updated only via updates to the + // VirtualMachine Scale Set. + DiskMBpsReadWrite *int64 +} + +// DataDiskImage - Contains the data disk images information. +type DataDiskImage struct { + // READ-ONLY; Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM + // and therefore must be unique for each data disk attached to a VM. + Lun *int32 +} + +// DataDiskImageEncryption - Contains encryption settings for a data disk image. +type DataDiskImageEncryption struct { + // REQUIRED; This property specifies the logical unit number of the data disk. This value is used to identify data disks within + // the Virtual Machine and therefore must be unique for each data disk attached to the + // Virtual Machine. + Lun *int32 + + // A relative URI containing the resource ID of the disk encryption set. + DiskEncryptionSetID *string +} + +// DataDisksToAttach - Describes the data disk to be attached. +type DataDisksToAttach struct { + // REQUIRED; ID of the managed data disk. + DiskID *string + + // The logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be + // unique for each data disk attached to a VM. If not specified, lun would be auto + // assigned. + Lun *int32 +} + +// DataDisksToDetach - Describes the data disk to be detached. +type DataDisksToDetach struct { + // REQUIRED; ID of the managed data disk. + DiskID *string + + // Supported options available for Detach of a disk from a VM. Refer to DetachOption object reference for more details. + DetachOption *DiskDetachOptionTypes +} + +// DedicatedHost - Specifies information about the Dedicated host. +type DedicatedHost struct { + // REQUIRED; Resource location + Location *string + + // REQUIRED; SKU of the dedicated host for Hardware Generation and VM family. Only name is required to be set. List Microsoft.Compute + // SKUs for a list of possible values. + SKU *SKU + + // Properties of the dedicated host. + Properties *DedicatedHostProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// DedicatedHostAllocatableVM - Represents the dedicated host unutilized capacity in terms of a specific VM size. +type DedicatedHostAllocatableVM struct { + // Maximum number of VMs of size vmSize that can fit in the dedicated host's remaining capacity. + Count *float64 + + // VM size in terms of which the unutilized capacity is represented. + VMSize *string +} + +// DedicatedHostAvailableCapacity - Dedicated host unutilized capacity. +type DedicatedHostAvailableCapacity struct { + // The unutilized capacity of the dedicated host represented in terms of each VM size that is allowed to be deployed to the + // dedicated host. + AllocatableVMs []*DedicatedHostAllocatableVM +} + +// DedicatedHostGroup - Specifies information about the dedicated host group that the dedicated hosts should be assigned to. +// Currently, a dedicated host can only be added to a dedicated host group at creation time. An +// existing dedicated host cannot be added to another dedicated host group. +type DedicatedHostGroup struct { + // REQUIRED; Resource location + Location *string + + // Dedicated Host Group Properties. + Properties *DedicatedHostGroupProperties + + // Resource tags + Tags map[string]*string + + // Availability Zone to use for this host group. Only single zone is supported. The zone can be assigned only during creation. + // If not provided, the group supports all zones in the region. If provided, + // enforces each host in the group to be in the same zone. + Zones []*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +type DedicatedHostGroupInstanceView struct { + // List of instance view of the dedicated hosts under the dedicated host group. + Hosts []*DedicatedHostInstanceViewWithName +} + +// DedicatedHostGroupListResult - The List Dedicated Host Group with resource group response. +type DedicatedHostGroupListResult struct { + // REQUIRED; The list of dedicated host groups + Value []*DedicatedHostGroup + + // The URI to fetch the next page of Dedicated Host Groups. Call ListNext() with this URI to fetch the next page of Dedicated + // Host Groups. + NextLink *string +} + +// DedicatedHostGroupProperties - Dedicated Host Group Properties. +type DedicatedHostGroupProperties struct { + // REQUIRED; Number of fault domains that the host group can span. + PlatformFaultDomainCount *int32 + + // Enables or disables a capability on the dedicated host group. Minimum api-version: 2022-03-01. + AdditionalCapabilities *DedicatedHostGroupPropertiesAdditionalCapabilities + + // Specifies whether virtual machines or virtual machine scale sets can be placed automatically on the dedicated host group. + // Automatic placement means resources are allocated on dedicated hosts, that are + // chosen by Azure, under the dedicated host group. The value is defaulted to 'false' when not provided. Minimum api-version: + // 2020-06-01. + SupportAutomaticPlacement *bool + + // READ-ONLY; A list of references to all dedicated hosts in the dedicated host group. + Hosts []*SubResourceReadOnly + + // READ-ONLY; The dedicated host group instance view, which has the list of instance view of the dedicated hosts under the + // dedicated host group. + InstanceView *DedicatedHostGroupInstanceView +} + +// DedicatedHostGroupPropertiesAdditionalCapabilities - Enables or disables a capability on the dedicated host group. Minimum +// api-version: 2022-03-01. +type DedicatedHostGroupPropertiesAdditionalCapabilities struct { + // The flag that enables or disables a capability to have UltraSSD Enabled Virtual Machines on Dedicated Hosts of the Dedicated + // Host Group. For the Virtual Machines to be UltraSSD Enabled, + // UltraSSDEnabled flag for the resource needs to be set true as well. The value is defaulted to 'false' when not provided. + // Please refer to + // https://docs.microsoft.com/en-us/azure/virtual-machines/disks-enable-ultra-ssd for more details on Ultra SSD feature. Note: + // The ultraSSDEnabled setting can only be enabled for Host Groups that are + // created as zonal. Minimum api-version: 2022-03-01. + UltraSSDEnabled *bool +} + +// DedicatedHostGroupUpdate - Specifies information about the dedicated host group that the dedicated host should be assigned +// to. Only tags may be updated. +type DedicatedHostGroupUpdate struct { + // Dedicated Host Group Properties. + Properties *DedicatedHostGroupProperties + + // Resource tags + Tags map[string]*string + + // Availability Zone to use for this host group. Only single zone is supported. The zone can be assigned only during creation. + // If not provided, the group supports all zones in the region. If provided, + // enforces each host in the group to be in the same zone. + Zones []*string +} + +// DedicatedHostInstanceView - The instance view of a dedicated host. +type DedicatedHostInstanceView struct { + // Unutilized capacity of the dedicated host. + AvailableCapacity *DedicatedHostAvailableCapacity + + // The resource status information. + Statuses []*InstanceViewStatus + + // READ-ONLY; Specifies the unique id of the dedicated physical machine on which the dedicated host resides. + AssetID *string +} + +// DedicatedHostInstanceViewWithName - The instance view of a dedicated host that includes the name of the dedicated host. +// It is used for the response to the instance view of a dedicated host group. +type DedicatedHostInstanceViewWithName struct { + // Unutilized capacity of the dedicated host. + AvailableCapacity *DedicatedHostAvailableCapacity + + // The resource status information. + Statuses []*InstanceViewStatus + + // READ-ONLY; Specifies the unique id of the dedicated physical machine on which the dedicated host resides. + AssetID *string + + // READ-ONLY; The name of the dedicated host. + Name *string +} + +// DedicatedHostListResult - The list dedicated host operation response. +type DedicatedHostListResult struct { + // REQUIRED; The list of dedicated hosts + Value []*DedicatedHost + + // The URI to fetch the next page of dedicated hosts. Call ListNext() with this URI to fetch the next page of dedicated hosts. + NextLink *string +} + +// DedicatedHostProperties - Properties of the dedicated host. +type DedicatedHostProperties struct { + // Specifies whether the dedicated host should be replaced automatically in case of a failure. The value is defaulted to 'true' + // when not provided. + AutoReplaceOnFailure *bool + + // Specifies the software license type that will be applied to the VMs deployed on the dedicated host. Possible values are: + // None, WindowsServerHybrid, WindowsServerPerpetual. The default value is: None. + LicenseType *DedicatedHostLicenseTypes + + // Fault domain of the dedicated host within a dedicated host group. + PlatformFaultDomain *int32 + + // READ-ONLY; A unique id generated and assigned to the dedicated host by the platform. Does not change throughout the lifetime + // of the host. + HostID *string + + // READ-ONLY; The dedicated host instance view. + InstanceView *DedicatedHostInstanceView + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string + + // READ-ONLY; The date when the host was first provisioned. + ProvisioningTime *time.Time + + // READ-ONLY; Specifies the time at which the Dedicated Host resource was created. Minimum api-version: 2021-11-01. + TimeCreated *time.Time + + // READ-ONLY; A list of references to all virtual machines in the Dedicated Host. + VirtualMachines []*SubResourceReadOnly +} + +// DedicatedHostSizeListResult - The List Dedicated Host sizes operation response. +type DedicatedHostSizeListResult struct { + // The list of dedicated host sizes. + Value []*string +} + +// DedicatedHostUpdate - Specifies information about the dedicated host. Only tags, autoReplaceOnFailure and licenseType may +// be updated. +type DedicatedHostUpdate struct { + // Properties of the dedicated host. + Properties *DedicatedHostProperties + + // List all available dedicated host sizes for resizing [https://docs.microsoft.com/rest/api/compute/dedicated-hosts/listavailablesizes]. + // Resizing can be only used to scale up DedicatedHost. Only name is + // required to be set. + SKU *SKU + + // Resource tags + Tags map[string]*string +} + +// DiagnosticsProfile - Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15. +type DiagnosticsProfile struct { + // Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. NOTE: + // If storageUri is being specified then ensure that the storage account is in + // the same region and subscription as the VM. You can easily view the output of your console log. Azure also enables you + // to see a screenshot of the VM from the hypervisor. + BootDiagnostics *BootDiagnostics +} + +// DiffDiskSettings - Describes the parameters of ephemeral disk settings that can be specified for operating system disk. +// Note: The ephemeral disk settings can only be specified for managed disk. +type DiffDiskSettings struct { + // Specifies the ephemeral disk settings for operating system disk. + Option *DiffDiskOptions + + // Specifies the ephemeral disk placement for operating system disk. Possible values are: CacheDisk, ResourceDisk. The defaulting + // behavior is: CacheDisk if one is configured for the VM size otherwise + // ResourceDisk is used. Refer to the VM size documentation for Windows VM at https://docs.microsoft.com/azure/virtual-machines/windows/sizes + // and Linux VM at + // https://docs.microsoft.com/azure/virtual-machines/linux/sizes to check which VM sizes exposes a cache disk. + Placement *DiffDiskPlacement +} + +// Disallowed - Describes the disallowed disk types. +type Disallowed struct { + // A list of disk types. + DiskTypes []*string +} + +// DisallowedConfiguration - Specifies the disallowed configuration for a virtual machine image. +type DisallowedConfiguration struct { + // VM disk types which are disallowed. + VMDiskType *VMDiskTypes +} + +// Disk resource. +type Disk struct { + // REQUIRED; Resource location + Location *string + + // The extended location where the disk will be created. Extended location cannot be changed. + ExtendedLocation *ExtendedLocation + + // Disk resource properties. + Properties *DiskProperties + + // The disks sku name. Can be StandardLRS, PremiumLRS, StandardSSDLRS, UltraSSDLRS, PremiumZRS, StandardSSDZRS, or PremiumV2_LRS. + SKU *DiskSKU + + // Resource tags + Tags map[string]*string + + // The Logical zone list for Disk. + Zones []*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; A relative URI containing the ID of the VM that has the disk attached. + ManagedBy *string + + // READ-ONLY; List of relative URIs containing the IDs of the VMs that have the disk attached. maxShares should be set to + // a value greater than one for disks to allow attaching them to multiple VMs. + ManagedByExtended []*string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// DiskAccess - disk access resource. +type DiskAccess struct { + // REQUIRED; Resource location + Location *string + + // The extended location where the disk access will be created. Extended location cannot be changed. + ExtendedLocation *ExtendedLocation + Properties *DiskAccessProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// DiskAccessList - The List disk access operation response. +type DiskAccessList struct { + // REQUIRED; A list of disk access resources. + Value []*DiskAccess + + // The uri to fetch the next page of disk access resources. Call ListNext() with this to fetch the next page of disk access + // resources. + NextLink *string +} + +type DiskAccessProperties struct { + // READ-ONLY; A readonly collection of private endpoint connections created on the disk. Currently only one endpoint connection + // is supported. + PrivateEndpointConnections []*PrivateEndpointConnection + + // READ-ONLY; The disk access resource provisioning state. + ProvisioningState *string + + // READ-ONLY; The time when the disk access was created. + TimeCreated *time.Time +} + +// DiskAccessUpdate - Used for updating a disk access resource. +type DiskAccessUpdate struct { + // Resource tags + Tags map[string]*string +} + +// DiskEncryptionSet - disk encryption set resource. +type DiskEncryptionSet struct { + // REQUIRED; Resource location + Location *string + + // The managed identity for the disk encryption set. It should be given permission on the key vault before it can be used + // to encrypt disks. + Identity *EncryptionSetIdentity + Properties *EncryptionSetProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// DiskEncryptionSetList - The List disk encryption set operation response. +type DiskEncryptionSetList struct { + // REQUIRED; A list of disk encryption sets. + Value []*DiskEncryptionSet + + // The uri to fetch the next page of disk encryption sets. Call ListNext() with this to fetch the next page of disk encryption + // sets. + NextLink *string +} + +// DiskEncryptionSetParameters - Describes the parameter of customer managed disk encryption set resource id that can be specified +// for disk. Note: The disk encryption set resource id can only be specified for managed disk. Please +// refer https://aka.ms/mdssewithcmkoverview for more details. +type DiskEncryptionSetParameters struct { + // Resource Id + ID *string +} + +// DiskEncryptionSetUpdate - disk encryption set update resource. +type DiskEncryptionSetUpdate struct { + // The managed identity for the disk encryption set. It should be given permission on the key vault before it can be used + // to encrypt disks. + Identity *EncryptionSetIdentity + + // disk encryption set resource update properties. + Properties *DiskEncryptionSetUpdateProperties + + // Resource tags + Tags map[string]*string +} + +// DiskEncryptionSetUpdateProperties - disk encryption set resource update properties. +type DiskEncryptionSetUpdateProperties struct { + // Key Vault Key Url to be used for server side encryption of Managed Disks and Snapshots + ActiveKey *KeyForDiskEncryptionSet + + // The type of key used to encrypt the data of the disk. + EncryptionType *DiskEncryptionSetType + + // Multi-tenant application client id to access key vault in a different tenant. Setting the value to 'None' will clear the + // property. + FederatedClientID *string + + // Set this flag to true to enable auto-updating of this disk encryption set to the latest key version. + RotationToLatestKeyVersionEnabled *bool +} + +// DiskEncryptionSettings - Describes a Encryption Settings for a Disk +type DiskEncryptionSettings struct { + // Specifies the location of the disk encryption key, which is a Key Vault Secret. + DiskEncryptionKey *KeyVaultSecretReference + + // Specifies whether disk encryption should be enabled on the virtual machine. + Enabled *bool + + // Specifies the location of the key encryption key in Key Vault. + KeyEncryptionKey *KeyVaultKeyReference +} + +// DiskImageEncryption - This is the disk image encryption base class. +type DiskImageEncryption struct { + // A relative URI containing the resource ID of the disk encryption set. + DiskEncryptionSetID *string +} + +// DiskInstanceView - The instance view of the disk. +type DiskInstanceView struct { + // Specifies the encryption settings for the OS Disk. + // Minimum api-version: 2015-06-15 + EncryptionSettings []*DiskEncryptionSettings + + // The disk name. + Name *string + + // The resource status information. + Statuses []*InstanceViewStatus +} + +// DiskList - The List Disks operation response. +type DiskList struct { + // REQUIRED; A list of disks. + Value []*Disk + + // The uri to fetch the next page of disks. Call ListNext() with this to fetch the next page of disks. + NextLink *string +} + +// DiskProperties - Disk resource properties. +type DiskProperties struct { + // REQUIRED; Disk source information. CreationData information cannot be changed after the disk has been created. + CreationData *CreationData + + // Set to true to enable bursting beyond the provisioned performance target of the disk. Bursting is disabled by default. + // Does not apply to Ultra disks. + BurstingEnabled *bool + + // Percentage complete for the background copy when a resource is created via the CopyStart operation. + CompletionPercent *float32 + + // Additional authentication requirements when exporting or uploading to a disk or snapshot. + DataAccessAuthMode *DataAccessAuthMode + + // ARM id of the DiskAccess resource for using private endpoints on disks. + DiskAccessID *string + + // The total number of IOPS that will be allowed across all VMs mounting the shared disk as ReadOnly. One operation can transfer + // between 4k and 256k bytes. + DiskIOPSReadOnly *int64 + + // The number of IOPS allowed for this disk; only settable for UltraSSD disks. One operation can transfer between 4k and 256k + // bytes. + DiskIOPSReadWrite *int64 + + // The total throughput (MBps) that will be allowed across all VMs mounting the shared disk as ReadOnly. MBps means millions + // of bytes per second - MB here uses the ISO notation, of powers of 10. + DiskMBpsReadOnly *int64 + + // The bandwidth allowed for this disk; only settable for UltraSSD disks. MBps means millions of bytes per second - MB here + // uses the ISO notation, of powers of 10. + DiskMBpsReadWrite *int64 + + // If creationData.createOption is Empty, this field is mandatory and it indicates the size of the disk to create. If this + // field is present for updates or creation with other options, it indicates a + // resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. + DiskSizeGB *int32 + + // Encryption property can be used to encrypt data at rest with customer managed keys or platform managed keys. + Encryption *Encryption + + // Encryption settings collection used for Azure Disk Encryption, can contain multiple encryption settings per disk or snapshot. + EncryptionSettingsCollection *EncryptionSettingsCollection + + // The hypervisor generation of the Virtual Machine. Applicable to OS disks only. + HyperVGeneration *HyperVGeneration + + // The maximum number of VMs that can attach to the disk at the same time. Value greater than one indicates a disk that can + // be mounted on multiple VMs at the same time. + MaxShares *int32 + + // Policy for accessing the disk via network. + NetworkAccessPolicy *NetworkAccessPolicy + + // The Operating System type. + OSType *OperatingSystemTypes + + // Setting this property to true improves reliability and performance of data disks that are frequently (more than 5 times + // a day) by detached from one virtual machine and attached to another. This + // property should not be set for disks that are not detached and attached frequently as it causes the disks to not align + // with the fault domain of the virtual machine. + OptimizedForFrequentAttach *bool + + // Policy for controlling export on the disk. + PublicNetworkAccess *PublicNetworkAccess + + // Purchase plan information for the the image from which the OS disk was created. E.g. - {name: 2019-Datacenter, publisher: + // MicrosoftWindowsServer, product: WindowsServer} + PurchasePlan *DiskPurchasePlan + + // Contains the security related information for the resource. + SecurityProfile *DiskSecurityProfile + + // List of supported capabilities for the image from which the OS disk was created. + SupportedCapabilities *SupportedCapabilities + + // Indicates the OS on a disk supports hibernation. + SupportsHibernation *bool + + // Performance tier of the disk (e.g, P4, S10) as described here: https://azure.microsoft.com/en-us/pricing/details/managed-disks/. + // Does not apply to Ultra disks. + Tier *string + + // READ-ONLY; Latest time when bursting was last enabled on a disk. + BurstingEnabledTime *time.Time + + // READ-ONLY; The size of the disk in bytes. This field is read only. + DiskSizeBytes *int64 + + // READ-ONLY; The state of the disk. + DiskState *DiskState + + // READ-ONLY; The UTC time when the ownership state of the disk was last changed i.e., the time the disk was last attached + // or detached from a VM or the time when the VM to which the disk was attached was + // deallocated or started. + LastOwnershipUpdateTime *time.Time + + // READ-ONLY; Properties of the disk for which update is pending. + PropertyUpdatesInProgress *PropertyUpdatesInProgress + + // READ-ONLY; The disk provisioning state. + ProvisioningState *string + + // READ-ONLY; Details of the list of all VMs that have the disk attached. maxShares should be set to a value greater than + // one for disks to allow attaching them to multiple VMs. + ShareInfo []*ShareInfoElement + + // READ-ONLY; The time when the disk was created. + TimeCreated *time.Time + + // READ-ONLY; Unique Guid identifying the resource. + UniqueID *string +} + +// DiskPurchasePlan - Used for establishing the purchase context of any 3rd Party artifact through MarketPlace. +type DiskPurchasePlan struct { + // REQUIRED; The plan ID. + Name *string + + // REQUIRED; Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference + // element. + Product *string + + // REQUIRED; The publisher ID. + Publisher *string + + // The Offer Promotion Code. + PromotionCode *string +} + +// DiskRestorePoint - Properties of disk restore point +type DiskRestorePoint struct { + // Properties of an incremental disk restore point + Properties *DiskRestorePointProperties + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// DiskRestorePointAttributes - Disk Restore Point details. +type DiskRestorePointAttributes struct { + // Encryption at rest settings for disk restore point. It is an optional property that can be specified in the input while + // creating a restore point. + Encryption *RestorePointEncryption + + // Resource Id of the source disk restore point. + SourceDiskRestorePoint *APIEntityReference + + // READ-ONLY; Resource Id + ID *string +} + +// DiskRestorePointInstanceView - The instance view of a disk restore point. +type DiskRestorePointInstanceView struct { + // Disk restore point Id. + ID *string + + // The disk restore point replication status information. + ReplicationStatus *DiskRestorePointReplicationStatus +} + +// DiskRestorePointList - The List Disk Restore Points operation response. +type DiskRestorePointList struct { + // REQUIRED; A list of disk restore points. + Value []*DiskRestorePoint + + // The uri to fetch the next page of disk restore points. Call ListNext() with this to fetch the next page of disk restore + // points. + NextLink *string +} + +// DiskRestorePointProperties - Properties of an incremental disk restore point +type DiskRestorePointProperties struct { + // Percentage complete for the background copy of disk restore point when source resource is from a different region. + CompletionPercent *float32 + + // ARM id of the DiskAccess resource for using private endpoints on disks. + DiskAccessID *string + + // The hypervisor generation of the Virtual Machine. Applicable to OS disks only. + HyperVGeneration *HyperVGeneration + + // Policy for accessing the disk via network. + NetworkAccessPolicy *NetworkAccessPolicy + + // Policy for controlling export on the disk. + PublicNetworkAccess *PublicNetworkAccess + + // Purchase plan information for the the image from which the OS disk was created. + PurchasePlan *DiskPurchasePlan + + // Contains the security related information for the resource. + SecurityProfile *DiskSecurityProfile + + // List of supported capabilities for the image from which the OS disk was created. + SupportedCapabilities *SupportedCapabilities + + // Indicates the OS on a disk supports hibernation. + SupportsHibernation *bool + + // READ-ONLY; Encryption property can be used to encrypt data at rest with customer managed keys or platform managed keys. + Encryption *Encryption + + // READ-ONLY; id of the backing snapshot's MIS family + FamilyID *string + + // READ-ONLY; The Operating System type. + OSType *OperatingSystemTypes + + // READ-ONLY; Replication state of disk restore point when source resource is from a different region. + ReplicationState *string + + // READ-ONLY; arm id of source disk or source disk restore point. + SourceResourceID *string + + // READ-ONLY; Location of source disk or source disk restore point when source resource is from a different region. + SourceResourceLocation *string + + // READ-ONLY; unique incarnation id of the source disk + SourceUniqueID *string + + // READ-ONLY; The timestamp of restorePoint creation + TimeCreated *time.Time +} + +// DiskRestorePointReplicationStatus - The instance view of a disk restore point. +type DiskRestorePointReplicationStatus struct { + // Replication completion percentage. + CompletionPercent *int32 + + // The resource status information. + Status *InstanceViewStatus +} + +// DiskSKU - The disks sku name. Can be StandardLRS, PremiumLRS, StandardSSDLRS, UltraSSDLRS, PremiumZRS, StandardSSDZRS, +// or PremiumV2_LRS. +type DiskSKU struct { + // The sku name. + Name *DiskStorageAccountTypes + + // READ-ONLY; The sku tier. + Tier *string +} + +// DiskSecurityProfile - Contains the security related information for the resource. +type DiskSecurityProfile struct { + // ResourceId of the disk encryption set associated to Confidential VM supported disk encrypted with customer managed key + SecureVMDiskEncryptionSetID *string + + // Specifies the SecurityType of the VM. Applicable for OS disks only. + SecurityType *DiskSecurityTypes +} + +// DiskUpdate - Disk update resource. +type DiskUpdate struct { + // Disk resource update properties. + Properties *DiskUpdateProperties + + // The disks sku name. Can be StandardLRS, PremiumLRS, StandardSSDLRS, UltraSSDLRS, PremiumZRS, StandardSSDZRS, or PremiumV2_LRS. + SKU *DiskSKU + + // Resource tags + Tags map[string]*string +} + +// DiskUpdateProperties - Disk resource update properties. +type DiskUpdateProperties struct { + // Set to true to enable bursting beyond the provisioned performance target of the disk. Bursting is disabled by default. + // Does not apply to Ultra disks. + BurstingEnabled *bool + + // Additional authentication requirements when exporting or uploading to a disk or snapshot. + DataAccessAuthMode *DataAccessAuthMode + + // ARM id of the DiskAccess resource for using private endpoints on disks. + DiskAccessID *string + + // The total number of IOPS that will be allowed across all VMs mounting the shared disk as ReadOnly. One operation can transfer + // between 4k and 256k bytes. + DiskIOPSReadOnly *int64 + + // The number of IOPS allowed for this disk; only settable for UltraSSD disks. One operation can transfer between 4k and 256k + // bytes. + DiskIOPSReadWrite *int64 + + // The total throughput (MBps) that will be allowed across all VMs mounting the shared disk as ReadOnly. MBps means millions + // of bytes per second - MB here uses the ISO notation, of powers of 10. + DiskMBpsReadOnly *int64 + + // The bandwidth allowed for this disk; only settable for UltraSSD disks. MBps means millions of bytes per second - MB here + // uses the ISO notation, of powers of 10. + DiskMBpsReadWrite *int64 + + // If creationData.createOption is Empty, this field is mandatory and it indicates the size of the disk to create. If this + // field is present for updates or creation with other options, it indicates a + // resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. + DiskSizeGB *int32 + + // Encryption property can be used to encrypt data at rest with customer managed keys or platform managed keys. + Encryption *Encryption + + // Encryption settings collection used be Azure Disk Encryption, can contain multiple encryption settings per disk or snapshot. + EncryptionSettingsCollection *EncryptionSettingsCollection + + // The maximum number of VMs that can attach to the disk at the same time. Value greater than one indicates a disk that can + // be mounted on multiple VMs at the same time. + MaxShares *int32 + + // Policy for accessing the disk via network. + NetworkAccessPolicy *NetworkAccessPolicy + + // the Operating System type. + OSType *OperatingSystemTypes + + // Setting this property to true improves reliability and performance of data disks that are frequently (more than 5 times + // a day) by detached from one virtual machine and attached to another. This + // property should not be set for disks that are not detached and attached frequently as it causes the disks to not align + // with the fault domain of the virtual machine. + OptimizedForFrequentAttach *bool + + // Policy for controlling export on the disk. + PublicNetworkAccess *PublicNetworkAccess + + // Purchase plan information to be added on the OS disk + PurchasePlan *DiskPurchasePlan + + // List of supported capabilities to be added on the OS disk. + SupportedCapabilities *SupportedCapabilities + + // Indicates the OS on a disk supports hibernation. + SupportsHibernation *bool + + // Performance tier of the disk (e.g, P4, S10) as described here: https://azure.microsoft.com/en-us/pricing/details/managed-disks/. + // Does not apply to Ultra disks. + Tier *string + + // READ-ONLY; Properties of the disk for which update is pending. + PropertyUpdatesInProgress *PropertyUpdatesInProgress +} + +// Encryption at rest settings for disk or snapshot +type Encryption struct { + // ResourceId of the disk encryption set to use for enabling encryption at rest. + DiskEncryptionSetID *string + + // The type of key used to encrypt the data of the disk. + Type *EncryptionType +} + +// EncryptionIdentity - Specifies the Managed Identity used by ADE to get access token for keyvault operations. +type EncryptionIdentity struct { + // Specifies ARM Resource ID of one of the user identities associated with the VM. + UserAssignedIdentityResourceID *string +} + +// EncryptionImages - Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the +// gallery artifact. +type EncryptionImages struct { + // A list of encryption specifications for data disk images. + DataDiskImages []*DataDiskImageEncryption + + // Contains encryption settings for an OS disk image. + OSDiskImage *OSDiskImageEncryption +} + +// EncryptionSetIdentity - The managed identity for the disk encryption set. It should be given permission on the key vault +// before it can be used to encrypt disks. +type EncryptionSetIdentity struct { + // The type of Managed Identity used by the DiskEncryptionSet. Only SystemAssigned is supported for new creations. Disk Encryption + // Sets can be updated with Identity type None during migration of + // subscription to a new Azure Active Directory tenant; it will cause the encrypted resources to lose access to the keys. + Type *DiskEncryptionSetIdentityType + + // The list of user identities associated with the disk encryption set. 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]*UserAssignedIdentitiesValue + + // READ-ONLY; The object id of the Managed Identity Resource. This will be sent to the RP from ARM via the x-ms-identity-principal-id + // header in the PUT request if the resource has a systemAssigned(implicit) + // identity + PrincipalID *string + + // READ-ONLY; The tenant id of the Managed Identity Resource. This will be sent to the RP from ARM via the x-ms-client-tenant-id + // header in the PUT request if the resource has a systemAssigned(implicit) identity + TenantID *string +} + +type EncryptionSetProperties struct { + // The key vault key which is currently used by this disk encryption set. + ActiveKey *KeyForDiskEncryptionSet + + // The type of key used to encrypt the data of the disk. + EncryptionType *DiskEncryptionSetType + + // Multi-tenant application client id to access key vault in a different tenant. Setting the value to 'None' will clear the + // property. + FederatedClientID *string + + // Set this flag to true to enable auto-updating of this disk encryption set to the latest key version. + RotationToLatestKeyVersionEnabled *bool + + // READ-ONLY; The error that was encountered during auto-key rotation. If an error is present, then auto-key rotation will + // not be attempted until the error on this disk encryption set is fixed. + AutoKeyRotationError *APIError + + // READ-ONLY; The time when the active key of this disk encryption set was updated. + LastKeyRotationTimestamp *time.Time + + // READ-ONLY; A readonly collection of key vault keys previously used by this disk encryption set while a key rotation is + // in progress. It will be empty if there is no ongoing key rotation. + PreviousKeys []*KeyForDiskEncryptionSet + + // READ-ONLY; The disk encryption set provisioning state. + ProvisioningState *string +} + +// EncryptionSettingsCollection - Encryption settings for disk or snapshot +type EncryptionSettingsCollection struct { + // REQUIRED; Set this flag to true and provide DiskEncryptionKey and optional KeyEncryptionKey to enable encryption. Set this + // flag to false and remove DiskEncryptionKey and KeyEncryptionKey to disable encryption. + // If EncryptionSettings is null in the request object, the existing settings remain unchanged. + Enabled *bool + + // A collection of encryption settings, one for each disk volume. + EncryptionSettings []*EncryptionSettingsElement + + // Describes what type of encryption is used for the disks. Once this field is set, it cannot be overwritten. '1.0' corresponds + // to Azure Disk Encryption with AAD app.'1.1' corresponds to Azure Disk + // Encryption. + EncryptionSettingsVersion *string +} + +// EncryptionSettingsElement - Encryption settings for one disk volume. +type EncryptionSettingsElement struct { + // Key Vault Secret Url and vault id of the disk encryption key + DiskEncryptionKey *KeyVaultAndSecretReference + + // Key Vault Key Url and vault id of the key encryption key. KeyEncryptionKey is optional and when provided is used to unwrap + // the disk encryption key. + KeyEncryptionKey *KeyVaultAndKeyReference +} + +// 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 +} + +// Extension - Describes a cloud service Extension. +type Extension struct { + // The name of the extension. + Name *string + + // Extension Properties. + Properties *CloudServiceExtensionProperties +} + +// Gallery - Specifies information about the Shared Image Gallery that you want to create or update. +type Gallery struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a Shared Image Gallery. + Properties *GalleryProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryApplication - Specifies information about the gallery Application Definition that you want to create or update. +type GalleryApplication struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a gallery Application Definition. + Properties *GalleryApplicationProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryApplicationCustomAction - A custom action that can be performed with a Gallery Application Version. +type GalleryApplicationCustomAction struct { + // REQUIRED; The name of the custom action. Must be unique within the Gallery Application Version. + Name *string + + // REQUIRED; The script to run when executing this custom action. + Script *string + + // Description to help the users understand what this custom action does. + Description *string + + // The parameters that this custom action uses + Parameters []*GalleryApplicationCustomActionParameter +} + +// GalleryApplicationCustomActionParameter - The definition of a parameter that can be passed to a custom action of a Gallery +// Application Version. +type GalleryApplicationCustomActionParameter struct { + // REQUIRED; The name of the custom action. Must be unique within the Gallery Application Version. + Name *string + + // The default value of the parameter. Only applies to string types + DefaultValue *string + + // A description to help users understand what this parameter means + Description *string + + // Indicates whether this parameter must be passed when running the custom action. + Required *bool + + // Specifies the type of the custom action parameter. Possible values are: String, ConfigurationDataBlob or LogOutputBlob + Type *GalleryApplicationCustomActionParameterType +} + +// GalleryApplicationList - The List Gallery Applications operation response. +type GalleryApplicationList struct { + // REQUIRED; A list of Gallery Applications. + Value []*GalleryApplication + + // The uri to fetch the next page of Application Definitions in the Application Gallery. Call ListNext() with this to fetch + // the next page of gallery Application Definitions. + NextLink *string +} + +// GalleryApplicationProperties - Describes the properties of a gallery Application Definition. +type GalleryApplicationProperties struct { + // REQUIRED; This property allows you to specify the supported type of the OS that application is built for. Possible values + // are: Windows, Linux. + SupportedOSType *OperatingSystemTypes + + // A list of custom actions that can be performed with all of the Gallery Application Versions within this Gallery Application. + CustomActions []*GalleryApplicationCustomAction + + // The description of this gallery Application Definition resource. This property is updatable. + Description *string + + // The end of life date of the gallery Application Definition. This property can be used for decommissioning purposes. This + // property is updatable. + EndOfLifeDate *time.Time + + // The Eula agreement for the gallery Application Definition. + Eula *string + + // The privacy statement uri. + PrivacyStatementURI *string + + // The release note uri. + ReleaseNoteURI *string +} + +// GalleryApplicationUpdate - Specifies information about the gallery Application Definition that you want to update. +type GalleryApplicationUpdate struct { + // Describes the properties of a gallery Application Definition. + Properties *GalleryApplicationProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryApplicationVersion - Specifies information about the gallery Application Version that you want to create or update. +type GalleryApplicationVersion struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a gallery image version. + Properties *GalleryApplicationVersionProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryApplicationVersionList - The List Gallery Application version operation response. +type GalleryApplicationVersionList struct { + // REQUIRED; A list of gallery Application Versions. + Value []*GalleryApplicationVersion + + // The uri to fetch the next page of gallery Application Versions. Call ListNext() with this to fetch the next page of gallery + // Application Versions. + NextLink *string +} + +// GalleryApplicationVersionProperties - Describes the properties of a gallery image version. +type GalleryApplicationVersionProperties struct { + // REQUIRED; The publishing profile of a gallery image version. + PublishingProfile *GalleryApplicationVersionPublishingProfile + + // The safety profile of the Gallery Application Version. + SafetyProfile *GalleryApplicationVersionSafetyProfile + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *GalleryProvisioningState + + // READ-ONLY; This is the replication status of the gallery image version. + ReplicationStatus *ReplicationStatus +} + +// GalleryApplicationVersionPublishingProfile - The publishing profile of a gallery image version. +type GalleryApplicationVersionPublishingProfile struct { + // REQUIRED; The source image from which the Image Version is going to be created. + Source *UserArtifactSource + + // Optional. Additional settings to pass to the vm-application-manager extension. For advanced use only. + AdvancedSettings map[string]*string + + // A list of custom actions that can be performed with this Gallery Application Version. + CustomActions []*GalleryApplicationCustomAction + + // Optional. Whether or not this application reports health. + EnableHealthCheck *bool + + // The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property + // is updatable. + EndOfLifeDate *time.Time + + // If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. + ExcludeFromLatest *bool + ManageActions *UserArtifactManage + + // The number of replicas of the Image Version to be created per region. This property would take effect for a region when + // regionalReplicaCount is not specified. This property is updatable. + ReplicaCount *int32 + + // Optional parameter which specifies the mode to be used for replication. This property is not updatable. + ReplicationMode *ReplicationMode + + // Additional settings for the VM app that contains the target package and config file name when it is deployed to target + // VM or VM scale set. + Settings *UserArtifactSettings + + // Specifies the storage account type to be used to store the image. This property is not updatable. + StorageAccountType *StorageAccountType + + // The target extended locations where the Image Version is going to be replicated to. This property is updatable. + TargetExtendedLocations []*GalleryTargetExtendedLocation + + // The target regions where the Image Version is going to be replicated to. This property is updatable. + TargetRegions []*TargetRegion + + // READ-ONLY; The timestamp for when the gallery image version is published. + PublishedDate *time.Time +} + +// GalleryApplicationVersionSafetyProfile - The safety profile of the Gallery Application Version. +type GalleryApplicationVersionSafetyProfile struct { + // Indicates whether or not removing this Gallery Image Version from replicated regions is allowed. + AllowDeletionOfReplicatedLocations *bool +} + +// GalleryApplicationVersionUpdate - Specifies information about the gallery Application Version that you want to update. +type GalleryApplicationVersionUpdate struct { + // Describes the properties of a gallery image version. + Properties *GalleryApplicationVersionProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryArtifactPublishingProfileBase - Describes the basic gallery artifact publishing profile. +type GalleryArtifactPublishingProfileBase struct { + // The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property + // is updatable. + EndOfLifeDate *time.Time + + // If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. + ExcludeFromLatest *bool + + // The number of replicas of the Image Version to be created per region. This property would take effect for a region when + // regionalReplicaCount is not specified. This property is updatable. + ReplicaCount *int32 + + // Optional parameter which specifies the mode to be used for replication. This property is not updatable. + ReplicationMode *ReplicationMode + + // Specifies the storage account type to be used to store the image. This property is not updatable. + StorageAccountType *StorageAccountType + + // The target extended locations where the Image Version is going to be replicated to. This property is updatable. + TargetExtendedLocations []*GalleryTargetExtendedLocation + + // The target regions where the Image Version is going to be replicated to. This property is updatable. + TargetRegions []*TargetRegion + + // READ-ONLY; The timestamp for when the gallery image version is published. + PublishedDate *time.Time +} + +// GalleryArtifactSafetyProfileBase - This is the safety profile of the Gallery Artifact Version. +type GalleryArtifactSafetyProfileBase struct { + // Indicates whether or not removing this Gallery Image Version from replicated regions is allowed. + AllowDeletionOfReplicatedLocations *bool +} + +// GalleryArtifactSource - The source image from which the Image Version is going to be created. +type GalleryArtifactSource struct { + // REQUIRED; The managed artifact. + ManagedImage *ManagedArtifact +} + +// GalleryArtifactVersionFullSource - The source of the gallery artifact version. +type GalleryArtifactVersionFullSource struct { + // The resource Id of the source Community Gallery Image. Only required when using Community Gallery Image as a source. + CommunityGalleryImageID *string + + // The id of the gallery artifact version source. Can specify a disk uri, snapshot uri, user image or storage account resource. + ID *string +} + +// GalleryArtifactVersionSource - The gallery artifact version source. +type GalleryArtifactVersionSource struct { + // The id of the gallery artifact version source. Can specify a disk uri, snapshot uri, user image or storage account resource. + ID *string +} + +// GalleryDataDiskImage - This is the data disk image. +type GalleryDataDiskImage struct { + // REQUIRED; This property specifies the logical unit number of the data disk. This value is used to identify data disks within + // the Virtual Machine and therefore must be unique for each data disk attached to the + // Virtual Machine. + Lun *int32 + + // The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' + HostCaching *HostCaching + + // The source for the disk image. + Source *GalleryDiskImageSource + + // READ-ONLY; This property indicates the size of the VHD to be created. + SizeInGB *int32 +} + +// GalleryDiskImage - This is the disk image base class. +type GalleryDiskImage struct { + // The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' + HostCaching *HostCaching + + // The source for the disk image. + Source *GalleryDiskImageSource + + // READ-ONLY; This property indicates the size of the VHD to be created. + SizeInGB *int32 +} + +// GalleryDiskImageSource - The source for the disk image. +type GalleryDiskImageSource struct { + // The id of the gallery artifact version source. Can specify a disk uri, snapshot uri, user image or storage account resource. + ID *string + + // The Storage Account Id that contains the vhd blob being used as a source for this artifact version. + StorageAccountID *string + + // The uri of the gallery artifact version source. Currently used to specify vhd/blob source. + URI *string +} + +// GalleryExtendedLocation - The name of the extended location. +type GalleryExtendedLocation struct { + Name *string + + // It is type of the extended location. + Type *GalleryExtendedLocationType +} + +// GalleryIdentifier - Describes the gallery unique name. +type GalleryIdentifier struct { + // READ-ONLY; The unique name of the Shared Image Gallery. This name is generated automatically by Azure. + UniqueName *string +} + +// GalleryImage - Specifies information about the gallery image definition that you want to create or update. +type GalleryImage struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a gallery image definition. + Properties *GalleryImageProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryImageFeature - A feature for gallery image. +type GalleryImageFeature struct { + // The name of the gallery image feature. + Name *string + + // The value of the gallery image feature. + Value *string +} + +// GalleryImageIdentifier - This is the gallery image definition identifier. +type GalleryImageIdentifier struct { + // REQUIRED; The name of the gallery image definition offer. + Offer *string + + // REQUIRED; The name of the gallery image definition publisher. + Publisher *string + + // REQUIRED; The name of the gallery image definition SKU. + SKU *string +} + +// GalleryImageList - The List Gallery Images operation response. +type GalleryImageList struct { + // REQUIRED; A list of Shared Image Gallery images. + Value []*GalleryImage + + // The uri to fetch the next page of Image Definitions in the Shared Image Gallery. Call ListNext() with this to fetch the + // next page of gallery image definitions. + NextLink *string +} + +// GalleryImageProperties - Describes the properties of a gallery image definition. +type GalleryImageProperties struct { + // REQUIRED; This is the gallery image definition identifier. + Identifier *GalleryImageIdentifier + + // REQUIRED; This property allows the user to specify whether the virtual machines created under this image are 'Generalized' + // or 'Specialized'. + OSState *OperatingSystemStateTypes + + // REQUIRED; This property allows you to specify the type of the OS that is included in the disk when creating a VM from a + // managed image. Possible values are: Windows, Linux. + OSType *OperatingSystemTypes + + // The architecture of the image. Applicable to OS disks only. + Architecture *Architecture + + // The description of this gallery image definition resource. This property is updatable. + Description *string + + // Describes the disallowed disk types. + Disallowed *Disallowed + + // The end of life date of the gallery image definition. This property can be used for decommissioning purposes. This property + // is updatable. + EndOfLifeDate *time.Time + + // The Eula agreement for the gallery image definition. + Eula *string + + // A list of gallery image features. + Features []*GalleryImageFeature + + // The hypervisor generation of the Virtual Machine. Applicable to OS disks only. + HyperVGeneration *HyperVGeneration + + // The privacy statement uri. + PrivacyStatementURI *string + + // Describes the gallery image definition purchase plan. This is used by marketplace images. + PurchasePlan *ImagePurchasePlan + + // The properties describe the recommended machine configuration for this Image Definition. These properties are updatable. + Recommended *RecommendedMachineConfiguration + + // The release note uri. + ReleaseNoteURI *string + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *GalleryProvisioningState +} + +// GalleryImageUpdate - Specifies information about the gallery image definition that you want to update. +type GalleryImageUpdate struct { + // Describes the properties of a gallery image definition. + Properties *GalleryImageProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryImageVersion - Specifies information about the gallery image version that you want to create or update. +type GalleryImageVersion struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a gallery image version. + Properties *GalleryImageVersionProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryImageVersionList - The List Gallery Image version operation response. +type GalleryImageVersionList struct { + // REQUIRED; A list of gallery image versions. + Value []*GalleryImageVersion + + // The uri to fetch the next page of gallery image versions. Call ListNext() with this to fetch the next page of gallery image + // versions. + NextLink *string +} + +// GalleryImageVersionProperties - Describes the properties of a gallery image version. +type GalleryImageVersionProperties struct { + // REQUIRED; This is the storage profile of a Gallery Image Version. + StorageProfile *GalleryImageVersionStorageProfile + + // The publishing profile of a gallery image Version. + PublishingProfile *GalleryImageVersionPublishingProfile + + // This is the safety profile of the Gallery Image Version. + SafetyProfile *GalleryImageVersionSafetyProfile + + // The security profile of a gallery image version + SecurityProfile *ImageVersionSecurityProfile + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *GalleryProvisioningState + + // READ-ONLY; This is the replication status of the gallery image version. + ReplicationStatus *ReplicationStatus +} + +// GalleryImageVersionPublishingProfile - The publishing profile of a gallery image Version. +type GalleryImageVersionPublishingProfile struct { + // The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property + // is updatable. + EndOfLifeDate *time.Time + + // If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. + ExcludeFromLatest *bool + + // The number of replicas of the Image Version to be created per region. This property would take effect for a region when + // regionalReplicaCount is not specified. This property is updatable. + ReplicaCount *int32 + + // Optional parameter which specifies the mode to be used for replication. This property is not updatable. + ReplicationMode *ReplicationMode + + // Specifies the storage account type to be used to store the image. This property is not updatable. + StorageAccountType *StorageAccountType + + // The target extended locations where the Image Version is going to be replicated to. This property is updatable. + TargetExtendedLocations []*GalleryTargetExtendedLocation + + // The target regions where the Image Version is going to be replicated to. This property is updatable. + TargetRegions []*TargetRegion + + // READ-ONLY; The timestamp for when the gallery image version is published. + PublishedDate *time.Time +} + +// GalleryImageVersionSafetyProfile - This is the safety profile of the Gallery Image Version. +type GalleryImageVersionSafetyProfile struct { + // Indicates whether or not removing this Gallery Image Version from replicated regions is allowed. + AllowDeletionOfReplicatedLocations *bool + + // READ-ONLY; A list of Policy Violations that have been reported for this Gallery Image Version. + PolicyViolations []*PolicyViolation + + // READ-ONLY; Indicates whether this image has been reported as violating Microsoft's policies. + ReportedForPolicyViolation *bool +} + +// GalleryImageVersionStorageProfile - This is the storage profile of a Gallery Image Version. +type GalleryImageVersionStorageProfile struct { + // A list of data disk images. + DataDiskImages []*GalleryDataDiskImage + + // This is the OS disk image. + OSDiskImage *GalleryOSDiskImage + + // The source of the gallery artifact version. + Source *GalleryArtifactVersionFullSource +} + +// GalleryImageVersionUefiSettings - Contains UEFI settings for the image version. +type GalleryImageVersionUefiSettings struct { + // Additional UEFI key signatures that will be added to the image in addition to the signature templates + AdditionalSignatures *UefiKeySignatures + + // The name of the template(s) that contains default UEFI key signatures that will be added to the image. + SignatureTemplateNames []*UefiSignatureTemplateName +} + +// GalleryImageVersionUpdate - Specifies information about the gallery image version that you want to update. +type GalleryImageVersionUpdate struct { + // Describes the properties of a gallery image version. + Properties *GalleryImageVersionProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GalleryList - The List Galleries operation response. +type GalleryList struct { + // REQUIRED; A list of galleries. + Value []*Gallery + + // The uri to fetch the next page of galleries. Call ListNext() with this to fetch the next page of galleries. + NextLink *string +} + +// GalleryOSDiskImage - This is the OS disk image. +type GalleryOSDiskImage struct { + // The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' + HostCaching *HostCaching + + // The source for the disk image. + Source *GalleryDiskImageSource + + // READ-ONLY; This property indicates the size of the VHD to be created. + SizeInGB *int32 +} + +// GalleryProperties - Describes the properties of a Shared Image Gallery. +type GalleryProperties struct { + // The description of this Shared Image Gallery resource. This property is updatable. + Description *string + + // Describes the gallery unique name. + Identifier *GalleryIdentifier + + // Profile for gallery sharing to subscription or tenant + SharingProfile *SharingProfile + + // Contains information about the soft deletion policy of the gallery. + SoftDeletePolicy *SoftDeletePolicy + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *GalleryProvisioningState + + // READ-ONLY; Sharing status of current gallery. + SharingStatus *SharingStatus +} + +type GalleryTargetExtendedLocation struct { + // Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the gallery artifact. + Encryption *EncryptionImages + + // The name of the extended location. + ExtendedLocation *GalleryExtendedLocation + + // The number of replicas of the Image Version to be created per extended location. This property is updatable. + ExtendedLocationReplicaCount *int32 + + // The name of the region. + Name *string + + // Specifies the storage account type to be used to store the image. This property is not updatable. + StorageAccountType *EdgeZoneStorageAccountType +} + +// GalleryUpdate - Specifies information about the Shared Image Gallery that you want to update. +type GalleryUpdate struct { + // Describes the properties of a Shared Image Gallery. + Properties *GalleryProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// GrantAccessData - Data used for requesting a SAS. +type GrantAccessData struct { + // REQUIRED + Access *AccessLevel + + // REQUIRED; Time duration in seconds until the SAS access expires. + DurationInSeconds *int32 + + // Used to specify the file format when making request for SAS on a VHDX file format snapshot + FileFormat *FileFormat + + // Set this flag to true to get additional SAS for VM guest state + GetSecureVMGuestStateSAS *bool +} + +// HardwareProfile - Specifies the hardware settings for the virtual machine. +type HardwareProfile struct { + // Specifies the size of the virtual machine. The enum data type is currently deprecated and will be removed by December 23rd + // 2023. The recommended way to get the list of available sizes is using these + // APIs: List all available virtual machine sizes in an availability set [https://docs.microsoft.com/rest/api/compute/availabilitysets/listavailablesizes], + // List all available virtual machine sizes in a + // region [https://docs.microsoft.com/rest/api/compute/resourceskus/list], List all available virtual machine sizes for resizing + // [https://docs.microsoft.com/rest/api/compute/virtualmachines/listavailablesizes]. For more information about virtual machine + // sizes, see Sizes for virtual machines + // [https://docs.microsoft.com/azure/virtual-machines/sizes]. The available VM sizes depend on region and availability set. + VMSize *VirtualMachineSizeTypes + + // Specifies the properties for customizing the size of the virtual machine. Minimum api-version: 2021-07-01. This feature + // is still in preview mode and is not supported for VirtualMachineScaleSet. Please + // follow the instructions in VM Customization [https://aka.ms/vmcustomization] for more details. + VMSizeProperties *VMSizeProperties +} + +// Image - The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual +// machine. If SourceImage is provided, the destination virtual hard drive must not +// exist. +type Image struct { + // REQUIRED; Resource location + Location *string + + // The extended location of the Image. + ExtendedLocation *ExtendedLocation + + // Describes the properties of an Image. + Properties *ImageProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// ImageDataDisk - Describes a data disk. +type ImageDataDisk struct { + // REQUIRED; Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and + // therefore must be unique for each data disk attached to a VM. + Lun *int32 + + // The Virtual Hard Disk. + BlobURI *string + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default values are: None for Standard + // storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies the customer managed disk encryption set resource id for the managed image disk. + DiskEncryptionSet *DiskEncryptionSetParameters + + // Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual + // machine image. This value cannot be larger than 1023 GB. + DiskSizeGB *int32 + + // The managedDisk. + ManagedDisk *SubResource + + // The snapshot. + Snapshot *SubResource + + // Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot + // be used with OS Disk. + StorageAccountType *StorageAccountTypes +} + +// ImageDeprecationStatus - Describes image deprecation status properties on the image. +type ImageDeprecationStatus struct { + // Describes the alternative option specified by the Publisher for this image when this image is deprecated. + AlternativeOption *AlternativeOption + + // Describes the state of the image. + ImageState *ImageState + + // The time, in future, at which this image will be marked as deprecated. This scheduled time is chosen by the Publisher. + ScheduledDeprecationTime *time.Time +} + +// ImageDisk - Describes a image disk. +type ImageDisk struct { + // The Virtual Hard Disk. + BlobURI *string + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default values are: None for Standard + // storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies the customer managed disk encryption set resource id for the managed image disk. + DiskEncryptionSet *DiskEncryptionSetParameters + + // Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual + // machine image. This value cannot be larger than 1023 GB. + DiskSizeGB *int32 + + // The managedDisk. + ManagedDisk *SubResource + + // The snapshot. + Snapshot *SubResource + + // Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot + // be used with OS Disk. + StorageAccountType *StorageAccountTypes +} + +// ImageDiskReference - The source image used for creating the disk. +type ImageDiskReference struct { + // A relative uri containing a community Azure Compute Gallery image reference. + CommunityGalleryImageID *string + + // A relative uri containing either a Platform Image Repository, user image, or Azure Compute Gallery image reference. + ID *string + + // If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image + // to use. For OS disks, this field is null. + Lun *int32 + + // A relative uri containing a direct shared Azure Compute Gallery image reference. + SharedGalleryImageID *string +} + +// ImageListResult - The List Image operation response. +type ImageListResult struct { + // REQUIRED; The list of Images. + Value []*Image + + // The uri to fetch the next page of Images. Call ListNext() with this to fetch the next page of Images. + NextLink *string +} + +// ImageOSDisk - Describes an Operating System disk. +type ImageOSDisk struct { + // REQUIRED; The OS State. For managed images, use Generalized. + OSState *OperatingSystemStateTypes + + // REQUIRED; This property allows you to specify the type of the OS that is included in the disk if creating a VM from a custom + // image. Possible values are: Windows, Linux. + OSType *OperatingSystemTypes + + // The Virtual Hard Disk. + BlobURI *string + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default values are: None for Standard + // storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies the customer managed disk encryption set resource id for the managed image disk. + DiskEncryptionSet *DiskEncryptionSetParameters + + // Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual + // machine image. This value cannot be larger than 1023 GB. + DiskSizeGB *int32 + + // The managedDisk. + ManagedDisk *SubResource + + // The snapshot. + Snapshot *SubResource + + // Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot + // be used with OS Disk. + StorageAccountType *StorageAccountTypes +} + +// ImageProperties - Describes the properties of an Image. +type ImageProperties struct { + // Specifies the HyperVGenerationType of the VirtualMachine created from the image. From API Version 2019-03-01 if the image + // source is a blob, then we need the user to specify the value, if the source is + // managed resource like disk or snapshot, we may require the user to specify the property if we cannot deduce it from the + // source managed resource. + HyperVGeneration *HyperVGenerationTypes + + // The source virtual machine from which Image is created. + SourceVirtualMachine *SubResource + + // Specifies the storage settings for the virtual machine disks. + StorageProfile *ImageStorageProfile + + // READ-ONLY; The provisioning state. + ProvisioningState *string +} + +// ImagePurchasePlan - Describes the gallery image definition purchase plan. This is used by marketplace images. +type ImagePurchasePlan struct { + // The plan ID. + Name *string + + // The product ID. + Product *string + + // The publisher ID. + Publisher *string +} + +// ImageReference - Specifies information about the image to use. You can specify information about platform images, marketplace +// images, or virtual machine images. This element is required when you want to use a platform +// image, marketplace image, or virtual machine image, but is not used in other creation operations. NOTE: Image reference +// publisher and offer can only be set when you create the scale set. +type ImageReference struct { + // Specified the community gallery image unique id for vm deployment. This can be fetched from community gallery image GET + // call. + CommunityGalleryImageID *string + + // Resource Id + ID *string + + // Specifies the offer of the platform image or marketplace image used to create the virtual machine. + Offer *string + + // The image publisher. + Publisher *string + + // The image SKU. + SKU *string + + // Specified the shared gallery image unique id for vm deployment. This can be fetched from shared gallery image GET call. + SharedGalleryImageID *string + + // Specifies the version of the platform image or marketplace image used to create the virtual machine. The allowed formats + // are Major.Minor.Build or 'latest'. Major, Minor, and Build are decimal numbers. + // Specify 'latest' to use the latest version of an image available at deploy time. Even if you use 'latest', the VM image + // will not automatically update after deploy time even if a new version becomes + // available. Please do not use field 'version' for gallery image deployment, gallery image should always use 'id' field for + // deployment, to use 'latest' version of gallery image, just set + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageName}' + // in the 'id' field without version input. + Version *string + + // READ-ONLY; Specifies in decimal numbers, the version of platform image or marketplace image used to create the virtual + // machine. This readonly field differs from 'version', only if the value specified in + // 'version' field is 'latest'. + ExactVersion *string +} + +// ImageStorageProfile - Describes a storage profile. +type ImageStorageProfile struct { + // Specifies the parameters that are used to add a data disk to a virtual machine. + // For more information about disks, see About disks and VHDs for Azure virtual machines [https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview]. + DataDisks []*ImageDataDisk + + // Specifies information about the operating system disk used by the virtual machine. + // For more information about disks, see About disks and VHDs for Azure virtual machines [https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview]. + OSDisk *ImageOSDisk + + // Specifies whether an image is zone resilient or not. Default is false. Zone resilient images can be created only in regions + // that provide Zone Redundant Storage (ZRS). + ZoneResilient *bool +} + +// ImageUpdate - The source user image virtual hard disk. Only tags may be updated. +type ImageUpdate struct { + // Describes the properties of an Image. + Properties *ImageProperties + + // Resource tags + Tags map[string]*string +} + +// ImageVersionSecurityProfile - The security profile of a gallery image version +type ImageVersionSecurityProfile struct { + // Contains UEFI settings for the image version. + UefiSettings *GalleryImageVersionUefiSettings +} + +// InnerError - Inner error details. +type InnerError struct { + // The internal error message or exception dump. + Errordetail *string + + // The exception type. + Exceptiontype *string +} + +// InstanceSKU - The role instance SKU. +type InstanceSKU struct { + // READ-ONLY; The sku name. + Name *string + + // READ-ONLY; The tier of the cloud service role instance. + Tier *string +} + +// InstanceViewStatus - Instance view status. +type InstanceViewStatus struct { + // The status code. + Code *string + + // The short localizable label for the status. + DisplayStatus *string + + // The level code. + Level *StatusLevelTypes + + // The detailed status message, including for alerts and error messages. + Message *string + + // The time of the status. + Time *time.Time +} + +// InstanceViewStatusesSummary - Instance view statuses. +type InstanceViewStatusesSummary struct { + // READ-ONLY; The summary. + StatusesSummary []*StatusCodeCount +} + +// KeyForDiskEncryptionSet - Key Vault Key Url to be used for server side encryption of Managed Disks and Snapshots +type KeyForDiskEncryptionSet struct { + // REQUIRED; Fully versioned Key Url pointing to a key in KeyVault. Version segment of the Url is required regardless of rotationToLatestKeyVersionEnabled + // value. + KeyURL *string + + // Resource id of the KeyVault containing the key or secret. This property is optional and cannot be used if the KeyVault + // subscription is not the same as the Disk Encryption Set subscription. + SourceVault *SourceVault +} + +// KeyVaultAndKeyReference - Key Vault Key Url and vault id of KeK, KeK is optional and when provided is used to unwrap the +// encryptionKey +type KeyVaultAndKeyReference struct { + // REQUIRED; Url pointing to a key or secret in KeyVault + KeyURL *string + + // REQUIRED; Resource id of the KeyVault containing the key or secret + SourceVault *SourceVault +} + +// KeyVaultAndSecretReference - Key Vault Secret Url and vault id of the encryption key +type KeyVaultAndSecretReference struct { + // REQUIRED; Url pointing to a key or secret in KeyVault + SecretURL *string + + // REQUIRED; Resource id of the KeyVault containing the key or secret + SourceVault *SourceVault +} + +// KeyVaultKeyReference - Describes a reference to Key Vault Key +type KeyVaultKeyReference struct { + // REQUIRED; The URL referencing a key encryption key in Key Vault. + KeyURL *string + + // REQUIRED; The relative URL of the Key Vault containing the key. + SourceVault *SubResource +} + +// KeyVaultSecretReference - Describes a reference to Key Vault Secret +type KeyVaultSecretReference struct { + // REQUIRED; The URL referencing a secret in a Key Vault. + SecretURL *string + + // REQUIRED; The relative URL of the Key Vault containing the secret. + SourceVault *SubResource +} + +// LastPatchInstallationSummary - Describes the properties of the last installed patch summary. +type LastPatchInstallationSummary struct { + // READ-ONLY; The errors that were encountered during execution of the operation. The details array contains the list of them. + Error *APIError + + // READ-ONLY; The number of all available patches but excluded explicitly by a customer-specified exclusion list match. + ExcludedPatchCount *int32 + + // READ-ONLY; The count of patches that failed installation. + FailedPatchCount *int32 + + // READ-ONLY; The activity ID of the operation that produced this result. It is used to correlate across CRP and extension + // logs. + InstallationActivityID *string + + // READ-ONLY; The count of patches that successfully installed. + InstalledPatchCount *int32 + + // READ-ONLY; The UTC timestamp when the operation began. + LastModifiedTime *time.Time + + // READ-ONLY; Describes whether the operation ran out of time before it completed all its intended actions + MaintenanceWindowExceeded *bool + + // READ-ONLY; The number of all available patches but not going to be installed because it didn't match a classification or + // inclusion list entry. + NotSelectedPatchCount *int32 + + // READ-ONLY; The number of all available patches expected to be installed over the course of the patch installation operation. + PendingPatchCount *int32 + + // READ-ONLY; The UTC timestamp when the operation began. + StartTime *time.Time + + // READ-ONLY; The overall success or failure status of the operation. It remains "InProgress" until the operation completes. + // At that point it will become "Unknown", "Failed", "Succeeded", or + // "CompletedWithWarnings." + Status *PatchOperationStatus +} + +// LatestGalleryImageVersion - The gallery image version with latest version in a particular region. +type LatestGalleryImageVersion struct { + // The name of the latest version in the region. + LatestVersionName *string + + // region of the Gallery Image Version. + Location *string +} + +// LinuxConfiguration - Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux +// distributions, see Linux on Azure-Endorsed Distributions +// [https://docs.microsoft.com/azure/virtual-machines/linux/endorsed-distros]. +type LinuxConfiguration struct { + // Specifies whether password authentication should be disabled. + DisablePasswordAuthentication *bool + + // Indicates whether VMAgent Platform Updates is enabled for the Linux virtual machine. Default value is false. + EnableVMAgentPlatformUpdates *bool + + // [Preview Feature] Specifies settings related to VM Guest Patching on Linux. + PatchSettings *LinuxPatchSettings + + // Indicates whether virtual machine agent should be provisioned on the virtual machine. When this property is not specified + // in the request body, default behavior is to set it to true. This will ensure + // that VM Agent is installed on the VM so that extensions can be added to the VM later. + ProvisionVMAgent *bool + + // Specifies the ssh key configuration for a Linux OS. + SSH *SSHConfiguration +} + +// LinuxParameters - Input for InstallPatches on a Linux VM, as directly received by the API +type LinuxParameters struct { + // The update classifications to select when installing patches for Linux. + ClassificationsToInclude []*VMGuestPatchClassificationLinux + + // This is used as a maintenance run identifier for Auto VM Guest Patching in Linux. + MaintenanceRunID *string + + // packages to exclude in the patch operation. Format: packageName_packageVersion + PackageNameMasksToExclude []*string + + // packages to include in the patch operation. Format: packageName_packageVersion + PackageNameMasksToInclude []*string +} + +// LinuxPatchSettings - Specifies settings related to VM Guest Patching on Linux. +type LinuxPatchSettings struct { + // Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine. + // Possible values are: + // ImageDefault - You control the timing of patch assessments on a virtual machine. + // AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true. + AssessmentMode *LinuxPatchAssessmentMode + + // Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Linux. + AutomaticByPlatformSettings *LinuxVMGuestPatchAutomaticByPlatformSettings + + // Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale + // set with OrchestrationMode as Flexible. + // Possible values are: + // ImageDefault - The virtual machine's default patching configuration is used. + // AutomaticByPlatform - The virtual machine will be automatically updated by the platform. The property provisionVMAgent + // must be true + PatchMode *LinuxVMGuestPatchMode +} + +// LinuxVMGuestPatchAutomaticByPlatformSettings - Specifies additional settings to be applied when patch mode AutomaticByPlatform +// is selected in Linux patch settings. +type LinuxVMGuestPatchAutomaticByPlatformSettings struct { + // Enables customer to schedule patching without accidental upgrades + BypassPlatformSafetyChecksOnUserSchedule *bool + + // Specifies the reboot setting for all AutomaticByPlatform patch installation operations. + RebootSetting *LinuxVMGuestPatchAutomaticByPlatformRebootSetting +} + +// ListUsagesResult - The List Usages operation response. +type ListUsagesResult struct { + // REQUIRED; The list of compute resource usages. + Value []*Usage + + // The URI to fetch the next page of compute resource usage information. Call ListNext() with this to fetch the next page + // of compute resource usage information. + NextLink *string +} + +// LoadBalancerConfiguration - Describes the load balancer configuration. +type LoadBalancerConfiguration struct { + // REQUIRED; The name of the Load balancer + Name *string + + // REQUIRED; Properties of the load balancer configuration. + Properties *LoadBalancerConfigurationProperties + + // Resource Id + ID *string +} + +// LoadBalancerConfigurationProperties - Describes the properties of the load balancer configuration. +type LoadBalancerConfigurationProperties struct { + // REQUIRED; Specifies the frontend IP to be used for the load balancer. Only IPv4 frontend IP address is supported. Each + // load balancer configuration must have exactly one frontend IP configuration. + FrontendIPConfigurations []*LoadBalancerFrontendIPConfiguration +} + +// LoadBalancerFrontendIPConfiguration - Specifies the frontend IP to be used for the load balancer. Only IPv4 frontend IP +// address is supported. Each load balancer configuration must have exactly one frontend IP configuration. +type LoadBalancerFrontendIPConfiguration struct { + // REQUIRED; The name of the resource that is unique within the set of frontend IP configurations used by the load balancer. + // This name can be used to access the resource. + Name *string + + // REQUIRED; Properties of load balancer frontend ip configuration. + Properties *LoadBalancerFrontendIPConfigurationProperties +} + +// LoadBalancerFrontendIPConfigurationProperties - Describes a cloud service IP Configuration +type LoadBalancerFrontendIPConfigurationProperties struct { + // The virtual network private IP address of the IP configuration. + PrivateIPAddress *string + + // The reference to the public ip address resource. + PublicIPAddress *SubResource + + // The reference to the virtual network subnet resource. + Subnet *SubResource +} + +// LogAnalyticsInputBase - Api input base class for LogAnalytics Api. +type LogAnalyticsInputBase struct { + // REQUIRED; SAS Uri of the logging blob container to which LogAnalytics Api writes output logs to. + BlobContainerSasURI *string + + // REQUIRED; From time of the query + FromTime *time.Time + + // REQUIRED; To time of the query + ToTime *time.Time + + // Group query result by Client Application ID. + GroupByClientApplicationID *bool + + // Group query result by Operation Name. + GroupByOperationName *bool + + // Group query result by Resource Name. + GroupByResourceName *bool + + // Group query result by Throttle Policy applied. + GroupByThrottlePolicy *bool + + // Group query result by User Agent. + GroupByUserAgent *bool +} + +// LogAnalyticsOperationResult - LogAnalytics operation status response +type LogAnalyticsOperationResult struct { + // READ-ONLY; LogAnalyticsOutput + Properties *LogAnalyticsOutput +} + +// LogAnalyticsOutput - LogAnalytics output properties +type LogAnalyticsOutput struct { + // READ-ONLY; Output file Uri path to blob container. + Output *string +} + +// MaintenanceRedeployStatus - Maintenance Operation Status. +type MaintenanceRedeployStatus struct { + // True, if customer is allowed to perform Maintenance. + IsCustomerInitiatedMaintenanceAllowed *bool + + // Message returned for the last Maintenance Operation. + LastOperationMessage *string + + // The Last Maintenance Operation Result Code. + LastOperationResultCode *MaintenanceOperationResultCodeTypes + + // End Time for the Maintenance Window. + MaintenanceWindowEndTime *time.Time + + // Start Time for the Maintenance Window. + MaintenanceWindowStartTime *time.Time + + // End Time for the Pre Maintenance Window. + PreMaintenanceWindowEndTime *time.Time + + // Start Time for the Pre Maintenance Window. + PreMaintenanceWindowStartTime *time.Time +} + +// ManagedArtifact - The managed artifact. +type ManagedArtifact struct { + // REQUIRED; The managed artifact id. + ID *string +} + +// ManagedDiskParameters - The parameters of a managed disk. +type ManagedDiskParameters struct { + // Specifies the customer managed disk encryption set resource id for the managed disk. + DiskEncryptionSet *DiskEncryptionSetParameters + + // Resource Id + ID *string + + // Specifies the security profile for the managed disk. + SecurityProfile *VMDiskSecurityProfile + + // Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot + // be used with OS Disk. + StorageAccountType *StorageAccountTypes +} + +// NetworkInterfaceReference - Describes a network interface reference. +type NetworkInterfaceReference struct { + // Resource Id + ID *string + + // Describes a network interface reference properties. + Properties *NetworkInterfaceReferenceProperties +} + +// NetworkInterfaceReferenceProperties - Describes a network interface reference properties. +type NetworkInterfaceReferenceProperties struct { + // Specify what happens to the network interface when the VM is deleted + DeleteOption *DeleteOptions + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool +} + +// NetworkProfile - Specifies the network interfaces or the networking configuration of the virtual machine. +type NetworkProfile struct { + // specifies the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations + NetworkAPIVersion *NetworkAPIVersion + + // Specifies the networking configurations that will be used to create the virtual machine networking resources. + NetworkInterfaceConfigurations []*VirtualMachineNetworkInterfaceConfiguration + + // Specifies the list of resource Ids for the network interfaces associated with the virtual machine. + NetworkInterfaces []*NetworkInterfaceReference +} + +// OSDisk - Specifies information about the operating system disk used by the virtual machine. For more information about +// disks, see About disks and VHDs for Azure virtual machines +// [https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview]. +type OSDisk struct { + // REQUIRED; Specifies how the virtual machine should be created. Possible values are: Attach. This value is used when you + // are using a specialized disk to create the virtual machine. FromImage. This value is used + // when you are using an image to create the virtual machine. If you are using a platform image, you should also use the imageReference + // element described above. If you are using a marketplace image, you + // should also use the plan element previously described. + CreateOption *DiskCreateOptionTypes + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for + // Standard storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies whether OS Disk should be deleted or detached upon VM deletion. Possible values are: Delete. If this value is + // used, the OS disk is deleted when VM is deleted. Detach. If this value is used, + // the os disk is retained after VM is deleted. The default value is set to Detach. For an ephemeral OS Disk, the default + // value is set to Delete. The user cannot change the delete option for an ephemeral + // OS Disk. + DeleteOption *DiskDeleteOptionTypes + + // Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. + DiffDiskSettings *DiffDiskSettings + + // Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a + // virtual machine image. The property 'diskSizeGB' is the number of bytes x 1024^3 + // for the disk and the value cannot be larger than 1023. + DiskSizeGB *int32 + + // Specifies the encryption settings for the OS Disk. Minimum api-version: 2015-06-15. + EncryptionSettings *DiskEncryptionSettings + + // The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. + // If SourceImage is provided, the destination virtual hard drive must not + // exist. + Image *VirtualHardDisk + + // The managed disk parameters. + ManagedDisk *ManagedDiskParameters + + // The disk name. + Name *string + + // This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or + // a specialized VHD. Possible values are: Windows, Linux. + OSType *OperatingSystemTypes + + // The virtual hard disk. + Vhd *VirtualHardDisk + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool +} + +// OSDiskImage - Contains the os disk image information. +type OSDiskImage struct { + // REQUIRED; The operating system of the osDiskImage. + OperatingSystem *OperatingSystemTypes +} + +// OSDiskImageEncryption - Contains encryption settings for an OS disk image. +type OSDiskImageEncryption struct { + // A relative URI containing the resource ID of the disk encryption set. + DiskEncryptionSetID *string + + // This property specifies the security profile of an OS disk image. + SecurityProfile *OSDiskImageSecurityProfile +} + +// OSDiskImageSecurityProfile - Contains security profile for an OS disk image. +type OSDiskImageSecurityProfile struct { + // confidential VM encryption types + ConfidentialVMEncryptionType *ConfidentialVMEncryptionType + + // secure VM disk encryption set id + SecureVMDiskEncryptionSetID *string +} + +// OSFamily - Describes a cloud service OS family. +type OSFamily struct { + // OS family properties. + Properties *OSFamilyProperties + + // READ-ONLY; Resource Id. + ID *string + + // READ-ONLY; Resource location. + Location *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// OSFamilyListResult - The list operation result. +type OSFamilyListResult struct { + // REQUIRED; The list of resources. + Value []*OSFamily + + // The URI to fetch the next page of resources. Use this to get the next page of resources. Do this till nextLink is null + // to fetch all the resources. + NextLink *string +} + +// OSFamilyProperties - OS family properties. +type OSFamilyProperties struct { + // READ-ONLY; The OS family label. + Label *string + + // READ-ONLY; The OS family name. + Name *string + + // READ-ONLY; List of OS versions belonging to this family. + Versions []*OSVersionPropertiesBase +} + +type OSImageNotificationProfile struct { + // Specifies whether the OS Image Scheduled event is enabled or disabled. + Enable *bool + + // Length of time a Virtual Machine being reimaged or having its OS upgraded will have to potentially approve the OS Image + // Scheduled Event before the event is auto approved (timed out). The configuration + // is specified in ISO 8601 format, and the value must be 15 minutes (PT15M) + NotBeforeTimeout *string +} + +// OSProfile - Specifies the operating system settings for the virtual machine. Some of the settings cannot be changed once +// VM is provisioned. +type OSProfile struct { + // Specifies the password of the administrator account. + // Minimum-length (Windows): 8 characters + // Minimum-length (Linux): 6 characters + // Max-length (Windows): 123 characters + // Max-length (Linux): 72 characters + // Complexity requirements: 3 out of 4 conditions below need to be fulfilled + // Has lower characters + // Has upper characters + // Has a digit + // Has a special character (Regex match [\W_]) + // Disallowed values: "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", + // "Password22", "iloveyou!" + // For resetting the password, see How to reset the Remote Desktop service or its login password in a Windows VM [https://docs.microsoft.com/troubleshoot/azure/virtual-machines/reset-rdp] + // For resetting root password, see Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension + // [https://docs.microsoft.com/troubleshoot/azure/virtual-machines/troubleshoot-ssh-connection] + AdminPassword *string + + // Specifies the name of the administrator account. + // This property cannot be updated after the VM is created. + // Windows-only restriction: Cannot end in "." + // Disallowed values: "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", + // "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", + // "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". + // Minimum-length (Linux): 1 character + // Max-length (Linux): 64 characters + // Max-length (Windows): 20 characters. + AdminUsername *string + + // Specifies whether extension operations should be allowed on the virtual machine. This may only be set to False when no + // extensions are present on the virtual machine. + AllowExtensionOperations *bool + + // Specifies the host OS name of the virtual machine. This name cannot be updated after the VM is created. Max-length (Windows): + // 15 characters. Max-length (Linux): 64 characters. For naming conventions + // and restrictions see Azure infrastructure services implementation guidelines [https://docs.microsoft.com/azure/azure-resource-manager/management/resource-name-rules]. + ComputerName *string + + // Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved + // as a file on the Virtual Machine. The maximum length of the binary array is + // 65535 bytes. Note: Do not pass any secrets or passwords in customData property. This property cannot be updated after the + // VM is created. The property 'customData' is passed to the VM to be saved as a + // file, for more information see Custom Data on Azure VMs [https://azure.microsoft.com/blog/custom-data-and-cloud-init-on-windows-azure/]. + // For using cloud-init for your Linux VM, see Using cloud-init to + // customize a Linux VM during creation [https://docs.microsoft.com/azure/virtual-machines/linux/using-cloud-init]. + CustomData *string + + // Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux distributions, see + // Linux on Azure-Endorsed Distributions + // [https://docs.microsoft.com/azure/virtual-machines/linux/endorsed-distros]. + LinuxConfiguration *LinuxConfiguration + + // Optional property which must either be set to True or omitted. + RequireGuestProvisionSignal *bool + + // Specifies set of certificates that should be installed onto the virtual machine. To install certificates on a virtual machine + // it is recommended to use the Azure Key Vault virtual machine extension for + // Linux [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux] or the Azure Key Vault virtual machine + // extension for Windows + // [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows]. + Secrets []*VaultSecretGroup + + // Specifies Windows operating system settings on the virtual machine. + WindowsConfiguration *WindowsConfiguration +} + +// OSProfileProvisioningData - Additional parameters for Reimaging Non-Ephemeral Virtual Machine. +type OSProfileProvisioningData struct { + // Specifies the password of the administrator account. + // Minimum-length (Windows): 8 characters + // Minimum-length (Linux): 6 characters + // Max-length (Windows): 123 characters + // Max-length (Linux): 72 characters + // Complexity requirements: 3 out of 4 conditions below need to be fulfilled + // Has lower characters + // Has upper characters + // Has a digit + // Has a special character (Regex match [\W_]) + // Disallowed values: "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", + // "Password22", "iloveyou!" + // For resetting the password, see How to reset the Remote Desktop service or its login password in a Windows VM [https://docs.microsoft.com/troubleshoot/azure/virtual-machines/reset-rdp] + // For resetting root password, see Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension + // [https://docs.microsoft.com/troubleshoot/azure/virtual-machines/troubleshoot-ssh-connection] + AdminPassword *string + + // Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved + // as a file on the Virtual Machine. The maximum length of the binary array is + // 65535 bytes. Note: Do not pass any secrets or passwords in customData property. This property cannot be updated after the + // VM is created. The property customData is passed to the VM to be saved as a + // file, for more information see Custom Data on Azure VMs [https://azure.microsoft.com/blog/custom-data-and-cloud-init-on-windows-azure/]. + // If using cloud-init for your Linux VM, see Using cloud-init to + // customize a Linux VM during creation [https://docs.microsoft.com/azure/virtual-machines/linux/using-cloud-init]. + CustomData *string +} + +// OSVersion - Describes a cloud service OS version. +type OSVersion struct { + // OS version properties. + Properties *OSVersionProperties + + // READ-ONLY; Resource Id. + ID *string + + // READ-ONLY; Resource location. + Location *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// OSVersionListResult - The list operation result. +type OSVersionListResult struct { + // REQUIRED; The list of resources. + Value []*OSVersion + + // The URI to fetch the next page of resources. Use this to get the next page of resources. Do this till nextLink is null + // to fetch all the resources. + NextLink *string +} + +// OSVersionProperties - OS version properties. +type OSVersionProperties struct { + // READ-ONLY; The family of this OS version. + Family *string + + // READ-ONLY; The family label of this OS version. + FamilyLabel *string + + // READ-ONLY; Specifies whether this OS version is active. + IsActive *bool + + // READ-ONLY; Specifies whether this is the default OS version for its family. + IsDefault *bool + + // READ-ONLY; The OS version label. + Label *string + + // READ-ONLY; The OS version. + Version *string +} + +// OSVersionPropertiesBase - Configuration view of an OS version. +type OSVersionPropertiesBase struct { + // READ-ONLY; Specifies whether this OS version is active. + IsActive *bool + + // READ-ONLY; Specifies whether this is the default OS version for its family. + IsDefault *bool + + // READ-ONLY; The OS version label. + Label *string + + // READ-ONLY; The OS version. + Version *string +} + +// OperationListResult - The List Compute Operation operation response. +type OperationListResult struct { + // READ-ONLY; The list of compute operations + Value []*OperationValue +} + +// OperationValue - Describes the properties of a Compute Operation value. +type OperationValue struct { + // Describes the properties of a Compute Operation Value Display. + Display *OperationValueDisplay + + // READ-ONLY; The name of the compute operation. + Name *string + + // READ-ONLY; The origin of the compute operation. + Origin *string +} + +// OperationValueDisplay - Describes the properties of a Compute Operation Value Display. +type OperationValueDisplay struct { + // READ-ONLY; The description of the operation. + Description *string + + // READ-ONLY; The display name of the compute operation. + Operation *string + + // READ-ONLY; The resource provider for the operation. + Provider *string + + // READ-ONLY; The display name of the resource the operation applies to. + Resource *string +} + +// OrchestrationServiceStateInput - The input for OrchestrationServiceState +type OrchestrationServiceStateInput struct { + // REQUIRED; The action to be performed. + Action *OrchestrationServiceStateAction + + // REQUIRED; The name of the service. + ServiceName *OrchestrationServiceNames +} + +// OrchestrationServiceSummary - Summary for an orchestration service of a virtual machine scale set. +type OrchestrationServiceSummary struct { + // READ-ONLY; The name of the service. + ServiceName *OrchestrationServiceNames + + // READ-ONLY; The current state of the service. + ServiceState *OrchestrationServiceState +} + +// PatchInstallationDetail - Information about a specific patch that was encountered during an installation action. +type PatchInstallationDetail struct { + // READ-ONLY; The classification(s) of the patch as provided by the patch publisher. + Classifications []*string + + // READ-ONLY; The state of the patch after the installation operation completed. + InstallationState *PatchInstallationState + + // READ-ONLY; The KBID of the patch. Only applies to Windows patches. + KbID *string + + // READ-ONLY; The friendly name of the patch. + Name *string + + // READ-ONLY; A unique identifier for the patch. + PatchID *string + + // READ-ONLY; The version string of the package. It may conform to Semantic Versioning. Only applies to Linux. + Version *string +} + +// PatchSettings - Specifies settings related to VM Guest Patching on Windows. +type PatchSettings struct { + // Specifies the mode of VM Guest patch assessment for the IaaS virtual machine. + // Possible values are: + // ImageDefault - You control the timing of patch assessments on a virtual machine. + // AutomaticByPlatform - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true. + AssessmentMode *WindowsPatchAssessmentMode + + // Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Windows. + AutomaticByPlatformSettings *WindowsVMGuestPatchAutomaticByPlatformSettings + + // Enables customers to patch their Azure VMs without requiring a reboot. For enableHotpatching, the 'provisionVMAgent' must + // be set to true and 'patchMode' must be set to 'AutomaticByPlatform'. + EnableHotpatching *bool + + // Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale + // set with OrchestrationMode as Flexible. + // Possible values are: + // Manual - You control the application of patches to a virtual machine. You do this by applying patches manually inside the + // VM. In this mode, automatic updates are disabled; the property + // WindowsConfiguration.enableAutomaticUpdates must be false + // AutomaticByOS - The virtual machine will automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates + // must be true. + // AutomaticByPlatform - the virtual machine will automatically updated by the platform. The properties provisionVMAgent and + // WindowsConfiguration.enableAutomaticUpdates must be true + PatchMode *WindowsVMGuestPatchMode +} + +// PirCommunityGalleryResource - Base information about the community gallery resource in azure compute gallery. +type PirCommunityGalleryResource struct { + // The identifier information of community gallery. + Identifier *CommunityGalleryIdentifier + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// PirResource - The Resource model definition. +type PirResource struct { + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string +} + +// PirSharedGalleryResource - Base information about the shared gallery resource in pir. +type PirSharedGalleryResource struct { + // The identifier information of shared gallery. + Identifier *SharedGalleryIdentifier + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string +} + +// Plan - Specifies information about the marketplace image used to create the virtual machine. This element is only used +// for marketplace images. Before you can use a marketplace image from an API, you must +// enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click +// Want to deploy programmatically, Get Started ->. Enter any required +// information and then click Save. +type Plan struct { + // The plan ID. + Name *string + + // Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. + Product *string + + // The promotion code. + PromotionCode *string + + // The publisher ID. + Publisher *string +} + +// PolicyViolation - A policy violation reported against a gallery artifact. +type PolicyViolation struct { + // Describes the nature of the policy violation. + Category *PolicyViolationCategory + + // Describes specific details about why this policy violation was reported. + Details *string +} + +// PriorityMixPolicy - Specifies the target splits for Spot and Regular priority VMs within a scale set with flexible orchestration +// mode. With this property the customer is able to specify the base number of regular +// priority VMs created as the VMSS flex instance scales out and the split between Spot and Regular priority VMs after this +// base target has been reached. +type PriorityMixPolicy struct { + // The base number of regular priority VMs that will be created in this scale set as it scales out. + BaseRegularPriorityCount *int32 + + // The percentage of VM instances, after the base regular priority count has been reached, that are expected to use regular + // priority. + RegularPriorityPercentageAboveBase *int32 +} + +// 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; private endpoint connection Id + ID *string + + // READ-ONLY; private endpoint connection name + Name *string + + // READ-ONLY; private endpoint connection type + Type *string +} + +// PrivateEndpointConnectionListResult - A list of private link resources +type PrivateEndpointConnectionListResult struct { + // The uri to fetch the next page of snapshots. Call ListNext() with this to fetch the next page of snapshots. + NextLink *string + + // 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 DiskAccess and Virtual Network. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // READ-ONLY; 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; private link resource Id + ID *string + + // READ-ONLY; private link resource name + Name *string + + // READ-ONLY; private link resource type + 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 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. + ActionsRequired *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 +} + +// PropertyUpdatesInProgress - Properties of the disk for which update is pending. +type PropertyUpdatesInProgress struct { + // The target performance tier of the disk if a tier change operation is in progress. + TargetTier *string +} + +// ProximityPlacementGroup - Specifies information about the proximity placement group. +type ProximityPlacementGroup struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a Proximity Placement Group. + Properties *ProximityPlacementGroupProperties + + // Resource tags + Tags map[string]*string + + // Specifies the Availability Zone where virtual machine, virtual machine scale set or availability set associated with the + // proximity placement group can be created. + Zones []*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// ProximityPlacementGroupListResult - The List Proximity Placement Group operation response. +type ProximityPlacementGroupListResult struct { + // REQUIRED; The list of proximity placement groups + Value []*ProximityPlacementGroup + + // The URI to fetch the next page of proximity placement groups. + NextLink *string +} + +// ProximityPlacementGroupProperties - Describes the properties of a Proximity Placement Group. +type ProximityPlacementGroupProperties struct { + // Describes colocation status of the Proximity Placement Group. + ColocationStatus *InstanceViewStatus + + // Specifies the user intent of the proximity placement group. + Intent *ProximityPlacementGroupPropertiesIntent + + // Specifies the type of the proximity placement group. Possible values are: Standard : Co-locate resources within an Azure + // region or Availability Zone. Ultra : For future use. + ProximityPlacementGroupType *ProximityPlacementGroupType + + // READ-ONLY; A list of references to all availability sets in the proximity placement group. + AvailabilitySets []*SubResourceWithColocationStatus + + // READ-ONLY; A list of references to all virtual machine scale sets in the proximity placement group. + VirtualMachineScaleSets []*SubResourceWithColocationStatus + + // READ-ONLY; A list of references to all virtual machines in the proximity placement group. + VirtualMachines []*SubResourceWithColocationStatus +} + +// ProximityPlacementGroupPropertiesIntent - Specifies the user intent of the proximity placement group. +type ProximityPlacementGroupPropertiesIntent struct { + // Specifies possible sizes of virtual machines that can be created in the proximity placement group. + VMSizes []*string +} + +// ProximityPlacementGroupUpdate - Specifies information about the proximity placement group. +type ProximityPlacementGroupUpdate struct { + // Resource tags + Tags map[string]*string +} + +// ProxyAgentSettings - Specifies ProxyAgent settings while creating the virtual machine. Minimum api-version: 2023-09-01. +type ProxyAgentSettings struct { + // Specifies whether ProxyAgent feature should be enabled on the virtual machine or virtual machine scale set. + Enabled *bool + + // Increase the value of this property allows user to reset the key used for securing communication channel between guest + // and host. + KeyIncarnationID *int32 + + // Specifies the mode that ProxyAgent will execute on if the feature is enabled. ProxyAgent will start to audit or monitor + // but not enforce access control over requests to host endpoints in Audit mode, + // while in Enforce mode it will enforce access control. The default value is Enforce mode. + Mode *Mode +} + +// ProxyOnlyResource - The ProxyOnly Resource model definition. +type ProxyOnlyResource struct { + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// ProxyResource - The resource model definition for an Azure Resource Manager proxy resource. It will not have tags and a +// location +type ProxyResource struct { + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// PublicIPAddressSKU - Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible. +type PublicIPAddressSKU struct { + // Specify public IP sku name + Name *PublicIPAddressSKUName + + // Specify public IP sku tier + Tier *PublicIPAddressSKUTier +} + +// PurchasePlan - Used for establishing the purchase context of any 3rd Party artifact through MarketPlace. +type PurchasePlan struct { + // REQUIRED; The plan ID. + Name *string + + // REQUIRED; Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference + // element. + Product *string + + // REQUIRED; The publisher ID. + Publisher *string +} + +// RecommendedMachineConfiguration - The properties describe the recommended machine configuration for this Image Definition. +// These properties are updatable. +type RecommendedMachineConfiguration struct { + // Describes the resource range. + Memory *ResourceRange + + // Describes the resource range. + VCPUs *ResourceRange +} + +// RecoveryWalkResponse - Response after calling a manual recovery walk +type RecoveryWalkResponse struct { + // READ-ONLY; The next update domain that needs to be walked. Null means walk spanning all update domains has been completed + NextPlatformUpdateDomain *int32 + + // READ-ONLY; Whether the recovery walk was performed + WalkPerformed *bool +} + +// RegionalReplicationStatus - This is the regional replication status. +type RegionalReplicationStatus struct { + // READ-ONLY; The details of the replication status. + Details *string + + // READ-ONLY; It indicates progress of the replication job. + Progress *int32 + + // READ-ONLY; The region to which the gallery image version is being replicated to. + Region *string + + // READ-ONLY; This is the regional replication state. + State *ReplicationState +} + +// RegionalSharingStatus - Gallery regional sharing status +type RegionalSharingStatus struct { + // Details of gallery regional sharing failure. + Details *string + + // Region name + Region *string + + // READ-ONLY; Gallery sharing state in current region + State *SharingState +} + +// ReplicationStatus - This is the replication status of the gallery image version. +type ReplicationStatus struct { + // READ-ONLY; This is the aggregated replication status based on all the regional replication status flags. + AggregatedState *AggregatedReplicationState + + // READ-ONLY; This is a summary of replication status for each region. + Summary []*RegionalReplicationStatus +} + +// RequestRateByIntervalInput - Api request input for LogAnalytics getRequestRateByInterval Api. +type RequestRateByIntervalInput struct { + // REQUIRED; SAS Uri of the logging blob container to which LogAnalytics Api writes output logs to. + BlobContainerSasURI *string + + // REQUIRED; From time of the query + FromTime *time.Time + + // REQUIRED; Interval value in minutes used to create LogAnalytics call rate logs. + IntervalLength *IntervalInMins + + // REQUIRED; To time of the query + ToTime *time.Time + + // Group query result by Client Application ID. + GroupByClientApplicationID *bool + + // Group query result by Operation Name. + GroupByOperationName *bool + + // Group query result by Resource Name. + GroupByResourceName *bool + + // Group query result by Throttle Policy applied. + GroupByThrottlePolicy *bool + + // Group query result by User Agent. + GroupByUserAgent *bool +} + +// ResiliencyPolicy - Describes an resiliency policy - resilientVMCreationPolicy and/or resilientVMDeletionPolicy. +type ResiliencyPolicy struct { + // The configuration parameters used while performing resilient VM creation. + ResilientVMCreationPolicy *ResilientVMCreationPolicy + + // The configuration parameters used while performing resilient VM deletion. + ResilientVMDeletionPolicy *ResilientVMDeletionPolicy +} + +// ResilientVMCreationPolicy - The configuration parameters used while performing resilient VM creation. +type ResilientVMCreationPolicy struct { + // Specifies whether resilient VM creation should be enabled on the virtual machine scale set. The default value is false. + Enabled *bool +} + +// ResilientVMDeletionPolicy - The configuration parameters used while performing resilient VM deletion. +type ResilientVMDeletionPolicy struct { + // Specifies whether resilient VM deletion should be enabled on the virtual machine scale set. The default value is false. + Enabled *bool +} + +// Resource - The Resource model definition. +type Resource struct { + // REQUIRED; Resource location + Location *string + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// ResourceInstanceViewStatus - Instance view status. +type ResourceInstanceViewStatus struct { + // The level code. + Level *StatusLevelTypes + + // READ-ONLY; The status code. + Code *string + + // READ-ONLY; The short localizable label for the status. + DisplayStatus *string + + // READ-ONLY; The detailed status message, including for alerts and error messages. + Message *string + + // READ-ONLY; The time of the status. + Time *time.Time +} + +// ResourceRange - Describes the resource range. +type ResourceRange struct { + // The maximum number of the resource. + Max *int32 + + // The minimum number of the resource. + Min *int32 +} + +// ResourceSKU - Describes an available Compute SKU. +type ResourceSKU struct { + // READ-ONLY; The api versions that support this SKU. + APIVersions []*string + + // READ-ONLY; A name value pair to describe the capability. + Capabilities []*ResourceSKUCapabilities + + // READ-ONLY; Specifies the number of virtual machines in the scale set. + Capacity *ResourceSKUCapacity + + // READ-ONLY; Metadata for retrieving price info. + Costs []*ResourceSKUCosts + + // READ-ONLY; The Family of this particular SKU. + Family *string + + // READ-ONLY; The Kind of resources that are supported in this SKU. + Kind *string + + // READ-ONLY; A list of locations and availability zones in those locations where the SKU is available. + LocationInfo []*ResourceSKULocationInfo + + // READ-ONLY; The set of locations that the SKU is available. + Locations []*string + + // READ-ONLY; The name of SKU. + Name *string + + // READ-ONLY; The type of resource the SKU applies to. + ResourceType *string + + // READ-ONLY; The restrictions because of which SKU cannot be used. This is empty if there are no restrictions. + Restrictions []*ResourceSKURestrictions + + // READ-ONLY; The Size of the SKU. + Size *string + + // READ-ONLY; Specifies the tier of virtual machines in a scale set. + // Possible Values: + // Standard + // Basic + Tier *string +} + +// ResourceSKUCapabilities - Describes The SKU capabilities object. +type ResourceSKUCapabilities struct { + // READ-ONLY; An invariant to describe the feature. + Name *string + + // READ-ONLY; An invariant if the feature is measured by quantity. + Value *string +} + +// ResourceSKUCapacity - Describes scaling information of a SKU. +type ResourceSKUCapacity struct { + // READ-ONLY; The default capacity. + Default *int64 + + // READ-ONLY; The maximum capacity that can be set. + Maximum *int64 + + // READ-ONLY; The minimum capacity. + Minimum *int64 + + // READ-ONLY; The scale type applicable to the sku. + ScaleType *ResourceSKUCapacityScaleType +} + +// ResourceSKUCosts - Describes metadata for retrieving price info. +type ResourceSKUCosts struct { + // READ-ONLY; An invariant to show the extended unit. + ExtendedUnit *string + + // READ-ONLY; Used for querying price from commerce. + MeterID *string + + // READ-ONLY; The multiplier is needed to extend the base metered cost. + Quantity *int64 +} + +// ResourceSKULocationInfo - Describes an available Compute SKU Location Information. +type ResourceSKULocationInfo struct { + // READ-ONLY; The names of extended locations. + ExtendedLocations []*string + + // READ-ONLY; Location of the SKU + Location *string + + // READ-ONLY; The type of the extended location. + Type *ExtendedLocationType + + // READ-ONLY; Details of capabilities available to a SKU in specific zones. + ZoneDetails []*ResourceSKUZoneDetails + + // READ-ONLY; List of availability zones where the SKU is supported. + Zones []*string +} + +// ResourceSKURestrictionInfo - Describes an available Compute SKU Restriction Information. +type ResourceSKURestrictionInfo struct { + // READ-ONLY; Locations where the SKU is restricted + Locations []*string + + // READ-ONLY; List of availability zones where the SKU is restricted. + Zones []*string +} + +// ResourceSKURestrictions - Describes scaling information of a SKU. +type ResourceSKURestrictions struct { + // READ-ONLY; The reason for restriction. + ReasonCode *ResourceSKURestrictionsReasonCode + + // READ-ONLY; The information about the restriction where the SKU cannot be used. + RestrictionInfo *ResourceSKURestrictionInfo + + // READ-ONLY; The type of restrictions. + Type *ResourceSKURestrictionsType + + // 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 +} + +// ResourceSKUZoneDetails - Describes The zonal capabilities of a SKU. +type ResourceSKUZoneDetails struct { + // READ-ONLY; A list of capabilities that are available for the SKU in the specified list of zones. + Capabilities []*ResourceSKUCapabilities + + // READ-ONLY; The set of zones that the SKU is available in with the specified capabilities. + Name []*string +} + +// ResourceSKUsResult - The List Resource Skus operation response. +type ResourceSKUsResult struct { + // REQUIRED; The list of skus available for the subscription. + Value []*ResourceSKU + + // The URI to fetch the next page of Resource Skus. Call ListNext() with this URI to fetch the next page of Resource Skus + NextLink *string +} + +type ResourceSharingProfile struct { + // Specifies an array of subscription resource IDs that capacity reservation group is shared with. Note: Minimum api-version: + // 2023-09-01. Please refer to https://aka.ms/computereservationsharing for more + // details. + SubscriptionIDs []*SubResource +} + +// ResourceURIList - The List resources which are encrypted with the disk encryption set. +type ResourceURIList struct { + // REQUIRED; A list of IDs or Owner IDs of resources which are encrypted with the disk encryption set. + Value []*string + + // The uri to fetch the next page of encrypted resources. Call ListNext() with this to fetch the next page of encrypted resources. + NextLink *string +} + +// ResourceWithOptionalLocation - The Resource model definition with location property as optional. +type ResourceWithOptionalLocation struct { + // Resource location + Location *string + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// RestorePoint - Restore Point details. +type RestorePoint struct { + // The restore point properties. + Properties *RestorePointProperties + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// RestorePointCollection - Create or update Restore Point collection parameters. +type RestorePointCollection struct { + // REQUIRED; Resource location + Location *string + + // The restore point collection properties. + Properties *RestorePointCollectionProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// RestorePointCollectionListResult - The List restore point collection operation response. +type RestorePointCollectionListResult struct { + // The uri to fetch the next page of RestorePointCollections. Call ListNext() with this to fetch the next page of RestorePointCollections + NextLink *string + + // Gets the list of restore point collections. + Value []*RestorePointCollection +} + +// RestorePointCollectionProperties - The restore point collection properties. +type RestorePointCollectionProperties struct { + // The properties of the source resource that this restore point collection is created from. + Source *RestorePointCollectionSourceProperties + + // READ-ONLY; The provisioning state of the restore point collection. + ProvisioningState *string + + // READ-ONLY; The unique id of the restore point collection. + RestorePointCollectionID *string + + // READ-ONLY; A list containing all restore points created under this restore point collection. + RestorePoints []*RestorePoint +} + +// RestorePointCollectionSourceProperties - The properties of the source resource that this restore point collection is created +// from. +type RestorePointCollectionSourceProperties struct { + // Resource Id of the source resource used to create this restore point collection + ID *string + + // READ-ONLY; Location of the source resource used to create this restore point collection. + Location *string +} + +// RestorePointCollectionUpdate - Update Restore Point collection parameters. +type RestorePointCollectionUpdate struct { + // The restore point collection properties. + Properties *RestorePointCollectionProperties + + // Resource tags + Tags map[string]*string +} + +// RestorePointEncryption - Encryption at rest settings for disk restore point. It is an optional property that can be specified +// in the input while creating a restore point. +type RestorePointEncryption struct { + // Describes the parameter of customer managed disk encryption set resource id that can be specified for disk. Note: The disk + // encryption set resource id can only be specified for managed disk. Please + // refer https://aka.ms/mdssewithcmkoverview for more details. + DiskEncryptionSet *DiskEncryptionSetParameters + + // The type of key used to encrypt the data of the disk restore point. + Type *RestorePointEncryptionType +} + +// RestorePointInstanceView - The instance view of a restore point. +type RestorePointInstanceView struct { + // The disk restore points information. + DiskRestorePoints []*DiskRestorePointInstanceView + + // The resource status information. + Statuses []*InstanceViewStatus +} + +// RestorePointProperties - The restore point properties. +type RestorePointProperties struct { + // ConsistencyMode of the RestorePoint. Can be specified in the input while creating a restore point. For now, only CrashConsistent + // is accepted as a valid input. Please refer to + // https://aka.ms/RestorePoints for more details. + ConsistencyMode *ConsistencyModeTypes + + // List of disk resource ids that the customer wishes to exclude from the restore point. If no disks are specified, all disks + // will be included. + ExcludeDisks []*APIEntityReference + + // Gets the details of the VM captured at the time of the restore point creation. + SourceMetadata *RestorePointSourceMetadata + + // Resource Id of the source restore point from which a copy needs to be created. + SourceRestorePoint *APIEntityReference + + // Gets the creation time of the restore point. + TimeCreated *time.Time + + // READ-ONLY; The restore point instance view. + InstanceView *RestorePointInstanceView + + // READ-ONLY; Gets the provisioning state of the restore point. + ProvisioningState *string +} + +// RestorePointSourceMetadata - Describes the properties of the Virtual Machine for which the restore point was created. The +// properties provided are a subset and the snapshot of the overall Virtual Machine properties captured at the +// time of the restore point creation. +type RestorePointSourceMetadata struct { + // Gets the storage profile. + StorageProfile *RestorePointSourceVMStorageProfile + + // READ-ONLY; Gets the diagnostics profile. + DiagnosticsProfile *DiagnosticsProfile + + // READ-ONLY; Gets the hardware profile. + HardwareProfile *HardwareProfile + + // READ-ONLY; HyperVGeneration of the source VM for which restore point is captured. + HyperVGeneration *HyperVGenerationTypes + + // READ-ONLY; Gets the license type, which is for bring your own license scenario. + LicenseType *string + + // READ-ONLY; Location of the VM from which the restore point was created. + Location *string + + // READ-ONLY; Gets the OS profile. + OSProfile *OSProfile + + // READ-ONLY; Gets the security profile. + SecurityProfile *SecurityProfile + + // READ-ONLY; UserData associated with the source VM for which restore point is captured, which is a base-64 encoded value. + UserData *string + + // READ-ONLY; Gets the virtual machine unique id. + VMID *string +} + +// RestorePointSourceVMDataDisk - Describes a data disk. +type RestorePointSourceVMDataDisk struct { + // Contains Disk Restore Point properties. + DiskRestorePoint *DiskRestorePointAttributes + + // Contains the managed disk details. + ManagedDisk *ManagedDiskParameters + + // READ-ONLY; Gets the caching type. + Caching *CachingTypes + + // READ-ONLY; Gets the initial disk size in GB for blank data disks, and the new desired size for existing OS and Data disks. + DiskSizeGB *int32 + + // READ-ONLY; Gets the logical unit number. + Lun *int32 + + // READ-ONLY; Gets the disk name. + Name *string + + // READ-ONLY; Shows true if the disk is write-accelerator enabled. + WriteAcceleratorEnabled *bool +} + +// RestorePointSourceVMOSDisk - Describes an Operating System disk. +type RestorePointSourceVMOSDisk struct { + // Contains Disk Restore Point properties. + DiskRestorePoint *DiskRestorePointAttributes + + // Gets the managed disk details + ManagedDisk *ManagedDiskParameters + + // READ-ONLY; Gets the caching type. + Caching *CachingTypes + + // READ-ONLY; Gets the disk size in GB. + DiskSizeGB *int32 + + // READ-ONLY; Gets the disk encryption settings. + EncryptionSettings *DiskEncryptionSettings + + // READ-ONLY; Gets the disk name. + Name *string + + // READ-ONLY; Gets the Operating System type. + OSType *OperatingSystemType + + // READ-ONLY; Shows true if the disk is write-accelerator enabled. + WriteAcceleratorEnabled *bool +} + +// RestorePointSourceVMStorageProfile - Describes the storage profile. +type RestorePointSourceVMStorageProfile struct { + // Gets the data disks of the VM captured at the time of the restore point creation. + DataDisks []*RestorePointSourceVMDataDisk + + // Gets the OS disk of the VM captured at the time of the restore point creation. + OSDisk *RestorePointSourceVMOSDisk + + // READ-ONLY; Gets the disk controller type of the VM captured at the time of the restore point creation. + DiskControllerType *DiskControllerTypes +} + +// RetrieveBootDiagnosticsDataResult - The SAS URIs of the console screenshot and serial log blobs. +type RetrieveBootDiagnosticsDataResult struct { + // READ-ONLY; The console screenshot blob URI + ConsoleScreenshotBlobURI *string + + // READ-ONLY; The serial console log blob URI. + SerialConsoleLogBlobURI *string +} + +// RoleInstance - Describes the cloud service role instance. +type RoleInstance struct { + // Role instance properties. + Properties *RoleInstanceProperties + + // The role instance SKU. + SKU *InstanceSKU + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource Location. + Location *string + + // READ-ONLY; Resource Name. + Name *string + + // READ-ONLY; Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Type. + Type *string +} + +// RoleInstanceListResult - The list operation result. +type RoleInstanceListResult struct { + // REQUIRED; The list of resources. + Value []*RoleInstance + + // The URI to fetch the next page of resources. Use this to get the next page of resources. Do this till nextLink is null + // to fetch all the resources. + NextLink *string +} + +// RoleInstanceNetworkProfile - Describes the network profile for the role instance. +type RoleInstanceNetworkProfile struct { + // READ-ONLY; Specifies the list of resource Ids for the network interfaces associated with the role instance. + NetworkInterfaces []*SubResource +} + +// RoleInstanceProperties - Role instance properties. +type RoleInstanceProperties struct { + // The instance view of the role instance. + InstanceView *RoleInstanceView + + // Describes the network profile for the role instance. + NetworkProfile *RoleInstanceNetworkProfile +} + +// RoleInstanceView - The instance view of the role instance. +type RoleInstanceView struct { + // READ-ONLY; The Fault Domain. + PlatformFaultDomain *int32 + + // READ-ONLY; The Update Domain. + PlatformUpdateDomain *int32 + + // READ-ONLY; Specifies a unique identifier generated internally for the cloud service associated with this role instance. + // NOTE: If you are using Azure Diagnostics extension, this property can be used as 'DeploymentId' for querying details. + PrivateID *string + + // READ-ONLY + Statuses []*ResourceInstanceViewStatus +} + +// RoleInstances - Specifies a list of role instances from the cloud service. +type RoleInstances struct { + // REQUIRED; List of cloud service role instance names. Value of '*' will signify all role instances of the cloud service. + RoleInstances []*string +} + +// RollbackStatusInfo - Information about rollback on failed VM instances after a OS Upgrade operation. +type RollbackStatusInfo struct { + // READ-ONLY; The number of instances which failed to rollback. + FailedRolledbackInstanceCount *int32 + + // READ-ONLY; Error details if OS rollback failed. + RollbackError *APIError + + // READ-ONLY; The number of instances which have been successfully rolled back. + SuccessfullyRolledbackInstanceCount *int32 +} + +// RollingUpgradePolicy - The configuration parameters used while performing a rolling upgrade. +type RollingUpgradePolicy struct { + // Allow VMSS to ignore AZ boundaries when constructing upgrade batches. Take into consideration the Update Domain and maxBatchInstancePercent + // to determine the batch size. + EnableCrossZoneUpgrade *bool + + // The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one + // batch. As this is a maximum, unhealthy instances in previous or future batches + // can cause the percentage of instances in a batch to decrease to ensure higher reliability. The default value for this parameter + // is 20%. + MaxBatchInstancePercent *int32 + + // Create new virtual machines to upgrade the scale set, rather than updating the existing virtual machines. Existing virtual + // machines will be deleted once the new virtual machines are created for each + // batch. + MaxSurge *bool + + // The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy, either + // as a result of being upgraded, or by being found in an unhealthy state by + // the virtual machine health checks before the rolling upgrade aborts. This constraint will be checked prior to starting + // any batch. The default value for this parameter is 20%. + MaxUnhealthyInstancePercent *int32 + + // The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. This check + // will happen after each batch is upgraded. If this percentage is ever exceeded, + // the rolling update aborts. The default value for this parameter is 20%. + MaxUnhealthyUpgradedInstancePercent *int32 + + // The wait time between completing the update for all virtual machines in one batch and starting the next batch. The time + // duration should be specified in ISO 8601 format. The default value is 0 seconds + // (PT0S). + PauseTimeBetweenBatches *string + + // Upgrade all unhealthy instances in a scale set before any healthy instances. + PrioritizeUnhealthyInstances *bool + + // Rollback failed instances to previous model if the Rolling Upgrade policy is violated. + RollbackFailedInstancesOnPolicyBreach *bool +} + +// RollingUpgradeProgressInfo - Information about the number of virtual machine instances in each upgrade state. +type RollingUpgradeProgressInfo struct { + // READ-ONLY; The number of instances that have failed to be upgraded successfully. + FailedInstanceCount *int32 + + // READ-ONLY; The number of instances that are currently being upgraded. + InProgressInstanceCount *int32 + + // READ-ONLY; The number of instances that have not yet begun to be upgraded. + PendingInstanceCount *int32 + + // READ-ONLY; The number of instances that have been successfully upgraded. + SuccessfulInstanceCount *int32 +} + +// RollingUpgradeRunningStatus - Information about the current running state of the overall upgrade. +type RollingUpgradeRunningStatus struct { + // READ-ONLY; Code indicating the current status of the upgrade. + Code *RollingUpgradeStatusCode + + // READ-ONLY; The last action performed on the rolling upgrade. + LastAction *RollingUpgradeActionType + + // READ-ONLY; Last action time of the upgrade. + LastActionTime *time.Time + + // READ-ONLY; Start time of the upgrade. + StartTime *time.Time +} + +// RollingUpgradeStatusInfo - The status of the latest virtual machine scale set rolling upgrade. +type RollingUpgradeStatusInfo struct { + // REQUIRED; Resource location + Location *string + + // The status of the latest virtual machine scale set rolling upgrade. + Properties *RollingUpgradeStatusInfoProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// RollingUpgradeStatusInfoProperties - The status of the latest virtual machine scale set rolling upgrade. +type RollingUpgradeStatusInfoProperties struct { + // READ-ONLY; Error details for this upgrade, if there are any. + Error *APIError + + // READ-ONLY; The rolling upgrade policies applied for this upgrade. + Policy *RollingUpgradePolicy + + // READ-ONLY; Information about the number of virtual machine instances in each upgrade state. + Progress *RollingUpgradeProgressInfo + + // READ-ONLY; Information about the current running state of the overall upgrade. + RunningStatus *RollingUpgradeRunningStatus +} + +// RunCommandDocument - Describes the properties of a Run Command. +type RunCommandDocument struct { + // REQUIRED; The VM run command description. + Description *string + + // REQUIRED; The VM run command id. + ID *string + + // REQUIRED; The VM run command label. + Label *string + + // REQUIRED; The Operating System type. + OSType *OperatingSystemTypes + + // REQUIRED; The VM run command schema. + Schema *string + + // REQUIRED; The script to be executed. + Script []*string + + // The parameters used by the script. + Parameters []*RunCommandParameterDefinition +} + +// RunCommandDocumentBase - Describes the properties of a Run Command metadata. +type RunCommandDocumentBase struct { + // REQUIRED; The VM run command description. + Description *string + + // REQUIRED; The VM run command id. + ID *string + + // REQUIRED; The VM run command label. + Label *string + + // REQUIRED; The Operating System type. + OSType *OperatingSystemTypes + + // REQUIRED; The VM run command schema. + Schema *string +} + +// RunCommandInput - Capture Virtual Machine parameters. +type RunCommandInput struct { + // REQUIRED; The run command id. + CommandID *string + + // The run command parameters. + Parameters []*RunCommandInputParameter + + // Optional. The script to be executed. When this value is given, the given script will override the default script of the + // command. + Script []*string +} + +// RunCommandInputParameter - Describes the properties of a run command parameter. +type RunCommandInputParameter struct { + // REQUIRED; The run command parameter name. + Name *string + + // REQUIRED; The run command parameter value. + Value *string +} + +// RunCommandListResult - The List Virtual Machine operation response. +type RunCommandListResult struct { + // REQUIRED; The list of virtual machine run commands. + Value []*RunCommandDocumentBase + + // The uri to fetch the next page of run commands. Call ListNext() with this to fetch the next page of run commands. + NextLink *string +} + +// RunCommandManagedIdentity - Contains clientId or objectId (use only one, not both) of a user-assigned managed identity +// that has access to storage blob used in Run Command. Use an empty RunCommandManagedIdentity object in case of +// system-assigned identity. Make sure the Azure storage blob exists in case of scriptUri, and managed identity has been given +// access to blob's container with 'Storage Blob Data Reader' role assignment +// with scriptUri blob and 'Storage Blob Data Contributor' for Append blobs(outputBlobUri, errorBlobUri). In case of user +// assigned identity, make sure you add it under VM's identity. For more info on +// managed identity and Run Command, refer https://aka.ms/ManagedIdentity and https://aka.ms/RunCommandManaged. +type RunCommandManagedIdentity struct { + // Client Id (GUID value) of the user-assigned managed identity. ObjectId should not be used if this is provided. + ClientID *string + + // Object Id (GUID value) of the user-assigned managed identity. ClientId should not be used if this is provided. + ObjectID *string +} + +// RunCommandParameterDefinition - Describes the properties of a run command parameter. +type RunCommandParameterDefinition struct { + // REQUIRED; The run command parameter name. + Name *string + + // REQUIRED; The run command parameter type. + Type *string + + // The run command parameter default value. + DefaultValue *string + + // The run command parameter required. + Required *bool +} + +type RunCommandResult struct { + // Run command operation response. + Value []*InstanceViewStatus +} + +// SKU - Describes a virtual machine scale set sku. NOTE: If the new VM SKU is not supported on the hardware the scale set +// is currently on, you need to deallocate the VMs in the scale set before you modify the +// SKU name. +type SKU struct { + // Specifies the number of virtual machines in the scale set. + Capacity *int64 + + // The sku name. + Name *string + + // Specifies the tier of virtual machines in a scale set. + // Possible Values: + // Standard + // Basic + Tier *string +} + +// SSHConfiguration - SSH configuration for Linux based VMs running on Azure +type SSHConfiguration struct { + // The list of SSH public keys used to authenticate with linux based VMs. + PublicKeys []*SSHPublicKey +} + +// SSHGenerateKeyPairInputParameters - Parameters for GenerateSshKeyPair. +type SSHGenerateKeyPairInputParameters struct { + // The encryption type of the SSH keys to be generated. See SshEncryptionTypes for possible set of values. If not provided, + // will default to RSA + EncryptionType *SSHEncryptionTypes +} + +// SSHPublicKey - Contains information about SSH certificate public key and the path on the Linux VM where the public key +// is placed. +type SSHPublicKey struct { + // SSH public key certificate used to authenticate with the VM through ssh. The key needs to be at least 2048-bit and in ssh-rsa + // format. For creating ssh keys, see [Create SSH keys on Linux and Mac for + // Linux VMs in Azure]https://docs.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed). + KeyData *string + + // Specifies the full path on the created VM where ssh public key is stored. If the file already exists, the specified key + // is appended to the file. Example: /home/user/.ssh/authorized_keys + Path *string +} + +// SSHPublicKeyGenerateKeyPairResult - Response from generation of an SSH key pair. +type SSHPublicKeyGenerateKeyPairResult struct { + // REQUIRED; The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{SshPublicKeyName} + ID *string + + // REQUIRED; Private key portion of the key pair used to authenticate to a virtual machine through ssh. The private key is + // returned in RFC3447 format and should be treated as a secret. + PrivateKey *string + + // REQUIRED; Public key portion of the key pair used to authenticate to a virtual machine through ssh. The public key is in + // ssh-rsa format. + PublicKey *string +} + +// SSHPublicKeyResource - Specifies information about the SSH public key. +type SSHPublicKeyResource struct { + // REQUIRED; Resource location + Location *string + + // Properties of the SSH public key. + Properties *SSHPublicKeyResourceProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// SSHPublicKeyResourceProperties - Properties of the SSH public key. +type SSHPublicKeyResourceProperties struct { + // SSH public key used to authenticate to a virtual machine through ssh. If this property is not initially provided when the + // resource is created, the publicKey property will be populated when + // generateKeyPair is called. If the public key is provided upon resource creation, the provided public key needs to be at + // least 2048-bit and in ssh-rsa format. + PublicKey *string +} + +// SSHPublicKeyUpdateResource - Specifies information about the SSH public key. +type SSHPublicKeyUpdateResource struct { + // Properties of the SSH public key. + Properties *SSHPublicKeyResourceProperties + + // Resource tags + Tags map[string]*string +} + +// SSHPublicKeysGroupListResult - The list SSH public keys operation response. +type SSHPublicKeysGroupListResult struct { + // REQUIRED; The list of SSH public keys + Value []*SSHPublicKeyResource + + // The URI to fetch the next page of SSH public keys. Call ListNext() with this URI to fetch the next page of SSH public keys. + NextLink *string +} + +// ScaleInPolicy - Describes a scale-in policy for a virtual machine scale set. +type ScaleInPolicy struct { + // This property allows you to specify if virtual machines chosen for removal have to be force deleted when a virtual machine + // scale set is being scaled-in.(Feature in Preview) + ForceDeletion *bool + + // The rules to be followed when scaling-in a virtual machine scale set. + // Possible values are: + // Default When a virtual machine scale set is scaled in, the scale set will first be balanced across zones if it is a zonal + // scale set. Then, it will be balanced across Fault Domains as far as possible. + // Within each Fault Domain, the virtual machines chosen for removal will be the newest ones that are not protected from scale-in. + // OldestVM When a virtual machine scale set is being scaled-in, the oldest virtual machines that are not protected from scale-in + // will be chosen for removal. For zonal virtual machine scale sets, the + // scale set will first be balanced across zones. Within each zone, the oldest virtual machines that are not protected will + // be chosen for removal. + // NewestVM When a virtual machine scale set is being scaled-in, the newest virtual machines that are not protected from scale-in + // will be chosen for removal. For zonal virtual machine scale sets, the + // scale set will first be balanced across zones. Within each zone, the newest virtual machines that are not protected will + // be chosen for removal. + Rules []*VirtualMachineScaleSetScaleInRules +} + +type ScheduledEventsProfile struct { + // Specifies OS Image Scheduled Event related configurations. + OSImageNotificationProfile *OSImageNotificationProfile + + // Specifies Terminate Scheduled Event related configurations. + TerminateNotificationProfile *TerminateNotificationProfile +} + +// SecurityPostureReference - Specifies the security posture to be used for all virtual machines in the scale set. Minimum +// api-version: 2023-03-01 +type SecurityPostureReference struct { + // List of virtual machine extensions to exclude when applying the Security Posture. + ExcludeExtensions []*VirtualMachineExtension + + // The security posture reference id in the form of /CommunityGalleries/{communityGalleryName}/securityPostures/{securityPostureName}/versions/{major.minor.patch}|{major.*}|latest + ID *string +} + +// SecurityProfile - Specifies the Security profile settings for the virtual machine or virtual machine scale set. +type SecurityProfile struct { + // This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine or virtual + // machine scale set. This will enable the encryption for all the disks + // including Resource/Temp disk at host itself. The default behavior is: The Encryption at host will be disabled unless this + // property is set to true for the resource. + EncryptionAtHost *bool + + // Specifies the Managed Identity used by ADE to get access token for keyvault operations. + EncryptionIdentity *EncryptionIdentity + + // Specifies ProxyAgent settings while creating the virtual machine. Minimum api-version: 2023-09-01. + ProxyAgentSettings *ProxyAgentSettings + + // Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. The + // default behavior is: UefiSettings will not be enabled unless this property is + // set. + SecurityType *SecurityTypes + + // Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Minimum api-version: + // 2020-12-01. + UefiSettings *UefiSettings +} + +// ServiceArtifactReference - Specifies the service artifact reference id used to set same image version for all virtual machines +// in the scale set when using 'latest' image version. Minimum api-version: 2022-11-01 +type ServiceArtifactReference struct { + // The service artifact reference id in the form of + // /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName} + ID *string +} + +type ShareInfoElement struct { + // READ-ONLY; A relative URI containing the ID of the VM that has the disk attached. + VMURI *string +} + +// SharedGallery - Specifies information about the Shared Gallery that you want to create or update. +type SharedGallery struct { + // The identifier information of shared gallery. + Identifier *SharedGalleryIdentifier + + // Specifies the properties of a shared gallery + Properties *SharedGalleryProperties + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string +} + +// SharedGalleryDataDiskImage - This is the data disk image. +type SharedGalleryDataDiskImage struct { + // REQUIRED; This property specifies the logical unit number of the data disk. This value is used to identify data disks within + // the Virtual Machine and therefore must be unique for each data disk attached to the + // Virtual Machine. + Lun *int32 + + // The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' + HostCaching *SharedGalleryHostCaching + + // READ-ONLY; This property indicates the size of the VHD to be created. + DiskSizeGB *int32 +} + +// SharedGalleryDiskImage - This is the disk image base class. +type SharedGalleryDiskImage struct { + // The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' + HostCaching *SharedGalleryHostCaching + + // READ-ONLY; This property indicates the size of the VHD to be created. + DiskSizeGB *int32 +} + +// SharedGalleryIdentifier - The identifier information of shared gallery. +type SharedGalleryIdentifier struct { + // The unique id of this shared gallery. + UniqueID *string +} + +// SharedGalleryImage - Specifies information about the gallery image definition that you want to create or update. +type SharedGalleryImage struct { + // The identifier information of shared gallery. + Identifier *SharedGalleryIdentifier + + // Describes the properties of a gallery image definition. + Properties *SharedGalleryImageProperties + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string +} + +// SharedGalleryImageList - The List Shared Gallery Images operation response. +type SharedGalleryImageList struct { + // REQUIRED; A list of shared gallery images. + Value []*SharedGalleryImage + + // The uri to fetch the next page of shared gallery images. Call ListNext() with this to fetch the next page of shared gallery + // images. + NextLink *string +} + +// SharedGalleryImageProperties - Describes the properties of a gallery image definition. +type SharedGalleryImageProperties struct { + // REQUIRED; This is the gallery image definition identifier. + Identifier *GalleryImageIdentifier + + // REQUIRED; This property allows the user to specify whether the virtual machines created under this image are 'Generalized' + // or 'Specialized'. + OSState *OperatingSystemStateTypes + + // REQUIRED; This property allows you to specify the type of the OS that is included in the disk when creating a VM from a + // managed image. Possible values are: Windows, Linux. + OSType *OperatingSystemTypes + + // The architecture of the image. Applicable to OS disks only. + Architecture *Architecture + + // The artifact tags of a shared gallery resource. + ArtifactTags map[string]*string + + // Describes the disallowed disk types. + Disallowed *Disallowed + + // The end of life date of the gallery image definition. This property can be used for decommissioning purposes. This property + // is updatable. + EndOfLifeDate *time.Time + + // End-user license agreement for the current community gallery image. + Eula *string + + // A list of gallery image features. + Features []*GalleryImageFeature + + // The hypervisor generation of the Virtual Machine. Applicable to OS disks only. + HyperVGeneration *HyperVGeneration + + // Privacy statement uri for the current community gallery image. + PrivacyStatementURI *string + + // Describes the gallery image definition purchase plan. This is used by marketplace images. + PurchasePlan *ImagePurchasePlan + + // The properties describe the recommended machine configuration for this Image Definition. These properties are updatable. + Recommended *RecommendedMachineConfiguration +} + +// SharedGalleryImageVersion - Specifies information about the gallery image version that you want to create or update. +type SharedGalleryImageVersion struct { + // The identifier information of shared gallery. + Identifier *SharedGalleryIdentifier + + // Describes the properties of a gallery image version. + Properties *SharedGalleryImageVersionProperties + + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Resource name + Name *string +} + +// SharedGalleryImageVersionList - The List Shared Gallery Image versions operation response. +type SharedGalleryImageVersionList struct { + // REQUIRED; A list of shared gallery images versions. + Value []*SharedGalleryImageVersion + + // The uri to fetch the next page of shared gallery image versions. Call ListNext() with this to fetch the next page of shared + // gallery image versions. + NextLink *string +} + +// SharedGalleryImageVersionProperties - Describes the properties of a gallery image version. +type SharedGalleryImageVersionProperties struct { + // The artifact tags of a shared gallery resource. + ArtifactTags map[string]*string + + // The end of life date of the gallery image version Definition. This property can be used for decommissioning purposes. This + // property is updatable. + EndOfLifeDate *time.Time + + // If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. + ExcludeFromLatest *bool + + // The published date of the gallery image version Definition. This property can be used for decommissioning purposes. This + // property is updatable. + PublishedDate *time.Time + + // Describes the storage profile of the image version. + StorageProfile *SharedGalleryImageVersionStorageProfile +} + +// SharedGalleryImageVersionStorageProfile - This is the storage profile of a Gallery Image Version. +type SharedGalleryImageVersionStorageProfile struct { + // A list of data disk images. + DataDiskImages []*SharedGalleryDataDiskImage + + // This is the OS disk image. + OSDiskImage *SharedGalleryOSDiskImage +} + +// SharedGalleryList - The List Shared Galleries operation response. +type SharedGalleryList struct { + // REQUIRED; A list of shared galleries. + Value []*SharedGallery + + // The uri to fetch the next page of shared galleries. Call ListNext() with this to fetch the next page of shared galleries. + NextLink *string +} + +// SharedGalleryOSDiskImage - This is the OS disk image. +type SharedGalleryOSDiskImage struct { + // The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' + HostCaching *SharedGalleryHostCaching + + // READ-ONLY; This property indicates the size of the VHD to be created. + DiskSizeGB *int32 +} + +// SharedGalleryProperties - Specifies the properties of a shared gallery +type SharedGalleryProperties struct { + // READ-ONLY; The artifact tags of a shared gallery resource. + ArtifactTags map[string]*string +} + +// SharingProfile - Profile for gallery sharing to subscription or tenant +type SharingProfile struct { + // Information of community gallery if current gallery is shared to community. + CommunityGalleryInfo *CommunityGalleryInfo + + // This property allows you to specify the permission of sharing gallery. Possible values are: Private, Groups, Community. + Permissions *GallerySharingPermissionTypes + + // READ-ONLY; A list of sharing profile groups. + Groups []*SharingProfileGroup +} + +// SharingProfileGroup - Group of the gallery sharing profile +type SharingProfileGroup struct { + // A list of subscription/tenant ids the gallery is aimed to be shared to. + IDs []*string + + // This property allows you to specify the type of sharing group. Possible values are: Subscriptions, AADTenants. + Type *SharingProfileGroupTypes +} + +// SharingStatus - Sharing status of current gallery. +type SharingStatus struct { + // Summary of all regional sharing status. + Summary []*RegionalSharingStatus + + // READ-ONLY; Aggregated sharing state of current gallery. + AggregatedState *SharingState +} + +// SharingUpdate - Specifies information about the gallery sharing profile update. +type SharingUpdate struct { + // REQUIRED; This property allows you to specify the operation type of gallery sharing update. Possible values are: Add, Remove, + // Reset. + OperationType *SharingUpdateOperationTypes + + // A list of sharing profile groups. + Groups []*SharingProfileGroup +} + +// Snapshot resource. +type Snapshot struct { + // REQUIRED; Resource location + Location *string + + // The extended location where the snapshot will be created. Extended location cannot be changed. + ExtendedLocation *ExtendedLocation + + // Snapshot resource properties. + Properties *SnapshotProperties + + // The snapshots sku name. Can be StandardLRS, PremiumLRS, or Standard_ZRS. This is an optional parameter for incremental + // snapshot and the default behavior is the SKU will be set to the same sku as the + // previous snapshot + SKU *SnapshotSKU + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Unused. Always Null. + ManagedBy *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// SnapshotList - The List Snapshots operation response. +type SnapshotList struct { + // REQUIRED; A list of snapshots. + Value []*Snapshot + + // The uri to fetch the next page of snapshots. Call ListNext() with this to fetch the next page of snapshots. + NextLink *string +} + +// SnapshotProperties - Snapshot resource properties. +type SnapshotProperties struct { + // REQUIRED; Disk source information. CreationData information cannot be changed after the disk has been created. + CreationData *CreationData + + // Percentage complete for the background copy when a resource is created via the CopyStart operation. + CompletionPercent *float32 + + // Indicates the error details if the background copy of a resource created via the CopyStart operation fails. + CopyCompletionError *CopyCompletionError + + // Additional authentication requirements when exporting or uploading to a disk or snapshot. + DataAccessAuthMode *DataAccessAuthMode + + // ARM id of the DiskAccess resource for using private endpoints on disks. + DiskAccessID *string + + // If creationData.createOption is Empty, this field is mandatory and it indicates the size of the disk to create. If this + // field is present for updates or creation with other options, it indicates a + // resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. + DiskSizeGB *int32 + + // Encryption property can be used to encrypt data at rest with customer managed keys or platform managed keys. + Encryption *Encryption + + // Encryption settings collection used be Azure Disk Encryption, can contain multiple encryption settings per disk or snapshot. + EncryptionSettingsCollection *EncryptionSettingsCollection + + // The hypervisor generation of the Virtual Machine. Applicable to OS disks only. + HyperVGeneration *HyperVGeneration + + // Whether a snapshot is incremental. Incremental snapshots on the same disk occupy less space than full snapshots and can + // be diffed. + Incremental *bool + + // Policy for accessing the disk via network. + NetworkAccessPolicy *NetworkAccessPolicy + + // The Operating System type. + OSType *OperatingSystemTypes + + // Policy for controlling export on the disk. + PublicNetworkAccess *PublicNetworkAccess + + // Purchase plan information for the image from which the source disk for the snapshot was originally created. + PurchasePlan *DiskPurchasePlan + + // Contains the security related information for the resource. + SecurityProfile *DiskSecurityProfile + + // List of supported capabilities for the image from which the source disk from the snapshot was originally created. + SupportedCapabilities *SupportedCapabilities + + // Indicates the OS on a snapshot supports hibernation. + SupportsHibernation *bool + + // READ-ONLY; The size of the disk in bytes. This field is read only. + DiskSizeBytes *int64 + + // READ-ONLY; The state of the snapshot. + DiskState *DiskState + + // READ-ONLY; Incremental snapshots for a disk share an incremental snapshot family id. The Get Page Range Diff API can only + // be called on incremental snapshots with the same family id. + IncrementalSnapshotFamilyID *string + + // READ-ONLY; The disk provisioning state. + ProvisioningState *string + + // READ-ONLY; The time when the snapshot was created. + TimeCreated *time.Time + + // READ-ONLY; Unique Guid identifying the resource. + UniqueID *string +} + +// SnapshotSKU - The snapshots sku name. Can be StandardLRS, PremiumLRS, or Standard_ZRS. This is an optional parameter for +// incremental snapshot and the default behavior is the SKU will be set to the same sku as the +// previous snapshot +type SnapshotSKU struct { + // The sku name. + Name *SnapshotStorageAccountTypes + + // READ-ONLY; The sku tier. + Tier *string +} + +// SnapshotUpdate - Snapshot update resource. +type SnapshotUpdate struct { + // Snapshot resource update properties. + Properties *SnapshotUpdateProperties + + // The snapshots sku name. Can be StandardLRS, PremiumLRS, or Standard_ZRS. This is an optional parameter for incremental + // snapshot and the default behavior is the SKU will be set to the same sku as the + // previous snapshot + SKU *SnapshotSKU + + // Resource tags + Tags map[string]*string +} + +// SnapshotUpdateProperties - Snapshot resource update properties. +type SnapshotUpdateProperties struct { + // Additional authentication requirements when exporting or uploading to a disk or snapshot. + DataAccessAuthMode *DataAccessAuthMode + + // ARM id of the DiskAccess resource for using private endpoints on disks. + DiskAccessID *string + + // If creationData.createOption is Empty, this field is mandatory and it indicates the size of the disk to create. If this + // field is present for updates or creation with other options, it indicates a + // resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. + DiskSizeGB *int32 + + // Encryption property can be used to encrypt data at rest with customer managed keys or platform managed keys. + Encryption *Encryption + + // Encryption settings collection used be Azure Disk Encryption, can contain multiple encryption settings per disk or snapshot. + EncryptionSettingsCollection *EncryptionSettingsCollection + + // Policy for accessing the disk via network. + NetworkAccessPolicy *NetworkAccessPolicy + + // the Operating System type. + OSType *OperatingSystemTypes + + // Policy for controlling export on the disk. + PublicNetworkAccess *PublicNetworkAccess + + // List of supported capabilities for the image from which the OS disk was created. + SupportedCapabilities *SupportedCapabilities + + // Indicates the OS on a snapshot supports hibernation. + SupportsHibernation *bool +} + +// SoftDeletePolicy - Contains information about the soft deletion policy of the gallery. +type SoftDeletePolicy struct { + // Enables soft-deletion for resources in this gallery, allowing them to be recovered within retention time. + IsSoftDeleteEnabled *bool +} + +// SourceVault - The vault id is an Azure Resource Manager Resource id in the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} +type SourceVault struct { + // Resource Id + ID *string +} + +// SpotRestorePolicy - Specifies the Spot-Try-Restore properties for the virtual machine scale set. With this property customer +// can enable or disable automatic restore of the evicted Spot VMSS VM instances opportunistically +// based on capacity availability and pricing constraint. +type SpotRestorePolicy struct { + // Enables the Spot-Try-Restore feature where evicted VMSS SPOT instances will be tried to be restored opportunistically based + // on capacity availability and pricing constraints + Enabled *bool + + // Timeout value expressed as an ISO 8601 time duration after which the platform will not try to restore the VMSS SPOT instances + RestoreTimeout *string +} + +// StatusCodeCount - The status code and count of the cloud service instance view statuses +type StatusCodeCount struct { + // READ-ONLY; The instance view status code + Code *string + + // READ-ONLY; Number of instances having this status code + Count *int32 +} + +// StorageProfile - Specifies the storage settings for the virtual machine disks. +type StorageProfile struct { + // Specifies the parameters that are used to add a data disk to a virtual machine. For more information about disks, see About + // disks and VHDs for Azure virtual machines + // [https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview]. + DataDisks []*DataDisk + + // Specifies the disk controller type configured for the VM. Note: This property will be set to the default disk controller + // type if not specified provided virtual machine is being created with + // 'hyperVGeneration' set to V2 based on the capabilities of the operating system disk and VM size from the the specified + // minimum api version. You need to deallocate the VM before updating its disk + // controller type unless you are updating the VM size in the VM configuration which implicitly deallocates and reallocates + // the VM. Minimum api-version: 2022-08-01. + DiskControllerType *DiskControllerTypes + + // Specifies information about the image to use. You can specify information about platform images, marketplace images, or + // virtual machine images. This element is required when you want to use a platform + // image, marketplace image, or virtual machine image, but is not used in other creation operations. + ImageReference *ImageReference + + // Specifies information about the operating system disk used by the virtual machine. For more information about disks, see + // About disks and VHDs for Azure virtual machines + // [https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview]. + OSDisk *OSDisk +} + +type SubResource struct { + // Resource Id + ID *string +} + +type SubResourceReadOnly struct { + // READ-ONLY; Resource Id + ID *string +} + +type SubResourceWithColocationStatus struct { + // Describes colocation status of a resource in the Proximity Placement Group. + ColocationStatus *InstanceViewStatus + + // Resource Id + ID *string +} + +// SupportedCapabilities - List of supported capabilities persisted on the disk resource for VM use. +type SupportedCapabilities struct { + // True if the image from which the OS disk is created supports accelerated networking. + AcceleratedNetwork *bool + + // CPU architecture supported by an OS disk. + Architecture *Architecture + + // The disk controllers that an OS disk supports. If set it can be SCSI or SCSI, NVME or NVME, SCSI. + DiskControllerTypes *string +} + +// SystemData - The system meta data relating to this resource. +type SystemData struct { + // READ-ONLY; Specifies the time in UTC at which the Cloud Service (extended support) resource was created. + // Minimum api-version: 2022-04-04. + CreatedAt *time.Time + + // READ-ONLY; Specifies the time in UTC at which the Cloud Service (extended support) resource was last modified. + // Minimum api-version: 2022-04-04. + LastModifiedAt *time.Time +} + +// TargetRegion - Describes the target region information. +type TargetRegion struct { + // REQUIRED; The name of the region. + Name *string + + // Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the gallery artifact. + Encryption *EncryptionImages + + // Contains the flag setting to hide an image when users specify version='latest' + ExcludeFromLatest *bool + + // The number of replicas of the Image Version to be created per region. This property is updatable. + RegionalReplicaCount *int32 + + // Specifies the storage account type to be used to store the image. This property is not updatable. + StorageAccountType *StorageAccountType +} + +type TerminateNotificationProfile struct { + // Specifies whether the Terminate Scheduled event is enabled or disabled. + Enable *bool + + // Configurable length of time a Virtual Machine being deleted will have to potentially approve the Terminate Scheduled Event + // before the event is auto approved (timed out). The configuration must be + // specified in ISO 8601 format, the default value is 5 minutes (PT5M) + NotBeforeTimeout *string +} + +// ThrottledRequestsInput - Api request input for LogAnalytics getThrottledRequests Api. +type ThrottledRequestsInput struct { + // REQUIRED; SAS Uri of the logging blob container to which LogAnalytics Api writes output logs to. + BlobContainerSasURI *string + + // REQUIRED; From time of the query + FromTime *time.Time + + // REQUIRED; To time of the query + ToTime *time.Time + + // Group query result by Client Application ID. + GroupByClientApplicationID *bool + + // Group query result by Operation Name. + GroupByOperationName *bool + + // Group query result by Resource Name. + GroupByResourceName *bool + + // Group query result by Throttle Policy applied. + GroupByThrottlePolicy *bool + + // Group query result by User Agent. + GroupByUserAgent *bool +} + +// UefiKey - A UEFI key signature. +type UefiKey struct { + // The type of key signature. + Type *UefiKeyType + + // The value of the key signature. + Value []*string +} + +// UefiKeySignatures - Additional UEFI key signatures that will be added to the image in addition to the signature templates +type UefiKeySignatures struct { + // The database of UEFI keys for this image version. + Db []*UefiKey + + // The database of revoked UEFI keys for this image version. + Dbx []*UefiKey + + // The Key Encryption Keys of this image version. + Kek []*UefiKey + + // The Platform Key of this image version. + Pk *UefiKey +} + +// UefiSettings - Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Minimum +// api-version: 2020-12-01. +type UefiSettings struct { + // Specifies whether secure boot should be enabled on the virtual machine. Minimum api-version: 2020-12-01. + SecureBootEnabled *bool + + // Specifies whether vTPM should be enabled on the virtual machine. Minimum api-version: 2020-12-01. + VTpmEnabled *bool +} + +// UpdateDomain - Defines an update domain for the cloud service. +type UpdateDomain struct { + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource Name + Name *string +} + +// UpdateDomainListResult - The list operation result. +type UpdateDomainListResult struct { + // REQUIRED; The list of resources. + Value []*UpdateDomain + + // The URI to fetch the next page of resources. Use this to get the next page of resources. Do this till nextLink is null + // to fetch all the resources. + NextLink *string +} + +// UpdateResource - The Update Resource model definition. +type UpdateResource struct { + // Resource tags + Tags map[string]*string +} + +// UpdateResourceDefinition - The Update Resource model definition. +type UpdateResourceDefinition struct { + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// UpgradeOperationHistoricalStatusInfo - Virtual Machine Scale Set OS Upgrade History operation response. +type UpgradeOperationHistoricalStatusInfo struct { + // READ-ONLY; Resource location + Location *string + + // READ-ONLY; Information about the properties of the upgrade operation. + Properties *UpgradeOperationHistoricalStatusInfoProperties + + // READ-ONLY; Resource type + Type *string +} + +// UpgradeOperationHistoricalStatusInfoProperties - Describes each OS upgrade on the Virtual Machine Scale Set. +type UpgradeOperationHistoricalStatusInfoProperties struct { + // READ-ONLY; Error Details for this upgrade if there are any. + Error *APIError + + // READ-ONLY; Counts of the VMs in each state. + Progress *RollingUpgradeProgressInfo + + // READ-ONLY; Information about OS rollback if performed + RollbackInfo *RollbackStatusInfo + + // READ-ONLY; Information about the overall status of the upgrade operation. + RunningStatus *UpgradeOperationHistoryStatus + + // READ-ONLY; Invoker of the Upgrade Operation + StartedBy *UpgradeOperationInvoker + + // READ-ONLY; Image Reference details + TargetImageReference *ImageReference +} + +// UpgradeOperationHistoryStatus - Information about the current running state of the overall upgrade. +type UpgradeOperationHistoryStatus struct { + // READ-ONLY; Code indicating the current status of the upgrade. + Code *UpgradeState + + // READ-ONLY; End time of the upgrade. + EndTime *time.Time + + // READ-ONLY; Start time of the upgrade. + StartTime *time.Time +} + +// UpgradePolicy - Describes an upgrade policy - automatic, manual, or rolling. +type UpgradePolicy struct { + // Configuration parameters used for performing automatic OS Upgrade. + AutomaticOSUpgradePolicy *AutomaticOSUpgradePolicy + + // Specifies the mode of an upgrade to virtual machines in the scale set. + // Possible values are: + // Manual - You control the application of updates to virtual machines in the scale set. You do this by using the manualUpgrade + // action. + // Automatic - All virtual machines in the scale set are automatically updated at the same time. + Mode *UpgradeMode + + // The configuration parameters used while performing a rolling upgrade. + RollingUpgradePolicy *RollingUpgradePolicy +} + +// Usage - Describes Compute Resource Usage. +type Usage struct { + // REQUIRED; The current usage of the resource. + CurrentValue *int32 + + // REQUIRED; The maximum permitted usage of the resource. + Limit *int64 + + // REQUIRED; The name of the type of usage. + Name *UsageName + + // REQUIRED; An enum describing the unit of usage measurement. + Unit *string +} + +// UsageName - The Usage Names. +type UsageName struct { + // The localized name of the resource. + LocalizedValue *string + + // The name of the resource. + Value *string +} + +type UserArtifactManage struct { + // REQUIRED; Required. The path and arguments to install the gallery application. This is limited to 4096 characters. + Install *string + + // REQUIRED; Required. The path and arguments to remove the gallery application. This is limited to 4096 characters. + Remove *string + + // Optional. The path and arguments to update the gallery application. If not present, then update operation will invoke remove + // command on the previous version and install command on the current version + // of the gallery application. This is limited to 4096 characters. + Update *string +} + +// UserArtifactSettings - Additional settings for the VM app that contains the target package and config file name when it +// is deployed to target VM or VM scale set. +type UserArtifactSettings struct { + // Optional. The name to assign the downloaded config file on the VM. This is limited to 4096 characters. If not specified, + // the config file will be named the Gallery Application name appended with + // "_config". + ConfigFileName *string + + // Optional. The name to assign the downloaded package file on the VM. This is limited to 4096 characters. If not specified, + // the package file will be named the same as the Gallery Application name. + PackageFileName *string +} + +// UserArtifactSource - The source image from which the Image Version is going to be created. +type UserArtifactSource struct { + // REQUIRED; Required. The mediaLink of the artifact, must be a readable storage page blob. + MediaLink *string + + // Optional. The defaultConfigurationLink of the artifact, must be a readable storage page blob. + DefaultConfigurationLink *string +} + +type UserAssignedIdentitiesValue struct { + // READ-ONLY; The client id of user assigned identity. + ClientID *string + + // READ-ONLY; The principal id of user assigned identity. + PrincipalID *string +} + +// VMDiskSecurityProfile - Specifies the security profile settings for the managed disk. Note: It can only be set for Confidential +// VMs. +type VMDiskSecurityProfile struct { + // Specifies the customer managed disk encryption set resource id for the managed disk that is used for Customer Managed Key + // encrypted ConfidentialVM OS Disk and VMGuest blob. + DiskEncryptionSet *DiskEncryptionSetParameters + + // Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for encryption of the managed disk + // along with VMGuestState blob, VMGuestStateOnly for encryption of just the + // VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the VMGuestState blob.. Note: It can be set + // for only Confidential VMs. + SecurityEncryptionType *SecurityEncryptionTypes +} + +// VMGalleryApplication - Specifies the required information to reference a compute gallery application version +type VMGalleryApplication struct { + // REQUIRED; Specifies the GalleryApplicationVersion resource id on the form of + // /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{application}/versions/{version} + PackageReferenceID *string + + // Optional, Specifies the uri to an azure blob that will replace the default configuration for the package if provided + ConfigurationReference *string + + // If set to true, when a new Gallery Application version is available in PIR/SIG, it will be automatically updated for the + // VM/VMSS + EnableAutomaticUpgrade *bool + + // Optional, Specifies the order in which the packages have to be installed + Order *int32 + + // Optional, Specifies a passthrough value for more generic context. + Tags *string + + // Optional, If true, any failure for any operation in the VmApplication will fail the deployment + TreatFailureAsDeploymentFailure *bool +} + +// VMImagesInEdgeZoneListResult - The List VmImages in EdgeZone operation response. +type VMImagesInEdgeZoneListResult struct { + // The URI to fetch the next page of VMImages in EdgeZone. Call ListNext() with this URI to fetch the next page of VmImages. + NextLink *string + + // The list of VMImages in EdgeZone + Value []*VirtualMachineImageResource +} + +type VMScaleSetConvertToSinglePlacementGroupInput struct { + // Id of the placement group in which you want future virtual machine instances to be placed. To query placement group Id, + // please use Virtual Machine Scale Set VMs - Get API. If not provided, the + // platform will choose one with maximum number of virtual machine instances. + ActivePlacementGroupID *string +} + +// VMSizeProperties - Specifies VM Size Property settings on the virtual machine. +type VMSizeProperties struct { + // Specifies the number of vCPUs available for the VM. When this property is not specified in the request body the default + // behavior is to set it to the value of vCPUs available for that VM size exposed + // in api response of List all available virtual machine sizes in a region [https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list]. + VCPUsAvailable *int32 + + // Specifies the vCPU to physical core ratio. When this property is not specified in the request body the default behavior + // is set to the value of vCPUsPerCore for the VM Size exposed in api response of + // List all available virtual machine sizes in a region [https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list]. + // Setting this property to 1 also means that hyper-threading is disabled. + VCPUsPerCore *int32 +} + +// VaultCertificate - Describes a single certificate reference in a Key Vault, and where the certificate should reside on +// the VM. +type VaultCertificate struct { + // For Windows VMs, specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified + // certificate store is implicitly in the LocalMachine account. For Linux + // VMs, the certificate file is placed under the /var/lib/waagent directory, with the file name .crt + // for the X509 certificate file and .prv for private key. Both + // of these files are .pem formatted. + CertificateStore *string + + // This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, + // see Add a key or secret to the key vault + // [https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add]. In this case, your certificate needs to be It + // is the Base64 encoding of the following JSON Object which is encoded in UTF-8: + // { + // "data":"", + // "dataType":"pfx", + // "password":"" + // } + // To install certificates on a virtual machine it is recommended to use the Azure Key Vault virtual machine extension for + // Linux + // [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux] or the Azure Key Vault virtual machine extension + // for Windows + // [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows]. + CertificateURL *string +} + +// VaultSecretGroup - Describes a set of certificates which are all in the same Key Vault. +type VaultSecretGroup struct { + // The relative URL of the Key Vault containing all of the certificates in VaultCertificates. + SourceVault *SubResource + + // The list of key vault references in SourceVault which contain certificates. + VaultCertificates []*VaultCertificate +} + +// VirtualHardDisk - Describes the uri of a disk. +type VirtualHardDisk struct { + // Specifies the virtual hard disk's uri. + URI *string +} + +// VirtualMachine - Describes a Virtual Machine. +type VirtualMachine struct { + // REQUIRED; Resource location + Location *string + + // The extended location of the Virtual Machine. + ExtendedLocation *ExtendedLocation + + // The identity of the virtual machine, if configured. + Identity *VirtualMachineIdentity + + // Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace + // images. Before you can use a marketplace image from an API, you must + // enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click + // Want to deploy programmatically, Get Started ->. Enter any required + // information and then click Save. + Plan *Plan + + // Describes the properties of a Virtual Machine. + Properties *VirtualMachineProperties + + // Resource tags + Tags map[string]*string + + // The virtual machine zones. + Zones []*string + + // READ-ONLY; Etag is property returned in Create/Update/Get response of the VM, so that customer can supply it in the header + // to ensure optimistic updates. + Etag *string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; ManagedBy is set to Virtual Machine Scale Set(VMSS) flex ARM resourceID, if the VM is part of the VMSS. This + // property is used by platform for internal resource group delete optimization. + ManagedBy *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; The virtual machine child extension resources. + Resources []*VirtualMachineExtension + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineAgentInstanceView - The instance view of the VM Agent running on the virtual machine. +type VirtualMachineAgentInstanceView struct { + // The virtual machine extension handler instance view. + ExtensionHandlers []*VirtualMachineExtensionHandlerInstanceView + + // The resource status information. + Statuses []*InstanceViewStatus + + // The VM Agent full version. + VMAgentVersion *string +} + +// VirtualMachineAssessPatchesResult - Describes the properties of an AssessPatches result. +type VirtualMachineAssessPatchesResult struct { + // READ-ONLY; The activity ID of the operation that produced this result. It is used to correlate across CRP and extension + // logs. + AssessmentActivityID *string + + // READ-ONLY; The list of patches that have been detected as available for installation. + AvailablePatches []*VirtualMachineSoftwarePatchProperties + + // READ-ONLY; The number of critical or security patches that have been detected as available and not yet installed. + CriticalAndSecurityPatchCount *int32 + + // READ-ONLY; The errors that were encountered during execution of the operation. The details array contains the list of them. + Error *APIError + + // READ-ONLY; The number of all available patches excluding critical and security. + OtherPatchCount *int32 + + // READ-ONLY; The overall reboot status of the VM. It will be true when partially installed patches require a reboot to complete + // installation but the reboot has not yet occurred. + RebootPending *bool + + // READ-ONLY; The UTC timestamp when the operation began. + StartDateTime *time.Time + + // READ-ONLY; The overall success or failure status of the operation. It remains "InProgress" until the operation completes. + // At that point it will become "Unknown", "Failed", "Succeeded", or + // "CompletedWithWarnings." + Status *PatchOperationStatus +} + +// VirtualMachineCaptureParameters - Capture Virtual Machine parameters. +type VirtualMachineCaptureParameters struct { + // REQUIRED; The destination container name. + DestinationContainerName *string + + // REQUIRED; Specifies whether to overwrite the destination virtual hard disk, in case of conflict. + OverwriteVhds *bool + + // REQUIRED; The captured virtual hard disk's name prefix. + VhdPrefix *string +} + +// VirtualMachineCaptureResult - Output of virtual machine capture operation. +type VirtualMachineCaptureResult struct { + // Resource Id + ID *string + + // READ-ONLY; the version of the content + ContentVersion *string + + // READ-ONLY; parameters of the captured virtual machine + Parameters any + + // READ-ONLY; a list of resource items of the captured virtual machine + Resources []any + + // READ-ONLY; the schema of the captured virtual machine + Schema *string +} + +// VirtualMachineExtension - Describes a Virtual Machine Extension. +type VirtualMachineExtension struct { + // Resource location + Location *string + + // Describes the properties of a Virtual Machine Extension. + Properties *VirtualMachineExtensionProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineExtensionHandlerInstanceView - The instance view of a virtual machine extension handler. +type VirtualMachineExtensionHandlerInstanceView struct { + // The extension handler status. + Status *InstanceViewStatus + + // Specifies the type of the extension; an example is "CustomScriptExtension". + Type *string + + // Specifies the version of the script handler. + TypeHandlerVersion *string +} + +// VirtualMachineExtensionImage - Describes a Virtual Machine Extension Image. +type VirtualMachineExtensionImage struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a Virtual Machine Extension Image. + Properties *VirtualMachineExtensionImageProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineExtensionImageProperties - Describes the properties of a Virtual Machine Extension Image. +type VirtualMachineExtensionImageProperties struct { + // REQUIRED; The type of role (IaaS or PaaS) this extension supports. + ComputeRole *string + + // REQUIRED; The schema defined by publisher, where extension consumers should provide settings in a matching schema. + HandlerSchema *string + + // REQUIRED; The operating system this extension supports. + OperatingSystem *string + + // Whether the handler can support multiple extensions. + SupportsMultipleExtensions *bool + + // Whether the extension can be used on xRP VMScaleSets. By default existing extensions are usable on scalesets, but there + // might be cases where a publisher wants to explicitly indicate the extension is + // only enabled for CRP VMs but not VMSS. + VMScaleSetEnabled *bool +} + +// VirtualMachineExtensionInstanceView - The instance view of a virtual machine extension. +type VirtualMachineExtensionInstanceView struct { + // The virtual machine extension name. + Name *string + + // The resource status information. + Statuses []*InstanceViewStatus + + // The resource status information. + Substatuses []*InstanceViewStatus + + // Specifies the type of the extension; an example is "CustomScriptExtension". + Type *string + + // Specifies the version of the script handler. + TypeHandlerVersion *string +} + +// VirtualMachineExtensionProperties - Describes the properties of a Virtual Machine Extension. +type VirtualMachineExtensionProperties struct { + // Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, + // however, the extension will not upgrade minor versions unless redeployed, even + // with this property set to true. + AutoUpgradeMinorVersion *bool + + // Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension + // available. + EnableAutomaticUpgrade *bool + + // How the extension handler should be forced to update even if the extension configuration has not changed. + ForceUpdateTag *string + + // The virtual machine extension instance view. + InstanceView *VirtualMachineExtensionInstanceView + + // The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. + ProtectedSettings any + + // The extensions protected settings that are passed by reference, and consumed from key vault + ProtectedSettingsFromKeyVault *KeyVaultSecretReference + + // Collection of extension names after which this extension needs to be provisioned. + ProvisionAfterExtensions []*string + + // The name of the extension handler publisher. + Publisher *string + + // Json formatted public settings for the extension. + Settings any + + // Indicates whether failures stemming from the extension will be suppressed (Operational failures such as not connecting + // to the VM will not be suppressed regardless of this value). The default is false. + SuppressFailures *bool + + // Specifies the type of the extension; an example is "CustomScriptExtension". + Type *string + + // Specifies the version of the script handler. + TypeHandlerVersion *string + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string +} + +// VirtualMachineExtensionUpdate - Describes a Virtual Machine Extension. +type VirtualMachineExtensionUpdate struct { + // Describes the properties of a Virtual Machine Extension. + Properties *VirtualMachineExtensionUpdateProperties + + // Resource tags + Tags map[string]*string +} + +// VirtualMachineExtensionUpdateProperties - Describes the properties of a Virtual Machine Extension. +type VirtualMachineExtensionUpdateProperties struct { + // Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, + // however, the extension will not upgrade minor versions unless redeployed, even + // with this property set to true. + AutoUpgradeMinorVersion *bool + + // Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension + // available. + EnableAutomaticUpgrade *bool + + // How the extension handler should be forced to update even if the extension configuration has not changed. + ForceUpdateTag *string + + // The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. + ProtectedSettings any + + // The extensions protected settings that are passed by reference, and consumed from key vault + ProtectedSettingsFromKeyVault *KeyVaultSecretReference + + // The name of the extension handler publisher. + Publisher *string + + // Json formatted public settings for the extension. + Settings any + + // Indicates whether failures stemming from the extension will be suppressed (Operational failures such as not connecting + // to the VM will not be suppressed regardless of this value). The default is false. + SuppressFailures *bool + + // Specifies the type of the extension; an example is "CustomScriptExtension". + Type *string + + // Specifies the version of the script handler. + TypeHandlerVersion *string +} + +// VirtualMachineExtensionsListResult - The List Extension operation response +type VirtualMachineExtensionsListResult struct { + // The list of extensions + Value []*VirtualMachineExtension +} + +// VirtualMachineHealthStatus - The health status of the VM. +type VirtualMachineHealthStatus struct { + // READ-ONLY; The health status information for the VM. + Status *InstanceViewStatus +} + +// VirtualMachineIPTag - Contains the IP tag associated with the public IP address. +type VirtualMachineIPTag struct { + // IP tag type. Example: FirstPartyUsage. + IPTagType *string + + // IP tag associated with the public IP. Example: SQL, Storage etc. + Tag *string +} + +// VirtualMachineIdentity - Identity for the virtual machine. +type VirtualMachineIdentity struct { + // The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly + // created identity and a set of user assigned identities. The type 'None' will + // remove any identities from the virtual machine. + Type *ResourceIdentityType + + // The list of user identities associated with the Virtual Machine. 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]*UserAssignedIdentitiesValue + + // READ-ONLY; The principal id of virtual machine identity. This property will only be provided for a system assigned identity. + PrincipalID *string + + // READ-ONLY; The tenant id associated with the virtual machine. This property will only be provided for a system assigned + // identity. + TenantID *string +} + +// VirtualMachineImage - Describes a Virtual Machine Image. +type VirtualMachineImage struct { + // REQUIRED; The supported Azure location of the resource. + Location *string + + // REQUIRED; The name of the resource. + Name *string + + // The extended location of the Virtual Machine. + ExtendedLocation *ExtendedLocation + + // Resource Id + ID *string + + // Describes the properties of a Virtual Machine Image. + Properties *VirtualMachineImageProperties + + // Specifies the tags that are assigned to the virtual machine. For more information about using tags, see Using tags to organize + // your Azure resources + // [https://docs.microsoft.com/azure/azure-resource-manager/resource-group-using-tags.md]. + Tags map[string]*string +} + +// VirtualMachineImageFeature - Specifies additional capabilities supported by the image +type VirtualMachineImageFeature struct { + // The name of the feature. + Name *string + + // The corresponding value for the feature. + Value *string +} + +// VirtualMachineImageProperties - Describes the properties of a Virtual Machine Image. +type VirtualMachineImageProperties struct { + // Specifies the Architecture Type + Architecture *ArchitectureTypes + + // Describes automatic OS upgrade properties on the image. + AutomaticOSUpgradeProperties *AutomaticOSUpgradeProperties + DataDiskImages []*DataDiskImage + + // Specifies disallowed configuration for the VirtualMachine created from the image + Disallowed *DisallowedConfiguration + Features []*VirtualMachineImageFeature + + // Specifies the HyperVGeneration Type + HyperVGeneration *HyperVGenerationTypes + + // Describes image deprecation status properties on the image. + ImageDeprecationStatus *ImageDeprecationStatus + + // Contains the os disk image information. + OSDiskImage *OSDiskImage + + // Used for establishing the purchase context of any 3rd Party artifact through MarketPlace. + Plan *PurchasePlan +} + +// VirtualMachineImageResource - Virtual machine image resource information. +type VirtualMachineImageResource struct { + // REQUIRED; The supported Azure location of the resource. + Location *string + + // REQUIRED; The name of the resource. + Name *string + + // The extended location of the Virtual Machine. + ExtendedLocation *ExtendedLocation + + // Resource Id + ID *string + + // Specifies the tags that are assigned to the virtual machine. For more information about using tags, see Using tags to organize + // your Azure resources + // [https://docs.microsoft.com/azure/azure-resource-manager/resource-group-using-tags.md]. + Tags map[string]*string +} + +// VirtualMachineInstallPatchesParameters - Input for InstallPatches as directly received by the API +type VirtualMachineInstallPatchesParameters struct { + // REQUIRED; Defines when it is acceptable to reboot a VM during a software update operation. + RebootSetting *VMGuestPatchRebootSetting + + // Input for InstallPatches on a Linux VM, as directly received by the API + LinuxParameters *LinuxParameters + + // Specifies the maximum amount of time that the operation will run. It must be an ISO 8601-compliant duration string such + // as PT4H (4 hours) + MaximumDuration *string + + // Input for InstallPatches on a Windows VM, as directly received by the API + WindowsParameters *WindowsParameters +} + +// VirtualMachineInstallPatchesResult - The result summary of an installation operation. +type VirtualMachineInstallPatchesResult struct { + // READ-ONLY; The errors that were encountered during execution of the operation. The details array contains the list of them. + Error *APIError + + // READ-ONLY; The number of patches that were not installed due to the user blocking their installation. + ExcludedPatchCount *int32 + + // READ-ONLY; The number of patches that could not be installed due to some issue. See errors for details. + FailedPatchCount *int32 + + // READ-ONLY; The activity ID of the operation that produced this result. It is used to correlate across CRP and extension + // logs. + InstallationActivityID *string + + // READ-ONLY; The number of patches successfully installed. + InstalledPatchCount *int32 + + // READ-ONLY; Whether the operation ran out of time before it completed all its intended actions. + MaintenanceWindowExceeded *bool + + // READ-ONLY; The number of patches that were detected as available for install, but did not meet the operation's criteria. + NotSelectedPatchCount *int32 + + // READ-ONLY; The patches that were installed during the operation. + Patches []*PatchInstallationDetail + + // READ-ONLY; The number of patches that were identified as meeting the installation criteria, but were not able to be installed. + // Typically this happens when maintenanceWindowExceeded == true. + PendingPatchCount *int32 + + // READ-ONLY; The reboot state of the VM following completion of the operation. + RebootStatus *VMGuestPatchRebootStatus + + // READ-ONLY; The UTC timestamp when the operation began. + StartDateTime *time.Time + + // READ-ONLY; The overall success or failure status of the operation. It remains "InProgress" until the operation completes. + // At that point it will become "Failed", "Succeeded", "Unknown" or "CompletedWithWarnings." + Status *PatchOperationStatus +} + +// VirtualMachineInstanceView - The instance view of a virtual machine. +type VirtualMachineInstanceView struct { + // Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. You + // can easily view the output of your console log. Azure also enables you to see + // a screenshot of the VM from the hypervisor. + BootDiagnostics *BootDiagnosticsInstanceView + + // The computer name assigned to the virtual machine. + ComputerName *string + + // The virtual machine disk information. + Disks []*DiskInstanceView + + // The extensions information. + Extensions []*VirtualMachineExtensionInstanceView + + // Specifies the HyperVGeneration Type associated with a resource + HyperVGeneration *HyperVGenerationType + + // The Maintenance Operation status on the virtual machine. + MaintenanceRedeployStatus *MaintenanceRedeployStatus + + // The Operating System running on the virtual machine. + OSName *string + + // The version of Operating System running on the virtual machine. + OSVersion *string + + // [Preview Feature] The status of virtual machine patch operations. + PatchStatus *VirtualMachinePatchStatus + + // Specifies the fault domain of the virtual machine. + PlatformFaultDomain *int32 + + // Specifies the update domain of the virtual machine. + PlatformUpdateDomain *int32 + + // The Remote desktop certificate thumbprint. + RdpThumbPrint *string + + // The resource status information. + Statuses []*InstanceViewStatus + + // The VM Agent running on the virtual machine. + VMAgent *VirtualMachineAgentInstanceView + + // READ-ONLY; Resource id of the dedicated host, on which the virtual machine is allocated through automatic placement, when + // the virtual machine is associated with a dedicated host group that has automatic + // placement enabled. Minimum api-version: 2020-06-01. + AssignedHost *string + + // READ-ONLY; [Preview Feature] Specifies whether the VM is currently in or out of the Standby Pool. + IsVMInStandbyPool *bool + + // READ-ONLY; The health status for the VM. + VMHealth *VirtualMachineHealthStatus +} + +// VirtualMachineListResult - The List Virtual Machine operation response. +type VirtualMachineListResult struct { + // REQUIRED; The list of virtual machines. + Value []*VirtualMachine + + // The URI to fetch the next page of VMs. Call ListNext() with this URI to fetch the next page of Virtual Machines. + NextLink *string +} + +// VirtualMachineNetworkInterfaceConfiguration - Describes a virtual machine network interface configurations. +type VirtualMachineNetworkInterfaceConfiguration struct { + // REQUIRED; The network interface configuration name. + Name *string + + // Describes a virtual machine network profile's IP configuration. + Properties *VirtualMachineNetworkInterfaceConfigurationProperties +} + +// VirtualMachineNetworkInterfaceConfigurationProperties - Describes a virtual machine network profile's IP configuration. +type VirtualMachineNetworkInterfaceConfigurationProperties struct { + // REQUIRED; Specifies the IP configurations of the network interface. + IPConfigurations []*VirtualMachineNetworkInterfaceIPConfiguration + + // Specifies whether the Auxiliary mode is enabled for the Network Interface resource. + AuxiliaryMode *NetworkInterfaceAuxiliaryMode + + // Specifies whether the Auxiliary sku is enabled for the Network Interface resource. + AuxiliarySKU *NetworkInterfaceAuxiliarySKU + + // The dns settings to be applied on the network interfaces. + DNSSettings *VirtualMachineNetworkInterfaceDNSSettingsConfiguration + + // Specify what happens to the network interface when the VM is deleted + DeleteOption *DeleteOptions + + // Specifies whether the network interface is disabled for tcp state tracking. + DisableTCPStateTracking *bool + DscpConfiguration *SubResource + + // Specifies whether the network interface is accelerated networking-enabled. + EnableAcceleratedNetworking *bool + + // Specifies whether the network interface is FPGA networking-enabled. + EnableFpga *bool + + // Whether IP forwarding enabled on this NIC. + EnableIPForwarding *bool + + // The network security group. + NetworkSecurityGroup *SubResource + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool +} + +// VirtualMachineNetworkInterfaceDNSSettingsConfiguration - Describes a virtual machines network configuration's DNS settings. +type VirtualMachineNetworkInterfaceDNSSettingsConfiguration struct { + // List of DNS servers IP addresses + DNSServers []*string +} + +// VirtualMachineNetworkInterfaceIPConfiguration - Describes a virtual machine network profile's IP configuration. +type VirtualMachineNetworkInterfaceIPConfiguration struct { + // REQUIRED; The IP configuration name. + Name *string + + // Describes a virtual machine network interface IP configuration properties. + Properties *VirtualMachineNetworkInterfaceIPConfigurationProperties +} + +// VirtualMachineNetworkInterfaceIPConfigurationProperties - Describes a virtual machine network interface IP configuration +// properties. +type VirtualMachineNetworkInterfaceIPConfigurationProperties struct { + // Specifies an array of references to backend address pools of application gateways. A virtual machine can reference backend + // address pools of multiple application gateways. Multiple virtual machines + // cannot use the same application gateway. + ApplicationGatewayBackendAddressPools []*SubResource + + // Specifies an array of references to application security group. + ApplicationSecurityGroups []*SubResource + + // Specifies an array of references to backend address pools of load balancers. A virtual machine can reference backend address + // pools of one public and one internal load balancer. [Multiple virtual + // machines cannot use the same basic sku load balancer]. + LoadBalancerBackendAddressPools []*SubResource + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool + + // Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default + // is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. + PrivateIPAddressVersion *IPVersions + + // The publicIPAddressConfiguration. + PublicIPAddressConfiguration *VirtualMachinePublicIPAddressConfiguration + + // Specifies the identifier of the subnet. + Subnet *SubResource +} + +// VirtualMachinePatchStatus - The status of virtual machine patch operations. +type VirtualMachinePatchStatus struct { + // The available patch summary of the latest assessment operation for the virtual machine. + AvailablePatchSummary *AvailablePatchSummary + + // The installation summary of the latest installation operation for the virtual machine. + LastPatchInstallationSummary *LastPatchInstallationSummary + + // READ-ONLY; The enablement status of the specified patchMode + ConfigurationStatuses []*InstanceViewStatus +} + +// VirtualMachineProperties - Describes the properties of a Virtual Machine. +type VirtualMachineProperties struct { + // Specifies additional capabilities enabled or disabled on the virtual machine. + AdditionalCapabilities *AdditionalCapabilities + + // Specifies the gallery applications that should be made available to the VM/VMSS. + ApplicationProfile *ApplicationProfile + + // Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified + // in the same availability set are allocated to different nodes to maximize + // availability. For more information about availability sets, see Availability sets overview [https://docs.microsoft.com/azure/virtual-machines/availability-set-overview]. + // For more information on Azure + // planned maintenance, see Maintenance and updates for Virtual Machines in Azure [https://docs.microsoft.com/azure/virtual-machines/maintenance-and-updates]. + // Currently, a VM can only be added to + // availability set at creation time. The availability set to which the VM is being added should be under the same resource + // group as the availability set resource. An existing VM cannot be added to an + // availability set. This property cannot exist along with a non-null properties.virtualMachineScaleSet reference. + AvailabilitySet *SubResource + + // Specifies the billing related details of a Azure Spot virtual machine. Minimum api-version: 2019-03-01. + BillingProfile *BillingProfile + + // Specifies information about the capacity reservation that is used to allocate virtual machine. Minimum api-version: 2021-04-01. + CapacityReservation *CapacityReservationProfile + + // Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15. + DiagnosticsProfile *DiagnosticsProfile + + // Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. For Azure Spot virtual machines, + // both 'Deallocate' and 'Delete' are supported and the minimum api-version is + // 2019-03-01. For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview. + EvictionPolicy *VirtualMachineEvictionPolicyTypes + + // Specifies the time alloted for all extensions to start. The time duration should be between 15 minutes and 120 minutes + // (inclusive) and should be specified in ISO 8601 format. The default value is 90 + // minutes (PT1H30M). Minimum api-version: 2020-06-01. + ExtensionsTimeBudget *string + + // Specifies the hardware settings for the virtual machine. + HardwareProfile *HardwareProfile + + // Specifies information about the dedicated host that the virtual machine resides in. Minimum api-version: 2018-10-01. + Host *SubResource + + // Specifies information about the dedicated host group that the virtual machine resides in. Note: User cannot specify both + // host and hostGroup properties. Minimum api-version: 2020-06-01. + HostGroup *SubResource + + // Specifies that the image or disk that is being used was licensed on-premises. + // Possible values for Windows Server operating system are: + // WindowsClient + // WindowsServer + // Possible values for Linux Server operating system are: + // RHELBYOS (for RHEL) + // SLESBYOS (for SUSE) + // For more information, see Azure Hybrid Use Benefit for Windows Server [https://docs.microsoft.com/azure/virtual-machines/windows/hybrid-use-benefit-licensing] + // Azure Hybrid Use Benefit for Linux Server [https://docs.microsoft.com/azure/virtual-machines/linux/azure-hybrid-benefit-linux] + // Minimum api-version: 2015-06-15 + LicenseType *string + + // Specifies the network interfaces of the virtual machine. + NetworkProfile *NetworkProfile + + // Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed + // once VM is provisioned. + OSProfile *OSProfile + + // Specifies the scale set logical fault domain into which the Virtual Machine will be created. By default, the Virtual Machine + // will by automatically assigned to a fault domain that best maintains + // balance across available fault domains. This is applicable only if the 'virtualMachineScaleSet' property of this Virtual + // Machine is set. The Virtual Machine Scale Set that is referenced, must have + // 'platformFaultDomainCount' greater than 1. This property cannot be updated once the Virtual Machine is created. Fault domain + // assignment can be viewed in the Virtual Machine Instance View. Minimum + // apiâ€version: 2020â€12â€01. + PlatformFaultDomain *int32 + + // Specifies the priority for the virtual machine. Minimum api-version: 2019-03-01 + Priority *VirtualMachinePriorityTypes + + // Specifies information about the proximity placement group that the virtual machine should be assigned to. Minimum api-version: + // 2018-04-01. + ProximityPlacementGroup *SubResource + + // Specifies Scheduled Event related configurations. + ScheduledEventsProfile *ScheduledEventsProfile + + // Specifies the Security related profile settings for the virtual machine. + SecurityProfile *SecurityProfile + + // Specifies the storage settings for the virtual machine disks. + StorageProfile *StorageProfile + + // UserData for the VM, which must be base-64 encoded. Customer should not pass any secrets in here. Minimum api-version: + // 2021-03-01. + UserData *string + + // Specifies information about the virtual machine scale set that the virtual machine should be assigned to. Virtual machines + // specified in the same virtual machine scale set are allocated to different + // nodes to maximize availability. Currently, a VM can only be added to virtual machine scale set at creation time. An existing + // VM cannot be added to a virtual machine scale set. This property cannot + // exist along with a non-null properties.availabilitySet reference. Minimum apiâ€version: 2019â€03â€01. + VirtualMachineScaleSet *SubResource + + // READ-ONLY; The virtual machine instance view. + InstanceView *VirtualMachineInstanceView + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string + + // READ-ONLY; Specifies the time at which the Virtual Machine resource was created. Minimum api-version: 2021-11-01. + TimeCreated *time.Time + + // READ-ONLY; Specifies the VM unique ID which is a 128-bits identifier that is encoded and stored in all Azure IaaS VMs SMBIOS + // and can be read using platform BIOS commands. + VMID *string +} + +// VirtualMachinePublicIPAddressConfiguration - Describes a virtual machines IP Configuration's PublicIPAddress configuration +type VirtualMachinePublicIPAddressConfiguration struct { + // REQUIRED; The publicIP address configuration name. + Name *string + + // Describes a virtual machines IP Configuration's PublicIPAddress configuration + Properties *VirtualMachinePublicIPAddressConfigurationProperties + + // Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible. + SKU *PublicIPAddressSKU +} + +// VirtualMachinePublicIPAddressConfigurationProperties - Describes a virtual machines IP Configuration's PublicIPAddress +// configuration +type VirtualMachinePublicIPAddressConfigurationProperties struct { + // The dns settings to be applied on the publicIP addresses . + DNSSettings *VirtualMachinePublicIPAddressDNSSettingsConfiguration + + // Specify what happens to the public IP address when the VM is deleted + DeleteOption *DeleteOptions + + // The list of IP tags associated with the public IP address. + IPTags []*VirtualMachineIPTag + + // The idle timeout of the public IP address. + IdleTimeoutInMinutes *int32 + + // Available from Api-Version 2019-07-01 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default + // is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. + PublicIPAddressVersion *IPVersions + + // Specify the public IP allocation type + PublicIPAllocationMethod *PublicIPAllocationMethod + + // The PublicIPPrefix from which to allocate publicIP addresses. + PublicIPPrefix *SubResource +} + +// VirtualMachinePublicIPAddressDNSSettingsConfiguration - Describes a virtual machines network configuration's DNS settings. +type VirtualMachinePublicIPAddressDNSSettingsConfiguration struct { + // REQUIRED; The Domain name label prefix of the PublicIPAddress resources that will be created. The generated name label + // is the concatenation of the domain name label and vm network profile unique ID. + DomainNameLabel *string + + // The Domain name label scope of the PublicIPAddress resources that will be created. The generated name label is the concatenation + // of the hashed domain name label with policy according to the domain + // name label scope and vm network profile unique ID. + DomainNameLabelScope *DomainNameLabelScopeTypes +} + +// VirtualMachineReimageParameters - Parameters for Reimaging Virtual Machine. NOTE: Virtual Machine OS disk will always be +// reimaged +type VirtualMachineReimageParameters struct { + // Specifies in decimal number, the version the OS disk should be reimaged to. If exact version is not provided, the OS disk + // is reimaged to the existing version of OS Disk. + ExactVersion *string + + // Specifies information required for reimaging the non-ephemeral OS disk. + OSProfile *OSProfileProvisioningData + + // Specifies whether to reimage temp disk. Default value: false. Note: This temp disk reimage parameter is only supported + // for VM/VMSS with Ephemeral OS disk. + TempDisk *bool +} + +// VirtualMachineRunCommand - Describes a Virtual Machine run command. +type VirtualMachineRunCommand struct { + // REQUIRED; Resource location + Location *string + + // Describes the properties of a Virtual Machine run command. + Properties *VirtualMachineRunCommandProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineRunCommandInstanceView - The instance view of a virtual machine run command. +type VirtualMachineRunCommandInstanceView struct { + // Script end time. + EndTime *time.Time + + // Script error stream. + Error *string + + // Communicate script configuration errors or execution messages. + ExecutionMessage *string + + // Script execution status. + ExecutionState *ExecutionState + + // Exit code returned from script execution. + ExitCode *int32 + + // Script output stream. + Output *string + + // Script start time. + StartTime *time.Time + + // The resource status information. + Statuses []*InstanceViewStatus +} + +// VirtualMachineRunCommandProperties - Describes the properties of a Virtual Machine run command. +type VirtualMachineRunCommandProperties struct { + // Optional. If set to true, provisioning will complete as soon as the script starts and will not wait for script to complete. + AsyncExecution *bool + + // User-assigned managed identity that has access to errorBlobUri storage blob. Use an empty object in case of system-assigned + // identity. Make sure managed identity has been given access to blob's + // container with 'Storage Blob Data Contributor' role assignment. In case of user-assigned identity, make sure you add it + // under VM's identity. For more info on managed identity and Run Command, refer + // https://aka.ms/ManagedIdentity and https://aka.ms/RunCommandManaged + ErrorBlobManagedIdentity *RunCommandManagedIdentity + + // Specifies the Azure storage blob where script error stream will be uploaded. Use a SAS URI with read, append, create, write + // access OR use managed identity to provide the VM access to the blob. Refer + // errorBlobManagedIdentity parameter. + ErrorBlobURI *string + + // User-assigned managed identity that has access to outputBlobUri storage blob. Use an empty object in case of system-assigned + // identity. Make sure managed identity has been given access to blob's + // container with 'Storage Blob Data Contributor' role assignment. In case of user-assigned identity, make sure you add it + // under VM's identity. For more info on managed identity and Run Command, refer + // https://aka.ms/ManagedIdentity and https://aka.ms/RunCommandManaged + OutputBlobManagedIdentity *RunCommandManagedIdentity + + // Specifies the Azure storage blob where script output stream will be uploaded. Use a SAS URI with read, append, create, + // write access OR use managed identity to provide the VM access to the blob. Refer + // outputBlobManagedIdentity parameter. + OutputBlobURI *string + + // The parameters used by the script. + Parameters []*RunCommandInputParameter + + // The parameters used by the script. + ProtectedParameters []*RunCommandInputParameter + + // Specifies the user account password on the VM when executing the run command. + RunAsPassword *string + + // Specifies the user account on the VM when executing the run command. + RunAsUser *string + + // The source of the run command script. + Source *VirtualMachineRunCommandScriptSource + + // The timeout in seconds to execute the run command. + TimeoutInSeconds *int32 + + // Optional. If set to true, any failure in the script will fail the deployment and ProvisioningState will be marked as Failed. + // If set to false, ProvisioningState would only reflect whether the run + // command was run or not by the extensions platform, it would not indicate whether script failed in case of script failures. + // See instance view of run command in case of script failures to see + // executionMessage, output, error: https://aka.ms/runcommandmanaged#get-execution-status-and-results + TreatFailureAsDeploymentFailure *bool + + // READ-ONLY; The virtual machine run command instance view. + InstanceView *VirtualMachineRunCommandInstanceView + + // READ-ONLY; The provisioning state, which only appears in the response. If treatFailureAsDeploymentFailure set to true, + // any failure in the script will fail the deployment and ProvisioningState will be marked as + // Failed. If treatFailureAsDeploymentFailure set to false, ProvisioningState would only reflect whether the run command was + // run or not by the extensions platform, it would not indicate whether script + // failed in case of script failures. See instance view of run command in case of script failures to see executionMessage, + // output, error: https://aka.ms/runcommandmanaged#get-execution-status-and-results + ProvisioningState *string +} + +// VirtualMachineRunCommandScriptSource - Describes the script sources for run command. Use only one of script, scriptUri, +// commandId. +type VirtualMachineRunCommandScriptSource struct { + // Specifies a commandId of predefined built-in script. + CommandID *string + + // Specifies the script content to be executed on the VM. + Script *string + + // Specifies the script download location. It can be either SAS URI of an Azure storage blob with read access or public URI. + ScriptURI *string + + // User-assigned managed identity that has access to scriptUri in case of Azure storage blob. Use an empty object in case + // of system-assigned identity. Make sure the Azure storage blob exists, and managed + // identity has been given access to blob's container with 'Storage Blob Data Reader' role assignment. In case of user-assigned + // identity, make sure you add it under VM's identity. For more info on + // managed identity and Run Command, refer https://aka.ms/ManagedIdentity and https://aka.ms/RunCommandManaged. + ScriptURIManagedIdentity *RunCommandManagedIdentity +} + +// VirtualMachineRunCommandUpdate - Describes a Virtual Machine run command. +type VirtualMachineRunCommandUpdate struct { + // Describes the properties of a Virtual Machine run command. + Properties *VirtualMachineRunCommandProperties + + // Resource tags + Tags map[string]*string +} + +// VirtualMachineRunCommandsListResult - The List run command operation response +type VirtualMachineRunCommandsListResult struct { + // REQUIRED; The list of run commands + Value []*VirtualMachineRunCommand + + // The uri to fetch the next page of run commands. + NextLink *string +} + +// VirtualMachineScaleSet - Describes a Virtual Machine Scale Set. +type VirtualMachineScaleSet struct { + // REQUIRED; Resource location + Location *string + + // The extended location of the Virtual Machine Scale Set. + ExtendedLocation *ExtendedLocation + + // The identity of the virtual machine scale set, if configured. + Identity *VirtualMachineScaleSetIdentity + + // Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace + // images. Before you can use a marketplace image from an API, you must + // enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click + // Want to deploy programmatically, Get Started ->. Enter any required + // information and then click Save. + Plan *Plan + + // Describes the properties of a Virtual Machine Scale Set. + Properties *VirtualMachineScaleSetProperties + + // The virtual machine scale set sku. + SKU *SKU + + // Resource tags + Tags map[string]*string + + // The virtual machine scale set zones. NOTE: Availability zones can only be set when you create the scale set + Zones []*string + + // READ-ONLY; Etag is property returned in Create/Update/Get response of the VMSS, so that customer can supply it in the header + // to ensure optimistic updates + Etag *string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineScaleSetDataDisk - Describes a virtual machine scale set data disk. +type VirtualMachineScaleSetDataDisk struct { + // REQUIRED; The create option. + CreateOption *DiskCreateOptionTypes + + // REQUIRED; Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and + // therefore must be unique for each data disk attached to a VM. + Lun *int32 + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default values are: None for Standard + // storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies whether data disk should be deleted or detached upon VMSS Flex deletion (This feature is available for VMSS with + // Flexible OrchestrationMode only). + // Possible values: + // Delete If this value is used, the data disk is deleted when the VMSS Flex VM is deleted. + // Detach If this value is used, the data disk is retained after VMSS Flex VM is deleted. + // The default value is set to Delete. + DeleteOption *DiskDeleteOptionTypes + + // Specifies the Read-Write IOPS for the managed disk. Should be used only when StorageAccountType is UltraSSD_LRS. If not + // specified, a default value would be assigned based on diskSizeGB. + DiskIOPSReadWrite *int64 + + // Specifies the bandwidth in MB per second for the managed disk. Should be used only when StorageAccountType is UltraSSD_LRS. + // If not specified, a default value would be assigned based on diskSizeGB. + DiskMBpsReadWrite *int64 + + // Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a + // virtual machine image. The property diskSizeGB is the number of bytes x 1024^3 + // for the disk and the value cannot be larger than 1023. + DiskSizeGB *int32 + + // The managed disk parameters. + ManagedDisk *VirtualMachineScaleSetManagedDiskParameters + + // The disk name. + Name *string + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool +} + +// VirtualMachineScaleSetExtension - Describes a Virtual Machine Scale Set Extension. +type VirtualMachineScaleSetExtension struct { + // The name of the extension. + Name *string + + // Describes the properties of a Virtual Machine Scale Set Extension. + Properties *VirtualMachineScaleSetExtensionProperties + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineScaleSetExtensionListResult - The List VM scale set extension operation response. +type VirtualMachineScaleSetExtensionListResult struct { + // REQUIRED; The list of VM scale set extensions. + Value []*VirtualMachineScaleSetExtension + + // The uri to fetch the next page of VM scale set extensions. Call ListNext() with this to fetch the next page of VM scale + // set extensions. + NextLink *string +} + +// VirtualMachineScaleSetExtensionProfile - Describes a virtual machine scale set extension profile. +type VirtualMachineScaleSetExtensionProfile struct { + // The virtual machine scale set child extension resources. + Extensions []*VirtualMachineScaleSetExtension + + // Specifies the time alloted for all extensions to start. The time duration should be between 15 minutes and 120 minutes + // (inclusive) and should be specified in ISO 8601 format. The default value is 90 + // minutes (PT1H30M). Minimum api-version: 2020-06-01. + ExtensionsTimeBudget *string +} + +// VirtualMachineScaleSetExtensionProperties - Describes the properties of a Virtual Machine Scale Set Extension. +type VirtualMachineScaleSetExtensionProperties struct { + // Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, + // however, the extension will not upgrade minor versions unless redeployed, even + // with this property set to true. + AutoUpgradeMinorVersion *bool + + // Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension + // available. + EnableAutomaticUpgrade *bool + + // If a value is provided and is different from the previous value, the extension handler will be forced to update even if + // the extension configuration has not changed. + ForceUpdateTag *string + + // The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. + ProtectedSettings any + + // The extensions protected settings that are passed by reference, and consumed from key vault + ProtectedSettingsFromKeyVault *KeyVaultSecretReference + + // Collection of extension names after which this extension needs to be provisioned. + ProvisionAfterExtensions []*string + + // The name of the extension handler publisher. + Publisher *string + + // Json formatted public settings for the extension. + Settings any + + // Indicates whether failures stemming from the extension will be suppressed (Operational failures such as not connecting + // to the VM will not be suppressed regardless of this value). The default is false. + SuppressFailures *bool + + // Specifies the type of the extension; an example is "CustomScriptExtension". + Type *string + + // Specifies the version of the script handler. + TypeHandlerVersion *string + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string +} + +// VirtualMachineScaleSetExtensionUpdate - Describes a Virtual Machine Scale Set Extension. +type VirtualMachineScaleSetExtensionUpdate struct { + // Describes the properties of a Virtual Machine Scale Set Extension. + Properties *VirtualMachineScaleSetExtensionProperties + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; The name of the extension. + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineScaleSetHardwareProfile - Specifies the hardware settings for the virtual machine scale set. +type VirtualMachineScaleSetHardwareProfile struct { + // Specifies the properties for customizing the size of the virtual machine. Minimum api-version: 2021-11-01. Please follow + // the instructions in VM Customization [https://aka.ms/vmcustomization] for more + // details. + VMSizeProperties *VMSizeProperties +} + +// VirtualMachineScaleSetIPConfiguration - Describes a virtual machine scale set network profile's IP configuration. +type VirtualMachineScaleSetIPConfiguration struct { + // REQUIRED; The IP configuration name. + Name *string + + // Describes a virtual machine scale set network profile's IP configuration properties. + Properties *VirtualMachineScaleSetIPConfigurationProperties +} + +// VirtualMachineScaleSetIPConfigurationProperties - Describes a virtual machine scale set network profile's IP configuration +// properties. +type VirtualMachineScaleSetIPConfigurationProperties struct { + // Specifies an array of references to backend address pools of application gateways. A scale set can reference backend address + // pools of multiple application gateways. Multiple scale sets cannot use the + // same application gateway. + ApplicationGatewayBackendAddressPools []*SubResource + + // Specifies an array of references to application security group. + ApplicationSecurityGroups []*SubResource + + // Specifies an array of references to backend address pools of load balancers. A scale set can reference backend address + // pools of one public and one internal load balancer. Multiple scale sets cannot + // use the same basic sku load balancer. + LoadBalancerBackendAddressPools []*SubResource + + // Specifies an array of references to inbound Nat pools of the load balancers. A scale set can reference inbound nat pools + // of one public and one internal load balancer. Multiple scale sets cannot use + // the same basic sku load balancer. + LoadBalancerInboundNatPools []*SubResource + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool + + // Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default + // is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. + PrivateIPAddressVersion *IPVersion + + // The publicIPAddressConfiguration. + PublicIPAddressConfiguration *VirtualMachineScaleSetPublicIPAddressConfiguration + + // Specifies the identifier of the subnet. + Subnet *APIEntityReference +} + +// VirtualMachineScaleSetIPTag - Contains the IP tag associated with the public IP address. +type VirtualMachineScaleSetIPTag struct { + // IP tag type. Example: FirstPartyUsage. + IPTagType *string + + // IP tag associated with the public IP. Example: SQL, Storage etc. + Tag *string +} + +// VirtualMachineScaleSetIdentity - Identity for the virtual machine scale set. +type VirtualMachineScaleSetIdentity struct { + // The type of identity used for the virtual machine scale set. The type 'SystemAssigned, UserAssigned' includes both an implicitly + // created identity and a set of user assigned identities. The type 'None' + // will remove any identities from the virtual machine scale set. + Type *ResourceIdentityType + + // The list of user identities associated with the virtual machine scale set. 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]*UserAssignedIdentitiesValue + + // READ-ONLY; The principal id of virtual machine scale set identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant id associated with the virtual machine scale set. This property will only be provided for a system + // assigned identity. + TenantID *string +} + +// VirtualMachineScaleSetInstanceView - The instance view of a virtual machine scale set. +type VirtualMachineScaleSetInstanceView struct { + // The resource status information. + Statuses []*InstanceViewStatus + + // READ-ONLY; The extensions information. + Extensions []*VirtualMachineScaleSetVMExtensionsSummary + + // READ-ONLY; The orchestration services information. + OrchestrationServices []*OrchestrationServiceSummary + + // READ-ONLY; The instance view status summary for the virtual machine scale set. + VirtualMachine *VirtualMachineScaleSetInstanceViewStatusesSummary +} + +// VirtualMachineScaleSetInstanceViewStatusesSummary - Instance view statuses summary for virtual machines of a virtual machine +// scale set. +type VirtualMachineScaleSetInstanceViewStatusesSummary struct { + // READ-ONLY; The extensions information. + StatusesSummary []*VirtualMachineStatusCodeCount +} + +// VirtualMachineScaleSetListOSUpgradeHistory - List of Virtual Machine Scale Set OS Upgrade History operation response. +type VirtualMachineScaleSetListOSUpgradeHistory struct { + // REQUIRED; The list of OS upgrades performed on the virtual machine scale set. + Value []*UpgradeOperationHistoricalStatusInfo + + // The uri to fetch the next page of OS Upgrade History. Call ListNext() with this to fetch the next page of history of upgrades. + NextLink *string +} + +// VirtualMachineScaleSetListResult - The List Virtual Machine operation response. +type VirtualMachineScaleSetListResult struct { + // REQUIRED; The list of virtual machine scale sets. + Value []*VirtualMachineScaleSet + + // The uri to fetch the next page of Virtual Machine Scale Sets. Call ListNext() with this to fetch the next page of VMSS. + NextLink *string +} + +// VirtualMachineScaleSetListSKUsResult - The Virtual Machine Scale Set List Skus operation response. +type VirtualMachineScaleSetListSKUsResult struct { + // REQUIRED; The list of skus available for the virtual machine scale set. + Value []*VirtualMachineScaleSetSKU + + // The uri to fetch the next page of Virtual Machine Scale Set Skus. Call ListNext() with this to fetch the next page of VMSS + // Skus. + NextLink *string +} + +// VirtualMachineScaleSetListWithLinkResult - The List Virtual Machine operation response. +type VirtualMachineScaleSetListWithLinkResult struct { + // REQUIRED; The list of virtual machine scale sets. + Value []*VirtualMachineScaleSet + + // The uri to fetch the next page of Virtual Machine Scale Sets. Call ListNext() with this to fetch the next page of Virtual + // Machine Scale Sets. + NextLink *string +} + +// VirtualMachineScaleSetManagedDiskParameters - Describes the parameters of a ScaleSet managed disk. +type VirtualMachineScaleSetManagedDiskParameters struct { + // Specifies the customer managed disk encryption set resource id for the managed disk. + DiskEncryptionSet *DiskEncryptionSetParameters + + // Specifies the security profile for the managed disk. + SecurityProfile *VMDiskSecurityProfile + + // Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot + // be used with OS Disk. + StorageAccountType *StorageAccountTypes +} + +// VirtualMachineScaleSetNetworkConfiguration - Describes a virtual machine scale set network profile's network configurations. +type VirtualMachineScaleSetNetworkConfiguration struct { + // REQUIRED; The network configuration name. + Name *string + + // Describes a virtual machine scale set network profile's IP configuration. + Properties *VirtualMachineScaleSetNetworkConfigurationProperties +} + +// VirtualMachineScaleSetNetworkConfigurationDNSSettings - Describes a virtual machines scale sets network configuration's +// DNS settings. +type VirtualMachineScaleSetNetworkConfigurationDNSSettings struct { + // List of DNS servers IP addresses + DNSServers []*string +} + +// VirtualMachineScaleSetNetworkConfigurationProperties - Describes a virtual machine scale set network profile's IP configuration. +type VirtualMachineScaleSetNetworkConfigurationProperties struct { + // REQUIRED; Specifies the IP configurations of the network interface. + IPConfigurations []*VirtualMachineScaleSetIPConfiguration + + // Specifies whether the Auxiliary mode is enabled for the Network Interface resource. + AuxiliaryMode *NetworkInterfaceAuxiliaryMode + + // Specifies whether the Auxiliary sku is enabled for the Network Interface resource. + AuxiliarySKU *NetworkInterfaceAuxiliarySKU + + // The dns settings to be applied on the network interfaces. + DNSSettings *VirtualMachineScaleSetNetworkConfigurationDNSSettings + + // Specify what happens to the network interface when the VM is deleted + DeleteOption *DeleteOptions + + // Specifies whether the network interface is disabled for tcp state tracking. + DisableTCPStateTracking *bool + + // Specifies whether the network interface is accelerated networking-enabled. + EnableAcceleratedNetworking *bool + + // Specifies whether the network interface is FPGA networking-enabled. + EnableFpga *bool + + // Whether IP forwarding enabled on this NIC. + EnableIPForwarding *bool + + // The network security group. + NetworkSecurityGroup *SubResource + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool +} + +// VirtualMachineScaleSetNetworkProfile - Describes a virtual machine scale set network profile. +type VirtualMachineScaleSetNetworkProfile struct { + // A reference to a load balancer probe used to determine the health of an instance in the virtual machine scale set. The + // reference will be in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. + HealthProbe *APIEntityReference + + // specifies the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations + // for Virtual Machine Scale Set with orchestration mode 'Flexible' + NetworkAPIVersion *NetworkAPIVersion + + // The list of network configurations. + NetworkInterfaceConfigurations []*VirtualMachineScaleSetNetworkConfiguration +} + +// VirtualMachineScaleSetOSDisk - Describes a virtual machine scale set operating system disk. +type VirtualMachineScaleSetOSDisk struct { + // REQUIRED; Specifies how the virtual machines in the scale set should be created. The only allowed value is: FromImage. + // This value is used when you are using an image to create the virtual machine. If you are + // using a platform image, you also use the imageReference element described above. If you are using a marketplace image, + // you also use the plan element previously described. + CreateOption *DiskCreateOptionTypes + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default values are: None for Standard + // storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies whether OS Disk should be deleted or detached upon VMSS Flex deletion (This feature is available for VMSS with + // Flexible OrchestrationMode only). + // Possible values: + // Delete If this value is used, the OS disk is deleted when VMSS Flex VM is deleted. + // Detach If this value is used, the OS disk is retained after VMSS Flex VM is deleted. + // The default value is set to Delete. For an Ephemeral OS Disk, the default value is set to Delete. User cannot change the + // delete option for Ephemeral OS Disk. + DeleteOption *DiskDeleteOptionTypes + + // Specifies the ephemeral disk Settings for the operating system disk used by the virtual machine scale set. + DiffDiskSettings *DiffDiskSettings + + // Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a + // virtual machine image. The property 'diskSizeGB' is the number of bytes x 1024^3 + // for the disk and the value cannot be larger than 1023. + DiskSizeGB *int32 + + // Specifies information about the unmanaged user image to base the scale set on. + Image *VirtualHardDisk + + // The managed disk parameters. + ManagedDisk *VirtualMachineScaleSetManagedDiskParameters + + // The disk name. + Name *string + + // This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or + // a specialized VHD. Possible values are: Windows, Linux. + OSType *OperatingSystemTypes + + // Specifies the container urls that are used to store operating system disks for the scale set. + VhdContainers []*string + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool +} + +// VirtualMachineScaleSetOSProfile - Describes a virtual machine scale set OS profile. +type VirtualMachineScaleSetOSProfile struct { + // Specifies the password of the administrator account. + // Minimum-length (Windows): 8 characters + // Minimum-length (Linux): 6 characters + // Max-length (Windows): 123 characters + // Max-length (Linux): 72 characters + // Complexity requirements: 3 out of 4 conditions below need to be fulfilled + // Has lower characters + // Has upper characters + // Has a digit + // Has a special character (Regex match [\W_]) + // Disallowed values: "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", + // "Password22", "iloveyou!" + // For resetting the password, see How to reset the Remote Desktop service or its login password in a Windows VM [https://docs.microsoft.com/troubleshoot/azure/virtual-machines/reset-rdp] + // For resetting root password, see Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension + // [https://docs.microsoft.com/troubleshoot/azure/virtual-machines/troubleshoot-ssh-connection] + AdminPassword *string + + // Specifies the name of the administrator account. + // Windows-only restriction: Cannot end in "." + // Disallowed values: "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", + // "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", + // "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". + // Minimum-length (Linux): 1 character + // Max-length (Linux): 64 characters + // Max-length (Windows): 20 characters + AdminUsername *string + + // Specifies whether extension operations should be allowed on the virtual machine scale set. This may only be set to False + // when no extensions are present on the virtual machine scale set. + AllowExtensionOperations *bool + + // Specifies the computer name prefix for all of the virtual machines in the scale set. Computer name prefixes must be 1 to + // 15 characters long. + ComputerNamePrefix *string + + // Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved + // as a file on the Virtual Machine. The maximum length of the binary array is + // 65535 bytes. For using cloud-init for your VM, see Using cloud-init to customize a Linux VM during creation [https://docs.microsoft.com/azure/virtual-machines/linux/using-cloud-init] + CustomData *string + + // Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux distributions, see + // Linux on Azure-Endorsed Distributions + // [https://docs.microsoft.com/azure/virtual-machines/linux/endorsed-distros]. + LinuxConfiguration *LinuxConfiguration + + // Optional property which must either be set to True or omitted. + RequireGuestProvisionSignal *bool + + // Specifies set of certificates that should be installed onto the virtual machines in the scale set. To install certificates + // on a virtual machine it is recommended to use the Azure Key Vault virtual + // machine extension for Linux [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux] or the Azure + // Key Vault virtual machine extension for Windows + // [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows]. + Secrets []*VaultSecretGroup + + // Specifies Windows operating system settings on the virtual machine. + WindowsConfiguration *WindowsConfiguration +} + +// VirtualMachineScaleSetProperties - Describes the properties of a Virtual Machine Scale Set. +type VirtualMachineScaleSetProperties struct { + // Specifies additional capabilities enabled or disabled on the Virtual Machines in the Virtual Machine Scale Set. For instance: + // whether the Virtual Machines have the capability to support attaching + // managed data disks with UltraSSD_LRS storage account type. + AdditionalCapabilities *AdditionalCapabilities + + // Policy for automatic repairs. + AutomaticRepairsPolicy *AutomaticRepairsPolicy + + // Optional property which must either be set to True or omitted. + ConstrainedMaximumCapacity *bool + + // When Overprovision is enabled, extensions are launched only on the requested number of VMs which are finally kept. This + // property will hence ensure that the extensions do not run on the extra + // overprovisioned VMs. + DoNotRunExtensionsOnOverprovisionedVMs *bool + + // Specifies information about the dedicated host group that the virtual machine scale set resides in. Minimum api-version: + // 2020-06-01. + HostGroup *SubResource + + // Specifies the orchestration mode for the virtual machine scale set. + OrchestrationMode *OrchestrationMode + + // Specifies whether the Virtual Machine Scale Set should be overprovisioned. + Overprovision *bool + + // Fault Domain count for each placement group. + PlatformFaultDomainCount *int32 + + // Specifies the desired targets for mixing Spot and Regular priority VMs within the same VMSS Flex instance. + PriorityMixPolicy *PriorityMixPolicy + + // Specifies information about the proximity placement group that the virtual machine scale set should be assigned to. Minimum + // api-version: 2018-04-01. + ProximityPlacementGroup *SubResource + + // Policy for Resiliency + ResiliencyPolicy *ResiliencyPolicy + + // Specifies the policies applied when scaling in Virtual Machines in the Virtual Machine Scale Set. + ScaleInPolicy *ScaleInPolicy + + // When true this limits the scale set to a single placement group, of max size 100 virtual machines. NOTE: If singlePlacementGroup + // is true, it may be modified to false. However, if singlePlacementGroup + // is false, it may not be modified to true. + SinglePlacementGroup *bool + + // Specifies the Spot Restore properties for the virtual machine scale set. + SpotRestorePolicy *SpotRestorePolicy + + // The upgrade policy. + UpgradePolicy *UpgradePolicy + + // The virtual machine profile. + VirtualMachineProfile *VirtualMachineScaleSetVMProfile + + // Whether to force strictly even Virtual Machine distribution cross x-zones in case there is zone outage. zoneBalance property + // can only be set if the zones property of the scale set contains more than + // one zone. If there are no zones or only one zone specified, then zoneBalance property should not be set. + ZoneBalance *bool + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string + + // READ-ONLY; Specifies the time at which the Virtual Machine Scale Set resource was created. Minimum api-version: 2021-11-01. + TimeCreated *time.Time + + // READ-ONLY; Specifies the ID which uniquely identifies a Virtual Machine Scale Set. + UniqueID *string +} + +// VirtualMachineScaleSetPublicIPAddressConfiguration - Describes a virtual machines scale set IP Configuration's PublicIPAddress +// configuration +type VirtualMachineScaleSetPublicIPAddressConfiguration struct { + // REQUIRED; The publicIP address configuration name. + Name *string + + // Describes a virtual machines scale set IP Configuration's PublicIPAddress configuration + Properties *VirtualMachineScaleSetPublicIPAddressConfigurationProperties + + // Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible. + SKU *PublicIPAddressSKU +} + +// VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings - Describes a virtual machines scale sets network configuration's +// DNS settings. +type VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings struct { + // REQUIRED; The Domain name label.The concatenation of the domain name label and vm index will be the domain name labels + // of the PublicIPAddress resources that will be created + DomainNameLabel *string + + // The Domain name label scope.The concatenation of the hashed domain name label that generated according to the policy from + // domain name label scope and vm index will be the domain name labels of the + // PublicIPAddress resources that will be created + DomainNameLabelScope *DomainNameLabelScopeTypes +} + +// VirtualMachineScaleSetPublicIPAddressConfigurationProperties - Describes a virtual machines scale set IP Configuration's +// PublicIPAddress configuration +type VirtualMachineScaleSetPublicIPAddressConfigurationProperties struct { + // The dns settings to be applied on the publicIP addresses . + DNSSettings *VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings + + // Specify what happens to the public IP when the VM is deleted + DeleteOption *DeleteOptions + + // The list of IP tags associated with the public IP address. + IPTags []*VirtualMachineScaleSetIPTag + + // The idle timeout of the public IP address. + IdleTimeoutInMinutes *int32 + + // Available from Api-Version 2019-07-01 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default + // is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. + PublicIPAddressVersion *IPVersion + + // The PublicIPPrefix from which to allocate publicIP addresses. + PublicIPPrefix *SubResource +} + +// VirtualMachineScaleSetReimageParameters - Describes a Virtual Machine Scale Set VM Reimage Parameters. +type VirtualMachineScaleSetReimageParameters struct { + // Specifies in decimal number, the version the OS disk should be reimaged to. If exact version is not provided, the OS disk + // is reimaged to the existing version of OS Disk. + ExactVersion *string + + // The virtual machine scale set instance ids. Omitting the virtual machine scale set instance ids will result in the operation + // being performed on all virtual machines in the virtual machine scale set. + InstanceIDs []*string + + // Specifies information required for reimaging the non-ephemeral OS disk. + OSProfile *OSProfileProvisioningData + + // Specifies whether to reimage temp disk. Default value: false. Note: This temp disk reimage parameter is only supported + // for VM/VMSS with Ephemeral OS disk. + TempDisk *bool +} + +// VirtualMachineScaleSetSKU - Describes an available virtual machine scale set sku. +type VirtualMachineScaleSetSKU struct { + // READ-ONLY; Specifies the number of virtual machines in the scale set. + Capacity *VirtualMachineScaleSetSKUCapacity + + // READ-ONLY; The type of resource the sku applies to. + ResourceType *string + + // READ-ONLY; The Sku. + SKU *SKU +} + +// VirtualMachineScaleSetSKUCapacity - Describes scaling information of a sku. +type VirtualMachineScaleSetSKUCapacity struct { + // READ-ONLY; The default capacity. + DefaultCapacity *int64 + + // READ-ONLY; The maximum capacity that can be set. + Maximum *int64 + + // READ-ONLY; The minimum capacity. + Minimum *int64 + + // READ-ONLY; The scale type applicable to the sku. + ScaleType *VirtualMachineScaleSetSKUScaleType +} + +// VirtualMachineScaleSetStorageProfile - Describes a virtual machine scale set storage profile. +type VirtualMachineScaleSetStorageProfile struct { + // Specifies the parameters that are used to add data disks to the virtual machines in the scale set. For more information + // about disks, see About disks and VHDs for Azure virtual machines + // [https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview]. + DataDisks []*VirtualMachineScaleSetDataDisk + DiskControllerType *string + + // Specifies information about the image to use. You can specify information about platform images, marketplace images, or + // virtual machine images. This element is required when you want to use a platform + // image, marketplace image, or virtual machine image, but is not used in other creation operations. + ImageReference *ImageReference + + // Specifies information about the operating system disk used by the virtual machines in the scale set. For more information + // about disks, see About disks and VHDs for Azure virtual machines + // [https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview]. + OSDisk *VirtualMachineScaleSetOSDisk +} + +// VirtualMachineScaleSetUpdate - Describes a Virtual Machine Scale Set. +type VirtualMachineScaleSetUpdate struct { + // The identity of the virtual machine scale set, if configured. + Identity *VirtualMachineScaleSetIdentity + + // The purchase plan when deploying a virtual machine scale set from VM Marketplace images. + Plan *Plan + + // Describes the properties of a Virtual Machine Scale Set. + Properties *VirtualMachineScaleSetUpdateProperties + + // The virtual machine scale set sku. + SKU *SKU + + // Resource tags + Tags map[string]*string +} + +// VirtualMachineScaleSetUpdateIPConfiguration - Describes a virtual machine scale set network profile's IP configuration. +// NOTE: The subnet of a scale set may be modified as long as the original subnet and the new subnet are in the same virtual +// network +type VirtualMachineScaleSetUpdateIPConfiguration struct { + // The IP configuration name. + Name *string + + // Describes a virtual machine scale set network profile's IP configuration properties. + Properties *VirtualMachineScaleSetUpdateIPConfigurationProperties +} + +// VirtualMachineScaleSetUpdateIPConfigurationProperties - Describes a virtual machine scale set network profile's IP configuration +// properties. +type VirtualMachineScaleSetUpdateIPConfigurationProperties struct { + // The application gateway backend address pools. + ApplicationGatewayBackendAddressPools []*SubResource + + // Specifies an array of references to application security group. + ApplicationSecurityGroups []*SubResource + + // The load balancer backend address pools. + LoadBalancerBackendAddressPools []*SubResource + + // The load balancer inbound nat pools. + LoadBalancerInboundNatPools []*SubResource + + // Specifies the primary IP Configuration in case the network interface has more than one IP Configuration. + Primary *bool + + // Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default + // is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. + PrivateIPAddressVersion *IPVersion + + // The publicIPAddressConfiguration. + PublicIPAddressConfiguration *VirtualMachineScaleSetUpdatePublicIPAddressConfiguration + + // The subnet. + Subnet *APIEntityReference +} + +// VirtualMachineScaleSetUpdateNetworkConfiguration - Describes a virtual machine scale set network profile's network configurations. +type VirtualMachineScaleSetUpdateNetworkConfiguration struct { + // The network configuration name. + Name *string + + // Describes a virtual machine scale set updatable network profile's IP configuration.Use this object for updating network + // profile's IP Configuration. + Properties *VirtualMachineScaleSetUpdateNetworkConfigurationProperties +} + +// VirtualMachineScaleSetUpdateNetworkConfigurationProperties - Describes a virtual machine scale set updatable network profile's +// IP configuration.Use this object for updating network profile's IP Configuration. +type VirtualMachineScaleSetUpdateNetworkConfigurationProperties struct { + // Specifies whether the Auxiliary mode is enabled for the Network Interface resource. + AuxiliaryMode *NetworkInterfaceAuxiliaryMode + + // Specifies whether the Auxiliary sku is enabled for the Network Interface resource. + AuxiliarySKU *NetworkInterfaceAuxiliarySKU + + // The dns settings to be applied on the network interfaces. + DNSSettings *VirtualMachineScaleSetNetworkConfigurationDNSSettings + + // Specify what happens to the network interface when the VM is deleted + DeleteOption *DeleteOptions + + // Specifies whether the network interface is disabled for tcp state tracking. + DisableTCPStateTracking *bool + + // Specifies whether the network interface is accelerated networking-enabled. + EnableAcceleratedNetworking *bool + + // Specifies whether the network interface is FPGA networking-enabled. + EnableFpga *bool + + // Whether IP forwarding enabled on this NIC. + EnableIPForwarding *bool + + // The virtual machine scale set IP Configuration. + IPConfigurations []*VirtualMachineScaleSetUpdateIPConfiguration + + // The network security group. + NetworkSecurityGroup *SubResource + + // Whether this is a primary NIC on a virtual machine. + Primary *bool +} + +// VirtualMachineScaleSetUpdateNetworkProfile - Describes a virtual machine scale set network profile. +type VirtualMachineScaleSetUpdateNetworkProfile struct { + // A reference to a load balancer probe used to determine the health of an instance in the virtual machine scale set. The + // reference will be in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. + HealthProbe *APIEntityReference + + // specifies the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations + // for Virtual Machine Scale Set with orchestration mode 'Flexible' + NetworkAPIVersion *NetworkAPIVersion + + // The list of network configurations. + NetworkInterfaceConfigurations []*VirtualMachineScaleSetUpdateNetworkConfiguration +} + +// VirtualMachineScaleSetUpdateOSDisk - Describes virtual machine scale set operating system disk Update Object. This should +// be used for Updating VMSS OS Disk. +type VirtualMachineScaleSetUpdateOSDisk struct { + // The caching type. + Caching *CachingTypes + + // Specifies whether OS Disk should be deleted or detached upon VMSS Flex deletion (This feature is available for VMSS with + // Flexible OrchestrationMode only). + // Possible values: + // Delete If this value is used, the OS disk is deleted when VMSS Flex VM is deleted. + // Detach If this value is used, the OS disk is retained after VMSS Flex VM is deleted. + // The default value is set to Delete. For an Ephemeral OS Disk, the default value is set to Delete. User cannot change the + // delete option for Ephemeral OS Disk. + DeleteOption *DiskDeleteOptionTypes + + // Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a + // virtual machine image. + // diskSizeGB is the number of bytes x 1024^3 for the disk and the value cannot be larger than 1023 + DiskSizeGB *int32 + + // The Source User Image VirtualHardDisk. This VirtualHardDisk will be copied before using it to attach to the Virtual Machine. + // If SourceImage is provided, the destination VirtualHardDisk should not + // exist. + Image *VirtualHardDisk + + // The managed disk parameters. + ManagedDisk *VirtualMachineScaleSetManagedDiskParameters + + // The list of virtual hard disk container uris. + VhdContainers []*string + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool +} + +// VirtualMachineScaleSetUpdateOSProfile - Describes a virtual machine scale set OS profile. +type VirtualMachineScaleSetUpdateOSProfile struct { + // A base-64 encoded string of custom data. + CustomData *string + + // The Linux Configuration of the OS profile. + LinuxConfiguration *LinuxConfiguration + + // The List of certificates for addition to the VM. + Secrets []*VaultSecretGroup + + // The Windows Configuration of the OS profile. + WindowsConfiguration *WindowsConfiguration +} + +// VirtualMachineScaleSetUpdateProperties - Describes the properties of a Virtual Machine Scale Set. +type VirtualMachineScaleSetUpdateProperties struct { + // Specifies additional capabilities enabled or disabled on the Virtual Machines in the Virtual Machine Scale Set. For instance: + // whether the Virtual Machines have the capability to support attaching + // managed data disks with UltraSSD_LRS storage account type. + AdditionalCapabilities *AdditionalCapabilities + + // Policy for automatic repairs. + AutomaticRepairsPolicy *AutomaticRepairsPolicy + + // When Overprovision is enabled, extensions are launched only on the requested number of VMs which are finally kept. This + // property will hence ensure that the extensions do not run on the extra + // overprovisioned VMs. + DoNotRunExtensionsOnOverprovisionedVMs *bool + + // Specifies whether the Virtual Machine Scale Set should be overprovisioned. + Overprovision *bool + + // Specifies the desired targets for mixing Spot and Regular priority VMs within the same VMSS Flex instance. + PriorityMixPolicy *PriorityMixPolicy + + // Specifies information about the proximity placement group that the virtual machine scale set should be assigned to. + // Minimum api-version: 2018-04-01. + ProximityPlacementGroup *SubResource + + // Policy for Resiliency + ResiliencyPolicy *ResiliencyPolicy + + // Specifies the policies applied when scaling in Virtual Machines in the Virtual Machine Scale Set. + ScaleInPolicy *ScaleInPolicy + + // When true this limits the scale set to a single placement group, of max size 100 virtual machines. NOTE: If singlePlacementGroup + // is true, it may be modified to false. However, if singlePlacementGroup + // is false, it may not be modified to true. + SinglePlacementGroup *bool + + // Specifies the Spot Restore properties for the virtual machine scale set. + SpotRestorePolicy *SpotRestorePolicy + + // The upgrade policy. + UpgradePolicy *UpgradePolicy + + // The virtual machine profile. + VirtualMachineProfile *VirtualMachineScaleSetUpdateVMProfile +} + +// VirtualMachineScaleSetUpdatePublicIPAddressConfiguration - Describes a virtual machines scale set IP Configuration's PublicIPAddress +// configuration +type VirtualMachineScaleSetUpdatePublicIPAddressConfiguration struct { + // The publicIP address configuration name. + Name *string + + // Describes a virtual machines scale set IP Configuration's PublicIPAddress configuration + Properties *VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties +} + +// VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties - Describes a virtual machines scale set IP Configuration's +// PublicIPAddress configuration +type VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties struct { + // The dns settings to be applied on the publicIP addresses . + DNSSettings *VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings + + // Specify what happens to the public IP when the VM is deleted + DeleteOption *DeleteOptions + + // The idle timeout of the public IP address. + IdleTimeoutInMinutes *int32 + + // The PublicIPPrefix from which to allocate publicIP addresses. + PublicIPPrefix *SubResource +} + +// VirtualMachineScaleSetUpdateStorageProfile - Describes a virtual machine scale set storage profile. +type VirtualMachineScaleSetUpdateStorageProfile struct { + // The data disks. + DataDisks []*VirtualMachineScaleSetDataDisk + DiskControllerType *string + + // The image reference. + ImageReference *ImageReference + + // The OS disk. + OSDisk *VirtualMachineScaleSetUpdateOSDisk +} + +// VirtualMachineScaleSetUpdateVMProfile - Describes a virtual machine scale set virtual machine profile. +type VirtualMachineScaleSetUpdateVMProfile struct { + // Specifies the billing related details of a Azure Spot VMSS. Minimum api-version: 2019-03-01. + BillingProfile *BillingProfile + + // The virtual machine scale set diagnostics profile. + DiagnosticsProfile *DiagnosticsProfile + + // The virtual machine scale set extension profile. + ExtensionProfile *VirtualMachineScaleSetExtensionProfile + + // Specifies the hardware profile related details of a scale set. Minimum api-version: 2021-11-01. + HardwareProfile *VirtualMachineScaleSetHardwareProfile + + // The license type, which is for bring your own license scenario. + LicenseType *string + + // The virtual machine scale set network profile. + NetworkProfile *VirtualMachineScaleSetUpdateNetworkProfile + + // The virtual machine scale set OS profile. + OSProfile *VirtualMachineScaleSetUpdateOSProfile + + // Specifies Scheduled Event related configurations. + ScheduledEventsProfile *ScheduledEventsProfile + + // The virtual machine scale set Security profile + SecurityProfile *SecurityProfile + + // The virtual machine scale set storage profile. + StorageProfile *VirtualMachineScaleSetUpdateStorageProfile + + // UserData for the VM, which must be base-64 encoded. Customer should not pass any secrets in here. + // Minimum api-version: 2021-03-01 + UserData *string +} + +// VirtualMachineScaleSetVM - Describes a virtual machine scale set virtual machine. +type VirtualMachineScaleSetVM struct { + // REQUIRED; Resource location + Location *string + + // The identity of the virtual machine, if configured. + Identity *VirtualMachineIdentity + + // Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace + // images. Before you can use a marketplace image from an API, you must + // enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click + // Want to deploy programmatically, Get Started ->. Enter any required + // information and then click Save. + Plan *Plan + + // Describes the properties of a virtual machine scale set virtual machine. + Properties *VirtualMachineScaleSetVMProperties + + // Resource tags + Tags map[string]*string + + // READ-ONLY; Etag is property returned in Update/Get response of the VMSS VM, so that customer can supply it in the header + // to ensure optimistic updates. + Etag *string + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; The virtual machine instance ID. + InstanceID *string + + // READ-ONLY; Resource name + Name *string + + // READ-ONLY; The virtual machine child extension resources. + Resources []*VirtualMachineExtension + + // READ-ONLY; The virtual machine SKU. + SKU *SKU + + // READ-ONLY; Resource type + Type *string + + // READ-ONLY; The virtual machine zones. + Zones []*string +} + +// VirtualMachineScaleSetVMExtension - Describes a VMSS VM Extension. +type VirtualMachineScaleSetVMExtension struct { + // The location of the extension. + Location *string + + // Describes the properties of a Virtual Machine Extension. + Properties *VirtualMachineExtensionProperties + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; The name of the extension. + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineScaleSetVMExtensionUpdate - Describes a VMSS VM Extension. +type VirtualMachineScaleSetVMExtensionUpdate struct { + // Describes the properties of a Virtual Machine Extension. + Properties *VirtualMachineExtensionUpdateProperties + + // READ-ONLY; Resource Id + ID *string + + // READ-ONLY; The name of the extension. + Name *string + + // READ-ONLY; Resource type + Type *string +} + +// VirtualMachineScaleSetVMExtensionsListResult - The List VMSS VM Extension operation response +type VirtualMachineScaleSetVMExtensionsListResult struct { + // The list of VMSS VM extensions + Value []*VirtualMachineScaleSetVMExtension +} + +// VirtualMachineScaleSetVMExtensionsSummary - Extensions summary for virtual machines of a virtual machine scale set. +type VirtualMachineScaleSetVMExtensionsSummary struct { + // READ-ONLY; The extension name. + Name *string + + // READ-ONLY; The extensions information. + StatusesSummary []*VirtualMachineStatusCodeCount +} + +// VirtualMachineScaleSetVMInstanceIDs - Specifies a list of virtual machine instance IDs from the VM scale set. +type VirtualMachineScaleSetVMInstanceIDs struct { + // The virtual machine scale set instance ids. Omitting the virtual machine scale set instance ids will result in the operation + // being performed on all virtual machines in the virtual machine scale set. + InstanceIDs []*string +} + +// VirtualMachineScaleSetVMInstanceRequiredIDs - Specifies a list of virtual machine instance IDs from the VM scale set. +type VirtualMachineScaleSetVMInstanceRequiredIDs struct { + // REQUIRED; The virtual machine scale set instance ids. + InstanceIDs []*string +} + +// VirtualMachineScaleSetVMInstanceView - The instance view of a virtual machine scale set VM. +type VirtualMachineScaleSetVMInstanceView struct { + // Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. You + // can easily view the output of your console log. Azure also enables you to see + // a screenshot of the VM from the hypervisor. + BootDiagnostics *BootDiagnosticsInstanceView + + // Specifies the host OS name of the virtual machine. + // This name cannot be updated after the VM is created. + // Max-length (Windows): 15 characters + // Max-length (Linux): 64 characters. + // For naming conventions and restrictions see Azure infrastructure services implementation guidelines + // [https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-infrastructure-subscription-accounts-guidelines?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#1-naming-conventions]. + ComputerName *string + + // The disks information. + Disks []*DiskInstanceView + + // The extensions information. + Extensions []*VirtualMachineExtensionInstanceView + + // The hypervisor generation of the Virtual Machine [V1, V2] + HyperVGeneration *HyperVGeneration + + // The Maintenance Operation status on the virtual machine. + MaintenanceRedeployStatus *MaintenanceRedeployStatus + + // The Operating System running on the hybrid machine. + OSName *string + + // The version of Operating System running on the hybrid machine. + OSVersion *string + + // The placement group in which the VM is running. If the VM is deallocated it will not have a placementGroupId. + PlacementGroupID *string + + // The Fault Domain count. + PlatformFaultDomain *int32 + + // The Update Domain count. + PlatformUpdateDomain *int32 + + // The Remote desktop certificate thumbprint. + RdpThumbPrint *string + + // The resource status information. + Statuses []*InstanceViewStatus + + // The VM Agent running on the virtual machine. + VMAgent *VirtualMachineAgentInstanceView + + // READ-ONLY; Resource id of the dedicated host, on which the virtual machine is allocated through automatic placement, when + // the virtual machine is associated with a dedicated host group that has automatic + // placement enabled. Minimum api-version: 2020-06-01. + AssignedHost *string + + // READ-ONLY; The health status for the VM. + VMHealth *VirtualMachineHealthStatus +} + +// VirtualMachineScaleSetVMListResult - The List Virtual Machine Scale Set VMs operation response. +type VirtualMachineScaleSetVMListResult struct { + // REQUIRED; The list of virtual machine scale sets VMs. + Value []*VirtualMachineScaleSetVM + + // The uri to fetch the next page of Virtual Machine Scale Set VMs. Call ListNext() with this to fetch the next page of VMSS + // VMs + NextLink *string +} + +// VirtualMachineScaleSetVMNetworkProfileConfiguration - Describes a virtual machine scale set VM network profile. +type VirtualMachineScaleSetVMNetworkProfileConfiguration struct { + // The list of network configurations. + NetworkInterfaceConfigurations []*VirtualMachineScaleSetNetworkConfiguration +} + +// VirtualMachineScaleSetVMProfile - Describes a virtual machine scale set virtual machine profile. +type VirtualMachineScaleSetVMProfile struct { + // Specifies the gallery applications that should be made available to the VM/VMSS + ApplicationProfile *ApplicationProfile + + // Specifies the billing related details of a Azure Spot VMSS. Minimum api-version: 2019-03-01. + BillingProfile *BillingProfile + + // Specifies the capacity reservation related details of a scale set. Minimum api-version: 2021-04-01. + CapacityReservation *CapacityReservationProfile + + // Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15. + DiagnosticsProfile *DiagnosticsProfile + + // Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. For Azure Spot virtual machines, + // both 'Deallocate' and 'Delete' are supported and the minimum api-version is + // 2019-03-01. For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview. + EvictionPolicy *VirtualMachineEvictionPolicyTypes + + // Specifies a collection of settings for extensions installed on virtual machines in the scale set. + ExtensionProfile *VirtualMachineScaleSetExtensionProfile + + // Specifies the hardware profile related details of a scale set. Minimum api-version: 2021-11-01. + HardwareProfile *VirtualMachineScaleSetHardwareProfile + + // Specifies that the image or disk that is being used was licensed on-premises. + // Possible values for Windows Server operating system are: + // WindowsClient + // WindowsServer + // Possible values for Linux Server operating system are: + // RHELBYOS (for RHEL) + // SLESBYOS (for SUSE) + // For more information, see Azure Hybrid Use Benefit for Windows Server [https://docs.microsoft.com/azure/virtual-machines/windows/hybrid-use-benefit-licensing] + // Azure Hybrid Use Benefit for Linux Server [https://docs.microsoft.com/azure/virtual-machines/linux/azure-hybrid-benefit-linux] + // Minimum api-version: 2015-06-15 + LicenseType *string + + // Specifies properties of the network interfaces of the virtual machines in the scale set. + NetworkProfile *VirtualMachineScaleSetNetworkProfile + + // Specifies the operating system settings for the virtual machines in the scale set. + OSProfile *VirtualMachineScaleSetOSProfile + + // Specifies the priority for the virtual machines in the scale set. Minimum api-version: 2017-10-30-preview. + Priority *VirtualMachinePriorityTypes + + // Specifies Scheduled Event related configurations. + ScheduledEventsProfile *ScheduledEventsProfile + + // Specifies the security posture to be used for all virtual machines in the scale set. Minimum api-version: 2023-03-01 + SecurityPostureReference *SecurityPostureReference + + // Specifies the Security related profile settings for the virtual machines in the scale set. + SecurityProfile *SecurityProfile + + // Specifies the service artifact reference id used to set same image version for all virtual machines in the scale set when + // using 'latest' image version. Minimum api-version: 2022-11-01 + ServiceArtifactReference *ServiceArtifactReference + + // Specifies the storage settings for the virtual machine disks. + StorageProfile *VirtualMachineScaleSetStorageProfile + + // UserData for the virtual machines in the scale set, which must be base-64 encoded. Customer should not pass any secrets + // in here. Minimum api-version: 2021-03-01. + UserData *string + + // READ-ONLY; Specifies the time in which this VM profile for the Virtual Machine Scale Set was created. Minimum API version + // for this property is 2023-09-01. This value will be added to VMSS Flex VM tags when + // creating/updating the VMSS VM Profile with minimum api-version 2023-09-01. + TimeCreated *time.Time +} + +// VirtualMachineScaleSetVMProperties - Describes the properties of a virtual machine scale set virtual machine. +type VirtualMachineScaleSetVMProperties struct { + // Specifies additional capabilities enabled or disabled on the virtual machine in the scale set. For instance: whether the + // virtual machine has the capability to support attaching managed data disks with + // UltraSSD_LRS storage account type. + AdditionalCapabilities *AdditionalCapabilities + + // Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified + // in the same availability set are allocated to different nodes to maximize + // availability. For more information about availability sets, see Availability sets overview [https://docs.microsoft.com/azure/virtual-machines/availability-set-overview]. + // For more information on Azure + // planned maintenance, see Maintenance and updates for Virtual Machines in Azure [https://docs.microsoft.com/azure/virtual-machines/maintenance-and-updates]. + // Currently, a VM can only be added to + // availability set at creation time. An existing VM cannot be added to an availability set. + AvailabilitySet *SubResource + + // Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15. + DiagnosticsProfile *DiagnosticsProfile + + // Specifies the hardware settings for the virtual machine. + HardwareProfile *HardwareProfile + + // Specifies that the image or disk that is being used was licensed on-premises. + // Possible values for Windows Server operating system are: + // WindowsClient + // WindowsServer + // Possible values for Linux Server operating system are: + // RHELBYOS (for RHEL) + // SLESBYOS (for SUSE) + // For more information, see Azure Hybrid Use Benefit for Windows Server [https://docs.microsoft.com/azure/virtual-machines/windows/hybrid-use-benefit-licensing] + // Azure Hybrid Use Benefit for Linux Server [https://docs.microsoft.com/azure/virtual-machines/linux/azure-hybrid-benefit-linux] + // Minimum api-version: 2015-06-15 + LicenseType *string + + // Specifies the network interfaces of the virtual machine. + NetworkProfile *NetworkProfile + + // Specifies the network profile configuration of the virtual machine. + NetworkProfileConfiguration *VirtualMachineScaleSetVMNetworkProfileConfiguration + + // Specifies the operating system settings for the virtual machine. + OSProfile *OSProfile + + // Specifies the protection policy of the virtual machine. + ProtectionPolicy *VirtualMachineScaleSetVMProtectionPolicy + + // Specifies the Security related profile settings for the virtual machine. + SecurityProfile *SecurityProfile + + // Specifies the storage settings for the virtual machine disks. + StorageProfile *StorageProfile + + // UserData for the VM, which must be base-64 encoded. Customer should not pass any secrets in here. + // Minimum api-version: 2021-03-01 + UserData *string + + // READ-ONLY; The virtual machine instance view. + InstanceView *VirtualMachineScaleSetVMInstanceView + + // READ-ONLY; Specifies whether the latest model has been applied to the virtual machine. + LatestModelApplied *bool + + // READ-ONLY; Specifies whether the model applied to the virtual machine is the model of the virtual machine scale set or + // the customized model for the virtual machine. + ModelDefinitionApplied *string + + // READ-ONLY; The provisioning state, which only appears in the response. + ProvisioningState *string + + // READ-ONLY; Specifies the time at which the Virtual Machine resource was created. + // Minimum api-version: 2021-11-01. + TimeCreated *time.Time + + // READ-ONLY; Azure VM unique ID. + VMID *string +} + +// VirtualMachineScaleSetVMProtectionPolicy - The protection policy of a virtual machine scale set VM. +type VirtualMachineScaleSetVMProtectionPolicy struct { + // Indicates that the virtual machine scale set VM shouldn't be considered for deletion during a scale-in operation. + ProtectFromScaleIn *bool + + // Indicates that model updates or actions (including scale-in) initiated on the virtual machine scale set should not be applied + // to the virtual machine scale set VM. + ProtectFromScaleSetActions *bool +} + +// VirtualMachineScaleSetVMReimageParameters - Describes a Virtual Machine Scale Set VM Reimage Parameters. +type VirtualMachineScaleSetVMReimageParameters struct { + // Specifies in decimal number, the version the OS disk should be reimaged to. If exact version is not provided, the OS disk + // is reimaged to the existing version of OS Disk. + ExactVersion *string + + // Specifies information required for reimaging the non-ephemeral OS disk. + OSProfile *OSProfileProvisioningData + + // Specifies whether to reimage temp disk. Default value: false. Note: This temp disk reimage parameter is only supported + // for VM/VMSS with Ephemeral OS disk. + TempDisk *bool +} + +// VirtualMachineSize - Describes the properties of a VM size. +type VirtualMachineSize struct { + // The maximum number of data disks that can be attached to the virtual machine size. + MaxDataDiskCount *int32 + + // The amount of memory, in MB, supported by the virtual machine size. + MemoryInMB *int32 + + // The name of the virtual machine size. + Name *string + + // The number of cores supported by the virtual machine size. For Constrained vCPU capable VM sizes, this number represents + // the total vCPUs of quota that the VM uses. For accurate vCPU count, please + // refer to https://docs.microsoft.com/azure/virtual-machines/constrained-vcpu or https://docs.microsoft.com/rest/api/compute/resourceskus/list + NumberOfCores *int32 + + // The OS disk size, in MB, allowed by the virtual machine size. + OSDiskSizeInMB *int32 + + // The resource disk size, in MB, allowed by the virtual machine size. + ResourceDiskSizeInMB *int32 +} + +// VirtualMachineSizeListResult - The List Virtual Machine operation response. +type VirtualMachineSizeListResult struct { + // The list of virtual machine sizes. + Value []*VirtualMachineSize +} + +// VirtualMachineSoftwarePatchProperties - Describes the properties of a Virtual Machine software patch. +type VirtualMachineSoftwarePatchProperties struct { + // READ-ONLY; The activity ID of the operation that produced this result. It is used to correlate across CRP and extension + // logs. + ActivityID *string + + // READ-ONLY; Describes the availability of a given patch. + AssessmentState *PatchAssessmentState + + // READ-ONLY; The classification(s) of the patch as provided by the patch publisher. + Classifications []*string + + // READ-ONLY; The KBID of the patch. Only applies to Windows patches. + KbID *string + + // READ-ONLY; The UTC timestamp of the last update to this patch record. + LastModifiedDateTime *time.Time + + // READ-ONLY; The friendly name of the patch. + Name *string + + // READ-ONLY; A unique identifier for the patch. + PatchID *string + + // READ-ONLY; The UTC timestamp when the repository published this patch. + PublishedDate *time.Time + + // READ-ONLY; Describes the reboot requirements of the patch. + RebootBehavior *VMGuestPatchRebootBehavior + + // READ-ONLY; The version number of the patch. This property applies only to Linux patches. + Version *string +} + +// VirtualMachineStatusCodeCount - The status code and count of the virtual machine scale set instance view status summary. +type VirtualMachineStatusCodeCount struct { + // READ-ONLY; The instance view status code. + Code *string + + // READ-ONLY; The number of instances having a particular status code. + Count *int32 +} + +// VirtualMachineUpdate - Describes a Virtual Machine Update. +type VirtualMachineUpdate struct { + // The identity of the virtual machine, if configured. + Identity *VirtualMachineIdentity + + // Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace + // images. Before you can use a marketplace image from an API, you must + // enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click + // Want to deploy programmatically, Get Started ->. Enter any required + // information and then click Save. + Plan *Plan + + // Describes the properties of a Virtual Machine. + Properties *VirtualMachineProperties + + // Resource tags + Tags map[string]*string + + // The virtual machine zones. + Zones []*string +} + +// WinRMConfiguration - Describes Windows Remote Management configuration of the VM +type WinRMConfiguration struct { + // The list of Windows Remote Management listeners + Listeners []*WinRMListener +} + +// WinRMListener - Describes Protocol and thumbprint of Windows Remote Management listener +type WinRMListener struct { + // This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, + // see Add a key or secret to the key vault + // [https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add]. In this case, your certificate needs to be the + // Base64 encoding of the following JSON Object which is encoded in UTF-8: + // { + // "data":"", + // "dataType":"pfx", + // "password":"" + // } + // To install certificates on a virtual machine it is recommended to use the Azure Key Vault virtual machine extension for + // Linux + // [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux] or the Azure Key Vault virtual machine extension + // for Windows + // [https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows]. + CertificateURL *string + + // Specifies the protocol of WinRM listener. Possible values are: http, https. + Protocol *ProtocolTypes +} + +// WindowsConfiguration - Specifies Windows operating system settings on the virtual machine. +type WindowsConfiguration struct { + // Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is + // used by Windows Setup. + AdditionalUnattendContent []*AdditionalUnattendContent + + // Indicates whether Automatic Updates is enabled for the Windows virtual machine. Default value is true. For virtual machine + // scale sets, this property can be updated and updates will take effect on OS + // reprovisioning. + EnableAutomaticUpdates *bool + + // Indicates whether VMAgent Platform Updates is enabled for the Windows virtual machine. Default value is false. + EnableVMAgentPlatformUpdates *bool + + // [Preview Feature] Specifies settings related to VM Guest Patching on Windows. + PatchSettings *PatchSettings + + // Indicates whether virtual machine agent should be provisioned on the virtual machine. When this property is not specified + // in the request body, it is set to true by default. This will ensure that VM + // Agent is installed on the VM so that extensions can be added to the VM later. + ProvisionVMAgent *bool + + // Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time". Possible values can be TimeZoneInfo.Id + // [https://docs.microsoft.com/dotnet/api/system.timezoneinfo.id?#System_TimeZoneInfo_Id] value from time zones returned by + // TimeZoneInfo.GetSystemTimeZones + // [https://docs.microsoft.com/dotnet/api/system.timezoneinfo.getsystemtimezones]. + TimeZone *string + + // Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell. + WinRM *WinRMConfiguration +} + +// WindowsParameters - Input for InstallPatches on a Windows VM, as directly received by the API +type WindowsParameters struct { + // The update classifications to select when installing patches for Windows. + ClassificationsToInclude []*VMGuestPatchClassificationWindows + + // Filters out Kbs that don't have an InstallationRebootBehavior of 'NeverReboots' when this is set to true. + ExcludeKbsRequiringReboot *bool + + // Kbs to exclude in the patch operation + KbNumbersToExclude []*string + + // Kbs to include in the patch operation + KbNumbersToInclude []*string + + // This is used to install patches that were published on or before this given max published date. + MaxPatchPublishDate *time.Time +} + +// WindowsVMGuestPatchAutomaticByPlatformSettings - Specifies additional settings to be applied when patch mode AutomaticByPlatform +// is selected in Windows patch settings. +type WindowsVMGuestPatchAutomaticByPlatformSettings struct { + // Enables customer to schedule patching without accidental upgrades + BypassPlatformSafetyChecksOnUserSchedule *bool + + // Specifies the reboot setting for all AutomaticByPlatform patch installation operations. + RebootSetting *WindowsVMGuestPatchAutomaticByPlatformRebootSetting +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models_serde.go new file mode 100644 index 000000000..3c63478d0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/models_serde.go @@ -0,0 +1,19775 @@ +//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 armcompute + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type APIEntityReference. +func (a APIEntityReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIEntityReference. +func (a *APIEntityReference) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIError. +func (a APIError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", a.Code) + populate(objectMap, "details", a.Details) + populate(objectMap, "innererror", a.Innererror) + populate(objectMap, "message", a.Message) + populate(objectMap, "target", a.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIError. +func (a *APIError) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &a.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &a.Details) + delete(rawMsg, key) + case "innererror": + err = unpopulate(val, "Innererror", &a.Innererror) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &a.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &a.Target) + 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 APIErrorBase. +func (a APIErrorBase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", a.Code) + populate(objectMap, "message", a.Message) + populate(objectMap, "target", a.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIErrorBase. +func (a *APIErrorBase) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &a.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &a.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &a.Target) + 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 AccessURI. +func (a AccessURI) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessSAS", a.AccessSAS) + populate(objectMap, "securityDataAccessSAS", a.SecurityDataAccessSAS) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccessURI. +func (a *AccessURI) UnmarshalJSON(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 "accessSAS": + err = unpopulate(val, "AccessSAS", &a.AccessSAS) + delete(rawMsg, key) + case "securityDataAccessSAS": + err = unpopulate(val, "SecurityDataAccessSAS", &a.SecurityDataAccessSAS) + 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 AdditionalCapabilities. +func (a AdditionalCapabilities) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hibernationEnabled", a.HibernationEnabled) + populate(objectMap, "ultraSSDEnabled", a.UltraSSDEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdditionalCapabilities. +func (a *AdditionalCapabilities) UnmarshalJSON(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 "hibernationEnabled": + err = unpopulate(val, "HibernationEnabled", &a.HibernationEnabled) + delete(rawMsg, key) + case "ultraSSDEnabled": + err = unpopulate(val, "UltraSSDEnabled", &a.UltraSSDEnabled) + 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 AdditionalUnattendContent. +func (a AdditionalUnattendContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["componentName"] = "Microsoft-Windows-Shell-Setup" + populate(objectMap, "content", a.Content) + objectMap["passName"] = "OobeSystem" + populate(objectMap, "settingName", a.SettingName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdditionalUnattendContent. +func (a *AdditionalUnattendContent) UnmarshalJSON(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 "componentName": + err = unpopulate(val, "ComponentName", &a.ComponentName) + delete(rawMsg, key) + case "content": + err = unpopulate(val, "Content", &a.Content) + delete(rawMsg, key) + case "passName": + err = unpopulate(val, "PassName", &a.PassName) + delete(rawMsg, key) + case "settingName": + err = unpopulate(val, "SettingName", &a.SettingName) + 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 AlternativeOption. +func (a AlternativeOption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", a.Type) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlternativeOption. +func (a *AlternativeOption) UnmarshalJSON(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) + 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 ApplicationProfile. +func (a ApplicationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "galleryApplications", a.GalleryApplications) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationProfile. +func (a *ApplicationProfile) UnmarshalJSON(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 "galleryApplications": + err = unpopulate(val, "GalleryApplications", &a.GalleryApplications) + 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 AttachDetachDataDisksRequest. +func (a AttachDetachDataDisksRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisksToAttach", a.DataDisksToAttach) + populate(objectMap, "dataDisksToDetach", a.DataDisksToDetach) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AttachDetachDataDisksRequest. +func (a *AttachDetachDataDisksRequest) UnmarshalJSON(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 "dataDisksToAttach": + err = unpopulate(val, "DataDisksToAttach", &a.DataDisksToAttach) + delete(rawMsg, key) + case "dataDisksToDetach": + err = unpopulate(val, "DataDisksToDetach", &a.DataDisksToDetach) + 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 AutomaticOSUpgradePolicy. +func (a AutomaticOSUpgradePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disableAutomaticRollback", a.DisableAutomaticRollback) + populate(objectMap, "enableAutomaticOSUpgrade", a.EnableAutomaticOSUpgrade) + populate(objectMap, "osRollingUpgradeDeferral", a.OSRollingUpgradeDeferral) + populate(objectMap, "useRollingUpgradePolicy", a.UseRollingUpgradePolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutomaticOSUpgradePolicy. +func (a *AutomaticOSUpgradePolicy) UnmarshalJSON(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 "disableAutomaticRollback": + err = unpopulate(val, "DisableAutomaticRollback", &a.DisableAutomaticRollback) + delete(rawMsg, key) + case "enableAutomaticOSUpgrade": + err = unpopulate(val, "EnableAutomaticOSUpgrade", &a.EnableAutomaticOSUpgrade) + delete(rawMsg, key) + case "osRollingUpgradeDeferral": + err = unpopulate(val, "OSRollingUpgradeDeferral", &a.OSRollingUpgradeDeferral) + delete(rawMsg, key) + case "useRollingUpgradePolicy": + err = unpopulate(val, "UseRollingUpgradePolicy", &a.UseRollingUpgradePolicy) + 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 AutomaticOSUpgradeProperties. +func (a AutomaticOSUpgradeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticOSUpgradeSupported", a.AutomaticOSUpgradeSupported) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutomaticOSUpgradeProperties. +func (a *AutomaticOSUpgradeProperties) UnmarshalJSON(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 "automaticOSUpgradeSupported": + err = unpopulate(val, "AutomaticOSUpgradeSupported", &a.AutomaticOSUpgradeSupported) + 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 AutomaticRepairsPolicy. +func (a AutomaticRepairsPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", a.Enabled) + populate(objectMap, "gracePeriod", a.GracePeriod) + populate(objectMap, "repairAction", a.RepairAction) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutomaticRepairsPolicy. +func (a *AutomaticRepairsPolicy) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &a.Enabled) + delete(rawMsg, key) + case "gracePeriod": + err = unpopulate(val, "GracePeriod", &a.GracePeriod) + delete(rawMsg, key) + case "repairAction": + err = unpopulate(val, "RepairAction", &a.RepairAction) + 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 AvailabilitySet. +func (a AvailabilitySet) 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, "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 AvailabilitySet. +func (a *AvailabilitySet) UnmarshalJSON(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 "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 AvailabilitySetListResult. +func (a AvailabilitySetListResult) 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 AvailabilitySetListResult. +func (a *AvailabilitySetListResult) UnmarshalJSON(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 AvailabilitySetProperties. +func (a AvailabilitySetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "platformFaultDomainCount", a.PlatformFaultDomainCount) + populate(objectMap, "platformUpdateDomainCount", a.PlatformUpdateDomainCount) + populate(objectMap, "proximityPlacementGroup", a.ProximityPlacementGroup) + populate(objectMap, "statuses", a.Statuses) + populate(objectMap, "virtualMachines", a.VirtualMachines) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailabilitySetProperties. +func (a *AvailabilitySetProperties) UnmarshalJSON(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 "platformFaultDomainCount": + err = unpopulate(val, "PlatformFaultDomainCount", &a.PlatformFaultDomainCount) + delete(rawMsg, key) + case "platformUpdateDomainCount": + err = unpopulate(val, "PlatformUpdateDomainCount", &a.PlatformUpdateDomainCount) + delete(rawMsg, key) + case "proximityPlacementGroup": + err = unpopulate(val, "ProximityPlacementGroup", &a.ProximityPlacementGroup) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &a.Statuses) + delete(rawMsg, key) + case "virtualMachines": + err = unpopulate(val, "VirtualMachines", &a.VirtualMachines) + 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 AvailabilitySetUpdate. +func (a AvailabilitySetUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + 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 AvailabilitySetUpdate. +func (a *AvailabilitySetUpdate) UnmarshalJSON(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 "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 AvailablePatchSummary. +func (a AvailablePatchSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assessmentActivityId", a.AssessmentActivityID) + populate(objectMap, "criticalAndSecurityPatchCount", a.CriticalAndSecurityPatchCount) + populate(objectMap, "error", a.Error) + populateDateTimeRFC3339(objectMap, "lastModifiedTime", a.LastModifiedTime) + populate(objectMap, "otherPatchCount", a.OtherPatchCount) + populate(objectMap, "rebootPending", a.RebootPending) + populateDateTimeRFC3339(objectMap, "startTime", a.StartTime) + populate(objectMap, "status", a.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailablePatchSummary. +func (a *AvailablePatchSummary) UnmarshalJSON(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 "assessmentActivityId": + err = unpopulate(val, "AssessmentActivityID", &a.AssessmentActivityID) + delete(rawMsg, key) + case "criticalAndSecurityPatchCount": + err = unpopulate(val, "CriticalAndSecurityPatchCount", &a.CriticalAndSecurityPatchCount) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "lastModifiedTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedTime", &a.LastModifiedTime) + delete(rawMsg, key) + case "otherPatchCount": + err = unpopulate(val, "OtherPatchCount", &a.OtherPatchCount) + delete(rawMsg, key) + case "rebootPending": + err = unpopulate(val, "RebootPending", &a.RebootPending) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &a.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &a.Status) + 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 BillingProfile. +func (b BillingProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "maxPrice", b.MaxPrice) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BillingProfile. +func (b *BillingProfile) UnmarshalJSON(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 "maxPrice": + err = unpopulate(val, "MaxPrice", &b.MaxPrice) + 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 BootDiagnostics. +func (b BootDiagnostics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", b.Enabled) + populate(objectMap, "storageUri", b.StorageURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BootDiagnostics. +func (b *BootDiagnostics) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &b.Enabled) + delete(rawMsg, key) + case "storageUri": + err = unpopulate(val, "StorageURI", &b.StorageURI) + 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 BootDiagnosticsInstanceView. +func (b BootDiagnosticsInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "consoleScreenshotBlobUri", b.ConsoleScreenshotBlobURI) + populate(objectMap, "serialConsoleLogBlobUri", b.SerialConsoleLogBlobURI) + populate(objectMap, "status", b.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BootDiagnosticsInstanceView. +func (b *BootDiagnosticsInstanceView) UnmarshalJSON(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 "consoleScreenshotBlobUri": + err = unpopulate(val, "ConsoleScreenshotBlobURI", &b.ConsoleScreenshotBlobURI) + delete(rawMsg, key) + case "serialConsoleLogBlobUri": + err = unpopulate(val, "SerialConsoleLogBlobURI", &b.SerialConsoleLogBlobURI) + 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 CapacityReservation. +func (c CapacityReservation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + populate(objectMap, "zones", c.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservation. +func (c *CapacityReservation) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &c.Location) + 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 "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &c.Zones) + 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 CapacityReservationGroup. +func (c CapacityReservationGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + populate(objectMap, "zones", c.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationGroup. +func (c *CapacityReservationGroup) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &c.Location) + 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 "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &c.Zones) + 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 CapacityReservationGroupInstanceView. +func (c CapacityReservationGroupInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacityReservations", c.CapacityReservations) + populate(objectMap, "sharedSubscriptionIds", c.SharedSubscriptionIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationGroupInstanceView. +func (c *CapacityReservationGroupInstanceView) UnmarshalJSON(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 "capacityReservations": + err = unpopulate(val, "CapacityReservations", &c.CapacityReservations) + delete(rawMsg, key) + case "sharedSubscriptionIds": + err = unpopulate(val, "SharedSubscriptionIDs", &c.SharedSubscriptionIDs) + 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 CapacityReservationGroupListResult. +func (c CapacityReservationGroupListResult) 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 CapacityReservationGroupListResult. +func (c *CapacityReservationGroupListResult) UnmarshalJSON(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 CapacityReservationGroupProperties. +func (c CapacityReservationGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacityReservations", c.CapacityReservations) + populate(objectMap, "instanceView", c.InstanceView) + populate(objectMap, "sharingProfile", c.SharingProfile) + populate(objectMap, "virtualMachinesAssociated", c.VirtualMachinesAssociated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationGroupProperties. +func (c *CapacityReservationGroupProperties) UnmarshalJSON(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 "capacityReservations": + err = unpopulate(val, "CapacityReservations", &c.CapacityReservations) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &c.InstanceView) + delete(rawMsg, key) + case "sharingProfile": + err = unpopulate(val, "SharingProfile", &c.SharingProfile) + delete(rawMsg, key) + case "virtualMachinesAssociated": + err = unpopulate(val, "VirtualMachinesAssociated", &c.VirtualMachinesAssociated) + 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 CapacityReservationGroupUpdate. +func (c CapacityReservationGroupUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationGroupUpdate. +func (c *CapacityReservationGroupUpdate) UnmarshalJSON(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) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + 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 CapacityReservationInstanceView. +func (c CapacityReservationInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "statuses", c.Statuses) + populate(objectMap, "utilizationInfo", c.UtilizationInfo) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationInstanceView. +func (c *CapacityReservationInstanceView) UnmarshalJSON(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 "statuses": + err = unpopulate(val, "Statuses", &c.Statuses) + delete(rawMsg, key) + case "utilizationInfo": + err = unpopulate(val, "UtilizationInfo", &c.UtilizationInfo) + 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 CapacityReservationInstanceViewWithName. +func (c CapacityReservationInstanceViewWithName) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "statuses", c.Statuses) + populate(objectMap, "utilizationInfo", c.UtilizationInfo) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationInstanceViewWithName. +func (c *CapacityReservationInstanceViewWithName) UnmarshalJSON(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 "statuses": + err = unpopulate(val, "Statuses", &c.Statuses) + delete(rawMsg, key) + case "utilizationInfo": + err = unpopulate(val, "UtilizationInfo", &c.UtilizationInfo) + 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 CapacityReservationListResult. +func (c CapacityReservationListResult) 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 CapacityReservationListResult. +func (c *CapacityReservationListResult) UnmarshalJSON(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 CapacityReservationProfile. +func (c CapacityReservationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacityReservationGroup", c.CapacityReservationGroup) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationProfile. +func (c *CapacityReservationProfile) UnmarshalJSON(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 "capacityReservationGroup": + err = unpopulate(val, "CapacityReservationGroup", &c.CapacityReservationGroup) + 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 CapacityReservationProperties. +func (c CapacityReservationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceView", c.InstanceView) + populate(objectMap, "platformFaultDomainCount", c.PlatformFaultDomainCount) + populate(objectMap, "provisioningState", c.ProvisioningState) + populateDateTimeRFC3339(objectMap, "provisioningTime", c.ProvisioningTime) + populate(objectMap, "reservationId", c.ReservationID) + populateDateTimeRFC3339(objectMap, "timeCreated", c.TimeCreated) + populate(objectMap, "virtualMachinesAssociated", c.VirtualMachinesAssociated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationProperties. +func (c *CapacityReservationProperties) UnmarshalJSON(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 "instanceView": + err = unpopulate(val, "InstanceView", &c.InstanceView) + delete(rawMsg, key) + case "platformFaultDomainCount": + err = unpopulate(val, "PlatformFaultDomainCount", &c.PlatformFaultDomainCount) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "provisioningTime": + err = unpopulateDateTimeRFC3339(val, "ProvisioningTime", &c.ProvisioningTime) + delete(rawMsg, key) + case "reservationId": + err = unpopulate(val, "ReservationID", &c.ReservationID) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &c.TimeCreated) + delete(rawMsg, key) + case "virtualMachinesAssociated": + err = unpopulate(val, "VirtualMachinesAssociated", &c.VirtualMachinesAssociated) + 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 CapacityReservationUpdate. +func (c CapacityReservationUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationUpdate. +func (c *CapacityReservationUpdate) UnmarshalJSON(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) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + 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 CapacityReservationUtilization. +func (c CapacityReservationUtilization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentCapacity", c.CurrentCapacity) + populate(objectMap, "virtualMachinesAllocated", c.VirtualMachinesAllocated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationUtilization. +func (c *CapacityReservationUtilization) UnmarshalJSON(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 "currentCapacity": + err = unpopulate(val, "CurrentCapacity", &c.CurrentCapacity) + delete(rawMsg, key) + case "virtualMachinesAllocated": + err = unpopulate(val, "VirtualMachinesAllocated", &c.VirtualMachinesAllocated) + 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 CloudService. +func (c CloudService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + populate(objectMap, "zones", c.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudService. +func (c *CloudService) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &c.Location) + 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 "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &c.Zones) + 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 CloudServiceExtensionProfile. +func (c CloudServiceExtensionProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extensions", c.Extensions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceExtensionProfile. +func (c *CloudServiceExtensionProfile) UnmarshalJSON(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 "extensions": + err = unpopulate(val, "Extensions", &c.Extensions) + 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 CloudServiceExtensionProperties. +func (c CloudServiceExtensionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoUpgradeMinorVersion", c.AutoUpgradeMinorVersion) + populate(objectMap, "forceUpdateTag", c.ForceUpdateTag) + populateAny(objectMap, "protectedSettings", c.ProtectedSettings) + populate(objectMap, "protectedSettingsFromKeyVault", c.ProtectedSettingsFromKeyVault) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "publisher", c.Publisher) + populate(objectMap, "rolesAppliedTo", c.RolesAppliedTo) + populateAny(objectMap, "settings", c.Settings) + populate(objectMap, "type", c.Type) + populate(objectMap, "typeHandlerVersion", c.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceExtensionProperties. +func (c *CloudServiceExtensionProperties) UnmarshalJSON(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 "autoUpgradeMinorVersion": + err = unpopulate(val, "AutoUpgradeMinorVersion", &c.AutoUpgradeMinorVersion) + delete(rawMsg, key) + case "forceUpdateTag": + err = unpopulate(val, "ForceUpdateTag", &c.ForceUpdateTag) + delete(rawMsg, key) + case "protectedSettings": + err = unpopulate(val, "ProtectedSettings", &c.ProtectedSettings) + delete(rawMsg, key) + case "protectedSettingsFromKeyVault": + err = unpopulate(val, "ProtectedSettingsFromKeyVault", &c.ProtectedSettingsFromKeyVault) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &c.Publisher) + delete(rawMsg, key) + case "rolesAppliedTo": + err = unpopulate(val, "RolesAppliedTo", &c.RolesAppliedTo) + delete(rawMsg, key) + case "settings": + err = unpopulate(val, "Settings", &c.Settings) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &c.TypeHandlerVersion) + 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 CloudServiceInstanceView. +func (c CloudServiceInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIds", c.PrivateIDs) + populate(objectMap, "roleInstance", c.RoleInstance) + populate(objectMap, "sdkVersion", c.SdkVersion) + populate(objectMap, "statuses", c.Statuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceInstanceView. +func (c *CloudServiceInstanceView) UnmarshalJSON(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 "privateIds": + err = unpopulate(val, "PrivateIDs", &c.PrivateIDs) + delete(rawMsg, key) + case "roleInstance": + err = unpopulate(val, "RoleInstance", &c.RoleInstance) + delete(rawMsg, key) + case "sdkVersion": + err = unpopulate(val, "SdkVersion", &c.SdkVersion) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &c.Statuses) + 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 CloudServiceListResult. +func (c CloudServiceListResult) 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 CloudServiceListResult. +func (c *CloudServiceListResult) UnmarshalJSON(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 CloudServiceNetworkProfile. +func (c CloudServiceNetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "loadBalancerConfigurations", c.LoadBalancerConfigurations) + populate(objectMap, "slotType", c.SlotType) + populate(objectMap, "swappableCloudService", c.SwappableCloudService) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceNetworkProfile. +func (c *CloudServiceNetworkProfile) UnmarshalJSON(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 "loadBalancerConfigurations": + err = unpopulate(val, "LoadBalancerConfigurations", &c.LoadBalancerConfigurations) + delete(rawMsg, key) + case "slotType": + err = unpopulate(val, "SlotType", &c.SlotType) + delete(rawMsg, key) + case "swappableCloudService": + err = unpopulate(val, "SwappableCloudService", &c.SwappableCloudService) + 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 CloudServiceOsProfile. +func (c CloudServiceOsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secrets", c.Secrets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceOsProfile. +func (c *CloudServiceOsProfile) UnmarshalJSON(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 "secrets": + err = unpopulate(val, "Secrets", &c.Secrets) + 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 CloudServiceProperties. +func (c CloudServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowModelOverride", c.AllowModelOverride) + populate(objectMap, "configuration", c.Configuration) + populate(objectMap, "configurationUrl", c.ConfigurationURL) + populate(objectMap, "extensionProfile", c.ExtensionProfile) + populate(objectMap, "networkProfile", c.NetworkProfile) + populate(objectMap, "osProfile", c.OSProfile) + populate(objectMap, "packageUrl", c.PackageURL) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "roleProfile", c.RoleProfile) + populate(objectMap, "startCloudService", c.StartCloudService) + populate(objectMap, "uniqueId", c.UniqueID) + populate(objectMap, "upgradeMode", c.UpgradeMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceProperties. +func (c *CloudServiceProperties) UnmarshalJSON(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 "allowModelOverride": + err = unpopulate(val, "AllowModelOverride", &c.AllowModelOverride) + delete(rawMsg, key) + case "configuration": + err = unpopulate(val, "Configuration", &c.Configuration) + delete(rawMsg, key) + case "configurationUrl": + err = unpopulate(val, "ConfigurationURL", &c.ConfigurationURL) + delete(rawMsg, key) + case "extensionProfile": + err = unpopulate(val, "ExtensionProfile", &c.ExtensionProfile) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &c.NetworkProfile) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &c.OSProfile) + delete(rawMsg, key) + case "packageUrl": + err = unpopulate(val, "PackageURL", &c.PackageURL) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "roleProfile": + err = unpopulate(val, "RoleProfile", &c.RoleProfile) + delete(rawMsg, key) + case "startCloudService": + err = unpopulate(val, "StartCloudService", &c.StartCloudService) + delete(rawMsg, key) + case "uniqueId": + err = unpopulate(val, "UniqueID", &c.UniqueID) + delete(rawMsg, key) + case "upgradeMode": + err = unpopulate(val, "UpgradeMode", &c.UpgradeMode) + 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 CloudServiceRole. +func (c CloudServiceRole) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceRole. +func (c *CloudServiceRole) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &c.Location) + 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 "sku": + err = unpopulate(val, "SKU", &c.SKU) + 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 CloudServiceRoleListResult. +func (c CloudServiceRoleListResult) 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 CloudServiceRoleListResult. +func (c *CloudServiceRoleListResult) UnmarshalJSON(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 CloudServiceRoleProfile. +func (c CloudServiceRoleProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "roles", c.Roles) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceRoleProfile. +func (c *CloudServiceRoleProfile) UnmarshalJSON(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 "roles": + err = unpopulate(val, "Roles", &c.Roles) + 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 CloudServiceRoleProfileProperties. +func (c CloudServiceRoleProfileProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "sku", c.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceRoleProfileProperties. +func (c *CloudServiceRoleProfileProperties) UnmarshalJSON(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 "sku": + err = unpopulate(val, "SKU", &c.SKU) + 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 CloudServiceRoleProperties. +func (c CloudServiceRoleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uniqueId", c.UniqueID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceRoleProperties. +func (c *CloudServiceRoleProperties) UnmarshalJSON(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 "uniqueId": + err = unpopulate(val, "UniqueID", &c.UniqueID) + 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 CloudServiceRoleSKU. +func (c CloudServiceRoleSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", c.Capacity) + populate(objectMap, "name", c.Name) + populate(objectMap, "tier", c.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceRoleSKU. +func (c *CloudServiceRoleSKU) UnmarshalJSON(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 "capacity": + err = unpopulate(val, "Capacity", &c.Capacity) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &c.Tier) + 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 CloudServiceUpdate. +func (c CloudServiceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceUpdate. +func (c *CloudServiceUpdate) UnmarshalJSON(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 "tags": + err = unpopulate(val, "Tags", &c.Tags) + 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 CloudServiceVaultAndSecretReference. +func (c CloudServiceVaultAndSecretReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secretUrl", c.SecretURL) + populate(objectMap, "sourceVault", c.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceVaultAndSecretReference. +func (c *CloudServiceVaultAndSecretReference) UnmarshalJSON(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 "secretUrl": + err = unpopulate(val, "SecretURL", &c.SecretURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &c.SourceVault) + 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 CloudServiceVaultCertificate. +func (c CloudServiceVaultCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateUrl", c.CertificateURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceVaultCertificate. +func (c *CloudServiceVaultCertificate) UnmarshalJSON(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 "certificateUrl": + err = unpopulate(val, "CertificateURL", &c.CertificateURL) + 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 CloudServiceVaultSecretGroup. +func (c CloudServiceVaultSecretGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sourceVault", c.SourceVault) + populate(objectMap, "vaultCertificates", c.VaultCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudServiceVaultSecretGroup. +func (c *CloudServiceVaultSecretGroup) UnmarshalJSON(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 "sourceVault": + err = unpopulate(val, "SourceVault", &c.SourceVault) + delete(rawMsg, key) + case "vaultCertificates": + err = unpopulate(val, "VaultCertificates", &c.VaultCertificates) + 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 CommunityGallery. +func (c CommunityGallery) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", c.Identifier) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGallery. +func (c *CommunityGallery) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &c.Identifier) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + 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 "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 CommunityGalleryIdentifier. +func (c CommunityGalleryIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uniqueId", c.UniqueID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryIdentifier. +func (c *CommunityGalleryIdentifier) UnmarshalJSON(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 "uniqueId": + err = unpopulate(val, "UniqueID", &c.UniqueID) + 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 CommunityGalleryImage. +func (c CommunityGalleryImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", c.Identifier) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryImage. +func (c *CommunityGalleryImage) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &c.Identifier) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + 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 "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 CommunityGalleryImageIdentifier. +func (c CommunityGalleryImageIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "offer", c.Offer) + populate(objectMap, "publisher", c.Publisher) + populate(objectMap, "sku", c.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryImageIdentifier. +func (c *CommunityGalleryImageIdentifier) UnmarshalJSON(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 "offer": + err = unpopulate(val, "Offer", &c.Offer) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &c.Publisher) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + 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 CommunityGalleryImageList. +func (c CommunityGalleryImageList) 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 CommunityGalleryImageList. +func (c *CommunityGalleryImageList) UnmarshalJSON(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 CommunityGalleryImageProperties. +func (c CommunityGalleryImageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "architecture", c.Architecture) + populate(objectMap, "artifactTags", c.ArtifactTags) + populate(objectMap, "disallowed", c.Disallowed) + populate(objectMap, "disclaimer", c.Disclaimer) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", c.EndOfLifeDate) + populate(objectMap, "eula", c.Eula) + populate(objectMap, "features", c.Features) + populate(objectMap, "hyperVGeneration", c.HyperVGeneration) + populate(objectMap, "identifier", c.Identifier) + populate(objectMap, "osState", c.OSState) + populate(objectMap, "osType", c.OSType) + populate(objectMap, "privacyStatementUri", c.PrivacyStatementURI) + populate(objectMap, "purchasePlan", c.PurchasePlan) + populate(objectMap, "recommended", c.Recommended) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryImageProperties. +func (c *CommunityGalleryImageProperties) UnmarshalJSON(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 "architecture": + err = unpopulate(val, "Architecture", &c.Architecture) + delete(rawMsg, key) + case "artifactTags": + err = unpopulate(val, "ArtifactTags", &c.ArtifactTags) + delete(rawMsg, key) + case "disallowed": + err = unpopulate(val, "Disallowed", &c.Disallowed) + delete(rawMsg, key) + case "disclaimer": + err = unpopulate(val, "Disclaimer", &c.Disclaimer) + delete(rawMsg, key) + case "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &c.EndOfLifeDate) + delete(rawMsg, key) + case "eula": + err = unpopulate(val, "Eula", &c.Eula) + delete(rawMsg, key) + case "features": + err = unpopulate(val, "Features", &c.Features) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &c.HyperVGeneration) + delete(rawMsg, key) + case "identifier": + err = unpopulate(val, "Identifier", &c.Identifier) + delete(rawMsg, key) + case "osState": + err = unpopulate(val, "OSState", &c.OSState) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &c.OSType) + delete(rawMsg, key) + case "privacyStatementUri": + err = unpopulate(val, "PrivacyStatementURI", &c.PrivacyStatementURI) + delete(rawMsg, key) + case "purchasePlan": + err = unpopulate(val, "PurchasePlan", &c.PurchasePlan) + delete(rawMsg, key) + case "recommended": + err = unpopulate(val, "Recommended", &c.Recommended) + 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 CommunityGalleryImageVersion. +func (c CommunityGalleryImageVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", c.Identifier) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryImageVersion. +func (c *CommunityGalleryImageVersion) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &c.Identifier) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + 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 "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 CommunityGalleryImageVersionList. +func (c CommunityGalleryImageVersionList) 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 CommunityGalleryImageVersionList. +func (c *CommunityGalleryImageVersionList) UnmarshalJSON(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 CommunityGalleryImageVersionProperties. +func (c CommunityGalleryImageVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "artifactTags", c.ArtifactTags) + populate(objectMap, "disclaimer", c.Disclaimer) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", c.EndOfLifeDate) + populate(objectMap, "excludeFromLatest", c.ExcludeFromLatest) + populateDateTimeRFC3339(objectMap, "publishedDate", c.PublishedDate) + populate(objectMap, "storageProfile", c.StorageProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryImageVersionProperties. +func (c *CommunityGalleryImageVersionProperties) UnmarshalJSON(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 "artifactTags": + err = unpopulate(val, "ArtifactTags", &c.ArtifactTags) + delete(rawMsg, key) + case "disclaimer": + err = unpopulate(val, "Disclaimer", &c.Disclaimer) + delete(rawMsg, key) + case "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &c.EndOfLifeDate) + delete(rawMsg, key) + case "excludeFromLatest": + err = unpopulate(val, "ExcludeFromLatest", &c.ExcludeFromLatest) + delete(rawMsg, key) + case "publishedDate": + err = unpopulateDateTimeRFC3339(val, "PublishedDate", &c.PublishedDate) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &c.StorageProfile) + 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 CommunityGalleryInfo. +func (c CommunityGalleryInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityGalleryEnabled", c.CommunityGalleryEnabled) + populate(objectMap, "eula", c.Eula) + populate(objectMap, "publicNamePrefix", c.PublicNamePrefix) + populate(objectMap, "publicNames", c.PublicNames) + populate(objectMap, "publisherContact", c.PublisherContact) + populate(objectMap, "publisherUri", c.PublisherURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryInfo. +func (c *CommunityGalleryInfo) UnmarshalJSON(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 "communityGalleryEnabled": + err = unpopulate(val, "CommunityGalleryEnabled", &c.CommunityGalleryEnabled) + delete(rawMsg, key) + case "eula": + err = unpopulate(val, "Eula", &c.Eula) + delete(rawMsg, key) + case "publicNamePrefix": + err = unpopulate(val, "PublicNamePrefix", &c.PublicNamePrefix) + delete(rawMsg, key) + case "publicNames": + err = unpopulate(val, "PublicNames", &c.PublicNames) + delete(rawMsg, key) + case "publisherContact": + err = unpopulate(val, "PublisherContact", &c.PublisherContact) + delete(rawMsg, key) + case "publisherUri": + err = unpopulate(val, "PublisherURI", &c.PublisherURI) + 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 CommunityGalleryMetadata. +func (c CommunityGalleryMetadata) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "eula", c.Eula) + populate(objectMap, "privacyStatementUri", c.PrivacyStatementURI) + populate(objectMap, "publicNames", c.PublicNames) + populate(objectMap, "publisherContact", c.PublisherContact) + populate(objectMap, "publisherUri", c.PublisherURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryMetadata. +func (c *CommunityGalleryMetadata) UnmarshalJSON(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 "eula": + err = unpopulate(val, "Eula", &c.Eula) + delete(rawMsg, key) + case "privacyStatementUri": + err = unpopulate(val, "PrivacyStatementURI", &c.PrivacyStatementURI) + delete(rawMsg, key) + case "publicNames": + err = unpopulate(val, "PublicNames", &c.PublicNames) + delete(rawMsg, key) + case "publisherContact": + err = unpopulate(val, "PublisherContact", &c.PublisherContact) + delete(rawMsg, key) + case "publisherUri": + err = unpopulate(val, "PublisherURI", &c.PublisherURI) + 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 CommunityGalleryProperties. +func (c CommunityGalleryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "artifactTags", c.ArtifactTags) + populate(objectMap, "communityMetadata", c.CommunityMetadata) + populate(objectMap, "disclaimer", c.Disclaimer) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityGalleryProperties. +func (c *CommunityGalleryProperties) UnmarshalJSON(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 "artifactTags": + err = unpopulate(val, "ArtifactTags", &c.ArtifactTags) + delete(rawMsg, key) + case "communityMetadata": + err = unpopulate(val, "CommunityMetadata", &c.CommunityMetadata) + delete(rawMsg, key) + case "disclaimer": + err = unpopulate(val, "Disclaimer", &c.Disclaimer) + 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 CopyCompletionError. +func (c CopyCompletionError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errorCode", c.ErrorCode) + populate(objectMap, "errorMessage", c.ErrorMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CopyCompletionError. +func (c *CopyCompletionError) UnmarshalJSON(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) + } + 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) + populate(objectMap, "createOption", c.CreateOption) + populate(objectMap, "elasticSanResourceId", c.ElasticSanResourceID) + populate(objectMap, "galleryImageReference", c.GalleryImageReference) + populate(objectMap, "imageReference", c.ImageReference) + populate(objectMap, "logicalSectorSize", c.LogicalSectorSize) + populate(objectMap, "performancePlus", c.PerformancePlus) + populate(objectMap, "securityDataUri", c.SecurityDataURI) + populate(objectMap, "sourceResourceId", c.SourceResourceID) + populate(objectMap, "sourceUri", c.SourceURI) + populate(objectMap, "sourceUniqueId", c.SourceUniqueID) + populate(objectMap, "storageAccountId", c.StorageAccountID) + populate(objectMap, "uploadSizeBytes", c.UploadSizeBytes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreationData. +func (c *CreationData) UnmarshalJSON(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 "createOption": + err = unpopulate(val, "CreateOption", &c.CreateOption) + delete(rawMsg, key) + case "elasticSanResourceId": + err = unpopulate(val, "ElasticSanResourceID", &c.ElasticSanResourceID) + delete(rawMsg, key) + case "galleryImageReference": + err = unpopulate(val, "GalleryImageReference", &c.GalleryImageReference) + delete(rawMsg, key) + case "imageReference": + err = unpopulate(val, "ImageReference", &c.ImageReference) + delete(rawMsg, key) + case "logicalSectorSize": + err = unpopulate(val, "LogicalSectorSize", &c.LogicalSectorSize) + delete(rawMsg, key) + case "performancePlus": + err = unpopulate(val, "PerformancePlus", &c.PerformancePlus) + delete(rawMsg, key) + case "securityDataUri": + err = unpopulate(val, "SecurityDataURI", &c.SecurityDataURI) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &c.SourceResourceID) + delete(rawMsg, key) + case "sourceUri": + err = unpopulate(val, "SourceURI", &c.SourceURI) + delete(rawMsg, key) + case "sourceUniqueId": + err = unpopulate(val, "SourceUniqueID", &c.SourceUniqueID) + delete(rawMsg, key) + case "storageAccountId": + err = unpopulate(val, "StorageAccountID", &c.StorageAccountID) + delete(rawMsg, key) + case "uploadSizeBytes": + err = unpopulate(val, "UploadSizeBytes", &c.UploadSizeBytes) + 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 DataDisk. +func (d DataDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", d.Caching) + populate(objectMap, "createOption", d.CreateOption) + populate(objectMap, "deleteOption", d.DeleteOption) + populate(objectMap, "detachOption", d.DetachOption) + populate(objectMap, "diskIOPSReadWrite", d.DiskIOPSReadWrite) + populate(objectMap, "diskMBpsReadWrite", d.DiskMBpsReadWrite) + populate(objectMap, "diskSizeGB", d.DiskSizeGB) + populate(objectMap, "image", d.Image) + populate(objectMap, "lun", d.Lun) + populate(objectMap, "managedDisk", d.ManagedDisk) + populate(objectMap, "name", d.Name) + populate(objectMap, "toBeDetached", d.ToBeDetached) + populate(objectMap, "vhd", d.Vhd) + populate(objectMap, "writeAcceleratorEnabled", d.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDisk. +func (d *DataDisk) UnmarshalJSON(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 "caching": + err = unpopulate(val, "Caching", &d.Caching) + delete(rawMsg, key) + case "createOption": + err = unpopulate(val, "CreateOption", &d.CreateOption) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &d.DeleteOption) + delete(rawMsg, key) + case "detachOption": + err = unpopulate(val, "DetachOption", &d.DetachOption) + delete(rawMsg, key) + case "diskIOPSReadWrite": + err = unpopulate(val, "DiskIOPSReadWrite", &d.DiskIOPSReadWrite) + delete(rawMsg, key) + case "diskMBpsReadWrite": + err = unpopulate(val, "DiskMBpsReadWrite", &d.DiskMBpsReadWrite) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &d.DiskSizeGB) + delete(rawMsg, key) + case "image": + err = unpopulate(val, "Image", &d.Image) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &d.Lun) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &d.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "toBeDetached": + err = unpopulate(val, "ToBeDetached", &d.ToBeDetached) + delete(rawMsg, key) + case "vhd": + err = unpopulate(val, "Vhd", &d.Vhd) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &d.WriteAcceleratorEnabled) + 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 DataDiskImage. +func (d DataDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "lun", d.Lun) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDiskImage. +func (d *DataDiskImage) UnmarshalJSON(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 "lun": + err = unpopulate(val, "Lun", &d.Lun) + 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 DataDiskImageEncryption. +func (d DataDiskImageEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSetId", d.DiskEncryptionSetID) + populate(objectMap, "lun", d.Lun) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDiskImageEncryption. +func (d *DataDiskImageEncryption) UnmarshalJSON(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 "diskEncryptionSetId": + err = unpopulate(val, "DiskEncryptionSetID", &d.DiskEncryptionSetID) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &d.Lun) + 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 DataDisksToAttach. +func (d DataDisksToAttach) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskId", d.DiskID) + populate(objectMap, "lun", d.Lun) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDisksToAttach. +func (d *DataDisksToAttach) UnmarshalJSON(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 "diskId": + err = unpopulate(val, "DiskID", &d.DiskID) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &d.Lun) + 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 DataDisksToDetach. +func (d DataDisksToDetach) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "detachOption", d.DetachOption) + populate(objectMap, "diskId", d.DiskID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDisksToDetach. +func (d *DataDisksToDetach) UnmarshalJSON(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 "detachOption": + err = unpopulate(val, "DetachOption", &d.DetachOption) + delete(rawMsg, key) + case "diskId": + err = unpopulate(val, "DiskID", &d.DiskID) + 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 DedicatedHost. +func (d DedicatedHost) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "sku", d.SKU) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHost. +func (d *DedicatedHost) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &d.Location) + 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 "sku": + err = unpopulate(val, "SKU", &d.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + 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 DedicatedHostAllocatableVM. +func (d DedicatedHostAllocatableVM) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", d.Count) + populate(objectMap, "vmSize", d.VMSize) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostAllocatableVM. +func (d *DedicatedHostAllocatableVM) UnmarshalJSON(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 "count": + err = unpopulate(val, "Count", &d.Count) + delete(rawMsg, key) + case "vmSize": + err = unpopulate(val, "VMSize", &d.VMSize) + 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 DedicatedHostAvailableCapacity. +func (d DedicatedHostAvailableCapacity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocatableVMs", d.AllocatableVMs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostAvailableCapacity. +func (d *DedicatedHostAvailableCapacity) UnmarshalJSON(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 "allocatableVMs": + err = unpopulate(val, "AllocatableVMs", &d.AllocatableVMs) + 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 DedicatedHostGroup. +func (d DedicatedHostGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + populate(objectMap, "zones", d.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostGroup. +func (d *DedicatedHostGroup) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &d.Location) + 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 "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &d.Zones) + 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 DedicatedHostGroupInstanceView. +func (d DedicatedHostGroupInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hosts", d.Hosts) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostGroupInstanceView. +func (d *DedicatedHostGroupInstanceView) UnmarshalJSON(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 "hosts": + err = unpopulate(val, "Hosts", &d.Hosts) + 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 DedicatedHostGroupListResult. +func (d DedicatedHostGroupListResult) 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 DedicatedHostGroupListResult. +func (d *DedicatedHostGroupListResult) UnmarshalJSON(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 DedicatedHostGroupProperties. +func (d DedicatedHostGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalCapabilities", d.AdditionalCapabilities) + populate(objectMap, "hosts", d.Hosts) + populate(objectMap, "instanceView", d.InstanceView) + populate(objectMap, "platformFaultDomainCount", d.PlatformFaultDomainCount) + populate(objectMap, "supportAutomaticPlacement", d.SupportAutomaticPlacement) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostGroupProperties. +func (d *DedicatedHostGroupProperties) UnmarshalJSON(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 "additionalCapabilities": + err = unpopulate(val, "AdditionalCapabilities", &d.AdditionalCapabilities) + delete(rawMsg, key) + case "hosts": + err = unpopulate(val, "Hosts", &d.Hosts) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &d.InstanceView) + delete(rawMsg, key) + case "platformFaultDomainCount": + err = unpopulate(val, "PlatformFaultDomainCount", &d.PlatformFaultDomainCount) + delete(rawMsg, key) + case "supportAutomaticPlacement": + err = unpopulate(val, "SupportAutomaticPlacement", &d.SupportAutomaticPlacement) + 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 DedicatedHostGroupPropertiesAdditionalCapabilities. +func (d DedicatedHostGroupPropertiesAdditionalCapabilities) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ultraSSDEnabled", d.UltraSSDEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostGroupPropertiesAdditionalCapabilities. +func (d *DedicatedHostGroupPropertiesAdditionalCapabilities) UnmarshalJSON(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 "ultraSSDEnabled": + err = unpopulate(val, "UltraSSDEnabled", &d.UltraSSDEnabled) + 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 DedicatedHostGroupUpdate. +func (d DedicatedHostGroupUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "zones", d.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostGroupUpdate. +func (d *DedicatedHostGroupUpdate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &d.Zones) + 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 DedicatedHostInstanceView. +func (d DedicatedHostInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assetId", d.AssetID) + populate(objectMap, "availableCapacity", d.AvailableCapacity) + populate(objectMap, "statuses", d.Statuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostInstanceView. +func (d *DedicatedHostInstanceView) UnmarshalJSON(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 "assetId": + err = unpopulate(val, "AssetID", &d.AssetID) + delete(rawMsg, key) + case "availableCapacity": + err = unpopulate(val, "AvailableCapacity", &d.AvailableCapacity) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &d.Statuses) + 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 DedicatedHostInstanceViewWithName. +func (d DedicatedHostInstanceViewWithName) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assetId", d.AssetID) + populate(objectMap, "availableCapacity", d.AvailableCapacity) + populate(objectMap, "name", d.Name) + populate(objectMap, "statuses", d.Statuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostInstanceViewWithName. +func (d *DedicatedHostInstanceViewWithName) UnmarshalJSON(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 "assetId": + err = unpopulate(val, "AssetID", &d.AssetID) + delete(rawMsg, key) + case "availableCapacity": + err = unpopulate(val, "AvailableCapacity", &d.AvailableCapacity) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &d.Statuses) + 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 DedicatedHostListResult. +func (d DedicatedHostListResult) 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 DedicatedHostListResult. +func (d *DedicatedHostListResult) UnmarshalJSON(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 DedicatedHostProperties. +func (d DedicatedHostProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoReplaceOnFailure", d.AutoReplaceOnFailure) + populate(objectMap, "hostId", d.HostID) + populate(objectMap, "instanceView", d.InstanceView) + populate(objectMap, "licenseType", d.LicenseType) + populate(objectMap, "platformFaultDomain", d.PlatformFaultDomain) + populate(objectMap, "provisioningState", d.ProvisioningState) + populateDateTimeRFC3339(objectMap, "provisioningTime", d.ProvisioningTime) + populateDateTimeRFC3339(objectMap, "timeCreated", d.TimeCreated) + populate(objectMap, "virtualMachines", d.VirtualMachines) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostProperties. +func (d *DedicatedHostProperties) UnmarshalJSON(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 "autoReplaceOnFailure": + err = unpopulate(val, "AutoReplaceOnFailure", &d.AutoReplaceOnFailure) + delete(rawMsg, key) + case "hostId": + err = unpopulate(val, "HostID", &d.HostID) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &d.InstanceView) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &d.LicenseType) + delete(rawMsg, key) + case "platformFaultDomain": + err = unpopulate(val, "PlatformFaultDomain", &d.PlatformFaultDomain) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "provisioningTime": + err = unpopulateDateTimeRFC3339(val, "ProvisioningTime", &d.ProvisioningTime) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &d.TimeCreated) + delete(rawMsg, key) + case "virtualMachines": + err = unpopulate(val, "VirtualMachines", &d.VirtualMachines) + 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 DedicatedHostSizeListResult. +func (d DedicatedHostSizeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostSizeListResult. +func (d *DedicatedHostSizeListResult) UnmarshalJSON(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 "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 DedicatedHostUpdate. +func (d DedicatedHostUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "sku", d.SKU) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHostUpdate. +func (d *DedicatedHostUpdate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &d.SKU) + 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 DiagnosticsProfile. +func (d DiagnosticsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bootDiagnostics", d.BootDiagnostics) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiagnosticsProfile. +func (d *DiagnosticsProfile) UnmarshalJSON(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 "bootDiagnostics": + err = unpopulate(val, "BootDiagnostics", &d.BootDiagnostics) + 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 DiffDiskSettings. +func (d DiffDiskSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "option", d.Option) + populate(objectMap, "placement", d.Placement) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiffDiskSettings. +func (d *DiffDiskSettings) UnmarshalJSON(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 "option": + err = unpopulate(val, "Option", &d.Option) + delete(rawMsg, key) + case "placement": + err = unpopulate(val, "Placement", &d.Placement) + 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 Disallowed. +func (d Disallowed) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskTypes", d.DiskTypes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Disallowed. +func (d *Disallowed) UnmarshalJSON(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 "diskTypes": + err = unpopulate(val, "DiskTypes", &d.DiskTypes) + 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 DisallowedConfiguration. +func (d DisallowedConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vmDiskType", d.VMDiskType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DisallowedConfiguration. +func (d *DisallowedConfiguration) UnmarshalJSON(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 "vmDiskType": + err = unpopulate(val, "VMDiskType", &d.VMDiskType) + 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 Disk. +func (d Disk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocation", d.ExtendedLocation) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "managedBy", d.ManagedBy) + populate(objectMap, "managedByExtended", d.ManagedByExtended) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "sku", d.SKU) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + populate(objectMap, "zones", d.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Disk. +func (d *Disk) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &d.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &d.ManagedBy) + delete(rawMsg, key) + case "managedByExtended": + err = unpopulate(val, "ManagedByExtended", &d.ManagedByExtended) + 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 "sku": + err = unpopulate(val, "SKU", &d.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &d.Zones) + 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 DiskAccess. +func (d DiskAccess) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocation", d.ExtendedLocation) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskAccess. +func (d *DiskAccess) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &d.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + 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 "tags": + err = unpopulate(val, "Tags", &d.Tags) + 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 DiskAccessList. +func (d DiskAccessList) 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 DiskAccessList. +func (d *DiskAccessList) UnmarshalJSON(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 DiskAccessProperties. +func (d DiskAccessProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateEndpointConnections", d.PrivateEndpointConnections) + populate(objectMap, "provisioningState", d.ProvisioningState) + populateDateTimeRFC3339(objectMap, "timeCreated", d.TimeCreated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskAccessProperties. +func (d *DiskAccessProperties) UnmarshalJSON(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 "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &d.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &d.TimeCreated) + 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 DiskAccessUpdate. +func (d DiskAccessUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskAccessUpdate. +func (d *DiskAccessUpdate) UnmarshalJSON(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 "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 DiskEncryptionSet. +func (d DiskEncryptionSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "identity", d.Identity) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionSet. +func (d *DiskEncryptionSet) UnmarshalJSON(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 "identity": + err = unpopulate(val, "Identity", &d.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + 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 "tags": + err = unpopulate(val, "Tags", &d.Tags) + 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 DiskEncryptionSetList. +func (d DiskEncryptionSetList) 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 DiskEncryptionSetList. +func (d *DiskEncryptionSetList) UnmarshalJSON(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 DiskEncryptionSetParameters. +func (d DiskEncryptionSetParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionSetParameters. +func (d *DiskEncryptionSetParameters) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiskEncryptionSetUpdate. +func (d DiskEncryptionSetUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", d.Identity) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionSetUpdate. +func (d *DiskEncryptionSetUpdate) UnmarshalJSON(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 "identity": + err = unpopulate(val, "Identity", &d.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + 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 DiskEncryptionSetUpdateProperties. +func (d DiskEncryptionSetUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activeKey", d.ActiveKey) + populate(objectMap, "encryptionType", d.EncryptionType) + populate(objectMap, "federatedClientId", d.FederatedClientID) + populate(objectMap, "rotationToLatestKeyVersionEnabled", d.RotationToLatestKeyVersionEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionSetUpdateProperties. +func (d *DiskEncryptionSetUpdateProperties) UnmarshalJSON(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 "activeKey": + err = unpopulate(val, "ActiveKey", &d.ActiveKey) + delete(rawMsg, key) + case "encryptionType": + err = unpopulate(val, "EncryptionType", &d.EncryptionType) + delete(rawMsg, key) + case "federatedClientId": + err = unpopulate(val, "FederatedClientID", &d.FederatedClientID) + delete(rawMsg, key) + case "rotationToLatestKeyVersionEnabled": + err = unpopulate(val, "RotationToLatestKeyVersionEnabled", &d.RotationToLatestKeyVersionEnabled) + 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 DiskEncryptionSettings. +func (d DiskEncryptionSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionKey", d.DiskEncryptionKey) + populate(objectMap, "enabled", d.Enabled) + populate(objectMap, "keyEncryptionKey", d.KeyEncryptionKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionSettings. +func (d *DiskEncryptionSettings) UnmarshalJSON(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 "diskEncryptionKey": + err = unpopulate(val, "DiskEncryptionKey", &d.DiskEncryptionKey) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &d.Enabled) + delete(rawMsg, key) + case "keyEncryptionKey": + err = unpopulate(val, "KeyEncryptionKey", &d.KeyEncryptionKey) + 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 DiskImageEncryption. +func (d DiskImageEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSetId", d.DiskEncryptionSetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskImageEncryption. +func (d *DiskImageEncryption) UnmarshalJSON(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 "diskEncryptionSetId": + err = unpopulate(val, "DiskEncryptionSetID", &d.DiskEncryptionSetID) + 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 DiskInstanceView. +func (d DiskInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryptionSettings", d.EncryptionSettings) + populate(objectMap, "name", d.Name) + populate(objectMap, "statuses", d.Statuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskInstanceView. +func (d *DiskInstanceView) UnmarshalJSON(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 "encryptionSettings": + err = unpopulate(val, "EncryptionSettings", &d.EncryptionSettings) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &d.Statuses) + 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 DiskList. +func (d DiskList) 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 DiskList. +func (d *DiskList) UnmarshalJSON(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 DiskProperties. +func (d DiskProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "burstingEnabled", d.BurstingEnabled) + populateDateTimeRFC3339(objectMap, "burstingEnabledTime", d.BurstingEnabledTime) + populate(objectMap, "completionPercent", d.CompletionPercent) + populate(objectMap, "creationData", d.CreationData) + populate(objectMap, "dataAccessAuthMode", d.DataAccessAuthMode) + populate(objectMap, "diskAccessId", d.DiskAccessID) + populate(objectMap, "diskIOPSReadOnly", d.DiskIOPSReadOnly) + populate(objectMap, "diskIOPSReadWrite", d.DiskIOPSReadWrite) + populate(objectMap, "diskMBpsReadOnly", d.DiskMBpsReadOnly) + populate(objectMap, "diskMBpsReadWrite", d.DiskMBpsReadWrite) + populate(objectMap, "diskSizeBytes", d.DiskSizeBytes) + populate(objectMap, "diskSizeGB", d.DiskSizeGB) + populate(objectMap, "diskState", d.DiskState) + populate(objectMap, "encryption", d.Encryption) + populate(objectMap, "encryptionSettingsCollection", d.EncryptionSettingsCollection) + populate(objectMap, "hyperVGeneration", d.HyperVGeneration) + populateDateTimeRFC3339(objectMap, "LastOwnershipUpdateTime", d.LastOwnershipUpdateTime) + populate(objectMap, "maxShares", d.MaxShares) + populate(objectMap, "networkAccessPolicy", d.NetworkAccessPolicy) + populate(objectMap, "osType", d.OSType) + populate(objectMap, "optimizedForFrequentAttach", d.OptimizedForFrequentAttach) + populate(objectMap, "propertyUpdatesInProgress", d.PropertyUpdatesInProgress) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "publicNetworkAccess", d.PublicNetworkAccess) + populate(objectMap, "purchasePlan", d.PurchasePlan) + populate(objectMap, "securityProfile", d.SecurityProfile) + populate(objectMap, "shareInfo", d.ShareInfo) + populate(objectMap, "supportedCapabilities", d.SupportedCapabilities) + populate(objectMap, "supportsHibernation", d.SupportsHibernation) + populate(objectMap, "tier", d.Tier) + populateDateTimeRFC3339(objectMap, "timeCreated", d.TimeCreated) + populate(objectMap, "uniqueId", d.UniqueID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskProperties. +func (d *DiskProperties) UnmarshalJSON(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 "burstingEnabled": + err = unpopulate(val, "BurstingEnabled", &d.BurstingEnabled) + delete(rawMsg, key) + case "burstingEnabledTime": + err = unpopulateDateTimeRFC3339(val, "BurstingEnabledTime", &d.BurstingEnabledTime) + delete(rawMsg, key) + case "completionPercent": + err = unpopulate(val, "CompletionPercent", &d.CompletionPercent) + delete(rawMsg, key) + case "creationData": + err = unpopulate(val, "CreationData", &d.CreationData) + delete(rawMsg, key) + case "dataAccessAuthMode": + err = unpopulate(val, "DataAccessAuthMode", &d.DataAccessAuthMode) + delete(rawMsg, key) + case "diskAccessId": + err = unpopulate(val, "DiskAccessID", &d.DiskAccessID) + delete(rawMsg, key) + case "diskIOPSReadOnly": + err = unpopulate(val, "DiskIOPSReadOnly", &d.DiskIOPSReadOnly) + delete(rawMsg, key) + case "diskIOPSReadWrite": + err = unpopulate(val, "DiskIOPSReadWrite", &d.DiskIOPSReadWrite) + delete(rawMsg, key) + case "diskMBpsReadOnly": + err = unpopulate(val, "DiskMBpsReadOnly", &d.DiskMBpsReadOnly) + delete(rawMsg, key) + case "diskMBpsReadWrite": + err = unpopulate(val, "DiskMBpsReadWrite", &d.DiskMBpsReadWrite) + delete(rawMsg, key) + case "diskSizeBytes": + err = unpopulate(val, "DiskSizeBytes", &d.DiskSizeBytes) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &d.DiskSizeGB) + delete(rawMsg, key) + case "diskState": + err = unpopulate(val, "DiskState", &d.DiskState) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &d.Encryption) + delete(rawMsg, key) + case "encryptionSettingsCollection": + err = unpopulate(val, "EncryptionSettingsCollection", &d.EncryptionSettingsCollection) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &d.HyperVGeneration) + delete(rawMsg, key) + case "LastOwnershipUpdateTime": + err = unpopulateDateTimeRFC3339(val, "LastOwnershipUpdateTime", &d.LastOwnershipUpdateTime) + delete(rawMsg, key) + case "maxShares": + err = unpopulate(val, "MaxShares", &d.MaxShares) + delete(rawMsg, key) + case "networkAccessPolicy": + err = unpopulate(val, "NetworkAccessPolicy", &d.NetworkAccessPolicy) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &d.OSType) + delete(rawMsg, key) + case "optimizedForFrequentAttach": + err = unpopulate(val, "OptimizedForFrequentAttach", &d.OptimizedForFrequentAttach) + delete(rawMsg, key) + case "propertyUpdatesInProgress": + err = unpopulate(val, "PropertyUpdatesInProgress", &d.PropertyUpdatesInProgress) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &d.PublicNetworkAccess) + delete(rawMsg, key) + case "purchasePlan": + err = unpopulate(val, "PurchasePlan", &d.PurchasePlan) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &d.SecurityProfile) + delete(rawMsg, key) + case "shareInfo": + err = unpopulate(val, "ShareInfo", &d.ShareInfo) + delete(rawMsg, key) + case "supportedCapabilities": + err = unpopulate(val, "SupportedCapabilities", &d.SupportedCapabilities) + delete(rawMsg, key) + case "supportsHibernation": + err = unpopulate(val, "SupportsHibernation", &d.SupportsHibernation) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &d.Tier) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &d.TimeCreated) + delete(rawMsg, key) + case "uniqueId": + err = unpopulate(val, "UniqueID", &d.UniqueID) + 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 DiskPurchasePlan. +func (d DiskPurchasePlan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", d.Name) + populate(objectMap, "product", d.Product) + populate(objectMap, "promotionCode", d.PromotionCode) + populate(objectMap, "publisher", d.Publisher) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskPurchasePlan. +func (d *DiskPurchasePlan) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &d.Product) + delete(rawMsg, key) + case "promotionCode": + err = unpopulate(val, "PromotionCode", &d.PromotionCode) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &d.Publisher) + 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 DiskRestorePoint. +func (d DiskRestorePoint) 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 DiskRestorePoint. +func (d *DiskRestorePoint) UnmarshalJSON(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 DiskRestorePointAttributes. +func (d DiskRestorePointAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryption", d.Encryption) + populate(objectMap, "id", d.ID) + populate(objectMap, "sourceDiskRestorePoint", d.SourceDiskRestorePoint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskRestorePointAttributes. +func (d *DiskRestorePointAttributes) UnmarshalJSON(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 "encryption": + err = unpopulate(val, "Encryption", &d.Encryption) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "sourceDiskRestorePoint": + err = unpopulate(val, "SourceDiskRestorePoint", &d.SourceDiskRestorePoint) + 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 DiskRestorePointInstanceView. +func (d DiskRestorePointInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "replicationStatus", d.ReplicationStatus) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskRestorePointInstanceView. +func (d *DiskRestorePointInstanceView) UnmarshalJSON(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 "replicationStatus": + err = unpopulate(val, "ReplicationStatus", &d.ReplicationStatus) + 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 DiskRestorePointList. +func (d DiskRestorePointList) 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 DiskRestorePointList. +func (d *DiskRestorePointList) UnmarshalJSON(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 DiskRestorePointProperties. +func (d DiskRestorePointProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "completionPercent", d.CompletionPercent) + populate(objectMap, "diskAccessId", d.DiskAccessID) + populate(objectMap, "encryption", d.Encryption) + populate(objectMap, "familyId", d.FamilyID) + populate(objectMap, "hyperVGeneration", d.HyperVGeneration) + populate(objectMap, "networkAccessPolicy", d.NetworkAccessPolicy) + populate(objectMap, "osType", d.OSType) + populate(objectMap, "publicNetworkAccess", d.PublicNetworkAccess) + populate(objectMap, "purchasePlan", d.PurchasePlan) + populate(objectMap, "replicationState", d.ReplicationState) + populate(objectMap, "securityProfile", d.SecurityProfile) + populate(objectMap, "sourceResourceId", d.SourceResourceID) + populate(objectMap, "sourceResourceLocation", d.SourceResourceLocation) + populate(objectMap, "sourceUniqueId", d.SourceUniqueID) + populate(objectMap, "supportedCapabilities", d.SupportedCapabilities) + populate(objectMap, "supportsHibernation", d.SupportsHibernation) + populateDateTimeRFC3339(objectMap, "timeCreated", d.TimeCreated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskRestorePointProperties. +func (d *DiskRestorePointProperties) UnmarshalJSON(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 "completionPercent": + err = unpopulate(val, "CompletionPercent", &d.CompletionPercent) + delete(rawMsg, key) + case "diskAccessId": + err = unpopulate(val, "DiskAccessID", &d.DiskAccessID) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &d.Encryption) + delete(rawMsg, key) + case "familyId": + err = unpopulate(val, "FamilyID", &d.FamilyID) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &d.HyperVGeneration) + delete(rawMsg, key) + case "networkAccessPolicy": + err = unpopulate(val, "NetworkAccessPolicy", &d.NetworkAccessPolicy) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &d.OSType) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &d.PublicNetworkAccess) + delete(rawMsg, key) + case "purchasePlan": + err = unpopulate(val, "PurchasePlan", &d.PurchasePlan) + delete(rawMsg, key) + case "replicationState": + err = unpopulate(val, "ReplicationState", &d.ReplicationState) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &d.SecurityProfile) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &d.SourceResourceID) + delete(rawMsg, key) + case "sourceResourceLocation": + err = unpopulate(val, "SourceResourceLocation", &d.SourceResourceLocation) + delete(rawMsg, key) + case "sourceUniqueId": + err = unpopulate(val, "SourceUniqueID", &d.SourceUniqueID) + delete(rawMsg, key) + case "supportedCapabilities": + err = unpopulate(val, "SupportedCapabilities", &d.SupportedCapabilities) + delete(rawMsg, key) + case "supportsHibernation": + err = unpopulate(val, "SupportsHibernation", &d.SupportsHibernation) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &d.TimeCreated) + 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 DiskRestorePointReplicationStatus. +func (d DiskRestorePointReplicationStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "completionPercent", d.CompletionPercent) + populate(objectMap, "status", d.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskRestorePointReplicationStatus. +func (d *DiskRestorePointReplicationStatus) UnmarshalJSON(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 "completionPercent": + err = unpopulate(val, "CompletionPercent", &d.CompletionPercent) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &d.Status) + 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 DiskSKU. +func (d DiskSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", d.Name) + populate(objectMap, "tier", d.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskSKU. +func (d *DiskSKU) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &d.Tier) + 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 DiskSecurityProfile. +func (d DiskSecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secureVMDiskEncryptionSetId", d.SecureVMDiskEncryptionSetID) + populate(objectMap, "securityType", d.SecurityType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskSecurityProfile. +func (d *DiskSecurityProfile) UnmarshalJSON(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 "secureVMDiskEncryptionSetId": + err = unpopulate(val, "SecureVMDiskEncryptionSetID", &d.SecureVMDiskEncryptionSetID) + delete(rawMsg, key) + case "securityType": + err = unpopulate(val, "SecurityType", &d.SecurityType) + 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 DiskUpdate. +func (d DiskUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "sku", d.SKU) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskUpdate. +func (d *DiskUpdate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &d.SKU) + 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 DiskUpdateProperties. +func (d DiskUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "burstingEnabled", d.BurstingEnabled) + populate(objectMap, "dataAccessAuthMode", d.DataAccessAuthMode) + populate(objectMap, "diskAccessId", d.DiskAccessID) + populate(objectMap, "diskIOPSReadOnly", d.DiskIOPSReadOnly) + populate(objectMap, "diskIOPSReadWrite", d.DiskIOPSReadWrite) + populate(objectMap, "diskMBpsReadOnly", d.DiskMBpsReadOnly) + populate(objectMap, "diskMBpsReadWrite", d.DiskMBpsReadWrite) + populate(objectMap, "diskSizeGB", d.DiskSizeGB) + populate(objectMap, "encryption", d.Encryption) + populate(objectMap, "encryptionSettingsCollection", d.EncryptionSettingsCollection) + populate(objectMap, "maxShares", d.MaxShares) + populate(objectMap, "networkAccessPolicy", d.NetworkAccessPolicy) + populate(objectMap, "osType", d.OSType) + populate(objectMap, "optimizedForFrequentAttach", d.OptimizedForFrequentAttach) + populate(objectMap, "propertyUpdatesInProgress", d.PropertyUpdatesInProgress) + populate(objectMap, "publicNetworkAccess", d.PublicNetworkAccess) + populate(objectMap, "purchasePlan", d.PurchasePlan) + populate(objectMap, "supportedCapabilities", d.SupportedCapabilities) + populate(objectMap, "supportsHibernation", d.SupportsHibernation) + populate(objectMap, "tier", d.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskUpdateProperties. +func (d *DiskUpdateProperties) UnmarshalJSON(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 "burstingEnabled": + err = unpopulate(val, "BurstingEnabled", &d.BurstingEnabled) + delete(rawMsg, key) + case "dataAccessAuthMode": + err = unpopulate(val, "DataAccessAuthMode", &d.DataAccessAuthMode) + delete(rawMsg, key) + case "diskAccessId": + err = unpopulate(val, "DiskAccessID", &d.DiskAccessID) + delete(rawMsg, key) + case "diskIOPSReadOnly": + err = unpopulate(val, "DiskIOPSReadOnly", &d.DiskIOPSReadOnly) + delete(rawMsg, key) + case "diskIOPSReadWrite": + err = unpopulate(val, "DiskIOPSReadWrite", &d.DiskIOPSReadWrite) + delete(rawMsg, key) + case "diskMBpsReadOnly": + err = unpopulate(val, "DiskMBpsReadOnly", &d.DiskMBpsReadOnly) + delete(rawMsg, key) + case "diskMBpsReadWrite": + err = unpopulate(val, "DiskMBpsReadWrite", &d.DiskMBpsReadWrite) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &d.DiskSizeGB) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &d.Encryption) + delete(rawMsg, key) + case "encryptionSettingsCollection": + err = unpopulate(val, "EncryptionSettingsCollection", &d.EncryptionSettingsCollection) + delete(rawMsg, key) + case "maxShares": + err = unpopulate(val, "MaxShares", &d.MaxShares) + delete(rawMsg, key) + case "networkAccessPolicy": + err = unpopulate(val, "NetworkAccessPolicy", &d.NetworkAccessPolicy) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &d.OSType) + delete(rawMsg, key) + case "optimizedForFrequentAttach": + err = unpopulate(val, "OptimizedForFrequentAttach", &d.OptimizedForFrequentAttach) + delete(rawMsg, key) + case "propertyUpdatesInProgress": + err = unpopulate(val, "PropertyUpdatesInProgress", &d.PropertyUpdatesInProgress) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &d.PublicNetworkAccess) + delete(rawMsg, key) + case "purchasePlan": + err = unpopulate(val, "PurchasePlan", &d.PurchasePlan) + delete(rawMsg, key) + case "supportedCapabilities": + err = unpopulate(val, "SupportedCapabilities", &d.SupportedCapabilities) + delete(rawMsg, key) + case "supportsHibernation": + err = unpopulate(val, "SupportsHibernation", &d.SupportsHibernation) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &d.Tier) + 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, "diskEncryptionSetId", e.DiskEncryptionSetID) + populate(objectMap, "type", e.Type) + 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 "diskEncryptionSetId": + err = unpopulate(val, "DiskEncryptionSetID", &e.DiskEncryptionSetID) + 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 EncryptionIdentity. +func (e EncryptionIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "userAssignedIdentityResourceId", e.UserAssignedIdentityResourceID) + 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 "userAssignedIdentityResourceId": + err = unpopulate(val, "UserAssignedIdentityResourceID", &e.UserAssignedIdentityResourceID) + 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 EncryptionImages. +func (e EncryptionImages) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDiskImages", e.DataDiskImages) + populate(objectMap, "osDiskImage", e.OSDiskImage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionImages. +func (e *EncryptionImages) UnmarshalJSON(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 "dataDiskImages": + err = unpopulate(val, "DataDiskImages", &e.DataDiskImages) + delete(rawMsg, key) + case "osDiskImage": + err = unpopulate(val, "OSDiskImage", &e.OSDiskImage) + 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 EncryptionSetIdentity. +func (e EncryptionSetIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", e.PrincipalID) + populate(objectMap, "tenantId", e.TenantID) + populate(objectMap, "type", e.Type) + populate(objectMap, "userAssignedIdentities", e.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionSetIdentity. +func (e *EncryptionSetIdentity) UnmarshalJSON(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 "principalId": + err = unpopulate(val, "PrincipalID", &e.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &e.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &e.UserAssignedIdentities) + 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 EncryptionSetProperties. +func (e EncryptionSetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activeKey", e.ActiveKey) + populate(objectMap, "autoKeyRotationError", e.AutoKeyRotationError) + populate(objectMap, "encryptionType", e.EncryptionType) + populate(objectMap, "federatedClientId", e.FederatedClientID) + populateDateTimeRFC3339(objectMap, "lastKeyRotationTimestamp", e.LastKeyRotationTimestamp) + populate(objectMap, "previousKeys", e.PreviousKeys) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "rotationToLatestKeyVersionEnabled", e.RotationToLatestKeyVersionEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionSetProperties. +func (e *EncryptionSetProperties) UnmarshalJSON(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 "activeKey": + err = unpopulate(val, "ActiveKey", &e.ActiveKey) + delete(rawMsg, key) + case "autoKeyRotationError": + err = unpopulate(val, "AutoKeyRotationError", &e.AutoKeyRotationError) + delete(rawMsg, key) + case "encryptionType": + err = unpopulate(val, "EncryptionType", &e.EncryptionType) + delete(rawMsg, key) + case "federatedClientId": + err = unpopulate(val, "FederatedClientID", &e.FederatedClientID) + delete(rawMsg, key) + case "lastKeyRotationTimestamp": + err = unpopulateDateTimeRFC3339(val, "LastKeyRotationTimestamp", &e.LastKeyRotationTimestamp) + delete(rawMsg, key) + case "previousKeys": + err = unpopulate(val, "PreviousKeys", &e.PreviousKeys) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "rotationToLatestKeyVersionEnabled": + err = unpopulate(val, "RotationToLatestKeyVersionEnabled", &e.RotationToLatestKeyVersionEnabled) + 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 EncryptionSettingsCollection. +func (e EncryptionSettingsCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", e.Enabled) + populate(objectMap, "encryptionSettings", e.EncryptionSettings) + populate(objectMap, "encryptionSettingsVersion", e.EncryptionSettingsVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionSettingsCollection. +func (e *EncryptionSettingsCollection) UnmarshalJSON(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 "encryptionSettings": + err = unpopulate(val, "EncryptionSettings", &e.EncryptionSettings) + delete(rawMsg, key) + case "encryptionSettingsVersion": + err = unpopulate(val, "EncryptionSettingsVersion", &e.EncryptionSettingsVersion) + 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 EncryptionSettingsElement. +func (e EncryptionSettingsElement) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionKey", e.DiskEncryptionKey) + populate(objectMap, "keyEncryptionKey", e.KeyEncryptionKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionSettingsElement. +func (e *EncryptionSettingsElement) UnmarshalJSON(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 "diskEncryptionKey": + err = unpopulate(val, "DiskEncryptionKey", &e.DiskEncryptionKey) + delete(rawMsg, key) + case "keyEncryptionKey": + err = unpopulate(val, "KeyEncryptionKey", &e.KeyEncryptionKey) + 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 Extension. +func (e Extension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Extension. +func (e *Extension) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 Gallery. +func (g Gallery) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "location", g.Location) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Gallery. +func (g *Gallery) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &g.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryApplication. +func (g GalleryApplication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "location", g.Location) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplication. +func (g *GalleryApplication) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &g.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryApplicationCustomAction. +func (g GalleryApplicationCustomAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", g.Description) + populate(objectMap, "name", g.Name) + populate(objectMap, "parameters", g.Parameters) + populate(objectMap, "script", g.Script) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationCustomAction. +func (g *GalleryApplicationCustomAction) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &g.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, "Parameters", &g.Parameters) + delete(rawMsg, key) + case "script": + err = unpopulate(val, "Script", &g.Script) + 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 GalleryApplicationCustomActionParameter. +func (g GalleryApplicationCustomActionParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultValue", g.DefaultValue) + populate(objectMap, "description", g.Description) + populate(objectMap, "name", g.Name) + populate(objectMap, "required", g.Required) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationCustomActionParameter. +func (g *GalleryApplicationCustomActionParameter) UnmarshalJSON(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 "defaultValue": + err = unpopulate(val, "DefaultValue", &g.DefaultValue) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &g.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "required": + err = unpopulate(val, "Required", &g.Required) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryApplicationList. +func (g GalleryApplicationList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationList. +func (g *GalleryApplicationList) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + 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 GalleryApplicationProperties. +func (g GalleryApplicationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customActions", g.CustomActions) + populate(objectMap, "description", g.Description) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", g.EndOfLifeDate) + populate(objectMap, "eula", g.Eula) + populate(objectMap, "privacyStatementUri", g.PrivacyStatementURI) + populate(objectMap, "releaseNoteUri", g.ReleaseNoteURI) + populate(objectMap, "supportedOSType", g.SupportedOSType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationProperties. +func (g *GalleryApplicationProperties) UnmarshalJSON(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 "customActions": + err = unpopulate(val, "CustomActions", &g.CustomActions) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &g.Description) + delete(rawMsg, key) + case "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &g.EndOfLifeDate) + delete(rawMsg, key) + case "eula": + err = unpopulate(val, "Eula", &g.Eula) + delete(rawMsg, key) + case "privacyStatementUri": + err = unpopulate(val, "PrivacyStatementURI", &g.PrivacyStatementURI) + delete(rawMsg, key) + case "releaseNoteUri": + err = unpopulate(val, "ReleaseNoteURI", &g.ReleaseNoteURI) + delete(rawMsg, key) + case "supportedOSType": + err = unpopulate(val, "SupportedOSType", &g.SupportedOSType) + 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 GalleryApplicationUpdate. +func (g GalleryApplicationUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationUpdate. +func (g *GalleryApplicationUpdate) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryApplicationVersion. +func (g GalleryApplicationVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "location", g.Location) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationVersion. +func (g *GalleryApplicationVersion) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &g.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryApplicationVersionList. +func (g GalleryApplicationVersionList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationVersionList. +func (g *GalleryApplicationVersionList) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + 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 GalleryApplicationVersionProperties. +func (g GalleryApplicationVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", g.ProvisioningState) + populate(objectMap, "publishingProfile", g.PublishingProfile) + populate(objectMap, "replicationStatus", g.ReplicationStatus) + populate(objectMap, "safetyProfile", g.SafetyProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationVersionProperties. +func (g *GalleryApplicationVersionProperties) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &g.ProvisioningState) + delete(rawMsg, key) + case "publishingProfile": + err = unpopulate(val, "PublishingProfile", &g.PublishingProfile) + delete(rawMsg, key) + case "replicationStatus": + err = unpopulate(val, "ReplicationStatus", &g.ReplicationStatus) + delete(rawMsg, key) + case "safetyProfile": + err = unpopulate(val, "SafetyProfile", &g.SafetyProfile) + 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 GalleryApplicationVersionPublishingProfile. +func (g GalleryApplicationVersionPublishingProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "advancedSettings", g.AdvancedSettings) + populate(objectMap, "customActions", g.CustomActions) + populate(objectMap, "enableHealthCheck", g.EnableHealthCheck) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", g.EndOfLifeDate) + populate(objectMap, "excludeFromLatest", g.ExcludeFromLatest) + populate(objectMap, "manageActions", g.ManageActions) + populateDateTimeRFC3339(objectMap, "publishedDate", g.PublishedDate) + populate(objectMap, "replicaCount", g.ReplicaCount) + populate(objectMap, "replicationMode", g.ReplicationMode) + populate(objectMap, "settings", g.Settings) + populate(objectMap, "source", g.Source) + populate(objectMap, "storageAccountType", g.StorageAccountType) + populate(objectMap, "targetExtendedLocations", g.TargetExtendedLocations) + populate(objectMap, "targetRegions", g.TargetRegions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationVersionPublishingProfile. +func (g *GalleryApplicationVersionPublishingProfile) UnmarshalJSON(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 "advancedSettings": + err = unpopulate(val, "AdvancedSettings", &g.AdvancedSettings) + delete(rawMsg, key) + case "customActions": + err = unpopulate(val, "CustomActions", &g.CustomActions) + delete(rawMsg, key) + case "enableHealthCheck": + err = unpopulate(val, "EnableHealthCheck", &g.EnableHealthCheck) + delete(rawMsg, key) + case "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &g.EndOfLifeDate) + delete(rawMsg, key) + case "excludeFromLatest": + err = unpopulate(val, "ExcludeFromLatest", &g.ExcludeFromLatest) + delete(rawMsg, key) + case "manageActions": + err = unpopulate(val, "ManageActions", &g.ManageActions) + delete(rawMsg, key) + case "publishedDate": + err = unpopulateDateTimeRFC3339(val, "PublishedDate", &g.PublishedDate) + delete(rawMsg, key) + case "replicaCount": + err = unpopulate(val, "ReplicaCount", &g.ReplicaCount) + delete(rawMsg, key) + case "replicationMode": + err = unpopulate(val, "ReplicationMode", &g.ReplicationMode) + delete(rawMsg, key) + case "settings": + err = unpopulate(val, "Settings", &g.Settings) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &g.Source) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &g.StorageAccountType) + delete(rawMsg, key) + case "targetExtendedLocations": + err = unpopulate(val, "TargetExtendedLocations", &g.TargetExtendedLocations) + delete(rawMsg, key) + case "targetRegions": + err = unpopulate(val, "TargetRegions", &g.TargetRegions) + 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 GalleryApplicationVersionSafetyProfile. +func (g GalleryApplicationVersionSafetyProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowDeletionOfReplicatedLocations", g.AllowDeletionOfReplicatedLocations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationVersionSafetyProfile. +func (g *GalleryApplicationVersionSafetyProfile) UnmarshalJSON(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 "allowDeletionOfReplicatedLocations": + err = unpopulate(val, "AllowDeletionOfReplicatedLocations", &g.AllowDeletionOfReplicatedLocations) + 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 GalleryApplicationVersionUpdate. +func (g GalleryApplicationVersionUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryApplicationVersionUpdate. +func (g *GalleryApplicationVersionUpdate) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryArtifactPublishingProfileBase. +func (g GalleryArtifactPublishingProfileBase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", g.EndOfLifeDate) + populate(objectMap, "excludeFromLatest", g.ExcludeFromLatest) + populateDateTimeRFC3339(objectMap, "publishedDate", g.PublishedDate) + populate(objectMap, "replicaCount", g.ReplicaCount) + populate(objectMap, "replicationMode", g.ReplicationMode) + populate(objectMap, "storageAccountType", g.StorageAccountType) + populate(objectMap, "targetExtendedLocations", g.TargetExtendedLocations) + populate(objectMap, "targetRegions", g.TargetRegions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryArtifactPublishingProfileBase. +func (g *GalleryArtifactPublishingProfileBase) UnmarshalJSON(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 "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &g.EndOfLifeDate) + delete(rawMsg, key) + case "excludeFromLatest": + err = unpopulate(val, "ExcludeFromLatest", &g.ExcludeFromLatest) + delete(rawMsg, key) + case "publishedDate": + err = unpopulateDateTimeRFC3339(val, "PublishedDate", &g.PublishedDate) + delete(rawMsg, key) + case "replicaCount": + err = unpopulate(val, "ReplicaCount", &g.ReplicaCount) + delete(rawMsg, key) + case "replicationMode": + err = unpopulate(val, "ReplicationMode", &g.ReplicationMode) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &g.StorageAccountType) + delete(rawMsg, key) + case "targetExtendedLocations": + err = unpopulate(val, "TargetExtendedLocations", &g.TargetExtendedLocations) + delete(rawMsg, key) + case "targetRegions": + err = unpopulate(val, "TargetRegions", &g.TargetRegions) + 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 GalleryArtifactSafetyProfileBase. +func (g GalleryArtifactSafetyProfileBase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowDeletionOfReplicatedLocations", g.AllowDeletionOfReplicatedLocations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryArtifactSafetyProfileBase. +func (g *GalleryArtifactSafetyProfileBase) UnmarshalJSON(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 "allowDeletionOfReplicatedLocations": + err = unpopulate(val, "AllowDeletionOfReplicatedLocations", &g.AllowDeletionOfReplicatedLocations) + 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 GalleryArtifactSource. +func (g GalleryArtifactSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "managedImage", g.ManagedImage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryArtifactSource. +func (g *GalleryArtifactSource) UnmarshalJSON(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 "managedImage": + err = unpopulate(val, "ManagedImage", &g.ManagedImage) + 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 GalleryArtifactVersionFullSource. +func (g GalleryArtifactVersionFullSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityGalleryImageId", g.CommunityGalleryImageID) + populate(objectMap, "id", g.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryArtifactVersionFullSource. +func (g *GalleryArtifactVersionFullSource) UnmarshalJSON(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 "communityGalleryImageId": + err = unpopulate(val, "CommunityGalleryImageID", &g.CommunityGalleryImageID) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &g.ID) + 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 GalleryArtifactVersionSource. +func (g GalleryArtifactVersionSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryArtifactVersionSource. +func (g *GalleryArtifactVersionSource) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + 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 GalleryDataDiskImage. +func (g GalleryDataDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hostCaching", g.HostCaching) + populate(objectMap, "lun", g.Lun) + populate(objectMap, "sizeInGB", g.SizeInGB) + populate(objectMap, "source", g.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryDataDiskImage. +func (g *GalleryDataDiskImage) UnmarshalJSON(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 "hostCaching": + err = unpopulate(val, "HostCaching", &g.HostCaching) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &g.Lun) + delete(rawMsg, key) + case "sizeInGB": + err = unpopulate(val, "SizeInGB", &g.SizeInGB) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &g.Source) + 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 GalleryDiskImage. +func (g GalleryDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hostCaching", g.HostCaching) + populate(objectMap, "sizeInGB", g.SizeInGB) + populate(objectMap, "source", g.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryDiskImage. +func (g *GalleryDiskImage) UnmarshalJSON(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 "hostCaching": + err = unpopulate(val, "HostCaching", &g.HostCaching) + delete(rawMsg, key) + case "sizeInGB": + err = unpopulate(val, "SizeInGB", &g.SizeInGB) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &g.Source) + 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 GalleryDiskImageSource. +func (g GalleryDiskImageSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "storageAccountId", g.StorageAccountID) + populate(objectMap, "uri", g.URI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryDiskImageSource. +func (g *GalleryDiskImageSource) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "storageAccountId": + err = unpopulate(val, "StorageAccountID", &g.StorageAccountID) + delete(rawMsg, key) + case "uri": + err = unpopulate(val, "URI", &g.URI) + 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 GalleryExtendedLocation. +func (g GalleryExtendedLocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", g.Name) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryExtendedLocation. +func (g *GalleryExtendedLocation) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryIdentifier. +func (g GalleryIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uniqueName", g.UniqueName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryIdentifier. +func (g *GalleryIdentifier) UnmarshalJSON(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 "uniqueName": + err = unpopulate(val, "UniqueName", &g.UniqueName) + 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 GalleryImage. +func (g GalleryImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "location", g.Location) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImage. +func (g *GalleryImage) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &g.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryImageFeature. +func (g GalleryImageFeature) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", g.Name) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageFeature. +func (g *GalleryImageFeature) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + 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 GalleryImageIdentifier. +func (g GalleryImageIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "offer", g.Offer) + populate(objectMap, "publisher", g.Publisher) + populate(objectMap, "sku", g.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageIdentifier. +func (g *GalleryImageIdentifier) UnmarshalJSON(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 "offer": + err = unpopulate(val, "Offer", &g.Offer) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &g.Publisher) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &g.SKU) + 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 GalleryImageList. +func (g GalleryImageList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageList. +func (g *GalleryImageList) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + 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 GalleryImageProperties. +func (g GalleryImageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "architecture", g.Architecture) + populate(objectMap, "description", g.Description) + populate(objectMap, "disallowed", g.Disallowed) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", g.EndOfLifeDate) + populate(objectMap, "eula", g.Eula) + populate(objectMap, "features", g.Features) + populate(objectMap, "hyperVGeneration", g.HyperVGeneration) + populate(objectMap, "identifier", g.Identifier) + populate(objectMap, "osState", g.OSState) + populate(objectMap, "osType", g.OSType) + populate(objectMap, "privacyStatementUri", g.PrivacyStatementURI) + populate(objectMap, "provisioningState", g.ProvisioningState) + populate(objectMap, "purchasePlan", g.PurchasePlan) + populate(objectMap, "recommended", g.Recommended) + populate(objectMap, "releaseNoteUri", g.ReleaseNoteURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageProperties. +func (g *GalleryImageProperties) UnmarshalJSON(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 "architecture": + err = unpopulate(val, "Architecture", &g.Architecture) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &g.Description) + delete(rawMsg, key) + case "disallowed": + err = unpopulate(val, "Disallowed", &g.Disallowed) + delete(rawMsg, key) + case "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &g.EndOfLifeDate) + delete(rawMsg, key) + case "eula": + err = unpopulate(val, "Eula", &g.Eula) + delete(rawMsg, key) + case "features": + err = unpopulate(val, "Features", &g.Features) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &g.HyperVGeneration) + delete(rawMsg, key) + case "identifier": + err = unpopulate(val, "Identifier", &g.Identifier) + delete(rawMsg, key) + case "osState": + err = unpopulate(val, "OSState", &g.OSState) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &g.OSType) + delete(rawMsg, key) + case "privacyStatementUri": + err = unpopulate(val, "PrivacyStatementURI", &g.PrivacyStatementURI) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &g.ProvisioningState) + delete(rawMsg, key) + case "purchasePlan": + err = unpopulate(val, "PurchasePlan", &g.PurchasePlan) + delete(rawMsg, key) + case "recommended": + err = unpopulate(val, "Recommended", &g.Recommended) + delete(rawMsg, key) + case "releaseNoteUri": + err = unpopulate(val, "ReleaseNoteURI", &g.ReleaseNoteURI) + 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 GalleryImageUpdate. +func (g GalleryImageUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageUpdate. +func (g *GalleryImageUpdate) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryImageVersion. +func (g GalleryImageVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "location", g.Location) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersion. +func (g *GalleryImageVersion) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &g.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryImageVersionList. +func (g GalleryImageVersionList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersionList. +func (g *GalleryImageVersionList) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + 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 GalleryImageVersionProperties. +func (g GalleryImageVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", g.ProvisioningState) + populate(objectMap, "publishingProfile", g.PublishingProfile) + populate(objectMap, "replicationStatus", g.ReplicationStatus) + populate(objectMap, "safetyProfile", g.SafetyProfile) + populate(objectMap, "securityProfile", g.SecurityProfile) + populate(objectMap, "storageProfile", g.StorageProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersionProperties. +func (g *GalleryImageVersionProperties) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &g.ProvisioningState) + delete(rawMsg, key) + case "publishingProfile": + err = unpopulate(val, "PublishingProfile", &g.PublishingProfile) + delete(rawMsg, key) + case "replicationStatus": + err = unpopulate(val, "ReplicationStatus", &g.ReplicationStatus) + delete(rawMsg, key) + case "safetyProfile": + err = unpopulate(val, "SafetyProfile", &g.SafetyProfile) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &g.SecurityProfile) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &g.StorageProfile) + 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 GalleryImageVersionPublishingProfile. +func (g GalleryImageVersionPublishingProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", g.EndOfLifeDate) + populate(objectMap, "excludeFromLatest", g.ExcludeFromLatest) + populateDateTimeRFC3339(objectMap, "publishedDate", g.PublishedDate) + populate(objectMap, "replicaCount", g.ReplicaCount) + populate(objectMap, "replicationMode", g.ReplicationMode) + populate(objectMap, "storageAccountType", g.StorageAccountType) + populate(objectMap, "targetExtendedLocations", g.TargetExtendedLocations) + populate(objectMap, "targetRegions", g.TargetRegions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersionPublishingProfile. +func (g *GalleryImageVersionPublishingProfile) UnmarshalJSON(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 "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &g.EndOfLifeDate) + delete(rawMsg, key) + case "excludeFromLatest": + err = unpopulate(val, "ExcludeFromLatest", &g.ExcludeFromLatest) + delete(rawMsg, key) + case "publishedDate": + err = unpopulateDateTimeRFC3339(val, "PublishedDate", &g.PublishedDate) + delete(rawMsg, key) + case "replicaCount": + err = unpopulate(val, "ReplicaCount", &g.ReplicaCount) + delete(rawMsg, key) + case "replicationMode": + err = unpopulate(val, "ReplicationMode", &g.ReplicationMode) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &g.StorageAccountType) + delete(rawMsg, key) + case "targetExtendedLocations": + err = unpopulate(val, "TargetExtendedLocations", &g.TargetExtendedLocations) + delete(rawMsg, key) + case "targetRegions": + err = unpopulate(val, "TargetRegions", &g.TargetRegions) + 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 GalleryImageVersionSafetyProfile. +func (g GalleryImageVersionSafetyProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowDeletionOfReplicatedLocations", g.AllowDeletionOfReplicatedLocations) + populate(objectMap, "policyViolations", g.PolicyViolations) + populate(objectMap, "reportedForPolicyViolation", g.ReportedForPolicyViolation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersionSafetyProfile. +func (g *GalleryImageVersionSafetyProfile) UnmarshalJSON(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 "allowDeletionOfReplicatedLocations": + err = unpopulate(val, "AllowDeletionOfReplicatedLocations", &g.AllowDeletionOfReplicatedLocations) + delete(rawMsg, key) + case "policyViolations": + err = unpopulate(val, "PolicyViolations", &g.PolicyViolations) + delete(rawMsg, key) + case "reportedForPolicyViolation": + err = unpopulate(val, "ReportedForPolicyViolation", &g.ReportedForPolicyViolation) + 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 GalleryImageVersionStorageProfile. +func (g GalleryImageVersionStorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDiskImages", g.DataDiskImages) + populate(objectMap, "osDiskImage", g.OSDiskImage) + populate(objectMap, "source", g.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersionStorageProfile. +func (g *GalleryImageVersionStorageProfile) UnmarshalJSON(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 "dataDiskImages": + err = unpopulate(val, "DataDiskImages", &g.DataDiskImages) + delete(rawMsg, key) + case "osDiskImage": + err = unpopulate(val, "OSDiskImage", &g.OSDiskImage) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &g.Source) + 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 GalleryImageVersionUefiSettings. +func (g GalleryImageVersionUefiSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalSignatures", g.AdditionalSignatures) + populate(objectMap, "signatureTemplateNames", g.SignatureTemplateNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersionUefiSettings. +func (g *GalleryImageVersionUefiSettings) UnmarshalJSON(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 "additionalSignatures": + err = unpopulate(val, "AdditionalSignatures", &g.AdditionalSignatures) + delete(rawMsg, key) + case "signatureTemplateNames": + err = unpopulate(val, "SignatureTemplateNames", &g.SignatureTemplateNames) + 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 GalleryImageVersionUpdate. +func (g GalleryImageVersionUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryImageVersionUpdate. +func (g *GalleryImageVersionUpdate) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GalleryList. +func (g GalleryList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryList. +func (g *GalleryList) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + 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 GalleryOSDiskImage. +func (g GalleryOSDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hostCaching", g.HostCaching) + populate(objectMap, "sizeInGB", g.SizeInGB) + populate(objectMap, "source", g.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryOSDiskImage. +func (g *GalleryOSDiskImage) UnmarshalJSON(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 "hostCaching": + err = unpopulate(val, "HostCaching", &g.HostCaching) + delete(rawMsg, key) + case "sizeInGB": + err = unpopulate(val, "SizeInGB", &g.SizeInGB) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &g.Source) + 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 GalleryProperties. +func (g GalleryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", g.Description) + populate(objectMap, "identifier", g.Identifier) + populate(objectMap, "provisioningState", g.ProvisioningState) + populate(objectMap, "sharingProfile", g.SharingProfile) + populate(objectMap, "sharingStatus", g.SharingStatus) + populate(objectMap, "softDeletePolicy", g.SoftDeletePolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryProperties. +func (g *GalleryProperties) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &g.Description) + delete(rawMsg, key) + case "identifier": + err = unpopulate(val, "Identifier", &g.Identifier) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &g.ProvisioningState) + delete(rawMsg, key) + case "sharingProfile": + err = unpopulate(val, "SharingProfile", &g.SharingProfile) + delete(rawMsg, key) + case "sharingStatus": + err = unpopulate(val, "SharingStatus", &g.SharingStatus) + delete(rawMsg, key) + case "softDeletePolicy": + err = unpopulate(val, "SoftDeletePolicy", &g.SoftDeletePolicy) + 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 GalleryTargetExtendedLocation. +func (g GalleryTargetExtendedLocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryption", g.Encryption) + populate(objectMap, "extendedLocation", g.ExtendedLocation) + populate(objectMap, "extendedLocationReplicaCount", g.ExtendedLocationReplicaCount) + populate(objectMap, "name", g.Name) + populate(objectMap, "storageAccountType", g.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryTargetExtendedLocation. +func (g *GalleryTargetExtendedLocation) UnmarshalJSON(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 "encryption": + err = unpopulate(val, "Encryption", &g.Encryption) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &g.ExtendedLocation) + delete(rawMsg, key) + case "extendedLocationReplicaCount": + err = unpopulate(val, "ExtendedLocationReplicaCount", &g.ExtendedLocationReplicaCount) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &g.StorageAccountType) + 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 GalleryUpdate. +func (g GalleryUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "tags", g.Tags) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GalleryUpdate. +func (g *GalleryUpdate) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &g.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GrantAccessData. +func (g GrantAccessData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", g.Access) + populate(objectMap, "durationInSeconds", g.DurationInSeconds) + populate(objectMap, "fileFormat", g.FileFormat) + populate(objectMap, "getSecureVMGuestStateSAS", g.GetSecureVMGuestStateSAS) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GrantAccessData. +func (g *GrantAccessData) UnmarshalJSON(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 "access": + err = unpopulate(val, "Access", &g.Access) + delete(rawMsg, key) + case "durationInSeconds": + err = unpopulate(val, "DurationInSeconds", &g.DurationInSeconds) + delete(rawMsg, key) + case "fileFormat": + err = unpopulate(val, "FileFormat", &g.FileFormat) + delete(rawMsg, key) + case "getSecureVMGuestStateSAS": + err = unpopulate(val, "GetSecureVMGuestStateSAS", &g.GetSecureVMGuestStateSAS) + 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 HardwareProfile. +func (h HardwareProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vmSize", h.VMSize) + populate(objectMap, "vmSizeProperties", h.VMSizeProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HardwareProfile. +func (h *HardwareProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "vmSize": + err = unpopulate(val, "VMSize", &h.VMSize) + delete(rawMsg, key) + case "vmSizeProperties": + err = unpopulate(val, "VMSizeProperties", &h.VMSizeProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Image. +func (i Image) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocation", i.ExtendedLocation) + populate(objectMap, "id", i.ID) + populate(objectMap, "location", i.Location) + populate(objectMap, "name", i.Name) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "tags", i.Tags) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Image. +func (i *Image) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &i.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &i.Location) + 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 "tags": + err = unpopulate(val, "Tags", &i.Tags) + 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 ImageDataDisk. +func (i ImageDataDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobUri", i.BlobURI) + populate(objectMap, "caching", i.Caching) + populate(objectMap, "diskEncryptionSet", i.DiskEncryptionSet) + populate(objectMap, "diskSizeGB", i.DiskSizeGB) + populate(objectMap, "lun", i.Lun) + populate(objectMap, "managedDisk", i.ManagedDisk) + populate(objectMap, "snapshot", i.Snapshot) + populate(objectMap, "storageAccountType", i.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageDataDisk. +func (i *ImageDataDisk) UnmarshalJSON(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 "blobUri": + err = unpopulate(val, "BlobURI", &i.BlobURI) + delete(rawMsg, key) + case "caching": + err = unpopulate(val, "Caching", &i.Caching) + delete(rawMsg, key) + case "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &i.DiskEncryptionSet) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &i.DiskSizeGB) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &i.Lun) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &i.ManagedDisk) + delete(rawMsg, key) + case "snapshot": + err = unpopulate(val, "Snapshot", &i.Snapshot) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &i.StorageAccountType) + 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 ImageDeprecationStatus. +func (i ImageDeprecationStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alternativeOption", i.AlternativeOption) + populate(objectMap, "imageState", i.ImageState) + populateDateTimeRFC3339(objectMap, "scheduledDeprecationTime", i.ScheduledDeprecationTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageDeprecationStatus. +func (i *ImageDeprecationStatus) UnmarshalJSON(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 "alternativeOption": + err = unpopulate(val, "AlternativeOption", &i.AlternativeOption) + delete(rawMsg, key) + case "imageState": + err = unpopulate(val, "ImageState", &i.ImageState) + delete(rawMsg, key) + case "scheduledDeprecationTime": + err = unpopulateDateTimeRFC3339(val, "ScheduledDeprecationTime", &i.ScheduledDeprecationTime) + 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 ImageDisk. +func (i ImageDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobUri", i.BlobURI) + populate(objectMap, "caching", i.Caching) + populate(objectMap, "diskEncryptionSet", i.DiskEncryptionSet) + populate(objectMap, "diskSizeGB", i.DiskSizeGB) + populate(objectMap, "managedDisk", i.ManagedDisk) + populate(objectMap, "snapshot", i.Snapshot) + populate(objectMap, "storageAccountType", i.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageDisk. +func (i *ImageDisk) UnmarshalJSON(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 "blobUri": + err = unpopulate(val, "BlobURI", &i.BlobURI) + delete(rawMsg, key) + case "caching": + err = unpopulate(val, "Caching", &i.Caching) + delete(rawMsg, key) + case "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &i.DiskEncryptionSet) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &i.DiskSizeGB) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &i.ManagedDisk) + delete(rawMsg, key) + case "snapshot": + err = unpopulate(val, "Snapshot", &i.Snapshot) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &i.StorageAccountType) + 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 ImageDiskReference. +func (i ImageDiskReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityGalleryImageId", i.CommunityGalleryImageID) + populate(objectMap, "id", i.ID) + populate(objectMap, "lun", i.Lun) + populate(objectMap, "sharedGalleryImageId", i.SharedGalleryImageID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageDiskReference. +func (i *ImageDiskReference) UnmarshalJSON(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 "communityGalleryImageId": + err = unpopulate(val, "CommunityGalleryImageID", &i.CommunityGalleryImageID) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &i.Lun) + delete(rawMsg, key) + case "sharedGalleryImageId": + err = unpopulate(val, "SharedGalleryImageID", &i.SharedGalleryImageID) + 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 ImageListResult. +func (i ImageListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageListResult. +func (i *ImageListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 ImageOSDisk. +func (i ImageOSDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobUri", i.BlobURI) + populate(objectMap, "caching", i.Caching) + populate(objectMap, "diskEncryptionSet", i.DiskEncryptionSet) + populate(objectMap, "diskSizeGB", i.DiskSizeGB) + populate(objectMap, "managedDisk", i.ManagedDisk) + populate(objectMap, "osState", i.OSState) + populate(objectMap, "osType", i.OSType) + populate(objectMap, "snapshot", i.Snapshot) + populate(objectMap, "storageAccountType", i.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageOSDisk. +func (i *ImageOSDisk) UnmarshalJSON(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 "blobUri": + err = unpopulate(val, "BlobURI", &i.BlobURI) + delete(rawMsg, key) + case "caching": + err = unpopulate(val, "Caching", &i.Caching) + delete(rawMsg, key) + case "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &i.DiskEncryptionSet) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &i.DiskSizeGB) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &i.ManagedDisk) + delete(rawMsg, key) + case "osState": + err = unpopulate(val, "OSState", &i.OSState) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &i.OSType) + delete(rawMsg, key) + case "snapshot": + err = unpopulate(val, "Snapshot", &i.Snapshot) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &i.StorageAccountType) + 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 ImageProperties. +func (i ImageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hyperVGeneration", i.HyperVGeneration) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "sourceVirtualMachine", i.SourceVirtualMachine) + populate(objectMap, "storageProfile", i.StorageProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageProperties. +func (i *ImageProperties) UnmarshalJSON(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 "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &i.HyperVGeneration) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "sourceVirtualMachine": + err = unpopulate(val, "SourceVirtualMachine", &i.SourceVirtualMachine) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &i.StorageProfile) + 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 ImagePurchasePlan. +func (i ImagePurchasePlan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + populate(objectMap, "product", i.Product) + populate(objectMap, "publisher", i.Publisher) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImagePurchasePlan. +func (i *ImagePurchasePlan) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &i.Product) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &i.Publisher) + 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 ImageReference. +func (i ImageReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityGalleryImageId", i.CommunityGalleryImageID) + populate(objectMap, "exactVersion", i.ExactVersion) + populate(objectMap, "id", i.ID) + populate(objectMap, "offer", i.Offer) + populate(objectMap, "publisher", i.Publisher) + populate(objectMap, "sku", i.SKU) + populate(objectMap, "sharedGalleryImageId", i.SharedGalleryImageID) + populate(objectMap, "version", i.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageReference. +func (i *ImageReference) UnmarshalJSON(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 "communityGalleryImageId": + err = unpopulate(val, "CommunityGalleryImageID", &i.CommunityGalleryImageID) + delete(rawMsg, key) + case "exactVersion": + err = unpopulate(val, "ExactVersion", &i.ExactVersion) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "offer": + err = unpopulate(val, "Offer", &i.Offer) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &i.Publisher) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &i.SKU) + delete(rawMsg, key) + case "sharedGalleryImageId": + err = unpopulate(val, "SharedGalleryImageID", &i.SharedGalleryImageID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &i.Version) + 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 ImageStorageProfile. +func (i ImageStorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisks", i.DataDisks) + populate(objectMap, "osDisk", i.OSDisk) + populate(objectMap, "zoneResilient", i.ZoneResilient) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageStorageProfile. +func (i *ImageStorageProfile) UnmarshalJSON(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 "dataDisks": + err = unpopulate(val, "DataDisks", &i.DataDisks) + delete(rawMsg, key) + case "osDisk": + err = unpopulate(val, "OSDisk", &i.OSDisk) + delete(rawMsg, key) + case "zoneResilient": + err = unpopulate(val, "ZoneResilient", &i.ZoneResilient) + 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 ImageUpdate. +func (i ImageUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "tags", i.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageUpdate. +func (i *ImageUpdate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &i.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &i.Tags) + 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 ImageVersionSecurityProfile. +func (i ImageVersionSecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uefiSettings", i.UefiSettings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageVersionSecurityProfile. +func (i *ImageVersionSecurityProfile) UnmarshalJSON(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 "uefiSettings": + err = unpopulate(val, "UefiSettings", &i.UefiSettings) + 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 InnerError. +func (i InnerError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errordetail", i.Errordetail) + populate(objectMap, "exceptiontype", i.Exceptiontype) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerError. +func (i *InnerError) UnmarshalJSON(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 "errordetail": + err = unpopulate(val, "Errordetail", &i.Errordetail) + delete(rawMsg, key) + case "exceptiontype": + err = unpopulate(val, "Exceptiontype", &i.Exceptiontype) + 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 InstanceSKU. +func (i InstanceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + populate(objectMap, "tier", i.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InstanceSKU. +func (i *InstanceSKU) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &i.Tier) + 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 InstanceViewStatus. +func (i InstanceViewStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", i.Code) + populate(objectMap, "displayStatus", i.DisplayStatus) + populate(objectMap, "level", i.Level) + populate(objectMap, "message", i.Message) + populateDateTimeRFC3339(objectMap, "time", i.Time) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InstanceViewStatus. +func (i *InstanceViewStatus) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &i.Code) + delete(rawMsg, key) + case "displayStatus": + err = unpopulate(val, "DisplayStatus", &i.DisplayStatus) + delete(rawMsg, key) + case "level": + err = unpopulate(val, "Level", &i.Level) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &i.Message) + delete(rawMsg, key) + case "time": + err = unpopulateDateTimeRFC3339(val, "Time", &i.Time) + 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 InstanceViewStatusesSummary. +func (i InstanceViewStatusesSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "statusesSummary", i.StatusesSummary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InstanceViewStatusesSummary. +func (i *InstanceViewStatusesSummary) UnmarshalJSON(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 "statusesSummary": + err = unpopulate(val, "StatusesSummary", &i.StatusesSummary) + 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 KeyForDiskEncryptionSet. +func (k KeyForDiskEncryptionSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyUrl", k.KeyURL) + populate(objectMap, "sourceVault", k.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyForDiskEncryptionSet. +func (k *KeyForDiskEncryptionSet) UnmarshalJSON(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 "keyUrl": + err = unpopulate(val, "KeyURL", &k.KeyURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &k.SourceVault) + 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 KeyVaultAndKeyReference. +func (k KeyVaultAndKeyReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyUrl", k.KeyURL) + populate(objectMap, "sourceVault", k.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultAndKeyReference. +func (k *KeyVaultAndKeyReference) UnmarshalJSON(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 "keyUrl": + err = unpopulate(val, "KeyURL", &k.KeyURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &k.SourceVault) + 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 KeyVaultAndSecretReference. +func (k KeyVaultAndSecretReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secretUrl", k.SecretURL) + populate(objectMap, "sourceVault", k.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultAndSecretReference. +func (k *KeyVaultAndSecretReference) UnmarshalJSON(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 "secretUrl": + err = unpopulate(val, "SecretURL", &k.SecretURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &k.SourceVault) + 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 KeyVaultKeyReference. +func (k KeyVaultKeyReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyUrl", k.KeyURL) + populate(objectMap, "sourceVault", k.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultKeyReference. +func (k *KeyVaultKeyReference) UnmarshalJSON(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 "keyUrl": + err = unpopulate(val, "KeyURL", &k.KeyURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &k.SourceVault) + 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 KeyVaultSecretReference. +func (k KeyVaultSecretReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secretUrl", k.SecretURL) + populate(objectMap, "sourceVault", k.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultSecretReference. +func (k *KeyVaultSecretReference) UnmarshalJSON(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 "secretUrl": + err = unpopulate(val, "SecretURL", &k.SecretURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &k.SourceVault) + 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 LastPatchInstallationSummary. +func (l LastPatchInstallationSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", l.Error) + populate(objectMap, "excludedPatchCount", l.ExcludedPatchCount) + populate(objectMap, "failedPatchCount", l.FailedPatchCount) + populate(objectMap, "installationActivityId", l.InstallationActivityID) + populate(objectMap, "installedPatchCount", l.InstalledPatchCount) + populateDateTimeRFC3339(objectMap, "lastModifiedTime", l.LastModifiedTime) + populate(objectMap, "maintenanceWindowExceeded", l.MaintenanceWindowExceeded) + populate(objectMap, "notSelectedPatchCount", l.NotSelectedPatchCount) + populate(objectMap, "pendingPatchCount", l.PendingPatchCount) + populateDateTimeRFC3339(objectMap, "startTime", l.StartTime) + populate(objectMap, "status", l.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LastPatchInstallationSummary. +func (l *LastPatchInstallationSummary) UnmarshalJSON(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 "error": + err = unpopulate(val, "Error", &l.Error) + delete(rawMsg, key) + case "excludedPatchCount": + err = unpopulate(val, "ExcludedPatchCount", &l.ExcludedPatchCount) + delete(rawMsg, key) + case "failedPatchCount": + err = unpopulate(val, "FailedPatchCount", &l.FailedPatchCount) + delete(rawMsg, key) + case "installationActivityId": + err = unpopulate(val, "InstallationActivityID", &l.InstallationActivityID) + delete(rawMsg, key) + case "installedPatchCount": + err = unpopulate(val, "InstalledPatchCount", &l.InstalledPatchCount) + delete(rawMsg, key) + case "lastModifiedTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedTime", &l.LastModifiedTime) + delete(rawMsg, key) + case "maintenanceWindowExceeded": + err = unpopulate(val, "MaintenanceWindowExceeded", &l.MaintenanceWindowExceeded) + delete(rawMsg, key) + case "notSelectedPatchCount": + err = unpopulate(val, "NotSelectedPatchCount", &l.NotSelectedPatchCount) + delete(rawMsg, key) + case "pendingPatchCount": + err = unpopulate(val, "PendingPatchCount", &l.PendingPatchCount) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &l.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &l.Status) + 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 LatestGalleryImageVersion. +func (l LatestGalleryImageVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "latestVersionName", l.LatestVersionName) + populate(objectMap, "location", l.Location) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LatestGalleryImageVersion. +func (l *LatestGalleryImageVersion) UnmarshalJSON(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 "latestVersionName": + err = unpopulate(val, "LatestVersionName", &l.LatestVersionName) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &l.Location) + 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 LinuxConfiguration. +func (l LinuxConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disablePasswordAuthentication", l.DisablePasswordAuthentication) + populate(objectMap, "enableVMAgentPlatformUpdates", l.EnableVMAgentPlatformUpdates) + populate(objectMap, "patchSettings", l.PatchSettings) + populate(objectMap, "provisionVMAgent", l.ProvisionVMAgent) + populate(objectMap, "ssh", l.SSH) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxConfiguration. +func (l *LinuxConfiguration) UnmarshalJSON(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 "disablePasswordAuthentication": + err = unpopulate(val, "DisablePasswordAuthentication", &l.DisablePasswordAuthentication) + delete(rawMsg, key) + case "enableVMAgentPlatformUpdates": + err = unpopulate(val, "EnableVMAgentPlatformUpdates", &l.EnableVMAgentPlatformUpdates) + delete(rawMsg, key) + case "patchSettings": + err = unpopulate(val, "PatchSettings", &l.PatchSettings) + delete(rawMsg, key) + case "provisionVMAgent": + err = unpopulate(val, "ProvisionVMAgent", &l.ProvisionVMAgent) + delete(rawMsg, key) + case "ssh": + err = unpopulate(val, "SSH", &l.SSH) + 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 LinuxParameters. +func (l LinuxParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "classificationsToInclude", l.ClassificationsToInclude) + populate(objectMap, "maintenanceRunId", l.MaintenanceRunID) + populate(objectMap, "packageNameMasksToExclude", l.PackageNameMasksToExclude) + populate(objectMap, "packageNameMasksToInclude", l.PackageNameMasksToInclude) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxParameters. +func (l *LinuxParameters) UnmarshalJSON(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 "classificationsToInclude": + err = unpopulate(val, "ClassificationsToInclude", &l.ClassificationsToInclude) + delete(rawMsg, key) + case "maintenanceRunId": + err = unpopulate(val, "MaintenanceRunID", &l.MaintenanceRunID) + delete(rawMsg, key) + case "packageNameMasksToExclude": + err = unpopulate(val, "PackageNameMasksToExclude", &l.PackageNameMasksToExclude) + delete(rawMsg, key) + case "packageNameMasksToInclude": + err = unpopulate(val, "PackageNameMasksToInclude", &l.PackageNameMasksToInclude) + 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 LinuxPatchSettings. +func (l LinuxPatchSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assessmentMode", l.AssessmentMode) + populate(objectMap, "automaticByPlatformSettings", l.AutomaticByPlatformSettings) + populate(objectMap, "patchMode", l.PatchMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxPatchSettings. +func (l *LinuxPatchSettings) UnmarshalJSON(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 "assessmentMode": + err = unpopulate(val, "AssessmentMode", &l.AssessmentMode) + delete(rawMsg, key) + case "automaticByPlatformSettings": + err = unpopulate(val, "AutomaticByPlatformSettings", &l.AutomaticByPlatformSettings) + delete(rawMsg, key) + case "patchMode": + err = unpopulate(val, "PatchMode", &l.PatchMode) + 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 LinuxVMGuestPatchAutomaticByPlatformSettings. +func (l LinuxVMGuestPatchAutomaticByPlatformSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypassPlatformSafetyChecksOnUserSchedule", l.BypassPlatformSafetyChecksOnUserSchedule) + populate(objectMap, "rebootSetting", l.RebootSetting) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxVMGuestPatchAutomaticByPlatformSettings. +func (l *LinuxVMGuestPatchAutomaticByPlatformSettings) UnmarshalJSON(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 "bypassPlatformSafetyChecksOnUserSchedule": + err = unpopulate(val, "BypassPlatformSafetyChecksOnUserSchedule", &l.BypassPlatformSafetyChecksOnUserSchedule) + delete(rawMsg, key) + case "rebootSetting": + err = unpopulate(val, "RebootSetting", &l.RebootSetting) + 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 ListUsagesResult. +func (l ListUsagesResult) 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 ListUsagesResult. +func (l *ListUsagesResult) UnmarshalJSON(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 LoadBalancerConfiguration. +func (l LoadBalancerConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerConfiguration. +func (l *LoadBalancerConfiguration) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadBalancerConfigurationProperties. +func (l LoadBalancerConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "frontendIpConfigurations", l.FrontendIPConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerConfigurationProperties. +func (l *LoadBalancerConfigurationProperties) UnmarshalJSON(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 "frontendIpConfigurations": + err = unpopulate(val, "FrontendIPConfigurations", &l.FrontendIPConfigurations) + 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 LoadBalancerFrontendIPConfiguration. +func (l LoadBalancerFrontendIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerFrontendIPConfiguration. +func (l *LoadBalancerFrontendIPConfiguration) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + 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 LoadBalancerFrontendIPConfigurationProperties. +func (l LoadBalancerFrontendIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAddress", l.PrivateIPAddress) + populate(objectMap, "publicIPAddress", l.PublicIPAddress) + populate(objectMap, "subnet", l.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerFrontendIPConfigurationProperties. +func (l *LoadBalancerFrontendIPConfigurationProperties) UnmarshalJSON(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 "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &l.PrivateIPAddress) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &l.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &l.Subnet) + 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 LogAnalyticsInputBase. +func (l LogAnalyticsInputBase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobContainerSasUri", l.BlobContainerSasURI) + populateDateTimeRFC3339(objectMap, "fromTime", l.FromTime) + populate(objectMap, "groupByClientApplicationId", l.GroupByClientApplicationID) + populate(objectMap, "groupByOperationName", l.GroupByOperationName) + populate(objectMap, "groupByResourceName", l.GroupByResourceName) + populate(objectMap, "groupByThrottlePolicy", l.GroupByThrottlePolicy) + populate(objectMap, "groupByUserAgent", l.GroupByUserAgent) + populateDateTimeRFC3339(objectMap, "toTime", l.ToTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LogAnalyticsInputBase. +func (l *LogAnalyticsInputBase) UnmarshalJSON(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 "blobContainerSasUri": + err = unpopulate(val, "BlobContainerSasURI", &l.BlobContainerSasURI) + delete(rawMsg, key) + case "fromTime": + err = unpopulateDateTimeRFC3339(val, "FromTime", &l.FromTime) + delete(rawMsg, key) + case "groupByClientApplicationId": + err = unpopulate(val, "GroupByClientApplicationID", &l.GroupByClientApplicationID) + delete(rawMsg, key) + case "groupByOperationName": + err = unpopulate(val, "GroupByOperationName", &l.GroupByOperationName) + delete(rawMsg, key) + case "groupByResourceName": + err = unpopulate(val, "GroupByResourceName", &l.GroupByResourceName) + delete(rawMsg, key) + case "groupByThrottlePolicy": + err = unpopulate(val, "GroupByThrottlePolicy", &l.GroupByThrottlePolicy) + delete(rawMsg, key) + case "groupByUserAgent": + err = unpopulate(val, "GroupByUserAgent", &l.GroupByUserAgent) + delete(rawMsg, key) + case "toTime": + err = unpopulateDateTimeRFC3339(val, "ToTime", &l.ToTime) + 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 LogAnalyticsOperationResult. +func (l LogAnalyticsOperationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", l.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LogAnalyticsOperationResult. +func (l *LogAnalyticsOperationResult) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &l.Properties) + 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 LogAnalyticsOutput. +func (l LogAnalyticsOutput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "output", l.Output) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LogAnalyticsOutput. +func (l *LogAnalyticsOutput) UnmarshalJSON(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 "output": + err = unpopulate(val, "Output", &l.Output) + 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 MaintenanceRedeployStatus. +func (m MaintenanceRedeployStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isCustomerInitiatedMaintenanceAllowed", m.IsCustomerInitiatedMaintenanceAllowed) + populate(objectMap, "lastOperationMessage", m.LastOperationMessage) + populate(objectMap, "lastOperationResultCode", m.LastOperationResultCode) + populateDateTimeRFC3339(objectMap, "maintenanceWindowEndTime", m.MaintenanceWindowEndTime) + populateDateTimeRFC3339(objectMap, "maintenanceWindowStartTime", m.MaintenanceWindowStartTime) + populateDateTimeRFC3339(objectMap, "preMaintenanceWindowEndTime", m.PreMaintenanceWindowEndTime) + populateDateTimeRFC3339(objectMap, "preMaintenanceWindowStartTime", m.PreMaintenanceWindowStartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaintenanceRedeployStatus. +func (m *MaintenanceRedeployStatus) UnmarshalJSON(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 "isCustomerInitiatedMaintenanceAllowed": + err = unpopulate(val, "IsCustomerInitiatedMaintenanceAllowed", &m.IsCustomerInitiatedMaintenanceAllowed) + delete(rawMsg, key) + case "lastOperationMessage": + err = unpopulate(val, "LastOperationMessage", &m.LastOperationMessage) + delete(rawMsg, key) + case "lastOperationResultCode": + err = unpopulate(val, "LastOperationResultCode", &m.LastOperationResultCode) + delete(rawMsg, key) + case "maintenanceWindowEndTime": + err = unpopulateDateTimeRFC3339(val, "MaintenanceWindowEndTime", &m.MaintenanceWindowEndTime) + delete(rawMsg, key) + case "maintenanceWindowStartTime": + err = unpopulateDateTimeRFC3339(val, "MaintenanceWindowStartTime", &m.MaintenanceWindowStartTime) + delete(rawMsg, key) + case "preMaintenanceWindowEndTime": + err = unpopulateDateTimeRFC3339(val, "PreMaintenanceWindowEndTime", &m.PreMaintenanceWindowEndTime) + delete(rawMsg, key) + case "preMaintenanceWindowStartTime": + err = unpopulateDateTimeRFC3339(val, "PreMaintenanceWindowStartTime", &m.PreMaintenanceWindowStartTime) + 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 ManagedArtifact. +func (m ManagedArtifact) 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 ManagedArtifact. +func (m *ManagedArtifact) UnmarshalJSON(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 ManagedDiskParameters. +func (m ManagedDiskParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSet", m.DiskEncryptionSet) + populate(objectMap, "id", m.ID) + populate(objectMap, "securityProfile", m.SecurityProfile) + populate(objectMap, "storageAccountType", m.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedDiskParameters. +func (m *ManagedDiskParameters) UnmarshalJSON(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 "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &m.DiskEncryptionSet) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &m.SecurityProfile) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &m.StorageAccountType) + 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 NetworkInterfaceReference. +func (n NetworkInterfaceReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkInterfaceReference. +func (n *NetworkInterfaceReference) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + 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 NetworkInterfaceReferenceProperties. +func (n NetworkInterfaceReferenceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deleteOption", n.DeleteOption) + populate(objectMap, "primary", n.Primary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkInterfaceReferenceProperties. +func (n *NetworkInterfaceReferenceProperties) UnmarshalJSON(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 "deleteOption": + err = unpopulate(val, "DeleteOption", &n.DeleteOption) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &n.Primary) + 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 NetworkProfile. +func (n NetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkApiVersion", n.NetworkAPIVersion) + populate(objectMap, "networkInterfaceConfigurations", n.NetworkInterfaceConfigurations) + populate(objectMap, "networkInterfaces", n.NetworkInterfaces) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkProfile. +func (n *NetworkProfile) UnmarshalJSON(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 "networkApiVersion": + err = unpopulate(val, "NetworkAPIVersion", &n.NetworkAPIVersion) + delete(rawMsg, key) + case "networkInterfaceConfigurations": + err = unpopulate(val, "NetworkInterfaceConfigurations", &n.NetworkInterfaceConfigurations) + delete(rawMsg, key) + case "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &n.NetworkInterfaces) + 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 OSDisk. +func (o OSDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", o.Caching) + populate(objectMap, "createOption", o.CreateOption) + populate(objectMap, "deleteOption", o.DeleteOption) + populate(objectMap, "diffDiskSettings", o.DiffDiskSettings) + populate(objectMap, "diskSizeGB", o.DiskSizeGB) + populate(objectMap, "encryptionSettings", o.EncryptionSettings) + populate(objectMap, "image", o.Image) + populate(objectMap, "managedDisk", o.ManagedDisk) + populate(objectMap, "name", o.Name) + populate(objectMap, "osType", o.OSType) + populate(objectMap, "vhd", o.Vhd) + populate(objectMap, "writeAcceleratorEnabled", o.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSDisk. +func (o *OSDisk) UnmarshalJSON(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 "caching": + err = unpopulate(val, "Caching", &o.Caching) + delete(rawMsg, key) + case "createOption": + err = unpopulate(val, "CreateOption", &o.CreateOption) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &o.DeleteOption) + delete(rawMsg, key) + case "diffDiskSettings": + err = unpopulate(val, "DiffDiskSettings", &o.DiffDiskSettings) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &o.DiskSizeGB) + delete(rawMsg, key) + case "encryptionSettings": + err = unpopulate(val, "EncryptionSettings", &o.EncryptionSettings) + delete(rawMsg, key) + case "image": + err = unpopulate(val, "Image", &o.Image) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &o.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &o.OSType) + delete(rawMsg, key) + case "vhd": + err = unpopulate(val, "Vhd", &o.Vhd) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &o.WriteAcceleratorEnabled) + 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 OSDiskImage. +func (o OSDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "operatingSystem", o.OperatingSystem) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSDiskImage. +func (o *OSDiskImage) UnmarshalJSON(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 "operatingSystem": + err = unpopulate(val, "OperatingSystem", &o.OperatingSystem) + 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 OSDiskImageEncryption. +func (o OSDiskImageEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSetId", o.DiskEncryptionSetID) + populate(objectMap, "securityProfile", o.SecurityProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSDiskImageEncryption. +func (o *OSDiskImageEncryption) UnmarshalJSON(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 "diskEncryptionSetId": + err = unpopulate(val, "DiskEncryptionSetID", &o.DiskEncryptionSetID) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &o.SecurityProfile) + 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 OSDiskImageSecurityProfile. +func (o OSDiskImageSecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "confidentialVMEncryptionType", o.ConfidentialVMEncryptionType) + populate(objectMap, "secureVMDiskEncryptionSetId", o.SecureVMDiskEncryptionSetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSDiskImageSecurityProfile. +func (o *OSDiskImageSecurityProfile) UnmarshalJSON(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 "confidentialVMEncryptionType": + err = unpopulate(val, "ConfidentialVMEncryptionType", &o.ConfidentialVMEncryptionType) + delete(rawMsg, key) + case "secureVMDiskEncryptionSetId": + err = unpopulate(val, "SecureVMDiskEncryptionSetID", &o.SecureVMDiskEncryptionSetID) + 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 OSFamily. +func (o OSFamily) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "location", o.Location) + 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 OSFamily. +func (o *OSFamily) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &o.Location) + 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 OSFamilyListResult. +func (o OSFamilyListResult) 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 OSFamilyListResult. +func (o *OSFamilyListResult) UnmarshalJSON(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 OSFamilyProperties. +func (o OSFamilyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "label", o.Label) + populate(objectMap, "name", o.Name) + populate(objectMap, "versions", o.Versions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSFamilyProperties. +func (o *OSFamilyProperties) UnmarshalJSON(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 "label": + err = unpopulate(val, "Label", &o.Label) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "versions": + err = unpopulate(val, "Versions", &o.Versions) + 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 OSImageNotificationProfile. +func (o OSImageNotificationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enable", o.Enable) + populate(objectMap, "notBeforeTimeout", o.NotBeforeTimeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSImageNotificationProfile. +func (o *OSImageNotificationProfile) UnmarshalJSON(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 "enable": + err = unpopulate(val, "Enable", &o.Enable) + delete(rawMsg, key) + case "notBeforeTimeout": + err = unpopulate(val, "NotBeforeTimeout", &o.NotBeforeTimeout) + 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 OSProfile. +func (o OSProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminPassword", o.AdminPassword) + populate(objectMap, "adminUsername", o.AdminUsername) + populate(objectMap, "allowExtensionOperations", o.AllowExtensionOperations) + populate(objectMap, "computerName", o.ComputerName) + populate(objectMap, "customData", o.CustomData) + populate(objectMap, "linuxConfiguration", o.LinuxConfiguration) + populate(objectMap, "requireGuestProvisionSignal", o.RequireGuestProvisionSignal) + populate(objectMap, "secrets", o.Secrets) + populate(objectMap, "windowsConfiguration", o.WindowsConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSProfile. +func (o *OSProfile) UnmarshalJSON(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 "adminPassword": + err = unpopulate(val, "AdminPassword", &o.AdminPassword) + delete(rawMsg, key) + case "adminUsername": + err = unpopulate(val, "AdminUsername", &o.AdminUsername) + delete(rawMsg, key) + case "allowExtensionOperations": + err = unpopulate(val, "AllowExtensionOperations", &o.AllowExtensionOperations) + delete(rawMsg, key) + case "computerName": + err = unpopulate(val, "ComputerName", &o.ComputerName) + delete(rawMsg, key) + case "customData": + err = unpopulate(val, "CustomData", &o.CustomData) + delete(rawMsg, key) + case "linuxConfiguration": + err = unpopulate(val, "LinuxConfiguration", &o.LinuxConfiguration) + delete(rawMsg, key) + case "requireGuestProvisionSignal": + err = unpopulate(val, "RequireGuestProvisionSignal", &o.RequireGuestProvisionSignal) + delete(rawMsg, key) + case "secrets": + err = unpopulate(val, "Secrets", &o.Secrets) + delete(rawMsg, key) + case "windowsConfiguration": + err = unpopulate(val, "WindowsConfiguration", &o.WindowsConfiguration) + 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 OSProfileProvisioningData. +func (o OSProfileProvisioningData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminPassword", o.AdminPassword) + populate(objectMap, "customData", o.CustomData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSProfileProvisioningData. +func (o *OSProfileProvisioningData) UnmarshalJSON(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 "adminPassword": + err = unpopulate(val, "AdminPassword", &o.AdminPassword) + delete(rawMsg, key) + case "customData": + err = unpopulate(val, "CustomData", &o.CustomData) + 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 OSVersion. +func (o OSVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "location", o.Location) + 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 OSVersion. +func (o *OSVersion) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &o.Location) + 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 OSVersionListResult. +func (o OSVersionListResult) 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 OSVersionListResult. +func (o *OSVersionListResult) UnmarshalJSON(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 OSVersionProperties. +func (o OSVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "family", o.Family) + populate(objectMap, "familyLabel", o.FamilyLabel) + populate(objectMap, "isActive", o.IsActive) + populate(objectMap, "isDefault", o.IsDefault) + populate(objectMap, "label", o.Label) + populate(objectMap, "version", o.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSVersionProperties. +func (o *OSVersionProperties) UnmarshalJSON(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 "family": + err = unpopulate(val, "Family", &o.Family) + delete(rawMsg, key) + case "familyLabel": + err = unpopulate(val, "FamilyLabel", &o.FamilyLabel) + delete(rawMsg, key) + case "isActive": + err = unpopulate(val, "IsActive", &o.IsActive) + delete(rawMsg, key) + case "isDefault": + err = unpopulate(val, "IsDefault", &o.IsDefault) + delete(rawMsg, key) + case "label": + err = unpopulate(val, "Label", &o.Label) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &o.Version) + 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 OSVersionPropertiesBase. +func (o OSVersionPropertiesBase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isActive", o.IsActive) + populate(objectMap, "isDefault", o.IsDefault) + populate(objectMap, "label", o.Label) + populate(objectMap, "version", o.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSVersionPropertiesBase. +func (o *OSVersionPropertiesBase) UnmarshalJSON(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 "isActive": + err = unpopulate(val, "IsActive", &o.IsActive) + delete(rawMsg, key) + case "isDefault": + err = unpopulate(val, "IsDefault", &o.IsDefault) + delete(rawMsg, key) + case "label": + err = unpopulate(val, "Label", &o.Label) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &o.Version) + 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 OperationValue. +func (o OperationValue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "display", o.Display) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationValue. +func (o *OperationValue) UnmarshalJSON(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 "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 OperationValueDisplay. +func (o OperationValueDisplay) 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 OperationValueDisplay. +func (o *OperationValueDisplay) UnmarshalJSON(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 OrchestrationServiceStateInput. +func (o OrchestrationServiceStateInput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", o.Action) + populate(objectMap, "serviceName", o.ServiceName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrchestrationServiceStateInput. +func (o *OrchestrationServiceStateInput) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &o.Action) + delete(rawMsg, key) + case "serviceName": + err = unpopulate(val, "ServiceName", &o.ServiceName) + 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 OrchestrationServiceSummary. +func (o OrchestrationServiceSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "serviceName", o.ServiceName) + populate(objectMap, "serviceState", o.ServiceState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrchestrationServiceSummary. +func (o *OrchestrationServiceSummary) UnmarshalJSON(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 "serviceName": + err = unpopulate(val, "ServiceName", &o.ServiceName) + delete(rawMsg, key) + case "serviceState": + err = unpopulate(val, "ServiceState", &o.ServiceState) + 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 PatchInstallationDetail. +func (p PatchInstallationDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "classifications", p.Classifications) + populate(objectMap, "installationState", p.InstallationState) + populate(objectMap, "kbId", p.KbID) + populate(objectMap, "name", p.Name) + populate(objectMap, "patchId", p.PatchID) + populate(objectMap, "version", p.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PatchInstallationDetail. +func (p *PatchInstallationDetail) UnmarshalJSON(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 "classifications": + err = unpopulate(val, "Classifications", &p.Classifications) + delete(rawMsg, key) + case "installationState": + err = unpopulate(val, "InstallationState", &p.InstallationState) + delete(rawMsg, key) + case "kbId": + err = unpopulate(val, "KbID", &p.KbID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "patchId": + err = unpopulate(val, "PatchID", &p.PatchID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &p.Version) + 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 PatchSettings. +func (p PatchSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assessmentMode", p.AssessmentMode) + populate(objectMap, "automaticByPlatformSettings", p.AutomaticByPlatformSettings) + populate(objectMap, "enableHotpatching", p.EnableHotpatching) + populate(objectMap, "patchMode", p.PatchMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PatchSettings. +func (p *PatchSettings) UnmarshalJSON(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 "assessmentMode": + err = unpopulate(val, "AssessmentMode", &p.AssessmentMode) + delete(rawMsg, key) + case "automaticByPlatformSettings": + err = unpopulate(val, "AutomaticByPlatformSettings", &p.AutomaticByPlatformSettings) + delete(rawMsg, key) + case "enableHotpatching": + err = unpopulate(val, "EnableHotpatching", &p.EnableHotpatching) + delete(rawMsg, key) + case "patchMode": + err = unpopulate(val, "PatchMode", &p.PatchMode) + 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 PirCommunityGalleryResource. +func (p PirCommunityGalleryResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", p.Identifier) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PirCommunityGalleryResource. +func (p *PirCommunityGalleryResource) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &p.Identifier) + 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 "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 PirResource. +func (p PirResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PirResource. +func (p *PirResource) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + 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 PirSharedGalleryResource. +func (p PirSharedGalleryResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", p.Identifier) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PirSharedGalleryResource. +func (p *PirSharedGalleryResource) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &p.Identifier) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Plan. +func (p Plan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "product", p.Product) + populate(objectMap, "promotionCode", p.PromotionCode) + populate(objectMap, "publisher", p.Publisher) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Plan. +func (p *Plan) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &p.Product) + delete(rawMsg, key) + case "promotionCode": + err = unpopulate(val, "PromotionCode", &p.PromotionCode) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &p.Publisher) + 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 PolicyViolation. +func (p PolicyViolation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", p.Category) + populate(objectMap, "details", p.Details) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PolicyViolation. +func (p *PolicyViolation) UnmarshalJSON(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 "category": + err = unpopulate(val, "Category", &p.Category) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &p.Details) + 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 PriorityMixPolicy. +func (p PriorityMixPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseRegularPriorityCount", p.BaseRegularPriorityCount) + populate(objectMap, "regularPriorityPercentageAboveBase", p.RegularPriorityPercentageAboveBase) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PriorityMixPolicy. +func (p *PriorityMixPolicy) UnmarshalJSON(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 "baseRegularPriorityCount": + err = unpopulate(val, "BaseRegularPriorityCount", &p.BaseRegularPriorityCount) + delete(rawMsg, key) + case "regularPriorityPercentageAboveBase": + err = unpopulate(val, "RegularPriorityPercentageAboveBase", &p.RegularPriorityPercentageAboveBase) + 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, "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, "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 PropertyUpdatesInProgress. +func (p PropertyUpdatesInProgress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targetTier", p.TargetTier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PropertyUpdatesInProgress. +func (p *PropertyUpdatesInProgress) UnmarshalJSON(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 "targetTier": + err = unpopulate(val, "TargetTier", &p.TargetTier) + 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 ProximityPlacementGroup. +func (p ProximityPlacementGroup) 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) + populate(objectMap, "zones", p.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProximityPlacementGroup. +func (p *ProximityPlacementGroup) UnmarshalJSON(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) + case "zones": + err = unpopulate(val, "Zones", &p.Zones) + 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 ProximityPlacementGroupListResult. +func (p ProximityPlacementGroupListResult) 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 ProximityPlacementGroupListResult. +func (p *ProximityPlacementGroupListResult) UnmarshalJSON(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 ProximityPlacementGroupProperties. +func (p ProximityPlacementGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availabilitySets", p.AvailabilitySets) + populate(objectMap, "colocationStatus", p.ColocationStatus) + populate(objectMap, "intent", p.Intent) + populate(objectMap, "proximityPlacementGroupType", p.ProximityPlacementGroupType) + populate(objectMap, "virtualMachineScaleSets", p.VirtualMachineScaleSets) + populate(objectMap, "virtualMachines", p.VirtualMachines) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProximityPlacementGroupProperties. +func (p *ProximityPlacementGroupProperties) UnmarshalJSON(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 "availabilitySets": + err = unpopulate(val, "AvailabilitySets", &p.AvailabilitySets) + delete(rawMsg, key) + case "colocationStatus": + err = unpopulate(val, "ColocationStatus", &p.ColocationStatus) + delete(rawMsg, key) + case "intent": + err = unpopulate(val, "Intent", &p.Intent) + delete(rawMsg, key) + case "proximityPlacementGroupType": + err = unpopulate(val, "ProximityPlacementGroupType", &p.ProximityPlacementGroupType) + delete(rawMsg, key) + case "virtualMachineScaleSets": + err = unpopulate(val, "VirtualMachineScaleSets", &p.VirtualMachineScaleSets) + delete(rawMsg, key) + case "virtualMachines": + err = unpopulate(val, "VirtualMachines", &p.VirtualMachines) + 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 ProximityPlacementGroupPropertiesIntent. +func (p ProximityPlacementGroupPropertiesIntent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vmSizes", p.VMSizes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProximityPlacementGroupPropertiesIntent. +func (p *ProximityPlacementGroupPropertiesIntent) UnmarshalJSON(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 "vmSizes": + err = unpopulate(val, "VMSizes", &p.VMSizes) + 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 ProximityPlacementGroupUpdate. +func (p ProximityPlacementGroupUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", p.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProximityPlacementGroupUpdate. +func (p *ProximityPlacementGroupUpdate) UnmarshalJSON(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 "tags": + err = unpopulate(val, "Tags", &p.Tags) + 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 ProxyAgentSettings. +func (p ProxyAgentSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", p.Enabled) + populate(objectMap, "keyIncarnationId", p.KeyIncarnationID) + populate(objectMap, "mode", p.Mode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProxyAgentSettings. +func (p *ProxyAgentSettings) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &p.Enabled) + delete(rawMsg, key) + case "keyIncarnationId": + err = unpopulate(val, "KeyIncarnationID", &p.KeyIncarnationID) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &p.Mode) + 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 ProxyOnlyResource. +func (p ProxyOnlyResource) 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 ProxyOnlyResource. +func (p *ProxyOnlyResource) UnmarshalJSON(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 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 PublicIPAddressSKU. +func (p PublicIPAddressSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "tier", p.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddressSKU. +func (p *PublicIPAddressSKU) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &p.Tier) + 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 PurchasePlan. +func (p PurchasePlan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "product", p.Product) + populate(objectMap, "publisher", p.Publisher) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PurchasePlan. +func (p *PurchasePlan) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &p.Product) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &p.Publisher) + 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 RecommendedMachineConfiguration. +func (r RecommendedMachineConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "memory", r.Memory) + populate(objectMap, "vCPUs", r.VCPUs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RecommendedMachineConfiguration. +func (r *RecommendedMachineConfiguration) UnmarshalJSON(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 "memory": + err = unpopulate(val, "Memory", &r.Memory) + delete(rawMsg, key) + case "vCPUs": + err = unpopulate(val, "VCPUs", &r.VCPUs) + 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 RecoveryWalkResponse. +func (r RecoveryWalkResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextPlatformUpdateDomain", r.NextPlatformUpdateDomain) + populate(objectMap, "walkPerformed", r.WalkPerformed) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RecoveryWalkResponse. +func (r *RecoveryWalkResponse) UnmarshalJSON(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 "nextPlatformUpdateDomain": + err = unpopulate(val, "NextPlatformUpdateDomain", &r.NextPlatformUpdateDomain) + delete(rawMsg, key) + case "walkPerformed": + err = unpopulate(val, "WalkPerformed", &r.WalkPerformed) + 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 RegionalReplicationStatus. +func (r RegionalReplicationStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "details", r.Details) + populate(objectMap, "progress", r.Progress) + populate(objectMap, "region", r.Region) + populate(objectMap, "state", r.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegionalReplicationStatus. +func (r *RegionalReplicationStatus) UnmarshalJSON(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 "details": + err = unpopulate(val, "Details", &r.Details) + delete(rawMsg, key) + case "progress": + err = unpopulate(val, "Progress", &r.Progress) + delete(rawMsg, key) + case "region": + err = unpopulate(val, "Region", &r.Region) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &r.State) + 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 RegionalSharingStatus. +func (r RegionalSharingStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "details", r.Details) + populate(objectMap, "region", r.Region) + populate(objectMap, "state", r.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegionalSharingStatus. +func (r *RegionalSharingStatus) UnmarshalJSON(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 "details": + err = unpopulate(val, "Details", &r.Details) + delete(rawMsg, key) + case "region": + err = unpopulate(val, "Region", &r.Region) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &r.State) + 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 ReplicationStatus. +func (r ReplicationStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregatedState", r.AggregatedState) + populate(objectMap, "summary", r.Summary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicationStatus. +func (r *ReplicationStatus) UnmarshalJSON(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 "aggregatedState": + err = unpopulate(val, "AggregatedState", &r.AggregatedState) + delete(rawMsg, key) + case "summary": + err = unpopulate(val, "Summary", &r.Summary) + 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 RequestRateByIntervalInput. +func (r RequestRateByIntervalInput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobContainerSasUri", r.BlobContainerSasURI) + populateDateTimeRFC3339(objectMap, "fromTime", r.FromTime) + populate(objectMap, "groupByClientApplicationId", r.GroupByClientApplicationID) + populate(objectMap, "groupByOperationName", r.GroupByOperationName) + populate(objectMap, "groupByResourceName", r.GroupByResourceName) + populate(objectMap, "groupByThrottlePolicy", r.GroupByThrottlePolicy) + populate(objectMap, "groupByUserAgent", r.GroupByUserAgent) + populate(objectMap, "intervalLength", r.IntervalLength) + populateDateTimeRFC3339(objectMap, "toTime", r.ToTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestRateByIntervalInput. +func (r *RequestRateByIntervalInput) UnmarshalJSON(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 "blobContainerSasUri": + err = unpopulate(val, "BlobContainerSasURI", &r.BlobContainerSasURI) + delete(rawMsg, key) + case "fromTime": + err = unpopulateDateTimeRFC3339(val, "FromTime", &r.FromTime) + delete(rawMsg, key) + case "groupByClientApplicationId": + err = unpopulate(val, "GroupByClientApplicationID", &r.GroupByClientApplicationID) + delete(rawMsg, key) + case "groupByOperationName": + err = unpopulate(val, "GroupByOperationName", &r.GroupByOperationName) + delete(rawMsg, key) + case "groupByResourceName": + err = unpopulate(val, "GroupByResourceName", &r.GroupByResourceName) + delete(rawMsg, key) + case "groupByThrottlePolicy": + err = unpopulate(val, "GroupByThrottlePolicy", &r.GroupByThrottlePolicy) + delete(rawMsg, key) + case "groupByUserAgent": + err = unpopulate(val, "GroupByUserAgent", &r.GroupByUserAgent) + delete(rawMsg, key) + case "intervalLength": + err = unpopulate(val, "IntervalLength", &r.IntervalLength) + delete(rawMsg, key) + case "toTime": + err = unpopulateDateTimeRFC3339(val, "ToTime", &r.ToTime) + 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 ResiliencyPolicy. +func (r ResiliencyPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resilientVMCreationPolicy", r.ResilientVMCreationPolicy) + populate(objectMap, "resilientVMDeletionPolicy", r.ResilientVMDeletionPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResiliencyPolicy. +func (r *ResiliencyPolicy) UnmarshalJSON(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 "resilientVMCreationPolicy": + err = unpopulate(val, "ResilientVMCreationPolicy", &r.ResilientVMCreationPolicy) + delete(rawMsg, key) + case "resilientVMDeletionPolicy": + err = unpopulate(val, "ResilientVMDeletionPolicy", &r.ResilientVMDeletionPolicy) + 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 ResilientVMCreationPolicy. +func (r ResilientVMCreationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", r.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResilientVMCreationPolicy. +func (r *ResilientVMCreationPolicy) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &r.Enabled) + 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 ResilientVMDeletionPolicy. +func (r ResilientVMDeletionPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", r.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResilientVMDeletionPolicy. +func (r *ResilientVMDeletionPolicy) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &r.Enabled) + 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 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 ResourceInstanceViewStatus. +func (r ResourceInstanceViewStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", r.Code) + populate(objectMap, "displayStatus", r.DisplayStatus) + populate(objectMap, "level", r.Level) + populate(objectMap, "message", r.Message) + populateDateTimeRFC3339(objectMap, "time", r.Time) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceInstanceViewStatus. +func (r *ResourceInstanceViewStatus) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &r.Code) + delete(rawMsg, key) + case "displayStatus": + err = unpopulate(val, "DisplayStatus", &r.DisplayStatus) + delete(rawMsg, key) + case "level": + err = unpopulate(val, "Level", &r.Level) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &r.Message) + delete(rawMsg, key) + case "time": + err = unpopulateDateTimeRFC3339(val, "Time", &r.Time) + 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 ResourceRange. +func (r ResourceRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "max", r.Max) + populate(objectMap, "min", r.Min) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceRange. +func (r *ResourceRange) UnmarshalJSON(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 "max": + err = unpopulate(val, "Max", &r.Max) + delete(rawMsg, key) + case "min": + err = unpopulate(val, "Min", &r.Min) + 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 ResourceSKU. +func (r ResourceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "apiVersions", r.APIVersions) + populate(objectMap, "capabilities", r.Capabilities) + populate(objectMap, "capacity", r.Capacity) + populate(objectMap, "costs", r.Costs) + populate(objectMap, "family", r.Family) + populate(objectMap, "kind", r.Kind) + populate(objectMap, "locationInfo", r.LocationInfo) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "name", r.Name) + populate(objectMap, "resourceType", r.ResourceType) + populate(objectMap, "restrictions", r.Restrictions) + populate(objectMap, "size", r.Size) + populate(objectMap, "tier", r.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKU. +func (r *ResourceSKU) UnmarshalJSON(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 "apiVersions": + err = unpopulate(val, "APIVersions", &r.APIVersions) + delete(rawMsg, key) + case "capabilities": + err = unpopulate(val, "Capabilities", &r.Capabilities) + delete(rawMsg, key) + case "capacity": + err = unpopulate(val, "Capacity", &r.Capacity) + delete(rawMsg, key) + case "costs": + err = unpopulate(val, "Costs", &r.Costs) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &r.Family) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &r.Kind) + delete(rawMsg, key) + case "locationInfo": + err = unpopulate(val, "LocationInfo", &r.LocationInfo) + delete(rawMsg, key) + case "locations": + err = unpopulate(val, "Locations", &r.Locations) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &r.ResourceType) + delete(rawMsg, key) + case "restrictions": + err = unpopulate(val, "Restrictions", &r.Restrictions) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &r.Size) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &r.Tier) + 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 ResourceSKUCapabilities. +func (r ResourceSKUCapabilities) 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 ResourceSKUCapabilities. +func (r *ResourceSKUCapabilities) UnmarshalJSON(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 ResourceSKUCapacity. +func (r ResourceSKUCapacity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "default", r.Default) + populate(objectMap, "maximum", r.Maximum) + populate(objectMap, "minimum", r.Minimum) + populate(objectMap, "scaleType", r.ScaleType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUCapacity. +func (r *ResourceSKUCapacity) UnmarshalJSON(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 "default": + err = unpopulate(val, "Default", &r.Default) + delete(rawMsg, key) + case "maximum": + err = unpopulate(val, "Maximum", &r.Maximum) + delete(rawMsg, key) + case "minimum": + err = unpopulate(val, "Minimum", &r.Minimum) + delete(rawMsg, key) + case "scaleType": + err = unpopulate(val, "ScaleType", &r.ScaleType) + 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 ResourceSKUCosts. +func (r ResourceSKUCosts) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedUnit", r.ExtendedUnit) + populate(objectMap, "meterID", r.MeterID) + populate(objectMap, "quantity", r.Quantity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUCosts. +func (r *ResourceSKUCosts) UnmarshalJSON(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 "extendedUnit": + err = unpopulate(val, "ExtendedUnit", &r.ExtendedUnit) + delete(rawMsg, key) + case "meterID": + err = unpopulate(val, "MeterID", &r.MeterID) + delete(rawMsg, key) + case "quantity": + err = unpopulate(val, "Quantity", &r.Quantity) + 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 ResourceSKULocationInfo. +func (r ResourceSKULocationInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocations", r.ExtendedLocations) + populate(objectMap, "location", r.Location) + populate(objectMap, "type", r.Type) + populate(objectMap, "zoneDetails", r.ZoneDetails) + populate(objectMap, "zones", r.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKULocationInfo. +func (r *ResourceSKULocationInfo) UnmarshalJSON(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 "extendedLocations": + err = unpopulate(val, "ExtendedLocations", &r.ExtendedLocations) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + case "zoneDetails": + err = unpopulate(val, "ZoneDetails", &r.ZoneDetails) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &r.Zones) + 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 ResourceSKURestrictionInfo. +func (r ResourceSKURestrictionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "zones", r.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKURestrictionInfo. +func (r *ResourceSKURestrictionInfo) UnmarshalJSON(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 "locations": + err = unpopulate(val, "Locations", &r.Locations) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &r.Zones) + 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 ResourceSKURestrictions. +func (r ResourceSKURestrictions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reasonCode", r.ReasonCode) + populate(objectMap, "restrictionInfo", r.RestrictionInfo) + populate(objectMap, "type", r.Type) + populate(objectMap, "values", r.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKURestrictions. +func (r *ResourceSKURestrictions) UnmarshalJSON(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 "restrictionInfo": + err = unpopulate(val, "RestrictionInfo", &r.RestrictionInfo) + 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 ResourceSKUZoneDetails. +func (r ResourceSKUZoneDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capabilities", r.Capabilities) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUZoneDetails. +func (r *ResourceSKUZoneDetails) UnmarshalJSON(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 "capabilities": + err = unpopulate(val, "Capabilities", &r.Capabilities) + delete(rawMsg, 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 ResourceSKUsResult. +func (r ResourceSKUsResult) 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 ResourceSKUsResult. +func (r *ResourceSKUsResult) UnmarshalJSON(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 ResourceSharingProfile. +func (r ResourceSharingProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "subscriptionIds", r.SubscriptionIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSharingProfile. +func (r *ResourceSharingProfile) UnmarshalJSON(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 "subscriptionIds": + err = unpopulate(val, "SubscriptionIDs", &r.SubscriptionIDs) + 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 ResourceURIList. +func (r ResourceURIList) 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 ResourceURIList. +func (r *ResourceURIList) UnmarshalJSON(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 ResourceWithOptionalLocation. +func (r ResourceWithOptionalLocation) 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 ResourceWithOptionalLocation. +func (r *ResourceWithOptionalLocation) UnmarshalJSON(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 RestorePoint. +func (r RestorePoint) 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, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePoint. +func (r *RestorePoint) UnmarshalJSON(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 "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 RestorePointCollection. +func (r RestorePointCollection) 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, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointCollection. +func (r *RestorePointCollection) UnmarshalJSON(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 "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 RestorePointCollectionListResult. +func (r RestorePointCollectionListResult) 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 RestorePointCollectionListResult. +func (r *RestorePointCollectionListResult) UnmarshalJSON(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 RestorePointCollectionProperties. +func (r RestorePointCollectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "restorePointCollectionId", r.RestorePointCollectionID) + populate(objectMap, "restorePoints", r.RestorePoints) + populate(objectMap, "source", r.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointCollectionProperties. +func (r *RestorePointCollectionProperties) UnmarshalJSON(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 "restorePointCollectionId": + err = unpopulate(val, "RestorePointCollectionID", &r.RestorePointCollectionID) + delete(rawMsg, key) + case "restorePoints": + err = unpopulate(val, "RestorePoints", &r.RestorePoints) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &r.Source) + 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 RestorePointCollectionSourceProperties. +func (r RestorePointCollectionSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointCollectionSourceProperties. +func (r *RestorePointCollectionSourceProperties) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestorePointCollectionUpdate. +func (r RestorePointCollectionUpdate) 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 RestorePointCollectionUpdate. +func (r *RestorePointCollectionUpdate) UnmarshalJSON(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 RestorePointEncryption. +func (r RestorePointEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSet", r.DiskEncryptionSet) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointEncryption. +func (r *RestorePointEncryption) UnmarshalJSON(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 "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &r.DiskEncryptionSet) + 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 RestorePointInstanceView. +func (r RestorePointInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskRestorePoints", r.DiskRestorePoints) + populate(objectMap, "statuses", r.Statuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointInstanceView. +func (r *RestorePointInstanceView) UnmarshalJSON(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 "diskRestorePoints": + err = unpopulate(val, "DiskRestorePoints", &r.DiskRestorePoints) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &r.Statuses) + 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 RestorePointProperties. +func (r RestorePointProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "consistencyMode", r.ConsistencyMode) + populate(objectMap, "excludeDisks", r.ExcludeDisks) + populate(objectMap, "instanceView", r.InstanceView) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "sourceMetadata", r.SourceMetadata) + populate(objectMap, "sourceRestorePoint", r.SourceRestorePoint) + populateDateTimeRFC3339(objectMap, "timeCreated", r.TimeCreated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointProperties. +func (r *RestorePointProperties) UnmarshalJSON(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 "consistencyMode": + err = unpopulate(val, "ConsistencyMode", &r.ConsistencyMode) + delete(rawMsg, key) + case "excludeDisks": + err = unpopulate(val, "ExcludeDisks", &r.ExcludeDisks) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &r.InstanceView) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "sourceMetadata": + err = unpopulate(val, "SourceMetadata", &r.SourceMetadata) + delete(rawMsg, key) + case "sourceRestorePoint": + err = unpopulate(val, "SourceRestorePoint", &r.SourceRestorePoint) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &r.TimeCreated) + 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 RestorePointSourceMetadata. +func (r RestorePointSourceMetadata) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diagnosticsProfile", r.DiagnosticsProfile) + populate(objectMap, "hardwareProfile", r.HardwareProfile) + populate(objectMap, "hyperVGeneration", r.HyperVGeneration) + populate(objectMap, "licenseType", r.LicenseType) + populate(objectMap, "location", r.Location) + populate(objectMap, "osProfile", r.OSProfile) + populate(objectMap, "securityProfile", r.SecurityProfile) + populate(objectMap, "storageProfile", r.StorageProfile) + populate(objectMap, "userData", r.UserData) + populate(objectMap, "vmId", r.VMID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointSourceMetadata. +func (r *RestorePointSourceMetadata) UnmarshalJSON(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 "diagnosticsProfile": + err = unpopulate(val, "DiagnosticsProfile", &r.DiagnosticsProfile) + delete(rawMsg, key) + case "hardwareProfile": + err = unpopulate(val, "HardwareProfile", &r.HardwareProfile) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &r.HyperVGeneration) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &r.LicenseType) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &r.OSProfile) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &r.SecurityProfile) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &r.StorageProfile) + delete(rawMsg, key) + case "userData": + err = unpopulate(val, "UserData", &r.UserData) + delete(rawMsg, key) + case "vmId": + err = unpopulate(val, "VMID", &r.VMID) + 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 RestorePointSourceVMDataDisk. +func (r RestorePointSourceVMDataDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", r.Caching) + populate(objectMap, "diskRestorePoint", r.DiskRestorePoint) + populate(objectMap, "diskSizeGB", r.DiskSizeGB) + populate(objectMap, "lun", r.Lun) + populate(objectMap, "managedDisk", r.ManagedDisk) + populate(objectMap, "name", r.Name) + populate(objectMap, "writeAcceleratorEnabled", r.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointSourceVMDataDisk. +func (r *RestorePointSourceVMDataDisk) UnmarshalJSON(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 "caching": + err = unpopulate(val, "Caching", &r.Caching) + delete(rawMsg, key) + case "diskRestorePoint": + err = unpopulate(val, "DiskRestorePoint", &r.DiskRestorePoint) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &r.DiskSizeGB) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &r.Lun) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &r.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &r.WriteAcceleratorEnabled) + 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 RestorePointSourceVMOSDisk. +func (r RestorePointSourceVMOSDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", r.Caching) + populate(objectMap, "diskRestorePoint", r.DiskRestorePoint) + populate(objectMap, "diskSizeGB", r.DiskSizeGB) + populate(objectMap, "encryptionSettings", r.EncryptionSettings) + populate(objectMap, "managedDisk", r.ManagedDisk) + populate(objectMap, "name", r.Name) + populate(objectMap, "osType", r.OSType) + populate(objectMap, "writeAcceleratorEnabled", r.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointSourceVMOSDisk. +func (r *RestorePointSourceVMOSDisk) UnmarshalJSON(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 "caching": + err = unpopulate(val, "Caching", &r.Caching) + delete(rawMsg, key) + case "diskRestorePoint": + err = unpopulate(val, "DiskRestorePoint", &r.DiskRestorePoint) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &r.DiskSizeGB) + delete(rawMsg, key) + case "encryptionSettings": + err = unpopulate(val, "EncryptionSettings", &r.EncryptionSettings) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &r.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &r.OSType) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &r.WriteAcceleratorEnabled) + 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 RestorePointSourceVMStorageProfile. +func (r RestorePointSourceVMStorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisks", r.DataDisks) + populate(objectMap, "diskControllerType", r.DiskControllerType) + populate(objectMap, "osDisk", r.OSDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePointSourceVMStorageProfile. +func (r *RestorePointSourceVMStorageProfile) UnmarshalJSON(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 "dataDisks": + err = unpopulate(val, "DataDisks", &r.DataDisks) + delete(rawMsg, key) + case "diskControllerType": + err = unpopulate(val, "DiskControllerType", &r.DiskControllerType) + delete(rawMsg, key) + case "osDisk": + err = unpopulate(val, "OSDisk", &r.OSDisk) + 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 RetrieveBootDiagnosticsDataResult. +func (r RetrieveBootDiagnosticsDataResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "consoleScreenshotBlobUri", r.ConsoleScreenshotBlobURI) + populate(objectMap, "serialConsoleLogBlobUri", r.SerialConsoleLogBlobURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RetrieveBootDiagnosticsDataResult. +func (r *RetrieveBootDiagnosticsDataResult) UnmarshalJSON(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 "consoleScreenshotBlobUri": + err = unpopulate(val, "ConsoleScreenshotBlobURI", &r.ConsoleScreenshotBlobURI) + delete(rawMsg, key) + case "serialConsoleLogBlobUri": + err = unpopulate(val, "SerialConsoleLogBlobURI", &r.SerialConsoleLogBlobURI) + 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 RoleInstance. +func (r RoleInstance) 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, "sku", r.SKU) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleInstance. +func (r *RoleInstance) UnmarshalJSON(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 "sku": + err = unpopulate(val, "SKU", &r.SKU) + 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 RoleInstanceListResult. +func (r RoleInstanceListResult) 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 RoleInstanceListResult. +func (r *RoleInstanceListResult) UnmarshalJSON(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 RoleInstanceNetworkProfile. +func (r RoleInstanceNetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkInterfaces", r.NetworkInterfaces) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleInstanceNetworkProfile. +func (r *RoleInstanceNetworkProfile) UnmarshalJSON(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 "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &r.NetworkInterfaces) + 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 RoleInstanceProperties. +func (r RoleInstanceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceView", r.InstanceView) + populate(objectMap, "networkProfile", r.NetworkProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleInstanceProperties. +func (r *RoleInstanceProperties) UnmarshalJSON(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 "instanceView": + err = unpopulate(val, "InstanceView", &r.InstanceView) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &r.NetworkProfile) + 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 RoleInstanceView. +func (r RoleInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "platformFaultDomain", r.PlatformFaultDomain) + populate(objectMap, "platformUpdateDomain", r.PlatformUpdateDomain) + populate(objectMap, "privateId", r.PrivateID) + populate(objectMap, "statuses", r.Statuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleInstanceView. +func (r *RoleInstanceView) UnmarshalJSON(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 "platformFaultDomain": + err = unpopulate(val, "PlatformFaultDomain", &r.PlatformFaultDomain) + delete(rawMsg, key) + case "platformUpdateDomain": + err = unpopulate(val, "PlatformUpdateDomain", &r.PlatformUpdateDomain) + delete(rawMsg, key) + case "privateId": + err = unpopulate(val, "PrivateID", &r.PrivateID) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &r.Statuses) + 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 RoleInstances. +func (r RoleInstances) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "roleInstances", r.RoleInstances) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleInstances. +func (r *RoleInstances) UnmarshalJSON(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 "roleInstances": + err = unpopulate(val, "RoleInstances", &r.RoleInstances) + 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 RollbackStatusInfo. +func (r RollbackStatusInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "failedRolledbackInstanceCount", r.FailedRolledbackInstanceCount) + populate(objectMap, "rollbackError", r.RollbackError) + populate(objectMap, "successfullyRolledbackInstanceCount", r.SuccessfullyRolledbackInstanceCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RollbackStatusInfo. +func (r *RollbackStatusInfo) UnmarshalJSON(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 "failedRolledbackInstanceCount": + err = unpopulate(val, "FailedRolledbackInstanceCount", &r.FailedRolledbackInstanceCount) + delete(rawMsg, key) + case "rollbackError": + err = unpopulate(val, "RollbackError", &r.RollbackError) + delete(rawMsg, key) + case "successfullyRolledbackInstanceCount": + err = unpopulate(val, "SuccessfullyRolledbackInstanceCount", &r.SuccessfullyRolledbackInstanceCount) + 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 RollingUpgradePolicy. +func (r RollingUpgradePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enableCrossZoneUpgrade", r.EnableCrossZoneUpgrade) + populate(objectMap, "maxBatchInstancePercent", r.MaxBatchInstancePercent) + populate(objectMap, "maxSurge", r.MaxSurge) + populate(objectMap, "maxUnhealthyInstancePercent", r.MaxUnhealthyInstancePercent) + populate(objectMap, "maxUnhealthyUpgradedInstancePercent", r.MaxUnhealthyUpgradedInstancePercent) + populate(objectMap, "pauseTimeBetweenBatches", r.PauseTimeBetweenBatches) + populate(objectMap, "prioritizeUnhealthyInstances", r.PrioritizeUnhealthyInstances) + populate(objectMap, "rollbackFailedInstancesOnPolicyBreach", r.RollbackFailedInstancesOnPolicyBreach) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RollingUpgradePolicy. +func (r *RollingUpgradePolicy) UnmarshalJSON(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 "enableCrossZoneUpgrade": + err = unpopulate(val, "EnableCrossZoneUpgrade", &r.EnableCrossZoneUpgrade) + delete(rawMsg, key) + case "maxBatchInstancePercent": + err = unpopulate(val, "MaxBatchInstancePercent", &r.MaxBatchInstancePercent) + delete(rawMsg, key) + case "maxSurge": + err = unpopulate(val, "MaxSurge", &r.MaxSurge) + delete(rawMsg, key) + case "maxUnhealthyInstancePercent": + err = unpopulate(val, "MaxUnhealthyInstancePercent", &r.MaxUnhealthyInstancePercent) + delete(rawMsg, key) + case "maxUnhealthyUpgradedInstancePercent": + err = unpopulate(val, "MaxUnhealthyUpgradedInstancePercent", &r.MaxUnhealthyUpgradedInstancePercent) + delete(rawMsg, key) + case "pauseTimeBetweenBatches": + err = unpopulate(val, "PauseTimeBetweenBatches", &r.PauseTimeBetweenBatches) + delete(rawMsg, key) + case "prioritizeUnhealthyInstances": + err = unpopulate(val, "PrioritizeUnhealthyInstances", &r.PrioritizeUnhealthyInstances) + delete(rawMsg, key) + case "rollbackFailedInstancesOnPolicyBreach": + err = unpopulate(val, "RollbackFailedInstancesOnPolicyBreach", &r.RollbackFailedInstancesOnPolicyBreach) + 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 RollingUpgradeProgressInfo. +func (r RollingUpgradeProgressInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "failedInstanceCount", r.FailedInstanceCount) + populate(objectMap, "inProgressInstanceCount", r.InProgressInstanceCount) + populate(objectMap, "pendingInstanceCount", r.PendingInstanceCount) + populate(objectMap, "successfulInstanceCount", r.SuccessfulInstanceCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RollingUpgradeProgressInfo. +func (r *RollingUpgradeProgressInfo) UnmarshalJSON(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 "failedInstanceCount": + err = unpopulate(val, "FailedInstanceCount", &r.FailedInstanceCount) + delete(rawMsg, key) + case "inProgressInstanceCount": + err = unpopulate(val, "InProgressInstanceCount", &r.InProgressInstanceCount) + delete(rawMsg, key) + case "pendingInstanceCount": + err = unpopulate(val, "PendingInstanceCount", &r.PendingInstanceCount) + delete(rawMsg, key) + case "successfulInstanceCount": + err = unpopulate(val, "SuccessfulInstanceCount", &r.SuccessfulInstanceCount) + 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 RollingUpgradeRunningStatus. +func (r RollingUpgradeRunningStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", r.Code) + populate(objectMap, "lastAction", r.LastAction) + populateDateTimeRFC3339(objectMap, "lastActionTime", r.LastActionTime) + populateDateTimeRFC3339(objectMap, "startTime", r.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RollingUpgradeRunningStatus. +func (r *RollingUpgradeRunningStatus) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &r.Code) + delete(rawMsg, key) + case "lastAction": + err = unpopulate(val, "LastAction", &r.LastAction) + delete(rawMsg, key) + case "lastActionTime": + err = unpopulateDateTimeRFC3339(val, "LastActionTime", &r.LastActionTime) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &r.StartTime) + 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 RollingUpgradeStatusInfo. +func (r RollingUpgradeStatusInfo) 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, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RollingUpgradeStatusInfo. +func (r *RollingUpgradeStatusInfo) UnmarshalJSON(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 "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 RollingUpgradeStatusInfoProperties. +func (r RollingUpgradeStatusInfoProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", r.Error) + populate(objectMap, "policy", r.Policy) + populate(objectMap, "progress", r.Progress) + populate(objectMap, "runningStatus", r.RunningStatus) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RollingUpgradeStatusInfoProperties. +func (r *RollingUpgradeStatusInfoProperties) UnmarshalJSON(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 "error": + err = unpopulate(val, "Error", &r.Error) + delete(rawMsg, key) + case "policy": + err = unpopulate(val, "Policy", &r.Policy) + delete(rawMsg, key) + case "progress": + err = unpopulate(val, "Progress", &r.Progress) + delete(rawMsg, key) + case "runningStatus": + err = unpopulate(val, "RunningStatus", &r.RunningStatus) + 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 RunCommandDocument. +func (r RunCommandDocument) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", r.Description) + populate(objectMap, "id", r.ID) + populate(objectMap, "label", r.Label) + populate(objectMap, "osType", r.OSType) + populate(objectMap, "parameters", r.Parameters) + populate(objectMap, "$schema", r.Schema) + populate(objectMap, "script", r.Script) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunCommandDocument. +func (r *RunCommandDocument) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "label": + err = unpopulate(val, "Label", &r.Label) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &r.OSType) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, "Parameters", &r.Parameters) + delete(rawMsg, key) + case "$schema": + err = unpopulate(val, "Schema", &r.Schema) + delete(rawMsg, key) + case "script": + err = unpopulate(val, "Script", &r.Script) + 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 RunCommandDocumentBase. +func (r RunCommandDocumentBase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", r.Description) + populate(objectMap, "id", r.ID) + populate(objectMap, "label", r.Label) + populate(objectMap, "osType", r.OSType) + populate(objectMap, "$schema", r.Schema) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunCommandDocumentBase. +func (r *RunCommandDocumentBase) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "label": + err = unpopulate(val, "Label", &r.Label) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &r.OSType) + delete(rawMsg, key) + case "$schema": + err = unpopulate(val, "Schema", &r.Schema) + 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 RunCommandInput. +func (r RunCommandInput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commandId", r.CommandID) + populate(objectMap, "parameters", r.Parameters) + populate(objectMap, "script", r.Script) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunCommandInput. +func (r *RunCommandInput) UnmarshalJSON(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 "commandId": + err = unpopulate(val, "CommandID", &r.CommandID) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, "Parameters", &r.Parameters) + delete(rawMsg, key) + case "script": + err = unpopulate(val, "Script", &r.Script) + 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 RunCommandInputParameter. +func (r RunCommandInputParameter) 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 RunCommandInputParameter. +func (r *RunCommandInputParameter) UnmarshalJSON(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 RunCommandListResult. +func (r RunCommandListResult) 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 RunCommandListResult. +func (r *RunCommandListResult) UnmarshalJSON(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 RunCommandManagedIdentity. +func (r RunCommandManagedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", r.ClientID) + populate(objectMap, "objectId", r.ObjectID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunCommandManagedIdentity. +func (r *RunCommandManagedIdentity) UnmarshalJSON(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 "clientId": + err = unpopulate(val, "ClientID", &r.ClientID) + delete(rawMsg, key) + case "objectId": + err = unpopulate(val, "ObjectID", &r.ObjectID) + 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 RunCommandParameterDefinition. +func (r RunCommandParameterDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultValue", r.DefaultValue) + populate(objectMap, "name", r.Name) + populate(objectMap, "required", r.Required) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunCommandParameterDefinition. +func (r *RunCommandParameterDefinition) UnmarshalJSON(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 "defaultValue": + err = unpopulate(val, "DefaultValue", &r.DefaultValue) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "required": + err = unpopulate(val, "Required", &r.Required) + 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 RunCommandResult. +func (r RunCommandResult) 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 RunCommandResult. +func (r *RunCommandResult) UnmarshalJSON(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 SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", s.Capacity) + 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 "capacity": + err = unpopulate(val, "Capacity", &s.Capacity) + delete(rawMsg, 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 SSHConfiguration. +func (s SSHConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "publicKeys", s.PublicKeys) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SSHConfiguration. +func (s *SSHConfiguration) UnmarshalJSON(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 "publicKeys": + err = unpopulate(val, "PublicKeys", &s.PublicKeys) + 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 SSHGenerateKeyPairInputParameters. +func (s SSHGenerateKeyPairInputParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryptionType", s.EncryptionType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SSHGenerateKeyPairInputParameters. +func (s *SSHGenerateKeyPairInputParameters) UnmarshalJSON(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 "encryptionType": + err = unpopulate(val, "EncryptionType", &s.EncryptionType) + 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, "keyData", s.KeyData) + populate(objectMap, "path", s.Path) + 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 "keyData": + err = unpopulate(val, "KeyData", &s.KeyData) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &s.Path) + 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 SSHPublicKeyGenerateKeyPairResult. +func (s SSHPublicKeyGenerateKeyPairResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "privateKey", s.PrivateKey) + populate(objectMap, "publicKey", s.PublicKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SSHPublicKeyGenerateKeyPairResult. +func (s *SSHPublicKeyGenerateKeyPairResult) UnmarshalJSON(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 "privateKey": + err = unpopulate(val, "PrivateKey", &s.PrivateKey) + delete(rawMsg, key) + case "publicKey": + err = unpopulate(val, "PublicKey", &s.PublicKey) + 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 SSHPublicKeyResource. +func (s SSHPublicKeyResource) 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 SSHPublicKeyResource. +func (s *SSHPublicKeyResource) UnmarshalJSON(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 SSHPublicKeyResourceProperties. +func (s SSHPublicKeyResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "publicKey", s.PublicKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SSHPublicKeyResourceProperties. +func (s *SSHPublicKeyResourceProperties) UnmarshalJSON(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 "publicKey": + err = unpopulate(val, "PublicKey", &s.PublicKey) + 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 SSHPublicKeyUpdateResource. +func (s SSHPublicKeyUpdateResource) 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 SSHPublicKeyUpdateResource. +func (s *SSHPublicKeyUpdateResource) UnmarshalJSON(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 SSHPublicKeysGroupListResult. +func (s SSHPublicKeysGroupListResult) 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 SSHPublicKeysGroupListResult. +func (s *SSHPublicKeysGroupListResult) UnmarshalJSON(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 ScaleInPolicy. +func (s ScaleInPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "forceDeletion", s.ForceDeletion) + populate(objectMap, "rules", s.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScaleInPolicy. +func (s *ScaleInPolicy) UnmarshalJSON(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 "forceDeletion": + err = unpopulate(val, "ForceDeletion", &s.ForceDeletion) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &s.Rules) + 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 ScheduledEventsProfile. +func (s ScheduledEventsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "osImageNotificationProfile", s.OSImageNotificationProfile) + populate(objectMap, "terminateNotificationProfile", s.TerminateNotificationProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledEventsProfile. +func (s *ScheduledEventsProfile) UnmarshalJSON(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 "osImageNotificationProfile": + err = unpopulate(val, "OSImageNotificationProfile", &s.OSImageNotificationProfile) + delete(rawMsg, key) + case "terminateNotificationProfile": + err = unpopulate(val, "TerminateNotificationProfile", &s.TerminateNotificationProfile) + 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 SecurityPostureReference. +func (s SecurityPostureReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "excludeExtensions", s.ExcludeExtensions) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityPostureReference. +func (s *SecurityPostureReference) UnmarshalJSON(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 "excludeExtensions": + err = unpopulate(val, "ExcludeExtensions", &s.ExcludeExtensions) + 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 SecurityProfile. +func (s SecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryptionAtHost", s.EncryptionAtHost) + populate(objectMap, "encryptionIdentity", s.EncryptionIdentity) + populate(objectMap, "proxyAgentSettings", s.ProxyAgentSettings) + populate(objectMap, "securityType", s.SecurityType) + populate(objectMap, "uefiSettings", s.UefiSettings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityProfile. +func (s *SecurityProfile) UnmarshalJSON(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 "encryptionAtHost": + err = unpopulate(val, "EncryptionAtHost", &s.EncryptionAtHost) + delete(rawMsg, key) + case "encryptionIdentity": + err = unpopulate(val, "EncryptionIdentity", &s.EncryptionIdentity) + delete(rawMsg, key) + case "proxyAgentSettings": + err = unpopulate(val, "ProxyAgentSettings", &s.ProxyAgentSettings) + delete(rawMsg, key) + case "securityType": + err = unpopulate(val, "SecurityType", &s.SecurityType) + delete(rawMsg, key) + case "uefiSettings": + err = unpopulate(val, "UefiSettings", &s.UefiSettings) + 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 ServiceArtifactReference. +func (s ServiceArtifactReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceArtifactReference. +func (s *ServiceArtifactReference) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ShareInfoElement. +func (s ShareInfoElement) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vmUri", s.VMURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ShareInfoElement. +func (s *ShareInfoElement) UnmarshalJSON(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 "vmUri": + err = unpopulate(val, "VMURI", &s.VMURI) + 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 SharedGallery. +func (s SharedGallery) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", s.Identifier) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGallery. +func (s *SharedGallery) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &s.Identifier) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SharedGalleryDataDiskImage. +func (s SharedGalleryDataDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskSizeGB", s.DiskSizeGB) + populate(objectMap, "hostCaching", s.HostCaching) + populate(objectMap, "lun", s.Lun) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryDataDiskImage. +func (s *SharedGalleryDataDiskImage) UnmarshalJSON(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 "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &s.DiskSizeGB) + delete(rawMsg, key) + case "hostCaching": + err = unpopulate(val, "HostCaching", &s.HostCaching) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &s.Lun) + 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 SharedGalleryDiskImage. +func (s SharedGalleryDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskSizeGB", s.DiskSizeGB) + populate(objectMap, "hostCaching", s.HostCaching) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryDiskImage. +func (s *SharedGalleryDiskImage) UnmarshalJSON(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 "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &s.DiskSizeGB) + delete(rawMsg, key) + case "hostCaching": + err = unpopulate(val, "HostCaching", &s.HostCaching) + 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 SharedGalleryIdentifier. +func (s SharedGalleryIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uniqueId", s.UniqueID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryIdentifier. +func (s *SharedGalleryIdentifier) UnmarshalJSON(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 "uniqueId": + err = unpopulate(val, "UniqueID", &s.UniqueID) + 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 SharedGalleryImage. +func (s SharedGalleryImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", s.Identifier) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryImage. +func (s *SharedGalleryImage) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &s.Identifier) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SharedGalleryImageList. +func (s SharedGalleryImageList) 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 SharedGalleryImageList. +func (s *SharedGalleryImageList) UnmarshalJSON(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 SharedGalleryImageProperties. +func (s SharedGalleryImageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "architecture", s.Architecture) + populate(objectMap, "artifactTags", s.ArtifactTags) + populate(objectMap, "disallowed", s.Disallowed) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", s.EndOfLifeDate) + populate(objectMap, "eula", s.Eula) + populate(objectMap, "features", s.Features) + populate(objectMap, "hyperVGeneration", s.HyperVGeneration) + populate(objectMap, "identifier", s.Identifier) + populate(objectMap, "osState", s.OSState) + populate(objectMap, "osType", s.OSType) + populate(objectMap, "privacyStatementUri", s.PrivacyStatementURI) + populate(objectMap, "purchasePlan", s.PurchasePlan) + populate(objectMap, "recommended", s.Recommended) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryImageProperties. +func (s *SharedGalleryImageProperties) UnmarshalJSON(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 "architecture": + err = unpopulate(val, "Architecture", &s.Architecture) + delete(rawMsg, key) + case "artifactTags": + err = unpopulate(val, "ArtifactTags", &s.ArtifactTags) + delete(rawMsg, key) + case "disallowed": + err = unpopulate(val, "Disallowed", &s.Disallowed) + delete(rawMsg, key) + case "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &s.EndOfLifeDate) + delete(rawMsg, key) + case "eula": + err = unpopulate(val, "Eula", &s.Eula) + delete(rawMsg, key) + case "features": + err = unpopulate(val, "Features", &s.Features) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &s.HyperVGeneration) + delete(rawMsg, key) + case "identifier": + err = unpopulate(val, "Identifier", &s.Identifier) + delete(rawMsg, key) + case "osState": + err = unpopulate(val, "OSState", &s.OSState) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &s.OSType) + delete(rawMsg, key) + case "privacyStatementUri": + err = unpopulate(val, "PrivacyStatementURI", &s.PrivacyStatementURI) + delete(rawMsg, key) + case "purchasePlan": + err = unpopulate(val, "PurchasePlan", &s.PurchasePlan) + delete(rawMsg, key) + case "recommended": + err = unpopulate(val, "Recommended", &s.Recommended) + 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 SharedGalleryImageVersion. +func (s SharedGalleryImageVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", s.Identifier) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryImageVersion. +func (s *SharedGalleryImageVersion) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &s.Identifier) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SharedGalleryImageVersionList. +func (s SharedGalleryImageVersionList) 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 SharedGalleryImageVersionList. +func (s *SharedGalleryImageVersionList) UnmarshalJSON(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 SharedGalleryImageVersionProperties. +func (s SharedGalleryImageVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "artifactTags", s.ArtifactTags) + populateDateTimeRFC3339(objectMap, "endOfLifeDate", s.EndOfLifeDate) + populate(objectMap, "excludeFromLatest", s.ExcludeFromLatest) + populateDateTimeRFC3339(objectMap, "publishedDate", s.PublishedDate) + populate(objectMap, "storageProfile", s.StorageProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryImageVersionProperties. +func (s *SharedGalleryImageVersionProperties) UnmarshalJSON(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 "artifactTags": + err = unpopulate(val, "ArtifactTags", &s.ArtifactTags) + delete(rawMsg, key) + case "endOfLifeDate": + err = unpopulateDateTimeRFC3339(val, "EndOfLifeDate", &s.EndOfLifeDate) + delete(rawMsg, key) + case "excludeFromLatest": + err = unpopulate(val, "ExcludeFromLatest", &s.ExcludeFromLatest) + delete(rawMsg, key) + case "publishedDate": + err = unpopulateDateTimeRFC3339(val, "PublishedDate", &s.PublishedDate) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &s.StorageProfile) + 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 SharedGalleryImageVersionStorageProfile. +func (s SharedGalleryImageVersionStorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDiskImages", s.DataDiskImages) + populate(objectMap, "osDiskImage", s.OSDiskImage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryImageVersionStorageProfile. +func (s *SharedGalleryImageVersionStorageProfile) UnmarshalJSON(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 "dataDiskImages": + err = unpopulate(val, "DataDiskImages", &s.DataDiskImages) + delete(rawMsg, key) + case "osDiskImage": + err = unpopulate(val, "OSDiskImage", &s.OSDiskImage) + 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 SharedGalleryList. +func (s SharedGalleryList) 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 SharedGalleryList. +func (s *SharedGalleryList) UnmarshalJSON(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 SharedGalleryOSDiskImage. +func (s SharedGalleryOSDiskImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskSizeGB", s.DiskSizeGB) + populate(objectMap, "hostCaching", s.HostCaching) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryOSDiskImage. +func (s *SharedGalleryOSDiskImage) UnmarshalJSON(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 "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &s.DiskSizeGB) + delete(rawMsg, key) + case "hostCaching": + err = unpopulate(val, "HostCaching", &s.HostCaching) + 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 SharedGalleryProperties. +func (s SharedGalleryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "artifactTags", s.ArtifactTags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedGalleryProperties. +func (s *SharedGalleryProperties) UnmarshalJSON(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 "artifactTags": + err = unpopulate(val, "ArtifactTags", &s.ArtifactTags) + 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 SharingProfile. +func (s SharingProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityGalleryInfo", s.CommunityGalleryInfo) + populate(objectMap, "groups", s.Groups) + populate(objectMap, "permissions", s.Permissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharingProfile. +func (s *SharingProfile) UnmarshalJSON(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 "communityGalleryInfo": + err = unpopulate(val, "CommunityGalleryInfo", &s.CommunityGalleryInfo) + delete(rawMsg, key) + case "groups": + err = unpopulate(val, "Groups", &s.Groups) + delete(rawMsg, key) + case "permissions": + err = unpopulate(val, "Permissions", &s.Permissions) + 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 SharingProfileGroup. +func (s SharingProfileGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ids", s.IDs) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharingProfileGroup. +func (s *SharingProfileGroup) UnmarshalJSON(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 "ids": + err = unpopulate(val, "IDs", &s.IDs) + 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 SharingStatus. +func (s SharingStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregatedState", s.AggregatedState) + populate(objectMap, "summary", s.Summary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharingStatus. +func (s *SharingStatus) UnmarshalJSON(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 "aggregatedState": + err = unpopulate(val, "AggregatedState", &s.AggregatedState) + delete(rawMsg, key) + case "summary": + err = unpopulate(val, "Summary", &s.Summary) + 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 SharingUpdate. +func (s SharingUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groups", s.Groups) + populate(objectMap, "operationType", s.OperationType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharingUpdate. +func (s *SharingUpdate) UnmarshalJSON(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 "groups": + err = unpopulate(val, "Groups", &s.Groups) + delete(rawMsg, key) + case "operationType": + err = unpopulate(val, "OperationType", &s.OperationType) + 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) + populate(objectMap, "extendedLocation", s.ExtendedLocation) + populate(objectMap, "id", s.ID) + populate(objectMap, "location", s.Location) + populate(objectMap, "managedBy", s.ManagedBy) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Snapshot. +func (s *Snapshot) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &s.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &s.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &s.ManagedBy) + 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 "sku": + err = unpopulate(val, "SKU", &s.SKU) + 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 SnapshotList. +func (s SnapshotList) 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 SnapshotList. +func (s *SnapshotList) UnmarshalJSON(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 SnapshotProperties. +func (s SnapshotProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "completionPercent", s.CompletionPercent) + populate(objectMap, "copyCompletionError", s.CopyCompletionError) + populate(objectMap, "creationData", s.CreationData) + populate(objectMap, "dataAccessAuthMode", s.DataAccessAuthMode) + populate(objectMap, "diskAccessId", s.DiskAccessID) + populate(objectMap, "diskSizeBytes", s.DiskSizeBytes) + populate(objectMap, "diskSizeGB", s.DiskSizeGB) + populate(objectMap, "diskState", s.DiskState) + populate(objectMap, "encryption", s.Encryption) + populate(objectMap, "encryptionSettingsCollection", s.EncryptionSettingsCollection) + populate(objectMap, "hyperVGeneration", s.HyperVGeneration) + populate(objectMap, "incremental", s.Incremental) + populate(objectMap, "incrementalSnapshotFamilyId", s.IncrementalSnapshotFamilyID) + populate(objectMap, "networkAccessPolicy", s.NetworkAccessPolicy) + populate(objectMap, "osType", s.OSType) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "publicNetworkAccess", s.PublicNetworkAccess) + populate(objectMap, "purchasePlan", s.PurchasePlan) + populate(objectMap, "securityProfile", s.SecurityProfile) + populate(objectMap, "supportedCapabilities", s.SupportedCapabilities) + populate(objectMap, "supportsHibernation", s.SupportsHibernation) + populateDateTimeRFC3339(objectMap, "timeCreated", s.TimeCreated) + populate(objectMap, "uniqueId", s.UniqueID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SnapshotProperties. +func (s *SnapshotProperties) UnmarshalJSON(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 "completionPercent": + err = unpopulate(val, "CompletionPercent", &s.CompletionPercent) + delete(rawMsg, key) + case "copyCompletionError": + err = unpopulate(val, "CopyCompletionError", &s.CopyCompletionError) + delete(rawMsg, key) + case "creationData": + err = unpopulate(val, "CreationData", &s.CreationData) + delete(rawMsg, key) + case "dataAccessAuthMode": + err = unpopulate(val, "DataAccessAuthMode", &s.DataAccessAuthMode) + delete(rawMsg, key) + case "diskAccessId": + err = unpopulate(val, "DiskAccessID", &s.DiskAccessID) + delete(rawMsg, key) + case "diskSizeBytes": + err = unpopulate(val, "DiskSizeBytes", &s.DiskSizeBytes) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &s.DiskSizeGB) + delete(rawMsg, key) + case "diskState": + err = unpopulate(val, "DiskState", &s.DiskState) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &s.Encryption) + delete(rawMsg, key) + case "encryptionSettingsCollection": + err = unpopulate(val, "EncryptionSettingsCollection", &s.EncryptionSettingsCollection) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &s.HyperVGeneration) + delete(rawMsg, key) + case "incremental": + err = unpopulate(val, "Incremental", &s.Incremental) + delete(rawMsg, key) + case "incrementalSnapshotFamilyId": + err = unpopulate(val, "IncrementalSnapshotFamilyID", &s.IncrementalSnapshotFamilyID) + delete(rawMsg, key) + case "networkAccessPolicy": + err = unpopulate(val, "NetworkAccessPolicy", &s.NetworkAccessPolicy) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &s.OSType) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &s.PublicNetworkAccess) + delete(rawMsg, key) + case "purchasePlan": + err = unpopulate(val, "PurchasePlan", &s.PurchasePlan) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &s.SecurityProfile) + delete(rawMsg, key) + case "supportedCapabilities": + err = unpopulate(val, "SupportedCapabilities", &s.SupportedCapabilities) + delete(rawMsg, key) + case "supportsHibernation": + err = unpopulate(val, "SupportsHibernation", &s.SupportsHibernation) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &s.TimeCreated) + delete(rawMsg, key) + case "uniqueId": + err = unpopulate(val, "UniqueID", &s.UniqueID) + 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 SnapshotSKU. +func (s SnapshotSKU) 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 SnapshotSKU. +func (s *SnapshotSKU) UnmarshalJSON(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 SnapshotUpdate. +func (s SnapshotUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SnapshotUpdate. +func (s *SnapshotUpdate) UnmarshalJSON(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 "sku": + err = unpopulate(val, "SKU", &s.SKU) + 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 SnapshotUpdateProperties. +func (s SnapshotUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataAccessAuthMode", s.DataAccessAuthMode) + populate(objectMap, "diskAccessId", s.DiskAccessID) + populate(objectMap, "diskSizeGB", s.DiskSizeGB) + populate(objectMap, "encryption", s.Encryption) + populate(objectMap, "encryptionSettingsCollection", s.EncryptionSettingsCollection) + populate(objectMap, "networkAccessPolicy", s.NetworkAccessPolicy) + populate(objectMap, "osType", s.OSType) + populate(objectMap, "publicNetworkAccess", s.PublicNetworkAccess) + populate(objectMap, "supportedCapabilities", s.SupportedCapabilities) + populate(objectMap, "supportsHibernation", s.SupportsHibernation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SnapshotUpdateProperties. +func (s *SnapshotUpdateProperties) UnmarshalJSON(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 "dataAccessAuthMode": + err = unpopulate(val, "DataAccessAuthMode", &s.DataAccessAuthMode) + delete(rawMsg, key) + case "diskAccessId": + err = unpopulate(val, "DiskAccessID", &s.DiskAccessID) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &s.DiskSizeGB) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &s.Encryption) + delete(rawMsg, key) + case "encryptionSettingsCollection": + err = unpopulate(val, "EncryptionSettingsCollection", &s.EncryptionSettingsCollection) + delete(rawMsg, key) + case "networkAccessPolicy": + err = unpopulate(val, "NetworkAccessPolicy", &s.NetworkAccessPolicy) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &s.OSType) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &s.PublicNetworkAccess) + delete(rawMsg, key) + case "supportedCapabilities": + err = unpopulate(val, "SupportedCapabilities", &s.SupportedCapabilities) + delete(rawMsg, key) + case "supportsHibernation": + err = unpopulate(val, "SupportsHibernation", &s.SupportsHibernation) + 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 SoftDeletePolicy. +func (s SoftDeletePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isSoftDeleteEnabled", s.IsSoftDeleteEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SoftDeletePolicy. +func (s *SoftDeletePolicy) UnmarshalJSON(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 "isSoftDeleteEnabled": + err = unpopulate(val, "IsSoftDeleteEnabled", &s.IsSoftDeleteEnabled) + 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 SourceVault. +func (s SourceVault) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceVault. +func (s *SourceVault) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SpotRestorePolicy. +func (s SpotRestorePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", s.Enabled) + populate(objectMap, "restoreTimeout", s.RestoreTimeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SpotRestorePolicy. +func (s *SpotRestorePolicy) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &s.Enabled) + delete(rawMsg, key) + case "restoreTimeout": + err = unpopulate(val, "RestoreTimeout", &s.RestoreTimeout) + 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 StatusCodeCount. +func (s StatusCodeCount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", s.Code) + populate(objectMap, "count", s.Count) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StatusCodeCount. +func (s *StatusCodeCount) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &s.Code) + delete(rawMsg, key) + case "count": + err = unpopulate(val, "Count", &s.Count) + 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 StorageProfile. +func (s StorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisks", s.DataDisks) + populate(objectMap, "diskControllerType", s.DiskControllerType) + populate(objectMap, "imageReference", s.ImageReference) + populate(objectMap, "osDisk", s.OSDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageProfile. +func (s *StorageProfile) UnmarshalJSON(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 "dataDisks": + err = unpopulate(val, "DataDisks", &s.DataDisks) + delete(rawMsg, key) + case "diskControllerType": + err = unpopulate(val, "DiskControllerType", &s.DiskControllerType) + delete(rawMsg, key) + case "imageReference": + err = unpopulate(val, "ImageReference", &s.ImageReference) + delete(rawMsg, key) + case "osDisk": + err = unpopulate(val, "OSDisk", &s.OSDisk) + 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 SubResource. +func (s SubResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubResource. +func (s *SubResource) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubResourceReadOnly. +func (s SubResourceReadOnly) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubResourceReadOnly. +func (s *SubResourceReadOnly) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubResourceWithColocationStatus. +func (s SubResourceWithColocationStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "colocationStatus", s.ColocationStatus) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubResourceWithColocationStatus. +func (s *SubResourceWithColocationStatus) UnmarshalJSON(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 "colocationStatus": + err = unpopulate(val, "ColocationStatus", &s.ColocationStatus) + 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 SupportedCapabilities. +func (s SupportedCapabilities) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "acceleratedNetwork", s.AcceleratedNetwork) + populate(objectMap, "architecture", s.Architecture) + populate(objectMap, "diskControllerTypes", s.DiskControllerTypes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SupportedCapabilities. +func (s *SupportedCapabilities) UnmarshalJSON(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 "acceleratedNetwork": + err = unpopulate(val, "AcceleratedNetwork", &s.AcceleratedNetwork) + delete(rawMsg, key) + case "architecture": + err = unpopulate(val, "Architecture", &s.Architecture) + delete(rawMsg, key) + case "diskControllerTypes": + err = unpopulate(val, "DiskControllerTypes", &s.DiskControllerTypes) + 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) + populateDateTimeRFC3339(objectMap, "lastModifiedAt", s.LastModifiedAt) + 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 "lastModifiedAt": + err = unpopulateDateTimeRFC3339(val, "LastModifiedAt", &s.LastModifiedAt) + 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 TargetRegion. +func (t TargetRegion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryption", t.Encryption) + populate(objectMap, "excludeFromLatest", t.ExcludeFromLatest) + populate(objectMap, "name", t.Name) + populate(objectMap, "regionalReplicaCount", t.RegionalReplicaCount) + populate(objectMap, "storageAccountType", t.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TargetRegion. +func (t *TargetRegion) UnmarshalJSON(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 "encryption": + err = unpopulate(val, "Encryption", &t.Encryption) + delete(rawMsg, key) + case "excludeFromLatest": + err = unpopulate(val, "ExcludeFromLatest", &t.ExcludeFromLatest) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "regionalReplicaCount": + err = unpopulate(val, "RegionalReplicaCount", &t.RegionalReplicaCount) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &t.StorageAccountType) + 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 TerminateNotificationProfile. +func (t TerminateNotificationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enable", t.Enable) + populate(objectMap, "notBeforeTimeout", t.NotBeforeTimeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TerminateNotificationProfile. +func (t *TerminateNotificationProfile) UnmarshalJSON(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 "enable": + err = unpopulate(val, "Enable", &t.Enable) + delete(rawMsg, key) + case "notBeforeTimeout": + err = unpopulate(val, "NotBeforeTimeout", &t.NotBeforeTimeout) + 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 ThrottledRequestsInput. +func (t ThrottledRequestsInput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobContainerSasUri", t.BlobContainerSasURI) + populateDateTimeRFC3339(objectMap, "fromTime", t.FromTime) + populate(objectMap, "groupByClientApplicationId", t.GroupByClientApplicationID) + populate(objectMap, "groupByOperationName", t.GroupByOperationName) + populate(objectMap, "groupByResourceName", t.GroupByResourceName) + populate(objectMap, "groupByThrottlePolicy", t.GroupByThrottlePolicy) + populate(objectMap, "groupByUserAgent", t.GroupByUserAgent) + populateDateTimeRFC3339(objectMap, "toTime", t.ToTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ThrottledRequestsInput. +func (t *ThrottledRequestsInput) UnmarshalJSON(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 "blobContainerSasUri": + err = unpopulate(val, "BlobContainerSasURI", &t.BlobContainerSasURI) + delete(rawMsg, key) + case "fromTime": + err = unpopulateDateTimeRFC3339(val, "FromTime", &t.FromTime) + delete(rawMsg, key) + case "groupByClientApplicationId": + err = unpopulate(val, "GroupByClientApplicationID", &t.GroupByClientApplicationID) + delete(rawMsg, key) + case "groupByOperationName": + err = unpopulate(val, "GroupByOperationName", &t.GroupByOperationName) + delete(rawMsg, key) + case "groupByResourceName": + err = unpopulate(val, "GroupByResourceName", &t.GroupByResourceName) + delete(rawMsg, key) + case "groupByThrottlePolicy": + err = unpopulate(val, "GroupByThrottlePolicy", &t.GroupByThrottlePolicy) + delete(rawMsg, key) + case "groupByUserAgent": + err = unpopulate(val, "GroupByUserAgent", &t.GroupByUserAgent) + delete(rawMsg, key) + case "toTime": + err = unpopulateDateTimeRFC3339(val, "ToTime", &t.ToTime) + 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 UefiKey. +func (u UefiKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", u.Type) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UefiKey. +func (u *UefiKey) UnmarshalJSON(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 "type": + err = unpopulate(val, "Type", &u.Type) + 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 UefiKeySignatures. +func (u UefiKeySignatures) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "db", u.Db) + populate(objectMap, "dbx", u.Dbx) + populate(objectMap, "kek", u.Kek) + populate(objectMap, "pk", u.Pk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UefiKeySignatures. +func (u *UefiKeySignatures) UnmarshalJSON(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 "db": + err = unpopulate(val, "Db", &u.Db) + delete(rawMsg, key) + case "dbx": + err = unpopulate(val, "Dbx", &u.Dbx) + delete(rawMsg, key) + case "kek": + err = unpopulate(val, "Kek", &u.Kek) + delete(rawMsg, key) + case "pk": + err = unpopulate(val, "Pk", &u.Pk) + 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 UefiSettings. +func (u UefiSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secureBootEnabled", u.SecureBootEnabled) + populate(objectMap, "vTpmEnabled", u.VTpmEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UefiSettings. +func (u *UefiSettings) UnmarshalJSON(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 "secureBootEnabled": + err = unpopulate(val, "SecureBootEnabled", &u.SecureBootEnabled) + delete(rawMsg, key) + case "vTpmEnabled": + err = unpopulate(val, "VTpmEnabled", &u.VTpmEnabled) + 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 UpdateDomain. +func (u UpdateDomain) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", u.ID) + populate(objectMap, "name", u.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateDomain. +func (u *UpdateDomain) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + 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 UpdateDomainListResult. +func (u UpdateDomainListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", u.NextLink) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateDomainListResult. +func (u *UpdateDomainListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &u.NextLink) + 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 UpdateResource. +func (u UpdateResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", u.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateResource. +func (u *UpdateResource) UnmarshalJSON(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 "tags": + err = unpopulate(val, "Tags", &u.Tags) + 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 UpdateResourceDefinition. +func (u UpdateResourceDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", u.ID) + populate(objectMap, "name", u.Name) + populate(objectMap, "tags", u.Tags) + populate(objectMap, "type", u.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateResourceDefinition. +func (u *UpdateResourceDefinition) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &u.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &u.Type) + 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 UpgradeOperationHistoricalStatusInfo. +func (u UpgradeOperationHistoricalStatusInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", u.Location) + populate(objectMap, "properties", u.Properties) + populate(objectMap, "type", u.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpgradeOperationHistoricalStatusInfo. +func (u *UpgradeOperationHistoricalStatusInfo) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &u.Location) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &u.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &u.Type) + 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 UpgradeOperationHistoricalStatusInfoProperties. +func (u UpgradeOperationHistoricalStatusInfoProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", u.Error) + populate(objectMap, "progress", u.Progress) + populate(objectMap, "rollbackInfo", u.RollbackInfo) + populate(objectMap, "runningStatus", u.RunningStatus) + populate(objectMap, "startedBy", u.StartedBy) + populate(objectMap, "targetImageReference", u.TargetImageReference) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpgradeOperationHistoricalStatusInfoProperties. +func (u *UpgradeOperationHistoricalStatusInfoProperties) UnmarshalJSON(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 "error": + err = unpopulate(val, "Error", &u.Error) + delete(rawMsg, key) + case "progress": + err = unpopulate(val, "Progress", &u.Progress) + delete(rawMsg, key) + case "rollbackInfo": + err = unpopulate(val, "RollbackInfo", &u.RollbackInfo) + delete(rawMsg, key) + case "runningStatus": + err = unpopulate(val, "RunningStatus", &u.RunningStatus) + delete(rawMsg, key) + case "startedBy": + err = unpopulate(val, "StartedBy", &u.StartedBy) + delete(rawMsg, key) + case "targetImageReference": + err = unpopulate(val, "TargetImageReference", &u.TargetImageReference) + 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 UpgradeOperationHistoryStatus. +func (u UpgradeOperationHistoryStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", u.Code) + populateDateTimeRFC3339(objectMap, "endTime", u.EndTime) + populateDateTimeRFC3339(objectMap, "startTime", u.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpgradeOperationHistoryStatus. +func (u *UpgradeOperationHistoryStatus) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &u.Code) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &u.EndTime) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &u.StartTime) + 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 UpgradePolicy. +func (u UpgradePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticOSUpgradePolicy", u.AutomaticOSUpgradePolicy) + populate(objectMap, "mode", u.Mode) + populate(objectMap, "rollingUpgradePolicy", u.RollingUpgradePolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpgradePolicy. +func (u *UpgradePolicy) UnmarshalJSON(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 "automaticOSUpgradePolicy": + err = unpopulate(val, "AutomaticOSUpgradePolicy", &u.AutomaticOSUpgradePolicy) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &u.Mode) + delete(rawMsg, key) + case "rollingUpgradePolicy": + err = unpopulate(val, "RollingUpgradePolicy", &u.RollingUpgradePolicy) + 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) + objectMap["unit"] = "Count" + 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 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 UserArtifactManage. +func (u UserArtifactManage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "install", u.Install) + populate(objectMap, "remove", u.Remove) + populate(objectMap, "update", u.Update) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserArtifactManage. +func (u *UserArtifactManage) UnmarshalJSON(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 "install": + err = unpopulate(val, "Install", &u.Install) + delete(rawMsg, key) + case "remove": + err = unpopulate(val, "Remove", &u.Remove) + delete(rawMsg, key) + case "update": + err = unpopulate(val, "Update", &u.Update) + 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 UserArtifactSettings. +func (u UserArtifactSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configFileName", u.ConfigFileName) + populate(objectMap, "packageFileName", u.PackageFileName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserArtifactSettings. +func (u *UserArtifactSettings) UnmarshalJSON(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 "configFileName": + err = unpopulate(val, "ConfigFileName", &u.ConfigFileName) + delete(rawMsg, key) + case "packageFileName": + err = unpopulate(val, "PackageFileName", &u.PackageFileName) + 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 UserArtifactSource. +func (u UserArtifactSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultConfigurationLink", u.DefaultConfigurationLink) + populate(objectMap, "mediaLink", u.MediaLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserArtifactSource. +func (u *UserArtifactSource) UnmarshalJSON(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 "defaultConfigurationLink": + err = unpopulate(val, "DefaultConfigurationLink", &u.DefaultConfigurationLink) + delete(rawMsg, key) + case "mediaLink": + err = unpopulate(val, "MediaLink", &u.MediaLink) + 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 UserAssignedIdentitiesValue. +func (u UserAssignedIdentitiesValue) 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 UserAssignedIdentitiesValue. +func (u *UserAssignedIdentitiesValue) UnmarshalJSON(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 VMDiskSecurityProfile. +func (v VMDiskSecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSet", v.DiskEncryptionSet) + populate(objectMap, "securityEncryptionType", v.SecurityEncryptionType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMDiskSecurityProfile. +func (v *VMDiskSecurityProfile) UnmarshalJSON(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 "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &v.DiskEncryptionSet) + delete(rawMsg, key) + case "securityEncryptionType": + err = unpopulate(val, "SecurityEncryptionType", &v.SecurityEncryptionType) + 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 VMGalleryApplication. +func (v VMGalleryApplication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configurationReference", v.ConfigurationReference) + populate(objectMap, "enableAutomaticUpgrade", v.EnableAutomaticUpgrade) + populate(objectMap, "order", v.Order) + populate(objectMap, "packageReferenceId", v.PackageReferenceID) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "treatFailureAsDeploymentFailure", v.TreatFailureAsDeploymentFailure) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMGalleryApplication. +func (v *VMGalleryApplication) UnmarshalJSON(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 "configurationReference": + err = unpopulate(val, "ConfigurationReference", &v.ConfigurationReference) + delete(rawMsg, key) + case "enableAutomaticUpgrade": + err = unpopulate(val, "EnableAutomaticUpgrade", &v.EnableAutomaticUpgrade) + delete(rawMsg, key) + case "order": + err = unpopulate(val, "Order", &v.Order) + delete(rawMsg, key) + case "packageReferenceId": + err = unpopulate(val, "PackageReferenceID", &v.PackageReferenceID) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + case "treatFailureAsDeploymentFailure": + err = unpopulate(val, "TreatFailureAsDeploymentFailure", &v.TreatFailureAsDeploymentFailure) + 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 VMImagesInEdgeZoneListResult. +func (v VMImagesInEdgeZoneListResult) 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 VMImagesInEdgeZoneListResult. +func (v *VMImagesInEdgeZoneListResult) UnmarshalJSON(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 VMScaleSetConvertToSinglePlacementGroupInput. +func (v VMScaleSetConvertToSinglePlacementGroupInput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activePlacementGroupId", v.ActivePlacementGroupID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMScaleSetConvertToSinglePlacementGroupInput. +func (v *VMScaleSetConvertToSinglePlacementGroupInput) UnmarshalJSON(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 "activePlacementGroupId": + err = unpopulate(val, "ActivePlacementGroupID", &v.ActivePlacementGroupID) + 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 VMSizeProperties. +func (v VMSizeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vCPUsAvailable", v.VCPUsAvailable) + populate(objectMap, "vCPUsPerCore", v.VCPUsPerCore) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMSizeProperties. +func (v *VMSizeProperties) UnmarshalJSON(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 "vCPUsAvailable": + err = unpopulate(val, "VCPUsAvailable", &v.VCPUsAvailable) + delete(rawMsg, key) + case "vCPUsPerCore": + err = unpopulate(val, "VCPUsPerCore", &v.VCPUsPerCore) + 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 VaultCertificate. +func (v VaultCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateStore", v.CertificateStore) + populate(objectMap, "certificateUrl", v.CertificateURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultCertificate. +func (v *VaultCertificate) UnmarshalJSON(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 "certificateStore": + err = unpopulate(val, "CertificateStore", &v.CertificateStore) + delete(rawMsg, key) + case "certificateUrl": + err = unpopulate(val, "CertificateURL", &v.CertificateURL) + 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 VaultSecretGroup. +func (v VaultSecretGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sourceVault", v.SourceVault) + populate(objectMap, "vaultCertificates", v.VaultCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultSecretGroup. +func (v *VaultSecretGroup) UnmarshalJSON(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 "sourceVault": + err = unpopulate(val, "SourceVault", &v.SourceVault) + delete(rawMsg, key) + case "vaultCertificates": + err = unpopulate(val, "VaultCertificates", &v.VaultCertificates) + 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 VirtualHardDisk. +func (v VirtualHardDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uri", v.URI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHardDisk. +func (v *VirtualHardDisk) UnmarshalJSON(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 "uri": + err = unpopulate(val, "URI", &v.URI) + 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 VirtualMachine. +func (v VirtualMachine) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "extendedLocation", v.ExtendedLocation) + populate(objectMap, "id", v.ID) + populate(objectMap, "identity", v.Identity) + populate(objectMap, "location", v.Location) + populate(objectMap, "managedBy", v.ManagedBy) + populate(objectMap, "name", v.Name) + populate(objectMap, "plan", v.Plan) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "resources", v.Resources) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + populate(objectMap, "zones", v.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachine. +func (v *VirtualMachine) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &v.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &v.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &v.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &v.ManagedBy) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &v.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &v.Resources) + 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) + case "zones": + err = unpopulate(val, "Zones", &v.Zones) + 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 VirtualMachineAgentInstanceView. +func (v VirtualMachineAgentInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extensionHandlers", v.ExtensionHandlers) + populate(objectMap, "statuses", v.Statuses) + populate(objectMap, "vmAgentVersion", v.VMAgentVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineAgentInstanceView. +func (v *VirtualMachineAgentInstanceView) UnmarshalJSON(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 "extensionHandlers": + err = unpopulate(val, "ExtensionHandlers", &v.ExtensionHandlers) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &v.Statuses) + delete(rawMsg, key) + case "vmAgentVersion": + err = unpopulate(val, "VMAgentVersion", &v.VMAgentVersion) + 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 VirtualMachineAssessPatchesResult. +func (v VirtualMachineAssessPatchesResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assessmentActivityId", v.AssessmentActivityID) + populate(objectMap, "availablePatches", v.AvailablePatches) + populate(objectMap, "criticalAndSecurityPatchCount", v.CriticalAndSecurityPatchCount) + populate(objectMap, "error", v.Error) + populate(objectMap, "otherPatchCount", v.OtherPatchCount) + populate(objectMap, "rebootPending", v.RebootPending) + populateDateTimeRFC3339(objectMap, "startDateTime", v.StartDateTime) + populate(objectMap, "status", v.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineAssessPatchesResult. +func (v *VirtualMachineAssessPatchesResult) UnmarshalJSON(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 "assessmentActivityId": + err = unpopulate(val, "AssessmentActivityID", &v.AssessmentActivityID) + delete(rawMsg, key) + case "availablePatches": + err = unpopulate(val, "AvailablePatches", &v.AvailablePatches) + delete(rawMsg, key) + case "criticalAndSecurityPatchCount": + err = unpopulate(val, "CriticalAndSecurityPatchCount", &v.CriticalAndSecurityPatchCount) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &v.Error) + delete(rawMsg, key) + case "otherPatchCount": + err = unpopulate(val, "OtherPatchCount", &v.OtherPatchCount) + delete(rawMsg, key) + case "rebootPending": + err = unpopulate(val, "RebootPending", &v.RebootPending) + delete(rawMsg, key) + case "startDateTime": + err = unpopulateDateTimeRFC3339(val, "StartDateTime", &v.StartDateTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &v.Status) + 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 VirtualMachineCaptureParameters. +func (v VirtualMachineCaptureParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationContainerName", v.DestinationContainerName) + populate(objectMap, "overwriteVhds", v.OverwriteVhds) + populate(objectMap, "vhdPrefix", v.VhdPrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineCaptureParameters. +func (v *VirtualMachineCaptureParameters) UnmarshalJSON(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 "destinationContainerName": + err = unpopulate(val, "DestinationContainerName", &v.DestinationContainerName) + delete(rawMsg, key) + case "overwriteVhds": + err = unpopulate(val, "OverwriteVhds", &v.OverwriteVhds) + delete(rawMsg, key) + case "vhdPrefix": + err = unpopulate(val, "VhdPrefix", &v.VhdPrefix) + 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 VirtualMachineCaptureResult. +func (v VirtualMachineCaptureResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentVersion", v.ContentVersion) + populate(objectMap, "id", v.ID) + populateAny(objectMap, "parameters", v.Parameters) + populate(objectMap, "resources", v.Resources) + populate(objectMap, "$schema", v.Schema) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineCaptureResult. +func (v *VirtualMachineCaptureResult) UnmarshalJSON(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 "contentVersion": + err = unpopulate(val, "ContentVersion", &v.ContentVersion) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, "Parameters", &v.Parameters) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &v.Resources) + delete(rawMsg, key) + case "$schema": + err = unpopulate(val, "Schema", &v.Schema) + 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 VirtualMachineExtension. +func (v VirtualMachineExtension) 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, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtension. +func (v *VirtualMachineExtension) UnmarshalJSON(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 "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 VirtualMachineExtensionHandlerInstanceView. +func (v VirtualMachineExtensionHandlerInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "status", v.Status) + populate(objectMap, "type", v.Type) + populate(objectMap, "typeHandlerVersion", v.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtensionHandlerInstanceView. +func (v *VirtualMachineExtensionHandlerInstanceView) UnmarshalJSON(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 "status": + err = unpopulate(val, "Status", &v.Status) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &v.TypeHandlerVersion) + 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 VirtualMachineExtensionImage. +func (v VirtualMachineExtensionImage) 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, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtensionImage. +func (v *VirtualMachineExtensionImage) UnmarshalJSON(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 "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 VirtualMachineExtensionImageProperties. +func (v VirtualMachineExtensionImageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "computeRole", v.ComputeRole) + populate(objectMap, "handlerSchema", v.HandlerSchema) + populate(objectMap, "operatingSystem", v.OperatingSystem) + populate(objectMap, "supportsMultipleExtensions", v.SupportsMultipleExtensions) + populate(objectMap, "vmScaleSetEnabled", v.VMScaleSetEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtensionImageProperties. +func (v *VirtualMachineExtensionImageProperties) UnmarshalJSON(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 "computeRole": + err = unpopulate(val, "ComputeRole", &v.ComputeRole) + delete(rawMsg, key) + case "handlerSchema": + err = unpopulate(val, "HandlerSchema", &v.HandlerSchema) + delete(rawMsg, key) + case "operatingSystem": + err = unpopulate(val, "OperatingSystem", &v.OperatingSystem) + delete(rawMsg, key) + case "supportsMultipleExtensions": + err = unpopulate(val, "SupportsMultipleExtensions", &v.SupportsMultipleExtensions) + delete(rawMsg, key) + case "vmScaleSetEnabled": + err = unpopulate(val, "VMScaleSetEnabled", &v.VMScaleSetEnabled) + 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 VirtualMachineExtensionInstanceView. +func (v VirtualMachineExtensionInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "statuses", v.Statuses) + populate(objectMap, "substatuses", v.Substatuses) + populate(objectMap, "type", v.Type) + populate(objectMap, "typeHandlerVersion", v.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtensionInstanceView. +func (v *VirtualMachineExtensionInstanceView) UnmarshalJSON(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 "statuses": + err = unpopulate(val, "Statuses", &v.Statuses) + delete(rawMsg, key) + case "substatuses": + err = unpopulate(val, "Substatuses", &v.Substatuses) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &v.TypeHandlerVersion) + 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 VirtualMachineExtensionProperties. +func (v VirtualMachineExtensionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoUpgradeMinorVersion", v.AutoUpgradeMinorVersion) + populate(objectMap, "enableAutomaticUpgrade", v.EnableAutomaticUpgrade) + populate(objectMap, "forceUpdateTag", v.ForceUpdateTag) + populate(objectMap, "instanceView", v.InstanceView) + populateAny(objectMap, "protectedSettings", v.ProtectedSettings) + populate(objectMap, "protectedSettingsFromKeyVault", v.ProtectedSettingsFromKeyVault) + populate(objectMap, "provisionAfterExtensions", v.ProvisionAfterExtensions) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "publisher", v.Publisher) + populateAny(objectMap, "settings", v.Settings) + populate(objectMap, "suppressFailures", v.SuppressFailures) + populate(objectMap, "type", v.Type) + populate(objectMap, "typeHandlerVersion", v.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtensionProperties. +func (v *VirtualMachineExtensionProperties) UnmarshalJSON(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 "autoUpgradeMinorVersion": + err = unpopulate(val, "AutoUpgradeMinorVersion", &v.AutoUpgradeMinorVersion) + delete(rawMsg, key) + case "enableAutomaticUpgrade": + err = unpopulate(val, "EnableAutomaticUpgrade", &v.EnableAutomaticUpgrade) + delete(rawMsg, key) + case "forceUpdateTag": + err = unpopulate(val, "ForceUpdateTag", &v.ForceUpdateTag) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &v.InstanceView) + delete(rawMsg, key) + case "protectedSettings": + err = unpopulate(val, "ProtectedSettings", &v.ProtectedSettings) + delete(rawMsg, key) + case "protectedSettingsFromKeyVault": + err = unpopulate(val, "ProtectedSettingsFromKeyVault", &v.ProtectedSettingsFromKeyVault) + delete(rawMsg, key) + case "provisionAfterExtensions": + err = unpopulate(val, "ProvisionAfterExtensions", &v.ProvisionAfterExtensions) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &v.Publisher) + delete(rawMsg, key) + case "settings": + err = unpopulate(val, "Settings", &v.Settings) + delete(rawMsg, key) + case "suppressFailures": + err = unpopulate(val, "SuppressFailures", &v.SuppressFailures) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &v.TypeHandlerVersion) + 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 VirtualMachineExtensionUpdate. +func (v VirtualMachineExtensionUpdate) 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 VirtualMachineExtensionUpdate. +func (v *VirtualMachineExtensionUpdate) UnmarshalJSON(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 VirtualMachineExtensionUpdateProperties. +func (v VirtualMachineExtensionUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoUpgradeMinorVersion", v.AutoUpgradeMinorVersion) + populate(objectMap, "enableAutomaticUpgrade", v.EnableAutomaticUpgrade) + populate(objectMap, "forceUpdateTag", v.ForceUpdateTag) + populateAny(objectMap, "protectedSettings", v.ProtectedSettings) + populate(objectMap, "protectedSettingsFromKeyVault", v.ProtectedSettingsFromKeyVault) + populate(objectMap, "publisher", v.Publisher) + populateAny(objectMap, "settings", v.Settings) + populate(objectMap, "suppressFailures", v.SuppressFailures) + populate(objectMap, "type", v.Type) + populate(objectMap, "typeHandlerVersion", v.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtensionUpdateProperties. +func (v *VirtualMachineExtensionUpdateProperties) UnmarshalJSON(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 "autoUpgradeMinorVersion": + err = unpopulate(val, "AutoUpgradeMinorVersion", &v.AutoUpgradeMinorVersion) + delete(rawMsg, key) + case "enableAutomaticUpgrade": + err = unpopulate(val, "EnableAutomaticUpgrade", &v.EnableAutomaticUpgrade) + delete(rawMsg, key) + case "forceUpdateTag": + err = unpopulate(val, "ForceUpdateTag", &v.ForceUpdateTag) + delete(rawMsg, key) + case "protectedSettings": + err = unpopulate(val, "ProtectedSettings", &v.ProtectedSettings) + delete(rawMsg, key) + case "protectedSettingsFromKeyVault": + err = unpopulate(val, "ProtectedSettingsFromKeyVault", &v.ProtectedSettingsFromKeyVault) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &v.Publisher) + delete(rawMsg, key) + case "settings": + err = unpopulate(val, "Settings", &v.Settings) + delete(rawMsg, key) + case "suppressFailures": + err = unpopulate(val, "SuppressFailures", &v.SuppressFailures) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &v.TypeHandlerVersion) + 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 VirtualMachineExtensionsListResult. +func (v VirtualMachineExtensionsListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineExtensionsListResult. +func (v *VirtualMachineExtensionsListResult) UnmarshalJSON(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 "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 VirtualMachineHealthStatus. +func (v VirtualMachineHealthStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "status", v.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineHealthStatus. +func (v *VirtualMachineHealthStatus) UnmarshalJSON(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 "status": + err = unpopulate(val, "Status", &v.Status) + 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 VirtualMachineIPTag. +func (v VirtualMachineIPTag) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipTagType", v.IPTagType) + populate(objectMap, "tag", v.Tag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineIPTag. +func (v *VirtualMachineIPTag) UnmarshalJSON(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 "ipTagType": + err = unpopulate(val, "IPTagType", &v.IPTagType) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &v.Tag) + 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 VirtualMachineIdentity. +func (v VirtualMachineIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", v.PrincipalID) + populate(objectMap, "tenantId", v.TenantID) + populate(objectMap, "type", v.Type) + populate(objectMap, "userAssignedIdentities", v.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineIdentity. +func (v *VirtualMachineIdentity) UnmarshalJSON(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 "principalId": + err = unpopulate(val, "PrincipalID", &v.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &v.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &v.UserAssignedIdentities) + 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 VirtualMachineImage. +func (v VirtualMachineImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocation", v.ExtendedLocation) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineImage. +func (v *VirtualMachineImage) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &v.ExtendedLocation) + delete(rawMsg, 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 "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 VirtualMachineImageFeature. +func (v VirtualMachineImageFeature) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineImageFeature. +func (v *VirtualMachineImageFeature) UnmarshalJSON(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 "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 VirtualMachineImageProperties. +func (v VirtualMachineImageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "architecture", v.Architecture) + populate(objectMap, "automaticOSUpgradeProperties", v.AutomaticOSUpgradeProperties) + populate(objectMap, "dataDiskImages", v.DataDiskImages) + populate(objectMap, "disallowed", v.Disallowed) + populate(objectMap, "features", v.Features) + populate(objectMap, "hyperVGeneration", v.HyperVGeneration) + populate(objectMap, "imageDeprecationStatus", v.ImageDeprecationStatus) + populate(objectMap, "osDiskImage", v.OSDiskImage) + populate(objectMap, "plan", v.Plan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineImageProperties. +func (v *VirtualMachineImageProperties) UnmarshalJSON(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 "architecture": + err = unpopulate(val, "Architecture", &v.Architecture) + delete(rawMsg, key) + case "automaticOSUpgradeProperties": + err = unpopulate(val, "AutomaticOSUpgradeProperties", &v.AutomaticOSUpgradeProperties) + delete(rawMsg, key) + case "dataDiskImages": + err = unpopulate(val, "DataDiskImages", &v.DataDiskImages) + delete(rawMsg, key) + case "disallowed": + err = unpopulate(val, "Disallowed", &v.Disallowed) + delete(rawMsg, key) + case "features": + err = unpopulate(val, "Features", &v.Features) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &v.HyperVGeneration) + delete(rawMsg, key) + case "imageDeprecationStatus": + err = unpopulate(val, "ImageDeprecationStatus", &v.ImageDeprecationStatus) + delete(rawMsg, key) + case "osDiskImage": + err = unpopulate(val, "OSDiskImage", &v.OSDiskImage) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &v.Plan) + 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 VirtualMachineImageResource. +func (v VirtualMachineImageResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocation", v.ExtendedLocation) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "tags", v.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineImageResource. +func (v *VirtualMachineImageResource) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &v.ExtendedLocation) + delete(rawMsg, 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 "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 VirtualMachineInstallPatchesParameters. +func (v VirtualMachineInstallPatchesParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "linuxParameters", v.LinuxParameters) + populate(objectMap, "maximumDuration", v.MaximumDuration) + populate(objectMap, "rebootSetting", v.RebootSetting) + populate(objectMap, "windowsParameters", v.WindowsParameters) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineInstallPatchesParameters. +func (v *VirtualMachineInstallPatchesParameters) UnmarshalJSON(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 "linuxParameters": + err = unpopulate(val, "LinuxParameters", &v.LinuxParameters) + delete(rawMsg, key) + case "maximumDuration": + err = unpopulate(val, "MaximumDuration", &v.MaximumDuration) + delete(rawMsg, key) + case "rebootSetting": + err = unpopulate(val, "RebootSetting", &v.RebootSetting) + delete(rawMsg, key) + case "windowsParameters": + err = unpopulate(val, "WindowsParameters", &v.WindowsParameters) + 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 VirtualMachineInstallPatchesResult. +func (v VirtualMachineInstallPatchesResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", v.Error) + populate(objectMap, "excludedPatchCount", v.ExcludedPatchCount) + populate(objectMap, "failedPatchCount", v.FailedPatchCount) + populate(objectMap, "installationActivityId", v.InstallationActivityID) + populate(objectMap, "installedPatchCount", v.InstalledPatchCount) + populate(objectMap, "maintenanceWindowExceeded", v.MaintenanceWindowExceeded) + populate(objectMap, "notSelectedPatchCount", v.NotSelectedPatchCount) + populate(objectMap, "patches", v.Patches) + populate(objectMap, "pendingPatchCount", v.PendingPatchCount) + populate(objectMap, "rebootStatus", v.RebootStatus) + populateDateTimeRFC3339(objectMap, "startDateTime", v.StartDateTime) + populate(objectMap, "status", v.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineInstallPatchesResult. +func (v *VirtualMachineInstallPatchesResult) UnmarshalJSON(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 "error": + err = unpopulate(val, "Error", &v.Error) + delete(rawMsg, key) + case "excludedPatchCount": + err = unpopulate(val, "ExcludedPatchCount", &v.ExcludedPatchCount) + delete(rawMsg, key) + case "failedPatchCount": + err = unpopulate(val, "FailedPatchCount", &v.FailedPatchCount) + delete(rawMsg, key) + case "installationActivityId": + err = unpopulate(val, "InstallationActivityID", &v.InstallationActivityID) + delete(rawMsg, key) + case "installedPatchCount": + err = unpopulate(val, "InstalledPatchCount", &v.InstalledPatchCount) + delete(rawMsg, key) + case "maintenanceWindowExceeded": + err = unpopulate(val, "MaintenanceWindowExceeded", &v.MaintenanceWindowExceeded) + delete(rawMsg, key) + case "notSelectedPatchCount": + err = unpopulate(val, "NotSelectedPatchCount", &v.NotSelectedPatchCount) + delete(rawMsg, key) + case "patches": + err = unpopulate(val, "Patches", &v.Patches) + delete(rawMsg, key) + case "pendingPatchCount": + err = unpopulate(val, "PendingPatchCount", &v.PendingPatchCount) + delete(rawMsg, key) + case "rebootStatus": + err = unpopulate(val, "RebootStatus", &v.RebootStatus) + delete(rawMsg, key) + case "startDateTime": + err = unpopulateDateTimeRFC3339(val, "StartDateTime", &v.StartDateTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &v.Status) + 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 VirtualMachineInstanceView. +func (v VirtualMachineInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assignedHost", v.AssignedHost) + populate(objectMap, "bootDiagnostics", v.BootDiagnostics) + populate(objectMap, "computerName", v.ComputerName) + populate(objectMap, "disks", v.Disks) + populate(objectMap, "extensions", v.Extensions) + populate(objectMap, "hyperVGeneration", v.HyperVGeneration) + populate(objectMap, "isVMInStandbyPool", v.IsVMInStandbyPool) + populate(objectMap, "maintenanceRedeployStatus", v.MaintenanceRedeployStatus) + populate(objectMap, "osName", v.OSName) + populate(objectMap, "osVersion", v.OSVersion) + populate(objectMap, "patchStatus", v.PatchStatus) + populate(objectMap, "platformFaultDomain", v.PlatformFaultDomain) + populate(objectMap, "platformUpdateDomain", v.PlatformUpdateDomain) + populate(objectMap, "rdpThumbPrint", v.RdpThumbPrint) + populate(objectMap, "statuses", v.Statuses) + populate(objectMap, "vmAgent", v.VMAgent) + populate(objectMap, "vmHealth", v.VMHealth) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineInstanceView. +func (v *VirtualMachineInstanceView) UnmarshalJSON(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 "assignedHost": + err = unpopulate(val, "AssignedHost", &v.AssignedHost) + delete(rawMsg, key) + case "bootDiagnostics": + err = unpopulate(val, "BootDiagnostics", &v.BootDiagnostics) + delete(rawMsg, key) + case "computerName": + err = unpopulate(val, "ComputerName", &v.ComputerName) + delete(rawMsg, key) + case "disks": + err = unpopulate(val, "Disks", &v.Disks) + delete(rawMsg, key) + case "extensions": + err = unpopulate(val, "Extensions", &v.Extensions) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &v.HyperVGeneration) + delete(rawMsg, key) + case "isVMInStandbyPool": + err = unpopulate(val, "IsVMInStandbyPool", &v.IsVMInStandbyPool) + delete(rawMsg, key) + case "maintenanceRedeployStatus": + err = unpopulate(val, "MaintenanceRedeployStatus", &v.MaintenanceRedeployStatus) + delete(rawMsg, key) + case "osName": + err = unpopulate(val, "OSName", &v.OSName) + delete(rawMsg, key) + case "osVersion": + err = unpopulate(val, "OSVersion", &v.OSVersion) + delete(rawMsg, key) + case "patchStatus": + err = unpopulate(val, "PatchStatus", &v.PatchStatus) + delete(rawMsg, key) + case "platformFaultDomain": + err = unpopulate(val, "PlatformFaultDomain", &v.PlatformFaultDomain) + delete(rawMsg, key) + case "platformUpdateDomain": + err = unpopulate(val, "PlatformUpdateDomain", &v.PlatformUpdateDomain) + delete(rawMsg, key) + case "rdpThumbPrint": + err = unpopulate(val, "RdpThumbPrint", &v.RdpThumbPrint) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &v.Statuses) + delete(rawMsg, key) + case "vmAgent": + err = unpopulate(val, "VMAgent", &v.VMAgent) + delete(rawMsg, key) + case "vmHealth": + err = unpopulate(val, "VMHealth", &v.VMHealth) + 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 VirtualMachineListResult. +func (v VirtualMachineListResult) 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 VirtualMachineListResult. +func (v *VirtualMachineListResult) UnmarshalJSON(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 VirtualMachineNetworkInterfaceConfiguration. +func (v VirtualMachineNetworkInterfaceConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceConfiguration. +func (v *VirtualMachineNetworkInterfaceConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualMachineNetworkInterfaceConfigurationProperties. +func (v VirtualMachineNetworkInterfaceConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "auxiliaryMode", v.AuxiliaryMode) + populate(objectMap, "auxiliarySku", v.AuxiliarySKU) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "disableTcpStateTracking", v.DisableTCPStateTracking) + populate(objectMap, "dscpConfiguration", v.DscpConfiguration) + populate(objectMap, "enableAcceleratedNetworking", v.EnableAcceleratedNetworking) + populate(objectMap, "enableFpga", v.EnableFpga) + populate(objectMap, "enableIPForwarding", v.EnableIPForwarding) + populate(objectMap, "ipConfigurations", v.IPConfigurations) + populate(objectMap, "networkSecurityGroup", v.NetworkSecurityGroup) + populate(objectMap, "primary", v.Primary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceConfigurationProperties. +func (v *VirtualMachineNetworkInterfaceConfigurationProperties) UnmarshalJSON(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 "auxiliaryMode": + err = unpopulate(val, "AuxiliaryMode", &v.AuxiliaryMode) + delete(rawMsg, key) + case "auxiliarySku": + err = unpopulate(val, "AuxiliarySKU", &v.AuxiliarySKU) + delete(rawMsg, key) + case "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "disableTcpStateTracking": + err = unpopulate(val, "DisableTCPStateTracking", &v.DisableTCPStateTracking) + delete(rawMsg, key) + case "dscpConfiguration": + err = unpopulate(val, "DscpConfiguration", &v.DscpConfiguration) + delete(rawMsg, key) + case "enableAcceleratedNetworking": + err = unpopulate(val, "EnableAcceleratedNetworking", &v.EnableAcceleratedNetworking) + delete(rawMsg, key) + case "enableFpga": + err = unpopulate(val, "EnableFpga", &v.EnableFpga) + delete(rawMsg, key) + case "enableIPForwarding": + err = unpopulate(val, "EnableIPForwarding", &v.EnableIPForwarding) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &v.IPConfigurations) + delete(rawMsg, key) + case "networkSecurityGroup": + err = unpopulate(val, "NetworkSecurityGroup", &v.NetworkSecurityGroup) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + 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 VirtualMachineNetworkInterfaceDNSSettingsConfiguration. +func (v VirtualMachineNetworkInterfaceDNSSettingsConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsServers", v.DNSServers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceDNSSettingsConfiguration. +func (v *VirtualMachineNetworkInterfaceDNSSettingsConfiguration) UnmarshalJSON(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 "dnsServers": + err = unpopulate(val, "DNSServers", &v.DNSServers) + 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 VirtualMachineNetworkInterfaceIPConfiguration. +func (v VirtualMachineNetworkInterfaceIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceIPConfiguration. +func (v *VirtualMachineNetworkInterfaceIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualMachineNetworkInterfaceIPConfigurationProperties. +func (v VirtualMachineNetworkInterfaceIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationGatewayBackendAddressPools", v.ApplicationGatewayBackendAddressPools) + populate(objectMap, "applicationSecurityGroups", v.ApplicationSecurityGroups) + populate(objectMap, "loadBalancerBackendAddressPools", v.LoadBalancerBackendAddressPools) + populate(objectMap, "primary", v.Primary) + populate(objectMap, "privateIPAddressVersion", v.PrivateIPAddressVersion) + populate(objectMap, "publicIPAddressConfiguration", v.PublicIPAddressConfiguration) + populate(objectMap, "subnet", v.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceIPConfigurationProperties. +func (v *VirtualMachineNetworkInterfaceIPConfigurationProperties) UnmarshalJSON(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 "applicationGatewayBackendAddressPools": + err = unpopulate(val, "ApplicationGatewayBackendAddressPools", &v.ApplicationGatewayBackendAddressPools) + delete(rawMsg, key) + case "applicationSecurityGroups": + err = unpopulate(val, "ApplicationSecurityGroups", &v.ApplicationSecurityGroups) + delete(rawMsg, key) + case "loadBalancerBackendAddressPools": + err = unpopulate(val, "LoadBalancerBackendAddressPools", &v.LoadBalancerBackendAddressPools) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + delete(rawMsg, key) + case "privateIPAddressVersion": + err = unpopulate(val, "PrivateIPAddressVersion", &v.PrivateIPAddressVersion) + delete(rawMsg, key) + case "publicIPAddressConfiguration": + err = unpopulate(val, "PublicIPAddressConfiguration", &v.PublicIPAddressConfiguration) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &v.Subnet) + 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 VirtualMachinePatchStatus. +func (v VirtualMachinePatchStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availablePatchSummary", v.AvailablePatchSummary) + populate(objectMap, "configurationStatuses", v.ConfigurationStatuses) + populate(objectMap, "lastPatchInstallationSummary", v.LastPatchInstallationSummary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachinePatchStatus. +func (v *VirtualMachinePatchStatus) UnmarshalJSON(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 "availablePatchSummary": + err = unpopulate(val, "AvailablePatchSummary", &v.AvailablePatchSummary) + delete(rawMsg, key) + case "configurationStatuses": + err = unpopulate(val, "ConfigurationStatuses", &v.ConfigurationStatuses) + delete(rawMsg, key) + case "lastPatchInstallationSummary": + err = unpopulate(val, "LastPatchInstallationSummary", &v.LastPatchInstallationSummary) + 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 VirtualMachineProperties. +func (v VirtualMachineProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalCapabilities", v.AdditionalCapabilities) + populate(objectMap, "applicationProfile", v.ApplicationProfile) + populate(objectMap, "availabilitySet", v.AvailabilitySet) + populate(objectMap, "billingProfile", v.BillingProfile) + populate(objectMap, "capacityReservation", v.CapacityReservation) + populate(objectMap, "diagnosticsProfile", v.DiagnosticsProfile) + populate(objectMap, "evictionPolicy", v.EvictionPolicy) + populate(objectMap, "extensionsTimeBudget", v.ExtensionsTimeBudget) + populate(objectMap, "hardwareProfile", v.HardwareProfile) + populate(objectMap, "host", v.Host) + populate(objectMap, "hostGroup", v.HostGroup) + populate(objectMap, "instanceView", v.InstanceView) + populate(objectMap, "licenseType", v.LicenseType) + populate(objectMap, "networkProfile", v.NetworkProfile) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "platformFaultDomain", v.PlatformFaultDomain) + populate(objectMap, "priority", v.Priority) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "proximityPlacementGroup", v.ProximityPlacementGroup) + populate(objectMap, "scheduledEventsProfile", v.ScheduledEventsProfile) + populate(objectMap, "securityProfile", v.SecurityProfile) + populate(objectMap, "storageProfile", v.StorageProfile) + populateDateTimeRFC3339(objectMap, "timeCreated", v.TimeCreated) + populate(objectMap, "userData", v.UserData) + populate(objectMap, "vmId", v.VMID) + populate(objectMap, "virtualMachineScaleSet", v.VirtualMachineScaleSet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineProperties. +func (v *VirtualMachineProperties) UnmarshalJSON(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 "additionalCapabilities": + err = unpopulate(val, "AdditionalCapabilities", &v.AdditionalCapabilities) + delete(rawMsg, key) + case "applicationProfile": + err = unpopulate(val, "ApplicationProfile", &v.ApplicationProfile) + delete(rawMsg, key) + case "availabilitySet": + err = unpopulate(val, "AvailabilitySet", &v.AvailabilitySet) + delete(rawMsg, key) + case "billingProfile": + err = unpopulate(val, "BillingProfile", &v.BillingProfile) + delete(rawMsg, key) + case "capacityReservation": + err = unpopulate(val, "CapacityReservation", &v.CapacityReservation) + delete(rawMsg, key) + case "diagnosticsProfile": + err = unpopulate(val, "DiagnosticsProfile", &v.DiagnosticsProfile) + delete(rawMsg, key) + case "evictionPolicy": + err = unpopulate(val, "EvictionPolicy", &v.EvictionPolicy) + delete(rawMsg, key) + case "extensionsTimeBudget": + err = unpopulate(val, "ExtensionsTimeBudget", &v.ExtensionsTimeBudget) + delete(rawMsg, key) + case "hardwareProfile": + err = unpopulate(val, "HardwareProfile", &v.HardwareProfile) + delete(rawMsg, key) + case "host": + err = unpopulate(val, "Host", &v.Host) + delete(rawMsg, key) + case "hostGroup": + err = unpopulate(val, "HostGroup", &v.HostGroup) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &v.InstanceView) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &v.LicenseType) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &v.NetworkProfile) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "platformFaultDomain": + err = unpopulate(val, "PlatformFaultDomain", &v.PlatformFaultDomain) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &v.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "proximityPlacementGroup": + err = unpopulate(val, "ProximityPlacementGroup", &v.ProximityPlacementGroup) + delete(rawMsg, key) + case "scheduledEventsProfile": + err = unpopulate(val, "ScheduledEventsProfile", &v.ScheduledEventsProfile) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &v.SecurityProfile) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &v.StorageProfile) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &v.TimeCreated) + delete(rawMsg, key) + case "userData": + err = unpopulate(val, "UserData", &v.UserData) + delete(rawMsg, key) + case "vmId": + err = unpopulate(val, "VMID", &v.VMID) + delete(rawMsg, key) + case "virtualMachineScaleSet": + err = unpopulate(val, "VirtualMachineScaleSet", &v.VirtualMachineScaleSet) + 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 VirtualMachinePublicIPAddressConfiguration. +func (v VirtualMachinePublicIPAddressConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "sku", v.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachinePublicIPAddressConfiguration. +func (v *VirtualMachinePublicIPAddressConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + 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 VirtualMachinePublicIPAddressConfigurationProperties. +func (v VirtualMachinePublicIPAddressConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "ipTags", v.IPTags) + populate(objectMap, "idleTimeoutInMinutes", v.IdleTimeoutInMinutes) + populate(objectMap, "publicIPAddressVersion", v.PublicIPAddressVersion) + populate(objectMap, "publicIPAllocationMethod", v.PublicIPAllocationMethod) + populate(objectMap, "publicIPPrefix", v.PublicIPPrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachinePublicIPAddressConfigurationProperties. +func (v *VirtualMachinePublicIPAddressConfigurationProperties) UnmarshalJSON(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 "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "ipTags": + err = unpopulate(val, "IPTags", &v.IPTags) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &v.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "publicIPAddressVersion": + err = unpopulate(val, "PublicIPAddressVersion", &v.PublicIPAddressVersion) + delete(rawMsg, key) + case "publicIPAllocationMethod": + err = unpopulate(val, "PublicIPAllocationMethod", &v.PublicIPAllocationMethod) + delete(rawMsg, key) + case "publicIPPrefix": + err = unpopulate(val, "PublicIPPrefix", &v.PublicIPPrefix) + 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 VirtualMachinePublicIPAddressDNSSettingsConfiguration. +func (v VirtualMachinePublicIPAddressDNSSettingsConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domainNameLabel", v.DomainNameLabel) + populate(objectMap, "domainNameLabelScope", v.DomainNameLabelScope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachinePublicIPAddressDNSSettingsConfiguration. +func (v *VirtualMachinePublicIPAddressDNSSettingsConfiguration) UnmarshalJSON(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 "domainNameLabel": + err = unpopulate(val, "DomainNameLabel", &v.DomainNameLabel) + delete(rawMsg, key) + case "domainNameLabelScope": + err = unpopulate(val, "DomainNameLabelScope", &v.DomainNameLabelScope) + 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 VirtualMachineReimageParameters. +func (v VirtualMachineReimageParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exactVersion", v.ExactVersion) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "tempDisk", v.TempDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineReimageParameters. +func (v *VirtualMachineReimageParameters) UnmarshalJSON(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 "exactVersion": + err = unpopulate(val, "ExactVersion", &v.ExactVersion) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "tempDisk": + err = unpopulate(val, "TempDisk", &v.TempDisk) + 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 VirtualMachineRunCommand. +func (v VirtualMachineRunCommand) 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, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineRunCommand. +func (v *VirtualMachineRunCommand) UnmarshalJSON(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 "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 VirtualMachineRunCommandInstanceView. +func (v VirtualMachineRunCommandInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endTime", v.EndTime) + populate(objectMap, "error", v.Error) + populate(objectMap, "executionMessage", v.ExecutionMessage) + populate(objectMap, "executionState", v.ExecutionState) + populate(objectMap, "exitCode", v.ExitCode) + populate(objectMap, "output", v.Output) + populateDateTimeRFC3339(objectMap, "startTime", v.StartTime) + populate(objectMap, "statuses", v.Statuses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineRunCommandInstanceView. +func (v *VirtualMachineRunCommandInstanceView) UnmarshalJSON(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 "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &v.EndTime) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &v.Error) + delete(rawMsg, key) + case "executionMessage": + err = unpopulate(val, "ExecutionMessage", &v.ExecutionMessage) + delete(rawMsg, key) + case "executionState": + err = unpopulate(val, "ExecutionState", &v.ExecutionState) + delete(rawMsg, key) + case "exitCode": + err = unpopulate(val, "ExitCode", &v.ExitCode) + delete(rawMsg, key) + case "output": + err = unpopulate(val, "Output", &v.Output) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &v.StartTime) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &v.Statuses) + 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 VirtualMachineRunCommandProperties. +func (v VirtualMachineRunCommandProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asyncExecution", v.AsyncExecution) + populate(objectMap, "errorBlobManagedIdentity", v.ErrorBlobManagedIdentity) + populate(objectMap, "errorBlobUri", v.ErrorBlobURI) + populate(objectMap, "instanceView", v.InstanceView) + populate(objectMap, "outputBlobManagedIdentity", v.OutputBlobManagedIdentity) + populate(objectMap, "outputBlobUri", v.OutputBlobURI) + populate(objectMap, "parameters", v.Parameters) + populate(objectMap, "protectedParameters", v.ProtectedParameters) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "runAsPassword", v.RunAsPassword) + populate(objectMap, "runAsUser", v.RunAsUser) + populate(objectMap, "source", v.Source) + populate(objectMap, "timeoutInSeconds", v.TimeoutInSeconds) + populate(objectMap, "treatFailureAsDeploymentFailure", v.TreatFailureAsDeploymentFailure) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineRunCommandProperties. +func (v *VirtualMachineRunCommandProperties) UnmarshalJSON(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 "asyncExecution": + err = unpopulate(val, "AsyncExecution", &v.AsyncExecution) + delete(rawMsg, key) + case "errorBlobManagedIdentity": + err = unpopulate(val, "ErrorBlobManagedIdentity", &v.ErrorBlobManagedIdentity) + delete(rawMsg, key) + case "errorBlobUri": + err = unpopulate(val, "ErrorBlobURI", &v.ErrorBlobURI) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &v.InstanceView) + delete(rawMsg, key) + case "outputBlobManagedIdentity": + err = unpopulate(val, "OutputBlobManagedIdentity", &v.OutputBlobManagedIdentity) + delete(rawMsg, key) + case "outputBlobUri": + err = unpopulate(val, "OutputBlobURI", &v.OutputBlobURI) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, "Parameters", &v.Parameters) + delete(rawMsg, key) + case "protectedParameters": + err = unpopulate(val, "ProtectedParameters", &v.ProtectedParameters) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "runAsPassword": + err = unpopulate(val, "RunAsPassword", &v.RunAsPassword) + delete(rawMsg, key) + case "runAsUser": + err = unpopulate(val, "RunAsUser", &v.RunAsUser) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &v.Source) + delete(rawMsg, key) + case "timeoutInSeconds": + err = unpopulate(val, "TimeoutInSeconds", &v.TimeoutInSeconds) + delete(rawMsg, key) + case "treatFailureAsDeploymentFailure": + err = unpopulate(val, "TreatFailureAsDeploymentFailure", &v.TreatFailureAsDeploymentFailure) + 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 VirtualMachineRunCommandScriptSource. +func (v VirtualMachineRunCommandScriptSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commandId", v.CommandID) + populate(objectMap, "script", v.Script) + populate(objectMap, "scriptUri", v.ScriptURI) + populate(objectMap, "scriptUriManagedIdentity", v.ScriptURIManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineRunCommandScriptSource. +func (v *VirtualMachineRunCommandScriptSource) UnmarshalJSON(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 "commandId": + err = unpopulate(val, "CommandID", &v.CommandID) + delete(rawMsg, key) + case "script": + err = unpopulate(val, "Script", &v.Script) + delete(rawMsg, key) + case "scriptUri": + err = unpopulate(val, "ScriptURI", &v.ScriptURI) + delete(rawMsg, key) + case "scriptUriManagedIdentity": + err = unpopulate(val, "ScriptURIManagedIdentity", &v.ScriptURIManagedIdentity) + 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 VirtualMachineRunCommandUpdate. +func (v VirtualMachineRunCommandUpdate) 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 VirtualMachineRunCommandUpdate. +func (v *VirtualMachineRunCommandUpdate) UnmarshalJSON(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 VirtualMachineRunCommandsListResult. +func (v VirtualMachineRunCommandsListResult) 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 VirtualMachineRunCommandsListResult. +func (v *VirtualMachineRunCommandsListResult) UnmarshalJSON(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 VirtualMachineScaleSet. +func (v VirtualMachineScaleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "extendedLocation", v.ExtendedLocation) + populate(objectMap, "id", v.ID) + populate(objectMap, "identity", v.Identity) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "plan", v.Plan) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + populate(objectMap, "zones", v.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSet. +func (v *VirtualMachineScaleSet) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &v.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &v.Identity) + 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 "plan": + err = unpopulate(val, "Plan", &v.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + 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) + case "zones": + err = unpopulate(val, "Zones", &v.Zones) + 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 VirtualMachineScaleSetDataDisk. +func (v VirtualMachineScaleSetDataDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", v.Caching) + populate(objectMap, "createOption", v.CreateOption) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "diskIOPSReadWrite", v.DiskIOPSReadWrite) + populate(objectMap, "diskMBpsReadWrite", v.DiskMBpsReadWrite) + populate(objectMap, "diskSizeGB", v.DiskSizeGB) + populate(objectMap, "lun", v.Lun) + populate(objectMap, "managedDisk", v.ManagedDisk) + populate(objectMap, "name", v.Name) + populate(objectMap, "writeAcceleratorEnabled", v.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetDataDisk. +func (v *VirtualMachineScaleSetDataDisk) UnmarshalJSON(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 "caching": + err = unpopulate(val, "Caching", &v.Caching) + delete(rawMsg, key) + case "createOption": + err = unpopulate(val, "CreateOption", &v.CreateOption) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "diskIOPSReadWrite": + err = unpopulate(val, "DiskIOPSReadWrite", &v.DiskIOPSReadWrite) + delete(rawMsg, key) + case "diskMBpsReadWrite": + err = unpopulate(val, "DiskMBpsReadWrite", &v.DiskMBpsReadWrite) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &v.DiskSizeGB) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &v.Lun) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &v.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &v.WriteAcceleratorEnabled) + 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 VirtualMachineScaleSetExtension. +func (v VirtualMachineScaleSetExtension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + 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 VirtualMachineScaleSetExtension. +func (v *VirtualMachineScaleSetExtension) UnmarshalJSON(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 "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 VirtualMachineScaleSetExtensionListResult. +func (v VirtualMachineScaleSetExtensionListResult) 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 VirtualMachineScaleSetExtensionListResult. +func (v *VirtualMachineScaleSetExtensionListResult) UnmarshalJSON(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 VirtualMachineScaleSetExtensionProfile. +func (v VirtualMachineScaleSetExtensionProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extensions", v.Extensions) + populate(objectMap, "extensionsTimeBudget", v.ExtensionsTimeBudget) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetExtensionProfile. +func (v *VirtualMachineScaleSetExtensionProfile) UnmarshalJSON(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 "extensions": + err = unpopulate(val, "Extensions", &v.Extensions) + delete(rawMsg, key) + case "extensionsTimeBudget": + err = unpopulate(val, "ExtensionsTimeBudget", &v.ExtensionsTimeBudget) + 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 VirtualMachineScaleSetExtensionProperties. +func (v VirtualMachineScaleSetExtensionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoUpgradeMinorVersion", v.AutoUpgradeMinorVersion) + populate(objectMap, "enableAutomaticUpgrade", v.EnableAutomaticUpgrade) + populate(objectMap, "forceUpdateTag", v.ForceUpdateTag) + populateAny(objectMap, "protectedSettings", v.ProtectedSettings) + populate(objectMap, "protectedSettingsFromKeyVault", v.ProtectedSettingsFromKeyVault) + populate(objectMap, "provisionAfterExtensions", v.ProvisionAfterExtensions) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "publisher", v.Publisher) + populateAny(objectMap, "settings", v.Settings) + populate(objectMap, "suppressFailures", v.SuppressFailures) + populate(objectMap, "type", v.Type) + populate(objectMap, "typeHandlerVersion", v.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetExtensionProperties. +func (v *VirtualMachineScaleSetExtensionProperties) UnmarshalJSON(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 "autoUpgradeMinorVersion": + err = unpopulate(val, "AutoUpgradeMinorVersion", &v.AutoUpgradeMinorVersion) + delete(rawMsg, key) + case "enableAutomaticUpgrade": + err = unpopulate(val, "EnableAutomaticUpgrade", &v.EnableAutomaticUpgrade) + delete(rawMsg, key) + case "forceUpdateTag": + err = unpopulate(val, "ForceUpdateTag", &v.ForceUpdateTag) + delete(rawMsg, key) + case "protectedSettings": + err = unpopulate(val, "ProtectedSettings", &v.ProtectedSettings) + delete(rawMsg, key) + case "protectedSettingsFromKeyVault": + err = unpopulate(val, "ProtectedSettingsFromKeyVault", &v.ProtectedSettingsFromKeyVault) + delete(rawMsg, key) + case "provisionAfterExtensions": + err = unpopulate(val, "ProvisionAfterExtensions", &v.ProvisionAfterExtensions) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &v.Publisher) + delete(rawMsg, key) + case "settings": + err = unpopulate(val, "Settings", &v.Settings) + delete(rawMsg, key) + case "suppressFailures": + err = unpopulate(val, "SuppressFailures", &v.SuppressFailures) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &v.TypeHandlerVersion) + 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 VirtualMachineScaleSetExtensionUpdate. +func (v VirtualMachineScaleSetExtensionUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + 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 VirtualMachineScaleSetExtensionUpdate. +func (v *VirtualMachineScaleSetExtensionUpdate) UnmarshalJSON(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 "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 VirtualMachineScaleSetHardwareProfile. +func (v VirtualMachineScaleSetHardwareProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vmSizeProperties", v.VMSizeProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetHardwareProfile. +func (v *VirtualMachineScaleSetHardwareProfile) UnmarshalJSON(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 "vmSizeProperties": + err = unpopulate(val, "VMSizeProperties", &v.VMSizeProperties) + 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 VirtualMachineScaleSetIPConfiguration. +func (v VirtualMachineScaleSetIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetIPConfiguration. +func (v *VirtualMachineScaleSetIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualMachineScaleSetIPConfigurationProperties. +func (v VirtualMachineScaleSetIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationGatewayBackendAddressPools", v.ApplicationGatewayBackendAddressPools) + populate(objectMap, "applicationSecurityGroups", v.ApplicationSecurityGroups) + populate(objectMap, "loadBalancerBackendAddressPools", v.LoadBalancerBackendAddressPools) + populate(objectMap, "loadBalancerInboundNatPools", v.LoadBalancerInboundNatPools) + populate(objectMap, "primary", v.Primary) + populate(objectMap, "privateIPAddressVersion", v.PrivateIPAddressVersion) + populate(objectMap, "publicIPAddressConfiguration", v.PublicIPAddressConfiguration) + populate(objectMap, "subnet", v.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetIPConfigurationProperties. +func (v *VirtualMachineScaleSetIPConfigurationProperties) UnmarshalJSON(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 "applicationGatewayBackendAddressPools": + err = unpopulate(val, "ApplicationGatewayBackendAddressPools", &v.ApplicationGatewayBackendAddressPools) + delete(rawMsg, key) + case "applicationSecurityGroups": + err = unpopulate(val, "ApplicationSecurityGroups", &v.ApplicationSecurityGroups) + delete(rawMsg, key) + case "loadBalancerBackendAddressPools": + err = unpopulate(val, "LoadBalancerBackendAddressPools", &v.LoadBalancerBackendAddressPools) + delete(rawMsg, key) + case "loadBalancerInboundNatPools": + err = unpopulate(val, "LoadBalancerInboundNatPools", &v.LoadBalancerInboundNatPools) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + delete(rawMsg, key) + case "privateIPAddressVersion": + err = unpopulate(val, "PrivateIPAddressVersion", &v.PrivateIPAddressVersion) + delete(rawMsg, key) + case "publicIPAddressConfiguration": + err = unpopulate(val, "PublicIPAddressConfiguration", &v.PublicIPAddressConfiguration) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &v.Subnet) + 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 VirtualMachineScaleSetIPTag. +func (v VirtualMachineScaleSetIPTag) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipTagType", v.IPTagType) + populate(objectMap, "tag", v.Tag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetIPTag. +func (v *VirtualMachineScaleSetIPTag) UnmarshalJSON(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 "ipTagType": + err = unpopulate(val, "IPTagType", &v.IPTagType) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &v.Tag) + 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 VirtualMachineScaleSetIdentity. +func (v VirtualMachineScaleSetIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", v.PrincipalID) + populate(objectMap, "tenantId", v.TenantID) + populate(objectMap, "type", v.Type) + populate(objectMap, "userAssignedIdentities", v.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetIdentity. +func (v *VirtualMachineScaleSetIdentity) UnmarshalJSON(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 "principalId": + err = unpopulate(val, "PrincipalID", &v.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &v.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &v.UserAssignedIdentities) + 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 VirtualMachineScaleSetInstanceView. +func (v VirtualMachineScaleSetInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extensions", v.Extensions) + populate(objectMap, "orchestrationServices", v.OrchestrationServices) + populate(objectMap, "statuses", v.Statuses) + populate(objectMap, "virtualMachine", v.VirtualMachine) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetInstanceView. +func (v *VirtualMachineScaleSetInstanceView) UnmarshalJSON(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 "extensions": + err = unpopulate(val, "Extensions", &v.Extensions) + delete(rawMsg, key) + case "orchestrationServices": + err = unpopulate(val, "OrchestrationServices", &v.OrchestrationServices) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &v.Statuses) + delete(rawMsg, key) + case "virtualMachine": + err = unpopulate(val, "VirtualMachine", &v.VirtualMachine) + 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 VirtualMachineScaleSetInstanceViewStatusesSummary. +func (v VirtualMachineScaleSetInstanceViewStatusesSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "statusesSummary", v.StatusesSummary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetInstanceViewStatusesSummary. +func (v *VirtualMachineScaleSetInstanceViewStatusesSummary) UnmarshalJSON(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 "statusesSummary": + err = unpopulate(val, "StatusesSummary", &v.StatusesSummary) + 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 VirtualMachineScaleSetListOSUpgradeHistory. +func (v VirtualMachineScaleSetListOSUpgradeHistory) 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 VirtualMachineScaleSetListOSUpgradeHistory. +func (v *VirtualMachineScaleSetListOSUpgradeHistory) UnmarshalJSON(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 VirtualMachineScaleSetListResult. +func (v VirtualMachineScaleSetListResult) 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 VirtualMachineScaleSetListResult. +func (v *VirtualMachineScaleSetListResult) UnmarshalJSON(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 VirtualMachineScaleSetListSKUsResult. +func (v VirtualMachineScaleSetListSKUsResult) 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 VirtualMachineScaleSetListSKUsResult. +func (v *VirtualMachineScaleSetListSKUsResult) UnmarshalJSON(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 VirtualMachineScaleSetListWithLinkResult. +func (v VirtualMachineScaleSetListWithLinkResult) 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 VirtualMachineScaleSetListWithLinkResult. +func (v *VirtualMachineScaleSetListWithLinkResult) UnmarshalJSON(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 VirtualMachineScaleSetManagedDiskParameters. +func (v VirtualMachineScaleSetManagedDiskParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSet", v.DiskEncryptionSet) + populate(objectMap, "securityProfile", v.SecurityProfile) + populate(objectMap, "storageAccountType", v.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetManagedDiskParameters. +func (v *VirtualMachineScaleSetManagedDiskParameters) UnmarshalJSON(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 "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &v.DiskEncryptionSet) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &v.SecurityProfile) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &v.StorageAccountType) + 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 VirtualMachineScaleSetNetworkConfiguration. +func (v VirtualMachineScaleSetNetworkConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetNetworkConfiguration. +func (v *VirtualMachineScaleSetNetworkConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualMachineScaleSetNetworkConfigurationDNSSettings. +func (v VirtualMachineScaleSetNetworkConfigurationDNSSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsServers", v.DNSServers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetNetworkConfigurationDNSSettings. +func (v *VirtualMachineScaleSetNetworkConfigurationDNSSettings) UnmarshalJSON(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 "dnsServers": + err = unpopulate(val, "DNSServers", &v.DNSServers) + 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 VirtualMachineScaleSetNetworkConfigurationProperties. +func (v VirtualMachineScaleSetNetworkConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "auxiliaryMode", v.AuxiliaryMode) + populate(objectMap, "auxiliarySku", v.AuxiliarySKU) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "disableTcpStateTracking", v.DisableTCPStateTracking) + populate(objectMap, "enableAcceleratedNetworking", v.EnableAcceleratedNetworking) + populate(objectMap, "enableFpga", v.EnableFpga) + populate(objectMap, "enableIPForwarding", v.EnableIPForwarding) + populate(objectMap, "ipConfigurations", v.IPConfigurations) + populate(objectMap, "networkSecurityGroup", v.NetworkSecurityGroup) + populate(objectMap, "primary", v.Primary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetNetworkConfigurationProperties. +func (v *VirtualMachineScaleSetNetworkConfigurationProperties) UnmarshalJSON(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 "auxiliaryMode": + err = unpopulate(val, "AuxiliaryMode", &v.AuxiliaryMode) + delete(rawMsg, key) + case "auxiliarySku": + err = unpopulate(val, "AuxiliarySKU", &v.AuxiliarySKU) + delete(rawMsg, key) + case "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "disableTcpStateTracking": + err = unpopulate(val, "DisableTCPStateTracking", &v.DisableTCPStateTracking) + delete(rawMsg, key) + case "enableAcceleratedNetworking": + err = unpopulate(val, "EnableAcceleratedNetworking", &v.EnableAcceleratedNetworking) + delete(rawMsg, key) + case "enableFpga": + err = unpopulate(val, "EnableFpga", &v.EnableFpga) + delete(rawMsg, key) + case "enableIPForwarding": + err = unpopulate(val, "EnableIPForwarding", &v.EnableIPForwarding) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &v.IPConfigurations) + delete(rawMsg, key) + case "networkSecurityGroup": + err = unpopulate(val, "NetworkSecurityGroup", &v.NetworkSecurityGroup) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + 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 VirtualMachineScaleSetNetworkProfile. +func (v VirtualMachineScaleSetNetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "healthProbe", v.HealthProbe) + populate(objectMap, "networkApiVersion", v.NetworkAPIVersion) + populate(objectMap, "networkInterfaceConfigurations", v.NetworkInterfaceConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetNetworkProfile. +func (v *VirtualMachineScaleSetNetworkProfile) UnmarshalJSON(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 "healthProbe": + err = unpopulate(val, "HealthProbe", &v.HealthProbe) + delete(rawMsg, key) + case "networkApiVersion": + err = unpopulate(val, "NetworkAPIVersion", &v.NetworkAPIVersion) + delete(rawMsg, key) + case "networkInterfaceConfigurations": + err = unpopulate(val, "NetworkInterfaceConfigurations", &v.NetworkInterfaceConfigurations) + 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 VirtualMachineScaleSetOSDisk. +func (v VirtualMachineScaleSetOSDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", v.Caching) + populate(objectMap, "createOption", v.CreateOption) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "diffDiskSettings", v.DiffDiskSettings) + populate(objectMap, "diskSizeGB", v.DiskSizeGB) + populate(objectMap, "image", v.Image) + populate(objectMap, "managedDisk", v.ManagedDisk) + populate(objectMap, "name", v.Name) + populate(objectMap, "osType", v.OSType) + populate(objectMap, "vhdContainers", v.VhdContainers) + populate(objectMap, "writeAcceleratorEnabled", v.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetOSDisk. +func (v *VirtualMachineScaleSetOSDisk) UnmarshalJSON(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 "caching": + err = unpopulate(val, "Caching", &v.Caching) + delete(rawMsg, key) + case "createOption": + err = unpopulate(val, "CreateOption", &v.CreateOption) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "diffDiskSettings": + err = unpopulate(val, "DiffDiskSettings", &v.DiffDiskSettings) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &v.DiskSizeGB) + delete(rawMsg, key) + case "image": + err = unpopulate(val, "Image", &v.Image) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &v.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &v.OSType) + delete(rawMsg, key) + case "vhdContainers": + err = unpopulate(val, "VhdContainers", &v.VhdContainers) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &v.WriteAcceleratorEnabled) + 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 VirtualMachineScaleSetOSProfile. +func (v VirtualMachineScaleSetOSProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminPassword", v.AdminPassword) + populate(objectMap, "adminUsername", v.AdminUsername) + populate(objectMap, "allowExtensionOperations", v.AllowExtensionOperations) + populate(objectMap, "computerNamePrefix", v.ComputerNamePrefix) + populate(objectMap, "customData", v.CustomData) + populate(objectMap, "linuxConfiguration", v.LinuxConfiguration) + populate(objectMap, "requireGuestProvisionSignal", v.RequireGuestProvisionSignal) + populate(objectMap, "secrets", v.Secrets) + populate(objectMap, "windowsConfiguration", v.WindowsConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetOSProfile. +func (v *VirtualMachineScaleSetOSProfile) UnmarshalJSON(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 "adminPassword": + err = unpopulate(val, "AdminPassword", &v.AdminPassword) + delete(rawMsg, key) + case "adminUsername": + err = unpopulate(val, "AdminUsername", &v.AdminUsername) + delete(rawMsg, key) + case "allowExtensionOperations": + err = unpopulate(val, "AllowExtensionOperations", &v.AllowExtensionOperations) + delete(rawMsg, key) + case "computerNamePrefix": + err = unpopulate(val, "ComputerNamePrefix", &v.ComputerNamePrefix) + delete(rawMsg, key) + case "customData": + err = unpopulate(val, "CustomData", &v.CustomData) + delete(rawMsg, key) + case "linuxConfiguration": + err = unpopulate(val, "LinuxConfiguration", &v.LinuxConfiguration) + delete(rawMsg, key) + case "requireGuestProvisionSignal": + err = unpopulate(val, "RequireGuestProvisionSignal", &v.RequireGuestProvisionSignal) + delete(rawMsg, key) + case "secrets": + err = unpopulate(val, "Secrets", &v.Secrets) + delete(rawMsg, key) + case "windowsConfiguration": + err = unpopulate(val, "WindowsConfiguration", &v.WindowsConfiguration) + 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 VirtualMachineScaleSetProperties. +func (v VirtualMachineScaleSetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalCapabilities", v.AdditionalCapabilities) + populate(objectMap, "automaticRepairsPolicy", v.AutomaticRepairsPolicy) + populate(objectMap, "constrainedMaximumCapacity", v.ConstrainedMaximumCapacity) + populate(objectMap, "doNotRunExtensionsOnOverprovisionedVMs", v.DoNotRunExtensionsOnOverprovisionedVMs) + populate(objectMap, "hostGroup", v.HostGroup) + populate(objectMap, "orchestrationMode", v.OrchestrationMode) + populate(objectMap, "overprovision", v.Overprovision) + populate(objectMap, "platformFaultDomainCount", v.PlatformFaultDomainCount) + populate(objectMap, "priorityMixPolicy", v.PriorityMixPolicy) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "proximityPlacementGroup", v.ProximityPlacementGroup) + populate(objectMap, "resiliencyPolicy", v.ResiliencyPolicy) + populate(objectMap, "scaleInPolicy", v.ScaleInPolicy) + populate(objectMap, "singlePlacementGroup", v.SinglePlacementGroup) + populate(objectMap, "spotRestorePolicy", v.SpotRestorePolicy) + populateDateTimeRFC3339(objectMap, "timeCreated", v.TimeCreated) + populate(objectMap, "uniqueId", v.UniqueID) + populate(objectMap, "upgradePolicy", v.UpgradePolicy) + populate(objectMap, "virtualMachineProfile", v.VirtualMachineProfile) + populate(objectMap, "zoneBalance", v.ZoneBalance) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetProperties. +func (v *VirtualMachineScaleSetProperties) UnmarshalJSON(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 "additionalCapabilities": + err = unpopulate(val, "AdditionalCapabilities", &v.AdditionalCapabilities) + delete(rawMsg, key) + case "automaticRepairsPolicy": + err = unpopulate(val, "AutomaticRepairsPolicy", &v.AutomaticRepairsPolicy) + delete(rawMsg, key) + case "constrainedMaximumCapacity": + err = unpopulate(val, "ConstrainedMaximumCapacity", &v.ConstrainedMaximumCapacity) + delete(rawMsg, key) + case "doNotRunExtensionsOnOverprovisionedVMs": + err = unpopulate(val, "DoNotRunExtensionsOnOverprovisionedVMs", &v.DoNotRunExtensionsOnOverprovisionedVMs) + delete(rawMsg, key) + case "hostGroup": + err = unpopulate(val, "HostGroup", &v.HostGroup) + delete(rawMsg, key) + case "orchestrationMode": + err = unpopulate(val, "OrchestrationMode", &v.OrchestrationMode) + delete(rawMsg, key) + case "overprovision": + err = unpopulate(val, "Overprovision", &v.Overprovision) + delete(rawMsg, key) + case "platformFaultDomainCount": + err = unpopulate(val, "PlatformFaultDomainCount", &v.PlatformFaultDomainCount) + delete(rawMsg, key) + case "priorityMixPolicy": + err = unpopulate(val, "PriorityMixPolicy", &v.PriorityMixPolicy) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "proximityPlacementGroup": + err = unpopulate(val, "ProximityPlacementGroup", &v.ProximityPlacementGroup) + delete(rawMsg, key) + case "resiliencyPolicy": + err = unpopulate(val, "ResiliencyPolicy", &v.ResiliencyPolicy) + delete(rawMsg, key) + case "scaleInPolicy": + err = unpopulate(val, "ScaleInPolicy", &v.ScaleInPolicy) + delete(rawMsg, key) + case "singlePlacementGroup": + err = unpopulate(val, "SinglePlacementGroup", &v.SinglePlacementGroup) + delete(rawMsg, key) + case "spotRestorePolicy": + err = unpopulate(val, "SpotRestorePolicy", &v.SpotRestorePolicy) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &v.TimeCreated) + delete(rawMsg, key) + case "uniqueId": + err = unpopulate(val, "UniqueID", &v.UniqueID) + delete(rawMsg, key) + case "upgradePolicy": + err = unpopulate(val, "UpgradePolicy", &v.UpgradePolicy) + delete(rawMsg, key) + case "virtualMachineProfile": + err = unpopulate(val, "VirtualMachineProfile", &v.VirtualMachineProfile) + delete(rawMsg, key) + case "zoneBalance": + err = unpopulate(val, "ZoneBalance", &v.ZoneBalance) + 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 VirtualMachineScaleSetPublicIPAddressConfiguration. +func (v VirtualMachineScaleSetPublicIPAddressConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "sku", v.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetPublicIPAddressConfiguration. +func (v *VirtualMachineScaleSetPublicIPAddressConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + 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 VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings. +func (v VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domainNameLabel", v.DomainNameLabel) + populate(objectMap, "domainNameLabelScope", v.DomainNameLabelScope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings. +func (v *VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings) UnmarshalJSON(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 "domainNameLabel": + err = unpopulate(val, "DomainNameLabel", &v.DomainNameLabel) + delete(rawMsg, key) + case "domainNameLabelScope": + err = unpopulate(val, "DomainNameLabelScope", &v.DomainNameLabelScope) + 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 VirtualMachineScaleSetPublicIPAddressConfigurationProperties. +func (v VirtualMachineScaleSetPublicIPAddressConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "ipTags", v.IPTags) + populate(objectMap, "idleTimeoutInMinutes", v.IdleTimeoutInMinutes) + populate(objectMap, "publicIPAddressVersion", v.PublicIPAddressVersion) + populate(objectMap, "publicIPPrefix", v.PublicIPPrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetPublicIPAddressConfigurationProperties. +func (v *VirtualMachineScaleSetPublicIPAddressConfigurationProperties) UnmarshalJSON(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 "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "ipTags": + err = unpopulate(val, "IPTags", &v.IPTags) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &v.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "publicIPAddressVersion": + err = unpopulate(val, "PublicIPAddressVersion", &v.PublicIPAddressVersion) + delete(rawMsg, key) + case "publicIPPrefix": + err = unpopulate(val, "PublicIPPrefix", &v.PublicIPPrefix) + 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 VirtualMachineScaleSetReimageParameters. +func (v VirtualMachineScaleSetReimageParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exactVersion", v.ExactVersion) + populate(objectMap, "instanceIds", v.InstanceIDs) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "tempDisk", v.TempDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetReimageParameters. +func (v *VirtualMachineScaleSetReimageParameters) UnmarshalJSON(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 "exactVersion": + err = unpopulate(val, "ExactVersion", &v.ExactVersion) + delete(rawMsg, key) + case "instanceIds": + err = unpopulate(val, "InstanceIDs", &v.InstanceIDs) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "tempDisk": + err = unpopulate(val, "TempDisk", &v.TempDisk) + 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 VirtualMachineScaleSetSKU. +func (v VirtualMachineScaleSetSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", v.Capacity) + populate(objectMap, "resourceType", v.ResourceType) + populate(objectMap, "sku", v.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetSKU. +func (v *VirtualMachineScaleSetSKU) UnmarshalJSON(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 "capacity": + err = unpopulate(val, "Capacity", &v.Capacity) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &v.ResourceType) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + 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 VirtualMachineScaleSetSKUCapacity. +func (v VirtualMachineScaleSetSKUCapacity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultCapacity", v.DefaultCapacity) + populate(objectMap, "maximum", v.Maximum) + populate(objectMap, "minimum", v.Minimum) + populate(objectMap, "scaleType", v.ScaleType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetSKUCapacity. +func (v *VirtualMachineScaleSetSKUCapacity) UnmarshalJSON(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 "defaultCapacity": + err = unpopulate(val, "DefaultCapacity", &v.DefaultCapacity) + delete(rawMsg, key) + case "maximum": + err = unpopulate(val, "Maximum", &v.Maximum) + delete(rawMsg, key) + case "minimum": + err = unpopulate(val, "Minimum", &v.Minimum) + delete(rawMsg, key) + case "scaleType": + err = unpopulate(val, "ScaleType", &v.ScaleType) + 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 VirtualMachineScaleSetStorageProfile. +func (v VirtualMachineScaleSetStorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisks", v.DataDisks) + populate(objectMap, "diskControllerType", v.DiskControllerType) + populate(objectMap, "imageReference", v.ImageReference) + populate(objectMap, "osDisk", v.OSDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetStorageProfile. +func (v *VirtualMachineScaleSetStorageProfile) UnmarshalJSON(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 "dataDisks": + err = unpopulate(val, "DataDisks", &v.DataDisks) + delete(rawMsg, key) + case "diskControllerType": + err = unpopulate(val, "DiskControllerType", &v.DiskControllerType) + delete(rawMsg, key) + case "imageReference": + err = unpopulate(val, "ImageReference", &v.ImageReference) + delete(rawMsg, key) + case "osDisk": + err = unpopulate(val, "OSDisk", &v.OSDisk) + 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 VirtualMachineScaleSetUpdate. +func (v VirtualMachineScaleSetUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", v.Identity) + populate(objectMap, "plan", v.Plan) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "tags", v.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdate. +func (v *VirtualMachineScaleSetUpdate) UnmarshalJSON(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 "identity": + err = unpopulate(val, "Identity", &v.Identity) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &v.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + 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 VirtualMachineScaleSetUpdateIPConfiguration. +func (v VirtualMachineScaleSetUpdateIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateIPConfiguration. +func (v *VirtualMachineScaleSetUpdateIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualMachineScaleSetUpdateIPConfigurationProperties. +func (v VirtualMachineScaleSetUpdateIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationGatewayBackendAddressPools", v.ApplicationGatewayBackendAddressPools) + populate(objectMap, "applicationSecurityGroups", v.ApplicationSecurityGroups) + populate(objectMap, "loadBalancerBackendAddressPools", v.LoadBalancerBackendAddressPools) + populate(objectMap, "loadBalancerInboundNatPools", v.LoadBalancerInboundNatPools) + populate(objectMap, "primary", v.Primary) + populate(objectMap, "privateIPAddressVersion", v.PrivateIPAddressVersion) + populate(objectMap, "publicIPAddressConfiguration", v.PublicIPAddressConfiguration) + populate(objectMap, "subnet", v.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateIPConfigurationProperties. +func (v *VirtualMachineScaleSetUpdateIPConfigurationProperties) UnmarshalJSON(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 "applicationGatewayBackendAddressPools": + err = unpopulate(val, "ApplicationGatewayBackendAddressPools", &v.ApplicationGatewayBackendAddressPools) + delete(rawMsg, key) + case "applicationSecurityGroups": + err = unpopulate(val, "ApplicationSecurityGroups", &v.ApplicationSecurityGroups) + delete(rawMsg, key) + case "loadBalancerBackendAddressPools": + err = unpopulate(val, "LoadBalancerBackendAddressPools", &v.LoadBalancerBackendAddressPools) + delete(rawMsg, key) + case "loadBalancerInboundNatPools": + err = unpopulate(val, "LoadBalancerInboundNatPools", &v.LoadBalancerInboundNatPools) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + delete(rawMsg, key) + case "privateIPAddressVersion": + err = unpopulate(val, "PrivateIPAddressVersion", &v.PrivateIPAddressVersion) + delete(rawMsg, key) + case "publicIPAddressConfiguration": + err = unpopulate(val, "PublicIPAddressConfiguration", &v.PublicIPAddressConfiguration) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &v.Subnet) + 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 VirtualMachineScaleSetUpdateNetworkConfiguration. +func (v VirtualMachineScaleSetUpdateNetworkConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateNetworkConfiguration. +func (v *VirtualMachineScaleSetUpdateNetworkConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualMachineScaleSetUpdateNetworkConfigurationProperties. +func (v VirtualMachineScaleSetUpdateNetworkConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "auxiliaryMode", v.AuxiliaryMode) + populate(objectMap, "auxiliarySku", v.AuxiliarySKU) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "disableTcpStateTracking", v.DisableTCPStateTracking) + populate(objectMap, "enableAcceleratedNetworking", v.EnableAcceleratedNetworking) + populate(objectMap, "enableFpga", v.EnableFpga) + populate(objectMap, "enableIPForwarding", v.EnableIPForwarding) + populate(objectMap, "ipConfigurations", v.IPConfigurations) + populate(objectMap, "networkSecurityGroup", v.NetworkSecurityGroup) + populate(objectMap, "primary", v.Primary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateNetworkConfigurationProperties. +func (v *VirtualMachineScaleSetUpdateNetworkConfigurationProperties) UnmarshalJSON(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 "auxiliaryMode": + err = unpopulate(val, "AuxiliaryMode", &v.AuxiliaryMode) + delete(rawMsg, key) + case "auxiliarySku": + err = unpopulate(val, "AuxiliarySKU", &v.AuxiliarySKU) + delete(rawMsg, key) + case "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "disableTcpStateTracking": + err = unpopulate(val, "DisableTCPStateTracking", &v.DisableTCPStateTracking) + delete(rawMsg, key) + case "enableAcceleratedNetworking": + err = unpopulate(val, "EnableAcceleratedNetworking", &v.EnableAcceleratedNetworking) + delete(rawMsg, key) + case "enableFpga": + err = unpopulate(val, "EnableFpga", &v.EnableFpga) + delete(rawMsg, key) + case "enableIPForwarding": + err = unpopulate(val, "EnableIPForwarding", &v.EnableIPForwarding) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &v.IPConfigurations) + delete(rawMsg, key) + case "networkSecurityGroup": + err = unpopulate(val, "NetworkSecurityGroup", &v.NetworkSecurityGroup) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + 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 VirtualMachineScaleSetUpdateNetworkProfile. +func (v VirtualMachineScaleSetUpdateNetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "healthProbe", v.HealthProbe) + populate(objectMap, "networkApiVersion", v.NetworkAPIVersion) + populate(objectMap, "networkInterfaceConfigurations", v.NetworkInterfaceConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateNetworkProfile. +func (v *VirtualMachineScaleSetUpdateNetworkProfile) UnmarshalJSON(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 "healthProbe": + err = unpopulate(val, "HealthProbe", &v.HealthProbe) + delete(rawMsg, key) + case "networkApiVersion": + err = unpopulate(val, "NetworkAPIVersion", &v.NetworkAPIVersion) + delete(rawMsg, key) + case "networkInterfaceConfigurations": + err = unpopulate(val, "NetworkInterfaceConfigurations", &v.NetworkInterfaceConfigurations) + 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 VirtualMachineScaleSetUpdateOSDisk. +func (v VirtualMachineScaleSetUpdateOSDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", v.Caching) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "diskSizeGB", v.DiskSizeGB) + populate(objectMap, "image", v.Image) + populate(objectMap, "managedDisk", v.ManagedDisk) + populate(objectMap, "vhdContainers", v.VhdContainers) + populate(objectMap, "writeAcceleratorEnabled", v.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateOSDisk. +func (v *VirtualMachineScaleSetUpdateOSDisk) UnmarshalJSON(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 "caching": + err = unpopulate(val, "Caching", &v.Caching) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &v.DiskSizeGB) + delete(rawMsg, key) + case "image": + err = unpopulate(val, "Image", &v.Image) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &v.ManagedDisk) + delete(rawMsg, key) + case "vhdContainers": + err = unpopulate(val, "VhdContainers", &v.VhdContainers) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &v.WriteAcceleratorEnabled) + 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 VirtualMachineScaleSetUpdateOSProfile. +func (v VirtualMachineScaleSetUpdateOSProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customData", v.CustomData) + populate(objectMap, "linuxConfiguration", v.LinuxConfiguration) + populate(objectMap, "secrets", v.Secrets) + populate(objectMap, "windowsConfiguration", v.WindowsConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateOSProfile. +func (v *VirtualMachineScaleSetUpdateOSProfile) UnmarshalJSON(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 "customData": + err = unpopulate(val, "CustomData", &v.CustomData) + delete(rawMsg, key) + case "linuxConfiguration": + err = unpopulate(val, "LinuxConfiguration", &v.LinuxConfiguration) + delete(rawMsg, key) + case "secrets": + err = unpopulate(val, "Secrets", &v.Secrets) + delete(rawMsg, key) + case "windowsConfiguration": + err = unpopulate(val, "WindowsConfiguration", &v.WindowsConfiguration) + 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 VirtualMachineScaleSetUpdateProperties. +func (v VirtualMachineScaleSetUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalCapabilities", v.AdditionalCapabilities) + populate(objectMap, "automaticRepairsPolicy", v.AutomaticRepairsPolicy) + populate(objectMap, "doNotRunExtensionsOnOverprovisionedVMs", v.DoNotRunExtensionsOnOverprovisionedVMs) + populate(objectMap, "overprovision", v.Overprovision) + populate(objectMap, "priorityMixPolicy", v.PriorityMixPolicy) + populate(objectMap, "proximityPlacementGroup", v.ProximityPlacementGroup) + populate(objectMap, "resiliencyPolicy", v.ResiliencyPolicy) + populate(objectMap, "scaleInPolicy", v.ScaleInPolicy) + populate(objectMap, "singlePlacementGroup", v.SinglePlacementGroup) + populate(objectMap, "spotRestorePolicy", v.SpotRestorePolicy) + populate(objectMap, "upgradePolicy", v.UpgradePolicy) + populate(objectMap, "virtualMachineProfile", v.VirtualMachineProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateProperties. +func (v *VirtualMachineScaleSetUpdateProperties) UnmarshalJSON(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 "additionalCapabilities": + err = unpopulate(val, "AdditionalCapabilities", &v.AdditionalCapabilities) + delete(rawMsg, key) + case "automaticRepairsPolicy": + err = unpopulate(val, "AutomaticRepairsPolicy", &v.AutomaticRepairsPolicy) + delete(rawMsg, key) + case "doNotRunExtensionsOnOverprovisionedVMs": + err = unpopulate(val, "DoNotRunExtensionsOnOverprovisionedVMs", &v.DoNotRunExtensionsOnOverprovisionedVMs) + delete(rawMsg, key) + case "overprovision": + err = unpopulate(val, "Overprovision", &v.Overprovision) + delete(rawMsg, key) + case "priorityMixPolicy": + err = unpopulate(val, "PriorityMixPolicy", &v.PriorityMixPolicy) + delete(rawMsg, key) + case "proximityPlacementGroup": + err = unpopulate(val, "ProximityPlacementGroup", &v.ProximityPlacementGroup) + delete(rawMsg, key) + case "resiliencyPolicy": + err = unpopulate(val, "ResiliencyPolicy", &v.ResiliencyPolicy) + delete(rawMsg, key) + case "scaleInPolicy": + err = unpopulate(val, "ScaleInPolicy", &v.ScaleInPolicy) + delete(rawMsg, key) + case "singlePlacementGroup": + err = unpopulate(val, "SinglePlacementGroup", &v.SinglePlacementGroup) + delete(rawMsg, key) + case "spotRestorePolicy": + err = unpopulate(val, "SpotRestorePolicy", &v.SpotRestorePolicy) + delete(rawMsg, key) + case "upgradePolicy": + err = unpopulate(val, "UpgradePolicy", &v.UpgradePolicy) + delete(rawMsg, key) + case "virtualMachineProfile": + err = unpopulate(val, "VirtualMachineProfile", &v.VirtualMachineProfile) + 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 VirtualMachineScaleSetUpdatePublicIPAddressConfiguration. +func (v VirtualMachineScaleSetUpdatePublicIPAddressConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdatePublicIPAddressConfiguration. +func (v *VirtualMachineScaleSetUpdatePublicIPAddressConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties. +func (v VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "idleTimeoutInMinutes", v.IdleTimeoutInMinutes) + populate(objectMap, "publicIPPrefix", v.PublicIPPrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties. +func (v *VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties) UnmarshalJSON(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 "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &v.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "publicIPPrefix": + err = unpopulate(val, "PublicIPPrefix", &v.PublicIPPrefix) + 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 VirtualMachineScaleSetUpdateStorageProfile. +func (v VirtualMachineScaleSetUpdateStorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisks", v.DataDisks) + populate(objectMap, "diskControllerType", v.DiskControllerType) + populate(objectMap, "imageReference", v.ImageReference) + populate(objectMap, "osDisk", v.OSDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateStorageProfile. +func (v *VirtualMachineScaleSetUpdateStorageProfile) UnmarshalJSON(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 "dataDisks": + err = unpopulate(val, "DataDisks", &v.DataDisks) + delete(rawMsg, key) + case "diskControllerType": + err = unpopulate(val, "DiskControllerType", &v.DiskControllerType) + delete(rawMsg, key) + case "imageReference": + err = unpopulate(val, "ImageReference", &v.ImageReference) + delete(rawMsg, key) + case "osDisk": + err = unpopulate(val, "OSDisk", &v.OSDisk) + 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 VirtualMachineScaleSetUpdateVMProfile. +func (v VirtualMachineScaleSetUpdateVMProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "billingProfile", v.BillingProfile) + populate(objectMap, "diagnosticsProfile", v.DiagnosticsProfile) + populate(objectMap, "extensionProfile", v.ExtensionProfile) + populate(objectMap, "hardwareProfile", v.HardwareProfile) + populate(objectMap, "licenseType", v.LicenseType) + populate(objectMap, "networkProfile", v.NetworkProfile) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "scheduledEventsProfile", v.ScheduledEventsProfile) + populate(objectMap, "securityProfile", v.SecurityProfile) + populate(objectMap, "storageProfile", v.StorageProfile) + populate(objectMap, "userData", v.UserData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetUpdateVMProfile. +func (v *VirtualMachineScaleSetUpdateVMProfile) UnmarshalJSON(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 "billingProfile": + err = unpopulate(val, "BillingProfile", &v.BillingProfile) + delete(rawMsg, key) + case "diagnosticsProfile": + err = unpopulate(val, "DiagnosticsProfile", &v.DiagnosticsProfile) + delete(rawMsg, key) + case "extensionProfile": + err = unpopulate(val, "ExtensionProfile", &v.ExtensionProfile) + delete(rawMsg, key) + case "hardwareProfile": + err = unpopulate(val, "HardwareProfile", &v.HardwareProfile) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &v.LicenseType) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &v.NetworkProfile) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "scheduledEventsProfile": + err = unpopulate(val, "ScheduledEventsProfile", &v.ScheduledEventsProfile) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &v.SecurityProfile) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &v.StorageProfile) + delete(rawMsg, key) + case "userData": + err = unpopulate(val, "UserData", &v.UserData) + 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 VirtualMachineScaleSetVM. +func (v VirtualMachineScaleSetVM) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "identity", v.Identity) + populate(objectMap, "instanceId", v.InstanceID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "plan", v.Plan) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "resources", v.Resources) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + populate(objectMap, "zones", v.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVM. +func (v *VirtualMachineScaleSetVM) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &v.Identity) + delete(rawMsg, key) + case "instanceId": + err = unpopulate(val, "InstanceID", &v.InstanceID) + 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 "plan": + err = unpopulate(val, "Plan", &v.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &v.Resources) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + 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) + case "zones": + err = unpopulate(val, "Zones", &v.Zones) + 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 VirtualMachineScaleSetVMExtension. +func (v VirtualMachineScaleSetVMExtension) 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 VirtualMachineScaleSetVMExtension. +func (v *VirtualMachineScaleSetVMExtension) UnmarshalJSON(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 VirtualMachineScaleSetVMExtensionUpdate. +func (v VirtualMachineScaleSetVMExtensionUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + 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 VirtualMachineScaleSetVMExtensionUpdate. +func (v *VirtualMachineScaleSetVMExtensionUpdate) UnmarshalJSON(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 "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 VirtualMachineScaleSetVMExtensionsListResult. +func (v VirtualMachineScaleSetVMExtensionsListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMExtensionsListResult. +func (v *VirtualMachineScaleSetVMExtensionsListResult) UnmarshalJSON(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 "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 VirtualMachineScaleSetVMExtensionsSummary. +func (v VirtualMachineScaleSetVMExtensionsSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "statusesSummary", v.StatusesSummary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMExtensionsSummary. +func (v *VirtualMachineScaleSetVMExtensionsSummary) UnmarshalJSON(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 "statusesSummary": + err = unpopulate(val, "StatusesSummary", &v.StatusesSummary) + 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 VirtualMachineScaleSetVMInstanceIDs. +func (v VirtualMachineScaleSetVMInstanceIDs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceIds", v.InstanceIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMInstanceIDs. +func (v *VirtualMachineScaleSetVMInstanceIDs) UnmarshalJSON(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 "instanceIds": + err = unpopulate(val, "InstanceIDs", &v.InstanceIDs) + 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 VirtualMachineScaleSetVMInstanceRequiredIDs. +func (v VirtualMachineScaleSetVMInstanceRequiredIDs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceIds", v.InstanceIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMInstanceRequiredIDs. +func (v *VirtualMachineScaleSetVMInstanceRequiredIDs) UnmarshalJSON(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 "instanceIds": + err = unpopulate(val, "InstanceIDs", &v.InstanceIDs) + 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 VirtualMachineScaleSetVMInstanceView. +func (v VirtualMachineScaleSetVMInstanceView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assignedHost", v.AssignedHost) + populate(objectMap, "bootDiagnostics", v.BootDiagnostics) + populate(objectMap, "computerName", v.ComputerName) + populate(objectMap, "disks", v.Disks) + populate(objectMap, "extensions", v.Extensions) + populate(objectMap, "hyperVGeneration", v.HyperVGeneration) + populate(objectMap, "maintenanceRedeployStatus", v.MaintenanceRedeployStatus) + populate(objectMap, "osName", v.OSName) + populate(objectMap, "osVersion", v.OSVersion) + populate(objectMap, "placementGroupId", v.PlacementGroupID) + populate(objectMap, "platformFaultDomain", v.PlatformFaultDomain) + populate(objectMap, "platformUpdateDomain", v.PlatformUpdateDomain) + populate(objectMap, "rdpThumbPrint", v.RdpThumbPrint) + populate(objectMap, "statuses", v.Statuses) + populate(objectMap, "vmAgent", v.VMAgent) + populate(objectMap, "vmHealth", v.VMHealth) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMInstanceView. +func (v *VirtualMachineScaleSetVMInstanceView) UnmarshalJSON(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 "assignedHost": + err = unpopulate(val, "AssignedHost", &v.AssignedHost) + delete(rawMsg, key) + case "bootDiagnostics": + err = unpopulate(val, "BootDiagnostics", &v.BootDiagnostics) + delete(rawMsg, key) + case "computerName": + err = unpopulate(val, "ComputerName", &v.ComputerName) + delete(rawMsg, key) + case "disks": + err = unpopulate(val, "Disks", &v.Disks) + delete(rawMsg, key) + case "extensions": + err = unpopulate(val, "Extensions", &v.Extensions) + delete(rawMsg, key) + case "hyperVGeneration": + err = unpopulate(val, "HyperVGeneration", &v.HyperVGeneration) + delete(rawMsg, key) + case "maintenanceRedeployStatus": + err = unpopulate(val, "MaintenanceRedeployStatus", &v.MaintenanceRedeployStatus) + delete(rawMsg, key) + case "osName": + err = unpopulate(val, "OSName", &v.OSName) + delete(rawMsg, key) + case "osVersion": + err = unpopulate(val, "OSVersion", &v.OSVersion) + delete(rawMsg, key) + case "placementGroupId": + err = unpopulate(val, "PlacementGroupID", &v.PlacementGroupID) + delete(rawMsg, key) + case "platformFaultDomain": + err = unpopulate(val, "PlatformFaultDomain", &v.PlatformFaultDomain) + delete(rawMsg, key) + case "platformUpdateDomain": + err = unpopulate(val, "PlatformUpdateDomain", &v.PlatformUpdateDomain) + delete(rawMsg, key) + case "rdpThumbPrint": + err = unpopulate(val, "RdpThumbPrint", &v.RdpThumbPrint) + delete(rawMsg, key) + case "statuses": + err = unpopulate(val, "Statuses", &v.Statuses) + delete(rawMsg, key) + case "vmAgent": + err = unpopulate(val, "VMAgent", &v.VMAgent) + delete(rawMsg, key) + case "vmHealth": + err = unpopulate(val, "VMHealth", &v.VMHealth) + 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 VirtualMachineScaleSetVMListResult. +func (v VirtualMachineScaleSetVMListResult) 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 VirtualMachineScaleSetVMListResult. +func (v *VirtualMachineScaleSetVMListResult) UnmarshalJSON(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 VirtualMachineScaleSetVMNetworkProfileConfiguration. +func (v VirtualMachineScaleSetVMNetworkProfileConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkInterfaceConfigurations", v.NetworkInterfaceConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMNetworkProfileConfiguration. +func (v *VirtualMachineScaleSetVMNetworkProfileConfiguration) UnmarshalJSON(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 "networkInterfaceConfigurations": + err = unpopulate(val, "NetworkInterfaceConfigurations", &v.NetworkInterfaceConfigurations) + 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 VirtualMachineScaleSetVMProfile. +func (v VirtualMachineScaleSetVMProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationProfile", v.ApplicationProfile) + populate(objectMap, "billingProfile", v.BillingProfile) + populate(objectMap, "capacityReservation", v.CapacityReservation) + populate(objectMap, "diagnosticsProfile", v.DiagnosticsProfile) + populate(objectMap, "evictionPolicy", v.EvictionPolicy) + populate(objectMap, "extensionProfile", v.ExtensionProfile) + populate(objectMap, "hardwareProfile", v.HardwareProfile) + populate(objectMap, "licenseType", v.LicenseType) + populate(objectMap, "networkProfile", v.NetworkProfile) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "priority", v.Priority) + populate(objectMap, "scheduledEventsProfile", v.ScheduledEventsProfile) + populate(objectMap, "securityPostureReference", v.SecurityPostureReference) + populate(objectMap, "securityProfile", v.SecurityProfile) + populate(objectMap, "serviceArtifactReference", v.ServiceArtifactReference) + populate(objectMap, "storageProfile", v.StorageProfile) + populateDateTimeRFC3339(objectMap, "timeCreated", v.TimeCreated) + populate(objectMap, "userData", v.UserData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMProfile. +func (v *VirtualMachineScaleSetVMProfile) UnmarshalJSON(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 "applicationProfile": + err = unpopulate(val, "ApplicationProfile", &v.ApplicationProfile) + delete(rawMsg, key) + case "billingProfile": + err = unpopulate(val, "BillingProfile", &v.BillingProfile) + delete(rawMsg, key) + case "capacityReservation": + err = unpopulate(val, "CapacityReservation", &v.CapacityReservation) + delete(rawMsg, key) + case "diagnosticsProfile": + err = unpopulate(val, "DiagnosticsProfile", &v.DiagnosticsProfile) + delete(rawMsg, key) + case "evictionPolicy": + err = unpopulate(val, "EvictionPolicy", &v.EvictionPolicy) + delete(rawMsg, key) + case "extensionProfile": + err = unpopulate(val, "ExtensionProfile", &v.ExtensionProfile) + delete(rawMsg, key) + case "hardwareProfile": + err = unpopulate(val, "HardwareProfile", &v.HardwareProfile) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &v.LicenseType) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &v.NetworkProfile) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &v.Priority) + delete(rawMsg, key) + case "scheduledEventsProfile": + err = unpopulate(val, "ScheduledEventsProfile", &v.ScheduledEventsProfile) + delete(rawMsg, key) + case "securityPostureReference": + err = unpopulate(val, "SecurityPostureReference", &v.SecurityPostureReference) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &v.SecurityProfile) + delete(rawMsg, key) + case "serviceArtifactReference": + err = unpopulate(val, "ServiceArtifactReference", &v.ServiceArtifactReference) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &v.StorageProfile) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &v.TimeCreated) + delete(rawMsg, key) + case "userData": + err = unpopulate(val, "UserData", &v.UserData) + 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 VirtualMachineScaleSetVMProperties. +func (v VirtualMachineScaleSetVMProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalCapabilities", v.AdditionalCapabilities) + populate(objectMap, "availabilitySet", v.AvailabilitySet) + populate(objectMap, "diagnosticsProfile", v.DiagnosticsProfile) + populate(objectMap, "hardwareProfile", v.HardwareProfile) + populate(objectMap, "instanceView", v.InstanceView) + populate(objectMap, "latestModelApplied", v.LatestModelApplied) + populate(objectMap, "licenseType", v.LicenseType) + populate(objectMap, "modelDefinitionApplied", v.ModelDefinitionApplied) + populate(objectMap, "networkProfile", v.NetworkProfile) + populate(objectMap, "networkProfileConfiguration", v.NetworkProfileConfiguration) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "protectionPolicy", v.ProtectionPolicy) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "securityProfile", v.SecurityProfile) + populate(objectMap, "storageProfile", v.StorageProfile) + populateDateTimeRFC3339(objectMap, "timeCreated", v.TimeCreated) + populate(objectMap, "userData", v.UserData) + populate(objectMap, "vmId", v.VMID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMProperties. +func (v *VirtualMachineScaleSetVMProperties) UnmarshalJSON(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 "additionalCapabilities": + err = unpopulate(val, "AdditionalCapabilities", &v.AdditionalCapabilities) + delete(rawMsg, key) + case "availabilitySet": + err = unpopulate(val, "AvailabilitySet", &v.AvailabilitySet) + delete(rawMsg, key) + case "diagnosticsProfile": + err = unpopulate(val, "DiagnosticsProfile", &v.DiagnosticsProfile) + delete(rawMsg, key) + case "hardwareProfile": + err = unpopulate(val, "HardwareProfile", &v.HardwareProfile) + delete(rawMsg, key) + case "instanceView": + err = unpopulate(val, "InstanceView", &v.InstanceView) + delete(rawMsg, key) + case "latestModelApplied": + err = unpopulate(val, "LatestModelApplied", &v.LatestModelApplied) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &v.LicenseType) + delete(rawMsg, key) + case "modelDefinitionApplied": + err = unpopulate(val, "ModelDefinitionApplied", &v.ModelDefinitionApplied) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &v.NetworkProfile) + delete(rawMsg, key) + case "networkProfileConfiguration": + err = unpopulate(val, "NetworkProfileConfiguration", &v.NetworkProfileConfiguration) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "protectionPolicy": + err = unpopulate(val, "ProtectionPolicy", &v.ProtectionPolicy) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &v.SecurityProfile) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &v.StorageProfile) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateDateTimeRFC3339(val, "TimeCreated", &v.TimeCreated) + delete(rawMsg, key) + case "userData": + err = unpopulate(val, "UserData", &v.UserData) + delete(rawMsg, key) + case "vmId": + err = unpopulate(val, "VMID", &v.VMID) + 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 VirtualMachineScaleSetVMProtectionPolicy. +func (v VirtualMachineScaleSetVMProtectionPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "protectFromScaleIn", v.ProtectFromScaleIn) + populate(objectMap, "protectFromScaleSetActions", v.ProtectFromScaleSetActions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMProtectionPolicy. +func (v *VirtualMachineScaleSetVMProtectionPolicy) UnmarshalJSON(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 "protectFromScaleIn": + err = unpopulate(val, "ProtectFromScaleIn", &v.ProtectFromScaleIn) + delete(rawMsg, key) + case "protectFromScaleSetActions": + err = unpopulate(val, "ProtectFromScaleSetActions", &v.ProtectFromScaleSetActions) + 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 VirtualMachineScaleSetVMReimageParameters. +func (v VirtualMachineScaleSetVMReimageParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exactVersion", v.ExactVersion) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "tempDisk", v.TempDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineScaleSetVMReimageParameters. +func (v *VirtualMachineScaleSetVMReimageParameters) UnmarshalJSON(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 "exactVersion": + err = unpopulate(val, "ExactVersion", &v.ExactVersion) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "tempDisk": + err = unpopulate(val, "TempDisk", &v.TempDisk) + 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 VirtualMachineSize. +func (v VirtualMachineSize) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "maxDataDiskCount", v.MaxDataDiskCount) + populate(objectMap, "memoryInMB", v.MemoryInMB) + populate(objectMap, "name", v.Name) + populate(objectMap, "numberOfCores", v.NumberOfCores) + populate(objectMap, "osDiskSizeInMB", v.OSDiskSizeInMB) + populate(objectMap, "resourceDiskSizeInMB", v.ResourceDiskSizeInMB) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineSize. +func (v *VirtualMachineSize) UnmarshalJSON(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 "maxDataDiskCount": + err = unpopulate(val, "MaxDataDiskCount", &v.MaxDataDiskCount) + delete(rawMsg, key) + case "memoryInMB": + err = unpopulate(val, "MemoryInMB", &v.MemoryInMB) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "numberOfCores": + err = unpopulate(val, "NumberOfCores", &v.NumberOfCores) + delete(rawMsg, key) + case "osDiskSizeInMB": + err = unpopulate(val, "OSDiskSizeInMB", &v.OSDiskSizeInMB) + delete(rawMsg, key) + case "resourceDiskSizeInMB": + err = unpopulate(val, "ResourceDiskSizeInMB", &v.ResourceDiskSizeInMB) + 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 VirtualMachineSizeListResult. +func (v VirtualMachineSizeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineSizeListResult. +func (v *VirtualMachineSizeListResult) UnmarshalJSON(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 "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 VirtualMachineSoftwarePatchProperties. +func (v VirtualMachineSoftwarePatchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activityId", v.ActivityID) + populate(objectMap, "assessmentState", v.AssessmentState) + populate(objectMap, "classifications", v.Classifications) + populate(objectMap, "kbId", v.KbID) + populateDateTimeRFC3339(objectMap, "lastModifiedDateTime", v.LastModifiedDateTime) + populate(objectMap, "name", v.Name) + populate(objectMap, "patchId", v.PatchID) + populateDateTimeRFC3339(objectMap, "publishedDate", v.PublishedDate) + populate(objectMap, "rebootBehavior", v.RebootBehavior) + populate(objectMap, "version", v.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineSoftwarePatchProperties. +func (v *VirtualMachineSoftwarePatchProperties) UnmarshalJSON(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 "activityId": + err = unpopulate(val, "ActivityID", &v.ActivityID) + delete(rawMsg, key) + case "assessmentState": + err = unpopulate(val, "AssessmentState", &v.AssessmentState) + delete(rawMsg, key) + case "classifications": + err = unpopulate(val, "Classifications", &v.Classifications) + delete(rawMsg, key) + case "kbId": + err = unpopulate(val, "KbID", &v.KbID) + delete(rawMsg, key) + case "lastModifiedDateTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedDateTime", &v.LastModifiedDateTime) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "patchId": + err = unpopulate(val, "PatchID", &v.PatchID) + delete(rawMsg, key) + case "publishedDate": + err = unpopulateDateTimeRFC3339(val, "PublishedDate", &v.PublishedDate) + delete(rawMsg, key) + case "rebootBehavior": + err = unpopulate(val, "RebootBehavior", &v.RebootBehavior) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &v.Version) + 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 VirtualMachineStatusCodeCount. +func (v VirtualMachineStatusCodeCount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", v.Code) + populate(objectMap, "count", v.Count) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineStatusCodeCount. +func (v *VirtualMachineStatusCodeCount) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &v.Code) + delete(rawMsg, key) + case "count": + err = unpopulate(val, "Count", &v.Count) + 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 VirtualMachineUpdate. +func (v VirtualMachineUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", v.Identity) + populate(objectMap, "plan", v.Plan) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "zones", v.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineUpdate. +func (v *VirtualMachineUpdate) UnmarshalJSON(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 "identity": + err = unpopulate(val, "Identity", &v.Identity) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &v.Plan) + 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) + case "zones": + err = unpopulate(val, "Zones", &v.Zones) + 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 WinRMConfiguration. +func (w WinRMConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "listeners", w.Listeners) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WinRMConfiguration. +func (w *WinRMConfiguration) UnmarshalJSON(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 "listeners": + err = unpopulate(val, "Listeners", &w.Listeners) + 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 WinRMListener. +func (w WinRMListener) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateUrl", w.CertificateURL) + populate(objectMap, "protocol", w.Protocol) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WinRMListener. +func (w *WinRMListener) UnmarshalJSON(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 "certificateUrl": + err = unpopulate(val, "CertificateURL", &w.CertificateURL) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &w.Protocol) + 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 WindowsConfiguration. +func (w WindowsConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalUnattendContent", w.AdditionalUnattendContent) + populate(objectMap, "enableAutomaticUpdates", w.EnableAutomaticUpdates) + populate(objectMap, "enableVMAgentPlatformUpdates", w.EnableVMAgentPlatformUpdates) + populate(objectMap, "patchSettings", w.PatchSettings) + populate(objectMap, "provisionVMAgent", w.ProvisionVMAgent) + populate(objectMap, "timeZone", w.TimeZone) + populate(objectMap, "winRM", w.WinRM) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WindowsConfiguration. +func (w *WindowsConfiguration) UnmarshalJSON(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 "additionalUnattendContent": + err = unpopulate(val, "AdditionalUnattendContent", &w.AdditionalUnattendContent) + delete(rawMsg, key) + case "enableAutomaticUpdates": + err = unpopulate(val, "EnableAutomaticUpdates", &w.EnableAutomaticUpdates) + delete(rawMsg, key) + case "enableVMAgentPlatformUpdates": + err = unpopulate(val, "EnableVMAgentPlatformUpdates", &w.EnableVMAgentPlatformUpdates) + delete(rawMsg, key) + case "patchSettings": + err = unpopulate(val, "PatchSettings", &w.PatchSettings) + delete(rawMsg, key) + case "provisionVMAgent": + err = unpopulate(val, "ProvisionVMAgent", &w.ProvisionVMAgent) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &w.TimeZone) + delete(rawMsg, key) + case "winRM": + err = unpopulate(val, "WinRM", &w.WinRM) + 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 WindowsParameters. +func (w WindowsParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "classificationsToInclude", w.ClassificationsToInclude) + populate(objectMap, "excludeKbsRequiringReboot", w.ExcludeKbsRequiringReboot) + populate(objectMap, "kbNumbersToExclude", w.KbNumbersToExclude) + populate(objectMap, "kbNumbersToInclude", w.KbNumbersToInclude) + populateDateTimeRFC3339(objectMap, "maxPatchPublishDate", w.MaxPatchPublishDate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WindowsParameters. +func (w *WindowsParameters) UnmarshalJSON(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 "classificationsToInclude": + err = unpopulate(val, "ClassificationsToInclude", &w.ClassificationsToInclude) + delete(rawMsg, key) + case "excludeKbsRequiringReboot": + err = unpopulate(val, "ExcludeKbsRequiringReboot", &w.ExcludeKbsRequiringReboot) + delete(rawMsg, key) + case "kbNumbersToExclude": + err = unpopulate(val, "KbNumbersToExclude", &w.KbNumbersToExclude) + delete(rawMsg, key) + case "kbNumbersToInclude": + err = unpopulate(val, "KbNumbersToInclude", &w.KbNumbersToInclude) + delete(rawMsg, key) + case "maxPatchPublishDate": + err = unpopulateDateTimeRFC3339(val, "MaxPatchPublishDate", &w.MaxPatchPublishDate) + 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 WindowsVMGuestPatchAutomaticByPlatformSettings. +func (w WindowsVMGuestPatchAutomaticByPlatformSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypassPlatformSafetyChecksOnUserSchedule", w.BypassPlatformSafetyChecksOnUserSchedule) + populate(objectMap, "rebootSetting", w.RebootSetting) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WindowsVMGuestPatchAutomaticByPlatformSettings. +func (w *WindowsVMGuestPatchAutomaticByPlatformSettings) UnmarshalJSON(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 "bypassPlatformSafetyChecksOnUserSchedule": + err = unpopulate(val, "BypassPlatformSafetyChecksOnUserSchedule", &w.BypassPlatformSafetyChecksOnUserSchedule) + delete(rawMsg, key) + case "rebootSetting": + err = unpopulate(val, "RebootSetting", &w.RebootSetting) + 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 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/compute/armcompute/v5/operations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/operations_client.go new file mode 100644 index 000000000..f7fded74a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/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 armcompute + +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 - Gets a list of compute operations. +// +// Generated from API version 2023-09-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.Compute/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-09-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/compute/armcompute/v5/options.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/options.go new file mode 100644 index 000000000..0c363663a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/options.go @@ -0,0 +1,1979 @@ +//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 armcompute + +// AvailabilitySetsClientCreateOrUpdateOptions contains the optional parameters for the AvailabilitySetsClient.CreateOrUpdate +// method. +type AvailabilitySetsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AvailabilitySetsClientDeleteOptions contains the optional parameters for the AvailabilitySetsClient.Delete method. +type AvailabilitySetsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// AvailabilitySetsClientGetOptions contains the optional parameters for the AvailabilitySetsClient.Get method. +type AvailabilitySetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AvailabilitySetsClientListAvailableSizesOptions contains the optional parameters for the AvailabilitySetsClient.NewListAvailableSizesPager +// method. +type AvailabilitySetsClientListAvailableSizesOptions struct { + // placeholder for future optional parameters +} + +// AvailabilitySetsClientListBySubscriptionOptions contains the optional parameters for the AvailabilitySetsClient.NewListBySubscriptionPager +// method. +type AvailabilitySetsClientListBySubscriptionOptions struct { + // The expand expression to apply to the operation. Allowed values are 'instanceView'. + Expand *string +} + +// AvailabilitySetsClientListOptions contains the optional parameters for the AvailabilitySetsClient.NewListPager method. +type AvailabilitySetsClientListOptions struct { + // placeholder for future optional parameters +} + +// AvailabilitySetsClientUpdateOptions contains the optional parameters for the AvailabilitySetsClient.Update method. +type AvailabilitySetsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// CapacityReservationGroupsClientCreateOrUpdateOptions contains the optional parameters for the CapacityReservationGroupsClient.CreateOrUpdate +// method. +type CapacityReservationGroupsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// CapacityReservationGroupsClientDeleteOptions contains the optional parameters for the CapacityReservationGroupsClient.Delete +// method. +type CapacityReservationGroupsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// CapacityReservationGroupsClientGetOptions contains the optional parameters for the CapacityReservationGroupsClient.Get +// method. +type CapacityReservationGroupsClientGetOptions struct { + // The expand expression to apply on the operation. 'InstanceView' will retrieve the list of instance views of the capacity + // reservations under the capacity reservation group which is a snapshot of the + // runtime properties of a capacity reservation that is managed by the platform and can change outside of control plane operations. + Expand *CapacityReservationGroupInstanceViewTypes +} + +// CapacityReservationGroupsClientListByResourceGroupOptions contains the optional parameters for the CapacityReservationGroupsClient.NewListByResourceGroupPager +// method. +type CapacityReservationGroupsClientListByResourceGroupOptions struct { + // The expand expression to apply on the operation. Based on the expand param(s) specified we return Virtual Machine or ScaleSet + // VM Instance or both resource Ids which are associated to capacity + // reservation group in the response. + Expand *ExpandTypesForGetCapacityReservationGroups +} + +// CapacityReservationGroupsClientListBySubscriptionOptions contains the optional parameters for the CapacityReservationGroupsClient.NewListBySubscriptionPager +// method. +type CapacityReservationGroupsClientListBySubscriptionOptions struct { + // The expand expression to apply on the operation. Based on the expand param(s) specified we return Virtual Machine or ScaleSet + // VM Instance or both resource Ids which are associated to capacity + // reservation group in the response. + Expand *ExpandTypesForGetCapacityReservationGroups +} + +// CapacityReservationGroupsClientUpdateOptions contains the optional parameters for the CapacityReservationGroupsClient.Update +// method. +type CapacityReservationGroupsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// CapacityReservationsClientBeginCreateOrUpdateOptions contains the optional parameters for the CapacityReservationsClient.BeginCreateOrUpdate +// method. +type CapacityReservationsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CapacityReservationsClientBeginDeleteOptions contains the optional parameters for the CapacityReservationsClient.BeginDelete +// method. +type CapacityReservationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CapacityReservationsClientBeginUpdateOptions contains the optional parameters for the CapacityReservationsClient.BeginUpdate +// method. +type CapacityReservationsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CapacityReservationsClientGetOptions contains the optional parameters for the CapacityReservationsClient.Get method. +type CapacityReservationsClientGetOptions struct { + // The expand expression to apply on the operation. 'InstanceView' retrieves a snapshot of the runtime properties of the capacity + // reservation that is managed by the platform and can change outside of + // control plane operations. + Expand *CapacityReservationInstanceViewTypes +} + +// CapacityReservationsClientListByCapacityReservationGroupOptions contains the optional parameters for the CapacityReservationsClient.NewListByCapacityReservationGroupPager +// method. +type CapacityReservationsClientListByCapacityReservationGroupOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceOperatingSystemsClientGetOSFamilyOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.GetOSFamily +// method. +type CloudServiceOperatingSystemsClientGetOSFamilyOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceOperatingSystemsClientGetOSVersionOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.GetOSVersion +// method. +type CloudServiceOperatingSystemsClientGetOSVersionOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceOperatingSystemsClientListOSFamiliesOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.NewListOSFamiliesPager +// method. +type CloudServiceOperatingSystemsClientListOSFamiliesOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceOperatingSystemsClientListOSVersionsOptions contains the optional parameters for the CloudServiceOperatingSystemsClient.NewListOSVersionsPager +// method. +type CloudServiceOperatingSystemsClientListOSVersionsOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceRoleInstancesClientBeginDeleteOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginDelete +// method. +type CloudServiceRoleInstancesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServiceRoleInstancesClientBeginRebuildOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginRebuild +// method. +type CloudServiceRoleInstancesClientBeginRebuildOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServiceRoleInstancesClientBeginReimageOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginReimage +// method. +type CloudServiceRoleInstancesClientBeginReimageOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServiceRoleInstancesClientBeginRestartOptions contains the optional parameters for the CloudServiceRoleInstancesClient.BeginRestart +// method. +type CloudServiceRoleInstancesClientBeginRestartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServiceRoleInstancesClientGetInstanceViewOptions contains the optional parameters for the CloudServiceRoleInstancesClient.GetInstanceView +// method. +type CloudServiceRoleInstancesClientGetInstanceViewOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceRoleInstancesClientGetOptions contains the optional parameters for the CloudServiceRoleInstancesClient.Get +// method. +type CloudServiceRoleInstancesClientGetOptions struct { + // The expand expression to apply to the operation. 'UserData' is not supported for cloud services. + Expand *InstanceViewTypes +} + +// CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions contains the optional parameters for the CloudServiceRoleInstancesClient.GetRemoteDesktopFile +// method. +type CloudServiceRoleInstancesClientGetRemoteDesktopFileOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceRoleInstancesClientListOptions contains the optional parameters for the CloudServiceRoleInstancesClient.NewListPager +// method. +type CloudServiceRoleInstancesClientListOptions struct { + // The expand expression to apply to the operation. 'UserData' is not supported for cloud services. + Expand *InstanceViewTypes +} + +// CloudServiceRolesClientGetOptions contains the optional parameters for the CloudServiceRolesClient.Get method. +type CloudServiceRolesClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudServiceRolesClientListOptions contains the optional parameters for the CloudServiceRolesClient.NewListPager method. +type CloudServiceRolesClientListOptions struct { + // placeholder for future optional parameters +} + +// CloudServicesClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudServicesClient.BeginCreateOrUpdate +// method. +type CloudServicesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginDeleteInstancesOptions contains the optional parameters for the CloudServicesClient.BeginDeleteInstances +// method. +type CloudServicesClientBeginDeleteInstancesOptions struct { + // List of cloud service role instance names. + Parameters *RoleInstances + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginDeleteOptions contains the optional parameters for the CloudServicesClient.BeginDelete method. +type CloudServicesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginPowerOffOptions contains the optional parameters for the CloudServicesClient.BeginPowerOff method. +type CloudServicesClientBeginPowerOffOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginRebuildOptions contains the optional parameters for the CloudServicesClient.BeginRebuild method. +type CloudServicesClientBeginRebuildOptions struct { + // List of cloud service role instance names. + Parameters *RoleInstances + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginReimageOptions contains the optional parameters for the CloudServicesClient.BeginReimage method. +type CloudServicesClientBeginReimageOptions struct { + // List of cloud service role instance names. + Parameters *RoleInstances + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginRestartOptions contains the optional parameters for the CloudServicesClient.BeginRestart method. +type CloudServicesClientBeginRestartOptions struct { + // List of cloud service role instance names. + Parameters *RoleInstances + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginStartOptions contains the optional parameters for the CloudServicesClient.BeginStart method. +type CloudServicesClientBeginStartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientBeginUpdateOptions contains the optional parameters for the CloudServicesClient.BeginUpdate method. +type CloudServicesClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesClientGetInstanceViewOptions contains the optional parameters for the CloudServicesClient.GetInstanceView +// method. +type CloudServicesClientGetInstanceViewOptions struct { + // placeholder for future optional parameters +} + +// CloudServicesClientGetOptions contains the optional parameters for the CloudServicesClient.Get method. +type CloudServicesClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudServicesClientListAllOptions contains the optional parameters for the CloudServicesClient.NewListAllPager method. +type CloudServicesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// CloudServicesClientListOptions contains the optional parameters for the CloudServicesClient.NewListPager method. +type CloudServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions contains the optional parameters for the CloudServicesUpdateDomainClient.BeginWalkUpdateDomain +// method. +type CloudServicesUpdateDomainClientBeginWalkUpdateDomainOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CloudServicesUpdateDomainClientGetUpdateDomainOptions contains the optional parameters for the CloudServicesUpdateDomainClient.GetUpdateDomain +// method. +type CloudServicesUpdateDomainClientGetUpdateDomainOptions struct { + // placeholder for future optional parameters +} + +// CloudServicesUpdateDomainClientListUpdateDomainsOptions contains the optional parameters for the CloudServicesUpdateDomainClient.NewListUpdateDomainsPager +// method. +type CloudServicesUpdateDomainClientListUpdateDomainsOptions struct { + // placeholder for future optional parameters +} + +// CommunityGalleriesClientGetOptions contains the optional parameters for the CommunityGalleriesClient.Get method. +type CommunityGalleriesClientGetOptions struct { + // placeholder for future optional parameters +} + +// CommunityGalleryImageVersionsClientGetOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.Get +// method. +type CommunityGalleryImageVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// CommunityGalleryImageVersionsClientListOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.NewListPager +// method. +type CommunityGalleryImageVersionsClientListOptions struct { + // placeholder for future optional parameters +} + +// CommunityGalleryImagesClientGetOptions contains the optional parameters for the CommunityGalleryImagesClient.Get method. +type CommunityGalleryImagesClientGetOptions struct { + // placeholder for future optional parameters +} + +// CommunityGalleryImagesClientListOptions contains the optional parameters for the CommunityGalleryImagesClient.NewListPager +// method. +type CommunityGalleryImagesClientListOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHostGroupsClientCreateOrUpdateOptions contains the optional parameters for the DedicatedHostGroupsClient.CreateOrUpdate +// method. +type DedicatedHostGroupsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHostGroupsClientDeleteOptions contains the optional parameters for the DedicatedHostGroupsClient.Delete method. +type DedicatedHostGroupsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHostGroupsClientGetOptions contains the optional parameters for the DedicatedHostGroupsClient.Get method. +type DedicatedHostGroupsClientGetOptions struct { + // The expand expression to apply on the operation. 'InstanceView' will retrieve the list of instance views of the dedicated + // hosts under the dedicated host group. 'UserData' is not supported for + // dedicated host group. + Expand *InstanceViewTypes +} + +// DedicatedHostGroupsClientListByResourceGroupOptions contains the optional parameters for the DedicatedHostGroupsClient.NewListByResourceGroupPager +// method. +type DedicatedHostGroupsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHostGroupsClientListBySubscriptionOptions contains the optional parameters for the DedicatedHostGroupsClient.NewListBySubscriptionPager +// method. +type DedicatedHostGroupsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHostGroupsClientUpdateOptions contains the optional parameters for the DedicatedHostGroupsClient.Update method. +type DedicatedHostGroupsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the DedicatedHostsClient.BeginCreateOrUpdate +// method. +type DedicatedHostsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DedicatedHostsClientBeginDeleteOptions contains the optional parameters for the DedicatedHostsClient.BeginDelete method. +type DedicatedHostsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DedicatedHostsClientBeginRedeployOptions contains the optional parameters for the DedicatedHostsClient.BeginRedeploy method. +type DedicatedHostsClientBeginRedeployOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DedicatedHostsClientBeginRestartOptions contains the optional parameters for the DedicatedHostsClient.BeginRestart method. +type DedicatedHostsClientBeginRestartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DedicatedHostsClientBeginUpdateOptions contains the optional parameters for the DedicatedHostsClient.BeginUpdate method. +type DedicatedHostsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DedicatedHostsClientGetOptions contains the optional parameters for the DedicatedHostsClient.Get method. +type DedicatedHostsClientGetOptions struct { + // The expand expression to apply on the operation. 'InstanceView' will retrieve the list of instance views of the dedicated + // host. 'UserData' is not supported for dedicated host. + Expand *InstanceViewTypes +} + +// DedicatedHostsClientListAvailableSizesOptions contains the optional parameters for the DedicatedHostsClient.NewListAvailableSizesPager +// method. +type DedicatedHostsClientListAvailableSizesOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHostsClientListByHostGroupOptions contains the optional parameters for the DedicatedHostsClient.NewListByHostGroupPager +// method. +type DedicatedHostsClientListByHostGroupOptions struct { + // placeholder for future optional parameters +} + +// DiskAccessesClientBeginCreateOrUpdateOptions contains the optional parameters for the DiskAccessesClient.BeginCreateOrUpdate +// method. +type DiskAccessesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.BeginDeleteAPrivateEndpointConnection +// method. +type DiskAccessesClientBeginDeleteAPrivateEndpointConnectionOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskAccessesClientBeginDeleteOptions contains the optional parameters for the DiskAccessesClient.BeginDelete method. +type DiskAccessesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.BeginUpdateAPrivateEndpointConnection +// method. +type DiskAccessesClientBeginUpdateAPrivateEndpointConnectionOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskAccessesClientBeginUpdateOptions contains the optional parameters for the DiskAccessesClient.BeginUpdate method. +type DiskAccessesClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskAccessesClientGetAPrivateEndpointConnectionOptions contains the optional parameters for the DiskAccessesClient.GetAPrivateEndpointConnection +// method. +type DiskAccessesClientGetAPrivateEndpointConnectionOptions struct { + // placeholder for future optional parameters +} + +// DiskAccessesClientGetOptions contains the optional parameters for the DiskAccessesClient.Get method. +type DiskAccessesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DiskAccessesClientGetPrivateLinkResourcesOptions contains the optional parameters for the DiskAccessesClient.GetPrivateLinkResources +// method. +type DiskAccessesClientGetPrivateLinkResourcesOptions struct { + // placeholder for future optional parameters +} + +// DiskAccessesClientListByResourceGroupOptions contains the optional parameters for the DiskAccessesClient.NewListByResourceGroupPager +// method. +type DiskAccessesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// DiskAccessesClientListOptions contains the optional parameters for the DiskAccessesClient.NewListPager method. +type DiskAccessesClientListOptions struct { + // placeholder for future optional parameters +} + +// DiskAccessesClientListPrivateEndpointConnectionsOptions contains the optional parameters for the DiskAccessesClient.NewListPrivateEndpointConnectionsPager +// method. +type DiskAccessesClientListPrivateEndpointConnectionsOptions struct { + // placeholder for future optional parameters +} + +// DiskEncryptionSetsClientBeginCreateOrUpdateOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginCreateOrUpdate +// method. +type DiskEncryptionSetsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskEncryptionSetsClientBeginDeleteOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginDelete +// method. +type DiskEncryptionSetsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskEncryptionSetsClientBeginUpdateOptions contains the optional parameters for the DiskEncryptionSetsClient.BeginUpdate +// method. +type DiskEncryptionSetsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskEncryptionSetsClientGetOptions contains the optional parameters for the DiskEncryptionSetsClient.Get method. +type DiskEncryptionSetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DiskEncryptionSetsClientListAssociatedResourcesOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListAssociatedResourcesPager +// method. +type DiskEncryptionSetsClientListAssociatedResourcesOptions struct { + // placeholder for future optional parameters +} + +// DiskEncryptionSetsClientListByResourceGroupOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListByResourceGroupPager +// method. +type DiskEncryptionSetsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// DiskEncryptionSetsClientListOptions contains the optional parameters for the DiskEncryptionSetsClient.NewListPager method. +type DiskEncryptionSetsClientListOptions struct { + // placeholder for future optional parameters +} + +// DiskRestorePointClientBeginGrantAccessOptions contains the optional parameters for the DiskRestorePointClient.BeginGrantAccess +// method. +type DiskRestorePointClientBeginGrantAccessOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskRestorePointClientBeginRevokeAccessOptions contains the optional parameters for the DiskRestorePointClient.BeginRevokeAccess +// method. +type DiskRestorePointClientBeginRevokeAccessOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DiskRestorePointClientGetOptions contains the optional parameters for the DiskRestorePointClient.Get method. +type DiskRestorePointClientGetOptions struct { + // placeholder for future optional parameters +} + +// DiskRestorePointClientListByRestorePointOptions contains the optional parameters for the DiskRestorePointClient.NewListByRestorePointPager +// method. +type DiskRestorePointClientListByRestorePointOptions struct { + // placeholder for future optional parameters +} + +// DisksClientBeginCreateOrUpdateOptions contains the optional parameters for the DisksClient.BeginCreateOrUpdate method. +type DisksClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DisksClientBeginDeleteOptions contains the optional parameters for the DisksClient.BeginDelete method. +type DisksClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DisksClientBeginGrantAccessOptions contains the optional parameters for the DisksClient.BeginGrantAccess method. +type DisksClientBeginGrantAccessOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DisksClientBeginRevokeAccessOptions contains the optional parameters for the DisksClient.BeginRevokeAccess method. +type DisksClientBeginRevokeAccessOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DisksClientBeginUpdateOptions contains the optional parameters for the DisksClient.BeginUpdate method. +type DisksClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DisksClientGetOptions contains the optional parameters for the DisksClient.Get method. +type DisksClientGetOptions struct { + // placeholder for future optional parameters +} + +// DisksClientListByResourceGroupOptions contains the optional parameters for the DisksClient.NewListByResourceGroupPager +// method. +type DisksClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// DisksClientListOptions contains the optional parameters for the DisksClient.NewListPager method. +type DisksClientListOptions struct { + // placeholder for future optional parameters +} + +// GalleriesClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleriesClient.BeginCreateOrUpdate +// method. +type GalleriesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleriesClientBeginDeleteOptions contains the optional parameters for the GalleriesClient.BeginDelete method. +type GalleriesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleriesClientBeginUpdateOptions contains the optional parameters for the GalleriesClient.BeginUpdate method. +type GalleriesClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleriesClientGetOptions contains the optional parameters for the GalleriesClient.Get method. +type GalleriesClientGetOptions struct { + // The expand query option to apply on the operation. + Expand *GalleryExpandParams + + // The select expression to apply on the operation. + Select *SelectPermissions +} + +// GalleriesClientListByResourceGroupOptions contains the optional parameters for the GalleriesClient.NewListByResourceGroupPager +// method. +type GalleriesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// GalleriesClientListOptions contains the optional parameters for the GalleriesClient.NewListPager method. +type GalleriesClientListOptions struct { + // placeholder for future optional parameters +} + +// GalleryApplicationVersionsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginCreateOrUpdate +// method. +type GalleryApplicationVersionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryApplicationVersionsClientBeginDeleteOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginDelete +// method. +type GalleryApplicationVersionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryApplicationVersionsClientBeginUpdateOptions contains the optional parameters for the GalleryApplicationVersionsClient.BeginUpdate +// method. +type GalleryApplicationVersionsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryApplicationVersionsClientGetOptions contains the optional parameters for the GalleryApplicationVersionsClient.Get +// method. +type GalleryApplicationVersionsClientGetOptions struct { + // The expand expression to apply on the operation. + Expand *ReplicationStatusTypes +} + +// GalleryApplicationVersionsClientListByGalleryApplicationOptions contains the optional parameters for the GalleryApplicationVersionsClient.NewListByGalleryApplicationPager +// method. +type GalleryApplicationVersionsClientListByGalleryApplicationOptions struct { + // placeholder for future optional parameters +} + +// GalleryApplicationsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryApplicationsClient.BeginCreateOrUpdate +// method. +type GalleryApplicationsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryApplicationsClientBeginDeleteOptions contains the optional parameters for the GalleryApplicationsClient.BeginDelete +// method. +type GalleryApplicationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryApplicationsClientBeginUpdateOptions contains the optional parameters for the GalleryApplicationsClient.BeginUpdate +// method. +type GalleryApplicationsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryApplicationsClientGetOptions contains the optional parameters for the GalleryApplicationsClient.Get method. +type GalleryApplicationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// GalleryApplicationsClientListByGalleryOptions contains the optional parameters for the GalleryApplicationsClient.NewListByGalleryPager +// method. +type GalleryApplicationsClientListByGalleryOptions struct { + // placeholder for future optional parameters +} + +// GalleryImageVersionsClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryImageVersionsClient.BeginCreateOrUpdate +// method. +type GalleryImageVersionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryImageVersionsClientBeginDeleteOptions contains the optional parameters for the GalleryImageVersionsClient.BeginDelete +// method. +type GalleryImageVersionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryImageVersionsClientBeginUpdateOptions contains the optional parameters for the GalleryImageVersionsClient.BeginUpdate +// method. +type GalleryImageVersionsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryImageVersionsClientGetOptions contains the optional parameters for the GalleryImageVersionsClient.Get method. +type GalleryImageVersionsClientGetOptions struct { + // The expand expression to apply on the operation. + Expand *ReplicationStatusTypes +} + +// GalleryImageVersionsClientListByGalleryImageOptions contains the optional parameters for the GalleryImageVersionsClient.NewListByGalleryImagePager +// method. +type GalleryImageVersionsClientListByGalleryImageOptions struct { + // placeholder for future optional parameters +} + +// GalleryImagesClientBeginCreateOrUpdateOptions contains the optional parameters for the GalleryImagesClient.BeginCreateOrUpdate +// method. +type GalleryImagesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryImagesClientBeginDeleteOptions contains the optional parameters for the GalleryImagesClient.BeginDelete method. +type GalleryImagesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryImagesClientBeginUpdateOptions contains the optional parameters for the GalleryImagesClient.BeginUpdate method. +type GalleryImagesClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GalleryImagesClientGetOptions contains the optional parameters for the GalleryImagesClient.Get method. +type GalleryImagesClientGetOptions struct { + // placeholder for future optional parameters +} + +// GalleryImagesClientListByGalleryOptions contains the optional parameters for the GalleryImagesClient.NewListByGalleryPager +// method. +type GalleryImagesClientListByGalleryOptions struct { + // placeholder for future optional parameters +} + +// GallerySharingProfileClientBeginUpdateOptions contains the optional parameters for the GallerySharingProfileClient.BeginUpdate +// method. +type GallerySharingProfileClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ImagesClientBeginCreateOrUpdateOptions contains the optional parameters for the ImagesClient.BeginCreateOrUpdate method. +type ImagesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ImagesClientBeginDeleteOptions contains the optional parameters for the ImagesClient.BeginDelete method. +type ImagesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ImagesClientBeginUpdateOptions contains the optional parameters for the ImagesClient.BeginUpdate method. +type ImagesClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ImagesClientGetOptions contains the optional parameters for the ImagesClient.Get method. +type ImagesClientGetOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// ImagesClientListByResourceGroupOptions contains the optional parameters for the ImagesClient.NewListByResourceGroupPager +// method. +type ImagesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ImagesClientListOptions contains the optional parameters for the ImagesClient.NewListPager method. +type ImagesClientListOptions struct { + // placeholder for future optional parameters +} + +// LogAnalyticsClientBeginExportRequestRateByIntervalOptions contains the optional parameters for the LogAnalyticsClient.BeginExportRequestRateByInterval +// method. +type LogAnalyticsClientBeginExportRequestRateByIntervalOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LogAnalyticsClientBeginExportThrottledRequestsOptions contains the optional parameters for the LogAnalyticsClient.BeginExportThrottledRequests +// method. +type LogAnalyticsClientBeginExportThrottledRequestsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ProximityPlacementGroupsClientCreateOrUpdateOptions contains the optional parameters for the ProximityPlacementGroupsClient.CreateOrUpdate +// method. +type ProximityPlacementGroupsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ProximityPlacementGroupsClientDeleteOptions contains the optional parameters for the ProximityPlacementGroupsClient.Delete +// method. +type ProximityPlacementGroupsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ProximityPlacementGroupsClientGetOptions contains the optional parameters for the ProximityPlacementGroupsClient.Get method. +type ProximityPlacementGroupsClientGetOptions struct { + // includeColocationStatus=true enables fetching the colocation status of all the resources in the proximity placement group. + IncludeColocationStatus *string +} + +// ProximityPlacementGroupsClientListByResourceGroupOptions contains the optional parameters for the ProximityPlacementGroupsClient.NewListByResourceGroupPager +// method. +type ProximityPlacementGroupsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ProximityPlacementGroupsClientListBySubscriptionOptions contains the optional parameters for the ProximityPlacementGroupsClient.NewListBySubscriptionPager +// method. +type ProximityPlacementGroupsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ProximityPlacementGroupsClientUpdateOptions contains the optional parameters for the ProximityPlacementGroupsClient.Update +// method. +type ProximityPlacementGroupsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// ResourceSKUsClientListOptions contains the optional parameters for the ResourceSKUsClient.NewListPager method. +type ResourceSKUsClientListOptions struct { + // The filter to apply on the operation. Only location filter is supported currently. + Filter *string + + // To Include Extended Locations information or not in the response. + IncludeExtendedLocations *string +} + +// RestorePointCollectionsClientBeginDeleteOptions contains the optional parameters for the RestorePointCollectionsClient.BeginDelete +// method. +type RestorePointCollectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RestorePointCollectionsClientCreateOrUpdateOptions contains the optional parameters for the RestorePointCollectionsClient.CreateOrUpdate +// method. +type RestorePointCollectionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RestorePointCollectionsClientGetOptions contains the optional parameters for the RestorePointCollectionsClient.Get method. +type RestorePointCollectionsClientGetOptions struct { + // The expand expression to apply on the operation. If expand=restorePoints, server will return all contained restore points + // in the restorePointCollection. + Expand *RestorePointCollectionExpandOptions +} + +// RestorePointCollectionsClientListAllOptions contains the optional parameters for the RestorePointCollectionsClient.NewListAllPager +// method. +type RestorePointCollectionsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// RestorePointCollectionsClientListOptions contains the optional parameters for the RestorePointCollectionsClient.NewListPager +// method. +type RestorePointCollectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// RestorePointCollectionsClientUpdateOptions contains the optional parameters for the RestorePointCollectionsClient.Update +// method. +type RestorePointCollectionsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// RestorePointsClientBeginCreateOptions contains the optional parameters for the RestorePointsClient.BeginCreate method. +type RestorePointsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RestorePointsClientBeginDeleteOptions contains the optional parameters for the RestorePointsClient.BeginDelete method. +type RestorePointsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RestorePointsClientGetOptions contains the optional parameters for the RestorePointsClient.Get method. +type RestorePointsClientGetOptions struct { + // The expand expression to apply on the operation. 'InstanceView' retrieves information about the run-time state of a restore + // point. + Expand *RestorePointExpandOptions +} + +// SSHPublicKeysClientCreateOptions contains the optional parameters for the SSHPublicKeysClient.Create method. +type SSHPublicKeysClientCreateOptions struct { + // placeholder for future optional parameters +} + +// SSHPublicKeysClientDeleteOptions contains the optional parameters for the SSHPublicKeysClient.Delete method. +type SSHPublicKeysClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SSHPublicKeysClientGenerateKeyPairOptions contains the optional parameters for the SSHPublicKeysClient.GenerateKeyPair +// method. +type SSHPublicKeysClientGenerateKeyPairOptions struct { + // Parameters supplied to generate the SSH public key. + Parameters *SSHGenerateKeyPairInputParameters +} + +// SSHPublicKeysClientGetOptions contains the optional parameters for the SSHPublicKeysClient.Get method. +type SSHPublicKeysClientGetOptions struct { + // placeholder for future optional parameters +} + +// SSHPublicKeysClientListByResourceGroupOptions contains the optional parameters for the SSHPublicKeysClient.NewListByResourceGroupPager +// method. +type SSHPublicKeysClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// SSHPublicKeysClientListBySubscriptionOptions contains the optional parameters for the SSHPublicKeysClient.NewListBySubscriptionPager +// method. +type SSHPublicKeysClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// SSHPublicKeysClientUpdateOptions contains the optional parameters for the SSHPublicKeysClient.Update method. +type SSHPublicKeysClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// SharedGalleriesClientGetOptions contains the optional parameters for the SharedGalleriesClient.Get method. +type SharedGalleriesClientGetOptions struct { + // placeholder for future optional parameters +} + +// SharedGalleriesClientListOptions contains the optional parameters for the SharedGalleriesClient.NewListPager method. +type SharedGalleriesClientListOptions struct { + // The query parameter to decide what shared galleries to fetch when doing listing operations. + SharedTo *SharedToValues +} + +// SharedGalleryImageVersionsClientGetOptions contains the optional parameters for the SharedGalleryImageVersionsClient.Get +// method. +type SharedGalleryImageVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SharedGalleryImageVersionsClientListOptions contains the optional parameters for the SharedGalleryImageVersionsClient.NewListPager +// method. +type SharedGalleryImageVersionsClientListOptions struct { + // The query parameter to decide what shared galleries to fetch when doing listing operations. + SharedTo *SharedToValues +} + +// SharedGalleryImagesClientGetOptions contains the optional parameters for the SharedGalleryImagesClient.Get method. +type SharedGalleryImagesClientGetOptions struct { + // placeholder for future optional parameters +} + +// SharedGalleryImagesClientListOptions contains the optional parameters for the SharedGalleryImagesClient.NewListPager method. +type SharedGalleryImagesClientListOptions struct { + // The query parameter to decide what shared galleries to fetch when doing listing operations. + SharedTo *SharedToValues +} + +// SnapshotsClientBeginCreateOrUpdateOptions contains the optional parameters for the SnapshotsClient.BeginCreateOrUpdate +// method. +type SnapshotsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SnapshotsClientBeginDeleteOptions contains the optional parameters for the SnapshotsClient.BeginDelete method. +type SnapshotsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SnapshotsClientBeginGrantAccessOptions contains the optional parameters for the SnapshotsClient.BeginGrantAccess method. +type SnapshotsClientBeginGrantAccessOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SnapshotsClientBeginRevokeAccessOptions contains the optional parameters for the SnapshotsClient.BeginRevokeAccess method. +type SnapshotsClientBeginRevokeAccessOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SnapshotsClientBeginUpdateOptions contains the optional parameters for the SnapshotsClient.BeginUpdate method. +type SnapshotsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SnapshotsClientGetOptions contains the optional parameters for the SnapshotsClient.Get method. +type SnapshotsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SnapshotsClientListByResourceGroupOptions contains the optional parameters for the SnapshotsClient.NewListByResourceGroupPager +// method. +type SnapshotsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// SnapshotsClientListOptions contains the optional parameters for the SnapshotsClient.NewListPager method. +type SnapshotsClientListOptions struct { + // placeholder for future optional parameters +} + +// UsageClientListOptions contains the optional parameters for the UsageClient.NewListPager method. +type UsageClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineExtensionImagesClientGetOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.Get +// method. +type VirtualMachineExtensionImagesClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineExtensionImagesClientListTypesOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.ListTypes +// method. +type VirtualMachineExtensionImagesClientListTypesOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineExtensionImagesClientListVersionsOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.ListVersions +// method. +type VirtualMachineExtensionImagesClientListVersionsOptions struct { + // The filter to apply on the operation. + Filter *string + Orderby *string + Top *int32 +} + +// VirtualMachineExtensionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginCreateOrUpdate +// method. +type VirtualMachineExtensionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineExtensionsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginDelete +// method. +type VirtualMachineExtensionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineExtensionsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginUpdate +// method. +type VirtualMachineExtensionsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineExtensionsClientGetOptions contains the optional parameters for the VirtualMachineExtensionsClient.Get method. +type VirtualMachineExtensionsClientGetOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineExtensionsClientListOptions contains the optional parameters for the VirtualMachineExtensionsClient.List +// method. +type VirtualMachineExtensionsClientListOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineImagesClientGetOptions contains the optional parameters for the VirtualMachineImagesClient.Get method. +type VirtualMachineImagesClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesClientListByEdgeZoneOptions contains the optional parameters for the VirtualMachineImagesClient.ListByEdgeZone +// method. +type VirtualMachineImagesClientListByEdgeZoneOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesClientListOffersOptions contains the optional parameters for the VirtualMachineImagesClient.ListOffers +// method. +type VirtualMachineImagesClientListOffersOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesClientListOptions contains the optional parameters for the VirtualMachineImagesClient.List method. +type VirtualMachineImagesClientListOptions struct { + // The expand expression to apply on the operation. + Expand *string + Orderby *string + Top *int32 +} + +// VirtualMachineImagesClientListPublishersOptions contains the optional parameters for the VirtualMachineImagesClient.ListPublishers +// method. +type VirtualMachineImagesClientListPublishersOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesClientListSKUsOptions contains the optional parameters for the VirtualMachineImagesClient.ListSKUs +// method. +type VirtualMachineImagesClientListSKUsOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesEdgeZoneClientGetOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.Get +// method. +type VirtualMachineImagesEdgeZoneClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesEdgeZoneClientListOffersOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.ListOffers +// method. +type VirtualMachineImagesEdgeZoneClientListOffersOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesEdgeZoneClientListOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.List +// method. +type VirtualMachineImagesEdgeZoneClientListOptions struct { + // The expand expression to apply on the operation. + Expand *string + + // Specifies the order of the results returned. Formatted as an OData query. + Orderby *string + + // An integer value specifying the number of images to return that matches supplied values. + Top *int32 +} + +// VirtualMachineImagesEdgeZoneClientListPublishersOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.ListPublishers +// method. +type VirtualMachineImagesEdgeZoneClientListPublishersOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineImagesEdgeZoneClientListSKUsOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.ListSKUs +// method. +type VirtualMachineImagesEdgeZoneClientListSKUsOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineRunCommandsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineRunCommandsClient.BeginCreateOrUpdate +// method. +type VirtualMachineRunCommandsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineRunCommandsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineRunCommandsClient.BeginDelete +// method. +type VirtualMachineRunCommandsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineRunCommandsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineRunCommandsClient.BeginUpdate +// method. +type VirtualMachineRunCommandsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineRunCommandsClientGetByVirtualMachineOptions contains the optional parameters for the VirtualMachineRunCommandsClient.GetByVirtualMachine +// method. +type VirtualMachineRunCommandsClientGetByVirtualMachineOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineRunCommandsClientGetOptions contains the optional parameters for the VirtualMachineRunCommandsClient.Get +// method. +type VirtualMachineRunCommandsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineRunCommandsClientListByVirtualMachineOptions contains the optional parameters for the VirtualMachineRunCommandsClient.NewListByVirtualMachinePager +// method. +type VirtualMachineRunCommandsClientListByVirtualMachineOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineRunCommandsClientListOptions contains the optional parameters for the VirtualMachineRunCommandsClient.NewListPager +// method. +type VirtualMachineRunCommandsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetExtensionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.BeginCreateOrUpdate +// method. +type VirtualMachineScaleSetExtensionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetExtensionsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.BeginDelete +// method. +type VirtualMachineScaleSetExtensionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetExtensionsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.BeginUpdate +// method. +type VirtualMachineScaleSetExtensionsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetExtensionsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.Get +// method. +type VirtualMachineScaleSetExtensionsClientGetOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineScaleSetExtensionsClientListOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.NewListPager +// method. +type VirtualMachineScaleSetExtensionsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetRollingUpgradesClientBeginCancelOptions contains the optional parameters for the VirtualMachineScaleSetRollingUpgradesClient.BeginCancel +// method. +type VirtualMachineScaleSetRollingUpgradesClientBeginCancelOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetRollingUpgradesClientBeginStartExtensionUpgradeOptions contains the optional parameters for the VirtualMachineScaleSetRollingUpgradesClient.BeginStartExtensionUpgrade +// method. +type VirtualMachineScaleSetRollingUpgradesClientBeginStartExtensionUpgradeOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetRollingUpgradesClientBeginStartOSUpgradeOptions contains the optional parameters for the VirtualMachineScaleSetRollingUpgradesClient.BeginStartOSUpgrade +// method. +type VirtualMachineScaleSetRollingUpgradesClientBeginStartOSUpgradeOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetRollingUpgradesClientGetLatestOptions contains the optional parameters for the VirtualMachineScaleSetRollingUpgradesClient.GetLatest +// method. +type VirtualMachineScaleSetRollingUpgradesClientGetLatestOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetVMExtensionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.BeginCreateOrUpdate +// method. +type VirtualMachineScaleSetVMExtensionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMExtensionsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.BeginDelete +// method. +type VirtualMachineScaleSetVMExtensionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMExtensionsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.BeginUpdate +// method. +type VirtualMachineScaleSetVMExtensionsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMExtensionsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.Get +// method. +type VirtualMachineScaleSetVMExtensionsClientGetOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineScaleSetVMExtensionsClientListOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.List +// method. +type VirtualMachineScaleSetVMExtensionsClientListOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineScaleSetVMRunCommandsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.BeginCreateOrUpdate +// method. +type VirtualMachineScaleSetVMRunCommandsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMRunCommandsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.BeginDelete +// method. +type VirtualMachineScaleSetVMRunCommandsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMRunCommandsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.BeginUpdate +// method. +type VirtualMachineScaleSetVMRunCommandsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMRunCommandsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.Get +// method. +type VirtualMachineScaleSetVMRunCommandsClientGetOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineScaleSetVMRunCommandsClientListOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.NewListPager +// method. +type VirtualMachineScaleSetVMRunCommandsClientListOptions struct { + // The expand expression to apply on the operation. + Expand *string +} + +// VirtualMachineScaleSetVMsClientBeginApproveRollingUpgradeOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginApproveRollingUpgrade +// method. +type VirtualMachineScaleSetVMsClientBeginApproveRollingUpgradeOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginAttachDetachDataDisksOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginAttachDetachDataDisks +// method. +type VirtualMachineScaleSetVMsClientBeginAttachDetachDataDisksOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginDeallocateOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginDeallocate +// method. +type VirtualMachineScaleSetVMsClientBeginDeallocateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginDelete +// method. +type VirtualMachineScaleSetVMsClientBeginDeleteOptions struct { + // Optional parameter to force delete a virtual machine from a VM scale set. (Feature in Preview) + ForceDeletion *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginPerformMaintenanceOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginPerformMaintenance +// method. +type VirtualMachineScaleSetVMsClientBeginPerformMaintenanceOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginPowerOffOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginPowerOff +// method. +type VirtualMachineScaleSetVMsClientBeginPowerOffOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // The parameter to request non-graceful VM shutdown. True value for this flag indicates non-graceful shutdown whereas false + // indicates otherwise. Default value for this flag is false if not specified + SkipShutdown *bool +} + +// VirtualMachineScaleSetVMsClientBeginRedeployOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginRedeploy +// method. +type VirtualMachineScaleSetVMsClientBeginRedeployOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginReimageAllOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginReimageAll +// method. +type VirtualMachineScaleSetVMsClientBeginReimageAllOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginReimageOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginReimage +// method. +type VirtualMachineScaleSetVMsClientBeginReimageOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // Parameters for the Reimaging Virtual machine in ScaleSet. + VMScaleSetVMReimageInput *VirtualMachineScaleSetVMReimageParameters +} + +// VirtualMachineScaleSetVMsClientBeginRestartOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginRestart +// method. +type VirtualMachineScaleSetVMsClientBeginRestartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginRunCommandOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginRunCommand +// method. +type VirtualMachineScaleSetVMsClientBeginRunCommandOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginStartOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginStart +// method. +type VirtualMachineScaleSetVMsClientBeginStartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginUpdate +// method. +type VirtualMachineScaleSetVMsClientBeginUpdateOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current resource. Specify the last-seen ETag value + // to prevent accidentally overwriting concurrent changes. + IfMatch *string + + // Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will result + // in error from server as they are not supported. + IfNoneMatch *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetVMsClientGetInstanceViewOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.GetInstanceView +// method. +type VirtualMachineScaleSetVMsClientGetInstanceViewOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetVMsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.Get +// method. +type VirtualMachineScaleSetVMsClientGetOptions struct { + // The expand expression to apply on the operation. 'InstanceView' will retrieve the instance view of the virtual machine. + // 'UserData' will retrieve the UserData of the virtual machine. + Expand *InstanceViewTypes +} + +// VirtualMachineScaleSetVMsClientListOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.NewListPager +// method. +type VirtualMachineScaleSetVMsClientListOptions struct { + // The expand expression to apply to the operation. Allowed values are 'instanceView'. + Expand *string + + // The filter to apply to the operation. Allowed values are 'startswith(instanceView/statuses/code, 'PowerState') eq true', + // 'properties/latestModelApplied eq true', 'properties/latestModelApplied eq + // false'. + Filter *string + + // The list parameters. Allowed values are 'instanceView', 'instanceView/statuses'. + Select *string +} + +// VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.RetrieveBootDiagnosticsData +// method. +type VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataOptions struct { + // Expiration duration in minutes for the SAS URIs with a value between 1 to 1440 minutes. Note: If not specified, SAS URIs + // will be generated with a default expiration duration of 120 minutes. + SasURIExpirationTimeInMinutes *int32 +} + +// VirtualMachineScaleSetVMsClientSimulateEvictionOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.SimulateEviction +// method. +type VirtualMachineScaleSetVMsClientSimulateEvictionOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetsClientBeginApproveRollingUpgradeOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginApproveRollingUpgrade +// method. +type VirtualMachineScaleSetsClientBeginApproveRollingUpgradeOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginCreateOrUpdate +// method. +type VirtualMachineScaleSetsClientBeginCreateOrUpdateOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current resource. Specify the last-seen ETag value + // to prevent accidentally overwriting concurrent changes. + IfMatch *string + + // Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will result + // in error from server as they are not supported. + IfNoneMatch *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetsClientBeginDeallocateOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginDeallocate +// method. +type VirtualMachineScaleSetsClientBeginDeallocateOptions struct { + // Optional parameter to hibernate a virtual machine from the VM scale set. (This feature is available for VMSS with Flexible + // OrchestrationMode only) + Hibernate *bool + + // Resumes the LRO from the provided token. + ResumeToken string + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginDeleteInstancesOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginDeleteInstances +// method. +type VirtualMachineScaleSetsClientBeginDeleteInstancesOptions struct { + // Optional parameter to force delete virtual machines from the VM scale set. (Feature in Preview) + ForceDeletion *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginDelete +// method. +type VirtualMachineScaleSetsClientBeginDeleteOptions struct { + // Optional parameter to force delete a VM scale set. (Feature in Preview) + ForceDeletion *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetsClientBeginPerformMaintenanceOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginPerformMaintenance +// method. +type VirtualMachineScaleSetsClientBeginPerformMaintenanceOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginPowerOffOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginPowerOff +// method. +type VirtualMachineScaleSetsClientBeginPowerOffOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // The parameter to request non-graceful VM shutdown. True value for this flag indicates non-graceful shutdown whereas false + // indicates otherwise. Default value for this flag is false if not specified + SkipShutdown *bool + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginReapplyOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginReapply +// method. +type VirtualMachineScaleSetsClientBeginReapplyOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetsClientBeginRedeployOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginRedeploy +// method. +type VirtualMachineScaleSetsClientBeginRedeployOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginReimageAllOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginReimageAll +// method. +type VirtualMachineScaleSetsClientBeginReimageAllOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginReimageOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginReimage +// method. +type VirtualMachineScaleSetsClientBeginReimageOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // Parameters for Reimaging VM ScaleSet. + VMScaleSetReimageInput *VirtualMachineScaleSetReimageParameters +} + +// VirtualMachineScaleSetsClientBeginRestartOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginRestart +// method. +type VirtualMachineScaleSetsClientBeginRestartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginSetOrchestrationServiceStateOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginSetOrchestrationServiceState +// method. +type VirtualMachineScaleSetsClientBeginSetOrchestrationServiceStateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetsClientBeginStartOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginStart +// method. +type VirtualMachineScaleSetsClientBeginStartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // A list of virtual machine instance IDs from the VM scale set. + VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs +} + +// VirtualMachineScaleSetsClientBeginUpdateInstancesOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginUpdateInstances +// method. +type VirtualMachineScaleSetsClientBeginUpdateInstancesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginUpdate +// method. +type VirtualMachineScaleSetsClientBeginUpdateOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current resource. Specify the last-seen ETag value + // to prevent accidentally overwriting concurrent changes. + IfMatch *string + + // Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will result + // in error from server as they are not supported. + IfNoneMatch *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachineScaleSetsClientConvertToSinglePlacementGroupOptions contains the optional parameters for the VirtualMachineScaleSetsClient.ConvertToSinglePlacementGroup +// method. +type VirtualMachineScaleSetsClientConvertToSinglePlacementGroupOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkOptions contains the optional parameters +// for the VirtualMachineScaleSetsClient.ForceRecoveryServiceFabricPlatformUpdateDomainWalk method. +type VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkOptions struct { + // The placement group id for which the manual recovery walk is requested. + PlacementGroupID *string + + // The zone in which the manual recovery walk is requested for cross zone virtual machine scale set + Zone *string +} + +// VirtualMachineScaleSetsClientGetInstanceViewOptions contains the optional parameters for the VirtualMachineScaleSetsClient.GetInstanceView +// method. +type VirtualMachineScaleSetsClientGetInstanceViewOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetsClientGetOSUpgradeHistoryOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewGetOSUpgradeHistoryPager +// method. +type VirtualMachineScaleSetsClientGetOSUpgradeHistoryOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetsClient.Get method. +type VirtualMachineScaleSetsClientGetOptions struct { + // The expand expression to apply on the operation. 'UserData' retrieves the UserData property of the VM scale set that was + // provided by the user during the VM scale set Create/Update operation + Expand *ExpandTypesForGetVMScaleSets +} + +// VirtualMachineScaleSetsClientListAllOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListAllPager +// method. +type VirtualMachineScaleSetsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetsClientListByLocationOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListByLocationPager +// method. +type VirtualMachineScaleSetsClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetsClientListOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListPager +// method. +type VirtualMachineScaleSetsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineScaleSetsClientListSKUsOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListSKUsPager +// method. +type VirtualMachineScaleSetsClientListSKUsOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachineSizesClientListOptions contains the optional parameters for the VirtualMachineSizesClient.NewListPager method. +type VirtualMachineSizesClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachinesClientBeginAssessPatchesOptions contains the optional parameters for the VirtualMachinesClient.BeginAssessPatches +// method. +type VirtualMachinesClientBeginAssessPatchesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginAttachDetachDataDisksOptions contains the optional parameters for the VirtualMachinesClient.BeginAttachDetachDataDisks +// method. +type VirtualMachinesClientBeginAttachDetachDataDisksOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginCaptureOptions contains the optional parameters for the VirtualMachinesClient.BeginCapture method. +type VirtualMachinesClientBeginCaptureOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginConvertToManagedDisksOptions contains the optional parameters for the VirtualMachinesClient.BeginConvertToManagedDisks +// method. +type VirtualMachinesClientBeginConvertToManagedDisksOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginCreateOrUpdate +// method. +type VirtualMachinesClientBeginCreateOrUpdateOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current resource. Specify the last-seen ETag value + // to prevent accidentally overwriting concurrent changes. + IfMatch *string + + // Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will result + // in error from server as they are not supported. + IfNoneMatch *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginDeallocateOptions contains the optional parameters for the VirtualMachinesClient.BeginDeallocate +// method. +type VirtualMachinesClientBeginDeallocateOptions struct { + // Optional parameter to hibernate a virtual machine. (Feature in Preview) + Hibernate *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginDeleteOptions contains the optional parameters for the VirtualMachinesClient.BeginDelete method. +type VirtualMachinesClientBeginDeleteOptions struct { + // Optional parameter to force delete virtual machines. + ForceDeletion *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginInstallPatchesOptions contains the optional parameters for the VirtualMachinesClient.BeginInstallPatches +// method. +type VirtualMachinesClientBeginInstallPatchesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginPerformMaintenanceOptions contains the optional parameters for the VirtualMachinesClient.BeginPerformMaintenance +// method. +type VirtualMachinesClientBeginPerformMaintenanceOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginPowerOffOptions contains the optional parameters for the VirtualMachinesClient.BeginPowerOff +// method. +type VirtualMachinesClientBeginPowerOffOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // The parameter to request non-graceful VM shutdown. True value for this flag indicates non-graceful shutdown whereas false + // indicates otherwise. Default value for this flag is false if not specified + SkipShutdown *bool +} + +// VirtualMachinesClientBeginReapplyOptions contains the optional parameters for the VirtualMachinesClient.BeginReapply method. +type VirtualMachinesClientBeginReapplyOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginRedeployOptions contains the optional parameters for the VirtualMachinesClient.BeginRedeploy +// method. +type VirtualMachinesClientBeginRedeployOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginReimageOptions contains the optional parameters for the VirtualMachinesClient.BeginReimage method. +type VirtualMachinesClientBeginReimageOptions struct { + // Parameters supplied to the Reimage Virtual Machine operation. + Parameters *VirtualMachineReimageParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginRestartOptions contains the optional parameters for the VirtualMachinesClient.BeginRestart method. +type VirtualMachinesClientBeginRestartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginRunCommandOptions contains the optional parameters for the VirtualMachinesClient.BeginRunCommand +// method. +type VirtualMachinesClientBeginRunCommandOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginStartOptions contains the optional parameters for the VirtualMachinesClient.BeginStart method. +type VirtualMachinesClientBeginStartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientBeginUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginUpdate method. +type VirtualMachinesClientBeginUpdateOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current resource. Specify the last-seen ETag value + // to prevent accidentally overwriting concurrent changes. + IfMatch *string + + // Set to '*' to allow a new record set to be created, but to prevent updating an existing record set. Other values will result + // in error from server as they are not supported. + IfNoneMatch *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualMachinesClientGeneralizeOptions contains the optional parameters for the VirtualMachinesClient.Generalize method. +type VirtualMachinesClientGeneralizeOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachinesClientGetOptions contains the optional parameters for the VirtualMachinesClient.Get method. +type VirtualMachinesClientGetOptions struct { + // The expand expression to apply on the operation. 'InstanceView' retrieves a snapshot of the runtime properties of the virtual + // machine that is managed by the platform and can change outside of control + // plane operations. 'UserData' retrieves the UserData property as part of the VM model view that was provided by the user + // during the VM Create/Update operation. + Expand *InstanceViewTypes +} + +// VirtualMachinesClientInstanceViewOptions contains the optional parameters for the VirtualMachinesClient.InstanceView method. +type VirtualMachinesClientInstanceViewOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachinesClientListAllOptions contains the optional parameters for the VirtualMachinesClient.NewListAllPager method. +type VirtualMachinesClientListAllOptions struct { + // The expand expression to apply on operation. 'instanceView' enables fetching run time status of all Virtual Machines, this + // can only be specified if a valid $filter option is specified + Expand *ExpandTypesForListVMs + + // The system query option to filter VMs returned in the response. Allowed value is 'virtualMachineScaleSet/id' eq + // /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmssName}' + Filter *string + + // statusOnly=true enables fetching run time status of all Virtual Machines in the subscription. + StatusOnly *string +} + +// VirtualMachinesClientListAvailableSizesOptions contains the optional parameters for the VirtualMachinesClient.NewListAvailableSizesPager +// method. +type VirtualMachinesClientListAvailableSizesOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachinesClientListByLocationOptions contains the optional parameters for the VirtualMachinesClient.NewListByLocationPager +// method. +type VirtualMachinesClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachinesClientListOptions contains the optional parameters for the VirtualMachinesClient.NewListPager method. +type VirtualMachinesClientListOptions struct { + // The expand expression to apply on operation. 'instanceView' enables fetching run time status of all Virtual Machines, this + // can only be specified if a valid $filter option is specified + Expand *ExpandTypeForListVMs + + // The system query option to filter VMs returned in the response. Allowed value is 'virtualMachineScaleSet/id' eq + // /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmssName}' + Filter *string +} + +// VirtualMachinesClientRetrieveBootDiagnosticsDataOptions contains the optional parameters for the VirtualMachinesClient.RetrieveBootDiagnosticsData +// method. +type VirtualMachinesClientRetrieveBootDiagnosticsDataOptions struct { + // Expiration duration in minutes for the SAS URIs with a value between 1 to 1440 minutes. Note: If not specified, SAS URIs + // will be generated with a default expiration duration of 120 minutes. + SasURIExpirationTimeInMinutes *int32 +} + +// VirtualMachinesClientSimulateEvictionOptions contains the optional parameters for the VirtualMachinesClient.SimulateEviction +// method. +type VirtualMachinesClientSimulateEvictionOptions struct { + // placeholder for future optional parameters +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/proximityplacementgroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/proximityplacementgroups_client.go new file mode 100644 index 000000000..947d83736 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/proximityplacementgroups_client.go @@ -0,0 +1,421 @@ +//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 armcompute + +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" +) + +// ProximityPlacementGroupsClient contains the methods for the ProximityPlacementGroups group. +// Don't use this type directly, use NewProximityPlacementGroupsClient() instead. +type ProximityPlacementGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewProximityPlacementGroupsClient creates a new instance of ProximityPlacementGroupsClient 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 NewProximityPlacementGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ProximityPlacementGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ProximityPlacementGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create or update a proximity placement group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - proximityPlacementGroupName - The name of the proximity placement group. +// - parameters - Parameters supplied to the Create Proximity Placement Group operation. +// - options - ProximityPlacementGroupsClientCreateOrUpdateOptions contains the optional parameters for the ProximityPlacementGroupsClient.CreateOrUpdate +// method. +func (client *ProximityPlacementGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroup, options *ProximityPlacementGroupsClientCreateOrUpdateOptions) (ProximityPlacementGroupsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ProximityPlacementGroupsClient.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, proximityPlacementGroupName, parameters, options) + if err != nil { + return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ProximityPlacementGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroup, options *ProximityPlacementGroupsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if proximityPlacementGroupName == "" { + return nil, errors.New("parameter proximityPlacementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName)) + 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-09-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 *ProximityPlacementGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientCreateOrUpdateResponse, error) { + result := ProximityPlacementGroupsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroup); err != nil { + return ProximityPlacementGroupsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a proximity placement group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - proximityPlacementGroupName - The name of the proximity placement group. +// - options - ProximityPlacementGroupsClientDeleteOptions contains the optional parameters for the ProximityPlacementGroupsClient.Delete +// method. +func (client *ProximityPlacementGroupsClient) Delete(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientDeleteOptions) (ProximityPlacementGroupsClientDeleteResponse, error) { + var err error + const operationName = "ProximityPlacementGroupsClient.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, proximityPlacementGroupName, options) + if err != nil { + return ProximityPlacementGroupsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProximityPlacementGroupsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProximityPlacementGroupsClientDeleteResponse{}, err + } + return ProximityPlacementGroupsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ProximityPlacementGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if proximityPlacementGroupName == "" { + return nil, errors.New("parameter proximityPlacementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about a proximity placement group . +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - proximityPlacementGroupName - The name of the proximity placement group. +// - options - ProximityPlacementGroupsClientGetOptions contains the optional parameters for the ProximityPlacementGroupsClient.Get +// method. +func (client *ProximityPlacementGroupsClient) Get(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientGetOptions) (ProximityPlacementGroupsClientGetResponse, error) { + var err error + const operationName = "ProximityPlacementGroupsClient.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, proximityPlacementGroupName, options) + if err != nil { + return ProximityPlacementGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProximityPlacementGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProximityPlacementGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ProximityPlacementGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, options *ProximityPlacementGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if proximityPlacementGroupName == "" { + return nil, errors.New("parameter proximityPlacementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName)) + 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.IncludeColocationStatus != nil { + reqQP.Set("includeColocationStatus", *options.IncludeColocationStatus) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ProximityPlacementGroupsClient) getHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientGetResponse, error) { + result := ProximityPlacementGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroup); err != nil { + return ProximityPlacementGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all proximity placement groups in a resource group. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - ProximityPlacementGroupsClientListByResourceGroupOptions contains the optional parameters for the ProximityPlacementGroupsClient.NewListByResourceGroupPager +// method. +func (client *ProximityPlacementGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *ProximityPlacementGroupsClientListByResourceGroupOptions) *runtime.Pager[ProximityPlacementGroupsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ProximityPlacementGroupsClientListByResourceGroupResponse]{ + More: func(page ProximityPlacementGroupsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ProximityPlacementGroupsClientListByResourceGroupResponse) (ProximityPlacementGroupsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProximityPlacementGroupsClient.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 ProximityPlacementGroupsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ProximityPlacementGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ProximityPlacementGroupsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ProximityPlacementGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientListByResourceGroupResponse, error) { + result := ProximityPlacementGroupsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroupListResult); err != nil { + return ProximityPlacementGroupsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists all proximity placement groups in a subscription. +// +// Generated from API version 2023-09-01 +// - options - ProximityPlacementGroupsClientListBySubscriptionOptions contains the optional parameters for the ProximityPlacementGroupsClient.NewListBySubscriptionPager +// method. +func (client *ProximityPlacementGroupsClient) NewListBySubscriptionPager(options *ProximityPlacementGroupsClientListBySubscriptionOptions) *runtime.Pager[ProximityPlacementGroupsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ProximityPlacementGroupsClientListBySubscriptionResponse]{ + More: func(page ProximityPlacementGroupsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ProximityPlacementGroupsClientListBySubscriptionResponse) (ProximityPlacementGroupsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProximityPlacementGroupsClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ProximityPlacementGroupsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ProximityPlacementGroupsClient) listBySubscriptionCreateRequest(ctx context.Context, options *ProximityPlacementGroupsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/proximityPlacementGroups" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ProximityPlacementGroupsClient) listBySubscriptionHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientListBySubscriptionResponse, error) { + result := ProximityPlacementGroupsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroupListResult); err != nil { + return ProximityPlacementGroupsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Update a proximity placement group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - proximityPlacementGroupName - The name of the proximity placement group. +// - parameters - Parameters supplied to the Update Proximity Placement Group operation. +// - options - ProximityPlacementGroupsClientUpdateOptions contains the optional parameters for the ProximityPlacementGroupsClient.Update +// method. +func (client *ProximityPlacementGroupsClient) Update(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroupUpdate, options *ProximityPlacementGroupsClientUpdateOptions) (ProximityPlacementGroupsClientUpdateResponse, error) { + var err error + const operationName = "ProximityPlacementGroupsClient.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, proximityPlacementGroupName, parameters, options) + if err != nil { + return ProximityPlacementGroupsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProximityPlacementGroupsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProximityPlacementGroupsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *ProximityPlacementGroupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroupUpdate, options *ProximityPlacementGroupsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if proximityPlacementGroupName == "" { + return nil, errors.New("parameter proximityPlacementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{proximityPlacementGroupName}", url.PathEscape(proximityPlacementGroupName)) + 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-09-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 *ProximityPlacementGroupsClient) updateHandleResponse(resp *http.Response) (ProximityPlacementGroupsClientUpdateResponse, error) { + result := ProximityPlacementGroupsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProximityPlacementGroup); err != nil { + return ProximityPlacementGroupsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/resourceskus_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/resourceskus_client.go new file mode 100644 index 000000000..e0dd1afa4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/resourceskus_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 armcompute + +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" +) + +// ResourceSKUsClient contains the methods for the ResourceSKUs group. +// Don't use this type directly, use NewResourceSKUsClient() instead. +type ResourceSKUsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewResourceSKUsClient creates a new instance of ResourceSKUsClient 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 NewResourceSKUsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResourceSKUsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ResourceSKUsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets the list of Microsoft.Compute SKUs available for your Subscription. +// +// Generated from API version 2021-07-01 +// - options - ResourceSKUsClientListOptions contains the optional parameters for the ResourceSKUsClient.NewListPager method. +func (client *ResourceSKUsClient) NewListPager(options *ResourceSKUsClientListOptions) *runtime.Pager[ResourceSKUsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ResourceSKUsClientListResponse]{ + More: func(page ResourceSKUsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ResourceSKUsClientListResponse) (ResourceSKUsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ResourceSKUsClient.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 ResourceSKUsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ResourceSKUsClient) listCreateRequest(ctx context.Context, options *ResourceSKUsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/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", "2021-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.IncludeExtendedLocations != nil { + reqQP.Set("includeExtendedLocations", *options.IncludeExtendedLocations) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ResourceSKUsClient) listHandleResponse(resp *http.Response) (ResourceSKUsClientListResponse, error) { + result := ResourceSKUsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceSKUsResult); err != nil { + return ResourceSKUsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/response_types.go new file mode 100644 index 000000000..db4fc2bd3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/response_types.go @@ -0,0 +1,1673 @@ +//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 armcompute + +import "io" + +// AvailabilitySetsClientCreateOrUpdateResponse contains the response from method AvailabilitySetsClient.CreateOrUpdate. +type AvailabilitySetsClientCreateOrUpdateResponse struct { + // Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified + // in the same availability set are allocated to different nodes to maximize availability. For more information about availability + // sets, see [Availability sets overview](https://docs.microsoft.com/azure/virtual-machines/availability-set-overview). For + // more information on Azure planned maintenance, see [Maintenance and updates for Virtual Machines in Azure](https://docs.microsoft.com/azure/virtual-machines/maintenance-and-updates). + // Currently, a VM can only be added to an availability set at creation time. An existing VM cannot be added to an availability + // set. + AvailabilitySet +} + +// AvailabilitySetsClientDeleteResponse contains the response from method AvailabilitySetsClient.Delete. +type AvailabilitySetsClientDeleteResponse struct { + // placeholder for future response values +} + +// AvailabilitySetsClientGetResponse contains the response from method AvailabilitySetsClient.Get. +type AvailabilitySetsClientGetResponse struct { + // Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified + // in the same availability set are allocated to different nodes to maximize availability. For more information about availability + // sets, see [Availability sets overview](https://docs.microsoft.com/azure/virtual-machines/availability-set-overview). For + // more information on Azure planned maintenance, see [Maintenance and updates for Virtual Machines in Azure](https://docs.microsoft.com/azure/virtual-machines/maintenance-and-updates). + // Currently, a VM can only be added to an availability set at creation time. An existing VM cannot be added to an availability + // set. + AvailabilitySet +} + +// AvailabilitySetsClientListAvailableSizesResponse contains the response from method AvailabilitySetsClient.NewListAvailableSizesPager. +type AvailabilitySetsClientListAvailableSizesResponse struct { + // The List Virtual Machine operation response. + VirtualMachineSizeListResult +} + +// AvailabilitySetsClientListBySubscriptionResponse contains the response from method AvailabilitySetsClient.NewListBySubscriptionPager. +type AvailabilitySetsClientListBySubscriptionResponse struct { + // The List Availability Set operation response. + AvailabilitySetListResult +} + +// AvailabilitySetsClientListResponse contains the response from method AvailabilitySetsClient.NewListPager. +type AvailabilitySetsClientListResponse struct { + // The List Availability Set operation response. + AvailabilitySetListResult +} + +// AvailabilitySetsClientUpdateResponse contains the response from method AvailabilitySetsClient.Update. +type AvailabilitySetsClientUpdateResponse struct { + // Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified + // in the same availability set are allocated to different nodes to maximize availability. For more information about availability + // sets, see [Availability sets overview](https://docs.microsoft.com/azure/virtual-machines/availability-set-overview). For + // more information on Azure planned maintenance, see [Maintenance and updates for Virtual Machines in Azure](https://docs.microsoft.com/azure/virtual-machines/maintenance-and-updates). + // Currently, a VM can only be added to an availability set at creation time. An existing VM cannot be added to an availability + // set. + AvailabilitySet +} + +// CapacityReservationGroupsClientCreateOrUpdateResponse contains the response from method CapacityReservationGroupsClient.CreateOrUpdate. +type CapacityReservationGroupsClientCreateOrUpdateResponse struct { + // Specifies information about the capacity reservation group that the capacity reservations should be assigned to. Currently, + // a capacity reservation can only be added to a capacity reservation group at creation time. An existing capacity reservation + // cannot be added or moved to another capacity reservation group. + CapacityReservationGroup +} + +// CapacityReservationGroupsClientDeleteResponse contains the response from method CapacityReservationGroupsClient.Delete. +type CapacityReservationGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// CapacityReservationGroupsClientGetResponse contains the response from method CapacityReservationGroupsClient.Get. +type CapacityReservationGroupsClientGetResponse struct { + // Specifies information about the capacity reservation group that the capacity reservations should be assigned to. Currently, + // a capacity reservation can only be added to a capacity reservation group at creation time. An existing capacity reservation + // cannot be added or moved to another capacity reservation group. + CapacityReservationGroup +} + +// CapacityReservationGroupsClientListByResourceGroupResponse contains the response from method CapacityReservationGroupsClient.NewListByResourceGroupPager. +type CapacityReservationGroupsClientListByResourceGroupResponse struct { + // The List capacity reservation group with resource group response. + CapacityReservationGroupListResult +} + +// CapacityReservationGroupsClientListBySubscriptionResponse contains the response from method CapacityReservationGroupsClient.NewListBySubscriptionPager. +type CapacityReservationGroupsClientListBySubscriptionResponse struct { + // The List capacity reservation group with resource group response. + CapacityReservationGroupListResult +} + +// CapacityReservationGroupsClientUpdateResponse contains the response from method CapacityReservationGroupsClient.Update. +type CapacityReservationGroupsClientUpdateResponse struct { + // Specifies information about the capacity reservation group that the capacity reservations should be assigned to. Currently, + // a capacity reservation can only be added to a capacity reservation group at creation time. An existing capacity reservation + // cannot be added or moved to another capacity reservation group. + CapacityReservationGroup +} + +// CapacityReservationsClientCreateOrUpdateResponse contains the response from method CapacityReservationsClient.BeginCreateOrUpdate. +type CapacityReservationsClientCreateOrUpdateResponse struct { + // Specifies information about the capacity reservation. + CapacityReservation +} + +// CapacityReservationsClientDeleteResponse contains the response from method CapacityReservationsClient.BeginDelete. +type CapacityReservationsClientDeleteResponse struct { + // placeholder for future response values +} + +// CapacityReservationsClientGetResponse contains the response from method CapacityReservationsClient.Get. +type CapacityReservationsClientGetResponse struct { + // Specifies information about the capacity reservation. + CapacityReservation +} + +// CapacityReservationsClientListByCapacityReservationGroupResponse contains the response from method CapacityReservationsClient.NewListByCapacityReservationGroupPager. +type CapacityReservationsClientListByCapacityReservationGroupResponse struct { + // The list capacity reservation operation response. + CapacityReservationListResult +} + +// CapacityReservationsClientUpdateResponse contains the response from method CapacityReservationsClient.BeginUpdate. +type CapacityReservationsClientUpdateResponse struct { + // Specifies information about the capacity reservation. + CapacityReservation +} + +// CloudServiceOperatingSystemsClientGetOSFamilyResponse contains the response from method CloudServiceOperatingSystemsClient.GetOSFamily. +type CloudServiceOperatingSystemsClientGetOSFamilyResponse struct { + // Describes a cloud service OS family. + OSFamily +} + +// CloudServiceOperatingSystemsClientGetOSVersionResponse contains the response from method CloudServiceOperatingSystemsClient.GetOSVersion. +type CloudServiceOperatingSystemsClientGetOSVersionResponse struct { + // Describes a cloud service OS version. + OSVersion +} + +// CloudServiceOperatingSystemsClientListOSFamiliesResponse contains the response from method CloudServiceOperatingSystemsClient.NewListOSFamiliesPager. +type CloudServiceOperatingSystemsClientListOSFamiliesResponse struct { + // The list operation result. + OSFamilyListResult +} + +// CloudServiceOperatingSystemsClientListOSVersionsResponse contains the response from method CloudServiceOperatingSystemsClient.NewListOSVersionsPager. +type CloudServiceOperatingSystemsClientListOSVersionsResponse struct { + // The list operation result. + OSVersionListResult +} + +// CloudServiceRoleInstancesClientDeleteResponse contains the response from method CloudServiceRoleInstancesClient.BeginDelete. +type CloudServiceRoleInstancesClientDeleteResponse struct { + // placeholder for future response values +} + +// CloudServiceRoleInstancesClientGetInstanceViewResponse contains the response from method CloudServiceRoleInstancesClient.GetInstanceView. +type CloudServiceRoleInstancesClientGetInstanceViewResponse struct { + // The instance view of the role instance. + RoleInstanceView +} + +// CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse contains the response from method CloudServiceRoleInstancesClient.GetRemoteDesktopFile. +type CloudServiceRoleInstancesClientGetRemoteDesktopFileResponse struct { + // Body contains the streaming response. + Body io.ReadCloser +} + +// CloudServiceRoleInstancesClientGetResponse contains the response from method CloudServiceRoleInstancesClient.Get. +type CloudServiceRoleInstancesClientGetResponse struct { + // Describes the cloud service role instance. + RoleInstance +} + +// CloudServiceRoleInstancesClientListResponse contains the response from method CloudServiceRoleInstancesClient.NewListPager. +type CloudServiceRoleInstancesClientListResponse struct { + // The list operation result. + RoleInstanceListResult +} + +// CloudServiceRoleInstancesClientRebuildResponse contains the response from method CloudServiceRoleInstancesClient.BeginRebuild. +type CloudServiceRoleInstancesClientRebuildResponse struct { + // placeholder for future response values +} + +// CloudServiceRoleInstancesClientReimageResponse contains the response from method CloudServiceRoleInstancesClient.BeginReimage. +type CloudServiceRoleInstancesClientReimageResponse struct { + // placeholder for future response values +} + +// CloudServiceRoleInstancesClientRestartResponse contains the response from method CloudServiceRoleInstancesClient.BeginRestart. +type CloudServiceRoleInstancesClientRestartResponse struct { + // placeholder for future response values +} + +// CloudServiceRolesClientGetResponse contains the response from method CloudServiceRolesClient.Get. +type CloudServiceRolesClientGetResponse struct { + // Describes a role of the cloud service. + CloudServiceRole +} + +// CloudServiceRolesClientListResponse contains the response from method CloudServiceRolesClient.NewListPager. +type CloudServiceRolesClientListResponse struct { + // The list operation result. + CloudServiceRoleListResult +} + +// CloudServicesClientCreateOrUpdateResponse contains the response from method CloudServicesClient.BeginCreateOrUpdate. +type CloudServicesClientCreateOrUpdateResponse struct { + // Describes the cloud service. + CloudService +} + +// CloudServicesClientDeleteInstancesResponse contains the response from method CloudServicesClient.BeginDeleteInstances. +type CloudServicesClientDeleteInstancesResponse struct { + // placeholder for future response values +} + +// CloudServicesClientDeleteResponse contains the response from method CloudServicesClient.BeginDelete. +type CloudServicesClientDeleteResponse struct { + // placeholder for future response values +} + +// CloudServicesClientGetInstanceViewResponse contains the response from method CloudServicesClient.GetInstanceView. +type CloudServicesClientGetInstanceViewResponse struct { + // InstanceView of CloudService as a whole + CloudServiceInstanceView +} + +// CloudServicesClientGetResponse contains the response from method CloudServicesClient.Get. +type CloudServicesClientGetResponse struct { + // Describes the cloud service. + CloudService +} + +// CloudServicesClientListAllResponse contains the response from method CloudServicesClient.NewListAllPager. +type CloudServicesClientListAllResponse struct { + // The list operation result. + CloudServiceListResult +} + +// CloudServicesClientListResponse contains the response from method CloudServicesClient.NewListPager. +type CloudServicesClientListResponse struct { + // The list operation result. + CloudServiceListResult +} + +// CloudServicesClientPowerOffResponse contains the response from method CloudServicesClient.BeginPowerOff. +type CloudServicesClientPowerOffResponse struct { + // placeholder for future response values +} + +// CloudServicesClientRebuildResponse contains the response from method CloudServicesClient.BeginRebuild. +type CloudServicesClientRebuildResponse struct { + // placeholder for future response values +} + +// CloudServicesClientReimageResponse contains the response from method CloudServicesClient.BeginReimage. +type CloudServicesClientReimageResponse struct { + // placeholder for future response values +} + +// CloudServicesClientRestartResponse contains the response from method CloudServicesClient.BeginRestart. +type CloudServicesClientRestartResponse struct { + // placeholder for future response values +} + +// CloudServicesClientStartResponse contains the response from method CloudServicesClient.BeginStart. +type CloudServicesClientStartResponse struct { + // placeholder for future response values +} + +// CloudServicesClientUpdateResponse contains the response from method CloudServicesClient.BeginUpdate. +type CloudServicesClientUpdateResponse struct { + // Describes the cloud service. + CloudService +} + +// CloudServicesUpdateDomainClientGetUpdateDomainResponse contains the response from method CloudServicesUpdateDomainClient.GetUpdateDomain. +type CloudServicesUpdateDomainClientGetUpdateDomainResponse struct { + // Defines an update domain for the cloud service. + UpdateDomain +} + +// CloudServicesUpdateDomainClientListUpdateDomainsResponse contains the response from method CloudServicesUpdateDomainClient.NewListUpdateDomainsPager. +type CloudServicesUpdateDomainClientListUpdateDomainsResponse struct { + // The list operation result. + UpdateDomainListResult +} + +// CloudServicesUpdateDomainClientWalkUpdateDomainResponse contains the response from method CloudServicesUpdateDomainClient.BeginWalkUpdateDomain. +type CloudServicesUpdateDomainClientWalkUpdateDomainResponse struct { + // placeholder for future response values +} + +// CommunityGalleriesClientGetResponse contains the response from method CommunityGalleriesClient.Get. +type CommunityGalleriesClientGetResponse struct { + // Specifies information about the Community Gallery that you want to create or update. + CommunityGallery +} + +// CommunityGalleryImageVersionsClientGetResponse contains the response from method CommunityGalleryImageVersionsClient.Get. +type CommunityGalleryImageVersionsClientGetResponse struct { + // Specifies information about the gallery image version that you want to create or update. + CommunityGalleryImageVersion +} + +// CommunityGalleryImageVersionsClientListResponse contains the response from method CommunityGalleryImageVersionsClient.NewListPager. +type CommunityGalleryImageVersionsClientListResponse struct { + // The List Community Gallery Image versions operation response. + CommunityGalleryImageVersionList +} + +// CommunityGalleryImagesClientGetResponse contains the response from method CommunityGalleryImagesClient.Get. +type CommunityGalleryImagesClientGetResponse struct { + // Specifies information about the gallery image definition that you want to create or update. + CommunityGalleryImage +} + +// CommunityGalleryImagesClientListResponse contains the response from method CommunityGalleryImagesClient.NewListPager. +type CommunityGalleryImagesClientListResponse struct { + // The List Community Gallery Images operation response. + CommunityGalleryImageList +} + +// DedicatedHostGroupsClientCreateOrUpdateResponse contains the response from method DedicatedHostGroupsClient.CreateOrUpdate. +type DedicatedHostGroupsClientCreateOrUpdateResponse struct { + // Specifies information about the dedicated host group that the dedicated hosts should be assigned to. Currently, a dedicated + // host can only be added to a dedicated host group at creation time. An existing dedicated host cannot be added to another + // dedicated host group. + DedicatedHostGroup +} + +// DedicatedHostGroupsClientDeleteResponse contains the response from method DedicatedHostGroupsClient.Delete. +type DedicatedHostGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// DedicatedHostGroupsClientGetResponse contains the response from method DedicatedHostGroupsClient.Get. +type DedicatedHostGroupsClientGetResponse struct { + // Specifies information about the dedicated host group that the dedicated hosts should be assigned to. Currently, a dedicated + // host can only be added to a dedicated host group at creation time. An existing dedicated host cannot be added to another + // dedicated host group. + DedicatedHostGroup +} + +// DedicatedHostGroupsClientListByResourceGroupResponse contains the response from method DedicatedHostGroupsClient.NewListByResourceGroupPager. +type DedicatedHostGroupsClientListByResourceGroupResponse struct { + // The List Dedicated Host Group with resource group response. + DedicatedHostGroupListResult +} + +// DedicatedHostGroupsClientListBySubscriptionResponse contains the response from method DedicatedHostGroupsClient.NewListBySubscriptionPager. +type DedicatedHostGroupsClientListBySubscriptionResponse struct { + // The List Dedicated Host Group with resource group response. + DedicatedHostGroupListResult +} + +// DedicatedHostGroupsClientUpdateResponse contains the response from method DedicatedHostGroupsClient.Update. +type DedicatedHostGroupsClientUpdateResponse struct { + // Specifies information about the dedicated host group that the dedicated hosts should be assigned to. Currently, a dedicated + // host can only be added to a dedicated host group at creation time. An existing dedicated host cannot be added to another + // dedicated host group. + DedicatedHostGroup +} + +// DedicatedHostsClientCreateOrUpdateResponse contains the response from method DedicatedHostsClient.BeginCreateOrUpdate. +type DedicatedHostsClientCreateOrUpdateResponse struct { + // Specifies information about the Dedicated host. + DedicatedHost +} + +// DedicatedHostsClientDeleteResponse contains the response from method DedicatedHostsClient.BeginDelete. +type DedicatedHostsClientDeleteResponse struct { + // placeholder for future response values +} + +// DedicatedHostsClientGetResponse contains the response from method DedicatedHostsClient.Get. +type DedicatedHostsClientGetResponse struct { + // Specifies information about the Dedicated host. + DedicatedHost +} + +// DedicatedHostsClientListAvailableSizesResponse contains the response from method DedicatedHostsClient.NewListAvailableSizesPager. +type DedicatedHostsClientListAvailableSizesResponse struct { + // The List Dedicated Host sizes operation response. + DedicatedHostSizeListResult +} + +// DedicatedHostsClientListByHostGroupResponse contains the response from method DedicatedHostsClient.NewListByHostGroupPager. +type DedicatedHostsClientListByHostGroupResponse struct { + // The list dedicated host operation response. + DedicatedHostListResult +} + +// DedicatedHostsClientRedeployResponse contains the response from method DedicatedHostsClient.BeginRedeploy. +type DedicatedHostsClientRedeployResponse struct { + // placeholder for future response values +} + +// DedicatedHostsClientRestartResponse contains the response from method DedicatedHostsClient.BeginRestart. +type DedicatedHostsClientRestartResponse struct { + // placeholder for future response values +} + +// DedicatedHostsClientUpdateResponse contains the response from method DedicatedHostsClient.BeginUpdate. +type DedicatedHostsClientUpdateResponse struct { + // Specifies information about the Dedicated host. + DedicatedHost +} + +// DiskAccessesClientCreateOrUpdateResponse contains the response from method DiskAccessesClient.BeginCreateOrUpdate. +type DiskAccessesClientCreateOrUpdateResponse struct { + // disk access resource. + DiskAccess +} + +// DiskAccessesClientDeleteAPrivateEndpointConnectionResponse contains the response from method DiskAccessesClient.BeginDeleteAPrivateEndpointConnection. +type DiskAccessesClientDeleteAPrivateEndpointConnectionResponse struct { + // placeholder for future response values +} + +// DiskAccessesClientDeleteResponse contains the response from method DiskAccessesClient.BeginDelete. +type DiskAccessesClientDeleteResponse struct { + // placeholder for future response values +} + +// DiskAccessesClientGetAPrivateEndpointConnectionResponse contains the response from method DiskAccessesClient.GetAPrivateEndpointConnection. +type DiskAccessesClientGetAPrivateEndpointConnectionResponse struct { + // The Private Endpoint Connection resource. + PrivateEndpointConnection +} + +// DiskAccessesClientGetPrivateLinkResourcesResponse contains the response from method DiskAccessesClient.GetPrivateLinkResources. +type DiskAccessesClientGetPrivateLinkResourcesResponse struct { + // A list of private link resources + PrivateLinkResourceListResult +} + +// DiskAccessesClientGetResponse contains the response from method DiskAccessesClient.Get. +type DiskAccessesClientGetResponse struct { + // disk access resource. + DiskAccess +} + +// DiskAccessesClientListByResourceGroupResponse contains the response from method DiskAccessesClient.NewListByResourceGroupPager. +type DiskAccessesClientListByResourceGroupResponse struct { + // The List disk access operation response. + DiskAccessList +} + +// DiskAccessesClientListPrivateEndpointConnectionsResponse contains the response from method DiskAccessesClient.NewListPrivateEndpointConnectionsPager. +type DiskAccessesClientListPrivateEndpointConnectionsResponse struct { + // A list of private link resources + PrivateEndpointConnectionListResult +} + +// DiskAccessesClientListResponse contains the response from method DiskAccessesClient.NewListPager. +type DiskAccessesClientListResponse struct { + // The List disk access operation response. + DiskAccessList +} + +// DiskAccessesClientUpdateAPrivateEndpointConnectionResponse contains the response from method DiskAccessesClient.BeginUpdateAPrivateEndpointConnection. +type DiskAccessesClientUpdateAPrivateEndpointConnectionResponse struct { + // The Private Endpoint Connection resource. + PrivateEndpointConnection +} + +// DiskAccessesClientUpdateResponse contains the response from method DiskAccessesClient.BeginUpdate. +type DiskAccessesClientUpdateResponse struct { + // disk access resource. + DiskAccess +} + +// DiskEncryptionSetsClientCreateOrUpdateResponse contains the response from method DiskEncryptionSetsClient.BeginCreateOrUpdate. +type DiskEncryptionSetsClientCreateOrUpdateResponse struct { + // disk encryption set resource. + DiskEncryptionSet +} + +// DiskEncryptionSetsClientDeleteResponse contains the response from method DiskEncryptionSetsClient.BeginDelete. +type DiskEncryptionSetsClientDeleteResponse struct { + // placeholder for future response values +} + +// DiskEncryptionSetsClientGetResponse contains the response from method DiskEncryptionSetsClient.Get. +type DiskEncryptionSetsClientGetResponse struct { + // disk encryption set resource. + DiskEncryptionSet +} + +// DiskEncryptionSetsClientListAssociatedResourcesResponse contains the response from method DiskEncryptionSetsClient.NewListAssociatedResourcesPager. +type DiskEncryptionSetsClientListAssociatedResourcesResponse struct { + // The List resources which are encrypted with the disk encryption set. + ResourceURIList +} + +// DiskEncryptionSetsClientListByResourceGroupResponse contains the response from method DiskEncryptionSetsClient.NewListByResourceGroupPager. +type DiskEncryptionSetsClientListByResourceGroupResponse struct { + // The List disk encryption set operation response. + DiskEncryptionSetList +} + +// DiskEncryptionSetsClientListResponse contains the response from method DiskEncryptionSetsClient.NewListPager. +type DiskEncryptionSetsClientListResponse struct { + // The List disk encryption set operation response. + DiskEncryptionSetList +} + +// DiskEncryptionSetsClientUpdateResponse contains the response from method DiskEncryptionSetsClient.BeginUpdate. +type DiskEncryptionSetsClientUpdateResponse struct { + // disk encryption set resource. + DiskEncryptionSet +} + +// DiskRestorePointClientGetResponse contains the response from method DiskRestorePointClient.Get. +type DiskRestorePointClientGetResponse struct { + // Properties of disk restore point + DiskRestorePoint +} + +// DiskRestorePointClientGrantAccessResponse contains the response from method DiskRestorePointClient.BeginGrantAccess. +type DiskRestorePointClientGrantAccessResponse struct { + // A disk access SAS uri. + AccessURI +} + +// DiskRestorePointClientListByRestorePointResponse contains the response from method DiskRestorePointClient.NewListByRestorePointPager. +type DiskRestorePointClientListByRestorePointResponse struct { + // The List Disk Restore Points operation response. + DiskRestorePointList +} + +// DiskRestorePointClientRevokeAccessResponse contains the response from method DiskRestorePointClient.BeginRevokeAccess. +type DiskRestorePointClientRevokeAccessResponse struct { + // placeholder for future response values +} + +// DisksClientCreateOrUpdateResponse contains the response from method DisksClient.BeginCreateOrUpdate. +type DisksClientCreateOrUpdateResponse struct { + // Disk resource. + Disk +} + +// DisksClientDeleteResponse contains the response from method DisksClient.BeginDelete. +type DisksClientDeleteResponse struct { + // placeholder for future response values +} + +// DisksClientGetResponse contains the response from method DisksClient.Get. +type DisksClientGetResponse struct { + // Disk resource. + Disk +} + +// DisksClientGrantAccessResponse contains the response from method DisksClient.BeginGrantAccess. +type DisksClientGrantAccessResponse struct { + // A disk access SAS uri. + AccessURI +} + +// DisksClientListByResourceGroupResponse contains the response from method DisksClient.NewListByResourceGroupPager. +type DisksClientListByResourceGroupResponse struct { + // The List Disks operation response. + DiskList +} + +// DisksClientListResponse contains the response from method DisksClient.NewListPager. +type DisksClientListResponse struct { + // The List Disks operation response. + DiskList +} + +// DisksClientRevokeAccessResponse contains the response from method DisksClient.BeginRevokeAccess. +type DisksClientRevokeAccessResponse struct { + // placeholder for future response values +} + +// DisksClientUpdateResponse contains the response from method DisksClient.BeginUpdate. +type DisksClientUpdateResponse struct { + // Disk resource. + Disk +} + +// GalleriesClientCreateOrUpdateResponse contains the response from method GalleriesClient.BeginCreateOrUpdate. +type GalleriesClientCreateOrUpdateResponse struct { + // Specifies information about the Shared Image Gallery that you want to create or update. + Gallery +} + +// GalleriesClientDeleteResponse contains the response from method GalleriesClient.BeginDelete. +type GalleriesClientDeleteResponse struct { + // placeholder for future response values +} + +// GalleriesClientGetResponse contains the response from method GalleriesClient.Get. +type GalleriesClientGetResponse struct { + // Specifies information about the Shared Image Gallery that you want to create or update. + Gallery +} + +// GalleriesClientListByResourceGroupResponse contains the response from method GalleriesClient.NewListByResourceGroupPager. +type GalleriesClientListByResourceGroupResponse struct { + // The List Galleries operation response. + GalleryList +} + +// GalleriesClientListResponse contains the response from method GalleriesClient.NewListPager. +type GalleriesClientListResponse struct { + // The List Galleries operation response. + GalleryList +} + +// GalleriesClientUpdateResponse contains the response from method GalleriesClient.BeginUpdate. +type GalleriesClientUpdateResponse struct { + // Specifies information about the Shared Image Gallery that you want to create or update. + Gallery +} + +// GalleryApplicationVersionsClientCreateOrUpdateResponse contains the response from method GalleryApplicationVersionsClient.BeginCreateOrUpdate. +type GalleryApplicationVersionsClientCreateOrUpdateResponse struct { + // Specifies information about the gallery Application Version that you want to create or update. + GalleryApplicationVersion +} + +// GalleryApplicationVersionsClientDeleteResponse contains the response from method GalleryApplicationVersionsClient.BeginDelete. +type GalleryApplicationVersionsClientDeleteResponse struct { + // placeholder for future response values +} + +// GalleryApplicationVersionsClientGetResponse contains the response from method GalleryApplicationVersionsClient.Get. +type GalleryApplicationVersionsClientGetResponse struct { + // Specifies information about the gallery Application Version that you want to create or update. + GalleryApplicationVersion +} + +// GalleryApplicationVersionsClientListByGalleryApplicationResponse contains the response from method GalleryApplicationVersionsClient.NewListByGalleryApplicationPager. +type GalleryApplicationVersionsClientListByGalleryApplicationResponse struct { + // The List Gallery Application version operation response. + GalleryApplicationVersionList +} + +// GalleryApplicationVersionsClientUpdateResponse contains the response from method GalleryApplicationVersionsClient.BeginUpdate. +type GalleryApplicationVersionsClientUpdateResponse struct { + // Specifies information about the gallery Application Version that you want to create or update. + GalleryApplicationVersion +} + +// GalleryApplicationsClientCreateOrUpdateResponse contains the response from method GalleryApplicationsClient.BeginCreateOrUpdate. +type GalleryApplicationsClientCreateOrUpdateResponse struct { + // Specifies information about the gallery Application Definition that you want to create or update. + GalleryApplication +} + +// GalleryApplicationsClientDeleteResponse contains the response from method GalleryApplicationsClient.BeginDelete. +type GalleryApplicationsClientDeleteResponse struct { + // placeholder for future response values +} + +// GalleryApplicationsClientGetResponse contains the response from method GalleryApplicationsClient.Get. +type GalleryApplicationsClientGetResponse struct { + // Specifies information about the gallery Application Definition that you want to create or update. + GalleryApplication +} + +// GalleryApplicationsClientListByGalleryResponse contains the response from method GalleryApplicationsClient.NewListByGalleryPager. +type GalleryApplicationsClientListByGalleryResponse struct { + // The List Gallery Applications operation response. + GalleryApplicationList +} + +// GalleryApplicationsClientUpdateResponse contains the response from method GalleryApplicationsClient.BeginUpdate. +type GalleryApplicationsClientUpdateResponse struct { + // Specifies information about the gallery Application Definition that you want to create or update. + GalleryApplication +} + +// GalleryImageVersionsClientCreateOrUpdateResponse contains the response from method GalleryImageVersionsClient.BeginCreateOrUpdate. +type GalleryImageVersionsClientCreateOrUpdateResponse struct { + // Specifies information about the gallery image version that you want to create or update. + GalleryImageVersion +} + +// GalleryImageVersionsClientDeleteResponse contains the response from method GalleryImageVersionsClient.BeginDelete. +type GalleryImageVersionsClientDeleteResponse struct { + // placeholder for future response values +} + +// GalleryImageVersionsClientGetResponse contains the response from method GalleryImageVersionsClient.Get. +type GalleryImageVersionsClientGetResponse struct { + // Specifies information about the gallery image version that you want to create or update. + GalleryImageVersion +} + +// GalleryImageVersionsClientListByGalleryImageResponse contains the response from method GalleryImageVersionsClient.NewListByGalleryImagePager. +type GalleryImageVersionsClientListByGalleryImageResponse struct { + // The List Gallery Image version operation response. + GalleryImageVersionList +} + +// GalleryImageVersionsClientUpdateResponse contains the response from method GalleryImageVersionsClient.BeginUpdate. +type GalleryImageVersionsClientUpdateResponse struct { + // Specifies information about the gallery image version that you want to create or update. + GalleryImageVersion +} + +// GalleryImagesClientCreateOrUpdateResponse contains the response from method GalleryImagesClient.BeginCreateOrUpdate. +type GalleryImagesClientCreateOrUpdateResponse struct { + // Specifies information about the gallery image definition that you want to create or update. + GalleryImage +} + +// GalleryImagesClientDeleteResponse contains the response from method GalleryImagesClient.BeginDelete. +type GalleryImagesClientDeleteResponse struct { + // placeholder for future response values +} + +// GalleryImagesClientGetResponse contains the response from method GalleryImagesClient.Get. +type GalleryImagesClientGetResponse struct { + // Specifies information about the gallery image definition that you want to create or update. + GalleryImage +} + +// GalleryImagesClientListByGalleryResponse contains the response from method GalleryImagesClient.NewListByGalleryPager. +type GalleryImagesClientListByGalleryResponse struct { + // The List Gallery Images operation response. + GalleryImageList +} + +// GalleryImagesClientUpdateResponse contains the response from method GalleryImagesClient.BeginUpdate. +type GalleryImagesClientUpdateResponse struct { + // Specifies information about the gallery image definition that you want to create or update. + GalleryImage +} + +// GallerySharingProfileClientUpdateResponse contains the response from method GallerySharingProfileClient.BeginUpdate. +type GallerySharingProfileClientUpdateResponse struct { + // Specifies information about the gallery sharing profile update. + SharingUpdate +} + +// ImagesClientCreateOrUpdateResponse contains the response from method ImagesClient.BeginCreateOrUpdate. +type ImagesClientCreateOrUpdateResponse struct { + // The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. + // If SourceImage is provided, the destination virtual hard drive must not exist. + Image +} + +// ImagesClientDeleteResponse contains the response from method ImagesClient.BeginDelete. +type ImagesClientDeleteResponse struct { + // placeholder for future response values +} + +// ImagesClientGetResponse contains the response from method ImagesClient.Get. +type ImagesClientGetResponse struct { + // The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. + // If SourceImage is provided, the destination virtual hard drive must not exist. + Image +} + +// ImagesClientListByResourceGroupResponse contains the response from method ImagesClient.NewListByResourceGroupPager. +type ImagesClientListByResourceGroupResponse struct { + // The List Image operation response. + ImageListResult +} + +// ImagesClientListResponse contains the response from method ImagesClient.NewListPager. +type ImagesClientListResponse struct { + // The List Image operation response. + ImageListResult +} + +// ImagesClientUpdateResponse contains the response from method ImagesClient.BeginUpdate. +type ImagesClientUpdateResponse struct { + // The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. + // If SourceImage is provided, the destination virtual hard drive must not exist. + Image +} + +// LogAnalyticsClientExportRequestRateByIntervalResponse contains the response from method LogAnalyticsClient.BeginExportRequestRateByInterval. +type LogAnalyticsClientExportRequestRateByIntervalResponse struct { + // LogAnalytics operation status response + LogAnalyticsOperationResult +} + +// LogAnalyticsClientExportThrottledRequestsResponse contains the response from method LogAnalyticsClient.BeginExportThrottledRequests. +type LogAnalyticsClientExportThrottledRequestsResponse struct { + // LogAnalytics operation status response + LogAnalyticsOperationResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // The List Compute Operation operation response. + OperationListResult +} + +// ProximityPlacementGroupsClientCreateOrUpdateResponse contains the response from method ProximityPlacementGroupsClient.CreateOrUpdate. +type ProximityPlacementGroupsClientCreateOrUpdateResponse struct { + // Specifies information about the proximity placement group. + ProximityPlacementGroup +} + +// ProximityPlacementGroupsClientDeleteResponse contains the response from method ProximityPlacementGroupsClient.Delete. +type ProximityPlacementGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// ProximityPlacementGroupsClientGetResponse contains the response from method ProximityPlacementGroupsClient.Get. +type ProximityPlacementGroupsClientGetResponse struct { + // Specifies information about the proximity placement group. + ProximityPlacementGroup +} + +// ProximityPlacementGroupsClientListByResourceGroupResponse contains the response from method ProximityPlacementGroupsClient.NewListByResourceGroupPager. +type ProximityPlacementGroupsClientListByResourceGroupResponse struct { + // The List Proximity Placement Group operation response. + ProximityPlacementGroupListResult +} + +// ProximityPlacementGroupsClientListBySubscriptionResponse contains the response from method ProximityPlacementGroupsClient.NewListBySubscriptionPager. +type ProximityPlacementGroupsClientListBySubscriptionResponse struct { + // The List Proximity Placement Group operation response. + ProximityPlacementGroupListResult +} + +// ProximityPlacementGroupsClientUpdateResponse contains the response from method ProximityPlacementGroupsClient.Update. +type ProximityPlacementGroupsClientUpdateResponse struct { + // Specifies information about the proximity placement group. + ProximityPlacementGroup +} + +// ResourceSKUsClientListResponse contains the response from method ResourceSKUsClient.NewListPager. +type ResourceSKUsClientListResponse struct { + // The List Resource Skus operation response. + ResourceSKUsResult +} + +// RestorePointCollectionsClientCreateOrUpdateResponse contains the response from method RestorePointCollectionsClient.CreateOrUpdate. +type RestorePointCollectionsClientCreateOrUpdateResponse struct { + // Create or update Restore Point collection parameters. + RestorePointCollection +} + +// RestorePointCollectionsClientDeleteResponse contains the response from method RestorePointCollectionsClient.BeginDelete. +type RestorePointCollectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// RestorePointCollectionsClientGetResponse contains the response from method RestorePointCollectionsClient.Get. +type RestorePointCollectionsClientGetResponse struct { + // Create or update Restore Point collection parameters. + RestorePointCollection +} + +// RestorePointCollectionsClientListAllResponse contains the response from method RestorePointCollectionsClient.NewListAllPager. +type RestorePointCollectionsClientListAllResponse struct { + // The List restore point collection operation response. + RestorePointCollectionListResult +} + +// RestorePointCollectionsClientListResponse contains the response from method RestorePointCollectionsClient.NewListPager. +type RestorePointCollectionsClientListResponse struct { + // The List restore point collection operation response. + RestorePointCollectionListResult +} + +// RestorePointCollectionsClientUpdateResponse contains the response from method RestorePointCollectionsClient.Update. +type RestorePointCollectionsClientUpdateResponse struct { + // Create or update Restore Point collection parameters. + RestorePointCollection +} + +// RestorePointsClientCreateResponse contains the response from method RestorePointsClient.BeginCreate. +type RestorePointsClientCreateResponse struct { + // Restore Point details. + RestorePoint +} + +// RestorePointsClientDeleteResponse contains the response from method RestorePointsClient.BeginDelete. +type RestorePointsClientDeleteResponse struct { + // placeholder for future response values +} + +// RestorePointsClientGetResponse contains the response from method RestorePointsClient.Get. +type RestorePointsClientGetResponse struct { + // Restore Point details. + RestorePoint +} + +// SSHPublicKeysClientCreateResponse contains the response from method SSHPublicKeysClient.Create. +type SSHPublicKeysClientCreateResponse struct { + // Specifies information about the SSH public key. + SSHPublicKeyResource +} + +// SSHPublicKeysClientDeleteResponse contains the response from method SSHPublicKeysClient.Delete. +type SSHPublicKeysClientDeleteResponse struct { + // placeholder for future response values +} + +// SSHPublicKeysClientGenerateKeyPairResponse contains the response from method SSHPublicKeysClient.GenerateKeyPair. +type SSHPublicKeysClientGenerateKeyPairResponse struct { + // Response from generation of an SSH key pair. + SSHPublicKeyGenerateKeyPairResult +} + +// SSHPublicKeysClientGetResponse contains the response from method SSHPublicKeysClient.Get. +type SSHPublicKeysClientGetResponse struct { + // Specifies information about the SSH public key. + SSHPublicKeyResource +} + +// SSHPublicKeysClientListByResourceGroupResponse contains the response from method SSHPublicKeysClient.NewListByResourceGroupPager. +type SSHPublicKeysClientListByResourceGroupResponse struct { + // The list SSH public keys operation response. + SSHPublicKeysGroupListResult +} + +// SSHPublicKeysClientListBySubscriptionResponse contains the response from method SSHPublicKeysClient.NewListBySubscriptionPager. +type SSHPublicKeysClientListBySubscriptionResponse struct { + // The list SSH public keys operation response. + SSHPublicKeysGroupListResult +} + +// SSHPublicKeysClientUpdateResponse contains the response from method SSHPublicKeysClient.Update. +type SSHPublicKeysClientUpdateResponse struct { + // Specifies information about the SSH public key. + SSHPublicKeyResource +} + +// SharedGalleriesClientGetResponse contains the response from method SharedGalleriesClient.Get. +type SharedGalleriesClientGetResponse struct { + // Specifies information about the Shared Gallery that you want to create or update. + SharedGallery +} + +// SharedGalleriesClientListResponse contains the response from method SharedGalleriesClient.NewListPager. +type SharedGalleriesClientListResponse struct { + // The List Shared Galleries operation response. + SharedGalleryList +} + +// SharedGalleryImageVersionsClientGetResponse contains the response from method SharedGalleryImageVersionsClient.Get. +type SharedGalleryImageVersionsClientGetResponse struct { + // Specifies information about the gallery image version that you want to create or update. + SharedGalleryImageVersion +} + +// SharedGalleryImageVersionsClientListResponse contains the response from method SharedGalleryImageVersionsClient.NewListPager. +type SharedGalleryImageVersionsClientListResponse struct { + // The List Shared Gallery Image versions operation response. + SharedGalleryImageVersionList +} + +// SharedGalleryImagesClientGetResponse contains the response from method SharedGalleryImagesClient.Get. +type SharedGalleryImagesClientGetResponse struct { + // Specifies information about the gallery image definition that you want to create or update. + SharedGalleryImage +} + +// SharedGalleryImagesClientListResponse contains the response from method SharedGalleryImagesClient.NewListPager. +type SharedGalleryImagesClientListResponse struct { + // The List Shared Gallery Images operation response. + SharedGalleryImageList +} + +// SnapshotsClientCreateOrUpdateResponse contains the response from method SnapshotsClient.BeginCreateOrUpdate. +type SnapshotsClientCreateOrUpdateResponse struct { + // Snapshot resource. + Snapshot +} + +// SnapshotsClientDeleteResponse contains the response from method SnapshotsClient.BeginDelete. +type SnapshotsClientDeleteResponse struct { + // placeholder for future response values +} + +// SnapshotsClientGetResponse contains the response from method SnapshotsClient.Get. +type SnapshotsClientGetResponse struct { + // Snapshot resource. + Snapshot +} + +// SnapshotsClientGrantAccessResponse contains the response from method SnapshotsClient.BeginGrantAccess. +type SnapshotsClientGrantAccessResponse struct { + // A disk access SAS uri. + AccessURI +} + +// SnapshotsClientListByResourceGroupResponse contains the response from method SnapshotsClient.NewListByResourceGroupPager. +type SnapshotsClientListByResourceGroupResponse struct { + // The List Snapshots operation response. + SnapshotList +} + +// SnapshotsClientListResponse contains the response from method SnapshotsClient.NewListPager. +type SnapshotsClientListResponse struct { + // The List Snapshots operation response. + SnapshotList +} + +// SnapshotsClientRevokeAccessResponse contains the response from method SnapshotsClient.BeginRevokeAccess. +type SnapshotsClientRevokeAccessResponse struct { + // placeholder for future response values +} + +// SnapshotsClientUpdateResponse contains the response from method SnapshotsClient.BeginUpdate. +type SnapshotsClientUpdateResponse struct { + // Snapshot resource. + Snapshot +} + +// UsageClientListResponse contains the response from method UsageClient.NewListPager. +type UsageClientListResponse struct { + // The List Usages operation response. + ListUsagesResult +} + +// VirtualMachineExtensionImagesClientGetResponse contains the response from method VirtualMachineExtensionImagesClient.Get. +type VirtualMachineExtensionImagesClientGetResponse struct { + // Describes a Virtual Machine Extension Image. + VirtualMachineExtensionImage +} + +// VirtualMachineExtensionImagesClientListTypesResponse contains the response from method VirtualMachineExtensionImagesClient.ListTypes. +type VirtualMachineExtensionImagesClientListTypesResponse struct { + // Array of VirtualMachineExtensionImage + VirtualMachineExtensionImageArray []*VirtualMachineExtensionImage +} + +// VirtualMachineExtensionImagesClientListVersionsResponse contains the response from method VirtualMachineExtensionImagesClient.ListVersions. +type VirtualMachineExtensionImagesClientListVersionsResponse struct { + // Array of VirtualMachineExtensionImage + VirtualMachineExtensionImageArray []*VirtualMachineExtensionImage +} + +// VirtualMachineExtensionsClientCreateOrUpdateResponse contains the response from method VirtualMachineExtensionsClient.BeginCreateOrUpdate. +type VirtualMachineExtensionsClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine Extension. + VirtualMachineExtension +} + +// VirtualMachineExtensionsClientDeleteResponse contains the response from method VirtualMachineExtensionsClient.BeginDelete. +type VirtualMachineExtensionsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachineExtensionsClientGetResponse contains the response from method VirtualMachineExtensionsClient.Get. +type VirtualMachineExtensionsClientGetResponse struct { + // Describes a Virtual Machine Extension. + VirtualMachineExtension +} + +// VirtualMachineExtensionsClientListResponse contains the response from method VirtualMachineExtensionsClient.List. +type VirtualMachineExtensionsClientListResponse struct { + // The List Extension operation response + VirtualMachineExtensionsListResult +} + +// VirtualMachineExtensionsClientUpdateResponse contains the response from method VirtualMachineExtensionsClient.BeginUpdate. +type VirtualMachineExtensionsClientUpdateResponse struct { + // Describes a Virtual Machine Extension. + VirtualMachineExtension +} + +// VirtualMachineImagesClientGetResponse contains the response from method VirtualMachineImagesClient.Get. +type VirtualMachineImagesClientGetResponse struct { + // Describes a Virtual Machine Image. + VirtualMachineImage +} + +// VirtualMachineImagesClientListByEdgeZoneResponse contains the response from method VirtualMachineImagesClient.ListByEdgeZone. +type VirtualMachineImagesClientListByEdgeZoneResponse struct { + // The List VmImages in EdgeZone operation response. + VMImagesInEdgeZoneListResult +} + +// VirtualMachineImagesClientListOffersResponse contains the response from method VirtualMachineImagesClient.ListOffers. +type VirtualMachineImagesClientListOffersResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineImagesClientListPublishersResponse contains the response from method VirtualMachineImagesClient.ListPublishers. +type VirtualMachineImagesClientListPublishersResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineImagesClientListResponse contains the response from method VirtualMachineImagesClient.List. +type VirtualMachineImagesClientListResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineImagesClientListSKUsResponse contains the response from method VirtualMachineImagesClient.ListSKUs. +type VirtualMachineImagesClientListSKUsResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineImagesEdgeZoneClientGetResponse contains the response from method VirtualMachineImagesEdgeZoneClient.Get. +type VirtualMachineImagesEdgeZoneClientGetResponse struct { + // Describes a Virtual Machine Image. + VirtualMachineImage +} + +// VirtualMachineImagesEdgeZoneClientListOffersResponse contains the response from method VirtualMachineImagesEdgeZoneClient.ListOffers. +type VirtualMachineImagesEdgeZoneClientListOffersResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineImagesEdgeZoneClientListPublishersResponse contains the response from method VirtualMachineImagesEdgeZoneClient.ListPublishers. +type VirtualMachineImagesEdgeZoneClientListPublishersResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineImagesEdgeZoneClientListResponse contains the response from method VirtualMachineImagesEdgeZoneClient.List. +type VirtualMachineImagesEdgeZoneClientListResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineImagesEdgeZoneClientListSKUsResponse contains the response from method VirtualMachineImagesEdgeZoneClient.ListSKUs. +type VirtualMachineImagesEdgeZoneClientListSKUsResponse struct { + // Array of VirtualMachineImageResource + VirtualMachineImageResourceArray []*VirtualMachineImageResource +} + +// VirtualMachineRunCommandsClientCreateOrUpdateResponse contains the response from method VirtualMachineRunCommandsClient.BeginCreateOrUpdate. +type VirtualMachineRunCommandsClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine run command. + VirtualMachineRunCommand +} + +// VirtualMachineRunCommandsClientDeleteResponse contains the response from method VirtualMachineRunCommandsClient.BeginDelete. +type VirtualMachineRunCommandsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachineRunCommandsClientGetByVirtualMachineResponse contains the response from method VirtualMachineRunCommandsClient.GetByVirtualMachine. +type VirtualMachineRunCommandsClientGetByVirtualMachineResponse struct { + // Describes a Virtual Machine run command. + VirtualMachineRunCommand +} + +// VirtualMachineRunCommandsClientGetResponse contains the response from method VirtualMachineRunCommandsClient.Get. +type VirtualMachineRunCommandsClientGetResponse struct { + // Describes the properties of a Run Command. + RunCommandDocument +} + +// VirtualMachineRunCommandsClientListByVirtualMachineResponse contains the response from method VirtualMachineRunCommandsClient.NewListByVirtualMachinePager. +type VirtualMachineRunCommandsClientListByVirtualMachineResponse struct { + // The List run command operation response + VirtualMachineRunCommandsListResult +} + +// VirtualMachineRunCommandsClientListResponse contains the response from method VirtualMachineRunCommandsClient.NewListPager. +type VirtualMachineRunCommandsClientListResponse struct { + // The List Virtual Machine operation response. + RunCommandListResult +} + +// VirtualMachineRunCommandsClientUpdateResponse contains the response from method VirtualMachineRunCommandsClient.BeginUpdate. +type VirtualMachineRunCommandsClientUpdateResponse struct { + // Describes a Virtual Machine run command. + VirtualMachineRunCommand +} + +// VirtualMachineScaleSetExtensionsClientCreateOrUpdateResponse contains the response from method VirtualMachineScaleSetExtensionsClient.BeginCreateOrUpdate. +type VirtualMachineScaleSetExtensionsClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine Scale Set Extension. + VirtualMachineScaleSetExtension +} + +// VirtualMachineScaleSetExtensionsClientDeleteResponse contains the response from method VirtualMachineScaleSetExtensionsClient.BeginDelete. +type VirtualMachineScaleSetExtensionsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetExtensionsClientGetResponse contains the response from method VirtualMachineScaleSetExtensionsClient.Get. +type VirtualMachineScaleSetExtensionsClientGetResponse struct { + // Describes a Virtual Machine Scale Set Extension. + VirtualMachineScaleSetExtension +} + +// VirtualMachineScaleSetExtensionsClientListResponse contains the response from method VirtualMachineScaleSetExtensionsClient.NewListPager. +type VirtualMachineScaleSetExtensionsClientListResponse struct { + // The List VM scale set extension operation response. + VirtualMachineScaleSetExtensionListResult +} + +// VirtualMachineScaleSetExtensionsClientUpdateResponse contains the response from method VirtualMachineScaleSetExtensionsClient.BeginUpdate. +type VirtualMachineScaleSetExtensionsClientUpdateResponse struct { + // Describes a Virtual Machine Scale Set Extension. + VirtualMachineScaleSetExtension +} + +// VirtualMachineScaleSetRollingUpgradesClientCancelResponse contains the response from method VirtualMachineScaleSetRollingUpgradesClient.BeginCancel. +type VirtualMachineScaleSetRollingUpgradesClientCancelResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse contains the response from method VirtualMachineScaleSetRollingUpgradesClient.GetLatest. +type VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse struct { + // The status of the latest virtual machine scale set rolling upgrade. + RollingUpgradeStatusInfo +} + +// VirtualMachineScaleSetRollingUpgradesClientStartExtensionUpgradeResponse contains the response from method VirtualMachineScaleSetRollingUpgradesClient.BeginStartExtensionUpgrade. +type VirtualMachineScaleSetRollingUpgradesClientStartExtensionUpgradeResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetRollingUpgradesClientStartOSUpgradeResponse contains the response from method VirtualMachineScaleSetRollingUpgradesClient.BeginStartOSUpgrade. +type VirtualMachineScaleSetRollingUpgradesClientStartOSUpgradeResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMExtensionsClientCreateOrUpdateResponse contains the response from method VirtualMachineScaleSetVMExtensionsClient.BeginCreateOrUpdate. +type VirtualMachineScaleSetVMExtensionsClientCreateOrUpdateResponse struct { + // Describes a VMSS VM Extension. + VirtualMachineScaleSetVMExtension +} + +// VirtualMachineScaleSetVMExtensionsClientDeleteResponse contains the response from method VirtualMachineScaleSetVMExtensionsClient.BeginDelete. +type VirtualMachineScaleSetVMExtensionsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMExtensionsClientGetResponse contains the response from method VirtualMachineScaleSetVMExtensionsClient.Get. +type VirtualMachineScaleSetVMExtensionsClientGetResponse struct { + // Describes a VMSS VM Extension. + VirtualMachineScaleSetVMExtension +} + +// VirtualMachineScaleSetVMExtensionsClientListResponse contains the response from method VirtualMachineScaleSetVMExtensionsClient.List. +type VirtualMachineScaleSetVMExtensionsClientListResponse struct { + // The List VMSS VM Extension operation response + VirtualMachineScaleSetVMExtensionsListResult +} + +// VirtualMachineScaleSetVMExtensionsClientUpdateResponse contains the response from method VirtualMachineScaleSetVMExtensionsClient.BeginUpdate. +type VirtualMachineScaleSetVMExtensionsClientUpdateResponse struct { + // Describes a VMSS VM Extension. + VirtualMachineScaleSetVMExtension +} + +// VirtualMachineScaleSetVMRunCommandsClientCreateOrUpdateResponse contains the response from method VirtualMachineScaleSetVMRunCommandsClient.BeginCreateOrUpdate. +type VirtualMachineScaleSetVMRunCommandsClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine run command. + VirtualMachineRunCommand +} + +// VirtualMachineScaleSetVMRunCommandsClientDeleteResponse contains the response from method VirtualMachineScaleSetVMRunCommandsClient.BeginDelete. +type VirtualMachineScaleSetVMRunCommandsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMRunCommandsClientGetResponse contains the response from method VirtualMachineScaleSetVMRunCommandsClient.Get. +type VirtualMachineScaleSetVMRunCommandsClientGetResponse struct { + // Describes a Virtual Machine run command. + VirtualMachineRunCommand +} + +// VirtualMachineScaleSetVMRunCommandsClientListResponse contains the response from method VirtualMachineScaleSetVMRunCommandsClient.NewListPager. +type VirtualMachineScaleSetVMRunCommandsClientListResponse struct { + // The List run command operation response + VirtualMachineRunCommandsListResult +} + +// VirtualMachineScaleSetVMRunCommandsClientUpdateResponse contains the response from method VirtualMachineScaleSetVMRunCommandsClient.BeginUpdate. +type VirtualMachineScaleSetVMRunCommandsClientUpdateResponse struct { + // Describes a Virtual Machine run command. + VirtualMachineRunCommand +} + +// VirtualMachineScaleSetVMsClientApproveRollingUpgradeResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginApproveRollingUpgrade. +type VirtualMachineScaleSetVMsClientApproveRollingUpgradeResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientAttachDetachDataDisksResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginAttachDetachDataDisks. +type VirtualMachineScaleSetVMsClientAttachDetachDataDisksResponse struct { + // Specifies the storage settings for the virtual machine disks. + StorageProfile +} + +// VirtualMachineScaleSetVMsClientDeallocateResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginDeallocate. +type VirtualMachineScaleSetVMsClientDeallocateResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientDeleteResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginDelete. +type VirtualMachineScaleSetVMsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientGetInstanceViewResponse contains the response from method VirtualMachineScaleSetVMsClient.GetInstanceView. +type VirtualMachineScaleSetVMsClientGetInstanceViewResponse struct { + // The instance view of a virtual machine scale set VM. + VirtualMachineScaleSetVMInstanceView +} + +// VirtualMachineScaleSetVMsClientGetResponse contains the response from method VirtualMachineScaleSetVMsClient.Get. +type VirtualMachineScaleSetVMsClientGetResponse struct { + // Describes a virtual machine scale set virtual machine. + VirtualMachineScaleSetVM +} + +// VirtualMachineScaleSetVMsClientListResponse contains the response from method VirtualMachineScaleSetVMsClient.NewListPager. +type VirtualMachineScaleSetVMsClientListResponse struct { + // The List Virtual Machine Scale Set VMs operation response. + VirtualMachineScaleSetVMListResult +} + +// VirtualMachineScaleSetVMsClientPerformMaintenanceResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginPerformMaintenance. +type VirtualMachineScaleSetVMsClientPerformMaintenanceResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientPowerOffResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginPowerOff. +type VirtualMachineScaleSetVMsClientPowerOffResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientRedeployResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginRedeploy. +type VirtualMachineScaleSetVMsClientRedeployResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientReimageAllResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginReimageAll. +type VirtualMachineScaleSetVMsClientReimageAllResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientReimageResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginReimage. +type VirtualMachineScaleSetVMsClientReimageResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientRestartResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginRestart. +type VirtualMachineScaleSetVMsClientRestartResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse contains the response from method VirtualMachineScaleSetVMsClient.RetrieveBootDiagnosticsData. +type VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse struct { + // The SAS URIs of the console screenshot and serial log blobs. + RetrieveBootDiagnosticsDataResult +} + +// VirtualMachineScaleSetVMsClientRunCommandResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginRunCommand. +type VirtualMachineScaleSetVMsClientRunCommandResponse struct { + RunCommandResult +} + +// VirtualMachineScaleSetVMsClientSimulateEvictionResponse contains the response from method VirtualMachineScaleSetVMsClient.SimulateEviction. +type VirtualMachineScaleSetVMsClientSimulateEvictionResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientStartResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginStart. +type VirtualMachineScaleSetVMsClientStartResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetVMsClientUpdateResponse contains the response from method VirtualMachineScaleSetVMsClient.BeginUpdate. +type VirtualMachineScaleSetVMsClientUpdateResponse struct { + // Describes a virtual machine scale set virtual machine. + VirtualMachineScaleSetVM +} + +// VirtualMachineScaleSetsClientApproveRollingUpgradeResponse contains the response from method VirtualMachineScaleSetsClient.BeginApproveRollingUpgrade. +type VirtualMachineScaleSetsClientApproveRollingUpgradeResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientConvertToSinglePlacementGroupResponse contains the response from method VirtualMachineScaleSetsClient.ConvertToSinglePlacementGroup. +type VirtualMachineScaleSetsClientConvertToSinglePlacementGroupResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientCreateOrUpdateResponse contains the response from method VirtualMachineScaleSetsClient.BeginCreateOrUpdate. +type VirtualMachineScaleSetsClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine Scale Set. + VirtualMachineScaleSet +} + +// VirtualMachineScaleSetsClientDeallocateResponse contains the response from method VirtualMachineScaleSetsClient.BeginDeallocate. +type VirtualMachineScaleSetsClientDeallocateResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientDeleteInstancesResponse contains the response from method VirtualMachineScaleSetsClient.BeginDeleteInstances. +type VirtualMachineScaleSetsClientDeleteInstancesResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientDeleteResponse contains the response from method VirtualMachineScaleSetsClient.BeginDelete. +type VirtualMachineScaleSetsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse contains the response from method +// VirtualMachineScaleSetsClient.ForceRecoveryServiceFabricPlatformUpdateDomainWalk. +type VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse struct { + // Response after calling a manual recovery walk + RecoveryWalkResponse +} + +// VirtualMachineScaleSetsClientGetInstanceViewResponse contains the response from method VirtualMachineScaleSetsClient.GetInstanceView. +type VirtualMachineScaleSetsClientGetInstanceViewResponse struct { + // The instance view of a virtual machine scale set. + VirtualMachineScaleSetInstanceView +} + +// VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse contains the response from method VirtualMachineScaleSetsClient.NewGetOSUpgradeHistoryPager. +type VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse struct { + // List of Virtual Machine Scale Set OS Upgrade History operation response. + VirtualMachineScaleSetListOSUpgradeHistory +} + +// VirtualMachineScaleSetsClientGetResponse contains the response from method VirtualMachineScaleSetsClient.Get. +type VirtualMachineScaleSetsClientGetResponse struct { + // Describes a Virtual Machine Scale Set. + VirtualMachineScaleSet +} + +// VirtualMachineScaleSetsClientListAllResponse contains the response from method VirtualMachineScaleSetsClient.NewListAllPager. +type VirtualMachineScaleSetsClientListAllResponse struct { + // The List Virtual Machine operation response. + VirtualMachineScaleSetListWithLinkResult +} + +// VirtualMachineScaleSetsClientListByLocationResponse contains the response from method VirtualMachineScaleSetsClient.NewListByLocationPager. +type VirtualMachineScaleSetsClientListByLocationResponse struct { + // The List Virtual Machine operation response. + VirtualMachineScaleSetListResult +} + +// VirtualMachineScaleSetsClientListResponse contains the response from method VirtualMachineScaleSetsClient.NewListPager. +type VirtualMachineScaleSetsClientListResponse struct { + // The List Virtual Machine operation response. + VirtualMachineScaleSetListResult +} + +// VirtualMachineScaleSetsClientListSKUsResponse contains the response from method VirtualMachineScaleSetsClient.NewListSKUsPager. +type VirtualMachineScaleSetsClientListSKUsResponse struct { + // The Virtual Machine Scale Set List Skus operation response. + VirtualMachineScaleSetListSKUsResult +} + +// VirtualMachineScaleSetsClientPerformMaintenanceResponse contains the response from method VirtualMachineScaleSetsClient.BeginPerformMaintenance. +type VirtualMachineScaleSetsClientPerformMaintenanceResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientPowerOffResponse contains the response from method VirtualMachineScaleSetsClient.BeginPowerOff. +type VirtualMachineScaleSetsClientPowerOffResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientReapplyResponse contains the response from method VirtualMachineScaleSetsClient.BeginReapply. +type VirtualMachineScaleSetsClientReapplyResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientRedeployResponse contains the response from method VirtualMachineScaleSetsClient.BeginRedeploy. +type VirtualMachineScaleSetsClientRedeployResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientReimageAllResponse contains the response from method VirtualMachineScaleSetsClient.BeginReimageAll. +type VirtualMachineScaleSetsClientReimageAllResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientReimageResponse contains the response from method VirtualMachineScaleSetsClient.BeginReimage. +type VirtualMachineScaleSetsClientReimageResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientRestartResponse contains the response from method VirtualMachineScaleSetsClient.BeginRestart. +type VirtualMachineScaleSetsClientRestartResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientSetOrchestrationServiceStateResponse contains the response from method VirtualMachineScaleSetsClient.BeginSetOrchestrationServiceState. +type VirtualMachineScaleSetsClientSetOrchestrationServiceStateResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientStartResponse contains the response from method VirtualMachineScaleSetsClient.BeginStart. +type VirtualMachineScaleSetsClientStartResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientUpdateInstancesResponse contains the response from method VirtualMachineScaleSetsClient.BeginUpdateInstances. +type VirtualMachineScaleSetsClientUpdateInstancesResponse struct { + // placeholder for future response values +} + +// VirtualMachineScaleSetsClientUpdateResponse contains the response from method VirtualMachineScaleSetsClient.BeginUpdate. +type VirtualMachineScaleSetsClientUpdateResponse struct { + // Describes a Virtual Machine Scale Set. + VirtualMachineScaleSet +} + +// VirtualMachineSizesClientListResponse contains the response from method VirtualMachineSizesClient.NewListPager. +type VirtualMachineSizesClientListResponse struct { + // The List Virtual Machine operation response. + VirtualMachineSizeListResult +} + +// VirtualMachinesClientAssessPatchesResponse contains the response from method VirtualMachinesClient.BeginAssessPatches. +type VirtualMachinesClientAssessPatchesResponse struct { + // Describes the properties of an AssessPatches result. + VirtualMachineAssessPatchesResult +} + +// VirtualMachinesClientAttachDetachDataDisksResponse contains the response from method VirtualMachinesClient.BeginAttachDetachDataDisks. +type VirtualMachinesClientAttachDetachDataDisksResponse struct { + // Specifies the storage settings for the virtual machine disks. + StorageProfile +} + +// VirtualMachinesClientCaptureResponse contains the response from method VirtualMachinesClient.BeginCapture. +type VirtualMachinesClientCaptureResponse struct { + // Output of virtual machine capture operation. + VirtualMachineCaptureResult +} + +// VirtualMachinesClientConvertToManagedDisksResponse contains the response from method VirtualMachinesClient.BeginConvertToManagedDisks. +type VirtualMachinesClientConvertToManagedDisksResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientCreateOrUpdateResponse contains the response from method VirtualMachinesClient.BeginCreateOrUpdate. +type VirtualMachinesClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine. + VirtualMachine +} + +// VirtualMachinesClientDeallocateResponse contains the response from method VirtualMachinesClient.BeginDeallocate. +type VirtualMachinesClientDeallocateResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientDeleteResponse contains the response from method VirtualMachinesClient.BeginDelete. +type VirtualMachinesClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientGeneralizeResponse contains the response from method VirtualMachinesClient.Generalize. +type VirtualMachinesClientGeneralizeResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientGetResponse contains the response from method VirtualMachinesClient.Get. +type VirtualMachinesClientGetResponse struct { + // Describes a Virtual Machine. + VirtualMachine +} + +// VirtualMachinesClientInstallPatchesResponse contains the response from method VirtualMachinesClient.BeginInstallPatches. +type VirtualMachinesClientInstallPatchesResponse struct { + // The result summary of an installation operation. + VirtualMachineInstallPatchesResult +} + +// VirtualMachinesClientInstanceViewResponse contains the response from method VirtualMachinesClient.InstanceView. +type VirtualMachinesClientInstanceViewResponse struct { + // The instance view of a virtual machine. + VirtualMachineInstanceView +} + +// VirtualMachinesClientListAllResponse contains the response from method VirtualMachinesClient.NewListAllPager. +type VirtualMachinesClientListAllResponse struct { + // The List Virtual Machine operation response. + VirtualMachineListResult +} + +// VirtualMachinesClientListAvailableSizesResponse contains the response from method VirtualMachinesClient.NewListAvailableSizesPager. +type VirtualMachinesClientListAvailableSizesResponse struct { + // The List Virtual Machine operation response. + VirtualMachineSizeListResult +} + +// VirtualMachinesClientListByLocationResponse contains the response from method VirtualMachinesClient.NewListByLocationPager. +type VirtualMachinesClientListByLocationResponse struct { + // The List Virtual Machine operation response. + VirtualMachineListResult +} + +// VirtualMachinesClientListResponse contains the response from method VirtualMachinesClient.NewListPager. +type VirtualMachinesClientListResponse struct { + // The List Virtual Machine operation response. + VirtualMachineListResult +} + +// VirtualMachinesClientPerformMaintenanceResponse contains the response from method VirtualMachinesClient.BeginPerformMaintenance. +type VirtualMachinesClientPerformMaintenanceResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientPowerOffResponse contains the response from method VirtualMachinesClient.BeginPowerOff. +type VirtualMachinesClientPowerOffResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientReapplyResponse contains the response from method VirtualMachinesClient.BeginReapply. +type VirtualMachinesClientReapplyResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientRedeployResponse contains the response from method VirtualMachinesClient.BeginRedeploy. +type VirtualMachinesClientRedeployResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientReimageResponse contains the response from method VirtualMachinesClient.BeginReimage. +type VirtualMachinesClientReimageResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientRestartResponse contains the response from method VirtualMachinesClient.BeginRestart. +type VirtualMachinesClientRestartResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientRetrieveBootDiagnosticsDataResponse contains the response from method VirtualMachinesClient.RetrieveBootDiagnosticsData. +type VirtualMachinesClientRetrieveBootDiagnosticsDataResponse struct { + // The SAS URIs of the console screenshot and serial log blobs. + RetrieveBootDiagnosticsDataResult +} + +// VirtualMachinesClientRunCommandResponse contains the response from method VirtualMachinesClient.BeginRunCommand. +type VirtualMachinesClientRunCommandResponse struct { + RunCommandResult +} + +// VirtualMachinesClientSimulateEvictionResponse contains the response from method VirtualMachinesClient.SimulateEviction. +type VirtualMachinesClientSimulateEvictionResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientStartResponse contains the response from method VirtualMachinesClient.BeginStart. +type VirtualMachinesClientStartResponse struct { + // placeholder for future response values +} + +// VirtualMachinesClientUpdateResponse contains the response from method VirtualMachinesClient.BeginUpdate. +type VirtualMachinesClientUpdateResponse struct { + // Describes a Virtual Machine. + VirtualMachine +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/restorepointcollections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/restorepointcollections_client.go new file mode 100644 index 000000000..b07477e6d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/restorepointcollections_client.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 armcompute + +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" +) + +// RestorePointCollectionsClient contains the methods for the RestorePointCollections group. +// Don't use this type directly, use NewRestorePointCollectionsClient() instead. +type RestorePointCollectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRestorePointCollectionsClient creates a new instance of RestorePointCollectionsClient 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 NewRestorePointCollectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RestorePointCollectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RestorePointCollectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - The operation to create or update the restore point collection. Please refer to https://aka.ms/RestorePoints +// for more details. When updating a restore point collection, only tags may be modified. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection. +// - parameters - Parameters supplied to the Create or Update restore point collection operation. +// - options - RestorePointCollectionsClientCreateOrUpdateOptions contains the optional parameters for the RestorePointCollectionsClient.CreateOrUpdate +// method. +func (client *RestorePointCollectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollection, options *RestorePointCollectionsClientCreateOrUpdateOptions) (RestorePointCollectionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RestorePointCollectionsClient.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, restorePointCollectionName, parameters, options) + if err != nil { + return RestorePointCollectionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RestorePointCollectionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RestorePointCollectionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RestorePointCollectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollection, options *RestorePointCollectionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + 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-09-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 *RestorePointCollectionsClient) createOrUpdateHandleResponse(resp *http.Response) (RestorePointCollectionsClientCreateOrUpdateResponse, error) { + result := RestorePointCollectionsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollection); err != nil { + return RestorePointCollectionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - The operation to delete the restore point collection. This operation will also delete all the contained restore +// points. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the Restore Point Collection. +// - options - RestorePointCollectionsClientBeginDeleteOptions contains the optional parameters for the RestorePointCollectionsClient.BeginDelete +// method. +func (client *RestorePointCollectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientBeginDeleteOptions) (*runtime.Poller[RestorePointCollectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, restorePointCollectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RestorePointCollectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RestorePointCollectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete the restore point collection. This operation will also delete all the contained restore +// points. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *RestorePointCollectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RestorePointCollectionsClient.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, restorePointCollectionName, 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 *RestorePointCollectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - The operation to get the restore point collection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection. +// - options - RestorePointCollectionsClientGetOptions contains the optional parameters for the RestorePointCollectionsClient.Get +// method. +func (client *RestorePointCollectionsClient) Get(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientGetOptions) (RestorePointCollectionsClientGetResponse, error) { + var err error + const operationName = "RestorePointCollectionsClient.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, restorePointCollectionName, options) + if err != nil { + return RestorePointCollectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RestorePointCollectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RestorePointCollectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RestorePointCollectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, options *RestorePointCollectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RestorePointCollectionsClient) getHandleResponse(resp *http.Response) (RestorePointCollectionsClientGetResponse, error) { + result := RestorePointCollectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollection); err != nil { + return RestorePointCollectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the list of restore point collections in a resource group. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - RestorePointCollectionsClientListOptions contains the optional parameters for the RestorePointCollectionsClient.NewListPager +// method. +func (client *RestorePointCollectionsClient) NewListPager(resourceGroupName string, options *RestorePointCollectionsClientListOptions) *runtime.Pager[RestorePointCollectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RestorePointCollectionsClientListResponse]{ + More: func(page RestorePointCollectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RestorePointCollectionsClientListResponse) (RestorePointCollectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RestorePointCollectionsClient.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, options) + }, nil) + if err != nil { + return RestorePointCollectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RestorePointCollectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *RestorePointCollectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RestorePointCollectionsClient) listHandleResponse(resp *http.Response) (RestorePointCollectionsClientListResponse, error) { + result := RestorePointCollectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollectionListResult); err != nil { + return RestorePointCollectionsClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets the list of restore point collections in the subscription. Use nextLink property in the response +// to get the next page of restore point collections. Do this till nextLink is not null to fetch all +// the restore point collections. +// +// Generated from API version 2023-09-01 +// - options - RestorePointCollectionsClientListAllOptions contains the optional parameters for the RestorePointCollectionsClient.NewListAllPager +// method. +func (client *RestorePointCollectionsClient) NewListAllPager(options *RestorePointCollectionsClientListAllOptions) *runtime.Pager[RestorePointCollectionsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[RestorePointCollectionsClientListAllResponse]{ + More: func(page RestorePointCollectionsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RestorePointCollectionsClientListAllResponse) (RestorePointCollectionsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RestorePointCollectionsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return RestorePointCollectionsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *RestorePointCollectionsClient) listAllCreateRequest(ctx context.Context, options *RestorePointCollectionsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/restorePointCollections" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *RestorePointCollectionsClient) listAllHandleResponse(resp *http.Response) (RestorePointCollectionsClientListAllResponse, error) { + result := RestorePointCollectionsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollectionListResult); err != nil { + return RestorePointCollectionsClientListAllResponse{}, err + } + return result, nil +} + +// Update - The operation to update the restore point collection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection. +// - parameters - Parameters supplied to the Update restore point collection operation. +// - options - RestorePointCollectionsClientUpdateOptions contains the optional parameters for the RestorePointCollectionsClient.Update +// method. +func (client *RestorePointCollectionsClient) Update(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollectionUpdate, options *RestorePointCollectionsClientUpdateOptions) (RestorePointCollectionsClientUpdateResponse, error) { + var err error + const operationName = "RestorePointCollectionsClient.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, restorePointCollectionName, parameters, options) + if err != nil { + return RestorePointCollectionsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RestorePointCollectionsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RestorePointCollectionsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *RestorePointCollectionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, parameters RestorePointCollectionUpdate, options *RestorePointCollectionsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + 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-09-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 *RestorePointCollectionsClient) updateHandleResponse(resp *http.Response) (RestorePointCollectionsClientUpdateResponse, error) { + result := RestorePointCollectionsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RestorePointCollection); err != nil { + return RestorePointCollectionsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/restorepoints_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/restorepoints_client.go new file mode 100644 index 000000000..7b6364f92 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/restorepoints_client.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 armcompute + +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" +) + +// RestorePointsClient contains the methods for the RestorePoints group. +// Don't use this type directly, use NewRestorePointsClient() instead. +type RestorePointsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRestorePointsClient creates a new instance of RestorePointsClient 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 NewRestorePointsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RestorePointsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RestorePointsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - The operation to create the restore point. Updating properties of an existing restore point is not allowed +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection. +// - restorePointName - The name of the restore point. +// - parameters - Parameters supplied to the Create restore point operation. +// - options - RestorePointsClientBeginCreateOptions contains the optional parameters for the RestorePointsClient.BeginCreate +// method. +func (client *RestorePointsClient) BeginCreate(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, parameters RestorePoint, options *RestorePointsClientBeginCreateOptions) (*runtime.Poller[RestorePointsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, restorePointCollectionName, restorePointName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RestorePointsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RestorePointsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - The operation to create the restore point. Updating properties of an existing restore point is not allowed +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *RestorePointsClient) create(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, parameters RestorePoint, options *RestorePointsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "RestorePointsClient.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, restorePointCollectionName, restorePointName, 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.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *RestorePointsClient) createCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, parameters RestorePoint, options *RestorePointsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{restorePointName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + if restorePointName == "" { + return nil, errors.New("parameter restorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointName}", url.PathEscape(restorePointName)) + 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-09-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 - The operation to delete the restore point. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the Restore Point Collection. +// - restorePointName - The name of the restore point. +// - options - RestorePointsClientBeginDeleteOptions contains the optional parameters for the RestorePointsClient.BeginDelete +// method. +func (client *RestorePointsClient) BeginDelete(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientBeginDeleteOptions) (*runtime.Poller[RestorePointsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, restorePointCollectionName, restorePointName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RestorePointsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RestorePointsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete the restore point. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *RestorePointsClient) deleteOperation(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RestorePointsClient.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, restorePointCollectionName, restorePointName, 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 *RestorePointsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{restorePointName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + if restorePointName == "" { + return nil, errors.New("parameter restorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointName}", url.PathEscape(restorePointName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - The operation to get the restore point. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - restorePointCollectionName - The name of the restore point collection. +// - restorePointName - The name of the restore point. +// - options - RestorePointsClientGetOptions contains the optional parameters for the RestorePointsClient.Get method. +func (client *RestorePointsClient) Get(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientGetOptions) (RestorePointsClientGetResponse, error) { + var err error + const operationName = "RestorePointsClient.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, restorePointCollectionName, restorePointName, options) + if err != nil { + return RestorePointsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RestorePointsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RestorePointsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RestorePointsClient) getCreateRequest(ctx context.Context, resourceGroupName string, restorePointCollectionName string, restorePointName string, options *RestorePointsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/restorePointCollections/{restorePointCollectionName}/restorePoints/{restorePointName}" + 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 restorePointCollectionName == "" { + return nil, errors.New("parameter restorePointCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointCollectionName}", url.PathEscape(restorePointCollectionName)) + if restorePointName == "" { + return nil, errors.New("parameter restorePointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{restorePointName}", url.PathEscape(restorePointName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RestorePointsClient) getHandleResponse(resp *http.Response) (RestorePointsClientGetResponse, error) { + result := RestorePointsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RestorePoint); err != nil { + return RestorePointsClientGetResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleries_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleries_client.go new file mode 100644 index 000000000..4bf2d0960 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleries_client.go @@ -0,0 +1,172 @@ +//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 armcompute + +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" +) + +// SharedGalleriesClient contains the methods for the SharedGalleries group. +// Don't use this type directly, use NewSharedGalleriesClient() instead. +type SharedGalleriesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSharedGalleriesClient creates a new instance of SharedGalleriesClient 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 NewSharedGalleriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SharedGalleriesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SharedGalleriesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a shared gallery by subscription id or tenant id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - galleryUniqueName - The unique name of the Shared Gallery. +// - options - SharedGalleriesClientGetOptions contains the optional parameters for the SharedGalleriesClient.Get method. +func (client *SharedGalleriesClient) Get(ctx context.Context, location string, galleryUniqueName string, options *SharedGalleriesClientGetOptions) (SharedGalleriesClientGetResponse, error) { + var err error + const operationName = "SharedGalleriesClient.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, location, galleryUniqueName, options) + if err != nil { + return SharedGalleriesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SharedGalleriesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SharedGalleriesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SharedGalleriesClient) getCreateRequest(ctx context.Context, location string, galleryUniqueName string, options *SharedGalleriesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}" + 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 galleryUniqueName == "" { + return nil, errors.New("parameter galleryUniqueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SharedGalleriesClient) getHandleResponse(resp *http.Response) (SharedGalleriesClientGetResponse, error) { + result := SharedGalleriesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedGallery); err != nil { + return SharedGalleriesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List shared galleries by subscription id or tenant id. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - options - SharedGalleriesClientListOptions contains the optional parameters for the SharedGalleriesClient.NewListPager +// method. +func (client *SharedGalleriesClient) NewListPager(location string, options *SharedGalleriesClientListOptions) *runtime.Pager[SharedGalleriesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SharedGalleriesClientListResponse]{ + More: func(page SharedGalleriesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SharedGalleriesClientListResponse) (SharedGalleriesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SharedGalleriesClient.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, location, options) + }, nil) + if err != nil { + return SharedGalleriesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SharedGalleriesClient) listCreateRequest(ctx context.Context, location string, options *SharedGalleriesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries" + 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", "2022-08-03") + if options != nil && options.SharedTo != nil { + reqQP.Set("sharedTo", string(*options.SharedTo)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SharedGalleriesClient) listHandleResponse(resp *http.Response) (SharedGalleriesClientListResponse, error) { + result := SharedGalleriesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryList); err != nil { + return SharedGalleriesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleryimages_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleryimages_client.go new file mode 100644 index 000000000..ad549b140 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleryimages_client.go @@ -0,0 +1,182 @@ +//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 armcompute + +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" +) + +// SharedGalleryImagesClient contains the methods for the SharedGalleryImages group. +// Don't use this type directly, use NewSharedGalleryImagesClient() instead. +type SharedGalleryImagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSharedGalleryImagesClient creates a new instance of SharedGalleryImagesClient 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 NewSharedGalleryImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SharedGalleryImagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SharedGalleryImagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a shared gallery image by subscription id or tenant id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - galleryUniqueName - The unique name of the Shared Gallery. +// - galleryImageName - The name of the Shared Gallery Image Definition from which the Image Versions are to be listed. +// - options - SharedGalleryImagesClientGetOptions contains the optional parameters for the SharedGalleryImagesClient.Get method. +func (client *SharedGalleryImagesClient) Get(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImagesClientGetOptions) (SharedGalleryImagesClientGetResponse, error) { + var err error + const operationName = "SharedGalleryImagesClient.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, location, galleryUniqueName, galleryImageName, options) + if err != nil { + return SharedGalleryImagesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SharedGalleryImagesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SharedGalleryImagesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SharedGalleryImagesClient) getCreateRequest(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImagesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images/{galleryImageName}" + 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 galleryUniqueName == "" { + return nil, errors.New("parameter galleryUniqueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SharedGalleryImagesClient) getHandleResponse(resp *http.Response) (SharedGalleryImagesClientGetResponse, error) { + result := SharedGalleryImagesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImage); err != nil { + return SharedGalleryImagesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List shared gallery images by subscription id or tenant id. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - galleryUniqueName - The unique name of the Shared Gallery. +// - options - SharedGalleryImagesClientListOptions contains the optional parameters for the SharedGalleryImagesClient.NewListPager +// method. +func (client *SharedGalleryImagesClient) NewListPager(location string, galleryUniqueName string, options *SharedGalleryImagesClientListOptions) *runtime.Pager[SharedGalleryImagesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SharedGalleryImagesClientListResponse]{ + More: func(page SharedGalleryImagesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SharedGalleryImagesClientListResponse) (SharedGalleryImagesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SharedGalleryImagesClient.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, location, galleryUniqueName, options) + }, nil) + if err != nil { + return SharedGalleryImagesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SharedGalleryImagesClient) listCreateRequest(ctx context.Context, location string, galleryUniqueName string, options *SharedGalleryImagesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images" + 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 galleryUniqueName == "" { + return nil, errors.New("parameter galleryUniqueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName)) + 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", "2022-08-03") + if options != nil && options.SharedTo != nil { + reqQP.Set("sharedTo", string(*options.SharedTo)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SharedGalleryImagesClient) listHandleResponse(resp *http.Response) (SharedGalleryImagesClientListResponse, error) { + result := SharedGalleryImagesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImageList); err != nil { + return SharedGalleryImagesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleryimageversions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleryimageversions_client.go new file mode 100644 index 000000000..5c64dc844 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sharedgalleryimageversions_client.go @@ -0,0 +1,195 @@ +//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 armcompute + +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" +) + +// SharedGalleryImageVersionsClient contains the methods for the SharedGalleryImageVersions group. +// Don't use this type directly, use NewSharedGalleryImageVersionsClient() instead. +type SharedGalleryImageVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSharedGalleryImageVersionsClient creates a new instance of SharedGalleryImageVersionsClient 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 NewSharedGalleryImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SharedGalleryImageVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SharedGalleryImageVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a shared gallery image version by subscription id or tenant id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - galleryUniqueName - The unique name of the Shared Gallery. +// - galleryImageName - The name of the Shared Gallery Image Definition from which the Image Versions are to be listed. +// - galleryImageVersionName - The name of the gallery image version to be created. Needs to follow semantic version name pattern: +// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer. +// Format: .. +// - options - SharedGalleryImageVersionsClientGetOptions contains the optional parameters for the SharedGalleryImageVersionsClient.Get +// method. +func (client *SharedGalleryImageVersionsClient) Get(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, galleryImageVersionName string, options *SharedGalleryImageVersionsClientGetOptions) (SharedGalleryImageVersionsClientGetResponse, error) { + var err error + const operationName = "SharedGalleryImageVersionsClient.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, location, galleryUniqueName, galleryImageName, galleryImageVersionName, options) + if err != nil { + return SharedGalleryImageVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SharedGalleryImageVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SharedGalleryImageVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SharedGalleryImageVersionsClient) getCreateRequest(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, galleryImageVersionName string, options *SharedGalleryImageVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images/{galleryImageName}/versions/{galleryImageVersionName}" + 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 galleryUniqueName == "" { + return nil, errors.New("parameter galleryUniqueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + if galleryImageVersionName == "" { + return nil, errors.New("parameter galleryImageVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName)) + 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", "2022-08-03") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SharedGalleryImageVersionsClient) getHandleResponse(resp *http.Response) (SharedGalleryImageVersionsClientGetResponse, error) { + result := SharedGalleryImageVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImageVersion); err != nil { + return SharedGalleryImageVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List shared gallery image versions by subscription id or tenant id. +// +// Generated from API version 2022-08-03 +// - location - Resource location. +// - galleryUniqueName - The unique name of the Shared Gallery. +// - galleryImageName - The name of the Shared Gallery Image Definition from which the Image Versions are to be listed. +// - options - SharedGalleryImageVersionsClientListOptions contains the optional parameters for the SharedGalleryImageVersionsClient.NewListPager +// method. +func (client *SharedGalleryImageVersionsClient) NewListPager(location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImageVersionsClientListOptions) *runtime.Pager[SharedGalleryImageVersionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SharedGalleryImageVersionsClientListResponse]{ + More: func(page SharedGalleryImageVersionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SharedGalleryImageVersionsClientListResponse) (SharedGalleryImageVersionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SharedGalleryImageVersionsClient.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, location, galleryUniqueName, galleryImageName, options) + }, nil) + if err != nil { + return SharedGalleryImageVersionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SharedGalleryImageVersionsClient) listCreateRequest(ctx context.Context, location string, galleryUniqueName string, galleryImageName string, options *SharedGalleryImageVersionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}/images/{galleryImageName}/versions" + 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 galleryUniqueName == "" { + return nil, errors.New("parameter galleryUniqueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryUniqueName}", url.PathEscape(galleryUniqueName)) + if galleryImageName == "" { + return nil, errors.New("parameter galleryImageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName)) + 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", "2022-08-03") + if options != nil && options.SharedTo != nil { + reqQP.Set("sharedTo", string(*options.SharedTo)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SharedGalleryImageVersionsClient) listHandleResponse(resp *http.Response) (SharedGalleryImageVersionsClientListResponse, error) { + result := SharedGalleryImageVersionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedGalleryImageVersionList); err != nil { + return SharedGalleryImageVersionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/snapshots_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/snapshots_client.go new file mode 100644 index 000000000..a0d263613 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/snapshots_client.go @@ -0,0 +1,625 @@ +//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 armcompute + +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" +) + +// SnapshotsClient contains the methods for the Snapshots group. +// Don't use this type directly, use NewSnapshotsClient() instead. +type SnapshotsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSnapshotsClient creates a new instance of SnapshotsClient 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 NewSnapshotsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SnapshotsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SnapshotsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. +// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 +// characters. +// - snapshot - Snapshot object supplied in the body of the Put disk operation. +// - options - SnapshotsClientBeginCreateOrUpdateOptions contains the optional parameters for the SnapshotsClient.BeginCreateOrUpdate +// method. +func (client *SnapshotsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot, options *SnapshotsClientBeginCreateOrUpdateOptions) (*runtime.Poller[SnapshotsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, snapshotName, snapshot, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *SnapshotsClient) createOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot, options *SnapshotsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SnapshotsClient.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, snapshotName, snapshot, 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 *SnapshotsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot, options *SnapshotsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}" + 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 snapshotName == "" { + return nil, errors.New("parameter snapshotName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, snapshot); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. +// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 +// characters. +// - options - SnapshotsClientBeginDeleteOptions contains the optional parameters for the SnapshotsClient.BeginDelete method. +func (client *SnapshotsClient) BeginDelete(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginDeleteOptions) (*runtime.Poller[SnapshotsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, snapshotName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *SnapshotsClient) deleteOperation(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SnapshotsClient.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, snapshotName, 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 *SnapshotsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}" + 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 snapshotName == "" { + return nil, errors.New("parameter snapshotName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Gets information about a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. +// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 +// characters. +// - options - SnapshotsClientGetOptions contains the optional parameters for the SnapshotsClient.Get method. +func (client *SnapshotsClient) Get(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientGetOptions) (SnapshotsClientGetResponse, error) { + var err error + const operationName = "SnapshotsClient.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, snapshotName, options) + if err != nil { + return SnapshotsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SnapshotsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SnapshotsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SnapshotsClient) getCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}" + 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 snapshotName == "" { + return nil, errors.New("parameter snapshotName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SnapshotsClient) getHandleResponse(resp *http.Response) (SnapshotsClientGetResponse, error) { + result := SnapshotsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Snapshot); err != nil { + return SnapshotsClientGetResponse{}, err + } + return result, nil +} + +// BeginGrantAccess - Grants access to a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. +// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 +// characters. +// - grantAccessData - Access data object supplied in the body of the get snapshot access operation. +// - options - SnapshotsClientBeginGrantAccessOptions contains the optional parameters for the SnapshotsClient.BeginGrantAccess +// method. +func (client *SnapshotsClient) BeginGrantAccess(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, options *SnapshotsClientBeginGrantAccessOptions) (*runtime.Poller[SnapshotsClientGrantAccessResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.grantAccess(ctx, resourceGroupName, snapshotName, grantAccessData, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientGrantAccessResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientGrantAccessResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GrantAccess - Grants access to a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *SnapshotsClient) grantAccess(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, options *SnapshotsClientBeginGrantAccessOptions) (*http.Response, error) { + var err error + const operationName = "SnapshotsClient.BeginGrantAccess" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.grantAccessCreateRequest(ctx, resourceGroupName, snapshotName, grantAccessData, 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 +} + +// grantAccessCreateRequest creates the GrantAccess request. +func (client *SnapshotsClient) grantAccessCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData, options *SnapshotsClientBeginGrantAccessOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/beginGetAccess" + 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 snapshotName == "" { + return nil, errors.New("parameter snapshotName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, grantAccessData); err != nil { + return nil, err + } + return req, nil +} + +// NewListPager - Lists snapshots under a subscription. +// +// Generated from API version 2023-04-02 +// - 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]{ + More: func(page SnapshotsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SnapshotsClientListResponse) (SnapshotsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SnapshotsClient.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 SnapshotsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SnapshotsClient) listCreateRequest(ctx context.Context, options *SnapshotsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/snapshots" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SnapshotsClient) listHandleResponse(resp *http.Response) (SnapshotsClientListResponse, error) { + result := SnapshotsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SnapshotList); err != nil { + return SnapshotsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists snapshots under a resource group. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - options - SnapshotsClientListByResourceGroupOptions contains the optional parameters for the SnapshotsClient.NewListByResourceGroupPager +// method. +func (client *SnapshotsClient) NewListByResourceGroupPager(resourceGroupName string, options *SnapshotsClientListByResourceGroupOptions) *runtime.Pager[SnapshotsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[SnapshotsClientListByResourceGroupResponse]{ + More: func(page SnapshotsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SnapshotsClientListByResourceGroupResponse) (SnapshotsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SnapshotsClient.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 SnapshotsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *SnapshotsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SnapshotsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots" + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *SnapshotsClient) listByResourceGroupHandleResponse(resp *http.Response) (SnapshotsClientListByResourceGroupResponse, error) { + result := SnapshotsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SnapshotList); err != nil { + return SnapshotsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginRevokeAccess - Revokes access to a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. +// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 +// characters. +// - options - SnapshotsClientBeginRevokeAccessOptions contains the optional parameters for the SnapshotsClient.BeginRevokeAccess +// method. +func (client *SnapshotsClient) BeginRevokeAccess(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginRevokeAccessOptions) (*runtime.Poller[SnapshotsClientRevokeAccessResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.revokeAccess(ctx, resourceGroupName, snapshotName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientRevokeAccessResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientRevokeAccessResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RevokeAccess - Revokes access to a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *SnapshotsClient) revokeAccess(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginRevokeAccessOptions) (*http.Response, error) { + var err error + const operationName = "SnapshotsClient.BeginRevokeAccess" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.revokeAccessCreateRequest(ctx, resourceGroupName, snapshotName, 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 +} + +// revokeAccessCreateRequest creates the RevokeAccess request. +func (client *SnapshotsClient) revokeAccessCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, options *SnapshotsClientBeginRevokeAccessOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/endGetAccess" + 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 snapshotName == "" { + return nil, errors.New("parameter snapshotName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// BeginUpdate - Updates (patches) a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +// - resourceGroupName - The name of the resource group. +// - snapshotName - The name of the snapshot that is being created. The name can't be changed after the snapshot is created. +// Supported characters for the name are a-z, A-Z, 0-9, _ and -. The max name length is 80 +// characters. +// - snapshot - Snapshot object supplied in the body of the Patch snapshot operation. +// - options - SnapshotsClientBeginUpdateOptions contains the optional parameters for the SnapshotsClient.BeginUpdate method. +func (client *SnapshotsClient) BeginUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, options *SnapshotsClientBeginUpdateOptions) (*runtime.Poller[SnapshotsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, snapshotName, snapshot, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SnapshotsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SnapshotsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates (patches) a snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-02 +func (client *SnapshotsClient) update(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, options *SnapshotsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SnapshotsClient.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, snapshotName, snapshot, 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 *SnapshotsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate, options *SnapshotsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}" + 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 snapshotName == "" { + return nil, errors.New("parameter snapshotName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{snapshotName}", url.PathEscape(snapshotName)) + 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-04-02") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, snapshot); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sshpublickeys_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sshpublickeys_client.go new file mode 100644 index 000000000..a577d55d2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/sshpublickeys_client.go @@ -0,0 +1,489 @@ +//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 armcompute + +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" +) + +// SSHPublicKeysClient contains the methods for the SSHPublicKeys group. +// Don't use this type directly, use NewSSHPublicKeysClient() instead. +type SSHPublicKeysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSSHPublicKeysClient creates a new instance of SSHPublicKeysClient 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 NewSSHPublicKeysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SSHPublicKeysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SSHPublicKeysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Creates a new SSH public key resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - sshPublicKeyName - The name of the SSH public key. +// - parameters - Parameters supplied to create the SSH public key. +// - options - SSHPublicKeysClientCreateOptions contains the optional parameters for the SSHPublicKeysClient.Create method. +func (client *SSHPublicKeysClient) Create(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyResource, options *SSHPublicKeysClientCreateOptions) (SSHPublicKeysClientCreateResponse, error) { + var err error + const operationName = "SSHPublicKeysClient.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, sshPublicKeyName, parameters, options) + if err != nil { + return SSHPublicKeysClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SSHPublicKeysClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SSHPublicKeysClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *SSHPublicKeysClient) createCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyResource, options *SSHPublicKeysClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if sshPublicKeyName == "" { + return nil, errors.New("parameter sshPublicKeyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName)) + 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-09-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 +} + +// createHandleResponse handles the Create response. +func (client *SSHPublicKeysClient) createHandleResponse(resp *http.Response) (SSHPublicKeysClientCreateResponse, error) { + result := SSHPublicKeysClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyResource); err != nil { + return SSHPublicKeysClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Delete an SSH public key. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - sshPublicKeyName - The name of the SSH public key. +// - options - SSHPublicKeysClientDeleteOptions contains the optional parameters for the SSHPublicKeysClient.Delete method. +func (client *SSHPublicKeysClient) Delete(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientDeleteOptions) (SSHPublicKeysClientDeleteResponse, error) { + var err error + const operationName = "SSHPublicKeysClient.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, sshPublicKeyName, options) + if err != nil { + return SSHPublicKeysClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SSHPublicKeysClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SSHPublicKeysClientDeleteResponse{}, err + } + return SSHPublicKeysClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SSHPublicKeysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if sshPublicKeyName == "" { + return nil, errors.New("parameter sshPublicKeyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// GenerateKeyPair - Generates and returns a public/private key pair and populates the SSH public key resource with the public +// key. The length of the key will be 3072 bits. This operation can only be performed once per +// SSH public key resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - sshPublicKeyName - The name of the SSH public key. +// - options - SSHPublicKeysClientGenerateKeyPairOptions contains the optional parameters for the SSHPublicKeysClient.GenerateKeyPair +// method. +func (client *SSHPublicKeysClient) GenerateKeyPair(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGenerateKeyPairOptions) (SSHPublicKeysClientGenerateKeyPairResponse, error) { + var err error + const operationName = "SSHPublicKeysClient.GenerateKeyPair" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generateKeyPairCreateRequest(ctx, resourceGroupName, sshPublicKeyName, options) + if err != nil { + return SSHPublicKeysClientGenerateKeyPairResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SSHPublicKeysClientGenerateKeyPairResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SSHPublicKeysClientGenerateKeyPairResponse{}, err + } + resp, err := client.generateKeyPairHandleResponse(httpResp) + return resp, err +} + +// generateKeyPairCreateRequest creates the GenerateKeyPair request. +func (client *SSHPublicKeysClient) generateKeyPairCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGenerateKeyPairOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}/generateKeyPair" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if sshPublicKeyName == "" { + return nil, errors.New("parameter sshPublicKeyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName)) + 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-09-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 +} + +// generateKeyPairHandleResponse handles the GenerateKeyPair response. +func (client *SSHPublicKeysClient) generateKeyPairHandleResponse(resp *http.Response) (SSHPublicKeysClientGenerateKeyPairResponse, error) { + result := SSHPublicKeysClientGenerateKeyPairResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyGenerateKeyPairResult); err != nil { + return SSHPublicKeysClientGenerateKeyPairResponse{}, err + } + return result, nil +} + +// Get - Retrieves information about an SSH public key. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - sshPublicKeyName - The name of the SSH public key. +// - options - SSHPublicKeysClientGetOptions contains the optional parameters for the SSHPublicKeysClient.Get method. +func (client *SSHPublicKeysClient) Get(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGetOptions) (SSHPublicKeysClientGetResponse, error) { + var err error + const operationName = "SSHPublicKeysClient.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, sshPublicKeyName, options) + if err != nil { + return SSHPublicKeysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SSHPublicKeysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SSHPublicKeysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SSHPublicKeysClient) getCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, options *SSHPublicKeysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if sshPublicKeyName == "" { + return nil, errors.New("parameter sshPublicKeyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SSHPublicKeysClient) getHandleResponse(resp *http.Response) (SSHPublicKeysClientGetResponse, error) { + result := SSHPublicKeysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyResource); err != nil { + return SSHPublicKeysClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all of the SSH public keys in the specified resource group. Use the nextLink property +// in the response to get the next page of SSH public keys. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - SSHPublicKeysClientListByResourceGroupOptions contains the optional parameters for the SSHPublicKeysClient.NewListByResourceGroupPager +// method. +func (client *SSHPublicKeysClient) NewListByResourceGroupPager(resourceGroupName string, options *SSHPublicKeysClientListByResourceGroupOptions) *runtime.Pager[SSHPublicKeysClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[SSHPublicKeysClientListByResourceGroupResponse]{ + More: func(page SSHPublicKeysClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SSHPublicKeysClientListByResourceGroupResponse) (SSHPublicKeysClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SSHPublicKeysClient.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 SSHPublicKeysClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *SSHPublicKeysClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SSHPublicKeysClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *SSHPublicKeysClient) listByResourceGroupHandleResponse(resp *http.Response) (SSHPublicKeysClientListByResourceGroupResponse, error) { + result := SSHPublicKeysClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeysGroupListResult); err != nil { + return SSHPublicKeysClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists all of the SSH public keys in the subscription. Use the nextLink property in the response +// to get the next page of SSH public keys. +// +// Generated from API version 2023-09-01 +// - options - SSHPublicKeysClientListBySubscriptionOptions contains the optional parameters for the SSHPublicKeysClient.NewListBySubscriptionPager +// method. +func (client *SSHPublicKeysClient) NewListBySubscriptionPager(options *SSHPublicKeysClientListBySubscriptionOptions) *runtime.Pager[SSHPublicKeysClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[SSHPublicKeysClientListBySubscriptionResponse]{ + More: func(page SSHPublicKeysClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SSHPublicKeysClientListBySubscriptionResponse) (SSHPublicKeysClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SSHPublicKeysClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return SSHPublicKeysClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *SSHPublicKeysClient) listBySubscriptionCreateRequest(ctx context.Context, options *SSHPublicKeysClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/sshPublicKeys" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *SSHPublicKeysClient) listBySubscriptionHandleResponse(resp *http.Response) (SSHPublicKeysClientListBySubscriptionResponse, error) { + result := SSHPublicKeysClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeysGroupListResult); err != nil { + return SSHPublicKeysClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Updates a new SSH public key resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - sshPublicKeyName - The name of the SSH public key. +// - parameters - Parameters supplied to update the SSH public key. +// - options - SSHPublicKeysClientUpdateOptions contains the optional parameters for the SSHPublicKeysClient.Update method. +func (client *SSHPublicKeysClient) Update(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyUpdateResource, options *SSHPublicKeysClientUpdateOptions) (SSHPublicKeysClientUpdateResponse, error) { + var err error + const operationName = "SSHPublicKeysClient.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, sshPublicKeyName, parameters, options) + if err != nil { + return SSHPublicKeysClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SSHPublicKeysClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SSHPublicKeysClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *SSHPublicKeysClient) updateCreateRequest(ctx context.Context, resourceGroupName string, sshPublicKeyName string, parameters SSHPublicKeyUpdateResource, options *SSHPublicKeysClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/sshPublicKeys/{sshPublicKeyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if sshPublicKeyName == "" { + return nil, errors.New("parameter sshPublicKeyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sshPublicKeyName}", url.PathEscape(sshPublicKeyName)) + 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-09-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 *SSHPublicKeysClient) updateHandleResponse(resp *http.Response) (SSHPublicKeysClientUpdateResponse, error) { + result := SSHPublicKeysClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SSHPublicKeyResource); err != nil { + return SSHPublicKeysClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/time_rfc3339.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/time_rfc3339.go new file mode 100644 index 000000000..4f75ccd6f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/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 armcompute + +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/compute/armcompute/v5/usage_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/usage_client.go new file mode 100644 index 000000000..afb6852b0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/usage_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 armcompute + +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" +) + +// UsageClient contains the methods for the Usage group. +// Don't use this type directly, use NewUsageClient() instead. +type UsageClient struct { + internal *arm.Client + subscriptionID string +} + +// NewUsageClient creates a new instance of UsageClient 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 NewUsageClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*UsageClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &UsageClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets, for the specified location, the current compute resource usage information as well as the limits for +// compute resources under the subscription. +// +// Generated from API version 2023-09-01 +// - location - The location for which resource usage is queried. +// - options - UsageClientListOptions contains the optional parameters for the UsageClient.NewListPager method. +func (client *UsageClient) NewListPager(location string, options *UsageClientListOptions) *runtime.Pager[UsageClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[UsageClientListResponse]{ + More: func(page UsageClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *UsageClientListResponse) (UsageClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "UsageClient.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, location, options) + }, nil) + if err != nil { + return UsageClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *UsageClient) listCreateRequest(ctx context.Context, location string, options *UsageClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *UsageClient) listHandleResponse(resp *http.Response) (UsageClientListResponse, error) { + result := UsageClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListUsagesResult); err != nil { + return UsageClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineextensionimages_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineextensionimages_client.go new file mode 100644 index 000000000..a8e90c4b1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineextensionimages_client.go @@ -0,0 +1,259 @@ +//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 armcompute + +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" +) + +// VirtualMachineExtensionImagesClient contains the methods for the VirtualMachineExtensionImages group. +// Don't use this type directly, use NewVirtualMachineExtensionImagesClient() instead. +type VirtualMachineExtensionImagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineExtensionImagesClient creates a new instance of VirtualMachineExtensionImagesClient 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 NewVirtualMachineExtensionImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineExtensionImagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineExtensionImagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets a virtual machine extension image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - options - VirtualMachineExtensionImagesClientGetOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.Get +// method. +func (client *VirtualMachineExtensionImagesClient) Get(ctx context.Context, location string, publisherName string, typeParam string, version string, options *VirtualMachineExtensionImagesClientGetOptions) (VirtualMachineExtensionImagesClientGetResponse, error) { + var err error + const operationName = "VirtualMachineExtensionImagesClient.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, location, publisherName, typeParam, version, options) + if err != nil { + return VirtualMachineExtensionImagesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineExtensionImagesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineExtensionImagesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineExtensionImagesClient) getCreateRequest(ctx context.Context, location string, publisherName string, typeParam string, version string, options *VirtualMachineExtensionImagesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions/{version}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if typeParam == "" { + return nil, errors.New("parameter typeParam cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{type}", url.PathEscape(typeParam)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{version}", url.PathEscape(version)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineExtensionImagesClient) getHandleResponse(resp *http.Response) (VirtualMachineExtensionImagesClientGetResponse, error) { + result := VirtualMachineExtensionImagesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionImage); err != nil { + return VirtualMachineExtensionImagesClientGetResponse{}, err + } + return result, nil +} + +// ListTypes - Gets a list of virtual machine extension image types. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - options - VirtualMachineExtensionImagesClientListTypesOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.ListTypes +// method. +func (client *VirtualMachineExtensionImagesClient) ListTypes(ctx context.Context, location string, publisherName string, options *VirtualMachineExtensionImagesClientListTypesOptions) (VirtualMachineExtensionImagesClientListTypesResponse, error) { + var err error + const operationName = "VirtualMachineExtensionImagesClient.ListTypes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listTypesCreateRequest(ctx, location, publisherName, options) + if err != nil { + return VirtualMachineExtensionImagesClientListTypesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineExtensionImagesClientListTypesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineExtensionImagesClientListTypesResponse{}, err + } + resp, err := client.listTypesHandleResponse(httpResp) + return resp, err +} + +// listTypesCreateRequest creates the ListTypes request. +func (client *VirtualMachineExtensionImagesClient) listTypesCreateRequest(ctx context.Context, location string, publisherName string, options *VirtualMachineExtensionImagesClientListTypesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listTypesHandleResponse handles the ListTypes response. +func (client *VirtualMachineExtensionImagesClient) listTypesHandleResponse(resp *http.Response) (VirtualMachineExtensionImagesClientListTypesResponse, error) { + result := VirtualMachineExtensionImagesClientListTypesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionImageArray); err != nil { + return VirtualMachineExtensionImagesClientListTypesResponse{}, err + } + return result, nil +} + +// ListVersions - Gets a list of virtual machine extension image versions. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - options - VirtualMachineExtensionImagesClientListVersionsOptions contains the optional parameters for the VirtualMachineExtensionImagesClient.ListVersions +// method. +func (client *VirtualMachineExtensionImagesClient) ListVersions(ctx context.Context, location string, publisherName string, typeParam string, options *VirtualMachineExtensionImagesClientListVersionsOptions) (VirtualMachineExtensionImagesClientListVersionsResponse, error) { + var err error + const operationName = "VirtualMachineExtensionImagesClient.ListVersions" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listVersionsCreateRequest(ctx, location, publisherName, typeParam, options) + if err != nil { + return VirtualMachineExtensionImagesClientListVersionsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineExtensionImagesClientListVersionsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineExtensionImagesClientListVersionsResponse{}, err + } + resp, err := client.listVersionsHandleResponse(httpResp) + return resp, err +} + +// listVersionsCreateRequest creates the ListVersions request. +func (client *VirtualMachineExtensionImagesClient) listVersionsCreateRequest(ctx context.Context, location string, publisherName string, typeParam string, options *VirtualMachineExtensionImagesClientListVersionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if typeParam == "" { + return nil, errors.New("parameter typeParam cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{type}", url.PathEscape(typeParam)) + 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.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listVersionsHandleResponse handles the ListVersions response. +func (client *VirtualMachineExtensionImagesClient) listVersionsHandleResponse(resp *http.Response) (VirtualMachineExtensionImagesClientListVersionsResponse, error) { + result := VirtualMachineExtensionImagesClientListVersionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionImageArray); err != nil { + return VirtualMachineExtensionImagesClientListVersionsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineextensions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineextensions_client.go new file mode 100644 index 000000000..9d658bb4e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineextensions_client.go @@ -0,0 +1,437 @@ +//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 armcompute + +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" +) + +// VirtualMachineExtensionsClient contains the methods for the VirtualMachineExtensions group. +// Don't use this type directly, use NewVirtualMachineExtensionsClient() instead. +type VirtualMachineExtensionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineExtensionsClient creates a new instance of VirtualMachineExtensionsClient 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 NewVirtualMachineExtensionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineExtensionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineExtensionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine where the extension should be created or updated. +// - vmExtensionName - The name of the virtual machine extension. +// - extensionParameters - Parameters supplied to the Create Virtual Machine Extension operation. +// - options - VirtualMachineExtensionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachineExtensionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, options *VirtualMachineExtensionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachineExtensionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmName, vmExtensionName, extensionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineExtensionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineExtensionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineExtensionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, options *VirtualMachineExtensionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineExtensionsClient.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, vmName, vmExtensionName, extensionParameters, 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 *VirtualMachineExtensionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, options *VirtualMachineExtensionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - The operation to delete the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine where the extension should be deleted. +// - vmExtensionName - The name of the virtual machine extension. +// - options - VirtualMachineExtensionsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginDelete +// method. +func (client *VirtualMachineExtensionsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineExtensionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmName, vmExtensionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineExtensionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineExtensionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineExtensionsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineExtensionsClient.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, vmName, vmExtensionName, 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 *VirtualMachineExtensionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - The operation to get the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine containing the extension. +// - vmExtensionName - The name of the virtual machine extension. +// - options - VirtualMachineExtensionsClientGetOptions contains the optional parameters for the VirtualMachineExtensionsClient.Get +// method. +func (client *VirtualMachineExtensionsClient) Get(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientGetOptions) (VirtualMachineExtensionsClientGetResponse, error) { + var err error + const operationName = "VirtualMachineExtensionsClient.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, vmName, vmExtensionName, options) + if err != nil { + return VirtualMachineExtensionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineExtensionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineExtensionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineExtensionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, options *VirtualMachineExtensionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineExtensionsClient) getHandleResponse(resp *http.Response) (VirtualMachineExtensionsClientGetResponse, error) { + result := VirtualMachineExtensionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtension); err != nil { + return VirtualMachineExtensionsClientGetResponse{}, err + } + return result, nil +} + +// List - The operation to get all extensions of a Virtual Machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine containing the extension. +// - options - VirtualMachineExtensionsClientListOptions contains the optional parameters for the VirtualMachineExtensionsClient.List +// method. +func (client *VirtualMachineExtensionsClient) List(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachineExtensionsClientListOptions) (VirtualMachineExtensionsClientListResponse, error) { + var err error + const operationName = "VirtualMachineExtensionsClient.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, vmName, options) + if err != nil { + return VirtualMachineExtensionsClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineExtensionsClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineExtensionsClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineExtensionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachineExtensionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineExtensionsClient) listHandleResponse(resp *http.Response) (VirtualMachineExtensionsClientListResponse, error) { + result := VirtualMachineExtensionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineExtensionsListResult); err != nil { + return VirtualMachineExtensionsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - The operation to update the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine where the extension should be updated. +// - vmExtensionName - The name of the virtual machine extension. +// - extensionParameters - Parameters supplied to the Update Virtual Machine Extension operation. +// - options - VirtualMachineExtensionsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineExtensionsClient.BeginUpdate +// method. +func (client *VirtualMachineExtensionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtensionUpdate, options *VirtualMachineExtensionsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineExtensionsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmName, vmExtensionName, extensionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineExtensionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineExtensionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - The operation to update the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineExtensionsClient) update(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtensionUpdate, options *VirtualMachineExtensionsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineExtensionsClient.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, vmName, vmExtensionName, extensionParameters, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *VirtualMachineExtensionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtensionUpdate, options *VirtualMachineExtensionsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineimages_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineimages_client.go new file mode 100644 index 000000000..1c5ab27e5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineimages_client.go @@ -0,0 +1,470 @@ +//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 armcompute + +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" +) + +// VirtualMachineImagesClient contains the methods for the VirtualMachineImages group. +// Don't use this type directly, use NewVirtualMachineImagesClient() instead. +type VirtualMachineImagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineImagesClient creates a new instance of VirtualMachineImagesClient 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 NewVirtualMachineImagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineImagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineImagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets a virtual machine image. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - publisherName - A valid image publisher. +// - offer - A valid image publisher offer. +// - skus - A valid image SKU. +// - version - A valid image SKU version. +// - options - VirtualMachineImagesClientGetOptions contains the optional parameters for the VirtualMachineImagesClient.Get +// method. +func (client *VirtualMachineImagesClient) Get(ctx context.Context, location string, publisherName string, offer string, skus string, version string, options *VirtualMachineImagesClientGetOptions) (VirtualMachineImagesClientGetResponse, error) { + var err error + const operationName = "VirtualMachineImagesClient.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, location, publisherName, offer, skus, version, options) + if err != nil { + return VirtualMachineImagesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineImagesClient) getCreateRequest(ctx context.Context, location string, publisherName string, offer string, skus string, version string, options *VirtualMachineImagesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if offer == "" { + return nil, errors.New("parameter offer cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{offer}", url.PathEscape(offer)) + if skus == "" { + return nil, errors.New("parameter skus cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{skus}", url.PathEscape(skus)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{version}", url.PathEscape(version)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineImagesClient) getHandleResponse(resp *http.Response) (VirtualMachineImagesClientGetResponse, error) { + result := VirtualMachineImagesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImage); err != nil { + return VirtualMachineImagesClientGetResponse{}, err + } + return result, nil +} + +// List - Gets a list of all virtual machine image versions for the specified location, publisher, offer, and SKU. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - publisherName - A valid image publisher. +// - offer - A valid image publisher offer. +// - skus - A valid image SKU. +// - options - VirtualMachineImagesClientListOptions contains the optional parameters for the VirtualMachineImagesClient.List +// method. +func (client *VirtualMachineImagesClient) List(ctx context.Context, location string, publisherName string, offer string, skus string, options *VirtualMachineImagesClientListOptions) (VirtualMachineImagesClientListResponse, error) { + var err error + const operationName = "VirtualMachineImagesClient.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, location, publisherName, offer, skus, options) + if err != nil { + return VirtualMachineImagesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineImagesClient) listCreateRequest(ctx context.Context, location string, publisherName string, offer string, skus string, options *VirtualMachineImagesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if offer == "" { + return nil, errors.New("parameter offer cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{offer}", url.PathEscape(offer)) + if skus == "" { + return nil, errors.New("parameter skus cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{skus}", url.PathEscape(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() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineImagesClient) listHandleResponse(resp *http.Response) (VirtualMachineImagesClientListResponse, error) { + result := VirtualMachineImagesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesClientListResponse{}, err + } + return result, nil +} + +// ListByEdgeZone - Gets a list of all virtual machine image versions for the specified edge zone +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - edgeZone - The name of the edge zone. +// - options - VirtualMachineImagesClientListByEdgeZoneOptions contains the optional parameters for the VirtualMachineImagesClient.ListByEdgeZone +// method. +func (client *VirtualMachineImagesClient) ListByEdgeZone(ctx context.Context, location string, edgeZone string, options *VirtualMachineImagesClientListByEdgeZoneOptions) (VirtualMachineImagesClientListByEdgeZoneResponse, error) { + var err error + const operationName = "VirtualMachineImagesClient.ListByEdgeZone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listByEdgeZoneCreateRequest(ctx, location, edgeZone, options) + if err != nil { + return VirtualMachineImagesClientListByEdgeZoneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesClientListByEdgeZoneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesClientListByEdgeZoneResponse{}, err + } + resp, err := client.listByEdgeZoneHandleResponse(httpResp) + return resp, err +} + +// listByEdgeZoneCreateRequest creates the ListByEdgeZone request. +func (client *VirtualMachineImagesClient) listByEdgeZoneCreateRequest(ctx context.Context, location string, edgeZone string, options *VirtualMachineImagesClientListByEdgeZoneOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/edgeZones/{edgeZone}/vmimages" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if edgeZone == "" { + return nil, errors.New("parameter edgeZone cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{edgeZone}", url.PathEscape(edgeZone)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByEdgeZoneHandleResponse handles the ListByEdgeZone response. +func (client *VirtualMachineImagesClient) listByEdgeZoneHandleResponse(resp *http.Response) (VirtualMachineImagesClientListByEdgeZoneResponse, error) { + result := VirtualMachineImagesClientListByEdgeZoneResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VMImagesInEdgeZoneListResult); err != nil { + return VirtualMachineImagesClientListByEdgeZoneResponse{}, err + } + return result, nil +} + +// ListOffers - Gets a list of virtual machine image offers for the specified location and publisher. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - publisherName - A valid image publisher. +// - options - VirtualMachineImagesClientListOffersOptions contains the optional parameters for the VirtualMachineImagesClient.ListOffers +// method. +func (client *VirtualMachineImagesClient) ListOffers(ctx context.Context, location string, publisherName string, options *VirtualMachineImagesClientListOffersOptions) (VirtualMachineImagesClientListOffersResponse, error) { + var err error + const operationName = "VirtualMachineImagesClient.ListOffers" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listOffersCreateRequest(ctx, location, publisherName, options) + if err != nil { + return VirtualMachineImagesClientListOffersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesClientListOffersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesClientListOffersResponse{}, err + } + resp, err := client.listOffersHandleResponse(httpResp) + return resp, err +} + +// listOffersCreateRequest creates the ListOffers request. +func (client *VirtualMachineImagesClient) listOffersCreateRequest(ctx context.Context, location string, publisherName string, options *VirtualMachineImagesClientListOffersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listOffersHandleResponse handles the ListOffers response. +func (client *VirtualMachineImagesClient) listOffersHandleResponse(resp *http.Response) (VirtualMachineImagesClientListOffersResponse, error) { + result := VirtualMachineImagesClientListOffersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesClientListOffersResponse{}, err + } + return result, nil +} + +// ListPublishers - Gets a list of virtual machine image publishers for the specified Azure location. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - options - VirtualMachineImagesClientListPublishersOptions contains the optional parameters for the VirtualMachineImagesClient.ListPublishers +// method. +func (client *VirtualMachineImagesClient) ListPublishers(ctx context.Context, location string, options *VirtualMachineImagesClientListPublishersOptions) (VirtualMachineImagesClientListPublishersResponse, error) { + var err error + const operationName = "VirtualMachineImagesClient.ListPublishers" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listPublishersCreateRequest(ctx, location, options) + if err != nil { + return VirtualMachineImagesClientListPublishersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesClientListPublishersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesClientListPublishersResponse{}, err + } + resp, err := client.listPublishersHandleResponse(httpResp) + return resp, err +} + +// listPublishersCreateRequest creates the ListPublishers request. +func (client *VirtualMachineImagesClient) listPublishersCreateRequest(ctx context.Context, location string, options *VirtualMachineImagesClientListPublishersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPublishersHandleResponse handles the ListPublishers response. +func (client *VirtualMachineImagesClient) listPublishersHandleResponse(resp *http.Response) (VirtualMachineImagesClientListPublishersResponse, error) { + result := VirtualMachineImagesClientListPublishersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesClientListPublishersResponse{}, err + } + return result, nil +} + +// ListSKUs - Gets a list of virtual machine image SKUs for the specified location, publisher, and offer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - publisherName - A valid image publisher. +// - offer - A valid image publisher offer. +// - options - VirtualMachineImagesClientListSKUsOptions contains the optional parameters for the VirtualMachineImagesClient.ListSKUs +// method. +func (client *VirtualMachineImagesClient) ListSKUs(ctx context.Context, location string, publisherName string, offer string, options *VirtualMachineImagesClientListSKUsOptions) (VirtualMachineImagesClientListSKUsResponse, error) { + var err error + const operationName = "VirtualMachineImagesClient.ListSKUs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listSKUsCreateRequest(ctx, location, publisherName, offer, options) + if err != nil { + return VirtualMachineImagesClientListSKUsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesClientListSKUsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesClientListSKUsResponse{}, err + } + resp, err := client.listSKUsHandleResponse(httpResp) + return resp, err +} + +// listSKUsCreateRequest creates the ListSKUs request. +func (client *VirtualMachineImagesClient) listSKUsCreateRequest(ctx context.Context, location string, publisherName string, offer string, options *VirtualMachineImagesClientListSKUsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if offer == "" { + return nil, errors.New("parameter offer cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{offer}", url.PathEscape(offer)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSKUsHandleResponse handles the ListSKUs response. +func (client *VirtualMachineImagesClient) listSKUsHandleResponse(resp *http.Response) (VirtualMachineImagesClientListSKUsResponse, error) { + result := VirtualMachineImagesClientListSKUsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesClientListSKUsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineimagesedgezone_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineimagesedgezone_client.go new file mode 100644 index 000000000..4151b10d3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineimagesedgezone_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 armcompute + +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" +) + +// VirtualMachineImagesEdgeZoneClient contains the methods for the VirtualMachineImagesEdgeZone group. +// Don't use this type directly, use NewVirtualMachineImagesEdgeZoneClient() instead. +type VirtualMachineImagesEdgeZoneClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineImagesEdgeZoneClient creates a new instance of VirtualMachineImagesEdgeZoneClient 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 NewVirtualMachineImagesEdgeZoneClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineImagesEdgeZoneClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineImagesEdgeZoneClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets a virtual machine image in an edge zone. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - edgeZone - The name of the edge zone. +// - publisherName - A valid image publisher. +// - offer - A valid image publisher offer. +// - skus - A valid image SKU. +// - version - A valid image SKU version. +// - options - VirtualMachineImagesEdgeZoneClientGetOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.Get +// method. +func (client *VirtualMachineImagesEdgeZoneClient) Get(ctx context.Context, location string, edgeZone string, publisherName string, offer string, skus string, version string, options *VirtualMachineImagesEdgeZoneClientGetOptions) (VirtualMachineImagesEdgeZoneClientGetResponse, error) { + var err error + const operationName = "VirtualMachineImagesEdgeZoneClient.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, location, edgeZone, publisherName, offer, skus, version, options) + if err != nil { + return VirtualMachineImagesEdgeZoneClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesEdgeZoneClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesEdgeZoneClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineImagesEdgeZoneClient) getCreateRequest(ctx context.Context, location string, edgeZone string, publisherName string, offer string, skus string, version string, options *VirtualMachineImagesEdgeZoneClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/edgeZones/{edgeZone}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if edgeZone == "" { + return nil, errors.New("parameter edgeZone cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{edgeZone}", url.PathEscape(edgeZone)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if offer == "" { + return nil, errors.New("parameter offer cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{offer}", url.PathEscape(offer)) + if skus == "" { + return nil, errors.New("parameter skus cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{skus}", url.PathEscape(skus)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{version}", url.PathEscape(version)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineImagesEdgeZoneClient) getHandleResponse(resp *http.Response) (VirtualMachineImagesEdgeZoneClientGetResponse, error) { + result := VirtualMachineImagesEdgeZoneClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImage); err != nil { + return VirtualMachineImagesEdgeZoneClientGetResponse{}, err + } + return result, nil +} + +// List - Gets a list of all virtual machine image versions for the specified location, edge zone, publisher, offer, and SKU. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - edgeZone - The name of the edge zone. +// - publisherName - A valid image publisher. +// - offer - A valid image publisher offer. +// - skus - A valid image SKU. +// - options - VirtualMachineImagesEdgeZoneClientListOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.List +// method. +func (client *VirtualMachineImagesEdgeZoneClient) List(ctx context.Context, location string, edgeZone string, publisherName string, offer string, skus string, options *VirtualMachineImagesEdgeZoneClientListOptions) (VirtualMachineImagesEdgeZoneClientListResponse, error) { + var err error + const operationName = "VirtualMachineImagesEdgeZoneClient.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, location, edgeZone, publisherName, offer, skus, options) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesEdgeZoneClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineImagesEdgeZoneClient) listCreateRequest(ctx context.Context, location string, edgeZone string, publisherName string, offer string, skus string, options *VirtualMachineImagesEdgeZoneClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/edgeZones/{edgeZone}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if edgeZone == "" { + return nil, errors.New("parameter edgeZone cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{edgeZone}", url.PathEscape(edgeZone)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if offer == "" { + return nil, errors.New("parameter offer cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{offer}", url.PathEscape(offer)) + if skus == "" { + return nil, errors.New("parameter skus cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{skus}", url.PathEscape(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() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineImagesEdgeZoneClient) listHandleResponse(resp *http.Response) (VirtualMachineImagesEdgeZoneClientListResponse, error) { + result := VirtualMachineImagesEdgeZoneClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesEdgeZoneClientListResponse{}, err + } + return result, nil +} + +// ListOffers - Gets a list of virtual machine image offers for the specified location, edge zone and publisher. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - edgeZone - The name of the edge zone. +// - publisherName - A valid image publisher. +// - options - VirtualMachineImagesEdgeZoneClientListOffersOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.ListOffers +// method. +func (client *VirtualMachineImagesEdgeZoneClient) ListOffers(ctx context.Context, location string, edgeZone string, publisherName string, options *VirtualMachineImagesEdgeZoneClientListOffersOptions) (VirtualMachineImagesEdgeZoneClientListOffersResponse, error) { + var err error + const operationName = "VirtualMachineImagesEdgeZoneClient.ListOffers" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listOffersCreateRequest(ctx, location, edgeZone, publisherName, options) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListOffersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListOffersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesEdgeZoneClientListOffersResponse{}, err + } + resp, err := client.listOffersHandleResponse(httpResp) + return resp, err +} + +// listOffersCreateRequest creates the ListOffers request. +func (client *VirtualMachineImagesEdgeZoneClient) listOffersCreateRequest(ctx context.Context, location string, edgeZone string, publisherName string, options *VirtualMachineImagesEdgeZoneClientListOffersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/edgeZones/{edgeZone}/publishers/{publisherName}/artifacttypes/vmimage/offers" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if edgeZone == "" { + return nil, errors.New("parameter edgeZone cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{edgeZone}", url.PathEscape(edgeZone)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listOffersHandleResponse handles the ListOffers response. +func (client *VirtualMachineImagesEdgeZoneClient) listOffersHandleResponse(resp *http.Response) (VirtualMachineImagesEdgeZoneClientListOffersResponse, error) { + result := VirtualMachineImagesEdgeZoneClientListOffersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesEdgeZoneClientListOffersResponse{}, err + } + return result, nil +} + +// ListPublishers - Gets a list of virtual machine image publishers for the specified Azure location and edge zone. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - edgeZone - The name of the edge zone. +// - options - VirtualMachineImagesEdgeZoneClientListPublishersOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.ListPublishers +// method. +func (client *VirtualMachineImagesEdgeZoneClient) ListPublishers(ctx context.Context, location string, edgeZone string, options *VirtualMachineImagesEdgeZoneClientListPublishersOptions) (VirtualMachineImagesEdgeZoneClientListPublishersResponse, error) { + var err error + const operationName = "VirtualMachineImagesEdgeZoneClient.ListPublishers" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listPublishersCreateRequest(ctx, location, edgeZone, options) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListPublishersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListPublishersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesEdgeZoneClientListPublishersResponse{}, err + } + resp, err := client.listPublishersHandleResponse(httpResp) + return resp, err +} + +// listPublishersCreateRequest creates the ListPublishers request. +func (client *VirtualMachineImagesEdgeZoneClient) listPublishersCreateRequest(ctx context.Context, location string, edgeZone string, options *VirtualMachineImagesEdgeZoneClientListPublishersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/edgeZones/{edgeZone}/publishers" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if edgeZone == "" { + return nil, errors.New("parameter edgeZone cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{edgeZone}", url.PathEscape(edgeZone)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPublishersHandleResponse handles the ListPublishers response. +func (client *VirtualMachineImagesEdgeZoneClient) listPublishersHandleResponse(resp *http.Response) (VirtualMachineImagesEdgeZoneClientListPublishersResponse, error) { + result := VirtualMachineImagesEdgeZoneClientListPublishersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesEdgeZoneClientListPublishersResponse{}, err + } + return result, nil +} + +// ListSKUs - Gets a list of virtual machine image SKUs for the specified location, edge zone, publisher, and offer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The name of a supported Azure region. +// - edgeZone - The name of the edge zone. +// - publisherName - A valid image publisher. +// - offer - A valid image publisher offer. +// - options - VirtualMachineImagesEdgeZoneClientListSKUsOptions contains the optional parameters for the VirtualMachineImagesEdgeZoneClient.ListSKUs +// method. +func (client *VirtualMachineImagesEdgeZoneClient) ListSKUs(ctx context.Context, location string, edgeZone string, publisherName string, offer string, options *VirtualMachineImagesEdgeZoneClientListSKUsOptions) (VirtualMachineImagesEdgeZoneClientListSKUsResponse, error) { + var err error + const operationName = "VirtualMachineImagesEdgeZoneClient.ListSKUs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listSKUsCreateRequest(ctx, location, edgeZone, publisherName, offer, options) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListSKUsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineImagesEdgeZoneClientListSKUsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineImagesEdgeZoneClientListSKUsResponse{}, err + } + resp, err := client.listSKUsHandleResponse(httpResp) + return resp, err +} + +// listSKUsCreateRequest creates the ListSKUs request. +func (client *VirtualMachineImagesEdgeZoneClient) listSKUsCreateRequest(ctx context.Context, location string, edgeZone string, publisherName string, offer string, options *VirtualMachineImagesEdgeZoneClientListSKUsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/edgeZones/{edgeZone}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if edgeZone == "" { + return nil, errors.New("parameter edgeZone cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{edgeZone}", url.PathEscape(edgeZone)) + if publisherName == "" { + return nil, errors.New("parameter publisherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publisherName}", url.PathEscape(publisherName)) + if offer == "" { + return nil, errors.New("parameter offer cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{offer}", url.PathEscape(offer)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSKUsHandleResponse handles the ListSKUs response. +func (client *VirtualMachineImagesEdgeZoneClient) listSKUsHandleResponse(resp *http.Response) (VirtualMachineImagesEdgeZoneClientListSKUsResponse, error) { + result := VirtualMachineImagesEdgeZoneClientListSKUsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineImageResourceArray); err != nil { + return VirtualMachineImagesEdgeZoneClientListSKUsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineruncommands_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineruncommands_client.go new file mode 100644 index 000000000..348c59ade --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachineruncommands_client.go @@ -0,0 +1,562 @@ +//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 armcompute + +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" +) + +// VirtualMachineRunCommandsClient contains the methods for the VirtualMachineRunCommands group. +// Don't use this type directly, use NewVirtualMachineRunCommandsClient() instead. +type VirtualMachineRunCommandsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineRunCommandsClient creates a new instance of VirtualMachineRunCommandsClient 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 NewVirtualMachineRunCommandsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineRunCommandsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineRunCommandsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update the run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine where the run command should be created or updated. +// - runCommandName - The name of the virtual machine run command. +// - runCommand - Parameters supplied to the Create Virtual Machine RunCommand operation. +// - options - VirtualMachineRunCommandsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineRunCommandsClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachineRunCommandsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, runCommand VirtualMachineRunCommand, options *VirtualMachineRunCommandsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachineRunCommandsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmName, runCommandName, runCommand, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineRunCommandsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineRunCommandsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update the run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineRunCommandsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, runCommand VirtualMachineRunCommand, options *VirtualMachineRunCommandsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineRunCommandsClient.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, vmName, runCommandName, runCommand, 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 *VirtualMachineRunCommandsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, runCommand VirtualMachineRunCommand, options *VirtualMachineRunCommandsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + if err := runtime.MarshalAsJSON(req, runCommand); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - The operation to delete the run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine where the run command should be deleted. +// - runCommandName - The name of the virtual machine run command. +// - options - VirtualMachineRunCommandsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineRunCommandsClient.BeginDelete +// method. +func (client *VirtualMachineRunCommandsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, options *VirtualMachineRunCommandsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineRunCommandsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmName, runCommandName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineRunCommandsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineRunCommandsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete the run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineRunCommandsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, options *VirtualMachineRunCommandsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineRunCommandsClient.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, vmName, runCommandName, 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 *VirtualMachineRunCommandsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, options *VirtualMachineRunCommandsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// Get - Gets specific run command for a subscription in a location. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - location - The location upon which run commands is queried. +// - commandID - The command id. +// - options - VirtualMachineRunCommandsClientGetOptions contains the optional parameters for the VirtualMachineRunCommandsClient.Get +// method. +func (client *VirtualMachineRunCommandsClient) Get(ctx context.Context, location string, commandID string, options *VirtualMachineRunCommandsClientGetOptions) (VirtualMachineRunCommandsClientGetResponse, error) { + var err error + const operationName = "VirtualMachineRunCommandsClient.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, location, commandID, options) + if err != nil { + return VirtualMachineRunCommandsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineRunCommandsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineRunCommandsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineRunCommandsClient) getCreateRequest(ctx context.Context, location string, commandID string, options *VirtualMachineRunCommandsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands/{commandId}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if commandID == "" { + return nil, errors.New("parameter commandID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commandId}", url.PathEscape(commandID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineRunCommandsClient) getHandleResponse(resp *http.Response) (VirtualMachineRunCommandsClientGetResponse, error) { + result := VirtualMachineRunCommandsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RunCommandDocument); err != nil { + return VirtualMachineRunCommandsClientGetResponse{}, err + } + return result, nil +} + +// GetByVirtualMachine - The operation to get the run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine containing the run command. +// - runCommandName - The name of the virtual machine run command. +// - options - VirtualMachineRunCommandsClientGetByVirtualMachineOptions contains the optional parameters for the VirtualMachineRunCommandsClient.GetByVirtualMachine +// method. +func (client *VirtualMachineRunCommandsClient) GetByVirtualMachine(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, options *VirtualMachineRunCommandsClientGetByVirtualMachineOptions) (VirtualMachineRunCommandsClientGetByVirtualMachineResponse, error) { + var err error + const operationName = "VirtualMachineRunCommandsClient.GetByVirtualMachine" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getByVirtualMachineCreateRequest(ctx, resourceGroupName, vmName, runCommandName, options) + if err != nil { + return VirtualMachineRunCommandsClientGetByVirtualMachineResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineRunCommandsClientGetByVirtualMachineResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineRunCommandsClientGetByVirtualMachineResponse{}, err + } + resp, err := client.getByVirtualMachineHandleResponse(httpResp) + return resp, err +} + +// getByVirtualMachineCreateRequest creates the GetByVirtualMachine request. +func (client *VirtualMachineRunCommandsClient) getByVirtualMachineCreateRequest(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, options *VirtualMachineRunCommandsClientGetByVirtualMachineOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// getByVirtualMachineHandleResponse handles the GetByVirtualMachine response. +func (client *VirtualMachineRunCommandsClient) getByVirtualMachineHandleResponse(resp *http.Response) (VirtualMachineRunCommandsClientGetByVirtualMachineResponse, error) { + result := VirtualMachineRunCommandsClientGetByVirtualMachineResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineRunCommand); err != nil { + return VirtualMachineRunCommandsClientGetByVirtualMachineResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all available run commands for a subscription in a location. +// +// Generated from API version 2023-09-01 +// - location - The location upon which run commands is queried. +// - options - VirtualMachineRunCommandsClientListOptions contains the optional parameters for the VirtualMachineRunCommandsClient.NewListPager +// method. +func (client *VirtualMachineRunCommandsClient) NewListPager(location string, options *VirtualMachineRunCommandsClientListOptions) *runtime.Pager[VirtualMachineRunCommandsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineRunCommandsClientListResponse]{ + More: func(page VirtualMachineRunCommandsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineRunCommandsClientListResponse) (VirtualMachineRunCommandsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineRunCommandsClient.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, location, options) + }, nil) + if err != nil { + return VirtualMachineRunCommandsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineRunCommandsClient) listCreateRequest(ctx context.Context, location string, options *VirtualMachineRunCommandsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineRunCommandsClient) listHandleResponse(resp *http.Response) (VirtualMachineRunCommandsClientListResponse, error) { + result := VirtualMachineRunCommandsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RunCommandListResult); err != nil { + return VirtualMachineRunCommandsClientListResponse{}, err + } + return result, nil +} + +// NewListByVirtualMachinePager - The operation to get all run commands of a Virtual Machine. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine containing the run command. +// - options - VirtualMachineRunCommandsClientListByVirtualMachineOptions contains the optional parameters for the VirtualMachineRunCommandsClient.NewListByVirtualMachinePager +// method. +func (client *VirtualMachineRunCommandsClient) NewListByVirtualMachinePager(resourceGroupName string, vmName string, options *VirtualMachineRunCommandsClientListByVirtualMachineOptions) *runtime.Pager[VirtualMachineRunCommandsClientListByVirtualMachineResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineRunCommandsClientListByVirtualMachineResponse]{ + More: func(page VirtualMachineRunCommandsClientListByVirtualMachineResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineRunCommandsClientListByVirtualMachineResponse) (VirtualMachineRunCommandsClientListByVirtualMachineResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineRunCommandsClient.NewListByVirtualMachinePager") + 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.listByVirtualMachineCreateRequest(ctx, resourceGroupName, vmName, options) + }, nil) + if err != nil { + return VirtualMachineRunCommandsClientListByVirtualMachineResponse{}, err + } + return client.listByVirtualMachineHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVirtualMachineCreateRequest creates the ListByVirtualMachine request. +func (client *VirtualMachineRunCommandsClient) listByVirtualMachineCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachineRunCommandsClientListByVirtualMachineOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// listByVirtualMachineHandleResponse handles the ListByVirtualMachine response. +func (client *VirtualMachineRunCommandsClient) listByVirtualMachineHandleResponse(resp *http.Response) (VirtualMachineRunCommandsClientListByVirtualMachineResponse, error) { + result := VirtualMachineRunCommandsClientListByVirtualMachineResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineRunCommandsListResult); err != nil { + return VirtualMachineRunCommandsClientListByVirtualMachineResponse{}, err + } + return result, nil +} + +// BeginUpdate - The operation to update the run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine where the run command should be updated. +// - runCommandName - The name of the virtual machine run command. +// - runCommand - Parameters supplied to the Update Virtual Machine RunCommand operation. +// - options - VirtualMachineRunCommandsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineRunCommandsClient.BeginUpdate +// method. +func (client *VirtualMachineRunCommandsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, runCommand VirtualMachineRunCommandUpdate, options *VirtualMachineRunCommandsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineRunCommandsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmName, runCommandName, runCommand, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineRunCommandsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineRunCommandsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - The operation to update the run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineRunCommandsClient) update(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, runCommand VirtualMachineRunCommandUpdate, options *VirtualMachineRunCommandsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineRunCommandsClient.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, vmName, runCommandName, runCommand, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *VirtualMachineRunCommandsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, runCommandName string, runCommand VirtualMachineRunCommandUpdate, options *VirtualMachineRunCommandsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + if err := runtime.MarshalAsJSON(req, runCommand); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachines_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachines_client.go new file mode 100644 index 000000000..b665b49f5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachines_client.go @@ -0,0 +1,1984 @@ +//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 armcompute + +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" +) + +// VirtualMachinesClient contains the methods for the VirtualMachines group. +// Don't use this type directly, use NewVirtualMachinesClient() instead. +type VirtualMachinesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachinesClient creates a new instance of VirtualMachinesClient 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 NewVirtualMachinesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachinesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachinesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAssessPatches - Assess patches on the VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginAssessPatchesOptions contains the optional parameters for the VirtualMachinesClient.BeginAssessPatches +// method. +func (client *VirtualMachinesClient) BeginAssessPatches(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginAssessPatchesOptions) (*runtime.Poller[VirtualMachinesClientAssessPatchesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.assessPatches(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientAssessPatchesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientAssessPatchesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// AssessPatches - Assess patches on the VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) assessPatches(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginAssessPatchesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginAssessPatches" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.assessPatchesCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// assessPatchesCreateRequest creates the AssessPatches request. +func (client *VirtualMachinesClient) assessPatchesCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginAssessPatchesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/assessPatches" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginAttachDetachDataDisks - Attach and detach data disks to/from the virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - parameters - Parameters supplied to the attach and detach data disks operation on the virtual machine. +// - options - VirtualMachinesClientBeginAttachDetachDataDisksOptions contains the optional parameters for the VirtualMachinesClient.BeginAttachDetachDataDisks +// method. +func (client *VirtualMachinesClient) BeginAttachDetachDataDisks(ctx context.Context, resourceGroupName string, vmName string, parameters AttachDetachDataDisksRequest, options *VirtualMachinesClientBeginAttachDetachDataDisksOptions) (*runtime.Poller[VirtualMachinesClientAttachDetachDataDisksResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.attachDetachDataDisks(ctx, resourceGroupName, vmName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientAttachDetachDataDisksResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientAttachDetachDataDisksResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// AttachDetachDataDisks - Attach and detach data disks to/from the virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) attachDetachDataDisks(ctx context.Context, resourceGroupName string, vmName string, parameters AttachDetachDataDisksRequest, options *VirtualMachinesClientBeginAttachDetachDataDisksOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginAttachDetachDataDisks" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.attachDetachDataDisksCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// attachDetachDataDisksCreateRequest creates the AttachDetachDataDisks request. +func (client *VirtualMachinesClient) attachDetachDataDisksCreateRequest(ctx context.Context, resourceGroupName string, vmName string, parameters AttachDetachDataDisksRequest, options *VirtualMachinesClientBeginAttachDetachDataDisksOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/attachDetachDataDisks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-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 +} + +// BeginCapture - Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to create +// similar VMs. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - parameters - Parameters supplied to the Capture Virtual Machine operation. +// - options - VirtualMachinesClientBeginCaptureOptions contains the optional parameters for the VirtualMachinesClient.BeginCapture +// method. +func (client *VirtualMachinesClient) BeginCapture(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, options *VirtualMachinesClientBeginCaptureOptions) (*runtime.Poller[VirtualMachinesClientCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.capture(ctx, resourceGroupName, vmName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Capture - Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to create similar +// VMs. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) capture(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, options *VirtualMachinesClientBeginCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.captureCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// captureCreateRequest creates the Capture request. +func (client *VirtualMachinesClient) captureCreateRequest(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, options *VirtualMachinesClientBeginCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/capture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-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 +} + +// BeginConvertToManagedDisks - Converts virtual machine disks from blob-based to managed disks. Virtual machine must be stop-deallocated +// before invoking this operation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginConvertToManagedDisksOptions contains the optional parameters for the VirtualMachinesClient.BeginConvertToManagedDisks +// method. +func (client *VirtualMachinesClient) BeginConvertToManagedDisks(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginConvertToManagedDisksOptions) (*runtime.Poller[VirtualMachinesClientConvertToManagedDisksResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.convertToManagedDisks(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientConvertToManagedDisksResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientConvertToManagedDisksResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ConvertToManagedDisks - Converts virtual machine disks from blob-based to managed disks. Virtual machine must be stop-deallocated +// before invoking this operation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) convertToManagedDisks(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginConvertToManagedDisksOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginConvertToManagedDisks" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.convertToManagedDisksCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// convertToManagedDisksCreateRequest creates the ConvertToManagedDisks request. +func (client *VirtualMachinesClient) convertToManagedDisksCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginConvertToManagedDisksOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/convertToManagedDisks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginCreateOrUpdate - The operation to create or update a virtual machine. Please note some properties can be set only +// during virtual machine creation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - parameters - Parameters supplied to the Create Virtual Machine operation. +// - options - VirtualMachinesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachinesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachine, options *VirtualMachinesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachinesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update a virtual machine. Please note some properties can be set only during +// virtual machine creation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachine, options *VirtualMachinesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.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, vmName, 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 *VirtualMachinesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachine, options *VirtualMachinesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDeallocate - Shuts down the virtual machine and releases the compute resources. You are not billed for the compute +// resources that this virtual machine uses. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginDeallocateOptions contains the optional parameters for the VirtualMachinesClient.BeginDeallocate +// method. +func (client *VirtualMachinesClient) BeginDeallocate(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginDeallocateOptions) (*runtime.Poller[VirtualMachinesClientDeallocateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deallocate(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientDeallocateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientDeallocateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Deallocate - Shuts down the virtual machine and releases the compute resources. You are not billed for the compute resources +// that this virtual machine uses. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) deallocate(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginDeallocateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginDeallocate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deallocateCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// deallocateCreateRequest creates the Deallocate request. +func (client *VirtualMachinesClient) deallocateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginDeallocateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/deallocate" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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() + if options != nil && options.Hibernate != nil { + reqQP.Set("hibernate", strconv.FormatBool(*options.Hibernate)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDelete - The operation to delete a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginDeleteOptions contains the optional parameters for the VirtualMachinesClient.BeginDelete +// method. +func (client *VirtualMachinesClient) BeginDelete(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginDeleteOptions) (*runtime.Poller[VirtualMachinesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) deleteOperation(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.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, vmName, 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 *VirtualMachinesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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() + if options != nil && options.ForceDeletion != nil { + reqQP.Set("forceDeletion", strconv.FormatBool(*options.ForceDeletion)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Generalize - Sets the OS state of the virtual machine to generalized. It is recommended to sysprep the virtual machine +// before performing this operation. For Windows, please refer to Create a managed image of a +// generalized VM in Azure [https://docs.microsoft.com/azure/virtual-machines/windows/capture-image-resource]. For Linux, +// please refer to How to create an image of a virtual machine or VHD +// [https://docs.microsoft.com/azure/virtual-machines/linux/capture-image]. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientGeneralizeOptions contains the optional parameters for the VirtualMachinesClient.Generalize +// method. +func (client *VirtualMachinesClient) Generalize(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientGeneralizeOptions) (VirtualMachinesClientGeneralizeResponse, error) { + var err error + const operationName = "VirtualMachinesClient.Generalize" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generalizeCreateRequest(ctx, resourceGroupName, vmName, options) + if err != nil { + return VirtualMachinesClientGeneralizeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientGeneralizeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachinesClientGeneralizeResponse{}, err + } + return VirtualMachinesClientGeneralizeResponse{}, nil +} + +// generalizeCreateRequest creates the Generalize request. +func (client *VirtualMachinesClient) generalizeCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientGeneralizeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/generalize" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves information about the model view or the instance view of a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientGetOptions contains the optional parameters for the VirtualMachinesClient.Get method. +func (client *VirtualMachinesClient) Get(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientGetOptions) (VirtualMachinesClientGetResponse, error) { + var err error + const operationName = "VirtualMachinesClient.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, vmName, options) + if err != nil { + return VirtualMachinesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachinesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachinesClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachinesClient) getHandleResponse(resp *http.Response) (VirtualMachinesClientGetResponse, error) { + result := VirtualMachinesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachine); err != nil { + return VirtualMachinesClientGetResponse{}, err + } + return result, nil +} + +// BeginInstallPatches - Installs patches on the VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - installPatchesInput - Input for InstallPatches as directly received by the API +// - options - VirtualMachinesClientBeginInstallPatchesOptions contains the optional parameters for the VirtualMachinesClient.BeginInstallPatches +// method. +func (client *VirtualMachinesClient) BeginInstallPatches(ctx context.Context, resourceGroupName string, vmName string, installPatchesInput VirtualMachineInstallPatchesParameters, options *VirtualMachinesClientBeginInstallPatchesOptions) (*runtime.Poller[VirtualMachinesClientInstallPatchesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.installPatches(ctx, resourceGroupName, vmName, installPatchesInput, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientInstallPatchesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientInstallPatchesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// InstallPatches - Installs patches on the VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) installPatches(ctx context.Context, resourceGroupName string, vmName string, installPatchesInput VirtualMachineInstallPatchesParameters, options *VirtualMachinesClientBeginInstallPatchesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginInstallPatches" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.installPatchesCreateRequest(ctx, resourceGroupName, vmName, installPatchesInput, 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 +} + +// installPatchesCreateRequest creates the InstallPatches request. +func (client *VirtualMachinesClient) installPatchesCreateRequest(ctx context.Context, resourceGroupName string, vmName string, installPatchesInput VirtualMachineInstallPatchesParameters, options *VirtualMachinesClientBeginInstallPatchesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/installPatches" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, installPatchesInput); err != nil { + return nil, err + } + return req, nil +} + +// InstanceView - Retrieves information about the run-time state of a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientInstanceViewOptions contains the optional parameters for the VirtualMachinesClient.InstanceView +// method. +func (client *VirtualMachinesClient) InstanceView(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientInstanceViewOptions) (VirtualMachinesClientInstanceViewResponse, error) { + var err error + const operationName = "VirtualMachinesClient.InstanceView" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.instanceViewCreateRequest(ctx, resourceGroupName, vmName, options) + if err != nil { + return VirtualMachinesClientInstanceViewResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientInstanceViewResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachinesClientInstanceViewResponse{}, err + } + resp, err := client.instanceViewHandleResponse(httpResp) + return resp, err +} + +// instanceViewCreateRequest creates the InstanceView request. +func (client *VirtualMachinesClient) instanceViewCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientInstanceViewOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/instanceView" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// instanceViewHandleResponse handles the InstanceView response. +func (client *VirtualMachinesClient) instanceViewHandleResponse(resp *http.Response) (VirtualMachinesClientInstanceViewResponse, error) { + result := VirtualMachinesClientInstanceViewResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineInstanceView); err != nil { + return VirtualMachinesClientInstanceViewResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all of the virtual machines in the specified resource group. Use the nextLink property in the response +// to get the next page of virtual machines. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualMachinesClientListOptions contains the optional parameters for the VirtualMachinesClient.NewListPager +// method. +func (client *VirtualMachinesClient) NewListPager(resourceGroupName string, options *VirtualMachinesClientListOptions) *runtime.Pager[VirtualMachinesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachinesClientListResponse]{ + More: func(page VirtualMachinesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachinesClientListResponse) (VirtualMachinesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachinesClient.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, options) + }, nil) + if err != nil { + return VirtualMachinesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualMachinesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualMachinesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines" + 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.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachinesClient) listHandleResponse(resp *http.Response) (VirtualMachinesClientListResponse, error) { + result := VirtualMachinesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineListResult); err != nil { + return VirtualMachinesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Lists all of the virtual machines in the specified subscription. Use the nextLink property in the response +// to get the next page of virtual machines. +// +// Generated from API version 2023-09-01 +// - options - VirtualMachinesClientListAllOptions contains the optional parameters for the VirtualMachinesClient.NewListAllPager +// method. +func (client *VirtualMachinesClient) NewListAllPager(options *VirtualMachinesClientListAllOptions) *runtime.Pager[VirtualMachinesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachinesClientListAllResponse]{ + More: func(page VirtualMachinesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachinesClientListAllResponse) (VirtualMachinesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachinesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return VirtualMachinesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *VirtualMachinesClient) listAllCreateRequest(ctx context.Context, options *VirtualMachinesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines" + 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-09-01") + if options != nil && options.StatusOnly != nil { + reqQP.Set("statusOnly", *options.StatusOnly) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + 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 +} + +// listAllHandleResponse handles the ListAll response. +func (client *VirtualMachinesClient) listAllHandleResponse(resp *http.Response) (VirtualMachinesClientListAllResponse, error) { + result := VirtualMachinesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineListResult); err != nil { + return VirtualMachinesClientListAllResponse{}, err + } + return result, nil +} + +// NewListAvailableSizesPager - Lists all available virtual machine sizes to which the specified virtual machine can be resized. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientListAvailableSizesOptions contains the optional parameters for the VirtualMachinesClient.NewListAvailableSizesPager +// method. +func (client *VirtualMachinesClient) NewListAvailableSizesPager(resourceGroupName string, vmName string, options *VirtualMachinesClientListAvailableSizesOptions) *runtime.Pager[VirtualMachinesClientListAvailableSizesResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachinesClientListAvailableSizesResponse]{ + More: func(page VirtualMachinesClientListAvailableSizesResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *VirtualMachinesClientListAvailableSizesResponse) (VirtualMachinesClientListAvailableSizesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachinesClient.NewListAvailableSizesPager") + req, err := client.listAvailableSizesCreateRequest(ctx, resourceGroupName, vmName, options) + if err != nil { + return VirtualMachinesClientListAvailableSizesResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientListAvailableSizesResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return VirtualMachinesClientListAvailableSizesResponse{}, runtime.NewResponseError(resp) + } + return client.listAvailableSizesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAvailableSizesCreateRequest creates the ListAvailableSizes request. +func (client *VirtualMachinesClient) listAvailableSizesCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientListAvailableSizesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/vmSizes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableSizesHandleResponse handles the ListAvailableSizes response. +func (client *VirtualMachinesClient) listAvailableSizesHandleResponse(resp *http.Response) (VirtualMachinesClientListAvailableSizesResponse, error) { + result := VirtualMachinesClientListAvailableSizesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineSizeListResult); err != nil { + return VirtualMachinesClientListAvailableSizesResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - Gets all the virtual machines under the specified subscription for the specified location. +// +// Generated from API version 2023-09-01 +// - location - The location for which virtual machines under the subscription are queried. +// - options - VirtualMachinesClientListByLocationOptions contains the optional parameters for the VirtualMachinesClient.NewListByLocationPager +// method. +func (client *VirtualMachinesClient) NewListByLocationPager(location string, options *VirtualMachinesClientListByLocationOptions) *runtime.Pager[VirtualMachinesClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachinesClientListByLocationResponse]{ + More: func(page VirtualMachinesClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachinesClientListByLocationResponse) (VirtualMachinesClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachinesClient.NewListByLocationPager") + 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.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return VirtualMachinesClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *VirtualMachinesClient) listByLocationCreateRequest(ctx context.Context, location string, options *VirtualMachinesClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/virtualMachines" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *VirtualMachinesClient) listByLocationHandleResponse(resp *http.Response) (VirtualMachinesClientListByLocationResponse, error) { + result := VirtualMachinesClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineListResult); err != nil { + return VirtualMachinesClientListByLocationResponse{}, err + } + return result, nil +} + +// BeginPerformMaintenance - The operation to perform maintenance on a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginPerformMaintenanceOptions contains the optional parameters for the VirtualMachinesClient.BeginPerformMaintenance +// method. +func (client *VirtualMachinesClient) BeginPerformMaintenance(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginPerformMaintenanceOptions) (*runtime.Poller[VirtualMachinesClientPerformMaintenanceResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.performMaintenance(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientPerformMaintenanceResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientPerformMaintenanceResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PerformMaintenance - The operation to perform maintenance on a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) performMaintenance(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginPerformMaintenanceOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginPerformMaintenance" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.performMaintenanceCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// performMaintenanceCreateRequest creates the PerformMaintenance request. +func (client *VirtualMachinesClient) performMaintenanceCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginPerformMaintenanceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/performMaintenance" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginPowerOff - The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same +// provisioned resources. You are still charged for this virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginPowerOffOptions contains the optional parameters for the VirtualMachinesClient.BeginPowerOff +// method. +func (client *VirtualMachinesClient) BeginPowerOff(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginPowerOffOptions) (*runtime.Poller[VirtualMachinesClientPowerOffResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.powerOff(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PowerOff - The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same provisioned +// resources. You are still charged for this virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) powerOff(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginPowerOffOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginPowerOff" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.powerOffCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// powerOffCreateRequest creates the PowerOff request. +func (client *VirtualMachinesClient) powerOffCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginPowerOffOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/powerOff" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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() + if options != nil && options.SkipShutdown != nil { + reqQP.Set("skipShutdown", strconv.FormatBool(*options.SkipShutdown)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginReapply - The operation to reapply a virtual machine's state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginReapplyOptions contains the optional parameters for the VirtualMachinesClient.BeginReapply +// method. +func (client *VirtualMachinesClient) BeginReapply(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginReapplyOptions) (*runtime.Poller[VirtualMachinesClientReapplyResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reapply(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientReapplyResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientReapplyResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reapply - The operation to reapply a virtual machine's state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) reapply(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginReapplyOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginReapply" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reapplyCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// reapplyCreateRequest creates the Reapply request. +func (client *VirtualMachinesClient) reapplyCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginReapplyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/reapply" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginRedeploy - Shuts down the virtual machine, moves it to a new node, and powers it back on. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginRedeployOptions contains the optional parameters for the VirtualMachinesClient.BeginRedeploy +// method. +func (client *VirtualMachinesClient) BeginRedeploy(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginRedeployOptions) (*runtime.Poller[VirtualMachinesClientRedeployResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.redeploy(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Redeploy - Shuts down the virtual machine, moves it to a new node, and powers it back on. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) redeploy(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginRedeployOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginRedeploy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.redeployCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// redeployCreateRequest creates the Redeploy request. +func (client *VirtualMachinesClient) redeployCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginRedeployOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/redeploy" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginReimage - Reimages (upgrade the operating system) a virtual machine which don't have a ephemeral OS disk, for virtual +// machines who have a ephemeral OS disk the virtual machine is reset to initial state. NOTE: +// The retaining of old OS disk depends on the value of deleteOption of OS disk. If deleteOption is detach, the old OS disk +// will be preserved after reimage. If deleteOption is delete, the old OS disk +// will be deleted after reimage. The deleteOption of the OS disk should be updated accordingly before performing the reimage. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginReimageOptions contains the optional parameters for the VirtualMachinesClient.BeginReimage +// method. +func (client *VirtualMachinesClient) BeginReimage(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginReimageOptions) (*runtime.Poller[VirtualMachinesClientReimageResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reimage(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reimage - Reimages (upgrade the operating system) a virtual machine which don't have a ephemeral OS disk, for virtual machines +// who have a ephemeral OS disk the virtual machine is reset to initial state. NOTE: +// The retaining of old OS disk depends on the value of deleteOption of OS disk. If deleteOption is detach, the old OS disk +// will be preserved after reimage. If deleteOption is delete, the old OS disk +// will be deleted after reimage. The deleteOption of the OS disk should be updated accordingly before performing the reimage. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) reimage(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginReimageOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginReimage" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// reimageCreateRequest creates the Reimage request. +func (client *VirtualMachinesClient) reimageCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginReimageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/reimage" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-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 +} + +// BeginRestart - The operation to restart a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginRestartOptions contains the optional parameters for the VirtualMachinesClient.BeginRestart +// method. +func (client *VirtualMachinesClient) BeginRestart(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginRestartOptions) (*runtime.Poller[VirtualMachinesClientRestartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restart(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restart - The operation to restart a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) restart(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginRestartOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginRestart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restartCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// restartCreateRequest creates the Restart request. +func (client *VirtualMachinesClient) restartCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginRestartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/restart" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// RetrieveBootDiagnosticsData - The operation to retrieve SAS URIs for a virtual machine's boot diagnostic logs. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientRetrieveBootDiagnosticsDataOptions contains the optional parameters for the VirtualMachinesClient.RetrieveBootDiagnosticsData +// method. +func (client *VirtualMachinesClient) RetrieveBootDiagnosticsData(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientRetrieveBootDiagnosticsDataOptions) (VirtualMachinesClientRetrieveBootDiagnosticsDataResponse, error) { + var err error + const operationName = "VirtualMachinesClient.RetrieveBootDiagnosticsData" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.retrieveBootDiagnosticsDataCreateRequest(ctx, resourceGroupName, vmName, options) + if err != nil { + return VirtualMachinesClientRetrieveBootDiagnosticsDataResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientRetrieveBootDiagnosticsDataResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachinesClientRetrieveBootDiagnosticsDataResponse{}, err + } + resp, err := client.retrieveBootDiagnosticsDataHandleResponse(httpResp) + return resp, err +} + +// retrieveBootDiagnosticsDataCreateRequest creates the RetrieveBootDiagnosticsData request. +func (client *VirtualMachinesClient) retrieveBootDiagnosticsDataCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientRetrieveBootDiagnosticsDataOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/retrieveBootDiagnosticsData" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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() + if options != nil && options.SasURIExpirationTimeInMinutes != nil { + reqQP.Set("sasUriExpirationTimeInMinutes", strconv.FormatInt(int64(*options.SasURIExpirationTimeInMinutes), 10)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// retrieveBootDiagnosticsDataHandleResponse handles the RetrieveBootDiagnosticsData response. +func (client *VirtualMachinesClient) retrieveBootDiagnosticsDataHandleResponse(resp *http.Response) (VirtualMachinesClientRetrieveBootDiagnosticsDataResponse, error) { + result := VirtualMachinesClientRetrieveBootDiagnosticsDataResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RetrieveBootDiagnosticsDataResult); err != nil { + return VirtualMachinesClientRetrieveBootDiagnosticsDataResponse{}, err + } + return result, nil +} + +// BeginRunCommand - Run command on the VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - parameters - Parameters supplied to the Run command operation. +// - options - VirtualMachinesClientBeginRunCommandOptions contains the optional parameters for the VirtualMachinesClient.BeginRunCommand +// method. +func (client *VirtualMachinesClient) BeginRunCommand(ctx context.Context, resourceGroupName string, vmName string, parameters RunCommandInput, options *VirtualMachinesClientBeginRunCommandOptions) (*runtime.Poller[VirtualMachinesClientRunCommandResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.runCommand(ctx, resourceGroupName, vmName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientRunCommandResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientRunCommandResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RunCommand - Run command on the VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) runCommand(ctx context.Context, resourceGroupName string, vmName string, parameters RunCommandInput, options *VirtualMachinesClientBeginRunCommandOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginRunCommand" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.runCommandCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// runCommandCreateRequest creates the RunCommand request. +func (client *VirtualMachinesClient) runCommandCreateRequest(ctx context.Context, resourceGroupName string, vmName string, parameters RunCommandInput, options *VirtualMachinesClientBeginRunCommandOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommand" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// SimulateEviction - The operation to simulate the eviction of spot virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientSimulateEvictionOptions contains the optional parameters for the VirtualMachinesClient.SimulateEviction +// method. +func (client *VirtualMachinesClient) SimulateEviction(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientSimulateEvictionOptions) (VirtualMachinesClientSimulateEvictionResponse, error) { + var err error + const operationName = "VirtualMachinesClient.SimulateEviction" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.simulateEvictionCreateRequest(ctx, resourceGroupName, vmName, options) + if err != nil { + return VirtualMachinesClientSimulateEvictionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientSimulateEvictionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return VirtualMachinesClientSimulateEvictionResponse{}, err + } + return VirtualMachinesClientSimulateEvictionResponse{}, nil +} + +// simulateEvictionCreateRequest creates the SimulateEviction request. +func (client *VirtualMachinesClient) simulateEvictionCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientSimulateEvictionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/simulateEviction" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStart - The operation to start a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - options - VirtualMachinesClientBeginStartOptions contains the optional parameters for the VirtualMachinesClient.BeginStart +// method. +func (client *VirtualMachinesClient) BeginStart(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginStartOptions) (*runtime.Poller[VirtualMachinesClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, vmName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - The operation to start a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) start(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, vmName, 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 +} + +// startCreateRequest creates the Start request. +func (client *VirtualMachinesClient) startCreateRequest(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/start" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - The operation to update a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmName - The name of the virtual machine. +// - parameters - Parameters supplied to the Update Virtual Machine operation. +// - options - VirtualMachinesClientBeginUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginUpdate +// method. +func (client *VirtualMachinesClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachineUpdate, options *VirtualMachinesClientBeginUpdateOptions) (*runtime.Poller[VirtualMachinesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - The operation to update a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachinesClient) update(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachineUpdate, options *VirtualMachinesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.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, vmName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *VirtualMachinesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, parameters VirtualMachineUpdate, options *VirtualMachinesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + 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/compute/armcompute/v5/virtualmachinescalesetextensions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetextensions_client.go new file mode 100644 index 000000000..585b42657 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetextensions_client.go @@ -0,0 +1,434 @@ +//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 armcompute + +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" +) + +// VirtualMachineScaleSetExtensionsClient contains the methods for the VirtualMachineScaleSetExtensions group. +// Don't use this type directly, use NewVirtualMachineScaleSetExtensionsClient() instead. +type VirtualMachineScaleSetExtensionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineScaleSetExtensionsClient creates a new instance of VirtualMachineScaleSetExtensionsClient 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 NewVirtualMachineScaleSetExtensionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineScaleSetExtensionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineScaleSetExtensionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update an extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set where the extension should be create or updated. +// - vmssExtensionName - The name of the VM scale set extension. +// - extensionParameters - Parameters supplied to the Create VM scale set Extension operation. +// - options - VirtualMachineScaleSetExtensionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachineScaleSetExtensionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtension, options *VirtualMachineScaleSetExtensionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetExtensionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetExtensionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetExtensionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update an extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetExtensionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtension, options *VirtualMachineScaleSetExtensionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetExtensionsClient.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, vmScaleSetName, vmssExtensionName, extensionParameters, 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 *VirtualMachineScaleSetExtensionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtension, options *VirtualMachineScaleSetExtensionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions/{vmssExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if vmssExtensionName == "" { + return nil, errors.New("parameter vmssExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmssExtensionName}", url.PathEscape(vmssExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - The operation to delete the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set where the extension should be deleted. +// - vmssExtensionName - The name of the VM scale set extension. +// - options - VirtualMachineScaleSetExtensionsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.BeginDelete +// method. +func (client *VirtualMachineScaleSetExtensionsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, options *VirtualMachineScaleSetExtensionsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineScaleSetExtensionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmScaleSetName, vmssExtensionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetExtensionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetExtensionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetExtensionsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, options *VirtualMachineScaleSetExtensionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetExtensionsClient.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, vmScaleSetName, vmssExtensionName, 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 *VirtualMachineScaleSetExtensionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, options *VirtualMachineScaleSetExtensionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions/{vmssExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if vmssExtensionName == "" { + return nil, errors.New("parameter vmssExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmssExtensionName}", url.PathEscape(vmssExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - The operation to get the extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set containing the extension. +// - vmssExtensionName - The name of the VM scale set extension. +// - options - VirtualMachineScaleSetExtensionsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.Get +// method. +func (client *VirtualMachineScaleSetExtensionsClient) Get(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, options *VirtualMachineScaleSetExtensionsClientGetOptions) (VirtualMachineScaleSetExtensionsClientGetResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetExtensionsClient.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, vmScaleSetName, vmssExtensionName, options) + if err != nil { + return VirtualMachineScaleSetExtensionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetExtensionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetExtensionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineScaleSetExtensionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, options *VirtualMachineScaleSetExtensionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions/{vmssExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if vmssExtensionName == "" { + return nil, errors.New("parameter vmssExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmssExtensionName}", url.PathEscape(vmssExtensionName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineScaleSetExtensionsClient) getHandleResponse(resp *http.Response) (VirtualMachineScaleSetExtensionsClientGetResponse, error) { + result := VirtualMachineScaleSetExtensionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetExtension); err != nil { + return VirtualMachineScaleSetExtensionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of all extensions in a VM scale set. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set containing the extension. +// - options - VirtualMachineScaleSetExtensionsClientListOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.NewListPager +// method. +func (client *VirtualMachineScaleSetExtensionsClient) NewListPager(resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetExtensionsClientListOptions) *runtime.Pager[VirtualMachineScaleSetExtensionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetExtensionsClientListResponse]{ + More: func(page VirtualMachineScaleSetExtensionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetExtensionsClientListResponse) (VirtualMachineScaleSetExtensionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetExtensionsClient.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, vmScaleSetName, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetExtensionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineScaleSetExtensionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetExtensionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineScaleSetExtensionsClient) listHandleResponse(resp *http.Response) (VirtualMachineScaleSetExtensionsClientListResponse, error) { + result := VirtualMachineScaleSetExtensionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetExtensionListResult); err != nil { + return VirtualMachineScaleSetExtensionsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - The operation to update an extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set where the extension should be updated. +// - vmssExtensionName - The name of the VM scale set extension. +// - extensionParameters - Parameters supplied to the Update VM scale set Extension operation. +// - options - VirtualMachineScaleSetExtensionsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetExtensionsClient.BeginUpdate +// method. +func (client *VirtualMachineScaleSetExtensionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtensionUpdate, options *VirtualMachineScaleSetExtensionsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetExtensionsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetExtensionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetExtensionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - The operation to update an extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetExtensionsClient) update(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtensionUpdate, options *VirtualMachineScaleSetExtensionsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetExtensionsClient.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, vmScaleSetName, vmssExtensionName, extensionParameters, 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 *VirtualMachineScaleSetExtensionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtensionUpdate, options *VirtualMachineScaleSetExtensionsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions/{vmssExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if vmssExtensionName == "" { + return nil, errors.New("parameter vmssExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmssExtensionName}", url.PathEscape(vmssExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetrollingupgrades_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetrollingupgrades_client.go new file mode 100644 index 000000000..9ef8a1902 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetrollingupgrades_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 armcompute + +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" +) + +// VirtualMachineScaleSetRollingUpgradesClient contains the methods for the VirtualMachineScaleSetRollingUpgrades group. +// Don't use this type directly, use NewVirtualMachineScaleSetRollingUpgradesClient() instead. +type VirtualMachineScaleSetRollingUpgradesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineScaleSetRollingUpgradesClient creates a new instance of VirtualMachineScaleSetRollingUpgradesClient 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 NewVirtualMachineScaleSetRollingUpgradesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineScaleSetRollingUpgradesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineScaleSetRollingUpgradesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCancel - Cancels the current virtual machine scale set rolling upgrade. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetRollingUpgradesClientBeginCancelOptions contains the optional parameters for the VirtualMachineScaleSetRollingUpgradesClient.BeginCancel +// method. +func (client *VirtualMachineScaleSetRollingUpgradesClient) BeginCancel(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginCancelOptions) (*runtime.Poller[VirtualMachineScaleSetRollingUpgradesClientCancelResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.cancel(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetRollingUpgradesClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetRollingUpgradesClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Cancel - Cancels the current virtual machine scale set rolling upgrade. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetRollingUpgradesClient) cancel(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginCancelOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetRollingUpgradesClient.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, vmScaleSetName, 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 *VirtualMachineScaleSetRollingUpgradesClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginCancelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/rollingUpgrades/cancel" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// GetLatest - Gets the status of the latest virtual machine scale set rolling upgrade. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetRollingUpgradesClientGetLatestOptions contains the optional parameters for the VirtualMachineScaleSetRollingUpgradesClient.GetLatest +// method. +func (client *VirtualMachineScaleSetRollingUpgradesClient) GetLatest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientGetLatestOptions) (VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetRollingUpgradesClient.GetLatest" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getLatestCreateRequest(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse{}, err + } + resp, err := client.getLatestHandleResponse(httpResp) + return resp, err +} + +// getLatestCreateRequest creates the GetLatest request. +func (client *VirtualMachineScaleSetRollingUpgradesClient) getLatestCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientGetLatestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/rollingUpgrades/latest" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getLatestHandleResponse handles the GetLatest response. +func (client *VirtualMachineScaleSetRollingUpgradesClient) getLatestHandleResponse(resp *http.Response) (VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse, error) { + result := VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RollingUpgradeStatusInfo); err != nil { + return VirtualMachineScaleSetRollingUpgradesClientGetLatestResponse{}, err + } + return result, nil +} + +// BeginStartExtensionUpgrade - Starts a rolling upgrade to move all extensions for all virtual machine scale set instances +// to the latest available extension version. Instances which are already running the latest extension versions +// are not affected. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetRollingUpgradesClientBeginStartExtensionUpgradeOptions contains the optional parameters +// for the VirtualMachineScaleSetRollingUpgradesClient.BeginStartExtensionUpgrade method. +func (client *VirtualMachineScaleSetRollingUpgradesClient) BeginStartExtensionUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginStartExtensionUpgradeOptions) (*runtime.Poller[VirtualMachineScaleSetRollingUpgradesClientStartExtensionUpgradeResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.startExtensionUpgrade(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetRollingUpgradesClientStartExtensionUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetRollingUpgradesClientStartExtensionUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StartExtensionUpgrade - Starts a rolling upgrade to move all extensions for all virtual machine scale set instances to +// the latest available extension version. Instances which are already running the latest extension versions +// are not affected. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetRollingUpgradesClient) startExtensionUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginStartExtensionUpgradeOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetRollingUpgradesClient.BeginStartExtensionUpgrade" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startExtensionUpgradeCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// startExtensionUpgradeCreateRequest creates the StartExtensionUpgrade request. +func (client *VirtualMachineScaleSetRollingUpgradesClient) startExtensionUpgradeCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginStartExtensionUpgradeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensionRollingUpgrade" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStartOSUpgrade - Starts a rolling upgrade to move all virtual machine scale set instances to the latest available +// Platform Image OS version. Instances which are already running the latest available OS version are not +// affected. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetRollingUpgradesClientBeginStartOSUpgradeOptions contains the optional parameters for the +// VirtualMachineScaleSetRollingUpgradesClient.BeginStartOSUpgrade method. +func (client *VirtualMachineScaleSetRollingUpgradesClient) BeginStartOSUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginStartOSUpgradeOptions) (*runtime.Poller[VirtualMachineScaleSetRollingUpgradesClientStartOSUpgradeResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.startOSUpgrade(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetRollingUpgradesClientStartOSUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetRollingUpgradesClientStartOSUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StartOSUpgrade - Starts a rolling upgrade to move all virtual machine scale set instances to the latest available Platform +// Image OS version. Instances which are already running the latest available OS version are not +// affected. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetRollingUpgradesClient) startOSUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginStartOSUpgradeOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetRollingUpgradesClient.BeginStartOSUpgrade" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startOSUpgradeCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// startOSUpgradeCreateRequest creates the StartOSUpgrade request. +func (client *VirtualMachineScaleSetRollingUpgradesClient) startOSUpgradeCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetRollingUpgradesClientBeginStartOSUpgradeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/osRollingUpgrade" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-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/compute/armcompute/v5/virtualmachinescalesets_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesets_client.go new file mode 100644 index 000000000..eb6506c15 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesets_client.go @@ -0,0 +1,1957 @@ +//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 armcompute + +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" +) + +// VirtualMachineScaleSetsClient contains the methods for the VirtualMachineScaleSets group. +// Don't use this type directly, use NewVirtualMachineScaleSetsClient() instead. +type VirtualMachineScaleSetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineScaleSetsClient creates a new instance of VirtualMachineScaleSetsClient 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 NewVirtualMachineScaleSetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineScaleSetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineScaleSetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginApproveRollingUpgrade - Approve upgrade on deferred rolling upgrades for OS disks in the virtual machines in a VM +// scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginApproveRollingUpgradeOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginApproveRollingUpgrade +// method. +func (client *VirtualMachineScaleSetsClient) BeginApproveRollingUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginApproveRollingUpgradeOptions) (*runtime.Poller[VirtualMachineScaleSetsClientApproveRollingUpgradeResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.approveRollingUpgrade(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientApproveRollingUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientApproveRollingUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ApproveRollingUpgrade - Approve upgrade on deferred rolling upgrades for OS disks in the virtual machines in a VM scale +// set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) approveRollingUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginApproveRollingUpgradeOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginApproveRollingUpgrade" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.approveRollingUpgradeCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// approveRollingUpgradeCreateRequest creates the ApproveRollingUpgrade request. +func (client *VirtualMachineScaleSetsClient) approveRollingUpgradeCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginApproveRollingUpgradeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/approveRollingUpgrade" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// ConvertToSinglePlacementGroup - Converts SinglePlacementGroup property to false for a existing virtual machine scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the virtual machine scale set to create or update. +// - parameters - The input object for ConvertToSinglePlacementGroup API. +// - options - VirtualMachineScaleSetsClientConvertToSinglePlacementGroupOptions contains the optional parameters for the VirtualMachineScaleSetsClient.ConvertToSinglePlacementGroup +// method. +func (client *VirtualMachineScaleSetsClient) ConvertToSinglePlacementGroup(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VMScaleSetConvertToSinglePlacementGroupInput, options *VirtualMachineScaleSetsClientConvertToSinglePlacementGroupOptions) (VirtualMachineScaleSetsClientConvertToSinglePlacementGroupResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.ConvertToSinglePlacementGroup" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.convertToSinglePlacementGroupCreateRequest(ctx, resourceGroupName, vmScaleSetName, parameters, options) + if err != nil { + return VirtualMachineScaleSetsClientConvertToSinglePlacementGroupResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetsClientConvertToSinglePlacementGroupResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetsClientConvertToSinglePlacementGroupResponse{}, err + } + return VirtualMachineScaleSetsClientConvertToSinglePlacementGroupResponse{}, nil +} + +// convertToSinglePlacementGroupCreateRequest creates the ConvertToSinglePlacementGroup request. +func (client *VirtualMachineScaleSetsClient) convertToSinglePlacementGroupCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VMScaleSetConvertToSinglePlacementGroupInput, options *VirtualMachineScaleSetsClientConvertToSinglePlacementGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/convertToSinglePlacementGroup" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-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 +} + +// BeginCreateOrUpdate - Create or update a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set to create or update. +// - parameters - The scale set object. +// - options - VirtualMachineScaleSetsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachineScaleSetsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VirtualMachineScaleSet, options *VirtualMachineScaleSetsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmScaleSetName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VirtualMachineScaleSet, options *VirtualMachineScaleSetsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.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, vmScaleSetName, 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 *VirtualMachineScaleSetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VirtualMachineScaleSet, options *VirtualMachineScaleSetsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDeallocate - Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and releases +// the compute resources. You are not billed for the compute resources that this virtual machine +// scale set deallocates. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginDeallocateOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginDeallocate +// method. +func (client *VirtualMachineScaleSetsClient) BeginDeallocate(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginDeallocateOptions) (*runtime.Poller[VirtualMachineScaleSetsClientDeallocateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deallocate(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientDeallocateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientDeallocateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Deallocate - Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and releases the +// compute resources. You are not billed for the compute resources that this virtual machine +// scale set deallocates. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) deallocate(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginDeallocateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginDeallocate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deallocateCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// deallocateCreateRequest creates the Deallocate request. +func (client *VirtualMachineScaleSetsClient) deallocateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginDeallocateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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() + if options != nil && options.Hibernate != nil { + reqQP.Set("hibernate", strconv.FormatBool(*options.Hibernate)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginDelete - Deletes a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginDelete +// method. +func (client *VirtualMachineScaleSetsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineScaleSetsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.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, vmScaleSetName, 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 *VirtualMachineScaleSetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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() + if options != nil && options.ForceDeletion != nil { + reqQP.Set("forceDeletion", strconv.FormatBool(*options.ForceDeletion)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDeleteInstances - Deletes virtual machines in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - vmInstanceIDs - A list of virtual machine instance IDs from the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginDeleteInstancesOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginDeleteInstances +// method. +func (client *VirtualMachineScaleSetsClient) BeginDeleteInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, options *VirtualMachineScaleSetsClientBeginDeleteInstancesOptions) (*runtime.Poller[VirtualMachineScaleSetsClientDeleteInstancesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteInstances(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientDeleteInstancesResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientDeleteInstancesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeleteInstances - Deletes virtual machines in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) deleteInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, options *VirtualMachineScaleSetsClientBeginDeleteInstancesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginDeleteInstances" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteInstancesCreateRequest(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs, 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 +} + +// deleteInstancesCreateRequest creates the DeleteInstances request. +func (client *VirtualMachineScaleSetsClient) deleteInstancesCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, options *VirtualMachineScaleSetsClientBeginDeleteInstancesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/delete" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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() + if options != nil && options.ForceDeletion != nil { + reqQP.Set("forceDeletion", strconv.FormatBool(*options.ForceDeletion)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vmInstanceIDs); err != nil { + return nil, err + } + return req, nil +} + +// ForceRecoveryServiceFabricPlatformUpdateDomainWalk - Manual platform update domain walk to update virtual machines in a +// service fabric virtual machine scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - platformUpdateDomain - The platform update domain for which a manual recovery walk is requested +// - options - VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkOptions contains the optional +// parameters for the VirtualMachineScaleSetsClient.ForceRecoveryServiceFabricPlatformUpdateDomainWalk method. +func (client *VirtualMachineScaleSetsClient) ForceRecoveryServiceFabricPlatformUpdateDomainWalk(ctx context.Context, resourceGroupName string, vmScaleSetName string, platformUpdateDomain int32, options *VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkOptions) (VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.ForceRecoveryServiceFabricPlatformUpdateDomainWalk" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.forceRecoveryServiceFabricPlatformUpdateDomainWalkCreateRequest(ctx, resourceGroupName, vmScaleSetName, platformUpdateDomain, options) + if err != nil { + return VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse{}, err + } + resp, err := client.forceRecoveryServiceFabricPlatformUpdateDomainWalkHandleResponse(httpResp) + return resp, err +} + +// forceRecoveryServiceFabricPlatformUpdateDomainWalkCreateRequest creates the ForceRecoveryServiceFabricPlatformUpdateDomainWalk request. +func (client *VirtualMachineScaleSetsClient) forceRecoveryServiceFabricPlatformUpdateDomainWalkCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, platformUpdateDomain int32, options *VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/forceRecoveryServiceFabricPlatformUpdateDomainWalk" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + reqQP.Set("platformUpdateDomain", strconv.FormatInt(int64(platformUpdateDomain), 10)) + if options != nil && options.Zone != nil { + reqQP.Set("zone", *options.Zone) + } + if options != nil && options.PlacementGroupID != nil { + reqQP.Set("placementGroupId", *options.PlacementGroupID) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// forceRecoveryServiceFabricPlatformUpdateDomainWalkHandleResponse handles the ForceRecoveryServiceFabricPlatformUpdateDomainWalk response. +func (client *VirtualMachineScaleSetsClient) forceRecoveryServiceFabricPlatformUpdateDomainWalkHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse, error) { + result := VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RecoveryWalkResponse); err != nil { + return VirtualMachineScaleSetsClientForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse{}, err + } + return result, nil +} + +// Get - Display information about a virtual machine scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetsClient.Get +// method. +func (client *VirtualMachineScaleSetsClient) Get(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientGetOptions) (VirtualMachineScaleSetsClientGetResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.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, vmScaleSetName, options) + if err != nil { + return VirtualMachineScaleSetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineScaleSetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-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 +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineScaleSetsClient) getHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientGetResponse, error) { + result := VirtualMachineScaleSetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSet); err != nil { + return VirtualMachineScaleSetsClientGetResponse{}, err + } + return result, nil +} + +// GetInstanceView - Gets the status of a VM scale set instance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientGetInstanceViewOptions contains the optional parameters for the VirtualMachineScaleSetsClient.GetInstanceView +// method. +func (client *VirtualMachineScaleSetsClient) GetInstanceView(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientGetInstanceViewOptions) (VirtualMachineScaleSetsClientGetInstanceViewResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.GetInstanceView" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getInstanceViewCreateRequest(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return VirtualMachineScaleSetsClientGetInstanceViewResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetsClientGetInstanceViewResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetsClientGetInstanceViewResponse{}, err + } + resp, err := client.getInstanceViewHandleResponse(httpResp) + return resp, err +} + +// getInstanceViewCreateRequest creates the GetInstanceView request. +func (client *VirtualMachineScaleSetsClient) getInstanceViewCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientGetInstanceViewOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/instanceView" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getInstanceViewHandleResponse handles the GetInstanceView response. +func (client *VirtualMachineScaleSetsClient) getInstanceViewHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientGetInstanceViewResponse, error) { + result := VirtualMachineScaleSetsClientGetInstanceViewResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetInstanceView); err != nil { + return VirtualMachineScaleSetsClientGetInstanceViewResponse{}, err + } + return result, nil +} + +// NewGetOSUpgradeHistoryPager - Gets list of OS upgrades on a VM scale set instance. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientGetOSUpgradeHistoryOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewGetOSUpgradeHistoryPager +// method. +func (client *VirtualMachineScaleSetsClient) NewGetOSUpgradeHistoryPager(resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientGetOSUpgradeHistoryOptions) *runtime.Pager[VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse]{ + More: func(page VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse) (VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetsClient.NewGetOSUpgradeHistoryPager") + 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.getOSUpgradeHistoryCreateRequest(ctx, resourceGroupName, vmScaleSetName, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse{}, err + } + return client.getOSUpgradeHistoryHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// getOSUpgradeHistoryCreateRequest creates the GetOSUpgradeHistory request. +func (client *VirtualMachineScaleSetsClient) getOSUpgradeHistoryCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientGetOSUpgradeHistoryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/osUpgradeHistory" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getOSUpgradeHistoryHandleResponse handles the GetOSUpgradeHistory response. +func (client *VirtualMachineScaleSetsClient) getOSUpgradeHistoryHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse, error) { + result := VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetListOSUpgradeHistory); err != nil { + return VirtualMachineScaleSetsClientGetOSUpgradeHistoryResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of all VM scale sets under a resource group. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualMachineScaleSetsClientListOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListPager +// method. +func (client *VirtualMachineScaleSetsClient) NewListPager(resourceGroupName string, options *VirtualMachineScaleSetsClientListOptions) *runtime.Pager[VirtualMachineScaleSetsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetsClientListResponse]{ + More: func(page VirtualMachineScaleSetsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetsClientListResponse) (VirtualMachineScaleSetsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetsClient.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, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineScaleSetsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualMachineScaleSetsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineScaleSetsClient) listHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientListResponse, error) { + result := VirtualMachineScaleSetsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetListResult); err != nil { + return VirtualMachineScaleSetsClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets a list of all VM Scale Sets in the subscription, regardless of the associated resource group. Use +// nextLink property in the response to get the next page of VM Scale Sets. Do this till nextLink is +// null to fetch all the VM Scale Sets. +// +// Generated from API version 2023-09-01 +// - options - VirtualMachineScaleSetsClientListAllOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListAllPager +// method. +func (client *VirtualMachineScaleSetsClient) NewListAllPager(options *VirtualMachineScaleSetsClientListAllOptions) *runtime.Pager[VirtualMachineScaleSetsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetsClientListAllResponse]{ + More: func(page VirtualMachineScaleSetsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetsClientListAllResponse) (VirtualMachineScaleSetsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *VirtualMachineScaleSetsClient) listAllCreateRequest(ctx context.Context, options *VirtualMachineScaleSetsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *VirtualMachineScaleSetsClient) listAllHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientListAllResponse, error) { + result := VirtualMachineScaleSetsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetListWithLinkResult); err != nil { + return VirtualMachineScaleSetsClientListAllResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - Gets all the VM scale sets under the specified subscription for the specified location. +// +// Generated from API version 2023-09-01 +// - location - The location for which VM scale sets under the subscription are queried. +// - options - VirtualMachineScaleSetsClientListByLocationOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListByLocationPager +// method. +func (client *VirtualMachineScaleSetsClient) NewListByLocationPager(location string, options *VirtualMachineScaleSetsClientListByLocationOptions) *runtime.Pager[VirtualMachineScaleSetsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetsClientListByLocationResponse]{ + More: func(page VirtualMachineScaleSetsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetsClientListByLocationResponse) (VirtualMachineScaleSetsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetsClient.NewListByLocationPager") + 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.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *VirtualMachineScaleSetsClient) listByLocationCreateRequest(ctx context.Context, location string, options *VirtualMachineScaleSetsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/virtualMachineScaleSets" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *VirtualMachineScaleSetsClient) listByLocationHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientListByLocationResponse, error) { + result := VirtualMachineScaleSetsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetListResult); err != nil { + return VirtualMachineScaleSetsClientListByLocationResponse{}, err + } + return result, nil +} + +// NewListSKUsPager - Gets a list of SKUs available for your VM scale set, including the minimum and maximum VM instances +// allowed for each SKU. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientListSKUsOptions contains the optional parameters for the VirtualMachineScaleSetsClient.NewListSKUsPager +// method. +func (client *VirtualMachineScaleSetsClient) NewListSKUsPager(resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientListSKUsOptions) *runtime.Pager[VirtualMachineScaleSetsClientListSKUsResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetsClientListSKUsResponse]{ + More: func(page VirtualMachineScaleSetsClientListSKUsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetsClientListSKUsResponse) (VirtualMachineScaleSetsClientListSKUsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetsClient.NewListSKUsPager") + 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.listSKUsCreateRequest(ctx, resourceGroupName, vmScaleSetName, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetsClientListSKUsResponse{}, err + } + return client.listSKUsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listSKUsCreateRequest creates the ListSKUs request. +func (client *VirtualMachineScaleSetsClient) listSKUsCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientListSKUsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/skus" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSKUsHandleResponse handles the ListSKUs response. +func (client *VirtualMachineScaleSetsClient) listSKUsHandleResponse(resp *http.Response) (VirtualMachineScaleSetsClientListSKUsResponse, error) { + result := VirtualMachineScaleSetsClientListSKUsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetListSKUsResult); err != nil { + return VirtualMachineScaleSetsClientListSKUsResponse{}, err + } + return result, nil +} + +// BeginPerformMaintenance - Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances +// which are not eligible for perform maintenance will be failed. Please refer to best practices for more +// details: https://docs.microsoft.com/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginPerformMaintenanceOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginPerformMaintenance +// method. +func (client *VirtualMachineScaleSetsClient) BeginPerformMaintenance(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginPerformMaintenanceOptions) (*runtime.Poller[VirtualMachineScaleSetsClientPerformMaintenanceResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.performMaintenance(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientPerformMaintenanceResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientPerformMaintenanceResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PerformMaintenance - Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances which +// are not eligible for perform maintenance will be failed. Please refer to best practices for more +// details: https://docs.microsoft.com/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) performMaintenance(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginPerformMaintenanceOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginPerformMaintenance" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.performMaintenanceCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// performMaintenanceCreateRequest creates the PerformMaintenance request. +func (client *VirtualMachineScaleSetsClient) performMaintenanceCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginPerformMaintenanceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/performMaintenance" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginPowerOff - Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still attached +// and you are getting charged for the resources. Instead, use deallocate to release resources and +// avoid charges. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginPowerOffOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginPowerOff +// method. +func (client *VirtualMachineScaleSetsClient) BeginPowerOff(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginPowerOffOptions) (*runtime.Poller[VirtualMachineScaleSetsClientPowerOffResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.powerOff(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PowerOff - Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still attached and +// you are getting charged for the resources. Instead, use deallocate to release resources and +// avoid charges. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) powerOff(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginPowerOffOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginPowerOff" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.powerOffCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// powerOffCreateRequest creates the PowerOff request. +func (client *VirtualMachineScaleSetsClient) powerOffCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginPowerOffOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/poweroff" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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() + if options != nil && options.SkipShutdown != nil { + reqQP.Set("skipShutdown", strconv.FormatBool(*options.SkipShutdown)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginReapply - Reapplies the Virtual Machine Scale Set Virtual Machine Profile to the Virtual Machine Instances +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginReapplyOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginReapply +// method. +func (client *VirtualMachineScaleSetsClient) BeginReapply(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReapplyOptions) (*runtime.Poller[VirtualMachineScaleSetsClientReapplyResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reapply(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientReapplyResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientReapplyResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reapply - Reapplies the Virtual Machine Scale Set Virtual Machine Profile to the Virtual Machine Instances +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) reapply(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReapplyOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginReapply" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reapplyCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// reapplyCreateRequest creates the Reapply request. +func (client *VirtualMachineScaleSetsClient) reapplyCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReapplyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reapply" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginRedeploy - Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and powers +// them back on. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginRedeployOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginRedeploy +// method. +func (client *VirtualMachineScaleSetsClient) BeginRedeploy(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginRedeployOptions) (*runtime.Poller[VirtualMachineScaleSetsClientRedeployResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.redeploy(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Redeploy - Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and powers them +// back on. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) redeploy(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginRedeployOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginRedeploy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.redeployCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// redeployCreateRequest creates the Redeploy request. +func (client *VirtualMachineScaleSetsClient) redeployCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginRedeployOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/redeploy" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginReimage - Reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't have +// a ephemeral OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is +// reset to initial state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginReimageOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginReimage +// method. +func (client *VirtualMachineScaleSetsClient) BeginReimage(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReimageOptions) (*runtime.Poller[VirtualMachineScaleSetsClientReimageResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reimage(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reimage - Reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't have a ephemeral +// OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is +// reset to initial state. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) reimage(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReimageOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginReimage" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// reimageCreateRequest creates the Reimage request. +func (client *VirtualMachineScaleSetsClient) reimageCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReimageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimage" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMScaleSetReimageInput != nil { + if err := runtime.MarshalAsJSON(req, *options.VMScaleSetReimageInput); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginReimageAll - Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This operation +// is only supported for managed disks. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginReimageAllOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginReimageAll +// method. +func (client *VirtualMachineScaleSetsClient) BeginReimageAll(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReimageAllOptions) (*runtime.Poller[VirtualMachineScaleSetsClientReimageAllResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reimageAll(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientReimageAllResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientReimageAllResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ReimageAll - Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This operation +// is only supported for managed disks. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) reimageAll(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReimageAllOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginReimageAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageAllCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// reimageAllCreateRequest creates the ReimageAll request. +func (client *VirtualMachineScaleSetsClient) reimageAllCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginReimageAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimageall" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginRestart - Restarts one or more virtual machines in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginRestartOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginRestart +// method. +func (client *VirtualMachineScaleSetsClient) BeginRestart(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginRestartOptions) (*runtime.Poller[VirtualMachineScaleSetsClientRestartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restart(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restart - Restarts one or more virtual machines in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) restart(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginRestartOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginRestart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restartCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// restartCreateRequest creates the Restart request. +func (client *VirtualMachineScaleSetsClient) restartCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginRestartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/restart" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginSetOrchestrationServiceState - Changes ServiceState property for a given service +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the virtual machine scale set to create or update. +// - parameters - The input object for SetOrchestrationServiceState API. +// - options - VirtualMachineScaleSetsClientBeginSetOrchestrationServiceStateOptions contains the optional parameters for the +// VirtualMachineScaleSetsClient.BeginSetOrchestrationServiceState method. +func (client *VirtualMachineScaleSetsClient) BeginSetOrchestrationServiceState(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters OrchestrationServiceStateInput, options *VirtualMachineScaleSetsClientBeginSetOrchestrationServiceStateOptions) (*runtime.Poller[VirtualMachineScaleSetsClientSetOrchestrationServiceStateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.setOrchestrationServiceState(ctx, resourceGroupName, vmScaleSetName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientSetOrchestrationServiceStateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientSetOrchestrationServiceStateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// SetOrchestrationServiceState - Changes ServiceState property for a given service +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) setOrchestrationServiceState(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters OrchestrationServiceStateInput, options *VirtualMachineScaleSetsClientBeginSetOrchestrationServiceStateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginSetOrchestrationServiceState" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setOrchestrationServiceStateCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// setOrchestrationServiceStateCreateRequest creates the SetOrchestrationServiceState request. +func (client *VirtualMachineScaleSetsClient) setOrchestrationServiceStateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters OrchestrationServiceStateInput, options *VirtualMachineScaleSetsClientBeginSetOrchestrationServiceStateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/setOrchestrationServiceState" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-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 +} + +// BeginStart - Starts one or more virtual machines in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginStartOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginStart +// method. +func (client *VirtualMachineScaleSetsClient) BeginStart(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginStartOptions) (*runtime.Poller[VirtualMachineScaleSetsClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, vmScaleSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - Starts one or more virtual machines in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) start(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, vmScaleSetName, 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 +} + +// startCreateRequest creates the Start request. +func (client *VirtualMachineScaleSetsClient) startCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/start" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMInstanceIDs != nil { + if err := runtime.MarshalAsJSON(req, *options.VMInstanceIDs); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginUpdate - Update a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set to create or update. +// - parameters - The scale set object. +// - options - VirtualMachineScaleSetsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginUpdate +// method. +func (client *VirtualMachineScaleSetsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VirtualMachineScaleSetUpdate, options *VirtualMachineScaleSetsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmScaleSetName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) update(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VirtualMachineScaleSetUpdate, options *VirtualMachineScaleSetsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.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, vmScaleSetName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *VirtualMachineScaleSetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, parameters VirtualMachineScaleSetUpdate, options *VirtualMachineScaleSetsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdateInstances - Upgrades one or more virtual machines to the latest SKU set in the VM scale set model. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - vmInstanceIDs - A list of virtual machine instance IDs from the VM scale set. +// - options - VirtualMachineScaleSetsClientBeginUpdateInstancesOptions contains the optional parameters for the VirtualMachineScaleSetsClient.BeginUpdateInstances +// method. +func (client *VirtualMachineScaleSetsClient) BeginUpdateInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, options *VirtualMachineScaleSetsClientBeginUpdateInstancesOptions) (*runtime.Poller[VirtualMachineScaleSetsClientUpdateInstancesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateInstances(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetsClientUpdateInstancesResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetsClientUpdateInstancesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateInstances - Upgrades one or more virtual machines to the latest SKU set in the VM scale set model. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetsClient) updateInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, options *VirtualMachineScaleSetsClientBeginUpdateInstancesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetsClient.BeginUpdateInstances" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateInstancesCreateRequest(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs, 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 +} + +// updateInstancesCreateRequest creates the UpdateInstances request. +func (client *VirtualMachineScaleSetsClient) updateInstancesCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, options *VirtualMachineScaleSetsClientBeginUpdateInstancesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/manualupgrade" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vmInstanceIDs); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvmextensions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvmextensions_client.go new file mode 100644 index 000000000..ff2347623 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvmextensions_client.go @@ -0,0 +1,462 @@ +//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 armcompute + +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" +) + +// VirtualMachineScaleSetVMExtensionsClient contains the methods for the VirtualMachineScaleSetVMExtensions group. +// Don't use this type directly, use NewVirtualMachineScaleSetVMExtensionsClient() instead. +type VirtualMachineScaleSetVMExtensionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineScaleSetVMExtensionsClient creates a new instance of VirtualMachineScaleSetVMExtensionsClient 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 NewVirtualMachineScaleSetVMExtensionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineScaleSetVMExtensionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineScaleSetVMExtensionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update the VMSS VM extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - vmExtensionName - The name of the virtual machine extension. +// - extensionParameters - Parameters supplied to the Create Virtual Machine Extension operation. +// - options - VirtualMachineScaleSetVMExtensionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachineScaleSetVMExtensionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, extensionParameters VirtualMachineScaleSetVMExtension, options *VirtualMachineScaleSetVMExtensionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetVMExtensionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmScaleSetName, instanceID, vmExtensionName, extensionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMExtensionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMExtensionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update the VMSS VM extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMExtensionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, extensionParameters VirtualMachineScaleSetVMExtension, options *VirtualMachineScaleSetVMExtensionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMExtensionsClient.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, vmScaleSetName, instanceID, vmExtensionName, extensionParameters, 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 *VirtualMachineScaleSetVMExtensionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, extensionParameters VirtualMachineScaleSetVMExtension, options *VirtualMachineScaleSetVMExtensionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - The operation to delete the VMSS VM extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - vmExtensionName - The name of the virtual machine extension. +// - options - VirtualMachineScaleSetVMExtensionsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.BeginDelete +// method. +func (client *VirtualMachineScaleSetVMExtensionsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, options *VirtualMachineScaleSetVMExtensionsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineScaleSetVMExtensionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmScaleSetName, instanceID, vmExtensionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMExtensionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMExtensionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete the VMSS VM extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMExtensionsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, options *VirtualMachineScaleSetVMExtensionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMExtensionsClient.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, vmScaleSetName, instanceID, vmExtensionName, 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 *VirtualMachineScaleSetVMExtensionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, options *VirtualMachineScaleSetVMExtensionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - The operation to get the VMSS VM extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - vmExtensionName - The name of the virtual machine extension. +// - options - VirtualMachineScaleSetVMExtensionsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.Get +// method. +func (client *VirtualMachineScaleSetVMExtensionsClient) Get(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, options *VirtualMachineScaleSetVMExtensionsClientGetOptions) (VirtualMachineScaleSetVMExtensionsClientGetResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetVMExtensionsClient.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, vmScaleSetName, instanceID, vmExtensionName, options) + if err != nil { + return VirtualMachineScaleSetVMExtensionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetVMExtensionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetVMExtensionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineScaleSetVMExtensionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, options *VirtualMachineScaleSetVMExtensionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineScaleSetVMExtensionsClient) getHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMExtensionsClientGetResponse, error) { + result := VirtualMachineScaleSetVMExtensionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetVMExtension); err != nil { + return VirtualMachineScaleSetVMExtensionsClientGetResponse{}, err + } + return result, nil +} + +// List - The operation to get all extensions of an instance in Virtual Machine Scaleset. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMExtensionsClientListOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.List +// method. +func (client *VirtualMachineScaleSetVMExtensionsClient) List(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMExtensionsClientListOptions) (VirtualMachineScaleSetVMExtensionsClientListResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetVMExtensionsClient.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, vmScaleSetName, instanceID, options) + if err != nil { + return VirtualMachineScaleSetVMExtensionsClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetVMExtensionsClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetVMExtensionsClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineScaleSetVMExtensionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMExtensionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/extensions" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineScaleSetVMExtensionsClient) listHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMExtensionsClientListResponse, error) { + result := VirtualMachineScaleSetVMExtensionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetVMExtensionsListResult); err != nil { + return VirtualMachineScaleSetVMExtensionsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - The operation to update the VMSS VM extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - vmExtensionName - The name of the virtual machine extension. +// - extensionParameters - Parameters supplied to the Update Virtual Machine Extension operation. +// - options - VirtualMachineScaleSetVMExtensionsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMExtensionsClient.BeginUpdate +// method. +func (client *VirtualMachineScaleSetVMExtensionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, extensionParameters VirtualMachineScaleSetVMExtensionUpdate, options *VirtualMachineScaleSetVMExtensionsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetVMExtensionsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmScaleSetName, instanceID, vmExtensionName, extensionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMExtensionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMExtensionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - The operation to update the VMSS VM extension. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMExtensionsClient) update(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, extensionParameters VirtualMachineScaleSetVMExtensionUpdate, options *VirtualMachineScaleSetVMExtensionsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMExtensionsClient.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, vmScaleSetName, instanceID, vmExtensionName, extensionParameters, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *VirtualMachineScaleSetVMExtensionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, vmExtensionName string, extensionParameters VirtualMachineScaleSetVMExtensionUpdate, options *VirtualMachineScaleSetVMExtensionsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/extensions/{vmExtensionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if vmExtensionName == "" { + return nil, errors.New("parameter vmExtensionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmExtensionName}", url.PathEscape(vmExtensionName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, extensionParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvmruncommands_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvmruncommands_client.go new file mode 100644 index 000000000..9736973fc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvmruncommands_client.go @@ -0,0 +1,462 @@ +//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 armcompute + +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" +) + +// VirtualMachineScaleSetVMRunCommandsClient contains the methods for the VirtualMachineScaleSetVMRunCommands group. +// Don't use this type directly, use NewVirtualMachineScaleSetVMRunCommandsClient() instead. +type VirtualMachineScaleSetVMRunCommandsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineScaleSetVMRunCommandsClient creates a new instance of VirtualMachineScaleSetVMRunCommandsClient 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 NewVirtualMachineScaleSetVMRunCommandsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineScaleSetVMRunCommandsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineScaleSetVMRunCommandsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update the VMSS VM run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - runCommandName - The name of the virtual machine run command. +// - runCommand - Parameters supplied to the Create Virtual Machine RunCommand operation. +// - options - VirtualMachineScaleSetVMRunCommandsClientBeginCreateOrUpdateOptions contains the optional parameters for the +// VirtualMachineScaleSetVMRunCommandsClient.BeginCreateOrUpdate method. +func (client *VirtualMachineScaleSetVMRunCommandsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, runCommand VirtualMachineRunCommand, options *VirtualMachineScaleSetVMRunCommandsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetVMRunCommandsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmScaleSetName, instanceID, runCommandName, runCommand, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMRunCommandsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMRunCommandsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update the VMSS VM run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMRunCommandsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, runCommand VirtualMachineRunCommand, options *VirtualMachineScaleSetVMRunCommandsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMRunCommandsClient.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, vmScaleSetName, instanceID, runCommandName, runCommand, 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 *VirtualMachineScaleSetVMRunCommandsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, runCommand VirtualMachineRunCommand, options *VirtualMachineScaleSetVMRunCommandsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + if err := runtime.MarshalAsJSON(req, runCommand); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - The operation to delete the VMSS VM run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - runCommandName - The name of the virtual machine run command. +// - options - VirtualMachineScaleSetVMRunCommandsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.BeginDelete +// method. +func (client *VirtualMachineScaleSetVMRunCommandsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, options *VirtualMachineScaleSetVMRunCommandsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineScaleSetVMRunCommandsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmScaleSetName, instanceID, runCommandName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMRunCommandsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMRunCommandsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The operation to delete the VMSS VM run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMRunCommandsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, options *VirtualMachineScaleSetVMRunCommandsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMRunCommandsClient.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, vmScaleSetName, instanceID, runCommandName, 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 *VirtualMachineScaleSetVMRunCommandsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, options *VirtualMachineScaleSetVMRunCommandsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// Get - The operation to get the VMSS VM run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - runCommandName - The name of the virtual machine run command. +// - options - VirtualMachineScaleSetVMRunCommandsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.Get +// method. +func (client *VirtualMachineScaleSetVMRunCommandsClient) Get(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, options *VirtualMachineScaleSetVMRunCommandsClientGetOptions) (VirtualMachineScaleSetVMRunCommandsClientGetResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetVMRunCommandsClient.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, vmScaleSetName, instanceID, runCommandName, options) + if err != nil { + return VirtualMachineScaleSetVMRunCommandsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetVMRunCommandsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetVMRunCommandsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineScaleSetVMRunCommandsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, options *VirtualMachineScaleSetVMRunCommandsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineScaleSetVMRunCommandsClient) getHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMRunCommandsClientGetResponse, error) { + result := VirtualMachineScaleSetVMRunCommandsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineRunCommand); err != nil { + return VirtualMachineScaleSetVMRunCommandsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - The operation to get all run commands of an instance in Virtual Machine Scaleset. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMRunCommandsClientListOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.NewListPager +// method. +func (client *VirtualMachineScaleSetVMRunCommandsClient) NewListPager(resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMRunCommandsClientListOptions) *runtime.Pager[VirtualMachineScaleSetVMRunCommandsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetVMRunCommandsClientListResponse]{ + More: func(page VirtualMachineScaleSetVMRunCommandsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetVMRunCommandsClientListResponse) (VirtualMachineScaleSetVMRunCommandsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetVMRunCommandsClient.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, vmScaleSetName, instanceID, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetVMRunCommandsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineScaleSetVMRunCommandsClient) listCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMRunCommandsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/runCommands" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineScaleSetVMRunCommandsClient) listHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMRunCommandsClientListResponse, error) { + result := VirtualMachineScaleSetVMRunCommandsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineRunCommandsListResult); err != nil { + return VirtualMachineScaleSetVMRunCommandsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - The operation to update the VMSS VM run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - runCommandName - The name of the virtual machine run command. +// - runCommand - Parameters supplied to the Update Virtual Machine RunCommand operation. +// - options - VirtualMachineScaleSetVMRunCommandsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMRunCommandsClient.BeginUpdate +// method. +func (client *VirtualMachineScaleSetVMRunCommandsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, runCommand VirtualMachineRunCommandUpdate, options *VirtualMachineScaleSetVMRunCommandsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetVMRunCommandsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmScaleSetName, instanceID, runCommandName, runCommand, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMRunCommandsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMRunCommandsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - The operation to update the VMSS VM run command. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMRunCommandsClient) update(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, runCommand VirtualMachineRunCommandUpdate, options *VirtualMachineScaleSetVMRunCommandsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMRunCommandsClient.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, vmScaleSetName, instanceID, runCommandName, runCommand, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *VirtualMachineScaleSetVMRunCommandsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, runCommand VirtualMachineRunCommandUpdate, options *VirtualMachineScaleSetVMRunCommandsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/runCommands/{runCommandName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + if runCommandName == "" { + return nil, errors.New("parameter runCommandName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runCommandName}", url.PathEscape(runCommandName)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + if err := runtime.MarshalAsJSON(req, runCommand); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvms_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvms_client.go new file mode 100644 index 000000000..e1da5fc11 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinescalesetvms_client.go @@ -0,0 +1,1494 @@ +//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 armcompute + +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" +) + +// VirtualMachineScaleSetVMsClient contains the methods for the VirtualMachineScaleSetVMs group. +// Don't use this type directly, use NewVirtualMachineScaleSetVMsClient() instead. +type VirtualMachineScaleSetVMsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineScaleSetVMsClient creates a new instance of VirtualMachineScaleSetVMsClient 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 NewVirtualMachineScaleSetVMsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineScaleSetVMsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineScaleSetVMsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginApproveRollingUpgrade - Approve upgrade on deferred rolling upgrade for OS disk on a VM scale set instance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginApproveRollingUpgradeOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginApproveRollingUpgrade +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginApproveRollingUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginApproveRollingUpgradeOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientApproveRollingUpgradeResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.approveRollingUpgrade(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientApproveRollingUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientApproveRollingUpgradeResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ApproveRollingUpgrade - Approve upgrade on deferred rolling upgrade for OS disk on a VM scale set instance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) approveRollingUpgrade(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginApproveRollingUpgradeOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginApproveRollingUpgrade" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.approveRollingUpgradeCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// approveRollingUpgradeCreateRequest creates the ApproveRollingUpgrade request. +func (client *VirtualMachineScaleSetVMsClient) approveRollingUpgradeCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginApproveRollingUpgradeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/approveRollingUpgrade" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginAttachDetachDataDisks - Attach and detach data disks to/from a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - parameters - Parameters supplied to the attach and detach data disks operation on a Virtual Machine Scale Sets VM. +// - options - VirtualMachineScaleSetVMsClientBeginAttachDetachDataDisksOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginAttachDetachDataDisks +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginAttachDetachDataDisks(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters AttachDetachDataDisksRequest, options *VirtualMachineScaleSetVMsClientBeginAttachDetachDataDisksOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientAttachDetachDataDisksResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.attachDetachDataDisks(ctx, resourceGroupName, vmScaleSetName, instanceID, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientAttachDetachDataDisksResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientAttachDetachDataDisksResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// AttachDetachDataDisks - Attach and detach data disks to/from a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) attachDetachDataDisks(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters AttachDetachDataDisksRequest, options *VirtualMachineScaleSetVMsClientBeginAttachDetachDataDisksOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginAttachDetachDataDisks" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.attachDetachDataDisksCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// attachDetachDataDisksCreateRequest creates the AttachDetachDataDisks request. +func (client *VirtualMachineScaleSetVMsClient) attachDetachDataDisksCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters AttachDetachDataDisksRequest, options *VirtualMachineScaleSetVMsClientBeginAttachDetachDataDisksOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/attachDetachDataDisks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-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 +} + +// BeginDeallocate - Deallocates a specific virtual machine in a VM scale set. Shuts down the virtual machine and releases +// the compute resources it uses. You are not billed for the compute resources of this virtual +// machine once it is deallocated. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginDeallocateOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginDeallocate +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginDeallocate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginDeallocateOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientDeallocateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deallocate(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientDeallocateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientDeallocateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Deallocate - Deallocates a specific virtual machine in a VM scale set. Shuts down the virtual machine and releases the +// compute resources it uses. You are not billed for the compute resources of this virtual +// machine once it is deallocated. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) deallocate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginDeallocateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginDeallocate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deallocateCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// deallocateCreateRequest creates the Deallocate request. +func (client *VirtualMachineScaleSetVMsClient) deallocateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginDeallocateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/deallocate" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDelete - Deletes a virtual machine from a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginDeleteOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginDelete +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginDelete(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginDeleteOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a virtual machine from a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) deleteOperation(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.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, vmScaleSetName, instanceID, 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 *VirtualMachineScaleSetVMsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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() + if options != nil && options.ForceDeletion != nil { + reqQP.Set("forceDeletion", strconv.FormatBool(*options.ForceDeletion)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a virtual machine from a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientGetOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.Get +// method. +func (client *VirtualMachineScaleSetVMsClient) Get(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientGetOptions) (VirtualMachineScaleSetVMsClientGetResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.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, vmScaleSetName, instanceID, options) + if err != nil { + return VirtualMachineScaleSetVMsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetVMsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetVMsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachineScaleSetVMsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachineScaleSetVMsClient) getHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMsClientGetResponse, error) { + result := VirtualMachineScaleSetVMsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetVM); err != nil { + return VirtualMachineScaleSetVMsClientGetResponse{}, err + } + return result, nil +} + +// GetInstanceView - Gets the status of a virtual machine from a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientGetInstanceViewOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.GetInstanceView +// method. +func (client *VirtualMachineScaleSetVMsClient) GetInstanceView(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientGetInstanceViewOptions) (VirtualMachineScaleSetVMsClientGetInstanceViewResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.GetInstanceView" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getInstanceViewCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return VirtualMachineScaleSetVMsClientGetInstanceViewResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetVMsClientGetInstanceViewResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetVMsClientGetInstanceViewResponse{}, err + } + resp, err := client.getInstanceViewHandleResponse(httpResp) + return resp, err +} + +// getInstanceViewCreateRequest creates the GetInstanceView request. +func (client *VirtualMachineScaleSetVMsClient) getInstanceViewCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientGetInstanceViewOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/instanceView" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getInstanceViewHandleResponse handles the GetInstanceView response. +func (client *VirtualMachineScaleSetVMsClient) getInstanceViewHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMsClientGetInstanceViewResponse, error) { + result := VirtualMachineScaleSetVMsClientGetInstanceViewResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetVMInstanceView); err != nil { + return VirtualMachineScaleSetVMsClientGetInstanceViewResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of all virtual machines in a VM scale sets. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the VM scale set. +// - options - VirtualMachineScaleSetVMsClientListOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.NewListPager +// method. +func (client *VirtualMachineScaleSetVMsClient) NewListPager(resourceGroupName string, virtualMachineScaleSetName string, options *VirtualMachineScaleSetVMsClientListOptions) *runtime.Pager[VirtualMachineScaleSetVMsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineScaleSetVMsClientListResponse]{ + More: func(page VirtualMachineScaleSetVMsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualMachineScaleSetVMsClientListResponse) (VirtualMachineScaleSetVMsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineScaleSetVMsClient.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, virtualMachineScaleSetName, options) + }, nil) + if err != nil { + return VirtualMachineScaleSetVMsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineScaleSetVMsClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, options *VirtualMachineScaleSetVMsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + 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.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineScaleSetVMsClient) listHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMsClientListResponse, error) { + result := VirtualMachineScaleSetVMsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineScaleSetVMListResult); err != nil { + return VirtualMachineScaleSetVMsClientListResponse{}, err + } + return result, nil +} + +// BeginPerformMaintenance - Performs maintenance on a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginPerformMaintenanceOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginPerformMaintenance +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginPerformMaintenance(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginPerformMaintenanceOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientPerformMaintenanceResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.performMaintenance(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientPerformMaintenanceResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientPerformMaintenanceResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PerformMaintenance - Performs maintenance on a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) performMaintenance(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginPerformMaintenanceOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginPerformMaintenance" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.performMaintenanceCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// performMaintenanceCreateRequest creates the PerformMaintenance request. +func (client *VirtualMachineScaleSetVMsClient) performMaintenanceCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginPerformMaintenanceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/performMaintenance" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginPowerOff - Power off (stop) a virtual machine in a VM scale set. Note that resources are still attached and you are +// getting charged for the resources. Instead, use deallocate to release resources and avoid +// charges. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginPowerOffOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginPowerOff +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginPowerOff(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginPowerOffOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientPowerOffResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.powerOff(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientPowerOffResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PowerOff - Power off (stop) a virtual machine in a VM scale set. Note that resources are still attached and you are getting +// charged for the resources. Instead, use deallocate to release resources and avoid +// charges. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) powerOff(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginPowerOffOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginPowerOff" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.powerOffCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// powerOffCreateRequest creates the PowerOff request. +func (client *VirtualMachineScaleSetVMsClient) powerOffCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginPowerOffOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/poweroff" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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() + if options != nil && options.SkipShutdown != nil { + reqQP.Set("skipShutdown", strconv.FormatBool(*options.SkipShutdown)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginRedeploy - Shuts down the virtual machine in the virtual machine scale set, moves it to a new node, and powers it +// back on. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginRedeployOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginRedeploy +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginRedeploy(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginRedeployOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientRedeployResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.redeploy(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientRedeployResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Redeploy - Shuts down the virtual machine in the virtual machine scale set, moves it to a new node, and powers it back +// on. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) redeploy(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginRedeployOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginRedeploy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.redeployCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// redeployCreateRequest creates the Redeploy request. +func (client *VirtualMachineScaleSetVMsClient) redeployCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginRedeployOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/redeploy" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginReimage - Reimages (upgrade the operating system) a specific virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginReimageOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginReimage +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginReimage(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginReimageOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientReimageResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reimage(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientReimageResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reimage - Reimages (upgrade the operating system) a specific virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) reimage(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginReimageOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginReimage" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// reimageCreateRequest creates the Reimage request. +func (client *VirtualMachineScaleSetVMsClient) reimageCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginReimageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/reimage" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.VMScaleSetVMReimageInput != nil { + if err := runtime.MarshalAsJSON(req, *options.VMScaleSetVMReimageInput); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginReimageAll - Allows you to re-image all the disks ( including data disks ) in the a VM scale set instance. This operation +// is only supported for managed disks. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginReimageAllOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginReimageAll +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginReimageAll(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginReimageAllOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientReimageAllResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reimageAll(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientReimageAllResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientReimageAllResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ReimageAll - Allows you to re-image all the disks ( including data disks ) in the a VM scale set instance. This operation +// is only supported for managed disks. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) reimageAll(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginReimageAllOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginReimageAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reimageAllCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// reimageAllCreateRequest creates the ReimageAll request. +func (client *VirtualMachineScaleSetVMsClient) reimageAllCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginReimageAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/reimageall" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginRestart - Restarts a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginRestartOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginRestart +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginRestart(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginRestartOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientRestartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restart(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restart - Restarts a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) restart(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginRestartOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginRestart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restartCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// restartCreateRequest creates the Restart request. +func (client *VirtualMachineScaleSetVMsClient) restartCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginRestartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/restart" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// RetrieveBootDiagnosticsData - The operation to retrieve SAS URIs of boot diagnostic logs for a virtual machine in a VM +// scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.RetrieveBootDiagnosticsData +// method. +func (client *VirtualMachineScaleSetVMsClient) RetrieveBootDiagnosticsData(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataOptions) (VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.RetrieveBootDiagnosticsData" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.retrieveBootDiagnosticsDataCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse{}, err + } + resp, err := client.retrieveBootDiagnosticsDataHandleResponse(httpResp) + return resp, err +} + +// retrieveBootDiagnosticsDataCreateRequest creates the RetrieveBootDiagnosticsData request. +func (client *VirtualMachineScaleSetVMsClient) retrieveBootDiagnosticsDataCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/retrieveBootDiagnosticsData" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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() + if options != nil && options.SasURIExpirationTimeInMinutes != nil { + reqQP.Set("sasUriExpirationTimeInMinutes", strconv.FormatInt(int64(*options.SasURIExpirationTimeInMinutes), 10)) + } + reqQP.Set("api-version", "2023-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// retrieveBootDiagnosticsDataHandleResponse handles the RetrieveBootDiagnosticsData response. +func (client *VirtualMachineScaleSetVMsClient) retrieveBootDiagnosticsDataHandleResponse(resp *http.Response) (VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse, error) { + result := VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RetrieveBootDiagnosticsDataResult); err != nil { + return VirtualMachineScaleSetVMsClientRetrieveBootDiagnosticsDataResponse{}, err + } + return result, nil +} + +// BeginRunCommand - Run command on a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - parameters - Parameters supplied to the Run command operation. +// - options - VirtualMachineScaleSetVMsClientBeginRunCommandOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginRunCommand +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginRunCommand(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters RunCommandInput, options *VirtualMachineScaleSetVMsClientBeginRunCommandOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientRunCommandResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.runCommand(ctx, resourceGroupName, vmScaleSetName, instanceID, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientRunCommandResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientRunCommandResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RunCommand - Run command on a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) runCommand(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters RunCommandInput, options *VirtualMachineScaleSetVMsClientBeginRunCommandOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginRunCommand" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.runCommandCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// runCommandCreateRequest creates the RunCommand request. +func (client *VirtualMachineScaleSetVMsClient) runCommandCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters RunCommandInput, options *VirtualMachineScaleSetVMsClientBeginRunCommandOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/runCommand" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json, text/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// SimulateEviction - The operation to simulate the eviction of spot virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientSimulateEvictionOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.SimulateEviction +// method. +func (client *VirtualMachineScaleSetVMsClient) SimulateEviction(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientSimulateEvictionOptions) (VirtualMachineScaleSetVMsClientSimulateEvictionResponse, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.SimulateEviction" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.simulateEvictionCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return VirtualMachineScaleSetVMsClientSimulateEvictionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineScaleSetVMsClientSimulateEvictionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return VirtualMachineScaleSetVMsClientSimulateEvictionResponse{}, err + } + return VirtualMachineScaleSetVMsClientSimulateEvictionResponse{}, nil +} + +// simulateEvictionCreateRequest creates the SimulateEviction request. +func (client *VirtualMachineScaleSetVMsClient) simulateEvictionCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientSimulateEvictionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/simulateEviction" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStart - Starts a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set. +// - instanceID - The instance ID of the virtual machine. +// - options - VirtualMachineScaleSetVMsClientBeginStartOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginStart +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginStart(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginStartOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, vmScaleSetName, instanceID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - Starts a virtual machine in a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) start(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, vmScaleSetName, instanceID, 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 +} + +// startCreateRequest creates the Start request. +func (client *VirtualMachineScaleSetVMsClient) startCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, options *VirtualMachineScaleSetVMsClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/start" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Updates a virtual machine of a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +// - resourceGroupName - The name of the resource group. +// - vmScaleSetName - The name of the VM scale set where the extension should be create or updated. +// - instanceID - The instance ID of the virtual machine. +// - parameters - Parameters supplied to the Update Virtual Machine Scale Sets VM operation. +// - options - VirtualMachineScaleSetVMsClientBeginUpdateOptions contains the optional parameters for the VirtualMachineScaleSetVMsClient.BeginUpdate +// method. +func (client *VirtualMachineScaleSetVMsClient) BeginUpdate(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM, options *VirtualMachineScaleSetVMsClientBeginUpdateOptions) (*runtime.Poller[VirtualMachineScaleSetVMsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, vmScaleSetName, instanceID, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachineScaleSetVMsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachineScaleSetVMsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a virtual machine of a VM scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-09-01 +func (client *VirtualMachineScaleSetVMsClient) update(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM, options *VirtualMachineScaleSetVMsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachineScaleSetVMsClient.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, vmScaleSetName, instanceID, 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 *VirtualMachineScaleSetVMsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM, options *VirtualMachineScaleSetVMsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmScaleSetName == "" { + return nil, errors.New("parameter vmScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmScaleSetName}", url.PathEscape(vmScaleSetName)) + if instanceID == "" { + return nil, errors.New("parameter instanceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{instanceId}", url.PathEscape(instanceID)) + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + 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/compute/armcompute/v5/virtualmachinesizes_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinesizes_client.go new file mode 100644 index 000000000..02aadc8c2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5/virtualmachinesizes_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 armcompute + +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" +) + +// VirtualMachineSizesClient contains the methods for the VirtualMachineSizes group. +// Don't use this type directly, use NewVirtualMachineSizesClient() instead. +type VirtualMachineSizesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachineSizesClient creates a new instance of VirtualMachineSizesClient 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 NewVirtualMachineSizesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachineSizesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachineSizesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - This API is deprecated. Use Resources Skus [https://docs.microsoft.com/rest/api/compute/resourceskus/list] +// +// Generated from API version 2023-09-01 +// - location - The location upon which virtual-machine-sizes is queried. +// - options - VirtualMachineSizesClientListOptions contains the optional parameters for the VirtualMachineSizesClient.NewListPager +// method. +func (client *VirtualMachineSizesClient) NewListPager(location string, options *VirtualMachineSizesClientListOptions) *runtime.Pager[VirtualMachineSizesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualMachineSizesClientListResponse]{ + More: func(page VirtualMachineSizesClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *VirtualMachineSizesClientListResponse) (VirtualMachineSizesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualMachineSizesClient.NewListPager") + req, err := client.listCreateRequest(ctx, location, options) + if err != nil { + return VirtualMachineSizesClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachineSizesClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return VirtualMachineSizesClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualMachineSizesClient) listCreateRequest(ctx context.Context, location string, options *VirtualMachineSizesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/vmSizes" + 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-09-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualMachineSizesClient) listHandleResponse(resp *http.Response) (VirtualMachineSizesClientListResponse, error) { + result := VirtualMachineSizesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachineSizeListResult); err != nil { + return VirtualMachineSizesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/CHANGELOG.md new file mode 100644 index 000000000..0d27c0773 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/CHANGELOG.md @@ -0,0 +1,732 @@ +# Release History + +## 4.3.0 (2023-11-24) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + + +## 4.3.0-beta.1 (2023-10-09) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + +## 4.2.0 (2023-09-22) +### Features Added + +- New struct `BastionHostPropertiesFormatNetworkACLs` +- New struct `IPRule` +- New struct `VirtualNetworkGatewayAutoScaleBounds` +- New struct `VirtualNetworkGatewayAutoScaleConfiguration` +- New field `NetworkACLs`, `VirtualNetwork` in struct `BastionHostPropertiesFormat` +- New field `Size` in struct `FirewallPolicyPropertiesFormat` +- New field `Size` in struct `FirewallPolicyRuleCollectionGroupProperties` +- New field `DefaultOutboundAccess` in struct `SubnetPropertiesFormat` +- New field `AutoScaleConfiguration` in struct `VirtualNetworkGatewayPropertiesFormat` + + +## 4.1.0 (2023-08-25) +### Features Added + +- New value `ApplicationGatewaySKUNameBasic` added to enum type `ApplicationGatewaySKUName` +- New value `ApplicationGatewayTierBasic` added to enum type `ApplicationGatewayTier` +- New enum type `SyncMode` with values `SyncModeAutomatic`, `SyncModeManual` +- New function `*LoadBalancersClient.MigrateToIPBased(context.Context, string, string, *LoadBalancersClientMigrateToIPBasedOptions) (LoadBalancersClientMigrateToIPBasedResponse, error)` +- New struct `MigrateLoadBalancerToIPBasedRequest` +- New struct `MigratedPools` +- New field `SyncMode` in struct `BackendAddressPoolPropertiesFormat` + + +## 4.0.0 (2023-07-11) +### Breaking Changes + +- `ApplicationGatewayCustomErrorStatusCodeHTTPStatus499` from enum `ApplicationGatewayCustomErrorStatusCode` has been removed + +### Features Added + +- New enum type `AdminState` with values `AdminStateDisabled`, `AdminStateEnabled` +- New field `ResourceGUID` in struct `AdminPropertiesFormat` +- New field `ResourceGUID` in struct `AdminRuleCollectionPropertiesFormat` +- New field `DefaultPredefinedSSLPolicy` in struct `ApplicationGatewayPropertiesFormat` +- New field `ResourceGUID` in struct `ConnectivityConfigurationProperties` +- New field `ResourceGUID` in struct `DefaultAdminPropertiesFormat` +- New field `ResourceGUID` in struct `GroupProperties` +- New field `ResourceGUID` in struct `ManagerProperties` +- New field `ResourceGUID` in struct `SecurityAdminConfigurationPropertiesFormat` +- New field `AdminState` in struct `VirtualNetworkGatewayPropertiesFormat` + + +## 3.0.0 (2023-05-26) +### Breaking Changes + +- Type of `EffectiveRouteMapRoute.Prefix` has been changed from `[]*string` to `*string` +- `LoadBalancerBackendAddressAdminStateDrain` from enum `LoadBalancerBackendAddressAdminState` has been removed +- Struct `PeerRouteList` has been removed +- Field `PeerRouteList` of struct `VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse` has been removed +- Field `PeerRouteList` of struct `VirtualHubBgpConnectionsClientListLearnedRoutesResponse` has been removed + +### Features Added + +- New value `NetworkInterfaceAuxiliaryModeAcceleratedConnections` added to enum type `NetworkInterfaceAuxiliaryMode` +- New value `WebApplicationFirewallRuleTypeRateLimitRule` added to enum type `WebApplicationFirewallRuleType` +- New enum type `ApplicationGatewayFirewallRateLimitDuration` with values `ApplicationGatewayFirewallRateLimitDurationFiveMins`, `ApplicationGatewayFirewallRateLimitDurationOneMin` +- New enum type `ApplicationGatewayFirewallUserSessionVariable` with values `ApplicationGatewayFirewallUserSessionVariableClientAddr`, `ApplicationGatewayFirewallUserSessionVariableGeoLocation`, `ApplicationGatewayFirewallUserSessionVariableNone` +- New enum type `AzureFirewallPacketCaptureFlagsType` with values `AzureFirewallPacketCaptureFlagsTypeAck`, `AzureFirewallPacketCaptureFlagsTypeFin`, `AzureFirewallPacketCaptureFlagsTypePush`, `AzureFirewallPacketCaptureFlagsTypeRst`, `AzureFirewallPacketCaptureFlagsTypeSyn`, `AzureFirewallPacketCaptureFlagsTypeUrg` +- New enum type `NetworkInterfaceAuxiliarySKU` with values `NetworkInterfaceAuxiliarySKUA1`, `NetworkInterfaceAuxiliarySKUA2`, `NetworkInterfaceAuxiliarySKUA4`, `NetworkInterfaceAuxiliarySKUA8`, `NetworkInterfaceAuxiliarySKUNone` +- New enum type `PublicIPAddressDNSSettingsDomainNameLabelScope` with values `PublicIPAddressDNSSettingsDomainNameLabelScopeNoReuse`, `PublicIPAddressDNSSettingsDomainNameLabelScopeResourceGroupReuse`, `PublicIPAddressDNSSettingsDomainNameLabelScopeSubscriptionReuse`, `PublicIPAddressDNSSettingsDomainNameLabelScopeTenantReuse` +- New enum type `ScrubbingRuleEntryMatchOperator` with values `ScrubbingRuleEntryMatchOperatorEquals`, `ScrubbingRuleEntryMatchOperatorEqualsAny` +- New enum type `ScrubbingRuleEntryMatchVariable` with values `ScrubbingRuleEntryMatchVariableRequestArgNames`, `ScrubbingRuleEntryMatchVariableRequestCookieNames`, `ScrubbingRuleEntryMatchVariableRequestHeaderNames`, `ScrubbingRuleEntryMatchVariableRequestIPAddress`, `ScrubbingRuleEntryMatchVariableRequestJSONArgNames`, `ScrubbingRuleEntryMatchVariableRequestPostArgNames` +- New enum type `ScrubbingRuleEntryState` with values `ScrubbingRuleEntryStateDisabled`, `ScrubbingRuleEntryStateEnabled` +- New enum type `WebApplicationFirewallScrubbingState` with values `WebApplicationFirewallScrubbingStateDisabled`, `WebApplicationFirewallScrubbingStateEnabled` +- New function `*AzureFirewallsClient.BeginPacketCapture(context.Context, string, string, FirewallPacketCaptureParameters, *AzureFirewallsClientBeginPacketCaptureOptions) (*runtime.Poller[AzureFirewallsClientPacketCaptureResponse], error)` +- New function `*ClientFactory.NewVirtualApplianceConnectionsClient() *VirtualApplianceConnectionsClient` +- New function `NewVirtualApplianceConnectionsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*VirtualApplianceConnectionsClient, error)` +- New function `*VirtualApplianceConnectionsClient.BeginCreateOrUpdate(context.Context, string, string, string, VirtualApplianceConnection, *VirtualApplianceConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualApplianceConnectionsClientCreateOrUpdateResponse], error)` +- New function `*VirtualApplianceConnectionsClient.BeginDelete(context.Context, string, string, string, *VirtualApplianceConnectionsClientBeginDeleteOptions) (*runtime.Poller[VirtualApplianceConnectionsClientDeleteResponse], error)` +- New function `*VirtualApplianceConnectionsClient.Get(context.Context, string, string, string, *VirtualApplianceConnectionsClientGetOptions) (VirtualApplianceConnectionsClientGetResponse, error)` +- New function `*VirtualApplianceConnectionsClient.NewListPager(string, string, *VirtualApplianceConnectionsClientListOptions) *runtime.Pager[VirtualApplianceConnectionsClientListResponse]` +- New struct `AzureFirewallPacketCaptureFlags` +- New struct `AzureFirewallPacketCaptureRule` +- New struct `EffectiveRouteMapRouteList` +- New struct `FirewallPacketCaptureParameters` +- New struct `FirewallPacketCaptureParametersFormat` +- New struct `FirewallPolicyHTTPHeaderToInsert` +- New struct `GroupByUserSession` +- New struct `GroupByVariable` +- New struct `PolicySettingsLogScrubbing` +- New struct `PropagatedRouteTableNfv` +- New struct `RoutingConfigurationNfv` +- New struct `RoutingConfigurationNfvSubResource` +- New struct `VirtualApplianceAdditionalNicProperties` +- New struct `VirtualApplianceConnection` +- New struct `VirtualApplianceConnectionList` +- New struct `VirtualApplianceConnectionProperties` +- New struct `WebApplicationFirewallScrubbingRules` +- New field `HTTPHeadersToInsert` in struct `ApplicationRule` +- New field `EnableKerberos` in struct `BastionHostPropertiesFormat` +- New field `AuxiliarySKU` in struct `InterfacePropertiesFormat` +- New field `FileUploadEnforcement`, `LogScrubbing`, `RequestBodyEnforcement`, `RequestBodyInspectLimitInKB` in struct `PolicySettings` +- New field `PrivateEndpointLocation` in struct `PrivateEndpointConnectionProperties` +- New field `DomainNameLabelScope` in struct `PublicIPAddressDNSSettings` +- New field `InstanceName` in struct `VirtualApplianceNicProperties` +- New field `AdditionalNics`, `VirtualApplianceConnections` in struct `VirtualAppliancePropertiesFormat` +- New field `Value` in struct `VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse` +- New field `Value` in struct `VirtualHubBgpConnectionsClientListLearnedRoutesResponse` +- New anonymous field `VirtualHubEffectiveRouteList` in struct `VirtualHubsClientGetEffectiveVirtualHubRoutesResponse` +- New anonymous field `EffectiveRouteMapRouteList` in struct `VirtualHubsClientGetInboundRoutesResponse` +- New anonymous field `EffectiveRouteMapRouteList` in struct `VirtualHubsClientGetOutboundRoutesResponse` +- New field `GroupByUserSession`, `RateLimitDuration`, `RateLimitThreshold` in struct `WebApplicationFirewallCustomRule` + + +## 2.2.1 (2023-04-14) +### Bug Fixes + +- Fix serialization bug of empty value of `any` type. + + +## 2.2.0 (2023-03-24) +### Features Added + +- New struct `ClientFactory` which is a client factory used to create any client in this module +- New value `ApplicationGatewayCustomErrorStatusCodeHTTPStatus400`, `ApplicationGatewayCustomErrorStatusCodeHTTPStatus404`, `ApplicationGatewayCustomErrorStatusCodeHTTPStatus405`, `ApplicationGatewayCustomErrorStatusCodeHTTPStatus408`, `ApplicationGatewayCustomErrorStatusCodeHTTPStatus499`, `ApplicationGatewayCustomErrorStatusCodeHTTPStatus500`, `ApplicationGatewayCustomErrorStatusCodeHTTPStatus503`, `ApplicationGatewayCustomErrorStatusCodeHTTPStatus504` added to enum type `ApplicationGatewayCustomErrorStatusCode` +- New enum type `WebApplicationFirewallState` with values `WebApplicationFirewallStateDisabled`, `WebApplicationFirewallStateEnabled` +- New field `AuthorizationStatus` in struct `ExpressRouteCircuitPropertiesFormat` +- New field `IPConfigurationID` in struct `VPNGatewaysClientBeginResetOptions` +- New field `FlowLogs` in struct `VirtualNetworkPropertiesFormat` +- New field `State` in struct `WebApplicationFirewallCustomRule` + + +## 2.1.0 (2022-12-23) +### Features Added + +- New struct `DelegationProperties` +- New struct `PartnerManagedResourceProperties` +- New field `VirtualNetwork` in struct `BackendAddressPoolPropertiesFormat` +- New field `CustomBlockResponseBody` in struct `PolicySettings` +- New field `CustomBlockResponseStatusCode` in struct `PolicySettings` +- New field `Delegation` in struct `VirtualAppliancePropertiesFormat` +- New field `DeploymentType` in struct `VirtualAppliancePropertiesFormat` +- New field `PartnerManagedResource` in struct `VirtualAppliancePropertiesFormat` + + +## 2.0.1 (2022-10-14) +### Others Changes +- Update live test dependencies + +## 2.0.0 (2022-09-29) +### Breaking Changes + +- Const `DdosCustomPolicyProtocolSyn` has been removed +- Const `DdosCustomPolicyTriggerSensitivityOverrideHigh` has been removed +- Const `DdosSettingsProtectionCoverageBasic` has been removed +- Const `DdosCustomPolicyProtocolUDP` has been removed +- Const `DdosCustomPolicyProtocolTCP` has been removed +- Const `DdosCustomPolicyTriggerSensitivityOverrideLow` has been removed +- Const `DdosCustomPolicyTriggerSensitivityOverrideDefault` has been removed +- Const `DdosSettingsProtectionCoverageStandard` has been removed +- Const `DdosCustomPolicyTriggerSensitivityOverrideRelaxed` has been removed +- Type alias `DdosSettingsProtectionCoverage` has been removed +- Type alias `DdosCustomPolicyTriggerSensitivityOverride` has been removed +- Type alias `DdosCustomPolicyProtocol` has been removed +- Function `PossibleDdosCustomPolicyProtocolValues` has been removed +- Function `PossibleDdosSettingsProtectionCoverageValues` has been removed +- Function `PossibleDdosCustomPolicyTriggerSensitivityOverrideValues` has been removed +- Struct `ProtocolCustomSettingsFormat` has been removed +- Field `PublicIPAddresses` of struct `DdosCustomPolicyPropertiesFormat` has been removed +- Field `ProtocolCustomSettings` of struct `DdosCustomPolicyPropertiesFormat` has been removed +- Field `DdosCustomPolicy` of struct `DdosSettings` has been removed +- Field `ProtectedIP` of struct `DdosSettings` has been removed +- Field `ProtectionCoverage` of struct `DdosSettings` has been removed + +### Features Added + +- New const `ApplicationGatewayWafRuleStateTypesEnabled` +- New const `RouteMapMatchConditionNotEquals` +- New const `ActionTypeBlock` +- New const `RouteMapActionTypeUnknown` +- New const `GeoAFRI` +- New const `IsWorkloadProtectedFalse` +- New const `ApplicationGatewayRuleSetStatusOptionsDeprecated` +- New const `ApplicationGatewayWafRuleActionTypesAllow` +- New const `RouteMapActionTypeRemove` +- New const `ApplicationGatewayClientRevocationOptionsNone` +- New const `NextStepContinue` +- New const `SlotTypeProduction` +- New const `NetworkIntentPolicyBasedServiceAllowRulesOnly` +- New const `ApplicationGatewayTierTypesWAFV2` +- New const `ActionTypeLog` +- New const `CommissionedStateDeprovisioned` +- New const `RouteMapMatchConditionEquals` +- New const `GeoOCEANIA` +- New const `GeoGLOBAL` +- New const `WebApplicationFirewallTransformUppercase` +- New const `NextStepUnknown` +- New const `ApplicationGatewayTierTypesWAF` +- New const `ApplicationGatewayWafRuleActionTypesNone` +- New const `CustomIPPrefixTypeSingular` +- New const `GeoME` +- New const `GeoLATAM` +- New const `ApplicationGatewayWafRuleActionTypesBlock` +- New const `ApplicationGatewayRuleSetStatusOptionsGA` +- New const `RouteMapMatchConditionUnknown` +- New const `ApplicationGatewayWafRuleStateTypesDisabled` +- New const `ApplicationGatewayTierTypesStandardV2` +- New const `VnetLocalRouteOverrideCriteriaEqual` +- New const `ManagedRuleEnabledStateEnabled` +- New const `RouteMapMatchConditionContains` +- New const `DdosSettingsProtectionModeDisabled` +- New const `ActionTypeAnomalyScoring` +- New const `ActionTypeAllow` +- New const `SlotTypeStaging` +- New const `GeoAQ` +- New const `RouteMapMatchConditionNotContains` +- New const `ApplicationGatewayClientRevocationOptionsOCSP` +- New const `RouteMapActionTypeReplace` +- New const `GeoNAM` +- New const `CustomIPPrefixTypeChild` +- New const `GeoEURO` +- New const `ExpressRoutePortsBillingTypeMeteredData` +- New const `GeoAPAC` +- New const `CustomIPPrefixTypeParent` +- New const `VnetLocalRouteOverrideCriteriaContains` +- New const `DdosSettingsProtectionModeVirtualNetworkInherited` +- New const `ApplicationGatewayWafRuleActionTypesLog` +- New const `ApplicationGatewayWafRuleActionTypesAnomalyScoring` +- New const `ApplicationGatewayRuleSetStatusOptionsSupported` +- New const `ExpressRoutePortsBillingTypeUnlimitedData` +- New const `DdosSettingsProtectionModeEnabled` +- New const `IsWorkloadProtectedTrue` +- New const `ApplicationGatewayRuleSetStatusOptionsPreview` +- New const `RouteMapActionTypeDrop` +- New const `ApplicationGatewayTierTypesStandard` +- New const `NextStepTerminate` +- New const `RouteMapActionTypeAdd` +- New type alias `DdosSettingsProtectionMode` +- New type alias `ApplicationGatewayWafRuleActionTypes` +- New type alias `ApplicationGatewayClientRevocationOptions` +- New type alias `NextStep` +- New type alias `ActionType` +- New type alias `SlotType` +- New type alias `IsWorkloadProtected` +- New type alias `RouteMapMatchCondition` +- New type alias `ApplicationGatewayWafRuleStateTypes` +- New type alias `ApplicationGatewayTierTypes` +- New type alias `CustomIPPrefixType` +- New type alias `RouteMapActionType` +- New type alias `ExpressRoutePortsBillingType` +- New type alias `ApplicationGatewayRuleSetStatusOptions` +- New type alias `Geo` +- New type alias `VnetLocalRouteOverrideCriteria` +- New function `PossibleSlotTypeValues() []SlotType` +- New function `NewVipSwapClient(string, azcore.TokenCredential, *arm.ClientOptions) (*VipSwapClient, error)` +- New function `PossibleNextStepValues() []NextStep` +- New function `*RouteMapsClient.BeginDelete(context.Context, string, string, string, *RouteMapsClientBeginDeleteOptions) (*runtime.Poller[RouteMapsClientDeleteResponse], error)` +- New function `PossibleRouteMapActionTypeValues() []RouteMapActionType` +- New function `*RouteMapsClient.Get(context.Context, string, string, string, *RouteMapsClientGetOptions) (RouteMapsClientGetResponse, error)` +- New function `*VirtualHubsClient.BeginGetOutboundRoutes(context.Context, string, string, GetOutboundRoutesParameters, *VirtualHubsClientBeginGetOutboundRoutesOptions) (*runtime.Poller[VirtualHubsClientGetOutboundRoutesResponse], error)` +- New function `PossibleGeoValues() []Geo` +- New function `PossibleApplicationGatewayClientRevocationOptionsValues() []ApplicationGatewayClientRevocationOptions` +- New function `*ApplicationGatewayWafDynamicManifestsClient.NewGetPager(string, *ApplicationGatewayWafDynamicManifestsClientGetOptions) *runtime.Pager[ApplicationGatewayWafDynamicManifestsClientGetResponse]` +- New function `*ApplicationGatewayWafDynamicManifestsDefaultClient.Get(context.Context, string, *ApplicationGatewayWafDynamicManifestsDefaultClientGetOptions) (ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse, error)` +- New function `PossibleActionTypeValues() []ActionType` +- New function `*RouteMapsClient.NewListPager(string, string, *RouteMapsClientListOptions) *runtime.Pager[RouteMapsClientListResponse]` +- New function `PossibleApplicationGatewayTierTypesValues() []ApplicationGatewayTierTypes` +- New function `NewApplicationGatewayWafDynamicManifestsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ApplicationGatewayWafDynamicManifestsClient, error)` +- New function `PossibleApplicationGatewayRuleSetStatusOptionsValues() []ApplicationGatewayRuleSetStatusOptions` +- New function `PossibleCustomIPPrefixTypeValues() []CustomIPPrefixType` +- New function `NewApplicationGatewayWafDynamicManifestsDefaultClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ApplicationGatewayWafDynamicManifestsDefaultClient, error)` +- New function `PossibleVnetLocalRouteOverrideCriteriaValues() []VnetLocalRouteOverrideCriteria` +- New function `*VirtualHubsClient.BeginGetInboundRoutes(context.Context, string, string, GetInboundRoutesParameters, *VirtualHubsClientBeginGetInboundRoutesOptions) (*runtime.Poller[VirtualHubsClientGetInboundRoutesResponse], error)` +- New function `*VipSwapClient.Get(context.Context, string, string, *VipSwapClientGetOptions) (VipSwapClientGetResponse, error)` +- New function `*PublicIPAddressesClient.BeginDdosProtectionStatus(context.Context, string, string, *PublicIPAddressesClientBeginDdosProtectionStatusOptions) (*runtime.Poller[PublicIPAddressesClientDdosProtectionStatusResponse], error)` +- New function `PossibleExpressRoutePortsBillingTypeValues() []ExpressRoutePortsBillingType` +- New function `*VipSwapClient.List(context.Context, string, string, *VipSwapClientListOptions) (VipSwapClientListResponse, error)` +- New function `*VirtualNetworksClient.BeginListDdosProtectionStatus(context.Context, string, string, *VirtualNetworksClientBeginListDdosProtectionStatusOptions) (*runtime.Poller[*runtime.Pager[VirtualNetworksClientListDdosProtectionStatusResponse]], error)` +- New function `PossibleIsWorkloadProtectedValues() []IsWorkloadProtected` +- New function `PossibleDdosSettingsProtectionModeValues() []DdosSettingsProtectionMode` +- New function `PossibleApplicationGatewayWafRuleStateTypesValues() []ApplicationGatewayWafRuleStateTypes` +- New function `NewRouteMapsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*RouteMapsClient, error)` +- New function `PossibleRouteMapMatchConditionValues() []RouteMapMatchCondition` +- New function `*VipSwapClient.BeginCreate(context.Context, string, string, SwapResource, *VipSwapClientBeginCreateOptions) (*runtime.Poller[VipSwapClientCreateResponse], error)` +- New function `PossibleApplicationGatewayWafRuleActionTypesValues() []ApplicationGatewayWafRuleActionTypes` +- New function `*RouteMapsClient.BeginCreateOrUpdate(context.Context, string, string, string, RouteMap, *RouteMapsClientBeginCreateOrUpdateOptions) (*runtime.Poller[RouteMapsClientCreateOrUpdateResponse], error)` +- New struct `Action` +- New struct `ApplicationGatewayFirewallManifestRuleSet` +- New struct `ApplicationGatewayWafDynamicManifestPropertiesResult` +- New struct `ApplicationGatewayWafDynamicManifestResult` +- New struct `ApplicationGatewayWafDynamicManifestResultList` +- New struct `ApplicationGatewayWafDynamicManifestsClient` +- New struct `ApplicationGatewayWafDynamicManifestsClientGetOptions` +- New struct `ApplicationGatewayWafDynamicManifestsClientGetResponse` +- New struct `ApplicationGatewayWafDynamicManifestsDefaultClient` +- New struct `ApplicationGatewayWafDynamicManifestsDefaultClientGetOptions` +- New struct `ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse` +- New struct `Criterion` +- New struct `DefaultRuleSetPropertyFormat` +- New struct `EffectiveRouteMapRoute` +- New struct `GetInboundRoutesParameters` +- New struct `GetOutboundRoutesParameters` +- New struct `ListRouteMapsResult` +- New struct `Parameter` +- New struct `PublicIPAddressesClientBeginDdosProtectionStatusOptions` +- New struct `PublicIPAddressesClientDdosProtectionStatusResponse` +- New struct `PublicIPDdosProtectionStatusResult` +- New struct `RouteMap` +- New struct `RouteMapProperties` +- New struct `RouteMapRule` +- New struct `RouteMapsClient` +- New struct `RouteMapsClientBeginCreateOrUpdateOptions` +- New struct `RouteMapsClientBeginDeleteOptions` +- New struct `RouteMapsClientCreateOrUpdateResponse` +- New struct `RouteMapsClientDeleteResponse` +- New struct `RouteMapsClientGetOptions` +- New struct `RouteMapsClientGetResponse` +- New struct `RouteMapsClientListOptions` +- New struct `RouteMapsClientListResponse` +- New struct `StaticRoutesConfig` +- New struct `SwapResource` +- New struct `SwapResourceListResult` +- New struct `SwapResourceProperties` +- New struct `VipSwapClient` +- New struct `VipSwapClientBeginCreateOptions` +- New struct `VipSwapClientCreateResponse` +- New struct `VipSwapClientGetOptions` +- New struct `VipSwapClientGetResponse` +- New struct `VipSwapClientListOptions` +- New struct `VipSwapClientListResponse` +- New struct `VirtualHubsClientBeginGetInboundRoutesOptions` +- New struct `VirtualHubsClientBeginGetOutboundRoutesOptions` +- New struct `VirtualHubsClientGetInboundRoutesResponse` +- New struct `VirtualHubsClientGetOutboundRoutesResponse` +- New struct `VirtualNetworkDdosProtectionStatusResult` +- New struct `VirtualNetworkGatewayPolicyGroup` +- New struct `VirtualNetworkGatewayPolicyGroupMember` +- New struct `VirtualNetworkGatewayPolicyGroupProperties` +- New struct `VirtualNetworksClientBeginListDdosProtectionStatusOptions` +- New struct `VirtualNetworksClientListDdosProtectionStatusResponse` +- New struct `VngClientConnectionConfiguration` +- New struct `VngClientConnectionConfigurationProperties` +- New field `RouteMaps` in struct `VirtualHubProperties` +- New field `Tiers` in struct `ApplicationGatewayFirewallRuleSetPropertiesFormat` +- New field `EnablePrivateLinkFastPath` in struct `VirtualNetworkGatewayConnectionListEntityPropertiesFormat` +- New field `ColoLocation` in struct `ExpressRouteLinkPropertiesFormat` +- New field `EnablePrivateLinkFastPath` in struct `VirtualNetworkGatewayConnectionPropertiesFormat` +- New field `DisableTCPStateTracking` in struct `InterfacePropertiesFormat` +- New field `Top` in struct `ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions` +- New field `Action` in struct `ManagedRuleOverride` +- New field `VngClientConnectionConfigurations` in struct `VPNClientConfiguration` +- New field `StaticRoutesConfig` in struct `VnetRoute` +- New field `AllowVirtualWanTraffic` in struct `VirtualNetworkGatewayPropertiesFormat` +- New field `VirtualNetworkGatewayPolicyGroups` in struct `VirtualNetworkGatewayPropertiesFormat` +- New field `AllowRemoteVnetTraffic` in struct `VirtualNetworkGatewayPropertiesFormat` +- New field `RuleIDString` in struct `ApplicationGatewayFirewallRule` +- New field `State` in struct `ApplicationGatewayFirewallRule` +- New field `Action` in struct `ApplicationGatewayFirewallRule` +- New field `Top` in struct `ManagerDeploymentStatusClientListOptions` +- New field `InboundRouteMap` in struct `RoutingConfiguration` +- New field `OutboundRouteMap` in struct `RoutingConfiguration` +- New field `VerifyClientRevocation` in struct `ApplicationGatewayClientAuthConfiguration` +- New field `Top` in struct `ManagementClientListActiveSecurityAdminRulesOptions` +- New field `ProbeThreshold` in struct `ProbePropertiesFormat` +- New field `AllowNonVirtualWanTraffic` in struct `ExpressRouteGatewayProperties` +- New field `Top` in struct `ManagementClientListActiveConnectivityConfigurationsOptions` +- New field `PublicIPAddresses` in struct `DdosProtectionPlanPropertiesFormat` +- New field `ProtectionMode` in struct `DdosSettings` +- New field `DdosProtectionPlan` in struct `DdosSettings` +- New field `ExpressRouteAdvertise` in struct `CustomIPPrefixPropertiesFormat` +- New field `Geo` in struct `CustomIPPrefixPropertiesFormat` +- New field `PrefixType` in struct `CustomIPPrefixPropertiesFormat` +- New field `Asn` in struct `CustomIPPrefixPropertiesFormat` +- New field `Top` in struct `ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions` +- New field `EnablePrivateLinkFastPath` in struct `ExpressRouteConnectionProperties` +- New field `BillingType` in struct `ExpressRoutePortPropertiesFormat` + + +## 1.1.0 (2022-08-05) +### Features Added + +- New const `SecurityConfigurationRuleDirectionInbound` +- New const `IsGlobalFalse` +- New const `EndpointTypeAzureVMSS` +- New const `ScopeConnectionStateConflict` +- New const `SecurityConfigurationRuleDirectionOutbound` +- New const `GroupConnectivityDirectlyConnected` +- New const `ScopeConnectionStateRejected` +- New const `ConfigurationTypeConnectivity` +- New const `AutoLearnPrivateRangesModeEnabled` +- New const `UseHubGatewayFalse` +- New const `NetworkIntentPolicyBasedServiceNone` +- New const `DeleteExistingPeeringFalse` +- New const `EffectiveAdminRuleKindDefault` +- New const `DeploymentStatusFailed` +- New const `AddressPrefixTypeIPPrefix` +- New const `AddressPrefixTypeServiceTag` +- New const `UseHubGatewayTrue` +- New const `WebApplicationFirewallOperatorAny` +- New const `SecurityConfigurationRuleAccessAlwaysAllow` +- New const `CreatedByTypeUser` +- New const `EndpointTypeAzureArcVM` +- New const `DeploymentStatusNotStarted` +- New const `SecurityConfigurationRuleProtocolTCP` +- New const `SecurityConfigurationRuleAccessDeny` +- New const `SecurityConfigurationRuleProtocolEsp` +- New const `IsGlobalTrue` +- New const `DeploymentStatusDeployed` +- New const `NetworkIntentPolicyBasedServiceAll` +- New const `SecurityConfigurationRuleProtocolUDP` +- New const `CreatedByTypeKey` +- New const `PacketCaptureTargetTypeAzureVMSS` +- New const `ApplicationGatewaySSLPolicyTypeCustomV2` +- New const `DeleteExistingPeeringTrue` +- New const `ScopeConnectionStateConnected` +- New const `ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20220101S` +- New const `ConnectivityTopologyMesh` +- New const `CreatedByTypeManagedIdentity` +- New const `AdminRuleKindCustom` +- New const `ApplicationGatewaySSLProtocolTLSv13` +- New const `ConnectivityTopologyHubAndSpoke` +- New const `ScopeConnectionStateRevoked` +- New const `ConfigurationTypeSecurityAdmin` +- New const `SecurityConfigurationRuleProtocolAh` +- New const `CommissionedStateCommissionedNoInternetAdvertise` +- New const `ScopeConnectionStatePending` +- New const `SecurityConfigurationRuleAccessAllow` +- New const `SecurityConfigurationRuleProtocolIcmp` +- New const `AutoLearnPrivateRangesModeDisabled` +- New const `SecurityConfigurationRuleProtocolAny` +- New const `ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20220101` +- New const `CreatedByTypeApplication` +- New const `GroupConnectivityNone` +- New const `EffectiveAdminRuleKindCustom` +- New const `AdminRuleKindDefault` +- New const `DeploymentStatusDeploying` +- New const `PacketCaptureTargetTypeAzureVM` +- New function `*ManagementClient.ListActiveConnectivityConfigurations(context.Context, string, string, ActiveConfigurationParameter, *ManagementClientListActiveConnectivityConfigurationsOptions) (ManagementClientListActiveConnectivityConfigurationsResponse, error)` +- New function `*ManagersClient.NewListBySubscriptionPager(*ManagersClientListBySubscriptionOptions) *runtime.Pager[ManagersClientListBySubscriptionResponse]` +- New function `NewStaticMembersClient(string, azcore.TokenCredential, *arm.ClientOptions) (*StaticMembersClient, error)` +- New function `NewAdminRulesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*AdminRulesClient, error)` +- New function `*EffectiveDefaultSecurityAdminRule.GetEffectiveBaseSecurityAdminRule() *EffectiveBaseSecurityAdminRule` +- New function `PossibleAddressPrefixTypeValues() []AddressPrefixType` +- New function `PossibleUseHubGatewayValues() []UseHubGateway` +- New function `*ScopeConnectionsClient.Delete(context.Context, string, string, string, *ScopeConnectionsClientDeleteOptions) (ScopeConnectionsClientDeleteResponse, error)` +- New function `PossibleIsGlobalValues() []IsGlobal` +- New function `*ManagementClient.ListActiveSecurityAdminRules(context.Context, string, string, ActiveConfigurationParameter, *ManagementClientListActiveSecurityAdminRulesOptions) (ManagementClientListActiveSecurityAdminRulesResponse, error)` +- New function `*ManagersClient.NewListPager(string, *ManagersClientListOptions) *runtime.Pager[ManagersClientListResponse]` +- New function `NewConnectivityConfigurationsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ConnectivityConfigurationsClient, error)` +- New function `*GroupsClient.Get(context.Context, string, string, string, *GroupsClientGetOptions) (GroupsClientGetResponse, error)` +- New function `PossibleAdminRuleKindValues() []AdminRuleKind` +- New function `*ScopeConnectionsClient.Get(context.Context, string, string, string, *ScopeConnectionsClientGetOptions) (ScopeConnectionsClientGetResponse, error)` +- New function `*AdminRuleCollectionsClient.CreateOrUpdate(context.Context, string, string, string, string, AdminRuleCollection, *AdminRuleCollectionsClientCreateOrUpdateOptions) (AdminRuleCollectionsClientCreateOrUpdateResponse, error)` +- New function `PossibleScopeConnectionStateValues() []ScopeConnectionState` +- New function `*ConnectivityConfigurationsClient.NewListPager(string, string, *ConnectivityConfigurationsClientListOptions) *runtime.Pager[ConnectivityConfigurationsClientListResponse]` +- New function `*BaseAdminRule.GetBaseAdminRule() *BaseAdminRule` +- New function `PossibleSecurityConfigurationRuleProtocolValues() []SecurityConfigurationRuleProtocol` +- New function `*AdminRulesClient.CreateOrUpdate(context.Context, string, string, string, string, string, BaseAdminRuleClassification, *AdminRulesClientCreateOrUpdateOptions) (AdminRulesClientCreateOrUpdateResponse, error)` +- New function `PossibleNetworkIntentPolicyBasedServiceValues() []NetworkIntentPolicyBasedService` +- New function `*ManagementGroupNetworkManagerConnectionsClient.Delete(context.Context, string, string, *ManagementGroupNetworkManagerConnectionsClientDeleteOptions) (ManagementGroupNetworkManagerConnectionsClientDeleteResponse, error)` +- New function `PossibleSecurityConfigurationRuleAccessValues() []SecurityConfigurationRuleAccess` +- New function `*ManagersClient.BeginDelete(context.Context, string, string, *ManagersClientBeginDeleteOptions) (*runtime.Poller[ManagersClientDeleteResponse], error)` +- New function `*ManagementClient.ExpressRouteProviderPort(context.Context, string, *ManagementClientExpressRouteProviderPortOptions) (ManagementClientExpressRouteProviderPortResponse, error)` +- New function `*ActiveBaseSecurityAdminRule.GetActiveBaseSecurityAdminRule() *ActiveBaseSecurityAdminRule` +- New function `*ConnectivityConfigurationsClient.BeginDelete(context.Context, string, string, string, *ConnectivityConfigurationsClientBeginDeleteOptions) (*runtime.Poller[ConnectivityConfigurationsClientDeleteResponse], error)` +- New function `*AdminRuleCollectionsClient.BeginDelete(context.Context, string, string, string, string, *AdminRuleCollectionsClientBeginDeleteOptions) (*runtime.Poller[AdminRuleCollectionsClientDeleteResponse], error)` +- New function `*ConnectivityConfigurationsClient.CreateOrUpdate(context.Context, string, string, string, ConnectivityConfiguration, *ConnectivityConfigurationsClientCreateOrUpdateOptions) (ConnectivityConfigurationsClientCreateOrUpdateResponse, error)` +- New function `*SecurityAdminConfigurationsClient.Get(context.Context, string, string, string, *SecurityAdminConfigurationsClientGetOptions) (SecurityAdminConfigurationsClientGetResponse, error)` +- New function `*StaticMembersClient.Delete(context.Context, string, string, string, string, *StaticMembersClientDeleteOptions) (StaticMembersClientDeleteResponse, error)` +- New function `*ManagerDeploymentStatusClient.List(context.Context, string, string, ManagerDeploymentStatusParameter, *ManagerDeploymentStatusClientListOptions) (ManagerDeploymentStatusClientListResponse, error)` +- New function `*SubscriptionNetworkManagerConnectionsClient.Delete(context.Context, string, *SubscriptionNetworkManagerConnectionsClientDeleteOptions) (SubscriptionNetworkManagerConnectionsClientDeleteResponse, error)` +- New function `PossibleEffectiveAdminRuleKindValues() []EffectiveAdminRuleKind` +- New function `*AdminRulesClient.NewListPager(string, string, string, string, *AdminRulesClientListOptions) *runtime.Pager[AdminRulesClientListResponse]` +- New function `*GroupsClient.NewListPager(string, string, *GroupsClientListOptions) *runtime.Pager[GroupsClientListResponse]` +- New function `*GroupsClient.BeginDelete(context.Context, string, string, string, *GroupsClientBeginDeleteOptions) (*runtime.Poller[GroupsClientDeleteResponse], error)` +- New function `*StaticMembersClient.NewListPager(string, string, string, *StaticMembersClientListOptions) *runtime.Pager[StaticMembersClientListResponse]` +- New function `NewGroupsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*GroupsClient, error)` +- New function `PossibleCreatedByTypeValues() []CreatedByType` +- New function `PossibleAutoLearnPrivateRangesModeValues() []AutoLearnPrivateRangesMode` +- New function `*ManagementGroupNetworkManagerConnectionsClient.CreateOrUpdate(context.Context, string, string, ManagerConnection, *ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateOptions) (ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse, error)` +- New function `*GroupsClient.CreateOrUpdate(context.Context, string, string, string, Group, *GroupsClientCreateOrUpdateOptions) (GroupsClientCreateOrUpdateResponse, error)` +- New function `*ActiveSecurityAdminRule.GetActiveBaseSecurityAdminRule() *ActiveBaseSecurityAdminRule` +- New function `*AdminRuleCollectionsClient.Get(context.Context, string, string, string, string, *AdminRuleCollectionsClientGetOptions) (AdminRuleCollectionsClientGetResponse, error)` +- New function `*ManagersClient.CreateOrUpdate(context.Context, string, string, Manager, *ManagersClientCreateOrUpdateOptions) (ManagersClientCreateOrUpdateResponse, error)` +- New function `*SubscriptionNetworkManagerConnectionsClient.NewListPager(*SubscriptionNetworkManagerConnectionsClientListOptions) *runtime.Pager[SubscriptionNetworkManagerConnectionsClientListResponse]` +- New function `*AdminRule.GetBaseAdminRule() *BaseAdminRule` +- New function `*AdminRulesClient.Get(context.Context, string, string, string, string, string, *AdminRulesClientGetOptions) (AdminRulesClientGetResponse, error)` +- New function `PossiblePacketCaptureTargetTypeValues() []PacketCaptureTargetType` +- New function `*ManagementClient.ListNetworkManagerEffectiveSecurityAdminRules(context.Context, string, string, QueryRequestOptions, *ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions) (ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse, error)` +- New function `*ManagementGroupNetworkManagerConnectionsClient.Get(context.Context, string, string, *ManagementGroupNetworkManagerConnectionsClientGetOptions) (ManagementGroupNetworkManagerConnectionsClientGetResponse, error)` +- New function `NewExpressRouteProviderPortsLocationClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ExpressRouteProviderPortsLocationClient, error)` +- New function `*DefaultAdminRule.GetBaseAdminRule() *BaseAdminRule` +- New function `*ConnectivityConfigurationsClient.Get(context.Context, string, string, string, *ConnectivityConfigurationsClientGetOptions) (ConnectivityConfigurationsClientGetResponse, error)` +- New function `NewManagersClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagersClient, error)` +- New function `*SubscriptionNetworkManagerConnectionsClient.Get(context.Context, string, *SubscriptionNetworkManagerConnectionsClientGetOptions) (SubscriptionNetworkManagerConnectionsClientGetResponse, error)` +- New function `*EffectiveSecurityAdminRule.GetEffectiveBaseSecurityAdminRule() *EffectiveBaseSecurityAdminRule` +- New function `*EffectiveBaseSecurityAdminRule.GetEffectiveBaseSecurityAdminRule() *EffectiveBaseSecurityAdminRule` +- New function `NewScopeConnectionsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ScopeConnectionsClient, error)` +- New function `NewAdminRuleCollectionsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*AdminRuleCollectionsClient, error)` +- New function `*ManagementClient.ListNetworkManagerEffectiveConnectivityConfigurations(context.Context, string, string, QueryRequestOptions, *ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions) (ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse, error)` +- New function `PossibleGroupConnectivityValues() []GroupConnectivity` +- New function `NewSubscriptionNetworkManagerConnectionsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*SubscriptionNetworkManagerConnectionsClient, error)` +- New function `*AzureFirewallsClient.BeginListLearnedPrefixes(context.Context, string, string, *AzureFirewallsClientBeginListLearnedPrefixesOptions) (*runtime.Poller[AzureFirewallsClientListLearnedPrefixesResponse], error)` +- New function `*ManagersClient.Patch(context.Context, string, string, PatchObject, *ManagersClientPatchOptions) (ManagersClientPatchResponse, error)` +- New function `*ManagersClient.Get(context.Context, string, string, *ManagersClientGetOptions) (ManagersClientGetResponse, error)` +- New function `*StaticMembersClient.CreateOrUpdate(context.Context, string, string, string, string, StaticMember, *StaticMembersClientCreateOrUpdateOptions) (StaticMembersClientCreateOrUpdateResponse, error)` +- New function `*AdminRuleCollectionsClient.NewListPager(string, string, string, *AdminRuleCollectionsClientListOptions) *runtime.Pager[AdminRuleCollectionsClientListResponse]` +- New function `*ScopeConnectionsClient.NewListPager(string, string, *ScopeConnectionsClientListOptions) *runtime.Pager[ScopeConnectionsClientListResponse]` +- New function `*ActiveDefaultSecurityAdminRule.GetActiveBaseSecurityAdminRule() *ActiveBaseSecurityAdminRule` +- New function `*ExpressRouteProviderPortsLocationClient.List(context.Context, *ExpressRouteProviderPortsLocationClientListOptions) (ExpressRouteProviderPortsLocationClientListResponse, error)` +- New function `*ManagerCommitsClient.BeginPost(context.Context, string, string, ManagerCommit, *ManagerCommitsClientBeginPostOptions) (*runtime.Poller[ManagerCommitsClientPostResponse], error)` +- New function `NewManagerCommitsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagerCommitsClient, error)` +- New function `PossibleConfigurationTypeValues() []ConfigurationType` +- New function `NewManagerDeploymentStatusClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagerDeploymentStatusClient, error)` +- New function `*ScopeConnectionsClient.CreateOrUpdate(context.Context, string, string, string, ScopeConnection, *ScopeConnectionsClientCreateOrUpdateOptions) (ScopeConnectionsClientCreateOrUpdateResponse, error)` +- New function `*SecurityAdminConfigurationsClient.CreateOrUpdate(context.Context, string, string, string, SecurityAdminConfiguration, *SecurityAdminConfigurationsClientCreateOrUpdateOptions) (SecurityAdminConfigurationsClientCreateOrUpdateResponse, error)` +- New function `NewManagementGroupNetworkManagerConnectionsClient(azcore.TokenCredential, *arm.ClientOptions) (*ManagementGroupNetworkManagerConnectionsClient, error)` +- New function `PossibleDeleteExistingPeeringValues() []DeleteExistingPeering` +- New function `PossibleDeploymentStatusValues() []DeploymentStatus` +- New function `*ManagementGroupNetworkManagerConnectionsClient.NewListPager(string, *ManagementGroupNetworkManagerConnectionsClientListOptions) *runtime.Pager[ManagementGroupNetworkManagerConnectionsClientListResponse]` +- New function `*SecurityAdminConfigurationsClient.NewListPager(string, string, *SecurityAdminConfigurationsClientListOptions) *runtime.Pager[SecurityAdminConfigurationsClientListResponse]` +- New function `PossibleConnectivityTopologyValues() []ConnectivityTopology` +- New function `*StaticMembersClient.Get(context.Context, string, string, string, string, *StaticMembersClientGetOptions) (StaticMembersClientGetResponse, error)` +- New function `PossibleSecurityConfigurationRuleDirectionValues() []SecurityConfigurationRuleDirection` +- New function `*SecurityAdminConfigurationsClient.BeginDelete(context.Context, string, string, string, *SecurityAdminConfigurationsClientBeginDeleteOptions) (*runtime.Poller[SecurityAdminConfigurationsClientDeleteResponse], error)` +- New function `NewSecurityAdminConfigurationsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*SecurityAdminConfigurationsClient, error)` +- New function `*AdminRulesClient.BeginDelete(context.Context, string, string, string, string, string, *AdminRulesClientBeginDeleteOptions) (*runtime.Poller[AdminRulesClientDeleteResponse], error)` +- New function `*SubscriptionNetworkManagerConnectionsClient.CreateOrUpdate(context.Context, string, ManagerConnection, *SubscriptionNetworkManagerConnectionsClientCreateOrUpdateOptions) (SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse, error)` +- New struct `ActiveBaseSecurityAdminRule` +- New struct `ActiveConfigurationParameter` +- New struct `ActiveConnectivityConfiguration` +- New struct `ActiveConnectivityConfigurationsListResult` +- New struct `ActiveDefaultSecurityAdminRule` +- New struct `ActiveSecurityAdminRule` +- New struct `ActiveSecurityAdminRulesListResult` +- New struct `AddressPrefixItem` +- New struct `AdminPropertiesFormat` +- New struct `AdminRule` +- New struct `AdminRuleCollection` +- New struct `AdminRuleCollectionListResult` +- New struct `AdminRuleCollectionPropertiesFormat` +- New struct `AdminRuleCollectionsClient` +- New struct `AdminRuleCollectionsClientBeginDeleteOptions` +- New struct `AdminRuleCollectionsClientCreateOrUpdateOptions` +- New struct `AdminRuleCollectionsClientCreateOrUpdateResponse` +- New struct `AdminRuleCollectionsClientDeleteResponse` +- New struct `AdminRuleCollectionsClientGetOptions` +- New struct `AdminRuleCollectionsClientGetResponse` +- New struct `AdminRuleCollectionsClientListOptions` +- New struct `AdminRuleCollectionsClientListResponse` +- New struct `AdminRuleListResult` +- New struct `AdminRulesClient` +- New struct `AdminRulesClientBeginDeleteOptions` +- New struct `AdminRulesClientCreateOrUpdateOptions` +- New struct `AdminRulesClientCreateOrUpdateResponse` +- New struct `AdminRulesClientDeleteResponse` +- New struct `AdminRulesClientGetOptions` +- New struct `AdminRulesClientGetResponse` +- New struct `AdminRulesClientListOptions` +- New struct `AdminRulesClientListResponse` +- New struct `AzureFirewallsClientBeginListLearnedPrefixesOptions` +- New struct `AzureFirewallsClientListLearnedPrefixesResponse` +- New struct `BaseAdminRule` +- New struct `ChildResource` +- New struct `ConfigurationGroup` +- New struct `ConnectivityConfiguration` +- New struct `ConnectivityConfigurationListResult` +- New struct `ConnectivityConfigurationProperties` +- New struct `ConnectivityConfigurationsClient` +- New struct `ConnectivityConfigurationsClientBeginDeleteOptions` +- New struct `ConnectivityConfigurationsClientCreateOrUpdateOptions` +- New struct `ConnectivityConfigurationsClientCreateOrUpdateResponse` +- New struct `ConnectivityConfigurationsClientDeleteResponse` +- New struct `ConnectivityConfigurationsClientGetOptions` +- New struct `ConnectivityConfigurationsClientGetResponse` +- New struct `ConnectivityConfigurationsClientListOptions` +- New struct `ConnectivityConfigurationsClientListResponse` +- New struct `ConnectivityGroupItem` +- New struct `CrossTenantScopes` +- New struct `DefaultAdminPropertiesFormat` +- New struct `DefaultAdminRule` +- New struct `EffectiveBaseSecurityAdminRule` +- New struct `EffectiveConnectivityConfiguration` +- New struct `EffectiveDefaultSecurityAdminRule` +- New struct `EffectiveSecurityAdminRule` +- New struct `ExpressRouteProviderPort` +- New struct `ExpressRouteProviderPortListResult` +- New struct `ExpressRouteProviderPortProperties` +- New struct `ExpressRouteProviderPortsLocationClient` +- New struct `ExpressRouteProviderPortsLocationClientListOptions` +- New struct `ExpressRouteProviderPortsLocationClientListResponse` +- New struct `Group` +- New struct `GroupListResult` +- New struct `GroupProperties` +- New struct `GroupsClient` +- New struct `GroupsClientBeginDeleteOptions` +- New struct `GroupsClientCreateOrUpdateOptions` +- New struct `GroupsClientCreateOrUpdateResponse` +- New struct `GroupsClientDeleteResponse` +- New struct `GroupsClientGetOptions` +- New struct `GroupsClientGetResponse` +- New struct `GroupsClientListOptions` +- New struct `GroupsClientListResponse` +- New struct `Hub` +- New struct `IPPrefixesList` +- New struct `ManagementClientExpressRouteProviderPortOptions` +- New struct `ManagementClientExpressRouteProviderPortResponse` +- New struct `ManagementClientListActiveConnectivityConfigurationsOptions` +- New struct `ManagementClientListActiveConnectivityConfigurationsResponse` +- New struct `ManagementClientListActiveSecurityAdminRulesOptions` +- New struct `ManagementClientListActiveSecurityAdminRulesResponse` +- New struct `ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions` +- New struct `ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse` +- New struct `ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions` +- New struct `ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse` +- New struct `ManagementGroupNetworkManagerConnectionsClient` +- New struct `ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateOptions` +- New struct `ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse` +- New struct `ManagementGroupNetworkManagerConnectionsClientDeleteOptions` +- New struct `ManagementGroupNetworkManagerConnectionsClientDeleteResponse` +- New struct `ManagementGroupNetworkManagerConnectionsClientGetOptions` +- New struct `ManagementGroupNetworkManagerConnectionsClientGetResponse` +- New struct `ManagementGroupNetworkManagerConnectionsClientListOptions` +- New struct `ManagementGroupNetworkManagerConnectionsClientListResponse` +- New struct `Manager` +- New struct `ManagerCommit` +- New struct `ManagerCommitsClient` +- New struct `ManagerCommitsClientBeginPostOptions` +- New struct `ManagerCommitsClientPostResponse` +- New struct `ManagerConnection` +- New struct `ManagerConnectionListResult` +- New struct `ManagerConnectionProperties` +- New struct `ManagerDeploymentStatus` +- New struct `ManagerDeploymentStatusClient` +- New struct `ManagerDeploymentStatusClientListOptions` +- New struct `ManagerDeploymentStatusClientListResponse` +- New struct `ManagerDeploymentStatusListResult` +- New struct `ManagerDeploymentStatusParameter` +- New struct `ManagerEffectiveConnectivityConfigurationListResult` +- New struct `ManagerEffectiveSecurityAdminRulesListResult` +- New struct `ManagerListResult` +- New struct `ManagerProperties` +- New struct `ManagerPropertiesNetworkManagerScopes` +- New struct `ManagerSecurityGroupItem` +- New struct `ManagersClient` +- New struct `ManagersClientBeginDeleteOptions` +- New struct `ManagersClientCreateOrUpdateOptions` +- New struct `ManagersClientCreateOrUpdateResponse` +- New struct `ManagersClientDeleteResponse` +- New struct `ManagersClientGetOptions` +- New struct `ManagersClientGetResponse` +- New struct `ManagersClientListBySubscriptionOptions` +- New struct `ManagersClientListBySubscriptionResponse` +- New struct `ManagersClientListOptions` +- New struct `ManagersClientListResponse` +- New struct `ManagersClientPatchOptions` +- New struct `ManagersClientPatchResponse` +- New struct `PacketCaptureMachineScope` +- New struct `PatchObject` +- New struct `QueryRequestOptions` +- New struct `ScopeConnection` +- New struct `ScopeConnectionListResult` +- New struct `ScopeConnectionProperties` +- New struct `ScopeConnectionsClient` +- New struct `ScopeConnectionsClientCreateOrUpdateOptions` +- New struct `ScopeConnectionsClientCreateOrUpdateResponse` +- New struct `ScopeConnectionsClientDeleteOptions` +- New struct `ScopeConnectionsClientDeleteResponse` +- New struct `ScopeConnectionsClientGetOptions` +- New struct `ScopeConnectionsClientGetResponse` +- New struct `ScopeConnectionsClientListOptions` +- New struct `ScopeConnectionsClientListResponse` +- New struct `SecurityAdminConfiguration` +- New struct `SecurityAdminConfigurationListResult` +- New struct `SecurityAdminConfigurationPropertiesFormat` +- New struct `SecurityAdminConfigurationsClient` +- New struct `SecurityAdminConfigurationsClientBeginDeleteOptions` +- New struct `SecurityAdminConfigurationsClientCreateOrUpdateOptions` +- New struct `SecurityAdminConfigurationsClientCreateOrUpdateResponse` +- New struct `SecurityAdminConfigurationsClientDeleteResponse` +- New struct `SecurityAdminConfigurationsClientGetOptions` +- New struct `SecurityAdminConfigurationsClientGetResponse` +- New struct `SecurityAdminConfigurationsClientListOptions` +- New struct `SecurityAdminConfigurationsClientListResponse` +- New struct `StaticMember` +- New struct `StaticMemberListResult` +- New struct `StaticMemberProperties` +- New struct `StaticMembersClient` +- New struct `StaticMembersClientCreateOrUpdateOptions` +- New struct `StaticMembersClientCreateOrUpdateResponse` +- New struct `StaticMembersClientDeleteOptions` +- New struct `StaticMembersClientDeleteResponse` +- New struct `StaticMembersClientGetOptions` +- New struct `StaticMembersClientGetResponse` +- New struct `StaticMembersClientListOptions` +- New struct `StaticMembersClientListResponse` +- New struct `SubscriptionNetworkManagerConnectionsClient` +- New struct `SubscriptionNetworkManagerConnectionsClientCreateOrUpdateOptions` +- New struct `SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse` +- New struct `SubscriptionNetworkManagerConnectionsClientDeleteOptions` +- New struct `SubscriptionNetworkManagerConnectionsClientDeleteResponse` +- New struct `SubscriptionNetworkManagerConnectionsClientGetOptions` +- New struct `SubscriptionNetworkManagerConnectionsClientGetResponse` +- New struct `SubscriptionNetworkManagerConnectionsClientListOptions` +- New struct `SubscriptionNetworkManagerConnectionsClientListResponse` +- New struct `SystemData` +- New struct `VirtualRouterAutoScaleConfiguration` +- New field `NoInternetAdvertise` in struct `CustomIPPrefixPropertiesFormat` +- New field `FlushConnection` in struct `SecurityGroupPropertiesFormat` +- New field `EnablePacFile` in struct `ExplicitProxySettings` +- New field `Scope` in struct `PacketCaptureParameters` +- New field `TargetType` in struct `PacketCaptureParameters` +- New field `Scope` in struct `PacketCaptureResultProperties` +- New field `TargetType` in struct `PacketCaptureResultProperties` +- New field `AutoLearnPrivateRanges` in struct `FirewallPolicySNAT` +- New field `VirtualRouterAutoScaleConfiguration` in struct `VirtualHubProperties` +- New field `Priority` in struct `ApplicationGatewayRoutingRulePropertiesFormat` + + +## 1.0.0 (2022-05-16) + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork` 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). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/LICENSE.txt new file mode 100644 index 000000000..dc0c2ffb3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/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/network/armnetwork/v4/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/README.md new file mode 100644 index 000000000..093565038 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/README.md @@ -0,0 +1,102 @@ +# Azure Network Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v2)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v2) + +The `armnetwork` module provides operations for working with Azure Network. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/network/armnetwork) + +# 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 Network module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v2 +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Network. 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 Network 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 := armnetwork.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 := armnetwork.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.NewVirtualHubBgpConnectionsClient() +``` + +## 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 + +- [Creating a Fake](https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/resourcemanager/network/armnetwork/fake_example_test.go) +- [IP Address](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/network/ipaddress) +- [Load Balancer](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/network/loadbalancer) +- [Network Interface](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/network/networkInterface) +- [Security Group](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/network/securitygroups) +- [Subnet](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/network/subnets) +- [Virtual Network](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/network/virtualnetwork) + +## 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 `Network` 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/network/armnetwork/v4/adminrulecollections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/adminrulecollections_client.go new file mode 100644 index 000000000..c3b96670a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/adminrulecollections_client.go @@ -0,0 +1,366 @@ +//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 armnetwork + +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" +) + +// AdminRuleCollectionsClient contains the methods for the AdminRuleCollections group. +// Don't use this type directly, use NewAdminRuleCollectionsClient() instead. +type AdminRuleCollectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAdminRuleCollectionsClient creates a new instance of AdminRuleCollectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAdminRuleCollectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AdminRuleCollectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AdminRuleCollectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates an admin rule collection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - ruleCollectionName - The name of the network manager security Configuration rule collection. +// - ruleCollection - The Rule Collection to create or update +// - options - AdminRuleCollectionsClientCreateOrUpdateOptions contains the optional parameters for the AdminRuleCollectionsClient.CreateOrUpdate +// method. +func (client *AdminRuleCollectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleCollection AdminRuleCollection, options *AdminRuleCollectionsClientCreateOrUpdateOptions) (AdminRuleCollectionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "AdminRuleCollectionsClient.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, networkManagerName, configurationName, ruleCollectionName, ruleCollection, options) + if err != nil { + return AdminRuleCollectionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AdminRuleCollectionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AdminRuleCollectionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AdminRuleCollectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleCollection AdminRuleCollection, options *AdminRuleCollectionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, ruleCollection); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *AdminRuleCollectionsClient) createOrUpdateHandleResponse(resp *http.Response) (AdminRuleCollectionsClientCreateOrUpdateResponse, error) { + result := AdminRuleCollectionsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AdminRuleCollection); err != nil { + return AdminRuleCollectionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes an admin rule collection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - ruleCollectionName - The name of the network manager security Configuration rule collection. +// - options - AdminRuleCollectionsClientBeginDeleteOptions contains the optional parameters for the AdminRuleCollectionsClient.BeginDelete +// method. +func (client *AdminRuleCollectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, options *AdminRuleCollectionsClientBeginDeleteOptions) (*runtime.Poller[AdminRuleCollectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AdminRuleCollectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AdminRuleCollectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes an admin rule collection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *AdminRuleCollectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, options *AdminRuleCollectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AdminRuleCollectionsClient.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, networkManagerName, configurationName, ruleCollectionName, 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 *AdminRuleCollectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, options *AdminRuleCollectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + 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-05-01") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a network manager security admin configuration rule collection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - ruleCollectionName - The name of the network manager security Configuration rule collection. +// - options - AdminRuleCollectionsClientGetOptions contains the optional parameters for the AdminRuleCollectionsClient.Get +// method. +func (client *AdminRuleCollectionsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, options *AdminRuleCollectionsClientGetOptions) (AdminRuleCollectionsClientGetResponse, error) { + var err error + const operationName = "AdminRuleCollectionsClient.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, networkManagerName, configurationName, ruleCollectionName, options) + if err != nil { + return AdminRuleCollectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AdminRuleCollectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AdminRuleCollectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AdminRuleCollectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, options *AdminRuleCollectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AdminRuleCollectionsClient) getHandleResponse(resp *http.Response) (AdminRuleCollectionsClientGetResponse, error) { + result := AdminRuleCollectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AdminRuleCollection); err != nil { + return AdminRuleCollectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the rule collections in a security admin configuration, in a paginated format. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - options - AdminRuleCollectionsClientListOptions contains the optional parameters for the AdminRuleCollectionsClient.NewListPager +// method. +func (client *AdminRuleCollectionsClient) NewListPager(resourceGroupName string, networkManagerName string, configurationName string, options *AdminRuleCollectionsClientListOptions) *runtime.Pager[AdminRuleCollectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AdminRuleCollectionsClientListResponse]{ + More: func(page AdminRuleCollectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AdminRuleCollectionsClientListResponse) (AdminRuleCollectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AdminRuleCollectionsClient.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, networkManagerName, configurationName, options) + }, nil) + if err != nil { + return AdminRuleCollectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AdminRuleCollectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *AdminRuleCollectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AdminRuleCollectionsClient) listHandleResponse(resp *http.Response) (AdminRuleCollectionsClientListResponse, error) { + result := AdminRuleCollectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AdminRuleCollectionListResult); err != nil { + return AdminRuleCollectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/adminrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/adminrules_client.go new file mode 100644 index 000000000..f5928b3df --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/adminrules_client.go @@ -0,0 +1,383 @@ +//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 armnetwork + +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" +) + +// AdminRulesClient contains the methods for the AdminRules group. +// Don't use this type directly, use NewAdminRulesClient() instead. +type AdminRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAdminRulesClient creates a new instance of AdminRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAdminRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AdminRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AdminRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates an admin rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - ruleCollectionName - The name of the network manager security Configuration rule collection. +// - ruleName - The name of the rule. +// - adminRule - The admin rule to create or update +// - options - AdminRulesClientCreateOrUpdateOptions contains the optional parameters for the AdminRulesClient.CreateOrUpdate +// method. +func (client *AdminRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, adminRule BaseAdminRuleClassification, options *AdminRulesClientCreateOrUpdateOptions) (AdminRulesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "AdminRulesClient.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, networkManagerName, configurationName, ruleCollectionName, ruleName, adminRule, options) + if err != nil { + return AdminRulesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AdminRulesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AdminRulesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AdminRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, adminRule BaseAdminRuleClassification, options *AdminRulesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules/{ruleName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, adminRule); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *AdminRulesClient) createOrUpdateHandleResponse(resp *http.Response) (AdminRulesClientCreateOrUpdateResponse, error) { + result := AdminRulesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return AdminRulesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes an admin rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - ruleCollectionName - The name of the network manager security Configuration rule collection. +// - ruleName - The name of the rule. +// - options - AdminRulesClientBeginDeleteOptions contains the optional parameters for the AdminRulesClient.BeginDelete method. +func (client *AdminRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, options *AdminRulesClientBeginDeleteOptions) (*runtime.Poller[AdminRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, ruleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AdminRulesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AdminRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes an admin rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *AdminRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, options *AdminRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AdminRulesClient.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, networkManagerName, configurationName, ruleCollectionName, ruleName, 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 *AdminRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, options *AdminRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules/{ruleName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + 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-05-01") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a network manager security configuration admin rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - ruleCollectionName - The name of the network manager security Configuration rule collection. +// - ruleName - The name of the rule. +// - options - AdminRulesClientGetOptions contains the optional parameters for the AdminRulesClient.Get method. +func (client *AdminRulesClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, options *AdminRulesClientGetOptions) (AdminRulesClientGetResponse, error) { + var err error + const operationName = "AdminRulesClient.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, networkManagerName, configurationName, ruleCollectionName, ruleName, options) + if err != nil { + return AdminRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AdminRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AdminRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AdminRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, options *AdminRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules/{ruleName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AdminRulesClient) getHandleResponse(resp *http.Response) (AdminRulesClientGetResponse, error) { + result := AdminRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return AdminRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all network manager security configuration admin rules. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - ruleCollectionName - The name of the network manager security Configuration rule collection. +// - options - AdminRulesClientListOptions contains the optional parameters for the AdminRulesClient.NewListPager method. +func (client *AdminRulesClient) NewListPager(resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, options *AdminRulesClientListOptions) *runtime.Pager[AdminRulesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AdminRulesClientListResponse]{ + More: func(page AdminRulesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AdminRulesClientListResponse) (AdminRulesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AdminRulesClient.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, networkManagerName, configurationName, ruleCollectionName, options) + }, nil) + if err != nil { + return AdminRulesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AdminRulesClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, options *AdminRulesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AdminRulesClient) listHandleResponse(resp *http.Response) (AdminRulesClientListResponse, error) { + result := AdminRulesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AdminRuleListResult); err != nil { + return AdminRulesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewayprivateendpointconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewayprivateendpointconnections_client.go new file mode 100644 index 000000000..6632c4bd2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewayprivateendpointconnections_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ApplicationGatewayPrivateEndpointConnectionsClient contains the methods for the ApplicationGatewayPrivateEndpointConnections group. +// Don't use this type directly, use NewApplicationGatewayPrivateEndpointConnectionsClient() instead. +type ApplicationGatewayPrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewApplicationGatewayPrivateEndpointConnectionsClient creates a new instance of ApplicationGatewayPrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewApplicationGatewayPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicationGatewayPrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApplicationGatewayPrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginDelete - Deletes the specified private endpoint connection on application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - connectionName - The name of the application gateway private endpoint connection. +// - options - ApplicationGatewayPrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the +// ApplicationGatewayPrivateEndpointConnectionsClient.BeginDelete method. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, options *ApplicationGatewayPrivateEndpointConnectionsClientBeginDeleteOptions) (*runtime.Poller[ApplicationGatewayPrivateEndpointConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, applicationGatewayName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewayPrivateEndpointConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewayPrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified private endpoint connection on application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, options *ApplicationGatewayPrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewayPrivateEndpointConnectionsClient.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, applicationGatewayName, connectionName, 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 *ApplicationGatewayPrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, options *ApplicationGatewayPrivateEndpointConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/privateEndpointConnections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified private endpoint connection on application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - connectionName - The name of the application gateway private endpoint connection. +// - options - ApplicationGatewayPrivateEndpointConnectionsClientGetOptions contains the optional parameters for the ApplicationGatewayPrivateEndpointConnectionsClient.Get +// method. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, options *ApplicationGatewayPrivateEndpointConnectionsClientGetOptions) (ApplicationGatewayPrivateEndpointConnectionsClientGetResponse, error) { + var err error + const operationName = "ApplicationGatewayPrivateEndpointConnectionsClient.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, applicationGatewayName, connectionName, options) + if err != nil { + return ApplicationGatewayPrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewayPrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewayPrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, options *ApplicationGatewayPrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/privateEndpointConnections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (ApplicationGatewayPrivateEndpointConnectionsClientGetResponse, error) { + result := ApplicationGatewayPrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayPrivateEndpointConnection); err != nil { + return ApplicationGatewayPrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all private endpoint connections on an application gateway. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - options - ApplicationGatewayPrivateEndpointConnectionsClientListOptions contains the optional parameters for the ApplicationGatewayPrivateEndpointConnectionsClient.NewListPager +// method. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) NewListPager(resourceGroupName string, applicationGatewayName string, options *ApplicationGatewayPrivateEndpointConnectionsClientListOptions) *runtime.Pager[ApplicationGatewayPrivateEndpointConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationGatewayPrivateEndpointConnectionsClientListResponse]{ + More: func(page ApplicationGatewayPrivateEndpointConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationGatewayPrivateEndpointConnectionsClientListResponse) (ApplicationGatewayPrivateEndpointConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationGatewayPrivateEndpointConnectionsClient.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, applicationGatewayName, options) + }, nil) + if err != nil { + return ApplicationGatewayPrivateEndpointConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewayPrivateEndpointConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/privateEndpointConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) listHandleResponse(resp *http.Response) (ApplicationGatewayPrivateEndpointConnectionsClientListResponse, error) { + result := ApplicationGatewayPrivateEndpointConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayPrivateEndpointConnectionListResult); err != nil { + return ApplicationGatewayPrivateEndpointConnectionsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates the specified private endpoint connection on application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - connectionName - The name of the application gateway private endpoint connection. +// - parameters - Parameters supplied to update application gateway private endpoint connection operation. +// - options - ApplicationGatewayPrivateEndpointConnectionsClientBeginUpdateOptions contains the optional parameters for the +// ApplicationGatewayPrivateEndpointConnectionsClient.BeginUpdate method. +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) BeginUpdate(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, parameters ApplicationGatewayPrivateEndpointConnection, options *ApplicationGatewayPrivateEndpointConnectionsClientBeginUpdateOptions) (*runtime.Poller[ApplicationGatewayPrivateEndpointConnectionsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, applicationGatewayName, connectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewayPrivateEndpointConnectionsClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewayPrivateEndpointConnectionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates the specified private endpoint connection on application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewayPrivateEndpointConnectionsClient) update(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, parameters ApplicationGatewayPrivateEndpointConnection, options *ApplicationGatewayPrivateEndpointConnectionsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewayPrivateEndpointConnectionsClient.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, applicationGatewayName, connectionName, 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 *ApplicationGatewayPrivateEndpointConnectionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, parameters ApplicationGatewayPrivateEndpointConnection, options *ApplicationGatewayPrivateEndpointConnectionsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/privateEndpointConnections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-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/network/armnetwork/v4/applicationgatewayprivatelinkresources_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewayprivatelinkresources_client.go new file mode 100644 index 000000000..a57e95d52 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewayprivatelinkresources_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 armnetwork + +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" +) + +// ApplicationGatewayPrivateLinkResourcesClient contains the methods for the ApplicationGatewayPrivateLinkResources group. +// Don't use this type directly, use NewApplicationGatewayPrivateLinkResourcesClient() instead. +type ApplicationGatewayPrivateLinkResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewApplicationGatewayPrivateLinkResourcesClient creates a new instance of ApplicationGatewayPrivateLinkResourcesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewApplicationGatewayPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicationGatewayPrivateLinkResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApplicationGatewayPrivateLinkResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Lists all private link resources on an application gateway. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - options - ApplicationGatewayPrivateLinkResourcesClientListOptions contains the optional parameters for the ApplicationGatewayPrivateLinkResourcesClient.NewListPager +// method. +func (client *ApplicationGatewayPrivateLinkResourcesClient) NewListPager(resourceGroupName string, applicationGatewayName string, options *ApplicationGatewayPrivateLinkResourcesClientListOptions) *runtime.Pager[ApplicationGatewayPrivateLinkResourcesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationGatewayPrivateLinkResourcesClientListResponse]{ + More: func(page ApplicationGatewayPrivateLinkResourcesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationGatewayPrivateLinkResourcesClientListResponse) (ApplicationGatewayPrivateLinkResourcesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationGatewayPrivateLinkResourcesClient.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, applicationGatewayName, options) + }, nil) + if err != nil { + return ApplicationGatewayPrivateLinkResourcesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ApplicationGatewayPrivateLinkResourcesClient) listCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewayPrivateLinkResourcesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/privateLinkResources" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ApplicationGatewayPrivateLinkResourcesClient) listHandleResponse(resp *http.Response) (ApplicationGatewayPrivateLinkResourcesClientListResponse, error) { + result := ApplicationGatewayPrivateLinkResourcesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayPrivateLinkResourceListResult); err != nil { + return ApplicationGatewayPrivateLinkResourcesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgateways_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgateways_client.go new file mode 100644 index 000000000..713c18f0e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgateways_client.go @@ -0,0 +1,1161 @@ +//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 armnetwork + +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" +) + +// ApplicationGatewaysClient contains the methods for the ApplicationGateways group. +// Don't use this type directly, use NewApplicationGatewaysClient() instead. +type ApplicationGatewaysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewApplicationGatewaysClient creates a new instance of ApplicationGatewaysClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewApplicationGatewaysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicationGatewaysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApplicationGatewaysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginBackendHealth - Gets the backend health of the specified application gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - options - ApplicationGatewaysClientBeginBackendHealthOptions contains the optional parameters for the ApplicationGatewaysClient.BeginBackendHealth +// method. +func (client *ApplicationGatewaysClient) BeginBackendHealth(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginBackendHealthOptions) (*runtime.Poller[ApplicationGatewaysClientBackendHealthResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.backendHealth(ctx, resourceGroupName, applicationGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewaysClientBackendHealthResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewaysClientBackendHealthResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// BackendHealth - Gets the backend health of the specified application gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewaysClient) backendHealth(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginBackendHealthOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewaysClient.BeginBackendHealth" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.backendHealthCreateRequest(ctx, resourceGroupName, applicationGatewayName, 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 +} + +// backendHealthCreateRequest creates the BackendHealth request. +func (client *ApplicationGatewaysClient) backendHealthCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginBackendHealthOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/backendhealth" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + 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 +} + +// BeginBackendHealthOnDemand - Gets the backend health for given combination of backend pool and http setting of the specified +// application gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - probeRequest - Request body for on-demand test probe operation. +// - options - ApplicationGatewaysClientBeginBackendHealthOnDemandOptions contains the optional parameters for the ApplicationGatewaysClient.BeginBackendHealthOnDemand +// method. +func (client *ApplicationGatewaysClient) BeginBackendHealthOnDemand(ctx context.Context, resourceGroupName string, applicationGatewayName string, probeRequest ApplicationGatewayOnDemandProbe, options *ApplicationGatewaysClientBeginBackendHealthOnDemandOptions) (*runtime.Poller[ApplicationGatewaysClientBackendHealthOnDemandResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.backendHealthOnDemand(ctx, resourceGroupName, applicationGatewayName, probeRequest, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewaysClientBackendHealthOnDemandResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewaysClientBackendHealthOnDemandResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// BackendHealthOnDemand - Gets the backend health for given combination of backend pool and http setting of the specified +// application gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewaysClient) backendHealthOnDemand(ctx context.Context, resourceGroupName string, applicationGatewayName string, probeRequest ApplicationGatewayOnDemandProbe, options *ApplicationGatewaysClientBeginBackendHealthOnDemandOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewaysClient.BeginBackendHealthOnDemand" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.backendHealthOnDemandCreateRequest(ctx, resourceGroupName, applicationGatewayName, probeRequest, 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 +} + +// backendHealthOnDemandCreateRequest creates the BackendHealthOnDemand request. +func (client *ApplicationGatewaysClient) backendHealthOnDemandCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, probeRequest ApplicationGatewayOnDemandProbe, options *ApplicationGatewaysClientBeginBackendHealthOnDemandOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/getBackendHealthOnDemand" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, probeRequest); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - parameters - Parameters supplied to the create or update application gateway operation. +// - options - ApplicationGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the ApplicationGatewaysClient.BeginCreateOrUpdate +// method. +func (client *ApplicationGatewaysClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, options *ApplicationGatewaysClientBeginCreateOrUpdateOptions) (*runtime.Poller[ApplicationGatewaysClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, applicationGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewaysClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewaysClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewaysClient) createOrUpdate(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, options *ApplicationGatewaysClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewaysClient.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, applicationGatewayName, 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 *ApplicationGatewaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, options *ApplicationGatewaysClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-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 application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - options - ApplicationGatewaysClientBeginDeleteOptions contains the optional parameters for the ApplicationGatewaysClient.BeginDelete +// method. +func (client *ApplicationGatewaysClient) BeginDelete(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginDeleteOptions) (*runtime.Poller[ApplicationGatewaysClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, applicationGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewaysClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewaysClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewaysClient) deleteOperation(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewaysClient.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, applicationGatewayName, 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 *ApplicationGatewaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - options - ApplicationGatewaysClientGetOptions contains the optional parameters for the ApplicationGatewaysClient.Get method. +func (client *ApplicationGatewaysClient) Get(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientGetOptions) (ApplicationGatewaysClientGetResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.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, applicationGatewayName, options) + if err != nil { + return ApplicationGatewaysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ApplicationGatewaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ApplicationGatewaysClient) getHandleResponse(resp *http.Response) (ApplicationGatewaysClientGetResponse, error) { + result := ApplicationGatewaysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGateway); err != nil { + return ApplicationGatewaysClientGetResponse{}, err + } + return result, nil +} + +// GetSSLPredefinedPolicy - Gets Ssl predefined policy with the specified policy name. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - predefinedPolicyName - Name of Ssl predefined policy. +// - options - ApplicationGatewaysClientGetSSLPredefinedPolicyOptions contains the optional parameters for the ApplicationGatewaysClient.GetSSLPredefinedPolicy +// method. +func (client *ApplicationGatewaysClient) GetSSLPredefinedPolicy(ctx context.Context, predefinedPolicyName string, options *ApplicationGatewaysClientGetSSLPredefinedPolicyOptions) (ApplicationGatewaysClientGetSSLPredefinedPolicyResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.GetSSLPredefinedPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getSSLPredefinedPolicyCreateRequest(ctx, predefinedPolicyName, options) + if err != nil { + return ApplicationGatewaysClientGetSSLPredefinedPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientGetSSLPredefinedPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientGetSSLPredefinedPolicyResponse{}, err + } + resp, err := client.getSSLPredefinedPolicyHandleResponse(httpResp) + return resp, err +} + +// getSSLPredefinedPolicyCreateRequest creates the GetSSLPredefinedPolicy request. +func (client *ApplicationGatewaysClient) getSSLPredefinedPolicyCreateRequest(ctx context.Context, predefinedPolicyName string, options *ApplicationGatewaysClientGetSSLPredefinedPolicyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies/{predefinedPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if predefinedPolicyName == "" { + return nil, errors.New("parameter predefinedPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{predefinedPolicyName}", url.PathEscape(predefinedPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getSSLPredefinedPolicyHandleResponse handles the GetSSLPredefinedPolicy response. +func (client *ApplicationGatewaysClient) getSSLPredefinedPolicyHandleResponse(resp *http.Response) (ApplicationGatewaysClientGetSSLPredefinedPolicyResponse, error) { + result := ApplicationGatewaysClientGetSSLPredefinedPolicyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewaySSLPredefinedPolicy); err != nil { + return ApplicationGatewaysClientGetSSLPredefinedPolicyResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all application gateways in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ApplicationGatewaysClientListOptions contains the optional parameters for the ApplicationGatewaysClient.NewListPager +// method. +func (client *ApplicationGatewaysClient) NewListPager(resourceGroupName string, options *ApplicationGatewaysClientListOptions) *runtime.Pager[ApplicationGatewaysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationGatewaysClientListResponse]{ + More: func(page ApplicationGatewaysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationGatewaysClientListResponse) (ApplicationGatewaysClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationGatewaysClient.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, options) + }, nil) + if err != nil { + return ApplicationGatewaysClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ApplicationGatewaysClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *ApplicationGatewaysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ApplicationGatewaysClient) listHandleResponse(resp *http.Response) (ApplicationGatewaysClientListResponse, error) { + result := ApplicationGatewaysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayListResult); err != nil { + return ApplicationGatewaysClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the application gateways in a subscription. +// +// Generated from API version 2023-05-01 +// - options - ApplicationGatewaysClientListAllOptions contains the optional parameters for the ApplicationGatewaysClient.NewListAllPager +// method. +func (client *ApplicationGatewaysClient) NewListAllPager(options *ApplicationGatewaysClientListAllOptions) *runtime.Pager[ApplicationGatewaysClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationGatewaysClientListAllResponse]{ + More: func(page ApplicationGatewaysClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationGatewaysClientListAllResponse) (ApplicationGatewaysClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationGatewaysClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return ApplicationGatewaysClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *ApplicationGatewaysClient) listAllCreateRequest(ctx context.Context, options *ApplicationGatewaysClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *ApplicationGatewaysClient) listAllHandleResponse(resp *http.Response) (ApplicationGatewaysClientListAllResponse, error) { + result := ApplicationGatewaysClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayListResult); err != nil { + return ApplicationGatewaysClientListAllResponse{}, err + } + return result, nil +} + +// ListAvailableRequestHeaders - Lists all available request headers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - options - ApplicationGatewaysClientListAvailableRequestHeadersOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableRequestHeaders +// method. +func (client *ApplicationGatewaysClient) ListAvailableRequestHeaders(ctx context.Context, options *ApplicationGatewaysClientListAvailableRequestHeadersOptions) (ApplicationGatewaysClientListAvailableRequestHeadersResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.ListAvailableRequestHeaders" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAvailableRequestHeadersCreateRequest(ctx, options) + if err != nil { + return ApplicationGatewaysClientListAvailableRequestHeadersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientListAvailableRequestHeadersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientListAvailableRequestHeadersResponse{}, err + } + resp, err := client.listAvailableRequestHeadersHandleResponse(httpResp) + return resp, err +} + +// listAvailableRequestHeadersCreateRequest creates the ListAvailableRequestHeaders request. +func (client *ApplicationGatewaysClient) listAvailableRequestHeadersCreateRequest(ctx context.Context, options *ApplicationGatewaysClientListAvailableRequestHeadersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableRequestHeaders" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableRequestHeadersHandleResponse handles the ListAvailableRequestHeaders response. +func (client *ApplicationGatewaysClient) listAvailableRequestHeadersHandleResponse(resp *http.Response) (ApplicationGatewaysClientListAvailableRequestHeadersResponse, error) { + result := ApplicationGatewaysClientListAvailableRequestHeadersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringArray); err != nil { + return ApplicationGatewaysClientListAvailableRequestHeadersResponse{}, err + } + return result, nil +} + +// ListAvailableResponseHeaders - Lists all available response headers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - options - ApplicationGatewaysClientListAvailableResponseHeadersOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableResponseHeaders +// method. +func (client *ApplicationGatewaysClient) ListAvailableResponseHeaders(ctx context.Context, options *ApplicationGatewaysClientListAvailableResponseHeadersOptions) (ApplicationGatewaysClientListAvailableResponseHeadersResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.ListAvailableResponseHeaders" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAvailableResponseHeadersCreateRequest(ctx, options) + if err != nil { + return ApplicationGatewaysClientListAvailableResponseHeadersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientListAvailableResponseHeadersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientListAvailableResponseHeadersResponse{}, err + } + resp, err := client.listAvailableResponseHeadersHandleResponse(httpResp) + return resp, err +} + +// listAvailableResponseHeadersCreateRequest creates the ListAvailableResponseHeaders request. +func (client *ApplicationGatewaysClient) listAvailableResponseHeadersCreateRequest(ctx context.Context, options *ApplicationGatewaysClientListAvailableResponseHeadersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableResponseHeaders" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableResponseHeadersHandleResponse handles the ListAvailableResponseHeaders response. +func (client *ApplicationGatewaysClient) listAvailableResponseHeadersHandleResponse(resp *http.Response) (ApplicationGatewaysClientListAvailableResponseHeadersResponse, error) { + result := ApplicationGatewaysClientListAvailableResponseHeadersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringArray); err != nil { + return ApplicationGatewaysClientListAvailableResponseHeadersResponse{}, err + } + return result, nil +} + +// ListAvailableSSLOptions - Lists available Ssl options for configuring Ssl policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - options - ApplicationGatewaysClientListAvailableSSLOptionsOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableSSLOptions +// method. +func (client *ApplicationGatewaysClient) ListAvailableSSLOptions(ctx context.Context, options *ApplicationGatewaysClientListAvailableSSLOptionsOptions) (ApplicationGatewaysClientListAvailableSSLOptionsResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.ListAvailableSSLOptions" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAvailableSSLOptionsCreateRequest(ctx, options) + if err != nil { + return ApplicationGatewaysClientListAvailableSSLOptionsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientListAvailableSSLOptionsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientListAvailableSSLOptionsResponse{}, err + } + resp, err := client.listAvailableSSLOptionsHandleResponse(httpResp) + return resp, err +} + +// listAvailableSSLOptionsCreateRequest creates the ListAvailableSSLOptions request. +func (client *ApplicationGatewaysClient) listAvailableSSLOptionsCreateRequest(ctx context.Context, options *ApplicationGatewaysClientListAvailableSSLOptionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableSSLOptionsHandleResponse handles the ListAvailableSSLOptions response. +func (client *ApplicationGatewaysClient) listAvailableSSLOptionsHandleResponse(resp *http.Response) (ApplicationGatewaysClientListAvailableSSLOptionsResponse, error) { + result := ApplicationGatewaysClientListAvailableSSLOptionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayAvailableSSLOptions); err != nil { + return ApplicationGatewaysClientListAvailableSSLOptionsResponse{}, err + } + return result, nil +} + +// NewListAvailableSSLPredefinedPoliciesPager - Lists all SSL predefined policies for configuring Ssl policy. +// +// Generated from API version 2023-05-01 +// - options - ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesOptions contains the optional parameters for the ApplicationGatewaysClient.NewListAvailableSSLPredefinedPoliciesPager +// method. +func (client *ApplicationGatewaysClient) NewListAvailableSSLPredefinedPoliciesPager(options *ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesOptions) *runtime.Pager[ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse]{ + More: func(page ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse) (ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationGatewaysClient.NewListAvailableSSLPredefinedPoliciesPager") + 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.listAvailableSSLPredefinedPoliciesCreateRequest(ctx, options) + }, nil) + if err != nil { + return ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse{}, err + } + return client.listAvailableSSLPredefinedPoliciesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAvailableSSLPredefinedPoliciesCreateRequest creates the ListAvailableSSLPredefinedPolicies request. +func (client *ApplicationGatewaysClient) listAvailableSSLPredefinedPoliciesCreateRequest(ctx context.Context, options *ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableSSLPredefinedPoliciesHandleResponse handles the ListAvailableSSLPredefinedPolicies response. +func (client *ApplicationGatewaysClient) listAvailableSSLPredefinedPoliciesHandleResponse(resp *http.Response) (ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse, error) { + result := ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayAvailableSSLPredefinedPolicies); err != nil { + return ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse{}, err + } + return result, nil +} + +// ListAvailableServerVariables - Lists all available server variables. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - options - ApplicationGatewaysClientListAvailableServerVariablesOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableServerVariables +// method. +func (client *ApplicationGatewaysClient) ListAvailableServerVariables(ctx context.Context, options *ApplicationGatewaysClientListAvailableServerVariablesOptions) (ApplicationGatewaysClientListAvailableServerVariablesResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.ListAvailableServerVariables" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAvailableServerVariablesCreateRequest(ctx, options) + if err != nil { + return ApplicationGatewaysClientListAvailableServerVariablesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientListAvailableServerVariablesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientListAvailableServerVariablesResponse{}, err + } + resp, err := client.listAvailableServerVariablesHandleResponse(httpResp) + return resp, err +} + +// listAvailableServerVariablesCreateRequest creates the ListAvailableServerVariables request. +func (client *ApplicationGatewaysClient) listAvailableServerVariablesCreateRequest(ctx context.Context, options *ApplicationGatewaysClientListAvailableServerVariablesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableServerVariables" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableServerVariablesHandleResponse handles the ListAvailableServerVariables response. +func (client *ApplicationGatewaysClient) listAvailableServerVariablesHandleResponse(resp *http.Response) (ApplicationGatewaysClientListAvailableServerVariablesResponse, error) { + result := ApplicationGatewaysClientListAvailableServerVariablesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringArray); err != nil { + return ApplicationGatewaysClientListAvailableServerVariablesResponse{}, err + } + return result, nil +} + +// ListAvailableWafRuleSets - Lists all available web application firewall rule sets. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - options - ApplicationGatewaysClientListAvailableWafRuleSetsOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableWafRuleSets +// method. +func (client *ApplicationGatewaysClient) ListAvailableWafRuleSets(ctx context.Context, options *ApplicationGatewaysClientListAvailableWafRuleSetsOptions) (ApplicationGatewaysClientListAvailableWafRuleSetsResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.ListAvailableWafRuleSets" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAvailableWafRuleSetsCreateRequest(ctx, options) + if err != nil { + return ApplicationGatewaysClientListAvailableWafRuleSetsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientListAvailableWafRuleSetsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientListAvailableWafRuleSetsResponse{}, err + } + resp, err := client.listAvailableWafRuleSetsHandleResponse(httpResp) + return resp, err +} + +// listAvailableWafRuleSetsCreateRequest creates the ListAvailableWafRuleSets request. +func (client *ApplicationGatewaysClient) listAvailableWafRuleSetsCreateRequest(ctx context.Context, options *ApplicationGatewaysClientListAvailableWafRuleSetsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableWafRuleSets" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAvailableWafRuleSetsHandleResponse handles the ListAvailableWafRuleSets response. +func (client *ApplicationGatewaysClient) listAvailableWafRuleSetsHandleResponse(resp *http.Response) (ApplicationGatewaysClientListAvailableWafRuleSetsResponse, error) { + result := ApplicationGatewaysClientListAvailableWafRuleSetsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayAvailableWafRuleSetsResult); err != nil { + return ApplicationGatewaysClientListAvailableWafRuleSetsResponse{}, err + } + return result, nil +} + +// BeginStart - Starts the specified application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - options - ApplicationGatewaysClientBeginStartOptions contains the optional parameters for the ApplicationGatewaysClient.BeginStart +// method. +func (client *ApplicationGatewaysClient) BeginStart(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginStartOptions) (*runtime.Poller[ApplicationGatewaysClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, applicationGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewaysClientStartResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewaysClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - Starts the specified application gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewaysClient) start(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewaysClient.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, applicationGatewayName, 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 +} + +// startCreateRequest creates the Start request. +func (client *ApplicationGatewaysClient) startCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/start" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStop - Stops the specified application gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - options - ApplicationGatewaysClientBeginStopOptions contains the optional parameters for the ApplicationGatewaysClient.BeginStop +// method. +func (client *ApplicationGatewaysClient) BeginStop(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginStopOptions) (*runtime.Poller[ApplicationGatewaysClientStopResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stop(ctx, resourceGroupName, applicationGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationGatewaysClientStopResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationGatewaysClientStopResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Stop - Stops the specified application gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationGatewaysClient) stop(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginStopOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationGatewaysClient.BeginStop" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopCreateRequest(ctx, resourceGroupName, applicationGatewayName, 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 +} + +// stopCreateRequest creates the Stop request. +func (client *ApplicationGatewaysClient) stopCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, options *ApplicationGatewaysClientBeginStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/stop" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// UpdateTags - Updates the specified application gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationGatewayName - The name of the application gateway. +// - parameters - Parameters supplied to update application gateway tags. +// - options - ApplicationGatewaysClientUpdateTagsOptions contains the optional parameters for the ApplicationGatewaysClient.UpdateTags +// method. +func (client *ApplicationGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters TagsObject, options *ApplicationGatewaysClientUpdateTagsOptions) (ApplicationGatewaysClientUpdateTagsResponse, error) { + var err error + const operationName = "ApplicationGatewaysClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, applicationGatewayName, parameters, options) + if err != nil { + return ApplicationGatewaysClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewaysClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewaysClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ApplicationGatewaysClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters TagsObject, options *ApplicationGatewaysClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationGatewayName == "" { + return nil, errors.New("parameter applicationGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationGatewayName}", url.PathEscape(applicationGatewayName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ApplicationGatewaysClient) updateTagsHandleResponse(resp *http.Response) (ApplicationGatewaysClientUpdateTagsResponse, error) { + result := ApplicationGatewaysClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGateway); err != nil { + return ApplicationGatewaysClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewaywafdynamicmanifests_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewaywafdynamicmanifests_client.go new file mode 100644 index 000000000..6821c9769 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewaywafdynamicmanifests_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 armnetwork + +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" +) + +// ApplicationGatewayWafDynamicManifestsClient contains the methods for the ApplicationGatewayWafDynamicManifests group. +// Don't use this type directly, use NewApplicationGatewayWafDynamicManifestsClient() instead. +type ApplicationGatewayWafDynamicManifestsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewApplicationGatewayWafDynamicManifestsClient creates a new instance of ApplicationGatewayWafDynamicManifestsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewApplicationGatewayWafDynamicManifestsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicationGatewayWafDynamicManifestsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApplicationGatewayWafDynamicManifestsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewGetPager - Gets the regional application gateway waf manifest. +// +// Generated from API version 2023-05-01 +// - location - The region where the nrp are located at. +// - options - ApplicationGatewayWafDynamicManifestsClientGetOptions contains the optional parameters for the ApplicationGatewayWafDynamicManifestsClient.NewGetPager +// method. +func (client *ApplicationGatewayWafDynamicManifestsClient) NewGetPager(location string, options *ApplicationGatewayWafDynamicManifestsClientGetOptions) *runtime.Pager[ApplicationGatewayWafDynamicManifestsClientGetResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationGatewayWafDynamicManifestsClientGetResponse]{ + More: func(page ApplicationGatewayWafDynamicManifestsClientGetResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationGatewayWafDynamicManifestsClientGetResponse) (ApplicationGatewayWafDynamicManifestsClientGetResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationGatewayWafDynamicManifestsClient.NewGetPager") + 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.getCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return ApplicationGatewayWafDynamicManifestsClientGetResponse{}, err + } + return client.getHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// getCreateRequest creates the Get request. +func (client *ApplicationGatewayWafDynamicManifestsClient) getCreateRequest(ctx context.Context, location string, options *ApplicationGatewayWafDynamicManifestsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/applicationGatewayWafDynamicManifests" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ApplicationGatewayWafDynamicManifestsClient) getHandleResponse(resp *http.Response) (ApplicationGatewayWafDynamicManifestsClientGetResponse, error) { + result := ApplicationGatewayWafDynamicManifestsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayWafDynamicManifestResultList); err != nil { + return ApplicationGatewayWafDynamicManifestsClientGetResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewaywafdynamicmanifestsdefault_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewaywafdynamicmanifestsdefault_client.go new file mode 100644 index 000000000..d189a5614 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationgatewaywafdynamicmanifestsdefault_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 armnetwork + +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" +) + +// ApplicationGatewayWafDynamicManifestsDefaultClient contains the methods for the ApplicationGatewayWafDynamicManifestsDefault group. +// Don't use this type directly, use NewApplicationGatewayWafDynamicManifestsDefaultClient() instead. +type ApplicationGatewayWafDynamicManifestsDefaultClient struct { + internal *arm.Client + subscriptionID string +} + +// NewApplicationGatewayWafDynamicManifestsDefaultClient creates a new instance of ApplicationGatewayWafDynamicManifestsDefaultClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewApplicationGatewayWafDynamicManifestsDefaultClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicationGatewayWafDynamicManifestsDefaultClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApplicationGatewayWafDynamicManifestsDefaultClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the regional application gateway waf manifest. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - location - The region where the nrp are located at. +// - options - ApplicationGatewayWafDynamicManifestsDefaultClientGetOptions contains the optional parameters for the ApplicationGatewayWafDynamicManifestsDefaultClient.Get +// method. +func (client *ApplicationGatewayWafDynamicManifestsDefaultClient) Get(ctx context.Context, location string, options *ApplicationGatewayWafDynamicManifestsDefaultClientGetOptions) (ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse, error) { + var err error + const operationName = "ApplicationGatewayWafDynamicManifestsDefaultClient.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, location, options) + if err != nil { + return ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ApplicationGatewayWafDynamicManifestsDefaultClient) getCreateRequest(ctx context.Context, location string, options *ApplicationGatewayWafDynamicManifestsDefaultClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/applicationGatewayWafDynamicManifests/dafault" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ApplicationGatewayWafDynamicManifestsDefaultClient) getHandleResponse(resp *http.Response) (ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse, error) { + result := ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationGatewayWafDynamicManifestResult); err != nil { + return ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationsecuritygroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationsecuritygroups_client.go new file mode 100644 index 000000000..74f42055f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/applicationsecuritygroups_client.go @@ -0,0 +1,452 @@ +//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 armnetwork + +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" +) + +// ApplicationSecurityGroupsClient contains the methods for the ApplicationSecurityGroups group. +// Don't use this type directly, use NewApplicationSecurityGroupsClient() instead. +type ApplicationSecurityGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewApplicationSecurityGroupsClient creates a new instance of ApplicationSecurityGroupsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewApplicationSecurityGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicationSecurityGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApplicationSecurityGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an application security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationSecurityGroupName - The name of the application security group. +// - parameters - Parameters supplied to the create or update ApplicationSecurityGroup operation. +// - options - ApplicationSecurityGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the ApplicationSecurityGroupsClient.BeginCreateOrUpdate +// method. +func (client *ApplicationSecurityGroupsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup, options *ApplicationSecurityGroupsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ApplicationSecurityGroupsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, applicationSecurityGroupName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationSecurityGroupsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationSecurityGroupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an application security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationSecurityGroupsClient) createOrUpdate(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup, options *ApplicationSecurityGroupsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationSecurityGroupsClient.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, applicationSecurityGroupName, 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 *ApplicationSecurityGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup, options *ApplicationSecurityGroupsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationSecurityGroupName == "" { + return nil, errors.New("parameter applicationSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationSecurityGroupName}", url.PathEscape(applicationSecurityGroupName)) + 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-05-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 application security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationSecurityGroupName - The name of the application security group. +// - options - ApplicationSecurityGroupsClientBeginDeleteOptions contains the optional parameters for the ApplicationSecurityGroupsClient.BeginDelete +// method. +func (client *ApplicationSecurityGroupsClient) BeginDelete(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, options *ApplicationSecurityGroupsClientBeginDeleteOptions) (*runtime.Poller[ApplicationSecurityGroupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, applicationSecurityGroupName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ApplicationSecurityGroupsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ApplicationSecurityGroupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified application security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ApplicationSecurityGroupsClient) deleteOperation(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, options *ApplicationSecurityGroupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ApplicationSecurityGroupsClient.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, applicationSecurityGroupName, 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 *ApplicationSecurityGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, options *ApplicationSecurityGroupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationSecurityGroupName == "" { + return nil, errors.New("parameter applicationSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationSecurityGroupName}", url.PathEscape(applicationSecurityGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about the specified application security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationSecurityGroupName - The name of the application security group. +// - options - ApplicationSecurityGroupsClientGetOptions contains the optional parameters for the ApplicationSecurityGroupsClient.Get +// method. +func (client *ApplicationSecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, options *ApplicationSecurityGroupsClientGetOptions) (ApplicationSecurityGroupsClientGetResponse, error) { + var err error + const operationName = "ApplicationSecurityGroupsClient.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, applicationSecurityGroupName, options) + if err != nil { + return ApplicationSecurityGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationSecurityGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationSecurityGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ApplicationSecurityGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, options *ApplicationSecurityGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationSecurityGroupName == "" { + return nil, errors.New("parameter applicationSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationSecurityGroupName}", url.PathEscape(applicationSecurityGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ApplicationSecurityGroupsClient) getHandleResponse(resp *http.Response) (ApplicationSecurityGroupsClientGetResponse, error) { + result := ApplicationSecurityGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationSecurityGroup); err != nil { + return ApplicationSecurityGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the application security groups in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ApplicationSecurityGroupsClientListOptions contains the optional parameters for the ApplicationSecurityGroupsClient.NewListPager +// method. +func (client *ApplicationSecurityGroupsClient) NewListPager(resourceGroupName string, options *ApplicationSecurityGroupsClientListOptions) *runtime.Pager[ApplicationSecurityGroupsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationSecurityGroupsClientListResponse]{ + More: func(page ApplicationSecurityGroupsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationSecurityGroupsClientListResponse) (ApplicationSecurityGroupsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationSecurityGroupsClient.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, options) + }, nil) + if err != nil { + return ApplicationSecurityGroupsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ApplicationSecurityGroupsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *ApplicationSecurityGroupsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ApplicationSecurityGroupsClient) listHandleResponse(resp *http.Response) (ApplicationSecurityGroupsClientListResponse, error) { + result := ApplicationSecurityGroupsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationSecurityGroupListResult); err != nil { + return ApplicationSecurityGroupsClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all application security groups in a subscription. +// +// Generated from API version 2023-05-01 +// - options - ApplicationSecurityGroupsClientListAllOptions contains the optional parameters for the ApplicationSecurityGroupsClient.NewListAllPager +// method. +func (client *ApplicationSecurityGroupsClient) NewListAllPager(options *ApplicationSecurityGroupsClientListAllOptions) *runtime.Pager[ApplicationSecurityGroupsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicationSecurityGroupsClientListAllResponse]{ + More: func(page ApplicationSecurityGroupsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicationSecurityGroupsClientListAllResponse) (ApplicationSecurityGroupsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationSecurityGroupsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return ApplicationSecurityGroupsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *ApplicationSecurityGroupsClient) listAllCreateRequest(ctx context.Context, options *ApplicationSecurityGroupsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationSecurityGroups" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *ApplicationSecurityGroupsClient) listAllHandleResponse(resp *http.Response) (ApplicationSecurityGroupsClientListAllResponse, error) { + result := ApplicationSecurityGroupsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationSecurityGroupListResult); err != nil { + return ApplicationSecurityGroupsClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates an application security group's tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - applicationSecurityGroupName - The name of the application security group. +// - parameters - Parameters supplied to update application security group tags. +// - options - ApplicationSecurityGroupsClientUpdateTagsOptions contains the optional parameters for the ApplicationSecurityGroupsClient.UpdateTags +// method. +func (client *ApplicationSecurityGroupsClient) UpdateTags(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters TagsObject, options *ApplicationSecurityGroupsClientUpdateTagsOptions) (ApplicationSecurityGroupsClientUpdateTagsResponse, error) { + var err error + const operationName = "ApplicationSecurityGroupsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, applicationSecurityGroupName, parameters, options) + if err != nil { + return ApplicationSecurityGroupsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApplicationSecurityGroupsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApplicationSecurityGroupsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ApplicationSecurityGroupsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters TagsObject, options *ApplicationSecurityGroupsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if applicationSecurityGroupName == "" { + return nil, errors.New("parameter applicationSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{applicationSecurityGroupName}", url.PathEscape(applicationSecurityGroupName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ApplicationSecurityGroupsClient) updateTagsHandleResponse(resp *http.Response) (ApplicationSecurityGroupsClientUpdateTagsResponse, error) { + result := ApplicationSecurityGroupsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationSecurityGroup); err != nil { + return ApplicationSecurityGroupsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/assets.json new file mode 100644 index 000000000..c83bdc67f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "go", + "TagPrefix": "go/resourcemanager/network/armnetwork", + "Tag": "go/resourcemanager/network/armnetwork_66967391f3" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/autorest.md new file mode 100644 index 000000000..1982a9354 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/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/80c21c17b4a7aa57f637ee594f7cfd653255a7e0/specification/network/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/80c21c17b4a7aa57f637ee594f7cfd653255a7e0/specification/network/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 4.3.0 +tag: package-2023-05 +``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availabledelegations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availabledelegations_client.go new file mode 100644 index 000000000..cd58ab741 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availabledelegations_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 armnetwork + +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" +) + +// AvailableDelegationsClient contains the methods for the AvailableDelegations group. +// Don't use this type directly, use NewAvailableDelegationsClient() instead. +type AvailableDelegationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAvailableDelegationsClient creates a new instance of AvailableDelegationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAvailableDelegationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AvailableDelegationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AvailableDelegationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets all of the available subnet delegations for this subscription in this region. +// +// Generated from API version 2023-05-01 +// - location - The location of the subnet. +// - options - AvailableDelegationsClientListOptions contains the optional parameters for the AvailableDelegationsClient.NewListPager +// method. +func (client *AvailableDelegationsClient) NewListPager(location string, options *AvailableDelegationsClientListOptions) *runtime.Pager[AvailableDelegationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailableDelegationsClientListResponse]{ + More: func(page AvailableDelegationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailableDelegationsClientListResponse) (AvailableDelegationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailableDelegationsClient.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, location, options) + }, nil) + if err != nil { + return AvailableDelegationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AvailableDelegationsClient) listCreateRequest(ctx context.Context, location string, options *AvailableDelegationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/availableDelegations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AvailableDelegationsClient) listHandleResponse(resp *http.Response) (AvailableDelegationsClientListResponse, error) { + result := AvailableDelegationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailableDelegationsResult); err != nil { + return AvailableDelegationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableendpointservices_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableendpointservices_client.go new file mode 100644 index 000000000..e64ff0ed7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableendpointservices_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 armnetwork + +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" +) + +// AvailableEndpointServicesClient contains the methods for the AvailableEndpointServices group. +// Don't use this type directly, use NewAvailableEndpointServicesClient() instead. +type AvailableEndpointServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAvailableEndpointServicesClient creates a new instance of AvailableEndpointServicesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAvailableEndpointServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AvailableEndpointServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AvailableEndpointServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - List what values of endpoint services are available for use. +// +// Generated from API version 2023-05-01 +// - location - The location to check available endpoint services. +// - options - AvailableEndpointServicesClientListOptions contains the optional parameters for the AvailableEndpointServicesClient.NewListPager +// method. +func (client *AvailableEndpointServicesClient) NewListPager(location string, options *AvailableEndpointServicesClientListOptions) *runtime.Pager[AvailableEndpointServicesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailableEndpointServicesClientListResponse]{ + More: func(page AvailableEndpointServicesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailableEndpointServicesClientListResponse) (AvailableEndpointServicesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailableEndpointServicesClient.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, location, options) + }, nil) + if err != nil { + return AvailableEndpointServicesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AvailableEndpointServicesClient) listCreateRequest(ctx context.Context, location string, options *AvailableEndpointServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/virtualNetworkAvailableEndpointServices" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AvailableEndpointServicesClient) listHandleResponse(resp *http.Response) (AvailableEndpointServicesClientListResponse, error) { + result := AvailableEndpointServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EndpointServicesListResult); err != nil { + return AvailableEndpointServicesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableprivateendpointtypes_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableprivateendpointtypes_client.go new file mode 100644 index 000000000..dec555fa1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableprivateendpointtypes_client.go @@ -0,0 +1,172 @@ +//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 armnetwork + +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" +) + +// AvailablePrivateEndpointTypesClient contains the methods for the AvailablePrivateEndpointTypes group. +// Don't use this type directly, use NewAvailablePrivateEndpointTypesClient() instead. +type AvailablePrivateEndpointTypesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAvailablePrivateEndpointTypesClient creates a new instance of AvailablePrivateEndpointTypesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAvailablePrivateEndpointTypesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AvailablePrivateEndpointTypesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AvailablePrivateEndpointTypesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Returns all of the resource types that can be linked to a Private Endpoint in this subscription in this +// region. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - options - AvailablePrivateEndpointTypesClientListOptions contains the optional parameters for the AvailablePrivateEndpointTypesClient.NewListPager +// method. +func (client *AvailablePrivateEndpointTypesClient) NewListPager(location string, options *AvailablePrivateEndpointTypesClientListOptions) *runtime.Pager[AvailablePrivateEndpointTypesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailablePrivateEndpointTypesClientListResponse]{ + More: func(page AvailablePrivateEndpointTypesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailablePrivateEndpointTypesClientListResponse) (AvailablePrivateEndpointTypesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailablePrivateEndpointTypesClient.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, location, options) + }, nil) + if err != nil { + return AvailablePrivateEndpointTypesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AvailablePrivateEndpointTypesClient) listCreateRequest(ctx context.Context, location string, options *AvailablePrivateEndpointTypesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/availablePrivateEndpointTypes" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AvailablePrivateEndpointTypesClient) listHandleResponse(resp *http.Response) (AvailablePrivateEndpointTypesClientListResponse, error) { + result := AvailablePrivateEndpointTypesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailablePrivateEndpointTypesResult); err != nil { + return AvailablePrivateEndpointTypesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Returns all of the resource types that can be linked to a Private Endpoint in this subscription +// in this region. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - resourceGroupName - The name of the resource group. +// - options - AvailablePrivateEndpointTypesClientListByResourceGroupOptions contains the optional parameters for the AvailablePrivateEndpointTypesClient.NewListByResourceGroupPager +// method. +func (client *AvailablePrivateEndpointTypesClient) NewListByResourceGroupPager(location string, resourceGroupName string, options *AvailablePrivateEndpointTypesClientListByResourceGroupOptions) *runtime.Pager[AvailablePrivateEndpointTypesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailablePrivateEndpointTypesClientListByResourceGroupResponse]{ + More: func(page AvailablePrivateEndpointTypesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailablePrivateEndpointTypesClientListByResourceGroupResponse) (AvailablePrivateEndpointTypesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailablePrivateEndpointTypesClient.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, location, resourceGroupName, options) + }, nil) + if err != nil { + return AvailablePrivateEndpointTypesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AvailablePrivateEndpointTypesClient) listByResourceGroupCreateRequest(ctx context.Context, location string, resourceGroupName string, options *AvailablePrivateEndpointTypesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/availablePrivateEndpointTypes" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AvailablePrivateEndpointTypesClient) listByResourceGroupHandleResponse(resp *http.Response) (AvailablePrivateEndpointTypesClientListByResourceGroupResponse, error) { + result := AvailablePrivateEndpointTypesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailablePrivateEndpointTypesResult); err != nil { + return AvailablePrivateEndpointTypesClientListByResourceGroupResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableresourcegroupdelegations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableresourcegroupdelegations_client.go new file mode 100644 index 000000000..c4916fbfc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableresourcegroupdelegations_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 armnetwork + +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" +) + +// AvailableResourceGroupDelegationsClient contains the methods for the AvailableResourceGroupDelegations group. +// Don't use this type directly, use NewAvailableResourceGroupDelegationsClient() instead. +type AvailableResourceGroupDelegationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAvailableResourceGroupDelegationsClient creates a new instance of AvailableResourceGroupDelegationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAvailableResourceGroupDelegationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AvailableResourceGroupDelegationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AvailableResourceGroupDelegationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets all of the available subnet delegations for this resource group in this region. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - resourceGroupName - The name of the resource group. +// - options - AvailableResourceGroupDelegationsClientListOptions contains the optional parameters for the AvailableResourceGroupDelegationsClient.NewListPager +// method. +func (client *AvailableResourceGroupDelegationsClient) NewListPager(location string, resourceGroupName string, options *AvailableResourceGroupDelegationsClientListOptions) *runtime.Pager[AvailableResourceGroupDelegationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailableResourceGroupDelegationsClientListResponse]{ + More: func(page AvailableResourceGroupDelegationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailableResourceGroupDelegationsClientListResponse) (AvailableResourceGroupDelegationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailableResourceGroupDelegationsClient.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, location, resourceGroupName, options) + }, nil) + if err != nil { + return AvailableResourceGroupDelegationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AvailableResourceGroupDelegationsClient) listCreateRequest(ctx context.Context, location string, resourceGroupName string, options *AvailableResourceGroupDelegationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/availableDelegations" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AvailableResourceGroupDelegationsClient) listHandleResponse(resp *http.Response) (AvailableResourceGroupDelegationsClientListResponse, error) { + result := AvailableResourceGroupDelegationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailableDelegationsResult); err != nil { + return AvailableResourceGroupDelegationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableservicealiases_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableservicealiases_client.go new file mode 100644 index 000000000..ccb45a0c6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/availableservicealiases_client.go @@ -0,0 +1,170 @@ +//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 armnetwork + +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" +) + +// AvailableServiceAliasesClient contains the methods for the AvailableServiceAliases group. +// Don't use this type directly, use NewAvailableServiceAliasesClient() instead. +type AvailableServiceAliasesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAvailableServiceAliasesClient creates a new instance of AvailableServiceAliasesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAvailableServiceAliasesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AvailableServiceAliasesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AvailableServiceAliasesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets all available service aliases for this subscription in this region. +// +// Generated from API version 2023-05-01 +// - location - The location. +// - options - AvailableServiceAliasesClientListOptions contains the optional parameters for the AvailableServiceAliasesClient.NewListPager +// method. +func (client *AvailableServiceAliasesClient) NewListPager(location string, options *AvailableServiceAliasesClientListOptions) *runtime.Pager[AvailableServiceAliasesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailableServiceAliasesClientListResponse]{ + More: func(page AvailableServiceAliasesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailableServiceAliasesClientListResponse) (AvailableServiceAliasesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailableServiceAliasesClient.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, location, options) + }, nil) + if err != nil { + return AvailableServiceAliasesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AvailableServiceAliasesClient) listCreateRequest(ctx context.Context, location string, options *AvailableServiceAliasesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/availableServiceAliases" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AvailableServiceAliasesClient) listHandleResponse(resp *http.Response) (AvailableServiceAliasesClientListResponse, error) { + result := AvailableServiceAliasesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailableServiceAliasesResult); err != nil { + return AvailableServiceAliasesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all available service aliases for this resource group in this region. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - location - The location. +// - options - AvailableServiceAliasesClientListByResourceGroupOptions contains the optional parameters for the AvailableServiceAliasesClient.NewListByResourceGroupPager +// method. +func (client *AvailableServiceAliasesClient) NewListByResourceGroupPager(resourceGroupName string, location string, options *AvailableServiceAliasesClientListByResourceGroupOptions) *runtime.Pager[AvailableServiceAliasesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AvailableServiceAliasesClientListByResourceGroupResponse]{ + More: func(page AvailableServiceAliasesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AvailableServiceAliasesClientListByResourceGroupResponse) (AvailableServiceAliasesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AvailableServiceAliasesClient.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, location, options) + }, nil) + if err != nil { + return AvailableServiceAliasesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AvailableServiceAliasesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, location string, options *AvailableServiceAliasesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/availableServiceAliases" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AvailableServiceAliasesClient) listByResourceGroupHandleResponse(resp *http.Response) (AvailableServiceAliasesClientListByResourceGroupResponse, error) { + result := AvailableServiceAliasesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailableServiceAliasesResult); err != nil { + return AvailableServiceAliasesClientListByResourceGroupResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/azurefirewallfqdntags_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/azurefirewallfqdntags_client.go new file mode 100644 index 000000000..dfd02e2ef --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/azurefirewallfqdntags_client.go @@ -0,0 +1,100 @@ +//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 armnetwork + +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" +) + +// AzureFirewallFqdnTagsClient contains the methods for the AzureFirewallFqdnTags group. +// Don't use this type directly, use NewAzureFirewallFqdnTagsClient() instead. +type AzureFirewallFqdnTagsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAzureFirewallFqdnTagsClient creates a new instance of AzureFirewallFqdnTagsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAzureFirewallFqdnTagsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AzureFirewallFqdnTagsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AzureFirewallFqdnTagsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListAllPager - Gets all the Azure Firewall FQDN Tags in a subscription. +// +// Generated from API version 2023-05-01 +// - options - AzureFirewallFqdnTagsClientListAllOptions contains the optional parameters for the AzureFirewallFqdnTagsClient.NewListAllPager +// method. +func (client *AzureFirewallFqdnTagsClient) NewListAllPager(options *AzureFirewallFqdnTagsClientListAllOptions) *runtime.Pager[AzureFirewallFqdnTagsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[AzureFirewallFqdnTagsClientListAllResponse]{ + More: func(page AzureFirewallFqdnTagsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AzureFirewallFqdnTagsClientListAllResponse) (AzureFirewallFqdnTagsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AzureFirewallFqdnTagsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return AzureFirewallFqdnTagsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *AzureFirewallFqdnTagsClient) listAllCreateRequest(ctx context.Context, options *AzureFirewallFqdnTagsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewallFqdnTags" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *AzureFirewallFqdnTagsClient) listAllHandleResponse(resp *http.Response) (AzureFirewallFqdnTagsClientListAllResponse, error) { + result := AzureFirewallFqdnTagsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureFirewallFqdnTagListResult); err != nil { + return AzureFirewallFqdnTagsClientListAllResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/azurefirewalls_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/azurefirewalls_client.go new file mode 100644 index 000000000..f46875f7c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/azurefirewalls_client.go @@ -0,0 +1,620 @@ +//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 armnetwork + +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" +) + +// AzureFirewallsClient contains the methods for the AzureFirewalls group. +// Don't use this type directly, use NewAzureFirewallsClient() instead. +type AzureFirewallsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAzureFirewallsClient creates a new instance of AzureFirewallsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewAzureFirewallsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AzureFirewallsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AzureFirewallsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Azure Firewall. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - azureFirewallName - The name of the Azure Firewall. +// - parameters - Parameters supplied to the create or update Azure Firewall operation. +// - options - AzureFirewallsClientBeginCreateOrUpdateOptions contains the optional parameters for the AzureFirewallsClient.BeginCreateOrUpdate +// method. +func (client *AzureFirewallsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall, options *AzureFirewallsClientBeginCreateOrUpdateOptions) (*runtime.Poller[AzureFirewallsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, azureFirewallName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AzureFirewallsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AzureFirewallsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Azure Firewall. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *AzureFirewallsClient) createOrUpdate(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall, options *AzureFirewallsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AzureFirewallsClient.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, azureFirewallName, 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 *AzureFirewallsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall, options *AzureFirewallsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureFirewallName == "" { + return nil, errors.New("parameter azureFirewallName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureFirewallName}", url.PathEscape(azureFirewallName)) + 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-05-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 Azure Firewall. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - azureFirewallName - The name of the Azure Firewall. +// - options - AzureFirewallsClientBeginDeleteOptions contains the optional parameters for the AzureFirewallsClient.BeginDelete +// method. +func (client *AzureFirewallsClient) BeginDelete(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientBeginDeleteOptions) (*runtime.Poller[AzureFirewallsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, azureFirewallName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AzureFirewallsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AzureFirewallsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Azure Firewall. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *AzureFirewallsClient) deleteOperation(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AzureFirewallsClient.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, azureFirewallName, 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 *AzureFirewallsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureFirewallName == "" { + return nil, errors.New("parameter azureFirewallName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureFirewallName}", url.PathEscape(azureFirewallName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Azure Firewall. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - azureFirewallName - The name of the Azure Firewall. +// - options - AzureFirewallsClientGetOptions contains the optional parameters for the AzureFirewallsClient.Get method. +func (client *AzureFirewallsClient) Get(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientGetOptions) (AzureFirewallsClientGetResponse, error) { + var err error + const operationName = "AzureFirewallsClient.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, azureFirewallName, options) + if err != nil { + return AzureFirewallsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AzureFirewallsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AzureFirewallsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AzureFirewallsClient) getCreateRequest(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureFirewallName == "" { + return nil, errors.New("parameter azureFirewallName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureFirewallName}", url.PathEscape(azureFirewallName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AzureFirewallsClient) getHandleResponse(resp *http.Response) (AzureFirewallsClientGetResponse, error) { + result := AzureFirewallsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureFirewall); err != nil { + return AzureFirewallsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all Azure Firewalls in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - AzureFirewallsClientListOptions contains the optional parameters for the AzureFirewallsClient.NewListPager method. +func (client *AzureFirewallsClient) NewListPager(resourceGroupName string, options *AzureFirewallsClientListOptions) *runtime.Pager[AzureFirewallsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AzureFirewallsClientListResponse]{ + More: func(page AzureFirewallsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AzureFirewallsClientListResponse) (AzureFirewallsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AzureFirewallsClient.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, options) + }, nil) + if err != nil { + return AzureFirewallsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AzureFirewallsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *AzureFirewallsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AzureFirewallsClient) listHandleResponse(resp *http.Response) (AzureFirewallsClientListResponse, error) { + result := AzureFirewallsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureFirewallListResult); err != nil { + return AzureFirewallsClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the Azure Firewalls in a subscription. +// +// Generated from API version 2023-05-01 +// - options - AzureFirewallsClientListAllOptions contains the optional parameters for the AzureFirewallsClient.NewListAllPager +// method. +func (client *AzureFirewallsClient) NewListAllPager(options *AzureFirewallsClientListAllOptions) *runtime.Pager[AzureFirewallsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[AzureFirewallsClientListAllResponse]{ + More: func(page AzureFirewallsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AzureFirewallsClientListAllResponse) (AzureFirewallsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AzureFirewallsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return AzureFirewallsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *AzureFirewallsClient) listAllCreateRequest(ctx context.Context, options *AzureFirewallsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewalls" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *AzureFirewallsClient) listAllHandleResponse(resp *http.Response) (AzureFirewallsClientListAllResponse, error) { + result := AzureFirewallsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureFirewallListResult); err != nil { + return AzureFirewallsClientListAllResponse{}, err + } + return result, nil +} + +// BeginListLearnedPrefixes - Retrieves a list of all IP prefixes that azure firewall has learned to not SNAT. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - azureFirewallName - The name of the azure firewall. +// - options - AzureFirewallsClientBeginListLearnedPrefixesOptions contains the optional parameters for the AzureFirewallsClient.BeginListLearnedPrefixes +// method. +func (client *AzureFirewallsClient) BeginListLearnedPrefixes(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientBeginListLearnedPrefixesOptions) (*runtime.Poller[AzureFirewallsClientListLearnedPrefixesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listLearnedPrefixes(ctx, resourceGroupName, azureFirewallName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AzureFirewallsClientListLearnedPrefixesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AzureFirewallsClientListLearnedPrefixesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListLearnedPrefixes - Retrieves a list of all IP prefixes that azure firewall has learned to not SNAT. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *AzureFirewallsClient) listLearnedPrefixes(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientBeginListLearnedPrefixesOptions) (*http.Response, error) { + var err error + const operationName = "AzureFirewallsClient.BeginListLearnedPrefixes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listLearnedPrefixesCreateRequest(ctx, resourceGroupName, azureFirewallName, 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 +} + +// listLearnedPrefixesCreateRequest creates the ListLearnedPrefixes request. +func (client *AzureFirewallsClient) listLearnedPrefixesCreateRequest(ctx context.Context, resourceGroupName string, azureFirewallName string, options *AzureFirewallsClientBeginListLearnedPrefixesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}/learnedIPPrefixes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureFirewallName == "" { + return nil, errors.New("parameter azureFirewallName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureFirewallName}", url.PathEscape(azureFirewallName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginPacketCapture - Runs a packet capture on AzureFirewall. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - azureFirewallName - The name of the Azure Firewall. +// - parameters - Parameters supplied to run packet capture on azure firewall. +// - options - AzureFirewallsClientBeginPacketCaptureOptions contains the optional parameters for the AzureFirewallsClient.BeginPacketCapture +// method. +func (client *AzureFirewallsClient) BeginPacketCapture(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters FirewallPacketCaptureParameters, options *AzureFirewallsClientBeginPacketCaptureOptions) (*runtime.Poller[AzureFirewallsClientPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.packetCapture(ctx, resourceGroupName, azureFirewallName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AzureFirewallsClientPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AzureFirewallsClientPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PacketCapture - Runs a packet capture on AzureFirewall. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *AzureFirewallsClient) packetCapture(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters FirewallPacketCaptureParameters, options *AzureFirewallsClientBeginPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "AzureFirewallsClient.BeginPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.packetCaptureCreateRequest(ctx, resourceGroupName, azureFirewallName, 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.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// packetCaptureCreateRequest creates the PacketCapture request. +func (client *AzureFirewallsClient) packetCaptureCreateRequest(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters FirewallPacketCaptureParameters, options *AzureFirewallsClientBeginPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}/packetCapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureFirewallName == "" { + return nil, errors.New("parameter azureFirewallName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureFirewallName}", url.PathEscape(azureFirewallName)) + 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-05-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 +} + +// BeginUpdateTags - Updates tags of an Azure Firewall resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - azureFirewallName - The name of the Azure Firewall. +// - parameters - Parameters supplied to update azure firewall tags. +// - options - AzureFirewallsClientBeginUpdateTagsOptions contains the optional parameters for the AzureFirewallsClient.BeginUpdateTags +// method. +func (client *AzureFirewallsClient) BeginUpdateTags(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters TagsObject, options *AzureFirewallsClientBeginUpdateTagsOptions) (*runtime.Poller[AzureFirewallsClientUpdateTagsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateTags(ctx, resourceGroupName, azureFirewallName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AzureFirewallsClientUpdateTagsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AzureFirewallsClientUpdateTagsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateTags - Updates tags of an Azure Firewall resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *AzureFirewallsClient) updateTags(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters TagsObject, options *AzureFirewallsClientBeginUpdateTagsOptions) (*http.Response, error) { + var err error + const operationName = "AzureFirewallsClient.BeginUpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, azureFirewallName, 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 +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *AzureFirewallsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters TagsObject, options *AzureFirewallsClientBeginUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureFirewallName == "" { + return nil, errors.New("parameter azureFirewallName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureFirewallName}", url.PathEscape(azureFirewallName)) + 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-05-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/network/armnetwork/v4/bastionhosts_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/bastionhosts_client.go new file mode 100644 index 000000000..315c2d66b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/bastionhosts_client.go @@ -0,0 +1,462 @@ +//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 armnetwork + +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" +) + +// BastionHostsClient contains the methods for the BastionHosts group. +// Don't use this type directly, use NewBastionHostsClient() instead. +type BastionHostsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewBastionHostsClient creates a new instance of BastionHostsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewBastionHostsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BastionHostsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BastionHostsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Bastion Host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - parameters - Parameters supplied to the create or update Bastion Host operation. +// - options - BastionHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the BastionHostsClient.BeginCreateOrUpdate +// method. +func (client *BastionHostsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, bastionHostName string, parameters BastionHost, options *BastionHostsClientBeginCreateOrUpdateOptions) (*runtime.Poller[BastionHostsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, bastionHostName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BastionHostsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BastionHostsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Bastion Host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *BastionHostsClient) createOrUpdate(ctx context.Context, resourceGroupName string, bastionHostName string, parameters BastionHost, options *BastionHostsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "BastionHostsClient.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, bastionHostName, 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 *BastionHostsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, parameters BastionHost, options *BastionHostsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-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 Bastion Host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - options - BastionHostsClientBeginDeleteOptions contains the optional parameters for the BastionHostsClient.BeginDelete +// method. +func (client *BastionHostsClient) BeginDelete(ctx context.Context, resourceGroupName string, bastionHostName string, options *BastionHostsClientBeginDeleteOptions) (*runtime.Poller[BastionHostsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, bastionHostName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BastionHostsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BastionHostsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Bastion Host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *BastionHostsClient) deleteOperation(ctx context.Context, resourceGroupName string, bastionHostName string, options *BastionHostsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "BastionHostsClient.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, bastionHostName, 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 *BastionHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, options *BastionHostsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Bastion Host. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - options - BastionHostsClientGetOptions contains the optional parameters for the BastionHostsClient.Get method. +func (client *BastionHostsClient) Get(ctx context.Context, resourceGroupName string, bastionHostName string, options *BastionHostsClientGetOptions) (BastionHostsClientGetResponse, error) { + var err error + const operationName = "BastionHostsClient.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, bastionHostName, options) + if err != nil { + return BastionHostsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BastionHostsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BastionHostsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *BastionHostsClient) getCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, options *BastionHostsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *BastionHostsClient) getHandleResponse(resp *http.Response) (BastionHostsClientGetResponse, error) { + result := BastionHostsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BastionHost); err != nil { + return BastionHostsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all Bastion Hosts in a subscription. +// +// Generated from API version 2023-05-01 +// - options - BastionHostsClientListOptions contains the optional parameters for the BastionHostsClient.NewListPager method. +func (client *BastionHostsClient) NewListPager(options *BastionHostsClientListOptions) *runtime.Pager[BastionHostsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BastionHostsClientListResponse]{ + More: func(page BastionHostsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BastionHostsClientListResponse) (BastionHostsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BastionHostsClient.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 BastionHostsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BastionHostsClient) listCreateRequest(ctx context.Context, options *BastionHostsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/bastionHosts" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BastionHostsClient) listHandleResponse(resp *http.Response) (BastionHostsClientListResponse, error) { + result := BastionHostsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BastionHostListResult); err != nil { + return BastionHostsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all Bastion Hosts in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - BastionHostsClientListByResourceGroupOptions contains the optional parameters for the BastionHostsClient.NewListByResourceGroupPager +// method. +func (client *BastionHostsClient) NewListByResourceGroupPager(resourceGroupName string, options *BastionHostsClientListByResourceGroupOptions) *runtime.Pager[BastionHostsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[BastionHostsClientListByResourceGroupResponse]{ + More: func(page BastionHostsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BastionHostsClientListByResourceGroupResponse) (BastionHostsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BastionHostsClient.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 BastionHostsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *BastionHostsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *BastionHostsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *BastionHostsClient) listByResourceGroupHandleResponse(resp *http.Response) (BastionHostsClientListByResourceGroupResponse, error) { + result := BastionHostsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BastionHostListResult); err != nil { + return BastionHostsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginUpdateTags - Updates Tags for BastionHost resource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - parameters - Parameters supplied to update BastionHost tags. +// - options - BastionHostsClientBeginUpdateTagsOptions contains the optional parameters for the BastionHostsClient.BeginUpdateTags +// method. +func (client *BastionHostsClient) BeginUpdateTags(ctx context.Context, resourceGroupName string, bastionHostName string, parameters TagsObject, options *BastionHostsClientBeginUpdateTagsOptions) (*runtime.Poller[BastionHostsClientUpdateTagsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateTags(ctx, resourceGroupName, bastionHostName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BastionHostsClientUpdateTagsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BastionHostsClientUpdateTagsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateTags - Updates Tags for BastionHost resource +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *BastionHostsClient) updateTags(ctx context.Context, resourceGroupName string, bastionHostName string, parameters TagsObject, options *BastionHostsClientBeginUpdateTagsOptions) (*http.Response, error) { + var err error + const operationName = "BastionHostsClient.BeginUpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, bastionHostName, 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 +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *BastionHostsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, parameters TagsObject, options *BastionHostsClientBeginUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}" + 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 bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-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/network/armnetwork/v4/bgpservicecommunities_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/bgpservicecommunities_client.go new file mode 100644 index 000000000..5364936f3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/bgpservicecommunities_client.go @@ -0,0 +1,100 @@ +//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 armnetwork + +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" +) + +// BgpServiceCommunitiesClient contains the methods for the BgpServiceCommunities group. +// Don't use this type directly, use NewBgpServiceCommunitiesClient() instead. +type BgpServiceCommunitiesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewBgpServiceCommunitiesClient creates a new instance of BgpServiceCommunitiesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewBgpServiceCommunitiesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BgpServiceCommunitiesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BgpServiceCommunitiesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets all the available bgp service communities. +// +// Generated from API version 2023-05-01 +// - options - BgpServiceCommunitiesClientListOptions contains the optional parameters for the BgpServiceCommunitiesClient.NewListPager +// method. +func (client *BgpServiceCommunitiesClient) NewListPager(options *BgpServiceCommunitiesClientListOptions) *runtime.Pager[BgpServiceCommunitiesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BgpServiceCommunitiesClientListResponse]{ + More: func(page BgpServiceCommunitiesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BgpServiceCommunitiesClientListResponse) (BgpServiceCommunitiesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BgpServiceCommunitiesClient.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 BgpServiceCommunitiesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BgpServiceCommunitiesClient) listCreateRequest(ctx context.Context, options *BgpServiceCommunitiesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BgpServiceCommunitiesClient) listHandleResponse(resp *http.Response) (BgpServiceCommunitiesClientListResponse, error) { + result := BgpServiceCommunitiesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BgpServiceCommunityListResult); err != nil { + return BgpServiceCommunitiesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/build.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/build.go new file mode 100644 index 000000000..a22250100 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/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/network/armnetwork + +package armnetwork diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ci.yml new file mode 100644 index 000000000..d1d36edca --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/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/network/armnetwork/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/network/armnetwork/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + IncludeRelease: true + ServiceDirectory: 'resourcemanager/network/armnetwork' diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/client_factory.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/client_factory.go new file mode 100644 index 000000000..b354e3dbb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/client_factory.go @@ -0,0 +1,837 @@ +//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 armnetwork + +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 subscription credentials which uniquely identify the 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, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, credential: credential, + options: options.Clone(), + }, nil +} + +// NewAdminRuleCollectionsClient creates a new instance of AdminRuleCollectionsClient. +func (c *ClientFactory) NewAdminRuleCollectionsClient() *AdminRuleCollectionsClient { + subClient, _ := NewAdminRuleCollectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAdminRulesClient creates a new instance of AdminRulesClient. +func (c *ClientFactory) NewAdminRulesClient() *AdminRulesClient { + subClient, _ := NewAdminRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewApplicationGatewayPrivateEndpointConnectionsClient creates a new instance of ApplicationGatewayPrivateEndpointConnectionsClient. +func (c *ClientFactory) NewApplicationGatewayPrivateEndpointConnectionsClient() *ApplicationGatewayPrivateEndpointConnectionsClient { + subClient, _ := NewApplicationGatewayPrivateEndpointConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewApplicationGatewayPrivateLinkResourcesClient creates a new instance of ApplicationGatewayPrivateLinkResourcesClient. +func (c *ClientFactory) NewApplicationGatewayPrivateLinkResourcesClient() *ApplicationGatewayPrivateLinkResourcesClient { + subClient, _ := NewApplicationGatewayPrivateLinkResourcesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewApplicationGatewayWafDynamicManifestsClient creates a new instance of ApplicationGatewayWafDynamicManifestsClient. +func (c *ClientFactory) NewApplicationGatewayWafDynamicManifestsClient() *ApplicationGatewayWafDynamicManifestsClient { + subClient, _ := NewApplicationGatewayWafDynamicManifestsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewApplicationGatewayWafDynamicManifestsDefaultClient creates a new instance of ApplicationGatewayWafDynamicManifestsDefaultClient. +func (c *ClientFactory) NewApplicationGatewayWafDynamicManifestsDefaultClient() *ApplicationGatewayWafDynamicManifestsDefaultClient { + subClient, _ := NewApplicationGatewayWafDynamicManifestsDefaultClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewApplicationGatewaysClient creates a new instance of ApplicationGatewaysClient. +func (c *ClientFactory) NewApplicationGatewaysClient() *ApplicationGatewaysClient { + subClient, _ := NewApplicationGatewaysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewApplicationSecurityGroupsClient creates a new instance of ApplicationSecurityGroupsClient. +func (c *ClientFactory) NewApplicationSecurityGroupsClient() *ApplicationSecurityGroupsClient { + subClient, _ := NewApplicationSecurityGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAvailableDelegationsClient creates a new instance of AvailableDelegationsClient. +func (c *ClientFactory) NewAvailableDelegationsClient() *AvailableDelegationsClient { + subClient, _ := NewAvailableDelegationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAvailableEndpointServicesClient creates a new instance of AvailableEndpointServicesClient. +func (c *ClientFactory) NewAvailableEndpointServicesClient() *AvailableEndpointServicesClient { + subClient, _ := NewAvailableEndpointServicesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAvailablePrivateEndpointTypesClient creates a new instance of AvailablePrivateEndpointTypesClient. +func (c *ClientFactory) NewAvailablePrivateEndpointTypesClient() *AvailablePrivateEndpointTypesClient { + subClient, _ := NewAvailablePrivateEndpointTypesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAvailableResourceGroupDelegationsClient creates a new instance of AvailableResourceGroupDelegationsClient. +func (c *ClientFactory) NewAvailableResourceGroupDelegationsClient() *AvailableResourceGroupDelegationsClient { + subClient, _ := NewAvailableResourceGroupDelegationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAvailableServiceAliasesClient creates a new instance of AvailableServiceAliasesClient. +func (c *ClientFactory) NewAvailableServiceAliasesClient() *AvailableServiceAliasesClient { + subClient, _ := NewAvailableServiceAliasesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAzureFirewallFqdnTagsClient creates a new instance of AzureFirewallFqdnTagsClient. +func (c *ClientFactory) NewAzureFirewallFqdnTagsClient() *AzureFirewallFqdnTagsClient { + subClient, _ := NewAzureFirewallFqdnTagsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewAzureFirewallsClient creates a new instance of AzureFirewallsClient. +func (c *ClientFactory) NewAzureFirewallsClient() *AzureFirewallsClient { + subClient, _ := NewAzureFirewallsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewBastionHostsClient creates a new instance of BastionHostsClient. +func (c *ClientFactory) NewBastionHostsClient() *BastionHostsClient { + subClient, _ := NewBastionHostsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewBgpServiceCommunitiesClient creates a new instance of BgpServiceCommunitiesClient. +func (c *ClientFactory) NewBgpServiceCommunitiesClient() *BgpServiceCommunitiesClient { + subClient, _ := NewBgpServiceCommunitiesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewConfigurationPolicyGroupsClient creates a new instance of ConfigurationPolicyGroupsClient. +func (c *ClientFactory) NewConfigurationPolicyGroupsClient() *ConfigurationPolicyGroupsClient { + subClient, _ := NewConfigurationPolicyGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewConnectionMonitorsClient creates a new instance of ConnectionMonitorsClient. +func (c *ClientFactory) NewConnectionMonitorsClient() *ConnectionMonitorsClient { + subClient, _ := NewConnectionMonitorsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewConnectivityConfigurationsClient creates a new instance of ConnectivityConfigurationsClient. +func (c *ClientFactory) NewConnectivityConfigurationsClient() *ConnectivityConfigurationsClient { + subClient, _ := NewConnectivityConfigurationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCustomIPPrefixesClient creates a new instance of CustomIPPrefixesClient. +func (c *ClientFactory) NewCustomIPPrefixesClient() *CustomIPPrefixesClient { + subClient, _ := NewCustomIPPrefixesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDdosCustomPoliciesClient creates a new instance of DdosCustomPoliciesClient. +func (c *ClientFactory) NewDdosCustomPoliciesClient() *DdosCustomPoliciesClient { + subClient, _ := NewDdosCustomPoliciesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDdosProtectionPlansClient creates a new instance of DdosProtectionPlansClient. +func (c *ClientFactory) NewDdosProtectionPlansClient() *DdosProtectionPlansClient { + subClient, _ := NewDdosProtectionPlansClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDefaultSecurityRulesClient creates a new instance of DefaultSecurityRulesClient. +func (c *ClientFactory) NewDefaultSecurityRulesClient() *DefaultSecurityRulesClient { + subClient, _ := NewDefaultSecurityRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDscpConfigurationClient creates a new instance of DscpConfigurationClient. +func (c *ClientFactory) NewDscpConfigurationClient() *DscpConfigurationClient { + subClient, _ := NewDscpConfigurationClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteCircuitAuthorizationsClient creates a new instance of ExpressRouteCircuitAuthorizationsClient. +func (c *ClientFactory) NewExpressRouteCircuitAuthorizationsClient() *ExpressRouteCircuitAuthorizationsClient { + subClient, _ := NewExpressRouteCircuitAuthorizationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteCircuitConnectionsClient creates a new instance of ExpressRouteCircuitConnectionsClient. +func (c *ClientFactory) NewExpressRouteCircuitConnectionsClient() *ExpressRouteCircuitConnectionsClient { + subClient, _ := NewExpressRouteCircuitConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteCircuitPeeringsClient creates a new instance of ExpressRouteCircuitPeeringsClient. +func (c *ClientFactory) NewExpressRouteCircuitPeeringsClient() *ExpressRouteCircuitPeeringsClient { + subClient, _ := NewExpressRouteCircuitPeeringsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteCircuitsClient creates a new instance of ExpressRouteCircuitsClient. +func (c *ClientFactory) NewExpressRouteCircuitsClient() *ExpressRouteCircuitsClient { + subClient, _ := NewExpressRouteCircuitsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteConnectionsClient creates a new instance of ExpressRouteConnectionsClient. +func (c *ClientFactory) NewExpressRouteConnectionsClient() *ExpressRouteConnectionsClient { + subClient, _ := NewExpressRouteConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteCrossConnectionPeeringsClient creates a new instance of ExpressRouteCrossConnectionPeeringsClient. +func (c *ClientFactory) NewExpressRouteCrossConnectionPeeringsClient() *ExpressRouteCrossConnectionPeeringsClient { + subClient, _ := NewExpressRouteCrossConnectionPeeringsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteCrossConnectionsClient creates a new instance of ExpressRouteCrossConnectionsClient. +func (c *ClientFactory) NewExpressRouteCrossConnectionsClient() *ExpressRouteCrossConnectionsClient { + subClient, _ := NewExpressRouteCrossConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteGatewaysClient creates a new instance of ExpressRouteGatewaysClient. +func (c *ClientFactory) NewExpressRouteGatewaysClient() *ExpressRouteGatewaysClient { + subClient, _ := NewExpressRouteGatewaysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteLinksClient creates a new instance of ExpressRouteLinksClient. +func (c *ClientFactory) NewExpressRouteLinksClient() *ExpressRouteLinksClient { + subClient, _ := NewExpressRouteLinksClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRoutePortAuthorizationsClient creates a new instance of ExpressRoutePortAuthorizationsClient. +func (c *ClientFactory) NewExpressRoutePortAuthorizationsClient() *ExpressRoutePortAuthorizationsClient { + subClient, _ := NewExpressRoutePortAuthorizationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRoutePortsClient creates a new instance of ExpressRoutePortsClient. +func (c *ClientFactory) NewExpressRoutePortsClient() *ExpressRoutePortsClient { + subClient, _ := NewExpressRoutePortsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRoutePortsLocationsClient creates a new instance of ExpressRoutePortsLocationsClient. +func (c *ClientFactory) NewExpressRoutePortsLocationsClient() *ExpressRoutePortsLocationsClient { + subClient, _ := NewExpressRoutePortsLocationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteProviderPortsLocationClient creates a new instance of ExpressRouteProviderPortsLocationClient. +func (c *ClientFactory) NewExpressRouteProviderPortsLocationClient() *ExpressRouteProviderPortsLocationClient { + subClient, _ := NewExpressRouteProviderPortsLocationClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewExpressRouteServiceProvidersClient creates a new instance of ExpressRouteServiceProvidersClient. +func (c *ClientFactory) NewExpressRouteServiceProvidersClient() *ExpressRouteServiceProvidersClient { + subClient, _ := NewExpressRouteServiceProvidersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFirewallPoliciesClient creates a new instance of FirewallPoliciesClient. +func (c *ClientFactory) NewFirewallPoliciesClient() *FirewallPoliciesClient { + subClient, _ := NewFirewallPoliciesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFirewallPolicyIdpsSignaturesClient creates a new instance of FirewallPolicyIdpsSignaturesClient. +func (c *ClientFactory) NewFirewallPolicyIdpsSignaturesClient() *FirewallPolicyIdpsSignaturesClient { + subClient, _ := NewFirewallPolicyIdpsSignaturesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFirewallPolicyIdpsSignaturesFilterValuesClient creates a new instance of FirewallPolicyIdpsSignaturesFilterValuesClient. +func (c *ClientFactory) NewFirewallPolicyIdpsSignaturesFilterValuesClient() *FirewallPolicyIdpsSignaturesFilterValuesClient { + subClient, _ := NewFirewallPolicyIdpsSignaturesFilterValuesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFirewallPolicyIdpsSignaturesOverridesClient creates a new instance of FirewallPolicyIdpsSignaturesOverridesClient. +func (c *ClientFactory) NewFirewallPolicyIdpsSignaturesOverridesClient() *FirewallPolicyIdpsSignaturesOverridesClient { + subClient, _ := NewFirewallPolicyIdpsSignaturesOverridesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFirewallPolicyRuleCollectionGroupsClient creates a new instance of FirewallPolicyRuleCollectionGroupsClient. +func (c *ClientFactory) NewFirewallPolicyRuleCollectionGroupsClient() *FirewallPolicyRuleCollectionGroupsClient { + subClient, _ := NewFirewallPolicyRuleCollectionGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFlowLogsClient creates a new instance of FlowLogsClient. +func (c *ClientFactory) NewFlowLogsClient() *FlowLogsClient { + subClient, _ := NewFlowLogsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewGroupsClient creates a new instance of GroupsClient. +func (c *ClientFactory) NewGroupsClient() *GroupsClient { + subClient, _ := NewGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewHubRouteTablesClient creates a new instance of HubRouteTablesClient. +func (c *ClientFactory) NewHubRouteTablesClient() *HubRouteTablesClient { + subClient, _ := NewHubRouteTablesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewHubVirtualNetworkConnectionsClient creates a new instance of HubVirtualNetworkConnectionsClient. +func (c *ClientFactory) NewHubVirtualNetworkConnectionsClient() *HubVirtualNetworkConnectionsClient { + subClient, _ := NewHubVirtualNetworkConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewIPAllocationsClient creates a new instance of IPAllocationsClient. +func (c *ClientFactory) NewIPAllocationsClient() *IPAllocationsClient { + subClient, _ := NewIPAllocationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewIPGroupsClient creates a new instance of IPGroupsClient. +func (c *ClientFactory) NewIPGroupsClient() *IPGroupsClient { + subClient, _ := NewIPGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewInboundNatRulesClient creates a new instance of InboundNatRulesClient. +func (c *ClientFactory) NewInboundNatRulesClient() *InboundNatRulesClient { + subClient, _ := NewInboundNatRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewInboundSecurityRuleClient creates a new instance of InboundSecurityRuleClient. +func (c *ClientFactory) NewInboundSecurityRuleClient() *InboundSecurityRuleClient { + subClient, _ := NewInboundSecurityRuleClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewInterfaceIPConfigurationsClient creates a new instance of InterfaceIPConfigurationsClient. +func (c *ClientFactory) NewInterfaceIPConfigurationsClient() *InterfaceIPConfigurationsClient { + subClient, _ := NewInterfaceIPConfigurationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewInterfaceLoadBalancersClient creates a new instance of InterfaceLoadBalancersClient. +func (c *ClientFactory) NewInterfaceLoadBalancersClient() *InterfaceLoadBalancersClient { + subClient, _ := NewInterfaceLoadBalancersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewInterfaceTapConfigurationsClient creates a new instance of InterfaceTapConfigurationsClient. +func (c *ClientFactory) NewInterfaceTapConfigurationsClient() *InterfaceTapConfigurationsClient { + subClient, _ := NewInterfaceTapConfigurationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewInterfacesClient creates a new instance of InterfacesClient. +func (c *ClientFactory) NewInterfacesClient() *InterfacesClient { + subClient, _ := NewInterfacesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLoadBalancerBackendAddressPoolsClient creates a new instance of LoadBalancerBackendAddressPoolsClient. +func (c *ClientFactory) NewLoadBalancerBackendAddressPoolsClient() *LoadBalancerBackendAddressPoolsClient { + subClient, _ := NewLoadBalancerBackendAddressPoolsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLoadBalancerFrontendIPConfigurationsClient creates a new instance of LoadBalancerFrontendIPConfigurationsClient. +func (c *ClientFactory) NewLoadBalancerFrontendIPConfigurationsClient() *LoadBalancerFrontendIPConfigurationsClient { + subClient, _ := NewLoadBalancerFrontendIPConfigurationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLoadBalancerLoadBalancingRulesClient creates a new instance of LoadBalancerLoadBalancingRulesClient. +func (c *ClientFactory) NewLoadBalancerLoadBalancingRulesClient() *LoadBalancerLoadBalancingRulesClient { + subClient, _ := NewLoadBalancerLoadBalancingRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLoadBalancerNetworkInterfacesClient creates a new instance of LoadBalancerNetworkInterfacesClient. +func (c *ClientFactory) NewLoadBalancerNetworkInterfacesClient() *LoadBalancerNetworkInterfacesClient { + subClient, _ := NewLoadBalancerNetworkInterfacesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLoadBalancerOutboundRulesClient creates a new instance of LoadBalancerOutboundRulesClient. +func (c *ClientFactory) NewLoadBalancerOutboundRulesClient() *LoadBalancerOutboundRulesClient { + subClient, _ := NewLoadBalancerOutboundRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLoadBalancerProbesClient creates a new instance of LoadBalancerProbesClient. +func (c *ClientFactory) NewLoadBalancerProbesClient() *LoadBalancerProbesClient { + subClient, _ := NewLoadBalancerProbesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLoadBalancersClient creates a new instance of LoadBalancersClient. +func (c *ClientFactory) NewLoadBalancersClient() *LoadBalancersClient { + subClient, _ := NewLoadBalancersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLocalNetworkGatewaysClient creates a new instance of LocalNetworkGatewaysClient. +func (c *ClientFactory) NewLocalNetworkGatewaysClient() *LocalNetworkGatewaysClient { + subClient, _ := NewLocalNetworkGatewaysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewManagementClient creates a new instance of ManagementClient. +func (c *ClientFactory) NewManagementClient() *ManagementClient { + subClient, _ := NewManagementClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewManagementGroupNetworkManagerConnectionsClient creates a new instance of ManagementGroupNetworkManagerConnectionsClient. +func (c *ClientFactory) NewManagementGroupNetworkManagerConnectionsClient() *ManagementGroupNetworkManagerConnectionsClient { + subClient, _ := NewManagementGroupNetworkManagerConnectionsClient(c.credential, c.options) + return subClient +} + +// NewManagerCommitsClient creates a new instance of ManagerCommitsClient. +func (c *ClientFactory) NewManagerCommitsClient() *ManagerCommitsClient { + subClient, _ := NewManagerCommitsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewManagerDeploymentStatusClient creates a new instance of ManagerDeploymentStatusClient. +func (c *ClientFactory) NewManagerDeploymentStatusClient() *ManagerDeploymentStatusClient { + subClient, _ := NewManagerDeploymentStatusClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewManagersClient creates a new instance of ManagersClient. +func (c *ClientFactory) NewManagersClient() *ManagersClient { + subClient, _ := NewManagersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewNatGatewaysClient creates a new instance of NatGatewaysClient. +func (c *ClientFactory) NewNatGatewaysClient() *NatGatewaysClient { + subClient, _ := NewNatGatewaysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewNatRulesClient creates a new instance of NatRulesClient. +func (c *ClientFactory) NewNatRulesClient() *NatRulesClient { + subClient, _ := NewNatRulesClient(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 +} + +// NewP2SVPNGatewaysClient creates a new instance of P2SVPNGatewaysClient. +func (c *ClientFactory) NewP2SVPNGatewaysClient() *P2SVPNGatewaysClient { + subClient, _ := NewP2SVPNGatewaysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPacketCapturesClient creates a new instance of PacketCapturesClient. +func (c *ClientFactory) NewPacketCapturesClient() *PacketCapturesClient { + subClient, _ := NewPacketCapturesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPeerExpressRouteCircuitConnectionsClient creates a new instance of PeerExpressRouteCircuitConnectionsClient. +func (c *ClientFactory) NewPeerExpressRouteCircuitConnectionsClient() *PeerExpressRouteCircuitConnectionsClient { + subClient, _ := NewPeerExpressRouteCircuitConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPrivateDNSZoneGroupsClient creates a new instance of PrivateDNSZoneGroupsClient. +func (c *ClientFactory) NewPrivateDNSZoneGroupsClient() *PrivateDNSZoneGroupsClient { + subClient, _ := NewPrivateDNSZoneGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPrivateEndpointsClient creates a new instance of PrivateEndpointsClient. +func (c *ClientFactory) NewPrivateEndpointsClient() *PrivateEndpointsClient { + subClient, _ := NewPrivateEndpointsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPrivateLinkServicesClient creates a new instance of PrivateLinkServicesClient. +func (c *ClientFactory) NewPrivateLinkServicesClient() *PrivateLinkServicesClient { + subClient, _ := NewPrivateLinkServicesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewProfilesClient creates a new instance of ProfilesClient. +func (c *ClientFactory) NewProfilesClient() *ProfilesClient { + subClient, _ := NewProfilesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPublicIPAddressesClient creates a new instance of PublicIPAddressesClient. +func (c *ClientFactory) NewPublicIPAddressesClient() *PublicIPAddressesClient { + subClient, _ := NewPublicIPAddressesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPublicIPPrefixesClient creates a new instance of PublicIPPrefixesClient. +func (c *ClientFactory) NewPublicIPPrefixesClient() *PublicIPPrefixesClient { + subClient, _ := NewPublicIPPrefixesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewResourceNavigationLinksClient creates a new instance of ResourceNavigationLinksClient. +func (c *ClientFactory) NewResourceNavigationLinksClient() *ResourceNavigationLinksClient { + subClient, _ := NewResourceNavigationLinksClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRouteFilterRulesClient creates a new instance of RouteFilterRulesClient. +func (c *ClientFactory) NewRouteFilterRulesClient() *RouteFilterRulesClient { + subClient, _ := NewRouteFilterRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRouteFiltersClient creates a new instance of RouteFiltersClient. +func (c *ClientFactory) NewRouteFiltersClient() *RouteFiltersClient { + subClient, _ := NewRouteFiltersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRouteMapsClient creates a new instance of RouteMapsClient. +func (c *ClientFactory) NewRouteMapsClient() *RouteMapsClient { + subClient, _ := NewRouteMapsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRouteTablesClient creates a new instance of RouteTablesClient. +func (c *ClientFactory) NewRouteTablesClient() *RouteTablesClient { + subClient, _ := NewRouteTablesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRoutesClient creates a new instance of RoutesClient. +func (c *ClientFactory) NewRoutesClient() *RoutesClient { + subClient, _ := NewRoutesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRoutingIntentClient creates a new instance of RoutingIntentClient. +func (c *ClientFactory) NewRoutingIntentClient() *RoutingIntentClient { + subClient, _ := NewRoutingIntentClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewScopeConnectionsClient creates a new instance of ScopeConnectionsClient. +func (c *ClientFactory) NewScopeConnectionsClient() *ScopeConnectionsClient { + subClient, _ := NewScopeConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSecurityAdminConfigurationsClient creates a new instance of SecurityAdminConfigurationsClient. +func (c *ClientFactory) NewSecurityAdminConfigurationsClient() *SecurityAdminConfigurationsClient { + subClient, _ := NewSecurityAdminConfigurationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSecurityGroupsClient creates a new instance of SecurityGroupsClient. +func (c *ClientFactory) NewSecurityGroupsClient() *SecurityGroupsClient { + subClient, _ := NewSecurityGroupsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSecurityPartnerProvidersClient creates a new instance of SecurityPartnerProvidersClient. +func (c *ClientFactory) NewSecurityPartnerProvidersClient() *SecurityPartnerProvidersClient { + subClient, _ := NewSecurityPartnerProvidersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSecurityRulesClient creates a new instance of SecurityRulesClient. +func (c *ClientFactory) NewSecurityRulesClient() *SecurityRulesClient { + subClient, _ := NewSecurityRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewServiceAssociationLinksClient creates a new instance of ServiceAssociationLinksClient. +func (c *ClientFactory) NewServiceAssociationLinksClient() *ServiceAssociationLinksClient { + subClient, _ := NewServiceAssociationLinksClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewServiceEndpointPoliciesClient creates a new instance of ServiceEndpointPoliciesClient. +func (c *ClientFactory) NewServiceEndpointPoliciesClient() *ServiceEndpointPoliciesClient { + subClient, _ := NewServiceEndpointPoliciesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewServiceEndpointPolicyDefinitionsClient creates a new instance of ServiceEndpointPolicyDefinitionsClient. +func (c *ClientFactory) NewServiceEndpointPolicyDefinitionsClient() *ServiceEndpointPolicyDefinitionsClient { + subClient, _ := NewServiceEndpointPolicyDefinitionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewServiceTagInformationClient creates a new instance of ServiceTagInformationClient. +func (c *ClientFactory) NewServiceTagInformationClient() *ServiceTagInformationClient { + subClient, _ := NewServiceTagInformationClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewServiceTagsClient creates a new instance of ServiceTagsClient. +func (c *ClientFactory) NewServiceTagsClient() *ServiceTagsClient { + subClient, _ := NewServiceTagsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewStaticMembersClient creates a new instance of StaticMembersClient. +func (c *ClientFactory) NewStaticMembersClient() *StaticMembersClient { + subClient, _ := NewStaticMembersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSubnetsClient creates a new instance of SubnetsClient. +func (c *ClientFactory) NewSubnetsClient() *SubnetsClient { + subClient, _ := NewSubnetsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSubscriptionNetworkManagerConnectionsClient creates a new instance of SubscriptionNetworkManagerConnectionsClient. +func (c *ClientFactory) NewSubscriptionNetworkManagerConnectionsClient() *SubscriptionNetworkManagerConnectionsClient { + subClient, _ := NewSubscriptionNetworkManagerConnectionsClient(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 +} + +// NewVPNConnectionsClient creates a new instance of VPNConnectionsClient. +func (c *ClientFactory) NewVPNConnectionsClient() *VPNConnectionsClient { + subClient, _ := NewVPNConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNGatewaysClient creates a new instance of VPNGatewaysClient. +func (c *ClientFactory) NewVPNGatewaysClient() *VPNGatewaysClient { + subClient, _ := NewVPNGatewaysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNLinkConnectionsClient creates a new instance of VPNLinkConnectionsClient. +func (c *ClientFactory) NewVPNLinkConnectionsClient() *VPNLinkConnectionsClient { + subClient, _ := NewVPNLinkConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNServerConfigurationsAssociatedWithVirtualWanClient creates a new instance of VPNServerConfigurationsAssociatedWithVirtualWanClient. +func (c *ClientFactory) NewVPNServerConfigurationsAssociatedWithVirtualWanClient() *VPNServerConfigurationsAssociatedWithVirtualWanClient { + subClient, _ := NewVPNServerConfigurationsAssociatedWithVirtualWanClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNServerConfigurationsClient creates a new instance of VPNServerConfigurationsClient. +func (c *ClientFactory) NewVPNServerConfigurationsClient() *VPNServerConfigurationsClient { + subClient, _ := NewVPNServerConfigurationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNSiteLinkConnectionsClient creates a new instance of VPNSiteLinkConnectionsClient. +func (c *ClientFactory) NewVPNSiteLinkConnectionsClient() *VPNSiteLinkConnectionsClient { + subClient, _ := NewVPNSiteLinkConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNSiteLinksClient creates a new instance of VPNSiteLinksClient. +func (c *ClientFactory) NewVPNSiteLinksClient() *VPNSiteLinksClient { + subClient, _ := NewVPNSiteLinksClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNSitesClient creates a new instance of VPNSitesClient. +func (c *ClientFactory) NewVPNSitesClient() *VPNSitesClient { + subClient, _ := NewVPNSitesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVPNSitesConfigurationClient creates a new instance of VPNSitesConfigurationClient. +func (c *ClientFactory) NewVPNSitesConfigurationClient() *VPNSitesConfigurationClient { + subClient, _ := NewVPNSitesConfigurationClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVipSwapClient creates a new instance of VipSwapClient. +func (c *ClientFactory) NewVipSwapClient() *VipSwapClient { + subClient, _ := NewVipSwapClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualApplianceConnectionsClient creates a new instance of VirtualApplianceConnectionsClient. +func (c *ClientFactory) NewVirtualApplianceConnectionsClient() *VirtualApplianceConnectionsClient { + subClient, _ := NewVirtualApplianceConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualApplianceSKUsClient creates a new instance of VirtualApplianceSKUsClient. +func (c *ClientFactory) NewVirtualApplianceSKUsClient() *VirtualApplianceSKUsClient { + subClient, _ := NewVirtualApplianceSKUsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualApplianceSitesClient creates a new instance of VirtualApplianceSitesClient. +func (c *ClientFactory) NewVirtualApplianceSitesClient() *VirtualApplianceSitesClient { + subClient, _ := NewVirtualApplianceSitesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualAppliancesClient creates a new instance of VirtualAppliancesClient. +func (c *ClientFactory) NewVirtualAppliancesClient() *VirtualAppliancesClient { + subClient, _ := NewVirtualAppliancesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualHubBgpConnectionClient creates a new instance of VirtualHubBgpConnectionClient. +func (c *ClientFactory) NewVirtualHubBgpConnectionClient() *VirtualHubBgpConnectionClient { + subClient, _ := NewVirtualHubBgpConnectionClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualHubBgpConnectionsClient creates a new instance of VirtualHubBgpConnectionsClient. +func (c *ClientFactory) NewVirtualHubBgpConnectionsClient() *VirtualHubBgpConnectionsClient { + subClient, _ := NewVirtualHubBgpConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualHubIPConfigurationClient creates a new instance of VirtualHubIPConfigurationClient. +func (c *ClientFactory) NewVirtualHubIPConfigurationClient() *VirtualHubIPConfigurationClient { + subClient, _ := NewVirtualHubIPConfigurationClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualHubRouteTableV2SClient creates a new instance of VirtualHubRouteTableV2SClient. +func (c *ClientFactory) NewVirtualHubRouteTableV2SClient() *VirtualHubRouteTableV2SClient { + subClient, _ := NewVirtualHubRouteTableV2SClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualHubsClient creates a new instance of VirtualHubsClient. +func (c *ClientFactory) NewVirtualHubsClient() *VirtualHubsClient { + subClient, _ := NewVirtualHubsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualNetworkGatewayConnectionsClient creates a new instance of VirtualNetworkGatewayConnectionsClient. +func (c *ClientFactory) NewVirtualNetworkGatewayConnectionsClient() *VirtualNetworkGatewayConnectionsClient { + subClient, _ := NewVirtualNetworkGatewayConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualNetworkGatewayNatRulesClient creates a new instance of VirtualNetworkGatewayNatRulesClient. +func (c *ClientFactory) NewVirtualNetworkGatewayNatRulesClient() *VirtualNetworkGatewayNatRulesClient { + subClient, _ := NewVirtualNetworkGatewayNatRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualNetworkGatewaysClient creates a new instance of VirtualNetworkGatewaysClient. +func (c *ClientFactory) NewVirtualNetworkGatewaysClient() *VirtualNetworkGatewaysClient { + subClient, _ := NewVirtualNetworkGatewaysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualNetworkPeeringsClient creates a new instance of VirtualNetworkPeeringsClient. +func (c *ClientFactory) NewVirtualNetworkPeeringsClient() *VirtualNetworkPeeringsClient { + subClient, _ := NewVirtualNetworkPeeringsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualNetworkTapsClient creates a new instance of VirtualNetworkTapsClient. +func (c *ClientFactory) NewVirtualNetworkTapsClient() *VirtualNetworkTapsClient { + subClient, _ := NewVirtualNetworkTapsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualNetworksClient creates a new instance of VirtualNetworksClient. +func (c *ClientFactory) NewVirtualNetworksClient() *VirtualNetworksClient { + subClient, _ := NewVirtualNetworksClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualRouterPeeringsClient creates a new instance of VirtualRouterPeeringsClient. +func (c *ClientFactory) NewVirtualRouterPeeringsClient() *VirtualRouterPeeringsClient { + subClient, _ := NewVirtualRouterPeeringsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualRoutersClient creates a new instance of VirtualRoutersClient. +func (c *ClientFactory) NewVirtualRoutersClient() *VirtualRoutersClient { + subClient, _ := NewVirtualRoutersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewVirtualWansClient creates a new instance of VirtualWansClient. +func (c *ClientFactory) NewVirtualWansClient() *VirtualWansClient { + subClient, _ := NewVirtualWansClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewWatchersClient creates a new instance of WatchersClient. +func (c *ClientFactory) NewWatchersClient() *WatchersClient { + subClient, _ := NewWatchersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewWebApplicationFirewallPoliciesClient creates a new instance of WebApplicationFirewallPoliciesClient. +func (c *ClientFactory) NewWebApplicationFirewallPoliciesClient() *WebApplicationFirewallPoliciesClient { + subClient, _ := NewWebApplicationFirewallPoliciesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewWebCategoriesClient creates a new instance of WebCategoriesClient. +func (c *ClientFactory) NewWebCategoriesClient() *WebCategoriesClient { + subClient, _ := NewWebCategoriesClient(c.subscriptionID, c.credential, c.options) + return subClient +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/configurationpolicygroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/configurationpolicygroups_client.go new file mode 100644 index 000000000..feeea87c1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/configurationpolicygroups_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ConfigurationPolicyGroupsClient contains the methods for the ConfigurationPolicyGroups group. +// Don't use this type directly, use NewConfigurationPolicyGroupsClient() instead. +type ConfigurationPolicyGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewConfigurationPolicyGroupsClient creates a new instance of ConfigurationPolicyGroupsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewConfigurationPolicyGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConfigurationPolicyGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ConfigurationPolicyGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a ConfigurationPolicyGroup if it doesn't exist else updates the existing one. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the ConfigurationPolicyGroup. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration. +// - configurationPolicyGroupName - The name of the ConfigurationPolicyGroup. +// - vpnServerConfigurationPolicyGroupParameters - Parameters supplied to create or update a VpnServerConfiguration PolicyGroup. +// - options - ConfigurationPolicyGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.BeginCreateOrUpdate +// method. +func (client *ConfigurationPolicyGroupsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, vpnServerConfigurationPolicyGroupParameters VPNServerConfigurationPolicyGroup, options *ConfigurationPolicyGroupsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ConfigurationPolicyGroupsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vpnServerConfigurationName, configurationPolicyGroupName, vpnServerConfigurationPolicyGroupParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConfigurationPolicyGroupsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConfigurationPolicyGroupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a ConfigurationPolicyGroup if it doesn't exist else updates the existing one. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConfigurationPolicyGroupsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, vpnServerConfigurationPolicyGroupParameters VPNServerConfigurationPolicyGroup, options *ConfigurationPolicyGroupsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ConfigurationPolicyGroupsClient.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, vpnServerConfigurationName, configurationPolicyGroupName, vpnServerConfigurationPolicyGroupParameters, 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 *ConfigurationPolicyGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, vpnServerConfigurationPolicyGroupParameters VPNServerConfigurationPolicyGroup, options *ConfigurationPolicyGroupsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups/{configurationPolicyGroupName}" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + if configurationPolicyGroupName == "" { + return nil, errors.New("parameter configurationPolicyGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationPolicyGroupName}", url.PathEscape(configurationPolicyGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnServerConfigurationPolicyGroupParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a ConfigurationPolicyGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the ConfigurationPolicyGroup. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration. +// - configurationPolicyGroupName - The name of the ConfigurationPolicyGroup. +// - options - ConfigurationPolicyGroupsClientBeginDeleteOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.BeginDelete +// method. +func (client *ConfigurationPolicyGroupsClient) BeginDelete(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, options *ConfigurationPolicyGroupsClientBeginDeleteOptions) (*runtime.Poller[ConfigurationPolicyGroupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vpnServerConfigurationName, configurationPolicyGroupName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConfigurationPolicyGroupsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConfigurationPolicyGroupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a ConfigurationPolicyGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConfigurationPolicyGroupsClient) deleteOperation(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, options *ConfigurationPolicyGroupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ConfigurationPolicyGroupsClient.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, vpnServerConfigurationName, configurationPolicyGroupName, 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 *ConfigurationPolicyGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, options *ConfigurationPolicyGroupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups/{configurationPolicyGroupName}" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + if configurationPolicyGroupName == "" { + return nil, errors.New("parameter configurationPolicyGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationPolicyGroupName}", url.PathEscape(configurationPolicyGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a ConfigurationPolicyGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnServerConfiguration. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration. +// - configurationPolicyGroupName - The name of the ConfigurationPolicyGroup being retrieved. +// - options - ConfigurationPolicyGroupsClientGetOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.Get +// method. +func (client *ConfigurationPolicyGroupsClient) Get(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, options *ConfigurationPolicyGroupsClientGetOptions) (ConfigurationPolicyGroupsClientGetResponse, error) { + var err error + const operationName = "ConfigurationPolicyGroupsClient.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, vpnServerConfigurationName, configurationPolicyGroupName, options) + if err != nil { + return ConfigurationPolicyGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConfigurationPolicyGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConfigurationPolicyGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ConfigurationPolicyGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, options *ConfigurationPolicyGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups/{configurationPolicyGroupName}" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + if configurationPolicyGroupName == "" { + return nil, errors.New("parameter configurationPolicyGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationPolicyGroupName}", url.PathEscape(configurationPolicyGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ConfigurationPolicyGroupsClient) getHandleResponse(resp *http.Response) (ConfigurationPolicyGroupsClientGetResponse, error) { + result := ConfigurationPolicyGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNServerConfigurationPolicyGroup); err != nil { + return ConfigurationPolicyGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListByVPNServerConfigurationPager - Lists all the configurationPolicyGroups in a resource group for a vpnServerConfiguration. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnServerConfiguration. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration. +// - options - ConfigurationPolicyGroupsClientListByVPNServerConfigurationOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.NewListByVPNServerConfigurationPager +// method. +func (client *ConfigurationPolicyGroupsClient) NewListByVPNServerConfigurationPager(resourceGroupName string, vpnServerConfigurationName string, options *ConfigurationPolicyGroupsClientListByVPNServerConfigurationOptions) *runtime.Pager[ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse] { + return runtime.NewPager(runtime.PagingHandler[ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse]{ + More: func(page ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse) (ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConfigurationPolicyGroupsClient.NewListByVPNServerConfigurationPager") + 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.listByVPNServerConfigurationCreateRequest(ctx, resourceGroupName, vpnServerConfigurationName, options) + }, nil) + if err != nil { + return ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse{}, err + } + return client.listByVPNServerConfigurationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVPNServerConfigurationCreateRequest creates the ListByVPNServerConfiguration request. +func (client *ConfigurationPolicyGroupsClient) listByVPNServerConfigurationCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, options *ConfigurationPolicyGroupsClientListByVPNServerConfigurationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVPNServerConfigurationHandleResponse handles the ListByVPNServerConfiguration response. +func (client *ConfigurationPolicyGroupsClient) listByVPNServerConfigurationHandleResponse(resp *http.Response) (ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse, error) { + result := ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNServerConfigurationPolicyGroupsResult); err != nil { + return ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/connectionmonitors_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/connectionmonitors_client.go new file mode 100644 index 000000000..905523443 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/connectionmonitors_client.go @@ -0,0 +1,671 @@ +//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 armnetwork + +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" +) + +// ConnectionMonitorsClient contains the methods for the ConnectionMonitors group. +// Don't use this type directly, use NewConnectionMonitorsClient() instead. +type ConnectionMonitorsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewConnectionMonitorsClient creates a new instance of ConnectionMonitorsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewConnectionMonitorsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConnectionMonitorsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ConnectionMonitorsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - connectionMonitorName - The name of the connection monitor. +// - parameters - Parameters that define the operation to create a connection monitor. +// - options - ConnectionMonitorsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConnectionMonitorsClient.BeginCreateOrUpdate +// method. +func (client *ConnectionMonitorsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor, options *ConnectionMonitorsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ConnectionMonitorsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConnectionMonitorsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConnectionMonitorsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConnectionMonitorsClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor, options *ConnectionMonitorsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ConnectionMonitorsClient.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, networkWatcherName, connectionMonitorName, 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 *ConnectionMonitorsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor, options *ConnectionMonitorsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if connectionMonitorName == "" { + return nil, errors.New("parameter connectionMonitorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionMonitorName}", url.PathEscape(connectionMonitorName)) + 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-05-01") + if options != nil && options.Migrate != nil { + reqQP.Set("migrate", *options.Migrate) + } + 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 connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - connectionMonitorName - The name of the connection monitor. +// - options - ConnectionMonitorsClientBeginDeleteOptions contains the optional parameters for the ConnectionMonitorsClient.BeginDelete +// method. +func (client *ConnectionMonitorsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginDeleteOptions) (*runtime.Poller[ConnectionMonitorsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConnectionMonitorsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConnectionMonitorsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConnectionMonitorsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ConnectionMonitorsClient.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, networkWatcherName, connectionMonitorName, 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 *ConnectionMonitorsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if connectionMonitorName == "" { + return nil, errors.New("parameter connectionMonitorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionMonitorName}", url.PathEscape(connectionMonitorName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a connection monitor by name. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - connectionMonitorName - The name of the connection monitor. +// - options - ConnectionMonitorsClientGetOptions contains the optional parameters for the ConnectionMonitorsClient.Get method. +func (client *ConnectionMonitorsClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientGetOptions) (ConnectionMonitorsClientGetResponse, error) { + var err error + const operationName = "ConnectionMonitorsClient.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, networkWatcherName, connectionMonitorName, options) + if err != nil { + return ConnectionMonitorsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectionMonitorsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConnectionMonitorsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ConnectionMonitorsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if connectionMonitorName == "" { + return nil, errors.New("parameter connectionMonitorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionMonitorName}", url.PathEscape(connectionMonitorName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ConnectionMonitorsClient) getHandleResponse(resp *http.Response) (ConnectionMonitorsClientGetResponse, error) { + result := ConnectionMonitorsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionMonitorResult); err != nil { + return ConnectionMonitorsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all connection monitors for the specified Network Watcher. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - options - ConnectionMonitorsClientListOptions contains the optional parameters for the ConnectionMonitorsClient.NewListPager +// method. +func (client *ConnectionMonitorsClient) NewListPager(resourceGroupName string, networkWatcherName string, options *ConnectionMonitorsClientListOptions) *runtime.Pager[ConnectionMonitorsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ConnectionMonitorsClientListResponse]{ + More: func(page ConnectionMonitorsClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *ConnectionMonitorsClientListResponse) (ConnectionMonitorsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConnectionMonitorsClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, networkWatcherName, options) + if err != nil { + return ConnectionMonitorsClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectionMonitorsClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ConnectionMonitorsClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ConnectionMonitorsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, options *ConnectionMonitorsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ConnectionMonitorsClient) listHandleResponse(resp *http.Response) (ConnectionMonitorsClientListResponse, error) { + result := ConnectionMonitorsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionMonitorListResult); err != nil { + return ConnectionMonitorsClientListResponse{}, err + } + return result, nil +} + +// BeginQuery - Query a snapshot of the most recent connection states. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - connectionMonitorName - The name given to the connection monitor. +// - options - ConnectionMonitorsClientBeginQueryOptions contains the optional parameters for the ConnectionMonitorsClient.BeginQuery +// method. +func (client *ConnectionMonitorsClient) BeginQuery(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginQueryOptions) (*runtime.Poller[ConnectionMonitorsClientQueryResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.query(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConnectionMonitorsClientQueryResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConnectionMonitorsClientQueryResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Query - Query a snapshot of the most recent connection states. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConnectionMonitorsClient) query(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginQueryOptions) (*http.Response, error) { + var err error + const operationName = "ConnectionMonitorsClient.BeginQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.queryCreateRequest(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, 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 +} + +// queryCreateRequest creates the Query request. +func (client *ConnectionMonitorsClient) queryCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginQueryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/query" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if connectionMonitorName == "" { + return nil, errors.New("parameter connectionMonitorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionMonitorName}", url.PathEscape(connectionMonitorName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStart - Starts the specified connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - connectionMonitorName - The name of the connection monitor. +// - options - ConnectionMonitorsClientBeginStartOptions contains the optional parameters for the ConnectionMonitorsClient.BeginStart +// method. +func (client *ConnectionMonitorsClient) BeginStart(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginStartOptions) (*runtime.Poller[ConnectionMonitorsClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConnectionMonitorsClientStartResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConnectionMonitorsClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - Starts the specified connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConnectionMonitorsClient) start(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "ConnectionMonitorsClient.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, 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 +} + +// startCreateRequest creates the Start request. +func (client *ConnectionMonitorsClient) startCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/start" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if connectionMonitorName == "" { + return nil, errors.New("parameter connectionMonitorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionMonitorName}", url.PathEscape(connectionMonitorName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStop - Stops the specified connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - connectionMonitorName - The name of the connection monitor. +// - options - ConnectionMonitorsClientBeginStopOptions contains the optional parameters for the ConnectionMonitorsClient.BeginStop +// method. +func (client *ConnectionMonitorsClient) BeginStop(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginStopOptions) (*runtime.Poller[ConnectionMonitorsClientStopResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stop(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConnectionMonitorsClientStopResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConnectionMonitorsClientStopResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Stop - Stops the specified connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConnectionMonitorsClient) stop(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginStopOptions) (*http.Response, error) { + var err error + const operationName = "ConnectionMonitorsClient.BeginStop" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopCreateRequest(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, 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 +} + +// stopCreateRequest creates the Stop request. +func (client *ConnectionMonitorsClient) stopCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, options *ConnectionMonitorsClientBeginStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/stop" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if connectionMonitorName == "" { + return nil, errors.New("parameter connectionMonitorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionMonitorName}", url.PathEscape(connectionMonitorName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// UpdateTags - Update tags of the specified connection monitor. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - connectionMonitorName - The name of the connection monitor. +// - parameters - Parameters supplied to update connection monitor tags. +// - options - ConnectionMonitorsClientUpdateTagsOptions contains the optional parameters for the ConnectionMonitorsClient.UpdateTags +// method. +func (client *ConnectionMonitorsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters TagsObject, options *ConnectionMonitorsClientUpdateTagsOptions) (ConnectionMonitorsClientUpdateTagsResponse, error) { + var err error + const operationName = "ConnectionMonitorsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, parameters, options) + if err != nil { + return ConnectionMonitorsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectionMonitorsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConnectionMonitorsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ConnectionMonitorsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters TagsObject, options *ConnectionMonitorsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if connectionMonitorName == "" { + return nil, errors.New("parameter connectionMonitorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionMonitorName}", url.PathEscape(connectionMonitorName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ConnectionMonitorsClient) updateTagsHandleResponse(resp *http.Response) (ConnectionMonitorsClientUpdateTagsResponse, error) { + result := ConnectionMonitorsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionMonitorResult); err != nil { + return ConnectionMonitorsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/connectivityconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/connectivityconfigurations_client.go new file mode 100644 index 000000000..0e0317c17 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/connectivityconfigurations_client.go @@ -0,0 +1,349 @@ +//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 armnetwork + +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" +) + +// ConnectivityConfigurationsClient contains the methods for the ConnectivityConfigurations group. +// Don't use this type directly, use NewConnectivityConfigurationsClient() instead. +type ConnectivityConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewConnectivityConfigurationsClient creates a new instance of ConnectivityConfigurationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewConnectivityConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConnectivityConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ConnectivityConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates/Updates a new network manager connectivity configuration +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager connectivity configuration. +// - connectivityConfiguration - Parameters supplied to create/update a network manager connectivity configuration +// - options - ConnectivityConfigurationsClientCreateOrUpdateOptions contains the optional parameters for the ConnectivityConfigurationsClient.CreateOrUpdate +// method. +func (client *ConnectivityConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, connectivityConfiguration ConnectivityConfiguration, options *ConnectivityConfigurationsClientCreateOrUpdateOptions) (ConnectivityConfigurationsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ConnectivityConfigurationsClient.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, networkManagerName, configurationName, connectivityConfiguration, options) + if err != nil { + return ConnectivityConfigurationsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectivityConfigurationsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ConnectivityConfigurationsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ConnectivityConfigurationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, connectivityConfiguration ConnectivityConfiguration, options *ConnectivityConfigurationsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/connectivityConfigurations/{configurationName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, connectivityConfiguration); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ConnectivityConfigurationsClient) createOrUpdateHandleResponse(resp *http.Response) (ConnectivityConfigurationsClientCreateOrUpdateResponse, error) { + result := ConnectivityConfigurationsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectivityConfiguration); err != nil { + return ConnectivityConfigurationsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes a network manager connectivity configuration, specified by the resource group, network manager name, +// and connectivity configuration name +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager connectivity configuration. +// - options - ConnectivityConfigurationsClientBeginDeleteOptions contains the optional parameters for the ConnectivityConfigurationsClient.BeginDelete +// method. +func (client *ConnectivityConfigurationsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *ConnectivityConfigurationsClientBeginDeleteOptions) (*runtime.Poller[ConnectivityConfigurationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkManagerName, configurationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConnectivityConfigurationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConnectivityConfigurationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a network manager connectivity configuration, specified by the resource group, network manager name, and +// connectivity configuration name +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ConnectivityConfigurationsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *ConnectivityConfigurationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ConnectivityConfigurationsClient.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, networkManagerName, configurationName, 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 *ConnectivityConfigurationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *ConnectivityConfigurationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/connectivityConfigurations/{configurationName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + 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-05-01") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a Network Connectivity Configuration, specified by the resource group, network manager name, and connectivity +// Configuration name +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager connectivity configuration. +// - options - ConnectivityConfigurationsClientGetOptions contains the optional parameters for the ConnectivityConfigurationsClient.Get +// method. +func (client *ConnectivityConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *ConnectivityConfigurationsClientGetOptions) (ConnectivityConfigurationsClientGetResponse, error) { + var err error + const operationName = "ConnectivityConfigurationsClient.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, networkManagerName, configurationName, options) + if err != nil { + return ConnectivityConfigurationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectivityConfigurationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConnectivityConfigurationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ConnectivityConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *ConnectivityConfigurationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/connectivityConfigurations/{configurationName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ConnectivityConfigurationsClient) getHandleResponse(resp *http.Response) (ConnectivityConfigurationsClientGetResponse, error) { + result := ConnectivityConfigurationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectivityConfiguration); err != nil { + return ConnectivityConfigurationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the network manager connectivity configuration in a specified network manager. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - options - ConnectivityConfigurationsClientListOptions contains the optional parameters for the ConnectivityConfigurationsClient.NewListPager +// method. +func (client *ConnectivityConfigurationsClient) NewListPager(resourceGroupName string, networkManagerName string, options *ConnectivityConfigurationsClientListOptions) *runtime.Pager[ConnectivityConfigurationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ConnectivityConfigurationsClientListResponse]{ + More: func(page ConnectivityConfigurationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConnectivityConfigurationsClientListResponse) (ConnectivityConfigurationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConnectivityConfigurationsClient.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, networkManagerName, options) + }, nil) + if err != nil { + return ConnectivityConfigurationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ConnectivityConfigurationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, options *ConnectivityConfigurationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/connectivityConfigurations" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ConnectivityConfigurationsClient) listHandleResponse(resp *http.Response) (ConnectivityConfigurationsClientListResponse, error) { + result := ConnectivityConfigurationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectivityConfigurationListResult); err != nil { + return ConnectivityConfigurationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/constants.go new file mode 100644 index 000000000..6ec8bdb32 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/constants.go @@ -0,0 +1,4198 @@ +//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 armnetwork + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork" + moduleVersion = "v4.3.0" +) + +// Access - Access to be allowed or denied. +type Access string + +const ( + AccessAllow Access = "Allow" + AccessDeny Access = "Deny" +) + +// PossibleAccessValues returns the possible values for the Access const type. +func PossibleAccessValues() []Access { + return []Access{ + AccessAllow, + AccessDeny, + } +} + +// ActionType - Defines the action to take on rule match. +type ActionType string + +const ( + ActionTypeAllow ActionType = "Allow" + ActionTypeAnomalyScoring ActionType = "AnomalyScoring" + ActionTypeBlock ActionType = "Block" + ActionTypeLog ActionType = "Log" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeAllow, + ActionTypeAnomalyScoring, + ActionTypeBlock, + ActionTypeLog, + } +} + +// AddressPrefixType - Address prefix type. +type AddressPrefixType string + +const ( + AddressPrefixTypeIPPrefix AddressPrefixType = "IPPrefix" + AddressPrefixTypeServiceTag AddressPrefixType = "ServiceTag" +) + +// PossibleAddressPrefixTypeValues returns the possible values for the AddressPrefixType const type. +func PossibleAddressPrefixTypeValues() []AddressPrefixType { + return []AddressPrefixType{ + AddressPrefixTypeIPPrefix, + AddressPrefixTypeServiceTag, + } +} + +// AdminRuleKind - Whether the rule is custom or default. +type AdminRuleKind string + +const ( + AdminRuleKindCustom AdminRuleKind = "Custom" + AdminRuleKindDefault AdminRuleKind = "Default" +) + +// PossibleAdminRuleKindValues returns the possible values for the AdminRuleKind const type. +func PossibleAdminRuleKindValues() []AdminRuleKind { + return []AdminRuleKind{ + AdminRuleKindCustom, + AdminRuleKindDefault, + } +} + +// AdminState - Property to indicate if the Express Route Gateway serves traffic when there are multiple Express Route Gateways +// in the vnet +type AdminState string + +const ( + AdminStateDisabled AdminState = "Disabled" + AdminStateEnabled AdminState = "Enabled" +) + +// PossibleAdminStateValues returns the possible values for the AdminState const type. +func PossibleAdminStateValues() []AdminState { + return []AdminState{ + AdminStateDisabled, + AdminStateEnabled, + } +} + +// ApplicationGatewayBackendHealthServerHealth - Health of backend server. +type ApplicationGatewayBackendHealthServerHealth string + +const ( + ApplicationGatewayBackendHealthServerHealthDown ApplicationGatewayBackendHealthServerHealth = "Down" + ApplicationGatewayBackendHealthServerHealthDraining ApplicationGatewayBackendHealthServerHealth = "Draining" + ApplicationGatewayBackendHealthServerHealthPartial ApplicationGatewayBackendHealthServerHealth = "Partial" + ApplicationGatewayBackendHealthServerHealthUnknown ApplicationGatewayBackendHealthServerHealth = "Unknown" + ApplicationGatewayBackendHealthServerHealthUp ApplicationGatewayBackendHealthServerHealth = "Up" +) + +// PossibleApplicationGatewayBackendHealthServerHealthValues returns the possible values for the ApplicationGatewayBackendHealthServerHealth const type. +func PossibleApplicationGatewayBackendHealthServerHealthValues() []ApplicationGatewayBackendHealthServerHealth { + return []ApplicationGatewayBackendHealthServerHealth{ + ApplicationGatewayBackendHealthServerHealthDown, + ApplicationGatewayBackendHealthServerHealthDraining, + ApplicationGatewayBackendHealthServerHealthPartial, + ApplicationGatewayBackendHealthServerHealthUnknown, + ApplicationGatewayBackendHealthServerHealthUp, + } +} + +// ApplicationGatewayClientRevocationOptions - Verify client certificate revocation status. +type ApplicationGatewayClientRevocationOptions string + +const ( + ApplicationGatewayClientRevocationOptionsNone ApplicationGatewayClientRevocationOptions = "None" + ApplicationGatewayClientRevocationOptionsOCSP ApplicationGatewayClientRevocationOptions = "OCSP" +) + +// PossibleApplicationGatewayClientRevocationOptionsValues returns the possible values for the ApplicationGatewayClientRevocationOptions const type. +func PossibleApplicationGatewayClientRevocationOptionsValues() []ApplicationGatewayClientRevocationOptions { + return []ApplicationGatewayClientRevocationOptions{ + ApplicationGatewayClientRevocationOptionsNone, + ApplicationGatewayClientRevocationOptionsOCSP, + } +} + +// ApplicationGatewayCookieBasedAffinity - Cookie based affinity. +type ApplicationGatewayCookieBasedAffinity string + +const ( + ApplicationGatewayCookieBasedAffinityDisabled ApplicationGatewayCookieBasedAffinity = "Disabled" + ApplicationGatewayCookieBasedAffinityEnabled ApplicationGatewayCookieBasedAffinity = "Enabled" +) + +// PossibleApplicationGatewayCookieBasedAffinityValues returns the possible values for the ApplicationGatewayCookieBasedAffinity const type. +func PossibleApplicationGatewayCookieBasedAffinityValues() []ApplicationGatewayCookieBasedAffinity { + return []ApplicationGatewayCookieBasedAffinity{ + ApplicationGatewayCookieBasedAffinityDisabled, + ApplicationGatewayCookieBasedAffinityEnabled, + } +} + +// ApplicationGatewayCustomErrorStatusCode - Status code of the application gateway custom error. +type ApplicationGatewayCustomErrorStatusCode string + +const ( + ApplicationGatewayCustomErrorStatusCodeHTTPStatus400 ApplicationGatewayCustomErrorStatusCode = "HttpStatus400" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus403 ApplicationGatewayCustomErrorStatusCode = "HttpStatus403" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus404 ApplicationGatewayCustomErrorStatusCode = "HttpStatus404" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus405 ApplicationGatewayCustomErrorStatusCode = "HttpStatus405" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus408 ApplicationGatewayCustomErrorStatusCode = "HttpStatus408" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus500 ApplicationGatewayCustomErrorStatusCode = "HttpStatus500" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus502 ApplicationGatewayCustomErrorStatusCode = "HttpStatus502" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus503 ApplicationGatewayCustomErrorStatusCode = "HttpStatus503" + ApplicationGatewayCustomErrorStatusCodeHTTPStatus504 ApplicationGatewayCustomErrorStatusCode = "HttpStatus504" +) + +// PossibleApplicationGatewayCustomErrorStatusCodeValues returns the possible values for the ApplicationGatewayCustomErrorStatusCode const type. +func PossibleApplicationGatewayCustomErrorStatusCodeValues() []ApplicationGatewayCustomErrorStatusCode { + return []ApplicationGatewayCustomErrorStatusCode{ + ApplicationGatewayCustomErrorStatusCodeHTTPStatus400, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus403, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus404, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus405, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus408, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus500, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus502, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus503, + ApplicationGatewayCustomErrorStatusCodeHTTPStatus504, + } +} + +// ApplicationGatewayFirewallMode - Web application firewall mode. +type ApplicationGatewayFirewallMode string + +const ( + ApplicationGatewayFirewallModeDetection ApplicationGatewayFirewallMode = "Detection" + ApplicationGatewayFirewallModePrevention ApplicationGatewayFirewallMode = "Prevention" +) + +// PossibleApplicationGatewayFirewallModeValues returns the possible values for the ApplicationGatewayFirewallMode const type. +func PossibleApplicationGatewayFirewallModeValues() []ApplicationGatewayFirewallMode { + return []ApplicationGatewayFirewallMode{ + ApplicationGatewayFirewallModeDetection, + ApplicationGatewayFirewallModePrevention, + } +} + +// ApplicationGatewayFirewallRateLimitDuration - Duration over which Rate Limit policy will be applied. Applies only when +// ruleType is RateLimitRule. +type ApplicationGatewayFirewallRateLimitDuration string + +const ( + ApplicationGatewayFirewallRateLimitDurationFiveMins ApplicationGatewayFirewallRateLimitDuration = "FiveMins" + ApplicationGatewayFirewallRateLimitDurationOneMin ApplicationGatewayFirewallRateLimitDuration = "OneMin" +) + +// PossibleApplicationGatewayFirewallRateLimitDurationValues returns the possible values for the ApplicationGatewayFirewallRateLimitDuration const type. +func PossibleApplicationGatewayFirewallRateLimitDurationValues() []ApplicationGatewayFirewallRateLimitDuration { + return []ApplicationGatewayFirewallRateLimitDuration{ + ApplicationGatewayFirewallRateLimitDurationFiveMins, + ApplicationGatewayFirewallRateLimitDurationOneMin, + } +} + +// ApplicationGatewayFirewallUserSessionVariable - User Session clause variable. +type ApplicationGatewayFirewallUserSessionVariable string + +const ( + ApplicationGatewayFirewallUserSessionVariableClientAddr ApplicationGatewayFirewallUserSessionVariable = "ClientAddr" + ApplicationGatewayFirewallUserSessionVariableGeoLocation ApplicationGatewayFirewallUserSessionVariable = "GeoLocation" + ApplicationGatewayFirewallUserSessionVariableNone ApplicationGatewayFirewallUserSessionVariable = "None" +) + +// PossibleApplicationGatewayFirewallUserSessionVariableValues returns the possible values for the ApplicationGatewayFirewallUserSessionVariable const type. +func PossibleApplicationGatewayFirewallUserSessionVariableValues() []ApplicationGatewayFirewallUserSessionVariable { + return []ApplicationGatewayFirewallUserSessionVariable{ + ApplicationGatewayFirewallUserSessionVariableClientAddr, + ApplicationGatewayFirewallUserSessionVariableGeoLocation, + ApplicationGatewayFirewallUserSessionVariableNone, + } +} + +// ApplicationGatewayLoadDistributionAlgorithm - Load Distribution Algorithm enums. +type ApplicationGatewayLoadDistributionAlgorithm string + +const ( + ApplicationGatewayLoadDistributionAlgorithmIPHash ApplicationGatewayLoadDistributionAlgorithm = "IpHash" + ApplicationGatewayLoadDistributionAlgorithmLeastConnections ApplicationGatewayLoadDistributionAlgorithm = "LeastConnections" + ApplicationGatewayLoadDistributionAlgorithmRoundRobin ApplicationGatewayLoadDistributionAlgorithm = "RoundRobin" +) + +// PossibleApplicationGatewayLoadDistributionAlgorithmValues returns the possible values for the ApplicationGatewayLoadDistributionAlgorithm const type. +func PossibleApplicationGatewayLoadDistributionAlgorithmValues() []ApplicationGatewayLoadDistributionAlgorithm { + return []ApplicationGatewayLoadDistributionAlgorithm{ + ApplicationGatewayLoadDistributionAlgorithmIPHash, + ApplicationGatewayLoadDistributionAlgorithmLeastConnections, + ApplicationGatewayLoadDistributionAlgorithmRoundRobin, + } +} + +// ApplicationGatewayOperationalState - Operational state of the application gateway resource. +type ApplicationGatewayOperationalState string + +const ( + ApplicationGatewayOperationalStateRunning ApplicationGatewayOperationalState = "Running" + ApplicationGatewayOperationalStateStarting ApplicationGatewayOperationalState = "Starting" + ApplicationGatewayOperationalStateStopped ApplicationGatewayOperationalState = "Stopped" + ApplicationGatewayOperationalStateStopping ApplicationGatewayOperationalState = "Stopping" +) + +// PossibleApplicationGatewayOperationalStateValues returns the possible values for the ApplicationGatewayOperationalState const type. +func PossibleApplicationGatewayOperationalStateValues() []ApplicationGatewayOperationalState { + return []ApplicationGatewayOperationalState{ + ApplicationGatewayOperationalStateRunning, + ApplicationGatewayOperationalStateStarting, + ApplicationGatewayOperationalStateStopped, + ApplicationGatewayOperationalStateStopping, + } +} + +// ApplicationGatewayProtocol - Application Gateway protocol. +type ApplicationGatewayProtocol string + +const ( + ApplicationGatewayProtocolHTTP ApplicationGatewayProtocol = "Http" + ApplicationGatewayProtocolHTTPS ApplicationGatewayProtocol = "Https" + ApplicationGatewayProtocolTCP ApplicationGatewayProtocol = "Tcp" + ApplicationGatewayProtocolTLS ApplicationGatewayProtocol = "Tls" +) + +// PossibleApplicationGatewayProtocolValues returns the possible values for the ApplicationGatewayProtocol const type. +func PossibleApplicationGatewayProtocolValues() []ApplicationGatewayProtocol { + return []ApplicationGatewayProtocol{ + ApplicationGatewayProtocolHTTP, + ApplicationGatewayProtocolHTTPS, + ApplicationGatewayProtocolTCP, + ApplicationGatewayProtocolTLS, + } +} + +// ApplicationGatewayRedirectType - Redirect type enum. +type ApplicationGatewayRedirectType string + +const ( + ApplicationGatewayRedirectTypeFound ApplicationGatewayRedirectType = "Found" + ApplicationGatewayRedirectTypePermanent ApplicationGatewayRedirectType = "Permanent" + ApplicationGatewayRedirectTypeSeeOther ApplicationGatewayRedirectType = "SeeOther" + ApplicationGatewayRedirectTypeTemporary ApplicationGatewayRedirectType = "Temporary" +) + +// PossibleApplicationGatewayRedirectTypeValues returns the possible values for the ApplicationGatewayRedirectType const type. +func PossibleApplicationGatewayRedirectTypeValues() []ApplicationGatewayRedirectType { + return []ApplicationGatewayRedirectType{ + ApplicationGatewayRedirectTypeFound, + ApplicationGatewayRedirectTypePermanent, + ApplicationGatewayRedirectTypeSeeOther, + ApplicationGatewayRedirectTypeTemporary, + } +} + +// ApplicationGatewayRequestRoutingRuleType - Rule type. +type ApplicationGatewayRequestRoutingRuleType string + +const ( + ApplicationGatewayRequestRoutingRuleTypeBasic ApplicationGatewayRequestRoutingRuleType = "Basic" + ApplicationGatewayRequestRoutingRuleTypePathBasedRouting ApplicationGatewayRequestRoutingRuleType = "PathBasedRouting" +) + +// PossibleApplicationGatewayRequestRoutingRuleTypeValues returns the possible values for the ApplicationGatewayRequestRoutingRuleType const type. +func PossibleApplicationGatewayRequestRoutingRuleTypeValues() []ApplicationGatewayRequestRoutingRuleType { + return []ApplicationGatewayRequestRoutingRuleType{ + ApplicationGatewayRequestRoutingRuleTypeBasic, + ApplicationGatewayRequestRoutingRuleTypePathBasedRouting, + } +} + +// ApplicationGatewayRuleSetStatusOptions - The rule set status +type ApplicationGatewayRuleSetStatusOptions string + +const ( + ApplicationGatewayRuleSetStatusOptionsDeprecated ApplicationGatewayRuleSetStatusOptions = "Deprecated" + ApplicationGatewayRuleSetStatusOptionsGA ApplicationGatewayRuleSetStatusOptions = "GA" + ApplicationGatewayRuleSetStatusOptionsPreview ApplicationGatewayRuleSetStatusOptions = "Preview" + ApplicationGatewayRuleSetStatusOptionsSupported ApplicationGatewayRuleSetStatusOptions = "Supported" +) + +// PossibleApplicationGatewayRuleSetStatusOptionsValues returns the possible values for the ApplicationGatewayRuleSetStatusOptions const type. +func PossibleApplicationGatewayRuleSetStatusOptionsValues() []ApplicationGatewayRuleSetStatusOptions { + return []ApplicationGatewayRuleSetStatusOptions{ + ApplicationGatewayRuleSetStatusOptionsDeprecated, + ApplicationGatewayRuleSetStatusOptionsGA, + ApplicationGatewayRuleSetStatusOptionsPreview, + ApplicationGatewayRuleSetStatusOptionsSupported, + } +} + +// ApplicationGatewaySKUName - Name of an application gateway SKU. +type ApplicationGatewaySKUName string + +const ( + ApplicationGatewaySKUNameBasic ApplicationGatewaySKUName = "Basic" + ApplicationGatewaySKUNameStandardLarge ApplicationGatewaySKUName = "Standard_Large" + ApplicationGatewaySKUNameStandardMedium ApplicationGatewaySKUName = "Standard_Medium" + ApplicationGatewaySKUNameStandardSmall ApplicationGatewaySKUName = "Standard_Small" + ApplicationGatewaySKUNameStandardV2 ApplicationGatewaySKUName = "Standard_v2" + ApplicationGatewaySKUNameWAFLarge ApplicationGatewaySKUName = "WAF_Large" + ApplicationGatewaySKUNameWAFMedium ApplicationGatewaySKUName = "WAF_Medium" + ApplicationGatewaySKUNameWAFV2 ApplicationGatewaySKUName = "WAF_v2" +) + +// PossibleApplicationGatewaySKUNameValues returns the possible values for the ApplicationGatewaySKUName const type. +func PossibleApplicationGatewaySKUNameValues() []ApplicationGatewaySKUName { + return []ApplicationGatewaySKUName{ + ApplicationGatewaySKUNameBasic, + ApplicationGatewaySKUNameStandardLarge, + ApplicationGatewaySKUNameStandardMedium, + ApplicationGatewaySKUNameStandardSmall, + ApplicationGatewaySKUNameStandardV2, + ApplicationGatewaySKUNameWAFLarge, + ApplicationGatewaySKUNameWAFMedium, + ApplicationGatewaySKUNameWAFV2, + } +} + +// ApplicationGatewaySSLCipherSuite - Ssl cipher suites enums. +type ApplicationGatewaySSLCipherSuite string + +const ( + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITH3DESEDECBCSHA ApplicationGatewaySSLCipherSuite = "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES128CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES128CBCSHA256 ApplicationGatewaySSLCipherSuite = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES256CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES256CBCSHA256 ApplicationGatewaySSLCipherSuite = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES128CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES128GCMSHA256 ApplicationGatewaySSLCipherSuite = "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES256CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES256GCMSHA384 ApplicationGatewaySSLCipherSuite = "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES128CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES128CBCSHA256 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES128GCMSHA256 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES256CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES256CBCSHA384 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES256GCMSHA384 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES128CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES128CBCSHA256 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES128GCMSHA256 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES256CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES256CBCSHA384 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES256GCMSHA384 ApplicationGatewaySSLCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" + ApplicationGatewaySSLCipherSuiteTLSRSAWITH3DESEDECBCSHA ApplicationGatewaySSLCipherSuite = "TLS_RSA_WITH_3DES_EDE_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES128CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_RSA_WITH_AES_128_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES128CBCSHA256 ApplicationGatewaySSLCipherSuite = "TLS_RSA_WITH_AES_128_CBC_SHA256" + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES128GCMSHA256 ApplicationGatewaySSLCipherSuite = "TLS_RSA_WITH_AES_128_GCM_SHA256" + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES256CBCSHA ApplicationGatewaySSLCipherSuite = "TLS_RSA_WITH_AES_256_CBC_SHA" + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES256CBCSHA256 ApplicationGatewaySSLCipherSuite = "TLS_RSA_WITH_AES_256_CBC_SHA256" + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES256GCMSHA384 ApplicationGatewaySSLCipherSuite = "TLS_RSA_WITH_AES_256_GCM_SHA384" +) + +// PossibleApplicationGatewaySSLCipherSuiteValues returns the possible values for the ApplicationGatewaySSLCipherSuite const type. +func PossibleApplicationGatewaySSLCipherSuiteValues() []ApplicationGatewaySSLCipherSuite { + return []ApplicationGatewaySSLCipherSuite{ + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITH3DESEDECBCSHA, + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES128CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES128CBCSHA256, + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES256CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSDHEDSSWITHAES256CBCSHA256, + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES128CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES128GCMSHA256, + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES256CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSDHERSAWITHAES256GCMSHA384, + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES128CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES128CBCSHA256, + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES128GCMSHA256, + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES256CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES256CBCSHA384, + ApplicationGatewaySSLCipherSuiteTLSECDHEECDSAWITHAES256GCMSHA384, + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES128CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES128CBCSHA256, + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES128GCMSHA256, + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES256CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES256CBCSHA384, + ApplicationGatewaySSLCipherSuiteTLSECDHERSAWITHAES256GCMSHA384, + ApplicationGatewaySSLCipherSuiteTLSRSAWITH3DESEDECBCSHA, + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES128CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES128CBCSHA256, + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES128GCMSHA256, + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES256CBCSHA, + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES256CBCSHA256, + ApplicationGatewaySSLCipherSuiteTLSRSAWITHAES256GCMSHA384, + } +} + +// ApplicationGatewaySSLPolicyName - Ssl predefined policy name enums. +type ApplicationGatewaySSLPolicyName string + +const ( + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20150501 ApplicationGatewaySSLPolicyName = "AppGwSslPolicy20150501" + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20170401 ApplicationGatewaySSLPolicyName = "AppGwSslPolicy20170401" + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20170401S ApplicationGatewaySSLPolicyName = "AppGwSslPolicy20170401S" + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20220101 ApplicationGatewaySSLPolicyName = "AppGwSslPolicy20220101" + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20220101S ApplicationGatewaySSLPolicyName = "AppGwSslPolicy20220101S" +) + +// PossibleApplicationGatewaySSLPolicyNameValues returns the possible values for the ApplicationGatewaySSLPolicyName const type. +func PossibleApplicationGatewaySSLPolicyNameValues() []ApplicationGatewaySSLPolicyName { + return []ApplicationGatewaySSLPolicyName{ + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20150501, + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20170401, + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20170401S, + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20220101, + ApplicationGatewaySSLPolicyNameAppGwSSLPolicy20220101S, + } +} + +// ApplicationGatewaySSLPolicyType - Type of Ssl Policy. +type ApplicationGatewaySSLPolicyType string + +const ( + ApplicationGatewaySSLPolicyTypeCustom ApplicationGatewaySSLPolicyType = "Custom" + ApplicationGatewaySSLPolicyTypeCustomV2 ApplicationGatewaySSLPolicyType = "CustomV2" + ApplicationGatewaySSLPolicyTypePredefined ApplicationGatewaySSLPolicyType = "Predefined" +) + +// PossibleApplicationGatewaySSLPolicyTypeValues returns the possible values for the ApplicationGatewaySSLPolicyType const type. +func PossibleApplicationGatewaySSLPolicyTypeValues() []ApplicationGatewaySSLPolicyType { + return []ApplicationGatewaySSLPolicyType{ + ApplicationGatewaySSLPolicyTypeCustom, + ApplicationGatewaySSLPolicyTypeCustomV2, + ApplicationGatewaySSLPolicyTypePredefined, + } +} + +// ApplicationGatewaySSLProtocol - Ssl protocol enums. +type ApplicationGatewaySSLProtocol string + +const ( + ApplicationGatewaySSLProtocolTLSv10 ApplicationGatewaySSLProtocol = "TLSv1_0" + ApplicationGatewaySSLProtocolTLSv11 ApplicationGatewaySSLProtocol = "TLSv1_1" + ApplicationGatewaySSLProtocolTLSv12 ApplicationGatewaySSLProtocol = "TLSv1_2" + ApplicationGatewaySSLProtocolTLSv13 ApplicationGatewaySSLProtocol = "TLSv1_3" +) + +// PossibleApplicationGatewaySSLProtocolValues returns the possible values for the ApplicationGatewaySSLProtocol const type. +func PossibleApplicationGatewaySSLProtocolValues() []ApplicationGatewaySSLProtocol { + return []ApplicationGatewaySSLProtocol{ + ApplicationGatewaySSLProtocolTLSv10, + ApplicationGatewaySSLProtocolTLSv11, + ApplicationGatewaySSLProtocolTLSv12, + ApplicationGatewaySSLProtocolTLSv13, + } +} + +// ApplicationGatewayTier - Tier of an application gateway. +type ApplicationGatewayTier string + +const ( + ApplicationGatewayTierBasic ApplicationGatewayTier = "Basic" + ApplicationGatewayTierStandard ApplicationGatewayTier = "Standard" + ApplicationGatewayTierStandardV2 ApplicationGatewayTier = "Standard_v2" + ApplicationGatewayTierWAF ApplicationGatewayTier = "WAF" + ApplicationGatewayTierWAFV2 ApplicationGatewayTier = "WAF_v2" +) + +// PossibleApplicationGatewayTierValues returns the possible values for the ApplicationGatewayTier const type. +func PossibleApplicationGatewayTierValues() []ApplicationGatewayTier { + return []ApplicationGatewayTier{ + ApplicationGatewayTierBasic, + ApplicationGatewayTierStandard, + ApplicationGatewayTierStandardV2, + ApplicationGatewayTierWAF, + ApplicationGatewayTierWAFV2, + } +} + +type ApplicationGatewayTierTypes string + +const ( + ApplicationGatewayTierTypesStandard ApplicationGatewayTierTypes = "Standard" + ApplicationGatewayTierTypesStandardV2 ApplicationGatewayTierTypes = "Standard_v2" + ApplicationGatewayTierTypesWAF ApplicationGatewayTierTypes = "WAF" + ApplicationGatewayTierTypesWAFV2 ApplicationGatewayTierTypes = "WAF_v2" +) + +// PossibleApplicationGatewayTierTypesValues returns the possible values for the ApplicationGatewayTierTypes const type. +func PossibleApplicationGatewayTierTypesValues() []ApplicationGatewayTierTypes { + return []ApplicationGatewayTierTypes{ + ApplicationGatewayTierTypesStandard, + ApplicationGatewayTierTypesStandardV2, + ApplicationGatewayTierTypesWAF, + ApplicationGatewayTierTypesWAFV2, + } +} + +// ApplicationGatewayWafRuleActionTypes - The string representation of the web application firewall rule action. +type ApplicationGatewayWafRuleActionTypes string + +const ( + ApplicationGatewayWafRuleActionTypesAllow ApplicationGatewayWafRuleActionTypes = "Allow" + ApplicationGatewayWafRuleActionTypesAnomalyScoring ApplicationGatewayWafRuleActionTypes = "AnomalyScoring" + ApplicationGatewayWafRuleActionTypesBlock ApplicationGatewayWafRuleActionTypes = "Block" + ApplicationGatewayWafRuleActionTypesLog ApplicationGatewayWafRuleActionTypes = "Log" + ApplicationGatewayWafRuleActionTypesNone ApplicationGatewayWafRuleActionTypes = "None" +) + +// PossibleApplicationGatewayWafRuleActionTypesValues returns the possible values for the ApplicationGatewayWafRuleActionTypes const type. +func PossibleApplicationGatewayWafRuleActionTypesValues() []ApplicationGatewayWafRuleActionTypes { + return []ApplicationGatewayWafRuleActionTypes{ + ApplicationGatewayWafRuleActionTypesAllow, + ApplicationGatewayWafRuleActionTypesAnomalyScoring, + ApplicationGatewayWafRuleActionTypesBlock, + ApplicationGatewayWafRuleActionTypesLog, + ApplicationGatewayWafRuleActionTypesNone, + } +} + +// ApplicationGatewayWafRuleStateTypes - The string representation of the web application firewall rule state. +type ApplicationGatewayWafRuleStateTypes string + +const ( + ApplicationGatewayWafRuleStateTypesDisabled ApplicationGatewayWafRuleStateTypes = "Disabled" + ApplicationGatewayWafRuleStateTypesEnabled ApplicationGatewayWafRuleStateTypes = "Enabled" +) + +// PossibleApplicationGatewayWafRuleStateTypesValues returns the possible values for the ApplicationGatewayWafRuleStateTypes const type. +func PossibleApplicationGatewayWafRuleStateTypesValues() []ApplicationGatewayWafRuleStateTypes { + return []ApplicationGatewayWafRuleStateTypes{ + ApplicationGatewayWafRuleStateTypesDisabled, + ApplicationGatewayWafRuleStateTypesEnabled, + } +} + +// AssociationType - The association type of the child resource to the parent resource. +type AssociationType string + +const ( + AssociationTypeAssociated AssociationType = "Associated" + AssociationTypeContains AssociationType = "Contains" +) + +// PossibleAssociationTypeValues returns the possible values for the AssociationType const type. +func PossibleAssociationTypeValues() []AssociationType { + return []AssociationType{ + AssociationTypeAssociated, + AssociationTypeContains, + } +} + +// AuthenticationMethod - VPN client authentication method. +type AuthenticationMethod string + +const ( + AuthenticationMethodEAPMSCHAPv2 AuthenticationMethod = "EAPMSCHAPv2" + AuthenticationMethodEAPTLS AuthenticationMethod = "EAPTLS" +) + +// PossibleAuthenticationMethodValues returns the possible values for the AuthenticationMethod const type. +func PossibleAuthenticationMethodValues() []AuthenticationMethod { + return []AuthenticationMethod{ + AuthenticationMethodEAPMSCHAPv2, + AuthenticationMethodEAPTLS, + } +} + +// AuthorizationUseStatus - The authorization use status. +type AuthorizationUseStatus string + +const ( + AuthorizationUseStatusAvailable AuthorizationUseStatus = "Available" + AuthorizationUseStatusInUse AuthorizationUseStatus = "InUse" +) + +// PossibleAuthorizationUseStatusValues returns the possible values for the AuthorizationUseStatus const type. +func PossibleAuthorizationUseStatusValues() []AuthorizationUseStatus { + return []AuthorizationUseStatus{ + AuthorizationUseStatusAvailable, + AuthorizationUseStatusInUse, + } +} + +// AutoLearnPrivateRangesMode - The operation mode for automatically learning private ranges to not be SNAT +type AutoLearnPrivateRangesMode string + +const ( + AutoLearnPrivateRangesModeDisabled AutoLearnPrivateRangesMode = "Disabled" + AutoLearnPrivateRangesModeEnabled AutoLearnPrivateRangesMode = "Enabled" +) + +// PossibleAutoLearnPrivateRangesModeValues returns the possible values for the AutoLearnPrivateRangesMode const type. +func PossibleAutoLearnPrivateRangesModeValues() []AutoLearnPrivateRangesMode { + return []AutoLearnPrivateRangesMode{ + AutoLearnPrivateRangesModeDisabled, + AutoLearnPrivateRangesModeEnabled, + } +} + +// AzureFirewallApplicationRuleProtocolType - The protocol type of a Application Rule resource. +type AzureFirewallApplicationRuleProtocolType string + +const ( + AzureFirewallApplicationRuleProtocolTypeHTTP AzureFirewallApplicationRuleProtocolType = "Http" + AzureFirewallApplicationRuleProtocolTypeHTTPS AzureFirewallApplicationRuleProtocolType = "Https" + AzureFirewallApplicationRuleProtocolTypeMssql AzureFirewallApplicationRuleProtocolType = "Mssql" +) + +// PossibleAzureFirewallApplicationRuleProtocolTypeValues returns the possible values for the AzureFirewallApplicationRuleProtocolType const type. +func PossibleAzureFirewallApplicationRuleProtocolTypeValues() []AzureFirewallApplicationRuleProtocolType { + return []AzureFirewallApplicationRuleProtocolType{ + AzureFirewallApplicationRuleProtocolTypeHTTP, + AzureFirewallApplicationRuleProtocolTypeHTTPS, + AzureFirewallApplicationRuleProtocolTypeMssql, + } +} + +// AzureFirewallNatRCActionType - The action type of a NAT rule collection. +type AzureFirewallNatRCActionType string + +const ( + AzureFirewallNatRCActionTypeDnat AzureFirewallNatRCActionType = "Dnat" + AzureFirewallNatRCActionTypeSnat AzureFirewallNatRCActionType = "Snat" +) + +// PossibleAzureFirewallNatRCActionTypeValues returns the possible values for the AzureFirewallNatRCActionType const type. +func PossibleAzureFirewallNatRCActionTypeValues() []AzureFirewallNatRCActionType { + return []AzureFirewallNatRCActionType{ + AzureFirewallNatRCActionTypeDnat, + AzureFirewallNatRCActionTypeSnat, + } +} + +// AzureFirewallNetworkRuleProtocol - The protocol of a Network Rule resource. +type AzureFirewallNetworkRuleProtocol string + +const ( + AzureFirewallNetworkRuleProtocolAny AzureFirewallNetworkRuleProtocol = "Any" + AzureFirewallNetworkRuleProtocolICMP AzureFirewallNetworkRuleProtocol = "ICMP" + AzureFirewallNetworkRuleProtocolTCP AzureFirewallNetworkRuleProtocol = "TCP" + AzureFirewallNetworkRuleProtocolUDP AzureFirewallNetworkRuleProtocol = "UDP" +) + +// PossibleAzureFirewallNetworkRuleProtocolValues returns the possible values for the AzureFirewallNetworkRuleProtocol const type. +func PossibleAzureFirewallNetworkRuleProtocolValues() []AzureFirewallNetworkRuleProtocol { + return []AzureFirewallNetworkRuleProtocol{ + AzureFirewallNetworkRuleProtocolAny, + AzureFirewallNetworkRuleProtocolICMP, + AzureFirewallNetworkRuleProtocolTCP, + AzureFirewallNetworkRuleProtocolUDP, + } +} + +// AzureFirewallPacketCaptureFlagsType - The flags type to be captured. +type AzureFirewallPacketCaptureFlagsType string + +const ( + AzureFirewallPacketCaptureFlagsTypeAck AzureFirewallPacketCaptureFlagsType = "ack" + AzureFirewallPacketCaptureFlagsTypeFin AzureFirewallPacketCaptureFlagsType = "fin" + AzureFirewallPacketCaptureFlagsTypePush AzureFirewallPacketCaptureFlagsType = "push" + AzureFirewallPacketCaptureFlagsTypeRst AzureFirewallPacketCaptureFlagsType = "rst" + AzureFirewallPacketCaptureFlagsTypeSyn AzureFirewallPacketCaptureFlagsType = "syn" + AzureFirewallPacketCaptureFlagsTypeUrg AzureFirewallPacketCaptureFlagsType = "urg" +) + +// PossibleAzureFirewallPacketCaptureFlagsTypeValues returns the possible values for the AzureFirewallPacketCaptureFlagsType const type. +func PossibleAzureFirewallPacketCaptureFlagsTypeValues() []AzureFirewallPacketCaptureFlagsType { + return []AzureFirewallPacketCaptureFlagsType{ + AzureFirewallPacketCaptureFlagsTypeAck, + AzureFirewallPacketCaptureFlagsTypeFin, + AzureFirewallPacketCaptureFlagsTypePush, + AzureFirewallPacketCaptureFlagsTypeRst, + AzureFirewallPacketCaptureFlagsTypeSyn, + AzureFirewallPacketCaptureFlagsTypeUrg, + } +} + +// AzureFirewallRCActionType - The action type of a rule collection. +type AzureFirewallRCActionType string + +const ( + AzureFirewallRCActionTypeAllow AzureFirewallRCActionType = "Allow" + AzureFirewallRCActionTypeDeny AzureFirewallRCActionType = "Deny" +) + +// PossibleAzureFirewallRCActionTypeValues returns the possible values for the AzureFirewallRCActionType const type. +func PossibleAzureFirewallRCActionTypeValues() []AzureFirewallRCActionType { + return []AzureFirewallRCActionType{ + AzureFirewallRCActionTypeAllow, + AzureFirewallRCActionTypeDeny, + } +} + +// AzureFirewallSKUName - Name of an Azure Firewall SKU. +type AzureFirewallSKUName string + +const ( + AzureFirewallSKUNameAZFWHub AzureFirewallSKUName = "AZFW_Hub" + AzureFirewallSKUNameAZFWVnet AzureFirewallSKUName = "AZFW_VNet" +) + +// PossibleAzureFirewallSKUNameValues returns the possible values for the AzureFirewallSKUName const type. +func PossibleAzureFirewallSKUNameValues() []AzureFirewallSKUName { + return []AzureFirewallSKUName{ + AzureFirewallSKUNameAZFWHub, + AzureFirewallSKUNameAZFWVnet, + } +} + +// AzureFirewallSKUTier - Tier of an Azure Firewall. +type AzureFirewallSKUTier string + +const ( + AzureFirewallSKUTierBasic AzureFirewallSKUTier = "Basic" + AzureFirewallSKUTierPremium AzureFirewallSKUTier = "Premium" + AzureFirewallSKUTierStandard AzureFirewallSKUTier = "Standard" +) + +// PossibleAzureFirewallSKUTierValues returns the possible values for the AzureFirewallSKUTier const type. +func PossibleAzureFirewallSKUTierValues() []AzureFirewallSKUTier { + return []AzureFirewallSKUTier{ + AzureFirewallSKUTierBasic, + AzureFirewallSKUTierPremium, + AzureFirewallSKUTierStandard, + } +} + +// AzureFirewallThreatIntelMode - The operation mode for Threat Intel. +type AzureFirewallThreatIntelMode string + +const ( + AzureFirewallThreatIntelModeAlert AzureFirewallThreatIntelMode = "Alert" + AzureFirewallThreatIntelModeDeny AzureFirewallThreatIntelMode = "Deny" + AzureFirewallThreatIntelModeOff AzureFirewallThreatIntelMode = "Off" +) + +// PossibleAzureFirewallThreatIntelModeValues returns the possible values for the AzureFirewallThreatIntelMode const type. +func PossibleAzureFirewallThreatIntelModeValues() []AzureFirewallThreatIntelMode { + return []AzureFirewallThreatIntelMode{ + AzureFirewallThreatIntelModeAlert, + AzureFirewallThreatIntelModeDeny, + AzureFirewallThreatIntelModeOff, + } +} + +// BastionConnectProtocol - The protocol used to connect to the target. +type BastionConnectProtocol string + +const ( + BastionConnectProtocolRDP BastionConnectProtocol = "RDP" + BastionConnectProtocolSSH BastionConnectProtocol = "SSH" +) + +// PossibleBastionConnectProtocolValues returns the possible values for the BastionConnectProtocol const type. +func PossibleBastionConnectProtocolValues() []BastionConnectProtocol { + return []BastionConnectProtocol{ + BastionConnectProtocolRDP, + BastionConnectProtocolSSH, + } +} + +// BastionHostSKUName - The name of this Bastion Host. +type BastionHostSKUName string + +const ( + BastionHostSKUNameBasic BastionHostSKUName = "Basic" + BastionHostSKUNameStandard BastionHostSKUName = "Standard" +) + +// PossibleBastionHostSKUNameValues returns the possible values for the BastionHostSKUName const type. +func PossibleBastionHostSKUNameValues() []BastionHostSKUName { + return []BastionHostSKUName{ + BastionHostSKUNameBasic, + BastionHostSKUNameStandard, + } +} + +// BgpPeerState - The BGP peer state. +type BgpPeerState string + +const ( + BgpPeerStateConnected BgpPeerState = "Connected" + BgpPeerStateConnecting BgpPeerState = "Connecting" + BgpPeerStateIdle BgpPeerState = "Idle" + BgpPeerStateStopped BgpPeerState = "Stopped" + BgpPeerStateUnknown BgpPeerState = "Unknown" +) + +// PossibleBgpPeerStateValues returns the possible values for the BgpPeerState const type. +func PossibleBgpPeerStateValues() []BgpPeerState { + return []BgpPeerState{ + BgpPeerStateConnected, + BgpPeerStateConnecting, + BgpPeerStateIdle, + BgpPeerStateStopped, + BgpPeerStateUnknown, + } +} + +// CircuitConnectionStatus - Express Route Circuit connection state. +type CircuitConnectionStatus string + +const ( + CircuitConnectionStatusConnected CircuitConnectionStatus = "Connected" + CircuitConnectionStatusConnecting CircuitConnectionStatus = "Connecting" + CircuitConnectionStatusDisconnected CircuitConnectionStatus = "Disconnected" +) + +// PossibleCircuitConnectionStatusValues returns the possible values for the CircuitConnectionStatus const type. +func PossibleCircuitConnectionStatusValues() []CircuitConnectionStatus { + return []CircuitConnectionStatus{ + CircuitConnectionStatusConnected, + CircuitConnectionStatusConnecting, + CircuitConnectionStatusDisconnected, + } +} + +// CommissionedState - The commissioned state of the Custom IP Prefix. +type CommissionedState string + +const ( + CommissionedStateCommissioned CommissionedState = "Commissioned" + CommissionedStateCommissionedNoInternetAdvertise CommissionedState = "CommissionedNoInternetAdvertise" + CommissionedStateCommissioning CommissionedState = "Commissioning" + CommissionedStateDecommissioning CommissionedState = "Decommissioning" + CommissionedStateDeprovisioned CommissionedState = "Deprovisioned" + CommissionedStateDeprovisioning CommissionedState = "Deprovisioning" + CommissionedStateProvisioned CommissionedState = "Provisioned" + CommissionedStateProvisioning CommissionedState = "Provisioning" +) + +// PossibleCommissionedStateValues returns the possible values for the CommissionedState const type. +func PossibleCommissionedStateValues() []CommissionedState { + return []CommissionedState{ + CommissionedStateCommissioned, + CommissionedStateCommissionedNoInternetAdvertise, + CommissionedStateCommissioning, + CommissionedStateDecommissioning, + CommissionedStateDeprovisioned, + CommissionedStateDeprovisioning, + CommissionedStateProvisioned, + CommissionedStateProvisioning, + } +} + +// ConfigurationType - Configuration Deployment Type. +type ConfigurationType string + +const ( + ConfigurationTypeConnectivity ConfigurationType = "Connectivity" + ConfigurationTypeSecurityAdmin ConfigurationType = "SecurityAdmin" +) + +// PossibleConfigurationTypeValues returns the possible values for the ConfigurationType const type. +func PossibleConfigurationTypeValues() []ConfigurationType { + return []ConfigurationType{ + ConfigurationTypeConnectivity, + ConfigurationTypeSecurityAdmin, + } +} + +// ConnectionMonitorEndpointFilterItemType - The type of item included in the filter. Currently only 'AgentAddress' is supported. +type ConnectionMonitorEndpointFilterItemType string + +const ( + ConnectionMonitorEndpointFilterItemTypeAgentAddress ConnectionMonitorEndpointFilterItemType = "AgentAddress" +) + +// PossibleConnectionMonitorEndpointFilterItemTypeValues returns the possible values for the ConnectionMonitorEndpointFilterItemType const type. +func PossibleConnectionMonitorEndpointFilterItemTypeValues() []ConnectionMonitorEndpointFilterItemType { + return []ConnectionMonitorEndpointFilterItemType{ + ConnectionMonitorEndpointFilterItemTypeAgentAddress, + } +} + +// ConnectionMonitorEndpointFilterType - The behavior of the endpoint filter. Currently only 'Include' is supported. +type ConnectionMonitorEndpointFilterType string + +const ( + ConnectionMonitorEndpointFilterTypeInclude ConnectionMonitorEndpointFilterType = "Include" +) + +// PossibleConnectionMonitorEndpointFilterTypeValues returns the possible values for the ConnectionMonitorEndpointFilterType const type. +func PossibleConnectionMonitorEndpointFilterTypeValues() []ConnectionMonitorEndpointFilterType { + return []ConnectionMonitorEndpointFilterType{ + ConnectionMonitorEndpointFilterTypeInclude, + } +} + +// ConnectionMonitorSourceStatus - Status of connection monitor source. +type ConnectionMonitorSourceStatus string + +const ( + ConnectionMonitorSourceStatusActive ConnectionMonitorSourceStatus = "Active" + ConnectionMonitorSourceStatusInactive ConnectionMonitorSourceStatus = "Inactive" + ConnectionMonitorSourceStatusUnknown ConnectionMonitorSourceStatus = "Unknown" +) + +// PossibleConnectionMonitorSourceStatusValues returns the possible values for the ConnectionMonitorSourceStatus const type. +func PossibleConnectionMonitorSourceStatusValues() []ConnectionMonitorSourceStatus { + return []ConnectionMonitorSourceStatus{ + ConnectionMonitorSourceStatusActive, + ConnectionMonitorSourceStatusInactive, + ConnectionMonitorSourceStatusUnknown, + } +} + +// ConnectionMonitorTestConfigurationProtocol - The protocol to use in test evaluation. +type ConnectionMonitorTestConfigurationProtocol string + +const ( + ConnectionMonitorTestConfigurationProtocolHTTP ConnectionMonitorTestConfigurationProtocol = "Http" + ConnectionMonitorTestConfigurationProtocolIcmp ConnectionMonitorTestConfigurationProtocol = "Icmp" + ConnectionMonitorTestConfigurationProtocolTCP ConnectionMonitorTestConfigurationProtocol = "Tcp" +) + +// PossibleConnectionMonitorTestConfigurationProtocolValues returns the possible values for the ConnectionMonitorTestConfigurationProtocol const type. +func PossibleConnectionMonitorTestConfigurationProtocolValues() []ConnectionMonitorTestConfigurationProtocol { + return []ConnectionMonitorTestConfigurationProtocol{ + ConnectionMonitorTestConfigurationProtocolHTTP, + ConnectionMonitorTestConfigurationProtocolIcmp, + ConnectionMonitorTestConfigurationProtocolTCP, + } +} + +// ConnectionMonitorType - Type of connection monitor. +type ConnectionMonitorType string + +const ( + ConnectionMonitorTypeMultiEndpoint ConnectionMonitorType = "MultiEndpoint" + ConnectionMonitorTypeSingleSourceDestination ConnectionMonitorType = "SingleSourceDestination" +) + +// PossibleConnectionMonitorTypeValues returns the possible values for the ConnectionMonitorType const type. +func PossibleConnectionMonitorTypeValues() []ConnectionMonitorType { + return []ConnectionMonitorType{ + ConnectionMonitorTypeMultiEndpoint, + ConnectionMonitorTypeSingleSourceDestination, + } +} + +// ConnectionState - The connection state. +type ConnectionState string + +const ( + ConnectionStateReachable ConnectionState = "Reachable" + ConnectionStateUnknown ConnectionState = "Unknown" + ConnectionStateUnreachable ConnectionState = "Unreachable" +) + +// PossibleConnectionStateValues returns the possible values for the ConnectionState const type. +func PossibleConnectionStateValues() []ConnectionState { + return []ConnectionState{ + ConnectionStateReachable, + ConnectionStateUnknown, + ConnectionStateUnreachable, + } +} + +// ConnectionStatus - The connection status. +type ConnectionStatus string + +const ( + ConnectionStatusConnected ConnectionStatus = "Connected" + ConnectionStatusDegraded ConnectionStatus = "Degraded" + ConnectionStatusDisconnected ConnectionStatus = "Disconnected" + ConnectionStatusUnknown ConnectionStatus = "Unknown" +) + +// PossibleConnectionStatusValues returns the possible values for the ConnectionStatus const type. +func PossibleConnectionStatusValues() []ConnectionStatus { + return []ConnectionStatus{ + ConnectionStatusConnected, + ConnectionStatusDegraded, + ConnectionStatusDisconnected, + ConnectionStatusUnknown, + } +} + +// ConnectivityTopology - Connectivity topology type. +type ConnectivityTopology string + +const ( + ConnectivityTopologyHubAndSpoke ConnectivityTopology = "HubAndSpoke" + ConnectivityTopologyMesh ConnectivityTopology = "Mesh" +) + +// PossibleConnectivityTopologyValues returns the possible values for the ConnectivityTopology const type. +func PossibleConnectivityTopologyValues() []ConnectivityTopology { + return []ConnectivityTopology{ + ConnectivityTopologyHubAndSpoke, + ConnectivityTopologyMesh, + } +} + +// CoverageLevel - Test coverage for the endpoint. +type CoverageLevel string + +const ( + CoverageLevelAboveAverage CoverageLevel = "AboveAverage" + CoverageLevelAverage CoverageLevel = "Average" + CoverageLevelBelowAverage CoverageLevel = "BelowAverage" + CoverageLevelDefault CoverageLevel = "Default" + CoverageLevelFull CoverageLevel = "Full" + CoverageLevelLow CoverageLevel = "Low" +) + +// PossibleCoverageLevelValues returns the possible values for the CoverageLevel const type. +func PossibleCoverageLevelValues() []CoverageLevel { + return []CoverageLevel{ + CoverageLevelAboveAverage, + CoverageLevelAverage, + CoverageLevelBelowAverage, + CoverageLevelDefault, + CoverageLevelFull, + CoverageLevelLow, + } +} + +// 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, + } +} + +// CustomIPPrefixType - Type of custom IP prefix. Should be Singular, Parent, or Child. +type CustomIPPrefixType string + +const ( + CustomIPPrefixTypeChild CustomIPPrefixType = "Child" + CustomIPPrefixTypeParent CustomIPPrefixType = "Parent" + CustomIPPrefixTypeSingular CustomIPPrefixType = "Singular" +) + +// PossibleCustomIPPrefixTypeValues returns the possible values for the CustomIPPrefixType const type. +func PossibleCustomIPPrefixTypeValues() []CustomIPPrefixType { + return []CustomIPPrefixType{ + CustomIPPrefixTypeChild, + CustomIPPrefixTypeParent, + CustomIPPrefixTypeSingular, + } +} + +// DdosSettingsProtectionMode - The DDoS protection mode of the public IP +type DdosSettingsProtectionMode string + +const ( + DdosSettingsProtectionModeDisabled DdosSettingsProtectionMode = "Disabled" + DdosSettingsProtectionModeEnabled DdosSettingsProtectionMode = "Enabled" + DdosSettingsProtectionModeVirtualNetworkInherited DdosSettingsProtectionMode = "VirtualNetworkInherited" +) + +// PossibleDdosSettingsProtectionModeValues returns the possible values for the DdosSettingsProtectionMode const type. +func PossibleDdosSettingsProtectionModeValues() []DdosSettingsProtectionMode { + return []DdosSettingsProtectionMode{ + DdosSettingsProtectionModeDisabled, + DdosSettingsProtectionModeEnabled, + DdosSettingsProtectionModeVirtualNetworkInherited, + } +} + +// DeleteExistingPeering - Flag if need to remove current existing peerings. +type DeleteExistingPeering string + +const ( + DeleteExistingPeeringFalse DeleteExistingPeering = "False" + DeleteExistingPeeringTrue DeleteExistingPeering = "True" +) + +// PossibleDeleteExistingPeeringValues returns the possible values for the DeleteExistingPeering const type. +func PossibleDeleteExistingPeeringValues() []DeleteExistingPeering { + return []DeleteExistingPeering{ + DeleteExistingPeeringFalse, + DeleteExistingPeeringTrue, + } +} + +// DeleteOptions - Specify what happens to the public IP address when the VM using it is deleted +type DeleteOptions string + +const ( + DeleteOptionsDelete DeleteOptions = "Delete" + DeleteOptionsDetach DeleteOptions = "Detach" +) + +// PossibleDeleteOptionsValues returns the possible values for the DeleteOptions const type. +func PossibleDeleteOptionsValues() []DeleteOptions { + return []DeleteOptions{ + DeleteOptionsDelete, + DeleteOptionsDetach, + } +} + +// DeploymentStatus - Deployment Status. +type DeploymentStatus string + +const ( + DeploymentStatusDeployed DeploymentStatus = "Deployed" + DeploymentStatusDeploying DeploymentStatus = "Deploying" + DeploymentStatusFailed DeploymentStatus = "Failed" + DeploymentStatusNotStarted DeploymentStatus = "NotStarted" +) + +// PossibleDeploymentStatusValues returns the possible values for the DeploymentStatus const type. +func PossibleDeploymentStatusValues() []DeploymentStatus { + return []DeploymentStatus{ + DeploymentStatusDeployed, + DeploymentStatusDeploying, + DeploymentStatusFailed, + DeploymentStatusNotStarted, + } +} + +// DestinationPortBehavior - Destination port behavior. +type DestinationPortBehavior string + +const ( + DestinationPortBehaviorListenIfAvailable DestinationPortBehavior = "ListenIfAvailable" + DestinationPortBehaviorNone DestinationPortBehavior = "None" +) + +// PossibleDestinationPortBehaviorValues returns the possible values for the DestinationPortBehavior const type. +func PossibleDestinationPortBehaviorValues() []DestinationPortBehavior { + return []DestinationPortBehavior{ + DestinationPortBehaviorListenIfAvailable, + DestinationPortBehaviorNone, + } +} + +// DhGroup - The DH Groups used in IKE Phase 1 for initial SA. +type DhGroup string + +const ( + DhGroupDHGroup1 DhGroup = "DHGroup1" + DhGroupDHGroup14 DhGroup = "DHGroup14" + DhGroupDHGroup2 DhGroup = "DHGroup2" + DhGroupDHGroup2048 DhGroup = "DHGroup2048" + DhGroupDHGroup24 DhGroup = "DHGroup24" + DhGroupECP256 DhGroup = "ECP256" + DhGroupECP384 DhGroup = "ECP384" + DhGroupNone DhGroup = "None" +) + +// PossibleDhGroupValues returns the possible values for the DhGroup const type. +func PossibleDhGroupValues() []DhGroup { + return []DhGroup{ + DhGroupDHGroup1, + DhGroupDHGroup14, + DhGroupDHGroup2, + DhGroupDHGroup2048, + DhGroupDHGroup24, + DhGroupECP256, + DhGroupECP384, + DhGroupNone, + } +} + +// Direction - The direction of the traffic. +type Direction string + +const ( + DirectionInbound Direction = "Inbound" + DirectionOutbound Direction = "Outbound" +) + +// PossibleDirectionValues returns the possible values for the Direction const type. +func PossibleDirectionValues() []Direction { + return []Direction{ + DirectionInbound, + DirectionOutbound, + } +} + +// EffectiveAdminRuleKind - Whether the rule is custom or default. +type EffectiveAdminRuleKind string + +const ( + EffectiveAdminRuleKindCustom EffectiveAdminRuleKind = "Custom" + EffectiveAdminRuleKindDefault EffectiveAdminRuleKind = "Default" +) + +// PossibleEffectiveAdminRuleKindValues returns the possible values for the EffectiveAdminRuleKind const type. +func PossibleEffectiveAdminRuleKindValues() []EffectiveAdminRuleKind { + return []EffectiveAdminRuleKind{ + EffectiveAdminRuleKindCustom, + EffectiveAdminRuleKindDefault, + } +} + +// EffectiveRouteSource - Who created the route. +type EffectiveRouteSource string + +const ( + EffectiveRouteSourceDefault EffectiveRouteSource = "Default" + EffectiveRouteSourceUnknown EffectiveRouteSource = "Unknown" + EffectiveRouteSourceUser EffectiveRouteSource = "User" + EffectiveRouteSourceVirtualNetworkGateway EffectiveRouteSource = "VirtualNetworkGateway" +) + +// PossibleEffectiveRouteSourceValues returns the possible values for the EffectiveRouteSource const type. +func PossibleEffectiveRouteSourceValues() []EffectiveRouteSource { + return []EffectiveRouteSource{ + EffectiveRouteSourceDefault, + EffectiveRouteSourceUnknown, + EffectiveRouteSourceUser, + EffectiveRouteSourceVirtualNetworkGateway, + } +} + +// EffectiveRouteState - The value of effective route. +type EffectiveRouteState string + +const ( + EffectiveRouteStateActive EffectiveRouteState = "Active" + EffectiveRouteStateInvalid EffectiveRouteState = "Invalid" +) + +// PossibleEffectiveRouteStateValues returns the possible values for the EffectiveRouteState const type. +func PossibleEffectiveRouteStateValues() []EffectiveRouteState { + return []EffectiveRouteState{ + EffectiveRouteStateActive, + EffectiveRouteStateInvalid, + } +} + +// EffectiveSecurityRuleProtocol - The network protocol this rule applies to. +type EffectiveSecurityRuleProtocol string + +const ( + EffectiveSecurityRuleProtocolAll EffectiveSecurityRuleProtocol = "All" + EffectiveSecurityRuleProtocolTCP EffectiveSecurityRuleProtocol = "Tcp" + EffectiveSecurityRuleProtocolUDP EffectiveSecurityRuleProtocol = "Udp" +) + +// PossibleEffectiveSecurityRuleProtocolValues returns the possible values for the EffectiveSecurityRuleProtocol const type. +func PossibleEffectiveSecurityRuleProtocolValues() []EffectiveSecurityRuleProtocol { + return []EffectiveSecurityRuleProtocol{ + EffectiveSecurityRuleProtocolAll, + EffectiveSecurityRuleProtocolTCP, + EffectiveSecurityRuleProtocolUDP, + } +} + +// EndpointType - The endpoint type. +type EndpointType string + +const ( + EndpointTypeAzureArcVM EndpointType = "AzureArcVM" + EndpointTypeAzureSubnet EndpointType = "AzureSubnet" + EndpointTypeAzureVM EndpointType = "AzureVM" + EndpointTypeAzureVMSS EndpointType = "AzureVMSS" + EndpointTypeAzureVNet EndpointType = "AzureVNet" + EndpointTypeExternalAddress EndpointType = "ExternalAddress" + EndpointTypeMMAWorkspaceMachine EndpointType = "MMAWorkspaceMachine" + EndpointTypeMMAWorkspaceNetwork EndpointType = "MMAWorkspaceNetwork" +) + +// PossibleEndpointTypeValues returns the possible values for the EndpointType const type. +func PossibleEndpointTypeValues() []EndpointType { + return []EndpointType{ + EndpointTypeAzureArcVM, + EndpointTypeAzureSubnet, + EndpointTypeAzureVM, + EndpointTypeAzureVMSS, + EndpointTypeAzureVNet, + EndpointTypeExternalAddress, + EndpointTypeMMAWorkspaceMachine, + EndpointTypeMMAWorkspaceNetwork, + } +} + +// EvaluationState - Connectivity analysis evaluation state. +type EvaluationState string + +const ( + EvaluationStateCompleted EvaluationState = "Completed" + EvaluationStateInProgress EvaluationState = "InProgress" + EvaluationStateNotStarted EvaluationState = "NotStarted" +) + +// PossibleEvaluationStateValues returns the possible values for the EvaluationState const type. +func PossibleEvaluationStateValues() []EvaluationState { + return []EvaluationState{ + EvaluationStateCompleted, + EvaluationStateInProgress, + EvaluationStateNotStarted, + } +} + +// ExpressRouteCircuitPeeringAdvertisedPublicPrefixState - The advertised public prefix state of the Peering resource. +type ExpressRouteCircuitPeeringAdvertisedPublicPrefixState string + +const ( + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateConfigured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configured" + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateConfiguring ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configuring" + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateNotConfigured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "NotConfigured" + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValidationNeeded ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "ValidationNeeded" +) + +// PossibleExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValues returns the possible values for the ExpressRouteCircuitPeeringAdvertisedPublicPrefixState const type. +func PossibleExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValues() []ExpressRouteCircuitPeeringAdvertisedPublicPrefixState { + return []ExpressRouteCircuitPeeringAdvertisedPublicPrefixState{ + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateConfigured, + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateConfiguring, + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateNotConfigured, + ExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValidationNeeded, + } +} + +// ExpressRouteCircuitPeeringState - The state of peering. +type ExpressRouteCircuitPeeringState string + +const ( + ExpressRouteCircuitPeeringStateDisabled ExpressRouteCircuitPeeringState = "Disabled" + ExpressRouteCircuitPeeringStateEnabled ExpressRouteCircuitPeeringState = "Enabled" +) + +// PossibleExpressRouteCircuitPeeringStateValues returns the possible values for the ExpressRouteCircuitPeeringState const type. +func PossibleExpressRouteCircuitPeeringStateValues() []ExpressRouteCircuitPeeringState { + return []ExpressRouteCircuitPeeringState{ + ExpressRouteCircuitPeeringStateDisabled, + ExpressRouteCircuitPeeringStateEnabled, + } +} + +// ExpressRouteCircuitSKUFamily - The family of the SKU. +type ExpressRouteCircuitSKUFamily string + +const ( + ExpressRouteCircuitSKUFamilyMeteredData ExpressRouteCircuitSKUFamily = "MeteredData" + ExpressRouteCircuitSKUFamilyUnlimitedData ExpressRouteCircuitSKUFamily = "UnlimitedData" +) + +// PossibleExpressRouteCircuitSKUFamilyValues returns the possible values for the ExpressRouteCircuitSKUFamily const type. +func PossibleExpressRouteCircuitSKUFamilyValues() []ExpressRouteCircuitSKUFamily { + return []ExpressRouteCircuitSKUFamily{ + ExpressRouteCircuitSKUFamilyMeteredData, + ExpressRouteCircuitSKUFamilyUnlimitedData, + } +} + +// ExpressRouteCircuitSKUTier - The tier of the SKU. +type ExpressRouteCircuitSKUTier string + +const ( + ExpressRouteCircuitSKUTierBasic ExpressRouteCircuitSKUTier = "Basic" + ExpressRouteCircuitSKUTierLocal ExpressRouteCircuitSKUTier = "Local" + ExpressRouteCircuitSKUTierPremium ExpressRouteCircuitSKUTier = "Premium" + ExpressRouteCircuitSKUTierStandard ExpressRouteCircuitSKUTier = "Standard" +) + +// PossibleExpressRouteCircuitSKUTierValues returns the possible values for the ExpressRouteCircuitSKUTier const type. +func PossibleExpressRouteCircuitSKUTierValues() []ExpressRouteCircuitSKUTier { + return []ExpressRouteCircuitSKUTier{ + ExpressRouteCircuitSKUTierBasic, + ExpressRouteCircuitSKUTierLocal, + ExpressRouteCircuitSKUTierPremium, + ExpressRouteCircuitSKUTierStandard, + } +} + +// ExpressRouteLinkAdminState - Administrative state of the physical port. +type ExpressRouteLinkAdminState string + +const ( + ExpressRouteLinkAdminStateDisabled ExpressRouteLinkAdminState = "Disabled" + ExpressRouteLinkAdminStateEnabled ExpressRouteLinkAdminState = "Enabled" +) + +// PossibleExpressRouteLinkAdminStateValues returns the possible values for the ExpressRouteLinkAdminState const type. +func PossibleExpressRouteLinkAdminStateValues() []ExpressRouteLinkAdminState { + return []ExpressRouteLinkAdminState{ + ExpressRouteLinkAdminStateDisabled, + ExpressRouteLinkAdminStateEnabled, + } +} + +// ExpressRouteLinkConnectorType - Physical fiber port type. +type ExpressRouteLinkConnectorType string + +const ( + ExpressRouteLinkConnectorTypeLC ExpressRouteLinkConnectorType = "LC" + ExpressRouteLinkConnectorTypeSC ExpressRouteLinkConnectorType = "SC" +) + +// PossibleExpressRouteLinkConnectorTypeValues returns the possible values for the ExpressRouteLinkConnectorType const type. +func PossibleExpressRouteLinkConnectorTypeValues() []ExpressRouteLinkConnectorType { + return []ExpressRouteLinkConnectorType{ + ExpressRouteLinkConnectorTypeLC, + ExpressRouteLinkConnectorTypeSC, + } +} + +// ExpressRouteLinkMacSecCipher - Mac security cipher. +type ExpressRouteLinkMacSecCipher string + +const ( + ExpressRouteLinkMacSecCipherGCMAES128 ExpressRouteLinkMacSecCipher = "GcmAes128" + ExpressRouteLinkMacSecCipherGCMAES256 ExpressRouteLinkMacSecCipher = "GcmAes256" + ExpressRouteLinkMacSecCipherGCMAesXpn128 ExpressRouteLinkMacSecCipher = "GcmAesXpn128" + ExpressRouteLinkMacSecCipherGCMAesXpn256 ExpressRouteLinkMacSecCipher = "GcmAesXpn256" +) + +// PossibleExpressRouteLinkMacSecCipherValues returns the possible values for the ExpressRouteLinkMacSecCipher const type. +func PossibleExpressRouteLinkMacSecCipherValues() []ExpressRouteLinkMacSecCipher { + return []ExpressRouteLinkMacSecCipher{ + ExpressRouteLinkMacSecCipherGCMAES128, + ExpressRouteLinkMacSecCipherGCMAES256, + ExpressRouteLinkMacSecCipherGCMAesXpn128, + ExpressRouteLinkMacSecCipherGCMAesXpn256, + } +} + +// ExpressRouteLinkMacSecSciState - Sci mode enabled/disabled. +type ExpressRouteLinkMacSecSciState string + +const ( + ExpressRouteLinkMacSecSciStateDisabled ExpressRouteLinkMacSecSciState = "Disabled" + ExpressRouteLinkMacSecSciStateEnabled ExpressRouteLinkMacSecSciState = "Enabled" +) + +// PossibleExpressRouteLinkMacSecSciStateValues returns the possible values for the ExpressRouteLinkMacSecSciState const type. +func PossibleExpressRouteLinkMacSecSciStateValues() []ExpressRouteLinkMacSecSciState { + return []ExpressRouteLinkMacSecSciState{ + ExpressRouteLinkMacSecSciStateDisabled, + ExpressRouteLinkMacSecSciStateEnabled, + } +} + +// ExpressRoutePeeringState - The state of peering. +type ExpressRoutePeeringState string + +const ( + ExpressRoutePeeringStateDisabled ExpressRoutePeeringState = "Disabled" + ExpressRoutePeeringStateEnabled ExpressRoutePeeringState = "Enabled" +) + +// PossibleExpressRoutePeeringStateValues returns the possible values for the ExpressRoutePeeringState const type. +func PossibleExpressRoutePeeringStateValues() []ExpressRoutePeeringState { + return []ExpressRoutePeeringState{ + ExpressRoutePeeringStateDisabled, + ExpressRoutePeeringStateEnabled, + } +} + +// ExpressRoutePeeringType - The peering type. +type ExpressRoutePeeringType string + +const ( + ExpressRoutePeeringTypeAzurePrivatePeering ExpressRoutePeeringType = "AzurePrivatePeering" + ExpressRoutePeeringTypeAzurePublicPeering ExpressRoutePeeringType = "AzurePublicPeering" + ExpressRoutePeeringTypeMicrosoftPeering ExpressRoutePeeringType = "MicrosoftPeering" +) + +// PossibleExpressRoutePeeringTypeValues returns the possible values for the ExpressRoutePeeringType const type. +func PossibleExpressRoutePeeringTypeValues() []ExpressRoutePeeringType { + return []ExpressRoutePeeringType{ + ExpressRoutePeeringTypeAzurePrivatePeering, + ExpressRoutePeeringTypeAzurePublicPeering, + ExpressRoutePeeringTypeMicrosoftPeering, + } +} + +// ExpressRoutePortAuthorizationUseStatus - The authorization use status. +type ExpressRoutePortAuthorizationUseStatus string + +const ( + ExpressRoutePortAuthorizationUseStatusAvailable ExpressRoutePortAuthorizationUseStatus = "Available" + ExpressRoutePortAuthorizationUseStatusInUse ExpressRoutePortAuthorizationUseStatus = "InUse" +) + +// PossibleExpressRoutePortAuthorizationUseStatusValues returns the possible values for the ExpressRoutePortAuthorizationUseStatus const type. +func PossibleExpressRoutePortAuthorizationUseStatusValues() []ExpressRoutePortAuthorizationUseStatus { + return []ExpressRoutePortAuthorizationUseStatus{ + ExpressRoutePortAuthorizationUseStatusAvailable, + ExpressRoutePortAuthorizationUseStatusInUse, + } +} + +// ExpressRoutePortsBillingType - The billing type of the ExpressRoutePort resource. +type ExpressRoutePortsBillingType string + +const ( + ExpressRoutePortsBillingTypeMeteredData ExpressRoutePortsBillingType = "MeteredData" + ExpressRoutePortsBillingTypeUnlimitedData ExpressRoutePortsBillingType = "UnlimitedData" +) + +// PossibleExpressRoutePortsBillingTypeValues returns the possible values for the ExpressRoutePortsBillingType const type. +func PossibleExpressRoutePortsBillingTypeValues() []ExpressRoutePortsBillingType { + return []ExpressRoutePortsBillingType{ + ExpressRoutePortsBillingTypeMeteredData, + ExpressRoutePortsBillingTypeUnlimitedData, + } +} + +// ExpressRoutePortsEncapsulation - Encapsulation method on physical ports. +type ExpressRoutePortsEncapsulation string + +const ( + ExpressRoutePortsEncapsulationDot1Q ExpressRoutePortsEncapsulation = "Dot1Q" + ExpressRoutePortsEncapsulationQinQ ExpressRoutePortsEncapsulation = "QinQ" +) + +// PossibleExpressRoutePortsEncapsulationValues returns the possible values for the ExpressRoutePortsEncapsulation const type. +func PossibleExpressRoutePortsEncapsulationValues() []ExpressRoutePortsEncapsulation { + return []ExpressRoutePortsEncapsulation{ + ExpressRoutePortsEncapsulationDot1Q, + ExpressRoutePortsEncapsulationQinQ, + } +} + +// ExtendedLocationTypes - The supported ExtendedLocation types. Currently only EdgeZone is supported in Microsoft.Network +// resources. +type ExtendedLocationTypes string + +const ( + ExtendedLocationTypesEdgeZone ExtendedLocationTypes = "EdgeZone" +) + +// PossibleExtendedLocationTypesValues returns the possible values for the ExtendedLocationTypes const type. +func PossibleExtendedLocationTypesValues() []ExtendedLocationTypes { + return []ExtendedLocationTypes{ + ExtendedLocationTypesEdgeZone, + } +} + +// FirewallPolicyFilterRuleCollectionActionType - The action type of a rule. +type FirewallPolicyFilterRuleCollectionActionType string + +const ( + FirewallPolicyFilterRuleCollectionActionTypeAllow FirewallPolicyFilterRuleCollectionActionType = "Allow" + FirewallPolicyFilterRuleCollectionActionTypeDeny FirewallPolicyFilterRuleCollectionActionType = "Deny" +) + +// PossibleFirewallPolicyFilterRuleCollectionActionTypeValues returns the possible values for the FirewallPolicyFilterRuleCollectionActionType const type. +func PossibleFirewallPolicyFilterRuleCollectionActionTypeValues() []FirewallPolicyFilterRuleCollectionActionType { + return []FirewallPolicyFilterRuleCollectionActionType{ + FirewallPolicyFilterRuleCollectionActionTypeAllow, + FirewallPolicyFilterRuleCollectionActionTypeDeny, + } +} + +// FirewallPolicyIDPSQuerySortOrder - Describes if results should be in ascending/descending order +type FirewallPolicyIDPSQuerySortOrder string + +const ( + FirewallPolicyIDPSQuerySortOrderAscending FirewallPolicyIDPSQuerySortOrder = "Ascending" + FirewallPolicyIDPSQuerySortOrderDescending FirewallPolicyIDPSQuerySortOrder = "Descending" +) + +// PossibleFirewallPolicyIDPSQuerySortOrderValues returns the possible values for the FirewallPolicyIDPSQuerySortOrder const type. +func PossibleFirewallPolicyIDPSQuerySortOrderValues() []FirewallPolicyIDPSQuerySortOrder { + return []FirewallPolicyIDPSQuerySortOrder{ + FirewallPolicyIDPSQuerySortOrderAscending, + FirewallPolicyIDPSQuerySortOrderDescending, + } +} + +// FirewallPolicyIDPSSignatureDirection - Describes in which direction signature is being enforced: 0 - Inbound, 1 - OutBound, +// 2 - Bidirectional +type FirewallPolicyIDPSSignatureDirection int32 + +const ( + FirewallPolicyIDPSSignatureDirectionOne FirewallPolicyIDPSSignatureDirection = 1 + FirewallPolicyIDPSSignatureDirectionTwo FirewallPolicyIDPSSignatureDirection = 2 + FirewallPolicyIDPSSignatureDirectionZero FirewallPolicyIDPSSignatureDirection = 0 +) + +// PossibleFirewallPolicyIDPSSignatureDirectionValues returns the possible values for the FirewallPolicyIDPSSignatureDirection const type. +func PossibleFirewallPolicyIDPSSignatureDirectionValues() []FirewallPolicyIDPSSignatureDirection { + return []FirewallPolicyIDPSSignatureDirection{ + FirewallPolicyIDPSSignatureDirectionOne, + FirewallPolicyIDPSSignatureDirectionTwo, + FirewallPolicyIDPSSignatureDirectionZero, + } +} + +// FirewallPolicyIDPSSignatureMode - The current mode enforced, 0 - Disabled, 1 - Alert, 2 -Deny +type FirewallPolicyIDPSSignatureMode int32 + +const ( + FirewallPolicyIDPSSignatureModeOne FirewallPolicyIDPSSignatureMode = 1 + FirewallPolicyIDPSSignatureModeTwo FirewallPolicyIDPSSignatureMode = 2 + FirewallPolicyIDPSSignatureModeZero FirewallPolicyIDPSSignatureMode = 0 +) + +// PossibleFirewallPolicyIDPSSignatureModeValues returns the possible values for the FirewallPolicyIDPSSignatureMode const type. +func PossibleFirewallPolicyIDPSSignatureModeValues() []FirewallPolicyIDPSSignatureMode { + return []FirewallPolicyIDPSSignatureMode{ + FirewallPolicyIDPSSignatureModeOne, + FirewallPolicyIDPSSignatureModeTwo, + FirewallPolicyIDPSSignatureModeZero, + } +} + +// FirewallPolicyIDPSSignatureSeverity - Describes the severity of signature: 1 - Low, 2 - Medium, 3 - High +type FirewallPolicyIDPSSignatureSeverity int32 + +const ( + FirewallPolicyIDPSSignatureSeverityOne FirewallPolicyIDPSSignatureSeverity = 1 + FirewallPolicyIDPSSignatureSeverityThree FirewallPolicyIDPSSignatureSeverity = 3 + FirewallPolicyIDPSSignatureSeverityTwo FirewallPolicyIDPSSignatureSeverity = 2 +) + +// PossibleFirewallPolicyIDPSSignatureSeverityValues returns the possible values for the FirewallPolicyIDPSSignatureSeverity const type. +func PossibleFirewallPolicyIDPSSignatureSeverityValues() []FirewallPolicyIDPSSignatureSeverity { + return []FirewallPolicyIDPSSignatureSeverity{ + FirewallPolicyIDPSSignatureSeverityOne, + FirewallPolicyIDPSSignatureSeverityThree, + FirewallPolicyIDPSSignatureSeverityTwo, + } +} + +// FirewallPolicyIntrusionDetectionProtocol - Possible intrusion detection bypass traffic protocols. +type FirewallPolicyIntrusionDetectionProtocol string + +const ( + FirewallPolicyIntrusionDetectionProtocolANY FirewallPolicyIntrusionDetectionProtocol = "ANY" + FirewallPolicyIntrusionDetectionProtocolICMP FirewallPolicyIntrusionDetectionProtocol = "ICMP" + FirewallPolicyIntrusionDetectionProtocolTCP FirewallPolicyIntrusionDetectionProtocol = "TCP" + FirewallPolicyIntrusionDetectionProtocolUDP FirewallPolicyIntrusionDetectionProtocol = "UDP" +) + +// PossibleFirewallPolicyIntrusionDetectionProtocolValues returns the possible values for the FirewallPolicyIntrusionDetectionProtocol const type. +func PossibleFirewallPolicyIntrusionDetectionProtocolValues() []FirewallPolicyIntrusionDetectionProtocol { + return []FirewallPolicyIntrusionDetectionProtocol{ + FirewallPolicyIntrusionDetectionProtocolANY, + FirewallPolicyIntrusionDetectionProtocolICMP, + FirewallPolicyIntrusionDetectionProtocolTCP, + FirewallPolicyIntrusionDetectionProtocolUDP, + } +} + +// FirewallPolicyIntrusionDetectionStateType - Possible state values. +type FirewallPolicyIntrusionDetectionStateType string + +const ( + FirewallPolicyIntrusionDetectionStateTypeAlert FirewallPolicyIntrusionDetectionStateType = "Alert" + FirewallPolicyIntrusionDetectionStateTypeDeny FirewallPolicyIntrusionDetectionStateType = "Deny" + FirewallPolicyIntrusionDetectionStateTypeOff FirewallPolicyIntrusionDetectionStateType = "Off" +) + +// PossibleFirewallPolicyIntrusionDetectionStateTypeValues returns the possible values for the FirewallPolicyIntrusionDetectionStateType const type. +func PossibleFirewallPolicyIntrusionDetectionStateTypeValues() []FirewallPolicyIntrusionDetectionStateType { + return []FirewallPolicyIntrusionDetectionStateType{ + FirewallPolicyIntrusionDetectionStateTypeAlert, + FirewallPolicyIntrusionDetectionStateTypeDeny, + FirewallPolicyIntrusionDetectionStateTypeOff, + } +} + +// FirewallPolicyNatRuleCollectionActionType - The action type of a rule. +type FirewallPolicyNatRuleCollectionActionType string + +const ( + FirewallPolicyNatRuleCollectionActionTypeDNAT FirewallPolicyNatRuleCollectionActionType = "DNAT" +) + +// PossibleFirewallPolicyNatRuleCollectionActionTypeValues returns the possible values for the FirewallPolicyNatRuleCollectionActionType const type. +func PossibleFirewallPolicyNatRuleCollectionActionTypeValues() []FirewallPolicyNatRuleCollectionActionType { + return []FirewallPolicyNatRuleCollectionActionType{ + FirewallPolicyNatRuleCollectionActionTypeDNAT, + } +} + +// FirewallPolicyRuleApplicationProtocolType - The application protocol type of a Rule. +type FirewallPolicyRuleApplicationProtocolType string + +const ( + FirewallPolicyRuleApplicationProtocolTypeHTTP FirewallPolicyRuleApplicationProtocolType = "Http" + FirewallPolicyRuleApplicationProtocolTypeHTTPS FirewallPolicyRuleApplicationProtocolType = "Https" +) + +// PossibleFirewallPolicyRuleApplicationProtocolTypeValues returns the possible values for the FirewallPolicyRuleApplicationProtocolType const type. +func PossibleFirewallPolicyRuleApplicationProtocolTypeValues() []FirewallPolicyRuleApplicationProtocolType { + return []FirewallPolicyRuleApplicationProtocolType{ + FirewallPolicyRuleApplicationProtocolTypeHTTP, + FirewallPolicyRuleApplicationProtocolTypeHTTPS, + } +} + +// FirewallPolicyRuleCollectionType - The type of the rule collection. +type FirewallPolicyRuleCollectionType string + +const ( + FirewallPolicyRuleCollectionTypeFirewallPolicyFilterRuleCollection FirewallPolicyRuleCollectionType = "FirewallPolicyFilterRuleCollection" + FirewallPolicyRuleCollectionTypeFirewallPolicyNatRuleCollection FirewallPolicyRuleCollectionType = "FirewallPolicyNatRuleCollection" +) + +// PossibleFirewallPolicyRuleCollectionTypeValues returns the possible values for the FirewallPolicyRuleCollectionType const type. +func PossibleFirewallPolicyRuleCollectionTypeValues() []FirewallPolicyRuleCollectionType { + return []FirewallPolicyRuleCollectionType{ + FirewallPolicyRuleCollectionTypeFirewallPolicyFilterRuleCollection, + FirewallPolicyRuleCollectionTypeFirewallPolicyNatRuleCollection, + } +} + +// FirewallPolicyRuleNetworkProtocol - The Network protocol of a Rule. +type FirewallPolicyRuleNetworkProtocol string + +const ( + FirewallPolicyRuleNetworkProtocolAny FirewallPolicyRuleNetworkProtocol = "Any" + FirewallPolicyRuleNetworkProtocolICMP FirewallPolicyRuleNetworkProtocol = "ICMP" + FirewallPolicyRuleNetworkProtocolTCP FirewallPolicyRuleNetworkProtocol = "TCP" + FirewallPolicyRuleNetworkProtocolUDP FirewallPolicyRuleNetworkProtocol = "UDP" +) + +// PossibleFirewallPolicyRuleNetworkProtocolValues returns the possible values for the FirewallPolicyRuleNetworkProtocol const type. +func PossibleFirewallPolicyRuleNetworkProtocolValues() []FirewallPolicyRuleNetworkProtocol { + return []FirewallPolicyRuleNetworkProtocol{ + FirewallPolicyRuleNetworkProtocolAny, + FirewallPolicyRuleNetworkProtocolICMP, + FirewallPolicyRuleNetworkProtocolTCP, + FirewallPolicyRuleNetworkProtocolUDP, + } +} + +// FirewallPolicyRuleType - Rule Type. +type FirewallPolicyRuleType string + +const ( + FirewallPolicyRuleTypeApplicationRule FirewallPolicyRuleType = "ApplicationRule" + FirewallPolicyRuleTypeNatRule FirewallPolicyRuleType = "NatRule" + FirewallPolicyRuleTypeNetworkRule FirewallPolicyRuleType = "NetworkRule" +) + +// PossibleFirewallPolicyRuleTypeValues returns the possible values for the FirewallPolicyRuleType const type. +func PossibleFirewallPolicyRuleTypeValues() []FirewallPolicyRuleType { + return []FirewallPolicyRuleType{ + FirewallPolicyRuleTypeApplicationRule, + FirewallPolicyRuleTypeNatRule, + FirewallPolicyRuleTypeNetworkRule, + } +} + +// FirewallPolicySKUTier - Tier of Firewall Policy. +type FirewallPolicySKUTier string + +const ( + FirewallPolicySKUTierBasic FirewallPolicySKUTier = "Basic" + FirewallPolicySKUTierPremium FirewallPolicySKUTier = "Premium" + FirewallPolicySKUTierStandard FirewallPolicySKUTier = "Standard" +) + +// PossibleFirewallPolicySKUTierValues returns the possible values for the FirewallPolicySKUTier const type. +func PossibleFirewallPolicySKUTierValues() []FirewallPolicySKUTier { + return []FirewallPolicySKUTier{ + FirewallPolicySKUTierBasic, + FirewallPolicySKUTierPremium, + FirewallPolicySKUTierStandard, + } +} + +// FlowLogFormatType - The file type of flow log. +type FlowLogFormatType string + +const ( + FlowLogFormatTypeJSON FlowLogFormatType = "JSON" +) + +// PossibleFlowLogFormatTypeValues returns the possible values for the FlowLogFormatType const type. +func PossibleFlowLogFormatTypeValues() []FlowLogFormatType { + return []FlowLogFormatType{ + FlowLogFormatTypeJSON, + } +} + +// GatewayLoadBalancerTunnelInterfaceType - Traffic type of gateway load balancer tunnel interface. +type GatewayLoadBalancerTunnelInterfaceType string + +const ( + GatewayLoadBalancerTunnelInterfaceTypeExternal GatewayLoadBalancerTunnelInterfaceType = "External" + GatewayLoadBalancerTunnelInterfaceTypeInternal GatewayLoadBalancerTunnelInterfaceType = "Internal" + GatewayLoadBalancerTunnelInterfaceTypeNone GatewayLoadBalancerTunnelInterfaceType = "None" +) + +// PossibleGatewayLoadBalancerTunnelInterfaceTypeValues returns the possible values for the GatewayLoadBalancerTunnelInterfaceType const type. +func PossibleGatewayLoadBalancerTunnelInterfaceTypeValues() []GatewayLoadBalancerTunnelInterfaceType { + return []GatewayLoadBalancerTunnelInterfaceType{ + GatewayLoadBalancerTunnelInterfaceTypeExternal, + GatewayLoadBalancerTunnelInterfaceTypeInternal, + GatewayLoadBalancerTunnelInterfaceTypeNone, + } +} + +// GatewayLoadBalancerTunnelProtocol - Protocol of gateway load balancer tunnel interface. +type GatewayLoadBalancerTunnelProtocol string + +const ( + GatewayLoadBalancerTunnelProtocolNative GatewayLoadBalancerTunnelProtocol = "Native" + GatewayLoadBalancerTunnelProtocolNone GatewayLoadBalancerTunnelProtocol = "None" + GatewayLoadBalancerTunnelProtocolVXLAN GatewayLoadBalancerTunnelProtocol = "VXLAN" +) + +// PossibleGatewayLoadBalancerTunnelProtocolValues returns the possible values for the GatewayLoadBalancerTunnelProtocol const type. +func PossibleGatewayLoadBalancerTunnelProtocolValues() []GatewayLoadBalancerTunnelProtocol { + return []GatewayLoadBalancerTunnelProtocol{ + GatewayLoadBalancerTunnelProtocolNative, + GatewayLoadBalancerTunnelProtocolNone, + GatewayLoadBalancerTunnelProtocolVXLAN, + } +} + +// Geo - The Geo for CIDR advertising. Should be an Geo code. +type Geo string + +const ( + GeoAFRI Geo = "AFRI" + GeoAPAC Geo = "APAC" + GeoAQ Geo = "AQ" + GeoEURO Geo = "EURO" + GeoGLOBAL Geo = "GLOBAL" + GeoLATAM Geo = "LATAM" + GeoME Geo = "ME" + GeoNAM Geo = "NAM" + GeoOCEANIA Geo = "OCEANIA" +) + +// PossibleGeoValues returns the possible values for the Geo const type. +func PossibleGeoValues() []Geo { + return []Geo{ + GeoAFRI, + GeoAPAC, + GeoAQ, + GeoEURO, + GeoGLOBAL, + GeoLATAM, + GeoME, + GeoNAM, + GeoOCEANIA, + } +} + +// GroupConnectivity - Group connectivity type. +type GroupConnectivity string + +const ( + GroupConnectivityDirectlyConnected GroupConnectivity = "DirectlyConnected" + GroupConnectivityNone GroupConnectivity = "None" +) + +// PossibleGroupConnectivityValues returns the possible values for the GroupConnectivity const type. +func PossibleGroupConnectivityValues() []GroupConnectivity { + return []GroupConnectivity{ + GroupConnectivityDirectlyConnected, + GroupConnectivityNone, + } +} + +// HTTPConfigurationMethod - The HTTP method to use. +type HTTPConfigurationMethod string + +const ( + HTTPConfigurationMethodGet HTTPConfigurationMethod = "Get" + HTTPConfigurationMethodPost HTTPConfigurationMethod = "Post" +) + +// PossibleHTTPConfigurationMethodValues returns the possible values for the HTTPConfigurationMethod const type. +func PossibleHTTPConfigurationMethodValues() []HTTPConfigurationMethod { + return []HTTPConfigurationMethod{ + HTTPConfigurationMethodGet, + HTTPConfigurationMethodPost, + } +} + +// HTTPMethod - HTTP method. +type HTTPMethod string + +const ( + HTTPMethodGet HTTPMethod = "Get" +) + +// PossibleHTTPMethodValues returns the possible values for the HTTPMethod const type. +func PossibleHTTPMethodValues() []HTTPMethod { + return []HTTPMethod{ + HTTPMethodGet, + } +} + +// HubBgpConnectionStatus - The current state of the VirtualHub to Peer. +type HubBgpConnectionStatus string + +const ( + HubBgpConnectionStatusConnected HubBgpConnectionStatus = "Connected" + HubBgpConnectionStatusConnecting HubBgpConnectionStatus = "Connecting" + HubBgpConnectionStatusNotConnected HubBgpConnectionStatus = "NotConnected" + HubBgpConnectionStatusUnknown HubBgpConnectionStatus = "Unknown" +) + +// PossibleHubBgpConnectionStatusValues returns the possible values for the HubBgpConnectionStatus const type. +func PossibleHubBgpConnectionStatusValues() []HubBgpConnectionStatus { + return []HubBgpConnectionStatus{ + HubBgpConnectionStatusConnected, + HubBgpConnectionStatusConnecting, + HubBgpConnectionStatusNotConnected, + HubBgpConnectionStatusUnknown, + } +} + +// HubRoutingPreference - The hub routing preference gateway types +type HubRoutingPreference string + +const ( + HubRoutingPreferenceASPath HubRoutingPreference = "ASPath" + HubRoutingPreferenceExpressRoute HubRoutingPreference = "ExpressRoute" + HubRoutingPreferenceVPNGateway HubRoutingPreference = "VpnGateway" +) + +// PossibleHubRoutingPreferenceValues returns the possible values for the HubRoutingPreference const type. +func PossibleHubRoutingPreferenceValues() []HubRoutingPreference { + return []HubRoutingPreference{ + HubRoutingPreferenceASPath, + HubRoutingPreferenceExpressRoute, + HubRoutingPreferenceVPNGateway, + } +} + +// HubVirtualNetworkConnectionStatus - The current state of the VirtualHub to vnet connection. +type HubVirtualNetworkConnectionStatus string + +const ( + HubVirtualNetworkConnectionStatusConnected HubVirtualNetworkConnectionStatus = "Connected" + HubVirtualNetworkConnectionStatusConnecting HubVirtualNetworkConnectionStatus = "Connecting" + HubVirtualNetworkConnectionStatusNotConnected HubVirtualNetworkConnectionStatus = "NotConnected" + HubVirtualNetworkConnectionStatusUnknown HubVirtualNetworkConnectionStatus = "Unknown" +) + +// PossibleHubVirtualNetworkConnectionStatusValues returns the possible values for the HubVirtualNetworkConnectionStatus const type. +func PossibleHubVirtualNetworkConnectionStatusValues() []HubVirtualNetworkConnectionStatus { + return []HubVirtualNetworkConnectionStatus{ + HubVirtualNetworkConnectionStatusConnected, + HubVirtualNetworkConnectionStatusConnecting, + HubVirtualNetworkConnectionStatusNotConnected, + HubVirtualNetworkConnectionStatusUnknown, + } +} + +// IPAllocationMethod - IP address allocation method. +type IPAllocationMethod string + +const ( + IPAllocationMethodDynamic IPAllocationMethod = "Dynamic" + IPAllocationMethodStatic IPAllocationMethod = "Static" +) + +// PossibleIPAllocationMethodValues returns the possible values for the IPAllocationMethod const type. +func PossibleIPAllocationMethodValues() []IPAllocationMethod { + return []IPAllocationMethod{ + IPAllocationMethodDynamic, + IPAllocationMethodStatic, + } +} + +// IPAllocationType - IpAllocation type. +type IPAllocationType string + +const ( + IPAllocationTypeHypernet IPAllocationType = "Hypernet" + IPAllocationTypeUndefined IPAllocationType = "Undefined" +) + +// PossibleIPAllocationTypeValues returns the possible values for the IPAllocationType const type. +func PossibleIPAllocationTypeValues() []IPAllocationType { + return []IPAllocationType{ + IPAllocationTypeHypernet, + IPAllocationTypeUndefined, + } +} + +// IPFlowProtocol - Protocol to be verified on. +type IPFlowProtocol string + +const ( + IPFlowProtocolTCP IPFlowProtocol = "TCP" + IPFlowProtocolUDP IPFlowProtocol = "UDP" +) + +// PossibleIPFlowProtocolValues returns the possible values for the IPFlowProtocol const type. +func PossibleIPFlowProtocolValues() []IPFlowProtocol { + return []IPFlowProtocol{ + IPFlowProtocolTCP, + IPFlowProtocolUDP, + } +} + +// IPSecEncryption - The IPSec encryption algorithm (IKE phase 1). +type IPSecEncryption string + +const ( + IPSecEncryptionAES128 IPSecEncryption = "AES128" + IPSecEncryptionAES192 IPSecEncryption = "AES192" + IPSecEncryptionAES256 IPSecEncryption = "AES256" + IPSecEncryptionDES IPSecEncryption = "DES" + IPSecEncryptionDES3 IPSecEncryption = "DES3" + IPSecEncryptionGCMAES128 IPSecEncryption = "GCMAES128" + IPSecEncryptionGCMAES192 IPSecEncryption = "GCMAES192" + IPSecEncryptionGCMAES256 IPSecEncryption = "GCMAES256" + IPSecEncryptionNone IPSecEncryption = "None" +) + +// PossibleIPSecEncryptionValues returns the possible values for the IPSecEncryption const type. +func PossibleIPSecEncryptionValues() []IPSecEncryption { + return []IPSecEncryption{ + IPSecEncryptionAES128, + IPSecEncryptionAES192, + IPSecEncryptionAES256, + IPSecEncryptionDES, + IPSecEncryptionDES3, + IPSecEncryptionGCMAES128, + IPSecEncryptionGCMAES192, + IPSecEncryptionGCMAES256, + IPSecEncryptionNone, + } +} + +// IPSecIntegrity - The IPSec integrity algorithm (IKE phase 1). +type IPSecIntegrity string + +const ( + IPSecIntegrityGCMAES128 IPSecIntegrity = "GCMAES128" + IPSecIntegrityGCMAES192 IPSecIntegrity = "GCMAES192" + IPSecIntegrityGCMAES256 IPSecIntegrity = "GCMAES256" + IPSecIntegrityMD5 IPSecIntegrity = "MD5" + IPSecIntegritySHA1 IPSecIntegrity = "SHA1" + IPSecIntegritySHA256 IPSecIntegrity = "SHA256" +) + +// PossibleIPSecIntegrityValues returns the possible values for the IPSecIntegrity const type. +func PossibleIPSecIntegrityValues() []IPSecIntegrity { + return []IPSecIntegrity{ + IPSecIntegrityGCMAES128, + IPSecIntegrityGCMAES192, + IPSecIntegrityGCMAES256, + IPSecIntegrityMD5, + IPSecIntegritySHA1, + IPSecIntegritySHA256, + } +} + +// IPVersion - IP address version. +type IPVersion string + +const ( + IPVersionIPv4 IPVersion = "IPv4" + IPVersionIPv6 IPVersion = "IPv6" +) + +// PossibleIPVersionValues returns the possible values for the IPVersion const type. +func PossibleIPVersionValues() []IPVersion { + return []IPVersion{ + IPVersionIPv4, + IPVersionIPv6, + } +} + +// IkeEncryption - The IKE encryption algorithm (IKE phase 2). +type IkeEncryption string + +const ( + IkeEncryptionAES128 IkeEncryption = "AES128" + IkeEncryptionAES192 IkeEncryption = "AES192" + IkeEncryptionAES256 IkeEncryption = "AES256" + IkeEncryptionDES IkeEncryption = "DES" + IkeEncryptionDES3 IkeEncryption = "DES3" + IkeEncryptionGCMAES128 IkeEncryption = "GCMAES128" + IkeEncryptionGCMAES256 IkeEncryption = "GCMAES256" +) + +// PossibleIkeEncryptionValues returns the possible values for the IkeEncryption const type. +func PossibleIkeEncryptionValues() []IkeEncryption { + return []IkeEncryption{ + IkeEncryptionAES128, + IkeEncryptionAES192, + IkeEncryptionAES256, + IkeEncryptionDES, + IkeEncryptionDES3, + IkeEncryptionGCMAES128, + IkeEncryptionGCMAES256, + } +} + +// IkeIntegrity - The IKE integrity algorithm (IKE phase 2). +type IkeIntegrity string + +const ( + IkeIntegrityGCMAES128 IkeIntegrity = "GCMAES128" + IkeIntegrityGCMAES256 IkeIntegrity = "GCMAES256" + IkeIntegrityMD5 IkeIntegrity = "MD5" + IkeIntegritySHA1 IkeIntegrity = "SHA1" + IkeIntegritySHA256 IkeIntegrity = "SHA256" + IkeIntegritySHA384 IkeIntegrity = "SHA384" +) + +// PossibleIkeIntegrityValues returns the possible values for the IkeIntegrity const type. +func PossibleIkeIntegrityValues() []IkeIntegrity { + return []IkeIntegrity{ + IkeIntegrityGCMAES128, + IkeIntegrityGCMAES256, + IkeIntegrityMD5, + IkeIntegritySHA1, + IkeIntegritySHA256, + IkeIntegritySHA384, + } +} + +// InboundSecurityRulesProtocol - Protocol. This should be either TCP or UDP. +type InboundSecurityRulesProtocol string + +const ( + InboundSecurityRulesProtocolTCP InboundSecurityRulesProtocol = "TCP" + InboundSecurityRulesProtocolUDP InboundSecurityRulesProtocol = "UDP" +) + +// PossibleInboundSecurityRulesProtocolValues returns the possible values for the InboundSecurityRulesProtocol const type. +func PossibleInboundSecurityRulesProtocolValues() []InboundSecurityRulesProtocol { + return []InboundSecurityRulesProtocol{ + InboundSecurityRulesProtocolTCP, + InboundSecurityRulesProtocolUDP, + } +} + +// IsGlobal - Flag if global mesh is supported. +type IsGlobal string + +const ( + IsGlobalFalse IsGlobal = "False" + IsGlobalTrue IsGlobal = "True" +) + +// PossibleIsGlobalValues returns the possible values for the IsGlobal const type. +func PossibleIsGlobalValues() []IsGlobal { + return []IsGlobal{ + IsGlobalFalse, + IsGlobalTrue, + } +} + +// IsWorkloadProtected - Value indicating whether the IP address is DDoS workload protected or not. +type IsWorkloadProtected string + +const ( + IsWorkloadProtectedFalse IsWorkloadProtected = "False" + IsWorkloadProtectedTrue IsWorkloadProtected = "True" +) + +// PossibleIsWorkloadProtectedValues returns the possible values for the IsWorkloadProtected const type. +func PossibleIsWorkloadProtectedValues() []IsWorkloadProtected { + return []IsWorkloadProtected{ + IsWorkloadProtectedFalse, + IsWorkloadProtectedTrue, + } +} + +// IssueType - The type of issue. +type IssueType string + +const ( + IssueTypeAgentStopped IssueType = "AgentStopped" + IssueTypeDNSResolution IssueType = "DnsResolution" + IssueTypeGuestFirewall IssueType = "GuestFirewall" + IssueTypeNetworkSecurityRule IssueType = "NetworkSecurityRule" + IssueTypePlatform IssueType = "Platform" + IssueTypePortThrottled IssueType = "PortThrottled" + IssueTypeSocketBind IssueType = "SocketBind" + IssueTypeUnknown IssueType = "Unknown" + IssueTypeUserDefinedRoute IssueType = "UserDefinedRoute" +) + +// PossibleIssueTypeValues returns the possible values for the IssueType const type. +func PossibleIssueTypeValues() []IssueType { + return []IssueType{ + IssueTypeAgentStopped, + IssueTypeDNSResolution, + IssueTypeGuestFirewall, + IssueTypeNetworkSecurityRule, + IssueTypePlatform, + IssueTypePortThrottled, + IssueTypeSocketBind, + IssueTypeUnknown, + IssueTypeUserDefinedRoute, + } +} + +// LoadBalancerBackendAddressAdminState - A list of administrative states which once set can override health probe so that +// Load Balancer will always forward new connections to backend, or deny new connections and reset existing connections. +type LoadBalancerBackendAddressAdminState string + +const ( + LoadBalancerBackendAddressAdminStateDown LoadBalancerBackendAddressAdminState = "Down" + LoadBalancerBackendAddressAdminStateNone LoadBalancerBackendAddressAdminState = "None" + LoadBalancerBackendAddressAdminStateUp LoadBalancerBackendAddressAdminState = "Up" +) + +// PossibleLoadBalancerBackendAddressAdminStateValues returns the possible values for the LoadBalancerBackendAddressAdminState const type. +func PossibleLoadBalancerBackendAddressAdminStateValues() []LoadBalancerBackendAddressAdminState { + return []LoadBalancerBackendAddressAdminState{ + LoadBalancerBackendAddressAdminStateDown, + LoadBalancerBackendAddressAdminStateNone, + LoadBalancerBackendAddressAdminStateUp, + } +} + +// LoadBalancerOutboundRuleProtocol - The protocol for the outbound rule in load balancer. +type LoadBalancerOutboundRuleProtocol string + +const ( + LoadBalancerOutboundRuleProtocolAll LoadBalancerOutboundRuleProtocol = "All" + LoadBalancerOutboundRuleProtocolTCP LoadBalancerOutboundRuleProtocol = "Tcp" + LoadBalancerOutboundRuleProtocolUDP LoadBalancerOutboundRuleProtocol = "Udp" +) + +// PossibleLoadBalancerOutboundRuleProtocolValues returns the possible values for the LoadBalancerOutboundRuleProtocol const type. +func PossibleLoadBalancerOutboundRuleProtocolValues() []LoadBalancerOutboundRuleProtocol { + return []LoadBalancerOutboundRuleProtocol{ + LoadBalancerOutboundRuleProtocolAll, + LoadBalancerOutboundRuleProtocolTCP, + LoadBalancerOutboundRuleProtocolUDP, + } +} + +// LoadBalancerSKUName - Name of a load balancer SKU. +type LoadBalancerSKUName string + +const ( + LoadBalancerSKUNameBasic LoadBalancerSKUName = "Basic" + LoadBalancerSKUNameGateway LoadBalancerSKUName = "Gateway" + LoadBalancerSKUNameStandard LoadBalancerSKUName = "Standard" +) + +// PossibleLoadBalancerSKUNameValues returns the possible values for the LoadBalancerSKUName const type. +func PossibleLoadBalancerSKUNameValues() []LoadBalancerSKUName { + return []LoadBalancerSKUName{ + LoadBalancerSKUNameBasic, + LoadBalancerSKUNameGateway, + LoadBalancerSKUNameStandard, + } +} + +// LoadBalancerSKUTier - Tier of a load balancer SKU. +type LoadBalancerSKUTier string + +const ( + LoadBalancerSKUTierGlobal LoadBalancerSKUTier = "Global" + LoadBalancerSKUTierRegional LoadBalancerSKUTier = "Regional" +) + +// PossibleLoadBalancerSKUTierValues returns the possible values for the LoadBalancerSKUTier const type. +func PossibleLoadBalancerSKUTierValues() []LoadBalancerSKUTier { + return []LoadBalancerSKUTier{ + LoadBalancerSKUTierGlobal, + LoadBalancerSKUTierRegional, + } +} + +// LoadDistribution - The load distribution policy for this rule. +type LoadDistribution string + +const ( + LoadDistributionDefault LoadDistribution = "Default" + LoadDistributionSourceIP LoadDistribution = "SourceIP" + LoadDistributionSourceIPProtocol LoadDistribution = "SourceIPProtocol" +) + +// PossibleLoadDistributionValues returns the possible values for the LoadDistribution const type. +func PossibleLoadDistributionValues() []LoadDistribution { + return []LoadDistribution{ + LoadDistributionDefault, + LoadDistributionSourceIP, + LoadDistributionSourceIPProtocol, + } +} + +// ManagedRuleEnabledState - The state of the managed rule. Defaults to Disabled if not specified. +type ManagedRuleEnabledState string + +const ( + ManagedRuleEnabledStateDisabled ManagedRuleEnabledState = "Disabled" + ManagedRuleEnabledStateEnabled ManagedRuleEnabledState = "Enabled" +) + +// PossibleManagedRuleEnabledStateValues returns the possible values for the ManagedRuleEnabledState const type. +func PossibleManagedRuleEnabledStateValues() []ManagedRuleEnabledState { + return []ManagedRuleEnabledState{ + ManagedRuleEnabledStateDisabled, + ManagedRuleEnabledStateEnabled, + } +} + +// NatGatewaySKUName - Name of Nat Gateway SKU. +type NatGatewaySKUName string + +const ( + NatGatewaySKUNameStandard NatGatewaySKUName = "Standard" +) + +// PossibleNatGatewaySKUNameValues returns the possible values for the NatGatewaySKUName const type. +func PossibleNatGatewaySKUNameValues() []NatGatewaySKUName { + return []NatGatewaySKUName{ + NatGatewaySKUNameStandard, + } +} + +// NetworkIntentPolicyBasedService - Network intent policy based services. +type NetworkIntentPolicyBasedService string + +const ( + NetworkIntentPolicyBasedServiceAll NetworkIntentPolicyBasedService = "All" + NetworkIntentPolicyBasedServiceAllowRulesOnly NetworkIntentPolicyBasedService = "AllowRulesOnly" + NetworkIntentPolicyBasedServiceNone NetworkIntentPolicyBasedService = "None" +) + +// PossibleNetworkIntentPolicyBasedServiceValues returns the possible values for the NetworkIntentPolicyBasedService const type. +func PossibleNetworkIntentPolicyBasedServiceValues() []NetworkIntentPolicyBasedService { + return []NetworkIntentPolicyBasedService{ + NetworkIntentPolicyBasedServiceAll, + NetworkIntentPolicyBasedServiceAllowRulesOnly, + NetworkIntentPolicyBasedServiceNone, + } +} + +// NetworkInterfaceAuxiliaryMode - Auxiliary mode of Network Interface resource. +type NetworkInterfaceAuxiliaryMode string + +const ( + NetworkInterfaceAuxiliaryModeAcceleratedConnections NetworkInterfaceAuxiliaryMode = "AcceleratedConnections" + NetworkInterfaceAuxiliaryModeFloating NetworkInterfaceAuxiliaryMode = "Floating" + NetworkInterfaceAuxiliaryModeMaxConnections NetworkInterfaceAuxiliaryMode = "MaxConnections" + NetworkInterfaceAuxiliaryModeNone NetworkInterfaceAuxiliaryMode = "None" +) + +// PossibleNetworkInterfaceAuxiliaryModeValues returns the possible values for the NetworkInterfaceAuxiliaryMode const type. +func PossibleNetworkInterfaceAuxiliaryModeValues() []NetworkInterfaceAuxiliaryMode { + return []NetworkInterfaceAuxiliaryMode{ + NetworkInterfaceAuxiliaryModeAcceleratedConnections, + NetworkInterfaceAuxiliaryModeFloating, + NetworkInterfaceAuxiliaryModeMaxConnections, + NetworkInterfaceAuxiliaryModeNone, + } +} + +// NetworkInterfaceAuxiliarySKU - Auxiliary sku of Network Interface resource. +type NetworkInterfaceAuxiliarySKU string + +const ( + NetworkInterfaceAuxiliarySKUA1 NetworkInterfaceAuxiliarySKU = "A1" + NetworkInterfaceAuxiliarySKUA2 NetworkInterfaceAuxiliarySKU = "A2" + NetworkInterfaceAuxiliarySKUA4 NetworkInterfaceAuxiliarySKU = "A4" + NetworkInterfaceAuxiliarySKUA8 NetworkInterfaceAuxiliarySKU = "A8" + NetworkInterfaceAuxiliarySKUNone NetworkInterfaceAuxiliarySKU = "None" +) + +// PossibleNetworkInterfaceAuxiliarySKUValues returns the possible values for the NetworkInterfaceAuxiliarySKU const type. +func PossibleNetworkInterfaceAuxiliarySKUValues() []NetworkInterfaceAuxiliarySKU { + return []NetworkInterfaceAuxiliarySKU{ + NetworkInterfaceAuxiliarySKUA1, + NetworkInterfaceAuxiliarySKUA2, + NetworkInterfaceAuxiliarySKUA4, + NetworkInterfaceAuxiliarySKUA8, + NetworkInterfaceAuxiliarySKUNone, + } +} + +// NetworkInterfaceMigrationPhase - Migration phase of Network Interface resource. +type NetworkInterfaceMigrationPhase string + +const ( + NetworkInterfaceMigrationPhaseAbort NetworkInterfaceMigrationPhase = "Abort" + NetworkInterfaceMigrationPhaseCommit NetworkInterfaceMigrationPhase = "Commit" + NetworkInterfaceMigrationPhaseCommitted NetworkInterfaceMigrationPhase = "Committed" + NetworkInterfaceMigrationPhaseNone NetworkInterfaceMigrationPhase = "None" + NetworkInterfaceMigrationPhasePrepare NetworkInterfaceMigrationPhase = "Prepare" +) + +// PossibleNetworkInterfaceMigrationPhaseValues returns the possible values for the NetworkInterfaceMigrationPhase const type. +func PossibleNetworkInterfaceMigrationPhaseValues() []NetworkInterfaceMigrationPhase { + return []NetworkInterfaceMigrationPhase{ + NetworkInterfaceMigrationPhaseAbort, + NetworkInterfaceMigrationPhaseCommit, + NetworkInterfaceMigrationPhaseCommitted, + NetworkInterfaceMigrationPhaseNone, + NetworkInterfaceMigrationPhasePrepare, + } +} + +// NetworkInterfaceNicType - Type of Network Interface resource. +type NetworkInterfaceNicType string + +const ( + NetworkInterfaceNicTypeElastic NetworkInterfaceNicType = "Elastic" + NetworkInterfaceNicTypeStandard NetworkInterfaceNicType = "Standard" +) + +// PossibleNetworkInterfaceNicTypeValues returns the possible values for the NetworkInterfaceNicType const type. +func PossibleNetworkInterfaceNicTypeValues() []NetworkInterfaceNicType { + return []NetworkInterfaceNicType{ + NetworkInterfaceNicTypeElastic, + NetworkInterfaceNicTypeStandard, + } +} + +// NetworkOperationStatus - Status of the Azure async operation. +type NetworkOperationStatus string + +const ( + NetworkOperationStatusFailed NetworkOperationStatus = "Failed" + NetworkOperationStatusInProgress NetworkOperationStatus = "InProgress" + NetworkOperationStatusSucceeded NetworkOperationStatus = "Succeeded" +) + +// PossibleNetworkOperationStatusValues returns the possible values for the NetworkOperationStatus const type. +func PossibleNetworkOperationStatusValues() []NetworkOperationStatus { + return []NetworkOperationStatus{ + NetworkOperationStatusFailed, + NetworkOperationStatusInProgress, + NetworkOperationStatusSucceeded, + } +} + +// NextHopType - Next hop type. +type NextHopType string + +const ( + NextHopTypeHyperNetGateway NextHopType = "HyperNetGateway" + NextHopTypeInternet NextHopType = "Internet" + NextHopTypeNone NextHopType = "None" + NextHopTypeVirtualAppliance NextHopType = "VirtualAppliance" + NextHopTypeVirtualNetworkGateway NextHopType = "VirtualNetworkGateway" + NextHopTypeVnetLocal NextHopType = "VnetLocal" +) + +// PossibleNextHopTypeValues returns the possible values for the NextHopType const type. +func PossibleNextHopTypeValues() []NextHopType { + return []NextHopType{ + NextHopTypeHyperNetGateway, + NextHopTypeInternet, + NextHopTypeNone, + NextHopTypeVirtualAppliance, + NextHopTypeVirtualNetworkGateway, + NextHopTypeVnetLocal, + } +} + +// NextStep - Supported next step behaviors after a rule is applied to a matched route +type NextStep string + +const ( + NextStepContinue NextStep = "Continue" + NextStepTerminate NextStep = "Terminate" + NextStepUnknown NextStep = "Unknown" +) + +// PossibleNextStepValues returns the possible values for the NextStep const type. +func PossibleNextStepValues() []NextStep { + return []NextStep{ + NextStepContinue, + NextStepTerminate, + NextStepUnknown, + } +} + +// OfficeTrafficCategory - The office traffic category. +type OfficeTrafficCategory string + +const ( + OfficeTrafficCategoryAll OfficeTrafficCategory = "All" + OfficeTrafficCategoryNone OfficeTrafficCategory = "None" + OfficeTrafficCategoryOptimize OfficeTrafficCategory = "Optimize" + OfficeTrafficCategoryOptimizeAndAllow OfficeTrafficCategory = "OptimizeAndAllow" +) + +// PossibleOfficeTrafficCategoryValues returns the possible values for the OfficeTrafficCategory const type. +func PossibleOfficeTrafficCategoryValues() []OfficeTrafficCategory { + return []OfficeTrafficCategory{ + OfficeTrafficCategoryAll, + OfficeTrafficCategoryNone, + OfficeTrafficCategoryOptimize, + OfficeTrafficCategoryOptimizeAndAllow, + } +} + +// Origin - The origin of the issue. +type Origin string + +const ( + OriginInbound Origin = "Inbound" + OriginLocal Origin = "Local" + OriginOutbound Origin = "Outbound" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginInbound, + OriginLocal, + OriginOutbound, + } +} + +// OutputType - Connection monitor output destination type. Currently, only "Workspace" is supported. +type OutputType string + +const ( + OutputTypeWorkspace OutputType = "Workspace" +) + +// PossibleOutputTypeValues returns the possible values for the OutputType const type. +func PossibleOutputTypeValues() []OutputType { + return []OutputType{ + OutputTypeWorkspace, + } +} + +// OwaspCrsExclusionEntryMatchVariable - The variable to be excluded. +type OwaspCrsExclusionEntryMatchVariable string + +const ( + OwaspCrsExclusionEntryMatchVariableRequestArgKeys OwaspCrsExclusionEntryMatchVariable = "RequestArgKeys" + OwaspCrsExclusionEntryMatchVariableRequestArgNames OwaspCrsExclusionEntryMatchVariable = "RequestArgNames" + OwaspCrsExclusionEntryMatchVariableRequestArgValues OwaspCrsExclusionEntryMatchVariable = "RequestArgValues" + OwaspCrsExclusionEntryMatchVariableRequestCookieKeys OwaspCrsExclusionEntryMatchVariable = "RequestCookieKeys" + OwaspCrsExclusionEntryMatchVariableRequestCookieNames OwaspCrsExclusionEntryMatchVariable = "RequestCookieNames" + OwaspCrsExclusionEntryMatchVariableRequestCookieValues OwaspCrsExclusionEntryMatchVariable = "RequestCookieValues" + OwaspCrsExclusionEntryMatchVariableRequestHeaderKeys OwaspCrsExclusionEntryMatchVariable = "RequestHeaderKeys" + OwaspCrsExclusionEntryMatchVariableRequestHeaderNames OwaspCrsExclusionEntryMatchVariable = "RequestHeaderNames" + OwaspCrsExclusionEntryMatchVariableRequestHeaderValues OwaspCrsExclusionEntryMatchVariable = "RequestHeaderValues" +) + +// PossibleOwaspCrsExclusionEntryMatchVariableValues returns the possible values for the OwaspCrsExclusionEntryMatchVariable const type. +func PossibleOwaspCrsExclusionEntryMatchVariableValues() []OwaspCrsExclusionEntryMatchVariable { + return []OwaspCrsExclusionEntryMatchVariable{ + OwaspCrsExclusionEntryMatchVariableRequestArgKeys, + OwaspCrsExclusionEntryMatchVariableRequestArgNames, + OwaspCrsExclusionEntryMatchVariableRequestArgValues, + OwaspCrsExclusionEntryMatchVariableRequestCookieKeys, + OwaspCrsExclusionEntryMatchVariableRequestCookieNames, + OwaspCrsExclusionEntryMatchVariableRequestCookieValues, + OwaspCrsExclusionEntryMatchVariableRequestHeaderKeys, + OwaspCrsExclusionEntryMatchVariableRequestHeaderNames, + OwaspCrsExclusionEntryMatchVariableRequestHeaderValues, + } +} + +// OwaspCrsExclusionEntrySelectorMatchOperator - When matchVariable is a collection, operate on the selector to specify which +// elements in the collection this exclusion applies to. +type OwaspCrsExclusionEntrySelectorMatchOperator string + +const ( + OwaspCrsExclusionEntrySelectorMatchOperatorContains OwaspCrsExclusionEntrySelectorMatchOperator = "Contains" + OwaspCrsExclusionEntrySelectorMatchOperatorEndsWith OwaspCrsExclusionEntrySelectorMatchOperator = "EndsWith" + OwaspCrsExclusionEntrySelectorMatchOperatorEquals OwaspCrsExclusionEntrySelectorMatchOperator = "Equals" + OwaspCrsExclusionEntrySelectorMatchOperatorEqualsAny OwaspCrsExclusionEntrySelectorMatchOperator = "EqualsAny" + OwaspCrsExclusionEntrySelectorMatchOperatorStartsWith OwaspCrsExclusionEntrySelectorMatchOperator = "StartsWith" +) + +// PossibleOwaspCrsExclusionEntrySelectorMatchOperatorValues returns the possible values for the OwaspCrsExclusionEntrySelectorMatchOperator const type. +func PossibleOwaspCrsExclusionEntrySelectorMatchOperatorValues() []OwaspCrsExclusionEntrySelectorMatchOperator { + return []OwaspCrsExclusionEntrySelectorMatchOperator{ + OwaspCrsExclusionEntrySelectorMatchOperatorContains, + OwaspCrsExclusionEntrySelectorMatchOperatorEndsWith, + OwaspCrsExclusionEntrySelectorMatchOperatorEquals, + OwaspCrsExclusionEntrySelectorMatchOperatorEqualsAny, + OwaspCrsExclusionEntrySelectorMatchOperatorStartsWith, + } +} + +// PacketCaptureTargetType - Target type of the resource provided. +type PacketCaptureTargetType string + +const ( + PacketCaptureTargetTypeAzureVM PacketCaptureTargetType = "AzureVM" + PacketCaptureTargetTypeAzureVMSS PacketCaptureTargetType = "AzureVMSS" +) + +// PossiblePacketCaptureTargetTypeValues returns the possible values for the PacketCaptureTargetType const type. +func PossiblePacketCaptureTargetTypeValues() []PacketCaptureTargetType { + return []PacketCaptureTargetType{ + PacketCaptureTargetTypeAzureVM, + PacketCaptureTargetTypeAzureVMSS, + } +} + +type PcError string + +const ( + PcErrorAgentStopped PcError = "AgentStopped" + PcErrorCaptureFailed PcError = "CaptureFailed" + PcErrorInternalError PcError = "InternalError" + PcErrorLocalFileFailed PcError = "LocalFileFailed" + PcErrorStorageFailed PcError = "StorageFailed" +) + +// PossiblePcErrorValues returns the possible values for the PcError const type. +func PossiblePcErrorValues() []PcError { + return []PcError{ + PcErrorAgentStopped, + PcErrorCaptureFailed, + PcErrorInternalError, + PcErrorLocalFileFailed, + PcErrorStorageFailed, + } +} + +// PcProtocol - Protocol to be filtered on. +type PcProtocol string + +const ( + PcProtocolAny PcProtocol = "Any" + PcProtocolTCP PcProtocol = "TCP" + PcProtocolUDP PcProtocol = "UDP" +) + +// PossiblePcProtocolValues returns the possible values for the PcProtocol const type. +func PossiblePcProtocolValues() []PcProtocol { + return []PcProtocol{ + PcProtocolAny, + PcProtocolTCP, + PcProtocolUDP, + } +} + +// PcStatus - The status of the packet capture session. +type PcStatus string + +const ( + PcStatusError PcStatus = "Error" + PcStatusNotStarted PcStatus = "NotStarted" + PcStatusRunning PcStatus = "Running" + PcStatusStopped PcStatus = "Stopped" + PcStatusUnknown PcStatus = "Unknown" +) + +// PossiblePcStatusValues returns the possible values for the PcStatus const type. +func PossiblePcStatusValues() []PcStatus { + return []PcStatus{ + PcStatusError, + PcStatusNotStarted, + PcStatusRunning, + PcStatusStopped, + PcStatusUnknown, + } +} + +// PfsGroup - The Pfs Groups used in IKE Phase 2 for new child SA. +type PfsGroup string + +const ( + PfsGroupECP256 PfsGroup = "ECP256" + PfsGroupECP384 PfsGroup = "ECP384" + PfsGroupNone PfsGroup = "None" + PfsGroupPFS1 PfsGroup = "PFS1" + PfsGroupPFS14 PfsGroup = "PFS14" + PfsGroupPFS2 PfsGroup = "PFS2" + PfsGroupPFS2048 PfsGroup = "PFS2048" + PfsGroupPFS24 PfsGroup = "PFS24" + PfsGroupPFSMM PfsGroup = "PFSMM" +) + +// PossiblePfsGroupValues returns the possible values for the PfsGroup const type. +func PossiblePfsGroupValues() []PfsGroup { + return []PfsGroup{ + PfsGroupECP256, + PfsGroupECP384, + PfsGroupNone, + PfsGroupPFS1, + PfsGroupPFS14, + PfsGroupPFS2, + PfsGroupPFS2048, + PfsGroupPFS24, + PfsGroupPFSMM, + } +} + +// PreferredIPVersion - The preferred IP version to use in test evaluation. The connection monitor may choose to use a different +// version depending on other parameters. +type PreferredIPVersion string + +const ( + PreferredIPVersionIPv4 PreferredIPVersion = "IPv4" + PreferredIPVersionIPv6 PreferredIPVersion = "IPv6" +) + +// PossiblePreferredIPVersionValues returns the possible values for the PreferredIPVersion const type. +func PossiblePreferredIPVersionValues() []PreferredIPVersion { + return []PreferredIPVersion{ + PreferredIPVersionIPv4, + PreferredIPVersionIPv6, + } +} + +// PreferredRoutingGateway - The preferred routing gateway types +type PreferredRoutingGateway string + +const ( + PreferredRoutingGatewayExpressRoute PreferredRoutingGateway = "ExpressRoute" + PreferredRoutingGatewayNone PreferredRoutingGateway = "None" + PreferredRoutingGatewayVPNGateway PreferredRoutingGateway = "VpnGateway" +) + +// PossiblePreferredRoutingGatewayValues returns the possible values for the PreferredRoutingGateway const type. +func PossiblePreferredRoutingGatewayValues() []PreferredRoutingGateway { + return []PreferredRoutingGateway{ + PreferredRoutingGatewayExpressRoute, + PreferredRoutingGatewayNone, + PreferredRoutingGatewayVPNGateway, + } +} + +// ProbeProtocol - The protocol of the end point. If 'Tcp' is specified, a received ACK is required for the probe to be successful. +// If 'Http' or 'Https' is specified, a 200 OK response from the specifies URI is required +// for the probe to be successful. +type ProbeProtocol string + +const ( + ProbeProtocolHTTP ProbeProtocol = "Http" + ProbeProtocolHTTPS ProbeProtocol = "Https" + ProbeProtocolTCP ProbeProtocol = "Tcp" +) + +// PossibleProbeProtocolValues returns the possible values for the ProbeProtocol const type. +func PossibleProbeProtocolValues() []ProbeProtocol { + return []ProbeProtocol{ + ProbeProtocolHTTP, + ProbeProtocolHTTPS, + ProbeProtocolTCP, + } +} + +// ProcessorArchitecture - VPN client Processor Architecture. +type ProcessorArchitecture string + +const ( + ProcessorArchitectureAmd64 ProcessorArchitecture = "Amd64" + ProcessorArchitectureX86 ProcessorArchitecture = "X86" +) + +// PossibleProcessorArchitectureValues returns the possible values for the ProcessorArchitecture const type. +func PossibleProcessorArchitectureValues() []ProcessorArchitecture { + return []ProcessorArchitecture{ + ProcessorArchitectureAmd64, + ProcessorArchitectureX86, + } +} + +// Protocol - Network protocol. +type Protocol string + +const ( + ProtocolHTTP Protocol = "Http" + ProtocolHTTPS Protocol = "Https" + ProtocolIcmp Protocol = "Icmp" + ProtocolTCP Protocol = "Tcp" +) + +// PossibleProtocolValues returns the possible values for the Protocol const type. +func PossibleProtocolValues() []Protocol { + return []Protocol{ + ProtocolHTTP, + ProtocolHTTPS, + ProtocolIcmp, + ProtocolTCP, + } +} + +// ProtocolType - RNM supported protocol types. +type ProtocolType string + +const ( + ProtocolTypeAh ProtocolType = "Ah" + ProtocolTypeAll ProtocolType = "All" + ProtocolTypeDoNotUse ProtocolType = "DoNotUse" + ProtocolTypeEsp ProtocolType = "Esp" + ProtocolTypeGre ProtocolType = "Gre" + ProtocolTypeIcmp ProtocolType = "Icmp" + ProtocolTypeTCP ProtocolType = "Tcp" + ProtocolTypeUDP ProtocolType = "Udp" + ProtocolTypeVxlan ProtocolType = "Vxlan" +) + +// PossibleProtocolTypeValues returns the possible values for the ProtocolType const type. +func PossibleProtocolTypeValues() []ProtocolType { + return []ProtocolType{ + ProtocolTypeAh, + ProtocolTypeAll, + ProtocolTypeDoNotUse, + ProtocolTypeEsp, + ProtocolTypeGre, + ProtocolTypeIcmp, + ProtocolTypeTCP, + ProtocolTypeUDP, + ProtocolTypeVxlan, + } +} + +// ProvisioningState - The current provisioning state. +type ProvisioningState string + +const ( + 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{ + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// PublicIPAddressDNSSettingsDomainNameLabelScope - The domain name label scope. If a domain name label and a domain name +// label scope are specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system with a hashed +// value +// includes in FQDN. +type PublicIPAddressDNSSettingsDomainNameLabelScope string + +const ( + PublicIPAddressDNSSettingsDomainNameLabelScopeNoReuse PublicIPAddressDNSSettingsDomainNameLabelScope = "NoReuse" + PublicIPAddressDNSSettingsDomainNameLabelScopeResourceGroupReuse PublicIPAddressDNSSettingsDomainNameLabelScope = "ResourceGroupReuse" + PublicIPAddressDNSSettingsDomainNameLabelScopeSubscriptionReuse PublicIPAddressDNSSettingsDomainNameLabelScope = "SubscriptionReuse" + PublicIPAddressDNSSettingsDomainNameLabelScopeTenantReuse PublicIPAddressDNSSettingsDomainNameLabelScope = "TenantReuse" +) + +// PossiblePublicIPAddressDNSSettingsDomainNameLabelScopeValues returns the possible values for the PublicIPAddressDNSSettingsDomainNameLabelScope const type. +func PossiblePublicIPAddressDNSSettingsDomainNameLabelScopeValues() []PublicIPAddressDNSSettingsDomainNameLabelScope { + return []PublicIPAddressDNSSettingsDomainNameLabelScope{ + PublicIPAddressDNSSettingsDomainNameLabelScopeNoReuse, + PublicIPAddressDNSSettingsDomainNameLabelScopeResourceGroupReuse, + PublicIPAddressDNSSettingsDomainNameLabelScopeSubscriptionReuse, + PublicIPAddressDNSSettingsDomainNameLabelScopeTenantReuse, + } +} + +// PublicIPAddressMigrationPhase - Migration phase of Public IP Address. +type PublicIPAddressMigrationPhase string + +const ( + PublicIPAddressMigrationPhaseAbort PublicIPAddressMigrationPhase = "Abort" + PublicIPAddressMigrationPhaseCommit PublicIPAddressMigrationPhase = "Commit" + PublicIPAddressMigrationPhaseCommitted PublicIPAddressMigrationPhase = "Committed" + PublicIPAddressMigrationPhaseNone PublicIPAddressMigrationPhase = "None" + PublicIPAddressMigrationPhasePrepare PublicIPAddressMigrationPhase = "Prepare" +) + +// PossiblePublicIPAddressMigrationPhaseValues returns the possible values for the PublicIPAddressMigrationPhase const type. +func PossiblePublicIPAddressMigrationPhaseValues() []PublicIPAddressMigrationPhase { + return []PublicIPAddressMigrationPhase{ + PublicIPAddressMigrationPhaseAbort, + PublicIPAddressMigrationPhaseCommit, + PublicIPAddressMigrationPhaseCommitted, + PublicIPAddressMigrationPhaseNone, + PublicIPAddressMigrationPhasePrepare, + } +} + +// PublicIPAddressSKUName - Name of a public IP address SKU. +type PublicIPAddressSKUName string + +const ( + PublicIPAddressSKUNameBasic PublicIPAddressSKUName = "Basic" + PublicIPAddressSKUNameStandard PublicIPAddressSKUName = "Standard" +) + +// PossiblePublicIPAddressSKUNameValues returns the possible values for the PublicIPAddressSKUName const type. +func PossiblePublicIPAddressSKUNameValues() []PublicIPAddressSKUName { + return []PublicIPAddressSKUName{ + PublicIPAddressSKUNameBasic, + PublicIPAddressSKUNameStandard, + } +} + +// PublicIPAddressSKUTier - Tier of a public IP address SKU. +type PublicIPAddressSKUTier string + +const ( + PublicIPAddressSKUTierGlobal PublicIPAddressSKUTier = "Global" + PublicIPAddressSKUTierRegional PublicIPAddressSKUTier = "Regional" +) + +// PossiblePublicIPAddressSKUTierValues returns the possible values for the PublicIPAddressSKUTier const type. +func PossiblePublicIPAddressSKUTierValues() []PublicIPAddressSKUTier { + return []PublicIPAddressSKUTier{ + PublicIPAddressSKUTierGlobal, + PublicIPAddressSKUTierRegional, + } +} + +// PublicIPPrefixSKUName - Name of a public IP prefix SKU. +type PublicIPPrefixSKUName string + +const ( + PublicIPPrefixSKUNameStandard PublicIPPrefixSKUName = "Standard" +) + +// PossiblePublicIPPrefixSKUNameValues returns the possible values for the PublicIPPrefixSKUName const type. +func PossiblePublicIPPrefixSKUNameValues() []PublicIPPrefixSKUName { + return []PublicIPPrefixSKUName{ + PublicIPPrefixSKUNameStandard, + } +} + +// PublicIPPrefixSKUTier - Tier of a public IP prefix SKU. +type PublicIPPrefixSKUTier string + +const ( + PublicIPPrefixSKUTierGlobal PublicIPPrefixSKUTier = "Global" + PublicIPPrefixSKUTierRegional PublicIPPrefixSKUTier = "Regional" +) + +// PossiblePublicIPPrefixSKUTierValues returns the possible values for the PublicIPPrefixSKUTier const type. +func PossiblePublicIPPrefixSKUTierValues() []PublicIPPrefixSKUTier { + return []PublicIPPrefixSKUTier{ + PublicIPPrefixSKUTierGlobal, + PublicIPPrefixSKUTierRegional, + } +} + +// ResourceIdentityType - The type of identity used for the resource. The type 'SystemAssigned, UserAssigned' includes both +// an implicitly created identity and a set of user assigned identities. The type 'None' will remove any +// identities from the virtual machine. +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, + } +} + +// RouteFilterRuleType - The rule type of the rule. +type RouteFilterRuleType string + +const ( + RouteFilterRuleTypeCommunity RouteFilterRuleType = "Community" +) + +// PossibleRouteFilterRuleTypeValues returns the possible values for the RouteFilterRuleType const type. +func PossibleRouteFilterRuleTypeValues() []RouteFilterRuleType { + return []RouteFilterRuleType{ + RouteFilterRuleTypeCommunity, + } +} + +// RouteMapActionType - Kind of actions which can be taken on a matched route. Add, Replace, Remove refer to parameters on +// the route, like community or prefix +type RouteMapActionType string + +const ( + RouteMapActionTypeAdd RouteMapActionType = "Add" + RouteMapActionTypeDrop RouteMapActionType = "Drop" + RouteMapActionTypeRemove RouteMapActionType = "Remove" + RouteMapActionTypeReplace RouteMapActionType = "Replace" + RouteMapActionTypeUnknown RouteMapActionType = "Unknown" +) + +// PossibleRouteMapActionTypeValues returns the possible values for the RouteMapActionType const type. +func PossibleRouteMapActionTypeValues() []RouteMapActionType { + return []RouteMapActionType{ + RouteMapActionTypeAdd, + RouteMapActionTypeDrop, + RouteMapActionTypeRemove, + RouteMapActionTypeReplace, + RouteMapActionTypeUnknown, + } +} + +// RouteMapMatchCondition - Match condition to apply RouteMap rules. +type RouteMapMatchCondition string + +const ( + RouteMapMatchConditionContains RouteMapMatchCondition = "Contains" + RouteMapMatchConditionEquals RouteMapMatchCondition = "Equals" + RouteMapMatchConditionNotContains RouteMapMatchCondition = "NotContains" + RouteMapMatchConditionNotEquals RouteMapMatchCondition = "NotEquals" + RouteMapMatchConditionUnknown RouteMapMatchCondition = "Unknown" +) + +// PossibleRouteMapMatchConditionValues returns the possible values for the RouteMapMatchCondition const type. +func PossibleRouteMapMatchConditionValues() []RouteMapMatchCondition { + return []RouteMapMatchCondition{ + RouteMapMatchConditionContains, + RouteMapMatchConditionEquals, + RouteMapMatchConditionNotContains, + RouteMapMatchConditionNotEquals, + RouteMapMatchConditionUnknown, + } +} + +// RouteNextHopType - The type of Azure hop the packet should be sent to. +type RouteNextHopType string + +const ( + RouteNextHopTypeInternet RouteNextHopType = "Internet" + RouteNextHopTypeNone RouteNextHopType = "None" + RouteNextHopTypeVirtualAppliance RouteNextHopType = "VirtualAppliance" + RouteNextHopTypeVirtualNetworkGateway RouteNextHopType = "VirtualNetworkGateway" + RouteNextHopTypeVnetLocal RouteNextHopType = "VnetLocal" +) + +// PossibleRouteNextHopTypeValues returns the possible values for the RouteNextHopType const type. +func PossibleRouteNextHopTypeValues() []RouteNextHopType { + return []RouteNextHopType{ + RouteNextHopTypeInternet, + RouteNextHopTypeNone, + RouteNextHopTypeVirtualAppliance, + RouteNextHopTypeVirtualNetworkGateway, + RouteNextHopTypeVnetLocal, + } +} + +// RoutingState - The current routing state of the VirtualHub. +type RoutingState string + +const ( + RoutingStateFailed RoutingState = "Failed" + RoutingStateNone RoutingState = "None" + RoutingStateProvisioned RoutingState = "Provisioned" + RoutingStateProvisioning RoutingState = "Provisioning" +) + +// PossibleRoutingStateValues returns the possible values for the RoutingState const type. +func PossibleRoutingStateValues() []RoutingState { + return []RoutingState{ + RoutingStateFailed, + RoutingStateNone, + RoutingStateProvisioned, + RoutingStateProvisioning, + } +} + +// ScopeConnectionState - The current scope connection state. +type ScopeConnectionState string + +const ( + ScopeConnectionStateConflict ScopeConnectionState = "Conflict" + ScopeConnectionStateConnected ScopeConnectionState = "Connected" + ScopeConnectionStatePending ScopeConnectionState = "Pending" + ScopeConnectionStateRejected ScopeConnectionState = "Rejected" + ScopeConnectionStateRevoked ScopeConnectionState = "Revoked" +) + +// PossibleScopeConnectionStateValues returns the possible values for the ScopeConnectionState const type. +func PossibleScopeConnectionStateValues() []ScopeConnectionState { + return []ScopeConnectionState{ + ScopeConnectionStateConflict, + ScopeConnectionStateConnected, + ScopeConnectionStatePending, + ScopeConnectionStateRejected, + ScopeConnectionStateRevoked, + } +} + +// ScrubbingRuleEntryMatchOperator - When matchVariable is a collection, operate on the selector to specify which elements +// in the collection this rule applies to. +type ScrubbingRuleEntryMatchOperator string + +const ( + ScrubbingRuleEntryMatchOperatorEquals ScrubbingRuleEntryMatchOperator = "Equals" + ScrubbingRuleEntryMatchOperatorEqualsAny ScrubbingRuleEntryMatchOperator = "EqualsAny" +) + +// PossibleScrubbingRuleEntryMatchOperatorValues returns the possible values for the ScrubbingRuleEntryMatchOperator const type. +func PossibleScrubbingRuleEntryMatchOperatorValues() []ScrubbingRuleEntryMatchOperator { + return []ScrubbingRuleEntryMatchOperator{ + ScrubbingRuleEntryMatchOperatorEquals, + ScrubbingRuleEntryMatchOperatorEqualsAny, + } +} + +// ScrubbingRuleEntryMatchVariable - The variable to be scrubbed from the logs. +type ScrubbingRuleEntryMatchVariable string + +const ( + ScrubbingRuleEntryMatchVariableRequestArgNames ScrubbingRuleEntryMatchVariable = "RequestArgNames" + ScrubbingRuleEntryMatchVariableRequestCookieNames ScrubbingRuleEntryMatchVariable = "RequestCookieNames" + ScrubbingRuleEntryMatchVariableRequestHeaderNames ScrubbingRuleEntryMatchVariable = "RequestHeaderNames" + ScrubbingRuleEntryMatchVariableRequestIPAddress ScrubbingRuleEntryMatchVariable = "RequestIPAddress" + ScrubbingRuleEntryMatchVariableRequestJSONArgNames ScrubbingRuleEntryMatchVariable = "RequestJSONArgNames" + ScrubbingRuleEntryMatchVariableRequestPostArgNames ScrubbingRuleEntryMatchVariable = "RequestPostArgNames" +) + +// PossibleScrubbingRuleEntryMatchVariableValues returns the possible values for the ScrubbingRuleEntryMatchVariable const type. +func PossibleScrubbingRuleEntryMatchVariableValues() []ScrubbingRuleEntryMatchVariable { + return []ScrubbingRuleEntryMatchVariable{ + ScrubbingRuleEntryMatchVariableRequestArgNames, + ScrubbingRuleEntryMatchVariableRequestCookieNames, + ScrubbingRuleEntryMatchVariableRequestHeaderNames, + ScrubbingRuleEntryMatchVariableRequestIPAddress, + ScrubbingRuleEntryMatchVariableRequestJSONArgNames, + ScrubbingRuleEntryMatchVariableRequestPostArgNames, + } +} + +// ScrubbingRuleEntryState - Defines the state of log scrubbing rule. Default value is Enabled. +type ScrubbingRuleEntryState string + +const ( + ScrubbingRuleEntryStateDisabled ScrubbingRuleEntryState = "Disabled" + ScrubbingRuleEntryStateEnabled ScrubbingRuleEntryState = "Enabled" +) + +// PossibleScrubbingRuleEntryStateValues returns the possible values for the ScrubbingRuleEntryState const type. +func PossibleScrubbingRuleEntryStateValues() []ScrubbingRuleEntryState { + return []ScrubbingRuleEntryState{ + ScrubbingRuleEntryStateDisabled, + ScrubbingRuleEntryStateEnabled, + } +} + +// SecurityConfigurationRuleAccess - Whether network traffic is allowed or denied. +type SecurityConfigurationRuleAccess string + +const ( + SecurityConfigurationRuleAccessAllow SecurityConfigurationRuleAccess = "Allow" + SecurityConfigurationRuleAccessAlwaysAllow SecurityConfigurationRuleAccess = "AlwaysAllow" + SecurityConfigurationRuleAccessDeny SecurityConfigurationRuleAccess = "Deny" +) + +// PossibleSecurityConfigurationRuleAccessValues returns the possible values for the SecurityConfigurationRuleAccess const type. +func PossibleSecurityConfigurationRuleAccessValues() []SecurityConfigurationRuleAccess { + return []SecurityConfigurationRuleAccess{ + SecurityConfigurationRuleAccessAllow, + SecurityConfigurationRuleAccessAlwaysAllow, + SecurityConfigurationRuleAccessDeny, + } +} + +// SecurityConfigurationRuleDirection - The direction of the rule. The direction specifies if the rule will be evaluated on +// incoming or outgoing traffic. +type SecurityConfigurationRuleDirection string + +const ( + SecurityConfigurationRuleDirectionInbound SecurityConfigurationRuleDirection = "Inbound" + SecurityConfigurationRuleDirectionOutbound SecurityConfigurationRuleDirection = "Outbound" +) + +// PossibleSecurityConfigurationRuleDirectionValues returns the possible values for the SecurityConfigurationRuleDirection const type. +func PossibleSecurityConfigurationRuleDirectionValues() []SecurityConfigurationRuleDirection { + return []SecurityConfigurationRuleDirection{ + SecurityConfigurationRuleDirectionInbound, + SecurityConfigurationRuleDirectionOutbound, + } +} + +// SecurityConfigurationRuleProtocol - Network protocol this rule applies to. +type SecurityConfigurationRuleProtocol string + +const ( + SecurityConfigurationRuleProtocolAh SecurityConfigurationRuleProtocol = "Ah" + SecurityConfigurationRuleProtocolAny SecurityConfigurationRuleProtocol = "Any" + SecurityConfigurationRuleProtocolEsp SecurityConfigurationRuleProtocol = "Esp" + SecurityConfigurationRuleProtocolIcmp SecurityConfigurationRuleProtocol = "Icmp" + SecurityConfigurationRuleProtocolTCP SecurityConfigurationRuleProtocol = "Tcp" + SecurityConfigurationRuleProtocolUDP SecurityConfigurationRuleProtocol = "Udp" +) + +// PossibleSecurityConfigurationRuleProtocolValues returns the possible values for the SecurityConfigurationRuleProtocol const type. +func PossibleSecurityConfigurationRuleProtocolValues() []SecurityConfigurationRuleProtocol { + return []SecurityConfigurationRuleProtocol{ + SecurityConfigurationRuleProtocolAh, + SecurityConfigurationRuleProtocolAny, + SecurityConfigurationRuleProtocolEsp, + SecurityConfigurationRuleProtocolIcmp, + SecurityConfigurationRuleProtocolTCP, + SecurityConfigurationRuleProtocolUDP, + } +} + +// SecurityPartnerProviderConnectionStatus - The current state of the connection with Security Partner Provider. +type SecurityPartnerProviderConnectionStatus string + +const ( + SecurityPartnerProviderConnectionStatusConnected SecurityPartnerProviderConnectionStatus = "Connected" + SecurityPartnerProviderConnectionStatusNotConnected SecurityPartnerProviderConnectionStatus = "NotConnected" + SecurityPartnerProviderConnectionStatusPartiallyConnected SecurityPartnerProviderConnectionStatus = "PartiallyConnected" + SecurityPartnerProviderConnectionStatusUnknown SecurityPartnerProviderConnectionStatus = "Unknown" +) + +// PossibleSecurityPartnerProviderConnectionStatusValues returns the possible values for the SecurityPartnerProviderConnectionStatus const type. +func PossibleSecurityPartnerProviderConnectionStatusValues() []SecurityPartnerProviderConnectionStatus { + return []SecurityPartnerProviderConnectionStatus{ + SecurityPartnerProviderConnectionStatusConnected, + SecurityPartnerProviderConnectionStatusNotConnected, + SecurityPartnerProviderConnectionStatusPartiallyConnected, + SecurityPartnerProviderConnectionStatusUnknown, + } +} + +// SecurityProviderName - The Security Providers. +type SecurityProviderName string + +const ( + SecurityProviderNameCheckpoint SecurityProviderName = "Checkpoint" + SecurityProviderNameIBoss SecurityProviderName = "IBoss" + SecurityProviderNameZScaler SecurityProviderName = "ZScaler" +) + +// PossibleSecurityProviderNameValues returns the possible values for the SecurityProviderName const type. +func PossibleSecurityProviderNameValues() []SecurityProviderName { + return []SecurityProviderName{ + SecurityProviderNameCheckpoint, + SecurityProviderNameIBoss, + SecurityProviderNameZScaler, + } +} + +// SecurityRuleAccess - Whether network traffic is allowed or denied. +type SecurityRuleAccess string + +const ( + SecurityRuleAccessAllow SecurityRuleAccess = "Allow" + SecurityRuleAccessDeny SecurityRuleAccess = "Deny" +) + +// PossibleSecurityRuleAccessValues returns the possible values for the SecurityRuleAccess const type. +func PossibleSecurityRuleAccessValues() []SecurityRuleAccess { + return []SecurityRuleAccess{ + SecurityRuleAccessAllow, + SecurityRuleAccessDeny, + } +} + +// SecurityRuleDirection - The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing +// traffic. +type SecurityRuleDirection string + +const ( + SecurityRuleDirectionInbound SecurityRuleDirection = "Inbound" + SecurityRuleDirectionOutbound SecurityRuleDirection = "Outbound" +) + +// PossibleSecurityRuleDirectionValues returns the possible values for the SecurityRuleDirection const type. +func PossibleSecurityRuleDirectionValues() []SecurityRuleDirection { + return []SecurityRuleDirection{ + SecurityRuleDirectionInbound, + SecurityRuleDirectionOutbound, + } +} + +// SecurityRuleProtocol - Network protocol this rule applies to. +type SecurityRuleProtocol string + +const ( + SecurityRuleProtocolAh SecurityRuleProtocol = "Ah" + SecurityRuleProtocolAsterisk SecurityRuleProtocol = "*" + SecurityRuleProtocolEsp SecurityRuleProtocol = "Esp" + SecurityRuleProtocolIcmp SecurityRuleProtocol = "Icmp" + SecurityRuleProtocolTCP SecurityRuleProtocol = "Tcp" + SecurityRuleProtocolUDP SecurityRuleProtocol = "Udp" +) + +// PossibleSecurityRuleProtocolValues returns the possible values for the SecurityRuleProtocol const type. +func PossibleSecurityRuleProtocolValues() []SecurityRuleProtocol { + return []SecurityRuleProtocol{ + SecurityRuleProtocolAh, + SecurityRuleProtocolAsterisk, + SecurityRuleProtocolEsp, + SecurityRuleProtocolIcmp, + SecurityRuleProtocolTCP, + SecurityRuleProtocolUDP, + } +} + +// ServiceProviderProvisioningState - The ServiceProviderProvisioningState state of the resource. +type ServiceProviderProvisioningState string + +const ( + ServiceProviderProvisioningStateDeprovisioning ServiceProviderProvisioningState = "Deprovisioning" + ServiceProviderProvisioningStateNotProvisioned ServiceProviderProvisioningState = "NotProvisioned" + ServiceProviderProvisioningStateProvisioned ServiceProviderProvisioningState = "Provisioned" + ServiceProviderProvisioningStateProvisioning ServiceProviderProvisioningState = "Provisioning" +) + +// PossibleServiceProviderProvisioningStateValues returns the possible values for the ServiceProviderProvisioningState const type. +func PossibleServiceProviderProvisioningStateValues() []ServiceProviderProvisioningState { + return []ServiceProviderProvisioningState{ + ServiceProviderProvisioningStateDeprovisioning, + ServiceProviderProvisioningStateNotProvisioned, + ServiceProviderProvisioningStateProvisioned, + ServiceProviderProvisioningStateProvisioning, + } +} + +// Severity - The severity of the issue. +type Severity string + +const ( + SeverityError Severity = "Error" + SeverityWarning Severity = "Warning" +) + +// PossibleSeverityValues returns the possible values for the Severity const type. +func PossibleSeverityValues() []Severity { + return []Severity{ + SeverityError, + SeverityWarning, + } +} + +// SlotType - Specifies slot info on a cloud service +type SlotType string + +const ( + SlotTypeProduction SlotType = "Production" + SlotTypeStaging SlotType = "Staging" +) + +// PossibleSlotTypeValues returns the possible values for the SlotType const type. +func PossibleSlotTypeValues() []SlotType { + return []SlotType{ + SlotTypeProduction, + SlotTypeStaging, + } +} + +// SyncMode - Backend address synchronous mode for the backend pool +type SyncMode string + +const ( + SyncModeAutomatic SyncMode = "Automatic" + SyncModeManual SyncMode = "Manual" +) + +// PossibleSyncModeValues returns the possible values for the SyncMode const type. +func PossibleSyncModeValues() []SyncMode { + return []SyncMode{ + SyncModeAutomatic, + SyncModeManual, + } +} + +type SyncRemoteAddressSpace string + +const ( + SyncRemoteAddressSpaceTrue SyncRemoteAddressSpace = "true" +) + +// PossibleSyncRemoteAddressSpaceValues returns the possible values for the SyncRemoteAddressSpace const type. +func PossibleSyncRemoteAddressSpaceValues() []SyncRemoteAddressSpace { + return []SyncRemoteAddressSpace{ + SyncRemoteAddressSpaceTrue, + } +} + +// TransportProtocol - The transport protocol for the endpoint. +type TransportProtocol string + +const ( + TransportProtocolAll TransportProtocol = "All" + TransportProtocolTCP TransportProtocol = "Tcp" + TransportProtocolUDP TransportProtocol = "Udp" +) + +// PossibleTransportProtocolValues returns the possible values for the TransportProtocol const type. +func PossibleTransportProtocolValues() []TransportProtocol { + return []TransportProtocol{ + TransportProtocolAll, + TransportProtocolTCP, + TransportProtocolUDP, + } +} + +// TunnelConnectionStatus - The current state of the tunnel. +type TunnelConnectionStatus string + +const ( + TunnelConnectionStatusConnected TunnelConnectionStatus = "Connected" + TunnelConnectionStatusConnecting TunnelConnectionStatus = "Connecting" + TunnelConnectionStatusNotConnected TunnelConnectionStatus = "NotConnected" + TunnelConnectionStatusUnknown TunnelConnectionStatus = "Unknown" +) + +// PossibleTunnelConnectionStatusValues returns the possible values for the TunnelConnectionStatus const type. +func PossibleTunnelConnectionStatusValues() []TunnelConnectionStatus { + return []TunnelConnectionStatus{ + TunnelConnectionStatusConnected, + TunnelConnectionStatusConnecting, + TunnelConnectionStatusNotConnected, + TunnelConnectionStatusUnknown, + } +} + +// UsageUnit - An enum describing the unit of measurement. +type UsageUnit string + +const ( + UsageUnitCount UsageUnit = "Count" +) + +// PossibleUsageUnitValues returns the possible values for the UsageUnit const type. +func PossibleUsageUnitValues() []UsageUnit { + return []UsageUnit{ + UsageUnitCount, + } +} + +// UseHubGateway - Flag if need to use hub gateway. +type UseHubGateway string + +const ( + UseHubGatewayFalse UseHubGateway = "False" + UseHubGatewayTrue UseHubGateway = "True" +) + +// PossibleUseHubGatewayValues returns the possible values for the UseHubGateway const type. +func PossibleUseHubGatewayValues() []UseHubGateway { + return []UseHubGateway{ + UseHubGatewayFalse, + UseHubGatewayTrue, + } +} + +// VPNAuthenticationType - VPN authentication types enabled for the virtual network gateway. +type VPNAuthenticationType string + +const ( + VPNAuthenticationTypeAAD VPNAuthenticationType = "AAD" + VPNAuthenticationTypeCertificate VPNAuthenticationType = "Certificate" + VPNAuthenticationTypeRadius VPNAuthenticationType = "Radius" +) + +// PossibleVPNAuthenticationTypeValues returns the possible values for the VPNAuthenticationType const type. +func PossibleVPNAuthenticationTypeValues() []VPNAuthenticationType { + return []VPNAuthenticationType{ + VPNAuthenticationTypeAAD, + VPNAuthenticationTypeCertificate, + VPNAuthenticationTypeRadius, + } +} + +// VPNClientProtocol - VPN client protocol enabled for the virtual network gateway. +type VPNClientProtocol string + +const ( + VPNClientProtocolIkeV2 VPNClientProtocol = "IkeV2" + VPNClientProtocolOpenVPN VPNClientProtocol = "OpenVPN" + VPNClientProtocolSSTP VPNClientProtocol = "SSTP" +) + +// PossibleVPNClientProtocolValues returns the possible values for the VPNClientProtocol const type. +func PossibleVPNClientProtocolValues() []VPNClientProtocol { + return []VPNClientProtocol{ + VPNClientProtocolIkeV2, + VPNClientProtocolOpenVPN, + VPNClientProtocolSSTP, + } +} + +// VPNConnectionStatus - The current state of the vpn connection. +type VPNConnectionStatus string + +const ( + VPNConnectionStatusConnected VPNConnectionStatus = "Connected" + VPNConnectionStatusConnecting VPNConnectionStatus = "Connecting" + VPNConnectionStatusNotConnected VPNConnectionStatus = "NotConnected" + VPNConnectionStatusUnknown VPNConnectionStatus = "Unknown" +) + +// PossibleVPNConnectionStatusValues returns the possible values for the VPNConnectionStatus const type. +func PossibleVPNConnectionStatusValues() []VPNConnectionStatus { + return []VPNConnectionStatus{ + VPNConnectionStatusConnected, + VPNConnectionStatusConnecting, + VPNConnectionStatusNotConnected, + VPNConnectionStatusUnknown, + } +} + +// VPNGatewayGeneration - The generation for this VirtualNetworkGateway. Must be None if gatewayType is not VPN. +type VPNGatewayGeneration string + +const ( + VPNGatewayGenerationGeneration1 VPNGatewayGeneration = "Generation1" + VPNGatewayGenerationGeneration2 VPNGatewayGeneration = "Generation2" + VPNGatewayGenerationNone VPNGatewayGeneration = "None" +) + +// PossibleVPNGatewayGenerationValues returns the possible values for the VPNGatewayGeneration const type. +func PossibleVPNGatewayGenerationValues() []VPNGatewayGeneration { + return []VPNGatewayGeneration{ + VPNGatewayGenerationGeneration1, + VPNGatewayGenerationGeneration2, + VPNGatewayGenerationNone, + } +} + +// VPNGatewayTunnelingProtocol - VPN protocol enabled for the VpnServerConfiguration. +type VPNGatewayTunnelingProtocol string + +const ( + VPNGatewayTunnelingProtocolIkeV2 VPNGatewayTunnelingProtocol = "IkeV2" + VPNGatewayTunnelingProtocolOpenVPN VPNGatewayTunnelingProtocol = "OpenVPN" +) + +// PossibleVPNGatewayTunnelingProtocolValues returns the possible values for the VPNGatewayTunnelingProtocol const type. +func PossibleVPNGatewayTunnelingProtocolValues() []VPNGatewayTunnelingProtocol { + return []VPNGatewayTunnelingProtocol{ + VPNGatewayTunnelingProtocolIkeV2, + VPNGatewayTunnelingProtocolOpenVPN, + } +} + +// VPNLinkConnectionMode - Vpn link connection mode. +type VPNLinkConnectionMode string + +const ( + VPNLinkConnectionModeDefault VPNLinkConnectionMode = "Default" + VPNLinkConnectionModeInitiatorOnly VPNLinkConnectionMode = "InitiatorOnly" + VPNLinkConnectionModeResponderOnly VPNLinkConnectionMode = "ResponderOnly" +) + +// PossibleVPNLinkConnectionModeValues returns the possible values for the VPNLinkConnectionMode const type. +func PossibleVPNLinkConnectionModeValues() []VPNLinkConnectionMode { + return []VPNLinkConnectionMode{ + VPNLinkConnectionModeDefault, + VPNLinkConnectionModeInitiatorOnly, + VPNLinkConnectionModeResponderOnly, + } +} + +// VPNNatRuleMode - The Source NAT direction of a VPN NAT. +type VPNNatRuleMode string + +const ( + VPNNatRuleModeEgressSnat VPNNatRuleMode = "EgressSnat" + VPNNatRuleModeIngressSnat VPNNatRuleMode = "IngressSnat" +) + +// PossibleVPNNatRuleModeValues returns the possible values for the VPNNatRuleMode const type. +func PossibleVPNNatRuleModeValues() []VPNNatRuleMode { + return []VPNNatRuleMode{ + VPNNatRuleModeEgressSnat, + VPNNatRuleModeIngressSnat, + } +} + +// VPNNatRuleType - The type of NAT rule for VPN NAT. +type VPNNatRuleType string + +const ( + VPNNatRuleTypeDynamic VPNNatRuleType = "Dynamic" + VPNNatRuleTypeStatic VPNNatRuleType = "Static" +) + +// PossibleVPNNatRuleTypeValues returns the possible values for the VPNNatRuleType const type. +func PossibleVPNNatRuleTypeValues() []VPNNatRuleType { + return []VPNNatRuleType{ + VPNNatRuleTypeDynamic, + VPNNatRuleTypeStatic, + } +} + +// VPNPolicyMemberAttributeType - The Vpn Policy member attribute type. +type VPNPolicyMemberAttributeType string + +const ( + VPNPolicyMemberAttributeTypeAADGroupID VPNPolicyMemberAttributeType = "AADGroupId" + VPNPolicyMemberAttributeTypeCertificateGroupID VPNPolicyMemberAttributeType = "CertificateGroupId" + VPNPolicyMemberAttributeTypeRadiusAzureGroupID VPNPolicyMemberAttributeType = "RadiusAzureGroupId" +) + +// PossibleVPNPolicyMemberAttributeTypeValues returns the possible values for the VPNPolicyMemberAttributeType const type. +func PossibleVPNPolicyMemberAttributeTypeValues() []VPNPolicyMemberAttributeType { + return []VPNPolicyMemberAttributeType{ + VPNPolicyMemberAttributeTypeAADGroupID, + VPNPolicyMemberAttributeTypeCertificateGroupID, + VPNPolicyMemberAttributeTypeRadiusAzureGroupID, + } +} + +// VPNType - The type of this virtual network gateway. +type VPNType string + +const ( + VPNTypePolicyBased VPNType = "PolicyBased" + VPNTypeRouteBased VPNType = "RouteBased" +) + +// PossibleVPNTypeValues returns the possible values for the VPNType const type. +func PossibleVPNTypeValues() []VPNType { + return []VPNType{ + VPNTypePolicyBased, + VPNTypeRouteBased, + } +} + +// VerbosityLevel - Verbosity level. +type VerbosityLevel string + +const ( + VerbosityLevelFull VerbosityLevel = "Full" + VerbosityLevelMinimum VerbosityLevel = "Minimum" + VerbosityLevelNormal VerbosityLevel = "Normal" +) + +// PossibleVerbosityLevelValues returns the possible values for the VerbosityLevel const type. +func PossibleVerbosityLevelValues() []VerbosityLevel { + return []VerbosityLevel{ + VerbosityLevelFull, + VerbosityLevelMinimum, + VerbosityLevelNormal, + } +} + +// VirtualNetworkEncryptionEnforcement - If the encrypted VNet allows VM that does not support encryption +type VirtualNetworkEncryptionEnforcement string + +const ( + VirtualNetworkEncryptionEnforcementAllowUnencrypted VirtualNetworkEncryptionEnforcement = "AllowUnencrypted" + VirtualNetworkEncryptionEnforcementDropUnencrypted VirtualNetworkEncryptionEnforcement = "DropUnencrypted" +) + +// PossibleVirtualNetworkEncryptionEnforcementValues returns the possible values for the VirtualNetworkEncryptionEnforcement const type. +func PossibleVirtualNetworkEncryptionEnforcementValues() []VirtualNetworkEncryptionEnforcement { + return []VirtualNetworkEncryptionEnforcement{ + VirtualNetworkEncryptionEnforcementAllowUnencrypted, + VirtualNetworkEncryptionEnforcementDropUnencrypted, + } +} + +// VirtualNetworkGatewayConnectionMode - Gateway connection type. +type VirtualNetworkGatewayConnectionMode string + +const ( + VirtualNetworkGatewayConnectionModeDefault VirtualNetworkGatewayConnectionMode = "Default" + VirtualNetworkGatewayConnectionModeInitiatorOnly VirtualNetworkGatewayConnectionMode = "InitiatorOnly" + VirtualNetworkGatewayConnectionModeResponderOnly VirtualNetworkGatewayConnectionMode = "ResponderOnly" +) + +// PossibleVirtualNetworkGatewayConnectionModeValues returns the possible values for the VirtualNetworkGatewayConnectionMode const type. +func PossibleVirtualNetworkGatewayConnectionModeValues() []VirtualNetworkGatewayConnectionMode { + return []VirtualNetworkGatewayConnectionMode{ + VirtualNetworkGatewayConnectionModeDefault, + VirtualNetworkGatewayConnectionModeInitiatorOnly, + VirtualNetworkGatewayConnectionModeResponderOnly, + } +} + +// VirtualNetworkGatewayConnectionProtocol - Gateway connection protocol. +type VirtualNetworkGatewayConnectionProtocol string + +const ( + VirtualNetworkGatewayConnectionProtocolIKEv1 VirtualNetworkGatewayConnectionProtocol = "IKEv1" + VirtualNetworkGatewayConnectionProtocolIKEv2 VirtualNetworkGatewayConnectionProtocol = "IKEv2" +) + +// PossibleVirtualNetworkGatewayConnectionProtocolValues returns the possible values for the VirtualNetworkGatewayConnectionProtocol const type. +func PossibleVirtualNetworkGatewayConnectionProtocolValues() []VirtualNetworkGatewayConnectionProtocol { + return []VirtualNetworkGatewayConnectionProtocol{ + VirtualNetworkGatewayConnectionProtocolIKEv1, + VirtualNetworkGatewayConnectionProtocolIKEv2, + } +} + +// VirtualNetworkGatewayConnectionStatus - Virtual Network Gateway connection status. +type VirtualNetworkGatewayConnectionStatus string + +const ( + VirtualNetworkGatewayConnectionStatusConnected VirtualNetworkGatewayConnectionStatus = "Connected" + VirtualNetworkGatewayConnectionStatusConnecting VirtualNetworkGatewayConnectionStatus = "Connecting" + VirtualNetworkGatewayConnectionStatusNotConnected VirtualNetworkGatewayConnectionStatus = "NotConnected" + VirtualNetworkGatewayConnectionStatusUnknown VirtualNetworkGatewayConnectionStatus = "Unknown" +) + +// PossibleVirtualNetworkGatewayConnectionStatusValues returns the possible values for the VirtualNetworkGatewayConnectionStatus const type. +func PossibleVirtualNetworkGatewayConnectionStatusValues() []VirtualNetworkGatewayConnectionStatus { + return []VirtualNetworkGatewayConnectionStatus{ + VirtualNetworkGatewayConnectionStatusConnected, + VirtualNetworkGatewayConnectionStatusConnecting, + VirtualNetworkGatewayConnectionStatusNotConnected, + VirtualNetworkGatewayConnectionStatusUnknown, + } +} + +// VirtualNetworkGatewayConnectionType - Gateway connection type. +type VirtualNetworkGatewayConnectionType string + +const ( + VirtualNetworkGatewayConnectionTypeExpressRoute VirtualNetworkGatewayConnectionType = "ExpressRoute" + VirtualNetworkGatewayConnectionTypeIPsec VirtualNetworkGatewayConnectionType = "IPsec" + VirtualNetworkGatewayConnectionTypeVPNClient VirtualNetworkGatewayConnectionType = "VPNClient" + VirtualNetworkGatewayConnectionTypeVnet2Vnet VirtualNetworkGatewayConnectionType = "Vnet2Vnet" +) + +// PossibleVirtualNetworkGatewayConnectionTypeValues returns the possible values for the VirtualNetworkGatewayConnectionType const type. +func PossibleVirtualNetworkGatewayConnectionTypeValues() []VirtualNetworkGatewayConnectionType { + return []VirtualNetworkGatewayConnectionType{ + VirtualNetworkGatewayConnectionTypeExpressRoute, + VirtualNetworkGatewayConnectionTypeIPsec, + VirtualNetworkGatewayConnectionTypeVPNClient, + VirtualNetworkGatewayConnectionTypeVnet2Vnet, + } +} + +// VirtualNetworkGatewaySKUName - Gateway SKU name. +type VirtualNetworkGatewaySKUName string + +const ( + VirtualNetworkGatewaySKUNameBasic VirtualNetworkGatewaySKUName = "Basic" + VirtualNetworkGatewaySKUNameErGw1AZ VirtualNetworkGatewaySKUName = "ErGw1AZ" + VirtualNetworkGatewaySKUNameErGw2AZ VirtualNetworkGatewaySKUName = "ErGw2AZ" + VirtualNetworkGatewaySKUNameErGw3AZ VirtualNetworkGatewaySKUName = "ErGw3AZ" + VirtualNetworkGatewaySKUNameHighPerformance VirtualNetworkGatewaySKUName = "HighPerformance" + VirtualNetworkGatewaySKUNameStandard VirtualNetworkGatewaySKUName = "Standard" + VirtualNetworkGatewaySKUNameUltraPerformance VirtualNetworkGatewaySKUName = "UltraPerformance" + VirtualNetworkGatewaySKUNameVPNGw1 VirtualNetworkGatewaySKUName = "VpnGw1" + VirtualNetworkGatewaySKUNameVPNGw1AZ VirtualNetworkGatewaySKUName = "VpnGw1AZ" + VirtualNetworkGatewaySKUNameVPNGw2 VirtualNetworkGatewaySKUName = "VpnGw2" + VirtualNetworkGatewaySKUNameVPNGw2AZ VirtualNetworkGatewaySKUName = "VpnGw2AZ" + VirtualNetworkGatewaySKUNameVPNGw3 VirtualNetworkGatewaySKUName = "VpnGw3" + VirtualNetworkGatewaySKUNameVPNGw3AZ VirtualNetworkGatewaySKUName = "VpnGw3AZ" + VirtualNetworkGatewaySKUNameVPNGw4 VirtualNetworkGatewaySKUName = "VpnGw4" + VirtualNetworkGatewaySKUNameVPNGw4AZ VirtualNetworkGatewaySKUName = "VpnGw4AZ" + VirtualNetworkGatewaySKUNameVPNGw5 VirtualNetworkGatewaySKUName = "VpnGw5" + VirtualNetworkGatewaySKUNameVPNGw5AZ VirtualNetworkGatewaySKUName = "VpnGw5AZ" +) + +// PossibleVirtualNetworkGatewaySKUNameValues returns the possible values for the VirtualNetworkGatewaySKUName const type. +func PossibleVirtualNetworkGatewaySKUNameValues() []VirtualNetworkGatewaySKUName { + return []VirtualNetworkGatewaySKUName{ + VirtualNetworkGatewaySKUNameBasic, + VirtualNetworkGatewaySKUNameErGw1AZ, + VirtualNetworkGatewaySKUNameErGw2AZ, + VirtualNetworkGatewaySKUNameErGw3AZ, + VirtualNetworkGatewaySKUNameHighPerformance, + VirtualNetworkGatewaySKUNameStandard, + VirtualNetworkGatewaySKUNameUltraPerformance, + VirtualNetworkGatewaySKUNameVPNGw1, + VirtualNetworkGatewaySKUNameVPNGw1AZ, + VirtualNetworkGatewaySKUNameVPNGw2, + VirtualNetworkGatewaySKUNameVPNGw2AZ, + VirtualNetworkGatewaySKUNameVPNGw3, + VirtualNetworkGatewaySKUNameVPNGw3AZ, + VirtualNetworkGatewaySKUNameVPNGw4, + VirtualNetworkGatewaySKUNameVPNGw4AZ, + VirtualNetworkGatewaySKUNameVPNGw5, + VirtualNetworkGatewaySKUNameVPNGw5AZ, + } +} + +// VirtualNetworkGatewaySKUTier - Gateway SKU tier. +type VirtualNetworkGatewaySKUTier string + +const ( + VirtualNetworkGatewaySKUTierBasic VirtualNetworkGatewaySKUTier = "Basic" + VirtualNetworkGatewaySKUTierErGw1AZ VirtualNetworkGatewaySKUTier = "ErGw1AZ" + VirtualNetworkGatewaySKUTierErGw2AZ VirtualNetworkGatewaySKUTier = "ErGw2AZ" + VirtualNetworkGatewaySKUTierErGw3AZ VirtualNetworkGatewaySKUTier = "ErGw3AZ" + VirtualNetworkGatewaySKUTierHighPerformance VirtualNetworkGatewaySKUTier = "HighPerformance" + VirtualNetworkGatewaySKUTierStandard VirtualNetworkGatewaySKUTier = "Standard" + VirtualNetworkGatewaySKUTierUltraPerformance VirtualNetworkGatewaySKUTier = "UltraPerformance" + VirtualNetworkGatewaySKUTierVPNGw1 VirtualNetworkGatewaySKUTier = "VpnGw1" + VirtualNetworkGatewaySKUTierVPNGw1AZ VirtualNetworkGatewaySKUTier = "VpnGw1AZ" + VirtualNetworkGatewaySKUTierVPNGw2 VirtualNetworkGatewaySKUTier = "VpnGw2" + VirtualNetworkGatewaySKUTierVPNGw2AZ VirtualNetworkGatewaySKUTier = "VpnGw2AZ" + VirtualNetworkGatewaySKUTierVPNGw3 VirtualNetworkGatewaySKUTier = "VpnGw3" + VirtualNetworkGatewaySKUTierVPNGw3AZ VirtualNetworkGatewaySKUTier = "VpnGw3AZ" + VirtualNetworkGatewaySKUTierVPNGw4 VirtualNetworkGatewaySKUTier = "VpnGw4" + VirtualNetworkGatewaySKUTierVPNGw4AZ VirtualNetworkGatewaySKUTier = "VpnGw4AZ" + VirtualNetworkGatewaySKUTierVPNGw5 VirtualNetworkGatewaySKUTier = "VpnGw5" + VirtualNetworkGatewaySKUTierVPNGw5AZ VirtualNetworkGatewaySKUTier = "VpnGw5AZ" +) + +// PossibleVirtualNetworkGatewaySKUTierValues returns the possible values for the VirtualNetworkGatewaySKUTier const type. +func PossibleVirtualNetworkGatewaySKUTierValues() []VirtualNetworkGatewaySKUTier { + return []VirtualNetworkGatewaySKUTier{ + VirtualNetworkGatewaySKUTierBasic, + VirtualNetworkGatewaySKUTierErGw1AZ, + VirtualNetworkGatewaySKUTierErGw2AZ, + VirtualNetworkGatewaySKUTierErGw3AZ, + VirtualNetworkGatewaySKUTierHighPerformance, + VirtualNetworkGatewaySKUTierStandard, + VirtualNetworkGatewaySKUTierUltraPerformance, + VirtualNetworkGatewaySKUTierVPNGw1, + VirtualNetworkGatewaySKUTierVPNGw1AZ, + VirtualNetworkGatewaySKUTierVPNGw2, + VirtualNetworkGatewaySKUTierVPNGw2AZ, + VirtualNetworkGatewaySKUTierVPNGw3, + VirtualNetworkGatewaySKUTierVPNGw3AZ, + VirtualNetworkGatewaySKUTierVPNGw4, + VirtualNetworkGatewaySKUTierVPNGw4AZ, + VirtualNetworkGatewaySKUTierVPNGw5, + VirtualNetworkGatewaySKUTierVPNGw5AZ, + } +} + +// VirtualNetworkGatewayType - The type of this virtual network gateway. +type VirtualNetworkGatewayType string + +const ( + VirtualNetworkGatewayTypeExpressRoute VirtualNetworkGatewayType = "ExpressRoute" + VirtualNetworkGatewayTypeLocalGateway VirtualNetworkGatewayType = "LocalGateway" + VirtualNetworkGatewayTypeVPN VirtualNetworkGatewayType = "Vpn" +) + +// PossibleVirtualNetworkGatewayTypeValues returns the possible values for the VirtualNetworkGatewayType const type. +func PossibleVirtualNetworkGatewayTypeValues() []VirtualNetworkGatewayType { + return []VirtualNetworkGatewayType{ + VirtualNetworkGatewayTypeExpressRoute, + VirtualNetworkGatewayTypeLocalGateway, + VirtualNetworkGatewayTypeVPN, + } +} + +// VirtualNetworkPeeringLevel - The peering sync status of the virtual network peering. +type VirtualNetworkPeeringLevel string + +const ( + VirtualNetworkPeeringLevelFullyInSync VirtualNetworkPeeringLevel = "FullyInSync" + VirtualNetworkPeeringLevelLocalAndRemoteNotInSync VirtualNetworkPeeringLevel = "LocalAndRemoteNotInSync" + VirtualNetworkPeeringLevelLocalNotInSync VirtualNetworkPeeringLevel = "LocalNotInSync" + VirtualNetworkPeeringLevelRemoteNotInSync VirtualNetworkPeeringLevel = "RemoteNotInSync" +) + +// PossibleVirtualNetworkPeeringLevelValues returns the possible values for the VirtualNetworkPeeringLevel const type. +func PossibleVirtualNetworkPeeringLevelValues() []VirtualNetworkPeeringLevel { + return []VirtualNetworkPeeringLevel{ + VirtualNetworkPeeringLevelFullyInSync, + VirtualNetworkPeeringLevelLocalAndRemoteNotInSync, + VirtualNetworkPeeringLevelLocalNotInSync, + VirtualNetworkPeeringLevelRemoteNotInSync, + } +} + +// VirtualNetworkPeeringState - The status of the virtual network peering. +type VirtualNetworkPeeringState string + +const ( + VirtualNetworkPeeringStateConnected VirtualNetworkPeeringState = "Connected" + VirtualNetworkPeeringStateDisconnected VirtualNetworkPeeringState = "Disconnected" + VirtualNetworkPeeringStateInitiated VirtualNetworkPeeringState = "Initiated" +) + +// PossibleVirtualNetworkPeeringStateValues returns the possible values for the VirtualNetworkPeeringState const type. +func PossibleVirtualNetworkPeeringStateValues() []VirtualNetworkPeeringState { + return []VirtualNetworkPeeringState{ + VirtualNetworkPeeringStateConnected, + VirtualNetworkPeeringStateDisconnected, + VirtualNetworkPeeringStateInitiated, + } +} + +// VirtualNetworkPrivateEndpointNetworkPolicies - Enable or Disable apply network policies on private end point in the subnet. +type VirtualNetworkPrivateEndpointNetworkPolicies string + +const ( + VirtualNetworkPrivateEndpointNetworkPoliciesDisabled VirtualNetworkPrivateEndpointNetworkPolicies = "Disabled" + VirtualNetworkPrivateEndpointNetworkPoliciesEnabled VirtualNetworkPrivateEndpointNetworkPolicies = "Enabled" +) + +// PossibleVirtualNetworkPrivateEndpointNetworkPoliciesValues returns the possible values for the VirtualNetworkPrivateEndpointNetworkPolicies const type. +func PossibleVirtualNetworkPrivateEndpointNetworkPoliciesValues() []VirtualNetworkPrivateEndpointNetworkPolicies { + return []VirtualNetworkPrivateEndpointNetworkPolicies{ + VirtualNetworkPrivateEndpointNetworkPoliciesDisabled, + VirtualNetworkPrivateEndpointNetworkPoliciesEnabled, + } +} + +// VirtualNetworkPrivateLinkServiceNetworkPolicies - Enable or Disable apply network policies on private link service in the +// subnet. +type VirtualNetworkPrivateLinkServiceNetworkPolicies string + +const ( + VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled VirtualNetworkPrivateLinkServiceNetworkPolicies = "Disabled" + VirtualNetworkPrivateLinkServiceNetworkPoliciesEnabled VirtualNetworkPrivateLinkServiceNetworkPolicies = "Enabled" +) + +// PossibleVirtualNetworkPrivateLinkServiceNetworkPoliciesValues returns the possible values for the VirtualNetworkPrivateLinkServiceNetworkPolicies const type. +func PossibleVirtualNetworkPrivateLinkServiceNetworkPoliciesValues() []VirtualNetworkPrivateLinkServiceNetworkPolicies { + return []VirtualNetworkPrivateLinkServiceNetworkPolicies{ + VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled, + VirtualNetworkPrivateLinkServiceNetworkPoliciesEnabled, + } +} + +// VirtualWanSecurityProviderType - The virtual wan security provider type. +type VirtualWanSecurityProviderType string + +const ( + VirtualWanSecurityProviderTypeExternal VirtualWanSecurityProviderType = "External" + VirtualWanSecurityProviderTypeNative VirtualWanSecurityProviderType = "Native" +) + +// PossibleVirtualWanSecurityProviderTypeValues returns the possible values for the VirtualWanSecurityProviderType const type. +func PossibleVirtualWanSecurityProviderTypeValues() []VirtualWanSecurityProviderType { + return []VirtualWanSecurityProviderType{ + VirtualWanSecurityProviderTypeExternal, + VirtualWanSecurityProviderTypeNative, + } +} + +// VnetLocalRouteOverrideCriteria - Parameter determining whether NVA in spoke vnet is bypassed for traffic with destination +// in spoke vnet. +type VnetLocalRouteOverrideCriteria string + +const ( + VnetLocalRouteOverrideCriteriaContains VnetLocalRouteOverrideCriteria = "Contains" + VnetLocalRouteOverrideCriteriaEqual VnetLocalRouteOverrideCriteria = "Equal" +) + +// PossibleVnetLocalRouteOverrideCriteriaValues returns the possible values for the VnetLocalRouteOverrideCriteria const type. +func PossibleVnetLocalRouteOverrideCriteriaValues() []VnetLocalRouteOverrideCriteria { + return []VnetLocalRouteOverrideCriteria{ + VnetLocalRouteOverrideCriteriaContains, + VnetLocalRouteOverrideCriteriaEqual, + } +} + +// WebApplicationFirewallAction - Type of Actions. +type WebApplicationFirewallAction string + +const ( + WebApplicationFirewallActionAllow WebApplicationFirewallAction = "Allow" + WebApplicationFirewallActionBlock WebApplicationFirewallAction = "Block" + WebApplicationFirewallActionLog WebApplicationFirewallAction = "Log" +) + +// PossibleWebApplicationFirewallActionValues returns the possible values for the WebApplicationFirewallAction const type. +func PossibleWebApplicationFirewallActionValues() []WebApplicationFirewallAction { + return []WebApplicationFirewallAction{ + WebApplicationFirewallActionAllow, + WebApplicationFirewallActionBlock, + WebApplicationFirewallActionLog, + } +} + +// WebApplicationFirewallEnabledState - The state of the policy. +type WebApplicationFirewallEnabledState string + +const ( + WebApplicationFirewallEnabledStateDisabled WebApplicationFirewallEnabledState = "Disabled" + WebApplicationFirewallEnabledStateEnabled WebApplicationFirewallEnabledState = "Enabled" +) + +// PossibleWebApplicationFirewallEnabledStateValues returns the possible values for the WebApplicationFirewallEnabledState const type. +func PossibleWebApplicationFirewallEnabledStateValues() []WebApplicationFirewallEnabledState { + return []WebApplicationFirewallEnabledState{ + WebApplicationFirewallEnabledStateDisabled, + WebApplicationFirewallEnabledStateEnabled, + } +} + +// WebApplicationFirewallMatchVariable - Match Variable. +type WebApplicationFirewallMatchVariable string + +const ( + WebApplicationFirewallMatchVariablePostArgs WebApplicationFirewallMatchVariable = "PostArgs" + WebApplicationFirewallMatchVariableQueryString WebApplicationFirewallMatchVariable = "QueryString" + WebApplicationFirewallMatchVariableRemoteAddr WebApplicationFirewallMatchVariable = "RemoteAddr" + WebApplicationFirewallMatchVariableRequestBody WebApplicationFirewallMatchVariable = "RequestBody" + WebApplicationFirewallMatchVariableRequestCookies WebApplicationFirewallMatchVariable = "RequestCookies" + WebApplicationFirewallMatchVariableRequestHeaders WebApplicationFirewallMatchVariable = "RequestHeaders" + WebApplicationFirewallMatchVariableRequestMethod WebApplicationFirewallMatchVariable = "RequestMethod" + WebApplicationFirewallMatchVariableRequestURI WebApplicationFirewallMatchVariable = "RequestUri" +) + +// PossibleWebApplicationFirewallMatchVariableValues returns the possible values for the WebApplicationFirewallMatchVariable const type. +func PossibleWebApplicationFirewallMatchVariableValues() []WebApplicationFirewallMatchVariable { + return []WebApplicationFirewallMatchVariable{ + WebApplicationFirewallMatchVariablePostArgs, + WebApplicationFirewallMatchVariableQueryString, + WebApplicationFirewallMatchVariableRemoteAddr, + WebApplicationFirewallMatchVariableRequestBody, + WebApplicationFirewallMatchVariableRequestCookies, + WebApplicationFirewallMatchVariableRequestHeaders, + WebApplicationFirewallMatchVariableRequestMethod, + WebApplicationFirewallMatchVariableRequestURI, + } +} + +// WebApplicationFirewallMode - The mode of the policy. +type WebApplicationFirewallMode string + +const ( + WebApplicationFirewallModeDetection WebApplicationFirewallMode = "Detection" + WebApplicationFirewallModePrevention WebApplicationFirewallMode = "Prevention" +) + +// PossibleWebApplicationFirewallModeValues returns the possible values for the WebApplicationFirewallMode const type. +func PossibleWebApplicationFirewallModeValues() []WebApplicationFirewallMode { + return []WebApplicationFirewallMode{ + WebApplicationFirewallModeDetection, + WebApplicationFirewallModePrevention, + } +} + +// WebApplicationFirewallOperator - The operator to be matched. +type WebApplicationFirewallOperator string + +const ( + WebApplicationFirewallOperatorAny WebApplicationFirewallOperator = "Any" + WebApplicationFirewallOperatorBeginsWith WebApplicationFirewallOperator = "BeginsWith" + WebApplicationFirewallOperatorContains WebApplicationFirewallOperator = "Contains" + WebApplicationFirewallOperatorEndsWith WebApplicationFirewallOperator = "EndsWith" + WebApplicationFirewallOperatorEqual WebApplicationFirewallOperator = "Equal" + WebApplicationFirewallOperatorGeoMatch WebApplicationFirewallOperator = "GeoMatch" + WebApplicationFirewallOperatorGreaterThan WebApplicationFirewallOperator = "GreaterThan" + WebApplicationFirewallOperatorGreaterThanOrEqual WebApplicationFirewallOperator = "GreaterThanOrEqual" + WebApplicationFirewallOperatorIPMatch WebApplicationFirewallOperator = "IPMatch" + WebApplicationFirewallOperatorLessThan WebApplicationFirewallOperator = "LessThan" + WebApplicationFirewallOperatorLessThanOrEqual WebApplicationFirewallOperator = "LessThanOrEqual" + WebApplicationFirewallOperatorRegex WebApplicationFirewallOperator = "Regex" +) + +// PossibleWebApplicationFirewallOperatorValues returns the possible values for the WebApplicationFirewallOperator const type. +func PossibleWebApplicationFirewallOperatorValues() []WebApplicationFirewallOperator { + return []WebApplicationFirewallOperator{ + WebApplicationFirewallOperatorAny, + WebApplicationFirewallOperatorBeginsWith, + WebApplicationFirewallOperatorContains, + WebApplicationFirewallOperatorEndsWith, + WebApplicationFirewallOperatorEqual, + WebApplicationFirewallOperatorGeoMatch, + WebApplicationFirewallOperatorGreaterThan, + WebApplicationFirewallOperatorGreaterThanOrEqual, + WebApplicationFirewallOperatorIPMatch, + WebApplicationFirewallOperatorLessThan, + WebApplicationFirewallOperatorLessThanOrEqual, + WebApplicationFirewallOperatorRegex, + } +} + +// WebApplicationFirewallPolicyResourceState - Resource status of the policy. +type WebApplicationFirewallPolicyResourceState string + +const ( + WebApplicationFirewallPolicyResourceStateCreating WebApplicationFirewallPolicyResourceState = "Creating" + WebApplicationFirewallPolicyResourceStateDeleting WebApplicationFirewallPolicyResourceState = "Deleting" + WebApplicationFirewallPolicyResourceStateDisabled WebApplicationFirewallPolicyResourceState = "Disabled" + WebApplicationFirewallPolicyResourceStateDisabling WebApplicationFirewallPolicyResourceState = "Disabling" + WebApplicationFirewallPolicyResourceStateEnabled WebApplicationFirewallPolicyResourceState = "Enabled" + WebApplicationFirewallPolicyResourceStateEnabling WebApplicationFirewallPolicyResourceState = "Enabling" +) + +// PossibleWebApplicationFirewallPolicyResourceStateValues returns the possible values for the WebApplicationFirewallPolicyResourceState const type. +func PossibleWebApplicationFirewallPolicyResourceStateValues() []WebApplicationFirewallPolicyResourceState { + return []WebApplicationFirewallPolicyResourceState{ + WebApplicationFirewallPolicyResourceStateCreating, + WebApplicationFirewallPolicyResourceStateDeleting, + WebApplicationFirewallPolicyResourceStateDisabled, + WebApplicationFirewallPolicyResourceStateDisabling, + WebApplicationFirewallPolicyResourceStateEnabled, + WebApplicationFirewallPolicyResourceStateEnabling, + } +} + +// WebApplicationFirewallRuleType - The rule type. +type WebApplicationFirewallRuleType string + +const ( + WebApplicationFirewallRuleTypeInvalid WebApplicationFirewallRuleType = "Invalid" + WebApplicationFirewallRuleTypeMatchRule WebApplicationFirewallRuleType = "MatchRule" + WebApplicationFirewallRuleTypeRateLimitRule WebApplicationFirewallRuleType = "RateLimitRule" +) + +// PossibleWebApplicationFirewallRuleTypeValues returns the possible values for the WebApplicationFirewallRuleType const type. +func PossibleWebApplicationFirewallRuleTypeValues() []WebApplicationFirewallRuleType { + return []WebApplicationFirewallRuleType{ + WebApplicationFirewallRuleTypeInvalid, + WebApplicationFirewallRuleTypeMatchRule, + WebApplicationFirewallRuleTypeRateLimitRule, + } +} + +// WebApplicationFirewallScrubbingState - State of the log scrubbing config. Default value is Enabled. +type WebApplicationFirewallScrubbingState string + +const ( + WebApplicationFirewallScrubbingStateDisabled WebApplicationFirewallScrubbingState = "Disabled" + WebApplicationFirewallScrubbingStateEnabled WebApplicationFirewallScrubbingState = "Enabled" +) + +// PossibleWebApplicationFirewallScrubbingStateValues returns the possible values for the WebApplicationFirewallScrubbingState const type. +func PossibleWebApplicationFirewallScrubbingStateValues() []WebApplicationFirewallScrubbingState { + return []WebApplicationFirewallScrubbingState{ + WebApplicationFirewallScrubbingStateDisabled, + WebApplicationFirewallScrubbingStateEnabled, + } +} + +// WebApplicationFirewallState - Describes if the custom rule is in enabled or disabled state. Defaults to Enabled if not +// specified. +type WebApplicationFirewallState string + +const ( + WebApplicationFirewallStateDisabled WebApplicationFirewallState = "Disabled" + WebApplicationFirewallStateEnabled WebApplicationFirewallState = "Enabled" +) + +// PossibleWebApplicationFirewallStateValues returns the possible values for the WebApplicationFirewallState const type. +func PossibleWebApplicationFirewallStateValues() []WebApplicationFirewallState { + return []WebApplicationFirewallState{ + WebApplicationFirewallStateDisabled, + WebApplicationFirewallStateEnabled, + } +} + +// WebApplicationFirewallTransform - Transforms applied before matching. +type WebApplicationFirewallTransform string + +const ( + WebApplicationFirewallTransformHTMLEntityDecode WebApplicationFirewallTransform = "HtmlEntityDecode" + WebApplicationFirewallTransformLowercase WebApplicationFirewallTransform = "Lowercase" + WebApplicationFirewallTransformRemoveNulls WebApplicationFirewallTransform = "RemoveNulls" + WebApplicationFirewallTransformTrim WebApplicationFirewallTransform = "Trim" + WebApplicationFirewallTransformURLDecode WebApplicationFirewallTransform = "UrlDecode" + WebApplicationFirewallTransformURLEncode WebApplicationFirewallTransform = "UrlEncode" + WebApplicationFirewallTransformUppercase WebApplicationFirewallTransform = "Uppercase" +) + +// PossibleWebApplicationFirewallTransformValues returns the possible values for the WebApplicationFirewallTransform const type. +func PossibleWebApplicationFirewallTransformValues() []WebApplicationFirewallTransform { + return []WebApplicationFirewallTransform{ + WebApplicationFirewallTransformHTMLEntityDecode, + WebApplicationFirewallTransformLowercase, + WebApplicationFirewallTransformRemoveNulls, + WebApplicationFirewallTransformTrim, + WebApplicationFirewallTransformURLDecode, + WebApplicationFirewallTransformURLEncode, + WebApplicationFirewallTransformUppercase, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/customipprefixes_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/customipprefixes_client.go new file mode 100644 index 000000000..52935bf86 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/customipprefixes_client.go @@ -0,0 +1,454 @@ +//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 armnetwork + +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" +) + +// CustomIPPrefixesClient contains the methods for the CustomIPPrefixes group. +// Don't use this type directly, use NewCustomIPPrefixesClient() instead. +type CustomIPPrefixesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCustomIPPrefixesClient creates a new instance of CustomIPPrefixesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewCustomIPPrefixesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CustomIPPrefixesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CustomIPPrefixesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a custom IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - customIPPrefixName - The name of the custom IP prefix. +// - parameters - Parameters supplied to the create or update custom IP prefix operation. +// - options - CustomIPPrefixesClientBeginCreateOrUpdateOptions contains the optional parameters for the CustomIPPrefixesClient.BeginCreateOrUpdate +// method. +func (client *CustomIPPrefixesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters CustomIPPrefix, options *CustomIPPrefixesClientBeginCreateOrUpdateOptions) (*runtime.Poller[CustomIPPrefixesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, customIPPrefixName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CustomIPPrefixesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CustomIPPrefixesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a custom IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *CustomIPPrefixesClient) createOrUpdate(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters CustomIPPrefix, options *CustomIPPrefixesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CustomIPPrefixesClient.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, customIPPrefixName, 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 *CustomIPPrefixesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters CustomIPPrefix, options *CustomIPPrefixesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/customIpPrefixes/{customIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if customIPPrefixName == "" { + return nil, errors.New("parameter customIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{customIpPrefixName}", url.PathEscape(customIPPrefixName)) + 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-05-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 custom IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - customIPPrefixName - The name of the CustomIpPrefix. +// - options - CustomIPPrefixesClientBeginDeleteOptions contains the optional parameters for the CustomIPPrefixesClient.BeginDelete +// method. +func (client *CustomIPPrefixesClient) BeginDelete(ctx context.Context, resourceGroupName string, customIPPrefixName string, options *CustomIPPrefixesClientBeginDeleteOptions) (*runtime.Poller[CustomIPPrefixesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, customIPPrefixName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CustomIPPrefixesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CustomIPPrefixesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified custom IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *CustomIPPrefixesClient) deleteOperation(ctx context.Context, resourceGroupName string, customIPPrefixName string, options *CustomIPPrefixesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CustomIPPrefixesClient.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, customIPPrefixName, 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 *CustomIPPrefixesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, customIPPrefixName string, options *CustomIPPrefixesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/customIpPrefixes/{customIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if customIPPrefixName == "" { + return nil, errors.New("parameter customIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{customIpPrefixName}", url.PathEscape(customIPPrefixName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified custom IP prefix in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - customIPPrefixName - The name of the custom IP prefix. +// - options - CustomIPPrefixesClientGetOptions contains the optional parameters for the CustomIPPrefixesClient.Get method. +func (client *CustomIPPrefixesClient) Get(ctx context.Context, resourceGroupName string, customIPPrefixName string, options *CustomIPPrefixesClientGetOptions) (CustomIPPrefixesClientGetResponse, error) { + var err error + const operationName = "CustomIPPrefixesClient.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, customIPPrefixName, options) + if err != nil { + return CustomIPPrefixesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CustomIPPrefixesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CustomIPPrefixesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CustomIPPrefixesClient) getCreateRequest(ctx context.Context, resourceGroupName string, customIPPrefixName string, options *CustomIPPrefixesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/customIpPrefixes/{customIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if customIPPrefixName == "" { + return nil, errors.New("parameter customIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{customIpPrefixName}", url.PathEscape(customIPPrefixName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *CustomIPPrefixesClient) getHandleResponse(resp *http.Response) (CustomIPPrefixesClientGetResponse, error) { + result := CustomIPPrefixesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CustomIPPrefix); err != nil { + return CustomIPPrefixesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all custom IP prefixes in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - CustomIPPrefixesClientListOptions contains the optional parameters for the CustomIPPrefixesClient.NewListPager +// method. +func (client *CustomIPPrefixesClient) NewListPager(resourceGroupName string, options *CustomIPPrefixesClientListOptions) *runtime.Pager[CustomIPPrefixesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CustomIPPrefixesClientListResponse]{ + More: func(page CustomIPPrefixesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CustomIPPrefixesClientListResponse) (CustomIPPrefixesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CustomIPPrefixesClient.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, options) + }, nil) + if err != nil { + return CustomIPPrefixesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CustomIPPrefixesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *CustomIPPrefixesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/customIpPrefixes" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CustomIPPrefixesClient) listHandleResponse(resp *http.Response) (CustomIPPrefixesClientListResponse, error) { + result := CustomIPPrefixesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CustomIPPrefixListResult); err != nil { + return CustomIPPrefixesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the custom IP prefixes in a subscription. +// +// Generated from API version 2023-05-01 +// - options - CustomIPPrefixesClientListAllOptions contains the optional parameters for the CustomIPPrefixesClient.NewListAllPager +// method. +func (client *CustomIPPrefixesClient) NewListAllPager(options *CustomIPPrefixesClientListAllOptions) *runtime.Pager[CustomIPPrefixesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[CustomIPPrefixesClientListAllResponse]{ + More: func(page CustomIPPrefixesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CustomIPPrefixesClientListAllResponse) (CustomIPPrefixesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CustomIPPrefixesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return CustomIPPrefixesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *CustomIPPrefixesClient) listAllCreateRequest(ctx context.Context, options *CustomIPPrefixesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/customIpPrefixes" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *CustomIPPrefixesClient) listAllHandleResponse(resp *http.Response) (CustomIPPrefixesClientListAllResponse, error) { + result := CustomIPPrefixesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CustomIPPrefixListResult); err != nil { + return CustomIPPrefixesClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates custom IP prefix tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - customIPPrefixName - The name of the custom IP prefix. +// - parameters - Parameters supplied to update custom IP prefix tags. +// - options - CustomIPPrefixesClientUpdateTagsOptions contains the optional parameters for the CustomIPPrefixesClient.UpdateTags +// method. +func (client *CustomIPPrefixesClient) UpdateTags(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters TagsObject, options *CustomIPPrefixesClientUpdateTagsOptions) (CustomIPPrefixesClientUpdateTagsResponse, error) { + var err error + const operationName = "CustomIPPrefixesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, customIPPrefixName, parameters, options) + if err != nil { + return CustomIPPrefixesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CustomIPPrefixesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CustomIPPrefixesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *CustomIPPrefixesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters TagsObject, options *CustomIPPrefixesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/customIpPrefixes/{customIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if customIPPrefixName == "" { + return nil, errors.New("parameter customIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{customIpPrefixName}", url.PathEscape(customIPPrefixName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *CustomIPPrefixesClient) updateTagsHandleResponse(resp *http.Response) (CustomIPPrefixesClientUpdateTagsResponse, error) { + result := CustomIPPrefixesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CustomIPPrefix); err != nil { + return CustomIPPrefixesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ddoscustompolicies_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ddoscustompolicies_client.go new file mode 100644 index 000000000..97593c1f1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ddoscustompolicies_client.go @@ -0,0 +1,336 @@ +//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 armnetwork + +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" +) + +// DdosCustomPoliciesClient contains the methods for the DdosCustomPolicies group. +// Don't use this type directly, use NewDdosCustomPoliciesClient() instead. +type DdosCustomPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDdosCustomPoliciesClient creates a new instance of DdosCustomPoliciesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewDdosCustomPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DdosCustomPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DdosCustomPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a DDoS custom policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosCustomPolicyName - The name of the DDoS custom policy. +// - parameters - Parameters supplied to the create or update operation. +// - options - DdosCustomPoliciesClientBeginCreateOrUpdateOptions contains the optional parameters for the DdosCustomPoliciesClient.BeginCreateOrUpdate +// method. +func (client *DdosCustomPoliciesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters DdosCustomPolicy, options *DdosCustomPoliciesClientBeginCreateOrUpdateOptions) (*runtime.Poller[DdosCustomPoliciesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, ddosCustomPolicyName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DdosCustomPoliciesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DdosCustomPoliciesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a DDoS custom policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *DdosCustomPoliciesClient) createOrUpdate(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters DdosCustomPolicy, options *DdosCustomPoliciesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DdosCustomPoliciesClient.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, ddosCustomPolicyName, 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 *DdosCustomPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters DdosCustomPolicy, options *DdosCustomPoliciesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosCustomPolicies/{ddosCustomPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosCustomPolicyName == "" { + return nil, errors.New("parameter ddosCustomPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosCustomPolicyName}", url.PathEscape(ddosCustomPolicyName)) + 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-05-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 DDoS custom policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosCustomPolicyName - The name of the DDoS custom policy. +// - options - DdosCustomPoliciesClientBeginDeleteOptions contains the optional parameters for the DdosCustomPoliciesClient.BeginDelete +// method. +func (client *DdosCustomPoliciesClient) BeginDelete(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, options *DdosCustomPoliciesClientBeginDeleteOptions) (*runtime.Poller[DdosCustomPoliciesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, ddosCustomPolicyName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DdosCustomPoliciesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DdosCustomPoliciesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified DDoS custom policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *DdosCustomPoliciesClient) deleteOperation(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, options *DdosCustomPoliciesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DdosCustomPoliciesClient.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, ddosCustomPolicyName, 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 *DdosCustomPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, options *DdosCustomPoliciesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosCustomPolicies/{ddosCustomPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosCustomPolicyName == "" { + return nil, errors.New("parameter ddosCustomPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosCustomPolicyName}", url.PathEscape(ddosCustomPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about the specified DDoS custom policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosCustomPolicyName - The name of the DDoS custom policy. +// - options - DdosCustomPoliciesClientGetOptions contains the optional parameters for the DdosCustomPoliciesClient.Get method. +func (client *DdosCustomPoliciesClient) Get(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, options *DdosCustomPoliciesClientGetOptions) (DdosCustomPoliciesClientGetResponse, error) { + var err error + const operationName = "DdosCustomPoliciesClient.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, ddosCustomPolicyName, options) + if err != nil { + return DdosCustomPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DdosCustomPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DdosCustomPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DdosCustomPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, options *DdosCustomPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosCustomPolicies/{ddosCustomPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosCustomPolicyName == "" { + return nil, errors.New("parameter ddosCustomPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosCustomPolicyName}", url.PathEscape(ddosCustomPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DdosCustomPoliciesClient) getHandleResponse(resp *http.Response) (DdosCustomPoliciesClientGetResponse, error) { + result := DdosCustomPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DdosCustomPolicy); err != nil { + return DdosCustomPoliciesClientGetResponse{}, err + } + return result, nil +} + +// UpdateTags - Update a DDoS custom policy tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosCustomPolicyName - The name of the DDoS custom policy. +// - parameters - Parameters supplied to update DDoS custom policy resource tags. +// - options - DdosCustomPoliciesClientUpdateTagsOptions contains the optional parameters for the DdosCustomPoliciesClient.UpdateTags +// method. +func (client *DdosCustomPoliciesClient) UpdateTags(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters TagsObject, options *DdosCustomPoliciesClientUpdateTagsOptions) (DdosCustomPoliciesClientUpdateTagsResponse, error) { + var err error + const operationName = "DdosCustomPoliciesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, ddosCustomPolicyName, parameters, options) + if err != nil { + return DdosCustomPoliciesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DdosCustomPoliciesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DdosCustomPoliciesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *DdosCustomPoliciesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters TagsObject, options *DdosCustomPoliciesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosCustomPolicies/{ddosCustomPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosCustomPolicyName == "" { + return nil, errors.New("parameter ddosCustomPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosCustomPolicyName}", url.PathEscape(ddosCustomPolicyName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *DdosCustomPoliciesClient) updateTagsHandleResponse(resp *http.Response) (DdosCustomPoliciesClientUpdateTagsResponse, error) { + result := DdosCustomPoliciesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DdosCustomPolicy); err != nil { + return DdosCustomPoliciesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ddosprotectionplans_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ddosprotectionplans_client.go new file mode 100644 index 000000000..24e240859 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ddosprotectionplans_client.go @@ -0,0 +1,451 @@ +//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 armnetwork + +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" +) + +// DdosProtectionPlansClient contains the methods for the DdosProtectionPlans group. +// Don't use this type directly, use NewDdosProtectionPlansClient() instead. +type DdosProtectionPlansClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDdosProtectionPlansClient creates a new instance of DdosProtectionPlansClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewDdosProtectionPlansClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DdosProtectionPlansClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DdosProtectionPlansClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a DDoS protection plan. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosProtectionPlanName - The name of the DDoS protection plan. +// - parameters - Parameters supplied to the create or update operation. +// - options - DdosProtectionPlansClientBeginCreateOrUpdateOptions contains the optional parameters for the DdosProtectionPlansClient.BeginCreateOrUpdate +// method. +func (client *DdosProtectionPlansClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan, options *DdosProtectionPlansClientBeginCreateOrUpdateOptions) (*runtime.Poller[DdosProtectionPlansClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, ddosProtectionPlanName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DdosProtectionPlansClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DdosProtectionPlansClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a DDoS protection plan. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *DdosProtectionPlansClient) createOrUpdate(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan, options *DdosProtectionPlansClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DdosProtectionPlansClient.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, ddosProtectionPlanName, 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 *DdosProtectionPlansClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan, options *DdosProtectionPlansClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosProtectionPlanName == "" { + return nil, errors.New("parameter ddosProtectionPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosProtectionPlanName}", url.PathEscape(ddosProtectionPlanName)) + 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-05-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 DDoS protection plan. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosProtectionPlanName - The name of the DDoS protection plan. +// - options - DdosProtectionPlansClientBeginDeleteOptions contains the optional parameters for the DdosProtectionPlansClient.BeginDelete +// method. +func (client *DdosProtectionPlansClient) BeginDelete(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, options *DdosProtectionPlansClientBeginDeleteOptions) (*runtime.Poller[DdosProtectionPlansClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, ddosProtectionPlanName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DdosProtectionPlansClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DdosProtectionPlansClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified DDoS protection plan. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *DdosProtectionPlansClient) deleteOperation(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, options *DdosProtectionPlansClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DdosProtectionPlansClient.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, ddosProtectionPlanName, 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 *DdosProtectionPlansClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, options *DdosProtectionPlansClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosProtectionPlanName == "" { + return nil, errors.New("parameter ddosProtectionPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosProtectionPlanName}", url.PathEscape(ddosProtectionPlanName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about the specified DDoS protection plan. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosProtectionPlanName - The name of the DDoS protection plan. +// - options - DdosProtectionPlansClientGetOptions contains the optional parameters for the DdosProtectionPlansClient.Get method. +func (client *DdosProtectionPlansClient) Get(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, options *DdosProtectionPlansClientGetOptions) (DdosProtectionPlansClientGetResponse, error) { + var err error + const operationName = "DdosProtectionPlansClient.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, ddosProtectionPlanName, options) + if err != nil { + return DdosProtectionPlansClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DdosProtectionPlansClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DdosProtectionPlansClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DdosProtectionPlansClient) getCreateRequest(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, options *DdosProtectionPlansClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosProtectionPlanName == "" { + return nil, errors.New("parameter ddosProtectionPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosProtectionPlanName}", url.PathEscape(ddosProtectionPlanName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DdosProtectionPlansClient) getHandleResponse(resp *http.Response) (DdosProtectionPlansClientGetResponse, error) { + result := DdosProtectionPlansClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DdosProtectionPlan); err != nil { + return DdosProtectionPlansClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all DDoS protection plans in a subscription. +// +// Generated from API version 2023-05-01 +// - options - DdosProtectionPlansClientListOptions contains the optional parameters for the DdosProtectionPlansClient.NewListPager +// method. +func (client *DdosProtectionPlansClient) NewListPager(options *DdosProtectionPlansClientListOptions) *runtime.Pager[DdosProtectionPlansClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DdosProtectionPlansClientListResponse]{ + More: func(page DdosProtectionPlansClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DdosProtectionPlansClientListResponse) (DdosProtectionPlansClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DdosProtectionPlansClient.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 DdosProtectionPlansClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DdosProtectionPlansClient) listCreateRequest(ctx context.Context, options *DdosProtectionPlansClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/ddosProtectionPlans" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DdosProtectionPlansClient) listHandleResponse(resp *http.Response) (DdosProtectionPlansClientListResponse, error) { + result := DdosProtectionPlansClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DdosProtectionPlanListResult); err != nil { + return DdosProtectionPlansClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all the DDoS protection plans in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - DdosProtectionPlansClientListByResourceGroupOptions contains the optional parameters for the DdosProtectionPlansClient.NewListByResourceGroupPager +// method. +func (client *DdosProtectionPlansClient) NewListByResourceGroupPager(resourceGroupName string, options *DdosProtectionPlansClientListByResourceGroupOptions) *runtime.Pager[DdosProtectionPlansClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DdosProtectionPlansClientListByResourceGroupResponse]{ + More: func(page DdosProtectionPlansClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DdosProtectionPlansClientListByResourceGroupResponse) (DdosProtectionPlansClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DdosProtectionPlansClient.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 DdosProtectionPlansClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *DdosProtectionPlansClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DdosProtectionPlansClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *DdosProtectionPlansClient) listByResourceGroupHandleResponse(resp *http.Response) (DdosProtectionPlansClientListByResourceGroupResponse, error) { + result := DdosProtectionPlansClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DdosProtectionPlanListResult); err != nil { + return DdosProtectionPlansClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Update a DDoS protection plan tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ddosProtectionPlanName - The name of the DDoS protection plan. +// - parameters - Parameters supplied to the update DDoS protection plan resource tags. +// - options - DdosProtectionPlansClientUpdateTagsOptions contains the optional parameters for the DdosProtectionPlansClient.UpdateTags +// method. +func (client *DdosProtectionPlansClient) UpdateTags(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters TagsObject, options *DdosProtectionPlansClientUpdateTagsOptions) (DdosProtectionPlansClientUpdateTagsResponse, error) { + var err error + const operationName = "DdosProtectionPlansClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, ddosProtectionPlanName, parameters, options) + if err != nil { + return DdosProtectionPlansClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DdosProtectionPlansClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DdosProtectionPlansClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *DdosProtectionPlansClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters TagsObject, options *DdosProtectionPlansClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ddosProtectionPlanName == "" { + return nil, errors.New("parameter ddosProtectionPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ddosProtectionPlanName}", url.PathEscape(ddosProtectionPlanName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *DdosProtectionPlansClient) updateTagsHandleResponse(resp *http.Response) (DdosProtectionPlansClientUpdateTagsResponse, error) { + result := DdosProtectionPlansClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DdosProtectionPlan); err != nil { + return DdosProtectionPlansClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/defaultsecurityrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/defaultsecurityrules_client.go new file mode 100644 index 000000000..3ebcfd56e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/defaultsecurityrules_client.go @@ -0,0 +1,180 @@ +//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 armnetwork + +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" +) + +// DefaultSecurityRulesClient contains the methods for the DefaultSecurityRules group. +// Don't use this type directly, use NewDefaultSecurityRulesClient() instead. +type DefaultSecurityRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDefaultSecurityRulesClient creates a new instance of DefaultSecurityRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewDefaultSecurityRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DefaultSecurityRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DefaultSecurityRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get the specified default network security rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - defaultSecurityRuleName - The name of the default security rule. +// - options - DefaultSecurityRulesClientGetOptions contains the optional parameters for the DefaultSecurityRulesClient.Get +// method. +func (client *DefaultSecurityRulesClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string, options *DefaultSecurityRulesClientGetOptions) (DefaultSecurityRulesClientGetResponse, error) { + var err error + const operationName = "DefaultSecurityRulesClient.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, networkSecurityGroupName, defaultSecurityRuleName, options) + if err != nil { + return DefaultSecurityRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DefaultSecurityRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DefaultSecurityRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DefaultSecurityRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string, options *DefaultSecurityRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + if defaultSecurityRuleName == "" { + return nil, errors.New("parameter defaultSecurityRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{defaultSecurityRuleName}", url.PathEscape(defaultSecurityRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DefaultSecurityRulesClient) getHandleResponse(resp *http.Response) (DefaultSecurityRulesClientGetResponse, error) { + result := DefaultSecurityRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityRule); err != nil { + return DefaultSecurityRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all default security rules in a network security group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - options - DefaultSecurityRulesClientListOptions contains the optional parameters for the DefaultSecurityRulesClient.NewListPager +// method. +func (client *DefaultSecurityRulesClient) NewListPager(resourceGroupName string, networkSecurityGroupName string, options *DefaultSecurityRulesClientListOptions) *runtime.Pager[DefaultSecurityRulesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DefaultSecurityRulesClientListResponse]{ + More: func(page DefaultSecurityRulesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DefaultSecurityRulesClientListResponse) (DefaultSecurityRulesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DefaultSecurityRulesClient.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, networkSecurityGroupName, options) + }, nil) + if err != nil { + return DefaultSecurityRulesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DefaultSecurityRulesClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, options *DefaultSecurityRulesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DefaultSecurityRulesClient) listHandleResponse(resp *http.Response) (DefaultSecurityRulesClientListResponse, error) { + result := DefaultSecurityRulesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityRuleListResult); err != nil { + return DefaultSecurityRulesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/dscpconfiguration_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/dscpconfiguration_client.go new file mode 100644 index 000000000..733734d3c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/dscpconfiguration_client.go @@ -0,0 +1,382 @@ +//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 armnetwork + +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" +) + +// DscpConfigurationClient contains the methods for the DscpConfiguration group. +// Don't use this type directly, use NewDscpConfigurationClient() instead. +type DscpConfigurationClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDscpConfigurationClient creates a new instance of DscpConfigurationClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewDscpConfigurationClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DscpConfigurationClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DscpConfigurationClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a DSCP Configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - dscpConfigurationName - The name of the resource. +// - parameters - Parameters supplied to the create or update dscp configuration operation. +// - options - DscpConfigurationClientBeginCreateOrUpdateOptions contains the optional parameters for the DscpConfigurationClient.BeginCreateOrUpdate +// method. +func (client *DscpConfigurationClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, dscpConfigurationName string, parameters DscpConfiguration, options *DscpConfigurationClientBeginCreateOrUpdateOptions) (*runtime.Poller[DscpConfigurationClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, dscpConfigurationName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DscpConfigurationClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DscpConfigurationClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a DSCP Configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *DscpConfigurationClient) createOrUpdate(ctx context.Context, resourceGroupName string, dscpConfigurationName string, parameters DscpConfiguration, options *DscpConfigurationClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DscpConfigurationClient.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, dscpConfigurationName, 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 *DscpConfigurationClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, dscpConfigurationName string, parameters DscpConfiguration, options *DscpConfigurationClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dscpConfigurations/{dscpConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if dscpConfigurationName == "" { + return nil, errors.New("parameter dscpConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dscpConfigurationName}", url.PathEscape(dscpConfigurationName)) + 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-05-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 a DSCP Configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - dscpConfigurationName - The name of the resource. +// - options - DscpConfigurationClientBeginDeleteOptions contains the optional parameters for the DscpConfigurationClient.BeginDelete +// method. +func (client *DscpConfigurationClient) BeginDelete(ctx context.Context, resourceGroupName string, dscpConfigurationName string, options *DscpConfigurationClientBeginDeleteOptions) (*runtime.Poller[DscpConfigurationClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, dscpConfigurationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DscpConfigurationClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DscpConfigurationClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a DSCP Configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *DscpConfigurationClient) deleteOperation(ctx context.Context, resourceGroupName string, dscpConfigurationName string, options *DscpConfigurationClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DscpConfigurationClient.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, dscpConfigurationName, 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 *DscpConfigurationClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, dscpConfigurationName string, options *DscpConfigurationClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dscpConfigurations/{dscpConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if dscpConfigurationName == "" { + return nil, errors.New("parameter dscpConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dscpConfigurationName}", url.PathEscape(dscpConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a DSCP Configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - dscpConfigurationName - The name of the resource. +// - options - DscpConfigurationClientGetOptions contains the optional parameters for the DscpConfigurationClient.Get method. +func (client *DscpConfigurationClient) Get(ctx context.Context, resourceGroupName string, dscpConfigurationName string, options *DscpConfigurationClientGetOptions) (DscpConfigurationClientGetResponse, error) { + var err error + const operationName = "DscpConfigurationClient.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, dscpConfigurationName, options) + if err != nil { + return DscpConfigurationClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DscpConfigurationClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DscpConfigurationClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DscpConfigurationClient) getCreateRequest(ctx context.Context, resourceGroupName string, dscpConfigurationName string, options *DscpConfigurationClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dscpConfigurations/{dscpConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if dscpConfigurationName == "" { + return nil, errors.New("parameter dscpConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dscpConfigurationName}", url.PathEscape(dscpConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DscpConfigurationClient) getHandleResponse(resp *http.Response) (DscpConfigurationClientGetResponse, error) { + result := DscpConfigurationClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DscpConfiguration); err != nil { + return DscpConfigurationClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a DSCP Configuration. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - DscpConfigurationClientListOptions contains the optional parameters for the DscpConfigurationClient.NewListPager +// method. +func (client *DscpConfigurationClient) NewListPager(resourceGroupName string, options *DscpConfigurationClientListOptions) *runtime.Pager[DscpConfigurationClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DscpConfigurationClientListResponse]{ + More: func(page DscpConfigurationClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DscpConfigurationClientListResponse) (DscpConfigurationClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DscpConfigurationClient.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, options) + }, nil) + if err != nil { + return DscpConfigurationClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DscpConfigurationClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *DscpConfigurationClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dscpConfigurations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DscpConfigurationClient) listHandleResponse(resp *http.Response) (DscpConfigurationClientListResponse, error) { + result := DscpConfigurationClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DscpConfigurationListResult); err != nil { + return DscpConfigurationClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all dscp configurations in a subscription. +// +// Generated from API version 2023-05-01 +// - options - DscpConfigurationClientListAllOptions contains the optional parameters for the DscpConfigurationClient.NewListAllPager +// method. +func (client *DscpConfigurationClient) NewListAllPager(options *DscpConfigurationClientListAllOptions) *runtime.Pager[DscpConfigurationClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[DscpConfigurationClientListAllResponse]{ + More: func(page DscpConfigurationClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DscpConfigurationClientListAllResponse) (DscpConfigurationClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DscpConfigurationClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return DscpConfigurationClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *DscpConfigurationClient) listAllCreateRequest(ctx context.Context, options *DscpConfigurationClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/dscpConfigurations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *DscpConfigurationClient) listAllHandleResponse(resp *http.Response) (DscpConfigurationClientListAllResponse, error) { + result := DscpConfigurationClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DscpConfigurationListResult); err != nil { + return DscpConfigurationClientListAllResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitauthorizations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitauthorizations_client.go new file mode 100644 index 000000000..91d2d8c29 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitauthorizations_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ExpressRouteCircuitAuthorizationsClient contains the methods for the ExpressRouteCircuitAuthorizations group. +// Don't use this type directly, use NewExpressRouteCircuitAuthorizationsClient() instead. +type ExpressRouteCircuitAuthorizationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteCircuitAuthorizationsClient creates a new instance of ExpressRouteCircuitAuthorizationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteCircuitAuthorizationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteCircuitAuthorizationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteCircuitAuthorizationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an authorization in the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - authorizationName - The name of the authorization. +// - authorizationParameters - Parameters supplied to the create or update express route circuit authorization operation. +// - options - ExpressRouteCircuitAuthorizationsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRouteCircuitAuthorizationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, options *ExpressRouteCircuitAuthorizationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteCircuitAuthorizationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, circuitName, authorizationName, authorizationParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitAuthorizationsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitAuthorizationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an authorization in the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitAuthorizationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, options *ExpressRouteCircuitAuthorizationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitAuthorizationsClient.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, circuitName, authorizationName, authorizationParameters, 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 *ExpressRouteCircuitAuthorizationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, options *ExpressRouteCircuitAuthorizationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if authorizationName == "" { + return nil, errors.New("parameter authorizationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationName}", url.PathEscape(authorizationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, authorizationParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified authorization from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - authorizationName - The name of the authorization. +// - options - ExpressRouteCircuitAuthorizationsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.BeginDelete +// method. +func (client *ExpressRouteCircuitAuthorizationsClient) BeginDelete(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, options *ExpressRouteCircuitAuthorizationsClientBeginDeleteOptions) (*runtime.Poller[ExpressRouteCircuitAuthorizationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, circuitName, authorizationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitAuthorizationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitAuthorizationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified authorization from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitAuthorizationsClient) deleteOperation(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, options *ExpressRouteCircuitAuthorizationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitAuthorizationsClient.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, circuitName, authorizationName, 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 *ExpressRouteCircuitAuthorizationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, options *ExpressRouteCircuitAuthorizationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if authorizationName == "" { + return nil, errors.New("parameter authorizationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationName}", url.PathEscape(authorizationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified authorization from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - authorizationName - The name of the authorization. +// - options - ExpressRouteCircuitAuthorizationsClientGetOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.Get +// method. +func (client *ExpressRouteCircuitAuthorizationsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, options *ExpressRouteCircuitAuthorizationsClientGetOptions) (ExpressRouteCircuitAuthorizationsClientGetResponse, error) { + var err error + const operationName = "ExpressRouteCircuitAuthorizationsClient.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, circuitName, authorizationName, options) + if err != nil { + return ExpressRouteCircuitAuthorizationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCircuitAuthorizationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCircuitAuthorizationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteCircuitAuthorizationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, options *ExpressRouteCircuitAuthorizationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if authorizationName == "" { + return nil, errors.New("parameter authorizationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationName}", url.PathEscape(authorizationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteCircuitAuthorizationsClient) getHandleResponse(resp *http.Response) (ExpressRouteCircuitAuthorizationsClientGetResponse, error) { + result := ExpressRouteCircuitAuthorizationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitAuthorization); err != nil { + return ExpressRouteCircuitAuthorizationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all authorizations in an express route circuit. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the circuit. +// - options - ExpressRouteCircuitAuthorizationsClientListOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.NewListPager +// method. +func (client *ExpressRouteCircuitAuthorizationsClient) NewListPager(resourceGroupName string, circuitName string, options *ExpressRouteCircuitAuthorizationsClientListOptions) *runtime.Pager[ExpressRouteCircuitAuthorizationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCircuitAuthorizationsClientListResponse]{ + More: func(page ExpressRouteCircuitAuthorizationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCircuitAuthorizationsClientListResponse) (ExpressRouteCircuitAuthorizationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCircuitAuthorizationsClient.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, circuitName, options) + }, nil) + if err != nil { + return ExpressRouteCircuitAuthorizationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteCircuitAuthorizationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitAuthorizationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteCircuitAuthorizationsClient) listHandleResponse(resp *http.Response) (ExpressRouteCircuitAuthorizationsClientListResponse, error) { + result := ExpressRouteCircuitAuthorizationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationListResult); err != nil { + return ExpressRouteCircuitAuthorizationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitconnections_client.go new file mode 100644 index 000000000..e07aaa0b0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitconnections_client.go @@ -0,0 +1,369 @@ +//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 armnetwork + +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" +) + +// ExpressRouteCircuitConnectionsClient contains the methods for the ExpressRouteCircuitConnections group. +// Don't use this type directly, use NewExpressRouteCircuitConnectionsClient() instead. +type ExpressRouteCircuitConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteCircuitConnectionsClient creates a new instance of ExpressRouteCircuitConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteCircuitConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteCircuitConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteCircuitConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a Express Route Circuit Connection in the specified express route circuits. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - connectionName - The name of the express route circuit connection. +// - expressRouteCircuitConnectionParameters - Parameters supplied to the create or update express route circuit connection +// operation. +// - options - ExpressRouteCircuitConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRouteCircuitConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection, options *ExpressRouteCircuitConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteCircuitConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a Express Route Circuit Connection in the specified express route circuits. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection, options *ExpressRouteCircuitConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitConnectionsClient.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, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters, 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 *ExpressRouteCircuitConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection, options *ExpressRouteCircuitConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, expressRouteCircuitConnectionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified Express Route Circuit Connection from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - connectionName - The name of the express route circuit connection. +// - options - ExpressRouteCircuitConnectionsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.BeginDelete +// method. +func (client *ExpressRouteCircuitConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, options *ExpressRouteCircuitConnectionsClientBeginDeleteOptions) (*runtime.Poller[ExpressRouteCircuitConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, circuitName, peeringName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Express Route Circuit Connection from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, options *ExpressRouteCircuitConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitConnectionsClient.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, circuitName, peeringName, connectionName, 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 *ExpressRouteCircuitConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, options *ExpressRouteCircuitConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Express Route Circuit Connection from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - connectionName - The name of the express route circuit connection. +// - options - ExpressRouteCircuitConnectionsClientGetOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.Get +// method. +func (client *ExpressRouteCircuitConnectionsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, options *ExpressRouteCircuitConnectionsClientGetOptions) (ExpressRouteCircuitConnectionsClientGetResponse, error) { + var err error + const operationName = "ExpressRouteCircuitConnectionsClient.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, circuitName, peeringName, connectionName, options) + if err != nil { + return ExpressRouteCircuitConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCircuitConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCircuitConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteCircuitConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, options *ExpressRouteCircuitConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteCircuitConnectionsClient) getHandleResponse(resp *http.Response) (ExpressRouteCircuitConnectionsClientGetResponse, error) { + result := ExpressRouteCircuitConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitConnection); err != nil { + return ExpressRouteCircuitConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all global reach connections associated with a private peering in an express route circuit. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the circuit. +// - peeringName - The name of the peering. +// - options - ExpressRouteCircuitConnectionsClientListOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.NewListPager +// method. +func (client *ExpressRouteCircuitConnectionsClient) NewListPager(resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitConnectionsClientListOptions) *runtime.Pager[ExpressRouteCircuitConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCircuitConnectionsClientListResponse]{ + More: func(page ExpressRouteCircuitConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCircuitConnectionsClientListResponse) (ExpressRouteCircuitConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCircuitConnectionsClient.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, circuitName, peeringName, options) + }, nil) + if err != nil { + return ExpressRouteCircuitConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteCircuitConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteCircuitConnectionsClient) listHandleResponse(resp *http.Response) (ExpressRouteCircuitConnectionsClientListResponse, error) { + result := ExpressRouteCircuitConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitConnectionListResult); err != nil { + return ExpressRouteCircuitConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitpeerings_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitpeerings_client.go new file mode 100644 index 000000000..4d849efaf --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuitpeerings_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ExpressRouteCircuitPeeringsClient contains the methods for the ExpressRouteCircuitPeerings group. +// Don't use this type directly, use NewExpressRouteCircuitPeeringsClient() instead. +type ExpressRouteCircuitPeeringsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteCircuitPeeringsClient creates a new instance of ExpressRouteCircuitPeeringsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteCircuitPeeringsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteCircuitPeeringsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteCircuitPeeringsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a peering in the specified express route circuits. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - peeringParameters - Parameters supplied to the create or update express route circuit peering operation. +// - options - ExpressRouteCircuitPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRouteCircuitPeeringsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, options *ExpressRouteCircuitPeeringsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteCircuitPeeringsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, circuitName, peeringName, peeringParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitPeeringsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitPeeringsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a peering in the specified express route circuits. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitPeeringsClient) createOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, options *ExpressRouteCircuitPeeringsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitPeeringsClient.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, circuitName, peeringName, peeringParameters, 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 *ExpressRouteCircuitPeeringsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, options *ExpressRouteCircuitPeeringsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, peeringParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified peering from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - options - ExpressRouteCircuitPeeringsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.BeginDelete +// method. +func (client *ExpressRouteCircuitPeeringsClient) BeginDelete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitPeeringsClientBeginDeleteOptions) (*runtime.Poller[ExpressRouteCircuitPeeringsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, circuitName, peeringName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitPeeringsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitPeeringsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified peering from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitPeeringsClient) deleteOperation(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitPeeringsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitPeeringsClient.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, circuitName, peeringName, 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 *ExpressRouteCircuitPeeringsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitPeeringsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified peering for the express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - options - ExpressRouteCircuitPeeringsClientGetOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.Get +// method. +func (client *ExpressRouteCircuitPeeringsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitPeeringsClientGetOptions) (ExpressRouteCircuitPeeringsClientGetResponse, error) { + var err error + const operationName = "ExpressRouteCircuitPeeringsClient.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, circuitName, peeringName, options) + if err != nil { + return ExpressRouteCircuitPeeringsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCircuitPeeringsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCircuitPeeringsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteCircuitPeeringsClient) getCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitPeeringsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteCircuitPeeringsClient) getHandleResponse(resp *http.Response) (ExpressRouteCircuitPeeringsClientGetResponse, error) { + result := ExpressRouteCircuitPeeringsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitPeering); err != nil { + return ExpressRouteCircuitPeeringsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all peerings in a specified express route circuit. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - options - ExpressRouteCircuitPeeringsClientListOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.NewListPager +// method. +func (client *ExpressRouteCircuitPeeringsClient) NewListPager(resourceGroupName string, circuitName string, options *ExpressRouteCircuitPeeringsClientListOptions) *runtime.Pager[ExpressRouteCircuitPeeringsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCircuitPeeringsClientListResponse]{ + More: func(page ExpressRouteCircuitPeeringsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCircuitPeeringsClientListResponse) (ExpressRouteCircuitPeeringsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCircuitPeeringsClient.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, circuitName, options) + }, nil) + if err != nil { + return ExpressRouteCircuitPeeringsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteCircuitPeeringsClient) listCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitPeeringsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteCircuitPeeringsClient) listHandleResponse(resp *http.Response) (ExpressRouteCircuitPeeringsClientListResponse, error) { + result := ExpressRouteCircuitPeeringsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitPeeringListResult); err != nil { + return ExpressRouteCircuitPeeringsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuits_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuits_client.go new file mode 100644 index 000000000..e106f07bc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecircuits_client.go @@ -0,0 +1,851 @@ +//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 armnetwork + +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" +) + +// ExpressRouteCircuitsClient contains the methods for the ExpressRouteCircuits group. +// Don't use this type directly, use NewExpressRouteCircuitsClient() instead. +type ExpressRouteCircuitsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteCircuitsClient creates a new instance of ExpressRouteCircuitsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteCircuitsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteCircuitsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteCircuitsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the circuit. +// - parameters - Parameters supplied to the create or update express route circuit operation. +// - options - ExpressRouteCircuitsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRouteCircuitsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, options *ExpressRouteCircuitsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteCircuitsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, circuitName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitsClient) createOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, options *ExpressRouteCircuitsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.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, circuitName, 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 *ExpressRouteCircuitsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, options *ExpressRouteCircuitsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + 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-05-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 express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - options - ExpressRouteCircuitsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginDelete +// method. +func (client *ExpressRouteCircuitsClient) BeginDelete(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitsClientBeginDeleteOptions) (*runtime.Poller[ExpressRouteCircuitsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, circuitName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitsClient) deleteOperation(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.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, circuitName, 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 *ExpressRouteCircuitsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of express route circuit. +// - options - ExpressRouteCircuitsClientGetOptions contains the optional parameters for the ExpressRouteCircuitsClient.Get +// method. +func (client *ExpressRouteCircuitsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitsClientGetOptions) (ExpressRouteCircuitsClientGetResponse, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.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, circuitName, options) + if err != nil { + return ExpressRouteCircuitsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCircuitsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCircuitsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteCircuitsClient) getCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteCircuitsClient) getHandleResponse(resp *http.Response) (ExpressRouteCircuitsClientGetResponse, error) { + result := ExpressRouteCircuitsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuit); err != nil { + return ExpressRouteCircuitsClientGetResponse{}, err + } + return result, nil +} + +// GetPeeringStats - Gets all stats from an express route circuit in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - options - ExpressRouteCircuitsClientGetPeeringStatsOptions contains the optional parameters for the ExpressRouteCircuitsClient.GetPeeringStats +// method. +func (client *ExpressRouteCircuitsClient) GetPeeringStats(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitsClientGetPeeringStatsOptions) (ExpressRouteCircuitsClientGetPeeringStatsResponse, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.GetPeeringStats" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPeeringStatsCreateRequest(ctx, resourceGroupName, circuitName, peeringName, options) + if err != nil { + return ExpressRouteCircuitsClientGetPeeringStatsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCircuitsClientGetPeeringStatsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCircuitsClientGetPeeringStatsResponse{}, err + } + resp, err := client.getPeeringStatsHandleResponse(httpResp) + return resp, err +} + +// getPeeringStatsCreateRequest creates the GetPeeringStats request. +func (client *ExpressRouteCircuitsClient) getPeeringStatsCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *ExpressRouteCircuitsClientGetPeeringStatsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/stats" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getPeeringStatsHandleResponse handles the GetPeeringStats response. +func (client *ExpressRouteCircuitsClient) getPeeringStatsHandleResponse(resp *http.Response) (ExpressRouteCircuitsClientGetPeeringStatsResponse, error) { + result := ExpressRouteCircuitsClientGetPeeringStatsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitStats); err != nil { + return ExpressRouteCircuitsClientGetPeeringStatsResponse{}, err + } + return result, nil +} + +// GetStats - Gets all the stats from an express route circuit in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - options - ExpressRouteCircuitsClientGetStatsOptions contains the optional parameters for the ExpressRouteCircuitsClient.GetStats +// method. +func (client *ExpressRouteCircuitsClient) GetStats(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitsClientGetStatsOptions) (ExpressRouteCircuitsClientGetStatsResponse, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.GetStats" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStatsCreateRequest(ctx, resourceGroupName, circuitName, options) + if err != nil { + return ExpressRouteCircuitsClientGetStatsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCircuitsClientGetStatsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCircuitsClientGetStatsResponse{}, err + } + resp, err := client.getStatsHandleResponse(httpResp) + return resp, err +} + +// getStatsCreateRequest creates the GetStats request. +func (client *ExpressRouteCircuitsClient) getStatsCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, options *ExpressRouteCircuitsClientGetStatsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/stats" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getStatsHandleResponse handles the GetStats response. +func (client *ExpressRouteCircuitsClient) getStatsHandleResponse(resp *http.Response) (ExpressRouteCircuitsClientGetStatsResponse, error) { + result := ExpressRouteCircuitsClientGetStatsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitStats); err != nil { + return ExpressRouteCircuitsClientGetStatsResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the express route circuits in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ExpressRouteCircuitsClientListOptions contains the optional parameters for the ExpressRouteCircuitsClient.NewListPager +// method. +func (client *ExpressRouteCircuitsClient) NewListPager(resourceGroupName string, options *ExpressRouteCircuitsClientListOptions) *runtime.Pager[ExpressRouteCircuitsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCircuitsClientListResponse]{ + More: func(page ExpressRouteCircuitsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCircuitsClientListResponse) (ExpressRouteCircuitsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCircuitsClient.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, options) + }, nil) + if err != nil { + return ExpressRouteCircuitsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteCircuitsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *ExpressRouteCircuitsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteCircuitsClient) listHandleResponse(resp *http.Response) (ExpressRouteCircuitsClientListResponse, error) { + result := ExpressRouteCircuitsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitListResult); err != nil { + return ExpressRouteCircuitsClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the express route circuits in a subscription. +// +// Generated from API version 2023-05-01 +// - options - ExpressRouteCircuitsClientListAllOptions contains the optional parameters for the ExpressRouteCircuitsClient.NewListAllPager +// method. +func (client *ExpressRouteCircuitsClient) NewListAllPager(options *ExpressRouteCircuitsClientListAllOptions) *runtime.Pager[ExpressRouteCircuitsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCircuitsClientListAllResponse]{ + More: func(page ExpressRouteCircuitsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCircuitsClientListAllResponse) (ExpressRouteCircuitsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCircuitsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return ExpressRouteCircuitsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *ExpressRouteCircuitsClient) listAllCreateRequest(ctx context.Context, options *ExpressRouteCircuitsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCircuits" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *ExpressRouteCircuitsClient) listAllHandleResponse(resp *http.Response) (ExpressRouteCircuitsClientListAllResponse, error) { + result := ExpressRouteCircuitsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuitListResult); err != nil { + return ExpressRouteCircuitsClientListAllResponse{}, err + } + return result, nil +} + +// BeginListArpTable - Gets the currently advertised ARP table associated with the express route circuit in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - devicePath - The path of the device. +// - options - ExpressRouteCircuitsClientBeginListArpTableOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginListArpTable +// method. +func (client *ExpressRouteCircuitsClient) BeginListArpTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListArpTableOptions) (*runtime.Poller[ExpressRouteCircuitsClientListArpTableResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listArpTable(ctx, resourceGroupName, circuitName, peeringName, devicePath, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitsClientListArpTableResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitsClientListArpTableResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListArpTable - Gets the currently advertised ARP table associated with the express route circuit in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitsClient) listArpTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListArpTableOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.BeginListArpTable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listArpTableCreateRequest(ctx, resourceGroupName, circuitName, peeringName, devicePath, 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 +} + +// listArpTableCreateRequest creates the ListArpTable request. +func (client *ExpressRouteCircuitsClient) listArpTableCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListArpTableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/arpTables/{devicePath}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if devicePath == "" { + return nil, errors.New("parameter devicePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{devicePath}", url.PathEscape(devicePath)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginListRoutesTable - Gets the currently advertised routes table associated with the express route circuit in a resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - devicePath - The path of the device. +// - options - ExpressRouteCircuitsClientBeginListRoutesTableOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginListRoutesTable +// method. +func (client *ExpressRouteCircuitsClient) BeginListRoutesTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListRoutesTableOptions) (*runtime.Poller[ExpressRouteCircuitsClientListRoutesTableResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listRoutesTable(ctx, resourceGroupName, circuitName, peeringName, devicePath, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitsClientListRoutesTableResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitsClientListRoutesTableResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListRoutesTable - Gets the currently advertised routes table associated with the express route circuit in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitsClient) listRoutesTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListRoutesTableOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.BeginListRoutesTable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listRoutesTableCreateRequest(ctx, resourceGroupName, circuitName, peeringName, devicePath, 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 +} + +// listRoutesTableCreateRequest creates the ListRoutesTable request. +func (client *ExpressRouteCircuitsClient) listRoutesTableCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListRoutesTableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTables/{devicePath}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if devicePath == "" { + return nil, errors.New("parameter devicePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{devicePath}", url.PathEscape(devicePath)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginListRoutesTableSummary - Gets the currently advertised routes table summary associated with the express route circuit +// in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - devicePath - The path of the device. +// - options - ExpressRouteCircuitsClientBeginListRoutesTableSummaryOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginListRoutesTableSummary +// method. +func (client *ExpressRouteCircuitsClient) BeginListRoutesTableSummary(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListRoutesTableSummaryOptions) (*runtime.Poller[ExpressRouteCircuitsClientListRoutesTableSummaryResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listRoutesTableSummary(ctx, resourceGroupName, circuitName, peeringName, devicePath, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCircuitsClientListRoutesTableSummaryResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCircuitsClientListRoutesTableSummaryResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListRoutesTableSummary - Gets the currently advertised routes table summary associated with the express route circuit in +// a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCircuitsClient) listRoutesTableSummary(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListRoutesTableSummaryOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.BeginListRoutesTableSummary" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listRoutesTableSummaryCreateRequest(ctx, resourceGroupName, circuitName, peeringName, devicePath, 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 +} + +// listRoutesTableSummaryCreateRequest creates the ListRoutesTableSummary request. +func (client *ExpressRouteCircuitsClient) listRoutesTableSummaryCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string, options *ExpressRouteCircuitsClientBeginListRoutesTableSummaryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTablesSummary/{devicePath}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if devicePath == "" { + return nil, errors.New("parameter devicePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{devicePath}", url.PathEscape(devicePath)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// UpdateTags - Updates an express route circuit tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the circuit. +// - parameters - Parameters supplied to update express route circuit tags. +// - options - ExpressRouteCircuitsClientUpdateTagsOptions contains the optional parameters for the ExpressRouteCircuitsClient.UpdateTags +// method. +func (client *ExpressRouteCircuitsClient) UpdateTags(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject, options *ExpressRouteCircuitsClientUpdateTagsOptions) (ExpressRouteCircuitsClientUpdateTagsResponse, error) { + var err error + const operationName = "ExpressRouteCircuitsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, circuitName, parameters, options) + if err != nil { + return ExpressRouteCircuitsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCircuitsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCircuitsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ExpressRouteCircuitsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject, options *ExpressRouteCircuitsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ExpressRouteCircuitsClient) updateTagsHandleResponse(resp *http.Response) (ExpressRouteCircuitsClientUpdateTagsResponse, error) { + result := ExpressRouteCircuitsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCircuit); err != nil { + return ExpressRouteCircuitsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteconnections_client.go new file mode 100644 index 000000000..40d454090 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteconnections_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ExpressRouteConnectionsClient contains the methods for the ExpressRouteConnections group. +// Don't use this type directly, use NewExpressRouteConnectionsClient() instead. +type ExpressRouteConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteConnectionsClient creates a new instance of ExpressRouteConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a connection between an ExpressRoute gateway and an ExpressRoute circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRouteGatewayName - The name of the ExpressRoute gateway. +// - connectionName - The name of the connection subresource. +// - putExpressRouteConnectionParameters - Parameters required in an ExpressRouteConnection PUT operation. +// - options - ExpressRouteConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteConnectionsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRouteConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, putExpressRouteConnectionParameters ExpressRouteConnection, options *ExpressRouteConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, expressRouteGatewayName, connectionName, putExpressRouteConnectionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a connection between an ExpressRoute gateway and an ExpressRoute circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, putExpressRouteConnectionParameters ExpressRouteConnection, options *ExpressRouteConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteConnectionsClient.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, expressRouteGatewayName, connectionName, putExpressRouteConnectionParameters, 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 *ExpressRouteConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, putExpressRouteConnectionParameters ExpressRouteConnection, options *ExpressRouteConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, putExpressRouteConnectionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a connection to a ExpressRoute circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRouteGatewayName - The name of the ExpressRoute gateway. +// - connectionName - The name of the connection subresource. +// - options - ExpressRouteConnectionsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteConnectionsClient.BeginDelete +// method. +func (client *ExpressRouteConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, options *ExpressRouteConnectionsClientBeginDeleteOptions) (*runtime.Poller[ExpressRouteConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, expressRouteGatewayName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a connection to a ExpressRoute circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, options *ExpressRouteConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteConnectionsClient.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, expressRouteGatewayName, connectionName, 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 *ExpressRouteConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, options *ExpressRouteConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified ExpressRouteConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRouteGatewayName - The name of the ExpressRoute gateway. +// - connectionName - The name of the ExpressRoute connection. +// - options - ExpressRouteConnectionsClientGetOptions contains the optional parameters for the ExpressRouteConnectionsClient.Get +// method. +func (client *ExpressRouteConnectionsClient) Get(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, options *ExpressRouteConnectionsClientGetOptions) (ExpressRouteConnectionsClientGetResponse, error) { + var err error + const operationName = "ExpressRouteConnectionsClient.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, expressRouteGatewayName, connectionName, options) + if err != nil { + return ExpressRouteConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, options *ExpressRouteConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteConnectionsClient) getHandleResponse(resp *http.Response) (ExpressRouteConnectionsClientGetResponse, error) { + result := ExpressRouteConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteConnection); err != nil { + return ExpressRouteConnectionsClientGetResponse{}, err + } + return result, nil +} + +// List - Lists ExpressRouteConnections. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRouteGatewayName - The name of the ExpressRoute gateway. +// - options - ExpressRouteConnectionsClientListOptions contains the optional parameters for the ExpressRouteConnectionsClient.List +// method. +func (client *ExpressRouteConnectionsClient) List(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, options *ExpressRouteConnectionsClientListOptions) (ExpressRouteConnectionsClientListResponse, error) { + var err error + const operationName = "ExpressRouteConnectionsClient.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, expressRouteGatewayName, options) + if err != nil { + return ExpressRouteConnectionsClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteConnectionsClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteConnectionsClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, options *ExpressRouteConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteConnectionsClient) listHandleResponse(resp *http.Response) (ExpressRouteConnectionsClientListResponse, error) { + result := ExpressRouteConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteConnectionList); err != nil { + return ExpressRouteConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecrossconnectionpeerings_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecrossconnectionpeerings_client.go new file mode 100644 index 000000000..b3eb6901b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecrossconnectionpeerings_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ExpressRouteCrossConnectionPeeringsClient contains the methods for the ExpressRouteCrossConnectionPeerings group. +// Don't use this type directly, use NewExpressRouteCrossConnectionPeeringsClient() instead. +type ExpressRouteCrossConnectionPeeringsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteCrossConnectionPeeringsClient creates a new instance of ExpressRouteCrossConnectionPeeringsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteCrossConnectionPeeringsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteCrossConnectionPeeringsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteCrossConnectionPeeringsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a peering in the specified ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - peeringName - The name of the peering. +// - peeringParameters - Parameters supplied to the create or update ExpressRouteCrossConnection peering operation. +// - options - ExpressRouteCrossConnectionPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the +// ExpressRouteCrossConnectionPeeringsClient.BeginCreateOrUpdate method. +func (client *ExpressRouteCrossConnectionPeeringsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering, options *ExpressRouteCrossConnectionPeeringsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteCrossConnectionPeeringsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, crossConnectionName, peeringName, peeringParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCrossConnectionPeeringsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCrossConnectionPeeringsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a peering in the specified ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCrossConnectionPeeringsClient) createOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering, options *ExpressRouteCrossConnectionPeeringsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCrossConnectionPeeringsClient.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, crossConnectionName, peeringName, peeringParameters, 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 *ExpressRouteCrossConnectionPeeringsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering, options *ExpressRouteCrossConnectionPeeringsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, peeringParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified peering from the ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - peeringName - The name of the peering. +// - options - ExpressRouteCrossConnectionPeeringsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCrossConnectionPeeringsClient.BeginDelete +// method. +func (client *ExpressRouteCrossConnectionPeeringsClient) BeginDelete(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, options *ExpressRouteCrossConnectionPeeringsClientBeginDeleteOptions) (*runtime.Poller[ExpressRouteCrossConnectionPeeringsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, crossConnectionName, peeringName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCrossConnectionPeeringsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCrossConnectionPeeringsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified peering from the ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCrossConnectionPeeringsClient) deleteOperation(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, options *ExpressRouteCrossConnectionPeeringsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCrossConnectionPeeringsClient.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, crossConnectionName, peeringName, 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 *ExpressRouteCrossConnectionPeeringsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, options *ExpressRouteCrossConnectionPeeringsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified peering for the ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - peeringName - The name of the peering. +// - options - ExpressRouteCrossConnectionPeeringsClientGetOptions contains the optional parameters for the ExpressRouteCrossConnectionPeeringsClient.Get +// method. +func (client *ExpressRouteCrossConnectionPeeringsClient) Get(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, options *ExpressRouteCrossConnectionPeeringsClientGetOptions) (ExpressRouteCrossConnectionPeeringsClientGetResponse, error) { + var err error + const operationName = "ExpressRouteCrossConnectionPeeringsClient.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, crossConnectionName, peeringName, options) + if err != nil { + return ExpressRouteCrossConnectionPeeringsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCrossConnectionPeeringsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCrossConnectionPeeringsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteCrossConnectionPeeringsClient) getCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, options *ExpressRouteCrossConnectionPeeringsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteCrossConnectionPeeringsClient) getHandleResponse(resp *http.Response) (ExpressRouteCrossConnectionPeeringsClientGetResponse, error) { + result := ExpressRouteCrossConnectionPeeringsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCrossConnectionPeering); err != nil { + return ExpressRouteCrossConnectionPeeringsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all peerings in a specified ExpressRouteCrossConnection. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - options - ExpressRouteCrossConnectionPeeringsClientListOptions contains the optional parameters for the ExpressRouteCrossConnectionPeeringsClient.NewListPager +// method. +func (client *ExpressRouteCrossConnectionPeeringsClient) NewListPager(resourceGroupName string, crossConnectionName string, options *ExpressRouteCrossConnectionPeeringsClientListOptions) *runtime.Pager[ExpressRouteCrossConnectionPeeringsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCrossConnectionPeeringsClientListResponse]{ + More: func(page ExpressRouteCrossConnectionPeeringsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCrossConnectionPeeringsClientListResponse) (ExpressRouteCrossConnectionPeeringsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCrossConnectionPeeringsClient.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, crossConnectionName, options) + }, nil) + if err != nil { + return ExpressRouteCrossConnectionPeeringsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteCrossConnectionPeeringsClient) listCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, options *ExpressRouteCrossConnectionPeeringsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteCrossConnectionPeeringsClient) listHandleResponse(resp *http.Response) (ExpressRouteCrossConnectionPeeringsClientListResponse, error) { + result := ExpressRouteCrossConnectionPeeringsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCrossConnectionPeeringList); err != nil { + return ExpressRouteCrossConnectionPeeringsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecrossconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecrossconnections_client.go new file mode 100644 index 000000000..0419a5555 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutecrossconnections_client.go @@ -0,0 +1,642 @@ +//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 armnetwork + +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" +) + +// ExpressRouteCrossConnectionsClient contains the methods for the ExpressRouteCrossConnections group. +// Don't use this type directly, use NewExpressRouteCrossConnectionsClient() instead. +type ExpressRouteCrossConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteCrossConnectionsClient creates a new instance of ExpressRouteCrossConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteCrossConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteCrossConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteCrossConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Update the specified ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - parameters - Parameters supplied to the update express route crossConnection operation. +// - options - ExpressRouteCrossConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRouteCrossConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, parameters ExpressRouteCrossConnection, options *ExpressRouteCrossConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteCrossConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, crossConnectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCrossConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCrossConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Update the specified ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCrossConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, parameters ExpressRouteCrossConnection, options *ExpressRouteCrossConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCrossConnectionsClient.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, crossConnectionName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ExpressRouteCrossConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, parameters ExpressRouteCrossConnection, options *ExpressRouteCrossConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + 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-05-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 +} + +// Get - Gets details about the specified ExpressRouteCrossConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group (peering location of the circuit). +// - crossConnectionName - The name of the ExpressRouteCrossConnection (service key of the circuit). +// - options - ExpressRouteCrossConnectionsClientGetOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.Get +// method. +func (client *ExpressRouteCrossConnectionsClient) Get(ctx context.Context, resourceGroupName string, crossConnectionName string, options *ExpressRouteCrossConnectionsClientGetOptions) (ExpressRouteCrossConnectionsClientGetResponse, error) { + var err error + const operationName = "ExpressRouteCrossConnectionsClient.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, crossConnectionName, options) + if err != nil { + return ExpressRouteCrossConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCrossConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCrossConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteCrossConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, options *ExpressRouteCrossConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteCrossConnectionsClient) getHandleResponse(resp *http.Response) (ExpressRouteCrossConnectionsClientGetResponse, error) { + result := ExpressRouteCrossConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCrossConnection); err != nil { + return ExpressRouteCrossConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves all the ExpressRouteCrossConnections in a subscription. +// +// Generated from API version 2023-05-01 +// - options - ExpressRouteCrossConnectionsClientListOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.NewListPager +// method. +func (client *ExpressRouteCrossConnectionsClient) NewListPager(options *ExpressRouteCrossConnectionsClientListOptions) *runtime.Pager[ExpressRouteCrossConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCrossConnectionsClientListResponse]{ + More: func(page ExpressRouteCrossConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCrossConnectionsClientListResponse) (ExpressRouteCrossConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCrossConnectionsClient.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 ExpressRouteCrossConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteCrossConnectionsClient) listCreateRequest(ctx context.Context, options *ExpressRouteCrossConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCrossConnections" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteCrossConnectionsClient) listHandleResponse(resp *http.Response) (ExpressRouteCrossConnectionsClientListResponse, error) { + result := ExpressRouteCrossConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCrossConnectionListResult); err != nil { + return ExpressRouteCrossConnectionsClientListResponse{}, err + } + return result, nil +} + +// BeginListArpTable - Gets the currently advertised ARP table associated with the express route cross connection in a resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - peeringName - The name of the peering. +// - devicePath - The path of the device. +// - options - ExpressRouteCrossConnectionsClientBeginListArpTableOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.BeginListArpTable +// method. +func (client *ExpressRouteCrossConnectionsClient) BeginListArpTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListArpTableOptions) (*runtime.Poller[ExpressRouteCrossConnectionsClientListArpTableResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listArpTable(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCrossConnectionsClientListArpTableResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCrossConnectionsClientListArpTableResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListArpTable - Gets the currently advertised ARP table associated with the express route cross connection in a resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCrossConnectionsClient) listArpTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListArpTableOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCrossConnectionsClient.BeginListArpTable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listArpTableCreateRequest(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath, 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 +} + +// listArpTableCreateRequest creates the ListArpTable request. +func (client *ExpressRouteCrossConnectionsClient) listArpTableCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListArpTableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/arpTables/{devicePath}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if devicePath == "" { + return nil, errors.New("parameter devicePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{devicePath}", url.PathEscape(devicePath)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// NewListByResourceGroupPager - Retrieves all the ExpressRouteCrossConnections in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ExpressRouteCrossConnectionsClientListByResourceGroupOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.NewListByResourceGroupPager +// method. +func (client *ExpressRouteCrossConnectionsClient) NewListByResourceGroupPager(resourceGroupName string, options *ExpressRouteCrossConnectionsClientListByResourceGroupOptions) *runtime.Pager[ExpressRouteCrossConnectionsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteCrossConnectionsClientListByResourceGroupResponse]{ + More: func(page ExpressRouteCrossConnectionsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteCrossConnectionsClientListByResourceGroupResponse) (ExpressRouteCrossConnectionsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteCrossConnectionsClient.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 ExpressRouteCrossConnectionsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ExpressRouteCrossConnectionsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ExpressRouteCrossConnectionsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ExpressRouteCrossConnectionsClient) listByResourceGroupHandleResponse(resp *http.Response) (ExpressRouteCrossConnectionsClientListByResourceGroupResponse, error) { + result := ExpressRouteCrossConnectionsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCrossConnectionListResult); err != nil { + return ExpressRouteCrossConnectionsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginListRoutesTable - Gets the currently advertised routes table associated with the express route cross connection in +// a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - peeringName - The name of the peering. +// - devicePath - The path of the device. +// - options - ExpressRouteCrossConnectionsClientBeginListRoutesTableOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.BeginListRoutesTable +// method. +func (client *ExpressRouteCrossConnectionsClient) BeginListRoutesTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListRoutesTableOptions) (*runtime.Poller[ExpressRouteCrossConnectionsClientListRoutesTableResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listRoutesTable(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCrossConnectionsClientListRoutesTableResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCrossConnectionsClientListRoutesTableResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListRoutesTable - Gets the currently advertised routes table associated with the express route cross connection in a resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCrossConnectionsClient) listRoutesTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListRoutesTableOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCrossConnectionsClient.BeginListRoutesTable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listRoutesTableCreateRequest(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath, 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 +} + +// listRoutesTableCreateRequest creates the ListRoutesTable request. +func (client *ExpressRouteCrossConnectionsClient) listRoutesTableCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListRoutesTableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTables/{devicePath}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if devicePath == "" { + return nil, errors.New("parameter devicePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{devicePath}", url.PathEscape(devicePath)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginListRoutesTableSummary - Gets the route table summary associated with the express route cross connection in a resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the ExpressRouteCrossConnection. +// - peeringName - The name of the peering. +// - devicePath - The path of the device. +// - options - ExpressRouteCrossConnectionsClientBeginListRoutesTableSummaryOptions contains the optional parameters for the +// ExpressRouteCrossConnectionsClient.BeginListRoutesTableSummary method. +func (client *ExpressRouteCrossConnectionsClient) BeginListRoutesTableSummary(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListRoutesTableSummaryOptions) (*runtime.Poller[ExpressRouteCrossConnectionsClientListRoutesTableSummaryResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listRoutesTableSummary(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteCrossConnectionsClientListRoutesTableSummaryResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteCrossConnectionsClientListRoutesTableSummaryResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListRoutesTableSummary - Gets the route table summary associated with the express route cross connection in a resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteCrossConnectionsClient) listRoutesTableSummary(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListRoutesTableSummaryOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteCrossConnectionsClient.BeginListRoutesTableSummary" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listRoutesTableSummaryCreateRequest(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath, 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 +} + +// listRoutesTableSummaryCreateRequest creates the ListRoutesTableSummary request. +func (client *ExpressRouteCrossConnectionsClient) listRoutesTableSummaryCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string, options *ExpressRouteCrossConnectionsClientBeginListRoutesTableSummaryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTablesSummary/{devicePath}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if devicePath == "" { + return nil, errors.New("parameter devicePath cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{devicePath}", url.PathEscape(devicePath)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// UpdateTags - Updates an express route cross connection tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - crossConnectionName - The name of the cross connection. +// - crossConnectionParameters - Parameters supplied to update express route cross connection tags. +// - options - ExpressRouteCrossConnectionsClientUpdateTagsOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.UpdateTags +// method. +func (client *ExpressRouteCrossConnectionsClient) UpdateTags(ctx context.Context, resourceGroupName string, crossConnectionName string, crossConnectionParameters TagsObject, options *ExpressRouteCrossConnectionsClientUpdateTagsOptions) (ExpressRouteCrossConnectionsClientUpdateTagsResponse, error) { + var err error + const operationName = "ExpressRouteCrossConnectionsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, crossConnectionName, crossConnectionParameters, options) + if err != nil { + return ExpressRouteCrossConnectionsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteCrossConnectionsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteCrossConnectionsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ExpressRouteCrossConnectionsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, crossConnectionName string, crossConnectionParameters TagsObject, options *ExpressRouteCrossConnectionsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if crossConnectionName == "" { + return nil, errors.New("parameter crossConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{crossConnectionName}", url.PathEscape(crossConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, crossConnectionParameters); err != nil { + return nil, err + } + return req, nil +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ExpressRouteCrossConnectionsClient) updateTagsHandleResponse(resp *http.Response) (ExpressRouteCrossConnectionsClientUpdateTagsResponse, error) { + result := ExpressRouteCrossConnectionsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteCrossConnection); err != nil { + return ExpressRouteCrossConnectionsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutegateways_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutegateways_client.go new file mode 100644 index 000000000..e2b0b5e7a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutegateways_client.go @@ -0,0 +1,466 @@ +//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 armnetwork + +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" +) + +// ExpressRouteGatewaysClient contains the methods for the ExpressRouteGateways group. +// Don't use this type directly, use NewExpressRouteGatewaysClient() instead. +type ExpressRouteGatewaysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteGatewaysClient creates a new instance of ExpressRouteGatewaysClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteGatewaysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteGatewaysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteGatewaysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a ExpressRoute gateway in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRouteGatewayName - The name of the ExpressRoute gateway. +// - putExpressRouteGatewayParameters - Parameters required in an ExpressRoute gateway PUT operation. +// - options - ExpressRouteGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteGatewaysClient.BeginCreateOrUpdate +// method. +func (client *ExpressRouteGatewaysClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, putExpressRouteGatewayParameters ExpressRouteGateway, options *ExpressRouteGatewaysClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRouteGatewaysClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, expressRouteGatewayName, putExpressRouteGatewayParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteGatewaysClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteGatewaysClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a ExpressRoute gateway in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteGatewaysClient) createOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, putExpressRouteGatewayParameters ExpressRouteGateway, options *ExpressRouteGatewaysClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteGatewaysClient.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, expressRouteGatewayName, putExpressRouteGatewayParameters, 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 *ExpressRouteGatewaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, putExpressRouteGatewayParameters ExpressRouteGateway, options *ExpressRouteGatewaysClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, putExpressRouteGatewayParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified ExpressRoute gateway in a resource group. An ExpressRoute gateway resource can only +// be deleted when there are no connection subresources. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRouteGatewayName - The name of the ExpressRoute gateway. +// - options - ExpressRouteGatewaysClientBeginDeleteOptions contains the optional parameters for the ExpressRouteGatewaysClient.BeginDelete +// method. +func (client *ExpressRouteGatewaysClient) BeginDelete(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, options *ExpressRouteGatewaysClientBeginDeleteOptions) (*runtime.Poller[ExpressRouteGatewaysClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, expressRouteGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteGatewaysClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteGatewaysClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified ExpressRoute gateway in a resource group. An ExpressRoute gateway resource can only be deleted +// when there are no connection subresources. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteGatewaysClient) deleteOperation(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, options *ExpressRouteGatewaysClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteGatewaysClient.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, expressRouteGatewayName, 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 *ExpressRouteGatewaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, options *ExpressRouteGatewaysClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Fetches the details of a ExpressRoute gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRouteGatewayName - The name of the ExpressRoute gateway. +// - options - ExpressRouteGatewaysClientGetOptions contains the optional parameters for the ExpressRouteGatewaysClient.Get +// method. +func (client *ExpressRouteGatewaysClient) Get(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, options *ExpressRouteGatewaysClientGetOptions) (ExpressRouteGatewaysClientGetResponse, error) { + var err error + const operationName = "ExpressRouteGatewaysClient.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, expressRouteGatewayName, options) + if err != nil { + return ExpressRouteGatewaysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteGatewaysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteGatewaysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteGatewaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, options *ExpressRouteGatewaysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteGatewaysClient) getHandleResponse(resp *http.Response) (ExpressRouteGatewaysClientGetResponse, error) { + result := ExpressRouteGatewaysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteGateway); err != nil { + return ExpressRouteGatewaysClientGetResponse{}, err + } + return result, nil +} + +// ListByResourceGroup - Lists ExpressRoute gateways in a given resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ExpressRouteGatewaysClientListByResourceGroupOptions contains the optional parameters for the ExpressRouteGatewaysClient.ListByResourceGroup +// method. +func (client *ExpressRouteGatewaysClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, options *ExpressRouteGatewaysClientListByResourceGroupOptions) (ExpressRouteGatewaysClientListByResourceGroupResponse, error) { + var err error + const operationName = "ExpressRouteGatewaysClient.ListByResourceGroup" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + if err != nil { + return ExpressRouteGatewaysClientListByResourceGroupResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteGatewaysClientListByResourceGroupResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteGatewaysClientListByResourceGroupResponse{}, err + } + resp, err := client.listByResourceGroupHandleResponse(httpResp) + return resp, err +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ExpressRouteGatewaysClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ExpressRouteGatewaysClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ExpressRouteGatewaysClient) listByResourceGroupHandleResponse(resp *http.Response) (ExpressRouteGatewaysClientListByResourceGroupResponse, error) { + result := ExpressRouteGatewaysClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteGatewayList); err != nil { + return ExpressRouteGatewaysClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// ListBySubscription - Lists ExpressRoute gateways under a given subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - options - ExpressRouteGatewaysClientListBySubscriptionOptions contains the optional parameters for the ExpressRouteGatewaysClient.ListBySubscription +// method. +func (client *ExpressRouteGatewaysClient) ListBySubscription(ctx context.Context, options *ExpressRouteGatewaysClientListBySubscriptionOptions) (ExpressRouteGatewaysClientListBySubscriptionResponse, error) { + var err error + const operationName = "ExpressRouteGatewaysClient.ListBySubscription" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listBySubscriptionCreateRequest(ctx, options) + if err != nil { + return ExpressRouteGatewaysClientListBySubscriptionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteGatewaysClientListBySubscriptionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteGatewaysClientListBySubscriptionResponse{}, err + } + resp, err := client.listBySubscriptionHandleResponse(httpResp) + return resp, err +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ExpressRouteGatewaysClient) listBySubscriptionCreateRequest(ctx context.Context, options *ExpressRouteGatewaysClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ExpressRouteGatewaysClient) listBySubscriptionHandleResponse(resp *http.Response) (ExpressRouteGatewaysClientListBySubscriptionResponse, error) { + result := ExpressRouteGatewaysClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteGatewayList); err != nil { + return ExpressRouteGatewaysClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdateTags - Updates express route gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the ExpressRouteGateway. +// - expressRouteGatewayName - The name of the gateway. +// - expressRouteGatewayParameters - Parameters supplied to update a virtual wan express route gateway tags. +// - options - ExpressRouteGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the ExpressRouteGatewaysClient.BeginUpdateTags +// method. +func (client *ExpressRouteGatewaysClient) BeginUpdateTags(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, expressRouteGatewayParameters TagsObject, options *ExpressRouteGatewaysClientBeginUpdateTagsOptions) (*runtime.Poller[ExpressRouteGatewaysClientUpdateTagsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateTags(ctx, resourceGroupName, expressRouteGatewayName, expressRouteGatewayParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRouteGatewaysClientUpdateTagsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRouteGatewaysClientUpdateTagsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateTags - Updates express route gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRouteGatewaysClient) updateTags(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, expressRouteGatewayParameters TagsObject, options *ExpressRouteGatewaysClientBeginUpdateTagsOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRouteGatewaysClient.BeginUpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, expressRouteGatewayName, expressRouteGatewayParameters, 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 +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ExpressRouteGatewaysClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, expressRouteGatewayParameters TagsObject, options *ExpressRouteGatewaysClientBeginUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}" + 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 expressRouteGatewayName == "" { + return nil, errors.New("parameter expressRouteGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRouteGatewayName}", url.PathEscape(expressRouteGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, expressRouteGatewayParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutelinks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutelinks_client.go new file mode 100644 index 000000000..99ea0d4b6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressroutelinks_client.go @@ -0,0 +1,179 @@ +//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 armnetwork + +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" +) + +// ExpressRouteLinksClient contains the methods for the ExpressRouteLinks group. +// Don't use this type directly, use NewExpressRouteLinksClient() instead. +type ExpressRouteLinksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteLinksClient creates a new instance of ExpressRouteLinksClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteLinksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteLinksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteLinksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Retrieves the specified ExpressRouteLink resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the ExpressRoutePort resource. +// - linkName - The name of the ExpressRouteLink resource. +// - options - ExpressRouteLinksClientGetOptions contains the optional parameters for the ExpressRouteLinksClient.Get method. +func (client *ExpressRouteLinksClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string, linkName string, options *ExpressRouteLinksClientGetOptions) (ExpressRouteLinksClientGetResponse, error) { + var err error + const operationName = "ExpressRouteLinksClient.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, expressRoutePortName, linkName, options) + if err != nil { + return ExpressRouteLinksClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteLinksClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteLinksClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRouteLinksClient) getCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, linkName string, options *ExpressRouteLinksClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links/{linkName}" + 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 expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + if linkName == "" { + return nil, errors.New("parameter linkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{linkName}", url.PathEscape(linkName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRouteLinksClient) getHandleResponse(resp *http.Response) (ExpressRouteLinksClientGetResponse, error) { + result := ExpressRouteLinksClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteLink); err != nil { + return ExpressRouteLinksClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort resource. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the ExpressRoutePort resource. +// - options - ExpressRouteLinksClientListOptions contains the optional parameters for the ExpressRouteLinksClient.NewListPager +// method. +func (client *ExpressRouteLinksClient) NewListPager(resourceGroupName string, expressRoutePortName string, options *ExpressRouteLinksClientListOptions) *runtime.Pager[ExpressRouteLinksClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteLinksClientListResponse]{ + More: func(page ExpressRouteLinksClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteLinksClientListResponse) (ExpressRouteLinksClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteLinksClient.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, expressRoutePortName, options) + }, nil) + if err != nil { + return ExpressRouteLinksClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteLinksClient) listCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, options *ExpressRouteLinksClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links" + 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 expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteLinksClient) listHandleResponse(resp *http.Response) (ExpressRouteLinksClientListResponse, error) { + result := ExpressRouteLinksClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteLinkListResult); err != nil { + return ExpressRouteLinksClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteportauthorizations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteportauthorizations_client.go new file mode 100644 index 000000000..ec6e1737b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteportauthorizations_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ExpressRoutePortAuthorizationsClient contains the methods for the ExpressRoutePortAuthorizations group. +// Don't use this type directly, use NewExpressRoutePortAuthorizationsClient() instead. +type ExpressRoutePortAuthorizationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRoutePortAuthorizationsClient creates a new instance of ExpressRoutePortAuthorizationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRoutePortAuthorizationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRoutePortAuthorizationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRoutePortAuthorizationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an authorization in the specified express route port. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the express route port. +// - authorizationName - The name of the authorization. +// - authorizationParameters - Parameters supplied to the create or update express route port authorization operation. +// - options - ExpressRoutePortAuthorizationsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRoutePortAuthorizationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, authorizationParameters ExpressRoutePortAuthorization, options *ExpressRoutePortAuthorizationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRoutePortAuthorizationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, expressRoutePortName, authorizationName, authorizationParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRoutePortAuthorizationsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRoutePortAuthorizationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an authorization in the specified express route port. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRoutePortAuthorizationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, authorizationParameters ExpressRoutePortAuthorization, options *ExpressRoutePortAuthorizationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRoutePortAuthorizationsClient.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, expressRoutePortName, authorizationName, authorizationParameters, 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 *ExpressRoutePortAuthorizationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, authorizationParameters ExpressRoutePortAuthorization, options *ExpressRoutePortAuthorizationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRoutePorts/{expressRoutePortName}/authorizations/{authorizationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + if authorizationName == "" { + return nil, errors.New("parameter authorizationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationName}", url.PathEscape(authorizationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, authorizationParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified authorization from the specified express route port. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the express route port. +// - authorizationName - The name of the authorization. +// - options - ExpressRoutePortAuthorizationsClientBeginDeleteOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.BeginDelete +// method. +func (client *ExpressRoutePortAuthorizationsClient) BeginDelete(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, options *ExpressRoutePortAuthorizationsClientBeginDeleteOptions) (*runtime.Poller[ExpressRoutePortAuthorizationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, expressRoutePortName, authorizationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRoutePortAuthorizationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRoutePortAuthorizationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified authorization from the specified express route port. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRoutePortAuthorizationsClient) deleteOperation(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, options *ExpressRoutePortAuthorizationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRoutePortAuthorizationsClient.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, expressRoutePortName, authorizationName, 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 *ExpressRoutePortAuthorizationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, options *ExpressRoutePortAuthorizationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRoutePorts/{expressRoutePortName}/authorizations/{authorizationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + if authorizationName == "" { + return nil, errors.New("parameter authorizationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationName}", url.PathEscape(authorizationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified authorization from the specified express route port. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the express route port. +// - authorizationName - The name of the authorization. +// - options - ExpressRoutePortAuthorizationsClientGetOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.Get +// method. +func (client *ExpressRoutePortAuthorizationsClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, options *ExpressRoutePortAuthorizationsClientGetOptions) (ExpressRoutePortAuthorizationsClientGetResponse, error) { + var err error + const operationName = "ExpressRoutePortAuthorizationsClient.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, expressRoutePortName, authorizationName, options) + if err != nil { + return ExpressRoutePortAuthorizationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRoutePortAuthorizationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRoutePortAuthorizationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRoutePortAuthorizationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, options *ExpressRoutePortAuthorizationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRoutePorts/{expressRoutePortName}/authorizations/{authorizationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + if authorizationName == "" { + return nil, errors.New("parameter authorizationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationName}", url.PathEscape(authorizationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRoutePortAuthorizationsClient) getHandleResponse(resp *http.Response) (ExpressRoutePortAuthorizationsClientGetResponse, error) { + result := ExpressRoutePortAuthorizationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePortAuthorization); err != nil { + return ExpressRoutePortAuthorizationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all authorizations in an express route port. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the express route port. +// - options - ExpressRoutePortAuthorizationsClientListOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.NewListPager +// method. +func (client *ExpressRoutePortAuthorizationsClient) NewListPager(resourceGroupName string, expressRoutePortName string, options *ExpressRoutePortAuthorizationsClientListOptions) *runtime.Pager[ExpressRoutePortAuthorizationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRoutePortAuthorizationsClientListResponse]{ + More: func(page ExpressRoutePortAuthorizationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRoutePortAuthorizationsClientListResponse) (ExpressRoutePortAuthorizationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRoutePortAuthorizationsClient.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, expressRoutePortName, options) + }, nil) + if err != nil { + return ExpressRoutePortAuthorizationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRoutePortAuthorizationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, options *ExpressRoutePortAuthorizationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRoutePorts/{expressRoutePortName}/authorizations" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRoutePortAuthorizationsClient) listHandleResponse(resp *http.Response) (ExpressRoutePortAuthorizationsClientListResponse, error) { + result := ExpressRoutePortAuthorizationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePortAuthorizationListResult); err != nil { + return ExpressRoutePortAuthorizationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteports_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteports_client.go new file mode 100644 index 000000000..4811abea7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteports_client.go @@ -0,0 +1,520 @@ +//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 armnetwork + +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" +) + +// ExpressRoutePortsClient contains the methods for the ExpressRoutePorts group. +// Don't use this type directly, use NewExpressRoutePortsClient() instead. +type ExpressRoutePortsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRoutePortsClient creates a new instance of ExpressRoutePortsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRoutePortsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRoutePortsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRoutePortsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified ExpressRoutePort resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the ExpressRoutePort resource. +// - parameters - Parameters supplied to the create ExpressRoutePort operation. +// - options - ExpressRoutePortsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRoutePortsClient.BeginCreateOrUpdate +// method. +func (client *ExpressRoutePortsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort, options *ExpressRoutePortsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExpressRoutePortsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, expressRoutePortName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRoutePortsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRoutePortsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified ExpressRoutePort resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRoutePortsClient) createOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort, options *ExpressRoutePortsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRoutePortsClient.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, expressRoutePortName, 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 *ExpressRoutePortsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort, options *ExpressRoutePortsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}" + 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 expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + 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-05-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 ExpressRoutePort resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the ExpressRoutePort resource. +// - options - ExpressRoutePortsClientBeginDeleteOptions contains the optional parameters for the ExpressRoutePortsClient.BeginDelete +// method. +func (client *ExpressRoutePortsClient) BeginDelete(ctx context.Context, resourceGroupName string, expressRoutePortName string, options *ExpressRoutePortsClientBeginDeleteOptions) (*runtime.Poller[ExpressRoutePortsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, expressRoutePortName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExpressRoutePortsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExpressRoutePortsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified ExpressRoutePort resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ExpressRoutePortsClient) deleteOperation(ctx context.Context, resourceGroupName string, expressRoutePortName string, options *ExpressRoutePortsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExpressRoutePortsClient.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, expressRoutePortName, 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 *ExpressRoutePortsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, options *ExpressRoutePortsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}" + 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 expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// GenerateLOA - Generate a letter of authorization for the requested ExpressRoutePort resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of ExpressRoutePort. +// - request - Request parameters supplied to generate a letter of authorization. +// - options - ExpressRoutePortsClientGenerateLOAOptions contains the optional parameters for the ExpressRoutePortsClient.GenerateLOA +// method. +func (client *ExpressRoutePortsClient) GenerateLOA(ctx context.Context, resourceGroupName string, expressRoutePortName string, request GenerateExpressRoutePortsLOARequest, options *ExpressRoutePortsClientGenerateLOAOptions) (ExpressRoutePortsClientGenerateLOAResponse, error) { + var err error + const operationName = "ExpressRoutePortsClient.GenerateLOA" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generateLOACreateRequest(ctx, resourceGroupName, expressRoutePortName, request, options) + if err != nil { + return ExpressRoutePortsClientGenerateLOAResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRoutePortsClientGenerateLOAResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRoutePortsClientGenerateLOAResponse{}, err + } + resp, err := client.generateLOAHandleResponse(httpResp) + return resp, err +} + +// generateLOACreateRequest creates the GenerateLOA request. +func (client *ExpressRoutePortsClient) generateLOACreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, request GenerateExpressRoutePortsLOARequest, options *ExpressRoutePortsClientGenerateLOAOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRoutePorts/{expressRoutePortName}/generateLoa" + 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 expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, request); err != nil { + return nil, err + } + return req, nil +} + +// generateLOAHandleResponse handles the GenerateLOA response. +func (client *ExpressRoutePortsClient) generateLOAHandleResponse(resp *http.Response) (ExpressRoutePortsClientGenerateLOAResponse, error) { + result := ExpressRoutePortsClientGenerateLOAResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GenerateExpressRoutePortsLOAResult); err != nil { + return ExpressRoutePortsClientGenerateLOAResponse{}, err + } + return result, nil +} + +// Get - Retrieves the requested ExpressRoutePort resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of ExpressRoutePort. +// - options - ExpressRoutePortsClientGetOptions contains the optional parameters for the ExpressRoutePortsClient.Get method. +func (client *ExpressRoutePortsClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string, options *ExpressRoutePortsClientGetOptions) (ExpressRoutePortsClientGetResponse, error) { + var err error + const operationName = "ExpressRoutePortsClient.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, expressRoutePortName, options) + if err != nil { + return ExpressRoutePortsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRoutePortsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRoutePortsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRoutePortsClient) getCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, options *ExpressRoutePortsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}" + 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 expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRoutePortsClient) getHandleResponse(resp *http.Response) (ExpressRoutePortsClientGetResponse, error) { + result := ExpressRoutePortsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePort); err != nil { + return ExpressRoutePortsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all the ExpressRoutePort resources in the specified subscription. +// +// Generated from API version 2023-05-01 +// - options - ExpressRoutePortsClientListOptions contains the optional parameters for the ExpressRoutePortsClient.NewListPager +// method. +func (client *ExpressRoutePortsClient) NewListPager(options *ExpressRoutePortsClientListOptions) *runtime.Pager[ExpressRoutePortsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRoutePortsClientListResponse]{ + More: func(page ExpressRoutePortsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRoutePortsClientListResponse) (ExpressRoutePortsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRoutePortsClient.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 ExpressRoutePortsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRoutePortsClient) listCreateRequest(ctx context.Context, options *ExpressRoutePortsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePorts" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRoutePortsClient) listHandleResponse(resp *http.Response) (ExpressRoutePortsClientListResponse, error) { + result := ExpressRoutePortsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePortListResult); err != nil { + return ExpressRoutePortsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List all the ExpressRoutePort resources in the specified resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ExpressRoutePortsClientListByResourceGroupOptions contains the optional parameters for the ExpressRoutePortsClient.NewListByResourceGroupPager +// method. +func (client *ExpressRoutePortsClient) NewListByResourceGroupPager(resourceGroupName string, options *ExpressRoutePortsClientListByResourceGroupOptions) *runtime.Pager[ExpressRoutePortsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRoutePortsClientListByResourceGroupResponse]{ + More: func(page ExpressRoutePortsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRoutePortsClientListByResourceGroupResponse) (ExpressRoutePortsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRoutePortsClient.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 ExpressRoutePortsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ExpressRoutePortsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ExpressRoutePortsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ExpressRoutePortsClient) listByResourceGroupHandleResponse(resp *http.Response) (ExpressRoutePortsClientListByResourceGroupResponse, error) { + result := ExpressRoutePortsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePortListResult); err != nil { + return ExpressRoutePortsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Update ExpressRoutePort tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - expressRoutePortName - The name of the ExpressRoutePort resource. +// - parameters - Parameters supplied to update ExpressRoutePort resource tags. +// - options - ExpressRoutePortsClientUpdateTagsOptions contains the optional parameters for the ExpressRoutePortsClient.UpdateTags +// method. +func (client *ExpressRoutePortsClient) UpdateTags(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject, options *ExpressRoutePortsClientUpdateTagsOptions) (ExpressRoutePortsClientUpdateTagsResponse, error) { + var err error + const operationName = "ExpressRoutePortsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, expressRoutePortName, parameters, options) + if err != nil { + return ExpressRoutePortsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRoutePortsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRoutePortsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ExpressRoutePortsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject, options *ExpressRoutePortsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}" + 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 expressRoutePortName == "" { + return nil, errors.New("parameter expressRoutePortName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{expressRoutePortName}", url.PathEscape(expressRoutePortName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ExpressRoutePortsClient) updateTagsHandleResponse(resp *http.Response) (ExpressRoutePortsClientUpdateTagsResponse, error) { + result := ExpressRoutePortsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePort); err != nil { + return ExpressRoutePortsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteportslocations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteportslocations_client.go new file mode 100644 index 000000000..60221bb4a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteportslocations_client.go @@ -0,0 +1,162 @@ +//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 armnetwork + +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" +) + +// ExpressRoutePortsLocationsClient contains the methods for the ExpressRoutePortsLocations group. +// Don't use this type directly, use NewExpressRoutePortsLocationsClient() instead. +type ExpressRoutePortsLocationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRoutePortsLocationsClient creates a new instance of ExpressRoutePortsLocationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRoutePortsLocationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRoutePortsLocationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRoutePortsLocationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Retrieves a single ExpressRoutePort peering location, including the list of available bandwidths available at said +// peering location. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - locationName - Name of the requested ExpressRoutePort peering location. +// - options - ExpressRoutePortsLocationsClientGetOptions contains the optional parameters for the ExpressRoutePortsLocationsClient.Get +// method. +func (client *ExpressRoutePortsLocationsClient) Get(ctx context.Context, locationName string, options *ExpressRoutePortsLocationsClientGetOptions) (ExpressRoutePortsLocationsClientGetResponse, error) { + var err error + const operationName = "ExpressRoutePortsLocationsClient.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, locationName, options) + if err != nil { + return ExpressRoutePortsLocationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRoutePortsLocationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRoutePortsLocationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExpressRoutePortsLocationsClient) getCreateRequest(ctx context.Context, locationName string, options *ExpressRoutePortsLocationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations/{locationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationName == "" { + return nil, errors.New("parameter locationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationName}", url.PathEscape(locationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExpressRoutePortsLocationsClient) getHandleResponse(resp *http.Response) (ExpressRoutePortsLocationsClientGetResponse, error) { + result := ExpressRoutePortsLocationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePortsLocation); err != nil { + return ExpressRoutePortsLocationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves all ExpressRoutePort peering locations. Does not return available bandwidths for each location. +// Available bandwidths can only be obtained when retrieving a specific peering location. +// +// Generated from API version 2023-05-01 +// - options - ExpressRoutePortsLocationsClientListOptions contains the optional parameters for the ExpressRoutePortsLocationsClient.NewListPager +// method. +func (client *ExpressRoutePortsLocationsClient) NewListPager(options *ExpressRoutePortsLocationsClientListOptions) *runtime.Pager[ExpressRoutePortsLocationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRoutePortsLocationsClientListResponse]{ + More: func(page ExpressRoutePortsLocationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRoutePortsLocationsClientListResponse) (ExpressRoutePortsLocationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRoutePortsLocationsClient.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 ExpressRoutePortsLocationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRoutePortsLocationsClient) listCreateRequest(ctx context.Context, options *ExpressRoutePortsLocationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRoutePortsLocationsClient) listHandleResponse(resp *http.Response) (ExpressRoutePortsLocationsClientListResponse, error) { + result := ExpressRoutePortsLocationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRoutePortsLocationListResult); err != nil { + return ExpressRoutePortsLocationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteproviderportslocation_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteproviderportslocation_client.go new file mode 100644 index 000000000..b3b55c5fa --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteproviderportslocation_client.go @@ -0,0 +1,103 @@ +//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 armnetwork + +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" +) + +// ExpressRouteProviderPortsLocationClient contains the methods for the ExpressRouteProviderPortsLocation group. +// Don't use this type directly, use NewExpressRouteProviderPortsLocationClient() instead. +type ExpressRouteProviderPortsLocationClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteProviderPortsLocationClient creates a new instance of ExpressRouteProviderPortsLocationClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteProviderPortsLocationClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteProviderPortsLocationClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteProviderPortsLocationClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Retrieves all the ExpressRouteProviderPorts in a subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - options - ExpressRouteProviderPortsLocationClientListOptions contains the optional parameters for the ExpressRouteProviderPortsLocationClient.List +// method. +func (client *ExpressRouteProviderPortsLocationClient) List(ctx context.Context, options *ExpressRouteProviderPortsLocationClientListOptions) (ExpressRouteProviderPortsLocationClientListResponse, error) { + var err error + const operationName = "ExpressRouteProviderPortsLocationClient.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, options) + if err != nil { + return ExpressRouteProviderPortsLocationClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExpressRouteProviderPortsLocationClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExpressRouteProviderPortsLocationClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteProviderPortsLocationClient) listCreateRequest(ctx context.Context, options *ExpressRouteProviderPortsLocationClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteProviderPorts" + 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-05-01") + 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 *ExpressRouteProviderPortsLocationClient) listHandleResponse(resp *http.Response) (ExpressRouteProviderPortsLocationClientListResponse, error) { + result := ExpressRouteProviderPortsLocationClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteProviderPortListResult); err != nil { + return ExpressRouteProviderPortsLocationClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteserviceproviders_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteserviceproviders_client.go new file mode 100644 index 000000000..5efbab718 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/expressrouteserviceproviders_client.go @@ -0,0 +1,100 @@ +//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 armnetwork + +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" +) + +// ExpressRouteServiceProvidersClient contains the methods for the ExpressRouteServiceProviders group. +// Don't use this type directly, use NewExpressRouteServiceProvidersClient() instead. +type ExpressRouteServiceProvidersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExpressRouteServiceProvidersClient creates a new instance of ExpressRouteServiceProvidersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewExpressRouteServiceProvidersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExpressRouteServiceProvidersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExpressRouteServiceProvidersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets all the available express route service providers. +// +// Generated from API version 2023-05-01 +// - options - ExpressRouteServiceProvidersClientListOptions contains the optional parameters for the ExpressRouteServiceProvidersClient.NewListPager +// method. +func (client *ExpressRouteServiceProvidersClient) NewListPager(options *ExpressRouteServiceProvidersClientListOptions) *runtime.Pager[ExpressRouteServiceProvidersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ExpressRouteServiceProvidersClientListResponse]{ + More: func(page ExpressRouteServiceProvidersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExpressRouteServiceProvidersClientListResponse) (ExpressRouteServiceProvidersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExpressRouteServiceProvidersClient.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 ExpressRouteServiceProvidersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ExpressRouteServiceProvidersClient) listCreateRequest(ctx context.Context, options *ExpressRouteServiceProvidersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ExpressRouteServiceProvidersClient) listHandleResponse(resp *http.Response) (ExpressRouteServiceProvidersClientListResponse, error) { + result := ExpressRouteServiceProvidersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteServiceProviderListResult); err != nil { + return ExpressRouteServiceProvidersClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicies_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicies_client.go new file mode 100644 index 000000000..8c6460375 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicies_client.go @@ -0,0 +1,454 @@ +//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 armnetwork + +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" +) + +// FirewallPoliciesClient contains the methods for the FirewallPolicies group. +// Don't use this type directly, use NewFirewallPoliciesClient() instead. +type FirewallPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFirewallPoliciesClient creates a new instance of FirewallPoliciesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewFirewallPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FirewallPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FirewallPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Firewall Policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - parameters - Parameters supplied to the create or update Firewall Policy operation. +// - options - FirewallPoliciesClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallPoliciesClient.BeginCreateOrUpdate +// method. +func (client *FirewallPoliciesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters FirewallPolicy, options *FirewallPoliciesClientBeginCreateOrUpdateOptions) (*runtime.Poller[FirewallPoliciesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, firewallPolicyName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallPoliciesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallPoliciesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Firewall Policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *FirewallPoliciesClient) createOrUpdate(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters FirewallPolicy, options *FirewallPoliciesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FirewallPoliciesClient.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, firewallPolicyName, 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 *FirewallPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters FirewallPolicy, options *FirewallPoliciesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-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 Firewall Policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - options - FirewallPoliciesClientBeginDeleteOptions contains the optional parameters for the FirewallPoliciesClient.BeginDelete +// method. +func (client *FirewallPoliciesClient) BeginDelete(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPoliciesClientBeginDeleteOptions) (*runtime.Poller[FirewallPoliciesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, firewallPolicyName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallPoliciesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallPoliciesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Firewall Policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *FirewallPoliciesClient) deleteOperation(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPoliciesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FirewallPoliciesClient.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, firewallPolicyName, 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 *FirewallPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPoliciesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Firewall Policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - options - FirewallPoliciesClientGetOptions contains the optional parameters for the FirewallPoliciesClient.Get method. +func (client *FirewallPoliciesClient) Get(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPoliciesClientGetOptions) (FirewallPoliciesClientGetResponse, error) { + var err error + const operationName = "FirewallPoliciesClient.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, firewallPolicyName, options) + if err != nil { + return FirewallPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FirewallPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *FirewallPoliciesClient) getHandleResponse(resp *http.Response) (FirewallPoliciesClientGetResponse, error) { + result := FirewallPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallPolicy); err != nil { + return FirewallPoliciesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all Firewall Policies in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - FirewallPoliciesClientListOptions contains the optional parameters for the FirewallPoliciesClient.NewListPager +// method. +func (client *FirewallPoliciesClient) NewListPager(resourceGroupName string, options *FirewallPoliciesClientListOptions) *runtime.Pager[FirewallPoliciesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[FirewallPoliciesClientListResponse]{ + More: func(page FirewallPoliciesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FirewallPoliciesClientListResponse) (FirewallPoliciesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FirewallPoliciesClient.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, options) + }, nil) + if err != nil { + return FirewallPoliciesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *FirewallPoliciesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *FirewallPoliciesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *FirewallPoliciesClient) listHandleResponse(resp *http.Response) (FirewallPoliciesClientListResponse, error) { + result := FirewallPoliciesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallPolicyListResult); err != nil { + return FirewallPoliciesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the Firewall Policies in a subscription. +// +// Generated from API version 2023-05-01 +// - options - FirewallPoliciesClientListAllOptions contains the optional parameters for the FirewallPoliciesClient.NewListAllPager +// method. +func (client *FirewallPoliciesClient) NewListAllPager(options *FirewallPoliciesClientListAllOptions) *runtime.Pager[FirewallPoliciesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[FirewallPoliciesClientListAllResponse]{ + More: func(page FirewallPoliciesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FirewallPoliciesClientListAllResponse) (FirewallPoliciesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FirewallPoliciesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return FirewallPoliciesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *FirewallPoliciesClient) listAllCreateRequest(ctx context.Context, options *FirewallPoliciesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/firewallPolicies" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *FirewallPoliciesClient) listAllHandleResponse(resp *http.Response) (FirewallPoliciesClientListAllResponse, error) { + result := FirewallPoliciesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallPolicyListResult); err != nil { + return FirewallPoliciesClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates tags of a Azure Firewall Policy resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - parameters - Parameters supplied to update Azure Firewall Policy tags. +// - options - FirewallPoliciesClientUpdateTagsOptions contains the optional parameters for the FirewallPoliciesClient.UpdateTags +// method. +func (client *FirewallPoliciesClient) UpdateTags(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters TagsObject, options *FirewallPoliciesClientUpdateTagsOptions) (FirewallPoliciesClientUpdateTagsResponse, error) { + var err error + const operationName = "FirewallPoliciesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, firewallPolicyName, parameters, options) + if err != nil { + return FirewallPoliciesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPoliciesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPoliciesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *FirewallPoliciesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters TagsObject, options *FirewallPoliciesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *FirewallPoliciesClient) updateTagsHandleResponse(resp *http.Response) (FirewallPoliciesClientUpdateTagsResponse, error) { + result := FirewallPoliciesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallPolicy); err != nil { + return FirewallPoliciesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignatures_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignatures_client.go new file mode 100644 index 000000000..db57d8830 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignatures_client.go @@ -0,0 +1,113 @@ +//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 armnetwork + +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" +) + +// FirewallPolicyIdpsSignaturesClient contains the methods for the FirewallPolicyIdpsSignatures group. +// Don't use this type directly, use NewFirewallPolicyIdpsSignaturesClient() instead. +type FirewallPolicyIdpsSignaturesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFirewallPolicyIdpsSignaturesClient creates a new instance of FirewallPolicyIdpsSignaturesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewFirewallPolicyIdpsSignaturesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FirewallPolicyIdpsSignaturesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FirewallPolicyIdpsSignaturesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Retrieves the current status of IDPS signatures for the relevant policy +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - options - FirewallPolicyIdpsSignaturesClientListOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesClient.List +// method. +func (client *FirewallPolicyIdpsSignaturesClient) List(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters IDPSQueryObject, options *FirewallPolicyIdpsSignaturesClientListOptions) (FirewallPolicyIdpsSignaturesClientListResponse, error) { + var err error + const operationName = "FirewallPolicyIdpsSignaturesClient.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, firewallPolicyName, parameters, options) + if err != nil { + return FirewallPolicyIdpsSignaturesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPolicyIdpsSignaturesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPolicyIdpsSignaturesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *FirewallPolicyIdpsSignaturesClient) listCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters IDPSQueryObject, options *FirewallPolicyIdpsSignaturesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/listIdpsSignatures" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-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 +} + +// listHandleResponse handles the List response. +func (client *FirewallPolicyIdpsSignaturesClient) listHandleResponse(resp *http.Response) (FirewallPolicyIdpsSignaturesClientListResponse, error) { + result := FirewallPolicyIdpsSignaturesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QueryResults); err != nil { + return FirewallPolicyIdpsSignaturesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignaturesfiltervalues_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignaturesfiltervalues_client.go new file mode 100644 index 000000000..2b23adb7b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignaturesfiltervalues_client.go @@ -0,0 +1,113 @@ +//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 armnetwork + +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" +) + +// FirewallPolicyIdpsSignaturesFilterValuesClient contains the methods for the FirewallPolicyIdpsSignaturesFilterValues group. +// Don't use this type directly, use NewFirewallPolicyIdpsSignaturesFilterValuesClient() instead. +type FirewallPolicyIdpsSignaturesFilterValuesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFirewallPolicyIdpsSignaturesFilterValuesClient creates a new instance of FirewallPolicyIdpsSignaturesFilterValuesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewFirewallPolicyIdpsSignaturesFilterValuesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FirewallPolicyIdpsSignaturesFilterValuesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FirewallPolicyIdpsSignaturesFilterValuesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Retrieves the current filter values for the signatures overrides +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - options - FirewallPolicyIdpsSignaturesFilterValuesClientListOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesFilterValuesClient.List +// method. +func (client *FirewallPolicyIdpsSignaturesFilterValuesClient) List(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters SignatureOverridesFilterValuesQuery, options *FirewallPolicyIdpsSignaturesFilterValuesClientListOptions) (FirewallPolicyIdpsSignaturesFilterValuesClientListResponse, error) { + var err error + const operationName = "FirewallPolicyIdpsSignaturesFilterValuesClient.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, firewallPolicyName, parameters, options) + if err != nil { + return FirewallPolicyIdpsSignaturesFilterValuesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPolicyIdpsSignaturesFilterValuesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPolicyIdpsSignaturesFilterValuesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *FirewallPolicyIdpsSignaturesFilterValuesClient) listCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters SignatureOverridesFilterValuesQuery, options *FirewallPolicyIdpsSignaturesFilterValuesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/listIdpsFilterOptions" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-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 +} + +// listHandleResponse handles the List response. +func (client *FirewallPolicyIdpsSignaturesFilterValuesClient) listHandleResponse(resp *http.Response) (FirewallPolicyIdpsSignaturesFilterValuesClientListResponse, error) { + result := FirewallPolicyIdpsSignaturesFilterValuesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignatureOverridesFilterValuesResponse); err != nil { + return FirewallPolicyIdpsSignaturesFilterValuesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignaturesoverrides_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignaturesoverrides_client.go new file mode 100644 index 000000000..18a77c798 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyidpssignaturesoverrides_client.go @@ -0,0 +1,313 @@ +//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 armnetwork + +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" +) + +// FirewallPolicyIdpsSignaturesOverridesClient contains the methods for the FirewallPolicyIdpsSignaturesOverrides group. +// Don't use this type directly, use NewFirewallPolicyIdpsSignaturesOverridesClient() instead. +type FirewallPolicyIdpsSignaturesOverridesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFirewallPolicyIdpsSignaturesOverridesClient creates a new instance of FirewallPolicyIdpsSignaturesOverridesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewFirewallPolicyIdpsSignaturesOverridesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FirewallPolicyIdpsSignaturesOverridesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FirewallPolicyIdpsSignaturesOverridesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Returns all signatures overrides for a specific policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - options - FirewallPolicyIdpsSignaturesOverridesClientGetOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.Get +// method. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) Get(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPolicyIdpsSignaturesOverridesClientGetOptions) (FirewallPolicyIdpsSignaturesOverridesClientGetResponse, error) { + var err error + const operationName = "FirewallPolicyIdpsSignaturesOverridesClient.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, firewallPolicyName, options) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPolicyIdpsSignaturesOverridesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) getCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPolicyIdpsSignaturesOverridesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/signatureOverrides/default" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) getHandleResponse(resp *http.Response) (FirewallPolicyIdpsSignaturesOverridesClientGetResponse, error) { + result := FirewallPolicyIdpsSignaturesOverridesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignaturesOverrides); err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientGetResponse{}, err + } + return result, nil +} + +// List - Returns all signatures overrides objects for a specific policy as a list containing a single value. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - options - FirewallPolicyIdpsSignaturesOverridesClientListOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.List +// method. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) List(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPolicyIdpsSignaturesOverridesClientListOptions) (FirewallPolicyIdpsSignaturesOverridesClientListResponse, error) { + var err error + const operationName = "FirewallPolicyIdpsSignaturesOverridesClient.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, firewallPolicyName, options) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPolicyIdpsSignaturesOverridesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) listCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPolicyIdpsSignaturesOverridesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/signatureOverrides" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) listHandleResponse(resp *http.Response) (FirewallPolicyIdpsSignaturesOverridesClientListResponse, error) { + result := FirewallPolicyIdpsSignaturesOverridesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignaturesOverridesList); err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientListResponse{}, err + } + return result, nil +} + +// Patch - Will update the status of policy's signature overrides for IDPS +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - parameters - Will contain all properties of the object to put +// - options - FirewallPolicyIdpsSignaturesOverridesClientPatchOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.Patch +// method. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) Patch(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters SignaturesOverrides, options *FirewallPolicyIdpsSignaturesOverridesClientPatchOptions) (FirewallPolicyIdpsSignaturesOverridesClientPatchResponse, error) { + var err error + const operationName = "FirewallPolicyIdpsSignaturesOverridesClient.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, firewallPolicyName, parameters, options) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientPatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientPatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPolicyIdpsSignaturesOverridesClientPatchResponse{}, err + } + resp, err := client.patchHandleResponse(httpResp) + return resp, err +} + +// patchCreateRequest creates the Patch request. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) patchCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters SignaturesOverrides, options *FirewallPolicyIdpsSignaturesOverridesClientPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/signatureOverrides/default" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-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 +} + +// patchHandleResponse handles the Patch response. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) patchHandleResponse(resp *http.Response) (FirewallPolicyIdpsSignaturesOverridesClientPatchResponse, error) { + result := FirewallPolicyIdpsSignaturesOverridesClientPatchResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignaturesOverrides); err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientPatchResponse{}, err + } + return result, nil +} + +// Put - Will override/create a new signature overrides for the policy's IDPS +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - parameters - Will contain all properties of the object to put +// - options - FirewallPolicyIdpsSignaturesOverridesClientPutOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.Put +// method. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) Put(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters SignaturesOverrides, options *FirewallPolicyIdpsSignaturesOverridesClientPutOptions) (FirewallPolicyIdpsSignaturesOverridesClientPutResponse, error) { + var err error + const operationName = "FirewallPolicyIdpsSignaturesOverridesClient.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, firewallPolicyName, parameters, options) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPolicyIdpsSignaturesOverridesClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) putCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters SignaturesOverrides, options *FirewallPolicyIdpsSignaturesOverridesClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/signatureOverrides/default" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-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 +} + +// putHandleResponse handles the Put response. +func (client *FirewallPolicyIdpsSignaturesOverridesClient) putHandleResponse(resp *http.Response) (FirewallPolicyIdpsSignaturesOverridesClientPutResponse, error) { + result := FirewallPolicyIdpsSignaturesOverridesClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignaturesOverrides); err != nil { + return FirewallPolicyIdpsSignaturesOverridesClientPutResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyrulecollectiongroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyrulecollectiongroups_client.go new file mode 100644 index 000000000..beaba2afd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/firewallpolicyrulecollectiongroups_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// FirewallPolicyRuleCollectionGroupsClient contains the methods for the FirewallPolicyRuleCollectionGroups group. +// Don't use this type directly, use NewFirewallPolicyRuleCollectionGroupsClient() instead. +type FirewallPolicyRuleCollectionGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFirewallPolicyRuleCollectionGroupsClient creates a new instance of FirewallPolicyRuleCollectionGroupsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewFirewallPolicyRuleCollectionGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FirewallPolicyRuleCollectionGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FirewallPolicyRuleCollectionGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified FirewallPolicyRuleCollectionGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - ruleCollectionGroupName - The name of the FirewallPolicyRuleCollectionGroup. +// - parameters - Parameters supplied to the create or update FirewallPolicyRuleCollectionGroup operation. +// - options - FirewallPolicyRuleCollectionGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.BeginCreateOrUpdate +// method. +func (client *FirewallPolicyRuleCollectionGroupsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, parameters FirewallPolicyRuleCollectionGroup, options *FirewallPolicyRuleCollectionGroupsClientBeginCreateOrUpdateOptions) (*runtime.Poller[FirewallPolicyRuleCollectionGroupsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, firewallPolicyName, ruleCollectionGroupName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallPolicyRuleCollectionGroupsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallPolicyRuleCollectionGroupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified FirewallPolicyRuleCollectionGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *FirewallPolicyRuleCollectionGroupsClient) createOrUpdate(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, parameters FirewallPolicyRuleCollectionGroup, options *FirewallPolicyRuleCollectionGroupsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FirewallPolicyRuleCollectionGroupsClient.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, firewallPolicyName, ruleCollectionGroupName, 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 *FirewallPolicyRuleCollectionGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, parameters FirewallPolicyRuleCollectionGroup, options *FirewallPolicyRuleCollectionGroupsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups/{ruleCollectionGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + if ruleCollectionGroupName == "" { + return nil, errors.New("parameter ruleCollectionGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionGroupName}", url.PathEscape(ruleCollectionGroupName)) + 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-05-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 FirewallPolicyRuleCollectionGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - ruleCollectionGroupName - The name of the FirewallPolicyRuleCollectionGroup. +// - options - FirewallPolicyRuleCollectionGroupsClientBeginDeleteOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.BeginDelete +// method. +func (client *FirewallPolicyRuleCollectionGroupsClient) BeginDelete(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, options *FirewallPolicyRuleCollectionGroupsClientBeginDeleteOptions) (*runtime.Poller[FirewallPolicyRuleCollectionGroupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, firewallPolicyName, ruleCollectionGroupName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallPolicyRuleCollectionGroupsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallPolicyRuleCollectionGroupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified FirewallPolicyRuleCollectionGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *FirewallPolicyRuleCollectionGroupsClient) deleteOperation(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, options *FirewallPolicyRuleCollectionGroupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FirewallPolicyRuleCollectionGroupsClient.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, firewallPolicyName, ruleCollectionGroupName, 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 *FirewallPolicyRuleCollectionGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, options *FirewallPolicyRuleCollectionGroupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups/{ruleCollectionGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + if ruleCollectionGroupName == "" { + return nil, errors.New("parameter ruleCollectionGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionGroupName}", url.PathEscape(ruleCollectionGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified FirewallPolicyRuleCollectionGroup. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - ruleCollectionGroupName - The name of the FirewallPolicyRuleCollectionGroup. +// - options - FirewallPolicyRuleCollectionGroupsClientGetOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.Get +// method. +func (client *FirewallPolicyRuleCollectionGroupsClient) Get(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, options *FirewallPolicyRuleCollectionGroupsClientGetOptions) (FirewallPolicyRuleCollectionGroupsClientGetResponse, error) { + var err error + const operationName = "FirewallPolicyRuleCollectionGroupsClient.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, firewallPolicyName, ruleCollectionGroupName, options) + if err != nil { + return FirewallPolicyRuleCollectionGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallPolicyRuleCollectionGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallPolicyRuleCollectionGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FirewallPolicyRuleCollectionGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, options *FirewallPolicyRuleCollectionGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups/{ruleCollectionGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + if ruleCollectionGroupName == "" { + return nil, errors.New("parameter ruleCollectionGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionGroupName}", url.PathEscape(ruleCollectionGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FirewallPolicyRuleCollectionGroupsClient) getHandleResponse(resp *http.Response) (FirewallPolicyRuleCollectionGroupsClientGetResponse, error) { + result := FirewallPolicyRuleCollectionGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallPolicyRuleCollectionGroup); err != nil { + return FirewallPolicyRuleCollectionGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all FirewallPolicyRuleCollectionGroups in a FirewallPolicy resource. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - firewallPolicyName - The name of the Firewall Policy. +// - options - FirewallPolicyRuleCollectionGroupsClientListOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.NewListPager +// method. +func (client *FirewallPolicyRuleCollectionGroupsClient) NewListPager(resourceGroupName string, firewallPolicyName string, options *FirewallPolicyRuleCollectionGroupsClientListOptions) *runtime.Pager[FirewallPolicyRuleCollectionGroupsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[FirewallPolicyRuleCollectionGroupsClientListResponse]{ + More: func(page FirewallPolicyRuleCollectionGroupsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FirewallPolicyRuleCollectionGroupsClientListResponse) (FirewallPolicyRuleCollectionGroupsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FirewallPolicyRuleCollectionGroupsClient.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, firewallPolicyName, options) + }, nil) + if err != nil { + return FirewallPolicyRuleCollectionGroupsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *FirewallPolicyRuleCollectionGroupsClient) listCreateRequest(ctx context.Context, resourceGroupName string, firewallPolicyName string, options *FirewallPolicyRuleCollectionGroupsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if firewallPolicyName == "" { + return nil, errors.New("parameter firewallPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallPolicyName}", url.PathEscape(firewallPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *FirewallPolicyRuleCollectionGroupsClient) listHandleResponse(resp *http.Response) (FirewallPolicyRuleCollectionGroupsClientListResponse, error) { + result := FirewallPolicyRuleCollectionGroupsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallPolicyRuleCollectionGroupListResult); err != nil { + return FirewallPolicyRuleCollectionGroupsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/flowlogs_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/flowlogs_client.go new file mode 100644 index 000000000..25a9005f8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/flowlogs_client.go @@ -0,0 +1,418 @@ +//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 armnetwork + +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" +) + +// FlowLogsClient contains the methods for the FlowLogs group. +// Don't use this type directly, use NewFlowLogsClient() instead. +type FlowLogsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFlowLogsClient creates a new instance of FlowLogsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewFlowLogsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FlowLogsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FlowLogsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update a flow log for the specified network security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - flowLogName - The name of the flow log. +// - parameters - Parameters that define the create or update flow log resource. +// - options - FlowLogsClientBeginCreateOrUpdateOptions contains the optional parameters for the FlowLogsClient.BeginCreateOrUpdate +// method. +func (client *FlowLogsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters FlowLog, options *FlowLogsClientBeginCreateOrUpdateOptions) (*runtime.Poller[FlowLogsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkWatcherName, flowLogName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FlowLogsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FlowLogsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a flow log for the specified network security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *FlowLogsClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters FlowLog, options *FlowLogsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FlowLogsClient.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, networkWatcherName, flowLogName, 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 *FlowLogsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters FlowLog, options *FlowLogsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/flowLogs/{flowLogName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if flowLogName == "" { + return nil, errors.New("parameter flowLogName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{flowLogName}", url.PathEscape(flowLogName)) + 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-05-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 flow log resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - flowLogName - The name of the flow log resource. +// - options - FlowLogsClientBeginDeleteOptions contains the optional parameters for the FlowLogsClient.BeginDelete method. +func (client *FlowLogsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, options *FlowLogsClientBeginDeleteOptions) (*runtime.Poller[FlowLogsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkWatcherName, flowLogName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FlowLogsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FlowLogsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified flow log resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *FlowLogsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, options *FlowLogsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FlowLogsClient.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, networkWatcherName, flowLogName, 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 *FlowLogsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, options *FlowLogsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/flowLogs/{flowLogName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if flowLogName == "" { + return nil, errors.New("parameter flowLogName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{flowLogName}", url.PathEscape(flowLogName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a flow log resource by name. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - flowLogName - The name of the flow log resource. +// - options - FlowLogsClientGetOptions contains the optional parameters for the FlowLogsClient.Get method. +func (client *FlowLogsClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, options *FlowLogsClientGetOptions) (FlowLogsClientGetResponse, error) { + var err error + const operationName = "FlowLogsClient.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, networkWatcherName, flowLogName, options) + if err != nil { + return FlowLogsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FlowLogsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FlowLogsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FlowLogsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, options *FlowLogsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/flowLogs/{flowLogName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if flowLogName == "" { + return nil, errors.New("parameter flowLogName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{flowLogName}", url.PathEscape(flowLogName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FlowLogsClient) getHandleResponse(resp *http.Response) (FlowLogsClientGetResponse, error) { + result := FlowLogsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FlowLog); err != nil { + return FlowLogsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all flow log resources for the specified Network Watcher. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group containing Network Watcher. +// - networkWatcherName - The name of the Network Watcher resource. +// - options - FlowLogsClientListOptions contains the optional parameters for the FlowLogsClient.NewListPager method. +func (client *FlowLogsClient) NewListPager(resourceGroupName string, networkWatcherName string, options *FlowLogsClientListOptions) *runtime.Pager[FlowLogsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[FlowLogsClientListResponse]{ + More: func(page FlowLogsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FlowLogsClientListResponse) (FlowLogsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FlowLogsClient.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, networkWatcherName, options) + }, nil) + if err != nil { + return FlowLogsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *FlowLogsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, options *FlowLogsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/flowLogs" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *FlowLogsClient) listHandleResponse(resp *http.Response) (FlowLogsClientListResponse, error) { + result := FlowLogsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FlowLogListResult); err != nil { + return FlowLogsClientListResponse{}, err + } + return result, nil +} + +// UpdateTags - Update tags of the specified flow log. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - flowLogName - The name of the flow log. +// - parameters - Parameters supplied to update flow log tags. +// - options - FlowLogsClientUpdateTagsOptions contains the optional parameters for the FlowLogsClient.UpdateTags method. +func (client *FlowLogsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters TagsObject, options *FlowLogsClientUpdateTagsOptions) (FlowLogsClientUpdateTagsResponse, error) { + var err error + const operationName = "FlowLogsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, networkWatcherName, flowLogName, parameters, options) + if err != nil { + return FlowLogsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FlowLogsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FlowLogsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *FlowLogsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters TagsObject, options *FlowLogsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/flowLogs/{flowLogName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if flowLogName == "" { + return nil, errors.New("parameter flowLogName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{flowLogName}", url.PathEscape(flowLogName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *FlowLogsClient) updateTagsHandleResponse(resp *http.Response) (FlowLogsClientUpdateTagsResponse, error) { + result := FlowLogsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FlowLog); err != nil { + return FlowLogsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/groups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/groups_client.go new file mode 100644 index 000000000..113bcc3bb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/groups_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// GroupsClient contains the methods for the NetworkGroups group. +// Don't use this type directly, use NewGroupsClient() instead. +type GroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGroupsClient creates a new instance of GroupsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates a network group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - networkGroupName - The name of the network group. +// - parameters - Parameters supplied to the specify which network group need to create +// - options - GroupsClientCreateOrUpdateOptions contains the optional parameters for the GroupsClient.CreateOrUpdate method. +func (client *GroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, parameters Group, options *GroupsClientCreateOrUpdateOptions) (GroupsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "GroupsClient.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, networkManagerName, networkGroupName, parameters, options) + if err != nil { + return GroupsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GroupsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return GroupsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *GroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, parameters Group, options *GroupsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if networkGroupName == "" { + return nil, errors.New("parameter networkGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkGroupName}", url.PathEscape(networkGroupName)) + 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-05-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 err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *GroupsClient) createOrUpdateHandleResponse(resp *http.Response) (GroupsClientCreateOrUpdateResponse, error) { + result := GroupsClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Group); err != nil { + return GroupsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes a network group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - networkGroupName - The name of the network group. +// - options - GroupsClientBeginDeleteOptions contains the optional parameters for the GroupsClient.BeginDelete method. +func (client *GroupsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, options *GroupsClientBeginDeleteOptions) (*runtime.Poller[GroupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkManagerName, networkGroupName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[GroupsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[GroupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a network group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *GroupsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, options *GroupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "GroupsClient.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, networkManagerName, networkGroupName, 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 *GroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, options *GroupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if networkGroupName == "" { + return nil, errors.New("parameter networkGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkGroupName}", url.PathEscape(networkGroupName)) + 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-05-01") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified network group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - networkGroupName - The name of the network group. +// - options - GroupsClientGetOptions contains the optional parameters for the GroupsClient.Get method. +func (client *GroupsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, options *GroupsClientGetOptions) (GroupsClientGetResponse, error) { + var err error + const operationName = "GroupsClient.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, networkManagerName, networkGroupName, options) + if err != nil { + return GroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, options *GroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if networkGroupName == "" { + return nil, errors.New("parameter networkGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkGroupName}", url.PathEscape(networkGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *GroupsClient) getHandleResponse(resp *http.Response) (GroupsClientGetResponse, error) { + result := GroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Group); err != nil { + return GroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists the specified network group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - options - GroupsClientListOptions contains the optional parameters for the GroupsClient.NewListPager method. +func (client *GroupsClient) NewListPager(resourceGroupName string, networkManagerName string, options *GroupsClientListOptions) *runtime.Pager[GroupsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[GroupsClientListResponse]{ + More: func(page GroupsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GroupsClientListResponse) (GroupsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GroupsClient.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, networkManagerName, options) + }, nil) + if err != nil { + return GroupsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *GroupsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, options *GroupsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *GroupsClient) listHandleResponse(resp *http.Response) (GroupsClientListResponse, error) { + result := GroupsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GroupListResult); err != nil { + return GroupsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/hubroutetables_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/hubroutetables_client.go new file mode 100644 index 000000000..d906077a5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/hubroutetables_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 armnetwork + +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" +) + +// HubRouteTablesClient contains the methods for the HubRouteTables group. +// Don't use this type directly, use NewHubRouteTablesClient() instead. +type HubRouteTablesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewHubRouteTablesClient creates a new instance of HubRouteTablesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewHubRouteTablesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*HubRouteTablesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &HubRouteTablesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a RouteTable resource if it doesn't exist else updates the existing RouteTable. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - routeTableName - The name of the RouteTable. +// - routeTableParameters - Parameters supplied to create or update RouteTable. +// - options - HubRouteTablesClientBeginCreateOrUpdateOptions contains the optional parameters for the HubRouteTablesClient.BeginCreateOrUpdate +// method. +func (client *HubRouteTablesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, routeTableParameters HubRouteTable, options *HubRouteTablesClientBeginCreateOrUpdateOptions) (*runtime.Poller[HubRouteTablesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, routeTableName, routeTableParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HubRouteTablesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HubRouteTablesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a RouteTable resource if it doesn't exist else updates the existing RouteTable. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *HubRouteTablesClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, routeTableParameters HubRouteTable, options *HubRouteTablesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "HubRouteTablesClient.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, virtualHubName, routeTableName, routeTableParameters, 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 *HubRouteTablesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, routeTableParameters HubRouteTable, options *HubRouteTablesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubRouteTables/{routeTableName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, routeTableParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a RouteTable. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RouteTable. +// - virtualHubName - The name of the VirtualHub. +// - routeTableName - The name of the RouteTable. +// - options - HubRouteTablesClientBeginDeleteOptions contains the optional parameters for the HubRouteTablesClient.BeginDelete +// method. +func (client *HubRouteTablesClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *HubRouteTablesClientBeginDeleteOptions) (*runtime.Poller[HubRouteTablesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, routeTableName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HubRouteTablesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HubRouteTablesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a RouteTable. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *HubRouteTablesClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *HubRouteTablesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "HubRouteTablesClient.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, virtualHubName, routeTableName, 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 *HubRouteTablesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *HubRouteTablesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubRouteTables/{routeTableName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a RouteTable. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - routeTableName - The name of the RouteTable. +// - options - HubRouteTablesClientGetOptions contains the optional parameters for the HubRouteTablesClient.Get method. +func (client *HubRouteTablesClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *HubRouteTablesClientGetOptions) (HubRouteTablesClientGetResponse, error) { + var err error + const operationName = "HubRouteTablesClient.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, virtualHubName, routeTableName, options) + if err != nil { + return HubRouteTablesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HubRouteTablesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HubRouteTablesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *HubRouteTablesClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *HubRouteTablesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubRouteTables/{routeTableName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *HubRouteTablesClient) getHandleResponse(resp *http.Response) (HubRouteTablesClientGetResponse, error) { + result := HubRouteTablesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HubRouteTable); err != nil { + return HubRouteTablesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves the details of all RouteTables. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - HubRouteTablesClientListOptions contains the optional parameters for the HubRouteTablesClient.NewListPager method. +func (client *HubRouteTablesClient) NewListPager(resourceGroupName string, virtualHubName string, options *HubRouteTablesClientListOptions) *runtime.Pager[HubRouteTablesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[HubRouteTablesClientListResponse]{ + More: func(page HubRouteTablesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *HubRouteTablesClientListResponse) (HubRouteTablesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "HubRouteTablesClient.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, virtualHubName, options) + }, nil) + if err != nil { + return HubRouteTablesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *HubRouteTablesClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *HubRouteTablesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubRouteTables" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *HubRouteTablesClient) listHandleResponse(resp *http.Response) (HubRouteTablesClientListResponse, error) { + result := HubRouteTablesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListHubRouteTablesResult); err != nil { + return HubRouteTablesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/hubvirtualnetworkconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/hubvirtualnetworkconnections_client.go new file mode 100644 index 000000000..e47c8bb56 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/hubvirtualnetworkconnections_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// HubVirtualNetworkConnectionsClient contains the methods for the HubVirtualNetworkConnections group. +// Don't use this type directly, use NewHubVirtualNetworkConnectionsClient() instead. +type HubVirtualNetworkConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewHubVirtualNetworkConnectionsClient creates a new instance of HubVirtualNetworkConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewHubVirtualNetworkConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*HubVirtualNetworkConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &HubVirtualNetworkConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a hub virtual network connection if it doesn't exist else updates the existing one. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the HubVirtualNetworkConnection. +// - virtualHubName - The name of the VirtualHub. +// - connectionName - The name of the HubVirtualNetworkConnection. +// - hubVirtualNetworkConnectionParameters - Parameters supplied to create or update a hub virtual network connection. +// - options - HubVirtualNetworkConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.BeginCreateOrUpdate +// method. +func (client *HubVirtualNetworkConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, hubVirtualNetworkConnectionParameters HubVirtualNetworkConnection, options *HubVirtualNetworkConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[HubVirtualNetworkConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, connectionName, hubVirtualNetworkConnectionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HubVirtualNetworkConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HubVirtualNetworkConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a hub virtual network connection if it doesn't exist else updates the existing one. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *HubVirtualNetworkConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, hubVirtualNetworkConnectionParameters HubVirtualNetworkConnection, options *HubVirtualNetworkConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "HubVirtualNetworkConnectionsClient.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, virtualHubName, connectionName, hubVirtualNetworkConnectionParameters, 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 *HubVirtualNetworkConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, hubVirtualNetworkConnectionParameters HubVirtualNetworkConnection, options *HubVirtualNetworkConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, hubVirtualNetworkConnectionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a HubVirtualNetworkConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - connectionName - The name of the HubVirtualNetworkConnection. +// - options - HubVirtualNetworkConnectionsClientBeginDeleteOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.BeginDelete +// method. +func (client *HubVirtualNetworkConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *HubVirtualNetworkConnectionsClientBeginDeleteOptions) (*runtime.Poller[HubVirtualNetworkConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HubVirtualNetworkConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HubVirtualNetworkConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a HubVirtualNetworkConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *HubVirtualNetworkConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *HubVirtualNetworkConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "HubVirtualNetworkConnectionsClient.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, virtualHubName, connectionName, 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 *HubVirtualNetworkConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *HubVirtualNetworkConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a HubVirtualNetworkConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - connectionName - The name of the vpn connection. +// - options - HubVirtualNetworkConnectionsClientGetOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.Get +// method. +func (client *HubVirtualNetworkConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *HubVirtualNetworkConnectionsClientGetOptions) (HubVirtualNetworkConnectionsClientGetResponse, error) { + var err error + const operationName = "HubVirtualNetworkConnectionsClient.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, virtualHubName, connectionName, options) + if err != nil { + return HubVirtualNetworkConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HubVirtualNetworkConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HubVirtualNetworkConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *HubVirtualNetworkConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *HubVirtualNetworkConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *HubVirtualNetworkConnectionsClient) getHandleResponse(resp *http.Response) (HubVirtualNetworkConnectionsClientGetResponse, error) { + result := HubVirtualNetworkConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HubVirtualNetworkConnection); err != nil { + return HubVirtualNetworkConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves the details of all HubVirtualNetworkConnections. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - HubVirtualNetworkConnectionsClientListOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.NewListPager +// method. +func (client *HubVirtualNetworkConnectionsClient) NewListPager(resourceGroupName string, virtualHubName string, options *HubVirtualNetworkConnectionsClientListOptions) *runtime.Pager[HubVirtualNetworkConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[HubVirtualNetworkConnectionsClientListResponse]{ + More: func(page HubVirtualNetworkConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *HubVirtualNetworkConnectionsClientListResponse) (HubVirtualNetworkConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "HubVirtualNetworkConnectionsClient.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, virtualHubName, options) + }, nil) + if err != nil { + return HubVirtualNetworkConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *HubVirtualNetworkConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *HubVirtualNetworkConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *HubVirtualNetworkConnectionsClient) listHandleResponse(resp *http.Response) (HubVirtualNetworkConnectionsClientListResponse, error) { + result := HubVirtualNetworkConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListHubVirtualNetworkConnectionsResult); err != nil { + return HubVirtualNetworkConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/inboundnatrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/inboundnatrules_client.go new file mode 100644 index 000000000..464d80dc0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/inboundnatrules_client.go @@ -0,0 +1,350 @@ +//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 armnetwork + +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" +) + +// InboundNatRulesClient contains the methods for the InboundNatRules group. +// Don't use this type directly, use NewInboundNatRulesClient() instead. +type InboundNatRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewInboundNatRulesClient creates a new instance of InboundNatRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewInboundNatRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*InboundNatRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &InboundNatRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a load balancer inbound NAT rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - inboundNatRuleName - The name of the inbound NAT rule. +// - inboundNatRuleParameters - Parameters supplied to the create or update inbound NAT rule operation. +// - options - InboundNatRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the InboundNatRulesClient.BeginCreateOrUpdate +// method. +func (client *InboundNatRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, inboundNatRuleParameters InboundNatRule, options *InboundNatRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[InboundNatRulesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InboundNatRulesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InboundNatRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a load balancer inbound NAT rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InboundNatRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, inboundNatRuleParameters InboundNatRule, options *InboundNatRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "InboundNatRulesClient.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, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, 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 *InboundNatRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, inboundNatRuleParameters InboundNatRule, options *InboundNatRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if inboundNatRuleName == "" { + return nil, errors.New("parameter inboundNatRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inboundNatRuleName}", url.PathEscape(inboundNatRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, inboundNatRuleParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified load balancer inbound NAT rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - inboundNatRuleName - The name of the inbound NAT rule. +// - options - InboundNatRulesClientBeginDeleteOptions contains the optional parameters for the InboundNatRulesClient.BeginDelete +// method. +func (client *InboundNatRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, options *InboundNatRulesClientBeginDeleteOptions) (*runtime.Poller[InboundNatRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InboundNatRulesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InboundNatRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified load balancer inbound NAT rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InboundNatRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, options *InboundNatRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "InboundNatRulesClient.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, loadBalancerName, inboundNatRuleName, 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 *InboundNatRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, options *InboundNatRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if inboundNatRuleName == "" { + return nil, errors.New("parameter inboundNatRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inboundNatRuleName}", url.PathEscape(inboundNatRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified load balancer inbound NAT rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - inboundNatRuleName - The name of the inbound NAT rule. +// - options - InboundNatRulesClientGetOptions contains the optional parameters for the InboundNatRulesClient.Get method. +func (client *InboundNatRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, options *InboundNatRulesClientGetOptions) (InboundNatRulesClientGetResponse, error) { + var err error + const operationName = "InboundNatRulesClient.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, loadBalancerName, inboundNatRuleName, options) + if err != nil { + return InboundNatRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InboundNatRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InboundNatRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *InboundNatRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, options *InboundNatRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if inboundNatRuleName == "" { + return nil, errors.New("parameter inboundNatRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inboundNatRuleName}", url.PathEscape(inboundNatRuleName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *InboundNatRulesClient) getHandleResponse(resp *http.Response) (InboundNatRulesClientGetResponse, error) { + result := InboundNatRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InboundNatRule); err != nil { + return InboundNatRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the inbound NAT rules in a load balancer. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - InboundNatRulesClientListOptions contains the optional parameters for the InboundNatRulesClient.NewListPager +// method. +func (client *InboundNatRulesClient) NewListPager(resourceGroupName string, loadBalancerName string, options *InboundNatRulesClientListOptions) *runtime.Pager[InboundNatRulesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[InboundNatRulesClientListResponse]{ + More: func(page InboundNatRulesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InboundNatRulesClientListResponse) (InboundNatRulesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InboundNatRulesClient.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, loadBalancerName, options) + }, nil) + if err != nil { + return InboundNatRulesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *InboundNatRulesClient) listCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *InboundNatRulesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *InboundNatRulesClient) listHandleResponse(resp *http.Response) (InboundNatRulesClientListResponse, error) { + result := InboundNatRulesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InboundNatRuleListResult); err != nil { + return InboundNatRulesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/inboundsecurityrule_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/inboundsecurityrule_client.go new file mode 100644 index 000000000..41108ace5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/inboundsecurityrule_client.go @@ -0,0 +1,131 @@ +//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 armnetwork + +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" +) + +// InboundSecurityRuleClient contains the methods for the InboundSecurityRule group. +// Don't use this type directly, use NewInboundSecurityRuleClient() instead. +type InboundSecurityRuleClient struct { + internal *arm.Client + subscriptionID string +} + +// NewInboundSecurityRuleClient creates a new instance of InboundSecurityRuleClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewInboundSecurityRuleClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*InboundSecurityRuleClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &InboundSecurityRuleClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Network Virtual Appliance Inbound Security Rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - ruleCollectionName - The name of security rule collection. +// - parameters - Parameters supplied to the create or update Network Virtual Appliance Inbound Security Rules operation. +// - options - InboundSecurityRuleClientBeginCreateOrUpdateOptions contains the optional parameters for the InboundSecurityRuleClient.BeginCreateOrUpdate +// method. +func (client *InboundSecurityRuleClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, ruleCollectionName string, parameters InboundSecurityRule, options *InboundSecurityRuleClientBeginCreateOrUpdateOptions) (*runtime.Poller[InboundSecurityRuleClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkVirtualApplianceName, ruleCollectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InboundSecurityRuleClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InboundSecurityRuleClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Network Virtual Appliance Inbound Security Rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InboundSecurityRuleClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, ruleCollectionName string, parameters InboundSecurityRule, options *InboundSecurityRuleClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "InboundSecurityRuleClient.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, networkVirtualApplianceName, ruleCollectionName, 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 *InboundSecurityRuleClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, ruleCollectionName string, parameters InboundSecurityRule, options *InboundSecurityRuleClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/inboundSecurityRules/{ruleCollectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + if ruleCollectionName == "" { + return nil, errors.New("parameter ruleCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleCollectionName}", url.PathEscape(ruleCollectionName)) + 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-05-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/network/armnetwork/v4/interfaceipconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaceipconfigurations_client.go new file mode 100644 index 000000000..805f961c7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaceipconfigurations_client.go @@ -0,0 +1,180 @@ +//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 armnetwork + +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" +) + +// InterfaceIPConfigurationsClient contains the methods for the NetworkInterfaceIPConfigurations group. +// Don't use this type directly, use NewInterfaceIPConfigurationsClient() instead. +type InterfaceIPConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewInterfaceIPConfigurationsClient creates a new instance of InterfaceIPConfigurationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewInterfaceIPConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*InterfaceIPConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &InterfaceIPConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the specified network interface ip configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - ipConfigurationName - The name of the ip configuration name. +// - options - InterfaceIPConfigurationsClientGetOptions contains the optional parameters for the InterfaceIPConfigurationsClient.Get +// method. +func (client *InterfaceIPConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, ipConfigurationName string, options *InterfaceIPConfigurationsClientGetOptions) (InterfaceIPConfigurationsClientGetResponse, error) { + var err error + const operationName = "InterfaceIPConfigurationsClient.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, networkInterfaceName, ipConfigurationName, options) + if err != nil { + return InterfaceIPConfigurationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InterfaceIPConfigurationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InterfaceIPConfigurationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *InterfaceIPConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, ipConfigurationName string, options *InterfaceIPConfigurationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if ipConfigurationName == "" { + return nil, errors.New("parameter ipConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigurationName}", url.PathEscape(ipConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *InterfaceIPConfigurationsClient) getHandleResponse(resp *http.Response) (InterfaceIPConfigurationsClientGetResponse, error) { + result := InterfaceIPConfigurationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceIPConfiguration); err != nil { + return InterfaceIPConfigurationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Get all ip configurations in a network interface. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - options - InterfaceIPConfigurationsClientListOptions contains the optional parameters for the InterfaceIPConfigurationsClient.NewListPager +// method. +func (client *InterfaceIPConfigurationsClient) NewListPager(resourceGroupName string, networkInterfaceName string, options *InterfaceIPConfigurationsClientListOptions) *runtime.Pager[InterfaceIPConfigurationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfaceIPConfigurationsClientListResponse]{ + More: func(page InterfaceIPConfigurationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfaceIPConfigurationsClientListResponse) (InterfaceIPConfigurationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfaceIPConfigurationsClient.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, networkInterfaceName, options) + }, nil) + if err != nil { + return InterfaceIPConfigurationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *InterfaceIPConfigurationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfaceIPConfigurationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *InterfaceIPConfigurationsClient) listHandleResponse(resp *http.Response) (InterfaceIPConfigurationsClientListResponse, error) { + result := InterfaceIPConfigurationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceIPConfigurationListResult); err != nil { + return InterfaceIPConfigurationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaceloadbalancers_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaceloadbalancers_client.go new file mode 100644 index 000000000..dd7e24733 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaceloadbalancers_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 armnetwork + +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" +) + +// InterfaceLoadBalancersClient contains the methods for the NetworkInterfaceLoadBalancers group. +// Don't use this type directly, use NewInterfaceLoadBalancersClient() instead. +type InterfaceLoadBalancersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewInterfaceLoadBalancersClient creates a new instance of InterfaceLoadBalancersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewInterfaceLoadBalancersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*InterfaceLoadBalancersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &InterfaceLoadBalancersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - List all load balancers in a network interface. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - options - InterfaceLoadBalancersClientListOptions contains the optional parameters for the InterfaceLoadBalancersClient.NewListPager +// method. +func (client *InterfaceLoadBalancersClient) NewListPager(resourceGroupName string, networkInterfaceName string, options *InterfaceLoadBalancersClientListOptions) *runtime.Pager[InterfaceLoadBalancersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfaceLoadBalancersClientListResponse]{ + More: func(page InterfaceLoadBalancersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfaceLoadBalancersClientListResponse) (InterfaceLoadBalancersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfaceLoadBalancersClient.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, networkInterfaceName, options) + }, nil) + if err != nil { + return InterfaceLoadBalancersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *InterfaceLoadBalancersClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfaceLoadBalancersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/loadBalancers" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *InterfaceLoadBalancersClient) listHandleResponse(resp *http.Response) (InterfaceLoadBalancersClientListResponse, error) { + result := InterfaceLoadBalancersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceLoadBalancerListResult); err != nil { + return InterfaceLoadBalancersClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaces.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaces.go new file mode 100644 index 000000000..a153dd576 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaces.go @@ -0,0 +1,54 @@ +//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 armnetwork + +// ActiveBaseSecurityAdminRuleClassification provides polymorphic access to related types. +// Call the interface's GetActiveBaseSecurityAdminRule() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ActiveBaseSecurityAdminRule, *ActiveDefaultSecurityAdminRule, *ActiveSecurityAdminRule +type ActiveBaseSecurityAdminRuleClassification interface { + // GetActiveBaseSecurityAdminRule returns the ActiveBaseSecurityAdminRule content of the underlying type. + GetActiveBaseSecurityAdminRule() *ActiveBaseSecurityAdminRule +} + +// BaseAdminRuleClassification provides polymorphic access to related types. +// Call the interface's GetBaseAdminRule() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AdminRule, *BaseAdminRule, *DefaultAdminRule +type BaseAdminRuleClassification interface { + // GetBaseAdminRule returns the BaseAdminRule content of the underlying type. + GetBaseAdminRule() *BaseAdminRule +} + +// EffectiveBaseSecurityAdminRuleClassification provides polymorphic access to related types. +// Call the interface's GetEffectiveBaseSecurityAdminRule() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *EffectiveBaseSecurityAdminRule, *EffectiveDefaultSecurityAdminRule, *EffectiveSecurityAdminRule +type EffectiveBaseSecurityAdminRuleClassification interface { + // GetEffectiveBaseSecurityAdminRule returns the EffectiveBaseSecurityAdminRule content of the underlying type. + GetEffectiveBaseSecurityAdminRule() *EffectiveBaseSecurityAdminRule +} + +// FirewallPolicyRuleClassification provides polymorphic access to related types. +// Call the interface's GetFirewallPolicyRule() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ApplicationRule, *FirewallPolicyRule, *NatRule, *Rule +type FirewallPolicyRuleClassification interface { + // GetFirewallPolicyRule returns the FirewallPolicyRule content of the underlying type. + GetFirewallPolicyRule() *FirewallPolicyRule +} + +// FirewallPolicyRuleCollectionClassification provides polymorphic access to related types. +// Call the interface's GetFirewallPolicyRuleCollection() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *FirewallPolicyFilterRuleCollection, *FirewallPolicyNatRuleCollection, *FirewallPolicyRuleCollection +type FirewallPolicyRuleCollectionClassification interface { + // GetFirewallPolicyRuleCollection returns the FirewallPolicyRuleCollection content of the underlying type. + GetFirewallPolicyRuleCollection() *FirewallPolicyRuleCollection +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaces_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaces_client.go new file mode 100644 index 000000000..e28e01c0b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfaces_client.go @@ -0,0 +1,1195 @@ +//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 armnetwork + +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" +) + +// InterfacesClient contains the methods for the NetworkInterfaces group. +// Don't use this type directly, use NewInterfacesClient() instead. +type InterfacesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewInterfacesClient creates a new instance of InterfacesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewInterfacesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*InterfacesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &InterfacesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - parameters - Parameters supplied to the create or update network interface operation. +// - options - InterfacesClientBeginCreateOrUpdateOptions contains the optional parameters for the InterfacesClient.BeginCreateOrUpdate +// method. +func (client *InterfacesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters Interface, options *InterfacesClientBeginCreateOrUpdateOptions) (*runtime.Poller[InterfacesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InterfacesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InterfacesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InterfacesClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters Interface, options *InterfacesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "InterfacesClient.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, networkInterfaceName, 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 *InterfacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters Interface, options *InterfacesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-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 network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - options - InterfacesClientBeginDeleteOptions contains the optional parameters for the InterfacesClient.BeginDelete method. +func (client *InterfacesClient) BeginDelete(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginDeleteOptions) (*runtime.Poller[InterfacesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkInterfaceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InterfacesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InterfacesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InterfacesClient) deleteOperation(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "InterfacesClient.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, networkInterfaceName, 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 *InterfacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about the specified network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - options - InterfacesClientGetOptions contains the optional parameters for the InterfacesClient.Get method. +func (client *InterfacesClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientGetOptions) (InterfacesClientGetResponse, error) { + var err error + const operationName = "InterfacesClient.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, networkInterfaceName, options) + if err != nil { + return InterfacesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InterfacesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InterfacesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *InterfacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *InterfacesClient) getHandleResponse(resp *http.Response) (InterfacesClientGetResponse, error) { + result := InterfacesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Interface); err != nil { + return InterfacesClientGetResponse{}, err + } + return result, nil +} + +// GetCloudServiceNetworkInterface - Get the specified network interface in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - cloudServiceName - The name of the cloud service. +// - roleInstanceName - The name of role instance. +// - networkInterfaceName - The name of the network interface. +// - options - InterfacesClientGetCloudServiceNetworkInterfaceOptions contains the optional parameters for the InterfacesClient.GetCloudServiceNetworkInterface +// method. +func (client *InterfacesClient) GetCloudServiceNetworkInterface(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, options *InterfacesClientGetCloudServiceNetworkInterfaceOptions) (InterfacesClientGetCloudServiceNetworkInterfaceResponse, error) { + var err error + const operationName = "InterfacesClient.GetCloudServiceNetworkInterface" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCloudServiceNetworkInterfaceCreateRequest(ctx, resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, options) + if err != nil { + return InterfacesClientGetCloudServiceNetworkInterfaceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InterfacesClientGetCloudServiceNetworkInterfaceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InterfacesClientGetCloudServiceNetworkInterfaceResponse{}, err + } + resp, err := client.getCloudServiceNetworkInterfaceHandleResponse(httpResp) + return resp, err +} + +// getCloudServiceNetworkInterfaceCreateRequest creates the GetCloudServiceNetworkInterface request. +func (client *InterfacesClient) getCloudServiceNetworkInterfaceCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, options *InterfacesClientGetCloudServiceNetworkInterfaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces/{networkInterfaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + 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 +} + +// getCloudServiceNetworkInterfaceHandleResponse handles the GetCloudServiceNetworkInterface response. +func (client *InterfacesClient) getCloudServiceNetworkInterfaceHandleResponse(resp *http.Response) (InterfacesClientGetCloudServiceNetworkInterfaceResponse, error) { + result := InterfacesClientGetCloudServiceNetworkInterfaceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Interface); err != nil { + return InterfacesClientGetCloudServiceNetworkInterfaceResponse{}, err + } + return result, nil +} + +// BeginGetEffectiveRouteTable - Gets all route tables applied to a network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - options - InterfacesClientBeginGetEffectiveRouteTableOptions contains the optional parameters for the InterfacesClient.BeginGetEffectiveRouteTable +// method. +func (client *InterfacesClient) BeginGetEffectiveRouteTable(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginGetEffectiveRouteTableOptions) (*runtime.Poller[InterfacesClientGetEffectiveRouteTableResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getEffectiveRouteTable(ctx, resourceGroupName, networkInterfaceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InterfacesClientGetEffectiveRouteTableResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InterfacesClientGetEffectiveRouteTableResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetEffectiveRouteTable - Gets all route tables applied to a network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InterfacesClient) getEffectiveRouteTable(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginGetEffectiveRouteTableOptions) (*http.Response, error) { + var err error + const operationName = "InterfacesClient.BeginGetEffectiveRouteTable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getEffectiveRouteTableCreateRequest(ctx, resourceGroupName, networkInterfaceName, 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 +} + +// getEffectiveRouteTableCreateRequest creates the GetEffectiveRouteTable request. +func (client *InterfacesClient) getEffectiveRouteTableCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginGetEffectiveRouteTableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/effectiveRouteTable" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// GetVirtualMachineScaleSetIPConfiguration - Get the specified network interface ip configuration in a virtual machine scale +// set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - virtualmachineIndex - The virtual machine index. +// - networkInterfaceName - The name of the network interface. +// - ipConfigurationName - The name of the ip configuration. +// - options - InterfacesClientGetVirtualMachineScaleSetIPConfigurationOptions contains the optional parameters for the InterfacesClient.GetVirtualMachineScaleSetIPConfiguration +// method. +func (client *InterfacesClient) GetVirtualMachineScaleSetIPConfiguration(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, ipConfigurationName string, options *InterfacesClientGetVirtualMachineScaleSetIPConfigurationOptions) (InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse, error) { + var err error + const operationName = "InterfacesClient.GetVirtualMachineScaleSetIPConfiguration" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getVirtualMachineScaleSetIPConfigurationCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, options) + if err != nil { + return InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse{}, err + } + resp, err := client.getVirtualMachineScaleSetIPConfigurationHandleResponse(httpResp) + return resp, err +} + +// getVirtualMachineScaleSetIPConfigurationCreateRequest creates the GetVirtualMachineScaleSetIPConfiguration request. +func (client *InterfacesClient) getVirtualMachineScaleSetIPConfigurationCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, ipConfigurationName string, options *InterfacesClientGetVirtualMachineScaleSetIPConfigurationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + if virtualmachineIndex == "" { + return nil, errors.New("parameter virtualmachineIndex cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualmachineIndex}", url.PathEscape(virtualmachineIndex)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if ipConfigurationName == "" { + return nil, errors.New("parameter ipConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigurationName}", url.PathEscape(ipConfigurationName)) + 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", "2018-10-01") + 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 +} + +// getVirtualMachineScaleSetIPConfigurationHandleResponse handles the GetVirtualMachineScaleSetIPConfiguration response. +func (client *InterfacesClient) getVirtualMachineScaleSetIPConfigurationHandleResponse(resp *http.Response) (InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse, error) { + result := InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceIPConfiguration); err != nil { + return InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse{}, err + } + return result, nil +} + +// GetVirtualMachineScaleSetNetworkInterface - Get the specified network interface in a virtual machine scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - virtualmachineIndex - The virtual machine index. +// - networkInterfaceName - The name of the network interface. +// - options - InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceOptions contains the optional parameters for the InterfacesClient.GetVirtualMachineScaleSetNetworkInterface +// method. +func (client *InterfacesClient) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, options *InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceOptions) (InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse, error) { + var err error + const operationName = "InterfacesClient.GetVirtualMachineScaleSetNetworkInterface" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getVirtualMachineScaleSetNetworkInterfaceCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, options) + if err != nil { + return InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse{}, err + } + resp, err := client.getVirtualMachineScaleSetNetworkInterfaceHandleResponse(httpResp) + return resp, err +} + +// getVirtualMachineScaleSetNetworkInterfaceCreateRequest creates the GetVirtualMachineScaleSetNetworkInterface request. +func (client *InterfacesClient) getVirtualMachineScaleSetNetworkInterfaceCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, options *InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + if virtualmachineIndex == "" { + return nil, errors.New("parameter virtualmachineIndex cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualmachineIndex}", url.PathEscape(virtualmachineIndex)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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", "2018-10-01") + 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 +} + +// getVirtualMachineScaleSetNetworkInterfaceHandleResponse handles the GetVirtualMachineScaleSetNetworkInterface response. +func (client *InterfacesClient) getVirtualMachineScaleSetNetworkInterfaceHandleResponse(resp *http.Response) (InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse, error) { + result := InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Interface); err != nil { + return InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all network interfaces in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - InterfacesClientListOptions contains the optional parameters for the InterfacesClient.NewListPager method. +func (client *InterfacesClient) NewListPager(resourceGroupName string, options *InterfacesClientListOptions) *runtime.Pager[InterfacesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfacesClientListResponse]{ + More: func(page InterfacesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfacesClientListResponse) (InterfacesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfacesClient.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, options) + }, nil) + if err != nil { + return InterfacesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *InterfacesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *InterfacesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *InterfacesClient) listHandleResponse(resp *http.Response) (InterfacesClientListResponse, error) { + result := InterfacesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceListResult); err != nil { + return InterfacesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all network interfaces in a subscription. +// +// Generated from API version 2023-05-01 +// - options - InterfacesClientListAllOptions contains the optional parameters for the InterfacesClient.NewListAllPager method. +func (client *InterfacesClient) NewListAllPager(options *InterfacesClientListAllOptions) *runtime.Pager[InterfacesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfacesClientListAllResponse]{ + More: func(page InterfacesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfacesClientListAllResponse) (InterfacesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfacesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return InterfacesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *InterfacesClient) listAllCreateRequest(ctx context.Context, options *InterfacesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkInterfaces" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *InterfacesClient) listAllHandleResponse(resp *http.Response) (InterfacesClientListAllResponse, error) { + result := InterfacesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceListResult); err != nil { + return InterfacesClientListAllResponse{}, err + } + return result, nil +} + +// NewListCloudServiceNetworkInterfacesPager - Gets all network interfaces in a cloud service. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - cloudServiceName - The name of the cloud service. +// - options - InterfacesClientListCloudServiceNetworkInterfacesOptions contains the optional parameters for the InterfacesClient.NewListCloudServiceNetworkInterfacesPager +// method. +func (client *InterfacesClient) NewListCloudServiceNetworkInterfacesPager(resourceGroupName string, cloudServiceName string, options *InterfacesClientListCloudServiceNetworkInterfacesOptions) *runtime.Pager[InterfacesClientListCloudServiceNetworkInterfacesResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfacesClientListCloudServiceNetworkInterfacesResponse]{ + More: func(page InterfacesClientListCloudServiceNetworkInterfacesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfacesClientListCloudServiceNetworkInterfacesResponse) (InterfacesClientListCloudServiceNetworkInterfacesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfacesClient.NewListCloudServiceNetworkInterfacesPager") + 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.listCloudServiceNetworkInterfacesCreateRequest(ctx, resourceGroupName, cloudServiceName, options) + }, nil) + if err != nil { + return InterfacesClientListCloudServiceNetworkInterfacesResponse{}, err + } + return client.listCloudServiceNetworkInterfacesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCloudServiceNetworkInterfacesCreateRequest creates the ListCloudServiceNetworkInterfaces request. +func (client *InterfacesClient) listCloudServiceNetworkInterfacesCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *InterfacesClientListCloudServiceNetworkInterfacesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/networkInterfaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listCloudServiceNetworkInterfacesHandleResponse handles the ListCloudServiceNetworkInterfaces response. +func (client *InterfacesClient) listCloudServiceNetworkInterfacesHandleResponse(resp *http.Response) (InterfacesClientListCloudServiceNetworkInterfacesResponse, error) { + result := InterfacesClientListCloudServiceNetworkInterfacesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceListResult); err != nil { + return InterfacesClientListCloudServiceNetworkInterfacesResponse{}, err + } + return result, nil +} + +// NewListCloudServiceRoleInstanceNetworkInterfacesPager - Gets information about all network interfaces in a role instance +// in a cloud service. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - cloudServiceName - The name of the cloud service. +// - roleInstanceName - The name of role instance. +// - options - InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesOptions contains the optional parameters for the +// InterfacesClient.NewListCloudServiceRoleInstanceNetworkInterfacesPager method. +func (client *InterfacesClient) NewListCloudServiceRoleInstanceNetworkInterfacesPager(resourceGroupName string, cloudServiceName string, roleInstanceName string, options *InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesOptions) *runtime.Pager[InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse]{ + More: func(page InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse) (InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfacesClient.NewListCloudServiceRoleInstanceNetworkInterfacesPager") + 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.listCloudServiceRoleInstanceNetworkInterfacesCreateRequest(ctx, resourceGroupName, cloudServiceName, roleInstanceName, options) + }, nil) + if err != nil { + return InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse{}, err + } + return client.listCloudServiceRoleInstanceNetworkInterfacesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCloudServiceRoleInstanceNetworkInterfacesCreateRequest creates the ListCloudServiceRoleInstanceNetworkInterfaces request. +func (client *InterfacesClient) listCloudServiceRoleInstanceNetworkInterfacesCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, options *InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listCloudServiceRoleInstanceNetworkInterfacesHandleResponse handles the ListCloudServiceRoleInstanceNetworkInterfaces response. +func (client *InterfacesClient) listCloudServiceRoleInstanceNetworkInterfacesHandleResponse(resp *http.Response) (InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse, error) { + result := InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceListResult); err != nil { + return InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse{}, err + } + return result, nil +} + +// BeginListEffectiveNetworkSecurityGroups - Gets all network security groups applied to a network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - options - InterfacesClientBeginListEffectiveNetworkSecurityGroupsOptions contains the optional parameters for the InterfacesClient.BeginListEffectiveNetworkSecurityGroups +// method. +func (client *InterfacesClient) BeginListEffectiveNetworkSecurityGroups(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginListEffectiveNetworkSecurityGroupsOptions) (*runtime.Poller[InterfacesClientListEffectiveNetworkSecurityGroupsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listEffectiveNetworkSecurityGroups(ctx, resourceGroupName, networkInterfaceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InterfacesClientListEffectiveNetworkSecurityGroupsResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InterfacesClientListEffectiveNetworkSecurityGroupsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListEffectiveNetworkSecurityGroups - Gets all network security groups applied to a network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InterfacesClient) listEffectiveNetworkSecurityGroups(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginListEffectiveNetworkSecurityGroupsOptions) (*http.Response, error) { + var err error + const operationName = "InterfacesClient.BeginListEffectiveNetworkSecurityGroups" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listEffectiveNetworkSecurityGroupsCreateRequest(ctx, resourceGroupName, networkInterfaceName, 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 +} + +// listEffectiveNetworkSecurityGroupsCreateRequest creates the ListEffectiveNetworkSecurityGroups request. +func (client *InterfacesClient) listEffectiveNetworkSecurityGroupsCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfacesClientBeginListEffectiveNetworkSecurityGroupsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/effectiveNetworkSecurityGroups" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// NewListVirtualMachineScaleSetIPConfigurationsPager - Get the specified network interface ip configuration in a virtual +// machine scale set. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - virtualmachineIndex - The virtual machine index. +// - networkInterfaceName - The name of the network interface. +// - options - InterfacesClientListVirtualMachineScaleSetIPConfigurationsOptions contains the optional parameters for the InterfacesClient.NewListVirtualMachineScaleSetIPConfigurationsPager +// method. +func (client *InterfacesClient) NewListVirtualMachineScaleSetIPConfigurationsPager(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, options *InterfacesClientListVirtualMachineScaleSetIPConfigurationsOptions) *runtime.Pager[InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse]{ + More: func(page InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse) (InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfacesClient.NewListVirtualMachineScaleSetIPConfigurationsPager") + 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.listVirtualMachineScaleSetIPConfigurationsCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, options) + }, nil) + if err != nil { + return InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse{}, err + } + return client.listVirtualMachineScaleSetIPConfigurationsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listVirtualMachineScaleSetIPConfigurationsCreateRequest creates the ListVirtualMachineScaleSetIPConfigurations request. +func (client *InterfacesClient) listVirtualMachineScaleSetIPConfigurationsCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, options *InterfacesClientListVirtualMachineScaleSetIPConfigurationsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipConfigurations" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + if virtualmachineIndex == "" { + return nil, errors.New("parameter virtualmachineIndex cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualmachineIndex}", url.PathEscape(virtualmachineIndex)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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", "2018-10-01") + 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 +} + +// listVirtualMachineScaleSetIPConfigurationsHandleResponse handles the ListVirtualMachineScaleSetIPConfigurations response. +func (client *InterfacesClient) listVirtualMachineScaleSetIPConfigurationsHandleResponse(resp *http.Response) (InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse, error) { + result := InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceIPConfigurationListResult); err != nil { + return InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse{}, err + } + return result, nil +} + +// NewListVirtualMachineScaleSetNetworkInterfacesPager - Gets all network interfaces in a virtual machine scale set. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - options - InterfacesClientListVirtualMachineScaleSetNetworkInterfacesOptions contains the optional parameters for the InterfacesClient.NewListVirtualMachineScaleSetNetworkInterfacesPager +// method. +func (client *InterfacesClient) NewListVirtualMachineScaleSetNetworkInterfacesPager(resourceGroupName string, virtualMachineScaleSetName string, options *InterfacesClientListVirtualMachineScaleSetNetworkInterfacesOptions) *runtime.Pager[InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse]{ + More: func(page InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse) (InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfacesClient.NewListVirtualMachineScaleSetNetworkInterfacesPager") + 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.listVirtualMachineScaleSetNetworkInterfacesCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, options) + }, nil) + if err != nil { + return InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse{}, err + } + return client.listVirtualMachineScaleSetNetworkInterfacesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listVirtualMachineScaleSetNetworkInterfacesCreateRequest creates the ListVirtualMachineScaleSetNetworkInterfaces request. +func (client *InterfacesClient) listVirtualMachineScaleSetNetworkInterfacesCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, options *InterfacesClientListVirtualMachineScaleSetNetworkInterfacesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/networkInterfaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + 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", "2018-10-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listVirtualMachineScaleSetNetworkInterfacesHandleResponse handles the ListVirtualMachineScaleSetNetworkInterfaces response. +func (client *InterfacesClient) listVirtualMachineScaleSetNetworkInterfacesHandleResponse(resp *http.Response) (InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse, error) { + result := InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceListResult); err != nil { + return InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse{}, err + } + return result, nil +} + +// NewListVirtualMachineScaleSetVMNetworkInterfacesPager - Gets information about all network interfaces in a virtual machine +// in a virtual machine scale set. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - virtualmachineIndex - The virtual machine index. +// - options - InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesOptions contains the optional parameters for the +// InterfacesClient.NewListVirtualMachineScaleSetVMNetworkInterfacesPager method. +func (client *InterfacesClient) NewListVirtualMachineScaleSetVMNetworkInterfacesPager(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, options *InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesOptions) *runtime.Pager[InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse]{ + More: func(page InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse) (InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfacesClient.NewListVirtualMachineScaleSetVMNetworkInterfacesPager") + 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.listVirtualMachineScaleSetVMNetworkInterfacesCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, options) + }, nil) + if err != nil { + return InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse{}, err + } + return client.listVirtualMachineScaleSetVMNetworkInterfacesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listVirtualMachineScaleSetVMNetworkInterfacesCreateRequest creates the ListVirtualMachineScaleSetVMNetworkInterfaces request. +func (client *InterfacesClient) listVirtualMachineScaleSetVMNetworkInterfacesCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, options *InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + if virtualmachineIndex == "" { + return nil, errors.New("parameter virtualmachineIndex cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualmachineIndex}", url.PathEscape(virtualmachineIndex)) + 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", "2018-10-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listVirtualMachineScaleSetVMNetworkInterfacesHandleResponse handles the ListVirtualMachineScaleSetVMNetworkInterfaces response. +func (client *InterfacesClient) listVirtualMachineScaleSetVMNetworkInterfacesHandleResponse(resp *http.Response) (InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse, error) { + result := InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceListResult); err != nil { + return InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a network interface tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - parameters - Parameters supplied to update network interface tags. +// - options - InterfacesClientUpdateTagsOptions contains the optional parameters for the InterfacesClient.UpdateTags method. +func (client *InterfacesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters TagsObject, options *InterfacesClientUpdateTagsOptions) (InterfacesClientUpdateTagsResponse, error) { + var err error + const operationName = "InterfacesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, networkInterfaceName, parameters, options) + if err != nil { + return InterfacesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InterfacesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InterfacesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *InterfacesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters TagsObject, options *InterfacesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *InterfacesClient) updateTagsHandleResponse(resp *http.Response) (InterfacesClientUpdateTagsResponse, error) { + result := InterfacesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Interface); err != nil { + return InterfacesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfacetapconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfacetapconfigurations_client.go new file mode 100644 index 000000000..fdff9756b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/interfacetapconfigurations_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// InterfaceTapConfigurationsClient contains the methods for the NetworkInterfaceTapConfigurations group. +// Don't use this type directly, use NewInterfaceTapConfigurationsClient() instead. +type InterfaceTapConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewInterfaceTapConfigurationsClient creates a new instance of InterfaceTapConfigurationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewInterfaceTapConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*InterfaceTapConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &InterfaceTapConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a Tap configuration in the specified NetworkInterface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - tapConfigurationName - The name of the tap configuration. +// - tapConfigurationParameters - Parameters supplied to the create or update tap configuration operation. +// - options - InterfaceTapConfigurationsClientBeginCreateOrUpdateOptions contains the optional parameters for the InterfaceTapConfigurationsClient.BeginCreateOrUpdate +// method. +func (client *InterfaceTapConfigurationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration, options *InterfaceTapConfigurationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[InterfaceTapConfigurationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName, tapConfigurationParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InterfaceTapConfigurationsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InterfaceTapConfigurationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a Tap configuration in the specified NetworkInterface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InterfaceTapConfigurationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration, options *InterfaceTapConfigurationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "InterfaceTapConfigurationsClient.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, networkInterfaceName, tapConfigurationName, tapConfigurationParameters, 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 *InterfaceTapConfigurationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration, options *InterfaceTapConfigurationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if tapConfigurationName == "" { + return nil, errors.New("parameter tapConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tapConfigurationName}", url.PathEscape(tapConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tapConfigurationParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified tap configuration from the NetworkInterface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - tapConfigurationName - The name of the tap configuration. +// - options - InterfaceTapConfigurationsClientBeginDeleteOptions contains the optional parameters for the InterfaceTapConfigurationsClient.BeginDelete +// method. +func (client *InterfaceTapConfigurationsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, options *InterfaceTapConfigurationsClientBeginDeleteOptions) (*runtime.Poller[InterfaceTapConfigurationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[InterfaceTapConfigurationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[InterfaceTapConfigurationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified tap configuration from the NetworkInterface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *InterfaceTapConfigurationsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, options *InterfaceTapConfigurationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "InterfaceTapConfigurationsClient.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, networkInterfaceName, tapConfigurationName, 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 *InterfaceTapConfigurationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, options *InterfaceTapConfigurationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if tapConfigurationName == "" { + return nil, errors.New("parameter tapConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tapConfigurationName}", url.PathEscape(tapConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get the specified tap configuration on a network interface. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - tapConfigurationName - The name of the tap configuration. +// - options - InterfaceTapConfigurationsClientGetOptions contains the optional parameters for the InterfaceTapConfigurationsClient.Get +// method. +func (client *InterfaceTapConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, options *InterfaceTapConfigurationsClientGetOptions) (InterfaceTapConfigurationsClientGetResponse, error) { + var err error + const operationName = "InterfaceTapConfigurationsClient.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, networkInterfaceName, tapConfigurationName, options) + if err != nil { + return InterfaceTapConfigurationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InterfaceTapConfigurationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InterfaceTapConfigurationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *InterfaceTapConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, options *InterfaceTapConfigurationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if tapConfigurationName == "" { + return nil, errors.New("parameter tapConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tapConfigurationName}", url.PathEscape(tapConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *InterfaceTapConfigurationsClient) getHandleResponse(resp *http.Response) (InterfaceTapConfigurationsClientGetResponse, error) { + result := InterfaceTapConfigurationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceTapConfiguration); err != nil { + return InterfaceTapConfigurationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Get all Tap configurations in a network interface. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkInterfaceName - The name of the network interface. +// - options - InterfaceTapConfigurationsClientListOptions contains the optional parameters for the InterfaceTapConfigurationsClient.NewListPager +// method. +func (client *InterfaceTapConfigurationsClient) NewListPager(resourceGroupName string, networkInterfaceName string, options *InterfaceTapConfigurationsClientListOptions) *runtime.Pager[InterfaceTapConfigurationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[InterfaceTapConfigurationsClientListResponse]{ + More: func(page InterfaceTapConfigurationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InterfaceTapConfigurationsClientListResponse) (InterfaceTapConfigurationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InterfaceTapConfigurationsClient.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, networkInterfaceName, options) + }, nil) + if err != nil { + return InterfaceTapConfigurationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *InterfaceTapConfigurationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkInterfaceName string, options *InterfaceTapConfigurationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *InterfaceTapConfigurationsClient) listHandleResponse(resp *http.Response) (InterfaceTapConfigurationsClientListResponse, error) { + result := InterfaceTapConfigurationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceTapConfigurationListResult); err != nil { + return InterfaceTapConfigurationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ipallocations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ipallocations_client.go new file mode 100644 index 000000000..3aff2a84d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ipallocations_client.go @@ -0,0 +1,453 @@ +//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 armnetwork + +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" +) + +// IPAllocationsClient contains the methods for the IPAllocations group. +// Don't use this type directly, use NewIPAllocationsClient() instead. +type IPAllocationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewIPAllocationsClient creates a new instance of IPAllocationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewIPAllocationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*IPAllocationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &IPAllocationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an IpAllocation in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipAllocationName - The name of the IpAllocation. +// - parameters - Parameters supplied to the create or update virtual network operation. +// - options - IPAllocationsClientBeginCreateOrUpdateOptions contains the optional parameters for the IPAllocationsClient.BeginCreateOrUpdate +// method. +func (client *IPAllocationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, ipAllocationName string, parameters IPAllocation, options *IPAllocationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[IPAllocationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, ipAllocationName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[IPAllocationsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[IPAllocationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an IpAllocation in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *IPAllocationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, ipAllocationName string, parameters IPAllocation, options *IPAllocationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "IPAllocationsClient.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, ipAllocationName, 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 *IPAllocationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, ipAllocationName string, parameters IPAllocation, options *IPAllocationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipAllocationName == "" { + return nil, errors.New("parameter ipAllocationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipAllocationName}", url.PathEscape(ipAllocationName)) + 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-05-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 IpAllocation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipAllocationName - The name of the IpAllocation. +// - options - IPAllocationsClientBeginDeleteOptions contains the optional parameters for the IPAllocationsClient.BeginDelete +// method. +func (client *IPAllocationsClient) BeginDelete(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientBeginDeleteOptions) (*runtime.Poller[IPAllocationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, ipAllocationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[IPAllocationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[IPAllocationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified IpAllocation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *IPAllocationsClient) deleteOperation(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "IPAllocationsClient.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, ipAllocationName, 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 *IPAllocationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipAllocationName == "" { + return nil, errors.New("parameter ipAllocationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipAllocationName}", url.PathEscape(ipAllocationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified IpAllocation by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipAllocationName - The name of the IpAllocation. +// - options - IPAllocationsClientGetOptions contains the optional parameters for the IPAllocationsClient.Get method. +func (client *IPAllocationsClient) Get(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientGetOptions) (IPAllocationsClientGetResponse, error) { + var err error + const operationName = "IPAllocationsClient.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, ipAllocationName, options) + if err != nil { + return IPAllocationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IPAllocationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IPAllocationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *IPAllocationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipAllocationName == "" { + return nil, errors.New("parameter ipAllocationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipAllocationName}", url.PathEscape(ipAllocationName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *IPAllocationsClient) getHandleResponse(resp *http.Response) (IPAllocationsClientGetResponse, error) { + result := IPAllocationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPAllocation); err != nil { + return IPAllocationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all IpAllocations in a subscription. +// +// Generated from API version 2023-05-01 +// - options - IPAllocationsClientListOptions contains the optional parameters for the IPAllocationsClient.NewListPager method. +func (client *IPAllocationsClient) NewListPager(options *IPAllocationsClientListOptions) *runtime.Pager[IPAllocationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[IPAllocationsClientListResponse]{ + More: func(page IPAllocationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *IPAllocationsClientListResponse) (IPAllocationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "IPAllocationsClient.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 IPAllocationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *IPAllocationsClient) listCreateRequest(ctx context.Context, options *IPAllocationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/IpAllocations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *IPAllocationsClient) listHandleResponse(resp *http.Response) (IPAllocationsClientListResponse, error) { + result := IPAllocationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPAllocationListResult); err != nil { + return IPAllocationsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all IpAllocations in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - IPAllocationsClientListByResourceGroupOptions contains the optional parameters for the IPAllocationsClient.NewListByResourceGroupPager +// method. +func (client *IPAllocationsClient) NewListByResourceGroupPager(resourceGroupName string, options *IPAllocationsClientListByResourceGroupOptions) *runtime.Pager[IPAllocationsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[IPAllocationsClientListByResourceGroupResponse]{ + More: func(page IPAllocationsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *IPAllocationsClientListByResourceGroupResponse) (IPAllocationsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "IPAllocationsClient.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 IPAllocationsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *IPAllocationsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *IPAllocationsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *IPAllocationsClient) listByResourceGroupHandleResponse(resp *http.Response) (IPAllocationsClientListByResourceGroupResponse, error) { + result := IPAllocationsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPAllocationListResult); err != nil { + return IPAllocationsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a IpAllocation tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipAllocationName - The name of the IpAllocation. +// - parameters - Parameters supplied to update IpAllocation tags. +// - options - IPAllocationsClientUpdateTagsOptions contains the optional parameters for the IPAllocationsClient.UpdateTags +// method. +func (client *IPAllocationsClient) UpdateTags(ctx context.Context, resourceGroupName string, ipAllocationName string, parameters TagsObject, options *IPAllocationsClientUpdateTagsOptions) (IPAllocationsClientUpdateTagsResponse, error) { + var err error + const operationName = "IPAllocationsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, ipAllocationName, parameters, options) + if err != nil { + return IPAllocationsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IPAllocationsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IPAllocationsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *IPAllocationsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, ipAllocationName string, parameters TagsObject, options *IPAllocationsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipAllocationName == "" { + return nil, errors.New("parameter ipAllocationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipAllocationName}", url.PathEscape(ipAllocationName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *IPAllocationsClient) updateTagsHandleResponse(resp *http.Response) (IPAllocationsClientUpdateTagsResponse, error) { + result := IPAllocationsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPAllocation); err != nil { + return IPAllocationsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ipgroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ipgroups_client.go new file mode 100644 index 000000000..e64510aa5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/ipgroups_client.go @@ -0,0 +1,451 @@ +//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 armnetwork + +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" +) + +// IPGroupsClient contains the methods for the IPGroups group. +// Don't use this type directly, use NewIPGroupsClient() instead. +type IPGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewIPGroupsClient creates a new instance of IPGroupsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewIPGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*IPGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &IPGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an ipGroups in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipGroupsName - The name of the ipGroups. +// - parameters - Parameters supplied to the create or update IpGroups operation. +// - options - IPGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the IPGroupsClient.BeginCreateOrUpdate +// method. +func (client *IPGroupsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, ipGroupsName string, parameters IPGroup, options *IPGroupsClientBeginCreateOrUpdateOptions) (*runtime.Poller[IPGroupsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, ipGroupsName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[IPGroupsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[IPGroupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an ipGroups in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *IPGroupsClient) createOrUpdate(ctx context.Context, resourceGroupName string, ipGroupsName string, parameters IPGroup, options *IPGroupsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "IPGroupsClient.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, ipGroupsName, 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 *IPGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, ipGroupsName string, parameters IPGroup, options *IPGroupsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipGroupsName == "" { + return nil, errors.New("parameter ipGroupsName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipGroupsName}", url.PathEscape(ipGroupsName)) + 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-05-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 ipGroups. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipGroupsName - The name of the ipGroups. +// - options - IPGroupsClientBeginDeleteOptions contains the optional parameters for the IPGroupsClient.BeginDelete method. +func (client *IPGroupsClient) BeginDelete(ctx context.Context, resourceGroupName string, ipGroupsName string, options *IPGroupsClientBeginDeleteOptions) (*runtime.Poller[IPGroupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, ipGroupsName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[IPGroupsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[IPGroupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified ipGroups. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *IPGroupsClient) deleteOperation(ctx context.Context, resourceGroupName string, ipGroupsName string, options *IPGroupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "IPGroupsClient.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, ipGroupsName, 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 *IPGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ipGroupsName string, options *IPGroupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipGroupsName == "" { + return nil, errors.New("parameter ipGroupsName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipGroupsName}", url.PathEscape(ipGroupsName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified ipGroups. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipGroupsName - The name of the ipGroups. +// - options - IPGroupsClientGetOptions contains the optional parameters for the IPGroupsClient.Get method. +func (client *IPGroupsClient) Get(ctx context.Context, resourceGroupName string, ipGroupsName string, options *IPGroupsClientGetOptions) (IPGroupsClientGetResponse, error) { + var err error + const operationName = "IPGroupsClient.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, ipGroupsName, options) + if err != nil { + return IPGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IPGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IPGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *IPGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, ipGroupsName string, options *IPGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipGroupsName == "" { + return nil, errors.New("parameter ipGroupsName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipGroupsName}", url.PathEscape(ipGroupsName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *IPGroupsClient) getHandleResponse(resp *http.Response) (IPGroupsClientGetResponse, error) { + result := IPGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPGroup); err != nil { + return IPGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all IpGroups in a subscription. +// +// Generated from API version 2023-05-01 +// - options - IPGroupsClientListOptions contains the optional parameters for the IPGroupsClient.NewListPager method. +func (client *IPGroupsClient) NewListPager(options *IPGroupsClientListOptions) *runtime.Pager[IPGroupsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[IPGroupsClientListResponse]{ + More: func(page IPGroupsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *IPGroupsClientListResponse) (IPGroupsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "IPGroupsClient.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 IPGroupsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *IPGroupsClient) listCreateRequest(ctx context.Context, options *IPGroupsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/ipGroups" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *IPGroupsClient) listHandleResponse(resp *http.Response) (IPGroupsClientListResponse, error) { + result := IPGroupsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPGroupListResult); err != nil { + return IPGroupsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all IpGroups in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - IPGroupsClientListByResourceGroupOptions contains the optional parameters for the IPGroupsClient.NewListByResourceGroupPager +// method. +func (client *IPGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *IPGroupsClientListByResourceGroupOptions) *runtime.Pager[IPGroupsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[IPGroupsClientListByResourceGroupResponse]{ + More: func(page IPGroupsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *IPGroupsClientListByResourceGroupResponse) (IPGroupsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "IPGroupsClient.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 IPGroupsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *IPGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *IPGroupsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *IPGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (IPGroupsClientListByResourceGroupResponse, error) { + result := IPGroupsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPGroupListResult); err != nil { + return IPGroupsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateGroups - Updates tags of an IpGroups resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - ipGroupsName - The name of the ipGroups. +// - parameters - Parameters supplied to the update ipGroups operation. +// - options - IPGroupsClientUpdateGroupsOptions contains the optional parameters for the IPGroupsClient.UpdateGroups method. +func (client *IPGroupsClient) UpdateGroups(ctx context.Context, resourceGroupName string, ipGroupsName string, parameters TagsObject, options *IPGroupsClientUpdateGroupsOptions) (IPGroupsClientUpdateGroupsResponse, error) { + var err error + const operationName = "IPGroupsClient.UpdateGroups" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateGroupsCreateRequest(ctx, resourceGroupName, ipGroupsName, parameters, options) + if err != nil { + return IPGroupsClientUpdateGroupsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IPGroupsClientUpdateGroupsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IPGroupsClientUpdateGroupsResponse{}, err + } + resp, err := client.updateGroupsHandleResponse(httpResp) + return resp, err +} + +// updateGroupsCreateRequest creates the UpdateGroups request. +func (client *IPGroupsClient) updateGroupsCreateRequest(ctx context.Context, resourceGroupName string, ipGroupsName string, parameters TagsObject, options *IPGroupsClientUpdateGroupsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ipGroupsName == "" { + return nil, errors.New("parameter ipGroupsName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipGroupsName}", url.PathEscape(ipGroupsName)) + 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-05-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 +} + +// updateGroupsHandleResponse handles the UpdateGroups response. +func (client *IPGroupsClient) updateGroupsHandleResponse(resp *http.Response) (IPGroupsClientUpdateGroupsResponse, error) { + result := IPGroupsClientUpdateGroupsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPGroup); err != nil { + return IPGroupsClientUpdateGroupsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerbackendaddresspools_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerbackendaddresspools_client.go new file mode 100644 index 000000000..f0c7b034f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerbackendaddresspools_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// LoadBalancerBackendAddressPoolsClient contains the methods for the LoadBalancerBackendAddressPools group. +// Don't use this type directly, use NewLoadBalancerBackendAddressPoolsClient() instead. +type LoadBalancerBackendAddressPoolsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadBalancerBackendAddressPoolsClient creates a new instance of LoadBalancerBackendAddressPoolsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLoadBalancerBackendAddressPoolsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancerBackendAddressPoolsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancerBackendAddressPoolsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a load balancer backend address pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - backendAddressPoolName - The name of the backend address pool. +// - parameters - Parameters supplied to the create or update load balancer backend address pool operation. +// - options - LoadBalancerBackendAddressPoolsClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.BeginCreateOrUpdate +// method. +func (client *LoadBalancerBackendAddressPoolsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, parameters BackendAddressPool, options *LoadBalancerBackendAddressPoolsClientBeginCreateOrUpdateOptions) (*runtime.Poller[LoadBalancerBackendAddressPoolsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, loadBalancerName, backendAddressPoolName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadBalancerBackendAddressPoolsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadBalancerBackendAddressPoolsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a load balancer backend address pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LoadBalancerBackendAddressPoolsClient) createOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, parameters BackendAddressPool, options *LoadBalancerBackendAddressPoolsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "LoadBalancerBackendAddressPoolsClient.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, loadBalancerName, backendAddressPoolName, 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 *LoadBalancerBackendAddressPoolsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, parameters BackendAddressPool, options *LoadBalancerBackendAddressPoolsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if backendAddressPoolName == "" { + return nil, errors.New("parameter backendAddressPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{backendAddressPoolName}", url.PathEscape(backendAddressPoolName)) + 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-05-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 load balancer backend address pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - backendAddressPoolName - The name of the backend address pool. +// - options - LoadBalancerBackendAddressPoolsClientBeginDeleteOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.BeginDelete +// method. +func (client *LoadBalancerBackendAddressPoolsClient) BeginDelete(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, options *LoadBalancerBackendAddressPoolsClientBeginDeleteOptions) (*runtime.Poller[LoadBalancerBackendAddressPoolsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, loadBalancerName, backendAddressPoolName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadBalancerBackendAddressPoolsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadBalancerBackendAddressPoolsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified load balancer backend address pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LoadBalancerBackendAddressPoolsClient) deleteOperation(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, options *LoadBalancerBackendAddressPoolsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "LoadBalancerBackendAddressPoolsClient.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, loadBalancerName, backendAddressPoolName, 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 *LoadBalancerBackendAddressPoolsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, options *LoadBalancerBackendAddressPoolsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if backendAddressPoolName == "" { + return nil, errors.New("parameter backendAddressPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{backendAddressPoolName}", url.PathEscape(backendAddressPoolName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets load balancer backend address pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - backendAddressPoolName - The name of the backend address pool. +// - options - LoadBalancerBackendAddressPoolsClientGetOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.Get +// method. +func (client *LoadBalancerBackendAddressPoolsClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, options *LoadBalancerBackendAddressPoolsClientGetOptions) (LoadBalancerBackendAddressPoolsClientGetResponse, error) { + var err error + const operationName = "LoadBalancerBackendAddressPoolsClient.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, loadBalancerName, backendAddressPoolName, options) + if err != nil { + return LoadBalancerBackendAddressPoolsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancerBackendAddressPoolsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancerBackendAddressPoolsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadBalancerBackendAddressPoolsClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, options *LoadBalancerBackendAddressPoolsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if backendAddressPoolName == "" { + return nil, errors.New("parameter backendAddressPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{backendAddressPoolName}", url.PathEscape(backendAddressPoolName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadBalancerBackendAddressPoolsClient) getHandleResponse(resp *http.Response) (LoadBalancerBackendAddressPoolsClientGetResponse, error) { + result := LoadBalancerBackendAddressPoolsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BackendAddressPool); err != nil { + return LoadBalancerBackendAddressPoolsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the load balancer backed address pools. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancerBackendAddressPoolsClientListOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.NewListPager +// method. +func (client *LoadBalancerBackendAddressPoolsClient) NewListPager(resourceGroupName string, loadBalancerName string, options *LoadBalancerBackendAddressPoolsClientListOptions) *runtime.Pager[LoadBalancerBackendAddressPoolsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancerBackendAddressPoolsClientListResponse]{ + More: func(page LoadBalancerBackendAddressPoolsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancerBackendAddressPoolsClientListResponse) (LoadBalancerBackendAddressPoolsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancerBackendAddressPoolsClient.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, loadBalancerName, options) + }, nil) + if err != nil { + return LoadBalancerBackendAddressPoolsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancerBackendAddressPoolsClient) listCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancerBackendAddressPoolsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancerBackendAddressPoolsClient) listHandleResponse(resp *http.Response) (LoadBalancerBackendAddressPoolsClientListResponse, error) { + result := LoadBalancerBackendAddressPoolsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerBackendAddressPoolListResult); err != nil { + return LoadBalancerBackendAddressPoolsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerfrontendipconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerfrontendipconfigurations_client.go new file mode 100644 index 000000000..8d996375c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerfrontendipconfigurations_client.go @@ -0,0 +1,180 @@ +//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 armnetwork + +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" +) + +// LoadBalancerFrontendIPConfigurationsClient contains the methods for the LoadBalancerFrontendIPConfigurations group. +// Don't use this type directly, use NewLoadBalancerFrontendIPConfigurationsClient() instead. +type LoadBalancerFrontendIPConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadBalancerFrontendIPConfigurationsClient creates a new instance of LoadBalancerFrontendIPConfigurationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLoadBalancerFrontendIPConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancerFrontendIPConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancerFrontendIPConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets load balancer frontend IP configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - frontendIPConfigurationName - The name of the frontend IP configuration. +// - options - LoadBalancerFrontendIPConfigurationsClientGetOptions contains the optional parameters for the LoadBalancerFrontendIPConfigurationsClient.Get +// method. +func (client *LoadBalancerFrontendIPConfigurationsClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string, options *LoadBalancerFrontendIPConfigurationsClientGetOptions) (LoadBalancerFrontendIPConfigurationsClientGetResponse, error) { + var err error + const operationName = "LoadBalancerFrontendIPConfigurationsClient.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, loadBalancerName, frontendIPConfigurationName, options) + if err != nil { + return LoadBalancerFrontendIPConfigurationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancerFrontendIPConfigurationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancerFrontendIPConfigurationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadBalancerFrontendIPConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string, options *LoadBalancerFrontendIPConfigurationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations/{frontendIPConfigurationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if frontendIPConfigurationName == "" { + return nil, errors.New("parameter frontendIPConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{frontendIPConfigurationName}", url.PathEscape(frontendIPConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadBalancerFrontendIPConfigurationsClient) getHandleResponse(resp *http.Response) (LoadBalancerFrontendIPConfigurationsClientGetResponse, error) { + result := LoadBalancerFrontendIPConfigurationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FrontendIPConfiguration); err != nil { + return LoadBalancerFrontendIPConfigurationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the load balancer frontend IP configurations. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancerFrontendIPConfigurationsClientListOptions contains the optional parameters for the LoadBalancerFrontendIPConfigurationsClient.NewListPager +// method. +func (client *LoadBalancerFrontendIPConfigurationsClient) NewListPager(resourceGroupName string, loadBalancerName string, options *LoadBalancerFrontendIPConfigurationsClientListOptions) *runtime.Pager[LoadBalancerFrontendIPConfigurationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancerFrontendIPConfigurationsClientListResponse]{ + More: func(page LoadBalancerFrontendIPConfigurationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancerFrontendIPConfigurationsClientListResponse) (LoadBalancerFrontendIPConfigurationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancerFrontendIPConfigurationsClient.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, loadBalancerName, options) + }, nil) + if err != nil { + return LoadBalancerFrontendIPConfigurationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancerFrontendIPConfigurationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancerFrontendIPConfigurationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancerFrontendIPConfigurationsClient) listHandleResponse(resp *http.Response) (LoadBalancerFrontendIPConfigurationsClientListResponse, error) { + result := LoadBalancerFrontendIPConfigurationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerFrontendIPConfigurationListResult); err != nil { + return LoadBalancerFrontendIPConfigurationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerloadbalancingrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerloadbalancingrules_client.go new file mode 100644 index 000000000..2e3039096 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerloadbalancingrules_client.go @@ -0,0 +1,180 @@ +//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 armnetwork + +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" +) + +// LoadBalancerLoadBalancingRulesClient contains the methods for the LoadBalancerLoadBalancingRules group. +// Don't use this type directly, use NewLoadBalancerLoadBalancingRulesClient() instead. +type LoadBalancerLoadBalancingRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadBalancerLoadBalancingRulesClient creates a new instance of LoadBalancerLoadBalancingRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLoadBalancerLoadBalancingRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancerLoadBalancingRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancerLoadBalancingRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the specified load balancer load balancing rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - loadBalancingRuleName - The name of the load balancing rule. +// - options - LoadBalancerLoadBalancingRulesClientGetOptions contains the optional parameters for the LoadBalancerLoadBalancingRulesClient.Get +// method. +func (client *LoadBalancerLoadBalancingRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string, options *LoadBalancerLoadBalancingRulesClientGetOptions) (LoadBalancerLoadBalancingRulesClientGetResponse, error) { + var err error + const operationName = "LoadBalancerLoadBalancingRulesClient.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, loadBalancerName, loadBalancingRuleName, options) + if err != nil { + return LoadBalancerLoadBalancingRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancerLoadBalancingRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancerLoadBalancingRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadBalancerLoadBalancingRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string, options *LoadBalancerLoadBalancingRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if loadBalancingRuleName == "" { + return nil, errors.New("parameter loadBalancingRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancingRuleName}", url.PathEscape(loadBalancingRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadBalancerLoadBalancingRulesClient) getHandleResponse(resp *http.Response) (LoadBalancerLoadBalancingRulesClientGetResponse, error) { + result := LoadBalancerLoadBalancingRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancingRule); err != nil { + return LoadBalancerLoadBalancingRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the load balancing rules in a load balancer. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancerLoadBalancingRulesClientListOptions contains the optional parameters for the LoadBalancerLoadBalancingRulesClient.NewListPager +// method. +func (client *LoadBalancerLoadBalancingRulesClient) NewListPager(resourceGroupName string, loadBalancerName string, options *LoadBalancerLoadBalancingRulesClientListOptions) *runtime.Pager[LoadBalancerLoadBalancingRulesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancerLoadBalancingRulesClientListResponse]{ + More: func(page LoadBalancerLoadBalancingRulesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancerLoadBalancingRulesClientListResponse) (LoadBalancerLoadBalancingRulesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancerLoadBalancingRulesClient.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, loadBalancerName, options) + }, nil) + if err != nil { + return LoadBalancerLoadBalancingRulesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancerLoadBalancingRulesClient) listCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancerLoadBalancingRulesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancerLoadBalancingRulesClient) listHandleResponse(resp *http.Response) (LoadBalancerLoadBalancingRulesClientListResponse, error) { + result := LoadBalancerLoadBalancingRulesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerLoadBalancingRuleListResult); err != nil { + return LoadBalancerLoadBalancingRulesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancernetworkinterfaces_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancernetworkinterfaces_client.go new file mode 100644 index 000000000..379161ac5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancernetworkinterfaces_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 armnetwork + +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" +) + +// LoadBalancerNetworkInterfacesClient contains the methods for the LoadBalancerNetworkInterfaces group. +// Don't use this type directly, use NewLoadBalancerNetworkInterfacesClient() instead. +type LoadBalancerNetworkInterfacesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadBalancerNetworkInterfacesClient creates a new instance of LoadBalancerNetworkInterfacesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLoadBalancerNetworkInterfacesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancerNetworkInterfacesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancerNetworkInterfacesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets associated load balancer network interfaces. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancerNetworkInterfacesClientListOptions contains the optional parameters for the LoadBalancerNetworkInterfacesClient.NewListPager +// method. +func (client *LoadBalancerNetworkInterfacesClient) NewListPager(resourceGroupName string, loadBalancerName string, options *LoadBalancerNetworkInterfacesClientListOptions) *runtime.Pager[LoadBalancerNetworkInterfacesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancerNetworkInterfacesClientListResponse]{ + More: func(page LoadBalancerNetworkInterfacesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancerNetworkInterfacesClientListResponse) (LoadBalancerNetworkInterfacesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancerNetworkInterfacesClient.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, loadBalancerName, options) + }, nil) + if err != nil { + return LoadBalancerNetworkInterfacesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancerNetworkInterfacesClient) listCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancerNetworkInterfacesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/networkInterfaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancerNetworkInterfacesClient) listHandleResponse(resp *http.Response) (LoadBalancerNetworkInterfacesClientListResponse, error) { + result := LoadBalancerNetworkInterfacesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceListResult); err != nil { + return LoadBalancerNetworkInterfacesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalanceroutboundrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalanceroutboundrules_client.go new file mode 100644 index 000000000..1c4826487 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalanceroutboundrules_client.go @@ -0,0 +1,180 @@ +//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 armnetwork + +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" +) + +// LoadBalancerOutboundRulesClient contains the methods for the LoadBalancerOutboundRules group. +// Don't use this type directly, use NewLoadBalancerOutboundRulesClient() instead. +type LoadBalancerOutboundRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadBalancerOutboundRulesClient creates a new instance of LoadBalancerOutboundRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLoadBalancerOutboundRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancerOutboundRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancerOutboundRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the specified load balancer outbound rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - outboundRuleName - The name of the outbound rule. +// - options - LoadBalancerOutboundRulesClientGetOptions contains the optional parameters for the LoadBalancerOutboundRulesClient.Get +// method. +func (client *LoadBalancerOutboundRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, outboundRuleName string, options *LoadBalancerOutboundRulesClientGetOptions) (LoadBalancerOutboundRulesClientGetResponse, error) { + var err error + const operationName = "LoadBalancerOutboundRulesClient.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, loadBalancerName, outboundRuleName, options) + if err != nil { + return LoadBalancerOutboundRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancerOutboundRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancerOutboundRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadBalancerOutboundRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, outboundRuleName string, options *LoadBalancerOutboundRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/outboundRules/{outboundRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if outboundRuleName == "" { + return nil, errors.New("parameter outboundRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{outboundRuleName}", url.PathEscape(outboundRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadBalancerOutboundRulesClient) getHandleResponse(resp *http.Response) (LoadBalancerOutboundRulesClientGetResponse, error) { + result := LoadBalancerOutboundRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OutboundRule); err != nil { + return LoadBalancerOutboundRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the outbound rules in a load balancer. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancerOutboundRulesClientListOptions contains the optional parameters for the LoadBalancerOutboundRulesClient.NewListPager +// method. +func (client *LoadBalancerOutboundRulesClient) NewListPager(resourceGroupName string, loadBalancerName string, options *LoadBalancerOutboundRulesClientListOptions) *runtime.Pager[LoadBalancerOutboundRulesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancerOutboundRulesClientListResponse]{ + More: func(page LoadBalancerOutboundRulesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancerOutboundRulesClientListResponse) (LoadBalancerOutboundRulesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancerOutboundRulesClient.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, loadBalancerName, options) + }, nil) + if err != nil { + return LoadBalancerOutboundRulesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancerOutboundRulesClient) listCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancerOutboundRulesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/outboundRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancerOutboundRulesClient) listHandleResponse(resp *http.Response) (LoadBalancerOutboundRulesClientListResponse, error) { + result := LoadBalancerOutboundRulesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerOutboundRuleListResult); err != nil { + return LoadBalancerOutboundRulesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerprobes_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerprobes_client.go new file mode 100644 index 000000000..8ab5b64e8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancerprobes_client.go @@ -0,0 +1,179 @@ +//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 armnetwork + +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" +) + +// LoadBalancerProbesClient contains the methods for the LoadBalancerProbes group. +// Don't use this type directly, use NewLoadBalancerProbesClient() instead. +type LoadBalancerProbesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadBalancerProbesClient creates a new instance of LoadBalancerProbesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLoadBalancerProbesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancerProbesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancerProbesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets load balancer probe. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - probeName - The name of the probe. +// - options - LoadBalancerProbesClientGetOptions contains the optional parameters for the LoadBalancerProbesClient.Get method. +func (client *LoadBalancerProbesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, probeName string, options *LoadBalancerProbesClientGetOptions) (LoadBalancerProbesClientGetResponse, error) { + var err error + const operationName = "LoadBalancerProbesClient.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, loadBalancerName, probeName, options) + if err != nil { + return LoadBalancerProbesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancerProbesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancerProbesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadBalancerProbesClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, probeName string, options *LoadBalancerProbesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if probeName == "" { + return nil, errors.New("parameter probeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{probeName}", url.PathEscape(probeName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadBalancerProbesClient) getHandleResponse(resp *http.Response) (LoadBalancerProbesClientGetResponse, error) { + result := LoadBalancerProbesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Probe); err != nil { + return LoadBalancerProbesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the load balancer probes. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancerProbesClientListOptions contains the optional parameters for the LoadBalancerProbesClient.NewListPager +// method. +func (client *LoadBalancerProbesClient) NewListPager(resourceGroupName string, loadBalancerName string, options *LoadBalancerProbesClientListOptions) *runtime.Pager[LoadBalancerProbesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancerProbesClientListResponse]{ + More: func(page LoadBalancerProbesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancerProbesClientListResponse) (LoadBalancerProbesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancerProbesClient.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, loadBalancerName, options) + }, nil) + if err != nil { + return LoadBalancerProbesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancerProbesClient) listCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancerProbesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancerProbesClient) listHandleResponse(resp *http.Response) (LoadBalancerProbesClientListResponse, error) { + result := LoadBalancerProbesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerProbeListResult); err != nil { + return LoadBalancerProbesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancers_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancers_client.go new file mode 100644 index 000000000..3dc0f757c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/loadbalancers_client.go @@ -0,0 +1,686 @@ +//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 armnetwork + +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" +) + +// LoadBalancersClient contains the methods for the LoadBalancers group. +// Don't use this type directly, use NewLoadBalancersClient() instead. +type LoadBalancersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadBalancersClient creates a new instance of LoadBalancersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLoadBalancersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a load balancer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - parameters - Parameters supplied to the create or update load balancer operation. +// - options - LoadBalancersClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadBalancersClient.BeginCreateOrUpdate +// method. +func (client *LoadBalancersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer, options *LoadBalancersClientBeginCreateOrUpdateOptions) (*runtime.Poller[LoadBalancersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, loadBalancerName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadBalancersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadBalancersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a load balancer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LoadBalancersClient) createOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer, options *LoadBalancersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "LoadBalancersClient.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, loadBalancerName, 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 *LoadBalancersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer, options *LoadBalancersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-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 load balancer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancersClientBeginDeleteOptions contains the optional parameters for the LoadBalancersClient.BeginDelete +// method. +func (client *LoadBalancersClient) BeginDelete(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancersClientBeginDeleteOptions) (*runtime.Poller[LoadBalancersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, loadBalancerName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadBalancersClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadBalancersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified load balancer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LoadBalancersClient) deleteOperation(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "LoadBalancersClient.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, loadBalancerName, 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 *LoadBalancersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified load balancer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancersClientGetOptions contains the optional parameters for the LoadBalancersClient.Get method. +func (client *LoadBalancersClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancersClientGetOptions) (LoadBalancersClientGetResponse, error) { + var err error + const operationName = "LoadBalancersClient.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, loadBalancerName, options) + if err != nil { + return LoadBalancersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadBalancersClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, options *LoadBalancersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *LoadBalancersClient) getHandleResponse(resp *http.Response) (LoadBalancersClientGetResponse, error) { + result := LoadBalancersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancer); err != nil { + return LoadBalancersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the load balancers in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - LoadBalancersClientListOptions contains the optional parameters for the LoadBalancersClient.NewListPager method. +func (client *LoadBalancersClient) NewListPager(resourceGroupName string, options *LoadBalancersClientListOptions) *runtime.Pager[LoadBalancersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancersClientListResponse]{ + More: func(page LoadBalancersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancersClientListResponse) (LoadBalancersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancersClient.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, options) + }, nil) + if err != nil { + return LoadBalancersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancersClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *LoadBalancersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancersClient) listHandleResponse(resp *http.Response) (LoadBalancersClientListResponse, error) { + result := LoadBalancersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerListResult); err != nil { + return LoadBalancersClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the load balancers in a subscription. +// +// Generated from API version 2023-05-01 +// - options - LoadBalancersClientListAllOptions contains the optional parameters for the LoadBalancersClient.NewListAllPager +// method. +func (client *LoadBalancersClient) NewListAllPager(options *LoadBalancersClientListAllOptions) *runtime.Pager[LoadBalancersClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancersClientListAllResponse]{ + More: func(page LoadBalancersClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancersClientListAllResponse) (LoadBalancersClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancersClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return LoadBalancersClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *LoadBalancersClient) listAllCreateRequest(ctx context.Context, options *LoadBalancersClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *LoadBalancersClient) listAllHandleResponse(resp *http.Response) (LoadBalancersClientListAllResponse, error) { + result := LoadBalancersClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerListResult); err != nil { + return LoadBalancersClientListAllResponse{}, err + } + return result, nil +} + +// BeginListInboundNatRulePortMappings - List of inbound NAT rule port mappings. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - groupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - backendPoolName - The name of the load balancer backend address pool. +// - parameters - Query inbound NAT rule port mapping request. +// - options - LoadBalancersClientBeginListInboundNatRulePortMappingsOptions contains the optional parameters for the LoadBalancersClient.BeginListInboundNatRulePortMappings +// method. +func (client *LoadBalancersClient) BeginListInboundNatRulePortMappings(ctx context.Context, groupName string, loadBalancerName string, backendPoolName string, parameters QueryInboundNatRulePortMappingRequest, options *LoadBalancersClientBeginListInboundNatRulePortMappingsOptions) (*runtime.Poller[LoadBalancersClientListInboundNatRulePortMappingsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listInboundNatRulePortMappings(ctx, groupName, loadBalancerName, backendPoolName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadBalancersClientListInboundNatRulePortMappingsResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadBalancersClientListInboundNatRulePortMappingsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListInboundNatRulePortMappings - List of inbound NAT rule port mappings. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LoadBalancersClient) listInboundNatRulePortMappings(ctx context.Context, groupName string, loadBalancerName string, backendPoolName string, parameters QueryInboundNatRulePortMappingRequest, options *LoadBalancersClientBeginListInboundNatRulePortMappingsOptions) (*http.Response, error) { + var err error + const operationName = "LoadBalancersClient.BeginListInboundNatRulePortMappings" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listInboundNatRulePortMappingsCreateRequest(ctx, groupName, loadBalancerName, backendPoolName, 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 +} + +// listInboundNatRulePortMappingsCreateRequest creates the ListInboundNatRulePortMappings request. +func (client *LoadBalancersClient) listInboundNatRulePortMappingsCreateRequest(ctx context.Context, groupName string, loadBalancerName string, backendPoolName string, parameters QueryInboundNatRulePortMappingRequest, options *LoadBalancersClientBeginListInboundNatRulePortMappingsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendPoolName}/queryInboundNatRulePortMapping" + if groupName == "" { + return nil, errors.New("parameter groupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupName}", url.PathEscape(groupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + if backendPoolName == "" { + return nil, errors.New("parameter backendPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{backendPoolName}", url.PathEscape(backendPoolName)) + 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-05-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 +} + +// MigrateToIPBased - Migrate load balancer to IP Based +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - groupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - options - LoadBalancersClientMigrateToIPBasedOptions contains the optional parameters for the LoadBalancersClient.MigrateToIPBased +// method. +func (client *LoadBalancersClient) MigrateToIPBased(ctx context.Context, groupName string, loadBalancerName string, options *LoadBalancersClientMigrateToIPBasedOptions) (LoadBalancersClientMigrateToIPBasedResponse, error) { + var err error + const operationName = "LoadBalancersClient.MigrateToIPBased" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.migrateToIPBasedCreateRequest(ctx, groupName, loadBalancerName, options) + if err != nil { + return LoadBalancersClientMigrateToIPBasedResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancersClientMigrateToIPBasedResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancersClientMigrateToIPBasedResponse{}, err + } + resp, err := client.migrateToIPBasedHandleResponse(httpResp) + return resp, err +} + +// migrateToIPBasedCreateRequest creates the MigrateToIPBased request. +func (client *LoadBalancersClient) migrateToIPBasedCreateRequest(ctx context.Context, groupName string, loadBalancerName string, options *LoadBalancersClientMigrateToIPBasedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/migrateToIpBased" + if groupName == "" { + return nil, errors.New("parameter groupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupName}", url.PathEscape(groupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-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 +} + +// migrateToIPBasedHandleResponse handles the MigrateToIPBased response. +func (client *LoadBalancersClient) migrateToIPBasedHandleResponse(resp *http.Response) (LoadBalancersClientMigrateToIPBasedResponse, error) { + result := LoadBalancersClientMigrateToIPBasedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MigratedPools); err != nil { + return LoadBalancersClientMigrateToIPBasedResponse{}, err + } + return result, nil +} + +// BeginSwapPublicIPAddresses - Swaps VIPs between two load balancers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - location - The region where load balancers are located at. +// - parameters - Parameters that define which VIPs should be swapped. +// - options - LoadBalancersClientBeginSwapPublicIPAddressesOptions contains the optional parameters for the LoadBalancersClient.BeginSwapPublicIPAddresses +// method. +func (client *LoadBalancersClient) BeginSwapPublicIPAddresses(ctx context.Context, location string, parameters LoadBalancerVipSwapRequest, options *LoadBalancersClientBeginSwapPublicIPAddressesOptions) (*runtime.Poller[LoadBalancersClientSwapPublicIPAddressesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.swapPublicIPAddresses(ctx, location, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadBalancersClientSwapPublicIPAddressesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadBalancersClientSwapPublicIPAddressesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// SwapPublicIPAddresses - Swaps VIPs between two load balancers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LoadBalancersClient) swapPublicIPAddresses(ctx context.Context, location string, parameters LoadBalancerVipSwapRequest, options *LoadBalancersClientBeginSwapPublicIPAddressesOptions) (*http.Response, error) { + var err error + const operationName = "LoadBalancersClient.BeginSwapPublicIPAddresses" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.swapPublicIPAddressesCreateRequest(ctx, location, 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 +} + +// swapPublicIPAddressesCreateRequest creates the SwapPublicIPAddresses request. +func (client *LoadBalancersClient) swapPublicIPAddressesCreateRequest(ctx context.Context, location string, parameters LoadBalancerVipSwapRequest, options *LoadBalancersClientBeginSwapPublicIPAddressesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/setLoadBalancerFrontendPublicIpAddresses" + 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-05-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 +} + +// UpdateTags - Updates a load balancer tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - loadBalancerName - The name of the load balancer. +// - parameters - Parameters supplied to update load balancer tags. +// - options - LoadBalancersClientUpdateTagsOptions contains the optional parameters for the LoadBalancersClient.UpdateTags +// method. +func (client *LoadBalancersClient) UpdateTags(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject, options *LoadBalancersClientUpdateTagsOptions) (LoadBalancersClientUpdateTagsResponse, error) { + var err error + const operationName = "LoadBalancersClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, loadBalancerName, parameters, options) + if err != nil { + return LoadBalancersClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancersClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancersClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *LoadBalancersClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject, options *LoadBalancersClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *LoadBalancersClient) updateTagsHandleResponse(resp *http.Response) (LoadBalancersClientUpdateTagsResponse, error) { + result := LoadBalancersClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancer); err != nil { + return LoadBalancersClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/localnetworkgateways_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/localnetworkgateways_client.go new file mode 100644 index 000000000..9f5a5e7c1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/localnetworkgateways_client.go @@ -0,0 +1,397 @@ +//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 armnetwork + +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" +) + +// LocalNetworkGatewaysClient contains the methods for the LocalNetworkGateways group. +// Don't use this type directly, use NewLocalNetworkGatewaysClient() instead. +type LocalNetworkGatewaysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLocalNetworkGatewaysClient creates a new instance of LocalNetworkGatewaysClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewLocalNetworkGatewaysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LocalNetworkGatewaysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LocalNetworkGatewaysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a local network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - localNetworkGatewayName - The name of the local network gateway. +// - parameters - Parameters supplied to the create or update local network gateway operation. +// - options - LocalNetworkGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the LocalNetworkGatewaysClient.BeginCreateOrUpdate +// method. +func (client *LocalNetworkGatewaysClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, options *LocalNetworkGatewaysClientBeginCreateOrUpdateOptions) (*runtime.Poller[LocalNetworkGatewaysClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, localNetworkGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LocalNetworkGatewaysClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LocalNetworkGatewaysClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a local network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LocalNetworkGatewaysClient) createOrUpdate(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, options *LocalNetworkGatewaysClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "LocalNetworkGatewaysClient.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, localNetworkGatewayName, 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 *LocalNetworkGatewaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, options *LocalNetworkGatewaysClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if localNetworkGatewayName == "" { + return nil, errors.New("parameter localNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{localNetworkGatewayName}", url.PathEscape(localNetworkGatewayName)) + 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-05-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 local network gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - localNetworkGatewayName - The name of the local network gateway. +// - options - LocalNetworkGatewaysClientBeginDeleteOptions contains the optional parameters for the LocalNetworkGatewaysClient.BeginDelete +// method. +func (client *LocalNetworkGatewaysClient) BeginDelete(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, options *LocalNetworkGatewaysClientBeginDeleteOptions) (*runtime.Poller[LocalNetworkGatewaysClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, localNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LocalNetworkGatewaysClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LocalNetworkGatewaysClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified local network gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *LocalNetworkGatewaysClient) deleteOperation(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, options *LocalNetworkGatewaysClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "LocalNetworkGatewaysClient.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, localNetworkGatewayName, 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 *LocalNetworkGatewaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, options *LocalNetworkGatewaysClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if localNetworkGatewayName == "" { + return nil, errors.New("parameter localNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{localNetworkGatewayName}", url.PathEscape(localNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified local network gateway in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - localNetworkGatewayName - The name of the local network gateway. +// - options - LocalNetworkGatewaysClientGetOptions contains the optional parameters for the LocalNetworkGatewaysClient.Get +// method. +func (client *LocalNetworkGatewaysClient) Get(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, options *LocalNetworkGatewaysClientGetOptions) (LocalNetworkGatewaysClientGetResponse, error) { + var err error + const operationName = "LocalNetworkGatewaysClient.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, localNetworkGatewayName, options) + if err != nil { + return LocalNetworkGatewaysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalNetworkGatewaysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocalNetworkGatewaysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LocalNetworkGatewaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, options *LocalNetworkGatewaysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if localNetworkGatewayName == "" { + return nil, errors.New("parameter localNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{localNetworkGatewayName}", url.PathEscape(localNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LocalNetworkGatewaysClient) getHandleResponse(resp *http.Response) (LocalNetworkGatewaysClientGetResponse, error) { + result := LocalNetworkGatewaysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalNetworkGateway); err != nil { + return LocalNetworkGatewaysClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the local network gateways in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - LocalNetworkGatewaysClientListOptions contains the optional parameters for the LocalNetworkGatewaysClient.NewListPager +// method. +func (client *LocalNetworkGatewaysClient) NewListPager(resourceGroupName string, options *LocalNetworkGatewaysClientListOptions) *runtime.Pager[LocalNetworkGatewaysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LocalNetworkGatewaysClientListResponse]{ + More: func(page LocalNetworkGatewaysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LocalNetworkGatewaysClientListResponse) (LocalNetworkGatewaysClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LocalNetworkGatewaysClient.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, options) + }, nil) + if err != nil { + return LocalNetworkGatewaysClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LocalNetworkGatewaysClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *LocalNetworkGatewaysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LocalNetworkGatewaysClient) listHandleResponse(resp *http.Response) (LocalNetworkGatewaysClientListResponse, error) { + result := LocalNetworkGatewaysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalNetworkGatewayListResult); err != nil { + return LocalNetworkGatewaysClientListResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a local network gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - localNetworkGatewayName - The name of the local network gateway. +// - parameters - Parameters supplied to update local network gateway tags. +// - options - LocalNetworkGatewaysClientUpdateTagsOptions contains the optional parameters for the LocalNetworkGatewaysClient.UpdateTags +// method. +func (client *LocalNetworkGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters TagsObject, options *LocalNetworkGatewaysClientUpdateTagsOptions) (LocalNetworkGatewaysClientUpdateTagsResponse, error) { + var err error + const operationName = "LocalNetworkGatewaysClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, localNetworkGatewayName, parameters, options) + if err != nil { + return LocalNetworkGatewaysClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalNetworkGatewaysClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocalNetworkGatewaysClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *LocalNetworkGatewaysClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters TagsObject, options *LocalNetworkGatewaysClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if localNetworkGatewayName == "" { + return nil, errors.New("parameter localNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{localNetworkGatewayName}", url.PathEscape(localNetworkGatewayName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *LocalNetworkGatewaysClient) updateTagsHandleResponse(resp *http.Response) (LocalNetworkGatewaysClientUpdateTagsResponse, error) { + result := LocalNetworkGatewaysClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalNetworkGateway); err != nil { + return LocalNetworkGatewaysClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/management_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/management_client.go new file mode 100644 index 000000000..2955b415a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/management_client.go @@ -0,0 +1,1032 @@ +//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 armnetwork + +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" +) + +// ManagementClient contains the methods for the NetworkManagementClient group. +// Don't use this type directly, use NewManagementClient() instead. +type ManagementClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagementClient creates a new instance of ManagementClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewManagementClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagementClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagementClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckDNSNameAvailability - Checks whether a domain name in the cloudapp.azure.com zone is available for use. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - domainNameLabel - The domain name to be verified. It must conform to the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. +// - options - ManagementClientCheckDNSNameAvailabilityOptions contains the optional parameters for the ManagementClient.CheckDNSNameAvailability +// method. +func (client *ManagementClient) CheckDNSNameAvailability(ctx context.Context, location string, domainNameLabel string, options *ManagementClientCheckDNSNameAvailabilityOptions) (ManagementClientCheckDNSNameAvailabilityResponse, error) { + var err error + const operationName = "ManagementClient.CheckDNSNameAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkDNSNameAvailabilityCreateRequest(ctx, location, domainNameLabel, options) + if err != nil { + return ManagementClientCheckDNSNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientCheckDNSNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientCheckDNSNameAvailabilityResponse{}, err + } + resp, err := client.checkDNSNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkDNSNameAvailabilityCreateRequest creates the CheckDNSNameAvailability request. +func (client *ManagementClient) checkDNSNameAvailabilityCreateRequest(ctx context.Context, location string, domainNameLabel string, options *ManagementClientCheckDNSNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability" + 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("domainNameLabel", domainNameLabel) + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// checkDNSNameAvailabilityHandleResponse handles the CheckDNSNameAvailability response. +func (client *ManagementClient) checkDNSNameAvailabilityHandleResponse(resp *http.Response) (ManagementClientCheckDNSNameAvailabilityResponse, error) { + result := ManagementClientCheckDNSNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DNSNameAvailabilityResult); err != nil { + return ManagementClientCheckDNSNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginDeleteBastionShareableLink - Deletes the Bastion Shareable Links for all the VMs specified in the request. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - bslRequest - Post request for all the Bastion Shareable Link endpoints. +// - options - ManagementClientBeginDeleteBastionShareableLinkOptions contains the optional parameters for the ManagementClient.BeginDeleteBastionShareableLink +// method. +func (client *ManagementClient) BeginDeleteBastionShareableLink(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientBeginDeleteBastionShareableLinkOptions) (*runtime.Poller[ManagementClientDeleteBastionShareableLinkResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteBastionShareableLink(ctx, resourceGroupName, bastionHostName, bslRequest, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagementClientDeleteBastionShareableLinkResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagementClientDeleteBastionShareableLinkResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeleteBastionShareableLink - Deletes the Bastion Shareable Links for all the VMs specified in the request. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ManagementClient) deleteBastionShareableLink(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientBeginDeleteBastionShareableLinkOptions) (*http.Response, error) { + var err error + const operationName = "ManagementClient.BeginDeleteBastionShareableLink" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteBastionShareableLinkCreateRequest(ctx, resourceGroupName, bastionHostName, bslRequest, 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 +} + +// deleteBastionShareableLinkCreateRequest creates the DeleteBastionShareableLink request. +func (client *ManagementClient) deleteBastionShareableLinkCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientBeginDeleteBastionShareableLinkOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/deleteShareableLinks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, bslRequest); err != nil { + return nil, err + } + return req, nil +} + +// NewDisconnectActiveSessionsPager - Returns the list of currently active sessions on the Bastion. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - sessionIDs - The list of sessionids to disconnect. +// - options - ManagementClientDisconnectActiveSessionsOptions contains the optional parameters for the ManagementClient.NewDisconnectActiveSessionsPager +// method. +func (client *ManagementClient) NewDisconnectActiveSessionsPager(resourceGroupName string, bastionHostName string, sessionIDs SessionIDs, options *ManagementClientDisconnectActiveSessionsOptions) *runtime.Pager[ManagementClientDisconnectActiveSessionsResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagementClientDisconnectActiveSessionsResponse]{ + More: func(page ManagementClientDisconnectActiveSessionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagementClientDisconnectActiveSessionsResponse) (ManagementClientDisconnectActiveSessionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagementClient.NewDisconnectActiveSessionsPager") + 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.disconnectActiveSessionsCreateRequest(ctx, resourceGroupName, bastionHostName, sessionIDs, options) + }, nil) + if err != nil { + return ManagementClientDisconnectActiveSessionsResponse{}, err + } + return client.disconnectActiveSessionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// disconnectActiveSessionsCreateRequest creates the DisconnectActiveSessions request. +func (client *ManagementClient) disconnectActiveSessionsCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, sessionIDs SessionIDs, options *ManagementClientDisconnectActiveSessionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/disconnectActiveSessions" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, sessionIDs); err != nil { + return nil, err + } + return req, nil +} + +// disconnectActiveSessionsHandleResponse handles the DisconnectActiveSessions response. +func (client *ManagementClient) disconnectActiveSessionsHandleResponse(resp *http.Response) (ManagementClientDisconnectActiveSessionsResponse, error) { + result := ManagementClientDisconnectActiveSessionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BastionSessionDeleteResult); err != nil { + return ManagementClientDisconnectActiveSessionsResponse{}, err + } + return result, nil +} + +// ExpressRouteProviderPort - Retrieves detail of a provider port. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - providerport - The name of the provider port. +// - options - ManagementClientExpressRouteProviderPortOptions contains the optional parameters for the ManagementClient.ExpressRouteProviderPort +// method. +func (client *ManagementClient) ExpressRouteProviderPort(ctx context.Context, providerport string, options *ManagementClientExpressRouteProviderPortOptions) (ManagementClientExpressRouteProviderPortResponse, error) { + var err error + const operationName = "ManagementClient.ExpressRouteProviderPort" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.expressRouteProviderPortCreateRequest(ctx, providerport, options) + if err != nil { + return ManagementClientExpressRouteProviderPortResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientExpressRouteProviderPortResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientExpressRouteProviderPortResponse{}, err + } + resp, err := client.expressRouteProviderPortHandleResponse(httpResp) + return resp, err +} + +// expressRouteProviderPortCreateRequest creates the ExpressRouteProviderPort request. +func (client *ManagementClient) expressRouteProviderPortCreateRequest(ctx context.Context, providerport string, options *ManagementClientExpressRouteProviderPortOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteProviderPorts/{providerport}" + if providerport == "" { + return nil, errors.New("parameter providerport cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{providerport}", url.PathEscape(providerport)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// expressRouteProviderPortHandleResponse handles the ExpressRouteProviderPort response. +func (client *ManagementClient) expressRouteProviderPortHandleResponse(resp *http.Response) (ManagementClientExpressRouteProviderPortResponse, error) { + result := ManagementClientExpressRouteProviderPortResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExpressRouteProviderPort); err != nil { + return ManagementClientExpressRouteProviderPortResponse{}, err + } + return result, nil +} + +// BeginGeneratevirtualwanvpnserverconfigurationvpnprofile - Generates a unique VPN profile for P2S clients for VirtualWan +// and associated VpnServerConfiguration combination in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name. +// - virtualWANName - The name of the VirtualWAN whose associated VpnServerConfigurations is needed. +// - vpnClientParams - Parameters supplied to the generate VirtualWan VPN profile generation operation. +// - options - ManagementClientBeginGeneratevirtualwanvpnserverconfigurationvpnprofileOptions contains the optional parameters +// for the ManagementClient.BeginGeneratevirtualwanvpnserverconfigurationvpnprofile method. +func (client *ManagementClient) BeginGeneratevirtualwanvpnserverconfigurationvpnprofile(ctx context.Context, resourceGroupName string, virtualWANName string, vpnClientParams VirtualWanVPNProfileParameters, options *ManagementClientBeginGeneratevirtualwanvpnserverconfigurationvpnprofileOptions) (*runtime.Poller[ManagementClientGeneratevirtualwanvpnserverconfigurationvpnprofileResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.generatevirtualwanvpnserverconfigurationvpnprofile(ctx, resourceGroupName, virtualWANName, vpnClientParams, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagementClientGeneratevirtualwanvpnserverconfigurationvpnprofileResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagementClientGeneratevirtualwanvpnserverconfigurationvpnprofileResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Generatevirtualwanvpnserverconfigurationvpnprofile - Generates a unique VPN profile for P2S clients for VirtualWan and +// associated VpnServerConfiguration combination in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ManagementClient) generatevirtualwanvpnserverconfigurationvpnprofile(ctx context.Context, resourceGroupName string, virtualWANName string, vpnClientParams VirtualWanVPNProfileParameters, options *ManagementClientBeginGeneratevirtualwanvpnserverconfigurationvpnprofileOptions) (*http.Response, error) { + var err error + const operationName = "ManagementClient.BeginGeneratevirtualwanvpnserverconfigurationvpnprofile" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generatevirtualwanvpnserverconfigurationvpnprofileCreateRequest(ctx, resourceGroupName, virtualWANName, vpnClientParams, 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 +} + +// generatevirtualwanvpnserverconfigurationvpnprofileCreateRequest creates the Generatevirtualwanvpnserverconfigurationvpnprofile request. +func (client *ManagementClient) generatevirtualwanvpnserverconfigurationvpnprofileCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, vpnClientParams VirtualWanVPNProfileParameters, options *ManagementClientBeginGeneratevirtualwanvpnserverconfigurationvpnprofileOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/GenerateVpnProfile" + 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 virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualWANName}", url.PathEscape(virtualWANName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnClientParams); err != nil { + return nil, err + } + return req, nil +} + +// BeginGetActiveSessions - Returns the list of currently active sessions on the Bastion. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - options - ManagementClientBeginGetActiveSessionsOptions contains the optional parameters for the ManagementClient.BeginGetActiveSessions +// method. +func (client *ManagementClient) BeginGetActiveSessions(ctx context.Context, resourceGroupName string, bastionHostName string, options *ManagementClientBeginGetActiveSessionsOptions) (*runtime.Poller[*runtime.Pager[ManagementClientGetActiveSessionsResponse]], error) { + pager := runtime.NewPager(runtime.PagingHandler[ManagementClientGetActiveSessionsResponse]{ + More: func(page ManagementClientGetActiveSessionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagementClientGetActiveSessionsResponse) (ManagementClientGetActiveSessionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagementClient.BeginGetActiveSessions") + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), *page.NextLink, func(ctx context.Context) (*policy.Request, error) { + return client.getActiveSessionsCreateRequest(ctx, resourceGroupName, bastionHostName, options) + }, nil) + if err != nil { + return ManagementClientGetActiveSessionsResponse{}, err + } + return client.getActiveSessionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) + if options == nil || options.ResumeToken == "" { + resp, err := client.getActiveSessions(ctx, resourceGroupName, bastionHostName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[*runtime.Pager[ManagementClientGetActiveSessionsResponse]]{ + FinalStateVia: runtime.FinalStateViaLocation, + Response: &pager, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[*runtime.Pager[ManagementClientGetActiveSessionsResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + } +} + +// GetActiveSessions - Returns the list of currently active sessions on the Bastion. +// +// Generated from API version 2023-05-01 +func (client *ManagementClient) getActiveSessions(ctx context.Context, resourceGroupName string, bastionHostName string, options *ManagementClientBeginGetActiveSessionsOptions) (*http.Response, error) { + var err error + const operationName = "ManagementClient.BeginGetActiveSessions" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getActiveSessionsCreateRequest(ctx, resourceGroupName, bastionHostName, 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 +} + +// getActiveSessionsCreateRequest creates the GetActiveSessions request. +func (client *ManagementClient) getActiveSessionsCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, options *ManagementClientBeginGetActiveSessionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/getActiveSessions" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getActiveSessionsHandleResponse handles the GetActiveSessions response. +func (client *ManagementClient) getActiveSessionsHandleResponse(resp *http.Response) (ManagementClientGetActiveSessionsResponse, error) { + result := ManagementClientGetActiveSessionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BastionActiveSessionListResult); err != nil { + return ManagementClientGetActiveSessionsResponse{}, err + } + return result, nil +} + +// NewGetBastionShareableLinkPager - Return the Bastion Shareable Links for all the VMs specified in the request. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - bslRequest - Post request for all the Bastion Shareable Link endpoints. +// - options - ManagementClientGetBastionShareableLinkOptions contains the optional parameters for the ManagementClient.NewGetBastionShareableLinkPager +// method. +func (client *ManagementClient) NewGetBastionShareableLinkPager(resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientGetBastionShareableLinkOptions) *runtime.Pager[ManagementClientGetBastionShareableLinkResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagementClientGetBastionShareableLinkResponse]{ + More: func(page ManagementClientGetBastionShareableLinkResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagementClientGetBastionShareableLinkResponse) (ManagementClientGetBastionShareableLinkResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagementClient.NewGetBastionShareableLinkPager") + 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.getBastionShareableLinkCreateRequest(ctx, resourceGroupName, bastionHostName, bslRequest, options) + }, nil) + if err != nil { + return ManagementClientGetBastionShareableLinkResponse{}, err + } + return client.getBastionShareableLinkHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// getBastionShareableLinkCreateRequest creates the GetBastionShareableLink request. +func (client *ManagementClient) getBastionShareableLinkCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientGetBastionShareableLinkOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/getShareableLinks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, bslRequest); err != nil { + return nil, err + } + return req, nil +} + +// getBastionShareableLinkHandleResponse handles the GetBastionShareableLink response. +func (client *ManagementClient) getBastionShareableLinkHandleResponse(resp *http.Response) (ManagementClientGetBastionShareableLinkResponse, error) { + result := ManagementClientGetBastionShareableLinkResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BastionShareableLinkListResult); err != nil { + return ManagementClientGetBastionShareableLinkResponse{}, err + } + return result, nil +} + +// ListActiveConnectivityConfigurations - Lists active connectivity configurations in a network manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - parameters - Active Configuration Parameter. +// - options - ManagementClientListActiveConnectivityConfigurationsOptions contains the optional parameters for the ManagementClient.ListActiveConnectivityConfigurations +// method. +func (client *ManagementClient) ListActiveConnectivityConfigurations(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ActiveConfigurationParameter, options *ManagementClientListActiveConnectivityConfigurationsOptions) (ManagementClientListActiveConnectivityConfigurationsResponse, error) { + var err error + const operationName = "ManagementClient.ListActiveConnectivityConfigurations" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listActiveConnectivityConfigurationsCreateRequest(ctx, resourceGroupName, networkManagerName, parameters, options) + if err != nil { + return ManagementClientListActiveConnectivityConfigurationsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientListActiveConnectivityConfigurationsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientListActiveConnectivityConfigurationsResponse{}, err + } + resp, err := client.listActiveConnectivityConfigurationsHandleResponse(httpResp) + return resp, err +} + +// listActiveConnectivityConfigurationsCreateRequest creates the ListActiveConnectivityConfigurations request. +func (client *ManagementClient) listActiveConnectivityConfigurationsCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ActiveConfigurationParameter, options *ManagementClientListActiveConnectivityConfigurationsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/listActiveConnectivityConfigurations" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + 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"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// listActiveConnectivityConfigurationsHandleResponse handles the ListActiveConnectivityConfigurations response. +func (client *ManagementClient) listActiveConnectivityConfigurationsHandleResponse(resp *http.Response) (ManagementClientListActiveConnectivityConfigurationsResponse, error) { + result := ManagementClientListActiveConnectivityConfigurationsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ActiveConnectivityConfigurationsListResult); err != nil { + return ManagementClientListActiveConnectivityConfigurationsResponse{}, err + } + return result, nil +} + +// ListActiveSecurityAdminRules - Lists active security admin rules in a network manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - parameters - Active Configuration Parameter. +// - options - ManagementClientListActiveSecurityAdminRulesOptions contains the optional parameters for the ManagementClient.ListActiveSecurityAdminRules +// method. +func (client *ManagementClient) ListActiveSecurityAdminRules(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ActiveConfigurationParameter, options *ManagementClientListActiveSecurityAdminRulesOptions) (ManagementClientListActiveSecurityAdminRulesResponse, error) { + var err error + const operationName = "ManagementClient.ListActiveSecurityAdminRules" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listActiveSecurityAdminRulesCreateRequest(ctx, resourceGroupName, networkManagerName, parameters, options) + if err != nil { + return ManagementClientListActiveSecurityAdminRulesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientListActiveSecurityAdminRulesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientListActiveSecurityAdminRulesResponse{}, err + } + resp, err := client.listActiveSecurityAdminRulesHandleResponse(httpResp) + return resp, err +} + +// listActiveSecurityAdminRulesCreateRequest creates the ListActiveSecurityAdminRules request. +func (client *ManagementClient) listActiveSecurityAdminRulesCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ActiveConfigurationParameter, options *ManagementClientListActiveSecurityAdminRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/listActiveSecurityAdminRules" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + 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"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// listActiveSecurityAdminRulesHandleResponse handles the ListActiveSecurityAdminRules response. +func (client *ManagementClient) listActiveSecurityAdminRulesHandleResponse(resp *http.Response) (ManagementClientListActiveSecurityAdminRulesResponse, error) { + result := ManagementClientListActiveSecurityAdminRulesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ActiveSecurityAdminRulesListResult); err != nil { + return ManagementClientListActiveSecurityAdminRulesResponse{}, err + } + return result, nil +} + +// ListNetworkManagerEffectiveConnectivityConfigurations - List all effective connectivity configurations applied on a virtual +// network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - parameters - Parameters supplied to list correct page. +// - options - ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions contains the optional parameters +// for the ManagementClient.ListNetworkManagerEffectiveConnectivityConfigurations method. +func (client *ManagementClient) ListNetworkManagerEffectiveConnectivityConfigurations(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters QueryRequestOptions, options *ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions) (ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse, error) { + var err error + const operationName = "ManagementClient.ListNetworkManagerEffectiveConnectivityConfigurations" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listNetworkManagerEffectiveConnectivityConfigurationsCreateRequest(ctx, resourceGroupName, virtualNetworkName, parameters, options) + if err != nil { + return ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse{}, err + } + resp, err := client.listNetworkManagerEffectiveConnectivityConfigurationsHandleResponse(httpResp) + return resp, err +} + +// listNetworkManagerEffectiveConnectivityConfigurationsCreateRequest creates the ListNetworkManagerEffectiveConnectivityConfigurations request. +func (client *ManagementClient) listNetworkManagerEffectiveConnectivityConfigurationsCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters QueryRequestOptions, options *ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/listNetworkManagerEffectiveConnectivityConfigurations" + 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 virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-01") + 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"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// listNetworkManagerEffectiveConnectivityConfigurationsHandleResponse handles the ListNetworkManagerEffectiveConnectivityConfigurations response. +func (client *ManagementClient) listNetworkManagerEffectiveConnectivityConfigurationsHandleResponse(resp *http.Response) (ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse, error) { + result := ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerEffectiveConnectivityConfigurationListResult); err != nil { + return ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse{}, err + } + return result, nil +} + +// ListNetworkManagerEffectiveSecurityAdminRules - List all effective security admin rules applied on a virtual network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - parameters - Parameters supplied to list correct page. +// - options - ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions contains the optional parameters for the +// ManagementClient.ListNetworkManagerEffectiveSecurityAdminRules method. +func (client *ManagementClient) ListNetworkManagerEffectiveSecurityAdminRules(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters QueryRequestOptions, options *ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions) (ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse, error) { + var err error + const operationName = "ManagementClient.ListNetworkManagerEffectiveSecurityAdminRules" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listNetworkManagerEffectiveSecurityAdminRulesCreateRequest(ctx, resourceGroupName, virtualNetworkName, parameters, options) + if err != nil { + return ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse{}, err + } + resp, err := client.listNetworkManagerEffectiveSecurityAdminRulesHandleResponse(httpResp) + return resp, err +} + +// listNetworkManagerEffectiveSecurityAdminRulesCreateRequest creates the ListNetworkManagerEffectiveSecurityAdminRules request. +func (client *ManagementClient) listNetworkManagerEffectiveSecurityAdminRulesCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters QueryRequestOptions, options *ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/listNetworkManagerEffectiveSecurityAdminRules" + 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 virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-01") + 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"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// listNetworkManagerEffectiveSecurityAdminRulesHandleResponse handles the ListNetworkManagerEffectiveSecurityAdminRules response. +func (client *ManagementClient) listNetworkManagerEffectiveSecurityAdminRulesHandleResponse(resp *http.Response) (ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse, error) { + result := ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerEffectiveSecurityAdminRulesListResult); err != nil { + return ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse{}, err + } + return result, nil +} + +// BeginPutBastionShareableLink - Creates a Bastion Shareable Links for all the VMs specified in the request. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - bastionHostName - The name of the Bastion Host. +// - bslRequest - Post request for all the Bastion Shareable Link endpoints. +// - options - ManagementClientBeginPutBastionShareableLinkOptions contains the optional parameters for the ManagementClient.BeginPutBastionShareableLink +// method. +func (client *ManagementClient) BeginPutBastionShareableLink(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientBeginPutBastionShareableLinkOptions) (*runtime.Poller[*runtime.Pager[ManagementClientPutBastionShareableLinkResponse]], error) { + pager := runtime.NewPager(runtime.PagingHandler[ManagementClientPutBastionShareableLinkResponse]{ + More: func(page ManagementClientPutBastionShareableLinkResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagementClientPutBastionShareableLinkResponse) (ManagementClientPutBastionShareableLinkResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagementClient.BeginPutBastionShareableLink") + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), *page.NextLink, func(ctx context.Context) (*policy.Request, error) { + return client.putBastionShareableLinkCreateRequest(ctx, resourceGroupName, bastionHostName, bslRequest, options) + }, nil) + if err != nil { + return ManagementClientPutBastionShareableLinkResponse{}, err + } + return client.putBastionShareableLinkHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) + if options == nil || options.ResumeToken == "" { + resp, err := client.putBastionShareableLink(ctx, resourceGroupName, bastionHostName, bslRequest, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[*runtime.Pager[ManagementClientPutBastionShareableLinkResponse]]{ + FinalStateVia: runtime.FinalStateViaLocation, + Response: &pager, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[*runtime.Pager[ManagementClientPutBastionShareableLinkResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + } +} + +// PutBastionShareableLink - Creates a Bastion Shareable Links for all the VMs specified in the request. +// +// Generated from API version 2023-05-01 +func (client *ManagementClient) putBastionShareableLink(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientBeginPutBastionShareableLinkOptions) (*http.Response, error) { + var err error + const operationName = "ManagementClient.BeginPutBastionShareableLink" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putBastionShareableLinkCreateRequest(ctx, resourceGroupName, bastionHostName, bslRequest, 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 +} + +// putBastionShareableLinkCreateRequest creates the PutBastionShareableLink request. +func (client *ManagementClient) putBastionShareableLinkCreateRequest(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest, options *ManagementClientBeginPutBastionShareableLinkOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/createShareableLinks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bastionHostName == "" { + return nil, errors.New("parameter bastionHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bastionHostName}", url.PathEscape(bastionHostName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, bslRequest); err != nil { + return nil, err + } + return req, nil +} + +// putBastionShareableLinkHandleResponse handles the PutBastionShareableLink response. +func (client *ManagementClient) putBastionShareableLinkHandleResponse(resp *http.Response) (ManagementClientPutBastionShareableLinkResponse, error) { + result := ManagementClientPutBastionShareableLinkResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BastionShareableLinkListResult); err != nil { + return ManagementClientPutBastionShareableLinkResponse{}, err + } + return result, nil +} + +// SupportedSecurityProviders - Gives the supported security providers for the virtual wan. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name. +// - virtualWANName - The name of the VirtualWAN for which supported security providers are needed. +// - options - ManagementClientSupportedSecurityProvidersOptions contains the optional parameters for the ManagementClient.SupportedSecurityProviders +// method. +func (client *ManagementClient) SupportedSecurityProviders(ctx context.Context, resourceGroupName string, virtualWANName string, options *ManagementClientSupportedSecurityProvidersOptions) (ManagementClientSupportedSecurityProvidersResponse, error) { + var err error + const operationName = "ManagementClient.SupportedSecurityProviders" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.supportedSecurityProvidersCreateRequest(ctx, resourceGroupName, virtualWANName, options) + if err != nil { + return ManagementClientSupportedSecurityProvidersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientSupportedSecurityProvidersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientSupportedSecurityProvidersResponse{}, err + } + resp, err := client.supportedSecurityProvidersHandleResponse(httpResp) + return resp, err +} + +// supportedSecurityProvidersCreateRequest creates the SupportedSecurityProviders request. +func (client *ManagementClient) supportedSecurityProvidersCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, options *ManagementClientSupportedSecurityProvidersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/supportedSecurityProviders" + 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 virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualWANName}", url.PathEscape(virtualWANName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// supportedSecurityProvidersHandleResponse handles the SupportedSecurityProviders response. +func (client *ManagementClient) supportedSecurityProvidersHandleResponse(resp *http.Response) (ManagementClientSupportedSecurityProvidersResponse, error) { + result := ManagementClientSupportedSecurityProvidersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualWanSecurityProviders); err != nil { + return ManagementClientSupportedSecurityProvidersResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managementgroupnetworkmanagerconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managementgroupnetworkmanagerconnections_client.go new file mode 100644 index 000000000..a672f6e34 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managementgroupnetworkmanagerconnections_client.go @@ -0,0 +1,281 @@ +//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 armnetwork + +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" +) + +// ManagementGroupNetworkManagerConnectionsClient contains the methods for the ManagementGroupNetworkManagerConnections group. +// Don't use this type directly, use NewManagementGroupNetworkManagerConnectionsClient() instead. +type ManagementGroupNetworkManagerConnectionsClient struct { + internal *arm.Client +} + +// NewManagementGroupNetworkManagerConnectionsClient creates a new instance of ManagementGroupNetworkManagerConnectionsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewManagementGroupNetworkManagerConnectionsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagementGroupNetworkManagerConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagementGroupNetworkManagerConnectionsClient{ + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a network manager connection on this management group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - managementGroupID - The management group Id which uniquely identify the Microsoft Azure management group. +// - networkManagerConnectionName - Name for the network manager connection. +// - parameters - Network manager connection to be created/updated. +// - options - ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateOptions contains the optional parameters for the +// ManagementGroupNetworkManagerConnectionsClient.CreateOrUpdate method. +func (client *ManagementGroupNetworkManagerConnectionsClient) CreateOrUpdate(ctx context.Context, managementGroupID string, networkManagerConnectionName string, parameters ManagerConnection, options *ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateOptions) (ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ManagementGroupNetworkManagerConnectionsClient.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, managementGroupID, networkManagerConnectionName, parameters, options) + if err != nil { + return ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ManagementGroupNetworkManagerConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, managementGroupID string, networkManagerConnectionName string, parameters ManagerConnection, options *ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}" + if managementGroupID == "" { + return nil, errors.New("parameter managementGroupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupId}", url.PathEscape(managementGroupID)) + if networkManagerConnectionName == "" { + return nil, errors.New("parameter networkManagerConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerConnectionName}", url.PathEscape(networkManagerConnectionName)) + 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-05-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 *ManagementGroupNetworkManagerConnectionsClient) createOrUpdateHandleResponse(resp *http.Response) (ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse, error) { + result := ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerConnection); err != nil { + return ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete specified pending connection created by this management group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - managementGroupID - The management group Id which uniquely identify the Microsoft Azure management group. +// - networkManagerConnectionName - Name for the network manager connection. +// - options - ManagementGroupNetworkManagerConnectionsClientDeleteOptions contains the optional parameters for the ManagementGroupNetworkManagerConnectionsClient.Delete +// method. +func (client *ManagementGroupNetworkManagerConnectionsClient) Delete(ctx context.Context, managementGroupID string, networkManagerConnectionName string, options *ManagementGroupNetworkManagerConnectionsClientDeleteOptions) (ManagementGroupNetworkManagerConnectionsClientDeleteResponse, error) { + var err error + const operationName = "ManagementGroupNetworkManagerConnectionsClient.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, managementGroupID, networkManagerConnectionName, options) + if err != nil { + return ManagementGroupNetworkManagerConnectionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementGroupNetworkManagerConnectionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ManagementGroupNetworkManagerConnectionsClientDeleteResponse{}, err + } + return ManagementGroupNetworkManagerConnectionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ManagementGroupNetworkManagerConnectionsClient) deleteCreateRequest(ctx context.Context, managementGroupID string, networkManagerConnectionName string, options *ManagementGroupNetworkManagerConnectionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}" + if managementGroupID == "" { + return nil, errors.New("parameter managementGroupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupId}", url.PathEscape(managementGroupID)) + if networkManagerConnectionName == "" { + return nil, errors.New("parameter networkManagerConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerConnectionName}", url.PathEscape(networkManagerConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a specified connection created by this management group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - managementGroupID - The management group Id which uniquely identify the Microsoft Azure management group. +// - networkManagerConnectionName - Name for the network manager connection. +// - options - ManagementGroupNetworkManagerConnectionsClientGetOptions contains the optional parameters for the ManagementGroupNetworkManagerConnectionsClient.Get +// method. +func (client *ManagementGroupNetworkManagerConnectionsClient) Get(ctx context.Context, managementGroupID string, networkManagerConnectionName string, options *ManagementGroupNetworkManagerConnectionsClientGetOptions) (ManagementGroupNetworkManagerConnectionsClientGetResponse, error) { + var err error + const operationName = "ManagementGroupNetworkManagerConnectionsClient.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, managementGroupID, networkManagerConnectionName, options) + if err != nil { + return ManagementGroupNetworkManagerConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementGroupNetworkManagerConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementGroupNetworkManagerConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ManagementGroupNetworkManagerConnectionsClient) getCreateRequest(ctx context.Context, managementGroupID string, networkManagerConnectionName string, options *ManagementGroupNetworkManagerConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}" + if managementGroupID == "" { + return nil, errors.New("parameter managementGroupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupId}", url.PathEscape(managementGroupID)) + if networkManagerConnectionName == "" { + return nil, errors.New("parameter networkManagerConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerConnectionName}", url.PathEscape(networkManagerConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagementGroupNetworkManagerConnectionsClient) getHandleResponse(resp *http.Response) (ManagementGroupNetworkManagerConnectionsClientGetResponse, error) { + result := ManagementGroupNetworkManagerConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerConnection); err != nil { + return ManagementGroupNetworkManagerConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all network manager connections created by this management group. +// +// Generated from API version 2023-05-01 +// - managementGroupID - The management group Id which uniquely identify the Microsoft Azure management group. +// - options - ManagementGroupNetworkManagerConnectionsClientListOptions contains the optional parameters for the ManagementGroupNetworkManagerConnectionsClient.NewListPager +// method. +func (client *ManagementGroupNetworkManagerConnectionsClient) NewListPager(managementGroupID string, options *ManagementGroupNetworkManagerConnectionsClientListOptions) *runtime.Pager[ManagementGroupNetworkManagerConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagementGroupNetworkManagerConnectionsClientListResponse]{ + More: func(page ManagementGroupNetworkManagerConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagementGroupNetworkManagerConnectionsClientListResponse) (ManagementGroupNetworkManagerConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagementGroupNetworkManagerConnectionsClient.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, managementGroupID, options) + }, nil) + if err != nil { + return ManagementGroupNetworkManagerConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ManagementGroupNetworkManagerConnectionsClient) listCreateRequest(ctx context.Context, managementGroupID string, options *ManagementGroupNetworkManagerConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections" + if managementGroupID == "" { + return nil, errors.New("parameter managementGroupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupId}", url.PathEscape(managementGroupID)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ManagementGroupNetworkManagerConnectionsClient) listHandleResponse(resp *http.Response) (ManagementGroupNetworkManagerConnectionsClientListResponse, error) { + result := ManagementGroupNetworkManagerConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerConnectionListResult); err != nil { + return ManagementGroupNetworkManagerConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managercommits_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managercommits_client.go new file mode 100644 index 000000000..664336970 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managercommits_client.go @@ -0,0 +1,126 @@ +//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 armnetwork + +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" +) + +// ManagerCommitsClient contains the methods for the NetworkManagerCommits group. +// Don't use this type directly, use NewManagerCommitsClient() instead. +type ManagerCommitsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagerCommitsClient creates a new instance of ManagerCommitsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewManagerCommitsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagerCommitsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagerCommitsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginPost - Post a Network Manager Commit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - parameters - Parameters supplied to specify which Managed Network commit is. +// - options - ManagerCommitsClientBeginPostOptions contains the optional parameters for the ManagerCommitsClient.BeginPost +// method. +func (client *ManagerCommitsClient) BeginPost(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ManagerCommit, options *ManagerCommitsClientBeginPostOptions) (*runtime.Poller[ManagerCommitsClientPostResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.post(ctx, resourceGroupName, networkManagerName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagerCommitsClientPostResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagerCommitsClientPostResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Post - Post a Network Manager Commit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ManagerCommitsClient) post(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ManagerCommit, options *ManagerCommitsClientBeginPostOptions) (*http.Response, error) { + var err error + const operationName = "ManagerCommitsClient.BeginPost" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postCreateRequest(ctx, resourceGroupName, networkManagerName, 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 +} + +// postCreateRequest creates the Post request. +func (client *ManagerCommitsClient) postCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ManagerCommit, options *ManagerCommitsClientBeginPostOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/commit" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-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/network/armnetwork/v4/managerdeploymentstatus_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managerdeploymentstatus_client.go new file mode 100644 index 000000000..d4d5b8580 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managerdeploymentstatus_client.go @@ -0,0 +1,118 @@ +//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 armnetwork + +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" +) + +// ManagerDeploymentStatusClient contains the methods for the NetworkManagerDeploymentStatus group. +// Don't use this type directly, use NewManagerDeploymentStatusClient() instead. +type ManagerDeploymentStatusClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagerDeploymentStatusClient creates a new instance of ManagerDeploymentStatusClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewManagerDeploymentStatusClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagerDeploymentStatusClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagerDeploymentStatusClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Post to List of Network Manager Deployment Status. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - parameters - Parameters supplied to specify which Managed Network deployment status is. +// - options - ManagerDeploymentStatusClientListOptions contains the optional parameters for the ManagerDeploymentStatusClient.List +// method. +func (client *ManagerDeploymentStatusClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ManagerDeploymentStatusParameter, options *ManagerDeploymentStatusClientListOptions) (ManagerDeploymentStatusClientListResponse, error) { + var err error + const operationName = "ManagerDeploymentStatusClient.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, networkManagerName, parameters, options) + if err != nil { + return ManagerDeploymentStatusClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagerDeploymentStatusClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagerDeploymentStatusClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *ManagerDeploymentStatusClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, parameters ManagerDeploymentStatusParameter, options *ManagerDeploymentStatusClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/listDeploymentStatus" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + 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"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ManagerDeploymentStatusClient) listHandleResponse(resp *http.Response) (ManagerDeploymentStatusClientListResponse, error) { + result := ManagerDeploymentStatusClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerDeploymentStatusListResult); err != nil { + return ManagerDeploymentStatusClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managers_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managers_client.go new file mode 100644 index 000000000..4bb745c86 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/managers_client.go @@ -0,0 +1,451 @@ +//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 armnetwork + +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" +) + +// ManagersClient contains the methods for the NetworkManagers group. +// Don't use this type directly, use NewManagersClient() instead. +type ManagersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagersClient creates a new instance of ManagersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewManagersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates a Network Manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - parameters - Parameters supplied to specify which network manager is. +// - options - ManagersClientCreateOrUpdateOptions contains the optional parameters for the ManagersClient.CreateOrUpdate method. +func (client *ManagersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, parameters Manager, options *ManagersClientCreateOrUpdateOptions) (ManagersClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ManagersClient.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, networkManagerName, parameters, options) + if err != nil { + return ManagersClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagersClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ManagersClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ManagersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, parameters Manager, options *ManagersClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-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 *ManagersClient) createOrUpdateHandleResponse(resp *http.Response) (ManagersClientCreateOrUpdateResponse, error) { + result := ManagersClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Manager); err != nil { + return ManagersClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes a network manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - options - ManagersClientBeginDeleteOptions contains the optional parameters for the ManagersClient.BeginDelete method. +func (client *ManagersClient) BeginDelete(ctx context.Context, resourceGroupName string, networkManagerName string, options *ManagersClientBeginDeleteOptions) (*runtime.Poller[ManagersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkManagerName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagersClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a network manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ManagersClient) deleteOperation(ctx context.Context, resourceGroupName string, networkManagerName string, options *ManagersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ManagersClient.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, networkManagerName, 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 *ManagersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, options *ManagersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Network Manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - options - ManagersClientGetOptions contains the optional parameters for the ManagersClient.Get method. +func (client *ManagersClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, options *ManagersClientGetOptions) (ManagersClientGetResponse, error) { + var err error + const operationName = "ManagersClient.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, networkManagerName, options) + if err != nil { + return ManagersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ManagersClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, options *ManagersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagersClient) getHandleResponse(resp *http.Response) (ManagersClientGetResponse, error) { + result := ManagersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Manager); err != nil { + return ManagersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List network managers in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ManagersClientListOptions contains the optional parameters for the ManagersClient.NewListPager method. +func (client *ManagersClient) NewListPager(resourceGroupName string, options *ManagersClientListOptions) *runtime.Pager[ManagersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagersClientListResponse]{ + More: func(page ManagersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagersClientListResponse) (ManagersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagersClient.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, options) + }, nil) + if err != nil { + return ManagersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ManagersClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *ManagersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers" + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ManagersClient) listHandleResponse(resp *http.Response) (ManagersClientListResponse, error) { + result := ManagersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerListResult); err != nil { + return ManagersClientListResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List all network managers in a subscription. +// +// Generated from API version 2023-05-01 +// - options - ManagersClientListBySubscriptionOptions contains the optional parameters for the ManagersClient.NewListBySubscriptionPager +// method. +func (client *ManagersClient) NewListBySubscriptionPager(options *ManagersClientListBySubscriptionOptions) *runtime.Pager[ManagersClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagersClientListBySubscriptionResponse]{ + More: func(page ManagersClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagersClientListBySubscriptionResponse) (ManagersClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagersClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ManagersClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ManagersClient) listBySubscriptionCreateRequest(ctx context.Context, options *ManagersClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagers" + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ManagersClient) listBySubscriptionHandleResponse(resp *http.Response) (ManagersClientListBySubscriptionResponse, error) { + result := ManagersClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerListResult); err != nil { + return ManagersClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Patch - Patch NetworkManager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - parameters - Parameters supplied to specify which network manager is. +// - options - ManagersClientPatchOptions contains the optional parameters for the ManagersClient.Patch method. +func (client *ManagersClient) Patch(ctx context.Context, resourceGroupName string, networkManagerName string, parameters PatchObject, options *ManagersClientPatchOptions) (ManagersClientPatchResponse, error) { + var err error + const operationName = "ManagersClient.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, networkManagerName, parameters, options) + if err != nil { + return ManagersClientPatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagersClientPatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagersClientPatchResponse{}, err + } + resp, err := client.patchHandleResponse(httpResp) + return resp, err +} + +// patchCreateRequest creates the Patch request. +func (client *ManagersClient) patchCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, parameters PatchObject, options *ManagersClientPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-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 +} + +// patchHandleResponse handles the Patch response. +func (client *ManagersClient) patchHandleResponse(resp *http.Response) (ManagersClientPatchResponse, error) { + result := ManagersClientPatchResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Manager); err != nil { + return ManagersClientPatchResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/models.go new file mode 100644 index 000000000..da6f49537 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/models.go @@ -0,0 +1,13941 @@ +//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 armnetwork + +import "time" + +// AADAuthenticationParameters - AAD Vpn authentication type related parameters. +type AADAuthenticationParameters struct { + // AAD Vpn authentication parameter AAD audience. + AADAudience *string + + // AAD Vpn authentication parameter AAD issuer. + AADIssuer *string + + // AAD Vpn authentication parameter AAD tenant. + AADTenant *string +} + +// Action to be taken on a route matching a RouteMap criterion. +type Action struct { + // List of parameters relevant to the action.For instance if type is drop then parameters has list of prefixes to be dropped.If + // type is add, parameters would have list of ASN numbers to be added + Parameters []*Parameter + + // Type of action to be taken. Supported types are 'Remove', 'Add', 'Replace', and 'Drop.' + Type *RouteMapActionType +} + +// ActiveBaseSecurityAdminRule - Network base admin rule. +type ActiveBaseSecurityAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *EffectiveAdminRuleKind + + // Deployment time string. + CommitTime *time.Time + + // A description of the security admin configuration. + ConfigurationDescription *string + + // Resource ID. + ID *string + + // Deployment region. + Region *string + + // Groups for rule collection + RuleCollectionAppliesToGroups []*ManagerSecurityGroupItem + + // A description of the rule collection. + RuleCollectionDescription *string + + // Effective configuration groups. + RuleGroups []*ConfigurationGroup +} + +// GetActiveBaseSecurityAdminRule implements the ActiveBaseSecurityAdminRuleClassification interface for type ActiveBaseSecurityAdminRule. +func (a *ActiveBaseSecurityAdminRule) GetActiveBaseSecurityAdminRule() *ActiveBaseSecurityAdminRule { + return a +} + +// ActiveConfigurationParameter - Effective Virtual Networks Parameter. +type ActiveConfigurationParameter struct { + // List of regions. + Regions []*string + + // When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current + // request) to retrieve the next page of data. + SkipToken *string +} + +// ActiveConnectivityConfiguration - Active connectivity configuration. +type ActiveConnectivityConfiguration struct { + // Deployment time string. + CommitTime *time.Time + + // Effective configuration groups. + ConfigurationGroups []*ConfigurationGroup + + // Connectivity configuration ID. + ID *string + + // Properties of a network manager connectivity configuration + Properties *ConnectivityConfigurationProperties + + // Deployment region. + Region *string +} + +// ActiveConnectivityConfigurationsListResult - Result of the request to list active connectivity configurations. It contains +// a list of active connectivity configurations and a skiptoken to get the next set of results. +type ActiveConnectivityConfigurationsListResult struct { + // When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current + // request) to retrieve the next page of data. + SkipToken *string + + // Gets a page of active connectivity configurations. + Value []*ActiveConnectivityConfiguration +} + +// ActiveDefaultSecurityAdminRule - Network default admin rule. +type ActiveDefaultSecurityAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *EffectiveAdminRuleKind + + // Deployment time string. + CommitTime *time.Time + + // A description of the security admin configuration. + ConfigurationDescription *string + + // Resource ID. + ID *string + + // Indicates the properties of the default security admin rule + Properties *DefaultAdminPropertiesFormat + + // Deployment region. + Region *string + + // Groups for rule collection + RuleCollectionAppliesToGroups []*ManagerSecurityGroupItem + + // A description of the rule collection. + RuleCollectionDescription *string + + // Effective configuration groups. + RuleGroups []*ConfigurationGroup +} + +// GetActiveBaseSecurityAdminRule implements the ActiveBaseSecurityAdminRuleClassification interface for type ActiveDefaultSecurityAdminRule. +func (a *ActiveDefaultSecurityAdminRule) GetActiveBaseSecurityAdminRule() *ActiveBaseSecurityAdminRule { + return &ActiveBaseSecurityAdminRule{ + CommitTime: a.CommitTime, + ConfigurationDescription: a.ConfigurationDescription, + ID: a.ID, + Kind: a.Kind, + Region: a.Region, + RuleCollectionAppliesToGroups: a.RuleCollectionAppliesToGroups, + RuleCollectionDescription: a.RuleCollectionDescription, + RuleGroups: a.RuleGroups, + } +} + +// ActiveSecurityAdminRule - Network admin rule. +type ActiveSecurityAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *EffectiveAdminRuleKind + + // Deployment time string. + CommitTime *time.Time + + // A description of the security admin configuration. + ConfigurationDescription *string + + // Resource ID. + ID *string + + // Indicates the properties of the security admin rule + Properties *AdminPropertiesFormat + + // Deployment region. + Region *string + + // Groups for rule collection + RuleCollectionAppliesToGroups []*ManagerSecurityGroupItem + + // A description of the rule collection. + RuleCollectionDescription *string + + // Effective configuration groups. + RuleGroups []*ConfigurationGroup +} + +// GetActiveBaseSecurityAdminRule implements the ActiveBaseSecurityAdminRuleClassification interface for type ActiveSecurityAdminRule. +func (a *ActiveSecurityAdminRule) GetActiveBaseSecurityAdminRule() *ActiveBaseSecurityAdminRule { + return &ActiveBaseSecurityAdminRule{ + CommitTime: a.CommitTime, + ConfigurationDescription: a.ConfigurationDescription, + ID: a.ID, + Kind: a.Kind, + Region: a.Region, + RuleCollectionAppliesToGroups: a.RuleCollectionAppliesToGroups, + RuleCollectionDescription: a.RuleCollectionDescription, + RuleGroups: a.RuleGroups, + } +} + +// ActiveSecurityAdminRulesListResult - Result of the request to list active security admin rules. It contains a list of active +// security admin rules and a skiptoken to get the next set of results. +type ActiveSecurityAdminRulesListResult struct { + // When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current + // request) to retrieve the next page of data. + SkipToken *string + + // Gets a page of active security admin rules. + Value []ActiveBaseSecurityAdminRuleClassification +} + +// AddressPrefixItem - Address prefix item. +type AddressPrefixItem struct { + // Address prefix. + AddressPrefix *string + + // Address prefix type. + AddressPrefixType *AddressPrefixType +} + +// AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual network. +type AddressSpace struct { + // A list of address blocks reserved for this virtual network in CIDR notation. + AddressPrefixes []*string +} + +// AdminPropertiesFormat - Security admin rule resource. +type AdminPropertiesFormat struct { + // REQUIRED; Indicates the access allowed for this particular rule + Access *SecurityConfigurationRuleAccess + + // REQUIRED; Indicates if the traffic matched against the rule in inbound or outbound. + Direction *SecurityConfigurationRuleDirection + + // REQUIRED; The priority of the rule. The value can be between 1 and 4096. The priority number must be unique for each rule + // in the collection. The lower the priority number, the higher the priority of the rule. + Priority *int32 + + // REQUIRED; Network protocol this rule applies to. + Protocol *SecurityConfigurationRuleProtocol + + // A description for this rule. Restricted to 140 chars. + Description *string + + // The destination port ranges. + DestinationPortRanges []*string + + // The destination address prefixes. CIDR or destination IP ranges. + Destinations []*AddressPrefixItem + + // The source port ranges. + SourcePortRanges []*string + + // The CIDR or source IP ranges. + Sources []*AddressPrefixItem + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Unique identifier for this resource. + ResourceGUID *string +} + +// AdminRule - Network admin rule. +type AdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *AdminRuleKind + + // Indicates the properties of the security admin rule + Properties *AdminPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// GetBaseAdminRule implements the BaseAdminRuleClassification interface for type AdminRule. +func (a *AdminRule) GetBaseAdminRule() *BaseAdminRule { + return &BaseAdminRule{ + Etag: a.Etag, + ID: a.ID, + Kind: a.Kind, + Name: a.Name, + SystemData: a.SystemData, + Type: a.Type, + } +} + +// AdminRuleCollection - Defines the admin rule collection. +type AdminRuleCollection struct { + // Indicates the properties for the network manager admin rule collection. + Properties *AdminRuleCollectionPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// AdminRuleCollectionListResult - Security admin configuration rule collection list result. +type AdminRuleCollectionListResult struct { + // Gets the URL to get the next set of results. + NextLink *string + + // A list of network manager security admin configuration rule collections + Value []*AdminRuleCollection +} + +// AdminRuleCollectionPropertiesFormat - Defines the admin rule collection properties. +type AdminRuleCollectionPropertiesFormat struct { + // REQUIRED; Groups for configuration + AppliesToGroups []*ManagerSecurityGroupItem + + // A description of the admin rule collection. + Description *string + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Unique identifier for this resource. + ResourceGUID *string +} + +// AdminRuleListResult - security configuration admin rule list result. +type AdminRuleListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of admin rules + Value []BaseAdminRuleClassification +} + +// ApplicationGateway - Application gateway resource. +type ApplicationGateway struct { + // Resource ID. + ID *string + + // The identity of the application gateway, if configured. + Identity *ManagedServiceIdentity + + // Resource location. + Location *string + + // Properties of the application gateway. + Properties *ApplicationGatewayPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // A list of availability zones denoting where the resource needs to come from. + Zones []*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ApplicationGatewayAuthenticationCertificate - Authentication certificates of an application gateway. +type ApplicationGatewayAuthenticationCertificate struct { + // Resource ID. + ID *string + + // Name of the authentication certificate that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway authentication certificate. + Properties *ApplicationGatewayAuthenticationCertificatePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayAuthenticationCertificatePropertiesFormat - Authentication certificates properties of an application +// gateway. +type ApplicationGatewayAuthenticationCertificatePropertiesFormat struct { + // Certificate public data. + Data *string + + // READ-ONLY; The provisioning state of the authentication certificate resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayAutoscaleConfiguration - Application Gateway autoscale configuration. +type ApplicationGatewayAutoscaleConfiguration struct { + // REQUIRED; Lower bound on number of Application Gateway capacity. + MinCapacity *int32 + + // Upper bound on number of Application Gateway capacity. + MaxCapacity *int32 +} + +// ApplicationGatewayAvailableSSLOptions - Response for ApplicationGatewayAvailableSslOptions API service call. +type ApplicationGatewayAvailableSSLOptions struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the application gateway available SSL options. + Properties *ApplicationGatewayAvailableSSLOptionsPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ApplicationGatewayAvailableSSLOptionsPropertiesFormat - Properties of ApplicationGatewayAvailableSslOptions. +type ApplicationGatewayAvailableSSLOptionsPropertiesFormat struct { + // List of available Ssl cipher suites. + AvailableCipherSuites []*ApplicationGatewaySSLCipherSuite + + // List of available Ssl protocols. + AvailableProtocols []*ApplicationGatewaySSLProtocol + + // Name of the Ssl predefined policy applied by default to application gateway. + DefaultPolicy *ApplicationGatewaySSLPolicyName + + // List of available Ssl predefined policy. + PredefinedPolicies []*SubResource +} + +// ApplicationGatewayAvailableSSLPredefinedPolicies - Response for ApplicationGatewayAvailableSslOptions API service call. +type ApplicationGatewayAvailableSSLPredefinedPolicies struct { + // URL to get the next set of results. + NextLink *string + + // List of available Ssl predefined policy. + Value []*ApplicationGatewaySSLPredefinedPolicy +} + +// ApplicationGatewayAvailableWafRuleSetsResult - Response for ApplicationGatewayAvailableWafRuleSets API service call. +type ApplicationGatewayAvailableWafRuleSetsResult struct { + // The list of application gateway rule sets. + Value []*ApplicationGatewayFirewallRuleSet +} + +// ApplicationGatewayBackendAddress - Backend address of an application gateway. +type ApplicationGatewayBackendAddress struct { + // Fully qualified domain name (FQDN). + Fqdn *string + + // IP address. + IPAddress *string +} + +// ApplicationGatewayBackendAddressPool - Backend Address Pool of an application gateway. +type ApplicationGatewayBackendAddressPool struct { + // Resource ID. + ID *string + + // Name of the backend address pool that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway backend address pool. + Properties *ApplicationGatewayBackendAddressPoolPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayBackendAddressPoolPropertiesFormat - Properties of Backend Address Pool of an application gateway. +type ApplicationGatewayBackendAddressPoolPropertiesFormat struct { + // Backend addresses. + BackendAddresses []*ApplicationGatewayBackendAddress + + // READ-ONLY; Collection of references to IPs defined in network interfaces. + BackendIPConfigurations []*InterfaceIPConfiguration + + // READ-ONLY; The provisioning state of the backend address pool resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayBackendHTTPSettings - Backend address pool settings of an application gateway. +type ApplicationGatewayBackendHTTPSettings struct { + // Resource ID. + ID *string + + // Name of the backend http settings that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway backend HTTP settings. + Properties *ApplicationGatewayBackendHTTPSettingsPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayBackendHTTPSettingsPropertiesFormat - Properties of Backend address pool settings of an application gateway. +type ApplicationGatewayBackendHTTPSettingsPropertiesFormat struct { + // Cookie name to use for the affinity cookie. + AffinityCookieName *string + + // Array of references to application gateway authentication certificates. + AuthenticationCertificates []*SubResource + + // Connection draining of the backend http settings resource. + ConnectionDraining *ApplicationGatewayConnectionDraining + + // Cookie based affinity. + CookieBasedAffinity *ApplicationGatewayCookieBasedAffinity + + // Host header to be sent to the backend servers. + HostName *string + + // Path which should be used as a prefix for all HTTP requests. Null means no path will be prefixed. Default value is null. + Path *string + + // Whether to pick host header should be picked from the host name of the backend server. Default value is false. + PickHostNameFromBackendAddress *bool + + // The destination port on the backend. + Port *int32 + + // Probe resource of an application gateway. + Probe *SubResource + + // Whether the probe is enabled. Default value is false. + ProbeEnabled *bool + + // The protocol used to communicate with the backend. + Protocol *ApplicationGatewayProtocol + + // Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. + // Acceptable values are from 1 second to 86400 seconds. + RequestTimeout *int32 + + // Array of references to application gateway trusted root certificates. + TrustedRootCertificates []*SubResource + + // READ-ONLY; The provisioning state of the backend HTTP settings resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayBackendHealth - Response for ApplicationGatewayBackendHealth API service call. +type ApplicationGatewayBackendHealth struct { + // A list of ApplicationGatewayBackendHealthPool resources. + BackendAddressPools []*ApplicationGatewayBackendHealthPool +} + +// ApplicationGatewayBackendHealthHTTPSettings - Application gateway BackendHealthHttp settings. +type ApplicationGatewayBackendHealthHTTPSettings struct { + // Reference to an ApplicationGatewayBackendHttpSettings resource. + BackendHTTPSettings *ApplicationGatewayBackendHTTPSettings + + // List of ApplicationGatewayBackendHealthServer resources. + Servers []*ApplicationGatewayBackendHealthServer +} + +// ApplicationGatewayBackendHealthOnDemand - Result of on demand test probe. +type ApplicationGatewayBackendHealthOnDemand struct { + // Reference to an ApplicationGatewayBackendAddressPool resource. + BackendAddressPool *ApplicationGatewayBackendAddressPool + + // Application gateway BackendHealthHttp settings. + BackendHealthHTTPSettings *ApplicationGatewayBackendHealthHTTPSettings +} + +// ApplicationGatewayBackendHealthPool - Application gateway BackendHealth pool. +type ApplicationGatewayBackendHealthPool struct { + // Reference to an ApplicationGatewayBackendAddressPool resource. + BackendAddressPool *ApplicationGatewayBackendAddressPool + + // List of ApplicationGatewayBackendHealthHttpSettings resources. + BackendHTTPSettingsCollection []*ApplicationGatewayBackendHealthHTTPSettings +} + +// ApplicationGatewayBackendHealthServer - Application gateway backendhealth http settings. +type ApplicationGatewayBackendHealthServer struct { + // IP address or FQDN of backend server. + Address *string + + // Health of backend server. + Health *ApplicationGatewayBackendHealthServerHealth + + // Health Probe Log. + HealthProbeLog *string + + // Reference to IP configuration of backend server. + IPConfiguration *InterfaceIPConfiguration +} + +// ApplicationGatewayBackendSettings - Backend address pool settings of an application gateway. +type ApplicationGatewayBackendSettings struct { + // Resource ID. + ID *string + + // Name of the backend settings that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway backend settings. + Properties *ApplicationGatewayBackendSettingsPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayBackendSettingsPropertiesFormat - Properties of Backend address pool settings of an application gateway. +type ApplicationGatewayBackendSettingsPropertiesFormat struct { + // Server name indication to be sent to the backend servers for Tls protocol. + HostName *string + + // Whether to pick server name indication from the host name of the backend server for Tls protocol. Default value is false. + PickHostNameFromBackendAddress *bool + + // The destination port on the backend. + Port *int32 + + // Probe resource of an application gateway. + Probe *SubResource + + // The protocol used to communicate with the backend. + Protocol *ApplicationGatewayProtocol + + // Connection timeout in seconds. Application Gateway will fail the request if response is not received within ConnectionTimeout. + // Acceptable values are from 1 second to 86400 seconds. + Timeout *int32 + + // Array of references to application gateway trusted root certificates. + TrustedRootCertificates []*SubResource + + // READ-ONLY; The provisioning state of the backend HTTP settings resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayClientAuthConfiguration - Application gateway client authentication configuration. +type ApplicationGatewayClientAuthConfiguration struct { + // Verify client certificate issuer name on the application gateway. + VerifyClientCertIssuerDN *bool + + // Verify client certificate revocation status. + VerifyClientRevocation *ApplicationGatewayClientRevocationOptions +} + +// ApplicationGatewayConnectionDraining - Connection draining allows open connections to a backend server to be active for +// a specified time after the backend server got removed from the configuration. +type ApplicationGatewayConnectionDraining struct { + // REQUIRED; The number of seconds connection draining is active. Acceptable values are from 1 second to 3600 seconds. + DrainTimeoutInSec *int32 + + // REQUIRED; Whether connection draining is enabled or not. + Enabled *bool +} + +// ApplicationGatewayCustomError - Custom error of an application gateway. +type ApplicationGatewayCustomError struct { + // Error page URL of the application gateway custom error. + CustomErrorPageURL *string + + // Status code of the application gateway custom error. + StatusCode *ApplicationGatewayCustomErrorStatusCode +} + +// ApplicationGatewayFirewallDisabledRuleGroup - Allows to disable rules within a rule group or an entire rule group. +type ApplicationGatewayFirewallDisabledRuleGroup struct { + // REQUIRED; The name of the rule group that will be disabled. + RuleGroupName *string + + // The list of rules that will be disabled. If null, all rules of the rule group will be disabled. + Rules []*int32 +} + +// ApplicationGatewayFirewallExclusion - Allow to exclude some variable satisfy the condition for the WAF check. +type ApplicationGatewayFirewallExclusion struct { + // REQUIRED; The variable to be excluded. + MatchVariable *string + + // REQUIRED; When matchVariable is a collection, operator used to specify which elements in the collection this exclusion + // applies to. + Selector *string + + // REQUIRED; When matchVariable is a collection, operate on the selector to specify which elements in the collection this + // exclusion applies to. + SelectorMatchOperator *string +} + +// ApplicationGatewayFirewallManifestRuleSet - Properties of the web application firewall rule set. +type ApplicationGatewayFirewallManifestRuleSet struct { + // REQUIRED; The rule groups of the web application firewall rule set. + RuleGroups []*ApplicationGatewayFirewallRuleGroup + + // REQUIRED; The type of the web application firewall rule set. + RuleSetType *string + + // REQUIRED; The version of the web application firewall rule set type. + RuleSetVersion *string + + // The rule set status + Status *ApplicationGatewayRuleSetStatusOptions + + // Tier of an application gateway that support the rule set. + Tiers []*ApplicationGatewayTierTypes +} + +// ApplicationGatewayFirewallRule - A web application firewall rule. +type ApplicationGatewayFirewallRule struct { + // REQUIRED; The identifier of the web application firewall rule. + RuleID *int32 + + // The string representation of the web application firewall rule action. + Action *ApplicationGatewayWafRuleActionTypes + + // The description of the web application firewall rule. + Description *string + + // The string representation of the web application firewall rule identifier. + RuleIDString *string + + // The string representation of the web application firewall rule state. + State *ApplicationGatewayWafRuleStateTypes +} + +// ApplicationGatewayFirewallRuleGroup - A web application firewall rule group. +type ApplicationGatewayFirewallRuleGroup struct { + // REQUIRED; The name of the web application firewall rule group. + RuleGroupName *string + + // REQUIRED; The rules of the web application firewall rule group. + Rules []*ApplicationGatewayFirewallRule + + // The description of the web application firewall rule group. + Description *string +} + +// ApplicationGatewayFirewallRuleSet - A web application firewall rule set. +type ApplicationGatewayFirewallRuleSet struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the application gateway firewall rule set. + Properties *ApplicationGatewayFirewallRuleSetPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ApplicationGatewayFirewallRuleSetPropertiesFormat - Properties of the web application firewall rule set. +type ApplicationGatewayFirewallRuleSetPropertiesFormat struct { + // REQUIRED; The rule groups of the web application firewall rule set. + RuleGroups []*ApplicationGatewayFirewallRuleGroup + + // REQUIRED; The type of the web application firewall rule set. + RuleSetType *string + + // REQUIRED; The version of the web application firewall rule set type. + RuleSetVersion *string + + // Tier of an application gateway that support the rule set. + Tiers []*ApplicationGatewayTierTypes + + // READ-ONLY; The provisioning state of the web application firewall rule set. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayFrontendIPConfiguration - Frontend IP configuration of an application gateway. +type ApplicationGatewayFrontendIPConfiguration struct { + // Resource ID. + ID *string + + // Name of the frontend IP configuration that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway frontend IP configuration. + Properties *ApplicationGatewayFrontendIPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayFrontendIPConfigurationPropertiesFormat - Properties of Frontend IP configuration of an application gateway. +type ApplicationGatewayFrontendIPConfigurationPropertiesFormat struct { + // PrivateIPAddress of the network interface IP Configuration. + PrivateIPAddress *string + + // The private IP address allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // Reference to the application gateway private link configuration. + PrivateLinkConfiguration *SubResource + + // Reference to the PublicIP resource. + PublicIPAddress *SubResource + + // Reference to the subnet resource. + Subnet *SubResource + + // READ-ONLY; The provisioning state of the frontend IP configuration resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayFrontendPort - Frontend port of an application gateway. +type ApplicationGatewayFrontendPort struct { + // Resource ID. + ID *string + + // Name of the frontend port that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway frontend port. + Properties *ApplicationGatewayFrontendPortPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayFrontendPortPropertiesFormat - Properties of Frontend port of an application gateway. +type ApplicationGatewayFrontendPortPropertiesFormat struct { + // Frontend port. + Port *int32 + + // READ-ONLY; The provisioning state of the frontend port resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayGlobalConfiguration - Application Gateway global configuration. +type ApplicationGatewayGlobalConfiguration struct { + // Enable request buffering. + EnableRequestBuffering *bool + + // Enable response buffering. + EnableResponseBuffering *bool +} + +// ApplicationGatewayHTTPListener - Http listener of an application gateway. +type ApplicationGatewayHTTPListener struct { + // Resource ID. + ID *string + + // Name of the HTTP listener that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway HTTP listener. + Properties *ApplicationGatewayHTTPListenerPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayHTTPListenerPropertiesFormat - Properties of HTTP listener of an application gateway. +type ApplicationGatewayHTTPListenerPropertiesFormat struct { + // Custom error configurations of the HTTP listener. + CustomErrorConfigurations []*ApplicationGatewayCustomError + + // Reference to the FirewallPolicy resource. + FirewallPolicy *SubResource + + // Frontend IP configuration resource of an application gateway. + FrontendIPConfiguration *SubResource + + // Frontend port resource of an application gateway. + FrontendPort *SubResource + + // Host name of HTTP listener. + HostName *string + + // List of Host names for HTTP Listener that allows special wildcard characters as well. + HostNames []*string + + // Protocol of the HTTP listener. + Protocol *ApplicationGatewayProtocol + + // Applicable only if protocol is https. Enables SNI for multi-hosting. + RequireServerNameIndication *bool + + // SSL certificate resource of an application gateway. + SSLCertificate *SubResource + + // SSL profile resource of the application gateway. + SSLProfile *SubResource + + // READ-ONLY; The provisioning state of the HTTP listener resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayHeaderConfiguration - Header configuration of the Actions set in Application Gateway. +type ApplicationGatewayHeaderConfiguration struct { + // Header name of the header configuration. + HeaderName *string + + // Header value of the header configuration. + HeaderValue *string +} + +// ApplicationGatewayIPConfiguration - IP configuration of an application gateway. Currently 1 public and 1 private IP configuration +// is allowed. +type ApplicationGatewayIPConfiguration struct { + // Resource ID. + ID *string + + // Name of the IP configuration that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway IP configuration. + Properties *ApplicationGatewayIPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayIPConfigurationPropertiesFormat - Properties of IP configuration of an application gateway. +type ApplicationGatewayIPConfigurationPropertiesFormat struct { + // Reference to the subnet resource. A subnet from where application gateway gets its private address. + Subnet *SubResource + + // READ-ONLY; The provisioning state of the application gateway IP configuration resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayListResult - Response for ListApplicationGateways API service call. +type ApplicationGatewayListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of an application gateways in a resource group. + Value []*ApplicationGateway +} + +// ApplicationGatewayListener - Listener of an application gateway. +type ApplicationGatewayListener struct { + // Resource ID. + ID *string + + // Name of the listener that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway listener. + Properties *ApplicationGatewayListenerPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayListenerPropertiesFormat - Properties of listener of an application gateway. +type ApplicationGatewayListenerPropertiesFormat struct { + // Frontend IP configuration resource of an application gateway. + FrontendIPConfiguration *SubResource + + // Frontend port resource of an application gateway. + FrontendPort *SubResource + + // Protocol of the listener. + Protocol *ApplicationGatewayProtocol + + // SSL certificate resource of an application gateway. + SSLCertificate *SubResource + + // SSL profile resource of the application gateway. + SSLProfile *SubResource + + // READ-ONLY; The provisioning state of the listener resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayLoadDistributionPolicy - Load Distribution Policy of an application gateway. +type ApplicationGatewayLoadDistributionPolicy struct { + // Resource ID. + ID *string + + // Name of the load distribution policy that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway load distribution policy. + Properties *ApplicationGatewayLoadDistributionPolicyPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayLoadDistributionPolicyPropertiesFormat - Properties of Load Distribution Policy of an application gateway. +type ApplicationGatewayLoadDistributionPolicyPropertiesFormat struct { + // Load Distribution Targets resource of an application gateway. + LoadDistributionAlgorithm *ApplicationGatewayLoadDistributionAlgorithm + + // Load Distribution Targets resource of an application gateway. + LoadDistributionTargets []*ApplicationGatewayLoadDistributionTarget + + // READ-ONLY; The provisioning state of the Load Distribution Policy resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayLoadDistributionTarget - Load Distribution Target of an application gateway. +type ApplicationGatewayLoadDistributionTarget struct { + // Resource ID. + ID *string + + // Name of the load distribution policy that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway load distribution target. + Properties *ApplicationGatewayLoadDistributionTargetPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +type ApplicationGatewayLoadDistributionTargetPropertiesFormat struct { + // Backend address pool resource of the application gateway. + BackendAddressPool *SubResource + + // Weight per server. Range between 1 and 100. + WeightPerServer *int32 +} + +// ApplicationGatewayOnDemandProbe - Details of on demand test probe request. +type ApplicationGatewayOnDemandProbe struct { + // Reference to backend pool of application gateway to which probe request will be sent. + BackendAddressPool *SubResource + + // Reference to backend http setting of application gateway to be used for test probe. + BackendHTTPSettings *SubResource + + // Host name to send the probe to. + Host *string + + // Criterion for classifying a healthy probe response. + Match *ApplicationGatewayProbeHealthResponseMatch + + // Relative path of probe. Valid path starts from '/'. Probe is sent to ://:. + Path *string + + // Whether the host header should be picked from the backend http settings. Default value is false. + PickHostNameFromBackendHTTPSettings *bool + + // The protocol used for the probe. + Protocol *ApplicationGatewayProtocol + + // The probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable + // values are from 1 second to 86400 seconds. + Timeout *int32 +} + +// ApplicationGatewayPathRule - Path rule of URL path map of an application gateway. +type ApplicationGatewayPathRule struct { + // Resource ID. + ID *string + + // Name of the path rule that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway path rule. + Properties *ApplicationGatewayPathRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayPathRulePropertiesFormat - Properties of path rule of an application gateway. +type ApplicationGatewayPathRulePropertiesFormat struct { + // Backend address pool resource of URL path map path rule. + BackendAddressPool *SubResource + + // Backend http settings resource of URL path map path rule. + BackendHTTPSettings *SubResource + + // Reference to the FirewallPolicy resource. + FirewallPolicy *SubResource + + // Load Distribution Policy resource of URL path map path rule. + LoadDistributionPolicy *SubResource + + // Path rules of URL path map. + Paths []*string + + // Redirect configuration resource of URL path map path rule. + RedirectConfiguration *SubResource + + // Rewrite rule set resource of URL path map path rule. + RewriteRuleSet *SubResource + + // READ-ONLY; The provisioning state of the path rule resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayPrivateEndpointConnection - Private Endpoint connection on an application gateway. +type ApplicationGatewayPrivateEndpointConnection struct { + // Resource ID. + ID *string + + // Name of the private endpoint connection on an application gateway. + Name *string + + // Properties of the application gateway private endpoint connection. + Properties *ApplicationGatewayPrivateEndpointConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayPrivateEndpointConnectionListResult - Response for ListApplicationGatewayPrivateEndpointConnection API +// service call. Gets all private endpoint connections for an application gateway. +type ApplicationGatewayPrivateEndpointConnectionListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of private endpoint connections on an application gateway. + Value []*ApplicationGatewayPrivateEndpointConnection +} + +// ApplicationGatewayPrivateEndpointConnectionProperties - Properties of Private Link Resource of an application gateway. +type ApplicationGatewayPrivateEndpointConnectionProperties struct { + // A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // READ-ONLY; The consumer link id. + LinkIdentifier *string + + // READ-ONLY; The resource of private end point. + PrivateEndpoint *PrivateEndpoint + + // READ-ONLY; The provisioning state of the application gateway private endpoint connection resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayPrivateLinkConfiguration - Private Link Configuration on an application gateway. +type ApplicationGatewayPrivateLinkConfiguration struct { + // Resource ID. + ID *string + + // Name of the private link configuration that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway private link configuration. + Properties *ApplicationGatewayPrivateLinkConfigurationProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayPrivateLinkConfigurationProperties - Properties of private link configuration on an application gateway. +type ApplicationGatewayPrivateLinkConfigurationProperties struct { + // An array of application gateway private link ip configurations. + IPConfigurations []*ApplicationGatewayPrivateLinkIPConfiguration + + // READ-ONLY; The provisioning state of the application gateway private link configuration. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayPrivateLinkIPConfiguration - The application gateway private link ip configuration. +type ApplicationGatewayPrivateLinkIPConfiguration struct { + // Resource ID. + ID *string + + // The name of application gateway private link ip configuration. + Name *string + + // Properties of an application gateway private link ip configuration. + Properties *ApplicationGatewayPrivateLinkIPConfigurationProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The resource type. + Type *string +} + +// ApplicationGatewayPrivateLinkIPConfigurationProperties - Properties of an application gateway private link IP configuration. +type ApplicationGatewayPrivateLinkIPConfigurationProperties struct { + // Whether the ip configuration is primary or not. + Primary *bool + + // The private IP address of the IP configuration. + PrivateIPAddress *string + + // The private IP address allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // Reference to the subnet resource. + Subnet *SubResource + + // READ-ONLY; The provisioning state of the application gateway private link IP configuration. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayPrivateLinkResource - PrivateLink Resource of an application gateway. +type ApplicationGatewayPrivateLinkResource struct { + // Resource ID. + ID *string + + // Name of the private link resource that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway private link resource. + Properties *ApplicationGatewayPrivateLinkResourceProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayPrivateLinkResourceListResult - Response for ListApplicationGatewayPrivateLinkResources API service call. +// Gets all private link resources for an application gateway. +type ApplicationGatewayPrivateLinkResourceListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of private link resources of an application gateway. + Value []*ApplicationGatewayPrivateLinkResource +} + +// ApplicationGatewayPrivateLinkResourceProperties - Properties of a private link resource. +type ApplicationGatewayPrivateLinkResourceProperties 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 +} + +// ApplicationGatewayProbe - Probe of the application gateway. +type ApplicationGatewayProbe struct { + // Resource ID. + ID *string + + // Name of the probe that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway probe. + Properties *ApplicationGatewayProbePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayProbeHealthResponseMatch - Application gateway probe health response match. +type ApplicationGatewayProbeHealthResponseMatch struct { + // Body that must be contained in the health response. Default value is empty. + Body *string + + // Allowed ranges of healthy status codes. Default range of healthy status codes is 200-399. + StatusCodes []*string +} + +// ApplicationGatewayProbePropertiesFormat - Properties of probe of an application gateway. +type ApplicationGatewayProbePropertiesFormat struct { + // Host name to send the probe to. + Host *string + + // The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 + // second to 86400 seconds. + Interval *int32 + + // Criterion for classifying a healthy probe response. + Match *ApplicationGatewayProbeHealthResponseMatch + + // Minimum number of servers that are always marked healthy. Default value is 0. + MinServers *int32 + + // Relative path of probe. Valid path starts from '/'. Probe is sent to ://:. + Path *string + + // Whether the host header should be picked from the backend http settings. Default value is false. + PickHostNameFromBackendHTTPSettings *bool + + // Whether the server name indication should be picked from the backend settings for Tls protocol. Default value is false. + PickHostNameFromBackendSettings *bool + + // Custom port which will be used for probing the backend servers. The valid value ranges from 1 to 65535. In case not set, + // port from http settings will be used. This property is valid for Basic, + // Standardv2 and WAFv2 only. + Port *int32 + + // The protocol used for the probe. + Protocol *ApplicationGatewayProtocol + + // The probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable + // values are from 1 second to 86400 seconds. + Timeout *int32 + + // The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. + // Acceptable values are from 1 second to 20. + UnhealthyThreshold *int32 + + // READ-ONLY; The provisioning state of the probe resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayPropertiesFormat - Properties of the application gateway. +type ApplicationGatewayPropertiesFormat struct { + // Authentication certificates of the application gateway resource. For default limits, see Application Gateway limits + // [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + AuthenticationCertificates []*ApplicationGatewayAuthenticationCertificate + + // Autoscale Configuration. + AutoscaleConfiguration *ApplicationGatewayAutoscaleConfiguration + + // Backend address pool of the application gateway resource. For default limits, see Application Gateway limits + // [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + BackendAddressPools []*ApplicationGatewayBackendAddressPool + + // Backend http settings of the application gateway resource. For default limits, see Application Gateway limits + // [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + BackendHTTPSettingsCollection []*ApplicationGatewayBackendHTTPSettings + + // Backend settings of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits] + // . + BackendSettingsCollection []*ApplicationGatewayBackendSettings + + // Custom error configurations of the application gateway resource. + CustomErrorConfigurations []*ApplicationGatewayCustomError + + // Whether FIPS is enabled on the application gateway resource. + EnableFips *bool + + // Whether HTTP2 is enabled on the application gateway resource. + EnableHTTP2 *bool + + // Reference to the FirewallPolicy resource. + FirewallPolicy *SubResource + + // If true, associates a firewall policy with an application gateway regardless whether the policy differs from the WAF Config. + ForceFirewallPolicyAssociation *bool + + // Frontend IP addresses of the application gateway resource. For default limits, see Application Gateway limits + // [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + FrontendIPConfigurations []*ApplicationGatewayFrontendIPConfiguration + + // Frontend ports of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + FrontendPorts []*ApplicationGatewayFrontendPort + + // Subnets of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + GatewayIPConfigurations []*ApplicationGatewayIPConfiguration + + // Global Configuration. + GlobalConfiguration *ApplicationGatewayGlobalConfiguration + + // Http listeners of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + HTTPListeners []*ApplicationGatewayHTTPListener + + // Listeners of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + Listeners []*ApplicationGatewayListener + + // Load distribution policies of the application gateway resource. + LoadDistributionPolicies []*ApplicationGatewayLoadDistributionPolicy + + // PrivateLink configurations on application gateway. + PrivateLinkConfigurations []*ApplicationGatewayPrivateLinkConfiguration + + // Probes of the application gateway resource. + Probes []*ApplicationGatewayProbe + + // Redirect configurations of the application gateway resource. For default limits, see Application Gateway limits + // [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + RedirectConfigurations []*ApplicationGatewayRedirectConfiguration + + // Request routing rules of the application gateway resource. + RequestRoutingRules []*ApplicationGatewayRequestRoutingRule + + // Rewrite rules for the application gateway resource. + RewriteRuleSets []*ApplicationGatewayRewriteRuleSet + + // Routing rules of the application gateway resource. + RoutingRules []*ApplicationGatewayRoutingRule + + // SKU of the application gateway resource. + SKU *ApplicationGatewaySKU + + // SSL certificates of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits] + // . + SSLCertificates []*ApplicationGatewaySSLCertificate + + // SSL policy of the application gateway resource. + SSLPolicy *ApplicationGatewaySSLPolicy + + // SSL profiles of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + SSLProfiles []*ApplicationGatewaySSLProfile + + // Trusted client certificates of the application gateway resource. For default limits, see Application Gateway limits + // [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + TrustedClientCertificates []*ApplicationGatewayTrustedClientCertificate + + // Trusted Root certificates of the application gateway resource. For default limits, see Application Gateway limits + // [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + TrustedRootCertificates []*ApplicationGatewayTrustedRootCertificate + + // URL path map of the application gateway resource. For default limits, see Application Gateway limits [https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits]. + URLPathMaps []*ApplicationGatewayURLPathMap + + // Web application firewall configuration. + WebApplicationFirewallConfiguration *ApplicationGatewayWebApplicationFirewallConfiguration + + // READ-ONLY; The default predefined SSL Policy applied on the application gateway resource. + DefaultPredefinedSSLPolicy *ApplicationGatewaySSLPolicyName + + // READ-ONLY; Operational state of the application gateway resource. + OperationalState *ApplicationGatewayOperationalState + + // READ-ONLY; Private Endpoint connections on application gateway. + PrivateEndpointConnections []*ApplicationGatewayPrivateEndpointConnection + + // READ-ONLY; The provisioning state of the application gateway resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the application gateway resource. + ResourceGUID *string +} + +// ApplicationGatewayRedirectConfiguration - Redirect configuration of an application gateway. +type ApplicationGatewayRedirectConfiguration struct { + // Resource ID. + ID *string + + // Name of the redirect configuration that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway redirect configuration. + Properties *ApplicationGatewayRedirectConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayRedirectConfigurationPropertiesFormat - Properties of redirect configuration of the application gateway. +type ApplicationGatewayRedirectConfigurationPropertiesFormat struct { + // Include path in the redirected url. + IncludePath *bool + + // Include query string in the redirected url. + IncludeQueryString *bool + + // Path rules specifying redirect configuration. + PathRules []*SubResource + + // HTTP redirection type. + RedirectType *ApplicationGatewayRedirectType + + // Request routing specifying redirect configuration. + RequestRoutingRules []*SubResource + + // Reference to a listener to redirect the request to. + TargetListener *SubResource + + // Url to redirect the request to. + TargetURL *string + + // Url path maps specifying default redirect configuration. + URLPathMaps []*SubResource +} + +// ApplicationGatewayRequestRoutingRule - Request routing rule of an application gateway. +type ApplicationGatewayRequestRoutingRule struct { + // Resource ID. + ID *string + + // Name of the request routing rule that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway request routing rule. + Properties *ApplicationGatewayRequestRoutingRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayRequestRoutingRulePropertiesFormat - Properties of request routing rule of the application gateway. +type ApplicationGatewayRequestRoutingRulePropertiesFormat struct { + // Backend address pool resource of the application gateway. + BackendAddressPool *SubResource + + // Backend http settings resource of the application gateway. + BackendHTTPSettings *SubResource + + // Http listener resource of the application gateway. + HTTPListener *SubResource + + // Load Distribution Policy resource of the application gateway. + LoadDistributionPolicy *SubResource + + // Priority of the request routing rule. + Priority *int32 + + // Redirect configuration resource of the application gateway. + RedirectConfiguration *SubResource + + // Rewrite Rule Set resource in Basic rule of the application gateway. + RewriteRuleSet *SubResource + + // Rule type. + RuleType *ApplicationGatewayRequestRoutingRuleType + + // URL path map resource of the application gateway. + URLPathMap *SubResource + + // READ-ONLY; The provisioning state of the request routing rule resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayRewriteRule - Rewrite rule of an application gateway. +type ApplicationGatewayRewriteRule struct { + // Set of actions to be done as part of the rewrite Rule. + ActionSet *ApplicationGatewayRewriteRuleActionSet + + // Conditions based on which the action set execution will be evaluated. + Conditions []*ApplicationGatewayRewriteRuleCondition + + // Name of the rewrite rule that is unique within an Application Gateway. + Name *string + + // Rule Sequence of the rewrite rule that determines the order of execution of a particular rule in a RewriteRuleSet. + RuleSequence *int32 +} + +// ApplicationGatewayRewriteRuleActionSet - Set of actions in the Rewrite Rule in Application Gateway. +type ApplicationGatewayRewriteRuleActionSet struct { + // Request Header Actions in the Action Set. + RequestHeaderConfigurations []*ApplicationGatewayHeaderConfiguration + + // Response Header Actions in the Action Set. + ResponseHeaderConfigurations []*ApplicationGatewayHeaderConfiguration + + // Url Configuration Action in the Action Set. + URLConfiguration *ApplicationGatewayURLConfiguration +} + +// ApplicationGatewayRewriteRuleCondition - Set of conditions in the Rewrite Rule in Application Gateway. +type ApplicationGatewayRewriteRuleCondition struct { + // Setting this parameter to truth value with force the pattern to do a case in-sensitive comparison. + IgnoreCase *bool + + // Setting this value as truth will force to check the negation of the condition given by the user. + Negate *bool + + // The pattern, either fixed string or regular expression, that evaluates the truthfulness of the condition. + Pattern *string + + // The condition parameter of the RewriteRuleCondition. + Variable *string +} + +// ApplicationGatewayRewriteRuleSet - Rewrite rule set of an application gateway. +type ApplicationGatewayRewriteRuleSet struct { + // Resource ID. + ID *string + + // Name of the rewrite rule set that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway rewrite rule set. + Properties *ApplicationGatewayRewriteRuleSetPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// ApplicationGatewayRewriteRuleSetPropertiesFormat - Properties of rewrite rule set of the application gateway. +type ApplicationGatewayRewriteRuleSetPropertiesFormat struct { + // Rewrite rules in the rewrite rule set. + RewriteRules []*ApplicationGatewayRewriteRule + + // READ-ONLY; The provisioning state of the rewrite rule set resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayRoutingRule - Routing rule of an application gateway. +type ApplicationGatewayRoutingRule struct { + // Resource ID. + ID *string + + // Name of the routing rule that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway routing rule. + Properties *ApplicationGatewayRoutingRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayRoutingRulePropertiesFormat - Properties of routing rule of the application gateway. +type ApplicationGatewayRoutingRulePropertiesFormat struct { + // REQUIRED; Priority of the routing rule. + Priority *int32 + + // Backend address pool resource of the application gateway. + BackendAddressPool *SubResource + + // Backend settings resource of the application gateway. + BackendSettings *SubResource + + // Listener resource of the application gateway. + Listener *SubResource + + // Rule type. + RuleType *ApplicationGatewayRequestRoutingRuleType + + // READ-ONLY; The provisioning state of the request routing rule resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewaySKU - SKU of an application gateway. +type ApplicationGatewaySKU struct { + // Capacity (instance count) of an application gateway. + Capacity *int32 + + // Name of an application gateway SKU. + Name *ApplicationGatewaySKUName + + // Tier of an application gateway. + Tier *ApplicationGatewayTier +} + +// ApplicationGatewaySSLCertificate - SSL certificates of an application gateway. +type ApplicationGatewaySSLCertificate struct { + // Resource ID. + ID *string + + // Name of the SSL certificate that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway SSL certificate. + Properties *ApplicationGatewaySSLCertificatePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewaySSLCertificatePropertiesFormat - Properties of SSL certificates of an application gateway. +type ApplicationGatewaySSLCertificatePropertiesFormat struct { + // Base-64 encoded pfx certificate. Only applicable in PUT Request. + Data *string + + // Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. + KeyVaultSecretID *string + + // Password for the pfx file specified in data. Only applicable in PUT request. + Password *string + + // READ-ONLY; The provisioning state of the SSL certificate resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Base-64 encoded Public cert data corresponding to pfx specified in data. Only applicable in GET request. + PublicCertData *string +} + +// ApplicationGatewaySSLPolicy - Application Gateway Ssl policy. +type ApplicationGatewaySSLPolicy struct { + // Ssl cipher suites to be enabled in the specified order to application gateway. + CipherSuites []*ApplicationGatewaySSLCipherSuite + + // Ssl protocols to be disabled on application gateway. + DisabledSSLProtocols []*ApplicationGatewaySSLProtocol + + // Minimum version of Ssl protocol to be supported on application gateway. + MinProtocolVersion *ApplicationGatewaySSLProtocol + + // Name of Ssl predefined policy. + PolicyName *ApplicationGatewaySSLPolicyName + + // Type of Ssl Policy. + PolicyType *ApplicationGatewaySSLPolicyType +} + +// ApplicationGatewaySSLPredefinedPolicy - An Ssl predefined policy. +type ApplicationGatewaySSLPredefinedPolicy struct { + // Resource ID. + ID *string + + // Name of the Ssl predefined policy. + Name *string + + // Properties of the application gateway SSL predefined policy. + Properties *ApplicationGatewaySSLPredefinedPolicyPropertiesFormat +} + +// ApplicationGatewaySSLPredefinedPolicyPropertiesFormat - Properties of ApplicationGatewaySslPredefinedPolicy. +type ApplicationGatewaySSLPredefinedPolicyPropertiesFormat struct { + // Ssl cipher suites to be enabled in the specified order for application gateway. + CipherSuites []*ApplicationGatewaySSLCipherSuite + + // Minimum version of Ssl protocol to be supported on application gateway. + MinProtocolVersion *ApplicationGatewaySSLProtocol +} + +// ApplicationGatewaySSLProfile - SSL profile of an application gateway. +type ApplicationGatewaySSLProfile struct { + // Resource ID. + ID *string + + // Name of the SSL profile that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway SSL profile. + Properties *ApplicationGatewaySSLProfilePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewaySSLProfilePropertiesFormat - Properties of SSL profile of an application gateway. +type ApplicationGatewaySSLProfilePropertiesFormat struct { + // Client authentication configuration of the application gateway resource. + ClientAuthConfiguration *ApplicationGatewayClientAuthConfiguration + + // SSL policy of the application gateway resource. + SSLPolicy *ApplicationGatewaySSLPolicy + + // Array of references to application gateway trusted client certificates. + TrustedClientCertificates []*SubResource + + // READ-ONLY; The provisioning state of the HTTP listener resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayTrustedClientCertificate - Trusted client certificates of an application gateway. +type ApplicationGatewayTrustedClientCertificate struct { + // Resource ID. + ID *string + + // Name of the trusted client certificate that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway trusted client certificate. + Properties *ApplicationGatewayTrustedClientCertificatePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayTrustedClientCertificatePropertiesFormat - Trusted client certificates properties of an application gateway. +type ApplicationGatewayTrustedClientCertificatePropertiesFormat struct { + // Certificate public data. + Data *string + + // READ-ONLY; Distinguished name of client certificate issuer. + ClientCertIssuerDN *string + + // READ-ONLY; The provisioning state of the trusted client certificate resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Validated certificate data. + ValidatedCertData *string +} + +// ApplicationGatewayTrustedRootCertificate - Trusted Root certificates of an application gateway. +type ApplicationGatewayTrustedRootCertificate struct { + // Resource ID. + ID *string + + // Name of the trusted root certificate that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway trusted root certificate. + Properties *ApplicationGatewayTrustedRootCertificatePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayTrustedRootCertificatePropertiesFormat - Trusted Root certificates properties of an application gateway. +type ApplicationGatewayTrustedRootCertificatePropertiesFormat struct { + // Certificate public data. + Data *string + + // Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. + KeyVaultSecretID *string + + // READ-ONLY; The provisioning state of the trusted root certificate resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayURLConfiguration - Url configuration of the Actions set in Application Gateway. +type ApplicationGatewayURLConfiguration struct { + // Url path which user has provided for url rewrite. Null means no path will be updated. Default value is null. + ModifiedPath *string + + // Query string which user has provided for url rewrite. Null means no query string will be updated. Default value is null. + ModifiedQueryString *string + + // If set as true, it will re-evaluate the url path map provided in path based request routing rules using modified path. + // Default value is false. + Reroute *bool +} + +// ApplicationGatewayURLPathMap - UrlPathMaps give a url path to the backend mapping information for PathBasedRouting. +type ApplicationGatewayURLPathMap struct { + // Resource ID. + ID *string + + // Name of the URL path map that is unique within an Application Gateway. + Name *string + + // Properties of the application gateway URL path map. + Properties *ApplicationGatewayURLPathMapPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ApplicationGatewayURLPathMapPropertiesFormat - Properties of UrlPathMap of the application gateway. +type ApplicationGatewayURLPathMapPropertiesFormat struct { + // Default backend address pool resource of URL path map. + DefaultBackendAddressPool *SubResource + + // Default backend http settings resource of URL path map. + DefaultBackendHTTPSettings *SubResource + + // Default Load Distribution Policy resource of URL path map. + DefaultLoadDistributionPolicy *SubResource + + // Default redirect configuration resource of URL path map. + DefaultRedirectConfiguration *SubResource + + // Default Rewrite rule set resource of URL path map. + DefaultRewriteRuleSet *SubResource + + // Path rule of URL path map resource. + PathRules []*ApplicationGatewayPathRule + + // READ-ONLY; The provisioning state of the URL path map resource. + ProvisioningState *ProvisioningState +} + +// ApplicationGatewayWafDynamicManifestPropertiesResult - Properties of ApplicationGatewayWafDynamicManifest. +type ApplicationGatewayWafDynamicManifestPropertiesResult struct { + // The available rulesets. + AvailableRuleSets []*ApplicationGatewayFirewallManifestRuleSet + + // The default ruleset. + DefaultRuleSet *DefaultRuleSetPropertyFormat +} + +// ApplicationGatewayWafDynamicManifestResult - Response for ApplicationGatewayWafDynamicManifest API service call. +type ApplicationGatewayWafDynamicManifestResult struct { + // Resource ID. + ID *string + + // Properties of the ApplicationGatewayWafDynamicManifest . + Properties *ApplicationGatewayWafDynamicManifestPropertiesResult + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ApplicationGatewayWafDynamicManifestResultList - Response for ApplicationGatewayWafDynamicManifests API service call. +type ApplicationGatewayWafDynamicManifestResultList struct { + // URL to get the next set of results. + NextLink *string + + // The list of application gateway waf manifest. + Value []*ApplicationGatewayWafDynamicManifestResult +} + +// ApplicationGatewayWebApplicationFirewallConfiguration - Application gateway web application firewall configuration. +type ApplicationGatewayWebApplicationFirewallConfiguration struct { + // REQUIRED; Whether the web application firewall is enabled or not. + Enabled *bool + + // REQUIRED; Web application firewall mode. + FirewallMode *ApplicationGatewayFirewallMode + + // REQUIRED; The type of the web application firewall rule set. Possible values are: 'OWASP'. + RuleSetType *string + + // REQUIRED; The version of the rule set type. + RuleSetVersion *string + + // The disabled rule groups. + DisabledRuleGroups []*ApplicationGatewayFirewallDisabledRuleGroup + + // The exclusion list. + Exclusions []*ApplicationGatewayFirewallExclusion + + // Maximum file upload size in Mb for WAF. + FileUploadLimitInMb *int32 + + // Maximum request body size for WAF. + MaxRequestBodySize *int32 + + // Maximum request body size in Kb for WAF. + MaxRequestBodySizeInKb *int32 + + // Whether allow WAF to check request Body. + RequestBodyCheck *bool +} + +// ApplicationRule - Rule of type application. +type ApplicationRule struct { + // REQUIRED; Rule Type. + RuleType *FirewallPolicyRuleType + + // Description of the rule. + Description *string + + // List of destination IP addresses or Service Tags. + DestinationAddresses []*string + + // List of FQDN Tags for this rule. + FqdnTags []*string + + // List of HTTP/S headers to insert. + HTTPHeadersToInsert []*FirewallPolicyHTTPHeaderToInsert + + // Name of the rule. + Name *string + + // Array of Application Protocols. + Protocols []*FirewallPolicyRuleApplicationProtocol + + // List of source IP addresses for this rule. + SourceAddresses []*string + + // List of source IpGroups for this rule. + SourceIPGroups []*string + + // List of FQDNs for this rule. + TargetFqdns []*string + + // List of Urls for this rule condition. + TargetUrls []*string + + // Terminate TLS connections for this rule. + TerminateTLS *bool + + // List of destination azure web categories. + WebCategories []*string +} + +// GetFirewallPolicyRule implements the FirewallPolicyRuleClassification interface for type ApplicationRule. +func (a *ApplicationRule) GetFirewallPolicyRule() *FirewallPolicyRule { + return &FirewallPolicyRule{ + Description: a.Description, + Name: a.Name, + RuleType: a.RuleType, + } +} + +// ApplicationSecurityGroup - An application security group in a resource group. +type ApplicationSecurityGroup struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the application security group. + Properties *ApplicationSecurityGroupPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ApplicationSecurityGroupListResult - A list of application security groups. +type ApplicationSecurityGroupListResult struct { + // A list of application security groups. + Value []*ApplicationSecurityGroup + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ApplicationSecurityGroupPropertiesFormat - Application security group properties. +type ApplicationSecurityGroupPropertiesFormat struct { + // READ-ONLY; The provisioning state of the application security group resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the application security group resource. It uniquely identifies a resource, even + // if the user changes its name or migrate the resource across subscriptions or resource + // groups. + ResourceGUID *string +} + +// AuthorizationListResult - Response for ListAuthorizations API service call retrieves all authorizations that belongs to +// an ExpressRouteCircuit. +type AuthorizationListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The authorizations in an ExpressRoute Circuit. + Value []*ExpressRouteCircuitAuthorization +} + +// AuthorizationPropertiesFormat - Properties of ExpressRouteCircuitAuthorization. +type AuthorizationPropertiesFormat struct { + // The authorization key. + AuthorizationKey *string + + // The authorization use status. + AuthorizationUseStatus *AuthorizationUseStatus + + // READ-ONLY; The provisioning state of the authorization resource. + ProvisioningState *ProvisioningState +} + +// AutoApprovedPrivateLinkService - The information of an AutoApprovedPrivateLinkService. +type AutoApprovedPrivateLinkService struct { + // The id of the private link service resource. + PrivateLinkService *string +} + +// AutoApprovedPrivateLinkServicesResult - An array of private link service id that can be linked to a private end point with +// auto approved. +type AutoApprovedPrivateLinkServicesResult struct { + // An array of auto approved private link service. + Value []*AutoApprovedPrivateLinkService + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// Availability of the metric. +type Availability struct { + // Duration of the availability blob. + BlobDuration *string + + // The retention of the availability. + Retention *string + + // The time grain of the availability. + TimeGrain *string +} + +// AvailableDelegation - The serviceName of an AvailableDelegation indicates a possible delegation for a subnet. +type AvailableDelegation struct { + // The actions permitted to the service upon delegation. + Actions []*string + + // A unique identifier of the AvailableDelegation resource. + ID *string + + // The name of the AvailableDelegation resource. + Name *string + + // The name of the service and resource. + ServiceName *string + + // Resource type. + Type *string +} + +// AvailableDelegationsResult - An array of available delegations. +type AvailableDelegationsResult struct { + // An array of available delegations. + Value []*AvailableDelegation + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// AvailablePrivateEndpointType - The information of an AvailablePrivateEndpointType. +type AvailablePrivateEndpointType struct { + // Display name of the resource. + DisplayName *string + + // A unique identifier of the AvailablePrivateEndpoint Type resource. + ID *string + + // The name of the service and resource. + Name *string + + // The name of the service and resource. + ResourceName *string + + // Resource type. + Type *string +} + +// AvailablePrivateEndpointTypesResult - An array of available PrivateEndpoint types. +type AvailablePrivateEndpointTypesResult struct { + // An array of available privateEndpoint type. + Value []*AvailablePrivateEndpointType + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// AvailableProvidersList - List of available countries with details. +type AvailableProvidersList struct { + // REQUIRED; List of available countries. + Countries []*AvailableProvidersListCountry +} + +// AvailableProvidersListCity - City or town details. +type AvailableProvidersListCity struct { + // The city or town name. + CityName *string + + // A list of Internet service providers. + Providers []*string +} + +// AvailableProvidersListCountry - Country details. +type AvailableProvidersListCountry struct { + // The country name. + CountryName *string + + // A list of Internet service providers. + Providers []*string + + // List of available states in the country. + States []*AvailableProvidersListState +} + +// AvailableProvidersListParameters - Constraints that determine the list of available Internet service providers. +type AvailableProvidersListParameters struct { + // A list of Azure regions. + AzureLocations []*string + + // The city or town for available providers list. + City *string + + // The country for available providers list. + Country *string + + // The state for available providers list. + State *string +} + +// AvailableProvidersListState - State details. +type AvailableProvidersListState struct { + // List of available cities or towns in the state. + Cities []*AvailableProvidersListCity + + // A list of Internet service providers. + Providers []*string + + // The state name. + StateName *string +} + +// AvailableServiceAlias - The available service alias. +type AvailableServiceAlias struct { + // The ID of the service alias. + ID *string + + // The name of the service alias. + Name *string + + // The resource name of the service alias. + ResourceName *string + + // The type of the resource. + Type *string +} + +// AvailableServiceAliasesResult - An array of available service aliases. +type AvailableServiceAliasesResult struct { + // An array of available service aliases. + Value []*AvailableServiceAlias + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// AzureAsyncOperationResult - The response body contains the status of the specified asynchronous operation, indicating whether +// it has succeeded, is in progress, or has failed. Note that this status is distinct from the HTTP +// status code returned for the Get Operation Status operation itself. If the asynchronous operation succeeded, the response +// body includes the HTTP status code for the successful request. If the +// asynchronous operation failed, the response body includes the HTTP status code for the failed request and error information +// regarding the failure. +type AzureAsyncOperationResult struct { + // Details of the error occurred during specified asynchronous operation. + Error *Error + + // Status of the Azure async operation. + Status *NetworkOperationStatus +} + +// AzureFirewall - Azure Firewall resource. +type AzureFirewall struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the azure firewall. + Properties *AzureFirewallPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // A list of availability zones denoting where the resource needs to come from. + Zones []*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// AzureFirewallApplicationRule - Properties of an application rule. +type AzureFirewallApplicationRule struct { + // Description of the rule. + Description *string + + // List of FQDN Tags for this rule. + FqdnTags []*string + + // Name of the application rule. + Name *string + + // Array of ApplicationRuleProtocols. + Protocols []*AzureFirewallApplicationRuleProtocol + + // List of source IP addresses for this rule. + SourceAddresses []*string + + // List of source IpGroups for this rule. + SourceIPGroups []*string + + // List of FQDNs for this rule. + TargetFqdns []*string +} + +// AzureFirewallApplicationRuleCollection - Application rule collection resource. +type AzureFirewallApplicationRuleCollection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the Azure firewall. This name can be used to access the resource. + Name *string + + // Properties of the azure firewall application rule collection. + Properties *AzureFirewallApplicationRuleCollectionPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// AzureFirewallApplicationRuleCollectionPropertiesFormat - Properties of the application rule collection. +type AzureFirewallApplicationRuleCollectionPropertiesFormat struct { + // The action type of a rule collection. + Action *AzureFirewallRCAction + + // Priority of the application rule collection resource. + Priority *int32 + + // Collection of rules used by a application rule collection. + Rules []*AzureFirewallApplicationRule + + // READ-ONLY; The provisioning state of the application rule collection resource. + ProvisioningState *ProvisioningState +} + +// AzureFirewallApplicationRuleProtocol - Properties of the application rule protocol. +type AzureFirewallApplicationRuleProtocol struct { + // Port number for the protocol, cannot be greater than 64000. This field is optional. + Port *int32 + + // Protocol type. + ProtocolType *AzureFirewallApplicationRuleProtocolType +} + +// AzureFirewallFqdnTag - Azure Firewall FQDN Tag Resource. +type AzureFirewallFqdnTag struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the azure firewall FQDN tag. + Properties *AzureFirewallFqdnTagPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// AzureFirewallFqdnTagListResult - Response for ListAzureFirewallFqdnTags API service call. +type AzureFirewallFqdnTagListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Azure Firewall FQDN Tags in a resource group. + Value []*AzureFirewallFqdnTag +} + +// AzureFirewallFqdnTagPropertiesFormat - Azure Firewall FQDN Tag Properties. +type AzureFirewallFqdnTagPropertiesFormat struct { + // READ-ONLY; The name of this FQDN Tag. + FqdnTagName *string + + // READ-ONLY; The provisioning state of the Azure firewall FQDN tag resource. + ProvisioningState *ProvisioningState +} + +// AzureFirewallIPConfiguration - IP configuration of an Azure Firewall. +type AzureFirewallIPConfiguration struct { + // Resource ID. + ID *string + + // Name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the azure firewall IP configuration. + Properties *AzureFirewallIPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// AzureFirewallIPConfigurationPropertiesFormat - Properties of IP configuration of an Azure Firewall. +type AzureFirewallIPConfigurationPropertiesFormat struct { + // Reference to the PublicIP resource. This field is a mandatory input if subnet is not null. + PublicIPAddress *SubResource + + // Reference to the subnet resource. This resource must be named 'AzureFirewallSubnet' or 'AzureFirewallManagementSubnet'. + Subnet *SubResource + + // READ-ONLY; The Firewall Internal Load Balancer IP to be used as the next hop in User Defined Routes. + PrivateIPAddress *string + + // READ-ONLY; The provisioning state of the Azure firewall IP configuration resource. + ProvisioningState *ProvisioningState +} + +// AzureFirewallIPGroups - IpGroups associated with azure firewall. +type AzureFirewallIPGroups struct { + // READ-ONLY; The iteration number. + ChangeNumber *string + + // READ-ONLY; Resource ID. + ID *string +} + +// AzureFirewallListResult - Response for ListAzureFirewalls API service call. +type AzureFirewallListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Azure Firewalls in a resource group. + Value []*AzureFirewall +} + +// AzureFirewallNatRCAction - AzureFirewall NAT Rule Collection Action. +type AzureFirewallNatRCAction struct { + // The type of action. + Type *AzureFirewallNatRCActionType +} + +// AzureFirewallNatRule - Properties of a NAT rule. +type AzureFirewallNatRule struct { + // Description of the rule. + Description *string + + // List of destination IP addresses for this rule. Supports IP ranges, prefixes, and service tags. + DestinationAddresses []*string + + // List of destination ports. + DestinationPorts []*string + + // Name of the NAT rule. + Name *string + + // Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule. + Protocols []*AzureFirewallNetworkRuleProtocol + + // List of source IP addresses for this rule. + SourceAddresses []*string + + // List of source IpGroups for this rule. + SourceIPGroups []*string + + // The translated address for this NAT rule. + TranslatedAddress *string + + // The translated FQDN for this NAT rule. + TranslatedFqdn *string + + // The translated port for this NAT rule. + TranslatedPort *string +} + +// AzureFirewallNatRuleCollection - NAT rule collection resource. +type AzureFirewallNatRuleCollection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the Azure firewall. This name can be used to access the resource. + Name *string + + // Properties of the azure firewall NAT rule collection. + Properties *AzureFirewallNatRuleCollectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// AzureFirewallNatRuleCollectionProperties - Properties of the NAT rule collection. +type AzureFirewallNatRuleCollectionProperties struct { + // The action type of a NAT rule collection. + Action *AzureFirewallNatRCAction + + // Priority of the NAT rule collection resource. + Priority *int32 + + // Collection of rules used by a NAT rule collection. + Rules []*AzureFirewallNatRule + + // READ-ONLY; The provisioning state of the NAT rule collection resource. + ProvisioningState *ProvisioningState +} + +// AzureFirewallNetworkRule - Properties of the network rule. +type AzureFirewallNetworkRule struct { + // Description of the rule. + Description *string + + // List of destination IP addresses. + DestinationAddresses []*string + + // List of destination FQDNs. + DestinationFqdns []*string + + // List of destination IpGroups for this rule. + DestinationIPGroups []*string + + // List of destination ports. + DestinationPorts []*string + + // Name of the network rule. + Name *string + + // Array of AzureFirewallNetworkRuleProtocols. + Protocols []*AzureFirewallNetworkRuleProtocol + + // List of source IP addresses for this rule. + SourceAddresses []*string + + // List of source IpGroups for this rule. + SourceIPGroups []*string +} + +// AzureFirewallNetworkRuleCollection - Network rule collection resource. +type AzureFirewallNetworkRuleCollection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the Azure firewall. This name can be used to access the resource. + Name *string + + // Properties of the azure firewall network rule collection. + Properties *AzureFirewallNetworkRuleCollectionPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// AzureFirewallNetworkRuleCollectionPropertiesFormat - Properties of the network rule collection. +type AzureFirewallNetworkRuleCollectionPropertiesFormat struct { + // The action type of a rule collection. + Action *AzureFirewallRCAction + + // Priority of the network rule collection resource. + Priority *int32 + + // Collection of rules used by a network rule collection. + Rules []*AzureFirewallNetworkRule + + // READ-ONLY; The provisioning state of the network rule collection resource. + ProvisioningState *ProvisioningState +} + +// AzureFirewallPacketCaptureFlags - Properties of the AzureFirewallRCAction. +type AzureFirewallPacketCaptureFlags struct { + // Flags to capture + Type *AzureFirewallPacketCaptureFlagsType +} + +// AzureFirewallPacketCaptureRule - Group of src/dest ips and ports to be captured. +type AzureFirewallPacketCaptureRule struct { + // List of ports to be captured. + DestinationPorts []*string + + // List of destination IP addresses/subnets to be captured. + Destinations []*string + + // List of source IP addresses/subnets to be captured. + Sources []*string +} + +// AzureFirewallPropertiesFormat - Properties of the Azure Firewall. +type AzureFirewallPropertiesFormat struct { + // The additional properties used to further config this azure firewall. + AdditionalProperties map[string]*string + + // Collection of application rule collections used by Azure Firewall. + ApplicationRuleCollections []*AzureFirewallApplicationRuleCollection + + // The firewallPolicy associated with this azure firewall. + FirewallPolicy *SubResource + + // IP addresses associated with AzureFirewall. + HubIPAddresses *HubIPAddresses + + // IP configuration of the Azure Firewall resource. + IPConfigurations []*AzureFirewallIPConfiguration + + // IP configuration of the Azure Firewall used for management traffic. + ManagementIPConfiguration *AzureFirewallIPConfiguration + + // Collection of NAT rule collections used by Azure Firewall. + NatRuleCollections []*AzureFirewallNatRuleCollection + + // Collection of network rule collections used by Azure Firewall. + NetworkRuleCollections []*AzureFirewallNetworkRuleCollection + + // The Azure Firewall Resource SKU. + SKU *AzureFirewallSKU + + // The operation mode for Threat Intelligence. + ThreatIntelMode *AzureFirewallThreatIntelMode + + // The virtualHub to which the firewall belongs. + VirtualHub *SubResource + + // READ-ONLY; IpGroups associated with AzureFirewall. + IPGroups []*AzureFirewallIPGroups + + // READ-ONLY; The provisioning state of the Azure firewall resource. + ProvisioningState *ProvisioningState +} + +// AzureFirewallPublicIPAddress - Public IP Address associated with azure firewall. +type AzureFirewallPublicIPAddress struct { + // Public IP Address value. + Address *string +} + +// AzureFirewallRCAction - Properties of the AzureFirewallRCAction. +type AzureFirewallRCAction struct { + // The type of action. + Type *AzureFirewallRCActionType +} + +// AzureFirewallSKU - SKU of an Azure Firewall. +type AzureFirewallSKU struct { + // Name of an Azure Firewall SKU. + Name *AzureFirewallSKUName + + // Tier of an Azure Firewall. + Tier *AzureFirewallSKUTier +} + +// AzureReachabilityReport - Azure reachability report details. +type AzureReachabilityReport struct { + // REQUIRED; The aggregation level of Azure reachability report. Can be Country, State or City. + AggregationLevel *string + + // REQUIRED; Parameters that define a geographic location. + ProviderLocation *AzureReachabilityReportLocation + + // REQUIRED; List of Azure reachability report items. + ReachabilityReport []*AzureReachabilityReportItem +} + +// AzureReachabilityReportItem - Azure reachability report details for a given provider location. +type AzureReachabilityReportItem struct { + // The Azure region. + AzureLocation *string + + // List of latency details for each of the time series. + Latencies []*AzureReachabilityReportLatencyInfo + + // The Internet service provider. + Provider *string +} + +// AzureReachabilityReportLatencyInfo - Details on latency for a time series. +type AzureReachabilityReportLatencyInfo struct { + // The relative latency score between 1 and 100, higher values indicating a faster connection. + Score *int32 + + // The time stamp. + TimeStamp *time.Time +} + +// AzureReachabilityReportLocation - Parameters that define a geographic location. +type AzureReachabilityReportLocation struct { + // REQUIRED; The name of the country. + Country *string + + // The name of the city or town. + City *string + + // The name of the state. + State *string +} + +// AzureReachabilityReportParameters - Geographic and time constraints for Azure reachability report. +type AzureReachabilityReportParameters struct { + // REQUIRED; The end time for the Azure reachability report. + EndTime *time.Time + + // REQUIRED; Parameters that define a geographic location. + ProviderLocation *AzureReachabilityReportLocation + + // REQUIRED; The start time for the Azure reachability report. + StartTime *time.Time + + // Optional Azure regions to scope the query to. + AzureLocations []*string + + // List of Internet service providers. + Providers []*string +} + +// AzureWebCategory - Azure Web Category Resource. +type AzureWebCategory struct { + // Resource ID. + ID *string + + // Properties of the Azure Web Category. + Properties *AzureWebCategoryPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// AzureWebCategoryListResult - Response for ListAzureWebCategories API service call. +type AzureWebCategoryListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Azure Web Categories for a given Subscription. + Value []*AzureWebCategory +} + +// AzureWebCategoryPropertiesFormat - Azure Web Category Properties. +type AzureWebCategoryPropertiesFormat struct { + // READ-ONLY; The name of the group that the category belongs to. + Group *string +} + +// BGPCommunity - Contains bgp community information offered in Service Community resources. +type BGPCommunity struct { + // The name of the bgp community. e.g. Skype. + CommunityName *string + + // The prefixes that the bgp community contains. + CommunityPrefixes []*string + + // The value of the bgp community. For more information: https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing. + CommunityValue *string + + // Customer is authorized to use bgp community or not. + IsAuthorizedToUse *bool + + // The service group of the bgp community contains. + ServiceGroup *string + + // The region which the service support. e.g. For O365, region is Global. + ServiceSupportedRegion *string +} + +// BackendAddressInboundNatRulePortMappings - The response for a QueryInboundNatRulePortMapping API. +type BackendAddressInboundNatRulePortMappings struct { + // Collection of inbound NAT rule port mappings. + InboundNatRulePortMappings []*InboundNatRulePortMapping +} + +// BackendAddressPool - Pool of backend IP addresses. +type BackendAddressPool struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the set of backend address pools used by the load balancer. This name can + // be used to access the resource. + Name *string + + // Properties of load balancer backend address pool. + Properties *BackendAddressPoolPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// BackendAddressPoolPropertiesFormat - Properties of the backend address pool. +type BackendAddressPoolPropertiesFormat struct { + // Amount of seconds Load Balancer waits for before sending RESET to client and backend address. + DrainPeriodInSeconds *int32 + + // An array of backend addresses. + LoadBalancerBackendAddresses []*LoadBalancerBackendAddress + + // The location of the backend address pool. + Location *string + + // Backend address synchronous mode for the backend pool + SyncMode *SyncMode + + // An array of gateway load balancer tunnel interfaces. + TunnelInterfaces []*GatewayLoadBalancerTunnelInterface + + // A reference to a virtual network. + VirtualNetwork *SubResource + + // READ-ONLY; An array of references to IP addresses defined in network interfaces. + BackendIPConfigurations []*InterfaceIPConfiguration + + // READ-ONLY; An array of references to inbound NAT rules that use this backend address pool. + InboundNatRules []*SubResource + + // READ-ONLY; An array of references to load balancing rules that use this backend address pool. + LoadBalancingRules []*SubResource + + // READ-ONLY; A reference to an outbound rule that uses this backend address pool. + OutboundRule *SubResource + + // READ-ONLY; An array of references to outbound rules that use this backend address pool. + OutboundRules []*SubResource + + // READ-ONLY; The provisioning state of the backend address pool resource. + ProvisioningState *ProvisioningState +} + +// BaseAdminRule - Network base admin rule. +type BaseAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *AdminRuleKind + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// GetBaseAdminRule implements the BaseAdminRuleClassification interface for type BaseAdminRule. +func (b *BaseAdminRule) GetBaseAdminRule() *BaseAdminRule { return b } + +// BastionActiveSession - The session detail for a target. +type BastionActiveSession struct { + // READ-ONLY; The protocol used to connect to the target. + Protocol *BastionConnectProtocol + + // READ-ONLY; The type of the resource. + ResourceType *string + + // READ-ONLY; Duration in mins the session has been active. + SessionDurationInMins *float32 + + // READ-ONLY; A unique id for the session. + SessionID *string + + // READ-ONLY; The time when the session started. + StartTime any + + // READ-ONLY; The host name of the target. + TargetHostName *string + + // READ-ONLY; The IP Address of the target. + TargetIPAddress *string + + // READ-ONLY; The resource group of the target. + TargetResourceGroup *string + + // READ-ONLY; The resource id of the target. + TargetResourceID *string + + // READ-ONLY; The subscription id for the target virtual machine. + TargetSubscriptionID *string + + // READ-ONLY; The user name who is active on this session. + UserName *string +} + +// BastionActiveSessionListResult - Response for GetActiveSessions. +type BastionActiveSessionListResult struct { + // The URL to get the next set of results. + NextLink *string + + // List of active sessions on the bastion. + Value []*BastionActiveSession +} + +// BastionHost - Bastion Host resource. +type BastionHost struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Represents the bastion host resource. + Properties *BastionHostPropertiesFormat + + // The sku of this Bastion Host. + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// BastionHostIPConfiguration - IP configuration of an Bastion Host. +type BastionHostIPConfiguration struct { + // Resource ID. + ID *string + + // Name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Represents the ip configuration associated with the resource. + Properties *BastionHostIPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Ip configuration type. + Type *string +} + +// BastionHostIPConfigurationPropertiesFormat - Properties of IP configuration of an Bastion Host. +type BastionHostIPConfigurationPropertiesFormat struct { + // REQUIRED; Reference of the PublicIP resource. + PublicIPAddress *SubResource + + // REQUIRED; Reference of the subnet resource. + Subnet *SubResource + + // Private IP allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // READ-ONLY; The provisioning state of the bastion host IP configuration resource. + ProvisioningState *ProvisioningState +} + +// BastionHostListResult - Response for ListBastionHosts API service call. +type BastionHostListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Bastion Hosts in a resource group. + Value []*BastionHost +} + +// BastionHostPropertiesFormat - Properties of the Bastion Host. +type BastionHostPropertiesFormat struct { + // FQDN for the endpoint on which bastion host is accessible. + DNSName *string + + // Enable/Disable Copy/Paste feature of the Bastion Host resource. + DisableCopyPaste *bool + + // Enable/Disable File Copy feature of the Bastion Host resource. + EnableFileCopy *bool + + // Enable/Disable IP Connect feature of the Bastion Host resource. + EnableIPConnect *bool + + // Enable/Disable Kerberos feature of the Bastion Host resource. + EnableKerberos *bool + + // Enable/Disable Shareable Link of the Bastion Host resource. + EnableShareableLink *bool + + // Enable/Disable Tunneling feature of the Bastion Host resource. + EnableTunneling *bool + + // IP configuration of the Bastion Host resource. + IPConfigurations []*BastionHostIPConfiguration + NetworkACLs *BastionHostPropertiesFormatNetworkACLs + + // The scale units for the Bastion Host resource. + ScaleUnits *int32 + + // Reference to an existing virtual network required for Developer Bastion Host only. + VirtualNetwork *SubResource + + // READ-ONLY; The provisioning state of the bastion host resource. + ProvisioningState *ProvisioningState +} + +type BastionHostPropertiesFormatNetworkACLs struct { + // Sets the IP ACL rules for Developer Bastion Host. + IPRules []*IPRule +} + +// BastionSessionDeleteResult - Response for DisconnectActiveSessions. +type BastionSessionDeleteResult struct { + // The URL to get the next set of results. + NextLink *string + + // List of sessions with their corresponding state. + Value []*BastionSessionState +} + +// BastionSessionState - The session state detail for a target. +type BastionSessionState struct { + // READ-ONLY; Used for extra information. + Message *string + + // READ-ONLY; A unique id for the session. + SessionID *string + + // READ-ONLY; The state of the session. Disconnected/Failed/NotFound. + State *string +} + +// BastionShareableLink - Bastion Shareable Link. +type BastionShareableLink struct { + // REQUIRED; Reference of the virtual machine resource. + VM *VM + + // READ-ONLY; The unique Bastion Shareable Link to the virtual machine. + Bsl *string + + // READ-ONLY; The time when the link was created. + CreatedAt *string + + // READ-ONLY; Optional field indicating the warning or error message related to the vm in case of partial failure. + Message *string +} + +// BastionShareableLinkListRequest - Post request for all the Bastion Shareable Link endpoints. +type BastionShareableLinkListRequest struct { + // List of VM references. + VMs []*BastionShareableLink +} + +// BastionShareableLinkListResult - Response for all the Bastion Shareable Link endpoints. +type BastionShareableLinkListResult struct { + // The URL to get the next set of results. + NextLink *string + + // List of Bastion Shareable Links for the request. + Value []*BastionShareableLink +} + +// BgpConnection - Virtual Appliance Site resource. +type BgpConnection struct { + // Resource ID. + ID *string + + // Name of the connection. + Name *string + + // The properties of the Bgp connections. + Properties *BgpConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Connection type. + Type *string +} + +// BgpConnectionProperties - Properties of the bgp connection. +type BgpConnectionProperties struct { + // The reference to the HubVirtualNetworkConnection resource. + HubVirtualNetworkConnection *SubResource + + // Peer ASN. + PeerAsn *int64 + + // Peer IP. + PeerIP *string + + // READ-ONLY; The current state of the VirtualHub to Peer. + ConnectionState *HubBgpConnectionStatus + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// BgpPeerStatus - BGP peer status details. +type BgpPeerStatus struct { + // READ-ONLY; The autonomous system number of the remote BGP peer. + Asn *int64 + + // READ-ONLY; For how long the peering has been up. + ConnectedDuration *string + + // READ-ONLY; The virtual network gateway's local address. + LocalAddress *string + + // READ-ONLY; The number of BGP messages received. + MessagesReceived *int64 + + // READ-ONLY; The number of BGP messages sent. + MessagesSent *int64 + + // READ-ONLY; The remote BGP peer. + Neighbor *string + + // READ-ONLY; The number of routes learned from this peer. + RoutesReceived *int64 + + // READ-ONLY; The BGP peer state. + State *BgpPeerState +} + +// BgpPeerStatusListResult - Response for list BGP peer status API service call. +type BgpPeerStatusListResult struct { + // List of BGP peers. + Value []*BgpPeerStatus +} + +// BgpServiceCommunity - Service Community Properties. +type BgpServiceCommunity struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the BGP service community. + Properties *BgpServiceCommunityPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// BgpServiceCommunityListResult - Response for the ListServiceCommunity API service call. +type BgpServiceCommunityListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of service community resources. + Value []*BgpServiceCommunity +} + +// BgpServiceCommunityPropertiesFormat - Properties of Service Community. +type BgpServiceCommunityPropertiesFormat struct { + // A list of bgp communities. + BgpCommunities []*BGPCommunity + + // The name of the bgp community. e.g. Skype. + ServiceName *string +} + +// BgpSettings - BGP settings details. +type BgpSettings struct { + // The BGP speaker's ASN. + Asn *int64 + + // The BGP peering address and BGP identifier of this BGP speaker. + BgpPeeringAddress *string + + // BGP peering address with IP configuration ID for virtual network gateway. + BgpPeeringAddresses []*IPConfigurationBgpPeeringAddress + + // The weight added to routes learned from this BGP speaker. + PeerWeight *int32 +} + +// BreakOutCategoryPolicies - Network Virtual Appliance Sku Properties. +type BreakOutCategoryPolicies struct { + // Flag to control breakout of o365 allow category. + Allow *bool + + // Flag to control breakout of o365 default category. + Default *bool + + // Flag to control breakout of o365 optimize category. + Optimize *bool +} + +// CheckPrivateLinkServiceVisibilityRequest - Request body of the CheckPrivateLinkServiceVisibility API service call. +type CheckPrivateLinkServiceVisibilityRequest struct { + // The alias of the private link service. + PrivateLinkServiceAlias *string +} + +// ChildResource - Proxy resource representation. +type ChildResource struct { + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +type Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties struct { + // READ-ONLY; The client id of user assigned identity. + ClientID *string + + // READ-ONLY; The principal id of user assigned identity. + PrincipalID *string +} + +// ConfigurationDiagnosticParameters - Parameters to get network configuration diagnostic. +type ConfigurationDiagnosticParameters struct { + // REQUIRED; List of network configuration diagnostic profiles. + Profiles []*ConfigurationDiagnosticProfile + + // REQUIRED; The ID of the target resource to perform network configuration diagnostic. Valid options are VM, NetworkInterface, + // VMSS/NetworkInterface and Application Gateway. + TargetResourceID *string + + // Verbosity level. + VerbosityLevel *VerbosityLevel +} + +// ConfigurationDiagnosticProfile - Parameters to compare with network configuration. +type ConfigurationDiagnosticProfile struct { + // REQUIRED; Traffic destination. Accepted values are: '*', IP Address/CIDR, Service Tag. + Destination *string + + // REQUIRED; Traffic destination port. Accepted values are '*' and a single port in the range (0 - 65535). + DestinationPort *string + + // REQUIRED; The direction of the traffic. + Direction *Direction + + // REQUIRED; Protocol to be verified on. Accepted values are '*', TCP, UDP. + Protocol *string + + // REQUIRED; Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag. + Source *string +} + +// ConfigurationDiagnosticResponse - Results of network configuration diagnostic on the target resource. +type ConfigurationDiagnosticResponse struct { + // READ-ONLY; List of network configuration diagnostic results. + Results []*ConfigurationDiagnosticResult +} + +// ConfigurationDiagnosticResult - Network configuration diagnostic result corresponded to provided traffic query. +type ConfigurationDiagnosticResult struct { + // Network security group result. + NetworkSecurityGroupResult *SecurityGroupResult + + // Network configuration diagnostic profile. + Profile *ConfigurationDiagnosticProfile +} + +// ConfigurationGroup - The network configuration group resource +type ConfigurationGroup struct { + // Network group ID. + ID *string + + // The network configuration group properties + Properties *GroupProperties +} + +// ConnectionMonitor - Parameters that define the operation to create a connection monitor. +type ConnectionMonitor struct { + // REQUIRED; Properties of the connection monitor. + Properties *ConnectionMonitorParameters + + // Connection monitor location. + Location *string + + // Connection monitor tags. + Tags map[string]*string +} + +// ConnectionMonitorDestination - Describes the destination of connection monitor. +type ConnectionMonitorDestination struct { + // Address of the connection monitor destination (IP or domain name). + Address *string + + // The destination port used by connection monitor. + Port *int32 + + // The ID of the resource used as the destination by connection monitor. + ResourceID *string +} + +// ConnectionMonitorEndpoint - Describes the connection monitor endpoint. +type ConnectionMonitorEndpoint struct { + // REQUIRED; The name of the connection monitor endpoint. + Name *string + + // Address of the connection monitor endpoint (IP or domain name). + Address *string + + // Test coverage for the endpoint. + CoverageLevel *CoverageLevel + + // Filter for sub-items within the endpoint. + Filter *ConnectionMonitorEndpointFilter + + // Resource ID of the connection monitor endpoint. + ResourceID *string + + // Endpoint scope. + Scope *ConnectionMonitorEndpointScope + + // The endpoint type. + Type *EndpointType +} + +// ConnectionMonitorEndpointFilter - Describes the connection monitor endpoint filter. +type ConnectionMonitorEndpointFilter struct { + // List of items in the filter. + Items []*ConnectionMonitorEndpointFilterItem + + // The behavior of the endpoint filter. Currently only 'Include' is supported. + Type *ConnectionMonitorEndpointFilterType +} + +// ConnectionMonitorEndpointFilterItem - Describes the connection monitor endpoint filter item. +type ConnectionMonitorEndpointFilterItem struct { + // The address of the filter item. + Address *string + + // The type of item included in the filter. Currently only 'AgentAddress' is supported. + Type *ConnectionMonitorEndpointFilterItemType +} + +// ConnectionMonitorEndpointScope - Describes the connection monitor endpoint scope. +type ConnectionMonitorEndpointScope struct { + // List of items which needs to be excluded from the endpoint scope. + Exclude []*ConnectionMonitorEndpointScopeItem + + // List of items which needs to be included to the endpoint scope. + Include []*ConnectionMonitorEndpointScopeItem +} + +// ConnectionMonitorEndpointScopeItem - Describes the connection monitor endpoint scope item. +type ConnectionMonitorEndpointScopeItem struct { + // The address of the endpoint item. Supported types are IPv4/IPv6 subnet mask or IPv4/IPv6 IP address. + Address *string +} + +// ConnectionMonitorHTTPConfiguration - Describes the HTTP configuration. +type ConnectionMonitorHTTPConfiguration struct { + // The HTTP method to use. + Method *HTTPConfigurationMethod + + // The path component of the URI. For instance, "/dir1/dir2". + Path *string + + // The port to connect to. + Port *int32 + + // Value indicating whether HTTPS is preferred over HTTP in cases where the choice is not explicit. + PreferHTTPS *bool + + // The HTTP headers to transmit with the request. + RequestHeaders []*HTTPHeader + + // HTTP status codes to consider successful. For instance, "2xx,301-304,418". + ValidStatusCodeRanges []*string +} + +// ConnectionMonitorIcmpConfiguration - Describes the ICMP configuration. +type ConnectionMonitorIcmpConfiguration struct { + // Value indicating whether path evaluation with trace route should be disabled. + DisableTraceRoute *bool +} + +// ConnectionMonitorListResult - List of connection monitors. +type ConnectionMonitorListResult struct { + // Information about connection monitors. + Value []*ConnectionMonitorResult +} + +// ConnectionMonitorOutput - Describes a connection monitor output destination. +type ConnectionMonitorOutput struct { + // Connection monitor output destination type. Currently, only "Workspace" is supported. + Type *OutputType + + // Describes the settings for producing output into a log analytics workspace. + WorkspaceSettings *ConnectionMonitorWorkspaceSettings +} + +// ConnectionMonitorParameters - Parameters that define the operation to create a connection monitor. +type ConnectionMonitorParameters struct { + // Determines if the connection monitor will start automatically once created. + AutoStart *bool + + // Describes the destination of connection monitor. + Destination *ConnectionMonitorDestination + + // List of connection monitor endpoints. + Endpoints []*ConnectionMonitorEndpoint + + // Monitoring interval in seconds. + MonitoringIntervalInSeconds *int32 + + // Optional notes to be associated with the connection monitor. + Notes *string + + // List of connection monitor outputs. + Outputs []*ConnectionMonitorOutput + + // Describes the source of connection monitor. + Source *ConnectionMonitorSource + + // List of connection monitor test configurations. + TestConfigurations []*ConnectionMonitorTestConfiguration + + // List of connection monitor test groups. + TestGroups []*ConnectionMonitorTestGroup +} + +// ConnectionMonitorQueryResult - List of connection states snapshots. +type ConnectionMonitorQueryResult struct { + // Status of connection monitor source. + SourceStatus *ConnectionMonitorSourceStatus + + // Information about connection states. + States []*ConnectionStateSnapshot +} + +// ConnectionMonitorResult - Information about the connection monitor. +type ConnectionMonitorResult struct { + // Connection monitor location. + Location *string + + // Properties of the connection monitor result. + Properties *ConnectionMonitorResultProperties + + // Connection monitor tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; ID of the connection monitor. + ID *string + + // READ-ONLY; Name of the connection monitor. + Name *string + + // READ-ONLY; Connection monitor type. + Type *string +} + +// ConnectionMonitorResultProperties - Describes the properties of a connection monitor. +type ConnectionMonitorResultProperties struct { + // Determines if the connection monitor will start automatically once created. + AutoStart *bool + + // Describes the destination of connection monitor. + Destination *ConnectionMonitorDestination + + // List of connection monitor endpoints. + Endpoints []*ConnectionMonitorEndpoint + + // Monitoring interval in seconds. + MonitoringIntervalInSeconds *int32 + + // Optional notes to be associated with the connection monitor. + Notes *string + + // List of connection monitor outputs. + Outputs []*ConnectionMonitorOutput + + // Describes the source of connection monitor. + Source *ConnectionMonitorSource + + // List of connection monitor test configurations. + TestConfigurations []*ConnectionMonitorTestConfiguration + + // List of connection monitor test groups. + TestGroups []*ConnectionMonitorTestGroup + + // READ-ONLY; Type of connection monitor. + ConnectionMonitorType *ConnectionMonitorType + + // READ-ONLY; The monitoring status of the connection monitor. + MonitoringStatus *string + + // READ-ONLY; The provisioning state of the connection monitor. + ProvisioningState *ProvisioningState + + // READ-ONLY; The date and time when the connection monitor was started. + StartTime *time.Time +} + +// ConnectionMonitorSource - Describes the source of connection monitor. +type ConnectionMonitorSource struct { + // REQUIRED; The ID of the resource used as the source by connection monitor. + ResourceID *string + + // The source port used by connection monitor. + Port *int32 +} + +// ConnectionMonitorSuccessThreshold - Describes the threshold for declaring a test successful. +type ConnectionMonitorSuccessThreshold struct { + // The maximum percentage of failed checks permitted for a test to evaluate as successful. + ChecksFailedPercent *int32 + + // The maximum round-trip time in milliseconds permitted for a test to evaluate as successful. + RoundTripTimeMs *float32 +} + +// ConnectionMonitorTCPConfiguration - Describes the TCP configuration. +type ConnectionMonitorTCPConfiguration struct { + // Destination port behavior. + DestinationPortBehavior *DestinationPortBehavior + + // Value indicating whether path evaluation with trace route should be disabled. + DisableTraceRoute *bool + + // The port to connect to. + Port *int32 +} + +// ConnectionMonitorTestConfiguration - Describes a connection monitor test configuration. +type ConnectionMonitorTestConfiguration struct { + // REQUIRED; The name of the connection monitor test configuration. + Name *string + + // REQUIRED; The protocol to use in test evaluation. + Protocol *ConnectionMonitorTestConfigurationProtocol + + // The parameters used to perform test evaluation over HTTP. + HTTPConfiguration *ConnectionMonitorHTTPConfiguration + + // The parameters used to perform test evaluation over ICMP. + IcmpConfiguration *ConnectionMonitorIcmpConfiguration + + // The preferred IP version to use in test evaluation. The connection monitor may choose to use a different version depending + // on other parameters. + PreferredIPVersion *PreferredIPVersion + + // The threshold for declaring a test successful. + SuccessThreshold *ConnectionMonitorSuccessThreshold + + // The parameters used to perform test evaluation over TCP. + TCPConfiguration *ConnectionMonitorTCPConfiguration + + // The frequency of test evaluation, in seconds. + TestFrequencySec *int32 +} + +// ConnectionMonitorTestGroup - Describes the connection monitor test group. +type ConnectionMonitorTestGroup struct { + // REQUIRED; List of destination endpoint names. + Destinations []*string + + // REQUIRED; The name of the connection monitor test group. + Name *string + + // REQUIRED; List of source endpoint names. + Sources []*string + + // REQUIRED; List of test configuration names. + TestConfigurations []*string + + // Value indicating whether test group is disabled. + Disable *bool +} + +// ConnectionMonitorWorkspaceSettings - Describes the settings for producing output into a log analytics workspace. +type ConnectionMonitorWorkspaceSettings struct { + // Log analytics workspace resource ID. + WorkspaceResourceID *string +} + +// ConnectionResetSharedKey - The virtual network connection reset shared key. +type ConnectionResetSharedKey struct { + // REQUIRED; The virtual network connection reset shared key length, should between 1 and 128. + KeyLength *int32 +} + +// ConnectionSharedKey - Response for GetConnectionSharedKey API service call. +type ConnectionSharedKey struct { + // REQUIRED; The virtual network connection shared key value. + Value *string + + // Resource ID. + ID *string +} + +// ConnectionStateSnapshot - Connection state snapshot. +type ConnectionStateSnapshot struct { + // Average latency in ms. + AvgLatencyInMs *int64 + + // The connection state. + ConnectionState *ConnectionState + + // The end time of the connection snapshot. + EndTime *time.Time + + // Connectivity analysis evaluation state. + EvaluationState *EvaluationState + + // Maximum latency in ms. + MaxLatencyInMs *int64 + + // Minimum latency in ms. + MinLatencyInMs *int64 + + // The number of failed probes. + ProbesFailed *int64 + + // The number of sent probes. + ProbesSent *int64 + + // The start time of the connection snapshot. + StartTime *time.Time + + // READ-ONLY; List of hops between the source and the destination. + Hops []*ConnectivityHop +} + +// ConnectivityConfiguration - The network manager connectivity configuration resource +type ConnectivityConfiguration struct { + // Properties of a network manager connectivity configuration + Properties *ConnectivityConfigurationProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// ConnectivityConfigurationListResult - Result of the request to list network manager connectivity configurations. It contains +// a list of configurations and a link to get the next set of results. +type ConnectivityConfigurationListResult struct { + // Gets the URL to get the next page of results. + NextLink *string + + // Gets a page of Connectivity Configurations + Value []*ConnectivityConfiguration +} + +// ConnectivityConfigurationProperties - Properties of network manager connectivity configuration +type ConnectivityConfigurationProperties struct { + // REQUIRED; Groups for configuration + AppliesToGroups []*ConnectivityGroupItem + + // REQUIRED; Connectivity topology type. + ConnectivityTopology *ConnectivityTopology + + // Flag if need to remove current existing peerings. + DeleteExistingPeering *DeleteExistingPeering + + // A description of the connectivity configuration. + Description *string + + // List of hubItems + Hubs []*Hub + + // Flag if global mesh is supported. + IsGlobal *IsGlobal + + // READ-ONLY; The provisioning state of the connectivity configuration resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Unique identifier for this resource. + ResourceGUID *string +} + +// ConnectivityDestination - Parameters that define destination of connection. +type ConnectivityDestination struct { + // The IP address or URI the resource to which a connection attempt will be made. + Address *string + + // Port on which check connectivity will be performed. + Port *int32 + + // The ID of the resource to which a connection attempt will be made. + ResourceID *string +} + +// ConnectivityGroupItem - Connectivity group item. +type ConnectivityGroupItem struct { + // REQUIRED; Group connectivity type. + GroupConnectivity *GroupConnectivity + + // REQUIRED; Network group Id. + NetworkGroupID *string + + // Flag if global is supported. + IsGlobal *IsGlobal + + // Flag if need to use hub gateway. + UseHubGateway *UseHubGateway +} + +// ConnectivityHop - Information about a hop between the source and the destination. +type ConnectivityHop struct { + // READ-ONLY; The IP address of the hop. + Address *string + + // READ-ONLY; The ID of the hop. + ID *string + + // READ-ONLY; List of issues. + Issues []*ConnectivityIssue + + // READ-ONLY; List of hop links. + Links []*HopLink + + // READ-ONLY; List of next hop identifiers. + NextHopIDs []*string + + // READ-ONLY; List of previous hop identifiers. + PreviousHopIDs []*string + + // READ-ONLY; List of previous hop links. + PreviousLinks []*HopLink + + // READ-ONLY; The ID of the resource corresponding to this hop. + ResourceID *string + + // READ-ONLY; The type of the hop. + Type *string +} + +// ConnectivityInformation - Information on the connectivity status. +type ConnectivityInformation struct { + // READ-ONLY; Average latency in milliseconds. + AvgLatencyInMs *int32 + + // READ-ONLY; The connection status. + ConnectionStatus *ConnectionStatus + + // READ-ONLY; List of hops between the source and the destination. + Hops []*ConnectivityHop + + // READ-ONLY; Maximum latency in milliseconds. + MaxLatencyInMs *int32 + + // READ-ONLY; Minimum latency in milliseconds. + MinLatencyInMs *int32 + + // READ-ONLY; Number of failed probes. + ProbesFailed *int32 + + // READ-ONLY; Total number of probes sent. + ProbesSent *int32 +} + +// ConnectivityIssue - Information about an issue encountered in the process of checking for connectivity. +type ConnectivityIssue struct { + // READ-ONLY; Provides additional context on the issue. + Context []map[string]*string + + // READ-ONLY; The origin of the issue. + Origin *Origin + + // READ-ONLY; The severity of the issue. + Severity *Severity + + // READ-ONLY; The type of issue. + Type *IssueType +} + +// ConnectivityParameters - Parameters that determine how the connectivity check will be performed. +type ConnectivityParameters struct { + // REQUIRED; The destination of connection. + Destination *ConnectivityDestination + + // REQUIRED; The source of the connection. + Source *ConnectivitySource + + // Preferred IP version of the connection. + PreferredIPVersion *IPVersion + + // Network protocol. + Protocol *Protocol + + // Configuration of the protocol. + ProtocolConfiguration *ProtocolConfiguration +} + +// ConnectivitySource - Parameters that define the source of the connection. +type ConnectivitySource struct { + // REQUIRED; The ID of the resource from which a connectivity check will be initiated. + ResourceID *string + + // The source port from which a connectivity check will be performed. + Port *int32 +} + +// Container - Reference to container resource in remote resource provider. +type Container struct { + // Resource ID. + ID *string +} + +// ContainerNetworkInterface - Container network interface child resource. +type ContainerNetworkInterface struct { + // Resource ID. + ID *string + + // The name of the resource. This name can be used to access the resource. + Name *string + + // Container network interface properties. + Properties *ContainerNetworkInterfacePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Sub Resource type. + Type *string +} + +// ContainerNetworkInterfaceConfiguration - Container network interface configuration child resource. +type ContainerNetworkInterfaceConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource. This name can be used to access the resource. + Name *string + + // Container network interface configuration properties. + Properties *ContainerNetworkInterfaceConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Sub Resource type. + Type *string +} + +// ContainerNetworkInterfaceConfigurationPropertiesFormat - Container network interface configuration properties. +type ContainerNetworkInterfaceConfigurationPropertiesFormat struct { + // A list of container network interfaces created from this container network interface configuration. + ContainerNetworkInterfaces []*SubResource + + // A list of ip configurations of the container network interface configuration. + IPConfigurations []*IPConfigurationProfile + + // READ-ONLY; The provisioning state of the container network interface configuration resource. + ProvisioningState *ProvisioningState +} + +// ContainerNetworkInterfaceIPConfiguration - The ip configuration for a container network interface. +type ContainerNetworkInterfaceIPConfiguration struct { + // The name of the resource. This name can be used to access the resource. + Name *string + + // Properties of the container network interface IP configuration. + Properties *ContainerNetworkInterfaceIPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Sub Resource type. + Type *string +} + +// ContainerNetworkInterfaceIPConfigurationPropertiesFormat - Properties of the container network interface IP configuration. +type ContainerNetworkInterfaceIPConfigurationPropertiesFormat struct { + // READ-ONLY; The provisioning state of the container network interface IP configuration resource. + ProvisioningState *ProvisioningState +} + +// ContainerNetworkInterfacePropertiesFormat - Properties of container network interface. +type ContainerNetworkInterfacePropertiesFormat struct { + // Reference to the container to which this container network interface is attached. + Container *Container + + // READ-ONLY; Container network interface configuration from which this container network interface is created. + ContainerNetworkInterfaceConfiguration *ContainerNetworkInterfaceConfiguration + + // READ-ONLY; Reference to the ip configuration on this container nic. + IPConfigurations []*ContainerNetworkInterfaceIPConfiguration + + // READ-ONLY; The provisioning state of the container network interface resource. + ProvisioningState *ProvisioningState +} + +// Criterion - A matching criteria which matches routes based on route prefix, community, and AS path. +type Criterion struct { + // List of AS paths which this criteria matches. + AsPath []*string + + // List of BGP communities which this criteria matches. + Community []*string + + // Match condition to apply RouteMap rules. + MatchCondition *RouteMapMatchCondition + + // List of route prefixes which this criteria matches. + RoutePrefix []*string +} + +// CrossTenantScopes - Cross tenant scopes. +type CrossTenantScopes struct { + // READ-ONLY; List of management groups. + ManagementGroups []*string + + // READ-ONLY; List of subscriptions. + Subscriptions []*string + + // READ-ONLY; Tenant ID. + TenantID *string +} + +// CustomDNSConfigPropertiesFormat - Contains custom Dns resolution configuration from customer. +type CustomDNSConfigPropertiesFormat struct { + // Fqdn that resolves to private endpoint ip address. + Fqdn *string + + // A list of private ip addresses of the private endpoint. + IPAddresses []*string +} + +// CustomIPPrefix - Custom IP prefix resource. +type CustomIPPrefix struct { + // The extended location of the custom IP prefix. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Custom IP prefix properties. + Properties *CustomIPPrefixPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // A list of availability zones denoting the IP allocated for the resource needs to come from. + Zones []*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// CustomIPPrefixListResult - Response for ListCustomIpPrefixes API service call. +type CustomIPPrefixListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of Custom IP prefixes that exists in a resource group. + Value []*CustomIPPrefix +} + +// CustomIPPrefixPropertiesFormat - Custom IP prefix properties. +type CustomIPPrefixPropertiesFormat struct { + // The ASN for CIDR advertising. Should be an integer as string. + Asn *string + + // Authorization message for WAN validation. + AuthorizationMessage *string + + // The prefix range in CIDR notation. Should include the start address and the prefix length. + Cidr *string + + // The commissioned state of the Custom IP Prefix. + CommissionedState *CommissionedState + + // The Parent CustomIpPrefix for IPv6 /64 CustomIpPrefix. + CustomIPPrefixParent *SubResource + + // Whether to do express route advertise. + ExpressRouteAdvertise *bool + + // The Geo for CIDR advertising. Should be an Geo code. + Geo *Geo + + // Whether to Advertise the range to Internet. + NoInternetAdvertise *bool + + // Type of custom IP prefix. Should be Singular, Parent, or Child. + PrefixType *CustomIPPrefixType + + // Signed message for WAN validation. + SignedMessage *string + + // READ-ONLY; The list of all Children for IPv6 /48 CustomIpPrefix. + ChildCustomIPPrefixes []*SubResource + + // READ-ONLY; The reason why resource is in failed state. + FailedReason *string + + // READ-ONLY; The provisioning state of the custom IP prefix resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The list of all referenced PublicIpPrefixes. + PublicIPPrefixes []*SubResource + + // READ-ONLY; The resource GUID property of the custom IP prefix resource. + ResourceGUID *string +} + +// DNSNameAvailabilityResult - Response for the CheckDnsNameAvailability API service call. +type DNSNameAvailabilityResult struct { + // Domain availability (True/False). + Available *bool +} + +// DNSSettings - DNS Proxy Settings in Firewall Policy. +type DNSSettings struct { + // Enable DNS Proxy on Firewalls attached to the Firewall Policy. + EnableProxy *bool + + // FQDNs in Network Rules are supported when set to true. + RequireProxyForNetworkRules *bool + + // List of Custom DNS Servers. + Servers []*string +} + +// DdosCustomPolicy - A DDoS custom policy in a resource group. +type DdosCustomPolicy struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the DDoS custom policy. + Properties *DdosCustomPolicyPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// DdosCustomPolicyPropertiesFormat - DDoS custom policy properties. +type DdosCustomPolicyPropertiesFormat struct { + // READ-ONLY; The provisioning state of the DDoS custom policy resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the DDoS custom policy resource. It uniquely identifies the resource, even if + // the user changes its name or migrate the resource across subscriptions or resource groups. + ResourceGUID *string +} + +// DdosProtectionPlan - A DDoS protection plan in a resource group. +type DdosProtectionPlan struct { + // Resource location. + Location *string + + // Properties of the DDoS protection plan. + Properties *DdosProtectionPlanPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// DdosProtectionPlanListResult - A list of DDoS protection plans. +type DdosProtectionPlanListResult struct { + // A list of DDoS protection plans. + Value []*DdosProtectionPlan + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// DdosProtectionPlanPropertiesFormat - DDoS protection plan properties. +type DdosProtectionPlanPropertiesFormat struct { + // READ-ONLY; The provisioning state of the DDoS protection plan resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The list of public IPs associated with the DDoS protection plan resource. This list is read-only. + PublicIPAddresses []*SubResource + + // READ-ONLY; The resource GUID property of the DDoS protection plan resource. It uniquely identifies the resource, even if + // the user changes its name or migrate the resource across subscriptions or resource groups. + ResourceGUID *string + + // READ-ONLY; The list of virtual networks associated with the DDoS protection plan resource. This list is read-only. + VirtualNetworks []*SubResource +} + +// DdosSettings - Contains the DDoS protection settings of the public IP. +type DdosSettings struct { + // The DDoS protection plan associated with the public IP. Can only be set if ProtectionMode is Enabled + DdosProtectionPlan *SubResource + + // The DDoS protection mode of the public IP + ProtectionMode *DdosSettingsProtectionMode +} + +// DefaultAdminPropertiesFormat - Security default admin rule resource. +type DefaultAdminPropertiesFormat struct { + // Default rule flag. + Flag *string + + // READ-ONLY; Indicates the access allowed for this particular rule + Access *SecurityConfigurationRuleAccess + + // READ-ONLY; A description for this rule. Restricted to 140 chars. + Description *string + + // READ-ONLY; The destination port ranges. + DestinationPortRanges []*string + + // READ-ONLY; The destination address prefixes. CIDR or destination IP ranges. + Destinations []*AddressPrefixItem + + // READ-ONLY; Indicates if the traffic matched against the rule in inbound or outbound. + Direction *SecurityConfigurationRuleDirection + + // READ-ONLY; The priority of the rule. The value can be between 1 and 4096. The priority number must be unique for each rule + // in the collection. The lower the priority number, the higher the priority of the rule. + Priority *int32 + + // READ-ONLY; Network protocol this rule applies to. + Protocol *SecurityConfigurationRuleProtocol + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Unique identifier for this resource. + ResourceGUID *string + + // READ-ONLY; The source port ranges. + SourcePortRanges []*string + + // READ-ONLY; The CIDR or source IP ranges. + Sources []*AddressPrefixItem +} + +// DefaultAdminRule - Network default admin rule. +type DefaultAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *AdminRuleKind + + // Indicates the properties of the security admin rule + Properties *DefaultAdminPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// GetBaseAdminRule implements the BaseAdminRuleClassification interface for type DefaultAdminRule. +func (d *DefaultAdminRule) GetBaseAdminRule() *BaseAdminRule { + return &BaseAdminRule{ + Etag: d.Etag, + ID: d.ID, + Kind: d.Kind, + Name: d.Name, + SystemData: d.SystemData, + Type: d.Type, + } +} + +// DefaultRuleSetPropertyFormat - the default web application firewall rule set. +type DefaultRuleSetPropertyFormat struct { + // The type of the web application firewall rule set. + RuleSetType *string + + // The version of the web application firewall rule set type. + RuleSetVersion *string +} + +// Delegation - Details the service to which the subnet is delegated. +type Delegation struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a subnet. This name can be used to access the resource. + Name *string + + // Properties of the subnet. + Properties *ServiceDelegationPropertiesFormat + + // Resource type. + Type *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// DelegationProperties - Properties of the delegation. +type DelegationProperties struct { + // The service name to which the NVA is delegated. + ServiceName *string + + // READ-ONLY; The current provisioning state. + ProvisioningState *ProvisioningState +} + +// DeviceProperties - List of properties of the device. +type DeviceProperties struct { + // Model of the device. + DeviceModel *string + + // Name of the device Vendor. + DeviceVendor *string + + // Link speed. + LinkSpeedInMbps *int32 +} + +// DhcpOptions contains an array of DNS servers available to VMs deployed in the virtual network. Standard DHCP option for +// a subnet overrides VNET DHCP options. +type DhcpOptions struct { + // The list of DNS servers IP addresses. + DNSServers []*string +} + +// Dimension of the metric. +type Dimension struct { + // The display name of the dimension. + DisplayName *string + + // The internal name of the dimension. + InternalName *string + + // The name of the dimension. + Name *string +} + +// DscpConfiguration - Differentiated Services Code Point configuration for any given network interface +type DscpConfiguration struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the network interface. + Properties *DscpConfigurationPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// DscpConfigurationListResult - Response for the DscpConfigurationList API service call. +type DscpConfigurationListResult struct { + // A list of dscp configurations in a resource group. + Value []*DscpConfiguration + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// DscpConfigurationPropertiesFormat - Differentiated Services Code Point configuration properties. +type DscpConfigurationPropertiesFormat struct { + // Destination IP ranges. + DestinationIPRanges []*QosIPRange + + // Destination port ranges. + DestinationPortRanges []*QosPortRange + + // List of markings to be used in the configuration. + Markings []*int32 + + // RNM supported protocol types. + Protocol *ProtocolType + + // QoS object definitions + QosDefinitionCollection []*QosDefinition + + // Source IP ranges. + SourceIPRanges []*QosIPRange + + // Sources port ranges. + SourcePortRanges []*QosPortRange + + // READ-ONLY; Associated Network Interfaces to the DSCP Configuration. + AssociatedNetworkInterfaces []*Interface + + // READ-ONLY; The provisioning state of the DSCP Configuration resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Qos Collection ID generated by RNM. + QosCollectionID *string + + // READ-ONLY; The resource GUID property of the DSCP Configuration resource. + ResourceGUID *string +} + +// EffectiveBaseSecurityAdminRule - Network base admin rule. +type EffectiveBaseSecurityAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *EffectiveAdminRuleKind + + // A description of the security admin configuration. + ConfigurationDescription *string + + // Resource ID. + ID *string + + // Groups for rule collection + RuleCollectionAppliesToGroups []*ManagerSecurityGroupItem + + // A description of the rule collection. + RuleCollectionDescription *string + + // Effective configuration groups. + RuleGroups []*ConfigurationGroup +} + +// GetEffectiveBaseSecurityAdminRule implements the EffectiveBaseSecurityAdminRuleClassification interface for type EffectiveBaseSecurityAdminRule. +func (e *EffectiveBaseSecurityAdminRule) GetEffectiveBaseSecurityAdminRule() *EffectiveBaseSecurityAdminRule { + return e +} + +// EffectiveConnectivityConfiguration - The network manager effective connectivity configuration +type EffectiveConnectivityConfiguration struct { + // Effective configuration groups. + ConfigurationGroups []*ConfigurationGroup + + // Connectivity configuration ID. + ID *string + + // Properties of a network manager connectivity configuration + Properties *ConnectivityConfigurationProperties +} + +// EffectiveDefaultSecurityAdminRule - Network default admin rule. +type EffectiveDefaultSecurityAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *EffectiveAdminRuleKind + + // A description of the security admin configuration. + ConfigurationDescription *string + + // Resource ID. + ID *string + + // Indicates the properties of the default security admin rule + Properties *DefaultAdminPropertiesFormat + + // Groups for rule collection + RuleCollectionAppliesToGroups []*ManagerSecurityGroupItem + + // A description of the rule collection. + RuleCollectionDescription *string + + // Effective configuration groups. + RuleGroups []*ConfigurationGroup +} + +// GetEffectiveBaseSecurityAdminRule implements the EffectiveBaseSecurityAdminRuleClassification interface for type EffectiveDefaultSecurityAdminRule. +func (e *EffectiveDefaultSecurityAdminRule) GetEffectiveBaseSecurityAdminRule() *EffectiveBaseSecurityAdminRule { + return &EffectiveBaseSecurityAdminRule{ + ConfigurationDescription: e.ConfigurationDescription, + ID: e.ID, + Kind: e.Kind, + RuleCollectionAppliesToGroups: e.RuleCollectionAppliesToGroups, + RuleCollectionDescription: e.RuleCollectionDescription, + RuleGroups: e.RuleGroups, + } +} + +// EffectiveNetworkSecurityGroup - Effective network security group. +type EffectiveNetworkSecurityGroup struct { + // Associated resources. + Association *EffectiveNetworkSecurityGroupAssociation + + // A collection of effective security rules. + EffectiveSecurityRules []*EffectiveNetworkSecurityRule + + // The ID of network security group that is applied. + NetworkSecurityGroup *SubResource + + // Mapping of tags to list of IP Addresses included within the tag. + TagMap *string +} + +// EffectiveNetworkSecurityGroupAssociation - The effective network security group association. +type EffectiveNetworkSecurityGroupAssociation struct { + // The ID of the network interface if assigned. + NetworkInterface *SubResource + + // The ID of the Azure network manager if assigned. + NetworkManager *SubResource + + // The ID of the subnet if assigned. + Subnet *SubResource +} + +// EffectiveNetworkSecurityGroupListResult - Response for list effective network security groups API service call. +type EffectiveNetworkSecurityGroupListResult struct { + // A list of effective network security groups. + Value []*EffectiveNetworkSecurityGroup + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// EffectiveNetworkSecurityRule - Effective network security rules. +type EffectiveNetworkSecurityRule struct { + // Whether network traffic is allowed or denied. + Access *SecurityRuleAccess + + // The destination address prefix. + DestinationAddressPrefix *string + + // The destination address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, + // Internet), System Tags, and the asterisk (*). + DestinationAddressPrefixes []*string + + // The destination port or range. + DestinationPortRange *string + + // The destination port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator + // (e.g. 100-400), or an asterisk (*). + DestinationPortRanges []*string + + // The direction of the rule. + Direction *SecurityRuleDirection + + // Expanded destination address prefix. + ExpandedDestinationAddressPrefix []*string + + // The expanded source address prefix. + ExpandedSourceAddressPrefix []*string + + // The name of the security rule specified by the user (if created by the user). + Name *string + + // The priority of the rule. + Priority *int32 + + // The network protocol this rule applies to. + Protocol *EffectiveSecurityRuleProtocol + + // The source address prefix. + SourceAddressPrefix *string + + // The source address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), + // System Tags, and the asterisk (*). + SourceAddressPrefixes []*string + + // The source port or range. + SourcePortRange *string + + // The source port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator (e.g. + // 100-400), or an asterisk (*). + SourcePortRanges []*string +} + +// EffectiveRoute - Effective Route. +type EffectiveRoute struct { + // The address prefixes of the effective routes in CIDR notation. + AddressPrefix []*string + + // If true, on-premises routes are not propagated to the network interfaces in the subnet. + DisableBgpRoutePropagation *bool + + // The name of the user defined route. This is optional. + Name *string + + // The IP address of the next hop of the effective route. + NextHopIPAddress []*string + + // The type of Azure hop the packet should be sent to. + NextHopType *RouteNextHopType + + // Who created the route. + Source *EffectiveRouteSource + + // The value of effective route. + State *EffectiveRouteState +} + +// EffectiveRouteListResult - Response for list effective route API service call. +type EffectiveRouteListResult struct { + // A list of effective routes. + Value []*EffectiveRoute + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// EffectiveRouteMapRoute - The effective RouteMap route configured on the connection resource. +type EffectiveRouteMapRoute struct { + // The ASPath of this route. + AsPath *string + + // BGP communities of the route. + BgpCommunities *string + + // The address prefix of the route. + Prefix *string +} + +// EffectiveRouteMapRouteList - EffectiveRouteMapRoute List. +type EffectiveRouteMapRouteList struct { + // The list of Effective RouteMap Routes configured on the connection resource. + Value []*EffectiveRouteMapRoute +} + +// EffectiveRoutesParameters - The parameters specifying the resource whose effective routes are being requested. +type EffectiveRoutesParameters struct { + // The resource whose effective routes are being requested. + ResourceID *string + + // The type of the specified resource like RouteTable, ExpressRouteConnection, HubVirtualNetworkConnection, VpnConnection + // and P2SConnection. + VirtualWanResourceType *string +} + +// EffectiveSecurityAdminRule - Network admin rule. +type EffectiveSecurityAdminRule struct { + // REQUIRED; Whether the rule is custom or default. + Kind *EffectiveAdminRuleKind + + // A description of the security admin configuration. + ConfigurationDescription *string + + // Resource ID. + ID *string + + // Indicates the properties of the security admin rule + Properties *AdminPropertiesFormat + + // Groups for rule collection + RuleCollectionAppliesToGroups []*ManagerSecurityGroupItem + + // A description of the rule collection. + RuleCollectionDescription *string + + // Effective configuration groups. + RuleGroups []*ConfigurationGroup +} + +// GetEffectiveBaseSecurityAdminRule implements the EffectiveBaseSecurityAdminRuleClassification interface for type EffectiveSecurityAdminRule. +func (e *EffectiveSecurityAdminRule) GetEffectiveBaseSecurityAdminRule() *EffectiveBaseSecurityAdminRule { + return &EffectiveBaseSecurityAdminRule{ + ConfigurationDescription: e.ConfigurationDescription, + ID: e.ID, + Kind: e.Kind, + RuleCollectionAppliesToGroups: e.RuleCollectionAppliesToGroups, + RuleCollectionDescription: e.RuleCollectionDescription, + RuleGroups: e.RuleGroups, + } +} + +// EndpointServiceResult - Endpoint service. +type EndpointServiceResult struct { + // Resource ID. + ID *string + + // READ-ONLY; Name of the endpoint service. + Name *string + + // READ-ONLY; Type of the endpoint service. + Type *string +} + +// EndpointServicesListResult - Response for the ListAvailableEndpointServices API service call. +type EndpointServicesListResult struct { + // The URL to get the next set of results. + NextLink *string + + // List of available endpoint services in a region. + Value []*EndpointServiceResult +} + +// Error - Common error representation. +type Error struct { + // Error code. + Code *string + + // Error details. + Details []*ErrorDetails + + // Inner error message. + InnerError *string + + // Error message. + Message *string + + // Error target. + Target *string +} + +// ErrorDetails - Common error details representation. +type ErrorDetails struct { + // Error code. + Code *string + + // Error message. + Message *string + + // Error target. + Target *string +} + +// ErrorResponse - The error object. +type ErrorResponse struct { + // The error details object. + Error *ErrorDetails +} + +// EvaluatedNetworkSecurityGroup - Results of network security group evaluation. +type EvaluatedNetworkSecurityGroup struct { + // Resource ID of nic or subnet to which network security group is applied. + AppliedTo *string + + // Matched network security rule. + MatchedRule *MatchedRule + + // Network security group ID. + NetworkSecurityGroupID *string + + // READ-ONLY; List of network security rules evaluation results. + RulesEvaluationResult []*SecurityRulesEvaluationResult +} + +// ExclusionManagedRule - Defines a managed rule to use for exclusion. +type ExclusionManagedRule struct { + // REQUIRED; Identifier for the managed rule. + RuleID *string +} + +// ExclusionManagedRuleGroup - Defines a managed rule group to use for exclusion. +type ExclusionManagedRuleGroup struct { + // REQUIRED; The managed rule group for exclusion. + RuleGroupName *string + + // List of rules that will be excluded. If none specified, all rules in the group will be excluded. + Rules []*ExclusionManagedRule +} + +// ExclusionManagedRuleSet - Defines a managed rule set for Exclusions. +type ExclusionManagedRuleSet struct { + // REQUIRED; Defines the rule set type to use. + RuleSetType *string + + // REQUIRED; Defines the version of the rule set to use. + RuleSetVersion *string + + // Defines the rule groups to apply to the rule set. + RuleGroups []*ExclusionManagedRuleGroup +} + +// ExplicitProxySettings - Explicit Proxy Settings in Firewall Policy. +type ExplicitProxySettings struct { + // When set to true, explicit proxy mode is enabled. + EnableExplicitProxy *bool + + // When set to true, pac file port and url needs to be provided. + EnablePacFile *bool + + // Port number for explicit proxy http protocol, cannot be greater than 64000. + HTTPPort *int32 + + // Port number for explicit proxy https protocol, cannot be greater than 64000. + HTTPSPort *int32 + + // SAS URL for PAC file. + PacFile *string + + // Port number for firewall to serve PAC file. + PacFilePort *int32 +} + +// ExpressRouteCircuit resource. +type ExpressRouteCircuit struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the express route circuit. + Properties *ExpressRouteCircuitPropertiesFormat + + // The SKU. + SKU *ExpressRouteCircuitSKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ExpressRouteCircuitArpTable - The ARP table associated with the ExpressRouteCircuit. +type ExpressRouteCircuitArpTable struct { + // Entry age in minutes. + Age *int32 + + // The IP address. + IPAddress *string + + // Interface address. + Interface *string + + // The MAC address. + MacAddress *string +} + +// ExpressRouteCircuitAuthorization - Authorization in an ExpressRouteCircuit resource. +type ExpressRouteCircuitAuthorization struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the express route circuit authorization. + Properties *AuthorizationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ExpressRouteCircuitConnection - Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. +type ExpressRouteCircuitConnection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the express route circuit connection. + Properties *ExpressRouteCircuitConnectionPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ExpressRouteCircuitConnectionListResult - Response for ListConnections API service call retrieves all global reach connections +// that belongs to a Private Peering for an ExpressRouteCircuit. +type ExpressRouteCircuitConnectionListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The global reach connection associated with Private Peering in an ExpressRoute Circuit. + Value []*ExpressRouteCircuitConnection +} + +// ExpressRouteCircuitConnectionPropertiesFormat - Properties of the express route circuit connection. +type ExpressRouteCircuitConnectionPropertiesFormat struct { + // /29 IP address space to carve out Customer addresses for tunnels. + AddressPrefix *string + + // The authorization key. + AuthorizationKey *string + + // Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection. + ExpressRouteCircuitPeering *SubResource + + // IPv6 Address PrefixProperties of the express route circuit connection. + IPv6CircuitConnectionConfig *IPv6CircuitConnectionConfig + + // Reference to Express Route Circuit Private Peering Resource of the peered circuit. + PeerExpressRouteCircuitPeering *SubResource + + // READ-ONLY; Express Route Circuit connection state. + CircuitConnectionStatus *CircuitConnectionStatus + + // READ-ONLY; The provisioning state of the express route circuit connection resource. + ProvisioningState *ProvisioningState +} + +// ExpressRouteCircuitListResult - Response for ListExpressRouteCircuit API service call. +type ExpressRouteCircuitListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of ExpressRouteCircuits in a resource group. + Value []*ExpressRouteCircuit +} + +// ExpressRouteCircuitPeering - Peering in an ExpressRouteCircuit resource. +type ExpressRouteCircuitPeering struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the express route circuit peering. + Properties *ExpressRouteCircuitPeeringPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ExpressRouteCircuitPeeringConfig - Specifies the peering configuration. +type ExpressRouteCircuitPeeringConfig struct { + // The communities of bgp peering. Specified for microsoft peering. + AdvertisedCommunities []*string + + // The reference to AdvertisedPublicPrefixes. + AdvertisedPublicPrefixes []*string + + // The CustomerASN of the peering. + CustomerASN *int32 + + // The legacy mode of the peering. + LegacyMode *int32 + + // The RoutingRegistryName of the configuration. + RoutingRegistryName *string + + // READ-ONLY; The advertised public prefix state of the Peering resource. + AdvertisedPublicPrefixesState *ExpressRouteCircuitPeeringAdvertisedPublicPrefixState +} + +// ExpressRouteCircuitPeeringID - ExpressRoute circuit peering identifier. +type ExpressRouteCircuitPeeringID struct { + // The ID of the ExpressRoute circuit peering. + ID *string +} + +// ExpressRouteCircuitPeeringListResult - Response for ListPeering API service call retrieves all peerings that belong to +// an ExpressRouteCircuit. +type ExpressRouteCircuitPeeringListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The peerings in an express route circuit. + Value []*ExpressRouteCircuitPeering +} + +// ExpressRouteCircuitPeeringPropertiesFormat - Properties of the express route circuit peering. +type ExpressRouteCircuitPeeringPropertiesFormat struct { + // The Azure ASN. + AzureASN *int32 + + // The list of circuit connections associated with Azure Private Peering for this circuit. + Connections []*ExpressRouteCircuitConnection + + // The ExpressRoute connection. + ExpressRouteConnection *ExpressRouteConnectionID + + // The GatewayManager Etag. + GatewayManagerEtag *string + + // The IPv6 peering configuration. + IPv6PeeringConfig *IPv6ExpressRouteCircuitPeeringConfig + + // The Microsoft peering configuration. + MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig + + // The peer ASN. + PeerASN *int64 + + // The peering type. + PeeringType *ExpressRoutePeeringType + + // The primary port. + PrimaryAzurePort *string + + // The primary address prefix. + PrimaryPeerAddressPrefix *string + + // The reference to the RouteFilter resource. + RouteFilter *SubResource + + // The secondary port. + SecondaryAzurePort *string + + // The secondary address prefix. + SecondaryPeerAddressPrefix *string + + // The shared key. + SharedKey *string + + // The peering state. + State *ExpressRoutePeeringState + + // The peering stats of express route circuit. + Stats *ExpressRouteCircuitStats + + // The VLAN ID. + VlanID *int32 + + // READ-ONLY; Who was the last to modify the peering. + LastModifiedBy *string + + // READ-ONLY; The list of peered circuit connections associated with Azure Private Peering for this circuit. + PeeredConnections []*PeerExpressRouteCircuitConnection + + // READ-ONLY; The provisioning state of the express route circuit peering resource. + ProvisioningState *ProvisioningState +} + +// ExpressRouteCircuitPropertiesFormat - Properties of ExpressRouteCircuit. +type ExpressRouteCircuitPropertiesFormat struct { + // Allow classic operations. + AllowClassicOperations *bool + + // The authorizationKey. + AuthorizationKey *string + + // The list of authorizations. + Authorizations []*ExpressRouteCircuitAuthorization + + // The bandwidth of the circuit when the circuit is provisioned on an ExpressRoutePort resource. + BandwidthInGbps *float32 + + // The CircuitProvisioningState state of the resource. + CircuitProvisioningState *string + + // The reference to the ExpressRoutePort resource when the circuit is provisioned on an ExpressRoutePort resource. + ExpressRoutePort *SubResource + + // The GatewayManager Etag. + GatewayManagerEtag *string + + // Flag denoting global reach status. + GlobalReachEnabled *bool + + // The list of peerings. + Peerings []*ExpressRouteCircuitPeering + + // The ServiceKey. + ServiceKey *string + + // The ServiceProviderNotes. + ServiceProviderNotes *string + + // The ServiceProviderProperties. + ServiceProviderProperties *ExpressRouteCircuitServiceProviderProperties + + // The ServiceProviderProvisioningState state of the resource. + ServiceProviderProvisioningState *ServiceProviderProvisioningState + + // READ-ONLY; The authorization status of the Circuit. + AuthorizationStatus *string + + // READ-ONLY; The provisioning state of the express route circuit resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The identifier of the circuit traffic. Outer tag for QinQ encapsulation. + Stag *int32 +} + +// ExpressRouteCircuitReference - Reference to an express route circuit. +type ExpressRouteCircuitReference struct { + // Corresponding Express Route Circuit Id. + ID *string +} + +// ExpressRouteCircuitRoutesTable - The routes table associated with the ExpressRouteCircuit. +type ExpressRouteCircuitRoutesTable struct { + // Local preference value as set with the set local-preference route-map configuration command. + LocPrf *string + + // IP address of a network entity. + Network *string + + // NextHop address. + NextHop *string + + // Autonomous system paths to the destination network. + Path *string + + // Route Weight. + Weight *int32 +} + +// ExpressRouteCircuitRoutesTableSummary - The routes table associated with the ExpressRouteCircuit. +type ExpressRouteCircuitRoutesTableSummary struct { + // Autonomous system number. + As *int32 + + // IP address of the neighbor. + Neighbor *string + + // Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. + StatePfxRcd *string + + // The length of time that the BGP session has been in the Established state, or the current status if not in the Established + // state. + UpDown *string + + // BGP version number spoken to the neighbor. + V *int32 +} + +// ExpressRouteCircuitSKU - Contains SKU in an ExpressRouteCircuit. +type ExpressRouteCircuitSKU struct { + // The family of the SKU. + Family *ExpressRouteCircuitSKUFamily + + // The name of the SKU. + Name *string + + // The tier of the SKU. + Tier *ExpressRouteCircuitSKUTier +} + +// ExpressRouteCircuitServiceProviderProperties - Contains ServiceProviderProperties in an ExpressRouteCircuit. +type ExpressRouteCircuitServiceProviderProperties struct { + // The BandwidthInMbps. + BandwidthInMbps *int32 + + // The peering location. + PeeringLocation *string + + // The serviceProviderName. + ServiceProviderName *string +} + +// ExpressRouteCircuitStats - Contains stats associated with the peering. +type ExpressRouteCircuitStats struct { + // The Primary BytesIn of the peering. + PrimarybytesIn *int64 + + // The primary BytesOut of the peering. + PrimarybytesOut *int64 + + // The secondary BytesIn of the peering. + SecondarybytesIn *int64 + + // The secondary BytesOut of the peering. + SecondarybytesOut *int64 +} + +// ExpressRouteCircuitsArpTableListResult - Response for ListArpTable associated with the Express Route Circuits API. +type ExpressRouteCircuitsArpTableListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of the ARP tables. + Value []*ExpressRouteCircuitArpTable +} + +// ExpressRouteCircuitsRoutesTableListResult - Response for ListRoutesTable associated with the Express Route Circuits API. +type ExpressRouteCircuitsRoutesTableListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of routes table. + Value []*ExpressRouteCircuitRoutesTable +} + +// ExpressRouteCircuitsRoutesTableSummaryListResult - Response for ListRoutesTable associated with the Express Route Circuits +// API. +type ExpressRouteCircuitsRoutesTableSummaryListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of the routes table. + Value []*ExpressRouteCircuitRoutesTableSummary +} + +// ExpressRouteConnection resource. +type ExpressRouteConnection struct { + // REQUIRED; The name of the resource. + Name *string + + // Resource ID. + ID *string + + // Properties of the express route connection. + Properties *ExpressRouteConnectionProperties +} + +// ExpressRouteConnectionID - The ID of the ExpressRouteConnection. +type ExpressRouteConnectionID struct { + // READ-ONLY; The ID of the ExpressRouteConnection. + ID *string +} + +// ExpressRouteConnectionList - ExpressRouteConnection list. +type ExpressRouteConnectionList struct { + // The list of ExpressRoute connections. + Value []*ExpressRouteConnection +} + +// ExpressRouteConnectionProperties - Properties of the ExpressRouteConnection subresource. +type ExpressRouteConnectionProperties struct { + // REQUIRED; The ExpressRoute circuit peering. + ExpressRouteCircuitPeering *ExpressRouteCircuitPeeringID + + // Authorization key to establish the connection. + AuthorizationKey *string + + // Enable internet security. + EnableInternetSecurity *bool + + // Bypass the ExpressRoute gateway when accessing private-links. ExpressRoute FastPath (expressRouteGatewayBypass) must be + // enabled. + EnablePrivateLinkFastPath *bool + + // Enable FastPath to vWan Firewall hub. + ExpressRouteGatewayBypass *bool + + // The Routing Configuration indicating the associated and propagated route tables on this connection. + RoutingConfiguration *RoutingConfiguration + + // The routing weight associated to the connection. + RoutingWeight *int32 + + // READ-ONLY; The provisioning state of the express route connection resource. + ProvisioningState *ProvisioningState +} + +// ExpressRouteCrossConnection resource. +type ExpressRouteCrossConnection struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the express route cross connection. + Properties *ExpressRouteCrossConnectionProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ExpressRouteCrossConnectionListResult - Response for ListExpressRouteCrossConnection API service call. +type ExpressRouteCrossConnectionListResult struct { + // A list of ExpressRouteCrossConnection resources. + Value []*ExpressRouteCrossConnection + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ExpressRouteCrossConnectionPeering - Peering in an ExpressRoute Cross Connection resource. +type ExpressRouteCrossConnectionPeering struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the express route cross connection peering. + Properties *ExpressRouteCrossConnectionPeeringProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// ExpressRouteCrossConnectionPeeringList - Response for ListPeering API service call retrieves all peerings that belong to +// an ExpressRouteCrossConnection. +type ExpressRouteCrossConnectionPeeringList struct { + // The peerings in an express route cross connection. + Value []*ExpressRouteCrossConnectionPeering + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ExpressRouteCrossConnectionPeeringProperties - Properties of express route cross connection peering. +type ExpressRouteCrossConnectionPeeringProperties struct { + // The GatewayManager Etag. + GatewayManagerEtag *string + + // The IPv6 peering configuration. + IPv6PeeringConfig *IPv6ExpressRouteCircuitPeeringConfig + + // The Microsoft peering configuration. + MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig + + // The peer ASN. + PeerASN *int64 + + // The peering type. + PeeringType *ExpressRoutePeeringType + + // The primary address prefix. + PrimaryPeerAddressPrefix *string + + // The secondary address prefix. + SecondaryPeerAddressPrefix *string + + // The shared key. + SharedKey *string + + // The peering state. + State *ExpressRoutePeeringState + + // The VLAN ID. + VlanID *int32 + + // READ-ONLY; The Azure ASN. + AzureASN *int32 + + // READ-ONLY; Who was the last to modify the peering. + LastModifiedBy *string + + // READ-ONLY; The primary port. + PrimaryAzurePort *string + + // READ-ONLY; The provisioning state of the express route cross connection peering resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The secondary port. + SecondaryAzurePort *string +} + +// ExpressRouteCrossConnectionProperties - Properties of ExpressRouteCrossConnection. +type ExpressRouteCrossConnectionProperties struct { + // The ExpressRouteCircuit. + ExpressRouteCircuit *ExpressRouteCircuitReference + + // The list of peerings. + Peerings []*ExpressRouteCrossConnectionPeering + + // Additional read only notes set by the connectivity provider. + ServiceProviderNotes *string + + // The provisioning state of the circuit in the connectivity provider system. + ServiceProviderProvisioningState *ServiceProviderProvisioningState + + // READ-ONLY; The circuit bandwidth In Mbps. + BandwidthInMbps *int32 + + // READ-ONLY; The peering location of the ExpressRoute circuit. + PeeringLocation *string + + // READ-ONLY; The name of the primary port. + PrimaryAzurePort *string + + // READ-ONLY; The provisioning state of the express route cross connection resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The identifier of the circuit traffic. + STag *int32 + + // READ-ONLY; The name of the secondary port. + SecondaryAzurePort *string +} + +// ExpressRouteCrossConnectionRoutesTableSummary - The routes table associated with the ExpressRouteCircuit. +type ExpressRouteCrossConnectionRoutesTableSummary struct { + // Autonomous system number. + Asn *int32 + + // IP address of Neighbor router. + Neighbor *string + + // Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. + StateOrPrefixesReceived *string + + // The length of time that the BGP session has been in the Established state, or the current status if not in the Established + // state. + UpDown *string +} + +// ExpressRouteCrossConnectionsRoutesTableSummaryListResult - Response for ListRoutesTable associated with the Express Route +// Cross Connections. +type ExpressRouteCrossConnectionsRoutesTableSummaryListResult struct { + // A list of the routes table. + Value []*ExpressRouteCrossConnectionRoutesTableSummary + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ExpressRouteGateway - ExpressRoute gateway resource. +type ExpressRouteGateway struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the express route gateway. + Properties *ExpressRouteGatewayProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ExpressRouteGatewayList - List of ExpressRoute gateways. +type ExpressRouteGatewayList struct { + // List of ExpressRoute gateways. + Value []*ExpressRouteGateway +} + +// ExpressRouteGatewayProperties - ExpressRoute gateway resource properties. +type ExpressRouteGatewayProperties struct { + // REQUIRED; The Virtual Hub where the ExpressRoute gateway is or will be deployed. + VirtualHub *VirtualHubID + + // Configures this gateway to accept traffic from non Virtual WAN networks. + AllowNonVirtualWanTraffic *bool + + // Configuration for auto scaling. + AutoScaleConfiguration *ExpressRouteGatewayPropertiesAutoScaleConfiguration + + // List of ExpressRoute connections to the ExpressRoute gateway. + ExpressRouteConnections []*ExpressRouteConnection + + // READ-ONLY; The provisioning state of the express route gateway resource. + ProvisioningState *ProvisioningState +} + +// ExpressRouteGatewayPropertiesAutoScaleConfiguration - Configuration for auto scaling. +type ExpressRouteGatewayPropertiesAutoScaleConfiguration struct { + // Minimum and maximum number of scale units to deploy. + Bounds *ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds +} + +// ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds - Minimum and maximum number of scale units to deploy. +type ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds struct { + // Maximum number of scale units deployed for ExpressRoute gateway. + Max *int32 + + // Minimum number of scale units deployed for ExpressRoute gateway. + Min *int32 +} + +// ExpressRouteLink child resource definition. +type ExpressRouteLink struct { + // Resource ID. + ID *string + + // Name of child port resource that is unique among child port resources of the parent. + Name *string + + // ExpressRouteLink properties. + Properties *ExpressRouteLinkPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// ExpressRouteLinkListResult - Response for ListExpressRouteLinks API service call. +type ExpressRouteLinkListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of ExpressRouteLink sub-resources. + Value []*ExpressRouteLink +} + +// ExpressRouteLinkMacSecConfig - ExpressRouteLink Mac Security Configuration. +type ExpressRouteLinkMacSecConfig struct { + // Keyvault Secret Identifier URL containing Mac security CAK key. + CakSecretIdentifier *string + + // Mac security cipher. + Cipher *ExpressRouteLinkMacSecCipher + + // Keyvault Secret Identifier URL containing Mac security CKN key. + CknSecretIdentifier *string + + // Sci mode enabled/disabled. + SciState *ExpressRouteLinkMacSecSciState +} + +// ExpressRouteLinkPropertiesFormat - Properties specific to ExpressRouteLink resources. +type ExpressRouteLinkPropertiesFormat struct { + // Administrative state of the physical port. + AdminState *ExpressRouteLinkAdminState + + // MacSec configuration. + MacSecConfig *ExpressRouteLinkMacSecConfig + + // READ-ONLY; Cololocation for ExpressRoute Hybrid Direct. + ColoLocation *string + + // READ-ONLY; Physical fiber port type. + ConnectorType *ExpressRouteLinkConnectorType + + // READ-ONLY; Name of Azure router interface. + InterfaceName *string + + // READ-ONLY; Mapping between physical port to patch panel port. + PatchPanelID *string + + // READ-ONLY; The provisioning state of the express route link resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Mapping of physical patch panel to rack. + RackID *string + + // READ-ONLY; Name of Azure router associated with physical port. + RouterName *string +} + +// ExpressRoutePort resource definition. +type ExpressRoutePort struct { + // Resource ID. + ID *string + + // The identity of ExpressRoutePort, if configured. + Identity *ManagedServiceIdentity + + // Resource location. + Location *string + + // ExpressRoutePort properties. + Properties *ExpressRoutePortPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ExpressRoutePortAuthorization - ExpressRoutePort Authorization resource definition. +type ExpressRoutePortAuthorization struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // ExpressRoutePort properties. + Properties *ExpressRoutePortAuthorizationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ExpressRoutePortAuthorizationListResult - Response for ListExpressRoutePortAuthorizations API service call. +type ExpressRoutePortAuthorizationListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The authorizations in an ExpressRoute Port. + Value []*ExpressRoutePortAuthorization +} + +// ExpressRoutePortAuthorizationPropertiesFormat - Properties of ExpressRoutePort Authorization. +type ExpressRoutePortAuthorizationPropertiesFormat struct { + // READ-ONLY; The authorization key. + AuthorizationKey *string + + // READ-ONLY; The authorization use status. + AuthorizationUseStatus *ExpressRoutePortAuthorizationUseStatus + + // READ-ONLY; The reference to the ExpressRoute circuit resource using the authorization. + CircuitResourceURI *string + + // READ-ONLY; The provisioning state of the authorization resource. + ProvisioningState *ProvisioningState +} + +// ExpressRoutePortListResult - Response for ListExpressRoutePorts API service call. +type ExpressRoutePortListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of ExpressRoutePort resources. + Value []*ExpressRoutePort +} + +// ExpressRoutePortPropertiesFormat - Properties specific to ExpressRoutePort resources. +type ExpressRoutePortPropertiesFormat struct { + // Bandwidth of procured ports in Gbps. + BandwidthInGbps *int32 + + // The billing type of the ExpressRoutePort resource. + BillingType *ExpressRoutePortsBillingType + + // Encapsulation method on physical ports. + Encapsulation *ExpressRoutePortsEncapsulation + + // The set of physical links of the ExpressRoutePort resource. + Links []*ExpressRouteLink + + // The name of the peering location that the ExpressRoutePort is mapped to physically. + PeeringLocation *string + + // READ-ONLY; Date of the physical port allocation to be used in Letter of Authorization. + AllocationDate *string + + // READ-ONLY; Reference the ExpressRoute circuit(s) that are provisioned on this ExpressRoutePort resource. + Circuits []*SubResource + + // READ-ONLY; Ether type of the physical port. + EtherType *string + + // READ-ONLY; Maximum transmission unit of the physical port pair(s). + Mtu *string + + // READ-ONLY; Aggregate Gbps of associated circuit bandwidths. + ProvisionedBandwidthInGbps *float32 + + // READ-ONLY; The provisioning state of the express route port resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the express route port resource. + ResourceGUID *string +} + +// ExpressRoutePortsLocation - Definition of the ExpressRoutePorts peering location resource. +type ExpressRoutePortsLocation struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // ExpressRoutePort peering location properties. + Properties *ExpressRoutePortsLocationPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ExpressRoutePortsLocationBandwidths - Real-time inventory of available ExpressRoute port bandwidths. +type ExpressRoutePortsLocationBandwidths struct { + // READ-ONLY; Bandwidth descriptive name. + OfferName *string + + // READ-ONLY; Bandwidth value in Gbps. + ValueInGbps *int32 +} + +// ExpressRoutePortsLocationListResult - Response for ListExpressRoutePortsLocations API service call. +type ExpressRoutePortsLocationListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The list of all ExpressRoutePort peering locations. + Value []*ExpressRoutePortsLocation +} + +// ExpressRoutePortsLocationPropertiesFormat - Properties specific to ExpressRoutePorts peering location resources. +type ExpressRoutePortsLocationPropertiesFormat struct { + // The inventory of available ExpressRoutePort bandwidths. + AvailableBandwidths []*ExpressRoutePortsLocationBandwidths + + // READ-ONLY; Address of peering location. + Address *string + + // READ-ONLY; Contact details of peering locations. + Contact *string + + // READ-ONLY; The provisioning state of the express route port location resource. + ProvisioningState *ProvisioningState +} + +// ExpressRouteProviderPort resource. +type ExpressRouteProviderPort struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the express route Service Provider Port. + Properties *ExpressRouteProviderPortProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ExpressRouteProviderPortListResult - Response for ListExpressRouteProviderPort API service call. +type ExpressRouteProviderPortListResult struct { + // A list of ExpressRouteProviderPort resources. + Value []*ExpressRouteProviderPort + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ExpressRouteProviderPortProperties - Properties of ExpressRouteProviderPort. +type ExpressRouteProviderPortProperties struct { + // Overprovisioning factor for the port pair. + OverprovisionFactor *int32 + + // The peering location of the port pair. + PeeringLocation *string + + // Bandwidth of the port in Mbps + PortBandwidthInMbps *int32 + + // Remaining Bandwidth of the port in Mbps + RemainingBandwidthInMbps *int32 + + // Used Bandwidth of the port in Mbps + UsedBandwidthInMbps *int32 + + // READ-ONLY; The name of the port pair. + PortPairDescriptor *string + + // READ-ONLY; The name of the primary port. + PrimaryAzurePort *string + + // READ-ONLY; The name of the secondary port. + SecondaryAzurePort *string +} + +// ExpressRouteServiceProvider - A ExpressRouteResourceProvider object. +type ExpressRouteServiceProvider struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the express route service provider. + Properties *ExpressRouteServiceProviderPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ExpressRouteServiceProviderBandwidthsOffered - Contains bandwidths offered in ExpressRouteServiceProvider resources. +type ExpressRouteServiceProviderBandwidthsOffered struct { + // The OfferName. + OfferName *string + + // The ValueInMbps. + ValueInMbps *int32 +} + +// ExpressRouteServiceProviderListResult - Response for the ListExpressRouteServiceProvider API service call. +type ExpressRouteServiceProviderListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of ExpressRouteResourceProvider resources. + Value []*ExpressRouteServiceProvider +} + +// ExpressRouteServiceProviderPropertiesFormat - Properties of ExpressRouteServiceProvider. +type ExpressRouteServiceProviderPropertiesFormat struct { + // A list of bandwidths offered. + BandwidthsOffered []*ExpressRouteServiceProviderBandwidthsOffered + + // A list of peering locations. + PeeringLocations []*string + + // READ-ONLY; The provisioning state of the express route service provider resource. + ProvisioningState *ProvisioningState +} + +// ExtendedLocation complex type. +type ExtendedLocation struct { + // The name of the extended location. + Name *string + + // The type of the extended location. + Type *ExtendedLocationTypes +} + +// FilterItems - Will contain the filter name and values to operate on +type FilterItems struct { + // The name of the field we would like to filter + Field *string + + // List of values to filter the current field by + Values []*string +} + +// FirewallPacketCaptureParameters - Azure Firewall Packet Capture Parameters resource. +type FirewallPacketCaptureParameters struct { + // Resource ID. + ID *string + + // Properties of the azure firewall. + Properties *FirewallPacketCaptureParametersFormat +} + +// FirewallPacketCaptureParametersFormat - Packet capture parameters on azure firewall. +type FirewallPacketCaptureParametersFormat struct { + // Duration of packet capture in seconds. + DurationInSeconds *int32 + + // Name of file to be uploaded to sasURL + FileName *string + + // Rules to filter packet captures. + Filters []*AzureFirewallPacketCaptureRule + + // The tcp-flag type to be captured. Used with protocol TCP + Flags []*AzureFirewallPacketCaptureFlags + + // Number of packets to be captured. + NumberOfPacketsToCapture *int32 + + // The protocol of packets to capture + Protocol *AzureFirewallNetworkRuleProtocol + + // Upload capture location + SasURL *string +} + +// FirewallPolicy Resource. +type FirewallPolicy struct { + // Resource ID. + ID *string + + // The identity of the firewall policy. + Identity *ManagedServiceIdentity + + // Resource location. + Location *string + + // Properties of the firewall policy. + Properties *FirewallPolicyPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// FirewallPolicyCertificateAuthority - Trusted Root certificates properties for tls. +type FirewallPolicyCertificateAuthority struct { + // Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. + KeyVaultSecretID *string + + // Name of the CA certificate. + Name *string +} + +// FirewallPolicyFilterRuleCollection - Firewall Policy Filter Rule Collection. +type FirewallPolicyFilterRuleCollection struct { + // REQUIRED; The type of the rule collection. + RuleCollectionType *FirewallPolicyRuleCollectionType + + // The action type of a Filter rule collection. + Action *FirewallPolicyFilterRuleCollectionAction + + // The name of the rule collection. + Name *string + + // Priority of the Firewall Policy Rule Collection resource. + Priority *int32 + + // List of rules included in a rule collection. + Rules []FirewallPolicyRuleClassification +} + +// GetFirewallPolicyRuleCollection implements the FirewallPolicyRuleCollectionClassification interface for type FirewallPolicyFilterRuleCollection. +func (f *FirewallPolicyFilterRuleCollection) GetFirewallPolicyRuleCollection() *FirewallPolicyRuleCollection { + return &FirewallPolicyRuleCollection{ + Name: f.Name, + Priority: f.Priority, + RuleCollectionType: f.RuleCollectionType, + } +} + +// FirewallPolicyFilterRuleCollectionAction - Properties of the FirewallPolicyFilterRuleCollectionAction. +type FirewallPolicyFilterRuleCollectionAction struct { + // The type of action. + Type *FirewallPolicyFilterRuleCollectionActionType +} + +// FirewallPolicyHTTPHeaderToInsert - name and value of HTTP/S header to insert +type FirewallPolicyHTTPHeaderToInsert struct { + // Contains the name of the header + HeaderName *string + + // Contains the value of the header + HeaderValue *string +} + +// FirewallPolicyInsights - Firewall Policy Insights. +type FirewallPolicyInsights struct { + // A flag to indicate if the insights are enabled on the policy. + IsEnabled *bool + + // Workspaces needed to configure the Firewall Policy Insights. + LogAnalyticsResources *FirewallPolicyLogAnalyticsResources + + // Number of days the insights should be enabled on the policy. + RetentionDays *int32 +} + +// FirewallPolicyIntrusionDetection - Configuration for intrusion detection mode and rules. +type FirewallPolicyIntrusionDetection struct { + // Intrusion detection configuration properties. + Configuration *FirewallPolicyIntrusionDetectionConfiguration + + // Intrusion detection general state. + Mode *FirewallPolicyIntrusionDetectionStateType +} + +// FirewallPolicyIntrusionDetectionBypassTrafficSpecifications - Intrusion detection bypass traffic specification. +type FirewallPolicyIntrusionDetectionBypassTrafficSpecifications struct { + // Description of the bypass traffic rule. + Description *string + + // List of destination IP addresses or ranges for this rule. + DestinationAddresses []*string + + // List of destination IpGroups for this rule. + DestinationIPGroups []*string + + // List of destination ports or ranges. + DestinationPorts []*string + + // Name of the bypass traffic rule. + Name *string + + // The rule bypass protocol. + Protocol *FirewallPolicyIntrusionDetectionProtocol + + // List of source IP addresses or ranges for this rule. + SourceAddresses []*string + + // List of source IpGroups for this rule. + SourceIPGroups []*string +} + +// FirewallPolicyIntrusionDetectionConfiguration - The operation for configuring intrusion detection. +type FirewallPolicyIntrusionDetectionConfiguration struct { + // List of rules for traffic to bypass. + BypassTrafficSettings []*FirewallPolicyIntrusionDetectionBypassTrafficSpecifications + + // IDPS Private IP address ranges are used to identify traffic direction (i.e. inbound, outbound, etc.). By default, only + // ranges defined by IANA RFC 1918 are considered private IP addresses. To modify + // default ranges, specify your Private IP address ranges with this property + PrivateRanges []*string + + // List of specific signatures states. + SignatureOverrides []*FirewallPolicyIntrusionDetectionSignatureSpecification +} + +// FirewallPolicyIntrusionDetectionSignatureSpecification - Intrusion detection signatures specification states. +type FirewallPolicyIntrusionDetectionSignatureSpecification struct { + // Signature id. + ID *string + + // The signature state. + Mode *FirewallPolicyIntrusionDetectionStateType +} + +// FirewallPolicyListResult - Response for ListFirewallPolicies API service call. +type FirewallPolicyListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Firewall Policies in a resource group. + Value []*FirewallPolicy +} + +// FirewallPolicyLogAnalyticsResources - Log Analytics Resources for Firewall Policy Insights. +type FirewallPolicyLogAnalyticsResources struct { + // The default workspace Id for Firewall Policy Insights. + DefaultWorkspaceID *SubResource + + // List of workspaces for Firewall Policy Insights. + Workspaces []*FirewallPolicyLogAnalyticsWorkspace +} + +// FirewallPolicyLogAnalyticsWorkspace - Log Analytics Workspace for Firewall Policy Insights. +type FirewallPolicyLogAnalyticsWorkspace struct { + // Region to configure the Workspace. + Region *string + + // The workspace Id for Firewall Policy Insights. + WorkspaceID *SubResource +} + +// FirewallPolicyNatRuleCollection - Firewall Policy NAT Rule Collection. +type FirewallPolicyNatRuleCollection struct { + // REQUIRED; The type of the rule collection. + RuleCollectionType *FirewallPolicyRuleCollectionType + + // The action type of a Nat rule collection. + Action *FirewallPolicyNatRuleCollectionAction + + // The name of the rule collection. + Name *string + + // Priority of the Firewall Policy Rule Collection resource. + Priority *int32 + + // List of rules included in a rule collection. + Rules []FirewallPolicyRuleClassification +} + +// GetFirewallPolicyRuleCollection implements the FirewallPolicyRuleCollectionClassification interface for type FirewallPolicyNatRuleCollection. +func (f *FirewallPolicyNatRuleCollection) GetFirewallPolicyRuleCollection() *FirewallPolicyRuleCollection { + return &FirewallPolicyRuleCollection{ + Name: f.Name, + Priority: f.Priority, + RuleCollectionType: f.RuleCollectionType, + } +} + +// FirewallPolicyNatRuleCollectionAction - Properties of the FirewallPolicyNatRuleCollectionAction. +type FirewallPolicyNatRuleCollectionAction struct { + // The type of action. + Type *FirewallPolicyNatRuleCollectionActionType +} + +// FirewallPolicyPropertiesFormat - Firewall Policy definition. +type FirewallPolicyPropertiesFormat struct { + // The parent firewall policy from which rules are inherited. + BasePolicy *SubResource + + // DNS Proxy Settings definition. + DNSSettings *DNSSettings + + // Explicit Proxy Settings definition. + ExplicitProxySettings *ExplicitProxySettings + + // Insights on Firewall Policy. + Insights *FirewallPolicyInsights + + // The configuration for Intrusion detection. + IntrusionDetection *FirewallPolicyIntrusionDetection + + // The Firewall Policy SKU. + SKU *FirewallPolicySKU + + // SQL Settings definition. + SQL *FirewallPolicySQL + + // The private IP addresses/IP ranges to which traffic will not be SNAT. + Snat *FirewallPolicySNAT + + // The operation mode for Threat Intelligence. + ThreatIntelMode *AzureFirewallThreatIntelMode + + // ThreatIntel Whitelist for Firewall Policy. + ThreatIntelWhitelist *FirewallPolicyThreatIntelWhitelist + + // TLS Configuration definition. + TransportSecurity *FirewallPolicyTransportSecurity + + // READ-ONLY; List of references to Child Firewall Policies. + ChildPolicies []*SubResource + + // READ-ONLY; List of references to Azure Firewalls that this Firewall Policy is associated with. + Firewalls []*SubResource + + // READ-ONLY; The provisioning state of the firewall policy resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; List of references to FirewallPolicyRuleCollectionGroups. + RuleCollectionGroups []*SubResource + + // READ-ONLY; A read-only string that represents the size of the FirewallPolicyPropertiesFormat in MB. (ex 0.5MB) + Size *string +} + +// FirewallPolicyRule - Properties of a rule. +type FirewallPolicyRule struct { + // REQUIRED; Rule Type. + RuleType *FirewallPolicyRuleType + + // Description of the rule. + Description *string + + // Name of the rule. + Name *string +} + +// GetFirewallPolicyRule implements the FirewallPolicyRuleClassification interface for type FirewallPolicyRule. +func (f *FirewallPolicyRule) GetFirewallPolicyRule() *FirewallPolicyRule { return f } + +// FirewallPolicyRuleApplicationProtocol - Properties of the application rule protocol. +type FirewallPolicyRuleApplicationProtocol struct { + // Port number for the protocol, cannot be greater than 64000. + Port *int32 + + // Protocol type. + ProtocolType *FirewallPolicyRuleApplicationProtocolType +} + +// FirewallPolicyRuleCollection - Properties of the rule collection. +type FirewallPolicyRuleCollection struct { + // REQUIRED; The type of the rule collection. + RuleCollectionType *FirewallPolicyRuleCollectionType + + // The name of the rule collection. + Name *string + + // Priority of the Firewall Policy Rule Collection resource. + Priority *int32 +} + +// GetFirewallPolicyRuleCollection implements the FirewallPolicyRuleCollectionClassification interface for type FirewallPolicyRuleCollection. +func (f *FirewallPolicyRuleCollection) GetFirewallPolicyRuleCollection() *FirewallPolicyRuleCollection { + return f +} + +// FirewallPolicyRuleCollectionGroup - Rule Collection Group resource. +type FirewallPolicyRuleCollectionGroup struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // The properties of the firewall policy rule collection group. + Properties *FirewallPolicyRuleCollectionGroupProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Rule Group type. + Type *string +} + +// FirewallPolicyRuleCollectionGroupListResult - Response for ListFirewallPolicyRuleCollectionGroups API service call. +type FirewallPolicyRuleCollectionGroupListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of FirewallPolicyRuleCollectionGroups in a FirewallPolicy. + Value []*FirewallPolicyRuleCollectionGroup +} + +// FirewallPolicyRuleCollectionGroupProperties - Properties of the rule collection group. +type FirewallPolicyRuleCollectionGroupProperties struct { + // Priority of the Firewall Policy Rule Collection Group resource. + Priority *int32 + + // Group of Firewall Policy rule collections. + RuleCollections []FirewallPolicyRuleCollectionClassification + + // READ-ONLY; The provisioning state of the firewall policy rule collection group resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; A read-only string that represents the size of the FirewallPolicyRuleCollectionGroupProperties in MB. (ex 1.2MB) + Size *string +} + +// FirewallPolicySKU - SKU of Firewall policy. +type FirewallPolicySKU struct { + // Tier of Firewall Policy. + Tier *FirewallPolicySKUTier +} + +// FirewallPolicySNAT - The private IP addresses/IP ranges to which traffic will not be SNAT. +type FirewallPolicySNAT struct { + // The operation mode for automatically learning private ranges to not be SNAT + AutoLearnPrivateRanges *AutoLearnPrivateRangesMode + + // List of private IP addresses/IP address ranges to not be SNAT. + PrivateRanges []*string +} + +// FirewallPolicySQL - SQL Settings in Firewall Policy. +type FirewallPolicySQL struct { + // A flag to indicate if SQL Redirect traffic filtering is enabled. Turning on the flag requires no rule using port 11000-11999. + AllowSQLRedirect *bool +} + +// FirewallPolicyThreatIntelWhitelist - ThreatIntel Whitelist for Firewall Policy. +type FirewallPolicyThreatIntelWhitelist struct { + // List of FQDNs for the ThreatIntel Whitelist. + Fqdns []*string + + // List of IP addresses for the ThreatIntel Whitelist. + IPAddresses []*string +} + +// FirewallPolicyTransportSecurity - Configuration needed to perform TLS termination & initiation. +type FirewallPolicyTransportSecurity struct { + // The CA used for intermediate CA generation. + CertificateAuthority *FirewallPolicyCertificateAuthority +} + +// FlowLog - A flow log resource. +type FlowLog struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the flow log. + Properties *FlowLogPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// FlowLogFormatParameters - Parameters that define the flow log format. +type FlowLogFormatParameters struct { + // The file type of flow log. + Type *FlowLogFormatType + + // The version (revision) of the flow log. + Version *int32 +} + +// FlowLogInformation - Information on the configuration of flow log and traffic analytics (optional) . +type FlowLogInformation struct { + // REQUIRED; Properties of the flow log. + Properties *FlowLogProperties + + // REQUIRED; The ID of the resource to configure for flow log and traffic analytics (optional) . + TargetResourceID *string + + // Parameters that define the configuration of traffic analytics. + FlowAnalyticsConfiguration *TrafficAnalyticsProperties +} + +// FlowLogListResult - List of flow logs. +type FlowLogListResult struct { + // Information about flow log resource. + Value []*FlowLog + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// FlowLogProperties - Parameters that define the configuration of flow log. +type FlowLogProperties struct { + // REQUIRED; Flag to enable/disable flow logging. + Enabled *bool + + // REQUIRED; ID of the storage account which is used to store the flow log. + StorageID *string + + // Parameters that define the flow log format. + Format *FlowLogFormatParameters + + // Parameters that define the retention policy for flow log. + RetentionPolicy *RetentionPolicyParameters +} + +// FlowLogPropertiesFormat - Parameters that define the configuration of flow log. +type FlowLogPropertiesFormat struct { + // REQUIRED; ID of the storage account which is used to store the flow log. + StorageID *string + + // REQUIRED; ID of network security group to which flow log will be applied. + TargetResourceID *string + + // Flag to enable/disable flow logging. + Enabled *bool + + // Parameters that define the configuration of traffic analytics. + FlowAnalyticsConfiguration *TrafficAnalyticsProperties + + // Parameters that define the flow log format. + Format *FlowLogFormatParameters + + // Parameters that define the retention policy for flow log. + RetentionPolicy *RetentionPolicyParameters + + // READ-ONLY; The provisioning state of the flow log. + ProvisioningState *ProvisioningState + + // READ-ONLY; Guid of network security group to which flow log will be applied. + TargetResourceGUID *string +} + +// FlowLogStatusParameters - Parameters that define a resource to query flow log and traffic analytics (optional) status. +type FlowLogStatusParameters struct { + // REQUIRED; The target resource where getting the flow log and traffic analytics (optional) status. + TargetResourceID *string +} + +// FrontendIPConfiguration - Frontend IP address of the load balancer. +type FrontendIPConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the set of frontend IP configurations used by the load balancer. This name + // can be used to access the resource. + Name *string + + // Properties of the load balancer probe. + Properties *FrontendIPConfigurationPropertiesFormat + + // A list of availability zones denoting the IP allocated for the resource needs to come from. + Zones []*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// FrontendIPConfigurationPropertiesFormat - Properties of Frontend IP Configuration of the load balancer. +type FrontendIPConfigurationPropertiesFormat struct { + // The reference to gateway load balancer frontend IP. + GatewayLoadBalancer *SubResource + + // The private IP address of the IP configuration. + PrivateIPAddress *string + + // Whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. + PrivateIPAddressVersion *IPVersion + + // The Private IP allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // The reference to the Public IP resource. + PublicIPAddress *PublicIPAddress + + // The reference to the Public IP Prefix resource. + PublicIPPrefix *SubResource + + // The reference to the subnet resource. + Subnet *Subnet + + // READ-ONLY; An array of references to inbound pools that use this frontend IP. + InboundNatPools []*SubResource + + // READ-ONLY; An array of references to inbound rules that use this frontend IP. + InboundNatRules []*SubResource + + // READ-ONLY; An array of references to load balancing rules that use this frontend IP. + LoadBalancingRules []*SubResource + + // READ-ONLY; An array of references to outbound rules that use this frontend IP. + OutboundRules []*SubResource + + // READ-ONLY; The provisioning state of the frontend IP configuration resource. + ProvisioningState *ProvisioningState +} + +// GatewayCustomBgpIPAddressIPConfiguration - GatewayCustomBgpIpAddressIpConfiguration for a virtual network gateway connection. +type GatewayCustomBgpIPAddressIPConfiguration struct { + // REQUIRED; The custom BgpPeeringAddress which belongs to IpconfigurationId. + CustomBgpIPAddress *string + + // REQUIRED; The IpconfigurationId of ipconfiguration which belongs to gateway. + IPConfigurationID *string +} + +// GatewayLoadBalancerTunnelInterface - Gateway load balancer tunnel interface of a load balancer backend address pool. +type GatewayLoadBalancerTunnelInterface struct { + // Identifier of gateway load balancer tunnel interface. + Identifier *int32 + + // Port of gateway load balancer tunnel interface. + Port *int32 + + // Protocol of gateway load balancer tunnel interface. + Protocol *GatewayLoadBalancerTunnelProtocol + + // Traffic type of gateway load balancer tunnel interface. + Type *GatewayLoadBalancerTunnelInterfaceType +} + +// GatewayRoute - Gateway routing details. +type GatewayRoute struct { + // READ-ONLY; The route's AS path sequence. + AsPath *string + + // READ-ONLY; The gateway's local address. + LocalAddress *string + + // READ-ONLY; The route's network prefix. + Network *string + + // READ-ONLY; The route's next hop. + NextHop *string + + // READ-ONLY; The source this route was learned from. + Origin *string + + // READ-ONLY; The peer this route was learned from. + SourcePeer *string + + // READ-ONLY; The route's weight. + Weight *int32 +} + +// GatewayRouteListResult - List of virtual network gateway routes. +type GatewayRouteListResult struct { + // List of gateway routes. + Value []*GatewayRoute +} + +// GenerateExpressRoutePortsLOARequest - The customer name to be printed on a letter of authorization. +type GenerateExpressRoutePortsLOARequest struct { + // REQUIRED; The customer name. + CustomerName *string +} + +// GenerateExpressRoutePortsLOAResult - Response for GenerateExpressRoutePortsLOA API service call. +type GenerateExpressRoutePortsLOAResult struct { + // The content as a base64 encoded string. + EncodedContent *string +} + +// GetInboundRoutesParameters - The parameters specifying the connection resource whose inbound routes are being requested. +type GetInboundRoutesParameters struct { + // The type of the specified connection resource like ExpressRouteConnection, HubVirtualNetworkConnection, VpnConnection and + // P2SConnection. + ConnectionType *string + + // The connection resource whose inbound routes are being requested. + ResourceURI *string +} + +// GetOutboundRoutesParameters - The parameters specifying the connection resource whose outbound routes are being requested. +type GetOutboundRoutesParameters struct { + // The type of the specified connection resource like ExpressRouteConnection, HubVirtualNetworkConnection, VpnConnection and + // P2SConnection. + ConnectionType *string + + // The connection resource whose outbound routes are being requested. + ResourceURI *string +} + +// GetVPNSitesConfigurationRequest - List of Vpn-Sites. +type GetVPNSitesConfigurationRequest struct { + // REQUIRED; The sas-url to download the configurations for vpn-sites. + OutputBlobSasURL *string + + // List of resource-ids of the vpn-sites for which config is to be downloaded. + VPNSites []*string +} + +// Group - The network group resource +type Group struct { + // The Network Group properties + Properties *GroupProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// GroupByUserSession - Define user session identifier group by clauses. +type GroupByUserSession struct { + // REQUIRED; List of group by clause variables. + GroupByVariables []*GroupByVariable +} + +// GroupByVariable - Define user session group by clause variables. +type GroupByVariable struct { + // REQUIRED; User Session clause variable. + VariableName *ApplicationGatewayFirewallUserSessionVariable +} + +// GroupListResult - Result of the request to list NetworkGroup. It contains a list of groups and a URL link to get the next +// set of results. +type GroupListResult struct { + // Gets the URL to get the next set of results. + NextLink *string + + // Gets a page of NetworkGroup + Value []*Group +} + +// GroupProperties - Properties of network group +type GroupProperties struct { + // A description of the network group. + Description *string + + // READ-ONLY; The provisioning state of the scope assignment resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Unique identifier for this resource. + ResourceGUID *string +} + +// HTTPConfiguration - HTTP configuration of the connectivity check. +type HTTPConfiguration struct { + // List of HTTP headers. + Headers []*HTTPHeader + + // HTTP method. + Method *HTTPMethod + + // Valid status codes. + ValidStatusCodes []*int32 +} + +// HTTPHeader - The HTTP header. +type HTTPHeader struct { + // The name in HTTP header. + Name *string + + // The value in HTTP header. + Value *string +} + +// HopLink - Hop link. +type HopLink struct { + // Hop link properties. + Properties *HopLinkProperties + + // READ-ONLY; Provides additional context on links. + Context map[string]*string + + // READ-ONLY; List of issues. + Issues []*ConnectivityIssue + + // READ-ONLY; Link type. + LinkType *string + + // READ-ONLY; The ID of the next hop. + NextHopID *string + + // READ-ONLY; Resource ID. + ResourceID *string +} + +// HopLinkProperties - Hop link properties. +type HopLinkProperties struct { + // READ-ONLY; Average roundtrip time in milliseconds. + RoundTripTimeAvg *int64 + + // READ-ONLY; Maximum roundtrip time in milliseconds. + RoundTripTimeMax *int64 + + // READ-ONLY; Minimum roundtrip time in milliseconds. + RoundTripTimeMin *int64 +} + +// Hub Item. +type Hub struct { + // Resource Id. + ResourceID *string + + // Resource Type. + ResourceType *string +} + +// HubIPAddresses - IP addresses associated with azure firewall. +type HubIPAddresses struct { + // Private IP Address associated with azure firewall. + PrivateIPAddress *string + + // Public IP addresses associated with azure firewall. + PublicIPs *HubPublicIPAddresses +} + +// HubIPConfiguration - IpConfigurations. +type HubIPConfiguration struct { + // Resource ID. + ID *string + + // Name of the Ip Configuration. + Name *string + + // The properties of the Virtual Hub IPConfigurations. + Properties *HubIPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Ipconfiguration type. + Type *string +} + +// HubIPConfigurationPropertiesFormat - Properties of IP configuration. +type HubIPConfigurationPropertiesFormat struct { + // The private IP address of the IP configuration. + PrivateIPAddress *string + + // The private IP address allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // The reference to the public IP resource. + PublicIPAddress *PublicIPAddress + + // The reference to the subnet resource. + Subnet *Subnet + + // READ-ONLY; The provisioning state of the IP configuration resource. + ProvisioningState *ProvisioningState +} + +// HubPublicIPAddresses - Public IP addresses associated with azure firewall. +type HubPublicIPAddresses struct { + // The list of Public IP addresses associated with azure firewall or IP addresses to be retained. + Addresses []*AzureFirewallPublicIPAddress + + // The number of Public IP addresses associated with azure firewall. + Count *int32 +} + +// HubRoute - RouteTable route. +type HubRoute struct { + // REQUIRED; The type of destinations (eg: CIDR, ResourceId, Service). + DestinationType *string + + // REQUIRED; List of all destinations. + Destinations []*string + + // REQUIRED; The name of the Route that is unique within a RouteTable. This name can be used to access this route. + Name *string + + // REQUIRED; NextHop resource ID. + NextHop *string + + // REQUIRED; The type of next hop (eg: ResourceId). + NextHopType *string +} + +// HubRouteTable - RouteTable resource in a virtual hub. +type HubRouteTable struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the RouteTable resource. + Properties *HubRouteTableProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// HubRouteTableProperties - Parameters for RouteTable. +type HubRouteTableProperties struct { + // List of labels associated with this route table. + Labels []*string + + // List of all routes. + Routes []*HubRoute + + // READ-ONLY; List of all connections associated with this route table. + AssociatedConnections []*string + + // READ-ONLY; List of all connections that advertise to this route table. + PropagatingConnections []*string + + // READ-ONLY; The provisioning state of the RouteTable resource. + ProvisioningState *ProvisioningState +} + +// HubVirtualNetworkConnection Resource. +type HubVirtualNetworkConnection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the hub virtual network connection. + Properties *HubVirtualNetworkConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// HubVirtualNetworkConnectionProperties - Parameters for HubVirtualNetworkConnection. +type HubVirtualNetworkConnectionProperties struct { + // Deprecated: VirtualHub to RemoteVnet transit to enabled or not. + AllowHubToRemoteVnetTransit *bool + + // Deprecated: Allow RemoteVnet to use Virtual Hub's gateways. + AllowRemoteVnetToUseHubVnetGateways *bool + + // Enable internet security. + EnableInternetSecurity *bool + + // Reference to the remote virtual network. + RemoteVirtualNetwork *SubResource + + // The Routing Configuration indicating the associated and propagated route tables on this connection. + RoutingConfiguration *RoutingConfiguration + + // READ-ONLY; The provisioning state of the hub virtual network connection resource. + ProvisioningState *ProvisioningState +} + +// IDPSQueryObject - Will describe the query to run against the IDPS signatures DB +type IDPSQueryObject struct { + // Contain all filters names and values + Filters []*FilterItems + + // Column to sort response by + OrderBy *OrderBy + + // The number of the results to return in each page + ResultsPerPage *int32 + + // Search term in all columns + Search *string + + // The number of records matching the filter to skip + Skip *int32 +} + +// IPAddressAvailabilityResult - Response for CheckIPAddressAvailability API service call. +type IPAddressAvailabilityResult struct { + // Private IP address availability. + Available *bool + + // Contains other available private IP addresses if the asked for address is taken. + AvailableIPAddresses []*string + + // Private IP address platform reserved. + IsPlatformReserved *bool +} + +// IPAllocation - IpAllocation resource. +type IPAllocation struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the IpAllocation. + Properties *IPAllocationPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// IPAllocationListResult - Response for the ListIpAllocations API service call. +type IPAllocationListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of IpAllocation resources. + Value []*IPAllocation +} + +// IPAllocationPropertiesFormat - Properties of the IpAllocation. +type IPAllocationPropertiesFormat struct { + // IpAllocation tags. + AllocationTags map[string]*string + + // The IPAM allocation ID. + IpamAllocationID *string + + // The address prefix for the IpAllocation. + Prefix *string + + // The address prefix length for the IpAllocation. + PrefixLength *int32 + + // The address prefix Type for the IpAllocation. + PrefixType *IPVersion + + // The type for the IpAllocation. + Type *IPAllocationType + + // READ-ONLY; The Subnet that using the prefix of this IpAllocation resource. + Subnet *SubResource + + // READ-ONLY; The VirtualNetwork that using the prefix of this IpAllocation resource. + VirtualNetwork *SubResource +} + +// IPConfiguration - IP configuration. +type IPConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the IP configuration. + Properties *IPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// IPConfigurationBgpPeeringAddress - Properties of IPConfigurationBgpPeeringAddress. +type IPConfigurationBgpPeeringAddress struct { + // The list of custom BGP peering addresses which belong to IP configuration. + CustomBgpIPAddresses []*string + + // The ID of IP configuration which belongs to gateway. + IPConfigurationID *string + + // READ-ONLY; The list of default BGP peering addresses which belong to IP configuration. + DefaultBgpIPAddresses []*string + + // READ-ONLY; The list of tunnel public IP addresses which belong to IP configuration. + TunnelIPAddresses []*string +} + +// IPConfigurationProfile - IP configuration profile child resource. +type IPConfigurationProfile struct { + // Resource ID. + ID *string + + // The name of the resource. This name can be used to access the resource. + Name *string + + // Properties of the IP configuration profile. + Properties *IPConfigurationProfilePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Sub Resource type. + Type *string +} + +// IPConfigurationProfilePropertiesFormat - IP configuration profile properties. +type IPConfigurationProfilePropertiesFormat struct { + // The reference to the subnet resource to create a container network interface ip configuration. + Subnet *Subnet + + // READ-ONLY; The provisioning state of the IP configuration profile resource. + ProvisioningState *ProvisioningState +} + +// IPConfigurationPropertiesFormat - Properties of IP configuration. +type IPConfigurationPropertiesFormat struct { + // The private IP address of the IP configuration. + PrivateIPAddress *string + + // The private IP address allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // The reference to the public IP resource. + PublicIPAddress *PublicIPAddress + + // The reference to the subnet resource. + Subnet *Subnet + + // READ-ONLY; The provisioning state of the IP configuration resource. + ProvisioningState *ProvisioningState +} + +// IPGroup - The IpGroups resource information. +type IPGroup struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the IpGroups. + Properties *IPGroupPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// IPGroupListResult - Response for the ListIpGroups API service call. +type IPGroupListResult struct { + // URL to get the next set of results. + NextLink *string + + // The list of IpGroups information resources. + Value []*IPGroup +} + +// IPGroupPropertiesFormat - The IpGroups property information. +type IPGroupPropertiesFormat struct { + // IpAddresses/IpAddressPrefixes in the IpGroups resource. + IPAddresses []*string + + // READ-ONLY; List of references to Firewall Policies resources that this IpGroups is associated with. + FirewallPolicies []*SubResource + + // READ-ONLY; List of references to Firewall resources that this IpGroups is associated with. + Firewalls []*SubResource + + // READ-ONLY; The provisioning state of the IpGroups resource. + ProvisioningState *ProvisioningState +} + +// IPPrefixesList - List of SNAT IP Prefixes learnt by firewall to not SNAT +type IPPrefixesList struct { + // IP Prefix value. + IPPrefixes []*string +} + +type IPRule struct { + // Specifies the IP or IP range in CIDR format. Only IPV4 address is allowed. + AddressPrefix *string +} + +// IPSecPolicy - An IPSec Policy configuration for a virtual network gateway connection. +type IPSecPolicy struct { + // REQUIRED; The DH Group used in IKE Phase 1 for initial SA. + DhGroup *DhGroup + + // REQUIRED; The IPSec encryption algorithm (IKE phase 1). + IPSecEncryption *IPSecEncryption + + // REQUIRED; The IPSec integrity algorithm (IKE phase 1). + IPSecIntegrity *IPSecIntegrity + + // REQUIRED; The IKE encryption algorithm (IKE phase 2). + IkeEncryption *IkeEncryption + + // REQUIRED; The IKE integrity algorithm (IKE phase 2). + IkeIntegrity *IkeIntegrity + + // REQUIRED; The Pfs Group used in IKE Phase 2 for new child SA. + PfsGroup *PfsGroup + + // REQUIRED; The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for a site to site VPN + // tunnel. + SaDataSizeKilobytes *int32 + + // REQUIRED; The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for a site to site + // VPN tunnel. + SaLifeTimeSeconds *int32 +} + +// IPTag - Contains the IpTag associated with the object. +type IPTag struct { + // The IP tag type. Example: FirstPartyUsage. + IPTagType *string + + // The value of the IP tag associated with the public IP. Example: SQL. + Tag *string +} + +// IPv6CircuitConnectionConfig - IPv6 Circuit Connection properties for global reach. +type IPv6CircuitConnectionConfig struct { + // /125 IP address space to carve out customer addresses for global reach. + AddressPrefix *string + + // READ-ONLY; Express Route Circuit connection state. + CircuitConnectionStatus *CircuitConnectionStatus +} + +// IPv6ExpressRouteCircuitPeeringConfig - Contains IPv6 peering config. +type IPv6ExpressRouteCircuitPeeringConfig struct { + // The Microsoft peering configuration. + MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig + + // The primary address prefix. + PrimaryPeerAddressPrefix *string + + // The reference to the RouteFilter resource. + RouteFilter *SubResource + + // The secondary address prefix. + SecondaryPeerAddressPrefix *string + + // The state of peering. + State *ExpressRouteCircuitPeeringState +} + +// InboundNatPool - Inbound NAT pool of the load balancer. +type InboundNatPool struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the set of inbound NAT pools used by the load balancer. This name can be + // used to access the resource. + Name *string + + // Properties of load balancer inbound nat pool. + Properties *InboundNatPoolPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// InboundNatPoolPropertiesFormat - Properties of Inbound NAT pool. +type InboundNatPoolPropertiesFormat struct { + // REQUIRED; The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. + BackendPort *int32 + + // REQUIRED; The last port number in the range of external ports that will be used to provide Inbound Nat to NICs associated + // with a load balancer. Acceptable values range between 1 and 65535. + FrontendPortRangeEnd *int32 + + // REQUIRED; The first port number in the range of external ports that will be used to provide Inbound Nat to NICs associated + // with a load balancer. Acceptable values range between 1 and 65534. + FrontendPortRangeStart *int32 + + // REQUIRED; The reference to the transport protocol used by the inbound NAT pool. + Protocol *TransportProtocol + + // Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability + // Group. This setting is required when using the SQL AlwaysOn Availability Groups + // in SQL server. This setting can't be changed after you create the endpoint. + EnableFloatingIP *bool + + // Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used + // when the protocol is set to TCP. + EnableTCPReset *bool + + // A reference to frontend IP addresses. + FrontendIPConfiguration *SubResource + + // The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. + // This element is only used when the protocol is set to TCP. + IdleTimeoutInMinutes *int32 + + // READ-ONLY; The provisioning state of the inbound NAT pool resource. + ProvisioningState *ProvisioningState +} + +// InboundNatRule - Inbound NAT rule of the load balancer. +type InboundNatRule struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the set of inbound NAT rules used by the load balancer. This name can be + // used to access the resource. + Name *string + + // Properties of load balancer inbound NAT rule. + Properties *InboundNatRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// InboundNatRuleListResult - Response for ListInboundNatRule API service call. +type InboundNatRuleListResult struct { + // A list of inbound NAT rules in a load balancer. + Value []*InboundNatRule + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// InboundNatRulePortMapping - Individual port mappings for inbound NAT rule created for backend pool. +type InboundNatRulePortMapping struct { + // READ-ONLY; Backend port. + BackendPort *int32 + + // READ-ONLY; Frontend port. + FrontendPort *int32 + + // READ-ONLY; Name of inbound NAT rule. + InboundNatRuleName *string + + // READ-ONLY; The reference to the transport protocol used by the inbound NAT rule. + Protocol *TransportProtocol +} + +// InboundNatRulePropertiesFormat - Properties of the inbound NAT rule. +type InboundNatRulePropertiesFormat struct { + // A reference to backendAddressPool resource. + BackendAddressPool *SubResource + + // The port used for the internal endpoint. Acceptable values range from 1 to 65535. + BackendPort *int32 + + // Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability + // Group. This setting is required when using the SQL AlwaysOn Availability Groups + // in SQL server. This setting can't be changed after you create the endpoint. + EnableFloatingIP *bool + + // Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used + // when the protocol is set to TCP. + EnableTCPReset *bool + + // A reference to frontend IP addresses. + FrontendIPConfiguration *SubResource + + // The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values + // range from 1 to 65534. + FrontendPort *int32 + + // The port range end for the external endpoint. This property is used together with BackendAddressPool and FrontendPortRangeStart. + // Individual inbound NAT rule port mappings will be created for each + // backend address from BackendAddressPool. Acceptable values range from 1 to 65534. + FrontendPortRangeEnd *int32 + + // The port range start for the external endpoint. This property is used together with BackendAddressPool and FrontendPortRangeEnd. + // Individual inbound NAT rule port mappings will be created for each + // backend address from BackendAddressPool. Acceptable values range from 1 to 65534. + FrontendPortRangeStart *int32 + + // The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. + // This element is only used when the protocol is set to TCP. + IdleTimeoutInMinutes *int32 + + // The reference to the transport protocol used by the load balancing rule. + Protocol *TransportProtocol + + // READ-ONLY; A reference to a private IP address defined on a network interface of a VM. Traffic sent to the frontend port + // of each of the frontend IP configurations is forwarded to the backend IP. + BackendIPConfiguration *InterfaceIPConfiguration + + // READ-ONLY; The provisioning state of the inbound NAT rule resource. + ProvisioningState *ProvisioningState +} + +// InboundSecurityRule - NVA Inbound Security Rule resource. +type InboundSecurityRule struct { + // Resource ID. + ID *string + + // Name of security rule collection. + Name *string + + // The properties of the Inbound Security Rules. + Properties *InboundSecurityRuleProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; NVA inbound security rule type. + Type *string +} + +// InboundSecurityRuleProperties - Properties of the Inbound Security Rules resource. +type InboundSecurityRuleProperties struct { + // List of allowed rules. + Rules []*InboundSecurityRules + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// InboundSecurityRules - Properties of the Inbound Security Rules resource. +type InboundSecurityRules struct { + // NVA port ranges to be opened up. One needs to provide specific ports. + DestinationPortRange *int32 + + // Protocol. This should be either TCP or UDP. + Protocol *InboundSecurityRulesProtocol + + // The CIDR or source IP range. Only /30, /31 and /32 Ip ranges are allowed. + SourceAddressPrefix *string +} + +// IntentPolicy - Network Intent Policy resource. +type IntentPolicy struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// IntentPolicyConfiguration - Details of NetworkIntentPolicyConfiguration for PrepareNetworkPoliciesRequest. +type IntentPolicyConfiguration struct { + // The name of the Network Intent Policy for storing in target subscription. + NetworkIntentPolicyName *string + + // Source network intent policy. + SourceNetworkIntentPolicy *IntentPolicy +} + +// Interface - A network interface in a resource group. +type Interface struct { + // The extended location of the network interface. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the network interface. + Properties *InterfacePropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// InterfaceAssociation - Network interface and its custom security rules. +type InterfaceAssociation struct { + // Collection of custom security rules. + SecurityRules []*SecurityRule + + // READ-ONLY; Network interface ID. + ID *string +} + +// InterfaceDNSSettings - DNS settings of a network interface. +type InterfaceDNSSettings struct { + // List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS resolution. 'AzureProvidedDNS' + // value cannot be combined with other IPs, it must be the only value in dnsServers + // collection. + DNSServers []*string + + // Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. + InternalDNSNameLabel *string + + // READ-ONLY; If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers + // from all NICs that are part of the Availability Set. This property is what is + // configured on each of those VMs. + AppliedDNSServers []*string + + // READ-ONLY; Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of the VM. This DNS + // name can be constructed by concatenating the VM name with the value of + // internalDomainNameSuffix. + InternalDomainNameSuffix *string + + // READ-ONLY; Fully qualified DNS name supporting internal communications between VMs in the same virtual network. + InternalFqdn *string +} + +// InterfaceIPConfiguration - IPConfiguration in a network interface. +type InterfaceIPConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Network interface IP configuration properties. + Properties *InterfaceIPConfigurationPropertiesFormat + + // Resource type. + Type *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// InterfaceIPConfigurationListResult - Response for list ip configurations API service call. +type InterfaceIPConfigurationListResult struct { + // A list of ip configurations. + Value []*InterfaceIPConfiguration + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// InterfaceIPConfigurationPrivateLinkConnectionProperties - PrivateLinkConnection properties for the network interface. +type InterfaceIPConfigurationPrivateLinkConnectionProperties struct { + // READ-ONLY; List of FQDNs for current private link connection. + Fqdns []*string + + // READ-ONLY; The group ID for current private link connection. + GroupID *string + + // READ-ONLY; The required member name for current private link connection. + RequiredMemberName *string +} + +// InterfaceIPConfigurationPropertiesFormat - Properties of IP configuration. +type InterfaceIPConfigurationPropertiesFormat struct { + // The reference to ApplicationGatewayBackendAddressPool resource. + ApplicationGatewayBackendAddressPools []*ApplicationGatewayBackendAddressPool + + // Application security groups in which the IP configuration is included. + ApplicationSecurityGroups []*ApplicationSecurityGroup + + // The reference to gateway load balancer frontend IP. + GatewayLoadBalancer *SubResource + + // The reference to LoadBalancerBackendAddressPool resource. + LoadBalancerBackendAddressPools []*BackendAddressPool + + // A list of references of LoadBalancerInboundNatRules. + LoadBalancerInboundNatRules []*InboundNatRule + + // Whether this is a primary customer address on the network interface. + Primary *bool + + // Private IP address of the IP configuration. + PrivateIPAddress *string + + // Whether the specific IP configuration is IPv4 or IPv6. Default is IPv4. + PrivateIPAddressVersion *IPVersion + + // The private IP address allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // Public IP address bound to the IP configuration. + PublicIPAddress *PublicIPAddress + + // Subnet bound to the IP configuration. + Subnet *Subnet + + // The reference to Virtual Network Taps. + VirtualNetworkTaps []*VirtualNetworkTap + + // READ-ONLY; PrivateLinkConnection properties for the network interface. + PrivateLinkConnectionProperties *InterfaceIPConfigurationPrivateLinkConnectionProperties + + // READ-ONLY; The provisioning state of the network interface IP configuration. + ProvisioningState *ProvisioningState +} + +// InterfaceListResult - Response for the ListNetworkInterface API service call. +type InterfaceListResult struct { + // A list of network interfaces in a resource group. + Value []*Interface + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// InterfaceLoadBalancerListResult - Response for list ip configurations API service call. +type InterfaceLoadBalancerListResult struct { + // A list of load balancers. + Value []*LoadBalancer + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// InterfacePropertiesFormat - NetworkInterface properties. +type InterfacePropertiesFormat struct { + // Auxiliary mode of Network Interface resource. + AuxiliaryMode *NetworkInterfaceAuxiliaryMode + + // Auxiliary sku of Network Interface resource. + AuxiliarySKU *NetworkInterfaceAuxiliarySKU + + // The DNS settings in network interface. + DNSSettings *InterfaceDNSSettings + + // Indicates whether to disable tcp state tracking. + DisableTCPStateTracking *bool + + // If the network interface is configured for accelerated networking. Not applicable to VM sizes which require accelerated + // networking. + EnableAcceleratedNetworking *bool + + // Indicates whether IP forwarding is enabled on this network interface. + EnableIPForwarding *bool + + // A list of IPConfigurations of the network interface. + IPConfigurations []*InterfaceIPConfiguration + + // Migration phase of Network Interface resource. + MigrationPhase *NetworkInterfaceMigrationPhase + + // The reference to the NetworkSecurityGroup resource. + NetworkSecurityGroup *SecurityGroup + + // Type of Network Interface resource. + NicType *NetworkInterfaceNicType + + // Privatelinkservice of the network interface resource. + PrivateLinkService *PrivateLinkService + + // WorkloadType of the NetworkInterface for BareMetal resources + WorkloadType *string + + // READ-ONLY; A reference to the dscp configuration to which the network interface is linked. + DscpConfiguration *SubResource + + // READ-ONLY; A list of references to linked BareMetal resources. + HostedWorkloads []*string + + // READ-ONLY; The MAC address of the network interface. + MacAddress *string + + // READ-ONLY; Whether this is a primary network interface on a virtual machine. + Primary *bool + + // READ-ONLY; A reference to the private endpoint to which the network interface is linked. + PrivateEndpoint *PrivateEndpoint + + // READ-ONLY; The provisioning state of the network interface resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the network interface resource. + ResourceGUID *string + + // READ-ONLY; A list of TapConfigurations of the network interface. + TapConfigurations []*InterfaceTapConfiguration + + // READ-ONLY; The reference to a virtual machine. + VirtualMachine *SubResource + + // READ-ONLY; Whether the virtual machine this nic is attached to supports encryption. + VnetEncryptionSupported *bool +} + +// InterfaceTapConfiguration - Tap configuration in a Network Interface. +type InterfaceTapConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the Virtual Network Tap configuration. + Properties *InterfaceTapConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Sub Resource type. + Type *string +} + +// InterfaceTapConfigurationListResult - Response for list tap configurations API service call. +type InterfaceTapConfigurationListResult struct { + // A list of tap configurations. + Value []*InterfaceTapConfiguration + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// InterfaceTapConfigurationPropertiesFormat - Properties of Virtual Network Tap configuration. +type InterfaceTapConfigurationPropertiesFormat struct { + // The reference to the Virtual Network Tap resource. + VirtualNetworkTap *VirtualNetworkTap + + // READ-ONLY; The provisioning state of the network interface tap configuration resource. + ProvisioningState *ProvisioningState +} + +// ListHubRouteTablesResult - List of RouteTables and a URL nextLink to get the next set of results. +type ListHubRouteTablesResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of RouteTables. + Value []*HubRouteTable +} + +// ListHubVirtualNetworkConnectionsResult - List of HubVirtualNetworkConnections and a URL nextLink to get the next set of +// results. +type ListHubVirtualNetworkConnectionsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of HubVirtualNetworkConnections. + Value []*HubVirtualNetworkConnection +} + +// ListP2SVPNGatewaysResult - Result of the request to list P2SVpnGateways. It contains a list of P2SVpnGateways and a URL +// nextLink to get the next set of results. +type ListP2SVPNGatewaysResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of P2SVpnGateways. + Value []*P2SVPNGateway +} + +// ListRouteMapsResult - List of RouteMaps and a URL nextLink to get the next set of results. +type ListRouteMapsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of RouteMaps. + Value []*RouteMap +} + +// ListRoutingIntentResult - List of the routing intent result and a URL nextLink to get the next set of results. +type ListRoutingIntentResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of RoutingIntent resource. + Value []*RoutingIntent +} + +// ListVPNConnectionsResult - Result of the request to list all vpn connections to a virtual wan vpn gateway. It contains +// a list of Vpn Connections and a URL nextLink to get the next set of results. +type ListVPNConnectionsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of Vpn Connections. + Value []*VPNConnection +} + +// ListVPNGatewayNatRulesResult - Result of the request to list all nat rules to a virtual wan vpn gateway. It contains a +// list of Nat rules and a URL nextLink to get the next set of results. +type ListVPNGatewayNatRulesResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of Nat Rules. + Value []*VPNGatewayNatRule +} + +// ListVPNGatewaysResult - Result of the request to list VpnGateways. It contains a list of VpnGateways and a URL nextLink +// to get the next set of results. +type ListVPNGatewaysResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VpnGateways. + Value []*VPNGateway +} + +// ListVPNServerConfigurationPolicyGroupsResult - Result of the request to list VpnServerConfigurationPolicyGroups. It contains +// a list of VpnServerConfigurationPolicyGroups and a URL nextLink to get the next set of results. +type ListVPNServerConfigurationPolicyGroupsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VpnServerConfigurationPolicyGroups. + Value []*VPNServerConfigurationPolicyGroup +} + +// ListVPNServerConfigurationsResult - Result of the request to list all VpnServerConfigurations. It contains a list of VpnServerConfigurations +// and a URL nextLink to get the next set of results. +type ListVPNServerConfigurationsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VpnServerConfigurations. + Value []*VPNServerConfiguration +} + +// ListVPNSiteLinkConnectionsResult - Result of the request to list all vpn connections to a virtual wan vpn gateway. It contains +// a list of Vpn Connections and a URL nextLink to get the next set of results. +type ListVPNSiteLinkConnectionsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VpnSiteLinkConnections. + Value []*VPNSiteLinkConnection +} + +// ListVPNSiteLinksResult - Result of the request to list VpnSiteLinks. It contains a list of VpnSiteLinks and a URL nextLink +// to get the next set of results. +type ListVPNSiteLinksResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VpnSitesLinks. + Value []*VPNSiteLink +} + +// ListVPNSitesResult - Result of the request to list VpnSites. It contains a list of VpnSites and a URL nextLink to get the +// next set of results. +type ListVPNSitesResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VpnSites. + Value []*VPNSite +} + +// ListVirtualHubBgpConnectionResults - VirtualHubBgpConnections list. +type ListVirtualHubBgpConnectionResults struct { + // URL to get the next set of results. + NextLink *string + + // The list of VirtualHubBgpConnections. + Value []*BgpConnection +} + +// ListVirtualHubIPConfigurationResults - VirtualHubIpConfigurations list. +type ListVirtualHubIPConfigurationResults struct { + // URL to get the next set of results. + NextLink *string + + // The list of VirtualHubIpConfigurations. + Value []*HubIPConfiguration +} + +// ListVirtualHubRouteTableV2SResult - List of VirtualHubRouteTableV2s and a URL nextLink to get the next set of results. +type ListVirtualHubRouteTableV2SResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VirtualHubRouteTableV2s. + Value []*VirtualHubRouteTableV2 +} + +// ListVirtualHubsResult - Result of the request to list VirtualHubs. It contains a list of VirtualHubs and a URL nextLink +// to get the next set of results. +type ListVirtualHubsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VirtualHubs. + Value []*VirtualHub +} + +// ListVirtualNetworkGatewayNatRulesResult - Result of the request to list all nat rules to a virtual network gateway. It +// contains a list of Nat rules and a URL nextLink to get the next set of results. +type ListVirtualNetworkGatewayNatRulesResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of Nat Rules. + Value []*VirtualNetworkGatewayNatRule +} + +// ListVirtualWANsResult - Result of the request to list VirtualWANs. It contains a list of VirtualWANs and a URL nextLink +// to get the next set of results. +type ListVirtualWANsResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of VirtualWANs. + Value []*VirtualWAN +} + +// LoadBalancer resource. +type LoadBalancer struct { + // The extended location of the load balancer. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of load balancer. + Properties *LoadBalancerPropertiesFormat + + // The load balancer SKU. + SKU *LoadBalancerSKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// LoadBalancerBackendAddress - Load balancer backend addresses. +type LoadBalancerBackendAddress struct { + // Name of the backend address. + Name *string + + // Properties of load balancer backend address pool. + Properties *LoadBalancerBackendAddressPropertiesFormat +} + +// LoadBalancerBackendAddressPoolListResult - Response for ListBackendAddressPool API service call. +type LoadBalancerBackendAddressPoolListResult struct { + // A list of backend address pools in a load balancer. + Value []*BackendAddressPool + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// LoadBalancerBackendAddressPropertiesFormat - Properties of the load balancer backend addresses. +type LoadBalancerBackendAddressPropertiesFormat struct { + // A list of administrative states which once set can override health probe so that Load Balancer will always forward new + // connections to backend, or deny new connections and reset existing connections. + AdminState *LoadBalancerBackendAddressAdminState + + // IP Address belonging to the referenced virtual network. + IPAddress *string + + // Reference to the frontend ip address configuration defined in regional loadbalancer. + LoadBalancerFrontendIPConfiguration *SubResource + + // Reference to an existing subnet. + Subnet *SubResource + + // Reference to an existing virtual network. + VirtualNetwork *SubResource + + // READ-ONLY; Collection of inbound NAT rule port mappings. + InboundNatRulesPortMapping []*NatRulePortMapping + + // READ-ONLY; Reference to IP address defined in network interfaces. + NetworkInterfaceIPConfiguration *SubResource +} + +// LoadBalancerFrontendIPConfigurationListResult - Response for ListFrontendIPConfiguration API service call. +type LoadBalancerFrontendIPConfigurationListResult struct { + // A list of frontend IP configurations in a load balancer. + Value []*FrontendIPConfiguration + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// LoadBalancerListResult - Response for ListLoadBalancers API service call. +type LoadBalancerListResult struct { + // A list of load balancers in a resource group. + Value []*LoadBalancer + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// LoadBalancerLoadBalancingRuleListResult - Response for ListLoadBalancingRule API service call. +type LoadBalancerLoadBalancingRuleListResult struct { + // A list of load balancing rules in a load balancer. + Value []*LoadBalancingRule + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// LoadBalancerOutboundRuleListResult - Response for ListOutboundRule API service call. +type LoadBalancerOutboundRuleListResult struct { + // A list of outbound rules in a load balancer. + Value []*OutboundRule + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// LoadBalancerProbeListResult - Response for ListProbe API service call. +type LoadBalancerProbeListResult struct { + // A list of probes in a load balancer. + Value []*Probe + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// LoadBalancerPropertiesFormat - Properties of the load balancer. +type LoadBalancerPropertiesFormat struct { + // Collection of backend address pools used by a load balancer. + BackendAddressPools []*BackendAddressPool + + // Object representing the frontend IPs to be used for the load balancer. + FrontendIPConfigurations []*FrontendIPConfiguration + + // Defines an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound + // NAT rules are created automatically for each NIC associated with the Load + // Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive + // with defining inbound NAT rules. Inbound NAT pools are referenced from virtual + // machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They + // have to reference individual inbound NAT rules. + InboundNatPools []*InboundNatPool + + // Collection of inbound NAT Rules used by a load balancer. Defining inbound NAT rules on your load balancer is mutually exclusive + // with defining an inbound NAT pool. Inbound NAT pools are referenced from + // virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. + // They have to reference individual inbound NAT rules. + InboundNatRules []*InboundNatRule + + // Object collection representing the load balancing rules Gets the provisioning. + LoadBalancingRules []*LoadBalancingRule + + // The outbound rules. + OutboundRules []*OutboundRule + + // Collection of probe objects used in the load balancer. + Probes []*Probe + + // READ-ONLY; The provisioning state of the load balancer resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the load balancer resource. + ResourceGUID *string +} + +// LoadBalancerSKU - SKU of a load balancer. +type LoadBalancerSKU struct { + // Name of a load balancer SKU. + Name *LoadBalancerSKUName + + // Tier of a load balancer SKU. + Tier *LoadBalancerSKUTier +} + +// LoadBalancerVipSwapRequest - The request for a VIP swap. +type LoadBalancerVipSwapRequest struct { + // A list of frontend IP configuration resources that should swap VIPs. + FrontendIPConfigurations []*LoadBalancerVipSwapRequestFrontendIPConfiguration +} + +// LoadBalancerVipSwapRequestFrontendIPConfiguration - VIP swap request's frontend IP configuration object. +type LoadBalancerVipSwapRequestFrontendIPConfiguration struct { + // The ID of frontend IP configuration resource. + ID *string + + // The properties of VIP swap request's frontend IP configuration object. + Properties *LoadBalancerVipSwapRequestFrontendIPConfigurationProperties +} + +// LoadBalancerVipSwapRequestFrontendIPConfigurationProperties - The properties of VIP swap request's frontend IP configuration +// object. +type LoadBalancerVipSwapRequestFrontendIPConfigurationProperties struct { + // A reference to public IP address resource. + PublicIPAddress *SubResource +} + +// LoadBalancingRule - A load balancing rule for a load balancer. +type LoadBalancingRule struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the set of load balancing rules used by the load balancer. This name can + // be used to access the resource. + Name *string + + // Properties of load balancer load balancing rule. + Properties *LoadBalancingRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// LoadBalancingRulePropertiesFormat - Properties of the load balancer. +type LoadBalancingRulePropertiesFormat struct { + // REQUIRED; The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable + // values are between 0 and 65534. Note that value 0 enables "Any Port". + FrontendPort *int32 + + // REQUIRED; The reference to the transport protocol used by the load balancing rule. + Protocol *TransportProtocol + + // A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs. + BackendAddressPool *SubResource + + // An array of references to pool of DIPs. + BackendAddressPools []*SubResource + + // The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables + // "Any Port". + BackendPort *int32 + + // Configures SNAT for the VMs in the backend pool to use the publicIP address specified in the frontend of the load balancing + // rule. + DisableOutboundSnat *bool + + // Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability + // Group. This setting is required when using the SQL AlwaysOn Availability Groups + // in SQL server. This setting can't be changed after you create the endpoint. + EnableFloatingIP *bool + + // Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used + // when the protocol is set to TCP. + EnableTCPReset *bool + + // A reference to frontend IP addresses. + FrontendIPConfiguration *SubResource + + // The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. + // This element is only used when the protocol is set to TCP. + IdleTimeoutInMinutes *int32 + + // The load distribution policy for this rule. + LoadDistribution *LoadDistribution + + // The reference to the load balancer probe used by the load balancing rule. + Probe *SubResource + + // READ-ONLY; The provisioning state of the load balancing rule resource. + ProvisioningState *ProvisioningState +} + +// LocalNetworkGateway - A common class for general resource information. +type LocalNetworkGateway struct { + // REQUIRED; Properties of the local network gateway. + Properties *LocalNetworkGatewayPropertiesFormat + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// LocalNetworkGatewayListResult - Response for ListLocalNetworkGateways API service call. +type LocalNetworkGatewayListResult struct { + // A list of local network gateways that exists in a resource group. + Value []*LocalNetworkGateway + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// LocalNetworkGatewayPropertiesFormat - LocalNetworkGateway properties. +type LocalNetworkGatewayPropertiesFormat struct { + // Local network gateway's BGP speaker settings. + BgpSettings *BgpSettings + + // FQDN of local network gateway. + Fqdn *string + + // IP address of local network gateway. + GatewayIPAddress *string + + // Local network site address space. + LocalNetworkAddressSpace *AddressSpace + + // READ-ONLY; The provisioning state of the local network gateway resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the local network gateway resource. + ResourceGUID *string +} + +// LogSpecification - Description of logging specification. +type LogSpecification struct { + // Duration of the blob. + BlobDuration *string + + // The display name of the specification. + DisplayName *string + + // The name of the specification. + Name *string +} + +// ManagedRuleGroupOverride - Defines a managed rule group override setting. +type ManagedRuleGroupOverride struct { + // REQUIRED; The managed rule group to override. + RuleGroupName *string + + // List of rules that will be disabled. If none specified, all rules in the group will be disabled. + Rules []*ManagedRuleOverride +} + +// ManagedRuleOverride - Defines a managed rule group override setting. +type ManagedRuleOverride struct { + // REQUIRED; Identifier for the managed rule. + RuleID *string + + // Describes the override action to be applied when rule matches. + Action *ActionType + + // The state of the managed rule. Defaults to Disabled if not specified. + State *ManagedRuleEnabledState +} + +// ManagedRuleSet - Defines a managed rule set. +type ManagedRuleSet struct { + // REQUIRED; Defines the rule set type to use. + RuleSetType *string + + // REQUIRED; Defines the version of the rule set to use. + RuleSetVersion *string + + // Defines the rule group overrides to apply to the rule set. + RuleGroupOverrides []*ManagedRuleGroupOverride +} + +// ManagedRulesDefinition - Allow to exclude some variable satisfy the condition for the WAF check. +type ManagedRulesDefinition struct { + // REQUIRED; The managed rule sets that are associated with the policy. + ManagedRuleSets []*ManagedRuleSet + + // The Exclusions that are applied on the policy. + Exclusions []*OwaspCrsExclusionEntry +} + +// ManagedServiceIdentity - Identity for the resource. +type ManagedServiceIdentity struct { + // The type of identity used for the resource. The type 'SystemAssigned, UserAssigned' includes both an implicitly created + // identity and a set of user assigned identities. The type 'None' will remove any + // identities from the virtual machine. + Type *ResourceIdentityType + + // The list of user identities associated with resource. The user identity dictionary key references will be ARM resource + // ids in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + UserAssignedIdentities map[string]*Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties + + // READ-ONLY; The 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 +} + +// Manager - The Managed Network resource +type Manager struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // The network manager properties + Properties *ManagerProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// ManagerCommit - Network Manager Commit. +type ManagerCommit struct { + // REQUIRED; Commit Type. + CommitType *ConfigurationType + + // REQUIRED; List of target locations. + TargetLocations []*string + + // List of configuration ids. + ConfigurationIDs []*string + + // READ-ONLY; Commit Id. + CommitID *string +} + +// ManagerConnection - The Network Manager Connection resource +type ManagerConnection struct { + // The scope connection properties + Properties *ManagerConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// ManagerConnectionListResult - List of network manager connections. +type ManagerConnectionListResult struct { + // Gets the URL to get the next page of results. + NextLink *string + + // List of network manager connections. + Value []*ManagerConnection +} + +// ManagerConnectionProperties - Information about the network manager connection. +type ManagerConnectionProperties struct { + // A description of the network manager connection. + Description *string + + // Network Manager Id. + NetworkManagerID *string + + // READ-ONLY; Connection state. + ConnectionState *ScopeConnectionState +} + +// ManagerDeploymentStatus - Network Manager Deployment Status. +type ManagerDeploymentStatus struct { + // Commit Time. + CommitTime *time.Time + + // List of configuration ids. + ConfigurationIDs []*string + + // Deployment Status. + DeploymentStatus *DeploymentStatus + + // Configuration Deployment Type. + DeploymentType *ConfigurationType + + // Error Message. + ErrorMessage *string + + // Region Name. + Region *string +} + +// ManagerDeploymentStatusListResult - A list of Network Manager Deployment Status +type ManagerDeploymentStatusListResult struct { + // When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current + // request) to retrieve the next page of data. + SkipToken *string + + // Gets a page of Network Manager Deployment Status + Value []*ManagerDeploymentStatus +} + +// ManagerDeploymentStatusParameter - Network Manager Deployment Status Parameter. +type ManagerDeploymentStatusParameter struct { + // List of deployment types. + DeploymentTypes []*ConfigurationType + + // List of locations. + Regions []*string + + // Continuation token for pagination, capturing the next page size and offset, as well as the context of the query. + SkipToken *string +} + +// ManagerEffectiveConnectivityConfigurationListResult - Result of the request to list networkManagerEffectiveConnectivityConfiguration. +// It contains a list of groups and a skiptoken to get the next set of results. +type ManagerEffectiveConnectivityConfigurationListResult struct { + // When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current + // request) to retrieve the next page of data. + SkipToken *string + + // Gets a page of NetworkManagerEffectiveConnectivityConfiguration + Value []*EffectiveConnectivityConfiguration +} + +// ManagerEffectiveSecurityAdminRulesListResult - Result of the request to list networkManagerEffectiveSecurityAdminRules. +// It contains a list of groups and a skiptoken to get the next set of results. +type ManagerEffectiveSecurityAdminRulesListResult struct { + // When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current + // request) to retrieve the next page of data. + SkipToken *string + + // Gets a page of NetworkManagerEffectiveSecurityAdminRules + Value []EffectiveBaseSecurityAdminRuleClassification +} + +// ManagerListResult - Result of the request to list NetworkManager. It contains a list of network managers and a URL link +// to get the next set of results. +type ManagerListResult struct { + // Gets the URL to get the next page of results. + NextLink *string + + // Gets a page of NetworkManager + Value []*Manager +} + +// ManagerProperties - Properties of Managed Network +type ManagerProperties struct { + // REQUIRED; Scope Access. + NetworkManagerScopeAccesses []*ConfigurationType + + // REQUIRED; Scope of Network Manager. + NetworkManagerScopes *ManagerPropertiesNetworkManagerScopes + + // A description of the network manager. + Description *string + + // READ-ONLY; The provisioning state of the network manager resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Unique identifier for this resource. + ResourceGUID *string +} + +// ManagerPropertiesNetworkManagerScopes - Scope of Network Manager. +type ManagerPropertiesNetworkManagerScopes struct { + // List of management groups. + ManagementGroups []*string + + // List of subscriptions. + Subscriptions []*string + + // READ-ONLY; List of cross tenant scopes. + CrossTenantScopes []*CrossTenantScopes +} + +// ManagerSecurityGroupItem - Network manager security group item. +type ManagerSecurityGroupItem struct { + // REQUIRED; Network manager group Id. + NetworkGroupID *string +} + +// MatchCondition - Define match conditions. +type MatchCondition struct { + // REQUIRED; Match value. + MatchValues []*string + + // REQUIRED; List of match variables. + MatchVariables []*MatchVariable + + // REQUIRED; The operator to be matched. + Operator *WebApplicationFirewallOperator + + // Whether this is negate condition or not. + NegationConditon *bool + + // List of transforms. + Transforms []*WebApplicationFirewallTransform +} + +// MatchVariable - Define match variables. +type MatchVariable struct { + // REQUIRED; Match Variable. + VariableName *WebApplicationFirewallMatchVariable + + // The selector of match variable. + Selector *string +} + +// MatchedRule - Matched rule. +type MatchedRule struct { + // The network traffic is allowed or denied. Possible values are 'Allow' and 'Deny'. + Action *string + + // Name of the matched network security rule. + RuleName *string +} + +// MetricSpecification - Description of metrics specification. +type MetricSpecification struct { + // The aggregation type. + AggregationType *string + + // List of availability. + Availabilities []*Availability + + // List of dimensions. + Dimensions []*Dimension + + // The description of the metric. + DisplayDescription *string + + // The display name of the metric. + DisplayName *string + + // Whether regional MDM account enabled. + EnableRegionalMdmAccount *bool + + // Whether gaps would be filled with zeros. + FillGapWithZero *bool + + // Whether the metric is internal. + IsInternal *bool + + // Pattern for the filter of the metric. + MetricFilterPattern *string + + // The name of the metric. + Name *string + + // The resource Id dimension name override. + ResourceIDDimensionNameOverride *string + + // The source MDM account. + SourceMdmAccount *string + + // The source MDM namespace. + SourceMdmNamespace *string + + // Units the metric to be displayed in. + Unit *string +} + +// MigrateLoadBalancerToIPBasedRequest - The request for a migrateToIpBased API. +type MigrateLoadBalancerToIPBasedRequest struct { + // A list of pool names that should be migrated from Nic based to IP based pool + Pools []*string +} + +// MigratedPools - The response for a migrateToIpBased API. +type MigratedPools struct { + // A list of pools migrated from Nic based to IP based pool + MigratedPools []*string +} + +// NatGateway - Nat Gateway resource. +type NatGateway struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Nat Gateway properties. + Properties *NatGatewayPropertiesFormat + + // The nat gateway SKU. + SKU *NatGatewaySKU + + // Resource tags. + Tags map[string]*string + + // A list of availability zones denoting the zone in which Nat Gateway should be deployed. + Zones []*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// NatGatewayListResult - Response for ListNatGateways API service call. +type NatGatewayListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of Nat Gateways that exists in a resource group. + Value []*NatGateway +} + +// NatGatewayPropertiesFormat - Nat Gateway properties. +type NatGatewayPropertiesFormat struct { + // The idle timeout of the nat gateway. + IdleTimeoutInMinutes *int32 + + // An array of public ip addresses associated with the nat gateway resource. + PublicIPAddresses []*SubResource + + // An array of public ip prefixes associated with the nat gateway resource. + PublicIPPrefixes []*SubResource + + // READ-ONLY; The provisioning state of the NAT gateway resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the NAT gateway resource. + ResourceGUID *string + + // READ-ONLY; An array of references to the subnets using this nat gateway resource. + Subnets []*SubResource +} + +// NatGatewaySKU - SKU of nat gateway. +type NatGatewaySKU struct { + // Name of Nat Gateway SKU. + Name *NatGatewaySKUName +} + +// NatRule - Rule of type nat. +type NatRule struct { + // REQUIRED; Rule Type. + RuleType *FirewallPolicyRuleType + + // Description of the rule. + Description *string + + // List of destination IP addresses or Service Tags. + DestinationAddresses []*string + + // List of destination ports. + DestinationPorts []*string + + // Array of FirewallPolicyRuleNetworkProtocols. + IPProtocols []*FirewallPolicyRuleNetworkProtocol + + // Name of the rule. + Name *string + + // List of source IP addresses for this rule. + SourceAddresses []*string + + // List of source IpGroups for this rule. + SourceIPGroups []*string + + // The translated address for this NAT rule. + TranslatedAddress *string + + // The translated FQDN for this NAT rule. + TranslatedFqdn *string + + // The translated port for this NAT rule. + TranslatedPort *string +} + +// GetFirewallPolicyRule implements the FirewallPolicyRuleClassification interface for type NatRule. +func (n *NatRule) GetFirewallPolicyRule() *FirewallPolicyRule { + return &FirewallPolicyRule{ + Description: n.Description, + Name: n.Name, + RuleType: n.RuleType, + } +} + +// NatRulePortMapping - Individual port mappings for inbound NAT rule created for backend pool. +type NatRulePortMapping struct { + // Backend port. + BackendPort *int32 + + // Frontend port. + FrontendPort *int32 + + // Name of inbound NAT rule. + InboundNatRuleName *string +} + +// NextHopParameters - Parameters that define the source and destination endpoint. +type NextHopParameters struct { + // REQUIRED; The destination IP address. + DestinationIPAddress *string + + // REQUIRED; The source IP address. + SourceIPAddress *string + + // REQUIRED; The resource identifier of the target resource against which the action is to be performed. + TargetResourceID *string + + // The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of the nics, then this parameter must be specified. + // Otherwise optional). + TargetNicResourceID *string +} + +// NextHopResult - The information about next hop from the specified VM. +type NextHopResult struct { + // Next hop IP Address. + NextHopIPAddress *string + + // Next hop type. + NextHopType *NextHopType + + // The resource identifier for the route table associated with the route being returned. If the route being returned does + // not correspond to any user created routes then this field will be the string + // 'System Route'. + RouteTableID *string +} + +// O365BreakOutCategoryPolicies - Office365 breakout categories. +type O365BreakOutCategoryPolicies struct { + // Flag to control allow category. + Allow *bool + + // Flag to control default category. + Default *bool + + // Flag to control optimize category. + Optimize *bool +} + +// O365PolicyProperties - The Office365 breakout policy. +type O365PolicyProperties struct { + // Office365 breakout categories. + BreakOutCategories *O365BreakOutCategoryPolicies +} + +// Office365PolicyProperties - Network Virtual Appliance Sku Properties. +type Office365PolicyProperties struct { + // Office 365 breakout categories. + BreakOutCategories *BreakOutCategoryPolicies +} + +// Operation - Network REST API operation definition. +type Operation struct { + // Display metadata associated with the operation. + Display *OperationDisplay + + // Operation name: {provider}/{resource}/{operation}. + Name *string + + // Origin of the operation. + Origin *string + + // Operation properties format. + Properties *OperationPropertiesFormat +} + +// OperationDisplay - Display metadata associated with the operation. +type OperationDisplay struct { + // Description of the operation. + Description *string + + // Type of the operation: get, read, delete, etc. + Operation *string + + // Service provider: Microsoft Network. + Provider *string + + // Resource on which the operation is performed. + Resource *string +} + +// OperationListResult - Result of the request to list Network operations. It contains a list of operations and a URL link +// to get the next set of results. +type OperationListResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string + + // List of Network operations supported by the Network resource provider. + Value []*Operation +} + +// OperationPropertiesFormat - Description of operation properties format. +type OperationPropertiesFormat struct { + // Specification of the service. + ServiceSpecification *OperationPropertiesFormatServiceSpecification +} + +// OperationPropertiesFormatServiceSpecification - Specification of the service. +type OperationPropertiesFormatServiceSpecification struct { + // Operation log specification. + LogSpecifications []*LogSpecification + + // Operation service specification. + MetricSpecifications []*MetricSpecification +} + +// OrderBy - Describes a column to sort +type OrderBy struct { + // Describes the actual column name to sort by + Field *string + + // Describes if results should be in ascending/descending order + Order *FirewallPolicyIDPSQuerySortOrder +} + +// OutboundRule - Outbound rule of the load balancer. +type OutboundRule struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the set of outbound rules used by the load balancer. This name can be used + // to access the resource. + Name *string + + // Properties of load balancer outbound rule. + Properties *OutboundRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// OutboundRulePropertiesFormat - Outbound rule of the load balancer. +type OutboundRulePropertiesFormat struct { + // REQUIRED; A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the backend IPs. + BackendAddressPool *SubResource + + // REQUIRED; The Frontend IP addresses of the load balancer. + FrontendIPConfigurations []*SubResource + + // REQUIRED; The protocol for the outbound rule in load balancer. + Protocol *LoadBalancerOutboundRuleProtocol + + // The number of outbound ports to be used for NAT. + AllocatedOutboundPorts *int32 + + // Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used + // when the protocol is set to TCP. + EnableTCPReset *bool + + // The timeout for the TCP idle connection. + IdleTimeoutInMinutes *int32 + + // READ-ONLY; The provisioning state of the outbound rule resource. + ProvisioningState *ProvisioningState +} + +// OwaspCrsExclusionEntry - Allow to exclude some variable satisfy the condition for the WAF check. +type OwaspCrsExclusionEntry struct { + // REQUIRED; The variable to be excluded. + MatchVariable *OwaspCrsExclusionEntryMatchVariable + + // REQUIRED; When matchVariable is a collection, operator used to specify which elements in the collection this exclusion + // applies to. + Selector *string + + // REQUIRED; When matchVariable is a collection, operate on the selector to specify which elements in the collection this + // exclusion applies to. + SelectorMatchOperator *OwaspCrsExclusionEntrySelectorMatchOperator + + // The managed rule sets that are associated with the exclusion. + ExclusionManagedRuleSets []*ExclusionManagedRuleSet +} + +// P2SConnectionConfiguration Resource. +type P2SConnectionConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the P2S connection configuration. + Properties *P2SConnectionConfigurationProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// P2SConnectionConfigurationProperties - Parameters for P2SConnectionConfiguration. +type P2SConnectionConfigurationProperties struct { + // Flag indicating whether the enable internet security flag is turned on for the P2S Connections or not. + EnableInternetSecurity *bool + + // The Routing Configuration indicating the associated and propagated route tables on this connection. + RoutingConfiguration *RoutingConfiguration + + // The reference to the address space resource which represents Address space for P2S VpnClient. + VPNClientAddressPool *AddressSpace + + // READ-ONLY; List of Configuration Policy Groups that this P2SConnectionConfiguration is attached to. + ConfigurationPolicyGroupAssociations []*SubResource + + // READ-ONLY; List of previous Configuration Policy Groups that this P2SConnectionConfiguration was attached to. + PreviousConfigurationPolicyGroupAssociations []*VPNServerConfigurationPolicyGroup + + // READ-ONLY; The provisioning state of the P2SConnectionConfiguration resource. + ProvisioningState *ProvisioningState +} + +// P2SVPNConnectionHealth - P2S Vpn connection detailed health written to sas url. +type P2SVPNConnectionHealth struct { + // Returned sas url of the blob to which the p2s vpn connection detailed health will be written. + SasURL *string +} + +// P2SVPNConnectionHealthRequest - List of P2S Vpn connection health request. +type P2SVPNConnectionHealthRequest struct { + // The sas-url to download the P2S Vpn connection health detail. + OutputBlobSasURL *string + + // The list of p2s vpn user names whose p2s vpn connection detailed health to retrieve for. + VPNUserNamesFilter []*string +} + +// P2SVPNConnectionRequest - List of p2s vpn connections to be disconnected. +type P2SVPNConnectionRequest struct { + // List of p2s vpn connection Ids. + VPNConnectionIDs []*string +} + +// P2SVPNGateway - P2SVpnGateway Resource. +type P2SVPNGateway struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the P2SVpnGateway. + Properties *P2SVPNGatewayProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// P2SVPNGatewayProperties - Parameters for P2SVpnGateway. +type P2SVPNGatewayProperties struct { + // List of all customer specified DNS servers IP addresses. + CustomDNSServers []*string + + // Enable Routing Preference property for the Public IP Interface of the P2SVpnGateway. + IsRoutingPreferenceInternet *bool + + // List of all p2s connection configurations of the gateway. + P2SConnectionConfigurations []*P2SConnectionConfiguration + + // The scale unit for this p2s vpn gateway. + VPNGatewayScaleUnit *int32 + + // The VpnServerConfiguration to which the p2sVpnGateway is attached to. + VPNServerConfiguration *SubResource + + // The VirtualHub to which the gateway belongs. + VirtualHub *SubResource + + // READ-ONLY; The provisioning state of the P2S VPN gateway resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; All P2S VPN clients' connection health status. + VPNClientConnectionHealth *VPNClientConnectionHealth +} + +// P2SVPNProfileParameters - Vpn Client Parameters for package generation. +type P2SVPNProfileParameters struct { + // VPN client authentication method. + AuthenticationMethod *AuthenticationMethod +} + +// PacketCapture - Parameters that define the create packet capture operation. +type PacketCapture struct { + // REQUIRED; Properties of the packet capture. + Properties *PacketCaptureParameters +} + +// PacketCaptureFilter - Filter that is applied to packet capture request. Multiple filters can be applied. +type PacketCaptureFilter struct { + // Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. + // "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently + // supported. Mixing ranges with multiple entries not currently supported. Default = null. + LocalIPAddress *string + + // Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple + // ranges not currently supported. Mixing ranges with multiple entries not + // currently supported. Default = null. + LocalPort *string + + // Protocol to be filtered on. + Protocol *PcProtocol + + // Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. + // "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently + // supported. Mixing ranges with multiple entries not currently supported. Default = null. + RemoteIPAddress *string + + // Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. + // Multiple ranges not currently supported. Mixing ranges with multiple entries not + // currently supported. Default = null. + RemotePort *string +} + +// PacketCaptureListResult - List of packet capture sessions. +type PacketCaptureListResult struct { + // Information about packet capture sessions. + Value []*PacketCaptureResult +} + +// PacketCaptureMachineScope - A list of AzureVMSS instances which can be included or excluded to run packet capture. If both +// included and excluded are empty, then the packet capture will run on all instances of AzureVMSS. +type PacketCaptureMachineScope struct { + // List of AzureVMSS instances which has to be excluded from the AzureVMSS from running packet capture. + Exclude []*string + + // List of AzureVMSS instances to run packet capture on. + Include []*string +} + +// PacketCaptureParameters - Parameters that define the create packet capture operation. +type PacketCaptureParameters struct { + // REQUIRED; The storage location for a packet capture session. + StorageLocation *PacketCaptureStorageLocation + + // REQUIRED; The ID of the targeted resource, only AzureVM and AzureVMSS as target type are currently supported. + Target *string + + // Number of bytes captured per packet, the remaining bytes are truncated. + BytesToCapturePerPacket *int64 + + // A list of packet capture filters. + Filters []*PacketCaptureFilter + + // A list of AzureVMSS instances which can be included or excluded to run packet capture. If both included and excluded are + // empty, then the packet capture will run on all instances of AzureVMSS. + Scope *PacketCaptureMachineScope + + // Target type of the resource provided. + TargetType *PacketCaptureTargetType + + // Maximum duration of the capture session in seconds. + TimeLimitInSeconds *int32 + + // Maximum size of the capture output. + TotalBytesPerSession *int64 +} + +// PacketCaptureQueryStatusResult - Status of packet capture session. +type PacketCaptureQueryStatusResult struct { + // The start time of the packet capture session. + CaptureStartTime *time.Time + + // The ID of the packet capture resource. + ID *string + + // The name of the packet capture resource. + Name *string + + // List of errors of packet capture session. + PacketCaptureError []*PcError + + // The status of the packet capture session. + PacketCaptureStatus *PcStatus + + // The reason the current packet capture session was stopped. + StopReason *string +} + +// PacketCaptureResult - Information about packet capture session. +type PacketCaptureResult struct { + // Properties of the packet capture result. + Properties *PacketCaptureResultProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; ID of the packet capture operation. + ID *string + + // READ-ONLY; Name of the packet capture session. + Name *string +} + +// PacketCaptureResultProperties - The properties of a packet capture session. +type PacketCaptureResultProperties struct { + // REQUIRED; The storage location for a packet capture session. + StorageLocation *PacketCaptureStorageLocation + + // REQUIRED; The ID of the targeted resource, only AzureVM and AzureVMSS as target type are currently supported. + Target *string + + // Number of bytes captured per packet, the remaining bytes are truncated. + BytesToCapturePerPacket *int64 + + // A list of packet capture filters. + Filters []*PacketCaptureFilter + + // A list of AzureVMSS instances which can be included or excluded to run packet capture. If both included and excluded are + // empty, then the packet capture will run on all instances of AzureVMSS. + Scope *PacketCaptureMachineScope + + // Target type of the resource provided. + TargetType *PacketCaptureTargetType + + // Maximum duration of the capture session in seconds. + TimeLimitInSeconds *int32 + + // Maximum size of the capture output. + TotalBytesPerSession *int64 + + // READ-ONLY; The provisioning state of the packet capture session. + ProvisioningState *ProvisioningState +} + +// PacketCaptureStorageLocation - The storage location for a packet capture session. +type PacketCaptureStorageLocation struct { + // A valid local path on the targeting VM. Must include the name of the capture file (*.cap). For linux virtual machine it + // must start with /var/captures. Required if no storage ID is provided, otherwise + // optional. + FilePath *string + + // The ID of the storage account to save the packet capture session. Required if no local file path is provided. + StorageID *string + + // The URI of the storage path to save the packet capture. Must be a well-formed URI describing the location to save the packet + // capture. + StoragePath *string +} + +// Parameters for an Action. +type Parameter struct { + // List of AS paths. + AsPath []*string + + // List of BGP communities. + Community []*string + + // List of route prefixes. + RoutePrefix []*string +} + +// PartnerManagedResourceProperties - Properties of the partner managed resource. +type PartnerManagedResourceProperties struct { + // READ-ONLY; The partner managed resource id. + ID *string + + // READ-ONLY; The partner managed ILB resource id + InternalLoadBalancerID *string + + // READ-ONLY; The partner managed SLB resource id + StandardLoadBalancerID *string +} + +// PatchObject - Object for patch operations. +type PatchObject struct { + // Resource tags. + Tags map[string]*string +} + +// PatchRouteFilter - Route Filter Resource. +type PatchRouteFilter struct { + // Resource ID. + ID *string + + // Properties of the route filter. + Properties *RouteFilterPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// PatchRouteFilterRule - Route Filter Rule Resource. +type PatchRouteFilterRule struct { + // Resource ID. + ID *string + + // Properties of the route filter rule. + Properties *RouteFilterRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string +} + +// PeerExpressRouteCircuitConnection - Peer Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. +type PeerExpressRouteCircuitConnection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the peer express route circuit connection. + Properties *PeerExpressRouteCircuitConnectionPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// PeerExpressRouteCircuitConnectionListResult - Response for ListPeeredConnections API service call retrieves all global +// reach peer circuit connections that belongs to a Private Peering for an ExpressRouteCircuit. +type PeerExpressRouteCircuitConnectionListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The global reach peer circuit connection associated with Private Peering in an ExpressRoute Circuit. + Value []*PeerExpressRouteCircuitConnection +} + +// PeerExpressRouteCircuitConnectionPropertiesFormat - Properties of the peer express route circuit connection. +type PeerExpressRouteCircuitConnectionPropertiesFormat struct { + // /29 IP address space to carve out Customer addresses for tunnels. + AddressPrefix *string + + // The resource guid of the authorization used for the express route circuit connection. + AuthResourceGUID *string + + // The name of the express route circuit connection resource. + ConnectionName *string + + // Reference to Express Route Circuit Private Peering Resource of the circuit. + ExpressRouteCircuitPeering *SubResource + + // Reference to Express Route Circuit Private Peering Resource of the peered circuit. + PeerExpressRouteCircuitPeering *SubResource + + // READ-ONLY; Express Route Circuit connection state. + CircuitConnectionStatus *CircuitConnectionStatus + + // READ-ONLY; The provisioning state of the peer express route circuit connection resource. + ProvisioningState *ProvisioningState +} + +// PeerRoute - Peer routing details. +type PeerRoute struct { + // READ-ONLY; The route's AS path sequence. + AsPath *string + + // READ-ONLY; The peer's local address. + LocalAddress *string + + // READ-ONLY; The route's network prefix. + Network *string + + // READ-ONLY; The route's next hop. + NextHop *string + + // READ-ONLY; The source this route was learned from. + Origin *string + + // READ-ONLY; The peer this route was learned from. + SourcePeer *string + + // READ-ONLY; The route's weight. + Weight *int32 +} + +// PolicySettings - Defines contents of a web application firewall global configuration. +type PolicySettings struct { + // If the action type is block, customer can override the response body. The body must be specified in base64 encoding. + CustomBlockResponseBody *string + + // If the action type is block, customer can override the response status code. + CustomBlockResponseStatusCode *int32 + + // Whether allow WAF to enforce file upload limits. + FileUploadEnforcement *bool + + // Maximum file upload size in Mb for WAF. + FileUploadLimitInMb *int32 + + // To scrub sensitive log fields + LogScrubbing *PolicySettingsLogScrubbing + + // Maximum request body size in Kb for WAF. + MaxRequestBodySizeInKb *int32 + + // The mode of the policy. + Mode *WebApplicationFirewallMode + + // Whether to allow WAF to check request Body. + RequestBodyCheck *bool + + // Whether allow WAF to enforce request body limits. + RequestBodyEnforcement *bool + + // Max inspection limit in KB for request body inspection for WAF. + RequestBodyInspectLimitInKB *int32 + + // The state of the policy. + State *WebApplicationFirewallEnabledState +} + +// PolicySettingsLogScrubbing - To scrub sensitive log fields +type PolicySettingsLogScrubbing struct { + // The rules that are applied to the logs for scrubbing. + ScrubbingRules []*WebApplicationFirewallScrubbingRules + + // State of the log scrubbing config. Default value is Enabled. + State *WebApplicationFirewallScrubbingState +} + +// PrepareNetworkPoliciesRequest - Details of PrepareNetworkPolicies for Subnet. +type PrepareNetworkPoliciesRequest struct { + // A list of NetworkIntentPolicyConfiguration. + NetworkIntentPolicyConfigurations []*IntentPolicyConfiguration + + // The name of the service for which subnet is being prepared for. + ServiceName *string +} + +// PrivateDNSZoneConfig - PrivateDnsZoneConfig resource. +type PrivateDNSZoneConfig struct { + // Name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the private dns zone configuration. + Properties *PrivateDNSZonePropertiesFormat +} + +// PrivateDNSZoneGroup - Private dns zone group resource. +type PrivateDNSZoneGroup struct { + // Resource ID. + ID *string + + // Name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the private dns zone group. + Properties *PrivateDNSZoneGroupPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// PrivateDNSZoneGroupListResult - Response for the ListPrivateDnsZoneGroups API service call. +type PrivateDNSZoneGroupListResult struct { + // A list of private dns zone group resources in a private endpoint. + Value []*PrivateDNSZoneGroup + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// PrivateDNSZoneGroupPropertiesFormat - Properties of the private dns zone group. +type PrivateDNSZoneGroupPropertiesFormat struct { + // A collection of private dns zone configurations of the private dns zone group. + PrivateDNSZoneConfigs []*PrivateDNSZoneConfig + + // READ-ONLY; The provisioning state of the private dns zone group resource. + ProvisioningState *ProvisioningState +} + +// PrivateDNSZonePropertiesFormat - Properties of the private dns zone configuration resource. +type PrivateDNSZonePropertiesFormat struct { + // The resource id of the private dns zone. + PrivateDNSZoneID *string + + // READ-ONLY; A collection of information regarding a recordSet, holding information to identify private resources. + RecordSets []*RecordSet +} + +// PrivateEndpoint - Private endpoint resource. +type PrivateEndpoint struct { + // The extended location of the load balancer. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the private endpoint. + Properties *PrivateEndpointProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// PrivateEndpointConnection resource. +type PrivateEndpointConnection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the private end point connection. + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The resource type. + Type *string +} + +// PrivateEndpointConnectionListResult - Response for the ListPrivateEndpointConnection API service call. +type PrivateEndpointConnectionListResult struct { + // A list of PrivateEndpointConnection resources for a specific private link service. + Value []*PrivateEndpointConnection + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// PrivateEndpointConnectionProperties - Properties of the PrivateEndpointConnectProperties. +type PrivateEndpointConnectionProperties struct { + // A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // READ-ONLY; The consumer link id. + LinkIdentifier *string + + // READ-ONLY; The resource of private end point. + PrivateEndpoint *PrivateEndpoint + + // READ-ONLY; The location of the private endpoint. + PrivateEndpointLocation *string + + // READ-ONLY; The provisioning state of the private endpoint connection resource. + ProvisioningState *ProvisioningState +} + +// PrivateEndpointIPConfiguration - An IP Configuration of the private endpoint. +type PrivateEndpointIPConfiguration struct { + // The name of the resource that is unique within a resource group. + Name *string + + // Properties of private endpoint IP configurations. + Properties *PrivateEndpointIPConfigurationProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The resource type. + Type *string +} + +// PrivateEndpointIPConfigurationProperties - Properties of an IP Configuration of the private endpoint. +type PrivateEndpointIPConfigurationProperties struct { + // The ID of a group obtained from the remote resource that this private endpoint should connect to. + GroupID *string + + // The member name of a group obtained from the remote resource that this private endpoint should connect to. + MemberName *string + + // A private ip address obtained from the private endpoint's subnet. + PrivateIPAddress *string +} + +// PrivateEndpointListResult - Response for the ListPrivateEndpoints API service call. +type PrivateEndpointListResult struct { + // A list of private endpoint resources in a resource group. + Value []*PrivateEndpoint + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// PrivateEndpointProperties - Properties of the private endpoint. +type PrivateEndpointProperties struct { + // Application security groups in which the private endpoint IP configuration is included. + ApplicationSecurityGroups []*ApplicationSecurityGroup + + // An array of custom dns configurations. + CustomDNSConfigs []*CustomDNSConfigPropertiesFormat + + // The custom name of the network interface attached to the private endpoint. + CustomNetworkInterfaceName *string + + // A list of IP configurations of the private endpoint. This will be used to map to the First Party Service's endpoints. + IPConfigurations []*PrivateEndpointIPConfiguration + + // A grouping of information about the connection to the remote resource. Used when the network admin does not have access + // to approve connections to the remote resource. + ManualPrivateLinkServiceConnections []*PrivateLinkServiceConnection + + // A grouping of information about the connection to the remote resource. + PrivateLinkServiceConnections []*PrivateLinkServiceConnection + + // The ID of the subnet from which the private IP will be allocated. + Subnet *Subnet + + // READ-ONLY; An array of references to the network interfaces created for this private endpoint. + NetworkInterfaces []*Interface + + // READ-ONLY; The provisioning state of the private endpoint resource. + ProvisioningState *ProvisioningState +} + +// PrivateLinkService - Private link service resource. +type PrivateLinkService struct { + // The extended location of the load balancer. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the private link service. + Properties *PrivateLinkServiceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// PrivateLinkServiceConnection resource. +type PrivateLinkServiceConnection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the private link service connection. + Properties *PrivateLinkServiceConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The resource type. + Type *string +} + +// PrivateLinkServiceConnectionProperties - Properties of the PrivateLinkServiceConnection. +type PrivateLinkServiceConnectionProperties struct { + // The ID(s) of the group(s) obtained from the remote resource that this private endpoint should connect to. + GroupIDs []*string + + // A collection of read-only information about the state of the connection to the remote resource. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // The resource id of private link service. + PrivateLinkServiceID *string + + // A message passed to the owner of the remote resource with this connection request. Restricted to 140 chars. + RequestMessage *string + + // READ-ONLY; The provisioning state of the private link service connection resource. + ProvisioningState *ProvisioningState +} + +// 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. + ActionsRequired *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 *string +} + +// PrivateLinkServiceIPConfiguration - The private link service ip configuration. +type PrivateLinkServiceIPConfiguration struct { + // Resource ID. + ID *string + + // The name of private link service ip configuration. + Name *string + + // Properties of the private link service ip configuration. + Properties *PrivateLinkServiceIPConfigurationProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The resource type. + Type *string +} + +// PrivateLinkServiceIPConfigurationProperties - Properties of private link service IP configuration. +type PrivateLinkServiceIPConfigurationProperties struct { + // Whether the ip configuration is primary or not. + Primary *bool + + // The private IP address of the IP configuration. + PrivateIPAddress *string + + // Whether the specific IP configuration is IPv4 or IPv6. Default is IPv4. + PrivateIPAddressVersion *IPVersion + + // The private IP address allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // The reference to the subnet resource. + Subnet *Subnet + + // READ-ONLY; The provisioning state of the private link service IP configuration resource. + ProvisioningState *ProvisioningState +} + +// PrivateLinkServiceListResult - Response for the ListPrivateLinkService API service call. +type PrivateLinkServiceListResult struct { + // A list of PrivateLinkService resources in a resource group. + Value []*PrivateLinkService + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// PrivateLinkServiceProperties - Properties of the private link service. +type PrivateLinkServiceProperties struct { + // The auto-approval list of the private link service. + AutoApproval *PrivateLinkServicePropertiesAutoApproval + + // Whether the private link service is enabled for proxy protocol or not. + EnableProxyProtocol *bool + + // The list of Fqdn. + Fqdns []*string + + // An array of private link service IP configurations. + IPConfigurations []*PrivateLinkServiceIPConfiguration + + // An array of references to the load balancer IP configurations. + LoadBalancerFrontendIPConfigurations []*FrontendIPConfiguration + + // The visibility list of the private link service. + Visibility *PrivateLinkServicePropertiesVisibility + + // READ-ONLY; The alias of the private link service. + Alias *string + + // READ-ONLY; An array of references to the network interfaces created for this private link service. + NetworkInterfaces []*Interface + + // READ-ONLY; An array of list about connections to the private endpoint. + PrivateEndpointConnections []*PrivateEndpointConnection + + // READ-ONLY; The provisioning state of the private link service resource. + ProvisioningState *ProvisioningState +} + +// PrivateLinkServicePropertiesAutoApproval - The auto-approval list of the private link service. +type PrivateLinkServicePropertiesAutoApproval struct { + // The list of subscriptions. + Subscriptions []*string +} + +// PrivateLinkServicePropertiesVisibility - The visibility list of the private link service. +type PrivateLinkServicePropertiesVisibility struct { + // The list of subscriptions. + Subscriptions []*string +} + +// PrivateLinkServiceVisibility - Response for the CheckPrivateLinkServiceVisibility API service call. +type PrivateLinkServiceVisibility struct { + // Private Link Service Visibility (True/False). + Visible *bool +} + +// Probe - A load balancer probe. +type Probe struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within the set of probes used by the load balancer. This name can be used to access + // the resource. + Name *string + + // Properties of load balancer probe. + Properties *ProbePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Type of the resource. + Type *string +} + +// ProbePropertiesFormat - Load balancer probe resource. +type ProbePropertiesFormat struct { + // REQUIRED; The port for communicating the probe. Possible values range from 1 to 65535, inclusive. + Port *int32 + + // REQUIRED; The protocol of the end point. If 'Tcp' is specified, a received ACK is required for the probe to be successful. + // If 'Http' or 'Https' is specified, a 200 OK response from the specifies URI is required + // for the probe to be successful. + Protocol *ProbeProtocol + + // The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly + // less than half the allocated timeout period (in seconds) which allows two full + // probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. + IntervalInSeconds *int32 + + // The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. + // This values allows endpoints to be taken out of rotation faster or slower than + // the typical times used in Azure. + NumberOfProbes *int32 + + // The number of consecutive successful or failed probes in order to allow or deny traffic from being delivered to this endpoint. + // After failing the number of consecutive probes equal to this value, the + // endpoint will be taken out of rotation and require the same number of successful consecutive probes to be placed back in + // rotation. + ProbeThreshold *int32 + + // The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is + // not allowed. There is no default value. + RequestPath *string + + // READ-ONLY; The load balancer rules that use this probe. + LoadBalancingRules []*SubResource + + // READ-ONLY; The provisioning state of the probe resource. + ProvisioningState *ProvisioningState +} + +// Profile - Network profile resource. +type Profile struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Network profile properties. + Properties *ProfilePropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ProfileListResult - Response for ListNetworkProfiles API service call. +type ProfileListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of network profiles that exist in a resource group. + Value []*Profile +} + +// ProfilePropertiesFormat - Network profile properties. +type ProfilePropertiesFormat struct { + // List of chid container network interface configurations. + ContainerNetworkInterfaceConfigurations []*ContainerNetworkInterfaceConfiguration + + // READ-ONLY; List of child container network interfaces. + ContainerNetworkInterfaces []*ContainerNetworkInterface + + // READ-ONLY; The provisioning state of the network profile resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the network profile resource. + ResourceGUID *string +} + +// PropagatedRouteTable - The list of RouteTables to advertise the routes to. +type PropagatedRouteTable struct { + // The list of resource ids of all the RouteTables. + IDs []*SubResource + + // The list of labels. + Labels []*string +} + +// PropagatedRouteTableNfv - Nfv version of the list of RouteTables to advertise the routes to. +type PropagatedRouteTableNfv struct { + // The list of resource ids of all the RouteTables. + IDs []*RoutingConfigurationNfvSubResource + + // The list of labels. + Labels []*string +} + +// ProtocolConfiguration - Configuration of the protocol. +type ProtocolConfiguration struct { + // HTTP configuration of the connectivity check. + HTTPConfiguration *HTTPConfiguration +} + +// PublicIPAddress - Public IP address resource. +type PublicIPAddress struct { + // The extended location of the public ip address. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Public IP address properties. + Properties *PublicIPAddressPropertiesFormat + + // The public IP address SKU. + SKU *PublicIPAddressSKU + + // Resource tags. + Tags map[string]*string + + // A list of availability zones denoting the IP allocated for the resource needs to come from. + Zones []*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// PublicIPAddressDNSSettings - Contains FQDN of the DNS record associated with the public IP address. +type PublicIPAddressDNSSettings struct { + // The domain name label. The concatenation of the domain name label and the regionalized DNS zone make up the fully qualified + // domain name associated with the public IP address. If a domain name label is + // specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. + DomainNameLabel *string + + // The domain name label scope. If a domain name label and a domain name label scope are specified, an A DNS record is created + // for the public IP in the Microsoft Azure DNS system with a hashed value + // includes in FQDN. + DomainNameLabelScope *PublicIPAddressDNSSettingsDomainNameLabelScope + + // The Fully Qualified Domain Name of the A DNS record associated with the public IP. This is the concatenation of the domainNameLabel + // and the regionalized DNS zone. + Fqdn *string + + // The reverse FQDN. A user-visible, fully qualified domain name that resolves to this public IP address. If the reverseFqdn + // is specified, then a PTR DNS record is created pointing from the IP address in + // the in-addr.arpa domain to the reverse FQDN. + ReverseFqdn *string +} + +// PublicIPAddressListResult - Response for ListPublicIpAddresses API service call. +type PublicIPAddressListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of public IP addresses that exists in a resource group. + Value []*PublicIPAddress +} + +// PublicIPAddressPropertiesFormat - Public IP address properties. +type PublicIPAddressPropertiesFormat struct { + // The FQDN of the DNS record associated with the public IP address. + DNSSettings *PublicIPAddressDNSSettings + + // The DDoS protection custom policy associated with the public IP address. + DdosSettings *DdosSettings + + // Specify what happens to the public IP address when the VM using it is deleted + DeleteOption *DeleteOptions + + // The IP address associated with the public IP address resource. + IPAddress *string + + // The list of tags associated with the public IP address. + IPTags []*IPTag + + // The idle timeout of the public IP address. + IdleTimeoutInMinutes *int32 + + // The linked public IP address of the public IP address resource. + LinkedPublicIPAddress *PublicIPAddress + + // Migration phase of Public IP Address. + MigrationPhase *PublicIPAddressMigrationPhase + + // The NatGateway for the Public IP address. + NatGateway *NatGateway + + // The public IP address version. + PublicIPAddressVersion *IPVersion + + // The public IP address allocation method. + PublicIPAllocationMethod *IPAllocationMethod + + // The Public IP Prefix this Public IP Address should be allocated from. + PublicIPPrefix *SubResource + + // The service public IP address of the public IP address resource. + ServicePublicIPAddress *PublicIPAddress + + // READ-ONLY; The IP configuration associated with the public IP address. + IPConfiguration *IPConfiguration + + // READ-ONLY; The provisioning state of the public IP address resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the public IP address resource. + ResourceGUID *string +} + +// PublicIPAddressSKU - SKU of a public IP address. +type PublicIPAddressSKU struct { + // Name of a public IP address SKU. + Name *PublicIPAddressSKUName + + // Tier of a public IP address SKU. + Tier *PublicIPAddressSKUTier +} + +// PublicIPDdosProtectionStatusResult - Response for GetPublicIpAddressDdosProtectionStatusOperation API service call. +type PublicIPDdosProtectionStatusResult struct { + // DDoS protection plan Resource Id of a if IP address is protected through a plan. + DdosProtectionPlanID *string + + // Value indicating whether the IP address is DDoS workload protected or not. + IsWorkloadProtected *IsWorkloadProtected + + // IP Address of the Public IP Resource + PublicIPAddress *string + + // Public IP ARM resource ID + PublicIPAddressID *string +} + +// PublicIPPrefix - Public IP prefix resource. +type PublicIPPrefix struct { + // The extended location of the public ip address. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Public IP prefix properties. + Properties *PublicIPPrefixPropertiesFormat + + // The public IP prefix SKU. + SKU *PublicIPPrefixSKU + + // Resource tags. + Tags map[string]*string + + // A list of availability zones denoting the IP allocated for the resource needs to come from. + Zones []*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// PublicIPPrefixListResult - Response for ListPublicIpPrefixes API service call. +type PublicIPPrefixListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of public IP prefixes that exists in a resource group. + Value []*PublicIPPrefix +} + +// PublicIPPrefixPropertiesFormat - Public IP prefix properties. +type PublicIPPrefixPropertiesFormat struct { + // The customIpPrefix that this prefix is associated with. + CustomIPPrefix *SubResource + + // The list of tags associated with the public IP prefix. + IPTags []*IPTag + + // NatGateway of Public IP Prefix. + NatGateway *NatGateway + + // The Length of the Public IP Prefix. + PrefixLength *int32 + + // The public IP address version. + PublicIPAddressVersion *IPVersion + + // READ-ONLY; The allocated Prefix. + IPPrefix *string + + // READ-ONLY; The reference to load balancer frontend IP configuration associated with the public IP prefix. + LoadBalancerFrontendIPConfiguration *SubResource + + // READ-ONLY; The provisioning state of the public IP prefix resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The list of all referenced PublicIPAddresses. + PublicIPAddresses []*ReferencedPublicIPAddress + + // READ-ONLY; The resource GUID property of the public IP prefix resource. + ResourceGUID *string +} + +// PublicIPPrefixSKU - SKU of a public IP prefix. +type PublicIPPrefixSKU struct { + // Name of a public IP prefix SKU. + Name *PublicIPPrefixSKUName + + // Tier of a public IP prefix SKU. + Tier *PublicIPPrefixSKUTier +} + +// QosDefinition - Quality of Service defines the traffic configuration between endpoints. Mandatory to have one marking. +type QosDefinition struct { + // Destination IP ranges. + DestinationIPRanges []*QosIPRange + + // Destination port ranges. + DestinationPortRanges []*QosPortRange + + // List of markings to be used in the configuration. + Markings []*int32 + + // RNM supported protocol types. + Protocol *ProtocolType + + // Source IP ranges. + SourceIPRanges []*QosIPRange + + // Sources port ranges. + SourcePortRanges []*QosPortRange +} + +// QosIPRange - Qos Traffic Profiler IP Range properties. +type QosIPRange struct { + // End IP Address. + EndIP *string + + // Start IP Address. + StartIP *string +} + +// QosPortRange - Qos Traffic Profiler Port range properties. +type QosPortRange struct { + // Qos Port Range end. + End *int32 + + // Qos Port Range start. + Start *int32 +} + +// QueryInboundNatRulePortMappingRequest - The request for a QueryInboundNatRulePortMapping API. Either IpConfiguration or +// IpAddress should be set +type QueryInboundNatRulePortMappingRequest struct { + // IP address set in load balancer backend address. + IPAddress *string + + // NetworkInterfaceIPConfiguration set in load balancer backend address. + IPConfiguration *SubResource +} + +// QueryRequestOptions - Query Request Options +type QueryRequestOptions struct { + // When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current + // request) to retrieve the next page of data. + SkipToken *string +} + +// QueryResults - Query result +type QueryResults struct { + // Number of total records matching the query. + MatchingRecordsCount *int64 + + // Array containing the results of the query + Signatures []*SingleQueryResult +} + +// QueryTroubleshootingParameters - Parameters that define the resource to query the troubleshooting result. +type QueryTroubleshootingParameters struct { + // REQUIRED; The target resource ID to query the troubleshooting result. + TargetResourceID *string +} + +// RadiusServer - Radius Server Settings. +type RadiusServer struct { + // REQUIRED; The address of this radius server. + RadiusServerAddress *string + + // The initial score assigned to this radius server. + RadiusServerScore *int64 + + // The secret used for this radius server. + RadiusServerSecret *string +} + +// RecordSet - A collective group of information about the record set information. +type RecordSet struct { + // Fqdn that resolves to private endpoint ip address. + Fqdn *string + + // The private ip address of the private endpoint. + IPAddresses []*string + + // Recordset name. + RecordSetName *string + + // Resource record type. + RecordType *string + + // Recordset time to live. + TTL *int32 + + // READ-ONLY; The provisioning state of the recordset. + ProvisioningState *ProvisioningState +} + +// ReferencedPublicIPAddress - Reference to a public IP address. +type ReferencedPublicIPAddress struct { + // The PublicIPAddress Reference. + ID *string +} + +// Resource - Common resource representation. +type Resource struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ResourceNavigationLink resource. +type ResourceNavigationLink struct { + // Resource ID. + ID *string + + // Name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Resource navigation link properties format. + Properties *ResourceNavigationLinkFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// ResourceNavigationLinkFormat - Properties of ResourceNavigationLink. +type ResourceNavigationLinkFormat struct { + // Link to the external resource. + Link *string + + // Resource type of the linked resource. + LinkedResourceType *string + + // READ-ONLY; The provisioning state of the resource navigation link resource. + ProvisioningState *ProvisioningState +} + +// ResourceNavigationLinksListResult - Response for ResourceNavigationLinks_List operation. +type ResourceNavigationLinksListResult struct { + // The resource navigation links in a subnet. + Value []*ResourceNavigationLink + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ResourceSet - The base resource set for visibility and auto-approval. +type ResourceSet struct { + // The list of subscriptions. + Subscriptions []*string +} + +// RetentionPolicyParameters - Parameters that define the retention policy for flow log. +type RetentionPolicyParameters struct { + // Number of days to retain flow log records. + Days *int32 + + // Flag to enable/disable retention. + Enabled *bool +} + +// Route resource. +type Route struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the route. + Properties *RoutePropertiesFormat + + // The type of the resource. + Type *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// RouteFilter - Route Filter Resource. +type RouteFilter struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the route filter. + Properties *RouteFilterPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// RouteFilterListResult - Response for the ListRouteFilters API service call. +type RouteFilterListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of route filters in a resource group. + Value []*RouteFilter +} + +// RouteFilterPropertiesFormat - Route Filter Resource. +type RouteFilterPropertiesFormat struct { + // Collection of RouteFilterRules contained within a route filter. + Rules []*RouteFilterRule + + // READ-ONLY; A collection of references to express route circuit ipv6 peerings. + IPv6Peerings []*ExpressRouteCircuitPeering + + // READ-ONLY; A collection of references to express route circuit peerings. + Peerings []*ExpressRouteCircuitPeering + + // READ-ONLY; The provisioning state of the route filter resource. + ProvisioningState *ProvisioningState +} + +// RouteFilterRule - Route Filter Rule Resource. +type RouteFilterRule struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the route filter rule. + Properties *RouteFilterRulePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// RouteFilterRuleListResult - Response for the ListRouteFilterRules API service call. +type RouteFilterRuleListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of RouteFilterRules in a resource group. + Value []*RouteFilterRule +} + +// RouteFilterRulePropertiesFormat - Route Filter Rule Resource. +type RouteFilterRulePropertiesFormat struct { + // REQUIRED; The access type of the rule. + Access *Access + + // REQUIRED; The collection for bgp community values to filter on. e.g. ['12076:5010','12076:5020']. + Communities []*string + + // REQUIRED; The rule type of the rule. + RouteFilterRuleType *RouteFilterRuleType + + // READ-ONLY; The provisioning state of the route filter rule resource. + ProvisioningState *ProvisioningState +} + +// RouteListResult - Response for the ListRoute API service call. +type RouteListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of routes in a resource group. + Value []*Route +} + +// RouteMap - The RouteMap child resource of a Virtual hub. +type RouteMap struct { + // Resource ID. + ID *string + + // Properties of the RouteMap resource. + Properties *RouteMapProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// RouteMapProperties - Properties of RouteMap resource +type RouteMapProperties struct { + // List of connections which have this RoutMap associated for inbound traffic. + AssociatedInboundConnections []*string + + // List of connections which have this RoutMap associated for outbound traffic. + AssociatedOutboundConnections []*string + + // List of RouteMap rules to be applied. + Rules []*RouteMapRule + + // READ-ONLY; The provisioning state of the RouteMap resource. + ProvisioningState *ProvisioningState +} + +// RouteMapRule - A RouteMap Rule. +type RouteMapRule struct { + // List of actions which will be applied on a match. + Actions []*Action + + // List of matching criterion which will be applied to traffic. + MatchCriteria []*Criterion + + // The unique name for the rule. + Name *string + + // Next step after rule is evaluated. Current supported behaviors are 'Continue'(to next rule) and 'Terminate'. + NextStepIfMatched *NextStep +} + +// RoutePropertiesFormat - Route resource. +type RoutePropertiesFormat struct { + // REQUIRED; The type of Azure hop the packet should be sent to. + NextHopType *RouteNextHopType + + // The destination CIDR to which the route applies. + AddressPrefix *string + + // A value indicating whether this route overrides overlapping BGP routes regardless of LPM. + HasBgpOverride *bool + + // The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. + NextHopIPAddress *string + + // READ-ONLY; The provisioning state of the route resource. + ProvisioningState *ProvisioningState +} + +// RouteTable - Route table resource. +type RouteTable struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the route table. + Properties *RouteTablePropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// RouteTableListResult - Response for the ListRouteTable API service call. +type RouteTableListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of route tables in a resource group. + Value []*RouteTable +} + +// RouteTablePropertiesFormat - Route Table resource. +type RouteTablePropertiesFormat struct { + // Whether to disable the routes learned by BGP on that route table. True means disable. + DisableBgpRoutePropagation *bool + + // Collection of routes contained within a route table. + Routes []*Route + + // READ-ONLY; The provisioning state of the route table resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the route table. + ResourceGUID *string + + // READ-ONLY; A collection of references to subnets. + Subnets []*Subnet +} + +// RoutingConfiguration - Routing Configuration indicating the associated and propagated route tables for this connection. +type RoutingConfiguration struct { + // The resource id RouteTable associated with this RoutingConfiguration. + AssociatedRouteTable *SubResource + + // The resource id of the RouteMap associated with this RoutingConfiguration for inbound learned routes. + InboundRouteMap *SubResource + + // The resource id of theRouteMap associated with this RoutingConfiguration for outbound advertised routes. + OutboundRouteMap *SubResource + + // The list of RouteTables to advertise the routes to. + PropagatedRouteTables *PropagatedRouteTable + + // List of routes that control routing from VirtualHub into a virtual network connection. + VnetRoutes *VnetRoute +} + +// RoutingConfigurationNfv - NFV version of Routing Configuration indicating the associated and propagated route tables for +// this connection. +type RoutingConfigurationNfv struct { + // The resource id RouteTable associated with this RoutingConfiguration. + AssociatedRouteTable *RoutingConfigurationNfvSubResource + + // The resource id of the RouteMap associated with this RoutingConfiguration for inbound learned routes. + InboundRouteMap *RoutingConfigurationNfvSubResource + + // The resource id of the RouteMap associated with this RoutingConfiguration for outbound advertised routes. + OutboundRouteMap *RoutingConfigurationNfvSubResource + + // The list of RouteTables to advertise the routes to. + PropagatedRouteTables *PropagatedRouteTableNfv +} + +// RoutingConfigurationNfvSubResource - Reference to RouteTableV3 associated with the connection. +type RoutingConfigurationNfvSubResource struct { + // Resource ID. + ResourceURI *string +} + +// RoutingIntent - The routing intent child resource of a Virtual hub. +type RoutingIntent struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the RoutingIntent resource. + Properties *RoutingIntentProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// RoutingIntentProperties - The properties of a RoutingIntent resource. +type RoutingIntentProperties struct { + // List of routing policies. + RoutingPolicies []*RoutingPolicy + + // READ-ONLY; The provisioning state of the RoutingIntent resource. + ProvisioningState *ProvisioningState +} + +// RoutingPolicy - The routing policy object used in a RoutingIntent resource. +type RoutingPolicy struct { + // REQUIRED; List of all destinations which this routing policy is applicable to (for example: Internet, PrivateTraffic). + Destinations []*string + + // REQUIRED; The unique name for the routing policy. + Name *string + + // REQUIRED; The next hop resource id on which this routing policy is applicable to. + NextHop *string +} + +// Rule of type network. +type Rule struct { + // REQUIRED; Rule Type. + RuleType *FirewallPolicyRuleType + + // Description of the rule. + Description *string + + // List of destination IP addresses or Service Tags. + DestinationAddresses []*string + + // List of destination FQDNs. + DestinationFqdns []*string + + // List of destination IpGroups for this rule. + DestinationIPGroups []*string + + // List of destination ports. + DestinationPorts []*string + + // Array of FirewallPolicyRuleNetworkProtocols. + IPProtocols []*FirewallPolicyRuleNetworkProtocol + + // Name of the rule. + Name *string + + // List of source IP addresses for this rule. + SourceAddresses []*string + + // List of source IpGroups for this rule. + SourceIPGroups []*string +} + +// GetFirewallPolicyRule implements the FirewallPolicyRuleClassification interface for type Rule. +func (r *Rule) GetFirewallPolicyRule() *FirewallPolicyRule { + return &FirewallPolicyRule{ + Description: r.Description, + Name: r.Name, + RuleType: r.RuleType, + } +} + +// SKU - The sku of this Bastion Host. +type SKU struct { + // The name of this Bastion Host. + Name *BastionHostSKUName +} + +// ScopeConnection - The Scope Connections resource +type ScopeConnection struct { + // The scope connection properties + Properties *ScopeConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// ScopeConnectionListResult - List of scope connections. +type ScopeConnectionListResult struct { + // Gets the URL to get the next page of results. + NextLink *string + + // List of scope connections. + Value []*ScopeConnection +} + +// ScopeConnectionProperties - Scope connection. +type ScopeConnectionProperties struct { + // A description of the scope connection. + Description *string + + // Resource ID. + ResourceID *string + + // Tenant ID. + TenantID *string + + // READ-ONLY; Connection State + ConnectionState *ScopeConnectionState +} + +// SecurityAdminConfiguration - Defines the security admin configuration +type SecurityAdminConfiguration struct { + // Indicates the properties for the network manager security admin configuration. + Properties *SecurityAdminConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// SecurityAdminConfigurationListResult - A list of network manager security admin configurations +type SecurityAdminConfigurationListResult struct { + // Gets the URL to get the next page of results. + NextLink *string + + // Gets a page of security admin configurations + Value []*SecurityAdminConfiguration +} + +// SecurityAdminConfigurationPropertiesFormat - Defines the security admin configuration properties. +type SecurityAdminConfigurationPropertiesFormat struct { + // Enum list of network intent policy based services. + ApplyOnNetworkIntentPolicyBasedServices []*NetworkIntentPolicyBasedService + + // A description of the security configuration. + Description *string + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Unique identifier for this resource. + ResourceGUID *string +} + +// SecurityGroup - NetworkSecurityGroup resource. +type SecurityGroup struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the network security group. + Properties *SecurityGroupPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// SecurityGroupListResult - Response for ListNetworkSecurityGroups API service call. +type SecurityGroupListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of NetworkSecurityGroup resources. + Value []*SecurityGroup +} + +// SecurityGroupNetworkInterface - Network interface and all its associated security rules. +type SecurityGroupNetworkInterface struct { + // ID of the network interface. + ID *string + + // All security rules associated with the network interface. + SecurityRuleAssociations *SecurityRuleAssociations +} + +// SecurityGroupPropertiesFormat - Network Security Group resource. +type SecurityGroupPropertiesFormat struct { + // When enabled, flows created from Network Security Group connections will be re-evaluated when rules are updates. Initial + // enablement will trigger re-evaluation. + FlushConnection *bool + + // A collection of security rules of the network security group. + SecurityRules []*SecurityRule + + // READ-ONLY; The default security rules of network security group. + DefaultSecurityRules []*SecurityRule + + // READ-ONLY; A collection of references to flow log resources. + FlowLogs []*FlowLog + + // READ-ONLY; A collection of references to network interfaces. + NetworkInterfaces []*Interface + + // READ-ONLY; The provisioning state of the network security group resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the network security group resource. + ResourceGUID *string + + // READ-ONLY; A collection of references to subnets. + Subnets []*Subnet +} + +// SecurityGroupResult - Network configuration diagnostic result corresponded provided traffic query. +type SecurityGroupResult struct { + // The network traffic is allowed or denied. + SecurityRuleAccessResult *SecurityRuleAccess + + // READ-ONLY; List of results network security groups diagnostic. + EvaluatedNetworkSecurityGroups []*EvaluatedNetworkSecurityGroup +} + +// SecurityGroupViewParameters - Parameters that define the VM to check security groups for. +type SecurityGroupViewParameters struct { + // REQUIRED; ID of the target VM. + TargetResourceID *string +} + +// SecurityGroupViewResult - The information about security rules applied to the specified VM. +type SecurityGroupViewResult struct { + // List of network interfaces on the specified VM. + NetworkInterfaces []*SecurityGroupNetworkInterface +} + +// SecurityPartnerProvider - Security Partner Provider resource. +type SecurityPartnerProvider struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the Security Partner Provider. + Properties *SecurityPartnerProviderPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// SecurityPartnerProviderListResult - Response for ListSecurityPartnerProviders API service call. +type SecurityPartnerProviderListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Security Partner Providers in a resource group. + Value []*SecurityPartnerProvider +} + +// SecurityPartnerProviderPropertiesFormat - Properties of the Security Partner Provider. +type SecurityPartnerProviderPropertiesFormat struct { + // The security provider name. + SecurityProviderName *SecurityProviderName + + // The virtualHub to which the Security Partner Provider belongs. + VirtualHub *SubResource + + // READ-ONLY; The connection status with the Security Partner Provider. + ConnectionStatus *SecurityPartnerProviderConnectionStatus + + // READ-ONLY; The provisioning state of the Security Partner Provider resource. + ProvisioningState *ProvisioningState +} + +// SecurityRule - Network security rule. +type SecurityRule struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the security rule. + Properties *SecurityRulePropertiesFormat + + // The type of the resource. + Type *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// SecurityRuleAssociations - All security rules associated with the network interface. +type SecurityRuleAssociations struct { + // Collection of default security rules of the network security group. + DefaultSecurityRules []*SecurityRule + + // Collection of effective security rules. + EffectiveSecurityRules []*EffectiveNetworkSecurityRule + + // Network interface and it's custom security rules. + NetworkInterfaceAssociation *InterfaceAssociation + + // Subnet and it's custom security rules. + SubnetAssociation *SubnetAssociation +} + +// SecurityRuleListResult - Response for ListSecurityRule API service call. Retrieves all security rules that belongs to a +// network security group. +type SecurityRuleListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The security rules in a network security group. + Value []*SecurityRule +} + +// SecurityRulePropertiesFormat - Security rule resource. +type SecurityRulePropertiesFormat struct { + // REQUIRED; The network traffic is allowed or denied. + Access *SecurityRuleAccess + + // REQUIRED; The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. + Direction *SecurityRuleDirection + + // REQUIRED; The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each + // rule in the collection. The lower the priority number, the higher the priority of the rule. + Priority *int32 + + // REQUIRED; Network protocol this rule applies to. + Protocol *SecurityRuleProtocol + + // A description for this rule. Restricted to 140 chars. + Description *string + + // The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default + // tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also + // be used. + DestinationAddressPrefix *string + + // The destination address prefixes. CIDR or destination IP ranges. + DestinationAddressPrefixes []*string + + // The application security group specified as destination. + DestinationApplicationSecurityGroups []*ApplicationSecurityGroup + + // The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. + DestinationPortRange *string + + // The destination port ranges. + DestinationPortRanges []*string + + // The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', + // 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress + // rule, specifies where network traffic originates from. + SourceAddressPrefix *string + + // The CIDR or source IP ranges. + SourceAddressPrefixes []*string + + // The application security group specified as source. + SourceApplicationSecurityGroups []*ApplicationSecurityGroup + + // The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. + SourcePortRange *string + + // The source port ranges. + SourcePortRanges []*string + + // READ-ONLY; The provisioning state of the security rule resource. + ProvisioningState *ProvisioningState +} + +// SecurityRulesEvaluationResult - Network security rules evaluation result. +type SecurityRulesEvaluationResult struct { + // Value indicating whether destination is matched. + DestinationMatched *bool + + // Value indicating whether destination port is matched. + DestinationPortMatched *bool + + // Name of the network security rule. + Name *string + + // Value indicating whether protocol is matched. + ProtocolMatched *bool + + // Value indicating whether source is matched. + SourceMatched *bool + + // Value indicating whether source port is matched. + SourcePortMatched *bool +} + +// ServiceAssociationLink resource. +type ServiceAssociationLink struct { + // Resource ID. + ID *string + + // Name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Resource navigation link properties format. + Properties *ServiceAssociationLinkPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// ServiceAssociationLinkPropertiesFormat - Properties of ServiceAssociationLink. +type ServiceAssociationLinkPropertiesFormat struct { + // If true, the resource can be deleted. + AllowDelete *bool + + // Link to the external resource. + Link *string + + // Resource type of the linked resource. + LinkedResourceType *string + + // A list of locations. + Locations []*string + + // READ-ONLY; The provisioning state of the service association link resource. + ProvisioningState *ProvisioningState +} + +// ServiceAssociationLinksListResult - Response for ServiceAssociationLinks_List operation. +type ServiceAssociationLinksListResult struct { + // The service association links in a subnet. + Value []*ServiceAssociationLink + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ServiceDelegationPropertiesFormat - Properties of a service delegation. +type ServiceDelegationPropertiesFormat struct { + // The name of the service to whom the subnet should be delegated (e.g. Microsoft.Sql/servers). + ServiceName *string + + // READ-ONLY; The actions permitted to the service upon delegation. + Actions []*string + + // READ-ONLY; The provisioning state of the service delegation resource. + ProvisioningState *ProvisioningState +} + +// ServiceEndpointPolicy - Service End point policy resource. +type ServiceEndpointPolicy struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the service end point policy. + Properties *ServiceEndpointPolicyPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Kind of service endpoint policy. This is metadata used for the Azure portal experience. + Kind *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// ServiceEndpointPolicyDefinition - Service Endpoint policy definitions. +type ServiceEndpointPolicyDefinition struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the service endpoint policy definition. + Properties *ServiceEndpointPolicyDefinitionPropertiesFormat + + // The type of the resource. + Type *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// ServiceEndpointPolicyDefinitionListResult - Response for ListServiceEndpointPolicyDefinition API service call. Retrieves +// all service endpoint policy definition that belongs to a service endpoint policy. +type ServiceEndpointPolicyDefinitionListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The service endpoint policy definition in a service endpoint policy. + Value []*ServiceEndpointPolicyDefinition +} + +// ServiceEndpointPolicyDefinitionPropertiesFormat - Service Endpoint policy definition resource. +type ServiceEndpointPolicyDefinitionPropertiesFormat struct { + // A description for this rule. Restricted to 140 chars. + Description *string + + // Service endpoint name. + Service *string + + // A list of service resources. + ServiceResources []*string + + // READ-ONLY; The provisioning state of the service endpoint policy definition resource. + ProvisioningState *ProvisioningState +} + +// ServiceEndpointPolicyListResult - Response for ListServiceEndpointPolicies API service call. +type ServiceEndpointPolicyListResult struct { + // A list of ServiceEndpointPolicy resources. + Value []*ServiceEndpointPolicy + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ServiceEndpointPolicyPropertiesFormat - Service Endpoint Policy resource. +type ServiceEndpointPolicyPropertiesFormat struct { + // A collection of contextual service endpoint policy. + ContextualServiceEndpointPolicies []*string + + // The alias indicating if the policy belongs to a service + ServiceAlias *string + + // A collection of service endpoint policy definitions of the service endpoint policy. + ServiceEndpointPolicyDefinitions []*ServiceEndpointPolicyDefinition + + // READ-ONLY; The provisioning state of the service endpoint policy resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the service endpoint policy resource. + ResourceGUID *string + + // READ-ONLY; A collection of references to subnets. + Subnets []*Subnet +} + +// ServiceEndpointPropertiesFormat - The service endpoint properties. +type ServiceEndpointPropertiesFormat struct { + // A list of locations. + Locations []*string + + // The type of the endpoint service. + Service *string + + // READ-ONLY; The provisioning state of the service endpoint resource. + ProvisioningState *ProvisioningState +} + +// ServiceTagInformation - The service tag information. +type ServiceTagInformation struct { + // READ-ONLY; The ID of service tag. + ID *string + + // READ-ONLY; The name of service tag. + Name *string + + // READ-ONLY; Properties of the service tag information. + Properties *ServiceTagInformationPropertiesFormat + + // READ-ONLY; The iteration number of service tag object for region. + ServiceTagChangeNumber *string +} + +// ServiceTagInformationListResult - Response for Get ServiceTagInformation API service call. Retrieves the list of service +// tag information resources. +type ServiceTagInformationListResult struct { + // The list of service tag information resources. + Value []*ServiceTagInformation + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// ServiceTagInformationPropertiesFormat - Properties of the service tag information. +type ServiceTagInformationPropertiesFormat struct { + // READ-ONLY; The list of IP address prefixes. + AddressPrefixes []*string + + // READ-ONLY; The iteration number of service tag. + ChangeNumber *string + + // READ-ONLY; The region of service tag. + Region *string + + // READ-ONLY; The state of the service tag. + State *string + + // READ-ONLY; The name of system service. + SystemService *string +} + +// ServiceTagsListResult - Response for the ListServiceTags API service call. +type ServiceTagsListResult struct { + // READ-ONLY; The iteration number. + ChangeNumber *string + + // READ-ONLY; The name of the cloud. + Cloud *string + + // READ-ONLY; The ID of the cloud. + ID *string + + // READ-ONLY; The name of the cloud. + Name *string + + // READ-ONLY; The URL to get next page of service tag information resources. + NextLink *string + + // READ-ONLY; The azure resource type. + Type *string + + // READ-ONLY; The list of service tag information resources. + Values []*ServiceTagInformation +} + +// SessionIDs - List of session IDs. +type SessionIDs struct { + // List of session IDs. + SessionIDs []*string +} + +// SignatureOverridesFilterValuesQuery - Describes the filter values possibles for a given column +type SignatureOverridesFilterValuesQuery struct { + // Describes the name of the column which values will be returned + FilterName *string +} + +// SignatureOverridesFilterValuesResponse - Describes the list of all possible values for a specific filter value +type SignatureOverridesFilterValuesResponse struct { + // Describes the possible values + FilterValues []*string +} + +// SignaturesOverrides - Contains all specific policy signatures overrides for the IDPS +type SignaturesOverrides struct { + // Will contain the resource id of the signature override resource + ID *string + + // Contains the name of the resource (default) + Name *string + + // Will contain the properties of the resource (the actual signature overrides) + Properties *SignaturesOverridesProperties + + // Will contain the type of the resource: Microsoft.Network/firewallPolicies/intrusionDetectionSignaturesOverrides + Type *string +} + +// SignaturesOverridesList - Describes an object containing an array with a single item +type SignaturesOverridesList struct { + // Describes a list consisting exactly one item describing the policy's signature override status + Value []*SignaturesOverrides +} + +// SignaturesOverridesProperties - Will contain the properties of the resource (the actual signature overrides) +type SignaturesOverridesProperties struct { + // Dictionary of + Signatures map[string]*string +} + +type SingleQueryResult struct { + // Describes what is the signature enforces + Description *string + + // Describes the list of destination ports related to this signature + DestinationPorts []*string + + // Describes in which direction signature is being enforced: 0 - Inbound, 1 - OutBound, 2 - Bidirectional + Direction *FirewallPolicyIDPSSignatureDirection + + // Describes the groups the signature belongs to + Group *string + + // Describes if this override is inherited from base policy or not + InheritedFromParentPolicy *bool + + // Describes the last updated time of the signature (provided from 3rd party vendor) + LastUpdated *string + + // The current mode enforced, 0 - Disabled, 1 - Alert, 2 -Deny + Mode *FirewallPolicyIDPSSignatureMode + + // Describes the protocol the signatures is being enforced in + Protocol *string + + // Describes the severity of signature: 1 - Low, 2 - Medium, 3 - High + Severity *FirewallPolicyIDPSSignatureSeverity + + // The ID of the signature + SignatureID *int32 + + // Describes the list of source ports related to this signature + SourcePorts []*string +} + +// StaticMember Item. +type StaticMember struct { + // The Static Member properties + Properties *StaticMemberProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource ID. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; The system metadata related to this resource. + SystemData *SystemData + + // READ-ONLY; Resource type. + Type *string +} + +// StaticMemberListResult - Result of the request to list StaticMember. It contains a list of groups and a URL link to get +// the next set of results. +type StaticMemberListResult struct { + // Gets the URL to get the next set of results. + NextLink *string + + // Gets a page of StaticMember + Value []*StaticMember +} + +// StaticMemberProperties - Properties of static member. +type StaticMemberProperties struct { + // Resource Id. + ResourceID *string + + // READ-ONLY; The provisioning state of the scope assignment resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Resource region. + Region *string +} + +// StaticRoute - List of all Static Routes. +type StaticRoute struct { + // List of all address prefixes. + AddressPrefixes []*string + + // The name of the StaticRoute that is unique within a VnetRoute. + Name *string + + // The ip address of the next hop. + NextHopIPAddress *string +} + +// StaticRoutesConfig - Configuration for static routes on this HubVnetConnectionConfiguration for static routes on this HubVnetConnection. +type StaticRoutesConfig struct { + // Parameter determining whether NVA in spoke vnet is bypassed for traffic with destination in spoke. + VnetLocalRouteOverrideCriteria *VnetLocalRouteOverrideCriteria + + // READ-ONLY; Boolean indicating whether static routes on this connection are automatically propagate to route tables which + // this connection propagates to. + PropagateStaticRoutes *bool +} + +// SubResource - Reference to another subresource. +type SubResource struct { + // Resource ID. + ID *string +} + +// Subnet in a virtual network resource. +type Subnet struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the subnet. + Properties *SubnetPropertiesFormat + + // Resource type. + Type *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// SubnetAssociation - Subnet and it's custom security rules. +type SubnetAssociation struct { + // Collection of custom security rules. + SecurityRules []*SecurityRule + + // READ-ONLY; Subnet ID. + ID *string +} + +// SubnetListResult - Response for ListSubnets API service callRetrieves all subnet that belongs to a virtual network. +type SubnetListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The subnets in a virtual network. + Value []*Subnet +} + +// SubnetPropertiesFormat - Properties of the subnet. +type SubnetPropertiesFormat struct { + // The address prefix for the subnet. + AddressPrefix *string + + // List of address prefixes for the subnet. + AddressPrefixes []*string + + // Application gateway IP configurations of virtual network resource. + ApplicationGatewayIPConfigurations []*ApplicationGatewayIPConfiguration + + // Set this property to false to disable default outbound connectivity for all VMs in the subnet. This property can only be + // set at the time of subnet creation and cannot be updated for an existing + // subnet. + DefaultOutboundAccess *bool + + // An array of references to the delegations on the subnet. + Delegations []*Delegation + + // Array of IpAllocation which reference this subnet. + IPAllocations []*SubResource + + // Nat gateway associated with this subnet. + NatGateway *SubResource + + // The reference to the NetworkSecurityGroup resource. + NetworkSecurityGroup *SecurityGroup + + // Enable or Disable apply network policies on private end point in the subnet. + PrivateEndpointNetworkPolicies *VirtualNetworkPrivateEndpointNetworkPolicies + + // Enable or Disable apply network policies on private link service in the subnet. + PrivateLinkServiceNetworkPolicies *VirtualNetworkPrivateLinkServiceNetworkPolicies + + // The reference to the RouteTable resource. + RouteTable *RouteTable + + // An array of service endpoint policies. + ServiceEndpointPolicies []*ServiceEndpointPolicy + + // An array of service endpoints. + ServiceEndpoints []*ServiceEndpointPropertiesFormat + + // READ-ONLY; Array of IP configuration profiles which reference this subnet. + IPConfigurationProfiles []*IPConfigurationProfile + + // READ-ONLY; An array of references to the network interface IP configurations using subnet. + IPConfigurations []*IPConfiguration + + // READ-ONLY; An array of references to private endpoints. + PrivateEndpoints []*PrivateEndpoint + + // READ-ONLY; The provisioning state of the subnet resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; A read-only string identifying the intention of use for this subnet based on delegations and other user-defined + // properties. + Purpose *string + + // READ-ONLY; An array of references to the external resources using subnet. + ResourceNavigationLinks []*ResourceNavigationLink + + // READ-ONLY; An array of references to services injecting into this subnet. + ServiceAssociationLinks []*ServiceAssociationLink +} + +// SwapResource to represent slot type on the specified cloud service. +type SwapResource struct { + // Swap resource properties + Properties *SwapResourceProperties + + // READ-ONLY; Resource Id. + ID *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// SwapResourceListResult - SwapResource List with single entry to represent slot type on the specified cloud service. +type SwapResourceListResult struct { + Value []*SwapResource +} + +// SwapResourceProperties - Swap resource properties +type SwapResourceProperties struct { + // Specifies slot info on a cloud service + SlotType *SlotType +} + +// 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 type of identity that last modified the resource. + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// TagsObject - Tags object for patch operations. +type TagsObject struct { + // Resource tags. + Tags map[string]*string +} + +// Topology of the specified resource group. +type Topology struct { + // A list of topology resources. + Resources []*TopologyResource + + // READ-ONLY; The datetime when the topology was initially created for the resource group. + CreatedDateTime *time.Time + + // READ-ONLY; GUID representing the operation id. + ID *string + + // READ-ONLY; The datetime when the topology was last modified. + LastModified *time.Time +} + +// TopologyAssociation - Resources that have an association with the parent resource. +type TopologyAssociation struct { + // The association type of the child resource to the parent resource. + AssociationType *AssociationType + + // The name of the resource that is associated with the parent resource. + Name *string + + // The ID of the resource that is associated with the parent resource. + ResourceID *string +} + +// TopologyParameters - Parameters that define the representation of topology. +type TopologyParameters struct { + // The name of the target resource group to perform topology on. + TargetResourceGroupName *string + + // The reference to the Subnet resource. + TargetSubnet *SubResource + + // The reference to the Virtual Network resource. + TargetVirtualNetwork *SubResource +} + +// TopologyResource - The network resource topology information for the given resource group. +type TopologyResource struct { + // Holds the associations the resource has with other resources in the resource group. + Associations []*TopologyAssociation + + // ID of the resource. + ID *string + + // Resource location. + Location *string + + // Name of the resource. + Name *string +} + +// TrafficAnalyticsConfigurationProperties - Parameters that define the configuration of traffic analytics. +type TrafficAnalyticsConfigurationProperties struct { + // Flag to enable/disable traffic analytics. + Enabled *bool + + // The interval in minutes which would decide how frequently TA service should do flow analytics. + TrafficAnalyticsInterval *int32 + + // The resource guid of the attached workspace. + WorkspaceID *string + + // The location of the attached workspace. + WorkspaceRegion *string + + // Resource Id of the attached workspace. + WorkspaceResourceID *string +} + +// TrafficAnalyticsProperties - Parameters that define the configuration of traffic analytics. +type TrafficAnalyticsProperties struct { + // Parameters that define the configuration of traffic analytics. + NetworkWatcherFlowAnalyticsConfiguration *TrafficAnalyticsConfigurationProperties +} + +// TrafficSelectorPolicy - An traffic selector policy for a virtual network gateway connection. +type TrafficSelectorPolicy struct { + // REQUIRED; A collection of local address spaces in CIDR format. + LocalAddressRanges []*string + + // REQUIRED; A collection of remote address spaces in CIDR format. + RemoteAddressRanges []*string +} + +// TroubleshootingDetails - Information gained from troubleshooting of specified resource. +type TroubleshootingDetails struct { + // Details on troubleshooting results. + Detail *string + + // The id of the get troubleshoot operation. + ID *string + + // Reason type of failure. + ReasonType *string + + // List of recommended actions. + RecommendedActions []*TroubleshootingRecommendedActions + + // A summary of troubleshooting. + Summary *string +} + +// TroubleshootingParameters - Parameters that define the resource to troubleshoot. +type TroubleshootingParameters struct { + // REQUIRED; Properties of the troubleshooting resource. + Properties *TroubleshootingProperties + + // REQUIRED; The target resource to troubleshoot. + TargetResourceID *string +} + +// TroubleshootingProperties - Storage location provided for troubleshoot. +type TroubleshootingProperties struct { + // REQUIRED; The ID for the storage account to save the troubleshoot result. + StorageID *string + + // REQUIRED; The path to the blob to save the troubleshoot result in. + StoragePath *string +} + +// TroubleshootingRecommendedActions - Recommended actions based on discovered issues. +type TroubleshootingRecommendedActions struct { + // ID of the recommended action. + ActionID *string + + // Description of recommended actions. + ActionText *string + + // The uri linking to a documentation for the recommended troubleshooting actions. + ActionURI *string + + // The information from the URI for the recommended troubleshooting actions. + ActionURIText *string +} + +// TroubleshootingResult - Troubleshooting information gained from specified resource. +type TroubleshootingResult struct { + // The result code of the troubleshooting. + Code *string + + // The end time of the troubleshooting. + EndTime *time.Time + + // Information from troubleshooting. + Results []*TroubleshootingDetails + + // The start time of the troubleshooting. + StartTime *time.Time +} + +// TunnelConnectionHealth - VirtualNetworkGatewayConnection properties. +type TunnelConnectionHealth struct { + // READ-ONLY; Virtual Network Gateway connection status. + ConnectionStatus *VirtualNetworkGatewayConnectionStatus + + // READ-ONLY; The Egress Bytes Transferred in this connection. + EgressBytesTransferred *int64 + + // READ-ONLY; The Ingress Bytes Transferred in this connection. + IngressBytesTransferred *int64 + + // READ-ONLY; The time at which connection was established in Utc format. + LastConnectionEstablishedUTCTime *string + + // READ-ONLY; Tunnel name. + Tunnel *string +} + +// UnprepareNetworkPoliciesRequest - Details of UnprepareNetworkPolicies for Subnet. +type UnprepareNetworkPoliciesRequest struct { + // The name of the service for which subnet is being unprepared for. + ServiceName *string +} + +// Usage - The network resource usage. +type Usage struct { + // REQUIRED; The current value of the usage. + CurrentValue *int64 + + // REQUIRED; The limit of usage. + Limit *int64 + + // REQUIRED; The name of the type of usage. + Name *UsageName + + // REQUIRED; An enum describing the unit of measurement. + Unit *UsageUnit + + // READ-ONLY; Resource identifier. + ID *string +} + +// UsageName - The usage names. +type UsageName struct { + // A localized string describing the resource name. + LocalizedValue *string + + // A string describing the resource name. + Value *string +} + +// UsagesListResult - The list usages operation response. +type UsagesListResult struct { + // URL to get the next set of results. + NextLink *string + + // The list network resource usages. + Value []*Usage +} + +// VM - Describes a Virtual Machine. +type VM struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNClientConfiguration - VpnClientConfiguration for P2S client. +type VPNClientConfiguration struct { + // The AADAudience property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. + AADAudience *string + + // The AADIssuer property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. + AADIssuer *string + + // The AADTenant property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. + AADTenant *string + + // The radius server address property of the VirtualNetworkGateway resource for vpn client connection. + RadiusServerAddress *string + + // The radius secret property of the VirtualNetworkGateway resource for vpn client connection. + RadiusServerSecret *string + + // The radiusServers property for multiple radius server configuration. + RadiusServers []*RadiusServer + + // VPN authentication types for the virtual network gateway.. + VPNAuthenticationTypes []*VPNAuthenticationType + + // The reference to the address space resource which represents Address space for P2S VpnClient. + VPNClientAddressPool *AddressSpace + + // VpnClientIpsecPolicies for virtual network gateway P2S client. + VPNClientIPSecPolicies []*IPSecPolicy + + // VpnClientProtocols for Virtual network gateway. + VPNClientProtocols []*VPNClientProtocol + + // VpnClientRevokedCertificate for Virtual network gateway. + VPNClientRevokedCertificates []*VPNClientRevokedCertificate + + // VpnClientRootCertificate for virtual network gateway. + VPNClientRootCertificates []*VPNClientRootCertificate + + // per ip address pool connection policy for virtual network gateway P2S client. + VngClientConnectionConfigurations []*VngClientConnectionConfiguration +} + +// VPNClientConnectionHealth - VpnClientConnectionHealth properties. +type VPNClientConnectionHealth struct { + // List of allocated ip addresses to the connected p2s vpn clients. + AllocatedIPAddresses []*string + + // The total of p2s vpn clients connected at this time to this P2SVpnGateway. + VPNClientConnectionsCount *int32 + + // READ-ONLY; Total of the Egress Bytes Transferred in this connection. + TotalEgressBytesTransferred *int64 + + // READ-ONLY; Total of the Ingress Bytes Transferred in this P2S Vpn connection. + TotalIngressBytesTransferred *int64 +} + +// VPNClientConnectionHealthDetail - VPN client connection health detail. +type VPNClientConnectionHealthDetail struct { + // READ-ONLY; The egress bytes per second. + EgressBytesTransferred *int64 + + // READ-ONLY; The egress packets per second. + EgressPacketsTransferred *int64 + + // READ-ONLY; The ingress bytes per second. + IngressBytesTransferred *int64 + + // READ-ONLY; The ingress packets per second. + IngressPacketsTransferred *int64 + + // READ-ONLY; The max band width. + MaxBandwidth *int64 + + // READ-ONLY; The max packets transferred per second. + MaxPacketsPerSecond *int64 + + // READ-ONLY; The assigned private Ip of a connected vpn client. + PrivateIPAddress *string + + // READ-ONLY; The public Ip of a connected vpn client. + PublicIPAddress *string + + // READ-ONLY; The duration time of a connected vpn client. + VPNConnectionDuration *int64 + + // READ-ONLY; The vpn client Id. + VPNConnectionID *string + + // READ-ONLY; The start time of a connected vpn client. + VPNConnectionTime *string + + // READ-ONLY; The user name of a connected vpn client. + VPNUserName *string +} + +// VPNClientConnectionHealthDetailListResult - List of virtual network gateway vpn client connection health. +type VPNClientConnectionHealthDetailListResult struct { + // List of vpn client connection health. + Value []*VPNClientConnectionHealthDetail +} + +// VPNClientIPsecParameters - An IPSec parameters for a virtual network gateway P2S connection. +type VPNClientIPsecParameters struct { + // REQUIRED; The DH Group used in IKE Phase 1 for initial SA. + DhGroup *DhGroup + + // REQUIRED; The IPSec encryption algorithm (IKE phase 1). + IPSecEncryption *IPSecEncryption + + // REQUIRED; The IPSec integrity algorithm (IKE phase 1). + IPSecIntegrity *IPSecIntegrity + + // REQUIRED; The IKE encryption algorithm (IKE phase 2). + IkeEncryption *IkeEncryption + + // REQUIRED; The IKE integrity algorithm (IKE phase 2). + IkeIntegrity *IkeIntegrity + + // REQUIRED; The Pfs Group used in IKE Phase 2 for new child SA. + PfsGroup *PfsGroup + + // REQUIRED; The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for P2S client.. + SaDataSizeKilobytes *int32 + + // REQUIRED; The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for P2S client. + SaLifeTimeSeconds *int32 +} + +// VPNClientParameters - Vpn Client Parameters for package generation. +type VPNClientParameters struct { + // VPN client authentication method. + AuthenticationMethod *AuthenticationMethod + + // A list of client root certificates public certificate data encoded as Base-64 strings. Optional parameter for external + // radius based authentication with EAPTLS. + ClientRootCertificates []*string + + // VPN client Processor Architecture. + ProcessorArchitecture *ProcessorArchitecture + + // The public certificate data for the radius server authentication certificate as a Base-64 encoded string. Required only + // if external radius authentication has been configured with EAPTLS + // authentication. + RadiusServerAuthCertificate *string +} + +// VPNClientRevokedCertificate - VPN client revoked certificate of virtual network gateway. +type VPNClientRevokedCertificate struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the vpn client revoked certificate. + Properties *VPNClientRevokedCertificatePropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VPNClientRevokedCertificatePropertiesFormat - Properties of the revoked VPN client certificate of virtual network gateway. +type VPNClientRevokedCertificatePropertiesFormat struct { + // The revoked VPN client certificate thumbprint. + Thumbprint *string + + // READ-ONLY; The provisioning state of the VPN client revoked certificate resource. + ProvisioningState *ProvisioningState +} + +// VPNClientRootCertificate - VPN client root certificate of virtual network gateway. +type VPNClientRootCertificate struct { + // REQUIRED; Properties of the vpn client root certificate. + Properties *VPNClientRootCertificatePropertiesFormat + + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VPNClientRootCertificatePropertiesFormat - Properties of SSL certificates of application gateway. +type VPNClientRootCertificatePropertiesFormat struct { + // REQUIRED; The certificate public data. + PublicCertData *string + + // READ-ONLY; The provisioning state of the VPN client root certificate resource. + ProvisioningState *ProvisioningState +} + +// VPNConnection - VpnConnection Resource. +type VPNConnection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the VPN connection. + Properties *VPNConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VPNConnectionPacketCaptureStartParameters - Vpn Connection packet capture parameters supplied to start packet capture on +// gateway connection. +type VPNConnectionPacketCaptureStartParameters struct { + // Start Packet capture parameters on vpn connection. + FilterData *string + + // List of site link connection names. + LinkConnectionNames []*string +} + +// VPNConnectionPacketCaptureStopParameters - Vpn Connection packet capture parameters supplied to stop packet capture on +// gateway connection. +type VPNConnectionPacketCaptureStopParameters struct { + // List of site link connection names. + LinkConnectionNames []*string + + // SAS url for packet capture on vpn connection. + SasURL *string +} + +// VPNConnectionProperties - Parameters for VpnConnection. +type VPNConnectionProperties struct { + // Expected bandwidth in MBPS. + ConnectionBandwidth *int32 + + // DPD timeout in seconds for vpn connection. + DpdTimeoutSeconds *int32 + + // EnableBgp flag. + EnableBgp *bool + + // Enable internet security. + EnableInternetSecurity *bool + + // EnableBgp flag. + EnableRateLimiting *bool + + // The IPSec Policies to be considered by this connection. + IPSecPolicies []*IPSecPolicy + + // Id of the connected vpn site. + RemoteVPNSite *SubResource + + // The Routing Configuration indicating the associated and propagated route tables on this connection. + RoutingConfiguration *RoutingConfiguration + + // Routing weight for vpn connection. + RoutingWeight *int32 + + // SharedKey for the vpn connection. + SharedKey *string + + // The Traffic Selector Policies to be considered by this connection. + TrafficSelectorPolicies []*TrafficSelectorPolicy + + // Use local azure ip to initiate connection. + UseLocalAzureIPAddress *bool + + // Enable policy-based traffic selectors. + UsePolicyBasedTrafficSelectors *bool + + // Connection protocol used for this connection. + VPNConnectionProtocolType *VirtualNetworkGatewayConnectionProtocol + + // List of all vpn site link connections to the gateway. + VPNLinkConnections []*VPNSiteLinkConnection + + // READ-ONLY; The connection status. + ConnectionStatus *VPNConnectionStatus + + // READ-ONLY; Egress bytes transferred. + EgressBytesTransferred *int64 + + // READ-ONLY; Ingress bytes transferred. + IngressBytesTransferred *int64 + + // READ-ONLY; The provisioning state of the VPN connection resource. + ProvisioningState *ProvisioningState +} + +// VPNDeviceScriptParameters - Vpn device configuration script generation parameters. +type VPNDeviceScriptParameters struct { + // The device family for the vpn device. + DeviceFamily *string + + // The firmware version for the vpn device. + FirmwareVersion *string + + // The vendor for the vpn device. + Vendor *string +} + +// VPNGateway - VpnGateway Resource. +type VPNGateway struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the VPN gateway. + Properties *VPNGatewayProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNGatewayIPConfiguration - IP Configuration of a VPN Gateway Resource. +type VPNGatewayIPConfiguration struct { + // The identifier of the IP configuration for a VPN Gateway. + ID *string + + // The private IP address of this IP configuration. + PrivateIPAddress *string + + // The public IP address of this IP configuration. + PublicIPAddress *string +} + +// VPNGatewayNatRule - VpnGatewayNatRule Resource. +type VPNGatewayNatRule struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the VpnGateway NAT rule. + Properties *VPNGatewayNatRuleProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNGatewayNatRuleProperties - Parameters for VpnGatewayNatRule. +type VPNGatewayNatRuleProperties struct { + // The private IP address external mapping for NAT. + ExternalMappings []*VPNNatRuleMapping + + // The IP Configuration ID this NAT rule applies to. + IPConfigurationID *string + + // The private IP address internal mapping for NAT. + InternalMappings []*VPNNatRuleMapping + + // The Source NAT direction of a VPN NAT. + Mode *VPNNatRuleMode + + // The type of NAT rule for VPN NAT. + Type *VPNNatRuleType + + // READ-ONLY; List of egress VpnSiteLinkConnections. + EgressVPNSiteLinkConnections []*SubResource + + // READ-ONLY; List of ingress VpnSiteLinkConnections. + IngressVPNSiteLinkConnections []*SubResource + + // READ-ONLY; The provisioning state of the NAT Rule resource. + ProvisioningState *ProvisioningState +} + +// VPNGatewayPacketCaptureStartParameters - Start packet capture parameters. +type VPNGatewayPacketCaptureStartParameters struct { + // Start Packet capture parameters on vpn gateway. + FilterData *string +} + +// VPNGatewayPacketCaptureStopParameters - Stop packet capture parameters. +type VPNGatewayPacketCaptureStopParameters struct { + // SAS url for packet capture on vpn gateway. + SasURL *string +} + +// VPNGatewayProperties - Parameters for VpnGateway. +type VPNGatewayProperties struct { + // Local network gateway's BGP speaker settings. + BgpSettings *BgpSettings + + // List of all vpn connections to the gateway. + Connections []*VPNConnection + + // Enable BGP routes translation for NAT on this VpnGateway. + EnableBgpRouteTranslationForNat *bool + + // Enable Routing Preference property for the Public IP Interface of the VpnGateway. + IsRoutingPreferenceInternet *bool + + // List of all the nat Rules associated with the gateway. + NatRules []*VPNGatewayNatRule + + // The scale unit for this vpn gateway. + VPNGatewayScaleUnit *int32 + + // The VirtualHub to which the gateway belongs. + VirtualHub *SubResource + + // READ-ONLY; List of all IPs configured on the gateway. + IPConfigurations []*VPNGatewayIPConfiguration + + // READ-ONLY; The provisioning state of the VPN gateway resource. + ProvisioningState *ProvisioningState +} + +// VPNLinkBgpSettings - BGP settings details for a link. +type VPNLinkBgpSettings struct { + // The BGP speaker's ASN. + Asn *int64 + + // The BGP peering address and BGP identifier of this BGP speaker. + BgpPeeringAddress *string +} + +// VPNLinkProviderProperties - List of properties of a link provider. +type VPNLinkProviderProperties struct { + // Name of the link provider. + LinkProviderName *string + + // Link speed. + LinkSpeedInMbps *int32 +} + +// VPNNatRuleMapping - Vpn NatRule mapping. +type VPNNatRuleMapping struct { + // Address space for Vpn NatRule mapping. + AddressSpace *string + + // Port range for Vpn NatRule mapping. + PortRange *string +} + +// VPNPacketCaptureStartParameters - Start packet capture parameters on virtual network gateway. +type VPNPacketCaptureStartParameters struct { + // Start Packet capture parameters. + FilterData *string +} + +// VPNPacketCaptureStopParameters - Stop packet capture parameters. +type VPNPacketCaptureStopParameters struct { + // SAS url for packet capture on virtual network gateway. + SasURL *string +} + +// VPNProfileResponse - Vpn Profile Response for package generation. +type VPNProfileResponse struct { + // URL to the VPN profile. + ProfileURL *string +} + +// VPNServerConfigRadiusClientRootCertificate - Properties of the Radius client root certificate of VpnServerConfiguration. +type VPNServerConfigRadiusClientRootCertificate struct { + // The certificate name. + Name *string + + // The Radius client root certificate thumbprint. + Thumbprint *string +} + +// VPNServerConfigRadiusServerRootCertificate - Properties of Radius Server root certificate of VpnServerConfiguration. +type VPNServerConfigRadiusServerRootCertificate struct { + // The certificate name. + Name *string + + // The certificate public data. + PublicCertData *string +} + +// VPNServerConfigVPNClientRevokedCertificate - Properties of the revoked VPN client certificate of VpnServerConfiguration. +type VPNServerConfigVPNClientRevokedCertificate struct { + // The certificate name. + Name *string + + // The revoked VPN client certificate thumbprint. + Thumbprint *string +} + +// VPNServerConfigVPNClientRootCertificate - Properties of VPN client root certificate of VpnServerConfiguration. +type VPNServerConfigVPNClientRootCertificate struct { + // The certificate name. + Name *string + + // The certificate public data. + PublicCertData *string +} + +// VPNServerConfiguration - VpnServerConfiguration Resource. +type VPNServerConfiguration struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the P2SVpnServer configuration. + Properties *VPNServerConfigurationProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNServerConfigurationPolicyGroup - VpnServerConfigurationPolicyGroup Resource. +type VPNServerConfigurationPolicyGroup struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the VpnServerConfigurationPolicyGroup. + Properties *VPNServerConfigurationPolicyGroupProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNServerConfigurationPolicyGroupMember - VpnServerConfiguration PolicyGroup member +type VPNServerConfigurationPolicyGroupMember struct { + // The Vpn Policy member attribute type. + AttributeType *VPNPolicyMemberAttributeType + + // The value of Attribute used for this VpnServerConfigurationPolicyGroupMember. + AttributeValue *string + + // Name of the VpnServerConfigurationPolicyGroupMember. + Name *string +} + +// VPNServerConfigurationPolicyGroupProperties - Parameters for VpnServerConfigurationPolicyGroup. +type VPNServerConfigurationPolicyGroupProperties struct { + // Shows if this is a Default VpnServerConfigurationPolicyGroup or not. + IsDefault *bool + + // Multiple PolicyMembers for VpnServerConfigurationPolicyGroup. + PolicyMembers []*VPNServerConfigurationPolicyGroupMember + + // Priority for VpnServerConfigurationPolicyGroup. + Priority *int32 + + // READ-ONLY; List of references to P2SConnectionConfigurations. + P2SConnectionConfigurations []*SubResource + + // READ-ONLY; The provisioning state of the VpnServerConfigurationPolicyGroup resource. + ProvisioningState *ProvisioningState +} + +// VPNServerConfigurationProperties - Parameters for VpnServerConfiguration. +type VPNServerConfigurationProperties struct { + // The set of aad vpn authentication parameters. + AADAuthenticationParameters *AADAuthenticationParameters + + // List of all VpnServerConfigurationPolicyGroups. + ConfigurationPolicyGroups []*VPNServerConfigurationPolicyGroup + + // The name of the VpnServerConfiguration that is unique within a resource group. + Name *string + + // Radius client root certificate of VpnServerConfiguration. + RadiusClientRootCertificates []*VPNServerConfigRadiusClientRootCertificate + + // The radius server address property of the VpnServerConfiguration resource for point to site client connection. + RadiusServerAddress *string + + // Radius Server root certificate of VpnServerConfiguration. + RadiusServerRootCertificates []*VPNServerConfigRadiusServerRootCertificate + + // The radius secret property of the VpnServerConfiguration resource for point to site client connection. + RadiusServerSecret *string + + // Multiple Radius Server configuration for VpnServerConfiguration. + RadiusServers []*RadiusServer + + // VPN authentication types for the VpnServerConfiguration. + VPNAuthenticationTypes []*VPNAuthenticationType + + // VpnClientIpsecPolicies for VpnServerConfiguration. + VPNClientIPSecPolicies []*IPSecPolicy + + // VPN client revoked certificate of VpnServerConfiguration. + VPNClientRevokedCertificates []*VPNServerConfigVPNClientRevokedCertificate + + // VPN client root certificate of VpnServerConfiguration. + VPNClientRootCertificates []*VPNServerConfigVPNClientRootCertificate + + // VPN protocols for the VpnServerConfiguration. + VPNProtocols []*VPNGatewayTunnelingProtocol + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; List of references to P2SVpnGateways. + P2SVPNGateways []*P2SVPNGateway + + // READ-ONLY; The provisioning state of the VpnServerConfiguration resource. Possible values are: 'Updating', 'Deleting', + // and 'Failed'. + ProvisioningState *string +} + +// VPNServerConfigurationsResponse - VpnServerConfigurations list associated with VirtualWan Response. +type VPNServerConfigurationsResponse struct { + // List of VpnServerConfigurations associated with VirtualWan. + VPNServerConfigurationResourceIDs []*string +} + +// VPNSite - VpnSite Resource. +type VPNSite struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the VPN site. + Properties *VPNSiteProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNSiteID - VpnSite Resource. +type VPNSiteID struct { + // READ-ONLY; The resource-uri of the vpn-site for which config is to be fetched. + VPNSite *string +} + +// VPNSiteLink - VpnSiteLink Resource. +type VPNSiteLink struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the VPN site link. + Properties *VPNSiteLinkProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNSiteLinkConnection - VpnSiteLinkConnection Resource. +type VPNSiteLinkConnection struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the VPN site link connection. + Properties *VPNSiteLinkConnectionProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// VPNSiteLinkConnectionProperties - Parameters for VpnConnection. +type VPNSiteLinkConnectionProperties struct { + // Expected bandwidth in MBPS. + ConnectionBandwidth *int32 + + // List of egress NatRules. + EgressNatRules []*SubResource + + // EnableBgp flag. + EnableBgp *bool + + // EnableBgp flag. + EnableRateLimiting *bool + + // The IPSec Policies to be considered by this connection. + IPSecPolicies []*IPSecPolicy + + // List of ingress NatRules. + IngressNatRules []*SubResource + + // Routing weight for vpn connection. + RoutingWeight *int32 + + // SharedKey for the vpn connection. + SharedKey *string + + // Use local azure ip to initiate connection. + UseLocalAzureIPAddress *bool + + // Enable policy-based traffic selectors. + UsePolicyBasedTrafficSelectors *bool + + // Connection protocol used for this connection. + VPNConnectionProtocolType *VirtualNetworkGatewayConnectionProtocol + + // vpnGatewayCustomBgpAddresses used by this connection. + VPNGatewayCustomBgpAddresses []*GatewayCustomBgpIPAddressIPConfiguration + + // Vpn link connection mode. + VPNLinkConnectionMode *VPNLinkConnectionMode + + // Id of the connected vpn site link. + VPNSiteLink *SubResource + + // READ-ONLY; The connection status. + ConnectionStatus *VPNConnectionStatus + + // READ-ONLY; Egress bytes transferred. + EgressBytesTransferred *int64 + + // READ-ONLY; Ingress bytes transferred. + IngressBytesTransferred *int64 + + // READ-ONLY; The provisioning state of the VPN site link connection resource. + ProvisioningState *ProvisioningState +} + +// VPNSiteLinkProperties - Parameters for VpnSite. +type VPNSiteLinkProperties struct { + // The set of bgp properties. + BgpProperties *VPNLinkBgpSettings + + // FQDN of vpn-site-link. + Fqdn *string + + // The ip-address for the vpn-site-link. + IPAddress *string + + // The link provider properties. + LinkProperties *VPNLinkProviderProperties + + // READ-ONLY; The provisioning state of the VPN site link resource. + ProvisioningState *ProvisioningState +} + +// VPNSiteProperties - Parameters for VpnSite. +type VPNSiteProperties struct { + // The AddressSpace that contains an array of IP address ranges. + AddressSpace *AddressSpace + + // The set of bgp properties. + BgpProperties *BgpSettings + + // The device properties. + DeviceProperties *DeviceProperties + + // The ip-address for the vpn-site. + IPAddress *string + + // IsSecuritySite flag. + IsSecuritySite *bool + + // Office365 Policy. + O365Policy *O365PolicyProperties + + // The key for vpn-site that can be used for connections. + SiteKey *string + + // List of all vpn site links. + VPNSiteLinks []*VPNSiteLink + + // The VirtualWAN to which the vpnSite belongs. + VirtualWan *SubResource + + // READ-ONLY; The provisioning state of the VPN site resource. + ProvisioningState *ProvisioningState +} + +// VerificationIPFlowParameters - Parameters that define the IP flow to be verified. +type VerificationIPFlowParameters struct { + // REQUIRED; The direction of the packet represented as a 5-tuple. + Direction *Direction + + // REQUIRED; The local IP address. Acceptable values are valid IPv4 addresses. + LocalIPAddress *string + + // REQUIRED; The local port. Acceptable values are a single integer in the range (0-65535). Support for * for the source port, + // which depends on the direction. + LocalPort *string + + // REQUIRED; Protocol to be verified on. + Protocol *IPFlowProtocol + + // REQUIRED; The remote IP address. Acceptable values are valid IPv4 addresses. + RemoteIPAddress *string + + // REQUIRED; The remote port. Acceptable values are a single integer in the range (0-65535). Support for * for the source + // port, which depends on the direction. + RemotePort *string + + // REQUIRED; The ID of the target resource to perform next-hop on. + TargetResourceID *string + + // The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of them, then this parameter must be specified. + // Otherwise optional). + TargetNicResourceID *string +} + +// VerificationIPFlowResult - Results of IP flow verification on the target resource. +type VerificationIPFlowResult struct { + // Indicates whether the traffic is allowed or denied. + Access *Access + + // Name of the rule. If input is not matched against any security rule, it is not displayed. + RuleName *string +} + +// VirtualAppliance - NetworkVirtualAppliance Resource. +type VirtualAppliance struct { + // Resource ID. + ID *string + + // The service principal that has read access to cloud-init and config blob. + Identity *ManagedServiceIdentity + + // Resource location. + Location *string + + // Properties of the Network Virtual Appliance. + Properties *VirtualAppliancePropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualApplianceAdditionalNicProperties - Network Virtual Appliance Additional NIC properties. +type VirtualApplianceAdditionalNicProperties struct { + // Flag (true or false) for Intent for Public Ip on additional nic + HasPublicIP *bool + + // Name of additional nic + Name *string +} + +// VirtualApplianceConnection - NetworkVirtualApplianceConnection resource. +type VirtualApplianceConnection struct { + // Resource ID. + ID *string + + // The name of the resource. + Name *string + + // Properties of the express route connection. + Properties *VirtualApplianceConnectionProperties +} + +// VirtualApplianceConnectionList - NetworkVirtualApplianceConnection list. +type VirtualApplianceConnectionList struct { + // URL to get the next set of results. + NextLink *string + + // The list of NetworkVirtualAppliance connections. + Value []*VirtualApplianceConnection +} + +// VirtualApplianceConnectionProperties - Properties of the NetworkVirtualApplianceConnection subresource. +type VirtualApplianceConnectionProperties struct { + // Network Virtual Appliance ASN. + Asn *int64 + + // List of bgpPeerAddresses for the NVA instances + BgpPeerAddress []*string + + // Enable internet security. + EnableInternetSecurity *bool + + // The name of the resource. + Name *string + + // The Routing Configuration indicating the associated and propagated route tables on this connection. + RoutingConfiguration *RoutingConfigurationNfv + + // Unique identifier for the connection. + TunnelIdentifier *int64 + + // READ-ONLY; The provisioning state of the NetworkVirtualApplianceConnection resource. + ProvisioningState *ProvisioningState +} + +// VirtualApplianceListResult - Response for ListNetworkVirtualAppliances API service call. +type VirtualApplianceListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Network Virtual Appliances. + Value []*VirtualAppliance +} + +// VirtualApplianceNicProperties - Network Virtual Appliance NIC properties. +type VirtualApplianceNicProperties struct { + // READ-ONLY; Instance on which nic is attached. + InstanceName *string + + // READ-ONLY; NIC name. + Name *string + + // READ-ONLY; Private IP address. + PrivateIPAddress *string + + // READ-ONLY; Public IP address. + PublicIPAddress *string +} + +// VirtualAppliancePropertiesFormat - Network Virtual Appliance definition. +type VirtualAppliancePropertiesFormat struct { + // Details required for Additional Network Interface. + AdditionalNics []*VirtualApplianceAdditionalNicProperties + + // BootStrapConfigurationBlobs storage URLs. + BootStrapConfigurationBlobs []*string + + // CloudInitConfiguration string in plain text. + CloudInitConfiguration *string + + // CloudInitConfigurationBlob storage URLs. + CloudInitConfigurationBlobs []*string + + // The delegation for the Virtual Appliance + Delegation *DelegationProperties + + // Network Virtual Appliance SKU. + NvaSKU *VirtualApplianceSKUProperties + + // The delegation for the Virtual Appliance + PartnerManagedResource *PartnerManagedResourceProperties + + // Public key for SSH login. + SSHPublicKey *string + + // VirtualAppliance ASN. Microsoft private, public and IANA reserved ASN are not supported. + VirtualApplianceAsn *int64 + + // The Virtual Hub where Network Virtual Appliance is being deployed. + VirtualHub *SubResource + + // READ-ONLY; Address Prefix. + AddressPrefix *string + + // READ-ONLY; The deployment type. PartnerManaged for the SaaS NVA + DeploymentType *string + + // READ-ONLY; List of references to InboundSecurityRules. + InboundSecurityRules []*SubResource + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; List of references to VirtualApplianceConnections. + VirtualApplianceConnections []*SubResource + + // READ-ONLY; List of Virtual Appliance Network Interfaces. + VirtualApplianceNics []*VirtualApplianceNicProperties + + // READ-ONLY; List of references to VirtualApplianceSite. + VirtualApplianceSites []*SubResource +} + +// VirtualApplianceSKU - Definition of the NetworkVirtualApplianceSkus resource. +type VirtualApplianceSKU struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // NetworkVirtualApplianceSku properties. + Properties *VirtualApplianceSKUPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualApplianceSKUInstances - List of available Sku and instances. +type VirtualApplianceSKUInstances struct { + // READ-ONLY; Instance Count. + InstanceCount *int32 + + // READ-ONLY; Scale Unit. + ScaleUnit *string +} + +// VirtualApplianceSKUListResult - Response for ListNetworkVirtualApplianceSkus API service call. +type VirtualApplianceSKUListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Network Virtual Appliance Skus that are available. + Value []*VirtualApplianceSKU +} + +// VirtualApplianceSKUProperties - Network Virtual Appliance Sku Properties. +type VirtualApplianceSKUProperties struct { + // Virtual Appliance Scale Unit. + BundledScaleUnit *string + + // Virtual Appliance Version. + MarketPlaceVersion *string + + // Virtual Appliance Vendor. + Vendor *string +} + +// VirtualApplianceSKUPropertiesFormat - Properties specific to NetworkVirtualApplianceSkus. +type VirtualApplianceSKUPropertiesFormat struct { + // The list of scale units available. + AvailableScaleUnits []*VirtualApplianceSKUInstances + + // READ-ONLY; Available Network Virtual Appliance versions. + AvailableVersions []*string + + // READ-ONLY; Network Virtual Appliance Sku vendor. + Vendor *string +} + +// VirtualApplianceSite - Virtual Appliance Site resource. +type VirtualApplianceSite struct { + // Resource ID. + ID *string + + // Name of the virtual appliance site. + Name *string + + // The properties of the Virtual Appliance Sites. + Properties *VirtualApplianceSiteProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Site type. + Type *string +} + +// VirtualApplianceSiteListResult - Response for ListNetworkVirtualApplianceSites API service call. +type VirtualApplianceSiteListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Network Virtual Appliance sites. + Value []*VirtualApplianceSite +} + +// VirtualApplianceSiteProperties - Properties of the rule group. +type VirtualApplianceSiteProperties struct { + // Address Prefix. + AddressPrefix *string + + // Office 365 Policy. + O365Policy *Office365PolicyProperties + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// VirtualHub Resource. +type VirtualHub struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the virtual hub. + Properties *VirtualHubProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Kind of service virtual hub. This is metadata used for the Azure portal experience for Route Server. + Kind *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualHubEffectiveRoute - The effective route configured on the virtual hub or specified resource. +type VirtualHubEffectiveRoute struct { + // The list of address prefixes. + AddressPrefixes []*string + + // The ASPath of this route. + AsPath *string + + // The type of the next hop. + NextHopType *string + + // The list of next hops. + NextHops []*string + + // The origin of this route. + RouteOrigin *string +} + +// VirtualHubEffectiveRouteList - EffectiveRoutes List. +type VirtualHubEffectiveRouteList struct { + // The list of effective routes configured on the virtual hub or the specified resource. + Value []*VirtualHubEffectiveRoute +} + +// VirtualHubID - Virtual Hub identifier. +type VirtualHubID struct { + // The resource URI for the Virtual Hub where the ExpressRoute gateway is or will be deployed. The Virtual Hub resource and + // the ExpressRoute gateway resource reside in the same subscription. + ID *string +} + +// VirtualHubProperties - Parameters for VirtualHub. +type VirtualHubProperties struct { + // Address-prefix for this VirtualHub. + AddressPrefix *string + + // Flag to control transit for VirtualRouter hub. + AllowBranchToBranchTraffic *bool + + // The azureFirewall associated with this VirtualHub. + AzureFirewall *SubResource + + // The expressRouteGateway associated with this VirtualHub. + ExpressRouteGateway *SubResource + + // The hubRoutingPreference of this VirtualHub. + HubRoutingPreference *HubRoutingPreference + + // The P2SVpnGateway associated with this VirtualHub. + P2SVPNGateway *SubResource + + // The preferred gateway to route on-prem traffic + PreferredRoutingGateway *PreferredRoutingGateway + + // The routeTable associated with this virtual hub. + RouteTable *VirtualHubRouteTable + + // The sku of this VirtualHub. + SKU *string + + // The securityPartnerProvider associated with this VirtualHub. + SecurityPartnerProvider *SubResource + + // The Security Provider name. + SecurityProviderName *string + + // The VpnGateway associated with this VirtualHub. + VPNGateway *SubResource + + // List of all virtual hub route table v2s associated with this VirtualHub. + VirtualHubRouteTableV2S []*VirtualHubRouteTableV2 + + // VirtualRouter ASN. + VirtualRouterAsn *int64 + + // The VirtualHub Router autoscale configuration. + VirtualRouterAutoScaleConfiguration *VirtualRouterAutoScaleConfiguration + + // VirtualRouter IPs. + VirtualRouterIPs []*string + + // The VirtualWAN to which the VirtualHub belongs. + VirtualWan *SubResource + + // READ-ONLY; List of references to Bgp Connections. + BgpConnections []*SubResource + + // READ-ONLY; List of references to IpConfigurations. + IPConfigurations []*SubResource + + // READ-ONLY; The provisioning state of the virtual hub resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; List of references to RouteMaps. + RouteMaps []*SubResource + + // READ-ONLY; The routing state. + RoutingState *RoutingState +} + +// VirtualHubRoute - VirtualHub route. +type VirtualHubRoute struct { + // List of all addressPrefixes. + AddressPrefixes []*string + + // NextHop ip address. + NextHopIPAddress *string +} + +// VirtualHubRouteTable - VirtualHub route table. +type VirtualHubRouteTable struct { + // List of all routes. + Routes []*VirtualHubRoute +} + +// VirtualHubRouteTableV2 Resource. +type VirtualHubRouteTableV2 struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the virtual hub route table v2. + Properties *VirtualHubRouteTableV2Properties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VirtualHubRouteTableV2Properties - Parameters for VirtualHubRouteTableV2. +type VirtualHubRouteTableV2Properties struct { + // List of all connections attached to this route table v2. + AttachedConnections []*string + + // List of all routes. + Routes []*VirtualHubRouteV2 + + // READ-ONLY; The provisioning state of the virtual hub route table v2 resource. + ProvisioningState *ProvisioningState +} + +// VirtualHubRouteV2 - VirtualHubRouteTableV2 route. +type VirtualHubRouteV2 struct { + // The type of destinations. + DestinationType *string + + // List of all destinations. + Destinations []*string + + // The type of next hops. + NextHopType *string + + // NextHops ip address. + NextHops []*string +} + +// VirtualNetwork - Virtual Network resource. +type VirtualNetwork struct { + // The extended location of the virtual network. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the virtual network. + Properties *VirtualNetworkPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualNetworkBgpCommunities - Bgp Communities sent over ExpressRoute with each route corresponding to a prefix in this +// VNET. +type VirtualNetworkBgpCommunities struct { + // REQUIRED; The BGP community associated with the virtual network. + VirtualNetworkCommunity *string + + // READ-ONLY; The BGP community associated with the region of the virtual network. + RegionalCommunity *string +} + +// VirtualNetworkConnectionGatewayReference - A reference to VirtualNetworkGateway or LocalNetworkGateway resource. +type VirtualNetworkConnectionGatewayReference struct { + // REQUIRED; The ID of VirtualNetworkGateway or LocalNetworkGateway resource. + ID *string +} + +// VirtualNetworkDdosProtectionStatusResult - Response for GetVirtualNetworkDdosProtectionStatusOperation. +type VirtualNetworkDdosProtectionStatusResult struct { + // The URL to get the next set of results. + NextLink *string + + // The Ddos Protection Status Result for each public ip under a virtual network. + Value []*PublicIPDdosProtectionStatusResult +} + +// VirtualNetworkEncryption - Indicates if encryption is enabled on virtual network and if VM without encryption is allowed +// in encrypted VNet. +type VirtualNetworkEncryption struct { + // REQUIRED; Indicates if encryption is enabled on the virtual network. + Enabled *bool + + // If the encrypted VNet allows VM that does not support encryption + Enforcement *VirtualNetworkEncryptionEnforcement +} + +// VirtualNetworkGateway - A common class for general resource information. +type VirtualNetworkGateway struct { + // REQUIRED; Properties of the virtual network gateway. + Properties *VirtualNetworkGatewayPropertiesFormat + + // The extended location of type local virtual network gateway. + ExtendedLocation *ExtendedLocation + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +type VirtualNetworkGatewayAutoScaleBounds struct { + // Maximum Scale Units for Autoscale configuration + Max *int32 + + // Minimum scale Units for Autoscale configuration + Min *int32 +} + +// VirtualNetworkGatewayAutoScaleConfiguration - Virtual Network Gateway Autoscale Configuration details +type VirtualNetworkGatewayAutoScaleConfiguration struct { + // The bounds of the autoscale configuration + Bounds *VirtualNetworkGatewayAutoScaleBounds +} + +// VirtualNetworkGatewayConnection - A common class for general resource information. +type VirtualNetworkGatewayConnection struct { + // REQUIRED; Properties of the virtual network gateway connection. + Properties *VirtualNetworkGatewayConnectionPropertiesFormat + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualNetworkGatewayConnectionListEntity - A common class for general resource information. +type VirtualNetworkGatewayConnectionListEntity struct { + // REQUIRED; Properties of the virtual network gateway connection. + Properties *VirtualNetworkGatewayConnectionListEntityPropertiesFormat + + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualNetworkGatewayConnectionListEntityPropertiesFormat - VirtualNetworkGatewayConnection properties. +type VirtualNetworkGatewayConnectionListEntityPropertiesFormat struct { + // REQUIRED; Gateway connection type. + ConnectionType *VirtualNetworkGatewayConnectionType + + // REQUIRED; The reference to virtual network gateway resource. + VirtualNetworkGateway1 *VirtualNetworkConnectionGatewayReference + + // The authorizationKey. + AuthorizationKey *string + + // The connection mode for this connection. + ConnectionMode *VirtualNetworkGatewayConnectionMode + + // Connection protocol used for this connection. + ConnectionProtocol *VirtualNetworkGatewayConnectionProtocol + + // EnableBgp flag. + EnableBgp *bool + + // Bypass the ExpressRoute gateway when accessing private-links. ExpressRoute FastPath (expressRouteGatewayBypass) must be + // enabled. + EnablePrivateLinkFastPath *bool + + // Bypass ExpressRoute Gateway for data forwarding. + ExpressRouteGatewayBypass *bool + + // GatewayCustomBgpIpAddresses to be used for virtual network gateway Connection. + GatewayCustomBgpIPAddresses []*GatewayCustomBgpIPAddressIPConfiguration + + // The IPSec Policies to be considered by this connection. + IPSecPolicies []*IPSecPolicy + + // The reference to local network gateway resource. + LocalNetworkGateway2 *VirtualNetworkConnectionGatewayReference + + // The reference to peerings resource. + Peer *SubResource + + // The routing weight. + RoutingWeight *int32 + + // The IPSec shared key. + SharedKey *string + + // The Traffic Selector Policies to be considered by this connection. + TrafficSelectorPolicies []*TrafficSelectorPolicy + + // Enable policy-based traffic selectors. + UsePolicyBasedTrafficSelectors *bool + + // The reference to virtual network gateway resource. + VirtualNetworkGateway2 *VirtualNetworkConnectionGatewayReference + + // READ-ONLY; Virtual Network Gateway connection status. + ConnectionStatus *VirtualNetworkGatewayConnectionStatus + + // READ-ONLY; The egress bytes transferred in this connection. + EgressBytesTransferred *int64 + + // READ-ONLY; The ingress bytes transferred in this connection. + IngressBytesTransferred *int64 + + // READ-ONLY; The provisioning state of the virtual network gateway connection resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the virtual network gateway connection resource. + ResourceGUID *string + + // READ-ONLY; Collection of all tunnels' connection health status. + TunnelConnectionStatus []*TunnelConnectionHealth +} + +// VirtualNetworkGatewayConnectionListResult - Response for the ListVirtualNetworkGatewayConnections API service call. +type VirtualNetworkGatewayConnectionListResult struct { + // A list of VirtualNetworkGatewayConnection resources that exists in a resource group. + Value []*VirtualNetworkGatewayConnection + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// VirtualNetworkGatewayConnectionPropertiesFormat - VirtualNetworkGatewayConnection properties. +type VirtualNetworkGatewayConnectionPropertiesFormat struct { + // REQUIRED; Gateway connection type. + ConnectionType *VirtualNetworkGatewayConnectionType + + // REQUIRED; The reference to virtual network gateway resource. + VirtualNetworkGateway1 *VirtualNetworkGateway + + // The authorizationKey. + AuthorizationKey *string + + // The connection mode for this connection. + ConnectionMode *VirtualNetworkGatewayConnectionMode + + // Connection protocol used for this connection. + ConnectionProtocol *VirtualNetworkGatewayConnectionProtocol + + // The dead peer detection timeout of this connection in seconds. + DpdTimeoutSeconds *int32 + + // List of egress NatRules. + EgressNatRules []*SubResource + + // EnableBgp flag. + EnableBgp *bool + + // Bypass the ExpressRoute gateway when accessing private-links. ExpressRoute FastPath (expressRouteGatewayBypass) must be + // enabled. + EnablePrivateLinkFastPath *bool + + // Bypass ExpressRoute Gateway for data forwarding. + ExpressRouteGatewayBypass *bool + + // GatewayCustomBgpIpAddresses to be used for virtual network gateway Connection. + GatewayCustomBgpIPAddresses []*GatewayCustomBgpIPAddressIPConfiguration + + // The IPSec Policies to be considered by this connection. + IPSecPolicies []*IPSecPolicy + + // List of ingress NatRules. + IngressNatRules []*SubResource + + // The reference to local network gateway resource. + LocalNetworkGateway2 *LocalNetworkGateway + + // The reference to peerings resource. + Peer *SubResource + + // The routing weight. + RoutingWeight *int32 + + // The IPSec shared key. + SharedKey *string + + // The Traffic Selector Policies to be considered by this connection. + TrafficSelectorPolicies []*TrafficSelectorPolicy + + // Use private local Azure IP for the connection. + UseLocalAzureIPAddress *bool + + // Enable policy-based traffic selectors. + UsePolicyBasedTrafficSelectors *bool + + // The reference to virtual network gateway resource. + VirtualNetworkGateway2 *VirtualNetworkGateway + + // READ-ONLY; Virtual Network Gateway connection status. + ConnectionStatus *VirtualNetworkGatewayConnectionStatus + + // READ-ONLY; The egress bytes transferred in this connection. + EgressBytesTransferred *int64 + + // READ-ONLY; The ingress bytes transferred in this connection. + IngressBytesTransferred *int64 + + // READ-ONLY; The provisioning state of the virtual network gateway connection resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the virtual network gateway connection resource. + ResourceGUID *string + + // READ-ONLY; Collection of all tunnels' connection health status. + TunnelConnectionStatus []*TunnelConnectionHealth +} + +// VirtualNetworkGatewayIPConfiguration - IP configuration for virtual network gateway. +type VirtualNetworkGatewayIPConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the virtual network gateway ip configuration. + Properties *VirtualNetworkGatewayIPConfigurationPropertiesFormat + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VirtualNetworkGatewayIPConfigurationPropertiesFormat - Properties of VirtualNetworkGatewayIPConfiguration. +type VirtualNetworkGatewayIPConfigurationPropertiesFormat struct { + // The private IP address allocation method. + PrivateIPAllocationMethod *IPAllocationMethod + + // The reference to the public IP resource. + PublicIPAddress *SubResource + + // The reference to the subnet resource. + Subnet *SubResource + + // READ-ONLY; Private IP Address for this gateway. + PrivateIPAddress *string + + // READ-ONLY; The provisioning state of the virtual network gateway IP configuration resource. + ProvisioningState *ProvisioningState +} + +// VirtualNetworkGatewayListConnectionsResult - Response for the VirtualNetworkGatewayListConnections API service call. +type VirtualNetworkGatewayListConnectionsResult struct { + // A list of VirtualNetworkGatewayConnection resources that exists in a resource group. + Value []*VirtualNetworkGatewayConnectionListEntity + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// VirtualNetworkGatewayListResult - Response for the ListVirtualNetworkGateways API service call. +type VirtualNetworkGatewayListResult struct { + // A list of VirtualNetworkGateway resources that exists in a resource group. + Value []*VirtualNetworkGateway + + // READ-ONLY; The URL to get the next set of results. + NextLink *string +} + +// VirtualNetworkGatewayNatRule Resource. +type VirtualNetworkGatewayNatRule struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the Virtual Network Gateway NAT rule. + Properties *VirtualNetworkGatewayNatRuleProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualNetworkGatewayNatRuleProperties - Parameters for VirtualNetworkGatewayNatRule. +type VirtualNetworkGatewayNatRuleProperties struct { + // The private IP address external mapping for NAT. + ExternalMappings []*VPNNatRuleMapping + + // The IP Configuration ID this NAT rule applies to. + IPConfigurationID *string + + // The private IP address internal mapping for NAT. + InternalMappings []*VPNNatRuleMapping + + // The Source NAT direction of a VPN NAT. + Mode *VPNNatRuleMode + + // The type of NAT rule for VPN NAT. + Type *VPNNatRuleType + + // READ-ONLY; The provisioning state of the NAT Rule resource. + ProvisioningState *ProvisioningState +} + +// VirtualNetworkGatewayPolicyGroup - Parameters for VirtualNetworkGatewayPolicyGroup. +type VirtualNetworkGatewayPolicyGroup struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of tVirtualNetworkGatewayPolicyGroup. + Properties *VirtualNetworkGatewayPolicyGroupProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VirtualNetworkGatewayPolicyGroupMember - Vpn Client Connection configuration PolicyGroup member +type VirtualNetworkGatewayPolicyGroupMember struct { + // The Vpn Policy member attribute type. + AttributeType *VPNPolicyMemberAttributeType + + // The value of Attribute used for this VirtualNetworkGatewayPolicyGroupMember. + AttributeValue *string + + // Name of the VirtualNetworkGatewayPolicyGroupMember. + Name *string +} + +// VirtualNetworkGatewayPolicyGroupProperties - Properties of VirtualNetworkGatewayPolicyGroup. +type VirtualNetworkGatewayPolicyGroupProperties struct { + // REQUIRED; Shows if this is a Default VirtualNetworkGatewayPolicyGroup or not. + IsDefault *bool + + // REQUIRED; Multiple PolicyMembers for VirtualNetworkGatewayPolicyGroup. + PolicyMembers []*VirtualNetworkGatewayPolicyGroupMember + + // REQUIRED; Priority for VirtualNetworkGatewayPolicyGroup. + Priority *int32 + + // READ-ONLY; The provisioning state of the VirtualNetworkGatewayPolicyGroup resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; List of references to vngClientConnectionConfigurations. + VngClientConnectionConfigurations []*SubResource +} + +// VirtualNetworkGatewayPropertiesFormat - VirtualNetworkGateway properties. +type VirtualNetworkGatewayPropertiesFormat struct { + // ActiveActive flag. + Active *bool + + // Property to indicate if the Express Route Gateway serves traffic when there are multiple Express Route Gateways in the + // vnet + AdminState *AdminState + + // Configure this gateway to accept traffic from other Azure Virtual Networks. This configuration does not support connectivity + // to Azure Virtual WAN. + AllowRemoteVnetTraffic *bool + + // Configures this gateway to accept traffic from remote Virtual WAN networks. + AllowVirtualWanTraffic *bool + + // Autoscale configuration for virutal network gateway + AutoScaleConfiguration *VirtualNetworkGatewayAutoScaleConfiguration + + // Virtual network gateway's BGP speaker settings. + BgpSettings *BgpSettings + + // The reference to the address space resource which represents the custom routes address space specified by the customer + // for virtual network gateway and VpnClient. + CustomRoutes *AddressSpace + + // disableIPSecReplayProtection flag. + DisableIPSecReplayProtection *bool + + // Whether BGP is enabled for this virtual network gateway or not. + EnableBgp *bool + + // EnableBgpRouteTranslationForNat flag. + EnableBgpRouteTranslationForNat *bool + + // Whether dns forwarding is enabled or not. + EnableDNSForwarding *bool + + // Whether private IP needs to be enabled on this gateway for connections or not. + EnablePrivateIPAddress *bool + + // The reference to the LocalNetworkGateway resource which represents local network site having default routes. Assign Null + // value in case of removing existing default site setting. + GatewayDefaultSite *SubResource + + // The type of this virtual network gateway. + GatewayType *VirtualNetworkGatewayType + + // IP configurations for virtual network gateway. + IPConfigurations []*VirtualNetworkGatewayIPConfiguration + + // NatRules for virtual network gateway. + NatRules []*VirtualNetworkGatewayNatRule + + // The reference to the VirtualNetworkGatewaySku resource which represents the SKU selected for Virtual network gateway. + SKU *VirtualNetworkGatewaySKU + + // Customer vnet resource id. VirtualNetworkGateway of type local gateway is associated with the customer vnet. + VNetExtendedLocationResourceID *string + + // The reference to the VpnClientConfiguration resource which represents the P2S VpnClient configurations. + VPNClientConfiguration *VPNClientConfiguration + + // The generation for this VirtualNetworkGateway. Must be None if gatewayType is not VPN. + VPNGatewayGeneration *VPNGatewayGeneration + + // The type of this virtual network gateway. + VPNType *VPNType + + // The reference to the VirtualNetworkGatewayPolicyGroup resource which represents the available VirtualNetworkGatewayPolicyGroup + // for the gateway. + VirtualNetworkGatewayPolicyGroups []*VirtualNetworkGatewayPolicyGroup + + // READ-ONLY; The IP address allocated by the gateway to which dns requests can be sent. + InboundDNSForwardingEndpoint *string + + // READ-ONLY; The provisioning state of the virtual network gateway resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the virtual network gateway resource. + ResourceGUID *string +} + +// VirtualNetworkGatewaySKU - VirtualNetworkGatewaySku details. +type VirtualNetworkGatewaySKU struct { + // Gateway SKU name. + Name *VirtualNetworkGatewaySKUName + + // Gateway SKU tier. + Tier *VirtualNetworkGatewaySKUTier + + // READ-ONLY; The capacity. + Capacity *int32 +} + +// VirtualNetworkListResult - Response for the ListVirtualNetworks API service call. +type VirtualNetworkListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of VirtualNetwork resources in a resource group. + Value []*VirtualNetwork +} + +// VirtualNetworkListUsageResult - Response for the virtual networks GetUsage API service call. +type VirtualNetworkListUsageResult struct { + // The URL to get the next set of results. + NextLink *string + + // READ-ONLY; VirtualNetwork usage stats. + Value []*VirtualNetworkUsage +} + +// VirtualNetworkPeering - Peerings in a virtual network resource. +type VirtualNetworkPeering struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the virtual network peering. + Properties *VirtualNetworkPeeringPropertiesFormat + + // Resource type. + Type *string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VirtualNetworkPeeringListResult - Response for ListSubnets API service call. Retrieves all subnets that belong to a virtual +// network. +type VirtualNetworkPeeringListResult struct { + // The URL to get the next set of results. + NextLink *string + + // The peerings in a virtual network. + Value []*VirtualNetworkPeering +} + +// VirtualNetworkPeeringPropertiesFormat - Properties of the virtual network peering. +type VirtualNetworkPeeringPropertiesFormat struct { + // Whether the forwarded traffic from the VMs in the local virtual network will be allowed/disallowed in remote virtual network. + AllowForwardedTraffic *bool + + // If gateway links can be used in remote virtual networking to link to this virtual network. + AllowGatewayTransit *bool + + // Whether the VMs in the local virtual network space would be able to access the VMs in remote virtual network space. + AllowVirtualNetworkAccess *bool + + // If we need to verify the provisioning state of the remote gateway. + DoNotVerifyRemoteGateways *bool + + // The status of the virtual network peering. + PeeringState *VirtualNetworkPeeringState + + // The peering sync status of the virtual network peering. + PeeringSyncLevel *VirtualNetworkPeeringLevel + + // The reference to the address space peered with the remote virtual network. + RemoteAddressSpace *AddressSpace + + // The reference to the remote virtual network's Bgp Communities. + RemoteBgpCommunities *VirtualNetworkBgpCommunities + + // The reference to the remote virtual network. The remote virtual network can be in the same or different region (preview). + // See here to register for the preview and learn more + // (https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering). + RemoteVirtualNetwork *SubResource + + // The reference to the current address space of the remote virtual network. + RemoteVirtualNetworkAddressSpace *AddressSpace + + // If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering + // is also true, virtual network will use gateways of remote virtual network + // for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a + // gateway. + UseRemoteGateways *bool + + // READ-ONLY; The provisioning state of the virtual network peering resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The reference to the remote virtual network's encryption + RemoteVirtualNetworkEncryption *VirtualNetworkEncryption + + // READ-ONLY; The resourceGuid property of the Virtual Network peering resource. + ResourceGUID *string +} + +// VirtualNetworkPropertiesFormat - Properties of the virtual network. +type VirtualNetworkPropertiesFormat struct { + // The AddressSpace that contains an array of IP address ranges that can be used by subnets. + AddressSpace *AddressSpace + + // Bgp Communities sent over ExpressRoute with each route corresponding to a prefix in this VNET. + BgpCommunities *VirtualNetworkBgpCommunities + + // The DDoS protection plan associated with the virtual network. + DdosProtectionPlan *SubResource + + // The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network. + DhcpOptions *DhcpOptions + + // Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection + // plan associated with the resource. + EnableDdosProtection *bool + + // Indicates if VM protection is enabled for all the subnets in the virtual network. + EnableVMProtection *bool + + // Indicates if encryption is enabled on virtual network and if VM without encryption is allowed in encrypted VNet. + Encryption *VirtualNetworkEncryption + + // The FlowTimeout value (in minutes) for the Virtual Network + FlowTimeoutInMinutes *int32 + + // Array of IpAllocation which reference this VNET. + IPAllocations []*SubResource + + // A list of subnets in a Virtual Network. + Subnets []*Subnet + + // A list of peerings in a Virtual Network. + VirtualNetworkPeerings []*VirtualNetworkPeering + + // READ-ONLY; A collection of references to flow log resources. + FlowLogs []*FlowLog + + // READ-ONLY; The provisioning state of the virtual network resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resourceGuid property of the Virtual Network resource. + ResourceGUID *string +} + +// VirtualNetworkTap - Virtual Network Tap resource. +type VirtualNetworkTap struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Virtual Network Tap Properties. + Properties *VirtualNetworkTapPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualNetworkTapListResult - Response for ListVirtualNetworkTap API service call. +type VirtualNetworkTapListResult struct { + // The URL to get the next set of results. + NextLink *string + + // A list of VirtualNetworkTaps in a resource group. + Value []*VirtualNetworkTap +} + +// VirtualNetworkTapPropertiesFormat - Virtual Network Tap properties. +type VirtualNetworkTapPropertiesFormat struct { + // The reference to the private IP address on the internal Load Balancer that will receive the tap. + DestinationLoadBalancerFrontEndIPConfiguration *FrontendIPConfiguration + + // The reference to the private IP Address of the collector nic that will receive the tap. + DestinationNetworkInterfaceIPConfiguration *InterfaceIPConfiguration + + // The VXLAN destination port that will receive the tapped traffic. + DestinationPort *int32 + + // READ-ONLY; Specifies the list of resource IDs for the network interface IP configuration that needs to be tapped. + NetworkInterfaceTapConfigurations []*InterfaceTapConfiguration + + // READ-ONLY; The provisioning state of the virtual network tap resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The resource GUID property of the virtual network tap resource. + ResourceGUID *string +} + +// VirtualNetworkUsage - Usage details for subnet. +type VirtualNetworkUsage struct { + // READ-ONLY; Indicates number of IPs used from the Subnet. + CurrentValue *float64 + + // READ-ONLY; Subnet identifier. + ID *string + + // READ-ONLY; Indicates the size of the subnet. + Limit *float64 + + // READ-ONLY; The name containing common and localized value for usage. + Name *VirtualNetworkUsageName + + // READ-ONLY; Usage units. Returns 'Count'. + Unit *string +} + +// VirtualNetworkUsageName - Usage strings container. +type VirtualNetworkUsageName struct { + // READ-ONLY; Localized subnet size and usage string. + LocalizedValue *string + + // READ-ONLY; Subnet size and usage string. + Value *string +} + +// VirtualRouter Resource. +type VirtualRouter struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the Virtual Router. + Properties *VirtualRouterPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualRouterAutoScaleConfiguration - The VirtualHub Router autoscale configuration. +type VirtualRouterAutoScaleConfiguration struct { + // The minimum number of scale units for VirtualHub Router. + MinCapacity *int32 +} + +// VirtualRouterListResult - Response for ListVirtualRouters API service call. +type VirtualRouterListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of Virtual Routers. + Value []*VirtualRouter +} + +// VirtualRouterPeering - Virtual Router Peering resource. +type VirtualRouterPeering struct { + // Resource ID. + ID *string + + // Name of the virtual router peering that is unique within a virtual router. + Name *string + + // The properties of the Virtual Router Peering. + Properties *VirtualRouterPeeringProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Peering type. + Type *string +} + +// VirtualRouterPeeringListResult - Response for ListVirtualRouterPeerings API service call. +type VirtualRouterPeeringListResult struct { + // URL to get the next set of results. + NextLink *string + + // List of VirtualRouterPeerings in a VirtualRouter. + Value []*VirtualRouterPeering +} + +// VirtualRouterPeeringProperties - Properties of the rule group. +type VirtualRouterPeeringProperties struct { + // Peer ASN. + PeerAsn *int64 + + // Peer IP. + PeerIP *string + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// VirtualRouterPropertiesFormat - Virtual Router definition. +type VirtualRouterPropertiesFormat struct { + // The Gateway on which VirtualRouter is hosted. + HostedGateway *SubResource + + // The Subnet on which VirtualRouter is hosted. + HostedSubnet *SubResource + + // VirtualRouter ASN. + VirtualRouterAsn *int64 + + // VirtualRouter IPs. + VirtualRouterIPs []*string + + // READ-ONLY; List of references to VirtualRouterPeerings. + Peerings []*SubResource + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// VirtualWAN Resource. +type VirtualWAN struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the virtual WAN. + Properties *VirtualWanProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// VirtualWanProperties - Parameters for VirtualWAN. +type VirtualWanProperties struct { + // True if branch to branch traffic is allowed. + AllowBranchToBranchTraffic *bool + + // True if Vnet to Vnet traffic is allowed. + AllowVnetToVnetTraffic *bool + + // Vpn encryption to be disabled or not. + DisableVPNEncryption *bool + + // The type of the VirtualWAN. + Type *string + + // READ-ONLY; The office local breakout category. + Office365LocalBreakoutCategory *OfficeTrafficCategory + + // READ-ONLY; The provisioning state of the virtual WAN resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; List of VpnSites in the VirtualWAN. + VPNSites []*SubResource + + // READ-ONLY; List of VirtualHubs in the VirtualWAN. + VirtualHubs []*SubResource +} + +// VirtualWanSecurityProvider - Collection of SecurityProviders. +type VirtualWanSecurityProvider struct { + // Name of the security provider. + Name *string + + // Url of the security provider. + URL *string + + // READ-ONLY; Name of the security provider. + Type *VirtualWanSecurityProviderType +} + +// VirtualWanSecurityProviders - Collection of SecurityProviders. +type VirtualWanSecurityProviders struct { + // List of VirtualWAN security providers. + SupportedProviders []*VirtualWanSecurityProvider +} + +// VirtualWanVPNProfileParameters - Virtual Wan Vpn profile parameters Vpn profile generation. +type VirtualWanVPNProfileParameters struct { + // VPN client authentication method. + AuthenticationMethod *AuthenticationMethod + + // VpnServerConfiguration partial resource uri with which VirtualWan is associated to. + VPNServerConfigurationResourceID *string +} + +// VnetRoute - List of routes that control routing from VirtualHub into a virtual network connection. +type VnetRoute struct { + // List of all Static Routes. + StaticRoutes []*StaticRoute + + // Configuration for static routes on this HubVnetConnection. + StaticRoutesConfig *StaticRoutesConfig + + // READ-ONLY; The list of references to HubBgpConnection objects. + BgpConnections []*SubResource +} + +// VngClientConnectionConfiguration - A vpn client connection configuration for client connection configuration. +type VngClientConnectionConfiguration struct { + // Resource ID. + ID *string + + // The name of the resource that is unique within a resource group. This name can be used to access the resource. + Name *string + + // Properties of the vpn client root certificate. + Properties *VngClientConnectionConfigurationProperties + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// VngClientConnectionConfigurationProperties - Properties of VngClientConnectionConfiguration. +type VngClientConnectionConfigurationProperties struct { + // REQUIRED; The reference to the address space resource which represents Address space for P2S VpnClient. + VPNClientAddressPool *AddressSpace + + // REQUIRED; List of references to virtualNetworkGatewayPolicyGroups + VirtualNetworkGatewayPolicyGroups []*SubResource + + // READ-ONLY; The provisioning state of the VngClientConnectionConfiguration resource. + ProvisioningState *ProvisioningState +} + +// Watcher - Network watcher in a resource group. +type Watcher struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the network watcher. + Properties *WatcherPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// WatcherListResult - Response for ListNetworkWatchers API service call. +type WatcherListResult struct { + // List of network watcher resources. + Value []*Watcher +} + +// WatcherPropertiesFormat - The network watcher properties. +type WatcherPropertiesFormat struct { + // READ-ONLY; The provisioning state of the network watcher resource. + ProvisioningState *ProvisioningState +} + +// WebApplicationFirewallCustomRule - Defines contents of a web application rule. +type WebApplicationFirewallCustomRule struct { + // REQUIRED; Type of Actions. + Action *WebApplicationFirewallAction + + // REQUIRED; List of match conditions. + MatchConditions []*MatchCondition + + // REQUIRED; Priority of the rule. Rules with a lower value will be evaluated before rules with a higher value. + Priority *int32 + + // REQUIRED; The rule type. + RuleType *WebApplicationFirewallRuleType + + // List of user session identifier group by clauses. + GroupByUserSession []*GroupByUserSession + + // The name of the resource that is unique within a policy. This name can be used to access the resource. + Name *string + + // Duration over which Rate Limit policy will be applied. Applies only when ruleType is RateLimitRule. + RateLimitDuration *ApplicationGatewayFirewallRateLimitDuration + + // Rate Limit threshold to apply in case ruleType is RateLimitRule. Must be greater than or equal to 1 + RateLimitThreshold *int32 + + // Describes if the custom rule is in enabled or disabled state. Defaults to Enabled if not specified. + State *WebApplicationFirewallState + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string +} + +// WebApplicationFirewallPolicy - Defines web application firewall policy. +type WebApplicationFirewallPolicy struct { + // Resource ID. + ID *string + + // Resource location. + Location *string + + // Properties of the web application firewall policy. + Properties *WebApplicationFirewallPolicyPropertiesFormat + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string + + // READ-ONLY; Resource name. + Name *string + + // READ-ONLY; Resource type. + Type *string +} + +// WebApplicationFirewallPolicyListResult - Result of the request to list WebApplicationFirewallPolicies. It contains a list +// of WebApplicationFirewallPolicy objects and a URL link to get the next set of results. +type WebApplicationFirewallPolicyListResult struct { + // READ-ONLY; URL to get the next set of WebApplicationFirewallPolicy objects if there are any. + NextLink *string + + // READ-ONLY; List of WebApplicationFirewallPolicies within a resource group. + Value []*WebApplicationFirewallPolicy +} + +// WebApplicationFirewallPolicyPropertiesFormat - Defines web application firewall policy properties. +type WebApplicationFirewallPolicyPropertiesFormat struct { + // REQUIRED; Describes the managedRules structure. + ManagedRules *ManagedRulesDefinition + + // The custom rules inside the policy. + CustomRules []*WebApplicationFirewallCustomRule + + // The PolicySettings for policy. + PolicySettings *PolicySettings + + // READ-ONLY; A collection of references to application gateways. + ApplicationGateways []*ApplicationGateway + + // READ-ONLY; A collection of references to application gateway http listeners. + HTTPListeners []*SubResource + + // READ-ONLY; A collection of references to application gateway path rules. + PathBasedRules []*SubResource + + // READ-ONLY; The provisioning state of the web application firewall policy resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; Resource status of the policy. + ResourceState *WebApplicationFirewallPolicyResourceState +} + +// WebApplicationFirewallScrubbingRules - Allow certain variables to be scrubbed on WAF logs +type WebApplicationFirewallScrubbingRules struct { + // REQUIRED; The variable to be scrubbed from the logs. + MatchVariable *ScrubbingRuleEntryMatchVariable + + // REQUIRED; When matchVariable is a collection, operate on the selector to specify which elements in the collection this + // rule applies to. + SelectorMatchOperator *ScrubbingRuleEntryMatchOperator + + // When matchVariable is a collection, operator used to specify which elements in the collection this rule applies to. + Selector *string + + // Defines the state of log scrubbing rule. Default value is Enabled. + State *ScrubbingRuleEntryState +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/models_serde.go new file mode 100644 index 000000000..affbe8f63 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/models_serde.go @@ -0,0 +1,34501 @@ +//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 armnetwork + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AADAuthenticationParameters. +func (a AADAuthenticationParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aadAudience", a.AADAudience) + populate(objectMap, "aadIssuer", a.AADIssuer) + populate(objectMap, "aadTenant", a.AADTenant) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AADAuthenticationParameters. +func (a *AADAuthenticationParameters) UnmarshalJSON(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 "aadAudience": + err = unpopulate(val, "AADAudience", &a.AADAudience) + delete(rawMsg, key) + case "aadIssuer": + err = unpopulate(val, "AADIssuer", &a.AADIssuer) + delete(rawMsg, key) + case "aadTenant": + err = unpopulate(val, "AADTenant", &a.AADTenant) + 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, "parameters", a.Parameters) + 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 "parameters": + err = unpopulate(val, "Parameters", &a.Parameters) + 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 ActiveBaseSecurityAdminRule. +func (a ActiveBaseSecurityAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "commitTime", a.CommitTime) + populate(objectMap, "configurationDescription", a.ConfigurationDescription) + populate(objectMap, "id", a.ID) + objectMap["kind"] = a.Kind + populate(objectMap, "region", a.Region) + populate(objectMap, "ruleCollectionAppliesToGroups", a.RuleCollectionAppliesToGroups) + populate(objectMap, "ruleCollectionDescription", a.RuleCollectionDescription) + populate(objectMap, "ruleGroups", a.RuleGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveBaseSecurityAdminRule. +func (a *ActiveBaseSecurityAdminRule) UnmarshalJSON(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 "commitTime": + err = unpopulateDateTimeRFC3339(val, "CommitTime", &a.CommitTime) + delete(rawMsg, key) + case "configurationDescription": + err = unpopulate(val, "ConfigurationDescription", &a.ConfigurationDescription) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "region": + err = unpopulate(val, "Region", &a.Region) + delete(rawMsg, key) + case "ruleCollectionAppliesToGroups": + err = unpopulate(val, "RuleCollectionAppliesToGroups", &a.RuleCollectionAppliesToGroups) + delete(rawMsg, key) + case "ruleCollectionDescription": + err = unpopulate(val, "RuleCollectionDescription", &a.RuleCollectionDescription) + delete(rawMsg, key) + case "ruleGroups": + err = unpopulate(val, "RuleGroups", &a.RuleGroups) + 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 ActiveConfigurationParameter. +func (a ActiveConfigurationParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "regions", a.Regions) + populate(objectMap, "skipToken", a.SkipToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveConfigurationParameter. +func (a *ActiveConfigurationParameter) UnmarshalJSON(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 "regions": + err = unpopulate(val, "Regions", &a.Regions) + delete(rawMsg, key) + case "skipToken": + err = unpopulate(val, "SkipToken", &a.SkipToken) + 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 ActiveConnectivityConfiguration. +func (a ActiveConnectivityConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "commitTime", a.CommitTime) + populate(objectMap, "configurationGroups", a.ConfigurationGroups) + populate(objectMap, "id", a.ID) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "region", a.Region) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveConnectivityConfiguration. +func (a *ActiveConnectivityConfiguration) UnmarshalJSON(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 "commitTime": + err = unpopulateDateTimeRFC3339(val, "CommitTime", &a.CommitTime) + delete(rawMsg, key) + case "configurationGroups": + err = unpopulate(val, "ConfigurationGroups", &a.ConfigurationGroups) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "region": + err = unpopulate(val, "Region", &a.Region) + 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 ActiveConnectivityConfigurationsListResult. +func (a ActiveConnectivityConfigurationsListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipToken", a.SkipToken) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveConnectivityConfigurationsListResult. +func (a *ActiveConnectivityConfigurationsListResult) UnmarshalJSON(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 "skipToken": + err = unpopulate(val, "SkipToken", &a.SkipToken) + 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 ActiveDefaultSecurityAdminRule. +func (a ActiveDefaultSecurityAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "commitTime", a.CommitTime) + populate(objectMap, "configurationDescription", a.ConfigurationDescription) + populate(objectMap, "id", a.ID) + objectMap["kind"] = EffectiveAdminRuleKindDefault + populate(objectMap, "properties", a.Properties) + populate(objectMap, "region", a.Region) + populate(objectMap, "ruleCollectionAppliesToGroups", a.RuleCollectionAppliesToGroups) + populate(objectMap, "ruleCollectionDescription", a.RuleCollectionDescription) + populate(objectMap, "ruleGroups", a.RuleGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveDefaultSecurityAdminRule. +func (a *ActiveDefaultSecurityAdminRule) UnmarshalJSON(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 "commitTime": + err = unpopulateDateTimeRFC3339(val, "CommitTime", &a.CommitTime) + delete(rawMsg, key) + case "configurationDescription": + err = unpopulate(val, "ConfigurationDescription", &a.ConfigurationDescription) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + 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 "region": + err = unpopulate(val, "Region", &a.Region) + delete(rawMsg, key) + case "ruleCollectionAppliesToGroups": + err = unpopulate(val, "RuleCollectionAppliesToGroups", &a.RuleCollectionAppliesToGroups) + delete(rawMsg, key) + case "ruleCollectionDescription": + err = unpopulate(val, "RuleCollectionDescription", &a.RuleCollectionDescription) + delete(rawMsg, key) + case "ruleGroups": + err = unpopulate(val, "RuleGroups", &a.RuleGroups) + 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 ActiveSecurityAdminRule. +func (a ActiveSecurityAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "commitTime", a.CommitTime) + populate(objectMap, "configurationDescription", a.ConfigurationDescription) + populate(objectMap, "id", a.ID) + objectMap["kind"] = EffectiveAdminRuleKindCustom + populate(objectMap, "properties", a.Properties) + populate(objectMap, "region", a.Region) + populate(objectMap, "ruleCollectionAppliesToGroups", a.RuleCollectionAppliesToGroups) + populate(objectMap, "ruleCollectionDescription", a.RuleCollectionDescription) + populate(objectMap, "ruleGroups", a.RuleGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveSecurityAdminRule. +func (a *ActiveSecurityAdminRule) UnmarshalJSON(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 "commitTime": + err = unpopulateDateTimeRFC3339(val, "CommitTime", &a.CommitTime) + delete(rawMsg, key) + case "configurationDescription": + err = unpopulate(val, "ConfigurationDescription", &a.ConfigurationDescription) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + 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 "region": + err = unpopulate(val, "Region", &a.Region) + delete(rawMsg, key) + case "ruleCollectionAppliesToGroups": + err = unpopulate(val, "RuleCollectionAppliesToGroups", &a.RuleCollectionAppliesToGroups) + delete(rawMsg, key) + case "ruleCollectionDescription": + err = unpopulate(val, "RuleCollectionDescription", &a.RuleCollectionDescription) + delete(rawMsg, key) + case "ruleGroups": + err = unpopulate(val, "RuleGroups", &a.RuleGroups) + 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 ActiveSecurityAdminRulesListResult. +func (a ActiveSecurityAdminRulesListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipToken", a.SkipToken) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveSecurityAdminRulesListResult. +func (a *ActiveSecurityAdminRulesListResult) UnmarshalJSON(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 "skipToken": + err = unpopulate(val, "SkipToken", &a.SkipToken) + delete(rawMsg, key) + case "value": + a.Value, err = unmarshalActiveBaseSecurityAdminRuleClassificationArray(val) + 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 AddressPrefixItem. +func (a AddressPrefixItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", a.AddressPrefix) + populate(objectMap, "addressPrefixType", a.AddressPrefixType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AddressPrefixItem. +func (a *AddressPrefixItem) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &a.AddressPrefix) + delete(rawMsg, key) + case "addressPrefixType": + err = unpopulate(val, "AddressPrefixType", &a.AddressPrefixType) + 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 AddressSpace. +func (a AddressSpace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefixes", a.AddressPrefixes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AddressSpace. +func (a *AddressSpace) UnmarshalJSON(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 "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &a.AddressPrefixes) + 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 AdminPropertiesFormat. +func (a AdminPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", a.Access) + populate(objectMap, "description", a.Description) + populate(objectMap, "destinationPortRanges", a.DestinationPortRanges) + populate(objectMap, "destinations", a.Destinations) + populate(objectMap, "direction", a.Direction) + populate(objectMap, "priority", a.Priority) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "resourceGuid", a.ResourceGUID) + populate(objectMap, "sourcePortRanges", a.SourcePortRanges) + populate(objectMap, "sources", a.Sources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdminPropertiesFormat. +func (a *AdminPropertiesFormat) UnmarshalJSON(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 "access": + err = unpopulate(val, "Access", &a.Access) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "destinationPortRanges": + err = unpopulate(val, "DestinationPortRanges", &a.DestinationPortRanges) + delete(rawMsg, key) + case "destinations": + err = unpopulate(val, "Destinations", &a.Destinations) + delete(rawMsg, key) + case "direction": + err = unpopulate(val, "Direction", &a.Direction) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &a.Priority) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &a.ResourceGUID) + delete(rawMsg, key) + case "sourcePortRanges": + err = unpopulate(val, "SourcePortRanges", &a.SourcePortRanges) + delete(rawMsg, key) + case "sources": + err = unpopulate(val, "Sources", &a.Sources) + 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 AdminRule. +func (a AdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "id", a.ID) + objectMap["kind"] = AdminRuleKindCustom + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdminRule. +func (a *AdminRule) UnmarshalJSON(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 "kind": + err = unpopulate(val, "Kind", &a.Kind) + 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 "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 AdminRuleCollection. +func (a AdminRuleCollection) 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, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdminRuleCollection. +func (a *AdminRuleCollection) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + 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 AdminRuleCollectionListResult. +func (a AdminRuleCollectionListResult) 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 AdminRuleCollectionListResult. +func (a *AdminRuleCollectionListResult) UnmarshalJSON(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 AdminRuleCollectionPropertiesFormat. +func (a AdminRuleCollectionPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliesToGroups", a.AppliesToGroups) + populate(objectMap, "description", a.Description) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "resourceGuid", a.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdminRuleCollectionPropertiesFormat. +func (a *AdminRuleCollectionPropertiesFormat) UnmarshalJSON(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 "appliesToGroups": + err = unpopulate(val, "AppliesToGroups", &a.AppliesToGroups) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &a.ResourceGUID) + 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 AdminRuleListResult. +func (a AdminRuleListResult) 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 AdminRuleListResult. +func (a *AdminRuleListResult) UnmarshalJSON(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": + a.Value, err = unmarshalBaseAdminRuleClassificationArray(val) + 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 ApplicationGateway. +func (a ApplicationGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "id", a.ID) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + populate(objectMap, "zones", a.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGateway. +func (a *ApplicationGateway) UnmarshalJSON(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 "identity": + err = unpopulate(val, "Identity", &a.Identity) + 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 "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &a.Zones) + 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 ApplicationGatewayAuthenticationCertificate. +func (a ApplicationGatewayAuthenticationCertificate) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayAuthenticationCertificate. +func (a *ApplicationGatewayAuthenticationCertificate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayAuthenticationCertificatePropertiesFormat. +func (a ApplicationGatewayAuthenticationCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "data", a.Data) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayAuthenticationCertificatePropertiesFormat. +func (a *ApplicationGatewayAuthenticationCertificatePropertiesFormat) UnmarshalJSON(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 "data": + err = unpopulate(val, "Data", &a.Data) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayAutoscaleConfiguration. +func (a ApplicationGatewayAutoscaleConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "maxCapacity", a.MaxCapacity) + populate(objectMap, "minCapacity", a.MinCapacity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayAutoscaleConfiguration. +func (a *ApplicationGatewayAutoscaleConfiguration) UnmarshalJSON(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 "maxCapacity": + err = unpopulate(val, "MaxCapacity", &a.MaxCapacity) + delete(rawMsg, key) + case "minCapacity": + err = unpopulate(val, "MinCapacity", &a.MinCapacity) + 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 ApplicationGatewayAvailableSSLOptions. +func (a ApplicationGatewayAvailableSSLOptions) 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, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayAvailableSSLOptions. +func (a *ApplicationGatewayAvailableSSLOptions) UnmarshalJSON(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 "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 ApplicationGatewayAvailableSSLOptionsPropertiesFormat. +func (a ApplicationGatewayAvailableSSLOptionsPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableCipherSuites", a.AvailableCipherSuites) + populate(objectMap, "availableProtocols", a.AvailableProtocols) + populate(objectMap, "defaultPolicy", a.DefaultPolicy) + populate(objectMap, "predefinedPolicies", a.PredefinedPolicies) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayAvailableSSLOptionsPropertiesFormat. +func (a *ApplicationGatewayAvailableSSLOptionsPropertiesFormat) UnmarshalJSON(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 "availableCipherSuites": + err = unpopulate(val, "AvailableCipherSuites", &a.AvailableCipherSuites) + delete(rawMsg, key) + case "availableProtocols": + err = unpopulate(val, "AvailableProtocols", &a.AvailableProtocols) + delete(rawMsg, key) + case "defaultPolicy": + err = unpopulate(val, "DefaultPolicy", &a.DefaultPolicy) + delete(rawMsg, key) + case "predefinedPolicies": + err = unpopulate(val, "PredefinedPolicies", &a.PredefinedPolicies) + 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 ApplicationGatewayAvailableSSLPredefinedPolicies. +func (a ApplicationGatewayAvailableSSLPredefinedPolicies) 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 ApplicationGatewayAvailableSSLPredefinedPolicies. +func (a *ApplicationGatewayAvailableSSLPredefinedPolicies) UnmarshalJSON(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 ApplicationGatewayAvailableWafRuleSetsResult. +func (a ApplicationGatewayAvailableWafRuleSetsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayAvailableWafRuleSetsResult. +func (a *ApplicationGatewayAvailableWafRuleSetsResult) UnmarshalJSON(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 "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 ApplicationGatewayBackendAddress. +func (a ApplicationGatewayBackendAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fqdn", a.Fqdn) + populate(objectMap, "ipAddress", a.IPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendAddress. +func (a *ApplicationGatewayBackendAddress) UnmarshalJSON(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 "fqdn": + err = unpopulate(val, "Fqdn", &a.Fqdn) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &a.IPAddress) + 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 ApplicationGatewayBackendAddressPool. +func (a ApplicationGatewayBackendAddressPool) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendAddressPool. +func (a *ApplicationGatewayBackendAddressPool) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayBackendAddressPoolPropertiesFormat. +func (a ApplicationGatewayBackendAddressPoolPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddresses", a.BackendAddresses) + populate(objectMap, "backendIPConfigurations", a.BackendIPConfigurations) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendAddressPoolPropertiesFormat. +func (a *ApplicationGatewayBackendAddressPoolPropertiesFormat) UnmarshalJSON(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 "backendAddresses": + err = unpopulate(val, "BackendAddresses", &a.BackendAddresses) + delete(rawMsg, key) + case "backendIPConfigurations": + err = unpopulate(val, "BackendIPConfigurations", &a.BackendIPConfigurations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayBackendHTTPSettings. +func (a ApplicationGatewayBackendHTTPSettings) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendHTTPSettings. +func (a *ApplicationGatewayBackendHTTPSettings) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayBackendHTTPSettingsPropertiesFormat. +func (a ApplicationGatewayBackendHTTPSettingsPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "affinityCookieName", a.AffinityCookieName) + populate(objectMap, "authenticationCertificates", a.AuthenticationCertificates) + populate(objectMap, "connectionDraining", a.ConnectionDraining) + populate(objectMap, "cookieBasedAffinity", a.CookieBasedAffinity) + populate(objectMap, "hostName", a.HostName) + populate(objectMap, "path", a.Path) + populate(objectMap, "pickHostNameFromBackendAddress", a.PickHostNameFromBackendAddress) + populate(objectMap, "port", a.Port) + populate(objectMap, "probe", a.Probe) + populate(objectMap, "probeEnabled", a.ProbeEnabled) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "requestTimeout", a.RequestTimeout) + populate(objectMap, "trustedRootCertificates", a.TrustedRootCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendHTTPSettingsPropertiesFormat. +func (a *ApplicationGatewayBackendHTTPSettingsPropertiesFormat) UnmarshalJSON(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 "affinityCookieName": + err = unpopulate(val, "AffinityCookieName", &a.AffinityCookieName) + delete(rawMsg, key) + case "authenticationCertificates": + err = unpopulate(val, "AuthenticationCertificates", &a.AuthenticationCertificates) + delete(rawMsg, key) + case "connectionDraining": + err = unpopulate(val, "ConnectionDraining", &a.ConnectionDraining) + delete(rawMsg, key) + case "cookieBasedAffinity": + err = unpopulate(val, "CookieBasedAffinity", &a.CookieBasedAffinity) + delete(rawMsg, key) + case "hostName": + err = unpopulate(val, "HostName", &a.HostName) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &a.Path) + delete(rawMsg, key) + case "pickHostNameFromBackendAddress": + err = unpopulate(val, "PickHostNameFromBackendAddress", &a.PickHostNameFromBackendAddress) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &a.Port) + delete(rawMsg, key) + case "probe": + err = unpopulate(val, "Probe", &a.Probe) + delete(rawMsg, key) + case "probeEnabled": + err = unpopulate(val, "ProbeEnabled", &a.ProbeEnabled) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "requestTimeout": + err = unpopulate(val, "RequestTimeout", &a.RequestTimeout) + delete(rawMsg, key) + case "trustedRootCertificates": + err = unpopulate(val, "TrustedRootCertificates", &a.TrustedRootCertificates) + 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 ApplicationGatewayBackendHealth. +func (a ApplicationGatewayBackendHealth) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPools", a.BackendAddressPools) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendHealth. +func (a *ApplicationGatewayBackendHealth) UnmarshalJSON(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 "backendAddressPools": + err = unpopulate(val, "BackendAddressPools", &a.BackendAddressPools) + 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 ApplicationGatewayBackendHealthHTTPSettings. +func (a ApplicationGatewayBackendHealthHTTPSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendHttpSettings", a.BackendHTTPSettings) + populate(objectMap, "servers", a.Servers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendHealthHTTPSettings. +func (a *ApplicationGatewayBackendHealthHTTPSettings) UnmarshalJSON(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 "backendHttpSettings": + err = unpopulate(val, "BackendHTTPSettings", &a.BackendHTTPSettings) + delete(rawMsg, key) + case "servers": + err = unpopulate(val, "Servers", &a.Servers) + 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 ApplicationGatewayBackendHealthOnDemand. +func (a ApplicationGatewayBackendHealthOnDemand) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", a.BackendAddressPool) + populate(objectMap, "backendHealthHttpSettings", a.BackendHealthHTTPSettings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendHealthOnDemand. +func (a *ApplicationGatewayBackendHealthOnDemand) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &a.BackendAddressPool) + delete(rawMsg, key) + case "backendHealthHttpSettings": + err = unpopulate(val, "BackendHealthHTTPSettings", &a.BackendHealthHTTPSettings) + 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 ApplicationGatewayBackendHealthPool. +func (a ApplicationGatewayBackendHealthPool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", a.BackendAddressPool) + populate(objectMap, "backendHttpSettingsCollection", a.BackendHTTPSettingsCollection) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendHealthPool. +func (a *ApplicationGatewayBackendHealthPool) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &a.BackendAddressPool) + delete(rawMsg, key) + case "backendHttpSettingsCollection": + err = unpopulate(val, "BackendHTTPSettingsCollection", &a.BackendHTTPSettingsCollection) + 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 ApplicationGatewayBackendHealthServer. +func (a ApplicationGatewayBackendHealthServer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", a.Address) + populate(objectMap, "health", a.Health) + populate(objectMap, "healthProbeLog", a.HealthProbeLog) + populate(objectMap, "ipConfiguration", a.IPConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendHealthServer. +func (a *ApplicationGatewayBackendHealthServer) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &a.Address) + delete(rawMsg, key) + case "health": + err = unpopulate(val, "Health", &a.Health) + delete(rawMsg, key) + case "healthProbeLog": + err = unpopulate(val, "HealthProbeLog", &a.HealthProbeLog) + delete(rawMsg, key) + case "ipConfiguration": + err = unpopulate(val, "IPConfiguration", &a.IPConfiguration) + 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 ApplicationGatewayBackendSettings. +func (a ApplicationGatewayBackendSettings) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendSettings. +func (a *ApplicationGatewayBackendSettings) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayBackendSettingsPropertiesFormat. +func (a ApplicationGatewayBackendSettingsPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hostName", a.HostName) + populate(objectMap, "pickHostNameFromBackendAddress", a.PickHostNameFromBackendAddress) + populate(objectMap, "port", a.Port) + populate(objectMap, "probe", a.Probe) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "timeout", a.Timeout) + populate(objectMap, "trustedRootCertificates", a.TrustedRootCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayBackendSettingsPropertiesFormat. +func (a *ApplicationGatewayBackendSettingsPropertiesFormat) UnmarshalJSON(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 "hostName": + err = unpopulate(val, "HostName", &a.HostName) + delete(rawMsg, key) + case "pickHostNameFromBackendAddress": + err = unpopulate(val, "PickHostNameFromBackendAddress", &a.PickHostNameFromBackendAddress) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &a.Port) + delete(rawMsg, key) + case "probe": + err = unpopulate(val, "Probe", &a.Probe) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &a.Timeout) + delete(rawMsg, key) + case "trustedRootCertificates": + err = unpopulate(val, "TrustedRootCertificates", &a.TrustedRootCertificates) + 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 ApplicationGatewayClientAuthConfiguration. +func (a ApplicationGatewayClientAuthConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "verifyClientCertIssuerDN", a.VerifyClientCertIssuerDN) + populate(objectMap, "verifyClientRevocation", a.VerifyClientRevocation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayClientAuthConfiguration. +func (a *ApplicationGatewayClientAuthConfiguration) UnmarshalJSON(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 "verifyClientCertIssuerDN": + err = unpopulate(val, "VerifyClientCertIssuerDN", &a.VerifyClientCertIssuerDN) + delete(rawMsg, key) + case "verifyClientRevocation": + err = unpopulate(val, "VerifyClientRevocation", &a.VerifyClientRevocation) + 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 ApplicationGatewayConnectionDraining. +func (a ApplicationGatewayConnectionDraining) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "drainTimeoutInSec", a.DrainTimeoutInSec) + populate(objectMap, "enabled", a.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayConnectionDraining. +func (a *ApplicationGatewayConnectionDraining) UnmarshalJSON(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 "drainTimeoutInSec": + err = unpopulate(val, "DrainTimeoutInSec", &a.DrainTimeoutInSec) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &a.Enabled) + 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 ApplicationGatewayCustomError. +func (a ApplicationGatewayCustomError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customErrorPageUrl", a.CustomErrorPageURL) + populate(objectMap, "statusCode", a.StatusCode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayCustomError. +func (a *ApplicationGatewayCustomError) UnmarshalJSON(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 "customErrorPageUrl": + err = unpopulate(val, "CustomErrorPageURL", &a.CustomErrorPageURL) + delete(rawMsg, key) + case "statusCode": + err = unpopulate(val, "StatusCode", &a.StatusCode) + 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 ApplicationGatewayFirewallDisabledRuleGroup. +func (a ApplicationGatewayFirewallDisabledRuleGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleGroupName", a.RuleGroupName) + populate(objectMap, "rules", a.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFirewallDisabledRuleGroup. +func (a *ApplicationGatewayFirewallDisabledRuleGroup) UnmarshalJSON(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 "ruleGroupName": + err = unpopulate(val, "RuleGroupName", &a.RuleGroupName) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &a.Rules) + 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 ApplicationGatewayFirewallExclusion. +func (a ApplicationGatewayFirewallExclusion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "matchVariable", a.MatchVariable) + populate(objectMap, "selector", a.Selector) + populate(objectMap, "selectorMatchOperator", a.SelectorMatchOperator) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFirewallExclusion. +func (a *ApplicationGatewayFirewallExclusion) UnmarshalJSON(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 "matchVariable": + err = unpopulate(val, "MatchVariable", &a.MatchVariable) + delete(rawMsg, key) + case "selector": + err = unpopulate(val, "Selector", &a.Selector) + delete(rawMsg, key) + case "selectorMatchOperator": + err = unpopulate(val, "SelectorMatchOperator", &a.SelectorMatchOperator) + 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 ApplicationGatewayFirewallManifestRuleSet. +func (a ApplicationGatewayFirewallManifestRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleGroups", a.RuleGroups) + populate(objectMap, "ruleSetType", a.RuleSetType) + populate(objectMap, "ruleSetVersion", a.RuleSetVersion) + populate(objectMap, "status", a.Status) + populate(objectMap, "tiers", a.Tiers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFirewallManifestRuleSet. +func (a *ApplicationGatewayFirewallManifestRuleSet) UnmarshalJSON(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 "ruleGroups": + err = unpopulate(val, "RuleGroups", &a.RuleGroups) + delete(rawMsg, key) + case "ruleSetType": + err = unpopulate(val, "RuleSetType", &a.RuleSetType) + delete(rawMsg, key) + case "ruleSetVersion": + err = unpopulate(val, "RuleSetVersion", &a.RuleSetVersion) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &a.Status) + delete(rawMsg, key) + case "tiers": + err = unpopulate(val, "Tiers", &a.Tiers) + 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 ApplicationGatewayFirewallRule. +func (a ApplicationGatewayFirewallRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", a.Action) + populate(objectMap, "description", a.Description) + populate(objectMap, "ruleId", a.RuleID) + populate(objectMap, "ruleIdString", a.RuleIDString) + populate(objectMap, "state", a.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFirewallRule. +func (a *ApplicationGatewayFirewallRule) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &a.Action) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "ruleId": + err = unpopulate(val, "RuleID", &a.RuleID) + delete(rawMsg, key) + case "ruleIdString": + err = unpopulate(val, "RuleIDString", &a.RuleIDString) + 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 ApplicationGatewayFirewallRuleGroup. +func (a ApplicationGatewayFirewallRuleGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "ruleGroupName", a.RuleGroupName) + populate(objectMap, "rules", a.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFirewallRuleGroup. +func (a *ApplicationGatewayFirewallRuleGroup) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "ruleGroupName": + err = unpopulate(val, "RuleGroupName", &a.RuleGroupName) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &a.Rules) + 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 ApplicationGatewayFirewallRuleSet. +func (a ApplicationGatewayFirewallRuleSet) 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, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFirewallRuleSet. +func (a *ApplicationGatewayFirewallRuleSet) UnmarshalJSON(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 "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 ApplicationGatewayFirewallRuleSetPropertiesFormat. +func (a ApplicationGatewayFirewallRuleSetPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "ruleGroups", a.RuleGroups) + populate(objectMap, "ruleSetType", a.RuleSetType) + populate(objectMap, "ruleSetVersion", a.RuleSetVersion) + populate(objectMap, "tiers", a.Tiers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFirewallRuleSetPropertiesFormat. +func (a *ApplicationGatewayFirewallRuleSetPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "ruleGroups": + err = unpopulate(val, "RuleGroups", &a.RuleGroups) + delete(rawMsg, key) + case "ruleSetType": + err = unpopulate(val, "RuleSetType", &a.RuleSetType) + delete(rawMsg, key) + case "ruleSetVersion": + err = unpopulate(val, "RuleSetVersion", &a.RuleSetVersion) + delete(rawMsg, key) + case "tiers": + err = unpopulate(val, "Tiers", &a.Tiers) + 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 ApplicationGatewayFrontendIPConfiguration. +func (a ApplicationGatewayFrontendIPConfiguration) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFrontendIPConfiguration. +func (a *ApplicationGatewayFrontendIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayFrontendIPConfigurationPropertiesFormat. +func (a ApplicationGatewayFrontendIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAddress", a.PrivateIPAddress) + populate(objectMap, "privateIPAllocationMethod", a.PrivateIPAllocationMethod) + populate(objectMap, "privateLinkConfiguration", a.PrivateLinkConfiguration) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "publicIPAddress", a.PublicIPAddress) + populate(objectMap, "subnet", a.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFrontendIPConfigurationPropertiesFormat. +func (a *ApplicationGatewayFrontendIPConfigurationPropertiesFormat) UnmarshalJSON(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 "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &a.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &a.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "privateLinkConfiguration": + err = unpopulate(val, "PrivateLinkConfiguration", &a.PrivateLinkConfiguration) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &a.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &a.Subnet) + 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 ApplicationGatewayFrontendPort. +func (a ApplicationGatewayFrontendPort) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFrontendPort. +func (a *ApplicationGatewayFrontendPort) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayFrontendPortPropertiesFormat. +func (a ApplicationGatewayFrontendPortPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "port", a.Port) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayFrontendPortPropertiesFormat. +func (a *ApplicationGatewayFrontendPortPropertiesFormat) UnmarshalJSON(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 "port": + err = unpopulate(val, "Port", &a.Port) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayGlobalConfiguration. +func (a ApplicationGatewayGlobalConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enableRequestBuffering", a.EnableRequestBuffering) + populate(objectMap, "enableResponseBuffering", a.EnableResponseBuffering) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayGlobalConfiguration. +func (a *ApplicationGatewayGlobalConfiguration) UnmarshalJSON(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 "enableRequestBuffering": + err = unpopulate(val, "EnableRequestBuffering", &a.EnableRequestBuffering) + delete(rawMsg, key) + case "enableResponseBuffering": + err = unpopulate(val, "EnableResponseBuffering", &a.EnableResponseBuffering) + 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 ApplicationGatewayHTTPListener. +func (a ApplicationGatewayHTTPListener) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayHTTPListener. +func (a *ApplicationGatewayHTTPListener) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayHTTPListenerPropertiesFormat. +func (a ApplicationGatewayHTTPListenerPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customErrorConfigurations", a.CustomErrorConfigurations) + populate(objectMap, "firewallPolicy", a.FirewallPolicy) + populate(objectMap, "frontendIPConfiguration", a.FrontendIPConfiguration) + populate(objectMap, "frontendPort", a.FrontendPort) + populate(objectMap, "hostName", a.HostName) + populate(objectMap, "hostNames", a.HostNames) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "requireServerNameIndication", a.RequireServerNameIndication) + populate(objectMap, "sslCertificate", a.SSLCertificate) + populate(objectMap, "sslProfile", a.SSLProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayHTTPListenerPropertiesFormat. +func (a *ApplicationGatewayHTTPListenerPropertiesFormat) UnmarshalJSON(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 "customErrorConfigurations": + err = unpopulate(val, "CustomErrorConfigurations", &a.CustomErrorConfigurations) + delete(rawMsg, key) + case "firewallPolicy": + err = unpopulate(val, "FirewallPolicy", &a.FirewallPolicy) + delete(rawMsg, key) + case "frontendIPConfiguration": + err = unpopulate(val, "FrontendIPConfiguration", &a.FrontendIPConfiguration) + delete(rawMsg, key) + case "frontendPort": + err = unpopulate(val, "FrontendPort", &a.FrontendPort) + delete(rawMsg, key) + case "hostName": + err = unpopulate(val, "HostName", &a.HostName) + delete(rawMsg, key) + case "hostNames": + err = unpopulate(val, "HostNames", &a.HostNames) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "requireServerNameIndication": + err = unpopulate(val, "RequireServerNameIndication", &a.RequireServerNameIndication) + delete(rawMsg, key) + case "sslCertificate": + err = unpopulate(val, "SSLCertificate", &a.SSLCertificate) + delete(rawMsg, key) + case "sslProfile": + err = unpopulate(val, "SSLProfile", &a.SSLProfile) + 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 ApplicationGatewayHeaderConfiguration. +func (a ApplicationGatewayHeaderConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "headerName", a.HeaderName) + populate(objectMap, "headerValue", a.HeaderValue) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayHeaderConfiguration. +func (a *ApplicationGatewayHeaderConfiguration) UnmarshalJSON(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 "headerName": + err = unpopulate(val, "HeaderName", &a.HeaderName) + delete(rawMsg, key) + case "headerValue": + err = unpopulate(val, "HeaderValue", &a.HeaderValue) + 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 ApplicationGatewayIPConfiguration. +func (a ApplicationGatewayIPConfiguration) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayIPConfiguration. +func (a *ApplicationGatewayIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayIPConfigurationPropertiesFormat. +func (a ApplicationGatewayIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "subnet", a.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayIPConfigurationPropertiesFormat. +func (a *ApplicationGatewayIPConfigurationPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &a.Subnet) + 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 ApplicationGatewayListResult. +func (a ApplicationGatewayListResult) 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 ApplicationGatewayListResult. +func (a *ApplicationGatewayListResult) UnmarshalJSON(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 ApplicationGatewayListener. +func (a ApplicationGatewayListener) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayListener. +func (a *ApplicationGatewayListener) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayListenerPropertiesFormat. +func (a ApplicationGatewayListenerPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "frontendIPConfiguration", a.FrontendIPConfiguration) + populate(objectMap, "frontendPort", a.FrontendPort) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "sslCertificate", a.SSLCertificate) + populate(objectMap, "sslProfile", a.SSLProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayListenerPropertiesFormat. +func (a *ApplicationGatewayListenerPropertiesFormat) UnmarshalJSON(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 "frontendIPConfiguration": + err = unpopulate(val, "FrontendIPConfiguration", &a.FrontendIPConfiguration) + delete(rawMsg, key) + case "frontendPort": + err = unpopulate(val, "FrontendPort", &a.FrontendPort) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "sslCertificate": + err = unpopulate(val, "SSLCertificate", &a.SSLCertificate) + delete(rawMsg, key) + case "sslProfile": + err = unpopulate(val, "SSLProfile", &a.SSLProfile) + 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 ApplicationGatewayLoadDistributionPolicy. +func (a ApplicationGatewayLoadDistributionPolicy) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayLoadDistributionPolicy. +func (a *ApplicationGatewayLoadDistributionPolicy) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayLoadDistributionPolicyPropertiesFormat. +func (a ApplicationGatewayLoadDistributionPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "loadDistributionAlgorithm", a.LoadDistributionAlgorithm) + populate(objectMap, "loadDistributionTargets", a.LoadDistributionTargets) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayLoadDistributionPolicyPropertiesFormat. +func (a *ApplicationGatewayLoadDistributionPolicyPropertiesFormat) UnmarshalJSON(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 "loadDistributionAlgorithm": + err = unpopulate(val, "LoadDistributionAlgorithm", &a.LoadDistributionAlgorithm) + delete(rawMsg, key) + case "loadDistributionTargets": + err = unpopulate(val, "LoadDistributionTargets", &a.LoadDistributionTargets) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayLoadDistributionTarget. +func (a ApplicationGatewayLoadDistributionTarget) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayLoadDistributionTarget. +func (a *ApplicationGatewayLoadDistributionTarget) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayLoadDistributionTargetPropertiesFormat. +func (a ApplicationGatewayLoadDistributionTargetPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", a.BackendAddressPool) + populate(objectMap, "weightPerServer", a.WeightPerServer) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayLoadDistributionTargetPropertiesFormat. +func (a *ApplicationGatewayLoadDistributionTargetPropertiesFormat) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &a.BackendAddressPool) + delete(rawMsg, key) + case "weightPerServer": + err = unpopulate(val, "WeightPerServer", &a.WeightPerServer) + 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 ApplicationGatewayOnDemandProbe. +func (a ApplicationGatewayOnDemandProbe) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", a.BackendAddressPool) + populate(objectMap, "backendHttpSettings", a.BackendHTTPSettings) + populate(objectMap, "host", a.Host) + populate(objectMap, "match", a.Match) + populate(objectMap, "path", a.Path) + populate(objectMap, "pickHostNameFromBackendHttpSettings", a.PickHostNameFromBackendHTTPSettings) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "timeout", a.Timeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayOnDemandProbe. +func (a *ApplicationGatewayOnDemandProbe) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &a.BackendAddressPool) + delete(rawMsg, key) + case "backendHttpSettings": + err = unpopulate(val, "BackendHTTPSettings", &a.BackendHTTPSettings) + delete(rawMsg, key) + case "host": + err = unpopulate(val, "Host", &a.Host) + delete(rawMsg, key) + case "match": + err = unpopulate(val, "Match", &a.Match) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &a.Path) + delete(rawMsg, key) + case "pickHostNameFromBackendHttpSettings": + err = unpopulate(val, "PickHostNameFromBackendHTTPSettings", &a.PickHostNameFromBackendHTTPSettings) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &a.Timeout) + 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 ApplicationGatewayPathRule. +func (a ApplicationGatewayPathRule) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPathRule. +func (a *ApplicationGatewayPathRule) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayPathRulePropertiesFormat. +func (a ApplicationGatewayPathRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", a.BackendAddressPool) + populate(objectMap, "backendHttpSettings", a.BackendHTTPSettings) + populate(objectMap, "firewallPolicy", a.FirewallPolicy) + populate(objectMap, "loadDistributionPolicy", a.LoadDistributionPolicy) + populate(objectMap, "paths", a.Paths) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "redirectConfiguration", a.RedirectConfiguration) + populate(objectMap, "rewriteRuleSet", a.RewriteRuleSet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPathRulePropertiesFormat. +func (a *ApplicationGatewayPathRulePropertiesFormat) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &a.BackendAddressPool) + delete(rawMsg, key) + case "backendHttpSettings": + err = unpopulate(val, "BackendHTTPSettings", &a.BackendHTTPSettings) + delete(rawMsg, key) + case "firewallPolicy": + err = unpopulate(val, "FirewallPolicy", &a.FirewallPolicy) + delete(rawMsg, key) + case "loadDistributionPolicy": + err = unpopulate(val, "LoadDistributionPolicy", &a.LoadDistributionPolicy) + delete(rawMsg, key) + case "paths": + err = unpopulate(val, "Paths", &a.Paths) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "redirectConfiguration": + err = unpopulate(val, "RedirectConfiguration", &a.RedirectConfiguration) + delete(rawMsg, key) + case "rewriteRuleSet": + err = unpopulate(val, "RewriteRuleSet", &a.RewriteRuleSet) + 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 ApplicationGatewayPrivateEndpointConnection. +func (a ApplicationGatewayPrivateEndpointConnection) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateEndpointConnection. +func (a *ApplicationGatewayPrivateEndpointConnection) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayPrivateEndpointConnectionListResult. +func (a ApplicationGatewayPrivateEndpointConnectionListResult) 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 ApplicationGatewayPrivateEndpointConnectionListResult. +func (a *ApplicationGatewayPrivateEndpointConnectionListResult) UnmarshalJSON(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 ApplicationGatewayPrivateEndpointConnectionProperties. +func (a ApplicationGatewayPrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "linkIdentifier", a.LinkIdentifier) + populate(objectMap, "privateEndpoint", a.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", a.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateEndpointConnectionProperties. +func (a *ApplicationGatewayPrivateEndpointConnectionProperties) UnmarshalJSON(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 "linkIdentifier": + err = unpopulate(val, "LinkIdentifier", &a.LinkIdentifier) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &a.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &a.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayPrivateLinkConfiguration. +func (a ApplicationGatewayPrivateLinkConfiguration) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateLinkConfiguration. +func (a *ApplicationGatewayPrivateLinkConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayPrivateLinkConfigurationProperties. +func (a ApplicationGatewayPrivateLinkConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipConfigurations", a.IPConfigurations) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateLinkConfigurationProperties. +func (a *ApplicationGatewayPrivateLinkConfigurationProperties) UnmarshalJSON(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 "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &a.IPConfigurations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayPrivateLinkIPConfiguration. +func (a ApplicationGatewayPrivateLinkIPConfiguration) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateLinkIPConfiguration. +func (a *ApplicationGatewayPrivateLinkIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayPrivateLinkIPConfigurationProperties. +func (a ApplicationGatewayPrivateLinkIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "primary", a.Primary) + populate(objectMap, "privateIPAddress", a.PrivateIPAddress) + populate(objectMap, "privateIPAllocationMethod", a.PrivateIPAllocationMethod) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "subnet", a.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateLinkIPConfigurationProperties. +func (a *ApplicationGatewayPrivateLinkIPConfigurationProperties) UnmarshalJSON(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 "primary": + err = unpopulate(val, "Primary", &a.Primary) + delete(rawMsg, key) + case "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &a.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &a.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &a.Subnet) + 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 ApplicationGatewayPrivateLinkResource. +func (a ApplicationGatewayPrivateLinkResource) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateLinkResource. +func (a *ApplicationGatewayPrivateLinkResource) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayPrivateLinkResourceListResult. +func (a ApplicationGatewayPrivateLinkResourceListResult) 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 ApplicationGatewayPrivateLinkResourceListResult. +func (a *ApplicationGatewayPrivateLinkResourceListResult) UnmarshalJSON(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 ApplicationGatewayPrivateLinkResourceProperties. +func (a ApplicationGatewayPrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", a.GroupID) + populate(objectMap, "requiredMembers", a.RequiredMembers) + populate(objectMap, "requiredZoneNames", a.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPrivateLinkResourceProperties. +func (a *ApplicationGatewayPrivateLinkResourceProperties) UnmarshalJSON(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 "groupId": + err = unpopulate(val, "GroupID", &a.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &a.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &a.RequiredZoneNames) + 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 ApplicationGatewayProbe. +func (a ApplicationGatewayProbe) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayProbe. +func (a *ApplicationGatewayProbe) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayProbeHealthResponseMatch. +func (a ApplicationGatewayProbeHealthResponseMatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "body", a.Body) + populate(objectMap, "statusCodes", a.StatusCodes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayProbeHealthResponseMatch. +func (a *ApplicationGatewayProbeHealthResponseMatch) UnmarshalJSON(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 "body": + err = unpopulate(val, "Body", &a.Body) + delete(rawMsg, key) + case "statusCodes": + err = unpopulate(val, "StatusCodes", &a.StatusCodes) + 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 ApplicationGatewayProbePropertiesFormat. +func (a ApplicationGatewayProbePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "host", a.Host) + populate(objectMap, "interval", a.Interval) + populate(objectMap, "match", a.Match) + populate(objectMap, "minServers", a.MinServers) + populate(objectMap, "path", a.Path) + populate(objectMap, "pickHostNameFromBackendHttpSettings", a.PickHostNameFromBackendHTTPSettings) + populate(objectMap, "pickHostNameFromBackendSettings", a.PickHostNameFromBackendSettings) + populate(objectMap, "port", a.Port) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "timeout", a.Timeout) + populate(objectMap, "unhealthyThreshold", a.UnhealthyThreshold) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayProbePropertiesFormat. +func (a *ApplicationGatewayProbePropertiesFormat) UnmarshalJSON(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 "host": + err = unpopulate(val, "Host", &a.Host) + delete(rawMsg, key) + case "interval": + err = unpopulate(val, "Interval", &a.Interval) + delete(rawMsg, key) + case "match": + err = unpopulate(val, "Match", &a.Match) + delete(rawMsg, key) + case "minServers": + err = unpopulate(val, "MinServers", &a.MinServers) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &a.Path) + delete(rawMsg, key) + case "pickHostNameFromBackendHttpSettings": + err = unpopulate(val, "PickHostNameFromBackendHTTPSettings", &a.PickHostNameFromBackendHTTPSettings) + delete(rawMsg, key) + case "pickHostNameFromBackendSettings": + err = unpopulate(val, "PickHostNameFromBackendSettings", &a.PickHostNameFromBackendSettings) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &a.Port) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &a.Timeout) + delete(rawMsg, key) + case "unhealthyThreshold": + err = unpopulate(val, "UnhealthyThreshold", &a.UnhealthyThreshold) + 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 ApplicationGatewayPropertiesFormat. +func (a ApplicationGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationCertificates", a.AuthenticationCertificates) + populate(objectMap, "autoscaleConfiguration", a.AutoscaleConfiguration) + populate(objectMap, "backendAddressPools", a.BackendAddressPools) + populate(objectMap, "backendHttpSettingsCollection", a.BackendHTTPSettingsCollection) + populate(objectMap, "backendSettingsCollection", a.BackendSettingsCollection) + populate(objectMap, "customErrorConfigurations", a.CustomErrorConfigurations) + populate(objectMap, "defaultPredefinedSslPolicy", a.DefaultPredefinedSSLPolicy) + populate(objectMap, "enableFips", a.EnableFips) + populate(objectMap, "enableHttp2", a.EnableHTTP2) + populate(objectMap, "firewallPolicy", a.FirewallPolicy) + populate(objectMap, "forceFirewallPolicyAssociation", a.ForceFirewallPolicyAssociation) + populate(objectMap, "frontendIPConfigurations", a.FrontendIPConfigurations) + populate(objectMap, "frontendPorts", a.FrontendPorts) + populate(objectMap, "gatewayIPConfigurations", a.GatewayIPConfigurations) + populate(objectMap, "globalConfiguration", a.GlobalConfiguration) + populate(objectMap, "httpListeners", a.HTTPListeners) + populate(objectMap, "listeners", a.Listeners) + populate(objectMap, "loadDistributionPolicies", a.LoadDistributionPolicies) + populate(objectMap, "operationalState", a.OperationalState) + populate(objectMap, "privateEndpointConnections", a.PrivateEndpointConnections) + populate(objectMap, "privateLinkConfigurations", a.PrivateLinkConfigurations) + populate(objectMap, "probes", a.Probes) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "redirectConfigurations", a.RedirectConfigurations) + populate(objectMap, "requestRoutingRules", a.RequestRoutingRules) + populate(objectMap, "resourceGuid", a.ResourceGUID) + populate(objectMap, "rewriteRuleSets", a.RewriteRuleSets) + populate(objectMap, "routingRules", a.RoutingRules) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "sslCertificates", a.SSLCertificates) + populate(objectMap, "sslPolicy", a.SSLPolicy) + populate(objectMap, "sslProfiles", a.SSLProfiles) + populate(objectMap, "trustedClientCertificates", a.TrustedClientCertificates) + populate(objectMap, "trustedRootCertificates", a.TrustedRootCertificates) + populate(objectMap, "urlPathMaps", a.URLPathMaps) + populate(objectMap, "webApplicationFirewallConfiguration", a.WebApplicationFirewallConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayPropertiesFormat. +func (a *ApplicationGatewayPropertiesFormat) UnmarshalJSON(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 "authenticationCertificates": + err = unpopulate(val, "AuthenticationCertificates", &a.AuthenticationCertificates) + delete(rawMsg, key) + case "autoscaleConfiguration": + err = unpopulate(val, "AutoscaleConfiguration", &a.AutoscaleConfiguration) + delete(rawMsg, key) + case "backendAddressPools": + err = unpopulate(val, "BackendAddressPools", &a.BackendAddressPools) + delete(rawMsg, key) + case "backendHttpSettingsCollection": + err = unpopulate(val, "BackendHTTPSettingsCollection", &a.BackendHTTPSettingsCollection) + delete(rawMsg, key) + case "backendSettingsCollection": + err = unpopulate(val, "BackendSettingsCollection", &a.BackendSettingsCollection) + delete(rawMsg, key) + case "customErrorConfigurations": + err = unpopulate(val, "CustomErrorConfigurations", &a.CustomErrorConfigurations) + delete(rawMsg, key) + case "defaultPredefinedSslPolicy": + err = unpopulate(val, "DefaultPredefinedSSLPolicy", &a.DefaultPredefinedSSLPolicy) + delete(rawMsg, key) + case "enableFips": + err = unpopulate(val, "EnableFips", &a.EnableFips) + delete(rawMsg, key) + case "enableHttp2": + err = unpopulate(val, "EnableHTTP2", &a.EnableHTTP2) + delete(rawMsg, key) + case "firewallPolicy": + err = unpopulate(val, "FirewallPolicy", &a.FirewallPolicy) + delete(rawMsg, key) + case "forceFirewallPolicyAssociation": + err = unpopulate(val, "ForceFirewallPolicyAssociation", &a.ForceFirewallPolicyAssociation) + delete(rawMsg, key) + case "frontendIPConfigurations": + err = unpopulate(val, "FrontendIPConfigurations", &a.FrontendIPConfigurations) + delete(rawMsg, key) + case "frontendPorts": + err = unpopulate(val, "FrontendPorts", &a.FrontendPorts) + delete(rawMsg, key) + case "gatewayIPConfigurations": + err = unpopulate(val, "GatewayIPConfigurations", &a.GatewayIPConfigurations) + delete(rawMsg, key) + case "globalConfiguration": + err = unpopulate(val, "GlobalConfiguration", &a.GlobalConfiguration) + delete(rawMsg, key) + case "httpListeners": + err = unpopulate(val, "HTTPListeners", &a.HTTPListeners) + delete(rawMsg, key) + case "listeners": + err = unpopulate(val, "Listeners", &a.Listeners) + delete(rawMsg, key) + case "loadDistributionPolicies": + err = unpopulate(val, "LoadDistributionPolicies", &a.LoadDistributionPolicies) + delete(rawMsg, key) + case "operationalState": + err = unpopulate(val, "OperationalState", &a.OperationalState) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &a.PrivateEndpointConnections) + delete(rawMsg, key) + case "privateLinkConfigurations": + err = unpopulate(val, "PrivateLinkConfigurations", &a.PrivateLinkConfigurations) + delete(rawMsg, key) + case "probes": + err = unpopulate(val, "Probes", &a.Probes) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "redirectConfigurations": + err = unpopulate(val, "RedirectConfigurations", &a.RedirectConfigurations) + delete(rawMsg, key) + case "requestRoutingRules": + err = unpopulate(val, "RequestRoutingRules", &a.RequestRoutingRules) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &a.ResourceGUID) + delete(rawMsg, key) + case "rewriteRuleSets": + err = unpopulate(val, "RewriteRuleSets", &a.RewriteRuleSets) + delete(rawMsg, key) + case "routingRules": + err = unpopulate(val, "RoutingRules", &a.RoutingRules) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "sslCertificates": + err = unpopulate(val, "SSLCertificates", &a.SSLCertificates) + delete(rawMsg, key) + case "sslPolicy": + err = unpopulate(val, "SSLPolicy", &a.SSLPolicy) + delete(rawMsg, key) + case "sslProfiles": + err = unpopulate(val, "SSLProfiles", &a.SSLProfiles) + delete(rawMsg, key) + case "trustedClientCertificates": + err = unpopulate(val, "TrustedClientCertificates", &a.TrustedClientCertificates) + delete(rawMsg, key) + case "trustedRootCertificates": + err = unpopulate(val, "TrustedRootCertificates", &a.TrustedRootCertificates) + delete(rawMsg, key) + case "urlPathMaps": + err = unpopulate(val, "URLPathMaps", &a.URLPathMaps) + delete(rawMsg, key) + case "webApplicationFirewallConfiguration": + err = unpopulate(val, "WebApplicationFirewallConfiguration", &a.WebApplicationFirewallConfiguration) + 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 ApplicationGatewayRedirectConfiguration. +func (a ApplicationGatewayRedirectConfiguration) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRedirectConfiguration. +func (a *ApplicationGatewayRedirectConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayRedirectConfigurationPropertiesFormat. +func (a ApplicationGatewayRedirectConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "includePath", a.IncludePath) + populate(objectMap, "includeQueryString", a.IncludeQueryString) + populate(objectMap, "pathRules", a.PathRules) + populate(objectMap, "redirectType", a.RedirectType) + populate(objectMap, "requestRoutingRules", a.RequestRoutingRules) + populate(objectMap, "targetListener", a.TargetListener) + populate(objectMap, "targetUrl", a.TargetURL) + populate(objectMap, "urlPathMaps", a.URLPathMaps) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRedirectConfigurationPropertiesFormat. +func (a *ApplicationGatewayRedirectConfigurationPropertiesFormat) UnmarshalJSON(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 "includePath": + err = unpopulate(val, "IncludePath", &a.IncludePath) + delete(rawMsg, key) + case "includeQueryString": + err = unpopulate(val, "IncludeQueryString", &a.IncludeQueryString) + delete(rawMsg, key) + case "pathRules": + err = unpopulate(val, "PathRules", &a.PathRules) + delete(rawMsg, key) + case "redirectType": + err = unpopulate(val, "RedirectType", &a.RedirectType) + delete(rawMsg, key) + case "requestRoutingRules": + err = unpopulate(val, "RequestRoutingRules", &a.RequestRoutingRules) + delete(rawMsg, key) + case "targetListener": + err = unpopulate(val, "TargetListener", &a.TargetListener) + delete(rawMsg, key) + case "targetUrl": + err = unpopulate(val, "TargetURL", &a.TargetURL) + delete(rawMsg, key) + case "urlPathMaps": + err = unpopulate(val, "URLPathMaps", &a.URLPathMaps) + 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 ApplicationGatewayRequestRoutingRule. +func (a ApplicationGatewayRequestRoutingRule) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRequestRoutingRule. +func (a *ApplicationGatewayRequestRoutingRule) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayRequestRoutingRulePropertiesFormat. +func (a ApplicationGatewayRequestRoutingRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", a.BackendAddressPool) + populate(objectMap, "backendHttpSettings", a.BackendHTTPSettings) + populate(objectMap, "httpListener", a.HTTPListener) + populate(objectMap, "loadDistributionPolicy", a.LoadDistributionPolicy) + populate(objectMap, "priority", a.Priority) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "redirectConfiguration", a.RedirectConfiguration) + populate(objectMap, "rewriteRuleSet", a.RewriteRuleSet) + populate(objectMap, "ruleType", a.RuleType) + populate(objectMap, "urlPathMap", a.URLPathMap) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRequestRoutingRulePropertiesFormat. +func (a *ApplicationGatewayRequestRoutingRulePropertiesFormat) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &a.BackendAddressPool) + delete(rawMsg, key) + case "backendHttpSettings": + err = unpopulate(val, "BackendHTTPSettings", &a.BackendHTTPSettings) + delete(rawMsg, key) + case "httpListener": + err = unpopulate(val, "HTTPListener", &a.HTTPListener) + delete(rawMsg, key) + case "loadDistributionPolicy": + err = unpopulate(val, "LoadDistributionPolicy", &a.LoadDistributionPolicy) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &a.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "redirectConfiguration": + err = unpopulate(val, "RedirectConfiguration", &a.RedirectConfiguration) + delete(rawMsg, key) + case "rewriteRuleSet": + err = unpopulate(val, "RewriteRuleSet", &a.RewriteRuleSet) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &a.RuleType) + delete(rawMsg, key) + case "urlPathMap": + err = unpopulate(val, "URLPathMap", &a.URLPathMap) + 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 ApplicationGatewayRewriteRule. +func (a ApplicationGatewayRewriteRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionSet", a.ActionSet) + populate(objectMap, "conditions", a.Conditions) + populate(objectMap, "name", a.Name) + populate(objectMap, "ruleSequence", a.RuleSequence) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRewriteRule. +func (a *ApplicationGatewayRewriteRule) UnmarshalJSON(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 "actionSet": + err = unpopulate(val, "ActionSet", &a.ActionSet) + delete(rawMsg, key) + case "conditions": + err = unpopulate(val, "Conditions", &a.Conditions) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "ruleSequence": + err = unpopulate(val, "RuleSequence", &a.RuleSequence) + 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 ApplicationGatewayRewriteRuleActionSet. +func (a ApplicationGatewayRewriteRuleActionSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "requestHeaderConfigurations", a.RequestHeaderConfigurations) + populate(objectMap, "responseHeaderConfigurations", a.ResponseHeaderConfigurations) + populate(objectMap, "urlConfiguration", a.URLConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRewriteRuleActionSet. +func (a *ApplicationGatewayRewriteRuleActionSet) UnmarshalJSON(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 "requestHeaderConfigurations": + err = unpopulate(val, "RequestHeaderConfigurations", &a.RequestHeaderConfigurations) + delete(rawMsg, key) + case "responseHeaderConfigurations": + err = unpopulate(val, "ResponseHeaderConfigurations", &a.ResponseHeaderConfigurations) + delete(rawMsg, key) + case "urlConfiguration": + err = unpopulate(val, "URLConfiguration", &a.URLConfiguration) + 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 ApplicationGatewayRewriteRuleCondition. +func (a ApplicationGatewayRewriteRuleCondition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ignoreCase", a.IgnoreCase) + populate(objectMap, "negate", a.Negate) + populate(objectMap, "pattern", a.Pattern) + populate(objectMap, "variable", a.Variable) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRewriteRuleCondition. +func (a *ApplicationGatewayRewriteRuleCondition) UnmarshalJSON(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 "ignoreCase": + err = unpopulate(val, "IgnoreCase", &a.IgnoreCase) + delete(rawMsg, key) + case "negate": + err = unpopulate(val, "Negate", &a.Negate) + delete(rawMsg, key) + case "pattern": + err = unpopulate(val, "Pattern", &a.Pattern) + delete(rawMsg, key) + case "variable": + err = unpopulate(val, "Variable", &a.Variable) + 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 ApplicationGatewayRewriteRuleSet. +func (a ApplicationGatewayRewriteRuleSet) 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, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRewriteRuleSet. +func (a *ApplicationGatewayRewriteRuleSet) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayRewriteRuleSetPropertiesFormat. +func (a ApplicationGatewayRewriteRuleSetPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "rewriteRules", a.RewriteRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRewriteRuleSetPropertiesFormat. +func (a *ApplicationGatewayRewriteRuleSetPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "rewriteRules": + err = unpopulate(val, "RewriteRules", &a.RewriteRules) + 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 ApplicationGatewayRoutingRule. +func (a ApplicationGatewayRoutingRule) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRoutingRule. +func (a *ApplicationGatewayRoutingRule) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayRoutingRulePropertiesFormat. +func (a ApplicationGatewayRoutingRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", a.BackendAddressPool) + populate(objectMap, "backendSettings", a.BackendSettings) + populate(objectMap, "listener", a.Listener) + populate(objectMap, "priority", a.Priority) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "ruleType", a.RuleType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayRoutingRulePropertiesFormat. +func (a *ApplicationGatewayRoutingRulePropertiesFormat) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &a.BackendAddressPool) + delete(rawMsg, key) + case "backendSettings": + err = unpopulate(val, "BackendSettings", &a.BackendSettings) + delete(rawMsg, key) + case "listener": + err = unpopulate(val, "Listener", &a.Listener) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &a.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &a.RuleType) + 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 ApplicationGatewaySKU. +func (a ApplicationGatewaySKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", a.Capacity) + populate(objectMap, "name", a.Name) + populate(objectMap, "tier", a.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySKU. +func (a *ApplicationGatewaySKU) UnmarshalJSON(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 "capacity": + err = unpopulate(val, "Capacity", &a.Capacity) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &a.Tier) + 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 ApplicationGatewaySSLCertificate. +func (a ApplicationGatewaySSLCertificate) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySSLCertificate. +func (a *ApplicationGatewaySSLCertificate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewaySSLCertificatePropertiesFormat. +func (a ApplicationGatewaySSLCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "data", a.Data) + populate(objectMap, "keyVaultSecretId", a.KeyVaultSecretID) + populate(objectMap, "password", a.Password) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "publicCertData", a.PublicCertData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySSLCertificatePropertiesFormat. +func (a *ApplicationGatewaySSLCertificatePropertiesFormat) UnmarshalJSON(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 "data": + err = unpopulate(val, "Data", &a.Data) + delete(rawMsg, key) + case "keyVaultSecretId": + err = unpopulate(val, "KeyVaultSecretID", &a.KeyVaultSecretID) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &a.Password) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "publicCertData": + err = unpopulate(val, "PublicCertData", &a.PublicCertData) + 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 ApplicationGatewaySSLPolicy. +func (a ApplicationGatewaySSLPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cipherSuites", a.CipherSuites) + populate(objectMap, "disabledSslProtocols", a.DisabledSSLProtocols) + populate(objectMap, "minProtocolVersion", a.MinProtocolVersion) + populate(objectMap, "policyName", a.PolicyName) + populate(objectMap, "policyType", a.PolicyType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySSLPolicy. +func (a *ApplicationGatewaySSLPolicy) UnmarshalJSON(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 "cipherSuites": + err = unpopulate(val, "CipherSuites", &a.CipherSuites) + delete(rawMsg, key) + case "disabledSslProtocols": + err = unpopulate(val, "DisabledSSLProtocols", &a.DisabledSSLProtocols) + delete(rawMsg, key) + case "minProtocolVersion": + err = unpopulate(val, "MinProtocolVersion", &a.MinProtocolVersion) + delete(rawMsg, key) + case "policyName": + err = unpopulate(val, "PolicyName", &a.PolicyName) + delete(rawMsg, key) + case "policyType": + err = unpopulate(val, "PolicyType", &a.PolicyType) + 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 ApplicationGatewaySSLPredefinedPolicy. +func (a ApplicationGatewaySSLPredefinedPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySSLPredefinedPolicy. +func (a *ApplicationGatewaySSLPredefinedPolicy) UnmarshalJSON(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, "Properties", &a.Properties) + 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 ApplicationGatewaySSLPredefinedPolicyPropertiesFormat. +func (a ApplicationGatewaySSLPredefinedPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cipherSuites", a.CipherSuites) + populate(objectMap, "minProtocolVersion", a.MinProtocolVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySSLPredefinedPolicyPropertiesFormat. +func (a *ApplicationGatewaySSLPredefinedPolicyPropertiesFormat) UnmarshalJSON(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 "cipherSuites": + err = unpopulate(val, "CipherSuites", &a.CipherSuites) + delete(rawMsg, key) + case "minProtocolVersion": + err = unpopulate(val, "MinProtocolVersion", &a.MinProtocolVersion) + 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 ApplicationGatewaySSLProfile. +func (a ApplicationGatewaySSLProfile) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySSLProfile. +func (a *ApplicationGatewaySSLProfile) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewaySSLProfilePropertiesFormat. +func (a ApplicationGatewaySSLProfilePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientAuthConfiguration", a.ClientAuthConfiguration) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "sslPolicy", a.SSLPolicy) + populate(objectMap, "trustedClientCertificates", a.TrustedClientCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewaySSLProfilePropertiesFormat. +func (a *ApplicationGatewaySSLProfilePropertiesFormat) UnmarshalJSON(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 "clientAuthConfiguration": + err = unpopulate(val, "ClientAuthConfiguration", &a.ClientAuthConfiguration) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "sslPolicy": + err = unpopulate(val, "SSLPolicy", &a.SSLPolicy) + delete(rawMsg, key) + case "trustedClientCertificates": + err = unpopulate(val, "TrustedClientCertificates", &a.TrustedClientCertificates) + 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 ApplicationGatewayTrustedClientCertificate. +func (a ApplicationGatewayTrustedClientCertificate) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayTrustedClientCertificate. +func (a *ApplicationGatewayTrustedClientCertificate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayTrustedClientCertificatePropertiesFormat. +func (a ApplicationGatewayTrustedClientCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientCertIssuerDN", a.ClientCertIssuerDN) + populate(objectMap, "data", a.Data) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "validatedCertData", a.ValidatedCertData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayTrustedClientCertificatePropertiesFormat. +func (a *ApplicationGatewayTrustedClientCertificatePropertiesFormat) UnmarshalJSON(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 "clientCertIssuerDN": + err = unpopulate(val, "ClientCertIssuerDN", &a.ClientCertIssuerDN) + delete(rawMsg, key) + case "data": + err = unpopulate(val, "Data", &a.Data) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "validatedCertData": + err = unpopulate(val, "ValidatedCertData", &a.ValidatedCertData) + 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 ApplicationGatewayTrustedRootCertificate. +func (a ApplicationGatewayTrustedRootCertificate) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayTrustedRootCertificate. +func (a *ApplicationGatewayTrustedRootCertificate) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayTrustedRootCertificatePropertiesFormat. +func (a ApplicationGatewayTrustedRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "data", a.Data) + populate(objectMap, "keyVaultSecretId", a.KeyVaultSecretID) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayTrustedRootCertificatePropertiesFormat. +func (a *ApplicationGatewayTrustedRootCertificatePropertiesFormat) UnmarshalJSON(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 "data": + err = unpopulate(val, "Data", &a.Data) + delete(rawMsg, key) + case "keyVaultSecretId": + err = unpopulate(val, "KeyVaultSecretID", &a.KeyVaultSecretID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayURLConfiguration. +func (a ApplicationGatewayURLConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "modifiedPath", a.ModifiedPath) + populate(objectMap, "modifiedQueryString", a.ModifiedQueryString) + populate(objectMap, "reroute", a.Reroute) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayURLConfiguration. +func (a *ApplicationGatewayURLConfiguration) UnmarshalJSON(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 "modifiedPath": + err = unpopulate(val, "ModifiedPath", &a.ModifiedPath) + delete(rawMsg, key) + case "modifiedQueryString": + err = unpopulate(val, "ModifiedQueryString", &a.ModifiedQueryString) + delete(rawMsg, key) + case "reroute": + err = unpopulate(val, "Reroute", &a.Reroute) + 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 ApplicationGatewayURLPathMap. +func (a ApplicationGatewayURLPathMap) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayURLPathMap. +func (a *ApplicationGatewayURLPathMap) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 ApplicationGatewayURLPathMapPropertiesFormat. +func (a ApplicationGatewayURLPathMapPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultBackendAddressPool", a.DefaultBackendAddressPool) + populate(objectMap, "defaultBackendHttpSettings", a.DefaultBackendHTTPSettings) + populate(objectMap, "defaultLoadDistributionPolicy", a.DefaultLoadDistributionPolicy) + populate(objectMap, "defaultRedirectConfiguration", a.DefaultRedirectConfiguration) + populate(objectMap, "defaultRewriteRuleSet", a.DefaultRewriteRuleSet) + populate(objectMap, "pathRules", a.PathRules) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayURLPathMapPropertiesFormat. +func (a *ApplicationGatewayURLPathMapPropertiesFormat) UnmarshalJSON(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 "defaultBackendAddressPool": + err = unpopulate(val, "DefaultBackendAddressPool", &a.DefaultBackendAddressPool) + delete(rawMsg, key) + case "defaultBackendHttpSettings": + err = unpopulate(val, "DefaultBackendHTTPSettings", &a.DefaultBackendHTTPSettings) + delete(rawMsg, key) + case "defaultLoadDistributionPolicy": + err = unpopulate(val, "DefaultLoadDistributionPolicy", &a.DefaultLoadDistributionPolicy) + delete(rawMsg, key) + case "defaultRedirectConfiguration": + err = unpopulate(val, "DefaultRedirectConfiguration", &a.DefaultRedirectConfiguration) + delete(rawMsg, key) + case "defaultRewriteRuleSet": + err = unpopulate(val, "DefaultRewriteRuleSet", &a.DefaultRewriteRuleSet) + delete(rawMsg, key) + case "pathRules": + err = unpopulate(val, "PathRules", &a.PathRules) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 ApplicationGatewayWafDynamicManifestPropertiesResult. +func (a ApplicationGatewayWafDynamicManifestPropertiesResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableRuleSets", a.AvailableRuleSets) + populate(objectMap, "defaultRuleSet", a.DefaultRuleSet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayWafDynamicManifestPropertiesResult. +func (a *ApplicationGatewayWafDynamicManifestPropertiesResult) UnmarshalJSON(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 "availableRuleSets": + err = unpopulate(val, "AvailableRuleSets", &a.AvailableRuleSets) + delete(rawMsg, key) + case "defaultRuleSet": + err = unpopulate(val, "DefaultRuleSet", &a.DefaultRuleSet) + 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 ApplicationGatewayWafDynamicManifestResult. +func (a ApplicationGatewayWafDynamicManifestResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayWafDynamicManifestResult. +func (a *ApplicationGatewayWafDynamicManifestResult) UnmarshalJSON(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, "Properties", &a.Properties) + 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 ApplicationGatewayWafDynamicManifestResultList. +func (a ApplicationGatewayWafDynamicManifestResultList) 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 ApplicationGatewayWafDynamicManifestResultList. +func (a *ApplicationGatewayWafDynamicManifestResultList) UnmarshalJSON(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 ApplicationGatewayWebApplicationFirewallConfiguration. +func (a ApplicationGatewayWebApplicationFirewallConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disabledRuleGroups", a.DisabledRuleGroups) + populate(objectMap, "enabled", a.Enabled) + populate(objectMap, "exclusions", a.Exclusions) + populate(objectMap, "fileUploadLimitInMb", a.FileUploadLimitInMb) + populate(objectMap, "firewallMode", a.FirewallMode) + populate(objectMap, "maxRequestBodySize", a.MaxRequestBodySize) + populate(objectMap, "maxRequestBodySizeInKb", a.MaxRequestBodySizeInKb) + populate(objectMap, "requestBodyCheck", a.RequestBodyCheck) + populate(objectMap, "ruleSetType", a.RuleSetType) + populate(objectMap, "ruleSetVersion", a.RuleSetVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGatewayWebApplicationFirewallConfiguration. +func (a *ApplicationGatewayWebApplicationFirewallConfiguration) UnmarshalJSON(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 "disabledRuleGroups": + err = unpopulate(val, "DisabledRuleGroups", &a.DisabledRuleGroups) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &a.Enabled) + delete(rawMsg, key) + case "exclusions": + err = unpopulate(val, "Exclusions", &a.Exclusions) + delete(rawMsg, key) + case "fileUploadLimitInMb": + err = unpopulate(val, "FileUploadLimitInMb", &a.FileUploadLimitInMb) + delete(rawMsg, key) + case "firewallMode": + err = unpopulate(val, "FirewallMode", &a.FirewallMode) + delete(rawMsg, key) + case "maxRequestBodySize": + err = unpopulate(val, "MaxRequestBodySize", &a.MaxRequestBodySize) + delete(rawMsg, key) + case "maxRequestBodySizeInKb": + err = unpopulate(val, "MaxRequestBodySizeInKb", &a.MaxRequestBodySizeInKb) + delete(rawMsg, key) + case "requestBodyCheck": + err = unpopulate(val, "RequestBodyCheck", &a.RequestBodyCheck) + delete(rawMsg, key) + case "ruleSetType": + err = unpopulate(val, "RuleSetType", &a.RuleSetType) + delete(rawMsg, key) + case "ruleSetVersion": + err = unpopulate(val, "RuleSetVersion", &a.RuleSetVersion) + 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 ApplicationRule. +func (a ApplicationRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "destinationAddresses", a.DestinationAddresses) + populate(objectMap, "fqdnTags", a.FqdnTags) + populate(objectMap, "httpHeadersToInsert", a.HTTPHeadersToInsert) + populate(objectMap, "name", a.Name) + populate(objectMap, "protocols", a.Protocols) + objectMap["ruleType"] = FirewallPolicyRuleTypeApplicationRule + populate(objectMap, "sourceAddresses", a.SourceAddresses) + populate(objectMap, "sourceIpGroups", a.SourceIPGroups) + populate(objectMap, "targetFqdns", a.TargetFqdns) + populate(objectMap, "targetUrls", a.TargetUrls) + populate(objectMap, "terminateTLS", a.TerminateTLS) + populate(objectMap, "webCategories", a.WebCategories) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationRule. +func (a *ApplicationRule) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "destinationAddresses": + err = unpopulate(val, "DestinationAddresses", &a.DestinationAddresses) + delete(rawMsg, key) + case "fqdnTags": + err = unpopulate(val, "FqdnTags", &a.FqdnTags) + delete(rawMsg, key) + case "httpHeadersToInsert": + err = unpopulate(val, "HTTPHeadersToInsert", &a.HTTPHeadersToInsert) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "protocols": + err = unpopulate(val, "Protocols", &a.Protocols) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &a.RuleType) + delete(rawMsg, key) + case "sourceAddresses": + err = unpopulate(val, "SourceAddresses", &a.SourceAddresses) + delete(rawMsg, key) + case "sourceIpGroups": + err = unpopulate(val, "SourceIPGroups", &a.SourceIPGroups) + delete(rawMsg, key) + case "targetFqdns": + err = unpopulate(val, "TargetFqdns", &a.TargetFqdns) + delete(rawMsg, key) + case "targetUrls": + err = unpopulate(val, "TargetUrls", &a.TargetUrls) + delete(rawMsg, key) + case "terminateTLS": + err = unpopulate(val, "TerminateTLS", &a.TerminateTLS) + delete(rawMsg, key) + case "webCategories": + err = unpopulate(val, "WebCategories", &a.WebCategories) + 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 ApplicationSecurityGroup. +func (a ApplicationSecurityGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationSecurityGroup. +func (a *ApplicationSecurityGroup) UnmarshalJSON(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 "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 "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 ApplicationSecurityGroupListResult. +func (a ApplicationSecurityGroupListResult) 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 ApplicationSecurityGroupListResult. +func (a *ApplicationSecurityGroupListResult) UnmarshalJSON(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 ApplicationSecurityGroupPropertiesFormat. +func (a ApplicationSecurityGroupPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "resourceGuid", a.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationSecurityGroupPropertiesFormat. +func (a *ApplicationSecurityGroupPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &a.ResourceGUID) + 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 AuthorizationListResult. +func (a AuthorizationListResult) 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 AuthorizationListResult. +func (a *AuthorizationListResult) UnmarshalJSON(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 AuthorizationPropertiesFormat. +func (a AuthorizationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authorizationKey", a.AuthorizationKey) + populate(objectMap, "authorizationUseStatus", a.AuthorizationUseStatus) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthorizationPropertiesFormat. +func (a *AuthorizationPropertiesFormat) UnmarshalJSON(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 "authorizationKey": + err = unpopulate(val, "AuthorizationKey", &a.AuthorizationKey) + delete(rawMsg, key) + case "authorizationUseStatus": + err = unpopulate(val, "AuthorizationUseStatus", &a.AuthorizationUseStatus) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 AutoApprovedPrivateLinkService. +func (a AutoApprovedPrivateLinkService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateLinkService", a.PrivateLinkService) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutoApprovedPrivateLinkService. +func (a *AutoApprovedPrivateLinkService) UnmarshalJSON(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 "privateLinkService": + err = unpopulate(val, "PrivateLinkService", &a.PrivateLinkService) + 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 AutoApprovedPrivateLinkServicesResult. +func (a AutoApprovedPrivateLinkServicesResult) 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 AutoApprovedPrivateLinkServicesResult. +func (a *AutoApprovedPrivateLinkServicesResult) UnmarshalJSON(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 Availability. +func (a Availability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobDuration", a.BlobDuration) + populate(objectMap, "retention", a.Retention) + populate(objectMap, "timeGrain", a.TimeGrain) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Availability. +func (a *Availability) UnmarshalJSON(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 "blobDuration": + err = unpopulate(val, "BlobDuration", &a.BlobDuration) + delete(rawMsg, key) + case "retention": + err = unpopulate(val, "Retention", &a.Retention) + delete(rawMsg, key) + case "timeGrain": + err = unpopulate(val, "TimeGrain", &a.TimeGrain) + 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 AvailableDelegation. +func (a AvailableDelegation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", a.Actions) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "serviceName", a.ServiceName) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableDelegation. +func (a *AvailableDelegation) UnmarshalJSON(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 "actions": + err = unpopulate(val, "Actions", &a.Actions) + 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 "serviceName": + err = unpopulate(val, "ServiceName", &a.ServiceName) + 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 AvailableDelegationsResult. +func (a AvailableDelegationsResult) 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 AvailableDelegationsResult. +func (a *AvailableDelegationsResult) UnmarshalJSON(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 AvailablePrivateEndpointType. +func (a AvailablePrivateEndpointType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "resourceName", a.ResourceName) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailablePrivateEndpointType. +func (a *AvailablePrivateEndpointType) UnmarshalJSON(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 "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + 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 "resourceName": + err = unpopulate(val, "ResourceName", &a.ResourceName) + 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 AvailablePrivateEndpointTypesResult. +func (a AvailablePrivateEndpointTypesResult) 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 AvailablePrivateEndpointTypesResult. +func (a *AvailablePrivateEndpointTypesResult) UnmarshalJSON(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 AvailableProvidersList. +func (a AvailableProvidersList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "countries", a.Countries) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableProvidersList. +func (a *AvailableProvidersList) UnmarshalJSON(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 "countries": + err = unpopulate(val, "Countries", &a.Countries) + 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 AvailableProvidersListCity. +func (a AvailableProvidersListCity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cityName", a.CityName) + populate(objectMap, "providers", a.Providers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableProvidersListCity. +func (a *AvailableProvidersListCity) UnmarshalJSON(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 "cityName": + err = unpopulate(val, "CityName", &a.CityName) + delete(rawMsg, key) + case "providers": + err = unpopulate(val, "Providers", &a.Providers) + 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 AvailableProvidersListCountry. +func (a AvailableProvidersListCountry) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "countryName", a.CountryName) + populate(objectMap, "providers", a.Providers) + populate(objectMap, "states", a.States) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableProvidersListCountry. +func (a *AvailableProvidersListCountry) UnmarshalJSON(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 "countryName": + err = unpopulate(val, "CountryName", &a.CountryName) + delete(rawMsg, key) + case "providers": + err = unpopulate(val, "Providers", &a.Providers) + delete(rawMsg, key) + case "states": + err = unpopulate(val, "States", &a.States) + 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 AvailableProvidersListParameters. +func (a AvailableProvidersListParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLocations", a.AzureLocations) + populate(objectMap, "city", a.City) + populate(objectMap, "country", a.Country) + populate(objectMap, "state", a.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableProvidersListParameters. +func (a *AvailableProvidersListParameters) UnmarshalJSON(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 "azureLocations": + err = unpopulate(val, "AzureLocations", &a.AzureLocations) + delete(rawMsg, key) + case "city": + err = unpopulate(val, "City", &a.City) + delete(rawMsg, key) + case "country": + err = unpopulate(val, "Country", &a.Country) + 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 AvailableProvidersListState. +func (a AvailableProvidersListState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cities", a.Cities) + populate(objectMap, "providers", a.Providers) + populate(objectMap, "stateName", a.StateName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableProvidersListState. +func (a *AvailableProvidersListState) UnmarshalJSON(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 "cities": + err = unpopulate(val, "Cities", &a.Cities) + delete(rawMsg, key) + case "providers": + err = unpopulate(val, "Providers", &a.Providers) + delete(rawMsg, key) + case "stateName": + err = unpopulate(val, "StateName", &a.StateName) + 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 AvailableServiceAlias. +func (a AvailableServiceAlias) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "resourceName", a.ResourceName) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableServiceAlias. +func (a *AvailableServiceAlias) UnmarshalJSON(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 "resourceName": + err = unpopulate(val, "ResourceName", &a.ResourceName) + 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 AvailableServiceAliasesResult. +func (a AvailableServiceAliasesResult) 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 AvailableServiceAliasesResult. +func (a *AvailableServiceAliasesResult) UnmarshalJSON(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 AzureAsyncOperationResult. +func (a AzureAsyncOperationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", a.Error) + populate(objectMap, "status", a.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureAsyncOperationResult. +func (a *AzureAsyncOperationResult) UnmarshalJSON(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 "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &a.Status) + 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 AzureFirewall. +func (a AzureFirewall) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + populate(objectMap, "zones", a.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewall. +func (a *AzureFirewall) UnmarshalJSON(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 "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 "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &a.Zones) + 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 AzureFirewallApplicationRule. +func (a AzureFirewallApplicationRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "fqdnTags", a.FqdnTags) + populate(objectMap, "name", a.Name) + populate(objectMap, "protocols", a.Protocols) + populate(objectMap, "sourceAddresses", a.SourceAddresses) + populate(objectMap, "sourceIpGroups", a.SourceIPGroups) + populate(objectMap, "targetFqdns", a.TargetFqdns) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallApplicationRule. +func (a *AzureFirewallApplicationRule) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "fqdnTags": + err = unpopulate(val, "FqdnTags", &a.FqdnTags) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "protocols": + err = unpopulate(val, "Protocols", &a.Protocols) + delete(rawMsg, key) + case "sourceAddresses": + err = unpopulate(val, "SourceAddresses", &a.SourceAddresses) + delete(rawMsg, key) + case "sourceIpGroups": + err = unpopulate(val, "SourceIPGroups", &a.SourceIPGroups) + delete(rawMsg, key) + case "targetFqdns": + err = unpopulate(val, "TargetFqdns", &a.TargetFqdns) + 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 AzureFirewallApplicationRuleCollection. +func (a AzureFirewallApplicationRuleCollection) 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, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallApplicationRuleCollection. +func (a *AzureFirewallApplicationRuleCollection) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 AzureFirewallApplicationRuleCollectionPropertiesFormat. +func (a AzureFirewallApplicationRuleCollectionPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", a.Action) + populate(objectMap, "priority", a.Priority) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "rules", a.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallApplicationRuleCollectionPropertiesFormat. +func (a *AzureFirewallApplicationRuleCollectionPropertiesFormat) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &a.Action) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &a.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &a.Rules) + 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 AzureFirewallApplicationRuleProtocol. +func (a AzureFirewallApplicationRuleProtocol) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "port", a.Port) + populate(objectMap, "protocolType", a.ProtocolType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallApplicationRuleProtocol. +func (a *AzureFirewallApplicationRuleProtocol) UnmarshalJSON(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 "port": + err = unpopulate(val, "Port", &a.Port) + delete(rawMsg, key) + case "protocolType": + err = unpopulate(val, "ProtocolType", &a.ProtocolType) + 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 AzureFirewallFqdnTag. +func (a AzureFirewallFqdnTag) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallFqdnTag. +func (a *AzureFirewallFqdnTag) UnmarshalJSON(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 "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 "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 AzureFirewallFqdnTagListResult. +func (a AzureFirewallFqdnTagListResult) 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 AzureFirewallFqdnTagListResult. +func (a *AzureFirewallFqdnTagListResult) UnmarshalJSON(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 AzureFirewallFqdnTagPropertiesFormat. +func (a AzureFirewallFqdnTagPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fqdnTagName", a.FqdnTagName) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallFqdnTagPropertiesFormat. +func (a *AzureFirewallFqdnTagPropertiesFormat) UnmarshalJSON(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 "fqdnTagName": + err = unpopulate(val, "FqdnTagName", &a.FqdnTagName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + 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 AzureFirewallIPConfiguration. +func (a AzureFirewallIPConfiguration) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallIPConfiguration. +func (a *AzureFirewallIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 AzureFirewallIPConfigurationPropertiesFormat. +func (a AzureFirewallIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAddress", a.PrivateIPAddress) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "publicIPAddress", a.PublicIPAddress) + populate(objectMap, "subnet", a.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallIPConfigurationPropertiesFormat. +func (a *AzureFirewallIPConfigurationPropertiesFormat) UnmarshalJSON(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 "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &a.PrivateIPAddress) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &a.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &a.Subnet) + 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 AzureFirewallIPGroups. +func (a AzureFirewallIPGroups) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "changeNumber", a.ChangeNumber) + populate(objectMap, "id", a.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallIPGroups. +func (a *AzureFirewallIPGroups) UnmarshalJSON(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 "changeNumber": + err = unpopulate(val, "ChangeNumber", &a.ChangeNumber) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + 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 AzureFirewallListResult. +func (a AzureFirewallListResult) 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 AzureFirewallListResult. +func (a *AzureFirewallListResult) UnmarshalJSON(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 AzureFirewallNatRCAction. +func (a AzureFirewallNatRCAction) 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 AzureFirewallNatRCAction. +func (a *AzureFirewallNatRCAction) UnmarshalJSON(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 AzureFirewallNatRule. +func (a AzureFirewallNatRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "destinationAddresses", a.DestinationAddresses) + populate(objectMap, "destinationPorts", a.DestinationPorts) + populate(objectMap, "name", a.Name) + populate(objectMap, "protocols", a.Protocols) + populate(objectMap, "sourceAddresses", a.SourceAddresses) + populate(objectMap, "sourceIpGroups", a.SourceIPGroups) + populate(objectMap, "translatedAddress", a.TranslatedAddress) + populate(objectMap, "translatedFqdn", a.TranslatedFqdn) + populate(objectMap, "translatedPort", a.TranslatedPort) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallNatRule. +func (a *AzureFirewallNatRule) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "destinationAddresses": + err = unpopulate(val, "DestinationAddresses", &a.DestinationAddresses) + delete(rawMsg, key) + case "destinationPorts": + err = unpopulate(val, "DestinationPorts", &a.DestinationPorts) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "protocols": + err = unpopulate(val, "Protocols", &a.Protocols) + delete(rawMsg, key) + case "sourceAddresses": + err = unpopulate(val, "SourceAddresses", &a.SourceAddresses) + delete(rawMsg, key) + case "sourceIpGroups": + err = unpopulate(val, "SourceIPGroups", &a.SourceIPGroups) + delete(rawMsg, key) + case "translatedAddress": + err = unpopulate(val, "TranslatedAddress", &a.TranslatedAddress) + delete(rawMsg, key) + case "translatedFqdn": + err = unpopulate(val, "TranslatedFqdn", &a.TranslatedFqdn) + delete(rawMsg, key) + case "translatedPort": + err = unpopulate(val, "TranslatedPort", &a.TranslatedPort) + 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 AzureFirewallNatRuleCollection. +func (a AzureFirewallNatRuleCollection) 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, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallNatRuleCollection. +func (a *AzureFirewallNatRuleCollection) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 AzureFirewallNatRuleCollectionProperties. +func (a AzureFirewallNatRuleCollectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", a.Action) + populate(objectMap, "priority", a.Priority) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "rules", a.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallNatRuleCollectionProperties. +func (a *AzureFirewallNatRuleCollectionProperties) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &a.Action) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &a.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &a.Rules) + 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 AzureFirewallNetworkRule. +func (a AzureFirewallNetworkRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "destinationAddresses", a.DestinationAddresses) + populate(objectMap, "destinationFqdns", a.DestinationFqdns) + populate(objectMap, "destinationIpGroups", a.DestinationIPGroups) + populate(objectMap, "destinationPorts", a.DestinationPorts) + populate(objectMap, "name", a.Name) + populate(objectMap, "protocols", a.Protocols) + populate(objectMap, "sourceAddresses", a.SourceAddresses) + populate(objectMap, "sourceIpGroups", a.SourceIPGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallNetworkRule. +func (a *AzureFirewallNetworkRule) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "destinationAddresses": + err = unpopulate(val, "DestinationAddresses", &a.DestinationAddresses) + delete(rawMsg, key) + case "destinationFqdns": + err = unpopulate(val, "DestinationFqdns", &a.DestinationFqdns) + delete(rawMsg, key) + case "destinationIpGroups": + err = unpopulate(val, "DestinationIPGroups", &a.DestinationIPGroups) + delete(rawMsg, key) + case "destinationPorts": + err = unpopulate(val, "DestinationPorts", &a.DestinationPorts) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "protocols": + err = unpopulate(val, "Protocols", &a.Protocols) + delete(rawMsg, key) + case "sourceAddresses": + err = unpopulate(val, "SourceAddresses", &a.SourceAddresses) + delete(rawMsg, key) + case "sourceIpGroups": + err = unpopulate(val, "SourceIPGroups", &a.SourceIPGroups) + 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 AzureFirewallNetworkRuleCollection. +func (a AzureFirewallNetworkRuleCollection) 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, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallNetworkRuleCollection. +func (a *AzureFirewallNetworkRuleCollection) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 AzureFirewallNetworkRuleCollectionPropertiesFormat. +func (a AzureFirewallNetworkRuleCollectionPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", a.Action) + populate(objectMap, "priority", a.Priority) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "rules", a.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallNetworkRuleCollectionPropertiesFormat. +func (a *AzureFirewallNetworkRuleCollectionPropertiesFormat) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &a.Action) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &a.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &a.Rules) + 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 AzureFirewallPacketCaptureFlags. +func (a AzureFirewallPacketCaptureFlags) 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 AzureFirewallPacketCaptureFlags. +func (a *AzureFirewallPacketCaptureFlags) UnmarshalJSON(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 AzureFirewallPacketCaptureRule. +func (a AzureFirewallPacketCaptureRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationPorts", a.DestinationPorts) + populate(objectMap, "destinations", a.Destinations) + populate(objectMap, "sources", a.Sources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallPacketCaptureRule. +func (a *AzureFirewallPacketCaptureRule) UnmarshalJSON(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 "destinationPorts": + err = unpopulate(val, "DestinationPorts", &a.DestinationPorts) + delete(rawMsg, key) + case "destinations": + err = unpopulate(val, "Destinations", &a.Destinations) + delete(rawMsg, key) + case "sources": + err = unpopulate(val, "Sources", &a.Sources) + 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 AzureFirewallPropertiesFormat. +func (a AzureFirewallPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalProperties", a.AdditionalProperties) + populate(objectMap, "applicationRuleCollections", a.ApplicationRuleCollections) + populate(objectMap, "firewallPolicy", a.FirewallPolicy) + populate(objectMap, "hubIPAddresses", a.HubIPAddresses) + populate(objectMap, "ipConfigurations", a.IPConfigurations) + populate(objectMap, "ipGroups", a.IPGroups) + populate(objectMap, "managementIpConfiguration", a.ManagementIPConfiguration) + populate(objectMap, "natRuleCollections", a.NatRuleCollections) + populate(objectMap, "networkRuleCollections", a.NetworkRuleCollections) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "threatIntelMode", a.ThreatIntelMode) + populate(objectMap, "virtualHub", a.VirtualHub) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallPropertiesFormat. +func (a *AzureFirewallPropertiesFormat) UnmarshalJSON(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 "additionalProperties": + err = unpopulate(val, "AdditionalProperties", &a.AdditionalProperties) + delete(rawMsg, key) + case "applicationRuleCollections": + err = unpopulate(val, "ApplicationRuleCollections", &a.ApplicationRuleCollections) + delete(rawMsg, key) + case "firewallPolicy": + err = unpopulate(val, "FirewallPolicy", &a.FirewallPolicy) + delete(rawMsg, key) + case "hubIPAddresses": + err = unpopulate(val, "HubIPAddresses", &a.HubIPAddresses) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &a.IPConfigurations) + delete(rawMsg, key) + case "ipGroups": + err = unpopulate(val, "IPGroups", &a.IPGroups) + delete(rawMsg, key) + case "managementIpConfiguration": + err = unpopulate(val, "ManagementIPConfiguration", &a.ManagementIPConfiguration) + delete(rawMsg, key) + case "natRuleCollections": + err = unpopulate(val, "NatRuleCollections", &a.NatRuleCollections) + delete(rawMsg, key) + case "networkRuleCollections": + err = unpopulate(val, "NetworkRuleCollections", &a.NetworkRuleCollections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "threatIntelMode": + err = unpopulate(val, "ThreatIntelMode", &a.ThreatIntelMode) + delete(rawMsg, key) + case "virtualHub": + err = unpopulate(val, "VirtualHub", &a.VirtualHub) + 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 AzureFirewallPublicIPAddress. +func (a AzureFirewallPublicIPAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", a.Address) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallPublicIPAddress. +func (a *AzureFirewallPublicIPAddress) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &a.Address) + 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 AzureFirewallRCAction. +func (a AzureFirewallRCAction) 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 AzureFirewallRCAction. +func (a *AzureFirewallRCAction) UnmarshalJSON(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 AzureFirewallSKU. +func (a AzureFirewallSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + populate(objectMap, "tier", a.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFirewallSKU. +func (a *AzureFirewallSKU) UnmarshalJSON(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 "tier": + err = unpopulate(val, "Tier", &a.Tier) + 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 AzureReachabilityReport. +func (a AzureReachabilityReport) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregationLevel", a.AggregationLevel) + populate(objectMap, "providerLocation", a.ProviderLocation) + populate(objectMap, "reachabilityReport", a.ReachabilityReport) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureReachabilityReport. +func (a *AzureReachabilityReport) UnmarshalJSON(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 "aggregationLevel": + err = unpopulate(val, "AggregationLevel", &a.AggregationLevel) + delete(rawMsg, key) + case "providerLocation": + err = unpopulate(val, "ProviderLocation", &a.ProviderLocation) + delete(rawMsg, key) + case "reachabilityReport": + err = unpopulate(val, "ReachabilityReport", &a.ReachabilityReport) + 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 AzureReachabilityReportItem. +func (a AzureReachabilityReportItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLocation", a.AzureLocation) + populate(objectMap, "latencies", a.Latencies) + populate(objectMap, "provider", a.Provider) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureReachabilityReportItem. +func (a *AzureReachabilityReportItem) UnmarshalJSON(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 "azureLocation": + err = unpopulate(val, "AzureLocation", &a.AzureLocation) + delete(rawMsg, key) + case "latencies": + err = unpopulate(val, "Latencies", &a.Latencies) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &a.Provider) + 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 AzureReachabilityReportLatencyInfo. +func (a AzureReachabilityReportLatencyInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "score", a.Score) + populateDateTimeRFC3339(objectMap, "timeStamp", a.TimeStamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureReachabilityReportLatencyInfo. +func (a *AzureReachabilityReportLatencyInfo) UnmarshalJSON(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 "score": + err = unpopulate(val, "Score", &a.Score) + delete(rawMsg, key) + case "timeStamp": + err = unpopulateDateTimeRFC3339(val, "TimeStamp", &a.TimeStamp) + 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 AzureReachabilityReportLocation. +func (a AzureReachabilityReportLocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "city", a.City) + populate(objectMap, "country", a.Country) + populate(objectMap, "state", a.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureReachabilityReportLocation. +func (a *AzureReachabilityReportLocation) UnmarshalJSON(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 "city": + err = unpopulate(val, "City", &a.City) + delete(rawMsg, key) + case "country": + err = unpopulate(val, "Country", &a.Country) + 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 AzureReachabilityReportParameters. +func (a AzureReachabilityReportParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLocations", a.AzureLocations) + populateDateTimeRFC3339(objectMap, "endTime", a.EndTime) + populate(objectMap, "providerLocation", a.ProviderLocation) + populate(objectMap, "providers", a.Providers) + populateDateTimeRFC3339(objectMap, "startTime", a.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureReachabilityReportParameters. +func (a *AzureReachabilityReportParameters) UnmarshalJSON(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 "azureLocations": + err = unpopulate(val, "AzureLocations", &a.AzureLocations) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &a.EndTime) + delete(rawMsg, key) + case "providerLocation": + err = unpopulate(val, "ProviderLocation", &a.ProviderLocation) + delete(rawMsg, key) + case "providers": + err = unpopulate(val, "Providers", &a.Providers) + 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 AzureWebCategory. +func (a AzureWebCategory) 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, "properties", a.Properties) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureWebCategory. +func (a *AzureWebCategory) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &a.Properties) + 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 AzureWebCategoryListResult. +func (a AzureWebCategoryListResult) 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 AzureWebCategoryListResult. +func (a *AzureWebCategoryListResult) UnmarshalJSON(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 AzureWebCategoryPropertiesFormat. +func (a AzureWebCategoryPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "group", a.Group) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureWebCategoryPropertiesFormat. +func (a *AzureWebCategoryPropertiesFormat) UnmarshalJSON(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 "group": + err = unpopulate(val, "Group", &a.Group) + 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 BGPCommunity. +func (b BGPCommunity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityName", b.CommunityName) + populate(objectMap, "communityPrefixes", b.CommunityPrefixes) + populate(objectMap, "communityValue", b.CommunityValue) + populate(objectMap, "isAuthorizedToUse", b.IsAuthorizedToUse) + populate(objectMap, "serviceGroup", b.ServiceGroup) + populate(objectMap, "serviceSupportedRegion", b.ServiceSupportedRegion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BGPCommunity. +func (b *BGPCommunity) UnmarshalJSON(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 "communityName": + err = unpopulate(val, "CommunityName", &b.CommunityName) + delete(rawMsg, key) + case "communityPrefixes": + err = unpopulate(val, "CommunityPrefixes", &b.CommunityPrefixes) + delete(rawMsg, key) + case "communityValue": + err = unpopulate(val, "CommunityValue", &b.CommunityValue) + delete(rawMsg, key) + case "isAuthorizedToUse": + err = unpopulate(val, "IsAuthorizedToUse", &b.IsAuthorizedToUse) + delete(rawMsg, key) + case "serviceGroup": + err = unpopulate(val, "ServiceGroup", &b.ServiceGroup) + delete(rawMsg, key) + case "serviceSupportedRegion": + err = unpopulate(val, "ServiceSupportedRegion", &b.ServiceSupportedRegion) + 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 BackendAddressInboundNatRulePortMappings. +func (b BackendAddressInboundNatRulePortMappings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "inboundNatRulePortMappings", b.InboundNatRulePortMappings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackendAddressInboundNatRulePortMappings. +func (b *BackendAddressInboundNatRulePortMappings) UnmarshalJSON(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 "inboundNatRulePortMappings": + err = unpopulate(val, "InboundNatRulePortMappings", &b.InboundNatRulePortMappings) + 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 BackendAddressPool. +func (b BackendAddressPool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", b.Etag) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackendAddressPool. +func (b *BackendAddressPool) UnmarshalJSON(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 "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 "properties": + err = unpopulate(val, "Properties", &b.Properties) + 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 BackendAddressPoolPropertiesFormat. +func (b BackendAddressPoolPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendIPConfigurations", b.BackendIPConfigurations) + populate(objectMap, "drainPeriodInSeconds", b.DrainPeriodInSeconds) + populate(objectMap, "inboundNatRules", b.InboundNatRules) + populate(objectMap, "loadBalancerBackendAddresses", b.LoadBalancerBackendAddresses) + populate(objectMap, "loadBalancingRules", b.LoadBalancingRules) + populate(objectMap, "location", b.Location) + populate(objectMap, "outboundRule", b.OutboundRule) + populate(objectMap, "outboundRules", b.OutboundRules) + populate(objectMap, "provisioningState", b.ProvisioningState) + populate(objectMap, "syncMode", b.SyncMode) + populate(objectMap, "tunnelInterfaces", b.TunnelInterfaces) + populate(objectMap, "virtualNetwork", b.VirtualNetwork) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackendAddressPoolPropertiesFormat. +func (b *BackendAddressPoolPropertiesFormat) UnmarshalJSON(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 "backendIPConfigurations": + err = unpopulate(val, "BackendIPConfigurations", &b.BackendIPConfigurations) + delete(rawMsg, key) + case "drainPeriodInSeconds": + err = unpopulate(val, "DrainPeriodInSeconds", &b.DrainPeriodInSeconds) + delete(rawMsg, key) + case "inboundNatRules": + err = unpopulate(val, "InboundNatRules", &b.InboundNatRules) + delete(rawMsg, key) + case "loadBalancerBackendAddresses": + err = unpopulate(val, "LoadBalancerBackendAddresses", &b.LoadBalancerBackendAddresses) + delete(rawMsg, key) + case "loadBalancingRules": + err = unpopulate(val, "LoadBalancingRules", &b.LoadBalancingRules) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &b.Location) + delete(rawMsg, key) + case "outboundRule": + err = unpopulate(val, "OutboundRule", &b.OutboundRule) + delete(rawMsg, key) + case "outboundRules": + err = unpopulate(val, "OutboundRules", &b.OutboundRules) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &b.ProvisioningState) + delete(rawMsg, key) + case "syncMode": + err = unpopulate(val, "SyncMode", &b.SyncMode) + delete(rawMsg, key) + case "tunnelInterfaces": + err = unpopulate(val, "TunnelInterfaces", &b.TunnelInterfaces) + delete(rawMsg, key) + case "virtualNetwork": + err = unpopulate(val, "VirtualNetwork", &b.VirtualNetwork) + 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 BaseAdminRule. +func (b BaseAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", b.Etag) + populate(objectMap, "id", b.ID) + objectMap["kind"] = b.Kind + populate(objectMap, "name", b.Name) + populate(objectMap, "systemData", b.SystemData) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BaseAdminRule. +func (b *BaseAdminRule) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &b.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &b.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + 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 BastionActiveSession. +func (b BastionActiveSession) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "protocol", b.Protocol) + populate(objectMap, "resourceType", b.ResourceType) + populate(objectMap, "sessionDurationInMins", b.SessionDurationInMins) + populate(objectMap, "sessionId", b.SessionID) + populateAny(objectMap, "startTime", b.StartTime) + populate(objectMap, "targetHostName", b.TargetHostName) + populate(objectMap, "targetIpAddress", b.TargetIPAddress) + populate(objectMap, "targetResourceGroup", b.TargetResourceGroup) + populate(objectMap, "targetResourceId", b.TargetResourceID) + populate(objectMap, "targetSubscriptionId", b.TargetSubscriptionID) + populate(objectMap, "userName", b.UserName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionActiveSession. +func (b *BastionActiveSession) UnmarshalJSON(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 "protocol": + err = unpopulate(val, "Protocol", &b.Protocol) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &b.ResourceType) + delete(rawMsg, key) + case "sessionDurationInMins": + err = unpopulate(val, "SessionDurationInMins", &b.SessionDurationInMins) + delete(rawMsg, key) + case "sessionId": + err = unpopulate(val, "SessionID", &b.SessionID) + delete(rawMsg, key) + case "startTime": + err = unpopulate(val, "StartTime", &b.StartTime) + delete(rawMsg, key) + case "targetHostName": + err = unpopulate(val, "TargetHostName", &b.TargetHostName) + delete(rawMsg, key) + case "targetIpAddress": + err = unpopulate(val, "TargetIPAddress", &b.TargetIPAddress) + delete(rawMsg, key) + case "targetResourceGroup": + err = unpopulate(val, "TargetResourceGroup", &b.TargetResourceGroup) + delete(rawMsg, key) + case "targetResourceId": + err = unpopulate(val, "TargetResourceID", &b.TargetResourceID) + delete(rawMsg, key) + case "targetSubscriptionId": + err = unpopulate(val, "TargetSubscriptionID", &b.TargetSubscriptionID) + delete(rawMsg, key) + case "userName": + err = unpopulate(val, "UserName", &b.UserName) + 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 BastionActiveSessionListResult. +func (b BastionActiveSessionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", b.NextLink) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionActiveSessionListResult. +func (b *BastionActiveSessionListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, 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 BastionHost. +func (b BastionHost) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", b.Etag) + populate(objectMap, "id", b.ID) + populate(objectMap, "location", b.Location) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "sku", b.SKU) + populate(objectMap, "tags", b.Tags) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionHost. +func (b *BastionHost) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &b.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &b.Location) + 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 "sku": + err = unpopulate(val, "SKU", &b.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &b.Tags) + 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 BastionHostIPConfiguration. +func (b BastionHostIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", b.Etag) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionHostIPConfiguration. +func (b *BastionHostIPConfiguration) UnmarshalJSON(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 "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 "properties": + err = unpopulate(val, "Properties", &b.Properties) + 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 BastionHostIPConfigurationPropertiesFormat. +func (b BastionHostIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAllocationMethod", b.PrivateIPAllocationMethod) + populate(objectMap, "provisioningState", b.ProvisioningState) + populate(objectMap, "publicIPAddress", b.PublicIPAddress) + populate(objectMap, "subnet", b.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionHostIPConfigurationPropertiesFormat. +func (b *BastionHostIPConfigurationPropertiesFormat) UnmarshalJSON(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 "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &b.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &b.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &b.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &b.Subnet) + 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 BastionHostListResult. +func (b BastionHostListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", b.NextLink) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionHostListResult. +func (b *BastionHostListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, 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 BastionHostPropertiesFormat. +func (b BastionHostPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsName", b.DNSName) + populate(objectMap, "disableCopyPaste", b.DisableCopyPaste) + populate(objectMap, "enableFileCopy", b.EnableFileCopy) + populate(objectMap, "enableIpConnect", b.EnableIPConnect) + populate(objectMap, "enableKerberos", b.EnableKerberos) + populate(objectMap, "enableShareableLink", b.EnableShareableLink) + populate(objectMap, "enableTunneling", b.EnableTunneling) + populate(objectMap, "ipConfigurations", b.IPConfigurations) + populate(objectMap, "networkAcls", b.NetworkACLs) + populate(objectMap, "provisioningState", b.ProvisioningState) + populate(objectMap, "scaleUnits", b.ScaleUnits) + populate(objectMap, "virtualNetwork", b.VirtualNetwork) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionHostPropertiesFormat. +func (b *BastionHostPropertiesFormat) UnmarshalJSON(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 "dnsName": + err = unpopulate(val, "DNSName", &b.DNSName) + delete(rawMsg, key) + case "disableCopyPaste": + err = unpopulate(val, "DisableCopyPaste", &b.DisableCopyPaste) + delete(rawMsg, key) + case "enableFileCopy": + err = unpopulate(val, "EnableFileCopy", &b.EnableFileCopy) + delete(rawMsg, key) + case "enableIpConnect": + err = unpopulate(val, "EnableIPConnect", &b.EnableIPConnect) + delete(rawMsg, key) + case "enableKerberos": + err = unpopulate(val, "EnableKerberos", &b.EnableKerberos) + delete(rawMsg, key) + case "enableShareableLink": + err = unpopulate(val, "EnableShareableLink", &b.EnableShareableLink) + delete(rawMsg, key) + case "enableTunneling": + err = unpopulate(val, "EnableTunneling", &b.EnableTunneling) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &b.IPConfigurations) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkACLs", &b.NetworkACLs) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &b.ProvisioningState) + delete(rawMsg, key) + case "scaleUnits": + err = unpopulate(val, "ScaleUnits", &b.ScaleUnits) + delete(rawMsg, key) + case "virtualNetwork": + err = unpopulate(val, "VirtualNetwork", &b.VirtualNetwork) + 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 BastionHostPropertiesFormatNetworkACLs. +func (b BastionHostPropertiesFormatNetworkACLs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipRules", b.IPRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionHostPropertiesFormatNetworkACLs. +func (b *BastionHostPropertiesFormatNetworkACLs) UnmarshalJSON(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 "ipRules": + err = unpopulate(val, "IPRules", &b.IPRules) + 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 BastionSessionDeleteResult. +func (b BastionSessionDeleteResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", b.NextLink) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionSessionDeleteResult. +func (b *BastionSessionDeleteResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, 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 BastionSessionState. +func (b BastionSessionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", b.Message) + populate(objectMap, "sessionId", b.SessionID) + populate(objectMap, "state", b.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionSessionState. +func (b *BastionSessionState) UnmarshalJSON(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 "message": + err = unpopulate(val, "Message", &b.Message) + delete(rawMsg, key) + case "sessionId": + err = unpopulate(val, "SessionID", &b.SessionID) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &b.State) + 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 BastionShareableLink. +func (b BastionShareableLink) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bsl", b.Bsl) + populate(objectMap, "createdAt", b.CreatedAt) + populate(objectMap, "message", b.Message) + populate(objectMap, "vm", b.VM) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionShareableLink. +func (b *BastionShareableLink) UnmarshalJSON(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 "bsl": + err = unpopulate(val, "Bsl", &b.Bsl) + delete(rawMsg, key) + case "createdAt": + err = unpopulate(val, "CreatedAt", &b.CreatedAt) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &b.Message) + delete(rawMsg, key) + case "vm": + err = unpopulate(val, "VM", &b.VM) + 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 BastionShareableLinkListRequest. +func (b BastionShareableLinkListRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vms", b.VMs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionShareableLinkListRequest. +func (b *BastionShareableLinkListRequest) UnmarshalJSON(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 "vms": + err = unpopulate(val, "VMs", &b.VMs) + 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 BastionShareableLinkListResult. +func (b BastionShareableLinkListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", b.NextLink) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BastionShareableLinkListResult. +func (b *BastionShareableLinkListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, 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 BgpConnection. +func (b BgpConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", b.Etag) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpConnection. +func (b *BgpConnection) UnmarshalJSON(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 "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 "properties": + err = unpopulate(val, "Properties", &b.Properties) + 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 BgpConnectionProperties. +func (b BgpConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionState", b.ConnectionState) + populate(objectMap, "hubVirtualNetworkConnection", b.HubVirtualNetworkConnection) + populate(objectMap, "peerAsn", b.PeerAsn) + populate(objectMap, "peerIp", b.PeerIP) + populate(objectMap, "provisioningState", b.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpConnectionProperties. +func (b *BgpConnectionProperties) UnmarshalJSON(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 "connectionState": + err = unpopulate(val, "ConnectionState", &b.ConnectionState) + delete(rawMsg, key) + case "hubVirtualNetworkConnection": + err = unpopulate(val, "HubVirtualNetworkConnection", &b.HubVirtualNetworkConnection) + delete(rawMsg, key) + case "peerAsn": + err = unpopulate(val, "PeerAsn", &b.PeerAsn) + delete(rawMsg, key) + case "peerIp": + err = unpopulate(val, "PeerIP", &b.PeerIP) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &b.ProvisioningState) + 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 BgpPeerStatus. +func (b BgpPeerStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asn", b.Asn) + populate(objectMap, "connectedDuration", b.ConnectedDuration) + populate(objectMap, "localAddress", b.LocalAddress) + populate(objectMap, "messagesReceived", b.MessagesReceived) + populate(objectMap, "messagesSent", b.MessagesSent) + populate(objectMap, "neighbor", b.Neighbor) + populate(objectMap, "routesReceived", b.RoutesReceived) + populate(objectMap, "state", b.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpPeerStatus. +func (b *BgpPeerStatus) UnmarshalJSON(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 "asn": + err = unpopulate(val, "Asn", &b.Asn) + delete(rawMsg, key) + case "connectedDuration": + err = unpopulate(val, "ConnectedDuration", &b.ConnectedDuration) + delete(rawMsg, key) + case "localAddress": + err = unpopulate(val, "LocalAddress", &b.LocalAddress) + delete(rawMsg, key) + case "messagesReceived": + err = unpopulate(val, "MessagesReceived", &b.MessagesReceived) + delete(rawMsg, key) + case "messagesSent": + err = unpopulate(val, "MessagesSent", &b.MessagesSent) + delete(rawMsg, key) + case "neighbor": + err = unpopulate(val, "Neighbor", &b.Neighbor) + delete(rawMsg, key) + case "routesReceived": + err = unpopulate(val, "RoutesReceived", &b.RoutesReceived) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &b.State) + 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 BgpPeerStatusListResult. +func (b BgpPeerStatusListResult) 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 BgpPeerStatusListResult. +func (b *BgpPeerStatusListResult) UnmarshalJSON(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 BgpServiceCommunity. +func (b BgpServiceCommunity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", b.ID) + populate(objectMap, "location", b.Location) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "tags", b.Tags) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpServiceCommunity. +func (b *BgpServiceCommunity) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &b.Location) + 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 "tags": + err = unpopulate(val, "Tags", &b.Tags) + 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 BgpServiceCommunityListResult. +func (b BgpServiceCommunityListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", b.NextLink) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpServiceCommunityListResult. +func (b *BgpServiceCommunityListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, 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 BgpServiceCommunityPropertiesFormat. +func (b BgpServiceCommunityPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bgpCommunities", b.BgpCommunities) + populate(objectMap, "serviceName", b.ServiceName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpServiceCommunityPropertiesFormat. +func (b *BgpServiceCommunityPropertiesFormat) UnmarshalJSON(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 "bgpCommunities": + err = unpopulate(val, "BgpCommunities", &b.BgpCommunities) + delete(rawMsg, key) + case "serviceName": + err = unpopulate(val, "ServiceName", &b.ServiceName) + 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 BgpSettings. +func (b BgpSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asn", b.Asn) + populate(objectMap, "bgpPeeringAddress", b.BgpPeeringAddress) + populate(objectMap, "bgpPeeringAddresses", b.BgpPeeringAddresses) + populate(objectMap, "peerWeight", b.PeerWeight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpSettings. +func (b *BgpSettings) UnmarshalJSON(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 "asn": + err = unpopulate(val, "Asn", &b.Asn) + delete(rawMsg, key) + case "bgpPeeringAddress": + err = unpopulate(val, "BgpPeeringAddress", &b.BgpPeeringAddress) + delete(rawMsg, key) + case "bgpPeeringAddresses": + err = unpopulate(val, "BgpPeeringAddresses", &b.BgpPeeringAddresses) + delete(rawMsg, key) + case "peerWeight": + err = unpopulate(val, "PeerWeight", &b.PeerWeight) + 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 BreakOutCategoryPolicies. +func (b BreakOutCategoryPolicies) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allow", b.Allow) + populate(objectMap, "default", b.Default) + populate(objectMap, "optimize", b.Optimize) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BreakOutCategoryPolicies. +func (b *BreakOutCategoryPolicies) UnmarshalJSON(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 "allow": + err = unpopulate(val, "Allow", &b.Allow) + delete(rawMsg, key) + case "default": + err = unpopulate(val, "Default", &b.Default) + delete(rawMsg, key) + case "optimize": + err = unpopulate(val, "Optimize", &b.Optimize) + 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 CheckPrivateLinkServiceVisibilityRequest. +func (c CheckPrivateLinkServiceVisibilityRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateLinkServiceAlias", c.PrivateLinkServiceAlias) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckPrivateLinkServiceVisibilityRequest. +func (c *CheckPrivateLinkServiceVisibilityRequest) UnmarshalJSON(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 "privateLinkServiceAlias": + err = unpopulate(val, "PrivateLinkServiceAlias", &c.PrivateLinkServiceAlias) + 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 ChildResource. +func (c ChildResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChildResource. +func (c *ChildResource) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + 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 Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties. +func (c Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", c.ClientID) + populate(objectMap, "principalId", c.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties. +func (c *Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties) UnmarshalJSON(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 "clientId": + err = unpopulate(val, "ClientID", &c.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &c.PrincipalID) + 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 ConfigurationDiagnosticParameters. +func (c ConfigurationDiagnosticParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "profiles", c.Profiles) + populate(objectMap, "targetResourceId", c.TargetResourceID) + populate(objectMap, "verbosityLevel", c.VerbosityLevel) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationDiagnosticParameters. +func (c *ConfigurationDiagnosticParameters) UnmarshalJSON(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 "profiles": + err = unpopulate(val, "Profiles", &c.Profiles) + delete(rawMsg, key) + case "targetResourceId": + err = unpopulate(val, "TargetResourceID", &c.TargetResourceID) + delete(rawMsg, key) + case "verbosityLevel": + err = unpopulate(val, "VerbosityLevel", &c.VerbosityLevel) + 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 ConfigurationDiagnosticProfile. +func (c ConfigurationDiagnosticProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destination", c.Destination) + populate(objectMap, "destinationPort", c.DestinationPort) + populate(objectMap, "direction", c.Direction) + populate(objectMap, "protocol", c.Protocol) + populate(objectMap, "source", c.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationDiagnosticProfile. +func (c *ConfigurationDiagnosticProfile) UnmarshalJSON(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 "destination": + err = unpopulate(val, "Destination", &c.Destination) + delete(rawMsg, key) + case "destinationPort": + err = unpopulate(val, "DestinationPort", &c.DestinationPort) + delete(rawMsg, key) + case "direction": + err = unpopulate(val, "Direction", &c.Direction) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &c.Protocol) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + 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 ConfigurationDiagnosticResponse. +func (c ConfigurationDiagnosticResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "results", c.Results) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationDiagnosticResponse. +func (c *ConfigurationDiagnosticResponse) UnmarshalJSON(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 "results": + err = unpopulate(val, "Results", &c.Results) + 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 ConfigurationDiagnosticResult. +func (c ConfigurationDiagnosticResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkSecurityGroupResult", c.NetworkSecurityGroupResult) + populate(objectMap, "profile", c.Profile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationDiagnosticResult. +func (c *ConfigurationDiagnosticResult) UnmarshalJSON(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 "networkSecurityGroupResult": + err = unpopulate(val, "NetworkSecurityGroupResult", &c.NetworkSecurityGroupResult) + delete(rawMsg, key) + case "profile": + err = unpopulate(val, "Profile", &c.Profile) + 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 ConfigurationGroup. +func (c ConfigurationGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationGroup. +func (c *ConfigurationGroup) UnmarshalJSON(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 "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 ConnectionMonitor. +func (c ConnectionMonitor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", c.Location) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitor. +func (c *ConnectionMonitor) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + 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 ConnectionMonitorDestination. +func (c ConnectionMonitorDestination) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", c.Address) + populate(objectMap, "port", c.Port) + populate(objectMap, "resourceId", c.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorDestination. +func (c *ConnectionMonitorDestination) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &c.Address) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &c.Port) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + 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 ConnectionMonitorEndpoint. +func (c ConnectionMonitorEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", c.Address) + populate(objectMap, "coverageLevel", c.CoverageLevel) + populate(objectMap, "filter", c.Filter) + populate(objectMap, "name", c.Name) + populate(objectMap, "resourceId", c.ResourceID) + populate(objectMap, "scope", c.Scope) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorEndpoint. +func (c *ConnectionMonitorEndpoint) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &c.Address) + delete(rawMsg, key) + case "coverageLevel": + err = unpopulate(val, "CoverageLevel", &c.CoverageLevel) + delete(rawMsg, key) + case "filter": + err = unpopulate(val, "Filter", &c.Filter) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &c.Scope) + 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 ConnectionMonitorEndpointFilter. +func (c ConnectionMonitorEndpointFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "items", c.Items) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorEndpointFilter. +func (c *ConnectionMonitorEndpointFilter) UnmarshalJSON(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 "items": + err = unpopulate(val, "Items", &c.Items) + 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 ConnectionMonitorEndpointFilterItem. +func (c ConnectionMonitorEndpointFilterItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", c.Address) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorEndpointFilterItem. +func (c *ConnectionMonitorEndpointFilterItem) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &c.Address) + 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 ConnectionMonitorEndpointScope. +func (c ConnectionMonitorEndpointScope) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exclude", c.Exclude) + populate(objectMap, "include", c.Include) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorEndpointScope. +func (c *ConnectionMonitorEndpointScope) UnmarshalJSON(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 "exclude": + err = unpopulate(val, "Exclude", &c.Exclude) + delete(rawMsg, key) + case "include": + err = unpopulate(val, "Include", &c.Include) + 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 ConnectionMonitorEndpointScopeItem. +func (c ConnectionMonitorEndpointScopeItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", c.Address) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorEndpointScopeItem. +func (c *ConnectionMonitorEndpointScopeItem) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &c.Address) + 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 ConnectionMonitorHTTPConfiguration. +func (c ConnectionMonitorHTTPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "method", c.Method) + populate(objectMap, "path", c.Path) + populate(objectMap, "port", c.Port) + populate(objectMap, "preferHTTPS", c.PreferHTTPS) + populate(objectMap, "requestHeaders", c.RequestHeaders) + populate(objectMap, "validStatusCodeRanges", c.ValidStatusCodeRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorHTTPConfiguration. +func (c *ConnectionMonitorHTTPConfiguration) UnmarshalJSON(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 "method": + err = unpopulate(val, "Method", &c.Method) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &c.Path) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &c.Port) + delete(rawMsg, key) + case "preferHTTPS": + err = unpopulate(val, "PreferHTTPS", &c.PreferHTTPS) + delete(rawMsg, key) + case "requestHeaders": + err = unpopulate(val, "RequestHeaders", &c.RequestHeaders) + delete(rawMsg, key) + case "validStatusCodeRanges": + err = unpopulate(val, "ValidStatusCodeRanges", &c.ValidStatusCodeRanges) + 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 ConnectionMonitorIcmpConfiguration. +func (c ConnectionMonitorIcmpConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disableTraceRoute", c.DisableTraceRoute) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorIcmpConfiguration. +func (c *ConnectionMonitorIcmpConfiguration) UnmarshalJSON(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 "disableTraceRoute": + err = unpopulate(val, "DisableTraceRoute", &c.DisableTraceRoute) + 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 ConnectionMonitorListResult. +func (c ConnectionMonitorListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorListResult. +func (c *ConnectionMonitorListResult) UnmarshalJSON(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 "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 ConnectionMonitorOutput. +func (c ConnectionMonitorOutput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", c.Type) + populate(objectMap, "workspaceSettings", c.WorkspaceSettings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorOutput. +func (c *ConnectionMonitorOutput) UnmarshalJSON(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 "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "workspaceSettings": + err = unpopulate(val, "WorkspaceSettings", &c.WorkspaceSettings) + 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 ConnectionMonitorParameters. +func (c ConnectionMonitorParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoStart", c.AutoStart) + populate(objectMap, "destination", c.Destination) + populate(objectMap, "endpoints", c.Endpoints) + populate(objectMap, "monitoringIntervalInSeconds", c.MonitoringIntervalInSeconds) + populate(objectMap, "notes", c.Notes) + populate(objectMap, "outputs", c.Outputs) + populate(objectMap, "source", c.Source) + populate(objectMap, "testConfigurations", c.TestConfigurations) + populate(objectMap, "testGroups", c.TestGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorParameters. +func (c *ConnectionMonitorParameters) UnmarshalJSON(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 "autoStart": + err = unpopulate(val, "AutoStart", &c.AutoStart) + delete(rawMsg, key) + case "destination": + err = unpopulate(val, "Destination", &c.Destination) + delete(rawMsg, key) + case "endpoints": + err = unpopulate(val, "Endpoints", &c.Endpoints) + delete(rawMsg, key) + case "monitoringIntervalInSeconds": + err = unpopulate(val, "MonitoringIntervalInSeconds", &c.MonitoringIntervalInSeconds) + delete(rawMsg, key) + case "notes": + err = unpopulate(val, "Notes", &c.Notes) + delete(rawMsg, key) + case "outputs": + err = unpopulate(val, "Outputs", &c.Outputs) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + case "testConfigurations": + err = unpopulate(val, "TestConfigurations", &c.TestConfigurations) + delete(rawMsg, key) + case "testGroups": + err = unpopulate(val, "TestGroups", &c.TestGroups) + 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 ConnectionMonitorQueryResult. +func (c ConnectionMonitorQueryResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sourceStatus", c.SourceStatus) + populate(objectMap, "states", c.States) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorQueryResult. +func (c *ConnectionMonitorQueryResult) UnmarshalJSON(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 "sourceStatus": + err = unpopulate(val, "SourceStatus", &c.SourceStatus) + delete(rawMsg, key) + case "states": + err = unpopulate(val, "States", &c.States) + 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 ConnectionMonitorResult. +func (c ConnectionMonitorResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorResult. +func (c *ConnectionMonitorResult) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + 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 "tags": + err = unpopulate(val, "Tags", &c.Tags) + 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 ConnectionMonitorResultProperties. +func (c ConnectionMonitorResultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoStart", c.AutoStart) + populate(objectMap, "connectionMonitorType", c.ConnectionMonitorType) + populate(objectMap, "destination", c.Destination) + populate(objectMap, "endpoints", c.Endpoints) + populate(objectMap, "monitoringIntervalInSeconds", c.MonitoringIntervalInSeconds) + populate(objectMap, "monitoringStatus", c.MonitoringStatus) + populate(objectMap, "notes", c.Notes) + populate(objectMap, "outputs", c.Outputs) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "source", c.Source) + populateDateTimeRFC3339(objectMap, "startTime", c.StartTime) + populate(objectMap, "testConfigurations", c.TestConfigurations) + populate(objectMap, "testGroups", c.TestGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorResultProperties. +func (c *ConnectionMonitorResultProperties) UnmarshalJSON(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 "autoStart": + err = unpopulate(val, "AutoStart", &c.AutoStart) + delete(rawMsg, key) + case "connectionMonitorType": + err = unpopulate(val, "ConnectionMonitorType", &c.ConnectionMonitorType) + delete(rawMsg, key) + case "destination": + err = unpopulate(val, "Destination", &c.Destination) + delete(rawMsg, key) + case "endpoints": + err = unpopulate(val, "Endpoints", &c.Endpoints) + delete(rawMsg, key) + case "monitoringIntervalInSeconds": + err = unpopulate(val, "MonitoringIntervalInSeconds", &c.MonitoringIntervalInSeconds) + delete(rawMsg, key) + case "monitoringStatus": + err = unpopulate(val, "MonitoringStatus", &c.MonitoringStatus) + delete(rawMsg, key) + case "notes": + err = unpopulate(val, "Notes", &c.Notes) + delete(rawMsg, key) + case "outputs": + err = unpopulate(val, "Outputs", &c.Outputs) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &c.StartTime) + delete(rawMsg, key) + case "testConfigurations": + err = unpopulate(val, "TestConfigurations", &c.TestConfigurations) + delete(rawMsg, key) + case "testGroups": + err = unpopulate(val, "TestGroups", &c.TestGroups) + 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 ConnectionMonitorSource. +func (c ConnectionMonitorSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "port", c.Port) + populate(objectMap, "resourceId", c.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorSource. +func (c *ConnectionMonitorSource) UnmarshalJSON(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 "port": + err = unpopulate(val, "Port", &c.Port) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + 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 ConnectionMonitorSuccessThreshold. +func (c ConnectionMonitorSuccessThreshold) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "checksFailedPercent", c.ChecksFailedPercent) + populate(objectMap, "roundTripTimeMs", c.RoundTripTimeMs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorSuccessThreshold. +func (c *ConnectionMonitorSuccessThreshold) UnmarshalJSON(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 "checksFailedPercent": + err = unpopulate(val, "ChecksFailedPercent", &c.ChecksFailedPercent) + delete(rawMsg, key) + case "roundTripTimeMs": + err = unpopulate(val, "RoundTripTimeMs", &c.RoundTripTimeMs) + 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 ConnectionMonitorTCPConfiguration. +func (c ConnectionMonitorTCPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationPortBehavior", c.DestinationPortBehavior) + populate(objectMap, "disableTraceRoute", c.DisableTraceRoute) + populate(objectMap, "port", c.Port) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorTCPConfiguration. +func (c *ConnectionMonitorTCPConfiguration) UnmarshalJSON(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 "destinationPortBehavior": + err = unpopulate(val, "DestinationPortBehavior", &c.DestinationPortBehavior) + delete(rawMsg, key) + case "disableTraceRoute": + err = unpopulate(val, "DisableTraceRoute", &c.DisableTraceRoute) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &c.Port) + 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 ConnectionMonitorTestConfiguration. +func (c ConnectionMonitorTestConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "httpConfiguration", c.HTTPConfiguration) + populate(objectMap, "icmpConfiguration", c.IcmpConfiguration) + populate(objectMap, "name", c.Name) + populate(objectMap, "preferredIPVersion", c.PreferredIPVersion) + populate(objectMap, "protocol", c.Protocol) + populate(objectMap, "successThreshold", c.SuccessThreshold) + populate(objectMap, "tcpConfiguration", c.TCPConfiguration) + populate(objectMap, "testFrequencySec", c.TestFrequencySec) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorTestConfiguration. +func (c *ConnectionMonitorTestConfiguration) UnmarshalJSON(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 "httpConfiguration": + err = unpopulate(val, "HTTPConfiguration", &c.HTTPConfiguration) + delete(rawMsg, key) + case "icmpConfiguration": + err = unpopulate(val, "IcmpConfiguration", &c.IcmpConfiguration) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "preferredIPVersion": + err = unpopulate(val, "PreferredIPVersion", &c.PreferredIPVersion) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &c.Protocol) + delete(rawMsg, key) + case "successThreshold": + err = unpopulate(val, "SuccessThreshold", &c.SuccessThreshold) + delete(rawMsg, key) + case "tcpConfiguration": + err = unpopulate(val, "TCPConfiguration", &c.TCPConfiguration) + delete(rawMsg, key) + case "testFrequencySec": + err = unpopulate(val, "TestFrequencySec", &c.TestFrequencySec) + 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 ConnectionMonitorTestGroup. +func (c ConnectionMonitorTestGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinations", c.Destinations) + populate(objectMap, "disable", c.Disable) + populate(objectMap, "name", c.Name) + populate(objectMap, "sources", c.Sources) + populate(objectMap, "testConfigurations", c.TestConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorTestGroup. +func (c *ConnectionMonitorTestGroup) UnmarshalJSON(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 "destinations": + err = unpopulate(val, "Destinations", &c.Destinations) + delete(rawMsg, key) + case "disable": + err = unpopulate(val, "Disable", &c.Disable) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "sources": + err = unpopulate(val, "Sources", &c.Sources) + delete(rawMsg, key) + case "testConfigurations": + err = unpopulate(val, "TestConfigurations", &c.TestConfigurations) + 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 ConnectionMonitorWorkspaceSettings. +func (c ConnectionMonitorWorkspaceSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "workspaceResourceId", c.WorkspaceResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionMonitorWorkspaceSettings. +func (c *ConnectionMonitorWorkspaceSettings) UnmarshalJSON(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 "workspaceResourceId": + err = unpopulate(val, "WorkspaceResourceID", &c.WorkspaceResourceID) + 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 ConnectionResetSharedKey. +func (c ConnectionResetSharedKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyLength", c.KeyLength) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionResetSharedKey. +func (c *ConnectionResetSharedKey) UnmarshalJSON(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 "keyLength": + err = unpopulate(val, "KeyLength", &c.KeyLength) + 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 ConnectionSharedKey. +func (c ConnectionSharedKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionSharedKey. +func (c *ConnectionSharedKey) UnmarshalJSON(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 "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 ConnectionStateSnapshot. +func (c ConnectionStateSnapshot) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "avgLatencyInMs", c.AvgLatencyInMs) + populate(objectMap, "connectionState", c.ConnectionState) + populateDateTimeRFC3339(objectMap, "endTime", c.EndTime) + populate(objectMap, "evaluationState", c.EvaluationState) + populate(objectMap, "hops", c.Hops) + populate(objectMap, "maxLatencyInMs", c.MaxLatencyInMs) + populate(objectMap, "minLatencyInMs", c.MinLatencyInMs) + populate(objectMap, "probesFailed", c.ProbesFailed) + populate(objectMap, "probesSent", c.ProbesSent) + populateDateTimeRFC3339(objectMap, "startTime", c.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionStateSnapshot. +func (c *ConnectionStateSnapshot) UnmarshalJSON(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 "avgLatencyInMs": + err = unpopulate(val, "AvgLatencyInMs", &c.AvgLatencyInMs) + delete(rawMsg, key) + case "connectionState": + err = unpopulate(val, "ConnectionState", &c.ConnectionState) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &c.EndTime) + delete(rawMsg, key) + case "evaluationState": + err = unpopulate(val, "EvaluationState", &c.EvaluationState) + delete(rawMsg, key) + case "hops": + err = unpopulate(val, "Hops", &c.Hops) + delete(rawMsg, key) + case "maxLatencyInMs": + err = unpopulate(val, "MaxLatencyInMs", &c.MaxLatencyInMs) + delete(rawMsg, key) + case "minLatencyInMs": + err = unpopulate(val, "MinLatencyInMs", &c.MinLatencyInMs) + delete(rawMsg, key) + case "probesFailed": + err = unpopulate(val, "ProbesFailed", &c.ProbesFailed) + delete(rawMsg, key) + case "probesSent": + err = unpopulate(val, "ProbesSent", &c.ProbesSent) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &c.StartTime) + 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 ConnectivityConfiguration. +func (c ConnectivityConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + 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 ConnectivityConfiguration. +func (c *ConnectivityConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, 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 ConnectivityConfigurationListResult. +func (c ConnectivityConfigurationListResult) 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 ConnectivityConfigurationListResult. +func (c *ConnectivityConfigurationListResult) UnmarshalJSON(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 ConnectivityConfigurationProperties. +func (c ConnectivityConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliesToGroups", c.AppliesToGroups) + populate(objectMap, "connectivityTopology", c.ConnectivityTopology) + populate(objectMap, "deleteExistingPeering", c.DeleteExistingPeering) + populate(objectMap, "description", c.Description) + populate(objectMap, "hubs", c.Hubs) + populate(objectMap, "isGlobal", c.IsGlobal) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "resourceGuid", c.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivityConfigurationProperties. +func (c *ConnectivityConfigurationProperties) UnmarshalJSON(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 "appliesToGroups": + err = unpopulate(val, "AppliesToGroups", &c.AppliesToGroups) + delete(rawMsg, key) + case "connectivityTopology": + err = unpopulate(val, "ConnectivityTopology", &c.ConnectivityTopology) + delete(rawMsg, key) + case "deleteExistingPeering": + err = unpopulate(val, "DeleteExistingPeering", &c.DeleteExistingPeering) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "hubs": + err = unpopulate(val, "Hubs", &c.Hubs) + delete(rawMsg, key) + case "isGlobal": + err = unpopulate(val, "IsGlobal", &c.IsGlobal) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &c.ResourceGUID) + 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 ConnectivityDestination. +func (c ConnectivityDestination) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", c.Address) + populate(objectMap, "port", c.Port) + populate(objectMap, "resourceId", c.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivityDestination. +func (c *ConnectivityDestination) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &c.Address) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &c.Port) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + 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 ConnectivityGroupItem. +func (c ConnectivityGroupItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupConnectivity", c.GroupConnectivity) + populate(objectMap, "isGlobal", c.IsGlobal) + populate(objectMap, "networkGroupId", c.NetworkGroupID) + populate(objectMap, "useHubGateway", c.UseHubGateway) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivityGroupItem. +func (c *ConnectivityGroupItem) UnmarshalJSON(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 "groupConnectivity": + err = unpopulate(val, "GroupConnectivity", &c.GroupConnectivity) + delete(rawMsg, key) + case "isGlobal": + err = unpopulate(val, "IsGlobal", &c.IsGlobal) + delete(rawMsg, key) + case "networkGroupId": + err = unpopulate(val, "NetworkGroupID", &c.NetworkGroupID) + delete(rawMsg, key) + case "useHubGateway": + err = unpopulate(val, "UseHubGateway", &c.UseHubGateway) + 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 ConnectivityHop. +func (c ConnectivityHop) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", c.Address) + populate(objectMap, "id", c.ID) + populate(objectMap, "issues", c.Issues) + populate(objectMap, "links", c.Links) + populate(objectMap, "nextHopIds", c.NextHopIDs) + populate(objectMap, "previousHopIds", c.PreviousHopIDs) + populate(objectMap, "previousLinks", c.PreviousLinks) + populate(objectMap, "resourceId", c.ResourceID) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivityHop. +func (c *ConnectivityHop) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &c.Address) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "issues": + err = unpopulate(val, "Issues", &c.Issues) + delete(rawMsg, key) + case "links": + err = unpopulate(val, "Links", &c.Links) + delete(rawMsg, key) + case "nextHopIds": + err = unpopulate(val, "NextHopIDs", &c.NextHopIDs) + delete(rawMsg, key) + case "previousHopIds": + err = unpopulate(val, "PreviousHopIDs", &c.PreviousHopIDs) + delete(rawMsg, key) + case "previousLinks": + err = unpopulate(val, "PreviousLinks", &c.PreviousLinks) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + 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 ConnectivityInformation. +func (c ConnectivityInformation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "avgLatencyInMs", c.AvgLatencyInMs) + populate(objectMap, "connectionStatus", c.ConnectionStatus) + populate(objectMap, "hops", c.Hops) + populate(objectMap, "maxLatencyInMs", c.MaxLatencyInMs) + populate(objectMap, "minLatencyInMs", c.MinLatencyInMs) + populate(objectMap, "probesFailed", c.ProbesFailed) + populate(objectMap, "probesSent", c.ProbesSent) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivityInformation. +func (c *ConnectivityInformation) UnmarshalJSON(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 "avgLatencyInMs": + err = unpopulate(val, "AvgLatencyInMs", &c.AvgLatencyInMs) + delete(rawMsg, key) + case "connectionStatus": + err = unpopulate(val, "ConnectionStatus", &c.ConnectionStatus) + delete(rawMsg, key) + case "hops": + err = unpopulate(val, "Hops", &c.Hops) + delete(rawMsg, key) + case "maxLatencyInMs": + err = unpopulate(val, "MaxLatencyInMs", &c.MaxLatencyInMs) + delete(rawMsg, key) + case "minLatencyInMs": + err = unpopulate(val, "MinLatencyInMs", &c.MinLatencyInMs) + delete(rawMsg, key) + case "probesFailed": + err = unpopulate(val, "ProbesFailed", &c.ProbesFailed) + delete(rawMsg, key) + case "probesSent": + err = unpopulate(val, "ProbesSent", &c.ProbesSent) + 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 ConnectivityIssue. +func (c ConnectivityIssue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "context", c.Context) + populate(objectMap, "origin", c.Origin) + populate(objectMap, "severity", c.Severity) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivityIssue. +func (c *ConnectivityIssue) UnmarshalJSON(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 "context": + err = unpopulate(val, "Context", &c.Context) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &c.Origin) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, "Severity", &c.Severity) + 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 ConnectivityParameters. +func (c ConnectivityParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destination", c.Destination) + populate(objectMap, "preferredIPVersion", c.PreferredIPVersion) + populate(objectMap, "protocol", c.Protocol) + populate(objectMap, "protocolConfiguration", c.ProtocolConfiguration) + populate(objectMap, "source", c.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivityParameters. +func (c *ConnectivityParameters) UnmarshalJSON(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 "destination": + err = unpopulate(val, "Destination", &c.Destination) + delete(rawMsg, key) + case "preferredIPVersion": + err = unpopulate(val, "PreferredIPVersion", &c.PreferredIPVersion) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &c.Protocol) + delete(rawMsg, key) + case "protocolConfiguration": + err = unpopulate(val, "ProtocolConfiguration", &c.ProtocolConfiguration) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + 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 ConnectivitySource. +func (c ConnectivitySource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "port", c.Port) + populate(objectMap, "resourceId", c.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectivitySource. +func (c *ConnectivitySource) UnmarshalJSON(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 "port": + err = unpopulate(val, "Port", &c.Port) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + 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 Container. +func (c Container) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Container. +func (c *Container) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContainerNetworkInterface. +func (c ContainerNetworkInterface) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerNetworkInterface. +func (c *ContainerNetworkInterface) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, 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 "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 ContainerNetworkInterfaceConfiguration. +func (c ContainerNetworkInterfaceConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerNetworkInterfaceConfiguration. +func (c *ContainerNetworkInterfaceConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, 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 "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 ContainerNetworkInterfaceConfigurationPropertiesFormat. +func (c ContainerNetworkInterfaceConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerNetworkInterfaces", c.ContainerNetworkInterfaces) + populate(objectMap, "ipConfigurations", c.IPConfigurations) + populate(objectMap, "provisioningState", c.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerNetworkInterfaceConfigurationPropertiesFormat. +func (c *ContainerNetworkInterfaceConfigurationPropertiesFormat) UnmarshalJSON(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 "containerNetworkInterfaces": + err = unpopulate(val, "ContainerNetworkInterfaces", &c.ContainerNetworkInterfaces) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &c.IPConfigurations) + 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 ContainerNetworkInterfaceIPConfiguration. +func (c ContainerNetworkInterfaceIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerNetworkInterfaceIPConfiguration. +func (c *ContainerNetworkInterfaceIPConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &c.Etag) + 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 "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 ContainerNetworkInterfaceIPConfigurationPropertiesFormat. +func (c ContainerNetworkInterfaceIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", c.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerNetworkInterfaceIPConfigurationPropertiesFormat. +func (c *ContainerNetworkInterfaceIPConfigurationPropertiesFormat) UnmarshalJSON(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 "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 ContainerNetworkInterfacePropertiesFormat. +func (c ContainerNetworkInterfacePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "container", c.Container) + populate(objectMap, "containerNetworkInterfaceConfiguration", c.ContainerNetworkInterfaceConfiguration) + populate(objectMap, "ipConfigurations", c.IPConfigurations) + populate(objectMap, "provisioningState", c.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerNetworkInterfacePropertiesFormat. +func (c *ContainerNetworkInterfacePropertiesFormat) UnmarshalJSON(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 "container": + err = unpopulate(val, "Container", &c.Container) + delete(rawMsg, key) + case "containerNetworkInterfaceConfiguration": + err = unpopulate(val, "ContainerNetworkInterfaceConfiguration", &c.ContainerNetworkInterfaceConfiguration) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &c.IPConfigurations) + 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 Criterion. +func (c Criterion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asPath", c.AsPath) + populate(objectMap, "community", c.Community) + populate(objectMap, "matchCondition", c.MatchCondition) + populate(objectMap, "routePrefix", c.RoutePrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Criterion. +func (c *Criterion) UnmarshalJSON(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 "asPath": + err = unpopulate(val, "AsPath", &c.AsPath) + delete(rawMsg, key) + case "community": + err = unpopulate(val, "Community", &c.Community) + delete(rawMsg, key) + case "matchCondition": + err = unpopulate(val, "MatchCondition", &c.MatchCondition) + delete(rawMsg, key) + case "routePrefix": + err = unpopulate(val, "RoutePrefix", &c.RoutePrefix) + 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 CrossTenantScopes. +func (c CrossTenantScopes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "managementGroups", c.ManagementGroups) + populate(objectMap, "subscriptions", c.Subscriptions) + populate(objectMap, "tenantId", c.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CrossTenantScopes. +func (c *CrossTenantScopes) UnmarshalJSON(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 "managementGroups": + err = unpopulate(val, "ManagementGroups", &c.ManagementGroups) + delete(rawMsg, key) + case "subscriptions": + err = unpopulate(val, "Subscriptions", &c.Subscriptions) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &c.TenantID) + 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 CustomDNSConfigPropertiesFormat. +func (c CustomDNSConfigPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fqdn", c.Fqdn) + populate(objectMap, "ipAddresses", c.IPAddresses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomDNSConfigPropertiesFormat. +func (c *CustomDNSConfigPropertiesFormat) UnmarshalJSON(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 "fqdn": + err = unpopulate(val, "Fqdn", &c.Fqdn) + delete(rawMsg, key) + case "ipAddresses": + err = unpopulate(val, "IPAddresses", &c.IPAddresses) + 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 CustomIPPrefix. +func (c CustomIPPrefix) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "extendedLocation", c.ExtendedLocation) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + populate(objectMap, "zones", c.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomIPPrefix. +func (c *CustomIPPrefix) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &c.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + 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 "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &c.Zones) + 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 CustomIPPrefixListResult. +func (c CustomIPPrefixListResult) 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 CustomIPPrefixListResult. +func (c *CustomIPPrefixListResult) UnmarshalJSON(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 CustomIPPrefixPropertiesFormat. +func (c CustomIPPrefixPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asn", c.Asn) + populate(objectMap, "authorizationMessage", c.AuthorizationMessage) + populate(objectMap, "childCustomIpPrefixes", c.ChildCustomIPPrefixes) + populate(objectMap, "cidr", c.Cidr) + populate(objectMap, "commissionedState", c.CommissionedState) + populate(objectMap, "customIpPrefixParent", c.CustomIPPrefixParent) + populate(objectMap, "expressRouteAdvertise", c.ExpressRouteAdvertise) + populate(objectMap, "failedReason", c.FailedReason) + populate(objectMap, "geo", c.Geo) + populate(objectMap, "noInternetAdvertise", c.NoInternetAdvertise) + populate(objectMap, "prefixType", c.PrefixType) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "publicIpPrefixes", c.PublicIPPrefixes) + populate(objectMap, "resourceGuid", c.ResourceGUID) + populate(objectMap, "signedMessage", c.SignedMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomIPPrefixPropertiesFormat. +func (c *CustomIPPrefixPropertiesFormat) UnmarshalJSON(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 "asn": + err = unpopulate(val, "Asn", &c.Asn) + delete(rawMsg, key) + case "authorizationMessage": + err = unpopulate(val, "AuthorizationMessage", &c.AuthorizationMessage) + delete(rawMsg, key) + case "childCustomIpPrefixes": + err = unpopulate(val, "ChildCustomIPPrefixes", &c.ChildCustomIPPrefixes) + delete(rawMsg, key) + case "cidr": + err = unpopulate(val, "Cidr", &c.Cidr) + delete(rawMsg, key) + case "commissionedState": + err = unpopulate(val, "CommissionedState", &c.CommissionedState) + delete(rawMsg, key) + case "customIpPrefixParent": + err = unpopulate(val, "CustomIPPrefixParent", &c.CustomIPPrefixParent) + delete(rawMsg, key) + case "expressRouteAdvertise": + err = unpopulate(val, "ExpressRouteAdvertise", &c.ExpressRouteAdvertise) + delete(rawMsg, key) + case "failedReason": + err = unpopulate(val, "FailedReason", &c.FailedReason) + delete(rawMsg, key) + case "geo": + err = unpopulate(val, "Geo", &c.Geo) + delete(rawMsg, key) + case "noInternetAdvertise": + err = unpopulate(val, "NoInternetAdvertise", &c.NoInternetAdvertise) + delete(rawMsg, key) + case "prefixType": + err = unpopulate(val, "PrefixType", &c.PrefixType) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "publicIpPrefixes": + err = unpopulate(val, "PublicIPPrefixes", &c.PublicIPPrefixes) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &c.ResourceGUID) + delete(rawMsg, key) + case "signedMessage": + err = unpopulate(val, "SignedMessage", &c.SignedMessage) + 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 DNSNameAvailabilityResult. +func (d DNSNameAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "available", d.Available) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSNameAvailabilityResult. +func (d *DNSNameAvailabilityResult) UnmarshalJSON(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 "available": + err = unpopulate(val, "Available", &d.Available) + 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 DNSSettings. +func (d DNSSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enableProxy", d.EnableProxy) + populate(objectMap, "requireProxyForNetworkRules", d.RequireProxyForNetworkRules) + populate(objectMap, "servers", d.Servers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSSettings. +func (d *DNSSettings) UnmarshalJSON(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 "enableProxy": + err = unpopulate(val, "EnableProxy", &d.EnableProxy) + delete(rawMsg, key) + case "requireProxyForNetworkRules": + err = unpopulate(val, "RequireProxyForNetworkRules", &d.RequireProxyForNetworkRules) + delete(rawMsg, key) + case "servers": + err = unpopulate(val, "Servers", &d.Servers) + 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 DdosCustomPolicy. +func (d DdosCustomPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DdosCustomPolicy. +func (d *DdosCustomPolicy) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + 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 "tags": + err = unpopulate(val, "Tags", &d.Tags) + 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 DdosCustomPolicyPropertiesFormat. +func (d DdosCustomPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "resourceGuid", d.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DdosCustomPolicyPropertiesFormat. +func (d *DdosCustomPolicyPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &d.ResourceGUID) + 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 DdosProtectionPlan. +func (d DdosProtectionPlan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DdosProtectionPlan. +func (d *DdosProtectionPlan) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + 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 "tags": + err = unpopulate(val, "Tags", &d.Tags) + 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 DdosProtectionPlanListResult. +func (d DdosProtectionPlanListResult) 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 DdosProtectionPlanListResult. +func (d *DdosProtectionPlanListResult) UnmarshalJSON(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 DdosProtectionPlanPropertiesFormat. +func (d DdosProtectionPlanPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "publicIPAddresses", d.PublicIPAddresses) + populate(objectMap, "resourceGuid", d.ResourceGUID) + populate(objectMap, "virtualNetworks", d.VirtualNetworks) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DdosProtectionPlanPropertiesFormat. +func (d *DdosProtectionPlanPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddresses": + err = unpopulate(val, "PublicIPAddresses", &d.PublicIPAddresses) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &d.ResourceGUID) + delete(rawMsg, key) + case "virtualNetworks": + err = unpopulate(val, "VirtualNetworks", &d.VirtualNetworks) + 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 DdosSettings. +func (d DdosSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ddosProtectionPlan", d.DdosProtectionPlan) + populate(objectMap, "protectionMode", d.ProtectionMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DdosSettings. +func (d *DdosSettings) UnmarshalJSON(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 "ddosProtectionPlan": + err = unpopulate(val, "DdosProtectionPlan", &d.DdosProtectionPlan) + delete(rawMsg, key) + case "protectionMode": + err = unpopulate(val, "ProtectionMode", &d.ProtectionMode) + 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 DefaultAdminPropertiesFormat. +func (d DefaultAdminPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", d.Access) + populate(objectMap, "description", d.Description) + populate(objectMap, "destinationPortRanges", d.DestinationPortRanges) + populate(objectMap, "destinations", d.Destinations) + populate(objectMap, "direction", d.Direction) + populate(objectMap, "flag", d.Flag) + populate(objectMap, "priority", d.Priority) + populate(objectMap, "protocol", d.Protocol) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "resourceGuid", d.ResourceGUID) + populate(objectMap, "sourcePortRanges", d.SourcePortRanges) + populate(objectMap, "sources", d.Sources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefaultAdminPropertiesFormat. +func (d *DefaultAdminPropertiesFormat) UnmarshalJSON(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 "access": + err = unpopulate(val, "Access", &d.Access) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &d.Description) + delete(rawMsg, key) + case "destinationPortRanges": + err = unpopulate(val, "DestinationPortRanges", &d.DestinationPortRanges) + delete(rawMsg, key) + case "destinations": + err = unpopulate(val, "Destinations", &d.Destinations) + delete(rawMsg, key) + case "direction": + err = unpopulate(val, "Direction", &d.Direction) + delete(rawMsg, key) + case "flag": + err = unpopulate(val, "Flag", &d.Flag) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &d.Priority) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &d.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &d.ResourceGUID) + delete(rawMsg, key) + case "sourcePortRanges": + err = unpopulate(val, "SourcePortRanges", &d.SourcePortRanges) + delete(rawMsg, key) + case "sources": + err = unpopulate(val, "Sources", &d.Sources) + 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 DefaultAdminRule. +func (d DefaultAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + populate(objectMap, "id", d.ID) + objectMap["kind"] = AdminRuleKindDefault + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefaultAdminRule. +func (d *DefaultAdminRule) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + 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 "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + 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 DefaultRuleSetPropertyFormat. +func (d DefaultRuleSetPropertyFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleSetType", d.RuleSetType) + populate(objectMap, "ruleSetVersion", d.RuleSetVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefaultRuleSetPropertyFormat. +func (d *DefaultRuleSetPropertyFormat) UnmarshalJSON(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 "ruleSetType": + err = unpopulate(val, "RuleSetType", &d.RuleSetType) + delete(rawMsg, key) + case "ruleSetVersion": + err = unpopulate(val, "RuleSetVersion", &d.RuleSetVersion) + 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 Delegation. +func (d Delegation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + 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 Delegation. +func (d *Delegation) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, 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 DelegationProperties. +func (d DelegationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "serviceName", d.ServiceName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DelegationProperties. +func (d *DelegationProperties) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "serviceName": + err = unpopulate(val, "ServiceName", &d.ServiceName) + 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 DeviceProperties. +func (d DeviceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deviceModel", d.DeviceModel) + populate(objectMap, "deviceVendor", d.DeviceVendor) + populate(objectMap, "linkSpeedInMbps", d.LinkSpeedInMbps) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeviceProperties. +func (d *DeviceProperties) UnmarshalJSON(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 "deviceModel": + err = unpopulate(val, "DeviceModel", &d.DeviceModel) + delete(rawMsg, key) + case "deviceVendor": + err = unpopulate(val, "DeviceVendor", &d.DeviceVendor) + delete(rawMsg, key) + case "linkSpeedInMbps": + err = unpopulate(val, "LinkSpeedInMbps", &d.LinkSpeedInMbps) + 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 DhcpOptions. +func (d DhcpOptions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsServers", d.DNSServers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DhcpOptions. +func (d *DhcpOptions) UnmarshalJSON(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 "dnsServers": + err = unpopulate(val, "DNSServers", &d.DNSServers) + 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, "internalName", d.InternalName) + 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 "internalName": + err = unpopulate(val, "InternalName", &d.InternalName) + 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 DscpConfiguration. +func (d DscpConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DscpConfiguration. +func (d *DscpConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + 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 "tags": + err = unpopulate(val, "Tags", &d.Tags) + 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 DscpConfigurationListResult. +func (d DscpConfigurationListResult) 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 DscpConfigurationListResult. +func (d *DscpConfigurationListResult) UnmarshalJSON(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 DscpConfigurationPropertiesFormat. +func (d DscpConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "associatedNetworkInterfaces", d.AssociatedNetworkInterfaces) + populate(objectMap, "destinationIpRanges", d.DestinationIPRanges) + populate(objectMap, "destinationPortRanges", d.DestinationPortRanges) + populate(objectMap, "markings", d.Markings) + populate(objectMap, "protocol", d.Protocol) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "qosCollectionId", d.QosCollectionID) + populate(objectMap, "qosDefinitionCollection", d.QosDefinitionCollection) + populate(objectMap, "resourceGuid", d.ResourceGUID) + populate(objectMap, "sourceIpRanges", d.SourceIPRanges) + populate(objectMap, "sourcePortRanges", d.SourcePortRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DscpConfigurationPropertiesFormat. +func (d *DscpConfigurationPropertiesFormat) UnmarshalJSON(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 "associatedNetworkInterfaces": + err = unpopulate(val, "AssociatedNetworkInterfaces", &d.AssociatedNetworkInterfaces) + delete(rawMsg, key) + case "destinationIpRanges": + err = unpopulate(val, "DestinationIPRanges", &d.DestinationIPRanges) + delete(rawMsg, key) + case "destinationPortRanges": + err = unpopulate(val, "DestinationPortRanges", &d.DestinationPortRanges) + delete(rawMsg, key) + case "markings": + err = unpopulate(val, "Markings", &d.Markings) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &d.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "qosCollectionId": + err = unpopulate(val, "QosCollectionID", &d.QosCollectionID) + delete(rawMsg, key) + case "qosDefinitionCollection": + err = unpopulate(val, "QosDefinitionCollection", &d.QosDefinitionCollection) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &d.ResourceGUID) + delete(rawMsg, key) + case "sourceIpRanges": + err = unpopulate(val, "SourceIPRanges", &d.SourceIPRanges) + delete(rawMsg, key) + case "sourcePortRanges": + err = unpopulate(val, "SourcePortRanges", &d.SourcePortRanges) + 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 EffectiveBaseSecurityAdminRule. +func (e EffectiveBaseSecurityAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configurationDescription", e.ConfigurationDescription) + populate(objectMap, "id", e.ID) + objectMap["kind"] = e.Kind + populate(objectMap, "ruleCollectionAppliesToGroups", e.RuleCollectionAppliesToGroups) + populate(objectMap, "ruleCollectionDescription", e.RuleCollectionDescription) + populate(objectMap, "ruleGroups", e.RuleGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveBaseSecurityAdminRule. +func (e *EffectiveBaseSecurityAdminRule) UnmarshalJSON(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 "configurationDescription": + err = unpopulate(val, "ConfigurationDescription", &e.ConfigurationDescription) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &e.Kind) + delete(rawMsg, key) + case "ruleCollectionAppliesToGroups": + err = unpopulate(val, "RuleCollectionAppliesToGroups", &e.RuleCollectionAppliesToGroups) + delete(rawMsg, key) + case "ruleCollectionDescription": + err = unpopulate(val, "RuleCollectionDescription", &e.RuleCollectionDescription) + delete(rawMsg, key) + case "ruleGroups": + err = unpopulate(val, "RuleGroups", &e.RuleGroups) + 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 EffectiveConnectivityConfiguration. +func (e EffectiveConnectivityConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configurationGroups", e.ConfigurationGroups) + populate(objectMap, "id", e.ID) + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveConnectivityConfiguration. +func (e *EffectiveConnectivityConfiguration) UnmarshalJSON(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 "configurationGroups": + err = unpopulate(val, "ConfigurationGroups", &e.ConfigurationGroups) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 EffectiveDefaultSecurityAdminRule. +func (e EffectiveDefaultSecurityAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configurationDescription", e.ConfigurationDescription) + populate(objectMap, "id", e.ID) + objectMap["kind"] = EffectiveAdminRuleKindDefault + populate(objectMap, "properties", e.Properties) + populate(objectMap, "ruleCollectionAppliesToGroups", e.RuleCollectionAppliesToGroups) + populate(objectMap, "ruleCollectionDescription", e.RuleCollectionDescription) + populate(objectMap, "ruleGroups", e.RuleGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveDefaultSecurityAdminRule. +func (e *EffectiveDefaultSecurityAdminRule) UnmarshalJSON(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 "configurationDescription": + err = unpopulate(val, "ConfigurationDescription", &e.ConfigurationDescription) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &e.Kind) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "ruleCollectionAppliesToGroups": + err = unpopulate(val, "RuleCollectionAppliesToGroups", &e.RuleCollectionAppliesToGroups) + delete(rawMsg, key) + case "ruleCollectionDescription": + err = unpopulate(val, "RuleCollectionDescription", &e.RuleCollectionDescription) + delete(rawMsg, key) + case "ruleGroups": + err = unpopulate(val, "RuleGroups", &e.RuleGroups) + 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 EffectiveNetworkSecurityGroup. +func (e EffectiveNetworkSecurityGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "association", e.Association) + populate(objectMap, "effectiveSecurityRules", e.EffectiveSecurityRules) + populate(objectMap, "networkSecurityGroup", e.NetworkSecurityGroup) + populate(objectMap, "tagMap", e.TagMap) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveNetworkSecurityGroup. +func (e *EffectiveNetworkSecurityGroup) UnmarshalJSON(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 "association": + err = unpopulate(val, "Association", &e.Association) + delete(rawMsg, key) + case "effectiveSecurityRules": + err = unpopulate(val, "EffectiveSecurityRules", &e.EffectiveSecurityRules) + delete(rawMsg, key) + case "networkSecurityGroup": + err = unpopulate(val, "NetworkSecurityGroup", &e.NetworkSecurityGroup) + delete(rawMsg, key) + case "tagMap": + err = unpopulate(val, "TagMap", &e.TagMap) + 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 EffectiveNetworkSecurityGroupAssociation. +func (e EffectiveNetworkSecurityGroupAssociation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkInterface", e.NetworkInterface) + populate(objectMap, "networkManager", e.NetworkManager) + populate(objectMap, "subnet", e.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveNetworkSecurityGroupAssociation. +func (e *EffectiveNetworkSecurityGroupAssociation) UnmarshalJSON(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 "networkInterface": + err = unpopulate(val, "NetworkInterface", &e.NetworkInterface) + delete(rawMsg, key) + case "networkManager": + err = unpopulate(val, "NetworkManager", &e.NetworkManager) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &e.Subnet) + 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 EffectiveNetworkSecurityGroupListResult. +func (e EffectiveNetworkSecurityGroupListResult) 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 EffectiveNetworkSecurityGroupListResult. +func (e *EffectiveNetworkSecurityGroupListResult) UnmarshalJSON(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 EffectiveNetworkSecurityRule. +func (e EffectiveNetworkSecurityRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", e.Access) + populate(objectMap, "destinationAddressPrefix", e.DestinationAddressPrefix) + populate(objectMap, "destinationAddressPrefixes", e.DestinationAddressPrefixes) + populate(objectMap, "destinationPortRange", e.DestinationPortRange) + populate(objectMap, "destinationPortRanges", e.DestinationPortRanges) + populate(objectMap, "direction", e.Direction) + populate(objectMap, "expandedDestinationAddressPrefix", e.ExpandedDestinationAddressPrefix) + populate(objectMap, "expandedSourceAddressPrefix", e.ExpandedSourceAddressPrefix) + populate(objectMap, "name", e.Name) + populate(objectMap, "priority", e.Priority) + populate(objectMap, "protocol", e.Protocol) + populate(objectMap, "sourceAddressPrefix", e.SourceAddressPrefix) + populate(objectMap, "sourceAddressPrefixes", e.SourceAddressPrefixes) + populate(objectMap, "sourcePortRange", e.SourcePortRange) + populate(objectMap, "sourcePortRanges", e.SourcePortRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveNetworkSecurityRule. +func (e *EffectiveNetworkSecurityRule) UnmarshalJSON(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 "access": + err = unpopulate(val, "Access", &e.Access) + delete(rawMsg, key) + case "destinationAddressPrefix": + err = unpopulate(val, "DestinationAddressPrefix", &e.DestinationAddressPrefix) + delete(rawMsg, key) + case "destinationAddressPrefixes": + err = unpopulate(val, "DestinationAddressPrefixes", &e.DestinationAddressPrefixes) + delete(rawMsg, key) + case "destinationPortRange": + err = unpopulate(val, "DestinationPortRange", &e.DestinationPortRange) + delete(rawMsg, key) + case "destinationPortRanges": + err = unpopulate(val, "DestinationPortRanges", &e.DestinationPortRanges) + delete(rawMsg, key) + case "direction": + err = unpopulate(val, "Direction", &e.Direction) + delete(rawMsg, key) + case "expandedDestinationAddressPrefix": + err = unpopulate(val, "ExpandedDestinationAddressPrefix", &e.ExpandedDestinationAddressPrefix) + delete(rawMsg, key) + case "expandedSourceAddressPrefix": + err = unpopulate(val, "ExpandedSourceAddressPrefix", &e.ExpandedSourceAddressPrefix) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &e.Priority) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &e.Protocol) + delete(rawMsg, key) + case "sourceAddressPrefix": + err = unpopulate(val, "SourceAddressPrefix", &e.SourceAddressPrefix) + delete(rawMsg, key) + case "sourceAddressPrefixes": + err = unpopulate(val, "SourceAddressPrefixes", &e.SourceAddressPrefixes) + delete(rawMsg, key) + case "sourcePortRange": + err = unpopulate(val, "SourcePortRange", &e.SourcePortRange) + delete(rawMsg, key) + case "sourcePortRanges": + err = unpopulate(val, "SourcePortRanges", &e.SourcePortRanges) + 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 EffectiveRoute. +func (e EffectiveRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", e.AddressPrefix) + populate(objectMap, "disableBgpRoutePropagation", e.DisableBgpRoutePropagation) + populate(objectMap, "name", e.Name) + populate(objectMap, "nextHopIpAddress", e.NextHopIPAddress) + populate(objectMap, "nextHopType", e.NextHopType) + populate(objectMap, "source", e.Source) + populate(objectMap, "state", e.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveRoute. +func (e *EffectiveRoute) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &e.AddressPrefix) + delete(rawMsg, key) + case "disableBgpRoutePropagation": + err = unpopulate(val, "DisableBgpRoutePropagation", &e.DisableBgpRoutePropagation) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "nextHopIpAddress": + err = unpopulate(val, "NextHopIPAddress", &e.NextHopIPAddress) + delete(rawMsg, key) + case "nextHopType": + err = unpopulate(val, "NextHopType", &e.NextHopType) + 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 EffectiveRouteListResult. +func (e EffectiveRouteListResult) 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 EffectiveRouteListResult. +func (e *EffectiveRouteListResult) UnmarshalJSON(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 EffectiveRouteMapRoute. +func (e EffectiveRouteMapRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asPath", e.AsPath) + populate(objectMap, "bgpCommunities", e.BgpCommunities) + populate(objectMap, "prefix", e.Prefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveRouteMapRoute. +func (e *EffectiveRouteMapRoute) UnmarshalJSON(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 "asPath": + err = unpopulate(val, "AsPath", &e.AsPath) + delete(rawMsg, key) + case "bgpCommunities": + err = unpopulate(val, "BgpCommunities", &e.BgpCommunities) + delete(rawMsg, key) + case "prefix": + err = unpopulate(val, "Prefix", &e.Prefix) + 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 EffectiveRouteMapRouteList. +func (e EffectiveRouteMapRouteList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveRouteMapRouteList. +func (e *EffectiveRouteMapRouteList) UnmarshalJSON(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 "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 EffectiveRoutesParameters. +func (e EffectiveRoutesParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceId", e.ResourceID) + populate(objectMap, "virtualWanResourceType", e.VirtualWanResourceType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveRoutesParameters. +func (e *EffectiveRoutesParameters) UnmarshalJSON(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 "resourceId": + err = unpopulate(val, "ResourceID", &e.ResourceID) + delete(rawMsg, key) + case "virtualWanResourceType": + err = unpopulate(val, "VirtualWanResourceType", &e.VirtualWanResourceType) + 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 EffectiveSecurityAdminRule. +func (e EffectiveSecurityAdminRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configurationDescription", e.ConfigurationDescription) + populate(objectMap, "id", e.ID) + objectMap["kind"] = EffectiveAdminRuleKindCustom + populate(objectMap, "properties", e.Properties) + populate(objectMap, "ruleCollectionAppliesToGroups", e.RuleCollectionAppliesToGroups) + populate(objectMap, "ruleCollectionDescription", e.RuleCollectionDescription) + populate(objectMap, "ruleGroups", e.RuleGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EffectiveSecurityAdminRule. +func (e *EffectiveSecurityAdminRule) UnmarshalJSON(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 "configurationDescription": + err = unpopulate(val, "ConfigurationDescription", &e.ConfigurationDescription) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &e.Kind) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "ruleCollectionAppliesToGroups": + err = unpopulate(val, "RuleCollectionAppliesToGroups", &e.RuleCollectionAppliesToGroups) + delete(rawMsg, key) + case "ruleCollectionDescription": + err = unpopulate(val, "RuleCollectionDescription", &e.RuleCollectionDescription) + delete(rawMsg, key) + case "ruleGroups": + err = unpopulate(val, "RuleGroups", &e.RuleGroups) + 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 EndpointServiceResult. +func (e EndpointServiceResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + 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 EndpointServiceResult. +func (e *EndpointServiceResult) UnmarshalJSON(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) + 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 EndpointServicesListResult. +func (e EndpointServicesListResult) 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 EndpointServicesListResult. +func (e *EndpointServicesListResult) UnmarshalJSON(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 Error. +func (e Error) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "innerError", e.InnerError) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Error. +func (e *Error) UnmarshalJSON(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 "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "innerError": + err = unpopulate(val, "InnerError", &e.InnerError) + 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 ErrorDetails. +func (e ErrorDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetails. +func (e *ErrorDetails) UnmarshalJSON(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) + 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 EvaluatedNetworkSecurityGroup. +func (e EvaluatedNetworkSecurityGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedTo", e.AppliedTo) + populate(objectMap, "matchedRule", e.MatchedRule) + populate(objectMap, "networkSecurityGroupId", e.NetworkSecurityGroupID) + populate(objectMap, "rulesEvaluationResult", e.RulesEvaluationResult) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EvaluatedNetworkSecurityGroup. +func (e *EvaluatedNetworkSecurityGroup) UnmarshalJSON(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 "appliedTo": + err = unpopulate(val, "AppliedTo", &e.AppliedTo) + delete(rawMsg, key) + case "matchedRule": + err = unpopulate(val, "MatchedRule", &e.MatchedRule) + delete(rawMsg, key) + case "networkSecurityGroupId": + err = unpopulate(val, "NetworkSecurityGroupID", &e.NetworkSecurityGroupID) + delete(rawMsg, key) + case "rulesEvaluationResult": + err = unpopulate(val, "RulesEvaluationResult", &e.RulesEvaluationResult) + 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 ExclusionManagedRule. +func (e ExclusionManagedRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleId", e.RuleID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExclusionManagedRule. +func (e *ExclusionManagedRule) UnmarshalJSON(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 "ruleId": + err = unpopulate(val, "RuleID", &e.RuleID) + 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 ExclusionManagedRuleGroup. +func (e ExclusionManagedRuleGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleGroupName", e.RuleGroupName) + populate(objectMap, "rules", e.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExclusionManagedRuleGroup. +func (e *ExclusionManagedRuleGroup) UnmarshalJSON(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 "ruleGroupName": + err = unpopulate(val, "RuleGroupName", &e.RuleGroupName) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &e.Rules) + 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 ExclusionManagedRuleSet. +func (e ExclusionManagedRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleGroups", e.RuleGroups) + populate(objectMap, "ruleSetType", e.RuleSetType) + populate(objectMap, "ruleSetVersion", e.RuleSetVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExclusionManagedRuleSet. +func (e *ExclusionManagedRuleSet) UnmarshalJSON(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 "ruleGroups": + err = unpopulate(val, "RuleGroups", &e.RuleGroups) + delete(rawMsg, key) + case "ruleSetType": + err = unpopulate(val, "RuleSetType", &e.RuleSetType) + delete(rawMsg, key) + case "ruleSetVersion": + err = unpopulate(val, "RuleSetVersion", &e.RuleSetVersion) + 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 ExplicitProxySettings. +func (e ExplicitProxySettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enableExplicitProxy", e.EnableExplicitProxy) + populate(objectMap, "enablePacFile", e.EnablePacFile) + populate(objectMap, "httpPort", e.HTTPPort) + populate(objectMap, "httpsPort", e.HTTPSPort) + populate(objectMap, "pacFile", e.PacFile) + populate(objectMap, "pacFilePort", e.PacFilePort) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExplicitProxySettings. +func (e *ExplicitProxySettings) UnmarshalJSON(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 "enableExplicitProxy": + err = unpopulate(val, "EnableExplicitProxy", &e.EnableExplicitProxy) + delete(rawMsg, key) + case "enablePacFile": + err = unpopulate(val, "EnablePacFile", &e.EnablePacFile) + delete(rawMsg, key) + case "httpPort": + err = unpopulate(val, "HTTPPort", &e.HTTPPort) + delete(rawMsg, key) + case "httpsPort": + err = unpopulate(val, "HTTPSPort", &e.HTTPSPort) + delete(rawMsg, key) + case "pacFile": + err = unpopulate(val, "PacFile", &e.PacFile) + delete(rawMsg, key) + case "pacFilePort": + err = unpopulate(val, "PacFilePort", &e.PacFilePort) + 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 ExpressRouteCircuit. +func (e ExpressRouteCircuit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "sku", e.SKU) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuit. +func (e *ExpressRouteCircuit) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &e.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 ExpressRouteCircuitArpTable. +func (e ExpressRouteCircuitArpTable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "age", e.Age) + populate(objectMap, "ipAddress", e.IPAddress) + populate(objectMap, "interface", e.Interface) + populate(objectMap, "macAddress", e.MacAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitArpTable. +func (e *ExpressRouteCircuitArpTable) UnmarshalJSON(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 "age": + err = unpopulate(val, "Age", &e.Age) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &e.IPAddress) + delete(rawMsg, key) + case "interface": + err = unpopulate(val, "Interface", &e.Interface) + delete(rawMsg, key) + case "macAddress": + err = unpopulate(val, "MacAddress", &e.MacAddress) + 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 ExpressRouteCircuitAuthorization. +func (e ExpressRouteCircuitAuthorization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitAuthorization. +func (e *ExpressRouteCircuitAuthorization) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + 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 "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 ExpressRouteCircuitConnection. +func (e ExpressRouteCircuitConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitConnection. +func (e *ExpressRouteCircuitConnection) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + 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 "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 ExpressRouteCircuitConnectionListResult. +func (e ExpressRouteCircuitConnectionListResult) 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 ExpressRouteCircuitConnectionListResult. +func (e *ExpressRouteCircuitConnectionListResult) UnmarshalJSON(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 ExpressRouteCircuitConnectionPropertiesFormat. +func (e ExpressRouteCircuitConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", e.AddressPrefix) + populate(objectMap, "authorizationKey", e.AuthorizationKey) + populate(objectMap, "circuitConnectionStatus", e.CircuitConnectionStatus) + populate(objectMap, "expressRouteCircuitPeering", e.ExpressRouteCircuitPeering) + populate(objectMap, "ipv6CircuitConnectionConfig", e.IPv6CircuitConnectionConfig) + populate(objectMap, "peerExpressRouteCircuitPeering", e.PeerExpressRouteCircuitPeering) + populate(objectMap, "provisioningState", e.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitConnectionPropertiesFormat. +func (e *ExpressRouteCircuitConnectionPropertiesFormat) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &e.AddressPrefix) + delete(rawMsg, key) + case "authorizationKey": + err = unpopulate(val, "AuthorizationKey", &e.AuthorizationKey) + delete(rawMsg, key) + case "circuitConnectionStatus": + err = unpopulate(val, "CircuitConnectionStatus", &e.CircuitConnectionStatus) + delete(rawMsg, key) + case "expressRouteCircuitPeering": + err = unpopulate(val, "ExpressRouteCircuitPeering", &e.ExpressRouteCircuitPeering) + delete(rawMsg, key) + case "ipv6CircuitConnectionConfig": + err = unpopulate(val, "IPv6CircuitConnectionConfig", &e.IPv6CircuitConnectionConfig) + delete(rawMsg, key) + case "peerExpressRouteCircuitPeering": + err = unpopulate(val, "PeerExpressRouteCircuitPeering", &e.PeerExpressRouteCircuitPeering) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + 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 ExpressRouteCircuitListResult. +func (e ExpressRouteCircuitListResult) 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 ExpressRouteCircuitListResult. +func (e *ExpressRouteCircuitListResult) UnmarshalJSON(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 ExpressRouteCircuitPeering. +func (e ExpressRouteCircuitPeering) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitPeering. +func (e *ExpressRouteCircuitPeering) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + 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 "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 ExpressRouteCircuitPeeringConfig. +func (e ExpressRouteCircuitPeeringConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "advertisedCommunities", e.AdvertisedCommunities) + populate(objectMap, "advertisedPublicPrefixes", e.AdvertisedPublicPrefixes) + populate(objectMap, "advertisedPublicPrefixesState", e.AdvertisedPublicPrefixesState) + populate(objectMap, "customerASN", e.CustomerASN) + populate(objectMap, "legacyMode", e.LegacyMode) + populate(objectMap, "routingRegistryName", e.RoutingRegistryName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitPeeringConfig. +func (e *ExpressRouteCircuitPeeringConfig) UnmarshalJSON(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 "advertisedCommunities": + err = unpopulate(val, "AdvertisedCommunities", &e.AdvertisedCommunities) + delete(rawMsg, key) + case "advertisedPublicPrefixes": + err = unpopulate(val, "AdvertisedPublicPrefixes", &e.AdvertisedPublicPrefixes) + delete(rawMsg, key) + case "advertisedPublicPrefixesState": + err = unpopulate(val, "AdvertisedPublicPrefixesState", &e.AdvertisedPublicPrefixesState) + delete(rawMsg, key) + case "customerASN": + err = unpopulate(val, "CustomerASN", &e.CustomerASN) + delete(rawMsg, key) + case "legacyMode": + err = unpopulate(val, "LegacyMode", &e.LegacyMode) + delete(rawMsg, key) + case "routingRegistryName": + err = unpopulate(val, "RoutingRegistryName", &e.RoutingRegistryName) + 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 ExpressRouteCircuitPeeringID. +func (e ExpressRouteCircuitPeeringID) 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 ExpressRouteCircuitPeeringID. +func (e *ExpressRouteCircuitPeeringID) UnmarshalJSON(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 ExpressRouteCircuitPeeringListResult. +func (e ExpressRouteCircuitPeeringListResult) 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 ExpressRouteCircuitPeeringListResult. +func (e *ExpressRouteCircuitPeeringListResult) UnmarshalJSON(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 ExpressRouteCircuitPeeringPropertiesFormat. +func (e ExpressRouteCircuitPeeringPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureASN", e.AzureASN) + populate(objectMap, "connections", e.Connections) + populate(objectMap, "expressRouteConnection", e.ExpressRouteConnection) + populate(objectMap, "gatewayManagerEtag", e.GatewayManagerEtag) + populate(objectMap, "ipv6PeeringConfig", e.IPv6PeeringConfig) + populate(objectMap, "lastModifiedBy", e.LastModifiedBy) + populate(objectMap, "microsoftPeeringConfig", e.MicrosoftPeeringConfig) + populate(objectMap, "peerASN", e.PeerASN) + populate(objectMap, "peeredConnections", e.PeeredConnections) + populate(objectMap, "peeringType", e.PeeringType) + populate(objectMap, "primaryAzurePort", e.PrimaryAzurePort) + populate(objectMap, "primaryPeerAddressPrefix", e.PrimaryPeerAddressPrefix) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "routeFilter", e.RouteFilter) + populate(objectMap, "secondaryAzurePort", e.SecondaryAzurePort) + populate(objectMap, "secondaryPeerAddressPrefix", e.SecondaryPeerAddressPrefix) + populate(objectMap, "sharedKey", e.SharedKey) + populate(objectMap, "state", e.State) + populate(objectMap, "stats", e.Stats) + populate(objectMap, "vlanId", e.VlanID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitPeeringPropertiesFormat. +func (e *ExpressRouteCircuitPeeringPropertiesFormat) UnmarshalJSON(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 "azureASN": + err = unpopulate(val, "AzureASN", &e.AzureASN) + delete(rawMsg, key) + case "connections": + err = unpopulate(val, "Connections", &e.Connections) + delete(rawMsg, key) + case "expressRouteConnection": + err = unpopulate(val, "ExpressRouteConnection", &e.ExpressRouteConnection) + delete(rawMsg, key) + case "gatewayManagerEtag": + err = unpopulate(val, "GatewayManagerEtag", &e.GatewayManagerEtag) + delete(rawMsg, key) + case "ipv6PeeringConfig": + err = unpopulate(val, "IPv6PeeringConfig", &e.IPv6PeeringConfig) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &e.LastModifiedBy) + delete(rawMsg, key) + case "microsoftPeeringConfig": + err = unpopulate(val, "MicrosoftPeeringConfig", &e.MicrosoftPeeringConfig) + delete(rawMsg, key) + case "peerASN": + err = unpopulate(val, "PeerASN", &e.PeerASN) + delete(rawMsg, key) + case "peeredConnections": + err = unpopulate(val, "PeeredConnections", &e.PeeredConnections) + delete(rawMsg, key) + case "peeringType": + err = unpopulate(val, "PeeringType", &e.PeeringType) + delete(rawMsg, key) + case "primaryAzurePort": + err = unpopulate(val, "PrimaryAzurePort", &e.PrimaryAzurePort) + delete(rawMsg, key) + case "primaryPeerAddressPrefix": + err = unpopulate(val, "PrimaryPeerAddressPrefix", &e.PrimaryPeerAddressPrefix) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "routeFilter": + err = unpopulate(val, "RouteFilter", &e.RouteFilter) + delete(rawMsg, key) + case "secondaryAzurePort": + err = unpopulate(val, "SecondaryAzurePort", &e.SecondaryAzurePort) + delete(rawMsg, key) + case "secondaryPeerAddressPrefix": + err = unpopulate(val, "SecondaryPeerAddressPrefix", &e.SecondaryPeerAddressPrefix) + delete(rawMsg, key) + case "sharedKey": + err = unpopulate(val, "SharedKey", &e.SharedKey) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &e.State) + delete(rawMsg, key) + case "stats": + err = unpopulate(val, "Stats", &e.Stats) + delete(rawMsg, key) + case "vlanId": + err = unpopulate(val, "VlanID", &e.VlanID) + 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 ExpressRouteCircuitPropertiesFormat. +func (e ExpressRouteCircuitPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowClassicOperations", e.AllowClassicOperations) + populate(objectMap, "authorizationKey", e.AuthorizationKey) + populate(objectMap, "authorizationStatus", e.AuthorizationStatus) + populate(objectMap, "authorizations", e.Authorizations) + populate(objectMap, "bandwidthInGbps", e.BandwidthInGbps) + populate(objectMap, "circuitProvisioningState", e.CircuitProvisioningState) + populate(objectMap, "expressRoutePort", e.ExpressRoutePort) + populate(objectMap, "gatewayManagerEtag", e.GatewayManagerEtag) + populate(objectMap, "globalReachEnabled", e.GlobalReachEnabled) + populate(objectMap, "peerings", e.Peerings) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "serviceKey", e.ServiceKey) + populate(objectMap, "serviceProviderNotes", e.ServiceProviderNotes) + populate(objectMap, "serviceProviderProperties", e.ServiceProviderProperties) + populate(objectMap, "serviceProviderProvisioningState", e.ServiceProviderProvisioningState) + populate(objectMap, "stag", e.Stag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitPropertiesFormat. +func (e *ExpressRouteCircuitPropertiesFormat) UnmarshalJSON(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 "allowClassicOperations": + err = unpopulate(val, "AllowClassicOperations", &e.AllowClassicOperations) + delete(rawMsg, key) + case "authorizationKey": + err = unpopulate(val, "AuthorizationKey", &e.AuthorizationKey) + delete(rawMsg, key) + case "authorizationStatus": + err = unpopulate(val, "AuthorizationStatus", &e.AuthorizationStatus) + delete(rawMsg, key) + case "authorizations": + err = unpopulate(val, "Authorizations", &e.Authorizations) + delete(rawMsg, key) + case "bandwidthInGbps": + err = unpopulate(val, "BandwidthInGbps", &e.BandwidthInGbps) + delete(rawMsg, key) + case "circuitProvisioningState": + err = unpopulate(val, "CircuitProvisioningState", &e.CircuitProvisioningState) + delete(rawMsg, key) + case "expressRoutePort": + err = unpopulate(val, "ExpressRoutePort", &e.ExpressRoutePort) + delete(rawMsg, key) + case "gatewayManagerEtag": + err = unpopulate(val, "GatewayManagerEtag", &e.GatewayManagerEtag) + delete(rawMsg, key) + case "globalReachEnabled": + err = unpopulate(val, "GlobalReachEnabled", &e.GlobalReachEnabled) + delete(rawMsg, key) + case "peerings": + err = unpopulate(val, "Peerings", &e.Peerings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "serviceKey": + err = unpopulate(val, "ServiceKey", &e.ServiceKey) + delete(rawMsg, key) + case "serviceProviderNotes": + err = unpopulate(val, "ServiceProviderNotes", &e.ServiceProviderNotes) + delete(rawMsg, key) + case "serviceProviderProperties": + err = unpopulate(val, "ServiceProviderProperties", &e.ServiceProviderProperties) + delete(rawMsg, key) + case "serviceProviderProvisioningState": + err = unpopulate(val, "ServiceProviderProvisioningState", &e.ServiceProviderProvisioningState) + delete(rawMsg, key) + case "stag": + err = unpopulate(val, "Stag", &e.Stag) + 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 ExpressRouteCircuitReference. +func (e ExpressRouteCircuitReference) 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 ExpressRouteCircuitReference. +func (e *ExpressRouteCircuitReference) UnmarshalJSON(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 ExpressRouteCircuitRoutesTable. +func (e ExpressRouteCircuitRoutesTable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "locPrf", e.LocPrf) + populate(objectMap, "network", e.Network) + populate(objectMap, "nextHop", e.NextHop) + populate(objectMap, "path", e.Path) + populate(objectMap, "weight", e.Weight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitRoutesTable. +func (e *ExpressRouteCircuitRoutesTable) UnmarshalJSON(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 "locPrf": + err = unpopulate(val, "LocPrf", &e.LocPrf) + delete(rawMsg, key) + case "network": + err = unpopulate(val, "Network", &e.Network) + delete(rawMsg, key) + case "nextHop": + err = unpopulate(val, "NextHop", &e.NextHop) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &e.Path) + delete(rawMsg, key) + case "weight": + err = unpopulate(val, "Weight", &e.Weight) + 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 ExpressRouteCircuitRoutesTableSummary. +func (e ExpressRouteCircuitRoutesTableSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "as", e.As) + populate(objectMap, "neighbor", e.Neighbor) + populate(objectMap, "statePfxRcd", e.StatePfxRcd) + populate(objectMap, "upDown", e.UpDown) + populate(objectMap, "v", e.V) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitRoutesTableSummary. +func (e *ExpressRouteCircuitRoutesTableSummary) UnmarshalJSON(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 "as": + err = unpopulate(val, "As", &e.As) + delete(rawMsg, key) + case "neighbor": + err = unpopulate(val, "Neighbor", &e.Neighbor) + delete(rawMsg, key) + case "statePfxRcd": + err = unpopulate(val, "StatePfxRcd", &e.StatePfxRcd) + delete(rawMsg, key) + case "upDown": + err = unpopulate(val, "UpDown", &e.UpDown) + delete(rawMsg, key) + case "v": + err = unpopulate(val, "V", &e.V) + 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 ExpressRouteCircuitSKU. +func (e ExpressRouteCircuitSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "family", e.Family) + populate(objectMap, "name", e.Name) + populate(objectMap, "tier", e.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitSKU. +func (e *ExpressRouteCircuitSKU) UnmarshalJSON(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 "family": + err = unpopulate(val, "Family", &e.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &e.Tier) + 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 ExpressRouteCircuitServiceProviderProperties. +func (e ExpressRouteCircuitServiceProviderProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bandwidthInMbps", e.BandwidthInMbps) + populate(objectMap, "peeringLocation", e.PeeringLocation) + populate(objectMap, "serviceProviderName", e.ServiceProviderName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitServiceProviderProperties. +func (e *ExpressRouteCircuitServiceProviderProperties) UnmarshalJSON(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 "bandwidthInMbps": + err = unpopulate(val, "BandwidthInMbps", &e.BandwidthInMbps) + delete(rawMsg, key) + case "peeringLocation": + err = unpopulate(val, "PeeringLocation", &e.PeeringLocation) + delete(rawMsg, key) + case "serviceProviderName": + err = unpopulate(val, "ServiceProviderName", &e.ServiceProviderName) + 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 ExpressRouteCircuitStats. +func (e ExpressRouteCircuitStats) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "primarybytesIn", e.PrimarybytesIn) + populate(objectMap, "primarybytesOut", e.PrimarybytesOut) + populate(objectMap, "secondarybytesIn", e.SecondarybytesIn) + populate(objectMap, "secondarybytesOut", e.SecondarybytesOut) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCircuitStats. +func (e *ExpressRouteCircuitStats) UnmarshalJSON(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 "primarybytesIn": + err = unpopulate(val, "PrimarybytesIn", &e.PrimarybytesIn) + delete(rawMsg, key) + case "primarybytesOut": + err = unpopulate(val, "PrimarybytesOut", &e.PrimarybytesOut) + delete(rawMsg, key) + case "secondarybytesIn": + err = unpopulate(val, "SecondarybytesIn", &e.SecondarybytesIn) + delete(rawMsg, key) + case "secondarybytesOut": + err = unpopulate(val, "SecondarybytesOut", &e.SecondarybytesOut) + 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 ExpressRouteCircuitsArpTableListResult. +func (e ExpressRouteCircuitsArpTableListResult) 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 ExpressRouteCircuitsArpTableListResult. +func (e *ExpressRouteCircuitsArpTableListResult) UnmarshalJSON(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 ExpressRouteCircuitsRoutesTableListResult. +func (e ExpressRouteCircuitsRoutesTableListResult) 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 ExpressRouteCircuitsRoutesTableListResult. +func (e *ExpressRouteCircuitsRoutesTableListResult) UnmarshalJSON(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 ExpressRouteCircuitsRoutesTableSummaryListResult. +func (e ExpressRouteCircuitsRoutesTableSummaryListResult) 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 ExpressRouteCircuitsRoutesTableSummaryListResult. +func (e *ExpressRouteCircuitsRoutesTableSummaryListResult) UnmarshalJSON(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 ExpressRouteConnection. +func (e ExpressRouteConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteConnection. +func (e *ExpressRouteConnection) UnmarshalJSON(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) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 ExpressRouteConnectionID. +func (e ExpressRouteConnectionID) 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 ExpressRouteConnectionID. +func (e *ExpressRouteConnectionID) UnmarshalJSON(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 ExpressRouteConnectionList. +func (e ExpressRouteConnectionList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteConnectionList. +func (e *ExpressRouteConnectionList) UnmarshalJSON(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 "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 ExpressRouteConnectionProperties. +func (e ExpressRouteConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authorizationKey", e.AuthorizationKey) + populate(objectMap, "enableInternetSecurity", e.EnableInternetSecurity) + populate(objectMap, "enablePrivateLinkFastPath", e.EnablePrivateLinkFastPath) + populate(objectMap, "expressRouteCircuitPeering", e.ExpressRouteCircuitPeering) + populate(objectMap, "expressRouteGatewayBypass", e.ExpressRouteGatewayBypass) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "routingConfiguration", e.RoutingConfiguration) + populate(objectMap, "routingWeight", e.RoutingWeight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteConnectionProperties. +func (e *ExpressRouteConnectionProperties) UnmarshalJSON(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 "authorizationKey": + err = unpopulate(val, "AuthorizationKey", &e.AuthorizationKey) + delete(rawMsg, key) + case "enableInternetSecurity": + err = unpopulate(val, "EnableInternetSecurity", &e.EnableInternetSecurity) + delete(rawMsg, key) + case "enablePrivateLinkFastPath": + err = unpopulate(val, "EnablePrivateLinkFastPath", &e.EnablePrivateLinkFastPath) + delete(rawMsg, key) + case "expressRouteCircuitPeering": + err = unpopulate(val, "ExpressRouteCircuitPeering", &e.ExpressRouteCircuitPeering) + delete(rawMsg, key) + case "expressRouteGatewayBypass": + err = unpopulate(val, "ExpressRouteGatewayBypass", &e.ExpressRouteGatewayBypass) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "routingConfiguration": + err = unpopulate(val, "RoutingConfiguration", &e.RoutingConfiguration) + delete(rawMsg, key) + case "routingWeight": + err = unpopulate(val, "RoutingWeight", &e.RoutingWeight) + 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 ExpressRouteCrossConnection. +func (e ExpressRouteCrossConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCrossConnection. +func (e *ExpressRouteCrossConnection) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 ExpressRouteCrossConnectionListResult. +func (e ExpressRouteCrossConnectionListResult) 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 ExpressRouteCrossConnectionListResult. +func (e *ExpressRouteCrossConnectionListResult) UnmarshalJSON(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 ExpressRouteCrossConnectionPeering. +func (e ExpressRouteCrossConnectionPeering) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCrossConnectionPeering. +func (e *ExpressRouteCrossConnectionPeering) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + 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 "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 ExpressRouteCrossConnectionPeeringList. +func (e ExpressRouteCrossConnectionPeeringList) 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 ExpressRouteCrossConnectionPeeringList. +func (e *ExpressRouteCrossConnectionPeeringList) UnmarshalJSON(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 ExpressRouteCrossConnectionPeeringProperties. +func (e ExpressRouteCrossConnectionPeeringProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureASN", e.AzureASN) + populate(objectMap, "gatewayManagerEtag", e.GatewayManagerEtag) + populate(objectMap, "ipv6PeeringConfig", e.IPv6PeeringConfig) + populate(objectMap, "lastModifiedBy", e.LastModifiedBy) + populate(objectMap, "microsoftPeeringConfig", e.MicrosoftPeeringConfig) + populate(objectMap, "peerASN", e.PeerASN) + populate(objectMap, "peeringType", e.PeeringType) + populate(objectMap, "primaryAzurePort", e.PrimaryAzurePort) + populate(objectMap, "primaryPeerAddressPrefix", e.PrimaryPeerAddressPrefix) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "secondaryAzurePort", e.SecondaryAzurePort) + populate(objectMap, "secondaryPeerAddressPrefix", e.SecondaryPeerAddressPrefix) + populate(objectMap, "sharedKey", e.SharedKey) + populate(objectMap, "state", e.State) + populate(objectMap, "vlanId", e.VlanID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCrossConnectionPeeringProperties. +func (e *ExpressRouteCrossConnectionPeeringProperties) UnmarshalJSON(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 "azureASN": + err = unpopulate(val, "AzureASN", &e.AzureASN) + delete(rawMsg, key) + case "gatewayManagerEtag": + err = unpopulate(val, "GatewayManagerEtag", &e.GatewayManagerEtag) + delete(rawMsg, key) + case "ipv6PeeringConfig": + err = unpopulate(val, "IPv6PeeringConfig", &e.IPv6PeeringConfig) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &e.LastModifiedBy) + delete(rawMsg, key) + case "microsoftPeeringConfig": + err = unpopulate(val, "MicrosoftPeeringConfig", &e.MicrosoftPeeringConfig) + delete(rawMsg, key) + case "peerASN": + err = unpopulate(val, "PeerASN", &e.PeerASN) + delete(rawMsg, key) + case "peeringType": + err = unpopulate(val, "PeeringType", &e.PeeringType) + delete(rawMsg, key) + case "primaryAzurePort": + err = unpopulate(val, "PrimaryAzurePort", &e.PrimaryAzurePort) + delete(rawMsg, key) + case "primaryPeerAddressPrefix": + err = unpopulate(val, "PrimaryPeerAddressPrefix", &e.PrimaryPeerAddressPrefix) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "secondaryAzurePort": + err = unpopulate(val, "SecondaryAzurePort", &e.SecondaryAzurePort) + delete(rawMsg, key) + case "secondaryPeerAddressPrefix": + err = unpopulate(val, "SecondaryPeerAddressPrefix", &e.SecondaryPeerAddressPrefix) + delete(rawMsg, key) + case "sharedKey": + err = unpopulate(val, "SharedKey", &e.SharedKey) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &e.State) + delete(rawMsg, key) + case "vlanId": + err = unpopulate(val, "VlanID", &e.VlanID) + 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 ExpressRouteCrossConnectionProperties. +func (e ExpressRouteCrossConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bandwidthInMbps", e.BandwidthInMbps) + populate(objectMap, "expressRouteCircuit", e.ExpressRouteCircuit) + populate(objectMap, "peeringLocation", e.PeeringLocation) + populate(objectMap, "peerings", e.Peerings) + populate(objectMap, "primaryAzurePort", e.PrimaryAzurePort) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "sTag", e.STag) + populate(objectMap, "secondaryAzurePort", e.SecondaryAzurePort) + populate(objectMap, "serviceProviderNotes", e.ServiceProviderNotes) + populate(objectMap, "serviceProviderProvisioningState", e.ServiceProviderProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCrossConnectionProperties. +func (e *ExpressRouteCrossConnectionProperties) UnmarshalJSON(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 "bandwidthInMbps": + err = unpopulate(val, "BandwidthInMbps", &e.BandwidthInMbps) + delete(rawMsg, key) + case "expressRouteCircuit": + err = unpopulate(val, "ExpressRouteCircuit", &e.ExpressRouteCircuit) + delete(rawMsg, key) + case "peeringLocation": + err = unpopulate(val, "PeeringLocation", &e.PeeringLocation) + delete(rawMsg, key) + case "peerings": + err = unpopulate(val, "Peerings", &e.Peerings) + delete(rawMsg, key) + case "primaryAzurePort": + err = unpopulate(val, "PrimaryAzurePort", &e.PrimaryAzurePort) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "sTag": + err = unpopulate(val, "STag", &e.STag) + delete(rawMsg, key) + case "secondaryAzurePort": + err = unpopulate(val, "SecondaryAzurePort", &e.SecondaryAzurePort) + delete(rawMsg, key) + case "serviceProviderNotes": + err = unpopulate(val, "ServiceProviderNotes", &e.ServiceProviderNotes) + delete(rawMsg, key) + case "serviceProviderProvisioningState": + err = unpopulate(val, "ServiceProviderProvisioningState", &e.ServiceProviderProvisioningState) + 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 ExpressRouteCrossConnectionRoutesTableSummary. +func (e ExpressRouteCrossConnectionRoutesTableSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asn", e.Asn) + populate(objectMap, "neighbor", e.Neighbor) + populate(objectMap, "stateOrPrefixesReceived", e.StateOrPrefixesReceived) + populate(objectMap, "upDown", e.UpDown) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteCrossConnectionRoutesTableSummary. +func (e *ExpressRouteCrossConnectionRoutesTableSummary) UnmarshalJSON(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 "asn": + err = unpopulate(val, "Asn", &e.Asn) + delete(rawMsg, key) + case "neighbor": + err = unpopulate(val, "Neighbor", &e.Neighbor) + delete(rawMsg, key) + case "stateOrPrefixesReceived": + err = unpopulate(val, "StateOrPrefixesReceived", &e.StateOrPrefixesReceived) + delete(rawMsg, key) + case "upDown": + err = unpopulate(val, "UpDown", &e.UpDown) + 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 ExpressRouteCrossConnectionsRoutesTableSummaryListResult. +func (e ExpressRouteCrossConnectionsRoutesTableSummaryListResult) 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 ExpressRouteCrossConnectionsRoutesTableSummaryListResult. +func (e *ExpressRouteCrossConnectionsRoutesTableSummaryListResult) UnmarshalJSON(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 ExpressRouteGateway. +func (e ExpressRouteGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteGateway. +func (e *ExpressRouteGateway) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 ExpressRouteGatewayList. +func (e ExpressRouteGatewayList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteGatewayList. +func (e *ExpressRouteGatewayList) UnmarshalJSON(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 "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 ExpressRouteGatewayProperties. +func (e ExpressRouteGatewayProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowNonVirtualWanTraffic", e.AllowNonVirtualWanTraffic) + populate(objectMap, "autoScaleConfiguration", e.AutoScaleConfiguration) + populate(objectMap, "expressRouteConnections", e.ExpressRouteConnections) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "virtualHub", e.VirtualHub) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteGatewayProperties. +func (e *ExpressRouteGatewayProperties) UnmarshalJSON(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 "allowNonVirtualWanTraffic": + err = unpopulate(val, "AllowNonVirtualWanTraffic", &e.AllowNonVirtualWanTraffic) + delete(rawMsg, key) + case "autoScaleConfiguration": + err = unpopulate(val, "AutoScaleConfiguration", &e.AutoScaleConfiguration) + delete(rawMsg, key) + case "expressRouteConnections": + err = unpopulate(val, "ExpressRouteConnections", &e.ExpressRouteConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "virtualHub": + err = unpopulate(val, "VirtualHub", &e.VirtualHub) + 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 ExpressRouteGatewayPropertiesAutoScaleConfiguration. +func (e ExpressRouteGatewayPropertiesAutoScaleConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bounds", e.Bounds) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteGatewayPropertiesAutoScaleConfiguration. +func (e *ExpressRouteGatewayPropertiesAutoScaleConfiguration) UnmarshalJSON(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 "bounds": + err = unpopulate(val, "Bounds", &e.Bounds) + 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 ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds. +func (e ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "max", e.Max) + populate(objectMap, "min", e.Min) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds. +func (e *ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds) UnmarshalJSON(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 "max": + err = unpopulate(val, "Max", &e.Max) + delete(rawMsg, key) + case "min": + err = unpopulate(val, "Min", &e.Min) + 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 ExpressRouteLink. +func (e ExpressRouteLink) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteLink. +func (e *ExpressRouteLink) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + 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 "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 ExpressRouteLinkListResult. +func (e ExpressRouteLinkListResult) 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 ExpressRouteLinkListResult. +func (e *ExpressRouteLinkListResult) UnmarshalJSON(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 ExpressRouteLinkMacSecConfig. +func (e ExpressRouteLinkMacSecConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cakSecretIdentifier", e.CakSecretIdentifier) + populate(objectMap, "cipher", e.Cipher) + populate(objectMap, "cknSecretIdentifier", e.CknSecretIdentifier) + populate(objectMap, "sciState", e.SciState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteLinkMacSecConfig. +func (e *ExpressRouteLinkMacSecConfig) UnmarshalJSON(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 "cakSecretIdentifier": + err = unpopulate(val, "CakSecretIdentifier", &e.CakSecretIdentifier) + delete(rawMsg, key) + case "cipher": + err = unpopulate(val, "Cipher", &e.Cipher) + delete(rawMsg, key) + case "cknSecretIdentifier": + err = unpopulate(val, "CknSecretIdentifier", &e.CknSecretIdentifier) + delete(rawMsg, key) + case "sciState": + err = unpopulate(val, "SciState", &e.SciState) + 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 ExpressRouteLinkPropertiesFormat. +func (e ExpressRouteLinkPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminState", e.AdminState) + populate(objectMap, "coloLocation", e.ColoLocation) + populate(objectMap, "connectorType", e.ConnectorType) + populate(objectMap, "interfaceName", e.InterfaceName) + populate(objectMap, "macSecConfig", e.MacSecConfig) + populate(objectMap, "patchPanelId", e.PatchPanelID) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "rackId", e.RackID) + populate(objectMap, "routerName", e.RouterName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteLinkPropertiesFormat. +func (e *ExpressRouteLinkPropertiesFormat) UnmarshalJSON(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 "adminState": + err = unpopulate(val, "AdminState", &e.AdminState) + delete(rawMsg, key) + case "coloLocation": + err = unpopulate(val, "ColoLocation", &e.ColoLocation) + delete(rawMsg, key) + case "connectorType": + err = unpopulate(val, "ConnectorType", &e.ConnectorType) + delete(rawMsg, key) + case "interfaceName": + err = unpopulate(val, "InterfaceName", &e.InterfaceName) + delete(rawMsg, key) + case "macSecConfig": + err = unpopulate(val, "MacSecConfig", &e.MacSecConfig) + delete(rawMsg, key) + case "patchPanelId": + err = unpopulate(val, "PatchPanelID", &e.PatchPanelID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "rackId": + err = unpopulate(val, "RackID", &e.RackID) + delete(rawMsg, key) + case "routerName": + err = unpopulate(val, "RouterName", &e.RouterName) + 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 ExpressRoutePort. +func (e ExpressRoutePort) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "identity", e.Identity) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRoutePort. +func (e *ExpressRoutePort) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &e.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 ExpressRoutePortAuthorization. +func (e ExpressRoutePortAuthorization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRoutePortAuthorization. +func (e *ExpressRoutePortAuthorization) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + 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 "properties": + err = unpopulate(val, "Properties", &e.Properties) + 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 ExpressRoutePortAuthorizationListResult. +func (e ExpressRoutePortAuthorizationListResult) 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 ExpressRoutePortAuthorizationListResult. +func (e *ExpressRoutePortAuthorizationListResult) UnmarshalJSON(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 ExpressRoutePortAuthorizationPropertiesFormat. +func (e ExpressRoutePortAuthorizationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authorizationKey", e.AuthorizationKey) + populate(objectMap, "authorizationUseStatus", e.AuthorizationUseStatus) + populate(objectMap, "circuitResourceUri", e.CircuitResourceURI) + populate(objectMap, "provisioningState", e.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRoutePortAuthorizationPropertiesFormat. +func (e *ExpressRoutePortAuthorizationPropertiesFormat) UnmarshalJSON(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 "authorizationKey": + err = unpopulate(val, "AuthorizationKey", &e.AuthorizationKey) + delete(rawMsg, key) + case "authorizationUseStatus": + err = unpopulate(val, "AuthorizationUseStatus", &e.AuthorizationUseStatus) + delete(rawMsg, key) + case "circuitResourceUri": + err = unpopulate(val, "CircuitResourceURI", &e.CircuitResourceURI) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + 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 ExpressRoutePortListResult. +func (e ExpressRoutePortListResult) 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 ExpressRoutePortListResult. +func (e *ExpressRoutePortListResult) UnmarshalJSON(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 ExpressRoutePortPropertiesFormat. +func (e ExpressRoutePortPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocationDate", e.AllocationDate) + populate(objectMap, "bandwidthInGbps", e.BandwidthInGbps) + populate(objectMap, "billingType", e.BillingType) + populate(objectMap, "circuits", e.Circuits) + populate(objectMap, "encapsulation", e.Encapsulation) + populate(objectMap, "etherType", e.EtherType) + populate(objectMap, "links", e.Links) + populate(objectMap, "mtu", e.Mtu) + populate(objectMap, "peeringLocation", e.PeeringLocation) + populate(objectMap, "provisionedBandwidthInGbps", e.ProvisionedBandwidthInGbps) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "resourceGuid", e.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRoutePortPropertiesFormat. +func (e *ExpressRoutePortPropertiesFormat) UnmarshalJSON(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 "allocationDate": + err = unpopulate(val, "AllocationDate", &e.AllocationDate) + delete(rawMsg, key) + case "bandwidthInGbps": + err = unpopulate(val, "BandwidthInGbps", &e.BandwidthInGbps) + delete(rawMsg, key) + case "billingType": + err = unpopulate(val, "BillingType", &e.BillingType) + delete(rawMsg, key) + case "circuits": + err = unpopulate(val, "Circuits", &e.Circuits) + delete(rawMsg, key) + case "encapsulation": + err = unpopulate(val, "Encapsulation", &e.Encapsulation) + delete(rawMsg, key) + case "etherType": + err = unpopulate(val, "EtherType", &e.EtherType) + delete(rawMsg, key) + case "links": + err = unpopulate(val, "Links", &e.Links) + delete(rawMsg, key) + case "mtu": + err = unpopulate(val, "Mtu", &e.Mtu) + delete(rawMsg, key) + case "peeringLocation": + err = unpopulate(val, "PeeringLocation", &e.PeeringLocation) + delete(rawMsg, key) + case "provisionedBandwidthInGbps": + err = unpopulate(val, "ProvisionedBandwidthInGbps", &e.ProvisionedBandwidthInGbps) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &e.ResourceGUID) + 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 ExpressRoutePortsLocation. +func (e ExpressRoutePortsLocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRoutePortsLocation. +func (e *ExpressRoutePortsLocation) UnmarshalJSON(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) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 ExpressRoutePortsLocationBandwidths. +func (e ExpressRoutePortsLocationBandwidths) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "offerName", e.OfferName) + populate(objectMap, "valueInGbps", e.ValueInGbps) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRoutePortsLocationBandwidths. +func (e *ExpressRoutePortsLocationBandwidths) UnmarshalJSON(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 "offerName": + err = unpopulate(val, "OfferName", &e.OfferName) + delete(rawMsg, key) + case "valueInGbps": + err = unpopulate(val, "ValueInGbps", &e.ValueInGbps) + 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 ExpressRoutePortsLocationListResult. +func (e ExpressRoutePortsLocationListResult) 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 ExpressRoutePortsLocationListResult. +func (e *ExpressRoutePortsLocationListResult) UnmarshalJSON(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 ExpressRoutePortsLocationPropertiesFormat. +func (e ExpressRoutePortsLocationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "address", e.Address) + populate(objectMap, "availableBandwidths", e.AvailableBandwidths) + populate(objectMap, "contact", e.Contact) + populate(objectMap, "provisioningState", e.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRoutePortsLocationPropertiesFormat. +func (e *ExpressRoutePortsLocationPropertiesFormat) UnmarshalJSON(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 "address": + err = unpopulate(val, "Address", &e.Address) + delete(rawMsg, key) + case "availableBandwidths": + err = unpopulate(val, "AvailableBandwidths", &e.AvailableBandwidths) + delete(rawMsg, key) + case "contact": + err = unpopulate(val, "Contact", &e.Contact) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + 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 ExpressRouteProviderPort. +func (e ExpressRouteProviderPort) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteProviderPort. +func (e *ExpressRouteProviderPort) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &e.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 ExpressRouteProviderPortListResult. +func (e ExpressRouteProviderPortListResult) 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 ExpressRouteProviderPortListResult. +func (e *ExpressRouteProviderPortListResult) UnmarshalJSON(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 ExpressRouteProviderPortProperties. +func (e ExpressRouteProviderPortProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "overprovisionFactor", e.OverprovisionFactor) + populate(objectMap, "peeringLocation", e.PeeringLocation) + populate(objectMap, "portBandwidthInMbps", e.PortBandwidthInMbps) + populate(objectMap, "portPairDescriptor", e.PortPairDescriptor) + populate(objectMap, "primaryAzurePort", e.PrimaryAzurePort) + populate(objectMap, "remainingBandwidthInMbps", e.RemainingBandwidthInMbps) + populate(objectMap, "secondaryAzurePort", e.SecondaryAzurePort) + populate(objectMap, "usedBandwidthInMbps", e.UsedBandwidthInMbps) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteProviderPortProperties. +func (e *ExpressRouteProviderPortProperties) UnmarshalJSON(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 "overprovisionFactor": + err = unpopulate(val, "OverprovisionFactor", &e.OverprovisionFactor) + delete(rawMsg, key) + case "peeringLocation": + err = unpopulate(val, "PeeringLocation", &e.PeeringLocation) + delete(rawMsg, key) + case "portBandwidthInMbps": + err = unpopulate(val, "PortBandwidthInMbps", &e.PortBandwidthInMbps) + delete(rawMsg, key) + case "portPairDescriptor": + err = unpopulate(val, "PortPairDescriptor", &e.PortPairDescriptor) + delete(rawMsg, key) + case "primaryAzurePort": + err = unpopulate(val, "PrimaryAzurePort", &e.PrimaryAzurePort) + delete(rawMsg, key) + case "remainingBandwidthInMbps": + err = unpopulate(val, "RemainingBandwidthInMbps", &e.RemainingBandwidthInMbps) + delete(rawMsg, key) + case "secondaryAzurePort": + err = unpopulate(val, "SecondaryAzurePort", &e.SecondaryAzurePort) + delete(rawMsg, key) + case "usedBandwidthInMbps": + err = unpopulate(val, "UsedBandwidthInMbps", &e.UsedBandwidthInMbps) + 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 ExpressRouteServiceProvider. +func (e ExpressRouteServiceProvider) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteServiceProvider. +func (e *ExpressRouteServiceProvider) UnmarshalJSON(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) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + 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 ExpressRouteServiceProviderBandwidthsOffered. +func (e ExpressRouteServiceProviderBandwidthsOffered) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "offerName", e.OfferName) + populate(objectMap, "valueInMbps", e.ValueInMbps) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteServiceProviderBandwidthsOffered. +func (e *ExpressRouteServiceProviderBandwidthsOffered) UnmarshalJSON(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 "offerName": + err = unpopulate(val, "OfferName", &e.OfferName) + delete(rawMsg, key) + case "valueInMbps": + err = unpopulate(val, "ValueInMbps", &e.ValueInMbps) + 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 ExpressRouteServiceProviderListResult. +func (e ExpressRouteServiceProviderListResult) 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 ExpressRouteServiceProviderListResult. +func (e *ExpressRouteServiceProviderListResult) UnmarshalJSON(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 ExpressRouteServiceProviderPropertiesFormat. +func (e ExpressRouteServiceProviderPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bandwidthsOffered", e.BandwidthsOffered) + populate(objectMap, "peeringLocations", e.PeeringLocations) + populate(objectMap, "provisioningState", e.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpressRouteServiceProviderPropertiesFormat. +func (e *ExpressRouteServiceProviderPropertiesFormat) UnmarshalJSON(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 "bandwidthsOffered": + err = unpopulate(val, "BandwidthsOffered", &e.BandwidthsOffered) + delete(rawMsg, key) + case "peeringLocations": + err = unpopulate(val, "PeeringLocations", &e.PeeringLocations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + 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 FilterItems. +func (f FilterItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "field", f.Field) + populate(objectMap, "values", f.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FilterItems. +func (f *FilterItems) UnmarshalJSON(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 "field": + err = unpopulate(val, "Field", &f.Field) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &f.Values) + 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 FirewallPacketCaptureParameters. +func (f FirewallPacketCaptureParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "properties", f.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPacketCaptureParameters. +func (f *FirewallPacketCaptureParameters) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + 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 FirewallPacketCaptureParametersFormat. +func (f FirewallPacketCaptureParametersFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "durationInSeconds", f.DurationInSeconds) + populate(objectMap, "fileName", f.FileName) + populate(objectMap, "filters", f.Filters) + populate(objectMap, "flags", f.Flags) + populate(objectMap, "numberOfPacketsToCapture", f.NumberOfPacketsToCapture) + populate(objectMap, "protocol", f.Protocol) + populate(objectMap, "sasUrl", f.SasURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPacketCaptureParametersFormat. +func (f *FirewallPacketCaptureParametersFormat) UnmarshalJSON(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 "durationInSeconds": + err = unpopulate(val, "DurationInSeconds", &f.DurationInSeconds) + delete(rawMsg, key) + case "fileName": + err = unpopulate(val, "FileName", &f.FileName) + delete(rawMsg, key) + case "filters": + err = unpopulate(val, "Filters", &f.Filters) + delete(rawMsg, key) + case "flags": + err = unpopulate(val, "Flags", &f.Flags) + delete(rawMsg, key) + case "numberOfPacketsToCapture": + err = unpopulate(val, "NumberOfPacketsToCapture", &f.NumberOfPacketsToCapture) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &f.Protocol) + delete(rawMsg, key) + case "sasUrl": + err = unpopulate(val, "SasURL", &f.SasURL) + 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 FirewallPolicy. +func (f FirewallPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", f.Etag) + populate(objectMap, "id", f.ID) + populate(objectMap, "identity", f.Identity) + populate(objectMap, "location", f.Location) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "tags", f.Tags) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicy. +func (f *FirewallPolicy) UnmarshalJSON(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 "identity": + err = unpopulate(val, "Identity", &f.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &f.Location) + 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 "tags": + err = unpopulate(val, "Tags", &f.Tags) + 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 FirewallPolicyCertificateAuthority. +func (f FirewallPolicyCertificateAuthority) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyVaultSecretId", f.KeyVaultSecretID) + populate(objectMap, "name", f.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyCertificateAuthority. +func (f *FirewallPolicyCertificateAuthority) UnmarshalJSON(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 "keyVaultSecretId": + err = unpopulate(val, "KeyVaultSecretID", &f.KeyVaultSecretID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + 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 FirewallPolicyFilterRuleCollection. +func (f FirewallPolicyFilterRuleCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", f.Action) + populate(objectMap, "name", f.Name) + populate(objectMap, "priority", f.Priority) + objectMap["ruleCollectionType"] = FirewallPolicyRuleCollectionTypeFirewallPolicyFilterRuleCollection + populate(objectMap, "rules", f.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyFilterRuleCollection. +func (f *FirewallPolicyFilterRuleCollection) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &f.Action) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &f.Priority) + delete(rawMsg, key) + case "ruleCollectionType": + err = unpopulate(val, "RuleCollectionType", &f.RuleCollectionType) + delete(rawMsg, key) + case "rules": + f.Rules, err = unmarshalFirewallPolicyRuleClassificationArray(val) + 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 FirewallPolicyFilterRuleCollectionAction. +func (f FirewallPolicyFilterRuleCollectionAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyFilterRuleCollectionAction. +func (f *FirewallPolicyFilterRuleCollectionAction) UnmarshalJSON(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 "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 FirewallPolicyHTTPHeaderToInsert. +func (f FirewallPolicyHTTPHeaderToInsert) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "headerName", f.HeaderName) + populate(objectMap, "headerValue", f.HeaderValue) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyHTTPHeaderToInsert. +func (f *FirewallPolicyHTTPHeaderToInsert) UnmarshalJSON(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 "headerName": + err = unpopulate(val, "HeaderName", &f.HeaderName) + delete(rawMsg, key) + case "headerValue": + err = unpopulate(val, "HeaderValue", &f.HeaderValue) + 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 FirewallPolicyInsights. +func (f FirewallPolicyInsights) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isEnabled", f.IsEnabled) + populate(objectMap, "logAnalyticsResources", f.LogAnalyticsResources) + populate(objectMap, "retentionDays", f.RetentionDays) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyInsights. +func (f *FirewallPolicyInsights) UnmarshalJSON(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 "isEnabled": + err = unpopulate(val, "IsEnabled", &f.IsEnabled) + delete(rawMsg, key) + case "logAnalyticsResources": + err = unpopulate(val, "LogAnalyticsResources", &f.LogAnalyticsResources) + delete(rawMsg, key) + case "retentionDays": + err = unpopulate(val, "RetentionDays", &f.RetentionDays) + 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 FirewallPolicyIntrusionDetection. +func (f FirewallPolicyIntrusionDetection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configuration", f.Configuration) + populate(objectMap, "mode", f.Mode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyIntrusionDetection. +func (f *FirewallPolicyIntrusionDetection) UnmarshalJSON(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 "configuration": + err = unpopulate(val, "Configuration", &f.Configuration) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &f.Mode) + 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 FirewallPolicyIntrusionDetectionBypassTrafficSpecifications. +func (f FirewallPolicyIntrusionDetectionBypassTrafficSpecifications) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", f.Description) + populate(objectMap, "destinationAddresses", f.DestinationAddresses) + populate(objectMap, "destinationIpGroups", f.DestinationIPGroups) + populate(objectMap, "destinationPorts", f.DestinationPorts) + populate(objectMap, "name", f.Name) + populate(objectMap, "protocol", f.Protocol) + populate(objectMap, "sourceAddresses", f.SourceAddresses) + populate(objectMap, "sourceIpGroups", f.SourceIPGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyIntrusionDetectionBypassTrafficSpecifications. +func (f *FirewallPolicyIntrusionDetectionBypassTrafficSpecifications) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &f.Description) + delete(rawMsg, key) + case "destinationAddresses": + err = unpopulate(val, "DestinationAddresses", &f.DestinationAddresses) + delete(rawMsg, key) + case "destinationIpGroups": + err = unpopulate(val, "DestinationIPGroups", &f.DestinationIPGroups) + delete(rawMsg, key) + case "destinationPorts": + err = unpopulate(val, "DestinationPorts", &f.DestinationPorts) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &f.Protocol) + delete(rawMsg, key) + case "sourceAddresses": + err = unpopulate(val, "SourceAddresses", &f.SourceAddresses) + delete(rawMsg, key) + case "sourceIpGroups": + err = unpopulate(val, "SourceIPGroups", &f.SourceIPGroups) + 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 FirewallPolicyIntrusionDetectionConfiguration. +func (f FirewallPolicyIntrusionDetectionConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypassTrafficSettings", f.BypassTrafficSettings) + populate(objectMap, "privateRanges", f.PrivateRanges) + populate(objectMap, "signatureOverrides", f.SignatureOverrides) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyIntrusionDetectionConfiguration. +func (f *FirewallPolicyIntrusionDetectionConfiguration) UnmarshalJSON(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 "bypassTrafficSettings": + err = unpopulate(val, "BypassTrafficSettings", &f.BypassTrafficSettings) + delete(rawMsg, key) + case "privateRanges": + err = unpopulate(val, "PrivateRanges", &f.PrivateRanges) + delete(rawMsg, key) + case "signatureOverrides": + err = unpopulate(val, "SignatureOverrides", &f.SignatureOverrides) + 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 FirewallPolicyIntrusionDetectionSignatureSpecification. +func (f FirewallPolicyIntrusionDetectionSignatureSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "mode", f.Mode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyIntrusionDetectionSignatureSpecification. +func (f *FirewallPolicyIntrusionDetectionSignatureSpecification) UnmarshalJSON(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 "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &f.Mode) + 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 FirewallPolicyListResult. +func (f FirewallPolicyListResult) 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 FirewallPolicyListResult. +func (f *FirewallPolicyListResult) UnmarshalJSON(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 FirewallPolicyLogAnalyticsResources. +func (f FirewallPolicyLogAnalyticsResources) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultWorkspaceId", f.DefaultWorkspaceID) + populate(objectMap, "workspaces", f.Workspaces) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyLogAnalyticsResources. +func (f *FirewallPolicyLogAnalyticsResources) UnmarshalJSON(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 "defaultWorkspaceId": + err = unpopulate(val, "DefaultWorkspaceID", &f.DefaultWorkspaceID) + delete(rawMsg, key) + case "workspaces": + err = unpopulate(val, "Workspaces", &f.Workspaces) + 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 FirewallPolicyLogAnalyticsWorkspace. +func (f FirewallPolicyLogAnalyticsWorkspace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "region", f.Region) + populate(objectMap, "workspaceId", f.WorkspaceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyLogAnalyticsWorkspace. +func (f *FirewallPolicyLogAnalyticsWorkspace) UnmarshalJSON(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 "region": + err = unpopulate(val, "Region", &f.Region) + delete(rawMsg, key) + case "workspaceId": + err = unpopulate(val, "WorkspaceID", &f.WorkspaceID) + 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 FirewallPolicyNatRuleCollection. +func (f FirewallPolicyNatRuleCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", f.Action) + populate(objectMap, "name", f.Name) + populate(objectMap, "priority", f.Priority) + objectMap["ruleCollectionType"] = FirewallPolicyRuleCollectionTypeFirewallPolicyNatRuleCollection + populate(objectMap, "rules", f.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyNatRuleCollection. +func (f *FirewallPolicyNatRuleCollection) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &f.Action) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &f.Priority) + delete(rawMsg, key) + case "ruleCollectionType": + err = unpopulate(val, "RuleCollectionType", &f.RuleCollectionType) + delete(rawMsg, key) + case "rules": + f.Rules, err = unmarshalFirewallPolicyRuleClassificationArray(val) + 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 FirewallPolicyNatRuleCollectionAction. +func (f FirewallPolicyNatRuleCollectionAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyNatRuleCollectionAction. +func (f *FirewallPolicyNatRuleCollectionAction) UnmarshalJSON(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 "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 FirewallPolicyPropertiesFormat. +func (f FirewallPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "basePolicy", f.BasePolicy) + populate(objectMap, "childPolicies", f.ChildPolicies) + populate(objectMap, "dnsSettings", f.DNSSettings) + populate(objectMap, "explicitProxySettings", f.ExplicitProxySettings) + populate(objectMap, "firewalls", f.Firewalls) + populate(objectMap, "insights", f.Insights) + populate(objectMap, "intrusionDetection", f.IntrusionDetection) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "ruleCollectionGroups", f.RuleCollectionGroups) + populate(objectMap, "sku", f.SKU) + populate(objectMap, "sql", f.SQL) + populate(objectMap, "size", f.Size) + populate(objectMap, "snat", f.Snat) + populate(objectMap, "threatIntelMode", f.ThreatIntelMode) + populate(objectMap, "threatIntelWhitelist", f.ThreatIntelWhitelist) + populate(objectMap, "transportSecurity", f.TransportSecurity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyPropertiesFormat. +func (f *FirewallPolicyPropertiesFormat) UnmarshalJSON(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 "basePolicy": + err = unpopulate(val, "BasePolicy", &f.BasePolicy) + delete(rawMsg, key) + case "childPolicies": + err = unpopulate(val, "ChildPolicies", &f.ChildPolicies) + delete(rawMsg, key) + case "dnsSettings": + err = unpopulate(val, "DNSSettings", &f.DNSSettings) + delete(rawMsg, key) + case "explicitProxySettings": + err = unpopulate(val, "ExplicitProxySettings", &f.ExplicitProxySettings) + delete(rawMsg, key) + case "firewalls": + err = unpopulate(val, "Firewalls", &f.Firewalls) + delete(rawMsg, key) + case "insights": + err = unpopulate(val, "Insights", &f.Insights) + delete(rawMsg, key) + case "intrusionDetection": + err = unpopulate(val, "IntrusionDetection", &f.IntrusionDetection) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "ruleCollectionGroups": + err = unpopulate(val, "RuleCollectionGroups", &f.RuleCollectionGroups) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &f.SKU) + delete(rawMsg, key) + case "sql": + err = unpopulate(val, "SQL", &f.SQL) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &f.Size) + delete(rawMsg, key) + case "snat": + err = unpopulate(val, "Snat", &f.Snat) + delete(rawMsg, key) + case "threatIntelMode": + err = unpopulate(val, "ThreatIntelMode", &f.ThreatIntelMode) + delete(rawMsg, key) + case "threatIntelWhitelist": + err = unpopulate(val, "ThreatIntelWhitelist", &f.ThreatIntelWhitelist) + delete(rawMsg, key) + case "transportSecurity": + err = unpopulate(val, "TransportSecurity", &f.TransportSecurity) + 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 FirewallPolicyRule. +func (f FirewallPolicyRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", f.Description) + populate(objectMap, "name", f.Name) + objectMap["ruleType"] = f.RuleType + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyRule. +func (f *FirewallPolicyRule) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &f.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &f.RuleType) + 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 FirewallPolicyRuleApplicationProtocol. +func (f FirewallPolicyRuleApplicationProtocol) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "port", f.Port) + populate(objectMap, "protocolType", f.ProtocolType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyRuleApplicationProtocol. +func (f *FirewallPolicyRuleApplicationProtocol) UnmarshalJSON(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 "port": + err = unpopulate(val, "Port", &f.Port) + delete(rawMsg, key) + case "protocolType": + err = unpopulate(val, "ProtocolType", &f.ProtocolType) + 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 FirewallPolicyRuleCollection. +func (f FirewallPolicyRuleCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + populate(objectMap, "priority", f.Priority) + objectMap["ruleCollectionType"] = f.RuleCollectionType + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyRuleCollection. +func (f *FirewallPolicyRuleCollection) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &f.Priority) + delete(rawMsg, key) + case "ruleCollectionType": + err = unpopulate(val, "RuleCollectionType", &f.RuleCollectionType) + 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 FirewallPolicyRuleCollectionGroup. +func (f FirewallPolicyRuleCollectionGroup) 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 FirewallPolicyRuleCollectionGroup. +func (f *FirewallPolicyRuleCollectionGroup) UnmarshalJSON(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 FirewallPolicyRuleCollectionGroupListResult. +func (f FirewallPolicyRuleCollectionGroupListResult) 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 FirewallPolicyRuleCollectionGroupListResult. +func (f *FirewallPolicyRuleCollectionGroupListResult) UnmarshalJSON(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 FirewallPolicyRuleCollectionGroupProperties. +func (f FirewallPolicyRuleCollectionGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "priority", f.Priority) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "ruleCollections", f.RuleCollections) + populate(objectMap, "size", f.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyRuleCollectionGroupProperties. +func (f *FirewallPolicyRuleCollectionGroupProperties) UnmarshalJSON(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 "priority": + err = unpopulate(val, "Priority", &f.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "ruleCollections": + f.RuleCollections, err = unmarshalFirewallPolicyRuleCollectionClassificationArray(val) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &f.Size) + 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 FirewallPolicySKU. +func (f FirewallPolicySKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tier", f.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicySKU. +func (f *FirewallPolicySKU) UnmarshalJSON(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 "tier": + err = unpopulate(val, "Tier", &f.Tier) + 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 FirewallPolicySNAT. +func (f FirewallPolicySNAT) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoLearnPrivateRanges", f.AutoLearnPrivateRanges) + populate(objectMap, "privateRanges", f.PrivateRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicySNAT. +func (f *FirewallPolicySNAT) UnmarshalJSON(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 "autoLearnPrivateRanges": + err = unpopulate(val, "AutoLearnPrivateRanges", &f.AutoLearnPrivateRanges) + delete(rawMsg, key) + case "privateRanges": + err = unpopulate(val, "PrivateRanges", &f.PrivateRanges) + 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 FirewallPolicySQL. +func (f FirewallPolicySQL) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowSqlRedirect", f.AllowSQLRedirect) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicySQL. +func (f *FirewallPolicySQL) UnmarshalJSON(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 "allowSqlRedirect": + err = unpopulate(val, "AllowSQLRedirect", &f.AllowSQLRedirect) + 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 FirewallPolicyThreatIntelWhitelist. +func (f FirewallPolicyThreatIntelWhitelist) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fqdns", f.Fqdns) + populate(objectMap, "ipAddresses", f.IPAddresses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyThreatIntelWhitelist. +func (f *FirewallPolicyThreatIntelWhitelist) UnmarshalJSON(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 "fqdns": + err = unpopulate(val, "Fqdns", &f.Fqdns) + delete(rawMsg, key) + case "ipAddresses": + err = unpopulate(val, "IPAddresses", &f.IPAddresses) + 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 FirewallPolicyTransportSecurity. +func (f FirewallPolicyTransportSecurity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateAuthority", f.CertificateAuthority) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallPolicyTransportSecurity. +func (f *FirewallPolicyTransportSecurity) UnmarshalJSON(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 "certificateAuthority": + err = unpopulate(val, "CertificateAuthority", &f.CertificateAuthority) + 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 FlowLog. +func (f FlowLog) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", f.Etag) + populate(objectMap, "id", f.ID) + populate(objectMap, "location", f.Location) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "tags", f.Tags) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlowLog. +func (f *FlowLog) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &f.Location) + 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 "tags": + err = unpopulate(val, "Tags", &f.Tags) + 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 FlowLogFormatParameters. +func (f FlowLogFormatParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", f.Type) + populate(objectMap, "version", f.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlowLogFormatParameters. +func (f *FlowLogFormatParameters) UnmarshalJSON(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 "type": + err = unpopulate(val, "Type", &f.Type) + 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 FlowLogInformation. +func (f FlowLogInformation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "flowAnalyticsConfiguration", f.FlowAnalyticsConfiguration) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "targetResourceId", f.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlowLogInformation. +func (f *FlowLogInformation) UnmarshalJSON(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 "flowAnalyticsConfiguration": + err = unpopulate(val, "FlowAnalyticsConfiguration", &f.FlowAnalyticsConfiguration) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "targetResourceId": + err = unpopulate(val, "TargetResourceID", &f.TargetResourceID) + 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 FlowLogListResult. +func (f FlowLogListResult) 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 FlowLogListResult. +func (f *FlowLogListResult) UnmarshalJSON(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 FlowLogProperties. +func (f FlowLogProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", f.Enabled) + populate(objectMap, "format", f.Format) + populate(objectMap, "retentionPolicy", f.RetentionPolicy) + populate(objectMap, "storageId", f.StorageID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlowLogProperties. +func (f *FlowLogProperties) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &f.Enabled) + delete(rawMsg, key) + case "format": + err = unpopulate(val, "Format", &f.Format) + delete(rawMsg, key) + case "retentionPolicy": + err = unpopulate(val, "RetentionPolicy", &f.RetentionPolicy) + delete(rawMsg, key) + case "storageId": + err = unpopulate(val, "StorageID", &f.StorageID) + 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 FlowLogPropertiesFormat. +func (f FlowLogPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", f.Enabled) + populate(objectMap, "flowAnalyticsConfiguration", f.FlowAnalyticsConfiguration) + populate(objectMap, "format", f.Format) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "retentionPolicy", f.RetentionPolicy) + populate(objectMap, "storageId", f.StorageID) + populate(objectMap, "targetResourceGuid", f.TargetResourceGUID) + populate(objectMap, "targetResourceId", f.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlowLogPropertiesFormat. +func (f *FlowLogPropertiesFormat) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &f.Enabled) + delete(rawMsg, key) + case "flowAnalyticsConfiguration": + err = unpopulate(val, "FlowAnalyticsConfiguration", &f.FlowAnalyticsConfiguration) + delete(rawMsg, key) + case "format": + err = unpopulate(val, "Format", &f.Format) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "retentionPolicy": + err = unpopulate(val, "RetentionPolicy", &f.RetentionPolicy) + delete(rawMsg, key) + case "storageId": + err = unpopulate(val, "StorageID", &f.StorageID) + delete(rawMsg, key) + case "targetResourceGuid": + err = unpopulate(val, "TargetResourceGUID", &f.TargetResourceGUID) + delete(rawMsg, key) + case "targetResourceId": + err = unpopulate(val, "TargetResourceID", &f.TargetResourceID) + 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 FlowLogStatusParameters. +func (f FlowLogStatusParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targetResourceId", f.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlowLogStatusParameters. +func (f *FlowLogStatusParameters) UnmarshalJSON(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 "targetResourceId": + err = unpopulate(val, "TargetResourceID", &f.TargetResourceID) + 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 FrontendIPConfiguration. +func (f FrontendIPConfiguration) 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) + populate(objectMap, "zones", f.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FrontendIPConfiguration. +func (f *FrontendIPConfiguration) UnmarshalJSON(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) + case "zones": + err = unpopulate(val, "Zones", &f.Zones) + 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 FrontendIPConfigurationPropertiesFormat. +func (f FrontendIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "gatewayLoadBalancer", f.GatewayLoadBalancer) + populate(objectMap, "inboundNatPools", f.InboundNatPools) + populate(objectMap, "inboundNatRules", f.InboundNatRules) + populate(objectMap, "loadBalancingRules", f.LoadBalancingRules) + populate(objectMap, "outboundRules", f.OutboundRules) + populate(objectMap, "privateIPAddress", f.PrivateIPAddress) + populate(objectMap, "privateIPAddressVersion", f.PrivateIPAddressVersion) + populate(objectMap, "privateIPAllocationMethod", f.PrivateIPAllocationMethod) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "publicIPAddress", f.PublicIPAddress) + populate(objectMap, "publicIPPrefix", f.PublicIPPrefix) + populate(objectMap, "subnet", f.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FrontendIPConfigurationPropertiesFormat. +func (f *FrontendIPConfigurationPropertiesFormat) UnmarshalJSON(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 "gatewayLoadBalancer": + err = unpopulate(val, "GatewayLoadBalancer", &f.GatewayLoadBalancer) + delete(rawMsg, key) + case "inboundNatPools": + err = unpopulate(val, "InboundNatPools", &f.InboundNatPools) + delete(rawMsg, key) + case "inboundNatRules": + err = unpopulate(val, "InboundNatRules", &f.InboundNatRules) + delete(rawMsg, key) + case "loadBalancingRules": + err = unpopulate(val, "LoadBalancingRules", &f.LoadBalancingRules) + delete(rawMsg, key) + case "outboundRules": + err = unpopulate(val, "OutboundRules", &f.OutboundRules) + delete(rawMsg, key) + case "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &f.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAddressVersion": + err = unpopulate(val, "PrivateIPAddressVersion", &f.PrivateIPAddressVersion) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &f.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &f.PublicIPAddress) + delete(rawMsg, key) + case "publicIPPrefix": + err = unpopulate(val, "PublicIPPrefix", &f.PublicIPPrefix) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &f.Subnet) + 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 GatewayCustomBgpIPAddressIPConfiguration. +func (g GatewayCustomBgpIPAddressIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customBgpIpAddress", g.CustomBgpIPAddress) + populate(objectMap, "ipConfigurationId", g.IPConfigurationID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GatewayCustomBgpIPAddressIPConfiguration. +func (g *GatewayCustomBgpIPAddressIPConfiguration) UnmarshalJSON(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 "customBgpIpAddress": + err = unpopulate(val, "CustomBgpIPAddress", &g.CustomBgpIPAddress) + delete(rawMsg, key) + case "ipConfigurationId": + err = unpopulate(val, "IPConfigurationID", &g.IPConfigurationID) + 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 GatewayLoadBalancerTunnelInterface. +func (g GatewayLoadBalancerTunnelInterface) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", g.Identifier) + populate(objectMap, "port", g.Port) + populate(objectMap, "protocol", g.Protocol) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GatewayLoadBalancerTunnelInterface. +func (g *GatewayLoadBalancerTunnelInterface) UnmarshalJSON(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 "identifier": + err = unpopulate(val, "Identifier", &g.Identifier) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &g.Port) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &g.Protocol) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GatewayRoute. +func (g GatewayRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asPath", g.AsPath) + populate(objectMap, "localAddress", g.LocalAddress) + populate(objectMap, "network", g.Network) + populate(objectMap, "nextHop", g.NextHop) + populate(objectMap, "origin", g.Origin) + populate(objectMap, "sourcePeer", g.SourcePeer) + populate(objectMap, "weight", g.Weight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GatewayRoute. +func (g *GatewayRoute) UnmarshalJSON(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 "asPath": + err = unpopulate(val, "AsPath", &g.AsPath) + delete(rawMsg, key) + case "localAddress": + err = unpopulate(val, "LocalAddress", &g.LocalAddress) + delete(rawMsg, key) + case "network": + err = unpopulate(val, "Network", &g.Network) + delete(rawMsg, key) + case "nextHop": + err = unpopulate(val, "NextHop", &g.NextHop) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &g.Origin) + delete(rawMsg, key) + case "sourcePeer": + err = unpopulate(val, "SourcePeer", &g.SourcePeer) + delete(rawMsg, key) + case "weight": + err = unpopulate(val, "Weight", &g.Weight) + 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 GatewayRouteListResult. +func (g GatewayRouteListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GatewayRouteListResult. +func (g *GatewayRouteListResult) UnmarshalJSON(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 "value": + err = unpopulate(val, "Value", &g.Value) + 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 GenerateExpressRoutePortsLOARequest. +func (g GenerateExpressRoutePortsLOARequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customerName", g.CustomerName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GenerateExpressRoutePortsLOARequest. +func (g *GenerateExpressRoutePortsLOARequest) UnmarshalJSON(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 "customerName": + err = unpopulate(val, "CustomerName", &g.CustomerName) + 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 GenerateExpressRoutePortsLOAResult. +func (g GenerateExpressRoutePortsLOAResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encodedContent", g.EncodedContent) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GenerateExpressRoutePortsLOAResult. +func (g *GenerateExpressRoutePortsLOAResult) UnmarshalJSON(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 "encodedContent": + err = unpopulate(val, "EncodedContent", &g.EncodedContent) + 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 GetInboundRoutesParameters. +func (g GetInboundRoutesParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionType", g.ConnectionType) + populate(objectMap, "resourceUri", g.ResourceURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetInboundRoutesParameters. +func (g *GetInboundRoutesParameters) UnmarshalJSON(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 "connectionType": + err = unpopulate(val, "ConnectionType", &g.ConnectionType) + delete(rawMsg, key) + case "resourceUri": + err = unpopulate(val, "ResourceURI", &g.ResourceURI) + 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 GetOutboundRoutesParameters. +func (g GetOutboundRoutesParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionType", g.ConnectionType) + populate(objectMap, "resourceUri", g.ResourceURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetOutboundRoutesParameters. +func (g *GetOutboundRoutesParameters) UnmarshalJSON(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 "connectionType": + err = unpopulate(val, "ConnectionType", &g.ConnectionType) + delete(rawMsg, key) + case "resourceUri": + err = unpopulate(val, "ResourceURI", &g.ResourceURI) + 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 GetVPNSitesConfigurationRequest. +func (g GetVPNSitesConfigurationRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "outputBlobSasUrl", g.OutputBlobSasURL) + populate(objectMap, "vpnSites", g.VPNSites) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetVPNSitesConfigurationRequest. +func (g *GetVPNSitesConfigurationRequest) UnmarshalJSON(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 "outputBlobSasUrl": + err = unpopulate(val, "OutputBlobSasURL", &g.OutputBlobSasURL) + delete(rawMsg, key) + case "vpnSites": + err = unpopulate(val, "VPNSites", &g.VPNSites) + 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 Group. +func (g Group) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", g.Etag) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "systemData", g.SystemData) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Group. +func (g *Group) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &g.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &g.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + 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 GroupByUserSession. +func (g GroupByUserSession) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupByVariables", g.GroupByVariables) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GroupByUserSession. +func (g *GroupByUserSession) UnmarshalJSON(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 "groupByVariables": + err = unpopulate(val, "GroupByVariables", &g.GroupByVariables) + 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 GroupByVariable. +func (g GroupByVariable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "variableName", g.VariableName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GroupByVariable. +func (g *GroupByVariable) UnmarshalJSON(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 "variableName": + err = unpopulate(val, "VariableName", &g.VariableName) + 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 GroupListResult. +func (g GroupListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GroupListResult. +func (g *GroupListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + 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 GroupProperties. +func (g GroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", g.Description) + populate(objectMap, "provisioningState", g.ProvisioningState) + populate(objectMap, "resourceGuid", g.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GroupProperties. +func (g *GroupProperties) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &g.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &g.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &g.ResourceGUID) + 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 HTTPConfiguration. +func (h HTTPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "headers", h.Headers) + populate(objectMap, "method", h.Method) + populate(objectMap, "validStatusCodes", h.ValidStatusCodes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HTTPConfiguration. +func (h *HTTPConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "headers": + err = unpopulate(val, "Headers", &h.Headers) + delete(rawMsg, key) + case "method": + err = unpopulate(val, "Method", &h.Method) + delete(rawMsg, key) + case "validStatusCodes": + err = unpopulate(val, "ValidStatusCodes", &h.ValidStatusCodes) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HTTPHeader. +func (h HTTPHeader) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", h.Name) + populate(objectMap, "value", h.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HTTPHeader. +func (h *HTTPHeader) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &h.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HopLink. +func (h HopLink) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "context", h.Context) + populate(objectMap, "issues", h.Issues) + populate(objectMap, "linkType", h.LinkType) + populate(objectMap, "nextHopId", h.NextHopID) + populate(objectMap, "properties", h.Properties) + populate(objectMap, "resourceId", h.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HopLink. +func (h *HopLink) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "context": + err = unpopulate(val, "Context", &h.Context) + delete(rawMsg, key) + case "issues": + err = unpopulate(val, "Issues", &h.Issues) + delete(rawMsg, key) + case "linkType": + err = unpopulate(val, "LinkType", &h.LinkType) + delete(rawMsg, key) + case "nextHopId": + err = unpopulate(val, "NextHopID", &h.NextHopID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &h.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HopLinkProperties. +func (h HopLinkProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "roundTripTimeAvg", h.RoundTripTimeAvg) + populate(objectMap, "roundTripTimeMax", h.RoundTripTimeMax) + populate(objectMap, "roundTripTimeMin", h.RoundTripTimeMin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HopLinkProperties. +func (h *HopLinkProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "roundTripTimeAvg": + err = unpopulate(val, "RoundTripTimeAvg", &h.RoundTripTimeAvg) + delete(rawMsg, key) + case "roundTripTimeMax": + err = unpopulate(val, "RoundTripTimeMax", &h.RoundTripTimeMax) + delete(rawMsg, key) + case "roundTripTimeMin": + err = unpopulate(val, "RoundTripTimeMin", &h.RoundTripTimeMin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Hub. +func (h Hub) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceId", h.ResourceID) + populate(objectMap, "resourceType", h.ResourceType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Hub. +func (h *Hub) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceId": + err = unpopulate(val, "ResourceID", &h.ResourceID) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &h.ResourceType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubIPAddresses. +func (h HubIPAddresses) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAddress", h.PrivateIPAddress) + populate(objectMap, "publicIPs", h.PublicIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubIPAddresses. +func (h *HubIPAddresses) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &h.PrivateIPAddress) + delete(rawMsg, key) + case "publicIPs": + err = unpopulate(val, "PublicIPs", &h.PublicIPs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubIPConfiguration. +func (h HubIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", h.Etag) + populate(objectMap, "id", h.ID) + populate(objectMap, "name", h.Name) + populate(objectMap, "properties", h.Properties) + populate(objectMap, "type", h.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubIPConfiguration. +func (h *HubIPConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &h.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &h.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &h.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubIPConfigurationPropertiesFormat. +func (h HubIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAddress", h.PrivateIPAddress) + populate(objectMap, "privateIPAllocationMethod", h.PrivateIPAllocationMethod) + populate(objectMap, "provisioningState", h.ProvisioningState) + populate(objectMap, "publicIPAddress", h.PublicIPAddress) + populate(objectMap, "subnet", h.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubIPConfigurationPropertiesFormat. +func (h *HubIPConfigurationPropertiesFormat) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &h.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &h.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &h.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &h.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &h.Subnet) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubPublicIPAddresses. +func (h HubPublicIPAddresses) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addresses", h.Addresses) + populate(objectMap, "count", h.Count) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubPublicIPAddresses. +func (h *HubPublicIPAddresses) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addresses": + err = unpopulate(val, "Addresses", &h.Addresses) + delete(rawMsg, key) + case "count": + err = unpopulate(val, "Count", &h.Count) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubRoute. +func (h HubRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationType", h.DestinationType) + populate(objectMap, "destinations", h.Destinations) + populate(objectMap, "name", h.Name) + populate(objectMap, "nextHop", h.NextHop) + populate(objectMap, "nextHopType", h.NextHopType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubRoute. +func (h *HubRoute) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "destinationType": + err = unpopulate(val, "DestinationType", &h.DestinationType) + delete(rawMsg, key) + case "destinations": + err = unpopulate(val, "Destinations", &h.Destinations) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "nextHop": + err = unpopulate(val, "NextHop", &h.NextHop) + delete(rawMsg, key) + case "nextHopType": + err = unpopulate(val, "NextHopType", &h.NextHopType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubRouteTable. +func (h HubRouteTable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", h.Etag) + populate(objectMap, "id", h.ID) + populate(objectMap, "name", h.Name) + populate(objectMap, "properties", h.Properties) + populate(objectMap, "type", h.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubRouteTable. +func (h *HubRouteTable) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &h.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &h.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &h.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubRouteTableProperties. +func (h HubRouteTableProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "associatedConnections", h.AssociatedConnections) + populate(objectMap, "labels", h.Labels) + populate(objectMap, "propagatingConnections", h.PropagatingConnections) + populate(objectMap, "provisioningState", h.ProvisioningState) + populate(objectMap, "routes", h.Routes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubRouteTableProperties. +func (h *HubRouteTableProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "associatedConnections": + err = unpopulate(val, "AssociatedConnections", &h.AssociatedConnections) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &h.Labels) + delete(rawMsg, key) + case "propagatingConnections": + err = unpopulate(val, "PropagatingConnections", &h.PropagatingConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &h.ProvisioningState) + delete(rawMsg, key) + case "routes": + err = unpopulate(val, "Routes", &h.Routes) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubVirtualNetworkConnection. +func (h HubVirtualNetworkConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", h.Etag) + populate(objectMap, "id", h.ID) + populate(objectMap, "name", h.Name) + populate(objectMap, "properties", h.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubVirtualNetworkConnection. +func (h *HubVirtualNetworkConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &h.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &h.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HubVirtualNetworkConnectionProperties. +func (h HubVirtualNetworkConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowHubToRemoteVnetTransit", h.AllowHubToRemoteVnetTransit) + populate(objectMap, "allowRemoteVnetToUseHubVnetGateways", h.AllowRemoteVnetToUseHubVnetGateways) + populate(objectMap, "enableInternetSecurity", h.EnableInternetSecurity) + populate(objectMap, "provisioningState", h.ProvisioningState) + populate(objectMap, "remoteVirtualNetwork", h.RemoteVirtualNetwork) + populate(objectMap, "routingConfiguration", h.RoutingConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HubVirtualNetworkConnectionProperties. +func (h *HubVirtualNetworkConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowHubToRemoteVnetTransit": + err = unpopulate(val, "AllowHubToRemoteVnetTransit", &h.AllowHubToRemoteVnetTransit) + delete(rawMsg, key) + case "allowRemoteVnetToUseHubVnetGateways": + err = unpopulate(val, "AllowRemoteVnetToUseHubVnetGateways", &h.AllowRemoteVnetToUseHubVnetGateways) + delete(rawMsg, key) + case "enableInternetSecurity": + err = unpopulate(val, "EnableInternetSecurity", &h.EnableInternetSecurity) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &h.ProvisioningState) + delete(rawMsg, key) + case "remoteVirtualNetwork": + err = unpopulate(val, "RemoteVirtualNetwork", &h.RemoteVirtualNetwork) + delete(rawMsg, key) + case "routingConfiguration": + err = unpopulate(val, "RoutingConfiguration", &h.RoutingConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IDPSQueryObject. +func (i IDPSQueryObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filters", i.Filters) + populate(objectMap, "orderBy", i.OrderBy) + populate(objectMap, "resultsPerPage", i.ResultsPerPage) + populate(objectMap, "search", i.Search) + populate(objectMap, "skip", i.Skip) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IDPSQueryObject. +func (i *IDPSQueryObject) UnmarshalJSON(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 "filters": + err = unpopulate(val, "Filters", &i.Filters) + delete(rawMsg, key) + case "orderBy": + err = unpopulate(val, "OrderBy", &i.OrderBy) + delete(rawMsg, key) + case "resultsPerPage": + err = unpopulate(val, "ResultsPerPage", &i.ResultsPerPage) + delete(rawMsg, key) + case "search": + err = unpopulate(val, "Search", &i.Search) + delete(rawMsg, key) + case "skip": + err = unpopulate(val, "Skip", &i.Skip) + 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 IPAddressAvailabilityResult. +func (i IPAddressAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "available", i.Available) + populate(objectMap, "availableIPAddresses", i.AvailableIPAddresses) + populate(objectMap, "isPlatformReserved", i.IsPlatformReserved) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPAddressAvailabilityResult. +func (i *IPAddressAvailabilityResult) UnmarshalJSON(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 "available": + err = unpopulate(val, "Available", &i.Available) + delete(rawMsg, key) + case "availableIPAddresses": + err = unpopulate(val, "AvailableIPAddresses", &i.AvailableIPAddresses) + delete(rawMsg, key) + case "isPlatformReserved": + err = unpopulate(val, "IsPlatformReserved", &i.IsPlatformReserved) + 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 IPAllocation. +func (i IPAllocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", i.Etag) + populate(objectMap, "id", i.ID) + populate(objectMap, "location", i.Location) + populate(objectMap, "name", i.Name) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "tags", i.Tags) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPAllocation. +func (i *IPAllocation) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &i.Location) + 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 "tags": + err = unpopulate(val, "Tags", &i.Tags) + 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 IPAllocationListResult. +func (i IPAllocationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPAllocationListResult. +func (i *IPAllocationListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 IPAllocationPropertiesFormat. +func (i IPAllocationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocationTags", i.AllocationTags) + populate(objectMap, "ipamAllocationId", i.IpamAllocationID) + populate(objectMap, "prefix", i.Prefix) + populate(objectMap, "prefixLength", i.PrefixLength) + populate(objectMap, "prefixType", i.PrefixType) + populate(objectMap, "subnet", i.Subnet) + populate(objectMap, "type", i.Type) + populate(objectMap, "virtualNetwork", i.VirtualNetwork) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPAllocationPropertiesFormat. +func (i *IPAllocationPropertiesFormat) UnmarshalJSON(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 "allocationTags": + err = unpopulate(val, "AllocationTags", &i.AllocationTags) + delete(rawMsg, key) + case "ipamAllocationId": + err = unpopulate(val, "IpamAllocationID", &i.IpamAllocationID) + delete(rawMsg, key) + case "prefix": + err = unpopulate(val, "Prefix", &i.Prefix) + delete(rawMsg, key) + case "prefixLength": + err = unpopulate(val, "PrefixLength", &i.PrefixLength) + delete(rawMsg, key) + case "prefixType": + err = unpopulate(val, "PrefixType", &i.PrefixType) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &i.Subnet) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + case "virtualNetwork": + err = unpopulate(val, "VirtualNetwork", &i.VirtualNetwork) + 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 IPConfiguration. +func (i IPConfiguration) 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) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPConfiguration. +func (i *IPConfiguration) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IPConfigurationBgpPeeringAddress. +func (i IPConfigurationBgpPeeringAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customBgpIpAddresses", i.CustomBgpIPAddresses) + populate(objectMap, "defaultBgpIpAddresses", i.DefaultBgpIPAddresses) + populate(objectMap, "ipconfigurationId", i.IPConfigurationID) + populate(objectMap, "tunnelIpAddresses", i.TunnelIPAddresses) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPConfigurationBgpPeeringAddress. +func (i *IPConfigurationBgpPeeringAddress) UnmarshalJSON(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 "customBgpIpAddresses": + err = unpopulate(val, "CustomBgpIPAddresses", &i.CustomBgpIPAddresses) + delete(rawMsg, key) + case "defaultBgpIpAddresses": + err = unpopulate(val, "DefaultBgpIPAddresses", &i.DefaultBgpIPAddresses) + delete(rawMsg, key) + case "ipconfigurationId": + err = unpopulate(val, "IPConfigurationID", &i.IPConfigurationID) + delete(rawMsg, key) + case "tunnelIpAddresses": + err = unpopulate(val, "TunnelIPAddresses", &i.TunnelIPAddresses) + 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 IPConfigurationProfile. +func (i IPConfigurationProfile) 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 IPConfigurationProfile. +func (i *IPConfigurationProfile) UnmarshalJSON(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 IPConfigurationProfilePropertiesFormat. +func (i IPConfigurationProfilePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "subnet", i.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPConfigurationProfilePropertiesFormat. +func (i *IPConfigurationProfilePropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &i.Subnet) + 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 IPConfigurationPropertiesFormat. +func (i IPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAddress", i.PrivateIPAddress) + populate(objectMap, "privateIPAllocationMethod", i.PrivateIPAllocationMethod) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "publicIPAddress", i.PublicIPAddress) + populate(objectMap, "subnet", i.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPConfigurationPropertiesFormat. +func (i *IPConfigurationPropertiesFormat) UnmarshalJSON(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 "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &i.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &i.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &i.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &i.Subnet) + 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 IPGroup. +func (i IPGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", i.Etag) + populate(objectMap, "id", i.ID) + populate(objectMap, "location", i.Location) + populate(objectMap, "name", i.Name) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "tags", i.Tags) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPGroup. +func (i *IPGroup) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &i.Location) + 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 "tags": + err = unpopulate(val, "Tags", &i.Tags) + 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 IPGroupListResult. +func (i IPGroupListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPGroupListResult. +func (i *IPGroupListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 IPGroupPropertiesFormat. +func (i IPGroupPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "firewallPolicies", i.FirewallPolicies) + populate(objectMap, "firewalls", i.Firewalls) + populate(objectMap, "ipAddresses", i.IPAddresses) + populate(objectMap, "provisioningState", i.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPGroupPropertiesFormat. +func (i *IPGroupPropertiesFormat) UnmarshalJSON(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 "firewallPolicies": + err = unpopulate(val, "FirewallPolicies", &i.FirewallPolicies) + delete(rawMsg, key) + case "firewalls": + err = unpopulate(val, "Firewalls", &i.Firewalls) + delete(rawMsg, key) + case "ipAddresses": + err = unpopulate(val, "IPAddresses", &i.IPAddresses) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + 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 IPPrefixesList. +func (i IPPrefixesList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipPrefixes", i.IPPrefixes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPPrefixesList. +func (i *IPPrefixesList) UnmarshalJSON(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 "ipPrefixes": + err = unpopulate(val, "IPPrefixes", &i.IPPrefixes) + 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 IPRule. +func (i IPRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", i.AddressPrefix) + 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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &i.AddressPrefix) + 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 IPSecPolicy. +func (i IPSecPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dhGroup", i.DhGroup) + populate(objectMap, "ipsecEncryption", i.IPSecEncryption) + populate(objectMap, "ipsecIntegrity", i.IPSecIntegrity) + populate(objectMap, "ikeEncryption", i.IkeEncryption) + populate(objectMap, "ikeIntegrity", i.IkeIntegrity) + populate(objectMap, "pfsGroup", i.PfsGroup) + populate(objectMap, "saDataSizeKilobytes", i.SaDataSizeKilobytes) + populate(objectMap, "saLifeTimeSeconds", i.SaLifeTimeSeconds) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPSecPolicy. +func (i *IPSecPolicy) UnmarshalJSON(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 "dhGroup": + err = unpopulate(val, "DhGroup", &i.DhGroup) + delete(rawMsg, key) + case "ipsecEncryption": + err = unpopulate(val, "IPSecEncryption", &i.IPSecEncryption) + delete(rawMsg, key) + case "ipsecIntegrity": + err = unpopulate(val, "IPSecIntegrity", &i.IPSecIntegrity) + delete(rawMsg, key) + case "ikeEncryption": + err = unpopulate(val, "IkeEncryption", &i.IkeEncryption) + delete(rawMsg, key) + case "ikeIntegrity": + err = unpopulate(val, "IkeIntegrity", &i.IkeIntegrity) + delete(rawMsg, key) + case "pfsGroup": + err = unpopulate(val, "PfsGroup", &i.PfsGroup) + delete(rawMsg, key) + case "saDataSizeKilobytes": + err = unpopulate(val, "SaDataSizeKilobytes", &i.SaDataSizeKilobytes) + delete(rawMsg, key) + case "saLifeTimeSeconds": + err = unpopulate(val, "SaLifeTimeSeconds", &i.SaLifeTimeSeconds) + 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 IPTag. +func (i IPTag) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipTagType", i.IPTagType) + populate(objectMap, "tag", i.Tag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPTag. +func (i *IPTag) UnmarshalJSON(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 "ipTagType": + err = unpopulate(val, "IPTagType", &i.IPTagType) + 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 IPv6CircuitConnectionConfig. +func (i IPv6CircuitConnectionConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", i.AddressPrefix) + populate(objectMap, "circuitConnectionStatus", i.CircuitConnectionStatus) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPv6CircuitConnectionConfig. +func (i *IPv6CircuitConnectionConfig) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &i.AddressPrefix) + delete(rawMsg, key) + case "circuitConnectionStatus": + err = unpopulate(val, "CircuitConnectionStatus", &i.CircuitConnectionStatus) + 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 IPv6ExpressRouteCircuitPeeringConfig. +func (i IPv6ExpressRouteCircuitPeeringConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "microsoftPeeringConfig", i.MicrosoftPeeringConfig) + populate(objectMap, "primaryPeerAddressPrefix", i.PrimaryPeerAddressPrefix) + populate(objectMap, "routeFilter", i.RouteFilter) + populate(objectMap, "secondaryPeerAddressPrefix", i.SecondaryPeerAddressPrefix) + populate(objectMap, "state", i.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPv6ExpressRouteCircuitPeeringConfig. +func (i *IPv6ExpressRouteCircuitPeeringConfig) UnmarshalJSON(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 "microsoftPeeringConfig": + err = unpopulate(val, "MicrosoftPeeringConfig", &i.MicrosoftPeeringConfig) + delete(rawMsg, key) + case "primaryPeerAddressPrefix": + err = unpopulate(val, "PrimaryPeerAddressPrefix", &i.PrimaryPeerAddressPrefix) + delete(rawMsg, key) + case "routeFilter": + err = unpopulate(val, "RouteFilter", &i.RouteFilter) + delete(rawMsg, key) + case "secondaryPeerAddressPrefix": + err = unpopulate(val, "SecondaryPeerAddressPrefix", &i.SecondaryPeerAddressPrefix) + 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 InboundNatPool. +func (i InboundNatPool) 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 InboundNatPool. +func (i *InboundNatPool) UnmarshalJSON(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 InboundNatPoolPropertiesFormat. +func (i InboundNatPoolPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendPort", i.BackendPort) + populate(objectMap, "enableFloatingIP", i.EnableFloatingIP) + populate(objectMap, "enableTcpReset", i.EnableTCPReset) + populate(objectMap, "frontendIPConfiguration", i.FrontendIPConfiguration) + populate(objectMap, "frontendPortRangeEnd", i.FrontendPortRangeEnd) + populate(objectMap, "frontendPortRangeStart", i.FrontendPortRangeStart) + populate(objectMap, "idleTimeoutInMinutes", i.IdleTimeoutInMinutes) + populate(objectMap, "protocol", i.Protocol) + populate(objectMap, "provisioningState", i.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundNatPoolPropertiesFormat. +func (i *InboundNatPoolPropertiesFormat) UnmarshalJSON(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 "backendPort": + err = unpopulate(val, "BackendPort", &i.BackendPort) + delete(rawMsg, key) + case "enableFloatingIP": + err = unpopulate(val, "EnableFloatingIP", &i.EnableFloatingIP) + delete(rawMsg, key) + case "enableTcpReset": + err = unpopulate(val, "EnableTCPReset", &i.EnableTCPReset) + delete(rawMsg, key) + case "frontendIPConfiguration": + err = unpopulate(val, "FrontendIPConfiguration", &i.FrontendIPConfiguration) + delete(rawMsg, key) + case "frontendPortRangeEnd": + err = unpopulate(val, "FrontendPortRangeEnd", &i.FrontendPortRangeEnd) + delete(rawMsg, key) + case "frontendPortRangeStart": + err = unpopulate(val, "FrontendPortRangeStart", &i.FrontendPortRangeStart) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &i.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &i.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + 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 InboundNatRule. +func (i InboundNatRule) 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 InboundNatRule. +func (i *InboundNatRule) UnmarshalJSON(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 InboundNatRuleListResult. +func (i InboundNatRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundNatRuleListResult. +func (i *InboundNatRuleListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 InboundNatRulePortMapping. +func (i InboundNatRulePortMapping) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendPort", i.BackendPort) + populate(objectMap, "frontendPort", i.FrontendPort) + populate(objectMap, "inboundNatRuleName", i.InboundNatRuleName) + populate(objectMap, "protocol", i.Protocol) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundNatRulePortMapping. +func (i *InboundNatRulePortMapping) UnmarshalJSON(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 "backendPort": + err = unpopulate(val, "BackendPort", &i.BackendPort) + delete(rawMsg, key) + case "frontendPort": + err = unpopulate(val, "FrontendPort", &i.FrontendPort) + delete(rawMsg, key) + case "inboundNatRuleName": + err = unpopulate(val, "InboundNatRuleName", &i.InboundNatRuleName) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &i.Protocol) + 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 InboundNatRulePropertiesFormat. +func (i InboundNatRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", i.BackendAddressPool) + populate(objectMap, "backendIPConfiguration", i.BackendIPConfiguration) + populate(objectMap, "backendPort", i.BackendPort) + populate(objectMap, "enableFloatingIP", i.EnableFloatingIP) + populate(objectMap, "enableTcpReset", i.EnableTCPReset) + populate(objectMap, "frontendIPConfiguration", i.FrontendIPConfiguration) + populate(objectMap, "frontendPort", i.FrontendPort) + populate(objectMap, "frontendPortRangeEnd", i.FrontendPortRangeEnd) + populate(objectMap, "frontendPortRangeStart", i.FrontendPortRangeStart) + populate(objectMap, "idleTimeoutInMinutes", i.IdleTimeoutInMinutes) + populate(objectMap, "protocol", i.Protocol) + populate(objectMap, "provisioningState", i.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundNatRulePropertiesFormat. +func (i *InboundNatRulePropertiesFormat) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &i.BackendAddressPool) + delete(rawMsg, key) + case "backendIPConfiguration": + err = unpopulate(val, "BackendIPConfiguration", &i.BackendIPConfiguration) + delete(rawMsg, key) + case "backendPort": + err = unpopulate(val, "BackendPort", &i.BackendPort) + delete(rawMsg, key) + case "enableFloatingIP": + err = unpopulate(val, "EnableFloatingIP", &i.EnableFloatingIP) + delete(rawMsg, key) + case "enableTcpReset": + err = unpopulate(val, "EnableTCPReset", &i.EnableTCPReset) + delete(rawMsg, key) + case "frontendIPConfiguration": + err = unpopulate(val, "FrontendIPConfiguration", &i.FrontendIPConfiguration) + delete(rawMsg, key) + case "frontendPort": + err = unpopulate(val, "FrontendPort", &i.FrontendPort) + delete(rawMsg, key) + case "frontendPortRangeEnd": + err = unpopulate(val, "FrontendPortRangeEnd", &i.FrontendPortRangeEnd) + delete(rawMsg, key) + case "frontendPortRangeStart": + err = unpopulate(val, "FrontendPortRangeStart", &i.FrontendPortRangeStart) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &i.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &i.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + 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 InboundSecurityRule. +func (i InboundSecurityRule) 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 InboundSecurityRule. +func (i *InboundSecurityRule) UnmarshalJSON(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 InboundSecurityRuleProperties. +func (i InboundSecurityRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "rules", i.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundSecurityRuleProperties. +func (i *InboundSecurityRuleProperties) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &i.Rules) + 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 InboundSecurityRules. +func (i InboundSecurityRules) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationPortRange", i.DestinationPortRange) + populate(objectMap, "protocol", i.Protocol) + populate(objectMap, "sourceAddressPrefix", i.SourceAddressPrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InboundSecurityRules. +func (i *InboundSecurityRules) UnmarshalJSON(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 "destinationPortRange": + err = unpopulate(val, "DestinationPortRange", &i.DestinationPortRange) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &i.Protocol) + delete(rawMsg, key) + case "sourceAddressPrefix": + err = unpopulate(val, "SourceAddressPrefix", &i.SourceAddressPrefix) + 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 IntentPolicy. +func (i IntentPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", i.Etag) + populate(objectMap, "id", i.ID) + populate(objectMap, "location", i.Location) + populate(objectMap, "name", i.Name) + populate(objectMap, "tags", i.Tags) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IntentPolicy. +func (i *IntentPolicy) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &i.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &i.Tags) + 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 IntentPolicyConfiguration. +func (i IntentPolicyConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkIntentPolicyName", i.NetworkIntentPolicyName) + populate(objectMap, "sourceNetworkIntentPolicy", i.SourceNetworkIntentPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IntentPolicyConfiguration. +func (i *IntentPolicyConfiguration) UnmarshalJSON(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 "networkIntentPolicyName": + err = unpopulate(val, "NetworkIntentPolicyName", &i.NetworkIntentPolicyName) + delete(rawMsg, key) + case "sourceNetworkIntentPolicy": + err = unpopulate(val, "SourceNetworkIntentPolicy", &i.SourceNetworkIntentPolicy) + 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 Interface. +func (i Interface) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", i.Etag) + populate(objectMap, "extendedLocation", i.ExtendedLocation) + populate(objectMap, "id", i.ID) + populate(objectMap, "location", i.Location) + populate(objectMap, "name", i.Name) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "tags", i.Tags) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Interface. +func (i *Interface) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &i.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &i.Location) + 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 "tags": + err = unpopulate(val, "Tags", &i.Tags) + 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 InterfaceAssociation. +func (i InterfaceAssociation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", i.ID) + populate(objectMap, "securityRules", i.SecurityRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceAssociation. +func (i *InterfaceAssociation) UnmarshalJSON(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 "securityRules": + err = unpopulate(val, "SecurityRules", &i.SecurityRules) + 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 InterfaceDNSSettings. +func (i InterfaceDNSSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedDnsServers", i.AppliedDNSServers) + populate(objectMap, "dnsServers", i.DNSServers) + populate(objectMap, "internalDnsNameLabel", i.InternalDNSNameLabel) + populate(objectMap, "internalDomainNameSuffix", i.InternalDomainNameSuffix) + populate(objectMap, "internalFqdn", i.InternalFqdn) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceDNSSettings. +func (i *InterfaceDNSSettings) UnmarshalJSON(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 "appliedDnsServers": + err = unpopulate(val, "AppliedDNSServers", &i.AppliedDNSServers) + delete(rawMsg, key) + case "dnsServers": + err = unpopulate(val, "DNSServers", &i.DNSServers) + delete(rawMsg, key) + case "internalDnsNameLabel": + err = unpopulate(val, "InternalDNSNameLabel", &i.InternalDNSNameLabel) + delete(rawMsg, key) + case "internalDomainNameSuffix": + err = unpopulate(val, "InternalDomainNameSuffix", &i.InternalDomainNameSuffix) + delete(rawMsg, key) + case "internalFqdn": + err = unpopulate(val, "InternalFqdn", &i.InternalFqdn) + 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 InterfaceIPConfiguration. +func (i InterfaceIPConfiguration) 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 InterfaceIPConfiguration. +func (i *InterfaceIPConfiguration) UnmarshalJSON(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 InterfaceIPConfigurationListResult. +func (i InterfaceIPConfigurationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceIPConfigurationListResult. +func (i *InterfaceIPConfigurationListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 InterfaceIPConfigurationPrivateLinkConnectionProperties. +func (i InterfaceIPConfigurationPrivateLinkConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fqdns", i.Fqdns) + populate(objectMap, "groupId", i.GroupID) + populate(objectMap, "requiredMemberName", i.RequiredMemberName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceIPConfigurationPrivateLinkConnectionProperties. +func (i *InterfaceIPConfigurationPrivateLinkConnectionProperties) UnmarshalJSON(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 "fqdns": + err = unpopulate(val, "Fqdns", &i.Fqdns) + delete(rawMsg, key) + case "groupId": + err = unpopulate(val, "GroupID", &i.GroupID) + delete(rawMsg, key) + case "requiredMemberName": + err = unpopulate(val, "RequiredMemberName", &i.RequiredMemberName) + 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 InterfaceIPConfigurationPropertiesFormat. +func (i InterfaceIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationGatewayBackendAddressPools", i.ApplicationGatewayBackendAddressPools) + populate(objectMap, "applicationSecurityGroups", i.ApplicationSecurityGroups) + populate(objectMap, "gatewayLoadBalancer", i.GatewayLoadBalancer) + populate(objectMap, "loadBalancerBackendAddressPools", i.LoadBalancerBackendAddressPools) + populate(objectMap, "loadBalancerInboundNatRules", i.LoadBalancerInboundNatRules) + populate(objectMap, "primary", i.Primary) + populate(objectMap, "privateIPAddress", i.PrivateIPAddress) + populate(objectMap, "privateIPAddressVersion", i.PrivateIPAddressVersion) + populate(objectMap, "privateIPAllocationMethod", i.PrivateIPAllocationMethod) + populate(objectMap, "privateLinkConnectionProperties", i.PrivateLinkConnectionProperties) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "publicIPAddress", i.PublicIPAddress) + populate(objectMap, "subnet", i.Subnet) + populate(objectMap, "virtualNetworkTaps", i.VirtualNetworkTaps) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceIPConfigurationPropertiesFormat. +func (i *InterfaceIPConfigurationPropertiesFormat) UnmarshalJSON(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 "applicationGatewayBackendAddressPools": + err = unpopulate(val, "ApplicationGatewayBackendAddressPools", &i.ApplicationGatewayBackendAddressPools) + delete(rawMsg, key) + case "applicationSecurityGroups": + err = unpopulate(val, "ApplicationSecurityGroups", &i.ApplicationSecurityGroups) + delete(rawMsg, key) + case "gatewayLoadBalancer": + err = unpopulate(val, "GatewayLoadBalancer", &i.GatewayLoadBalancer) + delete(rawMsg, key) + case "loadBalancerBackendAddressPools": + err = unpopulate(val, "LoadBalancerBackendAddressPools", &i.LoadBalancerBackendAddressPools) + delete(rawMsg, key) + case "loadBalancerInboundNatRules": + err = unpopulate(val, "LoadBalancerInboundNatRules", &i.LoadBalancerInboundNatRules) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &i.Primary) + delete(rawMsg, key) + case "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &i.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAddressVersion": + err = unpopulate(val, "PrivateIPAddressVersion", &i.PrivateIPAddressVersion) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &i.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "privateLinkConnectionProperties": + err = unpopulate(val, "PrivateLinkConnectionProperties", &i.PrivateLinkConnectionProperties) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &i.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &i.Subnet) + delete(rawMsg, key) + case "virtualNetworkTaps": + err = unpopulate(val, "VirtualNetworkTaps", &i.VirtualNetworkTaps) + 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 InterfaceListResult. +func (i InterfaceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceListResult. +func (i *InterfaceListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 InterfaceLoadBalancerListResult. +func (i InterfaceLoadBalancerListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceLoadBalancerListResult. +func (i *InterfaceLoadBalancerListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 InterfacePropertiesFormat. +func (i InterfacePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "auxiliaryMode", i.AuxiliaryMode) + populate(objectMap, "auxiliarySku", i.AuxiliarySKU) + populate(objectMap, "dnsSettings", i.DNSSettings) + populate(objectMap, "disableTcpStateTracking", i.DisableTCPStateTracking) + populate(objectMap, "dscpConfiguration", i.DscpConfiguration) + populate(objectMap, "enableAcceleratedNetworking", i.EnableAcceleratedNetworking) + populate(objectMap, "enableIPForwarding", i.EnableIPForwarding) + populate(objectMap, "hostedWorkloads", i.HostedWorkloads) + populate(objectMap, "ipConfigurations", i.IPConfigurations) + populate(objectMap, "macAddress", i.MacAddress) + populate(objectMap, "migrationPhase", i.MigrationPhase) + populate(objectMap, "networkSecurityGroup", i.NetworkSecurityGroup) + populate(objectMap, "nicType", i.NicType) + populate(objectMap, "primary", i.Primary) + populate(objectMap, "privateEndpoint", i.PrivateEndpoint) + populate(objectMap, "privateLinkService", i.PrivateLinkService) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "resourceGuid", i.ResourceGUID) + populate(objectMap, "tapConfigurations", i.TapConfigurations) + populate(objectMap, "virtualMachine", i.VirtualMachine) + populate(objectMap, "vnetEncryptionSupported", i.VnetEncryptionSupported) + populate(objectMap, "workloadType", i.WorkloadType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfacePropertiesFormat. +func (i *InterfacePropertiesFormat) UnmarshalJSON(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 "auxiliaryMode": + err = unpopulate(val, "AuxiliaryMode", &i.AuxiliaryMode) + delete(rawMsg, key) + case "auxiliarySku": + err = unpopulate(val, "AuxiliarySKU", &i.AuxiliarySKU) + delete(rawMsg, key) + case "dnsSettings": + err = unpopulate(val, "DNSSettings", &i.DNSSettings) + delete(rawMsg, key) + case "disableTcpStateTracking": + err = unpopulate(val, "DisableTCPStateTracking", &i.DisableTCPStateTracking) + delete(rawMsg, key) + case "dscpConfiguration": + err = unpopulate(val, "DscpConfiguration", &i.DscpConfiguration) + delete(rawMsg, key) + case "enableAcceleratedNetworking": + err = unpopulate(val, "EnableAcceleratedNetworking", &i.EnableAcceleratedNetworking) + delete(rawMsg, key) + case "enableIPForwarding": + err = unpopulate(val, "EnableIPForwarding", &i.EnableIPForwarding) + delete(rawMsg, key) + case "hostedWorkloads": + err = unpopulate(val, "HostedWorkloads", &i.HostedWorkloads) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &i.IPConfigurations) + delete(rawMsg, key) + case "macAddress": + err = unpopulate(val, "MacAddress", &i.MacAddress) + delete(rawMsg, key) + case "migrationPhase": + err = unpopulate(val, "MigrationPhase", &i.MigrationPhase) + delete(rawMsg, key) + case "networkSecurityGroup": + err = unpopulate(val, "NetworkSecurityGroup", &i.NetworkSecurityGroup) + delete(rawMsg, key) + case "nicType": + err = unpopulate(val, "NicType", &i.NicType) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &i.Primary) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &i.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkService": + err = unpopulate(val, "PrivateLinkService", &i.PrivateLinkService) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &i.ResourceGUID) + delete(rawMsg, key) + case "tapConfigurations": + err = unpopulate(val, "TapConfigurations", &i.TapConfigurations) + delete(rawMsg, key) + case "virtualMachine": + err = unpopulate(val, "VirtualMachine", &i.VirtualMachine) + delete(rawMsg, key) + case "vnetEncryptionSupported": + err = unpopulate(val, "VnetEncryptionSupported", &i.VnetEncryptionSupported) + delete(rawMsg, key) + case "workloadType": + err = unpopulate(val, "WorkloadType", &i.WorkloadType) + 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 InterfaceTapConfiguration. +func (i InterfaceTapConfiguration) 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 InterfaceTapConfiguration. +func (i *InterfaceTapConfiguration) UnmarshalJSON(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 InterfaceTapConfigurationListResult. +func (i InterfaceTapConfigurationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceTapConfigurationListResult. +func (i *InterfaceTapConfigurationListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, 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 InterfaceTapConfigurationPropertiesFormat. +func (i InterfaceTapConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "virtualNetworkTap", i.VirtualNetworkTap) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InterfaceTapConfigurationPropertiesFormat. +func (i *InterfaceTapConfigurationPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "virtualNetworkTap": + err = unpopulate(val, "VirtualNetworkTap", &i.VirtualNetworkTap) + 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 ListHubRouteTablesResult. +func (l ListHubRouteTablesResult) 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 ListHubRouteTablesResult. +func (l *ListHubRouteTablesResult) UnmarshalJSON(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 ListHubVirtualNetworkConnectionsResult. +func (l ListHubVirtualNetworkConnectionsResult) 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 ListHubVirtualNetworkConnectionsResult. +func (l *ListHubVirtualNetworkConnectionsResult) UnmarshalJSON(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 ListP2SVPNGatewaysResult. +func (l ListP2SVPNGatewaysResult) 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 ListP2SVPNGatewaysResult. +func (l *ListP2SVPNGatewaysResult) UnmarshalJSON(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 ListRouteMapsResult. +func (l ListRouteMapsResult) 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 ListRouteMapsResult. +func (l *ListRouteMapsResult) UnmarshalJSON(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 ListRoutingIntentResult. +func (l ListRoutingIntentResult) 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 ListRoutingIntentResult. +func (l *ListRoutingIntentResult) UnmarshalJSON(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 ListVPNConnectionsResult. +func (l ListVPNConnectionsResult) 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 ListVPNConnectionsResult. +func (l *ListVPNConnectionsResult) UnmarshalJSON(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 ListVPNGatewayNatRulesResult. +func (l ListVPNGatewayNatRulesResult) 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 ListVPNGatewayNatRulesResult. +func (l *ListVPNGatewayNatRulesResult) UnmarshalJSON(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 ListVPNGatewaysResult. +func (l ListVPNGatewaysResult) 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 ListVPNGatewaysResult. +func (l *ListVPNGatewaysResult) UnmarshalJSON(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 ListVPNServerConfigurationPolicyGroupsResult. +func (l ListVPNServerConfigurationPolicyGroupsResult) 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 ListVPNServerConfigurationPolicyGroupsResult. +func (l *ListVPNServerConfigurationPolicyGroupsResult) UnmarshalJSON(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 ListVPNServerConfigurationsResult. +func (l ListVPNServerConfigurationsResult) 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 ListVPNServerConfigurationsResult. +func (l *ListVPNServerConfigurationsResult) UnmarshalJSON(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 ListVPNSiteLinkConnectionsResult. +func (l ListVPNSiteLinkConnectionsResult) 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 ListVPNSiteLinkConnectionsResult. +func (l *ListVPNSiteLinkConnectionsResult) UnmarshalJSON(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 ListVPNSiteLinksResult. +func (l ListVPNSiteLinksResult) 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 ListVPNSiteLinksResult. +func (l *ListVPNSiteLinksResult) UnmarshalJSON(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 ListVPNSitesResult. +func (l ListVPNSitesResult) 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 ListVPNSitesResult. +func (l *ListVPNSitesResult) UnmarshalJSON(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 ListVirtualHubBgpConnectionResults. +func (l ListVirtualHubBgpConnectionResults) 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 ListVirtualHubBgpConnectionResults. +func (l *ListVirtualHubBgpConnectionResults) UnmarshalJSON(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 ListVirtualHubIPConfigurationResults. +func (l ListVirtualHubIPConfigurationResults) 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 ListVirtualHubIPConfigurationResults. +func (l *ListVirtualHubIPConfigurationResults) UnmarshalJSON(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 ListVirtualHubRouteTableV2SResult. +func (l ListVirtualHubRouteTableV2SResult) 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 ListVirtualHubRouteTableV2SResult. +func (l *ListVirtualHubRouteTableV2SResult) UnmarshalJSON(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 ListVirtualHubsResult. +func (l ListVirtualHubsResult) 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 ListVirtualHubsResult. +func (l *ListVirtualHubsResult) UnmarshalJSON(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 ListVirtualNetworkGatewayNatRulesResult. +func (l ListVirtualNetworkGatewayNatRulesResult) 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 ListVirtualNetworkGatewayNatRulesResult. +func (l *ListVirtualNetworkGatewayNatRulesResult) UnmarshalJSON(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 ListVirtualWANsResult. +func (l ListVirtualWANsResult) 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 ListVirtualWANsResult. +func (l *ListVirtualWANsResult) UnmarshalJSON(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 LoadBalancer. +func (l LoadBalancer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", l.Etag) + populate(objectMap, "extendedLocation", l.ExtendedLocation) + populate(objectMap, "id", l.ID) + populate(objectMap, "location", l.Location) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "sku", l.SKU) + populate(objectMap, "tags", l.Tags) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancer. +func (l *LoadBalancer) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &l.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &l.Location) + 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 "sku": + err = unpopulate(val, "SKU", &l.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &l.Tags) + 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 LoadBalancerBackendAddress. +func (l LoadBalancerBackendAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerBackendAddress. +func (l *LoadBalancerBackendAddress) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + 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 LoadBalancerBackendAddressPoolListResult. +func (l LoadBalancerBackendAddressPoolListResult) 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 LoadBalancerBackendAddressPoolListResult. +func (l *LoadBalancerBackendAddressPoolListResult) UnmarshalJSON(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 LoadBalancerBackendAddressPropertiesFormat. +func (l LoadBalancerBackendAddressPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminState", l.AdminState) + populate(objectMap, "ipAddress", l.IPAddress) + populate(objectMap, "inboundNatRulesPortMapping", l.InboundNatRulesPortMapping) + populate(objectMap, "loadBalancerFrontendIPConfiguration", l.LoadBalancerFrontendIPConfiguration) + populate(objectMap, "networkInterfaceIPConfiguration", l.NetworkInterfaceIPConfiguration) + populate(objectMap, "subnet", l.Subnet) + populate(objectMap, "virtualNetwork", l.VirtualNetwork) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerBackendAddressPropertiesFormat. +func (l *LoadBalancerBackendAddressPropertiesFormat) UnmarshalJSON(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 "adminState": + err = unpopulate(val, "AdminState", &l.AdminState) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &l.IPAddress) + delete(rawMsg, key) + case "inboundNatRulesPortMapping": + err = unpopulate(val, "InboundNatRulesPortMapping", &l.InboundNatRulesPortMapping) + delete(rawMsg, key) + case "loadBalancerFrontendIPConfiguration": + err = unpopulate(val, "LoadBalancerFrontendIPConfiguration", &l.LoadBalancerFrontendIPConfiguration) + delete(rawMsg, key) + case "networkInterfaceIPConfiguration": + err = unpopulate(val, "NetworkInterfaceIPConfiguration", &l.NetworkInterfaceIPConfiguration) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &l.Subnet) + delete(rawMsg, key) + case "virtualNetwork": + err = unpopulate(val, "VirtualNetwork", &l.VirtualNetwork) + 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 LoadBalancerFrontendIPConfigurationListResult. +func (l LoadBalancerFrontendIPConfigurationListResult) 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 LoadBalancerFrontendIPConfigurationListResult. +func (l *LoadBalancerFrontendIPConfigurationListResult) UnmarshalJSON(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 LoadBalancerListResult. +func (l LoadBalancerListResult) 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 LoadBalancerListResult. +func (l *LoadBalancerListResult) UnmarshalJSON(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 LoadBalancerLoadBalancingRuleListResult. +func (l LoadBalancerLoadBalancingRuleListResult) 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 LoadBalancerLoadBalancingRuleListResult. +func (l *LoadBalancerLoadBalancingRuleListResult) UnmarshalJSON(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 LoadBalancerOutboundRuleListResult. +func (l LoadBalancerOutboundRuleListResult) 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 LoadBalancerOutboundRuleListResult. +func (l *LoadBalancerOutboundRuleListResult) UnmarshalJSON(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 LoadBalancerProbeListResult. +func (l LoadBalancerProbeListResult) 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 LoadBalancerProbeListResult. +func (l *LoadBalancerProbeListResult) UnmarshalJSON(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 LoadBalancerPropertiesFormat. +func (l LoadBalancerPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPools", l.BackendAddressPools) + populate(objectMap, "frontendIPConfigurations", l.FrontendIPConfigurations) + populate(objectMap, "inboundNatPools", l.InboundNatPools) + populate(objectMap, "inboundNatRules", l.InboundNatRules) + populate(objectMap, "loadBalancingRules", l.LoadBalancingRules) + populate(objectMap, "outboundRules", l.OutboundRules) + populate(objectMap, "probes", l.Probes) + populate(objectMap, "provisioningState", l.ProvisioningState) + populate(objectMap, "resourceGuid", l.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerPropertiesFormat. +func (l *LoadBalancerPropertiesFormat) UnmarshalJSON(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 "backendAddressPools": + err = unpopulate(val, "BackendAddressPools", &l.BackendAddressPools) + delete(rawMsg, key) + case "frontendIPConfigurations": + err = unpopulate(val, "FrontendIPConfigurations", &l.FrontendIPConfigurations) + delete(rawMsg, key) + case "inboundNatPools": + err = unpopulate(val, "InboundNatPools", &l.InboundNatPools) + delete(rawMsg, key) + case "inboundNatRules": + err = unpopulate(val, "InboundNatRules", &l.InboundNatRules) + delete(rawMsg, key) + case "loadBalancingRules": + err = unpopulate(val, "LoadBalancingRules", &l.LoadBalancingRules) + delete(rawMsg, key) + case "outboundRules": + err = unpopulate(val, "OutboundRules", &l.OutboundRules) + delete(rawMsg, key) + case "probes": + err = unpopulate(val, "Probes", &l.Probes) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &l.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &l.ResourceGUID) + 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 LoadBalancerSKU. +func (l LoadBalancerSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", l.Name) + populate(objectMap, "tier", l.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerSKU. +func (l *LoadBalancerSKU) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &l.Tier) + 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 LoadBalancerVipSwapRequest. +func (l LoadBalancerVipSwapRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "frontendIPConfigurations", l.FrontendIPConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerVipSwapRequest. +func (l *LoadBalancerVipSwapRequest) UnmarshalJSON(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 "frontendIPConfigurations": + err = unpopulate(val, "FrontendIPConfigurations", &l.FrontendIPConfigurations) + 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 LoadBalancerVipSwapRequestFrontendIPConfiguration. +func (l LoadBalancerVipSwapRequestFrontendIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "properties", l.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerVipSwapRequestFrontendIPConfiguration. +func (l *LoadBalancerVipSwapRequestFrontendIPConfiguration) UnmarshalJSON(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 "properties": + err = unpopulate(val, "Properties", &l.Properties) + 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 LoadBalancerVipSwapRequestFrontendIPConfigurationProperties. +func (l LoadBalancerVipSwapRequestFrontendIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "publicIPAddress", l.PublicIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerVipSwapRequestFrontendIPConfigurationProperties. +func (l *LoadBalancerVipSwapRequestFrontendIPConfigurationProperties) UnmarshalJSON(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 "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &l.PublicIPAddress) + 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 LoadBalancingRule. +func (l LoadBalancingRule) 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 LoadBalancingRule. +func (l *LoadBalancingRule) UnmarshalJSON(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 LoadBalancingRulePropertiesFormat. +func (l LoadBalancingRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendAddressPool", l.BackendAddressPool) + populate(objectMap, "backendAddressPools", l.BackendAddressPools) + populate(objectMap, "backendPort", l.BackendPort) + populate(objectMap, "disableOutboundSnat", l.DisableOutboundSnat) + populate(objectMap, "enableFloatingIP", l.EnableFloatingIP) + populate(objectMap, "enableTcpReset", l.EnableTCPReset) + populate(objectMap, "frontendIPConfiguration", l.FrontendIPConfiguration) + populate(objectMap, "frontendPort", l.FrontendPort) + populate(objectMap, "idleTimeoutInMinutes", l.IdleTimeoutInMinutes) + populate(objectMap, "loadDistribution", l.LoadDistribution) + populate(objectMap, "probe", l.Probe) + populate(objectMap, "protocol", l.Protocol) + populate(objectMap, "provisioningState", l.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancingRulePropertiesFormat. +func (l *LoadBalancingRulePropertiesFormat) UnmarshalJSON(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 "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &l.BackendAddressPool) + delete(rawMsg, key) + case "backendAddressPools": + err = unpopulate(val, "BackendAddressPools", &l.BackendAddressPools) + delete(rawMsg, key) + case "backendPort": + err = unpopulate(val, "BackendPort", &l.BackendPort) + delete(rawMsg, key) + case "disableOutboundSnat": + err = unpopulate(val, "DisableOutboundSnat", &l.DisableOutboundSnat) + delete(rawMsg, key) + case "enableFloatingIP": + err = unpopulate(val, "EnableFloatingIP", &l.EnableFloatingIP) + delete(rawMsg, key) + case "enableTcpReset": + err = unpopulate(val, "EnableTCPReset", &l.EnableTCPReset) + delete(rawMsg, key) + case "frontendIPConfiguration": + err = unpopulate(val, "FrontendIPConfiguration", &l.FrontendIPConfiguration) + delete(rawMsg, key) + case "frontendPort": + err = unpopulate(val, "FrontendPort", &l.FrontendPort) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &l.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "loadDistribution": + err = unpopulate(val, "LoadDistribution", &l.LoadDistribution) + delete(rawMsg, key) + case "probe": + err = unpopulate(val, "Probe", &l.Probe) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &l.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &l.ProvisioningState) + 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 LocalNetworkGateway. +func (l LocalNetworkGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", l.Etag) + populate(objectMap, "id", l.ID) + populate(objectMap, "location", l.Location) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "tags", l.Tags) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocalNetworkGateway. +func (l *LocalNetworkGateway) UnmarshalJSON(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 "location": + err = unpopulate(val, "Location", &l.Location) + 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 "tags": + err = unpopulate(val, "Tags", &l.Tags) + 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 LocalNetworkGatewayListResult. +func (l LocalNetworkGatewayListResult) 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 LocalNetworkGatewayListResult. +func (l *LocalNetworkGatewayListResult) UnmarshalJSON(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 LocalNetworkGatewayPropertiesFormat. +func (l LocalNetworkGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bgpSettings", l.BgpSettings) + populate(objectMap, "fqdn", l.Fqdn) + populate(objectMap, "gatewayIpAddress", l.GatewayIPAddress) + populate(objectMap, "localNetworkAddressSpace", l.LocalNetworkAddressSpace) + populate(objectMap, "provisioningState", l.ProvisioningState) + populate(objectMap, "resourceGuid", l.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocalNetworkGatewayPropertiesFormat. +func (l *LocalNetworkGatewayPropertiesFormat) UnmarshalJSON(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 "bgpSettings": + err = unpopulate(val, "BgpSettings", &l.BgpSettings) + delete(rawMsg, key) + case "fqdn": + err = unpopulate(val, "Fqdn", &l.Fqdn) + delete(rawMsg, key) + case "gatewayIpAddress": + err = unpopulate(val, "GatewayIPAddress", &l.GatewayIPAddress) + delete(rawMsg, key) + case "localNetworkAddressSpace": + err = unpopulate(val, "LocalNetworkAddressSpace", &l.LocalNetworkAddressSpace) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &l.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &l.ResourceGUID) + 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 ManagedRuleGroupOverride. +func (m ManagedRuleGroupOverride) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleGroupName", m.RuleGroupName) + populate(objectMap, "rules", m.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedRuleGroupOverride. +func (m *ManagedRuleGroupOverride) UnmarshalJSON(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 "ruleGroupName": + err = unpopulate(val, "RuleGroupName", &m.RuleGroupName) + delete(rawMsg, 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 ManagedRuleOverride. +func (m ManagedRuleOverride) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", m.Action) + populate(objectMap, "ruleId", m.RuleID) + populate(objectMap, "state", m.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedRuleOverride. +func (m *ManagedRuleOverride) UnmarshalJSON(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 "ruleId": + err = unpopulate(val, "RuleID", &m.RuleID) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &m.State) + 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 ManagedRuleSet. +func (m ManagedRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ruleGroupOverrides", m.RuleGroupOverrides) + populate(objectMap, "ruleSetType", m.RuleSetType) + populate(objectMap, "ruleSetVersion", m.RuleSetVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedRuleSet. +func (m *ManagedRuleSet) UnmarshalJSON(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 "ruleGroupOverrides": + err = unpopulate(val, "RuleGroupOverrides", &m.RuleGroupOverrides) + delete(rawMsg, key) + case "ruleSetType": + err = unpopulate(val, "RuleSetType", &m.RuleSetType) + delete(rawMsg, key) + case "ruleSetVersion": + err = unpopulate(val, "RuleSetVersion", &m.RuleSetVersion) + 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 ManagedRulesDefinition. +func (m ManagedRulesDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exclusions", m.Exclusions) + populate(objectMap, "managedRuleSets", m.ManagedRuleSets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedRulesDefinition. +func (m *ManagedRulesDefinition) UnmarshalJSON(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 "exclusions": + err = unpopulate(val, "Exclusions", &m.Exclusions) + delete(rawMsg, key) + case "managedRuleSets": + err = unpopulate(val, "ManagedRuleSets", &m.ManagedRuleSets) + 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 Manager. +func (m Manager) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", m.Etag) + populate(objectMap, "id", m.ID) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + 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 Manager. +func (m *Manager) UnmarshalJSON(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 "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 "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 ManagerCommit. +func (m ManagerCommit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commitId", m.CommitID) + populate(objectMap, "commitType", m.CommitType) + populate(objectMap, "configurationIds", m.ConfigurationIDs) + populate(objectMap, "targetLocations", m.TargetLocations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerCommit. +func (m *ManagerCommit) UnmarshalJSON(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 "commitId": + err = unpopulate(val, "CommitID", &m.CommitID) + delete(rawMsg, key) + case "commitType": + err = unpopulate(val, "CommitType", &m.CommitType) + delete(rawMsg, key) + case "configurationIds": + err = unpopulate(val, "ConfigurationIDs", &m.ConfigurationIDs) + delete(rawMsg, key) + case "targetLocations": + err = unpopulate(val, "TargetLocations", &m.TargetLocations) + 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 ManagerConnection. +func (m ManagerConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", m.Etag) + 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 ManagerConnection. +func (m *ManagerConnection) UnmarshalJSON(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 "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 ManagerConnectionListResult. +func (m ManagerConnectionListResult) 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 ManagerConnectionListResult. +func (m *ManagerConnectionListResult) UnmarshalJSON(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 ManagerConnectionProperties. +func (m ManagerConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionState", m.ConnectionState) + populate(objectMap, "description", m.Description) + populate(objectMap, "networkManagerId", m.NetworkManagerID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerConnectionProperties. +func (m *ManagerConnectionProperties) UnmarshalJSON(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 "connectionState": + err = unpopulate(val, "ConnectionState", &m.ConnectionState) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &m.Description) + delete(rawMsg, key) + case "networkManagerId": + err = unpopulate(val, "NetworkManagerID", &m.NetworkManagerID) + 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 ManagerDeploymentStatus. +func (m ManagerDeploymentStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "commitTime", m.CommitTime) + populate(objectMap, "configurationIds", m.ConfigurationIDs) + populate(objectMap, "deploymentStatus", m.DeploymentStatus) + populate(objectMap, "deploymentType", m.DeploymentType) + populate(objectMap, "errorMessage", m.ErrorMessage) + populate(objectMap, "region", m.Region) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerDeploymentStatus. +func (m *ManagerDeploymentStatus) UnmarshalJSON(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 "commitTime": + err = unpopulateDateTimeRFC3339(val, "CommitTime", &m.CommitTime) + delete(rawMsg, key) + case "configurationIds": + err = unpopulate(val, "ConfigurationIDs", &m.ConfigurationIDs) + delete(rawMsg, key) + case "deploymentStatus": + err = unpopulate(val, "DeploymentStatus", &m.DeploymentStatus) + delete(rawMsg, key) + case "deploymentType": + err = unpopulate(val, "DeploymentType", &m.DeploymentType) + delete(rawMsg, key) + case "errorMessage": + err = unpopulate(val, "ErrorMessage", &m.ErrorMessage) + delete(rawMsg, key) + case "region": + err = unpopulate(val, "Region", &m.Region) + 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 ManagerDeploymentStatusListResult. +func (m ManagerDeploymentStatusListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipToken", m.SkipToken) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerDeploymentStatusListResult. +func (m *ManagerDeploymentStatusListResult) UnmarshalJSON(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 "skipToken": + err = unpopulate(val, "SkipToken", &m.SkipToken) + 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 ManagerDeploymentStatusParameter. +func (m ManagerDeploymentStatusParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deploymentTypes", m.DeploymentTypes) + populate(objectMap, "regions", m.Regions) + populate(objectMap, "skipToken", m.SkipToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerDeploymentStatusParameter. +func (m *ManagerDeploymentStatusParameter) UnmarshalJSON(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 "deploymentTypes": + err = unpopulate(val, "DeploymentTypes", &m.DeploymentTypes) + delete(rawMsg, key) + case "regions": + err = unpopulate(val, "Regions", &m.Regions) + delete(rawMsg, key) + case "skipToken": + err = unpopulate(val, "SkipToken", &m.SkipToken) + 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 ManagerEffectiveConnectivityConfigurationListResult. +func (m ManagerEffectiveConnectivityConfigurationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipToken", m.SkipToken) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerEffectiveConnectivityConfigurationListResult. +func (m *ManagerEffectiveConnectivityConfigurationListResult) UnmarshalJSON(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 "skipToken": + err = unpopulate(val, "SkipToken", &m.SkipToken) + 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 ManagerEffectiveSecurityAdminRulesListResult. +func (m ManagerEffectiveSecurityAdminRulesListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipToken", m.SkipToken) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerEffectiveSecurityAdminRulesListResult. +func (m *ManagerEffectiveSecurityAdminRulesListResult) UnmarshalJSON(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 "skipToken": + err = unpopulate(val, "SkipToken", &m.SkipToken) + delete(rawMsg, key) + case "value": + m.Value, err = unmarshalEffectiveBaseSecurityAdminRuleClassificationArray(val) + 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 ManagerListResult. +func (m ManagerListResult) 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 ManagerListResult. +func (m *ManagerListResult) UnmarshalJSON(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 ManagerProperties. +func (m ManagerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", m.Description) + populate(objectMap, "networkManagerScopeAccesses", m.NetworkManagerScopeAccesses) + populate(objectMap, "networkManagerScopes", m.NetworkManagerScopes) + populate(objectMap, "provisioningState", m.ProvisioningState) + populate(objectMap, "resourceGuid", m.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerProperties. +func (m *ManagerProperties) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &m.Description) + delete(rawMsg, key) + case "networkManagerScopeAccesses": + err = unpopulate(val, "NetworkManagerScopeAccesses", &m.NetworkManagerScopeAccesses) + delete(rawMsg, key) + case "networkManagerScopes": + err = unpopulate(val, "NetworkManagerScopes", &m.NetworkManagerScopes) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &m.ResourceGUID) + 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 ManagerPropertiesNetworkManagerScopes. +func (m ManagerPropertiesNetworkManagerScopes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "crossTenantScopes", m.CrossTenantScopes) + populate(objectMap, "managementGroups", m.ManagementGroups) + populate(objectMap, "subscriptions", m.Subscriptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerPropertiesNetworkManagerScopes. +func (m *ManagerPropertiesNetworkManagerScopes) UnmarshalJSON(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 "crossTenantScopes": + err = unpopulate(val, "CrossTenantScopes", &m.CrossTenantScopes) + delete(rawMsg, key) + case "managementGroups": + err = unpopulate(val, "ManagementGroups", &m.ManagementGroups) + delete(rawMsg, key) + case "subscriptions": + err = unpopulate(val, "Subscriptions", &m.Subscriptions) + 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 ManagerSecurityGroupItem. +func (m ManagerSecurityGroupItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkGroupId", m.NetworkGroupID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagerSecurityGroupItem. +func (m *ManagerSecurityGroupItem) UnmarshalJSON(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 "networkGroupId": + err = unpopulate(val, "NetworkGroupID", &m.NetworkGroupID) + 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 MatchCondition. +func (m MatchCondition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "matchValues", m.MatchValues) + populate(objectMap, "matchVariables", m.MatchVariables) + populate(objectMap, "negationConditon", m.NegationConditon) + populate(objectMap, "operator", m.Operator) + populate(objectMap, "transforms", m.Transforms) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MatchCondition. +func (m *MatchCondition) UnmarshalJSON(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 "matchValues": + err = unpopulate(val, "MatchValues", &m.MatchValues) + delete(rawMsg, key) + case "matchVariables": + err = unpopulate(val, "MatchVariables", &m.MatchVariables) + delete(rawMsg, key) + case "negationConditon": + err = unpopulate(val, "NegationConditon", &m.NegationConditon) + delete(rawMsg, key) + case "operator": + err = unpopulate(val, "Operator", &m.Operator) + delete(rawMsg, key) + case "transforms": + err = unpopulate(val, "Transforms", &m.Transforms) + 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 MatchVariable. +func (m MatchVariable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "selector", m.Selector) + populate(objectMap, "variableName", m.VariableName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MatchVariable. +func (m *MatchVariable) UnmarshalJSON(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 "selector": + err = unpopulate(val, "Selector", &m.Selector) + delete(rawMsg, key) + case "variableName": + err = unpopulate(val, "VariableName", &m.VariableName) + 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 MatchedRule. +func (m MatchedRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", m.Action) + populate(objectMap, "ruleName", m.RuleName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MatchedRule. +func (m *MatchedRule) UnmarshalJSON(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 "ruleName": + err = unpopulate(val, "RuleName", &m.RuleName) + 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, "availabilities", m.Availabilities) + populate(objectMap, "dimensions", m.Dimensions) + populate(objectMap, "displayDescription", m.DisplayDescription) + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "enableRegionalMdmAccount", m.EnableRegionalMdmAccount) + populate(objectMap, "fillGapWithZero", m.FillGapWithZero) + populate(objectMap, "isInternal", m.IsInternal) + populate(objectMap, "metricFilterPattern", m.MetricFilterPattern) + populate(objectMap, "name", m.Name) + populate(objectMap, "resourceIdDimensionNameOverride", m.ResourceIDDimensionNameOverride) + populate(objectMap, "sourceMdmAccount", m.SourceMdmAccount) + populate(objectMap, "sourceMdmNamespace", m.SourceMdmNamespace) + 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 "availabilities": + err = unpopulate(val, "Availabilities", &m.Availabilities) + 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 "enableRegionalMdmAccount": + err = unpopulate(val, "EnableRegionalMdmAccount", &m.EnableRegionalMdmAccount) + delete(rawMsg, key) + case "fillGapWithZero": + err = unpopulate(val, "FillGapWithZero", &m.FillGapWithZero) + delete(rawMsg, key) + case "isInternal": + err = unpopulate(val, "IsInternal", &m.IsInternal) + delete(rawMsg, key) + case "metricFilterPattern": + err = unpopulate(val, "MetricFilterPattern", &m.MetricFilterPattern) + 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 "sourceMdmAccount": + err = unpopulate(val, "SourceMdmAccount", &m.SourceMdmAccount) + delete(rawMsg, key) + case "sourceMdmNamespace": + err = unpopulate(val, "SourceMdmNamespace", &m.SourceMdmNamespace) + 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 MigrateLoadBalancerToIPBasedRequest. +func (m MigrateLoadBalancerToIPBasedRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pools", m.Pools) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MigrateLoadBalancerToIPBasedRequest. +func (m *MigrateLoadBalancerToIPBasedRequest) UnmarshalJSON(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 "pools": + err = unpopulate(val, "Pools", &m.Pools) + 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 MigratedPools. +func (m MigratedPools) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "migratedPools", m.MigratedPools) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MigratedPools. +func (m *MigratedPools) UnmarshalJSON(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 "migratedPools": + err = unpopulate(val, "MigratedPools", &m.MigratedPools) + 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 NatGateway. +func (n NatGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", n.Etag) + populate(objectMap, "id", n.ID) + populate(objectMap, "location", n.Location) + populate(objectMap, "name", n.Name) + populate(objectMap, "properties", n.Properties) + populate(objectMap, "sku", n.SKU) + populate(objectMap, "tags", n.Tags) + populate(objectMap, "type", n.Type) + populate(objectMap, "zones", n.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NatGateway. +func (n *NatGateway) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &n.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &n.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &n.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &n.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &n.Zones) + 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 NatGatewayListResult. +func (n NatGatewayListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NatGatewayListResult. +func (n *NatGatewayListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &n.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + 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 NatGatewayPropertiesFormat. +func (n NatGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "idleTimeoutInMinutes", n.IdleTimeoutInMinutes) + populate(objectMap, "provisioningState", n.ProvisioningState) + populate(objectMap, "publicIpAddresses", n.PublicIPAddresses) + populate(objectMap, "publicIpPrefixes", n.PublicIPPrefixes) + populate(objectMap, "resourceGuid", n.ResourceGUID) + populate(objectMap, "subnets", n.Subnets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NatGatewayPropertiesFormat. +func (n *NatGatewayPropertiesFormat) UnmarshalJSON(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 "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &n.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &n.ProvisioningState) + delete(rawMsg, key) + case "publicIpAddresses": + err = unpopulate(val, "PublicIPAddresses", &n.PublicIPAddresses) + delete(rawMsg, key) + case "publicIpPrefixes": + err = unpopulate(val, "PublicIPPrefixes", &n.PublicIPPrefixes) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &n.ResourceGUID) + delete(rawMsg, key) + case "subnets": + err = unpopulate(val, "Subnets", &n.Subnets) + 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 NatGatewaySKU. +func (n NatGatewaySKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NatGatewaySKU. +func (n *NatGatewaySKU) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &n.Name) + 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 NatRule. +func (n NatRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", n.Description) + populate(objectMap, "destinationAddresses", n.DestinationAddresses) + populate(objectMap, "destinationPorts", n.DestinationPorts) + populate(objectMap, "ipProtocols", n.IPProtocols) + populate(objectMap, "name", n.Name) + objectMap["ruleType"] = FirewallPolicyRuleTypeNatRule + populate(objectMap, "sourceAddresses", n.SourceAddresses) + populate(objectMap, "sourceIpGroups", n.SourceIPGroups) + populate(objectMap, "translatedAddress", n.TranslatedAddress) + populate(objectMap, "translatedFqdn", n.TranslatedFqdn) + populate(objectMap, "translatedPort", n.TranslatedPort) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NatRule. +func (n *NatRule) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &n.Description) + delete(rawMsg, key) + case "destinationAddresses": + err = unpopulate(val, "DestinationAddresses", &n.DestinationAddresses) + delete(rawMsg, key) + case "destinationPorts": + err = unpopulate(val, "DestinationPorts", &n.DestinationPorts) + delete(rawMsg, key) + case "ipProtocols": + err = unpopulate(val, "IPProtocols", &n.IPProtocols) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &n.RuleType) + delete(rawMsg, key) + case "sourceAddresses": + err = unpopulate(val, "SourceAddresses", &n.SourceAddresses) + delete(rawMsg, key) + case "sourceIpGroups": + err = unpopulate(val, "SourceIPGroups", &n.SourceIPGroups) + delete(rawMsg, key) + case "translatedAddress": + err = unpopulate(val, "TranslatedAddress", &n.TranslatedAddress) + delete(rawMsg, key) + case "translatedFqdn": + err = unpopulate(val, "TranslatedFqdn", &n.TranslatedFqdn) + delete(rawMsg, key) + case "translatedPort": + err = unpopulate(val, "TranslatedPort", &n.TranslatedPort) + 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 NatRulePortMapping. +func (n NatRulePortMapping) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backendPort", n.BackendPort) + populate(objectMap, "frontendPort", n.FrontendPort) + populate(objectMap, "inboundNatRuleName", n.InboundNatRuleName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NatRulePortMapping. +func (n *NatRulePortMapping) UnmarshalJSON(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 "backendPort": + err = unpopulate(val, "BackendPort", &n.BackendPort) + delete(rawMsg, key) + case "frontendPort": + err = unpopulate(val, "FrontendPort", &n.FrontendPort) + delete(rawMsg, key) + case "inboundNatRuleName": + err = unpopulate(val, "InboundNatRuleName", &n.InboundNatRuleName) + 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 NextHopParameters. +func (n NextHopParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationIPAddress", n.DestinationIPAddress) + populate(objectMap, "sourceIPAddress", n.SourceIPAddress) + populate(objectMap, "targetNicResourceId", n.TargetNicResourceID) + populate(objectMap, "targetResourceId", n.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NextHopParameters. +func (n *NextHopParameters) UnmarshalJSON(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 "destinationIPAddress": + err = unpopulate(val, "DestinationIPAddress", &n.DestinationIPAddress) + delete(rawMsg, key) + case "sourceIPAddress": + err = unpopulate(val, "SourceIPAddress", &n.SourceIPAddress) + delete(rawMsg, key) + case "targetNicResourceId": + err = unpopulate(val, "TargetNicResourceID", &n.TargetNicResourceID) + delete(rawMsg, key) + case "targetResourceId": + err = unpopulate(val, "TargetResourceID", &n.TargetResourceID) + 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 NextHopResult. +func (n NextHopResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextHopIpAddress", n.NextHopIPAddress) + populate(objectMap, "nextHopType", n.NextHopType) + populate(objectMap, "routeTableId", n.RouteTableID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NextHopResult. +func (n *NextHopResult) UnmarshalJSON(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 "nextHopIpAddress": + err = unpopulate(val, "NextHopIPAddress", &n.NextHopIPAddress) + delete(rawMsg, key) + case "nextHopType": + err = unpopulate(val, "NextHopType", &n.NextHopType) + delete(rawMsg, key) + case "routeTableId": + err = unpopulate(val, "RouteTableID", &n.RouteTableID) + 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 O365BreakOutCategoryPolicies. +func (o O365BreakOutCategoryPolicies) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allow", o.Allow) + populate(objectMap, "default", o.Default) + populate(objectMap, "optimize", o.Optimize) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type O365BreakOutCategoryPolicies. +func (o *O365BreakOutCategoryPolicies) UnmarshalJSON(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 "allow": + err = unpopulate(val, "Allow", &o.Allow) + delete(rawMsg, key) + case "default": + err = unpopulate(val, "Default", &o.Default) + delete(rawMsg, key) + case "optimize": + err = unpopulate(val, "Optimize", &o.Optimize) + 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 O365PolicyProperties. +func (o O365PolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "breakOutCategories", o.BreakOutCategories) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type O365PolicyProperties. +func (o *O365PolicyProperties) UnmarshalJSON(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 "breakOutCategories": + err = unpopulate(val, "BreakOutCategories", &o.BreakOutCategories) + 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 Office365PolicyProperties. +func (o Office365PolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "breakOutCategories", o.BreakOutCategories) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Office365PolicyProperties. +func (o *Office365PolicyProperties) UnmarshalJSON(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 "breakOutCategories": + err = unpopulate(val, "BreakOutCategories", &o.BreakOutCategories) + 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, "origin", o.Origin) + populate(objectMap, "properties", o.Properties) + 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 "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 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 OperationPropertiesFormat. +func (o OperationPropertiesFormat) 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 OperationPropertiesFormat. +func (o *OperationPropertiesFormat) UnmarshalJSON(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 OperationPropertiesFormatServiceSpecification. +func (o OperationPropertiesFormatServiceSpecification) 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 OperationPropertiesFormatServiceSpecification. +func (o *OperationPropertiesFormatServiceSpecification) UnmarshalJSON(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 OrderBy. +func (o OrderBy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "field", o.Field) + populate(objectMap, "order", o.Order) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrderBy. +func (o *OrderBy) UnmarshalJSON(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 "field": + err = unpopulate(val, "Field", &o.Field) + delete(rawMsg, key) + case "order": + err = unpopulate(val, "Order", &o.Order) + 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 OutboundRule. +func (o OutboundRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", o.Etag) + 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 OutboundRule. +func (o *OutboundRule) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &o.Etag) + delete(rawMsg, 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 OutboundRulePropertiesFormat. +func (o OutboundRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocatedOutboundPorts", o.AllocatedOutboundPorts) + populate(objectMap, "backendAddressPool", o.BackendAddressPool) + populate(objectMap, "enableTcpReset", o.EnableTCPReset) + populate(objectMap, "frontendIPConfigurations", o.FrontendIPConfigurations) + populate(objectMap, "idleTimeoutInMinutes", o.IdleTimeoutInMinutes) + populate(objectMap, "protocol", o.Protocol) + populate(objectMap, "provisioningState", o.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutboundRulePropertiesFormat. +func (o *OutboundRulePropertiesFormat) UnmarshalJSON(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 "allocatedOutboundPorts": + err = unpopulate(val, "AllocatedOutboundPorts", &o.AllocatedOutboundPorts) + delete(rawMsg, key) + case "backendAddressPool": + err = unpopulate(val, "BackendAddressPool", &o.BackendAddressPool) + delete(rawMsg, key) + case "enableTcpReset": + err = unpopulate(val, "EnableTCPReset", &o.EnableTCPReset) + delete(rawMsg, key) + case "frontendIPConfigurations": + err = unpopulate(val, "FrontendIPConfigurations", &o.FrontendIPConfigurations) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &o.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &o.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + 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 OwaspCrsExclusionEntry. +func (o OwaspCrsExclusionEntry) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exclusionManagedRuleSets", o.ExclusionManagedRuleSets) + populate(objectMap, "matchVariable", o.MatchVariable) + populate(objectMap, "selector", o.Selector) + populate(objectMap, "selectorMatchOperator", o.SelectorMatchOperator) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OwaspCrsExclusionEntry. +func (o *OwaspCrsExclusionEntry) UnmarshalJSON(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 "exclusionManagedRuleSets": + err = unpopulate(val, "ExclusionManagedRuleSets", &o.ExclusionManagedRuleSets) + delete(rawMsg, key) + case "matchVariable": + err = unpopulate(val, "MatchVariable", &o.MatchVariable) + delete(rawMsg, key) + case "selector": + err = unpopulate(val, "Selector", &o.Selector) + delete(rawMsg, key) + case "selectorMatchOperator": + err = unpopulate(val, "SelectorMatchOperator", &o.SelectorMatchOperator) + 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 P2SConnectionConfiguration. +func (p P2SConnectionConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type P2SConnectionConfiguration. +func (p *P2SConnectionConfiguration) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + 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 P2SConnectionConfigurationProperties. +func (p P2SConnectionConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configurationPolicyGroupAssociations", p.ConfigurationPolicyGroupAssociations) + populate(objectMap, "enableInternetSecurity", p.EnableInternetSecurity) + populate(objectMap, "previousConfigurationPolicyGroupAssociations", p.PreviousConfigurationPolicyGroupAssociations) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "routingConfiguration", p.RoutingConfiguration) + populate(objectMap, "vpnClientAddressPool", p.VPNClientAddressPool) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type P2SConnectionConfigurationProperties. +func (p *P2SConnectionConfigurationProperties) UnmarshalJSON(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 "configurationPolicyGroupAssociations": + err = unpopulate(val, "ConfigurationPolicyGroupAssociations", &p.ConfigurationPolicyGroupAssociations) + delete(rawMsg, key) + case "enableInternetSecurity": + err = unpopulate(val, "EnableInternetSecurity", &p.EnableInternetSecurity) + delete(rawMsg, key) + case "previousConfigurationPolicyGroupAssociations": + err = unpopulate(val, "PreviousConfigurationPolicyGroupAssociations", &p.PreviousConfigurationPolicyGroupAssociations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "routingConfiguration": + err = unpopulate(val, "RoutingConfiguration", &p.RoutingConfiguration) + delete(rawMsg, key) + case "vpnClientAddressPool": + err = unpopulate(val, "VPNClientAddressPool", &p.VPNClientAddressPool) + 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 P2SVPNConnectionHealth. +func (p P2SVPNConnectionHealth) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sasUrl", p.SasURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type P2SVPNConnectionHealth. +func (p *P2SVPNConnectionHealth) UnmarshalJSON(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 "sasUrl": + err = unpopulate(val, "SasURL", &p.SasURL) + 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 P2SVPNConnectionHealthRequest. +func (p P2SVPNConnectionHealthRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "outputBlobSasUrl", p.OutputBlobSasURL) + populate(objectMap, "vpnUserNamesFilter", p.VPNUserNamesFilter) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type P2SVPNConnectionHealthRequest. +func (p *P2SVPNConnectionHealthRequest) UnmarshalJSON(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 "outputBlobSasUrl": + err = unpopulate(val, "OutputBlobSasURL", &p.OutputBlobSasURL) + delete(rawMsg, key) + case "vpnUserNamesFilter": + err = unpopulate(val, "VPNUserNamesFilter", &p.VPNUserNamesFilter) + 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 P2SVPNConnectionRequest. +func (p P2SVPNConnectionRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vpnConnectionIds", p.VPNConnectionIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type P2SVPNConnectionRequest. +func (p *P2SVPNConnectionRequest) UnmarshalJSON(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 "vpnConnectionIds": + err = unpopulate(val, "VPNConnectionIDs", &p.VPNConnectionIDs) + 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 P2SVPNGateway. +func (p P2SVPNGateway) 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 P2SVPNGateway. +func (p *P2SVPNGateway) UnmarshalJSON(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 P2SVPNGatewayProperties. +func (p P2SVPNGatewayProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customDnsServers", p.CustomDNSServers) + populate(objectMap, "isRoutingPreferenceInternet", p.IsRoutingPreferenceInternet) + populate(objectMap, "p2SConnectionConfigurations", p.P2SConnectionConfigurations) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "vpnClientConnectionHealth", p.VPNClientConnectionHealth) + populate(objectMap, "vpnGatewayScaleUnit", p.VPNGatewayScaleUnit) + populate(objectMap, "vpnServerConfiguration", p.VPNServerConfiguration) + populate(objectMap, "virtualHub", p.VirtualHub) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type P2SVPNGatewayProperties. +func (p *P2SVPNGatewayProperties) UnmarshalJSON(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 "customDnsServers": + err = unpopulate(val, "CustomDNSServers", &p.CustomDNSServers) + delete(rawMsg, key) + case "isRoutingPreferenceInternet": + err = unpopulate(val, "IsRoutingPreferenceInternet", &p.IsRoutingPreferenceInternet) + delete(rawMsg, key) + case "p2SConnectionConfigurations": + err = unpopulate(val, "P2SConnectionConfigurations", &p.P2SConnectionConfigurations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "vpnClientConnectionHealth": + err = unpopulate(val, "VPNClientConnectionHealth", &p.VPNClientConnectionHealth) + delete(rawMsg, key) + case "vpnGatewayScaleUnit": + err = unpopulate(val, "VPNGatewayScaleUnit", &p.VPNGatewayScaleUnit) + delete(rawMsg, key) + case "vpnServerConfiguration": + err = unpopulate(val, "VPNServerConfiguration", &p.VPNServerConfiguration) + delete(rawMsg, key) + case "virtualHub": + err = unpopulate(val, "VirtualHub", &p.VirtualHub) + 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 P2SVPNProfileParameters. +func (p P2SVPNProfileParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationMethod", p.AuthenticationMethod) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type P2SVPNProfileParameters. +func (p *P2SVPNProfileParameters) UnmarshalJSON(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 "authenticationMethod": + err = unpopulate(val, "AuthenticationMethod", &p.AuthenticationMethod) + 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 PacketCapture. +func (p PacketCapture) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCapture. +func (p *PacketCapture) UnmarshalJSON(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 "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 PacketCaptureFilter. +func (p PacketCaptureFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "localIPAddress", p.LocalIPAddress) + populate(objectMap, "localPort", p.LocalPort) + populate(objectMap, "protocol", p.Protocol) + populate(objectMap, "remoteIPAddress", p.RemoteIPAddress) + populate(objectMap, "remotePort", p.RemotePort) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCaptureFilter. +func (p *PacketCaptureFilter) UnmarshalJSON(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 "localIPAddress": + err = unpopulate(val, "LocalIPAddress", &p.LocalIPAddress) + delete(rawMsg, key) + case "localPort": + err = unpopulate(val, "LocalPort", &p.LocalPort) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &p.Protocol) + delete(rawMsg, key) + case "remoteIPAddress": + err = unpopulate(val, "RemoteIPAddress", &p.RemoteIPAddress) + delete(rawMsg, key) + case "remotePort": + err = unpopulate(val, "RemotePort", &p.RemotePort) + 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 PacketCaptureListResult. +func (p PacketCaptureListResult) 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 PacketCaptureListResult. +func (p *PacketCaptureListResult) UnmarshalJSON(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 PacketCaptureMachineScope. +func (p PacketCaptureMachineScope) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exclude", p.Exclude) + populate(objectMap, "include", p.Include) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCaptureMachineScope. +func (p *PacketCaptureMachineScope) UnmarshalJSON(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 "exclude": + err = unpopulate(val, "Exclude", &p.Exclude) + delete(rawMsg, key) + case "include": + err = unpopulate(val, "Include", &p.Include) + 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 PacketCaptureParameters. +func (p PacketCaptureParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bytesToCapturePerPacket", p.BytesToCapturePerPacket) + populate(objectMap, "filters", p.Filters) + populate(objectMap, "scope", p.Scope) + populate(objectMap, "storageLocation", p.StorageLocation) + populate(objectMap, "target", p.Target) + populate(objectMap, "targetType", p.TargetType) + populate(objectMap, "timeLimitInSeconds", p.TimeLimitInSeconds) + populate(objectMap, "totalBytesPerSession", p.TotalBytesPerSession) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCaptureParameters. +func (p *PacketCaptureParameters) UnmarshalJSON(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 "bytesToCapturePerPacket": + err = unpopulate(val, "BytesToCapturePerPacket", &p.BytesToCapturePerPacket) + delete(rawMsg, key) + case "filters": + err = unpopulate(val, "Filters", &p.Filters) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &p.Scope) + delete(rawMsg, key) + case "storageLocation": + err = unpopulate(val, "StorageLocation", &p.StorageLocation) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &p.Target) + delete(rawMsg, key) + case "targetType": + err = unpopulate(val, "TargetType", &p.TargetType) + delete(rawMsg, key) + case "timeLimitInSeconds": + err = unpopulate(val, "TimeLimitInSeconds", &p.TimeLimitInSeconds) + delete(rawMsg, key) + case "totalBytesPerSession": + err = unpopulate(val, "TotalBytesPerSession", &p.TotalBytesPerSession) + 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 PacketCaptureQueryStatusResult. +func (p PacketCaptureQueryStatusResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "captureStartTime", p.CaptureStartTime) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "packetCaptureError", p.PacketCaptureError) + populate(objectMap, "packetCaptureStatus", p.PacketCaptureStatus) + populate(objectMap, "stopReason", p.StopReason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCaptureQueryStatusResult. +func (p *PacketCaptureQueryStatusResult) UnmarshalJSON(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 "captureStartTime": + err = unpopulateDateTimeRFC3339(val, "CaptureStartTime", &p.CaptureStartTime) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "packetCaptureError": + err = unpopulate(val, "PacketCaptureError", &p.PacketCaptureError) + delete(rawMsg, key) + case "packetCaptureStatus": + err = unpopulate(val, "PacketCaptureStatus", &p.PacketCaptureStatus) + delete(rawMsg, key) + case "stopReason": + err = unpopulate(val, "StopReason", &p.StopReason) + 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 PacketCaptureResult. +func (p PacketCaptureResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCaptureResult. +func (p *PacketCaptureResult) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + 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 PacketCaptureResultProperties. +func (p PacketCaptureResultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bytesToCapturePerPacket", p.BytesToCapturePerPacket) + populate(objectMap, "filters", p.Filters) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "scope", p.Scope) + populate(objectMap, "storageLocation", p.StorageLocation) + populate(objectMap, "target", p.Target) + populate(objectMap, "targetType", p.TargetType) + populate(objectMap, "timeLimitInSeconds", p.TimeLimitInSeconds) + populate(objectMap, "totalBytesPerSession", p.TotalBytesPerSession) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCaptureResultProperties. +func (p *PacketCaptureResultProperties) UnmarshalJSON(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 "bytesToCapturePerPacket": + err = unpopulate(val, "BytesToCapturePerPacket", &p.BytesToCapturePerPacket) + delete(rawMsg, key) + case "filters": + err = unpopulate(val, "Filters", &p.Filters) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &p.Scope) + delete(rawMsg, key) + case "storageLocation": + err = unpopulate(val, "StorageLocation", &p.StorageLocation) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &p.Target) + delete(rawMsg, key) + case "targetType": + err = unpopulate(val, "TargetType", &p.TargetType) + delete(rawMsg, key) + case "timeLimitInSeconds": + err = unpopulate(val, "TimeLimitInSeconds", &p.TimeLimitInSeconds) + delete(rawMsg, key) + case "totalBytesPerSession": + err = unpopulate(val, "TotalBytesPerSession", &p.TotalBytesPerSession) + 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 PacketCaptureStorageLocation. +func (p PacketCaptureStorageLocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filePath", p.FilePath) + populate(objectMap, "storageId", p.StorageID) + populate(objectMap, "storagePath", p.StoragePath) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PacketCaptureStorageLocation. +func (p *PacketCaptureStorageLocation) UnmarshalJSON(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 "filePath": + err = unpopulate(val, "FilePath", &p.FilePath) + delete(rawMsg, key) + case "storageId": + err = unpopulate(val, "StorageID", &p.StorageID) + delete(rawMsg, key) + case "storagePath": + err = unpopulate(val, "StoragePath", &p.StoragePath) + 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 Parameter. +func (p Parameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asPath", p.AsPath) + populate(objectMap, "community", p.Community) + populate(objectMap, "routePrefix", p.RoutePrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Parameter. +func (p *Parameter) UnmarshalJSON(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 "asPath": + err = unpopulate(val, "AsPath", &p.AsPath) + delete(rawMsg, key) + case "community": + err = unpopulate(val, "Community", &p.Community) + delete(rawMsg, key) + case "routePrefix": + err = unpopulate(val, "RoutePrefix", &p.RoutePrefix) + 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 PartnerManagedResourceProperties. +func (p PartnerManagedResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "internalLoadBalancerId", p.InternalLoadBalancerID) + populate(objectMap, "standardLoadBalancerId", p.StandardLoadBalancerID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PartnerManagedResourceProperties. +func (p *PartnerManagedResourceProperties) UnmarshalJSON(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 "internalLoadBalancerId": + err = unpopulate(val, "InternalLoadBalancerID", &p.InternalLoadBalancerID) + delete(rawMsg, key) + case "standardLoadBalancerId": + err = unpopulate(val, "StandardLoadBalancerID", &p.StandardLoadBalancerID) + 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 PatchObject. +func (p PatchObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", p.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PatchObject. +func (p *PatchObject) UnmarshalJSON(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 "tags": + err = unpopulate(val, "Tags", &p.Tags) + 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 PatchRouteFilter. +func (p PatchRouteFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + 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 PatchRouteFilter. +func (p *PatchRouteFilter) UnmarshalJSON(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 "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 PatchRouteFilterRule. +func (p PatchRouteFilterRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PatchRouteFilterRule. +func (p *PatchRouteFilterRule) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + 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 PeerExpressRouteCircuitConnection. +func (p PeerExpressRouteCircuitConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + 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 PeerExpressRouteCircuitConnection. +func (p *PeerExpressRouteCircuitConnection) UnmarshalJSON(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 "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 PeerExpressRouteCircuitConnectionListResult. +func (p PeerExpressRouteCircuitConnectionListResult) 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 PeerExpressRouteCircuitConnectionListResult. +func (p *PeerExpressRouteCircuitConnectionListResult) UnmarshalJSON(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 PeerExpressRouteCircuitConnectionPropertiesFormat. +func (p PeerExpressRouteCircuitConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", p.AddressPrefix) + populate(objectMap, "authResourceGuid", p.AuthResourceGUID) + populate(objectMap, "circuitConnectionStatus", p.CircuitConnectionStatus) + populate(objectMap, "connectionName", p.ConnectionName) + populate(objectMap, "expressRouteCircuitPeering", p.ExpressRouteCircuitPeering) + populate(objectMap, "peerExpressRouteCircuitPeering", p.PeerExpressRouteCircuitPeering) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PeerExpressRouteCircuitConnectionPropertiesFormat. +func (p *PeerExpressRouteCircuitConnectionPropertiesFormat) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &p.AddressPrefix) + delete(rawMsg, key) + case "authResourceGuid": + err = unpopulate(val, "AuthResourceGUID", &p.AuthResourceGUID) + delete(rawMsg, key) + case "circuitConnectionStatus": + err = unpopulate(val, "CircuitConnectionStatus", &p.CircuitConnectionStatus) + delete(rawMsg, key) + case "connectionName": + err = unpopulate(val, "ConnectionName", &p.ConnectionName) + delete(rawMsg, key) + case "expressRouteCircuitPeering": + err = unpopulate(val, "ExpressRouteCircuitPeering", &p.ExpressRouteCircuitPeering) + delete(rawMsg, key) + case "peerExpressRouteCircuitPeering": + err = unpopulate(val, "PeerExpressRouteCircuitPeering", &p.PeerExpressRouteCircuitPeering) + 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 PeerRoute. +func (p PeerRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asPath", p.AsPath) + populate(objectMap, "localAddress", p.LocalAddress) + populate(objectMap, "network", p.Network) + populate(objectMap, "nextHop", p.NextHop) + populate(objectMap, "origin", p.Origin) + populate(objectMap, "sourcePeer", p.SourcePeer) + populate(objectMap, "weight", p.Weight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PeerRoute. +func (p *PeerRoute) UnmarshalJSON(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 "asPath": + err = unpopulate(val, "AsPath", &p.AsPath) + delete(rawMsg, key) + case "localAddress": + err = unpopulate(val, "LocalAddress", &p.LocalAddress) + delete(rawMsg, key) + case "network": + err = unpopulate(val, "Network", &p.Network) + delete(rawMsg, key) + case "nextHop": + err = unpopulate(val, "NextHop", &p.NextHop) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &p.Origin) + delete(rawMsg, key) + case "sourcePeer": + err = unpopulate(val, "SourcePeer", &p.SourcePeer) + delete(rawMsg, key) + case "weight": + err = unpopulate(val, "Weight", &p.Weight) + 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 PolicySettings. +func (p PolicySettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customBlockResponseBody", p.CustomBlockResponseBody) + populate(objectMap, "customBlockResponseStatusCode", p.CustomBlockResponseStatusCode) + populate(objectMap, "fileUploadEnforcement", p.FileUploadEnforcement) + populate(objectMap, "fileUploadLimitInMb", p.FileUploadLimitInMb) + populate(objectMap, "logScrubbing", p.LogScrubbing) + populate(objectMap, "maxRequestBodySizeInKb", p.MaxRequestBodySizeInKb) + populate(objectMap, "mode", p.Mode) + populate(objectMap, "requestBodyCheck", p.RequestBodyCheck) + populate(objectMap, "requestBodyEnforcement", p.RequestBodyEnforcement) + populate(objectMap, "requestBodyInspectLimitInKB", p.RequestBodyInspectLimitInKB) + populate(objectMap, "state", p.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PolicySettings. +func (p *PolicySettings) UnmarshalJSON(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 "customBlockResponseBody": + err = unpopulate(val, "CustomBlockResponseBody", &p.CustomBlockResponseBody) + delete(rawMsg, key) + case "customBlockResponseStatusCode": + err = unpopulate(val, "CustomBlockResponseStatusCode", &p.CustomBlockResponseStatusCode) + delete(rawMsg, key) + case "fileUploadEnforcement": + err = unpopulate(val, "FileUploadEnforcement", &p.FileUploadEnforcement) + delete(rawMsg, key) + case "fileUploadLimitInMb": + err = unpopulate(val, "FileUploadLimitInMb", &p.FileUploadLimitInMb) + delete(rawMsg, key) + case "logScrubbing": + err = unpopulate(val, "LogScrubbing", &p.LogScrubbing) + delete(rawMsg, key) + case "maxRequestBodySizeInKb": + err = unpopulate(val, "MaxRequestBodySizeInKb", &p.MaxRequestBodySizeInKb) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &p.Mode) + delete(rawMsg, key) + case "requestBodyCheck": + err = unpopulate(val, "RequestBodyCheck", &p.RequestBodyCheck) + delete(rawMsg, key) + case "requestBodyEnforcement": + err = unpopulate(val, "RequestBodyEnforcement", &p.RequestBodyEnforcement) + delete(rawMsg, key) + case "requestBodyInspectLimitInKB": + err = unpopulate(val, "RequestBodyInspectLimitInKB", &p.RequestBodyInspectLimitInKB) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &p.State) + 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 PolicySettingsLogScrubbing. +func (p PolicySettingsLogScrubbing) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "scrubbingRules", p.ScrubbingRules) + populate(objectMap, "state", p.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PolicySettingsLogScrubbing. +func (p *PolicySettingsLogScrubbing) UnmarshalJSON(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 "scrubbingRules": + err = unpopulate(val, "ScrubbingRules", &p.ScrubbingRules) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &p.State) + 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 PrepareNetworkPoliciesRequest. +func (p PrepareNetworkPoliciesRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkIntentPolicyConfigurations", p.NetworkIntentPolicyConfigurations) + populate(objectMap, "serviceName", p.ServiceName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrepareNetworkPoliciesRequest. +func (p *PrepareNetworkPoliciesRequest) UnmarshalJSON(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 "networkIntentPolicyConfigurations": + err = unpopulate(val, "NetworkIntentPolicyConfigurations", &p.NetworkIntentPolicyConfigurations) + delete(rawMsg, key) + case "serviceName": + err = unpopulate(val, "ServiceName", &p.ServiceName) + 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 PrivateDNSZoneConfig. +func (p PrivateDNSZoneConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateDNSZoneConfig. +func (p *PrivateDNSZoneConfig) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + 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 PrivateDNSZoneGroup. +func (p PrivateDNSZoneGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateDNSZoneGroup. +func (p *PrivateDNSZoneGroup) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + 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 PrivateDNSZoneGroupListResult. +func (p PrivateDNSZoneGroupListResult) 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 PrivateDNSZoneGroupListResult. +func (p *PrivateDNSZoneGroupListResult) UnmarshalJSON(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 PrivateDNSZoneGroupPropertiesFormat. +func (p PrivateDNSZoneGroupPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateDnsZoneConfigs", p.PrivateDNSZoneConfigs) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateDNSZoneGroupPropertiesFormat. +func (p *PrivateDNSZoneGroupPropertiesFormat) UnmarshalJSON(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 "privateDnsZoneConfigs": + err = unpopulate(val, "PrivateDNSZoneConfigs", &p.PrivateDNSZoneConfigs) + 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 PrivateDNSZonePropertiesFormat. +func (p PrivateDNSZonePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateDnsZoneId", p.PrivateDNSZoneID) + populate(objectMap, "recordSets", p.RecordSets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateDNSZonePropertiesFormat. +func (p *PrivateDNSZonePropertiesFormat) UnmarshalJSON(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 "privateDnsZoneId": + err = unpopulate(val, "PrivateDNSZoneID", &p.PrivateDNSZoneID) + delete(rawMsg, key) + case "recordSets": + err = unpopulate(val, "RecordSets", &p.RecordSets) + 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, "etag", p.Etag) + populate(objectMap, "extendedLocation", p.ExtendedLocation) + 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 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 "etag": + err = unpopulate(val, "Etag", &p.Etag) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &p.ExtendedLocation) + 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 PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + 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 "etag": + err = unpopulate(val, "Etag", &p.Etag) + delete(rawMsg, 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, "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, "linkIdentifier", p.LinkIdentifier) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateEndpointLocation", p.PrivateEndpointLocation) + 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 "linkIdentifier": + err = unpopulate(val, "LinkIdentifier", &p.LinkIdentifier) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &p.PrivateEndpoint) + delete(rawMsg, key) + case "privateEndpointLocation": + err = unpopulate(val, "PrivateEndpointLocation", &p.PrivateEndpointLocation) + 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 PrivateEndpointIPConfiguration. +func (p PrivateEndpointIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + 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 PrivateEndpointIPConfiguration. +func (p *PrivateEndpointIPConfiguration) UnmarshalJSON(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 "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 PrivateEndpointIPConfigurationProperties. +func (p PrivateEndpointIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "memberName", p.MemberName) + populate(objectMap, "privateIPAddress", p.PrivateIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointIPConfigurationProperties. +func (p *PrivateEndpointIPConfigurationProperties) UnmarshalJSON(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 "memberName": + err = unpopulate(val, "MemberName", &p.MemberName) + delete(rawMsg, key) + case "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &p.PrivateIPAddress) + 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 PrivateEndpointListResult. +func (p PrivateEndpointListResult) 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 PrivateEndpointListResult. +func (p *PrivateEndpointListResult) UnmarshalJSON(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 PrivateEndpointProperties. +func (p PrivateEndpointProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationSecurityGroups", p.ApplicationSecurityGroups) + populate(objectMap, "customDnsConfigs", p.CustomDNSConfigs) + populate(objectMap, "customNetworkInterfaceName", p.CustomNetworkInterfaceName) + populate(objectMap, "ipConfigurations", p.IPConfigurations) + populate(objectMap, "manualPrivateLinkServiceConnections", p.ManualPrivateLinkServiceConnections) + populate(objectMap, "networkInterfaces", p.NetworkInterfaces) + populate(objectMap, "privateLinkServiceConnections", p.PrivateLinkServiceConnections) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "subnet", p.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointProperties. +func (p *PrivateEndpointProperties) UnmarshalJSON(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 "applicationSecurityGroups": + err = unpopulate(val, "ApplicationSecurityGroups", &p.ApplicationSecurityGroups) + delete(rawMsg, key) + case "customDnsConfigs": + err = unpopulate(val, "CustomDNSConfigs", &p.CustomDNSConfigs) + delete(rawMsg, key) + case "customNetworkInterfaceName": + err = unpopulate(val, "CustomNetworkInterfaceName", &p.CustomNetworkInterfaceName) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &p.IPConfigurations) + delete(rawMsg, key) + case "manualPrivateLinkServiceConnections": + err = unpopulate(val, "ManualPrivateLinkServiceConnections", &p.ManualPrivateLinkServiceConnections) + delete(rawMsg, key) + case "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &p.NetworkInterfaces) + delete(rawMsg, key) + case "privateLinkServiceConnections": + err = unpopulate(val, "PrivateLinkServiceConnections", &p.PrivateLinkServiceConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &p.Subnet) + 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 PrivateLinkService. +func (p PrivateLinkService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "extendedLocation", p.ExtendedLocation) + 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 PrivateLinkService. +func (p *PrivateLinkService) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &p.ExtendedLocation) + 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 PrivateLinkServiceConnection. +func (p PrivateLinkServiceConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + 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 PrivateLinkServiceConnection. +func (p *PrivateLinkServiceConnection) UnmarshalJSON(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 "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 PrivateLinkServiceConnectionProperties. +func (p PrivateLinkServiceConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupIds", p.GroupIDs) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "privateLinkServiceId", p.PrivateLinkServiceID) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "requestMessage", p.RequestMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceConnectionProperties. +func (p *PrivateLinkServiceConnectionProperties) UnmarshalJSON(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 "groupIds": + err = unpopulate(val, "GroupIDs", &p.GroupIDs) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &p.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "privateLinkServiceId": + err = unpopulate(val, "PrivateLinkServiceID", &p.PrivateLinkServiceID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "requestMessage": + err = unpopulate(val, "RequestMessage", &p.RequestMessage) + 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 PrivateLinkServiceIPConfiguration. +func (p PrivateLinkServiceIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + 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 PrivateLinkServiceIPConfiguration. +func (p *PrivateLinkServiceIPConfiguration) UnmarshalJSON(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 "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 PrivateLinkServiceIPConfigurationProperties. +func (p PrivateLinkServiceIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "primary", p.Primary) + populate(objectMap, "privateIPAddress", p.PrivateIPAddress) + populate(objectMap, "privateIPAddressVersion", p.PrivateIPAddressVersion) + populate(objectMap, "privateIPAllocationMethod", p.PrivateIPAllocationMethod) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "subnet", p.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceIPConfigurationProperties. +func (p *PrivateLinkServiceIPConfigurationProperties) UnmarshalJSON(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 "primary": + err = unpopulate(val, "Primary", &p.Primary) + delete(rawMsg, key) + case "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &p.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAddressVersion": + err = unpopulate(val, "PrivateIPAddressVersion", &p.PrivateIPAddressVersion) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &p.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &p.Subnet) + 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 PrivateLinkServiceListResult. +func (p PrivateLinkServiceListResult) 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 PrivateLinkServiceListResult. +func (p *PrivateLinkServiceListResult) UnmarshalJSON(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 PrivateLinkServiceProperties. +func (p PrivateLinkServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alias", p.Alias) + populate(objectMap, "autoApproval", p.AutoApproval) + populate(objectMap, "enableProxyProtocol", p.EnableProxyProtocol) + populate(objectMap, "fqdns", p.Fqdns) + populate(objectMap, "ipConfigurations", p.IPConfigurations) + populate(objectMap, "loadBalancerFrontendIpConfigurations", p.LoadBalancerFrontendIPConfigurations) + populate(objectMap, "networkInterfaces", p.NetworkInterfaces) + populate(objectMap, "privateEndpointConnections", p.PrivateEndpointConnections) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "visibility", p.Visibility) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceProperties. +func (p *PrivateLinkServiceProperties) UnmarshalJSON(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 "alias": + err = unpopulate(val, "Alias", &p.Alias) + delete(rawMsg, key) + case "autoApproval": + err = unpopulate(val, "AutoApproval", &p.AutoApproval) + delete(rawMsg, key) + case "enableProxyProtocol": + err = unpopulate(val, "EnableProxyProtocol", &p.EnableProxyProtocol) + delete(rawMsg, key) + case "fqdns": + err = unpopulate(val, "Fqdns", &p.Fqdns) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &p.IPConfigurations) + delete(rawMsg, key) + case "loadBalancerFrontendIpConfigurations": + err = unpopulate(val, "LoadBalancerFrontendIPConfigurations", &p.LoadBalancerFrontendIPConfigurations) + delete(rawMsg, key) + case "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &p.NetworkInterfaces) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &p.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "visibility": + err = unpopulate(val, "Visibility", &p.Visibility) + 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 PrivateLinkServicePropertiesAutoApproval. +func (p PrivateLinkServicePropertiesAutoApproval) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "subscriptions", p.Subscriptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServicePropertiesAutoApproval. +func (p *PrivateLinkServicePropertiesAutoApproval) UnmarshalJSON(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 "subscriptions": + err = unpopulate(val, "Subscriptions", &p.Subscriptions) + 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 PrivateLinkServicePropertiesVisibility. +func (p PrivateLinkServicePropertiesVisibility) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "subscriptions", p.Subscriptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServicePropertiesVisibility. +func (p *PrivateLinkServicePropertiesVisibility) UnmarshalJSON(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 "subscriptions": + err = unpopulate(val, "Subscriptions", &p.Subscriptions) + 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 PrivateLinkServiceVisibility. +func (p PrivateLinkServiceVisibility) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "visible", p.Visible) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceVisibility. +func (p *PrivateLinkServiceVisibility) UnmarshalJSON(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 "visible": + err = unpopulate(val, "Visible", &p.Visible) + 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 Probe. +func (p Probe) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + 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 Probe. +func (p *Probe) UnmarshalJSON(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 "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 ProbePropertiesFormat. +func (p ProbePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "intervalInSeconds", p.IntervalInSeconds) + populate(objectMap, "loadBalancingRules", p.LoadBalancingRules) + populate(objectMap, "numberOfProbes", p.NumberOfProbes) + populate(objectMap, "port", p.Port) + populate(objectMap, "probeThreshold", p.ProbeThreshold) + populate(objectMap, "protocol", p.Protocol) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "requestPath", p.RequestPath) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProbePropertiesFormat. +func (p *ProbePropertiesFormat) UnmarshalJSON(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 "intervalInSeconds": + err = unpopulate(val, "IntervalInSeconds", &p.IntervalInSeconds) + delete(rawMsg, key) + case "loadBalancingRules": + err = unpopulate(val, "LoadBalancingRules", &p.LoadBalancingRules) + delete(rawMsg, key) + case "numberOfProbes": + err = unpopulate(val, "NumberOfProbes", &p.NumberOfProbes) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &p.Port) + delete(rawMsg, key) + case "probeThreshold": + err = unpopulate(val, "ProbeThreshold", &p.ProbeThreshold) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &p.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "requestPath": + err = unpopulate(val, "RequestPath", &p.RequestPath) + 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 Profile. +func (p Profile) 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 Profile. +func (p *Profile) UnmarshalJSON(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 ProfileListResult. +func (p ProfileListResult) 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 ProfileListResult. +func (p *ProfileListResult) UnmarshalJSON(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 ProfilePropertiesFormat. +func (p ProfilePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containerNetworkInterfaceConfigurations", p.ContainerNetworkInterfaceConfigurations) + populate(objectMap, "containerNetworkInterfaces", p.ContainerNetworkInterfaces) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "resourceGuid", p.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProfilePropertiesFormat. +func (p *ProfilePropertiesFormat) UnmarshalJSON(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 "containerNetworkInterfaceConfigurations": + err = unpopulate(val, "ContainerNetworkInterfaceConfigurations", &p.ContainerNetworkInterfaceConfigurations) + delete(rawMsg, key) + case "containerNetworkInterfaces": + err = unpopulate(val, "ContainerNetworkInterfaces", &p.ContainerNetworkInterfaces) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &p.ResourceGUID) + 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 PropagatedRouteTable. +func (p PropagatedRouteTable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ids", p.IDs) + populate(objectMap, "labels", p.Labels) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PropagatedRouteTable. +func (p *PropagatedRouteTable) UnmarshalJSON(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 "ids": + err = unpopulate(val, "IDs", &p.IDs) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &p.Labels) + 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 PropagatedRouteTableNfv. +func (p PropagatedRouteTableNfv) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ids", p.IDs) + populate(objectMap, "labels", p.Labels) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PropagatedRouteTableNfv. +func (p *PropagatedRouteTableNfv) UnmarshalJSON(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 "ids": + err = unpopulate(val, "IDs", &p.IDs) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &p.Labels) + 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 ProtocolConfiguration. +func (p ProtocolConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "HTTPConfiguration", p.HTTPConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProtocolConfiguration. +func (p *ProtocolConfiguration) UnmarshalJSON(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 "HTTPConfiguration": + err = unpopulate(val, "HTTPConfiguration", &p.HTTPConfiguration) + 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 PublicIPAddress. +func (p PublicIPAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "extendedLocation", p.ExtendedLocation) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "sku", p.SKU) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + populate(objectMap, "zones", p.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddress. +func (p *PublicIPAddress) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &p.ExtendedLocation) + 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 "sku": + err = unpopulate(val, "SKU", &p.SKU) + 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) + case "zones": + err = unpopulate(val, "Zones", &p.Zones) + 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 PublicIPAddressDNSSettings. +func (p PublicIPAddressDNSSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domainNameLabel", p.DomainNameLabel) + populate(objectMap, "domainNameLabelScope", p.DomainNameLabelScope) + populate(objectMap, "fqdn", p.Fqdn) + populate(objectMap, "reverseFqdn", p.ReverseFqdn) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddressDNSSettings. +func (p *PublicIPAddressDNSSettings) UnmarshalJSON(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 "domainNameLabel": + err = unpopulate(val, "DomainNameLabel", &p.DomainNameLabel) + delete(rawMsg, key) + case "domainNameLabelScope": + err = unpopulate(val, "DomainNameLabelScope", &p.DomainNameLabelScope) + delete(rawMsg, key) + case "fqdn": + err = unpopulate(val, "Fqdn", &p.Fqdn) + delete(rawMsg, key) + case "reverseFqdn": + err = unpopulate(val, "ReverseFqdn", &p.ReverseFqdn) + 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 PublicIPAddressListResult. +func (p PublicIPAddressListResult) 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 PublicIPAddressListResult. +func (p *PublicIPAddressListResult) UnmarshalJSON(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 PublicIPAddressPropertiesFormat. +func (p PublicIPAddressPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsSettings", p.DNSSettings) + populate(objectMap, "ddosSettings", p.DdosSettings) + populate(objectMap, "deleteOption", p.DeleteOption) + populate(objectMap, "ipAddress", p.IPAddress) + populate(objectMap, "ipConfiguration", p.IPConfiguration) + populate(objectMap, "ipTags", p.IPTags) + populate(objectMap, "idleTimeoutInMinutes", p.IdleTimeoutInMinutes) + populate(objectMap, "linkedPublicIPAddress", p.LinkedPublicIPAddress) + populate(objectMap, "migrationPhase", p.MigrationPhase) + populate(objectMap, "natGateway", p.NatGateway) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "publicIPAddressVersion", p.PublicIPAddressVersion) + populate(objectMap, "publicIPAllocationMethod", p.PublicIPAllocationMethod) + populate(objectMap, "publicIPPrefix", p.PublicIPPrefix) + populate(objectMap, "resourceGuid", p.ResourceGUID) + populate(objectMap, "servicePublicIPAddress", p.ServicePublicIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddressPropertiesFormat. +func (p *PublicIPAddressPropertiesFormat) UnmarshalJSON(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 "dnsSettings": + err = unpopulate(val, "DNSSettings", &p.DNSSettings) + delete(rawMsg, key) + case "ddosSettings": + err = unpopulate(val, "DdosSettings", &p.DdosSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &p.DeleteOption) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &p.IPAddress) + delete(rawMsg, key) + case "ipConfiguration": + err = unpopulate(val, "IPConfiguration", &p.IPConfiguration) + delete(rawMsg, key) + case "ipTags": + err = unpopulate(val, "IPTags", &p.IPTags) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &p.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "linkedPublicIPAddress": + err = unpopulate(val, "LinkedPublicIPAddress", &p.LinkedPublicIPAddress) + delete(rawMsg, key) + case "migrationPhase": + err = unpopulate(val, "MigrationPhase", &p.MigrationPhase) + delete(rawMsg, key) + case "natGateway": + err = unpopulate(val, "NatGateway", &p.NatGateway) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddressVersion": + err = unpopulate(val, "PublicIPAddressVersion", &p.PublicIPAddressVersion) + delete(rawMsg, key) + case "publicIPAllocationMethod": + err = unpopulate(val, "PublicIPAllocationMethod", &p.PublicIPAllocationMethod) + delete(rawMsg, key) + case "publicIPPrefix": + err = unpopulate(val, "PublicIPPrefix", &p.PublicIPPrefix) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &p.ResourceGUID) + delete(rawMsg, key) + case "servicePublicIPAddress": + err = unpopulate(val, "ServicePublicIPAddress", &p.ServicePublicIPAddress) + 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 PublicIPAddressSKU. +func (p PublicIPAddressSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "tier", p.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddressSKU. +func (p *PublicIPAddressSKU) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &p.Tier) + 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 PublicIPDdosProtectionStatusResult. +func (p PublicIPDdosProtectionStatusResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ddosProtectionPlanId", p.DdosProtectionPlanID) + populate(objectMap, "isWorkloadProtected", p.IsWorkloadProtected) + populate(objectMap, "publicIpAddress", p.PublicIPAddress) + populate(objectMap, "publicIpAddressId", p.PublicIPAddressID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPDdosProtectionStatusResult. +func (p *PublicIPDdosProtectionStatusResult) UnmarshalJSON(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 "ddosProtectionPlanId": + err = unpopulate(val, "DdosProtectionPlanID", &p.DdosProtectionPlanID) + delete(rawMsg, key) + case "isWorkloadProtected": + err = unpopulate(val, "IsWorkloadProtected", &p.IsWorkloadProtected) + delete(rawMsg, key) + case "publicIpAddress": + err = unpopulate(val, "PublicIPAddress", &p.PublicIPAddress) + delete(rawMsg, key) + case "publicIpAddressId": + err = unpopulate(val, "PublicIPAddressID", &p.PublicIPAddressID) + 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 PublicIPPrefix. +func (p PublicIPPrefix) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "extendedLocation", p.ExtendedLocation) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "sku", p.SKU) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + populate(objectMap, "zones", p.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPPrefix. +func (p *PublicIPPrefix) UnmarshalJSON(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 "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &p.ExtendedLocation) + 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 "sku": + err = unpopulate(val, "SKU", &p.SKU) + 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) + case "zones": + err = unpopulate(val, "Zones", &p.Zones) + 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 PublicIPPrefixListResult. +func (p PublicIPPrefixListResult) 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 PublicIPPrefixListResult. +func (p *PublicIPPrefixListResult) UnmarshalJSON(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 PublicIPPrefixPropertiesFormat. +func (p PublicIPPrefixPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customIPPrefix", p.CustomIPPrefix) + populate(objectMap, "ipPrefix", p.IPPrefix) + populate(objectMap, "ipTags", p.IPTags) + populate(objectMap, "loadBalancerFrontendIpConfiguration", p.LoadBalancerFrontendIPConfiguration) + populate(objectMap, "natGateway", p.NatGateway) + populate(objectMap, "prefixLength", p.PrefixLength) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "publicIPAddressVersion", p.PublicIPAddressVersion) + populate(objectMap, "publicIPAddresses", p.PublicIPAddresses) + populate(objectMap, "resourceGuid", p.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPPrefixPropertiesFormat. +func (p *PublicIPPrefixPropertiesFormat) UnmarshalJSON(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 "customIPPrefix": + err = unpopulate(val, "CustomIPPrefix", &p.CustomIPPrefix) + delete(rawMsg, key) + case "ipPrefix": + err = unpopulate(val, "IPPrefix", &p.IPPrefix) + delete(rawMsg, key) + case "ipTags": + err = unpopulate(val, "IPTags", &p.IPTags) + delete(rawMsg, key) + case "loadBalancerFrontendIpConfiguration": + err = unpopulate(val, "LoadBalancerFrontendIPConfiguration", &p.LoadBalancerFrontendIPConfiguration) + delete(rawMsg, key) + case "natGateway": + err = unpopulate(val, "NatGateway", &p.NatGateway) + delete(rawMsg, key) + case "prefixLength": + err = unpopulate(val, "PrefixLength", &p.PrefixLength) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddressVersion": + err = unpopulate(val, "PublicIPAddressVersion", &p.PublicIPAddressVersion) + delete(rawMsg, key) + case "publicIPAddresses": + err = unpopulate(val, "PublicIPAddresses", &p.PublicIPAddresses) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &p.ResourceGUID) + 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 PublicIPPrefixSKU. +func (p PublicIPPrefixSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "tier", p.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPPrefixSKU. +func (p *PublicIPPrefixSKU) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &p.Tier) + 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 QosDefinition. +func (q QosDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationIpRanges", q.DestinationIPRanges) + populate(objectMap, "destinationPortRanges", q.DestinationPortRanges) + populate(objectMap, "markings", q.Markings) + populate(objectMap, "protocol", q.Protocol) + populate(objectMap, "sourceIpRanges", q.SourceIPRanges) + populate(objectMap, "sourcePortRanges", q.SourcePortRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QosDefinition. +func (q *QosDefinition) UnmarshalJSON(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 "destinationIpRanges": + err = unpopulate(val, "DestinationIPRanges", &q.DestinationIPRanges) + delete(rawMsg, key) + case "destinationPortRanges": + err = unpopulate(val, "DestinationPortRanges", &q.DestinationPortRanges) + delete(rawMsg, key) + case "markings": + err = unpopulate(val, "Markings", &q.Markings) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &q.Protocol) + delete(rawMsg, key) + case "sourceIpRanges": + err = unpopulate(val, "SourceIPRanges", &q.SourceIPRanges) + delete(rawMsg, key) + case "sourcePortRanges": + err = unpopulate(val, "SourcePortRanges", &q.SourcePortRanges) + 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 QosIPRange. +func (q QosIPRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "endIP", q.EndIP) + populate(objectMap, "startIP", q.StartIP) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QosIPRange. +func (q *QosIPRange) UnmarshalJSON(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 "endIP": + err = unpopulate(val, "EndIP", &q.EndIP) + delete(rawMsg, key) + case "startIP": + err = unpopulate(val, "StartIP", &q.StartIP) + 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 QosPortRange. +func (q QosPortRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "end", q.End) + populate(objectMap, "start", q.Start) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QosPortRange. +func (q *QosPortRange) UnmarshalJSON(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 "end": + err = unpopulate(val, "End", &q.End) + delete(rawMsg, key) + case "start": + err = unpopulate(val, "Start", &q.Start) + 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 QueryInboundNatRulePortMappingRequest. +func (q QueryInboundNatRulePortMappingRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipAddress", q.IPAddress) + populate(objectMap, "ipConfiguration", q.IPConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueryInboundNatRulePortMappingRequest. +func (q *QueryInboundNatRulePortMappingRequest) UnmarshalJSON(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 "ipAddress": + err = unpopulate(val, "IPAddress", &q.IPAddress) + delete(rawMsg, key) + case "ipConfiguration": + err = unpopulate(val, "IPConfiguration", &q.IPConfiguration) + 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 QueryRequestOptions. +func (q QueryRequestOptions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "skipToken", q.SkipToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueryRequestOptions. +func (q *QueryRequestOptions) UnmarshalJSON(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 "skipToken": + err = unpopulate(val, "SkipToken", &q.SkipToken) + 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 QueryResults. +func (q QueryResults) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "matchingRecordsCount", q.MatchingRecordsCount) + populate(objectMap, "signatures", q.Signatures) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueryResults. +func (q *QueryResults) UnmarshalJSON(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 "matchingRecordsCount": + err = unpopulate(val, "MatchingRecordsCount", &q.MatchingRecordsCount) + delete(rawMsg, key) + case "signatures": + err = unpopulate(val, "Signatures", &q.Signatures) + 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 QueryTroubleshootingParameters. +func (q QueryTroubleshootingParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targetResourceId", q.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueryTroubleshootingParameters. +func (q *QueryTroubleshootingParameters) UnmarshalJSON(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 "targetResourceId": + err = unpopulate(val, "TargetResourceID", &q.TargetResourceID) + 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 RadiusServer. +func (r RadiusServer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "radiusServerAddress", r.RadiusServerAddress) + populate(objectMap, "radiusServerScore", r.RadiusServerScore) + populate(objectMap, "radiusServerSecret", r.RadiusServerSecret) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RadiusServer. +func (r *RadiusServer) UnmarshalJSON(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 "radiusServerAddress": + err = unpopulate(val, "RadiusServerAddress", &r.RadiusServerAddress) + delete(rawMsg, key) + case "radiusServerScore": + err = unpopulate(val, "RadiusServerScore", &r.RadiusServerScore) + delete(rawMsg, key) + case "radiusServerSecret": + err = unpopulate(val, "RadiusServerSecret", &r.RadiusServerSecret) + 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 RecordSet. +func (r RecordSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fqdn", r.Fqdn) + populate(objectMap, "ipAddresses", r.IPAddresses) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "recordSetName", r.RecordSetName) + populate(objectMap, "recordType", r.RecordType) + populate(objectMap, "ttl", r.TTL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RecordSet. +func (r *RecordSet) UnmarshalJSON(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 "fqdn": + err = unpopulate(val, "Fqdn", &r.Fqdn) + delete(rawMsg, key) + case "ipAddresses": + err = unpopulate(val, "IPAddresses", &r.IPAddresses) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "recordSetName": + err = unpopulate(val, "RecordSetName", &r.RecordSetName) + delete(rawMsg, key) + case "recordType": + err = unpopulate(val, "RecordType", &r.RecordType) + delete(rawMsg, key) + case "ttl": + err = unpopulate(val, "TTL", &r.TTL) + 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 ReferencedPublicIPAddress. +func (r ReferencedPublicIPAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReferencedPublicIPAddress. +func (r *ReferencedPublicIPAddress) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, 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 ResourceNavigationLink. +func (r ResourceNavigationLink) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceNavigationLink. +func (r *ResourceNavigationLink) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, 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 "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 ResourceNavigationLinkFormat. +func (r ResourceNavigationLinkFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "link", r.Link) + populate(objectMap, "linkedResourceType", r.LinkedResourceType) + populate(objectMap, "provisioningState", r.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceNavigationLinkFormat. +func (r *ResourceNavigationLinkFormat) UnmarshalJSON(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 "link": + err = unpopulate(val, "Link", &r.Link) + delete(rawMsg, key) + case "linkedResourceType": + err = unpopulate(val, "LinkedResourceType", &r.LinkedResourceType) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + 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 ResourceNavigationLinksListResult. +func (r ResourceNavigationLinksListResult) 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 ResourceNavigationLinksListResult. +func (r *ResourceNavigationLinksListResult) UnmarshalJSON(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 ResourceSet. +func (r ResourceSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "subscriptions", r.Subscriptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSet. +func (r *ResourceSet) UnmarshalJSON(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 "subscriptions": + err = unpopulate(val, "Subscriptions", &r.Subscriptions) + 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 RetentionPolicyParameters. +func (r RetentionPolicyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "days", r.Days) + populate(objectMap, "enabled", r.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RetentionPolicyParameters. +func (r *RetentionPolicyParameters) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Route. +func (r Route) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Route. +func (r *Route) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, 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 "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 RouteFilter. +func (r RouteFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteFilter. +func (r *RouteFilter) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, 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 "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 RouteFilterListResult. +func (r RouteFilterListResult) 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 RouteFilterListResult. +func (r *RouteFilterListResult) UnmarshalJSON(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 RouteFilterPropertiesFormat. +func (r RouteFilterPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipv6Peerings", r.IPv6Peerings) + populate(objectMap, "peerings", r.Peerings) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "rules", r.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteFilterPropertiesFormat. +func (r *RouteFilterPropertiesFormat) UnmarshalJSON(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 "ipv6Peerings": + err = unpopulate(val, "IPv6Peerings", &r.IPv6Peerings) + delete(rawMsg, key) + case "peerings": + err = unpopulate(val, "Peerings", &r.Peerings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &r.Rules) + 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 RouteFilterRule. +func (r RouteFilterRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteFilterRule. +func (r *RouteFilterRule) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RouteFilterRuleListResult. +func (r RouteFilterRuleListResult) 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 RouteFilterRuleListResult. +func (r *RouteFilterRuleListResult) UnmarshalJSON(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 RouteFilterRulePropertiesFormat. +func (r RouteFilterRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", r.Access) + populate(objectMap, "communities", r.Communities) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "routeFilterRuleType", r.RouteFilterRuleType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteFilterRulePropertiesFormat. +func (r *RouteFilterRulePropertiesFormat) UnmarshalJSON(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 "access": + err = unpopulate(val, "Access", &r.Access) + delete(rawMsg, key) + case "communities": + err = unpopulate(val, "Communities", &r.Communities) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "routeFilterRuleType": + err = unpopulate(val, "RouteFilterRuleType", &r.RouteFilterRuleType) + 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 RouteListResult. +func (r RouteListResult) 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 RouteListResult. +func (r *RouteListResult) UnmarshalJSON(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 RouteMap. +func (r RouteMap) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteMap. +func (r *RouteMap) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, 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 "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 RouteMapProperties. +func (r RouteMapProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "associatedInboundConnections", r.AssociatedInboundConnections) + populate(objectMap, "associatedOutboundConnections", r.AssociatedOutboundConnections) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "rules", r.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteMapProperties. +func (r *RouteMapProperties) UnmarshalJSON(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 "associatedInboundConnections": + err = unpopulate(val, "AssociatedInboundConnections", &r.AssociatedInboundConnections) + delete(rawMsg, key) + case "associatedOutboundConnections": + err = unpopulate(val, "AssociatedOutboundConnections", &r.AssociatedOutboundConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &r.Rules) + 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 RouteMapRule. +func (r RouteMapRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", r.Actions) + populate(objectMap, "matchCriteria", r.MatchCriteria) + populate(objectMap, "name", r.Name) + populate(objectMap, "nextStepIfMatched", r.NextStepIfMatched) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteMapRule. +func (r *RouteMapRule) UnmarshalJSON(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 "actions": + err = unpopulate(val, "Actions", &r.Actions) + delete(rawMsg, key) + case "matchCriteria": + err = unpopulate(val, "MatchCriteria", &r.MatchCriteria) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "nextStepIfMatched": + err = unpopulate(val, "NextStepIfMatched", &r.NextStepIfMatched) + 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 RoutePropertiesFormat. +func (r RoutePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", r.AddressPrefix) + populate(objectMap, "hasBgpOverride", r.HasBgpOverride) + populate(objectMap, "nextHopIpAddress", r.NextHopIPAddress) + populate(objectMap, "nextHopType", r.NextHopType) + populate(objectMap, "provisioningState", r.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutePropertiesFormat. +func (r *RoutePropertiesFormat) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &r.AddressPrefix) + delete(rawMsg, key) + case "hasBgpOverride": + err = unpopulate(val, "HasBgpOverride", &r.HasBgpOverride) + delete(rawMsg, key) + case "nextHopIpAddress": + err = unpopulate(val, "NextHopIPAddress", &r.NextHopIPAddress) + delete(rawMsg, key) + case "nextHopType": + err = unpopulate(val, "NextHopType", &r.NextHopType) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + 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 RouteTable. +func (r RouteTable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteTable. +func (r *RouteTable) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, 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 "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 RouteTableListResult. +func (r RouteTableListResult) 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 RouteTableListResult. +func (r *RouteTableListResult) UnmarshalJSON(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 RouteTablePropertiesFormat. +func (r RouteTablePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disableBgpRoutePropagation", r.DisableBgpRoutePropagation) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "resourceGuid", r.ResourceGUID) + populate(objectMap, "routes", r.Routes) + populate(objectMap, "subnets", r.Subnets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RouteTablePropertiesFormat. +func (r *RouteTablePropertiesFormat) UnmarshalJSON(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 "disableBgpRoutePropagation": + err = unpopulate(val, "DisableBgpRoutePropagation", &r.DisableBgpRoutePropagation) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &r.ResourceGUID) + delete(rawMsg, key) + case "routes": + err = unpopulate(val, "Routes", &r.Routes) + delete(rawMsg, key) + case "subnets": + err = unpopulate(val, "Subnets", &r.Subnets) + 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 RoutingConfiguration. +func (r RoutingConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "associatedRouteTable", r.AssociatedRouteTable) + populate(objectMap, "inboundRouteMap", r.InboundRouteMap) + populate(objectMap, "outboundRouteMap", r.OutboundRouteMap) + populate(objectMap, "propagatedRouteTables", r.PropagatedRouteTables) + populate(objectMap, "vnetRoutes", r.VnetRoutes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutingConfiguration. +func (r *RoutingConfiguration) UnmarshalJSON(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 "associatedRouteTable": + err = unpopulate(val, "AssociatedRouteTable", &r.AssociatedRouteTable) + delete(rawMsg, key) + case "inboundRouteMap": + err = unpopulate(val, "InboundRouteMap", &r.InboundRouteMap) + delete(rawMsg, key) + case "outboundRouteMap": + err = unpopulate(val, "OutboundRouteMap", &r.OutboundRouteMap) + delete(rawMsg, key) + case "propagatedRouteTables": + err = unpopulate(val, "PropagatedRouteTables", &r.PropagatedRouteTables) + delete(rawMsg, key) + case "vnetRoutes": + err = unpopulate(val, "VnetRoutes", &r.VnetRoutes) + 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 RoutingConfigurationNfv. +func (r RoutingConfigurationNfv) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "associatedRouteTable", r.AssociatedRouteTable) + populate(objectMap, "inboundRouteMap", r.InboundRouteMap) + populate(objectMap, "outboundRouteMap", r.OutboundRouteMap) + populate(objectMap, "propagatedRouteTables", r.PropagatedRouteTables) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutingConfigurationNfv. +func (r *RoutingConfigurationNfv) UnmarshalJSON(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 "associatedRouteTable": + err = unpopulate(val, "AssociatedRouteTable", &r.AssociatedRouteTable) + delete(rawMsg, key) + case "inboundRouteMap": + err = unpopulate(val, "InboundRouteMap", &r.InboundRouteMap) + delete(rawMsg, key) + case "outboundRouteMap": + err = unpopulate(val, "OutboundRouteMap", &r.OutboundRouteMap) + delete(rawMsg, key) + case "propagatedRouteTables": + err = unpopulate(val, "PropagatedRouteTables", &r.PropagatedRouteTables) + 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 RoutingConfigurationNfvSubResource. +func (r RoutingConfigurationNfvSubResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceUri", r.ResourceURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutingConfigurationNfvSubResource. +func (r *RoutingConfigurationNfvSubResource) UnmarshalJSON(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 "resourceUri": + err = unpopulate(val, "ResourceURI", &r.ResourceURI) + 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 RoutingIntent. +func (r RoutingIntent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutingIntent. +func (r *RoutingIntent) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, 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 "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 RoutingIntentProperties. +func (r RoutingIntentProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "routingPolicies", r.RoutingPolicies) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutingIntentProperties. +func (r *RoutingIntentProperties) UnmarshalJSON(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 "routingPolicies": + err = unpopulate(val, "RoutingPolicies", &r.RoutingPolicies) + 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 RoutingPolicy. +func (r RoutingPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinations", r.Destinations) + populate(objectMap, "name", r.Name) + populate(objectMap, "nextHop", r.NextHop) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutingPolicy. +func (r *RoutingPolicy) UnmarshalJSON(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 "destinations": + err = unpopulate(val, "Destinations", &r.Destinations) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "nextHop": + err = unpopulate(val, "NextHop", &r.NextHop) + 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 Rule. +func (r Rule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", r.Description) + populate(objectMap, "destinationAddresses", r.DestinationAddresses) + populate(objectMap, "destinationFqdns", r.DestinationFqdns) + populate(objectMap, "destinationIpGroups", r.DestinationIPGroups) + populate(objectMap, "destinationPorts", r.DestinationPorts) + populate(objectMap, "ipProtocols", r.IPProtocols) + populate(objectMap, "name", r.Name) + objectMap["ruleType"] = FirewallPolicyRuleTypeNetworkRule + populate(objectMap, "sourceAddresses", r.SourceAddresses) + populate(objectMap, "sourceIpGroups", r.SourceIPGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Rule. +func (r *Rule) UnmarshalJSON(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 "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + case "destinationAddresses": + err = unpopulate(val, "DestinationAddresses", &r.DestinationAddresses) + delete(rawMsg, key) + case "destinationFqdns": + err = unpopulate(val, "DestinationFqdns", &r.DestinationFqdns) + delete(rawMsg, key) + case "destinationIpGroups": + err = unpopulate(val, "DestinationIPGroups", &r.DestinationIPGroups) + delete(rawMsg, key) + case "destinationPorts": + err = unpopulate(val, "DestinationPorts", &r.DestinationPorts) + delete(rawMsg, key) + case "ipProtocols": + err = unpopulate(val, "IPProtocols", &r.IPProtocols) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &r.RuleType) + delete(rawMsg, key) + case "sourceAddresses": + err = unpopulate(val, "SourceAddresses", &r.SourceAddresses) + delete(rawMsg, key) + case "sourceIpGroups": + err = unpopulate(val, "SourceIPGroups", &r.SourceIPGroups) + 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) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScopeConnection. +func (s ScopeConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + 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 ScopeConnection. +func (s *ScopeConnection) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 ScopeConnectionListResult. +func (s ScopeConnectionListResult) 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 ScopeConnectionListResult. +func (s *ScopeConnectionListResult) UnmarshalJSON(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 ScopeConnectionProperties. +func (s ScopeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionState", s.ConnectionState) + populate(objectMap, "description", s.Description) + populate(objectMap, "resourceId", s.ResourceID) + populate(objectMap, "tenantId", s.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScopeConnectionProperties. +func (s *ScopeConnectionProperties) UnmarshalJSON(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 "connectionState": + err = unpopulate(val, "ConnectionState", &s.ConnectionState) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &s.ResourceID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &s.TenantID) + 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 SecurityAdminConfiguration. +func (s SecurityAdminConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + 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 SecurityAdminConfiguration. +func (s *SecurityAdminConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 SecurityAdminConfigurationListResult. +func (s SecurityAdminConfigurationListResult) 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 SecurityAdminConfigurationListResult. +func (s *SecurityAdminConfigurationListResult) UnmarshalJSON(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 SecurityAdminConfigurationPropertiesFormat. +func (s SecurityAdminConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applyOnNetworkIntentPolicyBasedServices", s.ApplyOnNetworkIntentPolicyBasedServices) + populate(objectMap, "description", s.Description) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "resourceGuid", s.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityAdminConfigurationPropertiesFormat. +func (s *SecurityAdminConfigurationPropertiesFormat) UnmarshalJSON(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 "applyOnNetworkIntentPolicyBasedServices": + err = unpopulate(val, "ApplyOnNetworkIntentPolicyBasedServices", &s.ApplyOnNetworkIntentPolicyBasedServices) + 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 "resourceGuid": + err = unpopulate(val, "ResourceGUID", &s.ResourceGUID) + 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 SecurityGroup. +func (s SecurityGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + 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 SecurityGroup. +func (s *SecurityGroup) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 SecurityGroupListResult. +func (s SecurityGroupListResult) 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 SecurityGroupListResult. +func (s *SecurityGroupListResult) UnmarshalJSON(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 SecurityGroupNetworkInterface. +func (s SecurityGroupNetworkInterface) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "securityRuleAssociations", s.SecurityRuleAssociations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityGroupNetworkInterface. +func (s *SecurityGroupNetworkInterface) UnmarshalJSON(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 "securityRuleAssociations": + err = unpopulate(val, "SecurityRuleAssociations", &s.SecurityRuleAssociations) + 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 SecurityGroupPropertiesFormat. +func (s SecurityGroupPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultSecurityRules", s.DefaultSecurityRules) + populate(objectMap, "flowLogs", s.FlowLogs) + populate(objectMap, "flushConnection", s.FlushConnection) + populate(objectMap, "networkInterfaces", s.NetworkInterfaces) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "resourceGuid", s.ResourceGUID) + populate(objectMap, "securityRules", s.SecurityRules) + populate(objectMap, "subnets", s.Subnets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityGroupPropertiesFormat. +func (s *SecurityGroupPropertiesFormat) UnmarshalJSON(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 "defaultSecurityRules": + err = unpopulate(val, "DefaultSecurityRules", &s.DefaultSecurityRules) + delete(rawMsg, key) + case "flowLogs": + err = unpopulate(val, "FlowLogs", &s.FlowLogs) + delete(rawMsg, key) + case "flushConnection": + err = unpopulate(val, "FlushConnection", &s.FlushConnection) + delete(rawMsg, key) + case "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &s.NetworkInterfaces) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &s.ResourceGUID) + delete(rawMsg, key) + case "securityRules": + err = unpopulate(val, "SecurityRules", &s.SecurityRules) + delete(rawMsg, key) + case "subnets": + err = unpopulate(val, "Subnets", &s.Subnets) + 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 SecurityGroupResult. +func (s SecurityGroupResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "evaluatedNetworkSecurityGroups", s.EvaluatedNetworkSecurityGroups) + populate(objectMap, "securityRuleAccessResult", s.SecurityRuleAccessResult) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityGroupResult. +func (s *SecurityGroupResult) UnmarshalJSON(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 "evaluatedNetworkSecurityGroups": + err = unpopulate(val, "EvaluatedNetworkSecurityGroups", &s.EvaluatedNetworkSecurityGroups) + delete(rawMsg, key) + case "securityRuleAccessResult": + err = unpopulate(val, "SecurityRuleAccessResult", &s.SecurityRuleAccessResult) + 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 SecurityGroupViewParameters. +func (s SecurityGroupViewParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targetResourceId", s.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityGroupViewParameters. +func (s *SecurityGroupViewParameters) UnmarshalJSON(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 "targetResourceId": + err = unpopulate(val, "TargetResourceID", &s.TargetResourceID) + 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 SecurityGroupViewResult. +func (s SecurityGroupViewResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkInterfaces", s.NetworkInterfaces) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityGroupViewResult. +func (s *SecurityGroupViewResult) UnmarshalJSON(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 "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &s.NetworkInterfaces) + 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 SecurityPartnerProvider. +func (s SecurityPartnerProvider) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + 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 SecurityPartnerProvider. +func (s *SecurityPartnerProvider) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 SecurityPartnerProviderListResult. +func (s SecurityPartnerProviderListResult) 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 SecurityPartnerProviderListResult. +func (s *SecurityPartnerProviderListResult) UnmarshalJSON(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 SecurityPartnerProviderPropertiesFormat. +func (s SecurityPartnerProviderPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionStatus", s.ConnectionStatus) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "securityProviderName", s.SecurityProviderName) + populate(objectMap, "virtualHub", s.VirtualHub) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityPartnerProviderPropertiesFormat. +func (s *SecurityPartnerProviderPropertiesFormat) UnmarshalJSON(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 "connectionStatus": + err = unpopulate(val, "ConnectionStatus", &s.ConnectionStatus) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "securityProviderName": + err = unpopulate(val, "SecurityProviderName", &s.SecurityProviderName) + delete(rawMsg, key) + case "virtualHub": + err = unpopulate(val, "VirtualHub", &s.VirtualHub) + 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 SecurityRule. +func (s SecurityRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityRule. +func (s *SecurityRule) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 "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 SecurityRuleAssociations. +func (s SecurityRuleAssociations) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultSecurityRules", s.DefaultSecurityRules) + populate(objectMap, "effectiveSecurityRules", s.EffectiveSecurityRules) + populate(objectMap, "networkInterfaceAssociation", s.NetworkInterfaceAssociation) + populate(objectMap, "subnetAssociation", s.SubnetAssociation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityRuleAssociations. +func (s *SecurityRuleAssociations) UnmarshalJSON(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 "defaultSecurityRules": + err = unpopulate(val, "DefaultSecurityRules", &s.DefaultSecurityRules) + delete(rawMsg, key) + case "effectiveSecurityRules": + err = unpopulate(val, "EffectiveSecurityRules", &s.EffectiveSecurityRules) + delete(rawMsg, key) + case "networkInterfaceAssociation": + err = unpopulate(val, "NetworkInterfaceAssociation", &s.NetworkInterfaceAssociation) + delete(rawMsg, key) + case "subnetAssociation": + err = unpopulate(val, "SubnetAssociation", &s.SubnetAssociation) + 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 SecurityRuleListResult. +func (s SecurityRuleListResult) 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 SecurityRuleListResult. +func (s *SecurityRuleListResult) UnmarshalJSON(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 SecurityRulePropertiesFormat. +func (s SecurityRulePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", s.Access) + populate(objectMap, "description", s.Description) + populate(objectMap, "destinationAddressPrefix", s.DestinationAddressPrefix) + populate(objectMap, "destinationAddressPrefixes", s.DestinationAddressPrefixes) + populate(objectMap, "destinationApplicationSecurityGroups", s.DestinationApplicationSecurityGroups) + populate(objectMap, "destinationPortRange", s.DestinationPortRange) + populate(objectMap, "destinationPortRanges", s.DestinationPortRanges) + populate(objectMap, "direction", s.Direction) + populate(objectMap, "priority", s.Priority) + populate(objectMap, "protocol", s.Protocol) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "sourceAddressPrefix", s.SourceAddressPrefix) + populate(objectMap, "sourceAddressPrefixes", s.SourceAddressPrefixes) + populate(objectMap, "sourceApplicationSecurityGroups", s.SourceApplicationSecurityGroups) + populate(objectMap, "sourcePortRange", s.SourcePortRange) + populate(objectMap, "sourcePortRanges", s.SourcePortRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityRulePropertiesFormat. +func (s *SecurityRulePropertiesFormat) UnmarshalJSON(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 "access": + err = unpopulate(val, "Access", &s.Access) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "destinationAddressPrefix": + err = unpopulate(val, "DestinationAddressPrefix", &s.DestinationAddressPrefix) + delete(rawMsg, key) + case "destinationAddressPrefixes": + err = unpopulate(val, "DestinationAddressPrefixes", &s.DestinationAddressPrefixes) + delete(rawMsg, key) + case "destinationApplicationSecurityGroups": + err = unpopulate(val, "DestinationApplicationSecurityGroups", &s.DestinationApplicationSecurityGroups) + delete(rawMsg, key) + case "destinationPortRange": + err = unpopulate(val, "DestinationPortRange", &s.DestinationPortRange) + delete(rawMsg, key) + case "destinationPortRanges": + err = unpopulate(val, "DestinationPortRanges", &s.DestinationPortRanges) + delete(rawMsg, key) + case "direction": + err = unpopulate(val, "Direction", &s.Direction) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &s.Priority) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &s.Protocol) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "sourceAddressPrefix": + err = unpopulate(val, "SourceAddressPrefix", &s.SourceAddressPrefix) + delete(rawMsg, key) + case "sourceAddressPrefixes": + err = unpopulate(val, "SourceAddressPrefixes", &s.SourceAddressPrefixes) + delete(rawMsg, key) + case "sourceApplicationSecurityGroups": + err = unpopulate(val, "SourceApplicationSecurityGroups", &s.SourceApplicationSecurityGroups) + delete(rawMsg, key) + case "sourcePortRange": + err = unpopulate(val, "SourcePortRange", &s.SourcePortRange) + delete(rawMsg, key) + case "sourcePortRanges": + err = unpopulate(val, "SourcePortRanges", &s.SourcePortRanges) + 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 SecurityRulesEvaluationResult. +func (s SecurityRulesEvaluationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationMatched", s.DestinationMatched) + populate(objectMap, "destinationPortMatched", s.DestinationPortMatched) + populate(objectMap, "name", s.Name) + populate(objectMap, "protocolMatched", s.ProtocolMatched) + populate(objectMap, "sourceMatched", s.SourceMatched) + populate(objectMap, "sourcePortMatched", s.SourcePortMatched) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityRulesEvaluationResult. +func (s *SecurityRulesEvaluationResult) UnmarshalJSON(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 "destinationMatched": + err = unpopulate(val, "DestinationMatched", &s.DestinationMatched) + delete(rawMsg, key) + case "destinationPortMatched": + err = unpopulate(val, "DestinationPortMatched", &s.DestinationPortMatched) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "protocolMatched": + err = unpopulate(val, "ProtocolMatched", &s.ProtocolMatched) + delete(rawMsg, key) + case "sourceMatched": + err = unpopulate(val, "SourceMatched", &s.SourceMatched) + delete(rawMsg, key) + case "sourcePortMatched": + err = unpopulate(val, "SourcePortMatched", &s.SourcePortMatched) + 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 ServiceAssociationLink. +func (s ServiceAssociationLink) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceAssociationLink. +func (s *ServiceAssociationLink) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 "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 ServiceAssociationLinkPropertiesFormat. +func (s ServiceAssociationLinkPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowDelete", s.AllowDelete) + populate(objectMap, "link", s.Link) + populate(objectMap, "linkedResourceType", s.LinkedResourceType) + populate(objectMap, "locations", s.Locations) + populate(objectMap, "provisioningState", s.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceAssociationLinkPropertiesFormat. +func (s *ServiceAssociationLinkPropertiesFormat) UnmarshalJSON(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 "allowDelete": + err = unpopulate(val, "AllowDelete", &s.AllowDelete) + delete(rawMsg, key) + case "link": + err = unpopulate(val, "Link", &s.Link) + delete(rawMsg, key) + case "linkedResourceType": + err = unpopulate(val, "LinkedResourceType", &s.LinkedResourceType) + delete(rawMsg, key) + case "locations": + err = unpopulate(val, "Locations", &s.Locations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + 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 ServiceAssociationLinksListResult. +func (s ServiceAssociationLinksListResult) 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 ServiceAssociationLinksListResult. +func (s *ServiceAssociationLinksListResult) UnmarshalJSON(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 ServiceDelegationPropertiesFormat. +func (s ServiceDelegationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", s.Actions) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "serviceName", s.ServiceName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceDelegationPropertiesFormat. +func (s *ServiceDelegationPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "serviceName": + err = unpopulate(val, "ServiceName", &s.ServiceName) + 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 ServiceEndpointPolicy. +func (s ServiceEndpointPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + populate(objectMap, "id", s.ID) + populate(objectMap, "kind", s.Kind) + 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 ServiceEndpointPolicy. +func (s *ServiceEndpointPolicy) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + 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 ServiceEndpointPolicyDefinition. +func (s ServiceEndpointPolicyDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceEndpointPolicyDefinition. +func (s *ServiceEndpointPolicyDefinition) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 "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 ServiceEndpointPolicyDefinitionListResult. +func (s ServiceEndpointPolicyDefinitionListResult) 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 ServiceEndpointPolicyDefinitionListResult. +func (s *ServiceEndpointPolicyDefinitionListResult) UnmarshalJSON(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 ServiceEndpointPolicyDefinitionPropertiesFormat. +func (s ServiceEndpointPolicyDefinitionPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", s.Description) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "service", s.Service) + populate(objectMap, "serviceResources", s.ServiceResources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceEndpointPolicyDefinitionPropertiesFormat. +func (s *ServiceEndpointPolicyDefinitionPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "service": + err = unpopulate(val, "Service", &s.Service) + delete(rawMsg, key) + case "serviceResources": + err = unpopulate(val, "ServiceResources", &s.ServiceResources) + 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 ServiceEndpointPolicyListResult. +func (s ServiceEndpointPolicyListResult) 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 ServiceEndpointPolicyListResult. +func (s *ServiceEndpointPolicyListResult) UnmarshalJSON(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 ServiceEndpointPolicyPropertiesFormat. +func (s ServiceEndpointPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contextualServiceEndpointPolicies", s.ContextualServiceEndpointPolicies) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "resourceGuid", s.ResourceGUID) + populate(objectMap, "serviceAlias", s.ServiceAlias) + populate(objectMap, "serviceEndpointPolicyDefinitions", s.ServiceEndpointPolicyDefinitions) + populate(objectMap, "subnets", s.Subnets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceEndpointPolicyPropertiesFormat. +func (s *ServiceEndpointPolicyPropertiesFormat) UnmarshalJSON(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 "contextualServiceEndpointPolicies": + err = unpopulate(val, "ContextualServiceEndpointPolicies", &s.ContextualServiceEndpointPolicies) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &s.ResourceGUID) + delete(rawMsg, key) + case "serviceAlias": + err = unpopulate(val, "ServiceAlias", &s.ServiceAlias) + delete(rawMsg, key) + case "serviceEndpointPolicyDefinitions": + err = unpopulate(val, "ServiceEndpointPolicyDefinitions", &s.ServiceEndpointPolicyDefinitions) + delete(rawMsg, key) + case "subnets": + err = unpopulate(val, "Subnets", &s.Subnets) + 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 ServiceEndpointPropertiesFormat. +func (s ServiceEndpointPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "locations", s.Locations) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "service", s.Service) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceEndpointPropertiesFormat. +func (s *ServiceEndpointPropertiesFormat) UnmarshalJSON(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 "locations": + err = unpopulate(val, "Locations", &s.Locations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "service": + err = unpopulate(val, "Service", &s.Service) + 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 ServiceTagInformation. +func (s ServiceTagInformation) 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, "serviceTagChangeNumber", s.ServiceTagChangeNumber) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceTagInformation. +func (s *ServiceTagInformation) UnmarshalJSON(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 "serviceTagChangeNumber": + err = unpopulate(val, "ServiceTagChangeNumber", &s.ServiceTagChangeNumber) + 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 ServiceTagInformationListResult. +func (s ServiceTagInformationListResult) 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 ServiceTagInformationListResult. +func (s *ServiceTagInformationListResult) UnmarshalJSON(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 ServiceTagInformationPropertiesFormat. +func (s ServiceTagInformationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefixes", s.AddressPrefixes) + populate(objectMap, "changeNumber", s.ChangeNumber) + populate(objectMap, "region", s.Region) + populate(objectMap, "state", s.State) + populate(objectMap, "systemService", s.SystemService) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceTagInformationPropertiesFormat. +func (s *ServiceTagInformationPropertiesFormat) UnmarshalJSON(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 "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &s.AddressPrefixes) + delete(rawMsg, key) + case "changeNumber": + err = unpopulate(val, "ChangeNumber", &s.ChangeNumber) + delete(rawMsg, key) + case "region": + err = unpopulate(val, "Region", &s.Region) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &s.State) + delete(rawMsg, key) + case "systemService": + err = unpopulate(val, "SystemService", &s.SystemService) + 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 ServiceTagsListResult. +func (s ServiceTagsListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "changeNumber", s.ChangeNumber) + populate(objectMap, "cloud", s.Cloud) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "type", s.Type) + populate(objectMap, "values", s.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceTagsListResult. +func (s *ServiceTagsListResult) UnmarshalJSON(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 "changeNumber": + err = unpopulate(val, "ChangeNumber", &s.ChangeNumber) + delete(rawMsg, key) + case "cloud": + err = unpopulate(val, "Cloud", &s.Cloud) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &s.Values) + 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 SessionIDs. +func (s SessionIDs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sessionIds", s.SessionIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SessionIDs. +func (s *SessionIDs) UnmarshalJSON(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 "sessionIds": + err = unpopulate(val, "SessionIDs", &s.SessionIDs) + 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 SignatureOverridesFilterValuesQuery. +func (s SignatureOverridesFilterValuesQuery) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filterName", s.FilterName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignatureOverridesFilterValuesQuery. +func (s *SignatureOverridesFilterValuesQuery) UnmarshalJSON(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 "filterName": + err = unpopulate(val, "FilterName", &s.FilterName) + 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 SignatureOverridesFilterValuesResponse. +func (s SignatureOverridesFilterValuesResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filterValues", s.FilterValues) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignatureOverridesFilterValuesResponse. +func (s *SignatureOverridesFilterValuesResponse) UnmarshalJSON(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 "filterValues": + err = unpopulate(val, "FilterValues", &s.FilterValues) + 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 SignaturesOverrides. +func (s SignaturesOverrides) 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, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignaturesOverrides. +func (s *SignaturesOverrides) UnmarshalJSON(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 "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 SignaturesOverridesList. +func (s SignaturesOverridesList) 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 SignaturesOverridesList. +func (s *SignaturesOverridesList) UnmarshalJSON(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 SignaturesOverridesProperties. +func (s SignaturesOverridesProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "signatures", s.Signatures) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignaturesOverridesProperties. +func (s *SignaturesOverridesProperties) UnmarshalJSON(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 "signatures": + err = unpopulate(val, "Signatures", &s.Signatures) + 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 SingleQueryResult. +func (s SingleQueryResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", s.Description) + populate(objectMap, "destinationPorts", s.DestinationPorts) + populate(objectMap, "direction", s.Direction) + populate(objectMap, "group", s.Group) + populate(objectMap, "inheritedFromParentPolicy", s.InheritedFromParentPolicy) + populate(objectMap, "lastUpdated", s.LastUpdated) + populate(objectMap, "mode", s.Mode) + populate(objectMap, "protocol", s.Protocol) + populate(objectMap, "severity", s.Severity) + populate(objectMap, "signatureId", s.SignatureID) + populate(objectMap, "sourcePorts", s.SourcePorts) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleQueryResult. +func (s *SingleQueryResult) UnmarshalJSON(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 "destinationPorts": + err = unpopulate(val, "DestinationPorts", &s.DestinationPorts) + delete(rawMsg, key) + case "direction": + err = unpopulate(val, "Direction", &s.Direction) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &s.Group) + delete(rawMsg, key) + case "inheritedFromParentPolicy": + err = unpopulate(val, "InheritedFromParentPolicy", &s.InheritedFromParentPolicy) + delete(rawMsg, key) + case "lastUpdated": + err = unpopulate(val, "LastUpdated", &s.LastUpdated) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &s.Mode) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &s.Protocol) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, "Severity", &s.Severity) + delete(rawMsg, key) + case "signatureId": + err = unpopulate(val, "SignatureID", &s.SignatureID) + delete(rawMsg, key) + case "sourcePorts": + err = unpopulate(val, "SourcePorts", &s.SourcePorts) + 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 StaticMember. +func (s StaticMember) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + 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 StaticMember. +func (s *StaticMember) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 StaticMemberListResult. +func (s StaticMemberListResult) 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 StaticMemberListResult. +func (s *StaticMemberListResult) UnmarshalJSON(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 StaticMemberProperties. +func (s StaticMemberProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "region", s.Region) + populate(objectMap, "resourceId", s.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StaticMemberProperties. +func (s *StaticMemberProperties) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "region": + err = unpopulate(val, "Region", &s.Region) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &s.ResourceID) + 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 StaticRoute. +func (s StaticRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefixes", s.AddressPrefixes) + populate(objectMap, "name", s.Name) + populate(objectMap, "nextHopIpAddress", s.NextHopIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StaticRoute. +func (s *StaticRoute) UnmarshalJSON(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 "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &s.AddressPrefixes) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "nextHopIpAddress": + err = unpopulate(val, "NextHopIPAddress", &s.NextHopIPAddress) + 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 StaticRoutesConfig. +func (s StaticRoutesConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "propagateStaticRoutes", s.PropagateStaticRoutes) + populate(objectMap, "vnetLocalRouteOverrideCriteria", s.VnetLocalRouteOverrideCriteria) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StaticRoutesConfig. +func (s *StaticRoutesConfig) UnmarshalJSON(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 "propagateStaticRoutes": + err = unpopulate(val, "PropagateStaticRoutes", &s.PropagateStaticRoutes) + delete(rawMsg, key) + case "vnetLocalRouteOverrideCriteria": + err = unpopulate(val, "VnetLocalRouteOverrideCriteria", &s.VnetLocalRouteOverrideCriteria) + 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 SubResource. +func (s SubResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubResource. +func (s *SubResource) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Subnet. +func (s Subnet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", s.Etag) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Subnet. +func (s *Subnet) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &s.Etag) + delete(rawMsg, 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 "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 SubnetAssociation. +func (s SubnetAssociation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "securityRules", s.SecurityRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubnetAssociation. +func (s *SubnetAssociation) UnmarshalJSON(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 "securityRules": + err = unpopulate(val, "SecurityRules", &s.SecurityRules) + 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 SubnetListResult. +func (s SubnetListResult) 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 SubnetListResult. +func (s *SubnetListResult) UnmarshalJSON(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 SubnetPropertiesFormat. +func (s SubnetPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", s.AddressPrefix) + populate(objectMap, "addressPrefixes", s.AddressPrefixes) + populate(objectMap, "applicationGatewayIPConfigurations", s.ApplicationGatewayIPConfigurations) + populate(objectMap, "defaultOutboundAccess", s.DefaultOutboundAccess) + populate(objectMap, "delegations", s.Delegations) + populate(objectMap, "ipAllocations", s.IPAllocations) + populate(objectMap, "ipConfigurationProfiles", s.IPConfigurationProfiles) + populate(objectMap, "ipConfigurations", s.IPConfigurations) + populate(objectMap, "natGateway", s.NatGateway) + populate(objectMap, "networkSecurityGroup", s.NetworkSecurityGroup) + populate(objectMap, "privateEndpointNetworkPolicies", s.PrivateEndpointNetworkPolicies) + populate(objectMap, "privateEndpoints", s.PrivateEndpoints) + populate(objectMap, "privateLinkServiceNetworkPolicies", s.PrivateLinkServiceNetworkPolicies) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "purpose", s.Purpose) + populate(objectMap, "resourceNavigationLinks", s.ResourceNavigationLinks) + populate(objectMap, "routeTable", s.RouteTable) + populate(objectMap, "serviceAssociationLinks", s.ServiceAssociationLinks) + populate(objectMap, "serviceEndpointPolicies", s.ServiceEndpointPolicies) + populate(objectMap, "serviceEndpoints", s.ServiceEndpoints) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubnetPropertiesFormat. +func (s *SubnetPropertiesFormat) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &s.AddressPrefix) + delete(rawMsg, key) + case "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &s.AddressPrefixes) + delete(rawMsg, key) + case "applicationGatewayIPConfigurations": + err = unpopulate(val, "ApplicationGatewayIPConfigurations", &s.ApplicationGatewayIPConfigurations) + delete(rawMsg, key) + case "defaultOutboundAccess": + err = unpopulate(val, "DefaultOutboundAccess", &s.DefaultOutboundAccess) + delete(rawMsg, key) + case "delegations": + err = unpopulate(val, "Delegations", &s.Delegations) + delete(rawMsg, key) + case "ipAllocations": + err = unpopulate(val, "IPAllocations", &s.IPAllocations) + delete(rawMsg, key) + case "ipConfigurationProfiles": + err = unpopulate(val, "IPConfigurationProfiles", &s.IPConfigurationProfiles) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &s.IPConfigurations) + delete(rawMsg, key) + case "natGateway": + err = unpopulate(val, "NatGateway", &s.NatGateway) + delete(rawMsg, key) + case "networkSecurityGroup": + err = unpopulate(val, "NetworkSecurityGroup", &s.NetworkSecurityGroup) + delete(rawMsg, key) + case "privateEndpointNetworkPolicies": + err = unpopulate(val, "PrivateEndpointNetworkPolicies", &s.PrivateEndpointNetworkPolicies) + delete(rawMsg, key) + case "privateEndpoints": + err = unpopulate(val, "PrivateEndpoints", &s.PrivateEndpoints) + delete(rawMsg, key) + case "privateLinkServiceNetworkPolicies": + err = unpopulate(val, "PrivateLinkServiceNetworkPolicies", &s.PrivateLinkServiceNetworkPolicies) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "purpose": + err = unpopulate(val, "Purpose", &s.Purpose) + delete(rawMsg, key) + case "resourceNavigationLinks": + err = unpopulate(val, "ResourceNavigationLinks", &s.ResourceNavigationLinks) + delete(rawMsg, key) + case "routeTable": + err = unpopulate(val, "RouteTable", &s.RouteTable) + delete(rawMsg, key) + case "serviceAssociationLinks": + err = unpopulate(val, "ServiceAssociationLinks", &s.ServiceAssociationLinks) + delete(rawMsg, key) + case "serviceEndpointPolicies": + err = unpopulate(val, "ServiceEndpointPolicies", &s.ServiceEndpointPolicies) + delete(rawMsg, key) + case "serviceEndpoints": + err = unpopulate(val, "ServiceEndpoints", &s.ServiceEndpoints) + 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 SwapResource. +func (s SwapResource) 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, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SwapResource. +func (s *SwapResource) UnmarshalJSON(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 "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 SwapResourceListResult. +func (s SwapResourceListResult) 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 SwapResourceListResult. +func (s *SwapResourceListResult) UnmarshalJSON(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 SwapResourceProperties. +func (s SwapResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "slotType", s.SlotType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SwapResourceProperties. +func (s *SwapResourceProperties) UnmarshalJSON(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 "slotType": + err = unpopulate(val, "SlotType", &s.SlotType) + 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 TagsObject. +func (t TagsObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", t.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TagsObject. +func (t *TagsObject) UnmarshalJSON(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 "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 Topology. +func (t Topology) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createdDateTime", t.CreatedDateTime) + populate(objectMap, "id", t.ID) + populateDateTimeRFC3339(objectMap, "lastModified", t.LastModified) + populate(objectMap, "resources", t.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Topology. +func (t *Topology) UnmarshalJSON(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 "createdDateTime": + err = unpopulateDateTimeRFC3339(val, "CreatedDateTime", &t.CreatedDateTime) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "lastModified": + err = unpopulateDateTimeRFC3339(val, "LastModified", &t.LastModified) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &t.Resources) + 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 TopologyAssociation. +func (t TopologyAssociation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "associationType", t.AssociationType) + populate(objectMap, "name", t.Name) + populate(objectMap, "resourceId", t.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopologyAssociation. +func (t *TopologyAssociation) UnmarshalJSON(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 "associationType": + err = unpopulate(val, "AssociationType", &t.AssociationType) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &t.ResourceID) + 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 TopologyParameters. +func (t TopologyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targetResourceGroupName", t.TargetResourceGroupName) + populate(objectMap, "targetSubnet", t.TargetSubnet) + populate(objectMap, "targetVirtualNetwork", t.TargetVirtualNetwork) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopologyParameters. +func (t *TopologyParameters) UnmarshalJSON(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 "targetResourceGroupName": + err = unpopulate(val, "TargetResourceGroupName", &t.TargetResourceGroupName) + delete(rawMsg, key) + case "targetSubnet": + err = unpopulate(val, "TargetSubnet", &t.TargetSubnet) + delete(rawMsg, key) + case "targetVirtualNetwork": + err = unpopulate(val, "TargetVirtualNetwork", &t.TargetVirtualNetwork) + 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 TopologyResource. +func (t TopologyResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "associations", t.Associations) + populate(objectMap, "id", t.ID) + populate(objectMap, "location", t.Location) + populate(objectMap, "name", t.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopologyResource. +func (t *TopologyResource) UnmarshalJSON(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 "associations": + err = unpopulate(val, "Associations", &t.Associations) + delete(rawMsg, 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TrafficAnalyticsConfigurationProperties. +func (t TrafficAnalyticsConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", t.Enabled) + populate(objectMap, "trafficAnalyticsInterval", t.TrafficAnalyticsInterval) + populate(objectMap, "workspaceId", t.WorkspaceID) + populate(objectMap, "workspaceRegion", t.WorkspaceRegion) + populate(objectMap, "workspaceResourceId", t.WorkspaceResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrafficAnalyticsConfigurationProperties. +func (t *TrafficAnalyticsConfigurationProperties) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &t.Enabled) + delete(rawMsg, key) + case "trafficAnalyticsInterval": + err = unpopulate(val, "TrafficAnalyticsInterval", &t.TrafficAnalyticsInterval) + delete(rawMsg, key) + case "workspaceId": + err = unpopulate(val, "WorkspaceID", &t.WorkspaceID) + delete(rawMsg, key) + case "workspaceRegion": + err = unpopulate(val, "WorkspaceRegion", &t.WorkspaceRegion) + delete(rawMsg, key) + case "workspaceResourceId": + err = unpopulate(val, "WorkspaceResourceID", &t.WorkspaceResourceID) + 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 TrafficAnalyticsProperties. +func (t TrafficAnalyticsProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkWatcherFlowAnalyticsConfiguration", t.NetworkWatcherFlowAnalyticsConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrafficAnalyticsProperties. +func (t *TrafficAnalyticsProperties) UnmarshalJSON(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 "networkWatcherFlowAnalyticsConfiguration": + err = unpopulate(val, "NetworkWatcherFlowAnalyticsConfiguration", &t.NetworkWatcherFlowAnalyticsConfiguration) + 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 TrafficSelectorPolicy. +func (t TrafficSelectorPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "localAddressRanges", t.LocalAddressRanges) + populate(objectMap, "remoteAddressRanges", t.RemoteAddressRanges) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrafficSelectorPolicy. +func (t *TrafficSelectorPolicy) UnmarshalJSON(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 "localAddressRanges": + err = unpopulate(val, "LocalAddressRanges", &t.LocalAddressRanges) + delete(rawMsg, key) + case "remoteAddressRanges": + err = unpopulate(val, "RemoteAddressRanges", &t.RemoteAddressRanges) + 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 TroubleshootingDetails. +func (t TroubleshootingDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "detail", t.Detail) + populate(objectMap, "id", t.ID) + populate(objectMap, "reasonType", t.ReasonType) + populate(objectMap, "recommendedActions", t.RecommendedActions) + populate(objectMap, "summary", t.Summary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TroubleshootingDetails. +func (t *TroubleshootingDetails) UnmarshalJSON(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 "detail": + err = unpopulate(val, "Detail", &t.Detail) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "reasonType": + err = unpopulate(val, "ReasonType", &t.ReasonType) + delete(rawMsg, key) + case "recommendedActions": + err = unpopulate(val, "RecommendedActions", &t.RecommendedActions) + delete(rawMsg, key) + case "summary": + err = unpopulate(val, "Summary", &t.Summary) + 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 TroubleshootingParameters. +func (t TroubleshootingParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "targetResourceId", t.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TroubleshootingParameters. +func (t *TroubleshootingParameters) UnmarshalJSON(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) + case "targetResourceId": + err = unpopulate(val, "TargetResourceID", &t.TargetResourceID) + 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 TroubleshootingProperties. +func (t TroubleshootingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "storageId", t.StorageID) + populate(objectMap, "storagePath", t.StoragePath) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TroubleshootingProperties. +func (t *TroubleshootingProperties) UnmarshalJSON(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 "storageId": + err = unpopulate(val, "StorageID", &t.StorageID) + delete(rawMsg, key) + case "storagePath": + err = unpopulate(val, "StoragePath", &t.StoragePath) + 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 TroubleshootingRecommendedActions. +func (t TroubleshootingRecommendedActions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionId", t.ActionID) + populate(objectMap, "actionText", t.ActionText) + populate(objectMap, "actionUri", t.ActionURI) + populate(objectMap, "actionUriText", t.ActionURIText) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TroubleshootingRecommendedActions. +func (t *TroubleshootingRecommendedActions) UnmarshalJSON(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 "actionId": + err = unpopulate(val, "ActionID", &t.ActionID) + delete(rawMsg, key) + case "actionText": + err = unpopulate(val, "ActionText", &t.ActionText) + delete(rawMsg, key) + case "actionUri": + err = unpopulate(val, "ActionURI", &t.ActionURI) + delete(rawMsg, key) + case "actionUriText": + err = unpopulate(val, "ActionURIText", &t.ActionURIText) + 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 TroubleshootingResult. +func (t TroubleshootingResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", t.Code) + populateDateTimeRFC3339(objectMap, "endTime", t.EndTime) + populate(objectMap, "results", t.Results) + populateDateTimeRFC3339(objectMap, "startTime", t.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TroubleshootingResult. +func (t *TroubleshootingResult) UnmarshalJSON(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 "code": + err = unpopulate(val, "Code", &t.Code) + delete(rawMsg, key) + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &t.EndTime) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &t.Results) + 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 TunnelConnectionHealth. +func (t TunnelConnectionHealth) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionStatus", t.ConnectionStatus) + populate(objectMap, "egressBytesTransferred", t.EgressBytesTransferred) + populate(objectMap, "ingressBytesTransferred", t.IngressBytesTransferred) + populate(objectMap, "lastConnectionEstablishedUtcTime", t.LastConnectionEstablishedUTCTime) + populate(objectMap, "tunnel", t.Tunnel) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TunnelConnectionHealth. +func (t *TunnelConnectionHealth) UnmarshalJSON(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 "connectionStatus": + err = unpopulate(val, "ConnectionStatus", &t.ConnectionStatus) + delete(rawMsg, key) + case "egressBytesTransferred": + err = unpopulate(val, "EgressBytesTransferred", &t.EgressBytesTransferred) + delete(rawMsg, key) + case "ingressBytesTransferred": + err = unpopulate(val, "IngressBytesTransferred", &t.IngressBytesTransferred) + delete(rawMsg, key) + case "lastConnectionEstablishedUtcTime": + err = unpopulate(val, "LastConnectionEstablishedUTCTime", &t.LastConnectionEstablishedUTCTime) + delete(rawMsg, key) + case "tunnel": + err = unpopulate(val, "Tunnel", &t.Tunnel) + 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 UnprepareNetworkPoliciesRequest. +func (u UnprepareNetworkPoliciesRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "serviceName", u.ServiceName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnprepareNetworkPoliciesRequest. +func (u *UnprepareNetworkPoliciesRequest) UnmarshalJSON(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 "serviceName": + err = unpopulate(val, "ServiceName", &u.ServiceName) + 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, "id", u.ID) + 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 "id": + err = unpopulate(val, "ID", &u.ID) + 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 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 UsagesListResult. +func (u UsagesListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", u.NextLink) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UsagesListResult. +func (u *UsagesListResult) UnmarshalJSON(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 "nextLink": + err = unpopulate(val, "NextLink", &u.NextLink) + 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 VM. +func (v VM) 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, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VM. +func (v *VM) UnmarshalJSON(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 "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 VPNClientConfiguration. +func (v VPNClientConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aadAudience", v.AADAudience) + populate(objectMap, "aadIssuer", v.AADIssuer) + populate(objectMap, "aadTenant", v.AADTenant) + populate(objectMap, "radiusServerAddress", v.RadiusServerAddress) + populate(objectMap, "radiusServerSecret", v.RadiusServerSecret) + populate(objectMap, "radiusServers", v.RadiusServers) + populate(objectMap, "vpnAuthenticationTypes", v.VPNAuthenticationTypes) + populate(objectMap, "vpnClientAddressPool", v.VPNClientAddressPool) + populate(objectMap, "vpnClientIpsecPolicies", v.VPNClientIPSecPolicies) + populate(objectMap, "vpnClientProtocols", v.VPNClientProtocols) + populate(objectMap, "vpnClientRevokedCertificates", v.VPNClientRevokedCertificates) + populate(objectMap, "vpnClientRootCertificates", v.VPNClientRootCertificates) + populate(objectMap, "vngClientConnectionConfigurations", v.VngClientConnectionConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientConfiguration. +func (v *VPNClientConfiguration) UnmarshalJSON(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 "aadAudience": + err = unpopulate(val, "AADAudience", &v.AADAudience) + delete(rawMsg, key) + case "aadIssuer": + err = unpopulate(val, "AADIssuer", &v.AADIssuer) + delete(rawMsg, key) + case "aadTenant": + err = unpopulate(val, "AADTenant", &v.AADTenant) + delete(rawMsg, key) + case "radiusServerAddress": + err = unpopulate(val, "RadiusServerAddress", &v.RadiusServerAddress) + delete(rawMsg, key) + case "radiusServerSecret": + err = unpopulate(val, "RadiusServerSecret", &v.RadiusServerSecret) + delete(rawMsg, key) + case "radiusServers": + err = unpopulate(val, "RadiusServers", &v.RadiusServers) + delete(rawMsg, key) + case "vpnAuthenticationTypes": + err = unpopulate(val, "VPNAuthenticationTypes", &v.VPNAuthenticationTypes) + delete(rawMsg, key) + case "vpnClientAddressPool": + err = unpopulate(val, "VPNClientAddressPool", &v.VPNClientAddressPool) + delete(rawMsg, key) + case "vpnClientIpsecPolicies": + err = unpopulate(val, "VPNClientIPSecPolicies", &v.VPNClientIPSecPolicies) + delete(rawMsg, key) + case "vpnClientProtocols": + err = unpopulate(val, "VPNClientProtocols", &v.VPNClientProtocols) + delete(rawMsg, key) + case "vpnClientRevokedCertificates": + err = unpopulate(val, "VPNClientRevokedCertificates", &v.VPNClientRevokedCertificates) + delete(rawMsg, key) + case "vpnClientRootCertificates": + err = unpopulate(val, "VPNClientRootCertificates", &v.VPNClientRootCertificates) + delete(rawMsg, key) + case "vngClientConnectionConfigurations": + err = unpopulate(val, "VngClientConnectionConfigurations", &v.VngClientConnectionConfigurations) + 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 VPNClientConnectionHealth. +func (v VPNClientConnectionHealth) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocatedIpAddresses", v.AllocatedIPAddresses) + populate(objectMap, "totalEgressBytesTransferred", v.TotalEgressBytesTransferred) + populate(objectMap, "totalIngressBytesTransferred", v.TotalIngressBytesTransferred) + populate(objectMap, "vpnClientConnectionsCount", v.VPNClientConnectionsCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientConnectionHealth. +func (v *VPNClientConnectionHealth) UnmarshalJSON(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 "allocatedIpAddresses": + err = unpopulate(val, "AllocatedIPAddresses", &v.AllocatedIPAddresses) + delete(rawMsg, key) + case "totalEgressBytesTransferred": + err = unpopulate(val, "TotalEgressBytesTransferred", &v.TotalEgressBytesTransferred) + delete(rawMsg, key) + case "totalIngressBytesTransferred": + err = unpopulate(val, "TotalIngressBytesTransferred", &v.TotalIngressBytesTransferred) + delete(rawMsg, key) + case "vpnClientConnectionsCount": + err = unpopulate(val, "VPNClientConnectionsCount", &v.VPNClientConnectionsCount) + 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 VPNClientConnectionHealthDetail. +func (v VPNClientConnectionHealthDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "egressBytesTransferred", v.EgressBytesTransferred) + populate(objectMap, "egressPacketsTransferred", v.EgressPacketsTransferred) + populate(objectMap, "ingressBytesTransferred", v.IngressBytesTransferred) + populate(objectMap, "ingressPacketsTransferred", v.IngressPacketsTransferred) + populate(objectMap, "maxBandwidth", v.MaxBandwidth) + populate(objectMap, "maxPacketsPerSecond", v.MaxPacketsPerSecond) + populate(objectMap, "privateIpAddress", v.PrivateIPAddress) + populate(objectMap, "publicIpAddress", v.PublicIPAddress) + populate(objectMap, "vpnConnectionDuration", v.VPNConnectionDuration) + populate(objectMap, "vpnConnectionId", v.VPNConnectionID) + populate(objectMap, "vpnConnectionTime", v.VPNConnectionTime) + populate(objectMap, "vpnUserName", v.VPNUserName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientConnectionHealthDetail. +func (v *VPNClientConnectionHealthDetail) UnmarshalJSON(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 "egressBytesTransferred": + err = unpopulate(val, "EgressBytesTransferred", &v.EgressBytesTransferred) + delete(rawMsg, key) + case "egressPacketsTransferred": + err = unpopulate(val, "EgressPacketsTransferred", &v.EgressPacketsTransferred) + delete(rawMsg, key) + case "ingressBytesTransferred": + err = unpopulate(val, "IngressBytesTransferred", &v.IngressBytesTransferred) + delete(rawMsg, key) + case "ingressPacketsTransferred": + err = unpopulate(val, "IngressPacketsTransferred", &v.IngressPacketsTransferred) + delete(rawMsg, key) + case "maxBandwidth": + err = unpopulate(val, "MaxBandwidth", &v.MaxBandwidth) + delete(rawMsg, key) + case "maxPacketsPerSecond": + err = unpopulate(val, "MaxPacketsPerSecond", &v.MaxPacketsPerSecond) + delete(rawMsg, key) + case "privateIpAddress": + err = unpopulate(val, "PrivateIPAddress", &v.PrivateIPAddress) + delete(rawMsg, key) + case "publicIpAddress": + err = unpopulate(val, "PublicIPAddress", &v.PublicIPAddress) + delete(rawMsg, key) + case "vpnConnectionDuration": + err = unpopulate(val, "VPNConnectionDuration", &v.VPNConnectionDuration) + delete(rawMsg, key) + case "vpnConnectionId": + err = unpopulate(val, "VPNConnectionID", &v.VPNConnectionID) + delete(rawMsg, key) + case "vpnConnectionTime": + err = unpopulate(val, "VPNConnectionTime", &v.VPNConnectionTime) + delete(rawMsg, key) + case "vpnUserName": + err = unpopulate(val, "VPNUserName", &v.VPNUserName) + 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 VPNClientConnectionHealthDetailListResult. +func (v VPNClientConnectionHealthDetailListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientConnectionHealthDetailListResult. +func (v *VPNClientConnectionHealthDetailListResult) UnmarshalJSON(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 "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 VPNClientIPsecParameters. +func (v VPNClientIPsecParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dhGroup", v.DhGroup) + populate(objectMap, "ipsecEncryption", v.IPSecEncryption) + populate(objectMap, "ipsecIntegrity", v.IPSecIntegrity) + populate(objectMap, "ikeEncryption", v.IkeEncryption) + populate(objectMap, "ikeIntegrity", v.IkeIntegrity) + populate(objectMap, "pfsGroup", v.PfsGroup) + populate(objectMap, "saDataSizeKilobytes", v.SaDataSizeKilobytes) + populate(objectMap, "saLifeTimeSeconds", v.SaLifeTimeSeconds) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientIPsecParameters. +func (v *VPNClientIPsecParameters) UnmarshalJSON(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 "dhGroup": + err = unpopulate(val, "DhGroup", &v.DhGroup) + delete(rawMsg, key) + case "ipsecEncryption": + err = unpopulate(val, "IPSecEncryption", &v.IPSecEncryption) + delete(rawMsg, key) + case "ipsecIntegrity": + err = unpopulate(val, "IPSecIntegrity", &v.IPSecIntegrity) + delete(rawMsg, key) + case "ikeEncryption": + err = unpopulate(val, "IkeEncryption", &v.IkeEncryption) + delete(rawMsg, key) + case "ikeIntegrity": + err = unpopulate(val, "IkeIntegrity", &v.IkeIntegrity) + delete(rawMsg, key) + case "pfsGroup": + err = unpopulate(val, "PfsGroup", &v.PfsGroup) + delete(rawMsg, key) + case "saDataSizeKilobytes": + err = unpopulate(val, "SaDataSizeKilobytes", &v.SaDataSizeKilobytes) + delete(rawMsg, key) + case "saLifeTimeSeconds": + err = unpopulate(val, "SaLifeTimeSeconds", &v.SaLifeTimeSeconds) + 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 VPNClientParameters. +func (v VPNClientParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationMethod", v.AuthenticationMethod) + populate(objectMap, "clientRootCertificates", v.ClientRootCertificates) + populate(objectMap, "processorArchitecture", v.ProcessorArchitecture) + populate(objectMap, "radiusServerAuthCertificate", v.RadiusServerAuthCertificate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientParameters. +func (v *VPNClientParameters) UnmarshalJSON(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 "authenticationMethod": + err = unpopulate(val, "AuthenticationMethod", &v.AuthenticationMethod) + delete(rawMsg, key) + case "clientRootCertificates": + err = unpopulate(val, "ClientRootCertificates", &v.ClientRootCertificates) + delete(rawMsg, key) + case "processorArchitecture": + err = unpopulate(val, "ProcessorArchitecture", &v.ProcessorArchitecture) + delete(rawMsg, key) + case "radiusServerAuthCertificate": + err = unpopulate(val, "RadiusServerAuthCertificate", &v.RadiusServerAuthCertificate) + 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 VPNClientRevokedCertificate. +func (v VPNClientRevokedCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientRevokedCertificate. +func (v *VPNClientRevokedCertificate) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VPNClientRevokedCertificatePropertiesFormat. +func (v VPNClientRevokedCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "thumbprint", v.Thumbprint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientRevokedCertificatePropertiesFormat. +func (v *VPNClientRevokedCertificatePropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "thumbprint": + err = unpopulate(val, "Thumbprint", &v.Thumbprint) + 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 VPNClientRootCertificate. +func (v VPNClientRootCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientRootCertificate. +func (v *VPNClientRootCertificate) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VPNClientRootCertificatePropertiesFormat. +func (v VPNClientRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "publicCertData", v.PublicCertData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNClientRootCertificatePropertiesFormat. +func (v *VPNClientRootCertificatePropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "publicCertData": + err = unpopulate(val, "PublicCertData", &v.PublicCertData) + 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 VPNConnection. +func (v VPNConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNConnection. +func (v *VPNConnection) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VPNConnectionPacketCaptureStartParameters. +func (v VPNConnectionPacketCaptureStartParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filterData", v.FilterData) + populate(objectMap, "linkConnectionNames", v.LinkConnectionNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNConnectionPacketCaptureStartParameters. +func (v *VPNConnectionPacketCaptureStartParameters) UnmarshalJSON(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 "filterData": + err = unpopulate(val, "FilterData", &v.FilterData) + delete(rawMsg, key) + case "linkConnectionNames": + err = unpopulate(val, "LinkConnectionNames", &v.LinkConnectionNames) + 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 VPNConnectionPacketCaptureStopParameters. +func (v VPNConnectionPacketCaptureStopParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "linkConnectionNames", v.LinkConnectionNames) + populate(objectMap, "sasUrl", v.SasURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNConnectionPacketCaptureStopParameters. +func (v *VPNConnectionPacketCaptureStopParameters) UnmarshalJSON(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 "linkConnectionNames": + err = unpopulate(val, "LinkConnectionNames", &v.LinkConnectionNames) + delete(rawMsg, key) + case "sasUrl": + err = unpopulate(val, "SasURL", &v.SasURL) + 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 VPNConnectionProperties. +func (v VPNConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionBandwidth", v.ConnectionBandwidth) + populate(objectMap, "connectionStatus", v.ConnectionStatus) + populate(objectMap, "dpdTimeoutSeconds", v.DpdTimeoutSeconds) + populate(objectMap, "egressBytesTransferred", v.EgressBytesTransferred) + populate(objectMap, "enableBgp", v.EnableBgp) + populate(objectMap, "enableInternetSecurity", v.EnableInternetSecurity) + populate(objectMap, "enableRateLimiting", v.EnableRateLimiting) + populate(objectMap, "ipsecPolicies", v.IPSecPolicies) + populate(objectMap, "ingressBytesTransferred", v.IngressBytesTransferred) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "remoteVpnSite", v.RemoteVPNSite) + populate(objectMap, "routingConfiguration", v.RoutingConfiguration) + populate(objectMap, "routingWeight", v.RoutingWeight) + populate(objectMap, "sharedKey", v.SharedKey) + populate(objectMap, "trafficSelectorPolicies", v.TrafficSelectorPolicies) + populate(objectMap, "useLocalAzureIpAddress", v.UseLocalAzureIPAddress) + populate(objectMap, "usePolicyBasedTrafficSelectors", v.UsePolicyBasedTrafficSelectors) + populate(objectMap, "vpnConnectionProtocolType", v.VPNConnectionProtocolType) + populate(objectMap, "vpnLinkConnections", v.VPNLinkConnections) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNConnectionProperties. +func (v *VPNConnectionProperties) UnmarshalJSON(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 "connectionBandwidth": + err = unpopulate(val, "ConnectionBandwidth", &v.ConnectionBandwidth) + delete(rawMsg, key) + case "connectionStatus": + err = unpopulate(val, "ConnectionStatus", &v.ConnectionStatus) + delete(rawMsg, key) + case "dpdTimeoutSeconds": + err = unpopulate(val, "DpdTimeoutSeconds", &v.DpdTimeoutSeconds) + delete(rawMsg, key) + case "egressBytesTransferred": + err = unpopulate(val, "EgressBytesTransferred", &v.EgressBytesTransferred) + delete(rawMsg, key) + case "enableBgp": + err = unpopulate(val, "EnableBgp", &v.EnableBgp) + delete(rawMsg, key) + case "enableInternetSecurity": + err = unpopulate(val, "EnableInternetSecurity", &v.EnableInternetSecurity) + delete(rawMsg, key) + case "enableRateLimiting": + err = unpopulate(val, "EnableRateLimiting", &v.EnableRateLimiting) + delete(rawMsg, key) + case "ipsecPolicies": + err = unpopulate(val, "IPSecPolicies", &v.IPSecPolicies) + delete(rawMsg, key) + case "ingressBytesTransferred": + err = unpopulate(val, "IngressBytesTransferred", &v.IngressBytesTransferred) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "remoteVpnSite": + err = unpopulate(val, "RemoteVPNSite", &v.RemoteVPNSite) + delete(rawMsg, key) + case "routingConfiguration": + err = unpopulate(val, "RoutingConfiguration", &v.RoutingConfiguration) + delete(rawMsg, key) + case "routingWeight": + err = unpopulate(val, "RoutingWeight", &v.RoutingWeight) + delete(rawMsg, key) + case "sharedKey": + err = unpopulate(val, "SharedKey", &v.SharedKey) + delete(rawMsg, key) + case "trafficSelectorPolicies": + err = unpopulate(val, "TrafficSelectorPolicies", &v.TrafficSelectorPolicies) + delete(rawMsg, key) + case "useLocalAzureIpAddress": + err = unpopulate(val, "UseLocalAzureIPAddress", &v.UseLocalAzureIPAddress) + delete(rawMsg, key) + case "usePolicyBasedTrafficSelectors": + err = unpopulate(val, "UsePolicyBasedTrafficSelectors", &v.UsePolicyBasedTrafficSelectors) + delete(rawMsg, key) + case "vpnConnectionProtocolType": + err = unpopulate(val, "VPNConnectionProtocolType", &v.VPNConnectionProtocolType) + delete(rawMsg, key) + case "vpnLinkConnections": + err = unpopulate(val, "VPNLinkConnections", &v.VPNLinkConnections) + 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 VPNDeviceScriptParameters. +func (v VPNDeviceScriptParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deviceFamily", v.DeviceFamily) + populate(objectMap, "firmwareVersion", v.FirmwareVersion) + populate(objectMap, "vendor", v.Vendor) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNDeviceScriptParameters. +func (v *VPNDeviceScriptParameters) UnmarshalJSON(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 "deviceFamily": + err = unpopulate(val, "DeviceFamily", &v.DeviceFamily) + delete(rawMsg, key) + case "firmwareVersion": + err = unpopulate(val, "FirmwareVersion", &v.FirmwareVersion) + delete(rawMsg, key) + case "vendor": + err = unpopulate(val, "Vendor", &v.Vendor) + 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 VPNGateway. +func (v VPNGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGateway. +func (v *VPNGateway) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VPNGatewayIPConfiguration. +func (v VPNGatewayIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "privateIpAddress", v.PrivateIPAddress) + populate(objectMap, "publicIpAddress", v.PublicIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGatewayIPConfiguration. +func (v *VPNGatewayIPConfiguration) UnmarshalJSON(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 "privateIpAddress": + err = unpopulate(val, "PrivateIPAddress", &v.PrivateIPAddress) + delete(rawMsg, key) + case "publicIpAddress": + err = unpopulate(val, "PublicIPAddress", &v.PublicIPAddress) + 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 VPNGatewayNatRule. +func (v VPNGatewayNatRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VPNGatewayNatRule. +func (v *VPNGatewayNatRule) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VPNGatewayNatRuleProperties. +func (v VPNGatewayNatRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "egressVpnSiteLinkConnections", v.EgressVPNSiteLinkConnections) + populate(objectMap, "externalMappings", v.ExternalMappings) + populate(objectMap, "ipConfigurationId", v.IPConfigurationID) + populate(objectMap, "ingressVpnSiteLinkConnections", v.IngressVPNSiteLinkConnections) + populate(objectMap, "internalMappings", v.InternalMappings) + populate(objectMap, "mode", v.Mode) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGatewayNatRuleProperties. +func (v *VPNGatewayNatRuleProperties) UnmarshalJSON(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 "egressVpnSiteLinkConnections": + err = unpopulate(val, "EgressVPNSiteLinkConnections", &v.EgressVPNSiteLinkConnections) + delete(rawMsg, key) + case "externalMappings": + err = unpopulate(val, "ExternalMappings", &v.ExternalMappings) + delete(rawMsg, key) + case "ipConfigurationId": + err = unpopulate(val, "IPConfigurationID", &v.IPConfigurationID) + delete(rawMsg, key) + case "ingressVpnSiteLinkConnections": + err = unpopulate(val, "IngressVPNSiteLinkConnections", &v.IngressVPNSiteLinkConnections) + delete(rawMsg, key) + case "internalMappings": + err = unpopulate(val, "InternalMappings", &v.InternalMappings) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &v.Mode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + 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 VPNGatewayPacketCaptureStartParameters. +func (v VPNGatewayPacketCaptureStartParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filterData", v.FilterData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGatewayPacketCaptureStartParameters. +func (v *VPNGatewayPacketCaptureStartParameters) UnmarshalJSON(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 "filterData": + err = unpopulate(val, "FilterData", &v.FilterData) + 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 VPNGatewayPacketCaptureStopParameters. +func (v VPNGatewayPacketCaptureStopParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sasUrl", v.SasURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGatewayPacketCaptureStopParameters. +func (v *VPNGatewayPacketCaptureStopParameters) UnmarshalJSON(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 "sasUrl": + err = unpopulate(val, "SasURL", &v.SasURL) + 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 VPNGatewayProperties. +func (v VPNGatewayProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bgpSettings", v.BgpSettings) + populate(objectMap, "connections", v.Connections) + populate(objectMap, "enableBgpRouteTranslationForNat", v.EnableBgpRouteTranslationForNat) + populate(objectMap, "ipConfigurations", v.IPConfigurations) + populate(objectMap, "isRoutingPreferenceInternet", v.IsRoutingPreferenceInternet) + populate(objectMap, "natRules", v.NatRules) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "vpnGatewayScaleUnit", v.VPNGatewayScaleUnit) + populate(objectMap, "virtualHub", v.VirtualHub) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGatewayProperties. +func (v *VPNGatewayProperties) UnmarshalJSON(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 "bgpSettings": + err = unpopulate(val, "BgpSettings", &v.BgpSettings) + delete(rawMsg, key) + case "connections": + err = unpopulate(val, "Connections", &v.Connections) + delete(rawMsg, key) + case "enableBgpRouteTranslationForNat": + err = unpopulate(val, "EnableBgpRouteTranslationForNat", &v.EnableBgpRouteTranslationForNat) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &v.IPConfigurations) + delete(rawMsg, key) + case "isRoutingPreferenceInternet": + err = unpopulate(val, "IsRoutingPreferenceInternet", &v.IsRoutingPreferenceInternet) + delete(rawMsg, key) + case "natRules": + err = unpopulate(val, "NatRules", &v.NatRules) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "vpnGatewayScaleUnit": + err = unpopulate(val, "VPNGatewayScaleUnit", &v.VPNGatewayScaleUnit) + delete(rawMsg, key) + case "virtualHub": + err = unpopulate(val, "VirtualHub", &v.VirtualHub) + 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 VPNLinkBgpSettings. +func (v VPNLinkBgpSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asn", v.Asn) + populate(objectMap, "bgpPeeringAddress", v.BgpPeeringAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNLinkBgpSettings. +func (v *VPNLinkBgpSettings) UnmarshalJSON(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 "asn": + err = unpopulate(val, "Asn", &v.Asn) + delete(rawMsg, key) + case "bgpPeeringAddress": + err = unpopulate(val, "BgpPeeringAddress", &v.BgpPeeringAddress) + 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 VPNLinkProviderProperties. +func (v VPNLinkProviderProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "linkProviderName", v.LinkProviderName) + populate(objectMap, "linkSpeedInMbps", v.LinkSpeedInMbps) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNLinkProviderProperties. +func (v *VPNLinkProviderProperties) UnmarshalJSON(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 "linkProviderName": + err = unpopulate(val, "LinkProviderName", &v.LinkProviderName) + delete(rawMsg, key) + case "linkSpeedInMbps": + err = unpopulate(val, "LinkSpeedInMbps", &v.LinkSpeedInMbps) + 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 VPNNatRuleMapping. +func (v VPNNatRuleMapping) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressSpace", v.AddressSpace) + populate(objectMap, "portRange", v.PortRange) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNNatRuleMapping. +func (v *VPNNatRuleMapping) UnmarshalJSON(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 "addressSpace": + err = unpopulate(val, "AddressSpace", &v.AddressSpace) + delete(rawMsg, key) + case "portRange": + err = unpopulate(val, "PortRange", &v.PortRange) + 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 VPNPacketCaptureStartParameters. +func (v VPNPacketCaptureStartParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filterData", v.FilterData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNPacketCaptureStartParameters. +func (v *VPNPacketCaptureStartParameters) UnmarshalJSON(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 "filterData": + err = unpopulate(val, "FilterData", &v.FilterData) + 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 VPNPacketCaptureStopParameters. +func (v VPNPacketCaptureStopParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sasUrl", v.SasURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNPacketCaptureStopParameters. +func (v *VPNPacketCaptureStopParameters) UnmarshalJSON(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 "sasUrl": + err = unpopulate(val, "SasURL", &v.SasURL) + 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 VPNProfileResponse. +func (v VPNProfileResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "profileUrl", v.ProfileURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNProfileResponse. +func (v *VPNProfileResponse) UnmarshalJSON(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 "profileUrl": + err = unpopulate(val, "ProfileURL", &v.ProfileURL) + 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 VPNServerConfigRadiusClientRootCertificate. +func (v VPNServerConfigRadiusClientRootCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "thumbprint", v.Thumbprint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigRadiusClientRootCertificate. +func (v *VPNServerConfigRadiusClientRootCertificate) UnmarshalJSON(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 "thumbprint": + err = unpopulate(val, "Thumbprint", &v.Thumbprint) + 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 VPNServerConfigRadiusServerRootCertificate. +func (v VPNServerConfigRadiusServerRootCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "publicCertData", v.PublicCertData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigRadiusServerRootCertificate. +func (v *VPNServerConfigRadiusServerRootCertificate) UnmarshalJSON(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 "publicCertData": + err = unpopulate(val, "PublicCertData", &v.PublicCertData) + 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 VPNServerConfigVPNClientRevokedCertificate. +func (v VPNServerConfigVPNClientRevokedCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "thumbprint", v.Thumbprint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigVPNClientRevokedCertificate. +func (v *VPNServerConfigVPNClientRevokedCertificate) UnmarshalJSON(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 "thumbprint": + err = unpopulate(val, "Thumbprint", &v.Thumbprint) + 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 VPNServerConfigVPNClientRootCertificate. +func (v VPNServerConfigVPNClientRootCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "publicCertData", v.PublicCertData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigVPNClientRootCertificate. +func (v *VPNServerConfigVPNClientRootCertificate) UnmarshalJSON(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 "publicCertData": + err = unpopulate(val, "PublicCertData", &v.PublicCertData) + 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 VPNServerConfiguration. +func (v VPNServerConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfiguration. +func (v *VPNServerConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VPNServerConfigurationPolicyGroup. +func (v VPNServerConfigurationPolicyGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VPNServerConfigurationPolicyGroup. +func (v *VPNServerConfigurationPolicyGroup) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VPNServerConfigurationPolicyGroupMember. +func (v VPNServerConfigurationPolicyGroupMember) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributeType", v.AttributeType) + populate(objectMap, "attributeValue", v.AttributeValue) + populate(objectMap, "name", v.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigurationPolicyGroupMember. +func (v *VPNServerConfigurationPolicyGroupMember) UnmarshalJSON(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 "attributeType": + err = unpopulate(val, "AttributeType", &v.AttributeType) + delete(rawMsg, key) + case "attributeValue": + err = unpopulate(val, "AttributeValue", &v.AttributeValue) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + 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 VPNServerConfigurationPolicyGroupProperties. +func (v VPNServerConfigurationPolicyGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isDefault", v.IsDefault) + populate(objectMap, "p2SConnectionConfigurations", v.P2SConnectionConfigurations) + populate(objectMap, "policyMembers", v.PolicyMembers) + populate(objectMap, "priority", v.Priority) + populate(objectMap, "provisioningState", v.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigurationPolicyGroupProperties. +func (v *VPNServerConfigurationPolicyGroupProperties) UnmarshalJSON(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 "isDefault": + err = unpopulate(val, "IsDefault", &v.IsDefault) + delete(rawMsg, key) + case "p2SConnectionConfigurations": + err = unpopulate(val, "P2SConnectionConfigurations", &v.P2SConnectionConfigurations) + delete(rawMsg, key) + case "policyMembers": + err = unpopulate(val, "PolicyMembers", &v.PolicyMembers) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &v.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + 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 VPNServerConfigurationProperties. +func (v VPNServerConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aadAuthenticationParameters", v.AADAuthenticationParameters) + populate(objectMap, "configurationPolicyGroups", v.ConfigurationPolicyGroups) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "name", v.Name) + populate(objectMap, "p2SVpnGateways", v.P2SVPNGateways) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "radiusClientRootCertificates", v.RadiusClientRootCertificates) + populate(objectMap, "radiusServerAddress", v.RadiusServerAddress) + populate(objectMap, "radiusServerRootCertificates", v.RadiusServerRootCertificates) + populate(objectMap, "radiusServerSecret", v.RadiusServerSecret) + populate(objectMap, "radiusServers", v.RadiusServers) + populate(objectMap, "vpnAuthenticationTypes", v.VPNAuthenticationTypes) + populate(objectMap, "vpnClientIpsecPolicies", v.VPNClientIPSecPolicies) + populate(objectMap, "vpnClientRevokedCertificates", v.VPNClientRevokedCertificates) + populate(objectMap, "vpnClientRootCertificates", v.VPNClientRootCertificates) + populate(objectMap, "vpnProtocols", v.VPNProtocols) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigurationProperties. +func (v *VPNServerConfigurationProperties) UnmarshalJSON(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 "aadAuthenticationParameters": + err = unpopulate(val, "AADAuthenticationParameters", &v.AADAuthenticationParameters) + delete(rawMsg, key) + case "configurationPolicyGroups": + err = unpopulate(val, "ConfigurationPolicyGroups", &v.ConfigurationPolicyGroups) + delete(rawMsg, key) + case "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "p2SVpnGateways": + err = unpopulate(val, "P2SVPNGateways", &v.P2SVPNGateways) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "radiusClientRootCertificates": + err = unpopulate(val, "RadiusClientRootCertificates", &v.RadiusClientRootCertificates) + delete(rawMsg, key) + case "radiusServerAddress": + err = unpopulate(val, "RadiusServerAddress", &v.RadiusServerAddress) + delete(rawMsg, key) + case "radiusServerRootCertificates": + err = unpopulate(val, "RadiusServerRootCertificates", &v.RadiusServerRootCertificates) + delete(rawMsg, key) + case "radiusServerSecret": + err = unpopulate(val, "RadiusServerSecret", &v.RadiusServerSecret) + delete(rawMsg, key) + case "radiusServers": + err = unpopulate(val, "RadiusServers", &v.RadiusServers) + delete(rawMsg, key) + case "vpnAuthenticationTypes": + err = unpopulate(val, "VPNAuthenticationTypes", &v.VPNAuthenticationTypes) + delete(rawMsg, key) + case "vpnClientIpsecPolicies": + err = unpopulate(val, "VPNClientIPSecPolicies", &v.VPNClientIPSecPolicies) + delete(rawMsg, key) + case "vpnClientRevokedCertificates": + err = unpopulate(val, "VPNClientRevokedCertificates", &v.VPNClientRevokedCertificates) + delete(rawMsg, key) + case "vpnClientRootCertificates": + err = unpopulate(val, "VPNClientRootCertificates", &v.VPNClientRootCertificates) + delete(rawMsg, key) + case "vpnProtocols": + err = unpopulate(val, "VPNProtocols", &v.VPNProtocols) + 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 VPNServerConfigurationsResponse. +func (v VPNServerConfigurationsResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vpnServerConfigurationResourceIds", v.VPNServerConfigurationResourceIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNServerConfigurationsResponse. +func (v *VPNServerConfigurationsResponse) UnmarshalJSON(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 "vpnServerConfigurationResourceIds": + err = unpopulate(val, "VPNServerConfigurationResourceIDs", &v.VPNServerConfigurationResourceIDs) + 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 VPNSite. +func (v VPNSite) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNSite. +func (v *VPNSite) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VPNSiteID. +func (v VPNSiteID) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vpnSite", v.VPNSite) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNSiteID. +func (v *VPNSiteID) UnmarshalJSON(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 "vpnSite": + err = unpopulate(val, "VPNSite", &v.VPNSite) + 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 VPNSiteLink. +func (v VPNSiteLink) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VPNSiteLink. +func (v *VPNSiteLink) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VPNSiteLinkConnection. +func (v VPNSiteLinkConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VPNSiteLinkConnection. +func (v *VPNSiteLinkConnection) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VPNSiteLinkConnectionProperties. +func (v VPNSiteLinkConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionBandwidth", v.ConnectionBandwidth) + populate(objectMap, "connectionStatus", v.ConnectionStatus) + populate(objectMap, "egressBytesTransferred", v.EgressBytesTransferred) + populate(objectMap, "egressNatRules", v.EgressNatRules) + populate(objectMap, "enableBgp", v.EnableBgp) + populate(objectMap, "enableRateLimiting", v.EnableRateLimiting) + populate(objectMap, "ipsecPolicies", v.IPSecPolicies) + populate(objectMap, "ingressBytesTransferred", v.IngressBytesTransferred) + populate(objectMap, "ingressNatRules", v.IngressNatRules) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "routingWeight", v.RoutingWeight) + populate(objectMap, "sharedKey", v.SharedKey) + populate(objectMap, "useLocalAzureIpAddress", v.UseLocalAzureIPAddress) + populate(objectMap, "usePolicyBasedTrafficSelectors", v.UsePolicyBasedTrafficSelectors) + populate(objectMap, "vpnConnectionProtocolType", v.VPNConnectionProtocolType) + populate(objectMap, "vpnGatewayCustomBgpAddresses", v.VPNGatewayCustomBgpAddresses) + populate(objectMap, "vpnLinkConnectionMode", v.VPNLinkConnectionMode) + populate(objectMap, "vpnSiteLink", v.VPNSiteLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNSiteLinkConnectionProperties. +func (v *VPNSiteLinkConnectionProperties) UnmarshalJSON(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 "connectionBandwidth": + err = unpopulate(val, "ConnectionBandwidth", &v.ConnectionBandwidth) + delete(rawMsg, key) + case "connectionStatus": + err = unpopulate(val, "ConnectionStatus", &v.ConnectionStatus) + delete(rawMsg, key) + case "egressBytesTransferred": + err = unpopulate(val, "EgressBytesTransferred", &v.EgressBytesTransferred) + delete(rawMsg, key) + case "egressNatRules": + err = unpopulate(val, "EgressNatRules", &v.EgressNatRules) + delete(rawMsg, key) + case "enableBgp": + err = unpopulate(val, "EnableBgp", &v.EnableBgp) + delete(rawMsg, key) + case "enableRateLimiting": + err = unpopulate(val, "EnableRateLimiting", &v.EnableRateLimiting) + delete(rawMsg, key) + case "ipsecPolicies": + err = unpopulate(val, "IPSecPolicies", &v.IPSecPolicies) + delete(rawMsg, key) + case "ingressBytesTransferred": + err = unpopulate(val, "IngressBytesTransferred", &v.IngressBytesTransferred) + delete(rawMsg, key) + case "ingressNatRules": + err = unpopulate(val, "IngressNatRules", &v.IngressNatRules) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "routingWeight": + err = unpopulate(val, "RoutingWeight", &v.RoutingWeight) + delete(rawMsg, key) + case "sharedKey": + err = unpopulate(val, "SharedKey", &v.SharedKey) + delete(rawMsg, key) + case "useLocalAzureIpAddress": + err = unpopulate(val, "UseLocalAzureIPAddress", &v.UseLocalAzureIPAddress) + delete(rawMsg, key) + case "usePolicyBasedTrafficSelectors": + err = unpopulate(val, "UsePolicyBasedTrafficSelectors", &v.UsePolicyBasedTrafficSelectors) + delete(rawMsg, key) + case "vpnConnectionProtocolType": + err = unpopulate(val, "VPNConnectionProtocolType", &v.VPNConnectionProtocolType) + delete(rawMsg, key) + case "vpnGatewayCustomBgpAddresses": + err = unpopulate(val, "VPNGatewayCustomBgpAddresses", &v.VPNGatewayCustomBgpAddresses) + delete(rawMsg, key) + case "vpnLinkConnectionMode": + err = unpopulate(val, "VPNLinkConnectionMode", &v.VPNLinkConnectionMode) + delete(rawMsg, key) + case "vpnSiteLink": + err = unpopulate(val, "VPNSiteLink", &v.VPNSiteLink) + 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 VPNSiteLinkProperties. +func (v VPNSiteLinkProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bgpProperties", v.BgpProperties) + populate(objectMap, "fqdn", v.Fqdn) + populate(objectMap, "ipAddress", v.IPAddress) + populate(objectMap, "linkProperties", v.LinkProperties) + populate(objectMap, "provisioningState", v.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNSiteLinkProperties. +func (v *VPNSiteLinkProperties) UnmarshalJSON(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 "bgpProperties": + err = unpopulate(val, "BgpProperties", &v.BgpProperties) + delete(rawMsg, key) + case "fqdn": + err = unpopulate(val, "Fqdn", &v.Fqdn) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &v.IPAddress) + delete(rawMsg, key) + case "linkProperties": + err = unpopulate(val, "LinkProperties", &v.LinkProperties) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + 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 VPNSiteProperties. +func (v VPNSiteProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressSpace", v.AddressSpace) + populate(objectMap, "bgpProperties", v.BgpProperties) + populate(objectMap, "deviceProperties", v.DeviceProperties) + populate(objectMap, "ipAddress", v.IPAddress) + populate(objectMap, "isSecuritySite", v.IsSecuritySite) + populate(objectMap, "o365Policy", v.O365Policy) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "siteKey", v.SiteKey) + populate(objectMap, "vpnSiteLinks", v.VPNSiteLinks) + populate(objectMap, "virtualWan", v.VirtualWan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNSiteProperties. +func (v *VPNSiteProperties) UnmarshalJSON(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 "addressSpace": + err = unpopulate(val, "AddressSpace", &v.AddressSpace) + delete(rawMsg, key) + case "bgpProperties": + err = unpopulate(val, "BgpProperties", &v.BgpProperties) + delete(rawMsg, key) + case "deviceProperties": + err = unpopulate(val, "DeviceProperties", &v.DeviceProperties) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &v.IPAddress) + delete(rawMsg, key) + case "isSecuritySite": + err = unpopulate(val, "IsSecuritySite", &v.IsSecuritySite) + delete(rawMsg, key) + case "o365Policy": + err = unpopulate(val, "O365Policy", &v.O365Policy) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "siteKey": + err = unpopulate(val, "SiteKey", &v.SiteKey) + delete(rawMsg, key) + case "vpnSiteLinks": + err = unpopulate(val, "VPNSiteLinks", &v.VPNSiteLinks) + delete(rawMsg, key) + case "virtualWan": + err = unpopulate(val, "VirtualWan", &v.VirtualWan) + 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 VerificationIPFlowParameters. +func (v VerificationIPFlowParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "direction", v.Direction) + populate(objectMap, "localIPAddress", v.LocalIPAddress) + populate(objectMap, "localPort", v.LocalPort) + populate(objectMap, "protocol", v.Protocol) + populate(objectMap, "remoteIPAddress", v.RemoteIPAddress) + populate(objectMap, "remotePort", v.RemotePort) + populate(objectMap, "targetNicResourceId", v.TargetNicResourceID) + populate(objectMap, "targetResourceId", v.TargetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VerificationIPFlowParameters. +func (v *VerificationIPFlowParameters) UnmarshalJSON(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 "direction": + err = unpopulate(val, "Direction", &v.Direction) + delete(rawMsg, key) + case "localIPAddress": + err = unpopulate(val, "LocalIPAddress", &v.LocalIPAddress) + delete(rawMsg, key) + case "localPort": + err = unpopulate(val, "LocalPort", &v.LocalPort) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &v.Protocol) + delete(rawMsg, key) + case "remoteIPAddress": + err = unpopulate(val, "RemoteIPAddress", &v.RemoteIPAddress) + delete(rawMsg, key) + case "remotePort": + err = unpopulate(val, "RemotePort", &v.RemotePort) + delete(rawMsg, key) + case "targetNicResourceId": + err = unpopulate(val, "TargetNicResourceID", &v.TargetNicResourceID) + delete(rawMsg, key) + case "targetResourceId": + err = unpopulate(val, "TargetResourceID", &v.TargetResourceID) + 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 VerificationIPFlowResult. +func (v VerificationIPFlowResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "access", v.Access) + populate(objectMap, "ruleName", v.RuleName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VerificationIPFlowResult. +func (v *VerificationIPFlowResult) UnmarshalJSON(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 "access": + err = unpopulate(val, "Access", &v.Access) + delete(rawMsg, key) + case "ruleName": + err = unpopulate(val, "RuleName", &v.RuleName) + 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 VirtualAppliance. +func (v VirtualAppliance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "identity", v.Identity) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualAppliance. +func (v *VirtualAppliance) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &v.Identity) + 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 "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 VirtualApplianceAdditionalNicProperties. +func (v VirtualApplianceAdditionalNicProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hasPublicIp", v.HasPublicIP) + populate(objectMap, "name", v.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceAdditionalNicProperties. +func (v *VirtualApplianceAdditionalNicProperties) UnmarshalJSON(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 "hasPublicIp": + err = unpopulate(val, "HasPublicIP", &v.HasPublicIP) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + 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 VirtualApplianceConnection. +func (v VirtualApplianceConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceConnection. +func (v *VirtualApplianceConnection) UnmarshalJSON(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 "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + 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 VirtualApplianceConnectionList. +func (v VirtualApplianceConnectionList) 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 VirtualApplianceConnectionList. +func (v *VirtualApplianceConnectionList) UnmarshalJSON(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 VirtualApplianceConnectionProperties. +func (v VirtualApplianceConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "asn", v.Asn) + populate(objectMap, "bgpPeerAddress", v.BgpPeerAddress) + populate(objectMap, "enableInternetSecurity", v.EnableInternetSecurity) + populate(objectMap, "name", v.Name) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "routingConfiguration", v.RoutingConfiguration) + populate(objectMap, "tunnelIdentifier", v.TunnelIdentifier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceConnectionProperties. +func (v *VirtualApplianceConnectionProperties) UnmarshalJSON(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 "asn": + err = unpopulate(val, "Asn", &v.Asn) + delete(rawMsg, key) + case "bgpPeerAddress": + err = unpopulate(val, "BgpPeerAddress", &v.BgpPeerAddress) + delete(rawMsg, key) + case "enableInternetSecurity": + err = unpopulate(val, "EnableInternetSecurity", &v.EnableInternetSecurity) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "routingConfiguration": + err = unpopulate(val, "RoutingConfiguration", &v.RoutingConfiguration) + delete(rawMsg, key) + case "tunnelIdentifier": + err = unpopulate(val, "TunnelIdentifier", &v.TunnelIdentifier) + 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 VirtualApplianceListResult. +func (v VirtualApplianceListResult) 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 VirtualApplianceListResult. +func (v *VirtualApplianceListResult) UnmarshalJSON(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 VirtualApplianceNicProperties. +func (v VirtualApplianceNicProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceName", v.InstanceName) + populate(objectMap, "name", v.Name) + populate(objectMap, "privateIpAddress", v.PrivateIPAddress) + populate(objectMap, "publicIpAddress", v.PublicIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceNicProperties. +func (v *VirtualApplianceNicProperties) UnmarshalJSON(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 "instanceName": + err = unpopulate(val, "InstanceName", &v.InstanceName) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "privateIpAddress": + err = unpopulate(val, "PrivateIPAddress", &v.PrivateIPAddress) + delete(rawMsg, key) + case "publicIpAddress": + err = unpopulate(val, "PublicIPAddress", &v.PublicIPAddress) + 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 VirtualAppliancePropertiesFormat. +func (v VirtualAppliancePropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalNics", v.AdditionalNics) + populate(objectMap, "addressPrefix", v.AddressPrefix) + populate(objectMap, "bootStrapConfigurationBlobs", v.BootStrapConfigurationBlobs) + populate(objectMap, "cloudInitConfiguration", v.CloudInitConfiguration) + populate(objectMap, "cloudInitConfigurationBlobs", v.CloudInitConfigurationBlobs) + populate(objectMap, "delegation", v.Delegation) + populate(objectMap, "deploymentType", v.DeploymentType) + populate(objectMap, "inboundSecurityRules", v.InboundSecurityRules) + populate(objectMap, "nvaSku", v.NvaSKU) + populate(objectMap, "partnerManagedResource", v.PartnerManagedResource) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "sshPublicKey", v.SSHPublicKey) + populate(objectMap, "virtualApplianceAsn", v.VirtualApplianceAsn) + populate(objectMap, "virtualApplianceConnections", v.VirtualApplianceConnections) + populate(objectMap, "virtualApplianceNics", v.VirtualApplianceNics) + populate(objectMap, "virtualApplianceSites", v.VirtualApplianceSites) + populate(objectMap, "virtualHub", v.VirtualHub) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualAppliancePropertiesFormat. +func (v *VirtualAppliancePropertiesFormat) UnmarshalJSON(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 "additionalNics": + err = unpopulate(val, "AdditionalNics", &v.AdditionalNics) + delete(rawMsg, key) + case "addressPrefix": + err = unpopulate(val, "AddressPrefix", &v.AddressPrefix) + delete(rawMsg, key) + case "bootStrapConfigurationBlobs": + err = unpopulate(val, "BootStrapConfigurationBlobs", &v.BootStrapConfigurationBlobs) + delete(rawMsg, key) + case "cloudInitConfiguration": + err = unpopulate(val, "CloudInitConfiguration", &v.CloudInitConfiguration) + delete(rawMsg, key) + case "cloudInitConfigurationBlobs": + err = unpopulate(val, "CloudInitConfigurationBlobs", &v.CloudInitConfigurationBlobs) + delete(rawMsg, key) + case "delegation": + err = unpopulate(val, "Delegation", &v.Delegation) + delete(rawMsg, key) + case "deploymentType": + err = unpopulate(val, "DeploymentType", &v.DeploymentType) + delete(rawMsg, key) + case "inboundSecurityRules": + err = unpopulate(val, "InboundSecurityRules", &v.InboundSecurityRules) + delete(rawMsg, key) + case "nvaSku": + err = unpopulate(val, "NvaSKU", &v.NvaSKU) + delete(rawMsg, key) + case "partnerManagedResource": + err = unpopulate(val, "PartnerManagedResource", &v.PartnerManagedResource) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "sshPublicKey": + err = unpopulate(val, "SSHPublicKey", &v.SSHPublicKey) + delete(rawMsg, key) + case "virtualApplianceAsn": + err = unpopulate(val, "VirtualApplianceAsn", &v.VirtualApplianceAsn) + delete(rawMsg, key) + case "virtualApplianceConnections": + err = unpopulate(val, "VirtualApplianceConnections", &v.VirtualApplianceConnections) + delete(rawMsg, key) + case "virtualApplianceNics": + err = unpopulate(val, "VirtualApplianceNics", &v.VirtualApplianceNics) + delete(rawMsg, key) + case "virtualApplianceSites": + err = unpopulate(val, "VirtualApplianceSites", &v.VirtualApplianceSites) + delete(rawMsg, key) + case "virtualHub": + err = unpopulate(val, "VirtualHub", &v.VirtualHub) + 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 VirtualApplianceSKU. +func (v VirtualApplianceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceSKU. +func (v *VirtualApplianceSKU) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VirtualApplianceSKUInstances. +func (v VirtualApplianceSKUInstances) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceCount", v.InstanceCount) + populate(objectMap, "scaleUnit", v.ScaleUnit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceSKUInstances. +func (v *VirtualApplianceSKUInstances) UnmarshalJSON(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 "instanceCount": + err = unpopulate(val, "InstanceCount", &v.InstanceCount) + delete(rawMsg, key) + case "scaleUnit": + err = unpopulate(val, "ScaleUnit", &v.ScaleUnit) + 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 VirtualApplianceSKUListResult. +func (v VirtualApplianceSKUListResult) 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 VirtualApplianceSKUListResult. +func (v *VirtualApplianceSKUListResult) UnmarshalJSON(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 VirtualApplianceSKUProperties. +func (v VirtualApplianceSKUProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bundledScaleUnit", v.BundledScaleUnit) + populate(objectMap, "marketPlaceVersion", v.MarketPlaceVersion) + populate(objectMap, "vendor", v.Vendor) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceSKUProperties. +func (v *VirtualApplianceSKUProperties) UnmarshalJSON(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 "bundledScaleUnit": + err = unpopulate(val, "BundledScaleUnit", &v.BundledScaleUnit) + delete(rawMsg, key) + case "marketPlaceVersion": + err = unpopulate(val, "MarketPlaceVersion", &v.MarketPlaceVersion) + delete(rawMsg, key) + case "vendor": + err = unpopulate(val, "Vendor", &v.Vendor) + 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 VirtualApplianceSKUPropertiesFormat. +func (v VirtualApplianceSKUPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableScaleUnits", v.AvailableScaleUnits) + populate(objectMap, "availableVersions", v.AvailableVersions) + populate(objectMap, "vendor", v.Vendor) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceSKUPropertiesFormat. +func (v *VirtualApplianceSKUPropertiesFormat) UnmarshalJSON(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 "availableScaleUnits": + err = unpopulate(val, "AvailableScaleUnits", &v.AvailableScaleUnits) + delete(rawMsg, key) + case "availableVersions": + err = unpopulate(val, "AvailableVersions", &v.AvailableVersions) + delete(rawMsg, key) + case "vendor": + err = unpopulate(val, "Vendor", &v.Vendor) + 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 VirtualApplianceSite. +func (v VirtualApplianceSite) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VirtualApplianceSite. +func (v *VirtualApplianceSite) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VirtualApplianceSiteListResult. +func (v VirtualApplianceSiteListResult) 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 VirtualApplianceSiteListResult. +func (v *VirtualApplianceSiteListResult) UnmarshalJSON(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 VirtualApplianceSiteProperties. +func (v VirtualApplianceSiteProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", v.AddressPrefix) + populate(objectMap, "o365Policy", v.O365Policy) + populate(objectMap, "provisioningState", v.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualApplianceSiteProperties. +func (v *VirtualApplianceSiteProperties) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &v.AddressPrefix) + delete(rawMsg, key) + case "o365Policy": + err = unpopulate(val, "O365Policy", &v.O365Policy) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + 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 VirtualHub. +func (v VirtualHub) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "kind", v.Kind) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHub. +func (v *VirtualHub) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &v.Kind) + 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 "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 VirtualHubEffectiveRoute. +func (v VirtualHubEffectiveRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefixes", v.AddressPrefixes) + populate(objectMap, "asPath", v.AsPath) + populate(objectMap, "nextHopType", v.NextHopType) + populate(objectMap, "nextHops", v.NextHops) + populate(objectMap, "routeOrigin", v.RouteOrigin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubEffectiveRoute. +func (v *VirtualHubEffectiveRoute) UnmarshalJSON(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 "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &v.AddressPrefixes) + delete(rawMsg, key) + case "asPath": + err = unpopulate(val, "AsPath", &v.AsPath) + delete(rawMsg, key) + case "nextHopType": + err = unpopulate(val, "NextHopType", &v.NextHopType) + delete(rawMsg, key) + case "nextHops": + err = unpopulate(val, "NextHops", &v.NextHops) + delete(rawMsg, key) + case "routeOrigin": + err = unpopulate(val, "RouteOrigin", &v.RouteOrigin) + 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 VirtualHubEffectiveRouteList. +func (v VirtualHubEffectiveRouteList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubEffectiveRouteList. +func (v *VirtualHubEffectiveRouteList) UnmarshalJSON(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 "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 VirtualHubID. +func (v VirtualHubID) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubID. +func (v *VirtualHubID) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualHubProperties. +func (v VirtualHubProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefix", v.AddressPrefix) + populate(objectMap, "allowBranchToBranchTraffic", v.AllowBranchToBranchTraffic) + populate(objectMap, "azureFirewall", v.AzureFirewall) + populate(objectMap, "bgpConnections", v.BgpConnections) + populate(objectMap, "expressRouteGateway", v.ExpressRouteGateway) + populate(objectMap, "hubRoutingPreference", v.HubRoutingPreference) + populate(objectMap, "ipConfigurations", v.IPConfigurations) + populate(objectMap, "p2SVpnGateway", v.P2SVPNGateway) + populate(objectMap, "preferredRoutingGateway", v.PreferredRoutingGateway) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "routeMaps", v.RouteMaps) + populate(objectMap, "routeTable", v.RouteTable) + populate(objectMap, "routingState", v.RoutingState) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "securityPartnerProvider", v.SecurityPartnerProvider) + populate(objectMap, "securityProviderName", v.SecurityProviderName) + populate(objectMap, "vpnGateway", v.VPNGateway) + populate(objectMap, "virtualHubRouteTableV2s", v.VirtualHubRouteTableV2S) + populate(objectMap, "virtualRouterAsn", v.VirtualRouterAsn) + populate(objectMap, "virtualRouterAutoScaleConfiguration", v.VirtualRouterAutoScaleConfiguration) + populate(objectMap, "virtualRouterIps", v.VirtualRouterIPs) + populate(objectMap, "virtualWan", v.VirtualWan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubProperties. +func (v *VirtualHubProperties) UnmarshalJSON(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 "addressPrefix": + err = unpopulate(val, "AddressPrefix", &v.AddressPrefix) + delete(rawMsg, key) + case "allowBranchToBranchTraffic": + err = unpopulate(val, "AllowBranchToBranchTraffic", &v.AllowBranchToBranchTraffic) + delete(rawMsg, key) + case "azureFirewall": + err = unpopulate(val, "AzureFirewall", &v.AzureFirewall) + delete(rawMsg, key) + case "bgpConnections": + err = unpopulate(val, "BgpConnections", &v.BgpConnections) + delete(rawMsg, key) + case "expressRouteGateway": + err = unpopulate(val, "ExpressRouteGateway", &v.ExpressRouteGateway) + delete(rawMsg, key) + case "hubRoutingPreference": + err = unpopulate(val, "HubRoutingPreference", &v.HubRoutingPreference) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &v.IPConfigurations) + delete(rawMsg, key) + case "p2SVpnGateway": + err = unpopulate(val, "P2SVPNGateway", &v.P2SVPNGateway) + delete(rawMsg, key) + case "preferredRoutingGateway": + err = unpopulate(val, "PreferredRoutingGateway", &v.PreferredRoutingGateway) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "routeMaps": + err = unpopulate(val, "RouteMaps", &v.RouteMaps) + delete(rawMsg, key) + case "routeTable": + err = unpopulate(val, "RouteTable", &v.RouteTable) + delete(rawMsg, key) + case "routingState": + err = unpopulate(val, "RoutingState", &v.RoutingState) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + delete(rawMsg, key) + case "securityPartnerProvider": + err = unpopulate(val, "SecurityPartnerProvider", &v.SecurityPartnerProvider) + delete(rawMsg, key) + case "securityProviderName": + err = unpopulate(val, "SecurityProviderName", &v.SecurityProviderName) + delete(rawMsg, key) + case "vpnGateway": + err = unpopulate(val, "VPNGateway", &v.VPNGateway) + delete(rawMsg, key) + case "virtualHubRouteTableV2s": + err = unpopulate(val, "VirtualHubRouteTableV2S", &v.VirtualHubRouteTableV2S) + delete(rawMsg, key) + case "virtualRouterAsn": + err = unpopulate(val, "VirtualRouterAsn", &v.VirtualRouterAsn) + delete(rawMsg, key) + case "virtualRouterAutoScaleConfiguration": + err = unpopulate(val, "VirtualRouterAutoScaleConfiguration", &v.VirtualRouterAutoScaleConfiguration) + delete(rawMsg, key) + case "virtualRouterIps": + err = unpopulate(val, "VirtualRouterIPs", &v.VirtualRouterIPs) + delete(rawMsg, key) + case "virtualWan": + err = unpopulate(val, "VirtualWan", &v.VirtualWan) + 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 VirtualHubRoute. +func (v VirtualHubRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefixes", v.AddressPrefixes) + populate(objectMap, "nextHopIpAddress", v.NextHopIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubRoute. +func (v *VirtualHubRoute) UnmarshalJSON(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 "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &v.AddressPrefixes) + delete(rawMsg, key) + case "nextHopIpAddress": + err = unpopulate(val, "NextHopIPAddress", &v.NextHopIPAddress) + 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 VirtualHubRouteTable. +func (v VirtualHubRouteTable) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "routes", v.Routes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubRouteTable. +func (v *VirtualHubRouteTable) UnmarshalJSON(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 "routes": + err = unpopulate(val, "Routes", &v.Routes) + 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 VirtualHubRouteTableV2. +func (v VirtualHubRouteTableV2) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubRouteTableV2. +func (v *VirtualHubRouteTableV2) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualHubRouteTableV2Properties. +func (v VirtualHubRouteTableV2Properties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attachedConnections", v.AttachedConnections) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "routes", v.Routes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubRouteTableV2Properties. +func (v *VirtualHubRouteTableV2Properties) UnmarshalJSON(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 "attachedConnections": + err = unpopulate(val, "AttachedConnections", &v.AttachedConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "routes": + err = unpopulate(val, "Routes", &v.Routes) + 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 VirtualHubRouteV2. +func (v VirtualHubRouteV2) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationType", v.DestinationType) + populate(objectMap, "destinations", v.Destinations) + populate(objectMap, "nextHopType", v.NextHopType) + populate(objectMap, "nextHops", v.NextHops) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubRouteV2. +func (v *VirtualHubRouteV2) UnmarshalJSON(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 "destinationType": + err = unpopulate(val, "DestinationType", &v.DestinationType) + delete(rawMsg, key) + case "destinations": + err = unpopulate(val, "Destinations", &v.Destinations) + delete(rawMsg, key) + case "nextHopType": + err = unpopulate(val, "NextHopType", &v.NextHopType) + delete(rawMsg, key) + case "nextHops": + err = unpopulate(val, "NextHops", &v.NextHops) + 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 VirtualNetwork. +func (v VirtualNetwork) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "extendedLocation", v.ExtendedLocation) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetwork. +func (v *VirtualNetwork) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &v.ExtendedLocation) + delete(rawMsg, 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 "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 VirtualNetworkBgpCommunities. +func (v VirtualNetworkBgpCommunities) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "regionalCommunity", v.RegionalCommunity) + populate(objectMap, "virtualNetworkCommunity", v.VirtualNetworkCommunity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkBgpCommunities. +func (v *VirtualNetworkBgpCommunities) UnmarshalJSON(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 "regionalCommunity": + err = unpopulate(val, "RegionalCommunity", &v.RegionalCommunity) + delete(rawMsg, key) + case "virtualNetworkCommunity": + err = unpopulate(val, "VirtualNetworkCommunity", &v.VirtualNetworkCommunity) + 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 VirtualNetworkConnectionGatewayReference. +func (v VirtualNetworkConnectionGatewayReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkConnectionGatewayReference. +func (v *VirtualNetworkConnectionGatewayReference) UnmarshalJSON(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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkDdosProtectionStatusResult. +func (v VirtualNetworkDdosProtectionStatusResult) 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 VirtualNetworkDdosProtectionStatusResult. +func (v *VirtualNetworkDdosProtectionStatusResult) UnmarshalJSON(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 VirtualNetworkEncryption. +func (v VirtualNetworkEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", v.Enabled) + populate(objectMap, "enforcement", v.Enforcement) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkEncryption. +func (v *VirtualNetworkEncryption) UnmarshalJSON(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 "enabled": + err = unpopulate(val, "Enabled", &v.Enabled) + delete(rawMsg, key) + case "enforcement": + err = unpopulate(val, "Enforcement", &v.Enforcement) + 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 VirtualNetworkGateway. +func (v VirtualNetworkGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "extendedLocation", v.ExtendedLocation) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGateway. +func (v *VirtualNetworkGateway) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &v.ExtendedLocation) + delete(rawMsg, 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 "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 VirtualNetworkGatewayAutoScaleBounds. +func (v VirtualNetworkGatewayAutoScaleBounds) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "max", v.Max) + populate(objectMap, "min", v.Min) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayAutoScaleBounds. +func (v *VirtualNetworkGatewayAutoScaleBounds) UnmarshalJSON(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 "max": + err = unpopulate(val, "Max", &v.Max) + delete(rawMsg, key) + case "min": + err = unpopulate(val, "Min", &v.Min) + 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 VirtualNetworkGatewayAutoScaleConfiguration. +func (v VirtualNetworkGatewayAutoScaleConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bounds", v.Bounds) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayAutoScaleConfiguration. +func (v *VirtualNetworkGatewayAutoScaleConfiguration) UnmarshalJSON(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 "bounds": + err = unpopulate(val, "Bounds", &v.Bounds) + 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 VirtualNetworkGatewayConnection. +func (v VirtualNetworkGatewayConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayConnection. +func (v *VirtualNetworkGatewayConnection) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VirtualNetworkGatewayConnectionListEntity. +func (v VirtualNetworkGatewayConnectionListEntity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayConnectionListEntity. +func (v *VirtualNetworkGatewayConnectionListEntity) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VirtualNetworkGatewayConnectionListEntityPropertiesFormat. +func (v VirtualNetworkGatewayConnectionListEntityPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authorizationKey", v.AuthorizationKey) + populate(objectMap, "connectionMode", v.ConnectionMode) + populate(objectMap, "connectionProtocol", v.ConnectionProtocol) + populate(objectMap, "connectionStatus", v.ConnectionStatus) + populate(objectMap, "connectionType", v.ConnectionType) + populate(objectMap, "egressBytesTransferred", v.EgressBytesTransferred) + populate(objectMap, "enableBgp", v.EnableBgp) + populate(objectMap, "enablePrivateLinkFastPath", v.EnablePrivateLinkFastPath) + populate(objectMap, "expressRouteGatewayBypass", v.ExpressRouteGatewayBypass) + populate(objectMap, "gatewayCustomBgpIpAddresses", v.GatewayCustomBgpIPAddresses) + populate(objectMap, "ipsecPolicies", v.IPSecPolicies) + populate(objectMap, "ingressBytesTransferred", v.IngressBytesTransferred) + populate(objectMap, "localNetworkGateway2", v.LocalNetworkGateway2) + populate(objectMap, "peer", v.Peer) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "resourceGuid", v.ResourceGUID) + populate(objectMap, "routingWeight", v.RoutingWeight) + populate(objectMap, "sharedKey", v.SharedKey) + populate(objectMap, "trafficSelectorPolicies", v.TrafficSelectorPolicies) + populate(objectMap, "tunnelConnectionStatus", v.TunnelConnectionStatus) + populate(objectMap, "usePolicyBasedTrafficSelectors", v.UsePolicyBasedTrafficSelectors) + populate(objectMap, "virtualNetworkGateway1", v.VirtualNetworkGateway1) + populate(objectMap, "virtualNetworkGateway2", v.VirtualNetworkGateway2) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayConnectionListEntityPropertiesFormat. +func (v *VirtualNetworkGatewayConnectionListEntityPropertiesFormat) UnmarshalJSON(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 "authorizationKey": + err = unpopulate(val, "AuthorizationKey", &v.AuthorizationKey) + delete(rawMsg, key) + case "connectionMode": + err = unpopulate(val, "ConnectionMode", &v.ConnectionMode) + delete(rawMsg, key) + case "connectionProtocol": + err = unpopulate(val, "ConnectionProtocol", &v.ConnectionProtocol) + delete(rawMsg, key) + case "connectionStatus": + err = unpopulate(val, "ConnectionStatus", &v.ConnectionStatus) + delete(rawMsg, key) + case "connectionType": + err = unpopulate(val, "ConnectionType", &v.ConnectionType) + delete(rawMsg, key) + case "egressBytesTransferred": + err = unpopulate(val, "EgressBytesTransferred", &v.EgressBytesTransferred) + delete(rawMsg, key) + case "enableBgp": + err = unpopulate(val, "EnableBgp", &v.EnableBgp) + delete(rawMsg, key) + case "enablePrivateLinkFastPath": + err = unpopulate(val, "EnablePrivateLinkFastPath", &v.EnablePrivateLinkFastPath) + delete(rawMsg, key) + case "expressRouteGatewayBypass": + err = unpopulate(val, "ExpressRouteGatewayBypass", &v.ExpressRouteGatewayBypass) + delete(rawMsg, key) + case "gatewayCustomBgpIpAddresses": + err = unpopulate(val, "GatewayCustomBgpIPAddresses", &v.GatewayCustomBgpIPAddresses) + delete(rawMsg, key) + case "ipsecPolicies": + err = unpopulate(val, "IPSecPolicies", &v.IPSecPolicies) + delete(rawMsg, key) + case "ingressBytesTransferred": + err = unpopulate(val, "IngressBytesTransferred", &v.IngressBytesTransferred) + delete(rawMsg, key) + case "localNetworkGateway2": + err = unpopulate(val, "LocalNetworkGateway2", &v.LocalNetworkGateway2) + delete(rawMsg, key) + case "peer": + err = unpopulate(val, "Peer", &v.Peer) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &v.ResourceGUID) + delete(rawMsg, key) + case "routingWeight": + err = unpopulate(val, "RoutingWeight", &v.RoutingWeight) + delete(rawMsg, key) + case "sharedKey": + err = unpopulate(val, "SharedKey", &v.SharedKey) + delete(rawMsg, key) + case "trafficSelectorPolicies": + err = unpopulate(val, "TrafficSelectorPolicies", &v.TrafficSelectorPolicies) + delete(rawMsg, key) + case "tunnelConnectionStatus": + err = unpopulate(val, "TunnelConnectionStatus", &v.TunnelConnectionStatus) + delete(rawMsg, key) + case "usePolicyBasedTrafficSelectors": + err = unpopulate(val, "UsePolicyBasedTrafficSelectors", &v.UsePolicyBasedTrafficSelectors) + delete(rawMsg, key) + case "virtualNetworkGateway1": + err = unpopulate(val, "VirtualNetworkGateway1", &v.VirtualNetworkGateway1) + delete(rawMsg, key) + case "virtualNetworkGateway2": + err = unpopulate(val, "VirtualNetworkGateway2", &v.VirtualNetworkGateway2) + 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 VirtualNetworkGatewayConnectionListResult. +func (v VirtualNetworkGatewayConnectionListResult) 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 VirtualNetworkGatewayConnectionListResult. +func (v *VirtualNetworkGatewayConnectionListResult) UnmarshalJSON(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 VirtualNetworkGatewayConnectionPropertiesFormat. +func (v VirtualNetworkGatewayConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authorizationKey", v.AuthorizationKey) + populate(objectMap, "connectionMode", v.ConnectionMode) + populate(objectMap, "connectionProtocol", v.ConnectionProtocol) + populate(objectMap, "connectionStatus", v.ConnectionStatus) + populate(objectMap, "connectionType", v.ConnectionType) + populate(objectMap, "dpdTimeoutSeconds", v.DpdTimeoutSeconds) + populate(objectMap, "egressBytesTransferred", v.EgressBytesTransferred) + populate(objectMap, "egressNatRules", v.EgressNatRules) + populate(objectMap, "enableBgp", v.EnableBgp) + populate(objectMap, "enablePrivateLinkFastPath", v.EnablePrivateLinkFastPath) + populate(objectMap, "expressRouteGatewayBypass", v.ExpressRouteGatewayBypass) + populate(objectMap, "gatewayCustomBgpIpAddresses", v.GatewayCustomBgpIPAddresses) + populate(objectMap, "ipsecPolicies", v.IPSecPolicies) + populate(objectMap, "ingressBytesTransferred", v.IngressBytesTransferred) + populate(objectMap, "ingressNatRules", v.IngressNatRules) + populate(objectMap, "localNetworkGateway2", v.LocalNetworkGateway2) + populate(objectMap, "peer", v.Peer) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "resourceGuid", v.ResourceGUID) + populate(objectMap, "routingWeight", v.RoutingWeight) + populate(objectMap, "sharedKey", v.SharedKey) + populate(objectMap, "trafficSelectorPolicies", v.TrafficSelectorPolicies) + populate(objectMap, "tunnelConnectionStatus", v.TunnelConnectionStatus) + populate(objectMap, "useLocalAzureIpAddress", v.UseLocalAzureIPAddress) + populate(objectMap, "usePolicyBasedTrafficSelectors", v.UsePolicyBasedTrafficSelectors) + populate(objectMap, "virtualNetworkGateway1", v.VirtualNetworkGateway1) + populate(objectMap, "virtualNetworkGateway2", v.VirtualNetworkGateway2) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayConnectionPropertiesFormat. +func (v *VirtualNetworkGatewayConnectionPropertiesFormat) UnmarshalJSON(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 "authorizationKey": + err = unpopulate(val, "AuthorizationKey", &v.AuthorizationKey) + delete(rawMsg, key) + case "connectionMode": + err = unpopulate(val, "ConnectionMode", &v.ConnectionMode) + delete(rawMsg, key) + case "connectionProtocol": + err = unpopulate(val, "ConnectionProtocol", &v.ConnectionProtocol) + delete(rawMsg, key) + case "connectionStatus": + err = unpopulate(val, "ConnectionStatus", &v.ConnectionStatus) + delete(rawMsg, key) + case "connectionType": + err = unpopulate(val, "ConnectionType", &v.ConnectionType) + delete(rawMsg, key) + case "dpdTimeoutSeconds": + err = unpopulate(val, "DpdTimeoutSeconds", &v.DpdTimeoutSeconds) + delete(rawMsg, key) + case "egressBytesTransferred": + err = unpopulate(val, "EgressBytesTransferred", &v.EgressBytesTransferred) + delete(rawMsg, key) + case "egressNatRules": + err = unpopulate(val, "EgressNatRules", &v.EgressNatRules) + delete(rawMsg, key) + case "enableBgp": + err = unpopulate(val, "EnableBgp", &v.EnableBgp) + delete(rawMsg, key) + case "enablePrivateLinkFastPath": + err = unpopulate(val, "EnablePrivateLinkFastPath", &v.EnablePrivateLinkFastPath) + delete(rawMsg, key) + case "expressRouteGatewayBypass": + err = unpopulate(val, "ExpressRouteGatewayBypass", &v.ExpressRouteGatewayBypass) + delete(rawMsg, key) + case "gatewayCustomBgpIpAddresses": + err = unpopulate(val, "GatewayCustomBgpIPAddresses", &v.GatewayCustomBgpIPAddresses) + delete(rawMsg, key) + case "ipsecPolicies": + err = unpopulate(val, "IPSecPolicies", &v.IPSecPolicies) + delete(rawMsg, key) + case "ingressBytesTransferred": + err = unpopulate(val, "IngressBytesTransferred", &v.IngressBytesTransferred) + delete(rawMsg, key) + case "ingressNatRules": + err = unpopulate(val, "IngressNatRules", &v.IngressNatRules) + delete(rawMsg, key) + case "localNetworkGateway2": + err = unpopulate(val, "LocalNetworkGateway2", &v.LocalNetworkGateway2) + delete(rawMsg, key) + case "peer": + err = unpopulate(val, "Peer", &v.Peer) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &v.ResourceGUID) + delete(rawMsg, key) + case "routingWeight": + err = unpopulate(val, "RoutingWeight", &v.RoutingWeight) + delete(rawMsg, key) + case "sharedKey": + err = unpopulate(val, "SharedKey", &v.SharedKey) + delete(rawMsg, key) + case "trafficSelectorPolicies": + err = unpopulate(val, "TrafficSelectorPolicies", &v.TrafficSelectorPolicies) + delete(rawMsg, key) + case "tunnelConnectionStatus": + err = unpopulate(val, "TunnelConnectionStatus", &v.TunnelConnectionStatus) + delete(rawMsg, key) + case "useLocalAzureIpAddress": + err = unpopulate(val, "UseLocalAzureIPAddress", &v.UseLocalAzureIPAddress) + delete(rawMsg, key) + case "usePolicyBasedTrafficSelectors": + err = unpopulate(val, "UsePolicyBasedTrafficSelectors", &v.UsePolicyBasedTrafficSelectors) + delete(rawMsg, key) + case "virtualNetworkGateway1": + err = unpopulate(val, "VirtualNetworkGateway1", &v.VirtualNetworkGateway1) + delete(rawMsg, key) + case "virtualNetworkGateway2": + err = unpopulate(val, "VirtualNetworkGateway2", &v.VirtualNetworkGateway2) + 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 VirtualNetworkGatewayIPConfiguration. +func (v VirtualNetworkGatewayIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayIPConfiguration. +func (v *VirtualNetworkGatewayIPConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkGatewayIPConfigurationPropertiesFormat. +func (v VirtualNetworkGatewayIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIPAddress", v.PrivateIPAddress) + populate(objectMap, "privateIPAllocationMethod", v.PrivateIPAllocationMethod) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "publicIPAddress", v.PublicIPAddress) + populate(objectMap, "subnet", v.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayIPConfigurationPropertiesFormat. +func (v *VirtualNetworkGatewayIPConfigurationPropertiesFormat) UnmarshalJSON(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 "privateIPAddress": + err = unpopulate(val, "PrivateIPAddress", &v.PrivateIPAddress) + delete(rawMsg, key) + case "privateIPAllocationMethod": + err = unpopulate(val, "PrivateIPAllocationMethod", &v.PrivateIPAllocationMethod) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "publicIPAddress": + err = unpopulate(val, "PublicIPAddress", &v.PublicIPAddress) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &v.Subnet) + 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 VirtualNetworkGatewayListConnectionsResult. +func (v VirtualNetworkGatewayListConnectionsResult) 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 VirtualNetworkGatewayListConnectionsResult. +func (v *VirtualNetworkGatewayListConnectionsResult) UnmarshalJSON(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 VirtualNetworkGatewayListResult. +func (v VirtualNetworkGatewayListResult) 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 VirtualNetworkGatewayListResult. +func (v *VirtualNetworkGatewayListResult) UnmarshalJSON(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 VirtualNetworkGatewayNatRule. +func (v VirtualNetworkGatewayNatRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VirtualNetworkGatewayNatRule. +func (v *VirtualNetworkGatewayNatRule) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VirtualNetworkGatewayNatRuleProperties. +func (v VirtualNetworkGatewayNatRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "externalMappings", v.ExternalMappings) + populate(objectMap, "ipConfigurationId", v.IPConfigurationID) + populate(objectMap, "internalMappings", v.InternalMappings) + populate(objectMap, "mode", v.Mode) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayNatRuleProperties. +func (v *VirtualNetworkGatewayNatRuleProperties) UnmarshalJSON(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 "externalMappings": + err = unpopulate(val, "ExternalMappings", &v.ExternalMappings) + delete(rawMsg, key) + case "ipConfigurationId": + err = unpopulate(val, "IPConfigurationID", &v.IPConfigurationID) + delete(rawMsg, key) + case "internalMappings": + err = unpopulate(val, "InternalMappings", &v.InternalMappings) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &v.Mode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + 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 VirtualNetworkGatewayPolicyGroup. +func (v VirtualNetworkGatewayPolicyGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayPolicyGroup. +func (v *VirtualNetworkGatewayPolicyGroup) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkGatewayPolicyGroupMember. +func (v VirtualNetworkGatewayPolicyGroupMember) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributeType", v.AttributeType) + populate(objectMap, "attributeValue", v.AttributeValue) + populate(objectMap, "name", v.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayPolicyGroupMember. +func (v *VirtualNetworkGatewayPolicyGroupMember) UnmarshalJSON(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 "attributeType": + err = unpopulate(val, "AttributeType", &v.AttributeType) + delete(rawMsg, key) + case "attributeValue": + err = unpopulate(val, "AttributeValue", &v.AttributeValue) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + 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 VirtualNetworkGatewayPolicyGroupProperties. +func (v VirtualNetworkGatewayPolicyGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isDefault", v.IsDefault) + populate(objectMap, "policyMembers", v.PolicyMembers) + populate(objectMap, "priority", v.Priority) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "vngClientConnectionConfigurations", v.VngClientConnectionConfigurations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayPolicyGroupProperties. +func (v *VirtualNetworkGatewayPolicyGroupProperties) UnmarshalJSON(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 "isDefault": + err = unpopulate(val, "IsDefault", &v.IsDefault) + delete(rawMsg, key) + case "policyMembers": + err = unpopulate(val, "PolicyMembers", &v.PolicyMembers) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &v.Priority) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "vngClientConnectionConfigurations": + err = unpopulate(val, "VngClientConnectionConfigurations", &v.VngClientConnectionConfigurations) + 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 VirtualNetworkGatewayPropertiesFormat. +func (v VirtualNetworkGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activeActive", v.Active) + populate(objectMap, "adminState", v.AdminState) + populate(objectMap, "allowRemoteVnetTraffic", v.AllowRemoteVnetTraffic) + populate(objectMap, "allowVirtualWanTraffic", v.AllowVirtualWanTraffic) + populate(objectMap, "autoScaleConfiguration", v.AutoScaleConfiguration) + populate(objectMap, "bgpSettings", v.BgpSettings) + populate(objectMap, "customRoutes", v.CustomRoutes) + populate(objectMap, "disableIPSecReplayProtection", v.DisableIPSecReplayProtection) + populate(objectMap, "enableBgp", v.EnableBgp) + populate(objectMap, "enableBgpRouteTranslationForNat", v.EnableBgpRouteTranslationForNat) + populate(objectMap, "enableDnsForwarding", v.EnableDNSForwarding) + populate(objectMap, "enablePrivateIpAddress", v.EnablePrivateIPAddress) + populate(objectMap, "gatewayDefaultSite", v.GatewayDefaultSite) + populate(objectMap, "gatewayType", v.GatewayType) + populate(objectMap, "ipConfigurations", v.IPConfigurations) + populate(objectMap, "inboundDnsForwardingEndpoint", v.InboundDNSForwardingEndpoint) + populate(objectMap, "natRules", v.NatRules) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "resourceGuid", v.ResourceGUID) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "vNetExtendedLocationResourceId", v.VNetExtendedLocationResourceID) + populate(objectMap, "vpnClientConfiguration", v.VPNClientConfiguration) + populate(objectMap, "vpnGatewayGeneration", v.VPNGatewayGeneration) + populate(objectMap, "vpnType", v.VPNType) + populate(objectMap, "virtualNetworkGatewayPolicyGroups", v.VirtualNetworkGatewayPolicyGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayPropertiesFormat. +func (v *VirtualNetworkGatewayPropertiesFormat) UnmarshalJSON(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 "activeActive": + err = unpopulate(val, "Active", &v.Active) + delete(rawMsg, key) + case "adminState": + err = unpopulate(val, "AdminState", &v.AdminState) + delete(rawMsg, key) + case "allowRemoteVnetTraffic": + err = unpopulate(val, "AllowRemoteVnetTraffic", &v.AllowRemoteVnetTraffic) + delete(rawMsg, key) + case "allowVirtualWanTraffic": + err = unpopulate(val, "AllowVirtualWanTraffic", &v.AllowVirtualWanTraffic) + delete(rawMsg, key) + case "autoScaleConfiguration": + err = unpopulate(val, "AutoScaleConfiguration", &v.AutoScaleConfiguration) + delete(rawMsg, key) + case "bgpSettings": + err = unpopulate(val, "BgpSettings", &v.BgpSettings) + delete(rawMsg, key) + case "customRoutes": + err = unpopulate(val, "CustomRoutes", &v.CustomRoutes) + delete(rawMsg, key) + case "disableIPSecReplayProtection": + err = unpopulate(val, "DisableIPSecReplayProtection", &v.DisableIPSecReplayProtection) + delete(rawMsg, key) + case "enableBgp": + err = unpopulate(val, "EnableBgp", &v.EnableBgp) + delete(rawMsg, key) + case "enableBgpRouteTranslationForNat": + err = unpopulate(val, "EnableBgpRouteTranslationForNat", &v.EnableBgpRouteTranslationForNat) + delete(rawMsg, key) + case "enableDnsForwarding": + err = unpopulate(val, "EnableDNSForwarding", &v.EnableDNSForwarding) + delete(rawMsg, key) + case "enablePrivateIpAddress": + err = unpopulate(val, "EnablePrivateIPAddress", &v.EnablePrivateIPAddress) + delete(rawMsg, key) + case "gatewayDefaultSite": + err = unpopulate(val, "GatewayDefaultSite", &v.GatewayDefaultSite) + delete(rawMsg, key) + case "gatewayType": + err = unpopulate(val, "GatewayType", &v.GatewayType) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &v.IPConfigurations) + delete(rawMsg, key) + case "inboundDnsForwardingEndpoint": + err = unpopulate(val, "InboundDNSForwardingEndpoint", &v.InboundDNSForwardingEndpoint) + delete(rawMsg, key) + case "natRules": + err = unpopulate(val, "NatRules", &v.NatRules) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &v.ResourceGUID) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + delete(rawMsg, key) + case "vNetExtendedLocationResourceId": + err = unpopulate(val, "VNetExtendedLocationResourceID", &v.VNetExtendedLocationResourceID) + delete(rawMsg, key) + case "vpnClientConfiguration": + err = unpopulate(val, "VPNClientConfiguration", &v.VPNClientConfiguration) + delete(rawMsg, key) + case "vpnGatewayGeneration": + err = unpopulate(val, "VPNGatewayGeneration", &v.VPNGatewayGeneration) + delete(rawMsg, key) + case "vpnType": + err = unpopulate(val, "VPNType", &v.VPNType) + delete(rawMsg, key) + case "virtualNetworkGatewayPolicyGroups": + err = unpopulate(val, "VirtualNetworkGatewayPolicyGroups", &v.VirtualNetworkGatewayPolicyGroups) + 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 VirtualNetworkGatewaySKU. +func (v VirtualNetworkGatewaySKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", v.Capacity) + populate(objectMap, "name", v.Name) + populate(objectMap, "tier", v.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewaySKU. +func (v *VirtualNetworkGatewaySKU) UnmarshalJSON(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 "capacity": + err = unpopulate(val, "Capacity", &v.Capacity) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &v.Tier) + 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 VirtualNetworkListResult. +func (v VirtualNetworkListResult) 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 VirtualNetworkListResult. +func (v *VirtualNetworkListResult) UnmarshalJSON(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 VirtualNetworkListUsageResult. +func (v VirtualNetworkListUsageResult) 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 VirtualNetworkListUsageResult. +func (v *VirtualNetworkListUsageResult) UnmarshalJSON(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 VirtualNetworkPeering. +func (v VirtualNetworkPeering) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VirtualNetworkPeering. +func (v *VirtualNetworkPeering) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VirtualNetworkPeeringListResult. +func (v VirtualNetworkPeeringListResult) 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 VirtualNetworkPeeringListResult. +func (v *VirtualNetworkPeeringListResult) UnmarshalJSON(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 VirtualNetworkPeeringPropertiesFormat. +func (v VirtualNetworkPeeringPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowForwardedTraffic", v.AllowForwardedTraffic) + populate(objectMap, "allowGatewayTransit", v.AllowGatewayTransit) + populate(objectMap, "allowVirtualNetworkAccess", v.AllowVirtualNetworkAccess) + populate(objectMap, "doNotVerifyRemoteGateways", v.DoNotVerifyRemoteGateways) + populate(objectMap, "peeringState", v.PeeringState) + populate(objectMap, "peeringSyncLevel", v.PeeringSyncLevel) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "remoteAddressSpace", v.RemoteAddressSpace) + populate(objectMap, "remoteBgpCommunities", v.RemoteBgpCommunities) + populate(objectMap, "remoteVirtualNetwork", v.RemoteVirtualNetwork) + populate(objectMap, "remoteVirtualNetworkAddressSpace", v.RemoteVirtualNetworkAddressSpace) + populate(objectMap, "remoteVirtualNetworkEncryption", v.RemoteVirtualNetworkEncryption) + populate(objectMap, "resourceGuid", v.ResourceGUID) + populate(objectMap, "useRemoteGateways", v.UseRemoteGateways) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkPeeringPropertiesFormat. +func (v *VirtualNetworkPeeringPropertiesFormat) UnmarshalJSON(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 "allowForwardedTraffic": + err = unpopulate(val, "AllowForwardedTraffic", &v.AllowForwardedTraffic) + delete(rawMsg, key) + case "allowGatewayTransit": + err = unpopulate(val, "AllowGatewayTransit", &v.AllowGatewayTransit) + delete(rawMsg, key) + case "allowVirtualNetworkAccess": + err = unpopulate(val, "AllowVirtualNetworkAccess", &v.AllowVirtualNetworkAccess) + delete(rawMsg, key) + case "doNotVerifyRemoteGateways": + err = unpopulate(val, "DoNotVerifyRemoteGateways", &v.DoNotVerifyRemoteGateways) + delete(rawMsg, key) + case "peeringState": + err = unpopulate(val, "PeeringState", &v.PeeringState) + delete(rawMsg, key) + case "peeringSyncLevel": + err = unpopulate(val, "PeeringSyncLevel", &v.PeeringSyncLevel) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "remoteAddressSpace": + err = unpopulate(val, "RemoteAddressSpace", &v.RemoteAddressSpace) + delete(rawMsg, key) + case "remoteBgpCommunities": + err = unpopulate(val, "RemoteBgpCommunities", &v.RemoteBgpCommunities) + delete(rawMsg, key) + case "remoteVirtualNetwork": + err = unpopulate(val, "RemoteVirtualNetwork", &v.RemoteVirtualNetwork) + delete(rawMsg, key) + case "remoteVirtualNetworkAddressSpace": + err = unpopulate(val, "RemoteVirtualNetworkAddressSpace", &v.RemoteVirtualNetworkAddressSpace) + delete(rawMsg, key) + case "remoteVirtualNetworkEncryption": + err = unpopulate(val, "RemoteVirtualNetworkEncryption", &v.RemoteVirtualNetworkEncryption) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &v.ResourceGUID) + delete(rawMsg, key) + case "useRemoteGateways": + err = unpopulate(val, "UseRemoteGateways", &v.UseRemoteGateways) + 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 VirtualNetworkPropertiesFormat. +func (v VirtualNetworkPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressSpace", v.AddressSpace) + populate(objectMap, "bgpCommunities", v.BgpCommunities) + populate(objectMap, "ddosProtectionPlan", v.DdosProtectionPlan) + populate(objectMap, "dhcpOptions", v.DhcpOptions) + populate(objectMap, "enableDdosProtection", v.EnableDdosProtection) + populate(objectMap, "enableVmProtection", v.EnableVMProtection) + populate(objectMap, "encryption", v.Encryption) + populate(objectMap, "flowLogs", v.FlowLogs) + populate(objectMap, "flowTimeoutInMinutes", v.FlowTimeoutInMinutes) + populate(objectMap, "ipAllocations", v.IPAllocations) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "resourceGuid", v.ResourceGUID) + populate(objectMap, "subnets", v.Subnets) + populate(objectMap, "virtualNetworkPeerings", v.VirtualNetworkPeerings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkPropertiesFormat. +func (v *VirtualNetworkPropertiesFormat) UnmarshalJSON(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 "addressSpace": + err = unpopulate(val, "AddressSpace", &v.AddressSpace) + delete(rawMsg, key) + case "bgpCommunities": + err = unpopulate(val, "BgpCommunities", &v.BgpCommunities) + delete(rawMsg, key) + case "ddosProtectionPlan": + err = unpopulate(val, "DdosProtectionPlan", &v.DdosProtectionPlan) + delete(rawMsg, key) + case "dhcpOptions": + err = unpopulate(val, "DhcpOptions", &v.DhcpOptions) + delete(rawMsg, key) + case "enableDdosProtection": + err = unpopulate(val, "EnableDdosProtection", &v.EnableDdosProtection) + delete(rawMsg, key) + case "enableVmProtection": + err = unpopulate(val, "EnableVMProtection", &v.EnableVMProtection) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &v.Encryption) + delete(rawMsg, key) + case "flowLogs": + err = unpopulate(val, "FlowLogs", &v.FlowLogs) + delete(rawMsg, key) + case "flowTimeoutInMinutes": + err = unpopulate(val, "FlowTimeoutInMinutes", &v.FlowTimeoutInMinutes) + delete(rawMsg, key) + case "ipAllocations": + err = unpopulate(val, "IPAllocations", &v.IPAllocations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &v.ResourceGUID) + delete(rawMsg, key) + case "subnets": + err = unpopulate(val, "Subnets", &v.Subnets) + delete(rawMsg, key) + case "virtualNetworkPeerings": + err = unpopulate(val, "VirtualNetworkPeerings", &v.VirtualNetworkPeerings) + 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 VirtualNetworkTap. +func (v VirtualNetworkTap) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkTap. +func (v *VirtualNetworkTap) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VirtualNetworkTapListResult. +func (v VirtualNetworkTapListResult) 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 VirtualNetworkTapListResult. +func (v *VirtualNetworkTapListResult) UnmarshalJSON(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 VirtualNetworkTapPropertiesFormat. +func (v VirtualNetworkTapPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationLoadBalancerFrontEndIPConfiguration", v.DestinationLoadBalancerFrontEndIPConfiguration) + populate(objectMap, "destinationNetworkInterfaceIPConfiguration", v.DestinationNetworkInterfaceIPConfiguration) + populate(objectMap, "destinationPort", v.DestinationPort) + populate(objectMap, "networkInterfaceTapConfigurations", v.NetworkInterfaceTapConfigurations) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "resourceGuid", v.ResourceGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkTapPropertiesFormat. +func (v *VirtualNetworkTapPropertiesFormat) UnmarshalJSON(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 "destinationLoadBalancerFrontEndIPConfiguration": + err = unpopulate(val, "DestinationLoadBalancerFrontEndIPConfiguration", &v.DestinationLoadBalancerFrontEndIPConfiguration) + delete(rawMsg, key) + case "destinationNetworkInterfaceIPConfiguration": + err = unpopulate(val, "DestinationNetworkInterfaceIPConfiguration", &v.DestinationNetworkInterfaceIPConfiguration) + delete(rawMsg, key) + case "destinationPort": + err = unpopulate(val, "DestinationPort", &v.DestinationPort) + delete(rawMsg, key) + case "networkInterfaceTapConfigurations": + err = unpopulate(val, "NetworkInterfaceTapConfigurations", &v.NetworkInterfaceTapConfigurations) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "resourceGuid": + err = unpopulate(val, "ResourceGUID", &v.ResourceGUID) + 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 VirtualNetworkUsage. +func (v VirtualNetworkUsage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentValue", v.CurrentValue) + populate(objectMap, "id", v.ID) + populate(objectMap, "limit", v.Limit) + populate(objectMap, "name", v.Name) + populate(objectMap, "unit", v.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkUsage. +func (v *VirtualNetworkUsage) UnmarshalJSON(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 "currentValue": + err = unpopulate(val, "CurrentValue", &v.CurrentValue) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "limit": + err = unpopulate(val, "Limit", &v.Limit) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &v.Unit) + 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 VirtualNetworkUsageName. +func (v VirtualNetworkUsageName) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "localizedValue", v.LocalizedValue) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkUsageName. +func (v *VirtualNetworkUsageName) UnmarshalJSON(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 "localizedValue": + err = unpopulate(val, "LocalizedValue", &v.LocalizedValue) + 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 VirtualRouter. +func (v VirtualRouter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualRouter. +func (v *VirtualRouter) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VirtualRouterAutoScaleConfiguration. +func (v VirtualRouterAutoScaleConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "minCapacity", v.MinCapacity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualRouterAutoScaleConfiguration. +func (v *VirtualRouterAutoScaleConfiguration) UnmarshalJSON(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 "minCapacity": + err = unpopulate(val, "MinCapacity", &v.MinCapacity) + 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 VirtualRouterListResult. +func (v VirtualRouterListResult) 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 VirtualRouterListResult. +func (v *VirtualRouterListResult) UnmarshalJSON(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 VirtualRouterPeering. +func (v VirtualRouterPeering) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + 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 VirtualRouterPeering. +func (v *VirtualRouterPeering) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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 VirtualRouterPeeringListResult. +func (v VirtualRouterPeeringListResult) 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 VirtualRouterPeeringListResult. +func (v *VirtualRouterPeeringListResult) UnmarshalJSON(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 VirtualRouterPeeringProperties. +func (v VirtualRouterPeeringProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "peerAsn", v.PeerAsn) + populate(objectMap, "peerIp", v.PeerIP) + populate(objectMap, "provisioningState", v.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualRouterPeeringProperties. +func (v *VirtualRouterPeeringProperties) UnmarshalJSON(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 "peerAsn": + err = unpopulate(val, "PeerAsn", &v.PeerAsn) + delete(rawMsg, key) + case "peerIp": + err = unpopulate(val, "PeerIP", &v.PeerIP) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + 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 VirtualRouterPropertiesFormat. +func (v VirtualRouterPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hostedGateway", v.HostedGateway) + populate(objectMap, "hostedSubnet", v.HostedSubnet) + populate(objectMap, "peerings", v.Peerings) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "virtualRouterAsn", v.VirtualRouterAsn) + populate(objectMap, "virtualRouterIps", v.VirtualRouterIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualRouterPropertiesFormat. +func (v *VirtualRouterPropertiesFormat) UnmarshalJSON(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 "hostedGateway": + err = unpopulate(val, "HostedGateway", &v.HostedGateway) + delete(rawMsg, key) + case "hostedSubnet": + err = unpopulate(val, "HostedSubnet", &v.HostedSubnet) + delete(rawMsg, key) + case "peerings": + err = unpopulate(val, "Peerings", &v.Peerings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "virtualRouterAsn": + err = unpopulate(val, "VirtualRouterAsn", &v.VirtualRouterAsn) + delete(rawMsg, key) + case "virtualRouterIps": + err = unpopulate(val, "VirtualRouterIPs", &v.VirtualRouterIPs) + 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 VirtualWAN. +func (v VirtualWAN) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualWAN. +func (v *VirtualWAN) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, 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 "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 VirtualWanProperties. +func (v VirtualWanProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowBranchToBranchTraffic", v.AllowBranchToBranchTraffic) + populate(objectMap, "allowVnetToVnetTraffic", v.AllowVnetToVnetTraffic) + populate(objectMap, "disableVpnEncryption", v.DisableVPNEncryption) + populate(objectMap, "office365LocalBreakoutCategory", v.Office365LocalBreakoutCategory) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "type", v.Type) + populate(objectMap, "vpnSites", v.VPNSites) + populate(objectMap, "virtualHubs", v.VirtualHubs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualWanProperties. +func (v *VirtualWanProperties) UnmarshalJSON(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 "allowBranchToBranchTraffic": + err = unpopulate(val, "AllowBranchToBranchTraffic", &v.AllowBranchToBranchTraffic) + delete(rawMsg, key) + case "allowVnetToVnetTraffic": + err = unpopulate(val, "AllowVnetToVnetTraffic", &v.AllowVnetToVnetTraffic) + delete(rawMsg, key) + case "disableVpnEncryption": + err = unpopulate(val, "DisableVPNEncryption", &v.DisableVPNEncryption) + delete(rawMsg, key) + case "office365LocalBreakoutCategory": + err = unpopulate(val, "Office365LocalBreakoutCategory", &v.Office365LocalBreakoutCategory) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "vpnSites": + err = unpopulate(val, "VPNSites", &v.VPNSites) + delete(rawMsg, key) + case "virtualHubs": + err = unpopulate(val, "VirtualHubs", &v.VirtualHubs) + 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 VirtualWanSecurityProvider. +func (v VirtualWanSecurityProvider) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "type", v.Type) + populate(objectMap, "url", v.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualWanSecurityProvider. +func (v *VirtualWanSecurityProvider) UnmarshalJSON(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) + case "url": + err = unpopulate(val, "URL", &v.URL) + 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 VirtualWanSecurityProviders. +func (v VirtualWanSecurityProviders) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "supportedProviders", v.SupportedProviders) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualWanSecurityProviders. +func (v *VirtualWanSecurityProviders) UnmarshalJSON(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 "supportedProviders": + err = unpopulate(val, "SupportedProviders", &v.SupportedProviders) + 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 VirtualWanVPNProfileParameters. +func (v VirtualWanVPNProfileParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationMethod", v.AuthenticationMethod) + populate(objectMap, "vpnServerConfigurationResourceId", v.VPNServerConfigurationResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualWanVPNProfileParameters. +func (v *VirtualWanVPNProfileParameters) UnmarshalJSON(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 "authenticationMethod": + err = unpopulate(val, "AuthenticationMethod", &v.AuthenticationMethod) + delete(rawMsg, key) + case "vpnServerConfigurationResourceId": + err = unpopulate(val, "VPNServerConfigurationResourceID", &v.VPNServerConfigurationResourceID) + 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 VnetRoute. +func (v VnetRoute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bgpConnections", v.BgpConnections) + populate(objectMap, "staticRoutes", v.StaticRoutes) + populate(objectMap, "staticRoutesConfig", v.StaticRoutesConfig) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VnetRoute. +func (v *VnetRoute) UnmarshalJSON(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 "bgpConnections": + err = unpopulate(val, "BgpConnections", &v.BgpConnections) + delete(rawMsg, key) + case "staticRoutes": + err = unpopulate(val, "StaticRoutes", &v.StaticRoutes) + delete(rawMsg, key) + case "staticRoutesConfig": + err = unpopulate(val, "StaticRoutesConfig", &v.StaticRoutesConfig) + 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 VngClientConnectionConfiguration. +func (v VngClientConnectionConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", v.Etag) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VngClientConnectionConfiguration. +func (v *VngClientConnectionConfiguration) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &v.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &v.ID) + 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VngClientConnectionConfigurationProperties. +func (v VngClientConnectionConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "vpnClientAddressPool", v.VPNClientAddressPool) + populate(objectMap, "virtualNetworkGatewayPolicyGroups", v.VirtualNetworkGatewayPolicyGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VngClientConnectionConfigurationProperties. +func (v *VngClientConnectionConfigurationProperties) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "vpnClientAddressPool": + err = unpopulate(val, "VPNClientAddressPool", &v.VPNClientAddressPool) + delete(rawMsg, key) + case "virtualNetworkGatewayPolicyGroups": + err = unpopulate(val, "VirtualNetworkGatewayPolicyGroups", &v.VirtualNetworkGatewayPolicyGroups) + 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 Watcher. +func (w Watcher) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", w.Etag) + populate(objectMap, "id", w.ID) + populate(objectMap, "location", w.Location) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "tags", w.Tags) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Watcher. +func (w *Watcher) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &w.Etag) + delete(rawMsg, 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 "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 WatcherListResult. +func (w WatcherListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WatcherListResult. +func (w *WatcherListResult) UnmarshalJSON(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 "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 WatcherPropertiesFormat. +func (w WatcherPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", w.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WatcherPropertiesFormat. +func (w *WatcherPropertiesFormat) UnmarshalJSON(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 "provisioningState": + err = unpopulate(val, "ProvisioningState", &w.ProvisioningState) + 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 WebApplicationFirewallCustomRule. +func (w WebApplicationFirewallCustomRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", w.Action) + populate(objectMap, "etag", w.Etag) + populate(objectMap, "groupByUserSession", w.GroupByUserSession) + populate(objectMap, "matchConditions", w.MatchConditions) + populate(objectMap, "name", w.Name) + populate(objectMap, "priority", w.Priority) + populate(objectMap, "rateLimitDuration", w.RateLimitDuration) + populate(objectMap, "rateLimitThreshold", w.RateLimitThreshold) + populate(objectMap, "ruleType", w.RuleType) + populate(objectMap, "state", w.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebApplicationFirewallCustomRule. +func (w *WebApplicationFirewallCustomRule) UnmarshalJSON(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 "action": + err = unpopulate(val, "Action", &w.Action) + delete(rawMsg, key) + case "etag": + err = unpopulate(val, "Etag", &w.Etag) + delete(rawMsg, key) + case "groupByUserSession": + err = unpopulate(val, "GroupByUserSession", &w.GroupByUserSession) + delete(rawMsg, key) + case "matchConditions": + err = unpopulate(val, "MatchConditions", &w.MatchConditions) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &w.Priority) + delete(rawMsg, key) + case "rateLimitDuration": + err = unpopulate(val, "RateLimitDuration", &w.RateLimitDuration) + delete(rawMsg, key) + case "rateLimitThreshold": + err = unpopulate(val, "RateLimitThreshold", &w.RateLimitThreshold) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &w.RuleType) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &w.State) + 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 WebApplicationFirewallPolicy. +func (w WebApplicationFirewallPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", w.Etag) + populate(objectMap, "id", w.ID) + populate(objectMap, "location", w.Location) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "tags", w.Tags) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebApplicationFirewallPolicy. +func (w *WebApplicationFirewallPolicy) UnmarshalJSON(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 "etag": + err = unpopulate(val, "Etag", &w.Etag) + delete(rawMsg, 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 "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 WebApplicationFirewallPolicyListResult. +func (w WebApplicationFirewallPolicyListResult) 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 WebApplicationFirewallPolicyListResult. +func (w *WebApplicationFirewallPolicyListResult) UnmarshalJSON(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 WebApplicationFirewallPolicyPropertiesFormat. +func (w WebApplicationFirewallPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationGateways", w.ApplicationGateways) + populate(objectMap, "customRules", w.CustomRules) + populate(objectMap, "httpListeners", w.HTTPListeners) + populate(objectMap, "managedRules", w.ManagedRules) + populate(objectMap, "pathBasedRules", w.PathBasedRules) + populate(objectMap, "policySettings", w.PolicySettings) + populate(objectMap, "provisioningState", w.ProvisioningState) + populate(objectMap, "resourceState", w.ResourceState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebApplicationFirewallPolicyPropertiesFormat. +func (w *WebApplicationFirewallPolicyPropertiesFormat) UnmarshalJSON(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 "applicationGateways": + err = unpopulate(val, "ApplicationGateways", &w.ApplicationGateways) + delete(rawMsg, key) + case "customRules": + err = unpopulate(val, "CustomRules", &w.CustomRules) + delete(rawMsg, key) + case "httpListeners": + err = unpopulate(val, "HTTPListeners", &w.HTTPListeners) + delete(rawMsg, key) + case "managedRules": + err = unpopulate(val, "ManagedRules", &w.ManagedRules) + delete(rawMsg, key) + case "pathBasedRules": + err = unpopulate(val, "PathBasedRules", &w.PathBasedRules) + delete(rawMsg, key) + case "policySettings": + err = unpopulate(val, "PolicySettings", &w.PolicySettings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &w.ProvisioningState) + delete(rawMsg, key) + case "resourceState": + err = unpopulate(val, "ResourceState", &w.ResourceState) + 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 WebApplicationFirewallScrubbingRules. +func (w WebApplicationFirewallScrubbingRules) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "matchVariable", w.MatchVariable) + populate(objectMap, "selector", w.Selector) + populate(objectMap, "selectorMatchOperator", w.SelectorMatchOperator) + populate(objectMap, "state", w.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebApplicationFirewallScrubbingRules. +func (w *WebApplicationFirewallScrubbingRules) UnmarshalJSON(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 "matchVariable": + err = unpopulate(val, "MatchVariable", &w.MatchVariable) + delete(rawMsg, key) + case "selector": + err = unpopulate(val, "Selector", &w.Selector) + delete(rawMsg, key) + case "selectorMatchOperator": + err = unpopulate(val, "SelectorMatchOperator", &w.SelectorMatchOperator) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &w.State) + 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 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/network/armnetwork/v4/natgateways_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/natgateways_client.go new file mode 100644 index 000000000..d7cf68098 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/natgateways_client.go @@ -0,0 +1,450 @@ +//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 armnetwork + +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" +) + +// NatGatewaysClient contains the methods for the NatGateways group. +// Don't use this type directly, use NewNatGatewaysClient() instead. +type NatGatewaysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewNatGatewaysClient creates a new instance of NatGatewaysClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewNatGatewaysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*NatGatewaysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &NatGatewaysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a nat gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - natGatewayName - The name of the nat gateway. +// - parameters - Parameters supplied to the create or update nat gateway operation. +// - options - NatGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the NatGatewaysClient.BeginCreateOrUpdate +// method. +func (client *NatGatewaysClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, natGatewayName string, parameters NatGateway, options *NatGatewaysClientBeginCreateOrUpdateOptions) (*runtime.Poller[NatGatewaysClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, natGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NatGatewaysClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NatGatewaysClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a nat gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *NatGatewaysClient) createOrUpdate(ctx context.Context, resourceGroupName string, natGatewayName string, parameters NatGateway, options *NatGatewaysClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "NatGatewaysClient.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, natGatewayName, 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, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *NatGatewaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, natGatewayName string, parameters NatGateway, options *NatGatewaysClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/natGateways/{natGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if natGatewayName == "" { + return nil, errors.New("parameter natGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natGatewayName}", url.PathEscape(natGatewayName)) + 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-05-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 nat gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - natGatewayName - The name of the nat gateway. +// - options - NatGatewaysClientBeginDeleteOptions contains the optional parameters for the NatGatewaysClient.BeginDelete method. +func (client *NatGatewaysClient) BeginDelete(ctx context.Context, resourceGroupName string, natGatewayName string, options *NatGatewaysClientBeginDeleteOptions) (*runtime.Poller[NatGatewaysClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, natGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NatGatewaysClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NatGatewaysClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified nat gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *NatGatewaysClient) deleteOperation(ctx context.Context, resourceGroupName string, natGatewayName string, options *NatGatewaysClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "NatGatewaysClient.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, natGatewayName, 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 *NatGatewaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, natGatewayName string, options *NatGatewaysClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/natGateways/{natGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if natGatewayName == "" { + return nil, errors.New("parameter natGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natGatewayName}", url.PathEscape(natGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified nat gateway in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - natGatewayName - The name of the nat gateway. +// - options - NatGatewaysClientGetOptions contains the optional parameters for the NatGatewaysClient.Get method. +func (client *NatGatewaysClient) Get(ctx context.Context, resourceGroupName string, natGatewayName string, options *NatGatewaysClientGetOptions) (NatGatewaysClientGetResponse, error) { + var err error + const operationName = "NatGatewaysClient.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, natGatewayName, options) + if err != nil { + return NatGatewaysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NatGatewaysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NatGatewaysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *NatGatewaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, natGatewayName string, options *NatGatewaysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/natGateways/{natGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if natGatewayName == "" { + return nil, errors.New("parameter natGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natGatewayName}", url.PathEscape(natGatewayName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *NatGatewaysClient) getHandleResponse(resp *http.Response) (NatGatewaysClientGetResponse, error) { + result := NatGatewaysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NatGateway); err != nil { + return NatGatewaysClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all nat gateways in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - NatGatewaysClientListOptions contains the optional parameters for the NatGatewaysClient.NewListPager method. +func (client *NatGatewaysClient) NewListPager(resourceGroupName string, options *NatGatewaysClientListOptions) *runtime.Pager[NatGatewaysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[NatGatewaysClientListResponse]{ + More: func(page NatGatewaysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NatGatewaysClientListResponse) (NatGatewaysClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NatGatewaysClient.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, options) + }, nil) + if err != nil { + return NatGatewaysClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *NatGatewaysClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *NatGatewaysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/natGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *NatGatewaysClient) listHandleResponse(resp *http.Response) (NatGatewaysClientListResponse, error) { + result := NatGatewaysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NatGatewayListResult); err != nil { + return NatGatewaysClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the Nat Gateways in a subscription. +// +// Generated from API version 2023-05-01 +// - options - NatGatewaysClientListAllOptions contains the optional parameters for the NatGatewaysClient.NewListAllPager method. +func (client *NatGatewaysClient) NewListAllPager(options *NatGatewaysClientListAllOptions) *runtime.Pager[NatGatewaysClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[NatGatewaysClientListAllResponse]{ + More: func(page NatGatewaysClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NatGatewaysClientListAllResponse) (NatGatewaysClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NatGatewaysClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return NatGatewaysClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *NatGatewaysClient) listAllCreateRequest(ctx context.Context, options *NatGatewaysClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/natGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *NatGatewaysClient) listAllHandleResponse(resp *http.Response) (NatGatewaysClientListAllResponse, error) { + result := NatGatewaysClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NatGatewayListResult); err != nil { + return NatGatewaysClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates nat gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - natGatewayName - The name of the nat gateway. +// - parameters - Parameters supplied to update nat gateway tags. +// - options - NatGatewaysClientUpdateTagsOptions contains the optional parameters for the NatGatewaysClient.UpdateTags method. +func (client *NatGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, natGatewayName string, parameters TagsObject, options *NatGatewaysClientUpdateTagsOptions) (NatGatewaysClientUpdateTagsResponse, error) { + var err error + const operationName = "NatGatewaysClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, natGatewayName, parameters, options) + if err != nil { + return NatGatewaysClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NatGatewaysClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NatGatewaysClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *NatGatewaysClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, natGatewayName string, parameters TagsObject, options *NatGatewaysClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/natGateways/{natGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if natGatewayName == "" { + return nil, errors.New("parameter natGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natGatewayName}", url.PathEscape(natGatewayName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *NatGatewaysClient) updateTagsHandleResponse(resp *http.Response) (NatGatewaysClientUpdateTagsResponse, error) { + result := NatGatewaysClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NatGateway); err != nil { + return NatGatewaysClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/natrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/natrules_client.go new file mode 100644 index 000000000..3bfc0b6ae --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/natrules_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 armnetwork + +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" +) + +// NatRulesClient contains the methods for the NatRules group. +// Don't use this type directly, use NewNatRulesClient() instead. +type NatRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewNatRulesClient creates a new instance of NatRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewNatRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*NatRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &NatRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a nat rule to a scalable vpn gateway if it doesn't exist else updates the existing nat rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - natRuleName - The name of the nat rule. +// - natRuleParameters - Parameters supplied to create or Update a Nat Rule. +// - options - NatRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the NatRulesClient.BeginCreateOrUpdate +// method. +func (client *NatRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, natRuleParameters VPNGatewayNatRule, options *NatRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[NatRulesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, gatewayName, natRuleName, natRuleParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NatRulesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NatRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a nat rule to a scalable vpn gateway if it doesn't exist else updates the existing nat rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *NatRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, natRuleParameters VPNGatewayNatRule, options *NatRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "NatRulesClient.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, gatewayName, natRuleName, natRuleParameters, 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 *NatRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, natRuleParameters VPNGatewayNatRule, options *NatRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if natRuleName == "" { + return nil, errors.New("parameter natRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natRuleName}", url.PathEscape(natRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, natRuleParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a nat rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - natRuleName - The name of the nat rule. +// - options - NatRulesClientBeginDeleteOptions contains the optional parameters for the NatRulesClient.BeginDelete method. +func (client *NatRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, options *NatRulesClientBeginDeleteOptions) (*runtime.Poller[NatRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, gatewayName, natRuleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NatRulesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NatRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a nat rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *NatRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, options *NatRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "NatRulesClient.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, gatewayName, natRuleName, 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 *NatRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, options *NatRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if natRuleName == "" { + return nil, errors.New("parameter natRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natRuleName}", url.PathEscape(natRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a nat ruleGet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - natRuleName - The name of the nat rule. +// - options - NatRulesClientGetOptions contains the optional parameters for the NatRulesClient.Get method. +func (client *NatRulesClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, options *NatRulesClientGetOptions) (NatRulesClientGetResponse, error) { + var err error + const operationName = "NatRulesClient.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, gatewayName, natRuleName, options) + if err != nil { + return NatRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NatRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NatRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *NatRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, options *NatRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if natRuleName == "" { + return nil, errors.New("parameter natRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natRuleName}", url.PathEscape(natRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NatRulesClient) getHandleResponse(resp *http.Response) (NatRulesClientGetResponse, error) { + result := NatRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNGatewayNatRule); err != nil { + return NatRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListByVPNGatewayPager - Retrieves all nat rules for a particular virtual wan vpn gateway. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - options - NatRulesClientListByVPNGatewayOptions contains the optional parameters for the NatRulesClient.NewListByVPNGatewayPager +// method. +func (client *NatRulesClient) NewListByVPNGatewayPager(resourceGroupName string, gatewayName string, options *NatRulesClientListByVPNGatewayOptions) *runtime.Pager[NatRulesClientListByVPNGatewayResponse] { + return runtime.NewPager(runtime.PagingHandler[NatRulesClientListByVPNGatewayResponse]{ + More: func(page NatRulesClientListByVPNGatewayResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NatRulesClientListByVPNGatewayResponse) (NatRulesClientListByVPNGatewayResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NatRulesClient.NewListByVPNGatewayPager") + 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.listByVPNGatewayCreateRequest(ctx, resourceGroupName, gatewayName, options) + }, nil) + if err != nil { + return NatRulesClientListByVPNGatewayResponse{}, err + } + return client.listByVPNGatewayHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVPNGatewayCreateRequest creates the ListByVPNGateway request. +func (client *NatRulesClient) listByVPNGatewayCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *NatRulesClientListByVPNGatewayOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVPNGatewayHandleResponse handles the ListByVPNGateway response. +func (client *NatRulesClient) listByVPNGatewayHandleResponse(resp *http.Response) (NatRulesClientListByVPNGatewayResponse, error) { + result := NatRulesClientListByVPNGatewayResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNGatewayNatRulesResult); err != nil { + return NatRulesClientListByVPNGatewayResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/operations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/operations_client.go new file mode 100644 index 000000000..3312c5ba4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/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 armnetwork + +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 Network Rest API operations. +// +// Generated from API version 2023-05-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.Network/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-05-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/network/armnetwork/v4/options.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/options.go new file mode 100644 index 000000000..5efa1c6cc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/options.go @@ -0,0 +1,3927 @@ +//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 armnetwork + +// AdminRuleCollectionsClientBeginDeleteOptions contains the optional parameters for the AdminRuleCollectionsClient.BeginDelete +// method. +type AdminRuleCollectionsClientBeginDeleteOptions struct { + // Deletes the resource even if it is part of a deployed configuration. If the configuration has been deployed, the service + // will do a cleanup deployment in the background, prior to the delete. + Force *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AdminRuleCollectionsClientCreateOrUpdateOptions contains the optional parameters for the AdminRuleCollectionsClient.CreateOrUpdate +// method. +type AdminRuleCollectionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AdminRuleCollectionsClientGetOptions contains the optional parameters for the AdminRuleCollectionsClient.Get method. +type AdminRuleCollectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AdminRuleCollectionsClientListOptions contains the optional parameters for the AdminRuleCollectionsClient.NewListPager +// method. +type AdminRuleCollectionsClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// AdminRulesClientBeginDeleteOptions contains the optional parameters for the AdminRulesClient.BeginDelete method. +type AdminRulesClientBeginDeleteOptions struct { + // Deletes the resource even if it is part of a deployed configuration. If the configuration has been deployed, the service + // will do a cleanup deployment in the background, prior to the delete. + Force *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AdminRulesClientCreateOrUpdateOptions contains the optional parameters for the AdminRulesClient.CreateOrUpdate method. +type AdminRulesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AdminRulesClientGetOptions contains the optional parameters for the AdminRulesClient.Get method. +type AdminRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// AdminRulesClientListOptions contains the optional parameters for the AdminRulesClient.NewListPager method. +type AdminRulesClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ApplicationGatewayPrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the ApplicationGatewayPrivateEndpointConnectionsClient.BeginDelete +// method. +type ApplicationGatewayPrivateEndpointConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewayPrivateEndpointConnectionsClientBeginUpdateOptions contains the optional parameters for the ApplicationGatewayPrivateEndpointConnectionsClient.BeginUpdate +// method. +type ApplicationGatewayPrivateEndpointConnectionsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewayPrivateEndpointConnectionsClientGetOptions contains the optional parameters for the ApplicationGatewayPrivateEndpointConnectionsClient.Get +// method. +type ApplicationGatewayPrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewayPrivateEndpointConnectionsClientListOptions contains the optional parameters for the ApplicationGatewayPrivateEndpointConnectionsClient.NewListPager +// method. +type ApplicationGatewayPrivateEndpointConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewayPrivateLinkResourcesClientListOptions contains the optional parameters for the ApplicationGatewayPrivateLinkResourcesClient.NewListPager +// method. +type ApplicationGatewayPrivateLinkResourcesClientListOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewayWafDynamicManifestsClientGetOptions contains the optional parameters for the ApplicationGatewayWafDynamicManifestsClient.NewGetPager +// method. +type ApplicationGatewayWafDynamicManifestsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewayWafDynamicManifestsDefaultClientGetOptions contains the optional parameters for the ApplicationGatewayWafDynamicManifestsDefaultClient.Get +// method. +type ApplicationGatewayWafDynamicManifestsDefaultClientGetOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientBeginBackendHealthOnDemandOptions contains the optional parameters for the ApplicationGatewaysClient.BeginBackendHealthOnDemand +// method. +type ApplicationGatewaysClientBeginBackendHealthOnDemandOptions struct { + // Expands BackendAddressPool and BackendHttpSettings referenced in backend health. + Expand *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewaysClientBeginBackendHealthOptions contains the optional parameters for the ApplicationGatewaysClient.BeginBackendHealth +// method. +type ApplicationGatewaysClientBeginBackendHealthOptions struct { + // Expands BackendAddressPool and BackendHttpSettings referenced in backend health. + Expand *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the ApplicationGatewaysClient.BeginCreateOrUpdate +// method. +type ApplicationGatewaysClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewaysClientBeginDeleteOptions contains the optional parameters for the ApplicationGatewaysClient.BeginDelete +// method. +type ApplicationGatewaysClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewaysClientBeginStartOptions contains the optional parameters for the ApplicationGatewaysClient.BeginStart +// method. +type ApplicationGatewaysClientBeginStartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewaysClientBeginStopOptions contains the optional parameters for the ApplicationGatewaysClient.BeginStop +// method. +type ApplicationGatewaysClientBeginStopOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationGatewaysClientGetOptions contains the optional parameters for the ApplicationGatewaysClient.Get method. +type ApplicationGatewaysClientGetOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientGetSSLPredefinedPolicyOptions contains the optional parameters for the ApplicationGatewaysClient.GetSSLPredefinedPolicy +// method. +type ApplicationGatewaysClientGetSSLPredefinedPolicyOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListAllOptions contains the optional parameters for the ApplicationGatewaysClient.NewListAllPager +// method. +type ApplicationGatewaysClientListAllOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListAvailableRequestHeadersOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableRequestHeaders +// method. +type ApplicationGatewaysClientListAvailableRequestHeadersOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListAvailableResponseHeadersOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableResponseHeaders +// method. +type ApplicationGatewaysClientListAvailableResponseHeadersOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListAvailableSSLOptionsOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableSSLOptions +// method. +type ApplicationGatewaysClientListAvailableSSLOptionsOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesOptions contains the optional parameters for the ApplicationGatewaysClient.NewListAvailableSSLPredefinedPoliciesPager +// method. +type ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListAvailableServerVariablesOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableServerVariables +// method. +type ApplicationGatewaysClientListAvailableServerVariablesOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListAvailableWafRuleSetsOptions contains the optional parameters for the ApplicationGatewaysClient.ListAvailableWafRuleSets +// method. +type ApplicationGatewaysClientListAvailableWafRuleSetsOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientListOptions contains the optional parameters for the ApplicationGatewaysClient.NewListPager method. +type ApplicationGatewaysClientListOptions struct { + // placeholder for future optional parameters +} + +// ApplicationGatewaysClientUpdateTagsOptions contains the optional parameters for the ApplicationGatewaysClient.UpdateTags +// method. +type ApplicationGatewaysClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ApplicationSecurityGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the ApplicationSecurityGroupsClient.BeginCreateOrUpdate +// method. +type ApplicationSecurityGroupsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationSecurityGroupsClientBeginDeleteOptions contains the optional parameters for the ApplicationSecurityGroupsClient.BeginDelete +// method. +type ApplicationSecurityGroupsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ApplicationSecurityGroupsClientGetOptions contains the optional parameters for the ApplicationSecurityGroupsClient.Get +// method. +type ApplicationSecurityGroupsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ApplicationSecurityGroupsClientListAllOptions contains the optional parameters for the ApplicationSecurityGroupsClient.NewListAllPager +// method. +type ApplicationSecurityGroupsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// ApplicationSecurityGroupsClientListOptions contains the optional parameters for the ApplicationSecurityGroupsClient.NewListPager +// method. +type ApplicationSecurityGroupsClientListOptions struct { + // placeholder for future optional parameters +} + +// ApplicationSecurityGroupsClientUpdateTagsOptions contains the optional parameters for the ApplicationSecurityGroupsClient.UpdateTags +// method. +type ApplicationSecurityGroupsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// AvailableDelegationsClientListOptions contains the optional parameters for the AvailableDelegationsClient.NewListPager +// method. +type AvailableDelegationsClientListOptions struct { + // placeholder for future optional parameters +} + +// AvailableEndpointServicesClientListOptions contains the optional parameters for the AvailableEndpointServicesClient.NewListPager +// method. +type AvailableEndpointServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// AvailablePrivateEndpointTypesClientListByResourceGroupOptions contains the optional parameters for the AvailablePrivateEndpointTypesClient.NewListByResourceGroupPager +// method. +type AvailablePrivateEndpointTypesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AvailablePrivateEndpointTypesClientListOptions contains the optional parameters for the AvailablePrivateEndpointTypesClient.NewListPager +// method. +type AvailablePrivateEndpointTypesClientListOptions struct { + // placeholder for future optional parameters +} + +// AvailableResourceGroupDelegationsClientListOptions contains the optional parameters for the AvailableResourceGroupDelegationsClient.NewListPager +// method. +type AvailableResourceGroupDelegationsClientListOptions struct { + // placeholder for future optional parameters +} + +// AvailableServiceAliasesClientListByResourceGroupOptions contains the optional parameters for the AvailableServiceAliasesClient.NewListByResourceGroupPager +// method. +type AvailableServiceAliasesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AvailableServiceAliasesClientListOptions contains the optional parameters for the AvailableServiceAliasesClient.NewListPager +// method. +type AvailableServiceAliasesClientListOptions struct { + // placeholder for future optional parameters +} + +// AzureFirewallFqdnTagsClientListAllOptions contains the optional parameters for the AzureFirewallFqdnTagsClient.NewListAllPager +// method. +type AzureFirewallFqdnTagsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// AzureFirewallsClientBeginCreateOrUpdateOptions contains the optional parameters for the AzureFirewallsClient.BeginCreateOrUpdate +// method. +type AzureFirewallsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AzureFirewallsClientBeginDeleteOptions contains the optional parameters for the AzureFirewallsClient.BeginDelete method. +type AzureFirewallsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AzureFirewallsClientBeginListLearnedPrefixesOptions contains the optional parameters for the AzureFirewallsClient.BeginListLearnedPrefixes +// method. +type AzureFirewallsClientBeginListLearnedPrefixesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AzureFirewallsClientBeginPacketCaptureOptions contains the optional parameters for the AzureFirewallsClient.BeginPacketCapture +// method. +type AzureFirewallsClientBeginPacketCaptureOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AzureFirewallsClientBeginUpdateTagsOptions contains the optional parameters for the AzureFirewallsClient.BeginUpdateTags +// method. +type AzureFirewallsClientBeginUpdateTagsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AzureFirewallsClientGetOptions contains the optional parameters for the AzureFirewallsClient.Get method. +type AzureFirewallsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AzureFirewallsClientListAllOptions contains the optional parameters for the AzureFirewallsClient.NewListAllPager method. +type AzureFirewallsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// AzureFirewallsClientListOptions contains the optional parameters for the AzureFirewallsClient.NewListPager method. +type AzureFirewallsClientListOptions struct { + // placeholder for future optional parameters +} + +// BastionHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the BastionHostsClient.BeginCreateOrUpdate +// method. +type BastionHostsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// BastionHostsClientBeginDeleteOptions contains the optional parameters for the BastionHostsClient.BeginDelete method. +type BastionHostsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// BastionHostsClientBeginUpdateTagsOptions contains the optional parameters for the BastionHostsClient.BeginUpdateTags method. +type BastionHostsClientBeginUpdateTagsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// BastionHostsClientGetOptions contains the optional parameters for the BastionHostsClient.Get method. +type BastionHostsClientGetOptions struct { + // placeholder for future optional parameters +} + +// BastionHostsClientListByResourceGroupOptions contains the optional parameters for the BastionHostsClient.NewListByResourceGroupPager +// method. +type BastionHostsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// BastionHostsClientListOptions contains the optional parameters for the BastionHostsClient.NewListPager method. +type BastionHostsClientListOptions struct { + // placeholder for future optional parameters +} + +// BgpServiceCommunitiesClientListOptions contains the optional parameters for the BgpServiceCommunitiesClient.NewListPager +// method. +type BgpServiceCommunitiesClientListOptions struct { + // placeholder for future optional parameters +} + +// ConfigurationPolicyGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.BeginCreateOrUpdate +// method. +type ConfigurationPolicyGroupsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConfigurationPolicyGroupsClientBeginDeleteOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.BeginDelete +// method. +type ConfigurationPolicyGroupsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConfigurationPolicyGroupsClientGetOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.Get +// method. +type ConfigurationPolicyGroupsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ConfigurationPolicyGroupsClientListByVPNServerConfigurationOptions contains the optional parameters for the ConfigurationPolicyGroupsClient.NewListByVPNServerConfigurationPager +// method. +type ConfigurationPolicyGroupsClientListByVPNServerConfigurationOptions struct { + // placeholder for future optional parameters +} + +// ConnectionMonitorsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConnectionMonitorsClient.BeginCreateOrUpdate +// method. +type ConnectionMonitorsClientBeginCreateOrUpdateOptions struct { + // Value indicating whether connection monitor V1 should be migrated to V2 format. + Migrate *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConnectionMonitorsClientBeginDeleteOptions contains the optional parameters for the ConnectionMonitorsClient.BeginDelete +// method. +type ConnectionMonitorsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConnectionMonitorsClientBeginQueryOptions contains the optional parameters for the ConnectionMonitorsClient.BeginQuery +// method. +type ConnectionMonitorsClientBeginQueryOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConnectionMonitorsClientBeginStartOptions contains the optional parameters for the ConnectionMonitorsClient.BeginStart +// method. +type ConnectionMonitorsClientBeginStartOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConnectionMonitorsClientBeginStopOptions contains the optional parameters for the ConnectionMonitorsClient.BeginStop method. +type ConnectionMonitorsClientBeginStopOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConnectionMonitorsClientGetOptions contains the optional parameters for the ConnectionMonitorsClient.Get method. +type ConnectionMonitorsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ConnectionMonitorsClientListOptions contains the optional parameters for the ConnectionMonitorsClient.NewListPager method. +type ConnectionMonitorsClientListOptions struct { + // placeholder for future optional parameters +} + +// ConnectionMonitorsClientUpdateTagsOptions contains the optional parameters for the ConnectionMonitorsClient.UpdateTags +// method. +type ConnectionMonitorsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ConnectivityConfigurationsClientBeginDeleteOptions contains the optional parameters for the ConnectivityConfigurationsClient.BeginDelete +// method. +type ConnectivityConfigurationsClientBeginDeleteOptions struct { + // Deletes the resource even if it is part of a deployed configuration. If the configuration has been deployed, the service + // will do a cleanup deployment in the background, prior to the delete. + Force *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConnectivityConfigurationsClientCreateOrUpdateOptions contains the optional parameters for the ConnectivityConfigurationsClient.CreateOrUpdate +// method. +type ConnectivityConfigurationsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ConnectivityConfigurationsClientGetOptions contains the optional parameters for the ConnectivityConfigurationsClient.Get +// method. +type ConnectivityConfigurationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ConnectivityConfigurationsClientListOptions contains the optional parameters for the ConnectivityConfigurationsClient.NewListPager +// method. +type ConnectivityConfigurationsClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// CustomIPPrefixesClientBeginCreateOrUpdateOptions contains the optional parameters for the CustomIPPrefixesClient.BeginCreateOrUpdate +// method. +type CustomIPPrefixesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CustomIPPrefixesClientBeginDeleteOptions contains the optional parameters for the CustomIPPrefixesClient.BeginDelete method. +type CustomIPPrefixesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CustomIPPrefixesClientGetOptions contains the optional parameters for the CustomIPPrefixesClient.Get method. +type CustomIPPrefixesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// CustomIPPrefixesClientListAllOptions contains the optional parameters for the CustomIPPrefixesClient.NewListAllPager method. +type CustomIPPrefixesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// CustomIPPrefixesClientListOptions contains the optional parameters for the CustomIPPrefixesClient.NewListPager method. +type CustomIPPrefixesClientListOptions struct { + // placeholder for future optional parameters +} + +// CustomIPPrefixesClientUpdateTagsOptions contains the optional parameters for the CustomIPPrefixesClient.UpdateTags method. +type CustomIPPrefixesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// DdosCustomPoliciesClientBeginCreateOrUpdateOptions contains the optional parameters for the DdosCustomPoliciesClient.BeginCreateOrUpdate +// method. +type DdosCustomPoliciesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DdosCustomPoliciesClientBeginDeleteOptions contains the optional parameters for the DdosCustomPoliciesClient.BeginDelete +// method. +type DdosCustomPoliciesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DdosCustomPoliciesClientGetOptions contains the optional parameters for the DdosCustomPoliciesClient.Get method. +type DdosCustomPoliciesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DdosCustomPoliciesClientUpdateTagsOptions contains the optional parameters for the DdosCustomPoliciesClient.UpdateTags +// method. +type DdosCustomPoliciesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// DdosProtectionPlansClientBeginCreateOrUpdateOptions contains the optional parameters for the DdosProtectionPlansClient.BeginCreateOrUpdate +// method. +type DdosProtectionPlansClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DdosProtectionPlansClientBeginDeleteOptions contains the optional parameters for the DdosProtectionPlansClient.BeginDelete +// method. +type DdosProtectionPlansClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DdosProtectionPlansClientGetOptions contains the optional parameters for the DdosProtectionPlansClient.Get method. +type DdosProtectionPlansClientGetOptions struct { + // placeholder for future optional parameters +} + +// DdosProtectionPlansClientListByResourceGroupOptions contains the optional parameters for the DdosProtectionPlansClient.NewListByResourceGroupPager +// method. +type DdosProtectionPlansClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// DdosProtectionPlansClientListOptions contains the optional parameters for the DdosProtectionPlansClient.NewListPager method. +type DdosProtectionPlansClientListOptions struct { + // placeholder for future optional parameters +} + +// DdosProtectionPlansClientUpdateTagsOptions contains the optional parameters for the DdosProtectionPlansClient.UpdateTags +// method. +type DdosProtectionPlansClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// DefaultSecurityRulesClientGetOptions contains the optional parameters for the DefaultSecurityRulesClient.Get method. +type DefaultSecurityRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DefaultSecurityRulesClientListOptions contains the optional parameters for the DefaultSecurityRulesClient.NewListPager +// method. +type DefaultSecurityRulesClientListOptions struct { + // placeholder for future optional parameters +} + +// DscpConfigurationClientBeginCreateOrUpdateOptions contains the optional parameters for the DscpConfigurationClient.BeginCreateOrUpdate +// method. +type DscpConfigurationClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DscpConfigurationClientBeginDeleteOptions contains the optional parameters for the DscpConfigurationClient.BeginDelete +// method. +type DscpConfigurationClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// DscpConfigurationClientGetOptions contains the optional parameters for the DscpConfigurationClient.Get method. +type DscpConfigurationClientGetOptions struct { + // placeholder for future optional parameters +} + +// DscpConfigurationClientListAllOptions contains the optional parameters for the DscpConfigurationClient.NewListAllPager +// method. +type DscpConfigurationClientListAllOptions struct { + // placeholder for future optional parameters +} + +// DscpConfigurationClientListOptions contains the optional parameters for the DscpConfigurationClient.NewListPager method. +type DscpConfigurationClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitAuthorizationsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.BeginCreateOrUpdate +// method. +type ExpressRouteCircuitAuthorizationsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitAuthorizationsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.BeginDelete +// method. +type ExpressRouteCircuitAuthorizationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitAuthorizationsClientGetOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.Get +// method. +type ExpressRouteCircuitAuthorizationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitAuthorizationsClientListOptions contains the optional parameters for the ExpressRouteCircuitAuthorizationsClient.NewListPager +// method. +type ExpressRouteCircuitAuthorizationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.BeginCreateOrUpdate +// method. +type ExpressRouteCircuitConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitConnectionsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.BeginDelete +// method. +type ExpressRouteCircuitConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitConnectionsClientGetOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.Get +// method. +type ExpressRouteCircuitConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitConnectionsClientListOptions contains the optional parameters for the ExpressRouteCircuitConnectionsClient.NewListPager +// method. +type ExpressRouteCircuitConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.BeginCreateOrUpdate +// method. +type ExpressRouteCircuitPeeringsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitPeeringsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.BeginDelete +// method. +type ExpressRouteCircuitPeeringsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitPeeringsClientGetOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.Get +// method. +type ExpressRouteCircuitPeeringsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitPeeringsClientListOptions contains the optional parameters for the ExpressRouteCircuitPeeringsClient.NewListPager +// method. +type ExpressRouteCircuitPeeringsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginCreateOrUpdate +// method. +type ExpressRouteCircuitsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginDelete +// method. +type ExpressRouteCircuitsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitsClientBeginListArpTableOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginListArpTable +// method. +type ExpressRouteCircuitsClientBeginListArpTableOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitsClientBeginListRoutesTableOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginListRoutesTable +// method. +type ExpressRouteCircuitsClientBeginListRoutesTableOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitsClientBeginListRoutesTableSummaryOptions contains the optional parameters for the ExpressRouteCircuitsClient.BeginListRoutesTableSummary +// method. +type ExpressRouteCircuitsClientBeginListRoutesTableSummaryOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCircuitsClientGetOptions contains the optional parameters for the ExpressRouteCircuitsClient.Get method. +type ExpressRouteCircuitsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitsClientGetPeeringStatsOptions contains the optional parameters for the ExpressRouteCircuitsClient.GetPeeringStats +// method. +type ExpressRouteCircuitsClientGetPeeringStatsOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitsClientGetStatsOptions contains the optional parameters for the ExpressRouteCircuitsClient.GetStats +// method. +type ExpressRouteCircuitsClientGetStatsOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitsClientListAllOptions contains the optional parameters for the ExpressRouteCircuitsClient.NewListAllPager +// method. +type ExpressRouteCircuitsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitsClientListOptions contains the optional parameters for the ExpressRouteCircuitsClient.NewListPager +// method. +type ExpressRouteCircuitsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCircuitsClientUpdateTagsOptions contains the optional parameters for the ExpressRouteCircuitsClient.UpdateTags +// method. +type ExpressRouteCircuitsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteConnectionsClient.BeginCreateOrUpdate +// method. +type ExpressRouteConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteConnectionsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteConnectionsClient.BeginDelete +// method. +type ExpressRouteConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteConnectionsClientGetOptions contains the optional parameters for the ExpressRouteConnectionsClient.Get method. +type ExpressRouteConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteConnectionsClientListOptions contains the optional parameters for the ExpressRouteConnectionsClient.List method. +type ExpressRouteConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCrossConnectionPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCrossConnectionPeeringsClient.BeginCreateOrUpdate +// method. +type ExpressRouteCrossConnectionPeeringsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCrossConnectionPeeringsClientBeginDeleteOptions contains the optional parameters for the ExpressRouteCrossConnectionPeeringsClient.BeginDelete +// method. +type ExpressRouteCrossConnectionPeeringsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCrossConnectionPeeringsClientGetOptions contains the optional parameters for the ExpressRouteCrossConnectionPeeringsClient.Get +// method. +type ExpressRouteCrossConnectionPeeringsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCrossConnectionPeeringsClientListOptions contains the optional parameters for the ExpressRouteCrossConnectionPeeringsClient.NewListPager +// method. +type ExpressRouteCrossConnectionPeeringsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCrossConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.BeginCreateOrUpdate +// method. +type ExpressRouteCrossConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCrossConnectionsClientBeginListArpTableOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.BeginListArpTable +// method. +type ExpressRouteCrossConnectionsClientBeginListArpTableOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCrossConnectionsClientBeginListRoutesTableOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.BeginListRoutesTable +// method. +type ExpressRouteCrossConnectionsClientBeginListRoutesTableOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCrossConnectionsClientBeginListRoutesTableSummaryOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.BeginListRoutesTableSummary +// method. +type ExpressRouteCrossConnectionsClientBeginListRoutesTableSummaryOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteCrossConnectionsClientGetOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.Get +// method. +type ExpressRouteCrossConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCrossConnectionsClientListByResourceGroupOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.NewListByResourceGroupPager +// method. +type ExpressRouteCrossConnectionsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCrossConnectionsClientListOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.NewListPager +// method. +type ExpressRouteCrossConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteCrossConnectionsClientUpdateTagsOptions contains the optional parameters for the ExpressRouteCrossConnectionsClient.UpdateTags +// method. +type ExpressRouteCrossConnectionsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRouteGatewaysClient.BeginCreateOrUpdate +// method. +type ExpressRouteGatewaysClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteGatewaysClientBeginDeleteOptions contains the optional parameters for the ExpressRouteGatewaysClient.BeginDelete +// method. +type ExpressRouteGatewaysClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the ExpressRouteGatewaysClient.BeginUpdateTags +// method. +type ExpressRouteGatewaysClientBeginUpdateTagsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRouteGatewaysClientGetOptions contains the optional parameters for the ExpressRouteGatewaysClient.Get method. +type ExpressRouteGatewaysClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteGatewaysClientListByResourceGroupOptions contains the optional parameters for the ExpressRouteGatewaysClient.ListByResourceGroup +// method. +type ExpressRouteGatewaysClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteGatewaysClientListBySubscriptionOptions contains the optional parameters for the ExpressRouteGatewaysClient.ListBySubscription +// method. +type ExpressRouteGatewaysClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteLinksClientGetOptions contains the optional parameters for the ExpressRouteLinksClient.Get method. +type ExpressRouteLinksClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteLinksClientListOptions contains the optional parameters for the ExpressRouteLinksClient.NewListPager method. +type ExpressRouteLinksClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortAuthorizationsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.BeginCreateOrUpdate +// method. +type ExpressRoutePortAuthorizationsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRoutePortAuthorizationsClientBeginDeleteOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.BeginDelete +// method. +type ExpressRoutePortAuthorizationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRoutePortAuthorizationsClientGetOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.Get +// method. +type ExpressRoutePortAuthorizationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortAuthorizationsClientListOptions contains the optional parameters for the ExpressRoutePortAuthorizationsClient.NewListPager +// method. +type ExpressRoutePortAuthorizationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortsClientBeginCreateOrUpdateOptions contains the optional parameters for the ExpressRoutePortsClient.BeginCreateOrUpdate +// method. +type ExpressRoutePortsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRoutePortsClientBeginDeleteOptions contains the optional parameters for the ExpressRoutePortsClient.BeginDelete +// method. +type ExpressRoutePortsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ExpressRoutePortsClientGenerateLOAOptions contains the optional parameters for the ExpressRoutePortsClient.GenerateLOA +// method. +type ExpressRoutePortsClientGenerateLOAOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortsClientGetOptions contains the optional parameters for the ExpressRoutePortsClient.Get method. +type ExpressRoutePortsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortsClientListByResourceGroupOptions contains the optional parameters for the ExpressRoutePortsClient.NewListByResourceGroupPager +// method. +type ExpressRoutePortsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortsClientListOptions contains the optional parameters for the ExpressRoutePortsClient.NewListPager method. +type ExpressRoutePortsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortsClientUpdateTagsOptions contains the optional parameters for the ExpressRoutePortsClient.UpdateTags method. +type ExpressRoutePortsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortsLocationsClientGetOptions contains the optional parameters for the ExpressRoutePortsLocationsClient.Get +// method. +type ExpressRoutePortsLocationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExpressRoutePortsLocationsClientListOptions contains the optional parameters for the ExpressRoutePortsLocationsClient.NewListPager +// method. +type ExpressRoutePortsLocationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ExpressRouteProviderPortsLocationClientListOptions contains the optional parameters for the ExpressRouteProviderPortsLocationClient.List +// method. +type ExpressRouteProviderPortsLocationClientListOptions struct { + // The filter to apply on the operation. For example, you can use $filter=location eq '{state}'. + Filter *string +} + +// ExpressRouteServiceProvidersClientListOptions contains the optional parameters for the ExpressRouteServiceProvidersClient.NewListPager +// method. +type ExpressRouteServiceProvidersClientListOptions struct { + // placeholder for future optional parameters +} + +// FirewallPoliciesClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallPoliciesClient.BeginCreateOrUpdate +// method. +type FirewallPoliciesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// FirewallPoliciesClientBeginDeleteOptions contains the optional parameters for the FirewallPoliciesClient.BeginDelete method. +type FirewallPoliciesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// FirewallPoliciesClientGetOptions contains the optional parameters for the FirewallPoliciesClient.Get method. +type FirewallPoliciesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// FirewallPoliciesClientListAllOptions contains the optional parameters for the FirewallPoliciesClient.NewListAllPager method. +type FirewallPoliciesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// FirewallPoliciesClientListOptions contains the optional parameters for the FirewallPoliciesClient.NewListPager method. +type FirewallPoliciesClientListOptions struct { + // placeholder for future optional parameters +} + +// FirewallPoliciesClientUpdateTagsOptions contains the optional parameters for the FirewallPoliciesClient.UpdateTags method. +type FirewallPoliciesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyIdpsSignaturesClientListOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesClient.List +// method. +type FirewallPolicyIdpsSignaturesClientListOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyIdpsSignaturesFilterValuesClientListOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesFilterValuesClient.List +// method. +type FirewallPolicyIdpsSignaturesFilterValuesClientListOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyIdpsSignaturesOverridesClientGetOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.Get +// method. +type FirewallPolicyIdpsSignaturesOverridesClientGetOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyIdpsSignaturesOverridesClientListOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.List +// method. +type FirewallPolicyIdpsSignaturesOverridesClientListOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyIdpsSignaturesOverridesClientPatchOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.Patch +// method. +type FirewallPolicyIdpsSignaturesOverridesClientPatchOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyIdpsSignaturesOverridesClientPutOptions contains the optional parameters for the FirewallPolicyIdpsSignaturesOverridesClient.Put +// method. +type FirewallPolicyIdpsSignaturesOverridesClientPutOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyRuleCollectionGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.BeginCreateOrUpdate +// method. +type FirewallPolicyRuleCollectionGroupsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// FirewallPolicyRuleCollectionGroupsClientBeginDeleteOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.BeginDelete +// method. +type FirewallPolicyRuleCollectionGroupsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// FirewallPolicyRuleCollectionGroupsClientGetOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.Get +// method. +type FirewallPolicyRuleCollectionGroupsClientGetOptions struct { + // placeholder for future optional parameters +} + +// FirewallPolicyRuleCollectionGroupsClientListOptions contains the optional parameters for the FirewallPolicyRuleCollectionGroupsClient.NewListPager +// method. +type FirewallPolicyRuleCollectionGroupsClientListOptions struct { + // placeholder for future optional parameters +} + +// FlowLogsClientBeginCreateOrUpdateOptions contains the optional parameters for the FlowLogsClient.BeginCreateOrUpdate method. +type FlowLogsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// FlowLogsClientBeginDeleteOptions contains the optional parameters for the FlowLogsClient.BeginDelete method. +type FlowLogsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// FlowLogsClientGetOptions contains the optional parameters for the FlowLogsClient.Get method. +type FlowLogsClientGetOptions struct { + // placeholder for future optional parameters +} + +// FlowLogsClientListOptions contains the optional parameters for the FlowLogsClient.NewListPager method. +type FlowLogsClientListOptions struct { + // placeholder for future optional parameters +} + +// FlowLogsClientUpdateTagsOptions contains the optional parameters for the FlowLogsClient.UpdateTags method. +type FlowLogsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// GroupsClientBeginDeleteOptions contains the optional parameters for the GroupsClient.BeginDelete method. +type GroupsClientBeginDeleteOptions struct { + // Deletes the resource even if it is part of a deployed configuration. If the configuration has been deployed, the service + // will do a cleanup deployment in the background, prior to the delete. + Force *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// GroupsClientCreateOrUpdateOptions contains the optional parameters for the GroupsClient.CreateOrUpdate method. +type GroupsClientCreateOrUpdateOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current resource. Specify the last-seen ETag value + // to prevent accidentally overwriting concurrent changes. + IfMatch *string +} + +// GroupsClientGetOptions contains the optional parameters for the GroupsClient.Get method. +type GroupsClientGetOptions struct { + // placeholder for future optional parameters +} + +// GroupsClientListOptions contains the optional parameters for the GroupsClient.NewListPager method. +type GroupsClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// HubRouteTablesClientBeginCreateOrUpdateOptions contains the optional parameters for the HubRouteTablesClient.BeginCreateOrUpdate +// method. +type HubRouteTablesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// HubRouteTablesClientBeginDeleteOptions contains the optional parameters for the HubRouteTablesClient.BeginDelete method. +type HubRouteTablesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// HubRouteTablesClientGetOptions contains the optional parameters for the HubRouteTablesClient.Get method. +type HubRouteTablesClientGetOptions struct { + // placeholder for future optional parameters +} + +// HubRouteTablesClientListOptions contains the optional parameters for the HubRouteTablesClient.NewListPager method. +type HubRouteTablesClientListOptions struct { + // placeholder for future optional parameters +} + +// HubVirtualNetworkConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.BeginCreateOrUpdate +// method. +type HubVirtualNetworkConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// HubVirtualNetworkConnectionsClientBeginDeleteOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.BeginDelete +// method. +type HubVirtualNetworkConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// HubVirtualNetworkConnectionsClientGetOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.Get +// method. +type HubVirtualNetworkConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// HubVirtualNetworkConnectionsClientListOptions contains the optional parameters for the HubVirtualNetworkConnectionsClient.NewListPager +// method. +type HubVirtualNetworkConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// IPAllocationsClientBeginCreateOrUpdateOptions contains the optional parameters for the IPAllocationsClient.BeginCreateOrUpdate +// method. +type IPAllocationsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// IPAllocationsClientBeginDeleteOptions contains the optional parameters for the IPAllocationsClient.BeginDelete method. +type IPAllocationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// IPAllocationsClientGetOptions contains the optional parameters for the IPAllocationsClient.Get method. +type IPAllocationsClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// IPAllocationsClientListByResourceGroupOptions contains the optional parameters for the IPAllocationsClient.NewListByResourceGroupPager +// method. +type IPAllocationsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// IPAllocationsClientListOptions contains the optional parameters for the IPAllocationsClient.NewListPager method. +type IPAllocationsClientListOptions struct { + // placeholder for future optional parameters +} + +// IPAllocationsClientUpdateTagsOptions contains the optional parameters for the IPAllocationsClient.UpdateTags method. +type IPAllocationsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// IPGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the IPGroupsClient.BeginCreateOrUpdate method. +type IPGroupsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// IPGroupsClientBeginDeleteOptions contains the optional parameters for the IPGroupsClient.BeginDelete method. +type IPGroupsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// IPGroupsClientGetOptions contains the optional parameters for the IPGroupsClient.Get method. +type IPGroupsClientGetOptions struct { + // Expands resourceIds (of Firewalls/Network Security Groups etc.) back referenced by the IpGroups resource. + Expand *string +} + +// IPGroupsClientListByResourceGroupOptions contains the optional parameters for the IPGroupsClient.NewListByResourceGroupPager +// method. +type IPGroupsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// IPGroupsClientListOptions contains the optional parameters for the IPGroupsClient.NewListPager method. +type IPGroupsClientListOptions struct { + // placeholder for future optional parameters +} + +// IPGroupsClientUpdateGroupsOptions contains the optional parameters for the IPGroupsClient.UpdateGroups method. +type IPGroupsClientUpdateGroupsOptions struct { + // placeholder for future optional parameters +} + +// InboundNatRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the InboundNatRulesClient.BeginCreateOrUpdate +// method. +type InboundNatRulesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InboundNatRulesClientBeginDeleteOptions contains the optional parameters for the InboundNatRulesClient.BeginDelete method. +type InboundNatRulesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InboundNatRulesClientGetOptions contains the optional parameters for the InboundNatRulesClient.Get method. +type InboundNatRulesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// InboundNatRulesClientListOptions contains the optional parameters for the InboundNatRulesClient.NewListPager method. +type InboundNatRulesClientListOptions struct { + // placeholder for future optional parameters +} + +// InboundSecurityRuleClientBeginCreateOrUpdateOptions contains the optional parameters for the InboundSecurityRuleClient.BeginCreateOrUpdate +// method. +type InboundSecurityRuleClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InterfaceIPConfigurationsClientGetOptions contains the optional parameters for the InterfaceIPConfigurationsClient.Get +// method. +type InterfaceIPConfigurationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// InterfaceIPConfigurationsClientListOptions contains the optional parameters for the InterfaceIPConfigurationsClient.NewListPager +// method. +type InterfaceIPConfigurationsClientListOptions struct { + // placeholder for future optional parameters +} + +// InterfaceLoadBalancersClientListOptions contains the optional parameters for the InterfaceLoadBalancersClient.NewListPager +// method. +type InterfaceLoadBalancersClientListOptions struct { + // placeholder for future optional parameters +} + +// InterfaceTapConfigurationsClientBeginCreateOrUpdateOptions contains the optional parameters for the InterfaceTapConfigurationsClient.BeginCreateOrUpdate +// method. +type InterfaceTapConfigurationsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InterfaceTapConfigurationsClientBeginDeleteOptions contains the optional parameters for the InterfaceTapConfigurationsClient.BeginDelete +// method. +type InterfaceTapConfigurationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InterfaceTapConfigurationsClientGetOptions contains the optional parameters for the InterfaceTapConfigurationsClient.Get +// method. +type InterfaceTapConfigurationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// InterfaceTapConfigurationsClientListOptions contains the optional parameters for the InterfaceTapConfigurationsClient.NewListPager +// method. +type InterfaceTapConfigurationsClientListOptions struct { + // placeholder for future optional parameters +} + +// InterfacesClientBeginCreateOrUpdateOptions contains the optional parameters for the InterfacesClient.BeginCreateOrUpdate +// method. +type InterfacesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InterfacesClientBeginDeleteOptions contains the optional parameters for the InterfacesClient.BeginDelete method. +type InterfacesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InterfacesClientBeginGetEffectiveRouteTableOptions contains the optional parameters for the InterfacesClient.BeginGetEffectiveRouteTable +// method. +type InterfacesClientBeginGetEffectiveRouteTableOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InterfacesClientBeginListEffectiveNetworkSecurityGroupsOptions contains the optional parameters for the InterfacesClient.BeginListEffectiveNetworkSecurityGroups +// method. +type InterfacesClientBeginListEffectiveNetworkSecurityGroupsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// InterfacesClientGetCloudServiceNetworkInterfaceOptions contains the optional parameters for the InterfacesClient.GetCloudServiceNetworkInterface +// method. +type InterfacesClientGetCloudServiceNetworkInterfaceOptions struct { + // Expands referenced resources. + Expand *string +} + +// InterfacesClientGetOptions contains the optional parameters for the InterfacesClient.Get method. +type InterfacesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// InterfacesClientGetVirtualMachineScaleSetIPConfigurationOptions contains the optional parameters for the InterfacesClient.GetVirtualMachineScaleSetIPConfiguration +// method. +type InterfacesClientGetVirtualMachineScaleSetIPConfigurationOptions struct { + // Expands referenced resources. + Expand *string +} + +// InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceOptions contains the optional parameters for the InterfacesClient.GetVirtualMachineScaleSetNetworkInterface +// method. +type InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceOptions struct { + // Expands referenced resources. + Expand *string +} + +// InterfacesClientListAllOptions contains the optional parameters for the InterfacesClient.NewListAllPager method. +type InterfacesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// InterfacesClientListCloudServiceNetworkInterfacesOptions contains the optional parameters for the InterfacesClient.NewListCloudServiceNetworkInterfacesPager +// method. +type InterfacesClientListCloudServiceNetworkInterfacesOptions struct { + // placeholder for future optional parameters +} + +// InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesOptions contains the optional parameters for the InterfacesClient.NewListCloudServiceRoleInstanceNetworkInterfacesPager +// method. +type InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesOptions struct { + // placeholder for future optional parameters +} + +// InterfacesClientListOptions contains the optional parameters for the InterfacesClient.NewListPager method. +type InterfacesClientListOptions struct { + // placeholder for future optional parameters +} + +// InterfacesClientListVirtualMachineScaleSetIPConfigurationsOptions contains the optional parameters for the InterfacesClient.NewListVirtualMachineScaleSetIPConfigurationsPager +// method. +type InterfacesClientListVirtualMachineScaleSetIPConfigurationsOptions struct { + // Expands referenced resources. + Expand *string +} + +// InterfacesClientListVirtualMachineScaleSetNetworkInterfacesOptions contains the optional parameters for the InterfacesClient.NewListVirtualMachineScaleSetNetworkInterfacesPager +// method. +type InterfacesClientListVirtualMachineScaleSetNetworkInterfacesOptions struct { + // placeholder for future optional parameters +} + +// InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesOptions contains the optional parameters for the InterfacesClient.NewListVirtualMachineScaleSetVMNetworkInterfacesPager +// method. +type InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesOptions struct { + // placeholder for future optional parameters +} + +// InterfacesClientUpdateTagsOptions contains the optional parameters for the InterfacesClient.UpdateTags method. +type InterfacesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerBackendAddressPoolsClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.BeginCreateOrUpdate +// method. +type LoadBalancerBackendAddressPoolsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LoadBalancerBackendAddressPoolsClientBeginDeleteOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.BeginDelete +// method. +type LoadBalancerBackendAddressPoolsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LoadBalancerBackendAddressPoolsClientGetOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.Get +// method. +type LoadBalancerBackendAddressPoolsClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerBackendAddressPoolsClientListOptions contains the optional parameters for the LoadBalancerBackendAddressPoolsClient.NewListPager +// method. +type LoadBalancerBackendAddressPoolsClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerFrontendIPConfigurationsClientGetOptions contains the optional parameters for the LoadBalancerFrontendIPConfigurationsClient.Get +// method. +type LoadBalancerFrontendIPConfigurationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerFrontendIPConfigurationsClientListOptions contains the optional parameters for the LoadBalancerFrontendIPConfigurationsClient.NewListPager +// method. +type LoadBalancerFrontendIPConfigurationsClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerLoadBalancingRulesClientGetOptions contains the optional parameters for the LoadBalancerLoadBalancingRulesClient.Get +// method. +type LoadBalancerLoadBalancingRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerLoadBalancingRulesClientListOptions contains the optional parameters for the LoadBalancerLoadBalancingRulesClient.NewListPager +// method. +type LoadBalancerLoadBalancingRulesClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerNetworkInterfacesClientListOptions contains the optional parameters for the LoadBalancerNetworkInterfacesClient.NewListPager +// method. +type LoadBalancerNetworkInterfacesClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerOutboundRulesClientGetOptions contains the optional parameters for the LoadBalancerOutboundRulesClient.Get +// method. +type LoadBalancerOutboundRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerOutboundRulesClientListOptions contains the optional parameters for the LoadBalancerOutboundRulesClient.NewListPager +// method. +type LoadBalancerOutboundRulesClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerProbesClientGetOptions contains the optional parameters for the LoadBalancerProbesClient.Get method. +type LoadBalancerProbesClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancerProbesClientListOptions contains the optional parameters for the LoadBalancerProbesClient.NewListPager method. +type LoadBalancerProbesClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancersClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadBalancersClient.BeginCreateOrUpdate +// method. +type LoadBalancersClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LoadBalancersClientBeginDeleteOptions contains the optional parameters for the LoadBalancersClient.BeginDelete method. +type LoadBalancersClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LoadBalancersClientBeginListInboundNatRulePortMappingsOptions contains the optional parameters for the LoadBalancersClient.BeginListInboundNatRulePortMappings +// method. +type LoadBalancersClientBeginListInboundNatRulePortMappingsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LoadBalancersClientBeginSwapPublicIPAddressesOptions contains the optional parameters for the LoadBalancersClient.BeginSwapPublicIPAddresses +// method. +type LoadBalancersClientBeginSwapPublicIPAddressesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LoadBalancersClientGetOptions contains the optional parameters for the LoadBalancersClient.Get method. +type LoadBalancersClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// LoadBalancersClientListAllOptions contains the optional parameters for the LoadBalancersClient.NewListAllPager method. +type LoadBalancersClientListAllOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancersClientListOptions contains the optional parameters for the LoadBalancersClient.NewListPager method. +type LoadBalancersClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancersClientMigrateToIPBasedOptions contains the optional parameters for the LoadBalancersClient.MigrateToIPBased +// method. +type LoadBalancersClientMigrateToIPBasedOptions struct { + // Parameters supplied to the migrateToIpBased Api. + Parameters *MigrateLoadBalancerToIPBasedRequest +} + +// LoadBalancersClientUpdateTagsOptions contains the optional parameters for the LoadBalancersClient.UpdateTags method. +type LoadBalancersClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// LocalNetworkGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the LocalNetworkGatewaysClient.BeginCreateOrUpdate +// method. +type LocalNetworkGatewaysClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LocalNetworkGatewaysClientBeginDeleteOptions contains the optional parameters for the LocalNetworkGatewaysClient.BeginDelete +// method. +type LocalNetworkGatewaysClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// LocalNetworkGatewaysClientGetOptions contains the optional parameters for the LocalNetworkGatewaysClient.Get method. +type LocalNetworkGatewaysClientGetOptions struct { + // placeholder for future optional parameters +} + +// LocalNetworkGatewaysClientListOptions contains the optional parameters for the LocalNetworkGatewaysClient.NewListPager +// method. +type LocalNetworkGatewaysClientListOptions struct { + // placeholder for future optional parameters +} + +// LocalNetworkGatewaysClientUpdateTagsOptions contains the optional parameters for the LocalNetworkGatewaysClient.UpdateTags +// method. +type LocalNetworkGatewaysClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientBeginDeleteBastionShareableLinkOptions contains the optional parameters for the ManagementClient.BeginDeleteBastionShareableLink +// method. +type ManagementClientBeginDeleteBastionShareableLinkOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagementClientBeginGeneratevirtualwanvpnserverconfigurationvpnprofileOptions contains the optional parameters for the +// ManagementClient.BeginGeneratevirtualwanvpnserverconfigurationvpnprofile method. +type ManagementClientBeginGeneratevirtualwanvpnserverconfigurationvpnprofileOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagementClientBeginGetActiveSessionsOptions contains the optional parameters for the ManagementClient.BeginGetActiveSessions +// method. +type ManagementClientBeginGetActiveSessionsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagementClientBeginPutBastionShareableLinkOptions contains the optional parameters for the ManagementClient.BeginPutBastionShareableLink +// method. +type ManagementClientBeginPutBastionShareableLinkOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagementClientCheckDNSNameAvailabilityOptions contains the optional parameters for the ManagementClient.CheckDNSNameAvailability +// method. +type ManagementClientCheckDNSNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientDisconnectActiveSessionsOptions contains the optional parameters for the ManagementClient.NewDisconnectActiveSessionsPager +// method. +type ManagementClientDisconnectActiveSessionsOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientExpressRouteProviderPortOptions contains the optional parameters for the ManagementClient.ExpressRouteProviderPort +// method. +type ManagementClientExpressRouteProviderPortOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientGetBastionShareableLinkOptions contains the optional parameters for the ManagementClient.NewGetBastionShareableLinkPager +// method. +type ManagementClientGetBastionShareableLinkOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientListActiveConnectivityConfigurationsOptions contains the optional parameters for the ManagementClient.ListActiveConnectivityConfigurations +// method. +type ManagementClientListActiveConnectivityConfigurationsOptions struct { + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagementClientListActiveSecurityAdminRulesOptions contains the optional parameters for the ManagementClient.ListActiveSecurityAdminRules +// method. +type ManagementClientListActiveSecurityAdminRulesOptions struct { + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions contains the optional parameters for the ManagementClient.ListNetworkManagerEffectiveConnectivityConfigurations +// method. +type ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsOptions struct { + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions contains the optional parameters for the ManagementClient.ListNetworkManagerEffectiveSecurityAdminRules +// method. +type ManagementClientListNetworkManagerEffectiveSecurityAdminRulesOptions struct { + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagementClientSupportedSecurityProvidersOptions contains the optional parameters for the ManagementClient.SupportedSecurityProviders +// method. +type ManagementClientSupportedSecurityProvidersOptions struct { + // placeholder for future optional parameters +} + +// ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateOptions contains the optional parameters for the ManagementGroupNetworkManagerConnectionsClient.CreateOrUpdate +// method. +type ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ManagementGroupNetworkManagerConnectionsClientDeleteOptions contains the optional parameters for the ManagementGroupNetworkManagerConnectionsClient.Delete +// method. +type ManagementGroupNetworkManagerConnectionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ManagementGroupNetworkManagerConnectionsClientGetOptions contains the optional parameters for the ManagementGroupNetworkManagerConnectionsClient.Get +// method. +type ManagementGroupNetworkManagerConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ManagementGroupNetworkManagerConnectionsClientListOptions contains the optional parameters for the ManagementGroupNetworkManagerConnectionsClient.NewListPager +// method. +type ManagementGroupNetworkManagerConnectionsClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagerCommitsClientBeginPostOptions contains the optional parameters for the ManagerCommitsClient.BeginPost method. +type ManagerCommitsClientBeginPostOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagerDeploymentStatusClientListOptions contains the optional parameters for the ManagerDeploymentStatusClient.List method. +type ManagerDeploymentStatusClientListOptions struct { + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagersClientBeginDeleteOptions contains the optional parameters for the ManagersClient.BeginDelete method. +type ManagersClientBeginDeleteOptions struct { + // Deletes the resource even if it is part of a deployed configuration. If the configuration has been deployed, the service + // will do a cleanup deployment in the background, prior to the delete. + Force *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagersClientCreateOrUpdateOptions contains the optional parameters for the ManagersClient.CreateOrUpdate method. +type ManagersClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ManagersClientGetOptions contains the optional parameters for the ManagersClient.Get method. +type ManagersClientGetOptions struct { + // placeholder for future optional parameters +} + +// ManagersClientListBySubscriptionOptions contains the optional parameters for the ManagersClient.NewListBySubscriptionPager +// method. +type ManagersClientListBySubscriptionOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagersClientListOptions contains the optional parameters for the ManagersClient.NewListPager method. +type ManagersClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// ManagersClientPatchOptions contains the optional parameters for the ManagersClient.Patch method. +type ManagersClientPatchOptions struct { + // placeholder for future optional parameters +} + +// NatGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the NatGatewaysClient.BeginCreateOrUpdate +// method. +type NatGatewaysClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// NatGatewaysClientBeginDeleteOptions contains the optional parameters for the NatGatewaysClient.BeginDelete method. +type NatGatewaysClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// NatGatewaysClientGetOptions contains the optional parameters for the NatGatewaysClient.Get method. +type NatGatewaysClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// NatGatewaysClientListAllOptions contains the optional parameters for the NatGatewaysClient.NewListAllPager method. +type NatGatewaysClientListAllOptions struct { + // placeholder for future optional parameters +} + +// NatGatewaysClientListOptions contains the optional parameters for the NatGatewaysClient.NewListPager method. +type NatGatewaysClientListOptions struct { + // placeholder for future optional parameters +} + +// NatGatewaysClientUpdateTagsOptions contains the optional parameters for the NatGatewaysClient.UpdateTags method. +type NatGatewaysClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// NatRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the NatRulesClient.BeginCreateOrUpdate method. +type NatRulesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// NatRulesClientBeginDeleteOptions contains the optional parameters for the NatRulesClient.BeginDelete method. +type NatRulesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// NatRulesClientGetOptions contains the optional parameters for the NatRulesClient.Get method. +type NatRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// NatRulesClientListByVPNGatewayOptions contains the optional parameters for the NatRulesClient.NewListByVPNGatewayPager +// method. +type NatRulesClientListByVPNGatewayOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// P2SVPNGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginCreateOrUpdate +// method. +type P2SVPNGatewaysClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientBeginDeleteOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginDelete method. +type P2SVPNGatewaysClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientBeginDisconnectP2SVPNConnectionsOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginDisconnectP2SVPNConnections +// method. +type P2SVPNGatewaysClientBeginDisconnectP2SVPNConnectionsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientBeginGenerateVPNProfileOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginGenerateVPNProfile +// method. +type P2SVPNGatewaysClientBeginGenerateVPNProfileOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthDetailedOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealthDetailed +// method. +type P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthDetailedOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealth +// method. +type P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientBeginResetOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginReset method. +type P2SVPNGatewaysClientBeginResetOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginUpdateTags +// method. +type P2SVPNGatewaysClientBeginUpdateTagsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// P2SVPNGatewaysClientGetOptions contains the optional parameters for the P2SVPNGatewaysClient.Get method. +type P2SVPNGatewaysClientGetOptions struct { + // placeholder for future optional parameters +} + +// P2SVPNGatewaysClientListByResourceGroupOptions contains the optional parameters for the P2SVPNGatewaysClient.NewListByResourceGroupPager +// method. +type P2SVPNGatewaysClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// P2SVPNGatewaysClientListOptions contains the optional parameters for the P2SVPNGatewaysClient.NewListPager method. +type P2SVPNGatewaysClientListOptions struct { + // placeholder for future optional parameters +} + +// PacketCapturesClientBeginCreateOptions contains the optional parameters for the PacketCapturesClient.BeginCreate method. +type PacketCapturesClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PacketCapturesClientBeginDeleteOptions contains the optional parameters for the PacketCapturesClient.BeginDelete method. +type PacketCapturesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PacketCapturesClientBeginGetStatusOptions contains the optional parameters for the PacketCapturesClient.BeginGetStatus +// method. +type PacketCapturesClientBeginGetStatusOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PacketCapturesClientBeginStopOptions contains the optional parameters for the PacketCapturesClient.BeginStop method. +type PacketCapturesClientBeginStopOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PacketCapturesClientGetOptions contains the optional parameters for the PacketCapturesClient.Get method. +type PacketCapturesClientGetOptions struct { + // placeholder for future optional parameters +} + +// PacketCapturesClientListOptions contains the optional parameters for the PacketCapturesClient.NewListPager method. +type PacketCapturesClientListOptions struct { + // placeholder for future optional parameters +} + +// PeerExpressRouteCircuitConnectionsClientGetOptions contains the optional parameters for the PeerExpressRouteCircuitConnectionsClient.Get +// method. +type PeerExpressRouteCircuitConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PeerExpressRouteCircuitConnectionsClientListOptions contains the optional parameters for the PeerExpressRouteCircuitConnectionsClient.NewListPager +// method. +type PeerExpressRouteCircuitConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateDNSZoneGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.BeginCreateOrUpdate +// method. +type PrivateDNSZoneGroupsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateDNSZoneGroupsClientBeginDeleteOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.BeginDelete +// method. +type PrivateDNSZoneGroupsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateDNSZoneGroupsClientGetOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.Get method. +type PrivateDNSZoneGroupsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateDNSZoneGroupsClientListOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.NewListPager +// method. +type PrivateDNSZoneGroupsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointsClient.BeginCreateOrUpdate +// method. +type PrivateEndpointsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateEndpointsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointsClient.BeginDelete method. +type PrivateEndpointsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateEndpointsClientGetOptions contains the optional parameters for the PrivateEndpointsClient.Get method. +type PrivateEndpointsClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// PrivateEndpointsClientListBySubscriptionOptions contains the optional parameters for the PrivateEndpointsClient.NewListBySubscriptionPager +// method. +type PrivateEndpointsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointsClientListOptions contains the optional parameters for the PrivateEndpointsClient.NewListPager method. +type PrivateEndpointsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityByResourceGroupOptions contains the optional parameters +// for the PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibilityByResourceGroup method. +type PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityByResourceGroupOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityOptions contains the optional parameters for the PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibility +// method. +type PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateLinkServicesClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateLinkServicesClient.BeginCreateOrUpdate +// method. +type PrivateLinkServicesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateLinkServicesClientBeginDeleteOptions contains the optional parameters for the PrivateLinkServicesClient.BeginDelete +// method. +type PrivateLinkServicesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateLinkServicesClientBeginDeletePrivateEndpointConnectionOptions contains the optional parameters for the PrivateLinkServicesClient.BeginDeletePrivateEndpointConnection +// method. +type PrivateLinkServicesClientBeginDeletePrivateEndpointConnectionOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateLinkServicesClientGetOptions contains the optional parameters for the PrivateLinkServicesClient.Get method. +type PrivateLinkServicesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// PrivateLinkServicesClientGetPrivateEndpointConnectionOptions contains the optional parameters for the PrivateLinkServicesClient.GetPrivateEndpointConnection +// method. +type PrivateLinkServicesClientGetPrivateEndpointConnectionOptions struct { + // Expands referenced resources. + Expand *string +} + +// PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupOptions contains the optional parameters for +// the PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesByResourceGroupPager method. +type PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesOptions contains the optional parameters for the PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesPager +// method. +type PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServicesClientListBySubscriptionOptions contains the optional parameters for the PrivateLinkServicesClient.NewListBySubscriptionPager +// method. +type PrivateLinkServicesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServicesClientListOptions contains the optional parameters for the PrivateLinkServicesClient.NewListPager method. +type PrivateLinkServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServicesClientListPrivateEndpointConnectionsOptions contains the optional parameters for the PrivateLinkServicesClient.NewListPrivateEndpointConnectionsPager +// method. +type PrivateLinkServicesClientListPrivateEndpointConnectionsOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServicesClientUpdatePrivateEndpointConnectionOptions contains the optional parameters for the PrivateLinkServicesClient.UpdatePrivateEndpointConnection +// method. +type PrivateLinkServicesClientUpdatePrivateEndpointConnectionOptions struct { + // placeholder for future optional parameters +} + +// ProfilesClientBeginDeleteOptions contains the optional parameters for the ProfilesClient.BeginDelete method. +type ProfilesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ProfilesClientCreateOrUpdateOptions contains the optional parameters for the ProfilesClient.CreateOrUpdate method. +type ProfilesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ProfilesClientGetOptions contains the optional parameters for the ProfilesClient.Get method. +type ProfilesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// ProfilesClientListAllOptions contains the optional parameters for the ProfilesClient.NewListAllPager method. +type ProfilesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// ProfilesClientListOptions contains the optional parameters for the ProfilesClient.NewListPager method. +type ProfilesClientListOptions struct { + // placeholder for future optional parameters +} + +// ProfilesClientUpdateTagsOptions contains the optional parameters for the ProfilesClient.UpdateTags method. +type ProfilesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// PublicIPAddressesClientBeginCreateOrUpdateOptions contains the optional parameters for the PublicIPAddressesClient.BeginCreateOrUpdate +// method. +type PublicIPAddressesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PublicIPAddressesClientBeginDdosProtectionStatusOptions contains the optional parameters for the PublicIPAddressesClient.BeginDdosProtectionStatus +// method. +type PublicIPAddressesClientBeginDdosProtectionStatusOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PublicIPAddressesClientBeginDeleteOptions contains the optional parameters for the PublicIPAddressesClient.BeginDelete +// method. +type PublicIPAddressesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PublicIPAddressesClientGetCloudServicePublicIPAddressOptions contains the optional parameters for the PublicIPAddressesClient.GetCloudServicePublicIPAddress +// method. +type PublicIPAddressesClientGetCloudServicePublicIPAddressOptions struct { + // Expands referenced resources. + Expand *string +} + +// PublicIPAddressesClientGetOptions contains the optional parameters for the PublicIPAddressesClient.Get method. +type PublicIPAddressesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressOptions contains the optional parameters for the PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress +// method. +type PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressOptions struct { + // Expands referenced resources. + Expand *string +} + +// PublicIPAddressesClientListAllOptions contains the optional parameters for the PublicIPAddressesClient.NewListAllPager +// method. +type PublicIPAddressesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// PublicIPAddressesClientListCloudServicePublicIPAddressesOptions contains the optional parameters for the PublicIPAddressesClient.NewListCloudServicePublicIPAddressesPager +// method. +type PublicIPAddressesClientListCloudServicePublicIPAddressesOptions struct { + // placeholder for future optional parameters +} + +// PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesOptions contains the optional parameters for the PublicIPAddressesClient.NewListCloudServiceRoleInstancePublicIPAddressesPager +// method. +type PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesOptions struct { + // placeholder for future optional parameters +} + +// PublicIPAddressesClientListOptions contains the optional parameters for the PublicIPAddressesClient.NewListPager method. +type PublicIPAddressesClientListOptions struct { + // placeholder for future optional parameters +} + +// PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesOptions contains the optional parameters for the PublicIPAddressesClient.NewListVirtualMachineScaleSetPublicIPAddressesPager +// method. +type PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesOptions struct { + // placeholder for future optional parameters +} + +// PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesOptions contains the optional parameters for the PublicIPAddressesClient.NewListVirtualMachineScaleSetVMPublicIPAddressesPager +// method. +type PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesOptions struct { + // placeholder for future optional parameters +} + +// PublicIPAddressesClientUpdateTagsOptions contains the optional parameters for the PublicIPAddressesClient.UpdateTags method. +type PublicIPAddressesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// PublicIPPrefixesClientBeginCreateOrUpdateOptions contains the optional parameters for the PublicIPPrefixesClient.BeginCreateOrUpdate +// method. +type PublicIPPrefixesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PublicIPPrefixesClientBeginDeleteOptions contains the optional parameters for the PublicIPPrefixesClient.BeginDelete method. +type PublicIPPrefixesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PublicIPPrefixesClientGetOptions contains the optional parameters for the PublicIPPrefixesClient.Get method. +type PublicIPPrefixesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// PublicIPPrefixesClientListAllOptions contains the optional parameters for the PublicIPPrefixesClient.NewListAllPager method. +type PublicIPPrefixesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// PublicIPPrefixesClientListOptions contains the optional parameters for the PublicIPPrefixesClient.NewListPager method. +type PublicIPPrefixesClientListOptions struct { + // placeholder for future optional parameters +} + +// PublicIPPrefixesClientUpdateTagsOptions contains the optional parameters for the PublicIPPrefixesClient.UpdateTags method. +type PublicIPPrefixesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ResourceNavigationLinksClientListOptions contains the optional parameters for the ResourceNavigationLinksClient.List method. +type ResourceNavigationLinksClientListOptions struct { + // placeholder for future optional parameters +} + +// RouteFilterRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteFilterRulesClient.BeginCreateOrUpdate +// method. +type RouteFilterRulesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteFilterRulesClientBeginDeleteOptions contains the optional parameters for the RouteFilterRulesClient.BeginDelete method. +type RouteFilterRulesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteFilterRulesClientGetOptions contains the optional parameters for the RouteFilterRulesClient.Get method. +type RouteFilterRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// RouteFilterRulesClientListByRouteFilterOptions contains the optional parameters for the RouteFilterRulesClient.NewListByRouteFilterPager +// method. +type RouteFilterRulesClientListByRouteFilterOptions struct { + // placeholder for future optional parameters +} + +// RouteFiltersClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteFiltersClient.BeginCreateOrUpdate +// method. +type RouteFiltersClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteFiltersClientBeginDeleteOptions contains the optional parameters for the RouteFiltersClient.BeginDelete method. +type RouteFiltersClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteFiltersClientGetOptions contains the optional parameters for the RouteFiltersClient.Get method. +type RouteFiltersClientGetOptions struct { + // Expands referenced express route bgp peering resources. + Expand *string +} + +// RouteFiltersClientListByResourceGroupOptions contains the optional parameters for the RouteFiltersClient.NewListByResourceGroupPager +// method. +type RouteFiltersClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// RouteFiltersClientListOptions contains the optional parameters for the RouteFiltersClient.NewListPager method. +type RouteFiltersClientListOptions struct { + // placeholder for future optional parameters +} + +// RouteFiltersClientUpdateTagsOptions contains the optional parameters for the RouteFiltersClient.UpdateTags method. +type RouteFiltersClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// RouteMapsClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteMapsClient.BeginCreateOrUpdate +// method. +type RouteMapsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteMapsClientBeginDeleteOptions contains the optional parameters for the RouteMapsClient.BeginDelete method. +type RouteMapsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteMapsClientGetOptions contains the optional parameters for the RouteMapsClient.Get method. +type RouteMapsClientGetOptions struct { + // placeholder for future optional parameters +} + +// RouteMapsClientListOptions contains the optional parameters for the RouteMapsClient.NewListPager method. +type RouteMapsClientListOptions struct { + // placeholder for future optional parameters +} + +// RouteTablesClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteTablesClient.BeginCreateOrUpdate +// method. +type RouteTablesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteTablesClientBeginDeleteOptions contains the optional parameters for the RouteTablesClient.BeginDelete method. +type RouteTablesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RouteTablesClientGetOptions contains the optional parameters for the RouteTablesClient.Get method. +type RouteTablesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// RouteTablesClientListAllOptions contains the optional parameters for the RouteTablesClient.NewListAllPager method. +type RouteTablesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// RouteTablesClientListOptions contains the optional parameters for the RouteTablesClient.NewListPager method. +type RouteTablesClientListOptions struct { + // placeholder for future optional parameters +} + +// RouteTablesClientUpdateTagsOptions contains the optional parameters for the RouteTablesClient.UpdateTags method. +type RouteTablesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// RoutesClientBeginCreateOrUpdateOptions contains the optional parameters for the RoutesClient.BeginCreateOrUpdate method. +type RoutesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RoutesClientBeginDeleteOptions contains the optional parameters for the RoutesClient.BeginDelete method. +type RoutesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RoutesClientGetOptions contains the optional parameters for the RoutesClient.Get method. +type RoutesClientGetOptions struct { + // placeholder for future optional parameters +} + +// RoutesClientListOptions contains the optional parameters for the RoutesClient.NewListPager method. +type RoutesClientListOptions struct { + // placeholder for future optional parameters +} + +// RoutingIntentClientBeginCreateOrUpdateOptions contains the optional parameters for the RoutingIntentClient.BeginCreateOrUpdate +// method. +type RoutingIntentClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RoutingIntentClientBeginDeleteOptions contains the optional parameters for the RoutingIntentClient.BeginDelete method. +type RoutingIntentClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RoutingIntentClientGetOptions contains the optional parameters for the RoutingIntentClient.Get method. +type RoutingIntentClientGetOptions struct { + // placeholder for future optional parameters +} + +// RoutingIntentClientListOptions contains the optional parameters for the RoutingIntentClient.NewListPager method. +type RoutingIntentClientListOptions struct { + // placeholder for future optional parameters +} + +// ScopeConnectionsClientCreateOrUpdateOptions contains the optional parameters for the ScopeConnectionsClient.CreateOrUpdate +// method. +type ScopeConnectionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ScopeConnectionsClientDeleteOptions contains the optional parameters for the ScopeConnectionsClient.Delete method. +type ScopeConnectionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ScopeConnectionsClientGetOptions contains the optional parameters for the ScopeConnectionsClient.Get method. +type ScopeConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScopeConnectionsClientListOptions contains the optional parameters for the ScopeConnectionsClient.NewListPager method. +type ScopeConnectionsClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// SecurityAdminConfigurationsClientBeginDeleteOptions contains the optional parameters for the SecurityAdminConfigurationsClient.BeginDelete +// method. +type SecurityAdminConfigurationsClientBeginDeleteOptions struct { + // Deletes the resource even if it is part of a deployed configuration. If the configuration has been deployed, the service + // will do a cleanup deployment in the background, prior to the delete. + Force *bool + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SecurityAdminConfigurationsClientCreateOrUpdateOptions contains the optional parameters for the SecurityAdminConfigurationsClient.CreateOrUpdate +// method. +type SecurityAdminConfigurationsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// SecurityAdminConfigurationsClientGetOptions contains the optional parameters for the SecurityAdminConfigurationsClient.Get +// method. +type SecurityAdminConfigurationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SecurityAdminConfigurationsClientListOptions contains the optional parameters for the SecurityAdminConfigurationsClient.NewListPager +// method. +type SecurityAdminConfigurationsClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// SecurityGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the SecurityGroupsClient.BeginCreateOrUpdate +// method. +type SecurityGroupsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SecurityGroupsClientBeginDeleteOptions contains the optional parameters for the SecurityGroupsClient.BeginDelete method. +type SecurityGroupsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SecurityGroupsClientGetOptions contains the optional parameters for the SecurityGroupsClient.Get method. +type SecurityGroupsClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// SecurityGroupsClientListAllOptions contains the optional parameters for the SecurityGroupsClient.NewListAllPager method. +type SecurityGroupsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// SecurityGroupsClientListOptions contains the optional parameters for the SecurityGroupsClient.NewListPager method. +type SecurityGroupsClientListOptions struct { + // placeholder for future optional parameters +} + +// SecurityGroupsClientUpdateTagsOptions contains the optional parameters for the SecurityGroupsClient.UpdateTags method. +type SecurityGroupsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// SecurityPartnerProvidersClientBeginCreateOrUpdateOptions contains the optional parameters for the SecurityPartnerProvidersClient.BeginCreateOrUpdate +// method. +type SecurityPartnerProvidersClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SecurityPartnerProvidersClientBeginDeleteOptions contains the optional parameters for the SecurityPartnerProvidersClient.BeginDelete +// method. +type SecurityPartnerProvidersClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SecurityPartnerProvidersClientGetOptions contains the optional parameters for the SecurityPartnerProvidersClient.Get method. +type SecurityPartnerProvidersClientGetOptions struct { + // placeholder for future optional parameters +} + +// SecurityPartnerProvidersClientListByResourceGroupOptions contains the optional parameters for the SecurityPartnerProvidersClient.NewListByResourceGroupPager +// method. +type SecurityPartnerProvidersClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// SecurityPartnerProvidersClientListOptions contains the optional parameters for the SecurityPartnerProvidersClient.NewListPager +// method. +type SecurityPartnerProvidersClientListOptions struct { + // placeholder for future optional parameters +} + +// SecurityPartnerProvidersClientUpdateTagsOptions contains the optional parameters for the SecurityPartnerProvidersClient.UpdateTags +// method. +type SecurityPartnerProvidersClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// SecurityRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the SecurityRulesClient.BeginCreateOrUpdate +// method. +type SecurityRulesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SecurityRulesClientBeginDeleteOptions contains the optional parameters for the SecurityRulesClient.BeginDelete method. +type SecurityRulesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SecurityRulesClientGetOptions contains the optional parameters for the SecurityRulesClient.Get method. +type SecurityRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// SecurityRulesClientListOptions contains the optional parameters for the SecurityRulesClient.NewListPager method. +type SecurityRulesClientListOptions struct { + // placeholder for future optional parameters +} + +// ServiceAssociationLinksClientListOptions contains the optional parameters for the ServiceAssociationLinksClient.List method. +type ServiceAssociationLinksClientListOptions struct { + // placeholder for future optional parameters +} + +// ServiceEndpointPoliciesClientBeginCreateOrUpdateOptions contains the optional parameters for the ServiceEndpointPoliciesClient.BeginCreateOrUpdate +// method. +type ServiceEndpointPoliciesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ServiceEndpointPoliciesClientBeginDeleteOptions contains the optional parameters for the ServiceEndpointPoliciesClient.BeginDelete +// method. +type ServiceEndpointPoliciesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ServiceEndpointPoliciesClientGetOptions contains the optional parameters for the ServiceEndpointPoliciesClient.Get method. +type ServiceEndpointPoliciesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// ServiceEndpointPoliciesClientListByResourceGroupOptions contains the optional parameters for the ServiceEndpointPoliciesClient.NewListByResourceGroupPager +// method. +type ServiceEndpointPoliciesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ServiceEndpointPoliciesClientListOptions contains the optional parameters for the ServiceEndpointPoliciesClient.NewListPager +// method. +type ServiceEndpointPoliciesClientListOptions struct { + // placeholder for future optional parameters +} + +// ServiceEndpointPoliciesClientUpdateTagsOptions contains the optional parameters for the ServiceEndpointPoliciesClient.UpdateTags +// method. +type ServiceEndpointPoliciesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// ServiceEndpointPolicyDefinitionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.BeginCreateOrUpdate +// method. +type ServiceEndpointPolicyDefinitionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ServiceEndpointPolicyDefinitionsClientBeginDeleteOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.BeginDelete +// method. +type ServiceEndpointPolicyDefinitionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ServiceEndpointPolicyDefinitionsClientGetOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.Get +// method. +type ServiceEndpointPolicyDefinitionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ServiceEndpointPolicyDefinitionsClientListByResourceGroupOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.NewListByResourceGroupPager +// method. +type ServiceEndpointPolicyDefinitionsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ServiceTagInformationClientListOptions contains the optional parameters for the ServiceTagInformationClient.NewListPager +// method. +type ServiceTagInformationClientListOptions struct { + // Do not return address prefixes for the tag(s). + NoAddressPrefixes *bool + + // Return tag information for a particular tag. + TagName *string +} + +// ServiceTagsClientListOptions contains the optional parameters for the ServiceTagsClient.List method. +type ServiceTagsClientListOptions struct { + // placeholder for future optional parameters +} + +// StaticMembersClientCreateOrUpdateOptions contains the optional parameters for the StaticMembersClient.CreateOrUpdate method. +type StaticMembersClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// StaticMembersClientDeleteOptions contains the optional parameters for the StaticMembersClient.Delete method. +type StaticMembersClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// StaticMembersClientGetOptions contains the optional parameters for the StaticMembersClient.Get method. +type StaticMembersClientGetOptions struct { + // placeholder for future optional parameters +} + +// StaticMembersClientListOptions contains the optional parameters for the StaticMembersClient.NewListPager method. +type StaticMembersClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// SubnetsClientBeginCreateOrUpdateOptions contains the optional parameters for the SubnetsClient.BeginCreateOrUpdate method. +type SubnetsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SubnetsClientBeginDeleteOptions contains the optional parameters for the SubnetsClient.BeginDelete method. +type SubnetsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SubnetsClientBeginPrepareNetworkPoliciesOptions contains the optional parameters for the SubnetsClient.BeginPrepareNetworkPolicies +// method. +type SubnetsClientBeginPrepareNetworkPoliciesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SubnetsClientBeginUnprepareNetworkPoliciesOptions contains the optional parameters for the SubnetsClient.BeginUnprepareNetworkPolicies +// method. +type SubnetsClientBeginUnprepareNetworkPoliciesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// SubnetsClientGetOptions contains the optional parameters for the SubnetsClient.Get method. +type SubnetsClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// SubnetsClientListOptions contains the optional parameters for the SubnetsClient.NewListPager method. +type SubnetsClientListOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionNetworkManagerConnectionsClientCreateOrUpdateOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.CreateOrUpdate +// method. +type SubscriptionNetworkManagerConnectionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionNetworkManagerConnectionsClientDeleteOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.Delete +// method. +type SubscriptionNetworkManagerConnectionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionNetworkManagerConnectionsClientGetOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.Get +// method. +type SubscriptionNetworkManagerConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionNetworkManagerConnectionsClientListOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.NewListPager +// method. +type SubscriptionNetworkManagerConnectionsClientListOptions struct { + // SkipToken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, + // the value of the nextLink element will include a skipToken parameter that + // specifies a starting point to use for subsequent calls. + SkipToken *string + + // An optional query parameter which specifies the maximum number of records to be returned by the server. + Top *int32 +} + +// UsagesClientListOptions contains the optional parameters for the UsagesClient.NewListPager method. +type UsagesClientListOptions struct { + // placeholder for future optional parameters +} + +// VPNConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNConnectionsClient.BeginCreateOrUpdate +// method. +type VPNConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNConnectionsClientBeginDeleteOptions contains the optional parameters for the VPNConnectionsClient.BeginDelete method. +type VPNConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNConnectionsClientBeginStartPacketCaptureOptions contains the optional parameters for the VPNConnectionsClient.BeginStartPacketCapture +// method. +type VPNConnectionsClientBeginStartPacketCaptureOptions struct { + // Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. + Parameters *VPNConnectionPacketCaptureStartParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNConnectionsClientBeginStopPacketCaptureOptions contains the optional parameters for the VPNConnectionsClient.BeginStopPacketCapture +// method. +type VPNConnectionsClientBeginStopPacketCaptureOptions struct { + // Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. + Parameters *VPNConnectionPacketCaptureStopParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNConnectionsClientGetOptions contains the optional parameters for the VPNConnectionsClient.Get method. +type VPNConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VPNConnectionsClientListByVPNGatewayOptions contains the optional parameters for the VPNConnectionsClient.NewListByVPNGatewayPager +// method. +type VPNConnectionsClientListByVPNGatewayOptions struct { + // placeholder for future optional parameters +} + +// VPNGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNGatewaysClient.BeginCreateOrUpdate +// method. +type VPNGatewaysClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNGatewaysClientBeginDeleteOptions contains the optional parameters for the VPNGatewaysClient.BeginDelete method. +type VPNGatewaysClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNGatewaysClientBeginResetOptions contains the optional parameters for the VPNGatewaysClient.BeginReset method. +type VPNGatewaysClientBeginResetOptions struct { + // VpnGateway ipConfigurationId to specify the gateway instance. + IPConfigurationID *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNGatewaysClientBeginStartPacketCaptureOptions contains the optional parameters for the VPNGatewaysClient.BeginStartPacketCapture +// method. +type VPNGatewaysClientBeginStartPacketCaptureOptions struct { + // Vpn gateway packet capture parameters supplied to start packet capture on vpn gateway. + Parameters *VPNGatewayPacketCaptureStartParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNGatewaysClientBeginStopPacketCaptureOptions contains the optional parameters for the VPNGatewaysClient.BeginStopPacketCapture +// method. +type VPNGatewaysClientBeginStopPacketCaptureOptions struct { + // Vpn gateway packet capture parameters supplied to stop packet capture on vpn gateway. + Parameters *VPNGatewayPacketCaptureStopParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the VPNGatewaysClient.BeginUpdateTags method. +type VPNGatewaysClientBeginUpdateTagsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNGatewaysClientGetOptions contains the optional parameters for the VPNGatewaysClient.Get method. +type VPNGatewaysClientGetOptions struct { + // placeholder for future optional parameters +} + +// VPNGatewaysClientListByResourceGroupOptions contains the optional parameters for the VPNGatewaysClient.NewListByResourceGroupPager +// method. +type VPNGatewaysClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VPNGatewaysClientListOptions contains the optional parameters for the VPNGatewaysClient.NewListPager method. +type VPNGatewaysClientListOptions struct { + // placeholder for future optional parameters +} + +// VPNLinkConnectionsClientBeginGetIkeSasOptions contains the optional parameters for the VPNLinkConnectionsClient.BeginGetIkeSas +// method. +type VPNLinkConnectionsClientBeginGetIkeSasOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNLinkConnectionsClientBeginResetConnectionOptions contains the optional parameters for the VPNLinkConnectionsClient.BeginResetConnection +// method. +type VPNLinkConnectionsClientBeginResetConnectionOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNLinkConnectionsClientListByVPNConnectionOptions contains the optional parameters for the VPNLinkConnectionsClient.NewListByVPNConnectionPager +// method. +type VPNLinkConnectionsClientListByVPNConnectionOptions struct { + // placeholder for future optional parameters +} + +// VPNServerConfigurationsAssociatedWithVirtualWanClientBeginListOptions contains the optional parameters for the VPNServerConfigurationsAssociatedWithVirtualWanClient.BeginList +// method. +type VPNServerConfigurationsAssociatedWithVirtualWanClientBeginListOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNServerConfigurationsClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNServerConfigurationsClient.BeginCreateOrUpdate +// method. +type VPNServerConfigurationsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNServerConfigurationsClientBeginDeleteOptions contains the optional parameters for the VPNServerConfigurationsClient.BeginDelete +// method. +type VPNServerConfigurationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNServerConfigurationsClientGetOptions contains the optional parameters for the VPNServerConfigurationsClient.Get method. +type VPNServerConfigurationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VPNServerConfigurationsClientListByResourceGroupOptions contains the optional parameters for the VPNServerConfigurationsClient.NewListByResourceGroupPager +// method. +type VPNServerConfigurationsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VPNServerConfigurationsClientListOptions contains the optional parameters for the VPNServerConfigurationsClient.NewListPager +// method. +type VPNServerConfigurationsClientListOptions struct { + // placeholder for future optional parameters +} + +// VPNServerConfigurationsClientUpdateTagsOptions contains the optional parameters for the VPNServerConfigurationsClient.UpdateTags +// method. +type VPNServerConfigurationsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// VPNSiteLinkConnectionsClientGetOptions contains the optional parameters for the VPNSiteLinkConnectionsClient.Get method. +type VPNSiteLinkConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VPNSiteLinksClientGetOptions contains the optional parameters for the VPNSiteLinksClient.Get method. +type VPNSiteLinksClientGetOptions struct { + // placeholder for future optional parameters +} + +// VPNSiteLinksClientListByVPNSiteOptions contains the optional parameters for the VPNSiteLinksClient.NewListByVPNSitePager +// method. +type VPNSiteLinksClientListByVPNSiteOptions struct { + // placeholder for future optional parameters +} + +// VPNSitesClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNSitesClient.BeginCreateOrUpdate method. +type VPNSitesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNSitesClientBeginDeleteOptions contains the optional parameters for the VPNSitesClient.BeginDelete method. +type VPNSitesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VPNSitesClientGetOptions contains the optional parameters for the VPNSitesClient.Get method. +type VPNSitesClientGetOptions struct { + // placeholder for future optional parameters +} + +// VPNSitesClientListByResourceGroupOptions contains the optional parameters for the VPNSitesClient.NewListByResourceGroupPager +// method. +type VPNSitesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VPNSitesClientListOptions contains the optional parameters for the VPNSitesClient.NewListPager method. +type VPNSitesClientListOptions struct { + // placeholder for future optional parameters +} + +// VPNSitesClientUpdateTagsOptions contains the optional parameters for the VPNSitesClient.UpdateTags method. +type VPNSitesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// VPNSitesConfigurationClientBeginDownloadOptions contains the optional parameters for the VPNSitesConfigurationClient.BeginDownload +// method. +type VPNSitesConfigurationClientBeginDownloadOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VipSwapClientBeginCreateOptions contains the optional parameters for the VipSwapClient.BeginCreate method. +type VipSwapClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VipSwapClientGetOptions contains the optional parameters for the VipSwapClient.Get method. +type VipSwapClientGetOptions struct { + // placeholder for future optional parameters +} + +// VipSwapClientListOptions contains the optional parameters for the VipSwapClient.List method. +type VipSwapClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualApplianceConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualApplianceConnectionsClient.BeginCreateOrUpdate +// method. +type VirtualApplianceConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualApplianceConnectionsClientBeginDeleteOptions contains the optional parameters for the VirtualApplianceConnectionsClient.BeginDelete +// method. +type VirtualApplianceConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualApplianceConnectionsClientGetOptions contains the optional parameters for the VirtualApplianceConnectionsClient.Get +// method. +type VirtualApplianceConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualApplianceConnectionsClientListOptions contains the optional parameters for the VirtualApplianceConnectionsClient.NewListPager +// method. +type VirtualApplianceConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualApplianceSKUsClientGetOptions contains the optional parameters for the VirtualApplianceSKUsClient.Get method. +type VirtualApplianceSKUsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualApplianceSKUsClientListOptions contains the optional parameters for the VirtualApplianceSKUsClient.NewListPager +// method. +type VirtualApplianceSKUsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualApplianceSitesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualApplianceSitesClient.BeginCreateOrUpdate +// method. +type VirtualApplianceSitesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualApplianceSitesClientBeginDeleteOptions contains the optional parameters for the VirtualApplianceSitesClient.BeginDelete +// method. +type VirtualApplianceSitesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualApplianceSitesClientGetOptions contains the optional parameters for the VirtualApplianceSitesClient.Get method. +type VirtualApplianceSitesClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualApplianceSitesClientListOptions contains the optional parameters for the VirtualApplianceSitesClient.NewListPager +// method. +type VirtualApplianceSitesClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualAppliancesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualAppliancesClient.BeginCreateOrUpdate +// method. +type VirtualAppliancesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualAppliancesClientBeginDeleteOptions contains the optional parameters for the VirtualAppliancesClient.BeginDelete +// method. +type VirtualAppliancesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualAppliancesClientGetOptions contains the optional parameters for the VirtualAppliancesClient.Get method. +type VirtualAppliancesClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// VirtualAppliancesClientListByResourceGroupOptions contains the optional parameters for the VirtualAppliancesClient.NewListByResourceGroupPager +// method. +type VirtualAppliancesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VirtualAppliancesClientListOptions contains the optional parameters for the VirtualAppliancesClient.NewListPager method. +type VirtualAppliancesClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualAppliancesClientUpdateTagsOptions contains the optional parameters for the VirtualAppliancesClient.UpdateTags method. +type VirtualAppliancesClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubBgpConnectionClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubBgpConnectionClient.BeginCreateOrUpdate +// method. +type VirtualHubBgpConnectionClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubBgpConnectionClientBeginDeleteOptions contains the optional parameters for the VirtualHubBgpConnectionClient.BeginDelete +// method. +type VirtualHubBgpConnectionClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubBgpConnectionClientGetOptions contains the optional parameters for the VirtualHubBgpConnectionClient.Get method. +type VirtualHubBgpConnectionClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubBgpConnectionsClientBeginListAdvertisedRoutesOptions contains the optional parameters for the VirtualHubBgpConnectionsClient.BeginListAdvertisedRoutes +// method. +type VirtualHubBgpConnectionsClientBeginListAdvertisedRoutesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubBgpConnectionsClientBeginListLearnedRoutesOptions contains the optional parameters for the VirtualHubBgpConnectionsClient.BeginListLearnedRoutes +// method. +type VirtualHubBgpConnectionsClientBeginListLearnedRoutesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubBgpConnectionsClientListOptions contains the optional parameters for the VirtualHubBgpConnectionsClient.NewListPager +// method. +type VirtualHubBgpConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubIPConfigurationClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubIPConfigurationClient.BeginCreateOrUpdate +// method. +type VirtualHubIPConfigurationClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubIPConfigurationClientBeginDeleteOptions contains the optional parameters for the VirtualHubIPConfigurationClient.BeginDelete +// method. +type VirtualHubIPConfigurationClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubIPConfigurationClientGetOptions contains the optional parameters for the VirtualHubIPConfigurationClient.Get +// method. +type VirtualHubIPConfigurationClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubIPConfigurationClientListOptions contains the optional parameters for the VirtualHubIPConfigurationClient.NewListPager +// method. +type VirtualHubIPConfigurationClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubRouteTableV2SClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.BeginCreateOrUpdate +// method. +type VirtualHubRouteTableV2SClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubRouteTableV2SClientBeginDeleteOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.BeginDelete +// method. +type VirtualHubRouteTableV2SClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubRouteTableV2SClientGetOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.Get method. +type VirtualHubRouteTableV2SClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubRouteTableV2SClientListOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.NewListPager +// method. +type VirtualHubRouteTableV2SClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubsClient.BeginCreateOrUpdate +// method. +type VirtualHubsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubsClientBeginDeleteOptions contains the optional parameters for the VirtualHubsClient.BeginDelete method. +type VirtualHubsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubsClientBeginGetEffectiveVirtualHubRoutesOptions contains the optional parameters for the VirtualHubsClient.BeginGetEffectiveVirtualHubRoutes +// method. +type VirtualHubsClientBeginGetEffectiveVirtualHubRoutesOptions struct { + // Parameters supplied to get the effective routes for a specific resource. + EffectiveRoutesParameters *EffectiveRoutesParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubsClientBeginGetInboundRoutesOptions contains the optional parameters for the VirtualHubsClient.BeginGetInboundRoutes +// method. +type VirtualHubsClientBeginGetInboundRoutesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubsClientBeginGetOutboundRoutesOptions contains the optional parameters for the VirtualHubsClient.BeginGetOutboundRoutes +// method. +type VirtualHubsClientBeginGetOutboundRoutesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualHubsClientGetOptions contains the optional parameters for the VirtualHubsClient.Get method. +type VirtualHubsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubsClientListByResourceGroupOptions contains the optional parameters for the VirtualHubsClient.NewListByResourceGroupPager +// method. +type VirtualHubsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubsClientListOptions contains the optional parameters for the VirtualHubsClient.NewListPager method. +type VirtualHubsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualHubsClientUpdateTagsOptions contains the optional parameters for the VirtualHubsClient.UpdateTags method. +type VirtualHubsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewayConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginCreateOrUpdate +// method. +type VirtualNetworkGatewayConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginDelete +// method. +type VirtualNetworkGatewayConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginGetIkeSasOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginGetIkeSas +// method. +type VirtualNetworkGatewayConnectionsClientBeginGetIkeSasOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginResetConnectionOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginResetConnection +// method. +type VirtualNetworkGatewayConnectionsClientBeginResetConnectionOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginResetSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginResetSharedKey +// method. +type VirtualNetworkGatewayConnectionsClientBeginResetSharedKeyOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginSetSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginSetSharedKey +// method. +type VirtualNetworkGatewayConnectionsClientBeginSetSharedKeyOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginStartPacketCaptureOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginStartPacketCapture +// method. +type VirtualNetworkGatewayConnectionsClientBeginStartPacketCaptureOptions struct { + // Virtual network gateway packet capture parameters supplied to start packet capture on gateway connection. + Parameters *VPNPacketCaptureStartParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginStopPacketCaptureOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginStopPacketCapture +// method. +type VirtualNetworkGatewayConnectionsClientBeginStopPacketCaptureOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientBeginUpdateTagsOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginUpdateTags +// method. +type VirtualNetworkGatewayConnectionsClientBeginUpdateTagsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayConnectionsClientGetOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.Get +// method. +type VirtualNetworkGatewayConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewayConnectionsClientGetSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.GetSharedKey +// method. +type VirtualNetworkGatewayConnectionsClientGetSharedKeyOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewayConnectionsClientListOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.NewListPager +// method. +type VirtualNetworkGatewayConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewayNatRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkGatewayNatRulesClient.BeginCreateOrUpdate +// method. +type VirtualNetworkGatewayNatRulesClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayNatRulesClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkGatewayNatRulesClient.BeginDelete +// method. +type VirtualNetworkGatewayNatRulesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewayNatRulesClientGetOptions contains the optional parameters for the VirtualNetworkGatewayNatRulesClient.Get +// method. +type VirtualNetworkGatewayNatRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayOptions contains the optional parameters for the VirtualNetworkGatewayNatRulesClient.NewListByVirtualNetworkGatewayPager +// method. +type VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginCreateOrUpdate +// method. +type VirtualNetworkGatewaysClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginDelete +// method. +type VirtualNetworkGatewaysClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginDisconnectVirtualNetworkGatewayVPNConnectionsOptions contains the optional parameters +// for the VirtualNetworkGatewaysClient.BeginDisconnectVirtualNetworkGatewayVPNConnections method. +type VirtualNetworkGatewaysClientBeginDisconnectVirtualNetworkGatewayVPNConnectionsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGenerateVPNProfileOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGenerateVPNProfile +// method. +type VirtualNetworkGatewaysClientBeginGenerateVPNProfileOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGeneratevpnclientpackageOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGeneratevpnclientpackage +// method. +type VirtualNetworkGatewaysClientBeginGeneratevpnclientpackageOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGetAdvertisedRoutesOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetAdvertisedRoutes +// method. +type VirtualNetworkGatewaysClientBeginGetAdvertisedRoutesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGetBgpPeerStatusOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetBgpPeerStatus +// method. +type VirtualNetworkGatewaysClientBeginGetBgpPeerStatusOptions struct { + // The IP address of the peer to retrieve the status of. + Peer *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGetLearnedRoutesOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetLearnedRoutes +// method. +type VirtualNetworkGatewaysClientBeginGetLearnedRoutesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGetVPNProfilePackageURLOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetVPNProfilePackageURL +// method. +type VirtualNetworkGatewaysClientBeginGetVPNProfilePackageURLOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGetVpnclientConnectionHealthOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetVpnclientConnectionHealth +// method. +type VirtualNetworkGatewaysClientBeginGetVpnclientConnectionHealthOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginGetVpnclientIPSecParametersOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetVpnclientIPSecParameters +// method. +type VirtualNetworkGatewaysClientBeginGetVpnclientIPSecParametersOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginResetOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginReset +// method. +type VirtualNetworkGatewaysClientBeginResetOptions struct { + // Virtual network gateway vip address supplied to the begin reset of the active-active feature enabled gateway. + GatewayVip *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginResetVPNClientSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginResetVPNClientSharedKey +// method. +type VirtualNetworkGatewaysClientBeginResetVPNClientSharedKeyOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginSetVpnclientIPSecParametersOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginSetVpnclientIPSecParameters +// method. +type VirtualNetworkGatewaysClientBeginSetVpnclientIPSecParametersOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginStartPacketCaptureOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginStartPacketCapture +// method. +type VirtualNetworkGatewaysClientBeginStartPacketCaptureOptions struct { + // Virtual network gateway packet capture parameters supplied to start packet capture on gateway. + Parameters *VPNPacketCaptureStartParameters + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginStopPacketCaptureOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginStopPacketCapture +// method. +type VirtualNetworkGatewaysClientBeginStopPacketCaptureOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginUpdateTags +// method. +type VirtualNetworkGatewaysClientBeginUpdateTagsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkGatewaysClientGetOptions contains the optional parameters for the VirtualNetworkGatewaysClient.Get method. +type VirtualNetworkGatewaysClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewaysClientListConnectionsOptions contains the optional parameters for the VirtualNetworkGatewaysClient.NewListConnectionsPager +// method. +type VirtualNetworkGatewaysClientListConnectionsOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewaysClientListOptions contains the optional parameters for the VirtualNetworkGatewaysClient.NewListPager +// method. +type VirtualNetworkGatewaysClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewaysClientSupportedVPNDevicesOptions contains the optional parameters for the VirtualNetworkGatewaysClient.SupportedVPNDevices +// method. +type VirtualNetworkGatewaysClientSupportedVPNDevicesOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptOptions contains the optional parameters for the VirtualNetworkGatewaysClient.VPNDeviceConfigurationScript +// method. +type VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkPeeringsClient.BeginCreateOrUpdate +// method. +type VirtualNetworkPeeringsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // Parameter indicates the intention to sync the peering with the current address space on the remote vNet after it's updated. + SyncRemoteAddressSpace *SyncRemoteAddressSpace +} + +// VirtualNetworkPeeringsClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkPeeringsClient.BeginDelete +// method. +type VirtualNetworkPeeringsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkPeeringsClientGetOptions contains the optional parameters for the VirtualNetworkPeeringsClient.Get method. +type VirtualNetworkPeeringsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkPeeringsClientListOptions contains the optional parameters for the VirtualNetworkPeeringsClient.NewListPager +// method. +type VirtualNetworkPeeringsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkTapsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkTapsClient.BeginCreateOrUpdate +// method. +type VirtualNetworkTapsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkTapsClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkTapsClient.BeginDelete +// method. +type VirtualNetworkTapsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworkTapsClientGetOptions contains the optional parameters for the VirtualNetworkTapsClient.Get method. +type VirtualNetworkTapsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkTapsClientListAllOptions contains the optional parameters for the VirtualNetworkTapsClient.NewListAllPager +// method. +type VirtualNetworkTapsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkTapsClientListByResourceGroupOptions contains the optional parameters for the VirtualNetworkTapsClient.NewListByResourceGroupPager +// method. +type VirtualNetworkTapsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkTapsClientUpdateTagsOptions contains the optional parameters for the VirtualNetworkTapsClient.UpdateTags +// method. +type VirtualNetworkTapsClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworksClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworksClient.BeginCreateOrUpdate +// method. +type VirtualNetworksClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworksClientBeginDeleteOptions contains the optional parameters for the VirtualNetworksClient.BeginDelete method. +type VirtualNetworksClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualNetworksClientBeginListDdosProtectionStatusOptions contains the optional parameters for the VirtualNetworksClient.BeginListDdosProtectionStatus +// method. +type VirtualNetworksClientBeginListDdosProtectionStatusOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string + + // The skipToken that is given with nextLink. + SkipToken *string + + // The max number of ip addresses to return. + Top *int32 +} + +// VirtualNetworksClientCheckIPAddressAvailabilityOptions contains the optional parameters for the VirtualNetworksClient.CheckIPAddressAvailability +// method. +type VirtualNetworksClientCheckIPAddressAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworksClientGetOptions contains the optional parameters for the VirtualNetworksClient.Get method. +type VirtualNetworksClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// VirtualNetworksClientListAllOptions contains the optional parameters for the VirtualNetworksClient.NewListAllPager method. +type VirtualNetworksClientListAllOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworksClientListOptions contains the optional parameters for the VirtualNetworksClient.NewListPager method. +type VirtualNetworksClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworksClientListUsageOptions contains the optional parameters for the VirtualNetworksClient.NewListUsagePager +// method. +type VirtualNetworksClientListUsageOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworksClientUpdateTagsOptions contains the optional parameters for the VirtualNetworksClient.UpdateTags method. +type VirtualNetworksClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// VirtualRouterPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualRouterPeeringsClient.BeginCreateOrUpdate +// method. +type VirtualRouterPeeringsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualRouterPeeringsClientBeginDeleteOptions contains the optional parameters for the VirtualRouterPeeringsClient.BeginDelete +// method. +type VirtualRouterPeeringsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualRouterPeeringsClientGetOptions contains the optional parameters for the VirtualRouterPeeringsClient.Get method. +type VirtualRouterPeeringsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualRouterPeeringsClientListOptions contains the optional parameters for the VirtualRouterPeeringsClient.NewListPager +// method. +type VirtualRouterPeeringsClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualRoutersClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualRoutersClient.BeginCreateOrUpdate +// method. +type VirtualRoutersClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualRoutersClientBeginDeleteOptions contains the optional parameters for the VirtualRoutersClient.BeginDelete method. +type VirtualRoutersClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualRoutersClientGetOptions contains the optional parameters for the VirtualRoutersClient.Get method. +type VirtualRoutersClientGetOptions struct { + // Expands referenced resources. + Expand *string +} + +// VirtualRoutersClientListByResourceGroupOptions contains the optional parameters for the VirtualRoutersClient.NewListByResourceGroupPager +// method. +type VirtualRoutersClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VirtualRoutersClientListOptions contains the optional parameters for the VirtualRoutersClient.NewListPager method. +type VirtualRoutersClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualWansClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualWansClient.BeginCreateOrUpdate +// method. +type VirtualWansClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualWansClientBeginDeleteOptions contains the optional parameters for the VirtualWansClient.BeginDelete method. +type VirtualWansClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VirtualWansClientGetOptions contains the optional parameters for the VirtualWansClient.Get method. +type VirtualWansClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualWansClientListByResourceGroupOptions contains the optional parameters for the VirtualWansClient.NewListByResourceGroupPager +// method. +type VirtualWansClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// VirtualWansClientListOptions contains the optional parameters for the VirtualWansClient.NewListPager method. +type VirtualWansClientListOptions struct { + // placeholder for future optional parameters +} + +// VirtualWansClientUpdateTagsOptions contains the optional parameters for the VirtualWansClient.UpdateTags method. +type VirtualWansClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientBeginCheckConnectivityOptions contains the optional parameters for the WatchersClient.BeginCheckConnectivity +// method. +type WatchersClientBeginCheckConnectivityOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginDeleteOptions contains the optional parameters for the WatchersClient.BeginDelete method. +type WatchersClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginGetAzureReachabilityReportOptions contains the optional parameters for the WatchersClient.BeginGetAzureReachabilityReport +// method. +type WatchersClientBeginGetAzureReachabilityReportOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginGetFlowLogStatusOptions contains the optional parameters for the WatchersClient.BeginGetFlowLogStatus +// method. +type WatchersClientBeginGetFlowLogStatusOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginGetNetworkConfigurationDiagnosticOptions contains the optional parameters for the WatchersClient.BeginGetNetworkConfigurationDiagnostic +// method. +type WatchersClientBeginGetNetworkConfigurationDiagnosticOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginGetNextHopOptions contains the optional parameters for the WatchersClient.BeginGetNextHop method. +type WatchersClientBeginGetNextHopOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginGetTroubleshootingOptions contains the optional parameters for the WatchersClient.BeginGetTroubleshooting +// method. +type WatchersClientBeginGetTroubleshootingOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginGetTroubleshootingResultOptions contains the optional parameters for the WatchersClient.BeginGetTroubleshootingResult +// method. +type WatchersClientBeginGetTroubleshootingResultOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginGetVMSecurityRulesOptions contains the optional parameters for the WatchersClient.BeginGetVMSecurityRules +// method. +type WatchersClientBeginGetVMSecurityRulesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginListAvailableProvidersOptions contains the optional parameters for the WatchersClient.BeginListAvailableProviders +// method. +type WatchersClientBeginListAvailableProvidersOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginSetFlowLogConfigurationOptions contains the optional parameters for the WatchersClient.BeginSetFlowLogConfiguration +// method. +type WatchersClientBeginSetFlowLogConfigurationOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientBeginVerifyIPFlowOptions contains the optional parameters for the WatchersClient.BeginVerifyIPFlow method. +type WatchersClientBeginVerifyIPFlowOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WatchersClientCreateOrUpdateOptions contains the optional parameters for the WatchersClient.CreateOrUpdate method. +type WatchersClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientGetOptions contains the optional parameters for the WatchersClient.Get method. +type WatchersClientGetOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientGetTopologyOptions contains the optional parameters for the WatchersClient.GetTopology method. +type WatchersClientGetTopologyOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientListAllOptions contains the optional parameters for the WatchersClient.NewListAllPager method. +type WatchersClientListAllOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientListOptions contains the optional parameters for the WatchersClient.NewListPager method. +type WatchersClientListOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientUpdateTagsOptions contains the optional parameters for the WatchersClient.UpdateTags method. +type WatchersClientUpdateTagsOptions struct { + // placeholder for future optional parameters +} + +// WebApplicationFirewallPoliciesClientBeginDeleteOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.BeginDelete +// method. +type WebApplicationFirewallPoliciesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WebApplicationFirewallPoliciesClientCreateOrUpdateOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.CreateOrUpdate +// method. +type WebApplicationFirewallPoliciesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// WebApplicationFirewallPoliciesClientGetOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.Get +// method. +type WebApplicationFirewallPoliciesClientGetOptions struct { + // placeholder for future optional parameters +} + +// WebApplicationFirewallPoliciesClientListAllOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.NewListAllPager +// method. +type WebApplicationFirewallPoliciesClientListAllOptions struct { + // placeholder for future optional parameters +} + +// WebApplicationFirewallPoliciesClientListOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.NewListPager +// method. +type WebApplicationFirewallPoliciesClientListOptions struct { + // placeholder for future optional parameters +} + +// WebCategoriesClientGetOptions contains the optional parameters for the WebCategoriesClient.Get method. +type WebCategoriesClientGetOptions struct { + // Expands resourceIds back referenced by the azureWebCategory resource. + Expand *string +} + +// WebCategoriesClientListBySubscriptionOptions contains the optional parameters for the WebCategoriesClient.NewListBySubscriptionPager +// method. +type WebCategoriesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/p2svpngateways_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/p2svpngateways_client.go new file mode 100644 index 000000000..112e1e5c9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/p2svpngateways_client.go @@ -0,0 +1,865 @@ +//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 armnetwork + +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" +) + +// P2SVPNGatewaysClient contains the methods for the P2SVPNGateways group. +// Don't use this type directly, use NewP2SVPNGatewaysClient() instead. +type P2SVPNGatewaysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewP2SVPNGatewaysClient creates a new instance of P2SVPNGatewaysClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewP2SVPNGatewaysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*P2SVPNGatewaysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &P2SVPNGatewaysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a virtual wan p2s vpn gateway if it doesn't exist else updates the existing gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the P2SVpnGateway. +// - gatewayName - The name of the gateway. +// - p2SVPNGatewayParameters - Parameters supplied to create or Update a virtual wan p2s vpn gateway. +// - options - P2SVPNGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginCreateOrUpdate +// method. +func (client *P2SVPNGatewaysClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, p2SVPNGatewayParameters P2SVPNGateway, options *P2SVPNGatewaysClientBeginCreateOrUpdateOptions) (*runtime.Poller[P2SVPNGatewaysClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, gatewayName, p2SVPNGatewayParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a virtual wan p2s vpn gateway if it doesn't exist else updates the existing gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) createOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, p2SVPNGatewayParameters P2SVPNGateway, options *P2SVPNGatewaysClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.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, gatewayName, p2SVPNGatewayParameters, 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 *P2SVPNGatewaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, p2SVPNGatewayParameters P2SVPNGateway, options *P2SVPNGatewaysClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, p2SVPNGatewayParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a virtual wan p2s vpn gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the P2SVpnGateway. +// - gatewayName - The name of the gateway. +// - options - P2SVPNGatewaysClientBeginDeleteOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginDelete +// method. +func (client *P2SVPNGatewaysClient) BeginDelete(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginDeleteOptions) (*runtime.Poller[P2SVPNGatewaysClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, gatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a virtual wan p2s vpn gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) deleteOperation(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.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, gatewayName, 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 *P2SVPNGatewaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDisconnectP2SVPNConnections - Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - p2SVPNGatewayName - The name of the P2S Vpn Gateway. +// - request - The parameters are supplied to disconnect p2s vpn connections. +// - options - P2SVPNGatewaysClientBeginDisconnectP2SVPNConnectionsOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginDisconnectP2SVPNConnections +// method. +func (client *P2SVPNGatewaysClient) BeginDisconnectP2SVPNConnections(ctx context.Context, resourceGroupName string, p2SVPNGatewayName string, request P2SVPNConnectionRequest, options *P2SVPNGatewaysClientBeginDisconnectP2SVPNConnectionsOptions) (*runtime.Poller[P2SVPNGatewaysClientDisconnectP2SVPNConnectionsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.disconnectP2SVPNConnections(ctx, resourceGroupName, p2SVPNGatewayName, request, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientDisconnectP2SVPNConnectionsResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientDisconnectP2SVPNConnectionsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DisconnectP2SVPNConnections - Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) disconnectP2SVPNConnections(ctx context.Context, resourceGroupName string, p2SVPNGatewayName string, request P2SVPNConnectionRequest, options *P2SVPNGatewaysClientBeginDisconnectP2SVPNConnectionsOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.BeginDisconnectP2SVPNConnections" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disconnectP2SVPNConnectionsCreateRequest(ctx, resourceGroupName, p2SVPNGatewayName, request, 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 +} + +// disconnectP2SVPNConnectionsCreateRequest creates the DisconnectP2SVPNConnections request. +func (client *P2SVPNGatewaysClient) disconnectP2SVPNConnectionsCreateRequest(ctx context.Context, resourceGroupName string, p2SVPNGatewayName string, request P2SVPNConnectionRequest, options *P2SVPNGatewaysClientBeginDisconnectP2SVPNConnectionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{p2sVpnGatewayName}/disconnectP2sVpnConnections" + 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 p2SVPNGatewayName == "" { + return nil, errors.New("parameter p2SVPNGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{p2sVpnGatewayName}", url.PathEscape(p2SVPNGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, request); err != nil { + return nil, err + } + return req, nil +} + +// BeginGenerateVPNProfile - Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - gatewayName - The name of the P2SVpnGateway. +// - parameters - Parameters supplied to the generate P2SVpnGateway VPN client package operation. +// - options - P2SVPNGatewaysClientBeginGenerateVPNProfileOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginGenerateVPNProfile +// method. +func (client *P2SVPNGatewaysClient) BeginGenerateVPNProfile(ctx context.Context, resourceGroupName string, gatewayName string, parameters P2SVPNProfileParameters, options *P2SVPNGatewaysClientBeginGenerateVPNProfileOptions) (*runtime.Poller[P2SVPNGatewaysClientGenerateVPNProfileResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.generateVPNProfile(ctx, resourceGroupName, gatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientGenerateVPNProfileResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientGenerateVPNProfileResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GenerateVPNProfile - Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) generateVPNProfile(ctx context.Context, resourceGroupName string, gatewayName string, parameters P2SVPNProfileParameters, options *P2SVPNGatewaysClientBeginGenerateVPNProfileOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.BeginGenerateVPNProfile" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generateVPNProfileCreateRequest(ctx, resourceGroupName, gatewayName, 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 +} + +// generateVPNProfileCreateRequest creates the GenerateVPNProfile request. +func (client *P2SVPNGatewaysClient) generateVPNProfileCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, parameters P2SVPNProfileParameters, options *P2SVPNGatewaysClientBeginGenerateVPNProfileOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/generatevpnprofile" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-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 +} + +// Get - Retrieves the details of a virtual wan p2s vpn gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the P2SVpnGateway. +// - gatewayName - The name of the gateway. +// - options - P2SVPNGatewaysClientGetOptions contains the optional parameters for the P2SVPNGatewaysClient.Get method. +func (client *P2SVPNGatewaysClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientGetOptions) (P2SVPNGatewaysClientGetResponse, error) { + var err error + const operationName = "P2SVPNGatewaysClient.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, gatewayName, options) + if err != nil { + return P2SVPNGatewaysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return P2SVPNGatewaysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return P2SVPNGatewaysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *P2SVPNGatewaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *P2SVPNGatewaysClient) getHandleResponse(resp *http.Response) (P2SVPNGatewaysClientGetResponse, error) { + result := P2SVPNGatewaysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.P2SVPNGateway); err != nil { + return P2SVPNGatewaysClientGetResponse{}, err + } + return result, nil +} + +// BeginGetP2SVPNConnectionHealth - Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified +// resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - gatewayName - The name of the P2SVpnGateway. +// - options - P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealth +// method. +func (client *P2SVPNGatewaysClient) BeginGetP2SVPNConnectionHealth(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthOptions) (*runtime.Poller[P2SVPNGatewaysClientGetP2SVPNConnectionHealthResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getP2SVPNConnectionHealth(ctx, resourceGroupName, gatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientGetP2SVPNConnectionHealthResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientGetP2SVPNConnectionHealthResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetP2SVPNConnectionHealth - Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified +// resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) getP2SVPNConnectionHealth(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealth" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getP2SVPNConnectionHealthCreateRequest(ctx, resourceGroupName, gatewayName, 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 +} + +// getP2SVPNConnectionHealthCreateRequest creates the GetP2SVPNConnectionHealth request. +func (client *P2SVPNGatewaysClient) getP2SVPNConnectionHealthCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealth" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginGetP2SVPNConnectionHealthDetailed - Gets the sas url to get the connection health detail of P2S clients of the virtual +// wan P2SVpnGateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - gatewayName - The name of the P2SVpnGateway. +// - request - Request parameters supplied to get p2s vpn connections detailed health. +// - options - P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthDetailedOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealthDetailed +// method. +func (client *P2SVPNGatewaysClient) BeginGetP2SVPNConnectionHealthDetailed(ctx context.Context, resourceGroupName string, gatewayName string, request P2SVPNConnectionHealthRequest, options *P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthDetailedOptions) (*runtime.Poller[P2SVPNGatewaysClientGetP2SVPNConnectionHealthDetailedResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getP2SVPNConnectionHealthDetailed(ctx, resourceGroupName, gatewayName, request, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientGetP2SVPNConnectionHealthDetailedResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientGetP2SVPNConnectionHealthDetailedResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetP2SVPNConnectionHealthDetailed - Gets the sas url to get the connection health detail of P2S clients of the virtual +// wan P2SVpnGateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) getP2SVPNConnectionHealthDetailed(ctx context.Context, resourceGroupName string, gatewayName string, request P2SVPNConnectionHealthRequest, options *P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthDetailedOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealthDetailed" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getP2SVPNConnectionHealthDetailedCreateRequest(ctx, resourceGroupName, gatewayName, request, 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 +} + +// getP2SVPNConnectionHealthDetailedCreateRequest creates the GetP2SVPNConnectionHealthDetailed request. +func (client *P2SVPNGatewaysClient) getP2SVPNConnectionHealthDetailedCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, request P2SVPNConnectionHealthRequest, options *P2SVPNGatewaysClientBeginGetP2SVPNConnectionHealthDetailedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealthDetailed" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, request); err != nil { + return nil, err + } + return req, nil +} + +// NewListPager - Lists all the P2SVpnGateways in a subscription. +// +// Generated from API version 2023-05-01 +// - options - P2SVPNGatewaysClientListOptions contains the optional parameters for the P2SVPNGatewaysClient.NewListPager method. +func (client *P2SVPNGatewaysClient) NewListPager(options *P2SVPNGatewaysClientListOptions) *runtime.Pager[P2SVPNGatewaysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[P2SVPNGatewaysClientListResponse]{ + More: func(page P2SVPNGatewaysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *P2SVPNGatewaysClientListResponse) (P2SVPNGatewaysClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "P2SVPNGatewaysClient.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 P2SVPNGatewaysClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *P2SVPNGatewaysClient) listCreateRequest(ctx context.Context, options *P2SVPNGatewaysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/p2svpnGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *P2SVPNGatewaysClient) listHandleResponse(resp *http.Response) (P2SVPNGatewaysClientListResponse, error) { + result := P2SVPNGatewaysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListP2SVPNGatewaysResult); err != nil { + return P2SVPNGatewaysClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the P2SVpnGateways in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the P2SVpnGateway. +// - options - P2SVPNGatewaysClientListByResourceGroupOptions contains the optional parameters for the P2SVPNGatewaysClient.NewListByResourceGroupPager +// method. +func (client *P2SVPNGatewaysClient) NewListByResourceGroupPager(resourceGroupName string, options *P2SVPNGatewaysClientListByResourceGroupOptions) *runtime.Pager[P2SVPNGatewaysClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[P2SVPNGatewaysClientListByResourceGroupResponse]{ + More: func(page P2SVPNGatewaysClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *P2SVPNGatewaysClientListByResourceGroupResponse) (P2SVPNGatewaysClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "P2SVPNGatewaysClient.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 P2SVPNGatewaysClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *P2SVPNGatewaysClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *P2SVPNGatewaysClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *P2SVPNGatewaysClient) listByResourceGroupHandleResponse(resp *http.Response) (P2SVPNGatewaysClientListByResourceGroupResponse, error) { + result := P2SVPNGatewaysClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListP2SVPNGatewaysResult); err != nil { + return P2SVPNGatewaysClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginReset - Resets the primary of the p2s vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the P2SVpnGateway. +// - gatewayName - The name of the gateway. +// - options - P2SVPNGatewaysClientBeginResetOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginReset +// method. +func (client *P2SVPNGatewaysClient) BeginReset(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginResetOptions) (*runtime.Poller[P2SVPNGatewaysClientResetResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reset(ctx, resourceGroupName, gatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientResetResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientResetResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reset - Resets the primary of the p2s vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) reset(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginResetOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.BeginReset" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetCreateRequest(ctx, resourceGroupName, gatewayName, 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 +} + +// resetCreateRequest creates the Reset request. +func (client *P2SVPNGatewaysClient) resetCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *P2SVPNGatewaysClientBeginResetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/reset" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdateTags - Updates virtual wan p2s vpn gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the P2SVpnGateway. +// - gatewayName - The name of the gateway. +// - p2SVPNGatewayParameters - Parameters supplied to update a virtual wan p2s vpn gateway tags. +// - options - P2SVPNGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the P2SVPNGatewaysClient.BeginUpdateTags +// method. +func (client *P2SVPNGatewaysClient) BeginUpdateTags(ctx context.Context, resourceGroupName string, gatewayName string, p2SVPNGatewayParameters TagsObject, options *P2SVPNGatewaysClientBeginUpdateTagsOptions) (*runtime.Poller[P2SVPNGatewaysClientUpdateTagsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateTags(ctx, resourceGroupName, gatewayName, p2SVPNGatewayParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[P2SVPNGatewaysClientUpdateTagsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[P2SVPNGatewaysClientUpdateTagsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateTags - Updates virtual wan p2s vpn gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *P2SVPNGatewaysClient) updateTags(ctx context.Context, resourceGroupName string, gatewayName string, p2SVPNGatewayParameters TagsObject, options *P2SVPNGatewaysClientBeginUpdateTagsOptions) (*http.Response, error) { + var err error + const operationName = "P2SVPNGatewaysClient.BeginUpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, gatewayName, p2SVPNGatewayParameters, 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 +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *P2SVPNGatewaysClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, p2SVPNGatewayParameters TagsObject, options *P2SVPNGatewaysClientBeginUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, p2SVPNGatewayParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/packetcaptures_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/packetcaptures_client.go new file mode 100644 index 000000000..3b19453fb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/packetcaptures_client.go @@ -0,0 +1,511 @@ +//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 armnetwork + +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" +) + +// PacketCapturesClient contains the methods for the PacketCaptures group. +// Don't use this type directly, use NewPacketCapturesClient() instead. +type PacketCapturesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPacketCapturesClient creates a new instance of PacketCapturesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewPacketCapturesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PacketCapturesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PacketCapturesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create and start a packet capture on the specified VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - packetCaptureName - The name of the packet capture session. +// - parameters - Parameters that define the create packet capture operation. +// - options - PacketCapturesClientBeginCreateOptions contains the optional parameters for the PacketCapturesClient.BeginCreate +// method. +func (client *PacketCapturesClient) BeginCreate(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture, options *PacketCapturesClientBeginCreateOptions) (*runtime.Poller[PacketCapturesClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, networkWatcherName, packetCaptureName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PacketCapturesClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PacketCapturesClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create and start a packet capture on the specified VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PacketCapturesClient) create(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture, options *PacketCapturesClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "PacketCapturesClient.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, networkWatcherName, packetCaptureName, 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.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *PacketCapturesClient) createCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture, options *PacketCapturesClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if packetCaptureName == "" { + return nil, errors.New("parameter packetCaptureName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{packetCaptureName}", url.PathEscape(packetCaptureName)) + 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-05-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 packet capture session. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - packetCaptureName - The name of the packet capture session. +// - options - PacketCapturesClientBeginDeleteOptions contains the optional parameters for the PacketCapturesClient.BeginDelete +// method. +func (client *PacketCapturesClient) BeginDelete(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginDeleteOptions) (*runtime.Poller[PacketCapturesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkWatcherName, packetCaptureName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PacketCapturesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PacketCapturesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified packet capture session. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PacketCapturesClient) deleteOperation(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PacketCapturesClient.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, networkWatcherName, packetCaptureName, 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 *PacketCapturesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if packetCaptureName == "" { + return nil, errors.New("parameter packetCaptureName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{packetCaptureName}", url.PathEscape(packetCaptureName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets a packet capture session by name. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - packetCaptureName - The name of the packet capture session. +// - options - PacketCapturesClientGetOptions contains the optional parameters for the PacketCapturesClient.Get method. +func (client *PacketCapturesClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientGetOptions) (PacketCapturesClientGetResponse, error) { + var err error + const operationName = "PacketCapturesClient.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, networkWatcherName, packetCaptureName, options) + if err != nil { + return PacketCapturesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PacketCapturesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PacketCapturesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PacketCapturesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if packetCaptureName == "" { + return nil, errors.New("parameter packetCaptureName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{packetCaptureName}", url.PathEscape(packetCaptureName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PacketCapturesClient) getHandleResponse(resp *http.Response) (PacketCapturesClientGetResponse, error) { + result := PacketCapturesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PacketCaptureResult); err != nil { + return PacketCapturesClientGetResponse{}, err + } + return result, nil +} + +// BeginGetStatus - Query the status of a running packet capture session. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the Network Watcher resource. +// - packetCaptureName - The name given to the packet capture session. +// - options - PacketCapturesClientBeginGetStatusOptions contains the optional parameters for the PacketCapturesClient.BeginGetStatus +// method. +func (client *PacketCapturesClient) BeginGetStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginGetStatusOptions) (*runtime.Poller[PacketCapturesClientGetStatusResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getStatus(ctx, resourceGroupName, networkWatcherName, packetCaptureName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PacketCapturesClientGetStatusResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PacketCapturesClientGetStatusResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetStatus - Query the status of a running packet capture session. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PacketCapturesClient) getStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginGetStatusOptions) (*http.Response, error) { + var err error + const operationName = "PacketCapturesClient.BeginGetStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStatusCreateRequest(ctx, resourceGroupName, networkWatcherName, packetCaptureName, 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 +} + +// getStatusCreateRequest creates the GetStatus request. +func (client *PacketCapturesClient) getStatusCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginGetStatusOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if packetCaptureName == "" { + return nil, errors.New("parameter packetCaptureName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{packetCaptureName}", url.PathEscape(packetCaptureName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// NewListPager - Lists all packet capture sessions within the specified resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the Network Watcher resource. +// - options - PacketCapturesClientListOptions contains the optional parameters for the PacketCapturesClient.NewListPager method. +func (client *PacketCapturesClient) NewListPager(resourceGroupName string, networkWatcherName string, options *PacketCapturesClientListOptions) *runtime.Pager[PacketCapturesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PacketCapturesClientListResponse]{ + More: func(page PacketCapturesClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *PacketCapturesClientListResponse) (PacketCapturesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PacketCapturesClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, networkWatcherName, options) + if err != nil { + return PacketCapturesClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PacketCapturesClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PacketCapturesClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PacketCapturesClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, options *PacketCapturesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PacketCapturesClient) listHandleResponse(resp *http.Response) (PacketCapturesClientListResponse, error) { + result := PacketCapturesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PacketCaptureListResult); err != nil { + return PacketCapturesClientListResponse{}, err + } + return result, nil +} + +// BeginStop - Stops a specified packet capture session. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - packetCaptureName - The name of the packet capture session. +// - options - PacketCapturesClientBeginStopOptions contains the optional parameters for the PacketCapturesClient.BeginStop +// method. +func (client *PacketCapturesClient) BeginStop(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginStopOptions) (*runtime.Poller[PacketCapturesClientStopResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stop(ctx, resourceGroupName, networkWatcherName, packetCaptureName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PacketCapturesClientStopResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PacketCapturesClientStopResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Stop - Stops a specified packet capture session. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PacketCapturesClient) stop(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginStopOptions) (*http.Response, error) { + var err error + const operationName = "PacketCapturesClient.BeginStop" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopCreateRequest(ctx, resourceGroupName, networkWatcherName, packetCaptureName, 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 +} + +// stopCreateRequest creates the Stop request. +func (client *PacketCapturesClient) stopCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, options *PacketCapturesClientBeginStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + if packetCaptureName == "" { + return nil, errors.New("parameter packetCaptureName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{packetCaptureName}", url.PathEscape(packetCaptureName)) + 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-05-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/network/armnetwork/v4/peerexpressroutecircuitconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/peerexpressroutecircuitconnections_client.go new file mode 100644 index 000000000..d8a87d68c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/peerexpressroutecircuitconnections_client.go @@ -0,0 +1,190 @@ +//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 armnetwork + +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" +) + +// PeerExpressRouteCircuitConnectionsClient contains the methods for the PeerExpressRouteCircuitConnections group. +// Don't use this type directly, use NewPeerExpressRouteCircuitConnectionsClient() instead. +type PeerExpressRouteCircuitConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPeerExpressRouteCircuitConnectionsClient creates a new instance of PeerExpressRouteCircuitConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewPeerExpressRouteCircuitConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PeerExpressRouteCircuitConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PeerExpressRouteCircuitConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the specified Peer Express Route Circuit Connection from the specified express route circuit. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the express route circuit. +// - peeringName - The name of the peering. +// - connectionName - The name of the peer express route circuit connection. +// - options - PeerExpressRouteCircuitConnectionsClientGetOptions contains the optional parameters for the PeerExpressRouteCircuitConnectionsClient.Get +// method. +func (client *PeerExpressRouteCircuitConnectionsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, options *PeerExpressRouteCircuitConnectionsClientGetOptions) (PeerExpressRouteCircuitConnectionsClientGetResponse, error) { + var err error + const operationName = "PeerExpressRouteCircuitConnectionsClient.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, circuitName, peeringName, connectionName, options) + if err != nil { + return PeerExpressRouteCircuitConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PeerExpressRouteCircuitConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PeerExpressRouteCircuitConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PeerExpressRouteCircuitConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, options *PeerExpressRouteCircuitConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/peerConnections/{connectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PeerExpressRouteCircuitConnectionsClient) getHandleResponse(resp *http.Response) (PeerExpressRouteCircuitConnectionsClientGetResponse, error) { + result := PeerExpressRouteCircuitConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PeerExpressRouteCircuitConnection); err != nil { + return PeerExpressRouteCircuitConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all global reach peer connections associated with a private peering in an express route circuit. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - circuitName - The name of the circuit. +// - peeringName - The name of the peering. +// - options - PeerExpressRouteCircuitConnectionsClientListOptions contains the optional parameters for the PeerExpressRouteCircuitConnectionsClient.NewListPager +// method. +func (client *PeerExpressRouteCircuitConnectionsClient) NewListPager(resourceGroupName string, circuitName string, peeringName string, options *PeerExpressRouteCircuitConnectionsClientListOptions) *runtime.Pager[PeerExpressRouteCircuitConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PeerExpressRouteCircuitConnectionsClientListResponse]{ + More: func(page PeerExpressRouteCircuitConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PeerExpressRouteCircuitConnectionsClientListResponse) (PeerExpressRouteCircuitConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PeerExpressRouteCircuitConnectionsClient.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, circuitName, peeringName, options) + }, nil) + if err != nil { + return PeerExpressRouteCircuitConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PeerExpressRouteCircuitConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, options *PeerExpressRouteCircuitConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/peerConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if circuitName == "" { + return nil, errors.New("parameter circuitName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{circuitName}", url.PathEscape(circuitName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PeerExpressRouteCircuitConnectionsClient) listHandleResponse(resp *http.Response) (PeerExpressRouteCircuitConnectionsClientListResponse, error) { + result := PeerExpressRouteCircuitConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PeerExpressRouteCircuitConnectionListResult); err != nil { + return PeerExpressRouteCircuitConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/polymorphic_helpers.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/polymorphic_helpers.go new file mode 100644 index 000000000..0f6cd182a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/polymorphic_helpers.go @@ -0,0 +1,223 @@ +//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 armnetwork + +import "encoding/json" + +func unmarshalActiveBaseSecurityAdminRuleClassification(rawMsg json.RawMessage) (ActiveBaseSecurityAdminRuleClassification, 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 ActiveBaseSecurityAdminRuleClassification + switch m["kind"] { + case string(EffectiveAdminRuleKindCustom): + b = &ActiveSecurityAdminRule{} + case string(EffectiveAdminRuleKindDefault): + b = &ActiveDefaultSecurityAdminRule{} + default: + b = &ActiveBaseSecurityAdminRule{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalActiveBaseSecurityAdminRuleClassificationArray(rawMsg json.RawMessage) ([]ActiveBaseSecurityAdminRuleClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ActiveBaseSecurityAdminRuleClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalActiveBaseSecurityAdminRuleClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalBaseAdminRuleClassification(rawMsg json.RawMessage) (BaseAdminRuleClassification, 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 BaseAdminRuleClassification + switch m["kind"] { + case string(AdminRuleKindCustom): + b = &AdminRule{} + case string(AdminRuleKindDefault): + b = &DefaultAdminRule{} + default: + b = &BaseAdminRule{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalBaseAdminRuleClassificationArray(rawMsg json.RawMessage) ([]BaseAdminRuleClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]BaseAdminRuleClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalBaseAdminRuleClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalEffectiveBaseSecurityAdminRuleClassification(rawMsg json.RawMessage) (EffectiveBaseSecurityAdminRuleClassification, 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 EffectiveBaseSecurityAdminRuleClassification + switch m["kind"] { + case string(EffectiveAdminRuleKindCustom): + b = &EffectiveSecurityAdminRule{} + case string(EffectiveAdminRuleKindDefault): + b = &EffectiveDefaultSecurityAdminRule{} + default: + b = &EffectiveBaseSecurityAdminRule{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalEffectiveBaseSecurityAdminRuleClassificationArray(rawMsg json.RawMessage) ([]EffectiveBaseSecurityAdminRuleClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]EffectiveBaseSecurityAdminRuleClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalEffectiveBaseSecurityAdminRuleClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalFirewallPolicyRuleClassification(rawMsg json.RawMessage) (FirewallPolicyRuleClassification, 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 FirewallPolicyRuleClassification + switch m["ruleType"] { + case string(FirewallPolicyRuleTypeApplicationRule): + b = &ApplicationRule{} + case string(FirewallPolicyRuleTypeNatRule): + b = &NatRule{} + case string(FirewallPolicyRuleTypeNetworkRule): + b = &Rule{} + default: + b = &FirewallPolicyRule{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalFirewallPolicyRuleClassificationArray(rawMsg json.RawMessage) ([]FirewallPolicyRuleClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]FirewallPolicyRuleClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalFirewallPolicyRuleClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalFirewallPolicyRuleCollectionClassification(rawMsg json.RawMessage) (FirewallPolicyRuleCollectionClassification, 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 FirewallPolicyRuleCollectionClassification + switch m["ruleCollectionType"] { + case string(FirewallPolicyRuleCollectionTypeFirewallPolicyFilterRuleCollection): + b = &FirewallPolicyFilterRuleCollection{} + case string(FirewallPolicyRuleCollectionTypeFirewallPolicyNatRuleCollection): + b = &FirewallPolicyNatRuleCollection{} + default: + b = &FirewallPolicyRuleCollection{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalFirewallPolicyRuleCollectionClassificationArray(rawMsg json.RawMessage) ([]FirewallPolicyRuleCollectionClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]FirewallPolicyRuleCollectionClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalFirewallPolicyRuleCollectionClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privatednszonegroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privatednszonegroups_client.go new file mode 100644 index 000000000..e4177612b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privatednszonegroups_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// PrivateDNSZoneGroupsClient contains the methods for the PrivateDNSZoneGroups group. +// Don't use this type directly, use NewPrivateDNSZoneGroupsClient() instead. +type PrivateDNSZoneGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateDNSZoneGroupsClient creates a new instance of PrivateDNSZoneGroupsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewPrivateDNSZoneGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateDNSZoneGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateDNSZoneGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a private dns zone group in the specified private endpoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - privateEndpointName - The name of the private endpoint. +// - privateDNSZoneGroupName - The name of the private dns zone group. +// - parameters - Parameters supplied to the create or update private dns zone group operation. +// - options - PrivateDNSZoneGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.BeginCreateOrUpdate +// method. +func (client *PrivateDNSZoneGroupsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, parameters PrivateDNSZoneGroup, options *PrivateDNSZoneGroupsClientBeginCreateOrUpdateOptions) (*runtime.Poller[PrivateDNSZoneGroupsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, privateEndpointName, privateDNSZoneGroupName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateDNSZoneGroupsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateDNSZoneGroupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a private dns zone group in the specified private endpoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateDNSZoneGroupsClient) createOrUpdate(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, parameters PrivateDNSZoneGroup, options *PrivateDNSZoneGroupsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PrivateDNSZoneGroupsClient.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, privateEndpointName, privateDNSZoneGroupName, 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 *PrivateDNSZoneGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, parameters PrivateDNSZoneGroup, options *PrivateDNSZoneGroupsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + if privateDNSZoneGroupName == "" { + return nil, errors.New("parameter privateDNSZoneGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateDnsZoneGroupName}", url.PathEscape(privateDNSZoneGroupName)) + 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-05-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 private dns zone group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - privateEndpointName - The name of the private endpoint. +// - privateDNSZoneGroupName - The name of the private dns zone group. +// - options - PrivateDNSZoneGroupsClientBeginDeleteOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.BeginDelete +// method. +func (client *PrivateDNSZoneGroupsClient) BeginDelete(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientBeginDeleteOptions) (*runtime.Poller[PrivateDNSZoneGroupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, privateEndpointName, privateDNSZoneGroupName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateDNSZoneGroupsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateDNSZoneGroupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified private dns zone group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateDNSZoneGroupsClient) deleteOperation(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PrivateDNSZoneGroupsClient.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, privateEndpointName, privateDNSZoneGroupName, 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 *PrivateDNSZoneGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + if privateDNSZoneGroupName == "" { + return nil, errors.New("parameter privateDNSZoneGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateDnsZoneGroupName}", url.PathEscape(privateDNSZoneGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the private dns zone group resource by specified private dns zone group name. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - privateEndpointName - The name of the private endpoint. +// - privateDNSZoneGroupName - The name of the private dns zone group. +// - options - PrivateDNSZoneGroupsClientGetOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.Get +// method. +func (client *PrivateDNSZoneGroupsClient) Get(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientGetOptions) (PrivateDNSZoneGroupsClientGetResponse, error) { + var err error + const operationName = "PrivateDNSZoneGroupsClient.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, privateEndpointName, privateDNSZoneGroupName, options) + if err != nil { + return PrivateDNSZoneGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateDNSZoneGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateDNSZoneGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateDNSZoneGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + if privateDNSZoneGroupName == "" { + return nil, errors.New("parameter privateDNSZoneGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateDnsZoneGroupName}", url.PathEscape(privateDNSZoneGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateDNSZoneGroupsClient) getHandleResponse(resp *http.Response) (PrivateDNSZoneGroupsClientGetResponse, error) { + result := PrivateDNSZoneGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateDNSZoneGroup); err != nil { + return PrivateDNSZoneGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all private dns zone groups in a private endpoint. +// +// Generated from API version 2023-05-01 +// - privateEndpointName - The name of the private endpoint. +// - resourceGroupName - The name of the resource group. +// - options - PrivateDNSZoneGroupsClientListOptions contains the optional parameters for the PrivateDNSZoneGroupsClient.NewListPager +// method. +func (client *PrivateDNSZoneGroupsClient) NewListPager(privateEndpointName string, resourceGroupName string, options *PrivateDNSZoneGroupsClientListOptions) *runtime.Pager[PrivateDNSZoneGroupsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateDNSZoneGroupsClientListResponse]{ + More: func(page PrivateDNSZoneGroupsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateDNSZoneGroupsClientListResponse) (PrivateDNSZoneGroupsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateDNSZoneGroupsClient.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, privateEndpointName, resourceGroupName, options) + }, nil) + if err != nil { + return PrivateDNSZoneGroupsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PrivateDNSZoneGroupsClient) listCreateRequest(ctx context.Context, privateEndpointName string, resourceGroupName string, options *PrivateDNSZoneGroupsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups" + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateDNSZoneGroupsClient) listHandleResponse(resp *http.Response) (PrivateDNSZoneGroupsClientListResponse, error) { + result := PrivateDNSZoneGroupsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateDNSZoneGroupListResult); err != nil { + return PrivateDNSZoneGroupsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privateendpoints_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privateendpoints_client.go new file mode 100644 index 000000000..496153f08 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privateendpoints_client.go @@ -0,0 +1,385 @@ +//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 armnetwork + +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" +) + +// PrivateEndpointsClient contains the methods for the PrivateEndpoints group. +// Don't use this type directly, use NewPrivateEndpointsClient() instead. +type PrivateEndpointsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateEndpointsClient creates a new instance of PrivateEndpointsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewPrivateEndpointsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateEndpointsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateEndpointsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an private endpoint in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - privateEndpointName - The name of the private endpoint. +// - parameters - Parameters supplied to the create or update private endpoint operation. +// - options - PrivateEndpointsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointsClient.BeginCreateOrUpdate +// method. +func (client *PrivateEndpointsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, privateEndpointName string, parameters PrivateEndpoint, options *PrivateEndpointsClientBeginCreateOrUpdateOptions) (*runtime.Poller[PrivateEndpointsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, privateEndpointName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an private endpoint in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateEndpointsClient) createOrUpdate(ctx context.Context, resourceGroupName string, privateEndpointName string, parameters PrivateEndpoint, options *PrivateEndpointsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointsClient.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, privateEndpointName, 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 *PrivateEndpointsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, parameters PrivateEndpoint, options *PrivateEndpointsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + 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-05-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 private endpoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - privateEndpointName - The name of the private endpoint. +// - options - PrivateEndpointsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointsClient.BeginDelete +// method. +func (client *PrivateEndpointsClient) BeginDelete(ctx context.Context, resourceGroupName string, privateEndpointName string, options *PrivateEndpointsClientBeginDeleteOptions) (*runtime.Poller[PrivateEndpointsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, privateEndpointName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified private endpoint. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateEndpointsClient) deleteOperation(ctx context.Context, resourceGroupName string, privateEndpointName string, options *PrivateEndpointsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointsClient.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, privateEndpointName, 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 *PrivateEndpointsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, options *PrivateEndpointsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified private endpoint by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - privateEndpointName - The name of the private endpoint. +// - options - PrivateEndpointsClientGetOptions contains the optional parameters for the PrivateEndpointsClient.Get method. +func (client *PrivateEndpointsClient) Get(ctx context.Context, resourceGroupName string, privateEndpointName string, options *PrivateEndpointsClientGetOptions) (PrivateEndpointsClientGetResponse, error) { + var err error + const operationName = "PrivateEndpointsClient.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, privateEndpointName, options) + if err != nil { + return PrivateEndpointsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointsClient) getCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, options *PrivateEndpointsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointsClient) getHandleResponse(resp *http.Response) (PrivateEndpointsClientGetResponse, error) { + result := PrivateEndpointsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpoint); err != nil { + return PrivateEndpointsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all private endpoints in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - PrivateEndpointsClientListOptions contains the optional parameters for the PrivateEndpointsClient.NewListPager +// method. +func (client *PrivateEndpointsClient) NewListPager(resourceGroupName string, options *PrivateEndpointsClientListOptions) *runtime.Pager[PrivateEndpointsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateEndpointsClientListResponse]{ + More: func(page PrivateEndpointsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateEndpointsClientListResponse) (PrivateEndpointsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateEndpointsClient.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, options) + }, nil) + if err != nil { + return PrivateEndpointsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PrivateEndpointsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *PrivateEndpointsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateEndpointsClient) listHandleResponse(resp *http.Response) (PrivateEndpointsClientListResponse, error) { + result := PrivateEndpointsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointListResult); err != nil { + return PrivateEndpointsClientListResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Gets all private endpoints in a subscription. +// +// Generated from API version 2023-05-01 +// - options - PrivateEndpointsClientListBySubscriptionOptions contains the optional parameters for the PrivateEndpointsClient.NewListBySubscriptionPager +// method. +func (client *PrivateEndpointsClient) NewListBySubscriptionPager(options *PrivateEndpointsClientListBySubscriptionOptions) *runtime.Pager[PrivateEndpointsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateEndpointsClientListBySubscriptionResponse]{ + More: func(page PrivateEndpointsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateEndpointsClientListBySubscriptionResponse) (PrivateEndpointsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateEndpointsClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return PrivateEndpointsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *PrivateEndpointsClient) listBySubscriptionCreateRequest(ctx context.Context, options *PrivateEndpointsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/privateEndpoints" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *PrivateEndpointsClient) listBySubscriptionHandleResponse(resp *http.Response) (PrivateEndpointsClientListBySubscriptionResponse, error) { + result := PrivateEndpointsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointListResult); err != nil { + return PrivateEndpointsClientListBySubscriptionResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privatelinkservices_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privatelinkservices_client.go new file mode 100644 index 000000000..703fda2d2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/privatelinkservices_client.go @@ -0,0 +1,966 @@ +//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 armnetwork + +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" +) + +// PrivateLinkServicesClient contains the methods for the PrivateLinkServices group. +// Don't use this type directly, use NewPrivateLinkServicesClient() instead. +type PrivateLinkServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateLinkServicesClient creates a new instance of PrivateLinkServicesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewPrivateLinkServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateLinkServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateLinkServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCheckPrivateLinkServiceVisibility - Checks whether the subscription is visible to private link service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - parameters - The request body of CheckPrivateLinkService API call. +// - options - PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityOptions contains the optional parameters for the +// PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibility method. +func (client *PrivateLinkServicesClient) BeginCheckPrivateLinkServiceVisibility(ctx context.Context, location string, parameters CheckPrivateLinkServiceVisibilityRequest, options *PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityOptions) (*runtime.Poller[PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.checkPrivateLinkServiceVisibility(ctx, location, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CheckPrivateLinkServiceVisibility - Checks whether the subscription is visible to private link service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateLinkServicesClient) checkPrivateLinkServiceVisibility(ctx context.Context, location string, parameters CheckPrivateLinkServiceVisibilityRequest, options *PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityOptions) (*http.Response, error) { + var err error + const operationName = "PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibility" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkPrivateLinkServiceVisibilityCreateRequest(ctx, location, 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 +} + +// checkPrivateLinkServiceVisibilityCreateRequest creates the CheckPrivateLinkServiceVisibility request. +func (client *PrivateLinkServicesClient) checkPrivateLinkServiceVisibilityCreateRequest(ctx context.Context, location string, parameters CheckPrivateLinkServiceVisibilityRequest, options *PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility" + 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-05-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 +} + +// BeginCheckPrivateLinkServiceVisibilityByResourceGroup - Checks whether the subscription is visible to private link service +// in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - resourceGroupName - The name of the resource group. +// - parameters - The request body of CheckPrivateLinkService API call. +// - options - PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityByResourceGroupOptions contains the optional parameters +// for the PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibilityByResourceGroup method. +func (client *PrivateLinkServicesClient) BeginCheckPrivateLinkServiceVisibilityByResourceGroup(ctx context.Context, location string, resourceGroupName string, parameters CheckPrivateLinkServiceVisibilityRequest, options *PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityByResourceGroupOptions) (*runtime.Poller[PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityByResourceGroupResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.checkPrivateLinkServiceVisibilityByResourceGroup(ctx, location, resourceGroupName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityByResourceGroupResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityByResourceGroupResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CheckPrivateLinkServiceVisibilityByResourceGroup - Checks whether the subscription is visible to private link service in +// the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateLinkServicesClient) checkPrivateLinkServiceVisibilityByResourceGroup(ctx context.Context, location string, resourceGroupName string, parameters CheckPrivateLinkServiceVisibilityRequest, options *PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityByResourceGroupOptions) (*http.Response, error) { + var err error + const operationName = "PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibilityByResourceGroup" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkPrivateLinkServiceVisibilityByResourceGroupCreateRequest(ctx, location, resourceGroupName, 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 +} + +// checkPrivateLinkServiceVisibilityByResourceGroupCreateRequest creates the CheckPrivateLinkServiceVisibilityByResourceGroup request. +func (client *PrivateLinkServicesClient) checkPrivateLinkServiceVisibilityByResourceGroupCreateRequest(ctx context.Context, location string, resourceGroupName string, parameters CheckPrivateLinkServiceVisibilityRequest, options *PrivateLinkServicesClientBeginCheckPrivateLinkServiceVisibilityByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + 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.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-05-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 +} + +// BeginCreateOrUpdate - Creates or updates an private link service in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceName - The name of the private link service. +// - parameters - Parameters supplied to the create or update private link service operation. +// - options - PrivateLinkServicesClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateLinkServicesClient.BeginCreateOrUpdate +// method. +func (client *PrivateLinkServicesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, parameters PrivateLinkService, options *PrivateLinkServicesClientBeginCreateOrUpdateOptions) (*runtime.Poller[PrivateLinkServicesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, serviceName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateLinkServicesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateLinkServicesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an private link service in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateLinkServicesClient) createOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, parameters PrivateLinkService, options *PrivateLinkServicesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PrivateLinkServicesClient.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, serviceName, 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 *PrivateLinkServicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, parameters PrivateLinkService, options *PrivateLinkServicesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + 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-05-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 private link service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceName - The name of the private link service. +// - options - PrivateLinkServicesClientBeginDeleteOptions contains the optional parameters for the PrivateLinkServicesClient.BeginDelete +// method. +func (client *PrivateLinkServicesClient) BeginDelete(ctx context.Context, resourceGroupName string, serviceName string, options *PrivateLinkServicesClientBeginDeleteOptions) (*runtime.Poller[PrivateLinkServicesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, serviceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateLinkServicesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateLinkServicesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified private link service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateLinkServicesClient) deleteOperation(ctx context.Context, resourceGroupName string, serviceName string, options *PrivateLinkServicesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PrivateLinkServicesClient.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, serviceName, 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 *PrivateLinkServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *PrivateLinkServicesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDeletePrivateEndpointConnection - Delete private end point connection for a private link service in a subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceName - The name of the private link service. +// - peConnectionName - The name of the private end point connection. +// - options - PrivateLinkServicesClientBeginDeletePrivateEndpointConnectionOptions contains the optional parameters for the +// PrivateLinkServicesClient.BeginDeletePrivateEndpointConnection method. +func (client *PrivateLinkServicesClient) BeginDeletePrivateEndpointConnection(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, options *PrivateLinkServicesClientBeginDeletePrivateEndpointConnectionOptions) (*runtime.Poller[PrivateLinkServicesClientDeletePrivateEndpointConnectionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deletePrivateEndpointConnection(ctx, resourceGroupName, serviceName, peConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateLinkServicesClientDeletePrivateEndpointConnectionResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateLinkServicesClientDeletePrivateEndpointConnectionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeletePrivateEndpointConnection - Delete private end point connection for a private link service in a subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PrivateLinkServicesClient) deletePrivateEndpointConnection(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, options *PrivateLinkServicesClientBeginDeletePrivateEndpointConnectionOptions) (*http.Response, error) { + var err error + const operationName = "PrivateLinkServicesClient.BeginDeletePrivateEndpointConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deletePrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, serviceName, peConnectionName, 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 +} + +// deletePrivateEndpointConnectionCreateRequest creates the DeletePrivateEndpointConnection request. +func (client *PrivateLinkServicesClient) deletePrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, options *PrivateLinkServicesClientBeginDeletePrivateEndpointConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if peConnectionName == "" { + return nil, errors.New("parameter peConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peConnectionName}", url.PathEscape(peConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified private link service by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceName - The name of the private link service. +// - options - PrivateLinkServicesClientGetOptions contains the optional parameters for the PrivateLinkServicesClient.Get method. +func (client *PrivateLinkServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, options *PrivateLinkServicesClientGetOptions) (PrivateLinkServicesClientGetResponse, error) { + var err error + const operationName = "PrivateLinkServicesClient.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, serviceName, options) + if err != nil { + return PrivateLinkServicesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateLinkServicesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateLinkServicesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateLinkServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *PrivateLinkServicesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *PrivateLinkServicesClient) getHandleResponse(resp *http.Response) (PrivateLinkServicesClientGetResponse, error) { + result := PrivateLinkServicesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkService); err != nil { + return PrivateLinkServicesClientGetResponse{}, err + } + return result, nil +} + +// GetPrivateEndpointConnection - Get the specific private end point connection by specific private link service in the resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceName - The name of the private link service. +// - peConnectionName - The name of the private end point connection. +// - options - PrivateLinkServicesClientGetPrivateEndpointConnectionOptions contains the optional parameters for the PrivateLinkServicesClient.GetPrivateEndpointConnection +// method. +func (client *PrivateLinkServicesClient) GetPrivateEndpointConnection(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, options *PrivateLinkServicesClientGetPrivateEndpointConnectionOptions) (PrivateLinkServicesClientGetPrivateEndpointConnectionResponse, error) { + var err error + const operationName = "PrivateLinkServicesClient.GetPrivateEndpointConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, serviceName, peConnectionName, options) + if err != nil { + return PrivateLinkServicesClientGetPrivateEndpointConnectionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateLinkServicesClientGetPrivateEndpointConnectionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateLinkServicesClientGetPrivateEndpointConnectionResponse{}, err + } + resp, err := client.getPrivateEndpointConnectionHandleResponse(httpResp) + return resp, err +} + +// getPrivateEndpointConnectionCreateRequest creates the GetPrivateEndpointConnection request. +func (client *PrivateLinkServicesClient) getPrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, options *PrivateLinkServicesClientGetPrivateEndpointConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if peConnectionName == "" { + return nil, errors.New("parameter peConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peConnectionName}", url.PathEscape(peConnectionName)) + 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-05-01") + 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 +} + +// getPrivateEndpointConnectionHandleResponse handles the GetPrivateEndpointConnection response. +func (client *PrivateLinkServicesClient) getPrivateEndpointConnectionHandleResponse(resp *http.Response) (PrivateLinkServicesClientGetPrivateEndpointConnectionResponse, error) { + result := PrivateLinkServicesClientGetPrivateEndpointConnectionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateLinkServicesClientGetPrivateEndpointConnectionResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all private link services in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - PrivateLinkServicesClientListOptions contains the optional parameters for the PrivateLinkServicesClient.NewListPager +// method. +func (client *PrivateLinkServicesClient) NewListPager(resourceGroupName string, options *PrivateLinkServicesClientListOptions) *runtime.Pager[PrivateLinkServicesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateLinkServicesClientListResponse]{ + More: func(page PrivateLinkServicesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateLinkServicesClientListResponse) (PrivateLinkServicesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateLinkServicesClient.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, options) + }, nil) + if err != nil { + return PrivateLinkServicesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PrivateLinkServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *PrivateLinkServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateLinkServicesClient) listHandleResponse(resp *http.Response) (PrivateLinkServicesClientListResponse, error) { + result := PrivateLinkServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkServiceListResult); err != nil { + return PrivateLinkServicesClientListResponse{}, err + } + return result, nil +} + +// NewListAutoApprovedPrivateLinkServicesPager - Returns all of the private link service ids that can be linked to a Private +// Endpoint with auto approved in this subscription in this region. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - options - PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesOptions contains the optional parameters for the +// PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesPager method. +func (client *PrivateLinkServicesClient) NewListAutoApprovedPrivateLinkServicesPager(location string, options *PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesOptions) *runtime.Pager[PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse]{ + More: func(page PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse) (PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesPager") + 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.listAutoApprovedPrivateLinkServicesCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse{}, err + } + return client.listAutoApprovedPrivateLinkServicesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAutoApprovedPrivateLinkServicesCreateRequest creates the ListAutoApprovedPrivateLinkServices request. +func (client *PrivateLinkServicesClient) listAutoApprovedPrivateLinkServicesCreateRequest(ctx context.Context, location string, options *PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/autoApprovedPrivateLinkServices" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAutoApprovedPrivateLinkServicesHandleResponse handles the ListAutoApprovedPrivateLinkServices response. +func (client *PrivateLinkServicesClient) listAutoApprovedPrivateLinkServicesHandleResponse(resp *http.Response) (PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse, error) { + result := PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutoApprovedPrivateLinkServicesResult); err != nil { + return PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse{}, err + } + return result, nil +} + +// NewListAutoApprovedPrivateLinkServicesByResourceGroupPager - Returns all of the private link service ids that can be linked +// to a Private Endpoint with auto approved in this subscription in this region. +// +// Generated from API version 2023-05-01 +// - location - The location of the domain name. +// - resourceGroupName - The name of the resource group. +// - options - PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupOptions contains the optional parameters +// for the PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesByResourceGroupPager method. +func (client *PrivateLinkServicesClient) NewListAutoApprovedPrivateLinkServicesByResourceGroupPager(location string, resourceGroupName string, options *PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupOptions) *runtime.Pager[PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse]{ + More: func(page PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse) (PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesByResourceGroupPager") + 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.listAutoApprovedPrivateLinkServicesByResourceGroupCreateRequest(ctx, location, resourceGroupName, options) + }, nil) + if err != nil { + return PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse{}, err + } + return client.listAutoApprovedPrivateLinkServicesByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAutoApprovedPrivateLinkServicesByResourceGroupCreateRequest creates the ListAutoApprovedPrivateLinkServicesByResourceGroup request. +func (client *PrivateLinkServicesClient) listAutoApprovedPrivateLinkServicesByResourceGroupCreateRequest(ctx context.Context, location string, resourceGroupName string, options *PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/autoApprovedPrivateLinkServices" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAutoApprovedPrivateLinkServicesByResourceGroupHandleResponse handles the ListAutoApprovedPrivateLinkServicesByResourceGroup response. +func (client *PrivateLinkServicesClient) listAutoApprovedPrivateLinkServicesByResourceGroupHandleResponse(resp *http.Response) (PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse, error) { + result := PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutoApprovedPrivateLinkServicesResult); err != nil { + return PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Gets all private link service in a subscription. +// +// Generated from API version 2023-05-01 +// - options - PrivateLinkServicesClientListBySubscriptionOptions contains the optional parameters for the PrivateLinkServicesClient.NewListBySubscriptionPager +// method. +func (client *PrivateLinkServicesClient) NewListBySubscriptionPager(options *PrivateLinkServicesClientListBySubscriptionOptions) *runtime.Pager[PrivateLinkServicesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateLinkServicesClientListBySubscriptionResponse]{ + More: func(page PrivateLinkServicesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateLinkServicesClientListBySubscriptionResponse) (PrivateLinkServicesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateLinkServicesClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return PrivateLinkServicesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *PrivateLinkServicesClient) listBySubscriptionCreateRequest(ctx context.Context, options *PrivateLinkServicesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/privateLinkServices" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *PrivateLinkServicesClient) listBySubscriptionHandleResponse(resp *http.Response) (PrivateLinkServicesClientListBySubscriptionResponse, error) { + result := PrivateLinkServicesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkServiceListResult); err != nil { + return PrivateLinkServicesClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// NewListPrivateEndpointConnectionsPager - Gets all private end point connections for a specific private link service. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceName - The name of the private link service. +// - options - PrivateLinkServicesClientListPrivateEndpointConnectionsOptions contains the optional parameters for the PrivateLinkServicesClient.NewListPrivateEndpointConnectionsPager +// method. +func (client *PrivateLinkServicesClient) NewListPrivateEndpointConnectionsPager(resourceGroupName string, serviceName string, options *PrivateLinkServicesClientListPrivateEndpointConnectionsOptions) *runtime.Pager[PrivateLinkServicesClientListPrivateEndpointConnectionsResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateLinkServicesClientListPrivateEndpointConnectionsResponse]{ + More: func(page PrivateLinkServicesClientListPrivateEndpointConnectionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateLinkServicesClientListPrivateEndpointConnectionsResponse) (PrivateLinkServicesClientListPrivateEndpointConnectionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateLinkServicesClient.NewListPrivateEndpointConnectionsPager") + 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.listPrivateEndpointConnectionsCreateRequest(ctx, resourceGroupName, serviceName, options) + }, nil) + if err != nil { + return PrivateLinkServicesClientListPrivateEndpointConnectionsResponse{}, err + } + return client.listPrivateEndpointConnectionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPrivateEndpointConnectionsCreateRequest creates the ListPrivateEndpointConnections request. +func (client *PrivateLinkServicesClient) listPrivateEndpointConnectionsCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *PrivateLinkServicesClientListPrivateEndpointConnectionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPrivateEndpointConnectionsHandleResponse handles the ListPrivateEndpointConnections response. +func (client *PrivateLinkServicesClient) listPrivateEndpointConnectionsHandleResponse(resp *http.Response) (PrivateLinkServicesClientListPrivateEndpointConnectionsResponse, error) { + result := PrivateLinkServicesClientListPrivateEndpointConnectionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateLinkServicesClientListPrivateEndpointConnectionsResponse{}, err + } + return result, nil +} + +// UpdatePrivateEndpointConnection - Approve or reject private end point connection for a private link service in a subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceName - The name of the private link service. +// - peConnectionName - The name of the private end point connection. +// - parameters - Parameters supplied to approve or reject the private end point connection. +// - options - PrivateLinkServicesClientUpdatePrivateEndpointConnectionOptions contains the optional parameters for the PrivateLinkServicesClient.UpdatePrivateEndpointConnection +// method. +func (client *PrivateLinkServicesClient) UpdatePrivateEndpointConnection(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, parameters PrivateEndpointConnection, options *PrivateLinkServicesClientUpdatePrivateEndpointConnectionOptions) (PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse, error) { + var err error + const operationName = "PrivateLinkServicesClient.UpdatePrivateEndpointConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updatePrivateEndpointConnectionCreateRequest(ctx, resourceGroupName, serviceName, peConnectionName, parameters, options) + if err != nil { + return PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse{}, err + } + resp, err := client.updatePrivateEndpointConnectionHandleResponse(httpResp) + return resp, err +} + +// updatePrivateEndpointConnectionCreateRequest creates the UpdatePrivateEndpointConnection request. +func (client *PrivateLinkServicesClient) updatePrivateEndpointConnectionCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, parameters PrivateEndpointConnection, options *PrivateLinkServicesClientUpdatePrivateEndpointConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if peConnectionName == "" { + return nil, errors.New("parameter peConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peConnectionName}", url.PathEscape(peConnectionName)) + 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-05-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 +} + +// updatePrivateEndpointConnectionHandleResponse handles the UpdatePrivateEndpointConnection response. +func (client *PrivateLinkServicesClient) updatePrivateEndpointConnectionHandleResponse(resp *http.Response) (PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse, error) { + result := PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/profiles_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/profiles_client.go new file mode 100644 index 000000000..729f1c036 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/profiles_client.go @@ -0,0 +1,437 @@ +//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 armnetwork + +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" +) + +// ProfilesClient contains the methods for the NetworkProfiles group. +// Don't use this type directly, use NewProfilesClient() instead. +type ProfilesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewProfilesClient creates a new instance of ProfilesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewProfilesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ProfilesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ProfilesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates a network profile. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkProfileName - The name of the network profile. +// - parameters - Parameters supplied to the create or update network profile operation. +// - options - ProfilesClientCreateOrUpdateOptions contains the optional parameters for the ProfilesClient.CreateOrUpdate method. +func (client *ProfilesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkProfileName string, parameters Profile, options *ProfilesClientCreateOrUpdateOptions) (ProfilesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ProfilesClient.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, networkProfileName, parameters, options) + if err != nil { + return ProfilesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProfilesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ProfilesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ProfilesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkProfileName string, parameters Profile, options *ProfilesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkProfileName == "" { + return nil, errors.New("parameter networkProfileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkProfileName}", url.PathEscape(networkProfileName)) + 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-05-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 *ProfilesClient) createOrUpdateHandleResponse(resp *http.Response) (ProfilesClientCreateOrUpdateResponse, error) { + result := ProfilesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Profile); err != nil { + return ProfilesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified network profile. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkProfileName - The name of the NetworkProfile. +// - options - ProfilesClientBeginDeleteOptions contains the optional parameters for the ProfilesClient.BeginDelete method. +func (client *ProfilesClient) BeginDelete(ctx context.Context, resourceGroupName string, networkProfileName string, options *ProfilesClientBeginDeleteOptions) (*runtime.Poller[ProfilesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkProfileName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ProfilesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ProfilesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified network profile. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ProfilesClient) deleteOperation(ctx context.Context, resourceGroupName string, networkProfileName string, options *ProfilesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ProfilesClient.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, networkProfileName, 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 *ProfilesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkProfileName string, options *ProfilesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkProfileName == "" { + return nil, errors.New("parameter networkProfileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkProfileName}", url.PathEscape(networkProfileName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified network profile in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkProfileName - The name of the public IP prefix. +// - options - ProfilesClientGetOptions contains the optional parameters for the ProfilesClient.Get method. +func (client *ProfilesClient) Get(ctx context.Context, resourceGroupName string, networkProfileName string, options *ProfilesClientGetOptions) (ProfilesClientGetResponse, error) { + var err error + const operationName = "ProfilesClient.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, networkProfileName, options) + if err != nil { + return ProfilesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProfilesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProfilesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ProfilesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkProfileName string, options *ProfilesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkProfileName == "" { + return nil, errors.New("parameter networkProfileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkProfileName}", url.PathEscape(networkProfileName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *ProfilesClient) getHandleResponse(resp *http.Response) (ProfilesClientGetResponse, error) { + result := ProfilesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Profile); err != nil { + return ProfilesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all network profiles in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ProfilesClientListOptions contains the optional parameters for the ProfilesClient.NewListPager method. +func (client *ProfilesClient) NewListPager(resourceGroupName string, options *ProfilesClientListOptions) *runtime.Pager[ProfilesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ProfilesClientListResponse]{ + More: func(page ProfilesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ProfilesClientListResponse) (ProfilesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProfilesClient.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, options) + }, nil) + if err != nil { + return ProfilesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ProfilesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *ProfilesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ProfilesClient) listHandleResponse(resp *http.Response) (ProfilesClientListResponse, error) { + result := ProfilesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProfileListResult); err != nil { + return ProfilesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the network profiles in a subscription. +// +// Generated from API version 2023-05-01 +// - options - ProfilesClientListAllOptions contains the optional parameters for the ProfilesClient.NewListAllPager method. +func (client *ProfilesClient) NewListAllPager(options *ProfilesClientListAllOptions) *runtime.Pager[ProfilesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[ProfilesClientListAllResponse]{ + More: func(page ProfilesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ProfilesClientListAllResponse) (ProfilesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProfilesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return ProfilesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *ProfilesClient) listAllCreateRequest(ctx context.Context, options *ProfilesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkProfiles" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *ProfilesClient) listAllHandleResponse(resp *http.Response) (ProfilesClientListAllResponse, error) { + result := ProfilesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProfileListResult); err != nil { + return ProfilesClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates network profile tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkProfileName - The name of the network profile. +// - parameters - Parameters supplied to update network profile tags. +// - options - ProfilesClientUpdateTagsOptions contains the optional parameters for the ProfilesClient.UpdateTags method. +func (client *ProfilesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkProfileName string, parameters TagsObject, options *ProfilesClientUpdateTagsOptions) (ProfilesClientUpdateTagsResponse, error) { + var err error + const operationName = "ProfilesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, networkProfileName, parameters, options) + if err != nil { + return ProfilesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProfilesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProfilesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ProfilesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, networkProfileName string, parameters TagsObject, options *ProfilesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkProfileName == "" { + return nil, errors.New("parameter networkProfileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkProfileName}", url.PathEscape(networkProfileName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ProfilesClient) updateTagsHandleResponse(resp *http.Response) (ProfilesClientUpdateTagsResponse, error) { + result := ProfilesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Profile); err != nil { + return ProfilesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/publicipaddresses_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/publicipaddresses_client.go new file mode 100644 index 000000000..62d60e062 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/publicipaddresses_client.go @@ -0,0 +1,1000 @@ +//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 armnetwork + +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" +) + +// PublicIPAddressesClient contains the methods for the PublicIPAddresses group. +// Don't use this type directly, use NewPublicIPAddressesClient() instead. +type PublicIPAddressesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPublicIPAddressesClient creates a new instance of PublicIPAddressesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewPublicIPAddressesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PublicIPAddressesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PublicIPAddressesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a static or dynamic public IP address. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPAddressName - The name of the public IP address. +// - parameters - Parameters supplied to the create or update public IP address operation. +// - options - PublicIPAddressesClientBeginCreateOrUpdateOptions contains the optional parameters for the PublicIPAddressesClient.BeginCreateOrUpdate +// method. +func (client *PublicIPAddressesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, options *PublicIPAddressesClientBeginCreateOrUpdateOptions) (*runtime.Poller[PublicIPAddressesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, publicIPAddressName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PublicIPAddressesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PublicIPAddressesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a static or dynamic public IP address. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PublicIPAddressesClient) createOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, options *PublicIPAddressesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PublicIPAddressesClient.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, publicIPAddressName, 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 *PublicIPAddressesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, options *PublicIPAddressesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPAddressName == "" { + return nil, errors.New("parameter publicIPAddressName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpAddressName}", url.PathEscape(publicIPAddressName)) + 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-05-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 +} + +// BeginDdosProtectionStatus - Gets the Ddos Protection Status of a Public IP Address +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPAddressName - The name of the public IP address. +// - options - PublicIPAddressesClientBeginDdosProtectionStatusOptions contains the optional parameters for the PublicIPAddressesClient.BeginDdosProtectionStatus +// method. +func (client *PublicIPAddressesClient) BeginDdosProtectionStatus(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientBeginDdosProtectionStatusOptions) (*runtime.Poller[PublicIPAddressesClientDdosProtectionStatusResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.ddosProtectionStatus(ctx, resourceGroupName, publicIPAddressName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PublicIPAddressesClientDdosProtectionStatusResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PublicIPAddressesClientDdosProtectionStatusResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DdosProtectionStatus - Gets the Ddos Protection Status of a Public IP Address +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PublicIPAddressesClient) ddosProtectionStatus(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientBeginDdosProtectionStatusOptions) (*http.Response, error) { + var err error + const operationName = "PublicIPAddressesClient.BeginDdosProtectionStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.ddosProtectionStatusCreateRequest(ctx, resourceGroupName, publicIPAddressName, 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 +} + +// ddosProtectionStatusCreateRequest creates the DdosProtectionStatus request. +func (client *PublicIPAddressesClient) ddosProtectionStatusCreateRequest(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientBeginDdosProtectionStatusOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}/ddosProtectionStatus" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPAddressName == "" { + return nil, errors.New("parameter publicIPAddressName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpAddressName}", url.PathEscape(publicIPAddressName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDelete - Deletes the specified public IP address. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPAddressName - The name of the public IP address. +// - options - PublicIPAddressesClientBeginDeleteOptions contains the optional parameters for the PublicIPAddressesClient.BeginDelete +// method. +func (client *PublicIPAddressesClient) BeginDelete(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientBeginDeleteOptions) (*runtime.Poller[PublicIPAddressesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, publicIPAddressName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PublicIPAddressesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PublicIPAddressesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified public IP address. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PublicIPAddressesClient) deleteOperation(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PublicIPAddressesClient.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, publicIPAddressName, 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 *PublicIPAddressesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPAddressName == "" { + return nil, errors.New("parameter publicIPAddressName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpAddressName}", url.PathEscape(publicIPAddressName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified public IP address in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPAddressName - The name of the public IP address. +// - options - PublicIPAddressesClientGetOptions contains the optional parameters for the PublicIPAddressesClient.Get method. +func (client *PublicIPAddressesClient) Get(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientGetOptions) (PublicIPAddressesClientGetResponse, error) { + var err error + const operationName = "PublicIPAddressesClient.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, publicIPAddressName, options) + if err != nil { + return PublicIPAddressesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PublicIPAddressesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PublicIPAddressesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PublicIPAddressesClient) getCreateRequest(ctx context.Context, resourceGroupName string, publicIPAddressName string, options *PublicIPAddressesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPAddressName == "" { + return nil, errors.New("parameter publicIPAddressName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpAddressName}", url.PathEscape(publicIPAddressName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *PublicIPAddressesClient) getHandleResponse(resp *http.Response) (PublicIPAddressesClientGetResponse, error) { + result := PublicIPAddressesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddress); err != nil { + return PublicIPAddressesClientGetResponse{}, err + } + return result, nil +} + +// GetCloudServicePublicIPAddress - Get the specified public IP address in a cloud service. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - cloudServiceName - The name of the cloud service. +// - roleInstanceName - The role instance name. +// - networkInterfaceName - The name of the network interface. +// - ipConfigurationName - The name of the IP configuration. +// - publicIPAddressName - The name of the public IP Address. +// - options - PublicIPAddressesClientGetCloudServicePublicIPAddressOptions contains the optional parameters for the PublicIPAddressesClient.GetCloudServicePublicIPAddress +// method. +func (client *PublicIPAddressesClient) GetCloudServicePublicIPAddress(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, ipConfigurationName string, publicIPAddressName string, options *PublicIPAddressesClientGetCloudServicePublicIPAddressOptions) (PublicIPAddressesClientGetCloudServicePublicIPAddressResponse, error) { + var err error + const operationName = "PublicIPAddressesClient.GetCloudServicePublicIPAddress" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCloudServicePublicIPAddressCreateRequest(ctx, resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, ipConfigurationName, publicIPAddressName, options) + if err != nil { + return PublicIPAddressesClientGetCloudServicePublicIPAddressResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PublicIPAddressesClientGetCloudServicePublicIPAddressResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PublicIPAddressesClientGetCloudServicePublicIPAddressResponse{}, err + } + resp, err := client.getCloudServicePublicIPAddressHandleResponse(httpResp) + return resp, err +} + +// getCloudServicePublicIPAddressCreateRequest creates the GetCloudServicePublicIPAddress request. +func (client *PublicIPAddressesClient) getCloudServicePublicIPAddressCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, ipConfigurationName string, publicIPAddressName string, options *PublicIPAddressesClientGetCloudServicePublicIPAddressOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses/{publicIpAddressName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if ipConfigurationName == "" { + return nil, errors.New("parameter ipConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigurationName}", url.PathEscape(ipConfigurationName)) + if publicIPAddressName == "" { + return nil, errors.New("parameter publicIPAddressName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpAddressName}", url.PathEscape(publicIPAddressName)) + 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-05-01") + 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 +} + +// getCloudServicePublicIPAddressHandleResponse handles the GetCloudServicePublicIPAddress response. +func (client *PublicIPAddressesClient) getCloudServicePublicIPAddressHandleResponse(resp *http.Response) (PublicIPAddressesClientGetCloudServicePublicIPAddressResponse, error) { + result := PublicIPAddressesClientGetCloudServicePublicIPAddressResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddress); err != nil { + return PublicIPAddressesClientGetCloudServicePublicIPAddressResponse{}, err + } + return result, nil +} + +// GetVirtualMachineScaleSetPublicIPAddress - Get the specified public IP address in a virtual machine scale set. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - virtualmachineIndex - The virtual machine index. +// - networkInterfaceName - The name of the network interface. +// - ipConfigurationName - The name of the IP configuration. +// - publicIPAddressName - The name of the public IP Address. +// - options - PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressOptions contains the optional parameters for the +// PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress method. +func (client *PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, ipConfigurationName string, publicIPAddressName string, options *PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressOptions) (PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse, error) { + var err error + const operationName = "PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getVirtualMachineScaleSetPublicIPAddressCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, publicIPAddressName, options) + if err != nil { + return PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{}, err + } + resp, err := client.getVirtualMachineScaleSetPublicIPAddressHandleResponse(httpResp) + return resp, err +} + +// getVirtualMachineScaleSetPublicIPAddressCreateRequest creates the GetVirtualMachineScaleSetPublicIPAddress request. +func (client *PublicIPAddressesClient) getVirtualMachineScaleSetPublicIPAddressCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, ipConfigurationName string, publicIPAddressName string, options *PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses/{publicIpAddressName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + if virtualmachineIndex == "" { + return nil, errors.New("parameter virtualmachineIndex cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualmachineIndex}", url.PathEscape(virtualmachineIndex)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if ipConfigurationName == "" { + return nil, errors.New("parameter ipConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigurationName}", url.PathEscape(ipConfigurationName)) + if publicIPAddressName == "" { + return nil, errors.New("parameter publicIPAddressName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpAddressName}", url.PathEscape(publicIPAddressName)) + 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", "2018-10-01") + 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 +} + +// getVirtualMachineScaleSetPublicIPAddressHandleResponse handles the GetVirtualMachineScaleSetPublicIPAddress response. +func (client *PublicIPAddressesClient) getVirtualMachineScaleSetPublicIPAddressHandleResponse(resp *http.Response) (PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse, error) { + result := PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddress); err != nil { + return PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all public IP addresses in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - PublicIPAddressesClientListOptions contains the optional parameters for the PublicIPAddressesClient.NewListPager +// method. +func (client *PublicIPAddressesClient) NewListPager(resourceGroupName string, options *PublicIPAddressesClientListOptions) *runtime.Pager[PublicIPAddressesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPAddressesClientListResponse]{ + More: func(page PublicIPAddressesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPAddressesClientListResponse) (PublicIPAddressesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPAddressesClient.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, options) + }, nil) + if err != nil { + return PublicIPAddressesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PublicIPAddressesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *PublicIPAddressesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PublicIPAddressesClient) listHandleResponse(resp *http.Response) (PublicIPAddressesClientListResponse, error) { + result := PublicIPAddressesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddressListResult); err != nil { + return PublicIPAddressesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the public IP addresses in a subscription. +// +// Generated from API version 2023-05-01 +// - options - PublicIPAddressesClientListAllOptions contains the optional parameters for the PublicIPAddressesClient.NewListAllPager +// method. +func (client *PublicIPAddressesClient) NewListAllPager(options *PublicIPAddressesClientListAllOptions) *runtime.Pager[PublicIPAddressesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPAddressesClientListAllResponse]{ + More: func(page PublicIPAddressesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPAddressesClientListAllResponse) (PublicIPAddressesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPAddressesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return PublicIPAddressesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *PublicIPAddressesClient) listAllCreateRequest(ctx context.Context, options *PublicIPAddressesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *PublicIPAddressesClient) listAllHandleResponse(resp *http.Response) (PublicIPAddressesClientListAllResponse, error) { + result := PublicIPAddressesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddressListResult); err != nil { + return PublicIPAddressesClientListAllResponse{}, err + } + return result, nil +} + +// NewListCloudServicePublicIPAddressesPager - Gets information about all public IP addresses on a cloud service level. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - cloudServiceName - The name of the cloud service. +// - options - PublicIPAddressesClientListCloudServicePublicIPAddressesOptions contains the optional parameters for the PublicIPAddressesClient.NewListCloudServicePublicIPAddressesPager +// method. +func (client *PublicIPAddressesClient) NewListCloudServicePublicIPAddressesPager(resourceGroupName string, cloudServiceName string, options *PublicIPAddressesClientListCloudServicePublicIPAddressesOptions) *runtime.Pager[PublicIPAddressesClientListCloudServicePublicIPAddressesResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPAddressesClientListCloudServicePublicIPAddressesResponse]{ + More: func(page PublicIPAddressesClientListCloudServicePublicIPAddressesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPAddressesClientListCloudServicePublicIPAddressesResponse) (PublicIPAddressesClientListCloudServicePublicIPAddressesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPAddressesClient.NewListCloudServicePublicIPAddressesPager") + 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.listCloudServicePublicIPAddressesCreateRequest(ctx, resourceGroupName, cloudServiceName, options) + }, nil) + if err != nil { + return PublicIPAddressesClientListCloudServicePublicIPAddressesResponse{}, err + } + return client.listCloudServicePublicIPAddressesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCloudServicePublicIPAddressesCreateRequest creates the ListCloudServicePublicIPAddresses request. +func (client *PublicIPAddressesClient) listCloudServicePublicIPAddressesCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, options *PublicIPAddressesClientListCloudServicePublicIPAddressesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/publicipaddresses" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listCloudServicePublicIPAddressesHandleResponse handles the ListCloudServicePublicIPAddresses response. +func (client *PublicIPAddressesClient) listCloudServicePublicIPAddressesHandleResponse(resp *http.Response) (PublicIPAddressesClientListCloudServicePublicIPAddressesResponse, error) { + result := PublicIPAddressesClientListCloudServicePublicIPAddressesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddressListResult); err != nil { + return PublicIPAddressesClientListCloudServicePublicIPAddressesResponse{}, err + } + return result, nil +} + +// NewListCloudServiceRoleInstancePublicIPAddressesPager - Gets information about all public IP addresses in a role instance +// IP configuration in a cloud service. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - cloudServiceName - The name of the cloud service. +// - roleInstanceName - The name of role instance. +// - networkInterfaceName - The network interface name. +// - ipConfigurationName - The IP configuration name. +// - options - PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesOptions contains the optional parameters +// for the PublicIPAddressesClient.NewListCloudServiceRoleInstancePublicIPAddressesPager method. +func (client *PublicIPAddressesClient) NewListCloudServiceRoleInstancePublicIPAddressesPager(resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, ipConfigurationName string, options *PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesOptions) *runtime.Pager[PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse]{ + More: func(page PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse) (PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPAddressesClient.NewListCloudServiceRoleInstancePublicIPAddressesPager") + 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.listCloudServiceRoleInstancePublicIPAddressesCreateRequest(ctx, resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, ipConfigurationName, options) + }, nil) + if err != nil { + return PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse{}, err + } + return client.listCloudServiceRoleInstancePublicIPAddressesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCloudServiceRoleInstancePublicIPAddressesCreateRequest creates the ListCloudServiceRoleInstancePublicIPAddresses request. +func (client *PublicIPAddressesClient) listCloudServiceRoleInstancePublicIPAddressesCreateRequest(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, ipConfigurationName string, options *PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudServiceName == "" { + return nil, errors.New("parameter cloudServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudServiceName}", url.PathEscape(cloudServiceName)) + if roleInstanceName == "" { + return nil, errors.New("parameter roleInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{roleInstanceName}", url.PathEscape(roleInstanceName)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if ipConfigurationName == "" { + return nil, errors.New("parameter ipConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigurationName}", url.PathEscape(ipConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listCloudServiceRoleInstancePublicIPAddressesHandleResponse handles the ListCloudServiceRoleInstancePublicIPAddresses response. +func (client *PublicIPAddressesClient) listCloudServiceRoleInstancePublicIPAddressesHandleResponse(resp *http.Response) (PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse, error) { + result := PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddressListResult); err != nil { + return PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse{}, err + } + return result, nil +} + +// NewListVirtualMachineScaleSetPublicIPAddressesPager - Gets information about all public IP addresses on a virtual machine +// scale set level. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - options - PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesOptions contains the optional parameters for +// the PublicIPAddressesClient.NewListVirtualMachineScaleSetPublicIPAddressesPager method. +func (client *PublicIPAddressesClient) NewListVirtualMachineScaleSetPublicIPAddressesPager(resourceGroupName string, virtualMachineScaleSetName string, options *PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesOptions) *runtime.Pager[PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse]{ + More: func(page PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse) (PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPAddressesClient.NewListVirtualMachineScaleSetPublicIPAddressesPager") + 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.listVirtualMachineScaleSetPublicIPAddressesCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, options) + }, nil) + if err != nil { + return PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse{}, err + } + return client.listVirtualMachineScaleSetPublicIPAddressesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listVirtualMachineScaleSetPublicIPAddressesCreateRequest creates the ListVirtualMachineScaleSetPublicIPAddresses request. +func (client *PublicIPAddressesClient) listVirtualMachineScaleSetPublicIPAddressesCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, options *PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/publicipaddresses" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + 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", "2018-10-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listVirtualMachineScaleSetPublicIPAddressesHandleResponse handles the ListVirtualMachineScaleSetPublicIPAddresses response. +func (client *PublicIPAddressesClient) listVirtualMachineScaleSetPublicIPAddressesHandleResponse(resp *http.Response) (PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse, error) { + result := PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddressListResult); err != nil { + return PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse{}, err + } + return result, nil +} + +// NewListVirtualMachineScaleSetVMPublicIPAddressesPager - Gets information about all public IP addresses in a virtual machine +// IP configuration in a virtual machine scale set. +// +// Generated from API version 2018-10-01 +// - resourceGroupName - The name of the resource group. +// - virtualMachineScaleSetName - The name of the virtual machine scale set. +// - virtualmachineIndex - The virtual machine index. +// - networkInterfaceName - The network interface name. +// - ipConfigurationName - The IP configuration name. +// - options - PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesOptions contains the optional parameters +// for the PublicIPAddressesClient.NewListVirtualMachineScaleSetVMPublicIPAddressesPager method. +func (client *PublicIPAddressesClient) NewListVirtualMachineScaleSetVMPublicIPAddressesPager(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, ipConfigurationName string, options *PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesOptions) *runtime.Pager[PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse]{ + More: func(page PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse) (PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPAddressesClient.NewListVirtualMachineScaleSetVMPublicIPAddressesPager") + 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.listVirtualMachineScaleSetVMPublicIPAddressesCreateRequest(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, options) + }, nil) + if err != nil { + return PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse{}, err + } + return client.listVirtualMachineScaleSetVMPublicIPAddressesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listVirtualMachineScaleSetVMPublicIPAddressesCreateRequest creates the ListVirtualMachineScaleSetVMPublicIPAddresses request. +func (client *PublicIPAddressesClient) listVirtualMachineScaleSetVMPublicIPAddressesCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, ipConfigurationName string, options *PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualMachineScaleSetName == "" { + return nil, errors.New("parameter virtualMachineScaleSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualMachineScaleSetName}", url.PathEscape(virtualMachineScaleSetName)) + if virtualmachineIndex == "" { + return nil, errors.New("parameter virtualmachineIndex cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualmachineIndex}", url.PathEscape(virtualmachineIndex)) + if networkInterfaceName == "" { + return nil, errors.New("parameter networkInterfaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkInterfaceName}", url.PathEscape(networkInterfaceName)) + if ipConfigurationName == "" { + return nil, errors.New("parameter ipConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigurationName}", url.PathEscape(ipConfigurationName)) + 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", "2018-10-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listVirtualMachineScaleSetVMPublicIPAddressesHandleResponse handles the ListVirtualMachineScaleSetVMPublicIPAddresses response. +func (client *PublicIPAddressesClient) listVirtualMachineScaleSetVMPublicIPAddressesHandleResponse(resp *http.Response) (PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse, error) { + result := PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddressListResult); err != nil { + return PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates public IP address tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPAddressName - The name of the public IP address. +// - parameters - Parameters supplied to update public IP address tags. +// - options - PublicIPAddressesClientUpdateTagsOptions contains the optional parameters for the PublicIPAddressesClient.UpdateTags +// method. +func (client *PublicIPAddressesClient) UpdateTags(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters TagsObject, options *PublicIPAddressesClientUpdateTagsOptions) (PublicIPAddressesClientUpdateTagsResponse, error) { + var err error + const operationName = "PublicIPAddressesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, publicIPAddressName, parameters, options) + if err != nil { + return PublicIPAddressesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PublicIPAddressesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PublicIPAddressesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *PublicIPAddressesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters TagsObject, options *PublicIPAddressesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPAddressName == "" { + return nil, errors.New("parameter publicIPAddressName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpAddressName}", url.PathEscape(publicIPAddressName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *PublicIPAddressesClient) updateTagsHandleResponse(resp *http.Response) (PublicIPAddressesClientUpdateTagsResponse, error) { + result := PublicIPAddressesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddress); err != nil { + return PublicIPAddressesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/publicipprefixes_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/publicipprefixes_client.go new file mode 100644 index 000000000..992e20200 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/publicipprefixes_client.go @@ -0,0 +1,454 @@ +//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 armnetwork + +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" +) + +// PublicIPPrefixesClient contains the methods for the PublicIPPrefixes group. +// Don't use this type directly, use NewPublicIPPrefixesClient() instead. +type PublicIPPrefixesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPublicIPPrefixesClient creates a new instance of PublicIPPrefixesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewPublicIPPrefixesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PublicIPPrefixesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PublicIPPrefixesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a static or dynamic public IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPPrefixName - The name of the public IP prefix. +// - parameters - Parameters supplied to the create or update public IP prefix operation. +// - options - PublicIPPrefixesClientBeginCreateOrUpdateOptions contains the optional parameters for the PublicIPPrefixesClient.BeginCreateOrUpdate +// method. +func (client *PublicIPPrefixesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters PublicIPPrefix, options *PublicIPPrefixesClientBeginCreateOrUpdateOptions) (*runtime.Poller[PublicIPPrefixesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, publicIPPrefixName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PublicIPPrefixesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PublicIPPrefixesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a static or dynamic public IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PublicIPPrefixesClient) createOrUpdate(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters PublicIPPrefix, options *PublicIPPrefixesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PublicIPPrefixesClient.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, publicIPPrefixName, 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 *PublicIPPrefixesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters PublicIPPrefix, options *PublicIPPrefixesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPPrefixName == "" { + return nil, errors.New("parameter publicIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpPrefixName}", url.PathEscape(publicIPPrefixName)) + 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-05-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 public IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPPrefixName - The name of the PublicIpPrefix. +// - options - PublicIPPrefixesClientBeginDeleteOptions contains the optional parameters for the PublicIPPrefixesClient.BeginDelete +// method. +func (client *PublicIPPrefixesClient) BeginDelete(ctx context.Context, resourceGroupName string, publicIPPrefixName string, options *PublicIPPrefixesClientBeginDeleteOptions) (*runtime.Poller[PublicIPPrefixesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, publicIPPrefixName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PublicIPPrefixesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PublicIPPrefixesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified public IP prefix. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *PublicIPPrefixesClient) deleteOperation(ctx context.Context, resourceGroupName string, publicIPPrefixName string, options *PublicIPPrefixesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PublicIPPrefixesClient.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, publicIPPrefixName, 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 *PublicIPPrefixesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, publicIPPrefixName string, options *PublicIPPrefixesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPPrefixName == "" { + return nil, errors.New("parameter publicIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpPrefixName}", url.PathEscape(publicIPPrefixName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified public IP prefix in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPPrefixName - The name of the public IP prefix. +// - options - PublicIPPrefixesClientGetOptions contains the optional parameters for the PublicIPPrefixesClient.Get method. +func (client *PublicIPPrefixesClient) Get(ctx context.Context, resourceGroupName string, publicIPPrefixName string, options *PublicIPPrefixesClientGetOptions) (PublicIPPrefixesClientGetResponse, error) { + var err error + const operationName = "PublicIPPrefixesClient.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, publicIPPrefixName, options) + if err != nil { + return PublicIPPrefixesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PublicIPPrefixesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PublicIPPrefixesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PublicIPPrefixesClient) getCreateRequest(ctx context.Context, resourceGroupName string, publicIPPrefixName string, options *PublicIPPrefixesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPPrefixName == "" { + return nil, errors.New("parameter publicIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpPrefixName}", url.PathEscape(publicIPPrefixName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *PublicIPPrefixesClient) getHandleResponse(resp *http.Response) (PublicIPPrefixesClientGetResponse, error) { + result := PublicIPPrefixesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPPrefix); err != nil { + return PublicIPPrefixesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all public IP prefixes in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - PublicIPPrefixesClientListOptions contains the optional parameters for the PublicIPPrefixesClient.NewListPager +// method. +func (client *PublicIPPrefixesClient) NewListPager(resourceGroupName string, options *PublicIPPrefixesClientListOptions) *runtime.Pager[PublicIPPrefixesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPPrefixesClientListResponse]{ + More: func(page PublicIPPrefixesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPPrefixesClientListResponse) (PublicIPPrefixesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPPrefixesClient.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, options) + }, nil) + if err != nil { + return PublicIPPrefixesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PublicIPPrefixesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *PublicIPPrefixesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PublicIPPrefixesClient) listHandleResponse(resp *http.Response) (PublicIPPrefixesClientListResponse, error) { + result := PublicIPPrefixesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPPrefixListResult); err != nil { + return PublicIPPrefixesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the public IP prefixes in a subscription. +// +// Generated from API version 2023-05-01 +// - options - PublicIPPrefixesClientListAllOptions contains the optional parameters for the PublicIPPrefixesClient.NewListAllPager +// method. +func (client *PublicIPPrefixesClient) NewListAllPager(options *PublicIPPrefixesClientListAllOptions) *runtime.Pager[PublicIPPrefixesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[PublicIPPrefixesClientListAllResponse]{ + More: func(page PublicIPPrefixesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PublicIPPrefixesClientListAllResponse) (PublicIPPrefixesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PublicIPPrefixesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return PublicIPPrefixesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *PublicIPPrefixesClient) listAllCreateRequest(ctx context.Context, options *PublicIPPrefixesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPPrefixes" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *PublicIPPrefixesClient) listAllHandleResponse(resp *http.Response) (PublicIPPrefixesClientListAllResponse, error) { + result := PublicIPPrefixesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPPrefixListResult); err != nil { + return PublicIPPrefixesClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates public IP prefix tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - publicIPPrefixName - The name of the public IP prefix. +// - parameters - Parameters supplied to update public IP prefix tags. +// - options - PublicIPPrefixesClientUpdateTagsOptions contains the optional parameters for the PublicIPPrefixesClient.UpdateTags +// method. +func (client *PublicIPPrefixesClient) UpdateTags(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters TagsObject, options *PublicIPPrefixesClientUpdateTagsOptions) (PublicIPPrefixesClientUpdateTagsResponse, error) { + var err error + const operationName = "PublicIPPrefixesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, publicIPPrefixName, parameters, options) + if err != nil { + return PublicIPPrefixesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PublicIPPrefixesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PublicIPPrefixesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *PublicIPPrefixesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters TagsObject, options *PublicIPPrefixesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if publicIPPrefixName == "" { + return nil, errors.New("parameter publicIPPrefixName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{publicIpPrefixName}", url.PathEscape(publicIPPrefixName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *PublicIPPrefixesClient) updateTagsHandleResponse(resp *http.Response) (PublicIPPrefixesClientUpdateTagsResponse, error) { + result := PublicIPPrefixesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicIPPrefix); err != nil { + return PublicIPPrefixesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/resourcenavigationlinks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/resourcenavigationlinks_client.go new file mode 100644 index 000000000..9968fd01f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/resourcenavigationlinks_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 armnetwork + +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" +) + +// ResourceNavigationLinksClient contains the methods for the ResourceNavigationLinks group. +// Don't use this type directly, use NewResourceNavigationLinksClient() instead. +type ResourceNavigationLinksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewResourceNavigationLinksClient creates a new instance of ResourceNavigationLinksClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewResourceNavigationLinksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResourceNavigationLinksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ResourceNavigationLinksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Gets a list of resource navigation links for a subnet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - subnetName - The name of the subnet. +// - options - ResourceNavigationLinksClientListOptions contains the optional parameters for the ResourceNavigationLinksClient.List +// method. +func (client *ResourceNavigationLinksClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *ResourceNavigationLinksClientListOptions) (ResourceNavigationLinksClientListResponse, error) { + var err error + const operationName = "ResourceNavigationLinksClient.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, virtualNetworkName, subnetName, options) + if err != nil { + return ResourceNavigationLinksClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResourceNavigationLinksClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ResourceNavigationLinksClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *ResourceNavigationLinksClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *ResourceNavigationLinksClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/ResourceNavigationLinks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if subnetName == "" { + return nil, errors.New("parameter subnetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subnetName}", url.PathEscape(subnetName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ResourceNavigationLinksClient) listHandleResponse(resp *http.Response) (ResourceNavigationLinksClientListResponse, error) { + result := ResourceNavigationLinksClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceNavigationLinksListResult); err != nil { + return ResourceNavigationLinksClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/response_types.go new file mode 100644 index 000000000..d59e968e4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/response_types.go @@ -0,0 +1,3734 @@ +//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 armnetwork + +import "encoding/json" + +// AdminRuleCollectionsClientCreateOrUpdateResponse contains the response from method AdminRuleCollectionsClient.CreateOrUpdate. +type AdminRuleCollectionsClientCreateOrUpdateResponse struct { + // Defines the admin rule collection. + AdminRuleCollection +} + +// AdminRuleCollectionsClientDeleteResponse contains the response from method AdminRuleCollectionsClient.BeginDelete. +type AdminRuleCollectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// AdminRuleCollectionsClientGetResponse contains the response from method AdminRuleCollectionsClient.Get. +type AdminRuleCollectionsClientGetResponse struct { + // Defines the admin rule collection. + AdminRuleCollection +} + +// AdminRuleCollectionsClientListResponse contains the response from method AdminRuleCollectionsClient.NewListPager. +type AdminRuleCollectionsClientListResponse struct { + // Security admin configuration rule collection list result. + AdminRuleCollectionListResult +} + +// AdminRulesClientCreateOrUpdateResponse contains the response from method AdminRulesClient.CreateOrUpdate. +type AdminRulesClientCreateOrUpdateResponse struct { + // Network base admin rule. + BaseAdminRuleClassification +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdminRulesClientCreateOrUpdateResponse. +func (a *AdminRulesClientCreateOrUpdateResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalBaseAdminRuleClassification(data) + if err != nil { + return err + } + a.BaseAdminRuleClassification = res + return nil +} + +// AdminRulesClientDeleteResponse contains the response from method AdminRulesClient.BeginDelete. +type AdminRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// AdminRulesClientGetResponse contains the response from method AdminRulesClient.Get. +type AdminRulesClientGetResponse struct { + // Network base admin rule. + BaseAdminRuleClassification +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdminRulesClientGetResponse. +func (a *AdminRulesClientGetResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalBaseAdminRuleClassification(data) + if err != nil { + return err + } + a.BaseAdminRuleClassification = res + return nil +} + +// AdminRulesClientListResponse contains the response from method AdminRulesClient.NewListPager. +type AdminRulesClientListResponse struct { + // security configuration admin rule list result. + AdminRuleListResult +} + +// ApplicationGatewayPrivateEndpointConnectionsClientDeleteResponse contains the response from method ApplicationGatewayPrivateEndpointConnectionsClient.BeginDelete. +type ApplicationGatewayPrivateEndpointConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ApplicationGatewayPrivateEndpointConnectionsClientGetResponse contains the response from method ApplicationGatewayPrivateEndpointConnectionsClient.Get. +type ApplicationGatewayPrivateEndpointConnectionsClientGetResponse struct { + // Private Endpoint connection on an application gateway. + ApplicationGatewayPrivateEndpointConnection +} + +// ApplicationGatewayPrivateEndpointConnectionsClientListResponse contains the response from method ApplicationGatewayPrivateEndpointConnectionsClient.NewListPager. +type ApplicationGatewayPrivateEndpointConnectionsClientListResponse struct { + // Response for ListApplicationGatewayPrivateEndpointConnection API service call. Gets all private endpoint connections for + // an application gateway. + ApplicationGatewayPrivateEndpointConnectionListResult +} + +// ApplicationGatewayPrivateEndpointConnectionsClientUpdateResponse contains the response from method ApplicationGatewayPrivateEndpointConnectionsClient.BeginUpdate. +type ApplicationGatewayPrivateEndpointConnectionsClientUpdateResponse struct { + // Private Endpoint connection on an application gateway. + ApplicationGatewayPrivateEndpointConnection +} + +// ApplicationGatewayPrivateLinkResourcesClientListResponse contains the response from method ApplicationGatewayPrivateLinkResourcesClient.NewListPager. +type ApplicationGatewayPrivateLinkResourcesClientListResponse struct { + // Response for ListApplicationGatewayPrivateLinkResources API service call. Gets all private link resources for an application + // gateway. + ApplicationGatewayPrivateLinkResourceListResult +} + +// ApplicationGatewayWafDynamicManifestsClientGetResponse contains the response from method ApplicationGatewayWafDynamicManifestsClient.NewGetPager. +type ApplicationGatewayWafDynamicManifestsClientGetResponse struct { + // Response for ApplicationGatewayWafDynamicManifests API service call. + ApplicationGatewayWafDynamicManifestResultList +} + +// ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse contains the response from method ApplicationGatewayWafDynamicManifestsDefaultClient.Get. +type ApplicationGatewayWafDynamicManifestsDefaultClientGetResponse struct { + // Response for ApplicationGatewayWafDynamicManifest API service call. + ApplicationGatewayWafDynamicManifestResult +} + +// ApplicationGatewaysClientBackendHealthOnDemandResponse contains the response from method ApplicationGatewaysClient.BeginBackendHealthOnDemand. +type ApplicationGatewaysClientBackendHealthOnDemandResponse struct { + // Result of on demand test probe. + ApplicationGatewayBackendHealthOnDemand +} + +// ApplicationGatewaysClientBackendHealthResponse contains the response from method ApplicationGatewaysClient.BeginBackendHealth. +type ApplicationGatewaysClientBackendHealthResponse struct { + // Response for ApplicationGatewayBackendHealth API service call. + ApplicationGatewayBackendHealth +} + +// ApplicationGatewaysClientCreateOrUpdateResponse contains the response from method ApplicationGatewaysClient.BeginCreateOrUpdate. +type ApplicationGatewaysClientCreateOrUpdateResponse struct { + // Application gateway resource. + ApplicationGateway +} + +// ApplicationGatewaysClientDeleteResponse contains the response from method ApplicationGatewaysClient.BeginDelete. +type ApplicationGatewaysClientDeleteResponse struct { + // placeholder for future response values +} + +// ApplicationGatewaysClientGetResponse contains the response from method ApplicationGatewaysClient.Get. +type ApplicationGatewaysClientGetResponse struct { + // Application gateway resource. + ApplicationGateway +} + +// ApplicationGatewaysClientGetSSLPredefinedPolicyResponse contains the response from method ApplicationGatewaysClient.GetSSLPredefinedPolicy. +type ApplicationGatewaysClientGetSSLPredefinedPolicyResponse struct { + // An Ssl predefined policy. + ApplicationGatewaySSLPredefinedPolicy +} + +// ApplicationGatewaysClientListAllResponse contains the response from method ApplicationGatewaysClient.NewListAllPager. +type ApplicationGatewaysClientListAllResponse struct { + // Response for ListApplicationGateways API service call. + ApplicationGatewayListResult +} + +// ApplicationGatewaysClientListAvailableRequestHeadersResponse contains the response from method ApplicationGatewaysClient.ListAvailableRequestHeaders. +type ApplicationGatewaysClientListAvailableRequestHeadersResponse struct { + // Response for ApplicationGatewayAvailableRequestHeaders API service call. + StringArray []*string +} + +// ApplicationGatewaysClientListAvailableResponseHeadersResponse contains the response from method ApplicationGatewaysClient.ListAvailableResponseHeaders. +type ApplicationGatewaysClientListAvailableResponseHeadersResponse struct { + // Response for ApplicationGatewayAvailableResponseHeaders API service call. + StringArray []*string +} + +// ApplicationGatewaysClientListAvailableSSLOptionsResponse contains the response from method ApplicationGatewaysClient.ListAvailableSSLOptions. +type ApplicationGatewaysClientListAvailableSSLOptionsResponse struct { + // Response for ApplicationGatewayAvailableSslOptions API service call. + ApplicationGatewayAvailableSSLOptions +} + +// ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse contains the response from method ApplicationGatewaysClient.NewListAvailableSSLPredefinedPoliciesPager. +type ApplicationGatewaysClientListAvailableSSLPredefinedPoliciesResponse struct { + // Response for ApplicationGatewayAvailableSslOptions API service call. + ApplicationGatewayAvailableSSLPredefinedPolicies +} + +// ApplicationGatewaysClientListAvailableServerVariablesResponse contains the response from method ApplicationGatewaysClient.ListAvailableServerVariables. +type ApplicationGatewaysClientListAvailableServerVariablesResponse struct { + // Response for ApplicationGatewayAvailableServerVariables API service call. + StringArray []*string +} + +// ApplicationGatewaysClientListAvailableWafRuleSetsResponse contains the response from method ApplicationGatewaysClient.ListAvailableWafRuleSets. +type ApplicationGatewaysClientListAvailableWafRuleSetsResponse struct { + // Response for ApplicationGatewayAvailableWafRuleSets API service call. + ApplicationGatewayAvailableWafRuleSetsResult +} + +// ApplicationGatewaysClientListResponse contains the response from method ApplicationGatewaysClient.NewListPager. +type ApplicationGatewaysClientListResponse struct { + // Response for ListApplicationGateways API service call. + ApplicationGatewayListResult +} + +// ApplicationGatewaysClientStartResponse contains the response from method ApplicationGatewaysClient.BeginStart. +type ApplicationGatewaysClientStartResponse struct { + // placeholder for future response values +} + +// ApplicationGatewaysClientStopResponse contains the response from method ApplicationGatewaysClient.BeginStop. +type ApplicationGatewaysClientStopResponse struct { + // placeholder for future response values +} + +// ApplicationGatewaysClientUpdateTagsResponse contains the response from method ApplicationGatewaysClient.UpdateTags. +type ApplicationGatewaysClientUpdateTagsResponse struct { + // Application gateway resource. + ApplicationGateway +} + +// ApplicationSecurityGroupsClientCreateOrUpdateResponse contains the response from method ApplicationSecurityGroupsClient.BeginCreateOrUpdate. +type ApplicationSecurityGroupsClientCreateOrUpdateResponse struct { + // An application security group in a resource group. + ApplicationSecurityGroup +} + +// ApplicationSecurityGroupsClientDeleteResponse contains the response from method ApplicationSecurityGroupsClient.BeginDelete. +type ApplicationSecurityGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// ApplicationSecurityGroupsClientGetResponse contains the response from method ApplicationSecurityGroupsClient.Get. +type ApplicationSecurityGroupsClientGetResponse struct { + // An application security group in a resource group. + ApplicationSecurityGroup +} + +// ApplicationSecurityGroupsClientListAllResponse contains the response from method ApplicationSecurityGroupsClient.NewListAllPager. +type ApplicationSecurityGroupsClientListAllResponse struct { + // A list of application security groups. + ApplicationSecurityGroupListResult +} + +// ApplicationSecurityGroupsClientListResponse contains the response from method ApplicationSecurityGroupsClient.NewListPager. +type ApplicationSecurityGroupsClientListResponse struct { + // A list of application security groups. + ApplicationSecurityGroupListResult +} + +// ApplicationSecurityGroupsClientUpdateTagsResponse contains the response from method ApplicationSecurityGroupsClient.UpdateTags. +type ApplicationSecurityGroupsClientUpdateTagsResponse struct { + // An application security group in a resource group. + ApplicationSecurityGroup +} + +// AvailableDelegationsClientListResponse contains the response from method AvailableDelegationsClient.NewListPager. +type AvailableDelegationsClientListResponse struct { + // An array of available delegations. + AvailableDelegationsResult +} + +// AvailableEndpointServicesClientListResponse contains the response from method AvailableEndpointServicesClient.NewListPager. +type AvailableEndpointServicesClientListResponse struct { + // Response for the ListAvailableEndpointServices API service call. + EndpointServicesListResult +} + +// AvailablePrivateEndpointTypesClientListByResourceGroupResponse contains the response from method AvailablePrivateEndpointTypesClient.NewListByResourceGroupPager. +type AvailablePrivateEndpointTypesClientListByResourceGroupResponse struct { + // An array of available PrivateEndpoint types. + AvailablePrivateEndpointTypesResult +} + +// AvailablePrivateEndpointTypesClientListResponse contains the response from method AvailablePrivateEndpointTypesClient.NewListPager. +type AvailablePrivateEndpointTypesClientListResponse struct { + // An array of available PrivateEndpoint types. + AvailablePrivateEndpointTypesResult +} + +// AvailableResourceGroupDelegationsClientListResponse contains the response from method AvailableResourceGroupDelegationsClient.NewListPager. +type AvailableResourceGroupDelegationsClientListResponse struct { + // An array of available delegations. + AvailableDelegationsResult +} + +// AvailableServiceAliasesClientListByResourceGroupResponse contains the response from method AvailableServiceAliasesClient.NewListByResourceGroupPager. +type AvailableServiceAliasesClientListByResourceGroupResponse struct { + // An array of available service aliases. + AvailableServiceAliasesResult +} + +// AvailableServiceAliasesClientListResponse contains the response from method AvailableServiceAliasesClient.NewListPager. +type AvailableServiceAliasesClientListResponse struct { + // An array of available service aliases. + AvailableServiceAliasesResult +} + +// AzureFirewallFqdnTagsClientListAllResponse contains the response from method AzureFirewallFqdnTagsClient.NewListAllPager. +type AzureFirewallFqdnTagsClientListAllResponse struct { + // Response for ListAzureFirewallFqdnTags API service call. + AzureFirewallFqdnTagListResult +} + +// AzureFirewallsClientCreateOrUpdateResponse contains the response from method AzureFirewallsClient.BeginCreateOrUpdate. +type AzureFirewallsClientCreateOrUpdateResponse struct { + // Azure Firewall resource. + AzureFirewall +} + +// AzureFirewallsClientDeleteResponse contains the response from method AzureFirewallsClient.BeginDelete. +type AzureFirewallsClientDeleteResponse struct { + // placeholder for future response values +} + +// AzureFirewallsClientGetResponse contains the response from method AzureFirewallsClient.Get. +type AzureFirewallsClientGetResponse struct { + // Azure Firewall resource. + AzureFirewall +} + +// AzureFirewallsClientListAllResponse contains the response from method AzureFirewallsClient.NewListAllPager. +type AzureFirewallsClientListAllResponse struct { + // Response for ListAzureFirewalls API service call. + AzureFirewallListResult +} + +// AzureFirewallsClientListLearnedPrefixesResponse contains the response from method AzureFirewallsClient.BeginListLearnedPrefixes. +type AzureFirewallsClientListLearnedPrefixesResponse struct { + // List of SNAT IP Prefixes learnt by firewall to not SNAT + IPPrefixesList +} + +// AzureFirewallsClientListResponse contains the response from method AzureFirewallsClient.NewListPager. +type AzureFirewallsClientListResponse struct { + // Response for ListAzureFirewalls API service call. + AzureFirewallListResult +} + +// AzureFirewallsClientPacketCaptureResponse contains the response from method AzureFirewallsClient.BeginPacketCapture. +type AzureFirewallsClientPacketCaptureResponse struct { + // placeholder for future response values +} + +// AzureFirewallsClientUpdateTagsResponse contains the response from method AzureFirewallsClient.BeginUpdateTags. +type AzureFirewallsClientUpdateTagsResponse struct { + // Azure Firewall resource. + AzureFirewall +} + +// BastionHostsClientCreateOrUpdateResponse contains the response from method BastionHostsClient.BeginCreateOrUpdate. +type BastionHostsClientCreateOrUpdateResponse struct { + // Bastion Host resource. + BastionHost +} + +// BastionHostsClientDeleteResponse contains the response from method BastionHostsClient.BeginDelete. +type BastionHostsClientDeleteResponse struct { + // placeholder for future response values +} + +// BastionHostsClientGetResponse contains the response from method BastionHostsClient.Get. +type BastionHostsClientGetResponse struct { + // Bastion Host resource. + BastionHost +} + +// BastionHostsClientListByResourceGroupResponse contains the response from method BastionHostsClient.NewListByResourceGroupPager. +type BastionHostsClientListByResourceGroupResponse struct { + // Response for ListBastionHosts API service call. + BastionHostListResult +} + +// BastionHostsClientListResponse contains the response from method BastionHostsClient.NewListPager. +type BastionHostsClientListResponse struct { + // Response for ListBastionHosts API service call. + BastionHostListResult +} + +// BastionHostsClientUpdateTagsResponse contains the response from method BastionHostsClient.BeginUpdateTags. +type BastionHostsClientUpdateTagsResponse struct { + // Bastion Host resource. + BastionHost +} + +// BgpServiceCommunitiesClientListResponse contains the response from method BgpServiceCommunitiesClient.NewListPager. +type BgpServiceCommunitiesClientListResponse struct { + // Response for the ListServiceCommunity API service call. + BgpServiceCommunityListResult +} + +// ConfigurationPolicyGroupsClientCreateOrUpdateResponse contains the response from method ConfigurationPolicyGroupsClient.BeginCreateOrUpdate. +type ConfigurationPolicyGroupsClientCreateOrUpdateResponse struct { + // VpnServerConfigurationPolicyGroup Resource. + VPNServerConfigurationPolicyGroup +} + +// ConfigurationPolicyGroupsClientDeleteResponse contains the response from method ConfigurationPolicyGroupsClient.BeginDelete. +type ConfigurationPolicyGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// ConfigurationPolicyGroupsClientGetResponse contains the response from method ConfigurationPolicyGroupsClient.Get. +type ConfigurationPolicyGroupsClientGetResponse struct { + // VpnServerConfigurationPolicyGroup Resource. + VPNServerConfigurationPolicyGroup +} + +// ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse contains the response from method ConfigurationPolicyGroupsClient.NewListByVPNServerConfigurationPager. +type ConfigurationPolicyGroupsClientListByVPNServerConfigurationResponse struct { + // Result of the request to list VpnServerConfigurationPolicyGroups. It contains a list of VpnServerConfigurationPolicyGroups + // and a URL nextLink to get the next set of results. + ListVPNServerConfigurationPolicyGroupsResult +} + +// ConnectionMonitorsClientCreateOrUpdateResponse contains the response from method ConnectionMonitorsClient.BeginCreateOrUpdate. +type ConnectionMonitorsClientCreateOrUpdateResponse struct { + // Information about the connection monitor. + ConnectionMonitorResult +} + +// ConnectionMonitorsClientDeleteResponse contains the response from method ConnectionMonitorsClient.BeginDelete. +type ConnectionMonitorsClientDeleteResponse struct { + // placeholder for future response values +} + +// ConnectionMonitorsClientGetResponse contains the response from method ConnectionMonitorsClient.Get. +type ConnectionMonitorsClientGetResponse struct { + // Information about the connection monitor. + ConnectionMonitorResult +} + +// ConnectionMonitorsClientListResponse contains the response from method ConnectionMonitorsClient.NewListPager. +type ConnectionMonitorsClientListResponse struct { + // List of connection monitors. + ConnectionMonitorListResult +} + +// ConnectionMonitorsClientQueryResponse contains the response from method ConnectionMonitorsClient.BeginQuery. +type ConnectionMonitorsClientQueryResponse struct { + // List of connection states snapshots. + ConnectionMonitorQueryResult +} + +// ConnectionMonitorsClientStartResponse contains the response from method ConnectionMonitorsClient.BeginStart. +type ConnectionMonitorsClientStartResponse struct { + // placeholder for future response values +} + +// ConnectionMonitorsClientStopResponse contains the response from method ConnectionMonitorsClient.BeginStop. +type ConnectionMonitorsClientStopResponse struct { + // placeholder for future response values +} + +// ConnectionMonitorsClientUpdateTagsResponse contains the response from method ConnectionMonitorsClient.UpdateTags. +type ConnectionMonitorsClientUpdateTagsResponse struct { + // Information about the connection monitor. + ConnectionMonitorResult +} + +// ConnectivityConfigurationsClientCreateOrUpdateResponse contains the response from method ConnectivityConfigurationsClient.CreateOrUpdate. +type ConnectivityConfigurationsClientCreateOrUpdateResponse struct { + // The network manager connectivity configuration resource + ConnectivityConfiguration +} + +// ConnectivityConfigurationsClientDeleteResponse contains the response from method ConnectivityConfigurationsClient.BeginDelete. +type ConnectivityConfigurationsClientDeleteResponse struct { + // placeholder for future response values +} + +// ConnectivityConfigurationsClientGetResponse contains the response from method ConnectivityConfigurationsClient.Get. +type ConnectivityConfigurationsClientGetResponse struct { + // The network manager connectivity configuration resource + ConnectivityConfiguration +} + +// ConnectivityConfigurationsClientListResponse contains the response from method ConnectivityConfigurationsClient.NewListPager. +type ConnectivityConfigurationsClientListResponse struct { + // Result of the request to list network manager connectivity configurations. It contains a list of configurations and a link + // to get the next set of results. + ConnectivityConfigurationListResult +} + +// CustomIPPrefixesClientCreateOrUpdateResponse contains the response from method CustomIPPrefixesClient.BeginCreateOrUpdate. +type CustomIPPrefixesClientCreateOrUpdateResponse struct { + // Custom IP prefix resource. + CustomIPPrefix +} + +// CustomIPPrefixesClientDeleteResponse contains the response from method CustomIPPrefixesClient.BeginDelete. +type CustomIPPrefixesClientDeleteResponse struct { + // placeholder for future response values +} + +// CustomIPPrefixesClientGetResponse contains the response from method CustomIPPrefixesClient.Get. +type CustomIPPrefixesClientGetResponse struct { + // Custom IP prefix resource. + CustomIPPrefix +} + +// CustomIPPrefixesClientListAllResponse contains the response from method CustomIPPrefixesClient.NewListAllPager. +type CustomIPPrefixesClientListAllResponse struct { + // Response for ListCustomIpPrefixes API service call. + CustomIPPrefixListResult +} + +// CustomIPPrefixesClientListResponse contains the response from method CustomIPPrefixesClient.NewListPager. +type CustomIPPrefixesClientListResponse struct { + // Response for ListCustomIpPrefixes API service call. + CustomIPPrefixListResult +} + +// CustomIPPrefixesClientUpdateTagsResponse contains the response from method CustomIPPrefixesClient.UpdateTags. +type CustomIPPrefixesClientUpdateTagsResponse struct { + // Custom IP prefix resource. + CustomIPPrefix +} + +// DdosCustomPoliciesClientCreateOrUpdateResponse contains the response from method DdosCustomPoliciesClient.BeginCreateOrUpdate. +type DdosCustomPoliciesClientCreateOrUpdateResponse struct { + // A DDoS custom policy in a resource group. + DdosCustomPolicy +} + +// DdosCustomPoliciesClientDeleteResponse contains the response from method DdosCustomPoliciesClient.BeginDelete. +type DdosCustomPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// DdosCustomPoliciesClientGetResponse contains the response from method DdosCustomPoliciesClient.Get. +type DdosCustomPoliciesClientGetResponse struct { + // A DDoS custom policy in a resource group. + DdosCustomPolicy +} + +// DdosCustomPoliciesClientUpdateTagsResponse contains the response from method DdosCustomPoliciesClient.UpdateTags. +type DdosCustomPoliciesClientUpdateTagsResponse struct { + // A DDoS custom policy in a resource group. + DdosCustomPolicy +} + +// DdosProtectionPlansClientCreateOrUpdateResponse contains the response from method DdosProtectionPlansClient.BeginCreateOrUpdate. +type DdosProtectionPlansClientCreateOrUpdateResponse struct { + // A DDoS protection plan in a resource group. + DdosProtectionPlan +} + +// DdosProtectionPlansClientDeleteResponse contains the response from method DdosProtectionPlansClient.BeginDelete. +type DdosProtectionPlansClientDeleteResponse struct { + // placeholder for future response values +} + +// DdosProtectionPlansClientGetResponse contains the response from method DdosProtectionPlansClient.Get. +type DdosProtectionPlansClientGetResponse struct { + // A DDoS protection plan in a resource group. + DdosProtectionPlan +} + +// DdosProtectionPlansClientListByResourceGroupResponse contains the response from method DdosProtectionPlansClient.NewListByResourceGroupPager. +type DdosProtectionPlansClientListByResourceGroupResponse struct { + // A list of DDoS protection plans. + DdosProtectionPlanListResult +} + +// DdosProtectionPlansClientListResponse contains the response from method DdosProtectionPlansClient.NewListPager. +type DdosProtectionPlansClientListResponse struct { + // A list of DDoS protection plans. + DdosProtectionPlanListResult +} + +// DdosProtectionPlansClientUpdateTagsResponse contains the response from method DdosProtectionPlansClient.UpdateTags. +type DdosProtectionPlansClientUpdateTagsResponse struct { + // A DDoS protection plan in a resource group. + DdosProtectionPlan +} + +// DefaultSecurityRulesClientGetResponse contains the response from method DefaultSecurityRulesClient.Get. +type DefaultSecurityRulesClientGetResponse struct { + // Network security rule. + SecurityRule +} + +// DefaultSecurityRulesClientListResponse contains the response from method DefaultSecurityRulesClient.NewListPager. +type DefaultSecurityRulesClientListResponse struct { + // Response for ListSecurityRule API service call. Retrieves all security rules that belongs to a network security group. + SecurityRuleListResult +} + +// DscpConfigurationClientCreateOrUpdateResponse contains the response from method DscpConfigurationClient.BeginCreateOrUpdate. +type DscpConfigurationClientCreateOrUpdateResponse struct { + // Differentiated Services Code Point configuration for any given network interface + DscpConfiguration +} + +// DscpConfigurationClientDeleteResponse contains the response from method DscpConfigurationClient.BeginDelete. +type DscpConfigurationClientDeleteResponse struct { + // placeholder for future response values +} + +// DscpConfigurationClientGetResponse contains the response from method DscpConfigurationClient.Get. +type DscpConfigurationClientGetResponse struct { + // Differentiated Services Code Point configuration for any given network interface + DscpConfiguration +} + +// DscpConfigurationClientListAllResponse contains the response from method DscpConfigurationClient.NewListAllPager. +type DscpConfigurationClientListAllResponse struct { + // Response for the DscpConfigurationList API service call. + DscpConfigurationListResult +} + +// DscpConfigurationClientListResponse contains the response from method DscpConfigurationClient.NewListPager. +type DscpConfigurationClientListResponse struct { + // Response for the DscpConfigurationList API service call. + DscpConfigurationListResult +} + +// ExpressRouteCircuitAuthorizationsClientCreateOrUpdateResponse contains the response from method ExpressRouteCircuitAuthorizationsClient.BeginCreateOrUpdate. +type ExpressRouteCircuitAuthorizationsClientCreateOrUpdateResponse struct { + // Authorization in an ExpressRouteCircuit resource. + ExpressRouteCircuitAuthorization +} + +// ExpressRouteCircuitAuthorizationsClientDeleteResponse contains the response from method ExpressRouteCircuitAuthorizationsClient.BeginDelete. +type ExpressRouteCircuitAuthorizationsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRouteCircuitAuthorizationsClientGetResponse contains the response from method ExpressRouteCircuitAuthorizationsClient.Get. +type ExpressRouteCircuitAuthorizationsClientGetResponse struct { + // Authorization in an ExpressRouteCircuit resource. + ExpressRouteCircuitAuthorization +} + +// ExpressRouteCircuitAuthorizationsClientListResponse contains the response from method ExpressRouteCircuitAuthorizationsClient.NewListPager. +type ExpressRouteCircuitAuthorizationsClientListResponse struct { + // Response for ListAuthorizations API service call retrieves all authorizations that belongs to an ExpressRouteCircuit. + AuthorizationListResult +} + +// ExpressRouteCircuitConnectionsClientCreateOrUpdateResponse contains the response from method ExpressRouteCircuitConnectionsClient.BeginCreateOrUpdate. +type ExpressRouteCircuitConnectionsClientCreateOrUpdateResponse struct { + // Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. + ExpressRouteCircuitConnection +} + +// ExpressRouteCircuitConnectionsClientDeleteResponse contains the response from method ExpressRouteCircuitConnectionsClient.BeginDelete. +type ExpressRouteCircuitConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRouteCircuitConnectionsClientGetResponse contains the response from method ExpressRouteCircuitConnectionsClient.Get. +type ExpressRouteCircuitConnectionsClientGetResponse struct { + // Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. + ExpressRouteCircuitConnection +} + +// ExpressRouteCircuitConnectionsClientListResponse contains the response from method ExpressRouteCircuitConnectionsClient.NewListPager. +type ExpressRouteCircuitConnectionsClientListResponse struct { + // Response for ListConnections API service call retrieves all global reach connections that belongs to a Private Peering + // for an ExpressRouteCircuit. + ExpressRouteCircuitConnectionListResult +} + +// ExpressRouteCircuitPeeringsClientCreateOrUpdateResponse contains the response from method ExpressRouteCircuitPeeringsClient.BeginCreateOrUpdate. +type ExpressRouteCircuitPeeringsClientCreateOrUpdateResponse struct { + // Peering in an ExpressRouteCircuit resource. + ExpressRouteCircuitPeering +} + +// ExpressRouteCircuitPeeringsClientDeleteResponse contains the response from method ExpressRouteCircuitPeeringsClient.BeginDelete. +type ExpressRouteCircuitPeeringsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRouteCircuitPeeringsClientGetResponse contains the response from method ExpressRouteCircuitPeeringsClient.Get. +type ExpressRouteCircuitPeeringsClientGetResponse struct { + // Peering in an ExpressRouteCircuit resource. + ExpressRouteCircuitPeering +} + +// ExpressRouteCircuitPeeringsClientListResponse contains the response from method ExpressRouteCircuitPeeringsClient.NewListPager. +type ExpressRouteCircuitPeeringsClientListResponse struct { + // Response for ListPeering API service call retrieves all peerings that belong to an ExpressRouteCircuit. + ExpressRouteCircuitPeeringListResult +} + +// ExpressRouteCircuitsClientCreateOrUpdateResponse contains the response from method ExpressRouteCircuitsClient.BeginCreateOrUpdate. +type ExpressRouteCircuitsClientCreateOrUpdateResponse struct { + // ExpressRouteCircuit resource. + ExpressRouteCircuit +} + +// ExpressRouteCircuitsClientDeleteResponse contains the response from method ExpressRouteCircuitsClient.BeginDelete. +type ExpressRouteCircuitsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRouteCircuitsClientGetPeeringStatsResponse contains the response from method ExpressRouteCircuitsClient.GetPeeringStats. +type ExpressRouteCircuitsClientGetPeeringStatsResponse struct { + // Contains stats associated with the peering. + ExpressRouteCircuitStats +} + +// ExpressRouteCircuitsClientGetResponse contains the response from method ExpressRouteCircuitsClient.Get. +type ExpressRouteCircuitsClientGetResponse struct { + // ExpressRouteCircuit resource. + ExpressRouteCircuit +} + +// ExpressRouteCircuitsClientGetStatsResponse contains the response from method ExpressRouteCircuitsClient.GetStats. +type ExpressRouteCircuitsClientGetStatsResponse struct { + // Contains stats associated with the peering. + ExpressRouteCircuitStats +} + +// ExpressRouteCircuitsClientListAllResponse contains the response from method ExpressRouteCircuitsClient.NewListAllPager. +type ExpressRouteCircuitsClientListAllResponse struct { + // Response for ListExpressRouteCircuit API service call. + ExpressRouteCircuitListResult +} + +// ExpressRouteCircuitsClientListArpTableResponse contains the response from method ExpressRouteCircuitsClient.BeginListArpTable. +type ExpressRouteCircuitsClientListArpTableResponse struct { + // Response for ListArpTable associated with the Express Route Circuits API. + ExpressRouteCircuitsArpTableListResult +} + +// ExpressRouteCircuitsClientListResponse contains the response from method ExpressRouteCircuitsClient.NewListPager. +type ExpressRouteCircuitsClientListResponse struct { + // Response for ListExpressRouteCircuit API service call. + ExpressRouteCircuitListResult +} + +// ExpressRouteCircuitsClientListRoutesTableResponse contains the response from method ExpressRouteCircuitsClient.BeginListRoutesTable. +type ExpressRouteCircuitsClientListRoutesTableResponse struct { + // Response for ListRoutesTable associated with the Express Route Circuits API. + ExpressRouteCircuitsRoutesTableListResult +} + +// ExpressRouteCircuitsClientListRoutesTableSummaryResponse contains the response from method ExpressRouteCircuitsClient.BeginListRoutesTableSummary. +type ExpressRouteCircuitsClientListRoutesTableSummaryResponse struct { + // Response for ListRoutesTable associated with the Express Route Circuits API. + ExpressRouteCircuitsRoutesTableSummaryListResult +} + +// ExpressRouteCircuitsClientUpdateTagsResponse contains the response from method ExpressRouteCircuitsClient.UpdateTags. +type ExpressRouteCircuitsClientUpdateTagsResponse struct { + // ExpressRouteCircuit resource. + ExpressRouteCircuit +} + +// ExpressRouteConnectionsClientCreateOrUpdateResponse contains the response from method ExpressRouteConnectionsClient.BeginCreateOrUpdate. +type ExpressRouteConnectionsClientCreateOrUpdateResponse struct { + // ExpressRouteConnection resource. + ExpressRouteConnection +} + +// ExpressRouteConnectionsClientDeleteResponse contains the response from method ExpressRouteConnectionsClient.BeginDelete. +type ExpressRouteConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRouteConnectionsClientGetResponse contains the response from method ExpressRouteConnectionsClient.Get. +type ExpressRouteConnectionsClientGetResponse struct { + // ExpressRouteConnection resource. + ExpressRouteConnection +} + +// ExpressRouteConnectionsClientListResponse contains the response from method ExpressRouteConnectionsClient.List. +type ExpressRouteConnectionsClientListResponse struct { + // ExpressRouteConnection list. + ExpressRouteConnectionList +} + +// ExpressRouteCrossConnectionPeeringsClientCreateOrUpdateResponse contains the response from method ExpressRouteCrossConnectionPeeringsClient.BeginCreateOrUpdate. +type ExpressRouteCrossConnectionPeeringsClientCreateOrUpdateResponse struct { + // Peering in an ExpressRoute Cross Connection resource. + ExpressRouteCrossConnectionPeering +} + +// ExpressRouteCrossConnectionPeeringsClientDeleteResponse contains the response from method ExpressRouteCrossConnectionPeeringsClient.BeginDelete. +type ExpressRouteCrossConnectionPeeringsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRouteCrossConnectionPeeringsClientGetResponse contains the response from method ExpressRouteCrossConnectionPeeringsClient.Get. +type ExpressRouteCrossConnectionPeeringsClientGetResponse struct { + // Peering in an ExpressRoute Cross Connection resource. + ExpressRouteCrossConnectionPeering +} + +// ExpressRouteCrossConnectionPeeringsClientListResponse contains the response from method ExpressRouteCrossConnectionPeeringsClient.NewListPager. +type ExpressRouteCrossConnectionPeeringsClientListResponse struct { + // Response for ListPeering API service call retrieves all peerings that belong to an ExpressRouteCrossConnection. + ExpressRouteCrossConnectionPeeringList +} + +// ExpressRouteCrossConnectionsClientCreateOrUpdateResponse contains the response from method ExpressRouteCrossConnectionsClient.BeginCreateOrUpdate. +type ExpressRouteCrossConnectionsClientCreateOrUpdateResponse struct { + // ExpressRouteCrossConnection resource. + ExpressRouteCrossConnection +} + +// ExpressRouteCrossConnectionsClientGetResponse contains the response from method ExpressRouteCrossConnectionsClient.Get. +type ExpressRouteCrossConnectionsClientGetResponse struct { + // ExpressRouteCrossConnection resource. + ExpressRouteCrossConnection +} + +// ExpressRouteCrossConnectionsClientListArpTableResponse contains the response from method ExpressRouteCrossConnectionsClient.BeginListArpTable. +type ExpressRouteCrossConnectionsClientListArpTableResponse struct { + // Response for ListArpTable associated with the Express Route Circuits API. + ExpressRouteCircuitsArpTableListResult +} + +// ExpressRouteCrossConnectionsClientListByResourceGroupResponse contains the response from method ExpressRouteCrossConnectionsClient.NewListByResourceGroupPager. +type ExpressRouteCrossConnectionsClientListByResourceGroupResponse struct { + // Response for ListExpressRouteCrossConnection API service call. + ExpressRouteCrossConnectionListResult +} + +// ExpressRouteCrossConnectionsClientListResponse contains the response from method ExpressRouteCrossConnectionsClient.NewListPager. +type ExpressRouteCrossConnectionsClientListResponse struct { + // Response for ListExpressRouteCrossConnection API service call. + ExpressRouteCrossConnectionListResult +} + +// ExpressRouteCrossConnectionsClientListRoutesTableResponse contains the response from method ExpressRouteCrossConnectionsClient.BeginListRoutesTable. +type ExpressRouteCrossConnectionsClientListRoutesTableResponse struct { + // Response for ListRoutesTable associated with the Express Route Circuits API. + ExpressRouteCircuitsRoutesTableListResult +} + +// ExpressRouteCrossConnectionsClientListRoutesTableSummaryResponse contains the response from method ExpressRouteCrossConnectionsClient.BeginListRoutesTableSummary. +type ExpressRouteCrossConnectionsClientListRoutesTableSummaryResponse struct { + // Response for ListRoutesTable associated with the Express Route Cross Connections. + ExpressRouteCrossConnectionsRoutesTableSummaryListResult +} + +// ExpressRouteCrossConnectionsClientUpdateTagsResponse contains the response from method ExpressRouteCrossConnectionsClient.UpdateTags. +type ExpressRouteCrossConnectionsClientUpdateTagsResponse struct { + // ExpressRouteCrossConnection resource. + ExpressRouteCrossConnection +} + +// ExpressRouteGatewaysClientCreateOrUpdateResponse contains the response from method ExpressRouteGatewaysClient.BeginCreateOrUpdate. +type ExpressRouteGatewaysClientCreateOrUpdateResponse struct { + // ExpressRoute gateway resource. + ExpressRouteGateway +} + +// ExpressRouteGatewaysClientDeleteResponse contains the response from method ExpressRouteGatewaysClient.BeginDelete. +type ExpressRouteGatewaysClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRouteGatewaysClientGetResponse contains the response from method ExpressRouteGatewaysClient.Get. +type ExpressRouteGatewaysClientGetResponse struct { + // ExpressRoute gateway resource. + ExpressRouteGateway +} + +// ExpressRouteGatewaysClientListByResourceGroupResponse contains the response from method ExpressRouteGatewaysClient.ListByResourceGroup. +type ExpressRouteGatewaysClientListByResourceGroupResponse struct { + // List of ExpressRoute gateways. + ExpressRouteGatewayList +} + +// ExpressRouteGatewaysClientListBySubscriptionResponse contains the response from method ExpressRouteGatewaysClient.ListBySubscription. +type ExpressRouteGatewaysClientListBySubscriptionResponse struct { + // List of ExpressRoute gateways. + ExpressRouteGatewayList +} + +// ExpressRouteGatewaysClientUpdateTagsResponse contains the response from method ExpressRouteGatewaysClient.BeginUpdateTags. +type ExpressRouteGatewaysClientUpdateTagsResponse struct { + // ExpressRoute gateway resource. + ExpressRouteGateway +} + +// ExpressRouteLinksClientGetResponse contains the response from method ExpressRouteLinksClient.Get. +type ExpressRouteLinksClientGetResponse struct { + // ExpressRouteLink child resource definition. + ExpressRouteLink +} + +// ExpressRouteLinksClientListResponse contains the response from method ExpressRouteLinksClient.NewListPager. +type ExpressRouteLinksClientListResponse struct { + // Response for ListExpressRouteLinks API service call. + ExpressRouteLinkListResult +} + +// ExpressRoutePortAuthorizationsClientCreateOrUpdateResponse contains the response from method ExpressRoutePortAuthorizationsClient.BeginCreateOrUpdate. +type ExpressRoutePortAuthorizationsClientCreateOrUpdateResponse struct { + // ExpressRoutePort Authorization resource definition. + ExpressRoutePortAuthorization +} + +// ExpressRoutePortAuthorizationsClientDeleteResponse contains the response from method ExpressRoutePortAuthorizationsClient.BeginDelete. +type ExpressRoutePortAuthorizationsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRoutePortAuthorizationsClientGetResponse contains the response from method ExpressRoutePortAuthorizationsClient.Get. +type ExpressRoutePortAuthorizationsClientGetResponse struct { + // ExpressRoutePort Authorization resource definition. + ExpressRoutePortAuthorization +} + +// ExpressRoutePortAuthorizationsClientListResponse contains the response from method ExpressRoutePortAuthorizationsClient.NewListPager. +type ExpressRoutePortAuthorizationsClientListResponse struct { + // Response for ListExpressRoutePortAuthorizations API service call. + ExpressRoutePortAuthorizationListResult +} + +// ExpressRoutePortsClientCreateOrUpdateResponse contains the response from method ExpressRoutePortsClient.BeginCreateOrUpdate. +type ExpressRoutePortsClientCreateOrUpdateResponse struct { + // ExpressRoutePort resource definition. + ExpressRoutePort +} + +// ExpressRoutePortsClientDeleteResponse contains the response from method ExpressRoutePortsClient.BeginDelete. +type ExpressRoutePortsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExpressRoutePortsClientGenerateLOAResponse contains the response from method ExpressRoutePortsClient.GenerateLOA. +type ExpressRoutePortsClientGenerateLOAResponse struct { + // Response for GenerateExpressRoutePortsLOA API service call. + GenerateExpressRoutePortsLOAResult +} + +// ExpressRoutePortsClientGetResponse contains the response from method ExpressRoutePortsClient.Get. +type ExpressRoutePortsClientGetResponse struct { + // ExpressRoutePort resource definition. + ExpressRoutePort +} + +// ExpressRoutePortsClientListByResourceGroupResponse contains the response from method ExpressRoutePortsClient.NewListByResourceGroupPager. +type ExpressRoutePortsClientListByResourceGroupResponse struct { + // Response for ListExpressRoutePorts API service call. + ExpressRoutePortListResult +} + +// ExpressRoutePortsClientListResponse contains the response from method ExpressRoutePortsClient.NewListPager. +type ExpressRoutePortsClientListResponse struct { + // Response for ListExpressRoutePorts API service call. + ExpressRoutePortListResult +} + +// ExpressRoutePortsClientUpdateTagsResponse contains the response from method ExpressRoutePortsClient.UpdateTags. +type ExpressRoutePortsClientUpdateTagsResponse struct { + // ExpressRoutePort resource definition. + ExpressRoutePort +} + +// ExpressRoutePortsLocationsClientGetResponse contains the response from method ExpressRoutePortsLocationsClient.Get. +type ExpressRoutePortsLocationsClientGetResponse struct { + // Definition of the ExpressRoutePorts peering location resource. + ExpressRoutePortsLocation +} + +// ExpressRoutePortsLocationsClientListResponse contains the response from method ExpressRoutePortsLocationsClient.NewListPager. +type ExpressRoutePortsLocationsClientListResponse struct { + // Response for ListExpressRoutePortsLocations API service call. + ExpressRoutePortsLocationListResult +} + +// ExpressRouteProviderPortsLocationClientListResponse contains the response from method ExpressRouteProviderPortsLocationClient.List. +type ExpressRouteProviderPortsLocationClientListResponse struct { + // Response for ListExpressRouteProviderPort API service call. + ExpressRouteProviderPortListResult +} + +// ExpressRouteServiceProvidersClientListResponse contains the response from method ExpressRouteServiceProvidersClient.NewListPager. +type ExpressRouteServiceProvidersClientListResponse struct { + // Response for the ListExpressRouteServiceProvider API service call. + ExpressRouteServiceProviderListResult +} + +// FirewallPoliciesClientCreateOrUpdateResponse contains the response from method FirewallPoliciesClient.BeginCreateOrUpdate. +type FirewallPoliciesClientCreateOrUpdateResponse struct { + // FirewallPolicy Resource. + FirewallPolicy +} + +// FirewallPoliciesClientDeleteResponse contains the response from method FirewallPoliciesClient.BeginDelete. +type FirewallPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// FirewallPoliciesClientGetResponse contains the response from method FirewallPoliciesClient.Get. +type FirewallPoliciesClientGetResponse struct { + // FirewallPolicy Resource. + FirewallPolicy +} + +// FirewallPoliciesClientListAllResponse contains the response from method FirewallPoliciesClient.NewListAllPager. +type FirewallPoliciesClientListAllResponse struct { + // Response for ListFirewallPolicies API service call. + FirewallPolicyListResult +} + +// FirewallPoliciesClientListResponse contains the response from method FirewallPoliciesClient.NewListPager. +type FirewallPoliciesClientListResponse struct { + // Response for ListFirewallPolicies API service call. + FirewallPolicyListResult +} + +// FirewallPoliciesClientUpdateTagsResponse contains the response from method FirewallPoliciesClient.UpdateTags. +type FirewallPoliciesClientUpdateTagsResponse struct { + // FirewallPolicy Resource. + FirewallPolicy +} + +// FirewallPolicyIdpsSignaturesClientListResponse contains the response from method FirewallPolicyIdpsSignaturesClient.List. +type FirewallPolicyIdpsSignaturesClientListResponse struct { + // Query result + QueryResults +} + +// FirewallPolicyIdpsSignaturesFilterValuesClientListResponse contains the response from method FirewallPolicyIdpsSignaturesFilterValuesClient.List. +type FirewallPolicyIdpsSignaturesFilterValuesClientListResponse struct { + // Describes the list of all possible values for a specific filter value + SignatureOverridesFilterValuesResponse +} + +// FirewallPolicyIdpsSignaturesOverridesClientGetResponse contains the response from method FirewallPolicyIdpsSignaturesOverridesClient.Get. +type FirewallPolicyIdpsSignaturesOverridesClientGetResponse struct { + // Contains all specific policy signatures overrides for the IDPS + SignaturesOverrides +} + +// FirewallPolicyIdpsSignaturesOverridesClientListResponse contains the response from method FirewallPolicyIdpsSignaturesOverridesClient.List. +type FirewallPolicyIdpsSignaturesOverridesClientListResponse struct { + // Describes an object containing an array with a single item + SignaturesOverridesList +} + +// FirewallPolicyIdpsSignaturesOverridesClientPatchResponse contains the response from method FirewallPolicyIdpsSignaturesOverridesClient.Patch. +type FirewallPolicyIdpsSignaturesOverridesClientPatchResponse struct { + // Contains all specific policy signatures overrides for the IDPS + SignaturesOverrides +} + +// FirewallPolicyIdpsSignaturesOverridesClientPutResponse contains the response from method FirewallPolicyIdpsSignaturesOverridesClient.Put. +type FirewallPolicyIdpsSignaturesOverridesClientPutResponse struct { + // Contains all specific policy signatures overrides for the IDPS + SignaturesOverrides +} + +// FirewallPolicyRuleCollectionGroupsClientCreateOrUpdateResponse contains the response from method FirewallPolicyRuleCollectionGroupsClient.BeginCreateOrUpdate. +type FirewallPolicyRuleCollectionGroupsClientCreateOrUpdateResponse struct { + // Rule Collection Group resource. + FirewallPolicyRuleCollectionGroup +} + +// FirewallPolicyRuleCollectionGroupsClientDeleteResponse contains the response from method FirewallPolicyRuleCollectionGroupsClient.BeginDelete. +type FirewallPolicyRuleCollectionGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// FirewallPolicyRuleCollectionGroupsClientGetResponse contains the response from method FirewallPolicyRuleCollectionGroupsClient.Get. +type FirewallPolicyRuleCollectionGroupsClientGetResponse struct { + // Rule Collection Group resource. + FirewallPolicyRuleCollectionGroup +} + +// FirewallPolicyRuleCollectionGroupsClientListResponse contains the response from method FirewallPolicyRuleCollectionGroupsClient.NewListPager. +type FirewallPolicyRuleCollectionGroupsClientListResponse struct { + // Response for ListFirewallPolicyRuleCollectionGroups API service call. + FirewallPolicyRuleCollectionGroupListResult +} + +// FlowLogsClientCreateOrUpdateResponse contains the response from method FlowLogsClient.BeginCreateOrUpdate. +type FlowLogsClientCreateOrUpdateResponse struct { + // A flow log resource. + FlowLog +} + +// FlowLogsClientDeleteResponse contains the response from method FlowLogsClient.BeginDelete. +type FlowLogsClientDeleteResponse struct { + // placeholder for future response values +} + +// FlowLogsClientGetResponse contains the response from method FlowLogsClient.Get. +type FlowLogsClientGetResponse struct { + // A flow log resource. + FlowLog +} + +// FlowLogsClientListResponse contains the response from method FlowLogsClient.NewListPager. +type FlowLogsClientListResponse struct { + // List of flow logs. + FlowLogListResult +} + +// FlowLogsClientUpdateTagsResponse contains the response from method FlowLogsClient.UpdateTags. +type FlowLogsClientUpdateTagsResponse struct { + // A flow log resource. + FlowLog +} + +// GroupsClientCreateOrUpdateResponse contains the response from method GroupsClient.CreateOrUpdate. +type GroupsClientCreateOrUpdateResponse struct { + // The network group resource + Group + + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// GroupsClientDeleteResponse contains the response from method GroupsClient.BeginDelete. +type GroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// GroupsClientGetResponse contains the response from method GroupsClient.Get. +type GroupsClientGetResponse struct { + // The network group resource + Group +} + +// GroupsClientListResponse contains the response from method GroupsClient.NewListPager. +type GroupsClientListResponse struct { + // Result of the request to list NetworkGroup. It contains a list of groups and a URL link to get the next set of results. + GroupListResult +} + +// HubRouteTablesClientCreateOrUpdateResponse contains the response from method HubRouteTablesClient.BeginCreateOrUpdate. +type HubRouteTablesClientCreateOrUpdateResponse struct { + // RouteTable resource in a virtual hub. + HubRouteTable +} + +// HubRouteTablesClientDeleteResponse contains the response from method HubRouteTablesClient.BeginDelete. +type HubRouteTablesClientDeleteResponse struct { + // placeholder for future response values +} + +// HubRouteTablesClientGetResponse contains the response from method HubRouteTablesClient.Get. +type HubRouteTablesClientGetResponse struct { + // RouteTable resource in a virtual hub. + HubRouteTable +} + +// HubRouteTablesClientListResponse contains the response from method HubRouteTablesClient.NewListPager. +type HubRouteTablesClientListResponse struct { + // List of RouteTables and a URL nextLink to get the next set of results. + ListHubRouteTablesResult +} + +// HubVirtualNetworkConnectionsClientCreateOrUpdateResponse contains the response from method HubVirtualNetworkConnectionsClient.BeginCreateOrUpdate. +type HubVirtualNetworkConnectionsClientCreateOrUpdateResponse struct { + // HubVirtualNetworkConnection Resource. + HubVirtualNetworkConnection +} + +// HubVirtualNetworkConnectionsClientDeleteResponse contains the response from method HubVirtualNetworkConnectionsClient.BeginDelete. +type HubVirtualNetworkConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// HubVirtualNetworkConnectionsClientGetResponse contains the response from method HubVirtualNetworkConnectionsClient.Get. +type HubVirtualNetworkConnectionsClientGetResponse struct { + // HubVirtualNetworkConnection Resource. + HubVirtualNetworkConnection +} + +// HubVirtualNetworkConnectionsClientListResponse contains the response from method HubVirtualNetworkConnectionsClient.NewListPager. +type HubVirtualNetworkConnectionsClientListResponse struct { + // List of HubVirtualNetworkConnections and a URL nextLink to get the next set of results. + ListHubVirtualNetworkConnectionsResult +} + +// IPAllocationsClientCreateOrUpdateResponse contains the response from method IPAllocationsClient.BeginCreateOrUpdate. +type IPAllocationsClientCreateOrUpdateResponse struct { + // IpAllocation resource. + IPAllocation +} + +// IPAllocationsClientDeleteResponse contains the response from method IPAllocationsClient.BeginDelete. +type IPAllocationsClientDeleteResponse struct { + // placeholder for future response values +} + +// IPAllocationsClientGetResponse contains the response from method IPAllocationsClient.Get. +type IPAllocationsClientGetResponse struct { + // IpAllocation resource. + IPAllocation +} + +// IPAllocationsClientListByResourceGroupResponse contains the response from method IPAllocationsClient.NewListByResourceGroupPager. +type IPAllocationsClientListByResourceGroupResponse struct { + // Response for the ListIpAllocations API service call. + IPAllocationListResult +} + +// IPAllocationsClientListResponse contains the response from method IPAllocationsClient.NewListPager. +type IPAllocationsClientListResponse struct { + // Response for the ListIpAllocations API service call. + IPAllocationListResult +} + +// IPAllocationsClientUpdateTagsResponse contains the response from method IPAllocationsClient.UpdateTags. +type IPAllocationsClientUpdateTagsResponse struct { + // IpAllocation resource. + IPAllocation +} + +// IPGroupsClientCreateOrUpdateResponse contains the response from method IPGroupsClient.BeginCreateOrUpdate. +type IPGroupsClientCreateOrUpdateResponse struct { + // The IpGroups resource information. + IPGroup +} + +// IPGroupsClientDeleteResponse contains the response from method IPGroupsClient.BeginDelete. +type IPGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// IPGroupsClientGetResponse contains the response from method IPGroupsClient.Get. +type IPGroupsClientGetResponse struct { + // The IpGroups resource information. + IPGroup +} + +// IPGroupsClientListByResourceGroupResponse contains the response from method IPGroupsClient.NewListByResourceGroupPager. +type IPGroupsClientListByResourceGroupResponse struct { + // Response for the ListIpGroups API service call. + IPGroupListResult +} + +// IPGroupsClientListResponse contains the response from method IPGroupsClient.NewListPager. +type IPGroupsClientListResponse struct { + // Response for the ListIpGroups API service call. + IPGroupListResult +} + +// IPGroupsClientUpdateGroupsResponse contains the response from method IPGroupsClient.UpdateGroups. +type IPGroupsClientUpdateGroupsResponse struct { + // The IpGroups resource information. + IPGroup +} + +// InboundNatRulesClientCreateOrUpdateResponse contains the response from method InboundNatRulesClient.BeginCreateOrUpdate. +type InboundNatRulesClientCreateOrUpdateResponse struct { + // Inbound NAT rule of the load balancer. + InboundNatRule +} + +// InboundNatRulesClientDeleteResponse contains the response from method InboundNatRulesClient.BeginDelete. +type InboundNatRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// InboundNatRulesClientGetResponse contains the response from method InboundNatRulesClient.Get. +type InboundNatRulesClientGetResponse struct { + // Inbound NAT rule of the load balancer. + InboundNatRule +} + +// InboundNatRulesClientListResponse contains the response from method InboundNatRulesClient.NewListPager. +type InboundNatRulesClientListResponse struct { + // Response for ListInboundNatRule API service call. + InboundNatRuleListResult +} + +// InboundSecurityRuleClientCreateOrUpdateResponse contains the response from method InboundSecurityRuleClient.BeginCreateOrUpdate. +type InboundSecurityRuleClientCreateOrUpdateResponse struct { + // NVA Inbound Security Rule resource. + InboundSecurityRule +} + +// InterfaceIPConfigurationsClientGetResponse contains the response from method InterfaceIPConfigurationsClient.Get. +type InterfaceIPConfigurationsClientGetResponse struct { + // IPConfiguration in a network interface. + InterfaceIPConfiguration +} + +// InterfaceIPConfigurationsClientListResponse contains the response from method InterfaceIPConfigurationsClient.NewListPager. +type InterfaceIPConfigurationsClientListResponse struct { + // Response for list ip configurations API service call. + InterfaceIPConfigurationListResult +} + +// InterfaceLoadBalancersClientListResponse contains the response from method InterfaceLoadBalancersClient.NewListPager. +type InterfaceLoadBalancersClientListResponse struct { + // Response for list ip configurations API service call. + InterfaceLoadBalancerListResult +} + +// InterfaceTapConfigurationsClientCreateOrUpdateResponse contains the response from method InterfaceTapConfigurationsClient.BeginCreateOrUpdate. +type InterfaceTapConfigurationsClientCreateOrUpdateResponse struct { + // Tap configuration in a Network Interface. + InterfaceTapConfiguration +} + +// InterfaceTapConfigurationsClientDeleteResponse contains the response from method InterfaceTapConfigurationsClient.BeginDelete. +type InterfaceTapConfigurationsClientDeleteResponse struct { + // placeholder for future response values +} + +// InterfaceTapConfigurationsClientGetResponse contains the response from method InterfaceTapConfigurationsClient.Get. +type InterfaceTapConfigurationsClientGetResponse struct { + // Tap configuration in a Network Interface. + InterfaceTapConfiguration +} + +// InterfaceTapConfigurationsClientListResponse contains the response from method InterfaceTapConfigurationsClient.NewListPager. +type InterfaceTapConfigurationsClientListResponse struct { + // Response for list tap configurations API service call. + InterfaceTapConfigurationListResult +} + +// InterfacesClientCreateOrUpdateResponse contains the response from method InterfacesClient.BeginCreateOrUpdate. +type InterfacesClientCreateOrUpdateResponse struct { + // A network interface in a resource group. + Interface +} + +// InterfacesClientDeleteResponse contains the response from method InterfacesClient.BeginDelete. +type InterfacesClientDeleteResponse struct { + // placeholder for future response values +} + +// InterfacesClientGetCloudServiceNetworkInterfaceResponse contains the response from method InterfacesClient.GetCloudServiceNetworkInterface. +type InterfacesClientGetCloudServiceNetworkInterfaceResponse struct { + // A network interface in a resource group. + Interface +} + +// InterfacesClientGetEffectiveRouteTableResponse contains the response from method InterfacesClient.BeginGetEffectiveRouteTable. +type InterfacesClientGetEffectiveRouteTableResponse struct { + // Response for list effective route API service call. + EffectiveRouteListResult +} + +// InterfacesClientGetResponse contains the response from method InterfacesClient.Get. +type InterfacesClientGetResponse struct { + // A network interface in a resource group. + Interface +} + +// InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse contains the response from method InterfacesClient.GetVirtualMachineScaleSetIPConfiguration. +type InterfacesClientGetVirtualMachineScaleSetIPConfigurationResponse struct { + // IPConfiguration in a network interface. + InterfaceIPConfiguration +} + +// InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse contains the response from method InterfacesClient.GetVirtualMachineScaleSetNetworkInterface. +type InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse struct { + // A network interface in a resource group. + Interface +} + +// InterfacesClientListAllResponse contains the response from method InterfacesClient.NewListAllPager. +type InterfacesClientListAllResponse struct { + // Response for the ListNetworkInterface API service call. + InterfaceListResult +} + +// InterfacesClientListCloudServiceNetworkInterfacesResponse contains the response from method InterfacesClient.NewListCloudServiceNetworkInterfacesPager. +type InterfacesClientListCloudServiceNetworkInterfacesResponse struct { + // Response for the ListNetworkInterface API service call. + InterfaceListResult +} + +// InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse contains the response from method InterfacesClient.NewListCloudServiceRoleInstanceNetworkInterfacesPager. +type InterfacesClientListCloudServiceRoleInstanceNetworkInterfacesResponse struct { + // Response for the ListNetworkInterface API service call. + InterfaceListResult +} + +// InterfacesClientListEffectiveNetworkSecurityGroupsResponse contains the response from method InterfacesClient.BeginListEffectiveNetworkSecurityGroups. +type InterfacesClientListEffectiveNetworkSecurityGroupsResponse struct { + // Response for list effective network security groups API service call. + EffectiveNetworkSecurityGroupListResult +} + +// InterfacesClientListResponse contains the response from method InterfacesClient.NewListPager. +type InterfacesClientListResponse struct { + // Response for the ListNetworkInterface API service call. + InterfaceListResult +} + +// InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse contains the response from method InterfacesClient.NewListVirtualMachineScaleSetIPConfigurationsPager. +type InterfacesClientListVirtualMachineScaleSetIPConfigurationsResponse struct { + // Response for list ip configurations API service call. + InterfaceIPConfigurationListResult +} + +// InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse contains the response from method InterfacesClient.NewListVirtualMachineScaleSetNetworkInterfacesPager. +type InterfacesClientListVirtualMachineScaleSetNetworkInterfacesResponse struct { + // Response for the ListNetworkInterface API service call. + InterfaceListResult +} + +// InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse contains the response from method InterfacesClient.NewListVirtualMachineScaleSetVMNetworkInterfacesPager. +type InterfacesClientListVirtualMachineScaleSetVMNetworkInterfacesResponse struct { + // Response for the ListNetworkInterface API service call. + InterfaceListResult +} + +// InterfacesClientUpdateTagsResponse contains the response from method InterfacesClient.UpdateTags. +type InterfacesClientUpdateTagsResponse struct { + // A network interface in a resource group. + Interface +} + +// LoadBalancerBackendAddressPoolsClientCreateOrUpdateResponse contains the response from method LoadBalancerBackendAddressPoolsClient.BeginCreateOrUpdate. +type LoadBalancerBackendAddressPoolsClientCreateOrUpdateResponse struct { + // Pool of backend IP addresses. + BackendAddressPool +} + +// LoadBalancerBackendAddressPoolsClientDeleteResponse contains the response from method LoadBalancerBackendAddressPoolsClient.BeginDelete. +type LoadBalancerBackendAddressPoolsClientDeleteResponse struct { + // placeholder for future response values +} + +// LoadBalancerBackendAddressPoolsClientGetResponse contains the response from method LoadBalancerBackendAddressPoolsClient.Get. +type LoadBalancerBackendAddressPoolsClientGetResponse struct { + // Pool of backend IP addresses. + BackendAddressPool +} + +// LoadBalancerBackendAddressPoolsClientListResponse contains the response from method LoadBalancerBackendAddressPoolsClient.NewListPager. +type LoadBalancerBackendAddressPoolsClientListResponse struct { + // Response for ListBackendAddressPool API service call. + LoadBalancerBackendAddressPoolListResult +} + +// LoadBalancerFrontendIPConfigurationsClientGetResponse contains the response from method LoadBalancerFrontendIPConfigurationsClient.Get. +type LoadBalancerFrontendIPConfigurationsClientGetResponse struct { + // Frontend IP address of the load balancer. + FrontendIPConfiguration +} + +// LoadBalancerFrontendIPConfigurationsClientListResponse contains the response from method LoadBalancerFrontendIPConfigurationsClient.NewListPager. +type LoadBalancerFrontendIPConfigurationsClientListResponse struct { + // Response for ListFrontendIPConfiguration API service call. + LoadBalancerFrontendIPConfigurationListResult +} + +// LoadBalancerLoadBalancingRulesClientGetResponse contains the response from method LoadBalancerLoadBalancingRulesClient.Get. +type LoadBalancerLoadBalancingRulesClientGetResponse struct { + // A load balancing rule for a load balancer. + LoadBalancingRule +} + +// LoadBalancerLoadBalancingRulesClientListResponse contains the response from method LoadBalancerLoadBalancingRulesClient.NewListPager. +type LoadBalancerLoadBalancingRulesClientListResponse struct { + // Response for ListLoadBalancingRule API service call. + LoadBalancerLoadBalancingRuleListResult +} + +// LoadBalancerNetworkInterfacesClientListResponse contains the response from method LoadBalancerNetworkInterfacesClient.NewListPager. +type LoadBalancerNetworkInterfacesClientListResponse struct { + // Response for the ListNetworkInterface API service call. + InterfaceListResult +} + +// LoadBalancerOutboundRulesClientGetResponse contains the response from method LoadBalancerOutboundRulesClient.Get. +type LoadBalancerOutboundRulesClientGetResponse struct { + // Outbound rule of the load balancer. + OutboundRule +} + +// LoadBalancerOutboundRulesClientListResponse contains the response from method LoadBalancerOutboundRulesClient.NewListPager. +type LoadBalancerOutboundRulesClientListResponse struct { + // Response for ListOutboundRule API service call. + LoadBalancerOutboundRuleListResult +} + +// LoadBalancerProbesClientGetResponse contains the response from method LoadBalancerProbesClient.Get. +type LoadBalancerProbesClientGetResponse struct { + // A load balancer probe. + Probe +} + +// LoadBalancerProbesClientListResponse contains the response from method LoadBalancerProbesClient.NewListPager. +type LoadBalancerProbesClientListResponse struct { + // Response for ListProbe API service call. + LoadBalancerProbeListResult +} + +// LoadBalancersClientCreateOrUpdateResponse contains the response from method LoadBalancersClient.BeginCreateOrUpdate. +type LoadBalancersClientCreateOrUpdateResponse struct { + // LoadBalancer resource. + LoadBalancer +} + +// LoadBalancersClientDeleteResponse contains the response from method LoadBalancersClient.BeginDelete. +type LoadBalancersClientDeleteResponse struct { + // placeholder for future response values +} + +// LoadBalancersClientGetResponse contains the response from method LoadBalancersClient.Get. +type LoadBalancersClientGetResponse struct { + // LoadBalancer resource. + LoadBalancer +} + +// LoadBalancersClientListAllResponse contains the response from method LoadBalancersClient.NewListAllPager. +type LoadBalancersClientListAllResponse struct { + // Response for ListLoadBalancers API service call. + LoadBalancerListResult +} + +// LoadBalancersClientListInboundNatRulePortMappingsResponse contains the response from method LoadBalancersClient.BeginListInboundNatRulePortMappings. +type LoadBalancersClientListInboundNatRulePortMappingsResponse struct { + // The response for a QueryInboundNatRulePortMapping API. + BackendAddressInboundNatRulePortMappings +} + +// LoadBalancersClientListResponse contains the response from method LoadBalancersClient.NewListPager. +type LoadBalancersClientListResponse struct { + // Response for ListLoadBalancers API service call. + LoadBalancerListResult +} + +// LoadBalancersClientMigrateToIPBasedResponse contains the response from method LoadBalancersClient.MigrateToIPBased. +type LoadBalancersClientMigrateToIPBasedResponse struct { + // The response for a migrateToIpBased API. + MigratedPools +} + +// LoadBalancersClientSwapPublicIPAddressesResponse contains the response from method LoadBalancersClient.BeginSwapPublicIPAddresses. +type LoadBalancersClientSwapPublicIPAddressesResponse struct { + // placeholder for future response values +} + +// LoadBalancersClientUpdateTagsResponse contains the response from method LoadBalancersClient.UpdateTags. +type LoadBalancersClientUpdateTagsResponse struct { + // LoadBalancer resource. + LoadBalancer +} + +// LocalNetworkGatewaysClientCreateOrUpdateResponse contains the response from method LocalNetworkGatewaysClient.BeginCreateOrUpdate. +type LocalNetworkGatewaysClientCreateOrUpdateResponse struct { + // A common class for general resource information. + LocalNetworkGateway +} + +// LocalNetworkGatewaysClientDeleteResponse contains the response from method LocalNetworkGatewaysClient.BeginDelete. +type LocalNetworkGatewaysClientDeleteResponse struct { + // placeholder for future response values +} + +// LocalNetworkGatewaysClientGetResponse contains the response from method LocalNetworkGatewaysClient.Get. +type LocalNetworkGatewaysClientGetResponse struct { + // A common class for general resource information. + LocalNetworkGateway +} + +// LocalNetworkGatewaysClientListResponse contains the response from method LocalNetworkGatewaysClient.NewListPager. +type LocalNetworkGatewaysClientListResponse struct { + // Response for ListLocalNetworkGateways API service call. + LocalNetworkGatewayListResult +} + +// LocalNetworkGatewaysClientUpdateTagsResponse contains the response from method LocalNetworkGatewaysClient.UpdateTags. +type LocalNetworkGatewaysClientUpdateTagsResponse struct { + // A common class for general resource information. + LocalNetworkGateway +} + +// ManagementClientCheckDNSNameAvailabilityResponse contains the response from method ManagementClient.CheckDNSNameAvailability. +type ManagementClientCheckDNSNameAvailabilityResponse struct { + // Response for the CheckDnsNameAvailability API service call. + DNSNameAvailabilityResult +} + +// ManagementClientDeleteBastionShareableLinkResponse contains the response from method ManagementClient.BeginDeleteBastionShareableLink. +type ManagementClientDeleteBastionShareableLinkResponse struct { + // placeholder for future response values +} + +// ManagementClientDisconnectActiveSessionsResponse contains the response from method ManagementClient.NewDisconnectActiveSessionsPager. +type ManagementClientDisconnectActiveSessionsResponse struct { + // Response for DisconnectActiveSessions. + BastionSessionDeleteResult +} + +// ManagementClientExpressRouteProviderPortResponse contains the response from method ManagementClient.ExpressRouteProviderPort. +type ManagementClientExpressRouteProviderPortResponse struct { + // ExpressRouteProviderPort resource. + ExpressRouteProviderPort +} + +// ManagementClientGeneratevirtualwanvpnserverconfigurationvpnprofileResponse contains the response from method ManagementClient.BeginGeneratevirtualwanvpnserverconfigurationvpnprofile. +type ManagementClientGeneratevirtualwanvpnserverconfigurationvpnprofileResponse struct { + // Vpn Profile Response for package generation. + VPNProfileResponse +} + +// ManagementClientGetActiveSessionsResponse contains the response from method ManagementClient.BeginGetActiveSessions. +type ManagementClientGetActiveSessionsResponse struct { + // Response for GetActiveSessions. + BastionActiveSessionListResult +} + +// ManagementClientGetBastionShareableLinkResponse contains the response from method ManagementClient.NewGetBastionShareableLinkPager. +type ManagementClientGetBastionShareableLinkResponse struct { + // Response for all the Bastion Shareable Link endpoints. + BastionShareableLinkListResult +} + +// ManagementClientListActiveConnectivityConfigurationsResponse contains the response from method ManagementClient.ListActiveConnectivityConfigurations. +type ManagementClientListActiveConnectivityConfigurationsResponse struct { + // Result of the request to list active connectivity configurations. It contains a list of active connectivity configurations + // and a skiptoken to get the next set of results. + ActiveConnectivityConfigurationsListResult +} + +// ManagementClientListActiveSecurityAdminRulesResponse contains the response from method ManagementClient.ListActiveSecurityAdminRules. +type ManagementClientListActiveSecurityAdminRulesResponse struct { + // Result of the request to list active security admin rules. It contains a list of active security admin rules and a skiptoken + // to get the next set of results. + ActiveSecurityAdminRulesListResult +} + +// ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse contains the response from method ManagementClient.ListNetworkManagerEffectiveConnectivityConfigurations. +type ManagementClientListNetworkManagerEffectiveConnectivityConfigurationsResponse struct { + // Result of the request to list networkManagerEffectiveConnectivityConfiguration. It contains a list of groups and a skiptoken + // to get the next set of results. + ManagerEffectiveConnectivityConfigurationListResult +} + +// ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse contains the response from method ManagementClient.ListNetworkManagerEffectiveSecurityAdminRules. +type ManagementClientListNetworkManagerEffectiveSecurityAdminRulesResponse struct { + // Result of the request to list networkManagerEffectiveSecurityAdminRules. It contains a list of groups and a skiptoken to + // get the next set of results. + ManagerEffectiveSecurityAdminRulesListResult +} + +// ManagementClientPutBastionShareableLinkResponse contains the response from method ManagementClient.BeginPutBastionShareableLink. +type ManagementClientPutBastionShareableLinkResponse struct { + // Response for all the Bastion Shareable Link endpoints. + BastionShareableLinkListResult +} + +// ManagementClientSupportedSecurityProvidersResponse contains the response from method ManagementClient.SupportedSecurityProviders. +type ManagementClientSupportedSecurityProvidersResponse struct { + // Collection of SecurityProviders. + VirtualWanSecurityProviders +} + +// ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse contains the response from method ManagementGroupNetworkManagerConnectionsClient.CreateOrUpdate. +type ManagementGroupNetworkManagerConnectionsClientCreateOrUpdateResponse struct { + // The Network Manager Connection resource + ManagerConnection +} + +// ManagementGroupNetworkManagerConnectionsClientDeleteResponse contains the response from method ManagementGroupNetworkManagerConnectionsClient.Delete. +type ManagementGroupNetworkManagerConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ManagementGroupNetworkManagerConnectionsClientGetResponse contains the response from method ManagementGroupNetworkManagerConnectionsClient.Get. +type ManagementGroupNetworkManagerConnectionsClientGetResponse struct { + // The Network Manager Connection resource + ManagerConnection +} + +// ManagementGroupNetworkManagerConnectionsClientListResponse contains the response from method ManagementGroupNetworkManagerConnectionsClient.NewListPager. +type ManagementGroupNetworkManagerConnectionsClientListResponse struct { + // List of network manager connections. + ManagerConnectionListResult +} + +// ManagerCommitsClientPostResponse contains the response from method ManagerCommitsClient.BeginPost. +type ManagerCommitsClientPostResponse struct { + // Network Manager Commit. + ManagerCommit +} + +// ManagerDeploymentStatusClientListResponse contains the response from method ManagerDeploymentStatusClient.List. +type ManagerDeploymentStatusClientListResponse struct { + // A list of Network Manager Deployment Status + ManagerDeploymentStatusListResult +} + +// ManagersClientCreateOrUpdateResponse contains the response from method ManagersClient.CreateOrUpdate. +type ManagersClientCreateOrUpdateResponse struct { + // The Managed Network resource + Manager +} + +// ManagersClientDeleteResponse contains the response from method ManagersClient.BeginDelete. +type ManagersClientDeleteResponse struct { + // placeholder for future response values +} + +// ManagersClientGetResponse contains the response from method ManagersClient.Get. +type ManagersClientGetResponse struct { + // The Managed Network resource + Manager +} + +// ManagersClientListBySubscriptionResponse contains the response from method ManagersClient.NewListBySubscriptionPager. +type ManagersClientListBySubscriptionResponse struct { + // Result of the request to list NetworkManager. It contains a list of network managers and a URL link to get the next set + // of results. + ManagerListResult +} + +// ManagersClientListResponse contains the response from method ManagersClient.NewListPager. +type ManagersClientListResponse struct { + // Result of the request to list NetworkManager. It contains a list of network managers and a URL link to get the next set + // of results. + ManagerListResult +} + +// ManagersClientPatchResponse contains the response from method ManagersClient.Patch. +type ManagersClientPatchResponse struct { + // The Managed Network resource + Manager +} + +// NatGatewaysClientCreateOrUpdateResponse contains the response from method NatGatewaysClient.BeginCreateOrUpdate. +type NatGatewaysClientCreateOrUpdateResponse struct { + // Nat Gateway resource. + NatGateway +} + +// NatGatewaysClientDeleteResponse contains the response from method NatGatewaysClient.BeginDelete. +type NatGatewaysClientDeleteResponse struct { + // placeholder for future response values +} + +// NatGatewaysClientGetResponse contains the response from method NatGatewaysClient.Get. +type NatGatewaysClientGetResponse struct { + // Nat Gateway resource. + NatGateway +} + +// NatGatewaysClientListAllResponse contains the response from method NatGatewaysClient.NewListAllPager. +type NatGatewaysClientListAllResponse struct { + // Response for ListNatGateways API service call. + NatGatewayListResult +} + +// NatGatewaysClientListResponse contains the response from method NatGatewaysClient.NewListPager. +type NatGatewaysClientListResponse struct { + // Response for ListNatGateways API service call. + NatGatewayListResult +} + +// NatGatewaysClientUpdateTagsResponse contains the response from method NatGatewaysClient.UpdateTags. +type NatGatewaysClientUpdateTagsResponse struct { + // Nat Gateway resource. + NatGateway +} + +// NatRulesClientCreateOrUpdateResponse contains the response from method NatRulesClient.BeginCreateOrUpdate. +type NatRulesClientCreateOrUpdateResponse struct { + // VpnGatewayNatRule Resource. + VPNGatewayNatRule +} + +// NatRulesClientDeleteResponse contains the response from method NatRulesClient.BeginDelete. +type NatRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// NatRulesClientGetResponse contains the response from method NatRulesClient.Get. +type NatRulesClientGetResponse struct { + // VpnGatewayNatRule Resource. + VPNGatewayNatRule +} + +// NatRulesClientListByVPNGatewayResponse contains the response from method NatRulesClient.NewListByVPNGatewayPager. +type NatRulesClientListByVPNGatewayResponse struct { + // Result of the request to list all nat rules to a virtual wan vpn gateway. It contains a list of Nat rules and a URL nextLink + // to get the next set of results. + ListVPNGatewayNatRulesResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // Result of the request to list Network operations. It contains a list of operations and a URL link to get the next set of + // results. + OperationListResult +} + +// P2SVPNGatewaysClientCreateOrUpdateResponse contains the response from method P2SVPNGatewaysClient.BeginCreateOrUpdate. +type P2SVPNGatewaysClientCreateOrUpdateResponse struct { + // P2SVpnGateway Resource. + P2SVPNGateway +} + +// P2SVPNGatewaysClientDeleteResponse contains the response from method P2SVPNGatewaysClient.BeginDelete. +type P2SVPNGatewaysClientDeleteResponse struct { + // placeholder for future response values +} + +// P2SVPNGatewaysClientDisconnectP2SVPNConnectionsResponse contains the response from method P2SVPNGatewaysClient.BeginDisconnectP2SVPNConnections. +type P2SVPNGatewaysClientDisconnectP2SVPNConnectionsResponse struct { + // placeholder for future response values +} + +// P2SVPNGatewaysClientGenerateVPNProfileResponse contains the response from method P2SVPNGatewaysClient.BeginGenerateVPNProfile. +type P2SVPNGatewaysClientGenerateVPNProfileResponse struct { + // Vpn Profile Response for package generation. + VPNProfileResponse +} + +// P2SVPNGatewaysClientGetP2SVPNConnectionHealthDetailedResponse contains the response from method P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealthDetailed. +type P2SVPNGatewaysClientGetP2SVPNConnectionHealthDetailedResponse struct { + // P2S Vpn connection detailed health written to sas url. + P2SVPNConnectionHealth +} + +// P2SVPNGatewaysClientGetP2SVPNConnectionHealthResponse contains the response from method P2SVPNGatewaysClient.BeginGetP2SVPNConnectionHealth. +type P2SVPNGatewaysClientGetP2SVPNConnectionHealthResponse struct { + // P2SVpnGateway Resource. + P2SVPNGateway +} + +// P2SVPNGatewaysClientGetResponse contains the response from method P2SVPNGatewaysClient.Get. +type P2SVPNGatewaysClientGetResponse struct { + // P2SVpnGateway Resource. + P2SVPNGateway +} + +// P2SVPNGatewaysClientListByResourceGroupResponse contains the response from method P2SVPNGatewaysClient.NewListByResourceGroupPager. +type P2SVPNGatewaysClientListByResourceGroupResponse struct { + // Result of the request to list P2SVpnGateways. It contains a list of P2SVpnGateways and a URL nextLink to get the next set + // of results. + ListP2SVPNGatewaysResult +} + +// P2SVPNGatewaysClientListResponse contains the response from method P2SVPNGatewaysClient.NewListPager. +type P2SVPNGatewaysClientListResponse struct { + // Result of the request to list P2SVpnGateways. It contains a list of P2SVpnGateways and a URL nextLink to get the next set + // of results. + ListP2SVPNGatewaysResult +} + +// P2SVPNGatewaysClientResetResponse contains the response from method P2SVPNGatewaysClient.BeginReset. +type P2SVPNGatewaysClientResetResponse struct { + // P2SVpnGateway Resource. + P2SVPNGateway +} + +// P2SVPNGatewaysClientUpdateTagsResponse contains the response from method P2SVPNGatewaysClient.BeginUpdateTags. +type P2SVPNGatewaysClientUpdateTagsResponse struct { + // P2SVpnGateway Resource. + P2SVPNGateway +} + +// PacketCapturesClientCreateResponse contains the response from method PacketCapturesClient.BeginCreate. +type PacketCapturesClientCreateResponse struct { + // Information about packet capture session. + PacketCaptureResult +} + +// PacketCapturesClientDeleteResponse contains the response from method PacketCapturesClient.BeginDelete. +type PacketCapturesClientDeleteResponse struct { + // placeholder for future response values +} + +// PacketCapturesClientGetResponse contains the response from method PacketCapturesClient.Get. +type PacketCapturesClientGetResponse struct { + // Information about packet capture session. + PacketCaptureResult +} + +// PacketCapturesClientGetStatusResponse contains the response from method PacketCapturesClient.BeginGetStatus. +type PacketCapturesClientGetStatusResponse struct { + // Status of packet capture session. + PacketCaptureQueryStatusResult +} + +// PacketCapturesClientListResponse contains the response from method PacketCapturesClient.NewListPager. +type PacketCapturesClientListResponse struct { + // List of packet capture sessions. + PacketCaptureListResult +} + +// PacketCapturesClientStopResponse contains the response from method PacketCapturesClient.BeginStop. +type PacketCapturesClientStopResponse struct { + // placeholder for future response values +} + +// PeerExpressRouteCircuitConnectionsClientGetResponse contains the response from method PeerExpressRouteCircuitConnectionsClient.Get. +type PeerExpressRouteCircuitConnectionsClientGetResponse struct { + // Peer Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. + PeerExpressRouteCircuitConnection +} + +// PeerExpressRouteCircuitConnectionsClientListResponse contains the response from method PeerExpressRouteCircuitConnectionsClient.NewListPager. +type PeerExpressRouteCircuitConnectionsClientListResponse struct { + // Response for ListPeeredConnections API service call retrieves all global reach peer circuit connections that belongs to + // a Private Peering for an ExpressRouteCircuit. + PeerExpressRouteCircuitConnectionListResult +} + +// PrivateDNSZoneGroupsClientCreateOrUpdateResponse contains the response from method PrivateDNSZoneGroupsClient.BeginCreateOrUpdate. +type PrivateDNSZoneGroupsClientCreateOrUpdateResponse struct { + // Private dns zone group resource. + PrivateDNSZoneGroup +} + +// PrivateDNSZoneGroupsClientDeleteResponse contains the response from method PrivateDNSZoneGroupsClient.BeginDelete. +type PrivateDNSZoneGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// PrivateDNSZoneGroupsClientGetResponse contains the response from method PrivateDNSZoneGroupsClient.Get. +type PrivateDNSZoneGroupsClientGetResponse struct { + // Private dns zone group resource. + PrivateDNSZoneGroup +} + +// PrivateDNSZoneGroupsClientListResponse contains the response from method PrivateDNSZoneGroupsClient.NewListPager. +type PrivateDNSZoneGroupsClientListResponse struct { + // Response for the ListPrivateDnsZoneGroups API service call. + PrivateDNSZoneGroupListResult +} + +// PrivateEndpointsClientCreateOrUpdateResponse contains the response from method PrivateEndpointsClient.BeginCreateOrUpdate. +type PrivateEndpointsClientCreateOrUpdateResponse struct { + // Private endpoint resource. + PrivateEndpoint +} + +// PrivateEndpointsClientDeleteResponse contains the response from method PrivateEndpointsClient.BeginDelete. +type PrivateEndpointsClientDeleteResponse struct { + // placeholder for future response values +} + +// PrivateEndpointsClientGetResponse contains the response from method PrivateEndpointsClient.Get. +type PrivateEndpointsClientGetResponse struct { + // Private endpoint resource. + PrivateEndpoint +} + +// PrivateEndpointsClientListBySubscriptionResponse contains the response from method PrivateEndpointsClient.NewListBySubscriptionPager. +type PrivateEndpointsClientListBySubscriptionResponse struct { + // Response for the ListPrivateEndpoints API service call. + PrivateEndpointListResult +} + +// PrivateEndpointsClientListResponse contains the response from method PrivateEndpointsClient.NewListPager. +type PrivateEndpointsClientListResponse struct { + // Response for the ListPrivateEndpoints API service call. + PrivateEndpointListResult +} + +// PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityByResourceGroupResponse contains the response from method PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibilityByResourceGroup. +type PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityByResourceGroupResponse struct { + // Response for the CheckPrivateLinkServiceVisibility API service call. + PrivateLinkServiceVisibility +} + +// PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityResponse contains the response from method PrivateLinkServicesClient.BeginCheckPrivateLinkServiceVisibility. +type PrivateLinkServicesClientCheckPrivateLinkServiceVisibilityResponse struct { + // Response for the CheckPrivateLinkServiceVisibility API service call. + PrivateLinkServiceVisibility +} + +// PrivateLinkServicesClientCreateOrUpdateResponse contains the response from method PrivateLinkServicesClient.BeginCreateOrUpdate. +type PrivateLinkServicesClientCreateOrUpdateResponse struct { + // Private link service resource. + PrivateLinkService +} + +// PrivateLinkServicesClientDeletePrivateEndpointConnectionResponse contains the response from method PrivateLinkServicesClient.BeginDeletePrivateEndpointConnection. +type PrivateLinkServicesClientDeletePrivateEndpointConnectionResponse struct { + // placeholder for future response values +} + +// PrivateLinkServicesClientDeleteResponse contains the response from method PrivateLinkServicesClient.BeginDelete. +type PrivateLinkServicesClientDeleteResponse struct { + // placeholder for future response values +} + +// PrivateLinkServicesClientGetPrivateEndpointConnectionResponse contains the response from method PrivateLinkServicesClient.GetPrivateEndpointConnection. +type PrivateLinkServicesClientGetPrivateEndpointConnectionResponse struct { + // PrivateEndpointConnection resource. + PrivateEndpointConnection +} + +// PrivateLinkServicesClientGetResponse contains the response from method PrivateLinkServicesClient.Get. +type PrivateLinkServicesClientGetResponse struct { + // Private link service resource. + PrivateLinkService +} + +// PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse contains the response from method PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesByResourceGroupPager. +type PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesByResourceGroupResponse struct { + // An array of private link service id that can be linked to a private end point with auto approved. + AutoApprovedPrivateLinkServicesResult +} + +// PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse contains the response from method PrivateLinkServicesClient.NewListAutoApprovedPrivateLinkServicesPager. +type PrivateLinkServicesClientListAutoApprovedPrivateLinkServicesResponse struct { + // An array of private link service id that can be linked to a private end point with auto approved. + AutoApprovedPrivateLinkServicesResult +} + +// PrivateLinkServicesClientListBySubscriptionResponse contains the response from method PrivateLinkServicesClient.NewListBySubscriptionPager. +type PrivateLinkServicesClientListBySubscriptionResponse struct { + // Response for the ListPrivateLinkService API service call. + PrivateLinkServiceListResult +} + +// PrivateLinkServicesClientListPrivateEndpointConnectionsResponse contains the response from method PrivateLinkServicesClient.NewListPrivateEndpointConnectionsPager. +type PrivateLinkServicesClientListPrivateEndpointConnectionsResponse struct { + // Response for the ListPrivateEndpointConnection API service call. + PrivateEndpointConnectionListResult +} + +// PrivateLinkServicesClientListResponse contains the response from method PrivateLinkServicesClient.NewListPager. +type PrivateLinkServicesClientListResponse struct { + // Response for the ListPrivateLinkService API service call. + PrivateLinkServiceListResult +} + +// PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse contains the response from method PrivateLinkServicesClient.UpdatePrivateEndpointConnection. +type PrivateLinkServicesClientUpdatePrivateEndpointConnectionResponse struct { + // PrivateEndpointConnection resource. + PrivateEndpointConnection +} + +// ProfilesClientCreateOrUpdateResponse contains the response from method ProfilesClient.CreateOrUpdate. +type ProfilesClientCreateOrUpdateResponse struct { + // Network profile resource. + Profile +} + +// ProfilesClientDeleteResponse contains the response from method ProfilesClient.BeginDelete. +type ProfilesClientDeleteResponse struct { + // placeholder for future response values +} + +// ProfilesClientGetResponse contains the response from method ProfilesClient.Get. +type ProfilesClientGetResponse struct { + // Network profile resource. + Profile +} + +// ProfilesClientListAllResponse contains the response from method ProfilesClient.NewListAllPager. +type ProfilesClientListAllResponse struct { + // Response for ListNetworkProfiles API service call. + ProfileListResult +} + +// ProfilesClientListResponse contains the response from method ProfilesClient.NewListPager. +type ProfilesClientListResponse struct { + // Response for ListNetworkProfiles API service call. + ProfileListResult +} + +// ProfilesClientUpdateTagsResponse contains the response from method ProfilesClient.UpdateTags. +type ProfilesClientUpdateTagsResponse struct { + // Network profile resource. + Profile +} + +// PublicIPAddressesClientCreateOrUpdateResponse contains the response from method PublicIPAddressesClient.BeginCreateOrUpdate. +type PublicIPAddressesClientCreateOrUpdateResponse struct { + // Public IP address resource. + PublicIPAddress +} + +// PublicIPAddressesClientDdosProtectionStatusResponse contains the response from method PublicIPAddressesClient.BeginDdosProtectionStatus. +type PublicIPAddressesClientDdosProtectionStatusResponse struct { + // Response for GetPublicIpAddressDdosProtectionStatusOperation API service call. + PublicIPDdosProtectionStatusResult +} + +// PublicIPAddressesClientDeleteResponse contains the response from method PublicIPAddressesClient.BeginDelete. +type PublicIPAddressesClientDeleteResponse struct { + // placeholder for future response values +} + +// PublicIPAddressesClientGetCloudServicePublicIPAddressResponse contains the response from method PublicIPAddressesClient.GetCloudServicePublicIPAddress. +type PublicIPAddressesClientGetCloudServicePublicIPAddressResponse struct { + // Public IP address resource. + PublicIPAddress +} + +// PublicIPAddressesClientGetResponse contains the response from method PublicIPAddressesClient.Get. +type PublicIPAddressesClientGetResponse struct { + // Public IP address resource. + PublicIPAddress +} + +// PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse contains the response from method PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress. +type PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse struct { + // Public IP address resource. + PublicIPAddress +} + +// PublicIPAddressesClientListAllResponse contains the response from method PublicIPAddressesClient.NewListAllPager. +type PublicIPAddressesClientListAllResponse struct { + // Response for ListPublicIpAddresses API service call. + PublicIPAddressListResult +} + +// PublicIPAddressesClientListCloudServicePublicIPAddressesResponse contains the response from method PublicIPAddressesClient.NewListCloudServicePublicIPAddressesPager. +type PublicIPAddressesClientListCloudServicePublicIPAddressesResponse struct { + // Response for ListPublicIpAddresses API service call. + PublicIPAddressListResult +} + +// PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse contains the response from method PublicIPAddressesClient.NewListCloudServiceRoleInstancePublicIPAddressesPager. +type PublicIPAddressesClientListCloudServiceRoleInstancePublicIPAddressesResponse struct { + // Response for ListPublicIpAddresses API service call. + PublicIPAddressListResult +} + +// PublicIPAddressesClientListResponse contains the response from method PublicIPAddressesClient.NewListPager. +type PublicIPAddressesClientListResponse struct { + // Response for ListPublicIpAddresses API service call. + PublicIPAddressListResult +} + +// PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse contains the response from method PublicIPAddressesClient.NewListVirtualMachineScaleSetPublicIPAddressesPager. +type PublicIPAddressesClientListVirtualMachineScaleSetPublicIPAddressesResponse struct { + // Response for ListPublicIpAddresses API service call. + PublicIPAddressListResult +} + +// PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse contains the response from method PublicIPAddressesClient.NewListVirtualMachineScaleSetVMPublicIPAddressesPager. +type PublicIPAddressesClientListVirtualMachineScaleSetVMPublicIPAddressesResponse struct { + // Response for ListPublicIpAddresses API service call. + PublicIPAddressListResult +} + +// PublicIPAddressesClientUpdateTagsResponse contains the response from method PublicIPAddressesClient.UpdateTags. +type PublicIPAddressesClientUpdateTagsResponse struct { + // Public IP address resource. + PublicIPAddress +} + +// PublicIPPrefixesClientCreateOrUpdateResponse contains the response from method PublicIPPrefixesClient.BeginCreateOrUpdate. +type PublicIPPrefixesClientCreateOrUpdateResponse struct { + // Public IP prefix resource. + PublicIPPrefix +} + +// PublicIPPrefixesClientDeleteResponse contains the response from method PublicIPPrefixesClient.BeginDelete. +type PublicIPPrefixesClientDeleteResponse struct { + // placeholder for future response values +} + +// PublicIPPrefixesClientGetResponse contains the response from method PublicIPPrefixesClient.Get. +type PublicIPPrefixesClientGetResponse struct { + // Public IP prefix resource. + PublicIPPrefix +} + +// PublicIPPrefixesClientListAllResponse contains the response from method PublicIPPrefixesClient.NewListAllPager. +type PublicIPPrefixesClientListAllResponse struct { + // Response for ListPublicIpPrefixes API service call. + PublicIPPrefixListResult +} + +// PublicIPPrefixesClientListResponse contains the response from method PublicIPPrefixesClient.NewListPager. +type PublicIPPrefixesClientListResponse struct { + // Response for ListPublicIpPrefixes API service call. + PublicIPPrefixListResult +} + +// PublicIPPrefixesClientUpdateTagsResponse contains the response from method PublicIPPrefixesClient.UpdateTags. +type PublicIPPrefixesClientUpdateTagsResponse struct { + // Public IP prefix resource. + PublicIPPrefix +} + +// ResourceNavigationLinksClientListResponse contains the response from method ResourceNavigationLinksClient.List. +type ResourceNavigationLinksClientListResponse struct { + // Response for ResourceNavigationLinks_List operation. + ResourceNavigationLinksListResult +} + +// RouteFilterRulesClientCreateOrUpdateResponse contains the response from method RouteFilterRulesClient.BeginCreateOrUpdate. +type RouteFilterRulesClientCreateOrUpdateResponse struct { + // Route Filter Rule Resource. + RouteFilterRule +} + +// RouteFilterRulesClientDeleteResponse contains the response from method RouteFilterRulesClient.BeginDelete. +type RouteFilterRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// RouteFilterRulesClientGetResponse contains the response from method RouteFilterRulesClient.Get. +type RouteFilterRulesClientGetResponse struct { + // Route Filter Rule Resource. + RouteFilterRule +} + +// RouteFilterRulesClientListByRouteFilterResponse contains the response from method RouteFilterRulesClient.NewListByRouteFilterPager. +type RouteFilterRulesClientListByRouteFilterResponse struct { + // Response for the ListRouteFilterRules API service call. + RouteFilterRuleListResult +} + +// RouteFiltersClientCreateOrUpdateResponse contains the response from method RouteFiltersClient.BeginCreateOrUpdate. +type RouteFiltersClientCreateOrUpdateResponse struct { + // Route Filter Resource. + RouteFilter +} + +// RouteFiltersClientDeleteResponse contains the response from method RouteFiltersClient.BeginDelete. +type RouteFiltersClientDeleteResponse struct { + // placeholder for future response values +} + +// RouteFiltersClientGetResponse contains the response from method RouteFiltersClient.Get. +type RouteFiltersClientGetResponse struct { + // Route Filter Resource. + RouteFilter +} + +// RouteFiltersClientListByResourceGroupResponse contains the response from method RouteFiltersClient.NewListByResourceGroupPager. +type RouteFiltersClientListByResourceGroupResponse struct { + // Response for the ListRouteFilters API service call. + RouteFilterListResult +} + +// RouteFiltersClientListResponse contains the response from method RouteFiltersClient.NewListPager. +type RouteFiltersClientListResponse struct { + // Response for the ListRouteFilters API service call. + RouteFilterListResult +} + +// RouteFiltersClientUpdateTagsResponse contains the response from method RouteFiltersClient.UpdateTags. +type RouteFiltersClientUpdateTagsResponse struct { + // Route Filter Resource. + RouteFilter +} + +// RouteMapsClientCreateOrUpdateResponse contains the response from method RouteMapsClient.BeginCreateOrUpdate. +type RouteMapsClientCreateOrUpdateResponse struct { + // The RouteMap child resource of a Virtual hub. + RouteMap +} + +// RouteMapsClientDeleteResponse contains the response from method RouteMapsClient.BeginDelete. +type RouteMapsClientDeleteResponse struct { + // placeholder for future response values +} + +// RouteMapsClientGetResponse contains the response from method RouteMapsClient.Get. +type RouteMapsClientGetResponse struct { + // The RouteMap child resource of a Virtual hub. + RouteMap +} + +// RouteMapsClientListResponse contains the response from method RouteMapsClient.NewListPager. +type RouteMapsClientListResponse struct { + // List of RouteMaps and a URL nextLink to get the next set of results. + ListRouteMapsResult +} + +// RouteTablesClientCreateOrUpdateResponse contains the response from method RouteTablesClient.BeginCreateOrUpdate. +type RouteTablesClientCreateOrUpdateResponse struct { + // Route table resource. + RouteTable +} + +// RouteTablesClientDeleteResponse contains the response from method RouteTablesClient.BeginDelete. +type RouteTablesClientDeleteResponse struct { + // placeholder for future response values +} + +// RouteTablesClientGetResponse contains the response from method RouteTablesClient.Get. +type RouteTablesClientGetResponse struct { + // Route table resource. + RouteTable +} + +// RouteTablesClientListAllResponse contains the response from method RouteTablesClient.NewListAllPager. +type RouteTablesClientListAllResponse struct { + // Response for the ListRouteTable API service call. + RouteTableListResult +} + +// RouteTablesClientListResponse contains the response from method RouteTablesClient.NewListPager. +type RouteTablesClientListResponse struct { + // Response for the ListRouteTable API service call. + RouteTableListResult +} + +// RouteTablesClientUpdateTagsResponse contains the response from method RouteTablesClient.UpdateTags. +type RouteTablesClientUpdateTagsResponse struct { + // Route table resource. + RouteTable +} + +// RoutesClientCreateOrUpdateResponse contains the response from method RoutesClient.BeginCreateOrUpdate. +type RoutesClientCreateOrUpdateResponse struct { + // Route resource. + Route +} + +// RoutesClientDeleteResponse contains the response from method RoutesClient.BeginDelete. +type RoutesClientDeleteResponse struct { + // placeholder for future response values +} + +// RoutesClientGetResponse contains the response from method RoutesClient.Get. +type RoutesClientGetResponse struct { + // Route resource. + Route +} + +// RoutesClientListResponse contains the response from method RoutesClient.NewListPager. +type RoutesClientListResponse struct { + // Response for the ListRoute API service call. + RouteListResult +} + +// RoutingIntentClientCreateOrUpdateResponse contains the response from method RoutingIntentClient.BeginCreateOrUpdate. +type RoutingIntentClientCreateOrUpdateResponse struct { + // The routing intent child resource of a Virtual hub. + RoutingIntent +} + +// RoutingIntentClientDeleteResponse contains the response from method RoutingIntentClient.BeginDelete. +type RoutingIntentClientDeleteResponse struct { + // placeholder for future response values +} + +// RoutingIntentClientGetResponse contains the response from method RoutingIntentClient.Get. +type RoutingIntentClientGetResponse struct { + // The routing intent child resource of a Virtual hub. + RoutingIntent +} + +// RoutingIntentClientListResponse contains the response from method RoutingIntentClient.NewListPager. +type RoutingIntentClientListResponse struct { + // List of the routing intent result and a URL nextLink to get the next set of results. + ListRoutingIntentResult +} + +// ScopeConnectionsClientCreateOrUpdateResponse contains the response from method ScopeConnectionsClient.CreateOrUpdate. +type ScopeConnectionsClientCreateOrUpdateResponse struct { + // The Scope Connections resource + ScopeConnection +} + +// ScopeConnectionsClientDeleteResponse contains the response from method ScopeConnectionsClient.Delete. +type ScopeConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ScopeConnectionsClientGetResponse contains the response from method ScopeConnectionsClient.Get. +type ScopeConnectionsClientGetResponse struct { + // The Scope Connections resource + ScopeConnection +} + +// ScopeConnectionsClientListResponse contains the response from method ScopeConnectionsClient.NewListPager. +type ScopeConnectionsClientListResponse struct { + // List of scope connections. + ScopeConnectionListResult +} + +// SecurityAdminConfigurationsClientCreateOrUpdateResponse contains the response from method SecurityAdminConfigurationsClient.CreateOrUpdate. +type SecurityAdminConfigurationsClientCreateOrUpdateResponse struct { + // Defines the security admin configuration + SecurityAdminConfiguration +} + +// SecurityAdminConfigurationsClientDeleteResponse contains the response from method SecurityAdminConfigurationsClient.BeginDelete. +type SecurityAdminConfigurationsClientDeleteResponse struct { + // placeholder for future response values +} + +// SecurityAdminConfigurationsClientGetResponse contains the response from method SecurityAdminConfigurationsClient.Get. +type SecurityAdminConfigurationsClientGetResponse struct { + // Defines the security admin configuration + SecurityAdminConfiguration +} + +// SecurityAdminConfigurationsClientListResponse contains the response from method SecurityAdminConfigurationsClient.NewListPager. +type SecurityAdminConfigurationsClientListResponse struct { + // A list of network manager security admin configurations + SecurityAdminConfigurationListResult +} + +// SecurityGroupsClientCreateOrUpdateResponse contains the response from method SecurityGroupsClient.BeginCreateOrUpdate. +type SecurityGroupsClientCreateOrUpdateResponse struct { + // NetworkSecurityGroup resource. + SecurityGroup +} + +// SecurityGroupsClientDeleteResponse contains the response from method SecurityGroupsClient.BeginDelete. +type SecurityGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// SecurityGroupsClientGetResponse contains the response from method SecurityGroupsClient.Get. +type SecurityGroupsClientGetResponse struct { + // NetworkSecurityGroup resource. + SecurityGroup +} + +// SecurityGroupsClientListAllResponse contains the response from method SecurityGroupsClient.NewListAllPager. +type SecurityGroupsClientListAllResponse struct { + // Response for ListNetworkSecurityGroups API service call. + SecurityGroupListResult +} + +// SecurityGroupsClientListResponse contains the response from method SecurityGroupsClient.NewListPager. +type SecurityGroupsClientListResponse struct { + // Response for ListNetworkSecurityGroups API service call. + SecurityGroupListResult +} + +// SecurityGroupsClientUpdateTagsResponse contains the response from method SecurityGroupsClient.UpdateTags. +type SecurityGroupsClientUpdateTagsResponse struct { + // NetworkSecurityGroup resource. + SecurityGroup +} + +// SecurityPartnerProvidersClientCreateOrUpdateResponse contains the response from method SecurityPartnerProvidersClient.BeginCreateOrUpdate. +type SecurityPartnerProvidersClientCreateOrUpdateResponse struct { + // Security Partner Provider resource. + SecurityPartnerProvider +} + +// SecurityPartnerProvidersClientDeleteResponse contains the response from method SecurityPartnerProvidersClient.BeginDelete. +type SecurityPartnerProvidersClientDeleteResponse struct { + // placeholder for future response values +} + +// SecurityPartnerProvidersClientGetResponse contains the response from method SecurityPartnerProvidersClient.Get. +type SecurityPartnerProvidersClientGetResponse struct { + // Security Partner Provider resource. + SecurityPartnerProvider +} + +// SecurityPartnerProvidersClientListByResourceGroupResponse contains the response from method SecurityPartnerProvidersClient.NewListByResourceGroupPager. +type SecurityPartnerProvidersClientListByResourceGroupResponse struct { + // Response for ListSecurityPartnerProviders API service call. + SecurityPartnerProviderListResult +} + +// SecurityPartnerProvidersClientListResponse contains the response from method SecurityPartnerProvidersClient.NewListPager. +type SecurityPartnerProvidersClientListResponse struct { + // Response for ListSecurityPartnerProviders API service call. + SecurityPartnerProviderListResult +} + +// SecurityPartnerProvidersClientUpdateTagsResponse contains the response from method SecurityPartnerProvidersClient.UpdateTags. +type SecurityPartnerProvidersClientUpdateTagsResponse struct { + // Security Partner Provider resource. + SecurityPartnerProvider +} + +// SecurityRulesClientCreateOrUpdateResponse contains the response from method SecurityRulesClient.BeginCreateOrUpdate. +type SecurityRulesClientCreateOrUpdateResponse struct { + // Network security rule. + SecurityRule +} + +// SecurityRulesClientDeleteResponse contains the response from method SecurityRulesClient.BeginDelete. +type SecurityRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// SecurityRulesClientGetResponse contains the response from method SecurityRulesClient.Get. +type SecurityRulesClientGetResponse struct { + // Network security rule. + SecurityRule +} + +// SecurityRulesClientListResponse contains the response from method SecurityRulesClient.NewListPager. +type SecurityRulesClientListResponse struct { + // Response for ListSecurityRule API service call. Retrieves all security rules that belongs to a network security group. + SecurityRuleListResult +} + +// ServiceAssociationLinksClientListResponse contains the response from method ServiceAssociationLinksClient.List. +type ServiceAssociationLinksClientListResponse struct { + // Response for ServiceAssociationLinks_List operation. + ServiceAssociationLinksListResult +} + +// ServiceEndpointPoliciesClientCreateOrUpdateResponse contains the response from method ServiceEndpointPoliciesClient.BeginCreateOrUpdate. +type ServiceEndpointPoliciesClientCreateOrUpdateResponse struct { + // Service End point policy resource. + ServiceEndpointPolicy +} + +// ServiceEndpointPoliciesClientDeleteResponse contains the response from method ServiceEndpointPoliciesClient.BeginDelete. +type ServiceEndpointPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// ServiceEndpointPoliciesClientGetResponse contains the response from method ServiceEndpointPoliciesClient.Get. +type ServiceEndpointPoliciesClientGetResponse struct { + // Service End point policy resource. + ServiceEndpointPolicy +} + +// ServiceEndpointPoliciesClientListByResourceGroupResponse contains the response from method ServiceEndpointPoliciesClient.NewListByResourceGroupPager. +type ServiceEndpointPoliciesClientListByResourceGroupResponse struct { + // Response for ListServiceEndpointPolicies API service call. + ServiceEndpointPolicyListResult +} + +// ServiceEndpointPoliciesClientListResponse contains the response from method ServiceEndpointPoliciesClient.NewListPager. +type ServiceEndpointPoliciesClientListResponse struct { + // Response for ListServiceEndpointPolicies API service call. + ServiceEndpointPolicyListResult +} + +// ServiceEndpointPoliciesClientUpdateTagsResponse contains the response from method ServiceEndpointPoliciesClient.UpdateTags. +type ServiceEndpointPoliciesClientUpdateTagsResponse struct { + // Service End point policy resource. + ServiceEndpointPolicy +} + +// ServiceEndpointPolicyDefinitionsClientCreateOrUpdateResponse contains the response from method ServiceEndpointPolicyDefinitionsClient.BeginCreateOrUpdate. +type ServiceEndpointPolicyDefinitionsClientCreateOrUpdateResponse struct { + // Service Endpoint policy definitions. + ServiceEndpointPolicyDefinition +} + +// ServiceEndpointPolicyDefinitionsClientDeleteResponse contains the response from method ServiceEndpointPolicyDefinitionsClient.BeginDelete. +type ServiceEndpointPolicyDefinitionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ServiceEndpointPolicyDefinitionsClientGetResponse contains the response from method ServiceEndpointPolicyDefinitionsClient.Get. +type ServiceEndpointPolicyDefinitionsClientGetResponse struct { + // Service Endpoint policy definitions. + ServiceEndpointPolicyDefinition +} + +// ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse contains the response from method ServiceEndpointPolicyDefinitionsClient.NewListByResourceGroupPager. +type ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse struct { + // Response for ListServiceEndpointPolicyDefinition API service call. Retrieves all service endpoint policy definition that + // belongs to a service endpoint policy. + ServiceEndpointPolicyDefinitionListResult +} + +// ServiceTagInformationClientListResponse contains the response from method ServiceTagInformationClient.NewListPager. +type ServiceTagInformationClientListResponse struct { + // Response for Get ServiceTagInformation API service call. Retrieves the list of service tag information resources. + ServiceTagInformationListResult +} + +// ServiceTagsClientListResponse contains the response from method ServiceTagsClient.List. +type ServiceTagsClientListResponse struct { + // Response for the ListServiceTags API service call. + ServiceTagsListResult +} + +// StaticMembersClientCreateOrUpdateResponse contains the response from method StaticMembersClient.CreateOrUpdate. +type StaticMembersClientCreateOrUpdateResponse struct { + // StaticMember Item. + StaticMember +} + +// StaticMembersClientDeleteResponse contains the response from method StaticMembersClient.Delete. +type StaticMembersClientDeleteResponse struct { + // placeholder for future response values +} + +// StaticMembersClientGetResponse contains the response from method StaticMembersClient.Get. +type StaticMembersClientGetResponse struct { + // StaticMember Item. + StaticMember +} + +// StaticMembersClientListResponse contains the response from method StaticMembersClient.NewListPager. +type StaticMembersClientListResponse struct { + // Result of the request to list StaticMember. It contains a list of groups and a URL link to get the next set of results. + StaticMemberListResult +} + +// SubnetsClientCreateOrUpdateResponse contains the response from method SubnetsClient.BeginCreateOrUpdate. +type SubnetsClientCreateOrUpdateResponse struct { + // Subnet in a virtual network resource. + Subnet +} + +// SubnetsClientDeleteResponse contains the response from method SubnetsClient.BeginDelete. +type SubnetsClientDeleteResponse struct { + // placeholder for future response values +} + +// SubnetsClientGetResponse contains the response from method SubnetsClient.Get. +type SubnetsClientGetResponse struct { + // Subnet in a virtual network resource. + Subnet +} + +// SubnetsClientListResponse contains the response from method SubnetsClient.NewListPager. +type SubnetsClientListResponse struct { + // Response for ListSubnets API service callRetrieves all subnet that belongs to a virtual network. + SubnetListResult +} + +// SubnetsClientPrepareNetworkPoliciesResponse contains the response from method SubnetsClient.BeginPrepareNetworkPolicies. +type SubnetsClientPrepareNetworkPoliciesResponse struct { + // placeholder for future response values +} + +// SubnetsClientUnprepareNetworkPoliciesResponse contains the response from method SubnetsClient.BeginUnprepareNetworkPolicies. +type SubnetsClientUnprepareNetworkPoliciesResponse struct { + // placeholder for future response values +} + +// SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse contains the response from method SubscriptionNetworkManagerConnectionsClient.CreateOrUpdate. +type SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse struct { + // The Network Manager Connection resource + ManagerConnection +} + +// SubscriptionNetworkManagerConnectionsClientDeleteResponse contains the response from method SubscriptionNetworkManagerConnectionsClient.Delete. +type SubscriptionNetworkManagerConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// SubscriptionNetworkManagerConnectionsClientGetResponse contains the response from method SubscriptionNetworkManagerConnectionsClient.Get. +type SubscriptionNetworkManagerConnectionsClientGetResponse struct { + // The Network Manager Connection resource + ManagerConnection +} + +// SubscriptionNetworkManagerConnectionsClientListResponse contains the response from method SubscriptionNetworkManagerConnectionsClient.NewListPager. +type SubscriptionNetworkManagerConnectionsClientListResponse struct { + // List of network manager connections. + ManagerConnectionListResult +} + +// UsagesClientListResponse contains the response from method UsagesClient.NewListPager. +type UsagesClientListResponse struct { + // The list usages operation response. + UsagesListResult +} + +// VPNConnectionsClientCreateOrUpdateResponse contains the response from method VPNConnectionsClient.BeginCreateOrUpdate. +type VPNConnectionsClientCreateOrUpdateResponse struct { + // VpnConnection Resource. + VPNConnection +} + +// VPNConnectionsClientDeleteResponse contains the response from method VPNConnectionsClient.BeginDelete. +type VPNConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// VPNConnectionsClientGetResponse contains the response from method VPNConnectionsClient.Get. +type VPNConnectionsClientGetResponse struct { + // VpnConnection Resource. + VPNConnection +} + +// VPNConnectionsClientListByVPNGatewayResponse contains the response from method VPNConnectionsClient.NewListByVPNGatewayPager. +type VPNConnectionsClientListByVPNGatewayResponse struct { + // Result of the request to list all vpn connections to a virtual wan vpn gateway. It contains a list of Vpn Connections and + // a URL nextLink to get the next set of results. + ListVPNConnectionsResult +} + +// VPNConnectionsClientStartPacketCaptureResponse contains the response from method VPNConnectionsClient.BeginStartPacketCapture. +type VPNConnectionsClientStartPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNConnectionsClientStartPacketCaptureResponse. +func (v *VPNConnectionsClientStartPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VPNConnectionsClientStopPacketCaptureResponse contains the response from method VPNConnectionsClient.BeginStopPacketCapture. +type VPNConnectionsClientStopPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNConnectionsClientStopPacketCaptureResponse. +func (v *VPNConnectionsClientStopPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VPNGatewaysClientCreateOrUpdateResponse contains the response from method VPNGatewaysClient.BeginCreateOrUpdate. +type VPNGatewaysClientCreateOrUpdateResponse struct { + // VpnGateway Resource. + VPNGateway +} + +// VPNGatewaysClientDeleteResponse contains the response from method VPNGatewaysClient.BeginDelete. +type VPNGatewaysClientDeleteResponse struct { + // placeholder for future response values +} + +// VPNGatewaysClientGetResponse contains the response from method VPNGatewaysClient.Get. +type VPNGatewaysClientGetResponse struct { + // VpnGateway Resource. + VPNGateway +} + +// VPNGatewaysClientListByResourceGroupResponse contains the response from method VPNGatewaysClient.NewListByResourceGroupPager. +type VPNGatewaysClientListByResourceGroupResponse struct { + // Result of the request to list VpnGateways. It contains a list of VpnGateways and a URL nextLink to get the next set of + // results. + ListVPNGatewaysResult +} + +// VPNGatewaysClientListResponse contains the response from method VPNGatewaysClient.NewListPager. +type VPNGatewaysClientListResponse struct { + // Result of the request to list VpnGateways. It contains a list of VpnGateways and a URL nextLink to get the next set of + // results. + ListVPNGatewaysResult +} + +// VPNGatewaysClientResetResponse contains the response from method VPNGatewaysClient.BeginReset. +type VPNGatewaysClientResetResponse struct { + // VpnGateway Resource. + VPNGateway +} + +// VPNGatewaysClientStartPacketCaptureResponse contains the response from method VPNGatewaysClient.BeginStartPacketCapture. +type VPNGatewaysClientStartPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGatewaysClientStartPacketCaptureResponse. +func (v *VPNGatewaysClientStartPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VPNGatewaysClientStopPacketCaptureResponse contains the response from method VPNGatewaysClient.BeginStopPacketCapture. +type VPNGatewaysClientStopPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNGatewaysClientStopPacketCaptureResponse. +func (v *VPNGatewaysClientStopPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VPNGatewaysClientUpdateTagsResponse contains the response from method VPNGatewaysClient.BeginUpdateTags. +type VPNGatewaysClientUpdateTagsResponse struct { + // VpnGateway Resource. + VPNGateway +} + +// VPNLinkConnectionsClientGetIkeSasResponse contains the response from method VPNLinkConnectionsClient.BeginGetIkeSas. +type VPNLinkConnectionsClientGetIkeSasResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VPNLinkConnectionsClientGetIkeSasResponse. +func (v *VPNLinkConnectionsClientGetIkeSasResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VPNLinkConnectionsClientListByVPNConnectionResponse contains the response from method VPNLinkConnectionsClient.NewListByVPNConnectionPager. +type VPNLinkConnectionsClientListByVPNConnectionResponse struct { + // Result of the request to list all vpn connections to a virtual wan vpn gateway. It contains a list of Vpn Connections and + // a URL nextLink to get the next set of results. + ListVPNSiteLinkConnectionsResult +} + +// VPNLinkConnectionsClientResetConnectionResponse contains the response from method VPNLinkConnectionsClient.BeginResetConnection. +type VPNLinkConnectionsClientResetConnectionResponse struct { + // placeholder for future response values +} + +// VPNServerConfigurationsAssociatedWithVirtualWanClientListResponse contains the response from method VPNServerConfigurationsAssociatedWithVirtualWanClient.BeginList. +type VPNServerConfigurationsAssociatedWithVirtualWanClientListResponse struct { + // VpnServerConfigurations list associated with VirtualWan Response. + VPNServerConfigurationsResponse +} + +// VPNServerConfigurationsClientCreateOrUpdateResponse contains the response from method VPNServerConfigurationsClient.BeginCreateOrUpdate. +type VPNServerConfigurationsClientCreateOrUpdateResponse struct { + // VpnServerConfiguration Resource. + VPNServerConfiguration +} + +// VPNServerConfigurationsClientDeleteResponse contains the response from method VPNServerConfigurationsClient.BeginDelete. +type VPNServerConfigurationsClientDeleteResponse struct { + // placeholder for future response values +} + +// VPNServerConfigurationsClientGetResponse contains the response from method VPNServerConfigurationsClient.Get. +type VPNServerConfigurationsClientGetResponse struct { + // VpnServerConfiguration Resource. + VPNServerConfiguration +} + +// VPNServerConfigurationsClientListByResourceGroupResponse contains the response from method VPNServerConfigurationsClient.NewListByResourceGroupPager. +type VPNServerConfigurationsClientListByResourceGroupResponse struct { + // Result of the request to list all VpnServerConfigurations. It contains a list of VpnServerConfigurations and a URL nextLink + // to get the next set of results. + ListVPNServerConfigurationsResult +} + +// VPNServerConfigurationsClientListResponse contains the response from method VPNServerConfigurationsClient.NewListPager. +type VPNServerConfigurationsClientListResponse struct { + // Result of the request to list all VpnServerConfigurations. It contains a list of VpnServerConfigurations and a URL nextLink + // to get the next set of results. + ListVPNServerConfigurationsResult +} + +// VPNServerConfigurationsClientUpdateTagsResponse contains the response from method VPNServerConfigurationsClient.UpdateTags. +type VPNServerConfigurationsClientUpdateTagsResponse struct { + // VpnServerConfiguration Resource. + VPNServerConfiguration +} + +// VPNSiteLinkConnectionsClientGetResponse contains the response from method VPNSiteLinkConnectionsClient.Get. +type VPNSiteLinkConnectionsClientGetResponse struct { + // VpnSiteLinkConnection Resource. + VPNSiteLinkConnection +} + +// VPNSiteLinksClientGetResponse contains the response from method VPNSiteLinksClient.Get. +type VPNSiteLinksClientGetResponse struct { + // VpnSiteLink Resource. + VPNSiteLink +} + +// VPNSiteLinksClientListByVPNSiteResponse contains the response from method VPNSiteLinksClient.NewListByVPNSitePager. +type VPNSiteLinksClientListByVPNSiteResponse struct { + // Result of the request to list VpnSiteLinks. It contains a list of VpnSiteLinks and a URL nextLink to get the next set of + // results. + ListVPNSiteLinksResult +} + +// VPNSitesClientCreateOrUpdateResponse contains the response from method VPNSitesClient.BeginCreateOrUpdate. +type VPNSitesClientCreateOrUpdateResponse struct { + // VpnSite Resource. + VPNSite +} + +// VPNSitesClientDeleteResponse contains the response from method VPNSitesClient.BeginDelete. +type VPNSitesClientDeleteResponse struct { + // placeholder for future response values +} + +// VPNSitesClientGetResponse contains the response from method VPNSitesClient.Get. +type VPNSitesClientGetResponse struct { + // VpnSite Resource. + VPNSite +} + +// VPNSitesClientListByResourceGroupResponse contains the response from method VPNSitesClient.NewListByResourceGroupPager. +type VPNSitesClientListByResourceGroupResponse struct { + // Result of the request to list VpnSites. It contains a list of VpnSites and a URL nextLink to get the next set of results. + ListVPNSitesResult +} + +// VPNSitesClientListResponse contains the response from method VPNSitesClient.NewListPager. +type VPNSitesClientListResponse struct { + // Result of the request to list VpnSites. It contains a list of VpnSites and a URL nextLink to get the next set of results. + ListVPNSitesResult +} + +// VPNSitesClientUpdateTagsResponse contains the response from method VPNSitesClient.UpdateTags. +type VPNSitesClientUpdateTagsResponse struct { + // VpnSite Resource. + VPNSite +} + +// VPNSitesConfigurationClientDownloadResponse contains the response from method VPNSitesConfigurationClient.BeginDownload. +type VPNSitesConfigurationClientDownloadResponse struct { + // placeholder for future response values +} + +// VipSwapClientCreateResponse contains the response from method VipSwapClient.BeginCreate. +type VipSwapClientCreateResponse struct { + // placeholder for future response values +} + +// VipSwapClientGetResponse contains the response from method VipSwapClient.Get. +type VipSwapClientGetResponse struct { + // SwapResource to represent slot type on the specified cloud service. + SwapResource +} + +// VipSwapClientListResponse contains the response from method VipSwapClient.List. +type VipSwapClientListResponse struct { + // SwapResource List with single entry to represent slot type on the specified cloud service. + SwapResourceListResult +} + +// VirtualApplianceConnectionsClientCreateOrUpdateResponse contains the response from method VirtualApplianceConnectionsClient.BeginCreateOrUpdate. +type VirtualApplianceConnectionsClientCreateOrUpdateResponse struct { + // NetworkVirtualApplianceConnection resource. + VirtualApplianceConnection +} + +// VirtualApplianceConnectionsClientDeleteResponse contains the response from method VirtualApplianceConnectionsClient.BeginDelete. +type VirtualApplianceConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualApplianceConnectionsClientGetResponse contains the response from method VirtualApplianceConnectionsClient.Get. +type VirtualApplianceConnectionsClientGetResponse struct { + // NetworkVirtualApplianceConnection resource. + VirtualApplianceConnection +} + +// VirtualApplianceConnectionsClientListResponse contains the response from method VirtualApplianceConnectionsClient.NewListPager. +type VirtualApplianceConnectionsClientListResponse struct { + // NetworkVirtualApplianceConnection list. + VirtualApplianceConnectionList +} + +// VirtualApplianceSKUsClientGetResponse contains the response from method VirtualApplianceSKUsClient.Get. +type VirtualApplianceSKUsClientGetResponse struct { + // Definition of the NetworkVirtualApplianceSkus resource. + VirtualApplianceSKU +} + +// VirtualApplianceSKUsClientListResponse contains the response from method VirtualApplianceSKUsClient.NewListPager. +type VirtualApplianceSKUsClientListResponse struct { + // Response for ListNetworkVirtualApplianceSkus API service call. + VirtualApplianceSKUListResult +} + +// VirtualApplianceSitesClientCreateOrUpdateResponse contains the response from method VirtualApplianceSitesClient.BeginCreateOrUpdate. +type VirtualApplianceSitesClientCreateOrUpdateResponse struct { + // Virtual Appliance Site resource. + VirtualApplianceSite +} + +// VirtualApplianceSitesClientDeleteResponse contains the response from method VirtualApplianceSitesClient.BeginDelete. +type VirtualApplianceSitesClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualApplianceSitesClientGetResponse contains the response from method VirtualApplianceSitesClient.Get. +type VirtualApplianceSitesClientGetResponse struct { + // Virtual Appliance Site resource. + VirtualApplianceSite +} + +// VirtualApplianceSitesClientListResponse contains the response from method VirtualApplianceSitesClient.NewListPager. +type VirtualApplianceSitesClientListResponse struct { + // Response for ListNetworkVirtualApplianceSites API service call. + VirtualApplianceSiteListResult +} + +// VirtualAppliancesClientCreateOrUpdateResponse contains the response from method VirtualAppliancesClient.BeginCreateOrUpdate. +type VirtualAppliancesClientCreateOrUpdateResponse struct { + // NetworkVirtualAppliance Resource. + VirtualAppliance +} + +// VirtualAppliancesClientDeleteResponse contains the response from method VirtualAppliancesClient.BeginDelete. +type VirtualAppliancesClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualAppliancesClientGetResponse contains the response from method VirtualAppliancesClient.Get. +type VirtualAppliancesClientGetResponse struct { + // NetworkVirtualAppliance Resource. + VirtualAppliance +} + +// VirtualAppliancesClientListByResourceGroupResponse contains the response from method VirtualAppliancesClient.NewListByResourceGroupPager. +type VirtualAppliancesClientListByResourceGroupResponse struct { + // Response for ListNetworkVirtualAppliances API service call. + VirtualApplianceListResult +} + +// VirtualAppliancesClientListResponse contains the response from method VirtualAppliancesClient.NewListPager. +type VirtualAppliancesClientListResponse struct { + // Response for ListNetworkVirtualAppliances API service call. + VirtualApplianceListResult +} + +// VirtualAppliancesClientUpdateTagsResponse contains the response from method VirtualAppliancesClient.UpdateTags. +type VirtualAppliancesClientUpdateTagsResponse struct { + // NetworkVirtualAppliance Resource. + VirtualAppliance +} + +// VirtualHubBgpConnectionClientCreateOrUpdateResponse contains the response from method VirtualHubBgpConnectionClient.BeginCreateOrUpdate. +type VirtualHubBgpConnectionClientCreateOrUpdateResponse struct { + // Virtual Appliance Site resource. + BgpConnection +} + +// VirtualHubBgpConnectionClientDeleteResponse contains the response from method VirtualHubBgpConnectionClient.BeginDelete. +type VirtualHubBgpConnectionClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualHubBgpConnectionClientGetResponse contains the response from method VirtualHubBgpConnectionClient.Get. +type VirtualHubBgpConnectionClientGetResponse struct { + // Virtual Appliance Site resource. + BgpConnection +} + +// VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse contains the response from method VirtualHubBgpConnectionsClient.BeginListAdvertisedRoutes. +type VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse struct { + // Map from virtual router instance to list of peer routes. + Value map[string][]*PeerRoute +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse. +func (v *VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualHubBgpConnectionsClientListLearnedRoutesResponse contains the response from method VirtualHubBgpConnectionsClient.BeginListLearnedRoutes. +type VirtualHubBgpConnectionsClientListLearnedRoutesResponse struct { + // Map from virtual router instance to list of peer routes. + Value map[string][]*PeerRoute +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHubBgpConnectionsClientListLearnedRoutesResponse. +func (v *VirtualHubBgpConnectionsClientListLearnedRoutesResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualHubBgpConnectionsClientListResponse contains the response from method VirtualHubBgpConnectionsClient.NewListPager. +type VirtualHubBgpConnectionsClientListResponse struct { + // VirtualHubBgpConnections list. + ListVirtualHubBgpConnectionResults +} + +// VirtualHubIPConfigurationClientCreateOrUpdateResponse contains the response from method VirtualHubIPConfigurationClient.BeginCreateOrUpdate. +type VirtualHubIPConfigurationClientCreateOrUpdateResponse struct { + // IpConfigurations. + HubIPConfiguration +} + +// VirtualHubIPConfigurationClientDeleteResponse contains the response from method VirtualHubIPConfigurationClient.BeginDelete. +type VirtualHubIPConfigurationClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualHubIPConfigurationClientGetResponse contains the response from method VirtualHubIPConfigurationClient.Get. +type VirtualHubIPConfigurationClientGetResponse struct { + // IpConfigurations. + HubIPConfiguration +} + +// VirtualHubIPConfigurationClientListResponse contains the response from method VirtualHubIPConfigurationClient.NewListPager. +type VirtualHubIPConfigurationClientListResponse struct { + // VirtualHubIpConfigurations list. + ListVirtualHubIPConfigurationResults +} + +// VirtualHubRouteTableV2SClientCreateOrUpdateResponse contains the response from method VirtualHubRouteTableV2SClient.BeginCreateOrUpdate. +type VirtualHubRouteTableV2SClientCreateOrUpdateResponse struct { + // VirtualHubRouteTableV2 Resource. + VirtualHubRouteTableV2 +} + +// VirtualHubRouteTableV2SClientDeleteResponse contains the response from method VirtualHubRouteTableV2SClient.BeginDelete. +type VirtualHubRouteTableV2SClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualHubRouteTableV2SClientGetResponse contains the response from method VirtualHubRouteTableV2SClient.Get. +type VirtualHubRouteTableV2SClientGetResponse struct { + // VirtualHubRouteTableV2 Resource. + VirtualHubRouteTableV2 +} + +// VirtualHubRouteTableV2SClientListResponse contains the response from method VirtualHubRouteTableV2SClient.NewListPager. +type VirtualHubRouteTableV2SClientListResponse struct { + // List of VirtualHubRouteTableV2s and a URL nextLink to get the next set of results. + ListVirtualHubRouteTableV2SResult +} + +// VirtualHubsClientCreateOrUpdateResponse contains the response from method VirtualHubsClient.BeginCreateOrUpdate. +type VirtualHubsClientCreateOrUpdateResponse struct { + // VirtualHub Resource. + VirtualHub +} + +// VirtualHubsClientDeleteResponse contains the response from method VirtualHubsClient.BeginDelete. +type VirtualHubsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualHubsClientGetEffectiveVirtualHubRoutesResponse contains the response from method VirtualHubsClient.BeginGetEffectiveVirtualHubRoutes. +type VirtualHubsClientGetEffectiveVirtualHubRoutesResponse struct { + // EffectiveRoutes List. + VirtualHubEffectiveRouteList +} + +// VirtualHubsClientGetInboundRoutesResponse contains the response from method VirtualHubsClient.BeginGetInboundRoutes. +type VirtualHubsClientGetInboundRoutesResponse struct { + // EffectiveRouteMapRoute List. + EffectiveRouteMapRouteList +} + +// VirtualHubsClientGetOutboundRoutesResponse contains the response from method VirtualHubsClient.BeginGetOutboundRoutes. +type VirtualHubsClientGetOutboundRoutesResponse struct { + // EffectiveRouteMapRoute List. + EffectiveRouteMapRouteList +} + +// VirtualHubsClientGetResponse contains the response from method VirtualHubsClient.Get. +type VirtualHubsClientGetResponse struct { + // VirtualHub Resource. + VirtualHub +} + +// VirtualHubsClientListByResourceGroupResponse contains the response from method VirtualHubsClient.NewListByResourceGroupPager. +type VirtualHubsClientListByResourceGroupResponse struct { + // Result of the request to list VirtualHubs. It contains a list of VirtualHubs and a URL nextLink to get the next set of + // results. + ListVirtualHubsResult +} + +// VirtualHubsClientListResponse contains the response from method VirtualHubsClient.NewListPager. +type VirtualHubsClientListResponse struct { + // Result of the request to list VirtualHubs. It contains a list of VirtualHubs and a URL nextLink to get the next set of + // results. + ListVirtualHubsResult +} + +// VirtualHubsClientUpdateTagsResponse contains the response from method VirtualHubsClient.UpdateTags. +type VirtualHubsClientUpdateTagsResponse struct { + // VirtualHub Resource. + VirtualHub +} + +// VirtualNetworkGatewayConnectionsClientCreateOrUpdateResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginCreateOrUpdate. +type VirtualNetworkGatewayConnectionsClientCreateOrUpdateResponse struct { + // A common class for general resource information. + VirtualNetworkGatewayConnection +} + +// VirtualNetworkGatewayConnectionsClientDeleteResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginDelete. +type VirtualNetworkGatewayConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualNetworkGatewayConnectionsClientGetIkeSasResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginGetIkeSas. +type VirtualNetworkGatewayConnectionsClientGetIkeSasResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayConnectionsClientGetIkeSasResponse. +func (v *VirtualNetworkGatewayConnectionsClientGetIkeSasResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewayConnectionsClientGetResponse contains the response from method VirtualNetworkGatewayConnectionsClient.Get. +type VirtualNetworkGatewayConnectionsClientGetResponse struct { + // A common class for general resource information. + VirtualNetworkGatewayConnection +} + +// VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse contains the response from method VirtualNetworkGatewayConnectionsClient.GetSharedKey. +type VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse struct { + // Response for GetConnectionSharedKey API service call. + ConnectionSharedKey +} + +// VirtualNetworkGatewayConnectionsClientListResponse contains the response from method VirtualNetworkGatewayConnectionsClient.NewListPager. +type VirtualNetworkGatewayConnectionsClientListResponse struct { + // Response for the ListVirtualNetworkGatewayConnections API service call. + VirtualNetworkGatewayConnectionListResult +} + +// VirtualNetworkGatewayConnectionsClientResetConnectionResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginResetConnection. +type VirtualNetworkGatewayConnectionsClientResetConnectionResponse struct { + // placeholder for future response values +} + +// VirtualNetworkGatewayConnectionsClientResetSharedKeyResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginResetSharedKey. +type VirtualNetworkGatewayConnectionsClientResetSharedKeyResponse struct { + // The virtual network connection reset shared key. + ConnectionResetSharedKey +} + +// VirtualNetworkGatewayConnectionsClientSetSharedKeyResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginSetSharedKey. +type VirtualNetworkGatewayConnectionsClientSetSharedKeyResponse struct { + // Response for GetConnectionSharedKey API service call. + ConnectionSharedKey +} + +// VirtualNetworkGatewayConnectionsClientStartPacketCaptureResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginStartPacketCapture. +type VirtualNetworkGatewayConnectionsClientStartPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayConnectionsClientStartPacketCaptureResponse. +func (v *VirtualNetworkGatewayConnectionsClientStartPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewayConnectionsClientStopPacketCaptureResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginStopPacketCapture. +type VirtualNetworkGatewayConnectionsClientStopPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewayConnectionsClientStopPacketCaptureResponse. +func (v *VirtualNetworkGatewayConnectionsClientStopPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewayConnectionsClientUpdateTagsResponse contains the response from method VirtualNetworkGatewayConnectionsClient.BeginUpdateTags. +type VirtualNetworkGatewayConnectionsClientUpdateTagsResponse struct { + // A common class for general resource information. + VirtualNetworkGatewayConnection +} + +// VirtualNetworkGatewayNatRulesClientCreateOrUpdateResponse contains the response from method VirtualNetworkGatewayNatRulesClient.BeginCreateOrUpdate. +type VirtualNetworkGatewayNatRulesClientCreateOrUpdateResponse struct { + // VirtualNetworkGatewayNatRule Resource. + VirtualNetworkGatewayNatRule +} + +// VirtualNetworkGatewayNatRulesClientDeleteResponse contains the response from method VirtualNetworkGatewayNatRulesClient.BeginDelete. +type VirtualNetworkGatewayNatRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualNetworkGatewayNatRulesClientGetResponse contains the response from method VirtualNetworkGatewayNatRulesClient.Get. +type VirtualNetworkGatewayNatRulesClientGetResponse struct { + // VirtualNetworkGatewayNatRule Resource. + VirtualNetworkGatewayNatRule +} + +// VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse contains the response from method VirtualNetworkGatewayNatRulesClient.NewListByVirtualNetworkGatewayPager. +type VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse struct { + // Result of the request to list all nat rules to a virtual network gateway. It contains a list of Nat rules and a URL nextLink + // to get the next set of results. + ListVirtualNetworkGatewayNatRulesResult +} + +// VirtualNetworkGatewaysClientCreateOrUpdateResponse contains the response from method VirtualNetworkGatewaysClient.BeginCreateOrUpdate. +type VirtualNetworkGatewaysClientCreateOrUpdateResponse struct { + // A common class for general resource information. + VirtualNetworkGateway +} + +// VirtualNetworkGatewaysClientDeleteResponse contains the response from method VirtualNetworkGatewaysClient.BeginDelete. +type VirtualNetworkGatewaysClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualNetworkGatewaysClientDisconnectVirtualNetworkGatewayVPNConnectionsResponse contains the response from method VirtualNetworkGatewaysClient.BeginDisconnectVirtualNetworkGatewayVPNConnections. +type VirtualNetworkGatewaysClientDisconnectVirtualNetworkGatewayVPNConnectionsResponse struct { + // placeholder for future response values +} + +// VirtualNetworkGatewaysClientGenerateVPNProfileResponse contains the response from method VirtualNetworkGatewaysClient.BeginGenerateVPNProfile. +type VirtualNetworkGatewaysClientGenerateVPNProfileResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewaysClientGenerateVPNProfileResponse. +func (v *VirtualNetworkGatewaysClientGenerateVPNProfileResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewaysClientGeneratevpnclientpackageResponse contains the response from method VirtualNetworkGatewaysClient.BeginGeneratevpnclientpackage. +type VirtualNetworkGatewaysClientGeneratevpnclientpackageResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewaysClientGeneratevpnclientpackageResponse. +func (v *VirtualNetworkGatewaysClientGeneratevpnclientpackageResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewaysClientGetAdvertisedRoutesResponse contains the response from method VirtualNetworkGatewaysClient.BeginGetAdvertisedRoutes. +type VirtualNetworkGatewaysClientGetAdvertisedRoutesResponse struct { + // List of virtual network gateway routes. + GatewayRouteListResult +} + +// VirtualNetworkGatewaysClientGetBgpPeerStatusResponse contains the response from method VirtualNetworkGatewaysClient.BeginGetBgpPeerStatus. +type VirtualNetworkGatewaysClientGetBgpPeerStatusResponse struct { + // Response for list BGP peer status API service call. + BgpPeerStatusListResult +} + +// VirtualNetworkGatewaysClientGetLearnedRoutesResponse contains the response from method VirtualNetworkGatewaysClient.BeginGetLearnedRoutes. +type VirtualNetworkGatewaysClientGetLearnedRoutesResponse struct { + // List of virtual network gateway routes. + GatewayRouteListResult +} + +// VirtualNetworkGatewaysClientGetResponse contains the response from method VirtualNetworkGatewaysClient.Get. +type VirtualNetworkGatewaysClientGetResponse struct { + // A common class for general resource information. + VirtualNetworkGateway +} + +// VirtualNetworkGatewaysClientGetVPNProfilePackageURLResponse contains the response from method VirtualNetworkGatewaysClient.BeginGetVPNProfilePackageURL. +type VirtualNetworkGatewaysClientGetVPNProfilePackageURLResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewaysClientGetVPNProfilePackageURLResponse. +func (v *VirtualNetworkGatewaysClientGetVPNProfilePackageURLResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewaysClientGetVpnclientConnectionHealthResponse contains the response from method VirtualNetworkGatewaysClient.BeginGetVpnclientConnectionHealth. +type VirtualNetworkGatewaysClientGetVpnclientConnectionHealthResponse struct { + // List of virtual network gateway vpn client connection health. + VPNClientConnectionHealthDetailListResult +} + +// VirtualNetworkGatewaysClientGetVpnclientIPSecParametersResponse contains the response from method VirtualNetworkGatewaysClient.BeginGetVpnclientIPSecParameters. +type VirtualNetworkGatewaysClientGetVpnclientIPSecParametersResponse struct { + // An IPSec parameters for a virtual network gateway P2S connection. + VPNClientIPsecParameters +} + +// VirtualNetworkGatewaysClientListConnectionsResponse contains the response from method VirtualNetworkGatewaysClient.NewListConnectionsPager. +type VirtualNetworkGatewaysClientListConnectionsResponse struct { + // Response for the VirtualNetworkGatewayListConnections API service call. + VirtualNetworkGatewayListConnectionsResult +} + +// VirtualNetworkGatewaysClientListResponse contains the response from method VirtualNetworkGatewaysClient.NewListPager. +type VirtualNetworkGatewaysClientListResponse struct { + // Response for the ListVirtualNetworkGateways API service call. + VirtualNetworkGatewayListResult +} + +// VirtualNetworkGatewaysClientResetResponse contains the response from method VirtualNetworkGatewaysClient.BeginReset. +type VirtualNetworkGatewaysClientResetResponse struct { + // A common class for general resource information. + VirtualNetworkGateway +} + +// VirtualNetworkGatewaysClientResetVPNClientSharedKeyResponse contains the response from method VirtualNetworkGatewaysClient.BeginResetVPNClientSharedKey. +type VirtualNetworkGatewaysClientResetVPNClientSharedKeyResponse struct { + // placeholder for future response values +} + +// VirtualNetworkGatewaysClientSetVpnclientIPSecParametersResponse contains the response from method VirtualNetworkGatewaysClient.BeginSetVpnclientIPSecParameters. +type VirtualNetworkGatewaysClientSetVpnclientIPSecParametersResponse struct { + // An IPSec parameters for a virtual network gateway P2S connection. + VPNClientIPsecParameters +} + +// VirtualNetworkGatewaysClientStartPacketCaptureResponse contains the response from method VirtualNetworkGatewaysClient.BeginStartPacketCapture. +type VirtualNetworkGatewaysClientStartPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewaysClientStartPacketCaptureResponse. +func (v *VirtualNetworkGatewaysClientStartPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewaysClientStopPacketCaptureResponse contains the response from method VirtualNetworkGatewaysClient.BeginStopPacketCapture. +type VirtualNetworkGatewaysClientStopPacketCaptureResponse struct { + Value *string +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkGatewaysClientStopPacketCaptureResponse. +func (v *VirtualNetworkGatewaysClientStopPacketCaptureResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &v.Value) +} + +// VirtualNetworkGatewaysClientSupportedVPNDevicesResponse contains the response from method VirtualNetworkGatewaysClient.SupportedVPNDevices. +type VirtualNetworkGatewaysClientSupportedVPNDevicesResponse struct { + Value *string +} + +// VirtualNetworkGatewaysClientUpdateTagsResponse contains the response from method VirtualNetworkGatewaysClient.BeginUpdateTags. +type VirtualNetworkGatewaysClientUpdateTagsResponse struct { + // A common class for general resource information. + VirtualNetworkGateway +} + +// VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse contains the response from method VirtualNetworkGatewaysClient.VPNDeviceConfigurationScript. +type VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse struct { + Value *string +} + +// VirtualNetworkPeeringsClientCreateOrUpdateResponse contains the response from method VirtualNetworkPeeringsClient.BeginCreateOrUpdate. +type VirtualNetworkPeeringsClientCreateOrUpdateResponse struct { + // Peerings in a virtual network resource. + VirtualNetworkPeering +} + +// VirtualNetworkPeeringsClientDeleteResponse contains the response from method VirtualNetworkPeeringsClient.BeginDelete. +type VirtualNetworkPeeringsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualNetworkPeeringsClientGetResponse contains the response from method VirtualNetworkPeeringsClient.Get. +type VirtualNetworkPeeringsClientGetResponse struct { + // Peerings in a virtual network resource. + VirtualNetworkPeering +} + +// VirtualNetworkPeeringsClientListResponse contains the response from method VirtualNetworkPeeringsClient.NewListPager. +type VirtualNetworkPeeringsClientListResponse struct { + // Response for ListSubnets API service call. Retrieves all subnets that belong to a virtual network. + VirtualNetworkPeeringListResult +} + +// VirtualNetworkTapsClientCreateOrUpdateResponse contains the response from method VirtualNetworkTapsClient.BeginCreateOrUpdate. +type VirtualNetworkTapsClientCreateOrUpdateResponse struct { + // Virtual Network Tap resource. + VirtualNetworkTap +} + +// VirtualNetworkTapsClientDeleteResponse contains the response from method VirtualNetworkTapsClient.BeginDelete. +type VirtualNetworkTapsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualNetworkTapsClientGetResponse contains the response from method VirtualNetworkTapsClient.Get. +type VirtualNetworkTapsClientGetResponse struct { + // Virtual Network Tap resource. + VirtualNetworkTap +} + +// VirtualNetworkTapsClientListAllResponse contains the response from method VirtualNetworkTapsClient.NewListAllPager. +type VirtualNetworkTapsClientListAllResponse struct { + // Response for ListVirtualNetworkTap API service call. + VirtualNetworkTapListResult +} + +// VirtualNetworkTapsClientListByResourceGroupResponse contains the response from method VirtualNetworkTapsClient.NewListByResourceGroupPager. +type VirtualNetworkTapsClientListByResourceGroupResponse struct { + // Response for ListVirtualNetworkTap API service call. + VirtualNetworkTapListResult +} + +// VirtualNetworkTapsClientUpdateTagsResponse contains the response from method VirtualNetworkTapsClient.UpdateTags. +type VirtualNetworkTapsClientUpdateTagsResponse struct { + // Virtual Network Tap resource. + VirtualNetworkTap +} + +// VirtualNetworksClientCheckIPAddressAvailabilityResponse contains the response from method VirtualNetworksClient.CheckIPAddressAvailability. +type VirtualNetworksClientCheckIPAddressAvailabilityResponse struct { + // Response for CheckIPAddressAvailability API service call. + IPAddressAvailabilityResult +} + +// VirtualNetworksClientCreateOrUpdateResponse contains the response from method VirtualNetworksClient.BeginCreateOrUpdate. +type VirtualNetworksClientCreateOrUpdateResponse struct { + // Virtual Network resource. + VirtualNetwork +} + +// VirtualNetworksClientDeleteResponse contains the response from method VirtualNetworksClient.BeginDelete. +type VirtualNetworksClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualNetworksClientGetResponse contains the response from method VirtualNetworksClient.Get. +type VirtualNetworksClientGetResponse struct { + // Virtual Network resource. + VirtualNetwork +} + +// VirtualNetworksClientListAllResponse contains the response from method VirtualNetworksClient.NewListAllPager. +type VirtualNetworksClientListAllResponse struct { + // Response for the ListVirtualNetworks API service call. + VirtualNetworkListResult +} + +// VirtualNetworksClientListDdosProtectionStatusResponse contains the response from method VirtualNetworksClient.BeginListDdosProtectionStatus. +type VirtualNetworksClientListDdosProtectionStatusResponse struct { + // Response for GetVirtualNetworkDdosProtectionStatusOperation. + VirtualNetworkDdosProtectionStatusResult +} + +// VirtualNetworksClientListResponse contains the response from method VirtualNetworksClient.NewListPager. +type VirtualNetworksClientListResponse struct { + // Response for the ListVirtualNetworks API service call. + VirtualNetworkListResult +} + +// VirtualNetworksClientListUsageResponse contains the response from method VirtualNetworksClient.NewListUsagePager. +type VirtualNetworksClientListUsageResponse struct { + // Response for the virtual networks GetUsage API service call. + VirtualNetworkListUsageResult +} + +// VirtualNetworksClientUpdateTagsResponse contains the response from method VirtualNetworksClient.UpdateTags. +type VirtualNetworksClientUpdateTagsResponse struct { + // Virtual Network resource. + VirtualNetwork +} + +// VirtualRouterPeeringsClientCreateOrUpdateResponse contains the response from method VirtualRouterPeeringsClient.BeginCreateOrUpdate. +type VirtualRouterPeeringsClientCreateOrUpdateResponse struct { + // Virtual Router Peering resource. + VirtualRouterPeering +} + +// VirtualRouterPeeringsClientDeleteResponse contains the response from method VirtualRouterPeeringsClient.BeginDelete. +type VirtualRouterPeeringsClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualRouterPeeringsClientGetResponse contains the response from method VirtualRouterPeeringsClient.Get. +type VirtualRouterPeeringsClientGetResponse struct { + // Virtual Router Peering resource. + VirtualRouterPeering +} + +// VirtualRouterPeeringsClientListResponse contains the response from method VirtualRouterPeeringsClient.NewListPager. +type VirtualRouterPeeringsClientListResponse struct { + // Response for ListVirtualRouterPeerings API service call. + VirtualRouterPeeringListResult +} + +// VirtualRoutersClientCreateOrUpdateResponse contains the response from method VirtualRoutersClient.BeginCreateOrUpdate. +type VirtualRoutersClientCreateOrUpdateResponse struct { + // VirtualRouter Resource. + VirtualRouter +} + +// VirtualRoutersClientDeleteResponse contains the response from method VirtualRoutersClient.BeginDelete. +type VirtualRoutersClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualRoutersClientGetResponse contains the response from method VirtualRoutersClient.Get. +type VirtualRoutersClientGetResponse struct { + // VirtualRouter Resource. + VirtualRouter +} + +// VirtualRoutersClientListByResourceGroupResponse contains the response from method VirtualRoutersClient.NewListByResourceGroupPager. +type VirtualRoutersClientListByResourceGroupResponse struct { + // Response for ListVirtualRouters API service call. + VirtualRouterListResult +} + +// VirtualRoutersClientListResponse contains the response from method VirtualRoutersClient.NewListPager. +type VirtualRoutersClientListResponse struct { + // Response for ListVirtualRouters API service call. + VirtualRouterListResult +} + +// VirtualWansClientCreateOrUpdateResponse contains the response from method VirtualWansClient.BeginCreateOrUpdate. +type VirtualWansClientCreateOrUpdateResponse struct { + // VirtualWAN Resource. + VirtualWAN +} + +// VirtualWansClientDeleteResponse contains the response from method VirtualWansClient.BeginDelete. +type VirtualWansClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualWansClientGetResponse contains the response from method VirtualWansClient.Get. +type VirtualWansClientGetResponse struct { + // VirtualWAN Resource. + VirtualWAN +} + +// VirtualWansClientListByResourceGroupResponse contains the response from method VirtualWansClient.NewListByResourceGroupPager. +type VirtualWansClientListByResourceGroupResponse struct { + // Result of the request to list VirtualWANs. It contains a list of VirtualWANs and a URL nextLink to get the next set of + // results. + ListVirtualWANsResult +} + +// VirtualWansClientListResponse contains the response from method VirtualWansClient.NewListPager. +type VirtualWansClientListResponse struct { + // Result of the request to list VirtualWANs. It contains a list of VirtualWANs and a URL nextLink to get the next set of + // results. + ListVirtualWANsResult +} + +// VirtualWansClientUpdateTagsResponse contains the response from method VirtualWansClient.UpdateTags. +type VirtualWansClientUpdateTagsResponse struct { + // VirtualWAN Resource. + VirtualWAN +} + +// WatchersClientCheckConnectivityResponse contains the response from method WatchersClient.BeginCheckConnectivity. +type WatchersClientCheckConnectivityResponse struct { + // Information on the connectivity status. + ConnectivityInformation +} + +// WatchersClientCreateOrUpdateResponse contains the response from method WatchersClient.CreateOrUpdate. +type WatchersClientCreateOrUpdateResponse struct { + // Network watcher in a resource group. + Watcher +} + +// WatchersClientDeleteResponse contains the response from method WatchersClient.BeginDelete. +type WatchersClientDeleteResponse struct { + // placeholder for future response values +} + +// WatchersClientGetAzureReachabilityReportResponse contains the response from method WatchersClient.BeginGetAzureReachabilityReport. +type WatchersClientGetAzureReachabilityReportResponse struct { + // Azure reachability report details. + AzureReachabilityReport +} + +// WatchersClientGetFlowLogStatusResponse contains the response from method WatchersClient.BeginGetFlowLogStatus. +type WatchersClientGetFlowLogStatusResponse struct { + // Information on the configuration of flow log and traffic analytics (optional) . + FlowLogInformation +} + +// WatchersClientGetNetworkConfigurationDiagnosticResponse contains the response from method WatchersClient.BeginGetNetworkConfigurationDiagnostic. +type WatchersClientGetNetworkConfigurationDiagnosticResponse struct { + // Results of network configuration diagnostic on the target resource. + ConfigurationDiagnosticResponse +} + +// WatchersClientGetNextHopResponse contains the response from method WatchersClient.BeginGetNextHop. +type WatchersClientGetNextHopResponse struct { + // The information about next hop from the specified VM. + NextHopResult +} + +// WatchersClientGetResponse contains the response from method WatchersClient.Get. +type WatchersClientGetResponse struct { + // Network watcher in a resource group. + Watcher +} + +// WatchersClientGetTopologyResponse contains the response from method WatchersClient.GetTopology. +type WatchersClientGetTopologyResponse struct { + // Topology of the specified resource group. + Topology +} + +// WatchersClientGetTroubleshootingResponse contains the response from method WatchersClient.BeginGetTroubleshooting. +type WatchersClientGetTroubleshootingResponse struct { + // Troubleshooting information gained from specified resource. + TroubleshootingResult +} + +// WatchersClientGetTroubleshootingResultResponse contains the response from method WatchersClient.BeginGetTroubleshootingResult. +type WatchersClientGetTroubleshootingResultResponse struct { + // Troubleshooting information gained from specified resource. + TroubleshootingResult +} + +// WatchersClientGetVMSecurityRulesResponse contains the response from method WatchersClient.BeginGetVMSecurityRules. +type WatchersClientGetVMSecurityRulesResponse struct { + // The information about security rules applied to the specified VM. + SecurityGroupViewResult +} + +// WatchersClientListAllResponse contains the response from method WatchersClient.NewListAllPager. +type WatchersClientListAllResponse struct { + // Response for ListNetworkWatchers API service call. + WatcherListResult +} + +// WatchersClientListAvailableProvidersResponse contains the response from method WatchersClient.BeginListAvailableProviders. +type WatchersClientListAvailableProvidersResponse struct { + // List of available countries with details. + AvailableProvidersList +} + +// WatchersClientListResponse contains the response from method WatchersClient.NewListPager. +type WatchersClientListResponse struct { + // Response for ListNetworkWatchers API service call. + WatcherListResult +} + +// WatchersClientSetFlowLogConfigurationResponse contains the response from method WatchersClient.BeginSetFlowLogConfiguration. +type WatchersClientSetFlowLogConfigurationResponse struct { + // Information on the configuration of flow log and traffic analytics (optional) . + FlowLogInformation +} + +// WatchersClientUpdateTagsResponse contains the response from method WatchersClient.UpdateTags. +type WatchersClientUpdateTagsResponse struct { + // Network watcher in a resource group. + Watcher +} + +// WatchersClientVerifyIPFlowResponse contains the response from method WatchersClient.BeginVerifyIPFlow. +type WatchersClientVerifyIPFlowResponse struct { + // Results of IP flow verification on the target resource. + VerificationIPFlowResult +} + +// WebApplicationFirewallPoliciesClientCreateOrUpdateResponse contains the response from method WebApplicationFirewallPoliciesClient.CreateOrUpdate. +type WebApplicationFirewallPoliciesClientCreateOrUpdateResponse struct { + // Defines web application firewall policy. + WebApplicationFirewallPolicy +} + +// WebApplicationFirewallPoliciesClientDeleteResponse contains the response from method WebApplicationFirewallPoliciesClient.BeginDelete. +type WebApplicationFirewallPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// WebApplicationFirewallPoliciesClientGetResponse contains the response from method WebApplicationFirewallPoliciesClient.Get. +type WebApplicationFirewallPoliciesClientGetResponse struct { + // Defines web application firewall policy. + WebApplicationFirewallPolicy +} + +// WebApplicationFirewallPoliciesClientListAllResponse contains the response from method WebApplicationFirewallPoliciesClient.NewListAllPager. +type WebApplicationFirewallPoliciesClientListAllResponse struct { + // Result of the request to list WebApplicationFirewallPolicies. It contains a list of WebApplicationFirewallPolicy objects + // and a URL link to get the next set of results. + WebApplicationFirewallPolicyListResult +} + +// WebApplicationFirewallPoliciesClientListResponse contains the response from method WebApplicationFirewallPoliciesClient.NewListPager. +type WebApplicationFirewallPoliciesClientListResponse struct { + // Result of the request to list WebApplicationFirewallPolicies. It contains a list of WebApplicationFirewallPolicy objects + // and a URL link to get the next set of results. + WebApplicationFirewallPolicyListResult +} + +// WebCategoriesClientGetResponse contains the response from method WebCategoriesClient.Get. +type WebCategoriesClientGetResponse struct { + // Azure Web Category Resource. + AzureWebCategory +} + +// WebCategoriesClientListBySubscriptionResponse contains the response from method WebCategoriesClient.NewListBySubscriptionPager. +type WebCategoriesClientListBySubscriptionResponse struct { + // Response for ListAzureWebCategories API service call. + AzureWebCategoryListResult +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routefilterrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routefilterrules_client.go new file mode 100644 index 000000000..641b9f566 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routefilterrules_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 armnetwork + +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" +) + +// RouteFilterRulesClient contains the methods for the RouteFilterRules group. +// Don't use this type directly, use NewRouteFilterRulesClient() instead. +type RouteFilterRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRouteFilterRulesClient creates a new instance of RouteFilterRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewRouteFilterRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RouteFilterRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RouteFilterRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a route in the specified route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - ruleName - The name of the route filter rule. +// - routeFilterRuleParameters - Parameters supplied to the create or update route filter rule operation. +// - options - RouteFilterRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteFilterRulesClient.BeginCreateOrUpdate +// method. +func (client *RouteFilterRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule, options *RouteFilterRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[RouteFilterRulesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteFilterRulesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteFilterRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a route in the specified route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteFilterRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule, options *RouteFilterRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RouteFilterRulesClient.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, routeFilterName, ruleName, routeFilterRuleParameters, 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 *RouteFilterRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule, options *RouteFilterRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, routeFilterRuleParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified rule from a route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - ruleName - The name of the rule. +// - options - RouteFilterRulesClientBeginDeleteOptions contains the optional parameters for the RouteFilterRulesClient.BeginDelete +// method. +func (client *RouteFilterRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, options *RouteFilterRulesClientBeginDeleteOptions) (*runtime.Poller[RouteFilterRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, routeFilterName, ruleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteFilterRulesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteFilterRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified rule from a route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteFilterRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, options *RouteFilterRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RouteFilterRulesClient.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, routeFilterName, ruleName, 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 *RouteFilterRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, options *RouteFilterRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified rule from a route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - ruleName - The name of the rule. +// - options - RouteFilterRulesClientGetOptions contains the optional parameters for the RouteFilterRulesClient.Get method. +func (client *RouteFilterRulesClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, options *RouteFilterRulesClientGetOptions) (RouteFilterRulesClientGetResponse, error) { + var err error + const operationName = "RouteFilterRulesClient.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, routeFilterName, ruleName, options) + if err != nil { + return RouteFilterRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RouteFilterRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RouteFilterRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RouteFilterRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, options *RouteFilterRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RouteFilterRulesClient) getHandleResponse(resp *http.Response) (RouteFilterRulesClientGetResponse, error) { + result := RouteFilterRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilterRule); err != nil { + return RouteFilterRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListByRouteFilterPager - Gets all RouteFilterRules in a route filter. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - options - RouteFilterRulesClientListByRouteFilterOptions contains the optional parameters for the RouteFilterRulesClient.NewListByRouteFilterPager +// method. +func (client *RouteFilterRulesClient) NewListByRouteFilterPager(resourceGroupName string, routeFilterName string, options *RouteFilterRulesClientListByRouteFilterOptions) *runtime.Pager[RouteFilterRulesClientListByRouteFilterResponse] { + return runtime.NewPager(runtime.PagingHandler[RouteFilterRulesClientListByRouteFilterResponse]{ + More: func(page RouteFilterRulesClientListByRouteFilterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RouteFilterRulesClientListByRouteFilterResponse) (RouteFilterRulesClientListByRouteFilterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RouteFilterRulesClient.NewListByRouteFilterPager") + 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.listByRouteFilterCreateRequest(ctx, resourceGroupName, routeFilterName, options) + }, nil) + if err != nil { + return RouteFilterRulesClientListByRouteFilterResponse{}, err + } + return client.listByRouteFilterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByRouteFilterCreateRequest creates the ListByRouteFilter request. +func (client *RouteFilterRulesClient) listByRouteFilterCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFilterRulesClientListByRouteFilterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByRouteFilterHandleResponse handles the ListByRouteFilter response. +func (client *RouteFilterRulesClient) listByRouteFilterHandleResponse(resp *http.Response) (RouteFilterRulesClientListByRouteFilterResponse, error) { + result := RouteFilterRulesClientListByRouteFilterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilterRuleListResult); err != nil { + return RouteFilterRulesClientListByRouteFilterResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routefilters_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routefilters_client.go new file mode 100644 index 000000000..58b6b7c29 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routefilters_client.go @@ -0,0 +1,452 @@ +//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 armnetwork + +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" +) + +// RouteFiltersClient contains the methods for the RouteFilters group. +// Don't use this type directly, use NewRouteFiltersClient() instead. +type RouteFiltersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRouteFiltersClient creates a new instance of RouteFiltersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewRouteFiltersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RouteFiltersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RouteFiltersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a route filter in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - routeFilterParameters - Parameters supplied to the create or update route filter operation. +// - options - RouteFiltersClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteFiltersClient.BeginCreateOrUpdate +// method. +func (client *RouteFiltersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, options *RouteFiltersClientBeginCreateOrUpdateOptions) (*runtime.Poller[RouteFiltersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, routeFilterName, routeFilterParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteFiltersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteFiltersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a route filter in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteFiltersClient) createOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, options *RouteFiltersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RouteFiltersClient.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, routeFilterName, routeFilterParameters, 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 *RouteFiltersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, options *RouteFiltersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, routeFilterParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - options - RouteFiltersClientBeginDeleteOptions contains the optional parameters for the RouteFiltersClient.BeginDelete +// method. +func (client *RouteFiltersClient) BeginDelete(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientBeginDeleteOptions) (*runtime.Poller[RouteFiltersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, routeFilterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteFiltersClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteFiltersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteFiltersClient) deleteOperation(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RouteFiltersClient.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, routeFilterName, 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 *RouteFiltersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - options - RouteFiltersClientGetOptions contains the optional parameters for the RouteFiltersClient.Get method. +func (client *RouteFiltersClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientGetOptions) (RouteFiltersClientGetResponse, error) { + var err error + const operationName = "RouteFiltersClient.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, routeFilterName, options) + if err != nil { + return RouteFiltersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RouteFiltersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RouteFiltersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RouteFiltersClient) getCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *RouteFiltersClient) getHandleResponse(resp *http.Response) (RouteFiltersClientGetResponse, error) { + result := RouteFiltersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilter); err != nil { + return RouteFiltersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all route filters in a subscription. +// +// Generated from API version 2023-05-01 +// - options - RouteFiltersClientListOptions contains the optional parameters for the RouteFiltersClient.NewListPager method. +func (client *RouteFiltersClient) NewListPager(options *RouteFiltersClientListOptions) *runtime.Pager[RouteFiltersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RouteFiltersClientListResponse]{ + More: func(page RouteFiltersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RouteFiltersClientListResponse) (RouteFiltersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RouteFiltersClient.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 RouteFiltersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RouteFiltersClient) listCreateRequest(ctx context.Context, options *RouteFiltersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RouteFiltersClient) listHandleResponse(resp *http.Response) (RouteFiltersClientListResponse, error) { + result := RouteFiltersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilterListResult); err != nil { + return RouteFiltersClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all route filters in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - RouteFiltersClientListByResourceGroupOptions contains the optional parameters for the RouteFiltersClient.NewListByResourceGroupPager +// method. +func (client *RouteFiltersClient) NewListByResourceGroupPager(resourceGroupName string, options *RouteFiltersClientListByResourceGroupOptions) *runtime.Pager[RouteFiltersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[RouteFiltersClientListByResourceGroupResponse]{ + More: func(page RouteFiltersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RouteFiltersClientListByResourceGroupResponse) (RouteFiltersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RouteFiltersClient.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 RouteFiltersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *RouteFiltersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *RouteFiltersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *RouteFiltersClient) listByResourceGroupHandleResponse(resp *http.Response) (RouteFiltersClientListByResourceGroupResponse, error) { + result := RouteFiltersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilterListResult); err != nil { + return RouteFiltersClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates tags of a route filter. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeFilterName - The name of the route filter. +// - parameters - Parameters supplied to update route filter tags. +// - options - RouteFiltersClientUpdateTagsOptions contains the optional parameters for the RouteFiltersClient.UpdateTags method. +func (client *RouteFiltersClient) UpdateTags(ctx context.Context, resourceGroupName string, routeFilterName string, parameters TagsObject, options *RouteFiltersClientUpdateTagsOptions) (RouteFiltersClientUpdateTagsResponse, error) { + var err error + const operationName = "RouteFiltersClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, routeFilterName, parameters, options) + if err != nil { + return RouteFiltersClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RouteFiltersClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RouteFiltersClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *RouteFiltersClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, parameters TagsObject, options *RouteFiltersClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeFilterName == "" { + return nil, errors.New("parameter routeFilterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *RouteFiltersClient) updateTagsHandleResponse(resp *http.Response) (RouteFiltersClientUpdateTagsResponse, error) { + result := RouteFiltersClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilter); err != nil { + return RouteFiltersClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routemaps_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routemaps_client.go new file mode 100644 index 000000000..9ccc8abcd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routemaps_client.go @@ -0,0 +1,345 @@ +//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 armnetwork + +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" +) + +// RouteMapsClient contains the methods for the RouteMaps group. +// Don't use this type directly, use NewRouteMapsClient() instead. +type RouteMapsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRouteMapsClient creates a new instance of RouteMapsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewRouteMapsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RouteMapsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RouteMapsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a RouteMap if it doesn't exist else updates the existing one. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RouteMap's resource group. +// - virtualHubName - The name of the VirtualHub containing the RouteMap. +// - routeMapName - The name of the RouteMap. +// - routeMapParameters - Parameters supplied to create or update a RouteMap. +// - options - RouteMapsClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteMapsClient.BeginCreateOrUpdate +// method. +func (client *RouteMapsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, routeMapParameters RouteMap, options *RouteMapsClientBeginCreateOrUpdateOptions) (*runtime.Poller[RouteMapsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, routeMapName, routeMapParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteMapsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteMapsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a RouteMap if it doesn't exist else updates the existing one. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteMapsClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, routeMapParameters RouteMap, options *RouteMapsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RouteMapsClient.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, virtualHubName, routeMapName, routeMapParameters, 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 *RouteMapsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, routeMapParameters RouteMap, options *RouteMapsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeMaps/{routeMapName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeMapName == "" { + return nil, errors.New("parameter routeMapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeMapName}", url.PathEscape(routeMapName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, routeMapParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a RouteMap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RouteMap's resource group. +// - virtualHubName - The name of the VirtualHub containing the RouteMap. +// - routeMapName - The name of the RouteMap. +// - options - RouteMapsClientBeginDeleteOptions contains the optional parameters for the RouteMapsClient.BeginDelete method. +func (client *RouteMapsClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, options *RouteMapsClientBeginDeleteOptions) (*runtime.Poller[RouteMapsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, routeMapName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteMapsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteMapsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a RouteMap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteMapsClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, options *RouteMapsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RouteMapsClient.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, virtualHubName, routeMapName, 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 *RouteMapsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, options *RouteMapsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeMaps/{routeMapName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeMapName == "" { + return nil, errors.New("parameter routeMapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeMapName}", url.PathEscape(routeMapName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a RouteMap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RouteMap's resource group. +// - virtualHubName - The name of the VirtualHub containing the RouteMap. +// - routeMapName - The name of the RouteMap. +// - options - RouteMapsClientGetOptions contains the optional parameters for the RouteMapsClient.Get method. +func (client *RouteMapsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, options *RouteMapsClientGetOptions) (RouteMapsClientGetResponse, error) { + var err error + const operationName = "RouteMapsClient.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, virtualHubName, routeMapName, options) + if err != nil { + return RouteMapsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RouteMapsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RouteMapsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RouteMapsClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, options *RouteMapsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeMaps/{routeMapName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeMapName == "" { + return nil, errors.New("parameter routeMapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeMapName}", url.PathEscape(routeMapName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RouteMapsClient) getHandleResponse(resp *http.Response) (RouteMapsClientGetResponse, error) { + result := RouteMapsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteMap); err != nil { + return RouteMapsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves the details of all RouteMaps. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RouteMap's resource group'. +// - virtualHubName - The name of the VirtualHub containing the RouteMap. +// - options - RouteMapsClientListOptions contains the optional parameters for the RouteMapsClient.NewListPager method. +func (client *RouteMapsClient) NewListPager(resourceGroupName string, virtualHubName string, options *RouteMapsClientListOptions) *runtime.Pager[RouteMapsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RouteMapsClientListResponse]{ + More: func(page RouteMapsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RouteMapsClientListResponse) (RouteMapsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RouteMapsClient.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, virtualHubName, options) + }, nil) + if err != nil { + return RouteMapsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RouteMapsClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *RouteMapsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeMaps" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RouteMapsClient) listHandleResponse(resp *http.Response) (RouteMapsClientListResponse, error) { + result := RouteMapsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListRouteMapsResult); err != nil { + return RouteMapsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routes_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routes_client.go new file mode 100644 index 000000000..1574341d5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routes_client.go @@ -0,0 +1,345 @@ +//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 armnetwork + +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" +) + +// RoutesClient contains the methods for the Routes group. +// Don't use this type directly, use NewRoutesClient() instead. +type RoutesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRoutesClient creates a new instance of RoutesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewRoutesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RoutesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RoutesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a route in the specified route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - routeName - The name of the route. +// - routeParameters - Parameters supplied to the create or update route operation. +// - options - RoutesClientBeginCreateOrUpdateOptions contains the optional parameters for the RoutesClient.BeginCreateOrUpdate +// method. +func (client *RoutesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters Route, options *RoutesClientBeginCreateOrUpdateOptions) (*runtime.Poller[RoutesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, routeTableName, routeName, routeParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RoutesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RoutesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a route in the specified route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RoutesClient) createOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters Route, options *RoutesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RoutesClient.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, routeTableName, routeName, routeParameters, 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 *RoutesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters Route, options *RoutesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + if routeName == "" { + return nil, errors.New("parameter routeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeName}", url.PathEscape(routeName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, routeParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified route from a route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - routeName - The name of the route. +// - options - RoutesClientBeginDeleteOptions contains the optional parameters for the RoutesClient.BeginDelete method. +func (client *RoutesClient) BeginDelete(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, options *RoutesClientBeginDeleteOptions) (*runtime.Poller[RoutesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, routeTableName, routeName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RoutesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RoutesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified route from a route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RoutesClient) deleteOperation(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, options *RoutesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RoutesClient.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, routeTableName, routeName, 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 *RoutesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, options *RoutesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + if routeName == "" { + return nil, errors.New("parameter routeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeName}", url.PathEscape(routeName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified route from a route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - routeName - The name of the route. +// - options - RoutesClientGetOptions contains the optional parameters for the RoutesClient.Get method. +func (client *RoutesClient) Get(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, options *RoutesClientGetOptions) (RoutesClientGetResponse, error) { + var err error + const operationName = "RoutesClient.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, routeTableName, routeName, options) + if err != nil { + return RoutesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RoutesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RoutesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RoutesClient) getCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, options *RoutesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + if routeName == "" { + return nil, errors.New("parameter routeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeName}", url.PathEscape(routeName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RoutesClient) getHandleResponse(resp *http.Response) (RoutesClientGetResponse, error) { + result := RoutesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Route); err != nil { + return RoutesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all routes in a route table. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - options - RoutesClientListOptions contains the optional parameters for the RoutesClient.NewListPager method. +func (client *RoutesClient) NewListPager(resourceGroupName string, routeTableName string, options *RoutesClientListOptions) *runtime.Pager[RoutesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RoutesClientListResponse]{ + More: func(page RoutesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RoutesClientListResponse) (RoutesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RoutesClient.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, routeTableName, options) + }, nil) + if err != nil { + return RoutesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RoutesClient) listCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, options *RoutesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RoutesClient) listHandleResponse(resp *http.Response) (RoutesClientListResponse, error) { + result := RoutesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteListResult); err != nil { + return RoutesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routetables_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routetables_client.go new file mode 100644 index 000000000..c3da88450 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routetables_client.go @@ -0,0 +1,450 @@ +//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 armnetwork + +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" +) + +// RouteTablesClient contains the methods for the RouteTables group. +// Don't use this type directly, use NewRouteTablesClient() instead. +type RouteTablesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRouteTablesClient creates a new instance of RouteTablesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewRouteTablesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RouteTablesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RouteTablesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or updates a route table in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - parameters - Parameters supplied to the create or update route table operation. +// - options - RouteTablesClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteTablesClient.BeginCreateOrUpdate +// method. +func (client *RouteTablesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, parameters RouteTable, options *RouteTablesClientBeginCreateOrUpdateOptions) (*runtime.Poller[RouteTablesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, routeTableName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteTablesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteTablesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or updates a route table in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteTablesClient) createOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, parameters RouteTable, options *RouteTablesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RouteTablesClient.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, routeTableName, 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 *RouteTablesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, parameters RouteTable, options *RouteTablesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-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 route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - options - RouteTablesClientBeginDeleteOptions contains the optional parameters for the RouteTablesClient.BeginDelete method. +func (client *RouteTablesClient) BeginDelete(ctx context.Context, resourceGroupName string, routeTableName string, options *RouteTablesClientBeginDeleteOptions) (*runtime.Poller[RouteTablesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, routeTableName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RouteTablesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RouteTablesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RouteTablesClient) deleteOperation(ctx context.Context, resourceGroupName string, routeTableName string, options *RouteTablesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RouteTablesClient.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, routeTableName, 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 *RouteTablesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, options *RouteTablesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified route table. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - options - RouteTablesClientGetOptions contains the optional parameters for the RouteTablesClient.Get method. +func (client *RouteTablesClient) Get(ctx context.Context, resourceGroupName string, routeTableName string, options *RouteTablesClientGetOptions) (RouteTablesClientGetResponse, error) { + var err error + const operationName = "RouteTablesClient.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, routeTableName, options) + if err != nil { + return RouteTablesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RouteTablesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RouteTablesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RouteTablesClient) getCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, options *RouteTablesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *RouteTablesClient) getHandleResponse(resp *http.Response) (RouteTablesClientGetResponse, error) { + result := RouteTablesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteTable); err != nil { + return RouteTablesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all route tables in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - RouteTablesClientListOptions contains the optional parameters for the RouteTablesClient.NewListPager method. +func (client *RouteTablesClient) NewListPager(resourceGroupName string, options *RouteTablesClientListOptions) *runtime.Pager[RouteTablesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RouteTablesClientListResponse]{ + More: func(page RouteTablesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RouteTablesClientListResponse) (RouteTablesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RouteTablesClient.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, options) + }, nil) + if err != nil { + return RouteTablesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RouteTablesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *RouteTablesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RouteTablesClient) listHandleResponse(resp *http.Response) (RouteTablesClientListResponse, error) { + result := RouteTablesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteTableListResult); err != nil { + return RouteTablesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all route tables in a subscription. +// +// Generated from API version 2023-05-01 +// - options - RouteTablesClientListAllOptions contains the optional parameters for the RouteTablesClient.NewListAllPager method. +func (client *RouteTablesClient) NewListAllPager(options *RouteTablesClientListAllOptions) *runtime.Pager[RouteTablesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[RouteTablesClientListAllResponse]{ + More: func(page RouteTablesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RouteTablesClientListAllResponse) (RouteTablesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RouteTablesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return RouteTablesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *RouteTablesClient) listAllCreateRequest(ctx context.Context, options *RouteTablesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *RouteTablesClient) listAllHandleResponse(resp *http.Response) (RouteTablesClientListAllResponse, error) { + result := RouteTablesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteTableListResult); err != nil { + return RouteTablesClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a route table tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - routeTableName - The name of the route table. +// - parameters - Parameters supplied to update route table tags. +// - options - RouteTablesClientUpdateTagsOptions contains the optional parameters for the RouteTablesClient.UpdateTags method. +func (client *RouteTablesClient) UpdateTags(ctx context.Context, resourceGroupName string, routeTableName string, parameters TagsObject, options *RouteTablesClientUpdateTagsOptions) (RouteTablesClientUpdateTagsResponse, error) { + var err error + const operationName = "RouteTablesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, routeTableName, parameters, options) + if err != nil { + return RouteTablesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RouteTablesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RouteTablesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *RouteTablesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, parameters TagsObject, options *RouteTablesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *RouteTablesClient) updateTagsHandleResponse(resp *http.Response) (RouteTablesClientUpdateTagsResponse, error) { + result := RouteTablesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RouteTable); err != nil { + return RouteTablesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routingintent_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routingintent_client.go new file mode 100644 index 000000000..14c690fe7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/routingintent_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 armnetwork + +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" +) + +// RoutingIntentClient contains the methods for the RoutingIntent group. +// Don't use this type directly, use NewRoutingIntentClient() instead. +type RoutingIntentClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRoutingIntentClient creates a new instance of RoutingIntentClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewRoutingIntentClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RoutingIntentClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RoutingIntentClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a RoutingIntent resource if it doesn't exist else updates the existing RoutingIntent. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RoutingIntent. +// - virtualHubName - The name of the VirtualHub. +// - routingIntentName - The name of the per VirtualHub singleton Routing Intent resource. +// - routingIntentParameters - Parameters supplied to create or update RoutingIntent. +// - options - RoutingIntentClientBeginCreateOrUpdateOptions contains the optional parameters for the RoutingIntentClient.BeginCreateOrUpdate +// method. +func (client *RoutingIntentClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, routingIntentParameters RoutingIntent, options *RoutingIntentClientBeginCreateOrUpdateOptions) (*runtime.Poller[RoutingIntentClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, routingIntentName, routingIntentParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RoutingIntentClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RoutingIntentClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a RoutingIntent resource if it doesn't exist else updates the existing RoutingIntent. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RoutingIntentClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, routingIntentParameters RoutingIntent, options *RoutingIntentClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RoutingIntentClient.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, virtualHubName, routingIntentName, routingIntentParameters, 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 *RoutingIntentClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, routingIntentParameters RoutingIntent, options *RoutingIntentClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routingIntent/{routingIntentName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routingIntentName == "" { + return nil, errors.New("parameter routingIntentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routingIntentName}", url.PathEscape(routingIntentName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, routingIntentParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a RoutingIntent. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RoutingIntent. +// - virtualHubName - The name of the VirtualHub. +// - routingIntentName - The name of the RoutingIntent. +// - options - RoutingIntentClientBeginDeleteOptions contains the optional parameters for the RoutingIntentClient.BeginDelete +// method. +func (client *RoutingIntentClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, options *RoutingIntentClientBeginDeleteOptions) (*runtime.Poller[RoutingIntentClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, routingIntentName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RoutingIntentClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RoutingIntentClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a RoutingIntent. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *RoutingIntentClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, options *RoutingIntentClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RoutingIntentClient.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, virtualHubName, routingIntentName, 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 *RoutingIntentClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, options *RoutingIntentClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routingIntent/{routingIntentName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routingIntentName == "" { + return nil, errors.New("parameter routingIntentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routingIntentName}", url.PathEscape(routingIntentName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a RoutingIntent. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the RoutingIntent. +// - virtualHubName - The name of the VirtualHub. +// - routingIntentName - The name of the RoutingIntent. +// - options - RoutingIntentClientGetOptions contains the optional parameters for the RoutingIntentClient.Get method. +func (client *RoutingIntentClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, options *RoutingIntentClientGetOptions) (RoutingIntentClientGetResponse, error) { + var err error + const operationName = "RoutingIntentClient.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, virtualHubName, routingIntentName, options) + if err != nil { + return RoutingIntentClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RoutingIntentClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RoutingIntentClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RoutingIntentClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, options *RoutingIntentClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routingIntent/{routingIntentName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routingIntentName == "" { + return nil, errors.New("parameter routingIntentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routingIntentName}", url.PathEscape(routingIntentName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RoutingIntentClient) getHandleResponse(resp *http.Response) (RoutingIntentClientGetResponse, error) { + result := RoutingIntentClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RoutingIntent); err != nil { + return RoutingIntentClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves the details of all RoutingIntent child resources of the VirtualHub. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - RoutingIntentClientListOptions contains the optional parameters for the RoutingIntentClient.NewListPager method. +func (client *RoutingIntentClient) NewListPager(resourceGroupName string, virtualHubName string, options *RoutingIntentClientListOptions) *runtime.Pager[RoutingIntentClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RoutingIntentClientListResponse]{ + More: func(page RoutingIntentClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RoutingIntentClientListResponse) (RoutingIntentClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RoutingIntentClient.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, virtualHubName, options) + }, nil) + if err != nil { + return RoutingIntentClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RoutingIntentClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *RoutingIntentClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routingIntent" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RoutingIntentClient) listHandleResponse(resp *http.Response) (RoutingIntentClientListResponse, error) { + result := RoutingIntentClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListRoutingIntentResult); err != nil { + return RoutingIntentClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/scopeconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/scopeconnections_client.go new file mode 100644 index 000000000..eed7c65cc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/scopeconnections_client.go @@ -0,0 +1,319 @@ +//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 armnetwork + +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" +) + +// ScopeConnectionsClient contains the methods for the ScopeConnections group. +// Don't use this type directly, use NewScopeConnectionsClient() instead. +type ScopeConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewScopeConnectionsClient creates a new instance of ScopeConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewScopeConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ScopeConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ScopeConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates scope connection from Network Manager +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - scopeConnectionName - Name for the cross-tenant connection. +// - parameters - Scope connection to be created/updated. +// - options - ScopeConnectionsClientCreateOrUpdateOptions contains the optional parameters for the ScopeConnectionsClient.CreateOrUpdate +// method. +func (client *ScopeConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string, parameters ScopeConnection, options *ScopeConnectionsClientCreateOrUpdateOptions) (ScopeConnectionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ScopeConnectionsClient.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, networkManagerName, scopeConnectionName, parameters, options) + if err != nil { + return ScopeConnectionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScopeConnectionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ScopeConnectionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ScopeConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string, parameters ScopeConnection, options *ScopeConnectionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/scopeConnections/{scopeConnectionName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if scopeConnectionName == "" { + return nil, errors.New("parameter scopeConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scopeConnectionName}", url.PathEscape(scopeConnectionName)) + 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-05-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 *ScopeConnectionsClient) createOrUpdateHandleResponse(resp *http.Response) (ScopeConnectionsClientCreateOrUpdateResponse, error) { + result := ScopeConnectionsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScopeConnection); err != nil { + return ScopeConnectionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete the pending scope connection created by this network manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - scopeConnectionName - Name for the cross-tenant connection. +// - options - ScopeConnectionsClientDeleteOptions contains the optional parameters for the ScopeConnectionsClient.Delete method. +func (client *ScopeConnectionsClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string, options *ScopeConnectionsClientDeleteOptions) (ScopeConnectionsClientDeleteResponse, error) { + var err error + const operationName = "ScopeConnectionsClient.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, networkManagerName, scopeConnectionName, options) + if err != nil { + return ScopeConnectionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScopeConnectionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScopeConnectionsClientDeleteResponse{}, err + } + return ScopeConnectionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ScopeConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string, options *ScopeConnectionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/scopeConnections/{scopeConnectionName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if scopeConnectionName == "" { + return nil, errors.New("parameter scopeConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scopeConnectionName}", url.PathEscape(scopeConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get specified scope connection created by this Network Manager. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - scopeConnectionName - Name for the cross-tenant connection. +// - options - ScopeConnectionsClientGetOptions contains the optional parameters for the ScopeConnectionsClient.Get method. +func (client *ScopeConnectionsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string, options *ScopeConnectionsClientGetOptions) (ScopeConnectionsClientGetResponse, error) { + var err error + const operationName = "ScopeConnectionsClient.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, networkManagerName, scopeConnectionName, options) + if err != nil { + return ScopeConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScopeConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScopeConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScopeConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string, options *ScopeConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/scopeConnections/{scopeConnectionName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if scopeConnectionName == "" { + return nil, errors.New("parameter scopeConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scopeConnectionName}", url.PathEscape(scopeConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ScopeConnectionsClient) getHandleResponse(resp *http.Response) (ScopeConnectionsClientGetResponse, error) { + result := ScopeConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScopeConnection); err != nil { + return ScopeConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all scope connections created by this network manager. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - options - ScopeConnectionsClientListOptions contains the optional parameters for the ScopeConnectionsClient.NewListPager +// method. +func (client *ScopeConnectionsClient) NewListPager(resourceGroupName string, networkManagerName string, options *ScopeConnectionsClientListOptions) *runtime.Pager[ScopeConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ScopeConnectionsClientListResponse]{ + More: func(page ScopeConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ScopeConnectionsClientListResponse) (ScopeConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ScopeConnectionsClient.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, networkManagerName, options) + }, nil) + if err != nil { + return ScopeConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ScopeConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, options *ScopeConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/scopeConnections" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ScopeConnectionsClient) listHandleResponse(resp *http.Response) (ScopeConnectionsClientListResponse, error) { + result := ScopeConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScopeConnectionListResult); err != nil { + return ScopeConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securityadminconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securityadminconfigurations_client.go new file mode 100644 index 000000000..65a685236 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securityadminconfigurations_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 armnetwork + +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" +) + +// SecurityAdminConfigurationsClient contains the methods for the SecurityAdminConfigurations group. +// Don't use this type directly, use NewSecurityAdminConfigurationsClient() instead. +type SecurityAdminConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSecurityAdminConfigurationsClient creates a new instance of SecurityAdminConfigurationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewSecurityAdminConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SecurityAdminConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SecurityAdminConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates a network manager security admin configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - securityAdminConfiguration - The security admin configuration to create or update +// - options - SecurityAdminConfigurationsClientCreateOrUpdateOptions contains the optional parameters for the SecurityAdminConfigurationsClient.CreateOrUpdate +// method. +func (client *SecurityAdminConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, securityAdminConfiguration SecurityAdminConfiguration, options *SecurityAdminConfigurationsClientCreateOrUpdateOptions) (SecurityAdminConfigurationsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "SecurityAdminConfigurationsClient.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, networkManagerName, configurationName, securityAdminConfiguration, options) + if err != nil { + return SecurityAdminConfigurationsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecurityAdminConfigurationsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SecurityAdminConfigurationsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SecurityAdminConfigurationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, securityAdminConfiguration SecurityAdminConfiguration, options *SecurityAdminConfigurationsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, securityAdminConfiguration); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *SecurityAdminConfigurationsClient) createOrUpdateHandleResponse(resp *http.Response) (SecurityAdminConfigurationsClientCreateOrUpdateResponse, error) { + result := SecurityAdminConfigurationsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityAdminConfiguration); err != nil { + return SecurityAdminConfigurationsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes a network manager security admin configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - options - SecurityAdminConfigurationsClientBeginDeleteOptions contains the optional parameters for the SecurityAdminConfigurationsClient.BeginDelete +// method. +func (client *SecurityAdminConfigurationsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *SecurityAdminConfigurationsClientBeginDeleteOptions) (*runtime.Poller[SecurityAdminConfigurationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkManagerName, configurationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SecurityAdminConfigurationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SecurityAdminConfigurationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a network manager security admin configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SecurityAdminConfigurationsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *SecurityAdminConfigurationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SecurityAdminConfigurationsClient.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, networkManagerName, configurationName, 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 *SecurityAdminConfigurationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *SecurityAdminConfigurationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + 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-05-01") + if options != nil && options.Force != nil { + reqQP.Set("force", strconv.FormatBool(*options.Force)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves a network manager security admin configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - configurationName - The name of the network manager Security Configuration. +// - options - SecurityAdminConfigurationsClientGetOptions contains the optional parameters for the SecurityAdminConfigurationsClient.Get +// method. +func (client *SecurityAdminConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *SecurityAdminConfigurationsClientGetOptions) (SecurityAdminConfigurationsClientGetResponse, error) { + var err error + const operationName = "SecurityAdminConfigurationsClient.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, networkManagerName, configurationName, options) + if err != nil { + return SecurityAdminConfigurationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecurityAdminConfigurationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecurityAdminConfigurationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SecurityAdminConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, options *SecurityAdminConfigurationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SecurityAdminConfigurationsClient) getHandleResponse(resp *http.Response) (SecurityAdminConfigurationsClientGetResponse, error) { + result := SecurityAdminConfigurationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityAdminConfiguration); err != nil { + return SecurityAdminConfigurationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the network manager security admin configurations in a network manager, in a paginated format. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - options - SecurityAdminConfigurationsClientListOptions contains the optional parameters for the SecurityAdminConfigurationsClient.NewListPager +// method. +func (client *SecurityAdminConfigurationsClient) NewListPager(resourceGroupName string, networkManagerName string, options *SecurityAdminConfigurationsClientListOptions) *runtime.Pager[SecurityAdminConfigurationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SecurityAdminConfigurationsClientListResponse]{ + More: func(page SecurityAdminConfigurationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SecurityAdminConfigurationsClientListResponse) (SecurityAdminConfigurationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SecurityAdminConfigurationsClient.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, networkManagerName, options) + }, nil) + if err != nil { + return SecurityAdminConfigurationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SecurityAdminConfigurationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, options *SecurityAdminConfigurationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SecurityAdminConfigurationsClient) listHandleResponse(resp *http.Response) (SecurityAdminConfigurationsClientListResponse, error) { + result := SecurityAdminConfigurationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityAdminConfigurationListResult); err != nil { + return SecurityAdminConfigurationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securitygroups_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securitygroups_client.go new file mode 100644 index 000000000..4465ab507 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securitygroups_client.go @@ -0,0 +1,453 @@ +//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 armnetwork + +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" +) + +// SecurityGroupsClient contains the methods for the NetworkSecurityGroups group. +// Don't use this type directly, use NewSecurityGroupsClient() instead. +type SecurityGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSecurityGroupsClient creates a new instance of SecurityGroupsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewSecurityGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SecurityGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SecurityGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a network security group in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - parameters - Parameters supplied to the create or update network security group operation. +// - options - SecurityGroupsClientBeginCreateOrUpdateOptions contains the optional parameters for the SecurityGroupsClient.BeginCreateOrUpdate +// method. +func (client *SecurityGroupsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, options *SecurityGroupsClientBeginCreateOrUpdateOptions) (*runtime.Poller[SecurityGroupsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkSecurityGroupName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SecurityGroupsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SecurityGroupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a network security group in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SecurityGroupsClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, options *SecurityGroupsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SecurityGroupsClient.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, networkSecurityGroupName, 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 *SecurityGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, options *SecurityGroupsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + 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-05-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 network security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - options - SecurityGroupsClientBeginDeleteOptions contains the optional parameters for the SecurityGroupsClient.BeginDelete +// method. +func (client *SecurityGroupsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, options *SecurityGroupsClientBeginDeleteOptions) (*runtime.Poller[SecurityGroupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkSecurityGroupName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SecurityGroupsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SecurityGroupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified network security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SecurityGroupsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, options *SecurityGroupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SecurityGroupsClient.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, networkSecurityGroupName, 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 *SecurityGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, options *SecurityGroupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified network security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - options - SecurityGroupsClientGetOptions contains the optional parameters for the SecurityGroupsClient.Get method. +func (client *SecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, options *SecurityGroupsClientGetOptions) (SecurityGroupsClientGetResponse, error) { + var err error + const operationName = "SecurityGroupsClient.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, networkSecurityGroupName, options) + if err != nil { + return SecurityGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecurityGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecurityGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SecurityGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, options *SecurityGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *SecurityGroupsClient) getHandleResponse(resp *http.Response) (SecurityGroupsClientGetResponse, error) { + result := SecurityGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityGroup); err != nil { + return SecurityGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all network security groups in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - SecurityGroupsClientListOptions contains the optional parameters for the SecurityGroupsClient.NewListPager method. +func (client *SecurityGroupsClient) NewListPager(resourceGroupName string, options *SecurityGroupsClientListOptions) *runtime.Pager[SecurityGroupsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SecurityGroupsClientListResponse]{ + More: func(page SecurityGroupsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SecurityGroupsClientListResponse) (SecurityGroupsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SecurityGroupsClient.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, options) + }, nil) + if err != nil { + return SecurityGroupsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SecurityGroupsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *SecurityGroupsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SecurityGroupsClient) listHandleResponse(resp *http.Response) (SecurityGroupsClientListResponse, error) { + result := SecurityGroupsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityGroupListResult); err != nil { + return SecurityGroupsClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all network security groups in a subscription. +// +// Generated from API version 2023-05-01 +// - options - SecurityGroupsClientListAllOptions contains the optional parameters for the SecurityGroupsClient.NewListAllPager +// method. +func (client *SecurityGroupsClient) NewListAllPager(options *SecurityGroupsClientListAllOptions) *runtime.Pager[SecurityGroupsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[SecurityGroupsClientListAllResponse]{ + More: func(page SecurityGroupsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SecurityGroupsClientListAllResponse) (SecurityGroupsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SecurityGroupsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return SecurityGroupsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *SecurityGroupsClient) listAllCreateRequest(ctx context.Context, options *SecurityGroupsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *SecurityGroupsClient) listAllHandleResponse(resp *http.Response) (SecurityGroupsClientListAllResponse, error) { + result := SecurityGroupsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityGroupListResult); err != nil { + return SecurityGroupsClientListAllResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a network security group tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - parameters - Parameters supplied to update network security group tags. +// - options - SecurityGroupsClientUpdateTagsOptions contains the optional parameters for the SecurityGroupsClient.UpdateTags +// method. +func (client *SecurityGroupsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject, options *SecurityGroupsClientUpdateTagsOptions) (SecurityGroupsClientUpdateTagsResponse, error) { + var err error + const operationName = "SecurityGroupsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, networkSecurityGroupName, parameters, options) + if err != nil { + return SecurityGroupsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecurityGroupsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecurityGroupsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *SecurityGroupsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject, options *SecurityGroupsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *SecurityGroupsClient) updateTagsHandleResponse(resp *http.Response) (SecurityGroupsClientUpdateTagsResponse, error) { + result := SecurityGroupsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityGroup); err != nil { + return SecurityGroupsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securitypartnerproviders_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securitypartnerproviders_client.go new file mode 100644 index 000000000..08f18ad20 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securitypartnerproviders_client.go @@ -0,0 +1,452 @@ +//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 armnetwork + +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" +) + +// SecurityPartnerProvidersClient contains the methods for the SecurityPartnerProviders group. +// Don't use this type directly, use NewSecurityPartnerProvidersClient() instead. +type SecurityPartnerProvidersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSecurityPartnerProvidersClient creates a new instance of SecurityPartnerProvidersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewSecurityPartnerProvidersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SecurityPartnerProvidersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SecurityPartnerProvidersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Security Partner Provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - securityPartnerProviderName - The name of the Security Partner Provider. +// - parameters - Parameters supplied to the create or update Security Partner Provider operation. +// - options - SecurityPartnerProvidersClientBeginCreateOrUpdateOptions contains the optional parameters for the SecurityPartnerProvidersClient.BeginCreateOrUpdate +// method. +func (client *SecurityPartnerProvidersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters SecurityPartnerProvider, options *SecurityPartnerProvidersClientBeginCreateOrUpdateOptions) (*runtime.Poller[SecurityPartnerProvidersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, securityPartnerProviderName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SecurityPartnerProvidersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SecurityPartnerProvidersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Security Partner Provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SecurityPartnerProvidersClient) createOrUpdate(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters SecurityPartnerProvider, options *SecurityPartnerProvidersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SecurityPartnerProvidersClient.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, securityPartnerProviderName, 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 *SecurityPartnerProvidersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters SecurityPartnerProvider, options *SecurityPartnerProvidersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/securityPartnerProviders/{securityPartnerProviderName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if securityPartnerProviderName == "" { + return nil, errors.New("parameter securityPartnerProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{securityPartnerProviderName}", url.PathEscape(securityPartnerProviderName)) + 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-05-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 Security Partner Provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - securityPartnerProviderName - The name of the Security Partner Provider. +// - options - SecurityPartnerProvidersClientBeginDeleteOptions contains the optional parameters for the SecurityPartnerProvidersClient.BeginDelete +// method. +func (client *SecurityPartnerProvidersClient) BeginDelete(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, options *SecurityPartnerProvidersClientBeginDeleteOptions) (*runtime.Poller[SecurityPartnerProvidersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, securityPartnerProviderName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SecurityPartnerProvidersClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SecurityPartnerProvidersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Security Partner Provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SecurityPartnerProvidersClient) deleteOperation(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, options *SecurityPartnerProvidersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SecurityPartnerProvidersClient.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, securityPartnerProviderName, 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 *SecurityPartnerProvidersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, options *SecurityPartnerProvidersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/securityPartnerProviders/{securityPartnerProviderName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if securityPartnerProviderName == "" { + return nil, errors.New("parameter securityPartnerProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{securityPartnerProviderName}", url.PathEscape(securityPartnerProviderName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Security Partner Provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - securityPartnerProviderName - The name of the Security Partner Provider. +// - options - SecurityPartnerProvidersClientGetOptions contains the optional parameters for the SecurityPartnerProvidersClient.Get +// method. +func (client *SecurityPartnerProvidersClient) Get(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, options *SecurityPartnerProvidersClientGetOptions) (SecurityPartnerProvidersClientGetResponse, error) { + var err error + const operationName = "SecurityPartnerProvidersClient.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, securityPartnerProviderName, options) + if err != nil { + return SecurityPartnerProvidersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecurityPartnerProvidersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecurityPartnerProvidersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SecurityPartnerProvidersClient) getCreateRequest(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, options *SecurityPartnerProvidersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/securityPartnerProviders/{securityPartnerProviderName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if securityPartnerProviderName == "" { + return nil, errors.New("parameter securityPartnerProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{securityPartnerProviderName}", url.PathEscape(securityPartnerProviderName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SecurityPartnerProvidersClient) getHandleResponse(resp *http.Response) (SecurityPartnerProvidersClientGetResponse, error) { + result := SecurityPartnerProvidersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityPartnerProvider); err != nil { + return SecurityPartnerProvidersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the Security Partner Providers in a subscription. +// +// Generated from API version 2023-05-01 +// - options - SecurityPartnerProvidersClientListOptions contains the optional parameters for the SecurityPartnerProvidersClient.NewListPager +// method. +func (client *SecurityPartnerProvidersClient) NewListPager(options *SecurityPartnerProvidersClientListOptions) *runtime.Pager[SecurityPartnerProvidersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SecurityPartnerProvidersClientListResponse]{ + More: func(page SecurityPartnerProvidersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SecurityPartnerProvidersClientListResponse) (SecurityPartnerProvidersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SecurityPartnerProvidersClient.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 SecurityPartnerProvidersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SecurityPartnerProvidersClient) listCreateRequest(ctx context.Context, options *SecurityPartnerProvidersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/securityPartnerProviders" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SecurityPartnerProvidersClient) listHandleResponse(resp *http.Response) (SecurityPartnerProvidersClientListResponse, error) { + result := SecurityPartnerProvidersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityPartnerProviderListResult); err != nil { + return SecurityPartnerProvidersClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all Security Partner Providers in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - SecurityPartnerProvidersClientListByResourceGroupOptions contains the optional parameters for the SecurityPartnerProvidersClient.NewListByResourceGroupPager +// method. +func (client *SecurityPartnerProvidersClient) NewListByResourceGroupPager(resourceGroupName string, options *SecurityPartnerProvidersClientListByResourceGroupOptions) *runtime.Pager[SecurityPartnerProvidersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[SecurityPartnerProvidersClientListByResourceGroupResponse]{ + More: func(page SecurityPartnerProvidersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SecurityPartnerProvidersClientListByResourceGroupResponse) (SecurityPartnerProvidersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SecurityPartnerProvidersClient.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 SecurityPartnerProvidersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *SecurityPartnerProvidersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SecurityPartnerProvidersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/securityPartnerProviders" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *SecurityPartnerProvidersClient) listByResourceGroupHandleResponse(resp *http.Response) (SecurityPartnerProvidersClientListByResourceGroupResponse, error) { + result := SecurityPartnerProvidersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityPartnerProviderListResult); err != nil { + return SecurityPartnerProvidersClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates tags of a Security Partner Provider resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - securityPartnerProviderName - The name of the Security Partner Provider. +// - parameters - Parameters supplied to update Security Partner Provider tags. +// - options - SecurityPartnerProvidersClientUpdateTagsOptions contains the optional parameters for the SecurityPartnerProvidersClient.UpdateTags +// method. +func (client *SecurityPartnerProvidersClient) UpdateTags(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters TagsObject, options *SecurityPartnerProvidersClientUpdateTagsOptions) (SecurityPartnerProvidersClientUpdateTagsResponse, error) { + var err error + const operationName = "SecurityPartnerProvidersClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, securityPartnerProviderName, parameters, options) + if err != nil { + return SecurityPartnerProvidersClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecurityPartnerProvidersClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecurityPartnerProvidersClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *SecurityPartnerProvidersClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters TagsObject, options *SecurityPartnerProvidersClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/securityPartnerProviders/{securityPartnerProviderName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if securityPartnerProviderName == "" { + return nil, errors.New("parameter securityPartnerProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{securityPartnerProviderName}", url.PathEscape(securityPartnerProviderName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *SecurityPartnerProvidersClient) updateTagsHandleResponse(resp *http.Response) (SecurityPartnerProvidersClientUpdateTagsResponse, error) { + result := SecurityPartnerProvidersClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityPartnerProvider); err != nil { + return SecurityPartnerProvidersClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securityrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securityrules_client.go new file mode 100644 index 000000000..bf51f10ba --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/securityrules_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 armnetwork + +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" +) + +// SecurityRulesClient contains the methods for the SecurityRules group. +// Don't use this type directly, use NewSecurityRulesClient() instead. +type SecurityRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSecurityRulesClient creates a new instance of SecurityRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewSecurityRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SecurityRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SecurityRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a security rule in the specified network security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - securityRuleName - The name of the security rule. +// - securityRuleParameters - Parameters supplied to the create or update network security rule operation. +// - options - SecurityRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the SecurityRulesClient.BeginCreateOrUpdate +// method. +func (client *SecurityRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, options *SecurityRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[SecurityRulesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SecurityRulesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SecurityRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a security rule in the specified network security group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SecurityRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, options *SecurityRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SecurityRulesClient.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, networkSecurityGroupName, securityRuleName, securityRuleParameters, 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 *SecurityRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, options *SecurityRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + if securityRuleName == "" { + return nil, errors.New("parameter securityRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{securityRuleName}", url.PathEscape(securityRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, securityRuleParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified network security rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - securityRuleName - The name of the security rule. +// - options - SecurityRulesClientBeginDeleteOptions contains the optional parameters for the SecurityRulesClient.BeginDelete +// method. +func (client *SecurityRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, options *SecurityRulesClientBeginDeleteOptions) (*runtime.Poller[SecurityRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SecurityRulesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SecurityRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified network security rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SecurityRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, options *SecurityRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SecurityRulesClient.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, networkSecurityGroupName, securityRuleName, 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 *SecurityRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, options *SecurityRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + if securityRuleName == "" { + return nil, errors.New("parameter securityRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{securityRuleName}", url.PathEscape(securityRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get the specified network security rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - securityRuleName - The name of the security rule. +// - options - SecurityRulesClientGetOptions contains the optional parameters for the SecurityRulesClient.Get method. +func (client *SecurityRulesClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, options *SecurityRulesClientGetOptions) (SecurityRulesClientGetResponse, error) { + var err error + const operationName = "SecurityRulesClient.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, networkSecurityGroupName, securityRuleName, options) + if err != nil { + return SecurityRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecurityRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecurityRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SecurityRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, options *SecurityRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + if securityRuleName == "" { + return nil, errors.New("parameter securityRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{securityRuleName}", url.PathEscape(securityRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SecurityRulesClient) getHandleResponse(resp *http.Response) (SecurityRulesClientGetResponse, error) { + result := SecurityRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityRule); err != nil { + return SecurityRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all security rules in a network security group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkSecurityGroupName - The name of the network security group. +// - options - SecurityRulesClientListOptions contains the optional parameters for the SecurityRulesClient.NewListPager method. +func (client *SecurityRulesClient) NewListPager(resourceGroupName string, networkSecurityGroupName string, options *SecurityRulesClientListOptions) *runtime.Pager[SecurityRulesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SecurityRulesClientListResponse]{ + More: func(page SecurityRulesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SecurityRulesClientListResponse) (SecurityRulesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SecurityRulesClient.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, networkSecurityGroupName, options) + }, nil) + if err != nil { + return SecurityRulesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SecurityRulesClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, options *SecurityRulesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkSecurityGroupName == "" { + return nil, errors.New("parameter networkSecurityGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkSecurityGroupName}", url.PathEscape(networkSecurityGroupName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SecurityRulesClient) listHandleResponse(resp *http.Response) (SecurityRulesClientListResponse, error) { + result := SecurityRulesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecurityRuleListResult); err != nil { + return SecurityRulesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceassociationlinks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceassociationlinks_client.go new file mode 100644 index 000000000..da40a3502 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceassociationlinks_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 armnetwork + +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" +) + +// ServiceAssociationLinksClient contains the methods for the ServiceAssociationLinks group. +// Don't use this type directly, use NewServiceAssociationLinksClient() instead. +type ServiceAssociationLinksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewServiceAssociationLinksClient creates a new instance of ServiceAssociationLinksClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewServiceAssociationLinksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServiceAssociationLinksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ServiceAssociationLinksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Gets a list of service association links for a subnet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - subnetName - The name of the subnet. +// - options - ServiceAssociationLinksClientListOptions contains the optional parameters for the ServiceAssociationLinksClient.List +// method. +func (client *ServiceAssociationLinksClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *ServiceAssociationLinksClientListOptions) (ServiceAssociationLinksClientListResponse, error) { + var err error + const operationName = "ServiceAssociationLinksClient.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, virtualNetworkName, subnetName, options) + if err != nil { + return ServiceAssociationLinksClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceAssociationLinksClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceAssociationLinksClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *ServiceAssociationLinksClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *ServiceAssociationLinksClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/ServiceAssociationLinks" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if subnetName == "" { + return nil, errors.New("parameter subnetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subnetName}", url.PathEscape(subnetName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ServiceAssociationLinksClient) listHandleResponse(resp *http.Response) (ServiceAssociationLinksClientListResponse, error) { + result := ServiceAssociationLinksClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceAssociationLinksListResult); err != nil { + return ServiceAssociationLinksClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceendpointpolicies_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceendpointpolicies_client.go new file mode 100644 index 000000000..8609cd22a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceendpointpolicies_client.go @@ -0,0 +1,455 @@ +//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 armnetwork + +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" +) + +// ServiceEndpointPoliciesClient contains the methods for the ServiceEndpointPolicies group. +// Don't use this type directly, use NewServiceEndpointPoliciesClient() instead. +type ServiceEndpointPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewServiceEndpointPoliciesClient creates a new instance of ServiceEndpointPoliciesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewServiceEndpointPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServiceEndpointPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ServiceEndpointPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a service Endpoint Policies. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the service endpoint policy. +// - parameters - Parameters supplied to the create or update service endpoint policy operation. +// - options - ServiceEndpointPoliciesClientBeginCreateOrUpdateOptions contains the optional parameters for the ServiceEndpointPoliciesClient.BeginCreateOrUpdate +// method. +func (client *ServiceEndpointPoliciesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters ServiceEndpointPolicy, options *ServiceEndpointPoliciesClientBeginCreateOrUpdateOptions) (*runtime.Poller[ServiceEndpointPoliciesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, serviceEndpointPolicyName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ServiceEndpointPoliciesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ServiceEndpointPoliciesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a service Endpoint Policies. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ServiceEndpointPoliciesClient) createOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters ServiceEndpointPolicy, options *ServiceEndpointPoliciesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ServiceEndpointPoliciesClient.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, serviceEndpointPolicyName, 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 *ServiceEndpointPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters ServiceEndpointPolicy, options *ServiceEndpointPoliciesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + 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-05-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 service endpoint policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the service endpoint policy. +// - options - ServiceEndpointPoliciesClientBeginDeleteOptions contains the optional parameters for the ServiceEndpointPoliciesClient.BeginDelete +// method. +func (client *ServiceEndpointPoliciesClient) BeginDelete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, options *ServiceEndpointPoliciesClientBeginDeleteOptions) (*runtime.Poller[ServiceEndpointPoliciesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, serviceEndpointPolicyName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ServiceEndpointPoliciesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ServiceEndpointPoliciesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified service endpoint policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ServiceEndpointPoliciesClient) deleteOperation(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, options *ServiceEndpointPoliciesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ServiceEndpointPoliciesClient.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, serviceEndpointPolicyName, 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 *ServiceEndpointPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, options *ServiceEndpointPoliciesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified service Endpoint Policies in a specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the service endpoint policy. +// - options - ServiceEndpointPoliciesClientGetOptions contains the optional parameters for the ServiceEndpointPoliciesClient.Get +// method. +func (client *ServiceEndpointPoliciesClient) Get(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, options *ServiceEndpointPoliciesClientGetOptions) (ServiceEndpointPoliciesClientGetResponse, error) { + var err error + const operationName = "ServiceEndpointPoliciesClient.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, serviceEndpointPolicyName, options) + if err != nil { + return ServiceEndpointPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceEndpointPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceEndpointPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ServiceEndpointPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, options *ServiceEndpointPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *ServiceEndpointPoliciesClient) getHandleResponse(resp *http.Response) (ServiceEndpointPoliciesClientGetResponse, error) { + result := ServiceEndpointPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceEndpointPolicy); err != nil { + return ServiceEndpointPoliciesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the service endpoint policies in a subscription. +// +// Generated from API version 2023-05-01 +// - options - ServiceEndpointPoliciesClientListOptions contains the optional parameters for the ServiceEndpointPoliciesClient.NewListPager +// method. +func (client *ServiceEndpointPoliciesClient) NewListPager(options *ServiceEndpointPoliciesClientListOptions) *runtime.Pager[ServiceEndpointPoliciesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ServiceEndpointPoliciesClientListResponse]{ + More: func(page ServiceEndpointPoliciesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ServiceEndpointPoliciesClientListResponse) (ServiceEndpointPoliciesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ServiceEndpointPoliciesClient.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 ServiceEndpointPoliciesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ServiceEndpointPoliciesClient) listCreateRequest(ctx context.Context, options *ServiceEndpointPoliciesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/ServiceEndpointPolicies" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ServiceEndpointPoliciesClient) listHandleResponse(resp *http.Response) (ServiceEndpointPoliciesClientListResponse, error) { + result := ServiceEndpointPoliciesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceEndpointPolicyListResult); err != nil { + return ServiceEndpointPoliciesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all service endpoint Policies in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - ServiceEndpointPoliciesClientListByResourceGroupOptions contains the optional parameters for the ServiceEndpointPoliciesClient.NewListByResourceGroupPager +// method. +func (client *ServiceEndpointPoliciesClient) NewListByResourceGroupPager(resourceGroupName string, options *ServiceEndpointPoliciesClientListByResourceGroupOptions) *runtime.Pager[ServiceEndpointPoliciesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ServiceEndpointPoliciesClientListByResourceGroupResponse]{ + More: func(page ServiceEndpointPoliciesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ServiceEndpointPoliciesClientListByResourceGroupResponse) (ServiceEndpointPoliciesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ServiceEndpointPoliciesClient.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 ServiceEndpointPoliciesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ServiceEndpointPoliciesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ServiceEndpointPoliciesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ServiceEndpointPoliciesClient) listByResourceGroupHandleResponse(resp *http.Response) (ServiceEndpointPoliciesClientListByResourceGroupResponse, error) { + result := ServiceEndpointPoliciesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceEndpointPolicyListResult); err != nil { + return ServiceEndpointPoliciesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates tags of a service endpoint policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the service endpoint policy. +// - parameters - Parameters supplied to update service endpoint policy tags. +// - options - ServiceEndpointPoliciesClientUpdateTagsOptions contains the optional parameters for the ServiceEndpointPoliciesClient.UpdateTags +// method. +func (client *ServiceEndpointPoliciesClient) UpdateTags(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters TagsObject, options *ServiceEndpointPoliciesClientUpdateTagsOptions) (ServiceEndpointPoliciesClientUpdateTagsResponse, error) { + var err error + const operationName = "ServiceEndpointPoliciesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, serviceEndpointPolicyName, parameters, options) + if err != nil { + return ServiceEndpointPoliciesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceEndpointPoliciesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceEndpointPoliciesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *ServiceEndpointPoliciesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters TagsObject, options *ServiceEndpointPoliciesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *ServiceEndpointPoliciesClient) updateTagsHandleResponse(resp *http.Response) (ServiceEndpointPoliciesClientUpdateTagsResponse, error) { + result := ServiceEndpointPoliciesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceEndpointPolicy); err != nil { + return ServiceEndpointPoliciesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceendpointpolicydefinitions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceendpointpolicydefinitions_client.go new file mode 100644 index 000000000..ac6597319 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/serviceendpointpolicydefinitions_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// ServiceEndpointPolicyDefinitionsClient contains the methods for the ServiceEndpointPolicyDefinitions group. +// Don't use this type directly, use NewServiceEndpointPolicyDefinitionsClient() instead. +type ServiceEndpointPolicyDefinitionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewServiceEndpointPolicyDefinitionsClient creates a new instance of ServiceEndpointPolicyDefinitionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewServiceEndpointPolicyDefinitionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServiceEndpointPolicyDefinitionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ServiceEndpointPolicyDefinitionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a service endpoint policy definition in the specified service endpoint policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the service endpoint policy. +// - serviceEndpointPolicyDefinitionName - The name of the service endpoint policy definition name. +// - serviceEndpointPolicyDefinitions - Parameters supplied to the create or update service endpoint policy operation. +// - options - ServiceEndpointPolicyDefinitionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.BeginCreateOrUpdate +// method. +func (client *ServiceEndpointPolicyDefinitionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, serviceEndpointPolicyDefinitions ServiceEndpointPolicyDefinition, options *ServiceEndpointPolicyDefinitionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ServiceEndpointPolicyDefinitionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ServiceEndpointPolicyDefinitionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ServiceEndpointPolicyDefinitionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a service endpoint policy definition in the specified service endpoint policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ServiceEndpointPolicyDefinitionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, serviceEndpointPolicyDefinitions ServiceEndpointPolicyDefinition, options *ServiceEndpointPolicyDefinitionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ServiceEndpointPolicyDefinitionsClient.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, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions, 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 *ServiceEndpointPolicyDefinitionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, serviceEndpointPolicyDefinitions ServiceEndpointPolicyDefinition, options *ServiceEndpointPolicyDefinitionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + if serviceEndpointPolicyDefinitionName == "" { + return nil, errors.New("parameter serviceEndpointPolicyDefinitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyDefinitionName}", url.PathEscape(serviceEndpointPolicyDefinitionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, serviceEndpointPolicyDefinitions); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified ServiceEndpoint policy definitions. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the Service Endpoint Policy. +// - serviceEndpointPolicyDefinitionName - The name of the service endpoint policy definition. +// - options - ServiceEndpointPolicyDefinitionsClientBeginDeleteOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.BeginDelete +// method. +func (client *ServiceEndpointPolicyDefinitionsClient) BeginDelete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, options *ServiceEndpointPolicyDefinitionsClientBeginDeleteOptions) (*runtime.Poller[ServiceEndpointPolicyDefinitionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ServiceEndpointPolicyDefinitionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ServiceEndpointPolicyDefinitionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified ServiceEndpoint policy definitions. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *ServiceEndpointPolicyDefinitionsClient) deleteOperation(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, options *ServiceEndpointPolicyDefinitionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ServiceEndpointPolicyDefinitionsClient.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, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, 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 *ServiceEndpointPolicyDefinitionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, options *ServiceEndpointPolicyDefinitionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + if serviceEndpointPolicyDefinitionName == "" { + return nil, errors.New("parameter serviceEndpointPolicyDefinitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyDefinitionName}", url.PathEscape(serviceEndpointPolicyDefinitionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get the specified service endpoint policy definitions from service endpoint policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the service endpoint policy name. +// - serviceEndpointPolicyDefinitionName - The name of the service endpoint policy definition name. +// - options - ServiceEndpointPolicyDefinitionsClientGetOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.Get +// method. +func (client *ServiceEndpointPolicyDefinitionsClient) Get(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, options *ServiceEndpointPolicyDefinitionsClientGetOptions) (ServiceEndpointPolicyDefinitionsClientGetResponse, error) { + var err error + const operationName = "ServiceEndpointPolicyDefinitionsClient.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, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, options) + if err != nil { + return ServiceEndpointPolicyDefinitionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceEndpointPolicyDefinitionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceEndpointPolicyDefinitionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ServiceEndpointPolicyDefinitionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, options *ServiceEndpointPolicyDefinitionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + if serviceEndpointPolicyDefinitionName == "" { + return nil, errors.New("parameter serviceEndpointPolicyDefinitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyDefinitionName}", url.PathEscape(serviceEndpointPolicyDefinitionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ServiceEndpointPolicyDefinitionsClient) getHandleResponse(resp *http.Response) (ServiceEndpointPolicyDefinitionsClientGetResponse, error) { + result := ServiceEndpointPolicyDefinitionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceEndpointPolicyDefinition); err != nil { + return ServiceEndpointPolicyDefinitionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all service endpoint policy definitions in a service end point policy. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - serviceEndpointPolicyName - The name of the service endpoint policy name. +// - options - ServiceEndpointPolicyDefinitionsClientListByResourceGroupOptions contains the optional parameters for the ServiceEndpointPolicyDefinitionsClient.NewListByResourceGroupPager +// method. +func (client *ServiceEndpointPolicyDefinitionsClient) NewListByResourceGroupPager(resourceGroupName string, serviceEndpointPolicyName string, options *ServiceEndpointPolicyDefinitionsClientListByResourceGroupOptions) *runtime.Pager[ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse]{ + More: func(page ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse) (ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ServiceEndpointPolicyDefinitionsClient.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, serviceEndpointPolicyName, options) + }, nil) + if err != nil { + return ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ServiceEndpointPolicyDefinitionsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, options *ServiceEndpointPolicyDefinitionsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceEndpointPolicyName == "" { + return nil, errors.New("parameter serviceEndpointPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceEndpointPolicyName}", url.PathEscape(serviceEndpointPolicyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ServiceEndpointPolicyDefinitionsClient) listByResourceGroupHandleResponse(resp *http.Response) (ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse, error) { + result := ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceEndpointPolicyDefinitionListResult); err != nil { + return ServiceEndpointPolicyDefinitionsClientListByResourceGroupResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/servicetaginformation_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/servicetaginformation_client.go new file mode 100644 index 000000000..49d03beab --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/servicetaginformation_client.go @@ -0,0 +1,114 @@ +//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 armnetwork + +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" +) + +// ServiceTagInformationClient contains the methods for the ServiceTagInformation group. +// Don't use this type directly, use NewServiceTagInformationClient() instead. +type ServiceTagInformationClient struct { + internal *arm.Client + subscriptionID string +} + +// NewServiceTagInformationClient creates a new instance of ServiceTagInformationClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewServiceTagInformationClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServiceTagInformationClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ServiceTagInformationClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets a list of service tag information resources with pagination. +// +// Generated from API version 2023-05-01 +// - location - The location that will be used as a reference for cloud (not as a filter based on location, you will get the +// list of service tags with prefix details across all regions but limited to the cloud that +// your subscription belongs to). +// - options - ServiceTagInformationClientListOptions contains the optional parameters for the ServiceTagInformationClient.NewListPager +// method. +func (client *ServiceTagInformationClient) NewListPager(location string, options *ServiceTagInformationClientListOptions) *runtime.Pager[ServiceTagInformationClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ServiceTagInformationClientListResponse]{ + More: func(page ServiceTagInformationClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ServiceTagInformationClientListResponse) (ServiceTagInformationClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ServiceTagInformationClient.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, location, options) + }, nil) + if err != nil { + return ServiceTagInformationClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ServiceTagInformationClient) listCreateRequest(ctx context.Context, location string, options *ServiceTagInformationClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/serviceTagDetails" + 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-05-01") + if options != nil && options.NoAddressPrefixes != nil { + reqQP.Set("noAddressPrefixes", strconv.FormatBool(*options.NoAddressPrefixes)) + } + if options != nil && options.TagName != nil { + reqQP.Set("tagName", *options.TagName) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ServiceTagInformationClient) listHandleResponse(resp *http.Response) (ServiceTagInformationClientListResponse, error) { + result := ServiceTagInformationClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceTagInformationListResult); err != nil { + return ServiceTagInformationClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/servicetags_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/servicetags_client.go new file mode 100644 index 000000000..f0ecb696d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/servicetags_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 armnetwork + +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" +) + +// ServiceTagsClient contains the methods for the ServiceTags group. +// Don't use this type directly, use NewServiceTagsClient() instead. +type ServiceTagsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewServiceTagsClient creates a new instance of ServiceTagsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewServiceTagsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServiceTagsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ServiceTagsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Gets a list of service tag information resources. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - location - The location that will be used as a reference for version (not as a filter based on location, you will get the +// list of service tags with prefix details across all regions but limited to the cloud that +// your subscription belongs to). +// - options - ServiceTagsClientListOptions contains the optional parameters for the ServiceTagsClient.List method. +func (client *ServiceTagsClient) List(ctx context.Context, location string, options *ServiceTagsClientListOptions) (ServiceTagsClientListResponse, error) { + var err error + const operationName = "ServiceTagsClient.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, location, options) + if err != nil { + return ServiceTagsClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceTagsClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceTagsClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *ServiceTagsClient) listCreateRequest(ctx context.Context, location string, options *ServiceTagsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/serviceTags" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ServiceTagsClient) listHandleResponse(resp *http.Response) (ServiceTagsClientListResponse, error) { + result := ServiceTagsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceTagsListResult); err != nil { + return ServiceTagsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/staticmembers_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/staticmembers_client.go new file mode 100644 index 000000000..6e5e7ed02 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/staticmembers_client.go @@ -0,0 +1,338 @@ +//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 armnetwork + +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" +) + +// StaticMembersClient contains the methods for the StaticMembers group. +// Don't use this type directly, use NewStaticMembersClient() instead. +type StaticMembersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewStaticMembersClient creates a new instance of StaticMembersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewStaticMembersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*StaticMembersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &StaticMembersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or updates a static member. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - networkGroupName - The name of the network group. +// - staticMemberName - The name of the static member. +// - parameters - Parameters supplied to the specify the static member to create +// - options - StaticMembersClientCreateOrUpdateOptions contains the optional parameters for the StaticMembersClient.CreateOrUpdate +// method. +func (client *StaticMembersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string, parameters StaticMember, options *StaticMembersClientCreateOrUpdateOptions) (StaticMembersClientCreateOrUpdateResponse, error) { + var err error + const operationName = "StaticMembersClient.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, networkManagerName, networkGroupName, staticMemberName, parameters, options) + if err != nil { + return StaticMembersClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return StaticMembersClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return StaticMembersClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *StaticMembersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string, parameters StaticMember, options *StaticMembersClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers/{staticMemberName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if networkGroupName == "" { + return nil, errors.New("parameter networkGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkGroupName}", url.PathEscape(networkGroupName)) + if staticMemberName == "" { + return nil, errors.New("parameter staticMemberName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{staticMemberName}", url.PathEscape(staticMemberName)) + 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-05-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 *StaticMembersClient) createOrUpdateHandleResponse(resp *http.Response) (StaticMembersClientCreateOrUpdateResponse, error) { + result := StaticMembersClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StaticMember); err != nil { + return StaticMembersClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes a static member. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - networkGroupName - The name of the network group. +// - staticMemberName - The name of the static member. +// - options - StaticMembersClientDeleteOptions contains the optional parameters for the StaticMembersClient.Delete method. +func (client *StaticMembersClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string, options *StaticMembersClientDeleteOptions) (StaticMembersClientDeleteResponse, error) { + var err error + const operationName = "StaticMembersClient.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, networkManagerName, networkGroupName, staticMemberName, options) + if err != nil { + return StaticMembersClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return StaticMembersClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return StaticMembersClientDeleteResponse{}, err + } + return StaticMembersClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StaticMembersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string, options *StaticMembersClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers/{staticMemberName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if networkGroupName == "" { + return nil, errors.New("parameter networkGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkGroupName}", url.PathEscape(networkGroupName)) + if staticMemberName == "" { + return nil, errors.New("parameter staticMemberName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{staticMemberName}", url.PathEscape(staticMemberName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified static member. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - networkGroupName - The name of the network group. +// - staticMemberName - The name of the static member. +// - options - StaticMembersClientGetOptions contains the optional parameters for the StaticMembersClient.Get method. +func (client *StaticMembersClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string, options *StaticMembersClientGetOptions) (StaticMembersClientGetResponse, error) { + var err error + const operationName = "StaticMembersClient.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, networkManagerName, networkGroupName, staticMemberName, options) + if err != nil { + return StaticMembersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return StaticMembersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return StaticMembersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *StaticMembersClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string, options *StaticMembersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers/{staticMemberName}" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if networkGroupName == "" { + return nil, errors.New("parameter networkGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkGroupName}", url.PathEscape(networkGroupName)) + if staticMemberName == "" { + return nil, errors.New("parameter staticMemberName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{staticMemberName}", url.PathEscape(staticMemberName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StaticMembersClient) getHandleResponse(resp *http.Response) (StaticMembersClientGetResponse, error) { + result := StaticMembersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StaticMember); err != nil { + return StaticMembersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists the specified static member. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkManagerName - The name of the network manager. +// - networkGroupName - The name of the network group. +// - options - StaticMembersClientListOptions contains the optional parameters for the StaticMembersClient.NewListPager method. +func (client *StaticMembersClient) NewListPager(resourceGroupName string, networkManagerName string, networkGroupName string, options *StaticMembersClientListOptions) *runtime.Pager[StaticMembersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[StaticMembersClientListResponse]{ + More: func(page StaticMembersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *StaticMembersClientListResponse) (StaticMembersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "StaticMembersClient.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, networkManagerName, networkGroupName, options) + }, nil) + if err != nil { + return StaticMembersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *StaticMembersClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, options *StaticMembersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers" + 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 networkManagerName == "" { + return nil, errors.New("parameter networkManagerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerName}", url.PathEscape(networkManagerName)) + if networkGroupName == "" { + return nil, errors.New("parameter networkGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkGroupName}", url.PathEscape(networkGroupName)) + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *StaticMembersClient) listHandleResponse(resp *http.Response) (StaticMembersClientListResponse, error) { + result := StaticMembersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StaticMemberListResult); err != nil { + return StaticMembersClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/subnets_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/subnets_client.go new file mode 100644 index 000000000..6a73e8b6f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/subnets_client.go @@ -0,0 +1,520 @@ +//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 armnetwork + +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" +) + +// SubnetsClient contains the methods for the Subnets group. +// Don't use this type directly, use NewSubnetsClient() instead. +type SubnetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSubnetsClient creates a new instance of SubnetsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewSubnetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SubnetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SubnetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a subnet in the specified virtual network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - subnetName - The name of the subnet. +// - subnetParameters - Parameters supplied to the create or update subnet operation. +// - options - SubnetsClientBeginCreateOrUpdateOptions contains the optional parameters for the SubnetsClient.BeginCreateOrUpdate +// method. +func (client *SubnetsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, options *SubnetsClientBeginCreateOrUpdateOptions) (*runtime.Poller[SubnetsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SubnetsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SubnetsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a subnet in the specified virtual network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SubnetsClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, options *SubnetsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SubnetsClient.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, virtualNetworkName, subnetName, subnetParameters, 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 *SubnetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, options *SubnetsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if subnetName == "" { + return nil, errors.New("parameter subnetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subnetName}", url.PathEscape(subnetName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, subnetParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified subnet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - subnetName - The name of the subnet. +// - options - SubnetsClientBeginDeleteOptions contains the optional parameters for the SubnetsClient.BeginDelete method. +func (client *SubnetsClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *SubnetsClientBeginDeleteOptions) (*runtime.Poller[SubnetsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualNetworkName, subnetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SubnetsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SubnetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified subnet. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SubnetsClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *SubnetsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SubnetsClient.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, virtualNetworkName, subnetName, 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 *SubnetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *SubnetsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if subnetName == "" { + return nil, errors.New("parameter subnetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subnetName}", url.PathEscape(subnetName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified subnet by virtual network and resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - subnetName - The name of the subnet. +// - options - SubnetsClientGetOptions contains the optional parameters for the SubnetsClient.Get method. +func (client *SubnetsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *SubnetsClientGetOptions) (SubnetsClientGetResponse, error) { + var err error + const operationName = "SubnetsClient.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, virtualNetworkName, subnetName, options) + if err != nil { + return SubnetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubnetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SubnetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SubnetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, options *SubnetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if subnetName == "" { + return nil, errors.New("parameter subnetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subnetName}", url.PathEscape(subnetName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *SubnetsClient) getHandleResponse(resp *http.Response) (SubnetsClientGetResponse, error) { + result := SubnetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Subnet); err != nil { + return SubnetsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all subnets in a virtual network. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - options - SubnetsClientListOptions contains the optional parameters for the SubnetsClient.NewListPager method. +func (client *SubnetsClient) NewListPager(resourceGroupName string, virtualNetworkName string, options *SubnetsClientListOptions) *runtime.Pager[SubnetsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SubnetsClientListResponse]{ + More: func(page SubnetsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SubnetsClientListResponse) (SubnetsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SubnetsClient.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, virtualNetworkName, options) + }, nil) + if err != nil { + return SubnetsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SubnetsClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *SubnetsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SubnetsClient) listHandleResponse(resp *http.Response) (SubnetsClientListResponse, error) { + result := SubnetsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SubnetListResult); err != nil { + return SubnetsClientListResponse{}, err + } + return result, nil +} + +// BeginPrepareNetworkPolicies - Prepares a subnet by applying network intent policies. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - subnetName - The name of the subnet. +// - prepareNetworkPoliciesRequestParameters - Parameters supplied to prepare subnet by applying network intent policies. +// - options - SubnetsClientBeginPrepareNetworkPoliciesOptions contains the optional parameters for the SubnetsClient.BeginPrepareNetworkPolicies +// method. +func (client *SubnetsClient) BeginPrepareNetworkPolicies(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, prepareNetworkPoliciesRequestParameters PrepareNetworkPoliciesRequest, options *SubnetsClientBeginPrepareNetworkPoliciesOptions) (*runtime.Poller[SubnetsClientPrepareNetworkPoliciesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.prepareNetworkPolicies(ctx, resourceGroupName, virtualNetworkName, subnetName, prepareNetworkPoliciesRequestParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SubnetsClientPrepareNetworkPoliciesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SubnetsClientPrepareNetworkPoliciesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// PrepareNetworkPolicies - Prepares a subnet by applying network intent policies. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SubnetsClient) prepareNetworkPolicies(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, prepareNetworkPoliciesRequestParameters PrepareNetworkPoliciesRequest, options *SubnetsClientBeginPrepareNetworkPoliciesOptions) (*http.Response, error) { + var err error + const operationName = "SubnetsClient.BeginPrepareNetworkPolicies" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.prepareNetworkPoliciesCreateRequest(ctx, resourceGroupName, virtualNetworkName, subnetName, prepareNetworkPoliciesRequestParameters, 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 +} + +// prepareNetworkPoliciesCreateRequest creates the PrepareNetworkPolicies request. +func (client *SubnetsClient) prepareNetworkPoliciesCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, prepareNetworkPoliciesRequestParameters PrepareNetworkPoliciesRequest, options *SubnetsClientBeginPrepareNetworkPoliciesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/PrepareNetworkPolicies" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if subnetName == "" { + return nil, errors.New("parameter subnetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subnetName}", url.PathEscape(subnetName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, prepareNetworkPoliciesRequestParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginUnprepareNetworkPolicies - Unprepares a subnet by removing network intent policies. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - subnetName - The name of the subnet. +// - unprepareNetworkPoliciesRequestParameters - Parameters supplied to unprepare subnet to remove network intent policies. +// - options - SubnetsClientBeginUnprepareNetworkPoliciesOptions contains the optional parameters for the SubnetsClient.BeginUnprepareNetworkPolicies +// method. +func (client *SubnetsClient) BeginUnprepareNetworkPolicies(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, unprepareNetworkPoliciesRequestParameters UnprepareNetworkPoliciesRequest, options *SubnetsClientBeginUnprepareNetworkPoliciesOptions) (*runtime.Poller[SubnetsClientUnprepareNetworkPoliciesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.unprepareNetworkPolicies(ctx, resourceGroupName, virtualNetworkName, subnetName, unprepareNetworkPoliciesRequestParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SubnetsClientUnprepareNetworkPoliciesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SubnetsClientUnprepareNetworkPoliciesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UnprepareNetworkPolicies - Unprepares a subnet by removing network intent policies. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *SubnetsClient) unprepareNetworkPolicies(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, unprepareNetworkPoliciesRequestParameters UnprepareNetworkPoliciesRequest, options *SubnetsClientBeginUnprepareNetworkPoliciesOptions) (*http.Response, error) { + var err error + const operationName = "SubnetsClient.BeginUnprepareNetworkPolicies" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unprepareNetworkPoliciesCreateRequest(ctx, resourceGroupName, virtualNetworkName, subnetName, unprepareNetworkPoliciesRequestParameters, 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 +} + +// unprepareNetworkPoliciesCreateRequest creates the UnprepareNetworkPolicies request. +func (client *SubnetsClient) unprepareNetworkPoliciesCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, unprepareNetworkPoliciesRequestParameters UnprepareNetworkPoliciesRequest, options *SubnetsClientBeginUnprepareNetworkPoliciesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/UnprepareNetworkPolicies" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if subnetName == "" { + return nil, errors.New("parameter subnetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subnetName}", url.PathEscape(subnetName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, unprepareNetworkPoliciesRequestParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/subscriptionnetworkmanagerconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/subscriptionnetworkmanagerconnections_client.go new file mode 100644 index 000000000..0c5b7d5a6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/subscriptionnetworkmanagerconnections_client.go @@ -0,0 +1,281 @@ +//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 armnetwork + +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" +) + +// SubscriptionNetworkManagerConnectionsClient contains the methods for the SubscriptionNetworkManagerConnections group. +// Don't use this type directly, use NewSubscriptionNetworkManagerConnectionsClient() instead. +type SubscriptionNetworkManagerConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSubscriptionNetworkManagerConnectionsClient creates a new instance of SubscriptionNetworkManagerConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewSubscriptionNetworkManagerConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SubscriptionNetworkManagerConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SubscriptionNetworkManagerConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a network manager connection on this subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - networkManagerConnectionName - Name for the network manager connection. +// - parameters - Network manager connection to be created/updated. +// - options - SubscriptionNetworkManagerConnectionsClientCreateOrUpdateOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.CreateOrUpdate +// method. +func (client *SubscriptionNetworkManagerConnectionsClient) CreateOrUpdate(ctx context.Context, networkManagerConnectionName string, parameters ManagerConnection, options *SubscriptionNetworkManagerConnectionsClientCreateOrUpdateOptions) (SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "SubscriptionNetworkManagerConnectionsClient.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, networkManagerConnectionName, parameters, options) + if err != nil { + return SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SubscriptionNetworkManagerConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, networkManagerConnectionName string, parameters ManagerConnection, options *SubscriptionNetworkManagerConnectionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if networkManagerConnectionName == "" { + return nil, errors.New("parameter networkManagerConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerConnectionName}", url.PathEscape(networkManagerConnectionName)) + 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-05-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 *SubscriptionNetworkManagerConnectionsClient) createOrUpdateHandleResponse(resp *http.Response) (SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse, error) { + result := SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerConnection); err != nil { + return SubscriptionNetworkManagerConnectionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete specified connection created by this subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - networkManagerConnectionName - Name for the network manager connection. +// - options - SubscriptionNetworkManagerConnectionsClientDeleteOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.Delete +// method. +func (client *SubscriptionNetworkManagerConnectionsClient) Delete(ctx context.Context, networkManagerConnectionName string, options *SubscriptionNetworkManagerConnectionsClientDeleteOptions) (SubscriptionNetworkManagerConnectionsClientDeleteResponse, error) { + var err error + const operationName = "SubscriptionNetworkManagerConnectionsClient.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, networkManagerConnectionName, options) + if err != nil { + return SubscriptionNetworkManagerConnectionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionNetworkManagerConnectionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SubscriptionNetworkManagerConnectionsClientDeleteResponse{}, err + } + return SubscriptionNetworkManagerConnectionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SubscriptionNetworkManagerConnectionsClient) deleteCreateRequest(ctx context.Context, networkManagerConnectionName string, options *SubscriptionNetworkManagerConnectionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if networkManagerConnectionName == "" { + return nil, errors.New("parameter networkManagerConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerConnectionName}", url.PathEscape(networkManagerConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a specified connection created by this subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - networkManagerConnectionName - Name for the network manager connection. +// - options - SubscriptionNetworkManagerConnectionsClientGetOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.Get +// method. +func (client *SubscriptionNetworkManagerConnectionsClient) Get(ctx context.Context, networkManagerConnectionName string, options *SubscriptionNetworkManagerConnectionsClientGetOptions) (SubscriptionNetworkManagerConnectionsClientGetResponse, error) { + var err error + const operationName = "SubscriptionNetworkManagerConnectionsClient.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, networkManagerConnectionName, options) + if err != nil { + return SubscriptionNetworkManagerConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionNetworkManagerConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SubscriptionNetworkManagerConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SubscriptionNetworkManagerConnectionsClient) getCreateRequest(ctx context.Context, networkManagerConnectionName string, options *SubscriptionNetworkManagerConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if networkManagerConnectionName == "" { + return nil, errors.New("parameter networkManagerConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkManagerConnectionName}", url.PathEscape(networkManagerConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SubscriptionNetworkManagerConnectionsClient) getHandleResponse(resp *http.Response) (SubscriptionNetworkManagerConnectionsClientGetResponse, error) { + result := SubscriptionNetworkManagerConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerConnection); err != nil { + return SubscriptionNetworkManagerConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all network manager connections created by this subscription. +// +// Generated from API version 2023-05-01 +// - options - SubscriptionNetworkManagerConnectionsClientListOptions contains the optional parameters for the SubscriptionNetworkManagerConnectionsClient.NewListPager +// method. +func (client *SubscriptionNetworkManagerConnectionsClient) NewListPager(options *SubscriptionNetworkManagerConnectionsClientListOptions) *runtime.Pager[SubscriptionNetworkManagerConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SubscriptionNetworkManagerConnectionsClientListResponse]{ + More: func(page SubscriptionNetworkManagerConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SubscriptionNetworkManagerConnectionsClientListResponse) (SubscriptionNetworkManagerConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SubscriptionNetworkManagerConnectionsClient.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 SubscriptionNetworkManagerConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SubscriptionNetworkManagerConnectionsClient) listCreateRequest(ctx context.Context, options *SubscriptionNetworkManagerConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections" + 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-05-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SubscriptionNetworkManagerConnectionsClient) listHandleResponse(resp *http.Response) (SubscriptionNetworkManagerConnectionsClientListResponse, error) { + result := SubscriptionNetworkManagerConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagerConnectionListResult); err != nil { + return SubscriptionNetworkManagerConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/time_rfc3339.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/time_rfc3339.go new file mode 100644 index 000000000..ffdedf87e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/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 armnetwork + +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/network/armnetwork/v4/usages_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/usages_client.go new file mode 100644 index 000000000..ebacd3e6a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/usages_client.go @@ -0,0 +1,104 @@ +//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 armnetwork + +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 subscription credentials which uniquely identify the 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 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 +} + +// NewListPager - List network usages for a subscription. +// +// Generated from API version 2023-05-01 +// - location - The location where resource usage is queried. +// - options - UsagesClientListOptions contains the optional parameters for the UsagesClient.NewListPager method. +func (client *UsagesClient) NewListPager(location string, options *UsagesClientListOptions) *runtime.Pager[UsagesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[UsagesClientListResponse]{ + More: func(page UsagesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *UsagesClientListResponse) (UsagesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "UsagesClient.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, location, options) + }, nil) + if err != nil { + return UsagesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *UsagesClient) listCreateRequest(ctx context.Context, location string, options *UsagesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *UsagesClient) listHandleResponse(resp *http.Response) (UsagesClientListResponse, error) { + result := UsagesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UsagesListResult); err != nil { + return UsagesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vipswap_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vipswap_client.go new file mode 100644 index 000000000..ac92776c0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vipswap_client.go @@ -0,0 +1,256 @@ +//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 armnetwork + +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" +) + +// VipSwapClient contains the methods for the VipSwap group. +// Don't use this type directly, use NewVipSwapClient() instead. +type VipSwapClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVipSwapClient creates a new instance of VipSwapClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVipSwapClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VipSwapClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VipSwapClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Performs vip swap operation on swappable cloud services. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - groupName - The name of the resource group. +// - resourceName - The name of the cloud service. +// - parameters - SwapResource object where slot type should be the target slot after vip swap for the specified cloud service. +// - options - VipSwapClientBeginCreateOptions contains the optional parameters for the VipSwapClient.BeginCreate method. +func (client *VipSwapClient) BeginCreate(ctx context.Context, groupName string, resourceName string, parameters SwapResource, options *VipSwapClientBeginCreateOptions) (*runtime.Poller[VipSwapClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, groupName, resourceName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VipSwapClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VipSwapClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Performs vip swap operation on swappable cloud services. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VipSwapClient) create(ctx context.Context, groupName string, resourceName string, parameters SwapResource, options *VipSwapClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "VipSwapClient.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, groupName, resourceName, 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 *VipSwapClient) createCreateRequest(ctx context.Context, groupName string, resourceName string, parameters SwapResource, options *VipSwapClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Compute/cloudServices/{resourceName}/providers/Microsoft.Network/cloudServiceSlots/{singletonResource}" + if groupName == "" { + return nil, errors.New("parameter groupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupName}", url.PathEscape(groupName)) + if resourceName == "" { + return nil, errors.New("parameter resourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName)) + urlPath = strings.ReplaceAll(urlPath, "{singletonResource}", url.PathEscape("swap")) + 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-05-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 +} + +// Get - Gets the SwapResource which identifies the slot type for the specified cloud service. The slot type on a cloud service +// can either be Staging or Production +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - groupName - The name of the resource group. +// - resourceName - The name of the cloud service. +// - options - VipSwapClientGetOptions contains the optional parameters for the VipSwapClient.Get method. +func (client *VipSwapClient) Get(ctx context.Context, groupName string, resourceName string, options *VipSwapClientGetOptions) (VipSwapClientGetResponse, error) { + var err error + const operationName = "VipSwapClient.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, groupName, resourceName, options) + if err != nil { + return VipSwapClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VipSwapClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VipSwapClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VipSwapClient) getCreateRequest(ctx context.Context, groupName string, resourceName string, options *VipSwapClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Compute/cloudServices/{resourceName}/providers/Microsoft.Network/cloudServiceSlots/{singletonResource}" + if groupName == "" { + return nil, errors.New("parameter groupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupName}", url.PathEscape(groupName)) + if resourceName == "" { + return nil, errors.New("parameter resourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName)) + urlPath = strings.ReplaceAll(urlPath, "{singletonResource}", url.PathEscape("swap")) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VipSwapClient) getHandleResponse(resp *http.Response) (VipSwapClientGetResponse, error) { + result := VipSwapClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SwapResource); err != nil { + return VipSwapClientGetResponse{}, err + } + return result, nil +} + +// List - Gets the list of SwapResource which identifies the slot type for the specified cloud service. The slot type on a +// cloud service can either be Staging or Production +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - groupName - The name of the resource group. +// - resourceName - The name of the cloud service. +// - options - VipSwapClientListOptions contains the optional parameters for the VipSwapClient.List method. +func (client *VipSwapClient) List(ctx context.Context, groupName string, resourceName string, options *VipSwapClientListOptions) (VipSwapClientListResponse, error) { + var err error + const operationName = "VipSwapClient.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, groupName, resourceName, options) + if err != nil { + return VipSwapClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VipSwapClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VipSwapClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *VipSwapClient) listCreateRequest(ctx context.Context, groupName string, resourceName string, options *VipSwapClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Compute/cloudServices/{resourceName}/providers/Microsoft.Network/cloudServiceSlots" + if groupName == "" { + return nil, errors.New("parameter groupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupName}", url.PathEscape(groupName)) + if resourceName == "" { + return nil, errors.New("parameter resourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VipSwapClient) listHandleResponse(resp *http.Response) (VipSwapClientListResponse, error) { + result := VipSwapClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SwapResourceListResult); err != nil { + return VipSwapClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualapplianceconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualapplianceconnections_client.go new file mode 100644 index 000000000..9ecd1b48c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualapplianceconnections_client.go @@ -0,0 +1,349 @@ +//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 armnetwork + +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" +) + +// VirtualApplianceConnectionsClient contains the methods for the NetworkVirtualApplianceConnections group. +// Don't use this type directly, use NewVirtualApplianceConnectionsClient() instead. +type VirtualApplianceConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualApplianceConnectionsClient creates a new instance of VirtualApplianceConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualApplianceConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualApplianceConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualApplianceConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a connection to Network Virtual Appliance, if it doesn't exist else updates the existing +// NVA connection' +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - connectionName - The name of the NVA connection. +// - networkVirtualApplianceConnectionParameters - Parameters supplied in an NetworkVirtualApplianceConnection PUT operation. +// - options - VirtualApplianceConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualApplianceConnectionsClient.BeginCreateOrUpdate +// method. +func (client *VirtualApplianceConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, networkVirtualApplianceConnectionParameters VirtualApplianceConnection, options *VirtualApplianceConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualApplianceConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkVirtualApplianceName, connectionName, networkVirtualApplianceConnectionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualApplianceConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualApplianceConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a connection to Network Virtual Appliance, if it doesn't exist else updates the existing NVA connection' +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualApplianceConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, networkVirtualApplianceConnectionParameters VirtualApplianceConnection, options *VirtualApplianceConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualApplianceConnectionsClient.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, networkVirtualApplianceName, connectionName, networkVirtualApplianceConnectionParameters, 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 *VirtualApplianceConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, networkVirtualApplianceConnectionParameters VirtualApplianceConnection, options *VirtualApplianceConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/networkVirtualApplianceConnections/{connectionName}" + 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 networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, networkVirtualApplianceConnectionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a NVA connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - connectionName - The name of the NVA connection. +// - options - VirtualApplianceConnectionsClientBeginDeleteOptions contains the optional parameters for the VirtualApplianceConnectionsClient.BeginDelete +// method. +func (client *VirtualApplianceConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, options *VirtualApplianceConnectionsClientBeginDeleteOptions) (*runtime.Poller[VirtualApplianceConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkVirtualApplianceName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualApplianceConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualApplianceConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a NVA connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualApplianceConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, options *VirtualApplianceConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualApplianceConnectionsClient.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, networkVirtualApplianceName, connectionName, 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 *VirtualApplianceConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, options *VirtualApplianceConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/networkVirtualApplianceConnections/{connectionName}" + 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 networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of specified NVA connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - connectionName - The name of the NVA connection. +// - options - VirtualApplianceConnectionsClientGetOptions contains the optional parameters for the VirtualApplianceConnectionsClient.Get +// method. +func (client *VirtualApplianceConnectionsClient) Get(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, options *VirtualApplianceConnectionsClientGetOptions) (VirtualApplianceConnectionsClientGetResponse, error) { + var err error + const operationName = "VirtualApplianceConnectionsClient.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, networkVirtualApplianceName, connectionName, options) + if err != nil { + return VirtualApplianceConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualApplianceConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualApplianceConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualApplianceConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, connectionName string, options *VirtualApplianceConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/networkVirtualApplianceConnections/{connectionName}" + 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 networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualApplianceConnectionsClient) getHandleResponse(resp *http.Response) (VirtualApplianceConnectionsClientGetResponse, error) { + result := VirtualApplianceConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceConnection); err != nil { + return VirtualApplianceConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists NetworkVirtualApplianceConnections under the NVA. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - options - VirtualApplianceConnectionsClientListOptions contains the optional parameters for the VirtualApplianceConnectionsClient.NewListPager +// method. +func (client *VirtualApplianceConnectionsClient) NewListPager(resourceGroupName string, networkVirtualApplianceName string, options *VirtualApplianceConnectionsClientListOptions) *runtime.Pager[VirtualApplianceConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualApplianceConnectionsClientListResponse]{ + More: func(page VirtualApplianceConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualApplianceConnectionsClientListResponse) (VirtualApplianceConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualApplianceConnectionsClient.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, networkVirtualApplianceName, options) + }, nil) + if err != nil { + return VirtualApplianceConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualApplianceConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, options *VirtualApplianceConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/networkVirtualApplianceConnections" + 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 networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualApplianceConnectionsClient) listHandleResponse(resp *http.Response) (VirtualApplianceConnectionsClientListResponse, error) { + result := VirtualApplianceConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceConnectionList); err != nil { + return VirtualApplianceConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualappliances_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualappliances_client.go new file mode 100644 index 000000000..01fa3cfef --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualappliances_client.go @@ -0,0 +1,454 @@ +//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 armnetwork + +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" +) + +// VirtualAppliancesClient contains the methods for the NetworkVirtualAppliances group. +// Don't use this type directly, use NewVirtualAppliancesClient() instead. +type VirtualAppliancesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualAppliancesClient creates a new instance of VirtualAppliancesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualAppliancesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualAppliancesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualAppliancesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Network Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of Network Virtual Appliance. +// - parameters - Parameters supplied to the create or update Network Virtual Appliance. +// - options - VirtualAppliancesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualAppliancesClient.BeginCreateOrUpdate +// method. +func (client *VirtualAppliancesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters VirtualAppliance, options *VirtualAppliancesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualAppliancesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkVirtualApplianceName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualAppliancesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualAppliancesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Network Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualAppliancesClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters VirtualAppliance, options *VirtualAppliancesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualAppliancesClient.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, networkVirtualApplianceName, 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 *VirtualAppliancesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters VirtualAppliance, options *VirtualAppliancesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + 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-05-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 Network Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of Network Virtual Appliance. +// - options - VirtualAppliancesClientBeginDeleteOptions contains the optional parameters for the VirtualAppliancesClient.BeginDelete +// method. +func (client *VirtualAppliancesClient) BeginDelete(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, options *VirtualAppliancesClientBeginDeleteOptions) (*runtime.Poller[VirtualAppliancesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkVirtualApplianceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualAppliancesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualAppliancesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Network Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualAppliancesClient) deleteOperation(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, options *VirtualAppliancesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualAppliancesClient.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, networkVirtualApplianceName, 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 *VirtualAppliancesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, options *VirtualAppliancesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Network Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of Network Virtual Appliance. +// - options - VirtualAppliancesClientGetOptions contains the optional parameters for the VirtualAppliancesClient.Get method. +func (client *VirtualAppliancesClient) Get(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, options *VirtualAppliancesClientGetOptions) (VirtualAppliancesClientGetResponse, error) { + var err error + const operationName = "VirtualAppliancesClient.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, networkVirtualApplianceName, options) + if err != nil { + return VirtualAppliancesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualAppliancesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualAppliancesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualAppliancesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, options *VirtualAppliancesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *VirtualAppliancesClient) getHandleResponse(resp *http.Response) (VirtualAppliancesClientGetResponse, error) { + result := VirtualAppliancesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualAppliance); err != nil { + return VirtualAppliancesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all Network Virtual Appliances in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VirtualAppliancesClientListOptions contains the optional parameters for the VirtualAppliancesClient.NewListPager +// method. +func (client *VirtualAppliancesClient) NewListPager(options *VirtualAppliancesClientListOptions) *runtime.Pager[VirtualAppliancesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualAppliancesClientListResponse]{ + More: func(page VirtualAppliancesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualAppliancesClientListResponse) (VirtualAppliancesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualAppliancesClient.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 VirtualAppliancesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualAppliancesClient) listCreateRequest(ctx context.Context, options *VirtualAppliancesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkVirtualAppliances" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualAppliancesClient) listHandleResponse(resp *http.Response) (VirtualAppliancesClientListResponse, error) { + result := VirtualAppliancesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceListResult); err != nil { + return VirtualAppliancesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all Network Virtual Appliances in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualAppliancesClientListByResourceGroupOptions contains the optional parameters for the VirtualAppliancesClient.NewListByResourceGroupPager +// method. +func (client *VirtualAppliancesClient) NewListByResourceGroupPager(resourceGroupName string, options *VirtualAppliancesClientListByResourceGroupOptions) *runtime.Pager[VirtualAppliancesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualAppliancesClientListByResourceGroupResponse]{ + More: func(page VirtualAppliancesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualAppliancesClientListByResourceGroupResponse) (VirtualAppliancesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualAppliancesClient.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 VirtualAppliancesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VirtualAppliancesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualAppliancesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VirtualAppliancesClient) listByResourceGroupHandleResponse(resp *http.Response) (VirtualAppliancesClientListByResourceGroupResponse, error) { + result := VirtualAppliancesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceListResult); err != nil { + return VirtualAppliancesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a Network Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of Network Virtual Appliance. +// - networkVirtualApplianceName - The name of Network Virtual Appliance being updated. +// - parameters - Parameters supplied to Update Network Virtual Appliance Tags. +// - options - VirtualAppliancesClientUpdateTagsOptions contains the optional parameters for the VirtualAppliancesClient.UpdateTags +// method. +func (client *VirtualAppliancesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters TagsObject, options *VirtualAppliancesClientUpdateTagsOptions) (VirtualAppliancesClientUpdateTagsResponse, error) { + var err error + const operationName = "VirtualAppliancesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, networkVirtualApplianceName, parameters, options) + if err != nil { + return VirtualAppliancesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualAppliancesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualAppliancesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VirtualAppliancesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters TagsObject, options *VirtualAppliancesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}" + 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 networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *VirtualAppliancesClient) updateTagsHandleResponse(resp *http.Response) (VirtualAppliancesClientUpdateTagsResponse, error) { + result := VirtualAppliancesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualAppliance); err != nil { + return VirtualAppliancesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualappliancesites_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualappliancesites_client.go new file mode 100644 index 000000000..af8f589f8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualappliancesites_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// VirtualApplianceSitesClient contains the methods for the VirtualApplianceSites group. +// Don't use this type directly, use NewVirtualApplianceSitesClient() instead. +type VirtualApplianceSitesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualApplianceSitesClient creates a new instance of VirtualApplianceSitesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualApplianceSitesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualApplianceSitesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualApplianceSitesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Network Virtual Appliance Site. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - siteName - The name of the site. +// - parameters - Parameters supplied to the create or update Network Virtual Appliance Site operation. +// - options - VirtualApplianceSitesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualApplianceSitesClient.BeginCreateOrUpdate +// method. +func (client *VirtualApplianceSitesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, parameters VirtualApplianceSite, options *VirtualApplianceSitesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualApplianceSitesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkVirtualApplianceName, siteName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualApplianceSitesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualApplianceSitesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Network Virtual Appliance Site. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualApplianceSitesClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, parameters VirtualApplianceSite, options *VirtualApplianceSitesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualApplianceSitesClient.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, networkVirtualApplianceName, siteName, 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 *VirtualApplianceSitesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, parameters VirtualApplianceSite, options *VirtualApplianceSitesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + if siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + 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-05-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 site from a Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - siteName - The name of the site. +// - options - VirtualApplianceSitesClientBeginDeleteOptions contains the optional parameters for the VirtualApplianceSitesClient.BeginDelete +// method. +func (client *VirtualApplianceSitesClient) BeginDelete(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, options *VirtualApplianceSitesClientBeginDeleteOptions) (*runtime.Poller[VirtualApplianceSitesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkVirtualApplianceName, siteName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualApplianceSitesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualApplianceSitesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified site from a Virtual Appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualApplianceSitesClient) deleteOperation(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, options *VirtualApplianceSitesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualApplianceSitesClient.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, networkVirtualApplianceName, siteName, 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 *VirtualApplianceSitesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, options *VirtualApplianceSitesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + if siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Virtual Appliance Site. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - siteName - The name of the site. +// - options - VirtualApplianceSitesClientGetOptions contains the optional parameters for the VirtualApplianceSitesClient.Get +// method. +func (client *VirtualApplianceSitesClient) Get(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, options *VirtualApplianceSitesClientGetOptions) (VirtualApplianceSitesClientGetResponse, error) { + var err error + const operationName = "VirtualApplianceSitesClient.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, networkVirtualApplianceName, siteName, options) + if err != nil { + return VirtualApplianceSitesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualApplianceSitesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualApplianceSitesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualApplianceSitesClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, options *VirtualApplianceSitesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + if siteName == "" { + return nil, errors.New("parameter siteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{siteName}", url.PathEscape(siteName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualApplianceSitesClient) getHandleResponse(resp *http.Response) (VirtualApplianceSitesClientGetResponse, error) { + result := VirtualApplianceSitesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceSite); err != nil { + return VirtualApplianceSitesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all Network Virtual Appliance Sites in a Network Virtual Appliance resource. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkVirtualApplianceName - The name of the Network Virtual Appliance. +// - options - VirtualApplianceSitesClientListOptions contains the optional parameters for the VirtualApplianceSitesClient.NewListPager +// method. +func (client *VirtualApplianceSitesClient) NewListPager(resourceGroupName string, networkVirtualApplianceName string, options *VirtualApplianceSitesClientListOptions) *runtime.Pager[VirtualApplianceSitesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualApplianceSitesClientListResponse]{ + More: func(page VirtualApplianceSitesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualApplianceSitesClientListResponse) (VirtualApplianceSitesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualApplianceSitesClient.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, networkVirtualApplianceName, options) + }, nil) + if err != nil { + return VirtualApplianceSitesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualApplianceSitesClient) listCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, options *VirtualApplianceSitesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkVirtualApplianceName == "" { + return nil, errors.New("parameter networkVirtualApplianceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkVirtualApplianceName}", url.PathEscape(networkVirtualApplianceName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualApplianceSitesClient) listHandleResponse(resp *http.Response) (VirtualApplianceSitesClientListResponse, error) { + result := VirtualApplianceSitesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceSiteListResult); err != nil { + return VirtualApplianceSitesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualapplianceskus_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualapplianceskus_client.go new file mode 100644 index 000000000..2247d3c9c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualapplianceskus_client.go @@ -0,0 +1,160 @@ +//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 armnetwork + +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" +) + +// VirtualApplianceSKUsClient contains the methods for the VirtualApplianceSKUs group. +// Don't use this type directly, use NewVirtualApplianceSKUsClient() instead. +type VirtualApplianceSKUsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualApplianceSKUsClient creates a new instance of VirtualApplianceSKUsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualApplianceSKUsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualApplianceSKUsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualApplianceSKUsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Retrieves a single available sku for network virtual appliance. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - skuName - Name of the Sku. +// - options - VirtualApplianceSKUsClientGetOptions contains the optional parameters for the VirtualApplianceSKUsClient.Get +// method. +func (client *VirtualApplianceSKUsClient) Get(ctx context.Context, skuName string, options *VirtualApplianceSKUsClientGetOptions) (VirtualApplianceSKUsClientGetResponse, error) { + var err error + const operationName = "VirtualApplianceSKUsClient.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, skuName, options) + if err != nil { + return VirtualApplianceSKUsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualApplianceSKUsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualApplianceSKUsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualApplianceSKUsClient) getCreateRequest(ctx context.Context, skuName string, options *VirtualApplianceSKUsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkVirtualApplianceSkus/{skuName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if skuName == "" { + return nil, errors.New("parameter skuName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{skuName}", url.PathEscape(skuName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualApplianceSKUsClient) getHandleResponse(resp *http.Response) (VirtualApplianceSKUsClientGetResponse, error) { + result := VirtualApplianceSKUsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceSKU); err != nil { + return VirtualApplianceSKUsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all SKUs available for a virtual appliance. +// +// Generated from API version 2023-05-01 +// - options - VirtualApplianceSKUsClientListOptions contains the optional parameters for the VirtualApplianceSKUsClient.NewListPager +// method. +func (client *VirtualApplianceSKUsClient) NewListPager(options *VirtualApplianceSKUsClientListOptions) *runtime.Pager[VirtualApplianceSKUsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualApplianceSKUsClientListResponse]{ + More: func(page VirtualApplianceSKUsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualApplianceSKUsClientListResponse) (VirtualApplianceSKUsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualApplianceSKUsClient.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 VirtualApplianceSKUsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualApplianceSKUsClient) listCreateRequest(ctx context.Context, options *VirtualApplianceSKUsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkVirtualApplianceSkus" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualApplianceSKUsClient) listHandleResponse(resp *http.Response) (VirtualApplianceSKUsClientListResponse, error) { + result := VirtualApplianceSKUsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualApplianceSKUListResult); err != nil { + return VirtualApplianceSKUsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubbgpconnection_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubbgpconnection_client.go new file mode 100644 index 000000000..1334b44f4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubbgpconnection_client.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 armnetwork + +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" +) + +// VirtualHubBgpConnectionClient contains the methods for the VirtualHubBgpConnection group. +// Don't use this type directly, use NewVirtualHubBgpConnectionClient() instead. +type VirtualHubBgpConnectionClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualHubBgpConnectionClient creates a new instance of VirtualHubBgpConnectionClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualHubBgpConnectionClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualHubBgpConnectionClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualHubBgpConnectionClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a VirtualHubBgpConnection resource if it doesn't exist else updates the existing VirtualHubBgpConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - connectionName - The name of the connection. +// - parameters - Parameters of Bgp connection. +// - options - VirtualHubBgpConnectionClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubBgpConnectionClient.BeginCreateOrUpdate +// method. +func (client *VirtualHubBgpConnectionClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, parameters BgpConnection, options *VirtualHubBgpConnectionClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualHubBgpConnectionClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, connectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubBgpConnectionClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubBgpConnectionClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a VirtualHubBgpConnection resource if it doesn't exist else updates the existing VirtualHubBgpConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubBgpConnectionClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, parameters BgpConnection, options *VirtualHubBgpConnectionClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubBgpConnectionClient.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, virtualHubName, connectionName, 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 *VirtualHubBgpConnectionClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, parameters BgpConnection, options *VirtualHubBgpConnectionClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-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 a VirtualHubBgpConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHubBgpConnection. +// - virtualHubName - The name of the VirtualHub. +// - connectionName - The name of the connection. +// - options - VirtualHubBgpConnectionClientBeginDeleteOptions contains the optional parameters for the VirtualHubBgpConnectionClient.BeginDelete +// method. +func (client *VirtualHubBgpConnectionClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *VirtualHubBgpConnectionClientBeginDeleteOptions) (*runtime.Poller[VirtualHubBgpConnectionClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubBgpConnectionClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubBgpConnectionClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VirtualHubBgpConnection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubBgpConnectionClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *VirtualHubBgpConnectionClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubBgpConnectionClient.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, virtualHubName, connectionName, 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 *VirtualHubBgpConnectionClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *VirtualHubBgpConnectionClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a Virtual Hub Bgp Connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - connectionName - The name of the connection. +// - options - VirtualHubBgpConnectionClientGetOptions contains the optional parameters for the VirtualHubBgpConnectionClient.Get +// method. +func (client *VirtualHubBgpConnectionClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *VirtualHubBgpConnectionClientGetOptions) (VirtualHubBgpConnectionClientGetResponse, error) { + var err error + const operationName = "VirtualHubBgpConnectionClient.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, virtualHubName, connectionName, options) + if err != nil { + return VirtualHubBgpConnectionClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualHubBgpConnectionClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualHubBgpConnectionClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualHubBgpConnectionClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, options *VirtualHubBgpConnectionClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualHubBgpConnectionClient) getHandleResponse(resp *http.Response) (VirtualHubBgpConnectionClientGetResponse, error) { + result := VirtualHubBgpConnectionClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BgpConnection); err != nil { + return VirtualHubBgpConnectionClientGetResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubbgpconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubbgpconnections_client.go new file mode 100644 index 000000000..80b64897a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubbgpconnections_client.go @@ -0,0 +1,274 @@ +//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 armnetwork + +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" +) + +// VirtualHubBgpConnectionsClient contains the methods for the VirtualHubBgpConnections group. +// Don't use this type directly, use NewVirtualHubBgpConnectionsClient() instead. +type VirtualHubBgpConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualHubBgpConnectionsClient creates a new instance of VirtualHubBgpConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualHubBgpConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualHubBgpConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualHubBgpConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Retrieves the details of all VirtualHubBgpConnections. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - VirtualHubBgpConnectionsClientListOptions contains the optional parameters for the VirtualHubBgpConnectionsClient.NewListPager +// method. +func (client *VirtualHubBgpConnectionsClient) NewListPager(resourceGroupName string, virtualHubName string, options *VirtualHubBgpConnectionsClientListOptions) *runtime.Pager[VirtualHubBgpConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualHubBgpConnectionsClientListResponse]{ + More: func(page VirtualHubBgpConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualHubBgpConnectionsClientListResponse) (VirtualHubBgpConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualHubBgpConnectionsClient.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, virtualHubName, options) + }, nil) + if err != nil { + return VirtualHubBgpConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualHubBgpConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubBgpConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/bgpConnections" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualHubBgpConnectionsClient) listHandleResponse(resp *http.Response) (VirtualHubBgpConnectionsClientListResponse, error) { + result := VirtualHubBgpConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualHubBgpConnectionResults); err != nil { + return VirtualHubBgpConnectionsClientListResponse{}, err + } + return result, nil +} + +// BeginListAdvertisedRoutes - Retrieves a list of routes the virtual hub bgp connection is advertising to the specified peer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - hubName - The name of the virtual hub. +// - connectionName - The name of the virtual hub bgp connection. +// - options - VirtualHubBgpConnectionsClientBeginListAdvertisedRoutesOptions contains the optional parameters for the VirtualHubBgpConnectionsClient.BeginListAdvertisedRoutes +// method. +func (client *VirtualHubBgpConnectionsClient) BeginListAdvertisedRoutes(ctx context.Context, resourceGroupName string, hubName string, connectionName string, options *VirtualHubBgpConnectionsClientBeginListAdvertisedRoutesOptions) (*runtime.Poller[VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listAdvertisedRoutes(ctx, resourceGroupName, hubName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubBgpConnectionsClientListAdvertisedRoutesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListAdvertisedRoutes - Retrieves a list of routes the virtual hub bgp connection is advertising to the specified peer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubBgpConnectionsClient) listAdvertisedRoutes(ctx context.Context, resourceGroupName string, hubName string, connectionName string, options *VirtualHubBgpConnectionsClientBeginListAdvertisedRoutesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubBgpConnectionsClient.BeginListAdvertisedRoutes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAdvertisedRoutesCreateRequest(ctx, resourceGroupName, hubName, connectionName, 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 +} + +// listAdvertisedRoutesCreateRequest creates the ListAdvertisedRoutes request. +func (client *VirtualHubBgpConnectionsClient) listAdvertisedRoutesCreateRequest(ctx context.Context, resourceGroupName string, hubName string, connectionName string, options *VirtualHubBgpConnectionsClientBeginListAdvertisedRoutesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{hubName}/bgpConnections/{connectionName}/advertisedRoutes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hubName == "" { + return nil, errors.New("parameter hubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hubName}", url.PathEscape(hubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginListLearnedRoutes - Retrieves a list of routes the virtual hub bgp connection has learned. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - hubName - The name of the virtual hub. +// - connectionName - The name of the virtual hub bgp connection. +// - options - VirtualHubBgpConnectionsClientBeginListLearnedRoutesOptions contains the optional parameters for the VirtualHubBgpConnectionsClient.BeginListLearnedRoutes +// method. +func (client *VirtualHubBgpConnectionsClient) BeginListLearnedRoutes(ctx context.Context, resourceGroupName string, hubName string, connectionName string, options *VirtualHubBgpConnectionsClientBeginListLearnedRoutesOptions) (*runtime.Poller[VirtualHubBgpConnectionsClientListLearnedRoutesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listLearnedRoutes(ctx, resourceGroupName, hubName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubBgpConnectionsClientListLearnedRoutesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubBgpConnectionsClientListLearnedRoutesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListLearnedRoutes - Retrieves a list of routes the virtual hub bgp connection has learned. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubBgpConnectionsClient) listLearnedRoutes(ctx context.Context, resourceGroupName string, hubName string, connectionName string, options *VirtualHubBgpConnectionsClientBeginListLearnedRoutesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubBgpConnectionsClient.BeginListLearnedRoutes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listLearnedRoutesCreateRequest(ctx, resourceGroupName, hubName, connectionName, 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 +} + +// listLearnedRoutesCreateRequest creates the ListLearnedRoutes request. +func (client *VirtualHubBgpConnectionsClient) listLearnedRoutesCreateRequest(ctx context.Context, resourceGroupName string, hubName string, connectionName string, options *VirtualHubBgpConnectionsClientBeginListLearnedRoutesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{hubName}/bgpConnections/{connectionName}/learnedRoutes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if hubName == "" { + return nil, errors.New("parameter hubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hubName}", url.PathEscape(hubName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-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/network/armnetwork/v4/virtualhubipconfiguration_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubipconfiguration_client.go new file mode 100644 index 000000000..2bd36082f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubipconfiguration_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// VirtualHubIPConfigurationClient contains the methods for the VirtualHubIPConfiguration group. +// Don't use this type directly, use NewVirtualHubIPConfigurationClient() instead. +type VirtualHubIPConfigurationClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualHubIPConfigurationClient creates a new instance of VirtualHubIPConfigurationClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualHubIPConfigurationClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualHubIPConfigurationClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualHubIPConfigurationClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a VirtualHubIpConfiguration resource if it doesn't exist else updates the existing VirtualHubIpConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - ipConfigName - The name of the ipconfig. +// - parameters - Hub Ip Configuration parameters. +// - options - VirtualHubIPConfigurationClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubIPConfigurationClient.BeginCreateOrUpdate +// method. +func (client *VirtualHubIPConfigurationClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, parameters HubIPConfiguration, options *VirtualHubIPConfigurationClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualHubIPConfigurationClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, ipConfigName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubIPConfigurationClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubIPConfigurationClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a VirtualHubIpConfiguration resource if it doesn't exist else updates the existing VirtualHubIpConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubIPConfigurationClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, parameters HubIPConfiguration, options *VirtualHubIPConfigurationClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubIPConfigurationClient.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, virtualHubName, ipConfigName, 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 *VirtualHubIPConfigurationClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, parameters HubIPConfiguration, options *VirtualHubIPConfigurationClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/ipConfigurations/{ipConfigName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if ipConfigName == "" { + return nil, errors.New("parameter ipConfigName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigName}", url.PathEscape(ipConfigName)) + 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-05-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 a VirtualHubIpConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHubBgpConnection. +// - virtualHubName - The name of the VirtualHub. +// - ipConfigName - The name of the ipconfig. +// - options - VirtualHubIPConfigurationClientBeginDeleteOptions contains the optional parameters for the VirtualHubIPConfigurationClient.BeginDelete +// method. +func (client *VirtualHubIPConfigurationClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, options *VirtualHubIPConfigurationClientBeginDeleteOptions) (*runtime.Poller[VirtualHubIPConfigurationClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, ipConfigName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubIPConfigurationClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubIPConfigurationClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VirtualHubIpConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubIPConfigurationClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, options *VirtualHubIPConfigurationClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubIPConfigurationClient.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, virtualHubName, ipConfigName, 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 *VirtualHubIPConfigurationClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, options *VirtualHubIPConfigurationClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/ipConfigurations/{ipConfigName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if ipConfigName == "" { + return nil, errors.New("parameter ipConfigName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigName}", url.PathEscape(ipConfigName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a Virtual Hub Ip configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - ipConfigName - The name of the ipconfig. +// - options - VirtualHubIPConfigurationClientGetOptions contains the optional parameters for the VirtualHubIPConfigurationClient.Get +// method. +func (client *VirtualHubIPConfigurationClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, options *VirtualHubIPConfigurationClientGetOptions) (VirtualHubIPConfigurationClientGetResponse, error) { + var err error + const operationName = "VirtualHubIPConfigurationClient.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, virtualHubName, ipConfigName, options) + if err != nil { + return VirtualHubIPConfigurationClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualHubIPConfigurationClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualHubIPConfigurationClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualHubIPConfigurationClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, ipConfigName string, options *VirtualHubIPConfigurationClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/ipConfigurations/{ipConfigName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if ipConfigName == "" { + return nil, errors.New("parameter ipConfigName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ipConfigName}", url.PathEscape(ipConfigName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualHubIPConfigurationClient) getHandleResponse(resp *http.Response) (VirtualHubIPConfigurationClientGetResponse, error) { + result := VirtualHubIPConfigurationClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HubIPConfiguration); err != nil { + return VirtualHubIPConfigurationClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves the details of all VirtualHubIpConfigurations. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - VirtualHubIPConfigurationClientListOptions contains the optional parameters for the VirtualHubIPConfigurationClient.NewListPager +// method. +func (client *VirtualHubIPConfigurationClient) NewListPager(resourceGroupName string, virtualHubName string, options *VirtualHubIPConfigurationClientListOptions) *runtime.Pager[VirtualHubIPConfigurationClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualHubIPConfigurationClientListResponse]{ + More: func(page VirtualHubIPConfigurationClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualHubIPConfigurationClientListResponse) (VirtualHubIPConfigurationClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualHubIPConfigurationClient.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, virtualHubName, options) + }, nil) + if err != nil { + return VirtualHubIPConfigurationClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualHubIPConfigurationClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubIPConfigurationClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/ipConfigurations" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualHubIPConfigurationClient) listHandleResponse(resp *http.Response) (VirtualHubIPConfigurationClientListResponse, error) { + result := VirtualHubIPConfigurationClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualHubIPConfigurationResults); err != nil { + return VirtualHubIPConfigurationClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubroutetablev2s_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubroutetablev2s_client.go new file mode 100644 index 000000000..421996273 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubroutetablev2s_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// VirtualHubRouteTableV2SClient contains the methods for the VirtualHubRouteTableV2S group. +// Don't use this type directly, use NewVirtualHubRouteTableV2SClient() instead. +type VirtualHubRouteTableV2SClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualHubRouteTableV2SClient creates a new instance of VirtualHubRouteTableV2SClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualHubRouteTableV2SClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualHubRouteTableV2SClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualHubRouteTableV2SClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a VirtualHubRouteTableV2 resource if it doesn't exist else updates the existing VirtualHubRouteTableV2. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - routeTableName - The name of the VirtualHubRouteTableV2. +// - virtualHubRouteTableV2Parameters - Parameters supplied to create or update VirtualHubRouteTableV2. +// - options - VirtualHubRouteTableV2SClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.BeginCreateOrUpdate +// method. +func (client *VirtualHubRouteTableV2SClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, virtualHubRouteTableV2Parameters VirtualHubRouteTableV2, options *VirtualHubRouteTableV2SClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualHubRouteTableV2SClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, routeTableName, virtualHubRouteTableV2Parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubRouteTableV2SClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubRouteTableV2SClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a VirtualHubRouteTableV2 resource if it doesn't exist else updates the existing VirtualHubRouteTableV2. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubRouteTableV2SClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, virtualHubRouteTableV2Parameters VirtualHubRouteTableV2, options *VirtualHubRouteTableV2SClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubRouteTableV2SClient.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, virtualHubName, routeTableName, virtualHubRouteTableV2Parameters, 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 *VirtualHubRouteTableV2SClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, virtualHubRouteTableV2Parameters VirtualHubRouteTableV2, options *VirtualHubRouteTableV2SClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, virtualHubRouteTableV2Parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a VirtualHubRouteTableV2. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHubRouteTableV2. +// - virtualHubName - The name of the VirtualHub. +// - routeTableName - The name of the VirtualHubRouteTableV2. +// - options - VirtualHubRouteTableV2SClientBeginDeleteOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.BeginDelete +// method. +func (client *VirtualHubRouteTableV2SClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *VirtualHubRouteTableV2SClientBeginDeleteOptions) (*runtime.Poller[VirtualHubRouteTableV2SClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, routeTableName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubRouteTableV2SClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubRouteTableV2SClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VirtualHubRouteTableV2. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubRouteTableV2SClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *VirtualHubRouteTableV2SClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubRouteTableV2SClient.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, virtualHubName, routeTableName, 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 *VirtualHubRouteTableV2SClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *VirtualHubRouteTableV2SClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a VirtualHubRouteTableV2. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHubRouteTableV2. +// - virtualHubName - The name of the VirtualHub. +// - routeTableName - The name of the VirtualHubRouteTableV2. +// - options - VirtualHubRouteTableV2SClientGetOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.Get +// method. +func (client *VirtualHubRouteTableV2SClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *VirtualHubRouteTableV2SClientGetOptions) (VirtualHubRouteTableV2SClientGetResponse, error) { + var err error + const operationName = "VirtualHubRouteTableV2SClient.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, virtualHubName, routeTableName, options) + if err != nil { + return VirtualHubRouteTableV2SClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualHubRouteTableV2SClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualHubRouteTableV2SClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualHubRouteTableV2SClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, options *VirtualHubRouteTableV2SClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + if routeTableName == "" { + return nil, errors.New("parameter routeTableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{routeTableName}", url.PathEscape(routeTableName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualHubRouteTableV2SClient) getHandleResponse(resp *http.Response) (VirtualHubRouteTableV2SClientGetResponse, error) { + result := VirtualHubRouteTableV2SClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualHubRouteTableV2); err != nil { + return VirtualHubRouteTableV2SClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Retrieves the details of all VirtualHubRouteTableV2s. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - VirtualHubRouteTableV2SClientListOptions contains the optional parameters for the VirtualHubRouteTableV2SClient.NewListPager +// method. +func (client *VirtualHubRouteTableV2SClient) NewListPager(resourceGroupName string, virtualHubName string, options *VirtualHubRouteTableV2SClientListOptions) *runtime.Pager[VirtualHubRouteTableV2SClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualHubRouteTableV2SClientListResponse]{ + More: func(page VirtualHubRouteTableV2SClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualHubRouteTableV2SClientListResponse) (VirtualHubRouteTableV2SClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualHubRouteTableV2SClient.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, virtualHubName, options) + }, nil) + if err != nil { + return VirtualHubRouteTableV2SClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualHubRouteTableV2SClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubRouteTableV2SClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualHubRouteTableV2SClient) listHandleResponse(resp *http.Response) (VirtualHubRouteTableV2SClientListResponse, error) { + result := VirtualHubRouteTableV2SClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualHubRouteTableV2SResult); err != nil { + return VirtualHubRouteTableV2SClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubs_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubs_client.go new file mode 100644 index 000000000..3cb2a8d30 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualhubs_client.go @@ -0,0 +1,695 @@ +//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 armnetwork + +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" +) + +// VirtualHubsClient contains the methods for the VirtualHubs group. +// Don't use this type directly, use NewVirtualHubsClient() instead. +type VirtualHubsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualHubsClient creates a new instance of VirtualHubsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualHubsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualHubsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualHubsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a VirtualHub resource if it doesn't exist else updates the existing VirtualHub. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - virtualHubParameters - Parameters supplied to create or update VirtualHub. +// - options - VirtualHubsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualHubsClient.BeginCreateOrUpdate +// method. +func (client *VirtualHubsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters VirtualHub, options *VirtualHubsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualHubsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualHubName, virtualHubParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a VirtualHub resource if it doesn't exist else updates the existing VirtualHub. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubsClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters VirtualHub, options *VirtualHubsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubsClient.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, virtualHubName, virtualHubParameters, 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 *VirtualHubsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters VirtualHub, options *VirtualHubsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, virtualHubParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a VirtualHub. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - VirtualHubsClientBeginDeleteOptions contains the optional parameters for the VirtualHubsClient.BeginDelete method. +func (client *VirtualHubsClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientBeginDeleteOptions) (*runtime.Poller[VirtualHubsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualHubName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VirtualHub. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubsClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubsClient.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, virtualHubName, 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 *VirtualHubsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a VirtualHub. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - VirtualHubsClientGetOptions contains the optional parameters for the VirtualHubsClient.Get method. +func (client *VirtualHubsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientGetOptions) (VirtualHubsClientGetResponse, error) { + var err error + const operationName = "VirtualHubsClient.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, virtualHubName, options) + if err != nil { + return VirtualHubsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualHubsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualHubsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualHubsClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualHubsClient) getHandleResponse(resp *http.Response) (VirtualHubsClientGetResponse, error) { + result := VirtualHubsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualHub); err != nil { + return VirtualHubsClientGetResponse{}, err + } + return result, nil +} + +// BeginGetEffectiveVirtualHubRoutes - Gets the effective routes configured for the Virtual Hub resource or the specified +// resource . +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - options - VirtualHubsClientBeginGetEffectiveVirtualHubRoutesOptions contains the optional parameters for the VirtualHubsClient.BeginGetEffectiveVirtualHubRoutes +// method. +func (client *VirtualHubsClient) BeginGetEffectiveVirtualHubRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientBeginGetEffectiveVirtualHubRoutesOptions) (*runtime.Poller[VirtualHubsClientGetEffectiveVirtualHubRoutesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getEffectiveVirtualHubRoutes(ctx, resourceGroupName, virtualHubName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubsClientGetEffectiveVirtualHubRoutesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubsClientGetEffectiveVirtualHubRoutesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetEffectiveVirtualHubRoutes - Gets the effective routes configured for the Virtual Hub resource or the specified resource +// . +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubsClient) getEffectiveVirtualHubRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientBeginGetEffectiveVirtualHubRoutesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubsClient.BeginGetEffectiveVirtualHubRoutes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getEffectiveVirtualHubRoutesCreateRequest(ctx, resourceGroupName, virtualHubName, 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 +} + +// getEffectiveVirtualHubRoutesCreateRequest creates the GetEffectiveVirtualHubRoutes request. +func (client *VirtualHubsClient) getEffectiveVirtualHubRoutesCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, options *VirtualHubsClientBeginGetEffectiveVirtualHubRoutesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/effectiveRoutes" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.EffectiveRoutesParameters != nil { + if err := runtime.MarshalAsJSON(req, *options.EffectiveRoutesParameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginGetInboundRoutes - Gets the inbound routes configured for the Virtual Hub on a particular connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - getInboundRoutesParameters - Parameters supplied to get the inbound routes for a connection resource. +// - options - VirtualHubsClientBeginGetInboundRoutesOptions contains the optional parameters for the VirtualHubsClient.BeginGetInboundRoutes +// method. +func (client *VirtualHubsClient) BeginGetInboundRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, getInboundRoutesParameters GetInboundRoutesParameters, options *VirtualHubsClientBeginGetInboundRoutesOptions) (*runtime.Poller[VirtualHubsClientGetInboundRoutesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getInboundRoutes(ctx, resourceGroupName, virtualHubName, getInboundRoutesParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubsClientGetInboundRoutesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubsClientGetInboundRoutesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetInboundRoutes - Gets the inbound routes configured for the Virtual Hub on a particular connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubsClient) getInboundRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, getInboundRoutesParameters GetInboundRoutesParameters, options *VirtualHubsClientBeginGetInboundRoutesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubsClient.BeginGetInboundRoutes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getInboundRoutesCreateRequest(ctx, resourceGroupName, virtualHubName, getInboundRoutesParameters, 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 +} + +// getInboundRoutesCreateRequest creates the GetInboundRoutes request. +func (client *VirtualHubsClient) getInboundRoutesCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, getInboundRoutesParameters GetInboundRoutesParameters, options *VirtualHubsClientBeginGetInboundRoutesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/inboundRoutes" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, getInboundRoutesParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginGetOutboundRoutes - Gets the outbound routes configured for the Virtual Hub on a particular connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - getOutboundRoutesParameters - Parameters supplied to get the outbound routes for a connection resource. +// - options - VirtualHubsClientBeginGetOutboundRoutesOptions contains the optional parameters for the VirtualHubsClient.BeginGetOutboundRoutes +// method. +func (client *VirtualHubsClient) BeginGetOutboundRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, getOutboundRoutesParameters GetOutboundRoutesParameters, options *VirtualHubsClientBeginGetOutboundRoutesOptions) (*runtime.Poller[VirtualHubsClientGetOutboundRoutesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getOutboundRoutes(ctx, resourceGroupName, virtualHubName, getOutboundRoutesParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualHubsClientGetOutboundRoutesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualHubsClientGetOutboundRoutesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetOutboundRoutes - Gets the outbound routes configured for the Virtual Hub on a particular connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualHubsClient) getOutboundRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, getOutboundRoutesParameters GetOutboundRoutesParameters, options *VirtualHubsClientBeginGetOutboundRoutesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualHubsClient.BeginGetOutboundRoutes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getOutboundRoutesCreateRequest(ctx, resourceGroupName, virtualHubName, getOutboundRoutesParameters, 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 +} + +// getOutboundRoutesCreateRequest creates the GetOutboundRoutes request. +func (client *VirtualHubsClient) getOutboundRoutesCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, getOutboundRoutesParameters GetOutboundRoutesParameters, options *VirtualHubsClientBeginGetOutboundRoutesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/outboundRoutes" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, getOutboundRoutesParameters); err != nil { + return nil, err + } + return req, nil +} + +// NewListPager - Lists all the VirtualHubs in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VirtualHubsClientListOptions contains the optional parameters for the VirtualHubsClient.NewListPager method. +func (client *VirtualHubsClient) NewListPager(options *VirtualHubsClientListOptions) *runtime.Pager[VirtualHubsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualHubsClientListResponse]{ + More: func(page VirtualHubsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualHubsClientListResponse) (VirtualHubsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualHubsClient.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 VirtualHubsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualHubsClient) listCreateRequest(ctx context.Context, options *VirtualHubsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualHubs" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualHubsClient) listHandleResponse(resp *http.Response) (VirtualHubsClientListResponse, error) { + result := VirtualHubsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualHubsResult); err != nil { + return VirtualHubsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the VirtualHubs in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - options - VirtualHubsClientListByResourceGroupOptions contains the optional parameters for the VirtualHubsClient.NewListByResourceGroupPager +// method. +func (client *VirtualHubsClient) NewListByResourceGroupPager(resourceGroupName string, options *VirtualHubsClientListByResourceGroupOptions) *runtime.Pager[VirtualHubsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualHubsClientListByResourceGroupResponse]{ + More: func(page VirtualHubsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualHubsClientListByResourceGroupResponse) (VirtualHubsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualHubsClient.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 VirtualHubsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VirtualHubsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualHubsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VirtualHubsClient) listByResourceGroupHandleResponse(resp *http.Response) (VirtualHubsClientListByResourceGroupResponse, error) { + result := VirtualHubsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualHubsResult); err != nil { + return VirtualHubsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates VirtualHub tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualHub. +// - virtualHubName - The name of the VirtualHub. +// - virtualHubParameters - Parameters supplied to update VirtualHub tags. +// - options - VirtualHubsClientUpdateTagsOptions contains the optional parameters for the VirtualHubsClient.UpdateTags method. +func (client *VirtualHubsClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters TagsObject, options *VirtualHubsClientUpdateTagsOptions) (VirtualHubsClientUpdateTagsResponse, error) { + var err error + const operationName = "VirtualHubsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, virtualHubName, virtualHubParameters, options) + if err != nil { + return VirtualHubsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualHubsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualHubsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VirtualHubsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters TagsObject, options *VirtualHubsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}" + 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 virtualHubName == "" { + return nil, errors.New("parameter virtualHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualHubName}", url.PathEscape(virtualHubName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, virtualHubParameters); err != nil { + return nil, err + } + return req, nil +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *VirtualHubsClient) updateTagsHandleResponse(resp *http.Response) (VirtualHubsClientUpdateTagsResponse, error) { + result := VirtualHubsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualHub); err != nil { + return VirtualHubsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgatewayconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgatewayconnections_client.go new file mode 100644 index 000000000..f1bdd90b3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgatewayconnections_client.go @@ -0,0 +1,966 @@ +//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 armnetwork + +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" +) + +// VirtualNetworkGatewayConnectionsClient contains the methods for the VirtualNetworkGatewayConnections group. +// Don't use this type directly, use NewVirtualNetworkGatewayConnectionsClient() instead. +type VirtualNetworkGatewayConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualNetworkGatewayConnectionsClient creates a new instance of VirtualNetworkGatewayConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualNetworkGatewayConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualNetworkGatewayConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualNetworkGatewayConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway connection. +// - parameters - Parameters supplied to the create or update virtual network gateway connection operation. +// - options - VirtualNetworkGatewayConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginCreateOrUpdate +// method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, options *VirtualNetworkGatewayConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, options *VirtualNetworkGatewayConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.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, virtualNetworkGatewayConnectionName, 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 *VirtualNetworkGatewayConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, options *VirtualNetworkGatewayConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-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 virtual network Gateway connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway connection. +// - options - VirtualNetworkGatewayConnectionsClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginDelete +// method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginDeleteOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified virtual network Gateway connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.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, virtualNetworkGatewayConnectionName, 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 *VirtualNetworkGatewayConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified virtual network gateway connection by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway connection. +// - options - VirtualNetworkGatewayConnectionsClientGetOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.Get +// method. +func (client *VirtualNetworkGatewayConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientGetOptions) (VirtualNetworkGatewayConnectionsClientGetResponse, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.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, virtualNetworkGatewayConnectionName, options) + if err != nil { + return VirtualNetworkGatewayConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkGatewayConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkGatewayConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualNetworkGatewayConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualNetworkGatewayConnectionsClient) getHandleResponse(resp *http.Response) (VirtualNetworkGatewayConnectionsClientGetResponse, error) { + result := VirtualNetworkGatewayConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkGatewayConnection); err != nil { + return VirtualNetworkGatewayConnectionsClientGetResponse{}, err + } + return result, nil +} + +// BeginGetIkeSas - Lists IKE Security Associations for the virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway Connection. +// - options - VirtualNetworkGatewayConnectionsClientBeginGetIkeSasOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginGetIkeSas +// method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginGetIkeSas(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginGetIkeSasOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientGetIkeSasResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getIkeSas(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientGetIkeSasResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientGetIkeSasResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetIkeSas - Lists IKE Security Associations for the virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) getIkeSas(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginGetIkeSasOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.BeginGetIkeSas" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getIkeSasCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, 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 +} + +// getIkeSasCreateRequest creates the GetIkeSas request. +func (client *VirtualNetworkGatewayConnectionsClient) getIkeSasCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginGetIkeSasOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/getikesas" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// GetSharedKey - The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual +// network gateway connection shared key through Network resource provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The virtual network gateway connection shared key name. +// - options - VirtualNetworkGatewayConnectionsClientGetSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.GetSharedKey +// method. +func (client *VirtualNetworkGatewayConnectionsClient) GetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientGetSharedKeyOptions) (VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.GetSharedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getSharedKeyCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, options) + if err != nil { + return VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse{}, err + } + resp, err := client.getSharedKeyHandleResponse(httpResp) + return resp, err +} + +// getSharedKeyCreateRequest creates the GetSharedKey request. +func (client *VirtualNetworkGatewayConnectionsClient) getSharedKeyCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientGetSharedKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getSharedKeyHandleResponse handles the GetSharedKey response. +func (client *VirtualNetworkGatewayConnectionsClient) getSharedKeyHandleResponse(resp *http.Response) (VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse, error) { + result := VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionSharedKey); err != nil { + return VirtualNetworkGatewayConnectionsClientGetSharedKeyResponse{}, err + } + return result, nil +} + +// NewListPager - The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections +// created. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualNetworkGatewayConnectionsClientListOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.NewListPager +// method. +func (client *VirtualNetworkGatewayConnectionsClient) NewListPager(resourceGroupName string, options *VirtualNetworkGatewayConnectionsClientListOptions) *runtime.Pager[VirtualNetworkGatewayConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkGatewayConnectionsClientListResponse]{ + More: func(page VirtualNetworkGatewayConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkGatewayConnectionsClientListResponse) (VirtualNetworkGatewayConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkGatewayConnectionsClient.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, options) + }, nil) + if err != nil { + return VirtualNetworkGatewayConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualNetworkGatewayConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualNetworkGatewayConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualNetworkGatewayConnectionsClient) listHandleResponse(resp *http.Response) (VirtualNetworkGatewayConnectionsClientListResponse, error) { + result := VirtualNetworkGatewayConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkGatewayConnectionListResult); err != nil { + return VirtualNetworkGatewayConnectionsClientListResponse{}, err + } + return result, nil +} + +// BeginResetConnection - Resets the virtual network gateway connection specified. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway Connection. +// - options - VirtualNetworkGatewayConnectionsClientBeginResetConnectionOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginResetConnection +// method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginResetConnection(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginResetConnectionOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientResetConnectionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.resetConnection(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientResetConnectionResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientResetConnectionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ResetConnection - Resets the virtual network gateway connection specified. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) resetConnection(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginResetConnectionOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.BeginResetConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetConnectionCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, 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 +} + +// resetConnectionCreateRequest creates the ResetConnection request. +func (client *VirtualNetworkGatewayConnectionsClient) resetConnectionCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginResetConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/resetconnection" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginResetSharedKey - The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection +// shared key for passed virtual network gateway connection in the specified resource group +// through Network resource provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The virtual network gateway connection reset shared key Name. +// - parameters - Parameters supplied to the begin reset virtual network gateway connection shared key operation through network +// resource provider. +// - options - VirtualNetworkGatewayConnectionsClientBeginResetSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginResetSharedKey +// method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginResetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, options *VirtualNetworkGatewayConnectionsClientBeginResetSharedKeyOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientResetSharedKeyResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.resetSharedKey(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientResetSharedKeyResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientResetSharedKeyResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ResetSharedKey - The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection +// shared key for passed virtual network gateway connection in the specified resource group +// through Network resource provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) resetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, options *VirtualNetworkGatewayConnectionsClientBeginResetSharedKeyOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.BeginResetSharedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetSharedKeyCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, 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 +} + +// resetSharedKeyCreateRequest creates the ResetSharedKey request. +func (client *VirtualNetworkGatewayConnectionsClient) resetSharedKeyCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, options *VirtualNetworkGatewayConnectionsClientBeginResetSharedKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-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 +} + +// BeginSetSharedKey - The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection +// shared key for passed virtual network gateway connection in the specified resource group through +// Network resource provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The virtual network gateway connection name. +// - parameters - Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork +// resource provider. +// - options - VirtualNetworkGatewayConnectionsClientBeginSetSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginSetSharedKey +// method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginSetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, options *VirtualNetworkGatewayConnectionsClientBeginSetSharedKeyOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientSetSharedKeyResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.setSharedKey(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientSetSharedKeyResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientSetSharedKeyResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// SetSharedKey - The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared +// key for passed virtual network gateway connection in the specified resource group through +// Network resource provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) setSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, options *VirtualNetworkGatewayConnectionsClientBeginSetSharedKeyOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.BeginSetSharedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setSharedKeyCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, 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 +} + +// setSharedKeyCreateRequest creates the SetSharedKey request. +func (client *VirtualNetworkGatewayConnectionsClient) setSharedKeyCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, options *VirtualNetworkGatewayConnectionsClientBeginSetSharedKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-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 +} + +// BeginStartPacketCapture - Starts packet capture on virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway connection. +// - options - VirtualNetworkGatewayConnectionsClientBeginStartPacketCaptureOptions contains the optional parameters for the +// VirtualNetworkGatewayConnectionsClient.BeginStartPacketCapture method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginStartPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginStartPacketCaptureOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientStartPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.startPacketCapture(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientStartPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientStartPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StartPacketCapture - Starts packet capture on virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) startPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginStartPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.BeginStartPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startPacketCaptureCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, 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 +} + +// startPacketCaptureCreateRequest creates the StartPacketCapture request. +func (client *VirtualNetworkGatewayConnectionsClient) startPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, options *VirtualNetworkGatewayConnectionsClientBeginStartPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/startPacketCapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-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 +} + +// BeginStopPacketCapture - Stops packet capture on virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway Connection. +// - parameters - Virtual network gateway packet capture parameters supplied to stop packet capture on gateway connection. +// - options - VirtualNetworkGatewayConnectionsClientBeginStopPacketCaptureOptions contains the optional parameters for the +// VirtualNetworkGatewayConnectionsClient.BeginStopPacketCapture method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginStopPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VPNPacketCaptureStopParameters, options *VirtualNetworkGatewayConnectionsClientBeginStopPacketCaptureOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientStopPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stopPacketCapture(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientStopPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientStopPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StopPacketCapture - Stops packet capture on virtual network gateway connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) stopPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VPNPacketCaptureStopParameters, options *VirtualNetworkGatewayConnectionsClientBeginStopPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.BeginStopPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopPacketCaptureCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, 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 +} + +// stopPacketCaptureCreateRequest creates the StopPacketCapture request. +func (client *VirtualNetworkGatewayConnectionsClient) stopPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VPNPacketCaptureStopParameters, options *VirtualNetworkGatewayConnectionsClientBeginStopPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/stopPacketCapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-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 +} + +// BeginUpdateTags - Updates a virtual network gateway connection tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway connection. +// - parameters - Parameters supplied to update virtual network gateway connection tags. +// - options - VirtualNetworkGatewayConnectionsClientBeginUpdateTagsOptions contains the optional parameters for the VirtualNetworkGatewayConnectionsClient.BeginUpdateTags +// method. +func (client *VirtualNetworkGatewayConnectionsClient) BeginUpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters TagsObject, options *VirtualNetworkGatewayConnectionsClientBeginUpdateTagsOptions) (*runtime.Poller[VirtualNetworkGatewayConnectionsClientUpdateTagsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateTags(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayConnectionsClientUpdateTagsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayConnectionsClientUpdateTagsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateTags - Updates a virtual network gateway connection tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayConnectionsClient) updateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters TagsObject, options *VirtualNetworkGatewayConnectionsClientBeginUpdateTagsOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayConnectionsClient.BeginUpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, 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 +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VirtualNetworkGatewayConnectionsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters TagsObject, options *VirtualNetworkGatewayConnectionsClientBeginUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-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/network/armnetwork/v4/virtualnetworkgatewaynatrules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgatewaynatrules_client.go new file mode 100644 index 000000000..28dd7a3b7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgatewaynatrules_client.go @@ -0,0 +1,350 @@ +//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 armnetwork + +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" +) + +// VirtualNetworkGatewayNatRulesClient contains the methods for the VirtualNetworkGatewayNatRules group. +// Don't use this type directly, use NewVirtualNetworkGatewayNatRulesClient() instead. +type VirtualNetworkGatewayNatRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualNetworkGatewayNatRulesClient creates a new instance of VirtualNetworkGatewayNatRulesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualNetworkGatewayNatRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualNetworkGatewayNatRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualNetworkGatewayNatRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a nat rule to a scalable virtual network gateway if it doesn't exist else updates the existing +// nat rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the Virtual Network Gateway. +// - virtualNetworkGatewayName - The name of the gateway. +// - natRuleName - The name of the nat rule. +// - natRuleParameters - Parameters supplied to create or Update a Nat Rule. +// - options - VirtualNetworkGatewayNatRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkGatewayNatRulesClient.BeginCreateOrUpdate +// method. +func (client *VirtualNetworkGatewayNatRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, natRuleParameters VirtualNetworkGatewayNatRule, options *VirtualNetworkGatewayNatRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualNetworkGatewayNatRulesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualNetworkGatewayName, natRuleName, natRuleParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayNatRulesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayNatRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a nat rule to a scalable virtual network gateway if it doesn't exist else updates the existing +// nat rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayNatRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, natRuleParameters VirtualNetworkGatewayNatRule, options *VirtualNetworkGatewayNatRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayNatRulesClient.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, virtualNetworkGatewayName, natRuleName, natRuleParameters, 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 *VirtualNetworkGatewayNatRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, natRuleParameters VirtualNetworkGatewayNatRule, options *VirtualNetworkGatewayNatRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules/{natRuleName}" + 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 virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + if natRuleName == "" { + return nil, errors.New("parameter natRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natRuleName}", url.PathEscape(natRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, natRuleParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a nat rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the Virtual Network Gateway. +// - virtualNetworkGatewayName - The name of the gateway. +// - natRuleName - The name of the nat rule. +// - options - VirtualNetworkGatewayNatRulesClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkGatewayNatRulesClient.BeginDelete +// method. +func (client *VirtualNetworkGatewayNatRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, options *VirtualNetworkGatewayNatRulesClientBeginDeleteOptions) (*runtime.Poller[VirtualNetworkGatewayNatRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualNetworkGatewayName, natRuleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewayNatRulesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewayNatRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a nat rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewayNatRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, options *VirtualNetworkGatewayNatRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewayNatRulesClient.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, virtualNetworkGatewayName, natRuleName, 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 *VirtualNetworkGatewayNatRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, options *VirtualNetworkGatewayNatRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules/{natRuleName}" + 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 virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + if natRuleName == "" { + return nil, errors.New("parameter natRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natRuleName}", url.PathEscape(natRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a nat rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the Virtual Network Gateway. +// - virtualNetworkGatewayName - The name of the gateway. +// - natRuleName - The name of the nat rule. +// - options - VirtualNetworkGatewayNatRulesClientGetOptions contains the optional parameters for the VirtualNetworkGatewayNatRulesClient.Get +// method. +func (client *VirtualNetworkGatewayNatRulesClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, options *VirtualNetworkGatewayNatRulesClientGetOptions) (VirtualNetworkGatewayNatRulesClientGetResponse, error) { + var err error + const operationName = "VirtualNetworkGatewayNatRulesClient.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, virtualNetworkGatewayName, natRuleName, options) + if err != nil { + return VirtualNetworkGatewayNatRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkGatewayNatRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkGatewayNatRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualNetworkGatewayNatRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, options *VirtualNetworkGatewayNatRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules/{natRuleName}" + 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 virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + if natRuleName == "" { + return nil, errors.New("parameter natRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{natRuleName}", url.PathEscape(natRuleName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualNetworkGatewayNatRulesClient) getHandleResponse(resp *http.Response) (VirtualNetworkGatewayNatRulesClientGetResponse, error) { + result := VirtualNetworkGatewayNatRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkGatewayNatRule); err != nil { + return VirtualNetworkGatewayNatRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListByVirtualNetworkGatewayPager - Retrieves all nat rules for a particular virtual network gateway. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the virtual network gateway. +// - virtualNetworkGatewayName - The name of the gateway. +// - options - VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayOptions contains the optional parameters for the +// VirtualNetworkGatewayNatRulesClient.NewListByVirtualNetworkGatewayPager method. +func (client *VirtualNetworkGatewayNatRulesClient) NewListByVirtualNetworkGatewayPager(resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayOptions) *runtime.Pager[VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse]{ + More: func(page VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse) (VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkGatewayNatRulesClient.NewListByVirtualNetworkGatewayPager") + 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.listByVirtualNetworkGatewayCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, options) + }, nil) + if err != nil { + return VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse{}, err + } + return client.listByVirtualNetworkGatewayHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVirtualNetworkGatewayCreateRequest creates the ListByVirtualNetworkGateway request. +func (client *VirtualNetworkGatewayNatRulesClient) listByVirtualNetworkGatewayCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules" + 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 virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVirtualNetworkGatewayHandleResponse handles the ListByVirtualNetworkGateway response. +func (client *VirtualNetworkGatewayNatRulesClient) listByVirtualNetworkGatewayHandleResponse(resp *http.Response) (VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse, error) { + result := VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualNetworkGatewayNatRulesResult); err != nil { + return VirtualNetworkGatewayNatRulesClientListByVirtualNetworkGatewayResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgateways_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgateways_client.go new file mode 100644 index 000000000..e1bf690f8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkgateways_client.go @@ -0,0 +1,1743 @@ +//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 armnetwork + +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" +) + +// VirtualNetworkGatewaysClient contains the methods for the VirtualNetworkGateways group. +// Don't use this type directly, use NewVirtualNetworkGatewaysClient() instead. +type VirtualNetworkGatewaysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualNetworkGatewaysClient creates a new instance of VirtualNetworkGatewaysClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualNetworkGatewaysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualNetworkGatewaysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualNetworkGatewaysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - parameters - Parameters supplied to create or update virtual network gateway operation. +// - options - VirtualNetworkGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginCreateOrUpdate +// method. +func (client *VirtualNetworkGatewaysClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, options *VirtualNetworkGatewaysClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualNetworkGatewaysClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualNetworkGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, options *VirtualNetworkGatewaysClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.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, virtualNetworkGatewayName, 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 *VirtualNetworkGatewaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, options *VirtualNetworkGatewaysClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-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 virtual network gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginDelete +// method. +func (client *VirtualNetworkGatewaysClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginDeleteOptions) (*runtime.Poller[VirtualNetworkGatewaysClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified virtual network gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.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, virtualNetworkGatewayName, 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 *VirtualNetworkGatewaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginDisconnectVirtualNetworkGatewayVPNConnections - Disconnect vpn connections of virtual network gateway in the specified +// resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - request - The parameters are supplied to disconnect vpn connections. +// - options - VirtualNetworkGatewaysClientBeginDisconnectVirtualNetworkGatewayVPNConnectionsOptions contains the optional parameters +// for the VirtualNetworkGatewaysClient.BeginDisconnectVirtualNetworkGatewayVPNConnections method. +func (client *VirtualNetworkGatewaysClient) BeginDisconnectVirtualNetworkGatewayVPNConnections(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, request P2SVPNConnectionRequest, options *VirtualNetworkGatewaysClientBeginDisconnectVirtualNetworkGatewayVPNConnectionsOptions) (*runtime.Poller[VirtualNetworkGatewaysClientDisconnectVirtualNetworkGatewayVPNConnectionsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.disconnectVirtualNetworkGatewayVPNConnections(ctx, resourceGroupName, virtualNetworkGatewayName, request, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientDisconnectVirtualNetworkGatewayVPNConnectionsResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientDisconnectVirtualNetworkGatewayVPNConnectionsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DisconnectVirtualNetworkGatewayVPNConnections - Disconnect vpn connections of virtual network gateway in the specified +// resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) disconnectVirtualNetworkGatewayVPNConnections(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, request P2SVPNConnectionRequest, options *VirtualNetworkGatewaysClientBeginDisconnectVirtualNetworkGatewayVPNConnectionsOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginDisconnectVirtualNetworkGatewayVPNConnections" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disconnectVirtualNetworkGatewayVPNConnectionsCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, request, 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 +} + +// disconnectVirtualNetworkGatewayVPNConnectionsCreateRequest creates the DisconnectVirtualNetworkGatewayVPNConnections request. +func (client *VirtualNetworkGatewaysClient) disconnectVirtualNetworkGatewayVPNConnectionsCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, request P2SVPNConnectionRequest, options *VirtualNetworkGatewaysClientBeginDisconnectVirtualNetworkGatewayVPNConnectionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/disconnectVirtualNetworkGatewayVpnConnections" + 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 virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, request); err != nil { + return nil, err + } + return req, nil +} + +// BeginGenerateVPNProfile - Generates VPN profile for P2S client of the virtual network gateway in the specified resource +// group. Used for IKEV2 and radius based authentication. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - parameters - Parameters supplied to the generate virtual network gateway VPN client package operation. +// - options - VirtualNetworkGatewaysClientBeginGenerateVPNProfileOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGenerateVPNProfile +// method. +func (client *VirtualNetworkGatewaysClient) BeginGenerateVPNProfile(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNClientParameters, options *VirtualNetworkGatewaysClientBeginGenerateVPNProfileOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGenerateVPNProfileResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.generateVPNProfile(ctx, resourceGroupName, virtualNetworkGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGenerateVPNProfileResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGenerateVPNProfileResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GenerateVPNProfile - Generates VPN profile for P2S client of the virtual network gateway in the specified resource group. +// Used for IKEV2 and radius based authentication. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) generateVPNProfile(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNClientParameters, options *VirtualNetworkGatewaysClientBeginGenerateVPNProfileOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGenerateVPNProfile" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generateVPNProfileCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// generateVPNProfileCreateRequest creates the GenerateVPNProfile request. +func (client *VirtualNetworkGatewaysClient) generateVPNProfileCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNClientParameters, options *VirtualNetworkGatewaysClientBeginGenerateVPNProfileOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/generatevpnprofile" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-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 +} + +// BeginGeneratevpnclientpackage - Generates VPN client package for P2S client of the virtual network gateway in the specified +// resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - parameters - Parameters supplied to the generate virtual network gateway VPN client package operation. +// - options - VirtualNetworkGatewaysClientBeginGeneratevpnclientpackageOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGeneratevpnclientpackage +// method. +func (client *VirtualNetworkGatewaysClient) BeginGeneratevpnclientpackage(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNClientParameters, options *VirtualNetworkGatewaysClientBeginGeneratevpnclientpackageOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGeneratevpnclientpackageResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.generatevpnclientpackage(ctx, resourceGroupName, virtualNetworkGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGeneratevpnclientpackageResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGeneratevpnclientpackageResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Generatevpnclientpackage - Generates VPN client package for P2S client of the virtual network gateway in the specified +// resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) generatevpnclientpackage(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNClientParameters, options *VirtualNetworkGatewaysClientBeginGeneratevpnclientpackageOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGeneratevpnclientpackage" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generatevpnclientpackageCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// generatevpnclientpackageCreateRequest creates the Generatevpnclientpackage request. +func (client *VirtualNetworkGatewaysClient) generatevpnclientpackageCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNClientParameters, options *VirtualNetworkGatewaysClientBeginGeneratevpnclientpackageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/generatevpnclientpackage" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-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 +} + +// Get - Gets the specified virtual network gateway by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientGetOptions contains the optional parameters for the VirtualNetworkGatewaysClient.Get +// method. +func (client *VirtualNetworkGatewaysClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientGetOptions) (VirtualNetworkGatewaysClientGetResponse, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.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, virtualNetworkGatewayName, options) + if err != nil { + return VirtualNetworkGatewaysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkGatewaysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkGatewaysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualNetworkGatewaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualNetworkGatewaysClient) getHandleResponse(resp *http.Response) (VirtualNetworkGatewaysClientGetResponse, error) { + result := VirtualNetworkGatewaysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkGateway); err != nil { + return VirtualNetworkGatewaysClientGetResponse{}, err + } + return result, nil +} + +// BeginGetAdvertisedRoutes - This operation retrieves a list of routes the virtual network gateway is advertising to the +// specified peer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - peer - The IP address of the peer. +// - options - VirtualNetworkGatewaysClientBeginGetAdvertisedRoutesOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetAdvertisedRoutes +// method. +func (client *VirtualNetworkGatewaysClient) BeginGetAdvertisedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string, options *VirtualNetworkGatewaysClientBeginGetAdvertisedRoutesOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGetAdvertisedRoutesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getAdvertisedRoutes(ctx, resourceGroupName, virtualNetworkGatewayName, peer, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGetAdvertisedRoutesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGetAdvertisedRoutesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetAdvertisedRoutes - This operation retrieves a list of routes the virtual network gateway is advertising to the specified +// peer. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) getAdvertisedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string, options *VirtualNetworkGatewaysClientBeginGetAdvertisedRoutesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGetAdvertisedRoutes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAdvertisedRoutesCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, peer, 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 +} + +// getAdvertisedRoutesCreateRequest creates the GetAdvertisedRoutes request. +func (client *VirtualNetworkGatewaysClient) getAdvertisedRoutesCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string, options *VirtualNetworkGatewaysClientBeginGetAdvertisedRoutesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getAdvertisedRoutes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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("peer", peer) + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginGetBgpPeerStatus - The GetBgpPeerStatus operation retrieves the status of all BGP peers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginGetBgpPeerStatusOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetBgpPeerStatus +// method. +func (client *VirtualNetworkGatewaysClient) BeginGetBgpPeerStatus(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetBgpPeerStatusOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGetBgpPeerStatusResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getBgpPeerStatus(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGetBgpPeerStatusResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGetBgpPeerStatusResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetBgpPeerStatus - The GetBgpPeerStatus operation retrieves the status of all BGP peers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) getBgpPeerStatus(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetBgpPeerStatusOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGetBgpPeerStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getBgpPeerStatusCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// getBgpPeerStatusCreateRequest creates the GetBgpPeerStatus request. +func (client *VirtualNetworkGatewaysClient) getBgpPeerStatusCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetBgpPeerStatusOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getBgpPeerStatus" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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() + if options != nil && options.Peer != nil { + reqQP.Set("peer", *options.Peer) + } + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginGetLearnedRoutes - This operation retrieves a list of routes the virtual network gateway has learned, including routes +// learned from BGP peers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginGetLearnedRoutesOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetLearnedRoutes +// method. +func (client *VirtualNetworkGatewaysClient) BeginGetLearnedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetLearnedRoutesOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGetLearnedRoutesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getLearnedRoutes(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGetLearnedRoutesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGetLearnedRoutesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetLearnedRoutes - This operation retrieves a list of routes the virtual network gateway has learned, including routes +// learned from BGP peers. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) getLearnedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetLearnedRoutesOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGetLearnedRoutes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getLearnedRoutesCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// getLearnedRoutesCreateRequest creates the GetLearnedRoutes request. +func (client *VirtualNetworkGatewaysClient) getLearnedRoutesCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetLearnedRoutesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getLearnedRoutes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginGetVPNProfilePackageURL - Gets pre-generated VPN profile for P2S client of the virtual network gateway in the specified +// resource group. The profile needs to be generated first using generateVpnProfile. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginGetVPNProfilePackageURLOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginGetVPNProfilePackageURL +// method. +func (client *VirtualNetworkGatewaysClient) BeginGetVPNProfilePackageURL(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVPNProfilePackageURLOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGetVPNProfilePackageURLResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getVPNProfilePackageURL(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGetVPNProfilePackageURLResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGetVPNProfilePackageURLResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetVPNProfilePackageURL - Gets pre-generated VPN profile for P2S client of the virtual network gateway in the specified +// resource group. The profile needs to be generated first using generateVpnProfile. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) getVPNProfilePackageURL(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVPNProfilePackageURLOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGetVPNProfilePackageURL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getVPNProfilePackageURLCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// getVPNProfilePackageURLCreateRequest creates the GetVPNProfilePackageURL request. +func (client *VirtualNetworkGatewaysClient) getVPNProfilePackageURLCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVPNProfilePackageURLOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getvpnprofilepackageurl" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginGetVpnclientConnectionHealth - Get VPN client connection health detail per P2S client connection of the virtual network +// gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginGetVpnclientConnectionHealthOptions contains the optional parameters for the +// VirtualNetworkGatewaysClient.BeginGetVpnclientConnectionHealth method. +func (client *VirtualNetworkGatewaysClient) BeginGetVpnclientConnectionHealth(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVpnclientConnectionHealthOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGetVpnclientConnectionHealthResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getVpnclientConnectionHealth(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGetVpnclientConnectionHealthResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGetVpnclientConnectionHealthResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetVpnclientConnectionHealth - Get VPN client connection health detail per P2S client connection of the virtual network +// gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) getVpnclientConnectionHealth(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVpnclientConnectionHealthOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGetVpnclientConnectionHealth" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getVpnclientConnectionHealthCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// getVpnclientConnectionHealthCreateRequest creates the GetVpnclientConnectionHealth request. +func (client *VirtualNetworkGatewaysClient) getVpnclientConnectionHealthCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVpnclientConnectionHealthOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getVpnClientConnectionHealth" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginGetVpnclientIPSecParameters - The Get VpnclientIpsecParameters operation retrieves information about the vpnclient +// ipsec policy for P2S client of virtual network gateway in the specified resource group through Network resource +// provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The virtual network gateway name. +// - options - VirtualNetworkGatewaysClientBeginGetVpnclientIPSecParametersOptions contains the optional parameters for the +// VirtualNetworkGatewaysClient.BeginGetVpnclientIPSecParameters method. +func (client *VirtualNetworkGatewaysClient) BeginGetVpnclientIPSecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVpnclientIPSecParametersOptions) (*runtime.Poller[VirtualNetworkGatewaysClientGetVpnclientIPSecParametersResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getVpnclientIPSecParameters(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientGetVpnclientIPSecParametersResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientGetVpnclientIPSecParametersResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetVpnclientIPSecParameters - The Get VpnclientIpsecParameters operation retrieves information about the vpnclient ipsec +// policy for P2S client of virtual network gateway in the specified resource group through Network resource +// provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) getVpnclientIPSecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVpnclientIPSecParametersOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginGetVpnclientIPSecParameters" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getVpnclientIPSecParametersCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// getVpnclientIPSecParametersCreateRequest creates the GetVpnclientIPSecParameters request. +func (client *VirtualNetworkGatewaysClient) getVpnclientIPSecParametersCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginGetVpnclientIPSecParametersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getvpnclientipsecparameters" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// NewListPager - Gets all virtual network gateways by resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualNetworkGatewaysClientListOptions contains the optional parameters for the VirtualNetworkGatewaysClient.NewListPager +// method. +func (client *VirtualNetworkGatewaysClient) NewListPager(resourceGroupName string, options *VirtualNetworkGatewaysClientListOptions) *runtime.Pager[VirtualNetworkGatewaysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkGatewaysClientListResponse]{ + More: func(page VirtualNetworkGatewaysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkGatewaysClientListResponse) (VirtualNetworkGatewaysClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkGatewaysClient.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, options) + }, nil) + if err != nil { + return VirtualNetworkGatewaysClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualNetworkGatewaysClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualNetworkGatewaysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualNetworkGatewaysClient) listHandleResponse(resp *http.Response) (VirtualNetworkGatewaysClientListResponse, error) { + result := VirtualNetworkGatewaysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkGatewayListResult); err != nil { + return VirtualNetworkGatewaysClientListResponse{}, err + } + return result, nil +} + +// NewListConnectionsPager - Gets all the connections in a virtual network gateway. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientListConnectionsOptions contains the optional parameters for the VirtualNetworkGatewaysClient.NewListConnectionsPager +// method. +func (client *VirtualNetworkGatewaysClient) NewListConnectionsPager(resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientListConnectionsOptions) *runtime.Pager[VirtualNetworkGatewaysClientListConnectionsResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkGatewaysClientListConnectionsResponse]{ + More: func(page VirtualNetworkGatewaysClientListConnectionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkGatewaysClientListConnectionsResponse) (VirtualNetworkGatewaysClientListConnectionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkGatewaysClient.NewListConnectionsPager") + 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.listConnectionsCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, options) + }, nil) + if err != nil { + return VirtualNetworkGatewaysClientListConnectionsResponse{}, err + } + return client.listConnectionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listConnectionsCreateRequest creates the ListConnections request. +func (client *VirtualNetworkGatewaysClient) listConnectionsCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientListConnectionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/connections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listConnectionsHandleResponse handles the ListConnections response. +func (client *VirtualNetworkGatewaysClient) listConnectionsHandleResponse(resp *http.Response) (VirtualNetworkGatewaysClientListConnectionsResponse, error) { + result := VirtualNetworkGatewaysClientListConnectionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkGatewayListConnectionsResult); err != nil { + return VirtualNetworkGatewaysClientListConnectionsResponse{}, err + } + return result, nil +} + +// BeginReset - Resets the primary of the virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginResetOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginReset +// method. +func (client *VirtualNetworkGatewaysClient) BeginReset(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginResetOptions) (*runtime.Poller[VirtualNetworkGatewaysClientResetResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reset(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientResetResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientResetResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reset - Resets the primary of the virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) reset(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginResetOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginReset" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// resetCreateRequest creates the Reset request. +func (client *VirtualNetworkGatewaysClient) resetCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginResetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/reset" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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() + if options != nil && options.GatewayVip != nil { + reqQP.Set("gatewayVip", *options.GatewayVip) + } + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginResetVPNClientSharedKey - Resets the VPN client shared key of the virtual network gateway in the specified resource +// group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginResetVPNClientSharedKeyOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginResetVPNClientSharedKey +// method. +func (client *VirtualNetworkGatewaysClient) BeginResetVPNClientSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginResetVPNClientSharedKeyOptions) (*runtime.Poller[VirtualNetworkGatewaysClientResetVPNClientSharedKeyResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.resetVPNClientSharedKey(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientResetVPNClientSharedKeyResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientResetVPNClientSharedKeyResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ResetVPNClientSharedKey - Resets the VPN client shared key of the virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) resetVPNClientSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginResetVPNClientSharedKeyOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginResetVPNClientSharedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetVPNClientSharedKeyCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// resetVPNClientSharedKeyCreateRequest creates the ResetVPNClientSharedKey request. +func (client *VirtualNetworkGatewaysClient) resetVPNClientSharedKeyCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginResetVPNClientSharedKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/resetvpnclientsharedkey" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginSetVpnclientIPSecParameters - The Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy for P2S client +// of virtual network gateway in the specified resource group through Network resource provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - vpnclientIPSecParams - Parameters supplied to the Begin Set vpnclient ipsec parameters of Virtual Network Gateway P2S client +// operation through Network resource provider. +// - options - VirtualNetworkGatewaysClientBeginSetVpnclientIPSecParametersOptions contains the optional parameters for the +// VirtualNetworkGatewaysClient.BeginSetVpnclientIPSecParameters method. +func (client *VirtualNetworkGatewaysClient) BeginSetVpnclientIPSecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, vpnclientIPSecParams VPNClientIPsecParameters, options *VirtualNetworkGatewaysClientBeginSetVpnclientIPSecParametersOptions) (*runtime.Poller[VirtualNetworkGatewaysClientSetVpnclientIPSecParametersResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.setVpnclientIPSecParameters(ctx, resourceGroupName, virtualNetworkGatewayName, vpnclientIPSecParams, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientSetVpnclientIPSecParametersResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientSetVpnclientIPSecParametersResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// SetVpnclientIPSecParameters - The Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy for P2S client +// of virtual network gateway in the specified resource group through Network resource provider. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) setVpnclientIPSecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, vpnclientIPSecParams VPNClientIPsecParameters, options *VirtualNetworkGatewaysClientBeginSetVpnclientIPSecParametersOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginSetVpnclientIPSecParameters" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setVpnclientIPSecParametersCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, vpnclientIPSecParams, 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 +} + +// setVpnclientIPSecParametersCreateRequest creates the SetVpnclientIPSecParameters request. +func (client *VirtualNetworkGatewaysClient) setVpnclientIPSecParametersCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, vpnclientIPSecParams VPNClientIPsecParameters, options *VirtualNetworkGatewaysClientBeginSetVpnclientIPSecParametersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/setvpnclientipsecparameters" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnclientIPSecParams); err != nil { + return nil, err + } + return req, nil +} + +// BeginStartPacketCapture - Starts packet capture on virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientBeginStartPacketCaptureOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginStartPacketCapture +// method. +func (client *VirtualNetworkGatewaysClient) BeginStartPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginStartPacketCaptureOptions) (*runtime.Poller[VirtualNetworkGatewaysClientStartPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.startPacketCapture(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientStartPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientStartPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StartPacketCapture - Starts packet capture on virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) startPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginStartPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginStartPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startPacketCaptureCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// startPacketCaptureCreateRequest creates the StartPacketCapture request. +func (client *VirtualNetworkGatewaysClient) startPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientBeginStartPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/startPacketCapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-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 +} + +// BeginStopPacketCapture - Stops packet capture on virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - parameters - Virtual network gateway packet capture parameters supplied to stop packet capture on gateway. +// - options - VirtualNetworkGatewaysClientBeginStopPacketCaptureOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginStopPacketCapture +// method. +func (client *VirtualNetworkGatewaysClient) BeginStopPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNPacketCaptureStopParameters, options *VirtualNetworkGatewaysClientBeginStopPacketCaptureOptions) (*runtime.Poller[VirtualNetworkGatewaysClientStopPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stopPacketCapture(ctx, resourceGroupName, virtualNetworkGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientStopPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientStopPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StopPacketCapture - Stops packet capture on virtual network gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) stopPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNPacketCaptureStopParameters, options *VirtualNetworkGatewaysClientBeginStopPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginStopPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopPacketCaptureCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// stopPacketCaptureCreateRequest creates the StopPacketCapture request. +func (client *VirtualNetworkGatewaysClient) stopPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VPNPacketCaptureStopParameters, options *VirtualNetworkGatewaysClientBeginStopPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/stopPacketCapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-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 +} + +// SupportedVPNDevices - Gets a xml format representation for supported vpn devices. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - options - VirtualNetworkGatewaysClientSupportedVPNDevicesOptions contains the optional parameters for the VirtualNetworkGatewaysClient.SupportedVPNDevices +// method. +func (client *VirtualNetworkGatewaysClient) SupportedVPNDevices(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientSupportedVPNDevicesOptions) (VirtualNetworkGatewaysClientSupportedVPNDevicesResponse, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.SupportedVPNDevices" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.supportedVPNDevicesCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, options) + if err != nil { + return VirtualNetworkGatewaysClientSupportedVPNDevicesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkGatewaysClientSupportedVPNDevicesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkGatewaysClientSupportedVPNDevicesResponse{}, err + } + resp, err := client.supportedVPNDevicesHandleResponse(httpResp) + return resp, err +} + +// supportedVPNDevicesCreateRequest creates the SupportedVPNDevices request. +func (client *VirtualNetworkGatewaysClient) supportedVPNDevicesCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, options *VirtualNetworkGatewaysClientSupportedVPNDevicesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/supportedvpndevices" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// supportedVPNDevicesHandleResponse handles the SupportedVPNDevices response. +func (client *VirtualNetworkGatewaysClient) supportedVPNDevicesHandleResponse(resp *http.Response) (VirtualNetworkGatewaysClientSupportedVPNDevicesResponse, error) { + result := VirtualNetworkGatewaysClientSupportedVPNDevicesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return VirtualNetworkGatewaysClientSupportedVPNDevicesResponse{}, err + } + return result, nil +} + +// BeginUpdateTags - Updates a virtual network gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayName - The name of the virtual network gateway. +// - parameters - Parameters supplied to update virtual network gateway tags. +// - options - VirtualNetworkGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the VirtualNetworkGatewaysClient.BeginUpdateTags +// method. +func (client *VirtualNetworkGatewaysClient) BeginUpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters TagsObject, options *VirtualNetworkGatewaysClientBeginUpdateTagsOptions) (*runtime.Poller[VirtualNetworkGatewaysClientUpdateTagsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateTags(ctx, resourceGroupName, virtualNetworkGatewayName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkGatewaysClientUpdateTagsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkGatewaysClientUpdateTagsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateTags - Updates a virtual network gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkGatewaysClient) updateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters TagsObject, options *VirtualNetworkGatewaysClientBeginUpdateTagsOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.BeginUpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayName, 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 +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VirtualNetworkGatewaysClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters TagsObject, options *VirtualNetworkGatewaysClientBeginUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayName == "" { + return nil, errors.New("parameter virtualNetworkGatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayName}", url.PathEscape(virtualNetworkGatewayName)) + 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-05-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 +} + +// VPNDeviceConfigurationScript - Gets a xml format representation for vpn device configuration script. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkGatewayConnectionName - The name of the virtual network gateway connection for which the configuration script +// is generated. +// - parameters - Parameters supplied to the generate vpn device script operation. +// - options - VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptOptions contains the optional parameters for the VirtualNetworkGatewaysClient.VPNDeviceConfigurationScript +// method. +func (client *VirtualNetworkGatewaysClient) VPNDeviceConfigurationScript(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VPNDeviceScriptParameters, options *VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptOptions) (VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse, error) { + var err error + const operationName = "VirtualNetworkGatewaysClient.VPNDeviceConfigurationScript" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.vpnDeviceConfigurationScriptCreateRequest(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters, options) + if err != nil { + return VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse{}, err + } + resp, err := client.vpnDeviceConfigurationScriptHandleResponse(httpResp) + return resp, err +} + +// vpnDeviceConfigurationScriptCreateRequest creates the VPNDeviceConfigurationScript request. +func (client *VirtualNetworkGatewaysClient) vpnDeviceConfigurationScriptCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VPNDeviceScriptParameters, options *VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/vpndeviceconfigurationscript" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkGatewayConnectionName == "" { + return nil, errors.New("parameter virtualNetworkGatewayConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkGatewayConnectionName}", url.PathEscape(virtualNetworkGatewayConnectionName)) + 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-05-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 +} + +// vpnDeviceConfigurationScriptHandleResponse handles the VPNDeviceConfigurationScript response. +func (client *VirtualNetworkGatewaysClient) vpnDeviceConfigurationScriptHandleResponse(resp *http.Response) (VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse, error) { + result := VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return VirtualNetworkGatewaysClientVPNDeviceConfigurationScriptResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkpeerings_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkpeerings_client.go new file mode 100644 index 000000000..eaa5d8314 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworkpeerings_client.go @@ -0,0 +1,351 @@ +//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 armnetwork + +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" +) + +// VirtualNetworkPeeringsClient contains the methods for the VirtualNetworkPeerings group. +// Don't use this type directly, use NewVirtualNetworkPeeringsClient() instead. +type VirtualNetworkPeeringsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualNetworkPeeringsClient creates a new instance of VirtualNetworkPeeringsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualNetworkPeeringsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualNetworkPeeringsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualNetworkPeeringsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a peering in the specified virtual network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - virtualNetworkPeeringName - The name of the peering. +// - virtualNetworkPeeringParameters - Parameters supplied to the create or update virtual network peering operation. +// - options - VirtualNetworkPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkPeeringsClient.BeginCreateOrUpdate +// method. +func (client *VirtualNetworkPeeringsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, options *VirtualNetworkPeeringsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualNetworkPeeringsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkPeeringsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkPeeringsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a peering in the specified virtual network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkPeeringsClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, options *VirtualNetworkPeeringsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkPeeringsClient.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, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, 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 *VirtualNetworkPeeringsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, options *VirtualNetworkPeeringsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if virtualNetworkPeeringName == "" { + return nil, errors.New("parameter virtualNetworkPeeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkPeeringName}", url.PathEscape(virtualNetworkPeeringName)) + 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.SyncRemoteAddressSpace != nil { + reqQP.Set("syncRemoteAddressSpace", string(*options.SyncRemoteAddressSpace)) + } + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, virtualNetworkPeeringParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified virtual network peering. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - virtualNetworkPeeringName - The name of the virtual network peering. +// - options - VirtualNetworkPeeringsClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkPeeringsClient.BeginDelete +// method. +func (client *VirtualNetworkPeeringsClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, options *VirtualNetworkPeeringsClientBeginDeleteOptions) (*runtime.Poller[VirtualNetworkPeeringsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkPeeringsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkPeeringsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified virtual network peering. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkPeeringsClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, options *VirtualNetworkPeeringsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkPeeringsClient.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, virtualNetworkName, virtualNetworkPeeringName, 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 *VirtualNetworkPeeringsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, options *VirtualNetworkPeeringsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if virtualNetworkPeeringName == "" { + return nil, errors.New("parameter virtualNetworkPeeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkPeeringName}", url.PathEscape(virtualNetworkPeeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified virtual network peering. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - virtualNetworkPeeringName - The name of the virtual network peering. +// - options - VirtualNetworkPeeringsClientGetOptions contains the optional parameters for the VirtualNetworkPeeringsClient.Get +// method. +func (client *VirtualNetworkPeeringsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, options *VirtualNetworkPeeringsClientGetOptions) (VirtualNetworkPeeringsClientGetResponse, error) { + var err error + const operationName = "VirtualNetworkPeeringsClient.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, virtualNetworkName, virtualNetworkPeeringName, options) + if err != nil { + return VirtualNetworkPeeringsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkPeeringsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkPeeringsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualNetworkPeeringsClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, options *VirtualNetworkPeeringsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + if virtualNetworkPeeringName == "" { + return nil, errors.New("parameter virtualNetworkPeeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkPeeringName}", url.PathEscape(virtualNetworkPeeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualNetworkPeeringsClient) getHandleResponse(resp *http.Response) (VirtualNetworkPeeringsClientGetResponse, error) { + result := VirtualNetworkPeeringsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkPeering); err != nil { + return VirtualNetworkPeeringsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all virtual network peerings in a virtual network. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - options - VirtualNetworkPeeringsClientListOptions contains the optional parameters for the VirtualNetworkPeeringsClient.NewListPager +// method. +func (client *VirtualNetworkPeeringsClient) NewListPager(resourceGroupName string, virtualNetworkName string, options *VirtualNetworkPeeringsClientListOptions) *runtime.Pager[VirtualNetworkPeeringsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkPeeringsClientListResponse]{ + More: func(page VirtualNetworkPeeringsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkPeeringsClientListResponse) (VirtualNetworkPeeringsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkPeeringsClient.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, virtualNetworkName, options) + }, nil) + if err != nil { + return VirtualNetworkPeeringsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualNetworkPeeringsClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworkPeeringsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualNetworkPeeringsClient) listHandleResponse(resp *http.Response) (VirtualNetworkPeeringsClientListResponse, error) { + result := VirtualNetworkPeeringsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkPeeringListResult); err != nil { + return VirtualNetworkPeeringsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworks_client.go new file mode 100644 index 000000000..6feedb751 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworks_client.go @@ -0,0 +1,695 @@ +//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 armnetwork + +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" +) + +// VirtualNetworksClient contains the methods for the VirtualNetworks group. +// Don't use this type directly, use NewVirtualNetworksClient() instead. +type VirtualNetworksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualNetworksClient creates a new instance of VirtualNetworksClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualNetworksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualNetworksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualNetworksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckIPAddressAvailability - Checks whether a private IP address is available for use. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - ipAddress - The private IP address to be verified. +// - options - VirtualNetworksClientCheckIPAddressAvailabilityOptions contains the optional parameters for the VirtualNetworksClient.CheckIPAddressAvailability +// method. +func (client *VirtualNetworksClient) CheckIPAddressAvailability(ctx context.Context, resourceGroupName string, virtualNetworkName string, ipAddress string, options *VirtualNetworksClientCheckIPAddressAvailabilityOptions) (VirtualNetworksClientCheckIPAddressAvailabilityResponse, error) { + var err error + const operationName = "VirtualNetworksClient.CheckIPAddressAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkIPAddressAvailabilityCreateRequest(ctx, resourceGroupName, virtualNetworkName, ipAddress, options) + if err != nil { + return VirtualNetworksClientCheckIPAddressAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworksClientCheckIPAddressAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworksClientCheckIPAddressAvailabilityResponse{}, err + } + resp, err := client.checkIPAddressAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkIPAddressAvailabilityCreateRequest creates the CheckIPAddressAvailability request. +func (client *VirtualNetworksClient) checkIPAddressAvailabilityCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, ipAddress string, options *VirtualNetworksClientCheckIPAddressAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/CheckIPAddressAvailability" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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("ipAddress", ipAddress) + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// checkIPAddressAvailabilityHandleResponse handles the CheckIPAddressAvailability response. +func (client *VirtualNetworksClient) checkIPAddressAvailabilityHandleResponse(resp *http.Response) (VirtualNetworksClientCheckIPAddressAvailabilityResponse, error) { + result := VirtualNetworksClientCheckIPAddressAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IPAddressAvailabilityResult); err != nil { + return VirtualNetworksClientCheckIPAddressAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreateOrUpdate - Creates or updates a virtual network in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - parameters - Parameters supplied to the create or update virtual network operation. +// - options - VirtualNetworksClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworksClient.BeginCreateOrUpdate +// method. +func (client *VirtualNetworksClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, options *VirtualNetworksClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualNetworksClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualNetworkName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworksClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworksClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a virtual network in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworksClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, options *VirtualNetworksClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworksClient.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, virtualNetworkName, 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 *VirtualNetworksClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, options *VirtualNetworksClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-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 virtual network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - options - VirtualNetworksClientBeginDeleteOptions contains the optional parameters for the VirtualNetworksClient.BeginDelete +// method. +func (client *VirtualNetworksClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientBeginDeleteOptions) (*runtime.Poller[VirtualNetworksClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualNetworkName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworksClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworksClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified virtual network. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworksClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworksClient.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, virtualNetworkName, 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 *VirtualNetworksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified virtual network by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - options - VirtualNetworksClientGetOptions contains the optional parameters for the VirtualNetworksClient.Get method. +func (client *VirtualNetworksClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientGetOptions) (VirtualNetworksClientGetResponse, error) { + var err error + const operationName = "VirtualNetworksClient.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, virtualNetworkName, options) + if err != nil { + return VirtualNetworksClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworksClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworksClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualNetworksClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *VirtualNetworksClient) getHandleResponse(resp *http.Response) (VirtualNetworksClientGetResponse, error) { + result := VirtualNetworksClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetwork); err != nil { + return VirtualNetworksClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all virtual networks in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualNetworksClientListOptions contains the optional parameters for the VirtualNetworksClient.NewListPager +// method. +func (client *VirtualNetworksClient) NewListPager(resourceGroupName string, options *VirtualNetworksClientListOptions) *runtime.Pager[VirtualNetworksClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworksClientListResponse]{ + More: func(page VirtualNetworksClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworksClientListResponse) (VirtualNetworksClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworksClient.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, options) + }, nil) + if err != nil { + return VirtualNetworksClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualNetworksClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualNetworksClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualNetworksClient) listHandleResponse(resp *http.Response) (VirtualNetworksClientListResponse, error) { + result := VirtualNetworksClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkListResult); err != nil { + return VirtualNetworksClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all virtual networks in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VirtualNetworksClientListAllOptions contains the optional parameters for the VirtualNetworksClient.NewListAllPager +// method. +func (client *VirtualNetworksClient) NewListAllPager(options *VirtualNetworksClientListAllOptions) *runtime.Pager[VirtualNetworksClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworksClientListAllResponse]{ + More: func(page VirtualNetworksClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworksClientListAllResponse) (VirtualNetworksClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworksClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return VirtualNetworksClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *VirtualNetworksClient) listAllCreateRequest(ctx context.Context, options *VirtualNetworksClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *VirtualNetworksClient) listAllHandleResponse(resp *http.Response) (VirtualNetworksClientListAllResponse, error) { + result := VirtualNetworksClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkListResult); err != nil { + return VirtualNetworksClientListAllResponse{}, err + } + return result, nil +} + +// BeginListDdosProtectionStatus - Gets the Ddos Protection Status of all IP Addresses under the Virtual Network +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - options - VirtualNetworksClientBeginListDdosProtectionStatusOptions contains the optional parameters for the VirtualNetworksClient.BeginListDdosProtectionStatus +// method. +func (client *VirtualNetworksClient) BeginListDdosProtectionStatus(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientBeginListDdosProtectionStatusOptions) (*runtime.Poller[*runtime.Pager[VirtualNetworksClientListDdosProtectionStatusResponse]], error) { + pager := runtime.NewPager(runtime.PagingHandler[VirtualNetworksClientListDdosProtectionStatusResponse]{ + More: func(page VirtualNetworksClientListDdosProtectionStatusResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworksClientListDdosProtectionStatusResponse) (VirtualNetworksClientListDdosProtectionStatusResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworksClient.BeginListDdosProtectionStatus") + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), *page.NextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listDdosProtectionStatusCreateRequest(ctx, resourceGroupName, virtualNetworkName, options) + }, nil) + if err != nil { + return VirtualNetworksClientListDdosProtectionStatusResponse{}, err + } + return client.listDdosProtectionStatusHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) + if options == nil || options.ResumeToken == "" { + resp, err := client.listDdosProtectionStatus(ctx, resourceGroupName, virtualNetworkName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[*runtime.Pager[VirtualNetworksClientListDdosProtectionStatusResponse]]{ + FinalStateVia: runtime.FinalStateViaLocation, + Response: &pager, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[*runtime.Pager[VirtualNetworksClientListDdosProtectionStatusResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + } +} + +// ListDdosProtectionStatus - Gets the Ddos Protection Status of all IP Addresses under the Virtual Network +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworksClient) listDdosProtectionStatus(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientBeginListDdosProtectionStatusOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworksClient.BeginListDdosProtectionStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listDdosProtectionStatusCreateRequest(ctx, resourceGroupName, virtualNetworkName, 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 +} + +// listDdosProtectionStatusCreateRequest creates the ListDdosProtectionStatus request. +func (client *VirtualNetworksClient) listDdosProtectionStatusCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientBeginListDdosProtectionStatusOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/ddosProtectionStatus" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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() + if options != nil && options.Top != nil { + reqQP.Set("top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("skipToken", *options.SkipToken) + } + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listDdosProtectionStatusHandleResponse handles the ListDdosProtectionStatus response. +func (client *VirtualNetworksClient) listDdosProtectionStatusHandleResponse(resp *http.Response) (VirtualNetworksClientListDdosProtectionStatusResponse, error) { + result := VirtualNetworksClientListDdosProtectionStatusResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkDdosProtectionStatusResult); err != nil { + return VirtualNetworksClientListDdosProtectionStatusResponse{}, err + } + return result, nil +} + +// NewListUsagePager - Lists usage stats. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - options - VirtualNetworksClientListUsageOptions contains the optional parameters for the VirtualNetworksClient.NewListUsagePager +// method. +func (client *VirtualNetworksClient) NewListUsagePager(resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientListUsageOptions) *runtime.Pager[VirtualNetworksClientListUsageResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworksClientListUsageResponse]{ + More: func(page VirtualNetworksClientListUsageResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworksClientListUsageResponse) (VirtualNetworksClientListUsageResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworksClient.NewListUsagePager") + 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.listUsageCreateRequest(ctx, resourceGroupName, virtualNetworkName, options) + }, nil) + if err != nil { + return VirtualNetworksClientListUsageResponse{}, err + } + return client.listUsageHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listUsageCreateRequest creates the ListUsage request. +func (client *VirtualNetworksClient) listUsageCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, options *VirtualNetworksClientListUsageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/usages" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listUsageHandleResponse handles the ListUsage response. +func (client *VirtualNetworksClient) listUsageHandleResponse(resp *http.Response) (VirtualNetworksClientListUsageResponse, error) { + result := VirtualNetworksClientListUsageResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkListUsageResult); err != nil { + return VirtualNetworksClientListUsageResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a virtual network tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualNetworkName - The name of the virtual network. +// - parameters - Parameters supplied to update virtual network tags. +// - options - VirtualNetworksClientUpdateTagsOptions contains the optional parameters for the VirtualNetworksClient.UpdateTags +// method. +func (client *VirtualNetworksClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters TagsObject, options *VirtualNetworksClientUpdateTagsOptions) (VirtualNetworksClientUpdateTagsResponse, error) { + var err error + const operationName = "VirtualNetworksClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, virtualNetworkName, parameters, options) + if err != nil { + return VirtualNetworksClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworksClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworksClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VirtualNetworksClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters TagsObject, options *VirtualNetworksClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualNetworkName == "" { + return nil, errors.New("parameter virtualNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualNetworkName}", url.PathEscape(virtualNetworkName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *VirtualNetworksClient) updateTagsHandleResponse(resp *http.Response) (VirtualNetworksClientUpdateTagsResponse, error) { + result := VirtualNetworksClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetwork); err != nil { + return VirtualNetworksClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworktaps_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworktaps_client.go new file mode 100644 index 000000000..3ab3dd130 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualnetworktaps_client.go @@ -0,0 +1,451 @@ +//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 armnetwork + +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" +) + +// VirtualNetworkTapsClient contains the methods for the VirtualNetworkTaps group. +// Don't use this type directly, use NewVirtualNetworkTapsClient() instead. +type VirtualNetworkTapsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualNetworkTapsClient creates a new instance of VirtualNetworkTapsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualNetworkTapsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualNetworkTapsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualNetworkTapsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a Virtual Network Tap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - tapName - The name of the virtual network tap. +// - parameters - Parameters supplied to the create or update virtual network tap operation. +// - options - VirtualNetworkTapsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkTapsClient.BeginCreateOrUpdate +// method. +func (client *VirtualNetworkTapsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap, options *VirtualNetworkTapsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualNetworkTapsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, tapName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkTapsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkTapsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a Virtual Network Tap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkTapsClient) createOrUpdate(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap, options *VirtualNetworkTapsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkTapsClient.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, tapName, 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 *VirtualNetworkTapsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap, options *VirtualNetworkTapsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if tapName == "" { + return nil, errors.New("parameter tapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tapName}", url.PathEscape(tapName)) + 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-05-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 virtual network tap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - tapName - The name of the virtual network tap. +// - options - VirtualNetworkTapsClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkTapsClient.BeginDelete +// method. +func (client *VirtualNetworkTapsClient) BeginDelete(ctx context.Context, resourceGroupName string, tapName string, options *VirtualNetworkTapsClientBeginDeleteOptions) (*runtime.Poller[VirtualNetworkTapsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, tapName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkTapsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkTapsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified virtual network tap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualNetworkTapsClient) deleteOperation(ctx context.Context, resourceGroupName string, tapName string, options *VirtualNetworkTapsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkTapsClient.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, tapName, 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 *VirtualNetworkTapsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, tapName string, options *VirtualNetworkTapsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if tapName == "" { + return nil, errors.New("parameter tapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tapName}", url.PathEscape(tapName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets information about the specified virtual network tap. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - tapName - The name of virtual network tap. +// - options - VirtualNetworkTapsClientGetOptions contains the optional parameters for the VirtualNetworkTapsClient.Get method. +func (client *VirtualNetworkTapsClient) Get(ctx context.Context, resourceGroupName string, tapName string, options *VirtualNetworkTapsClientGetOptions) (VirtualNetworkTapsClientGetResponse, error) { + var err error + const operationName = "VirtualNetworkTapsClient.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, tapName, options) + if err != nil { + return VirtualNetworkTapsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkTapsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkTapsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualNetworkTapsClient) getCreateRequest(ctx context.Context, resourceGroupName string, tapName string, options *VirtualNetworkTapsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if tapName == "" { + return nil, errors.New("parameter tapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tapName}", url.PathEscape(tapName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualNetworkTapsClient) getHandleResponse(resp *http.Response) (VirtualNetworkTapsClientGetResponse, error) { + result := VirtualNetworkTapsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkTap); err != nil { + return VirtualNetworkTapsClientGetResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the VirtualNetworkTaps in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VirtualNetworkTapsClientListAllOptions contains the optional parameters for the VirtualNetworkTapsClient.NewListAllPager +// method. +func (client *VirtualNetworkTapsClient) NewListAllPager(options *VirtualNetworkTapsClientListAllOptions) *runtime.Pager[VirtualNetworkTapsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkTapsClientListAllResponse]{ + More: func(page VirtualNetworkTapsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkTapsClientListAllResponse) (VirtualNetworkTapsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkTapsClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return VirtualNetworkTapsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *VirtualNetworkTapsClient) listAllCreateRequest(ctx context.Context, options *VirtualNetworkTapsClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworkTaps" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *VirtualNetworkTapsClient) listAllHandleResponse(resp *http.Response) (VirtualNetworkTapsClientListAllResponse, error) { + result := VirtualNetworkTapsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkTapListResult); err != nil { + return VirtualNetworkTapsClientListAllResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets all the VirtualNetworkTaps in a subscription. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualNetworkTapsClientListByResourceGroupOptions contains the optional parameters for the VirtualNetworkTapsClient.NewListByResourceGroupPager +// method. +func (client *VirtualNetworkTapsClient) NewListByResourceGroupPager(resourceGroupName string, options *VirtualNetworkTapsClientListByResourceGroupOptions) *runtime.Pager[VirtualNetworkTapsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkTapsClientListByResourceGroupResponse]{ + More: func(page VirtualNetworkTapsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkTapsClientListByResourceGroupResponse) (VirtualNetworkTapsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkTapsClient.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 VirtualNetworkTapsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VirtualNetworkTapsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualNetworkTapsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VirtualNetworkTapsClient) listByResourceGroupHandleResponse(resp *http.Response) (VirtualNetworkTapsClientListByResourceGroupResponse, error) { + result := VirtualNetworkTapsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkTapListResult); err != nil { + return VirtualNetworkTapsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates an VirtualNetworkTap tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - tapName - The name of the tap. +// - tapParameters - Parameters supplied to update VirtualNetworkTap tags. +// - options - VirtualNetworkTapsClientUpdateTagsOptions contains the optional parameters for the VirtualNetworkTapsClient.UpdateTags +// method. +func (client *VirtualNetworkTapsClient) UpdateTags(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject, options *VirtualNetworkTapsClientUpdateTagsOptions) (VirtualNetworkTapsClientUpdateTagsResponse, error) { + var err error + const operationName = "VirtualNetworkTapsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, tapName, tapParameters, options) + if err != nil { + return VirtualNetworkTapsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkTapsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkTapsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VirtualNetworkTapsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject, options *VirtualNetworkTapsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if tapName == "" { + return nil, errors.New("parameter tapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tapName}", url.PathEscape(tapName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tapParameters); err != nil { + return nil, err + } + return req, nil +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *VirtualNetworkTapsClient) updateTagsHandleResponse(resp *http.Response) (VirtualNetworkTapsClientUpdateTagsResponse, error) { + result := VirtualNetworkTapsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkTap); err != nil { + return VirtualNetworkTapsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualrouterpeerings_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualrouterpeerings_client.go new file mode 100644 index 000000000..984e683b7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualrouterpeerings_client.go @@ -0,0 +1,348 @@ +//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 armnetwork + +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" +) + +// VirtualRouterPeeringsClient contains the methods for the VirtualRouterPeerings group. +// Don't use this type directly, use NewVirtualRouterPeeringsClient() instead. +type VirtualRouterPeeringsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualRouterPeeringsClient creates a new instance of VirtualRouterPeeringsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualRouterPeeringsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualRouterPeeringsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualRouterPeeringsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Virtual Router Peering. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualRouterName - The name of the Virtual Router. +// - peeringName - The name of the Virtual Router Peering. +// - parameters - Parameters supplied to the create or update Virtual Router Peering operation. +// - options - VirtualRouterPeeringsClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualRouterPeeringsClient.BeginCreateOrUpdate +// method. +func (client *VirtualRouterPeeringsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, parameters VirtualRouterPeering, options *VirtualRouterPeeringsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualRouterPeeringsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualRouterName, peeringName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualRouterPeeringsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualRouterPeeringsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Virtual Router Peering. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualRouterPeeringsClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, parameters VirtualRouterPeering, options *VirtualRouterPeeringsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualRouterPeeringsClient.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, virtualRouterName, peeringName, 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 *VirtualRouterPeeringsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, parameters VirtualRouterPeering, options *VirtualRouterPeeringsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualRouterName == "" { + return nil, errors.New("parameter virtualRouterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualRouterName}", url.PathEscape(virtualRouterName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-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 peering from a Virtual Router. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualRouterName - The name of the Virtual Router. +// - peeringName - The name of the peering. +// - options - VirtualRouterPeeringsClientBeginDeleteOptions contains the optional parameters for the VirtualRouterPeeringsClient.BeginDelete +// method. +func (client *VirtualRouterPeeringsClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, options *VirtualRouterPeeringsClientBeginDeleteOptions) (*runtime.Poller[VirtualRouterPeeringsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualRouterName, peeringName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualRouterPeeringsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualRouterPeeringsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified peering from a Virtual Router. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualRouterPeeringsClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, options *VirtualRouterPeeringsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualRouterPeeringsClient.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, virtualRouterName, peeringName, 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 *VirtualRouterPeeringsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, options *VirtualRouterPeeringsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualRouterName == "" { + return nil, errors.New("parameter virtualRouterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualRouterName}", url.PathEscape(virtualRouterName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Virtual Router Peering. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualRouterName - The name of the Virtual Router. +// - peeringName - The name of the Virtual Router Peering. +// - options - VirtualRouterPeeringsClientGetOptions contains the optional parameters for the VirtualRouterPeeringsClient.Get +// method. +func (client *VirtualRouterPeeringsClient) Get(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, options *VirtualRouterPeeringsClientGetOptions) (VirtualRouterPeeringsClientGetResponse, error) { + var err error + const operationName = "VirtualRouterPeeringsClient.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, virtualRouterName, peeringName, options) + if err != nil { + return VirtualRouterPeeringsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualRouterPeeringsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualRouterPeeringsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualRouterPeeringsClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, options *VirtualRouterPeeringsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualRouterName == "" { + return nil, errors.New("parameter virtualRouterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualRouterName}", url.PathEscape(virtualRouterName)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualRouterPeeringsClient) getHandleResponse(resp *http.Response) (VirtualRouterPeeringsClientGetResponse, error) { + result := VirtualRouterPeeringsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualRouterPeering); err != nil { + return VirtualRouterPeeringsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all Virtual Router Peerings in a Virtual Router resource. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualRouterName - The name of the Virtual Router. +// - options - VirtualRouterPeeringsClientListOptions contains the optional parameters for the VirtualRouterPeeringsClient.NewListPager +// method. +func (client *VirtualRouterPeeringsClient) NewListPager(resourceGroupName string, virtualRouterName string, options *VirtualRouterPeeringsClientListOptions) *runtime.Pager[VirtualRouterPeeringsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualRouterPeeringsClientListResponse]{ + More: func(page VirtualRouterPeeringsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualRouterPeeringsClientListResponse) (VirtualRouterPeeringsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualRouterPeeringsClient.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, virtualRouterName, options) + }, nil) + if err != nil { + return VirtualRouterPeeringsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualRouterPeeringsClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualRouterName string, options *VirtualRouterPeeringsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualRouterName == "" { + return nil, errors.New("parameter virtualRouterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualRouterName}", url.PathEscape(virtualRouterName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualRouterPeeringsClient) listHandleResponse(resp *http.Response) (VirtualRouterPeeringsClientListResponse, error) { + result := VirtualRouterPeeringsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualRouterPeeringListResult); err != nil { + return VirtualRouterPeeringsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualrouters_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualrouters_client.go new file mode 100644 index 000000000..8b803a5bf --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualrouters_client.go @@ -0,0 +1,384 @@ +//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 armnetwork + +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" +) + +// VirtualRoutersClient contains the methods for the VirtualRouters group. +// Don't use this type directly, use NewVirtualRoutersClient() instead. +type VirtualRoutersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualRoutersClient creates a new instance of VirtualRoutersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualRoutersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualRoutersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualRoutersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates the specified Virtual Router. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualRouterName - The name of the Virtual Router. +// - parameters - Parameters supplied to the create or update Virtual Router. +// - options - VirtualRoutersClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualRoutersClient.BeginCreateOrUpdate +// method. +func (client *VirtualRoutersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualRouterName string, parameters VirtualRouter, options *VirtualRoutersClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualRoutersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualRouterName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualRoutersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualRoutersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates the specified Virtual Router. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualRoutersClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualRouterName string, parameters VirtualRouter, options *VirtualRoutersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualRoutersClient.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, virtualRouterName, 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 *VirtualRoutersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualRouterName string, parameters VirtualRouter, options *VirtualRoutersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualRouterName == "" { + return nil, errors.New("parameter virtualRouterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualRouterName}", url.PathEscape(virtualRouterName)) + 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-05-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 Virtual Router. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualRouterName - The name of the Virtual Router. +// - options - VirtualRoutersClientBeginDeleteOptions contains the optional parameters for the VirtualRoutersClient.BeginDelete +// method. +func (client *VirtualRoutersClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualRouterName string, options *VirtualRoutersClientBeginDeleteOptions) (*runtime.Poller[VirtualRoutersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualRouterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualRoutersClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualRoutersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Virtual Router. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualRoutersClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualRouterName string, options *VirtualRoutersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualRoutersClient.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, virtualRouterName, 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 *VirtualRoutersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualRouterName string, options *VirtualRoutersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualRouterName == "" { + return nil, errors.New("parameter virtualRouterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualRouterName}", url.PathEscape(virtualRouterName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Virtual Router. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - virtualRouterName - The name of the Virtual Router. +// - options - VirtualRoutersClientGetOptions contains the optional parameters for the VirtualRoutersClient.Get method. +func (client *VirtualRoutersClient) Get(ctx context.Context, resourceGroupName string, virtualRouterName string, options *VirtualRoutersClientGetOptions) (VirtualRoutersClientGetResponse, error) { + var err error + const operationName = "VirtualRoutersClient.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, virtualRouterName, options) + if err != nil { + return VirtualRoutersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualRoutersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualRoutersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualRoutersClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualRouterName string, options *VirtualRoutersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualRouterName == "" { + return nil, errors.New("parameter virtualRouterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualRouterName}", url.PathEscape(virtualRouterName)) + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *VirtualRoutersClient) getHandleResponse(resp *http.Response) (VirtualRoutersClientGetResponse, error) { + result := VirtualRoutersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualRouter); err != nil { + return VirtualRoutersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the Virtual Routers in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VirtualRoutersClientListOptions contains the optional parameters for the VirtualRoutersClient.NewListPager method. +func (client *VirtualRoutersClient) NewListPager(options *VirtualRoutersClientListOptions) *runtime.Pager[VirtualRoutersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualRoutersClientListResponse]{ + More: func(page VirtualRoutersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualRoutersClientListResponse) (VirtualRoutersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualRoutersClient.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 VirtualRoutersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualRoutersClient) listCreateRequest(ctx context.Context, options *VirtualRoutersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualRouters" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualRoutersClient) listHandleResponse(resp *http.Response) (VirtualRoutersClientListResponse, error) { + result := VirtualRoutersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualRouterListResult); err != nil { + return VirtualRoutersClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all Virtual Routers in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - VirtualRoutersClientListByResourceGroupOptions contains the optional parameters for the VirtualRoutersClient.NewListByResourceGroupPager +// method. +func (client *VirtualRoutersClient) NewListByResourceGroupPager(resourceGroupName string, options *VirtualRoutersClientListByResourceGroupOptions) *runtime.Pager[VirtualRoutersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualRoutersClientListByResourceGroupResponse]{ + More: func(page VirtualRoutersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualRoutersClientListByResourceGroupResponse) (VirtualRoutersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualRoutersClient.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 VirtualRoutersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VirtualRoutersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualRoutersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VirtualRoutersClient) listByResourceGroupHandleResponse(resp *http.Response) (VirtualRoutersClientListByResourceGroupResponse, error) { + result := VirtualRoutersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualRouterListResult); err != nil { + return VirtualRoutersClientListByResourceGroupResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualwans_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualwans_client.go new file mode 100644 index 000000000..3b5210fc9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/virtualwans_client.go @@ -0,0 +1,448 @@ +//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 armnetwork + +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" +) + +// VirtualWansClient contains the methods for the VirtualWans group. +// Don't use this type directly, use NewVirtualWansClient() instead. +type VirtualWansClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualWansClient creates a new instance of VirtualWansClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVirtualWansClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualWansClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualWansClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualWan. +// - virtualWANName - The name of the VirtualWAN being created or updated. +// - wanParameters - Parameters supplied to create or update VirtualWAN. +// - options - VirtualWansClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualWansClient.BeginCreateOrUpdate +// method. +func (client *VirtualWansClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, virtualWANName string, wanParameters VirtualWAN, options *VirtualWansClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualWansClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, virtualWANName, wanParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualWansClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualWansClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualWansClient) createOrUpdate(ctx context.Context, resourceGroupName string, virtualWANName string, wanParameters VirtualWAN, options *VirtualWansClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualWansClient.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, virtualWANName, wanParameters, 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 *VirtualWansClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, wanParameters VirtualWAN, options *VirtualWansClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}" + 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 virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{VirtualWANName}", url.PathEscape(virtualWANName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, wanParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a VirtualWAN. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualWan. +// - virtualWANName - The name of the VirtualWAN being deleted. +// - options - VirtualWansClientBeginDeleteOptions contains the optional parameters for the VirtualWansClient.BeginDelete method. +func (client *VirtualWansClient) BeginDelete(ctx context.Context, resourceGroupName string, virtualWANName string, options *VirtualWansClientBeginDeleteOptions) (*runtime.Poller[VirtualWansClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, virtualWANName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualWansClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualWansClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VirtualWAN. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VirtualWansClient) deleteOperation(ctx context.Context, resourceGroupName string, virtualWANName string, options *VirtualWansClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualWansClient.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, virtualWANName, 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 *VirtualWansClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, options *VirtualWansClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}" + 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 virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{VirtualWANName}", url.PathEscape(virtualWANName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a VirtualWAN. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualWan. +// - virtualWANName - The name of the VirtualWAN being retrieved. +// - options - VirtualWansClientGetOptions contains the optional parameters for the VirtualWansClient.Get method. +func (client *VirtualWansClient) Get(ctx context.Context, resourceGroupName string, virtualWANName string, options *VirtualWansClientGetOptions) (VirtualWansClientGetResponse, error) { + var err error + const operationName = "VirtualWansClient.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, virtualWANName, options) + if err != nil { + return VirtualWansClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualWansClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualWansClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualWansClient) getCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, options *VirtualWansClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{VirtualWANName}", url.PathEscape(virtualWANName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualWansClient) getHandleResponse(resp *http.Response) (VirtualWansClientGetResponse, error) { + result := VirtualWansClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualWAN); err != nil { + return VirtualWansClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the VirtualWANs in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VirtualWansClientListOptions contains the optional parameters for the VirtualWansClient.NewListPager method. +func (client *VirtualWansClient) NewListPager(options *VirtualWansClientListOptions) *runtime.Pager[VirtualWansClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualWansClientListResponse]{ + More: func(page VirtualWansClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualWansClientListResponse) (VirtualWansClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualWansClient.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 VirtualWansClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VirtualWansClient) listCreateRequest(ctx context.Context, options *VirtualWansClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualWans" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VirtualWansClient) listHandleResponse(resp *http.Response) (VirtualWansClientListResponse, error) { + result := VirtualWansClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualWANsResult); err != nil { + return VirtualWansClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the VirtualWANs in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualWan. +// - options - VirtualWansClientListByResourceGroupOptions contains the optional parameters for the VirtualWansClient.NewListByResourceGroupPager +// method. +func (client *VirtualWansClient) NewListByResourceGroupPager(resourceGroupName string, options *VirtualWansClientListByResourceGroupOptions) *runtime.Pager[VirtualWansClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualWansClientListByResourceGroupResponse]{ + More: func(page VirtualWansClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualWansClientListByResourceGroupResponse) (VirtualWansClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualWansClient.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 VirtualWansClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VirtualWansClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VirtualWansClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VirtualWansClient) listByResourceGroupHandleResponse(resp *http.Response) (VirtualWansClientListByResourceGroupResponse, error) { + result := VirtualWansClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVirtualWANsResult); err != nil { + return VirtualWansClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates a VirtualWAN tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VirtualWan. +// - virtualWANName - The name of the VirtualWAN being updated. +// - wanParameters - Parameters supplied to Update VirtualWAN tags. +// - options - VirtualWansClientUpdateTagsOptions contains the optional parameters for the VirtualWansClient.UpdateTags method. +func (client *VirtualWansClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualWANName string, wanParameters TagsObject, options *VirtualWansClientUpdateTagsOptions) (VirtualWansClientUpdateTagsResponse, error) { + var err error + const operationName = "VirtualWansClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, virtualWANName, wanParameters, options) + if err != nil { + return VirtualWansClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualWansClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualWansClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VirtualWansClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, wanParameters TagsObject, options *VirtualWansClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}" + 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 virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{VirtualWANName}", url.PathEscape(virtualWANName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, wanParameters); err != nil { + return nil, err + } + return req, nil +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *VirtualWansClient) updateTagsHandleResponse(resp *http.Response) (VirtualWansClientUpdateTagsResponse, error) { + result := VirtualWansClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualWAN); err != nil { + return VirtualWansClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnconnections_client.go new file mode 100644 index 000000000..a18a74883 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnconnections_client.go @@ -0,0 +1,524 @@ +//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 armnetwork + +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" +) + +// VPNConnectionsClient contains the methods for the VPNConnections group. +// Don't use this type directly, use NewVPNConnectionsClient() instead. +type VPNConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNConnectionsClient creates a new instance of VPNConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing +// connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - connectionName - The name of the connection. +// - vpnConnectionParameters - Parameters supplied to create or Update a VPN Connection. +// - options - VPNConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNConnectionsClient.BeginCreateOrUpdate +// method. +func (client *VPNConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VPNConnection, options *VPNConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VPNConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, gatewayName, connectionName, vpnConnectionParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VPNConnection, options *VPNConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VPNConnectionsClient.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, gatewayName, connectionName, vpnConnectionParameters, 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 *VPNConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VPNConnection, options *VPNConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnConnectionParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a vpn connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - connectionName - The name of the connection. +// - options - VPNConnectionsClientBeginDeleteOptions contains the optional parameters for the VPNConnectionsClient.BeginDelete +// method. +func (client *VPNConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, options *VPNConnectionsClientBeginDeleteOptions) (*runtime.Poller[VPNConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, gatewayName, connectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a vpn connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, options *VPNConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VPNConnectionsClient.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, gatewayName, connectionName, 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 *VPNConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, options *VPNConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a vpn connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - connectionName - The name of the vpn connection. +// - options - VPNConnectionsClientGetOptions contains the optional parameters for the VPNConnectionsClient.Get method. +func (client *VPNConnectionsClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, options *VPNConnectionsClientGetOptions) (VPNConnectionsClientGetResponse, error) { + var err error + const operationName = "VPNConnectionsClient.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, gatewayName, connectionName, options) + if err != nil { + return VPNConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VPNConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, options *VPNConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VPNConnectionsClient) getHandleResponse(resp *http.Response) (VPNConnectionsClientGetResponse, error) { + result := VPNConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNConnection); err != nil { + return VPNConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByVPNGatewayPager - Retrieves all vpn connections for a particular virtual wan vpn gateway. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - options - VPNConnectionsClientListByVPNGatewayOptions contains the optional parameters for the VPNConnectionsClient.NewListByVPNGatewayPager +// method. +func (client *VPNConnectionsClient) NewListByVPNGatewayPager(resourceGroupName string, gatewayName string, options *VPNConnectionsClientListByVPNGatewayOptions) *runtime.Pager[VPNConnectionsClientListByVPNGatewayResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNConnectionsClientListByVPNGatewayResponse]{ + More: func(page VPNConnectionsClientListByVPNGatewayResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNConnectionsClientListByVPNGatewayResponse) (VPNConnectionsClientListByVPNGatewayResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNConnectionsClient.NewListByVPNGatewayPager") + 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.listByVPNGatewayCreateRequest(ctx, resourceGroupName, gatewayName, options) + }, nil) + if err != nil { + return VPNConnectionsClientListByVPNGatewayResponse{}, err + } + return client.listByVPNGatewayHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVPNGatewayCreateRequest creates the ListByVPNGateway request. +func (client *VPNConnectionsClient) listByVPNGatewayCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNConnectionsClientListByVPNGatewayOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVPNGatewayHandleResponse handles the ListByVPNGateway response. +func (client *VPNConnectionsClient) listByVPNGatewayHandleResponse(resp *http.Response) (VPNConnectionsClientListByVPNGatewayResponse, error) { + result := VPNConnectionsClientListByVPNGatewayResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNConnectionsResult); err != nil { + return VPNConnectionsClientListByVPNGatewayResponse{}, err + } + return result, nil +} + +// BeginStartPacketCapture - Starts packet capture on Vpn connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - gatewayName - The name of the gateway. +// - vpnConnectionName - The name of the vpn connection. +// - options - VPNConnectionsClientBeginStartPacketCaptureOptions contains the optional parameters for the VPNConnectionsClient.BeginStartPacketCapture +// method. +func (client *VPNConnectionsClient) BeginStartPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, options *VPNConnectionsClientBeginStartPacketCaptureOptions) (*runtime.Poller[VPNConnectionsClientStartPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.startPacketCapture(ctx, resourceGroupName, gatewayName, vpnConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNConnectionsClientStartPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNConnectionsClientStartPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StartPacketCapture - Starts packet capture on Vpn connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNConnectionsClient) startPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, options *VPNConnectionsClientBeginStartPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VPNConnectionsClient.BeginStartPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startPacketCaptureCreateRequest(ctx, resourceGroupName, gatewayName, vpnConnectionName, 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 +} + +// startPacketCaptureCreateRequest creates the StartPacketCapture request. +func (client *VPNConnectionsClient) startPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, options *VPNConnectionsClientBeginStartPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/startpacketcapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if vpnConnectionName == "" { + return nil, errors.New("parameter vpnConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnConnectionName}", url.PathEscape(vpnConnectionName)) + 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-05-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 +} + +// BeginStopPacketCapture - Stops packet capture on Vpn connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - gatewayName - The name of the gateway. +// - vpnConnectionName - The name of the vpn connection. +// - options - VPNConnectionsClientBeginStopPacketCaptureOptions contains the optional parameters for the VPNConnectionsClient.BeginStopPacketCapture +// method. +func (client *VPNConnectionsClient) BeginStopPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, options *VPNConnectionsClientBeginStopPacketCaptureOptions) (*runtime.Poller[VPNConnectionsClientStopPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stopPacketCapture(ctx, resourceGroupName, gatewayName, vpnConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNConnectionsClientStopPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNConnectionsClientStopPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StopPacketCapture - Stops packet capture on Vpn connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNConnectionsClient) stopPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, options *VPNConnectionsClientBeginStopPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VPNConnectionsClient.BeginStopPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopPacketCaptureCreateRequest(ctx, resourceGroupName, gatewayName, vpnConnectionName, 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 +} + +// stopPacketCaptureCreateRequest creates the StopPacketCapture request. +func (client *VPNConnectionsClient) stopPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, options *VPNConnectionsClientBeginStopPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/stoppacketcapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if vpnConnectionName == "" { + return nil, errors.New("parameter vpnConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnConnectionName}", url.PathEscape(vpnConnectionName)) + 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-05-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 +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpngateways_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpngateways_client.go new file mode 100644 index 000000000..5d28c7988 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpngateways_client.go @@ -0,0 +1,706 @@ +//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 armnetwork + +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" +) + +// VPNGatewaysClient contains the methods for the VPNGateways group. +// Don't use this type directly, use NewVPNGatewaysClient() instead. +type VPNGatewaysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNGatewaysClient creates a new instance of VPNGatewaysClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNGatewaysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNGatewaysClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNGatewaysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - vpnGatewayParameters - Parameters supplied to create or Update a virtual wan vpn gateway. +// - options - VPNGatewaysClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNGatewaysClient.BeginCreateOrUpdate +// method. +func (client *VPNGatewaysClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters VPNGateway, options *VPNGatewaysClientBeginCreateOrUpdateOptions) (*runtime.Poller[VPNGatewaysClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, gatewayName, vpnGatewayParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNGatewaysClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNGatewaysClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNGatewaysClient) createOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters VPNGateway, options *VPNGatewaysClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VPNGatewaysClient.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, gatewayName, vpnGatewayParameters, 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 *VPNGatewaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters VPNGateway, options *VPNGatewaysClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnGatewayParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a virtual wan vpn gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - options - VPNGatewaysClientBeginDeleteOptions contains the optional parameters for the VPNGatewaysClient.BeginDelete method. +func (client *VPNGatewaysClient) BeginDelete(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginDeleteOptions) (*runtime.Poller[VPNGatewaysClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, gatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNGatewaysClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNGatewaysClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a virtual wan vpn gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNGatewaysClient) deleteOperation(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VPNGatewaysClient.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, gatewayName, 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 *VPNGatewaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a virtual wan vpn gateway. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - options - VPNGatewaysClientGetOptions contains the optional parameters for the VPNGatewaysClient.Get method. +func (client *VPNGatewaysClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientGetOptions) (VPNGatewaysClientGetResponse, error) { + var err error + const operationName = "VPNGatewaysClient.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, gatewayName, options) + if err != nil { + return VPNGatewaysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNGatewaysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNGatewaysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VPNGatewaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VPNGatewaysClient) getHandleResponse(resp *http.Response) (VPNGatewaysClientGetResponse, error) { + result := VPNGatewaysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNGateway); err != nil { + return VPNGatewaysClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the VpnGateways in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VPNGatewaysClientListOptions contains the optional parameters for the VPNGatewaysClient.NewListPager method. +func (client *VPNGatewaysClient) NewListPager(options *VPNGatewaysClientListOptions) *runtime.Pager[VPNGatewaysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNGatewaysClientListResponse]{ + More: func(page VPNGatewaysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNGatewaysClientListResponse) (VPNGatewaysClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNGatewaysClient.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 VPNGatewaysClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VPNGatewaysClient) listCreateRequest(ctx context.Context, options *VPNGatewaysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VPNGatewaysClient) listHandleResponse(resp *http.Response) (VPNGatewaysClientListResponse, error) { + result := VPNGatewaysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNGatewaysResult); err != nil { + return VPNGatewaysClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the VpnGateways in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - options - VPNGatewaysClientListByResourceGroupOptions contains the optional parameters for the VPNGatewaysClient.NewListByResourceGroupPager +// method. +func (client *VPNGatewaysClient) NewListByResourceGroupPager(resourceGroupName string, options *VPNGatewaysClientListByResourceGroupOptions) *runtime.Pager[VPNGatewaysClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNGatewaysClientListByResourceGroupResponse]{ + More: func(page VPNGatewaysClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNGatewaysClientListByResourceGroupResponse) (VPNGatewaysClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNGatewaysClient.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 VPNGatewaysClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VPNGatewaysClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VPNGatewaysClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VPNGatewaysClient) listByResourceGroupHandleResponse(resp *http.Response) (VPNGatewaysClientListByResourceGroupResponse, error) { + result := VPNGatewaysClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNGatewaysResult); err != nil { + return VPNGatewaysClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// BeginReset - Resets the primary of the vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - options - VPNGatewaysClientBeginResetOptions contains the optional parameters for the VPNGatewaysClient.BeginReset method. +func (client *VPNGatewaysClient) BeginReset(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginResetOptions) (*runtime.Poller[VPNGatewaysClientResetResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reset(ctx, resourceGroupName, gatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNGatewaysClientResetResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNGatewaysClientResetResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reset - Resets the primary of the vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNGatewaysClient) reset(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginResetOptions) (*http.Response, error) { + var err error + const operationName = "VPNGatewaysClient.BeginReset" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetCreateRequest(ctx, resourceGroupName, gatewayName, 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 +} + +// resetCreateRequest creates the Reset request. +func (client *VPNGatewaysClient) resetCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginResetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/reset" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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() + if options != nil && options.IPConfigurationID != nil { + reqQP.Set("ipConfigurationId", *options.IPConfigurationID) + } + reqQP.Set("api-version", "2023-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStartPacketCapture - Starts packet capture on vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - options - VPNGatewaysClientBeginStartPacketCaptureOptions contains the optional parameters for the VPNGatewaysClient.BeginStartPacketCapture +// method. +func (client *VPNGatewaysClient) BeginStartPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginStartPacketCaptureOptions) (*runtime.Poller[VPNGatewaysClientStartPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.startPacketCapture(ctx, resourceGroupName, gatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNGatewaysClientStartPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNGatewaysClientStartPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StartPacketCapture - Starts packet capture on vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNGatewaysClient) startPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginStartPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VPNGatewaysClient.BeginStartPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startPacketCaptureCreateRequest(ctx, resourceGroupName, gatewayName, 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 +} + +// startPacketCaptureCreateRequest creates the StartPacketCapture request. +func (client *VPNGatewaysClient) startPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginStartPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/startpacketcapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-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 +} + +// BeginStopPacketCapture - Stops packet capture on vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - options - VPNGatewaysClientBeginStopPacketCaptureOptions contains the optional parameters for the VPNGatewaysClient.BeginStopPacketCapture +// method. +func (client *VPNGatewaysClient) BeginStopPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginStopPacketCaptureOptions) (*runtime.Poller[VPNGatewaysClientStopPacketCaptureResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stopPacketCapture(ctx, resourceGroupName, gatewayName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNGatewaysClientStopPacketCaptureResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNGatewaysClientStopPacketCaptureResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StopPacketCapture - Stops packet capture on vpn gateway in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNGatewaysClient) stopPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginStopPacketCaptureOptions) (*http.Response, error) { + var err error + const operationName = "VPNGatewaysClient.BeginStopPacketCapture" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopPacketCaptureCreateRequest(ctx, resourceGroupName, gatewayName, 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 +} + +// stopPacketCaptureCreateRequest creates the StopPacketCapture request. +func (client *VPNGatewaysClient) stopPacketCaptureCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, options *VPNGatewaysClientBeginStopPacketCaptureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/stoppacketcapture" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-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 +} + +// BeginUpdateTags - Updates virtual wan vpn gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - vpnGatewayParameters - Parameters supplied to update a virtual wan vpn gateway tags. +// - options - VPNGatewaysClientBeginUpdateTagsOptions contains the optional parameters for the VPNGatewaysClient.BeginUpdateTags +// method. +func (client *VPNGatewaysClient) BeginUpdateTags(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters TagsObject, options *VPNGatewaysClientBeginUpdateTagsOptions) (*runtime.Poller[VPNGatewaysClientUpdateTagsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updateTags(ctx, resourceGroupName, gatewayName, vpnGatewayParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNGatewaysClientUpdateTagsResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNGatewaysClientUpdateTagsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdateTags - Updates virtual wan vpn gateway tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNGatewaysClient) updateTags(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters TagsObject, options *VPNGatewaysClientBeginUpdateTagsOptions) (*http.Response, error) { + var err error + const operationName = "VPNGatewaysClient.BeginUpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, gatewayName, vpnGatewayParameters, 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 +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VPNGatewaysClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters TagsObject, options *VPNGatewaysClientBeginUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnGatewayParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnlinkconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnlinkconnections_client.go new file mode 100644 index 000000000..c9e13cc5f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnlinkconnections_client.go @@ -0,0 +1,289 @@ +//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 armnetwork + +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" +) + +// VPNLinkConnectionsClient contains the methods for the VPNLinkConnections group. +// Don't use this type directly, use NewVPNLinkConnectionsClient() instead. +type VPNLinkConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNLinkConnectionsClient creates a new instance of VPNLinkConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNLinkConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNLinkConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNLinkConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginGetIkeSas - Lists IKE Security Associations for Vpn Site Link Connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - gatewayName - The name of the gateway. +// - connectionName - The name of the vpn connection. +// - linkConnectionName - The name of the vpn link connection. +// - options - VPNLinkConnectionsClientBeginGetIkeSasOptions contains the optional parameters for the VPNLinkConnectionsClient.BeginGetIkeSas +// method. +func (client *VPNLinkConnectionsClient) BeginGetIkeSas(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNLinkConnectionsClientBeginGetIkeSasOptions) (*runtime.Poller[VPNLinkConnectionsClientGetIkeSasResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getIkeSas(ctx, resourceGroupName, gatewayName, connectionName, linkConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNLinkConnectionsClientGetIkeSasResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNLinkConnectionsClientGetIkeSasResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetIkeSas - Lists IKE Security Associations for Vpn Site Link Connection in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNLinkConnectionsClient) getIkeSas(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNLinkConnectionsClientBeginGetIkeSasOptions) (*http.Response, error) { + var err error + const operationName = "VPNLinkConnectionsClient.BeginGetIkeSas" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getIkeSasCreateRequest(ctx, resourceGroupName, gatewayName, connectionName, linkConnectionName, 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 +} + +// getIkeSasCreateRequest creates the GetIkeSas request. +func (client *VPNLinkConnectionsClient) getIkeSasCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNLinkConnectionsClientBeginGetIkeSasOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections/{linkConnectionName}/getikesas" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + if linkConnectionName == "" { + return nil, errors.New("parameter linkConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{linkConnectionName}", url.PathEscape(linkConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// NewListByVPNConnectionPager - Retrieves all vpn site link connections for a particular virtual wan vpn gateway vpn connection. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the vpn gateway. +// - gatewayName - The name of the gateway. +// - connectionName - The name of the vpn connection. +// - options - VPNLinkConnectionsClientListByVPNConnectionOptions contains the optional parameters for the VPNLinkConnectionsClient.NewListByVPNConnectionPager +// method. +func (client *VPNLinkConnectionsClient) NewListByVPNConnectionPager(resourceGroupName string, gatewayName string, connectionName string, options *VPNLinkConnectionsClientListByVPNConnectionOptions) *runtime.Pager[VPNLinkConnectionsClientListByVPNConnectionResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNLinkConnectionsClientListByVPNConnectionResponse]{ + More: func(page VPNLinkConnectionsClientListByVPNConnectionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNLinkConnectionsClientListByVPNConnectionResponse) (VPNLinkConnectionsClientListByVPNConnectionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNLinkConnectionsClient.NewListByVPNConnectionPager") + 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.listByVPNConnectionCreateRequest(ctx, resourceGroupName, gatewayName, connectionName, options) + }, nil) + if err != nil { + return VPNLinkConnectionsClientListByVPNConnectionResponse{}, err + } + return client.listByVPNConnectionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVPNConnectionCreateRequest creates the ListByVPNConnection request. +func (client *VPNLinkConnectionsClient) listByVPNConnectionCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, options *VPNLinkConnectionsClientListByVPNConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVPNConnectionHandleResponse handles the ListByVPNConnection response. +func (client *VPNLinkConnectionsClient) listByVPNConnectionHandleResponse(resp *http.Response) (VPNLinkConnectionsClientListByVPNConnectionResponse, error) { + result := VPNLinkConnectionsClientListByVPNConnectionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNSiteLinkConnectionsResult); err != nil { + return VPNLinkConnectionsClientListByVPNConnectionResponse{}, err + } + return result, nil +} + +// BeginResetConnection - Resets the VpnLink connection specified. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - gatewayName - The name of the gateway. +// - connectionName - The name of the vpn connection. +// - linkConnectionName - The name of the vpn link connection. +// - options - VPNLinkConnectionsClientBeginResetConnectionOptions contains the optional parameters for the VPNLinkConnectionsClient.BeginResetConnection +// method. +func (client *VPNLinkConnectionsClient) BeginResetConnection(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNLinkConnectionsClientBeginResetConnectionOptions) (*runtime.Poller[VPNLinkConnectionsClientResetConnectionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.resetConnection(ctx, resourceGroupName, gatewayName, connectionName, linkConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNLinkConnectionsClientResetConnectionResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNLinkConnectionsClientResetConnectionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ResetConnection - Resets the VpnLink connection specified. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNLinkConnectionsClient) resetConnection(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNLinkConnectionsClientBeginResetConnectionOptions) (*http.Response, error) { + var err error + const operationName = "VPNLinkConnectionsClient.BeginResetConnection" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetConnectionCreateRequest(ctx, resourceGroupName, gatewayName, connectionName, linkConnectionName, 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 +} + +// resetConnectionCreateRequest creates the ResetConnection request. +func (client *VPNLinkConnectionsClient) resetConnectionCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNLinkConnectionsClientBeginResetConnectionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections/{linkConnectionName}/resetconnection" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + if linkConnectionName == "" { + return nil, errors.New("parameter linkConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{linkConnectionName}", url.PathEscape(linkConnectionName)) + 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-05-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/network/armnetwork/v4/vpnserverconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnserverconfigurations_client.go new file mode 100644 index 000000000..1cb954690 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnserverconfigurations_client.go @@ -0,0 +1,452 @@ +//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 armnetwork + +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" +) + +// VPNServerConfigurationsClient contains the methods for the VPNServerConfigurations group. +// Don't use this type directly, use NewVPNServerConfigurationsClient() instead. +type VPNServerConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNServerConfigurationsClient creates a new instance of VPNServerConfigurationsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNServerConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNServerConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNServerConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a VpnServerConfiguration resource if it doesn't exist else updates the existing VpnServerConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnServerConfiguration. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration being created or updated. +// - vpnServerConfigurationParameters - Parameters supplied to create or update VpnServerConfiguration. +// - options - VPNServerConfigurationsClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNServerConfigurationsClient.BeginCreateOrUpdate +// method. +func (client *VPNServerConfigurationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters VPNServerConfiguration, options *VPNServerConfigurationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VPNServerConfigurationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vpnServerConfigurationName, vpnServerConfigurationParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNServerConfigurationsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNServerConfigurationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a VpnServerConfiguration resource if it doesn't exist else updates the existing VpnServerConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNServerConfigurationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters VPNServerConfiguration, options *VPNServerConfigurationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VPNServerConfigurationsClient.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, vpnServerConfigurationName, vpnServerConfigurationParameters, 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 *VPNServerConfigurationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters VPNServerConfiguration, options *VPNServerConfigurationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnServerConfigurationParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a VpnServerConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnServerConfiguration. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration being deleted. +// - options - VPNServerConfigurationsClientBeginDeleteOptions contains the optional parameters for the VPNServerConfigurationsClient.BeginDelete +// method. +func (client *VPNServerConfigurationsClient) BeginDelete(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, options *VPNServerConfigurationsClientBeginDeleteOptions) (*runtime.Poller[VPNServerConfigurationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vpnServerConfigurationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNServerConfigurationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNServerConfigurationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VpnServerConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNServerConfigurationsClient) deleteOperation(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, options *VPNServerConfigurationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VPNServerConfigurationsClient.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, vpnServerConfigurationName, 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 *VPNServerConfigurationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, options *VPNServerConfigurationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a VpnServerConfiguration. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnServerConfiguration. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration being retrieved. +// - options - VPNServerConfigurationsClientGetOptions contains the optional parameters for the VPNServerConfigurationsClient.Get +// method. +func (client *VPNServerConfigurationsClient) Get(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, options *VPNServerConfigurationsClientGetOptions) (VPNServerConfigurationsClientGetResponse, error) { + var err error + const operationName = "VPNServerConfigurationsClient.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, vpnServerConfigurationName, options) + if err != nil { + return VPNServerConfigurationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNServerConfigurationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNServerConfigurationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VPNServerConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, options *VPNServerConfigurationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VPNServerConfigurationsClient) getHandleResponse(resp *http.Response) (VPNServerConfigurationsClientGetResponse, error) { + result := VPNServerConfigurationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNServerConfiguration); err != nil { + return VPNServerConfigurationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the VpnServerConfigurations in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VPNServerConfigurationsClientListOptions contains the optional parameters for the VPNServerConfigurationsClient.NewListPager +// method. +func (client *VPNServerConfigurationsClient) NewListPager(options *VPNServerConfigurationsClientListOptions) *runtime.Pager[VPNServerConfigurationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNServerConfigurationsClientListResponse]{ + More: func(page VPNServerConfigurationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNServerConfigurationsClientListResponse) (VPNServerConfigurationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNServerConfigurationsClient.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 VPNServerConfigurationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VPNServerConfigurationsClient) listCreateRequest(ctx context.Context, options *VPNServerConfigurationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnServerConfigurations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VPNServerConfigurationsClient) listHandleResponse(resp *http.Response) (VPNServerConfigurationsClientListResponse, error) { + result := VPNServerConfigurationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNServerConfigurationsResult); err != nil { + return VPNServerConfigurationsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the vpnServerConfigurations in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnServerConfiguration. +// - options - VPNServerConfigurationsClientListByResourceGroupOptions contains the optional parameters for the VPNServerConfigurationsClient.NewListByResourceGroupPager +// method. +func (client *VPNServerConfigurationsClient) NewListByResourceGroupPager(resourceGroupName string, options *VPNServerConfigurationsClientListByResourceGroupOptions) *runtime.Pager[VPNServerConfigurationsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNServerConfigurationsClientListByResourceGroupResponse]{ + More: func(page VPNServerConfigurationsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNServerConfigurationsClientListByResourceGroupResponse) (VPNServerConfigurationsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNServerConfigurationsClient.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 VPNServerConfigurationsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VPNServerConfigurationsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VPNServerConfigurationsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VPNServerConfigurationsClient) listByResourceGroupHandleResponse(resp *http.Response) (VPNServerConfigurationsClientListByResourceGroupResponse, error) { + result := VPNServerConfigurationsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNServerConfigurationsResult); err != nil { + return VPNServerConfigurationsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates VpnServerConfiguration tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnServerConfiguration. +// - vpnServerConfigurationName - The name of the VpnServerConfiguration being updated. +// - vpnServerConfigurationParameters - Parameters supplied to update VpnServerConfiguration tags. +// - options - VPNServerConfigurationsClientUpdateTagsOptions contains the optional parameters for the VPNServerConfigurationsClient.UpdateTags +// method. +func (client *VPNServerConfigurationsClient) UpdateTags(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters TagsObject, options *VPNServerConfigurationsClientUpdateTagsOptions) (VPNServerConfigurationsClientUpdateTagsResponse, error) { + var err error + const operationName = "VPNServerConfigurationsClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, vpnServerConfigurationName, vpnServerConfigurationParameters, options) + if err != nil { + return VPNServerConfigurationsClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNServerConfigurationsClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNServerConfigurationsClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VPNServerConfigurationsClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters TagsObject, options *VPNServerConfigurationsClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}" + 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 vpnServerConfigurationName == "" { + return nil, errors.New("parameter vpnServerConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnServerConfigurationName}", url.PathEscape(vpnServerConfigurationName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnServerConfigurationParameters); err != nil { + return nil, err + } + return req, nil +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *VPNServerConfigurationsClient) updateTagsHandleResponse(resp *http.Response) (VPNServerConfigurationsClientUpdateTagsResponse, error) { + result := VPNServerConfigurationsClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNServerConfiguration); err != nil { + return VPNServerConfigurationsClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnserverconfigurationsassociatedwithvirtualwan_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnserverconfigurationsassociatedwithvirtualwan_client.go new file mode 100644 index 000000000..f7e5490f7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnserverconfigurationsassociatedwithvirtualwan_client.go @@ -0,0 +1,122 @@ +//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 armnetwork + +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" +) + +// VPNServerConfigurationsAssociatedWithVirtualWanClient contains the methods for the VPNServerConfigurationsAssociatedWithVirtualWan group. +// Don't use this type directly, use NewVPNServerConfigurationsAssociatedWithVirtualWanClient() instead. +type VPNServerConfigurationsAssociatedWithVirtualWanClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNServerConfigurationsAssociatedWithVirtualWanClient creates a new instance of VPNServerConfigurationsAssociatedWithVirtualWanClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNServerConfigurationsAssociatedWithVirtualWanClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNServerConfigurationsAssociatedWithVirtualWanClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNServerConfigurationsAssociatedWithVirtualWanClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginList - Gives the list of VpnServerConfigurations associated with Virtual Wan in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name. +// - virtualWANName - The name of the VirtualWAN whose associated VpnServerConfigurations is needed. +// - options - VPNServerConfigurationsAssociatedWithVirtualWanClientBeginListOptions contains the optional parameters for the +// VPNServerConfigurationsAssociatedWithVirtualWanClient.BeginList method. +func (client *VPNServerConfigurationsAssociatedWithVirtualWanClient) BeginList(ctx context.Context, resourceGroupName string, virtualWANName string, options *VPNServerConfigurationsAssociatedWithVirtualWanClientBeginListOptions) (*runtime.Poller[VPNServerConfigurationsAssociatedWithVirtualWanClientListResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listOperation(ctx, resourceGroupName, virtualWANName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNServerConfigurationsAssociatedWithVirtualWanClientListResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNServerConfigurationsAssociatedWithVirtualWanClientListResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// List - Gives the list of VpnServerConfigurations associated with Virtual Wan in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNServerConfigurationsAssociatedWithVirtualWanClient) listOperation(ctx context.Context, resourceGroupName string, virtualWANName string, options *VPNServerConfigurationsAssociatedWithVirtualWanClientBeginListOptions) (*http.Response, error) { + var err error + const operationName = "VPNServerConfigurationsAssociatedWithVirtualWanClient.BeginList" + 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, virtualWANName, 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 +} + +// listCreateRequest creates the List request. +func (client *VPNServerConfigurationsAssociatedWithVirtualWanClient) listCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, options *VPNServerConfigurationsAssociatedWithVirtualWanClientBeginListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnServerConfigurations" + 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 virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualWANName}", url.PathEscape(virtualWANName)) + 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-05-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/network/armnetwork/v4/vpnsitelinkconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitelinkconnections_client.go new file mode 100644 index 000000000..ce9c64340 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitelinkconnections_client.go @@ -0,0 +1,120 @@ +//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 armnetwork + +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" +) + +// VPNSiteLinkConnectionsClient contains the methods for the VPNSiteLinkConnections group. +// Don't use this type directly, use NewVPNSiteLinkConnectionsClient() instead. +type VPNSiteLinkConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNSiteLinkConnectionsClient creates a new instance of VPNSiteLinkConnectionsClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNSiteLinkConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNSiteLinkConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNSiteLinkConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Retrieves the details of a vpn site link connection. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnGateway. +// - gatewayName - The name of the gateway. +// - connectionName - The name of the vpn connection. +// - linkConnectionName - The name of the vpn connection. +// - options - VPNSiteLinkConnectionsClientGetOptions contains the optional parameters for the VPNSiteLinkConnectionsClient.Get +// method. +func (client *VPNSiteLinkConnectionsClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNSiteLinkConnectionsClientGetOptions) (VPNSiteLinkConnectionsClientGetResponse, error) { + var err error + const operationName = "VPNSiteLinkConnectionsClient.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, gatewayName, connectionName, linkConnectionName, options) + if err != nil { + return VPNSiteLinkConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNSiteLinkConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNSiteLinkConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VPNSiteLinkConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string, options *VPNSiteLinkConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections/{linkConnectionName}" + 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 gatewayName == "" { + return nil, errors.New("parameter gatewayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{gatewayName}", url.PathEscape(gatewayName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + if linkConnectionName == "" { + return nil, errors.New("parameter linkConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{linkConnectionName}", url.PathEscape(linkConnectionName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VPNSiteLinkConnectionsClient) getHandleResponse(resp *http.Response) (VPNSiteLinkConnectionsClientGetResponse, error) { + result := VPNSiteLinkConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNSiteLinkConnection); err != nil { + return VPNSiteLinkConnectionsClientGetResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitelinks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitelinks_client.go new file mode 100644 index 000000000..ae77b690b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitelinks_client.go @@ -0,0 +1,179 @@ +//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 armnetwork + +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" +) + +// VPNSiteLinksClient contains the methods for the VPNSiteLinks group. +// Don't use this type directly, use NewVPNSiteLinksClient() instead. +type VPNSiteLinksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNSiteLinksClient creates a new instance of VPNSiteLinksClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNSiteLinksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNSiteLinksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNSiteLinksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Retrieves the details of a VPN site link. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnSite. +// - vpnSiteName - The name of the VpnSite. +// - vpnSiteLinkName - The name of the VpnSiteLink being retrieved. +// - options - VPNSiteLinksClientGetOptions contains the optional parameters for the VPNSiteLinksClient.Get method. +func (client *VPNSiteLinksClient) Get(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteLinkName string, options *VPNSiteLinksClientGetOptions) (VPNSiteLinksClientGetResponse, error) { + var err error + const operationName = "VPNSiteLinksClient.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, vpnSiteName, vpnSiteLinkName, options) + if err != nil { + return VPNSiteLinksClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNSiteLinksClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNSiteLinksClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VPNSiteLinksClient) getCreateRequest(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteLinkName string, options *VPNSiteLinksClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}/vpnSiteLinks/{vpnSiteLinkName}" + 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 vpnSiteName == "" { + return nil, errors.New("parameter vpnSiteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnSiteName}", url.PathEscape(vpnSiteName)) + if vpnSiteLinkName == "" { + return nil, errors.New("parameter vpnSiteLinkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnSiteLinkName}", url.PathEscape(vpnSiteLinkName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VPNSiteLinksClient) getHandleResponse(resp *http.Response) (VPNSiteLinksClientGetResponse, error) { + result := VPNSiteLinksClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNSiteLink); err != nil { + return VPNSiteLinksClientGetResponse{}, err + } + return result, nil +} + +// NewListByVPNSitePager - Lists all the vpnSiteLinks in a resource group for a vpn site. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnSite. +// - vpnSiteName - The name of the VpnSite. +// - options - VPNSiteLinksClientListByVPNSiteOptions contains the optional parameters for the VPNSiteLinksClient.NewListByVPNSitePager +// method. +func (client *VPNSiteLinksClient) NewListByVPNSitePager(resourceGroupName string, vpnSiteName string, options *VPNSiteLinksClientListByVPNSiteOptions) *runtime.Pager[VPNSiteLinksClientListByVPNSiteResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNSiteLinksClientListByVPNSiteResponse]{ + More: func(page VPNSiteLinksClientListByVPNSiteResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNSiteLinksClientListByVPNSiteResponse) (VPNSiteLinksClientListByVPNSiteResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNSiteLinksClient.NewListByVPNSitePager") + 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.listByVPNSiteCreateRequest(ctx, resourceGroupName, vpnSiteName, options) + }, nil) + if err != nil { + return VPNSiteLinksClientListByVPNSiteResponse{}, err + } + return client.listByVPNSiteHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVPNSiteCreateRequest creates the ListByVPNSite request. +func (client *VPNSiteLinksClient) listByVPNSiteCreateRequest(ctx context.Context, resourceGroupName string, vpnSiteName string, options *VPNSiteLinksClientListByVPNSiteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}/vpnSiteLinks" + 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 vpnSiteName == "" { + return nil, errors.New("parameter vpnSiteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnSiteName}", url.PathEscape(vpnSiteName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVPNSiteHandleResponse handles the ListByVPNSite response. +func (client *VPNSiteLinksClient) listByVPNSiteHandleResponse(resp *http.Response) (VPNSiteLinksClientListByVPNSiteResponse, error) { + result := VPNSiteLinksClientListByVPNSiteResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNSiteLinksResult); err != nil { + return VPNSiteLinksClientListByVPNSiteResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsites_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsites_client.go new file mode 100644 index 000000000..ea91d8bec --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsites_client.go @@ -0,0 +1,448 @@ +//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 armnetwork + +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" +) + +// VPNSitesClient contains the methods for the VPNSites group. +// Don't use this type directly, use NewVPNSitesClient() instead. +type VPNSitesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNSitesClient creates a new instance of VPNSitesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNSitesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNSitesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNSitesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a VpnSite resource if it doesn't exist else updates the existing VpnSite. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnSite. +// - vpnSiteName - The name of the VpnSite being created or updated. +// - vpnSiteParameters - Parameters supplied to create or update VpnSite. +// - options - VPNSitesClientBeginCreateOrUpdateOptions contains the optional parameters for the VPNSitesClient.BeginCreateOrUpdate +// method. +func (client *VPNSitesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VPNSite, options *VPNSitesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VPNSitesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNSitesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNSitesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a VpnSite resource if it doesn't exist else updates the existing VpnSite. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNSitesClient) createOrUpdate(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VPNSite, options *VPNSitesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VPNSitesClient.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, vpnSiteName, vpnSiteParameters, 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 *VPNSitesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VPNSite, options *VPNSitesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}" + 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 vpnSiteName == "" { + return nil, errors.New("parameter vpnSiteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnSiteName}", url.PathEscape(vpnSiteName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnSiteParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a VpnSite. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnSite. +// - vpnSiteName - The name of the VpnSite being deleted. +// - options - VPNSitesClientBeginDeleteOptions contains the optional parameters for the VPNSitesClient.BeginDelete method. +func (client *VPNSitesClient) BeginDelete(ctx context.Context, resourceGroupName string, vpnSiteName string, options *VPNSitesClientBeginDeleteOptions) (*runtime.Poller[VPNSitesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vpnSiteName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNSitesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNSitesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a VpnSite. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNSitesClient) deleteOperation(ctx context.Context, resourceGroupName string, vpnSiteName string, options *VPNSitesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VPNSitesClient.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, vpnSiteName, 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 *VPNSitesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vpnSiteName string, options *VPNSitesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}" + 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 vpnSiteName == "" { + return nil, errors.New("parameter vpnSiteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnSiteName}", url.PathEscape(vpnSiteName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieves the details of a VPN site. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnSite. +// - vpnSiteName - The name of the VpnSite being retrieved. +// - options - VPNSitesClientGetOptions contains the optional parameters for the VPNSitesClient.Get method. +func (client *VPNSitesClient) Get(ctx context.Context, resourceGroupName string, vpnSiteName string, options *VPNSitesClientGetOptions) (VPNSitesClientGetResponse, error) { + var err error + const operationName = "VPNSitesClient.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, vpnSiteName, options) + if err != nil { + return VPNSitesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNSitesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNSitesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VPNSitesClient) getCreateRequest(ctx context.Context, resourceGroupName string, vpnSiteName string, options *VPNSitesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}" + 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 vpnSiteName == "" { + return nil, errors.New("parameter vpnSiteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnSiteName}", url.PathEscape(vpnSiteName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VPNSitesClient) getHandleResponse(resp *http.Response) (VPNSitesClientGetResponse, error) { + result := VPNSitesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNSite); err != nil { + return VPNSitesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the VpnSites in a subscription. +// +// Generated from API version 2023-05-01 +// - options - VPNSitesClientListOptions contains the optional parameters for the VPNSitesClient.NewListPager method. +func (client *VPNSitesClient) NewListPager(options *VPNSitesClientListOptions) *runtime.Pager[VPNSitesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNSitesClientListResponse]{ + More: func(page VPNSitesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNSitesClientListResponse) (VPNSitesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNSitesClient.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 VPNSitesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *VPNSitesClient) listCreateRequest(ctx context.Context, options *VPNSitesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnSites" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VPNSitesClient) listHandleResponse(resp *http.Response) (VPNSitesClientListResponse, error) { + result := VPNSitesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNSitesResult); err != nil { + return VPNSitesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the vpnSites in a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnSite. +// - options - VPNSitesClientListByResourceGroupOptions contains the optional parameters for the VPNSitesClient.NewListByResourceGroupPager +// method. +func (client *VPNSitesClient) NewListByResourceGroupPager(resourceGroupName string, options *VPNSitesClientListByResourceGroupOptions) *runtime.Pager[VPNSitesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VPNSitesClientListByResourceGroupResponse]{ + More: func(page VPNSitesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VPNSitesClientListByResourceGroupResponse) (VPNSitesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VPNSitesClient.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 VPNSitesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VPNSitesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VPNSitesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VPNSitesClient) listByResourceGroupHandleResponse(resp *http.Response) (VPNSitesClientListByResourceGroupResponse, error) { + result := VPNSitesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListVPNSitesResult); err != nil { + return VPNSitesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// UpdateTags - Updates VpnSite tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name of the VpnSite. +// - vpnSiteName - The name of the VpnSite being updated. +// - vpnSiteParameters - Parameters supplied to update VpnSite tags. +// - options - VPNSitesClientUpdateTagsOptions contains the optional parameters for the VPNSitesClient.UpdateTags method. +func (client *VPNSitesClient) UpdateTags(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject, options *VPNSitesClientUpdateTagsOptions) (VPNSitesClientUpdateTagsResponse, error) { + var err error + const operationName = "VPNSitesClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters, options) + if err != nil { + return VPNSitesClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VPNSitesClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VPNSitesClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *VPNSitesClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject, options *VPNSitesClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}" + 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 vpnSiteName == "" { + return nil, errors.New("parameter vpnSiteName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vpnSiteName}", url.PathEscape(vpnSiteName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vpnSiteParameters); err != nil { + return nil, err + } + return req, nil +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *VPNSitesClient) updateTagsHandleResponse(resp *http.Response) (VPNSitesClientUpdateTagsResponse, error) { + result := VPNSitesClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VPNSite); err != nil { + return VPNSitesClientUpdateTagsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitesconfiguration_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitesconfiguration_client.go new file mode 100644 index 000000000..ae821016a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/vpnsitesconfiguration_client.go @@ -0,0 +1,126 @@ +//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 armnetwork + +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" +) + +// VPNSitesConfigurationClient contains the methods for the VPNSitesConfiguration group. +// Don't use this type directly, use NewVPNSitesConfigurationClient() instead. +type VPNSitesConfigurationClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVPNSitesConfigurationClient creates a new instance of VPNSitesConfigurationClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewVPNSitesConfigurationClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VPNSitesConfigurationClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VPNSitesConfigurationClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginDownload - Gives the sas-url to download the configurations for vpn-sites in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The resource group name. +// - virtualWANName - The name of the VirtualWAN for which configuration of all vpn-sites is needed. +// - request - Parameters supplied to download vpn-sites configuration. +// - options - VPNSitesConfigurationClientBeginDownloadOptions contains the optional parameters for the VPNSitesConfigurationClient.BeginDownload +// method. +func (client *VPNSitesConfigurationClient) BeginDownload(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVPNSitesConfigurationRequest, options *VPNSitesConfigurationClientBeginDownloadOptions) (*runtime.Poller[VPNSitesConfigurationClientDownloadResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.download(ctx, resourceGroupName, virtualWANName, request, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VPNSitesConfigurationClientDownloadResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VPNSitesConfigurationClientDownloadResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Download - Gives the sas-url to download the configurations for vpn-sites in a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *VPNSitesConfigurationClient) download(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVPNSitesConfigurationRequest, options *VPNSitesConfigurationClientBeginDownloadOptions) (*http.Response, error) { + var err error + const operationName = "VPNSitesConfigurationClient.BeginDownload" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.downloadCreateRequest(ctx, resourceGroupName, virtualWANName, request, 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 +} + +// downloadCreateRequest creates the Download request. +func (client *VPNSitesConfigurationClient) downloadCreateRequest(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVPNSitesConfigurationRequest, options *VPNSitesConfigurationClientBeginDownloadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration" + 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 virtualWANName == "" { + return nil, errors.New("parameter virtualWANName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualWANName}", url.PathEscape(virtualWANName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, request); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/watchers_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/watchers_client.go new file mode 100644 index 000000000..b29eebfb1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/watchers_client.go @@ -0,0 +1,1409 @@ +//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 armnetwork + +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" +) + +// WatchersClient contains the methods for the NetworkWatchers group. +// Don't use this type directly, use NewWatchersClient() instead. +type WatchersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWatchersClient creates a new instance of WatchersClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewWatchersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WatchersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WatchersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCheckConnectivity - Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given +// endpoint including another VM or an arbitrary remote server. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the network watcher resource group. +// - networkWatcherName - The name of the network watcher resource. +// - parameters - Parameters that determine how the connectivity check will be performed. +// - options - WatchersClientBeginCheckConnectivityOptions contains the optional parameters for the WatchersClient.BeginCheckConnectivity +// method. +func (client *WatchersClient) BeginCheckConnectivity(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters, options *WatchersClientBeginCheckConnectivityOptions) (*runtime.Poller[WatchersClientCheckConnectivityResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.checkConnectivity(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientCheckConnectivityResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientCheckConnectivityResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CheckConnectivity - Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given +// endpoint including another VM or an arbitrary remote server. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) checkConnectivity(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters, options *WatchersClientBeginCheckConnectivityOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginCheckConnectivity" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkConnectivityCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// checkConnectivityCreateRequest creates the CheckConnectivity request. +func (client *WatchersClient) checkConnectivityCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters, options *WatchersClientBeginCheckConnectivityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectivityCheck" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// CreateOrUpdate - Creates or updates a network watcher in the specified resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - parameters - Parameters that define the network watcher resource. +// - options - WatchersClientCreateOrUpdateOptions contains the optional parameters for the WatchersClient.CreateOrUpdate method. +func (client *WatchersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters Watcher, options *WatchersClientCreateOrUpdateOptions) (WatchersClientCreateOrUpdateResponse, error) { + var err error + const operationName = "WatchersClient.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, networkWatcherName, parameters, options) + if err != nil { + return WatchersClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WatchersClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return WatchersClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *WatchersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters Watcher, options *WatchersClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 *WatchersClient) createOrUpdateHandleResponse(resp *http.Response) (WatchersClientCreateOrUpdateResponse, error) { + result := WatchersClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Watcher); err != nil { + return WatchersClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified network watcher resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - options - WatchersClientBeginDeleteOptions contains the optional parameters for the WatchersClient.BeginDelete method. +func (client *WatchersClient) BeginDelete(ctx context.Context, resourceGroupName string, networkWatcherName string, options *WatchersClientBeginDeleteOptions) (*runtime.Poller[WatchersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkWatcherName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified network watcher resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) deleteOperation(ctx context.Context, resourceGroupName string, networkWatcherName string, options *WatchersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.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, networkWatcherName, 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 *WatchersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, options *WatchersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified network watcher by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - options - WatchersClientGetOptions contains the optional parameters for the WatchersClient.Get method. +func (client *WatchersClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, options *WatchersClientGetOptions) (WatchersClientGetResponse, error) { + var err error + const operationName = "WatchersClient.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, networkWatcherName, options) + if err != nil { + return WatchersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WatchersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WatchersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *WatchersClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, options *WatchersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WatchersClient) getHandleResponse(resp *http.Response) (WatchersClientGetResponse, error) { + result := WatchersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Watcher); err != nil { + return WatchersClientGetResponse{}, err + } + return result, nil +} + +// BeginGetAzureReachabilityReport - NOTE: This feature is currently in preview and still being tested for stability. Gets +// the relative latency score for internet service providers from a specified location to Azure regions. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the network watcher resource group. +// - networkWatcherName - The name of the network watcher resource. +// - parameters - Parameters that determine Azure reachability report configuration. +// - options - WatchersClientBeginGetAzureReachabilityReportOptions contains the optional parameters for the WatchersClient.BeginGetAzureReachabilityReport +// method. +func (client *WatchersClient) BeginGetAzureReachabilityReport(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters, options *WatchersClientBeginGetAzureReachabilityReportOptions) (*runtime.Poller[WatchersClientGetAzureReachabilityReportResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getAzureReachabilityReport(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientGetAzureReachabilityReportResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientGetAzureReachabilityReportResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetAzureReachabilityReport - NOTE: This feature is currently in preview and still being tested for stability. Gets the +// relative latency score for internet service providers from a specified location to Azure regions. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) getAzureReachabilityReport(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters, options *WatchersClientBeginGetAzureReachabilityReportOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginGetAzureReachabilityReport" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAzureReachabilityReportCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// getAzureReachabilityReportCreateRequest creates the GetAzureReachabilityReport request. +func (client *WatchersClient) getAzureReachabilityReportCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters, options *WatchersClientBeginGetAzureReachabilityReportOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/azureReachabilityReport" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// BeginGetFlowLogStatus - Queries status of flow log and traffic analytics (optional) on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the network watcher resource group. +// - networkWatcherName - The name of the network watcher resource. +// - parameters - Parameters that define a resource to query flow log and traffic analytics (optional) status. +// - options - WatchersClientBeginGetFlowLogStatusOptions contains the optional parameters for the WatchersClient.BeginGetFlowLogStatus +// method. +func (client *WatchersClient) BeginGetFlowLogStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters, options *WatchersClientBeginGetFlowLogStatusOptions) (*runtime.Poller[WatchersClientGetFlowLogStatusResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getFlowLogStatus(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientGetFlowLogStatusResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientGetFlowLogStatusResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetFlowLogStatus - Queries status of flow log and traffic analytics (optional) on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) getFlowLogStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters, options *WatchersClientBeginGetFlowLogStatusOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginGetFlowLogStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFlowLogStatusCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// getFlowLogStatusCreateRequest creates the GetFlowLogStatus request. +func (client *WatchersClient) getFlowLogStatusCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters, options *WatchersClientBeginGetFlowLogStatusOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryFlowLogStatus" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// BeginGetNetworkConfigurationDiagnostic - Gets Network Configuration Diagnostic data to help customers understand and debug +// network behavior. It provides detailed information on what security rules were applied to a specified traffic flow and +// the result of evaluating these rules. Customers must provide details of a flow like source, destination, protocol, etc. +// The API returns whether traffic was allowed or denied, the rules evaluated for +// the specified flow and the evaluation results. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - parameters - Parameters to get network configuration diagnostic. +// - options - WatchersClientBeginGetNetworkConfigurationDiagnosticOptions contains the optional parameters for the WatchersClient.BeginGetNetworkConfigurationDiagnostic +// method. +func (client *WatchersClient) BeginGetNetworkConfigurationDiagnostic(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters, options *WatchersClientBeginGetNetworkConfigurationDiagnosticOptions) (*runtime.Poller[WatchersClientGetNetworkConfigurationDiagnosticResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getNetworkConfigurationDiagnostic(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientGetNetworkConfigurationDiagnosticResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientGetNetworkConfigurationDiagnosticResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetNetworkConfigurationDiagnostic - Gets Network Configuration Diagnostic data to help customers understand and debug network +// behavior. It provides detailed information on what security rules were applied to a specified traffic flow and +// the result of evaluating these rules. Customers must provide details of a flow like source, destination, protocol, etc. +// The API returns whether traffic was allowed or denied, the rules evaluated for +// the specified flow and the evaluation results. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) getNetworkConfigurationDiagnostic(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters, options *WatchersClientBeginGetNetworkConfigurationDiagnosticOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginGetNetworkConfigurationDiagnostic" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNetworkConfigurationDiagnosticCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// getNetworkConfigurationDiagnosticCreateRequest creates the GetNetworkConfigurationDiagnostic request. +func (client *WatchersClient) getNetworkConfigurationDiagnosticCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters, options *WatchersClientBeginGetNetworkConfigurationDiagnosticOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/networkConfigurationDiagnostic" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// BeginGetNextHop - Gets the next hop from the specified VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - parameters - Parameters that define the source and destination endpoint. +// - options - WatchersClientBeginGetNextHopOptions contains the optional parameters for the WatchersClient.BeginGetNextHop +// method. +func (client *WatchersClient) BeginGetNextHop(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters, options *WatchersClientBeginGetNextHopOptions) (*runtime.Poller[WatchersClientGetNextHopResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getNextHop(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientGetNextHopResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientGetNextHopResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetNextHop - Gets the next hop from the specified VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) getNextHop(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters, options *WatchersClientBeginGetNextHopOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginGetNextHop" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNextHopCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// getNextHopCreateRequest creates the GetNextHop request. +func (client *WatchersClient) getNextHopCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters, options *WatchersClientBeginGetNextHopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/nextHop" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// GetTopology - Gets the current network topology by resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - parameters - Parameters that define the representation of topology. +// - options - WatchersClientGetTopologyOptions contains the optional parameters for the WatchersClient.GetTopology method. +func (client *WatchersClient) GetTopology(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TopologyParameters, options *WatchersClientGetTopologyOptions) (WatchersClientGetTopologyResponse, error) { + var err error + const operationName = "WatchersClient.GetTopology" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getTopologyCreateRequest(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return WatchersClientGetTopologyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WatchersClientGetTopologyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WatchersClientGetTopologyResponse{}, err + } + resp, err := client.getTopologyHandleResponse(httpResp) + return resp, err +} + +// getTopologyCreateRequest creates the GetTopology request. +func (client *WatchersClient) getTopologyCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TopologyParameters, options *WatchersClientGetTopologyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/topology" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// getTopologyHandleResponse handles the GetTopology response. +func (client *WatchersClient) getTopologyHandleResponse(resp *http.Response) (WatchersClientGetTopologyResponse, error) { + result := WatchersClientGetTopologyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Topology); err != nil { + return WatchersClientGetTopologyResponse{}, err + } + return result, nil +} + +// BeginGetTroubleshooting - Initiate troubleshooting on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher resource. +// - parameters - Parameters that define the resource to troubleshoot. +// - options - WatchersClientBeginGetTroubleshootingOptions contains the optional parameters for the WatchersClient.BeginGetTroubleshooting +// method. +func (client *WatchersClient) BeginGetTroubleshooting(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters, options *WatchersClientBeginGetTroubleshootingOptions) (*runtime.Poller[WatchersClientGetTroubleshootingResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getTroubleshooting(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientGetTroubleshootingResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientGetTroubleshootingResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetTroubleshooting - Initiate troubleshooting on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) getTroubleshooting(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters, options *WatchersClientBeginGetTroubleshootingOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginGetTroubleshooting" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getTroubleshootingCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// getTroubleshootingCreateRequest creates the GetTroubleshooting request. +func (client *WatchersClient) getTroubleshootingCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters, options *WatchersClientBeginGetTroubleshootingOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/troubleshoot" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// BeginGetTroubleshootingResult - Get the last completed troubleshooting result on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher resource. +// - parameters - Parameters that define the resource to query the troubleshooting result. +// - options - WatchersClientBeginGetTroubleshootingResultOptions contains the optional parameters for the WatchersClient.BeginGetTroubleshootingResult +// method. +func (client *WatchersClient) BeginGetTroubleshootingResult(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters, options *WatchersClientBeginGetTroubleshootingResultOptions) (*runtime.Poller[WatchersClientGetTroubleshootingResultResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getTroubleshootingResult(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientGetTroubleshootingResultResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientGetTroubleshootingResultResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetTroubleshootingResult - Get the last completed troubleshooting result on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) getTroubleshootingResult(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters, options *WatchersClientBeginGetTroubleshootingResultOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginGetTroubleshootingResult" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getTroubleshootingResultCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// getTroubleshootingResultCreateRequest creates the GetTroubleshootingResult request. +func (client *WatchersClient) getTroubleshootingResultCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters, options *WatchersClientBeginGetTroubleshootingResultOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryTroubleshootResult" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// BeginGetVMSecurityRules - Gets the configured and effective security group rules on the specified VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - parameters - Parameters that define the VM to check security groups for. +// - options - WatchersClientBeginGetVMSecurityRulesOptions contains the optional parameters for the WatchersClient.BeginGetVMSecurityRules +// method. +func (client *WatchersClient) BeginGetVMSecurityRules(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters, options *WatchersClientBeginGetVMSecurityRulesOptions) (*runtime.Poller[WatchersClientGetVMSecurityRulesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.getVMSecurityRules(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientGetVMSecurityRulesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientGetVMSecurityRulesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GetVMSecurityRules - Gets the configured and effective security group rules on the specified VM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) getVMSecurityRules(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters, options *WatchersClientBeginGetVMSecurityRulesOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginGetVMSecurityRules" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getVMSecurityRulesCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// getVMSecurityRulesCreateRequest creates the GetVMSecurityRules request. +func (client *WatchersClient) getVMSecurityRulesCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters, options *WatchersClientBeginGetVMSecurityRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/securityGroupView" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// NewListPager - Gets all network watchers by resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - WatchersClientListOptions contains the optional parameters for the WatchersClient.NewListPager method. +func (client *WatchersClient) NewListPager(resourceGroupName string, options *WatchersClientListOptions) *runtime.Pager[WatchersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[WatchersClientListResponse]{ + More: func(page WatchersClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *WatchersClientListResponse) (WatchersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WatchersClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, options) + if err != nil { + return WatchersClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WatchersClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WatchersClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *WatchersClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *WatchersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *WatchersClient) listHandleResponse(resp *http.Response) (WatchersClientListResponse, error) { + result := WatchersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WatcherListResult); err != nil { + return WatchersClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all network watchers by subscription. +// +// Generated from API version 2023-05-01 +// - options - WatchersClientListAllOptions contains the optional parameters for the WatchersClient.NewListAllPager method. +func (client *WatchersClient) NewListAllPager(options *WatchersClientListAllOptions) *runtime.Pager[WatchersClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[WatchersClientListAllResponse]{ + More: func(page WatchersClientListAllResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *WatchersClientListAllResponse) (WatchersClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WatchersClient.NewListAllPager") + req, err := client.listAllCreateRequest(ctx, options) + if err != nil { + return WatchersClientListAllResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WatchersClientListAllResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WatchersClientListAllResponse{}, runtime.NewResponseError(resp) + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *WatchersClient) listAllCreateRequest(ctx context.Context, options *WatchersClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkWatchers" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *WatchersClient) listAllHandleResponse(resp *http.Response) (WatchersClientListAllResponse, error) { + result := WatchersClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WatcherListResult); err != nil { + return WatchersClientListAllResponse{}, err + } + return result, nil +} + +// BeginListAvailableProviders - NOTE: This feature is currently in preview and still being tested for stability. Lists all +// available internet service providers for a specified Azure region. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the network watcher resource group. +// - networkWatcherName - The name of the network watcher resource. +// - parameters - Parameters that scope the list of available providers. +// - options - WatchersClientBeginListAvailableProvidersOptions contains the optional parameters for the WatchersClient.BeginListAvailableProviders +// method. +func (client *WatchersClient) BeginListAvailableProviders(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters, options *WatchersClientBeginListAvailableProvidersOptions) (*runtime.Poller[WatchersClientListAvailableProvidersResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listAvailableProviders(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientListAvailableProvidersResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientListAvailableProvidersResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListAvailableProviders - NOTE: This feature is currently in preview and still being tested for stability. Lists all available +// internet service providers for a specified Azure region. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) listAvailableProviders(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters, options *WatchersClientBeginListAvailableProvidersOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginListAvailableProviders" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAvailableProvidersCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// listAvailableProvidersCreateRequest creates the ListAvailableProviders request. +func (client *WatchersClient) listAvailableProvidersCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters, options *WatchersClientBeginListAvailableProvidersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/availableProvidersList" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// BeginSetFlowLogConfiguration - Configures flow log and traffic analytics (optional) on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the network watcher resource group. +// - networkWatcherName - The name of the network watcher resource. +// - parameters - Parameters that define the configuration of flow log. +// - options - WatchersClientBeginSetFlowLogConfigurationOptions contains the optional parameters for the WatchersClient.BeginSetFlowLogConfiguration +// method. +func (client *WatchersClient) BeginSetFlowLogConfiguration(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation, options *WatchersClientBeginSetFlowLogConfigurationOptions) (*runtime.Poller[WatchersClientSetFlowLogConfigurationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.setFlowLogConfiguration(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientSetFlowLogConfigurationResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientSetFlowLogConfigurationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// SetFlowLogConfiguration - Configures flow log and traffic analytics (optional) on a specified resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) setFlowLogConfiguration(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation, options *WatchersClientBeginSetFlowLogConfigurationOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginSetFlowLogConfiguration" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setFlowLogConfigurationCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// setFlowLogConfigurationCreateRequest creates the SetFlowLogConfiguration request. +func (client *WatchersClient) setFlowLogConfigurationCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation, options *WatchersClientBeginSetFlowLogConfigurationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/configureFlowLog" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// UpdateTags - Updates a network watcher tags. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - parameters - Parameters supplied to update network watcher tags. +// - options - WatchersClientUpdateTagsOptions contains the optional parameters for the WatchersClient.UpdateTags method. +func (client *WatchersClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject, options *WatchersClientUpdateTagsOptions) (WatchersClientUpdateTagsResponse, error) { + var err error + const operationName = "WatchersClient.UpdateTags" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return WatchersClientUpdateTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WatchersClientUpdateTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WatchersClientUpdateTagsResponse{}, err + } + resp, err := client.updateTagsHandleResponse(httpResp) + return resp, err +} + +// updateTagsCreateRequest creates the UpdateTags request. +func (client *WatchersClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject, options *WatchersClientUpdateTagsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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 +} + +// updateTagsHandleResponse handles the UpdateTags response. +func (client *WatchersClient) updateTagsHandleResponse(resp *http.Response) (WatchersClientUpdateTagsResponse, error) { + result := WatchersClientUpdateTagsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Watcher); err != nil { + return WatchersClientUpdateTagsResponse{}, err + } + return result, nil +} + +// BeginVerifyIPFlow - Verify IP flow from the specified VM to a location given the currently configured NSG rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - networkWatcherName - The name of the network watcher. +// - parameters - Parameters that define the IP flow to be verified. +// - options - WatchersClientBeginVerifyIPFlowOptions contains the optional parameters for the WatchersClient.BeginVerifyIPFlow +// method. +func (client *WatchersClient) BeginVerifyIPFlow(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters, options *WatchersClientBeginVerifyIPFlowOptions) (*runtime.Poller[WatchersClientVerifyIPFlowResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.verifyIPFlow(ctx, resourceGroupName, networkWatcherName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientVerifyIPFlowResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientVerifyIPFlowResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// VerifyIPFlow - Verify IP flow from the specified VM to a location given the currently configured NSG rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WatchersClient) verifyIPFlow(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters, options *WatchersClientBeginVerifyIPFlowOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginVerifyIPFlow" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.verifyIPFlowCreateRequest(ctx, resourceGroupName, networkWatcherName, 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 +} + +// verifyIPFlowCreateRequest creates the VerifyIPFlow request. +func (client *WatchersClient) verifyIPFlowCreateRequest(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters, options *WatchersClientBeginVerifyIPFlowOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/ipFlowVerify" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkWatcherName == "" { + return nil, errors.New("parameter networkWatcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkWatcherName}", url.PathEscape(networkWatcherName)) + 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-05-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/network/armnetwork/v4/webapplicationfirewallpolicies_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/webapplicationfirewallpolicies_client.go new file mode 100644 index 000000000..eb2154b45 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/webapplicationfirewallpolicies_client.go @@ -0,0 +1,371 @@ +//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 armnetwork + +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" +) + +// WebApplicationFirewallPoliciesClient contains the methods for the WebApplicationFirewallPolicies group. +// Don't use this type directly, use NewWebApplicationFirewallPoliciesClient() instead. +type WebApplicationFirewallPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWebApplicationFirewallPoliciesClient creates a new instance of WebApplicationFirewallPoliciesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewWebApplicationFirewallPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WebApplicationFirewallPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WebApplicationFirewallPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or update policy with specified rule set name within a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - policyName - The name of the policy. +// - parameters - Policy to be created. +// - options - WebApplicationFirewallPoliciesClientCreateOrUpdateOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.CreateOrUpdate +// method. +func (client *WebApplicationFirewallPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy, options *WebApplicationFirewallPoliciesClientCreateOrUpdateOptions) (WebApplicationFirewallPoliciesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "WebApplicationFirewallPoliciesClient.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, policyName, parameters, options) + if err != nil { + return WebApplicationFirewallPoliciesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WebApplicationFirewallPoliciesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return WebApplicationFirewallPoliciesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *WebApplicationFirewallPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy, options *WebApplicationFirewallPoliciesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if policyName == "" { + return nil, errors.New("parameter policyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{policyName}", url.PathEscape(policyName)) + 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-05-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 *WebApplicationFirewallPoliciesClient) createOrUpdateHandleResponse(resp *http.Response) (WebApplicationFirewallPoliciesClientCreateOrUpdateResponse, error) { + result := WebApplicationFirewallPoliciesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WebApplicationFirewallPolicy); err != nil { + return WebApplicationFirewallPoliciesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes Policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - policyName - The name of the policy. +// - options - WebApplicationFirewallPoliciesClientBeginDeleteOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.BeginDelete +// method. +func (client *WebApplicationFirewallPoliciesClient) BeginDelete(ctx context.Context, resourceGroupName string, policyName string, options *WebApplicationFirewallPoliciesClientBeginDeleteOptions) (*runtime.Poller[WebApplicationFirewallPoliciesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, policyName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WebApplicationFirewallPoliciesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WebApplicationFirewallPoliciesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes Policy. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +func (client *WebApplicationFirewallPoliciesClient) deleteOperation(ctx context.Context, resourceGroupName string, policyName string, options *WebApplicationFirewallPoliciesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "WebApplicationFirewallPoliciesClient.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, policyName, 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 *WebApplicationFirewallPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, policyName string, options *WebApplicationFirewallPoliciesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if policyName == "" { + return nil, errors.New("parameter policyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{policyName}", url.PathEscape(policyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieve protection policy with specified name within a resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - policyName - The name of the policy. +// - options - WebApplicationFirewallPoliciesClientGetOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.Get +// method. +func (client *WebApplicationFirewallPoliciesClient) Get(ctx context.Context, resourceGroupName string, policyName string, options *WebApplicationFirewallPoliciesClientGetOptions) (WebApplicationFirewallPoliciesClientGetResponse, error) { + var err error + const operationName = "WebApplicationFirewallPoliciesClient.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, policyName, options) + if err != nil { + return WebApplicationFirewallPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WebApplicationFirewallPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WebApplicationFirewallPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *WebApplicationFirewallPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, policyName string, options *WebApplicationFirewallPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if policyName == "" { + return nil, errors.New("parameter policyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{policyName}", url.PathEscape(policyName)) + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WebApplicationFirewallPoliciesClient) getHandleResponse(resp *http.Response) (WebApplicationFirewallPoliciesClientGetResponse, error) { + result := WebApplicationFirewallPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WebApplicationFirewallPolicy); err != nil { + return WebApplicationFirewallPoliciesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all of the protection policies within a resource group. +// +// Generated from API version 2023-05-01 +// - resourceGroupName - The name of the resource group. +// - options - WebApplicationFirewallPoliciesClientListOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.NewListPager +// method. +func (client *WebApplicationFirewallPoliciesClient) NewListPager(resourceGroupName string, options *WebApplicationFirewallPoliciesClientListOptions) *runtime.Pager[WebApplicationFirewallPoliciesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[WebApplicationFirewallPoliciesClientListResponse]{ + More: func(page WebApplicationFirewallPoliciesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WebApplicationFirewallPoliciesClientListResponse) (WebApplicationFirewallPoliciesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WebApplicationFirewallPoliciesClient.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, options) + }, nil) + if err != nil { + return WebApplicationFirewallPoliciesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *WebApplicationFirewallPoliciesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *WebApplicationFirewallPoliciesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *WebApplicationFirewallPoliciesClient) listHandleResponse(resp *http.Response) (WebApplicationFirewallPoliciesClientListResponse, error) { + result := WebApplicationFirewallPoliciesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WebApplicationFirewallPolicyListResult); err != nil { + return WebApplicationFirewallPoliciesClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - Gets all the WAF policies in a subscription. +// +// Generated from API version 2023-05-01 +// - options - WebApplicationFirewallPoliciesClientListAllOptions contains the optional parameters for the WebApplicationFirewallPoliciesClient.NewListAllPager +// method. +func (client *WebApplicationFirewallPoliciesClient) NewListAllPager(options *WebApplicationFirewallPoliciesClientListAllOptions) *runtime.Pager[WebApplicationFirewallPoliciesClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[WebApplicationFirewallPoliciesClientListAllResponse]{ + More: func(page WebApplicationFirewallPoliciesClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WebApplicationFirewallPoliciesClientListAllResponse) (WebApplicationFirewallPoliciesClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WebApplicationFirewallPoliciesClient.NewListAllPager") + 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.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return WebApplicationFirewallPoliciesClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *WebApplicationFirewallPoliciesClient) listAllCreateRequest(ctx context.Context, options *WebApplicationFirewallPoliciesClientListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *WebApplicationFirewallPoliciesClient) listAllHandleResponse(resp *http.Response) (WebApplicationFirewallPoliciesClientListAllResponse, error) { + result := WebApplicationFirewallPoliciesClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WebApplicationFirewallPolicyListResult); err != nil { + return WebApplicationFirewallPoliciesClientListAllResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/webcategories_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/webcategories_client.go new file mode 100644 index 000000000..26f7c27a7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4/webcategories_client.go @@ -0,0 +1,162 @@ +//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 armnetwork + +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" +) + +// WebCategoriesClient contains the methods for the WebCategories group. +// Don't use this type directly, use NewWebCategoriesClient() instead. +type WebCategoriesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWebCategoriesClient creates a new instance of WebCategoriesClient with the specified values. +// - subscriptionID - The subscription credentials which uniquely identify the 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 NewWebCategoriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WebCategoriesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WebCategoriesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the specified Azure Web Category. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-05-01 +// - name - The name of the azureWebCategory. +// - options - WebCategoriesClientGetOptions contains the optional parameters for the WebCategoriesClient.Get method. +func (client *WebCategoriesClient) Get(ctx context.Context, name string, options *WebCategoriesClientGetOptions) (WebCategoriesClientGetResponse, error) { + var err error + const operationName = "WebCategoriesClient.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, name, options) + if err != nil { + return WebCategoriesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WebCategoriesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WebCategoriesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *WebCategoriesClient) getCreateRequest(ctx context.Context, name string, options *WebCategoriesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureWebCategories/{name}" + 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-05-01") + 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 +} + +// getHandleResponse handles the Get response. +func (client *WebCategoriesClient) getHandleResponse(resp *http.Response) (WebCategoriesClientGetResponse, error) { + result := WebCategoriesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureWebCategory); err != nil { + return WebCategoriesClientGetResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Gets all the Azure Web Categories in a subscription. +// +// Generated from API version 2023-05-01 +// - options - WebCategoriesClientListBySubscriptionOptions contains the optional parameters for the WebCategoriesClient.NewListBySubscriptionPager +// method. +func (client *WebCategoriesClient) NewListBySubscriptionPager(options *WebCategoriesClientListBySubscriptionOptions) *runtime.Pager[WebCategoriesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[WebCategoriesClientListBySubscriptionResponse]{ + More: func(page WebCategoriesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WebCategoriesClientListBySubscriptionResponse) (WebCategoriesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WebCategoriesClient.NewListBySubscriptionPager") + 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.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return WebCategoriesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *WebCategoriesClient) listBySubscriptionCreateRequest(ctx context.Context, options *WebCategoriesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureWebCategories" + 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-05-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *WebCategoriesClient) listBySubscriptionHandleResponse(resp *http.Response) (WebCategoriesClientListBySubscriptionResponse, error) { + result := WebCategoriesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureWebCategoryListResult); err != nil { + return WebCategoriesClientListBySubscriptionResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/CHANGELOG.md deleted file mode 100644 index 52911e4cc..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/_meta.json deleted file mode 100644 index e6ac6c440..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "3c764635e7d442b3e74caf593029fcd440b3ef82", - "readme": "/_/azure-rest-api-specs/specification/compute/resource-manager/readme.md", - "tag": "package-2018-10-01", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2018-10-01 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION /_/azure-rest-api-specs/specification/compute/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/availabilitysets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/availabilitysets.go deleted file mode 100644 index 8c5fed693..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/availabilitysets.go +++ /dev/null @@ -1,652 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailabilitySetsClient is the compute Client -type AvailabilitySetsClient struct { - BaseClient -} - -// NewAvailabilitySetsClient creates an instance of the AvailabilitySetsClient client. -func NewAvailabilitySetsClient(subscriptionID string) AvailabilitySetsClient { - return NewAvailabilitySetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailabilitySetsClientWithBaseURI creates an instance of the AvailabilitySetsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewAvailabilitySetsClientWithBaseURI(baseURI string, subscriptionID string) AvailabilitySetsClient { - return AvailabilitySetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update an availability set. -// Parameters: -// resourceGroupName - the name of the resource group. -// availabilitySetName - the name of the availability set. -// parameters - parameters supplied to the Create Availability Set operation. -func (client AvailabilitySetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySet) (result AvailabilitySet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, availabilitySetName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AvailabilitySetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySet) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "availabilitySetName": autorest.Encode("path", availabilitySetName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client AvailabilitySetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AvailabilitySetsClient) CreateOrUpdateResponder(resp *http.Response) (result AvailabilitySet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete an availability set. -// Parameters: -// resourceGroupName - the name of the resource group. -// availabilitySetName - the name of the availability set. -func (client AvailabilitySetsClient) Delete(ctx context.Context, resourceGroupName string, availabilitySetName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, availabilitySetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AvailabilitySetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, availabilitySetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "availabilitySetName": autorest.Encode("path", availabilitySetName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client AvailabilitySetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves information about an availability set. -// Parameters: -// resourceGroupName - the name of the resource group. -// availabilitySetName - the name of the availability set. -func (client AvailabilitySetsClient) Get(ctx context.Context, resourceGroupName string, availabilitySetName string) (result AvailabilitySet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, availabilitySetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AvailabilitySetsClient) GetPreparer(ctx context.Context, resourceGroupName string, availabilitySetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "availabilitySetName": autorest.Encode("path", availabilitySetName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client AvailabilitySetsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AvailabilitySetsClient) GetResponder(resp *http.Response) (result AvailabilitySet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all availability sets in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client AvailabilitySetsClient) List(ctx context.Context, resourceGroupName string) (result AvailabilitySetListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.List") - defer func() { - sc := -1 - if result.aslr.Response.Response != nil { - sc = result.aslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.aslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending request") - return - } - - result.aslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure responding to request") - return - } - if result.aslr.hasNextLink() && result.aslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailabilitySetsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailabilitySetsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailabilitySetsClient) ListResponder(resp *http.Response) (result AvailabilitySetListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client AvailabilitySetsClient) listNextResults(ctx context.Context, lastResults AvailabilitySetListResult) (result AvailabilitySetListResult, err error) { - req, err := lastResults.availabilitySetListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailabilitySetsClient) ListComplete(ctx context.Context, resourceGroupName string) (result AvailabilitySetListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAvailableSizes lists all available virtual machine sizes that can be used to create a new virtual machine in an -// existing availability set. -// Parameters: -// resourceGroupName - the name of the resource group. -// availabilitySetName - the name of the availability set. -func (client AvailabilitySetsClient) ListAvailableSizes(ctx context.Context, resourceGroupName string, availabilitySetName string) (result VirtualMachineSizeListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.ListAvailableSizes") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableSizesPreparer(ctx, resourceGroupName, availabilitySetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableSizesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableSizesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableSizesPreparer prepares the ListAvailableSizes request. -func (client AvailabilitySetsClient) ListAvailableSizesPreparer(ctx context.Context, resourceGroupName string, availabilitySetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "availabilitySetName": autorest.Encode("path", availabilitySetName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}/vmSizes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableSizesSender sends the ListAvailableSizes request. The method will close the -// http.Response Body if it receives an error. -func (client AvailabilitySetsClient) ListAvailableSizesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableSizesResponder handles the response to the ListAvailableSizes request. The method always -// closes the http.Response Body. -func (client AvailabilitySetsClient) ListAvailableSizesResponder(resp *http.Response) (result VirtualMachineSizeListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListBySubscription lists all availability sets in a subscription. -// Parameters: -// expand - the expand expression to apply to the operation. Allowed values are 'instanceView'. -func (client AvailabilitySetsClient) ListBySubscription(ctx context.Context, expand string) (result AvailabilitySetListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.ListBySubscription") - defer func() { - sc := -1 - if result.aslr.Response.Response != nil { - sc = result.aslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.aslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.aslr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.aslr.hasNextLink() && result.aslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client AvailabilitySetsClient) ListBySubscriptionPreparer(ctx context.Context, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/availabilitySets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client AvailabilitySetsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client AvailabilitySetsClient) ListBySubscriptionResponder(resp *http.Response) (result AvailabilitySetListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client AvailabilitySetsClient) listBySubscriptionNextResults(ctx context.Context, lastResults AvailabilitySetListResult) (result AvailabilitySetListResult, err error) { - req, err := lastResults.availabilitySetListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailabilitySetsClient) ListBySubscriptionComplete(ctx context.Context, expand string) (result AvailabilitySetListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx, expand) - return -} - -// Update update an availability set. -// Parameters: -// resourceGroupName - the name of the resource group. -// availabilitySetName - the name of the availability set. -// parameters - parameters supplied to the Update Availability Set operation. -func (client AvailabilitySetsClient) Update(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySetUpdate) (result AvailabilitySet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetsClient.Update") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, availabilitySetName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Update", resp, "Failure responding to request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client AvailabilitySetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, availabilitySetName string, parameters AvailabilitySetUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "availabilitySetName": autorest.Encode("path", availabilitySetName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client AvailabilitySetsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client AvailabilitySetsClient) UpdateResponder(resp *http.Response) (result AvailabilitySet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/client.go deleted file mode 100644 index 1812f27fe..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/client.go +++ /dev/null @@ -1,41 +0,0 @@ -// Package compute implements the Azure ARM Compute service API version . -// -// Compute Client -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/Azure/go-autorest/autorest" -) - -const ( - // DefaultBaseURI is the default URI used for the service Compute - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Compute. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string -} - -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, - } -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/containerservices.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/containerservices.go deleted file mode 100644 index b1c854615..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/containerservices.go +++ /dev/null @@ -1,538 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ContainerServicesClient is the compute Client -type ContainerServicesClient struct { - BaseClient -} - -// NewContainerServicesClient creates an instance of the ContainerServicesClient client. -func NewContainerServicesClient(subscriptionID string) ContainerServicesClient { - return NewContainerServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewContainerServicesClientWithBaseURI creates an instance of the ContainerServicesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewContainerServicesClientWithBaseURI(baseURI string, subscriptionID string) ContainerServicesClient { - return ContainerServicesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a container service with the specified configuration of orchestrator, masters, and -// agents. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerServiceName - the name of the container service in the specified subscription and resource group. -// parameters - parameters supplied to the Create or Update a Container Service operation. -func (client ContainerServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, containerServiceName string, parameters ContainerService) (result ContainerServicesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServicesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ContainerServiceProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.CustomProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.CustomProfile.Orchestrator", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.ContainerServiceProperties.ServicePrincipalProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.ServicePrincipalProfile.ClientID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ContainerServiceProperties.ServicePrincipalProfile.Secret", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "parameters.ContainerServiceProperties.MasterProfile", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.MasterProfile.DNSPrefix", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.ContainerServiceProperties.AgentPoolProfiles", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ContainerServiceProperties.WindowsProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.WindowsProfile.AdminUsername", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.WindowsProfile.AdminUsername", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$`, Chain: nil}}}, - {Target: "parameters.ContainerServiceProperties.WindowsProfile.AdminPassword", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "parameters.ContainerServiceProperties.LinuxProfile", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.LinuxProfile.AdminUsername", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.LinuxProfile.AdminUsername", Name: validation.Pattern, Rule: `^[a-z][a-z0-9_-]*$`, Chain: nil}}}, - {Target: "parameters.ContainerServiceProperties.LinuxProfile.SSH", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.LinuxProfile.SSH.PublicKeys", Name: validation.Null, Rule: true, Chain: nil}}}, - }}, - {Target: "parameters.ContainerServiceProperties.DiagnosticsProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.DiagnosticsProfile.VMDiagnostics", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ContainerServiceProperties.DiagnosticsProfile.VMDiagnostics.Enabled", Name: validation.Null, Rule: true, Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("compute.ContainerServicesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, containerServiceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ContainerServicesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, containerServiceName string, parameters ContainerService) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerServiceName": autorest.Encode("path", containerServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-01-31" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices/{containerServiceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerServicesClient) CreateOrUpdateSender(req *http.Request) (future ContainerServicesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ContainerServicesClient) CreateOrUpdateResponder(resp *http.Response) (result ContainerService, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified container service in the specified subscription and resource group. The operation does -// not delete other resources created as part of creating a container service, including storage accounts, VMs, and -// availability sets. All the other resources created with the container service are part of the same resource group -// and can be deleted individually. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerServiceName - the name of the container service in the specified subscription and resource group. -func (client ContainerServicesClient) Delete(ctx context.Context, resourceGroupName string, containerServiceName string) (result ContainerServicesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServicesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, containerServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ContainerServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, containerServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerServiceName": autorest.Encode("path", containerServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-01-31" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices/{containerServiceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerServicesClient) DeleteSender(req *http.Request) (future ContainerServicesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ContainerServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the properties of the specified container service in the specified subscription and resource group. The -// operation returns the properties including state, orchestrator, number of masters and agents, and FQDNs of masters -// and agents. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerServiceName - the name of the container service in the specified subscription and resource group. -func (client ContainerServicesClient) Get(ctx context.Context, resourceGroupName string, containerServiceName string) (result ContainerService, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServicesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, containerServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ContainerServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, containerServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerServiceName": autorest.Encode("path", containerServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-01-31" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices/{containerServiceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerServicesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ContainerServicesClient) GetResponder(resp *http.Response) (result ContainerService, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets a list of container services in the specified subscription. The operation returns properties of each -// container service including state, orchestrator, number of masters and agents, and FQDNs of masters and agents. -func (client ContainerServicesClient) List(ctx context.Context) (result ContainerServiceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServicesClient.List") - defer func() { - sc := -1 - if result.cslr.Response.Response != nil { - sc = result.cslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.cslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "List", resp, "Failure sending request") - return - } - - result.cslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "List", resp, "Failure responding to request") - return - } - if result.cslr.hasNextLink() && result.cslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ContainerServicesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-01-31" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/containerServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerServicesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ContainerServicesClient) ListResponder(resp *http.Response) (result ContainerServiceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ContainerServicesClient) listNextResults(ctx context.Context, lastResults ContainerServiceListResult) (result ContainerServiceListResult, err error) { - req, err := lastResults.containerServiceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ContainerServicesClient) ListComplete(ctx context.Context) (result ContainerServiceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServicesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets a list of container services in the specified subscription and resource group. The -// operation returns properties of each container service including state, orchestrator, number of masters and agents, -// and FQDNs of masters and agents. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ContainerServicesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ContainerServiceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServicesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.cslr.Response.Response != nil { - sc = result.cslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.cslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.cslr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.cslr.hasNextLink() && result.cslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ContainerServicesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-01-31" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerServicesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ContainerServicesClient) ListByResourceGroupResponder(resp *http.Response) (result ContainerServiceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ContainerServicesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ContainerServiceListResult) (result ContainerServiceListResult, err error) { - req, err := lastResults.containerServiceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ContainerServicesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ContainerServiceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServicesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/disks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/disks.go deleted file mode 100644 index 6799ee09c..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/disks.go +++ /dev/null @@ -1,779 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DisksClient is the compute Client -type DisksClient struct { - BaseClient -} - -// NewDisksClient creates an instance of the DisksClient client. -func NewDisksClient(subscriptionID string) DisksClient { - return NewDisksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDisksClientWithBaseURI creates an instance of the DisksClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewDisksClientWithBaseURI(baseURI string, subscriptionID string) DisksClient { - return DisksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a disk. -// Parameters: -// resourceGroupName - the name of the resource group. -// diskName - the name of the managed disk that is being created. The name can't be changed after the disk is -// created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 -// characters. -// disk - disk object supplied in the body of the Put disk operation. -func (client DisksClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, diskName string, disk Disk) (result DisksCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: disk, - Constraints: []validation.Constraint{{Target: "disk.DiskProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "disk.DiskProperties.CreationData", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "disk.DiskProperties.CreationData.ImageReference", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "disk.DiskProperties.CreationData.ImageReference.ID", Name: validation.Null, Rule: true, Chain: nil}}}, - }}, - {Target: "disk.DiskProperties.EncryptionSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "disk.DiskProperties.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "disk.DiskProperties.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "disk.DiskProperties.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "disk.DiskProperties.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "disk.DiskProperties.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "disk.DiskProperties.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("compute.DisksClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, diskName, disk) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DisksClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, diskName string, disk Disk) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "diskName": autorest.Encode("path", diskName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - disk.ManagedBy = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), - autorest.WithJSON(disk), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) CreateOrUpdateSender(req *http.Request) (future DisksCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DisksClient) CreateOrUpdateResponder(resp *http.Response) (result Disk, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a disk. -// Parameters: -// resourceGroupName - the name of the resource group. -// diskName - the name of the managed disk that is being created. The name can't be changed after the disk is -// created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 -// characters. -func (client DisksClient) Delete(ctx context.Context, resourceGroupName string, diskName string) (result DisksDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, diskName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DisksClient) DeletePreparer(ctx context.Context, resourceGroupName string, diskName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "diskName": autorest.Encode("path", diskName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) DeleteSender(req *http.Request) (future DisksDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DisksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about a disk. -// Parameters: -// resourceGroupName - the name of the resource group. -// diskName - the name of the managed disk that is being created. The name can't be changed after the disk is -// created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 -// characters. -func (client DisksClient) Get(ctx context.Context, resourceGroupName string, diskName string) (result Disk, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, diskName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.DisksClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DisksClient) GetPreparer(ctx context.Context, resourceGroupName string, diskName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "diskName": autorest.Encode("path", diskName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DisksClient) GetResponder(resp *http.Response) (result Disk, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GrantAccess grants access to a disk. -// Parameters: -// resourceGroupName - the name of the resource group. -// diskName - the name of the managed disk that is being created. The name can't be changed after the disk is -// created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 -// characters. -// grantAccessData - access data object supplied in the body of the get disk access operation. -func (client DisksClient) GrantAccess(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData) (result DisksGrantAccessFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.GrantAccess") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: grantAccessData, - Constraints: []validation.Constraint{{Target: "grantAccessData.DurationInSeconds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.DisksClient", "GrantAccess", err.Error()) - } - - req, err := client.GrantAccessPreparer(ctx, resourceGroupName, diskName, grantAccessData) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "GrantAccess", nil, "Failure preparing request") - return - } - - result, err = client.GrantAccessSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "GrantAccess", result.Response(), "Failure sending request") - return - } - - return -} - -// GrantAccessPreparer prepares the GrantAccess request. -func (client DisksClient) GrantAccessPreparer(ctx context.Context, resourceGroupName string, diskName string, grantAccessData GrantAccessData) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "diskName": autorest.Encode("path", diskName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/beginGetAccess", pathParameters), - autorest.WithJSON(grantAccessData), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GrantAccessSender sends the GrantAccess request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) GrantAccessSender(req *http.Request) (future DisksGrantAccessFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GrantAccessResponder handles the response to the GrantAccess request. The method always -// closes the http.Response Body. -func (client DisksClient) GrantAccessResponder(resp *http.Response) (result AccessURI, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the disks under a subscription. -func (client DisksClient) List(ctx context.Context) (result DiskListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.List") - defer func() { - sc := -1 - if result.dl.Response.Response != nil { - sc = result.dl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.dl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.DisksClient", "List", resp, "Failure sending request") - return - } - - result.dl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "List", resp, "Failure responding to request") - return - } - if result.dl.hasNextLink() && result.dl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DisksClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/disks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DisksClient) ListResponder(resp *http.Response) (result DiskList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client DisksClient) listNextResults(ctx context.Context, lastResults DiskList) (result DiskList, err error) { - req, err := lastResults.diskListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.DisksClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.DisksClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client DisksClient) ListComplete(ctx context.Context) (result DiskListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the disks under a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client DisksClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result DiskListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.dl.Response.Response != nil { - sc = result.dl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.dl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.DisksClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.dl, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.dl.hasNextLink() && result.dl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client DisksClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client DisksClient) ListByResourceGroupResponder(resp *http.Response) (result DiskList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client DisksClient) listByResourceGroupNextResults(ctx context.Context, lastResults DiskList) (result DiskList, err error) { - req, err := lastResults.diskListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.DisksClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.DisksClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client DisksClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result DiskListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// RevokeAccess revokes access to a disk. -// Parameters: -// resourceGroupName - the name of the resource group. -// diskName - the name of the managed disk that is being created. The name can't be changed after the disk is -// created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 -// characters. -func (client DisksClient) RevokeAccess(ctx context.Context, resourceGroupName string, diskName string) (result DisksRevokeAccessFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.RevokeAccess") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RevokeAccessPreparer(ctx, resourceGroupName, diskName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "RevokeAccess", nil, "Failure preparing request") - return - } - - result, err = client.RevokeAccessSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "RevokeAccess", result.Response(), "Failure sending request") - return - } - - return -} - -// RevokeAccessPreparer prepares the RevokeAccess request. -func (client DisksClient) RevokeAccessPreparer(ctx context.Context, resourceGroupName string, diskName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "diskName": autorest.Encode("path", diskName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}/endGetAccess", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RevokeAccessSender sends the RevokeAccess request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) RevokeAccessSender(req *http.Request) (future DisksRevokeAccessFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RevokeAccessResponder handles the response to the RevokeAccess request. The method always -// closes the http.Response Body. -func (client DisksClient) RevokeAccessResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update updates (patches) a disk. -// Parameters: -// resourceGroupName - the name of the resource group. -// diskName - the name of the managed disk that is being created. The name can't be changed after the disk is -// created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 -// characters. -// disk - disk object supplied in the body of the Patch disk operation. -func (client DisksClient) Update(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate) (result DisksUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, diskName, disk) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client DisksClient) UpdatePreparer(ctx context.Context, resourceGroupName string, diskName string, disk DiskUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "diskName": autorest.Encode("path", diskName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}", pathParameters), - autorest.WithJSON(disk), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client DisksClient) UpdateSender(req *http.Request) (future DisksUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client DisksClient) UpdateResponder(resp *http.Response) (result Disk, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/enums.go deleted file mode 100644 index 4ff08cdd5..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/enums.go +++ /dev/null @@ -1,1148 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// AccessLevel enumerates the values for access level. -type AccessLevel string - -const ( - // None ... - None AccessLevel = "None" - // Read ... - Read AccessLevel = "Read" -) - -// PossibleAccessLevelValues returns an array of possible values for the AccessLevel const type. -func PossibleAccessLevelValues() []AccessLevel { - return []AccessLevel{None, Read} -} - -// AggregatedReplicationState enumerates the values for aggregated replication state. -type AggregatedReplicationState string - -const ( - // Completed ... - Completed AggregatedReplicationState = "Completed" - // Failed ... - Failed AggregatedReplicationState = "Failed" - // InProgress ... - InProgress AggregatedReplicationState = "InProgress" - // Unknown ... - Unknown AggregatedReplicationState = "Unknown" -) - -// PossibleAggregatedReplicationStateValues returns an array of possible values for the AggregatedReplicationState const type. -func PossibleAggregatedReplicationStateValues() []AggregatedReplicationState { - return []AggregatedReplicationState{Completed, Failed, InProgress, Unknown} -} - -// AvailabilitySetSkuTypes enumerates the values for availability set sku types. -type AvailabilitySetSkuTypes string - -const ( - // Aligned ... - Aligned AvailabilitySetSkuTypes = "Aligned" - // Classic ... - Classic AvailabilitySetSkuTypes = "Classic" -) - -// PossibleAvailabilitySetSkuTypesValues returns an array of possible values for the AvailabilitySetSkuTypes const type. -func PossibleAvailabilitySetSkuTypesValues() []AvailabilitySetSkuTypes { - return []AvailabilitySetSkuTypes{Aligned, Classic} -} - -// CachingTypes enumerates the values for caching types. -type CachingTypes string - -const ( - // CachingTypesNone ... - CachingTypesNone CachingTypes = "None" - // CachingTypesReadOnly ... - CachingTypesReadOnly CachingTypes = "ReadOnly" - // CachingTypesReadWrite ... - CachingTypesReadWrite CachingTypes = "ReadWrite" -) - -// PossibleCachingTypesValues returns an array of possible values for the CachingTypes const type. -func PossibleCachingTypesValues() []CachingTypes { - return []CachingTypes{CachingTypesNone, CachingTypesReadOnly, CachingTypesReadWrite} -} - -// ComponentNames enumerates the values for component names. -type ComponentNames string - -const ( - // MicrosoftWindowsShellSetup ... - MicrosoftWindowsShellSetup ComponentNames = "Microsoft-Windows-Shell-Setup" -) - -// PossibleComponentNamesValues returns an array of possible values for the ComponentNames const type. -func PossibleComponentNamesValues() []ComponentNames { - return []ComponentNames{MicrosoftWindowsShellSetup} -} - -// ContainerServiceOrchestratorTypes enumerates the values for container service orchestrator types. -type ContainerServiceOrchestratorTypes string - -const ( - // Custom ... - Custom ContainerServiceOrchestratorTypes = "Custom" - // DCOS ... - DCOS ContainerServiceOrchestratorTypes = "DCOS" - // Kubernetes ... - Kubernetes ContainerServiceOrchestratorTypes = "Kubernetes" - // Swarm ... - Swarm ContainerServiceOrchestratorTypes = "Swarm" -) - -// PossibleContainerServiceOrchestratorTypesValues returns an array of possible values for the ContainerServiceOrchestratorTypes const type. -func PossibleContainerServiceOrchestratorTypesValues() []ContainerServiceOrchestratorTypes { - return []ContainerServiceOrchestratorTypes{Custom, DCOS, Kubernetes, Swarm} -} - -// ContainerServiceVMSizeTypes enumerates the values for container service vm size types. -type ContainerServiceVMSizeTypes string - -const ( - // StandardA0 ... - StandardA0 ContainerServiceVMSizeTypes = "Standard_A0" - // StandardA1 ... - StandardA1 ContainerServiceVMSizeTypes = "Standard_A1" - // StandardA10 ... - StandardA10 ContainerServiceVMSizeTypes = "Standard_A10" - // StandardA11 ... - StandardA11 ContainerServiceVMSizeTypes = "Standard_A11" - // StandardA2 ... - StandardA2 ContainerServiceVMSizeTypes = "Standard_A2" - // StandardA3 ... - StandardA3 ContainerServiceVMSizeTypes = "Standard_A3" - // StandardA4 ... - StandardA4 ContainerServiceVMSizeTypes = "Standard_A4" - // StandardA5 ... - StandardA5 ContainerServiceVMSizeTypes = "Standard_A5" - // StandardA6 ... - StandardA6 ContainerServiceVMSizeTypes = "Standard_A6" - // StandardA7 ... - StandardA7 ContainerServiceVMSizeTypes = "Standard_A7" - // StandardA8 ... - StandardA8 ContainerServiceVMSizeTypes = "Standard_A8" - // StandardA9 ... - StandardA9 ContainerServiceVMSizeTypes = "Standard_A9" - // StandardD1 ... - StandardD1 ContainerServiceVMSizeTypes = "Standard_D1" - // StandardD11 ... - StandardD11 ContainerServiceVMSizeTypes = "Standard_D11" - // StandardD11V2 ... - StandardD11V2 ContainerServiceVMSizeTypes = "Standard_D11_v2" - // StandardD12 ... - StandardD12 ContainerServiceVMSizeTypes = "Standard_D12" - // StandardD12V2 ... - StandardD12V2 ContainerServiceVMSizeTypes = "Standard_D12_v2" - // StandardD13 ... - StandardD13 ContainerServiceVMSizeTypes = "Standard_D13" - // StandardD13V2 ... - StandardD13V2 ContainerServiceVMSizeTypes = "Standard_D13_v2" - // StandardD14 ... - StandardD14 ContainerServiceVMSizeTypes = "Standard_D14" - // StandardD14V2 ... - StandardD14V2 ContainerServiceVMSizeTypes = "Standard_D14_v2" - // StandardD1V2 ... - StandardD1V2 ContainerServiceVMSizeTypes = "Standard_D1_v2" - // StandardD2 ... - StandardD2 ContainerServiceVMSizeTypes = "Standard_D2" - // StandardD2V2 ... - StandardD2V2 ContainerServiceVMSizeTypes = "Standard_D2_v2" - // StandardD3 ... - StandardD3 ContainerServiceVMSizeTypes = "Standard_D3" - // StandardD3V2 ... - StandardD3V2 ContainerServiceVMSizeTypes = "Standard_D3_v2" - // StandardD4 ... - StandardD4 ContainerServiceVMSizeTypes = "Standard_D4" - // StandardD4V2 ... - StandardD4V2 ContainerServiceVMSizeTypes = "Standard_D4_v2" - // StandardD5V2 ... - StandardD5V2 ContainerServiceVMSizeTypes = "Standard_D5_v2" - // StandardDS1 ... - StandardDS1 ContainerServiceVMSizeTypes = "Standard_DS1" - // StandardDS11 ... - StandardDS11 ContainerServiceVMSizeTypes = "Standard_DS11" - // StandardDS12 ... - StandardDS12 ContainerServiceVMSizeTypes = "Standard_DS12" - // StandardDS13 ... - StandardDS13 ContainerServiceVMSizeTypes = "Standard_DS13" - // StandardDS14 ... - StandardDS14 ContainerServiceVMSizeTypes = "Standard_DS14" - // StandardDS2 ... - StandardDS2 ContainerServiceVMSizeTypes = "Standard_DS2" - // StandardDS3 ... - StandardDS3 ContainerServiceVMSizeTypes = "Standard_DS3" - // StandardDS4 ... - StandardDS4 ContainerServiceVMSizeTypes = "Standard_DS4" - // StandardG1 ... - StandardG1 ContainerServiceVMSizeTypes = "Standard_G1" - // StandardG2 ... - StandardG2 ContainerServiceVMSizeTypes = "Standard_G2" - // StandardG3 ... - StandardG3 ContainerServiceVMSizeTypes = "Standard_G3" - // StandardG4 ... - StandardG4 ContainerServiceVMSizeTypes = "Standard_G4" - // StandardG5 ... - StandardG5 ContainerServiceVMSizeTypes = "Standard_G5" - // StandardGS1 ... - StandardGS1 ContainerServiceVMSizeTypes = "Standard_GS1" - // StandardGS2 ... - StandardGS2 ContainerServiceVMSizeTypes = "Standard_GS2" - // StandardGS3 ... - StandardGS3 ContainerServiceVMSizeTypes = "Standard_GS3" - // StandardGS4 ... - StandardGS4 ContainerServiceVMSizeTypes = "Standard_GS4" - // StandardGS5 ... - StandardGS5 ContainerServiceVMSizeTypes = "Standard_GS5" -) - -// PossibleContainerServiceVMSizeTypesValues returns an array of possible values for the ContainerServiceVMSizeTypes const type. -func PossibleContainerServiceVMSizeTypesValues() []ContainerServiceVMSizeTypes { - return []ContainerServiceVMSizeTypes{StandardA0, StandardA1, StandardA10, StandardA11, StandardA2, StandardA3, StandardA4, StandardA5, StandardA6, StandardA7, StandardA8, StandardA9, StandardD1, StandardD11, StandardD11V2, StandardD12, StandardD12V2, StandardD13, StandardD13V2, StandardD14, StandardD14V2, StandardD1V2, StandardD2, StandardD2V2, StandardD3, StandardD3V2, StandardD4, StandardD4V2, StandardD5V2, StandardDS1, StandardDS11, StandardDS12, StandardDS13, StandardDS14, StandardDS2, StandardDS3, StandardDS4, StandardG1, StandardG2, StandardG3, StandardG4, StandardG5, StandardGS1, StandardGS2, StandardGS3, StandardGS4, StandardGS5} -} - -// DiffDiskOptions enumerates the values for diff disk options. -type DiffDiskOptions string - -const ( - // Local ... - Local DiffDiskOptions = "Local" -) - -// PossibleDiffDiskOptionsValues returns an array of possible values for the DiffDiskOptions const type. -func PossibleDiffDiskOptionsValues() []DiffDiskOptions { - return []DiffDiskOptions{Local} -} - -// DiskCreateOption enumerates the values for disk create option. -type DiskCreateOption string - -const ( - // Attach ... - Attach DiskCreateOption = "Attach" - // Copy ... - Copy DiskCreateOption = "Copy" - // Empty ... - Empty DiskCreateOption = "Empty" - // FromImage ... - FromImage DiskCreateOption = "FromImage" - // Import ... - Import DiskCreateOption = "Import" - // Restore ... - Restore DiskCreateOption = "Restore" -) - -// PossibleDiskCreateOptionValues returns an array of possible values for the DiskCreateOption const type. -func PossibleDiskCreateOptionValues() []DiskCreateOption { - return []DiskCreateOption{Attach, Copy, Empty, FromImage, Import, Restore} -} - -// DiskCreateOptionTypes enumerates the values for disk create option types. -type DiskCreateOptionTypes string - -const ( - // DiskCreateOptionTypesAttach ... - DiskCreateOptionTypesAttach DiskCreateOptionTypes = "Attach" - // DiskCreateOptionTypesEmpty ... - DiskCreateOptionTypesEmpty DiskCreateOptionTypes = "Empty" - // DiskCreateOptionTypesFromImage ... - DiskCreateOptionTypesFromImage DiskCreateOptionTypes = "FromImage" -) - -// PossibleDiskCreateOptionTypesValues returns an array of possible values for the DiskCreateOptionTypes const type. -func PossibleDiskCreateOptionTypesValues() []DiskCreateOptionTypes { - return []DiskCreateOptionTypes{DiskCreateOptionTypesAttach, DiskCreateOptionTypesEmpty, DiskCreateOptionTypesFromImage} -} - -// DiskStorageAccountTypes enumerates the values for disk storage account types. -type DiskStorageAccountTypes string - -const ( - // PremiumLRS ... - PremiumLRS DiskStorageAccountTypes = "Premium_LRS" - // StandardLRS ... - StandardLRS DiskStorageAccountTypes = "Standard_LRS" - // StandardSSDLRS ... - StandardSSDLRS DiskStorageAccountTypes = "StandardSSD_LRS" - // UltraSSDLRS ... - UltraSSDLRS DiskStorageAccountTypes = "UltraSSD_LRS" -) - -// PossibleDiskStorageAccountTypesValues returns an array of possible values for the DiskStorageAccountTypes const type. -func PossibleDiskStorageAccountTypesValues() []DiskStorageAccountTypes { - return []DiskStorageAccountTypes{PremiumLRS, StandardLRS, StandardSSDLRS, UltraSSDLRS} -} - -// HostCaching enumerates the values for host caching. -type HostCaching string - -const ( - // HostCachingNone ... - HostCachingNone HostCaching = "None" - // HostCachingReadOnly ... - HostCachingReadOnly HostCaching = "ReadOnly" - // HostCachingReadWrite ... - HostCachingReadWrite HostCaching = "ReadWrite" -) - -// PossibleHostCachingValues returns an array of possible values for the HostCaching const type. -func PossibleHostCachingValues() []HostCaching { - return []HostCaching{HostCachingNone, HostCachingReadOnly, HostCachingReadWrite} -} - -// InstanceViewTypes enumerates the values for instance view types. -type InstanceViewTypes string - -const ( - // InstanceView ... - InstanceView InstanceViewTypes = "instanceView" -) - -// PossibleInstanceViewTypesValues returns an array of possible values for the InstanceViewTypes const type. -func PossibleInstanceViewTypesValues() []InstanceViewTypes { - return []InstanceViewTypes{InstanceView} -} - -// IntervalInMins enumerates the values for interval in mins. -type IntervalInMins string - -const ( - // FiveMins ... - FiveMins IntervalInMins = "FiveMins" - // SixtyMins ... - SixtyMins IntervalInMins = "SixtyMins" - // ThirtyMins ... - ThirtyMins IntervalInMins = "ThirtyMins" - // ThreeMins ... - ThreeMins IntervalInMins = "ThreeMins" -) - -// PossibleIntervalInMinsValues returns an array of possible values for the IntervalInMins const type. -func PossibleIntervalInMinsValues() []IntervalInMins { - return []IntervalInMins{FiveMins, SixtyMins, ThirtyMins, ThreeMins} -} - -// IPVersion enumerates the values for ip version. -type IPVersion string - -const ( - // IPv4 ... - IPv4 IPVersion = "IPv4" - // IPv6 ... - IPv6 IPVersion = "IPv6" -) - -// PossibleIPVersionValues returns an array of possible values for the IPVersion const type. -func PossibleIPVersionValues() []IPVersion { - return []IPVersion{IPv4, IPv6} -} - -// MaintenanceOperationResultCodeTypes enumerates the values for maintenance operation result code types. -type MaintenanceOperationResultCodeTypes string - -const ( - // MaintenanceOperationResultCodeTypesMaintenanceAborted ... - MaintenanceOperationResultCodeTypesMaintenanceAborted MaintenanceOperationResultCodeTypes = "MaintenanceAborted" - // MaintenanceOperationResultCodeTypesMaintenanceCompleted ... - MaintenanceOperationResultCodeTypesMaintenanceCompleted MaintenanceOperationResultCodeTypes = "MaintenanceCompleted" - // MaintenanceOperationResultCodeTypesNone ... - MaintenanceOperationResultCodeTypesNone MaintenanceOperationResultCodeTypes = "None" - // MaintenanceOperationResultCodeTypesRetryLater ... - MaintenanceOperationResultCodeTypesRetryLater MaintenanceOperationResultCodeTypes = "RetryLater" -) - -// PossibleMaintenanceOperationResultCodeTypesValues returns an array of possible values for the MaintenanceOperationResultCodeTypes const type. -func PossibleMaintenanceOperationResultCodeTypesValues() []MaintenanceOperationResultCodeTypes { - return []MaintenanceOperationResultCodeTypes{MaintenanceOperationResultCodeTypesMaintenanceAborted, MaintenanceOperationResultCodeTypesMaintenanceCompleted, MaintenanceOperationResultCodeTypesNone, MaintenanceOperationResultCodeTypesRetryLater} -} - -// OperatingSystemStateTypes enumerates the values for operating system state types. -type OperatingSystemStateTypes string - -const ( - // Generalized ... - Generalized OperatingSystemStateTypes = "Generalized" - // Specialized ... - Specialized OperatingSystemStateTypes = "Specialized" -) - -// PossibleOperatingSystemStateTypesValues returns an array of possible values for the OperatingSystemStateTypes const type. -func PossibleOperatingSystemStateTypesValues() []OperatingSystemStateTypes { - return []OperatingSystemStateTypes{Generalized, Specialized} -} - -// OperatingSystemTypes enumerates the values for operating system types. -type OperatingSystemTypes string - -const ( - // Linux ... - Linux OperatingSystemTypes = "Linux" - // Windows ... - Windows OperatingSystemTypes = "Windows" -) - -// PossibleOperatingSystemTypesValues returns an array of possible values for the OperatingSystemTypes const type. -func PossibleOperatingSystemTypesValues() []OperatingSystemTypes { - return []OperatingSystemTypes{Linux, Windows} -} - -// PassNames enumerates the values for pass names. -type PassNames string - -const ( - // OobeSystem ... - OobeSystem PassNames = "OobeSystem" -) - -// PossiblePassNamesValues returns an array of possible values for the PassNames const type. -func PossiblePassNamesValues() []PassNames { - return []PassNames{OobeSystem} -} - -// ProtocolTypes enumerates the values for protocol types. -type ProtocolTypes string - -const ( - // HTTP ... - HTTP ProtocolTypes = "Http" - // HTTPS ... - HTTPS ProtocolTypes = "Https" -) - -// PossibleProtocolTypesValues returns an array of possible values for the ProtocolTypes const type. -func PossibleProtocolTypesValues() []ProtocolTypes { - return []ProtocolTypes{HTTP, HTTPS} -} - -// ProvisioningState enumerates the values for provisioning state. -type ProvisioningState string - -const ( - // ProvisioningStateCreating ... - ProvisioningStateCreating ProvisioningState = "Creating" - // ProvisioningStateDeleting ... - ProvisioningStateDeleting ProvisioningState = "Deleting" - // ProvisioningStateFailed ... - ProvisioningStateFailed ProvisioningState = "Failed" - // ProvisioningStateMigrating ... - ProvisioningStateMigrating ProvisioningState = "Migrating" - // ProvisioningStateSucceeded ... - ProvisioningStateSucceeded ProvisioningState = "Succeeded" - // ProvisioningStateUpdating ... - ProvisioningStateUpdating ProvisioningState = "Updating" -) - -// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. -func PossibleProvisioningStateValues() []ProvisioningState { - return []ProvisioningState{ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateMigrating, ProvisioningStateSucceeded, ProvisioningStateUpdating} -} - -// ProvisioningState1 enumerates the values for provisioning state 1. -type ProvisioningState1 string - -const ( - // ProvisioningState1Creating ... - ProvisioningState1Creating ProvisioningState1 = "Creating" - // ProvisioningState1Deleting ... - ProvisioningState1Deleting ProvisioningState1 = "Deleting" - // ProvisioningState1Failed ... - ProvisioningState1Failed ProvisioningState1 = "Failed" - // ProvisioningState1Migrating ... - ProvisioningState1Migrating ProvisioningState1 = "Migrating" - // ProvisioningState1Succeeded ... - ProvisioningState1Succeeded ProvisioningState1 = "Succeeded" - // ProvisioningState1Updating ... - ProvisioningState1Updating ProvisioningState1 = "Updating" -) - -// PossibleProvisioningState1Values returns an array of possible values for the ProvisioningState1 const type. -func PossibleProvisioningState1Values() []ProvisioningState1 { - return []ProvisioningState1{ProvisioningState1Creating, ProvisioningState1Deleting, ProvisioningState1Failed, ProvisioningState1Migrating, ProvisioningState1Succeeded, ProvisioningState1Updating} -} - -// ProvisioningState2 enumerates the values for provisioning state 2. -type ProvisioningState2 string - -const ( - // ProvisioningState2Creating ... - ProvisioningState2Creating ProvisioningState2 = "Creating" - // ProvisioningState2Deleting ... - ProvisioningState2Deleting ProvisioningState2 = "Deleting" - // ProvisioningState2Failed ... - ProvisioningState2Failed ProvisioningState2 = "Failed" - // ProvisioningState2Migrating ... - ProvisioningState2Migrating ProvisioningState2 = "Migrating" - // ProvisioningState2Succeeded ... - ProvisioningState2Succeeded ProvisioningState2 = "Succeeded" - // ProvisioningState2Updating ... - ProvisioningState2Updating ProvisioningState2 = "Updating" -) - -// PossibleProvisioningState2Values returns an array of possible values for the ProvisioningState2 const type. -func PossibleProvisioningState2Values() []ProvisioningState2 { - return []ProvisioningState2{ProvisioningState2Creating, ProvisioningState2Deleting, ProvisioningState2Failed, ProvisioningState2Migrating, ProvisioningState2Succeeded, ProvisioningState2Updating} -} - -// ProximityPlacementGroupType enumerates the values for proximity placement group type. -type ProximityPlacementGroupType string - -const ( - // Standard ... - Standard ProximityPlacementGroupType = "Standard" - // Ultra ... - Ultra ProximityPlacementGroupType = "Ultra" -) - -// PossibleProximityPlacementGroupTypeValues returns an array of possible values for the ProximityPlacementGroupType const type. -func PossibleProximityPlacementGroupTypeValues() []ProximityPlacementGroupType { - return []ProximityPlacementGroupType{Standard, Ultra} -} - -// ReplicationState enumerates the values for replication state. -type ReplicationState string - -const ( - // ReplicationStateCompleted ... - ReplicationStateCompleted ReplicationState = "Completed" - // ReplicationStateFailed ... - ReplicationStateFailed ReplicationState = "Failed" - // ReplicationStateReplicating ... - ReplicationStateReplicating ReplicationState = "Replicating" - // ReplicationStateUnknown ... - ReplicationStateUnknown ReplicationState = "Unknown" -) - -// PossibleReplicationStateValues returns an array of possible values for the ReplicationState const type. -func PossibleReplicationStateValues() []ReplicationState { - return []ReplicationState{ReplicationStateCompleted, ReplicationStateFailed, ReplicationStateReplicating, ReplicationStateUnknown} -} - -// ReplicationStatusTypes enumerates the values for replication status types. -type ReplicationStatusTypes string - -const ( - // ReplicationStatusTypesReplicationStatus ... - ReplicationStatusTypesReplicationStatus ReplicationStatusTypes = "ReplicationStatus" -) - -// PossibleReplicationStatusTypesValues returns an array of possible values for the ReplicationStatusTypes const type. -func PossibleReplicationStatusTypesValues() []ReplicationStatusTypes { - return []ReplicationStatusTypes{ReplicationStatusTypesReplicationStatus} -} - -// ResourceIdentityType enumerates the values for resource identity type. -type ResourceIdentityType string - -const ( - // ResourceIdentityTypeNone ... - ResourceIdentityTypeNone ResourceIdentityType = "None" - // ResourceIdentityTypeSystemAssigned ... - ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" - // ResourceIdentityTypeSystemAssignedUserAssigned ... - ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" - // ResourceIdentityTypeUserAssigned ... - ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" -) - -// PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type. -func PossibleResourceIdentityTypeValues() []ResourceIdentityType { - return []ResourceIdentityType{ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned} -} - -// ResourceSkuCapacityScaleType enumerates the values for resource sku capacity scale type. -type ResourceSkuCapacityScaleType string - -const ( - // ResourceSkuCapacityScaleTypeAutomatic ... - ResourceSkuCapacityScaleTypeAutomatic ResourceSkuCapacityScaleType = "Automatic" - // ResourceSkuCapacityScaleTypeManual ... - ResourceSkuCapacityScaleTypeManual ResourceSkuCapacityScaleType = "Manual" - // ResourceSkuCapacityScaleTypeNone ... - ResourceSkuCapacityScaleTypeNone ResourceSkuCapacityScaleType = "None" -) - -// PossibleResourceSkuCapacityScaleTypeValues returns an array of possible values for the ResourceSkuCapacityScaleType const type. -func PossibleResourceSkuCapacityScaleTypeValues() []ResourceSkuCapacityScaleType { - return []ResourceSkuCapacityScaleType{ResourceSkuCapacityScaleTypeAutomatic, ResourceSkuCapacityScaleTypeManual, ResourceSkuCapacityScaleTypeNone} -} - -// ResourceSkuRestrictionsReasonCode enumerates the values for resource sku restrictions reason code. -type ResourceSkuRestrictionsReasonCode string - -const ( - // NotAvailableForSubscription ... - NotAvailableForSubscription ResourceSkuRestrictionsReasonCode = "NotAvailableForSubscription" - // QuotaID ... - QuotaID ResourceSkuRestrictionsReasonCode = "QuotaId" -) - -// PossibleResourceSkuRestrictionsReasonCodeValues returns an array of possible values for the ResourceSkuRestrictionsReasonCode const type. -func PossibleResourceSkuRestrictionsReasonCodeValues() []ResourceSkuRestrictionsReasonCode { - return []ResourceSkuRestrictionsReasonCode{NotAvailableForSubscription, QuotaID} -} - -// ResourceSkuRestrictionsType enumerates the values for resource sku restrictions type. -type ResourceSkuRestrictionsType string - -const ( - // Location ... - Location ResourceSkuRestrictionsType = "Location" - // Zone ... - Zone ResourceSkuRestrictionsType = "Zone" -) - -// PossibleResourceSkuRestrictionsTypeValues returns an array of possible values for the ResourceSkuRestrictionsType const type. -func PossibleResourceSkuRestrictionsTypeValues() []ResourceSkuRestrictionsType { - return []ResourceSkuRestrictionsType{Location, Zone} -} - -// RollingUpgradeActionType enumerates the values for rolling upgrade action type. -type RollingUpgradeActionType string - -const ( - // Cancel ... - Cancel RollingUpgradeActionType = "Cancel" - // Start ... - Start RollingUpgradeActionType = "Start" -) - -// PossibleRollingUpgradeActionTypeValues returns an array of possible values for the RollingUpgradeActionType const type. -func PossibleRollingUpgradeActionTypeValues() []RollingUpgradeActionType { - return []RollingUpgradeActionType{Cancel, Start} -} - -// RollingUpgradeStatusCode enumerates the values for rolling upgrade status code. -type RollingUpgradeStatusCode string - -const ( - // RollingUpgradeStatusCodeCancelled ... - RollingUpgradeStatusCodeCancelled RollingUpgradeStatusCode = "Cancelled" - // RollingUpgradeStatusCodeCompleted ... - RollingUpgradeStatusCodeCompleted RollingUpgradeStatusCode = "Completed" - // RollingUpgradeStatusCodeFaulted ... - RollingUpgradeStatusCodeFaulted RollingUpgradeStatusCode = "Faulted" - // RollingUpgradeStatusCodeRollingForward ... - RollingUpgradeStatusCodeRollingForward RollingUpgradeStatusCode = "RollingForward" -) - -// PossibleRollingUpgradeStatusCodeValues returns an array of possible values for the RollingUpgradeStatusCode const type. -func PossibleRollingUpgradeStatusCodeValues() []RollingUpgradeStatusCode { - return []RollingUpgradeStatusCode{RollingUpgradeStatusCodeCancelled, RollingUpgradeStatusCodeCompleted, RollingUpgradeStatusCodeFaulted, RollingUpgradeStatusCodeRollingForward} -} - -// SettingNames enumerates the values for setting names. -type SettingNames string - -const ( - // AutoLogon ... - AutoLogon SettingNames = "AutoLogon" - // FirstLogonCommands ... - FirstLogonCommands SettingNames = "FirstLogonCommands" -) - -// PossibleSettingNamesValues returns an array of possible values for the SettingNames const type. -func PossibleSettingNamesValues() []SettingNames { - return []SettingNames{AutoLogon, FirstLogonCommands} -} - -// SnapshotStorageAccountTypes enumerates the values for snapshot storage account types. -type SnapshotStorageAccountTypes string - -const ( - // SnapshotStorageAccountTypesPremiumLRS ... - SnapshotStorageAccountTypesPremiumLRS SnapshotStorageAccountTypes = "Premium_LRS" - // SnapshotStorageAccountTypesStandardLRS ... - SnapshotStorageAccountTypesStandardLRS SnapshotStorageAccountTypes = "Standard_LRS" - // SnapshotStorageAccountTypesStandardZRS ... - SnapshotStorageAccountTypesStandardZRS SnapshotStorageAccountTypes = "Standard_ZRS" -) - -// PossibleSnapshotStorageAccountTypesValues returns an array of possible values for the SnapshotStorageAccountTypes const type. -func PossibleSnapshotStorageAccountTypesValues() []SnapshotStorageAccountTypes { - return []SnapshotStorageAccountTypes{SnapshotStorageAccountTypesPremiumLRS, SnapshotStorageAccountTypesStandardLRS, SnapshotStorageAccountTypesStandardZRS} -} - -// StatusLevelTypes enumerates the values for status level types. -type StatusLevelTypes string - -const ( - // Error ... - Error StatusLevelTypes = "Error" - // Info ... - Info StatusLevelTypes = "Info" - // Warning ... - Warning StatusLevelTypes = "Warning" -) - -// PossibleStatusLevelTypesValues returns an array of possible values for the StatusLevelTypes const type. -func PossibleStatusLevelTypesValues() []StatusLevelTypes { - return []StatusLevelTypes{Error, Info, Warning} -} - -// StorageAccountTypes enumerates the values for storage account types. -type StorageAccountTypes string - -const ( - // StorageAccountTypesPremiumLRS ... - StorageAccountTypesPremiumLRS StorageAccountTypes = "Premium_LRS" - // StorageAccountTypesStandardLRS ... - StorageAccountTypesStandardLRS StorageAccountTypes = "Standard_LRS" - // StorageAccountTypesStandardSSDLRS ... - StorageAccountTypesStandardSSDLRS StorageAccountTypes = "StandardSSD_LRS" - // StorageAccountTypesUltraSSDLRS ... - StorageAccountTypesUltraSSDLRS StorageAccountTypes = "UltraSSD_LRS" -) - -// PossibleStorageAccountTypesValues returns an array of possible values for the StorageAccountTypes const type. -func PossibleStorageAccountTypesValues() []StorageAccountTypes { - return []StorageAccountTypes{StorageAccountTypesPremiumLRS, StorageAccountTypesStandardLRS, StorageAccountTypesStandardSSDLRS, StorageAccountTypesUltraSSDLRS} -} - -// UpgradeMode enumerates the values for upgrade mode. -type UpgradeMode string - -const ( - // Automatic ... - Automatic UpgradeMode = "Automatic" - // Manual ... - Manual UpgradeMode = "Manual" - // Rolling ... - Rolling UpgradeMode = "Rolling" -) - -// PossibleUpgradeModeValues returns an array of possible values for the UpgradeMode const type. -func PossibleUpgradeModeValues() []UpgradeMode { - return []UpgradeMode{Automatic, Manual, Rolling} -} - -// UpgradeOperationInvoker enumerates the values for upgrade operation invoker. -type UpgradeOperationInvoker string - -const ( - // UpgradeOperationInvokerPlatform ... - UpgradeOperationInvokerPlatform UpgradeOperationInvoker = "Platform" - // UpgradeOperationInvokerUnknown ... - UpgradeOperationInvokerUnknown UpgradeOperationInvoker = "Unknown" - // UpgradeOperationInvokerUser ... - UpgradeOperationInvokerUser UpgradeOperationInvoker = "User" -) - -// PossibleUpgradeOperationInvokerValues returns an array of possible values for the UpgradeOperationInvoker const type. -func PossibleUpgradeOperationInvokerValues() []UpgradeOperationInvoker { - return []UpgradeOperationInvoker{UpgradeOperationInvokerPlatform, UpgradeOperationInvokerUnknown, UpgradeOperationInvokerUser} -} - -// UpgradeState enumerates the values for upgrade state. -type UpgradeState string - -const ( - // UpgradeStateCancelled ... - UpgradeStateCancelled UpgradeState = "Cancelled" - // UpgradeStateCompleted ... - UpgradeStateCompleted UpgradeState = "Completed" - // UpgradeStateFaulted ... - UpgradeStateFaulted UpgradeState = "Faulted" - // UpgradeStateRollingForward ... - UpgradeStateRollingForward UpgradeState = "RollingForward" -) - -// PossibleUpgradeStateValues returns an array of possible values for the UpgradeState const type. -func PossibleUpgradeStateValues() []UpgradeState { - return []UpgradeState{UpgradeStateCancelled, UpgradeStateCompleted, UpgradeStateFaulted, UpgradeStateRollingForward} -} - -// VirtualMachineEvictionPolicyTypes enumerates the values for virtual machine eviction policy types. -type VirtualMachineEvictionPolicyTypes string - -const ( - // Deallocate ... - Deallocate VirtualMachineEvictionPolicyTypes = "Deallocate" - // Delete ... - Delete VirtualMachineEvictionPolicyTypes = "Delete" -) - -// PossibleVirtualMachineEvictionPolicyTypesValues returns an array of possible values for the VirtualMachineEvictionPolicyTypes const type. -func PossibleVirtualMachineEvictionPolicyTypesValues() []VirtualMachineEvictionPolicyTypes { - return []VirtualMachineEvictionPolicyTypes{Deallocate, Delete} -} - -// VirtualMachinePriorityTypes enumerates the values for virtual machine priority types. -type VirtualMachinePriorityTypes string - -const ( - // Low ... - Low VirtualMachinePriorityTypes = "Low" - // Regular ... - Regular VirtualMachinePriorityTypes = "Regular" -) - -// PossibleVirtualMachinePriorityTypesValues returns an array of possible values for the VirtualMachinePriorityTypes const type. -func PossibleVirtualMachinePriorityTypesValues() []VirtualMachinePriorityTypes { - return []VirtualMachinePriorityTypes{Low, Regular} -} - -// VirtualMachineScaleSetSkuScaleType enumerates the values for virtual machine scale set sku scale type. -type VirtualMachineScaleSetSkuScaleType string - -const ( - // VirtualMachineScaleSetSkuScaleTypeAutomatic ... - VirtualMachineScaleSetSkuScaleTypeAutomatic VirtualMachineScaleSetSkuScaleType = "Automatic" - // VirtualMachineScaleSetSkuScaleTypeNone ... - VirtualMachineScaleSetSkuScaleTypeNone VirtualMachineScaleSetSkuScaleType = "None" -) - -// PossibleVirtualMachineScaleSetSkuScaleTypeValues returns an array of possible values for the VirtualMachineScaleSetSkuScaleType const type. -func PossibleVirtualMachineScaleSetSkuScaleTypeValues() []VirtualMachineScaleSetSkuScaleType { - return []VirtualMachineScaleSetSkuScaleType{VirtualMachineScaleSetSkuScaleTypeAutomatic, VirtualMachineScaleSetSkuScaleTypeNone} -} - -// VirtualMachineSizeTypes enumerates the values for virtual machine size types. -type VirtualMachineSizeTypes string - -const ( - // VirtualMachineSizeTypesBasicA0 ... - VirtualMachineSizeTypesBasicA0 VirtualMachineSizeTypes = "Basic_A0" - // VirtualMachineSizeTypesBasicA1 ... - VirtualMachineSizeTypesBasicA1 VirtualMachineSizeTypes = "Basic_A1" - // VirtualMachineSizeTypesBasicA2 ... - VirtualMachineSizeTypesBasicA2 VirtualMachineSizeTypes = "Basic_A2" - // VirtualMachineSizeTypesBasicA3 ... - VirtualMachineSizeTypesBasicA3 VirtualMachineSizeTypes = "Basic_A3" - // VirtualMachineSizeTypesBasicA4 ... - VirtualMachineSizeTypesBasicA4 VirtualMachineSizeTypes = "Basic_A4" - // VirtualMachineSizeTypesStandardA0 ... - VirtualMachineSizeTypesStandardA0 VirtualMachineSizeTypes = "Standard_A0" - // VirtualMachineSizeTypesStandardA1 ... - VirtualMachineSizeTypesStandardA1 VirtualMachineSizeTypes = "Standard_A1" - // VirtualMachineSizeTypesStandardA10 ... - VirtualMachineSizeTypesStandardA10 VirtualMachineSizeTypes = "Standard_A10" - // VirtualMachineSizeTypesStandardA11 ... - VirtualMachineSizeTypesStandardA11 VirtualMachineSizeTypes = "Standard_A11" - // VirtualMachineSizeTypesStandardA1V2 ... - VirtualMachineSizeTypesStandardA1V2 VirtualMachineSizeTypes = "Standard_A1_v2" - // VirtualMachineSizeTypesStandardA2 ... - VirtualMachineSizeTypesStandardA2 VirtualMachineSizeTypes = "Standard_A2" - // VirtualMachineSizeTypesStandardA2mV2 ... - VirtualMachineSizeTypesStandardA2mV2 VirtualMachineSizeTypes = "Standard_A2m_v2" - // VirtualMachineSizeTypesStandardA2V2 ... - VirtualMachineSizeTypesStandardA2V2 VirtualMachineSizeTypes = "Standard_A2_v2" - // VirtualMachineSizeTypesStandardA3 ... - VirtualMachineSizeTypesStandardA3 VirtualMachineSizeTypes = "Standard_A3" - // VirtualMachineSizeTypesStandardA4 ... - VirtualMachineSizeTypesStandardA4 VirtualMachineSizeTypes = "Standard_A4" - // VirtualMachineSizeTypesStandardA4mV2 ... - VirtualMachineSizeTypesStandardA4mV2 VirtualMachineSizeTypes = "Standard_A4m_v2" - // VirtualMachineSizeTypesStandardA4V2 ... - VirtualMachineSizeTypesStandardA4V2 VirtualMachineSizeTypes = "Standard_A4_v2" - // VirtualMachineSizeTypesStandardA5 ... - VirtualMachineSizeTypesStandardA5 VirtualMachineSizeTypes = "Standard_A5" - // VirtualMachineSizeTypesStandardA6 ... - VirtualMachineSizeTypesStandardA6 VirtualMachineSizeTypes = "Standard_A6" - // VirtualMachineSizeTypesStandardA7 ... - VirtualMachineSizeTypesStandardA7 VirtualMachineSizeTypes = "Standard_A7" - // VirtualMachineSizeTypesStandardA8 ... - VirtualMachineSizeTypesStandardA8 VirtualMachineSizeTypes = "Standard_A8" - // VirtualMachineSizeTypesStandardA8mV2 ... - VirtualMachineSizeTypesStandardA8mV2 VirtualMachineSizeTypes = "Standard_A8m_v2" - // VirtualMachineSizeTypesStandardA8V2 ... - VirtualMachineSizeTypesStandardA8V2 VirtualMachineSizeTypes = "Standard_A8_v2" - // VirtualMachineSizeTypesStandardA9 ... - VirtualMachineSizeTypesStandardA9 VirtualMachineSizeTypes = "Standard_A9" - // VirtualMachineSizeTypesStandardB1ms ... - VirtualMachineSizeTypesStandardB1ms VirtualMachineSizeTypes = "Standard_B1ms" - // VirtualMachineSizeTypesStandardB1s ... - VirtualMachineSizeTypesStandardB1s VirtualMachineSizeTypes = "Standard_B1s" - // VirtualMachineSizeTypesStandardB2ms ... - VirtualMachineSizeTypesStandardB2ms VirtualMachineSizeTypes = "Standard_B2ms" - // VirtualMachineSizeTypesStandardB2s ... - VirtualMachineSizeTypesStandardB2s VirtualMachineSizeTypes = "Standard_B2s" - // VirtualMachineSizeTypesStandardB4ms ... - VirtualMachineSizeTypesStandardB4ms VirtualMachineSizeTypes = "Standard_B4ms" - // VirtualMachineSizeTypesStandardB8ms ... - VirtualMachineSizeTypesStandardB8ms VirtualMachineSizeTypes = "Standard_B8ms" - // VirtualMachineSizeTypesStandardD1 ... - VirtualMachineSizeTypesStandardD1 VirtualMachineSizeTypes = "Standard_D1" - // VirtualMachineSizeTypesStandardD11 ... - VirtualMachineSizeTypesStandardD11 VirtualMachineSizeTypes = "Standard_D11" - // VirtualMachineSizeTypesStandardD11V2 ... - VirtualMachineSizeTypesStandardD11V2 VirtualMachineSizeTypes = "Standard_D11_v2" - // VirtualMachineSizeTypesStandardD12 ... - VirtualMachineSizeTypesStandardD12 VirtualMachineSizeTypes = "Standard_D12" - // VirtualMachineSizeTypesStandardD12V2 ... - VirtualMachineSizeTypesStandardD12V2 VirtualMachineSizeTypes = "Standard_D12_v2" - // VirtualMachineSizeTypesStandardD13 ... - VirtualMachineSizeTypesStandardD13 VirtualMachineSizeTypes = "Standard_D13" - // VirtualMachineSizeTypesStandardD13V2 ... - VirtualMachineSizeTypesStandardD13V2 VirtualMachineSizeTypes = "Standard_D13_v2" - // VirtualMachineSizeTypesStandardD14 ... - VirtualMachineSizeTypesStandardD14 VirtualMachineSizeTypes = "Standard_D14" - // VirtualMachineSizeTypesStandardD14V2 ... - VirtualMachineSizeTypesStandardD14V2 VirtualMachineSizeTypes = "Standard_D14_v2" - // VirtualMachineSizeTypesStandardD15V2 ... - VirtualMachineSizeTypesStandardD15V2 VirtualMachineSizeTypes = "Standard_D15_v2" - // VirtualMachineSizeTypesStandardD16sV3 ... - VirtualMachineSizeTypesStandardD16sV3 VirtualMachineSizeTypes = "Standard_D16s_v3" - // VirtualMachineSizeTypesStandardD16V3 ... - VirtualMachineSizeTypesStandardD16V3 VirtualMachineSizeTypes = "Standard_D16_v3" - // VirtualMachineSizeTypesStandardD1V2 ... - VirtualMachineSizeTypesStandardD1V2 VirtualMachineSizeTypes = "Standard_D1_v2" - // VirtualMachineSizeTypesStandardD2 ... - VirtualMachineSizeTypesStandardD2 VirtualMachineSizeTypes = "Standard_D2" - // VirtualMachineSizeTypesStandardD2sV3 ... - VirtualMachineSizeTypesStandardD2sV3 VirtualMachineSizeTypes = "Standard_D2s_v3" - // VirtualMachineSizeTypesStandardD2V2 ... - VirtualMachineSizeTypesStandardD2V2 VirtualMachineSizeTypes = "Standard_D2_v2" - // VirtualMachineSizeTypesStandardD2V3 ... - VirtualMachineSizeTypesStandardD2V3 VirtualMachineSizeTypes = "Standard_D2_v3" - // VirtualMachineSizeTypesStandardD3 ... - VirtualMachineSizeTypesStandardD3 VirtualMachineSizeTypes = "Standard_D3" - // VirtualMachineSizeTypesStandardD32sV3 ... - VirtualMachineSizeTypesStandardD32sV3 VirtualMachineSizeTypes = "Standard_D32s_v3" - // VirtualMachineSizeTypesStandardD32V3 ... - VirtualMachineSizeTypesStandardD32V3 VirtualMachineSizeTypes = "Standard_D32_v3" - // VirtualMachineSizeTypesStandardD3V2 ... - VirtualMachineSizeTypesStandardD3V2 VirtualMachineSizeTypes = "Standard_D3_v2" - // VirtualMachineSizeTypesStandardD4 ... - VirtualMachineSizeTypesStandardD4 VirtualMachineSizeTypes = "Standard_D4" - // VirtualMachineSizeTypesStandardD4sV3 ... - VirtualMachineSizeTypesStandardD4sV3 VirtualMachineSizeTypes = "Standard_D4s_v3" - // VirtualMachineSizeTypesStandardD4V2 ... - VirtualMachineSizeTypesStandardD4V2 VirtualMachineSizeTypes = "Standard_D4_v2" - // VirtualMachineSizeTypesStandardD4V3 ... - VirtualMachineSizeTypesStandardD4V3 VirtualMachineSizeTypes = "Standard_D4_v3" - // VirtualMachineSizeTypesStandardD5V2 ... - VirtualMachineSizeTypesStandardD5V2 VirtualMachineSizeTypes = "Standard_D5_v2" - // VirtualMachineSizeTypesStandardD64sV3 ... - VirtualMachineSizeTypesStandardD64sV3 VirtualMachineSizeTypes = "Standard_D64s_v3" - // VirtualMachineSizeTypesStandardD64V3 ... - VirtualMachineSizeTypesStandardD64V3 VirtualMachineSizeTypes = "Standard_D64_v3" - // VirtualMachineSizeTypesStandardD8sV3 ... - VirtualMachineSizeTypesStandardD8sV3 VirtualMachineSizeTypes = "Standard_D8s_v3" - // VirtualMachineSizeTypesStandardD8V3 ... - VirtualMachineSizeTypesStandardD8V3 VirtualMachineSizeTypes = "Standard_D8_v3" - // VirtualMachineSizeTypesStandardDS1 ... - VirtualMachineSizeTypesStandardDS1 VirtualMachineSizeTypes = "Standard_DS1" - // VirtualMachineSizeTypesStandardDS11 ... - VirtualMachineSizeTypesStandardDS11 VirtualMachineSizeTypes = "Standard_DS11" - // VirtualMachineSizeTypesStandardDS11V2 ... - VirtualMachineSizeTypesStandardDS11V2 VirtualMachineSizeTypes = "Standard_DS11_v2" - // VirtualMachineSizeTypesStandardDS12 ... - VirtualMachineSizeTypesStandardDS12 VirtualMachineSizeTypes = "Standard_DS12" - // VirtualMachineSizeTypesStandardDS12V2 ... - VirtualMachineSizeTypesStandardDS12V2 VirtualMachineSizeTypes = "Standard_DS12_v2" - // VirtualMachineSizeTypesStandardDS13 ... - VirtualMachineSizeTypesStandardDS13 VirtualMachineSizeTypes = "Standard_DS13" - // VirtualMachineSizeTypesStandardDS132V2 ... - VirtualMachineSizeTypesStandardDS132V2 VirtualMachineSizeTypes = "Standard_DS13-2_v2" - // VirtualMachineSizeTypesStandardDS134V2 ... - VirtualMachineSizeTypesStandardDS134V2 VirtualMachineSizeTypes = "Standard_DS13-4_v2" - // VirtualMachineSizeTypesStandardDS13V2 ... - VirtualMachineSizeTypesStandardDS13V2 VirtualMachineSizeTypes = "Standard_DS13_v2" - // VirtualMachineSizeTypesStandardDS14 ... - VirtualMachineSizeTypesStandardDS14 VirtualMachineSizeTypes = "Standard_DS14" - // VirtualMachineSizeTypesStandardDS144V2 ... - VirtualMachineSizeTypesStandardDS144V2 VirtualMachineSizeTypes = "Standard_DS14-4_v2" - // VirtualMachineSizeTypesStandardDS148V2 ... - VirtualMachineSizeTypesStandardDS148V2 VirtualMachineSizeTypes = "Standard_DS14-8_v2" - // VirtualMachineSizeTypesStandardDS14V2 ... - VirtualMachineSizeTypesStandardDS14V2 VirtualMachineSizeTypes = "Standard_DS14_v2" - // VirtualMachineSizeTypesStandardDS15V2 ... - VirtualMachineSizeTypesStandardDS15V2 VirtualMachineSizeTypes = "Standard_DS15_v2" - // VirtualMachineSizeTypesStandardDS1V2 ... - VirtualMachineSizeTypesStandardDS1V2 VirtualMachineSizeTypes = "Standard_DS1_v2" - // VirtualMachineSizeTypesStandardDS2 ... - VirtualMachineSizeTypesStandardDS2 VirtualMachineSizeTypes = "Standard_DS2" - // VirtualMachineSizeTypesStandardDS2V2 ... - VirtualMachineSizeTypesStandardDS2V2 VirtualMachineSizeTypes = "Standard_DS2_v2" - // VirtualMachineSizeTypesStandardDS3 ... - VirtualMachineSizeTypesStandardDS3 VirtualMachineSizeTypes = "Standard_DS3" - // VirtualMachineSizeTypesStandardDS3V2 ... - VirtualMachineSizeTypesStandardDS3V2 VirtualMachineSizeTypes = "Standard_DS3_v2" - // VirtualMachineSizeTypesStandardDS4 ... - VirtualMachineSizeTypesStandardDS4 VirtualMachineSizeTypes = "Standard_DS4" - // VirtualMachineSizeTypesStandardDS4V2 ... - VirtualMachineSizeTypesStandardDS4V2 VirtualMachineSizeTypes = "Standard_DS4_v2" - // VirtualMachineSizeTypesStandardDS5V2 ... - VirtualMachineSizeTypesStandardDS5V2 VirtualMachineSizeTypes = "Standard_DS5_v2" - // VirtualMachineSizeTypesStandardE16sV3 ... - VirtualMachineSizeTypesStandardE16sV3 VirtualMachineSizeTypes = "Standard_E16s_v3" - // VirtualMachineSizeTypesStandardE16V3 ... - VirtualMachineSizeTypesStandardE16V3 VirtualMachineSizeTypes = "Standard_E16_v3" - // VirtualMachineSizeTypesStandardE2sV3 ... - VirtualMachineSizeTypesStandardE2sV3 VirtualMachineSizeTypes = "Standard_E2s_v3" - // VirtualMachineSizeTypesStandardE2V3 ... - VirtualMachineSizeTypesStandardE2V3 VirtualMachineSizeTypes = "Standard_E2_v3" - // VirtualMachineSizeTypesStandardE3216V3 ... - VirtualMachineSizeTypesStandardE3216V3 VirtualMachineSizeTypes = "Standard_E32-16_v3" - // VirtualMachineSizeTypesStandardE328sV3 ... - VirtualMachineSizeTypesStandardE328sV3 VirtualMachineSizeTypes = "Standard_E32-8s_v3" - // VirtualMachineSizeTypesStandardE32sV3 ... - VirtualMachineSizeTypesStandardE32sV3 VirtualMachineSizeTypes = "Standard_E32s_v3" - // VirtualMachineSizeTypesStandardE32V3 ... - VirtualMachineSizeTypesStandardE32V3 VirtualMachineSizeTypes = "Standard_E32_v3" - // VirtualMachineSizeTypesStandardE4sV3 ... - VirtualMachineSizeTypesStandardE4sV3 VirtualMachineSizeTypes = "Standard_E4s_v3" - // VirtualMachineSizeTypesStandardE4V3 ... - VirtualMachineSizeTypesStandardE4V3 VirtualMachineSizeTypes = "Standard_E4_v3" - // VirtualMachineSizeTypesStandardE6416sV3 ... - VirtualMachineSizeTypesStandardE6416sV3 VirtualMachineSizeTypes = "Standard_E64-16s_v3" - // VirtualMachineSizeTypesStandardE6432sV3 ... - VirtualMachineSizeTypesStandardE6432sV3 VirtualMachineSizeTypes = "Standard_E64-32s_v3" - // VirtualMachineSizeTypesStandardE64sV3 ... - VirtualMachineSizeTypesStandardE64sV3 VirtualMachineSizeTypes = "Standard_E64s_v3" - // VirtualMachineSizeTypesStandardE64V3 ... - VirtualMachineSizeTypesStandardE64V3 VirtualMachineSizeTypes = "Standard_E64_v3" - // VirtualMachineSizeTypesStandardE8sV3 ... - VirtualMachineSizeTypesStandardE8sV3 VirtualMachineSizeTypes = "Standard_E8s_v3" - // VirtualMachineSizeTypesStandardE8V3 ... - VirtualMachineSizeTypesStandardE8V3 VirtualMachineSizeTypes = "Standard_E8_v3" - // VirtualMachineSizeTypesStandardF1 ... - VirtualMachineSizeTypesStandardF1 VirtualMachineSizeTypes = "Standard_F1" - // VirtualMachineSizeTypesStandardF16 ... - VirtualMachineSizeTypesStandardF16 VirtualMachineSizeTypes = "Standard_F16" - // VirtualMachineSizeTypesStandardF16s ... - VirtualMachineSizeTypesStandardF16s VirtualMachineSizeTypes = "Standard_F16s" - // VirtualMachineSizeTypesStandardF16sV2 ... - VirtualMachineSizeTypesStandardF16sV2 VirtualMachineSizeTypes = "Standard_F16s_v2" - // VirtualMachineSizeTypesStandardF1s ... - VirtualMachineSizeTypesStandardF1s VirtualMachineSizeTypes = "Standard_F1s" - // VirtualMachineSizeTypesStandardF2 ... - VirtualMachineSizeTypesStandardF2 VirtualMachineSizeTypes = "Standard_F2" - // VirtualMachineSizeTypesStandardF2s ... - VirtualMachineSizeTypesStandardF2s VirtualMachineSizeTypes = "Standard_F2s" - // VirtualMachineSizeTypesStandardF2sV2 ... - VirtualMachineSizeTypesStandardF2sV2 VirtualMachineSizeTypes = "Standard_F2s_v2" - // VirtualMachineSizeTypesStandardF32sV2 ... - VirtualMachineSizeTypesStandardF32sV2 VirtualMachineSizeTypes = "Standard_F32s_v2" - // VirtualMachineSizeTypesStandardF4 ... - VirtualMachineSizeTypesStandardF4 VirtualMachineSizeTypes = "Standard_F4" - // VirtualMachineSizeTypesStandardF4s ... - VirtualMachineSizeTypesStandardF4s VirtualMachineSizeTypes = "Standard_F4s" - // VirtualMachineSizeTypesStandardF4sV2 ... - VirtualMachineSizeTypesStandardF4sV2 VirtualMachineSizeTypes = "Standard_F4s_v2" - // VirtualMachineSizeTypesStandardF64sV2 ... - VirtualMachineSizeTypesStandardF64sV2 VirtualMachineSizeTypes = "Standard_F64s_v2" - // VirtualMachineSizeTypesStandardF72sV2 ... - VirtualMachineSizeTypesStandardF72sV2 VirtualMachineSizeTypes = "Standard_F72s_v2" - // VirtualMachineSizeTypesStandardF8 ... - VirtualMachineSizeTypesStandardF8 VirtualMachineSizeTypes = "Standard_F8" - // VirtualMachineSizeTypesStandardF8s ... - VirtualMachineSizeTypesStandardF8s VirtualMachineSizeTypes = "Standard_F8s" - // VirtualMachineSizeTypesStandardF8sV2 ... - VirtualMachineSizeTypesStandardF8sV2 VirtualMachineSizeTypes = "Standard_F8s_v2" - // VirtualMachineSizeTypesStandardG1 ... - VirtualMachineSizeTypesStandardG1 VirtualMachineSizeTypes = "Standard_G1" - // VirtualMachineSizeTypesStandardG2 ... - VirtualMachineSizeTypesStandardG2 VirtualMachineSizeTypes = "Standard_G2" - // VirtualMachineSizeTypesStandardG3 ... - VirtualMachineSizeTypesStandardG3 VirtualMachineSizeTypes = "Standard_G3" - // VirtualMachineSizeTypesStandardG4 ... - VirtualMachineSizeTypesStandardG4 VirtualMachineSizeTypes = "Standard_G4" - // VirtualMachineSizeTypesStandardG5 ... - VirtualMachineSizeTypesStandardG5 VirtualMachineSizeTypes = "Standard_G5" - // VirtualMachineSizeTypesStandardGS1 ... - VirtualMachineSizeTypesStandardGS1 VirtualMachineSizeTypes = "Standard_GS1" - // VirtualMachineSizeTypesStandardGS2 ... - VirtualMachineSizeTypesStandardGS2 VirtualMachineSizeTypes = "Standard_GS2" - // VirtualMachineSizeTypesStandardGS3 ... - VirtualMachineSizeTypesStandardGS3 VirtualMachineSizeTypes = "Standard_GS3" - // VirtualMachineSizeTypesStandardGS4 ... - VirtualMachineSizeTypesStandardGS4 VirtualMachineSizeTypes = "Standard_GS4" - // VirtualMachineSizeTypesStandardGS44 ... - VirtualMachineSizeTypesStandardGS44 VirtualMachineSizeTypes = "Standard_GS4-4" - // VirtualMachineSizeTypesStandardGS48 ... - VirtualMachineSizeTypesStandardGS48 VirtualMachineSizeTypes = "Standard_GS4-8" - // VirtualMachineSizeTypesStandardGS5 ... - VirtualMachineSizeTypesStandardGS5 VirtualMachineSizeTypes = "Standard_GS5" - // VirtualMachineSizeTypesStandardGS516 ... - VirtualMachineSizeTypesStandardGS516 VirtualMachineSizeTypes = "Standard_GS5-16" - // VirtualMachineSizeTypesStandardGS58 ... - VirtualMachineSizeTypesStandardGS58 VirtualMachineSizeTypes = "Standard_GS5-8" - // VirtualMachineSizeTypesStandardH16 ... - VirtualMachineSizeTypesStandardH16 VirtualMachineSizeTypes = "Standard_H16" - // VirtualMachineSizeTypesStandardH16m ... - VirtualMachineSizeTypesStandardH16m VirtualMachineSizeTypes = "Standard_H16m" - // VirtualMachineSizeTypesStandardH16mr ... - VirtualMachineSizeTypesStandardH16mr VirtualMachineSizeTypes = "Standard_H16mr" - // VirtualMachineSizeTypesStandardH16r ... - VirtualMachineSizeTypesStandardH16r VirtualMachineSizeTypes = "Standard_H16r" - // VirtualMachineSizeTypesStandardH8 ... - VirtualMachineSizeTypesStandardH8 VirtualMachineSizeTypes = "Standard_H8" - // VirtualMachineSizeTypesStandardH8m ... - VirtualMachineSizeTypesStandardH8m VirtualMachineSizeTypes = "Standard_H8m" - // VirtualMachineSizeTypesStandardL16s ... - VirtualMachineSizeTypesStandardL16s VirtualMachineSizeTypes = "Standard_L16s" - // VirtualMachineSizeTypesStandardL32s ... - VirtualMachineSizeTypesStandardL32s VirtualMachineSizeTypes = "Standard_L32s" - // VirtualMachineSizeTypesStandardL4s ... - VirtualMachineSizeTypesStandardL4s VirtualMachineSizeTypes = "Standard_L4s" - // VirtualMachineSizeTypesStandardL8s ... - VirtualMachineSizeTypesStandardL8s VirtualMachineSizeTypes = "Standard_L8s" - // VirtualMachineSizeTypesStandardM12832ms ... - VirtualMachineSizeTypesStandardM12832ms VirtualMachineSizeTypes = "Standard_M128-32ms" - // VirtualMachineSizeTypesStandardM12864ms ... - VirtualMachineSizeTypesStandardM12864ms VirtualMachineSizeTypes = "Standard_M128-64ms" - // VirtualMachineSizeTypesStandardM128ms ... - VirtualMachineSizeTypesStandardM128ms VirtualMachineSizeTypes = "Standard_M128ms" - // VirtualMachineSizeTypesStandardM128s ... - VirtualMachineSizeTypesStandardM128s VirtualMachineSizeTypes = "Standard_M128s" - // VirtualMachineSizeTypesStandardM6416ms ... - VirtualMachineSizeTypesStandardM6416ms VirtualMachineSizeTypes = "Standard_M64-16ms" - // VirtualMachineSizeTypesStandardM6432ms ... - VirtualMachineSizeTypesStandardM6432ms VirtualMachineSizeTypes = "Standard_M64-32ms" - // VirtualMachineSizeTypesStandardM64ms ... - VirtualMachineSizeTypesStandardM64ms VirtualMachineSizeTypes = "Standard_M64ms" - // VirtualMachineSizeTypesStandardM64s ... - VirtualMachineSizeTypesStandardM64s VirtualMachineSizeTypes = "Standard_M64s" - // VirtualMachineSizeTypesStandardNC12 ... - VirtualMachineSizeTypesStandardNC12 VirtualMachineSizeTypes = "Standard_NC12" - // VirtualMachineSizeTypesStandardNC12sV2 ... - VirtualMachineSizeTypesStandardNC12sV2 VirtualMachineSizeTypes = "Standard_NC12s_v2" - // VirtualMachineSizeTypesStandardNC12sV3 ... - VirtualMachineSizeTypesStandardNC12sV3 VirtualMachineSizeTypes = "Standard_NC12s_v3" - // VirtualMachineSizeTypesStandardNC24 ... - VirtualMachineSizeTypesStandardNC24 VirtualMachineSizeTypes = "Standard_NC24" - // VirtualMachineSizeTypesStandardNC24r ... - VirtualMachineSizeTypesStandardNC24r VirtualMachineSizeTypes = "Standard_NC24r" - // VirtualMachineSizeTypesStandardNC24rsV2 ... - VirtualMachineSizeTypesStandardNC24rsV2 VirtualMachineSizeTypes = "Standard_NC24rs_v2" - // VirtualMachineSizeTypesStandardNC24rsV3 ... - VirtualMachineSizeTypesStandardNC24rsV3 VirtualMachineSizeTypes = "Standard_NC24rs_v3" - // VirtualMachineSizeTypesStandardNC24sV2 ... - VirtualMachineSizeTypesStandardNC24sV2 VirtualMachineSizeTypes = "Standard_NC24s_v2" - // VirtualMachineSizeTypesStandardNC24sV3 ... - VirtualMachineSizeTypesStandardNC24sV3 VirtualMachineSizeTypes = "Standard_NC24s_v3" - // VirtualMachineSizeTypesStandardNC6 ... - VirtualMachineSizeTypesStandardNC6 VirtualMachineSizeTypes = "Standard_NC6" - // VirtualMachineSizeTypesStandardNC6sV2 ... - VirtualMachineSizeTypesStandardNC6sV2 VirtualMachineSizeTypes = "Standard_NC6s_v2" - // VirtualMachineSizeTypesStandardNC6sV3 ... - VirtualMachineSizeTypesStandardNC6sV3 VirtualMachineSizeTypes = "Standard_NC6s_v3" - // VirtualMachineSizeTypesStandardND12s ... - VirtualMachineSizeTypesStandardND12s VirtualMachineSizeTypes = "Standard_ND12s" - // VirtualMachineSizeTypesStandardND24rs ... - VirtualMachineSizeTypesStandardND24rs VirtualMachineSizeTypes = "Standard_ND24rs" - // VirtualMachineSizeTypesStandardND24s ... - VirtualMachineSizeTypesStandardND24s VirtualMachineSizeTypes = "Standard_ND24s" - // VirtualMachineSizeTypesStandardND6s ... - VirtualMachineSizeTypesStandardND6s VirtualMachineSizeTypes = "Standard_ND6s" - // VirtualMachineSizeTypesStandardNV12 ... - VirtualMachineSizeTypesStandardNV12 VirtualMachineSizeTypes = "Standard_NV12" - // VirtualMachineSizeTypesStandardNV24 ... - VirtualMachineSizeTypesStandardNV24 VirtualMachineSizeTypes = "Standard_NV24" - // VirtualMachineSizeTypesStandardNV6 ... - VirtualMachineSizeTypesStandardNV6 VirtualMachineSizeTypes = "Standard_NV6" -) - -// PossibleVirtualMachineSizeTypesValues returns an array of possible values for the VirtualMachineSizeTypes const type. -func PossibleVirtualMachineSizeTypesValues() []VirtualMachineSizeTypes { - return []VirtualMachineSizeTypes{VirtualMachineSizeTypesBasicA0, VirtualMachineSizeTypesBasicA1, VirtualMachineSizeTypesBasicA2, VirtualMachineSizeTypesBasicA3, VirtualMachineSizeTypesBasicA4, VirtualMachineSizeTypesStandardA0, VirtualMachineSizeTypesStandardA1, VirtualMachineSizeTypesStandardA10, VirtualMachineSizeTypesStandardA11, VirtualMachineSizeTypesStandardA1V2, VirtualMachineSizeTypesStandardA2, VirtualMachineSizeTypesStandardA2mV2, VirtualMachineSizeTypesStandardA2V2, VirtualMachineSizeTypesStandardA3, VirtualMachineSizeTypesStandardA4, VirtualMachineSizeTypesStandardA4mV2, VirtualMachineSizeTypesStandardA4V2, VirtualMachineSizeTypesStandardA5, VirtualMachineSizeTypesStandardA6, VirtualMachineSizeTypesStandardA7, VirtualMachineSizeTypesStandardA8, VirtualMachineSizeTypesStandardA8mV2, VirtualMachineSizeTypesStandardA8V2, VirtualMachineSizeTypesStandardA9, VirtualMachineSizeTypesStandardB1ms, VirtualMachineSizeTypesStandardB1s, VirtualMachineSizeTypesStandardB2ms, VirtualMachineSizeTypesStandardB2s, VirtualMachineSizeTypesStandardB4ms, VirtualMachineSizeTypesStandardB8ms, VirtualMachineSizeTypesStandardD1, VirtualMachineSizeTypesStandardD11, VirtualMachineSizeTypesStandardD11V2, VirtualMachineSizeTypesStandardD12, VirtualMachineSizeTypesStandardD12V2, VirtualMachineSizeTypesStandardD13, VirtualMachineSizeTypesStandardD13V2, VirtualMachineSizeTypesStandardD14, VirtualMachineSizeTypesStandardD14V2, VirtualMachineSizeTypesStandardD15V2, VirtualMachineSizeTypesStandardD16sV3, VirtualMachineSizeTypesStandardD16V3, VirtualMachineSizeTypesStandardD1V2, VirtualMachineSizeTypesStandardD2, VirtualMachineSizeTypesStandardD2sV3, VirtualMachineSizeTypesStandardD2V2, VirtualMachineSizeTypesStandardD2V3, VirtualMachineSizeTypesStandardD3, VirtualMachineSizeTypesStandardD32sV3, VirtualMachineSizeTypesStandardD32V3, VirtualMachineSizeTypesStandardD3V2, VirtualMachineSizeTypesStandardD4, VirtualMachineSizeTypesStandardD4sV3, VirtualMachineSizeTypesStandardD4V2, VirtualMachineSizeTypesStandardD4V3, VirtualMachineSizeTypesStandardD5V2, VirtualMachineSizeTypesStandardD64sV3, VirtualMachineSizeTypesStandardD64V3, VirtualMachineSizeTypesStandardD8sV3, VirtualMachineSizeTypesStandardD8V3, VirtualMachineSizeTypesStandardDS1, VirtualMachineSizeTypesStandardDS11, VirtualMachineSizeTypesStandardDS11V2, VirtualMachineSizeTypesStandardDS12, VirtualMachineSizeTypesStandardDS12V2, VirtualMachineSizeTypesStandardDS13, VirtualMachineSizeTypesStandardDS132V2, VirtualMachineSizeTypesStandardDS134V2, VirtualMachineSizeTypesStandardDS13V2, VirtualMachineSizeTypesStandardDS14, VirtualMachineSizeTypesStandardDS144V2, VirtualMachineSizeTypesStandardDS148V2, VirtualMachineSizeTypesStandardDS14V2, VirtualMachineSizeTypesStandardDS15V2, VirtualMachineSizeTypesStandardDS1V2, VirtualMachineSizeTypesStandardDS2, VirtualMachineSizeTypesStandardDS2V2, VirtualMachineSizeTypesStandardDS3, VirtualMachineSizeTypesStandardDS3V2, VirtualMachineSizeTypesStandardDS4, VirtualMachineSizeTypesStandardDS4V2, VirtualMachineSizeTypesStandardDS5V2, VirtualMachineSizeTypesStandardE16sV3, VirtualMachineSizeTypesStandardE16V3, VirtualMachineSizeTypesStandardE2sV3, VirtualMachineSizeTypesStandardE2V3, VirtualMachineSizeTypesStandardE3216V3, VirtualMachineSizeTypesStandardE328sV3, VirtualMachineSizeTypesStandardE32sV3, VirtualMachineSizeTypesStandardE32V3, VirtualMachineSizeTypesStandardE4sV3, VirtualMachineSizeTypesStandardE4V3, VirtualMachineSizeTypesStandardE6416sV3, VirtualMachineSizeTypesStandardE6432sV3, VirtualMachineSizeTypesStandardE64sV3, VirtualMachineSizeTypesStandardE64V3, VirtualMachineSizeTypesStandardE8sV3, VirtualMachineSizeTypesStandardE8V3, VirtualMachineSizeTypesStandardF1, VirtualMachineSizeTypesStandardF16, VirtualMachineSizeTypesStandardF16s, VirtualMachineSizeTypesStandardF16sV2, VirtualMachineSizeTypesStandardF1s, VirtualMachineSizeTypesStandardF2, VirtualMachineSizeTypesStandardF2s, VirtualMachineSizeTypesStandardF2sV2, VirtualMachineSizeTypesStandardF32sV2, VirtualMachineSizeTypesStandardF4, VirtualMachineSizeTypesStandardF4s, VirtualMachineSizeTypesStandardF4sV2, VirtualMachineSizeTypesStandardF64sV2, VirtualMachineSizeTypesStandardF72sV2, VirtualMachineSizeTypesStandardF8, VirtualMachineSizeTypesStandardF8s, VirtualMachineSizeTypesStandardF8sV2, VirtualMachineSizeTypesStandardG1, VirtualMachineSizeTypesStandardG2, VirtualMachineSizeTypesStandardG3, VirtualMachineSizeTypesStandardG4, VirtualMachineSizeTypesStandardG5, VirtualMachineSizeTypesStandardGS1, VirtualMachineSizeTypesStandardGS2, VirtualMachineSizeTypesStandardGS3, VirtualMachineSizeTypesStandardGS4, VirtualMachineSizeTypesStandardGS44, VirtualMachineSizeTypesStandardGS48, VirtualMachineSizeTypesStandardGS5, VirtualMachineSizeTypesStandardGS516, VirtualMachineSizeTypesStandardGS58, VirtualMachineSizeTypesStandardH16, VirtualMachineSizeTypesStandardH16m, VirtualMachineSizeTypesStandardH16mr, VirtualMachineSizeTypesStandardH16r, VirtualMachineSizeTypesStandardH8, VirtualMachineSizeTypesStandardH8m, VirtualMachineSizeTypesStandardL16s, VirtualMachineSizeTypesStandardL32s, VirtualMachineSizeTypesStandardL4s, VirtualMachineSizeTypesStandardL8s, VirtualMachineSizeTypesStandardM12832ms, VirtualMachineSizeTypesStandardM12864ms, VirtualMachineSizeTypesStandardM128ms, VirtualMachineSizeTypesStandardM128s, VirtualMachineSizeTypesStandardM6416ms, VirtualMachineSizeTypesStandardM6432ms, VirtualMachineSizeTypesStandardM64ms, VirtualMachineSizeTypesStandardM64s, VirtualMachineSizeTypesStandardNC12, VirtualMachineSizeTypesStandardNC12sV2, VirtualMachineSizeTypesStandardNC12sV3, VirtualMachineSizeTypesStandardNC24, VirtualMachineSizeTypesStandardNC24r, VirtualMachineSizeTypesStandardNC24rsV2, VirtualMachineSizeTypesStandardNC24rsV3, VirtualMachineSizeTypesStandardNC24sV2, VirtualMachineSizeTypesStandardNC24sV3, VirtualMachineSizeTypesStandardNC6, VirtualMachineSizeTypesStandardNC6sV2, VirtualMachineSizeTypesStandardNC6sV3, VirtualMachineSizeTypesStandardND12s, VirtualMachineSizeTypesStandardND24rs, VirtualMachineSizeTypesStandardND24s, VirtualMachineSizeTypesStandardND6s, VirtualMachineSizeTypesStandardNV12, VirtualMachineSizeTypesStandardNV24, VirtualMachineSizeTypesStandardNV6} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleries.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleries.go deleted file mode 100644 index ab5af41db..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleries.go +++ /dev/null @@ -1,497 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// GalleriesClient is the compute Client -type GalleriesClient struct { - BaseClient -} - -// NewGalleriesClient creates an instance of the GalleriesClient client. -func NewGalleriesClient(subscriptionID string) GalleriesClient { - return NewGalleriesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewGalleriesClientWithBaseURI creates an instance of the GalleriesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewGalleriesClientWithBaseURI(baseURI string, subscriptionID string) GalleriesClient { - return GalleriesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a Shared Image Gallery. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery. The allowed characters are alphabets and numbers with -// dots and periods allowed in the middle. The maximum length is 80 characters. -// gallery - parameters supplied to the create or update Shared Image Gallery operation. -func (client GalleriesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery) (result GalleriesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleriesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, galleryName, gallery) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client GalleriesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, galleryName string, gallery Gallery) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}", pathParameters), - autorest.WithJSON(gallery), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client GalleriesClient) CreateOrUpdateSender(req *http.Request) (future GalleriesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client GalleriesClient) CreateOrUpdateResponder(resp *http.Response) (result Gallery, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete a Shared Image Gallery. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery to be deleted. -func (client GalleriesClient) Delete(ctx context.Context, resourceGroupName string, galleryName string) (result GalleriesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleriesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, galleryName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client GalleriesClient) DeletePreparer(ctx context.Context, resourceGroupName string, galleryName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client GalleriesClient) DeleteSender(req *http.Request) (future GalleriesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client GalleriesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves information about a Shared Image Gallery. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery. -func (client GalleriesClient) Get(ctx context.Context, resourceGroupName string, galleryName string) (result Gallery, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleriesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, galleryName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client GalleriesClient) GetPreparer(ctx context.Context, resourceGroupName string, galleryName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client GalleriesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client GalleriesClient) GetResponder(resp *http.Response) (result Gallery, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list galleries under a subscription. -func (client GalleriesClient) List(ctx context.Context) (result GalleryListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleriesClient.List") - defer func() { - sc := -1 - if result.gl.Response.Response != nil { - sc = result.gl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.gl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "List", resp, "Failure sending request") - return - } - - result.gl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "List", resp, "Failure responding to request") - return - } - if result.gl.hasNextLink() && result.gl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client GalleriesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/galleries", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client GalleriesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client GalleriesClient) ListResponder(resp *http.Response) (result GalleryList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client GalleriesClient) listNextResults(ctx context.Context, lastResults GalleryList) (result GalleryList, err error) { - req, err := lastResults.galleryListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.GalleriesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.GalleriesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client GalleriesClient) ListComplete(ctx context.Context) (result GalleryListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleriesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup list galleries under a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client GalleriesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result GalleryListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleriesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.gl.Response.Response != nil { - sc = result.gl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.gl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.gl, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.gl.hasNextLink() && result.gl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client GalleriesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client GalleriesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client GalleriesClient) ListByResourceGroupResponder(resp *http.Response) (result GalleryList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client GalleriesClient) listByResourceGroupNextResults(ctx context.Context, lastResults GalleryList) (result GalleryList, err error) { - req, err := lastResults.galleryListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.GalleriesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.GalleriesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client GalleriesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result GalleryListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleriesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleryimages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleryimages.go deleted file mode 100644 index 9e2499ada..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleryimages.go +++ /dev/null @@ -1,406 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// GalleryImagesClient is the compute Client -type GalleryImagesClient struct { - BaseClient -} - -// NewGalleryImagesClient creates an instance of the GalleryImagesClient client. -func NewGalleryImagesClient(subscriptionID string) GalleryImagesClient { - return NewGalleryImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewGalleryImagesClientWithBaseURI creates an instance of the GalleryImagesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewGalleryImagesClientWithBaseURI(baseURI string, subscriptionID string) GalleryImagesClient { - return GalleryImagesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a gallery Image Definition. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery in which the Image Definition is to be created. -// galleryImageName - the name of the gallery Image Definition to be created or updated. The allowed characters -// are alphabets and numbers with dots, dashes, and periods allowed in the middle. The maximum length is 80 -// characters. -// galleryImage - parameters supplied to the create or update gallery image operation. -func (client GalleryImagesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage) (result GalleryImagesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImagesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: galleryImage, - Constraints: []validation.Constraint{{Target: "galleryImage.GalleryImageProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "galleryImage.GalleryImageProperties.Identifier", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "galleryImage.GalleryImageProperties.Identifier.Publisher", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "galleryImage.GalleryImageProperties.Identifier.Offer", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "galleryImage.GalleryImageProperties.Identifier.Sku", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("compute.GalleryImagesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, galleryName, galleryImageName, galleryImage) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client GalleryImagesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImage GalleryImage) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryImageName": autorest.Encode("path", galleryImageName), - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}", pathParameters), - autorest.WithJSON(galleryImage), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImagesClient) CreateOrUpdateSender(req *http.Request) (future GalleryImagesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client GalleryImagesClient) CreateOrUpdateResponder(resp *http.Response) (result GalleryImage, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete a gallery image. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery in which the Image Definition is to be deleted. -// galleryImageName - the name of the gallery Image Definition to be deleted. -func (client GalleryImagesClient) Delete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string) (result GalleryImagesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImagesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, galleryName, galleryImageName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client GalleryImagesClient) DeletePreparer(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryImageName": autorest.Encode("path", galleryImageName), - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImagesClient) DeleteSender(req *http.Request) (future GalleryImagesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client GalleryImagesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves information about a gallery Image Definition. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery from which the Image Definitions are to be retrieved. -// galleryImageName - the name of the gallery Image Definition to be retrieved. -func (client GalleryImagesClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string) (result GalleryImage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImagesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, galleryName, galleryImageName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client GalleryImagesClient) GetPreparer(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryImageName": autorest.Encode("path", galleryImageName), - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImagesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client GalleryImagesClient) GetResponder(resp *http.Response) (result GalleryImage, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByGallery list gallery Image Definitions in a gallery. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery from which Image Definitions are to be listed. -func (client GalleryImagesClient) ListByGallery(ctx context.Context, resourceGroupName string, galleryName string) (result GalleryImageListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImagesClient.ListByGallery") - defer func() { - sc := -1 - if result.gil.Response.Response != nil { - sc = result.gil.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByGalleryNextResults - req, err := client.ListByGalleryPreparer(ctx, resourceGroupName, galleryName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "ListByGallery", nil, "Failure preparing request") - return - } - - resp, err := client.ListByGallerySender(req) - if err != nil { - result.gil.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "ListByGallery", resp, "Failure sending request") - return - } - - result.gil, err = client.ListByGalleryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "ListByGallery", resp, "Failure responding to request") - return - } - if result.gil.hasNextLink() && result.gil.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByGalleryPreparer prepares the ListByGallery request. -func (client GalleryImagesClient) ListByGalleryPreparer(ctx context.Context, resourceGroupName string, galleryName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByGallerySender sends the ListByGallery request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImagesClient) ListByGallerySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByGalleryResponder handles the response to the ListByGallery request. The method always -// closes the http.Response Body. -func (client GalleryImagesClient) ListByGalleryResponder(resp *http.Response) (result GalleryImageList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByGalleryNextResults retrieves the next set of results, if any. -func (client GalleryImagesClient) listByGalleryNextResults(ctx context.Context, lastResults GalleryImageList) (result GalleryImageList, err error) { - req, err := lastResults.galleryImageListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "listByGalleryNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByGallerySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "listByGalleryNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByGalleryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesClient", "listByGalleryNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByGalleryComplete enumerates all values, automatically crossing page boundaries as required. -func (client GalleryImagesClient) ListByGalleryComplete(ctx context.Context, resourceGroupName string, galleryName string) (result GalleryImageListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImagesClient.ListByGallery") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByGallery(ctx, resourceGroupName, galleryName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleryimageversions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleryimageversions.go deleted file mode 100644 index b61e419dc..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/galleryimageversions.go +++ /dev/null @@ -1,415 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// GalleryImageVersionsClient is the compute Client -type GalleryImageVersionsClient struct { - BaseClient -} - -// NewGalleryImageVersionsClient creates an instance of the GalleryImageVersionsClient client. -func NewGalleryImageVersionsClient(subscriptionID string) GalleryImageVersionsClient { - return NewGalleryImageVersionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewGalleryImageVersionsClientWithBaseURI creates an instance of the GalleryImageVersionsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewGalleryImageVersionsClientWithBaseURI(baseURI string, subscriptionID string) GalleryImageVersionsClient { - return GalleryImageVersionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a gallery Image Version. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery in which the Image Definition resides. -// galleryImageName - the name of the gallery Image Definition in which the Image Version is to be created. -// galleryImageVersionName - the name of the gallery Image Version to be created. Needs to follow semantic -// version name pattern: The allowed characters are digit and period. Digits must be within the range of a -// 32-bit integer. Format: .. -// galleryImageVersion - parameters supplied to the create or update gallery Image Version operation. -func (client GalleryImageVersionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion) (result GalleryImageVersionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageVersionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: galleryImageVersion, - Constraints: []validation.Constraint{{Target: "galleryImageVersion.GalleryImageVersionProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "galleryImageVersion.GalleryImageVersionProperties.PublishingProfile", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("compute.GalleryImageVersionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client GalleryImageVersionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, galleryImageVersion GalleryImageVersion) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryImageName": autorest.Encode("path", galleryImageName), - "galleryImageVersionName": autorest.Encode("path", galleryImageVersionName), - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}", pathParameters), - autorest.WithJSON(galleryImageVersion), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImageVersionsClient) CreateOrUpdateSender(req *http.Request) (future GalleryImageVersionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client GalleryImageVersionsClient) CreateOrUpdateResponder(resp *http.Response) (result GalleryImageVersion, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete a gallery Image Version. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery in which the Image Definition resides. -// galleryImageName - the name of the gallery Image Definition in which the Image Version resides. -// galleryImageVersionName - the name of the gallery Image Version to be deleted. -func (client GalleryImageVersionsClient) Delete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string) (result GalleryImageVersionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageVersionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client GalleryImageVersionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryImageName": autorest.Encode("path", galleryImageName), - "galleryImageVersionName": autorest.Encode("path", galleryImageVersionName), - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImageVersionsClient) DeleteSender(req *http.Request) (future GalleryImageVersionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client GalleryImageVersionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves information about a gallery Image Version. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery in which the Image Definition resides. -// galleryImageName - the name of the gallery Image Definition in which the Image Version resides. -// galleryImageVersionName - the name of the gallery Image Version to be retrieved. -// expand - the expand expression to apply on the operation. -func (client GalleryImageVersionsClient) Get(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, expand ReplicationStatusTypes) (result GalleryImageVersion, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageVersionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client GalleryImageVersionsClient) GetPreparer(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, galleryImageVersionName string, expand ReplicationStatusTypes) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryImageName": autorest.Encode("path", galleryImageName), - "galleryImageVersionName": autorest.Encode("path", galleryImageVersionName), - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(string(expand)) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImageVersionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client GalleryImageVersionsClient) GetResponder(resp *http.Response) (result GalleryImageVersion, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByGalleryImage list gallery Image Versions in a gallery Image Definition. -// Parameters: -// resourceGroupName - the name of the resource group. -// galleryName - the name of the Shared Image Gallery in which the Image Definition resides. -// galleryImageName - the name of the Shared Image Gallery Image Definition from which the Image Versions are -// to be listed. -func (client GalleryImageVersionsClient) ListByGalleryImage(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string) (result GalleryImageVersionListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageVersionsClient.ListByGalleryImage") - defer func() { - sc := -1 - if result.givl.Response.Response != nil { - sc = result.givl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByGalleryImageNextResults - req, err := client.ListByGalleryImagePreparer(ctx, resourceGroupName, galleryName, galleryImageName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "ListByGalleryImage", nil, "Failure preparing request") - return - } - - resp, err := client.ListByGalleryImageSender(req) - if err != nil { - result.givl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "ListByGalleryImage", resp, "Failure sending request") - return - } - - result.givl, err = client.ListByGalleryImageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "ListByGalleryImage", resp, "Failure responding to request") - return - } - if result.givl.hasNextLink() && result.givl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByGalleryImagePreparer prepares the ListByGalleryImage request. -func (client GalleryImageVersionsClient) ListByGalleryImagePreparer(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "galleryImageName": autorest.Encode("path", galleryImageName), - "galleryName": autorest.Encode("path", galleryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByGalleryImageSender sends the ListByGalleryImage request. The method will close the -// http.Response Body if it receives an error. -func (client GalleryImageVersionsClient) ListByGalleryImageSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByGalleryImageResponder handles the response to the ListByGalleryImage request. The method always -// closes the http.Response Body. -func (client GalleryImageVersionsClient) ListByGalleryImageResponder(resp *http.Response) (result GalleryImageVersionList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByGalleryImageNextResults retrieves the next set of results, if any. -func (client GalleryImageVersionsClient) listByGalleryImageNextResults(ctx context.Context, lastResults GalleryImageVersionList) (result GalleryImageVersionList, err error) { - req, err := lastResults.galleryImageVersionListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "listByGalleryImageNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByGalleryImageSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "listByGalleryImageNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByGalleryImageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsClient", "listByGalleryImageNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByGalleryImageComplete enumerates all values, automatically crossing page boundaries as required. -func (client GalleryImageVersionsClient) ListByGalleryImageComplete(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string) (result GalleryImageVersionListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageVersionsClient.ListByGalleryImage") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByGalleryImage(ctx, resourceGroupName, galleryName, galleryImageName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/images.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/images.go deleted file mode 100644 index 12fdabd9f..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/images.go +++ /dev/null @@ -1,583 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ImagesClient is the compute Client -type ImagesClient struct { - BaseClient -} - -// NewImagesClient creates an instance of the ImagesClient client. -func NewImagesClient(subscriptionID string) ImagesClient { - return NewImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewImagesClientWithBaseURI creates an instance of the ImagesClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewImagesClientWithBaseURI(baseURI string, subscriptionID string) ImagesClient { - return ImagesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update an image. -// Parameters: -// resourceGroupName - the name of the resource group. -// imageName - the name of the image. -// parameters - parameters supplied to the Create Image operation. -func (client ImagesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, imageName string, parameters Image) (result ImagesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, imageName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ImagesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, imageName string, parameters Image) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "imageName": autorest.Encode("path", imageName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ImagesClient) CreateOrUpdateSender(req *http.Request) (future ImagesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ImagesClient) CreateOrUpdateResponder(resp *http.Response) (result Image, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes an Image. -// Parameters: -// resourceGroupName - the name of the resource group. -// imageName - the name of the image. -func (client ImagesClient) Delete(ctx context.Context, resourceGroupName string, imageName string) (result ImagesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, imageName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ImagesClient) DeletePreparer(ctx context.Context, resourceGroupName string, imageName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "imageName": autorest.Encode("path", imageName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ImagesClient) DeleteSender(req *http.Request) (future ImagesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ImagesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets an image. -// Parameters: -// resourceGroupName - the name of the resource group. -// imageName - the name of the image. -// expand - the expand expression to apply on the operation. -func (client ImagesClient) Get(ctx context.Context, resourceGroupName string, imageName string, expand string) (result Image, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, imageName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ImagesClient) GetPreparer(ctx context.Context, resourceGroupName string, imageName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "imageName": autorest.Encode("path", imageName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ImagesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ImagesClient) GetResponder(resp *http.Response) (result Image, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets the list of Images in the subscription. Use nextLink property in the response to get the next page of -// Images. Do this till nextLink is null to fetch all the Images. -func (client ImagesClient) List(ctx context.Context) (result ImageListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.List") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "List", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "List", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ImagesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/images", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ImagesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ImagesClient) ListResponder(resp *http.Response) (result ImageListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ImagesClient) listNextResults(ctx context.Context, lastResults ImageListResult) (result ImageListResult, err error) { - req, err := lastResults.imageListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ImagesClient) ListComplete(ctx context.Context) (result ImageListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets the list of images under a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ImagesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ImageListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ImagesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ImagesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ImagesClient) ListByResourceGroupResponder(resp *http.Response) (result ImageListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ImagesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ImageListResult) (result ImageListResult, err error) { - req, err := lastResults.imageListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ImagesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ImageListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// Update update an image. -// Parameters: -// resourceGroupName - the name of the resource group. -// imageName - the name of the image. -// parameters - parameters supplied to the Update Image operation. -func (client ImagesClient) Update(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate) (result ImagesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, imageName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ImagesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, imageName string, parameters ImageUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "imageName": autorest.Encode("path", imageName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client ImagesClient) UpdateSender(req *http.Request) (future ImagesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ImagesClient) UpdateResponder(resp *http.Response) (result Image, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/loganalytics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/loganalytics.go deleted file mode 100644 index 299f7c184..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/loganalytics.go +++ /dev/null @@ -1,206 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LogAnalyticsClient is the compute Client -type LogAnalyticsClient struct { - BaseClient -} - -// NewLogAnalyticsClient creates an instance of the LogAnalyticsClient client. -func NewLogAnalyticsClient(subscriptionID string) LogAnalyticsClient { - return NewLogAnalyticsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLogAnalyticsClientWithBaseURI creates an instance of the LogAnalyticsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewLogAnalyticsClientWithBaseURI(baseURI string, subscriptionID string) LogAnalyticsClient { - return LogAnalyticsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// ExportRequestRateByInterval export logs that show Api requests made by this subscription in the given time window to -// show throttling activities. -// Parameters: -// parameters - parameters supplied to the LogAnalytics getRequestRateByInterval Api. -// location - the location upon which virtual-machine-sizes is queried. -func (client LogAnalyticsClient) ExportRequestRateByInterval(ctx context.Context, parameters RequestRateByIntervalInput, location string) (result LogAnalyticsExportRequestRateByIntervalFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LogAnalyticsClient.ExportRequestRateByInterval") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.LogAnalyticsClient", "ExportRequestRateByInterval", err.Error()) - } - - req, err := client.ExportRequestRateByIntervalPreparer(ctx, parameters, location) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsClient", "ExportRequestRateByInterval", nil, "Failure preparing request") - return - } - - result, err = client.ExportRequestRateByIntervalSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsClient", "ExportRequestRateByInterval", result.Response(), "Failure sending request") - return - } - - return -} - -// ExportRequestRateByIntervalPreparer prepares the ExportRequestRateByInterval request. -func (client LogAnalyticsClient) ExportRequestRateByIntervalPreparer(ctx context.Context, parameters RequestRateByIntervalInput, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getRequestRateByInterval", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ExportRequestRateByIntervalSender sends the ExportRequestRateByInterval request. The method will close the -// http.Response Body if it receives an error. -func (client LogAnalyticsClient) ExportRequestRateByIntervalSender(req *http.Request) (future LogAnalyticsExportRequestRateByIntervalFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ExportRequestRateByIntervalResponder handles the response to the ExportRequestRateByInterval request. The method always -// closes the http.Response Body. -func (client LogAnalyticsClient) ExportRequestRateByIntervalResponder(resp *http.Response) (result LogAnalyticsOperationResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ExportThrottledRequests export logs that show total throttled Api requests for this subscription in the given time -// window. -// Parameters: -// parameters - parameters supplied to the LogAnalytics getThrottledRequests Api. -// location - the location upon which virtual-machine-sizes is queried. -func (client LogAnalyticsClient) ExportThrottledRequests(ctx context.Context, parameters ThrottledRequestsInput, location string) (result LogAnalyticsExportThrottledRequestsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LogAnalyticsClient.ExportThrottledRequests") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.LogAnalyticsClient", "ExportThrottledRequests", err.Error()) - } - - req, err := client.ExportThrottledRequestsPreparer(ctx, parameters, location) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsClient", "ExportThrottledRequests", nil, "Failure preparing request") - return - } - - result, err = client.ExportThrottledRequestsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsClient", "ExportThrottledRequests", result.Response(), "Failure sending request") - return - } - - return -} - -// ExportThrottledRequestsPreparer prepares the ExportThrottledRequests request. -func (client LogAnalyticsClient) ExportThrottledRequestsPreparer(ctx context.Context, parameters ThrottledRequestsInput, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getThrottledRequests", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ExportThrottledRequestsSender sends the ExportThrottledRequests request. The method will close the -// http.Response Body if it receives an error. -func (client LogAnalyticsClient) ExportThrottledRequestsSender(req *http.Request) (future LogAnalyticsExportThrottledRequestsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ExportThrottledRequestsResponder handles the response to the ExportThrottledRequests request. The method always -// closes the http.Response Body. -func (client LogAnalyticsClient) ExportThrottledRequestsResponder(resp *http.Response) (result LogAnalyticsOperationResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/models.go deleted file mode 100644 index 9aed45caa..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/models.go +++ /dev/null @@ -1,11533 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute" - -// AccessURI a disk access SAS uri. -type AccessURI struct { - autorest.Response `json:"-"` - // AccessSAS - READ-ONLY; A SAS uri for accessing a disk. - AccessSAS *string `json:"accessSAS,omitempty"` -} - -// MarshalJSON is the custom marshaler for AccessURI. -func (au AccessURI) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// AdditionalCapabilities enables or disables a capability on the virtual machine or virtual machine scale -// set. -type AdditionalCapabilities struct { - // UltraSSDEnabled - The flag that enables or disables a capability to have one or more managed data disks with UltraSSD_LRS storage account type on the VM or VMSS. Managed disks with storage account type UltraSSD_LRS can be added to a virtual machine or virtual machine scale set only if this property is enabled. - UltraSSDEnabled *bool `json:"ultraSSDEnabled,omitempty"` -} - -// AdditionalUnattendContent specifies additional XML formatted information that can be included in the -// Unattend.xml file, which is used by Windows Setup. Contents are defined by setting name, component name, -// and the pass in which the content is applied. -type AdditionalUnattendContent struct { - // PassName - The pass name. Currently, the only allowable value is OobeSystem. Possible values include: 'OobeSystem' - PassName PassNames `json:"passName,omitempty"` - // ComponentName - The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup. Possible values include: 'MicrosoftWindowsShellSetup' - ComponentName ComponentNames `json:"componentName,omitempty"` - // SettingName - Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon. Possible values include: 'AutoLogon', 'FirstLogonCommands' - SettingName SettingNames `json:"settingName,omitempty"` - // Content - Specifies the XML formatted content that is added to the unattend.xml file for the specified path and component. The XML must be less than 4KB and must include the root element for the setting or feature that is being inserted. - Content *string `json:"content,omitempty"` -} - -// APIEntityReference the API entity reference. -type APIEntityReference struct { - // ID - The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... - ID *string `json:"id,omitempty"` -} - -// APIError api error. -type APIError struct { - // Details - The Api error details - Details *[]APIErrorBase `json:"details,omitempty"` - // Innererror - The Api inner error - Innererror *InnerError `json:"innererror,omitempty"` - // Code - The error code. - Code *string `json:"code,omitempty"` - // Target - The target of the particular error. - Target *string `json:"target,omitempty"` - // Message - The error message. - Message *string `json:"message,omitempty"` -} - -// APIErrorBase api error base. -type APIErrorBase struct { - // Code - The error code. - Code *string `json:"code,omitempty"` - // Target - The target of the particular error. - Target *string `json:"target,omitempty"` - // Message - The error message. - Message *string `json:"message,omitempty"` -} - -// AutomaticOSUpgradePolicy the configuration parameters used for performing automatic OS upgrade. -type AutomaticOSUpgradePolicy struct { - // EnableAutomaticOSUpgrade - Indicates whether OS upgrades should automatically be applied to scale set instances in a rolling fashion when a newer version of the OS image becomes available. Default value is false. If this is set to true for Windows based scale sets, recommendation is to set [enableAutomaticUpdates](https://docs.microsoft.com/dotnet/api/microsoft.azure.management.compute.models.windowsconfiguration.enableautomaticupdates?view=azure-dotnet) to false. - EnableAutomaticOSUpgrade *bool `json:"enableAutomaticOSUpgrade,omitempty"` - // DisableAutomaticRollback - Whether OS image rollback feature should be disabled. Default value is false. - DisableAutomaticRollback *bool `json:"disableAutomaticRollback,omitempty"` -} - -// AutomaticOSUpgradeProperties describes automatic OS upgrade properties on the image. -type AutomaticOSUpgradeProperties struct { - // AutomaticOSUpgradeSupported - Specifies whether automatic OS upgrade is supported on the image. - AutomaticOSUpgradeSupported *bool `json:"automaticOSUpgradeSupported,omitempty"` -} - -// AutomaticRepairsPolicy specifies the configuration parameters for automatic repairs on the virtual -// machine scale set. -type AutomaticRepairsPolicy struct { - // Enabled - Specifies whether automatic repairs should be enabled on the virtual machine scale set. The default value is false. - Enabled *bool `json:"enabled,omitempty"` - // GracePeriod - The amount of time for which automatic repairs are suspended due to a state change on VM. The grace time starts after the state change has completed. This helps avoid premature or accidental repairs. The time duration should be specified in ISO 8601 format. The minimum allowed grace period is 30 minutes (PT30M), which is also the default value. The maximum allowed grace period is 90 minutes (PT90M). - GracePeriod *string `json:"gracePeriod,omitempty"` -} - -// AvailabilitySet specifies information about the availability set that the virtual machine should be -// assigned to. Virtual machines specified in the same availability set are allocated to different nodes to -// maximize availability. For more information about availability sets, see [Manage the availability of -// virtual -// machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). -//

      For more information on Azure planned maintenance, see [Planned maintenance for virtual -// machines in -// Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) -//

      Currently, a VM can only be added to availability set at creation time. An existing VM cannot -// be added to an availability set. -type AvailabilitySet struct { - autorest.Response `json:"-"` - *AvailabilitySetProperties `json:"properties,omitempty"` - // Sku - Sku of the availability set, only name is required to be set. See AvailabilitySetSkuTypes for possible set of values. Use 'Aligned' for virtual machines with managed disks and 'Classic' for virtual machines with unmanaged disks. Default value is 'Classic'. - Sku *Sku `json:"sku,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for AvailabilitySet. -func (as AvailabilitySet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if as.AvailabilitySetProperties != nil { - objectMap["properties"] = as.AvailabilitySetProperties - } - if as.Sku != nil { - objectMap["sku"] = as.Sku - } - if as.Location != nil { - objectMap["location"] = as.Location - } - if as.Tags != nil { - objectMap["tags"] = as.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AvailabilitySet struct. -func (as *AvailabilitySet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var availabilitySetProperties AvailabilitySetProperties - err = json.Unmarshal(*v, &availabilitySetProperties) - if err != nil { - return err - } - as.AvailabilitySetProperties = &availabilitySetProperties - } - case "sku": - if v != nil { - var sku Sku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - as.Sku = &sku - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - as.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - as.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - as.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - as.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - as.Tags = tags - } - } - } - - return nil -} - -// AvailabilitySetListResult the List Availability Set operation response. -type AvailabilitySetListResult struct { - autorest.Response `json:"-"` - // Value - The list of availability sets - Value *[]AvailabilitySet `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of AvailabilitySets. Call ListNext() with this URI to fetch the next page of AvailabilitySets. - NextLink *string `json:"nextLink,omitempty"` -} - -// AvailabilitySetListResultIterator provides access to a complete listing of AvailabilitySet values. -type AvailabilitySetListResultIterator struct { - i int - page AvailabilitySetListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AvailabilitySetListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AvailabilitySetListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AvailabilitySetListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AvailabilitySetListResultIterator) Response() AvailabilitySetListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AvailabilitySetListResultIterator) Value() AvailabilitySet { - if !iter.page.NotDone() { - return AvailabilitySet{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AvailabilitySetListResultIterator type. -func NewAvailabilitySetListResultIterator(page AvailabilitySetListResultPage) AvailabilitySetListResultIterator { - return AvailabilitySetListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (aslr AvailabilitySetListResult) IsEmpty() bool { - return aslr.Value == nil || len(*aslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (aslr AvailabilitySetListResult) hasNextLink() bool { - return aslr.NextLink != nil && len(*aslr.NextLink) != 0 -} - -// availabilitySetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (aslr AvailabilitySetListResult) availabilitySetListResultPreparer(ctx context.Context) (*http.Request, error) { - if !aslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(aslr.NextLink))) -} - -// AvailabilitySetListResultPage contains a page of AvailabilitySet values. -type AvailabilitySetListResultPage struct { - fn func(context.Context, AvailabilitySetListResult) (AvailabilitySetListResult, error) - aslr AvailabilitySetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AvailabilitySetListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilitySetListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.aslr) - if err != nil { - return err - } - page.aslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AvailabilitySetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AvailabilitySetListResultPage) NotDone() bool { - return !page.aslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AvailabilitySetListResultPage) Response() AvailabilitySetListResult { - return page.aslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AvailabilitySetListResultPage) Values() []AvailabilitySet { - if page.aslr.IsEmpty() { - return nil - } - return *page.aslr.Value -} - -// Creates a new instance of the AvailabilitySetListResultPage type. -func NewAvailabilitySetListResultPage(cur AvailabilitySetListResult, getNextPage func(context.Context, AvailabilitySetListResult) (AvailabilitySetListResult, error)) AvailabilitySetListResultPage { - return AvailabilitySetListResultPage{ - fn: getNextPage, - aslr: cur, - } -} - -// AvailabilitySetProperties the instance view of a resource. -type AvailabilitySetProperties struct { - // PlatformUpdateDomainCount - Update Domain count. - PlatformUpdateDomainCount *int32 `json:"platformUpdateDomainCount,omitempty"` - // PlatformFaultDomainCount - Fault Domain count. - PlatformFaultDomainCount *int32 `json:"platformFaultDomainCount,omitempty"` - // VirtualMachines - A list of references to all virtual machines in the availability set. - VirtualMachines *[]SubResource `json:"virtualMachines,omitempty"` - // ProximityPlacementGroup - Specifies information about the proximity placement group that the availability set should be assigned to.

      Minimum api-version: 2018-04-01. - ProximityPlacementGroup *SubResource `json:"proximityPlacementGroup,omitempty"` - // Statuses - READ-ONLY; The resource status information. - Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` -} - -// MarshalJSON is the custom marshaler for AvailabilitySetProperties. -func (asp AvailabilitySetProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if asp.PlatformUpdateDomainCount != nil { - objectMap["platformUpdateDomainCount"] = asp.PlatformUpdateDomainCount - } - if asp.PlatformFaultDomainCount != nil { - objectMap["platformFaultDomainCount"] = asp.PlatformFaultDomainCount - } - if asp.VirtualMachines != nil { - objectMap["virtualMachines"] = asp.VirtualMachines - } - if asp.ProximityPlacementGroup != nil { - objectMap["proximityPlacementGroup"] = asp.ProximityPlacementGroup - } - return json.Marshal(objectMap) -} - -// AvailabilitySetUpdate specifies information about the availability set that the virtual machine should -// be assigned to. Only tags may be updated. -type AvailabilitySetUpdate struct { - *AvailabilitySetProperties `json:"properties,omitempty"` - // Sku - Sku of the availability set - Sku *Sku `json:"sku,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for AvailabilitySetUpdate. -func (asu AvailabilitySetUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if asu.AvailabilitySetProperties != nil { - objectMap["properties"] = asu.AvailabilitySetProperties - } - if asu.Sku != nil { - objectMap["sku"] = asu.Sku - } - if asu.Tags != nil { - objectMap["tags"] = asu.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AvailabilitySetUpdate struct. -func (asu *AvailabilitySetUpdate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var availabilitySetProperties AvailabilitySetProperties - err = json.Unmarshal(*v, &availabilitySetProperties) - if err != nil { - return err - } - asu.AvailabilitySetProperties = &availabilitySetProperties - } - case "sku": - if v != nil { - var sku Sku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - asu.Sku = &sku - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - asu.Tags = tags - } - } - } - - return nil -} - -// BootDiagnostics boot Diagnostics is a debugging feature which allows you to view Console Output and -// Screenshot to diagnose VM status.

      You can easily view the output of your console log.

      -// Azure also enables you to see a screenshot of the VM from the hypervisor. -type BootDiagnostics struct { - // Enabled - Whether boot diagnostics should be enabled on the Virtual Machine. - Enabled *bool `json:"enabled,omitempty"` - // StorageURI - Uri of the storage account to use for placing the console output and screenshot. - StorageURI *string `json:"storageUri,omitempty"` -} - -// BootDiagnosticsInstanceView the instance view of a virtual machine boot diagnostics. -type BootDiagnosticsInstanceView struct { - // ConsoleScreenshotBlobURI - READ-ONLY; The console screenshot blob URI. - ConsoleScreenshotBlobURI *string `json:"consoleScreenshotBlobUri,omitempty"` - // SerialConsoleLogBlobURI - READ-ONLY; The Linux serial console log blob Uri. - SerialConsoleLogBlobURI *string `json:"serialConsoleLogBlobUri,omitempty"` - // Status - READ-ONLY; The boot diagnostics status information for the VM.

      NOTE: It will be set only if there are errors encountered in enabling boot diagnostics. - Status *InstanceViewStatus `json:"status,omitempty"` -} - -// MarshalJSON is the custom marshaler for BootDiagnosticsInstanceView. -func (bdiv BootDiagnosticsInstanceView) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// CloudError an error response from the Gallery service. -type CloudError struct { - Error *APIError `json:"error,omitempty"` -} - -// ContainerService container service. -type ContainerService struct { - autorest.Response `json:"-"` - *ContainerServiceProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ContainerService. -func (cs ContainerService) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cs.ContainerServiceProperties != nil { - objectMap["properties"] = cs.ContainerServiceProperties - } - if cs.Location != nil { - objectMap["location"] = cs.Location - } - if cs.Tags != nil { - objectMap["tags"] = cs.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerService struct. -func (cs *ContainerService) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var containerServiceProperties ContainerServiceProperties - err = json.Unmarshal(*v, &containerServiceProperties) - if err != nil { - return err - } - cs.ContainerServiceProperties = &containerServiceProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cs.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cs.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cs.Tags = tags - } - } - } - - return nil -} - -// ContainerServiceAgentPoolProfile profile for the container service agent pool. -type ContainerServiceAgentPoolProfile struct { - // Name - Unique name of the agent pool profile in the context of the subscription and resource group. - Name *string `json:"name,omitempty"` - // Count - Number of agents (VMs) to host docker containers. Allowed values must be in the range of 1 to 100 (inclusive). The default value is 1. - Count *int32 `json:"count,omitempty"` - // VMSize - Size of agent VMs. Possible values include: 'StandardA0', 'StandardA1', 'StandardA2', 'StandardA3', 'StandardA4', 'StandardA5', 'StandardA6', 'StandardA7', 'StandardA8', 'StandardA9', 'StandardA10', 'StandardA11', 'StandardD1', 'StandardD2', 'StandardD3', 'StandardD4', 'StandardD11', 'StandardD12', 'StandardD13', 'StandardD14', 'StandardD1V2', 'StandardD2V2', 'StandardD3V2', 'StandardD4V2', 'StandardD5V2', 'StandardD11V2', 'StandardD12V2', 'StandardD13V2', 'StandardD14V2', 'StandardG1', 'StandardG2', 'StandardG3', 'StandardG4', 'StandardG5', 'StandardDS1', 'StandardDS2', 'StandardDS3', 'StandardDS4', 'StandardDS11', 'StandardDS12', 'StandardDS13', 'StandardDS14', 'StandardGS1', 'StandardGS2', 'StandardGS3', 'StandardGS4', 'StandardGS5' - VMSize ContainerServiceVMSizeTypes `json:"vmSize,omitempty"` - // DNSPrefix - DNS prefix to be used to create the FQDN for the agent pool. - DNSPrefix *string `json:"dnsPrefix,omitempty"` - // Fqdn - READ-ONLY; FQDN for the agent pool. - Fqdn *string `json:"fqdn,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerServiceAgentPoolProfile. -func (csapp ContainerServiceAgentPoolProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csapp.Name != nil { - objectMap["name"] = csapp.Name - } - if csapp.Count != nil { - objectMap["count"] = csapp.Count - } - if csapp.VMSize != "" { - objectMap["vmSize"] = csapp.VMSize - } - if csapp.DNSPrefix != nil { - objectMap["dnsPrefix"] = csapp.DNSPrefix - } - return json.Marshal(objectMap) -} - -// ContainerServiceCustomProfile properties to configure a custom container service cluster. -type ContainerServiceCustomProfile struct { - // Orchestrator - The name of the custom orchestrator to use. - Orchestrator *string `json:"orchestrator,omitempty"` -} - -// ContainerServiceDiagnosticsProfile ... -type ContainerServiceDiagnosticsProfile struct { - // VMDiagnostics - Profile for the container service VM diagnostic agent. - VMDiagnostics *ContainerServiceVMDiagnostics `json:"vmDiagnostics,omitempty"` -} - -// ContainerServiceLinuxProfile profile for Linux VMs in the container service cluster. -type ContainerServiceLinuxProfile struct { - // AdminUsername - The administrator username to use for Linux VMs. - AdminUsername *string `json:"adminUsername,omitempty"` - // SSH - The ssh key configuration for Linux VMs. - SSH *ContainerServiceSSHConfiguration `json:"ssh,omitempty"` -} - -// ContainerServiceListResult the response from the List Container Services operation. -type ContainerServiceListResult struct { - autorest.Response `json:"-"` - // Value - the list of container services. - Value *[]ContainerService `json:"value,omitempty"` - // NextLink - The URL to get the next set of container service results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ContainerServiceListResultIterator provides access to a complete listing of ContainerService values. -type ContainerServiceListResultIterator struct { - i int - page ContainerServiceListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ContainerServiceListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServiceListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ContainerServiceListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ContainerServiceListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ContainerServiceListResultIterator) Response() ContainerServiceListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ContainerServiceListResultIterator) Value() ContainerService { - if !iter.page.NotDone() { - return ContainerService{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ContainerServiceListResultIterator type. -func NewContainerServiceListResultIterator(page ContainerServiceListResultPage) ContainerServiceListResultIterator { - return ContainerServiceListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (cslr ContainerServiceListResult) IsEmpty() bool { - return cslr.Value == nil || len(*cslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (cslr ContainerServiceListResult) hasNextLink() bool { - return cslr.NextLink != nil && len(*cslr.NextLink) != 0 -} - -// containerServiceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (cslr ContainerServiceListResult) containerServiceListResultPreparer(ctx context.Context) (*http.Request, error) { - if !cslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(cslr.NextLink))) -} - -// ContainerServiceListResultPage contains a page of ContainerService values. -type ContainerServiceListResultPage struct { - fn func(context.Context, ContainerServiceListResult) (ContainerServiceListResult, error) - cslr ContainerServiceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ContainerServiceListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerServiceListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.cslr) - if err != nil { - return err - } - page.cslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ContainerServiceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ContainerServiceListResultPage) NotDone() bool { - return !page.cslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ContainerServiceListResultPage) Response() ContainerServiceListResult { - return page.cslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ContainerServiceListResultPage) Values() []ContainerService { - if page.cslr.IsEmpty() { - return nil - } - return *page.cslr.Value -} - -// Creates a new instance of the ContainerServiceListResultPage type. -func NewContainerServiceListResultPage(cur ContainerServiceListResult, getNextPage func(context.Context, ContainerServiceListResult) (ContainerServiceListResult, error)) ContainerServiceListResultPage { - return ContainerServiceListResultPage{ - fn: getNextPage, - cslr: cur, - } -} - -// ContainerServiceMasterProfile profile for the container service master. -type ContainerServiceMasterProfile struct { - // Count - Number of masters (VMs) in the container service cluster. Allowed values are 1, 3, and 5. The default value is 1. - Count *int32 `json:"count,omitempty"` - // DNSPrefix - DNS prefix to be used to create the FQDN for master. - DNSPrefix *string `json:"dnsPrefix,omitempty"` - // Fqdn - READ-ONLY; FQDN for the master. - Fqdn *string `json:"fqdn,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerServiceMasterProfile. -func (csmp ContainerServiceMasterProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csmp.Count != nil { - objectMap["count"] = csmp.Count - } - if csmp.DNSPrefix != nil { - objectMap["dnsPrefix"] = csmp.DNSPrefix - } - return json.Marshal(objectMap) -} - -// ContainerServiceOrchestratorProfile profile for the container service orchestrator. -type ContainerServiceOrchestratorProfile struct { - // OrchestratorType - The orchestrator to use to manage container service cluster resources. Valid values are Swarm, DCOS, and Custom. Possible values include: 'Swarm', 'DCOS', 'Custom', 'Kubernetes' - OrchestratorType ContainerServiceOrchestratorTypes `json:"orchestratorType,omitempty"` -} - -// ContainerServiceProperties properties of the container service. -type ContainerServiceProperties struct { - // ProvisioningState - READ-ONLY; the current deployment or provisioning state, which only appears in the response. - ProvisioningState *string `json:"provisioningState,omitempty"` - // OrchestratorProfile - Properties of the orchestrator. - OrchestratorProfile *ContainerServiceOrchestratorProfile `json:"orchestratorProfile,omitempty"` - // CustomProfile - Properties for custom clusters. - CustomProfile *ContainerServiceCustomProfile `json:"customProfile,omitempty"` - // ServicePrincipalProfile - Properties for cluster service principals. - ServicePrincipalProfile *ContainerServiceServicePrincipalProfile `json:"servicePrincipalProfile,omitempty"` - // MasterProfile - Properties of master agents. - MasterProfile *ContainerServiceMasterProfile `json:"masterProfile,omitempty"` - // AgentPoolProfiles - Properties of the agent pool. - AgentPoolProfiles *[]ContainerServiceAgentPoolProfile `json:"agentPoolProfiles,omitempty"` - // WindowsProfile - Properties of Windows VMs. - WindowsProfile *ContainerServiceWindowsProfile `json:"windowsProfile,omitempty"` - // LinuxProfile - Properties of Linux VMs. - LinuxProfile *ContainerServiceLinuxProfile `json:"linuxProfile,omitempty"` - // DiagnosticsProfile - Properties of the diagnostic agent. - DiagnosticsProfile *ContainerServiceDiagnosticsProfile `json:"diagnosticsProfile,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerServiceProperties. -func (csp ContainerServiceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csp.OrchestratorProfile != nil { - objectMap["orchestratorProfile"] = csp.OrchestratorProfile - } - if csp.CustomProfile != nil { - objectMap["customProfile"] = csp.CustomProfile - } - if csp.ServicePrincipalProfile != nil { - objectMap["servicePrincipalProfile"] = csp.ServicePrincipalProfile - } - if csp.MasterProfile != nil { - objectMap["masterProfile"] = csp.MasterProfile - } - if csp.AgentPoolProfiles != nil { - objectMap["agentPoolProfiles"] = csp.AgentPoolProfiles - } - if csp.WindowsProfile != nil { - objectMap["windowsProfile"] = csp.WindowsProfile - } - if csp.LinuxProfile != nil { - objectMap["linuxProfile"] = csp.LinuxProfile - } - if csp.DiagnosticsProfile != nil { - objectMap["diagnosticsProfile"] = csp.DiagnosticsProfile - } - return json.Marshal(objectMap) -} - -// ContainerServicesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ContainerServicesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ContainerServicesClient) (ContainerService, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ContainerServicesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ContainerServicesCreateOrUpdateFuture.Result. -func (future *ContainerServicesCreateOrUpdateFuture) result(client ContainerServicesClient) (cs ContainerService, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cs.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.ContainerServicesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cs.Response.Response, err = future.GetResult(sender); err == nil && cs.Response.Response.StatusCode != http.StatusNoContent { - cs, err = client.CreateOrUpdateResponder(cs.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesCreateOrUpdateFuture", "Result", cs.Response.Response, "Failure responding to request") - } - } - return -} - -// ContainerServicesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ContainerServicesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ContainerServicesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ContainerServicesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ContainerServicesDeleteFuture.Result. -func (future *ContainerServicesDeleteFuture) result(client ContainerServicesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ContainerServicesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.ContainerServicesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ContainerServiceServicePrincipalProfile information about a service principal identity for the cluster -// to use for manipulating Azure APIs. -type ContainerServiceServicePrincipalProfile struct { - // ClientID - The ID for the service principal. - ClientID *string `json:"clientId,omitempty"` - // Secret - The secret password associated with the service principal. - Secret *string `json:"secret,omitempty"` -} - -// ContainerServiceSSHConfiguration SSH configuration for Linux-based VMs running on Azure. -type ContainerServiceSSHConfiguration struct { - // PublicKeys - the list of SSH public keys used to authenticate with Linux-based VMs. - PublicKeys *[]ContainerServiceSSHPublicKey `json:"publicKeys,omitempty"` -} - -// ContainerServiceSSHPublicKey contains information about SSH certificate public key data. -type ContainerServiceSSHPublicKey struct { - // KeyData - Certificate public key used to authenticate with VMs through SSH. The certificate must be in PEM format with or without headers. - KeyData *string `json:"keyData,omitempty"` -} - -// ContainerServiceVMDiagnostics profile for diagnostics on the container service VMs. -type ContainerServiceVMDiagnostics struct { - // Enabled - Whether the VM diagnostic agent is provisioned on the VM. - Enabled *bool `json:"enabled,omitempty"` - // StorageURI - READ-ONLY; The URI of the storage account where diagnostics are stored. - StorageURI *string `json:"storageUri,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerServiceVMDiagnostics. -func (csvd ContainerServiceVMDiagnostics) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csvd.Enabled != nil { - objectMap["enabled"] = csvd.Enabled - } - return json.Marshal(objectMap) -} - -// ContainerServiceWindowsProfile profile for Windows VMs in the container service cluster. -type ContainerServiceWindowsProfile struct { - // AdminUsername - The administrator username to use for Windows VMs. - AdminUsername *string `json:"adminUsername,omitempty"` - // AdminPassword - The administrator password to use for Windows VMs. - AdminPassword *string `json:"adminPassword,omitempty"` -} - -// CreationData data used when creating a disk. -type CreationData struct { - // CreateOption - This enumerates the possible sources of a disk's creation. Possible values include: 'Empty', 'Attach', 'FromImage', 'Import', 'Copy', 'Restore' - CreateOption DiskCreateOption `json:"createOption,omitempty"` - // StorageAccountID - If createOption is Import, the Azure Resource Manager identifier of the storage account containing the blob to import as a disk. Required only if the blob is in a different subscription - StorageAccountID *string `json:"storageAccountId,omitempty"` - // ImageReference - Disk source information. - ImageReference *ImageDiskReference `json:"imageReference,omitempty"` - // SourceURI - If createOption is Import, this is the URI of a blob to be imported into a managed disk. - SourceURI *string `json:"sourceUri,omitempty"` - // SourceResourceID - If createOption is Copy, this is the ARM id of the source snapshot or disk. - SourceResourceID *string `json:"sourceResourceId,omitempty"` -} - -// DataDisk describes a data disk. -type DataDisk struct { - // Lun - Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. - Lun *int32 `json:"lun,omitempty"` - // Name - The disk name. - Name *string `json:"name,omitempty"` - // Vhd - The virtual hard disk. - Vhd *VirtualHardDisk `json:"vhd,omitempty"` - // Image - The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist. - Image *VirtualHardDisk `json:"image,omitempty"` - // Caching - Specifies the caching requirements.

      Possible values are:

      **None**

      **ReadOnly**

      **ReadWrite**

      Default: **None for Standard storage. ReadOnly for Premium storage**. Possible values include: 'CachingTypesNone', 'CachingTypesReadOnly', 'CachingTypesReadWrite' - Caching CachingTypes `json:"caching,omitempty"` - // WriteAcceleratorEnabled - Specifies whether writeAccelerator should be enabled or disabled on the disk. - WriteAcceleratorEnabled *bool `json:"writeAcceleratorEnabled,omitempty"` - // CreateOption - Specifies how the virtual machine should be created.

      Possible values are:

      **Attach** \u2013 This value is used when you are using a specialized disk to create the virtual machine.

      **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. Possible values include: 'DiskCreateOptionTypesFromImage', 'DiskCreateOptionTypesEmpty', 'DiskCreateOptionTypesAttach' - CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` - // DiskSizeGB - Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image.

      This value cannot be larger than 1023 GB - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // ManagedDisk - The managed disk parameters. - ManagedDisk *ManagedDiskParameters `json:"managedDisk,omitempty"` -} - -// DataDiskImage contains the data disk images information. -type DataDiskImage struct { - // Lun - READ-ONLY; Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. - Lun *int32 `json:"lun,omitempty"` -} - -// MarshalJSON is the custom marshaler for DataDiskImage. -func (ddi DataDiskImage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// DiagnosticsProfile specifies the boot diagnostic settings state.

      Minimum api-version: -// 2015-06-15. -type DiagnosticsProfile struct { - // BootDiagnostics - Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status.

      You can easily view the output of your console log.

      Azure also enables you to see a screenshot of the VM from the hypervisor. - BootDiagnostics *BootDiagnostics `json:"bootDiagnostics,omitempty"` -} - -// DiffDiskSettings describes the parameters of ephemeral disk settings that can be specified for operating -// system disk.

      NOTE: The ephemeral disk settings can only be specified for managed disk. -type DiffDiskSettings struct { - // Option - Specifies the ephemeral disk settings for operating system disk. Possible values include: 'Local' - Option DiffDiskOptions `json:"option,omitempty"` -} - -// Disallowed describes the disallowed disk types. -type Disallowed struct { - // DiskTypes - A list of disk types. - DiskTypes *[]string `json:"diskTypes,omitempty"` -} - -// Disk disk resource. -type Disk struct { - autorest.Response `json:"-"` - // ManagedBy - READ-ONLY; A relative URI containing the ID of the VM that has the disk attached. - ManagedBy *string `json:"managedBy,omitempty"` - Sku *DiskSku `json:"sku,omitempty"` - // Zones - The Logical zone list for Disk. - Zones *[]string `json:"zones,omitempty"` - *DiskProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Disk. -func (d Disk) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if d.Sku != nil { - objectMap["sku"] = d.Sku - } - if d.Zones != nil { - objectMap["zones"] = d.Zones - } - if d.DiskProperties != nil { - objectMap["properties"] = d.DiskProperties - } - if d.Location != nil { - objectMap["location"] = d.Location - } - if d.Tags != nil { - objectMap["tags"] = d.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Disk struct. -func (d *Disk) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "managedBy": - if v != nil { - var managedBy string - err = json.Unmarshal(*v, &managedBy) - if err != nil { - return err - } - d.ManagedBy = &managedBy - } - case "sku": - if v != nil { - var sku DiskSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - d.Sku = &sku - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - d.Zones = &zones - } - case "properties": - if v != nil { - var diskProperties DiskProperties - err = json.Unmarshal(*v, &diskProperties) - if err != nil { - return err - } - d.DiskProperties = &diskProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - d.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - d.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - d.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - d.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - d.Tags = tags - } - } - } - - return nil -} - -// DiskEncryptionSettings describes a Encryption Settings for a Disk -type DiskEncryptionSettings struct { - // DiskEncryptionKey - Specifies the location of the disk encryption key, which is a Key Vault Secret. - DiskEncryptionKey *KeyVaultSecretReference `json:"diskEncryptionKey,omitempty"` - // KeyEncryptionKey - Specifies the location of the key encryption key in Key Vault. - KeyEncryptionKey *KeyVaultKeyReference `json:"keyEncryptionKey,omitempty"` - // Enabled - Specifies whether disk encryption should be enabled on the virtual machine. - Enabled *bool `json:"enabled,omitempty"` -} - -// DiskInstanceView the instance view of the disk. -type DiskInstanceView struct { - // Name - The disk name. - Name *string `json:"name,omitempty"` - // EncryptionSettings - Specifies the encryption settings for the OS Disk.

      Minimum api-version: 2015-06-15 - EncryptionSettings *[]DiskEncryptionSettings `json:"encryptionSettings,omitempty"` - // Statuses - The resource status information. - Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` -} - -// DiskList the List Disks operation response. -type DiskList struct { - autorest.Response `json:"-"` - // Value - A list of disks. - Value *[]Disk `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of disks. Call ListNext() with this to fetch the next page of disks. - NextLink *string `json:"nextLink,omitempty"` -} - -// DiskListIterator provides access to a complete listing of Disk values. -type DiskListIterator struct { - i int - page DiskListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *DiskListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DiskListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DiskListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DiskListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter DiskListIterator) Response() DiskList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter DiskListIterator) Value() Disk { - if !iter.page.NotDone() { - return Disk{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DiskListIterator type. -func NewDiskListIterator(page DiskListPage) DiskListIterator { - return DiskListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dl DiskList) IsEmpty() bool { - return dl.Value == nil || len(*dl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dl DiskList) hasNextLink() bool { - return dl.NextLink != nil && len(*dl.NextLink) != 0 -} - -// diskListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dl DiskList) diskListPreparer(ctx context.Context) (*http.Request, error) { - if !dl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dl.NextLink))) -} - -// DiskListPage contains a page of Disk values. -type DiskListPage struct { - fn func(context.Context, DiskList) (DiskList, error) - dl DiskList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DiskListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DiskListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dl) - if err != nil { - return err - } - page.dl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DiskListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DiskListPage) NotDone() bool { - return !page.dl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DiskListPage) Response() DiskList { - return page.dl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DiskListPage) Values() []Disk { - if page.dl.IsEmpty() { - return nil - } - return *page.dl.Value -} - -// Creates a new instance of the DiskListPage type. -func NewDiskListPage(cur DiskList, getNextPage func(context.Context, DiskList) (DiskList, error)) DiskListPage { - return DiskListPage{ - fn: getNextPage, - dl: cur, - } -} - -// DiskProperties disk resource properties. -type DiskProperties struct { - // TimeCreated - READ-ONLY; The time when the disk was created. - TimeCreated *date.Time `json:"timeCreated,omitempty"` - // OsType - The Operating System type. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // CreationData - Disk source information. CreationData information cannot be changed after the disk has been created. - CreationData *CreationData `json:"creationData,omitempty"` - // DiskSizeGB - If creationData.createOption is Empty, this field is mandatory and it indicates the size of the VHD to create. If this field is present for updates or creation with other options, it indicates a resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // EncryptionSettings - Encryption settings for disk or snapshot - EncryptionSettings *EncryptionSettings `json:"encryptionSettings,omitempty"` - // ProvisioningState - READ-ONLY; The disk provisioning state. - ProvisioningState *string `json:"provisioningState,omitempty"` - // DiskIOPSReadWrite - The number of IOPS allowed for this disk; only settable for UltraSSD disks. One operation can transfer between 4k and 256k bytes. For a description of the range of values you can set, see [Ultra SSD Managed Disk Offerings](https://docs.microsoft.com/azure/virtual-machines/windows/disks-ultra-ssd#ultra-ssd-managed-disk-offerings). - DiskIOPSReadWrite *int64 `json:"diskIOPSReadWrite,omitempty"` - // DiskMBpsReadWrite - The bandwidth allowed for this disk; only settable for UltraSSD disks. MBps means millions of bytes per second - MB here uses the ISO notation, of powers of 10. For a description of the range of values you can set, see [Ultra SSD Managed Disk Offerings](https://docs.microsoft.com/azure/virtual-machines/windows/disks-ultra-ssd#ultra-ssd-managed-disk-offerings). - DiskMBpsReadWrite *int32 `json:"diskMBpsReadWrite,omitempty"` -} - -// MarshalJSON is the custom marshaler for DiskProperties. -func (dp DiskProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dp.OsType != "" { - objectMap["osType"] = dp.OsType - } - if dp.CreationData != nil { - objectMap["creationData"] = dp.CreationData - } - if dp.DiskSizeGB != nil { - objectMap["diskSizeGB"] = dp.DiskSizeGB - } - if dp.EncryptionSettings != nil { - objectMap["encryptionSettings"] = dp.EncryptionSettings - } - if dp.DiskIOPSReadWrite != nil { - objectMap["diskIOPSReadWrite"] = dp.DiskIOPSReadWrite - } - if dp.DiskMBpsReadWrite != nil { - objectMap["diskMBpsReadWrite"] = dp.DiskMBpsReadWrite - } - return json.Marshal(objectMap) -} - -// DisksCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DisksCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DisksClient) (Disk, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DisksCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DisksCreateOrUpdateFuture.Result. -func (future *DisksCreateOrUpdateFuture) result(client DisksClient) (d Disk, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - d.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.DisksCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { - d, err = client.CreateOrUpdateResponder(d.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksCreateOrUpdateFuture", "Result", d.Response.Response, "Failure responding to request") - } - } - return -} - -// DisksDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type DisksDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DisksClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DisksDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DisksDeleteFuture.Result. -func (future *DisksDeleteFuture) result(client DisksClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.DisksDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DisksGrantAccessFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DisksGrantAccessFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DisksClient) (AccessURI, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DisksGrantAccessFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DisksGrantAccessFuture.Result. -func (future *DisksGrantAccessFuture) result(client DisksClient) (au AccessURI, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksGrantAccessFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - au.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.DisksGrantAccessFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if au.Response.Response, err = future.GetResult(sender); err == nil && au.Response.Response.StatusCode != http.StatusNoContent { - au, err = client.GrantAccessResponder(au.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksGrantAccessFuture", "Result", au.Response.Response, "Failure responding to request") - } - } - return -} - -// DiskSku the disks sku name. Can be Standard_LRS, Premium_LRS, StandardSSD_LRS, or UltraSSD_LRS. -type DiskSku struct { - // Name - The sku name. Possible values include: 'StandardLRS', 'PremiumLRS', 'StandardSSDLRS', 'UltraSSDLRS' - Name DiskStorageAccountTypes `json:"name,omitempty"` - // Tier - READ-ONLY; The sku tier. - Tier *string `json:"tier,omitempty"` -} - -// MarshalJSON is the custom marshaler for DiskSku. -func (ds DiskSku) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ds.Name != "" { - objectMap["name"] = ds.Name - } - return json.Marshal(objectMap) -} - -// DisksRevokeAccessFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DisksRevokeAccessFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DisksClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DisksRevokeAccessFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DisksRevokeAccessFuture.Result. -func (future *DisksRevokeAccessFuture) result(client DisksClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksRevokeAccessFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.DisksRevokeAccessFuture") - return - } - ar.Response = future.Response() - return -} - -// DisksUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type DisksUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DisksClient) (Disk, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DisksUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DisksUpdateFuture.Result. -func (future *DisksUpdateFuture) result(client DisksClient) (d Disk, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - d.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.DisksUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { - d, err = client.UpdateResponder(d.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.DisksUpdateFuture", "Result", d.Response.Response, "Failure responding to request") - } - } - return -} - -// DiskUpdate disk update resource. -type DiskUpdate struct { - *DiskUpdateProperties `json:"properties,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - Sku *DiskSku `json:"sku,omitempty"` -} - -// MarshalJSON is the custom marshaler for DiskUpdate. -func (du DiskUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if du.DiskUpdateProperties != nil { - objectMap["properties"] = du.DiskUpdateProperties - } - if du.Tags != nil { - objectMap["tags"] = du.Tags - } - if du.Sku != nil { - objectMap["sku"] = du.Sku - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for DiskUpdate struct. -func (du *DiskUpdate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var diskUpdateProperties DiskUpdateProperties - err = json.Unmarshal(*v, &diskUpdateProperties) - if err != nil { - return err - } - du.DiskUpdateProperties = &diskUpdateProperties - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - du.Tags = tags - } - case "sku": - if v != nil { - var sku DiskSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - du.Sku = &sku - } - } - } - - return nil -} - -// DiskUpdateProperties disk resource update properties. -type DiskUpdateProperties struct { - // OsType - the Operating System type. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // DiskSizeGB - If creationData.createOption is Empty, this field is mandatory and it indicates the size of the VHD to create. If this field is present for updates or creation with other options, it indicates a resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // EncryptionSettings - Encryption settings for disk or snapshot - EncryptionSettings *EncryptionSettings `json:"encryptionSettings,omitempty"` - // DiskIOPSReadWrite - The number of IOPS allowed for this disk; only settable for UltraSSD disks. One operation can transfer between 4k and 256k bytes. - DiskIOPSReadWrite *int64 `json:"diskIOPSReadWrite,omitempty"` - // DiskMBpsReadWrite - The bandwidth allowed for this disk; only settable for UltraSSD disks. MBps means millions of bytes per second - MB here uses the ISO notation, of powers of 10. - DiskMBpsReadWrite *int32 `json:"diskMBpsReadWrite,omitempty"` -} - -// EncryptionSettings encryption settings for disk or snapshot -type EncryptionSettings struct { - // Enabled - Set this flag to true and provide DiskEncryptionKey and optional KeyEncryptionKey to enable encryption. Set this flag to false and remove DiskEncryptionKey and KeyEncryptionKey to disable encryption. If EncryptionSettings is null in the request object, the existing settings remain unchanged. - Enabled *bool `json:"enabled,omitempty"` - // DiskEncryptionKey - Key Vault Secret Url and vault id of the disk encryption key - DiskEncryptionKey *KeyVaultAndSecretReference `json:"diskEncryptionKey,omitempty"` - // KeyEncryptionKey - Key Vault Key Url and vault id of the key encryption key - KeyEncryptionKey *KeyVaultAndKeyReference `json:"keyEncryptionKey,omitempty"` -} - -// GalleriesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type GalleriesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GalleriesClient) (Gallery, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GalleriesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GalleriesCreateOrUpdateFuture.Result. -func (future *GalleriesCreateOrUpdateFuture) result(client GalleriesClient) (g Gallery, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - g.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.GalleriesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if g.Response.Response, err = future.GetResult(sender); err == nil && g.Response.Response.StatusCode != http.StatusNoContent { - g, err = client.CreateOrUpdateResponder(g.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesCreateOrUpdateFuture", "Result", g.Response.Response, "Failure responding to request") - } - } - return -} - -// GalleriesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type GalleriesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GalleriesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GalleriesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GalleriesDeleteFuture.Result. -func (future *GalleriesDeleteFuture) result(client GalleriesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleriesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.GalleriesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// Gallery specifies information about the Shared Image Gallery that you want to create or update. -type Gallery struct { - autorest.Response `json:"-"` - *GalleryProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Gallery. -func (g Gallery) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if g.GalleryProperties != nil { - objectMap["properties"] = g.GalleryProperties - } - if g.Location != nil { - objectMap["location"] = g.Location - } - if g.Tags != nil { - objectMap["tags"] = g.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Gallery struct. -func (g *Gallery) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var galleryProperties GalleryProperties - err = json.Unmarshal(*v, &galleryProperties) - if err != nil { - return err - } - g.GalleryProperties = &galleryProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - g.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - g.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - g.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - g.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - g.Tags = tags - } - } - } - - return nil -} - -// GalleryArtifactPublishingProfileBase describes the basic gallery artifact publishing profile. -type GalleryArtifactPublishingProfileBase struct { - // TargetRegions - The target regions where the Image Version is going to be replicated to. This property is updatable. - TargetRegions *[]TargetRegion `json:"targetRegions,omitempty"` - Source *GalleryArtifactSource `json:"source,omitempty"` -} - -// GalleryArtifactSource the source image from which the Image Version is going to be created. -type GalleryArtifactSource struct { - ManagedImage *ManagedArtifact `json:"managedImage,omitempty"` -} - -// GalleryDataDiskImage this is the data disk image. -type GalleryDataDiskImage struct { - // Lun - READ-ONLY; This property specifies the logical unit number of the data disk. This value is used to identify data disks within the Virtual Machine and therefore must be unique for each data disk attached to the Virtual Machine. - Lun *int32 `json:"lun,omitempty"` - // SizeInGB - READ-ONLY; This property indicates the size of the VHD to be created. - SizeInGB *int32 `json:"sizeInGB,omitempty"` - // HostCaching - READ-ONLY; The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite'. Possible values include: 'HostCachingNone', 'HostCachingReadOnly', 'HostCachingReadWrite' - HostCaching HostCaching `json:"hostCaching,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryDataDiskImage. -func (gddi GalleryDataDiskImage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GalleryDiskImage this is the disk image base class. -type GalleryDiskImage struct { - // SizeInGB - READ-ONLY; This property indicates the size of the VHD to be created. - SizeInGB *int32 `json:"sizeInGB,omitempty"` - // HostCaching - READ-ONLY; The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite'. Possible values include: 'HostCachingNone', 'HostCachingReadOnly', 'HostCachingReadWrite' - HostCaching HostCaching `json:"hostCaching,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryDiskImage. -func (gdi GalleryDiskImage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GalleryIdentifier describes the gallery unique name. -type GalleryIdentifier struct { - // UniqueName - READ-ONLY; The unique name of the Shared Image Gallery. This name is generated automatically by Azure. - UniqueName *string `json:"uniqueName,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryIdentifier. -func (gi GalleryIdentifier) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GalleryImage specifies information about the gallery Image Definition that you want to create or update. -type GalleryImage struct { - autorest.Response `json:"-"` - *GalleryImageProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for GalleryImage. -func (gi GalleryImage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gi.GalleryImageProperties != nil { - objectMap["properties"] = gi.GalleryImageProperties - } - if gi.Location != nil { - objectMap["location"] = gi.Location - } - if gi.Tags != nil { - objectMap["tags"] = gi.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for GalleryImage struct. -func (gi *GalleryImage) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var galleryImageProperties GalleryImageProperties - err = json.Unmarshal(*v, &galleryImageProperties) - if err != nil { - return err - } - gi.GalleryImageProperties = &galleryImageProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - gi.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - gi.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - gi.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - gi.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - gi.Tags = tags - } - } - } - - return nil -} - -// GalleryImageIdentifier this is the gallery Image Definition identifier. -type GalleryImageIdentifier struct { - // Publisher - The name of the gallery Image Definition publisher. - Publisher *string `json:"publisher,omitempty"` - // Offer - The name of the gallery Image Definition offer. - Offer *string `json:"offer,omitempty"` - // Sku - The name of the gallery Image Definition SKU. - Sku *string `json:"sku,omitempty"` -} - -// GalleryImageList the List Gallery Images operation response. -type GalleryImageList struct { - autorest.Response `json:"-"` - // Value - A list of Shared Image Gallery images. - Value *[]GalleryImage `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of Image Definitions in the Shared Image Gallery. Call ListNext() with this to fetch the next page of gallery Image Definitions. - NextLink *string `json:"nextLink,omitempty"` -} - -// GalleryImageListIterator provides access to a complete listing of GalleryImage values. -type GalleryImageListIterator struct { - i int - page GalleryImageListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *GalleryImageListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *GalleryImageListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter GalleryImageListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter GalleryImageListIterator) Response() GalleryImageList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter GalleryImageListIterator) Value() GalleryImage { - if !iter.page.NotDone() { - return GalleryImage{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the GalleryImageListIterator type. -func NewGalleryImageListIterator(page GalleryImageListPage) GalleryImageListIterator { - return GalleryImageListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (gil GalleryImageList) IsEmpty() bool { - return gil.Value == nil || len(*gil.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (gil GalleryImageList) hasNextLink() bool { - return gil.NextLink != nil && len(*gil.NextLink) != 0 -} - -// galleryImageListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (gil GalleryImageList) galleryImageListPreparer(ctx context.Context) (*http.Request, error) { - if !gil.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(gil.NextLink))) -} - -// GalleryImageListPage contains a page of GalleryImage values. -type GalleryImageListPage struct { - fn func(context.Context, GalleryImageList) (GalleryImageList, error) - gil GalleryImageList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *GalleryImageListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.gil) - if err != nil { - return err - } - page.gil = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *GalleryImageListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page GalleryImageListPage) NotDone() bool { - return !page.gil.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page GalleryImageListPage) Response() GalleryImageList { - return page.gil -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page GalleryImageListPage) Values() []GalleryImage { - if page.gil.IsEmpty() { - return nil - } - return *page.gil.Value -} - -// Creates a new instance of the GalleryImageListPage type. -func NewGalleryImageListPage(cur GalleryImageList, getNextPage func(context.Context, GalleryImageList) (GalleryImageList, error)) GalleryImageListPage { - return GalleryImageListPage{ - fn: getNextPage, - gil: cur, - } -} - -// GalleryImageProperties describes the properties of a gallery Image Definition. -type GalleryImageProperties struct { - // Description - The description of this gallery Image Definition resource. This property is updatable. - Description *string `json:"description,omitempty"` - // Eula - The Eula agreement for the gallery Image Definition. - Eula *string `json:"eula,omitempty"` - // PrivacyStatementURI - The privacy statement uri. - PrivacyStatementURI *string `json:"privacyStatementUri,omitempty"` - // ReleaseNoteURI - The release note uri. - ReleaseNoteURI *string `json:"releaseNoteUri,omitempty"` - // OsType - This property allows you to specify the type of the OS that is included in the disk when creating a VM from a managed image.

      Possible values are:

      **Windows**

      **Linux**. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // OsState - The allowed values for OS State are 'Generalized'. Possible values include: 'Generalized', 'Specialized' - OsState OperatingSystemStateTypes `json:"osState,omitempty"` - // EndOfLifeDate - The end of life date of the gallery Image Definition. This property can be used for decommissioning purposes. This property is updatable. - EndOfLifeDate *date.Time `json:"endOfLifeDate,omitempty"` - Identifier *GalleryImageIdentifier `json:"identifier,omitempty"` - Recommended *RecommendedMachineConfiguration `json:"recommended,omitempty"` - Disallowed *Disallowed `json:"disallowed,omitempty"` - PurchasePlan *ImagePurchasePlan `json:"purchasePlan,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. Possible values include: 'ProvisioningState1Creating', 'ProvisioningState1Updating', 'ProvisioningState1Failed', 'ProvisioningState1Succeeded', 'ProvisioningState1Deleting', 'ProvisioningState1Migrating' - ProvisioningState ProvisioningState1 `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryImageProperties. -func (gip GalleryImageProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gip.Description != nil { - objectMap["description"] = gip.Description - } - if gip.Eula != nil { - objectMap["eula"] = gip.Eula - } - if gip.PrivacyStatementURI != nil { - objectMap["privacyStatementUri"] = gip.PrivacyStatementURI - } - if gip.ReleaseNoteURI != nil { - objectMap["releaseNoteUri"] = gip.ReleaseNoteURI - } - if gip.OsType != "" { - objectMap["osType"] = gip.OsType - } - if gip.OsState != "" { - objectMap["osState"] = gip.OsState - } - if gip.EndOfLifeDate != nil { - objectMap["endOfLifeDate"] = gip.EndOfLifeDate - } - if gip.Identifier != nil { - objectMap["identifier"] = gip.Identifier - } - if gip.Recommended != nil { - objectMap["recommended"] = gip.Recommended - } - if gip.Disallowed != nil { - objectMap["disallowed"] = gip.Disallowed - } - if gip.PurchasePlan != nil { - objectMap["purchasePlan"] = gip.PurchasePlan - } - return json.Marshal(objectMap) -} - -// GalleryImagesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type GalleryImagesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GalleryImagesClient) (GalleryImage, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GalleryImagesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GalleryImagesCreateOrUpdateFuture.Result. -func (future *GalleryImagesCreateOrUpdateFuture) result(client GalleryImagesClient) (gi GalleryImage, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - gi.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.GalleryImagesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if gi.Response.Response, err = future.GetResult(sender); err == nil && gi.Response.Response.StatusCode != http.StatusNoContent { - gi, err = client.CreateOrUpdateResponder(gi.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesCreateOrUpdateFuture", "Result", gi.Response.Response, "Failure responding to request") - } - } - return -} - -// GalleryImagesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type GalleryImagesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GalleryImagesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GalleryImagesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GalleryImagesDeleteFuture.Result. -func (future *GalleryImagesDeleteFuture) result(client GalleryImagesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImagesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.GalleryImagesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// GalleryImageVersion specifies information about the gallery Image Version that you want to create or -// update. -type GalleryImageVersion struct { - autorest.Response `json:"-"` - *GalleryImageVersionProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for GalleryImageVersion. -func (giv GalleryImageVersion) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if giv.GalleryImageVersionProperties != nil { - objectMap["properties"] = giv.GalleryImageVersionProperties - } - if giv.Location != nil { - objectMap["location"] = giv.Location - } - if giv.Tags != nil { - objectMap["tags"] = giv.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for GalleryImageVersion struct. -func (giv *GalleryImageVersion) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var galleryImageVersionProperties GalleryImageVersionProperties - err = json.Unmarshal(*v, &galleryImageVersionProperties) - if err != nil { - return err - } - giv.GalleryImageVersionProperties = &galleryImageVersionProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - giv.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - giv.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - giv.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - giv.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - giv.Tags = tags - } - } - } - - return nil -} - -// GalleryImageVersionList the List Gallery Image version operation response. -type GalleryImageVersionList struct { - autorest.Response `json:"-"` - // Value - A list of gallery Image Versions. - Value *[]GalleryImageVersion `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of gallery Image Versions. Call ListNext() with this to fetch the next page of gallery Image Versions. - NextLink *string `json:"nextLink,omitempty"` -} - -// GalleryImageVersionListIterator provides access to a complete listing of GalleryImageVersion values. -type GalleryImageVersionListIterator struct { - i int - page GalleryImageVersionListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *GalleryImageVersionListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageVersionListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *GalleryImageVersionListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter GalleryImageVersionListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter GalleryImageVersionListIterator) Response() GalleryImageVersionList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter GalleryImageVersionListIterator) Value() GalleryImageVersion { - if !iter.page.NotDone() { - return GalleryImageVersion{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the GalleryImageVersionListIterator type. -func NewGalleryImageVersionListIterator(page GalleryImageVersionListPage) GalleryImageVersionListIterator { - return GalleryImageVersionListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (givl GalleryImageVersionList) IsEmpty() bool { - return givl.Value == nil || len(*givl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (givl GalleryImageVersionList) hasNextLink() bool { - return givl.NextLink != nil && len(*givl.NextLink) != 0 -} - -// galleryImageVersionListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (givl GalleryImageVersionList) galleryImageVersionListPreparer(ctx context.Context) (*http.Request, error) { - if !givl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(givl.NextLink))) -} - -// GalleryImageVersionListPage contains a page of GalleryImageVersion values. -type GalleryImageVersionListPage struct { - fn func(context.Context, GalleryImageVersionList) (GalleryImageVersionList, error) - givl GalleryImageVersionList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *GalleryImageVersionListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageVersionListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.givl) - if err != nil { - return err - } - page.givl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *GalleryImageVersionListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page GalleryImageVersionListPage) NotDone() bool { - return !page.givl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page GalleryImageVersionListPage) Response() GalleryImageVersionList { - return page.givl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page GalleryImageVersionListPage) Values() []GalleryImageVersion { - if page.givl.IsEmpty() { - return nil - } - return *page.givl.Value -} - -// Creates a new instance of the GalleryImageVersionListPage type. -func NewGalleryImageVersionListPage(cur GalleryImageVersionList, getNextPage func(context.Context, GalleryImageVersionList) (GalleryImageVersionList, error)) GalleryImageVersionListPage { - return GalleryImageVersionListPage{ - fn: getNextPage, - givl: cur, - } -} - -// GalleryImageVersionProperties describes the properties of a gallery Image Version. -type GalleryImageVersionProperties struct { - PublishingProfile *GalleryImageVersionPublishingProfile `json:"publishingProfile,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. Possible values include: 'ProvisioningState2Creating', 'ProvisioningState2Updating', 'ProvisioningState2Failed', 'ProvisioningState2Succeeded', 'ProvisioningState2Deleting', 'ProvisioningState2Migrating' - ProvisioningState ProvisioningState2 `json:"provisioningState,omitempty"` - // StorageProfile - READ-ONLY - StorageProfile *GalleryImageVersionStorageProfile `json:"storageProfile,omitempty"` - // ReplicationStatus - READ-ONLY - ReplicationStatus *ReplicationStatus `json:"replicationStatus,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryImageVersionProperties. -func (givp GalleryImageVersionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if givp.PublishingProfile != nil { - objectMap["publishingProfile"] = givp.PublishingProfile - } - return json.Marshal(objectMap) -} - -// GalleryImageVersionPublishingProfile the publishing profile of a gallery Image Version. -type GalleryImageVersionPublishingProfile struct { - // ReplicaCount - The number of replicas of the Image Version to be created per region. This property would take effect for a region when regionalReplicaCount is not specified. This property is updatable. - ReplicaCount *int32 `json:"replicaCount,omitempty"` - // ExcludeFromLatest - If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. - ExcludeFromLatest *bool `json:"excludeFromLatest,omitempty"` - // PublishedDate - READ-ONLY; The timestamp for when the gallery Image Version is published. - PublishedDate *date.Time `json:"publishedDate,omitempty"` - // EndOfLifeDate - The end of life date of the gallery Image Version. This property can be used for decommissioning purposes. This property is updatable. - EndOfLifeDate *date.Time `json:"endOfLifeDate,omitempty"` - // TargetRegions - The target regions where the Image Version is going to be replicated to. This property is updatable. - TargetRegions *[]TargetRegion `json:"targetRegions,omitempty"` - Source *GalleryArtifactSource `json:"source,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryImageVersionPublishingProfile. -func (givpp GalleryImageVersionPublishingProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if givpp.ReplicaCount != nil { - objectMap["replicaCount"] = givpp.ReplicaCount - } - if givpp.ExcludeFromLatest != nil { - objectMap["excludeFromLatest"] = givpp.ExcludeFromLatest - } - if givpp.EndOfLifeDate != nil { - objectMap["endOfLifeDate"] = givpp.EndOfLifeDate - } - if givpp.TargetRegions != nil { - objectMap["targetRegions"] = givpp.TargetRegions - } - if givpp.Source != nil { - objectMap["source"] = givpp.Source - } - return json.Marshal(objectMap) -} - -// GalleryImageVersionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type GalleryImageVersionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GalleryImageVersionsClient) (GalleryImageVersion, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GalleryImageVersionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GalleryImageVersionsCreateOrUpdateFuture.Result. -func (future *GalleryImageVersionsCreateOrUpdateFuture) result(client GalleryImageVersionsClient) (giv GalleryImageVersion, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - giv.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.GalleryImageVersionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if giv.Response.Response, err = future.GetResult(sender); err == nil && giv.Response.Response.StatusCode != http.StatusNoContent { - giv, err = client.CreateOrUpdateResponder(giv.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsCreateOrUpdateFuture", "Result", giv.Response.Response, "Failure responding to request") - } - } - return -} - -// GalleryImageVersionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type GalleryImageVersionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GalleryImageVersionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GalleryImageVersionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GalleryImageVersionsDeleteFuture.Result. -func (future *GalleryImageVersionsDeleteFuture) result(client GalleryImageVersionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.GalleryImageVersionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.GalleryImageVersionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// GalleryImageVersionStorageProfile this is the storage profile of a gallery Image Version. -type GalleryImageVersionStorageProfile struct { - // OsDiskImage - READ-ONLY - OsDiskImage *GalleryOSDiskImage `json:"osDiskImage,omitempty"` - // DataDiskImages - READ-ONLY; A list of data disk images. - DataDiskImages *[]GalleryDataDiskImage `json:"dataDiskImages,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryImageVersionStorageProfile. -func (givsp GalleryImageVersionStorageProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GalleryList the List Galleries operation response. -type GalleryList struct { - autorest.Response `json:"-"` - // Value - A list of galleries. - Value *[]Gallery `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of galleries. Call ListNext() with this to fetch the next page of galleries. - NextLink *string `json:"nextLink,omitempty"` -} - -// GalleryListIterator provides access to a complete listing of Gallery values. -type GalleryListIterator struct { - i int - page GalleryListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *GalleryListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *GalleryListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter GalleryListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter GalleryListIterator) Response() GalleryList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter GalleryListIterator) Value() Gallery { - if !iter.page.NotDone() { - return Gallery{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the GalleryListIterator type. -func NewGalleryListIterator(page GalleryListPage) GalleryListIterator { - return GalleryListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (gl GalleryList) IsEmpty() bool { - return gl.Value == nil || len(*gl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (gl GalleryList) hasNextLink() bool { - return gl.NextLink != nil && len(*gl.NextLink) != 0 -} - -// galleryListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (gl GalleryList) galleryListPreparer(ctx context.Context) (*http.Request, error) { - if !gl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(gl.NextLink))) -} - -// GalleryListPage contains a page of Gallery values. -type GalleryListPage struct { - fn func(context.Context, GalleryList) (GalleryList, error) - gl GalleryList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *GalleryListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GalleryListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.gl) - if err != nil { - return err - } - page.gl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *GalleryListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page GalleryListPage) NotDone() bool { - return !page.gl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page GalleryListPage) Response() GalleryList { - return page.gl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page GalleryListPage) Values() []Gallery { - if page.gl.IsEmpty() { - return nil - } - return *page.gl.Value -} - -// Creates a new instance of the GalleryListPage type. -func NewGalleryListPage(cur GalleryList, getNextPage func(context.Context, GalleryList) (GalleryList, error)) GalleryListPage { - return GalleryListPage{ - fn: getNextPage, - gl: cur, - } -} - -// GalleryOSDiskImage this is the OS disk image. -type GalleryOSDiskImage struct { - // SizeInGB - READ-ONLY; This property indicates the size of the VHD to be created. - SizeInGB *int32 `json:"sizeInGB,omitempty"` - // HostCaching - READ-ONLY; The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite'. Possible values include: 'HostCachingNone', 'HostCachingReadOnly', 'HostCachingReadWrite' - HostCaching HostCaching `json:"hostCaching,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryOSDiskImage. -func (godi GalleryOSDiskImage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GalleryProperties describes the properties of a Shared Image Gallery. -type GalleryProperties struct { - // Description - The description of this Shared Image Gallery resource. This property is updatable. - Description *string `json:"description,omitempty"` - Identifier *GalleryIdentifier `json:"identifier,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. Possible values include: 'ProvisioningStateCreating', 'ProvisioningStateUpdating', 'ProvisioningStateFailed', 'ProvisioningStateSucceeded', 'ProvisioningStateDeleting', 'ProvisioningStateMigrating' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for GalleryProperties. -func (gp GalleryProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gp.Description != nil { - objectMap["description"] = gp.Description - } - if gp.Identifier != nil { - objectMap["identifier"] = gp.Identifier - } - return json.Marshal(objectMap) -} - -// GrantAccessData data used for requesting a SAS. -type GrantAccessData struct { - // Access - Possible values include: 'None', 'Read' - Access AccessLevel `json:"access,omitempty"` - // DurationInSeconds - Time duration in seconds until the SAS access expires. - DurationInSeconds *int32 `json:"durationInSeconds,omitempty"` -} - -// HardwareProfile specifies the hardware settings for the virtual machine. -type HardwareProfile struct { - // VMSize - Specifies the size of the virtual machine. For more information about virtual machine sizes, see [Sizes for virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-sizes?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).

      The available VM sizes depend on region and availability set. For a list of available sizes use these APIs:

      [List all available virtual machine sizes in an availability set](https://docs.microsoft.com/rest/api/compute/availabilitysets/listavailablesizes)

      [List all available virtual machine sizes in a region](https://docs.microsoft.com/rest/api/compute/virtualmachinesizes/list)

      [List all available virtual machine sizes for resizing](https://docs.microsoft.com/rest/api/compute/virtualmachines/listavailablesizes). Possible values include: 'VirtualMachineSizeTypesBasicA0', 'VirtualMachineSizeTypesBasicA1', 'VirtualMachineSizeTypesBasicA2', 'VirtualMachineSizeTypesBasicA3', 'VirtualMachineSizeTypesBasicA4', 'VirtualMachineSizeTypesStandardA0', 'VirtualMachineSizeTypesStandardA1', 'VirtualMachineSizeTypesStandardA2', 'VirtualMachineSizeTypesStandardA3', 'VirtualMachineSizeTypesStandardA4', 'VirtualMachineSizeTypesStandardA5', 'VirtualMachineSizeTypesStandardA6', 'VirtualMachineSizeTypesStandardA7', 'VirtualMachineSizeTypesStandardA8', 'VirtualMachineSizeTypesStandardA9', 'VirtualMachineSizeTypesStandardA10', 'VirtualMachineSizeTypesStandardA11', 'VirtualMachineSizeTypesStandardA1V2', 'VirtualMachineSizeTypesStandardA2V2', 'VirtualMachineSizeTypesStandardA4V2', 'VirtualMachineSizeTypesStandardA8V2', 'VirtualMachineSizeTypesStandardA2mV2', 'VirtualMachineSizeTypesStandardA4mV2', 'VirtualMachineSizeTypesStandardA8mV2', 'VirtualMachineSizeTypesStandardB1s', 'VirtualMachineSizeTypesStandardB1ms', 'VirtualMachineSizeTypesStandardB2s', 'VirtualMachineSizeTypesStandardB2ms', 'VirtualMachineSizeTypesStandardB4ms', 'VirtualMachineSizeTypesStandardB8ms', 'VirtualMachineSizeTypesStandardD1', 'VirtualMachineSizeTypesStandardD2', 'VirtualMachineSizeTypesStandardD3', 'VirtualMachineSizeTypesStandardD4', 'VirtualMachineSizeTypesStandardD11', 'VirtualMachineSizeTypesStandardD12', 'VirtualMachineSizeTypesStandardD13', 'VirtualMachineSizeTypesStandardD14', 'VirtualMachineSizeTypesStandardD1V2', 'VirtualMachineSizeTypesStandardD2V2', 'VirtualMachineSizeTypesStandardD3V2', 'VirtualMachineSizeTypesStandardD4V2', 'VirtualMachineSizeTypesStandardD5V2', 'VirtualMachineSizeTypesStandardD2V3', 'VirtualMachineSizeTypesStandardD4V3', 'VirtualMachineSizeTypesStandardD8V3', 'VirtualMachineSizeTypesStandardD16V3', 'VirtualMachineSizeTypesStandardD32V3', 'VirtualMachineSizeTypesStandardD64V3', 'VirtualMachineSizeTypesStandardD2sV3', 'VirtualMachineSizeTypesStandardD4sV3', 'VirtualMachineSizeTypesStandardD8sV3', 'VirtualMachineSizeTypesStandardD16sV3', 'VirtualMachineSizeTypesStandardD32sV3', 'VirtualMachineSizeTypesStandardD64sV3', 'VirtualMachineSizeTypesStandardD11V2', 'VirtualMachineSizeTypesStandardD12V2', 'VirtualMachineSizeTypesStandardD13V2', 'VirtualMachineSizeTypesStandardD14V2', 'VirtualMachineSizeTypesStandardD15V2', 'VirtualMachineSizeTypesStandardDS1', 'VirtualMachineSizeTypesStandardDS2', 'VirtualMachineSizeTypesStandardDS3', 'VirtualMachineSizeTypesStandardDS4', 'VirtualMachineSizeTypesStandardDS11', 'VirtualMachineSizeTypesStandardDS12', 'VirtualMachineSizeTypesStandardDS13', 'VirtualMachineSizeTypesStandardDS14', 'VirtualMachineSizeTypesStandardDS1V2', 'VirtualMachineSizeTypesStandardDS2V2', 'VirtualMachineSizeTypesStandardDS3V2', 'VirtualMachineSizeTypesStandardDS4V2', 'VirtualMachineSizeTypesStandardDS5V2', 'VirtualMachineSizeTypesStandardDS11V2', 'VirtualMachineSizeTypesStandardDS12V2', 'VirtualMachineSizeTypesStandardDS13V2', 'VirtualMachineSizeTypesStandardDS14V2', 'VirtualMachineSizeTypesStandardDS15V2', 'VirtualMachineSizeTypesStandardDS134V2', 'VirtualMachineSizeTypesStandardDS132V2', 'VirtualMachineSizeTypesStandardDS148V2', 'VirtualMachineSizeTypesStandardDS144V2', 'VirtualMachineSizeTypesStandardE2V3', 'VirtualMachineSizeTypesStandardE4V3', 'VirtualMachineSizeTypesStandardE8V3', 'VirtualMachineSizeTypesStandardE16V3', 'VirtualMachineSizeTypesStandardE32V3', 'VirtualMachineSizeTypesStandardE64V3', 'VirtualMachineSizeTypesStandardE2sV3', 'VirtualMachineSizeTypesStandardE4sV3', 'VirtualMachineSizeTypesStandardE8sV3', 'VirtualMachineSizeTypesStandardE16sV3', 'VirtualMachineSizeTypesStandardE32sV3', 'VirtualMachineSizeTypesStandardE64sV3', 'VirtualMachineSizeTypesStandardE3216V3', 'VirtualMachineSizeTypesStandardE328sV3', 'VirtualMachineSizeTypesStandardE6432sV3', 'VirtualMachineSizeTypesStandardE6416sV3', 'VirtualMachineSizeTypesStandardF1', 'VirtualMachineSizeTypesStandardF2', 'VirtualMachineSizeTypesStandardF4', 'VirtualMachineSizeTypesStandardF8', 'VirtualMachineSizeTypesStandardF16', 'VirtualMachineSizeTypesStandardF1s', 'VirtualMachineSizeTypesStandardF2s', 'VirtualMachineSizeTypesStandardF4s', 'VirtualMachineSizeTypesStandardF8s', 'VirtualMachineSizeTypesStandardF16s', 'VirtualMachineSizeTypesStandardF2sV2', 'VirtualMachineSizeTypesStandardF4sV2', 'VirtualMachineSizeTypesStandardF8sV2', 'VirtualMachineSizeTypesStandardF16sV2', 'VirtualMachineSizeTypesStandardF32sV2', 'VirtualMachineSizeTypesStandardF64sV2', 'VirtualMachineSizeTypesStandardF72sV2', 'VirtualMachineSizeTypesStandardG1', 'VirtualMachineSizeTypesStandardG2', 'VirtualMachineSizeTypesStandardG3', 'VirtualMachineSizeTypesStandardG4', 'VirtualMachineSizeTypesStandardG5', 'VirtualMachineSizeTypesStandardGS1', 'VirtualMachineSizeTypesStandardGS2', 'VirtualMachineSizeTypesStandardGS3', 'VirtualMachineSizeTypesStandardGS4', 'VirtualMachineSizeTypesStandardGS5', 'VirtualMachineSizeTypesStandardGS48', 'VirtualMachineSizeTypesStandardGS44', 'VirtualMachineSizeTypesStandardGS516', 'VirtualMachineSizeTypesStandardGS58', 'VirtualMachineSizeTypesStandardH8', 'VirtualMachineSizeTypesStandardH16', 'VirtualMachineSizeTypesStandardH8m', 'VirtualMachineSizeTypesStandardH16m', 'VirtualMachineSizeTypesStandardH16r', 'VirtualMachineSizeTypesStandardH16mr', 'VirtualMachineSizeTypesStandardL4s', 'VirtualMachineSizeTypesStandardL8s', 'VirtualMachineSizeTypesStandardL16s', 'VirtualMachineSizeTypesStandardL32s', 'VirtualMachineSizeTypesStandardM64s', 'VirtualMachineSizeTypesStandardM64ms', 'VirtualMachineSizeTypesStandardM128s', 'VirtualMachineSizeTypesStandardM128ms', 'VirtualMachineSizeTypesStandardM6432ms', 'VirtualMachineSizeTypesStandardM6416ms', 'VirtualMachineSizeTypesStandardM12864ms', 'VirtualMachineSizeTypesStandardM12832ms', 'VirtualMachineSizeTypesStandardNC6', 'VirtualMachineSizeTypesStandardNC12', 'VirtualMachineSizeTypesStandardNC24', 'VirtualMachineSizeTypesStandardNC24r', 'VirtualMachineSizeTypesStandardNC6sV2', 'VirtualMachineSizeTypesStandardNC12sV2', 'VirtualMachineSizeTypesStandardNC24sV2', 'VirtualMachineSizeTypesStandardNC24rsV2', 'VirtualMachineSizeTypesStandardNC6sV3', 'VirtualMachineSizeTypesStandardNC12sV3', 'VirtualMachineSizeTypesStandardNC24sV3', 'VirtualMachineSizeTypesStandardNC24rsV3', 'VirtualMachineSizeTypesStandardND6s', 'VirtualMachineSizeTypesStandardND12s', 'VirtualMachineSizeTypesStandardND24s', 'VirtualMachineSizeTypesStandardND24rs', 'VirtualMachineSizeTypesStandardNV6', 'VirtualMachineSizeTypesStandardNV12', 'VirtualMachineSizeTypesStandardNV24' - VMSize VirtualMachineSizeTypes `json:"vmSize,omitempty"` -} - -// Image the source user image virtual hard disk. The virtual hard disk will be copied before being -// attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not -// exist. -type Image struct { - autorest.Response `json:"-"` - *ImageProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Image. -func (i Image) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if i.ImageProperties != nil { - objectMap["properties"] = i.ImageProperties - } - if i.Location != nil { - objectMap["location"] = i.Location - } - if i.Tags != nil { - objectMap["tags"] = i.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Image struct. -func (i *Image) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var imageProperties ImageProperties - err = json.Unmarshal(*v, &imageProperties) - if err != nil { - return err - } - i.ImageProperties = &imageProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - i.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - i.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - i.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - i.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - i.Tags = tags - } - } - } - - return nil -} - -// ImageDataDisk describes a data disk. -type ImageDataDisk struct { - // Lun - Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. - Lun *int32 `json:"lun,omitempty"` - // Snapshot - The snapshot. - Snapshot *SubResource `json:"snapshot,omitempty"` - // ManagedDisk - The managedDisk. - ManagedDisk *SubResource `json:"managedDisk,omitempty"` - // BlobURI - The Virtual Hard Disk. - BlobURI *string `json:"blobUri,omitempty"` - // Caching - Specifies the caching requirements.

      Possible values are:

      **None**

      **ReadOnly**

      **ReadWrite**

      Default: **None for Standard storage. ReadOnly for Premium storage**. Possible values include: 'CachingTypesNone', 'CachingTypesReadOnly', 'CachingTypesReadWrite' - Caching CachingTypes `json:"caching,omitempty"` - // DiskSizeGB - Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual machine image.

      This value cannot be larger than 1023 GB - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // StorageAccountType - Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk. Possible values include: 'StorageAccountTypesStandardLRS', 'StorageAccountTypesPremiumLRS', 'StorageAccountTypesStandardSSDLRS', 'StorageAccountTypesUltraSSDLRS' - StorageAccountType StorageAccountTypes `json:"storageAccountType,omitempty"` -} - -// ImageDiskReference the source image used for creating the disk. -type ImageDiskReference struct { - // ID - A relative uri containing either a Platform Image Repository or user image reference. - ID *string `json:"id,omitempty"` - // Lun - If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image to use. For OS disks, this field is null. - Lun *int32 `json:"lun,omitempty"` -} - -// ImageListResult the List Image operation response. -type ImageListResult struct { - autorest.Response `json:"-"` - // Value - The list of Images. - Value *[]Image `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of Images. Call ListNext() with this to fetch the next page of Images. - NextLink *string `json:"nextLink,omitempty"` -} - -// ImageListResultIterator provides access to a complete listing of Image values. -type ImageListResultIterator struct { - i int - page ImageListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ImageListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImageListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ImageListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ImageListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ImageListResultIterator) Response() ImageListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ImageListResultIterator) Value() Image { - if !iter.page.NotDone() { - return Image{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ImageListResultIterator type. -func NewImageListResultIterator(page ImageListResultPage) ImageListResultIterator { - return ImageListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ilr ImageListResult) IsEmpty() bool { - return ilr.Value == nil || len(*ilr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ilr ImageListResult) hasNextLink() bool { - return ilr.NextLink != nil && len(*ilr.NextLink) != 0 -} - -// imageListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ilr ImageListResult) imageListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ilr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ilr.NextLink))) -} - -// ImageListResultPage contains a page of Image values. -type ImageListResultPage struct { - fn func(context.Context, ImageListResult) (ImageListResult, error) - ilr ImageListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ImageListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ImageListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ilr) - if err != nil { - return err - } - page.ilr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ImageListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ImageListResultPage) NotDone() bool { - return !page.ilr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ImageListResultPage) Response() ImageListResult { - return page.ilr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ImageListResultPage) Values() []Image { - if page.ilr.IsEmpty() { - return nil - } - return *page.ilr.Value -} - -// Creates a new instance of the ImageListResultPage type. -func NewImageListResultPage(cur ImageListResult, getNextPage func(context.Context, ImageListResult) (ImageListResult, error)) ImageListResultPage { - return ImageListResultPage{ - fn: getNextPage, - ilr: cur, - } -} - -// ImageOSDisk describes an Operating System disk. -type ImageOSDisk struct { - // OsType - This property allows you to specify the type of the OS that is included in the disk if creating a VM from a custom image.

      Possible values are:

      **Windows**

      **Linux**. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // OsState - The OS State. Possible values include: 'Generalized', 'Specialized' - OsState OperatingSystemStateTypes `json:"osState,omitempty"` - // Snapshot - The snapshot. - Snapshot *SubResource `json:"snapshot,omitempty"` - // ManagedDisk - The managedDisk. - ManagedDisk *SubResource `json:"managedDisk,omitempty"` - // BlobURI - The Virtual Hard Disk. - BlobURI *string `json:"blobUri,omitempty"` - // Caching - Specifies the caching requirements.

      Possible values are:

      **None**

      **ReadOnly**

      **ReadWrite**

      Default: **None for Standard storage. ReadOnly for Premium storage**. Possible values include: 'CachingTypesNone', 'CachingTypesReadOnly', 'CachingTypesReadWrite' - Caching CachingTypes `json:"caching,omitempty"` - // DiskSizeGB - Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual machine image.

      This value cannot be larger than 1023 GB - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // StorageAccountType - Specifies the storage account type for the managed disk. UltraSSD_LRS cannot be used with OS Disk. Possible values include: 'StorageAccountTypesStandardLRS', 'StorageAccountTypesPremiumLRS', 'StorageAccountTypesStandardSSDLRS', 'StorageAccountTypesUltraSSDLRS' - StorageAccountType StorageAccountTypes `json:"storageAccountType,omitempty"` -} - -// ImageProperties describes the properties of an Image. -type ImageProperties struct { - // SourceVirtualMachine - The source virtual machine from which Image is created. - SourceVirtualMachine *SubResource `json:"sourceVirtualMachine,omitempty"` - // StorageProfile - Specifies the storage settings for the virtual machine disks. - StorageProfile *ImageStorageProfile `json:"storageProfile,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ImageProperties. -func (IP ImageProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if IP.SourceVirtualMachine != nil { - objectMap["sourceVirtualMachine"] = IP.SourceVirtualMachine - } - if IP.StorageProfile != nil { - objectMap["storageProfile"] = IP.StorageProfile - } - return json.Marshal(objectMap) -} - -// ImagePurchasePlan describes the gallery Image Definition purchase plan. This is used by marketplace -// images. -type ImagePurchasePlan struct { - // Name - The plan ID. - Name *string `json:"name,omitempty"` - // Publisher - The publisher ID. - Publisher *string `json:"publisher,omitempty"` - // Product - The product ID. - Product *string `json:"product,omitempty"` -} - -// ImageReference specifies information about the image to use. You can specify information about platform -// images, marketplace images, or virtual machine images. This element is required when you want to use a -// platform image, marketplace image, or virtual machine image, but is not used in other creation -// operations. NOTE: Image reference publisher and offer can only be set when you create the scale set. -type ImageReference struct { - // Publisher - The image publisher. - Publisher *string `json:"publisher,omitempty"` - // Offer - Specifies the offer of the platform image or marketplace image used to create the virtual machine. - Offer *string `json:"offer,omitempty"` - // Sku - The image SKU. - Sku *string `json:"sku,omitempty"` - // Version - Specifies the version of the platform image or marketplace image used to create the virtual machine. The allowed formats are Major.Minor.Build or 'latest'. Major, Minor, and Build are decimal numbers. Specify 'latest' to use the latest version of an image available at deploy time. Even if you use 'latest', the VM image will not automatically update after deploy time even if a new version becomes available. - Version *string `json:"version,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// ImagesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ImagesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ImagesClient) (Image, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ImagesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ImagesCreateOrUpdateFuture.Result. -func (future *ImagesCreateOrUpdateFuture) result(client ImagesClient) (i Image, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - i.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.ImagesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if i.Response.Response, err = future.GetResult(sender); err == nil && i.Response.Response.StatusCode != http.StatusNoContent { - i, err = client.CreateOrUpdateResponder(i.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesCreateOrUpdateFuture", "Result", i.Response.Response, "Failure responding to request") - } - } - return -} - -// ImagesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ImagesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ImagesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ImagesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ImagesDeleteFuture.Result. -func (future *ImagesDeleteFuture) result(client ImagesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.ImagesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ImageStorageProfile describes a storage profile. -type ImageStorageProfile struct { - // OsDisk - Specifies information about the operating system disk used by the virtual machine.

      For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). - OsDisk *ImageOSDisk `json:"osDisk,omitempty"` - // DataDisks - Specifies the parameters that are used to add a data disk to a virtual machine.

      For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). - DataDisks *[]ImageDataDisk `json:"dataDisks,omitempty"` - // ZoneResilient - Specifies whether an image is zone resilient or not. Default is false. Zone resilient images can be created only in regions that provide Zone Redundant Storage (ZRS). - ZoneResilient *bool `json:"zoneResilient,omitempty"` -} - -// ImagesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ImagesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ImagesClient) (Image, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ImagesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ImagesUpdateFuture.Result. -func (future *ImagesUpdateFuture) result(client ImagesClient) (i Image, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - i.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.ImagesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if i.Response.Response, err = future.GetResult(sender); err == nil && i.Response.Response.StatusCode != http.StatusNoContent { - i, err = client.UpdateResponder(i.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ImagesUpdateFuture", "Result", i.Response.Response, "Failure responding to request") - } - } - return -} - -// ImageUpdate the source user image virtual hard disk. Only tags may be updated. -type ImageUpdate struct { - *ImageProperties `json:"properties,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ImageUpdate. -func (iu ImageUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iu.ImageProperties != nil { - objectMap["properties"] = iu.ImageProperties - } - if iu.Tags != nil { - objectMap["tags"] = iu.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ImageUpdate struct. -func (iu *ImageUpdate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var imageProperties ImageProperties - err = json.Unmarshal(*v, &imageProperties) - if err != nil { - return err - } - iu.ImageProperties = &imageProperties - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - iu.Tags = tags - } - } - } - - return nil -} - -// InnerError inner error details. -type InnerError struct { - // Exceptiontype - The exception type. - Exceptiontype *string `json:"exceptiontype,omitempty"` - // Errordetail - The internal error message or exception dump. - Errordetail *string `json:"errordetail,omitempty"` -} - -// InstanceViewStatus instance view status. -type InstanceViewStatus struct { - // Code - The status code. - Code *string `json:"code,omitempty"` - // Level - The level code. Possible values include: 'Info', 'Warning', 'Error' - Level StatusLevelTypes `json:"level,omitempty"` - // DisplayStatus - The short localizable label for the status. - DisplayStatus *string `json:"displayStatus,omitempty"` - // Message - The detailed status message, including for alerts and error messages. - Message *string `json:"message,omitempty"` - // Time - The time of the status. - Time *date.Time `json:"time,omitempty"` -} - -// KeyVaultAndKeyReference key Vault Key Url and vault id of KeK, KeK is optional and when provided is used -// to unwrap the encryptionKey -type KeyVaultAndKeyReference struct { - // SourceVault - Resource id of the KeyVault containing the key or secret - SourceVault *SourceVault `json:"sourceVault,omitempty"` - // KeyURL - Url pointing to a key or secret in KeyVault - KeyURL *string `json:"keyUrl,omitempty"` -} - -// KeyVaultAndSecretReference key Vault Secret Url and vault id of the encryption key -type KeyVaultAndSecretReference struct { - // SourceVault - Resource id of the KeyVault containing the key or secret - SourceVault *SourceVault `json:"sourceVault,omitempty"` - // SecretURL - Url pointing to a key or secret in KeyVault - SecretURL *string `json:"secretUrl,omitempty"` -} - -// KeyVaultKeyReference describes a reference to Key Vault Key -type KeyVaultKeyReference struct { - // KeyURL - The URL referencing a key encryption key in Key Vault. - KeyURL *string `json:"keyUrl,omitempty"` - // SourceVault - The relative URL of the Key Vault containing the key. - SourceVault *SubResource `json:"sourceVault,omitempty"` -} - -// KeyVaultSecretReference describes a reference to Key Vault Secret -type KeyVaultSecretReference struct { - // SecretURL - The URL referencing a secret in a Key Vault. - SecretURL *string `json:"secretUrl,omitempty"` - // SourceVault - The relative URL of the Key Vault containing the secret. - SourceVault *SubResource `json:"sourceVault,omitempty"` -} - -// LinuxConfiguration specifies the Linux operating system settings on the virtual machine.

      For a -// list of supported Linux distributions, see [Linux on Azure-Endorsed -// Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) -//

      For running non-endorsed distributions, see [Information for Non-Endorsed -// Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). -type LinuxConfiguration struct { - // DisablePasswordAuthentication - Specifies whether password authentication should be disabled. - DisablePasswordAuthentication *bool `json:"disablePasswordAuthentication,omitempty"` - // SSH - Specifies the ssh key configuration for a Linux OS. - SSH *SSHConfiguration `json:"ssh,omitempty"` - // ProvisionVMAgent - Indicates whether virtual machine agent should be provisioned on the virtual machine.

      When this property is not specified in the request body, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later. - ProvisionVMAgent *bool `json:"provisionVMAgent,omitempty"` -} - -// ListUsagesResult the List Usages operation response. -type ListUsagesResult struct { - autorest.Response `json:"-"` - // Value - The list of compute resource usages. - Value *[]Usage `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of compute resource usage information. Call ListNext() with this to fetch the next page of compute resource usage information. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListUsagesResultIterator provides access to a complete listing of Usage values. -type ListUsagesResultIterator struct { - i int - page ListUsagesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListUsagesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListUsagesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListUsagesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListUsagesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListUsagesResultIterator) Response() ListUsagesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListUsagesResultIterator) Value() Usage { - if !iter.page.NotDone() { - return Usage{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListUsagesResultIterator type. -func NewListUsagesResultIterator(page ListUsagesResultPage) ListUsagesResultIterator { - return ListUsagesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lur ListUsagesResult) IsEmpty() bool { - return lur.Value == nil || len(*lur.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lur ListUsagesResult) hasNextLink() bool { - return lur.NextLink != nil && len(*lur.NextLink) != 0 -} - -// listUsagesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lur ListUsagesResult) listUsagesResultPreparer(ctx context.Context) (*http.Request, error) { - if !lur.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lur.NextLink))) -} - -// ListUsagesResultPage contains a page of Usage values. -type ListUsagesResultPage struct { - fn func(context.Context, ListUsagesResult) (ListUsagesResult, error) - lur ListUsagesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListUsagesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListUsagesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lur) - if err != nil { - return err - } - page.lur = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListUsagesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListUsagesResultPage) NotDone() bool { - return !page.lur.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListUsagesResultPage) Response() ListUsagesResult { - return page.lur -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListUsagesResultPage) Values() []Usage { - if page.lur.IsEmpty() { - return nil - } - return *page.lur.Value -} - -// Creates a new instance of the ListUsagesResultPage type. -func NewListUsagesResultPage(cur ListUsagesResult, getNextPage func(context.Context, ListUsagesResult) (ListUsagesResult, error)) ListUsagesResultPage { - return ListUsagesResultPage{ - fn: getNextPage, - lur: cur, - } -} - -// ListVirtualMachineExtensionImage ... -type ListVirtualMachineExtensionImage struct { - autorest.Response `json:"-"` - Value *[]VirtualMachineExtensionImage `json:"value,omitempty"` -} - -// ListVirtualMachineImageResource ... -type ListVirtualMachineImageResource struct { - autorest.Response `json:"-"` - Value *[]VirtualMachineImageResource `json:"value,omitempty"` -} - -// LogAnalyticsExportRequestRateByIntervalFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type LogAnalyticsExportRequestRateByIntervalFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LogAnalyticsClient) (LogAnalyticsOperationResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LogAnalyticsExportRequestRateByIntervalFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LogAnalyticsExportRequestRateByIntervalFuture.Result. -func (future *LogAnalyticsExportRequestRateByIntervalFuture) result(client LogAnalyticsClient) (laor LogAnalyticsOperationResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsExportRequestRateByIntervalFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - laor.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.LogAnalyticsExportRequestRateByIntervalFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if laor.Response.Response, err = future.GetResult(sender); err == nil && laor.Response.Response.StatusCode != http.StatusNoContent { - laor, err = client.ExportRequestRateByIntervalResponder(laor.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsExportRequestRateByIntervalFuture", "Result", laor.Response.Response, "Failure responding to request") - } - } - return -} - -// LogAnalyticsExportThrottledRequestsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LogAnalyticsExportThrottledRequestsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LogAnalyticsClient) (LogAnalyticsOperationResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LogAnalyticsExportThrottledRequestsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LogAnalyticsExportThrottledRequestsFuture.Result. -func (future *LogAnalyticsExportThrottledRequestsFuture) result(client LogAnalyticsClient) (laor LogAnalyticsOperationResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsExportThrottledRequestsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - laor.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.LogAnalyticsExportThrottledRequestsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if laor.Response.Response, err = future.GetResult(sender); err == nil && laor.Response.Response.StatusCode != http.StatusNoContent { - laor, err = client.ExportThrottledRequestsResponder(laor.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.LogAnalyticsExportThrottledRequestsFuture", "Result", laor.Response.Response, "Failure responding to request") - } - } - return -} - -// LogAnalyticsInputBase api input base class for LogAnalytics Api. -type LogAnalyticsInputBase struct { - // BlobContainerSasURI - SAS Uri of the logging blob container to which LogAnalytics Api writes output logs to. - BlobContainerSasURI *string `json:"blobContainerSasUri,omitempty"` - // FromTime - From time of the query - FromTime *date.Time `json:"fromTime,omitempty"` - // ToTime - To time of the query - ToTime *date.Time `json:"toTime,omitempty"` - // GroupByThrottlePolicy - Group query result by Throttle Policy applied. - GroupByThrottlePolicy *bool `json:"groupByThrottlePolicy,omitempty"` - // GroupByOperationName - Group query result by Operation Name. - GroupByOperationName *bool `json:"groupByOperationName,omitempty"` - // GroupByResourceName - Group query result by Resource Name. - GroupByResourceName *bool `json:"groupByResourceName,omitempty"` -} - -// LogAnalyticsOperationResult logAnalytics operation status response -type LogAnalyticsOperationResult struct { - autorest.Response `json:"-"` - // Properties - READ-ONLY; LogAnalyticsOutput - Properties *LogAnalyticsOutput `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for LogAnalyticsOperationResult. -func (laor LogAnalyticsOperationResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// LogAnalyticsOutput logAnalytics output properties -type LogAnalyticsOutput struct { - // Output - READ-ONLY; Output file Uri path to blob container. - Output *string `json:"output,omitempty"` -} - -// MarshalJSON is the custom marshaler for LogAnalyticsOutput. -func (lao LogAnalyticsOutput) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// MaintenanceRedeployStatus maintenance Operation Status. -type MaintenanceRedeployStatus struct { - // IsCustomerInitiatedMaintenanceAllowed - True, if customer is allowed to perform Maintenance. - IsCustomerInitiatedMaintenanceAllowed *bool `json:"isCustomerInitiatedMaintenanceAllowed,omitempty"` - // PreMaintenanceWindowStartTime - Start Time for the Pre Maintenance Window. - PreMaintenanceWindowStartTime *date.Time `json:"preMaintenanceWindowStartTime,omitempty"` - // PreMaintenanceWindowEndTime - End Time for the Pre Maintenance Window. - PreMaintenanceWindowEndTime *date.Time `json:"preMaintenanceWindowEndTime,omitempty"` - // MaintenanceWindowStartTime - Start Time for the Maintenance Window. - MaintenanceWindowStartTime *date.Time `json:"maintenanceWindowStartTime,omitempty"` - // MaintenanceWindowEndTime - End Time for the Maintenance Window. - MaintenanceWindowEndTime *date.Time `json:"maintenanceWindowEndTime,omitempty"` - // LastOperationResultCode - The Last Maintenance Operation Result Code. Possible values include: 'MaintenanceOperationResultCodeTypesNone', 'MaintenanceOperationResultCodeTypesRetryLater', 'MaintenanceOperationResultCodeTypesMaintenanceAborted', 'MaintenanceOperationResultCodeTypesMaintenanceCompleted' - LastOperationResultCode MaintenanceOperationResultCodeTypes `json:"lastOperationResultCode,omitempty"` - // LastOperationMessage - Message returned for the last Maintenance Operation. - LastOperationMessage *string `json:"lastOperationMessage,omitempty"` -} - -// ManagedArtifact the managed artifact. -type ManagedArtifact struct { - // ID - The managed artifact id. - ID *string `json:"id,omitempty"` -} - -// ManagedDiskParameters the parameters of a managed disk. -type ManagedDiskParameters struct { - // StorageAccountType - Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk. Possible values include: 'StorageAccountTypesStandardLRS', 'StorageAccountTypesPremiumLRS', 'StorageAccountTypesStandardSSDLRS', 'StorageAccountTypesUltraSSDLRS' - StorageAccountType StorageAccountTypes `json:"storageAccountType,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// NetworkInterfaceReference describes a network interface reference. -type NetworkInterfaceReference struct { - *NetworkInterfaceReferenceProperties `json:"properties,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for NetworkInterfaceReference. -func (nir NetworkInterfaceReference) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if nir.NetworkInterfaceReferenceProperties != nil { - objectMap["properties"] = nir.NetworkInterfaceReferenceProperties - } - if nir.ID != nil { - objectMap["id"] = nir.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for NetworkInterfaceReference struct. -func (nir *NetworkInterfaceReference) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var networkInterfaceReferenceProperties NetworkInterfaceReferenceProperties - err = json.Unmarshal(*v, &networkInterfaceReferenceProperties) - if err != nil { - return err - } - nir.NetworkInterfaceReferenceProperties = &networkInterfaceReferenceProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - nir.ID = &ID - } - } - } - - return nil -} - -// NetworkInterfaceReferenceProperties describes a network interface reference properties. -type NetworkInterfaceReferenceProperties struct { - // Primary - Specifies the primary network interface in case the virtual machine has more than 1 network interface. - Primary *bool `json:"primary,omitempty"` -} - -// NetworkProfile specifies the network interfaces of the virtual machine. -type NetworkProfile struct { - // NetworkInterfaces - Specifies the list of resource Ids for the network interfaces associated with the virtual machine. - NetworkInterfaces *[]NetworkInterfaceReference `json:"networkInterfaces,omitempty"` -} - -// OperationListResult the List Compute Operation operation response. -type OperationListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; The list of compute operations - Value *[]OperationValue `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationListResult. -func (olr OperationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// OperationValue describes the properties of a Compute Operation value. -type OperationValue struct { - // Origin - READ-ONLY; The origin of the compute operation. - Origin *string `json:"origin,omitempty"` - // Name - READ-ONLY; The name of the compute operation. - Name *string `json:"name,omitempty"` - *OperationValueDisplay `json:"display,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationValue. -func (ov OperationValue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ov.OperationValueDisplay != nil { - objectMap["display"] = ov.OperationValueDisplay - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for OperationValue struct. -func (ov *OperationValue) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "origin": - if v != nil { - var origin string - err = json.Unmarshal(*v, &origin) - if err != nil { - return err - } - ov.Origin = &origin - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ov.Name = &name - } - case "display": - if v != nil { - var operationValueDisplay OperationValueDisplay - err = json.Unmarshal(*v, &operationValueDisplay) - if err != nil { - return err - } - ov.OperationValueDisplay = &operationValueDisplay - } - } - } - - return nil -} - -// OperationValueDisplay describes the properties of a Compute Operation Value Display. -type OperationValueDisplay struct { - // Operation - READ-ONLY; The display name of the compute operation. - Operation *string `json:"operation,omitempty"` - // Resource - READ-ONLY; The display name of the resource the operation applies to. - Resource *string `json:"resource,omitempty"` - // Description - READ-ONLY; The description of the operation. - Description *string `json:"description,omitempty"` - // Provider - READ-ONLY; The resource provider for the operation. - Provider *string `json:"provider,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationValueDisplay. -func (ovd OperationValueDisplay) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// OSDisk specifies information about the operating system disk used by the virtual machine.

      For -// more information about disks, see [About disks and VHDs for Azure virtual -// machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). -type OSDisk struct { - // OsType - This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD.

      Possible values are:

      **Windows**

      **Linux**. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // EncryptionSettings - Specifies the encryption settings for the OS Disk.

      Minimum api-version: 2015-06-15 - EncryptionSettings *DiskEncryptionSettings `json:"encryptionSettings,omitempty"` - // Name - The disk name. - Name *string `json:"name,omitempty"` - // Vhd - The virtual hard disk. - Vhd *VirtualHardDisk `json:"vhd,omitempty"` - // Image - The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist. - Image *VirtualHardDisk `json:"image,omitempty"` - // Caching - Specifies the caching requirements.

      Possible values are:

      **None**

      **ReadOnly**

      **ReadWrite**

      Default: **None for Standard storage. ReadOnly for Premium storage**. Possible values include: 'CachingTypesNone', 'CachingTypesReadOnly', 'CachingTypesReadWrite' - Caching CachingTypes `json:"caching,omitempty"` - // WriteAcceleratorEnabled - Specifies whether writeAccelerator should be enabled or disabled on the disk. - WriteAcceleratorEnabled *bool `json:"writeAcceleratorEnabled,omitempty"` - // DiffDiskSettings - Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. - DiffDiskSettings *DiffDiskSettings `json:"diffDiskSettings,omitempty"` - // CreateOption - Specifies how the virtual machine should be created.

      Possible values are:

      **Attach** \u2013 This value is used when you are using a specialized disk to create the virtual machine.

      **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. Possible values include: 'DiskCreateOptionTypesFromImage', 'DiskCreateOptionTypesEmpty', 'DiskCreateOptionTypesAttach' - CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` - // DiskSizeGB - Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image.

      This value cannot be larger than 1023 GB - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // ManagedDisk - The managed disk parameters. - ManagedDisk *ManagedDiskParameters `json:"managedDisk,omitempty"` -} - -// OSDiskImage contains the os disk image information. -type OSDiskImage struct { - // OperatingSystem - The operating system of the osDiskImage. Possible values include: 'Windows', 'Linux' - OperatingSystem OperatingSystemTypes `json:"operatingSystem,omitempty"` -} - -// OSProfile specifies the operating system settings for the virtual machine. -type OSProfile struct { - // ComputerName - Specifies the host OS name of the virtual machine.

      This name cannot be updated after the VM is created.

      **Max-length (Windows):** 15 characters

      **Max-length (Linux):** 64 characters.

      For naming conventions and restrictions see [Azure infrastructure services implementation guidelines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-infrastructure-subscription-accounts-guidelines?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#1-naming-conventions). - ComputerName *string `json:"computerName,omitempty"` - // AdminUsername - Specifies the name of the administrator account.

      **Windows-only restriction:** Cannot end in "."

      **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5".

      **Minimum-length (Linux):** 1 character

      **Max-length (Linux):** 64 characters

      **Max-length (Windows):** 20 characters

    • For root access to the Linux VM, see [Using root privileges on Linux virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-use-root-privileges?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)
    • For a list of built-in system users on Linux that should not be used in this field, see [Selecting User Names for Linux on Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-usernames?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) - AdminUsername *string `json:"adminUsername,omitempty"` - // AdminPassword - Specifies the password of the administrator account.

      **Minimum-length (Windows):** 8 characters

      **Minimum-length (Linux):** 6 characters

      **Max-length (Windows):** 123 characters

      **Max-length (Linux):** 72 characters

      **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled
      Has lower characters
      Has upper characters
      Has a digit
      Has a special character (Regex match [\W_])

      **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!"

      For resetting the password, see [How to reset the Remote Desktop service or its login password in a Windows VM](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-reset-rdp?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)

      For resetting root password, see [Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-vmaccess-extension?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#reset-root-password) - AdminPassword *string `json:"adminPassword,omitempty"` - // CustomData - Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes.

      For using cloud-init for your VM, see [Using cloud-init to customize a Linux VM during creation](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-cloud-init?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) - CustomData *string `json:"customData,omitempty"` - // WindowsConfiguration - Specifies Windows operating system settings on the virtual machine. - WindowsConfiguration *WindowsConfiguration `json:"windowsConfiguration,omitempty"` - // LinuxConfiguration - Specifies the Linux operating system settings on the virtual machine.

      For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)

      For running non-endorsed distributions, see [Information for Non-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). - LinuxConfiguration *LinuxConfiguration `json:"linuxConfiguration,omitempty"` - // Secrets - Specifies set of certificates that should be installed onto the virtual machine. - Secrets *[]VaultSecretGroup `json:"secrets,omitempty"` - // AllowExtensionOperations - Specifies whether extension operations should be allowed on the virtual machine.

      This may only be set to False when no extensions are present on the virtual machine. - AllowExtensionOperations *bool `json:"allowExtensionOperations,omitempty"` -} - -// Plan specifies information about the marketplace image used to create the virtual machine. This element -// is only used for marketplace images. Before you can use a marketplace image from an API, you must enable -// the image for programmatic use. In the Azure portal, find the marketplace image that you want to use -// and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and -// then click **Save**. -type Plan struct { - // Name - The plan ID. - Name *string `json:"name,omitempty"` - // Publisher - The publisher ID. - Publisher *string `json:"publisher,omitempty"` - // Product - Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. - Product *string `json:"product,omitempty"` - // PromotionCode - The promotion code. - PromotionCode *string `json:"promotionCode,omitempty"` -} - -// ProximityPlacementGroup specifies information about the proximity placement group. -type ProximityPlacementGroup struct { - autorest.Response `json:"-"` - // ProximityPlacementGroupProperties - Describes the properties of a Proximity Placement Group. - *ProximityPlacementGroupProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ProximityPlacementGroup. -func (ppg ProximityPlacementGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ppg.ProximityPlacementGroupProperties != nil { - objectMap["properties"] = ppg.ProximityPlacementGroupProperties - } - if ppg.Location != nil { - objectMap["location"] = ppg.Location - } - if ppg.Tags != nil { - objectMap["tags"] = ppg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ProximityPlacementGroup struct. -func (ppg *ProximityPlacementGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var proximityPlacementGroupProperties ProximityPlacementGroupProperties - err = json.Unmarshal(*v, &proximityPlacementGroupProperties) - if err != nil { - return err - } - ppg.ProximityPlacementGroupProperties = &proximityPlacementGroupProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ppg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ppg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ppg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ppg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ppg.Tags = tags - } - } - } - - return nil -} - -// ProximityPlacementGroupListResult the List Proximity Placement Group operation response. -type ProximityPlacementGroupListResult struct { - autorest.Response `json:"-"` - // Value - The list of proximity placement groups - Value *[]ProximityPlacementGroup `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of proximity placement groups. - NextLink *string `json:"nextLink,omitempty"` -} - -// ProximityPlacementGroupListResultIterator provides access to a complete listing of -// ProximityPlacementGroup values. -type ProximityPlacementGroupListResultIterator struct { - i int - page ProximityPlacementGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ProximityPlacementGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ProximityPlacementGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ProximityPlacementGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ProximityPlacementGroupListResultIterator) Response() ProximityPlacementGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ProximityPlacementGroupListResultIterator) Value() ProximityPlacementGroup { - if !iter.page.NotDone() { - return ProximityPlacementGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ProximityPlacementGroupListResultIterator type. -func NewProximityPlacementGroupListResultIterator(page ProximityPlacementGroupListResultPage) ProximityPlacementGroupListResultIterator { - return ProximityPlacementGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ppglr ProximityPlacementGroupListResult) IsEmpty() bool { - return ppglr.Value == nil || len(*ppglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ppglr ProximityPlacementGroupListResult) hasNextLink() bool { - return ppglr.NextLink != nil && len(*ppglr.NextLink) != 0 -} - -// proximityPlacementGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ppglr ProximityPlacementGroupListResult) proximityPlacementGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ppglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ppglr.NextLink))) -} - -// ProximityPlacementGroupListResultPage contains a page of ProximityPlacementGroup values. -type ProximityPlacementGroupListResultPage struct { - fn func(context.Context, ProximityPlacementGroupListResult) (ProximityPlacementGroupListResult, error) - ppglr ProximityPlacementGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ProximityPlacementGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ppglr) - if err != nil { - return err - } - page.ppglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ProximityPlacementGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ProximityPlacementGroupListResultPage) NotDone() bool { - return !page.ppglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ProximityPlacementGroupListResultPage) Response() ProximityPlacementGroupListResult { - return page.ppglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ProximityPlacementGroupListResultPage) Values() []ProximityPlacementGroup { - if page.ppglr.IsEmpty() { - return nil - } - return *page.ppglr.Value -} - -// Creates a new instance of the ProximityPlacementGroupListResultPage type. -func NewProximityPlacementGroupListResultPage(cur ProximityPlacementGroupListResult, getNextPage func(context.Context, ProximityPlacementGroupListResult) (ProximityPlacementGroupListResult, error)) ProximityPlacementGroupListResultPage { - return ProximityPlacementGroupListResultPage{ - fn: getNextPage, - ppglr: cur, - } -} - -// ProximityPlacementGroupProperties describes the properties of a Proximity Placement Group. -type ProximityPlacementGroupProperties struct { - // ProximityPlacementGroupType - Specifies the type of the proximity placement group.

      Possible values are:

      **Standard** : Co-locate resources within an Azure region or Availability Zone.

      **Ultra** : For future use. Possible values include: 'Standard', 'Ultra' - ProximityPlacementGroupType ProximityPlacementGroupType `json:"proximityPlacementGroupType,omitempty"` - // VirtualMachines - READ-ONLY; A list of references to all virtual machines in the proximity placement group. - VirtualMachines *[]SubResource `json:"virtualMachines,omitempty"` - // VirtualMachineScaleSets - READ-ONLY; A list of references to all virtual machine scale sets in the proximity placement group. - VirtualMachineScaleSets *[]SubResource `json:"virtualMachineScaleSets,omitempty"` - // AvailabilitySets - READ-ONLY; A list of references to all availability sets in the proximity placement group. - AvailabilitySets *[]SubResource `json:"availabilitySets,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProximityPlacementGroupProperties. -func (ppgp ProximityPlacementGroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ppgp.ProximityPlacementGroupType != "" { - objectMap["proximityPlacementGroupType"] = ppgp.ProximityPlacementGroupType - } - return json.Marshal(objectMap) -} - -// ProximityPlacementGroupUpdate specifies information about the proximity placement group. -type ProximityPlacementGroupUpdate struct { - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ProximityPlacementGroupUpdate. -func (ppgu ProximityPlacementGroupUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ppgu.Tags != nil { - objectMap["tags"] = ppgu.Tags - } - return json.Marshal(objectMap) -} - -// PurchasePlan used for establishing the purchase context of any 3rd Party artifact through MarketPlace. -type PurchasePlan struct { - // Publisher - The publisher ID. - Publisher *string `json:"publisher,omitempty"` - // Name - The plan ID. - Name *string `json:"name,omitempty"` - // Product - Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. - Product *string `json:"product,omitempty"` -} - -// RecommendedMachineConfiguration the properties describe the recommended machine configuration for this -// Image Definition. These properties are updatable. -type RecommendedMachineConfiguration struct { - VCPUs *ResourceRange `json:"vCPUs,omitempty"` - Memory *ResourceRange `json:"memory,omitempty"` -} - -// RecoveryWalkResponse response after calling a manual recovery walk -type RecoveryWalkResponse struct { - autorest.Response `json:"-"` - // WalkPerformed - READ-ONLY; Whether the recovery walk was performed - WalkPerformed *bool `json:"walkPerformed,omitempty"` - // NextPlatformUpdateDomain - READ-ONLY; The next update domain that needs to be walked. Null means walk spanning all update domains has been completed - NextPlatformUpdateDomain *int32 `json:"nextPlatformUpdateDomain,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecoveryWalkResponse. -func (rwr RecoveryWalkResponse) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RegionalReplicationStatus this is the regional replication status. -type RegionalReplicationStatus struct { - // Region - READ-ONLY; The region to which the gallery Image Version is being replicated to. - Region *string `json:"region,omitempty"` - // State - READ-ONLY; This is the regional replication state. Possible values include: 'ReplicationStateUnknown', 'ReplicationStateReplicating', 'ReplicationStateCompleted', 'ReplicationStateFailed' - State ReplicationState `json:"state,omitempty"` - // Details - READ-ONLY; The details of the replication status. - Details *string `json:"details,omitempty"` - // Progress - READ-ONLY; It indicates progress of the replication job. - Progress *int32 `json:"progress,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegionalReplicationStatus. -func (rrs RegionalReplicationStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ReplicationStatus this is the replication status of the gallery Image Version. -type ReplicationStatus struct { - // AggregatedState - READ-ONLY; This is the aggregated replication status based on all the regional replication status flags. Possible values include: 'Unknown', 'InProgress', 'Completed', 'Failed' - AggregatedState AggregatedReplicationState `json:"aggregatedState,omitempty"` - // Summary - READ-ONLY; This is a summary of replication status for each region. - Summary *[]RegionalReplicationStatus `json:"summary,omitempty"` -} - -// MarshalJSON is the custom marshaler for ReplicationStatus. -func (rs ReplicationStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RequestRateByIntervalInput api request input for LogAnalytics getRequestRateByInterval Api. -type RequestRateByIntervalInput struct { - // IntervalLength - Interval value in minutes used to create LogAnalytics call rate logs. Possible values include: 'ThreeMins', 'FiveMins', 'ThirtyMins', 'SixtyMins' - IntervalLength IntervalInMins `json:"intervalLength,omitempty"` - // BlobContainerSasURI - SAS Uri of the logging blob container to which LogAnalytics Api writes output logs to. - BlobContainerSasURI *string `json:"blobContainerSasUri,omitempty"` - // FromTime - From time of the query - FromTime *date.Time `json:"fromTime,omitempty"` - // ToTime - To time of the query - ToTime *date.Time `json:"toTime,omitempty"` - // GroupByThrottlePolicy - Group query result by Throttle Policy applied. - GroupByThrottlePolicy *bool `json:"groupByThrottlePolicy,omitempty"` - // GroupByOperationName - Group query result by Operation Name. - GroupByOperationName *bool `json:"groupByOperationName,omitempty"` - // GroupByResourceName - Group query result by Resource Name. - GroupByResourceName *bool `json:"groupByResourceName,omitempty"` -} - -// Resource the Resource model definition. -type Resource struct { - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// ResourceRange describes the resource range. -type ResourceRange struct { - // Min - The minimum number of the resource. - Min *int32 `json:"min,omitempty"` - // Max - The maximum number of the resource. - Max *int32 `json:"max,omitempty"` -} - -// ResourceSku describes an available Compute SKU. -type ResourceSku struct { - // ResourceType - READ-ONLY; The type of resource the SKU applies to. - ResourceType *string `json:"resourceType,omitempty"` - // Name - READ-ONLY; The name of SKU. - Name *string `json:"name,omitempty"` - // Tier - READ-ONLY; Specifies the tier of virtual machines in a scale set.

      Possible Values:

      **Standard**

      **Basic** - Tier *string `json:"tier,omitempty"` - // Size - READ-ONLY; The Size of the SKU. - Size *string `json:"size,omitempty"` - // Family - READ-ONLY; The Family of this particular SKU. - Family *string `json:"family,omitempty"` - // Kind - READ-ONLY; The Kind of resources that are supported in this SKU. - Kind *string `json:"kind,omitempty"` - // Capacity - READ-ONLY; Specifies the number of virtual machines in the scale set. - Capacity *ResourceSkuCapacity `json:"capacity,omitempty"` - // Locations - READ-ONLY; The set of locations that the SKU is available. - Locations *[]string `json:"locations,omitempty"` - // LocationInfo - READ-ONLY; A list of locations and availability zones in those locations where the SKU is available. - LocationInfo *[]ResourceSkuLocationInfo `json:"locationInfo,omitempty"` - // APIVersions - READ-ONLY; The api versions that support this SKU. - APIVersions *[]string `json:"apiVersions,omitempty"` - // Costs - READ-ONLY; Metadata for retrieving price info. - Costs *[]ResourceSkuCosts `json:"costs,omitempty"` - // Capabilities - READ-ONLY; A name value pair to describe the capability. - Capabilities *[]ResourceSkuCapabilities `json:"capabilities,omitempty"` - // Restrictions - READ-ONLY; The restrictions because of which SKU cannot be used. This is empty if there are no restrictions. - Restrictions *[]ResourceSkuRestrictions `json:"restrictions,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceSku. -func (rs ResourceSku) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceSkuCapabilities describes The SKU capabilities object. -type ResourceSkuCapabilities struct { - // Name - READ-ONLY; An invariant to describe the feature. - Name *string `json:"name,omitempty"` - // Value - READ-ONLY; An invariant if the feature is measured by quantity. - Value *string `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceSkuCapabilities. -func (rsc ResourceSkuCapabilities) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceSkuCapacity describes scaling information of a SKU. -type ResourceSkuCapacity struct { - // Minimum - READ-ONLY; The minimum capacity. - Minimum *int64 `json:"minimum,omitempty"` - // Maximum - READ-ONLY; The maximum capacity that can be set. - Maximum *int64 `json:"maximum,omitempty"` - // Default - READ-ONLY; The default capacity. - Default *int64 `json:"default,omitempty"` - // ScaleType - READ-ONLY; The scale type applicable to the sku. Possible values include: 'ResourceSkuCapacityScaleTypeAutomatic', 'ResourceSkuCapacityScaleTypeManual', 'ResourceSkuCapacityScaleTypeNone' - ScaleType ResourceSkuCapacityScaleType `json:"scaleType,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceSkuCapacity. -func (rsc ResourceSkuCapacity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceSkuCosts describes metadata for retrieving price info. -type ResourceSkuCosts struct { - // MeterID - READ-ONLY; Used for querying price from commerce. - MeterID *string `json:"meterID,omitempty"` - // Quantity - READ-ONLY; The multiplier is needed to extend the base metered cost. - Quantity *int64 `json:"quantity,omitempty"` - // ExtendedUnit - READ-ONLY; An invariant to show the extended unit. - ExtendedUnit *string `json:"extendedUnit,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceSkuCosts. -func (rsc ResourceSkuCosts) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceSkuLocationInfo ... -type ResourceSkuLocationInfo struct { - // Location - READ-ONLY; Location of the SKU - Location *string `json:"location,omitempty"` - // Zones - READ-ONLY; List of availability zones where the SKU is supported. - Zones *[]string `json:"zones,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceSkuLocationInfo. -func (rsli ResourceSkuLocationInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceSkuRestrictionInfo ... -type ResourceSkuRestrictionInfo struct { - // Locations - READ-ONLY; Locations where the SKU is restricted - Locations *[]string `json:"locations,omitempty"` - // Zones - READ-ONLY; List of availability zones where the SKU is restricted. - Zones *[]string `json:"zones,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceSkuRestrictionInfo. -func (rsri ResourceSkuRestrictionInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceSkuRestrictions describes scaling information of a SKU. -type ResourceSkuRestrictions struct { - // Type - READ-ONLY; The type of restrictions. Possible values include: 'Location', 'Zone' - Type ResourceSkuRestrictionsType `json:"type,omitempty"` - // Values - 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 `json:"values,omitempty"` - // RestrictionInfo - READ-ONLY; The information about the restriction where the SKU cannot be used. - RestrictionInfo *ResourceSkuRestrictionInfo `json:"restrictionInfo,omitempty"` - // ReasonCode - READ-ONLY; The reason for restriction. Possible values include: 'QuotaID', 'NotAvailableForSubscription' - ReasonCode ResourceSkuRestrictionsReasonCode `json:"reasonCode,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceSkuRestrictions. -func (rsr ResourceSkuRestrictions) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceSkusResult the List Resource Skus operation response. -type ResourceSkusResult struct { - autorest.Response `json:"-"` - // Value - The list of skus available for the subscription. - Value *[]ResourceSku `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of Resource Skus. Call ListNext() with this URI to fetch the next page of Resource Skus - NextLink *string `json:"nextLink,omitempty"` -} - -// ResourceSkusResultIterator provides access to a complete listing of ResourceSku values. -type ResourceSkusResultIterator struct { - i int - page ResourceSkusResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ResourceSkusResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkusResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ResourceSkusResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ResourceSkusResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ResourceSkusResultIterator) Response() ResourceSkusResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ResourceSkusResultIterator) Value() ResourceSku { - if !iter.page.NotDone() { - return ResourceSku{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ResourceSkusResultIterator type. -func NewResourceSkusResultIterator(page ResourceSkusResultPage) ResourceSkusResultIterator { - return ResourceSkusResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rsr ResourceSkusResult) IsEmpty() bool { - return rsr.Value == nil || len(*rsr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rsr ResourceSkusResult) hasNextLink() bool { - return rsr.NextLink != nil && len(*rsr.NextLink) != 0 -} - -// resourceSkusResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rsr ResourceSkusResult) resourceSkusResultPreparer(ctx context.Context) (*http.Request, error) { - if !rsr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rsr.NextLink))) -} - -// ResourceSkusResultPage contains a page of ResourceSku values. -type ResourceSkusResultPage struct { - fn func(context.Context, ResourceSkusResult) (ResourceSkusResult, error) - rsr ResourceSkusResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ResourceSkusResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkusResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rsr) - if err != nil { - return err - } - page.rsr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ResourceSkusResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ResourceSkusResultPage) NotDone() bool { - return !page.rsr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ResourceSkusResultPage) Response() ResourceSkusResult { - return page.rsr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ResourceSkusResultPage) Values() []ResourceSku { - if page.rsr.IsEmpty() { - return nil - } - return *page.rsr.Value -} - -// Creates a new instance of the ResourceSkusResultPage type. -func NewResourceSkusResultPage(cur ResourceSkusResult, getNextPage func(context.Context, ResourceSkusResult) (ResourceSkusResult, error)) ResourceSkusResultPage { - return ResourceSkusResultPage{ - fn: getNextPage, - rsr: cur, - } -} - -// RollbackStatusInfo information about rollback on failed VM instances after a OS Upgrade operation. -type RollbackStatusInfo struct { - // SuccessfullyRolledbackInstanceCount - READ-ONLY; The number of instances which have been successfully rolled back. - SuccessfullyRolledbackInstanceCount *int32 `json:"successfullyRolledbackInstanceCount,omitempty"` - // FailedRolledbackInstanceCount - READ-ONLY; The number of instances which failed to rollback. - FailedRolledbackInstanceCount *int32 `json:"failedRolledbackInstanceCount,omitempty"` - // RollbackError - READ-ONLY; Error details if OS rollback failed. - RollbackError *APIError `json:"rollbackError,omitempty"` -} - -// MarshalJSON is the custom marshaler for RollbackStatusInfo. -func (rsi RollbackStatusInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RollingUpgradePolicy the configuration parameters used while performing a rolling upgrade. -type RollingUpgradePolicy struct { - // MaxBatchInstancePercent - The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one batch. As this is a maximum, unhealthy instances in previous or future batches can cause the percentage of instances in a batch to decrease to ensure higher reliability. The default value for this parameter is 20%. - MaxBatchInstancePercent *int32 `json:"maxBatchInstancePercent,omitempty"` - // MaxUnhealthyInstancePercent - The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy, either as a result of being upgraded, or by being found in an unhealthy state by the virtual machine health checks before the rolling upgrade aborts. This constraint will be checked prior to starting any batch. The default value for this parameter is 20%. - MaxUnhealthyInstancePercent *int32 `json:"maxUnhealthyInstancePercent,omitempty"` - // MaxUnhealthyUpgradedInstancePercent - The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. This check will happen after each batch is upgraded. If this percentage is ever exceeded, the rolling update aborts. The default value for this parameter is 20%. - MaxUnhealthyUpgradedInstancePercent *int32 `json:"maxUnhealthyUpgradedInstancePercent,omitempty"` - // PauseTimeBetweenBatches - The wait time between completing the update for all virtual machines in one batch and starting the next batch. The time duration should be specified in ISO 8601 format. The default value is 0 seconds (PT0S). - PauseTimeBetweenBatches *string `json:"pauseTimeBetweenBatches,omitempty"` -} - -// RollingUpgradeProgressInfo information about the number of virtual machine instances in each upgrade -// state. -type RollingUpgradeProgressInfo struct { - // SuccessfulInstanceCount - READ-ONLY; The number of instances that have been successfully upgraded. - SuccessfulInstanceCount *int32 `json:"successfulInstanceCount,omitempty"` - // FailedInstanceCount - READ-ONLY; The number of instances that have failed to be upgraded successfully. - FailedInstanceCount *int32 `json:"failedInstanceCount,omitempty"` - // InProgressInstanceCount - READ-ONLY; The number of instances that are currently being upgraded. - InProgressInstanceCount *int32 `json:"inProgressInstanceCount,omitempty"` - // PendingInstanceCount - READ-ONLY; The number of instances that have not yet begun to be upgraded. - PendingInstanceCount *int32 `json:"pendingInstanceCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for RollingUpgradeProgressInfo. -func (rupi RollingUpgradeProgressInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RollingUpgradeRunningStatus information about the current running state of the overall upgrade. -type RollingUpgradeRunningStatus struct { - // Code - READ-ONLY; Code indicating the current status of the upgrade. Possible values include: 'RollingUpgradeStatusCodeRollingForward', 'RollingUpgradeStatusCodeCancelled', 'RollingUpgradeStatusCodeCompleted', 'RollingUpgradeStatusCodeFaulted' - Code RollingUpgradeStatusCode `json:"code,omitempty"` - // StartTime - READ-ONLY; Start time of the upgrade. - StartTime *date.Time `json:"startTime,omitempty"` - // LastAction - READ-ONLY; The last action performed on the rolling upgrade. Possible values include: 'Start', 'Cancel' - LastAction RollingUpgradeActionType `json:"lastAction,omitempty"` - // LastActionTime - READ-ONLY; Last action time of the upgrade. - LastActionTime *date.Time `json:"lastActionTime,omitempty"` -} - -// MarshalJSON is the custom marshaler for RollingUpgradeRunningStatus. -func (rurs RollingUpgradeRunningStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RollingUpgradeStatusInfo the status of the latest virtual machine scale set rolling upgrade. -type RollingUpgradeStatusInfo struct { - autorest.Response `json:"-"` - *RollingUpgradeStatusInfoProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for RollingUpgradeStatusInfo. -func (rusi RollingUpgradeStatusInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rusi.RollingUpgradeStatusInfoProperties != nil { - objectMap["properties"] = rusi.RollingUpgradeStatusInfoProperties - } - if rusi.Location != nil { - objectMap["location"] = rusi.Location - } - if rusi.Tags != nil { - objectMap["tags"] = rusi.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RollingUpgradeStatusInfo struct. -func (rusi *RollingUpgradeStatusInfo) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var rollingUpgradeStatusInfoProperties RollingUpgradeStatusInfoProperties - err = json.Unmarshal(*v, &rollingUpgradeStatusInfoProperties) - if err != nil { - return err - } - rusi.RollingUpgradeStatusInfoProperties = &rollingUpgradeStatusInfoProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rusi.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rusi.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rusi.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rusi.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - rusi.Tags = tags - } - } - } - - return nil -} - -// RollingUpgradeStatusInfoProperties the status of the latest virtual machine scale set rolling upgrade. -type RollingUpgradeStatusInfoProperties struct { - // Policy - READ-ONLY; The rolling upgrade policies applied for this upgrade. - Policy *RollingUpgradePolicy `json:"policy,omitempty"` - // RunningStatus - READ-ONLY; Information about the current running state of the overall upgrade. - RunningStatus *RollingUpgradeRunningStatus `json:"runningStatus,omitempty"` - // Progress - READ-ONLY; Information about the number of virtual machine instances in each upgrade state. - Progress *RollingUpgradeProgressInfo `json:"progress,omitempty"` - // Error - READ-ONLY; Error details for this upgrade, if there are any. - Error *APIError `json:"error,omitempty"` -} - -// MarshalJSON is the custom marshaler for RollingUpgradeStatusInfoProperties. -func (rusip RollingUpgradeStatusInfoProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RunCommandDocument describes the properties of a Run Command. -type RunCommandDocument struct { - autorest.Response `json:"-"` - // Script - The script to be executed. - Script *[]string `json:"script,omitempty"` - // Parameters - The parameters used by the script. - Parameters *[]RunCommandParameterDefinition `json:"parameters,omitempty"` - // Schema - The VM run command schema. - Schema *string `json:"$schema,omitempty"` - // ID - The VM run command id. - ID *string `json:"id,omitempty"` - // OsType - The Operating System type. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // Label - The VM run command label. - Label *string `json:"label,omitempty"` - // Description - The VM run command description. - Description *string `json:"description,omitempty"` -} - -// RunCommandDocumentBase describes the properties of a Run Command metadata. -type RunCommandDocumentBase struct { - // Schema - The VM run command schema. - Schema *string `json:"$schema,omitempty"` - // ID - The VM run command id. - ID *string `json:"id,omitempty"` - // OsType - The Operating System type. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // Label - The VM run command label. - Label *string `json:"label,omitempty"` - // Description - The VM run command description. - Description *string `json:"description,omitempty"` -} - -// RunCommandInput capture Virtual Machine parameters. -type RunCommandInput struct { - // CommandID - The run command id. - CommandID *string `json:"commandId,omitempty"` - // Script - Optional. The script to be executed. When this value is given, the given script will override the default script of the command. - Script *[]string `json:"script,omitempty"` - // Parameters - The run command parameters. - Parameters *[]RunCommandInputParameter `json:"parameters,omitempty"` -} - -// RunCommandInputParameter describes the properties of a run command parameter. -type RunCommandInputParameter struct { - // Name - The run command parameter name. - Name *string `json:"name,omitempty"` - // Value - The run command parameter value. - Value *string `json:"value,omitempty"` -} - -// RunCommandListResult the List Virtual Machine operation response. -type RunCommandListResult struct { - autorest.Response `json:"-"` - // Value - The list of virtual machine run commands. - Value *[]RunCommandDocumentBase `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of run commands. Call ListNext() with this to fetch the next page of run commands. - NextLink *string `json:"nextLink,omitempty"` -} - -// RunCommandListResultIterator provides access to a complete listing of RunCommandDocumentBase values. -type RunCommandListResultIterator struct { - i int - page RunCommandListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RunCommandListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RunCommandListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RunCommandListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RunCommandListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RunCommandListResultIterator) Response() RunCommandListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RunCommandListResultIterator) Value() RunCommandDocumentBase { - if !iter.page.NotDone() { - return RunCommandDocumentBase{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RunCommandListResultIterator type. -func NewRunCommandListResultIterator(page RunCommandListResultPage) RunCommandListResultIterator { - return RunCommandListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rclr RunCommandListResult) IsEmpty() bool { - return rclr.Value == nil || len(*rclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rclr RunCommandListResult) hasNextLink() bool { - return rclr.NextLink != nil && len(*rclr.NextLink) != 0 -} - -// runCommandListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rclr RunCommandListResult) runCommandListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rclr.NextLink))) -} - -// RunCommandListResultPage contains a page of RunCommandDocumentBase values. -type RunCommandListResultPage struct { - fn func(context.Context, RunCommandListResult) (RunCommandListResult, error) - rclr RunCommandListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RunCommandListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RunCommandListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rclr) - if err != nil { - return err - } - page.rclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RunCommandListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RunCommandListResultPage) NotDone() bool { - return !page.rclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RunCommandListResultPage) Response() RunCommandListResult { - return page.rclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RunCommandListResultPage) Values() []RunCommandDocumentBase { - if page.rclr.IsEmpty() { - return nil - } - return *page.rclr.Value -} - -// Creates a new instance of the RunCommandListResultPage type. -func NewRunCommandListResultPage(cur RunCommandListResult, getNextPage func(context.Context, RunCommandListResult) (RunCommandListResult, error)) RunCommandListResultPage { - return RunCommandListResultPage{ - fn: getNextPage, - rclr: cur, - } -} - -// RunCommandParameterDefinition describes the properties of a run command parameter. -type RunCommandParameterDefinition struct { - // Name - The run command parameter name. - Name *string `json:"name,omitempty"` - // Type - The run command parameter type. - Type *string `json:"type,omitempty"` - // DefaultValue - The run command parameter default value. - DefaultValue *string `json:"defaultValue,omitempty"` - // Required - The run command parameter required. - Required *bool `json:"required,omitempty"` -} - -// RunCommandResult ... -type RunCommandResult struct { - autorest.Response `json:"-"` - // Value - Run command operation response. - Value *[]InstanceViewStatus `json:"value,omitempty"` -} - -// Sku describes a virtual machine scale set sku. NOTE: If the new VM SKU is not supported on the hardware -// the scale set is currently on, you need to deallocate the VMs in the scale set before you modify the SKU -// name. -type Sku struct { - // Name - The sku name. - Name *string `json:"name,omitempty"` - // Tier - Specifies the tier of virtual machines in a scale set.

      Possible Values:

      **Standard**

      **Basic** - Tier *string `json:"tier,omitempty"` - // Capacity - Specifies the number of virtual machines in the scale set. - Capacity *int64 `json:"capacity,omitempty"` -} - -// Snapshot snapshot resource. -type Snapshot struct { - autorest.Response `json:"-"` - // ManagedBy - READ-ONLY; Unused. Always Null. - ManagedBy *string `json:"managedBy,omitempty"` - Sku *SnapshotSku `json:"sku,omitempty"` - *SnapshotProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Snapshot. -func (s Snapshot) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if s.Sku != nil { - objectMap["sku"] = s.Sku - } - if s.SnapshotProperties != nil { - objectMap["properties"] = s.SnapshotProperties - } - if s.Location != nil { - objectMap["location"] = s.Location - } - if s.Tags != nil { - objectMap["tags"] = s.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Snapshot struct. -func (s *Snapshot) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "managedBy": - if v != nil { - var managedBy string - err = json.Unmarshal(*v, &managedBy) - if err != nil { - return err - } - s.ManagedBy = &managedBy - } - case "sku": - if v != nil { - var sku SnapshotSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - s.Sku = &sku - } - case "properties": - if v != nil { - var snapshotProperties SnapshotProperties - err = json.Unmarshal(*v, &snapshotProperties) - if err != nil { - return err - } - s.SnapshotProperties = &snapshotProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - s.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - s.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - s.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - s.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - s.Tags = tags - } - } - } - - return nil -} - -// SnapshotList the List Snapshots operation response. -type SnapshotList struct { - autorest.Response `json:"-"` - // Value - A list of snapshots. - Value *[]Snapshot `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of snapshots. Call ListNext() with this to fetch the next page of snapshots. - NextLink *string `json:"nextLink,omitempty"` -} - -// SnapshotListIterator provides access to a complete listing of Snapshot values. -type SnapshotListIterator struct { - i int - page SnapshotListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SnapshotListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SnapshotListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SnapshotListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SnapshotListIterator) Response() SnapshotList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SnapshotListIterator) Value() Snapshot { - if !iter.page.NotDone() { - return Snapshot{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SnapshotListIterator type. -func NewSnapshotListIterator(page SnapshotListPage) SnapshotListIterator { - return SnapshotListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sl SnapshotList) IsEmpty() bool { - return sl.Value == nil || len(*sl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sl SnapshotList) hasNextLink() bool { - return sl.NextLink != nil && len(*sl.NextLink) != 0 -} - -// snapshotListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sl SnapshotList) snapshotListPreparer(ctx context.Context) (*http.Request, error) { - if !sl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sl.NextLink))) -} - -// SnapshotListPage contains a page of Snapshot values. -type SnapshotListPage struct { - fn func(context.Context, SnapshotList) (SnapshotList, error) - sl SnapshotList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SnapshotListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sl) - if err != nil { - return err - } - page.sl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SnapshotListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SnapshotListPage) NotDone() bool { - return !page.sl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SnapshotListPage) Response() SnapshotList { - return page.sl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SnapshotListPage) Values() []Snapshot { - if page.sl.IsEmpty() { - return nil - } - return *page.sl.Value -} - -// Creates a new instance of the SnapshotListPage type. -func NewSnapshotListPage(cur SnapshotList, getNextPage func(context.Context, SnapshotList) (SnapshotList, error)) SnapshotListPage { - return SnapshotListPage{ - fn: getNextPage, - sl: cur, - } -} - -// SnapshotProperties snapshot resource properties. -type SnapshotProperties struct { - // TimeCreated - READ-ONLY; The time when the disk was created. - TimeCreated *date.Time `json:"timeCreated,omitempty"` - // OsType - The Operating System type. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // CreationData - Disk source information. CreationData information cannot be changed after the disk has been created. - CreationData *CreationData `json:"creationData,omitempty"` - // DiskSizeGB - If creationData.createOption is Empty, this field is mandatory and it indicates the size of the VHD to create. If this field is present for updates or creation with other options, it indicates a resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // EncryptionSettings - Encryption settings for disk or snapshot - EncryptionSettings *EncryptionSettings `json:"encryptionSettings,omitempty"` - // ProvisioningState - READ-ONLY; The disk provisioning state. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotProperties. -func (sp SnapshotProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sp.OsType != "" { - objectMap["osType"] = sp.OsType - } - if sp.CreationData != nil { - objectMap["creationData"] = sp.CreationData - } - if sp.DiskSizeGB != nil { - objectMap["diskSizeGB"] = sp.DiskSizeGB - } - if sp.EncryptionSettings != nil { - objectMap["encryptionSettings"] = sp.EncryptionSettings - } - return json.Marshal(objectMap) -} - -// SnapshotsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (Snapshot, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsCreateOrUpdateFuture.Result. -func (future *SnapshotsCreateOrUpdateFuture) result(client SnapshotsClient) (s Snapshot, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.SnapshotsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.CreateOrUpdateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsCreateOrUpdateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// SnapshotsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsDeleteFuture.Result. -func (future *SnapshotsDeleteFuture) result(client SnapshotsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.SnapshotsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SnapshotsGrantAccessFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsGrantAccessFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (AccessURI, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsGrantAccessFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsGrantAccessFuture.Result. -func (future *SnapshotsGrantAccessFuture) result(client SnapshotsClient) (au AccessURI, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsGrantAccessFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - au.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.SnapshotsGrantAccessFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if au.Response.Response, err = future.GetResult(sender); err == nil && au.Response.Response.StatusCode != http.StatusNoContent { - au, err = client.GrantAccessResponder(au.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsGrantAccessFuture", "Result", au.Response.Response, "Failure responding to request") - } - } - return -} - -// SnapshotSku the snapshots sku name. Can be Standard_LRS, Premium_LRS, or Standard_ZRS. -type SnapshotSku struct { - // Name - The sku name. Possible values include: 'SnapshotStorageAccountTypesStandardLRS', 'SnapshotStorageAccountTypesPremiumLRS', 'SnapshotStorageAccountTypesStandardZRS' - Name SnapshotStorageAccountTypes `json:"name,omitempty"` - // Tier - READ-ONLY; The sku tier. - Tier *string `json:"tier,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotSku. -func (ss SnapshotSku) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ss.Name != "" { - objectMap["name"] = ss.Name - } - return json.Marshal(objectMap) -} - -// SnapshotsRevokeAccessFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsRevokeAccessFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsRevokeAccessFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsRevokeAccessFuture.Result. -func (future *SnapshotsRevokeAccessFuture) result(client SnapshotsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsRevokeAccessFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.SnapshotsRevokeAccessFuture") - return - } - ar.Response = future.Response() - return -} - -// SnapshotsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (Snapshot, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsUpdateFuture.Result. -func (future *SnapshotsUpdateFuture) result(client SnapshotsClient) (s Snapshot, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.SnapshotsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.UpdateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsUpdateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// SnapshotUpdate snapshot update resource. -type SnapshotUpdate struct { - *SnapshotUpdateProperties `json:"properties,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - Sku *SnapshotSku `json:"sku,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotUpdate. -func (su SnapshotUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if su.SnapshotUpdateProperties != nil { - objectMap["properties"] = su.SnapshotUpdateProperties - } - if su.Tags != nil { - objectMap["tags"] = su.Tags - } - if su.Sku != nil { - objectMap["sku"] = su.Sku - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SnapshotUpdate struct. -func (su *SnapshotUpdate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var snapshotUpdateProperties SnapshotUpdateProperties - err = json.Unmarshal(*v, &snapshotUpdateProperties) - if err != nil { - return err - } - su.SnapshotUpdateProperties = &snapshotUpdateProperties - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - su.Tags = tags - } - case "sku": - if v != nil { - var sku SnapshotSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - su.Sku = &sku - } - } - } - - return nil -} - -// SnapshotUpdateProperties snapshot resource update properties. -type SnapshotUpdateProperties struct { - // OsType - the Operating System type. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // DiskSizeGB - If creationData.createOption is Empty, this field is mandatory and it indicates the size of the VHD to create. If this field is present for updates or creation with other options, it indicates a resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size. - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // EncryptionSettings - Encryption settings for disk or snapshot - EncryptionSettings *EncryptionSettings `json:"encryptionSettings,omitempty"` -} - -// SourceVault the vault id is an Azure Resource Manager Resource id in the form -// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} -type SourceVault struct { - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// SSHConfiguration SSH configuration for Linux based VMs running on Azure -type SSHConfiguration struct { - // PublicKeys - The list of SSH public keys used to authenticate with linux based VMs. - PublicKeys *[]SSHPublicKey `json:"publicKeys,omitempty"` -} - -// SSHPublicKey contains information about SSH certificate public key and the path on the Linux VM where -// the public key is placed. -type SSHPublicKey struct { - // Path - Specifies the full path on the created VM where ssh public key is stored. If the file already exists, the specified key is appended to the file. Example: /home/user/.ssh/authorized_keys - Path *string `json:"path,omitempty"` - // KeyData - SSH public key certificate used to authenticate with the VM through ssh. The key needs to be at least 2048-bit and in ssh-rsa format.

      For creating ssh keys, see [Create SSH keys on Linux and Mac for Linux VMs in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-mac-create-ssh-keys?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). - KeyData *string `json:"keyData,omitempty"` -} - -// StorageProfile specifies the storage settings for the virtual machine disks. -type StorageProfile struct { - // ImageReference - Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. - ImageReference *ImageReference `json:"imageReference,omitempty"` - // OsDisk - Specifies information about the operating system disk used by the virtual machine.

      For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). - OsDisk *OSDisk `json:"osDisk,omitempty"` - // DataDisks - Specifies the parameters that are used to add a data disk to a virtual machine.

      For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). - DataDisks *[]DataDisk `json:"dataDisks,omitempty"` -} - -// SubResource ... -type SubResource struct { - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// SubResourceReadOnly ... -type SubResourceReadOnly struct { - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubResourceReadOnly. -func (srro SubResourceReadOnly) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// TargetRegion describes the target region information. -type TargetRegion struct { - // Name - The name of the region. - Name *string `json:"name,omitempty"` - // RegionalReplicaCount - The number of replicas of the Image Version to be created per region. This property is updatable. - RegionalReplicaCount *int32 `json:"regionalReplicaCount,omitempty"` -} - -// ThrottledRequestsInput api request input for LogAnalytics getThrottledRequests Api. -type ThrottledRequestsInput struct { - // BlobContainerSasURI - SAS Uri of the logging blob container to which LogAnalytics Api writes output logs to. - BlobContainerSasURI *string `json:"blobContainerSasUri,omitempty"` - // FromTime - From time of the query - FromTime *date.Time `json:"fromTime,omitempty"` - // ToTime - To time of the query - ToTime *date.Time `json:"toTime,omitempty"` - // GroupByThrottlePolicy - Group query result by Throttle Policy applied. - GroupByThrottlePolicy *bool `json:"groupByThrottlePolicy,omitempty"` - // GroupByOperationName - Group query result by Operation Name. - GroupByOperationName *bool `json:"groupByOperationName,omitempty"` - // GroupByResourceName - Group query result by Resource Name. - GroupByResourceName *bool `json:"groupByResourceName,omitempty"` -} - -// UpdateResource the Update Resource model definition. -type UpdateResource struct { - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for UpdateResource. -func (ur UpdateResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ur.Tags != nil { - objectMap["tags"] = ur.Tags - } - return json.Marshal(objectMap) -} - -// UpgradeOperationHistoricalStatusInfo virtual Machine Scale Set OS Upgrade History operation response. -type UpgradeOperationHistoricalStatusInfo struct { - // Properties - READ-ONLY; Information about the properties of the upgrade operation. - Properties *UpgradeOperationHistoricalStatusInfoProperties `json:"properties,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - READ-ONLY; Resource location - Location *string `json:"location,omitempty"` -} - -// MarshalJSON is the custom marshaler for UpgradeOperationHistoricalStatusInfo. -func (uohsi UpgradeOperationHistoricalStatusInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// UpgradeOperationHistoricalStatusInfoProperties describes each OS upgrade on the Virtual Machine Scale -// Set. -type UpgradeOperationHistoricalStatusInfoProperties struct { - // RunningStatus - READ-ONLY; Information about the overall status of the upgrade operation. - RunningStatus *UpgradeOperationHistoryStatus `json:"runningStatus,omitempty"` - // Progress - READ-ONLY; Counts of the VMs in each state. - Progress *RollingUpgradeProgressInfo `json:"progress,omitempty"` - // Error - READ-ONLY; Error Details for this upgrade if there are any. - Error *APIError `json:"error,omitempty"` - // StartedBy - READ-ONLY; Invoker of the Upgrade Operation. Possible values include: 'UpgradeOperationInvokerUnknown', 'UpgradeOperationInvokerUser', 'UpgradeOperationInvokerPlatform' - StartedBy UpgradeOperationInvoker `json:"startedBy,omitempty"` - // TargetImageReference - READ-ONLY; Image Reference details - TargetImageReference *ImageReference `json:"targetImageReference,omitempty"` - // RollbackInfo - READ-ONLY; Information about OS rollback if performed - RollbackInfo *RollbackStatusInfo `json:"rollbackInfo,omitempty"` -} - -// MarshalJSON is the custom marshaler for UpgradeOperationHistoricalStatusInfoProperties. -func (uohsip UpgradeOperationHistoricalStatusInfoProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// UpgradeOperationHistoryStatus information about the current running state of the overall upgrade. -type UpgradeOperationHistoryStatus struct { - // Code - READ-ONLY; Code indicating the current status of the upgrade. Possible values include: 'UpgradeStateRollingForward', 'UpgradeStateCancelled', 'UpgradeStateCompleted', 'UpgradeStateFaulted' - Code UpgradeState `json:"code,omitempty"` - // StartTime - READ-ONLY; Start time of the upgrade. - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - READ-ONLY; End time of the upgrade. - EndTime *date.Time `json:"endTime,omitempty"` -} - -// MarshalJSON is the custom marshaler for UpgradeOperationHistoryStatus. -func (uohs UpgradeOperationHistoryStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// UpgradePolicy describes an upgrade policy - automatic, manual, or rolling. -type UpgradePolicy struct { - // Mode - Specifies the mode of an upgrade to virtual machines in the scale set.

      Possible values are:

      **Manual** - You control the application of updates to virtual machines in the scale set. You do this by using the manualUpgrade action.

      **Automatic** - All virtual machines in the scale set are automatically updated at the same time. Possible values include: 'Automatic', 'Manual', 'Rolling' - Mode UpgradeMode `json:"mode,omitempty"` - // RollingUpgradePolicy - The configuration parameters used while performing a rolling upgrade. - RollingUpgradePolicy *RollingUpgradePolicy `json:"rollingUpgradePolicy,omitempty"` - // AutomaticOSUpgradePolicy - Configuration parameters used for performing automatic OS Upgrade. - AutomaticOSUpgradePolicy *AutomaticOSUpgradePolicy `json:"automaticOSUpgradePolicy,omitempty"` -} - -// Usage describes Compute Resource Usage. -type Usage struct { - // Unit - An enum describing the unit of usage measurement. - Unit *string `json:"unit,omitempty"` - // CurrentValue - The current usage of the resource. - CurrentValue *int32 `json:"currentValue,omitempty"` - // Limit - The maximum permitted usage of the resource. - Limit *int64 `json:"limit,omitempty"` - // Name - The name of the type of usage. - Name *UsageName `json:"name,omitempty"` -} - -// UsageName the Usage Names. -type UsageName struct { - // Value - The name of the resource. - Value *string `json:"value,omitempty"` - // LocalizedValue - The localized name of the resource. - LocalizedValue *string `json:"localizedValue,omitempty"` -} - -// VaultCertificate describes a single certificate reference in a Key Vault, and where the certificate -// should reside on the VM. -type VaultCertificate struct { - // CertificateURL - This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8:

      {
      "data":"",
      "dataType":"pfx",
      "password":""
      } - CertificateURL *string `json:"certificateUrl,omitempty"` - // CertificateStore - For Windows VMs, specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified certificate store is implicitly in the LocalMachine account.

      For Linux VMs, the certificate file is placed under the /var/lib/waagent directory, with the file name <UppercaseThumbprint>.crt for the X509 certificate file and <UppercaseThumbprint>.prv for private key. Both of these files are .pem formatted. - CertificateStore *string `json:"certificateStore,omitempty"` -} - -// VaultSecretGroup describes a set of certificates which are all in the same Key Vault. -type VaultSecretGroup struct { - // SourceVault - The relative URL of the Key Vault containing all of the certificates in VaultCertificates. - SourceVault *SubResource `json:"sourceVault,omitempty"` - // VaultCertificates - The list of key vault references in SourceVault which contain certificates. - VaultCertificates *[]VaultCertificate `json:"vaultCertificates,omitempty"` -} - -// VirtualHardDisk describes the uri of a disk. -type VirtualHardDisk struct { - // URI - Specifies the virtual hard disk's uri. - URI *string `json:"uri,omitempty"` -} - -// VirtualMachine describes a Virtual Machine. -type VirtualMachine struct { - autorest.Response `json:"-"` - // Plan - Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. - Plan *Plan `json:"plan,omitempty"` - *VirtualMachineProperties `json:"properties,omitempty"` - // Resources - READ-ONLY; The virtual machine child extension resources. - Resources *[]VirtualMachineExtension `json:"resources,omitempty"` - // Identity - The identity of the virtual machine, if configured. - Identity *VirtualMachineIdentity `json:"identity,omitempty"` - // Zones - The virtual machine zones. - Zones *[]string `json:"zones,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachine. -func (VM VirtualMachine) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if VM.Plan != nil { - objectMap["plan"] = VM.Plan - } - if VM.VirtualMachineProperties != nil { - objectMap["properties"] = VM.VirtualMachineProperties - } - if VM.Identity != nil { - objectMap["identity"] = VM.Identity - } - if VM.Zones != nil { - objectMap["zones"] = VM.Zones - } - if VM.Location != nil { - objectMap["location"] = VM.Location - } - if VM.Tags != nil { - objectMap["tags"] = VM.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachine struct. -func (VM *VirtualMachine) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "plan": - if v != nil { - var plan Plan - err = json.Unmarshal(*v, &plan) - if err != nil { - return err - } - VM.Plan = &plan - } - case "properties": - if v != nil { - var virtualMachineProperties VirtualMachineProperties - err = json.Unmarshal(*v, &virtualMachineProperties) - if err != nil { - return err - } - VM.VirtualMachineProperties = &virtualMachineProperties - } - case "resources": - if v != nil { - var resources []VirtualMachineExtension - err = json.Unmarshal(*v, &resources) - if err != nil { - return err - } - VM.Resources = &resources - } - case "identity": - if v != nil { - var identity VirtualMachineIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - VM.Identity = &identity - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - VM.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - VM.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - VM.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - VM.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - VM.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - VM.Tags = tags - } - } - } - - return nil -} - -// VirtualMachineAgentInstanceView the instance view of the VM Agent running on the virtual machine. -type VirtualMachineAgentInstanceView struct { - // VMAgentVersion - The VM Agent full version. - VMAgentVersion *string `json:"vmAgentVersion,omitempty"` - // ExtensionHandlers - The virtual machine extension handler instance view. - ExtensionHandlers *[]VirtualMachineExtensionHandlerInstanceView `json:"extensionHandlers,omitempty"` - // Statuses - The resource status information. - Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` -} - -// VirtualMachineCaptureParameters capture Virtual Machine parameters. -type VirtualMachineCaptureParameters struct { - // VhdPrefix - The captured virtual hard disk's name prefix. - VhdPrefix *string `json:"vhdPrefix,omitempty"` - // DestinationContainerName - The destination container name. - DestinationContainerName *string `json:"destinationContainerName,omitempty"` - // OverwriteVhds - Specifies whether to overwrite the destination virtual hard disk, in case of conflict. - OverwriteVhds *bool `json:"overwriteVhds,omitempty"` -} - -// VirtualMachineCaptureResult output of virtual machine capture operation. -type VirtualMachineCaptureResult struct { - autorest.Response `json:"-"` - // Schema - READ-ONLY; the schema of the captured virtual machine - Schema *string `json:"$schema,omitempty"` - // ContentVersion - READ-ONLY; the version of the content - ContentVersion *string `json:"contentVersion,omitempty"` - // Parameters - READ-ONLY; parameters of the captured virtual machine - Parameters interface{} `json:"parameters,omitempty"` - // Resources - READ-ONLY; a list of resource items of the captured virtual machine - Resources *[]interface{} `json:"resources,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineCaptureResult. -func (vmcr VirtualMachineCaptureResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmcr.ID != nil { - objectMap["id"] = vmcr.ID - } - return json.Marshal(objectMap) -} - -// VirtualMachineExtension describes a Virtual Machine Extension. -type VirtualMachineExtension struct { - autorest.Response `json:"-"` - *VirtualMachineExtensionProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineExtension. -func (vme VirtualMachineExtension) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vme.VirtualMachineExtensionProperties != nil { - objectMap["properties"] = vme.VirtualMachineExtensionProperties - } - if vme.Location != nil { - objectMap["location"] = vme.Location - } - if vme.Tags != nil { - objectMap["tags"] = vme.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineExtension struct. -func (vme *VirtualMachineExtension) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualMachineExtensionProperties VirtualMachineExtensionProperties - err = json.Unmarshal(*v, &virtualMachineExtensionProperties) - if err != nil { - return err - } - vme.VirtualMachineExtensionProperties = &virtualMachineExtensionProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vme.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vme.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vme.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vme.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vme.Tags = tags - } - } - } - - return nil -} - -// VirtualMachineExtensionHandlerInstanceView the instance view of a virtual machine extension handler. -type VirtualMachineExtensionHandlerInstanceView struct { - // Type - Specifies the type of the extension; an example is "CustomScriptExtension". - Type *string `json:"type,omitempty"` - // TypeHandlerVersion - Specifies the version of the script handler. - TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` - // Status - The extension handler status. - Status *InstanceViewStatus `json:"status,omitempty"` -} - -// VirtualMachineExtensionImage describes a Virtual Machine Extension Image. -type VirtualMachineExtensionImage struct { - autorest.Response `json:"-"` - *VirtualMachineExtensionImageProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineExtensionImage. -func (vmei VirtualMachineExtensionImage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmei.VirtualMachineExtensionImageProperties != nil { - objectMap["properties"] = vmei.VirtualMachineExtensionImageProperties - } - if vmei.Location != nil { - objectMap["location"] = vmei.Location - } - if vmei.Tags != nil { - objectMap["tags"] = vmei.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineExtensionImage struct. -func (vmei *VirtualMachineExtensionImage) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualMachineExtensionImageProperties VirtualMachineExtensionImageProperties - err = json.Unmarshal(*v, &virtualMachineExtensionImageProperties) - if err != nil { - return err - } - vmei.VirtualMachineExtensionImageProperties = &virtualMachineExtensionImageProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmei.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmei.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vmei.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vmei.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vmei.Tags = tags - } - } - } - - return nil -} - -// VirtualMachineExtensionImageProperties describes the properties of a Virtual Machine Extension Image. -type VirtualMachineExtensionImageProperties struct { - // OperatingSystem - The operating system this extension supports. - OperatingSystem *string `json:"operatingSystem,omitempty"` - // ComputeRole - The type of role (IaaS or PaaS) this extension supports. - ComputeRole *string `json:"computeRole,omitempty"` - // HandlerSchema - The schema defined by publisher, where extension consumers should provide settings in a matching schema. - HandlerSchema *string `json:"handlerSchema,omitempty"` - // VMScaleSetEnabled - Whether the extension can be used on xRP VMScaleSets. By default existing extensions are usable on scalesets, but there might be cases where a publisher wants to explicitly indicate the extension is only enabled for CRP VMs but not VMSS. - VMScaleSetEnabled *bool `json:"vmScaleSetEnabled,omitempty"` - // SupportsMultipleExtensions - Whether the handler can support multiple extensions. - SupportsMultipleExtensions *bool `json:"supportsMultipleExtensions,omitempty"` -} - -// VirtualMachineExtensionInstanceView the instance view of a virtual machine extension. -type VirtualMachineExtensionInstanceView struct { - // Name - The virtual machine extension name. - Name *string `json:"name,omitempty"` - // Type - Specifies the type of the extension; an example is "CustomScriptExtension". - Type *string `json:"type,omitempty"` - // TypeHandlerVersion - Specifies the version of the script handler. - TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` - // Substatuses - The resource status information. - Substatuses *[]InstanceViewStatus `json:"substatuses,omitempty"` - // Statuses - The resource status information. - Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` -} - -// VirtualMachineExtensionProperties describes the properties of a Virtual Machine Extension. -type VirtualMachineExtensionProperties struct { - // ForceUpdateTag - How the extension handler should be forced to update even if the extension configuration has not changed. - ForceUpdateTag *string `json:"forceUpdateTag,omitempty"` - // Publisher - The name of the extension handler publisher. - Publisher *string `json:"publisher,omitempty"` - // Type - Specifies the type of the extension; an example is "CustomScriptExtension". - Type *string `json:"type,omitempty"` - // TypeHandlerVersion - Specifies the version of the script handler. - TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` - // AutoUpgradeMinorVersion - Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. - AutoUpgradeMinorVersion *bool `json:"autoUpgradeMinorVersion,omitempty"` - // Settings - Json formatted public settings for the extension. - Settings interface{} `json:"settings,omitempty"` - // ProtectedSettings - The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. - ProtectedSettings interface{} `json:"protectedSettings,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. - ProvisioningState *string `json:"provisioningState,omitempty"` - // InstanceView - The virtual machine extension instance view. - InstanceView *VirtualMachineExtensionInstanceView `json:"instanceView,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineExtensionProperties. -func (vmep VirtualMachineExtensionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmep.ForceUpdateTag != nil { - objectMap["forceUpdateTag"] = vmep.ForceUpdateTag - } - if vmep.Publisher != nil { - objectMap["publisher"] = vmep.Publisher - } - if vmep.Type != nil { - objectMap["type"] = vmep.Type - } - if vmep.TypeHandlerVersion != nil { - objectMap["typeHandlerVersion"] = vmep.TypeHandlerVersion - } - if vmep.AutoUpgradeMinorVersion != nil { - objectMap["autoUpgradeMinorVersion"] = vmep.AutoUpgradeMinorVersion - } - if vmep.Settings != nil { - objectMap["settings"] = vmep.Settings - } - if vmep.ProtectedSettings != nil { - objectMap["protectedSettings"] = vmep.ProtectedSettings - } - if vmep.InstanceView != nil { - objectMap["instanceView"] = vmep.InstanceView - } - return json.Marshal(objectMap) -} - -// VirtualMachineExtensionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualMachineExtensionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineExtensionsClient) (VirtualMachineExtension, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineExtensionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineExtensionsCreateOrUpdateFuture.Result. -func (future *VirtualMachineExtensionsCreateOrUpdateFuture) result(client VirtualMachineExtensionsClient) (vme VirtualMachineExtension, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vme.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineExtensionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vme.Response.Response, err = future.GetResult(sender); err == nil && vme.Response.Response.StatusCode != http.StatusNoContent { - vme, err = client.CreateOrUpdateResponder(vme.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsCreateOrUpdateFuture", "Result", vme.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachineExtensionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineExtensionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineExtensionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineExtensionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineExtensionsDeleteFuture.Result. -func (future *VirtualMachineExtensionsDeleteFuture) result(client VirtualMachineExtensionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineExtensionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineExtensionsListResult the List Extension operation response -type VirtualMachineExtensionsListResult struct { - autorest.Response `json:"-"` - // Value - The list of extensions - Value *[]VirtualMachineExtension `json:"value,omitempty"` -} - -// VirtualMachineExtensionsUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineExtensionsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineExtensionsClient) (VirtualMachineExtension, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineExtensionsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineExtensionsUpdateFuture.Result. -func (future *VirtualMachineExtensionsUpdateFuture) result(client VirtualMachineExtensionsClient) (vme VirtualMachineExtension, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vme.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineExtensionsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vme.Response.Response, err = future.GetResult(sender); err == nil && vme.Response.Response.StatusCode != http.StatusNoContent { - vme, err = client.UpdateResponder(vme.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsUpdateFuture", "Result", vme.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachineExtensionUpdate describes a Virtual Machine Extension. -type VirtualMachineExtensionUpdate struct { - *VirtualMachineExtensionUpdateProperties `json:"properties,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineExtensionUpdate. -func (vmeu VirtualMachineExtensionUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmeu.VirtualMachineExtensionUpdateProperties != nil { - objectMap["properties"] = vmeu.VirtualMachineExtensionUpdateProperties - } - if vmeu.Tags != nil { - objectMap["tags"] = vmeu.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineExtensionUpdate struct. -func (vmeu *VirtualMachineExtensionUpdate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualMachineExtensionUpdateProperties VirtualMachineExtensionUpdateProperties - err = json.Unmarshal(*v, &virtualMachineExtensionUpdateProperties) - if err != nil { - return err - } - vmeu.VirtualMachineExtensionUpdateProperties = &virtualMachineExtensionUpdateProperties - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vmeu.Tags = tags - } - } - } - - return nil -} - -// VirtualMachineExtensionUpdateProperties describes the properties of a Virtual Machine Extension. -type VirtualMachineExtensionUpdateProperties struct { - // ForceUpdateTag - How the extension handler should be forced to update even if the extension configuration has not changed. - ForceUpdateTag *string `json:"forceUpdateTag,omitempty"` - // Publisher - The name of the extension handler publisher. - Publisher *string `json:"publisher,omitempty"` - // Type - Specifies the type of the extension; an example is "CustomScriptExtension". - Type *string `json:"type,omitempty"` - // TypeHandlerVersion - Specifies the version of the script handler. - TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` - // AutoUpgradeMinorVersion - Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. - AutoUpgradeMinorVersion *bool `json:"autoUpgradeMinorVersion,omitempty"` - // Settings - Json formatted public settings for the extension. - Settings interface{} `json:"settings,omitempty"` - // ProtectedSettings - The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. - ProtectedSettings interface{} `json:"protectedSettings,omitempty"` -} - -// VirtualMachineHealthStatus the health status of the VM. -type VirtualMachineHealthStatus struct { - // Status - READ-ONLY; The health status information for the VM. - Status *InstanceViewStatus `json:"status,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineHealthStatus. -func (vmhs VirtualMachineHealthStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachineIdentity identity for the virtual machine. -type VirtualMachineIdentity struct { - // PrincipalID - READ-ONLY; The principal id of virtual machine identity. This property will only be provided for a system assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; The tenant id associated with the virtual machine. This property will only be provided for a system assigned identity. - TenantID *string `json:"tenantId,omitempty"` - // Type - The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. Possible values include: 'ResourceIdentityTypeSystemAssigned', 'ResourceIdentityTypeUserAssigned', 'ResourceIdentityTypeSystemAssignedUserAssigned', 'ResourceIdentityTypeNone' - Type ResourceIdentityType `json:"type,omitempty"` - // UserAssignedIdentities - The list of user identities associated with the Virtual Machine. 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]*VirtualMachineIdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineIdentity. -func (vmi VirtualMachineIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmi.Type != "" { - objectMap["type"] = vmi.Type - } - if vmi.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = vmi.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// VirtualMachineIdentityUserAssignedIdentitiesValue ... -type VirtualMachineIdentityUserAssignedIdentitiesValue struct { - // PrincipalID - READ-ONLY; The principal id of user assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; The client id of user assigned identity. - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineIdentityUserAssignedIdentitiesValue. -func (vmiAiv VirtualMachineIdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachineImage describes a Virtual Machine Image. -type VirtualMachineImage struct { - autorest.Response `json:"-"` - *VirtualMachineImageProperties `json:"properties,omitempty"` - // Name - The name of the resource. - Name *string `json:"name,omitempty"` - // Location - The supported Azure location of the resource. - Location *string `json:"location,omitempty"` - // Tags - Specifies the tags that are assigned to the virtual machine. For more information about using tags, see [Using tags to organize your Azure resources](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-using-tags.md). - Tags map[string]*string `json:"tags"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineImage. -func (vmi VirtualMachineImage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmi.VirtualMachineImageProperties != nil { - objectMap["properties"] = vmi.VirtualMachineImageProperties - } - if vmi.Name != nil { - objectMap["name"] = vmi.Name - } - if vmi.Location != nil { - objectMap["location"] = vmi.Location - } - if vmi.Tags != nil { - objectMap["tags"] = vmi.Tags - } - if vmi.ID != nil { - objectMap["id"] = vmi.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineImage struct. -func (vmi *VirtualMachineImage) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualMachineImageProperties VirtualMachineImageProperties - err = json.Unmarshal(*v, &virtualMachineImageProperties) - if err != nil { - return err - } - vmi.VirtualMachineImageProperties = &virtualMachineImageProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmi.Name = &name - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vmi.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vmi.Tags = tags - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmi.ID = &ID - } - } - } - - return nil -} - -// VirtualMachineImageProperties describes the properties of a Virtual Machine Image. -type VirtualMachineImageProperties struct { - Plan *PurchasePlan `json:"plan,omitempty"` - OsDiskImage *OSDiskImage `json:"osDiskImage,omitempty"` - DataDiskImages *[]DataDiskImage `json:"dataDiskImages,omitempty"` - AutomaticOSUpgradeProperties *AutomaticOSUpgradeProperties `json:"automaticOSUpgradeProperties,omitempty"` -} - -// VirtualMachineImageResource virtual machine image resource information. -type VirtualMachineImageResource struct { - // Name - The name of the resource. - Name *string `json:"name,omitempty"` - // Location - The supported Azure location of the resource. - Location *string `json:"location,omitempty"` - // Tags - Specifies the tags that are assigned to the virtual machine. For more information about using tags, see [Using tags to organize your Azure resources](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-using-tags.md). - Tags map[string]*string `json:"tags"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineImageResource. -func (vmir VirtualMachineImageResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmir.Name != nil { - objectMap["name"] = vmir.Name - } - if vmir.Location != nil { - objectMap["location"] = vmir.Location - } - if vmir.Tags != nil { - objectMap["tags"] = vmir.Tags - } - if vmir.ID != nil { - objectMap["id"] = vmir.ID - } - return json.Marshal(objectMap) -} - -// VirtualMachineInstanceView the instance view of a virtual machine. -type VirtualMachineInstanceView struct { - autorest.Response `json:"-"` - // PlatformUpdateDomain - Specifies the update domain of the virtual machine. - PlatformUpdateDomain *int32 `json:"platformUpdateDomain,omitempty"` - // PlatformFaultDomain - Specifies the fault domain of the virtual machine. - PlatformFaultDomain *int32 `json:"platformFaultDomain,omitempty"` - // ComputerName - The computer name assigned to the virtual machine. - ComputerName *string `json:"computerName,omitempty"` - // OsName - The Operating System running on the virtual machine. - OsName *string `json:"osName,omitempty"` - // OsVersion - The version of Operating System running on the virtual machine. - OsVersion *string `json:"osVersion,omitempty"` - // RdpThumbPrint - The Remote desktop certificate thumbprint. - RdpThumbPrint *string `json:"rdpThumbPrint,omitempty"` - // VMAgent - The VM Agent running on the virtual machine. - VMAgent *VirtualMachineAgentInstanceView `json:"vmAgent,omitempty"` - // MaintenanceRedeployStatus - The Maintenance Operation status on the virtual machine. - MaintenanceRedeployStatus *MaintenanceRedeployStatus `json:"maintenanceRedeployStatus,omitempty"` - // Disks - The virtual machine disk information. - Disks *[]DiskInstanceView `json:"disks,omitempty"` - // Extensions - The extensions information. - Extensions *[]VirtualMachineExtensionInstanceView `json:"extensions,omitempty"` - // BootDiagnostics - Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status.

      You can easily view the output of your console log.

      Azure also enables you to see a screenshot of the VM from the hypervisor. - BootDiagnostics *BootDiagnosticsInstanceView `json:"bootDiagnostics,omitempty"` - // Statuses - The resource status information. - Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` -} - -// VirtualMachineListResult the List Virtual Machine operation response. -type VirtualMachineListResult struct { - autorest.Response `json:"-"` - // Value - The list of virtual machines. - Value *[]VirtualMachine `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of VMs. Call ListNext() with this URI to fetch the next page of Virtual Machines. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualMachineListResultIterator provides access to a complete listing of VirtualMachine values. -type VirtualMachineListResultIterator struct { - i int - page VirtualMachineListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualMachineListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualMachineListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualMachineListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualMachineListResultIterator) Response() VirtualMachineListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualMachineListResultIterator) Value() VirtualMachine { - if !iter.page.NotDone() { - return VirtualMachine{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualMachineListResultIterator type. -func NewVirtualMachineListResultIterator(page VirtualMachineListResultPage) VirtualMachineListResultIterator { - return VirtualMachineListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vmlr VirtualMachineListResult) IsEmpty() bool { - return vmlr.Value == nil || len(*vmlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vmlr VirtualMachineListResult) hasNextLink() bool { - return vmlr.NextLink != nil && len(*vmlr.NextLink) != 0 -} - -// virtualMachineListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vmlr VirtualMachineListResult) virtualMachineListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vmlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vmlr.NextLink))) -} - -// VirtualMachineListResultPage contains a page of VirtualMachine values. -type VirtualMachineListResultPage struct { - fn func(context.Context, VirtualMachineListResult) (VirtualMachineListResult, error) - vmlr VirtualMachineListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vmlr) - if err != nil { - return err - } - page.vmlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineListResultPage) NotDone() bool { - return !page.vmlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineListResultPage) Response() VirtualMachineListResult { - return page.vmlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineListResultPage) Values() []VirtualMachine { - if page.vmlr.IsEmpty() { - return nil - } - return *page.vmlr.Value -} - -// Creates a new instance of the VirtualMachineListResultPage type. -func NewVirtualMachineListResultPage(cur VirtualMachineListResult, getNextPage func(context.Context, VirtualMachineListResult) (VirtualMachineListResult, error)) VirtualMachineListResultPage { - return VirtualMachineListResultPage{ - fn: getNextPage, - vmlr: cur, - } -} - -// VirtualMachineProperties describes the properties of a Virtual Machine. -type VirtualMachineProperties struct { - // HardwareProfile - Specifies the hardware settings for the virtual machine. - HardwareProfile *HardwareProfile `json:"hardwareProfile,omitempty"` - // StorageProfile - Specifies the storage settings for the virtual machine disks. - StorageProfile *StorageProfile `json:"storageProfile,omitempty"` - // AdditionalCapabilities - Specifies additional capabilities enabled or disabled on the virtual machine. - AdditionalCapabilities *AdditionalCapabilities `json:"additionalCapabilities,omitempty"` - // OsProfile - Specifies the operating system settings for the virtual machine. - OsProfile *OSProfile `json:"osProfile,omitempty"` - // NetworkProfile - Specifies the network interfaces of the virtual machine. - NetworkProfile *NetworkProfile `json:"networkProfile,omitempty"` - // DiagnosticsProfile - Specifies the boot diagnostic settings state.

      Minimum api-version: 2015-06-15. - DiagnosticsProfile *DiagnosticsProfile `json:"diagnosticsProfile,omitempty"` - // AvailabilitySet - Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see [Manage the availability of virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).

      For more information on Azure planned maintenance, see [Planned maintenance for virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)

      Currently, a VM can only be added to availability set at creation time. An existing VM cannot be added to an availability set. - AvailabilitySet *SubResource `json:"availabilitySet,omitempty"` - // ProximityPlacementGroup - Specifies information about the proximity placement group that the virtual machine should be assigned to.

      Minimum api-version: 2018-04-01. - ProximityPlacementGroup *SubResource `json:"proximityPlacementGroup,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. - ProvisioningState *string `json:"provisioningState,omitempty"` - // InstanceView - READ-ONLY; The virtual machine instance view. - InstanceView *VirtualMachineInstanceView `json:"instanceView,omitempty"` - // LicenseType - Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system.

      Possible values are:

      Windows_Client

      Windows_Server

      If this element is included in a request for an update, the value must match the initial value. This value cannot be updated.

      For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)

      Minimum api-version: 2015-06-15 - LicenseType *string `json:"licenseType,omitempty"` - // VMID - READ-ONLY; Specifies the VM unique ID which is a 128-bits identifier that is encoded and stored in all Azure IaaS VMs SMBIOS and can be read using platform BIOS commands. - VMID *string `json:"vmId,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineProperties. -func (vmp VirtualMachineProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmp.HardwareProfile != nil { - objectMap["hardwareProfile"] = vmp.HardwareProfile - } - if vmp.StorageProfile != nil { - objectMap["storageProfile"] = vmp.StorageProfile - } - if vmp.AdditionalCapabilities != nil { - objectMap["additionalCapabilities"] = vmp.AdditionalCapabilities - } - if vmp.OsProfile != nil { - objectMap["osProfile"] = vmp.OsProfile - } - if vmp.NetworkProfile != nil { - objectMap["networkProfile"] = vmp.NetworkProfile - } - if vmp.DiagnosticsProfile != nil { - objectMap["diagnosticsProfile"] = vmp.DiagnosticsProfile - } - if vmp.AvailabilitySet != nil { - objectMap["availabilitySet"] = vmp.AvailabilitySet - } - if vmp.ProximityPlacementGroup != nil { - objectMap["proximityPlacementGroup"] = vmp.ProximityPlacementGroup - } - if vmp.LicenseType != nil { - objectMap["licenseType"] = vmp.LicenseType - } - return json.Marshal(objectMap) -} - -// VirtualMachineReimageParameters parameters for Reimaging Virtual Machine. NOTE: Virtual Machine OS disk -// will always be reimaged -type VirtualMachineReimageParameters struct { - // TempDisk - Specifies whether to reimage temp disk. Default value: false. Note: This temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS disk. - TempDisk *bool `json:"tempDisk,omitempty"` -} - -// VirtualMachineScaleSet describes a Virtual Machine Scale Set. -type VirtualMachineScaleSet struct { - autorest.Response `json:"-"` - // Sku - The virtual machine scale set sku. - Sku *Sku `json:"sku,omitempty"` - // Plan - Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. - Plan *Plan `json:"plan,omitempty"` - *VirtualMachineScaleSetProperties `json:"properties,omitempty"` - // Identity - The identity of the virtual machine scale set, if configured. - Identity *VirtualMachineScaleSetIdentity `json:"identity,omitempty"` - // Zones - The virtual machine scale set zones. NOTE: Availability zones can only be set when you create the scale set. - Zones *[]string `json:"zones,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSet. -func (vmss VirtualMachineScaleSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmss.Sku != nil { - objectMap["sku"] = vmss.Sku - } - if vmss.Plan != nil { - objectMap["plan"] = vmss.Plan - } - if vmss.VirtualMachineScaleSetProperties != nil { - objectMap["properties"] = vmss.VirtualMachineScaleSetProperties - } - if vmss.Identity != nil { - objectMap["identity"] = vmss.Identity - } - if vmss.Zones != nil { - objectMap["zones"] = vmss.Zones - } - if vmss.Location != nil { - objectMap["location"] = vmss.Location - } - if vmss.Tags != nil { - objectMap["tags"] = vmss.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSet struct. -func (vmss *VirtualMachineScaleSet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku Sku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - vmss.Sku = &sku - } - case "plan": - if v != nil { - var plan Plan - err = json.Unmarshal(*v, &plan) - if err != nil { - return err - } - vmss.Plan = &plan - } - case "properties": - if v != nil { - var virtualMachineScaleSetProperties VirtualMachineScaleSetProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetProperties) - if err != nil { - return err - } - vmss.VirtualMachineScaleSetProperties = &virtualMachineScaleSetProperties - } - case "identity": - if v != nil { - var identity VirtualMachineScaleSetIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - vmss.Identity = &identity - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - vmss.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmss.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmss.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vmss.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vmss.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vmss.Tags = tags - } - } - } - - return nil -} - -// VirtualMachineScaleSetDataDisk describes a virtual machine scale set data disk. -type VirtualMachineScaleSetDataDisk struct { - // Name - The disk name. - Name *string `json:"name,omitempty"` - // Lun - Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. - Lun *int32 `json:"lun,omitempty"` - // Caching - Specifies the caching requirements.

      Possible values are:

      **None**

      **ReadOnly**

      **ReadWrite**

      Default: **None for Standard storage. ReadOnly for Premium storage**. Possible values include: 'CachingTypesNone', 'CachingTypesReadOnly', 'CachingTypesReadWrite' - Caching CachingTypes `json:"caching,omitempty"` - // WriteAcceleratorEnabled - Specifies whether writeAccelerator should be enabled or disabled on the disk. - WriteAcceleratorEnabled *bool `json:"writeAcceleratorEnabled,omitempty"` - // CreateOption - The create option. Possible values include: 'DiskCreateOptionTypesFromImage', 'DiskCreateOptionTypesEmpty', 'DiskCreateOptionTypesAttach' - CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` - // DiskSizeGB - Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image.

      This value cannot be larger than 1023 GB - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // ManagedDisk - The managed disk parameters. - ManagedDisk *VirtualMachineScaleSetManagedDiskParameters `json:"managedDisk,omitempty"` -} - -// VirtualMachineScaleSetExtension describes a Virtual Machine Scale Set Extension. -type VirtualMachineScaleSetExtension struct { - autorest.Response `json:"-"` - // Name - The name of the extension. - Name *string `json:"name,omitempty"` - *VirtualMachineScaleSetExtensionProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetExtension. -func (vmsse VirtualMachineScaleSetExtension) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmsse.Name != nil { - objectMap["name"] = vmsse.Name - } - if vmsse.VirtualMachineScaleSetExtensionProperties != nil { - objectMap["properties"] = vmsse.VirtualMachineScaleSetExtensionProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetExtension struct. -func (vmsse *VirtualMachineScaleSetExtension) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmsse.Name = &name - } - case "properties": - if v != nil { - var virtualMachineScaleSetExtensionProperties VirtualMachineScaleSetExtensionProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetExtensionProperties) - if err != nil { - return err - } - vmsse.VirtualMachineScaleSetExtensionProperties = &virtualMachineScaleSetExtensionProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmsse.ID = &ID - } - } - } - - return nil -} - -// VirtualMachineScaleSetExtensionListResult the List VM scale set extension operation response. -type VirtualMachineScaleSetExtensionListResult struct { - autorest.Response `json:"-"` - // Value - The list of VM scale set extensions. - Value *[]VirtualMachineScaleSetExtension `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of VM scale set extensions. Call ListNext() with this to fetch the next page of VM scale set extensions. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualMachineScaleSetExtensionListResultIterator provides access to a complete listing of -// VirtualMachineScaleSetExtension values. -type VirtualMachineScaleSetExtensionListResultIterator struct { - i int - page VirtualMachineScaleSetExtensionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualMachineScaleSetExtensionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetExtensionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualMachineScaleSetExtensionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualMachineScaleSetExtensionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualMachineScaleSetExtensionListResultIterator) Response() VirtualMachineScaleSetExtensionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualMachineScaleSetExtensionListResultIterator) Value() VirtualMachineScaleSetExtension { - if !iter.page.NotDone() { - return VirtualMachineScaleSetExtension{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualMachineScaleSetExtensionListResultIterator type. -func NewVirtualMachineScaleSetExtensionListResultIterator(page VirtualMachineScaleSetExtensionListResultPage) VirtualMachineScaleSetExtensionListResultIterator { - return VirtualMachineScaleSetExtensionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vmsselr VirtualMachineScaleSetExtensionListResult) IsEmpty() bool { - return vmsselr.Value == nil || len(*vmsselr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vmsselr VirtualMachineScaleSetExtensionListResult) hasNextLink() bool { - return vmsselr.NextLink != nil && len(*vmsselr.NextLink) != 0 -} - -// virtualMachineScaleSetExtensionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vmsselr VirtualMachineScaleSetExtensionListResult) virtualMachineScaleSetExtensionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vmsselr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vmsselr.NextLink))) -} - -// VirtualMachineScaleSetExtensionListResultPage contains a page of VirtualMachineScaleSetExtension values. -type VirtualMachineScaleSetExtensionListResultPage struct { - fn func(context.Context, VirtualMachineScaleSetExtensionListResult) (VirtualMachineScaleSetExtensionListResult, error) - vmsselr VirtualMachineScaleSetExtensionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetExtensionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetExtensionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vmsselr) - if err != nil { - return err - } - page.vmsselr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetExtensionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetExtensionListResultPage) NotDone() bool { - return !page.vmsselr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetExtensionListResultPage) Response() VirtualMachineScaleSetExtensionListResult { - return page.vmsselr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetExtensionListResultPage) Values() []VirtualMachineScaleSetExtension { - if page.vmsselr.IsEmpty() { - return nil - } - return *page.vmsselr.Value -} - -// Creates a new instance of the VirtualMachineScaleSetExtensionListResultPage type. -func NewVirtualMachineScaleSetExtensionListResultPage(cur VirtualMachineScaleSetExtensionListResult, getNextPage func(context.Context, VirtualMachineScaleSetExtensionListResult) (VirtualMachineScaleSetExtensionListResult, error)) VirtualMachineScaleSetExtensionListResultPage { - return VirtualMachineScaleSetExtensionListResultPage{ - fn: getNextPage, - vmsselr: cur, - } -} - -// VirtualMachineScaleSetExtensionProfile describes a virtual machine scale set extension profile. -type VirtualMachineScaleSetExtensionProfile struct { - // Extensions - The virtual machine scale set child extension resources. - Extensions *[]VirtualMachineScaleSetExtension `json:"extensions,omitempty"` -} - -// VirtualMachineScaleSetExtensionProperties describes the properties of a Virtual Machine Scale Set -// Extension. -type VirtualMachineScaleSetExtensionProperties struct { - // ForceUpdateTag - If a value is provided and is different from the previous value, the extension handler will be forced to update even if the extension configuration has not changed. - ForceUpdateTag *string `json:"forceUpdateTag,omitempty"` - // Publisher - The name of the extension handler publisher. - Publisher *string `json:"publisher,omitempty"` - // Type - Specifies the type of the extension; an example is "CustomScriptExtension". - Type *string `json:"type,omitempty"` - // TypeHandlerVersion - Specifies the version of the script handler. - TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` - // AutoUpgradeMinorVersion - Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. - AutoUpgradeMinorVersion *bool `json:"autoUpgradeMinorVersion,omitempty"` - // Settings - Json formatted public settings for the extension. - Settings interface{} `json:"settings,omitempty"` - // ProtectedSettings - The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. - ProtectedSettings interface{} `json:"protectedSettings,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. - ProvisioningState *string `json:"provisioningState,omitempty"` - // ProvisionAfterExtensions - Collection of extension names after which this extension needs to be provisioned. - ProvisionAfterExtensions *[]string `json:"provisionAfterExtensions,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetExtensionProperties. -func (vmssep VirtualMachineScaleSetExtensionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssep.ForceUpdateTag != nil { - objectMap["forceUpdateTag"] = vmssep.ForceUpdateTag - } - if vmssep.Publisher != nil { - objectMap["publisher"] = vmssep.Publisher - } - if vmssep.Type != nil { - objectMap["type"] = vmssep.Type - } - if vmssep.TypeHandlerVersion != nil { - objectMap["typeHandlerVersion"] = vmssep.TypeHandlerVersion - } - if vmssep.AutoUpgradeMinorVersion != nil { - objectMap["autoUpgradeMinorVersion"] = vmssep.AutoUpgradeMinorVersion - } - if vmssep.Settings != nil { - objectMap["settings"] = vmssep.Settings - } - if vmssep.ProtectedSettings != nil { - objectMap["protectedSettings"] = vmssep.ProtectedSettings - } - if vmssep.ProvisionAfterExtensions != nil { - objectMap["provisionAfterExtensions"] = vmssep.ProvisionAfterExtensions - } - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetExtensionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualMachineScaleSetExtensionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetExtensionsClient) (VirtualMachineScaleSetExtension, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetExtensionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetExtensionsCreateOrUpdateFuture.Result. -func (future *VirtualMachineScaleSetExtensionsCreateOrUpdateFuture) result(client VirtualMachineScaleSetExtensionsClient) (vmsse VirtualMachineScaleSetExtension, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vmsse.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetExtensionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vmsse.Response.Response, err = future.GetResult(sender); err == nil && vmsse.Response.Response.StatusCode != http.StatusNoContent { - vmsse, err = client.CreateOrUpdateResponder(vmsse.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsCreateOrUpdateFuture", "Result", vmsse.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachineScaleSetExtensionsDeleteFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualMachineScaleSetExtensionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetExtensionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetExtensionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetExtensionsDeleteFuture.Result. -func (future *VirtualMachineScaleSetExtensionsDeleteFuture) result(client VirtualMachineScaleSetExtensionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetExtensionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetIdentity identity for the virtual machine scale set. -type VirtualMachineScaleSetIdentity struct { - // PrincipalID - READ-ONLY; The principal id of virtual machine scale set identity. This property will only be provided for a system assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; The tenant id associated with the virtual machine scale set. This property will only be provided for a system assigned identity. - TenantID *string `json:"tenantId,omitempty"` - // Type - The type of identity used for the virtual machine scale set. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine scale set. Possible values include: 'ResourceIdentityTypeSystemAssigned', 'ResourceIdentityTypeUserAssigned', 'ResourceIdentityTypeSystemAssignedUserAssigned', 'ResourceIdentityTypeNone' - Type ResourceIdentityType `json:"type,omitempty"` - // UserAssignedIdentities - The list of user identities associated with the virtual machine scale set. 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]*VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetIdentity. -func (vmssi VirtualMachineScaleSetIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssi.Type != "" { - objectMap["type"] = vmssi.Type - } - if vmssi.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = vmssi.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue ... -type VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue struct { - // PrincipalID - READ-ONLY; The principal id of user assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; The client id of user assigned identity. - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue. -func (vmssiAiv VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetInstanceView the instance view of a virtual machine scale set. -type VirtualMachineScaleSetInstanceView struct { - autorest.Response `json:"-"` - // VirtualMachine - READ-ONLY; The instance view status summary for the virtual machine scale set. - VirtualMachine *VirtualMachineScaleSetInstanceViewStatusesSummary `json:"virtualMachine,omitempty"` - // Extensions - READ-ONLY; The extensions information. - Extensions *[]VirtualMachineScaleSetVMExtensionsSummary `json:"extensions,omitempty"` - // Statuses - The resource status information. - Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetInstanceView. -func (vmssiv VirtualMachineScaleSetInstanceView) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssiv.Statuses != nil { - objectMap["statuses"] = vmssiv.Statuses - } - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetInstanceViewStatusesSummary instance view statuses summary for virtual machines of -// a virtual machine scale set. -type VirtualMachineScaleSetInstanceViewStatusesSummary struct { - // StatusesSummary - READ-ONLY; The extensions information. - StatusesSummary *[]VirtualMachineStatusCodeCount `json:"statusesSummary,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetInstanceViewStatusesSummary. -func (vmssivss VirtualMachineScaleSetInstanceViewStatusesSummary) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetIPConfiguration describes a virtual machine scale set network profile's IP -// configuration. -type VirtualMachineScaleSetIPConfiguration struct { - // Name - The IP configuration name. - Name *string `json:"name,omitempty"` - *VirtualMachineScaleSetIPConfigurationProperties `json:"properties,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetIPConfiguration. -func (vmssic VirtualMachineScaleSetIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssic.Name != nil { - objectMap["name"] = vmssic.Name - } - if vmssic.VirtualMachineScaleSetIPConfigurationProperties != nil { - objectMap["properties"] = vmssic.VirtualMachineScaleSetIPConfigurationProperties - } - if vmssic.ID != nil { - objectMap["id"] = vmssic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetIPConfiguration struct. -func (vmssic *VirtualMachineScaleSetIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmssic.Name = &name - } - case "properties": - if v != nil { - var virtualMachineScaleSetIPConfigurationProperties VirtualMachineScaleSetIPConfigurationProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetIPConfigurationProperties) - if err != nil { - return err - } - vmssic.VirtualMachineScaleSetIPConfigurationProperties = &virtualMachineScaleSetIPConfigurationProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmssic.ID = &ID - } - } - } - - return nil -} - -// VirtualMachineScaleSetIPConfigurationProperties describes a virtual machine scale set network profile's -// IP configuration properties. -type VirtualMachineScaleSetIPConfigurationProperties struct { - // Subnet - Specifies the identifier of the subnet. - Subnet *APIEntityReference `json:"subnet,omitempty"` - // Primary - Specifies the primary network interface in case the virtual machine has more than 1 network interface. - Primary *bool `json:"primary,omitempty"` - // PublicIPAddressConfiguration - The publicIPAddressConfiguration. - PublicIPAddressConfiguration *VirtualMachineScaleSetPublicIPAddressConfiguration `json:"publicIPAddressConfiguration,omitempty"` - // PrivateIPAddressVersion - Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. Possible values include: 'IPv4', 'IPv6' - PrivateIPAddressVersion IPVersion `json:"privateIPAddressVersion,omitempty"` - // ApplicationGatewayBackendAddressPools - Specifies an array of references to backend address pools of application gateways. A scale set can reference backend address pools of multiple application gateways. Multiple scale sets cannot use the same application gateway. - ApplicationGatewayBackendAddressPools *[]SubResource `json:"applicationGatewayBackendAddressPools,omitempty"` - // ApplicationSecurityGroups - Specifies an array of references to application security group. - ApplicationSecurityGroups *[]SubResource `json:"applicationSecurityGroups,omitempty"` - // LoadBalancerBackendAddressPools - Specifies an array of references to backend address pools of load balancers. A scale set can reference backend address pools of one public and one internal load balancer. Multiple scale sets cannot use the same load balancer. - LoadBalancerBackendAddressPools *[]SubResource `json:"loadBalancerBackendAddressPools,omitempty"` - // LoadBalancerInboundNatPools - Specifies an array of references to inbound Nat pools of the load balancers. A scale set can reference inbound nat pools of one public and one internal load balancer. Multiple scale sets cannot use the same load balancer - LoadBalancerInboundNatPools *[]SubResource `json:"loadBalancerInboundNatPools,omitempty"` -} - -// VirtualMachineScaleSetIPTag contains the IP tag associated with the public IP address. -type VirtualMachineScaleSetIPTag struct { - // IPTagType - IP tag type. Example: FirstPartyUsage. - IPTagType *string `json:"ipTagType,omitempty"` - // Tag - IP tag associated with the public IP. Example: SQL, Storage etc. - Tag *string `json:"tag,omitempty"` -} - -// VirtualMachineScaleSetListOSUpgradeHistory list of Virtual Machine Scale Set OS Upgrade History -// operation response. -type VirtualMachineScaleSetListOSUpgradeHistory struct { - autorest.Response `json:"-"` - // Value - The list of OS upgrades performed on the virtual machine scale set. - Value *[]UpgradeOperationHistoricalStatusInfo `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of OS Upgrade History. Call ListNext() with this to fetch the next page of history of upgrades. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualMachineScaleSetListOSUpgradeHistoryIterator provides access to a complete listing of -// UpgradeOperationHistoricalStatusInfo values. -type VirtualMachineScaleSetListOSUpgradeHistoryIterator struct { - i int - page VirtualMachineScaleSetListOSUpgradeHistoryPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualMachineScaleSetListOSUpgradeHistoryIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListOSUpgradeHistoryIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualMachineScaleSetListOSUpgradeHistoryIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualMachineScaleSetListOSUpgradeHistoryIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualMachineScaleSetListOSUpgradeHistoryIterator) Response() VirtualMachineScaleSetListOSUpgradeHistory { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualMachineScaleSetListOSUpgradeHistoryIterator) Value() UpgradeOperationHistoricalStatusInfo { - if !iter.page.NotDone() { - return UpgradeOperationHistoricalStatusInfo{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualMachineScaleSetListOSUpgradeHistoryIterator type. -func NewVirtualMachineScaleSetListOSUpgradeHistoryIterator(page VirtualMachineScaleSetListOSUpgradeHistoryPage) VirtualMachineScaleSetListOSUpgradeHistoryIterator { - return VirtualMachineScaleSetListOSUpgradeHistoryIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vmsslouh VirtualMachineScaleSetListOSUpgradeHistory) IsEmpty() bool { - return vmsslouh.Value == nil || len(*vmsslouh.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vmsslouh VirtualMachineScaleSetListOSUpgradeHistory) hasNextLink() bool { - return vmsslouh.NextLink != nil && len(*vmsslouh.NextLink) != 0 -} - -// virtualMachineScaleSetListOSUpgradeHistoryPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vmsslouh VirtualMachineScaleSetListOSUpgradeHistory) virtualMachineScaleSetListOSUpgradeHistoryPreparer(ctx context.Context) (*http.Request, error) { - if !vmsslouh.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vmsslouh.NextLink))) -} - -// VirtualMachineScaleSetListOSUpgradeHistoryPage contains a page of UpgradeOperationHistoricalStatusInfo -// values. -type VirtualMachineScaleSetListOSUpgradeHistoryPage struct { - fn func(context.Context, VirtualMachineScaleSetListOSUpgradeHistory) (VirtualMachineScaleSetListOSUpgradeHistory, error) - vmsslouh VirtualMachineScaleSetListOSUpgradeHistory -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetListOSUpgradeHistoryPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListOSUpgradeHistoryPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vmsslouh) - if err != nil { - return err - } - page.vmsslouh = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetListOSUpgradeHistoryPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetListOSUpgradeHistoryPage) NotDone() bool { - return !page.vmsslouh.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetListOSUpgradeHistoryPage) Response() VirtualMachineScaleSetListOSUpgradeHistory { - return page.vmsslouh -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetListOSUpgradeHistoryPage) Values() []UpgradeOperationHistoricalStatusInfo { - if page.vmsslouh.IsEmpty() { - return nil - } - return *page.vmsslouh.Value -} - -// Creates a new instance of the VirtualMachineScaleSetListOSUpgradeHistoryPage type. -func NewVirtualMachineScaleSetListOSUpgradeHistoryPage(cur VirtualMachineScaleSetListOSUpgradeHistory, getNextPage func(context.Context, VirtualMachineScaleSetListOSUpgradeHistory) (VirtualMachineScaleSetListOSUpgradeHistory, error)) VirtualMachineScaleSetListOSUpgradeHistoryPage { - return VirtualMachineScaleSetListOSUpgradeHistoryPage{ - fn: getNextPage, - vmsslouh: cur, - } -} - -// VirtualMachineScaleSetListResult the List Virtual Machine operation response. -type VirtualMachineScaleSetListResult struct { - autorest.Response `json:"-"` - // Value - The list of virtual machine scale sets. - Value *[]VirtualMachineScaleSet `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of Virtual Machine Scale Sets. Call ListNext() with this to fetch the next page of VMSS. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualMachineScaleSetListResultIterator provides access to a complete listing of VirtualMachineScaleSet -// values. -type VirtualMachineScaleSetListResultIterator struct { - i int - page VirtualMachineScaleSetListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualMachineScaleSetListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualMachineScaleSetListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualMachineScaleSetListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualMachineScaleSetListResultIterator) Response() VirtualMachineScaleSetListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualMachineScaleSetListResultIterator) Value() VirtualMachineScaleSet { - if !iter.page.NotDone() { - return VirtualMachineScaleSet{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualMachineScaleSetListResultIterator type. -func NewVirtualMachineScaleSetListResultIterator(page VirtualMachineScaleSetListResultPage) VirtualMachineScaleSetListResultIterator { - return VirtualMachineScaleSetListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vmsslr VirtualMachineScaleSetListResult) IsEmpty() bool { - return vmsslr.Value == nil || len(*vmsslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vmsslr VirtualMachineScaleSetListResult) hasNextLink() bool { - return vmsslr.NextLink != nil && len(*vmsslr.NextLink) != 0 -} - -// virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vmsslr VirtualMachineScaleSetListResult) virtualMachineScaleSetListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vmsslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vmsslr.NextLink))) -} - -// VirtualMachineScaleSetListResultPage contains a page of VirtualMachineScaleSet values. -type VirtualMachineScaleSetListResultPage struct { - fn func(context.Context, VirtualMachineScaleSetListResult) (VirtualMachineScaleSetListResult, error) - vmsslr VirtualMachineScaleSetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vmsslr) - if err != nil { - return err - } - page.vmsslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetListResultPage) NotDone() bool { - return !page.vmsslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetListResultPage) Response() VirtualMachineScaleSetListResult { - return page.vmsslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetListResultPage) Values() []VirtualMachineScaleSet { - if page.vmsslr.IsEmpty() { - return nil - } - return *page.vmsslr.Value -} - -// Creates a new instance of the VirtualMachineScaleSetListResultPage type. -func NewVirtualMachineScaleSetListResultPage(cur VirtualMachineScaleSetListResult, getNextPage func(context.Context, VirtualMachineScaleSetListResult) (VirtualMachineScaleSetListResult, error)) VirtualMachineScaleSetListResultPage { - return VirtualMachineScaleSetListResultPage{ - fn: getNextPage, - vmsslr: cur, - } -} - -// VirtualMachineScaleSetListSkusResult the Virtual Machine Scale Set List Skus operation response. -type VirtualMachineScaleSetListSkusResult struct { - autorest.Response `json:"-"` - // Value - The list of skus available for the virtual machine scale set. - Value *[]VirtualMachineScaleSetSku `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of Virtual Machine Scale Set Skus. Call ListNext() with this to fetch the next page of VMSS Skus. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualMachineScaleSetListSkusResultIterator provides access to a complete listing of -// VirtualMachineScaleSetSku values. -type VirtualMachineScaleSetListSkusResultIterator struct { - i int - page VirtualMachineScaleSetListSkusResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualMachineScaleSetListSkusResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListSkusResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualMachineScaleSetListSkusResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualMachineScaleSetListSkusResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualMachineScaleSetListSkusResultIterator) Response() VirtualMachineScaleSetListSkusResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualMachineScaleSetListSkusResultIterator) Value() VirtualMachineScaleSetSku { - if !iter.page.NotDone() { - return VirtualMachineScaleSetSku{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualMachineScaleSetListSkusResultIterator type. -func NewVirtualMachineScaleSetListSkusResultIterator(page VirtualMachineScaleSetListSkusResultPage) VirtualMachineScaleSetListSkusResultIterator { - return VirtualMachineScaleSetListSkusResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vmsslsr VirtualMachineScaleSetListSkusResult) IsEmpty() bool { - return vmsslsr.Value == nil || len(*vmsslsr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vmsslsr VirtualMachineScaleSetListSkusResult) hasNextLink() bool { - return vmsslsr.NextLink != nil && len(*vmsslsr.NextLink) != 0 -} - -// virtualMachineScaleSetListSkusResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vmsslsr VirtualMachineScaleSetListSkusResult) virtualMachineScaleSetListSkusResultPreparer(ctx context.Context) (*http.Request, error) { - if !vmsslsr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vmsslsr.NextLink))) -} - -// VirtualMachineScaleSetListSkusResultPage contains a page of VirtualMachineScaleSetSku values. -type VirtualMachineScaleSetListSkusResultPage struct { - fn func(context.Context, VirtualMachineScaleSetListSkusResult) (VirtualMachineScaleSetListSkusResult, error) - vmsslsr VirtualMachineScaleSetListSkusResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetListSkusResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListSkusResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vmsslsr) - if err != nil { - return err - } - page.vmsslsr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetListSkusResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetListSkusResultPage) NotDone() bool { - return !page.vmsslsr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetListSkusResultPage) Response() VirtualMachineScaleSetListSkusResult { - return page.vmsslsr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetListSkusResultPage) Values() []VirtualMachineScaleSetSku { - if page.vmsslsr.IsEmpty() { - return nil - } - return *page.vmsslsr.Value -} - -// Creates a new instance of the VirtualMachineScaleSetListSkusResultPage type. -func NewVirtualMachineScaleSetListSkusResultPage(cur VirtualMachineScaleSetListSkusResult, getNextPage func(context.Context, VirtualMachineScaleSetListSkusResult) (VirtualMachineScaleSetListSkusResult, error)) VirtualMachineScaleSetListSkusResultPage { - return VirtualMachineScaleSetListSkusResultPage{ - fn: getNextPage, - vmsslsr: cur, - } -} - -// VirtualMachineScaleSetListWithLinkResult the List Virtual Machine operation response. -type VirtualMachineScaleSetListWithLinkResult struct { - autorest.Response `json:"-"` - // Value - The list of virtual machine scale sets. - Value *[]VirtualMachineScaleSet `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of Virtual Machine Scale Sets. Call ListNext() with this to fetch the next page of Virtual Machine Scale Sets. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualMachineScaleSetListWithLinkResultIterator provides access to a complete listing of -// VirtualMachineScaleSet values. -type VirtualMachineScaleSetListWithLinkResultIterator struct { - i int - page VirtualMachineScaleSetListWithLinkResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualMachineScaleSetListWithLinkResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListWithLinkResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualMachineScaleSetListWithLinkResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualMachineScaleSetListWithLinkResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualMachineScaleSetListWithLinkResultIterator) Response() VirtualMachineScaleSetListWithLinkResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualMachineScaleSetListWithLinkResultIterator) Value() VirtualMachineScaleSet { - if !iter.page.NotDone() { - return VirtualMachineScaleSet{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualMachineScaleSetListWithLinkResultIterator type. -func NewVirtualMachineScaleSetListWithLinkResultIterator(page VirtualMachineScaleSetListWithLinkResultPage) VirtualMachineScaleSetListWithLinkResultIterator { - return VirtualMachineScaleSetListWithLinkResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vmsslwlr VirtualMachineScaleSetListWithLinkResult) IsEmpty() bool { - return vmsslwlr.Value == nil || len(*vmsslwlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vmsslwlr VirtualMachineScaleSetListWithLinkResult) hasNextLink() bool { - return vmsslwlr.NextLink != nil && len(*vmsslwlr.NextLink) != 0 -} - -// virtualMachineScaleSetListWithLinkResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vmsslwlr VirtualMachineScaleSetListWithLinkResult) virtualMachineScaleSetListWithLinkResultPreparer(ctx context.Context) (*http.Request, error) { - if !vmsslwlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vmsslwlr.NextLink))) -} - -// VirtualMachineScaleSetListWithLinkResultPage contains a page of VirtualMachineScaleSet values. -type VirtualMachineScaleSetListWithLinkResultPage struct { - fn func(context.Context, VirtualMachineScaleSetListWithLinkResult) (VirtualMachineScaleSetListWithLinkResult, error) - vmsslwlr VirtualMachineScaleSetListWithLinkResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetListWithLinkResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetListWithLinkResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vmsslwlr) - if err != nil { - return err - } - page.vmsslwlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetListWithLinkResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetListWithLinkResultPage) NotDone() bool { - return !page.vmsslwlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetListWithLinkResultPage) Response() VirtualMachineScaleSetListWithLinkResult { - return page.vmsslwlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetListWithLinkResultPage) Values() []VirtualMachineScaleSet { - if page.vmsslwlr.IsEmpty() { - return nil - } - return *page.vmsslwlr.Value -} - -// Creates a new instance of the VirtualMachineScaleSetListWithLinkResultPage type. -func NewVirtualMachineScaleSetListWithLinkResultPage(cur VirtualMachineScaleSetListWithLinkResult, getNextPage func(context.Context, VirtualMachineScaleSetListWithLinkResult) (VirtualMachineScaleSetListWithLinkResult, error)) VirtualMachineScaleSetListWithLinkResultPage { - return VirtualMachineScaleSetListWithLinkResultPage{ - fn: getNextPage, - vmsslwlr: cur, - } -} - -// VirtualMachineScaleSetManagedDiskParameters describes the parameters of a ScaleSet managed disk. -type VirtualMachineScaleSetManagedDiskParameters struct { - // StorageAccountType - Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk. Possible values include: 'StorageAccountTypesStandardLRS', 'StorageAccountTypesPremiumLRS', 'StorageAccountTypesStandardSSDLRS', 'StorageAccountTypesUltraSSDLRS' - StorageAccountType StorageAccountTypes `json:"storageAccountType,omitempty"` -} - -// VirtualMachineScaleSetNetworkConfiguration describes a virtual machine scale set network profile's -// network configurations. -type VirtualMachineScaleSetNetworkConfiguration struct { - // Name - The network configuration name. - Name *string `json:"name,omitempty"` - *VirtualMachineScaleSetNetworkConfigurationProperties `json:"properties,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetNetworkConfiguration. -func (vmssnc VirtualMachineScaleSetNetworkConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssnc.Name != nil { - objectMap["name"] = vmssnc.Name - } - if vmssnc.VirtualMachineScaleSetNetworkConfigurationProperties != nil { - objectMap["properties"] = vmssnc.VirtualMachineScaleSetNetworkConfigurationProperties - } - if vmssnc.ID != nil { - objectMap["id"] = vmssnc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetNetworkConfiguration struct. -func (vmssnc *VirtualMachineScaleSetNetworkConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmssnc.Name = &name - } - case "properties": - if v != nil { - var virtualMachineScaleSetNetworkConfigurationProperties VirtualMachineScaleSetNetworkConfigurationProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetNetworkConfigurationProperties) - if err != nil { - return err - } - vmssnc.VirtualMachineScaleSetNetworkConfigurationProperties = &virtualMachineScaleSetNetworkConfigurationProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmssnc.ID = &ID - } - } - } - - return nil -} - -// VirtualMachineScaleSetNetworkConfigurationDNSSettings describes a virtual machines scale sets network -// configuration's DNS settings. -type VirtualMachineScaleSetNetworkConfigurationDNSSettings struct { - // DNSServers - List of DNS servers IP addresses - DNSServers *[]string `json:"dnsServers,omitempty"` -} - -// VirtualMachineScaleSetNetworkConfigurationProperties describes a virtual machine scale set network -// profile's IP configuration. -type VirtualMachineScaleSetNetworkConfigurationProperties struct { - // Primary - Specifies the primary network interface in case the virtual machine has more than 1 network interface. - Primary *bool `json:"primary,omitempty"` - // EnableAcceleratedNetworking - Specifies whether the network interface is accelerated networking-enabled. - EnableAcceleratedNetworking *bool `json:"enableAcceleratedNetworking,omitempty"` - // NetworkSecurityGroup - The network security group. - NetworkSecurityGroup *SubResource `json:"networkSecurityGroup,omitempty"` - // DNSSettings - The dns settings to be applied on the network interfaces. - DNSSettings *VirtualMachineScaleSetNetworkConfigurationDNSSettings `json:"dnsSettings,omitempty"` - // IPConfigurations - Specifies the IP configurations of the network interface. - IPConfigurations *[]VirtualMachineScaleSetIPConfiguration `json:"ipConfigurations,omitempty"` - // EnableIPForwarding - Whether IP forwarding enabled on this NIC. - EnableIPForwarding *bool `json:"enableIPForwarding,omitempty"` -} - -// VirtualMachineScaleSetNetworkProfile describes a virtual machine scale set network profile. -type VirtualMachineScaleSetNetworkProfile struct { - // HealthProbe - A reference to a load balancer probe used to determine the health of an instance in the virtual machine scale set. The reference will be in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. - HealthProbe *APIEntityReference `json:"healthProbe,omitempty"` - // NetworkInterfaceConfigurations - The list of network configurations. - NetworkInterfaceConfigurations *[]VirtualMachineScaleSetNetworkConfiguration `json:"networkInterfaceConfigurations,omitempty"` -} - -// VirtualMachineScaleSetOSDisk describes a virtual machine scale set operating system disk. -type VirtualMachineScaleSetOSDisk struct { - // Name - The disk name. - Name *string `json:"name,omitempty"` - // Caching - Specifies the caching requirements.

      Possible values are:

      **None**

      **ReadOnly**

      **ReadWrite**

      Default: **None for Standard storage. ReadOnly for Premium storage**. Possible values include: 'CachingTypesNone', 'CachingTypesReadOnly', 'CachingTypesReadWrite' - Caching CachingTypes `json:"caching,omitempty"` - // WriteAcceleratorEnabled - Specifies whether writeAccelerator should be enabled or disabled on the disk. - WriteAcceleratorEnabled *bool `json:"writeAcceleratorEnabled,omitempty"` - // CreateOption - Specifies how the virtual machines in the scale set should be created.

      The only allowed value is: **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. Possible values include: 'DiskCreateOptionTypesFromImage', 'DiskCreateOptionTypesEmpty', 'DiskCreateOptionTypesAttach' - CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` - // DiffDiskSettings - Specifies the ephemeral disk Settings for the operating system disk used by the virtual machine scale set. - DiffDiskSettings *DiffDiskSettings `json:"diffDiskSettings,omitempty"` - // DiskSizeGB - Specifies the size of the operating system disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image.

      This value cannot be larger than 1023 GB - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // OsType - This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD.

      Possible values are:

      **Windows**

      **Linux**. Possible values include: 'Windows', 'Linux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // Image - Specifies information about the unmanaged user image to base the scale set on. - Image *VirtualHardDisk `json:"image,omitempty"` - // VhdContainers - Specifies the container urls that are used to store operating system disks for the scale set. - VhdContainers *[]string `json:"vhdContainers,omitempty"` - // ManagedDisk - The managed disk parameters. - ManagedDisk *VirtualMachineScaleSetManagedDiskParameters `json:"managedDisk,omitempty"` -} - -// VirtualMachineScaleSetOSProfile describes a virtual machine scale set OS profile. -type VirtualMachineScaleSetOSProfile struct { - // ComputerNamePrefix - Specifies the computer name prefix for all of the virtual machines in the scale set. Computer name prefixes must be 1 to 15 characters long. - ComputerNamePrefix *string `json:"computerNamePrefix,omitempty"` - // AdminUsername - Specifies the name of the administrator account.

      **Windows-only restriction:** Cannot end in "."

      **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5".

      **Minimum-length (Linux):** 1 character

      **Max-length (Linux):** 64 characters

      **Max-length (Windows):** 20 characters

    • For root access to the Linux VM, see [Using root privileges on Linux virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-use-root-privileges?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)
    • For a list of built-in system users on Linux that should not be used in this field, see [Selecting User Names for Linux on Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-usernames?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) - AdminUsername *string `json:"adminUsername,omitempty"` - // AdminPassword - Specifies the password of the administrator account.

      **Minimum-length (Windows):** 8 characters

      **Minimum-length (Linux):** 6 characters

      **Max-length (Windows):** 123 characters

      **Max-length (Linux):** 72 characters

      **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled
      Has lower characters
      Has upper characters
      Has a digit
      Has a special character (Regex match [\W_])

      **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!"

      For resetting the password, see [How to reset the Remote Desktop service or its login password in a Windows VM](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-reset-rdp?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)

      For resetting root password, see [Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-vmaccess-extension?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#reset-root-password) - AdminPassword *string `json:"adminPassword,omitempty"` - // CustomData - Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes.

      For using cloud-init for your VM, see [Using cloud-init to customize a Linux VM during creation](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-cloud-init?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) - CustomData *string `json:"customData,omitempty"` - // WindowsConfiguration - Specifies Windows operating system settings on the virtual machine. - WindowsConfiguration *WindowsConfiguration `json:"windowsConfiguration,omitempty"` - // LinuxConfiguration - Specifies the Linux operating system settings on the virtual machine.

      For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)

      For running non-endorsed distributions, see [Information for Non-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). - LinuxConfiguration *LinuxConfiguration `json:"linuxConfiguration,omitempty"` - // Secrets - Specifies set of certificates that should be installed onto the virtual machines in the scale set. - Secrets *[]VaultSecretGroup `json:"secrets,omitempty"` -} - -// VirtualMachineScaleSetProperties describes the properties of a Virtual Machine Scale Set. -type VirtualMachineScaleSetProperties struct { - // UpgradePolicy - The upgrade policy. - UpgradePolicy *UpgradePolicy `json:"upgradePolicy,omitempty"` - // AutomaticRepairsPolicy - Policy for automatic repairs. - AutomaticRepairsPolicy *AutomaticRepairsPolicy `json:"automaticRepairsPolicy,omitempty"` - // VirtualMachineProfile - The virtual machine profile. - VirtualMachineProfile *VirtualMachineScaleSetVMProfile `json:"virtualMachineProfile,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. - ProvisioningState *string `json:"provisioningState,omitempty"` - // Overprovision - Specifies whether the Virtual Machine Scale Set should be overprovisioned. - Overprovision *bool `json:"overprovision,omitempty"` - // DoNotRunExtensionsOnOverprovisionedVMs - When Overprovision is enabled, extensions are launched only on the requested number of VMs which are finally kept. This property will hence ensure that the extensions do not run on the extra overprovisioned VMs. - DoNotRunExtensionsOnOverprovisionedVMs *bool `json:"doNotRunExtensionsOnOverprovisionedVMs,omitempty"` - // UniqueID - READ-ONLY; Specifies the ID which uniquely identifies a Virtual Machine Scale Set. - UniqueID *string `json:"uniqueId,omitempty"` - // SinglePlacementGroup - When true this limits the scale set to a single placement group, of max size 100 virtual machines. - SinglePlacementGroup *bool `json:"singlePlacementGroup,omitempty"` - // ZoneBalance - Whether to force strictly even Virtual Machine distribution cross x-zones in case there is zone outage. - ZoneBalance *bool `json:"zoneBalance,omitempty"` - // PlatformFaultDomainCount - Fault Domain count for each placement group. - PlatformFaultDomainCount *int32 `json:"platformFaultDomainCount,omitempty"` - // ProximityPlacementGroup - Specifies information about the proximity placement group that the virtual machine scale set should be assigned to.

      Minimum api-version: 2018-04-01. - ProximityPlacementGroup *SubResource `json:"proximityPlacementGroup,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetProperties. -func (vmssp VirtualMachineScaleSetProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssp.UpgradePolicy != nil { - objectMap["upgradePolicy"] = vmssp.UpgradePolicy - } - if vmssp.AutomaticRepairsPolicy != nil { - objectMap["automaticRepairsPolicy"] = vmssp.AutomaticRepairsPolicy - } - if vmssp.VirtualMachineProfile != nil { - objectMap["virtualMachineProfile"] = vmssp.VirtualMachineProfile - } - if vmssp.Overprovision != nil { - objectMap["overprovision"] = vmssp.Overprovision - } - if vmssp.DoNotRunExtensionsOnOverprovisionedVMs != nil { - objectMap["doNotRunExtensionsOnOverprovisionedVMs"] = vmssp.DoNotRunExtensionsOnOverprovisionedVMs - } - if vmssp.SinglePlacementGroup != nil { - objectMap["singlePlacementGroup"] = vmssp.SinglePlacementGroup - } - if vmssp.ZoneBalance != nil { - objectMap["zoneBalance"] = vmssp.ZoneBalance - } - if vmssp.PlatformFaultDomainCount != nil { - objectMap["platformFaultDomainCount"] = vmssp.PlatformFaultDomainCount - } - if vmssp.ProximityPlacementGroup != nil { - objectMap["proximityPlacementGroup"] = vmssp.ProximityPlacementGroup - } - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetPublicIPAddressConfiguration describes a virtual machines scale set IP -// Configuration's PublicIPAddress configuration -type VirtualMachineScaleSetPublicIPAddressConfiguration struct { - // Name - The publicIP address configuration name. - Name *string `json:"name,omitempty"` - *VirtualMachineScaleSetPublicIPAddressConfigurationProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetPublicIPAddressConfiguration. -func (vmsspiac VirtualMachineScaleSetPublicIPAddressConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmsspiac.Name != nil { - objectMap["name"] = vmsspiac.Name - } - if vmsspiac.VirtualMachineScaleSetPublicIPAddressConfigurationProperties != nil { - objectMap["properties"] = vmsspiac.VirtualMachineScaleSetPublicIPAddressConfigurationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetPublicIPAddressConfiguration struct. -func (vmsspiac *VirtualMachineScaleSetPublicIPAddressConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmsspiac.Name = &name - } - case "properties": - if v != nil { - var virtualMachineScaleSetPublicIPAddressConfigurationProperties VirtualMachineScaleSetPublicIPAddressConfigurationProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetPublicIPAddressConfigurationProperties) - if err != nil { - return err - } - vmsspiac.VirtualMachineScaleSetPublicIPAddressConfigurationProperties = &virtualMachineScaleSetPublicIPAddressConfigurationProperties - } - } - } - - return nil -} - -// VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings describes a virtual machines scale sets -// network configuration's DNS settings. -type VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings struct { - // DomainNameLabel - The Domain name label.The concatenation of the domain name label and vm index will be the domain name labels of the PublicIPAddress resources that will be created - DomainNameLabel *string `json:"domainNameLabel,omitempty"` -} - -// VirtualMachineScaleSetPublicIPAddressConfigurationProperties describes a virtual machines scale set IP -// Configuration's PublicIPAddress configuration -type VirtualMachineScaleSetPublicIPAddressConfigurationProperties struct { - // IdleTimeoutInMinutes - The idle timeout of the public IP address. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // DNSSettings - The dns settings to be applied on the publicIP addresses . - DNSSettings *VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings `json:"dnsSettings,omitempty"` - // IPTags - The list of IP tags associated with the public IP address. - IPTags *[]VirtualMachineScaleSetIPTag `json:"ipTags,omitempty"` - // PublicIPPrefix - The PublicIPPrefix from which to allocate publicIP addresses. - PublicIPPrefix *SubResource `json:"publicIPPrefix,omitempty"` -} - -// VirtualMachineScaleSetReimageParameters describes a Virtual Machine Scale Set VM Reimage Parameters. -type VirtualMachineScaleSetReimageParameters struct { - // InstanceIds - The virtual machine scale set instance ids. Omitting the virtual machine scale set instance ids will result in the operation being performed on all virtual machines in the virtual machine scale set. - InstanceIds *[]string `json:"instanceIds,omitempty"` - // TempDisk - Specifies whether to reimage temp disk. Default value: false. Note: This temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS disk. - TempDisk *bool `json:"tempDisk,omitempty"` -} - -// VirtualMachineScaleSetRollingUpgradesCancelFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualMachineScaleSetRollingUpgradesCancelFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetRollingUpgradesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetRollingUpgradesCancelFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetRollingUpgradesCancelFuture.Result. -func (future *VirtualMachineScaleSetRollingUpgradesCancelFuture) result(client VirtualMachineScaleSetRollingUpgradesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesCancelFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetRollingUpgradesCancelFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture an abstraction for monitoring and -// retrieving the results of a long-running operation. -type VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetRollingUpgradesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture.Result. -func (future *VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture) result(client VirtualMachineScaleSetRollingUpgradesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetRollingUpgradesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture.Result. -func (future *VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture) result(client VirtualMachineScaleSetRollingUpgradesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualMachineScaleSetsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (VirtualMachineScaleSet, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsCreateOrUpdateFuture.Result. -func (future *VirtualMachineScaleSetsCreateOrUpdateFuture) result(client VirtualMachineScaleSetsClient) (vmss VirtualMachineScaleSet, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vmss.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vmss.Response.Response, err = future.GetResult(sender); err == nil && vmss.Response.Response.StatusCode != http.StatusNoContent { - vmss, err = client.CreateOrUpdateResponder(vmss.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsCreateOrUpdateFuture", "Result", vmss.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachineScaleSetsDeallocateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsDeallocateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsDeallocateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsDeallocateFuture.Result. -func (future *VirtualMachineScaleSetsDeallocateFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsDeallocateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsDeallocateFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsDeleteFuture.Result. -func (future *VirtualMachineScaleSetsDeleteFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsDeleteInstancesFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualMachineScaleSetsDeleteInstancesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsDeleteInstancesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsDeleteInstancesFuture.Result. -func (future *VirtualMachineScaleSetsDeleteInstancesFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsDeleteInstancesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsDeleteInstancesFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetSku describes an available virtual machine scale set sku. -type VirtualMachineScaleSetSku struct { - // ResourceType - READ-ONLY; The type of resource the sku applies to. - ResourceType *string `json:"resourceType,omitempty"` - // Sku - READ-ONLY; The Sku. - Sku *Sku `json:"sku,omitempty"` - // Capacity - READ-ONLY; Specifies the number of virtual machines in the scale set. - Capacity *VirtualMachineScaleSetSkuCapacity `json:"capacity,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetSku. -func (vmsss VirtualMachineScaleSetSku) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetSkuCapacity describes scaling information of a sku. -type VirtualMachineScaleSetSkuCapacity struct { - // Minimum - READ-ONLY; The minimum capacity. - Minimum *int64 `json:"minimum,omitempty"` - // Maximum - READ-ONLY; The maximum capacity that can be set. - Maximum *int64 `json:"maximum,omitempty"` - // DefaultCapacity - READ-ONLY; The default capacity. - DefaultCapacity *int64 `json:"defaultCapacity,omitempty"` - // ScaleType - READ-ONLY; The scale type applicable to the sku. Possible values include: 'VirtualMachineScaleSetSkuScaleTypeAutomatic', 'VirtualMachineScaleSetSkuScaleTypeNone' - ScaleType VirtualMachineScaleSetSkuScaleType `json:"scaleType,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetSkuCapacity. -func (vmsssc VirtualMachineScaleSetSkuCapacity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetsPerformMaintenanceFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualMachineScaleSetsPerformMaintenanceFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsPerformMaintenanceFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsPerformMaintenanceFuture.Result. -func (future *VirtualMachineScaleSetsPerformMaintenanceFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsPerformMaintenanceFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsPerformMaintenanceFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsPowerOffFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsPowerOffFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsPowerOffFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsPowerOffFuture.Result. -func (future *VirtualMachineScaleSetsPowerOffFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsPowerOffFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsPowerOffFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsRedeployFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsRedeployFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsRedeployFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsRedeployFuture.Result. -func (future *VirtualMachineScaleSetsRedeployFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsRedeployFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsRedeployFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsReimageAllFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsReimageAllFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsReimageAllFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsReimageAllFuture.Result. -func (future *VirtualMachineScaleSetsReimageAllFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsReimageAllFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsReimageAllFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsReimageFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsReimageFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsReimageFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsReimageFuture.Result. -func (future *VirtualMachineScaleSetsReimageFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsReimageFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsReimageFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsRestartFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsRestartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsRestartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsRestartFuture.Result. -func (future *VirtualMachineScaleSetsRestartFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsRestartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsRestartFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetsStartFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsStartFuture.Result. -func (future *VirtualMachineScaleSetsStartFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsStartFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetStorageProfile describes a virtual machine scale set storage profile. -type VirtualMachineScaleSetStorageProfile struct { - // ImageReference - Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. - ImageReference *ImageReference `json:"imageReference,omitempty"` - // OsDisk - Specifies information about the operating system disk used by the virtual machines in the scale set.

      For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). - OsDisk *VirtualMachineScaleSetOSDisk `json:"osDisk,omitempty"` - // DataDisks - Specifies the parameters that are used to add data disks to the virtual machines in the scale set.

      For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). - DataDisks *[]VirtualMachineScaleSetDataDisk `json:"dataDisks,omitempty"` -} - -// VirtualMachineScaleSetsUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (VirtualMachineScaleSet, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsUpdateFuture.Result. -func (future *VirtualMachineScaleSetsUpdateFuture) result(client VirtualMachineScaleSetsClient) (vmss VirtualMachineScaleSet, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vmss.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vmss.Response.Response, err = future.GetResult(sender); err == nil && vmss.Response.Response.StatusCode != http.StatusNoContent { - vmss, err = client.UpdateResponder(vmss.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsUpdateFuture", "Result", vmss.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachineScaleSetsUpdateInstancesFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualMachineScaleSetsUpdateInstancesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetsUpdateInstancesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetsUpdateInstancesFuture.Result. -func (future *VirtualMachineScaleSetsUpdateInstancesFuture) result(client VirtualMachineScaleSetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsUpdateInstancesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetsUpdateInstancesFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetUpdate describes a Virtual Machine Scale Set. -type VirtualMachineScaleSetUpdate struct { - // Sku - The virtual machine scale set sku. - Sku *Sku `json:"sku,omitempty"` - // Plan - The purchase plan when deploying a virtual machine scale set from VM Marketplace images. - Plan *Plan `json:"plan,omitempty"` - *VirtualMachineScaleSetUpdateProperties `json:"properties,omitempty"` - // Identity - The identity of the virtual machine scale set, if configured. - Identity *VirtualMachineScaleSetIdentity `json:"identity,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetUpdate. -func (vmssu VirtualMachineScaleSetUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssu.Sku != nil { - objectMap["sku"] = vmssu.Sku - } - if vmssu.Plan != nil { - objectMap["plan"] = vmssu.Plan - } - if vmssu.VirtualMachineScaleSetUpdateProperties != nil { - objectMap["properties"] = vmssu.VirtualMachineScaleSetUpdateProperties - } - if vmssu.Identity != nil { - objectMap["identity"] = vmssu.Identity - } - if vmssu.Tags != nil { - objectMap["tags"] = vmssu.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetUpdate struct. -func (vmssu *VirtualMachineScaleSetUpdate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku Sku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - vmssu.Sku = &sku - } - case "plan": - if v != nil { - var plan Plan - err = json.Unmarshal(*v, &plan) - if err != nil { - return err - } - vmssu.Plan = &plan - } - case "properties": - if v != nil { - var virtualMachineScaleSetUpdateProperties VirtualMachineScaleSetUpdateProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetUpdateProperties) - if err != nil { - return err - } - vmssu.VirtualMachineScaleSetUpdateProperties = &virtualMachineScaleSetUpdateProperties - } - case "identity": - if v != nil { - var identity VirtualMachineScaleSetIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - vmssu.Identity = &identity - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vmssu.Tags = tags - } - } - } - - return nil -} - -// VirtualMachineScaleSetUpdateIPConfiguration describes a virtual machine scale set network profile's IP -// configuration. -type VirtualMachineScaleSetUpdateIPConfiguration struct { - // Name - The IP configuration name. - Name *string `json:"name,omitempty"` - *VirtualMachineScaleSetUpdateIPConfigurationProperties `json:"properties,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetUpdateIPConfiguration. -func (vmssuic VirtualMachineScaleSetUpdateIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssuic.Name != nil { - objectMap["name"] = vmssuic.Name - } - if vmssuic.VirtualMachineScaleSetUpdateIPConfigurationProperties != nil { - objectMap["properties"] = vmssuic.VirtualMachineScaleSetUpdateIPConfigurationProperties - } - if vmssuic.ID != nil { - objectMap["id"] = vmssuic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetUpdateIPConfiguration struct. -func (vmssuic *VirtualMachineScaleSetUpdateIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmssuic.Name = &name - } - case "properties": - if v != nil { - var virtualMachineScaleSetUpdateIPConfigurationProperties VirtualMachineScaleSetUpdateIPConfigurationProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetUpdateIPConfigurationProperties) - if err != nil { - return err - } - vmssuic.VirtualMachineScaleSetUpdateIPConfigurationProperties = &virtualMachineScaleSetUpdateIPConfigurationProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmssuic.ID = &ID - } - } - } - - return nil -} - -// VirtualMachineScaleSetUpdateIPConfigurationProperties describes a virtual machine scale set network -// profile's IP configuration properties. NOTE: The subnet of a scale set may be modified as long as the -// original subnet and the new subnet are in the same virtual network. -type VirtualMachineScaleSetUpdateIPConfigurationProperties struct { - // Subnet - The subnet. - Subnet *APIEntityReference `json:"subnet,omitempty"` - // Primary - Specifies the primary IP Configuration in case the network interface has more than one IP Configuration. - Primary *bool `json:"primary,omitempty"` - // PublicIPAddressConfiguration - The publicIPAddressConfiguration. - PublicIPAddressConfiguration *VirtualMachineScaleSetUpdatePublicIPAddressConfiguration `json:"publicIPAddressConfiguration,omitempty"` - // PrivateIPAddressVersion - Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. Possible values include: 'IPv4', 'IPv6' - PrivateIPAddressVersion IPVersion `json:"privateIPAddressVersion,omitempty"` - // ApplicationGatewayBackendAddressPools - The application gateway backend address pools. - ApplicationGatewayBackendAddressPools *[]SubResource `json:"applicationGatewayBackendAddressPools,omitempty"` - // ApplicationSecurityGroups - Specifies an array of references to application security group. - ApplicationSecurityGroups *[]SubResource `json:"applicationSecurityGroups,omitempty"` - // LoadBalancerBackendAddressPools - The load balancer backend address pools. - LoadBalancerBackendAddressPools *[]SubResource `json:"loadBalancerBackendAddressPools,omitempty"` - // LoadBalancerInboundNatPools - The load balancer inbound nat pools. - LoadBalancerInboundNatPools *[]SubResource `json:"loadBalancerInboundNatPools,omitempty"` -} - -// VirtualMachineScaleSetUpdateNetworkConfiguration describes a virtual machine scale set network profile's -// network configurations. -type VirtualMachineScaleSetUpdateNetworkConfiguration struct { - // Name - The network configuration name. - Name *string `json:"name,omitempty"` - *VirtualMachineScaleSetUpdateNetworkConfigurationProperties `json:"properties,omitempty"` - // ID - Resource Id - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetUpdateNetworkConfiguration. -func (vmssunc VirtualMachineScaleSetUpdateNetworkConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssunc.Name != nil { - objectMap["name"] = vmssunc.Name - } - if vmssunc.VirtualMachineScaleSetUpdateNetworkConfigurationProperties != nil { - objectMap["properties"] = vmssunc.VirtualMachineScaleSetUpdateNetworkConfigurationProperties - } - if vmssunc.ID != nil { - objectMap["id"] = vmssunc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetUpdateNetworkConfiguration struct. -func (vmssunc *VirtualMachineScaleSetUpdateNetworkConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmssunc.Name = &name - } - case "properties": - if v != nil { - var virtualMachineScaleSetUpdateNetworkConfigurationProperties VirtualMachineScaleSetUpdateNetworkConfigurationProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetUpdateNetworkConfigurationProperties) - if err != nil { - return err - } - vmssunc.VirtualMachineScaleSetUpdateNetworkConfigurationProperties = &virtualMachineScaleSetUpdateNetworkConfigurationProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmssunc.ID = &ID - } - } - } - - return nil -} - -// VirtualMachineScaleSetUpdateNetworkConfigurationProperties describes a virtual machine scale set -// updatable network profile's IP configuration.Use this object for updating network profile's IP -// Configuration. -type VirtualMachineScaleSetUpdateNetworkConfigurationProperties struct { - // Primary - Whether this is a primary NIC on a virtual machine. - Primary *bool `json:"primary,omitempty"` - // EnableAcceleratedNetworking - Specifies whether the network interface is accelerated networking-enabled. - EnableAcceleratedNetworking *bool `json:"enableAcceleratedNetworking,omitempty"` - // NetworkSecurityGroup - The network security group. - NetworkSecurityGroup *SubResource `json:"networkSecurityGroup,omitempty"` - // DNSSettings - The dns settings to be applied on the network interfaces. - DNSSettings *VirtualMachineScaleSetNetworkConfigurationDNSSettings `json:"dnsSettings,omitempty"` - // IPConfigurations - The virtual machine scale set IP Configuration. - IPConfigurations *[]VirtualMachineScaleSetUpdateIPConfiguration `json:"ipConfigurations,omitempty"` - // EnableIPForwarding - Whether IP forwarding enabled on this NIC. - EnableIPForwarding *bool `json:"enableIPForwarding,omitempty"` -} - -// VirtualMachineScaleSetUpdateNetworkProfile describes a virtual machine scale set network profile. -type VirtualMachineScaleSetUpdateNetworkProfile struct { - // NetworkInterfaceConfigurations - The list of network configurations. - NetworkInterfaceConfigurations *[]VirtualMachineScaleSetUpdateNetworkConfiguration `json:"networkInterfaceConfigurations,omitempty"` -} - -// VirtualMachineScaleSetUpdateOSDisk describes virtual machine scale set operating system disk Update -// Object. This should be used for Updating VMSS OS Disk. -type VirtualMachineScaleSetUpdateOSDisk struct { - // Caching - The caching type. Possible values include: 'CachingTypesNone', 'CachingTypesReadOnly', 'CachingTypesReadWrite' - Caching CachingTypes `json:"caching,omitempty"` - // WriteAcceleratorEnabled - Specifies whether writeAccelerator should be enabled or disabled on the disk. - WriteAcceleratorEnabled *bool `json:"writeAcceleratorEnabled,omitempty"` - // DiskSizeGB - Specifies the size of the operating system disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image.

      This value cannot be larger than 1023 GB - DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` - // Image - The Source User Image VirtualHardDisk. This VirtualHardDisk will be copied before using it to attach to the Virtual Machine. If SourceImage is provided, the destination VirtualHardDisk should not exist. - Image *VirtualHardDisk `json:"image,omitempty"` - // VhdContainers - The list of virtual hard disk container uris. - VhdContainers *[]string `json:"vhdContainers,omitempty"` - // ManagedDisk - The managed disk parameters. - ManagedDisk *VirtualMachineScaleSetManagedDiskParameters `json:"managedDisk,omitempty"` -} - -// VirtualMachineScaleSetUpdateOSProfile describes a virtual machine scale set OS profile. -type VirtualMachineScaleSetUpdateOSProfile struct { - // CustomData - A base-64 encoded string of custom data. - CustomData *string `json:"customData,omitempty"` - // WindowsConfiguration - The Windows Configuration of the OS profile. - WindowsConfiguration *WindowsConfiguration `json:"windowsConfiguration,omitempty"` - // LinuxConfiguration - The Linux Configuration of the OS profile. - LinuxConfiguration *LinuxConfiguration `json:"linuxConfiguration,omitempty"` - // Secrets - The List of certificates for addition to the VM. - Secrets *[]VaultSecretGroup `json:"secrets,omitempty"` -} - -// VirtualMachineScaleSetUpdateProperties describes the properties of a Virtual Machine Scale Set. -type VirtualMachineScaleSetUpdateProperties struct { - // UpgradePolicy - The upgrade policy. - UpgradePolicy *UpgradePolicy `json:"upgradePolicy,omitempty"` - // AutomaticRepairsPolicy - Policy for automatic repairs. - AutomaticRepairsPolicy *AutomaticRepairsPolicy `json:"automaticRepairsPolicy,omitempty"` - // VirtualMachineProfile - The virtual machine profile. - VirtualMachineProfile *VirtualMachineScaleSetUpdateVMProfile `json:"virtualMachineProfile,omitempty"` - // Overprovision - Specifies whether the Virtual Machine Scale Set should be overprovisioned. - Overprovision *bool `json:"overprovision,omitempty"` - // DoNotRunExtensionsOnOverprovisionedVMs - When Overprovision is enabled, extensions are launched only on the requested number of VMs which are finally kept. This property will hence ensure that the extensions do not run on the extra overprovisioned VMs. - DoNotRunExtensionsOnOverprovisionedVMs *bool `json:"doNotRunExtensionsOnOverprovisionedVMs,omitempty"` - // SinglePlacementGroup - When true this limits the scale set to a single placement group, of max size 100 virtual machines. NOTE: If singlePlacementGroup is true, it may be modified to false. However, if singlePlacementGroup is false, it may not be modified to true. - SinglePlacementGroup *bool `json:"singlePlacementGroup,omitempty"` - // ProximityPlacementGroup - Specifies information about the proximity placement group that the virtual machine scale set should be assigned to.

      Minimum api-version: 2018-04-01. - ProximityPlacementGroup *SubResource `json:"proximityPlacementGroup,omitempty"` -} - -// VirtualMachineScaleSetUpdatePublicIPAddressConfiguration describes a virtual machines scale set IP -// Configuration's PublicIPAddress configuration -type VirtualMachineScaleSetUpdatePublicIPAddressConfiguration struct { - // Name - The publicIP address configuration name. - Name *string `json:"name,omitempty"` - *VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetUpdatePublicIPAddressConfiguration. -func (vmssupiac VirtualMachineScaleSetUpdatePublicIPAddressConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssupiac.Name != nil { - objectMap["name"] = vmssupiac.Name - } - if vmssupiac.VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties != nil { - objectMap["properties"] = vmssupiac.VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetUpdatePublicIPAddressConfiguration struct. -func (vmssupiac *VirtualMachineScaleSetUpdatePublicIPAddressConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmssupiac.Name = &name - } - case "properties": - if v != nil { - var virtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties) - if err != nil { - return err - } - vmssupiac.VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties = &virtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties - } - } - } - - return nil -} - -// VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties describes a virtual machines scale -// set IP Configuration's PublicIPAddress configuration -type VirtualMachineScaleSetUpdatePublicIPAddressConfigurationProperties struct { - // IdleTimeoutInMinutes - The idle timeout of the public IP address. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // DNSSettings - The dns settings to be applied on the publicIP addresses . - DNSSettings *VirtualMachineScaleSetPublicIPAddressConfigurationDNSSettings `json:"dnsSettings,omitempty"` -} - -// VirtualMachineScaleSetUpdateStorageProfile describes a virtual machine scale set storage profile. -type VirtualMachineScaleSetUpdateStorageProfile struct { - // ImageReference - The image reference. - ImageReference *ImageReference `json:"imageReference,omitempty"` - // OsDisk - The OS disk. - OsDisk *VirtualMachineScaleSetUpdateOSDisk `json:"osDisk,omitempty"` - // DataDisks - The data disks. - DataDisks *[]VirtualMachineScaleSetDataDisk `json:"dataDisks,omitempty"` -} - -// VirtualMachineScaleSetUpdateVMProfile describes a virtual machine scale set virtual machine profile. -type VirtualMachineScaleSetUpdateVMProfile struct { - // OsProfile - The virtual machine scale set OS profile. - OsProfile *VirtualMachineScaleSetUpdateOSProfile `json:"osProfile,omitempty"` - // StorageProfile - The virtual machine scale set storage profile. - StorageProfile *VirtualMachineScaleSetUpdateStorageProfile `json:"storageProfile,omitempty"` - // NetworkProfile - The virtual machine scale set network profile. - NetworkProfile *VirtualMachineScaleSetUpdateNetworkProfile `json:"networkProfile,omitempty"` - // DiagnosticsProfile - The virtual machine scale set diagnostics profile. - DiagnosticsProfile *DiagnosticsProfile `json:"diagnosticsProfile,omitempty"` - // ExtensionProfile - The virtual machine scale set extension profile. - ExtensionProfile *VirtualMachineScaleSetExtensionProfile `json:"extensionProfile,omitempty"` - // LicenseType - The license type, which is for bring your own license scenario. - LicenseType *string `json:"licenseType,omitempty"` -} - -// VirtualMachineScaleSetVM describes a virtual machine scale set virtual machine. -type VirtualMachineScaleSetVM struct { - autorest.Response `json:"-"` - // InstanceID - READ-ONLY; The virtual machine instance ID. - InstanceID *string `json:"instanceId,omitempty"` - // Sku - READ-ONLY; The virtual machine SKU. - Sku *Sku `json:"sku,omitempty"` - *VirtualMachineScaleSetVMProperties `json:"properties,omitempty"` - // Plan - Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. - Plan *Plan `json:"plan,omitempty"` - // Resources - READ-ONLY; The virtual machine child extension resources. - Resources *[]VirtualMachineExtension `json:"resources,omitempty"` - // Zones - READ-ONLY; The virtual machine zones. - Zones *[]string `json:"zones,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetVM. -func (vmssv VirtualMachineScaleSetVM) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssv.VirtualMachineScaleSetVMProperties != nil { - objectMap["properties"] = vmssv.VirtualMachineScaleSetVMProperties - } - if vmssv.Plan != nil { - objectMap["plan"] = vmssv.Plan - } - if vmssv.Location != nil { - objectMap["location"] = vmssv.Location - } - if vmssv.Tags != nil { - objectMap["tags"] = vmssv.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineScaleSetVM struct. -func (vmssv *VirtualMachineScaleSetVM) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "instanceId": - if v != nil { - var instanceID string - err = json.Unmarshal(*v, &instanceID) - if err != nil { - return err - } - vmssv.InstanceID = &instanceID - } - case "sku": - if v != nil { - var sku Sku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - vmssv.Sku = &sku - } - case "properties": - if v != nil { - var virtualMachineScaleSetVMProperties VirtualMachineScaleSetVMProperties - err = json.Unmarshal(*v, &virtualMachineScaleSetVMProperties) - if err != nil { - return err - } - vmssv.VirtualMachineScaleSetVMProperties = &virtualMachineScaleSetVMProperties - } - case "plan": - if v != nil { - var plan Plan - err = json.Unmarshal(*v, &plan) - if err != nil { - return err - } - vmssv.Plan = &plan - } - case "resources": - if v != nil { - var resources []VirtualMachineExtension - err = json.Unmarshal(*v, &resources) - if err != nil { - return err - } - vmssv.Resources = &resources - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - vmssv.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vmssv.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vmssv.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vmssv.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vmssv.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vmssv.Tags = tags - } - } - } - - return nil -} - -// VirtualMachineScaleSetVMExtensionsSummary extensions summary for virtual machines of a virtual machine -// scale set. -type VirtualMachineScaleSetVMExtensionsSummary struct { - // Name - READ-ONLY; The extension name. - Name *string `json:"name,omitempty"` - // StatusesSummary - READ-ONLY; The extensions information. - StatusesSummary *[]VirtualMachineStatusCodeCount `json:"statusesSummary,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetVMExtensionsSummary. -func (vmssves VirtualMachineScaleSetVMExtensionsSummary) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetVMInstanceIDs specifies a list of virtual machine instance IDs from the VM scale -// set. -type VirtualMachineScaleSetVMInstanceIDs struct { - // InstanceIds - The virtual machine scale set instance ids. Omitting the virtual machine scale set instance ids will result in the operation being performed on all virtual machines in the virtual machine scale set. - InstanceIds *[]string `json:"instanceIds,omitempty"` -} - -// VirtualMachineScaleSetVMInstanceRequiredIDs specifies a list of virtual machine instance IDs from the VM -// scale set. -type VirtualMachineScaleSetVMInstanceRequiredIDs struct { - // InstanceIds - The virtual machine scale set instance ids. - InstanceIds *[]string `json:"instanceIds,omitempty"` -} - -// VirtualMachineScaleSetVMInstanceView the instance view of a virtual machine scale set VM. -type VirtualMachineScaleSetVMInstanceView struct { - autorest.Response `json:"-"` - // PlatformUpdateDomain - The Update Domain count. - PlatformUpdateDomain *int32 `json:"platformUpdateDomain,omitempty"` - // PlatformFaultDomain - The Fault Domain count. - PlatformFaultDomain *int32 `json:"platformFaultDomain,omitempty"` - // RdpThumbPrint - The Remote desktop certificate thumbprint. - RdpThumbPrint *string `json:"rdpThumbPrint,omitempty"` - // VMAgent - The VM Agent running on the virtual machine. - VMAgent *VirtualMachineAgentInstanceView `json:"vmAgent,omitempty"` - // MaintenanceRedeployStatus - The Maintenance Operation status on the virtual machine. - MaintenanceRedeployStatus *MaintenanceRedeployStatus `json:"maintenanceRedeployStatus,omitempty"` - // Disks - The disks information. - Disks *[]DiskInstanceView `json:"disks,omitempty"` - // Extensions - The extensions information. - Extensions *[]VirtualMachineExtensionInstanceView `json:"extensions,omitempty"` - // VMHealth - READ-ONLY; The health status for the VM. - VMHealth *VirtualMachineHealthStatus `json:"vmHealth,omitempty"` - // BootDiagnostics - Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status.

      You can easily view the output of your console log.

      Azure also enables you to see a screenshot of the VM from the hypervisor. - BootDiagnostics *BootDiagnosticsInstanceView `json:"bootDiagnostics,omitempty"` - // Statuses - The resource status information. - Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` - // PlacementGroupID - The placement group in which the VM is running. If the VM is deallocated it will not have a placementGroupId. - PlacementGroupID *string `json:"placementGroupId,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetVMInstanceView. -func (vmssviv VirtualMachineScaleSetVMInstanceView) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssviv.PlatformUpdateDomain != nil { - objectMap["platformUpdateDomain"] = vmssviv.PlatformUpdateDomain - } - if vmssviv.PlatformFaultDomain != nil { - objectMap["platformFaultDomain"] = vmssviv.PlatformFaultDomain - } - if vmssviv.RdpThumbPrint != nil { - objectMap["rdpThumbPrint"] = vmssviv.RdpThumbPrint - } - if vmssviv.VMAgent != nil { - objectMap["vmAgent"] = vmssviv.VMAgent - } - if vmssviv.MaintenanceRedeployStatus != nil { - objectMap["maintenanceRedeployStatus"] = vmssviv.MaintenanceRedeployStatus - } - if vmssviv.Disks != nil { - objectMap["disks"] = vmssviv.Disks - } - if vmssviv.Extensions != nil { - objectMap["extensions"] = vmssviv.Extensions - } - if vmssviv.BootDiagnostics != nil { - objectMap["bootDiagnostics"] = vmssviv.BootDiagnostics - } - if vmssviv.Statuses != nil { - objectMap["statuses"] = vmssviv.Statuses - } - if vmssviv.PlacementGroupID != nil { - objectMap["placementGroupId"] = vmssviv.PlacementGroupID - } - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetVMListResult the List Virtual Machine Scale Set VMs operation response. -type VirtualMachineScaleSetVMListResult struct { - autorest.Response `json:"-"` - // Value - The list of virtual machine scale sets VMs. - Value *[]VirtualMachineScaleSetVM `json:"value,omitempty"` - // NextLink - The uri to fetch the next page of Virtual Machine Scale Set VMs. Call ListNext() with this to fetch the next page of VMSS VMs - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualMachineScaleSetVMListResultIterator provides access to a complete listing of -// VirtualMachineScaleSetVM values. -type VirtualMachineScaleSetVMListResultIterator struct { - i int - page VirtualMachineScaleSetVMListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualMachineScaleSetVMListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualMachineScaleSetVMListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualMachineScaleSetVMListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualMachineScaleSetVMListResultIterator) Response() VirtualMachineScaleSetVMListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualMachineScaleSetVMListResultIterator) Value() VirtualMachineScaleSetVM { - if !iter.page.NotDone() { - return VirtualMachineScaleSetVM{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualMachineScaleSetVMListResultIterator type. -func NewVirtualMachineScaleSetVMListResultIterator(page VirtualMachineScaleSetVMListResultPage) VirtualMachineScaleSetVMListResultIterator { - return VirtualMachineScaleSetVMListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vmssvlr VirtualMachineScaleSetVMListResult) IsEmpty() bool { - return vmssvlr.Value == nil || len(*vmssvlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vmssvlr VirtualMachineScaleSetVMListResult) hasNextLink() bool { - return vmssvlr.NextLink != nil && len(*vmssvlr.NextLink) != 0 -} - -// virtualMachineScaleSetVMListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vmssvlr VirtualMachineScaleSetVMListResult) virtualMachineScaleSetVMListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vmssvlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vmssvlr.NextLink))) -} - -// VirtualMachineScaleSetVMListResultPage contains a page of VirtualMachineScaleSetVM values. -type VirtualMachineScaleSetVMListResultPage struct { - fn func(context.Context, VirtualMachineScaleSetVMListResult) (VirtualMachineScaleSetVMListResult, error) - vmssvlr VirtualMachineScaleSetVMListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetVMListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vmssvlr) - if err != nil { - return err - } - page.vmssvlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetVMListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetVMListResultPage) NotDone() bool { - return !page.vmssvlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetVMListResultPage) Response() VirtualMachineScaleSetVMListResult { - return page.vmssvlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetVMListResultPage) Values() []VirtualMachineScaleSetVM { - if page.vmssvlr.IsEmpty() { - return nil - } - return *page.vmssvlr.Value -} - -// Creates a new instance of the VirtualMachineScaleSetVMListResultPage type. -func NewVirtualMachineScaleSetVMListResultPage(cur VirtualMachineScaleSetVMListResult, getNextPage func(context.Context, VirtualMachineScaleSetVMListResult) (VirtualMachineScaleSetVMListResult, error)) VirtualMachineScaleSetVMListResultPage { - return VirtualMachineScaleSetVMListResultPage{ - fn: getNextPage, - vmssvlr: cur, - } -} - -// VirtualMachineScaleSetVMProfile describes a virtual machine scale set virtual machine profile. -type VirtualMachineScaleSetVMProfile struct { - // OsProfile - Specifies the operating system settings for the virtual machines in the scale set. - OsProfile *VirtualMachineScaleSetOSProfile `json:"osProfile,omitempty"` - // StorageProfile - Specifies the storage settings for the virtual machine disks. - StorageProfile *VirtualMachineScaleSetStorageProfile `json:"storageProfile,omitempty"` - // AdditionalCapabilities - Specifies additional capabilities enabled or disabled on the virtual machine in the scale set. For instance: whether the virtual machine has the capability to support attaching managed data disks with UltraSSD_LRS storage account type. - AdditionalCapabilities *AdditionalCapabilities `json:"additionalCapabilities,omitempty"` - // NetworkProfile - Specifies properties of the network interfaces of the virtual machines in the scale set. - NetworkProfile *VirtualMachineScaleSetNetworkProfile `json:"networkProfile,omitempty"` - // DiagnosticsProfile - Specifies the boot diagnostic settings state.

      Minimum api-version: 2015-06-15. - DiagnosticsProfile *DiagnosticsProfile `json:"diagnosticsProfile,omitempty"` - // ExtensionProfile - Specifies a collection of settings for extensions installed on virtual machines in the scale set. - ExtensionProfile *VirtualMachineScaleSetExtensionProfile `json:"extensionProfile,omitempty"` - // LicenseType - Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system.

      Possible values are:

      Windows_Client

      Windows_Server

      If this element is included in a request for an update, the value must match the initial value. This value cannot be updated.

      For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)

      Minimum api-version: 2015-06-15 - LicenseType *string `json:"licenseType,omitempty"` - // Priority - Specifies the priority for the virtual machines in the scale set.

      Minimum api-version: 2017-10-30-preview. Possible values include: 'Regular', 'Low' - Priority VirtualMachinePriorityTypes `json:"priority,omitempty"` - // EvictionPolicy - Specifies the eviction policy for virtual machines in a low priority scale set.

      Minimum api-version: 2017-10-30-preview. Possible values include: 'Deallocate', 'Delete' - EvictionPolicy VirtualMachineEvictionPolicyTypes `json:"evictionPolicy,omitempty"` -} - -// VirtualMachineScaleSetVMProperties describes the properties of a virtual machine scale set virtual -// machine. -type VirtualMachineScaleSetVMProperties struct { - // LatestModelApplied - READ-ONLY; Specifies whether the latest model has been applied to the virtual machine. - LatestModelApplied *bool `json:"latestModelApplied,omitempty"` - // VMID - READ-ONLY; Azure VM unique ID. - VMID *string `json:"vmId,omitempty"` - // InstanceView - READ-ONLY; The virtual machine instance view. - InstanceView *VirtualMachineScaleSetVMInstanceView `json:"instanceView,omitempty"` - // HardwareProfile - Specifies the hardware settings for the virtual machine. - HardwareProfile *HardwareProfile `json:"hardwareProfile,omitempty"` - // StorageProfile - Specifies the storage settings for the virtual machine disks. - StorageProfile *StorageProfile `json:"storageProfile,omitempty"` - // AdditionalCapabilities - Specifies additional capabilities enabled or disabled on the virtual machine in the scale set. For instance: whether the virtual machine has the capability to support attaching managed data disks with UltraSSD_LRS storage account type. - AdditionalCapabilities *AdditionalCapabilities `json:"additionalCapabilities,omitempty"` - // OsProfile - Specifies the operating system settings for the virtual machine. - OsProfile *OSProfile `json:"osProfile,omitempty"` - // NetworkProfile - Specifies the network interfaces of the virtual machine. - NetworkProfile *NetworkProfile `json:"networkProfile,omitempty"` - // DiagnosticsProfile - Specifies the boot diagnostic settings state.

      Minimum api-version: 2015-06-15. - DiagnosticsProfile *DiagnosticsProfile `json:"diagnosticsProfile,omitempty"` - // AvailabilitySet - Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see [Manage the availability of virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).

      For more information on Azure planned maintenance, see [Planned maintenance for virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)

      Currently, a VM can only be added to availability set at creation time. An existing VM cannot be added to an availability set. - AvailabilitySet *SubResource `json:"availabilitySet,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state, which only appears in the response. - ProvisioningState *string `json:"provisioningState,omitempty"` - // LicenseType - Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system.

      Possible values are:

      Windows_Client

      Windows_Server

      If this element is included in a request for an update, the value must match the initial value. This value cannot be updated.

      For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)

      Minimum api-version: 2015-06-15 - LicenseType *string `json:"licenseType,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineScaleSetVMProperties. -func (vmssvp VirtualMachineScaleSetVMProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmssvp.HardwareProfile != nil { - objectMap["hardwareProfile"] = vmssvp.HardwareProfile - } - if vmssvp.StorageProfile != nil { - objectMap["storageProfile"] = vmssvp.StorageProfile - } - if vmssvp.AdditionalCapabilities != nil { - objectMap["additionalCapabilities"] = vmssvp.AdditionalCapabilities - } - if vmssvp.OsProfile != nil { - objectMap["osProfile"] = vmssvp.OsProfile - } - if vmssvp.NetworkProfile != nil { - objectMap["networkProfile"] = vmssvp.NetworkProfile - } - if vmssvp.DiagnosticsProfile != nil { - objectMap["diagnosticsProfile"] = vmssvp.DiagnosticsProfile - } - if vmssvp.AvailabilitySet != nil { - objectMap["availabilitySet"] = vmssvp.AvailabilitySet - } - if vmssvp.LicenseType != nil { - objectMap["licenseType"] = vmssvp.LicenseType - } - return json.Marshal(objectMap) -} - -// VirtualMachineScaleSetVMReimageParameters describes a Virtual Machine Scale Set VM Reimage Parameters. -type VirtualMachineScaleSetVMReimageParameters struct { - // TempDisk - Specifies whether to reimage temp disk. Default value: false. Note: This temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS disk. - TempDisk *bool `json:"tempDisk,omitempty"` -} - -// VirtualMachineScaleSetVMsDeallocateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsDeallocateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsDeallocateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsDeallocateFuture.Result. -func (future *VirtualMachineScaleSetVMsDeallocateFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsDeallocateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsDeallocateFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsDeleteFuture.Result. -func (future *VirtualMachineScaleSetVMsDeleteFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsPerformMaintenanceFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualMachineScaleSetVMsPerformMaintenanceFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsPerformMaintenanceFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsPerformMaintenanceFuture.Result. -func (future *VirtualMachineScaleSetVMsPerformMaintenanceFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsPerformMaintenanceFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsPerformMaintenanceFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsPowerOffFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsPowerOffFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsPowerOffFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsPowerOffFuture.Result. -func (future *VirtualMachineScaleSetVMsPowerOffFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsPowerOffFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsPowerOffFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsRedeployFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsRedeployFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsRedeployFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsRedeployFuture.Result. -func (future *VirtualMachineScaleSetVMsRedeployFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRedeployFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRedeployFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsReimageAllFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsReimageAllFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsReimageAllFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsReimageAllFuture.Result. -func (future *VirtualMachineScaleSetVMsReimageAllFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsReimageAllFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsReimageAllFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsReimageFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsReimageFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsReimageFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsReimageFuture.Result. -func (future *VirtualMachineScaleSetVMsReimageFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsReimageFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsReimageFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsRestartFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsRestartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsRestartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsRestartFuture.Result. -func (future *VirtualMachineScaleSetVMsRestartFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRestartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRestartFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsRunCommandFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsRunCommandFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (RunCommandResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsRunCommandFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsRunCommandFuture.Result. -func (future *VirtualMachineScaleSetVMsRunCommandFuture) result(client VirtualMachineScaleSetVMsClient) (rcr RunCommandResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRunCommandFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rcr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsRunCommandFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rcr.Response.Response, err = future.GetResult(sender); err == nil && rcr.Response.Response.StatusCode != http.StatusNoContent { - rcr, err = client.RunCommandResponder(rcr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsRunCommandFuture", "Result", rcr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachineScaleSetVMsStartFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsStartFuture.Result. -func (future *VirtualMachineScaleSetVMsStartFuture) result(client VirtualMachineScaleSetVMsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsStartFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineScaleSetVMsUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachineScaleSetVMsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachineScaleSetVMsClient) (VirtualMachineScaleSetVM, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachineScaleSetVMsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachineScaleSetVMsUpdateFuture.Result. -func (future *VirtualMachineScaleSetVMsUpdateFuture) result(client VirtualMachineScaleSetVMsClient) (vmssv VirtualMachineScaleSetVM, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vmssv.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachineScaleSetVMsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vmssv.Response.Response, err = future.GetResult(sender); err == nil && vmssv.Response.Response.StatusCode != http.StatusNoContent { - vmssv, err = client.UpdateResponder(vmssv.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsUpdateFuture", "Result", vmssv.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachinesCaptureFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (VirtualMachineCaptureResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesCaptureFuture.Result. -func (future *VirtualMachinesCaptureFuture) result(client VirtualMachinesClient) (vmcr VirtualMachineCaptureResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vmcr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vmcr.Response.Response, err = future.GetResult(sender); err == nil && vmcr.Response.Response.StatusCode != http.StatusNoContent { - vmcr, err = client.CaptureResponder(vmcr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesCaptureFuture", "Result", vmcr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachinesConvertToManagedDisksFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachinesConvertToManagedDisksFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesConvertToManagedDisksFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesConvertToManagedDisksFuture.Result. -func (future *VirtualMachinesConvertToManagedDisksFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesConvertToManagedDisksFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesConvertToManagedDisksFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachinesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachinesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (VirtualMachine, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesCreateOrUpdateFuture.Result. -func (future *VirtualMachinesCreateOrUpdateFuture) result(client VirtualMachinesClient) (VM VirtualMachine, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - VM.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if VM.Response.Response, err = future.GetResult(sender); err == nil && VM.Response.Response.StatusCode != http.StatusNoContent { - VM, err = client.CreateOrUpdateResponder(VM.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesCreateOrUpdateFuture", "Result", VM.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachinesDeallocateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachinesDeallocateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesDeallocateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesDeallocateFuture.Result. -func (future *VirtualMachinesDeallocateFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesDeallocateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesDeallocateFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachinesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesDeleteFuture.Result. -func (future *VirtualMachinesDeleteFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineSize describes the properties of a VM size. -type VirtualMachineSize struct { - // Name - The name of the virtual machine size. - Name *string `json:"name,omitempty"` - // NumberOfCores - The number of cores supported by the virtual machine size. - NumberOfCores *int32 `json:"numberOfCores,omitempty"` - // OsDiskSizeInMB - The OS disk size, in MB, allowed by the virtual machine size. - OsDiskSizeInMB *int32 `json:"osDiskSizeInMB,omitempty"` - // ResourceDiskSizeInMB - The resource disk size, in MB, allowed by the virtual machine size. - ResourceDiskSizeInMB *int32 `json:"resourceDiskSizeInMB,omitempty"` - // MemoryInMB - The amount of memory, in MB, supported by the virtual machine size. - MemoryInMB *int32 `json:"memoryInMB,omitempty"` - // MaxDataDiskCount - The maximum number of data disks that can be attached to the virtual machine size. - MaxDataDiskCount *int32 `json:"maxDataDiskCount,omitempty"` -} - -// VirtualMachineSizeListResult the List Virtual Machine operation response. -type VirtualMachineSizeListResult struct { - autorest.Response `json:"-"` - // Value - The list of virtual machine sizes. - Value *[]VirtualMachineSize `json:"value,omitempty"` -} - -// VirtualMachinesPerformMaintenanceFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachinesPerformMaintenanceFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesPerformMaintenanceFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesPerformMaintenanceFuture.Result. -func (future *VirtualMachinesPerformMaintenanceFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesPerformMaintenanceFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesPerformMaintenanceFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachinesPowerOffFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesPowerOffFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesPowerOffFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesPowerOffFuture.Result. -func (future *VirtualMachinesPowerOffFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesPowerOffFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesPowerOffFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachinesRedeployFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesRedeployFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesRedeployFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesRedeployFuture.Result. -func (future *VirtualMachinesRedeployFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesRedeployFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesRedeployFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachinesReimageFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesReimageFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesReimageFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesReimageFuture.Result. -func (future *VirtualMachinesReimageFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesReimageFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesReimageFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachinesRestartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesRestartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesRestartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesRestartFuture.Result. -func (future *VirtualMachinesRestartFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesRestartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesRestartFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachinesRunCommandFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualMachinesRunCommandFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (RunCommandResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesRunCommandFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesRunCommandFuture.Result. -func (future *VirtualMachinesRunCommandFuture) result(client VirtualMachinesClient) (rcr RunCommandResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesRunCommandFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rcr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesRunCommandFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rcr.Response.Response, err = future.GetResult(sender); err == nil && rcr.Response.Response.StatusCode != http.StatusNoContent { - rcr, err = client.RunCommandResponder(rcr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesRunCommandFuture", "Result", rcr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachinesStartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesStartFuture.Result. -func (future *VirtualMachinesStartFuture) result(client VirtualMachinesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesStartFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualMachineStatusCodeCount the status code and count of the virtual machine scale set instance view -// status summary. -type VirtualMachineStatusCodeCount struct { - // Code - READ-ONLY; The instance view status code. - Code *string `json:"code,omitempty"` - // Count - READ-ONLY; The number of instances having a particular status code. - Count *int32 `json:"count,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineStatusCodeCount. -func (vmscc VirtualMachineStatusCodeCount) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualMachinesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualMachinesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualMachinesClient) (VirtualMachine, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualMachinesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualMachinesUpdateFuture.Result. -func (future *VirtualMachinesUpdateFuture) result(client VirtualMachinesClient) (VM VirtualMachine, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - VM.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("compute.VirtualMachinesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if VM.Response.Response, err = future.GetResult(sender); err == nil && VM.Response.Response.StatusCode != http.StatusNoContent { - VM, err = client.UpdateResponder(VM.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesUpdateFuture", "Result", VM.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualMachineUpdate describes a Virtual Machine Update. -type VirtualMachineUpdate struct { - // Plan - Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. - Plan *Plan `json:"plan,omitempty"` - *VirtualMachineProperties `json:"properties,omitempty"` - // Identity - The identity of the virtual machine, if configured. - Identity *VirtualMachineIdentity `json:"identity,omitempty"` - // Zones - The virtual machine zones. - Zones *[]string `json:"zones,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualMachineUpdate. -func (vmu VirtualMachineUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vmu.Plan != nil { - objectMap["plan"] = vmu.Plan - } - if vmu.VirtualMachineProperties != nil { - objectMap["properties"] = vmu.VirtualMachineProperties - } - if vmu.Identity != nil { - objectMap["identity"] = vmu.Identity - } - if vmu.Zones != nil { - objectMap["zones"] = vmu.Zones - } - if vmu.Tags != nil { - objectMap["tags"] = vmu.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualMachineUpdate struct. -func (vmu *VirtualMachineUpdate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "plan": - if v != nil { - var plan Plan - err = json.Unmarshal(*v, &plan) - if err != nil { - return err - } - vmu.Plan = &plan - } - case "properties": - if v != nil { - var virtualMachineProperties VirtualMachineProperties - err = json.Unmarshal(*v, &virtualMachineProperties) - if err != nil { - return err - } - vmu.VirtualMachineProperties = &virtualMachineProperties - } - case "identity": - if v != nil { - var identity VirtualMachineIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - vmu.Identity = &identity - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - vmu.Zones = &zones - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vmu.Tags = tags - } - } - } - - return nil -} - -// WindowsConfiguration specifies Windows operating system settings on the virtual machine. -type WindowsConfiguration struct { - // ProvisionVMAgent - Indicates whether virtual machine agent should be provisioned on the virtual machine.

      When this property is not specified in the request body, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later. - ProvisionVMAgent *bool `json:"provisionVMAgent,omitempty"` - // EnableAutomaticUpdates - Indicates whether virtual machine is enabled for automatic Windows updates. Default value is true.

      For virtual machine scale sets, this property can be updated and updates will take effect on OS reprovisioning. - EnableAutomaticUpdates *bool `json:"enableAutomaticUpdates,omitempty"` - // TimeZone - Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time" - TimeZone *string `json:"timeZone,omitempty"` - // AdditionalUnattendContent - Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup. - AdditionalUnattendContent *[]AdditionalUnattendContent `json:"additionalUnattendContent,omitempty"` - // WinRM - Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell. - WinRM *WinRMConfiguration `json:"winRM,omitempty"` -} - -// WinRMConfiguration describes Windows Remote Management configuration of the VM -type WinRMConfiguration struct { - // Listeners - The list of Windows Remote Management listeners - Listeners *[]WinRMListener `json:"listeners,omitempty"` -} - -// WinRMListener describes Protocol and thumbprint of Windows Remote Management listener -type WinRMListener struct { - // Protocol - Specifies the protocol of listener.

      Possible values are:
      **http**

      **https**. Possible values include: 'HTTP', 'HTTPS' - Protocol ProtocolTypes `json:"protocol,omitempty"` - // CertificateURL - This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8:

      {
      "data":"",
      "dataType":"pfx",
      "password":""
      } - CertificateURL *string `json:"certificateUrl,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/operations.go deleted file mode 100644 index 72f4ddf52..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/operations.go +++ /dev/null @@ -1,98 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// OperationsClient is the compute Client -type OperationsClient struct { - BaseClient -} - -// NewOperationsClient creates an instance of the OperationsClient client. -func NewOperationsClient(subscriptionID string) OperationsClient { - return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets a list of compute operations. -func (client OperationsClient) List(ctx context.Context) (result OperationListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.OperationsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.OperationsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Compute/operations"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/proximityplacementgroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/proximityplacementgroups.go deleted file mode 100644 index 2a495e27e..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/proximityplacementgroups.go +++ /dev/null @@ -1,570 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ProximityPlacementGroupsClient is the compute Client -type ProximityPlacementGroupsClient struct { - BaseClient -} - -// NewProximityPlacementGroupsClient creates an instance of the ProximityPlacementGroupsClient client. -func NewProximityPlacementGroupsClient(subscriptionID string) ProximityPlacementGroupsClient { - return NewProximityPlacementGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewProximityPlacementGroupsClientWithBaseURI creates an instance of the ProximityPlacementGroupsClient client using -// a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewProximityPlacementGroupsClientWithBaseURI(baseURI string, subscriptionID string) ProximityPlacementGroupsClient { - return ProximityPlacementGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a proximity placement group. -// Parameters: -// resourceGroupName - the name of the resource group. -// proximityPlacementGroupName - the name of the proximity placement group. -// parameters - parameters supplied to the Create Proximity Placement Group operation. -func (client ProximityPlacementGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroup) (result ProximityPlacementGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, proximityPlacementGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ProximityPlacementGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "proximityPlacementGroupName": autorest.Encode("path", proximityPlacementGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ProximityPlacementGroupsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ProximityPlacementGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result ProximityPlacementGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete a proximity placement group. -// Parameters: -// resourceGroupName - the name of the resource group. -// proximityPlacementGroupName - the name of the proximity placement group. -func (client ProximityPlacementGroupsClient) Delete(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, proximityPlacementGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ProximityPlacementGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "proximityPlacementGroupName": autorest.Encode("path", proximityPlacementGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ProximityPlacementGroupsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ProximityPlacementGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves information about a proximity placement group . -// Parameters: -// resourceGroupName - the name of the resource group. -// proximityPlacementGroupName - the name of the proximity placement group. -func (client ProximityPlacementGroupsClient) Get(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string) (result ProximityPlacementGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, proximityPlacementGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ProximityPlacementGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "proximityPlacementGroupName": autorest.Encode("path", proximityPlacementGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ProximityPlacementGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ProximityPlacementGroupsClient) GetResponder(resp *http.Response) (result ProximityPlacementGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup lists all proximity placement groups in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ProximityPlacementGroupsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ProximityPlacementGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.ppglr.Response.Response != nil { - sc = result.ppglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.ppglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.ppglr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.ppglr.hasNextLink() && result.ppglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ProximityPlacementGroupsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ProximityPlacementGroupsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ProximityPlacementGroupsClient) ListByResourceGroupResponder(resp *http.Response) (result ProximityPlacementGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ProximityPlacementGroupsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ProximityPlacementGroupListResult) (result ProximityPlacementGroupListResult, err error) { - req, err := lastResults.proximityPlacementGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProximityPlacementGroupsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ProximityPlacementGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// ListBySubscription lists all proximity placement groups in a subscription. -func (client ProximityPlacementGroupsClient) ListBySubscription(ctx context.Context) (result ProximityPlacementGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.ListBySubscription") - defer func() { - sc := -1 - if result.ppglr.Response.Response != nil { - sc = result.ppglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.ppglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.ppglr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.ppglr.hasNextLink() && result.ppglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client ProximityPlacementGroupsClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/proximityPlacementGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client ProximityPlacementGroupsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client ProximityPlacementGroupsClient) ListBySubscriptionResponder(resp *http.Response) (result ProximityPlacementGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client ProximityPlacementGroupsClient) listBySubscriptionNextResults(ctx context.Context, lastResults ProximityPlacementGroupListResult) (result ProximityPlacementGroupListResult, err error) { - req, err := lastResults.proximityPlacementGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProximityPlacementGroupsClient) ListBySubscriptionComplete(ctx context.Context) (result ProximityPlacementGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} - -// Update update a proximity placement group. -// Parameters: -// resourceGroupName - the name of the resource group. -// proximityPlacementGroupName - the name of the proximity placement group. -// parameters - parameters supplied to the Update Proximity Placement Group operation. -func (client ProximityPlacementGroupsClient) Update(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroupUpdate) (result ProximityPlacementGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProximityPlacementGroupsClient.Update") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, proximityPlacementGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ProximityPlacementGroupsClient", "Update", resp, "Failure responding to request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ProximityPlacementGroupsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, proximityPlacementGroupName string, parameters ProximityPlacementGroupUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "proximityPlacementGroupName": autorest.Encode("path", proximityPlacementGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/proximityPlacementGroups/{proximityPlacementGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client ProximityPlacementGroupsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ProximityPlacementGroupsClient) UpdateResponder(resp *http.Response) (result ProximityPlacementGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/resourceskus.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/resourceskus.go deleted file mode 100644 index f42e100fc..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/resourceskus.go +++ /dev/null @@ -1,144 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ResourceSkusClient is the compute Client -type ResourceSkusClient struct { - BaseClient -} - -// NewResourceSkusClient creates an instance of the ResourceSkusClient client. -func NewResourceSkusClient(subscriptionID string) ResourceSkusClient { - return NewResourceSkusClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewResourceSkusClientWithBaseURI creates an instance of the ResourceSkusClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewResourceSkusClientWithBaseURI(baseURI string, subscriptionID string) ResourceSkusClient { - return ResourceSkusClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets the list of Microsoft.Compute SKUs available for your Subscription. -func (client ResourceSkusClient) List(ctx context.Context) (result ResourceSkusResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkusClient.List") - defer func() { - sc := -1 - if result.rsr.Response.Response != nil { - sc = result.rsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ResourceSkusClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.ResourceSkusClient", "List", resp, "Failure sending request") - return - } - - result.rsr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ResourceSkusClient", "List", resp, "Failure responding to request") - return - } - if result.rsr.hasNextLink() && result.rsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ResourceSkusClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/skus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ResourceSkusClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ResourceSkusClient) ListResponder(resp *http.Response) (result ResourceSkusResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ResourceSkusClient) listNextResults(ctx context.Context, lastResults ResourceSkusResult) (result ResourceSkusResult, err error) { - req, err := lastResults.resourceSkusResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.ResourceSkusClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.ResourceSkusClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.ResourceSkusClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ResourceSkusClient) ListComplete(ctx context.Context) (result ResourceSkusResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkusClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/snapshots.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/snapshots.go deleted file mode 100644 index d93683fa7..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/snapshots.go +++ /dev/null @@ -1,773 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SnapshotsClient is the compute Client -type SnapshotsClient struct { - BaseClient -} - -// NewSnapshotsClient creates an instance of the SnapshotsClient client. -func NewSnapshotsClient(subscriptionID string) SnapshotsClient { - return NewSnapshotsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSnapshotsClientWithBaseURI creates an instance of the SnapshotsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSnapshotsClientWithBaseURI(baseURI string, subscriptionID string) SnapshotsClient { - return SnapshotsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a snapshot. -// Parameters: -// resourceGroupName - the name of the resource group. -// snapshotName - the name of the snapshot that is being created. The name can't be changed after the snapshot -// is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. -// snapshot - snapshot object supplied in the body of the Put disk operation. -func (client SnapshotsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot) (result SnapshotsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: snapshot, - Constraints: []validation.Constraint{{Target: "snapshot.SnapshotProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "snapshot.SnapshotProperties.CreationData", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "snapshot.SnapshotProperties.CreationData.ImageReference", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "snapshot.SnapshotProperties.CreationData.ImageReference.ID", Name: validation.Null, Rule: true, Chain: nil}}}, - }}, - {Target: "snapshot.SnapshotProperties.EncryptionSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "snapshot.SnapshotProperties.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "snapshot.SnapshotProperties.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "snapshot.SnapshotProperties.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "snapshot.SnapshotProperties.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "snapshot.SnapshotProperties.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "snapshot.SnapshotProperties.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("compute.SnapshotsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, snapshotName, snapshot) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SnapshotsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, snapshotName string, snapshot Snapshot) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - snapshot.ManagedBy = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), - autorest.WithJSON(snapshot), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) CreateOrUpdateSender(req *http.Request) (future SnapshotsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) CreateOrUpdateResponder(resp *http.Response) (result Snapshot, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a snapshot. -// Parameters: -// resourceGroupName - the name of the resource group. -// snapshotName - the name of the snapshot that is being created. The name can't be changed after the snapshot -// is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. -func (client SnapshotsClient) Delete(ctx context.Context, resourceGroupName string, snapshotName string) (result SnapshotsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SnapshotsClient) DeletePreparer(ctx context.Context, resourceGroupName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) DeleteSender(req *http.Request) (future SnapshotsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about a snapshot. -// Parameters: -// resourceGroupName - the name of the resource group. -// snapshotName - the name of the snapshot that is being created. The name can't be changed after the snapshot -// is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. -func (client SnapshotsClient) Get(ctx context.Context, resourceGroupName string, snapshotName string) (result Snapshot, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SnapshotsClient) GetPreparer(ctx context.Context, resourceGroupName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) GetResponder(resp *http.Response) (result Snapshot, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GrantAccess grants access to a snapshot. -// Parameters: -// resourceGroupName - the name of the resource group. -// snapshotName - the name of the snapshot that is being created. The name can't be changed after the snapshot -// is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. -// grantAccessData - access data object supplied in the body of the get snapshot access operation. -func (client SnapshotsClient) GrantAccess(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData) (result SnapshotsGrantAccessFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.GrantAccess") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: grantAccessData, - Constraints: []validation.Constraint{{Target: "grantAccessData.DurationInSeconds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.SnapshotsClient", "GrantAccess", err.Error()) - } - - req, err := client.GrantAccessPreparer(ctx, resourceGroupName, snapshotName, grantAccessData) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "GrantAccess", nil, "Failure preparing request") - return - } - - result, err = client.GrantAccessSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "GrantAccess", result.Response(), "Failure sending request") - return - } - - return -} - -// GrantAccessPreparer prepares the GrantAccess request. -func (client SnapshotsClient) GrantAccessPreparer(ctx context.Context, resourceGroupName string, snapshotName string, grantAccessData GrantAccessData) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/beginGetAccess", pathParameters), - autorest.WithJSON(grantAccessData), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GrantAccessSender sends the GrantAccess request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) GrantAccessSender(req *http.Request) (future SnapshotsGrantAccessFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GrantAccessResponder handles the response to the GrantAccess request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) GrantAccessResponder(resp *http.Response) (result AccessURI, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists snapshots under a subscription. -func (client SnapshotsClient) List(ctx context.Context) (result SnapshotListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.List") - defer func() { - sc := -1 - if result.sl.Response.Response != nil { - sc = result.sl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.sl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "List", resp, "Failure sending request") - return - } - - result.sl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "List", resp, "Failure responding to request") - return - } - if result.sl.hasNextLink() && result.sl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SnapshotsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/snapshots", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) ListResponder(resp *http.Response) (result SnapshotList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client SnapshotsClient) listNextResults(ctx context.Context, lastResults SnapshotList) (result SnapshotList, err error) { - req, err := lastResults.snapshotListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.SnapshotsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.SnapshotsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SnapshotsClient) ListComplete(ctx context.Context) (result SnapshotListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists snapshots under a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client SnapshotsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result SnapshotListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.sl.Response.Response != nil { - sc = result.sl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.sl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.sl, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.sl.hasNextLink() && result.sl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client SnapshotsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) ListByResourceGroupResponder(resp *http.Response) (result SnapshotList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client SnapshotsClient) listByResourceGroupNextResults(ctx context.Context, lastResults SnapshotList) (result SnapshotList, err error) { - req, err := lastResults.snapshotListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.SnapshotsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.SnapshotsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client SnapshotsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result SnapshotListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// RevokeAccess revokes access to a snapshot. -// Parameters: -// resourceGroupName - the name of the resource group. -// snapshotName - the name of the snapshot that is being created. The name can't be changed after the snapshot -// is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. -func (client SnapshotsClient) RevokeAccess(ctx context.Context, resourceGroupName string, snapshotName string) (result SnapshotsRevokeAccessFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.RevokeAccess") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RevokeAccessPreparer(ctx, resourceGroupName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "RevokeAccess", nil, "Failure preparing request") - return - } - - result, err = client.RevokeAccessSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "RevokeAccess", result.Response(), "Failure sending request") - return - } - - return -} - -// RevokeAccessPreparer prepares the RevokeAccess request. -func (client SnapshotsClient) RevokeAccessPreparer(ctx context.Context, resourceGroupName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/endGetAccess", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RevokeAccessSender sends the RevokeAccess request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) RevokeAccessSender(req *http.Request) (future SnapshotsRevokeAccessFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RevokeAccessResponder handles the response to the RevokeAccess request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) RevokeAccessResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update updates (patches) a snapshot. -// Parameters: -// resourceGroupName - the name of the resource group. -// snapshotName - the name of the snapshot that is being created. The name can't be changed after the snapshot -// is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. -// snapshot - snapshot object supplied in the body of the Patch snapshot operation. -func (client SnapshotsClient) Update(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate) (result SnapshotsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, snapshotName, snapshot) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.SnapshotsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client SnapshotsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, snapshotName string, snapshot SnapshotUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}", pathParameters), - autorest.WithJSON(snapshot), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) UpdateSender(req *http.Request) (future SnapshotsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) UpdateResponder(resp *http.Response) (result Snapshot, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/usage.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/usage.go deleted file mode 100644 index 5da784bce..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/usage.go +++ /dev/null @@ -1,155 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// UsageClient is the compute Client -type UsageClient struct { - BaseClient -} - -// NewUsageClient creates an instance of the UsageClient client. -func NewUsageClient(subscriptionID string) UsageClient { - return NewUsageClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewUsageClientWithBaseURI creates an instance of the UsageClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClient { - return UsageClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets, for the specified location, the current compute resource usage information as well as the limits for -// compute resources under the subscription. -// Parameters: -// location - the location for which resource usage is queried. -func (client UsageClient) List(ctx context.Context, location string) (result ListUsagesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsageClient.List") - defer func() { - sc := -1 - if result.lur.Response.Response != nil { - sc = result.lur.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.UsageClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.UsageClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lur.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.UsageClient", "List", resp, "Failure sending request") - return - } - - result.lur, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.UsageClient", "List", resp, "Failure responding to request") - return - } - if result.lur.hasNextLink() && result.lur.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client UsageClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client UsageClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client UsageClient) ListResponder(resp *http.Response) (result ListUsagesResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client UsageClient) listNextResults(ctx context.Context, lastResults ListUsagesResult) (result ListUsagesResult, err error) { - req, err := lastResults.listUsagesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.UsageClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.UsageClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.UsageClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client UsageClient) ListComplete(ctx context.Context, location string) (result ListUsagesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsageClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/version.go deleted file mode 100644 index 986a65475..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package compute - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// UserAgent returns the UserAgent string to use when sending http.Requests. -func UserAgent() string { - return "Azure-SDK-For-Go/" + Version() + " compute/2018-10-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineextensionimages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineextensionimages.go deleted file mode 100644 index d389b76c3..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineextensionimages.go +++ /dev/null @@ -1,270 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineExtensionImagesClient is the compute Client -type VirtualMachineExtensionImagesClient struct { - BaseClient -} - -// NewVirtualMachineExtensionImagesClient creates an instance of the VirtualMachineExtensionImagesClient client. -func NewVirtualMachineExtensionImagesClient(subscriptionID string) VirtualMachineExtensionImagesClient { - return NewVirtualMachineExtensionImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineExtensionImagesClientWithBaseURI creates an instance of the VirtualMachineExtensionImagesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineExtensionImagesClient { - return VirtualMachineExtensionImagesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets a virtual machine extension image. -// Parameters: -// location - the name of a supported Azure region. -func (client VirtualMachineExtensionImagesClient) Get(ctx context.Context, location string, publisherName string, typeParameter string, version string) (result VirtualMachineExtensionImage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionImagesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, location, publisherName, typeParameter, version) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachineExtensionImagesClient) GetPreparer(ctx context.Context, location string, publisherName string, typeParameter string, version string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "publisherName": autorest.Encode("path", publisherName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "type": autorest.Encode("path", typeParameter), - "version": autorest.Encode("path", version), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions/{version}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionImagesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionImagesClient) GetResponder(resp *http.Response) (result VirtualMachineExtensionImage, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListTypes gets a list of virtual machine extension image types. -// Parameters: -// location - the name of a supported Azure region. -func (client VirtualMachineExtensionImagesClient) ListTypes(ctx context.Context, location string, publisherName string) (result ListVirtualMachineExtensionImage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionImagesClient.ListTypes") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListTypesPreparer(ctx, location, publisherName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", nil, "Failure preparing request") - return - } - - resp, err := client.ListTypesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure sending request") - return - } - - result, err = client.ListTypesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure responding to request") - return - } - - return -} - -// ListTypesPreparer prepares the ListTypes request. -func (client VirtualMachineExtensionImagesClient) ListTypesPreparer(ctx context.Context, location string, publisherName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "publisherName": autorest.Encode("path", publisherName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListTypesSender sends the ListTypes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionImagesClient) ListTypesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListTypesResponder handles the response to the ListTypes request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http.Response) (result ListVirtualMachineExtensionImage, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListVersions gets a list of virtual machine extension image versions. -// Parameters: -// location - the name of a supported Azure region. -// filter - the filter to apply on the operation. -func (client VirtualMachineExtensionImagesClient) ListVersions(ctx context.Context, location string, publisherName string, typeParameter string, filter string, top *int32, orderby string) (result ListVirtualMachineExtensionImage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionImagesClient.ListVersions") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListVersionsPreparer(ctx, location, publisherName, typeParameter, filter, top, orderby) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", nil, "Failure preparing request") - return - } - - resp, err := client.ListVersionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure sending request") - return - } - - result, err = client.ListVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure responding to request") - return - } - - return -} - -// ListVersionsPreparer prepares the ListVersions request. -func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(ctx context.Context, location string, publisherName string, typeParameter string, filter string, top *int32, orderby string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "publisherName": autorest.Encode("path", publisherName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "type": autorest.Encode("path", typeParameter), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderby) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderby) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVersionsSender sends the ListVersions request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionImagesClient) ListVersionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVersionsResponder handles the response to the ListVersions request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionImagesClient) ListVersionsResponder(resp *http.Response) (result ListVirtualMachineExtensionImage, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineextensions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineextensions.go deleted file mode 100644 index 2fab31afa..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineextensions.go +++ /dev/null @@ -1,442 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineExtensionsClient is the compute Client -type VirtualMachineExtensionsClient struct { - BaseClient -} - -// NewVirtualMachineExtensionsClient creates an instance of the VirtualMachineExtensionsClient client. -func NewVirtualMachineExtensionsClient(subscriptionID string) VirtualMachineExtensionsClient { - return NewVirtualMachineExtensionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineExtensionsClientWithBaseURI creates an instance of the VirtualMachineExtensionsClient client using -// a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewVirtualMachineExtensionsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineExtensionsClient { - return VirtualMachineExtensionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate the operation to create or update the extension. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine where the extension should be created or updated. -// VMExtensionName - the name of the virtual machine extension. -// extensionParameters - parameters supplied to the Create Virtual Machine Extension operation. -func (client VirtualMachineExtensionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string, extensionParameters VirtualMachineExtension) (result VirtualMachineExtensionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, VMName, VMExtensionName, extensionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachineExtensionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string, extensionParameters VirtualMachineExtension) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmExtensionName": autorest.Encode("path", VMExtensionName), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", pathParameters), - autorest.WithJSON(extensionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionsClient) CreateOrUpdateSender(req *http.Request) (future VirtualMachineExtensionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineExtension, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete the operation to delete the extension. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine where the extension should be deleted. -// VMExtensionName - the name of the virtual machine extension. -func (client VirtualMachineExtensionsClient) Delete(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string) (result VirtualMachineExtensionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, VMName, VMExtensionName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualMachineExtensionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmExtensionName": autorest.Encode("path", VMExtensionName), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionsClient) DeleteSender(req *http.Request) (future VirtualMachineExtensionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get the operation to get the extension. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine containing the extension. -// VMExtensionName - the name of the virtual machine extension. -// expand - the expand expression to apply on the operation. -func (client VirtualMachineExtensionsClient) Get(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string, expand string) (result VirtualMachineExtension, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, VMName, VMExtensionName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachineExtensionsClient) GetPreparer(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmExtensionName": autorest.Encode("path", VMExtensionName), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionsClient) GetResponder(resp *http.Response) (result VirtualMachineExtension, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List the operation to get all extensions of a Virtual Machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine containing the extension. -// expand - the expand expression to apply on the operation. -func (client VirtualMachineExtensionsClient) List(ctx context.Context, resourceGroupName string, VMName string, expand string) (result VirtualMachineExtensionsListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, VMName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachineExtensionsClient) ListPreparer(ctx context.Context, resourceGroupName string, VMName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionsClient) ListResponder(resp *http.Response) (result VirtualMachineExtensionsListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update the operation to update the extension. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine where the extension should be updated. -// VMExtensionName - the name of the virtual machine extension. -// extensionParameters - parameters supplied to the Update Virtual Machine Extension operation. -func (client VirtualMachineExtensionsClient) Update(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string, extensionParameters VirtualMachineExtensionUpdate) (result VirtualMachineExtensionsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineExtensionsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, VMName, VMExtensionName, extensionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client VirtualMachineExtensionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, VMName string, VMExtensionName string, extensionParameters VirtualMachineExtensionUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmExtensionName": autorest.Encode("path", VMExtensionName), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", pathParameters), - autorest.WithJSON(extensionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineExtensionsClient) UpdateSender(req *http.Request) (future VirtualMachineExtensionsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client VirtualMachineExtensionsClient) UpdateResponder(resp *http.Response) (result VirtualMachineExtension, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineimages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineimages.go deleted file mode 100644 index 59450d69d..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineimages.go +++ /dev/null @@ -1,432 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineImagesClient is the compute Client -type VirtualMachineImagesClient struct { - BaseClient -} - -// NewVirtualMachineImagesClient creates an instance of the VirtualMachineImagesClient client. -func NewVirtualMachineImagesClient(subscriptionID string) VirtualMachineImagesClient { - return NewVirtualMachineImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineImagesClientWithBaseURI creates an instance of the VirtualMachineImagesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewVirtualMachineImagesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineImagesClient { - return VirtualMachineImagesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets a virtual machine image. -// Parameters: -// location - the name of a supported Azure region. -// publisherName - a valid image publisher. -// offer - a valid image publisher offer. -// skus - a valid image SKU. -// version - a valid image SKU version. -func (client VirtualMachineImagesClient) Get(ctx context.Context, location string, publisherName string, offer string, skus string, version string) (result VirtualMachineImage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImagesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, location, publisherName, offer, skus, version) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachineImagesClient) GetPreparer(ctx context.Context, location string, publisherName string, offer string, skus string, version string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "offer": autorest.Encode("path", offer), - "publisherName": autorest.Encode("path", publisherName), - "skus": autorest.Encode("path", skus), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "version": autorest.Encode("path", version), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineImagesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachineImagesClient) GetResponder(resp *http.Response) (result VirtualMachineImage, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets a list of all virtual machine image versions for the specified location, publisher, offer, and SKU. -// Parameters: -// location - the name of a supported Azure region. -// publisherName - a valid image publisher. -// offer - a valid image publisher offer. -// skus - a valid image SKU. -// expand - the expand expression to apply on the operation. -func (client VirtualMachineImagesClient) List(ctx context.Context, location string, publisherName string, offer string, skus string, expand string, top *int32, orderby string) (result ListVirtualMachineImageResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImagesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, location, publisherName, offer, skus, expand, top, orderby) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachineImagesClient) ListPreparer(ctx context.Context, location string, publisherName string, offer string, skus string, expand string, top *int32, orderby string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "offer": autorest.Encode("path", offer), - "publisherName": autorest.Encode("path", publisherName), - "skus": autorest.Encode("path", skus), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderby) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderby) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineImagesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListOffers gets a list of virtual machine image offers for the specified location and publisher. -// Parameters: -// location - the name of a supported Azure region. -// publisherName - a valid image publisher. -func (client VirtualMachineImagesClient) ListOffers(ctx context.Context, location string, publisherName string) (result ListVirtualMachineImageResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImagesClient.ListOffers") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListOffersPreparer(ctx, location, publisherName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", nil, "Failure preparing request") - return - } - - resp, err := client.ListOffersSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure sending request") - return - } - - result, err = client.ListOffersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure responding to request") - return - } - - return -} - -// ListOffersPreparer prepares the ListOffers request. -func (client VirtualMachineImagesClient) ListOffersPreparer(ctx context.Context, location string, publisherName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "publisherName": autorest.Encode("path", publisherName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListOffersSender sends the ListOffers request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineImagesClient) ListOffersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListOffersResponder handles the response to the ListOffers request. The method always -// closes the http.Response Body. -func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListPublishers gets a list of virtual machine image publishers for the specified Azure location. -// Parameters: -// location - the name of a supported Azure region. -func (client VirtualMachineImagesClient) ListPublishers(ctx context.Context, location string) (result ListVirtualMachineImageResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImagesClient.ListPublishers") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPublishersPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", nil, "Failure preparing request") - return - } - - resp, err := client.ListPublishersSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure sending request") - return - } - - result, err = client.ListPublishersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure responding to request") - return - } - - return -} - -// ListPublishersPreparer prepares the ListPublishers request. -func (client VirtualMachineImagesClient) ListPublishersPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListPublishersSender sends the ListPublishers request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineImagesClient) ListPublishersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListPublishersResponder handles the response to the ListPublishers request. The method always -// closes the http.Response Body. -func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListSkus gets a list of virtual machine image SKUs for the specified location, publisher, and offer. -// Parameters: -// location - the name of a supported Azure region. -// publisherName - a valid image publisher. -// offer - a valid image publisher offer. -func (client VirtualMachineImagesClient) ListSkus(ctx context.Context, location string, publisherName string, offer string) (result ListVirtualMachineImageResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImagesClient.ListSkus") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListSkusPreparer(ctx, location, publisherName, offer) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", nil, "Failure preparing request") - return - } - - resp, err := client.ListSkusSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure sending request") - return - } - - result, err = client.ListSkusResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure responding to request") - return - } - - return -} - -// ListSkusPreparer prepares the ListSkus request. -func (client VirtualMachineImagesClient) ListSkusPreparer(ctx context.Context, location string, publisherName string, offer string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "offer": autorest.Encode("path", offer), - "publisherName": autorest.Encode("path", publisherName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSkusSender sends the ListSkus request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineImagesClient) ListSkusSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListSkusResponder handles the response to the ListSkus request. The method always -// closes the http.Response Body. -func (client VirtualMachineImagesClient) ListSkusResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineruncommands.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineruncommands.go deleted file mode 100644 index 0eb5fa414..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachineruncommands.go +++ /dev/null @@ -1,237 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineRunCommandsClient is the compute Client -type VirtualMachineRunCommandsClient struct { - BaseClient -} - -// NewVirtualMachineRunCommandsClient creates an instance of the VirtualMachineRunCommandsClient client. -func NewVirtualMachineRunCommandsClient(subscriptionID string) VirtualMachineRunCommandsClient { - return NewVirtualMachineRunCommandsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineRunCommandsClientWithBaseURI creates an instance of the VirtualMachineRunCommandsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewVirtualMachineRunCommandsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineRunCommandsClient { - return VirtualMachineRunCommandsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets specific run command for a subscription in a location. -// Parameters: -// location - the location upon which run commands is queried. -// commandID - the command id. -func (client VirtualMachineRunCommandsClient) Get(ctx context.Context, location string, commandID string) (result RunCommandDocument, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, location, commandID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachineRunCommandsClient) GetPreparer(ctx context.Context, location string, commandID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "commandId": autorest.Encode("path", commandID), - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands/{commandId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineRunCommandsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachineRunCommandsClient) GetResponder(resp *http.Response) (result RunCommandDocument, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all available run commands for a subscription in a location. -// Parameters: -// location - the location upon which run commands is queried. -func (client VirtualMachineRunCommandsClient) List(ctx context.Context, location string) (result RunCommandListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List") - defer func() { - sc := -1 - if result.rclr.Response.Response != nil { - sc = result.rclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure sending request") - return - } - - result.rclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure responding to request") - return - } - if result.rclr.hasNextLink() && result.rclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachineRunCommandsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineRunCommandsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachineRunCommandsClient) ListResponder(resp *http.Response) (result RunCommandListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualMachineRunCommandsClient) listNextResults(ctx context.Context, lastResults RunCommandListResult) (result RunCommandListResult, err error) { - req, err := lastResults.runCommandListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachineRunCommandsClient) ListComplete(ctx context.Context, location string) (result RunCommandListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachines.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachines.go deleted file mode 100644 index 60dd11943..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachines.go +++ /dev/null @@ -1,1768 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachinesClient is the compute Client -type VirtualMachinesClient struct { - BaseClient -} - -// NewVirtualMachinesClient creates an instance of the VirtualMachinesClient client. -func NewVirtualMachinesClient(subscriptionID string) VirtualMachinesClient { - return NewVirtualMachinesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachinesClientWithBaseURI creates an instance of the VirtualMachinesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualMachinesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachinesClient { - return VirtualMachinesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Capture captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to create -// similar VMs. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -// parameters - parameters supplied to the Capture Virtual Machine operation. -func (client VirtualMachinesClient) Capture(ctx context.Context, resourceGroupName string, VMName string, parameters VirtualMachineCaptureParameters) (result VirtualMachinesCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Capture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VhdPrefix", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.DestinationContainerName", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.OverwriteVhds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachinesClient", "Capture", err.Error()) - } - - req, err := client.CapturePreparer(ctx, resourceGroupName, VMName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", nil, "Failure preparing request") - return - } - - result, err = client.CaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", result.Response(), "Failure sending request") - return - } - - return -} - -// CapturePreparer prepares the Capture request. -func (client VirtualMachinesClient) CapturePreparer(ctx context.Context, resourceGroupName string, VMName string, parameters VirtualMachineCaptureParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/capture", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CaptureSender sends the Capture request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) CaptureSender(req *http.Request) (future VirtualMachinesCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CaptureResponder handles the response to the Capture request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) CaptureResponder(resp *http.Response) (result VirtualMachineCaptureResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ConvertToManagedDisks converts virtual machine disks from blob-based to managed disks. Virtual machine must be -// stop-deallocated before invoking this operation. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) ConvertToManagedDisks(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesConvertToManagedDisksFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ConvertToManagedDisks") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ConvertToManagedDisksPreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ConvertToManagedDisks", nil, "Failure preparing request") - return - } - - result, err = client.ConvertToManagedDisksSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ConvertToManagedDisks", result.Response(), "Failure sending request") - return - } - - return -} - -// ConvertToManagedDisksPreparer prepares the ConvertToManagedDisks request. -func (client VirtualMachinesClient) ConvertToManagedDisksPreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/convertToManagedDisks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ConvertToManagedDisksSender sends the ConvertToManagedDisks request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) ConvertToManagedDisksSender(req *http.Request) (future VirtualMachinesConvertToManagedDisksFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ConvertToManagedDisksResponder handles the response to the ConvertToManagedDisks request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) ConvertToManagedDisksResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// CreateOrUpdate the operation to create or update a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -// parameters - parameters supplied to the Create Virtual Machine operation. -func (client VirtualMachinesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMName string, parameters VirtualMachine) (result VirtualMachinesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualMachineProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineProperties.StorageProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachinesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, VMName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachinesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, VMName string, parameters VirtualMachine) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Resources = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) CreateOrUpdateSender(req *http.Request) (future VirtualMachinesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachine, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Deallocate shuts down the virtual machine and releases the compute resources. You are not billed for the compute -// resources that this virtual machine uses. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) Deallocate(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesDeallocateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Deallocate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeallocatePreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", nil, "Failure preparing request") - return - } - - result, err = client.DeallocateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", result.Response(), "Failure sending request") - return - } - - return -} - -// DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachinesClient) DeallocatePreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/deallocate", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeallocateSender sends the Deallocate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) DeallocateSender(req *http.Request) (future VirtualMachinesDeallocateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeallocateResponder handles the response to the Deallocate request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Delete the operation to delete a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) Delete(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualMachinesClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) DeleteSender(req *http.Request) (future VirtualMachinesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Generalize sets the state of the virtual machine to generalized. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) Generalize(ctx context.Context, resourceGroupName string, VMName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Generalize") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GeneralizePreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", nil, "Failure preparing request") - return - } - - resp, err := client.GeneralizeSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure sending request") - return - } - - result, err = client.GeneralizeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure responding to request") - return - } - - return -} - -// GeneralizePreparer prepares the Generalize request. -func (client VirtualMachinesClient) GeneralizePreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/generalize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GeneralizeSender sends the Generalize request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) GeneralizeSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GeneralizeResponder handles the response to the Generalize request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) GeneralizeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves information about the model view or the instance view of a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -// expand - the expand expression to apply on the operation. -func (client VirtualMachinesClient) Get(ctx context.Context, resourceGroupName string, VMName string, expand InstanceViewTypes) (result VirtualMachine, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, VMName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachinesClient) GetPreparer(ctx context.Context, resourceGroupName string, VMName string, expand InstanceViewTypes) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(string(expand)) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) GetResponder(resp *http.Response) (result VirtualMachine, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// InstanceView retrieves information about the run-time state of a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) InstanceView(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachineInstanceView, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.InstanceView") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.InstanceViewPreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "InstanceView", nil, "Failure preparing request") - return - } - - resp, err := client.InstanceViewSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "InstanceView", resp, "Failure sending request") - return - } - - result, err = client.InstanceViewResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "InstanceView", resp, "Failure responding to request") - return - } - - return -} - -// InstanceViewPreparer prepares the InstanceView request. -func (client VirtualMachinesClient) InstanceViewPreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/instanceView", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// InstanceViewSender sends the InstanceView request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) InstanceViewSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// InstanceViewResponder handles the response to the InstanceView request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) InstanceViewResponder(resp *http.Response) (result VirtualMachineInstanceView, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all of the virtual machines in the specified resource group. Use the nextLink property in the response to -// get the next page of virtual machines. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualMachinesClient) List(ctx context.Context, resourceGroupName string) (result VirtualMachineListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.List") - defer func() { - sc := -1 - if result.vmlr.Response.Response != nil { - sc = result.vmlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vmlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure sending request") - return - } - - result.vmlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure responding to request") - return - } - if result.vmlr.hasNextLink() && result.vmlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachinesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) ListResponder(resp *http.Response) (result VirtualMachineListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualMachinesClient) listNextResults(ctx context.Context, lastResults VirtualMachineListResult) (result VirtualMachineListResult, err error) { - req, err := lastResults.virtualMachineListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachinesClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualMachineListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll lists all of the virtual machines in the specified subscription. Use the nextLink property in the response -// to get the next page of virtual machines. -func (client VirtualMachinesClient) ListAll(ctx context.Context) (result VirtualMachineListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ListAll") - defer func() { - sc := -1 - if result.vmlr.Response.Response != nil { - sc = result.vmlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.vmlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure sending request") - return - } - - result.vmlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.vmlr.hasNextLink() && result.vmlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client VirtualMachinesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) ListAllResponder(resp *http.Response) (result VirtualMachineListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client VirtualMachinesClient) listAllNextResults(ctx context.Context, lastResults VirtualMachineListResult) (result VirtualMachineListResult, err error) { - req, err := lastResults.virtualMachineListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachinesClient) ListAllComplete(ctx context.Context) (result VirtualMachineListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListAvailableSizes lists all available virtual machine sizes to which the specified virtual machine can be resized. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) ListAvailableSizes(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachineSizeListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ListAvailableSizes") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableSizesPreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableSizesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableSizesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableSizesPreparer prepares the ListAvailableSizes request. -func (client VirtualMachinesClient) ListAvailableSizesPreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/vmSizes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableSizesSender sends the ListAvailableSizes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) ListAvailableSizesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableSizesResponder handles the response to the ListAvailableSizes request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) ListAvailableSizesResponder(resp *http.Response) (result VirtualMachineSizeListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByLocation gets all the virtual machines under the specified subscription for the specified location. -// Parameters: -// location - the location for which virtual machines under the subscription are queried. -func (client VirtualMachinesClient) ListByLocation(ctx context.Context, location string) (result VirtualMachineListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ListByLocation") - defer func() { - sc := -1 - if result.vmlr.Response.Response != nil { - sc = result.vmlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachinesClient", "ListByLocation", err.Error()) - } - - result.fn = client.listByLocationNextResults - req, err := client.ListByLocationPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListByLocation", nil, "Failure preparing request") - return - } - - resp, err := client.ListByLocationSender(req) - if err != nil { - result.vmlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListByLocation", resp, "Failure sending request") - return - } - - result.vmlr, err = client.ListByLocationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListByLocation", resp, "Failure responding to request") - return - } - if result.vmlr.hasNextLink() && result.vmlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByLocationPreparer prepares the ListByLocation request. -func (client VirtualMachinesClient) ListByLocationPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/virtualMachines", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByLocationSender sends the ListByLocation request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) ListByLocationSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByLocationResponder handles the response to the ListByLocation request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) ListByLocationResponder(resp *http.Response) (result VirtualMachineListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByLocationNextResults retrieves the next set of results, if any. -func (client VirtualMachinesClient) listByLocationNextResults(ctx context.Context, lastResults VirtualMachineListResult) (result VirtualMachineListResult, err error) { - req, err := lastResults.virtualMachineListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listByLocationNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByLocationSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listByLocationNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByLocationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "listByLocationNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByLocationComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachinesClient) ListByLocationComplete(ctx context.Context, location string) (result VirtualMachineListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ListByLocation") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByLocation(ctx, location) - return -} - -// PerformMaintenance the operation to perform maintenance on a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) PerformMaintenance(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesPerformMaintenanceFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.PerformMaintenance") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PerformMaintenancePreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PerformMaintenance", nil, "Failure preparing request") - return - } - - result, err = client.PerformMaintenanceSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PerformMaintenance", result.Response(), "Failure sending request") - return - } - - return -} - -// PerformMaintenancePreparer prepares the PerformMaintenance request. -func (client VirtualMachinesClient) PerformMaintenancePreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/performMaintenance", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PerformMaintenanceSender sends the PerformMaintenance request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) PerformMaintenanceSender(req *http.Request) (future VirtualMachinesPerformMaintenanceFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PerformMaintenanceResponder handles the response to the PerformMaintenance request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) PerformMaintenanceResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// PowerOff the operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same -// provisioned resources. You are still charged for this virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) PowerOff(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesPowerOffFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.PowerOff") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PowerOffPreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", nil, "Failure preparing request") - return - } - - result, err = client.PowerOffSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", result.Response(), "Failure sending request") - return - } - - return -} - -// PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachinesClient) PowerOffPreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/powerOff", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PowerOffSender sends the PowerOff request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) PowerOffSender(req *http.Request) (future VirtualMachinesPowerOffFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PowerOffResponder handles the response to the PowerOff request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Redeploy shuts down the virtual machine, moves it to a new node, and powers it back on. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) Redeploy(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesRedeployFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Redeploy") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RedeployPreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", nil, "Failure preparing request") - return - } - - result, err = client.RedeploySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", result.Response(), "Failure sending request") - return - } - - return -} - -// RedeployPreparer prepares the Redeploy request. -func (client VirtualMachinesClient) RedeployPreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/redeploy", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RedeploySender sends the Redeploy request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) RedeploySender(req *http.Request) (future VirtualMachinesRedeployFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RedeployResponder handles the response to the Redeploy request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Reimage reimages the virtual machine which has an ephemeral OS disk back to its initial state. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -// parameters - parameters supplied to the Reimage Virtual Machine operation. -func (client VirtualMachinesClient) Reimage(ctx context.Context, resourceGroupName string, VMName string, parameters *VirtualMachineReimageParameters) (result VirtualMachinesReimageFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Reimage") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ReimagePreparer(ctx, resourceGroupName, VMName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Reimage", nil, "Failure preparing request") - return - } - - result, err = client.ReimageSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Reimage", result.Response(), "Failure sending request") - return - } - - return -} - -// ReimagePreparer prepares the Reimage request. -func (client VirtualMachinesClient) ReimagePreparer(ctx context.Context, resourceGroupName string, VMName string, parameters *VirtualMachineReimageParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/reimage", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReimageSender sends the Reimage request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) ReimageSender(req *http.Request) (future VirtualMachinesReimageFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ReimageResponder handles the response to the Reimage request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Restart the operation to restart a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) Restart(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesRestartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Restart") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RestartPreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", nil, "Failure preparing request") - return - } - - result, err = client.RestartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", result.Response(), "Failure sending request") - return - } - - return -} - -// RestartPreparer prepares the Restart request. -func (client VirtualMachinesClient) RestartPreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/restart", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestartSender sends the Restart request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) RestartSender(req *http.Request) (future VirtualMachinesRestartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RestartResponder handles the response to the Restart request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// RunCommand run command on the VM. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -// parameters - parameters supplied to the Run command operation. -func (client VirtualMachinesClient) RunCommand(ctx context.Context, resourceGroupName string, VMName string, parameters RunCommandInput) (result VirtualMachinesRunCommandFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.RunCommand") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.CommandID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachinesClient", "RunCommand", err.Error()) - } - - req, err := client.RunCommandPreparer(ctx, resourceGroupName, VMName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "RunCommand", nil, "Failure preparing request") - return - } - - result, err = client.RunCommandSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "RunCommand", result.Response(), "Failure sending request") - return - } - - return -} - -// RunCommandPreparer prepares the RunCommand request. -func (client VirtualMachinesClient) RunCommandPreparer(ctx context.Context, resourceGroupName string, VMName string, parameters RunCommandInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommand", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RunCommandSender sends the RunCommand request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) RunCommandSender(req *http.Request) (future VirtualMachinesRunCommandFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RunCommandResponder handles the response to the RunCommand request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) RunCommandResponder(resp *http.Response) (result RunCommandResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Start the operation to start a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -func (client VirtualMachinesClient) Start(ctx context.Context, resourceGroupName string, VMName string) (result VirtualMachinesStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, VMName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client VirtualMachinesClient) StartPreparer(ctx context.Context, resourceGroupName string, VMName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) StartSender(req *http.Request) (future VirtualMachinesStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update the operation to update a virtual machine. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMName - the name of the virtual machine. -// parameters - parameters supplied to the Update Virtual Machine operation. -func (client VirtualMachinesClient) Update(ctx context.Context, resourceGroupName string, VMName string, parameters VirtualMachineUpdate) (result VirtualMachinesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, VMName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client VirtualMachinesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, VMName string, parameters VirtualMachineUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", VMName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachinesClient) UpdateSender(req *http.Request) (future VirtualMachinesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client VirtualMachinesClient) UpdateResponder(resp *http.Response) (result VirtualMachine, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetextensions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetextensions.go deleted file mode 100644 index b4ceb26b5..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetextensions.go +++ /dev/null @@ -1,396 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineScaleSetExtensionsClient is the compute Client -type VirtualMachineScaleSetExtensionsClient struct { - BaseClient -} - -// NewVirtualMachineScaleSetExtensionsClient creates an instance of the VirtualMachineScaleSetExtensionsClient client. -func NewVirtualMachineScaleSetExtensionsClient(subscriptionID string) VirtualMachineScaleSetExtensionsClient { - return NewVirtualMachineScaleSetExtensionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineScaleSetExtensionsClientWithBaseURI creates an instance of the -// VirtualMachineScaleSetExtensionsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualMachineScaleSetExtensionsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetExtensionsClient { - return VirtualMachineScaleSetExtensionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate the operation to create or update an extension. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set where the extension should be create or updated. -// vmssExtensionName - the name of the VM scale set extension. -// extensionParameters - parameters supplied to the Create VM scale set Extension operation. -func (client VirtualMachineScaleSetExtensionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtension) (result VirtualMachineScaleSetExtensionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetExtensionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, VMScaleSetName, vmssExtensionName, extensionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachineScaleSetExtensionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, vmssExtensionName string, extensionParameters VirtualMachineScaleSetExtension) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - "vmssExtensionName": autorest.Encode("path", vmssExtensionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions/{vmssExtensionName}", pathParameters), - autorest.WithJSON(extensionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetExtensionsClient) CreateOrUpdateSender(req *http.Request) (future VirtualMachineScaleSetExtensionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetExtensionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineScaleSetExtension, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete the operation to delete the extension. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set where the extension should be deleted. -// vmssExtensionName - the name of the VM scale set extension. -func (client VirtualMachineScaleSetExtensionsClient) Delete(ctx context.Context, resourceGroupName string, VMScaleSetName string, vmssExtensionName string) (result VirtualMachineScaleSetExtensionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetExtensionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, VMScaleSetName, vmssExtensionName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualMachineScaleSetExtensionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, vmssExtensionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - "vmssExtensionName": autorest.Encode("path", vmssExtensionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions/{vmssExtensionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetExtensionsClient) DeleteSender(req *http.Request) (future VirtualMachineScaleSetExtensionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetExtensionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get the operation to get the extension. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set containing the extension. -// vmssExtensionName - the name of the VM scale set extension. -// expand - the expand expression to apply on the operation. -func (client VirtualMachineScaleSetExtensionsClient) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, vmssExtensionName string, expand string) (result VirtualMachineScaleSetExtension, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetExtensionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, VMScaleSetName, vmssExtensionName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachineScaleSetExtensionsClient) GetPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, vmssExtensionName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - "vmssExtensionName": autorest.Encode("path", vmssExtensionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions/{vmssExtensionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetExtensionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetExtensionsClient) GetResponder(resp *http.Response) (result VirtualMachineScaleSetExtension, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets a list of all extensions in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set containing the extension. -func (client VirtualMachineScaleSetExtensionsClient) List(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetExtensionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetExtensionsClient.List") - defer func() { - sc := -1 - if result.vmsselr.Response.Response != nil { - sc = result.vmsselr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vmsselr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "List", resp, "Failure sending request") - return - } - - result.vmsselr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "List", resp, "Failure responding to request") - return - } - if result.vmsselr.hasNextLink() && result.vmsselr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachineScaleSetExtensionsClient) ListPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetExtensionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetExtensionsClient) ListResponder(resp *http.Response) (result VirtualMachineScaleSetExtensionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetExtensionsClient) listNextResults(ctx context.Context, lastResults VirtualMachineScaleSetExtensionListResult) (result VirtualMachineScaleSetExtensionListResult, err error) { - req, err := lastResults.virtualMachineScaleSetExtensionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetExtensionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachineScaleSetExtensionsClient) ListComplete(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetExtensionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetExtensionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, VMScaleSetName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetrollingupgrades.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetrollingupgrades.go deleted file mode 100644 index 6c212f081..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetrollingupgrades.go +++ /dev/null @@ -1,346 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineScaleSetRollingUpgradesClient is the compute Client -type VirtualMachineScaleSetRollingUpgradesClient struct { - BaseClient -} - -// NewVirtualMachineScaleSetRollingUpgradesClient creates an instance of the -// VirtualMachineScaleSetRollingUpgradesClient client. -func NewVirtualMachineScaleSetRollingUpgradesClient(subscriptionID string) VirtualMachineScaleSetRollingUpgradesClient { - return NewVirtualMachineScaleSetRollingUpgradesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineScaleSetRollingUpgradesClientWithBaseURI creates an instance of the -// VirtualMachineScaleSetRollingUpgradesClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualMachineScaleSetRollingUpgradesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetRollingUpgradesClient { - return VirtualMachineScaleSetRollingUpgradesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Cancel cancels the current virtual machine scale set rolling upgrade. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetRollingUpgradesClient) Cancel(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetRollingUpgradesCancelFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetRollingUpgradesClient.Cancel") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CancelPreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "Cancel", nil, "Failure preparing request") - return - } - - result, err = client.CancelSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "Cancel", result.Response(), "Failure sending request") - return - } - - return -} - -// CancelPreparer prepares the Cancel request. -func (client VirtualMachineScaleSetRollingUpgradesClient) CancelPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/rollingUpgrades/cancel", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CancelSender sends the Cancel request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetRollingUpgradesClient) CancelSender(req *http.Request) (future VirtualMachineScaleSetRollingUpgradesCancelFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CancelResponder handles the response to the Cancel request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetRollingUpgradesClient) CancelResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// GetLatest gets the status of the latest virtual machine scale set rolling upgrade. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetRollingUpgradesClient) GetLatest(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result RollingUpgradeStatusInfo, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetRollingUpgradesClient.GetLatest") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetLatestPreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "GetLatest", nil, "Failure preparing request") - return - } - - resp, err := client.GetLatestSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "GetLatest", resp, "Failure sending request") - return - } - - result, err = client.GetLatestResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "GetLatest", resp, "Failure responding to request") - return - } - - return -} - -// GetLatestPreparer prepares the GetLatest request. -func (client VirtualMachineScaleSetRollingUpgradesClient) GetLatestPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/rollingUpgrades/latest", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetLatestSender sends the GetLatest request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetRollingUpgradesClient) GetLatestSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetLatestResponder handles the response to the GetLatest request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetRollingUpgradesClient) GetLatestResponder(resp *http.Response) (result RollingUpgradeStatusInfo, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StartExtensionUpgrade starts a rolling upgrade to move all extensions for all virtual machine scale set instances to -// the latest available extension version. Instances which are already running the latest extension versions are not -// affected. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartExtensionUpgrade(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetRollingUpgradesClient.StartExtensionUpgrade") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartExtensionUpgradePreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "StartExtensionUpgrade", nil, "Failure preparing request") - return - } - - result, err = client.StartExtensionUpgradeSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "StartExtensionUpgrade", result.Response(), "Failure sending request") - return - } - - return -} - -// StartExtensionUpgradePreparer prepares the StartExtensionUpgrade request. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartExtensionUpgradePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/extensionRollingUpgrade", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartExtensionUpgradeSender sends the StartExtensionUpgrade request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartExtensionUpgradeSender(req *http.Request) (future VirtualMachineScaleSetRollingUpgradesStartExtensionUpgradeFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartExtensionUpgradeResponder handles the response to the StartExtensionUpgrade request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartExtensionUpgradeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// StartOSUpgrade starts a rolling upgrade to move all virtual machine scale set instances to the latest available -// Platform Image OS version. Instances which are already running the latest available OS version are not affected. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartOSUpgrade(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetRollingUpgradesClient.StartOSUpgrade") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartOSUpgradePreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "StartOSUpgrade", nil, "Failure preparing request") - return - } - - result, err = client.StartOSUpgradeSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetRollingUpgradesClient", "StartOSUpgrade", result.Response(), "Failure sending request") - return - } - - return -} - -// StartOSUpgradePreparer prepares the StartOSUpgrade request. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartOSUpgradePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/osRollingUpgrade", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartOSUpgradeSender sends the StartOSUpgrade request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartOSUpgradeSender(req *http.Request) (future VirtualMachineScaleSetRollingUpgradesStartOSUpgradeFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartOSUpgradeResponder handles the response to the StartOSUpgrade request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetRollingUpgradesClient) StartOSUpgradeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesets.go deleted file mode 100644 index bc4b5004c..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesets.go +++ /dev/null @@ -1,1850 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineScaleSetsClient is the compute Client -type VirtualMachineScaleSetsClient struct { - BaseClient -} - -// NewVirtualMachineScaleSetsClient creates an instance of the VirtualMachineScaleSetsClient client. -func NewVirtualMachineScaleSetsClient(subscriptionID string) VirtualMachineScaleSetsClient { - return NewVirtualMachineScaleSetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineScaleSetsClientWithBaseURI creates an instance of the VirtualMachineScaleSetsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualMachineScaleSetsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetsClient { - return VirtualMachineScaleSetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set to create or update. -// parameters - the scale set object. -func (client VirtualMachineScaleSetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters VirtualMachineScaleSet) (result VirtualMachineScaleSetsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxBatchInstancePercent", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxBatchInstancePercent", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, - {Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxBatchInstancePercent", Name: validation.InclusiveMinimum, Rule: int64(5), Chain: nil}, - }}, - {Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyInstancePercent", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyInstancePercent", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, - {Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyInstancePercent", Name: validation.InclusiveMinimum, Rule: int64(5), Chain: nil}, - }}, - {Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyUpgradedInstancePercent", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyUpgradedInstancePercent", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, - {Target: "parameters.VirtualMachineScaleSetProperties.UpgradePolicy.RollingUpgradePolicy.MaxUnhealthyUpgradedInstancePercent", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, VMScaleSetName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachineScaleSetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters VirtualMachineScaleSet) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) CreateOrUpdateSender(req *http.Request) (future VirtualMachineScaleSetsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineScaleSet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Deallocate deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and releases the -// compute resources. You are not billed for the compute resources that this virtual machine scale set deallocates. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) Deallocate(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result VirtualMachineScaleSetsDeallocateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Deallocate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeallocatePreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", nil, "Failure preparing request") - return - } - - result, err = client.DeallocateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", result.Response(), "Failure sending request") - return - } - - return -} - -// DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachineScaleSetsClient) DeallocatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMInstanceIDs != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMInstanceIDs)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeallocateSender sends the Deallocate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) DeallocateSender(req *http.Request) (future VirtualMachineScaleSetsDeallocateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeallocateResponder handles the response to the Deallocate request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Delete deletes a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetsClient) Delete(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualMachineScaleSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) DeleteSender(req *http.Request) (future VirtualMachineScaleSetsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// DeleteInstances deletes virtual machines in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) DeleteInstances(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (result VirtualMachineScaleSetsDeleteInstancesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.DeleteInstances") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: VMInstanceIDs, - Constraints: []validation.Constraint{{Target: "VMInstanceIDs.InstanceIds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineScaleSetsClient", "DeleteInstances", err.Error()) - } - - req, err := client.DeleteInstancesPreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", nil, "Failure preparing request") - return - } - - result, err = client.DeleteInstancesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", result.Response(), "Failure sending request") - return - } - - return -} - -// DeleteInstancesPreparer prepares the DeleteInstances request. -func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/delete", pathParameters), - autorest.WithJSON(VMInstanceIDs), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteInstancesSender sends the DeleteInstances request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) DeleteInstancesSender(req *http.Request) (future VirtualMachineScaleSetsDeleteInstancesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteInstancesResponder handles the response to the DeleteInstances request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) DeleteInstancesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// ForceRecoveryServiceFabricPlatformUpdateDomainWalk manual platform update domain walk to update virtual machines in -// a service fabric virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// platformUpdateDomain - the platform update domain for which a manual recovery walk is requested -func (client VirtualMachineScaleSetsClient) ForceRecoveryServiceFabricPlatformUpdateDomainWalk(ctx context.Context, resourceGroupName string, VMScaleSetName string, platformUpdateDomain int32) (result RecoveryWalkResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.ForceRecoveryServiceFabricPlatformUpdateDomainWalk") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ForceRecoveryServiceFabricPlatformUpdateDomainWalkPreparer(ctx, resourceGroupName, VMScaleSetName, platformUpdateDomain) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ForceRecoveryServiceFabricPlatformUpdateDomainWalk", nil, "Failure preparing request") - return - } - - resp, err := client.ForceRecoveryServiceFabricPlatformUpdateDomainWalkSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ForceRecoveryServiceFabricPlatformUpdateDomainWalk", resp, "Failure sending request") - return - } - - result, err = client.ForceRecoveryServiceFabricPlatformUpdateDomainWalkResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ForceRecoveryServiceFabricPlatformUpdateDomainWalk", resp, "Failure responding to request") - return - } - - return -} - -// ForceRecoveryServiceFabricPlatformUpdateDomainWalkPreparer prepares the ForceRecoveryServiceFabricPlatformUpdateDomainWalk request. -func (client VirtualMachineScaleSetsClient) ForceRecoveryServiceFabricPlatformUpdateDomainWalkPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, platformUpdateDomain int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - "platformUpdateDomain": autorest.Encode("query", platformUpdateDomain), - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/forceRecoveryServiceFabricPlatformUpdateDomainWalk", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ForceRecoveryServiceFabricPlatformUpdateDomainWalkSender sends the ForceRecoveryServiceFabricPlatformUpdateDomainWalk request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) ForceRecoveryServiceFabricPlatformUpdateDomainWalkSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ForceRecoveryServiceFabricPlatformUpdateDomainWalkResponder handles the response to the ForceRecoveryServiceFabricPlatformUpdateDomainWalk request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) ForceRecoveryServiceFabricPlatformUpdateDomainWalkResponder(resp *http.Response) (result RecoveryWalkResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get display information about a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetsClient) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachineScaleSetsClient) GetPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) GetResponder(resp *http.Response) (result VirtualMachineScaleSet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetInstanceView gets the status of a VM scale set instance. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetsClient) GetInstanceView(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetInstanceView, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.GetInstanceView") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetInstanceViewPreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", nil, "Failure preparing request") - return - } - - resp, err := client.GetInstanceViewSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure sending request") - return - } - - result, err = client.GetInstanceViewResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure responding to request") - return - } - - return -} - -// GetInstanceViewPreparer prepares the GetInstanceView request. -func (client VirtualMachineScaleSetsClient) GetInstanceViewPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/instanceView", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetInstanceViewSender sends the GetInstanceView request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetInstanceViewResponder handles the response to the GetInstanceView request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) GetInstanceViewResponder(resp *http.Response) (result VirtualMachineScaleSetInstanceView, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetOSUpgradeHistory gets list of OS upgrades on a VM scale set instance. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetsClient) GetOSUpgradeHistory(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetListOSUpgradeHistoryPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.GetOSUpgradeHistory") - defer func() { - sc := -1 - if result.vmsslouh.Response.Response != nil { - sc = result.vmsslouh.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.getOSUpgradeHistoryNextResults - req, err := client.GetOSUpgradeHistoryPreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetOSUpgradeHistory", nil, "Failure preparing request") - return - } - - resp, err := client.GetOSUpgradeHistorySender(req) - if err != nil { - result.vmsslouh.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetOSUpgradeHistory", resp, "Failure sending request") - return - } - - result.vmsslouh, err = client.GetOSUpgradeHistoryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetOSUpgradeHistory", resp, "Failure responding to request") - return - } - if result.vmsslouh.hasNextLink() && result.vmsslouh.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetOSUpgradeHistoryPreparer prepares the GetOSUpgradeHistory request. -func (client VirtualMachineScaleSetsClient) GetOSUpgradeHistoryPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/osUpgradeHistory", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetOSUpgradeHistorySender sends the GetOSUpgradeHistory request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) GetOSUpgradeHistorySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetOSUpgradeHistoryResponder handles the response to the GetOSUpgradeHistory request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) GetOSUpgradeHistoryResponder(resp *http.Response) (result VirtualMachineScaleSetListOSUpgradeHistory, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getOSUpgradeHistoryNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetsClient) getOSUpgradeHistoryNextResults(ctx context.Context, lastResults VirtualMachineScaleSetListOSUpgradeHistory) (result VirtualMachineScaleSetListOSUpgradeHistory, err error) { - req, err := lastResults.virtualMachineScaleSetListOSUpgradeHistoryPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "getOSUpgradeHistoryNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetOSUpgradeHistorySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "getOSUpgradeHistoryNextResults", resp, "Failure sending next results request") - } - result, err = client.GetOSUpgradeHistoryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "getOSUpgradeHistoryNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetOSUpgradeHistoryComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachineScaleSetsClient) GetOSUpgradeHistoryComplete(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetListOSUpgradeHistoryIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.GetOSUpgradeHistory") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetOSUpgradeHistory(ctx, resourceGroupName, VMScaleSetName) - return -} - -// List gets a list of all VM scale sets under a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualMachineScaleSetsClient) List(ctx context.Context, resourceGroupName string) (result VirtualMachineScaleSetListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.List") - defer func() { - sc := -1 - if result.vmsslr.Response.Response != nil { - sc = result.vmsslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vmsslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure sending request") - return - } - - result.vmsslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure responding to request") - return - } - if result.vmsslr.hasNextLink() && result.vmsslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachineScaleSetsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) ListResponder(resp *http.Response) (result VirtualMachineScaleSetListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetsClient) listNextResults(ctx context.Context, lastResults VirtualMachineScaleSetListResult) (result VirtualMachineScaleSetListResult, err error) { - req, err := lastResults.virtualMachineScaleSetListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachineScaleSetsClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualMachineScaleSetListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets a list of all VM Scale Sets in the subscription, regardless of the associated resource group. Use -// nextLink property in the response to get the next page of VM Scale Sets. Do this till nextLink is null to fetch all -// the VM Scale Sets. -func (client VirtualMachineScaleSetsClient) ListAll(ctx context.Context) (result VirtualMachineScaleSetListWithLinkResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.ListAll") - defer func() { - sc := -1 - if result.vmsslwlr.Response.Response != nil { - sc = result.vmsslwlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.vmsslwlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure sending request") - return - } - - result.vmsslwlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.vmsslwlr.hasNextLink() && result.vmsslwlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client VirtualMachineScaleSetsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) ListAllResponder(resp *http.Response) (result VirtualMachineScaleSetListWithLinkResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetsClient) listAllNextResults(ctx context.Context, lastResults VirtualMachineScaleSetListWithLinkResult) (result VirtualMachineScaleSetListWithLinkResult, err error) { - req, err := lastResults.virtualMachineScaleSetListWithLinkResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachineScaleSetsClient) ListAllComplete(ctx context.Context) (result VirtualMachineScaleSetListWithLinkResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListSkus gets a list of SKUs available for your VM scale set, including the minimum and maximum VM instances allowed -// for each SKU. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -func (client VirtualMachineScaleSetsClient) ListSkus(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetListSkusResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.ListSkus") - defer func() { - sc := -1 - if result.vmsslsr.Response.Response != nil { - sc = result.vmsslsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listSkusNextResults - req, err := client.ListSkusPreparer(ctx, resourceGroupName, VMScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", nil, "Failure preparing request") - return - } - - resp, err := client.ListSkusSender(req) - if err != nil { - result.vmsslsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure sending request") - return - } - - result.vmsslsr, err = client.ListSkusResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure responding to request") - return - } - if result.vmsslsr.hasNextLink() && result.vmsslsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListSkusPreparer prepares the ListSkus request. -func (client VirtualMachineScaleSetsClient) ListSkusPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/skus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSkusSender sends the ListSkus request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) ListSkusSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListSkusResponder handles the response to the ListSkus request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) ListSkusResponder(resp *http.Response) (result VirtualMachineScaleSetListSkusResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listSkusNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetsClient) listSkusNextResults(ctx context.Context, lastResults VirtualMachineScaleSetListSkusResult) (result VirtualMachineScaleSetListSkusResult, err error) { - req, err := lastResults.virtualMachineScaleSetListSkusResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listSkusNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSkusSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listSkusNextResults", resp, "Failure sending next results request") - } - result, err = client.ListSkusResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "listSkusNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListSkusComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachineScaleSetsClient) ListSkusComplete(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result VirtualMachineScaleSetListSkusResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.ListSkus") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListSkus(ctx, resourceGroupName, VMScaleSetName) - return -} - -// PerformMaintenance perform maintenance on one or more virtual machines in a VM scale set. Operation on instances -// which are not eligible for perform maintenance will be failed. Please refer to best practices for more details: -// https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) PerformMaintenance(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result VirtualMachineScaleSetsPerformMaintenanceFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.PerformMaintenance") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PerformMaintenancePreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PerformMaintenance", nil, "Failure preparing request") - return - } - - result, err = client.PerformMaintenanceSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PerformMaintenance", result.Response(), "Failure sending request") - return - } - - return -} - -// PerformMaintenancePreparer prepares the PerformMaintenance request. -func (client VirtualMachineScaleSetsClient) PerformMaintenancePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/performMaintenance", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMInstanceIDs != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMInstanceIDs)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PerformMaintenanceSender sends the PerformMaintenance request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) PerformMaintenanceSender(req *http.Request) (future VirtualMachineScaleSetsPerformMaintenanceFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PerformMaintenanceResponder handles the response to the PerformMaintenance request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) PerformMaintenanceResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// PowerOff power off (stop) one or more virtual machines in a VM scale set. Note that resources are still attached and -// you are getting charged for the resources. Instead, use deallocate to release resources and avoid charges. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) PowerOff(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result VirtualMachineScaleSetsPowerOffFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.PowerOff") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PowerOffPreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", nil, "Failure preparing request") - return - } - - result, err = client.PowerOffSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", result.Response(), "Failure sending request") - return - } - - return -} - -// PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachineScaleSetsClient) PowerOffPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/poweroff", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMInstanceIDs != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMInstanceIDs)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PowerOffSender sends the PowerOff request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) PowerOffSender(req *http.Request) (future VirtualMachineScaleSetsPowerOffFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PowerOffResponder handles the response to the PowerOff request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Redeploy shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and powers -// them back on. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) Redeploy(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result VirtualMachineScaleSetsRedeployFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Redeploy") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RedeployPreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Redeploy", nil, "Failure preparing request") - return - } - - result, err = client.RedeploySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Redeploy", result.Response(), "Failure sending request") - return - } - - return -} - -// RedeployPreparer prepares the Redeploy request. -func (client VirtualMachineScaleSetsClient) RedeployPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/redeploy", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMInstanceIDs != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMInstanceIDs)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RedeploySender sends the Redeploy request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) RedeploySender(req *http.Request) (future VirtualMachineScaleSetsRedeployFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RedeployResponder handles the response to the Redeploy request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Reimage reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't have a -// ephemeral OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is reset to initial state. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMScaleSetReimageInput - parameters for Reimaging VM ScaleSet. -func (client VirtualMachineScaleSetsClient) Reimage(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMScaleSetReimageInput *VirtualMachineScaleSetReimageParameters) (result VirtualMachineScaleSetsReimageFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Reimage") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ReimagePreparer(ctx, resourceGroupName, VMScaleSetName, VMScaleSetReimageInput) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", nil, "Failure preparing request") - return - } - - result, err = client.ReimageSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", result.Response(), "Failure sending request") - return - } - - return -} - -// ReimagePreparer prepares the Reimage request. -func (client VirtualMachineScaleSetsClient) ReimagePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMScaleSetReimageInput *VirtualMachineScaleSetReimageParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimage", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMScaleSetReimageInput != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMScaleSetReimageInput)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReimageSender sends the Reimage request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) ReimageSender(req *http.Request) (future VirtualMachineScaleSetsReimageFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ReimageResponder handles the response to the Reimage request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// ReimageAll reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This operation -// is only supported for managed disks. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) ReimageAll(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result VirtualMachineScaleSetsReimageAllFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.ReimageAll") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ReimageAllPreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ReimageAll", nil, "Failure preparing request") - return - } - - result, err = client.ReimageAllSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ReimageAll", result.Response(), "Failure sending request") - return - } - - return -} - -// ReimageAllPreparer prepares the ReimageAll request. -func (client VirtualMachineScaleSetsClient) ReimageAllPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimageall", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMInstanceIDs != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMInstanceIDs)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReimageAllSender sends the ReimageAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) ReimageAllSender(req *http.Request) (future VirtualMachineScaleSetsReimageAllFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ReimageAllResponder handles the response to the ReimageAll request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) ReimageAllResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Restart restarts one or more virtual machines in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) Restart(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result VirtualMachineScaleSetsRestartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Restart") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RestartPreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", nil, "Failure preparing request") - return - } - - result, err = client.RestartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", result.Response(), "Failure sending request") - return - } - - return -} - -// RestartPreparer prepares the Restart request. -func (client VirtualMachineScaleSetsClient) RestartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/restart", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMInstanceIDs != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMInstanceIDs)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestartSender sends the Restart request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) RestartSender(req *http.Request) (future VirtualMachineScaleSetsRestartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RestartResponder handles the response to the Restart request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Start starts one or more virtual machines in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) Start(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result VirtualMachineScaleSetsStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client VirtualMachineScaleSetsClient) StartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMInstanceIDs != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMInstanceIDs)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) StartSender(req *http.Request) (future VirtualMachineScaleSetsStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update update a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set to create or update. -// parameters - the scale set object. -func (client VirtualMachineScaleSetsClient) Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters VirtualMachineScaleSetUpdate) (result VirtualMachineScaleSetsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, VMScaleSetName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client VirtualMachineScaleSetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters VirtualMachineScaleSetUpdate) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) UpdateSender(req *http.Request) (future VirtualMachineScaleSetsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) UpdateResponder(resp *http.Response) (result VirtualMachineScaleSet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateInstances upgrades one or more virtual machines to the latest SKU set in the VM scale set model. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// VMInstanceIDs - a list of virtual machine instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) UpdateInstances(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (result VirtualMachineScaleSetsUpdateInstancesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetsClient.UpdateInstances") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: VMInstanceIDs, - Constraints: []validation.Constraint{{Target: "VMInstanceIDs.InstanceIds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineScaleSetsClient", "UpdateInstances", err.Error()) - } - - req, err := client.UpdateInstancesPreparer(ctx, resourceGroupName, VMScaleSetName, VMInstanceIDs) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", nil, "Failure preparing request") - return - } - - result, err = client.UpdateInstancesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateInstancesPreparer prepares the UpdateInstances request. -func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/manualupgrade", pathParameters), - autorest.WithJSON(VMInstanceIDs), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateInstancesSender sends the UpdateInstances request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetsClient) UpdateInstancesSender(req *http.Request) (future VirtualMachineScaleSetsUpdateInstancesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateInstancesResponder handles the response to the UpdateInstances request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) UpdateInstancesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetvms.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetvms.go deleted file mode 100644 index 33e030538..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinescalesetvms.go +++ /dev/null @@ -1,1250 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineScaleSetVMsClient is the compute Client -type VirtualMachineScaleSetVMsClient struct { - BaseClient -} - -// NewVirtualMachineScaleSetVMsClient creates an instance of the VirtualMachineScaleSetVMsClient client. -func NewVirtualMachineScaleSetVMsClient(subscriptionID string) VirtualMachineScaleSetVMsClient { - return NewVirtualMachineScaleSetVMsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineScaleSetVMsClientWithBaseURI creates an instance of the VirtualMachineScaleSetVMsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewVirtualMachineScaleSetVMsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineScaleSetVMsClient { - return VirtualMachineScaleSetVMsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Deallocate deallocates a specific virtual machine in a VM scale set. Shuts down the virtual machine and releases the -// compute resources it uses. You are not billed for the compute resources of this virtual machine once it is -// deallocated. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Deallocate(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsDeallocateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Deallocate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeallocatePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure preparing request") - return - } - - result, err = client.DeallocateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", result.Response(), "Failure sending request") - return - } - - return -} - -// DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/deallocate", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeallocateSender sends the Deallocate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) DeallocateSender(req *http.Request) (future VirtualMachineScaleSetVMsDeallocateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeallocateResponder handles the response to the Deallocate request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Delete deletes a virtual machine from a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Delete(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualMachineScaleSetVMsClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) DeleteSender(req *http.Request) (future VirtualMachineScaleSetVMsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a virtual machine from a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVM, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualMachineScaleSetVMsClient) GetPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) GetResponder(resp *http.Response) (result VirtualMachineScaleSetVM, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetInstanceView gets the status of a virtual machine from a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) GetInstanceView(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMInstanceView, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.GetInstanceView") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetInstanceViewPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", nil, "Failure preparing request") - return - } - - resp, err := client.GetInstanceViewSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure sending request") - return - } - - result, err = client.GetInstanceViewResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure responding to request") - return - } - - return -} - -// GetInstanceViewPreparer prepares the GetInstanceView request. -func (client VirtualMachineScaleSetVMsClient) GetInstanceViewPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/instanceView", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetInstanceViewSender sends the GetInstanceView request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetInstanceViewResponder handles the response to the GetInstanceView request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) GetInstanceViewResponder(resp *http.Response) (result VirtualMachineScaleSetVMInstanceView, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets a list of all virtual machines in a VM scale sets. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the VM scale set. -// filter - the filter to apply to the operation. Allowed values are 'startswith(instanceView/statuses/code, -// 'PowerState') eq true', 'properties/latestModelApplied eq true', 'properties/latestModelApplied eq false'. -// selectParameter - the list parameters. Allowed values are 'instanceView', 'instanceView/statuses'. -// expand - the expand expression to apply to the operation. Allowed values are 'instanceView'. -func (client VirtualMachineScaleSetVMsClient) List(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.List") - defer func() { - sc := -1 - if result.vmssvlr.Response.Response != nil { - sc = result.vmssvlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vmssvlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending request") - return - } - - result.vmssvlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure responding to request") - return - } - if result.vmssvlr.hasNextLink() && result.vmssvlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachineScaleSetVMsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) ListResponder(resp *http.Response) (result VirtualMachineScaleSetVMListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetVMsClient) listNextResults(ctx context.Context, lastResults VirtualMachineScaleSetVMListResult) (result VirtualMachineScaleSetVMListResult, err error) { - req, err := lastResults.virtualMachineScaleSetVMListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualMachineScaleSetVMsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) - return -} - -// PerformMaintenance performs maintenance on a virtual machine in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) PerformMaintenance(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsPerformMaintenanceFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.PerformMaintenance") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PerformMaintenancePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PerformMaintenance", nil, "Failure preparing request") - return - } - - result, err = client.PerformMaintenanceSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PerformMaintenance", result.Response(), "Failure sending request") - return - } - - return -} - -// PerformMaintenancePreparer prepares the PerformMaintenance request. -func (client VirtualMachineScaleSetVMsClient) PerformMaintenancePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/performMaintenance", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PerformMaintenanceSender sends the PerformMaintenance request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) PerformMaintenanceSender(req *http.Request) (future VirtualMachineScaleSetVMsPerformMaintenanceFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PerformMaintenanceResponder handles the response to the PerformMaintenance request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) PerformMaintenanceResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// PowerOff power off (stop) a virtual machine in a VM scale set. Note that resources are still attached and you are -// getting charged for the resources. Instead, use deallocate to release resources and avoid charges. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) PowerOff(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsPowerOffFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.PowerOff") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PowerOffPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure preparing request") - return - } - - result, err = client.PowerOffSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", result.Response(), "Failure sending request") - return - } - - return -} - -// PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/poweroff", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PowerOffSender sends the PowerOff request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) PowerOffSender(req *http.Request) (future VirtualMachineScaleSetVMsPowerOffFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PowerOffResponder handles the response to the PowerOff request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Redeploy shuts down the virtual machine in the virtual machine scale set, moves it to a new node, and powers it back -// on. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Redeploy(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsRedeployFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Redeploy") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RedeployPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Redeploy", nil, "Failure preparing request") - return - } - - result, err = client.RedeploySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Redeploy", result.Response(), "Failure sending request") - return - } - - return -} - -// RedeployPreparer prepares the Redeploy request. -func (client VirtualMachineScaleSetVMsClient) RedeployPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/redeploy", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RedeploySender sends the Redeploy request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) RedeploySender(req *http.Request) (future VirtualMachineScaleSetVMsRedeployFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RedeployResponder handles the response to the Redeploy request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Reimage reimages (upgrade the operating system) a specific virtual machine in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -// VMScaleSetVMReimageInput - parameters for the Reimaging Virtual machine in ScaleSet. -func (client VirtualMachineScaleSetVMsClient) Reimage(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, VMScaleSetVMReimageInput *VirtualMachineScaleSetVMReimageParameters) (result VirtualMachineScaleSetVMsReimageFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Reimage") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ReimagePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, VMScaleSetVMReimageInput) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure preparing request") - return - } - - result, err = client.ReimageSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", result.Response(), "Failure sending request") - return - } - - return -} - -// ReimagePreparer prepares the Reimage request. -func (client VirtualMachineScaleSetVMsClient) ReimagePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, VMScaleSetVMReimageInput *VirtualMachineScaleSetVMReimageParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimage", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if VMScaleSetVMReimageInput != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(VMScaleSetVMReimageInput)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReimageSender sends the Reimage request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) ReimageSender(req *http.Request) (future VirtualMachineScaleSetVMsReimageFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ReimageResponder handles the response to the Reimage request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// ReimageAll allows you to re-image all the disks ( including data disks ) in the a VM scale set instance. This -// operation is only supported for managed disks. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) ReimageAll(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsReimageAllFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.ReimageAll") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ReimageAllPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", nil, "Failure preparing request") - return - } - - result, err = client.ReimageAllSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", result.Response(), "Failure sending request") - return - } - - return -} - -// ReimageAllPreparer prepares the ReimageAll request. -func (client VirtualMachineScaleSetVMsClient) ReimageAllPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimageall", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReimageAllSender sends the ReimageAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) ReimageAllSender(req *http.Request) (future VirtualMachineScaleSetVMsReimageAllFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ReimageAllResponder handles the response to the ReimageAll request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) ReimageAllResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Restart restarts a virtual machine in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Restart(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsRestartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Restart") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RestartPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure preparing request") - return - } - - result, err = client.RestartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", result.Response(), "Failure sending request") - return - } - - return -} - -// RestartPreparer prepares the Restart request. -func (client VirtualMachineScaleSetVMsClient) RestartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/restart", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestartSender sends the Restart request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) RestartSender(req *http.Request) (future VirtualMachineScaleSetVMsRestartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RestartResponder handles the response to the Restart request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// RunCommand run command on a virtual machine in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -// parameters - parameters supplied to the Run command operation. -func (client VirtualMachineScaleSetVMsClient) RunCommand(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters RunCommandInput) (result VirtualMachineScaleSetVMsRunCommandFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.RunCommand") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.CommandID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineScaleSetVMsClient", "RunCommand", err.Error()) - } - - req, err := client.RunCommandPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "RunCommand", nil, "Failure preparing request") - return - } - - result, err = client.RunCommandSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "RunCommand", result.Response(), "Failure sending request") - return - } - - return -} - -// RunCommandPreparer prepares the RunCommand request. -func (client VirtualMachineScaleSetVMsClient) RunCommandPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters RunCommandInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/runCommand", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RunCommandSender sends the RunCommand request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) RunCommandSender(req *http.Request) (future VirtualMachineScaleSetVMsRunCommandFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RunCommandResponder handles the response to the RunCommand request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) RunCommandResponder(resp *http.Response) (result RunCommandResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Start starts a virtual machine in a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set. -// instanceID - the instance ID of the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Start(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMsStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, VMScaleSetName, instanceID) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client VirtualMachineScaleSetVMsClient) StartPreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) StartSender(req *http.Request) (future VirtualMachineScaleSetVMsStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update updates a virtual machine of a VM scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// VMScaleSetName - the name of the VM scale set where the extension should be create or updated. -// instanceID - the instance ID of the virtual machine. -// parameters - parameters supplied to the Update Virtual Machine Scale Sets VM operation. -func (client VirtualMachineScaleSetVMsClient) Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM) (result VirtualMachineScaleSetVMsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineScaleSetVMsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SecretURL", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.DiskEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.KeyURL", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualMachineScaleSetVMProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineScaleSetVMsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client VirtualMachineScaleSetVMsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters VirtualMachineScaleSetVM) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "instanceId": autorest.Encode("path", instanceID), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", VMScaleSetName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.InstanceID = nil - parameters.Sku = nil - parameters.Resources = nil - parameters.Zones = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineScaleSetVMsClient) UpdateSender(req *http.Request) (future VirtualMachineScaleSetVMsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) UpdateResponder(resp *http.Response) (result VirtualMachineScaleSetVM, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinesizes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinesizes.go deleted file mode 100644 index 449ce499a..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute/virtualmachinesizes.go +++ /dev/null @@ -1,114 +0,0 @@ -package compute - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualMachineSizesClient is the compute Client -type VirtualMachineSizesClient struct { - BaseClient -} - -// NewVirtualMachineSizesClient creates an instance of the VirtualMachineSizesClient client. -func NewVirtualMachineSizesClient(subscriptionID string) VirtualMachineSizesClient { - return NewVirtualMachineSizesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualMachineSizesClientWithBaseURI creates an instance of the VirtualMachineSizesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewVirtualMachineSizesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineSizesClient { - return VirtualMachineSizesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List this API is deprecated. Use [Resources -// Skus](https://docs.microsoft.com/en-us/rest/api/compute/resourceskus/list) -// Parameters: -// location - the location upon which virtual-machine-sizes is queried. -func (client VirtualMachineSizesClient) List(ctx context.Context, location string) (result VirtualMachineSizeListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSizesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("compute.VirtualMachineSizesClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualMachineSizesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/vmSizes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualMachineSizesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualMachineSizesClient) ListResponder(resp *http.Response) (result VirtualMachineSizeListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/CHANGELOG.md deleted file mode 100644 index 52911e4cc..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/_meta.json deleted file mode 100644 index 40a859850..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "3c764635e7d442b3e74caf593029fcd440b3ef82", - "readme": "/_/azure-rest-api-specs/specification/network/resource-manager/readme.md", - "tag": "package-2018-10", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2018-10 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION /_/azure-rest-api-specs/specification/network/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/applicationgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/applicationgateways.go deleted file mode 100644 index 7237c51f0..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/applicationgateways.go +++ /dev/null @@ -1,1176 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationGatewaysClient is the network Client -type ApplicationGatewaysClient struct { - BaseClient -} - -// NewApplicationGatewaysClient creates an instance of the ApplicationGatewaysClient client. -func NewApplicationGatewaysClient(subscriptionID string) ApplicationGatewaysClient { - return NewApplicationGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationGatewaysClientWithBaseURI creates an instance of the ApplicationGatewaysClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewApplicationGatewaysClientWithBaseURI(baseURI string, subscriptionID string) ApplicationGatewaysClient { - return ApplicationGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// BackendHealth gets the backend health of the specified application gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// expand - expands BackendAddressPool and BackendHttpSettings referenced in backend health. -func (client ApplicationGatewaysClient) BackendHealth(ctx context.Context, resourceGroupName string, applicationGatewayName string, expand string) (result ApplicationGatewaysBackendHealthFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.BackendHealth") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.BackendHealthPreparer(ctx, resourceGroupName, applicationGatewayName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", nil, "Failure preparing request") - return - } - - result, err = client.BackendHealthSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", result.Response(), "Failure sending request") - return - } - - return -} - -// BackendHealthPreparer prepares the BackendHealth request. -func (client ApplicationGatewaysClient) BackendHealthPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/backendhealth", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BackendHealthSender sends the BackendHealth request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) BackendHealthSender(req *http.Request) (future ApplicationGatewaysBackendHealthFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// BackendHealthResponder handles the response to the BackendHealth request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) BackendHealthResponder(resp *http.Response) (result ApplicationGatewayBackendHealth, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// parameters - parameters supplied to the create or update application gateway operation. -func (client ApplicationGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway) (result ApplicationGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.Enabled", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.RuleSetType", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.RuleSetVersion", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySize", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySize", Name: validation.InclusiveMaximum, Rule: int64(128), Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySize", Name: validation.InclusiveMinimum, Rule: int64(8), Chain: nil}, - }}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySizeInKb", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySizeInKb", Name: validation.InclusiveMaximum, Rule: int64(128), Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySizeInKb", Name: validation.InclusiveMinimum, Rule: int64(8), Chain: nil}, - }}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.FileUploadLimitInMb", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.FileUploadLimitInMb", Name: validation.InclusiveMaximum, Rule: int64(500), Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.FileUploadLimitInMb", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration.MinCapacity", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration.MinCapacity", Name: validation.InclusiveMinimum, Rule: int64(2), Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.ApplicationGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, applicationGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) CreateOrUpdateSender(req *http.Request) (future ApplicationGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result ApplicationGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Delete(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ApplicationGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) DeleteSender(req *http.Request) (future ApplicationGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Get(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ApplicationGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) GetResponder(resp *http.Response) (result ApplicationGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSslPredefinedPolicy gets Ssl predefined policy with the specified policy name. -// Parameters: -// predefinedPolicyName - name of Ssl predefined policy. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicy(ctx context.Context, predefinedPolicyName string) (result ApplicationGatewaySslPredefinedPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.GetSslPredefinedPolicy") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetSslPredefinedPolicyPreparer(ctx, predefinedPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "GetSslPredefinedPolicy", nil, "Failure preparing request") - return - } - - resp, err := client.GetSslPredefinedPolicySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "GetSslPredefinedPolicy", resp, "Failure sending request") - return - } - - result, err = client.GetSslPredefinedPolicyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "GetSslPredefinedPolicy", resp, "Failure responding to request") - return - } - - return -} - -// GetSslPredefinedPolicyPreparer prepares the GetSslPredefinedPolicy request. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicyPreparer(ctx context.Context, predefinedPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "predefinedPolicyName": autorest.Encode("path", predefinedPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies/{predefinedPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSslPredefinedPolicySender sends the GetSslPredefinedPolicy request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetSslPredefinedPolicyResponder handles the response to the GetSslPredefinedPolicy request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicyResponder(resp *http.Response) (result ApplicationGatewaySslPredefinedPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all application gateways in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ApplicationGatewaysClient) List(ctx context.Context, resourceGroupName string) (result ApplicationGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.List") - defer func() { - sc := -1 - if result.aglr.Response.Response != nil { - sc = result.aglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.aglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.aglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.aglr.hasNextLink() && result.aglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ApplicationGatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListResponder(resp *http.Response) (result ApplicationGatewayListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ApplicationGatewaysClient) listNextResults(ctx context.Context, lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { - req, err := lastResults.applicationGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewaysClient) ListComplete(ctx context.Context, resourceGroupName string) (result ApplicationGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the application gateways in a subscription. -func (client ApplicationGatewaysClient) ListAll(ctx context.Context) (result ApplicationGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAll") - defer func() { - sc := -1 - if result.aglr.Response.Response != nil { - sc = result.aglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.aglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending request") - return - } - - result.aglr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure responding to request") - return - } - if result.aglr.hasNextLink() && result.aglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ApplicationGatewaysClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAllResponder(resp *http.Response) (result ApplicationGatewayListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ApplicationGatewaysClient) listAllNextResults(ctx context.Context, lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { - req, err := lastResults.applicationGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewaysClient) ListAllComplete(ctx context.Context) (result ApplicationGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListAvailableSslOptions lists available Ssl options for configuring Ssl policy. -func (client ApplicationGatewaysClient) ListAvailableSslOptions(ctx context.Context) (result ApplicationGatewayAvailableSslOptions, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableSslOptions") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableSslOptionsPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslOptions", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableSslOptionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslOptions", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableSslOptionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslOptions", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableSslOptionsPreparer prepares the ListAvailableSslOptions request. -func (client ApplicationGatewaysClient) ListAvailableSslOptionsPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableSslOptionsSender sends the ListAvailableSslOptions request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableSslOptionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableSslOptionsResponder handles the response to the ListAvailableSslOptions request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableSslOptionsResponder(resp *http.Response) (result ApplicationGatewayAvailableSslOptions, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAvailableSslPredefinedPolicies lists all SSL predefined policies for configuring Ssl policy. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPolicies(ctx context.Context) (result ApplicationGatewayAvailableSslPredefinedPoliciesPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableSslPredefinedPolicies") - defer func() { - sc := -1 - if result.agaspp.Response.Response != nil { - sc = result.agaspp.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAvailableSslPredefinedPoliciesNextResults - req, err := client.ListAvailableSslPredefinedPoliciesPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslPredefinedPolicies", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableSslPredefinedPoliciesSender(req) - if err != nil { - result.agaspp.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslPredefinedPolicies", resp, "Failure sending request") - return - } - - result.agaspp, err = client.ListAvailableSslPredefinedPoliciesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslPredefinedPolicies", resp, "Failure responding to request") - return - } - if result.agaspp.hasNextLink() && result.agaspp.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAvailableSslPredefinedPoliciesPreparer prepares the ListAvailableSslPredefinedPolicies request. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableSslPredefinedPoliciesSender sends the ListAvailableSslPredefinedPolicies request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableSslPredefinedPoliciesResponder handles the response to the ListAvailableSslPredefinedPolicies request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesResponder(resp *http.Response) (result ApplicationGatewayAvailableSslPredefinedPolicies, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAvailableSslPredefinedPoliciesNextResults retrieves the next set of results, if any. -func (client ApplicationGatewaysClient) listAvailableSslPredefinedPoliciesNextResults(ctx context.Context, lastResults ApplicationGatewayAvailableSslPredefinedPolicies) (result ApplicationGatewayAvailableSslPredefinedPolicies, err error) { - req, err := lastResults.applicationGatewayAvailableSslPredefinedPoliciesPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAvailableSslPredefinedPoliciesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAvailableSslPredefinedPoliciesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAvailableSslPredefinedPoliciesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAvailableSslPredefinedPoliciesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAvailableSslPredefinedPoliciesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAvailableSslPredefinedPoliciesComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesComplete(ctx context.Context) (result ApplicationGatewayAvailableSslPredefinedPoliciesIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableSslPredefinedPolicies") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAvailableSslPredefinedPolicies(ctx) - return -} - -// ListAvailableWafRuleSets lists all available web application firewall rule sets. -func (client ApplicationGatewaysClient) ListAvailableWafRuleSets(ctx context.Context) (result ApplicationGatewayAvailableWafRuleSetsResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableWafRuleSets") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableWafRuleSetsPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableWafRuleSetsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableWafRuleSetsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableWafRuleSetsPreparer prepares the ListAvailableWafRuleSets request. -func (client ApplicationGatewaysClient) ListAvailableWafRuleSetsPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableWafRuleSets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableWafRuleSetsSender sends the ListAvailableWafRuleSets request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableWafRuleSetsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableWafRuleSetsResponder handles the response to the ListAvailableWafRuleSets request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableWafRuleSetsResponder(resp *http.Response) (result ApplicationGatewayAvailableWafRuleSetsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Start starts the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Start(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewaysStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client ApplicationGatewaysClient) StartPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) StartSender(req *http.Request) (future ApplicationGatewaysStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stops the specified application gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Stop(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewaysStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client ApplicationGatewaysClient) StopPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) StopSender(req *http.Request) (future ApplicationGatewaysStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// UpdateTags updates the specified application gateway tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// parameters - parameters supplied to update application gateway tags. -func (client ApplicationGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters TagsObject) (result ApplicationGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, applicationGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ApplicationGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) UpdateTagsSender(req *http.Request) (future ApplicationGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) UpdateTagsResponder(resp *http.Response) (result ApplicationGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/applicationsecuritygroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/applicationsecuritygroups.go deleted file mode 100644 index a4fef87b5..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/applicationsecuritygroups.go +++ /dev/null @@ -1,498 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationSecurityGroupsClient is the network Client -type ApplicationSecurityGroupsClient struct { - BaseClient -} - -// NewApplicationSecurityGroupsClient creates an instance of the ApplicationSecurityGroupsClient client. -func NewApplicationSecurityGroupsClient(subscriptionID string) ApplicationSecurityGroupsClient { - return NewApplicationSecurityGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationSecurityGroupsClientWithBaseURI creates an instance of the ApplicationSecurityGroupsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewApplicationSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) ApplicationSecurityGroupsClient { - return ApplicationSecurityGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an application security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationSecurityGroupName - the name of the application security group. -// parameters - parameters supplied to the create or update ApplicationSecurityGroup operation. -func (client ApplicationSecurityGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup) (result ApplicationSecurityGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, applicationSecurityGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ApplicationSecurityGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (future ApplicationSecurityGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result ApplicationSecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified application security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationSecurityGroupName - the name of the application security group. -func (client ApplicationSecurityGroupsClient) Delete(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (result ApplicationSecurityGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, applicationSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ApplicationSecurityGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) DeleteSender(req *http.Request) (future ApplicationSecurityGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified application security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationSecurityGroupName - the name of the application security group. -func (client ApplicationSecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (result ApplicationSecurityGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, applicationSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ApplicationSecurityGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) GetResponder(resp *http.Response) (result ApplicationSecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the application security groups in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ApplicationSecurityGroupsClient) List(ctx context.Context, resourceGroupName string) (result ApplicationSecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.List") - defer func() { - sc := -1 - if result.asglr.Response.Response != nil { - sc = result.asglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.asglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", resp, "Failure sending request") - return - } - - result.asglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.asglr.hasNextLink() && result.asglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ApplicationSecurityGroupsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) ListResponder(resp *http.Response) (result ApplicationSecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ApplicationSecurityGroupsClient) listNextResults(ctx context.Context, lastResults ApplicationSecurityGroupListResult) (result ApplicationSecurityGroupListResult, err error) { - req, err := lastResults.applicationSecurityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationSecurityGroupsClient) ListComplete(ctx context.Context, resourceGroupName string) (result ApplicationSecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all application security groups in a subscription. -func (client ApplicationSecurityGroupsClient) ListAll(ctx context.Context) (result ApplicationSecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.asglr.Response.Response != nil { - sc = result.asglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.asglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", resp, "Failure sending request") - return - } - - result.asglr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.asglr.hasNextLink() && result.asglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ApplicationSecurityGroupsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) ListAllResponder(resp *http.Response) (result ApplicationSecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ApplicationSecurityGroupsClient) listAllNextResults(ctx context.Context, lastResults ApplicationSecurityGroupListResult) (result ApplicationSecurityGroupListResult, err error) { - req, err := lastResults.applicationSecurityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationSecurityGroupsClient) ListAllComplete(ctx context.Context) (result ApplicationSecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availabledelegations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availabledelegations.go deleted file mode 100644 index 90a3d2b5c..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availabledelegations.go +++ /dev/null @@ -1,148 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailableDelegationsClient is the network Client -type AvailableDelegationsClient struct { - BaseClient -} - -// NewAvailableDelegationsClient creates an instance of the AvailableDelegationsClient client. -func NewAvailableDelegationsClient(subscriptionID string) AvailableDelegationsClient { - return NewAvailableDelegationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailableDelegationsClientWithBaseURI creates an instance of the AvailableDelegationsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewAvailableDelegationsClientWithBaseURI(baseURI string, subscriptionID string) AvailableDelegationsClient { - return AvailableDelegationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all of the available subnet delegations for this subscription in this region. -// Parameters: -// location - the location of the subnet. -func (client AvailableDelegationsClient) List(ctx context.Context, location string) (result AvailableDelegationsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsClient.List") - defer func() { - sc := -1 - if result.adr.Response.Response != nil { - sc = result.adr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.adr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "List", resp, "Failure sending request") - return - } - - result.adr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "List", resp, "Failure responding to request") - return - } - if result.adr.hasNextLink() && result.adr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailableDelegationsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/availableDelegations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableDelegationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailableDelegationsClient) ListResponder(resp *http.Response) (result AvailableDelegationsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client AvailableDelegationsClient) listNextResults(ctx context.Context, lastResults AvailableDelegationsResult) (result AvailableDelegationsResult, err error) { - req, err := lastResults.availableDelegationsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableDelegationsClient) ListComplete(ctx context.Context, location string) (result AvailableDelegationsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availableendpointservices.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availableendpointservices.go deleted file mode 100644 index a9be34ca6..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availableendpointservices.go +++ /dev/null @@ -1,148 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailableEndpointServicesClient is the network Client -type AvailableEndpointServicesClient struct { - BaseClient -} - -// NewAvailableEndpointServicesClient creates an instance of the AvailableEndpointServicesClient client. -func NewAvailableEndpointServicesClient(subscriptionID string) AvailableEndpointServicesClient { - return NewAvailableEndpointServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailableEndpointServicesClientWithBaseURI creates an instance of the AvailableEndpointServicesClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewAvailableEndpointServicesClientWithBaseURI(baseURI string, subscriptionID string) AvailableEndpointServicesClient { - return AvailableEndpointServicesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list what values of endpoint services are available for use. -// Parameters: -// location - the location to check available endpoint services. -func (client AvailableEndpointServicesClient) List(ctx context.Context, location string) (result EndpointServicesListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableEndpointServicesClient.List") - defer func() { - sc := -1 - if result.eslr.Response.Response != nil { - sc = result.eslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.eslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", resp, "Failure sending request") - return - } - - result.eslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", resp, "Failure responding to request") - return - } - if result.eslr.hasNextLink() && result.eslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailableEndpointServicesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/virtualNetworkAvailableEndpointServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableEndpointServicesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailableEndpointServicesClient) ListResponder(resp *http.Response) (result EndpointServicesListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client AvailableEndpointServicesClient) listNextResults(ctx context.Context, lastResults EndpointServicesListResult) (result EndpointServicesListResult, err error) { - req, err := lastResults.endpointServicesListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableEndpointServicesClient) ListComplete(ctx context.Context, location string) (result EndpointServicesListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableEndpointServicesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availableresourcegroupdelegations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availableresourcegroupdelegations.go deleted file mode 100644 index 82dbc6b17..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/availableresourcegroupdelegations.go +++ /dev/null @@ -1,151 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailableResourceGroupDelegationsClient is the network Client -type AvailableResourceGroupDelegationsClient struct { - BaseClient -} - -// NewAvailableResourceGroupDelegationsClient creates an instance of the AvailableResourceGroupDelegationsClient -// client. -func NewAvailableResourceGroupDelegationsClient(subscriptionID string) AvailableResourceGroupDelegationsClient { - return NewAvailableResourceGroupDelegationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailableResourceGroupDelegationsClientWithBaseURI creates an instance of the -// AvailableResourceGroupDelegationsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAvailableResourceGroupDelegationsClientWithBaseURI(baseURI string, subscriptionID string) AvailableResourceGroupDelegationsClient { - return AvailableResourceGroupDelegationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all of the available subnet delegations for this resource group in this region. -// Parameters: -// location - the location of the domain name. -// resourceGroupName - the name of the resource group. -func (client AvailableResourceGroupDelegationsClient) List(ctx context.Context, location string, resourceGroupName string) (result AvailableDelegationsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableResourceGroupDelegationsClient.List") - defer func() { - sc := -1 - if result.adr.Response.Response != nil { - sc = result.adr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.adr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "List", resp, "Failure sending request") - return - } - - result.adr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "List", resp, "Failure responding to request") - return - } - if result.adr.hasNextLink() && result.adr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailableResourceGroupDelegationsClient) ListPreparer(ctx context.Context, location string, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/availableDelegations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableResourceGroupDelegationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailableResourceGroupDelegationsClient) ListResponder(resp *http.Response) (result AvailableDelegationsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client AvailableResourceGroupDelegationsClient) listNextResults(ctx context.Context, lastResults AvailableDelegationsResult) (result AvailableDelegationsResult, err error) { - req, err := lastResults.availableDelegationsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableResourceGroupDelegationsClient) ListComplete(ctx context.Context, location string, resourceGroupName string) (result AvailableDelegationsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableResourceGroupDelegationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/azurefirewallfqdntags.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/azurefirewallfqdntags.go deleted file mode 100644 index b7e7da18b..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/azurefirewallfqdntags.go +++ /dev/null @@ -1,145 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AzureFirewallFqdnTagsClient is the network Client -type AzureFirewallFqdnTagsClient struct { - BaseClient -} - -// NewAzureFirewallFqdnTagsClient creates an instance of the AzureFirewallFqdnTagsClient client. -func NewAzureFirewallFqdnTagsClient(subscriptionID string) AzureFirewallFqdnTagsClient { - return NewAzureFirewallFqdnTagsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAzureFirewallFqdnTagsClientWithBaseURI creates an instance of the AzureFirewallFqdnTagsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewAzureFirewallFqdnTagsClientWithBaseURI(baseURI string, subscriptionID string) AzureFirewallFqdnTagsClient { - return AzureFirewallFqdnTagsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// ListAll gets all the Azure Firewall FQDN Tags in a subscription. -func (client AzureFirewallFqdnTagsClient) ListAll(ctx context.Context) (result AzureFirewallFqdnTagListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagsClient.ListAll") - defer func() { - sc := -1 - if result.afftlr.Response.Response != nil { - sc = result.afftlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.afftlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "ListAll", resp, "Failure sending request") - return - } - - result.afftlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.afftlr.hasNextLink() && result.afftlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client AzureFirewallFqdnTagsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewallFqdnTags", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallFqdnTagsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client AzureFirewallFqdnTagsClient) ListAllResponder(resp *http.Response) (result AzureFirewallFqdnTagListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client AzureFirewallFqdnTagsClient) listAllNextResults(ctx context.Context, lastResults AzureFirewallFqdnTagListResult) (result AzureFirewallFqdnTagListResult, err error) { - req, err := lastResults.azureFirewallFqdnTagListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client AzureFirewallFqdnTagsClient) ListAllComplete(ctx context.Context) (result AzureFirewallFqdnTagListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/azurefirewalls.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/azurefirewalls.go deleted file mode 100644 index ffd77f264..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/azurefirewalls.go +++ /dev/null @@ -1,497 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AzureFirewallsClient is the network Client -type AzureFirewallsClient struct { - BaseClient -} - -// NewAzureFirewallsClient creates an instance of the AzureFirewallsClient client. -func NewAzureFirewallsClient(subscriptionID string) AzureFirewallsClient { - return NewAzureFirewallsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAzureFirewallsClientWithBaseURI creates an instance of the AzureFirewallsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAzureFirewallsClientWithBaseURI(baseURI string, subscriptionID string) AzureFirewallsClient { - return AzureFirewallsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Azure Firewall. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the Azure Firewall. -// parameters - parameters supplied to the create or update Azure Firewall operation. -func (client AzureFirewallsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall) (result AzureFirewallsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, azureFirewallName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AzureFirewallsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) CreateOrUpdateSender(req *http.Request) (future AzureFirewallsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) CreateOrUpdateResponder(resp *http.Response) (result AzureFirewall, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Azure Firewall. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the Azure Firewall. -func (client AzureFirewallsClient) Delete(ctx context.Context, resourceGroupName string, azureFirewallName string) (result AzureFirewallsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, azureFirewallName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AzureFirewallsClient) DeletePreparer(ctx context.Context, resourceGroupName string, azureFirewallName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) DeleteSender(req *http.Request) (future AzureFirewallsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Azure Firewall. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the Azure Firewall. -func (client AzureFirewallsClient) Get(ctx context.Context, resourceGroupName string, azureFirewallName string) (result AzureFirewall, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, azureFirewallName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AzureFirewallsClient) GetPreparer(ctx context.Context, resourceGroupName string, azureFirewallName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) GetResponder(resp *http.Response) (result AzureFirewall, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Azure Firewalls in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client AzureFirewallsClient) List(ctx context.Context, resourceGroupName string) (result AzureFirewallListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.List") - defer func() { - sc := -1 - if result.aflr.Response.Response != nil { - sc = result.aflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.aflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", resp, "Failure sending request") - return - } - - result.aflr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", resp, "Failure responding to request") - return - } - if result.aflr.hasNextLink() && result.aflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AzureFirewallsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) ListResponder(resp *http.Response) (result AzureFirewallListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client AzureFirewallsClient) listNextResults(ctx context.Context, lastResults AzureFirewallListResult) (result AzureFirewallListResult, err error) { - req, err := lastResults.azureFirewallListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AzureFirewallsClient) ListComplete(ctx context.Context, resourceGroupName string) (result AzureFirewallListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the Azure Firewalls in a subscription. -func (client AzureFirewallsClient) ListAll(ctx context.Context) (result AzureFirewallListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.ListAll") - defer func() { - sc := -1 - if result.aflr.Response.Response != nil { - sc = result.aflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.aflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", resp, "Failure sending request") - return - } - - result.aflr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.aflr.hasNextLink() && result.aflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client AzureFirewallsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewalls", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) ListAllResponder(resp *http.Response) (result AzureFirewallListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client AzureFirewallsClient) listAllNextResults(ctx context.Context, lastResults AzureFirewallListResult) (result AzureFirewallListResult, err error) { - req, err := lastResults.azureFirewallListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client AzureFirewallsClient) ListAllComplete(ctx context.Context) (result AzureFirewallListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/bgpservicecommunities.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/bgpservicecommunities.go deleted file mode 100644 index bef8d21b8..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/bgpservicecommunities.go +++ /dev/null @@ -1,145 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// BgpServiceCommunitiesClient is the network Client -type BgpServiceCommunitiesClient struct { - BaseClient -} - -// NewBgpServiceCommunitiesClient creates an instance of the BgpServiceCommunitiesClient client. -func NewBgpServiceCommunitiesClient(subscriptionID string) BgpServiceCommunitiesClient { - return NewBgpServiceCommunitiesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBgpServiceCommunitiesClientWithBaseURI creates an instance of the BgpServiceCommunitiesClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewBgpServiceCommunitiesClientWithBaseURI(baseURI string, subscriptionID string) BgpServiceCommunitiesClient { - return BgpServiceCommunitiesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all the available bgp service communities. -func (client BgpServiceCommunitiesClient) List(ctx context.Context) (result BgpServiceCommunityListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunitiesClient.List") - defer func() { - sc := -1 - if result.bsclr.Response.Response != nil { - sc = result.bsclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.bsclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure sending request") - return - } - - result.bsclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure responding to request") - return - } - if result.bsclr.hasNextLink() && result.bsclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BgpServiceCommunitiesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client BgpServiceCommunitiesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BgpServiceCommunitiesClient) ListResponder(resp *http.Response) (result BgpServiceCommunityListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client BgpServiceCommunitiesClient) listNextResults(ctx context.Context, lastResults BgpServiceCommunityListResult) (result BgpServiceCommunityListResult, err error) { - req, err := lastResults.bgpServiceCommunityListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client BgpServiceCommunitiesClient) ListComplete(ctx context.Context) (result BgpServiceCommunityListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunitiesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/client.go deleted file mode 100644 index efb7a0f19..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/client.go +++ /dev/null @@ -1,198 +0,0 @@ -// Package network implements the Azure ARM Network service API version . -// -// Network Client -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -const ( - // DefaultBaseURI is the default URI used for the service Network - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Network. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string -} - -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, - } -} - -// CheckDNSNameAvailability checks whether a domain name in the cloudapp.azure.com zone is available for use. -// Parameters: -// location - the location of the domain name. -// domainNameLabel - the domain name to be verified. It must conform to the following regular expression: -// ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. -func (client BaseClient) CheckDNSNameAvailability(ctx context.Context, location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CheckDNSNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CheckDNSNameAvailabilityPreparer(ctx, location, domainNameLabel) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckDNSNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckDNSNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckDNSNameAvailabilityPreparer prepares the CheckDNSNameAvailability request. -func (client BaseClient) CheckDNSNameAvailabilityPreparer(ctx context.Context, location string, domainNameLabel string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - "domainNameLabel": autorest.Encode("query", domainNameLabel), - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckDNSNameAvailabilitySender sends the CheckDNSNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) CheckDNSNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckDNSNameAvailabilityResponder handles the response to the CheckDNSNameAvailability request. The method always -// closes the http.Response Body. -func (client BaseClient) CheckDNSNameAvailabilityResponder(resp *http.Response) (result DNSNameAvailabilityResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SupportedSecurityProviders gives the supported security providers for the virtual wan. -// Parameters: -// resourceGroupName - the resource group name. -// virtualWANName - the name of the VirtualWAN for which supported security providers are needed. -func (client BaseClient) SupportedSecurityProviders(ctx context.Context, resourceGroupName string, virtualWANName string) (result VirtualWanSecurityProviders, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SupportedSecurityProviders") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.SupportedSecurityProvidersPreparer(ctx, resourceGroupName, virtualWANName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", nil, "Failure preparing request") - return - } - - resp, err := client.SupportedSecurityProvidersSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", resp, "Failure sending request") - return - } - - result, err = client.SupportedSecurityProvidersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", resp, "Failure responding to request") - return - } - - return -} - -// SupportedSecurityProvidersPreparer prepares the SupportedSecurityProviders request. -func (client BaseClient) SupportedSecurityProvidersPreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/supportedSecurityProviders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SupportedSecurityProvidersSender sends the SupportedSecurityProviders request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SupportedSecurityProvidersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SupportedSecurityProvidersResponder handles the response to the SupportedSecurityProviders request. The method always -// closes the http.Response Body. -func (client BaseClient) SupportedSecurityProvidersResponder(resp *http.Response) (result VirtualWanSecurityProviders, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/connectionmonitors.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/connectionmonitors.go deleted file mode 100644 index d69dcc99a..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/connectionmonitors.go +++ /dev/null @@ -1,602 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ConnectionMonitorsClient is the network Client -type ConnectionMonitorsClient struct { - BaseClient -} - -// NewConnectionMonitorsClient creates an instance of the ConnectionMonitorsClient client. -func NewConnectionMonitorsClient(subscriptionID string) ConnectionMonitorsClient { - return NewConnectionMonitorsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewConnectionMonitorsClientWithBaseURI creates an instance of the ConnectionMonitorsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewConnectionMonitorsClientWithBaseURI(baseURI string, subscriptionID string) ConnectionMonitorsClient { - return ConnectionMonitorsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -// parameters - parameters that define the operation to create a connection monitor. -func (client ConnectionMonitorsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor) (result ConnectionMonitorsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Source", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Source.ResourceID", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.ConnectionMonitorParameters.Destination", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ConnectionMonitorsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ConnectionMonitorsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) CreateOrUpdateSender(req *http.Request) (future ConnectionMonitorsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) CreateOrUpdateResponder(resp *http.Response) (result ConnectionMonitorResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ConnectionMonitorsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) DeleteSender(req *http.Request) (future ConnectionMonitorsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a connection monitor by name. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ConnectionMonitorsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) GetResponder(resp *http.Response) (result ConnectionMonitorResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all connection monitors for the specified Network Watcher. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -func (client ConnectionMonitorsClient) List(ctx context.Context, resourceGroupName string, networkWatcherName string) (result ConnectionMonitorListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, networkWatcherName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ConnectionMonitorsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) ListResponder(resp *http.Response) (result ConnectionMonitorListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Query query a snapshot of the most recent connection states. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name given to the connection monitor. -func (client ConnectionMonitorsClient) Query(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsQueryFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Query") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.QueryPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Query", nil, "Failure preparing request") - return - } - - result, err = client.QuerySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Query", result.Response(), "Failure sending request") - return - } - - return -} - -// QueryPreparer prepares the Query request. -func (client ConnectionMonitorsClient) QueryPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/query", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// QuerySender sends the Query request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) QuerySender(req *http.Request) (future ConnectionMonitorsQueryFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// QueryResponder handles the response to the Query request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) QueryResponder(resp *http.Response) (result ConnectionMonitorQueryResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Start starts the specified connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Start(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client ConnectionMonitorsClient) StartPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) StartSender(req *http.Request) (future ConnectionMonitorsStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stops the specified connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Stop(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client ConnectionMonitorsClient) StopPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) StopSender(req *http.Request) (future ConnectionMonitorsStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/ddosprotectionplans.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/ddosprotectionplans.go deleted file mode 100644 index 76f49bd1b..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/ddosprotectionplans.go +++ /dev/null @@ -1,501 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DdosProtectionPlansClient is the network Client -type DdosProtectionPlansClient struct { - BaseClient -} - -// NewDdosProtectionPlansClient creates an instance of the DdosProtectionPlansClient client. -func NewDdosProtectionPlansClient(subscriptionID string) DdosProtectionPlansClient { - return NewDdosProtectionPlansClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDdosProtectionPlansClientWithBaseURI creates an instance of the DdosProtectionPlansClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewDdosProtectionPlansClientWithBaseURI(baseURI string, subscriptionID string) DdosProtectionPlansClient { - return DdosProtectionPlansClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DDoS protection plan. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosProtectionPlanName - the name of the DDoS protection plan. -// parameters - parameters supplied to the create or update operation. -func (client DdosProtectionPlansClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan) (result DdosProtectionPlansCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, ddosProtectionPlanName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DdosProtectionPlansClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.ID = nil - parameters.Name = nil - parameters.Type = nil - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) CreateOrUpdateSender(req *http.Request) (future DdosProtectionPlansCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) CreateOrUpdateResponder(resp *http.Response) (result DdosProtectionPlan, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified DDoS protection plan. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosProtectionPlanName - the name of the DDoS protection plan. -func (client DdosProtectionPlansClient) Delete(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (result DdosProtectionPlansDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, ddosProtectionPlanName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DdosProtectionPlansClient) DeletePreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) DeleteSender(req *http.Request) (future DdosProtectionPlansDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified DDoS protection plan. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosProtectionPlanName - the name of the DDoS protection plan. -func (client DdosProtectionPlansClient) Get(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (result DdosProtectionPlan, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, ddosProtectionPlanName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DdosProtectionPlansClient) GetPreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) GetResponder(resp *http.Response) (result DdosProtectionPlan, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all DDoS protection plans in a subscription. -func (client DdosProtectionPlansClient) List(ctx context.Context) (result DdosProtectionPlanListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.List") - defer func() { - sc := -1 - if result.dpplr.Response.Response != nil { - sc = result.dpplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.dpplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", resp, "Failure sending request") - return - } - - result.dpplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", resp, "Failure responding to request") - return - } - if result.dpplr.hasNextLink() && result.dpplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DdosProtectionPlansClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ddosProtectionPlans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) ListResponder(resp *http.Response) (result DdosProtectionPlanListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client DdosProtectionPlansClient) listNextResults(ctx context.Context, lastResults DdosProtectionPlanListResult) (result DdosProtectionPlanListResult, err error) { - req, err := lastResults.ddosProtectionPlanListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client DdosProtectionPlansClient) ListComplete(ctx context.Context) (result DdosProtectionPlanListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all the DDoS protection plans in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client DdosProtectionPlansClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result DdosProtectionPlanListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.dpplr.Response.Response != nil { - sc = result.dpplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.dpplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.dpplr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.dpplr.hasNextLink() && result.dpplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client DdosProtectionPlansClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) ListByResourceGroupResponder(resp *http.Response) (result DdosProtectionPlanListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client DdosProtectionPlansClient) listByResourceGroupNextResults(ctx context.Context, lastResults DdosProtectionPlanListResult) (result DdosProtectionPlanListResult, err error) { - req, err := lastResults.ddosProtectionPlanListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client DdosProtectionPlansClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result DdosProtectionPlanListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/defaultsecurityrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/defaultsecurityrules.go deleted file mode 100644 index 4357a32ce..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/defaultsecurityrules.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DefaultSecurityRulesClient is the network Client -type DefaultSecurityRulesClient struct { - BaseClient -} - -// NewDefaultSecurityRulesClient creates an instance of the DefaultSecurityRulesClient client. -func NewDefaultSecurityRulesClient(subscriptionID string) DefaultSecurityRulesClient { - return NewDefaultSecurityRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDefaultSecurityRulesClientWithBaseURI creates an instance of the DefaultSecurityRulesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewDefaultSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) DefaultSecurityRulesClient { - return DefaultSecurityRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get get the specified default network security rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// defaultSecurityRuleName - the name of the default security rule. -func (client DefaultSecurityRulesClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (result SecurityRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DefaultSecurityRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, defaultSecurityRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DefaultSecurityRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "defaultSecurityRuleName": autorest.Encode("path", defaultSecurityRuleName), - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client DefaultSecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DefaultSecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all default security rules in a network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -func (client DefaultSecurityRulesClient) List(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DefaultSecurityRulesClient.List") - defer func() { - sc := -1 - if result.srlr.Response.Response != nil { - sc = result.srlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.srlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure sending request") - return - } - - result.srlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure responding to request") - return - } - if result.srlr.hasNextLink() && result.srlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DefaultSecurityRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client DefaultSecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DefaultSecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client DefaultSecurityRulesClient) listNextResults(ctx context.Context, lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) { - req, err := lastResults.securityRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client DefaultSecurityRulesClient) ListComplete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DefaultSecurityRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkSecurityGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/enums.go deleted file mode 100644 index 0c115159d..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/enums.go +++ /dev/null @@ -1,1719 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Access enumerates the values for access. -type Access string - -const ( - // Allow ... - Allow Access = "Allow" - // Deny ... - Deny Access = "Deny" -) - -// PossibleAccessValues returns an array of possible values for the Access const type. -func PossibleAccessValues() []Access { - return []Access{Allow, Deny} -} - -// ApplicationGatewayBackendHealthServerHealth enumerates the values for application gateway backend health -// server health. -type ApplicationGatewayBackendHealthServerHealth string - -const ( - // Down ... - Down ApplicationGatewayBackendHealthServerHealth = "Down" - // Draining ... - Draining ApplicationGatewayBackendHealthServerHealth = "Draining" - // Partial ... - Partial ApplicationGatewayBackendHealthServerHealth = "Partial" - // Unknown ... - Unknown ApplicationGatewayBackendHealthServerHealth = "Unknown" - // Up ... - Up ApplicationGatewayBackendHealthServerHealth = "Up" -) - -// PossibleApplicationGatewayBackendHealthServerHealthValues returns an array of possible values for the ApplicationGatewayBackendHealthServerHealth const type. -func PossibleApplicationGatewayBackendHealthServerHealthValues() []ApplicationGatewayBackendHealthServerHealth { - return []ApplicationGatewayBackendHealthServerHealth{Down, Draining, Partial, Unknown, Up} -} - -// ApplicationGatewayCookieBasedAffinity enumerates the values for application gateway cookie based affinity. -type ApplicationGatewayCookieBasedAffinity string - -const ( - // Disabled ... - Disabled ApplicationGatewayCookieBasedAffinity = "Disabled" - // Enabled ... - Enabled ApplicationGatewayCookieBasedAffinity = "Enabled" -) - -// PossibleApplicationGatewayCookieBasedAffinityValues returns an array of possible values for the ApplicationGatewayCookieBasedAffinity const type. -func PossibleApplicationGatewayCookieBasedAffinityValues() []ApplicationGatewayCookieBasedAffinity { - return []ApplicationGatewayCookieBasedAffinity{Disabled, Enabled} -} - -// ApplicationGatewayCustomErrorStatusCode enumerates the values for application gateway custom error status -// code. -type ApplicationGatewayCustomErrorStatusCode string - -const ( - // HTTPStatus403 ... - HTTPStatus403 ApplicationGatewayCustomErrorStatusCode = "HttpStatus403" - // HTTPStatus502 ... - HTTPStatus502 ApplicationGatewayCustomErrorStatusCode = "HttpStatus502" -) - -// PossibleApplicationGatewayCustomErrorStatusCodeValues returns an array of possible values for the ApplicationGatewayCustomErrorStatusCode const type. -func PossibleApplicationGatewayCustomErrorStatusCodeValues() []ApplicationGatewayCustomErrorStatusCode { - return []ApplicationGatewayCustomErrorStatusCode{HTTPStatus403, HTTPStatus502} -} - -// ApplicationGatewayFirewallMode enumerates the values for application gateway firewall mode. -type ApplicationGatewayFirewallMode string - -const ( - // Detection ... - Detection ApplicationGatewayFirewallMode = "Detection" - // Prevention ... - Prevention ApplicationGatewayFirewallMode = "Prevention" -) - -// PossibleApplicationGatewayFirewallModeValues returns an array of possible values for the ApplicationGatewayFirewallMode const type. -func PossibleApplicationGatewayFirewallModeValues() []ApplicationGatewayFirewallMode { - return []ApplicationGatewayFirewallMode{Detection, Prevention} -} - -// ApplicationGatewayOperationalState enumerates the values for application gateway operational state. -type ApplicationGatewayOperationalState string - -const ( - // Running ... - Running ApplicationGatewayOperationalState = "Running" - // Starting ... - Starting ApplicationGatewayOperationalState = "Starting" - // Stopped ... - Stopped ApplicationGatewayOperationalState = "Stopped" - // Stopping ... - Stopping ApplicationGatewayOperationalState = "Stopping" -) - -// PossibleApplicationGatewayOperationalStateValues returns an array of possible values for the ApplicationGatewayOperationalState const type. -func PossibleApplicationGatewayOperationalStateValues() []ApplicationGatewayOperationalState { - return []ApplicationGatewayOperationalState{Running, Starting, Stopped, Stopping} -} - -// ApplicationGatewayProtocol enumerates the values for application gateway protocol. -type ApplicationGatewayProtocol string - -const ( - // HTTP ... - HTTP ApplicationGatewayProtocol = "Http" - // HTTPS ... - HTTPS ApplicationGatewayProtocol = "Https" -) - -// PossibleApplicationGatewayProtocolValues returns an array of possible values for the ApplicationGatewayProtocol const type. -func PossibleApplicationGatewayProtocolValues() []ApplicationGatewayProtocol { - return []ApplicationGatewayProtocol{HTTP, HTTPS} -} - -// ApplicationGatewayRedirectType enumerates the values for application gateway redirect type. -type ApplicationGatewayRedirectType string - -const ( - // Found ... - Found ApplicationGatewayRedirectType = "Found" - // Permanent ... - Permanent ApplicationGatewayRedirectType = "Permanent" - // SeeOther ... - SeeOther ApplicationGatewayRedirectType = "SeeOther" - // Temporary ... - Temporary ApplicationGatewayRedirectType = "Temporary" -) - -// PossibleApplicationGatewayRedirectTypeValues returns an array of possible values for the ApplicationGatewayRedirectType const type. -func PossibleApplicationGatewayRedirectTypeValues() []ApplicationGatewayRedirectType { - return []ApplicationGatewayRedirectType{Found, Permanent, SeeOther, Temporary} -} - -// ApplicationGatewayRequestRoutingRuleType enumerates the values for application gateway request routing rule -// type. -type ApplicationGatewayRequestRoutingRuleType string - -const ( - // Basic ... - Basic ApplicationGatewayRequestRoutingRuleType = "Basic" - // PathBasedRouting ... - PathBasedRouting ApplicationGatewayRequestRoutingRuleType = "PathBasedRouting" -) - -// PossibleApplicationGatewayRequestRoutingRuleTypeValues returns an array of possible values for the ApplicationGatewayRequestRoutingRuleType const type. -func PossibleApplicationGatewayRequestRoutingRuleTypeValues() []ApplicationGatewayRequestRoutingRuleType { - return []ApplicationGatewayRequestRoutingRuleType{Basic, PathBasedRouting} -} - -// ApplicationGatewaySkuName enumerates the values for application gateway sku name. -type ApplicationGatewaySkuName string - -const ( - // StandardLarge ... - StandardLarge ApplicationGatewaySkuName = "Standard_Large" - // StandardMedium ... - StandardMedium ApplicationGatewaySkuName = "Standard_Medium" - // StandardSmall ... - StandardSmall ApplicationGatewaySkuName = "Standard_Small" - // StandardV2 ... - StandardV2 ApplicationGatewaySkuName = "Standard_v2" - // WAFLarge ... - WAFLarge ApplicationGatewaySkuName = "WAF_Large" - // WAFMedium ... - WAFMedium ApplicationGatewaySkuName = "WAF_Medium" - // WAFV2 ... - WAFV2 ApplicationGatewaySkuName = "WAF_v2" -) - -// PossibleApplicationGatewaySkuNameValues returns an array of possible values for the ApplicationGatewaySkuName const type. -func PossibleApplicationGatewaySkuNameValues() []ApplicationGatewaySkuName { - return []ApplicationGatewaySkuName{StandardLarge, StandardMedium, StandardSmall, StandardV2, WAFLarge, WAFMedium, WAFV2} -} - -// ApplicationGatewaySslCipherSuite enumerates the values for application gateway ssl cipher suite. -type ApplicationGatewaySslCipherSuite string - -const ( - // TLSDHEDSSWITH3DESEDECBCSHA ... - TLSDHEDSSWITH3DESEDECBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" - // TLSDHEDSSWITHAES128CBCSHA ... - TLSDHEDSSWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" - // TLSDHEDSSWITHAES128CBCSHA256 ... - TLSDHEDSSWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" - // TLSDHEDSSWITHAES256CBCSHA ... - TLSDHEDSSWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" - // TLSDHEDSSWITHAES256CBCSHA256 ... - TLSDHEDSSWITHAES256CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" - // TLSDHERSAWITHAES128CBCSHA ... - TLSDHERSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" - // TLSDHERSAWITHAES128GCMSHA256 ... - TLSDHERSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" - // TLSDHERSAWITHAES256CBCSHA ... - TLSDHERSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" - // TLSDHERSAWITHAES256GCMSHA384 ... - TLSDHERSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" - // TLSECDHEECDSAWITHAES128CBCSHA ... - TLSECDHEECDSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" - // TLSECDHEECDSAWITHAES128CBCSHA256 ... - TLSECDHEECDSAWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" - // TLSECDHEECDSAWITHAES128GCMSHA256 ... - TLSECDHEECDSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" - // TLSECDHEECDSAWITHAES256CBCSHA ... - TLSECDHEECDSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" - // TLSECDHEECDSAWITHAES256CBCSHA384 ... - TLSECDHEECDSAWITHAES256CBCSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" - // TLSECDHEECDSAWITHAES256GCMSHA384 ... - TLSECDHEECDSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" - // TLSECDHERSAWITHAES128CBCSHA ... - TLSECDHERSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" - // TLSECDHERSAWITHAES128CBCSHA256 ... - TLSECDHERSAWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" - // TLSECDHERSAWITHAES128GCMSHA256 ... - TLSECDHERSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" - // TLSECDHERSAWITHAES256CBCSHA ... - TLSECDHERSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" - // TLSECDHERSAWITHAES256CBCSHA384 ... - TLSECDHERSAWITHAES256CBCSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" - // TLSECDHERSAWITHAES256GCMSHA384 ... - TLSECDHERSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" - // TLSRSAWITH3DESEDECBCSHA ... - TLSRSAWITH3DESEDECBCSHA ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_3DES_EDE_CBC_SHA" - // TLSRSAWITHAES128CBCSHA ... - TLSRSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_128_CBC_SHA" - // TLSRSAWITHAES128CBCSHA256 ... - TLSRSAWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_128_CBC_SHA256" - // TLSRSAWITHAES128GCMSHA256 ... - TLSRSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_128_GCM_SHA256" - // TLSRSAWITHAES256CBCSHA ... - TLSRSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_256_CBC_SHA" - // TLSRSAWITHAES256CBCSHA256 ... - TLSRSAWITHAES256CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_256_CBC_SHA256" - // TLSRSAWITHAES256GCMSHA384 ... - TLSRSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_256_GCM_SHA384" -) - -// PossibleApplicationGatewaySslCipherSuiteValues returns an array of possible values for the ApplicationGatewaySslCipherSuite const type. -func PossibleApplicationGatewaySslCipherSuiteValues() []ApplicationGatewaySslCipherSuite { - return []ApplicationGatewaySslCipherSuite{TLSDHEDSSWITH3DESEDECBCSHA, TLSDHEDSSWITHAES128CBCSHA, TLSDHEDSSWITHAES128CBCSHA256, TLSDHEDSSWITHAES256CBCSHA, TLSDHEDSSWITHAES256CBCSHA256, TLSDHERSAWITHAES128CBCSHA, TLSDHERSAWITHAES128GCMSHA256, TLSDHERSAWITHAES256CBCSHA, TLSDHERSAWITHAES256GCMSHA384, TLSECDHEECDSAWITHAES128CBCSHA, TLSECDHEECDSAWITHAES128CBCSHA256, TLSECDHEECDSAWITHAES128GCMSHA256, TLSECDHEECDSAWITHAES256CBCSHA, TLSECDHEECDSAWITHAES256CBCSHA384, TLSECDHEECDSAWITHAES256GCMSHA384, TLSECDHERSAWITHAES128CBCSHA, TLSECDHERSAWITHAES128CBCSHA256, TLSECDHERSAWITHAES128GCMSHA256, TLSECDHERSAWITHAES256CBCSHA, TLSECDHERSAWITHAES256CBCSHA384, TLSECDHERSAWITHAES256GCMSHA384, TLSRSAWITH3DESEDECBCSHA, TLSRSAWITHAES128CBCSHA, TLSRSAWITHAES128CBCSHA256, TLSRSAWITHAES128GCMSHA256, TLSRSAWITHAES256CBCSHA, TLSRSAWITHAES256CBCSHA256, TLSRSAWITHAES256GCMSHA384} -} - -// ApplicationGatewaySslPolicyName enumerates the values for application gateway ssl policy name. -type ApplicationGatewaySslPolicyName string - -const ( - // AppGwSslPolicy20150501 ... - AppGwSslPolicy20150501 ApplicationGatewaySslPolicyName = "AppGwSslPolicy20150501" - // AppGwSslPolicy20170401 ... - AppGwSslPolicy20170401 ApplicationGatewaySslPolicyName = "AppGwSslPolicy20170401" - // AppGwSslPolicy20170401S ... - AppGwSslPolicy20170401S ApplicationGatewaySslPolicyName = "AppGwSslPolicy20170401S" -) - -// PossibleApplicationGatewaySslPolicyNameValues returns an array of possible values for the ApplicationGatewaySslPolicyName const type. -func PossibleApplicationGatewaySslPolicyNameValues() []ApplicationGatewaySslPolicyName { - return []ApplicationGatewaySslPolicyName{AppGwSslPolicy20150501, AppGwSslPolicy20170401, AppGwSslPolicy20170401S} -} - -// ApplicationGatewaySslPolicyType enumerates the values for application gateway ssl policy type. -type ApplicationGatewaySslPolicyType string - -const ( - // Custom ... - Custom ApplicationGatewaySslPolicyType = "Custom" - // Predefined ... - Predefined ApplicationGatewaySslPolicyType = "Predefined" -) - -// PossibleApplicationGatewaySslPolicyTypeValues returns an array of possible values for the ApplicationGatewaySslPolicyType const type. -func PossibleApplicationGatewaySslPolicyTypeValues() []ApplicationGatewaySslPolicyType { - return []ApplicationGatewaySslPolicyType{Custom, Predefined} -} - -// ApplicationGatewaySslProtocol enumerates the values for application gateway ssl protocol. -type ApplicationGatewaySslProtocol string - -const ( - // TLSv10 ... - TLSv10 ApplicationGatewaySslProtocol = "TLSv1_0" - // TLSv11 ... - TLSv11 ApplicationGatewaySslProtocol = "TLSv1_1" - // TLSv12 ... - TLSv12 ApplicationGatewaySslProtocol = "TLSv1_2" -) - -// PossibleApplicationGatewaySslProtocolValues returns an array of possible values for the ApplicationGatewaySslProtocol const type. -func PossibleApplicationGatewaySslProtocolValues() []ApplicationGatewaySslProtocol { - return []ApplicationGatewaySslProtocol{TLSv10, TLSv11, TLSv12} -} - -// ApplicationGatewayTier enumerates the values for application gateway tier. -type ApplicationGatewayTier string - -const ( - // ApplicationGatewayTierStandard ... - ApplicationGatewayTierStandard ApplicationGatewayTier = "Standard" - // ApplicationGatewayTierStandardV2 ... - ApplicationGatewayTierStandardV2 ApplicationGatewayTier = "Standard_v2" - // ApplicationGatewayTierWAF ... - ApplicationGatewayTierWAF ApplicationGatewayTier = "WAF" - // ApplicationGatewayTierWAFV2 ... - ApplicationGatewayTierWAFV2 ApplicationGatewayTier = "WAF_v2" -) - -// PossibleApplicationGatewayTierValues returns an array of possible values for the ApplicationGatewayTier const type. -func PossibleApplicationGatewayTierValues() []ApplicationGatewayTier { - return []ApplicationGatewayTier{ApplicationGatewayTierStandard, ApplicationGatewayTierStandardV2, ApplicationGatewayTierWAF, ApplicationGatewayTierWAFV2} -} - -// AssociationType enumerates the values for association type. -type AssociationType string - -const ( - // Associated ... - Associated AssociationType = "Associated" - // Contains ... - Contains AssociationType = "Contains" -) - -// PossibleAssociationTypeValues returns an array of possible values for the AssociationType const type. -func PossibleAssociationTypeValues() []AssociationType { - return []AssociationType{Associated, Contains} -} - -// AuthenticationMethod enumerates the values for authentication method. -type AuthenticationMethod string - -const ( - // EAPMSCHAPv2 ... - EAPMSCHAPv2 AuthenticationMethod = "EAPMSCHAPv2" - // EAPTLS ... - EAPTLS AuthenticationMethod = "EAPTLS" -) - -// PossibleAuthenticationMethodValues returns an array of possible values for the AuthenticationMethod const type. -func PossibleAuthenticationMethodValues() []AuthenticationMethod { - return []AuthenticationMethod{EAPMSCHAPv2, EAPTLS} -} - -// AuthorizationUseStatus enumerates the values for authorization use status. -type AuthorizationUseStatus string - -const ( - // Available ... - Available AuthorizationUseStatus = "Available" - // InUse ... - InUse AuthorizationUseStatus = "InUse" -) - -// PossibleAuthorizationUseStatusValues returns an array of possible values for the AuthorizationUseStatus const type. -func PossibleAuthorizationUseStatusValues() []AuthorizationUseStatus { - return []AuthorizationUseStatus{Available, InUse} -} - -// AzureFirewallApplicationRuleProtocolType enumerates the values for azure firewall application rule protocol -// type. -type AzureFirewallApplicationRuleProtocolType string - -const ( - // AzureFirewallApplicationRuleProtocolTypeHTTP ... - AzureFirewallApplicationRuleProtocolTypeHTTP AzureFirewallApplicationRuleProtocolType = "Http" - // AzureFirewallApplicationRuleProtocolTypeHTTPS ... - AzureFirewallApplicationRuleProtocolTypeHTTPS AzureFirewallApplicationRuleProtocolType = "Https" -) - -// PossibleAzureFirewallApplicationRuleProtocolTypeValues returns an array of possible values for the AzureFirewallApplicationRuleProtocolType const type. -func PossibleAzureFirewallApplicationRuleProtocolTypeValues() []AzureFirewallApplicationRuleProtocolType { - return []AzureFirewallApplicationRuleProtocolType{AzureFirewallApplicationRuleProtocolTypeHTTP, AzureFirewallApplicationRuleProtocolTypeHTTPS} -} - -// AzureFirewallNatRCActionType enumerates the values for azure firewall nat rc action type. -type AzureFirewallNatRCActionType string - -const ( - // Dnat ... - Dnat AzureFirewallNatRCActionType = "Dnat" - // Snat ... - Snat AzureFirewallNatRCActionType = "Snat" -) - -// PossibleAzureFirewallNatRCActionTypeValues returns an array of possible values for the AzureFirewallNatRCActionType const type. -func PossibleAzureFirewallNatRCActionTypeValues() []AzureFirewallNatRCActionType { - return []AzureFirewallNatRCActionType{Dnat, Snat} -} - -// AzureFirewallNetworkRuleProtocol enumerates the values for azure firewall network rule protocol. -type AzureFirewallNetworkRuleProtocol string - -const ( - // Any ... - Any AzureFirewallNetworkRuleProtocol = "Any" - // ICMP ... - ICMP AzureFirewallNetworkRuleProtocol = "ICMP" - // TCP ... - TCP AzureFirewallNetworkRuleProtocol = "TCP" - // UDP ... - UDP AzureFirewallNetworkRuleProtocol = "UDP" -) - -// PossibleAzureFirewallNetworkRuleProtocolValues returns an array of possible values for the AzureFirewallNetworkRuleProtocol const type. -func PossibleAzureFirewallNetworkRuleProtocolValues() []AzureFirewallNetworkRuleProtocol { - return []AzureFirewallNetworkRuleProtocol{Any, ICMP, TCP, UDP} -} - -// AzureFirewallRCActionType enumerates the values for azure firewall rc action type. -type AzureFirewallRCActionType string - -const ( - // AzureFirewallRCActionTypeAllow ... - AzureFirewallRCActionTypeAllow AzureFirewallRCActionType = "Allow" - // AzureFirewallRCActionTypeDeny ... - AzureFirewallRCActionTypeDeny AzureFirewallRCActionType = "Deny" -) - -// PossibleAzureFirewallRCActionTypeValues returns an array of possible values for the AzureFirewallRCActionType const type. -func PossibleAzureFirewallRCActionTypeValues() []AzureFirewallRCActionType { - return []AzureFirewallRCActionType{AzureFirewallRCActionTypeAllow, AzureFirewallRCActionTypeDeny} -} - -// BgpPeerState enumerates the values for bgp peer state. -type BgpPeerState string - -const ( - // BgpPeerStateConnected ... - BgpPeerStateConnected BgpPeerState = "Connected" - // BgpPeerStateConnecting ... - BgpPeerStateConnecting BgpPeerState = "Connecting" - // BgpPeerStateIdle ... - BgpPeerStateIdle BgpPeerState = "Idle" - // BgpPeerStateStopped ... - BgpPeerStateStopped BgpPeerState = "Stopped" - // BgpPeerStateUnknown ... - BgpPeerStateUnknown BgpPeerState = "Unknown" -) - -// PossibleBgpPeerStateValues returns an array of possible values for the BgpPeerState const type. -func PossibleBgpPeerStateValues() []BgpPeerState { - return []BgpPeerState{BgpPeerStateConnected, BgpPeerStateConnecting, BgpPeerStateIdle, BgpPeerStateStopped, BgpPeerStateUnknown} -} - -// CircuitConnectionStatus enumerates the values for circuit connection status. -type CircuitConnectionStatus string - -const ( - // Connected ... - Connected CircuitConnectionStatus = "Connected" - // Connecting ... - Connecting CircuitConnectionStatus = "Connecting" - // Disconnected ... - Disconnected CircuitConnectionStatus = "Disconnected" -) - -// PossibleCircuitConnectionStatusValues returns an array of possible values for the CircuitConnectionStatus const type. -func PossibleCircuitConnectionStatusValues() []CircuitConnectionStatus { - return []CircuitConnectionStatus{Connected, Connecting, Disconnected} -} - -// ConnectionMonitorSourceStatus enumerates the values for connection monitor source status. -type ConnectionMonitorSourceStatus string - -const ( - // Active ... - Active ConnectionMonitorSourceStatus = "Active" - // Inactive ... - Inactive ConnectionMonitorSourceStatus = "Inactive" - // Uknown ... - Uknown ConnectionMonitorSourceStatus = "Uknown" -) - -// PossibleConnectionMonitorSourceStatusValues returns an array of possible values for the ConnectionMonitorSourceStatus const type. -func PossibleConnectionMonitorSourceStatusValues() []ConnectionMonitorSourceStatus { - return []ConnectionMonitorSourceStatus{Active, Inactive, Uknown} -} - -// ConnectionState enumerates the values for connection state. -type ConnectionState string - -const ( - // ConnectionStateReachable ... - ConnectionStateReachable ConnectionState = "Reachable" - // ConnectionStateUnknown ... - ConnectionStateUnknown ConnectionState = "Unknown" - // ConnectionStateUnreachable ... - ConnectionStateUnreachable ConnectionState = "Unreachable" -) - -// PossibleConnectionStateValues returns an array of possible values for the ConnectionState const type. -func PossibleConnectionStateValues() []ConnectionState { - return []ConnectionState{ConnectionStateReachable, ConnectionStateUnknown, ConnectionStateUnreachable} -} - -// ConnectionStatus enumerates the values for connection status. -type ConnectionStatus string - -const ( - // ConnectionStatusConnected ... - ConnectionStatusConnected ConnectionStatus = "Connected" - // ConnectionStatusDegraded ... - ConnectionStatusDegraded ConnectionStatus = "Degraded" - // ConnectionStatusDisconnected ... - ConnectionStatusDisconnected ConnectionStatus = "Disconnected" - // ConnectionStatusUnknown ... - ConnectionStatusUnknown ConnectionStatus = "Unknown" -) - -// PossibleConnectionStatusValues returns an array of possible values for the ConnectionStatus const type. -func PossibleConnectionStatusValues() []ConnectionStatus { - return []ConnectionStatus{ConnectionStatusConnected, ConnectionStatusDegraded, ConnectionStatusDisconnected, ConnectionStatusUnknown} -} - -// DhGroup enumerates the values for dh group. -type DhGroup string - -const ( - // DHGroup1 ... - DHGroup1 DhGroup = "DHGroup1" - // DHGroup14 ... - DHGroup14 DhGroup = "DHGroup14" - // DHGroup2 ... - DHGroup2 DhGroup = "DHGroup2" - // DHGroup2048 ... - DHGroup2048 DhGroup = "DHGroup2048" - // DHGroup24 ... - DHGroup24 DhGroup = "DHGroup24" - // ECP256 ... - ECP256 DhGroup = "ECP256" - // ECP384 ... - ECP384 DhGroup = "ECP384" - // None ... - None DhGroup = "None" -) - -// PossibleDhGroupValues returns an array of possible values for the DhGroup const type. -func PossibleDhGroupValues() []DhGroup { - return []DhGroup{DHGroup1, DHGroup14, DHGroup2, DHGroup2048, DHGroup24, ECP256, ECP384, None} -} - -// Direction enumerates the values for direction. -type Direction string - -const ( - // Inbound ... - Inbound Direction = "Inbound" - // Outbound ... - Outbound Direction = "Outbound" -) - -// PossibleDirectionValues returns an array of possible values for the Direction const type. -func PossibleDirectionValues() []Direction { - return []Direction{Inbound, Outbound} -} - -// EffectiveRouteSource enumerates the values for effective route source. -type EffectiveRouteSource string - -const ( - // EffectiveRouteSourceDefault ... - EffectiveRouteSourceDefault EffectiveRouteSource = "Default" - // EffectiveRouteSourceUnknown ... - EffectiveRouteSourceUnknown EffectiveRouteSource = "Unknown" - // EffectiveRouteSourceUser ... - EffectiveRouteSourceUser EffectiveRouteSource = "User" - // EffectiveRouteSourceVirtualNetworkGateway ... - EffectiveRouteSourceVirtualNetworkGateway EffectiveRouteSource = "VirtualNetworkGateway" -) - -// PossibleEffectiveRouteSourceValues returns an array of possible values for the EffectiveRouteSource const type. -func PossibleEffectiveRouteSourceValues() []EffectiveRouteSource { - return []EffectiveRouteSource{EffectiveRouteSourceDefault, EffectiveRouteSourceUnknown, EffectiveRouteSourceUser, EffectiveRouteSourceVirtualNetworkGateway} -} - -// EffectiveRouteState enumerates the values for effective route state. -type EffectiveRouteState string - -const ( - // EffectiveRouteStateActive ... - EffectiveRouteStateActive EffectiveRouteState = "Active" - // EffectiveRouteStateInvalid ... - EffectiveRouteStateInvalid EffectiveRouteState = "Invalid" -) - -// PossibleEffectiveRouteStateValues returns an array of possible values for the EffectiveRouteState const type. -func PossibleEffectiveRouteStateValues() []EffectiveRouteState { - return []EffectiveRouteState{EffectiveRouteStateActive, EffectiveRouteStateInvalid} -} - -// EffectiveSecurityRuleProtocol enumerates the values for effective security rule protocol. -type EffectiveSecurityRuleProtocol string - -const ( - // EffectiveSecurityRuleProtocolAll ... - EffectiveSecurityRuleProtocolAll EffectiveSecurityRuleProtocol = "All" - // EffectiveSecurityRuleProtocolTCP ... - EffectiveSecurityRuleProtocolTCP EffectiveSecurityRuleProtocol = "Tcp" - // EffectiveSecurityRuleProtocolUDP ... - EffectiveSecurityRuleProtocolUDP EffectiveSecurityRuleProtocol = "Udp" -) - -// PossibleEffectiveSecurityRuleProtocolValues returns an array of possible values for the EffectiveSecurityRuleProtocol const type. -func PossibleEffectiveSecurityRuleProtocolValues() []EffectiveSecurityRuleProtocol { - return []EffectiveSecurityRuleProtocol{EffectiveSecurityRuleProtocolAll, EffectiveSecurityRuleProtocolTCP, EffectiveSecurityRuleProtocolUDP} -} - -// EvaluationState enumerates the values for evaluation state. -type EvaluationState string - -const ( - // Completed ... - Completed EvaluationState = "Completed" - // InProgress ... - InProgress EvaluationState = "InProgress" - // NotStarted ... - NotStarted EvaluationState = "NotStarted" -) - -// PossibleEvaluationStateValues returns an array of possible values for the EvaluationState const type. -func PossibleEvaluationStateValues() []EvaluationState { - return []EvaluationState{Completed, InProgress, NotStarted} -} - -// ExpressRouteCircuitPeeringAdvertisedPublicPrefixState enumerates the values for express route circuit -// peering advertised public prefix state. -type ExpressRouteCircuitPeeringAdvertisedPublicPrefixState string - -const ( - // Configured ... - Configured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configured" - // Configuring ... - Configuring ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configuring" - // NotConfigured ... - NotConfigured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "NotConfigured" - // ValidationNeeded ... - ValidationNeeded ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "ValidationNeeded" -) - -// PossibleExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValues returns an array of possible values for the ExpressRouteCircuitPeeringAdvertisedPublicPrefixState const type. -func PossibleExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValues() []ExpressRouteCircuitPeeringAdvertisedPublicPrefixState { - return []ExpressRouteCircuitPeeringAdvertisedPublicPrefixState{Configured, Configuring, NotConfigured, ValidationNeeded} -} - -// ExpressRouteCircuitPeeringState enumerates the values for express route circuit peering state. -type ExpressRouteCircuitPeeringState string - -const ( - // ExpressRouteCircuitPeeringStateDisabled ... - ExpressRouteCircuitPeeringStateDisabled ExpressRouteCircuitPeeringState = "Disabled" - // ExpressRouteCircuitPeeringStateEnabled ... - ExpressRouteCircuitPeeringStateEnabled ExpressRouteCircuitPeeringState = "Enabled" -) - -// PossibleExpressRouteCircuitPeeringStateValues returns an array of possible values for the ExpressRouteCircuitPeeringState const type. -func PossibleExpressRouteCircuitPeeringStateValues() []ExpressRouteCircuitPeeringState { - return []ExpressRouteCircuitPeeringState{ExpressRouteCircuitPeeringStateDisabled, ExpressRouteCircuitPeeringStateEnabled} -} - -// ExpressRouteCircuitSkuFamily enumerates the values for express route circuit sku family. -type ExpressRouteCircuitSkuFamily string - -const ( - // MeteredData ... - MeteredData ExpressRouteCircuitSkuFamily = "MeteredData" - // UnlimitedData ... - UnlimitedData ExpressRouteCircuitSkuFamily = "UnlimitedData" -) - -// PossibleExpressRouteCircuitSkuFamilyValues returns an array of possible values for the ExpressRouteCircuitSkuFamily const type. -func PossibleExpressRouteCircuitSkuFamilyValues() []ExpressRouteCircuitSkuFamily { - return []ExpressRouteCircuitSkuFamily{MeteredData, UnlimitedData} -} - -// ExpressRouteCircuitSkuTier enumerates the values for express route circuit sku tier. -type ExpressRouteCircuitSkuTier string - -const ( - // ExpressRouteCircuitSkuTierBasic ... - ExpressRouteCircuitSkuTierBasic ExpressRouteCircuitSkuTier = "Basic" - // ExpressRouteCircuitSkuTierPremium ... - ExpressRouteCircuitSkuTierPremium ExpressRouteCircuitSkuTier = "Premium" - // ExpressRouteCircuitSkuTierStandard ... - ExpressRouteCircuitSkuTierStandard ExpressRouteCircuitSkuTier = "Standard" -) - -// PossibleExpressRouteCircuitSkuTierValues returns an array of possible values for the ExpressRouteCircuitSkuTier const type. -func PossibleExpressRouteCircuitSkuTierValues() []ExpressRouteCircuitSkuTier { - return []ExpressRouteCircuitSkuTier{ExpressRouteCircuitSkuTierBasic, ExpressRouteCircuitSkuTierPremium, ExpressRouteCircuitSkuTierStandard} -} - -// ExpressRouteLinkAdminState enumerates the values for express route link admin state. -type ExpressRouteLinkAdminState string - -const ( - // ExpressRouteLinkAdminStateDisabled ... - ExpressRouteLinkAdminStateDisabled ExpressRouteLinkAdminState = "Disabled" - // ExpressRouteLinkAdminStateEnabled ... - ExpressRouteLinkAdminStateEnabled ExpressRouteLinkAdminState = "Enabled" -) - -// PossibleExpressRouteLinkAdminStateValues returns an array of possible values for the ExpressRouteLinkAdminState const type. -func PossibleExpressRouteLinkAdminStateValues() []ExpressRouteLinkAdminState { - return []ExpressRouteLinkAdminState{ExpressRouteLinkAdminStateDisabled, ExpressRouteLinkAdminStateEnabled} -} - -// ExpressRouteLinkConnectorType enumerates the values for express route link connector type. -type ExpressRouteLinkConnectorType string - -const ( - // LC ... - LC ExpressRouteLinkConnectorType = "LC" - // SC ... - SC ExpressRouteLinkConnectorType = "SC" -) - -// PossibleExpressRouteLinkConnectorTypeValues returns an array of possible values for the ExpressRouteLinkConnectorType const type. -func PossibleExpressRouteLinkConnectorTypeValues() []ExpressRouteLinkConnectorType { - return []ExpressRouteLinkConnectorType{LC, SC} -} - -// ExpressRoutePeeringState enumerates the values for express route peering state. -type ExpressRoutePeeringState string - -const ( - // ExpressRoutePeeringStateDisabled ... - ExpressRoutePeeringStateDisabled ExpressRoutePeeringState = "Disabled" - // ExpressRoutePeeringStateEnabled ... - ExpressRoutePeeringStateEnabled ExpressRoutePeeringState = "Enabled" -) - -// PossibleExpressRoutePeeringStateValues returns an array of possible values for the ExpressRoutePeeringState const type. -func PossibleExpressRoutePeeringStateValues() []ExpressRoutePeeringState { - return []ExpressRoutePeeringState{ExpressRoutePeeringStateDisabled, ExpressRoutePeeringStateEnabled} -} - -// ExpressRoutePeeringType enumerates the values for express route peering type. -type ExpressRoutePeeringType string - -const ( - // AzurePrivatePeering ... - AzurePrivatePeering ExpressRoutePeeringType = "AzurePrivatePeering" - // AzurePublicPeering ... - AzurePublicPeering ExpressRoutePeeringType = "AzurePublicPeering" - // MicrosoftPeering ... - MicrosoftPeering ExpressRoutePeeringType = "MicrosoftPeering" -) - -// PossibleExpressRoutePeeringTypeValues returns an array of possible values for the ExpressRoutePeeringType const type. -func PossibleExpressRoutePeeringTypeValues() []ExpressRoutePeeringType { - return []ExpressRoutePeeringType{AzurePrivatePeering, AzurePublicPeering, MicrosoftPeering} -} - -// ExpressRoutePortsEncapsulation enumerates the values for express route ports encapsulation. -type ExpressRoutePortsEncapsulation string - -const ( - // Dot1Q ... - Dot1Q ExpressRoutePortsEncapsulation = "Dot1Q" - // QinQ ... - QinQ ExpressRoutePortsEncapsulation = "QinQ" -) - -// PossibleExpressRoutePortsEncapsulationValues returns an array of possible values for the ExpressRoutePortsEncapsulation const type. -func PossibleExpressRoutePortsEncapsulationValues() []ExpressRoutePortsEncapsulation { - return []ExpressRoutePortsEncapsulation{Dot1Q, QinQ} -} - -// FlowLogFormatType enumerates the values for flow log format type. -type FlowLogFormatType string - -const ( - // JSON ... - JSON FlowLogFormatType = "JSON" -) - -// PossibleFlowLogFormatTypeValues returns an array of possible values for the FlowLogFormatType const type. -func PossibleFlowLogFormatTypeValues() []FlowLogFormatType { - return []FlowLogFormatType{JSON} -} - -// HTTPMethod enumerates the values for http method. -type HTTPMethod string - -const ( - // Get ... - Get HTTPMethod = "Get" -) - -// PossibleHTTPMethodValues returns an array of possible values for the HTTPMethod const type. -func PossibleHTTPMethodValues() []HTTPMethod { - return []HTTPMethod{Get} -} - -// HubVirtualNetworkConnectionStatus enumerates the values for hub virtual network connection status. -type HubVirtualNetworkConnectionStatus string - -const ( - // HubVirtualNetworkConnectionStatusConnected ... - HubVirtualNetworkConnectionStatusConnected HubVirtualNetworkConnectionStatus = "Connected" - // HubVirtualNetworkConnectionStatusConnecting ... - HubVirtualNetworkConnectionStatusConnecting HubVirtualNetworkConnectionStatus = "Connecting" - // HubVirtualNetworkConnectionStatusNotConnected ... - HubVirtualNetworkConnectionStatusNotConnected HubVirtualNetworkConnectionStatus = "NotConnected" - // HubVirtualNetworkConnectionStatusUnknown ... - HubVirtualNetworkConnectionStatusUnknown HubVirtualNetworkConnectionStatus = "Unknown" -) - -// PossibleHubVirtualNetworkConnectionStatusValues returns an array of possible values for the HubVirtualNetworkConnectionStatus const type. -func PossibleHubVirtualNetworkConnectionStatusValues() []HubVirtualNetworkConnectionStatus { - return []HubVirtualNetworkConnectionStatus{HubVirtualNetworkConnectionStatusConnected, HubVirtualNetworkConnectionStatusConnecting, HubVirtualNetworkConnectionStatusNotConnected, HubVirtualNetworkConnectionStatusUnknown} -} - -// IkeEncryption enumerates the values for ike encryption. -type IkeEncryption string - -const ( - // AES128 ... - AES128 IkeEncryption = "AES128" - // AES192 ... - AES192 IkeEncryption = "AES192" - // AES256 ... - AES256 IkeEncryption = "AES256" - // DES ... - DES IkeEncryption = "DES" - // DES3 ... - DES3 IkeEncryption = "DES3" - // GCMAES128 ... - GCMAES128 IkeEncryption = "GCMAES128" - // GCMAES256 ... - GCMAES256 IkeEncryption = "GCMAES256" -) - -// PossibleIkeEncryptionValues returns an array of possible values for the IkeEncryption const type. -func PossibleIkeEncryptionValues() []IkeEncryption { - return []IkeEncryption{AES128, AES192, AES256, DES, DES3, GCMAES128, GCMAES256} -} - -// IkeIntegrity enumerates the values for ike integrity. -type IkeIntegrity string - -const ( - // IkeIntegrityGCMAES128 ... - IkeIntegrityGCMAES128 IkeIntegrity = "GCMAES128" - // IkeIntegrityGCMAES256 ... - IkeIntegrityGCMAES256 IkeIntegrity = "GCMAES256" - // IkeIntegrityMD5 ... - IkeIntegrityMD5 IkeIntegrity = "MD5" - // IkeIntegritySHA1 ... - IkeIntegritySHA1 IkeIntegrity = "SHA1" - // IkeIntegritySHA256 ... - IkeIntegritySHA256 IkeIntegrity = "SHA256" - // IkeIntegritySHA384 ... - IkeIntegritySHA384 IkeIntegrity = "SHA384" -) - -// PossibleIkeIntegrityValues returns an array of possible values for the IkeIntegrity const type. -func PossibleIkeIntegrityValues() []IkeIntegrity { - return []IkeIntegrity{IkeIntegrityGCMAES128, IkeIntegrityGCMAES256, IkeIntegrityMD5, IkeIntegritySHA1, IkeIntegritySHA256, IkeIntegritySHA384} -} - -// IPAllocationMethod enumerates the values for ip allocation method. -type IPAllocationMethod string - -const ( - // Dynamic ... - Dynamic IPAllocationMethod = "Dynamic" - // Static ... - Static IPAllocationMethod = "Static" -) - -// PossibleIPAllocationMethodValues returns an array of possible values for the IPAllocationMethod const type. -func PossibleIPAllocationMethodValues() []IPAllocationMethod { - return []IPAllocationMethod{Dynamic, Static} -} - -// IPFlowProtocol enumerates the values for ip flow protocol. -type IPFlowProtocol string - -const ( - // IPFlowProtocolTCP ... - IPFlowProtocolTCP IPFlowProtocol = "TCP" - // IPFlowProtocolUDP ... - IPFlowProtocolUDP IPFlowProtocol = "UDP" -) - -// PossibleIPFlowProtocolValues returns an array of possible values for the IPFlowProtocol const type. -func PossibleIPFlowProtocolValues() []IPFlowProtocol { - return []IPFlowProtocol{IPFlowProtocolTCP, IPFlowProtocolUDP} -} - -// IpsecEncryption enumerates the values for ipsec encryption. -type IpsecEncryption string - -const ( - // IpsecEncryptionAES128 ... - IpsecEncryptionAES128 IpsecEncryption = "AES128" - // IpsecEncryptionAES192 ... - IpsecEncryptionAES192 IpsecEncryption = "AES192" - // IpsecEncryptionAES256 ... - IpsecEncryptionAES256 IpsecEncryption = "AES256" - // IpsecEncryptionDES ... - IpsecEncryptionDES IpsecEncryption = "DES" - // IpsecEncryptionDES3 ... - IpsecEncryptionDES3 IpsecEncryption = "DES3" - // IpsecEncryptionGCMAES128 ... - IpsecEncryptionGCMAES128 IpsecEncryption = "GCMAES128" - // IpsecEncryptionGCMAES192 ... - IpsecEncryptionGCMAES192 IpsecEncryption = "GCMAES192" - // IpsecEncryptionGCMAES256 ... - IpsecEncryptionGCMAES256 IpsecEncryption = "GCMAES256" - // IpsecEncryptionNone ... - IpsecEncryptionNone IpsecEncryption = "None" -) - -// PossibleIpsecEncryptionValues returns an array of possible values for the IpsecEncryption const type. -func PossibleIpsecEncryptionValues() []IpsecEncryption { - return []IpsecEncryption{IpsecEncryptionAES128, IpsecEncryptionAES192, IpsecEncryptionAES256, IpsecEncryptionDES, IpsecEncryptionDES3, IpsecEncryptionGCMAES128, IpsecEncryptionGCMAES192, IpsecEncryptionGCMAES256, IpsecEncryptionNone} -} - -// IpsecIntegrity enumerates the values for ipsec integrity. -type IpsecIntegrity string - -const ( - // IpsecIntegrityGCMAES128 ... - IpsecIntegrityGCMAES128 IpsecIntegrity = "GCMAES128" - // IpsecIntegrityGCMAES192 ... - IpsecIntegrityGCMAES192 IpsecIntegrity = "GCMAES192" - // IpsecIntegrityGCMAES256 ... - IpsecIntegrityGCMAES256 IpsecIntegrity = "GCMAES256" - // IpsecIntegrityMD5 ... - IpsecIntegrityMD5 IpsecIntegrity = "MD5" - // IpsecIntegritySHA1 ... - IpsecIntegritySHA1 IpsecIntegrity = "SHA1" - // IpsecIntegritySHA256 ... - IpsecIntegritySHA256 IpsecIntegrity = "SHA256" -) - -// PossibleIpsecIntegrityValues returns an array of possible values for the IpsecIntegrity const type. -func PossibleIpsecIntegrityValues() []IpsecIntegrity { - return []IpsecIntegrity{IpsecIntegrityGCMAES128, IpsecIntegrityGCMAES192, IpsecIntegrityGCMAES256, IpsecIntegrityMD5, IpsecIntegritySHA1, IpsecIntegritySHA256} -} - -// IPVersion enumerates the values for ip version. -type IPVersion string - -const ( - // IPv4 ... - IPv4 IPVersion = "IPv4" - // IPv6 ... - IPv6 IPVersion = "IPv6" -) - -// PossibleIPVersionValues returns an array of possible values for the IPVersion const type. -func PossibleIPVersionValues() []IPVersion { - return []IPVersion{IPv4, IPv6} -} - -// IssueType enumerates the values for issue type. -type IssueType string - -const ( - // IssueTypeAgentStopped ... - IssueTypeAgentStopped IssueType = "AgentStopped" - // IssueTypeDNSResolution ... - IssueTypeDNSResolution IssueType = "DnsResolution" - // IssueTypeGuestFirewall ... - IssueTypeGuestFirewall IssueType = "GuestFirewall" - // IssueTypeNetworkSecurityRule ... - IssueTypeNetworkSecurityRule IssueType = "NetworkSecurityRule" - // IssueTypePlatform ... - IssueTypePlatform IssueType = "Platform" - // IssueTypePortThrottled ... - IssueTypePortThrottled IssueType = "PortThrottled" - // IssueTypeSocketBind ... - IssueTypeSocketBind IssueType = "SocketBind" - // IssueTypeUnknown ... - IssueTypeUnknown IssueType = "Unknown" - // IssueTypeUserDefinedRoute ... - IssueTypeUserDefinedRoute IssueType = "UserDefinedRoute" -) - -// PossibleIssueTypeValues returns an array of possible values for the IssueType const type. -func PossibleIssueTypeValues() []IssueType { - return []IssueType{IssueTypeAgentStopped, IssueTypeDNSResolution, IssueTypeGuestFirewall, IssueTypeNetworkSecurityRule, IssueTypePlatform, IssueTypePortThrottled, IssueTypeSocketBind, IssueTypeUnknown, IssueTypeUserDefinedRoute} -} - -// LoadBalancerSkuName enumerates the values for load balancer sku name. -type LoadBalancerSkuName string - -const ( - // LoadBalancerSkuNameBasic ... - LoadBalancerSkuNameBasic LoadBalancerSkuName = "Basic" - // LoadBalancerSkuNameStandard ... - LoadBalancerSkuNameStandard LoadBalancerSkuName = "Standard" -) - -// PossibleLoadBalancerSkuNameValues returns an array of possible values for the LoadBalancerSkuName const type. -func PossibleLoadBalancerSkuNameValues() []LoadBalancerSkuName { - return []LoadBalancerSkuName{LoadBalancerSkuNameBasic, LoadBalancerSkuNameStandard} -} - -// LoadDistribution enumerates the values for load distribution. -type LoadDistribution string - -const ( - // Default ... - Default LoadDistribution = "Default" - // SourceIP ... - SourceIP LoadDistribution = "SourceIP" - // SourceIPProtocol ... - SourceIPProtocol LoadDistribution = "SourceIPProtocol" -) - -// PossibleLoadDistributionValues returns an array of possible values for the LoadDistribution const type. -func PossibleLoadDistributionValues() []LoadDistribution { - return []LoadDistribution{Default, SourceIP, SourceIPProtocol} -} - -// NextHopType enumerates the values for next hop type. -type NextHopType string - -const ( - // NextHopTypeHyperNetGateway ... - NextHopTypeHyperNetGateway NextHopType = "HyperNetGateway" - // NextHopTypeInternet ... - NextHopTypeInternet NextHopType = "Internet" - // NextHopTypeNone ... - NextHopTypeNone NextHopType = "None" - // NextHopTypeVirtualAppliance ... - NextHopTypeVirtualAppliance NextHopType = "VirtualAppliance" - // NextHopTypeVirtualNetworkGateway ... - NextHopTypeVirtualNetworkGateway NextHopType = "VirtualNetworkGateway" - // NextHopTypeVnetLocal ... - NextHopTypeVnetLocal NextHopType = "VnetLocal" -) - -// PossibleNextHopTypeValues returns an array of possible values for the NextHopType const type. -func PossibleNextHopTypeValues() []NextHopType { - return []NextHopType{NextHopTypeHyperNetGateway, NextHopTypeInternet, NextHopTypeNone, NextHopTypeVirtualAppliance, NextHopTypeVirtualNetworkGateway, NextHopTypeVnetLocal} -} - -// OfficeTrafficCategory enumerates the values for office traffic category. -type OfficeTrafficCategory string - -const ( - // OfficeTrafficCategoryAll ... - OfficeTrafficCategoryAll OfficeTrafficCategory = "All" - // OfficeTrafficCategoryNone ... - OfficeTrafficCategoryNone OfficeTrafficCategory = "None" - // OfficeTrafficCategoryOptimize ... - OfficeTrafficCategoryOptimize OfficeTrafficCategory = "Optimize" - // OfficeTrafficCategoryOptimizeAndAllow ... - OfficeTrafficCategoryOptimizeAndAllow OfficeTrafficCategory = "OptimizeAndAllow" -) - -// PossibleOfficeTrafficCategoryValues returns an array of possible values for the OfficeTrafficCategory const type. -func PossibleOfficeTrafficCategoryValues() []OfficeTrafficCategory { - return []OfficeTrafficCategory{OfficeTrafficCategoryAll, OfficeTrafficCategoryNone, OfficeTrafficCategoryOptimize, OfficeTrafficCategoryOptimizeAndAllow} -} - -// OperationStatus enumerates the values for operation status. -type OperationStatus string - -const ( - // OperationStatusFailed ... - OperationStatusFailed OperationStatus = "Failed" - // OperationStatusInProgress ... - OperationStatusInProgress OperationStatus = "InProgress" - // OperationStatusSucceeded ... - OperationStatusSucceeded OperationStatus = "Succeeded" -) - -// PossibleOperationStatusValues returns an array of possible values for the OperationStatus const type. -func PossibleOperationStatusValues() []OperationStatus { - return []OperationStatus{OperationStatusFailed, OperationStatusInProgress, OperationStatusSucceeded} -} - -// Origin enumerates the values for origin. -type Origin string - -const ( - // OriginInbound ... - OriginInbound Origin = "Inbound" - // OriginLocal ... - OriginLocal Origin = "Local" - // OriginOutbound ... - OriginOutbound Origin = "Outbound" -) - -// PossibleOriginValues returns an array of possible values for the Origin const type. -func PossibleOriginValues() []Origin { - return []Origin{OriginInbound, OriginLocal, OriginOutbound} -} - -// PcError enumerates the values for pc error. -type PcError string - -const ( - // AgentStopped ... - AgentStopped PcError = "AgentStopped" - // CaptureFailed ... - CaptureFailed PcError = "CaptureFailed" - // InternalError ... - InternalError PcError = "InternalError" - // LocalFileFailed ... - LocalFileFailed PcError = "LocalFileFailed" - // StorageFailed ... - StorageFailed PcError = "StorageFailed" -) - -// PossiblePcErrorValues returns an array of possible values for the PcError const type. -func PossiblePcErrorValues() []PcError { - return []PcError{AgentStopped, CaptureFailed, InternalError, LocalFileFailed, StorageFailed} -} - -// PcProtocol enumerates the values for pc protocol. -type PcProtocol string - -const ( - // PcProtocolAny ... - PcProtocolAny PcProtocol = "Any" - // PcProtocolTCP ... - PcProtocolTCP PcProtocol = "TCP" - // PcProtocolUDP ... - PcProtocolUDP PcProtocol = "UDP" -) - -// PossiblePcProtocolValues returns an array of possible values for the PcProtocol const type. -func PossiblePcProtocolValues() []PcProtocol { - return []PcProtocol{PcProtocolAny, PcProtocolTCP, PcProtocolUDP} -} - -// PcStatus enumerates the values for pc status. -type PcStatus string - -const ( - // PcStatusError ... - PcStatusError PcStatus = "Error" - // PcStatusNotStarted ... - PcStatusNotStarted PcStatus = "NotStarted" - // PcStatusRunning ... - PcStatusRunning PcStatus = "Running" - // PcStatusStopped ... - PcStatusStopped PcStatus = "Stopped" - // PcStatusUnknown ... - PcStatusUnknown PcStatus = "Unknown" -) - -// PossiblePcStatusValues returns an array of possible values for the PcStatus const type. -func PossiblePcStatusValues() []PcStatus { - return []PcStatus{PcStatusError, PcStatusNotStarted, PcStatusRunning, PcStatusStopped, PcStatusUnknown} -} - -// PfsGroup enumerates the values for pfs group. -type PfsGroup string - -const ( - // PfsGroupECP256 ... - PfsGroupECP256 PfsGroup = "ECP256" - // PfsGroupECP384 ... - PfsGroupECP384 PfsGroup = "ECP384" - // PfsGroupNone ... - PfsGroupNone PfsGroup = "None" - // PfsGroupPFS1 ... - PfsGroupPFS1 PfsGroup = "PFS1" - // PfsGroupPFS14 ... - PfsGroupPFS14 PfsGroup = "PFS14" - // PfsGroupPFS2 ... - PfsGroupPFS2 PfsGroup = "PFS2" - // PfsGroupPFS2048 ... - PfsGroupPFS2048 PfsGroup = "PFS2048" - // PfsGroupPFS24 ... - PfsGroupPFS24 PfsGroup = "PFS24" - // PfsGroupPFSMM ... - PfsGroupPFSMM PfsGroup = "PFSMM" -) - -// PossiblePfsGroupValues returns an array of possible values for the PfsGroup const type. -func PossiblePfsGroupValues() []PfsGroup { - return []PfsGroup{PfsGroupECP256, PfsGroupECP384, PfsGroupNone, PfsGroupPFS1, PfsGroupPFS14, PfsGroupPFS2, PfsGroupPFS2048, PfsGroupPFS24, PfsGroupPFSMM} -} - -// ProbeProtocol enumerates the values for probe protocol. -type ProbeProtocol string - -const ( - // ProbeProtocolHTTP ... - ProbeProtocolHTTP ProbeProtocol = "Http" - // ProbeProtocolHTTPS ... - ProbeProtocolHTTPS ProbeProtocol = "Https" - // ProbeProtocolTCP ... - ProbeProtocolTCP ProbeProtocol = "Tcp" -) - -// PossibleProbeProtocolValues returns an array of possible values for the ProbeProtocol const type. -func PossibleProbeProtocolValues() []ProbeProtocol { - return []ProbeProtocol{ProbeProtocolHTTP, ProbeProtocolHTTPS, ProbeProtocolTCP} -} - -// ProcessorArchitecture enumerates the values for processor architecture. -type ProcessorArchitecture string - -const ( - // Amd64 ... - Amd64 ProcessorArchitecture = "Amd64" - // X86 ... - X86 ProcessorArchitecture = "X86" -) - -// PossibleProcessorArchitectureValues returns an array of possible values for the ProcessorArchitecture const type. -func PossibleProcessorArchitectureValues() []ProcessorArchitecture { - return []ProcessorArchitecture{Amd64, X86} -} - -// Protocol enumerates the values for protocol. -type Protocol string - -const ( - // ProtocolHTTP ... - ProtocolHTTP Protocol = "Http" - // ProtocolHTTPS ... - ProtocolHTTPS Protocol = "Https" - // ProtocolIcmp ... - ProtocolIcmp Protocol = "Icmp" - // ProtocolTCP ... - ProtocolTCP Protocol = "Tcp" -) - -// PossibleProtocolValues returns an array of possible values for the Protocol const type. -func PossibleProtocolValues() []Protocol { - return []Protocol{ProtocolHTTP, ProtocolHTTPS, ProtocolIcmp, ProtocolTCP} -} - -// Protocol1 enumerates the values for protocol 1. -type Protocol1 string - -const ( - // Protocol1All ... - Protocol1All Protocol1 = "All" - // Protocol1TCP ... - Protocol1TCP Protocol1 = "Tcp" - // Protocol1UDP ... - Protocol1UDP Protocol1 = "Udp" -) - -// PossibleProtocol1Values returns an array of possible values for the Protocol1 const type. -func PossibleProtocol1Values() []Protocol1 { - return []Protocol1{Protocol1All, Protocol1TCP, Protocol1UDP} -} - -// ProvisioningState enumerates the values for provisioning state. -type ProvisioningState string - -const ( - // Deleting ... - Deleting ProvisioningState = "Deleting" - // Failed ... - Failed ProvisioningState = "Failed" - // Succeeded ... - Succeeded ProvisioningState = "Succeeded" - // Updating ... - Updating ProvisioningState = "Updating" -) - -// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. -func PossibleProvisioningStateValues() []ProvisioningState { - return []ProvisioningState{Deleting, Failed, Succeeded, Updating} -} - -// PublicIPAddressSkuName enumerates the values for public ip address sku name. -type PublicIPAddressSkuName string - -const ( - // PublicIPAddressSkuNameBasic ... - PublicIPAddressSkuNameBasic PublicIPAddressSkuName = "Basic" - // PublicIPAddressSkuNameStandard ... - PublicIPAddressSkuNameStandard PublicIPAddressSkuName = "Standard" -) - -// PossiblePublicIPAddressSkuNameValues returns an array of possible values for the PublicIPAddressSkuName const type. -func PossiblePublicIPAddressSkuNameValues() []PublicIPAddressSkuName { - return []PublicIPAddressSkuName{PublicIPAddressSkuNameBasic, PublicIPAddressSkuNameStandard} -} - -// PublicIPPrefixSkuName enumerates the values for public ip prefix sku name. -type PublicIPPrefixSkuName string - -const ( - // Standard ... - Standard PublicIPPrefixSkuName = "Standard" -) - -// PossiblePublicIPPrefixSkuNameValues returns an array of possible values for the PublicIPPrefixSkuName const type. -func PossiblePublicIPPrefixSkuNameValues() []PublicIPPrefixSkuName { - return []PublicIPPrefixSkuName{Standard} -} - -// ResourceIdentityType enumerates the values for resource identity type. -type ResourceIdentityType string - -const ( - // ResourceIdentityTypeNone ... - ResourceIdentityTypeNone ResourceIdentityType = "None" - // ResourceIdentityTypeSystemAssigned ... - ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" - // ResourceIdentityTypeSystemAssignedUserAssigned ... - ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" - // ResourceIdentityTypeUserAssigned ... - ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" -) - -// PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type. -func PossibleResourceIdentityTypeValues() []ResourceIdentityType { - return []ResourceIdentityType{ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned} -} - -// RouteNextHopType enumerates the values for route next hop type. -type RouteNextHopType string - -const ( - // RouteNextHopTypeInternet ... - RouteNextHopTypeInternet RouteNextHopType = "Internet" - // RouteNextHopTypeNone ... - RouteNextHopTypeNone RouteNextHopType = "None" - // RouteNextHopTypeVirtualAppliance ... - RouteNextHopTypeVirtualAppliance RouteNextHopType = "VirtualAppliance" - // RouteNextHopTypeVirtualNetworkGateway ... - RouteNextHopTypeVirtualNetworkGateway RouteNextHopType = "VirtualNetworkGateway" - // RouteNextHopTypeVnetLocal ... - RouteNextHopTypeVnetLocal RouteNextHopType = "VnetLocal" -) - -// PossibleRouteNextHopTypeValues returns an array of possible values for the RouteNextHopType const type. -func PossibleRouteNextHopTypeValues() []RouteNextHopType { - return []RouteNextHopType{RouteNextHopTypeInternet, RouteNextHopTypeNone, RouteNextHopTypeVirtualAppliance, RouteNextHopTypeVirtualNetworkGateway, RouteNextHopTypeVnetLocal} -} - -// SecurityRuleAccess enumerates the values for security rule access. -type SecurityRuleAccess string - -const ( - // SecurityRuleAccessAllow ... - SecurityRuleAccessAllow SecurityRuleAccess = "Allow" - // SecurityRuleAccessDeny ... - SecurityRuleAccessDeny SecurityRuleAccess = "Deny" -) - -// PossibleSecurityRuleAccessValues returns an array of possible values for the SecurityRuleAccess const type. -func PossibleSecurityRuleAccessValues() []SecurityRuleAccess { - return []SecurityRuleAccess{SecurityRuleAccessAllow, SecurityRuleAccessDeny} -} - -// SecurityRuleDirection enumerates the values for security rule direction. -type SecurityRuleDirection string - -const ( - // SecurityRuleDirectionInbound ... - SecurityRuleDirectionInbound SecurityRuleDirection = "Inbound" - // SecurityRuleDirectionOutbound ... - SecurityRuleDirectionOutbound SecurityRuleDirection = "Outbound" -) - -// PossibleSecurityRuleDirectionValues returns an array of possible values for the SecurityRuleDirection const type. -func PossibleSecurityRuleDirectionValues() []SecurityRuleDirection { - return []SecurityRuleDirection{SecurityRuleDirectionInbound, SecurityRuleDirectionOutbound} -} - -// SecurityRuleProtocol enumerates the values for security rule protocol. -type SecurityRuleProtocol string - -const ( - // SecurityRuleProtocolAsterisk ... - SecurityRuleProtocolAsterisk SecurityRuleProtocol = "*" - // SecurityRuleProtocolTCP ... - SecurityRuleProtocolTCP SecurityRuleProtocol = "Tcp" - // SecurityRuleProtocolUDP ... - SecurityRuleProtocolUDP SecurityRuleProtocol = "Udp" -) - -// PossibleSecurityRuleProtocolValues returns an array of possible values for the SecurityRuleProtocol const type. -func PossibleSecurityRuleProtocolValues() []SecurityRuleProtocol { - return []SecurityRuleProtocol{SecurityRuleProtocolAsterisk, SecurityRuleProtocolTCP, SecurityRuleProtocolUDP} -} - -// ServiceProviderProvisioningState enumerates the values for service provider provisioning state. -type ServiceProviderProvisioningState string - -const ( - // Deprovisioning ... - Deprovisioning ServiceProviderProvisioningState = "Deprovisioning" - // NotProvisioned ... - NotProvisioned ServiceProviderProvisioningState = "NotProvisioned" - // Provisioned ... - Provisioned ServiceProviderProvisioningState = "Provisioned" - // Provisioning ... - Provisioning ServiceProviderProvisioningState = "Provisioning" -) - -// PossibleServiceProviderProvisioningStateValues returns an array of possible values for the ServiceProviderProvisioningState const type. -func PossibleServiceProviderProvisioningStateValues() []ServiceProviderProvisioningState { - return []ServiceProviderProvisioningState{Deprovisioning, NotProvisioned, Provisioned, Provisioning} -} - -// Severity enumerates the values for severity. -type Severity string - -const ( - // SeverityError ... - SeverityError Severity = "Error" - // SeverityWarning ... - SeverityWarning Severity = "Warning" -) - -// PossibleSeverityValues returns an array of possible values for the Severity const type. -func PossibleSeverityValues() []Severity { - return []Severity{SeverityError, SeverityWarning} -} - -// TransportProtocol enumerates the values for transport protocol. -type TransportProtocol string - -const ( - // TransportProtocolAll ... - TransportProtocolAll TransportProtocol = "All" - // TransportProtocolTCP ... - TransportProtocolTCP TransportProtocol = "Tcp" - // TransportProtocolUDP ... - TransportProtocolUDP TransportProtocol = "Udp" -) - -// PossibleTransportProtocolValues returns an array of possible values for the TransportProtocol const type. -func PossibleTransportProtocolValues() []TransportProtocol { - return []TransportProtocol{TransportProtocolAll, TransportProtocolTCP, TransportProtocolUDP} -} - -// TunnelConnectionStatus enumerates the values for tunnel connection status. -type TunnelConnectionStatus string - -const ( - // TunnelConnectionStatusConnected ... - TunnelConnectionStatusConnected TunnelConnectionStatus = "Connected" - // TunnelConnectionStatusConnecting ... - TunnelConnectionStatusConnecting TunnelConnectionStatus = "Connecting" - // TunnelConnectionStatusNotConnected ... - TunnelConnectionStatusNotConnected TunnelConnectionStatus = "NotConnected" - // TunnelConnectionStatusUnknown ... - TunnelConnectionStatusUnknown TunnelConnectionStatus = "Unknown" -) - -// PossibleTunnelConnectionStatusValues returns an array of possible values for the TunnelConnectionStatus const type. -func PossibleTunnelConnectionStatusValues() []TunnelConnectionStatus { - return []TunnelConnectionStatus{TunnelConnectionStatusConnected, TunnelConnectionStatusConnecting, TunnelConnectionStatusNotConnected, TunnelConnectionStatusUnknown} -} - -// VerbosityLevel enumerates the values for verbosity level. -type VerbosityLevel string - -const ( - // Full ... - Full VerbosityLevel = "Full" - // Minimum ... - Minimum VerbosityLevel = "Minimum" - // Normal ... - Normal VerbosityLevel = "Normal" -) - -// PossibleVerbosityLevelValues returns an array of possible values for the VerbosityLevel const type. -func PossibleVerbosityLevelValues() []VerbosityLevel { - return []VerbosityLevel{Full, Minimum, Normal} -} - -// VirtualNetworkGatewayConnectionProtocol enumerates the values for virtual network gateway connection -// protocol. -type VirtualNetworkGatewayConnectionProtocol string - -const ( - // IKEv1 ... - IKEv1 VirtualNetworkGatewayConnectionProtocol = "IKEv1" - // IKEv2 ... - IKEv2 VirtualNetworkGatewayConnectionProtocol = "IKEv2" -) - -// PossibleVirtualNetworkGatewayConnectionProtocolValues returns an array of possible values for the VirtualNetworkGatewayConnectionProtocol const type. -func PossibleVirtualNetworkGatewayConnectionProtocolValues() []VirtualNetworkGatewayConnectionProtocol { - return []VirtualNetworkGatewayConnectionProtocol{IKEv1, IKEv2} -} - -// VirtualNetworkGatewayConnectionStatus enumerates the values for virtual network gateway connection status. -type VirtualNetworkGatewayConnectionStatus string - -const ( - // VirtualNetworkGatewayConnectionStatusConnected ... - VirtualNetworkGatewayConnectionStatusConnected VirtualNetworkGatewayConnectionStatus = "Connected" - // VirtualNetworkGatewayConnectionStatusConnecting ... - VirtualNetworkGatewayConnectionStatusConnecting VirtualNetworkGatewayConnectionStatus = "Connecting" - // VirtualNetworkGatewayConnectionStatusNotConnected ... - VirtualNetworkGatewayConnectionStatusNotConnected VirtualNetworkGatewayConnectionStatus = "NotConnected" - // VirtualNetworkGatewayConnectionStatusUnknown ... - VirtualNetworkGatewayConnectionStatusUnknown VirtualNetworkGatewayConnectionStatus = "Unknown" -) - -// PossibleVirtualNetworkGatewayConnectionStatusValues returns an array of possible values for the VirtualNetworkGatewayConnectionStatus const type. -func PossibleVirtualNetworkGatewayConnectionStatusValues() []VirtualNetworkGatewayConnectionStatus { - return []VirtualNetworkGatewayConnectionStatus{VirtualNetworkGatewayConnectionStatusConnected, VirtualNetworkGatewayConnectionStatusConnecting, VirtualNetworkGatewayConnectionStatusNotConnected, VirtualNetworkGatewayConnectionStatusUnknown} -} - -// VirtualNetworkGatewayConnectionType enumerates the values for virtual network gateway connection type. -type VirtualNetworkGatewayConnectionType string - -const ( - // ExpressRoute ... - ExpressRoute VirtualNetworkGatewayConnectionType = "ExpressRoute" - // IPsec ... - IPsec VirtualNetworkGatewayConnectionType = "IPsec" - // Vnet2Vnet ... - Vnet2Vnet VirtualNetworkGatewayConnectionType = "Vnet2Vnet" - // VPNClient ... - VPNClient VirtualNetworkGatewayConnectionType = "VPNClient" -) - -// PossibleVirtualNetworkGatewayConnectionTypeValues returns an array of possible values for the VirtualNetworkGatewayConnectionType const type. -func PossibleVirtualNetworkGatewayConnectionTypeValues() []VirtualNetworkGatewayConnectionType { - return []VirtualNetworkGatewayConnectionType{ExpressRoute, IPsec, Vnet2Vnet, VPNClient} -} - -// VirtualNetworkGatewaySkuName enumerates the values for virtual network gateway sku name. -type VirtualNetworkGatewaySkuName string - -const ( - // VirtualNetworkGatewaySkuNameBasic ... - VirtualNetworkGatewaySkuNameBasic VirtualNetworkGatewaySkuName = "Basic" - // VirtualNetworkGatewaySkuNameErGw1AZ ... - VirtualNetworkGatewaySkuNameErGw1AZ VirtualNetworkGatewaySkuName = "ErGw1AZ" - // VirtualNetworkGatewaySkuNameErGw2AZ ... - VirtualNetworkGatewaySkuNameErGw2AZ VirtualNetworkGatewaySkuName = "ErGw2AZ" - // VirtualNetworkGatewaySkuNameErGw3AZ ... - VirtualNetworkGatewaySkuNameErGw3AZ VirtualNetworkGatewaySkuName = "ErGw3AZ" - // VirtualNetworkGatewaySkuNameHighPerformance ... - VirtualNetworkGatewaySkuNameHighPerformance VirtualNetworkGatewaySkuName = "HighPerformance" - // VirtualNetworkGatewaySkuNameStandard ... - VirtualNetworkGatewaySkuNameStandard VirtualNetworkGatewaySkuName = "Standard" - // VirtualNetworkGatewaySkuNameUltraPerformance ... - VirtualNetworkGatewaySkuNameUltraPerformance VirtualNetworkGatewaySkuName = "UltraPerformance" - // VirtualNetworkGatewaySkuNameVpnGw1 ... - VirtualNetworkGatewaySkuNameVpnGw1 VirtualNetworkGatewaySkuName = "VpnGw1" - // VirtualNetworkGatewaySkuNameVpnGw1AZ ... - VirtualNetworkGatewaySkuNameVpnGw1AZ VirtualNetworkGatewaySkuName = "VpnGw1AZ" - // VirtualNetworkGatewaySkuNameVpnGw2 ... - VirtualNetworkGatewaySkuNameVpnGw2 VirtualNetworkGatewaySkuName = "VpnGw2" - // VirtualNetworkGatewaySkuNameVpnGw2AZ ... - VirtualNetworkGatewaySkuNameVpnGw2AZ VirtualNetworkGatewaySkuName = "VpnGw2AZ" - // VirtualNetworkGatewaySkuNameVpnGw3 ... - VirtualNetworkGatewaySkuNameVpnGw3 VirtualNetworkGatewaySkuName = "VpnGw3" - // VirtualNetworkGatewaySkuNameVpnGw3AZ ... - VirtualNetworkGatewaySkuNameVpnGw3AZ VirtualNetworkGatewaySkuName = "VpnGw3AZ" -) - -// PossibleVirtualNetworkGatewaySkuNameValues returns an array of possible values for the VirtualNetworkGatewaySkuName const type. -func PossibleVirtualNetworkGatewaySkuNameValues() []VirtualNetworkGatewaySkuName { - return []VirtualNetworkGatewaySkuName{VirtualNetworkGatewaySkuNameBasic, VirtualNetworkGatewaySkuNameErGw1AZ, VirtualNetworkGatewaySkuNameErGw2AZ, VirtualNetworkGatewaySkuNameErGw3AZ, VirtualNetworkGatewaySkuNameHighPerformance, VirtualNetworkGatewaySkuNameStandard, VirtualNetworkGatewaySkuNameUltraPerformance, VirtualNetworkGatewaySkuNameVpnGw1, VirtualNetworkGatewaySkuNameVpnGw1AZ, VirtualNetworkGatewaySkuNameVpnGw2, VirtualNetworkGatewaySkuNameVpnGw2AZ, VirtualNetworkGatewaySkuNameVpnGw3, VirtualNetworkGatewaySkuNameVpnGw3AZ} -} - -// VirtualNetworkGatewaySkuTier enumerates the values for virtual network gateway sku tier. -type VirtualNetworkGatewaySkuTier string - -const ( - // VirtualNetworkGatewaySkuTierBasic ... - VirtualNetworkGatewaySkuTierBasic VirtualNetworkGatewaySkuTier = "Basic" - // VirtualNetworkGatewaySkuTierErGw1AZ ... - VirtualNetworkGatewaySkuTierErGw1AZ VirtualNetworkGatewaySkuTier = "ErGw1AZ" - // VirtualNetworkGatewaySkuTierErGw2AZ ... - VirtualNetworkGatewaySkuTierErGw2AZ VirtualNetworkGatewaySkuTier = "ErGw2AZ" - // VirtualNetworkGatewaySkuTierErGw3AZ ... - VirtualNetworkGatewaySkuTierErGw3AZ VirtualNetworkGatewaySkuTier = "ErGw3AZ" - // VirtualNetworkGatewaySkuTierHighPerformance ... - VirtualNetworkGatewaySkuTierHighPerformance VirtualNetworkGatewaySkuTier = "HighPerformance" - // VirtualNetworkGatewaySkuTierStandard ... - VirtualNetworkGatewaySkuTierStandard VirtualNetworkGatewaySkuTier = "Standard" - // VirtualNetworkGatewaySkuTierUltraPerformance ... - VirtualNetworkGatewaySkuTierUltraPerformance VirtualNetworkGatewaySkuTier = "UltraPerformance" - // VirtualNetworkGatewaySkuTierVpnGw1 ... - VirtualNetworkGatewaySkuTierVpnGw1 VirtualNetworkGatewaySkuTier = "VpnGw1" - // VirtualNetworkGatewaySkuTierVpnGw1AZ ... - VirtualNetworkGatewaySkuTierVpnGw1AZ VirtualNetworkGatewaySkuTier = "VpnGw1AZ" - // VirtualNetworkGatewaySkuTierVpnGw2 ... - VirtualNetworkGatewaySkuTierVpnGw2 VirtualNetworkGatewaySkuTier = "VpnGw2" - // VirtualNetworkGatewaySkuTierVpnGw2AZ ... - VirtualNetworkGatewaySkuTierVpnGw2AZ VirtualNetworkGatewaySkuTier = "VpnGw2AZ" - // VirtualNetworkGatewaySkuTierVpnGw3 ... - VirtualNetworkGatewaySkuTierVpnGw3 VirtualNetworkGatewaySkuTier = "VpnGw3" - // VirtualNetworkGatewaySkuTierVpnGw3AZ ... - VirtualNetworkGatewaySkuTierVpnGw3AZ VirtualNetworkGatewaySkuTier = "VpnGw3AZ" -) - -// PossibleVirtualNetworkGatewaySkuTierValues returns an array of possible values for the VirtualNetworkGatewaySkuTier const type. -func PossibleVirtualNetworkGatewaySkuTierValues() []VirtualNetworkGatewaySkuTier { - return []VirtualNetworkGatewaySkuTier{VirtualNetworkGatewaySkuTierBasic, VirtualNetworkGatewaySkuTierErGw1AZ, VirtualNetworkGatewaySkuTierErGw2AZ, VirtualNetworkGatewaySkuTierErGw3AZ, VirtualNetworkGatewaySkuTierHighPerformance, VirtualNetworkGatewaySkuTierStandard, VirtualNetworkGatewaySkuTierUltraPerformance, VirtualNetworkGatewaySkuTierVpnGw1, VirtualNetworkGatewaySkuTierVpnGw1AZ, VirtualNetworkGatewaySkuTierVpnGw2, VirtualNetworkGatewaySkuTierVpnGw2AZ, VirtualNetworkGatewaySkuTierVpnGw3, VirtualNetworkGatewaySkuTierVpnGw3AZ} -} - -// VirtualNetworkGatewayType enumerates the values for virtual network gateway type. -type VirtualNetworkGatewayType string - -const ( - // VirtualNetworkGatewayTypeExpressRoute ... - VirtualNetworkGatewayTypeExpressRoute VirtualNetworkGatewayType = "ExpressRoute" - // VirtualNetworkGatewayTypeVpn ... - VirtualNetworkGatewayTypeVpn VirtualNetworkGatewayType = "Vpn" -) - -// PossibleVirtualNetworkGatewayTypeValues returns an array of possible values for the VirtualNetworkGatewayType const type. -func PossibleVirtualNetworkGatewayTypeValues() []VirtualNetworkGatewayType { - return []VirtualNetworkGatewayType{VirtualNetworkGatewayTypeExpressRoute, VirtualNetworkGatewayTypeVpn} -} - -// VirtualNetworkPeeringState enumerates the values for virtual network peering state. -type VirtualNetworkPeeringState string - -const ( - // VirtualNetworkPeeringStateConnected ... - VirtualNetworkPeeringStateConnected VirtualNetworkPeeringState = "Connected" - // VirtualNetworkPeeringStateDisconnected ... - VirtualNetworkPeeringStateDisconnected VirtualNetworkPeeringState = "Disconnected" - // VirtualNetworkPeeringStateInitiated ... - VirtualNetworkPeeringStateInitiated VirtualNetworkPeeringState = "Initiated" -) - -// PossibleVirtualNetworkPeeringStateValues returns an array of possible values for the VirtualNetworkPeeringState const type. -func PossibleVirtualNetworkPeeringStateValues() []VirtualNetworkPeeringState { - return []VirtualNetworkPeeringState{VirtualNetworkPeeringStateConnected, VirtualNetworkPeeringStateDisconnected, VirtualNetworkPeeringStateInitiated} -} - -// VirtualWanSecurityProviderType enumerates the values for virtual wan security provider type. -type VirtualWanSecurityProviderType string - -const ( - // External ... - External VirtualWanSecurityProviderType = "External" - // Native ... - Native VirtualWanSecurityProviderType = "Native" -) - -// PossibleVirtualWanSecurityProviderTypeValues returns an array of possible values for the VirtualWanSecurityProviderType const type. -func PossibleVirtualWanSecurityProviderTypeValues() []VirtualWanSecurityProviderType { - return []VirtualWanSecurityProviderType{External, Native} -} - -// VpnClientProtocol enumerates the values for vpn client protocol. -type VpnClientProtocol string - -const ( - // IkeV2 ... - IkeV2 VpnClientProtocol = "IkeV2" - // OpenVPN ... - OpenVPN VpnClientProtocol = "OpenVPN" - // SSTP ... - SSTP VpnClientProtocol = "SSTP" -) - -// PossibleVpnClientProtocolValues returns an array of possible values for the VpnClientProtocol const type. -func PossibleVpnClientProtocolValues() []VpnClientProtocol { - return []VpnClientProtocol{IkeV2, OpenVPN, SSTP} -} - -// VpnConnectionStatus enumerates the values for vpn connection status. -type VpnConnectionStatus string - -const ( - // VpnConnectionStatusConnected ... - VpnConnectionStatusConnected VpnConnectionStatus = "Connected" - // VpnConnectionStatusConnecting ... - VpnConnectionStatusConnecting VpnConnectionStatus = "Connecting" - // VpnConnectionStatusNotConnected ... - VpnConnectionStatusNotConnected VpnConnectionStatus = "NotConnected" - // VpnConnectionStatusUnknown ... - VpnConnectionStatusUnknown VpnConnectionStatus = "Unknown" -) - -// PossibleVpnConnectionStatusValues returns an array of possible values for the VpnConnectionStatus const type. -func PossibleVpnConnectionStatusValues() []VpnConnectionStatus { - return []VpnConnectionStatus{VpnConnectionStatusConnected, VpnConnectionStatusConnecting, VpnConnectionStatusNotConnected, VpnConnectionStatusUnknown} -} - -// VpnGatewayTunnelingProtocol enumerates the values for vpn gateway tunneling protocol. -type VpnGatewayTunnelingProtocol string - -const ( - // VpnGatewayTunnelingProtocolIkeV2 ... - VpnGatewayTunnelingProtocolIkeV2 VpnGatewayTunnelingProtocol = "IkeV2" - // VpnGatewayTunnelingProtocolOpenVPN ... - VpnGatewayTunnelingProtocolOpenVPN VpnGatewayTunnelingProtocol = "OpenVPN" -) - -// PossibleVpnGatewayTunnelingProtocolValues returns an array of possible values for the VpnGatewayTunnelingProtocol const type. -func PossibleVpnGatewayTunnelingProtocolValues() []VpnGatewayTunnelingProtocol { - return []VpnGatewayTunnelingProtocol{VpnGatewayTunnelingProtocolIkeV2, VpnGatewayTunnelingProtocolOpenVPN} -} - -// VpnType enumerates the values for vpn type. -type VpnType string - -const ( - // PolicyBased ... - PolicyBased VpnType = "PolicyBased" - // RouteBased ... - RouteBased VpnType = "RouteBased" -) - -// PossibleVpnTypeValues returns an array of possible values for the VpnType const type. -func PossibleVpnTypeValues() []VpnType { - return []VpnType{PolicyBased, RouteBased} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitauthorizations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitauthorizations.go deleted file mode 100644 index b634ce95a..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitauthorizations.go +++ /dev/null @@ -1,395 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitAuthorizationsClient is the network Client -type ExpressRouteCircuitAuthorizationsClient struct { - BaseClient -} - -// NewExpressRouteCircuitAuthorizationsClient creates an instance of the ExpressRouteCircuitAuthorizationsClient -// client. -func NewExpressRouteCircuitAuthorizationsClient(subscriptionID string) ExpressRouteCircuitAuthorizationsClient { - return NewExpressRouteCircuitAuthorizationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitAuthorizationsClientWithBaseURI creates an instance of the -// ExpressRouteCircuitAuthorizationsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewExpressRouteCircuitAuthorizationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitAuthorizationsClient { - return ExpressRouteCircuitAuthorizationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an authorization in the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// authorizationName - the name of the authorization. -// authorizationParameters - parameters supplied to the create or update express route circuit authorization -// operation. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (result ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, authorizationName, authorizationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - authorizationParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), - autorest.WithJSON(authorizationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified authorization from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// authorizationName - the name of the authorization. -func (client ExpressRouteCircuitAuthorizationsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorizationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, authorizationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified authorization from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// authorizationName - the name of the authorization. -func (client ExpressRouteCircuitAuthorizationsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorization, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, authorizationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitAuthorizationsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all authorizations in an express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -func (client ExpressRouteCircuitAuthorizationsClient) List(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.List") - defer func() { - sc := -1 - if result.alr.Response.Response != nil { - sc = result.alr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.alr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request") - return - } - - result.alr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to request") - return - } - if result.alr.hasNextLink() && result.alr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitAuthorizationsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) ListResponder(resp *http.Response) (result AuthorizationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitAuthorizationsClient) listNextResults(ctx context.Context, lastResults AuthorizationListResult) (result AuthorizationListResult, err error) { - req, err := lastResults.authorizationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitAuthorizationsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, circuitName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitconnections.go deleted file mode 100644 index 35018f771..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitconnections.go +++ /dev/null @@ -1,402 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitConnectionsClient is the network Client -type ExpressRouteCircuitConnectionsClient struct { - BaseClient -} - -// NewExpressRouteCircuitConnectionsClient creates an instance of the ExpressRouteCircuitConnectionsClient client. -func NewExpressRouteCircuitConnectionsClient(subscriptionID string) ExpressRouteCircuitConnectionsClient { - return NewExpressRouteCircuitConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitConnectionsClientWithBaseURI creates an instance of the ExpressRouteCircuitConnectionsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewExpressRouteCircuitConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitConnectionsClient { - return ExpressRouteCircuitConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Express Route Circuit Connection in the specified express route circuits. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// connectionName - the name of the express route circuit connection. -// expressRouteCircuitConnectionParameters - parameters supplied to the create or update express route circuit -// connection operation. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection) (result ExpressRouteCircuitConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "connectionName": autorest.Encode("path", connectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - expressRouteCircuitConnectionParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters), - autorest.WithJSON(expressRouteCircuitConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Express Route Circuit Connection from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// connectionName - the name of the express route circuit connection. -func (client ExpressRouteCircuitConnectionsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (result ExpressRouteCircuitConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "connectionName": autorest.Encode("path", connectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Express Route Circuit Connection from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// connectionName - the name of the express route circuit connection. -func (client ExpressRouteCircuitConnectionsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (result ExpressRouteCircuitConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "connectionName": autorest.Encode("path", connectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all global reach connections associated with a private peering in an express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitConnectionsClient) List(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.List") - defer func() { - sc := -1 - if result.ercclr.Response.Response != nil { - sc = result.ercclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ercclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.ercclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.ercclr.hasNextLink() && result.ercclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitConnectionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitConnectionsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCircuitConnectionListResult) (result ExpressRouteCircuitConnectionListResult, err error) { - req, err := lastResults.expressRouteCircuitConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, circuitName, peeringName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitpeerings.go deleted file mode 100644 index 68513b833..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuitpeerings.go +++ /dev/null @@ -1,405 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitPeeringsClient is the network Client -type ExpressRouteCircuitPeeringsClient struct { - BaseClient -} - -// NewExpressRouteCircuitPeeringsClient creates an instance of the ExpressRouteCircuitPeeringsClient client. -func NewExpressRouteCircuitPeeringsClient(subscriptionID string) ExpressRouteCircuitPeeringsClient { - return NewExpressRouteCircuitPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitPeeringsClientWithBaseURI creates an instance of the ExpressRouteCircuitPeeringsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewExpressRouteCircuitPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitPeeringsClient { - return ExpressRouteCircuitPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a peering in the specified express route circuits. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// peeringParameters - parameters supplied to the create or update express route circuit peering operation. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (result ExpressRouteCircuitPeeringsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: peeringParameters, - Constraints: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, peeringName, peeringParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - peeringParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), - autorest.WithJSON(peeringParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitPeeringsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified peering from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitPeeringsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeeringsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitPeeringsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified peering for the express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitPeeringsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all peerings in a specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -func (client ExpressRouteCircuitPeeringsClient) List(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.List") - defer func() { - sc := -1 - if result.ercplr.Response.Response != nil { - sc = result.ercplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ercplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request") - return - } - - result.ercplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to request") - return - } - if result.ercplr.hasNextLink() && result.ercplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitPeeringListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitPeeringsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, err error) { - req, err := lastResults.expressRouteCircuitPeeringListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, circuitName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuits.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuits.go deleted file mode 100644 index 482d81376..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecircuits.go +++ /dev/null @@ -1,985 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitsClient is the network Client -type ExpressRouteCircuitsClient struct { - BaseClient -} - -// NewExpressRouteCircuitsClient creates an instance of the ExpressRouteCircuitsClient client. -func NewExpressRouteCircuitsClient(subscriptionID string) ExpressRouteCircuitsClient { - return NewExpressRouteCircuitsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitsClientWithBaseURI creates an instance of the ExpressRouteCircuitsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRouteCircuitsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitsClient { - return ExpressRouteCircuitsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -// parameters - parameters supplied to the create or update express route circuit operation. -func (client ExpressRouteCircuitsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (result ExpressRouteCircuitsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -func (client ExpressRouteCircuitsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of express route circuit. -func (client ExpressRouteCircuitsClient) Get(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuit, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetPeeringStats gets all stats from an express route circuit in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitsClient) GetPeeringStats(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitStats, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.GetPeeringStats") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPeeringStatsPreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", nil, "Failure preparing request") - return - } - - resp, err := client.GetPeeringStatsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure sending request") - return - } - - result, err = client.GetPeeringStatsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure responding to request") - return - } - - return -} - -// GetPeeringStatsPreparer prepares the GetPeeringStats request. -func (client ExpressRouteCircuitsClient) GetPeeringStatsPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/stats", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPeeringStatsSender sends the GetPeeringStats request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) GetPeeringStatsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetPeeringStatsResponder handles the response to the GetPeeringStats request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) GetPeeringStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetStats gets all the stats from an express route circuit in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -func (client ExpressRouteCircuitsClient) GetStats(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitStats, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.GetStats") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetStatsPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", nil, "Failure preparing request") - return - } - - resp, err := client.GetStatsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure sending request") - return - } - - result, err = client.GetStatsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure responding to request") - return - } - - return -} - -// GetStatsPreparer prepares the GetStats request. -func (client ExpressRouteCircuitsClient) GetStatsPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/stats", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetStatsSender sends the GetStats request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) GetStatsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetStatsResponder handles the response to the GetStats request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) GetStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the express route circuits in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRouteCircuitsClient) List(ctx context.Context, resourceGroupName string) (result ExpressRouteCircuitListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.List") - defer func() { - sc := -1 - if result.erclr.Response.Response != nil { - sc = result.erclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending request") - return - } - - result.erclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure responding to request") - return - } - if result.erclr.hasNextLink() && result.erclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { - req, err := lastResults.expressRouteCircuitListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitsClient) ListComplete(ctx context.Context, resourceGroupName string) (result ExpressRouteCircuitListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the express route circuits in a subscription. -func (client ExpressRouteCircuitsClient) ListAll(ctx context.Context) (result ExpressRouteCircuitListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListAll") - defer func() { - sc := -1 - if result.erclr.Response.Response != nil { - sc = result.erclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.erclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending request") - return - } - - result.erclr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.erclr.hasNextLink() && result.erclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ExpressRouteCircuitsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCircuits", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListAllResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) listAllNextResults(ctx context.Context, lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { - req, err := lastResults.expressRouteCircuitListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitsClient) ListAllComplete(ctx context.Context) (result ExpressRouteCircuitListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListArpTable gets the currently advertised ARP table associated with the express route circuit in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCircuitsClient) ListArpTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListArpTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListArpTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListArpTablePreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing request") - return - } - - result, err = client.ListArpTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListArpTablePreparer prepares the ListArpTable request. -func (client ExpressRouteCircuitsClient) ListArpTablePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/arpTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListArpTableSender sends the ListArpTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListArpTableSender(req *http.Request) (future ExpressRouteCircuitsListArpTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListArpTableResponder handles the response to the ListArpTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Response) (result ExpressRouteCircuitsArpTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListRoutesTable gets the currently advertised routes table associated with the express route circuit in a resource -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCircuitsClient) ListRoutesTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListRoutesTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListRoutesTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTablePreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTablePreparer prepares the ListRoutesTable request. -func (client ExpressRouteCircuitsClient) ListRoutesTablePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSender sends the ListRoutesTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListRoutesTableSender(req *http.Request) (future ExpressRouteCircuitsListRoutesTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListRoutesTableSummary gets the currently advertised routes table summary associated with the express route circuit -// in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummary(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListRoutesTableSummaryFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListRoutesTableSummary") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTableSummaryPreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSummarySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTableSummaryPreparer prepares the ListRoutesTableSummary request. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTablesSummary/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSummarySender sends the ListRoutesTableSummary request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummarySender(req *http.Request) (future ExpressRouteCircuitsListRoutesTableSummaryFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableSummaryResponder handles the response to the ListRoutesTableSummary request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableSummaryListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates an express route circuit tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -// parameters - parameters supplied to update express route circuit tags. -func (client ExpressRouteCircuitsClient) UpdateTags(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject) (result ExpressRouteCircuitsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, circuitName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ExpressRouteCircuitsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) UpdateTagsSender(req *http.Request) (future ExpressRouteCircuitsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteconnections.go deleted file mode 100644 index 46445ee1c..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteconnections.go +++ /dev/null @@ -1,359 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteConnectionsClient is the network Client -type ExpressRouteConnectionsClient struct { - BaseClient -} - -// NewExpressRouteConnectionsClient creates an instance of the ExpressRouteConnectionsClient client. -func NewExpressRouteConnectionsClient(subscriptionID string) ExpressRouteConnectionsClient { - return NewExpressRouteConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteConnectionsClientWithBaseURI creates an instance of the ExpressRouteConnectionsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewExpressRouteConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteConnectionsClient { - return ExpressRouteConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a connection between an ExpressRoute gateway and an ExpressRoute circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// connectionName - the name of the connection subresource. -// putExpressRouteConnectionParameters - parameters required in an ExpressRouteConnection PUT operation. -func (client ExpressRouteConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, putExpressRouteConnectionParameters ExpressRouteConnection) (result ExpressRouteConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: putExpressRouteConnectionParameters, - Constraints: []validation.Constraint{{Target: "putExpressRouteConnectionParameters.ExpressRouteConnectionProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "putExpressRouteConnectionParameters.ExpressRouteConnectionProperties.ExpressRouteCircuitPeering", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "putExpressRouteConnectionParameters.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteConnectionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRouteGatewayName, connectionName, putExpressRouteConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, putExpressRouteConnectionParameters ExpressRouteConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}", pathParameters), - autorest.WithJSON(putExpressRouteConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a connection to a ExpressRoute circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// connectionName - the name of the connection subresource. -func (client ExpressRouteConnectionsClient) Delete(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (result ExpressRouteConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, expressRouteGatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) DeleteSender(req *http.Request) (future ExpressRouteConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified ExpressRouteConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// connectionName - the name of the ExpressRoute connection. -func (client ExpressRouteConnectionsClient) Get(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (result ExpressRouteConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRouteGatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) GetResponder(resp *http.Response) (result ExpressRouteConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists ExpressRouteConnections. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -func (client ExpressRouteConnectionsClient) List(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (result ExpressRouteConnectionList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, expressRouteGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) ListResponder(resp *http.Response) (result ExpressRouteConnectionList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecrossconnectionpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecrossconnectionpeerings.go deleted file mode 100644 index 739fa96a9..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecrossconnectionpeerings.go +++ /dev/null @@ -1,407 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCrossConnectionPeeringsClient is the network Client -type ExpressRouteCrossConnectionPeeringsClient struct { - BaseClient -} - -// NewExpressRouteCrossConnectionPeeringsClient creates an instance of the ExpressRouteCrossConnectionPeeringsClient -// client. -func NewExpressRouteCrossConnectionPeeringsClient(subscriptionID string) ExpressRouteCrossConnectionPeeringsClient { - return NewExpressRouteCrossConnectionPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCrossConnectionPeeringsClientWithBaseURI creates an instance of the -// ExpressRouteCrossConnectionPeeringsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewExpressRouteCrossConnectionPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCrossConnectionPeeringsClient { - return ExpressRouteCrossConnectionPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a peering in the specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// peeringParameters - parameters supplied to the create or update ExpressRouteCrossConnection peering -// operation. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering) (result ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: peeringParameters, - Constraints: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, crossConnectionName, peeringName, peeringParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - peeringParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters), - autorest.WithJSON(peeringParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified peering from the ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -func (client ExpressRouteCrossConnectionPeeringsClient) Delete(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (result ExpressRouteCrossConnectionPeeringsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, crossConnectionName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCrossConnectionPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) DeleteSender(req *http.Request) (future ExpressRouteCrossConnectionPeeringsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified peering for the ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -func (client ExpressRouteCrossConnectionPeeringsClient) Get(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (result ExpressRouteCrossConnectionPeering, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, crossConnectionName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCrossConnectionPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all peerings in a specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -func (client ExpressRouteCrossConnectionPeeringsClient) List(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnectionPeeringListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.List") - defer func() { - sc := -1 - if result.erccpl.Response.Response != nil { - sc = result.erccpl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, crossConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erccpl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", resp, "Failure sending request") - return - } - - result.erccpl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", resp, "Failure responding to request") - return - } - if result.erccpl.hasNextLink() && result.erccpl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCrossConnectionPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeeringList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteCrossConnectionPeeringsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCrossConnectionPeeringList) (result ExpressRouteCrossConnectionPeeringList, err error) { - req, err := lastResults.expressRouteCrossConnectionPeeringListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCrossConnectionPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnectionPeeringListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, crossConnectionName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecrossconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecrossconnections.go deleted file mode 100644 index 449a9d624..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutecrossconnections.go +++ /dev/null @@ -1,754 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCrossConnectionsClient is the network Client -type ExpressRouteCrossConnectionsClient struct { - BaseClient -} - -// NewExpressRouteCrossConnectionsClient creates an instance of the ExpressRouteCrossConnectionsClient client. -func NewExpressRouteCrossConnectionsClient(subscriptionID string) ExpressRouteCrossConnectionsClient { - return NewExpressRouteCrossConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCrossConnectionsClientWithBaseURI creates an instance of the ExpressRouteCrossConnectionsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewExpressRouteCrossConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCrossConnectionsClient { - return ExpressRouteCrossConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate update the specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// parameters - parameters supplied to the update express route crossConnection operation. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, parameters ExpressRouteCrossConnection) (result ExpressRouteCrossConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, crossConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, parameters ExpressRouteCrossConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCrossConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCrossConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get gets details about the specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group (peering location of the circuit). -// crossConnectionName - the name of the ExpressRouteCrossConnection (service key of the circuit). -func (client ExpressRouteCrossConnectionsClient) Get(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, crossConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCrossConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) GetResponder(resp *http.Response) (result ExpressRouteCrossConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves all the ExpressRouteCrossConnections in a subscription. -func (client ExpressRouteCrossConnectionsClient) List(ctx context.Context) (result ExpressRouteCrossConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.List") - defer func() { - sc := -1 - if result.ercclr.Response.Response != nil { - sc = result.ercclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ercclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.ercclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.ercclr.hasNextLink() && result.ercclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCrossConnectionsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCrossConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListResponder(resp *http.Response) (result ExpressRouteCrossConnectionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteCrossConnectionsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCrossConnectionListResult) (result ExpressRouteCrossConnectionListResult, err error) { - req, err := lastResults.expressRouteCrossConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCrossConnectionsClient) ListComplete(ctx context.Context) (result ExpressRouteCrossConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListArpTable gets the currently advertised ARP table associated with the express route cross connection in a -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// devicePath - the path of the device -func (client ExpressRouteCrossConnectionsClient) ListArpTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (result ExpressRouteCrossConnectionsListArpTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListArpTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListArpTablePreparer(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListArpTable", nil, "Failure preparing request") - return - } - - result, err = client.ListArpTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListArpTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListArpTablePreparer prepares the ListArpTable request. -func (client ExpressRouteCrossConnectionsClient) ListArpTablePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/arpTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListArpTableSender sends the ListArpTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListArpTableSender(req *http.Request) (future ExpressRouteCrossConnectionsListArpTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListArpTableResponder handles the response to the ListArpTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListArpTableResponder(resp *http.Response) (result ExpressRouteCircuitsArpTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup retrieves all the ExpressRouteCrossConnections in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ExpressRouteCrossConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.ercclr.Response.Response != nil { - sc = result.ercclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.ercclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.ercclr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.ercclr.hasNextLink() && result.ercclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupResponder(resp *http.Response) (result ExpressRouteCrossConnectionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ExpressRouteCrossConnectionsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ExpressRouteCrossConnectionListResult) (result ExpressRouteCrossConnectionListResult, err error) { - req, err := lastResults.expressRouteCrossConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ExpressRouteCrossConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// ListRoutesTable gets the currently advertised routes table associated with the express route cross connection in a -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (result ExpressRouteCrossConnectionsListRoutesTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListRoutesTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTablePreparer(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTable", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTablePreparer prepares the ListRoutesTable request. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTablePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSender sends the ListRoutesTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSender(req *http.Request) (future ExpressRouteCrossConnectionsListRoutesTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListRoutesTableSummary gets the route table summary associated with the express route cross connection in a resource -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummary(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (result ExpressRouteCrossConnectionsListRoutesTableSummaryFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListRoutesTableSummary") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTableSummaryPreparer(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTableSummary", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSummarySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTableSummary", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTableSummaryPreparer prepares the ListRoutesTableSummary request. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummaryPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTablesSummary/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSummarySender sends the ListRoutesTableSummary request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummarySender(req *http.Request) (future ExpressRouteCrossConnectionsListRoutesTableSummaryFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableSummaryResponder handles the response to the ListRoutesTableSummary request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result ExpressRouteCrossConnectionsRoutesTableSummaryListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates an express route cross connection tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the cross connection. -// crossConnectionParameters - parameters supplied to update express route cross connection tags. -func (client ExpressRouteCrossConnectionsClient) UpdateTags(ctx context.Context, resourceGroupName string, crossConnectionName string, crossConnectionParameters TagsObject) (result ExpressRouteCrossConnectionsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, crossConnectionName, crossConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ExpressRouteCrossConnectionsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, crossConnectionParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}", pathParameters), - autorest.WithJSON(crossConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) UpdateTagsSender(req *http.Request) (future ExpressRouteCrossConnectionsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRouteCrossConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutegateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutegateways.go deleted file mode 100644 index 69131989e..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutegateways.go +++ /dev/null @@ -1,423 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteGatewaysClient is the network Client -type ExpressRouteGatewaysClient struct { - BaseClient -} - -// NewExpressRouteGatewaysClient creates an instance of the ExpressRouteGatewaysClient client. -func NewExpressRouteGatewaysClient(subscriptionID string) ExpressRouteGatewaysClient { - return NewExpressRouteGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteGatewaysClientWithBaseURI creates an instance of the ExpressRouteGatewaysClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRouteGatewaysClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteGatewaysClient { - return ExpressRouteGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a ExpressRoute gateway in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// putExpressRouteGatewayParameters - parameters required in an ExpressRoute gateway PUT operation. -func (client ExpressRouteGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, putExpressRouteGatewayParameters ExpressRouteGateway) (result ExpressRouteGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: putExpressRouteGatewayParameters, - Constraints: []validation.Constraint{{Target: "putExpressRouteGatewayParameters.ExpressRouteGatewayProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "putExpressRouteGatewayParameters.ExpressRouteGatewayProperties.VirtualHub", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRouteGatewayName, putExpressRouteGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, putExpressRouteGatewayParameters ExpressRouteGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - putExpressRouteGatewayParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}", pathParameters), - autorest.WithJSON(putExpressRouteGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified ExpressRoute gateway in a resource group. An ExpressRoute gateway resource can only be -// deleted when there are no connection subresources. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -func (client ExpressRouteGatewaysClient) Delete(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (result ExpressRouteGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, expressRouteGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) DeleteSender(req *http.Request) (future ExpressRouteGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get fetches the details of a ExpressRoute gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -func (client ExpressRouteGatewaysClient) Get(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (result ExpressRouteGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRouteGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) GetResponder(resp *http.Response) (result ExpressRouteGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup lists ExpressRoute gateways in a given resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRouteGatewaysClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ExpressRouteGatewayList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ExpressRouteGatewaysClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) ListByResourceGroupResponder(resp *http.Response) (result ExpressRouteGatewayList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListBySubscription lists ExpressRoute gateways under a given subscription. -func (client ExpressRouteGatewaysClient) ListBySubscription(ctx context.Context) (result ExpressRouteGatewayList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListBySubscription", resp, "Failure responding to request") - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client ExpressRouteGatewaysClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) ListBySubscriptionResponder(resp *http.Response) (result ExpressRouteGatewayList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutelinks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutelinks.go deleted file mode 100644 index 1c4d6060c..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressroutelinks.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteLinksClient is the network Client -type ExpressRouteLinksClient struct { - BaseClient -} - -// NewExpressRouteLinksClient creates an instance of the ExpressRouteLinksClient client. -func NewExpressRouteLinksClient(subscriptionID string) ExpressRouteLinksClient { - return NewExpressRouteLinksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteLinksClientWithBaseURI creates an instance of the ExpressRouteLinksClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRouteLinksClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteLinksClient { - return ExpressRouteLinksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves the specified ExpressRouteLink resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -// linkName - the name of the ExpressRouteLink resource. -func (client ExpressRouteLinksClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string, linkName string) (result ExpressRouteLink, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinksClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRoutePortName, linkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteLinksClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, linkName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "linkName": autorest.Encode("path", linkName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links/{linkName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteLinksClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteLinksClient) GetResponder(resp *http.Response) (result ExpressRouteLink, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -func (client ExpressRouteLinksClient) List(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRouteLinkListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinksClient.List") - defer func() { - sc := -1 - if result.erllr.Response.Response != nil { - sc = result.erllr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, expressRoutePortName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erllr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "List", resp, "Failure sending request") - return - } - - result.erllr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "List", resp, "Failure responding to request") - return - } - if result.erllr.hasNextLink() && result.erllr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteLinksClient) ListPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteLinksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteLinksClient) ListResponder(resp *http.Response) (result ExpressRouteLinkListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteLinksClient) listNextResults(ctx context.Context, lastResults ExpressRouteLinkListResult) (result ExpressRouteLinkListResult, err error) { - req, err := lastResults.expressRouteLinkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteLinksClient) ListComplete(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRouteLinkListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinksClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, expressRoutePortName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteports.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteports.go deleted file mode 100644 index 08967764b..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteports.go +++ /dev/null @@ -1,580 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRoutePortsClient is the network Client -type ExpressRoutePortsClient struct { - BaseClient -} - -// NewExpressRoutePortsClient creates an instance of the ExpressRoutePortsClient client. -func NewExpressRoutePortsClient(subscriptionID string) ExpressRoutePortsClient { - return NewExpressRoutePortsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRoutePortsClientWithBaseURI creates an instance of the ExpressRoutePortsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRoutePortsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRoutePortsClient { - return ExpressRoutePortsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -// parameters - parameters supplied to the create ExpressRoutePort operation. -func (client ExpressRoutePortsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort) (result ExpressRoutePortsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRoutePortName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRoutePortsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRoutePortsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRoutePort, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -func (client ExpressRoutePortsClient) Delete(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePortsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, expressRoutePortName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRoutePortsClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) DeleteSender(req *http.Request) (future ExpressRoutePortsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the requested ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of ExpressRoutePort. -func (client ExpressRoutePortsClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePort, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRoutePortName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRoutePortsClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) GetResponder(resp *http.Response) (result ExpressRoutePort, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all the ExpressRoutePort resources in the specified subscription -func (client ExpressRoutePortsClient) List(ctx context.Context) (result ExpressRoutePortListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.List") - defer func() { - sc := -1 - if result.erplr.Response.Response != nil { - sc = result.erplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", resp, "Failure sending request") - return - } - - result.erplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", resp, "Failure responding to request") - return - } - if result.erplr.hasNextLink() && result.erplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRoutePortsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePorts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) ListResponder(resp *http.Response) (result ExpressRoutePortListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRoutePortsClient) listNextResults(ctx context.Context, lastResults ExpressRoutePortListResult) (result ExpressRoutePortListResult, err error) { - req, err := lastResults.expressRoutePortListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRoutePortsClient) ListComplete(ctx context.Context) (result ExpressRoutePortListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup list all the ExpressRoutePort resources in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRoutePortsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ExpressRoutePortListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.erplr.Response.Response != nil { - sc = result.erplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.erplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.erplr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.erplr.hasNextLink() && result.erplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ExpressRoutePortsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) ListByResourceGroupResponder(resp *http.Response) (result ExpressRoutePortListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ExpressRoutePortsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ExpressRoutePortListResult) (result ExpressRoutePortListResult, err error) { - req, err := lastResults.expressRoutePortListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRoutePortsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ExpressRoutePortListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags update ExpressRoutePort tags -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -// parameters - parameters supplied to update ExpressRoutePort resource tags. -func (client ExpressRoutePortsClient) UpdateTags(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject) (result ExpressRoutePortsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, expressRoutePortName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ExpressRoutePortsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) UpdateTagsSender(req *http.Request) (future ExpressRoutePortsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRoutePort, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteportslocations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteportslocations.go deleted file mode 100644 index 4a11798ad..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteportslocations.go +++ /dev/null @@ -1,221 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRoutePortsLocationsClient is the network Client -type ExpressRoutePortsLocationsClient struct { - BaseClient -} - -// NewExpressRoutePortsLocationsClient creates an instance of the ExpressRoutePortsLocationsClient client. -func NewExpressRoutePortsLocationsClient(subscriptionID string) ExpressRoutePortsLocationsClient { - return NewExpressRoutePortsLocationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRoutePortsLocationsClientWithBaseURI creates an instance of the ExpressRoutePortsLocationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewExpressRoutePortsLocationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRoutePortsLocationsClient { - return ExpressRoutePortsLocationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves a single ExpressRoutePort peering location, including the list of available bandwidths available at -// said peering location. -// Parameters: -// locationName - name of the requested ExpressRoutePort peering location. -func (client ExpressRoutePortsLocationsClient) Get(ctx context.Context, locationName string) (result ExpressRoutePortsLocation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, locationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRoutePortsLocationsClient) GetPreparer(ctx context.Context, locationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "locationName": autorest.Encode("path", locationName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations/{locationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsLocationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsLocationsClient) GetResponder(resp *http.Response) (result ExpressRoutePortsLocation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves all ExpressRoutePort peering locations. Does not return available bandwidths for each location. -// Available bandwidths can only be obtained when retrieving a specific peering location. -func (client ExpressRoutePortsLocationsClient) List(ctx context.Context) (result ExpressRoutePortsLocationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.List") - defer func() { - sc := -1 - if result.erpllr.Response.Response != nil { - sc = result.erpllr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erpllr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", resp, "Failure sending request") - return - } - - result.erpllr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", resp, "Failure responding to request") - return - } - if result.erpllr.hasNextLink() && result.erpllr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRoutePortsLocationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsLocationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsLocationsClient) ListResponder(resp *http.Response) (result ExpressRoutePortsLocationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRoutePortsLocationsClient) listNextResults(ctx context.Context, lastResults ExpressRoutePortsLocationListResult) (result ExpressRoutePortsLocationListResult, err error) { - req, err := lastResults.expressRoutePortsLocationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRoutePortsLocationsClient) ListComplete(ctx context.Context) (result ExpressRoutePortsLocationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteserviceproviders.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteserviceproviders.go deleted file mode 100644 index 48de50145..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/expressrouteserviceproviders.go +++ /dev/null @@ -1,145 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteServiceProvidersClient is the network Client -type ExpressRouteServiceProvidersClient struct { - BaseClient -} - -// NewExpressRouteServiceProvidersClient creates an instance of the ExpressRouteServiceProvidersClient client. -func NewExpressRouteServiceProvidersClient(subscriptionID string) ExpressRouteServiceProvidersClient { - return NewExpressRouteServiceProvidersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteServiceProvidersClientWithBaseURI creates an instance of the ExpressRouteServiceProvidersClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewExpressRouteServiceProvidersClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteServiceProvidersClient { - return ExpressRouteServiceProvidersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all the available express route service providers. -func (client ExpressRouteServiceProvidersClient) List(ctx context.Context) (result ExpressRouteServiceProviderListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProvidersClient.List") - defer func() { - sc := -1 - if result.ersplr.Response.Response != nil { - sc = result.ersplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ersplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request") - return - } - - result.ersplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure responding to request") - return - } - if result.ersplr.hasNextLink() && result.ersplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteServiceProvidersClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteServiceProvidersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteServiceProvidersClient) ListResponder(resp *http.Response) (result ExpressRouteServiceProviderListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ExpressRouteServiceProvidersClient) listNextResults(ctx context.Context, lastResults ExpressRouteServiceProviderListResult) (result ExpressRouteServiceProviderListResult, err error) { - req, err := lastResults.expressRouteServiceProviderListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteServiceProvidersClient) ListComplete(ctx context.Context) (result ExpressRouteServiceProviderListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProvidersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/hubvirtualnetworkconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/hubvirtualnetworkconnections.go deleted file mode 100644 index 7369edba5..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/hubvirtualnetworkconnections.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// HubVirtualNetworkConnectionsClient is the network Client -type HubVirtualNetworkConnectionsClient struct { - BaseClient -} - -// NewHubVirtualNetworkConnectionsClient creates an instance of the HubVirtualNetworkConnectionsClient client. -func NewHubVirtualNetworkConnectionsClient(subscriptionID string) HubVirtualNetworkConnectionsClient { - return NewHubVirtualNetworkConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewHubVirtualNetworkConnectionsClientWithBaseURI creates an instance of the HubVirtualNetworkConnectionsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewHubVirtualNetworkConnectionsClientWithBaseURI(baseURI string, subscriptionID string) HubVirtualNetworkConnectionsClient { - return HubVirtualNetworkConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves the details of a HubVirtualNetworkConnection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// connectionName - the name of the vpn connection. -func (client HubVirtualNetworkConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result HubVirtualNetworkConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client HubVirtualNetworkConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client HubVirtualNetworkConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client HubVirtualNetworkConnectionsClient) GetResponder(resp *http.Response) (result HubVirtualNetworkConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves the details of all HubVirtualNetworkConnections. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client HubVirtualNetworkConnectionsClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List") - defer func() { - sc := -1 - if result.lhvncr.Response.Response != nil { - sc = result.lhvncr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lhvncr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.lhvncr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.lhvncr.hasNextLink() && result.lhvncr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client HubVirtualNetworkConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client HubVirtualNetworkConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client HubVirtualNetworkConnectionsClient) ListResponder(resp *http.Response) (result ListHubVirtualNetworkConnectionsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client HubVirtualNetworkConnectionsClient) listNextResults(ctx context.Context, lastResults ListHubVirtualNetworkConnectionsResult) (result ListHubVirtualNetworkConnectionsResult, err error) { - req, err := lastResults.listHubVirtualNetworkConnectionsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client HubVirtualNetworkConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/inboundnatrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/inboundnatrules.go deleted file mode 100644 index decf6e4a8..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/inboundnatrules.go +++ /dev/null @@ -1,415 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InboundNatRulesClient is the network Client -type InboundNatRulesClient struct { - BaseClient -} - -// NewInboundNatRulesClient creates an instance of the InboundNatRulesClient client. -func NewInboundNatRulesClient(subscriptionID string) InboundNatRulesClient { - return NewInboundNatRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInboundNatRulesClientWithBaseURI creates an instance of the InboundNatRulesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewInboundNatRulesClientWithBaseURI(baseURI string, subscriptionID string) InboundNatRulesClient { - return InboundNatRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a load balancer inbound nat rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// inboundNatRuleName - the name of the inbound nat rule. -// inboundNatRuleParameters - parameters supplied to the create or update inbound nat rule operation. -func (client InboundNatRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, inboundNatRuleParameters InboundNatRule) (result InboundNatRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: inboundNatRuleParameters, - Constraints: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.InboundNatRulesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InboundNatRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, inboundNatRuleParameters InboundNatRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "inboundNatRuleName": autorest.Encode("path", inboundNatRuleName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}", pathParameters), - autorest.WithJSON(inboundNatRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) CreateOrUpdateSender(req *http.Request) (future InboundNatRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) CreateOrUpdateResponder(resp *http.Response) (result InboundNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified load balancer inbound nat rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// inboundNatRuleName - the name of the inbound nat rule. -func (client InboundNatRulesClient) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string) (result InboundNatRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client InboundNatRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "inboundNatRuleName": autorest.Encode("path", inboundNatRuleName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) DeleteSender(req *http.Request) (future InboundNatRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified load balancer inbound nat rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// inboundNatRuleName - the name of the inbound nat rule. -// expand - expands referenced resources. -func (client InboundNatRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, expand string) (result InboundNatRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InboundNatRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "inboundNatRuleName": autorest.Encode("path", inboundNatRuleName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) GetResponder(resp *http.Response) (result InboundNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the inbound nat rules in a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client InboundNatRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InboundNatRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.List") - defer func() { - sc := -1 - if result.inrlr.Response.Response != nil { - sc = result.inrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.inrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "List", resp, "Failure sending request") - return - } - - result.inrlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "List", resp, "Failure responding to request") - return - } - if result.inrlr.hasNextLink() && result.inrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InboundNatRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) ListResponder(resp *http.Response) (result InboundNatRuleListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client InboundNatRulesClient) listNextResults(ctx context.Context, lastResults InboundNatRuleListResult) (result InboundNatRuleListResult, err error) { - req, err := lastResults.inboundNatRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InboundNatRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InboundNatRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceendpoints.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceendpoints.go deleted file mode 100644 index d813e08e0..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceendpoints.go +++ /dev/null @@ -1,501 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfaceEndpointsClient is the network Client -type InterfaceEndpointsClient struct { - BaseClient -} - -// NewInterfaceEndpointsClient creates an instance of the InterfaceEndpointsClient client. -func NewInterfaceEndpointsClient(subscriptionID string) InterfaceEndpointsClient { - return NewInterfaceEndpointsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfaceEndpointsClientWithBaseURI creates an instance of the InterfaceEndpointsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewInterfaceEndpointsClientWithBaseURI(baseURI string, subscriptionID string) InterfaceEndpointsClient { - return InterfaceEndpointsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an interface endpoint in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// interfaceEndpointName - the name of the interface endpoint. -// parameters - parameters supplied to the create or update interface endpoint operation -func (client InterfaceEndpointsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, interfaceEndpointName string, parameters InterfaceEndpoint) (result InterfaceEndpointsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, interfaceEndpointName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InterfaceEndpointsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, interfaceEndpointName string, parameters InterfaceEndpoint) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "interfaceEndpointName": autorest.Encode("path", interfaceEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceEndpointsClient) CreateOrUpdateSender(req *http.Request) (future InterfaceEndpointsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InterfaceEndpointsClient) CreateOrUpdateResponder(resp *http.Response) (result InterfaceEndpoint, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified interface endpoint. -// Parameters: -// resourceGroupName - the name of the resource group. -// interfaceEndpointName - the name of the interface endpoint. -func (client InterfaceEndpointsClient) Delete(ctx context.Context, resourceGroupName string, interfaceEndpointName string) (result InterfaceEndpointsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, interfaceEndpointName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client InterfaceEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, interfaceEndpointName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "interfaceEndpointName": autorest.Encode("path", interfaceEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceEndpointsClient) DeleteSender(req *http.Request) (future InterfaceEndpointsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client InterfaceEndpointsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified interface endpoint by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// interfaceEndpointName - the name of the interface endpoint. -// expand - expands referenced resources. -func (client InterfaceEndpointsClient) Get(ctx context.Context, resourceGroupName string, interfaceEndpointName string, expand string) (result InterfaceEndpoint, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, interfaceEndpointName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InterfaceEndpointsClient) GetPreparer(ctx context.Context, resourceGroupName string, interfaceEndpointName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "interfaceEndpointName": autorest.Encode("path", interfaceEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceEndpointsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InterfaceEndpointsClient) GetResponder(resp *http.Response) (result InterfaceEndpoint, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all interface endpoints in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client InterfaceEndpointsClient) List(ctx context.Context, resourceGroupName string) (result InterfaceEndpointListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointsClient.List") - defer func() { - sc := -1 - if result.ielr.Response.Response != nil { - sc = result.ielr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ielr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "List", resp, "Failure sending request") - return - } - - result.ielr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "List", resp, "Failure responding to request") - return - } - if result.ielr.hasNextLink() && result.ielr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfaceEndpointsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceEndpointsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfaceEndpointsClient) ListResponder(resp *http.Response) (result InterfaceEndpointListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client InterfaceEndpointsClient) listNextResults(ctx context.Context, lastResults InterfaceEndpointListResult) (result InterfaceEndpointListResult, err error) { - req, err := lastResults.interfaceEndpointListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceEndpointsClient) ListComplete(ctx context.Context, resourceGroupName string) (result InterfaceEndpointListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListBySubscription gets all interface endpoints in a subscription. -func (client InterfaceEndpointsClient) ListBySubscription(ctx context.Context) (result InterfaceEndpointListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointsClient.ListBySubscription") - defer func() { - sc := -1 - if result.ielr.Response.Response != nil { - sc = result.ielr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.ielr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.ielr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.ielr.hasNextLink() && result.ielr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client InterfaceEndpointsClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/interfaceEndpoints", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceEndpointsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client InterfaceEndpointsClient) ListBySubscriptionResponder(resp *http.Response) (result InterfaceEndpointListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client InterfaceEndpointsClient) listBySubscriptionNextResults(ctx context.Context, lastResults InterfaceEndpointListResult) (result InterfaceEndpointListResult, err error) { - req, err := lastResults.interfaceEndpointListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceEndpointsClient) ListBySubscriptionComplete(ctx context.Context) (result InterfaceEndpointListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointsClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceipconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceipconfigurations.go deleted file mode 100644 index f3247fbd1..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceipconfigurations.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfaceIPConfigurationsClient is the network Client -type InterfaceIPConfigurationsClient struct { - BaseClient -} - -// NewInterfaceIPConfigurationsClient creates an instance of the InterfaceIPConfigurationsClient client. -func NewInterfaceIPConfigurationsClient(subscriptionID string) InterfaceIPConfigurationsClient { - return NewInterfaceIPConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfaceIPConfigurationsClientWithBaseURI creates an instance of the InterfaceIPConfigurationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewInterfaceIPConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) InterfaceIPConfigurationsClient { - return InterfaceIPConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified network interface ip configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// IPConfigurationName - the name of the ip configuration name. -func (client InterfaceIPConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, IPConfigurationName string) (result InterfaceIPConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkInterfaceName, IPConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InterfaceIPConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, IPConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceIPConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InterfaceIPConfigurationsClient) GetResponder(resp *http.Response) (result InterfaceIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get all ip configurations in a network interface -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfaceIPConfigurationsClient) List(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceIPConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.iiclr.Response.Response != nil { - sc = result.iiclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.iiclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.iiclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.iiclr.hasNextLink() && result.iiclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfaceIPConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceIPConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfaceIPConfigurationsClient) ListResponder(resp *http.Response) (result InterfaceIPConfigurationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client InterfaceIPConfigurationsClient) listNextResults(ctx context.Context, lastResults InterfaceIPConfigurationListResult) (result InterfaceIPConfigurationListResult, err error) { - req, err := lastResults.interfaceIPConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceIPConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceIPConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkInterfaceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceloadbalancers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceloadbalancers.go deleted file mode 100644 index 77302fafb..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfaceloadbalancers.go +++ /dev/null @@ -1,150 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfaceLoadBalancersClient is the network Client -type InterfaceLoadBalancersClient struct { - BaseClient -} - -// NewInterfaceLoadBalancersClient creates an instance of the InterfaceLoadBalancersClient client. -func NewInterfaceLoadBalancersClient(subscriptionID string) InterfaceLoadBalancersClient { - return NewInterfaceLoadBalancersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfaceLoadBalancersClientWithBaseURI creates an instance of the InterfaceLoadBalancersClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewInterfaceLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) InterfaceLoadBalancersClient { - return InterfaceLoadBalancersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list all load balancers in a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfaceLoadBalancersClient) List(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceLoadBalancerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancersClient.List") - defer func() { - sc := -1 - if result.ilblr.Response.Response != nil { - sc = result.ilblr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ilblr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "List", resp, "Failure sending request") - return - } - - result.ilblr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "List", resp, "Failure responding to request") - return - } - if result.ilblr.hasNextLink() && result.ilblr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfaceLoadBalancersClient) ListPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/loadBalancers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceLoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfaceLoadBalancersClient) ListResponder(resp *http.Response) (result InterfaceLoadBalancerListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client InterfaceLoadBalancersClient) listNextResults(ctx context.Context, lastResults InterfaceLoadBalancerListResult) (result InterfaceLoadBalancerListResult, err error) { - req, err := lastResults.interfaceLoadBalancerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceLoadBalancersClient) ListComplete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceLoadBalancerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkInterfaceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfacesgroup.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfacesgroup.go deleted file mode 100644 index 367637ff1..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfacesgroup.go +++ /dev/null @@ -1,1277 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfacesClient is the network Client -type InterfacesClient struct { - BaseClient -} - -// NewInterfacesClient creates an instance of the InterfacesClient client. -func NewInterfacesClient(subscriptionID string) InterfacesClient { - return NewInterfacesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfacesClientWithBaseURI creates an instance of the InterfacesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewInterfacesClientWithBaseURI(baseURI string, subscriptionID string) InterfacesClient { - return InterfacesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// parameters - parameters supplied to the create or update network interface operation. -func (client InterfacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters Interface) (result InterfacesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkInterfaceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InterfacesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters Interface) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) CreateOrUpdateSender(req *http.Request) (future InterfacesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InterfacesClient) CreateOrUpdateResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfacesClient) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfacesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client InterfacesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) DeleteSender(req *http.Request) (future InterfacesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client InterfacesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// expand - expands referenced resources. -func (client InterfacesClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (result Interface, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkInterfaceName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InterfacesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetEffectiveRouteTable gets all route tables applied to a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfacesClient) GetEffectiveRouteTable(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfacesGetEffectiveRouteTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.GetEffectiveRouteTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetEffectiveRouteTablePreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", nil, "Failure preparing request") - return - } - - result, err = client.GetEffectiveRouteTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", result.Response(), "Failure sending request") - return - } - - return -} - -// GetEffectiveRouteTablePreparer prepares the GetEffectiveRouteTable request. -func (client InterfacesClient) GetEffectiveRouteTablePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/effectiveRouteTable", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetEffectiveRouteTableSender sends the GetEffectiveRouteTable request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetEffectiveRouteTableSender(req *http.Request) (future InterfacesGetEffectiveRouteTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetEffectiveRouteTableResponder handles the response to the GetEffectiveRouteTable request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetEffectiveRouteTableResponder(resp *http.Response) (result EffectiveRouteListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVirtualMachineScaleSetIPConfiguration get the specified network interface ip configuration in a virtual machine -// scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// IPConfigurationName - the name of the ip configuration. -// expand - expands referenced resources. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfiguration(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, expand string) (result InterfaceIPConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.GetVirtualMachineScaleSetIPConfiguration") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVirtualMachineScaleSetIPConfigurationPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetIPConfiguration", nil, "Failure preparing request") - return - } - - resp, err := client.GetVirtualMachineScaleSetIPConfigurationSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetIPConfiguration", resp, "Failure sending request") - return - } - - result, err = client.GetVirtualMachineScaleSetIPConfigurationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetIPConfiguration", resp, "Failure responding to request") - return - } - - return -} - -// GetVirtualMachineScaleSetIPConfigurationPreparer prepares the GetVirtualMachineScaleSetIPConfiguration request. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfigurationPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVirtualMachineScaleSetIPConfigurationSender sends the GetVirtualMachineScaleSetIPConfiguration request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfigurationSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetVirtualMachineScaleSetIPConfigurationResponder handles the response to the GetVirtualMachineScaleSetIPConfiguration request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfigurationResponder(resp *http.Response) (result InterfaceIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVirtualMachineScaleSetNetworkInterface get the specified network interface in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// expand - expands referenced resources. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result Interface, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.GetVirtualMachineScaleSetNetworkInterface") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVirtualMachineScaleSetNetworkInterfacePreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", nil, "Failure preparing request") - return - } - - resp, err := client.GetVirtualMachineScaleSetNetworkInterfaceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure sending request") - return - } - - result, err = client.GetVirtualMachineScaleSetNetworkInterfaceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure responding to request") - return - } - - return -} - -// GetVirtualMachineScaleSetNetworkInterfacePreparer prepares the GetVirtualMachineScaleSetNetworkInterface request. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfacePreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVirtualMachineScaleSetNetworkInterfaceSender sends the GetVirtualMachineScaleSetNetworkInterface request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetVirtualMachineScaleSetNetworkInterfaceResponder handles the response to the GetVirtualMachineScaleSetNetworkInterface request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all network interfaces in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client InterfacesClient) List(ctx context.Context, resourceGroupName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.List") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfacesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListComplete(ctx context.Context, resourceGroupName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all network interfaces in a subscription. -func (client InterfacesClient) ListAll(ctx context.Context) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListAll") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client InterfacesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListAllResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listAllNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListAllComplete(ctx context.Context) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListEffectiveNetworkSecurityGroups gets all network security groups applied to a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroups(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfacesListEffectiveNetworkSecurityGroupsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListEffectiveNetworkSecurityGroups") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListEffectiveNetworkSecurityGroupsPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", nil, "Failure preparing request") - return - } - - result, err = client.ListEffectiveNetworkSecurityGroupsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", result.Response(), "Failure sending request") - return - } - - return -} - -// ListEffectiveNetworkSecurityGroupsPreparer prepares the ListEffectiveNetworkSecurityGroups request. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/effectiveNetworkSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListEffectiveNetworkSecurityGroupsSender sends the ListEffectiveNetworkSecurityGroups request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsSender(req *http.Request) (future InterfacesListEffectiveNetworkSecurityGroupsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListEffectiveNetworkSecurityGroupsResponder handles the response to the ListEffectiveNetworkSecurityGroups request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsResponder(resp *http.Response) (result EffectiveNetworkSecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListVirtualMachineScaleSetIPConfigurations get the specified network interface ip configuration in a virtual machine -// scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// expand - expands referenced resources. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurations(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result InterfaceIPConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetIPConfigurations") - defer func() { - sc := -1 - if result.iiclr.Response.Response != nil { - sc = result.iiclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetIPConfigurationsNextResults - req, err := client.ListVirtualMachineScaleSetIPConfigurationsPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetIPConfigurations", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetIPConfigurationsSender(req) - if err != nil { - result.iiclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetIPConfigurations", resp, "Failure sending request") - return - } - - result.iiclr, err = client.ListVirtualMachineScaleSetIPConfigurationsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetIPConfigurations", resp, "Failure responding to request") - return - } - if result.iiclr.hasNextLink() && result.iiclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetIPConfigurationsPreparer prepares the ListVirtualMachineScaleSetIPConfigurations request. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetIPConfigurationsSender sends the ListVirtualMachineScaleSetIPConfigurations request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetIPConfigurationsResponder handles the response to the ListVirtualMachineScaleSetIPConfigurations request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsResponder(resp *http.Response) (result InterfaceIPConfigurationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetIPConfigurationsNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listVirtualMachineScaleSetIPConfigurationsNextResults(ctx context.Context, lastResults InterfaceIPConfigurationListResult) (result InterfaceIPConfigurationListResult, err error) { - req, err := lastResults.interfaceIPConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetIPConfigurationsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetIPConfigurationsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetIPConfigurationsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetIPConfigurationsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetIPConfigurationsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetIPConfigurationsComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result InterfaceIPConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetIPConfigurations") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetIPConfigurations(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - return -} - -// ListVirtualMachineScaleSetNetworkInterfaces gets all network interfaces in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfaces(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetNetworkInterfaces") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetNetworkInterfacesNextResults - req, err := client.ListVirtualMachineScaleSetNetworkInterfacesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetNetworkInterfacesPreparer prepares the ListVirtualMachineScaleSetNetworkInterfaces request. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetNetworkInterfacesSender sends the ListVirtualMachineScaleSetNetworkInterfaces request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetNetworkInterfaces request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listVirtualMachineScaleSetNetworkInterfacesNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetNetworkInterfacesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetNetworkInterfacesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetNetworkInterfacesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetNetworkInterfacesComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetNetworkInterfaces") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetNetworkInterfaces(ctx, resourceGroupName, virtualMachineScaleSetName) - return -} - -// ListVirtualMachineScaleSetVMNetworkInterfaces gets information about all network interfaces in a virtual machine in -// a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfaces(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetVMNetworkInterfaces") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetVMNetworkInterfacesNextResults - req, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesPreparer prepares the ListVirtualMachineScaleSetVMNetworkInterfaces request. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesSender sends the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetVMNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listVirtualMachineScaleSetVMNetworkInterfacesNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetVMNetworkInterfacesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetVMNetworkInterfacesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetVMNetworkInterfacesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetVMNetworkInterfaces") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetVMNetworkInterfaces(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex) - return -} - -// UpdateTags updates a network interface tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// parameters - parameters supplied to update network interface tags. -func (client InterfacesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters TagsObject) (result InterfacesUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkInterfaceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client InterfacesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) UpdateTagsSender(req *http.Request) (future InterfacesUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client InterfacesClient) UpdateTagsResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfacetapconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfacetapconfigurations.go deleted file mode 100644 index 9a0999f12..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/interfacetapconfigurations.go +++ /dev/null @@ -1,429 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfaceTapConfigurationsClient is the network Client -type InterfaceTapConfigurationsClient struct { - BaseClient -} - -// NewInterfaceTapConfigurationsClient creates an instance of the InterfaceTapConfigurationsClient client. -func NewInterfaceTapConfigurationsClient(subscriptionID string) InterfaceTapConfigurationsClient { - return NewInterfaceTapConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfaceTapConfigurationsClientWithBaseURI creates an instance of the InterfaceTapConfigurationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewInterfaceTapConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) InterfaceTapConfigurationsClient { - return InterfaceTapConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Tap configuration in the specified NetworkInterface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// tapConfigurationName - the name of the tap configuration. -// tapConfigurationParameters - parameters supplied to the create or update tap configuration operation. -func (client InterfaceTapConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration) (result InterfaceTapConfigurationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: tapConfigurationParameters, - Constraints: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - }}, - }}, - }}, - }}, - {Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - }}, - }}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.InterfaceTapConfigurationsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName, tapConfigurationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InterfaceTapConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapConfigurationName": autorest.Encode("path", tapConfigurationName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - tapConfigurationParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters), - autorest.WithJSON(tapConfigurationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) CreateOrUpdateSender(req *http.Request) (future InterfaceTapConfigurationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result InterfaceTapConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified tap configuration from the NetworkInterface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// tapConfigurationName - the name of the tap configuration. -func (client InterfaceTapConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (result InterfaceTapConfigurationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client InterfaceTapConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapConfigurationName": autorest.Encode("path", tapConfigurationName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) DeleteSender(req *http.Request) (future InterfaceTapConfigurationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the specified tap configuration on a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// tapConfigurationName - the name of the tap configuration. -func (client InterfaceTapConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (result InterfaceTapConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InterfaceTapConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapConfigurationName": autorest.Encode("path", tapConfigurationName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) GetResponder(resp *http.Response) (result InterfaceTapConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get all Tap configurations in a network interface -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfaceTapConfigurationsClient) List(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceTapConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.List") - defer func() { - sc := -1 - if result.itclr.Response.Response != nil { - sc = result.itclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.itclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.itclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.itclr.hasNextLink() && result.itclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfaceTapConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) ListResponder(resp *http.Response) (result InterfaceTapConfigurationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client InterfaceTapConfigurationsClient) listNextResults(ctx context.Context, lastResults InterfaceTapConfigurationListResult) (result InterfaceTapConfigurationListResult, err error) { - req, err := lastResults.interfaceTapConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceTapConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceTapConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkInterfaceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerbackendaddresspools.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerbackendaddresspools.go deleted file mode 100644 index 9c1f5a9b9..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerbackendaddresspools.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerBackendAddressPoolsClient is the network Client -type LoadBalancerBackendAddressPoolsClient struct { - BaseClient -} - -// NewLoadBalancerBackendAddressPoolsClient creates an instance of the LoadBalancerBackendAddressPoolsClient client. -func NewLoadBalancerBackendAddressPoolsClient(subscriptionID string) LoadBalancerBackendAddressPoolsClient { - return NewLoadBalancerBackendAddressPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerBackendAddressPoolsClientWithBaseURI creates an instance of the LoadBalancerBackendAddressPoolsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewLoadBalancerBackendAddressPoolsClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerBackendAddressPoolsClient { - return LoadBalancerBackendAddressPoolsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets load balancer backend address pool. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// backendAddressPoolName - the name of the backend address pool. -func (client LoadBalancerBackendAddressPoolsClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string) (result BackendAddressPool, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, backendAddressPoolName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerBackendAddressPoolsClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "backendAddressPoolName": autorest.Encode("path", backendAddressPoolName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerBackendAddressPoolsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerBackendAddressPoolsClient) GetResponder(resp *http.Response) (result BackendAddressPool, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancer backed address pools. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerBackendAddressPoolsClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerBackendAddressPoolListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.List") - defer func() { - sc := -1 - if result.lbbaplr.Response.Response != nil { - sc = result.lbbaplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lbbaplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "List", resp, "Failure sending request") - return - } - - result.lbbaplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "List", resp, "Failure responding to request") - return - } - if result.lbbaplr.hasNextLink() && result.lbbaplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerBackendAddressPoolsClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerBackendAddressPoolsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerBackendAddressPoolsClient) ListResponder(resp *http.Response) (result LoadBalancerBackendAddressPoolListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LoadBalancerBackendAddressPoolsClient) listNextResults(ctx context.Context, lastResults LoadBalancerBackendAddressPoolListResult) (result LoadBalancerBackendAddressPoolListResult, err error) { - req, err := lastResults.loadBalancerBackendAddressPoolListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerBackendAddressPoolsClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerBackendAddressPoolListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerfrontendipconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerfrontendipconfigurations.go deleted file mode 100644 index 514e14bf2..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerfrontendipconfigurations.go +++ /dev/null @@ -1,229 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerFrontendIPConfigurationsClient is the network Client -type LoadBalancerFrontendIPConfigurationsClient struct { - BaseClient -} - -// NewLoadBalancerFrontendIPConfigurationsClient creates an instance of the LoadBalancerFrontendIPConfigurationsClient -// client. -func NewLoadBalancerFrontendIPConfigurationsClient(subscriptionID string) LoadBalancerFrontendIPConfigurationsClient { - return NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI creates an instance of the -// LoadBalancerFrontendIPConfigurationsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerFrontendIPConfigurationsClient { - return LoadBalancerFrontendIPConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets load balancer frontend IP configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// frontendIPConfigurationName - the name of the frontend IP configuration. -func (client LoadBalancerFrontendIPConfigurationsClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string) (result FrontendIPConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, frontendIPConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerFrontendIPConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "frontendIPConfigurationName": autorest.Encode("path", frontendIPConfigurationName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations/{frontendIPConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerFrontendIPConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerFrontendIPConfigurationsClient) GetResponder(resp *http.Response) (result FrontendIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancer frontend IP configurations. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerFrontendIPConfigurationsClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerFrontendIPConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.lbficlr.Response.Response != nil { - sc = result.lbficlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lbficlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.lbficlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.lbficlr.hasNextLink() && result.lbficlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerFrontendIPConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerFrontendIPConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerFrontendIPConfigurationsClient) ListResponder(resp *http.Response) (result LoadBalancerFrontendIPConfigurationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LoadBalancerFrontendIPConfigurationsClient) listNextResults(ctx context.Context, lastResults LoadBalancerFrontendIPConfigurationListResult) (result LoadBalancerFrontendIPConfigurationListResult, err error) { - req, err := lastResults.loadBalancerFrontendIPConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerFrontendIPConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerFrontendIPConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerloadbalancingrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerloadbalancingrules.go deleted file mode 100644 index d74adc96d..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerloadbalancingrules.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerLoadBalancingRulesClient is the network Client -type LoadBalancerLoadBalancingRulesClient struct { - BaseClient -} - -// NewLoadBalancerLoadBalancingRulesClient creates an instance of the LoadBalancerLoadBalancingRulesClient client. -func NewLoadBalancerLoadBalancingRulesClient(subscriptionID string) LoadBalancerLoadBalancingRulesClient { - return NewLoadBalancerLoadBalancingRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerLoadBalancingRulesClientWithBaseURI creates an instance of the LoadBalancerLoadBalancingRulesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewLoadBalancerLoadBalancingRulesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerLoadBalancingRulesClient { - return LoadBalancerLoadBalancingRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified load balancer load balancing rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// loadBalancingRuleName - the name of the load balancing rule. -func (client LoadBalancerLoadBalancingRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (result LoadBalancingRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, loadBalancingRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerLoadBalancingRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "loadBalancingRuleName": autorest.Encode("path", loadBalancingRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerLoadBalancingRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerLoadBalancingRulesClient) GetResponder(resp *http.Response) (result LoadBalancingRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancing rules in a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerLoadBalancingRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List") - defer func() { - sc := -1 - if result.lblbrlr.Response.Response != nil { - sc = result.lblbrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lblbrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure sending request") - return - } - - result.lblbrlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure responding to request") - return - } - if result.lblbrlr.hasNextLink() && result.lblbrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerLoadBalancingRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerLoadBalancingRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerLoadBalancingRulesClient) ListResponder(resp *http.Response) (result LoadBalancerLoadBalancingRuleListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LoadBalancerLoadBalancingRulesClient) listNextResults(ctx context.Context, lastResults LoadBalancerLoadBalancingRuleListResult) (result LoadBalancerLoadBalancingRuleListResult, err error) { - req, err := lastResults.loadBalancerLoadBalancingRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerLoadBalancingRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancernetworkinterfaces.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancernetworkinterfaces.go deleted file mode 100644 index 471399113..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancernetworkinterfaces.go +++ /dev/null @@ -1,150 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerNetworkInterfacesClient is the network Client -type LoadBalancerNetworkInterfacesClient struct { - BaseClient -} - -// NewLoadBalancerNetworkInterfacesClient creates an instance of the LoadBalancerNetworkInterfacesClient client. -func NewLoadBalancerNetworkInterfacesClient(subscriptionID string) LoadBalancerNetworkInterfacesClient { - return NewLoadBalancerNetworkInterfacesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerNetworkInterfacesClientWithBaseURI creates an instance of the LoadBalancerNetworkInterfacesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewLoadBalancerNetworkInterfacesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerNetworkInterfacesClient { - return LoadBalancerNetworkInterfacesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets associated load balancer network interfaces. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerNetworkInterfacesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerNetworkInterfacesClient.List") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "List", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "List", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerNetworkInterfacesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerNetworkInterfacesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerNetworkInterfacesClient) ListResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LoadBalancerNetworkInterfacesClient) listNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerNetworkInterfacesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerNetworkInterfacesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalanceroutboundrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalanceroutboundrules.go deleted file mode 100644 index acfbed6ff..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalanceroutboundrules.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerOutboundRulesClient is the network Client -type LoadBalancerOutboundRulesClient struct { - BaseClient -} - -// NewLoadBalancerOutboundRulesClient creates an instance of the LoadBalancerOutboundRulesClient client. -func NewLoadBalancerOutboundRulesClient(subscriptionID string) LoadBalancerOutboundRulesClient { - return NewLoadBalancerOutboundRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerOutboundRulesClientWithBaseURI creates an instance of the LoadBalancerOutboundRulesClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewLoadBalancerOutboundRulesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerOutboundRulesClient { - return LoadBalancerOutboundRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified load balancer outbound rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// outboundRuleName - the name of the outbound rule. -func (client LoadBalancerOutboundRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, outboundRuleName string) (result OutboundRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, outboundRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerOutboundRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, outboundRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "outboundRuleName": autorest.Encode("path", outboundRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/outboundRules/{outboundRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerOutboundRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerOutboundRulesClient) GetResponder(resp *http.Response) (result OutboundRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the outbound rules in a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerOutboundRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerOutboundRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRulesClient.List") - defer func() { - sc := -1 - if result.lborlr.Response.Response != nil { - sc = result.lborlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lborlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "List", resp, "Failure sending request") - return - } - - result.lborlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "List", resp, "Failure responding to request") - return - } - if result.lborlr.hasNextLink() && result.lborlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerOutboundRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/outboundRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerOutboundRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerOutboundRulesClient) ListResponder(resp *http.Response) (result LoadBalancerOutboundRuleListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LoadBalancerOutboundRulesClient) listNextResults(ctx context.Context, lastResults LoadBalancerOutboundRuleListResult) (result LoadBalancerOutboundRuleListResult, err error) { - req, err := lastResults.loadBalancerOutboundRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerOutboundRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerOutboundRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerprobes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerprobes.go deleted file mode 100644 index bcfce8e84..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancerprobes.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerProbesClient is the network Client -type LoadBalancerProbesClient struct { - BaseClient -} - -// NewLoadBalancerProbesClient creates an instance of the LoadBalancerProbesClient client. -func NewLoadBalancerProbesClient(subscriptionID string) LoadBalancerProbesClient { - return NewLoadBalancerProbesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerProbesClientWithBaseURI creates an instance of the LoadBalancerProbesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewLoadBalancerProbesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerProbesClient { - return LoadBalancerProbesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets load balancer probe. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// probeName - the name of the probe. -func (client LoadBalancerProbesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, probeName string) (result Probe, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, probeName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerProbesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, probeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "probeName": autorest.Encode("path", probeName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerProbesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerProbesClient) GetResponder(resp *http.Response) (result Probe, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancer probes. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerProbesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerProbeListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbesClient.List") - defer func() { - sc := -1 - if result.lbplr.Response.Response != nil { - sc = result.lbplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lbplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "List", resp, "Failure sending request") - return - } - - result.lbplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "List", resp, "Failure responding to request") - return - } - if result.lbplr.hasNextLink() && result.lbplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerProbesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerProbesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerProbesClient) ListResponder(resp *http.Response) (result LoadBalancerProbeListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LoadBalancerProbesClient) listNextResults(ctx context.Context, lastResults LoadBalancerProbeListResult) (result LoadBalancerProbeListResult, err error) { - req, err := lastResults.loadBalancerProbeListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerProbesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerProbeListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancers.go deleted file mode 100644 index 8d35f5d81..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/loadbalancers.go +++ /dev/null @@ -1,582 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancersClient is the network Client -type LoadBalancersClient struct { - BaseClient -} - -// NewLoadBalancersClient creates an instance of the LoadBalancersClient client. -func NewLoadBalancersClient(subscriptionID string) LoadBalancersClient { - return NewLoadBalancersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancersClientWithBaseURI creates an instance of the LoadBalancersClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancersClient { - return LoadBalancersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// parameters - parameters supplied to the create or update load balancer operation. -func (client LoadBalancersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (result LoadBalancersCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, loadBalancerName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client LoadBalancersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) CreateOrUpdateSender(req *http.Request) (future LoadBalancersCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result LoadBalancer, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancersClient) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client LoadBalancersClient) DeletePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) DeleteSender(req *http.Request) (future LoadBalancersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// expand - expands referenced resources. -func (client LoadBalancersClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (result LoadBalancer, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancersClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) GetResponder(resp *http.Response) (result LoadBalancer, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancers in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client LoadBalancersClient) List(ctx context.Context, resourceGroupName string) (result LoadBalancerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.List") - defer func() { - sc := -1 - if result.lblr.Response.Response != nil { - sc = result.lblr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lblr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request") - return - } - - result.lblr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to request") - return - } - if result.lblr.hasNextLink() && result.lblr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancersClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) ListResponder(resp *http.Response) (result LoadBalancerListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LoadBalancersClient) listNextResults(ctx context.Context, lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { - req, err := lastResults.loadBalancerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancersClient) ListComplete(ctx context.Context, resourceGroupName string) (result LoadBalancerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the load balancers in a subscription. -func (client LoadBalancersClient) ListAll(ctx context.Context) (result LoadBalancerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.ListAll") - defer func() { - sc := -1 - if result.lblr.Response.Response != nil { - sc = result.lblr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.lblr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request") - return - } - - result.lblr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to request") - return - } - if result.lblr.hasNextLink() && result.lblr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client LoadBalancersClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) ListAllResponder(resp *http.Response) (result LoadBalancerListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client LoadBalancersClient) listAllNextResults(ctx context.Context, lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { - req, err := lastResults.loadBalancerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancersClient) ListAllComplete(ctx context.Context) (result LoadBalancerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates a load balancer tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// parameters - parameters supplied to update load balancer tags. -func (client LoadBalancersClient) UpdateTags(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject) (result LoadBalancersUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, loadBalancerName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client LoadBalancersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) UpdateTagsSender(req *http.Request) (future LoadBalancersUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) UpdateTagsResponder(resp *http.Response) (result LoadBalancer, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/localnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/localnetworkgateways.go deleted file mode 100644 index 4b3e53c0a..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/localnetworkgateways.go +++ /dev/null @@ -1,493 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LocalNetworkGatewaysClient is the network Client -type LocalNetworkGatewaysClient struct { - BaseClient -} - -// NewLocalNetworkGatewaysClient creates an instance of the LocalNetworkGatewaysClient client. -func NewLocalNetworkGatewaysClient(subscriptionID string) LocalNetworkGatewaysClient { - return NewLocalNetworkGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLocalNetworkGatewaysClientWithBaseURI creates an instance of the LocalNetworkGatewaysClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewLocalNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID string) LocalNetworkGatewaysClient { - return LocalNetworkGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a local network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -// parameters - parameters supplied to the create or update local network gateway operation. -func (client LocalNetworkGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway) (result LocalNetworkGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: localNetworkGatewayName, - Constraints: []validation.Constraint{{Target: "localNetworkGatewayName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.LocalNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.LocalNetworkGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, localNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (future LocalNetworkGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result LocalNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified local network gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -func (client LocalNetworkGatewaysClient) Delete(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (result LocalNetworkGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: localNetworkGatewayName, - Constraints: []validation.Constraint{{Target: "localNetworkGatewayName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.LocalNetworkGatewaysClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, localNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client LocalNetworkGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) DeleteSender(req *http.Request) (future LocalNetworkGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified local network gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -func (client LocalNetworkGatewaysClient) Get(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (result LocalNetworkGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: localNetworkGatewayName, - Constraints: []validation.Constraint{{Target: "localNetworkGatewayName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.LocalNetworkGatewaysClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, localNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LocalNetworkGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) GetResponder(resp *http.Response) (result LocalNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the local network gateways in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client LocalNetworkGatewaysClient) List(ctx context.Context, resourceGroupName string) (result LocalNetworkGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.lnglr.Response.Response != nil { - sc = result.lnglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lnglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.lnglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.lnglr.hasNextLink() && result.lnglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LocalNetworkGatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) ListResponder(resp *http.Response) (result LocalNetworkGatewayListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client LocalNetworkGatewaysClient) listNextResults(ctx context.Context, lastResults LocalNetworkGatewayListResult) (result LocalNetworkGatewayListResult, err error) { - req, err := lastResults.localNetworkGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LocalNetworkGatewaysClient) ListComplete(ctx context.Context, resourceGroupName string) (result LocalNetworkGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// UpdateTags updates a local network gateway tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -// parameters - parameters supplied to update local network gateway tags. -func (client LocalNetworkGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters TagsObject) (result LocalNetworkGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: localNetworkGatewayName, - Constraints: []validation.Constraint{{Target: "localNetworkGatewayName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.LocalNetworkGatewaysClient", "UpdateTags", err.Error()) - } - - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, localNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client LocalNetworkGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) UpdateTagsSender(req *http.Request) (future LocalNetworkGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) UpdateTagsResponder(resp *http.Response) (result LocalNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/models.go deleted file mode 100644 index 4e296dc54..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/models.go +++ /dev/null @@ -1,31003 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network" - -// AddressSpace addressSpace contains an array of IP address ranges that can be used by subnets of the -// virtual network. -type AddressSpace struct { - // AddressPrefixes - A list of address blocks reserved for this virtual network in CIDR notation. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` -} - -// ApplicationGateway application gateway resource -type ApplicationGateway struct { - autorest.Response `json:"-"` - *ApplicationGatewayPropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting where the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // Identity - The identity of the application gateway, if configured. - Identity *ManagedServiceIdentity `json:"identity,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationGateway. -func (ag ApplicationGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ag.ApplicationGatewayPropertiesFormat != nil { - objectMap["properties"] = ag.ApplicationGatewayPropertiesFormat - } - if ag.Etag != nil { - objectMap["etag"] = ag.Etag - } - if ag.Zones != nil { - objectMap["zones"] = ag.Zones - } - if ag.Identity != nil { - objectMap["identity"] = ag.Identity - } - if ag.ID != nil { - objectMap["id"] = ag.ID - } - if ag.Location != nil { - objectMap["location"] = ag.Location - } - if ag.Tags != nil { - objectMap["tags"] = ag.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGateway struct. -func (ag *ApplicationGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPropertiesFormat ApplicationGatewayPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayPropertiesFormat) - if err != nil { - return err - } - ag.ApplicationGatewayPropertiesFormat = &applicationGatewayPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ag.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - ag.Zones = &zones - } - case "identity": - if v != nil { - var identity ManagedServiceIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - ag.Identity = &identity - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ag.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ag.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ag.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ag.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ag.Tags = tags - } - } - } - - return nil -} - -// ApplicationGatewayAuthenticationCertificate authentication certificates of an application gateway. -type ApplicationGatewayAuthenticationCertificate struct { - *ApplicationGatewayAuthenticationCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the authentication certificate that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayAuthenticationCertificate. -func (agac ApplicationGatewayAuthenticationCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agac.ApplicationGatewayAuthenticationCertificatePropertiesFormat != nil { - objectMap["properties"] = agac.ApplicationGatewayAuthenticationCertificatePropertiesFormat - } - if agac.Name != nil { - objectMap["name"] = agac.Name - } - if agac.Etag != nil { - objectMap["etag"] = agac.Etag - } - if agac.Type != nil { - objectMap["type"] = agac.Type - } - if agac.ID != nil { - objectMap["id"] = agac.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayAuthenticationCertificate struct. -func (agac *ApplicationGatewayAuthenticationCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayAuthenticationCertificatePropertiesFormat ApplicationGatewayAuthenticationCertificatePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayAuthenticationCertificatePropertiesFormat) - if err != nil { - return err - } - agac.ApplicationGatewayAuthenticationCertificatePropertiesFormat = &applicationGatewayAuthenticationCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agac.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agac.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agac.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agac.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayAuthenticationCertificatePropertiesFormat authentication certificates properties of an -// application gateway. -type ApplicationGatewayAuthenticationCertificatePropertiesFormat struct { - // Data - Certificate public data. - Data *string `json:"data,omitempty"` - // ProvisioningState - Provisioning state of the authentication certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayAutoscaleConfiguration application Gateway autoscale configuration. -type ApplicationGatewayAutoscaleConfiguration struct { - // MinCapacity - Lower bound on number of Application Gateway instances - MinCapacity *int32 `json:"minCapacity,omitempty"` -} - -// ApplicationGatewayAvailableSslOptions response for ApplicationGatewayAvailableSslOptions API service -// call. -type ApplicationGatewayAvailableSslOptions struct { - autorest.Response `json:"-"` - *ApplicationGatewayAvailableSslOptionsPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayAvailableSslOptions. -func (agaso ApplicationGatewayAvailableSslOptions) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agaso.ApplicationGatewayAvailableSslOptionsPropertiesFormat != nil { - objectMap["properties"] = agaso.ApplicationGatewayAvailableSslOptionsPropertiesFormat - } - if agaso.ID != nil { - objectMap["id"] = agaso.ID - } - if agaso.Location != nil { - objectMap["location"] = agaso.Location - } - if agaso.Tags != nil { - objectMap["tags"] = agaso.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayAvailableSslOptions struct. -func (agaso *ApplicationGatewayAvailableSslOptions) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayAvailableSslOptionsPropertiesFormat ApplicationGatewayAvailableSslOptionsPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayAvailableSslOptionsPropertiesFormat) - if err != nil { - return err - } - agaso.ApplicationGatewayAvailableSslOptionsPropertiesFormat = &applicationGatewayAvailableSslOptionsPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agaso.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agaso.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agaso.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - agaso.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - agaso.Tags = tags - } - } - } - - return nil -} - -// ApplicationGatewayAvailableSslOptionsPropertiesFormat properties of -// ApplicationGatewayAvailableSslOptions -type ApplicationGatewayAvailableSslOptionsPropertiesFormat struct { - // PredefinedPolicies - List of available Ssl predefined policy. - PredefinedPolicies *[]SubResource `json:"predefinedPolicies,omitempty"` - // DefaultPolicy - Name of the Ssl predefined policy applied by default to application gateway. Possible values include: 'AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S' - DefaultPolicy ApplicationGatewaySslPolicyName `json:"defaultPolicy,omitempty"` - // AvailableCipherSuites - List of available Ssl cipher suites. - AvailableCipherSuites *[]ApplicationGatewaySslCipherSuite `json:"availableCipherSuites,omitempty"` - // AvailableProtocols - List of available Ssl protocols. - AvailableProtocols *[]ApplicationGatewaySslProtocol `json:"availableProtocols,omitempty"` -} - -// ApplicationGatewayAvailableSslPredefinedPolicies response for ApplicationGatewayAvailableSslOptions API -// service call. -type ApplicationGatewayAvailableSslPredefinedPolicies struct { - autorest.Response `json:"-"` - // Value - List of available Ssl predefined policy. - Value *[]ApplicationGatewaySslPredefinedPolicy `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ApplicationGatewayAvailableSslPredefinedPoliciesIterator provides access to a complete listing of -// ApplicationGatewaySslPredefinedPolicy values. -type ApplicationGatewayAvailableSslPredefinedPoliciesIterator struct { - i int - page ApplicationGatewayAvailableSslPredefinedPoliciesPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationGatewayAvailableSslPredefinedPoliciesIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayAvailableSslPredefinedPoliciesIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationGatewayAvailableSslPredefinedPoliciesIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationGatewayAvailableSslPredefinedPoliciesIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationGatewayAvailableSslPredefinedPoliciesIterator) Response() ApplicationGatewayAvailableSslPredefinedPolicies { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationGatewayAvailableSslPredefinedPoliciesIterator) Value() ApplicationGatewaySslPredefinedPolicy { - if !iter.page.NotDone() { - return ApplicationGatewaySslPredefinedPolicy{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationGatewayAvailableSslPredefinedPoliciesIterator type. -func NewApplicationGatewayAvailableSslPredefinedPoliciesIterator(page ApplicationGatewayAvailableSslPredefinedPoliciesPage) ApplicationGatewayAvailableSslPredefinedPoliciesIterator { - return ApplicationGatewayAvailableSslPredefinedPoliciesIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (agaspp ApplicationGatewayAvailableSslPredefinedPolicies) IsEmpty() bool { - return agaspp.Value == nil || len(*agaspp.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (agaspp ApplicationGatewayAvailableSslPredefinedPolicies) hasNextLink() bool { - return agaspp.NextLink != nil && len(*agaspp.NextLink) != 0 -} - -// applicationGatewayAvailableSslPredefinedPoliciesPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (agaspp ApplicationGatewayAvailableSslPredefinedPolicies) applicationGatewayAvailableSslPredefinedPoliciesPreparer(ctx context.Context) (*http.Request, error) { - if !agaspp.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(agaspp.NextLink))) -} - -// ApplicationGatewayAvailableSslPredefinedPoliciesPage contains a page of -// ApplicationGatewaySslPredefinedPolicy values. -type ApplicationGatewayAvailableSslPredefinedPoliciesPage struct { - fn func(context.Context, ApplicationGatewayAvailableSslPredefinedPolicies) (ApplicationGatewayAvailableSslPredefinedPolicies, error) - agaspp ApplicationGatewayAvailableSslPredefinedPolicies -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationGatewayAvailableSslPredefinedPoliciesPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayAvailableSslPredefinedPoliciesPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.agaspp) - if err != nil { - return err - } - page.agaspp = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationGatewayAvailableSslPredefinedPoliciesPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationGatewayAvailableSslPredefinedPoliciesPage) NotDone() bool { - return !page.agaspp.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationGatewayAvailableSslPredefinedPoliciesPage) Response() ApplicationGatewayAvailableSslPredefinedPolicies { - return page.agaspp -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationGatewayAvailableSslPredefinedPoliciesPage) Values() []ApplicationGatewaySslPredefinedPolicy { - if page.agaspp.IsEmpty() { - return nil - } - return *page.agaspp.Value -} - -// Creates a new instance of the ApplicationGatewayAvailableSslPredefinedPoliciesPage type. -func NewApplicationGatewayAvailableSslPredefinedPoliciesPage(cur ApplicationGatewayAvailableSslPredefinedPolicies, getNextPage func(context.Context, ApplicationGatewayAvailableSslPredefinedPolicies) (ApplicationGatewayAvailableSslPredefinedPolicies, error)) ApplicationGatewayAvailableSslPredefinedPoliciesPage { - return ApplicationGatewayAvailableSslPredefinedPoliciesPage{ - fn: getNextPage, - agaspp: cur, - } -} - -// ApplicationGatewayAvailableWafRuleSetsResult response for ApplicationGatewayAvailableWafRuleSets API -// service call. -type ApplicationGatewayAvailableWafRuleSetsResult struct { - autorest.Response `json:"-"` - // Value - The list of application gateway rule sets. - Value *[]ApplicationGatewayFirewallRuleSet `json:"value,omitempty"` -} - -// ApplicationGatewayBackendAddress backend address of an application gateway. -type ApplicationGatewayBackendAddress struct { - // Fqdn - Fully qualified domain name (FQDN). - Fqdn *string `json:"fqdn,omitempty"` - // IPAddress - IP address - IPAddress *string `json:"ipAddress,omitempty"` -} - -// ApplicationGatewayBackendAddressPool backend Address Pool of an application gateway. -type ApplicationGatewayBackendAddressPool struct { - *ApplicationGatewayBackendAddressPoolPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the backend address pool that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendAddressPool. -func (agbap ApplicationGatewayBackendAddressPool) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbap.ApplicationGatewayBackendAddressPoolPropertiesFormat != nil { - objectMap["properties"] = agbap.ApplicationGatewayBackendAddressPoolPropertiesFormat - } - if agbap.Name != nil { - objectMap["name"] = agbap.Name - } - if agbap.Etag != nil { - objectMap["etag"] = agbap.Etag - } - if agbap.Type != nil { - objectMap["type"] = agbap.Type - } - if agbap.ID != nil { - objectMap["id"] = agbap.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayBackendAddressPool struct. -func (agbap *ApplicationGatewayBackendAddressPool) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayBackendAddressPoolPropertiesFormat ApplicationGatewayBackendAddressPoolPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayBackendAddressPoolPropertiesFormat) - if err != nil { - return err - } - agbap.ApplicationGatewayBackendAddressPoolPropertiesFormat = &applicationGatewayBackendAddressPoolPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agbap.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agbap.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agbap.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agbap.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayBackendAddressPoolPropertiesFormat properties of Backend Address Pool of an -// application gateway. -type ApplicationGatewayBackendAddressPoolPropertiesFormat struct { - // BackendIPConfigurations - Collection of references to IPs defined in network interfaces. - BackendIPConfigurations *[]InterfaceIPConfiguration `json:"backendIPConfigurations,omitempty"` - // BackendAddresses - Backend addresses - BackendAddresses *[]ApplicationGatewayBackendAddress `json:"backendAddresses,omitempty"` - // ProvisioningState - Provisioning state of the backend address pool resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayBackendHealth list of ApplicationGatewayBackendHealthPool resources. -type ApplicationGatewayBackendHealth struct { - autorest.Response `json:"-"` - BackendAddressPools *[]ApplicationGatewayBackendHealthPool `json:"backendAddressPools,omitempty"` -} - -// ApplicationGatewayBackendHealthHTTPSettings application gateway BackendHealthHttp settings. -type ApplicationGatewayBackendHealthHTTPSettings struct { - // BackendHTTPSettings - Reference of an ApplicationGatewayBackendHttpSettings resource. - BackendHTTPSettings *ApplicationGatewayBackendHTTPSettings `json:"backendHttpSettings,omitempty"` - // Servers - List of ApplicationGatewayBackendHealthServer resources. - Servers *[]ApplicationGatewayBackendHealthServer `json:"servers,omitempty"` -} - -// ApplicationGatewayBackendHealthPool application gateway BackendHealth pool. -type ApplicationGatewayBackendHealthPool struct { - // BackendAddressPool - Reference of an ApplicationGatewayBackendAddressPool resource. - BackendAddressPool *ApplicationGatewayBackendAddressPool `json:"backendAddressPool,omitempty"` - // BackendHTTPSettingsCollection - List of ApplicationGatewayBackendHealthHttpSettings resources. - BackendHTTPSettingsCollection *[]ApplicationGatewayBackendHealthHTTPSettings `json:"backendHttpSettingsCollection,omitempty"` -} - -// ApplicationGatewayBackendHealthServer application gateway backendhealth http settings. -type ApplicationGatewayBackendHealthServer struct { - // Address - IP address or FQDN of backend server. - Address *string `json:"address,omitempty"` - // IPConfiguration - Reference of IP configuration of backend server. - IPConfiguration *InterfaceIPConfiguration `json:"ipConfiguration,omitempty"` - // Health - Health of backend server. Possible values include: 'Unknown', 'Up', 'Down', 'Partial', 'Draining' - Health ApplicationGatewayBackendHealthServerHealth `json:"health,omitempty"` -} - -// ApplicationGatewayBackendHTTPSettings backend address pool settings of an application gateway. -type ApplicationGatewayBackendHTTPSettings struct { - *ApplicationGatewayBackendHTTPSettingsPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the backend http settings that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendHTTPSettings. -func (agbhs ApplicationGatewayBackendHTTPSettings) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbhs.ApplicationGatewayBackendHTTPSettingsPropertiesFormat != nil { - objectMap["properties"] = agbhs.ApplicationGatewayBackendHTTPSettingsPropertiesFormat - } - if agbhs.Name != nil { - objectMap["name"] = agbhs.Name - } - if agbhs.Etag != nil { - objectMap["etag"] = agbhs.Etag - } - if agbhs.Type != nil { - objectMap["type"] = agbhs.Type - } - if agbhs.ID != nil { - objectMap["id"] = agbhs.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayBackendHTTPSettings struct. -func (agbhs *ApplicationGatewayBackendHTTPSettings) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayBackendHTTPSettingsPropertiesFormat ApplicationGatewayBackendHTTPSettingsPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayBackendHTTPSettingsPropertiesFormat) - if err != nil { - return err - } - agbhs.ApplicationGatewayBackendHTTPSettingsPropertiesFormat = &applicationGatewayBackendHTTPSettingsPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agbhs.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agbhs.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agbhs.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agbhs.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayBackendHTTPSettingsPropertiesFormat properties of Backend address pool settings of an -// application gateway. -type ApplicationGatewayBackendHTTPSettingsPropertiesFormat struct { - // Port - The destination port on the backend. - Port *int32 `json:"port,omitempty"` - // Protocol - The protocol used to communicate with the backend. Possible values are 'Http' and 'Https'. Possible values include: 'HTTP', 'HTTPS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // CookieBasedAffinity - Cookie based affinity. Possible values include: 'Enabled', 'Disabled' - CookieBasedAffinity ApplicationGatewayCookieBasedAffinity `json:"cookieBasedAffinity,omitempty"` - // RequestTimeout - Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400 seconds. - RequestTimeout *int32 `json:"requestTimeout,omitempty"` - // Probe - Probe resource of an application gateway. - Probe *SubResource `json:"probe,omitempty"` - // AuthenticationCertificates - Array of references to application gateway authentication certificates. - AuthenticationCertificates *[]SubResource `json:"authenticationCertificates,omitempty"` - // TrustedRootCertificates - Array of references to application gateway trusted root certificates. - TrustedRootCertificates *[]SubResource `json:"trustedRootCertificates,omitempty"` - // ConnectionDraining - Connection draining of the backend http settings resource. - ConnectionDraining *ApplicationGatewayConnectionDraining `json:"connectionDraining,omitempty"` - // HostName - Host header to be sent to the backend servers. - HostName *string `json:"hostName,omitempty"` - // PickHostNameFromBackendAddress - Whether to pick host header should be picked from the host name of the backend server. Default value is false. - PickHostNameFromBackendAddress *bool `json:"pickHostNameFromBackendAddress,omitempty"` - // AffinityCookieName - Cookie name to use for the affinity cookie. - AffinityCookieName *string `json:"affinityCookieName,omitempty"` - // ProbeEnabled - Whether the probe is enabled. Default value is false. - ProbeEnabled *bool `json:"probeEnabled,omitempty"` - // Path - Path which should be used as a prefix for all HTTP requests. Null means no path will be prefixed. Default value is null. - Path *string `json:"path,omitempty"` - // ProvisioningState - Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayConnectionDraining connection draining allows open connections to a backend server to -// be active for a specified time after the backend server got removed from the configuration. -type ApplicationGatewayConnectionDraining struct { - // Enabled - Whether connection draining is enabled or not. - Enabled *bool `json:"enabled,omitempty"` - // DrainTimeoutInSec - The number of seconds connection draining is active. Acceptable values are from 1 second to 3600 seconds. - DrainTimeoutInSec *int32 `json:"drainTimeoutInSec,omitempty"` -} - -// ApplicationGatewayCustomError customer error of an application gateway. -type ApplicationGatewayCustomError struct { - // StatusCode - Status code of the application gateway customer error. Possible values include: 'HTTPStatus403', 'HTTPStatus502' - StatusCode ApplicationGatewayCustomErrorStatusCode `json:"statusCode,omitempty"` - // CustomErrorPageURL - Error page URL of the application gateway customer error. - CustomErrorPageURL *string `json:"customErrorPageUrl,omitempty"` -} - -// ApplicationGatewayFirewallDisabledRuleGroup allows to disable rules within a rule group or an entire -// rule group. -type ApplicationGatewayFirewallDisabledRuleGroup struct { - // RuleGroupName - The name of the rule group that will be disabled. - RuleGroupName *string `json:"ruleGroupName,omitempty"` - // Rules - The list of rules that will be disabled. If null, all rules of the rule group will be disabled. - Rules *[]int32 `json:"rules,omitempty"` -} - -// ApplicationGatewayFirewallExclusion allow to exclude some variable satisfy the condition for the WAF -// check -type ApplicationGatewayFirewallExclusion struct { - // MatchVariable - The variable to be excluded. - MatchVariable *string `json:"matchVariable,omitempty"` - // SelectorMatchOperator - When matchVariable is a collection, operate on the selector to specify which elements in the collection this exclusion applies to. - SelectorMatchOperator *string `json:"selectorMatchOperator,omitempty"` - // Selector - When matchVariable is a collection, operator used to specify which elements in the collection this exclusion applies to. - Selector *string `json:"selector,omitempty"` -} - -// ApplicationGatewayFirewallRule a web application firewall rule. -type ApplicationGatewayFirewallRule struct { - // RuleID - The identifier of the web application firewall rule. - RuleID *int32 `json:"ruleId,omitempty"` - // Description - The description of the web application firewall rule. - Description *string `json:"description,omitempty"` -} - -// ApplicationGatewayFirewallRuleGroup a web application firewall rule group. -type ApplicationGatewayFirewallRuleGroup struct { - // RuleGroupName - The name of the web application firewall rule group. - RuleGroupName *string `json:"ruleGroupName,omitempty"` - // Description - The description of the web application firewall rule group. - Description *string `json:"description,omitempty"` - // Rules - The rules of the web application firewall rule group. - Rules *[]ApplicationGatewayFirewallRule `json:"rules,omitempty"` -} - -// ApplicationGatewayFirewallRuleSet a web application firewall rule set. -type ApplicationGatewayFirewallRuleSet struct { - *ApplicationGatewayFirewallRuleSetPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFirewallRuleSet. -func (agfrs ApplicationGatewayFirewallRuleSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfrs.ApplicationGatewayFirewallRuleSetPropertiesFormat != nil { - objectMap["properties"] = agfrs.ApplicationGatewayFirewallRuleSetPropertiesFormat - } - if agfrs.ID != nil { - objectMap["id"] = agfrs.ID - } - if agfrs.Location != nil { - objectMap["location"] = agfrs.Location - } - if agfrs.Tags != nil { - objectMap["tags"] = agfrs.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayFirewallRuleSet struct. -func (agfrs *ApplicationGatewayFirewallRuleSet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayFirewallRuleSetPropertiesFormat ApplicationGatewayFirewallRuleSetPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayFirewallRuleSetPropertiesFormat) - if err != nil { - return err - } - agfrs.ApplicationGatewayFirewallRuleSetPropertiesFormat = &applicationGatewayFirewallRuleSetPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agfrs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agfrs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agfrs.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - agfrs.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - agfrs.Tags = tags - } - } - } - - return nil -} - -// ApplicationGatewayFirewallRuleSetPropertiesFormat properties of the web application firewall rule set. -type ApplicationGatewayFirewallRuleSetPropertiesFormat struct { - // ProvisioningState - The provisioning state of the web application firewall rule set. - ProvisioningState *string `json:"provisioningState,omitempty"` - // RuleSetType - The type of the web application firewall rule set. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - The version of the web application firewall rule set type. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` - // RuleGroups - The rule groups of the web application firewall rule set. - RuleGroups *[]ApplicationGatewayFirewallRuleGroup `json:"ruleGroups,omitempty"` -} - -// ApplicationGatewayFrontendIPConfiguration frontend IP configuration of an application gateway. -type ApplicationGatewayFrontendIPConfiguration struct { - *ApplicationGatewayFrontendIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the frontend IP configuration that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFrontendIPConfiguration. -func (agfic ApplicationGatewayFrontendIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfic.ApplicationGatewayFrontendIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = agfic.ApplicationGatewayFrontendIPConfigurationPropertiesFormat - } - if agfic.Name != nil { - objectMap["name"] = agfic.Name - } - if agfic.Etag != nil { - objectMap["etag"] = agfic.Etag - } - if agfic.Type != nil { - objectMap["type"] = agfic.Type - } - if agfic.ID != nil { - objectMap["id"] = agfic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayFrontendIPConfiguration struct. -func (agfic *ApplicationGatewayFrontendIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayFrontendIPConfigurationPropertiesFormat ApplicationGatewayFrontendIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayFrontendIPConfigurationPropertiesFormat) - if err != nil { - return err - } - agfic.ApplicationGatewayFrontendIPConfigurationPropertiesFormat = &applicationGatewayFrontendIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agfic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agfic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agfic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agfic.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayFrontendIPConfigurationPropertiesFormat properties of Frontend IP configuration of an -// application gateway. -type ApplicationGatewayFrontendIPConfigurationPropertiesFormat struct { - // PrivateIPAddress - PrivateIPAddress of the network interface IP Configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - PrivateIP allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - Reference of the subnet resource. - Subnet *SubResource `json:"subnet,omitempty"` - // PublicIPAddress - Reference of the PublicIP resource. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` - // ProvisioningState - Provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayFrontendPort frontend port of an application gateway. -type ApplicationGatewayFrontendPort struct { - *ApplicationGatewayFrontendPortPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the frontend port that is unique within an Application Gateway - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFrontendPort. -func (agfp ApplicationGatewayFrontendPort) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfp.ApplicationGatewayFrontendPortPropertiesFormat != nil { - objectMap["properties"] = agfp.ApplicationGatewayFrontendPortPropertiesFormat - } - if agfp.Name != nil { - objectMap["name"] = agfp.Name - } - if agfp.Etag != nil { - objectMap["etag"] = agfp.Etag - } - if agfp.Type != nil { - objectMap["type"] = agfp.Type - } - if agfp.ID != nil { - objectMap["id"] = agfp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayFrontendPort struct. -func (agfp *ApplicationGatewayFrontendPort) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayFrontendPortPropertiesFormat ApplicationGatewayFrontendPortPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayFrontendPortPropertiesFormat) - if err != nil { - return err - } - agfp.ApplicationGatewayFrontendPortPropertiesFormat = &applicationGatewayFrontendPortPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agfp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agfp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agfp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agfp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayFrontendPortPropertiesFormat properties of Frontend port of an application gateway. -type ApplicationGatewayFrontendPortPropertiesFormat struct { - // Port - Frontend port - Port *int32 `json:"port,omitempty"` - // ProvisioningState - Provisioning state of the frontend port resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayHeaderConfiguration header configuration of the Actions set in Application Gateway. -type ApplicationGatewayHeaderConfiguration struct { - // HeaderName - Header name of the header configuration - HeaderName *string `json:"headerName,omitempty"` - // HeaderValue - Header value of the header configuration - HeaderValue *string `json:"headerValue,omitempty"` -} - -// ApplicationGatewayHTTPListener http listener of an application gateway. -type ApplicationGatewayHTTPListener struct { - *ApplicationGatewayHTTPListenerPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the HTTP listener that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayHTTPListener. -func (aghl ApplicationGatewayHTTPListener) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if aghl.ApplicationGatewayHTTPListenerPropertiesFormat != nil { - objectMap["properties"] = aghl.ApplicationGatewayHTTPListenerPropertiesFormat - } - if aghl.Name != nil { - objectMap["name"] = aghl.Name - } - if aghl.Etag != nil { - objectMap["etag"] = aghl.Etag - } - if aghl.Type != nil { - objectMap["type"] = aghl.Type - } - if aghl.ID != nil { - objectMap["id"] = aghl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayHTTPListener struct. -func (aghl *ApplicationGatewayHTTPListener) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayHTTPListenerPropertiesFormat ApplicationGatewayHTTPListenerPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayHTTPListenerPropertiesFormat) - if err != nil { - return err - } - aghl.ApplicationGatewayHTTPListenerPropertiesFormat = &applicationGatewayHTTPListenerPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - aghl.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - aghl.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - aghl.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - aghl.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayHTTPListenerPropertiesFormat properties of HTTP listener of an application gateway. -type ApplicationGatewayHTTPListenerPropertiesFormat struct { - // FrontendIPConfiguration - Frontend IP configuration resource of an application gateway. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // FrontendPort - Frontend port resource of an application gateway. - FrontendPort *SubResource `json:"frontendPort,omitempty"` - // Protocol - Protocol of the HTTP listener. Possible values are 'Http' and 'Https'. Possible values include: 'HTTP', 'HTTPS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // HostName - Host name of HTTP listener. - HostName *string `json:"hostName,omitempty"` - // SslCertificate - SSL certificate resource of an application gateway. - SslCertificate *SubResource `json:"sslCertificate,omitempty"` - // RequireServerNameIndication - Applicable only if protocol is https. Enables SNI for multi-hosting. - RequireServerNameIndication *bool `json:"requireServerNameIndication,omitempty"` - // ProvisioningState - Provisioning state of the HTTP listener resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // CustomErrorConfigurations - Custom error configurations of the HTTP listener. - CustomErrorConfigurations *[]ApplicationGatewayCustomError `json:"customErrorConfigurations,omitempty"` -} - -// ApplicationGatewayIPConfiguration IP configuration of an application gateway. Currently 1 public and 1 -// private IP configuration is allowed. -type ApplicationGatewayIPConfiguration struct { - *ApplicationGatewayIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the IP configuration that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayIPConfiguration. -func (agic ApplicationGatewayIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agic.ApplicationGatewayIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = agic.ApplicationGatewayIPConfigurationPropertiesFormat - } - if agic.Name != nil { - objectMap["name"] = agic.Name - } - if agic.Etag != nil { - objectMap["etag"] = agic.Etag - } - if agic.Type != nil { - objectMap["type"] = agic.Type - } - if agic.ID != nil { - objectMap["id"] = agic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayIPConfiguration struct. -func (agic *ApplicationGatewayIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayIPConfigurationPropertiesFormat ApplicationGatewayIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayIPConfigurationPropertiesFormat) - if err != nil { - return err - } - agic.ApplicationGatewayIPConfigurationPropertiesFormat = &applicationGatewayIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agic.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayIPConfigurationPropertiesFormat properties of IP configuration of an application -// gateway. -type ApplicationGatewayIPConfigurationPropertiesFormat struct { - // Subnet - Reference of the subnet resource. A subnet from where application gateway gets its private address. - Subnet *SubResource `json:"subnet,omitempty"` - // ProvisioningState - Provisioning state of the application gateway subnet resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayListResult response for ListApplicationGateways API service call. -type ApplicationGatewayListResult struct { - autorest.Response `json:"-"` - // Value - List of an application gateways in a resource group. - Value *[]ApplicationGateway `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ApplicationGatewayListResultIterator provides access to a complete listing of ApplicationGateway values. -type ApplicationGatewayListResultIterator struct { - i int - page ApplicationGatewayListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationGatewayListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationGatewayListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationGatewayListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationGatewayListResultIterator) Response() ApplicationGatewayListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationGatewayListResultIterator) Value() ApplicationGateway { - if !iter.page.NotDone() { - return ApplicationGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationGatewayListResultIterator type. -func NewApplicationGatewayListResultIterator(page ApplicationGatewayListResultPage) ApplicationGatewayListResultIterator { - return ApplicationGatewayListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (aglr ApplicationGatewayListResult) IsEmpty() bool { - return aglr.Value == nil || len(*aglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (aglr ApplicationGatewayListResult) hasNextLink() bool { - return aglr.NextLink != nil && len(*aglr.NextLink) != 0 -} - -// applicationGatewayListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (aglr ApplicationGatewayListResult) applicationGatewayListResultPreparer(ctx context.Context) (*http.Request, error) { - if !aglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(aglr.NextLink))) -} - -// ApplicationGatewayListResultPage contains a page of ApplicationGateway values. -type ApplicationGatewayListResultPage struct { - fn func(context.Context, ApplicationGatewayListResult) (ApplicationGatewayListResult, error) - aglr ApplicationGatewayListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationGatewayListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.aglr) - if err != nil { - return err - } - page.aglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationGatewayListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationGatewayListResultPage) NotDone() bool { - return !page.aglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationGatewayListResultPage) Response() ApplicationGatewayListResult { - return page.aglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationGatewayListResultPage) Values() []ApplicationGateway { - if page.aglr.IsEmpty() { - return nil - } - return *page.aglr.Value -} - -// Creates a new instance of the ApplicationGatewayListResultPage type. -func NewApplicationGatewayListResultPage(cur ApplicationGatewayListResult, getNextPage func(context.Context, ApplicationGatewayListResult) (ApplicationGatewayListResult, error)) ApplicationGatewayListResultPage { - return ApplicationGatewayListResultPage{ - fn: getNextPage, - aglr: cur, - } -} - -// ApplicationGatewayPathRule path rule of URL path map of an application gateway. -type ApplicationGatewayPathRule struct { - *ApplicationGatewayPathRulePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the path rule that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPathRule. -func (agpr ApplicationGatewayPathRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agpr.ApplicationGatewayPathRulePropertiesFormat != nil { - objectMap["properties"] = agpr.ApplicationGatewayPathRulePropertiesFormat - } - if agpr.Name != nil { - objectMap["name"] = agpr.Name - } - if agpr.Etag != nil { - objectMap["etag"] = agpr.Etag - } - if agpr.Type != nil { - objectMap["type"] = agpr.Type - } - if agpr.ID != nil { - objectMap["id"] = agpr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayPathRule struct. -func (agpr *ApplicationGatewayPathRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPathRulePropertiesFormat ApplicationGatewayPathRulePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayPathRulePropertiesFormat) - if err != nil { - return err - } - agpr.ApplicationGatewayPathRulePropertiesFormat = &applicationGatewayPathRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agpr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agpr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agpr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agpr.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayPathRulePropertiesFormat properties of path rule of an application gateway. -type ApplicationGatewayPathRulePropertiesFormat struct { - // Paths - Path rules of URL path map. - Paths *[]string `json:"paths,omitempty"` - // BackendAddressPool - Backend address pool resource of URL path map path rule. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // BackendHTTPSettings - Backend http settings resource of URL path map path rule. - BackendHTTPSettings *SubResource `json:"backendHttpSettings,omitempty"` - // RedirectConfiguration - Redirect configuration resource of URL path map path rule. - RedirectConfiguration *SubResource `json:"redirectConfiguration,omitempty"` - // RewriteRuleSet - Rewrite rule set resource of URL path map path rule. - RewriteRuleSet *SubResource `json:"rewriteRuleSet,omitempty"` - // ProvisioningState - Path rule of URL path map resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayProbe probe of the application gateway. -type ApplicationGatewayProbe struct { - *ApplicationGatewayProbePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the probe that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayProbe. -func (agp ApplicationGatewayProbe) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agp.ApplicationGatewayProbePropertiesFormat != nil { - objectMap["properties"] = agp.ApplicationGatewayProbePropertiesFormat - } - if agp.Name != nil { - objectMap["name"] = agp.Name - } - if agp.Etag != nil { - objectMap["etag"] = agp.Etag - } - if agp.Type != nil { - objectMap["type"] = agp.Type - } - if agp.ID != nil { - objectMap["id"] = agp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayProbe struct. -func (agp *ApplicationGatewayProbe) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayProbePropertiesFormat ApplicationGatewayProbePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayProbePropertiesFormat) - if err != nil { - return err - } - agp.ApplicationGatewayProbePropertiesFormat = &applicationGatewayProbePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayProbeHealthResponseMatch application gateway probe health response match -type ApplicationGatewayProbeHealthResponseMatch struct { - // Body - Body that must be contained in the health response. Default value is empty. - Body *string `json:"body,omitempty"` - // StatusCodes - Allowed ranges of healthy status codes. Default range of healthy status codes is 200-399. - StatusCodes *[]string `json:"statusCodes,omitempty"` -} - -// ApplicationGatewayProbePropertiesFormat properties of probe of an application gateway. -type ApplicationGatewayProbePropertiesFormat struct { - // Protocol - The protocol used for the probe. Possible values are 'Http' and 'Https'. Possible values include: 'HTTP', 'HTTPS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // Host - Host name to send the probe to. - Host *string `json:"host,omitempty"` - // Path - Relative path of probe. Valid path starts from '/'. Probe is sent to ://: - Path *string `json:"path,omitempty"` - // Interval - The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 second to 86400 seconds. - Interval *int32 `json:"interval,omitempty"` - // Timeout - the probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. - Timeout *int32 `json:"timeout,omitempty"` - // UnhealthyThreshold - The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second to 20. - UnhealthyThreshold *int32 `json:"unhealthyThreshold,omitempty"` - // PickHostNameFromBackendHTTPSettings - Whether the host header should be picked from the backend http settings. Default value is false. - PickHostNameFromBackendHTTPSettings *bool `json:"pickHostNameFromBackendHttpSettings,omitempty"` - // MinServers - Minimum number of servers that are always marked healthy. Default value is 0. - MinServers *int32 `json:"minServers,omitempty"` - // Match - Criterion for classifying a healthy probe response. - Match *ApplicationGatewayProbeHealthResponseMatch `json:"match,omitempty"` - // ProvisioningState - Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayPropertiesFormat properties of the application gateway. -type ApplicationGatewayPropertiesFormat struct { - // Sku - SKU of the application gateway resource. - Sku *ApplicationGatewaySku `json:"sku,omitempty"` - // SslPolicy - SSL policy of the application gateway resource. - SslPolicy *ApplicationGatewaySslPolicy `json:"sslPolicy,omitempty"` - // OperationalState - READ-ONLY; Operational state of the application gateway resource. Possible values include: 'Stopped', 'Starting', 'Running', 'Stopping' - OperationalState ApplicationGatewayOperationalState `json:"operationalState,omitempty"` - // GatewayIPConfigurations - Subnets of application the gateway resource. - GatewayIPConfigurations *[]ApplicationGatewayIPConfiguration `json:"gatewayIPConfigurations,omitempty"` - // AuthenticationCertificates - Authentication certificates of the application gateway resource. - AuthenticationCertificates *[]ApplicationGatewayAuthenticationCertificate `json:"authenticationCertificates,omitempty"` - // TrustedRootCertificates - Trusted Root certificates of the application gateway resource. - TrustedRootCertificates *[]ApplicationGatewayTrustedRootCertificate `json:"trustedRootCertificates,omitempty"` - // SslCertificates - SSL certificates of the application gateway resource. - SslCertificates *[]ApplicationGatewaySslCertificate `json:"sslCertificates,omitempty"` - // FrontendIPConfigurations - Frontend IP addresses of the application gateway resource. - FrontendIPConfigurations *[]ApplicationGatewayFrontendIPConfiguration `json:"frontendIPConfigurations,omitempty"` - // FrontendPorts - Frontend ports of the application gateway resource. - FrontendPorts *[]ApplicationGatewayFrontendPort `json:"frontendPorts,omitempty"` - // Probes - Probes of the application gateway resource. - Probes *[]ApplicationGatewayProbe `json:"probes,omitempty"` - // BackendAddressPools - Backend address pool of the application gateway resource. - BackendAddressPools *[]ApplicationGatewayBackendAddressPool `json:"backendAddressPools,omitempty"` - // BackendHTTPSettingsCollection - Backend http settings of the application gateway resource. - BackendHTTPSettingsCollection *[]ApplicationGatewayBackendHTTPSettings `json:"backendHttpSettingsCollection,omitempty"` - // HTTPListeners - Http listeners of the application gateway resource. - HTTPListeners *[]ApplicationGatewayHTTPListener `json:"httpListeners,omitempty"` - // URLPathMaps - URL path map of the application gateway resource. - URLPathMaps *[]ApplicationGatewayURLPathMap `json:"urlPathMaps,omitempty"` - // RequestRoutingRules - Request routing rules of the application gateway resource. - RequestRoutingRules *[]ApplicationGatewayRequestRoutingRule `json:"requestRoutingRules,omitempty"` - // RewriteRuleSets - Rewrite rules for the application gateway resource. - RewriteRuleSets *[]ApplicationGatewayRewriteRuleSet `json:"rewriteRuleSets,omitempty"` - // RedirectConfigurations - Redirect configurations of the application gateway resource. - RedirectConfigurations *[]ApplicationGatewayRedirectConfiguration `json:"redirectConfigurations,omitempty"` - // WebApplicationFirewallConfiguration - Web application firewall configuration. - WebApplicationFirewallConfiguration *ApplicationGatewayWebApplicationFirewallConfiguration `json:"webApplicationFirewallConfiguration,omitempty"` - // EnableHTTP2 - Whether HTTP2 is enabled on the application gateway resource. - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` - // EnableFips - Whether FIPS is enabled on the application gateway resource. - EnableFips *bool `json:"enableFips,omitempty"` - // AutoscaleConfiguration - Autoscale Configuration. - AutoscaleConfiguration *ApplicationGatewayAutoscaleConfiguration `json:"autoscaleConfiguration,omitempty"` - // ResourceGUID - Resource GUID property of the application gateway resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - Provisioning state of the application gateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // CustomErrorConfigurations - Custom error configurations of the application gateway resource. - CustomErrorConfigurations *[]ApplicationGatewayCustomError `json:"customErrorConfigurations,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPropertiesFormat. -func (agpf ApplicationGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agpf.Sku != nil { - objectMap["sku"] = agpf.Sku - } - if agpf.SslPolicy != nil { - objectMap["sslPolicy"] = agpf.SslPolicy - } - if agpf.GatewayIPConfigurations != nil { - objectMap["gatewayIPConfigurations"] = agpf.GatewayIPConfigurations - } - if agpf.AuthenticationCertificates != nil { - objectMap["authenticationCertificates"] = agpf.AuthenticationCertificates - } - if agpf.TrustedRootCertificates != nil { - objectMap["trustedRootCertificates"] = agpf.TrustedRootCertificates - } - if agpf.SslCertificates != nil { - objectMap["sslCertificates"] = agpf.SslCertificates - } - if agpf.FrontendIPConfigurations != nil { - objectMap["frontendIPConfigurations"] = agpf.FrontendIPConfigurations - } - if agpf.FrontendPorts != nil { - objectMap["frontendPorts"] = agpf.FrontendPorts - } - if agpf.Probes != nil { - objectMap["probes"] = agpf.Probes - } - if agpf.BackendAddressPools != nil { - objectMap["backendAddressPools"] = agpf.BackendAddressPools - } - if agpf.BackendHTTPSettingsCollection != nil { - objectMap["backendHttpSettingsCollection"] = agpf.BackendHTTPSettingsCollection - } - if agpf.HTTPListeners != nil { - objectMap["httpListeners"] = agpf.HTTPListeners - } - if agpf.URLPathMaps != nil { - objectMap["urlPathMaps"] = agpf.URLPathMaps - } - if agpf.RequestRoutingRules != nil { - objectMap["requestRoutingRules"] = agpf.RequestRoutingRules - } - if agpf.RewriteRuleSets != nil { - objectMap["rewriteRuleSets"] = agpf.RewriteRuleSets - } - if agpf.RedirectConfigurations != nil { - objectMap["redirectConfigurations"] = agpf.RedirectConfigurations - } - if agpf.WebApplicationFirewallConfiguration != nil { - objectMap["webApplicationFirewallConfiguration"] = agpf.WebApplicationFirewallConfiguration - } - if agpf.EnableHTTP2 != nil { - objectMap["enableHttp2"] = agpf.EnableHTTP2 - } - if agpf.EnableFips != nil { - objectMap["enableFips"] = agpf.EnableFips - } - if agpf.AutoscaleConfiguration != nil { - objectMap["autoscaleConfiguration"] = agpf.AutoscaleConfiguration - } - if agpf.ResourceGUID != nil { - objectMap["resourceGuid"] = agpf.ResourceGUID - } - if agpf.ProvisioningState != nil { - objectMap["provisioningState"] = agpf.ProvisioningState - } - if agpf.CustomErrorConfigurations != nil { - objectMap["customErrorConfigurations"] = agpf.CustomErrorConfigurations - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayRedirectConfiguration redirect configuration of an application gateway. -type ApplicationGatewayRedirectConfiguration struct { - *ApplicationGatewayRedirectConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the redirect configuration that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRedirectConfiguration. -func (agrc ApplicationGatewayRedirectConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrc.ApplicationGatewayRedirectConfigurationPropertiesFormat != nil { - objectMap["properties"] = agrc.ApplicationGatewayRedirectConfigurationPropertiesFormat - } - if agrc.Name != nil { - objectMap["name"] = agrc.Name - } - if agrc.Etag != nil { - objectMap["etag"] = agrc.Etag - } - if agrc.Type != nil { - objectMap["type"] = agrc.Type - } - if agrc.ID != nil { - objectMap["id"] = agrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayRedirectConfiguration struct. -func (agrc *ApplicationGatewayRedirectConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayRedirectConfigurationPropertiesFormat ApplicationGatewayRedirectConfigurationPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayRedirectConfigurationPropertiesFormat) - if err != nil { - return err - } - agrc.ApplicationGatewayRedirectConfigurationPropertiesFormat = &applicationGatewayRedirectConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agrc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agrc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agrc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayRedirectConfigurationPropertiesFormat properties of redirect configuration of the -// application gateway. -type ApplicationGatewayRedirectConfigurationPropertiesFormat struct { - // RedirectType - Supported http redirection types - Permanent, Temporary, Found, SeeOther. Possible values include: 'Permanent', 'Found', 'SeeOther', 'Temporary' - RedirectType ApplicationGatewayRedirectType `json:"redirectType,omitempty"` - // TargetListener - Reference to a listener to redirect the request to. - TargetListener *SubResource `json:"targetListener,omitempty"` - // TargetURL - Url to redirect the request to. - TargetURL *string `json:"targetUrl,omitempty"` - // IncludePath - Include path in the redirected url. - IncludePath *bool `json:"includePath,omitempty"` - // IncludeQueryString - Include query string in the redirected url. - IncludeQueryString *bool `json:"includeQueryString,omitempty"` - // RequestRoutingRules - Request routing specifying redirect configuration. - RequestRoutingRules *[]SubResource `json:"requestRoutingRules,omitempty"` - // URLPathMaps - Url path maps specifying default redirect configuration. - URLPathMaps *[]SubResource `json:"urlPathMaps,omitempty"` - // PathRules - Path rules specifying redirect configuration. - PathRules *[]SubResource `json:"pathRules,omitempty"` -} - -// ApplicationGatewayRequestRoutingRule request routing rule of an application gateway. -type ApplicationGatewayRequestRoutingRule struct { - *ApplicationGatewayRequestRoutingRulePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the request routing rule that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRequestRoutingRule. -func (agrrr ApplicationGatewayRequestRoutingRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrr.ApplicationGatewayRequestRoutingRulePropertiesFormat != nil { - objectMap["properties"] = agrrr.ApplicationGatewayRequestRoutingRulePropertiesFormat - } - if agrrr.Name != nil { - objectMap["name"] = agrrr.Name - } - if agrrr.Etag != nil { - objectMap["etag"] = agrrr.Etag - } - if agrrr.Type != nil { - objectMap["type"] = agrrr.Type - } - if agrrr.ID != nil { - objectMap["id"] = agrrr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayRequestRoutingRule struct. -func (agrrr *ApplicationGatewayRequestRoutingRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayRequestRoutingRulePropertiesFormat ApplicationGatewayRequestRoutingRulePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayRequestRoutingRulePropertiesFormat) - if err != nil { - return err - } - agrrr.ApplicationGatewayRequestRoutingRulePropertiesFormat = &applicationGatewayRequestRoutingRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agrrr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agrrr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agrrr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agrrr.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayRequestRoutingRulePropertiesFormat properties of request routing rule of the -// application gateway. -type ApplicationGatewayRequestRoutingRulePropertiesFormat struct { - // RuleType - Rule type. Possible values include: 'Basic', 'PathBasedRouting' - RuleType ApplicationGatewayRequestRoutingRuleType `json:"ruleType,omitempty"` - // BackendAddressPool - Backend address pool resource of the application gateway. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // BackendHTTPSettings - Backend http settings resource of the application gateway. - BackendHTTPSettings *SubResource `json:"backendHttpSettings,omitempty"` - // HTTPListener - Http listener resource of the application gateway. - HTTPListener *SubResource `json:"httpListener,omitempty"` - // URLPathMap - URL path map resource of the application gateway. - URLPathMap *SubResource `json:"urlPathMap,omitempty"` - // RewriteRuleSet - Rewrite Rule Set resource in Basic rule of the application gateway. - RewriteRuleSet *SubResource `json:"rewriteRuleSet,omitempty"` - // RedirectConfiguration - Redirect configuration resource of the application gateway. - RedirectConfiguration *SubResource `json:"redirectConfiguration,omitempty"` - // ProvisioningState - Provisioning state of the request routing rule resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayRewriteRule rewrite rule of an application gateway. -type ApplicationGatewayRewriteRule struct { - // Name - Name of the rewrite rule that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // ActionSet - Set of actions to be done as part of the rewrite Rule. - ActionSet *ApplicationGatewayRewriteRuleActionSet `json:"actionSet,omitempty"` -} - -// ApplicationGatewayRewriteRuleActionSet set of actions in the Rewrite Rule in Application Gateway. -type ApplicationGatewayRewriteRuleActionSet struct { - // RequestHeaderConfigurations - Request Header Actions in the Action Set - RequestHeaderConfigurations *[]ApplicationGatewayHeaderConfiguration `json:"requestHeaderConfigurations,omitempty"` - // ResponseHeaderConfigurations - Response Header Actions in the Action Set - ResponseHeaderConfigurations *[]ApplicationGatewayHeaderConfiguration `json:"responseHeaderConfigurations,omitempty"` -} - -// ApplicationGatewayRewriteRuleSet rewrite rule set of an application gateway. -type ApplicationGatewayRewriteRuleSet struct { - *ApplicationGatewayRewriteRuleSetPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the rewrite rule set that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRewriteRuleSet. -func (agrrs ApplicationGatewayRewriteRuleSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrs.ApplicationGatewayRewriteRuleSetPropertiesFormat != nil { - objectMap["properties"] = agrrs.ApplicationGatewayRewriteRuleSetPropertiesFormat - } - if agrrs.Name != nil { - objectMap["name"] = agrrs.Name - } - if agrrs.ID != nil { - objectMap["id"] = agrrs.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayRewriteRuleSet struct. -func (agrrs *ApplicationGatewayRewriteRuleSet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayRewriteRuleSetPropertiesFormat ApplicationGatewayRewriteRuleSetPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayRewriteRuleSetPropertiesFormat) - if err != nil { - return err - } - agrrs.ApplicationGatewayRewriteRuleSetPropertiesFormat = &applicationGatewayRewriteRuleSetPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agrrs.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agrrs.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agrrs.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayRewriteRuleSetPropertiesFormat properties of rewrite rule set of the application -// gateway. -type ApplicationGatewayRewriteRuleSetPropertiesFormat struct { - // RewriteRules - Rewrite rules in the rewrite rule set. - RewriteRules *[]ApplicationGatewayRewriteRule `json:"rewriteRules,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the rewrite rule set resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRewriteRuleSetPropertiesFormat. -func (agrrspf ApplicationGatewayRewriteRuleSetPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrspf.RewriteRules != nil { - objectMap["rewriteRules"] = agrrspf.RewriteRules - } - return json.Marshal(objectMap) -} - -// ApplicationGatewaysBackendHealthFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysBackendHealthFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (ApplicationGatewayBackendHealth, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysBackendHealthFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysBackendHealthFuture.Result. -func (future *ApplicationGatewaysBackendHealthFuture) result(client ApplicationGatewaysClient) (agbh ApplicationGatewayBackendHealth, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysBackendHealthFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - agbh.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysBackendHealthFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if agbh.Response.Response, err = future.GetResult(sender); err == nil && agbh.Response.Response.StatusCode != http.StatusNoContent { - agbh, err = client.BackendHealthResponder(agbh.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysBackendHealthFuture", "Result", agbh.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (ApplicationGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysCreateOrUpdateFuture.Result. -func (future *ApplicationGatewaysCreateOrUpdateFuture) result(client ApplicationGatewaysClient) (ag ApplicationGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ag.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ag.Response.Response, err = future.GetResult(sender); err == nil && ag.Response.Response.StatusCode != http.StatusNoContent { - ag, err = client.CreateOrUpdateResponder(ag.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysCreateOrUpdateFuture", "Result", ag.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysDeleteFuture.Result. -func (future *ApplicationGatewaysDeleteFuture) result(client ApplicationGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGatewaySku SKU of an application gateway -type ApplicationGatewaySku struct { - // Name - Name of an application gateway SKU. Possible values include: 'StandardSmall', 'StandardMedium', 'StandardLarge', 'WAFMedium', 'WAFLarge', 'StandardV2', 'WAFV2' - Name ApplicationGatewaySkuName `json:"name,omitempty"` - // Tier - Tier of an application gateway. Possible values include: 'ApplicationGatewayTierStandard', 'ApplicationGatewayTierWAF', 'ApplicationGatewayTierStandardV2', 'ApplicationGatewayTierWAFV2' - Tier ApplicationGatewayTier `json:"tier,omitempty"` - // Capacity - Capacity (instance count) of an application gateway. - Capacity *int32 `json:"capacity,omitempty"` -} - -// ApplicationGatewaySslCertificate SSL certificates of an application gateway. -type ApplicationGatewaySslCertificate struct { - *ApplicationGatewaySslCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the SSL certificate that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewaySslCertificate. -func (agsc ApplicationGatewaySslCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agsc.ApplicationGatewaySslCertificatePropertiesFormat != nil { - objectMap["properties"] = agsc.ApplicationGatewaySslCertificatePropertiesFormat - } - if agsc.Name != nil { - objectMap["name"] = agsc.Name - } - if agsc.Etag != nil { - objectMap["etag"] = agsc.Etag - } - if agsc.Type != nil { - objectMap["type"] = agsc.Type - } - if agsc.ID != nil { - objectMap["id"] = agsc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewaySslCertificate struct. -func (agsc *ApplicationGatewaySslCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewaySslCertificatePropertiesFormat ApplicationGatewaySslCertificatePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewaySslCertificatePropertiesFormat) - if err != nil { - return err - } - agsc.ApplicationGatewaySslCertificatePropertiesFormat = &applicationGatewaySslCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agsc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agsc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agsc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agsc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewaySslCertificatePropertiesFormat properties of SSL certificates of an application -// gateway. -type ApplicationGatewaySslCertificatePropertiesFormat struct { - // Data - Base-64 encoded pfx certificate. Only applicable in PUT Request. - Data *string `json:"data,omitempty"` - // Password - Password for the pfx file specified in data. Only applicable in PUT request. - Password *string `json:"password,omitempty"` - // PublicCertData - Base-64 encoded Public cert data corresponding to pfx specified in data. Only applicable in GET request. - PublicCertData *string `json:"publicCertData,omitempty"` - // KeyVaultSecretID - Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. - KeyVaultSecretID *string `json:"keyVaultSecretId,omitempty"` - // ProvisioningState - Provisioning state of the SSL certificate resource Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewaySslPolicy application Gateway Ssl policy. -type ApplicationGatewaySslPolicy struct { - // DisabledSslProtocols - Ssl protocols to be disabled on application gateway. - DisabledSslProtocols *[]ApplicationGatewaySslProtocol `json:"disabledSslProtocols,omitempty"` - // PolicyType - Type of Ssl Policy. Possible values include: 'Predefined', 'Custom' - PolicyType ApplicationGatewaySslPolicyType `json:"policyType,omitempty"` - // PolicyName - Name of Ssl predefined policy. Possible values include: 'AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S' - PolicyName ApplicationGatewaySslPolicyName `json:"policyName,omitempty"` - // CipherSuites - Ssl cipher suites to be enabled in the specified order to application gateway. - CipherSuites *[]ApplicationGatewaySslCipherSuite `json:"cipherSuites,omitempty"` - // MinProtocolVersion - Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv10', 'TLSv11', 'TLSv12' - MinProtocolVersion ApplicationGatewaySslProtocol `json:"minProtocolVersion,omitempty"` -} - -// ApplicationGatewaySslPredefinedPolicy an Ssl predefined policy -type ApplicationGatewaySslPredefinedPolicy struct { - autorest.Response `json:"-"` - // Name - Name of the Ssl predefined policy. - Name *string `json:"name,omitempty"` - *ApplicationGatewaySslPredefinedPolicyPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewaySslPredefinedPolicy. -func (agspp ApplicationGatewaySslPredefinedPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agspp.Name != nil { - objectMap["name"] = agspp.Name - } - if agspp.ApplicationGatewaySslPredefinedPolicyPropertiesFormat != nil { - objectMap["properties"] = agspp.ApplicationGatewaySslPredefinedPolicyPropertiesFormat - } - if agspp.ID != nil { - objectMap["id"] = agspp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewaySslPredefinedPolicy struct. -func (agspp *ApplicationGatewaySslPredefinedPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agspp.Name = &name - } - case "properties": - if v != nil { - var applicationGatewaySslPredefinedPolicyPropertiesFormat ApplicationGatewaySslPredefinedPolicyPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewaySslPredefinedPolicyPropertiesFormat) - if err != nil { - return err - } - agspp.ApplicationGatewaySslPredefinedPolicyPropertiesFormat = &applicationGatewaySslPredefinedPolicyPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agspp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewaySslPredefinedPolicyPropertiesFormat properties of -// ApplicationGatewaySslPredefinedPolicy -type ApplicationGatewaySslPredefinedPolicyPropertiesFormat struct { - // CipherSuites - Ssl cipher suites to be enabled in the specified order for application gateway. - CipherSuites *[]ApplicationGatewaySslCipherSuite `json:"cipherSuites,omitempty"` - // MinProtocolVersion - Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv10', 'TLSv11', 'TLSv12' - MinProtocolVersion ApplicationGatewaySslProtocol `json:"minProtocolVersion,omitempty"` -} - -// ApplicationGatewaysStartFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysStartFuture.Result. -func (future *ApplicationGatewaysStartFuture) result(client ApplicationGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysStartFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGatewaysStopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ApplicationGatewaysStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysStopFuture.Result. -func (future *ApplicationGatewaysStopFuture) result(client ApplicationGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysStopFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (ApplicationGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysUpdateTagsFuture.Result. -func (future *ApplicationGatewaysUpdateTagsFuture) result(client ApplicationGatewaysClient) (ag ApplicationGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ag.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ag.Response.Response, err = future.GetResult(sender); err == nil && ag.Response.Response.StatusCode != http.StatusNoContent { - ag, err = client.UpdateTagsResponder(ag.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysUpdateTagsFuture", "Result", ag.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationGatewayTrustedRootCertificate trusted Root certificates of an application gateway. -type ApplicationGatewayTrustedRootCertificate struct { - *ApplicationGatewayTrustedRootCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the trusted root certificate that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayTrustedRootCertificate. -func (agtrc ApplicationGatewayTrustedRootCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agtrc.ApplicationGatewayTrustedRootCertificatePropertiesFormat != nil { - objectMap["properties"] = agtrc.ApplicationGatewayTrustedRootCertificatePropertiesFormat - } - if agtrc.Name != nil { - objectMap["name"] = agtrc.Name - } - if agtrc.Etag != nil { - objectMap["etag"] = agtrc.Etag - } - if agtrc.Type != nil { - objectMap["type"] = agtrc.Type - } - if agtrc.ID != nil { - objectMap["id"] = agtrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayTrustedRootCertificate struct. -func (agtrc *ApplicationGatewayTrustedRootCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayTrustedRootCertificatePropertiesFormat ApplicationGatewayTrustedRootCertificatePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayTrustedRootCertificatePropertiesFormat) - if err != nil { - return err - } - agtrc.ApplicationGatewayTrustedRootCertificatePropertiesFormat = &applicationGatewayTrustedRootCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agtrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agtrc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agtrc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agtrc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayTrustedRootCertificatePropertiesFormat trusted Root certificates properties of an -// application gateway. -type ApplicationGatewayTrustedRootCertificatePropertiesFormat struct { - // Data - Certificate public data. - Data *string `json:"data,omitempty"` - // KeyVaultSecretID - Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. - KeyVaultSecretID *string `json:"keyVaultSecretId,omitempty"` - // ProvisioningState - Provisioning state of the trusted root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayURLPathMap urlPathMaps give a url path to the backend mapping information for -// PathBasedRouting. -type ApplicationGatewayURLPathMap struct { - *ApplicationGatewayURLPathMapPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the URL path map that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayURLPathMap. -func (agupm ApplicationGatewayURLPathMap) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agupm.ApplicationGatewayURLPathMapPropertiesFormat != nil { - objectMap["properties"] = agupm.ApplicationGatewayURLPathMapPropertiesFormat - } - if agupm.Name != nil { - objectMap["name"] = agupm.Name - } - if agupm.Etag != nil { - objectMap["etag"] = agupm.Etag - } - if agupm.Type != nil { - objectMap["type"] = agupm.Type - } - if agupm.ID != nil { - objectMap["id"] = agupm.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayURLPathMap struct. -func (agupm *ApplicationGatewayURLPathMap) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayURLPathMapPropertiesFormat ApplicationGatewayURLPathMapPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayURLPathMapPropertiesFormat) - if err != nil { - return err - } - agupm.ApplicationGatewayURLPathMapPropertiesFormat = &applicationGatewayURLPathMapPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agupm.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agupm.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agupm.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agupm.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayURLPathMapPropertiesFormat properties of UrlPathMap of the application gateway. -type ApplicationGatewayURLPathMapPropertiesFormat struct { - // DefaultBackendAddressPool - Default backend address pool resource of URL path map. - DefaultBackendAddressPool *SubResource `json:"defaultBackendAddressPool,omitempty"` - // DefaultBackendHTTPSettings - Default backend http settings resource of URL path map. - DefaultBackendHTTPSettings *SubResource `json:"defaultBackendHttpSettings,omitempty"` - // DefaultRewriteRuleSet - Default Rewrite rule set resource of URL path map. - DefaultRewriteRuleSet *SubResource `json:"defaultRewriteRuleSet,omitempty"` - // DefaultRedirectConfiguration - Default redirect configuration resource of URL path map. - DefaultRedirectConfiguration *SubResource `json:"defaultRedirectConfiguration,omitempty"` - // PathRules - Path rule of URL path map resource. - PathRules *[]ApplicationGatewayPathRule `json:"pathRules,omitempty"` - // ProvisioningState - Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// ApplicationGatewayWebApplicationFirewallConfiguration application gateway web application firewall -// configuration. -type ApplicationGatewayWebApplicationFirewallConfiguration struct { - // Enabled - Whether the web application firewall is enabled or not. - Enabled *bool `json:"enabled,omitempty"` - // FirewallMode - Web application firewall mode. Possible values include: 'Detection', 'Prevention' - FirewallMode ApplicationGatewayFirewallMode `json:"firewallMode,omitempty"` - // RuleSetType - The type of the web application firewall rule set. Possible values are: 'OWASP'. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - The version of the rule set type. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` - // DisabledRuleGroups - The disabled rule groups. - DisabledRuleGroups *[]ApplicationGatewayFirewallDisabledRuleGroup `json:"disabledRuleGroups,omitempty"` - // RequestBodyCheck - Whether allow WAF to check request Body. - RequestBodyCheck *bool `json:"requestBodyCheck,omitempty"` - // MaxRequestBodySize - Maximum request body size for WAF. - MaxRequestBodySize *int32 `json:"maxRequestBodySize,omitempty"` - // MaxRequestBodySizeInKb - Maximum request body size in Kb for WAF. - MaxRequestBodySizeInKb *int32 `json:"maxRequestBodySizeInKb,omitempty"` - // FileUploadLimitInMb - Maximum file upload size in Mb for WAF. - FileUploadLimitInMb *int32 `json:"fileUploadLimitInMb,omitempty"` - // Exclusions - The exclusion list. - Exclusions *[]ApplicationGatewayFirewallExclusion `json:"exclusions,omitempty"` -} - -// ApplicationSecurityGroup an application security group in a resource group. -type ApplicationSecurityGroup struct { - autorest.Response `json:"-"` - // ApplicationSecurityGroupPropertiesFormat - Properties of the application security group. - *ApplicationSecurityGroupPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationSecurityGroup. -func (asg ApplicationSecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if asg.ApplicationSecurityGroupPropertiesFormat != nil { - objectMap["properties"] = asg.ApplicationSecurityGroupPropertiesFormat - } - if asg.ID != nil { - objectMap["id"] = asg.ID - } - if asg.Location != nil { - objectMap["location"] = asg.Location - } - if asg.Tags != nil { - objectMap["tags"] = asg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationSecurityGroup struct. -func (asg *ApplicationSecurityGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationSecurityGroupPropertiesFormat ApplicationSecurityGroupPropertiesFormat - err = json.Unmarshal(*v, &applicationSecurityGroupPropertiesFormat) - if err != nil { - return err - } - asg.ApplicationSecurityGroupPropertiesFormat = &applicationSecurityGroupPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - asg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - asg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - asg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - asg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - asg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - asg.Tags = tags - } - } - } - - return nil -} - -// ApplicationSecurityGroupListResult a list of application security groups. -type ApplicationSecurityGroupListResult struct { - autorest.Response `json:"-"` - // Value - A list of application security groups. - Value *[]ApplicationSecurityGroup `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationSecurityGroupListResult. -func (asglr ApplicationSecurityGroupListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if asglr.Value != nil { - objectMap["value"] = asglr.Value - } - return json.Marshal(objectMap) -} - -// ApplicationSecurityGroupListResultIterator provides access to a complete listing of -// ApplicationSecurityGroup values. -type ApplicationSecurityGroupListResultIterator struct { - i int - page ApplicationSecurityGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationSecurityGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationSecurityGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationSecurityGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationSecurityGroupListResultIterator) Response() ApplicationSecurityGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationSecurityGroupListResultIterator) Value() ApplicationSecurityGroup { - if !iter.page.NotDone() { - return ApplicationSecurityGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationSecurityGroupListResultIterator type. -func NewApplicationSecurityGroupListResultIterator(page ApplicationSecurityGroupListResultPage) ApplicationSecurityGroupListResultIterator { - return ApplicationSecurityGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (asglr ApplicationSecurityGroupListResult) IsEmpty() bool { - return asglr.Value == nil || len(*asglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (asglr ApplicationSecurityGroupListResult) hasNextLink() bool { - return asglr.NextLink != nil && len(*asglr.NextLink) != 0 -} - -// applicationSecurityGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (asglr ApplicationSecurityGroupListResult) applicationSecurityGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !asglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(asglr.NextLink))) -} - -// ApplicationSecurityGroupListResultPage contains a page of ApplicationSecurityGroup values. -type ApplicationSecurityGroupListResultPage struct { - fn func(context.Context, ApplicationSecurityGroupListResult) (ApplicationSecurityGroupListResult, error) - asglr ApplicationSecurityGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationSecurityGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.asglr) - if err != nil { - return err - } - page.asglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationSecurityGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationSecurityGroupListResultPage) NotDone() bool { - return !page.asglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationSecurityGroupListResultPage) Response() ApplicationSecurityGroupListResult { - return page.asglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationSecurityGroupListResultPage) Values() []ApplicationSecurityGroup { - if page.asglr.IsEmpty() { - return nil - } - return *page.asglr.Value -} - -// Creates a new instance of the ApplicationSecurityGroupListResultPage type. -func NewApplicationSecurityGroupListResultPage(cur ApplicationSecurityGroupListResult, getNextPage func(context.Context, ApplicationSecurityGroupListResult) (ApplicationSecurityGroupListResult, error)) ApplicationSecurityGroupListResultPage { - return ApplicationSecurityGroupListResultPage{ - fn: getNextPage, - asglr: cur, - } -} - -// ApplicationSecurityGroupPropertiesFormat application security group properties. -type ApplicationSecurityGroupPropertiesFormat struct { - // ResourceGUID - READ-ONLY; The resource GUID property of the application security group resource. It uniquely identifies a resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application security group resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationSecurityGroupPropertiesFormat. -func (asgpf ApplicationSecurityGroupPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ApplicationSecurityGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ApplicationSecurityGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationSecurityGroupsClient) (ApplicationSecurityGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationSecurityGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationSecurityGroupsCreateOrUpdateFuture.Result. -func (future *ApplicationSecurityGroupsCreateOrUpdateFuture) result(client ApplicationSecurityGroupsClient) (asg ApplicationSecurityGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - asg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationSecurityGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if asg.Response.Response, err = future.GetResult(sender); err == nil && asg.Response.Response.StatusCode != http.StatusNoContent { - asg, err = client.CreateOrUpdateResponder(asg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsCreateOrUpdateFuture", "Result", asg.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationSecurityGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationSecurityGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationSecurityGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationSecurityGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationSecurityGroupsDeleteFuture.Result. -func (future *ApplicationSecurityGroupsDeleteFuture) result(client ApplicationSecurityGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationSecurityGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AuthorizationListResult response for ListAuthorizations API service call retrieves all authorizations -// that belongs to an ExpressRouteCircuit. -type AuthorizationListResult struct { - autorest.Response `json:"-"` - // Value - The authorizations in an ExpressRoute Circuit. - Value *[]ExpressRouteCircuitAuthorization `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AuthorizationListResultIterator provides access to a complete listing of -// ExpressRouteCircuitAuthorization values. -type AuthorizationListResultIterator struct { - i int - page AuthorizationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AuthorizationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AuthorizationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AuthorizationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AuthorizationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AuthorizationListResultIterator) Response() AuthorizationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AuthorizationListResultIterator) Value() ExpressRouteCircuitAuthorization { - if !iter.page.NotDone() { - return ExpressRouteCircuitAuthorization{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AuthorizationListResultIterator type. -func NewAuthorizationListResultIterator(page AuthorizationListResultPage) AuthorizationListResultIterator { - return AuthorizationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (alr AuthorizationListResult) IsEmpty() bool { - return alr.Value == nil || len(*alr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (alr AuthorizationListResult) hasNextLink() bool { - return alr.NextLink != nil && len(*alr.NextLink) != 0 -} - -// authorizationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (alr AuthorizationListResult) authorizationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !alr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(alr.NextLink))) -} - -// AuthorizationListResultPage contains a page of ExpressRouteCircuitAuthorization values. -type AuthorizationListResultPage struct { - fn func(context.Context, AuthorizationListResult) (AuthorizationListResult, error) - alr AuthorizationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AuthorizationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AuthorizationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.alr) - if err != nil { - return err - } - page.alr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AuthorizationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AuthorizationListResultPage) NotDone() bool { - return !page.alr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AuthorizationListResultPage) Response() AuthorizationListResult { - return page.alr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AuthorizationListResultPage) Values() []ExpressRouteCircuitAuthorization { - if page.alr.IsEmpty() { - return nil - } - return *page.alr.Value -} - -// Creates a new instance of the AuthorizationListResultPage type. -func NewAuthorizationListResultPage(cur AuthorizationListResult, getNextPage func(context.Context, AuthorizationListResult) (AuthorizationListResult, error)) AuthorizationListResultPage { - return AuthorizationListResultPage{ - fn: getNextPage, - alr: cur, - } -} - -// AuthorizationPropertiesFormat ... -type AuthorizationPropertiesFormat struct { - // AuthorizationKey - The authorization key. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // AuthorizationUseStatus - AuthorizationUseStatus. Possible values are: 'Available' and 'InUse'. Possible values include: 'Available', 'InUse' - AuthorizationUseStatus AuthorizationUseStatus `json:"authorizationUseStatus,omitempty"` - // ProvisioningState - Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// Availability availability of the metric. -type Availability struct { - // TimeGrain - The time grain of the availability. - TimeGrain *string `json:"timeGrain,omitempty"` - // Retention - The retention of the availability. - Retention *string `json:"retention,omitempty"` - // BlobDuration - Duration of the availability blob. - BlobDuration *string `json:"blobDuration,omitempty"` -} - -// AvailableDelegation the serviceName of an AvailableDelegation indicates a possible delegation for a -// subnet. -type AvailableDelegation struct { - // Name - The name of the AvailableDelegation resource. - Name *string `json:"name,omitempty"` - // ID - A unique identifier of the AvailableDelegation resource. - ID *string `json:"id,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // ServiceName - The name of the service and resource - ServiceName *string `json:"serviceName,omitempty"` - // Actions - Describes the actions permitted to the service upon delegation - Actions *[]string `json:"actions,omitempty"` -} - -// AvailableDelegationsResult an array of available delegations. -type AvailableDelegationsResult struct { - autorest.Response `json:"-"` - // Value - An array of available delegations. - Value *[]AvailableDelegation `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for AvailableDelegationsResult. -func (adr AvailableDelegationsResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if adr.Value != nil { - objectMap["value"] = adr.Value - } - return json.Marshal(objectMap) -} - -// AvailableDelegationsResultIterator provides access to a complete listing of AvailableDelegation values. -type AvailableDelegationsResultIterator struct { - i int - page AvailableDelegationsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AvailableDelegationsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AvailableDelegationsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AvailableDelegationsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AvailableDelegationsResultIterator) Response() AvailableDelegationsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AvailableDelegationsResultIterator) Value() AvailableDelegation { - if !iter.page.NotDone() { - return AvailableDelegation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AvailableDelegationsResultIterator type. -func NewAvailableDelegationsResultIterator(page AvailableDelegationsResultPage) AvailableDelegationsResultIterator { - return AvailableDelegationsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (adr AvailableDelegationsResult) IsEmpty() bool { - return adr.Value == nil || len(*adr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (adr AvailableDelegationsResult) hasNextLink() bool { - return adr.NextLink != nil && len(*adr.NextLink) != 0 -} - -// availableDelegationsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (adr AvailableDelegationsResult) availableDelegationsResultPreparer(ctx context.Context) (*http.Request, error) { - if !adr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(adr.NextLink))) -} - -// AvailableDelegationsResultPage contains a page of AvailableDelegation values. -type AvailableDelegationsResultPage struct { - fn func(context.Context, AvailableDelegationsResult) (AvailableDelegationsResult, error) - adr AvailableDelegationsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AvailableDelegationsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.adr) - if err != nil { - return err - } - page.adr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AvailableDelegationsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AvailableDelegationsResultPage) NotDone() bool { - return !page.adr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AvailableDelegationsResultPage) Response() AvailableDelegationsResult { - return page.adr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AvailableDelegationsResultPage) Values() []AvailableDelegation { - if page.adr.IsEmpty() { - return nil - } - return *page.adr.Value -} - -// Creates a new instance of the AvailableDelegationsResultPage type. -func NewAvailableDelegationsResultPage(cur AvailableDelegationsResult, getNextPage func(context.Context, AvailableDelegationsResult) (AvailableDelegationsResult, error)) AvailableDelegationsResultPage { - return AvailableDelegationsResultPage{ - fn: getNextPage, - adr: cur, - } -} - -// AvailableProvidersList list of available countries with details. -type AvailableProvidersList struct { - autorest.Response `json:"-"` - // Countries - List of available countries. - Countries *[]AvailableProvidersListCountry `json:"countries,omitempty"` -} - -// AvailableProvidersListCity city or town details. -type AvailableProvidersListCity struct { - // CityName - The city or town name. - CityName *string `json:"cityName,omitempty"` - // Providers - A list of Internet service providers. - Providers *[]string `json:"providers,omitempty"` -} - -// AvailableProvidersListCountry country details. -type AvailableProvidersListCountry struct { - // CountryName - The country name. - CountryName *string `json:"countryName,omitempty"` - // Providers - A list of Internet service providers. - Providers *[]string `json:"providers,omitempty"` - // States - List of available states in the country. - States *[]AvailableProvidersListState `json:"states,omitempty"` -} - -// AvailableProvidersListParameters constraints that determine the list of available Internet service -// providers. -type AvailableProvidersListParameters struct { - // AzureLocations - A list of Azure regions. - AzureLocations *[]string `json:"azureLocations,omitempty"` - // Country - The country for available providers list. - Country *string `json:"country,omitempty"` - // State - The state for available providers list. - State *string `json:"state,omitempty"` - // City - The city or town for available providers list. - City *string `json:"city,omitempty"` -} - -// AvailableProvidersListState state details. -type AvailableProvidersListState struct { - // StateName - The state name. - StateName *string `json:"stateName,omitempty"` - // Providers - A list of Internet service providers. - Providers *[]string `json:"providers,omitempty"` - // Cities - List of available cities or towns in the state. - Cities *[]AvailableProvidersListCity `json:"cities,omitempty"` -} - -// AzureAsyncOperationResult the response body contains the status of the specified asynchronous operation, -// indicating whether it has succeeded, is in progress, or has failed. Note that this status is distinct -// from the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous -// operation succeeded, the response body includes the HTTP status code for the successful request. If the -// asynchronous operation failed, the response body includes the HTTP status code for the failed request -// and error information regarding the failure. -type AzureAsyncOperationResult struct { - // Status - Status of the Azure async operation. Possible values are: 'InProgress', 'Succeeded', and 'Failed'. Possible values include: 'OperationStatusInProgress', 'OperationStatusSucceeded', 'OperationStatusFailed' - Status OperationStatus `json:"status,omitempty"` - Error *Error `json:"error,omitempty"` -} - -// AzureFirewall azure Firewall resource -type AzureFirewall struct { - autorest.Response `json:"-"` - *AzureFirewallPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for AzureFirewall. -func (af AzureFirewall) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if af.AzureFirewallPropertiesFormat != nil { - objectMap["properties"] = af.AzureFirewallPropertiesFormat - } - if af.ID != nil { - objectMap["id"] = af.ID - } - if af.Location != nil { - objectMap["location"] = af.Location - } - if af.Tags != nil { - objectMap["tags"] = af.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewall struct. -func (af *AzureFirewall) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallPropertiesFormat AzureFirewallPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallPropertiesFormat) - if err != nil { - return err - } - af.AzureFirewallPropertiesFormat = &azureFirewallPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - af.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - af.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - af.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - af.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - af.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - af.Tags = tags - } - } - } - - return nil -} - -// AzureFirewallApplicationRule properties of an application rule. -type AzureFirewallApplicationRule struct { - // Name - Name of the application rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // Protocols - Array of ApplicationRuleProtocols. - Protocols *[]AzureFirewallApplicationRuleProtocol `json:"protocols,omitempty"` - // TargetFqdns - List of FQDNs for this rule. - TargetFqdns *[]string `json:"targetFqdns,omitempty"` - // FqdnTags - List of FQDN Tags for this rule. - FqdnTags *[]string `json:"fqdnTags,omitempty"` -} - -// AzureFirewallApplicationRuleCollection application rule collection resource -type AzureFirewallApplicationRuleCollection struct { - *AzureFirewallApplicationRuleCollectionPropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallApplicationRuleCollection. -func (afarc AzureFirewallApplicationRuleCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afarc.AzureFirewallApplicationRuleCollectionPropertiesFormat != nil { - objectMap["properties"] = afarc.AzureFirewallApplicationRuleCollectionPropertiesFormat - } - if afarc.Name != nil { - objectMap["name"] = afarc.Name - } - if afarc.ID != nil { - objectMap["id"] = afarc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallApplicationRuleCollection struct. -func (afarc *AzureFirewallApplicationRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallApplicationRuleCollectionPropertiesFormat AzureFirewallApplicationRuleCollectionPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallApplicationRuleCollectionPropertiesFormat) - if err != nil { - return err - } - afarc.AzureFirewallApplicationRuleCollectionPropertiesFormat = &azureFirewallApplicationRuleCollectionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afarc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afarc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afarc.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallApplicationRuleCollectionPropertiesFormat properties of the application rule collection. -type AzureFirewallApplicationRuleCollectionPropertiesFormat struct { - // Priority - Priority of the application rule collection resource. - Priority *int32 `json:"priority,omitempty"` - // Action - The action type of a rule collection - Action *AzureFirewallRCAction `json:"action,omitempty"` - // Rules - Collection of rules used by a application rule collection. - Rules *[]AzureFirewallApplicationRule `json:"rules,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// AzureFirewallApplicationRuleProtocol properties of the application rule protocol. -type AzureFirewallApplicationRuleProtocol struct { - // ProtocolType - Protocol type. Possible values include: 'AzureFirewallApplicationRuleProtocolTypeHTTP', 'AzureFirewallApplicationRuleProtocolTypeHTTPS' - ProtocolType AzureFirewallApplicationRuleProtocolType `json:"protocolType,omitempty"` - // Port - Port number for the protocol, cannot be greater than 64000. This field is optional. - Port *int32 `json:"port,omitempty"` -} - -// AzureFirewallFqdnTag azure Firewall FQDN Tag Resource -type AzureFirewallFqdnTag struct { - *AzureFirewallFqdnTagPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallFqdnTag. -func (afft AzureFirewallFqdnTag) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afft.AzureFirewallFqdnTagPropertiesFormat != nil { - objectMap["properties"] = afft.AzureFirewallFqdnTagPropertiesFormat - } - if afft.ID != nil { - objectMap["id"] = afft.ID - } - if afft.Location != nil { - objectMap["location"] = afft.Location - } - if afft.Tags != nil { - objectMap["tags"] = afft.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallFqdnTag struct. -func (afft *AzureFirewallFqdnTag) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallFqdnTagPropertiesFormat AzureFirewallFqdnTagPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallFqdnTagPropertiesFormat) - if err != nil { - return err - } - afft.AzureFirewallFqdnTagPropertiesFormat = &azureFirewallFqdnTagPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afft.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afft.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afft.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - afft.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - afft.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - afft.Tags = tags - } - } - } - - return nil -} - -// AzureFirewallFqdnTagListResult response for ListAzureFirewallFqdnTags API service call. -type AzureFirewallFqdnTagListResult struct { - autorest.Response `json:"-"` - // Value - List of Azure Firewall FQDN Tags in a resource group. - Value *[]AzureFirewallFqdnTag `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AzureFirewallFqdnTagListResultIterator provides access to a complete listing of AzureFirewallFqdnTag -// values. -type AzureFirewallFqdnTagListResultIterator struct { - i int - page AzureFirewallFqdnTagListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AzureFirewallFqdnTagListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AzureFirewallFqdnTagListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AzureFirewallFqdnTagListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AzureFirewallFqdnTagListResultIterator) Response() AzureFirewallFqdnTagListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AzureFirewallFqdnTagListResultIterator) Value() AzureFirewallFqdnTag { - if !iter.page.NotDone() { - return AzureFirewallFqdnTag{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AzureFirewallFqdnTagListResultIterator type. -func NewAzureFirewallFqdnTagListResultIterator(page AzureFirewallFqdnTagListResultPage) AzureFirewallFqdnTagListResultIterator { - return AzureFirewallFqdnTagListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (afftlr AzureFirewallFqdnTagListResult) IsEmpty() bool { - return afftlr.Value == nil || len(*afftlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (afftlr AzureFirewallFqdnTagListResult) hasNextLink() bool { - return afftlr.NextLink != nil && len(*afftlr.NextLink) != 0 -} - -// azureFirewallFqdnTagListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (afftlr AzureFirewallFqdnTagListResult) azureFirewallFqdnTagListResultPreparer(ctx context.Context) (*http.Request, error) { - if !afftlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(afftlr.NextLink))) -} - -// AzureFirewallFqdnTagListResultPage contains a page of AzureFirewallFqdnTag values. -type AzureFirewallFqdnTagListResultPage struct { - fn func(context.Context, AzureFirewallFqdnTagListResult) (AzureFirewallFqdnTagListResult, error) - afftlr AzureFirewallFqdnTagListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AzureFirewallFqdnTagListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.afftlr) - if err != nil { - return err - } - page.afftlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AzureFirewallFqdnTagListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AzureFirewallFqdnTagListResultPage) NotDone() bool { - return !page.afftlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AzureFirewallFqdnTagListResultPage) Response() AzureFirewallFqdnTagListResult { - return page.afftlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AzureFirewallFqdnTagListResultPage) Values() []AzureFirewallFqdnTag { - if page.afftlr.IsEmpty() { - return nil - } - return *page.afftlr.Value -} - -// Creates a new instance of the AzureFirewallFqdnTagListResultPage type. -func NewAzureFirewallFqdnTagListResultPage(cur AzureFirewallFqdnTagListResult, getNextPage func(context.Context, AzureFirewallFqdnTagListResult) (AzureFirewallFqdnTagListResult, error)) AzureFirewallFqdnTagListResultPage { - return AzureFirewallFqdnTagListResultPage{ - fn: getNextPage, - afftlr: cur, - } -} - -// AzureFirewallFqdnTagPropertiesFormat azure Firewall FQDN Tag Properties -type AzureFirewallFqdnTagPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` - // FqdnTagName - READ-ONLY; The name of this FQDN Tag. - FqdnTagName *string `json:"fqdnTagName,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallFqdnTagPropertiesFormat. -func (afftpf AzureFirewallFqdnTagPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// AzureFirewallIPConfiguration IP configuration of an Azure Firewall. -type AzureFirewallIPConfiguration struct { - *AzureFirewallIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallIPConfiguration. -func (afic AzureFirewallIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afic.AzureFirewallIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = afic.AzureFirewallIPConfigurationPropertiesFormat - } - if afic.Name != nil { - objectMap["name"] = afic.Name - } - if afic.ID != nil { - objectMap["id"] = afic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallIPConfiguration struct. -func (afic *AzureFirewallIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallIPConfigurationPropertiesFormat AzureFirewallIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallIPConfigurationPropertiesFormat) - if err != nil { - return err - } - afic.AzureFirewallIPConfigurationPropertiesFormat = &azureFirewallIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afic.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallIPConfigurationPropertiesFormat properties of IP configuration of an Azure Firewall. -type AzureFirewallIPConfigurationPropertiesFormat struct { - // PrivateIPAddress - READ-ONLY; The Firewall Internal Load Balancer IP to be used as the next hop in User Defined Routes. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // Subnet - Reference of the subnet resource. This resource must be named 'AzureFirewallSubnet'. - Subnet *SubResource `json:"subnet,omitempty"` - // PublicIPAddress - Reference of the PublicIP resource. This field is a mandatory input if subnet is not null. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallIPConfigurationPropertiesFormat. -func (aficpf AzureFirewallIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if aficpf.Subnet != nil { - objectMap["subnet"] = aficpf.Subnet - } - if aficpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = aficpf.PublicIPAddress - } - if aficpf.ProvisioningState != "" { - objectMap["provisioningState"] = aficpf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// AzureFirewallListResult response for ListAzureFirewalls API service call. -type AzureFirewallListResult struct { - autorest.Response `json:"-"` - // Value - List of Azure Firewalls in a resource group. - Value *[]AzureFirewall `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AzureFirewallListResultIterator provides access to a complete listing of AzureFirewall values. -type AzureFirewallListResultIterator struct { - i int - page AzureFirewallListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AzureFirewallListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AzureFirewallListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AzureFirewallListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AzureFirewallListResultIterator) Response() AzureFirewallListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AzureFirewallListResultIterator) Value() AzureFirewall { - if !iter.page.NotDone() { - return AzureFirewall{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AzureFirewallListResultIterator type. -func NewAzureFirewallListResultIterator(page AzureFirewallListResultPage) AzureFirewallListResultIterator { - return AzureFirewallListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (aflr AzureFirewallListResult) IsEmpty() bool { - return aflr.Value == nil || len(*aflr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (aflr AzureFirewallListResult) hasNextLink() bool { - return aflr.NextLink != nil && len(*aflr.NextLink) != 0 -} - -// azureFirewallListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (aflr AzureFirewallListResult) azureFirewallListResultPreparer(ctx context.Context) (*http.Request, error) { - if !aflr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(aflr.NextLink))) -} - -// AzureFirewallListResultPage contains a page of AzureFirewall values. -type AzureFirewallListResultPage struct { - fn func(context.Context, AzureFirewallListResult) (AzureFirewallListResult, error) - aflr AzureFirewallListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AzureFirewallListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.aflr) - if err != nil { - return err - } - page.aflr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AzureFirewallListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AzureFirewallListResultPage) NotDone() bool { - return !page.aflr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AzureFirewallListResultPage) Response() AzureFirewallListResult { - return page.aflr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AzureFirewallListResultPage) Values() []AzureFirewall { - if page.aflr.IsEmpty() { - return nil - } - return *page.aflr.Value -} - -// Creates a new instance of the AzureFirewallListResultPage type. -func NewAzureFirewallListResultPage(cur AzureFirewallListResult, getNextPage func(context.Context, AzureFirewallListResult) (AzureFirewallListResult, error)) AzureFirewallListResultPage { - return AzureFirewallListResultPage{ - fn: getNextPage, - aflr: cur, - } -} - -// AzureFirewallNatRCAction azureFirewall NAT Rule Collection Action. -type AzureFirewallNatRCAction struct { - // Type - The type of action. Possible values include: 'Snat', 'Dnat' - Type AzureFirewallNatRCActionType `json:"type,omitempty"` -} - -// AzureFirewallNatRule properties of a NAT rule. -type AzureFirewallNatRule struct { - // Name - Name of the NAT rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses for this rule. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // DestinationPorts - List of destination ports. - DestinationPorts *[]string `json:"destinationPorts,omitempty"` - // Protocols - Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule. - Protocols *[]AzureFirewallNetworkRuleProtocol `json:"protocols,omitempty"` - // TranslatedAddress - The translated address for this NAT rule. - TranslatedAddress *string `json:"translatedAddress,omitempty"` - // TranslatedPort - The translated port for this NAT rule. - TranslatedPort *string `json:"translatedPort,omitempty"` -} - -// AzureFirewallNatRuleCollection NAT rule collection resource -type AzureFirewallNatRuleCollection struct { - *AzureFirewallNatRuleCollectionProperties `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallNatRuleCollection. -func (afnrc AzureFirewallNatRuleCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afnrc.AzureFirewallNatRuleCollectionProperties != nil { - objectMap["properties"] = afnrc.AzureFirewallNatRuleCollectionProperties - } - if afnrc.Name != nil { - objectMap["name"] = afnrc.Name - } - if afnrc.ID != nil { - objectMap["id"] = afnrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallNatRuleCollection struct. -func (afnrc *AzureFirewallNatRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallNatRuleCollectionProperties AzureFirewallNatRuleCollectionProperties - err = json.Unmarshal(*v, &azureFirewallNatRuleCollectionProperties) - if err != nil { - return err - } - afnrc.AzureFirewallNatRuleCollectionProperties = &azureFirewallNatRuleCollectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afnrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afnrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afnrc.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallNatRuleCollectionProperties properties of the NAT rule collection. -type AzureFirewallNatRuleCollectionProperties struct { - // Priority - Priority of the NAT rule collection resource. - Priority *int32 `json:"priority,omitempty"` - // Action - The action type of a NAT rule collection - Action *AzureFirewallNatRCAction `json:"action,omitempty"` - // Rules - Collection of rules used by a NAT rule collection. - Rules *[]AzureFirewallNatRule `json:"rules,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// AzureFirewallNetworkRule properties of the network rule. -type AzureFirewallNetworkRule struct { - // Name - Name of the network rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // Protocols - Array of AzureFirewallNetworkRuleProtocols. - Protocols *[]AzureFirewallNetworkRuleProtocol `json:"protocols,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // DestinationPorts - List of destination ports. - DestinationPorts *[]string `json:"destinationPorts,omitempty"` -} - -// AzureFirewallNetworkRuleCollection network rule collection resource -type AzureFirewallNetworkRuleCollection struct { - *AzureFirewallNetworkRuleCollectionPropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallNetworkRuleCollection. -func (afnrc AzureFirewallNetworkRuleCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afnrc.AzureFirewallNetworkRuleCollectionPropertiesFormat != nil { - objectMap["properties"] = afnrc.AzureFirewallNetworkRuleCollectionPropertiesFormat - } - if afnrc.Name != nil { - objectMap["name"] = afnrc.Name - } - if afnrc.ID != nil { - objectMap["id"] = afnrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallNetworkRuleCollection struct. -func (afnrc *AzureFirewallNetworkRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallNetworkRuleCollectionPropertiesFormat AzureFirewallNetworkRuleCollectionPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallNetworkRuleCollectionPropertiesFormat) - if err != nil { - return err - } - afnrc.AzureFirewallNetworkRuleCollectionPropertiesFormat = &azureFirewallNetworkRuleCollectionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afnrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afnrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afnrc.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallNetworkRuleCollectionPropertiesFormat properties of the network rule collection. -type AzureFirewallNetworkRuleCollectionPropertiesFormat struct { - // Priority - Priority of the network rule collection resource. - Priority *int32 `json:"priority,omitempty"` - // Action - The action type of a rule collection - Action *AzureFirewallRCAction `json:"action,omitempty"` - // Rules - Collection of rules used by a network rule collection. - Rules *[]AzureFirewallNetworkRule `json:"rules,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// AzureFirewallPropertiesFormat properties of the Azure Firewall. -type AzureFirewallPropertiesFormat struct { - // ApplicationRuleCollections - Collection of application rule collections used by Azure Firewall. - ApplicationRuleCollections *[]AzureFirewallApplicationRuleCollection `json:"applicationRuleCollections,omitempty"` - // NatRuleCollections - Collection of NAT rule collections used by Azure Firewall. - NatRuleCollections *[]AzureFirewallNatRuleCollection `json:"natRuleCollections,omitempty"` - // NetworkRuleCollections - Collection of network rule collections used by Azure Firewall. - NetworkRuleCollections *[]AzureFirewallNetworkRuleCollection `json:"networkRuleCollections,omitempty"` - // IPConfigurations - IP configuration of the Azure Firewall resource. - IPConfigurations *[]AzureFirewallIPConfiguration `json:"ipConfigurations,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// AzureFirewallRCAction properties of the AzureFirewallRCAction. -type AzureFirewallRCAction struct { - // Type - The type of action. Possible values include: 'AzureFirewallRCActionTypeAllow', 'AzureFirewallRCActionTypeDeny' - Type AzureFirewallRCActionType `json:"type,omitempty"` -} - -// AzureFirewallsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type AzureFirewallsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AzureFirewallsClient) (AzureFirewall, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AzureFirewallsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AzureFirewallsCreateOrUpdateFuture.Result. -func (future *AzureFirewallsCreateOrUpdateFuture) result(client AzureFirewallsClient) (af AzureFirewall, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - af.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AzureFirewallsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if af.Response.Response, err = future.GetResult(sender); err == nil && af.Response.Response.StatusCode != http.StatusNoContent { - af, err = client.CreateOrUpdateResponder(af.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsCreateOrUpdateFuture", "Result", af.Response.Response, "Failure responding to request") - } - } - return -} - -// AzureFirewallsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AzureFirewallsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AzureFirewallsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AzureFirewallsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AzureFirewallsDeleteFuture.Result. -func (future *AzureFirewallsDeleteFuture) result(client AzureFirewallsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AzureFirewallsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AzureReachabilityReport azure reachability report details. -type AzureReachabilityReport struct { - autorest.Response `json:"-"` - // AggregationLevel - The aggregation level of Azure reachability report. Can be Country, State or City. - AggregationLevel *string `json:"aggregationLevel,omitempty"` - ProviderLocation *AzureReachabilityReportLocation `json:"providerLocation,omitempty"` - // ReachabilityReport - List of Azure reachability report items. - ReachabilityReport *[]AzureReachabilityReportItem `json:"reachabilityReport,omitempty"` -} - -// AzureReachabilityReportItem azure reachability report details for a given provider location. -type AzureReachabilityReportItem struct { - // Provider - The Internet service provider. - Provider *string `json:"provider,omitempty"` - // AzureLocation - The Azure region. - AzureLocation *string `json:"azureLocation,omitempty"` - // Latencies - List of latency details for each of the time series. - Latencies *[]AzureReachabilityReportLatencyInfo `json:"latencies,omitempty"` -} - -// AzureReachabilityReportLatencyInfo details on latency for a time series. -type AzureReachabilityReportLatencyInfo struct { - // TimeStamp - The time stamp. - TimeStamp *date.Time `json:"timeStamp,omitempty"` - // Score - The relative latency score between 1 and 100, higher values indicating a faster connection. - Score *int32 `json:"score,omitempty"` -} - -// AzureReachabilityReportLocation parameters that define a geographic location. -type AzureReachabilityReportLocation struct { - // Country - The name of the country. - Country *string `json:"country,omitempty"` - // State - The name of the state. - State *string `json:"state,omitempty"` - // City - The name of the city or town. - City *string `json:"city,omitempty"` -} - -// AzureReachabilityReportParameters geographic and time constraints for Azure reachability report. -type AzureReachabilityReportParameters struct { - ProviderLocation *AzureReachabilityReportLocation `json:"providerLocation,omitempty"` - // Providers - List of Internet service providers. - Providers *[]string `json:"providers,omitempty"` - // AzureLocations - Optional Azure regions to scope the query to. - AzureLocations *[]string `json:"azureLocations,omitempty"` - // StartTime - The start time for the Azure reachability report. - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - The end time for the Azure reachability report. - EndTime *date.Time `json:"endTime,omitempty"` -} - -// BackendAddressPool pool of backend IP addresses. -type BackendAddressPool struct { - autorest.Response `json:"-"` - // BackendAddressPoolPropertiesFormat - Properties of load balancer backend address pool. - *BackendAddressPoolPropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackendAddressPool. -func (bap BackendAddressPool) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bap.BackendAddressPoolPropertiesFormat != nil { - objectMap["properties"] = bap.BackendAddressPoolPropertiesFormat - } - if bap.Name != nil { - objectMap["name"] = bap.Name - } - if bap.Etag != nil { - objectMap["etag"] = bap.Etag - } - if bap.ID != nil { - objectMap["id"] = bap.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BackendAddressPool struct. -func (bap *BackendAddressPool) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var backendAddressPoolPropertiesFormat BackendAddressPoolPropertiesFormat - err = json.Unmarshal(*v, &backendAddressPoolPropertiesFormat) - if err != nil { - return err - } - bap.BackendAddressPoolPropertiesFormat = &backendAddressPoolPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bap.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - bap.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bap.ID = &ID - } - } - } - - return nil -} - -// BackendAddressPoolPropertiesFormat properties of the backend address pool. -type BackendAddressPoolPropertiesFormat struct { - // BackendIPConfigurations - READ-ONLY; Gets collection of references to IP addresses defined in network interfaces. - BackendIPConfigurations *[]InterfaceIPConfiguration `json:"backendIPConfigurations,omitempty"` - // LoadBalancingRules - READ-ONLY; Gets load balancing rules that use this backend address pool. - LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` - // OutboundRule - READ-ONLY; Gets outbound rules that use this backend address pool. - OutboundRule *SubResource `json:"outboundRule,omitempty"` - // OutboundRules - READ-ONLY; Gets outbound rules that use this backend address pool. - OutboundRules *[]SubResource `json:"outboundRules,omitempty"` - // ProvisioningState - Get provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackendAddressPoolPropertiesFormat. -func (bappf BackendAddressPoolPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bappf.ProvisioningState != nil { - objectMap["provisioningState"] = bappf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// BGPCommunity contains bgp community information offered in Service Community resources. -type BGPCommunity struct { - // ServiceSupportedRegion - The region which the service support. e.g. For O365, region is Global. - ServiceSupportedRegion *string `json:"serviceSupportedRegion,omitempty"` - // CommunityName - The name of the bgp community. e.g. Skype. - CommunityName *string `json:"communityName,omitempty"` - // CommunityValue - The value of the bgp community. For more information: https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing. - CommunityValue *string `json:"communityValue,omitempty"` - // CommunityPrefixes - The prefixes that the bgp community contains. - CommunityPrefixes *[]string `json:"communityPrefixes,omitempty"` - // IsAuthorizedToUse - Customer is authorized to use bgp community or not. - IsAuthorizedToUse *bool `json:"isAuthorizedToUse,omitempty"` - // ServiceGroup - The service group of the bgp community contains. - ServiceGroup *string `json:"serviceGroup,omitempty"` -} - -// BgpPeerStatus BGP peer status details -type BgpPeerStatus struct { - // LocalAddress - READ-ONLY; The virtual network gateway's local address - LocalAddress *string `json:"localAddress,omitempty"` - // Neighbor - READ-ONLY; The remote BGP peer - Neighbor *string `json:"neighbor,omitempty"` - // Asn - READ-ONLY; The autonomous system number of the remote BGP peer - Asn *int32 `json:"asn,omitempty"` - // State - READ-ONLY; The BGP peer state. Possible values include: 'BgpPeerStateUnknown', 'BgpPeerStateStopped', 'BgpPeerStateIdle', 'BgpPeerStateConnecting', 'BgpPeerStateConnected' - State BgpPeerState `json:"state,omitempty"` - // ConnectedDuration - READ-ONLY; For how long the peering has been up - ConnectedDuration *string `json:"connectedDuration,omitempty"` - // RoutesReceived - READ-ONLY; The number of routes learned from this peer - RoutesReceived *int64 `json:"routesReceived,omitempty"` - // MessagesSent - READ-ONLY; The number of BGP messages sent - MessagesSent *int64 `json:"messagesSent,omitempty"` - // MessagesReceived - READ-ONLY; The number of BGP messages received - MessagesReceived *int64 `json:"messagesReceived,omitempty"` -} - -// MarshalJSON is the custom marshaler for BgpPeerStatus. -func (bps BgpPeerStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BgpPeerStatusListResult response for list BGP peer status API service call -type BgpPeerStatusListResult struct { - autorest.Response `json:"-"` - // Value - List of BGP peers - Value *[]BgpPeerStatus `json:"value,omitempty"` -} - -// BgpServiceCommunity service Community Properties. -type BgpServiceCommunity struct { - *BgpServiceCommunityPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for BgpServiceCommunity. -func (bsc BgpServiceCommunity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bsc.BgpServiceCommunityPropertiesFormat != nil { - objectMap["properties"] = bsc.BgpServiceCommunityPropertiesFormat - } - if bsc.ID != nil { - objectMap["id"] = bsc.ID - } - if bsc.Location != nil { - objectMap["location"] = bsc.Location - } - if bsc.Tags != nil { - objectMap["tags"] = bsc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BgpServiceCommunity struct. -func (bsc *BgpServiceCommunity) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var bgpServiceCommunityPropertiesFormat BgpServiceCommunityPropertiesFormat - err = json.Unmarshal(*v, &bgpServiceCommunityPropertiesFormat) - if err != nil { - return err - } - bsc.BgpServiceCommunityPropertiesFormat = &bgpServiceCommunityPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bsc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bsc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bsc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - bsc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - bsc.Tags = tags - } - } - } - - return nil -} - -// BgpServiceCommunityListResult response for the ListServiceCommunity API service call. -type BgpServiceCommunityListResult struct { - autorest.Response `json:"-"` - // Value - A list of service community resources. - Value *[]BgpServiceCommunity `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// BgpServiceCommunityListResultIterator provides access to a complete listing of BgpServiceCommunity -// values. -type BgpServiceCommunityListResultIterator struct { - i int - page BgpServiceCommunityListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *BgpServiceCommunityListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunityListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BgpServiceCommunityListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BgpServiceCommunityListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter BgpServiceCommunityListResultIterator) Response() BgpServiceCommunityListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter BgpServiceCommunityListResultIterator) Value() BgpServiceCommunity { - if !iter.page.NotDone() { - return BgpServiceCommunity{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BgpServiceCommunityListResultIterator type. -func NewBgpServiceCommunityListResultIterator(page BgpServiceCommunityListResultPage) BgpServiceCommunityListResultIterator { - return BgpServiceCommunityListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bsclr BgpServiceCommunityListResult) IsEmpty() bool { - return bsclr.Value == nil || len(*bsclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bsclr BgpServiceCommunityListResult) hasNextLink() bool { - return bsclr.NextLink != nil && len(*bsclr.NextLink) != 0 -} - -// bgpServiceCommunityListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bsclr BgpServiceCommunityListResult) bgpServiceCommunityListResultPreparer(ctx context.Context) (*http.Request, error) { - if !bsclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bsclr.NextLink))) -} - -// BgpServiceCommunityListResultPage contains a page of BgpServiceCommunity values. -type BgpServiceCommunityListResultPage struct { - fn func(context.Context, BgpServiceCommunityListResult) (BgpServiceCommunityListResult, error) - bsclr BgpServiceCommunityListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BgpServiceCommunityListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunityListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bsclr) - if err != nil { - return err - } - page.bsclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BgpServiceCommunityListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BgpServiceCommunityListResultPage) NotDone() bool { - return !page.bsclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BgpServiceCommunityListResultPage) Response() BgpServiceCommunityListResult { - return page.bsclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BgpServiceCommunityListResultPage) Values() []BgpServiceCommunity { - if page.bsclr.IsEmpty() { - return nil - } - return *page.bsclr.Value -} - -// Creates a new instance of the BgpServiceCommunityListResultPage type. -func NewBgpServiceCommunityListResultPage(cur BgpServiceCommunityListResult, getNextPage func(context.Context, BgpServiceCommunityListResult) (BgpServiceCommunityListResult, error)) BgpServiceCommunityListResultPage { - return BgpServiceCommunityListResultPage{ - fn: getNextPage, - bsclr: cur, - } -} - -// BgpServiceCommunityPropertiesFormat properties of Service Community. -type BgpServiceCommunityPropertiesFormat struct { - // ServiceName - The name of the bgp community. e.g. Skype. - ServiceName *string `json:"serviceName,omitempty"` - // BgpCommunities - Get a list of bgp communities. - BgpCommunities *[]BGPCommunity `json:"bgpCommunities,omitempty"` -} - -// BgpSettings BGP settings details -type BgpSettings struct { - // Asn - The BGP speaker's ASN. - Asn *int64 `json:"asn,omitempty"` - // BgpPeeringAddress - The BGP peering address and BGP identifier of this BGP speaker. - BgpPeeringAddress *string `json:"bgpPeeringAddress,omitempty"` - // PeerWeight - The weight added to routes learned from this BGP speaker. - PeerWeight *int32 `json:"peerWeight,omitempty"` -} - -// ConfigurationDiagnosticParameters parameters to get network configuration diagnostic. -type ConfigurationDiagnosticParameters struct { - // TargetResourceID - The ID of the target resource to perform network configuration diagnostic. Valid options are VM, NetworkInterface, VMSS/NetworkInterface and Application Gateway. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // VerbosityLevel - Verbosity level. Accepted values are 'Normal', 'Minimum', 'Full'. Possible values include: 'Normal', 'Minimum', 'Full' - VerbosityLevel VerbosityLevel `json:"verbosityLevel,omitempty"` - // Profiles - List of network configuration diagnostic profiles. - Profiles *[]ConfigurationDiagnosticProfile `json:"profiles,omitempty"` -} - -// ConfigurationDiagnosticProfile parameters to compare with network configuration. -type ConfigurationDiagnosticProfile struct { - // Direction - The direction of the traffic. Accepted values are 'Inbound' and 'Outbound'. Possible values include: 'Inbound', 'Outbound' - Direction Direction `json:"direction,omitempty"` - // Protocol - Protocol to be verified on. Accepted values are '*', TCP, UDP. - Protocol *string `json:"protocol,omitempty"` - // Source - Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag. - Source *string `json:"source,omitempty"` - // Destination - Traffic destination. Accepted values are: '*', IP Address/CIDR, Service Tag. - Destination *string `json:"destination,omitempty"` - // DestinationPort - Traffic destination port. Accepted values are '*', port (for example, 3389) and port range (for example, 80-100). - DestinationPort *string `json:"destinationPort,omitempty"` -} - -// ConfigurationDiagnosticResponse results of network configuration diagnostic on the target resource. -type ConfigurationDiagnosticResponse struct { - autorest.Response `json:"-"` - // Results - READ-ONLY; List of network configuration diagnostic results. - Results *[]ConfigurationDiagnosticResult `json:"results,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigurationDiagnosticResponse. -func (cdr ConfigurationDiagnosticResponse) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConfigurationDiagnosticResult network configuration diagnostic result corresponded to provided traffic -// query. -type ConfigurationDiagnosticResult struct { - Profile *ConfigurationDiagnosticProfile `json:"profile,omitempty"` - NetworkSecurityGroupResult *SecurityGroupResult `json:"networkSecurityGroupResult,omitempty"` -} - -// ConnectionMonitor parameters that define the operation to create a connection monitor. -type ConnectionMonitor struct { - // Location - Connection monitor location. - Location *string `json:"location,omitempty"` - // Tags - Connection monitor tags. - Tags map[string]*string `json:"tags"` - *ConnectionMonitorParameters `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectionMonitor. -func (cm ConnectionMonitor) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cm.Location != nil { - objectMap["location"] = cm.Location - } - if cm.Tags != nil { - objectMap["tags"] = cm.Tags - } - if cm.ConnectionMonitorParameters != nil { - objectMap["properties"] = cm.ConnectionMonitorParameters - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ConnectionMonitor struct. -func (cm *ConnectionMonitor) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cm.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cm.Tags = tags - } - case "properties": - if v != nil { - var connectionMonitorParameters ConnectionMonitorParameters - err = json.Unmarshal(*v, &connectionMonitorParameters) - if err != nil { - return err - } - cm.ConnectionMonitorParameters = &connectionMonitorParameters - } - } - } - - return nil -} - -// ConnectionMonitorDestination describes the destination of connection monitor. -type ConnectionMonitorDestination struct { - // ResourceID - The ID of the resource used as the destination by connection monitor. - ResourceID *string `json:"resourceId,omitempty"` - // Address - Address of the connection monitor destination (IP or domain name). - Address *string `json:"address,omitempty"` - // Port - The destination port used by connection monitor. - Port *int32 `json:"port,omitempty"` -} - -// ConnectionMonitorListResult list of connection monitors. -type ConnectionMonitorListResult struct { - autorest.Response `json:"-"` - // Value - Information about connection monitors. - Value *[]ConnectionMonitorResult `json:"value,omitempty"` -} - -// ConnectionMonitorParameters parameters that define the operation to create a connection monitor. -type ConnectionMonitorParameters struct { - Source *ConnectionMonitorSource `json:"source,omitempty"` - Destination *ConnectionMonitorDestination `json:"destination,omitempty"` - // AutoStart - Determines if the connection monitor will start automatically once created. - AutoStart *bool `json:"autoStart,omitempty"` - // MonitoringIntervalInSeconds - Monitoring interval in seconds. - MonitoringIntervalInSeconds *int32 `json:"monitoringIntervalInSeconds,omitempty"` -} - -// ConnectionMonitorQueryResult list of connection states snapshots. -type ConnectionMonitorQueryResult struct { - autorest.Response `json:"-"` - // SourceStatus - Status of connection monitor source. Possible values include: 'Uknown', 'Active', 'Inactive' - SourceStatus ConnectionMonitorSourceStatus `json:"sourceStatus,omitempty"` - // States - Information about connection states. - States *[]ConnectionStateSnapshot `json:"states,omitempty"` -} - -// ConnectionMonitorResult information about the connection monitor. -type ConnectionMonitorResult struct { - autorest.Response `json:"-"` - // Name - READ-ONLY; Name of the connection monitor. - Name *string `json:"name,omitempty"` - // ID - READ-ONLY; ID of the connection monitor. - ID *string `json:"id,omitempty"` - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Connection monitor type. - Type *string `json:"type,omitempty"` - // Location - Connection monitor location. - Location *string `json:"location,omitempty"` - // Tags - Connection monitor tags. - Tags map[string]*string `json:"tags"` - *ConnectionMonitorResultProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectionMonitorResult. -func (cmr ConnectionMonitorResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cmr.Etag != nil { - objectMap["etag"] = cmr.Etag - } - if cmr.Location != nil { - objectMap["location"] = cmr.Location - } - if cmr.Tags != nil { - objectMap["tags"] = cmr.Tags - } - if cmr.ConnectionMonitorResultProperties != nil { - objectMap["properties"] = cmr.ConnectionMonitorResultProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ConnectionMonitorResult struct. -func (cmr *ConnectionMonitorResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cmr.Name = &name - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cmr.ID = &ID - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cmr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cmr.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cmr.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cmr.Tags = tags - } - case "properties": - if v != nil { - var connectionMonitorResultProperties ConnectionMonitorResultProperties - err = json.Unmarshal(*v, &connectionMonitorResultProperties) - if err != nil { - return err - } - cmr.ConnectionMonitorResultProperties = &connectionMonitorResultProperties - } - } - } - - return nil -} - -// ConnectionMonitorResultProperties describes the properties of a connection monitor. -type ConnectionMonitorResultProperties struct { - // ProvisioningState - The provisioning state of the connection monitor. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // StartTime - The date and time when the connection monitor was started. - StartTime *date.Time `json:"startTime,omitempty"` - // MonitoringStatus - The monitoring status of the connection monitor. - MonitoringStatus *string `json:"monitoringStatus,omitempty"` - Source *ConnectionMonitorSource `json:"source,omitempty"` - Destination *ConnectionMonitorDestination `json:"destination,omitempty"` - // AutoStart - Determines if the connection monitor will start automatically once created. - AutoStart *bool `json:"autoStart,omitempty"` - // MonitoringIntervalInSeconds - Monitoring interval in seconds. - MonitoringIntervalInSeconds *int32 `json:"monitoringIntervalInSeconds,omitempty"` -} - -// ConnectionMonitorsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConnectionMonitorsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (ConnectionMonitorResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsCreateOrUpdateFuture.Result. -func (future *ConnectionMonitorsCreateOrUpdateFuture) result(client ConnectionMonitorsClient) (cmr ConnectionMonitorResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cmr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cmr.Response.Response, err = future.GetResult(sender); err == nil && cmr.Response.Response.StatusCode != http.StatusNoContent { - cmr, err = client.CreateOrUpdateResponder(cmr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsCreateOrUpdateFuture", "Result", cmr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConnectionMonitorsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConnectionMonitorsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsDeleteFuture.Result. -func (future *ConnectionMonitorsDeleteFuture) result(client ConnectionMonitorsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectionMonitorSource describes the source of connection monitor. -type ConnectionMonitorSource struct { - // ResourceID - The ID of the resource used as the source by connection monitor. - ResourceID *string `json:"resourceId,omitempty"` - // Port - The source port used by connection monitor. - Port *int32 `json:"port,omitempty"` -} - -// ConnectionMonitorsQueryFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConnectionMonitorsQueryFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (ConnectionMonitorQueryResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsQueryFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsQueryFuture.Result. -func (future *ConnectionMonitorsQueryFuture) result(client ConnectionMonitorsClient) (cmqr ConnectionMonitorQueryResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsQueryFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cmqr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsQueryFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cmqr.Response.Response, err = future.GetResult(sender); err == nil && cmqr.Response.Response.StatusCode != http.StatusNoContent { - cmqr, err = client.QueryResponder(cmqr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsQueryFuture", "Result", cmqr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConnectionMonitorsStartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConnectionMonitorsStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsStartFuture.Result. -func (future *ConnectionMonitorsStartFuture) result(client ConnectionMonitorsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsStartFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectionMonitorsStopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConnectionMonitorsStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsStopFuture.Result. -func (future *ConnectionMonitorsStopFuture) result(client ConnectionMonitorsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsStopFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectionResetSharedKey the virtual network connection reset shared key -type ConnectionResetSharedKey struct { - autorest.Response `json:"-"` - // KeyLength - The virtual network connection reset shared key length, should between 1 and 128. - KeyLength *int32 `json:"keyLength,omitempty"` -} - -// ConnectionSharedKey response for GetConnectionSharedKey API service call -type ConnectionSharedKey struct { - autorest.Response `json:"-"` - // Value - The virtual network connection shared key value. - Value *string `json:"value,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// ConnectionStateSnapshot connection state snapshot. -type ConnectionStateSnapshot struct { - // ConnectionState - The connection state. Possible values include: 'ConnectionStateReachable', 'ConnectionStateUnreachable', 'ConnectionStateUnknown' - ConnectionState ConnectionState `json:"connectionState,omitempty"` - // StartTime - The start time of the connection snapshot. - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - The end time of the connection snapshot. - EndTime *date.Time `json:"endTime,omitempty"` - // EvaluationState - Connectivity analysis evaluation state. Possible values include: 'NotStarted', 'InProgress', 'Completed' - EvaluationState EvaluationState `json:"evaluationState,omitempty"` - // AvgLatencyInMs - Average latency in ms. - AvgLatencyInMs *int32 `json:"avgLatencyInMs,omitempty"` - // MinLatencyInMs - Minimum latency in ms. - MinLatencyInMs *int32 `json:"minLatencyInMs,omitempty"` - // MaxLatencyInMs - Maximum latency in ms. - MaxLatencyInMs *int32 `json:"maxLatencyInMs,omitempty"` - // ProbesSent - The number of sent probes. - ProbesSent *int32 `json:"probesSent,omitempty"` - // ProbesFailed - The number of failed probes. - ProbesFailed *int32 `json:"probesFailed,omitempty"` - // Hops - READ-ONLY; List of hops between the source and the destination. - Hops *[]ConnectivityHop `json:"hops,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectionStateSnapshot. -func (CSS ConnectionStateSnapshot) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if CSS.ConnectionState != "" { - objectMap["connectionState"] = CSS.ConnectionState - } - if CSS.StartTime != nil { - objectMap["startTime"] = CSS.StartTime - } - if CSS.EndTime != nil { - objectMap["endTime"] = CSS.EndTime - } - if CSS.EvaluationState != "" { - objectMap["evaluationState"] = CSS.EvaluationState - } - if CSS.AvgLatencyInMs != nil { - objectMap["avgLatencyInMs"] = CSS.AvgLatencyInMs - } - if CSS.MinLatencyInMs != nil { - objectMap["minLatencyInMs"] = CSS.MinLatencyInMs - } - if CSS.MaxLatencyInMs != nil { - objectMap["maxLatencyInMs"] = CSS.MaxLatencyInMs - } - if CSS.ProbesSent != nil { - objectMap["probesSent"] = CSS.ProbesSent - } - if CSS.ProbesFailed != nil { - objectMap["probesFailed"] = CSS.ProbesFailed - } - return json.Marshal(objectMap) -} - -// ConnectivityDestination parameters that define destination of connection. -type ConnectivityDestination struct { - // ResourceID - The ID of the resource to which a connection attempt will be made. - ResourceID *string `json:"resourceId,omitempty"` - // Address - The IP address or URI the resource to which a connection attempt will be made. - Address *string `json:"address,omitempty"` - // Port - Port on which check connectivity will be performed. - Port *int32 `json:"port,omitempty"` -} - -// ConnectivityHop information about a hop between the source and the destination. -type ConnectivityHop struct { - // Type - READ-ONLY; The type of the hop. - Type *string `json:"type,omitempty"` - // ID - READ-ONLY; The ID of the hop. - ID *string `json:"id,omitempty"` - // Address - READ-ONLY; The IP address of the hop. - Address *string `json:"address,omitempty"` - // ResourceID - READ-ONLY; The ID of the resource corresponding to this hop. - ResourceID *string `json:"resourceId,omitempty"` - // NextHopIds - READ-ONLY; List of next hop identifiers. - NextHopIds *[]string `json:"nextHopIds,omitempty"` - // Issues - READ-ONLY; List of issues. - Issues *[]ConnectivityIssue `json:"issues,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityHop. -func (ch ConnectivityHop) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConnectivityInformation information on the connectivity status. -type ConnectivityInformation struct { - autorest.Response `json:"-"` - // Hops - READ-ONLY; List of hops between the source and the destination. - Hops *[]ConnectivityHop `json:"hops,omitempty"` - // ConnectionStatus - READ-ONLY; The connection status. Possible values include: 'ConnectionStatusUnknown', 'ConnectionStatusConnected', 'ConnectionStatusDisconnected', 'ConnectionStatusDegraded' - ConnectionStatus ConnectionStatus `json:"connectionStatus,omitempty"` - // AvgLatencyInMs - READ-ONLY; Average latency in milliseconds. - AvgLatencyInMs *int32 `json:"avgLatencyInMs,omitempty"` - // MinLatencyInMs - READ-ONLY; Minimum latency in milliseconds. - MinLatencyInMs *int32 `json:"minLatencyInMs,omitempty"` - // MaxLatencyInMs - READ-ONLY; Maximum latency in milliseconds. - MaxLatencyInMs *int32 `json:"maxLatencyInMs,omitempty"` - // ProbesSent - READ-ONLY; Total number of probes sent. - ProbesSent *int32 `json:"probesSent,omitempty"` - // ProbesFailed - READ-ONLY; Number of failed probes. - ProbesFailed *int32 `json:"probesFailed,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityInformation. -func (ci ConnectivityInformation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConnectivityIssue information about an issue encountered in the process of checking for connectivity. -type ConnectivityIssue struct { - // Origin - READ-ONLY; The origin of the issue. Possible values include: 'OriginLocal', 'OriginInbound', 'OriginOutbound' - Origin Origin `json:"origin,omitempty"` - // Severity - READ-ONLY; The severity of the issue. Possible values include: 'SeverityError', 'SeverityWarning' - Severity Severity `json:"severity,omitempty"` - // Type - READ-ONLY; The type of issue. Possible values include: 'IssueTypeUnknown', 'IssueTypeAgentStopped', 'IssueTypeGuestFirewall', 'IssueTypeDNSResolution', 'IssueTypeSocketBind', 'IssueTypeNetworkSecurityRule', 'IssueTypeUserDefinedRoute', 'IssueTypePortThrottled', 'IssueTypePlatform' - Type IssueType `json:"type,omitempty"` - // Context - READ-ONLY; Provides additional context on the issue. - Context *[]map[string]*string `json:"context,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityIssue. -func (ci ConnectivityIssue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConnectivityParameters parameters that determine how the connectivity check will be performed. -type ConnectivityParameters struct { - Source *ConnectivitySource `json:"source,omitempty"` - Destination *ConnectivityDestination `json:"destination,omitempty"` - // Protocol - Network protocol. Possible values include: 'ProtocolTCP', 'ProtocolHTTP', 'ProtocolHTTPS', 'ProtocolIcmp' - Protocol Protocol `json:"protocol,omitempty"` - ProtocolConfiguration *ProtocolConfiguration `json:"protocolConfiguration,omitempty"` -} - -// ConnectivitySource parameters that define the source of the connection. -type ConnectivitySource struct { - // ResourceID - The ID of the resource from which a connectivity check will be initiated. - ResourceID *string `json:"resourceId,omitempty"` - // Port - The source port from which a connectivity check will be performed. - Port *int32 `json:"port,omitempty"` -} - -// Container reference to container resource in remote resource provider. -type Container struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// ContainerNetworkInterface container network interface child resource. -type ContainerNetworkInterface struct { - // ContainerNetworkInterfacePropertiesFormat - Container network interface properties. - *ContainerNetworkInterfacePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterface. -func (cni ContainerNetworkInterface) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cni.ContainerNetworkInterfacePropertiesFormat != nil { - objectMap["properties"] = cni.ContainerNetworkInterfacePropertiesFormat - } - if cni.Name != nil { - objectMap["name"] = cni.Name - } - if cni.Etag != nil { - objectMap["etag"] = cni.Etag - } - if cni.ID != nil { - objectMap["id"] = cni.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerNetworkInterface struct. -func (cni *ContainerNetworkInterface) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var containerNetworkInterfacePropertiesFormat ContainerNetworkInterfacePropertiesFormat - err = json.Unmarshal(*v, &containerNetworkInterfacePropertiesFormat) - if err != nil { - return err - } - cni.ContainerNetworkInterfacePropertiesFormat = &containerNetworkInterfacePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cni.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cni.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cni.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cni.ID = &ID - } - } - } - - return nil -} - -// ContainerNetworkInterfaceConfiguration container network interface configuration child resource. -type ContainerNetworkInterfaceConfiguration struct { - // ContainerNetworkInterfaceConfigurationPropertiesFormat - Container network interface configuration properties. - *ContainerNetworkInterfaceConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceConfiguration. -func (cnic ContainerNetworkInterfaceConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cnic.ContainerNetworkInterfaceConfigurationPropertiesFormat != nil { - objectMap["properties"] = cnic.ContainerNetworkInterfaceConfigurationPropertiesFormat - } - if cnic.Name != nil { - objectMap["name"] = cnic.Name - } - if cnic.Etag != nil { - objectMap["etag"] = cnic.Etag - } - if cnic.ID != nil { - objectMap["id"] = cnic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerNetworkInterfaceConfiguration struct. -func (cnic *ContainerNetworkInterfaceConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var containerNetworkInterfaceConfigurationPropertiesFormat ContainerNetworkInterfaceConfigurationPropertiesFormat - err = json.Unmarshal(*v, &containerNetworkInterfaceConfigurationPropertiesFormat) - if err != nil { - return err - } - cnic.ContainerNetworkInterfaceConfigurationPropertiesFormat = &containerNetworkInterfaceConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cnic.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cnic.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cnic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cnic.ID = &ID - } - } - } - - return nil -} - -// ContainerNetworkInterfaceConfigurationPropertiesFormat container network interface configuration -// properties. -type ContainerNetworkInterfaceConfigurationPropertiesFormat struct { - // IPConfigurations - A list of ip configurations of the container network interface configuration. - IPConfigurations *[]IPConfigurationProfile `json:"ipConfigurations,omitempty"` - // ContainerNetworkInterfaces - A list of container network interfaces created from this container network interface configuration. - ContainerNetworkInterfaces *[]SubResource `json:"containerNetworkInterfaces,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceConfigurationPropertiesFormat. -func (cnicpf ContainerNetworkInterfaceConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cnicpf.IPConfigurations != nil { - objectMap["ipConfigurations"] = cnicpf.IPConfigurations - } - if cnicpf.ContainerNetworkInterfaces != nil { - objectMap["containerNetworkInterfaces"] = cnicpf.ContainerNetworkInterfaces - } - return json.Marshal(objectMap) -} - -// ContainerNetworkInterfaceIPConfiguration the ip configuration for a container network interface. -type ContainerNetworkInterfaceIPConfiguration struct { - // ContainerNetworkInterfaceIPConfigurationPropertiesFormat - Properties of the container network interface IP configuration. - *ContainerNetworkInterfaceIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceIPConfiguration. -func (cniic ContainerNetworkInterfaceIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cniic.ContainerNetworkInterfaceIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = cniic.ContainerNetworkInterfaceIPConfigurationPropertiesFormat - } - if cniic.Name != nil { - objectMap["name"] = cniic.Name - } - if cniic.Etag != nil { - objectMap["etag"] = cniic.Etag - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerNetworkInterfaceIPConfiguration struct. -func (cniic *ContainerNetworkInterfaceIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var containerNetworkInterfaceIPConfigurationPropertiesFormat ContainerNetworkInterfaceIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &containerNetworkInterfaceIPConfigurationPropertiesFormat) - if err != nil { - return err - } - cniic.ContainerNetworkInterfaceIPConfigurationPropertiesFormat = &containerNetworkInterfaceIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cniic.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cniic.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cniic.Etag = &etag - } - } - } - - return nil -} - -// ContainerNetworkInterfaceIPConfigurationPropertiesFormat properties of the container network interface -// IP configuration. -type ContainerNetworkInterfaceIPConfigurationPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceIPConfigurationPropertiesFormat. -func (cniicpf ContainerNetworkInterfaceIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ContainerNetworkInterfacePropertiesFormat ... -type ContainerNetworkInterfacePropertiesFormat struct { - // ContainerNetworkInterfaceConfiguration - Container network interface configuration from which this container network interface is created. - ContainerNetworkInterfaceConfiguration *ContainerNetworkInterfaceConfiguration `json:"containerNetworkInterfaceConfiguration,omitempty"` - // Container - Reference to the container to which this container network interface is attached. - Container *Container `json:"container,omitempty"` - // IPConfigurations - Reference to the ip configuration on this container nic. - IPConfigurations *[]ContainerNetworkInterfaceIPConfiguration `json:"ipConfigurations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfacePropertiesFormat. -func (cnipf ContainerNetworkInterfacePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cnipf.ContainerNetworkInterfaceConfiguration != nil { - objectMap["containerNetworkInterfaceConfiguration"] = cnipf.ContainerNetworkInterfaceConfiguration - } - if cnipf.Container != nil { - objectMap["container"] = cnipf.Container - } - if cnipf.IPConfigurations != nil { - objectMap["ipConfigurations"] = cnipf.IPConfigurations - } - return json.Marshal(objectMap) -} - -// DdosProtectionPlan a DDoS protection plan in a resource group. -type DdosProtectionPlan struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // DdosProtectionPlanPropertiesFormat - Properties of the DDoS protection plan. - *DdosProtectionPlanPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for DdosProtectionPlan. -func (dpp DdosProtectionPlan) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dpp.Location != nil { - objectMap["location"] = dpp.Location - } - if dpp.Tags != nil { - objectMap["tags"] = dpp.Tags - } - if dpp.DdosProtectionPlanPropertiesFormat != nil { - objectMap["properties"] = dpp.DdosProtectionPlanPropertiesFormat - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for DdosProtectionPlan struct. -func (dpp *DdosProtectionPlan) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - dpp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - dpp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - dpp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - dpp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - dpp.Tags = tags - } - case "properties": - if v != nil { - var ddosProtectionPlanPropertiesFormat DdosProtectionPlanPropertiesFormat - err = json.Unmarshal(*v, &ddosProtectionPlanPropertiesFormat) - if err != nil { - return err - } - dpp.DdosProtectionPlanPropertiesFormat = &ddosProtectionPlanPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - dpp.Etag = &etag - } - } - } - - return nil -} - -// DdosProtectionPlanListResult a list of DDoS protection plans. -type DdosProtectionPlanListResult struct { - autorest.Response `json:"-"` - // Value - A list of DDoS protection plans. - Value *[]DdosProtectionPlan `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for DdosProtectionPlanListResult. -func (dpplr DdosProtectionPlanListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dpplr.Value != nil { - objectMap["value"] = dpplr.Value - } - return json.Marshal(objectMap) -} - -// DdosProtectionPlanListResultIterator provides access to a complete listing of DdosProtectionPlan values. -type DdosProtectionPlanListResultIterator struct { - i int - page DdosProtectionPlanListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *DdosProtectionPlanListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlanListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DdosProtectionPlanListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DdosProtectionPlanListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter DdosProtectionPlanListResultIterator) Response() DdosProtectionPlanListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter DdosProtectionPlanListResultIterator) Value() DdosProtectionPlan { - if !iter.page.NotDone() { - return DdosProtectionPlan{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DdosProtectionPlanListResultIterator type. -func NewDdosProtectionPlanListResultIterator(page DdosProtectionPlanListResultPage) DdosProtectionPlanListResultIterator { - return DdosProtectionPlanListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dpplr DdosProtectionPlanListResult) IsEmpty() bool { - return dpplr.Value == nil || len(*dpplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dpplr DdosProtectionPlanListResult) hasNextLink() bool { - return dpplr.NextLink != nil && len(*dpplr.NextLink) != 0 -} - -// ddosProtectionPlanListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dpplr DdosProtectionPlanListResult) ddosProtectionPlanListResultPreparer(ctx context.Context) (*http.Request, error) { - if !dpplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dpplr.NextLink))) -} - -// DdosProtectionPlanListResultPage contains a page of DdosProtectionPlan values. -type DdosProtectionPlanListResultPage struct { - fn func(context.Context, DdosProtectionPlanListResult) (DdosProtectionPlanListResult, error) - dpplr DdosProtectionPlanListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DdosProtectionPlanListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlanListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dpplr) - if err != nil { - return err - } - page.dpplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DdosProtectionPlanListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DdosProtectionPlanListResultPage) NotDone() bool { - return !page.dpplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DdosProtectionPlanListResultPage) Response() DdosProtectionPlanListResult { - return page.dpplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DdosProtectionPlanListResultPage) Values() []DdosProtectionPlan { - if page.dpplr.IsEmpty() { - return nil - } - return *page.dpplr.Value -} - -// Creates a new instance of the DdosProtectionPlanListResultPage type. -func NewDdosProtectionPlanListResultPage(cur DdosProtectionPlanListResult, getNextPage func(context.Context, DdosProtectionPlanListResult) (DdosProtectionPlanListResult, error)) DdosProtectionPlanListResultPage { - return DdosProtectionPlanListResultPage{ - fn: getNextPage, - dpplr: cur, - } -} - -// DdosProtectionPlanPropertiesFormat dDoS protection plan properties. -type DdosProtectionPlanPropertiesFormat struct { - // ResourceGUID - READ-ONLY; The resource GUID property of the DDoS protection plan resource. It uniquely identifies the resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the DDoS protection plan resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // VirtualNetworks - READ-ONLY; The list of virtual networks associated with the DDoS protection plan resource. This list is read-only. - VirtualNetworks *[]SubResource `json:"virtualNetworks,omitempty"` -} - -// MarshalJSON is the custom marshaler for DdosProtectionPlanPropertiesFormat. -func (dpppf DdosProtectionPlanPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// DdosProtectionPlansCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DdosProtectionPlansCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DdosProtectionPlansClient) (DdosProtectionPlan, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DdosProtectionPlansCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DdosProtectionPlansCreateOrUpdateFuture.Result. -func (future *DdosProtectionPlansCreateOrUpdateFuture) result(client DdosProtectionPlansClient) (dpp DdosProtectionPlan, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dpp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DdosProtectionPlansCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dpp.Response.Response, err = future.GetResult(sender); err == nil && dpp.Response.Response.StatusCode != http.StatusNoContent { - dpp, err = client.CreateOrUpdateResponder(dpp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansCreateOrUpdateFuture", "Result", dpp.Response.Response, "Failure responding to request") - } - } - return -} - -// DdosProtectionPlansDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DdosProtectionPlansDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DdosProtectionPlansClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DdosProtectionPlansDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DdosProtectionPlansDeleteFuture.Result. -func (future *DdosProtectionPlansDeleteFuture) result(client DdosProtectionPlansClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DdosProtectionPlansDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// Delegation details the service to which the subnet is delegated. -type Delegation struct { - // ServiceDelegationPropertiesFormat - Properties of the subnet. - *ServiceDelegationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a subnet. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Delegation. -func (d Delegation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if d.ServiceDelegationPropertiesFormat != nil { - objectMap["properties"] = d.ServiceDelegationPropertiesFormat - } - if d.Name != nil { - objectMap["name"] = d.Name - } - if d.Etag != nil { - objectMap["etag"] = d.Etag - } - if d.ID != nil { - objectMap["id"] = d.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Delegation struct. -func (d *Delegation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceDelegationPropertiesFormat ServiceDelegationPropertiesFormat - err = json.Unmarshal(*v, &serviceDelegationPropertiesFormat) - if err != nil { - return err - } - d.ServiceDelegationPropertiesFormat = &serviceDelegationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - d.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - d.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - d.ID = &ID - } - } - } - - return nil -} - -// DeviceProperties list of properties of the device. -type DeviceProperties struct { - // DeviceVendor - Name of the device Vendor. - DeviceVendor *string `json:"deviceVendor,omitempty"` - // DeviceModel - Model of the device. - DeviceModel *string `json:"deviceModel,omitempty"` - // LinkSpeedInMbps - Link speed. - LinkSpeedInMbps *int32 `json:"linkSpeedInMbps,omitempty"` -} - -// DhcpOptions dhcpOptions contains an array of DNS servers available to VMs deployed in the virtual -// network. Standard DHCP option for a subnet overrides VNET DHCP options. -type DhcpOptions struct { - // DNSServers - The list of DNS servers IP addresses. - DNSServers *[]string `json:"dnsServers,omitempty"` -} - -// Dimension dimension of the metric. -type Dimension struct { - // Name - The name of the dimension. - Name *string `json:"name,omitempty"` - // DisplayName - The display name of the dimension. - DisplayName *string `json:"displayName,omitempty"` - // InternalName - The internal name of the dimension. - InternalName *string `json:"internalName,omitempty"` -} - -// DNSNameAvailabilityResult response for the CheckDnsNameAvailability API service call. -type DNSNameAvailabilityResult struct { - autorest.Response `json:"-"` - // Available - Domain availability (True/False). - Available *bool `json:"available,omitempty"` -} - -// EffectiveNetworkSecurityGroup effective network security group. -type EffectiveNetworkSecurityGroup struct { - // NetworkSecurityGroup - The ID of network security group that is applied. - NetworkSecurityGroup *SubResource `json:"networkSecurityGroup,omitempty"` - // Association - Associated resources. - Association *EffectiveNetworkSecurityGroupAssociation `json:"association,omitempty"` - // EffectiveSecurityRules - A collection of effective security rules. - EffectiveSecurityRules *[]EffectiveNetworkSecurityRule `json:"effectiveSecurityRules,omitempty"` - // TagMap - Mapping of tags to list of IP Addresses included within the tag. - TagMap map[string][]string `json:"tagMap"` -} - -// MarshalJSON is the custom marshaler for EffectiveNetworkSecurityGroup. -func (ensg EffectiveNetworkSecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ensg.NetworkSecurityGroup != nil { - objectMap["networkSecurityGroup"] = ensg.NetworkSecurityGroup - } - if ensg.Association != nil { - objectMap["association"] = ensg.Association - } - if ensg.EffectiveSecurityRules != nil { - objectMap["effectiveSecurityRules"] = ensg.EffectiveSecurityRules - } - if ensg.TagMap != nil { - objectMap["tagMap"] = ensg.TagMap - } - return json.Marshal(objectMap) -} - -// EffectiveNetworkSecurityGroupAssociation the effective network security group association. -type EffectiveNetworkSecurityGroupAssociation struct { - // Subnet - The ID of the subnet if assigned. - Subnet *SubResource `json:"subnet,omitempty"` - // NetworkInterface - The ID of the network interface if assigned. - NetworkInterface *SubResource `json:"networkInterface,omitempty"` -} - -// EffectiveNetworkSecurityGroupListResult response for list effective network security groups API service -// call. -type EffectiveNetworkSecurityGroupListResult struct { - autorest.Response `json:"-"` - // Value - A list of effective network security groups. - Value *[]EffectiveNetworkSecurityGroup `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for EffectiveNetworkSecurityGroupListResult. -func (ensglr EffectiveNetworkSecurityGroupListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ensglr.Value != nil { - objectMap["value"] = ensglr.Value - } - return json.Marshal(objectMap) -} - -// EffectiveNetworkSecurityRule effective network security rules. -type EffectiveNetworkSecurityRule struct { - // Name - The name of the security rule specified by the user (if created by the user). - Name *string `json:"name,omitempty"` - // Protocol - The network protocol this rule applies to. Possible values are: 'Tcp', 'Udp', and 'All'. Possible values include: 'EffectiveSecurityRuleProtocolTCP', 'EffectiveSecurityRuleProtocolUDP', 'EffectiveSecurityRuleProtocolAll' - Protocol EffectiveSecurityRuleProtocol `json:"protocol,omitempty"` - // SourcePortRange - The source port or range. - SourcePortRange *string `json:"sourcePortRange,omitempty"` - // DestinationPortRange - The destination port or range. - DestinationPortRange *string `json:"destinationPortRange,omitempty"` - // SourcePortRanges - The source port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*) - SourcePortRanges *[]string `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - The destination port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*) - DestinationPortRanges *[]string `json:"destinationPortRanges,omitempty"` - // SourceAddressPrefix - The source address prefix. - SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` - // DestinationAddressPrefix - The destination address prefix. - DestinationAddressPrefix *string `json:"destinationAddressPrefix,omitempty"` - // SourceAddressPrefixes - The source address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*). - SourceAddressPrefixes *[]string `json:"sourceAddressPrefixes,omitempty"` - // DestinationAddressPrefixes - The destination address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*). - DestinationAddressPrefixes *[]string `json:"destinationAddressPrefixes,omitempty"` - // ExpandedSourceAddressPrefix - The expanded source address prefix. - ExpandedSourceAddressPrefix *[]string `json:"expandedSourceAddressPrefix,omitempty"` - // ExpandedDestinationAddressPrefix - Expanded destination address prefix. - ExpandedDestinationAddressPrefix *[]string `json:"expandedDestinationAddressPrefix,omitempty"` - // Access - Whether network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'. Possible values include: 'SecurityRuleAccessAllow', 'SecurityRuleAccessDeny' - Access SecurityRuleAccess `json:"access,omitempty"` - // Priority - The priority of the rule. - Priority *int32 `json:"priority,omitempty"` - // Direction - The direction of the rule. Possible values are: 'Inbound and Outbound'. Possible values include: 'SecurityRuleDirectionInbound', 'SecurityRuleDirectionOutbound' - Direction SecurityRuleDirection `json:"direction,omitempty"` -} - -// EffectiveRoute effective Route -type EffectiveRoute struct { - // Name - The name of the user defined route. This is optional. - Name *string `json:"name,omitempty"` - // Source - Who created the route. Possible values are: 'Unknown', 'User', 'VirtualNetworkGateway', and 'Default'. Possible values include: 'EffectiveRouteSourceUnknown', 'EffectiveRouteSourceUser', 'EffectiveRouteSourceVirtualNetworkGateway', 'EffectiveRouteSourceDefault' - Source EffectiveRouteSource `json:"source,omitempty"` - // State - The value of effective route. Possible values are: 'Active' and 'Invalid'. Possible values include: 'EffectiveRouteStateActive', 'EffectiveRouteStateInvalid' - State EffectiveRouteState `json:"state,omitempty"` - // AddressPrefix - The address prefixes of the effective routes in CIDR notation. - AddressPrefix *[]string `json:"addressPrefix,omitempty"` - // NextHopIPAddress - The IP address of the next hop of the effective route. - NextHopIPAddress *[]string `json:"nextHopIpAddress,omitempty"` - // NextHopType - The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. Possible values include: 'RouteNextHopTypeVirtualNetworkGateway', 'RouteNextHopTypeVnetLocal', 'RouteNextHopTypeInternet', 'RouteNextHopTypeVirtualAppliance', 'RouteNextHopTypeNone' - NextHopType RouteNextHopType `json:"nextHopType,omitempty"` -} - -// EffectiveRouteListResult response for list effective route API service call. -type EffectiveRouteListResult struct { - autorest.Response `json:"-"` - // Value - A list of effective routes. - Value *[]EffectiveRoute `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for EffectiveRouteListResult. -func (erlr EffectiveRouteListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erlr.Value != nil { - objectMap["value"] = erlr.Value - } - return json.Marshal(objectMap) -} - -// EndpointService identifies the service being brought into the virtual network. -type EndpointService struct { - // ID - A unique identifier of the service being referenced by the interface endpoint. - ID *string `json:"id,omitempty"` -} - -// EndpointServiceResult endpoint service. -type EndpointServiceResult struct { - // Name - READ-ONLY; Name of the endpoint service. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the endpoint service. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for EndpointServiceResult. -func (esr EndpointServiceResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if esr.ID != nil { - objectMap["id"] = esr.ID - } - return json.Marshal(objectMap) -} - -// EndpointServicesListResult response for the ListAvailableEndpointServices API service call. -type EndpointServicesListResult struct { - autorest.Response `json:"-"` - // Value - List of available endpoint services in a region. - Value *[]EndpointServiceResult `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// EndpointServicesListResultIterator provides access to a complete listing of EndpointServiceResult -// values. -type EndpointServicesListResultIterator struct { - i int - page EndpointServicesListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *EndpointServicesListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/EndpointServicesListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *EndpointServicesListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter EndpointServicesListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter EndpointServicesListResultIterator) Response() EndpointServicesListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter EndpointServicesListResultIterator) Value() EndpointServiceResult { - if !iter.page.NotDone() { - return EndpointServiceResult{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the EndpointServicesListResultIterator type. -func NewEndpointServicesListResultIterator(page EndpointServicesListResultPage) EndpointServicesListResultIterator { - return EndpointServicesListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (eslr EndpointServicesListResult) IsEmpty() bool { - return eslr.Value == nil || len(*eslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (eslr EndpointServicesListResult) hasNextLink() bool { - return eslr.NextLink != nil && len(*eslr.NextLink) != 0 -} - -// endpointServicesListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (eslr EndpointServicesListResult) endpointServicesListResultPreparer(ctx context.Context) (*http.Request, error) { - if !eslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(eslr.NextLink))) -} - -// EndpointServicesListResultPage contains a page of EndpointServiceResult values. -type EndpointServicesListResultPage struct { - fn func(context.Context, EndpointServicesListResult) (EndpointServicesListResult, error) - eslr EndpointServicesListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *EndpointServicesListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/EndpointServicesListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.eslr) - if err != nil { - return err - } - page.eslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *EndpointServicesListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page EndpointServicesListResultPage) NotDone() bool { - return !page.eslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page EndpointServicesListResultPage) Response() EndpointServicesListResult { - return page.eslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page EndpointServicesListResultPage) Values() []EndpointServiceResult { - if page.eslr.IsEmpty() { - return nil - } - return *page.eslr.Value -} - -// Creates a new instance of the EndpointServicesListResultPage type. -func NewEndpointServicesListResultPage(cur EndpointServicesListResult, getNextPage func(context.Context, EndpointServicesListResult) (EndpointServicesListResult, error)) EndpointServicesListResultPage { - return EndpointServicesListResultPage{ - fn: getNextPage, - eslr: cur, - } -} - -// Error ... -type Error struct { - Code *string `json:"code,omitempty"` - Message *string `json:"message,omitempty"` - Target *string `json:"target,omitempty"` - Details *[]ErrorDetails `json:"details,omitempty"` - InnerError *string `json:"innerError,omitempty"` -} - -// ErrorDetails ... -type ErrorDetails struct { - Code *string `json:"code,omitempty"` - Target *string `json:"target,omitempty"` - Message *string `json:"message,omitempty"` -} - -// ErrorResponse the error object. -type ErrorResponse struct { - Error *ErrorDetails `json:"error,omitempty"` -} - -// EvaluatedNetworkSecurityGroup results of network security group evaluation. -type EvaluatedNetworkSecurityGroup struct { - // NetworkSecurityGroupID - Network security group ID. - NetworkSecurityGroupID *string `json:"networkSecurityGroupId,omitempty"` - // AppliedTo - Resource ID of nic or subnet to which network security group is applied. - AppliedTo *string `json:"appliedTo,omitempty"` - MatchedRule *MatchedRule `json:"matchedRule,omitempty"` - // RulesEvaluationResult - READ-ONLY; List of network security rules evaluation results. - RulesEvaluationResult *[]SecurityRulesEvaluationResult `json:"rulesEvaluationResult,omitempty"` -} - -// MarshalJSON is the custom marshaler for EvaluatedNetworkSecurityGroup. -func (ensg EvaluatedNetworkSecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ensg.NetworkSecurityGroupID != nil { - objectMap["networkSecurityGroupId"] = ensg.NetworkSecurityGroupID - } - if ensg.AppliedTo != nil { - objectMap["appliedTo"] = ensg.AppliedTo - } - if ensg.MatchedRule != nil { - objectMap["matchedRule"] = ensg.MatchedRule - } - return json.Marshal(objectMap) -} - -// ExpressRouteCircuit expressRouteCircuit resource -type ExpressRouteCircuit struct { - autorest.Response `json:"-"` - // Sku - The SKU. - Sku *ExpressRouteCircuitSku `json:"sku,omitempty"` - *ExpressRouteCircuitPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuit. -func (erc ExpressRouteCircuit) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erc.Sku != nil { - objectMap["sku"] = erc.Sku - } - if erc.ExpressRouteCircuitPropertiesFormat != nil { - objectMap["properties"] = erc.ExpressRouteCircuitPropertiesFormat - } - if erc.ID != nil { - objectMap["id"] = erc.ID - } - if erc.Location != nil { - objectMap["location"] = erc.Location - } - if erc.Tags != nil { - objectMap["tags"] = erc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuit struct. -func (erc *ExpressRouteCircuit) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku ExpressRouteCircuitSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - erc.Sku = &sku - } - case "properties": - if v != nil { - var expressRouteCircuitPropertiesFormat ExpressRouteCircuitPropertiesFormat - err = json.Unmarshal(*v, &expressRouteCircuitPropertiesFormat) - if err != nil { - return err - } - erc.ExpressRouteCircuitPropertiesFormat = &expressRouteCircuitPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erc.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteCircuitArpTable the ARP table associated with the ExpressRouteCircuit. -type ExpressRouteCircuitArpTable struct { - // Age - Entry age in minutes - Age *int32 `json:"age,omitempty"` - // Interface - Interface address - Interface *string `json:"interface,omitempty"` - // IPAddress - The IP address. - IPAddress *string `json:"ipAddress,omitempty"` - // MacAddress - The MAC address. - MacAddress *string `json:"macAddress,omitempty"` -} - -// ExpressRouteCircuitAuthorization authorization in an ExpressRouteCircuit resource. -type ExpressRouteCircuitAuthorization struct { - autorest.Response `json:"-"` - *AuthorizationPropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitAuthorization. -func (erca ExpressRouteCircuitAuthorization) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erca.AuthorizationPropertiesFormat != nil { - objectMap["properties"] = erca.AuthorizationPropertiesFormat - } - if erca.Name != nil { - objectMap["name"] = erca.Name - } - if erca.ID != nil { - objectMap["id"] = erca.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuitAuthorization struct. -func (erca *ExpressRouteCircuitAuthorization) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var authorizationPropertiesFormat AuthorizationPropertiesFormat - err = json.Unmarshal(*v, &authorizationPropertiesFormat) - if err != nil { - return err - } - erca.AuthorizationPropertiesFormat = &authorizationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erca.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erca.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erca.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitAuthorizationsClient) (ExpressRouteCircuitAuthorization, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture) result(client ExpressRouteCircuitAuthorizationsClient) (erca ExpressRouteCircuitAuthorization, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erca.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erca.Response.Response, err = future.GetResult(sender); err == nil && erca.Response.Response.StatusCode != http.StatusNoContent { - erca, err = client.CreateOrUpdateResponder(erca.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture", "Result", erca.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitAuthorizationsDeleteFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCircuitAuthorizationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitAuthorizationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitAuthorizationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitAuthorizationsDeleteFuture.Result. -func (future *ExpressRouteCircuitAuthorizationsDeleteFuture) result(client ExpressRouteCircuitAuthorizationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitAuthorizationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitConnection express Route Circuit Connection in an ExpressRouteCircuitPeering -// resource. -type ExpressRouteCircuitConnection struct { - autorest.Response `json:"-"` - *ExpressRouteCircuitConnectionPropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitConnection. -func (ercc ExpressRouteCircuitConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercc.ExpressRouteCircuitConnectionPropertiesFormat != nil { - objectMap["properties"] = ercc.ExpressRouteCircuitConnectionPropertiesFormat - } - if ercc.Name != nil { - objectMap["name"] = ercc.Name - } - if ercc.ID != nil { - objectMap["id"] = ercc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuitConnection struct. -func (ercc *ExpressRouteCircuitConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCircuitConnectionPropertiesFormat ExpressRouteCircuitConnectionPropertiesFormat - err = json.Unmarshal(*v, &expressRouteCircuitConnectionPropertiesFormat) - if err != nil { - return err - } - ercc.ExpressRouteCircuitConnectionPropertiesFormat = &expressRouteCircuitConnectionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ercc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ercc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ercc.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCircuitConnectionListResult response for ListConnections API service call retrieves all -// global reach connections that belongs to a Private Peering for an ExpressRouteCircuit. -type ExpressRouteCircuitConnectionListResult struct { - autorest.Response `json:"-"` - // Value - The global reach connection associated with Private Peering in an ExpressRoute Circuit. - Value *[]ExpressRouteCircuitConnection `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitConnectionListResultIterator provides access to a complete listing of -// ExpressRouteCircuitConnection values. -type ExpressRouteCircuitConnectionListResultIterator struct { - i int - page ExpressRouteCircuitConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCircuitConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCircuitConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCircuitConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCircuitConnectionListResultIterator) Response() ExpressRouteCircuitConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCircuitConnectionListResultIterator) Value() ExpressRouteCircuitConnection { - if !iter.page.NotDone() { - return ExpressRouteCircuitConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCircuitConnectionListResultIterator type. -func NewExpressRouteCircuitConnectionListResultIterator(page ExpressRouteCircuitConnectionListResultPage) ExpressRouteCircuitConnectionListResultIterator { - return ExpressRouteCircuitConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ercclr ExpressRouteCircuitConnectionListResult) IsEmpty() bool { - return ercclr.Value == nil || len(*ercclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ercclr ExpressRouteCircuitConnectionListResult) hasNextLink() bool { - return ercclr.NextLink != nil && len(*ercclr.NextLink) != 0 -} - -// expressRouteCircuitConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ercclr ExpressRouteCircuitConnectionListResult) expressRouteCircuitConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ercclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ercclr.NextLink))) -} - -// ExpressRouteCircuitConnectionListResultPage contains a page of ExpressRouteCircuitConnection values. -type ExpressRouteCircuitConnectionListResultPage struct { - fn func(context.Context, ExpressRouteCircuitConnectionListResult) (ExpressRouteCircuitConnectionListResult, error) - ercclr ExpressRouteCircuitConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCircuitConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ercclr) - if err != nil { - return err - } - page.ercclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCircuitConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCircuitConnectionListResultPage) NotDone() bool { - return !page.ercclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCircuitConnectionListResultPage) Response() ExpressRouteCircuitConnectionListResult { - return page.ercclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCircuitConnectionListResultPage) Values() []ExpressRouteCircuitConnection { - if page.ercclr.IsEmpty() { - return nil - } - return *page.ercclr.Value -} - -// Creates a new instance of the ExpressRouteCircuitConnectionListResultPage type. -func NewExpressRouteCircuitConnectionListResultPage(cur ExpressRouteCircuitConnectionListResult, getNextPage func(context.Context, ExpressRouteCircuitConnectionListResult) (ExpressRouteCircuitConnectionListResult, error)) ExpressRouteCircuitConnectionListResultPage { - return ExpressRouteCircuitConnectionListResultPage{ - fn: getNextPage, - ercclr: cur, - } -} - -// ExpressRouteCircuitConnectionPropertiesFormat ... -type ExpressRouteCircuitConnectionPropertiesFormat struct { - // ExpressRouteCircuitPeering - Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection. - ExpressRouteCircuitPeering *SubResource `json:"expressRouteCircuitPeering,omitempty"` - // PeerExpressRouteCircuitPeering - Reference to Express Route Circuit Private Peering Resource of the peered circuit. - PeerExpressRouteCircuitPeering *SubResource `json:"peerExpressRouteCircuitPeering,omitempty"` - // AddressPrefix - /29 IP address space to carve out Customer addresses for tunnels. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // AuthorizationKey - The authorization key. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // CircuitConnectionStatus - READ-ONLY; Express Route Circuit Connection State. Possible values are: 'Connected' and 'Disconnected'. Possible values include: 'Connected', 'Connecting', 'Disconnected' - CircuitConnectionStatus CircuitConnectionStatus `json:"circuitConnectionStatus,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the circuit connection resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitConnectionPropertiesFormat. -func (erccpf ExpressRouteCircuitConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccpf.ExpressRouteCircuitPeering != nil { - objectMap["expressRouteCircuitPeering"] = erccpf.ExpressRouteCircuitPeering - } - if erccpf.PeerExpressRouteCircuitPeering != nil { - objectMap["peerExpressRouteCircuitPeering"] = erccpf.PeerExpressRouteCircuitPeering - } - if erccpf.AddressPrefix != nil { - objectMap["addressPrefix"] = erccpf.AddressPrefix - } - if erccpf.AuthorizationKey != nil { - objectMap["authorizationKey"] = erccpf.AuthorizationKey - } - return json.Marshal(objectMap) -} - -// ExpressRouteCircuitConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCircuitConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitConnectionsClient) (ExpressRouteCircuitConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitConnectionsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitConnectionsCreateOrUpdateFuture) result(client ExpressRouteCircuitConnectionsClient) (ercc ExpressRouteCircuitConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercc.Response.Response, err = future.GetResult(sender); err == nil && ercc.Response.Response.StatusCode != http.StatusNoContent { - ercc, err = client.CreateOrUpdateResponder(ercc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsCreateOrUpdateFuture", "Result", ercc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitConnectionsDeleteFuture.Result. -func (future *ExpressRouteCircuitConnectionsDeleteFuture) result(client ExpressRouteCircuitConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitListResult response for ListExpressRouteCircuit API service call. -type ExpressRouteCircuitListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRouteCircuits in a resource group. - Value *[]ExpressRouteCircuit `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitListResultIterator provides access to a complete listing of ExpressRouteCircuit -// values. -type ExpressRouteCircuitListResultIterator struct { - i int - page ExpressRouteCircuitListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCircuitListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCircuitListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCircuitListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCircuitListResultIterator) Response() ExpressRouteCircuitListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCircuitListResultIterator) Value() ExpressRouteCircuit { - if !iter.page.NotDone() { - return ExpressRouteCircuit{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCircuitListResultIterator type. -func NewExpressRouteCircuitListResultIterator(page ExpressRouteCircuitListResultPage) ExpressRouteCircuitListResultIterator { - return ExpressRouteCircuitListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erclr ExpressRouteCircuitListResult) IsEmpty() bool { - return erclr.Value == nil || len(*erclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erclr ExpressRouteCircuitListResult) hasNextLink() bool { - return erclr.NextLink != nil && len(*erclr.NextLink) != 0 -} - -// expressRouteCircuitListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erclr ExpressRouteCircuitListResult) expressRouteCircuitListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erclr.NextLink))) -} - -// ExpressRouteCircuitListResultPage contains a page of ExpressRouteCircuit values. -type ExpressRouteCircuitListResultPage struct { - fn func(context.Context, ExpressRouteCircuitListResult) (ExpressRouteCircuitListResult, error) - erclr ExpressRouteCircuitListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCircuitListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erclr) - if err != nil { - return err - } - page.erclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCircuitListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCircuitListResultPage) NotDone() bool { - return !page.erclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCircuitListResultPage) Response() ExpressRouteCircuitListResult { - return page.erclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCircuitListResultPage) Values() []ExpressRouteCircuit { - if page.erclr.IsEmpty() { - return nil - } - return *page.erclr.Value -} - -// Creates a new instance of the ExpressRouteCircuitListResultPage type. -func NewExpressRouteCircuitListResultPage(cur ExpressRouteCircuitListResult, getNextPage func(context.Context, ExpressRouteCircuitListResult) (ExpressRouteCircuitListResult, error)) ExpressRouteCircuitListResultPage { - return ExpressRouteCircuitListResultPage{ - fn: getNextPage, - erclr: cur, - } -} - -// ExpressRouteCircuitPeering peering in an ExpressRouteCircuit resource. -type ExpressRouteCircuitPeering struct { - autorest.Response `json:"-"` - *ExpressRouteCircuitPeeringPropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitPeering. -func (ercp ExpressRouteCircuitPeering) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercp.ExpressRouteCircuitPeeringPropertiesFormat != nil { - objectMap["properties"] = ercp.ExpressRouteCircuitPeeringPropertiesFormat - } - if ercp.Name != nil { - objectMap["name"] = ercp.Name - } - if ercp.ID != nil { - objectMap["id"] = ercp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuitPeering struct. -func (ercp *ExpressRouteCircuitPeering) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCircuitPeeringPropertiesFormat ExpressRouteCircuitPeeringPropertiesFormat - err = json.Unmarshal(*v, &expressRouteCircuitPeeringPropertiesFormat) - if err != nil { - return err - } - ercp.ExpressRouteCircuitPeeringPropertiesFormat = &expressRouteCircuitPeeringPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ercp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ercp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ercp.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCircuitPeeringConfig specifies the peering configuration. -type ExpressRouteCircuitPeeringConfig struct { - // AdvertisedPublicPrefixes - The reference of AdvertisedPublicPrefixes. - AdvertisedPublicPrefixes *[]string `json:"advertisedPublicPrefixes,omitempty"` - // AdvertisedCommunities - The communities of bgp peering. Specified for microsoft peering - AdvertisedCommunities *[]string `json:"advertisedCommunities,omitempty"` - // AdvertisedPublicPrefixesState - AdvertisedPublicPrefixState of the Peering resource. Possible values are 'NotConfigured', 'Configuring', 'Configured', and 'ValidationNeeded'. Possible values include: 'NotConfigured', 'Configuring', 'Configured', 'ValidationNeeded' - AdvertisedPublicPrefixesState ExpressRouteCircuitPeeringAdvertisedPublicPrefixState `json:"advertisedPublicPrefixesState,omitempty"` - // LegacyMode - The legacy mode of the peering. - LegacyMode *int32 `json:"legacyMode,omitempty"` - // CustomerASN - The CustomerASN of the peering. - CustomerASN *int32 `json:"customerASN,omitempty"` - // RoutingRegistryName - The RoutingRegistryName of the configuration. - RoutingRegistryName *string `json:"routingRegistryName,omitempty"` -} - -// ExpressRouteCircuitPeeringID expressRoute circuit peering identifier. -type ExpressRouteCircuitPeeringID struct { - // ID - The ID of the ExpressRoute circuit peering. - ID *string `json:"id,omitempty"` -} - -// ExpressRouteCircuitPeeringListResult response for ListPeering API service call retrieves all peerings -// that belong to an ExpressRouteCircuit. -type ExpressRouteCircuitPeeringListResult struct { - autorest.Response `json:"-"` - // Value - The peerings in an express route circuit. - Value *[]ExpressRouteCircuitPeering `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitPeeringListResultIterator provides access to a complete listing of -// ExpressRouteCircuitPeering values. -type ExpressRouteCircuitPeeringListResultIterator struct { - i int - page ExpressRouteCircuitPeeringListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCircuitPeeringListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCircuitPeeringListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCircuitPeeringListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCircuitPeeringListResultIterator) Response() ExpressRouteCircuitPeeringListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCircuitPeeringListResultIterator) Value() ExpressRouteCircuitPeering { - if !iter.page.NotDone() { - return ExpressRouteCircuitPeering{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCircuitPeeringListResultIterator type. -func NewExpressRouteCircuitPeeringListResultIterator(page ExpressRouteCircuitPeeringListResultPage) ExpressRouteCircuitPeeringListResultIterator { - return ExpressRouteCircuitPeeringListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ercplr ExpressRouteCircuitPeeringListResult) IsEmpty() bool { - return ercplr.Value == nil || len(*ercplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ercplr ExpressRouteCircuitPeeringListResult) hasNextLink() bool { - return ercplr.NextLink != nil && len(*ercplr.NextLink) != 0 -} - -// expressRouteCircuitPeeringListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ercplr ExpressRouteCircuitPeeringListResult) expressRouteCircuitPeeringListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ercplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ercplr.NextLink))) -} - -// ExpressRouteCircuitPeeringListResultPage contains a page of ExpressRouteCircuitPeering values. -type ExpressRouteCircuitPeeringListResultPage struct { - fn func(context.Context, ExpressRouteCircuitPeeringListResult) (ExpressRouteCircuitPeeringListResult, error) - ercplr ExpressRouteCircuitPeeringListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCircuitPeeringListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ercplr) - if err != nil { - return err - } - page.ercplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCircuitPeeringListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCircuitPeeringListResultPage) NotDone() bool { - return !page.ercplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCircuitPeeringListResultPage) Response() ExpressRouteCircuitPeeringListResult { - return page.ercplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCircuitPeeringListResultPage) Values() []ExpressRouteCircuitPeering { - if page.ercplr.IsEmpty() { - return nil - } - return *page.ercplr.Value -} - -// Creates a new instance of the ExpressRouteCircuitPeeringListResultPage type. -func NewExpressRouteCircuitPeeringListResultPage(cur ExpressRouteCircuitPeeringListResult, getNextPage func(context.Context, ExpressRouteCircuitPeeringListResult) (ExpressRouteCircuitPeeringListResult, error)) ExpressRouteCircuitPeeringListResultPage { - return ExpressRouteCircuitPeeringListResultPage{ - fn: getNextPage, - ercplr: cur, - } -} - -// ExpressRouteCircuitPeeringPropertiesFormat ... -type ExpressRouteCircuitPeeringPropertiesFormat struct { - // PeeringType - The peering type. Possible values include: 'AzurePublicPeering', 'AzurePrivatePeering', 'MicrosoftPeering' - PeeringType ExpressRoutePeeringType `json:"peeringType,omitempty"` - // State - The peering state. Possible values include: 'ExpressRoutePeeringStateDisabled', 'ExpressRoutePeeringStateEnabled' - State ExpressRoutePeeringState `json:"state,omitempty"` - // AzureASN - The Azure ASN. - AzureASN *int32 `json:"azureASN,omitempty"` - // PeerASN - The peer ASN. - PeerASN *int64 `json:"peerASN,omitempty"` - // PrimaryPeerAddressPrefix - The primary address prefix. - PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` - // SecondaryPeerAddressPrefix - The secondary address prefix. - SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` - // PrimaryAzurePort - The primary port. - PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` - // SecondaryAzurePort - The secondary port. - SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` - // SharedKey - The shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // VlanID - The VLAN ID. - VlanID *int32 `json:"vlanId,omitempty"` - // MicrosoftPeeringConfig - The Microsoft peering configuration. - MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` - // Stats - Gets peering stats. - Stats *ExpressRouteCircuitStats `json:"stats,omitempty"` - // ProvisioningState - Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // GatewayManagerEtag - The GatewayManager Etag. - GatewayManagerEtag *string `json:"gatewayManagerEtag,omitempty"` - // LastModifiedBy - Gets whether the provider or the customer last modified the peering. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // RouteFilter - The reference of the RouteFilter resource. - RouteFilter *RouteFilter `json:"routeFilter,omitempty"` - // Ipv6PeeringConfig - The IPv6 peering configuration. - Ipv6PeeringConfig *Ipv6ExpressRouteCircuitPeeringConfig `json:"ipv6PeeringConfig,omitempty"` - // ExpressRouteConnection - The ExpressRoute connection. - ExpressRouteConnection *ExpressRouteConnectionID `json:"expressRouteConnection,omitempty"` - // Connections - The list of circuit connections associated with Azure Private Peering for this circuit. - Connections *[]ExpressRouteCircuitConnection `json:"connections,omitempty"` -} - -// ExpressRouteCircuitPeeringsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCircuitPeeringsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitPeeringsClient) (ExpressRouteCircuitPeering, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitPeeringsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitPeeringsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitPeeringsCreateOrUpdateFuture) result(client ExpressRouteCircuitPeeringsClient) (ercp ExpressRouteCircuitPeering, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitPeeringsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercp.Response.Response, err = future.GetResult(sender); err == nil && ercp.Response.Response.StatusCode != http.StatusNoContent { - ercp, err = client.CreateOrUpdateResponder(ercp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsCreateOrUpdateFuture", "Result", ercp.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitPeeringsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitPeeringsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitPeeringsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitPeeringsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitPeeringsDeleteFuture.Result. -func (future *ExpressRouteCircuitPeeringsDeleteFuture) result(client ExpressRouteCircuitPeeringsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitPeeringsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitPropertiesFormat properties of ExpressRouteCircuit. -type ExpressRouteCircuitPropertiesFormat struct { - // AllowClassicOperations - Allow classic operations - AllowClassicOperations *bool `json:"allowClassicOperations,omitempty"` - // CircuitProvisioningState - The CircuitProvisioningState state of the resource. - CircuitProvisioningState *string `json:"circuitProvisioningState,omitempty"` - // ServiceProviderProvisioningState - The ServiceProviderProvisioningState state of the resource. Possible values are 'NotProvisioned', 'Provisioning', 'Provisioned', and 'Deprovisioning'. Possible values include: 'NotProvisioned', 'Provisioning', 'Provisioned', 'Deprovisioning' - ServiceProviderProvisioningState ServiceProviderProvisioningState `json:"serviceProviderProvisioningState,omitempty"` - // Authorizations - The list of authorizations. - Authorizations *[]ExpressRouteCircuitAuthorization `json:"authorizations,omitempty"` - // Peerings - The list of peerings. - Peerings *[]ExpressRouteCircuitPeering `json:"peerings,omitempty"` - // ServiceKey - The ServiceKey. - ServiceKey *string `json:"serviceKey,omitempty"` - // ServiceProviderNotes - The ServiceProviderNotes. - ServiceProviderNotes *string `json:"serviceProviderNotes,omitempty"` - // ServiceProviderProperties - The ServiceProviderProperties. - ServiceProviderProperties *ExpressRouteCircuitServiceProviderProperties `json:"serviceProviderProperties,omitempty"` - // ExpressRoutePort - The reference to the ExpressRoutePort resource when the circuit is provisioned on an ExpressRoutePort resource. - ExpressRoutePort *SubResource `json:"expressRoutePort,omitempty"` - // BandwidthInGbps - The bandwidth of the circuit when the circuit is provisioned on an ExpressRoutePort resource. - BandwidthInGbps *float64 `json:"bandwidthInGbps,omitempty"` - // Stag - READ-ONLY; The identifier of the circuit traffic. Outer tag for QinQ encapsulation. - Stag *int32 `json:"stag,omitempty"` - // ProvisioningState - Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // GatewayManagerEtag - The GatewayManager Etag. - GatewayManagerEtag *string `json:"gatewayManagerEtag,omitempty"` - // AllowGlobalReach - Flag to enable Global Reach on the circuit. - AllowGlobalReach *bool `json:"allowGlobalReach,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitPropertiesFormat. -func (ercpf ExpressRouteCircuitPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercpf.AllowClassicOperations != nil { - objectMap["allowClassicOperations"] = ercpf.AllowClassicOperations - } - if ercpf.CircuitProvisioningState != nil { - objectMap["circuitProvisioningState"] = ercpf.CircuitProvisioningState - } - if ercpf.ServiceProviderProvisioningState != "" { - objectMap["serviceProviderProvisioningState"] = ercpf.ServiceProviderProvisioningState - } - if ercpf.Authorizations != nil { - objectMap["authorizations"] = ercpf.Authorizations - } - if ercpf.Peerings != nil { - objectMap["peerings"] = ercpf.Peerings - } - if ercpf.ServiceKey != nil { - objectMap["serviceKey"] = ercpf.ServiceKey - } - if ercpf.ServiceProviderNotes != nil { - objectMap["serviceProviderNotes"] = ercpf.ServiceProviderNotes - } - if ercpf.ServiceProviderProperties != nil { - objectMap["serviceProviderProperties"] = ercpf.ServiceProviderProperties - } - if ercpf.ExpressRoutePort != nil { - objectMap["expressRoutePort"] = ercpf.ExpressRoutePort - } - if ercpf.BandwidthInGbps != nil { - objectMap["bandwidthInGbps"] = ercpf.BandwidthInGbps - } - if ercpf.ProvisioningState != nil { - objectMap["provisioningState"] = ercpf.ProvisioningState - } - if ercpf.GatewayManagerEtag != nil { - objectMap["gatewayManagerEtag"] = ercpf.GatewayManagerEtag - } - if ercpf.AllowGlobalReach != nil { - objectMap["allowGlobalReach"] = ercpf.AllowGlobalReach - } - return json.Marshal(objectMap) -} - -// ExpressRouteCircuitReference ... -type ExpressRouteCircuitReference struct { - // ID - Corresponding Express Route Circuit Id. - ID *string `json:"id,omitempty"` -} - -// ExpressRouteCircuitRoutesTable the routes table associated with the ExpressRouteCircuit -type ExpressRouteCircuitRoutesTable struct { - // NetworkProperty - IP address of a network entity - NetworkProperty *string `json:"network,omitempty"` - // NextHop - NextHop address - NextHop *string `json:"nextHop,omitempty"` - // LocPrf - Local preference value as set with the set local-preference route-map configuration command - LocPrf *string `json:"locPrf,omitempty"` - // Weight - Route Weight. - Weight *int32 `json:"weight,omitempty"` - // Path - Autonomous system paths to the destination network. - Path *string `json:"path,omitempty"` -} - -// ExpressRouteCircuitRoutesTableSummary the routes table associated with the ExpressRouteCircuit. -type ExpressRouteCircuitRoutesTableSummary struct { - // Neighbor - IP address of the neighbor. - Neighbor *string `json:"neighbor,omitempty"` - // V - BGP version number spoken to the neighbor. - V *int32 `json:"v,omitempty"` - // As - Autonomous system number. - As *int32 `json:"as,omitempty"` - // UpDown - The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. - UpDown *string `json:"upDown,omitempty"` - // StatePfxRcd - Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. - StatePfxRcd *string `json:"statePfxRcd,omitempty"` -} - -// ExpressRouteCircuitsArpTableListResult response for ListArpTable associated with the Express Route -// Circuits API. -type ExpressRouteCircuitsArpTableListResult struct { - autorest.Response `json:"-"` - // Value - Gets list of the ARP table. - Value *[]ExpressRouteCircuitArpTable `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuit, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitsCreateOrUpdateFuture) result(client ExpressRouteCircuitsClient) (erc ExpressRouteCircuit, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erc.Response.Response, err = future.GetResult(sender); err == nil && erc.Response.Response.StatusCode != http.StatusNoContent { - erc, err = client.CreateOrUpdateResponder(erc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsCreateOrUpdateFuture", "Result", erc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsDeleteFuture.Result. -func (future *ExpressRouteCircuitsDeleteFuture) result(client ExpressRouteCircuitsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitServiceProviderProperties contains ServiceProviderProperties in an -// ExpressRouteCircuit. -type ExpressRouteCircuitServiceProviderProperties struct { - // ServiceProviderName - The serviceProviderName. - ServiceProviderName *string `json:"serviceProviderName,omitempty"` - // PeeringLocation - The peering location. - PeeringLocation *string `json:"peeringLocation,omitempty"` - // BandwidthInMbps - The BandwidthInMbps. - BandwidthInMbps *int32 `json:"bandwidthInMbps,omitempty"` -} - -// ExpressRouteCircuitSku contains SKU in an ExpressRouteCircuit. -type ExpressRouteCircuitSku struct { - // Name - The name of the SKU. - Name *string `json:"name,omitempty"` - // Tier - The tier of the SKU. Possible values are 'Standard', 'Premium' or 'Basic'. Possible values include: 'ExpressRouteCircuitSkuTierStandard', 'ExpressRouteCircuitSkuTierPremium', 'ExpressRouteCircuitSkuTierBasic' - Tier ExpressRouteCircuitSkuTier `json:"tier,omitempty"` - // Family - The family of the SKU. Possible values are: 'UnlimitedData' and 'MeteredData'. Possible values include: 'UnlimitedData', 'MeteredData' - Family ExpressRouteCircuitSkuFamily `json:"family,omitempty"` -} - -// ExpressRouteCircuitsListArpTableFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsListArpTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuitsArpTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsListArpTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsListArpTableFuture.Result. -func (future *ExpressRouteCircuitsListArpTableFuture) result(client ExpressRouteCircuitsClient) (ercatlr ExpressRouteCircuitsArpTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListArpTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercatlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsListArpTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercatlr.Response.Response, err = future.GetResult(sender); err == nil && ercatlr.Response.Response.StatusCode != http.StatusNoContent { - ercatlr, err = client.ListArpTableResponder(ercatlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListArpTableFuture", "Result", ercatlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsListRoutesTableFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsListRoutesTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuitsRoutesTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsListRoutesTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsListRoutesTableFuture.Result. -func (future *ExpressRouteCircuitsListRoutesTableFuture) result(client ExpressRouteCircuitsClient) (ercrtlr ExpressRouteCircuitsRoutesTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercrtlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsListRoutesTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercrtlr.Response.Response, err = future.GetResult(sender); err == nil && ercrtlr.Response.Response.StatusCode != http.StatusNoContent { - ercrtlr, err = client.ListRoutesTableResponder(ercrtlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableFuture", "Result", ercrtlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsListRoutesTableSummaryFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCircuitsListRoutesTableSummaryFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuitsRoutesTableSummaryListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsListRoutesTableSummaryFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsListRoutesTableSummaryFuture.Result. -func (future *ExpressRouteCircuitsListRoutesTableSummaryFuture) result(client ExpressRouteCircuitsClient) (ercrtslr ExpressRouteCircuitsRoutesTableSummaryListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableSummaryFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercrtslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsListRoutesTableSummaryFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercrtslr.Response.Response, err = future.GetResult(sender); err == nil && ercrtslr.Response.Response.StatusCode != http.StatusNoContent { - ercrtslr, err = client.ListRoutesTableSummaryResponder(ercrtslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableSummaryFuture", "Result", ercrtslr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsRoutesTableListResult response for ListRoutesTable associated with the Express Route -// Circuits API. -type ExpressRouteCircuitsRoutesTableListResult struct { - autorest.Response `json:"-"` - // Value - The list of routes table. - Value *[]ExpressRouteCircuitRoutesTable `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitsRoutesTableSummaryListResult response for ListRoutesTable associated with the -// Express Route Circuits API. -type ExpressRouteCircuitsRoutesTableSummaryListResult struct { - autorest.Response `json:"-"` - // Value - A list of the routes table. - Value *[]ExpressRouteCircuitRoutesTableSummary `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitStats contains stats associated with the peering. -type ExpressRouteCircuitStats struct { - autorest.Response `json:"-"` - // PrimarybytesIn - Gets BytesIn of the peering. - PrimarybytesIn *int64 `json:"primarybytesIn,omitempty"` - // PrimarybytesOut - Gets BytesOut of the peering. - PrimarybytesOut *int64 `json:"primarybytesOut,omitempty"` - // SecondarybytesIn - Gets BytesIn of the peering. - SecondarybytesIn *int64 `json:"secondarybytesIn,omitempty"` - // SecondarybytesOut - Gets BytesOut of the peering. - SecondarybytesOut *int64 `json:"secondarybytesOut,omitempty"` -} - -// ExpressRouteCircuitsUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuit, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsUpdateTagsFuture.Result. -func (future *ExpressRouteCircuitsUpdateTagsFuture) result(client ExpressRouteCircuitsClient) (erc ExpressRouteCircuit, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erc.Response.Response, err = future.GetResult(sender); err == nil && erc.Response.Response.StatusCode != http.StatusNoContent { - erc, err = client.UpdateTagsResponder(erc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsUpdateTagsFuture", "Result", erc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteConnection expressRouteConnection resource. -type ExpressRouteConnection struct { - autorest.Response `json:"-"` - *ExpressRouteConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource. - Name *string `json:"name,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteConnection. -func (erc ExpressRouteConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erc.ExpressRouteConnectionProperties != nil { - objectMap["properties"] = erc.ExpressRouteConnectionProperties - } - if erc.Name != nil { - objectMap["name"] = erc.Name - } - if erc.ID != nil { - objectMap["id"] = erc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteConnection struct. -func (erc *ExpressRouteConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteConnectionProperties ExpressRouteConnectionProperties - err = json.Unmarshal(*v, &expressRouteConnectionProperties) - if err != nil { - return err - } - erc.ExpressRouteConnectionProperties = &expressRouteConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erc.Name = &name - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erc.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteConnectionID the ID of the ExpressRouteConnection. -type ExpressRouteConnectionID struct { - // ID - READ-ONLY; The ID of the ExpressRouteConnection. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteConnectionID. -func (erci ExpressRouteConnectionID) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ExpressRouteConnectionList expressRouteConnection list -type ExpressRouteConnectionList struct { - autorest.Response `json:"-"` - // Value - The list of ExpressRoute connections - Value *[]ExpressRouteConnection `json:"value,omitempty"` -} - -// ExpressRouteConnectionProperties properties of the ExpressRouteConnection subresource. -type ExpressRouteConnectionProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ExpressRouteCircuitPeering - The ExpressRoute circuit peering. - ExpressRouteCircuitPeering *ExpressRouteCircuitPeeringID `json:"expressRouteCircuitPeering,omitempty"` - // AuthorizationKey - Authorization key to establish the connection. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // RoutingWeight - The routing weight associated to the connection. - RoutingWeight *int32 `json:"routingWeight,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteConnectionProperties. -func (ercp ExpressRouteConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercp.ExpressRouteCircuitPeering != nil { - objectMap["expressRouteCircuitPeering"] = ercp.ExpressRouteCircuitPeering - } - if ercp.AuthorizationKey != nil { - objectMap["authorizationKey"] = ercp.AuthorizationKey - } - if ercp.RoutingWeight != nil { - objectMap["routingWeight"] = ercp.RoutingWeight - } - return json.Marshal(objectMap) -} - -// ExpressRouteConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ExpressRouteConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteConnectionsClient) (ExpressRouteConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteConnectionsCreateOrUpdateFuture.Result. -func (future *ExpressRouteConnectionsCreateOrUpdateFuture) result(client ExpressRouteConnectionsClient) (erc ExpressRouteConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erc.Response.Response, err = future.GetResult(sender); err == nil && erc.Response.Response.StatusCode != http.StatusNoContent { - erc, err = client.CreateOrUpdateResponder(erc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsCreateOrUpdateFuture", "Result", erc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteConnectionsDeleteFuture.Result. -func (future *ExpressRouteConnectionsDeleteFuture) result(client ExpressRouteConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCrossConnection expressRouteCrossConnection resource -type ExpressRouteCrossConnection struct { - autorest.Response `json:"-"` - *ExpressRouteCrossConnectionProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnection. -func (ercc ExpressRouteCrossConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercc.ExpressRouteCrossConnectionProperties != nil { - objectMap["properties"] = ercc.ExpressRouteCrossConnectionProperties - } - if ercc.ID != nil { - objectMap["id"] = ercc.ID - } - if ercc.Location != nil { - objectMap["location"] = ercc.Location - } - if ercc.Tags != nil { - objectMap["tags"] = ercc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCrossConnection struct. -func (ercc *ExpressRouteCrossConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCrossConnectionProperties ExpressRouteCrossConnectionProperties - err = json.Unmarshal(*v, &expressRouteCrossConnectionProperties) - if err != nil { - return err - } - ercc.ExpressRouteCrossConnectionProperties = &expressRouteCrossConnectionProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ercc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ercc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ercc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ercc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ercc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ercc.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteCrossConnectionListResult response for ListExpressRouteCrossConnection API service call. -type ExpressRouteCrossConnectionListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRouteCrossConnection resources. - Value *[]ExpressRouteCrossConnection `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionListResult. -func (ercclr ExpressRouteCrossConnectionListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercclr.Value != nil { - objectMap["value"] = ercclr.Value - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionListResultIterator provides access to a complete listing of -// ExpressRouteCrossConnection values. -type ExpressRouteCrossConnectionListResultIterator struct { - i int - page ExpressRouteCrossConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCrossConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCrossConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCrossConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCrossConnectionListResultIterator) Response() ExpressRouteCrossConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCrossConnectionListResultIterator) Value() ExpressRouteCrossConnection { - if !iter.page.NotDone() { - return ExpressRouteCrossConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCrossConnectionListResultIterator type. -func NewExpressRouteCrossConnectionListResultIterator(page ExpressRouteCrossConnectionListResultPage) ExpressRouteCrossConnectionListResultIterator { - return ExpressRouteCrossConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ercclr ExpressRouteCrossConnectionListResult) IsEmpty() bool { - return ercclr.Value == nil || len(*ercclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ercclr ExpressRouteCrossConnectionListResult) hasNextLink() bool { - return ercclr.NextLink != nil && len(*ercclr.NextLink) != 0 -} - -// expressRouteCrossConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ercclr ExpressRouteCrossConnectionListResult) expressRouteCrossConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ercclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ercclr.NextLink))) -} - -// ExpressRouteCrossConnectionListResultPage contains a page of ExpressRouteCrossConnection values. -type ExpressRouteCrossConnectionListResultPage struct { - fn func(context.Context, ExpressRouteCrossConnectionListResult) (ExpressRouteCrossConnectionListResult, error) - ercclr ExpressRouteCrossConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCrossConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ercclr) - if err != nil { - return err - } - page.ercclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCrossConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCrossConnectionListResultPage) NotDone() bool { - return !page.ercclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCrossConnectionListResultPage) Response() ExpressRouteCrossConnectionListResult { - return page.ercclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCrossConnectionListResultPage) Values() []ExpressRouteCrossConnection { - if page.ercclr.IsEmpty() { - return nil - } - return *page.ercclr.Value -} - -// Creates a new instance of the ExpressRouteCrossConnectionListResultPage type. -func NewExpressRouteCrossConnectionListResultPage(cur ExpressRouteCrossConnectionListResult, getNextPage func(context.Context, ExpressRouteCrossConnectionListResult) (ExpressRouteCrossConnectionListResult, error)) ExpressRouteCrossConnectionListResultPage { - return ExpressRouteCrossConnectionListResultPage{ - fn: getNextPage, - ercclr: cur, - } -} - -// ExpressRouteCrossConnectionPeering peering in an ExpressRoute Cross Connection resource. -type ExpressRouteCrossConnectionPeering struct { - autorest.Response `json:"-"` - *ExpressRouteCrossConnectionPeeringProperties `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionPeering. -func (erccp ExpressRouteCrossConnectionPeering) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccp.ExpressRouteCrossConnectionPeeringProperties != nil { - objectMap["properties"] = erccp.ExpressRouteCrossConnectionPeeringProperties - } - if erccp.Name != nil { - objectMap["name"] = erccp.Name - } - if erccp.ID != nil { - objectMap["id"] = erccp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCrossConnectionPeering struct. -func (erccp *ExpressRouteCrossConnectionPeering) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCrossConnectionPeeringProperties ExpressRouteCrossConnectionPeeringProperties - err = json.Unmarshal(*v, &expressRouteCrossConnectionPeeringProperties) - if err != nil { - return err - } - erccp.ExpressRouteCrossConnectionPeeringProperties = &expressRouteCrossConnectionPeeringProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erccp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erccp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erccp.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCrossConnectionPeeringList response for ListPeering API service call retrieves all peerings -// that belong to an ExpressRouteCrossConnection. -type ExpressRouteCrossConnectionPeeringList struct { - autorest.Response `json:"-"` - // Value - The peerings in an express route cross connection. - Value *[]ExpressRouteCrossConnectionPeering `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionPeeringList. -func (erccpl ExpressRouteCrossConnectionPeeringList) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccpl.Value != nil { - objectMap["value"] = erccpl.Value - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionPeeringListIterator provides access to a complete listing of -// ExpressRouteCrossConnectionPeering values. -type ExpressRouteCrossConnectionPeeringListIterator struct { - i int - page ExpressRouteCrossConnectionPeeringListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCrossConnectionPeeringListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCrossConnectionPeeringListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCrossConnectionPeeringListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCrossConnectionPeeringListIterator) Response() ExpressRouteCrossConnectionPeeringList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCrossConnectionPeeringListIterator) Value() ExpressRouteCrossConnectionPeering { - if !iter.page.NotDone() { - return ExpressRouteCrossConnectionPeering{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCrossConnectionPeeringListIterator type. -func NewExpressRouteCrossConnectionPeeringListIterator(page ExpressRouteCrossConnectionPeeringListPage) ExpressRouteCrossConnectionPeeringListIterator { - return ExpressRouteCrossConnectionPeeringListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erccpl ExpressRouteCrossConnectionPeeringList) IsEmpty() bool { - return erccpl.Value == nil || len(*erccpl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erccpl ExpressRouteCrossConnectionPeeringList) hasNextLink() bool { - return erccpl.NextLink != nil && len(*erccpl.NextLink) != 0 -} - -// expressRouteCrossConnectionPeeringListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erccpl ExpressRouteCrossConnectionPeeringList) expressRouteCrossConnectionPeeringListPreparer(ctx context.Context) (*http.Request, error) { - if !erccpl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erccpl.NextLink))) -} - -// ExpressRouteCrossConnectionPeeringListPage contains a page of ExpressRouteCrossConnectionPeering values. -type ExpressRouteCrossConnectionPeeringListPage struct { - fn func(context.Context, ExpressRouteCrossConnectionPeeringList) (ExpressRouteCrossConnectionPeeringList, error) - erccpl ExpressRouteCrossConnectionPeeringList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCrossConnectionPeeringListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erccpl) - if err != nil { - return err - } - page.erccpl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCrossConnectionPeeringListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCrossConnectionPeeringListPage) NotDone() bool { - return !page.erccpl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCrossConnectionPeeringListPage) Response() ExpressRouteCrossConnectionPeeringList { - return page.erccpl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCrossConnectionPeeringListPage) Values() []ExpressRouteCrossConnectionPeering { - if page.erccpl.IsEmpty() { - return nil - } - return *page.erccpl.Value -} - -// Creates a new instance of the ExpressRouteCrossConnectionPeeringListPage type. -func NewExpressRouteCrossConnectionPeeringListPage(cur ExpressRouteCrossConnectionPeeringList, getNextPage func(context.Context, ExpressRouteCrossConnectionPeeringList) (ExpressRouteCrossConnectionPeeringList, error)) ExpressRouteCrossConnectionPeeringListPage { - return ExpressRouteCrossConnectionPeeringListPage{ - fn: getNextPage, - erccpl: cur, - } -} - -// ExpressRouteCrossConnectionPeeringProperties ... -type ExpressRouteCrossConnectionPeeringProperties struct { - // PeeringType - The peering type. Possible values include: 'AzurePublicPeering', 'AzurePrivatePeering', 'MicrosoftPeering' - PeeringType ExpressRoutePeeringType `json:"peeringType,omitempty"` - // State - The peering state. Possible values include: 'ExpressRoutePeeringStateDisabled', 'ExpressRoutePeeringStateEnabled' - State ExpressRoutePeeringState `json:"state,omitempty"` - // AzureASN - READ-ONLY; The Azure ASN. - AzureASN *int32 `json:"azureASN,omitempty"` - // PeerASN - The peer ASN. - PeerASN *int64 `json:"peerASN,omitempty"` - // PrimaryPeerAddressPrefix - The primary address prefix. - PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` - // SecondaryPeerAddressPrefix - The secondary address prefix. - SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` - // PrimaryAzurePort - READ-ONLY; The primary port. - PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` - // SecondaryAzurePort - READ-ONLY; The secondary port. - SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` - // SharedKey - The shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // VlanID - The VLAN ID. - VlanID *int32 `json:"vlanId,omitempty"` - // MicrosoftPeeringConfig - The Microsoft peering configuration. - MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` - // ProvisioningState - READ-ONLY; Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // GatewayManagerEtag - The GatewayManager Etag. - GatewayManagerEtag *string `json:"gatewayManagerEtag,omitempty"` - // LastModifiedBy - Gets whether the provider or the customer last modified the peering. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // Ipv6PeeringConfig - The IPv6 peering configuration. - Ipv6PeeringConfig *Ipv6ExpressRouteCircuitPeeringConfig `json:"ipv6PeeringConfig,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionPeeringProperties. -func (erccpp ExpressRouteCrossConnectionPeeringProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccpp.PeeringType != "" { - objectMap["peeringType"] = erccpp.PeeringType - } - if erccpp.State != "" { - objectMap["state"] = erccpp.State - } - if erccpp.PeerASN != nil { - objectMap["peerASN"] = erccpp.PeerASN - } - if erccpp.PrimaryPeerAddressPrefix != nil { - objectMap["primaryPeerAddressPrefix"] = erccpp.PrimaryPeerAddressPrefix - } - if erccpp.SecondaryPeerAddressPrefix != nil { - objectMap["secondaryPeerAddressPrefix"] = erccpp.SecondaryPeerAddressPrefix - } - if erccpp.SharedKey != nil { - objectMap["sharedKey"] = erccpp.SharedKey - } - if erccpp.VlanID != nil { - objectMap["vlanId"] = erccpp.VlanID - } - if erccpp.MicrosoftPeeringConfig != nil { - objectMap["microsoftPeeringConfig"] = erccpp.MicrosoftPeeringConfig - } - if erccpp.GatewayManagerEtag != nil { - objectMap["gatewayManagerEtag"] = erccpp.GatewayManagerEtag - } - if erccpp.LastModifiedBy != nil { - objectMap["lastModifiedBy"] = erccpp.LastModifiedBy - } - if erccpp.Ipv6PeeringConfig != nil { - objectMap["ipv6PeeringConfig"] = erccpp.Ipv6PeeringConfig - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionPeeringsClient) (ExpressRouteCrossConnectionPeering, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture) result(client ExpressRouteCrossConnectionPeeringsClient) (erccp ExpressRouteCrossConnectionPeering, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erccp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erccp.Response.Response, err = future.GetResult(sender); err == nil && erccp.Response.Response.StatusCode != http.StatusNoContent { - erccp, err = client.CreateOrUpdateResponder(erccp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture", "Result", erccp.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionPeeringsDeleteFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCrossConnectionPeeringsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionPeeringsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionPeeringsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionPeeringsDeleteFuture.Result. -func (future *ExpressRouteCrossConnectionPeeringsDeleteFuture) result(client ExpressRouteCrossConnectionPeeringsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionPeeringsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCrossConnectionProperties properties of ExpressRouteCrossConnection. -type ExpressRouteCrossConnectionProperties struct { - // PrimaryAzurePort - READ-ONLY; The name of the primary port. - PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` - // SecondaryAzurePort - READ-ONLY; The name of the secondary port. - SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` - // STag - READ-ONLY; The identifier of the circuit traffic. - STag *int32 `json:"sTag,omitempty"` - // PeeringLocation - The peering location of the ExpressRoute circuit. - PeeringLocation *string `json:"peeringLocation,omitempty"` - // BandwidthInMbps - The circuit bandwidth In Mbps. - BandwidthInMbps *int32 `json:"bandwidthInMbps,omitempty"` - // ExpressRouteCircuit - The ExpressRouteCircuit - ExpressRouteCircuit *ExpressRouteCircuitReference `json:"expressRouteCircuit,omitempty"` - // ServiceProviderProvisioningState - The provisioning state of the circuit in the connectivity provider system. Possible values are 'NotProvisioned', 'Provisioning', 'Provisioned'. Possible values include: 'NotProvisioned', 'Provisioning', 'Provisioned', 'Deprovisioning' - ServiceProviderProvisioningState ServiceProviderProvisioningState `json:"serviceProviderProvisioningState,omitempty"` - // ServiceProviderNotes - Additional read only notes set by the connectivity provider. - ServiceProviderNotes *string `json:"serviceProviderNotes,omitempty"` - // ProvisioningState - READ-ONLY; Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // Peerings - The list of peerings. - Peerings *[]ExpressRouteCrossConnectionPeering `json:"peerings,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionProperties. -func (erccp ExpressRouteCrossConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccp.PeeringLocation != nil { - objectMap["peeringLocation"] = erccp.PeeringLocation - } - if erccp.BandwidthInMbps != nil { - objectMap["bandwidthInMbps"] = erccp.BandwidthInMbps - } - if erccp.ExpressRouteCircuit != nil { - objectMap["expressRouteCircuit"] = erccp.ExpressRouteCircuit - } - if erccp.ServiceProviderProvisioningState != "" { - objectMap["serviceProviderProvisioningState"] = erccp.ServiceProviderProvisioningState - } - if erccp.ServiceProviderNotes != nil { - objectMap["serviceProviderNotes"] = erccp.ServiceProviderNotes - } - if erccp.Peerings != nil { - objectMap["peerings"] = erccp.Peerings - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionRoutesTableSummary the routes table associated with the ExpressRouteCircuit. -type ExpressRouteCrossConnectionRoutesTableSummary struct { - // Neighbor - IP address of Neighbor router - Neighbor *string `json:"neighbor,omitempty"` - // Asn - Autonomous system number. - Asn *int32 `json:"asn,omitempty"` - // UpDown - The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. - UpDown *string `json:"upDown,omitempty"` - // StateOrPrefixesReceived - Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. - StateOrPrefixesReceived *string `json:"stateOrPrefixesReceived,omitempty"` -} - -// ExpressRouteCrossConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCrossConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCrossConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCrossConnectionsCreateOrUpdateFuture) result(client ExpressRouteCrossConnectionsClient) (ercc ExpressRouteCrossConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercc.Response.Response, err = future.GetResult(sender); err == nil && ercc.Response.Response.StatusCode != http.StatusNoContent { - ercc, err = client.CreateOrUpdateResponder(ercc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsCreateOrUpdateFuture", "Result", ercc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsListArpTableFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCrossConnectionsListArpTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCircuitsArpTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsListArpTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsListArpTableFuture.Result. -func (future *ExpressRouteCrossConnectionsListArpTableFuture) result(client ExpressRouteCrossConnectionsClient) (ercatlr ExpressRouteCircuitsArpTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListArpTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercatlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsListArpTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercatlr.Response.Response, err = future.GetResult(sender); err == nil && ercatlr.Response.Response.StatusCode != http.StatusNoContent { - ercatlr, err = client.ListArpTableResponder(ercatlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListArpTableFuture", "Result", ercatlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsListRoutesTableFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCrossConnectionsListRoutesTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCircuitsRoutesTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsListRoutesTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsListRoutesTableFuture.Result. -func (future *ExpressRouteCrossConnectionsListRoutesTableFuture) result(client ExpressRouteCrossConnectionsClient) (ercrtlr ExpressRouteCircuitsRoutesTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercrtlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsListRoutesTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercrtlr.Response.Response, err = future.GetResult(sender); err == nil && ercrtlr.Response.Response.StatusCode != http.StatusNoContent { - ercrtlr, err = client.ListRoutesTableResponder(ercrtlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableFuture", "Result", ercrtlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsListRoutesTableSummaryFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type ExpressRouteCrossConnectionsListRoutesTableSummaryFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCrossConnectionsRoutesTableSummaryListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsListRoutesTableSummaryFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsListRoutesTableSummaryFuture.Result. -func (future *ExpressRouteCrossConnectionsListRoutesTableSummaryFuture) result(client ExpressRouteCrossConnectionsClient) (erccrtslr ExpressRouteCrossConnectionsRoutesTableSummaryListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableSummaryFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erccrtslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsListRoutesTableSummaryFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erccrtslr.Response.Response, err = future.GetResult(sender); err == nil && erccrtslr.Response.Response.StatusCode != http.StatusNoContent { - erccrtslr, err = client.ListRoutesTableSummaryResponder(erccrtslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableSummaryFuture", "Result", erccrtslr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsRoutesTableSummaryListResult response for ListRoutesTable associated with -// the Express Route Cross Connections. -type ExpressRouteCrossConnectionsRoutesTableSummaryListResult struct { - autorest.Response `json:"-"` - // Value - A list of the routes table. - Value *[]ExpressRouteCrossConnectionRoutesTableSummary `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionsRoutesTableSummaryListResult. -func (erccrtslr ExpressRouteCrossConnectionsRoutesTableSummaryListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccrtslr.Value != nil { - objectMap["value"] = erccrtslr.Value - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionsUpdateTagsFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ExpressRouteCrossConnectionsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCrossConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsUpdateTagsFuture.Result. -func (future *ExpressRouteCrossConnectionsUpdateTagsFuture) result(client ExpressRouteCrossConnectionsClient) (ercc ExpressRouteCrossConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercc.Response.Response, err = future.GetResult(sender); err == nil && ercc.Response.Response.StatusCode != http.StatusNoContent { - ercc, err = client.UpdateTagsResponder(ercc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsUpdateTagsFuture", "Result", ercc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteGateway expressRoute gateway resource. -type ExpressRouteGateway struct { - autorest.Response `json:"-"` - *ExpressRouteGatewayProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteGateway. -func (erg ExpressRouteGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erg.ExpressRouteGatewayProperties != nil { - objectMap["properties"] = erg.ExpressRouteGatewayProperties - } - if erg.ID != nil { - objectMap["id"] = erg.ID - } - if erg.Location != nil { - objectMap["location"] = erg.Location - } - if erg.Tags != nil { - objectMap["tags"] = erg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteGateway struct. -func (erg *ExpressRouteGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteGatewayProperties ExpressRouteGatewayProperties - err = json.Unmarshal(*v, &expressRouteGatewayProperties) - if err != nil { - return err - } - erg.ExpressRouteGatewayProperties = &expressRouteGatewayProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erg.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteGatewayList list of ExpressRoute gateways. -type ExpressRouteGatewayList struct { - autorest.Response `json:"-"` - // Value - List of ExpressRoute gateways. - Value *[]ExpressRouteGateway `json:"value,omitempty"` -} - -// ExpressRouteGatewayProperties expressRoute gateway resource properties. -type ExpressRouteGatewayProperties struct { - // AutoScaleConfiguration - Configuration for auto scaling. - AutoScaleConfiguration *ExpressRouteGatewayPropertiesAutoScaleConfiguration `json:"autoScaleConfiguration,omitempty"` - // ExpressRouteConnections - READ-ONLY; List of ExpressRoute connections to the ExpressRoute gateway. - ExpressRouteConnections *[]ExpressRouteConnection `json:"expressRouteConnections,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // VirtualHub - The Virtual Hub where the ExpressRoute gateway is or will be deployed. - VirtualHub *VirtualHubID `json:"virtualHub,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteGatewayProperties. -func (ergp ExpressRouteGatewayProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ergp.AutoScaleConfiguration != nil { - objectMap["autoScaleConfiguration"] = ergp.AutoScaleConfiguration - } - if ergp.VirtualHub != nil { - objectMap["virtualHub"] = ergp.VirtualHub - } - return json.Marshal(objectMap) -} - -// ExpressRouteGatewayPropertiesAutoScaleConfiguration configuration for auto scaling. -type ExpressRouteGatewayPropertiesAutoScaleConfiguration struct { - // Bounds - Minimum and maximum number of scale units to deploy. - Bounds *ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds `json:"bounds,omitempty"` -} - -// ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds minimum and maximum number of scale units to -// deploy. -type ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds struct { - // Min - Minimum number of scale units deployed for ExpressRoute gateway. - Min *int32 `json:"min,omitempty"` - // Max - Maximum number of scale units deployed for ExpressRoute gateway. - Max *int32 `json:"max,omitempty"` -} - -// ExpressRouteGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteGatewaysClient) (ExpressRouteGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteGatewaysCreateOrUpdateFuture.Result. -func (future *ExpressRouteGatewaysCreateOrUpdateFuture) result(client ExpressRouteGatewaysClient) (erg ExpressRouteGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erg.Response.Response, err = future.GetResult(sender); err == nil && erg.Response.Response.StatusCode != http.StatusNoContent { - erg, err = client.CreateOrUpdateResponder(erg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysCreateOrUpdateFuture", "Result", erg.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteGatewaysDeleteFuture.Result. -func (future *ExpressRouteGatewaysDeleteFuture) result(client ExpressRouteGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteLink expressRouteLink child resource definition. -type ExpressRouteLink struct { - autorest.Response `json:"-"` - // ExpressRouteLinkPropertiesFormat - ExpressRouteLink properties - *ExpressRouteLinkPropertiesFormat `json:"properties,omitempty"` - // Name - Name of child port resource that is unique among child port resources of the parent. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteLink. -func (erl ExpressRouteLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erl.ExpressRouteLinkPropertiesFormat != nil { - objectMap["properties"] = erl.ExpressRouteLinkPropertiesFormat - } - if erl.Name != nil { - objectMap["name"] = erl.Name - } - if erl.ID != nil { - objectMap["id"] = erl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteLink struct. -func (erl *ExpressRouteLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteLinkPropertiesFormat ExpressRouteLinkPropertiesFormat - err = json.Unmarshal(*v, &expressRouteLinkPropertiesFormat) - if err != nil { - return err - } - erl.ExpressRouteLinkPropertiesFormat = &expressRouteLinkPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erl.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erl.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erl.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteLinkListResult response for ListExpressRouteLinks API service call. -type ExpressRouteLinkListResult struct { - autorest.Response `json:"-"` - // Value - The list of ExpressRouteLink sub-resources. - Value *[]ExpressRouteLink `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteLinkListResultIterator provides access to a complete listing of ExpressRouteLink values. -type ExpressRouteLinkListResultIterator struct { - i int - page ExpressRouteLinkListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteLinkListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinkListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteLinkListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteLinkListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteLinkListResultIterator) Response() ExpressRouteLinkListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteLinkListResultIterator) Value() ExpressRouteLink { - if !iter.page.NotDone() { - return ExpressRouteLink{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteLinkListResultIterator type. -func NewExpressRouteLinkListResultIterator(page ExpressRouteLinkListResultPage) ExpressRouteLinkListResultIterator { - return ExpressRouteLinkListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erllr ExpressRouteLinkListResult) IsEmpty() bool { - return erllr.Value == nil || len(*erllr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erllr ExpressRouteLinkListResult) hasNextLink() bool { - return erllr.NextLink != nil && len(*erllr.NextLink) != 0 -} - -// expressRouteLinkListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erllr ExpressRouteLinkListResult) expressRouteLinkListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erllr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erllr.NextLink))) -} - -// ExpressRouteLinkListResultPage contains a page of ExpressRouteLink values. -type ExpressRouteLinkListResultPage struct { - fn func(context.Context, ExpressRouteLinkListResult) (ExpressRouteLinkListResult, error) - erllr ExpressRouteLinkListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteLinkListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinkListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erllr) - if err != nil { - return err - } - page.erllr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteLinkListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteLinkListResultPage) NotDone() bool { - return !page.erllr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteLinkListResultPage) Response() ExpressRouteLinkListResult { - return page.erllr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteLinkListResultPage) Values() []ExpressRouteLink { - if page.erllr.IsEmpty() { - return nil - } - return *page.erllr.Value -} - -// Creates a new instance of the ExpressRouteLinkListResultPage type. -func NewExpressRouteLinkListResultPage(cur ExpressRouteLinkListResult, getNextPage func(context.Context, ExpressRouteLinkListResult) (ExpressRouteLinkListResult, error)) ExpressRouteLinkListResultPage { - return ExpressRouteLinkListResultPage{ - fn: getNextPage, - erllr: cur, - } -} - -// ExpressRouteLinkPropertiesFormat properties specific to ExpressRouteLink resources. -type ExpressRouteLinkPropertiesFormat struct { - // RouterName - READ-ONLY; Name of Azure router associated with physical port. - RouterName *string `json:"routerName,omitempty"` - // InterfaceName - READ-ONLY; Name of Azure router interface. - InterfaceName *string `json:"interfaceName,omitempty"` - // PatchPanelID - READ-ONLY; Mapping between physical port to patch panel port. - PatchPanelID *string `json:"patchPanelId,omitempty"` - // RackID - READ-ONLY; Mapping of physical patch panel to rack. - RackID *string `json:"rackId,omitempty"` - // ConnectorType - READ-ONLY; Physical fiber port type. Possible values include: 'LC', 'SC' - ConnectorType ExpressRouteLinkConnectorType `json:"connectorType,omitempty"` - // AdminState - Administrative state of the physical port. Possible values include: 'ExpressRouteLinkAdminStateEnabled', 'ExpressRouteLinkAdminStateDisabled' - AdminState ExpressRouteLinkAdminState `json:"adminState,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the ExpressRouteLink resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteLinkPropertiesFormat. -func (erlpf ExpressRouteLinkPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erlpf.AdminState != "" { - objectMap["adminState"] = erlpf.AdminState - } - return json.Marshal(objectMap) -} - -// ExpressRoutePort expressRoutePort resource definition. -type ExpressRoutePort struct { - autorest.Response `json:"-"` - // ExpressRoutePortPropertiesFormat - ExpressRoutePort properties - *ExpressRoutePortPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePort. -func (erp ExpressRoutePort) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erp.ExpressRoutePortPropertiesFormat != nil { - objectMap["properties"] = erp.ExpressRoutePortPropertiesFormat - } - if erp.ID != nil { - objectMap["id"] = erp.ID - } - if erp.Location != nil { - objectMap["location"] = erp.Location - } - if erp.Tags != nil { - objectMap["tags"] = erp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRoutePort struct. -func (erp *ExpressRoutePort) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRoutePortPropertiesFormat ExpressRoutePortPropertiesFormat - err = json.Unmarshal(*v, &expressRoutePortPropertiesFormat) - if err != nil { - return err - } - erp.ExpressRoutePortPropertiesFormat = &expressRoutePortPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erp.Tags = tags - } - } - } - - return nil -} - -// ExpressRoutePortListResult response for ListExpressRoutePorts API service call. -type ExpressRoutePortListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRoutePort resources. - Value *[]ExpressRoutePort `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRoutePortListResultIterator provides access to a complete listing of ExpressRoutePort values. -type ExpressRoutePortListResultIterator struct { - i int - page ExpressRoutePortListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRoutePortListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRoutePortListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRoutePortListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRoutePortListResultIterator) Response() ExpressRoutePortListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRoutePortListResultIterator) Value() ExpressRoutePort { - if !iter.page.NotDone() { - return ExpressRoutePort{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRoutePortListResultIterator type. -func NewExpressRoutePortListResultIterator(page ExpressRoutePortListResultPage) ExpressRoutePortListResultIterator { - return ExpressRoutePortListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erplr ExpressRoutePortListResult) IsEmpty() bool { - return erplr.Value == nil || len(*erplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erplr ExpressRoutePortListResult) hasNextLink() bool { - return erplr.NextLink != nil && len(*erplr.NextLink) != 0 -} - -// expressRoutePortListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erplr ExpressRoutePortListResult) expressRoutePortListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erplr.NextLink))) -} - -// ExpressRoutePortListResultPage contains a page of ExpressRoutePort values. -type ExpressRoutePortListResultPage struct { - fn func(context.Context, ExpressRoutePortListResult) (ExpressRoutePortListResult, error) - erplr ExpressRoutePortListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRoutePortListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erplr) - if err != nil { - return err - } - page.erplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRoutePortListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRoutePortListResultPage) NotDone() bool { - return !page.erplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRoutePortListResultPage) Response() ExpressRoutePortListResult { - return page.erplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRoutePortListResultPage) Values() []ExpressRoutePort { - if page.erplr.IsEmpty() { - return nil - } - return *page.erplr.Value -} - -// Creates a new instance of the ExpressRoutePortListResultPage type. -func NewExpressRoutePortListResultPage(cur ExpressRoutePortListResult, getNextPage func(context.Context, ExpressRoutePortListResult) (ExpressRoutePortListResult, error)) ExpressRoutePortListResultPage { - return ExpressRoutePortListResultPage{ - fn: getNextPage, - erplr: cur, - } -} - -// ExpressRoutePortPropertiesFormat properties specific to ExpressRoutePort resources. -type ExpressRoutePortPropertiesFormat struct { - // PeeringLocation - The name of the peering location that the ExpressRoutePort is mapped to physically. - PeeringLocation *string `json:"peeringLocation,omitempty"` - // BandwidthInGbps - Bandwidth of procured ports in Gbps - BandwidthInGbps *int32 `json:"bandwidthInGbps,omitempty"` - // ProvisionedBandwidthInGbps - READ-ONLY; Aggregate Gbps of associated circuit bandwidths. - ProvisionedBandwidthInGbps *float64 `json:"provisionedBandwidthInGbps,omitempty"` - // Mtu - READ-ONLY; Maximum transmission unit of the physical port pair(s) - Mtu *string `json:"mtu,omitempty"` - // Encapsulation - Encapsulation method on physical ports. Possible values include: 'Dot1Q', 'QinQ' - Encapsulation ExpressRoutePortsEncapsulation `json:"encapsulation,omitempty"` - // EtherType - READ-ONLY; Ether type of the physical port. - EtherType *string `json:"etherType,omitempty"` - // AllocationDate - READ-ONLY; Date of the physical port allocation to be used in Letter of Authorization. - AllocationDate *string `json:"allocationDate,omitempty"` - // Links - The set of physical links of the ExpressRoutePort resource - Links *[]ExpressRouteLink `json:"links,omitempty"` - // Circuits - READ-ONLY; Reference the ExpressRoute circuit(s) that are provisioned on this ExpressRoutePort resource. - Circuits *[]SubResource `json:"circuits,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the ExpressRoutePort resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // ResourceGUID - The resource GUID property of the ExpressRoutePort resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortPropertiesFormat. -func (erppf ExpressRoutePortPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erppf.PeeringLocation != nil { - objectMap["peeringLocation"] = erppf.PeeringLocation - } - if erppf.BandwidthInGbps != nil { - objectMap["bandwidthInGbps"] = erppf.BandwidthInGbps - } - if erppf.Encapsulation != "" { - objectMap["encapsulation"] = erppf.Encapsulation - } - if erppf.Links != nil { - objectMap["links"] = erppf.Links - } - if erppf.ResourceGUID != nil { - objectMap["resourceGuid"] = erppf.ResourceGUID - } - return json.Marshal(objectMap) -} - -// ExpressRoutePortsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRoutePortsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRoutePortsClient) (ExpressRoutePort, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRoutePortsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRoutePortsCreateOrUpdateFuture.Result. -func (future *ExpressRoutePortsCreateOrUpdateFuture) result(client ExpressRoutePortsClient) (erp ExpressRoutePort, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRoutePortsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erp.Response.Response, err = future.GetResult(sender); err == nil && erp.Response.Response.StatusCode != http.StatusNoContent { - erp, err = client.CreateOrUpdateResponder(erp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsCreateOrUpdateFuture", "Result", erp.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRoutePortsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ExpressRoutePortsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRoutePortsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRoutePortsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRoutePortsDeleteFuture.Result. -func (future *ExpressRoutePortsDeleteFuture) result(client ExpressRoutePortsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRoutePortsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRoutePortsLocation definition of the ExpressRoutePorts peering location resource. -type ExpressRoutePortsLocation struct { - autorest.Response `json:"-"` - // ExpressRoutePortsLocationPropertiesFormat - ExpressRoutePort peering location properties - *ExpressRoutePortsLocationPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortsLocation. -func (erpl ExpressRoutePortsLocation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erpl.ExpressRoutePortsLocationPropertiesFormat != nil { - objectMap["properties"] = erpl.ExpressRoutePortsLocationPropertiesFormat - } - if erpl.ID != nil { - objectMap["id"] = erpl.ID - } - if erpl.Location != nil { - objectMap["location"] = erpl.Location - } - if erpl.Tags != nil { - objectMap["tags"] = erpl.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRoutePortsLocation struct. -func (erpl *ExpressRoutePortsLocation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRoutePortsLocationPropertiesFormat ExpressRoutePortsLocationPropertiesFormat - err = json.Unmarshal(*v, &expressRoutePortsLocationPropertiesFormat) - if err != nil { - return err - } - erpl.ExpressRoutePortsLocationPropertiesFormat = &expressRoutePortsLocationPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erpl.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erpl.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erpl.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erpl.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erpl.Tags = tags - } - } - } - - return nil -} - -// ExpressRoutePortsLocationBandwidths real-time inventory of available ExpressRoute port bandwidths. -type ExpressRoutePortsLocationBandwidths struct { - // OfferName - READ-ONLY; Bandwidth descriptive name - OfferName *string `json:"offerName,omitempty"` - // ValueInGbps - READ-ONLY; Bandwidth value in Gbps - ValueInGbps *int32 `json:"valueInGbps,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortsLocationBandwidths. -func (erplb ExpressRoutePortsLocationBandwidths) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ExpressRoutePortsLocationListResult response for ListExpressRoutePortsLocations API service call. -type ExpressRoutePortsLocationListResult struct { - autorest.Response `json:"-"` - // Value - The list of all ExpressRoutePort peering locations. - Value *[]ExpressRoutePortsLocation `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRoutePortsLocationListResultIterator provides access to a complete listing of -// ExpressRoutePortsLocation values. -type ExpressRoutePortsLocationListResultIterator struct { - i int - page ExpressRoutePortsLocationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRoutePortsLocationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRoutePortsLocationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRoutePortsLocationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRoutePortsLocationListResultIterator) Response() ExpressRoutePortsLocationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRoutePortsLocationListResultIterator) Value() ExpressRoutePortsLocation { - if !iter.page.NotDone() { - return ExpressRoutePortsLocation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRoutePortsLocationListResultIterator type. -func NewExpressRoutePortsLocationListResultIterator(page ExpressRoutePortsLocationListResultPage) ExpressRoutePortsLocationListResultIterator { - return ExpressRoutePortsLocationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erpllr ExpressRoutePortsLocationListResult) IsEmpty() bool { - return erpllr.Value == nil || len(*erpllr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erpllr ExpressRoutePortsLocationListResult) hasNextLink() bool { - return erpllr.NextLink != nil && len(*erpllr.NextLink) != 0 -} - -// expressRoutePortsLocationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erpllr ExpressRoutePortsLocationListResult) expressRoutePortsLocationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erpllr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erpllr.NextLink))) -} - -// ExpressRoutePortsLocationListResultPage contains a page of ExpressRoutePortsLocation values. -type ExpressRoutePortsLocationListResultPage struct { - fn func(context.Context, ExpressRoutePortsLocationListResult) (ExpressRoutePortsLocationListResult, error) - erpllr ExpressRoutePortsLocationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRoutePortsLocationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erpllr) - if err != nil { - return err - } - page.erpllr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRoutePortsLocationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRoutePortsLocationListResultPage) NotDone() bool { - return !page.erpllr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRoutePortsLocationListResultPage) Response() ExpressRoutePortsLocationListResult { - return page.erpllr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRoutePortsLocationListResultPage) Values() []ExpressRoutePortsLocation { - if page.erpllr.IsEmpty() { - return nil - } - return *page.erpllr.Value -} - -// Creates a new instance of the ExpressRoutePortsLocationListResultPage type. -func NewExpressRoutePortsLocationListResultPage(cur ExpressRoutePortsLocationListResult, getNextPage func(context.Context, ExpressRoutePortsLocationListResult) (ExpressRoutePortsLocationListResult, error)) ExpressRoutePortsLocationListResultPage { - return ExpressRoutePortsLocationListResultPage{ - fn: getNextPage, - erpllr: cur, - } -} - -// ExpressRoutePortsLocationPropertiesFormat properties specific to ExpressRoutePorts peering location -// resources. -type ExpressRoutePortsLocationPropertiesFormat struct { - // Address - READ-ONLY; Address of peering location. - Address *string `json:"address,omitempty"` - // Contact - READ-ONLY; Contact details of peering locations. - Contact *string `json:"contact,omitempty"` - // AvailableBandwidths - The inventory of available ExpressRoutePort bandwidths. - AvailableBandwidths *[]ExpressRoutePortsLocationBandwidths `json:"availableBandwidths,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the ExpressRoutePortLocation resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortsLocationPropertiesFormat. -func (erplpf ExpressRoutePortsLocationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erplpf.AvailableBandwidths != nil { - objectMap["availableBandwidths"] = erplpf.AvailableBandwidths - } - return json.Marshal(objectMap) -} - -// ExpressRoutePortsUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRoutePortsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRoutePortsClient) (ExpressRoutePort, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRoutePortsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRoutePortsUpdateTagsFuture.Result. -func (future *ExpressRoutePortsUpdateTagsFuture) result(client ExpressRoutePortsClient) (erp ExpressRoutePort, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRoutePortsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erp.Response.Response, err = future.GetResult(sender); err == nil && erp.Response.Response.StatusCode != http.StatusNoContent { - erp, err = client.UpdateTagsResponder(erp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsUpdateTagsFuture", "Result", erp.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteServiceProvider a ExpressRouteResourceProvider object. -type ExpressRouteServiceProvider struct { - *ExpressRouteServiceProviderPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteServiceProvider. -func (ersp ExpressRouteServiceProvider) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ersp.ExpressRouteServiceProviderPropertiesFormat != nil { - objectMap["properties"] = ersp.ExpressRouteServiceProviderPropertiesFormat - } - if ersp.ID != nil { - objectMap["id"] = ersp.ID - } - if ersp.Location != nil { - objectMap["location"] = ersp.Location - } - if ersp.Tags != nil { - objectMap["tags"] = ersp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteServiceProvider struct. -func (ersp *ExpressRouteServiceProvider) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteServiceProviderPropertiesFormat ExpressRouteServiceProviderPropertiesFormat - err = json.Unmarshal(*v, &expressRouteServiceProviderPropertiesFormat) - if err != nil { - return err - } - ersp.ExpressRouteServiceProviderPropertiesFormat = &expressRouteServiceProviderPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ersp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ersp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ersp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ersp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ersp.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteServiceProviderBandwidthsOffered contains bandwidths offered in ExpressRouteServiceProvider -// resources. -type ExpressRouteServiceProviderBandwidthsOffered struct { - // OfferName - The OfferName. - OfferName *string `json:"offerName,omitempty"` - // ValueInMbps - The ValueInMbps. - ValueInMbps *int32 `json:"valueInMbps,omitempty"` -} - -// ExpressRouteServiceProviderListResult response for the ListExpressRouteServiceProvider API service call. -type ExpressRouteServiceProviderListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRouteResourceProvider resources. - Value *[]ExpressRouteServiceProvider `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteServiceProviderListResultIterator provides access to a complete listing of -// ExpressRouteServiceProvider values. -type ExpressRouteServiceProviderListResultIterator struct { - i int - page ExpressRouteServiceProviderListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteServiceProviderListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProviderListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteServiceProviderListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteServiceProviderListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteServiceProviderListResultIterator) Response() ExpressRouteServiceProviderListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteServiceProviderListResultIterator) Value() ExpressRouteServiceProvider { - if !iter.page.NotDone() { - return ExpressRouteServiceProvider{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteServiceProviderListResultIterator type. -func NewExpressRouteServiceProviderListResultIterator(page ExpressRouteServiceProviderListResultPage) ExpressRouteServiceProviderListResultIterator { - return ExpressRouteServiceProviderListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ersplr ExpressRouteServiceProviderListResult) IsEmpty() bool { - return ersplr.Value == nil || len(*ersplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ersplr ExpressRouteServiceProviderListResult) hasNextLink() bool { - return ersplr.NextLink != nil && len(*ersplr.NextLink) != 0 -} - -// expressRouteServiceProviderListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ersplr ExpressRouteServiceProviderListResult) expressRouteServiceProviderListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ersplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ersplr.NextLink))) -} - -// ExpressRouteServiceProviderListResultPage contains a page of ExpressRouteServiceProvider values. -type ExpressRouteServiceProviderListResultPage struct { - fn func(context.Context, ExpressRouteServiceProviderListResult) (ExpressRouteServiceProviderListResult, error) - ersplr ExpressRouteServiceProviderListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteServiceProviderListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProviderListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ersplr) - if err != nil { - return err - } - page.ersplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteServiceProviderListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteServiceProviderListResultPage) NotDone() bool { - return !page.ersplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteServiceProviderListResultPage) Response() ExpressRouteServiceProviderListResult { - return page.ersplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteServiceProviderListResultPage) Values() []ExpressRouteServiceProvider { - if page.ersplr.IsEmpty() { - return nil - } - return *page.ersplr.Value -} - -// Creates a new instance of the ExpressRouteServiceProviderListResultPage type. -func NewExpressRouteServiceProviderListResultPage(cur ExpressRouteServiceProviderListResult, getNextPage func(context.Context, ExpressRouteServiceProviderListResult) (ExpressRouteServiceProviderListResult, error)) ExpressRouteServiceProviderListResultPage { - return ExpressRouteServiceProviderListResultPage{ - fn: getNextPage, - ersplr: cur, - } -} - -// ExpressRouteServiceProviderPropertiesFormat properties of ExpressRouteServiceProvider. -type ExpressRouteServiceProviderPropertiesFormat struct { - // PeeringLocations - Get a list of peering locations. - PeeringLocations *[]string `json:"peeringLocations,omitempty"` - // BandwidthsOffered - Gets bandwidths offered. - BandwidthsOffered *[]ExpressRouteServiceProviderBandwidthsOffered `json:"bandwidthsOffered,omitempty"` - // ProvisioningState - Gets the provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// FlowLogFormatParameters parameters that define the flow log format. -type FlowLogFormatParameters struct { - // Type - The file type of flow log. Possible values include: 'JSON' - Type FlowLogFormatType `json:"type,omitempty"` - // Version - The version (revision) of the flow log. - Version *int32 `json:"version,omitempty"` -} - -// FlowLogInformation information on the configuration of flow log and traffic analytics (optional) . -type FlowLogInformation struct { - autorest.Response `json:"-"` - // TargetResourceID - The ID of the resource to configure for flow log and traffic analytics (optional) . - TargetResourceID *string `json:"targetResourceId,omitempty"` - *FlowLogProperties `json:"properties,omitempty"` - FlowAnalyticsConfiguration *TrafficAnalyticsProperties `json:"flowAnalyticsConfiguration,omitempty"` -} - -// MarshalJSON is the custom marshaler for FlowLogInformation. -func (fli FlowLogInformation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fli.TargetResourceID != nil { - objectMap["targetResourceId"] = fli.TargetResourceID - } - if fli.FlowLogProperties != nil { - objectMap["properties"] = fli.FlowLogProperties - } - if fli.FlowAnalyticsConfiguration != nil { - objectMap["flowAnalyticsConfiguration"] = fli.FlowAnalyticsConfiguration - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FlowLogInformation struct. -func (fli *FlowLogInformation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "targetResourceId": - if v != nil { - var targetResourceID string - err = json.Unmarshal(*v, &targetResourceID) - if err != nil { - return err - } - fli.TargetResourceID = &targetResourceID - } - case "properties": - if v != nil { - var flowLogProperties FlowLogProperties - err = json.Unmarshal(*v, &flowLogProperties) - if err != nil { - return err - } - fli.FlowLogProperties = &flowLogProperties - } - case "flowAnalyticsConfiguration": - if v != nil { - var flowAnalyticsConfiguration TrafficAnalyticsProperties - err = json.Unmarshal(*v, &flowAnalyticsConfiguration) - if err != nil { - return err - } - fli.FlowAnalyticsConfiguration = &flowAnalyticsConfiguration - } - } - } - - return nil -} - -// FlowLogProperties parameters that define the configuration of flow log. -type FlowLogProperties struct { - // StorageID - ID of the storage account which is used to store the flow log. - StorageID *string `json:"storageId,omitempty"` - // Enabled - Flag to enable/disable flow logging. - Enabled *bool `json:"enabled,omitempty"` - RetentionPolicy *RetentionPolicyParameters `json:"retentionPolicy,omitempty"` - Format *FlowLogFormatParameters `json:"format,omitempty"` -} - -// FlowLogStatusParameters parameters that define a resource to query flow log and traffic analytics -// (optional) status. -type FlowLogStatusParameters struct { - // TargetResourceID - The target resource where getting the flow log and traffic analytics (optional) status. - TargetResourceID *string `json:"targetResourceId,omitempty"` -} - -// FrontendIPConfiguration frontend IP address of the load balancer. -type FrontendIPConfiguration struct { - autorest.Response `json:"-"` - // FrontendIPConfigurationPropertiesFormat - Properties of the load balancer probe. - *FrontendIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting the IP allocated for the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for FrontendIPConfiguration. -func (fic FrontendIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fic.FrontendIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = fic.FrontendIPConfigurationPropertiesFormat - } - if fic.Name != nil { - objectMap["name"] = fic.Name - } - if fic.Etag != nil { - objectMap["etag"] = fic.Etag - } - if fic.Zones != nil { - objectMap["zones"] = fic.Zones - } - if fic.ID != nil { - objectMap["id"] = fic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FrontendIPConfiguration struct. -func (fic *FrontendIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var frontendIPConfigurationPropertiesFormat FrontendIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &frontendIPConfigurationPropertiesFormat) - if err != nil { - return err - } - fic.FrontendIPConfigurationPropertiesFormat = &frontendIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - fic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - fic.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - fic.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - fic.ID = &ID - } - } - } - - return nil -} - -// FrontendIPConfigurationPropertiesFormat properties of Frontend IP Configuration of the load balancer. -type FrontendIPConfigurationPropertiesFormat struct { - // InboundNatRules - READ-ONLY; Read only. Inbound rules URIs that use this frontend IP. - InboundNatRules *[]SubResource `json:"inboundNatRules,omitempty"` - // InboundNatPools - READ-ONLY; Read only. Inbound pools URIs that use this frontend IP. - InboundNatPools *[]SubResource `json:"inboundNatPools,omitempty"` - // OutboundRules - READ-ONLY; Read only. Outbound rules URIs that use this frontend IP. - OutboundRules *[]SubResource `json:"outboundRules,omitempty"` - // LoadBalancingRules - READ-ONLY; Gets load balancing rules URIs that use this frontend IP. - LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` - // PrivateIPAddress - The private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - The reference of the subnet resource. - Subnet *Subnet `json:"subnet,omitempty"` - // PublicIPAddress - The reference of the Public IP resource. - PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` - // PublicIPPrefix - The reference of the Public IP Prefix resource. - PublicIPPrefix *SubResource `json:"publicIPPrefix,omitempty"` - // ProvisioningState - Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for FrontendIPConfigurationPropertiesFormat. -func (ficpf FrontendIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ficpf.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = ficpf.PrivateIPAddress - } - if ficpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = ficpf.PrivateIPAllocationMethod - } - if ficpf.Subnet != nil { - objectMap["subnet"] = ficpf.Subnet - } - if ficpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = ficpf.PublicIPAddress - } - if ficpf.PublicIPPrefix != nil { - objectMap["publicIPPrefix"] = ficpf.PublicIPPrefix - } - if ficpf.ProvisioningState != nil { - objectMap["provisioningState"] = ficpf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// GatewayRoute gateway routing details -type GatewayRoute struct { - // LocalAddress - READ-ONLY; The gateway's local address - LocalAddress *string `json:"localAddress,omitempty"` - // NetworkProperty - READ-ONLY; The route's network prefix - NetworkProperty *string `json:"network,omitempty"` - // NextHop - READ-ONLY; The route's next hop - NextHop *string `json:"nextHop,omitempty"` - // SourcePeer - READ-ONLY; The peer this route was learned from - SourcePeer *string `json:"sourcePeer,omitempty"` - // Origin - READ-ONLY; The source this route was learned from - Origin *string `json:"origin,omitempty"` - // AsPath - READ-ONLY; The route's AS path sequence - AsPath *string `json:"asPath,omitempty"` - // Weight - READ-ONLY; The route's weight - Weight *int32 `json:"weight,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayRoute. -func (gr GatewayRoute) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GatewayRouteListResult list of virtual network gateway routes -type GatewayRouteListResult struct { - autorest.Response `json:"-"` - // Value - List of gateway routes - Value *[]GatewayRoute `json:"value,omitempty"` -} - -// GetVpnSitesConfigurationRequest list of Vpn-Sites -type GetVpnSitesConfigurationRequest struct { - // VpnSites - List of resource-ids of the vpn-sites for which config is to be downloaded. - VpnSites *[]string `json:"vpnSites,omitempty"` - // OutputBlobSasURL - The sas-url to download the configurations for vpn-sites - OutputBlobSasURL *string `json:"outputBlobSasUrl,omitempty"` -} - -// HTTPConfiguration HTTP configuration of the connectivity check. -type HTTPConfiguration struct { - // Method - HTTP method. Possible values include: 'Get' - Method HTTPMethod `json:"method,omitempty"` - // Headers - List of HTTP headers. - Headers *[]HTTPHeader `json:"headers,omitempty"` - // ValidStatusCodes - Valid status codes. - ValidStatusCodes *[]int32 `json:"validStatusCodes,omitempty"` -} - -// HTTPHeader describes the HTTP header. -type HTTPHeader struct { - // Name - The name in HTTP header. - Name *string `json:"name,omitempty"` - // Value - The value in HTTP header. - Value *string `json:"value,omitempty"` -} - -// HubVirtualNetworkConnection hubVirtualNetworkConnection Resource. -type HubVirtualNetworkConnection struct { - autorest.Response `json:"-"` - *HubVirtualNetworkConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for HubVirtualNetworkConnection. -func (hvnc HubVirtualNetworkConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hvnc.HubVirtualNetworkConnectionProperties != nil { - objectMap["properties"] = hvnc.HubVirtualNetworkConnectionProperties - } - if hvnc.Name != nil { - objectMap["name"] = hvnc.Name - } - if hvnc.ID != nil { - objectMap["id"] = hvnc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for HubVirtualNetworkConnection struct. -func (hvnc *HubVirtualNetworkConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var hubVirtualNetworkConnectionProperties HubVirtualNetworkConnectionProperties - err = json.Unmarshal(*v, &hubVirtualNetworkConnectionProperties) - if err != nil { - return err - } - hvnc.HubVirtualNetworkConnectionProperties = &hubVirtualNetworkConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - hvnc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - hvnc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - hvnc.ID = &ID - } - } - } - - return nil -} - -// HubVirtualNetworkConnectionProperties parameters for HubVirtualNetworkConnection -type HubVirtualNetworkConnectionProperties struct { - // RemoteVirtualNetwork - Reference to the remote virtual network. - RemoteVirtualNetwork *SubResource `json:"remoteVirtualNetwork,omitempty"` - // AllowHubToRemoteVnetTransit - VirtualHub to RemoteVnet transit to enabled or not. - AllowHubToRemoteVnetTransit *bool `json:"allowHubToRemoteVnetTransit,omitempty"` - // AllowRemoteVnetToUseHubVnetGateways - Allow RemoteVnet to use Virtual Hub's gateways. - AllowRemoteVnetToUseHubVnetGateways *bool `json:"allowRemoteVnetToUseHubVnetGateways,omitempty"` - // EnableInternetSecurity - Enable internet security - EnableInternetSecurity *bool `json:"enableInternetSecurity,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// InboundNatPool inbound NAT pool of the load balancer. -type InboundNatPool struct { - // InboundNatPoolPropertiesFormat - Properties of load balancer inbound nat pool. - *InboundNatPoolPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatPool. -func (inp InboundNatPool) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inp.InboundNatPoolPropertiesFormat != nil { - objectMap["properties"] = inp.InboundNatPoolPropertiesFormat - } - if inp.Name != nil { - objectMap["name"] = inp.Name - } - if inp.Etag != nil { - objectMap["etag"] = inp.Etag - } - if inp.ID != nil { - objectMap["id"] = inp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InboundNatPool struct. -func (inp *InboundNatPool) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var inboundNatPoolPropertiesFormat InboundNatPoolPropertiesFormat - err = json.Unmarshal(*v, &inboundNatPoolPropertiesFormat) - if err != nil { - return err - } - inp.InboundNatPoolPropertiesFormat = &inboundNatPoolPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - inp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - inp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - inp.ID = &ID - } - } - } - - return nil -} - -// InboundNatPoolPropertiesFormat properties of Inbound NAT pool. -type InboundNatPoolPropertiesFormat struct { - // FrontendIPConfiguration - A reference to frontend IP addresses. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // Protocol - Possible values include: 'TransportProtocolUDP', 'TransportProtocolTCP', 'TransportProtocolAll' - Protocol TransportProtocol `json:"protocol,omitempty"` - // FrontendPortRangeStart - The first port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - FrontendPortRangeStart *int32 `json:"frontendPortRangeStart,omitempty"` - // FrontendPortRangeEnd - The last port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - FrontendPortRangeEnd *int32 `json:"frontendPortRangeEnd,omitempty"` - // BackendPort - The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. - BackendPort *int32 `json:"backendPort,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // EnableFloatingIP - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // ProvisioningState - Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// InboundNatRule inbound NAT rule of the load balancer. -type InboundNatRule struct { - autorest.Response `json:"-"` - // InboundNatRulePropertiesFormat - Properties of load balancer inbound nat rule. - *InboundNatRulePropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatRule. -func (inr InboundNatRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inr.InboundNatRulePropertiesFormat != nil { - objectMap["properties"] = inr.InboundNatRulePropertiesFormat - } - if inr.Name != nil { - objectMap["name"] = inr.Name - } - if inr.Etag != nil { - objectMap["etag"] = inr.Etag - } - if inr.ID != nil { - objectMap["id"] = inr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InboundNatRule struct. -func (inr *InboundNatRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var inboundNatRulePropertiesFormat InboundNatRulePropertiesFormat - err = json.Unmarshal(*v, &inboundNatRulePropertiesFormat) - if err != nil { - return err - } - inr.InboundNatRulePropertiesFormat = &inboundNatRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - inr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - inr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - inr.ID = &ID - } - } - } - - return nil -} - -// InboundNatRuleListResult response for ListInboundNatRule API service call. -type InboundNatRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of inbound nat rules in a load balancer. - Value *[]InboundNatRule `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatRuleListResult. -func (inrlr InboundNatRuleListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inrlr.Value != nil { - objectMap["value"] = inrlr.Value - } - return json.Marshal(objectMap) -} - -// InboundNatRuleListResultIterator provides access to a complete listing of InboundNatRule values. -type InboundNatRuleListResultIterator struct { - i int - page InboundNatRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InboundNatRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InboundNatRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InboundNatRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InboundNatRuleListResultIterator) Response() InboundNatRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InboundNatRuleListResultIterator) Value() InboundNatRule { - if !iter.page.NotDone() { - return InboundNatRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InboundNatRuleListResultIterator type. -func NewInboundNatRuleListResultIterator(page InboundNatRuleListResultPage) InboundNatRuleListResultIterator { - return InboundNatRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (inrlr InboundNatRuleListResult) IsEmpty() bool { - return inrlr.Value == nil || len(*inrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (inrlr InboundNatRuleListResult) hasNextLink() bool { - return inrlr.NextLink != nil && len(*inrlr.NextLink) != 0 -} - -// inboundNatRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (inrlr InboundNatRuleListResult) inboundNatRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !inrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(inrlr.NextLink))) -} - -// InboundNatRuleListResultPage contains a page of InboundNatRule values. -type InboundNatRuleListResultPage struct { - fn func(context.Context, InboundNatRuleListResult) (InboundNatRuleListResult, error) - inrlr InboundNatRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InboundNatRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.inrlr) - if err != nil { - return err - } - page.inrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InboundNatRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InboundNatRuleListResultPage) NotDone() bool { - return !page.inrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InboundNatRuleListResultPage) Response() InboundNatRuleListResult { - return page.inrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InboundNatRuleListResultPage) Values() []InboundNatRule { - if page.inrlr.IsEmpty() { - return nil - } - return *page.inrlr.Value -} - -// Creates a new instance of the InboundNatRuleListResultPage type. -func NewInboundNatRuleListResultPage(cur InboundNatRuleListResult, getNextPage func(context.Context, InboundNatRuleListResult) (InboundNatRuleListResult, error)) InboundNatRuleListResultPage { - return InboundNatRuleListResultPage{ - fn: getNextPage, - inrlr: cur, - } -} - -// InboundNatRulePropertiesFormat properties of the inbound NAT rule. -type InboundNatRulePropertiesFormat struct { - // FrontendIPConfiguration - A reference to frontend IP addresses. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // BackendIPConfiguration - READ-ONLY; A reference to a private IP address defined on a network interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations is forwarded to the backend IP. - BackendIPConfiguration *InterfaceIPConfiguration `json:"backendIPConfiguration,omitempty"` - // Protocol - Possible values include: 'TransportProtocolUDP', 'TransportProtocolTCP', 'TransportProtocolAll' - Protocol TransportProtocol `json:"protocol,omitempty"` - // FrontendPort - The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - FrontendPort *int32 `json:"frontendPort,omitempty"` - // BackendPort - The port used for the internal endpoint. Acceptable values range from 1 to 65535. - BackendPort *int32 `json:"backendPort,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // EnableFloatingIP - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // ProvisioningState - Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatRulePropertiesFormat. -func (inrpf InboundNatRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inrpf.FrontendIPConfiguration != nil { - objectMap["frontendIPConfiguration"] = inrpf.FrontendIPConfiguration - } - if inrpf.Protocol != "" { - objectMap["protocol"] = inrpf.Protocol - } - if inrpf.FrontendPort != nil { - objectMap["frontendPort"] = inrpf.FrontendPort - } - if inrpf.BackendPort != nil { - objectMap["backendPort"] = inrpf.BackendPort - } - if inrpf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = inrpf.IdleTimeoutInMinutes - } - if inrpf.EnableFloatingIP != nil { - objectMap["enableFloatingIP"] = inrpf.EnableFloatingIP - } - if inrpf.EnableTCPReset != nil { - objectMap["enableTcpReset"] = inrpf.EnableTCPReset - } - if inrpf.ProvisioningState != nil { - objectMap["provisioningState"] = inrpf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// InboundNatRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InboundNatRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InboundNatRulesClient) (InboundNatRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InboundNatRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InboundNatRulesCreateOrUpdateFuture.Result. -func (future *InboundNatRulesCreateOrUpdateFuture) result(client InboundNatRulesClient) (inr InboundNatRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - inr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InboundNatRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if inr.Response.Response, err = future.GetResult(sender); err == nil && inr.Response.Response.StatusCode != http.StatusNoContent { - inr, err = client.CreateOrUpdateResponder(inr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesCreateOrUpdateFuture", "Result", inr.Response.Response, "Failure responding to request") - } - } - return -} - -// InboundNatRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type InboundNatRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InboundNatRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InboundNatRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InboundNatRulesDeleteFuture.Result. -func (future *InboundNatRulesDeleteFuture) result(client InboundNatRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InboundNatRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// Interface a network interface in a resource group. -type Interface struct { - autorest.Response `json:"-"` - // InterfacePropertiesFormat - Properties of the network interface. - *InterfacePropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Interface. -func (i Interface) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if i.InterfacePropertiesFormat != nil { - objectMap["properties"] = i.InterfacePropertiesFormat - } - if i.Etag != nil { - objectMap["etag"] = i.Etag - } - if i.ID != nil { - objectMap["id"] = i.ID - } - if i.Location != nil { - objectMap["location"] = i.Location - } - if i.Tags != nil { - objectMap["tags"] = i.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Interface struct. -func (i *Interface) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var interfacePropertiesFormat InterfacePropertiesFormat - err = json.Unmarshal(*v, &interfacePropertiesFormat) - if err != nil { - return err - } - i.InterfacePropertiesFormat = &interfacePropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - i.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - i.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - i.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - i.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - i.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - i.Tags = tags - } - } - } - - return nil -} - -// InterfaceAssociation network interface and its custom security rules. -type InterfaceAssociation struct { - // ID - READ-ONLY; Network interface ID. - ID *string `json:"id,omitempty"` - // SecurityRules - Collection of custom security rules. - SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceAssociation. -func (ia InterfaceAssociation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ia.SecurityRules != nil { - objectMap["securityRules"] = ia.SecurityRules - } - return json.Marshal(objectMap) -} - -// InterfaceDNSSettings DNS settings of a network interface. -type InterfaceDNSSettings struct { - // DNSServers - List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dnsServers collection. - DNSServers *[]string `json:"dnsServers,omitempty"` - // AppliedDNSServers - If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers from all NICs that are part of the Availability Set. This property is what is configured on each of those VMs. - AppliedDNSServers *[]string `json:"appliedDnsServers,omitempty"` - // InternalDNSNameLabel - Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - InternalDNSNameLabel *string `json:"internalDnsNameLabel,omitempty"` - // InternalFqdn - Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - InternalFqdn *string `json:"internalFqdn,omitempty"` - // InternalDomainNameSuffix - Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internalDomainNameSuffix. - InternalDomainNameSuffix *string `json:"internalDomainNameSuffix,omitempty"` -} - -// InterfaceEndpoint interface endpoint resource. -type InterfaceEndpoint struct { - autorest.Response `json:"-"` - // InterfaceEndpointProperties - Properties of the interface endpoint. - *InterfaceEndpointProperties `json:"properties,omitempty"` - // Etag - Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for InterfaceEndpoint. -func (ie InterfaceEndpoint) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ie.InterfaceEndpointProperties != nil { - objectMap["properties"] = ie.InterfaceEndpointProperties - } - if ie.Etag != nil { - objectMap["etag"] = ie.Etag - } - if ie.ID != nil { - objectMap["id"] = ie.ID - } - if ie.Location != nil { - objectMap["location"] = ie.Location - } - if ie.Tags != nil { - objectMap["tags"] = ie.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InterfaceEndpoint struct. -func (ie *InterfaceEndpoint) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var interfaceEndpointProperties InterfaceEndpointProperties - err = json.Unmarshal(*v, &interfaceEndpointProperties) - if err != nil { - return err - } - ie.InterfaceEndpointProperties = &interfaceEndpointProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ie.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ie.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ie.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ie.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ie.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ie.Tags = tags - } - } - } - - return nil -} - -// InterfaceEndpointListResult response for the ListInterfaceEndpoints API service call. -type InterfaceEndpointListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of InterfaceEndpoint resources in a resource group. - Value *[]InterfaceEndpoint `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceEndpointListResult. -func (ielr InterfaceEndpointListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ielr.Value != nil { - objectMap["value"] = ielr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceEndpointListResultIterator provides access to a complete listing of InterfaceEndpoint values. -type InterfaceEndpointListResultIterator struct { - i int - page InterfaceEndpointListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceEndpointListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceEndpointListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceEndpointListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceEndpointListResultIterator) Response() InterfaceEndpointListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceEndpointListResultIterator) Value() InterfaceEndpoint { - if !iter.page.NotDone() { - return InterfaceEndpoint{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceEndpointListResultIterator type. -func NewInterfaceEndpointListResultIterator(page InterfaceEndpointListResultPage) InterfaceEndpointListResultIterator { - return InterfaceEndpointListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ielr InterfaceEndpointListResult) IsEmpty() bool { - return ielr.Value == nil || len(*ielr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ielr InterfaceEndpointListResult) hasNextLink() bool { - return ielr.NextLink != nil && len(*ielr.NextLink) != 0 -} - -// interfaceEndpointListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ielr InterfaceEndpointListResult) interfaceEndpointListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ielr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ielr.NextLink))) -} - -// InterfaceEndpointListResultPage contains a page of InterfaceEndpoint values. -type InterfaceEndpointListResultPage struct { - fn func(context.Context, InterfaceEndpointListResult) (InterfaceEndpointListResult, error) - ielr InterfaceEndpointListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceEndpointListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceEndpointListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ielr) - if err != nil { - return err - } - page.ielr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceEndpointListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceEndpointListResultPage) NotDone() bool { - return !page.ielr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceEndpointListResultPage) Response() InterfaceEndpointListResult { - return page.ielr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceEndpointListResultPage) Values() []InterfaceEndpoint { - if page.ielr.IsEmpty() { - return nil - } - return *page.ielr.Value -} - -// Creates a new instance of the InterfaceEndpointListResultPage type. -func NewInterfaceEndpointListResultPage(cur InterfaceEndpointListResult, getNextPage func(context.Context, InterfaceEndpointListResult) (InterfaceEndpointListResult, error)) InterfaceEndpointListResultPage { - return InterfaceEndpointListResultPage{ - fn: getNextPage, - ielr: cur, - } -} - -// InterfaceEndpointProperties properties of the interface endpoint. -type InterfaceEndpointProperties struct { - // Fqdn - A first-party service's FQDN that is mapped to the private IP allocated via this interface endpoint. - Fqdn *string `json:"fqdn,omitempty"` - // EndpointService - A reference to the service being brought into the virtual network. - EndpointService *EndpointService `json:"endpointService,omitempty"` - // Subnet - The ID of the subnet from which the private IP will be allocated. - Subnet *Subnet `json:"subnet,omitempty"` - // NetworkInterfaces - READ-ONLY; Gets an array of references to the network interfaces created for this interface endpoint. - NetworkInterfaces *[]Interface `json:"networkInterfaces,omitempty"` - // Owner - READ-ONLY; A read-only property that identifies who created this interface endpoint. - Owner *string `json:"owner,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the interface endpoint. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceEndpointProperties. -func (iep InterfaceEndpointProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iep.Fqdn != nil { - objectMap["fqdn"] = iep.Fqdn - } - if iep.EndpointService != nil { - objectMap["endpointService"] = iep.EndpointService - } - if iep.Subnet != nil { - objectMap["subnet"] = iep.Subnet - } - return json.Marshal(objectMap) -} - -// InterfaceEndpointsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfaceEndpointsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfaceEndpointsClient) (InterfaceEndpoint, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfaceEndpointsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfaceEndpointsCreateOrUpdateFuture.Result. -func (future *InterfaceEndpointsCreateOrUpdateFuture) result(client InterfaceEndpointsClient) (ie InterfaceEndpoint, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ie.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfaceEndpointsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ie.Response.Response, err = future.GetResult(sender); err == nil && ie.Response.Response.StatusCode != http.StatusNoContent { - ie, err = client.CreateOrUpdateResponder(ie.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsCreateOrUpdateFuture", "Result", ie.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfaceEndpointsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfaceEndpointsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfaceEndpointsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfaceEndpointsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfaceEndpointsDeleteFuture.Result. -func (future *InterfaceEndpointsDeleteFuture) result(client InterfaceEndpointsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceEndpointsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfaceEndpointsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// InterfaceIPConfiguration iPConfiguration in a network interface. -type InterfaceIPConfiguration struct { - autorest.Response `json:"-"` - // InterfaceIPConfigurationPropertiesFormat - Network interface IP configuration properties. - *InterfaceIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceIPConfiguration. -func (iic InterfaceIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iic.InterfaceIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = iic.InterfaceIPConfigurationPropertiesFormat - } - if iic.Name != nil { - objectMap["name"] = iic.Name - } - if iic.Etag != nil { - objectMap["etag"] = iic.Etag - } - if iic.ID != nil { - objectMap["id"] = iic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InterfaceIPConfiguration struct. -func (iic *InterfaceIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var interfaceIPConfigurationPropertiesFormat InterfaceIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &interfaceIPConfigurationPropertiesFormat) - if err != nil { - return err - } - iic.InterfaceIPConfigurationPropertiesFormat = &interfaceIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - iic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - iic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - iic.ID = &ID - } - } - } - - return nil -} - -// InterfaceIPConfigurationListResult response for list ip configurations API service call. -type InterfaceIPConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - A list of ip configurations. - Value *[]InterfaceIPConfiguration `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceIPConfigurationListResult. -func (iiclr InterfaceIPConfigurationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iiclr.Value != nil { - objectMap["value"] = iiclr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceIPConfigurationListResultIterator provides access to a complete listing of -// InterfaceIPConfiguration values. -type InterfaceIPConfigurationListResultIterator struct { - i int - page InterfaceIPConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceIPConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceIPConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceIPConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceIPConfigurationListResultIterator) Response() InterfaceIPConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceIPConfigurationListResultIterator) Value() InterfaceIPConfiguration { - if !iter.page.NotDone() { - return InterfaceIPConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceIPConfigurationListResultIterator type. -func NewInterfaceIPConfigurationListResultIterator(page InterfaceIPConfigurationListResultPage) InterfaceIPConfigurationListResultIterator { - return InterfaceIPConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (iiclr InterfaceIPConfigurationListResult) IsEmpty() bool { - return iiclr.Value == nil || len(*iiclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (iiclr InterfaceIPConfigurationListResult) hasNextLink() bool { - return iiclr.NextLink != nil && len(*iiclr.NextLink) != 0 -} - -// interfaceIPConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (iiclr InterfaceIPConfigurationListResult) interfaceIPConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !iiclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(iiclr.NextLink))) -} - -// InterfaceIPConfigurationListResultPage contains a page of InterfaceIPConfiguration values. -type InterfaceIPConfigurationListResultPage struct { - fn func(context.Context, InterfaceIPConfigurationListResult) (InterfaceIPConfigurationListResult, error) - iiclr InterfaceIPConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceIPConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.iiclr) - if err != nil { - return err - } - page.iiclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceIPConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceIPConfigurationListResultPage) NotDone() bool { - return !page.iiclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceIPConfigurationListResultPage) Response() InterfaceIPConfigurationListResult { - return page.iiclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceIPConfigurationListResultPage) Values() []InterfaceIPConfiguration { - if page.iiclr.IsEmpty() { - return nil - } - return *page.iiclr.Value -} - -// Creates a new instance of the InterfaceIPConfigurationListResultPage type. -func NewInterfaceIPConfigurationListResultPage(cur InterfaceIPConfigurationListResult, getNextPage func(context.Context, InterfaceIPConfigurationListResult) (InterfaceIPConfigurationListResult, error)) InterfaceIPConfigurationListResultPage { - return InterfaceIPConfigurationListResultPage{ - fn: getNextPage, - iiclr: cur, - } -} - -// InterfaceIPConfigurationPropertiesFormat properties of IP configuration. -type InterfaceIPConfigurationPropertiesFormat struct { - // VirtualNetworkTaps - The reference to Virtual Network Taps. - VirtualNetworkTaps *[]VirtualNetworkTap `json:"virtualNetworkTaps,omitempty"` - // ApplicationGatewayBackendAddressPools - The reference of ApplicationGatewayBackendAddressPool resource. - ApplicationGatewayBackendAddressPools *[]ApplicationGatewayBackendAddressPool `json:"applicationGatewayBackendAddressPools,omitempty"` - // LoadBalancerBackendAddressPools - The reference of LoadBalancerBackendAddressPool resource. - LoadBalancerBackendAddressPools *[]BackendAddressPool `json:"loadBalancerBackendAddressPools,omitempty"` - // LoadBalancerInboundNatRules - A list of references of LoadBalancerInboundNatRules. - LoadBalancerInboundNatRules *[]InboundNatRule `json:"loadBalancerInboundNatRules,omitempty"` - // PrivateIPAddress - Private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - Defines how a private IP address is assigned. Possible values are: 'Static' and 'Dynamic'. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // PrivateIPAddressVersion - Available from Api-Version 2016-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. Possible values include: 'IPv4', 'IPv6' - PrivateIPAddressVersion IPVersion `json:"privateIPAddressVersion,omitempty"` - // Subnet - Subnet bound to the IP configuration. - Subnet *Subnet `json:"subnet,omitempty"` - // Primary - Gets whether this is a primary customer address on the network interface. - Primary *bool `json:"primary,omitempty"` - // PublicIPAddress - Public IP address bound to the IP configuration. - PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` - // ApplicationSecurityGroups - Application security groups in which the IP configuration is included. - ApplicationSecurityGroups *[]ApplicationSecurityGroup `json:"applicationSecurityGroups,omitempty"` - // ProvisioningState - The provisioning state of the network interface IP configuration. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// InterfaceListResult response for the ListNetworkInterface API service call. -type InterfaceListResult struct { - autorest.Response `json:"-"` - // Value - A list of network interfaces in a resource group. - Value *[]Interface `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceListResult. -func (ilr InterfaceListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ilr.Value != nil { - objectMap["value"] = ilr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceListResultIterator provides access to a complete listing of Interface values. -type InterfaceListResultIterator struct { - i int - page InterfaceListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceListResultIterator) Response() InterfaceListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceListResultIterator) Value() Interface { - if !iter.page.NotDone() { - return Interface{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceListResultIterator type. -func NewInterfaceListResultIterator(page InterfaceListResultPage) InterfaceListResultIterator { - return InterfaceListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ilr InterfaceListResult) IsEmpty() bool { - return ilr.Value == nil || len(*ilr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ilr InterfaceListResult) hasNextLink() bool { - return ilr.NextLink != nil && len(*ilr.NextLink) != 0 -} - -// interfaceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ilr InterfaceListResult) interfaceListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ilr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ilr.NextLink))) -} - -// InterfaceListResultPage contains a page of Interface values. -type InterfaceListResultPage struct { - fn func(context.Context, InterfaceListResult) (InterfaceListResult, error) - ilr InterfaceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ilr) - if err != nil { - return err - } - page.ilr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceListResultPage) NotDone() bool { - return !page.ilr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceListResultPage) Response() InterfaceListResult { - return page.ilr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceListResultPage) Values() []Interface { - if page.ilr.IsEmpty() { - return nil - } - return *page.ilr.Value -} - -// Creates a new instance of the InterfaceListResultPage type. -func NewInterfaceListResultPage(cur InterfaceListResult, getNextPage func(context.Context, InterfaceListResult) (InterfaceListResult, error)) InterfaceListResultPage { - return InterfaceListResultPage{ - fn: getNextPage, - ilr: cur, - } -} - -// InterfaceLoadBalancerListResult response for list ip configurations API service call. -type InterfaceLoadBalancerListResult struct { - autorest.Response `json:"-"` - // Value - A list of load balancers. - Value *[]LoadBalancer `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceLoadBalancerListResult. -func (ilblr InterfaceLoadBalancerListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ilblr.Value != nil { - objectMap["value"] = ilblr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceLoadBalancerListResultIterator provides access to a complete listing of LoadBalancer values. -type InterfaceLoadBalancerListResultIterator struct { - i int - page InterfaceLoadBalancerListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceLoadBalancerListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancerListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceLoadBalancerListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceLoadBalancerListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceLoadBalancerListResultIterator) Response() InterfaceLoadBalancerListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceLoadBalancerListResultIterator) Value() LoadBalancer { - if !iter.page.NotDone() { - return LoadBalancer{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceLoadBalancerListResultIterator type. -func NewInterfaceLoadBalancerListResultIterator(page InterfaceLoadBalancerListResultPage) InterfaceLoadBalancerListResultIterator { - return InterfaceLoadBalancerListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ilblr InterfaceLoadBalancerListResult) IsEmpty() bool { - return ilblr.Value == nil || len(*ilblr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ilblr InterfaceLoadBalancerListResult) hasNextLink() bool { - return ilblr.NextLink != nil && len(*ilblr.NextLink) != 0 -} - -// interfaceLoadBalancerListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ilblr InterfaceLoadBalancerListResult) interfaceLoadBalancerListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ilblr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ilblr.NextLink))) -} - -// InterfaceLoadBalancerListResultPage contains a page of LoadBalancer values. -type InterfaceLoadBalancerListResultPage struct { - fn func(context.Context, InterfaceLoadBalancerListResult) (InterfaceLoadBalancerListResult, error) - ilblr InterfaceLoadBalancerListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceLoadBalancerListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancerListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ilblr) - if err != nil { - return err - } - page.ilblr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceLoadBalancerListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceLoadBalancerListResultPage) NotDone() bool { - return !page.ilblr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceLoadBalancerListResultPage) Response() InterfaceLoadBalancerListResult { - return page.ilblr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceLoadBalancerListResultPage) Values() []LoadBalancer { - if page.ilblr.IsEmpty() { - return nil - } - return *page.ilblr.Value -} - -// Creates a new instance of the InterfaceLoadBalancerListResultPage type. -func NewInterfaceLoadBalancerListResultPage(cur InterfaceLoadBalancerListResult, getNextPage func(context.Context, InterfaceLoadBalancerListResult) (InterfaceLoadBalancerListResult, error)) InterfaceLoadBalancerListResultPage { - return InterfaceLoadBalancerListResultPage{ - fn: getNextPage, - ilblr: cur, - } -} - -// InterfacePropertiesFormat networkInterface properties. -type InterfacePropertiesFormat struct { - // VirtualMachine - READ-ONLY; The reference of a virtual machine. - VirtualMachine *SubResource `json:"virtualMachine,omitempty"` - // NetworkSecurityGroup - The reference of the NetworkSecurityGroup resource. - NetworkSecurityGroup *SecurityGroup `json:"networkSecurityGroup,omitempty"` - // InterfaceEndpoint - READ-ONLY; A reference to the interface endpoint to which the network interface is linked. - InterfaceEndpoint *InterfaceEndpoint `json:"interfaceEndpoint,omitempty"` - // IPConfigurations - A list of IPConfigurations of the network interface. - IPConfigurations *[]InterfaceIPConfiguration `json:"ipConfigurations,omitempty"` - // TapConfigurations - A list of TapConfigurations of the network interface. - TapConfigurations *[]InterfaceTapConfiguration `json:"tapConfigurations,omitempty"` - // DNSSettings - The DNS settings in network interface. - DNSSettings *InterfaceDNSSettings `json:"dnsSettings,omitempty"` - // MacAddress - The MAC address of the network interface. - MacAddress *string `json:"macAddress,omitempty"` - // Primary - Gets whether this is a primary network interface on a virtual machine. - Primary *bool `json:"primary,omitempty"` - // EnableAcceleratedNetworking - If the network interface is accelerated networking enabled. - EnableAcceleratedNetworking *bool `json:"enableAcceleratedNetworking,omitempty"` - // EnableIPForwarding - Indicates whether IP forwarding is enabled on this network interface. - EnableIPForwarding *bool `json:"enableIPForwarding,omitempty"` - // HostedWorkloads - READ-ONLY; A list of references to linked BareMetal resources - HostedWorkloads *[]string `json:"hostedWorkloads,omitempty"` - // ResourceGUID - The resource GUID property of the network interface resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfacePropertiesFormat. -func (ipf InterfacePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ipf.NetworkSecurityGroup != nil { - objectMap["networkSecurityGroup"] = ipf.NetworkSecurityGroup - } - if ipf.IPConfigurations != nil { - objectMap["ipConfigurations"] = ipf.IPConfigurations - } - if ipf.TapConfigurations != nil { - objectMap["tapConfigurations"] = ipf.TapConfigurations - } - if ipf.DNSSettings != nil { - objectMap["dnsSettings"] = ipf.DNSSettings - } - if ipf.MacAddress != nil { - objectMap["macAddress"] = ipf.MacAddress - } - if ipf.Primary != nil { - objectMap["primary"] = ipf.Primary - } - if ipf.EnableAcceleratedNetworking != nil { - objectMap["enableAcceleratedNetworking"] = ipf.EnableAcceleratedNetworking - } - if ipf.EnableIPForwarding != nil { - objectMap["enableIPForwarding"] = ipf.EnableIPForwarding - } - if ipf.ResourceGUID != nil { - objectMap["resourceGuid"] = ipf.ResourceGUID - } - if ipf.ProvisioningState != nil { - objectMap["provisioningState"] = ipf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// InterfacesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfacesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (Interface, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesCreateOrUpdateFuture.Result. -func (future *InterfacesCreateOrUpdateFuture) result(client InterfacesClient) (i Interface, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - i.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if i.Response.Response, err = future.GetResult(sender); err == nil && i.Response.Response.StatusCode != http.StatusNoContent { - i, err = client.CreateOrUpdateResponder(i.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesCreateOrUpdateFuture", "Result", i.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfacesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type InterfacesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesDeleteFuture.Result. -func (future *InterfacesDeleteFuture) result(client InterfacesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// InterfacesGetEffectiveRouteTableFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfacesGetEffectiveRouteTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (EffectiveRouteListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesGetEffectiveRouteTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesGetEffectiveRouteTableFuture.Result. -func (future *InterfacesGetEffectiveRouteTableFuture) result(client InterfacesClient) (erlr EffectiveRouteListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesGetEffectiveRouteTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesGetEffectiveRouteTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erlr.Response.Response, err = future.GetResult(sender); err == nil && erlr.Response.Response.StatusCode != http.StatusNoContent { - erlr, err = client.GetEffectiveRouteTableResponder(erlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesGetEffectiveRouteTableFuture", "Result", erlr.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfacesListEffectiveNetworkSecurityGroupsFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type InterfacesListEffectiveNetworkSecurityGroupsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (EffectiveNetworkSecurityGroupListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesListEffectiveNetworkSecurityGroupsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesListEffectiveNetworkSecurityGroupsFuture.Result. -func (future *InterfacesListEffectiveNetworkSecurityGroupsFuture) result(client InterfacesClient) (ensglr EffectiveNetworkSecurityGroupListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesListEffectiveNetworkSecurityGroupsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ensglr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesListEffectiveNetworkSecurityGroupsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ensglr.Response.Response, err = future.GetResult(sender); err == nil && ensglr.Response.Response.StatusCode != http.StatusNoContent { - ensglr, err = client.ListEffectiveNetworkSecurityGroupsResponder(ensglr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesListEffectiveNetworkSecurityGroupsFuture", "Result", ensglr.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfacesUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type InterfacesUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (Interface, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesUpdateTagsFuture.Result. -func (future *InterfacesUpdateTagsFuture) result(client InterfacesClient) (i Interface, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - i.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if i.Response.Response, err = future.GetResult(sender); err == nil && i.Response.Response.StatusCode != http.StatusNoContent { - i, err = client.UpdateTagsResponder(i.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesUpdateTagsFuture", "Result", i.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfaceTapConfiguration tap configuration in a Network Interface -type InterfaceTapConfiguration struct { - autorest.Response `json:"-"` - // InterfaceTapConfigurationPropertiesFormat - Properties of the Virtual Network Tap configuration - *InterfaceTapConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceTapConfiguration. -func (itc InterfaceTapConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if itc.InterfaceTapConfigurationPropertiesFormat != nil { - objectMap["properties"] = itc.InterfaceTapConfigurationPropertiesFormat - } - if itc.Name != nil { - objectMap["name"] = itc.Name - } - if itc.Etag != nil { - objectMap["etag"] = itc.Etag - } - if itc.ID != nil { - objectMap["id"] = itc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InterfaceTapConfiguration struct. -func (itc *InterfaceTapConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var interfaceTapConfigurationPropertiesFormat InterfaceTapConfigurationPropertiesFormat - err = json.Unmarshal(*v, &interfaceTapConfigurationPropertiesFormat) - if err != nil { - return err - } - itc.InterfaceTapConfigurationPropertiesFormat = &interfaceTapConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - itc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - itc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - itc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - itc.ID = &ID - } - } - } - - return nil -} - -// InterfaceTapConfigurationListResult response for list tap configurations API service call. -type InterfaceTapConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - A list of tap configurations. - Value *[]InterfaceTapConfiguration `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceTapConfigurationListResult. -func (itclr InterfaceTapConfigurationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if itclr.Value != nil { - objectMap["value"] = itclr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceTapConfigurationListResultIterator provides access to a complete listing of -// InterfaceTapConfiguration values. -type InterfaceTapConfigurationListResultIterator struct { - i int - page InterfaceTapConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceTapConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceTapConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceTapConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceTapConfigurationListResultIterator) Response() InterfaceTapConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceTapConfigurationListResultIterator) Value() InterfaceTapConfiguration { - if !iter.page.NotDone() { - return InterfaceTapConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceTapConfigurationListResultIterator type. -func NewInterfaceTapConfigurationListResultIterator(page InterfaceTapConfigurationListResultPage) InterfaceTapConfigurationListResultIterator { - return InterfaceTapConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (itclr InterfaceTapConfigurationListResult) IsEmpty() bool { - return itclr.Value == nil || len(*itclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (itclr InterfaceTapConfigurationListResult) hasNextLink() bool { - return itclr.NextLink != nil && len(*itclr.NextLink) != 0 -} - -// interfaceTapConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (itclr InterfaceTapConfigurationListResult) interfaceTapConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !itclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(itclr.NextLink))) -} - -// InterfaceTapConfigurationListResultPage contains a page of InterfaceTapConfiguration values. -type InterfaceTapConfigurationListResultPage struct { - fn func(context.Context, InterfaceTapConfigurationListResult) (InterfaceTapConfigurationListResult, error) - itclr InterfaceTapConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceTapConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.itclr) - if err != nil { - return err - } - page.itclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceTapConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceTapConfigurationListResultPage) NotDone() bool { - return !page.itclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceTapConfigurationListResultPage) Response() InterfaceTapConfigurationListResult { - return page.itclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceTapConfigurationListResultPage) Values() []InterfaceTapConfiguration { - if page.itclr.IsEmpty() { - return nil - } - return *page.itclr.Value -} - -// Creates a new instance of the InterfaceTapConfigurationListResultPage type. -func NewInterfaceTapConfigurationListResultPage(cur InterfaceTapConfigurationListResult, getNextPage func(context.Context, InterfaceTapConfigurationListResult) (InterfaceTapConfigurationListResult, error)) InterfaceTapConfigurationListResultPage { - return InterfaceTapConfigurationListResultPage{ - fn: getNextPage, - itclr: cur, - } -} - -// InterfaceTapConfigurationPropertiesFormat properties of Virtual Network Tap configuration. -type InterfaceTapConfigurationPropertiesFormat struct { - // VirtualNetworkTap - The reference of the Virtual Network Tap resource. - VirtualNetworkTap *VirtualNetworkTap `json:"virtualNetworkTap,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network interface tap configuration. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceTapConfigurationPropertiesFormat. -func (itcpf InterfaceTapConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if itcpf.VirtualNetworkTap != nil { - objectMap["virtualNetworkTap"] = itcpf.VirtualNetworkTap - } - return json.Marshal(objectMap) -} - -// InterfaceTapConfigurationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type InterfaceTapConfigurationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfaceTapConfigurationsClient) (InterfaceTapConfiguration, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfaceTapConfigurationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfaceTapConfigurationsCreateOrUpdateFuture.Result. -func (future *InterfaceTapConfigurationsCreateOrUpdateFuture) result(client InterfaceTapConfigurationsClient) (itc InterfaceTapConfiguration, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - itc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfaceTapConfigurationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if itc.Response.Response, err = future.GetResult(sender); err == nil && itc.Response.Response.StatusCode != http.StatusNoContent { - itc, err = client.CreateOrUpdateResponder(itc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsCreateOrUpdateFuture", "Result", itc.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfaceTapConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfaceTapConfigurationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfaceTapConfigurationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfaceTapConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfaceTapConfigurationsDeleteFuture.Result. -func (future *InterfaceTapConfigurationsDeleteFuture) result(client InterfaceTapConfigurationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfaceTapConfigurationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// IPAddressAvailabilityResult response for CheckIPAddressAvailability API service call -type IPAddressAvailabilityResult struct { - autorest.Response `json:"-"` - // Available - Private IP address availability. - Available *bool `json:"available,omitempty"` - // AvailableIPAddresses - Contains other available private IP addresses if the asked for address is taken. - AvailableIPAddresses *[]string `json:"availableIPAddresses,omitempty"` -} - -// IPConfiguration IP configuration -type IPConfiguration struct { - // IPConfigurationPropertiesFormat - Properties of the IP configuration - *IPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfiguration. -func (ic IPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ic.IPConfigurationPropertiesFormat != nil { - objectMap["properties"] = ic.IPConfigurationPropertiesFormat - } - if ic.Name != nil { - objectMap["name"] = ic.Name - } - if ic.Etag != nil { - objectMap["etag"] = ic.Etag - } - if ic.ID != nil { - objectMap["id"] = ic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for IPConfiguration struct. -func (ic *IPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var IPConfigurationPropertiesFormat IPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &IPConfigurationPropertiesFormat) - if err != nil { - return err - } - ic.IPConfigurationPropertiesFormat = &IPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ic.ID = &ID - } - } - } - - return nil -} - -// IPConfigurationProfile IP configuration profile child resource. -type IPConfigurationProfile struct { - // IPConfigurationProfilePropertiesFormat - Properties of the IP configuration profile. - *IPConfigurationProfilePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfigurationProfile. -func (icp IPConfigurationProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icp.IPConfigurationProfilePropertiesFormat != nil { - objectMap["properties"] = icp.IPConfigurationProfilePropertiesFormat - } - if icp.Name != nil { - objectMap["name"] = icp.Name - } - if icp.Etag != nil { - objectMap["etag"] = icp.Etag - } - if icp.ID != nil { - objectMap["id"] = icp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for IPConfigurationProfile struct. -func (icp *IPConfigurationProfile) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var IPConfigurationProfilePropertiesFormat IPConfigurationProfilePropertiesFormat - err = json.Unmarshal(*v, &IPConfigurationProfilePropertiesFormat) - if err != nil { - return err - } - icp.IPConfigurationProfilePropertiesFormat = &IPConfigurationProfilePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - icp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - icp.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - icp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - icp.ID = &ID - } - } - } - - return nil -} - -// IPConfigurationProfilePropertiesFormat IP configuration profile properties. -type IPConfigurationProfilePropertiesFormat struct { - // Subnet - The reference of the subnet resource to create a container network interface ip configuration. - Subnet *Subnet `json:"subnet,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfigurationProfilePropertiesFormat. -func (icppf IPConfigurationProfilePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icppf.Subnet != nil { - objectMap["subnet"] = icppf.Subnet - } - return json.Marshal(objectMap) -} - -// IPConfigurationPropertiesFormat properties of IP configuration. -type IPConfigurationPropertiesFormat struct { - // PrivateIPAddress - The private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The private IP allocation method. Possible values are 'Static' and 'Dynamic'. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - The reference of the subnet resource. - Subnet *Subnet `json:"subnet,omitempty"` - // PublicIPAddress - The reference of the public IP resource. - PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` - // ProvisioningState - Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// IpsecPolicy an IPSec Policy configuration for a virtual network gateway connection -type IpsecPolicy struct { - // SaLifeTimeSeconds - The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for a site to site VPN tunnel. - SaLifeTimeSeconds *int32 `json:"saLifeTimeSeconds,omitempty"` - // SaDataSizeKilobytes - The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for a site to site VPN tunnel. - SaDataSizeKilobytes *int32 `json:"saDataSizeKilobytes,omitempty"` - // IpsecEncryption - The IPSec encryption algorithm (IKE phase 1). Possible values include: 'IpsecEncryptionNone', 'IpsecEncryptionDES', 'IpsecEncryptionDES3', 'IpsecEncryptionAES128', 'IpsecEncryptionAES192', 'IpsecEncryptionAES256', 'IpsecEncryptionGCMAES128', 'IpsecEncryptionGCMAES192', 'IpsecEncryptionGCMAES256' - IpsecEncryption IpsecEncryption `json:"ipsecEncryption,omitempty"` - // IpsecIntegrity - The IPSec integrity algorithm (IKE phase 1). Possible values include: 'IpsecIntegrityMD5', 'IpsecIntegritySHA1', 'IpsecIntegritySHA256', 'IpsecIntegrityGCMAES128', 'IpsecIntegrityGCMAES192', 'IpsecIntegrityGCMAES256' - IpsecIntegrity IpsecIntegrity `json:"ipsecIntegrity,omitempty"` - // IkeEncryption - The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES256', 'GCMAES128' - IkeEncryption IkeEncryption `json:"ikeEncryption,omitempty"` - // IkeIntegrity - The IKE integrity algorithm (IKE phase 2). Possible values include: 'IkeIntegrityMD5', 'IkeIntegritySHA1', 'IkeIntegritySHA256', 'IkeIntegritySHA384', 'IkeIntegrityGCMAES256', 'IkeIntegrityGCMAES128' - IkeIntegrity IkeIntegrity `json:"ikeIntegrity,omitempty"` - // DhGroup - The DH Groups used in IKE Phase 1 for initial SA. Possible values include: 'None', 'DHGroup1', 'DHGroup2', 'DHGroup14', 'DHGroup2048', 'ECP256', 'ECP384', 'DHGroup24' - DhGroup DhGroup `json:"dhGroup,omitempty"` - // PfsGroup - The Pfs Groups used in IKE Phase 2 for new child SA. Possible values include: 'PfsGroupNone', 'PfsGroupPFS1', 'PfsGroupPFS2', 'PfsGroupPFS2048', 'PfsGroupECP256', 'PfsGroupECP384', 'PfsGroupPFS24', 'PfsGroupPFS14', 'PfsGroupPFSMM' - PfsGroup PfsGroup `json:"pfsGroup,omitempty"` -} - -// IPTag contains the IpTag associated with the object -type IPTag struct { - // IPTagType - Gets or sets the ipTag type: Example FirstPartyUsage. - IPTagType *string `json:"ipTagType,omitempty"` - // Tag - Gets or sets value of the IpTag associated with the public IP. Example SQL, Storage etc - Tag *string `json:"tag,omitempty"` -} - -// Ipv6ExpressRouteCircuitPeeringConfig contains IPv6 peering config. -type Ipv6ExpressRouteCircuitPeeringConfig struct { - // PrimaryPeerAddressPrefix - The primary address prefix. - PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` - // SecondaryPeerAddressPrefix - The secondary address prefix. - SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` - // MicrosoftPeeringConfig - The Microsoft peering configuration. - MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` - // RouteFilter - The reference of the RouteFilter resource. - RouteFilter *RouteFilter `json:"routeFilter,omitempty"` - // State - The state of peering. Possible values are: 'Disabled' and 'Enabled'. Possible values include: 'ExpressRouteCircuitPeeringStateDisabled', 'ExpressRouteCircuitPeeringStateEnabled' - State ExpressRouteCircuitPeeringState `json:"state,omitempty"` -} - -// ListHubVirtualNetworkConnectionsResult list of HubVirtualNetworkConnections and a URL nextLink to get -// the next set of results. -type ListHubVirtualNetworkConnectionsResult struct { - autorest.Response `json:"-"` - // Value - List of HubVirtualNetworkConnections. - Value *[]HubVirtualNetworkConnection `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListHubVirtualNetworkConnectionsResultIterator provides access to a complete listing of -// HubVirtualNetworkConnection values. -type ListHubVirtualNetworkConnectionsResultIterator struct { - i int - page ListHubVirtualNetworkConnectionsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListHubVirtualNetworkConnectionsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListHubVirtualNetworkConnectionsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListHubVirtualNetworkConnectionsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListHubVirtualNetworkConnectionsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListHubVirtualNetworkConnectionsResultIterator) Response() ListHubVirtualNetworkConnectionsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListHubVirtualNetworkConnectionsResultIterator) Value() HubVirtualNetworkConnection { - if !iter.page.NotDone() { - return HubVirtualNetworkConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListHubVirtualNetworkConnectionsResultIterator type. -func NewListHubVirtualNetworkConnectionsResultIterator(page ListHubVirtualNetworkConnectionsResultPage) ListHubVirtualNetworkConnectionsResultIterator { - return ListHubVirtualNetworkConnectionsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lhvncr ListHubVirtualNetworkConnectionsResult) IsEmpty() bool { - return lhvncr.Value == nil || len(*lhvncr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lhvncr ListHubVirtualNetworkConnectionsResult) hasNextLink() bool { - return lhvncr.NextLink != nil && len(*lhvncr.NextLink) != 0 -} - -// listHubVirtualNetworkConnectionsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lhvncr ListHubVirtualNetworkConnectionsResult) listHubVirtualNetworkConnectionsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lhvncr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lhvncr.NextLink))) -} - -// ListHubVirtualNetworkConnectionsResultPage contains a page of HubVirtualNetworkConnection values. -type ListHubVirtualNetworkConnectionsResultPage struct { - fn func(context.Context, ListHubVirtualNetworkConnectionsResult) (ListHubVirtualNetworkConnectionsResult, error) - lhvncr ListHubVirtualNetworkConnectionsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListHubVirtualNetworkConnectionsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListHubVirtualNetworkConnectionsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lhvncr) - if err != nil { - return err - } - page.lhvncr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListHubVirtualNetworkConnectionsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListHubVirtualNetworkConnectionsResultPage) NotDone() bool { - return !page.lhvncr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListHubVirtualNetworkConnectionsResultPage) Response() ListHubVirtualNetworkConnectionsResult { - return page.lhvncr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListHubVirtualNetworkConnectionsResultPage) Values() []HubVirtualNetworkConnection { - if page.lhvncr.IsEmpty() { - return nil - } - return *page.lhvncr.Value -} - -// Creates a new instance of the ListHubVirtualNetworkConnectionsResultPage type. -func NewListHubVirtualNetworkConnectionsResultPage(cur ListHubVirtualNetworkConnectionsResult, getNextPage func(context.Context, ListHubVirtualNetworkConnectionsResult) (ListHubVirtualNetworkConnectionsResult, error)) ListHubVirtualNetworkConnectionsResultPage { - return ListHubVirtualNetworkConnectionsResultPage{ - fn: getNextPage, - lhvncr: cur, - } -} - -// ListP2SVpnGatewaysResult result of the request to list P2SVpnGateways. It contains a list of -// P2SVpnGateways and a URL nextLink to get the next set of results. -type ListP2SVpnGatewaysResult struct { - autorest.Response `json:"-"` - // Value - List of P2SVpnGateways. - Value *[]P2SVpnGateway `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListP2SVpnGatewaysResultIterator provides access to a complete listing of P2SVpnGateway values. -type ListP2SVpnGatewaysResultIterator struct { - i int - page ListP2SVpnGatewaysResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListP2SVpnGatewaysResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListP2SVpnGatewaysResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListP2SVpnGatewaysResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListP2SVpnGatewaysResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListP2SVpnGatewaysResultIterator) Response() ListP2SVpnGatewaysResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListP2SVpnGatewaysResultIterator) Value() P2SVpnGateway { - if !iter.page.NotDone() { - return P2SVpnGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListP2SVpnGatewaysResultIterator type. -func NewListP2SVpnGatewaysResultIterator(page ListP2SVpnGatewaysResultPage) ListP2SVpnGatewaysResultIterator { - return ListP2SVpnGatewaysResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lpvgr ListP2SVpnGatewaysResult) IsEmpty() bool { - return lpvgr.Value == nil || len(*lpvgr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lpvgr ListP2SVpnGatewaysResult) hasNextLink() bool { - return lpvgr.NextLink != nil && len(*lpvgr.NextLink) != 0 -} - -// listP2SVpnGatewaysResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lpvgr ListP2SVpnGatewaysResult) listP2SVpnGatewaysResultPreparer(ctx context.Context) (*http.Request, error) { - if !lpvgr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lpvgr.NextLink))) -} - -// ListP2SVpnGatewaysResultPage contains a page of P2SVpnGateway values. -type ListP2SVpnGatewaysResultPage struct { - fn func(context.Context, ListP2SVpnGatewaysResult) (ListP2SVpnGatewaysResult, error) - lpvgr ListP2SVpnGatewaysResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListP2SVpnGatewaysResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListP2SVpnGatewaysResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lpvgr) - if err != nil { - return err - } - page.lpvgr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListP2SVpnGatewaysResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListP2SVpnGatewaysResultPage) NotDone() bool { - return !page.lpvgr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListP2SVpnGatewaysResultPage) Response() ListP2SVpnGatewaysResult { - return page.lpvgr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListP2SVpnGatewaysResultPage) Values() []P2SVpnGateway { - if page.lpvgr.IsEmpty() { - return nil - } - return *page.lpvgr.Value -} - -// Creates a new instance of the ListP2SVpnGatewaysResultPage type. -func NewListP2SVpnGatewaysResultPage(cur ListP2SVpnGatewaysResult, getNextPage func(context.Context, ListP2SVpnGatewaysResult) (ListP2SVpnGatewaysResult, error)) ListP2SVpnGatewaysResultPage { - return ListP2SVpnGatewaysResultPage{ - fn: getNextPage, - lpvgr: cur, - } -} - -// ListP2SVpnServerConfigurationsResult result of the request to list all P2SVpnServerConfigurations -// associated to a VirtualWan. It contains a list of P2SVpnServerConfigurations and a URL nextLink to get -// the next set of results. -type ListP2SVpnServerConfigurationsResult struct { - autorest.Response `json:"-"` - // Value - List of P2SVpnServerConfigurations. - Value *[]P2SVpnServerConfiguration `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListP2SVpnServerConfigurationsResultIterator provides access to a complete listing of -// P2SVpnServerConfiguration values. -type ListP2SVpnServerConfigurationsResultIterator struct { - i int - page ListP2SVpnServerConfigurationsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListP2SVpnServerConfigurationsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListP2SVpnServerConfigurationsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListP2SVpnServerConfigurationsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListP2SVpnServerConfigurationsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListP2SVpnServerConfigurationsResultIterator) Response() ListP2SVpnServerConfigurationsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListP2SVpnServerConfigurationsResultIterator) Value() P2SVpnServerConfiguration { - if !iter.page.NotDone() { - return P2SVpnServerConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListP2SVpnServerConfigurationsResultIterator type. -func NewListP2SVpnServerConfigurationsResultIterator(page ListP2SVpnServerConfigurationsResultPage) ListP2SVpnServerConfigurationsResultIterator { - return ListP2SVpnServerConfigurationsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lpvscr ListP2SVpnServerConfigurationsResult) IsEmpty() bool { - return lpvscr.Value == nil || len(*lpvscr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lpvscr ListP2SVpnServerConfigurationsResult) hasNextLink() bool { - return lpvscr.NextLink != nil && len(*lpvscr.NextLink) != 0 -} - -// listP2SVpnServerConfigurationsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lpvscr ListP2SVpnServerConfigurationsResult) listP2SVpnServerConfigurationsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lpvscr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lpvscr.NextLink))) -} - -// ListP2SVpnServerConfigurationsResultPage contains a page of P2SVpnServerConfiguration values. -type ListP2SVpnServerConfigurationsResultPage struct { - fn func(context.Context, ListP2SVpnServerConfigurationsResult) (ListP2SVpnServerConfigurationsResult, error) - lpvscr ListP2SVpnServerConfigurationsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListP2SVpnServerConfigurationsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListP2SVpnServerConfigurationsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lpvscr) - if err != nil { - return err - } - page.lpvscr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListP2SVpnServerConfigurationsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListP2SVpnServerConfigurationsResultPage) NotDone() bool { - return !page.lpvscr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListP2SVpnServerConfigurationsResultPage) Response() ListP2SVpnServerConfigurationsResult { - return page.lpvscr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListP2SVpnServerConfigurationsResultPage) Values() []P2SVpnServerConfiguration { - if page.lpvscr.IsEmpty() { - return nil - } - return *page.lpvscr.Value -} - -// Creates a new instance of the ListP2SVpnServerConfigurationsResultPage type. -func NewListP2SVpnServerConfigurationsResultPage(cur ListP2SVpnServerConfigurationsResult, getNextPage func(context.Context, ListP2SVpnServerConfigurationsResult) (ListP2SVpnServerConfigurationsResult, error)) ListP2SVpnServerConfigurationsResultPage { - return ListP2SVpnServerConfigurationsResultPage{ - fn: getNextPage, - lpvscr: cur, - } -} - -// ListVirtualHubsResult result of the request to list VirtualHubs. It contains a list of VirtualHubs and a -// URL nextLink to get the next set of results. -type ListVirtualHubsResult struct { - autorest.Response `json:"-"` - // Value - List of VirtualHubs. - Value *[]VirtualHub `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualHubsResultIterator provides access to a complete listing of VirtualHub values. -type ListVirtualHubsResultIterator struct { - i int - page ListVirtualHubsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualHubsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualHubsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualHubsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualHubsResultIterator) Response() ListVirtualHubsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualHubsResultIterator) Value() VirtualHub { - if !iter.page.NotDone() { - return VirtualHub{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualHubsResultIterator type. -func NewListVirtualHubsResultIterator(page ListVirtualHubsResultPage) ListVirtualHubsResultIterator { - return ListVirtualHubsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvhr ListVirtualHubsResult) IsEmpty() bool { - return lvhr.Value == nil || len(*lvhr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvhr ListVirtualHubsResult) hasNextLink() bool { - return lvhr.NextLink != nil && len(*lvhr.NextLink) != 0 -} - -// listVirtualHubsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvhr ListVirtualHubsResult) listVirtualHubsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvhr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvhr.NextLink))) -} - -// ListVirtualHubsResultPage contains a page of VirtualHub values. -type ListVirtualHubsResultPage struct { - fn func(context.Context, ListVirtualHubsResult) (ListVirtualHubsResult, error) - lvhr ListVirtualHubsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualHubsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvhr) - if err != nil { - return err - } - page.lvhr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualHubsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualHubsResultPage) NotDone() bool { - return !page.lvhr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualHubsResultPage) Response() ListVirtualHubsResult { - return page.lvhr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualHubsResultPage) Values() []VirtualHub { - if page.lvhr.IsEmpty() { - return nil - } - return *page.lvhr.Value -} - -// Creates a new instance of the ListVirtualHubsResultPage type. -func NewListVirtualHubsResultPage(cur ListVirtualHubsResult, getNextPage func(context.Context, ListVirtualHubsResult) (ListVirtualHubsResult, error)) ListVirtualHubsResultPage { - return ListVirtualHubsResultPage{ - fn: getNextPage, - lvhr: cur, - } -} - -// ListVirtualWANsResult result of the request to list VirtualWANs. It contains a list of VirtualWANs and a -// URL nextLink to get the next set of results. -type ListVirtualWANsResult struct { - autorest.Response `json:"-"` - // Value - List of VirtualWANs. - Value *[]VirtualWAN `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualWANsResultIterator provides access to a complete listing of VirtualWAN values. -type ListVirtualWANsResultIterator struct { - i int - page ListVirtualWANsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualWANsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualWANsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualWANsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualWANsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualWANsResultIterator) Response() ListVirtualWANsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualWANsResultIterator) Value() VirtualWAN { - if !iter.page.NotDone() { - return VirtualWAN{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualWANsResultIterator type. -func NewListVirtualWANsResultIterator(page ListVirtualWANsResultPage) ListVirtualWANsResultIterator { - return ListVirtualWANsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvwnr ListVirtualWANsResult) IsEmpty() bool { - return lvwnr.Value == nil || len(*lvwnr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvwnr ListVirtualWANsResult) hasNextLink() bool { - return lvwnr.NextLink != nil && len(*lvwnr.NextLink) != 0 -} - -// listVirtualWANsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvwnr ListVirtualWANsResult) listVirtualWANsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvwnr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvwnr.NextLink))) -} - -// ListVirtualWANsResultPage contains a page of VirtualWAN values. -type ListVirtualWANsResultPage struct { - fn func(context.Context, ListVirtualWANsResult) (ListVirtualWANsResult, error) - lvwnr ListVirtualWANsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualWANsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualWANsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvwnr) - if err != nil { - return err - } - page.lvwnr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualWANsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualWANsResultPage) NotDone() bool { - return !page.lvwnr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualWANsResultPage) Response() ListVirtualWANsResult { - return page.lvwnr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualWANsResultPage) Values() []VirtualWAN { - if page.lvwnr.IsEmpty() { - return nil - } - return *page.lvwnr.Value -} - -// Creates a new instance of the ListVirtualWANsResultPage type. -func NewListVirtualWANsResultPage(cur ListVirtualWANsResult, getNextPage func(context.Context, ListVirtualWANsResult) (ListVirtualWANsResult, error)) ListVirtualWANsResultPage { - return ListVirtualWANsResultPage{ - fn: getNextPage, - lvwnr: cur, - } -} - -// ListVpnConnectionsResult result of the request to list all vpn connections to a virtual wan vpn gateway. -// It contains a list of Vpn Connections and a URL nextLink to get the next set of results. -type ListVpnConnectionsResult struct { - autorest.Response `json:"-"` - // Value - List of Vpn Connections. - Value *[]VpnConnection `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnConnectionsResultIterator provides access to a complete listing of VpnConnection values. -type ListVpnConnectionsResultIterator struct { - i int - page ListVpnConnectionsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnConnectionsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnConnectionsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnConnectionsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnConnectionsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnConnectionsResultIterator) Response() ListVpnConnectionsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnConnectionsResultIterator) Value() VpnConnection { - if !iter.page.NotDone() { - return VpnConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnConnectionsResultIterator type. -func NewListVpnConnectionsResultIterator(page ListVpnConnectionsResultPage) ListVpnConnectionsResultIterator { - return ListVpnConnectionsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvcr ListVpnConnectionsResult) IsEmpty() bool { - return lvcr.Value == nil || len(*lvcr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvcr ListVpnConnectionsResult) hasNextLink() bool { - return lvcr.NextLink != nil && len(*lvcr.NextLink) != 0 -} - -// listVpnConnectionsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvcr ListVpnConnectionsResult) listVpnConnectionsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvcr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvcr.NextLink))) -} - -// ListVpnConnectionsResultPage contains a page of VpnConnection values. -type ListVpnConnectionsResultPage struct { - fn func(context.Context, ListVpnConnectionsResult) (ListVpnConnectionsResult, error) - lvcr ListVpnConnectionsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnConnectionsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnConnectionsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvcr) - if err != nil { - return err - } - page.lvcr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnConnectionsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnConnectionsResultPage) NotDone() bool { - return !page.lvcr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnConnectionsResultPage) Response() ListVpnConnectionsResult { - return page.lvcr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnConnectionsResultPage) Values() []VpnConnection { - if page.lvcr.IsEmpty() { - return nil - } - return *page.lvcr.Value -} - -// Creates a new instance of the ListVpnConnectionsResultPage type. -func NewListVpnConnectionsResultPage(cur ListVpnConnectionsResult, getNextPage func(context.Context, ListVpnConnectionsResult) (ListVpnConnectionsResult, error)) ListVpnConnectionsResultPage { - return ListVpnConnectionsResultPage{ - fn: getNextPage, - lvcr: cur, - } -} - -// ListVpnGatewaysResult result of the request to list VpnGateways. It contains a list of VpnGateways and a -// URL nextLink to get the next set of results. -type ListVpnGatewaysResult struct { - autorest.Response `json:"-"` - // Value - List of VpnGateways. - Value *[]VpnGateway `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnGatewaysResultIterator provides access to a complete listing of VpnGateway values. -type ListVpnGatewaysResultIterator struct { - i int - page ListVpnGatewaysResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnGatewaysResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnGatewaysResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnGatewaysResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnGatewaysResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnGatewaysResultIterator) Response() ListVpnGatewaysResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnGatewaysResultIterator) Value() VpnGateway { - if !iter.page.NotDone() { - return VpnGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnGatewaysResultIterator type. -func NewListVpnGatewaysResultIterator(page ListVpnGatewaysResultPage) ListVpnGatewaysResultIterator { - return ListVpnGatewaysResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvgr ListVpnGatewaysResult) IsEmpty() bool { - return lvgr.Value == nil || len(*lvgr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvgr ListVpnGatewaysResult) hasNextLink() bool { - return lvgr.NextLink != nil && len(*lvgr.NextLink) != 0 -} - -// listVpnGatewaysResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvgr ListVpnGatewaysResult) listVpnGatewaysResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvgr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvgr.NextLink))) -} - -// ListVpnGatewaysResultPage contains a page of VpnGateway values. -type ListVpnGatewaysResultPage struct { - fn func(context.Context, ListVpnGatewaysResult) (ListVpnGatewaysResult, error) - lvgr ListVpnGatewaysResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnGatewaysResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnGatewaysResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvgr) - if err != nil { - return err - } - page.lvgr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnGatewaysResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnGatewaysResultPage) NotDone() bool { - return !page.lvgr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnGatewaysResultPage) Response() ListVpnGatewaysResult { - return page.lvgr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnGatewaysResultPage) Values() []VpnGateway { - if page.lvgr.IsEmpty() { - return nil - } - return *page.lvgr.Value -} - -// Creates a new instance of the ListVpnGatewaysResultPage type. -func NewListVpnGatewaysResultPage(cur ListVpnGatewaysResult, getNextPage func(context.Context, ListVpnGatewaysResult) (ListVpnGatewaysResult, error)) ListVpnGatewaysResultPage { - return ListVpnGatewaysResultPage{ - fn: getNextPage, - lvgr: cur, - } -} - -// ListVpnSitesResult result of the request to list VpnSites. It contains a list of VpnSites and a URL -// nextLink to get the next set of results. -type ListVpnSitesResult struct { - autorest.Response `json:"-"` - // Value - List of VpnSites. - Value *[]VpnSite `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnSitesResultIterator provides access to a complete listing of VpnSite values. -type ListVpnSitesResultIterator struct { - i int - page ListVpnSitesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnSitesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSitesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnSitesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnSitesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnSitesResultIterator) Response() ListVpnSitesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnSitesResultIterator) Value() VpnSite { - if !iter.page.NotDone() { - return VpnSite{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnSitesResultIterator type. -func NewListVpnSitesResultIterator(page ListVpnSitesResultPage) ListVpnSitesResultIterator { - return ListVpnSitesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvsr ListVpnSitesResult) IsEmpty() bool { - return lvsr.Value == nil || len(*lvsr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvsr ListVpnSitesResult) hasNextLink() bool { - return lvsr.NextLink != nil && len(*lvsr.NextLink) != 0 -} - -// listVpnSitesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvsr ListVpnSitesResult) listVpnSitesResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvsr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvsr.NextLink))) -} - -// ListVpnSitesResultPage contains a page of VpnSite values. -type ListVpnSitesResultPage struct { - fn func(context.Context, ListVpnSitesResult) (ListVpnSitesResult, error) - lvsr ListVpnSitesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnSitesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSitesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvsr) - if err != nil { - return err - } - page.lvsr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnSitesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnSitesResultPage) NotDone() bool { - return !page.lvsr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnSitesResultPage) Response() ListVpnSitesResult { - return page.lvsr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnSitesResultPage) Values() []VpnSite { - if page.lvsr.IsEmpty() { - return nil - } - return *page.lvsr.Value -} - -// Creates a new instance of the ListVpnSitesResultPage type. -func NewListVpnSitesResultPage(cur ListVpnSitesResult, getNextPage func(context.Context, ListVpnSitesResult) (ListVpnSitesResult, error)) ListVpnSitesResultPage { - return ListVpnSitesResultPage{ - fn: getNextPage, - lvsr: cur, - } -} - -// LoadBalancer loadBalancer resource -type LoadBalancer struct { - autorest.Response `json:"-"` - // Sku - The load balancer SKU. - Sku *LoadBalancerSku `json:"sku,omitempty"` - // LoadBalancerPropertiesFormat - Properties of load balancer. - *LoadBalancerPropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for LoadBalancer. -func (lb LoadBalancer) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lb.Sku != nil { - objectMap["sku"] = lb.Sku - } - if lb.LoadBalancerPropertiesFormat != nil { - objectMap["properties"] = lb.LoadBalancerPropertiesFormat - } - if lb.Etag != nil { - objectMap["etag"] = lb.Etag - } - if lb.ID != nil { - objectMap["id"] = lb.ID - } - if lb.Location != nil { - objectMap["location"] = lb.Location - } - if lb.Tags != nil { - objectMap["tags"] = lb.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LoadBalancer struct. -func (lb *LoadBalancer) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku LoadBalancerSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - lb.Sku = &sku - } - case "properties": - if v != nil { - var loadBalancerPropertiesFormat LoadBalancerPropertiesFormat - err = json.Unmarshal(*v, &loadBalancerPropertiesFormat) - if err != nil { - return err - } - lb.LoadBalancerPropertiesFormat = &loadBalancerPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - lb.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - lb.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - lb.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - lb.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - lb.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - lb.Tags = tags - } - } - } - - return nil -} - -// LoadBalancerBackendAddressPoolListResult response for ListBackendAddressPool API service call. -type LoadBalancerBackendAddressPoolListResult struct { - autorest.Response `json:"-"` - // Value - A list of backend address pools in a load balancer. - Value *[]BackendAddressPool `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerBackendAddressPoolListResult. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbbaplr.Value != nil { - objectMap["value"] = lbbaplr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerBackendAddressPoolListResultIterator provides access to a complete listing of -// BackendAddressPool values. -type LoadBalancerBackendAddressPoolListResultIterator struct { - i int - page LoadBalancerBackendAddressPoolListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerBackendAddressPoolListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerBackendAddressPoolListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerBackendAddressPoolListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerBackendAddressPoolListResultIterator) Response() LoadBalancerBackendAddressPoolListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerBackendAddressPoolListResultIterator) Value() BackendAddressPool { - if !iter.page.NotDone() { - return BackendAddressPool{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerBackendAddressPoolListResultIterator type. -func NewLoadBalancerBackendAddressPoolListResultIterator(page LoadBalancerBackendAddressPoolListResultPage) LoadBalancerBackendAddressPoolListResultIterator { - return LoadBalancerBackendAddressPoolListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) IsEmpty() bool { - return lbbaplr.Value == nil || len(*lbbaplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) hasNextLink() bool { - return lbbaplr.NextLink != nil && len(*lbbaplr.NextLink) != 0 -} - -// loadBalancerBackendAddressPoolListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) loadBalancerBackendAddressPoolListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lbbaplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lbbaplr.NextLink))) -} - -// LoadBalancerBackendAddressPoolListResultPage contains a page of BackendAddressPool values. -type LoadBalancerBackendAddressPoolListResultPage struct { - fn func(context.Context, LoadBalancerBackendAddressPoolListResult) (LoadBalancerBackendAddressPoolListResult, error) - lbbaplr LoadBalancerBackendAddressPoolListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerBackendAddressPoolListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lbbaplr) - if err != nil { - return err - } - page.lbbaplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerBackendAddressPoolListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerBackendAddressPoolListResultPage) NotDone() bool { - return !page.lbbaplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerBackendAddressPoolListResultPage) Response() LoadBalancerBackendAddressPoolListResult { - return page.lbbaplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerBackendAddressPoolListResultPage) Values() []BackendAddressPool { - if page.lbbaplr.IsEmpty() { - return nil - } - return *page.lbbaplr.Value -} - -// Creates a new instance of the LoadBalancerBackendAddressPoolListResultPage type. -func NewLoadBalancerBackendAddressPoolListResultPage(cur LoadBalancerBackendAddressPoolListResult, getNextPage func(context.Context, LoadBalancerBackendAddressPoolListResult) (LoadBalancerBackendAddressPoolListResult, error)) LoadBalancerBackendAddressPoolListResultPage { - return LoadBalancerBackendAddressPoolListResultPage{ - fn: getNextPage, - lbbaplr: cur, - } -} - -// LoadBalancerFrontendIPConfigurationListResult response for ListFrontendIPConfiguration API service call. -type LoadBalancerFrontendIPConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - A list of frontend IP configurations in a load balancer. - Value *[]FrontendIPConfiguration `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerFrontendIPConfigurationListResult. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbficlr.Value != nil { - objectMap["value"] = lbficlr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerFrontendIPConfigurationListResultIterator provides access to a complete listing of -// FrontendIPConfiguration values. -type LoadBalancerFrontendIPConfigurationListResultIterator struct { - i int - page LoadBalancerFrontendIPConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerFrontendIPConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerFrontendIPConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerFrontendIPConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerFrontendIPConfigurationListResultIterator) Response() LoadBalancerFrontendIPConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerFrontendIPConfigurationListResultIterator) Value() FrontendIPConfiguration { - if !iter.page.NotDone() { - return FrontendIPConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerFrontendIPConfigurationListResultIterator type. -func NewLoadBalancerFrontendIPConfigurationListResultIterator(page LoadBalancerFrontendIPConfigurationListResultPage) LoadBalancerFrontendIPConfigurationListResultIterator { - return LoadBalancerFrontendIPConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) IsEmpty() bool { - return lbficlr.Value == nil || len(*lbficlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) hasNextLink() bool { - return lbficlr.NextLink != nil && len(*lbficlr.NextLink) != 0 -} - -// loadBalancerFrontendIPConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) loadBalancerFrontendIPConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lbficlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lbficlr.NextLink))) -} - -// LoadBalancerFrontendIPConfigurationListResultPage contains a page of FrontendIPConfiguration values. -type LoadBalancerFrontendIPConfigurationListResultPage struct { - fn func(context.Context, LoadBalancerFrontendIPConfigurationListResult) (LoadBalancerFrontendIPConfigurationListResult, error) - lbficlr LoadBalancerFrontendIPConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerFrontendIPConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lbficlr) - if err != nil { - return err - } - page.lbficlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerFrontendIPConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerFrontendIPConfigurationListResultPage) NotDone() bool { - return !page.lbficlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerFrontendIPConfigurationListResultPage) Response() LoadBalancerFrontendIPConfigurationListResult { - return page.lbficlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerFrontendIPConfigurationListResultPage) Values() []FrontendIPConfiguration { - if page.lbficlr.IsEmpty() { - return nil - } - return *page.lbficlr.Value -} - -// Creates a new instance of the LoadBalancerFrontendIPConfigurationListResultPage type. -func NewLoadBalancerFrontendIPConfigurationListResultPage(cur LoadBalancerFrontendIPConfigurationListResult, getNextPage func(context.Context, LoadBalancerFrontendIPConfigurationListResult) (LoadBalancerFrontendIPConfigurationListResult, error)) LoadBalancerFrontendIPConfigurationListResultPage { - return LoadBalancerFrontendIPConfigurationListResultPage{ - fn: getNextPage, - lbficlr: cur, - } -} - -// LoadBalancerListResult response for ListLoadBalancers API service call. -type LoadBalancerListResult struct { - autorest.Response `json:"-"` - // Value - A list of load balancers in a resource group. - Value *[]LoadBalancer `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerListResult. -func (lblr LoadBalancerListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lblr.Value != nil { - objectMap["value"] = lblr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerListResultIterator provides access to a complete listing of LoadBalancer values. -type LoadBalancerListResultIterator struct { - i int - page LoadBalancerListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerListResultIterator) Response() LoadBalancerListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerListResultIterator) Value() LoadBalancer { - if !iter.page.NotDone() { - return LoadBalancer{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerListResultIterator type. -func NewLoadBalancerListResultIterator(page LoadBalancerListResultPage) LoadBalancerListResultIterator { - return LoadBalancerListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lblr LoadBalancerListResult) IsEmpty() bool { - return lblr.Value == nil || len(*lblr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lblr LoadBalancerListResult) hasNextLink() bool { - return lblr.NextLink != nil && len(*lblr.NextLink) != 0 -} - -// loadBalancerListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lblr LoadBalancerListResult) loadBalancerListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lblr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lblr.NextLink))) -} - -// LoadBalancerListResultPage contains a page of LoadBalancer values. -type LoadBalancerListResultPage struct { - fn func(context.Context, LoadBalancerListResult) (LoadBalancerListResult, error) - lblr LoadBalancerListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lblr) - if err != nil { - return err - } - page.lblr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerListResultPage) NotDone() bool { - return !page.lblr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerListResultPage) Response() LoadBalancerListResult { - return page.lblr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerListResultPage) Values() []LoadBalancer { - if page.lblr.IsEmpty() { - return nil - } - return *page.lblr.Value -} - -// Creates a new instance of the LoadBalancerListResultPage type. -func NewLoadBalancerListResultPage(cur LoadBalancerListResult, getNextPage func(context.Context, LoadBalancerListResult) (LoadBalancerListResult, error)) LoadBalancerListResultPage { - return LoadBalancerListResultPage{ - fn: getNextPage, - lblr: cur, - } -} - -// LoadBalancerLoadBalancingRuleListResult response for ListLoadBalancingRule API service call. -type LoadBalancerLoadBalancingRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of load balancing rules in a load balancer. - Value *[]LoadBalancingRule `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerLoadBalancingRuleListResult. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lblbrlr.Value != nil { - objectMap["value"] = lblbrlr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerLoadBalancingRuleListResultIterator provides access to a complete listing of -// LoadBalancingRule values. -type LoadBalancerLoadBalancingRuleListResultIterator struct { - i int - page LoadBalancerLoadBalancingRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerLoadBalancingRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerLoadBalancingRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerLoadBalancingRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerLoadBalancingRuleListResultIterator) Response() LoadBalancerLoadBalancingRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerLoadBalancingRuleListResultIterator) Value() LoadBalancingRule { - if !iter.page.NotDone() { - return LoadBalancingRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerLoadBalancingRuleListResultIterator type. -func NewLoadBalancerLoadBalancingRuleListResultIterator(page LoadBalancerLoadBalancingRuleListResultPage) LoadBalancerLoadBalancingRuleListResultIterator { - return LoadBalancerLoadBalancingRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) IsEmpty() bool { - return lblbrlr.Value == nil || len(*lblbrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) hasNextLink() bool { - return lblbrlr.NextLink != nil && len(*lblbrlr.NextLink) != 0 -} - -// loadBalancerLoadBalancingRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) loadBalancerLoadBalancingRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lblbrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lblbrlr.NextLink))) -} - -// LoadBalancerLoadBalancingRuleListResultPage contains a page of LoadBalancingRule values. -type LoadBalancerLoadBalancingRuleListResultPage struct { - fn func(context.Context, LoadBalancerLoadBalancingRuleListResult) (LoadBalancerLoadBalancingRuleListResult, error) - lblbrlr LoadBalancerLoadBalancingRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerLoadBalancingRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lblbrlr) - if err != nil { - return err - } - page.lblbrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerLoadBalancingRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerLoadBalancingRuleListResultPage) NotDone() bool { - return !page.lblbrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerLoadBalancingRuleListResultPage) Response() LoadBalancerLoadBalancingRuleListResult { - return page.lblbrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerLoadBalancingRuleListResultPage) Values() []LoadBalancingRule { - if page.lblbrlr.IsEmpty() { - return nil - } - return *page.lblbrlr.Value -} - -// Creates a new instance of the LoadBalancerLoadBalancingRuleListResultPage type. -func NewLoadBalancerLoadBalancingRuleListResultPage(cur LoadBalancerLoadBalancingRuleListResult, getNextPage func(context.Context, LoadBalancerLoadBalancingRuleListResult) (LoadBalancerLoadBalancingRuleListResult, error)) LoadBalancerLoadBalancingRuleListResultPage { - return LoadBalancerLoadBalancingRuleListResultPage{ - fn: getNextPage, - lblbrlr: cur, - } -} - -// LoadBalancerOutboundRuleListResult response for ListOutboundRule API service call. -type LoadBalancerOutboundRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of outbound rules in a load balancer. - Value *[]OutboundRule `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerOutboundRuleListResult. -func (lborlr LoadBalancerOutboundRuleListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lborlr.Value != nil { - objectMap["value"] = lborlr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerOutboundRuleListResultIterator provides access to a complete listing of OutboundRule values. -type LoadBalancerOutboundRuleListResultIterator struct { - i int - page LoadBalancerOutboundRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerOutboundRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerOutboundRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerOutboundRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerOutboundRuleListResultIterator) Response() LoadBalancerOutboundRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerOutboundRuleListResultIterator) Value() OutboundRule { - if !iter.page.NotDone() { - return OutboundRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerOutboundRuleListResultIterator type. -func NewLoadBalancerOutboundRuleListResultIterator(page LoadBalancerOutboundRuleListResultPage) LoadBalancerOutboundRuleListResultIterator { - return LoadBalancerOutboundRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lborlr LoadBalancerOutboundRuleListResult) IsEmpty() bool { - return lborlr.Value == nil || len(*lborlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lborlr LoadBalancerOutboundRuleListResult) hasNextLink() bool { - return lborlr.NextLink != nil && len(*lborlr.NextLink) != 0 -} - -// loadBalancerOutboundRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lborlr LoadBalancerOutboundRuleListResult) loadBalancerOutboundRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lborlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lborlr.NextLink))) -} - -// LoadBalancerOutboundRuleListResultPage contains a page of OutboundRule values. -type LoadBalancerOutboundRuleListResultPage struct { - fn func(context.Context, LoadBalancerOutboundRuleListResult) (LoadBalancerOutboundRuleListResult, error) - lborlr LoadBalancerOutboundRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerOutboundRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lborlr) - if err != nil { - return err - } - page.lborlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerOutboundRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerOutboundRuleListResultPage) NotDone() bool { - return !page.lborlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerOutboundRuleListResultPage) Response() LoadBalancerOutboundRuleListResult { - return page.lborlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerOutboundRuleListResultPage) Values() []OutboundRule { - if page.lborlr.IsEmpty() { - return nil - } - return *page.lborlr.Value -} - -// Creates a new instance of the LoadBalancerOutboundRuleListResultPage type. -func NewLoadBalancerOutboundRuleListResultPage(cur LoadBalancerOutboundRuleListResult, getNextPage func(context.Context, LoadBalancerOutboundRuleListResult) (LoadBalancerOutboundRuleListResult, error)) LoadBalancerOutboundRuleListResultPage { - return LoadBalancerOutboundRuleListResultPage{ - fn: getNextPage, - lborlr: cur, - } -} - -// LoadBalancerProbeListResult response for ListProbe API service call. -type LoadBalancerProbeListResult struct { - autorest.Response `json:"-"` - // Value - A list of probes in a load balancer. - Value *[]Probe `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerProbeListResult. -func (lbplr LoadBalancerProbeListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbplr.Value != nil { - objectMap["value"] = lbplr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerProbeListResultIterator provides access to a complete listing of Probe values. -type LoadBalancerProbeListResultIterator struct { - i int - page LoadBalancerProbeListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerProbeListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbeListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerProbeListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerProbeListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerProbeListResultIterator) Response() LoadBalancerProbeListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerProbeListResultIterator) Value() Probe { - if !iter.page.NotDone() { - return Probe{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerProbeListResultIterator type. -func NewLoadBalancerProbeListResultIterator(page LoadBalancerProbeListResultPage) LoadBalancerProbeListResultIterator { - return LoadBalancerProbeListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lbplr LoadBalancerProbeListResult) IsEmpty() bool { - return lbplr.Value == nil || len(*lbplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lbplr LoadBalancerProbeListResult) hasNextLink() bool { - return lbplr.NextLink != nil && len(*lbplr.NextLink) != 0 -} - -// loadBalancerProbeListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lbplr LoadBalancerProbeListResult) loadBalancerProbeListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lbplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lbplr.NextLink))) -} - -// LoadBalancerProbeListResultPage contains a page of Probe values. -type LoadBalancerProbeListResultPage struct { - fn func(context.Context, LoadBalancerProbeListResult) (LoadBalancerProbeListResult, error) - lbplr LoadBalancerProbeListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerProbeListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbeListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lbplr) - if err != nil { - return err - } - page.lbplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerProbeListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerProbeListResultPage) NotDone() bool { - return !page.lbplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerProbeListResultPage) Response() LoadBalancerProbeListResult { - return page.lbplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerProbeListResultPage) Values() []Probe { - if page.lbplr.IsEmpty() { - return nil - } - return *page.lbplr.Value -} - -// Creates a new instance of the LoadBalancerProbeListResultPage type. -func NewLoadBalancerProbeListResultPage(cur LoadBalancerProbeListResult, getNextPage func(context.Context, LoadBalancerProbeListResult) (LoadBalancerProbeListResult, error)) LoadBalancerProbeListResultPage { - return LoadBalancerProbeListResultPage{ - fn: getNextPage, - lbplr: cur, - } -} - -// LoadBalancerPropertiesFormat properties of the load balancer. -type LoadBalancerPropertiesFormat struct { - // FrontendIPConfigurations - Object representing the frontend IPs to be used for the load balancer - FrontendIPConfigurations *[]FrontendIPConfiguration `json:"frontendIPConfigurations,omitempty"` - // BackendAddressPools - Collection of backend address pools used by a load balancer - BackendAddressPools *[]BackendAddressPool `json:"backendAddressPools,omitempty"` - // LoadBalancingRules - Object collection representing the load balancing rules Gets the provisioning - LoadBalancingRules *[]LoadBalancingRule `json:"loadBalancingRules,omitempty"` - // Probes - Collection of probe objects used in the load balancer - Probes *[]Probe `json:"probes,omitempty"` - // InboundNatRules - Collection of inbound NAT Rules used by a load balancer. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. - InboundNatRules *[]InboundNatRule `json:"inboundNatRules,omitempty"` - // InboundNatPools - Defines an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound Nat rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. - InboundNatPools *[]InboundNatPool `json:"inboundNatPools,omitempty"` - // OutboundRules - The outbound rules. - OutboundRules *[]OutboundRule `json:"outboundRules,omitempty"` - // ResourceGUID - The resource GUID property of the load balancer resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// LoadBalancersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LoadBalancersCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancersClient) (LoadBalancer, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancersCreateOrUpdateFuture.Result. -func (future *LoadBalancersCreateOrUpdateFuture) result(client LoadBalancersClient) (lb LoadBalancer, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - lb.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancersCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if lb.Response.Response, err = future.GetResult(sender); err == nil && lb.Response.Response.StatusCode != http.StatusNoContent { - lb, err = client.CreateOrUpdateResponder(lb.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersCreateOrUpdateFuture", "Result", lb.Response.Response, "Failure responding to request") - } - } - return -} - -// LoadBalancersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type LoadBalancersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancersDeleteFuture.Result. -func (future *LoadBalancersDeleteFuture) result(client LoadBalancersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// LoadBalancerSku SKU of a load balancer -type LoadBalancerSku struct { - // Name - Name of a load balancer SKU. Possible values include: 'LoadBalancerSkuNameBasic', 'LoadBalancerSkuNameStandard' - Name LoadBalancerSkuName `json:"name,omitempty"` -} - -// LoadBalancersUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type LoadBalancersUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancersClient) (LoadBalancer, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancersUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancersUpdateTagsFuture.Result. -func (future *LoadBalancersUpdateTagsFuture) result(client LoadBalancersClient) (lb LoadBalancer, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - lb.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancersUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if lb.Response.Response, err = future.GetResult(sender); err == nil && lb.Response.Response.StatusCode != http.StatusNoContent { - lb, err = client.UpdateTagsResponder(lb.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersUpdateTagsFuture", "Result", lb.Response.Response, "Failure responding to request") - } - } - return -} - -// LoadBalancingRule a load balancing rule for a load balancer. -type LoadBalancingRule struct { - autorest.Response `json:"-"` - // LoadBalancingRulePropertiesFormat - Properties of load balancer load balancing rule. - *LoadBalancingRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancingRule. -func (lbr LoadBalancingRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbr.LoadBalancingRulePropertiesFormat != nil { - objectMap["properties"] = lbr.LoadBalancingRulePropertiesFormat - } - if lbr.Name != nil { - objectMap["name"] = lbr.Name - } - if lbr.Etag != nil { - objectMap["etag"] = lbr.Etag - } - if lbr.ID != nil { - objectMap["id"] = lbr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LoadBalancingRule struct. -func (lbr *LoadBalancingRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var loadBalancingRulePropertiesFormat LoadBalancingRulePropertiesFormat - err = json.Unmarshal(*v, &loadBalancingRulePropertiesFormat) - if err != nil { - return err - } - lbr.LoadBalancingRulePropertiesFormat = &loadBalancingRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - lbr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - lbr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - lbr.ID = &ID - } - } - } - - return nil -} - -// LoadBalancingRulePropertiesFormat properties of the load balancer. -type LoadBalancingRulePropertiesFormat struct { - // FrontendIPConfiguration - A reference to frontend IP addresses. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // BackendAddressPool - A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // Probe - The reference of the load balancer probe used by the load balancing rule. - Probe *SubResource `json:"probe,omitempty"` - // Protocol - Possible values include: 'TransportProtocolUDP', 'TransportProtocolTCP', 'TransportProtocolAll' - Protocol TransportProtocol `json:"protocol,omitempty"` - // LoadDistribution - The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. Possible values include: 'Default', 'SourceIP', 'SourceIPProtocol' - LoadDistribution LoadDistribution `json:"loadDistribution,omitempty"` - // FrontendPort - The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables "Any Port" - FrontendPort *int32 `json:"frontendPort,omitempty"` - // BackendPort - The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables "Any Port" - BackendPort *int32 `json:"backendPort,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // EnableFloatingIP - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // DisableOutboundSnat - Configures SNAT for the VMs in the backend pool to use the publicIP address specified in the frontend of the load balancing rule. - DisableOutboundSnat *bool `json:"disableOutboundSnat,omitempty"` - // ProvisioningState - Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// LocalNetworkGateway a common class for general resource information -type LocalNetworkGateway struct { - autorest.Response `json:"-"` - // LocalNetworkGatewayPropertiesFormat - Properties of the local network gateway. - *LocalNetworkGatewayPropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for LocalNetworkGateway. -func (lng LocalNetworkGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lng.LocalNetworkGatewayPropertiesFormat != nil { - objectMap["properties"] = lng.LocalNetworkGatewayPropertiesFormat - } - if lng.Etag != nil { - objectMap["etag"] = lng.Etag - } - if lng.ID != nil { - objectMap["id"] = lng.ID - } - if lng.Location != nil { - objectMap["location"] = lng.Location - } - if lng.Tags != nil { - objectMap["tags"] = lng.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LocalNetworkGateway struct. -func (lng *LocalNetworkGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var localNetworkGatewayPropertiesFormat LocalNetworkGatewayPropertiesFormat - err = json.Unmarshal(*v, &localNetworkGatewayPropertiesFormat) - if err != nil { - return err - } - lng.LocalNetworkGatewayPropertiesFormat = &localNetworkGatewayPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - lng.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - lng.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - lng.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - lng.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - lng.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - lng.Tags = tags - } - } - } - - return nil -} - -// LocalNetworkGatewayListResult response for ListLocalNetworkGateways API service call. -type LocalNetworkGatewayListResult struct { - autorest.Response `json:"-"` - // Value - A list of local network gateways that exists in a resource group. - Value *[]LocalNetworkGateway `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LocalNetworkGatewayListResult. -func (lnglr LocalNetworkGatewayListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lnglr.Value != nil { - objectMap["value"] = lnglr.Value - } - return json.Marshal(objectMap) -} - -// LocalNetworkGatewayListResultIterator provides access to a complete listing of LocalNetworkGateway -// values. -type LocalNetworkGatewayListResultIterator struct { - i int - page LocalNetworkGatewayListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LocalNetworkGatewayListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewayListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LocalNetworkGatewayListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LocalNetworkGatewayListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LocalNetworkGatewayListResultIterator) Response() LocalNetworkGatewayListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LocalNetworkGatewayListResultIterator) Value() LocalNetworkGateway { - if !iter.page.NotDone() { - return LocalNetworkGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LocalNetworkGatewayListResultIterator type. -func NewLocalNetworkGatewayListResultIterator(page LocalNetworkGatewayListResultPage) LocalNetworkGatewayListResultIterator { - return LocalNetworkGatewayListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lnglr LocalNetworkGatewayListResult) IsEmpty() bool { - return lnglr.Value == nil || len(*lnglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lnglr LocalNetworkGatewayListResult) hasNextLink() bool { - return lnglr.NextLink != nil && len(*lnglr.NextLink) != 0 -} - -// localNetworkGatewayListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lnglr LocalNetworkGatewayListResult) localNetworkGatewayListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lnglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lnglr.NextLink))) -} - -// LocalNetworkGatewayListResultPage contains a page of LocalNetworkGateway values. -type LocalNetworkGatewayListResultPage struct { - fn func(context.Context, LocalNetworkGatewayListResult) (LocalNetworkGatewayListResult, error) - lnglr LocalNetworkGatewayListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LocalNetworkGatewayListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewayListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lnglr) - if err != nil { - return err - } - page.lnglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LocalNetworkGatewayListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LocalNetworkGatewayListResultPage) NotDone() bool { - return !page.lnglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LocalNetworkGatewayListResultPage) Response() LocalNetworkGatewayListResult { - return page.lnglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LocalNetworkGatewayListResultPage) Values() []LocalNetworkGateway { - if page.lnglr.IsEmpty() { - return nil - } - return *page.lnglr.Value -} - -// Creates a new instance of the LocalNetworkGatewayListResultPage type. -func NewLocalNetworkGatewayListResultPage(cur LocalNetworkGatewayListResult, getNextPage func(context.Context, LocalNetworkGatewayListResult) (LocalNetworkGatewayListResult, error)) LocalNetworkGatewayListResultPage { - return LocalNetworkGatewayListResultPage{ - fn: getNextPage, - lnglr: cur, - } -} - -// LocalNetworkGatewayPropertiesFormat localNetworkGateway properties -type LocalNetworkGatewayPropertiesFormat struct { - // LocalNetworkAddressSpace - Local network site address space. - LocalNetworkAddressSpace *AddressSpace `json:"localNetworkAddressSpace,omitempty"` - // GatewayIPAddress - IP address of local network gateway. - GatewayIPAddress *string `json:"gatewayIpAddress,omitempty"` - // BgpSettings - Local network gateway's BGP speaker settings. - BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` - // ResourceGUID - The resource GUID property of the LocalNetworkGateway resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the LocalNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for LocalNetworkGatewayPropertiesFormat. -func (lngpf LocalNetworkGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lngpf.LocalNetworkAddressSpace != nil { - objectMap["localNetworkAddressSpace"] = lngpf.LocalNetworkAddressSpace - } - if lngpf.GatewayIPAddress != nil { - objectMap["gatewayIpAddress"] = lngpf.GatewayIPAddress - } - if lngpf.BgpSettings != nil { - objectMap["bgpSettings"] = lngpf.BgpSettings - } - if lngpf.ResourceGUID != nil { - objectMap["resourceGuid"] = lngpf.ResourceGUID - } - return json.Marshal(objectMap) -} - -// LocalNetworkGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LocalNetworkGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LocalNetworkGatewaysClient) (LocalNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LocalNetworkGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LocalNetworkGatewaysCreateOrUpdateFuture.Result. -func (future *LocalNetworkGatewaysCreateOrUpdateFuture) result(client LocalNetworkGatewaysClient) (lng LocalNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - lng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LocalNetworkGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if lng.Response.Response, err = future.GetResult(sender); err == nil && lng.Response.Response.StatusCode != http.StatusNoContent { - lng, err = client.CreateOrUpdateResponder(lng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysCreateOrUpdateFuture", "Result", lng.Response.Response, "Failure responding to request") - } - } - return -} - -// LocalNetworkGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LocalNetworkGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LocalNetworkGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LocalNetworkGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LocalNetworkGatewaysDeleteFuture.Result. -func (future *LocalNetworkGatewaysDeleteFuture) result(client LocalNetworkGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LocalNetworkGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// LocalNetworkGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LocalNetworkGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LocalNetworkGatewaysClient) (LocalNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LocalNetworkGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LocalNetworkGatewaysUpdateTagsFuture.Result. -func (future *LocalNetworkGatewaysUpdateTagsFuture) result(client LocalNetworkGatewaysClient) (lng LocalNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - lng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LocalNetworkGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if lng.Response.Response, err = future.GetResult(sender); err == nil && lng.Response.Response.StatusCode != http.StatusNoContent { - lng, err = client.UpdateTagsResponder(lng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysUpdateTagsFuture", "Result", lng.Response.Response, "Failure responding to request") - } - } - return -} - -// LogSpecification description of logging specification. -type LogSpecification struct { - // Name - The name of the specification. - Name *string `json:"name,omitempty"` - // DisplayName - The display name of the specification. - DisplayName *string `json:"displayName,omitempty"` - // BlobDuration - Duration of the blob. - BlobDuration *string `json:"blobDuration,omitempty"` -} - -// ManagedServiceIdentity identity for the resource. -type ManagedServiceIdentity struct { - // PrincipalID - READ-ONLY; The principal id of the system assigned identity. This property will only be provided for a system assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; The tenant id of the system assigned identity. This property will only be provided for a system assigned identity. - TenantID *string `json:"tenantId,omitempty"` - // Type - The type of identity used for the resource. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. Possible values include: 'ResourceIdentityTypeSystemAssigned', 'ResourceIdentityTypeUserAssigned', 'ResourceIdentityTypeSystemAssignedUserAssigned', 'ResourceIdentityTypeNone' - Type ResourceIdentityType `json:"type,omitempty"` - // UserAssignedIdentities - The list of user identities associated with resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - UserAssignedIdentities map[string]*ManagedServiceIdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for ManagedServiceIdentity. -func (msi ManagedServiceIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if msi.Type != "" { - objectMap["type"] = msi.Type - } - if msi.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = msi.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// ManagedServiceIdentityUserAssignedIdentitiesValue ... -type ManagedServiceIdentityUserAssignedIdentitiesValue struct { - // PrincipalID - READ-ONLY; The principal id of user assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; The client id of user assigned identity. - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagedServiceIdentityUserAssignedIdentitiesValue. -func (msiAiv ManagedServiceIdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// MatchedRule matched rule. -type MatchedRule struct { - // RuleName - Name of the matched network security rule. - RuleName *string `json:"ruleName,omitempty"` - // Action - The network traffic is allowed or denied. Possible values are 'Allow' and 'Deny'. - Action *string `json:"action,omitempty"` -} - -// MetricSpecification description of metrics specification. -type MetricSpecification struct { - // Name - The name of the metric. - Name *string `json:"name,omitempty"` - // DisplayName - The display name of the metric. - DisplayName *string `json:"displayName,omitempty"` - // DisplayDescription - The description of the metric. - DisplayDescription *string `json:"displayDescription,omitempty"` - // Unit - Units the metric to be displayed in. - Unit *string `json:"unit,omitempty"` - // AggregationType - The aggregation type. - AggregationType *string `json:"aggregationType,omitempty"` - // Availabilities - List of availability. - Availabilities *[]Availability `json:"availabilities,omitempty"` - // EnableRegionalMdmAccount - Whether regional MDM account enabled. - EnableRegionalMdmAccount *bool `json:"enableRegionalMdmAccount,omitempty"` - // FillGapWithZero - Whether gaps would be filled with zeros. - FillGapWithZero *bool `json:"fillGapWithZero,omitempty"` - // MetricFilterPattern - Pattern for the filter of the metric. - MetricFilterPattern *string `json:"metricFilterPattern,omitempty"` - // Dimensions - List of dimensions. - Dimensions *[]Dimension `json:"dimensions,omitempty"` - // IsInternal - Whether the metric is internal. - IsInternal *bool `json:"isInternal,omitempty"` - // SourceMdmAccount - The source MDM account. - SourceMdmAccount *string `json:"sourceMdmAccount,omitempty"` - // SourceMdmNamespace - The source MDM namespace. - SourceMdmNamespace *string `json:"sourceMdmNamespace,omitempty"` - // ResourceIDDimensionNameOverride - The resource Id dimension name override. - ResourceIDDimensionNameOverride *string `json:"resourceIdDimensionNameOverride,omitempty"` -} - -// NextHopParameters parameters that define the source and destination endpoint. -type NextHopParameters struct { - // TargetResourceID - The resource identifier of the target resource against which the action is to be performed. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // SourceIPAddress - The source IP address. - SourceIPAddress *string `json:"sourceIPAddress,omitempty"` - // DestinationIPAddress - The destination IP address. - DestinationIPAddress *string `json:"destinationIPAddress,omitempty"` - // TargetNicResourceID - The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of the nics, then this parameter must be specified. Otherwise optional). - TargetNicResourceID *string `json:"targetNicResourceId,omitempty"` -} - -// NextHopResult the information about next hop from the specified VM. -type NextHopResult struct { - autorest.Response `json:"-"` - // NextHopType - Next hop type. Possible values include: 'NextHopTypeInternet', 'NextHopTypeVirtualAppliance', 'NextHopTypeVirtualNetworkGateway', 'NextHopTypeVnetLocal', 'NextHopTypeHyperNetGateway', 'NextHopTypeNone' - NextHopType NextHopType `json:"nextHopType,omitempty"` - // NextHopIPAddress - Next hop IP Address - NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` - // RouteTableID - The resource identifier for the route table associated with the route being returned. If the route being returned does not correspond to any user created routes then this field will be the string 'System Route'. - RouteTableID *string `json:"routeTableId,omitempty"` -} - -// Operation network REST API operation definition. -type Operation struct { - // Name - Operation name: {provider}/{resource}/{operation} - Name *string `json:"name,omitempty"` - // Display - Display metadata associated with the operation. - Display *OperationDisplay `json:"display,omitempty"` - // Origin - Origin of the operation. - Origin *string `json:"origin,omitempty"` - // OperationPropertiesFormat - Operation properties format. - *OperationPropertiesFormat `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for Operation. -func (o Operation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if o.Name != nil { - objectMap["name"] = o.Name - } - if o.Display != nil { - objectMap["display"] = o.Display - } - if o.Origin != nil { - objectMap["origin"] = o.Origin - } - if o.OperationPropertiesFormat != nil { - objectMap["properties"] = o.OperationPropertiesFormat - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Operation struct. -func (o *Operation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - o.Name = &name - } - case "display": - if v != nil { - var display OperationDisplay - err = json.Unmarshal(*v, &display) - if err != nil { - return err - } - o.Display = &display - } - case "origin": - if v != nil { - var origin string - err = json.Unmarshal(*v, &origin) - if err != nil { - return err - } - o.Origin = &origin - } - case "properties": - if v != nil { - var operationPropertiesFormat OperationPropertiesFormat - err = json.Unmarshal(*v, &operationPropertiesFormat) - if err != nil { - return err - } - o.OperationPropertiesFormat = &operationPropertiesFormat - } - } - } - - return nil -} - -// OperationDisplay display metadata associated with the operation. -type OperationDisplay struct { - // Provider - Service provider: Microsoft Network. - Provider *string `json:"provider,omitempty"` - // Resource - Resource on which the operation is performed. - Resource *string `json:"resource,omitempty"` - // Operation - Type of the operation: get, read, delete, etc. - Operation *string `json:"operation,omitempty"` - // Description - Description of the operation. - Description *string `json:"description,omitempty"` -} - -// OperationListResult result of the request to list Network operations. It contains a list of operations -// and a URL link to get the next set of results. -type OperationListResult struct { - autorest.Response `json:"-"` - // Value - List of Network operations supported by the Network resource provider. - Value *[]Operation `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// OperationListResultIterator provides access to a complete listing of Operation values. -type OperationListResultIterator struct { - i int - page OperationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *OperationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter OperationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter OperationListResultIterator) Response() OperationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter OperationListResultIterator) Value() Operation { - if !iter.page.NotDone() { - return Operation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the OperationListResultIterator type. -func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { - return OperationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (olr OperationListResult) IsEmpty() bool { - return olr.Value == nil || len(*olr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (olr OperationListResult) hasNextLink() bool { - return olr.NextLink != nil && len(*olr.NextLink) != 0 -} - -// operationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !olr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(olr.NextLink))) -} - -// OperationListResultPage contains a page of Operation values. -type OperationListResultPage struct { - fn func(context.Context, OperationListResult) (OperationListResult, error) - olr OperationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.olr) - if err != nil { - return err - } - page.olr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *OperationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page OperationListResultPage) NotDone() bool { - return !page.olr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page OperationListResultPage) Response() OperationListResult { - return page.olr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page OperationListResultPage) Values() []Operation { - if page.olr.IsEmpty() { - return nil - } - return *page.olr.Value -} - -// Creates a new instance of the OperationListResultPage type. -func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { - return OperationListResultPage{ - fn: getNextPage, - olr: cur, - } -} - -// OperationPropertiesFormat description of operation properties format. -type OperationPropertiesFormat struct { - // ServiceSpecification - Specification of the service. - ServiceSpecification *OperationPropertiesFormatServiceSpecification `json:"serviceSpecification,omitempty"` -} - -// OperationPropertiesFormatServiceSpecification specification of the service. -type OperationPropertiesFormatServiceSpecification struct { - // MetricSpecifications - Operation service specification. - MetricSpecifications *[]MetricSpecification `json:"metricSpecifications,omitempty"` - // LogSpecifications - Operation log specification. - LogSpecifications *[]LogSpecification `json:"logSpecifications,omitempty"` -} - -// OutboundRule outbound rule of the load balancer. -type OutboundRule struct { - autorest.Response `json:"-"` - // OutboundRulePropertiesFormat - Properties of load balancer outbound rule. - *OutboundRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for OutboundRule. -func (or OutboundRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if or.OutboundRulePropertiesFormat != nil { - objectMap["properties"] = or.OutboundRulePropertiesFormat - } - if or.Name != nil { - objectMap["name"] = or.Name - } - if or.Etag != nil { - objectMap["etag"] = or.Etag - } - if or.ID != nil { - objectMap["id"] = or.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for OutboundRule struct. -func (or *OutboundRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var outboundRulePropertiesFormat OutboundRulePropertiesFormat - err = json.Unmarshal(*v, &outboundRulePropertiesFormat) - if err != nil { - return err - } - or.OutboundRulePropertiesFormat = &outboundRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - or.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - or.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - or.ID = &ID - } - } - } - - return nil -} - -// OutboundRulePropertiesFormat outbound rule of the load balancer. -type OutboundRulePropertiesFormat struct { - // AllocatedOutboundPorts - The number of outbound ports to be used for NAT. - AllocatedOutboundPorts *int32 `json:"allocatedOutboundPorts,omitempty"` - // FrontendIPConfigurations - The Frontend IP addresses of the load balancer. - FrontendIPConfigurations *[]SubResource `json:"frontendIPConfigurations,omitempty"` - // BackendAddressPool - A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the backend IPs. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // ProvisioningState - Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // Protocol - Protocol - TCP, UDP or All. Possible values include: 'Protocol1TCP', 'Protocol1UDP', 'Protocol1All' - Protocol Protocol1 `json:"protocol,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` -} - -// P2SVpnGateway p2SVpnGateway Resource. -type P2SVpnGateway struct { - autorest.Response `json:"-"` - *P2SVpnGatewayProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for P2SVpnGateway. -func (pvg P2SVpnGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvg.P2SVpnGatewayProperties != nil { - objectMap["properties"] = pvg.P2SVpnGatewayProperties - } - if pvg.ID != nil { - objectMap["id"] = pvg.ID - } - if pvg.Location != nil { - objectMap["location"] = pvg.Location - } - if pvg.Tags != nil { - objectMap["tags"] = pvg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SVpnGateway struct. -func (pvg *P2SVpnGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SVpnGatewayProperties P2SVpnGatewayProperties - err = json.Unmarshal(*v, &p2SVpnGatewayProperties) - if err != nil { - return err - } - pvg.P2SVpnGatewayProperties = &p2SVpnGatewayProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pvg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pvg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pvg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pvg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - pvg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pvg.Tags = tags - } - } - } - - return nil -} - -// P2SVpnGatewayProperties parameters for P2SVpnGateway -type P2SVpnGatewayProperties struct { - // VirtualHub - The VirtualHub to which the gateway belongs - VirtualHub *SubResource `json:"virtualHub,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // VpnGatewayScaleUnit - The scale unit for this p2s vpn gateway. - VpnGatewayScaleUnit *int32 `json:"vpnGatewayScaleUnit,omitempty"` - // P2SVpnServerConfiguration - The P2SVpnServerConfiguration to which the p2sVpnGateway is attached to. - P2SVpnServerConfiguration *SubResource `json:"p2SVpnServerConfiguration,omitempty"` - // VpnClientAddressPool - The reference of the address space resource which represents Address space for P2S VpnClient. - VpnClientAddressPool *AddressSpace `json:"vpnClientAddressPool,omitempty"` - // VpnClientConnectionHealth - READ-ONLY; All P2S VPN clients' connection health status. - VpnClientConnectionHealth *VpnClientConnectionHealth `json:"vpnClientConnectionHealth,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnGatewayProperties. -func (pvgp P2SVpnGatewayProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvgp.VirtualHub != nil { - objectMap["virtualHub"] = pvgp.VirtualHub - } - if pvgp.ProvisioningState != "" { - objectMap["provisioningState"] = pvgp.ProvisioningState - } - if pvgp.VpnGatewayScaleUnit != nil { - objectMap["vpnGatewayScaleUnit"] = pvgp.VpnGatewayScaleUnit - } - if pvgp.P2SVpnServerConfiguration != nil { - objectMap["p2SVpnServerConfiguration"] = pvgp.P2SVpnServerConfiguration - } - if pvgp.VpnClientAddressPool != nil { - objectMap["vpnClientAddressPool"] = pvgp.VpnClientAddressPool - } - return json.Marshal(objectMap) -} - -// P2sVpnGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type P2sVpnGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (P2SVpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysCreateOrUpdateFuture.Result. -func (future *P2sVpnGatewaysCreateOrUpdateFuture) result(client P2sVpnGatewaysClient) (pvg P2SVpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvg.Response.Response, err = future.GetResult(sender); err == nil && pvg.Response.Response.StatusCode != http.StatusNoContent { - pvg, err = client.CreateOrUpdateResponder(pvg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysCreateOrUpdateFuture", "Result", pvg.Response.Response, "Failure responding to request") - } - } - return -} - -// P2sVpnGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type P2sVpnGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysDeleteFuture.Result. -func (future *P2sVpnGatewaysDeleteFuture) result(client P2sVpnGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// P2sVpnGatewaysGenerateVpnProfileFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type P2sVpnGatewaysGenerateVpnProfileFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (VpnProfileResponse, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysGenerateVpnProfileFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysGenerateVpnProfileFuture.Result. -func (future *P2sVpnGatewaysGenerateVpnProfileFuture) result(client P2sVpnGatewaysClient) (vpr VpnProfileResponse, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGenerateVpnProfileFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vpr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysGenerateVpnProfileFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vpr.Response.Response, err = future.GetResult(sender); err == nil && vpr.Response.Response.StatusCode != http.StatusNoContent { - vpr, err = client.GenerateVpnProfileResponder(vpr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGenerateVpnProfileFuture", "Result", vpr.Response.Response, "Failure responding to request") - } - } - return -} - -// P2sVpnGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type P2sVpnGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (P2SVpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysUpdateTagsFuture.Result. -func (future *P2sVpnGatewaysUpdateTagsFuture) result(client P2sVpnGatewaysClient) (pvg P2SVpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvg.Response.Response, err = future.GetResult(sender); err == nil && pvg.Response.Response.StatusCode != http.StatusNoContent { - pvg, err = client.UpdateTagsResponder(pvg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysUpdateTagsFuture", "Result", pvg.Response.Response, "Failure responding to request") - } - } - return -} - -// P2SVpnProfileParameters vpn Client Parameters for package generation -type P2SVpnProfileParameters struct { - // AuthenticationMethod - VPN client Authentication Method. Possible values are: 'EAPTLS' and 'EAPMSCHAPv2'. Possible values include: 'EAPTLS', 'EAPMSCHAPv2' - AuthenticationMethod AuthenticationMethod `json:"authenticationMethod,omitempty"` -} - -// P2SVpnServerConfigRadiusClientRootCertificate radius client root certificate of -// P2SVpnServerConfiguration. -type P2SVpnServerConfigRadiusClientRootCertificate struct { - // P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat - Properties of the Radius client root certificate. - *P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigRadiusClientRootCertificate. -func (pvscrcrc P2SVpnServerConfigRadiusClientRootCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscrcrc.P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat != nil { - objectMap["properties"] = pvscrcrc.P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat - } - if pvscrcrc.Name != nil { - objectMap["name"] = pvscrcrc.Name - } - if pvscrcrc.Etag != nil { - objectMap["etag"] = pvscrcrc.Etag - } - if pvscrcrc.ID != nil { - objectMap["id"] = pvscrcrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SVpnServerConfigRadiusClientRootCertificate struct. -func (pvscrcrc *P2SVpnServerConfigRadiusClientRootCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat - err = json.Unmarshal(*v, &p2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat) - if err != nil { - return err - } - pvscrcrc.P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat = &p2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pvscrcrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pvscrcrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pvscrcrc.ID = &ID - } - } - } - - return nil -} - -// P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat properties of the Radius client root -// certificate of P2SVpnServerConfiguration. -type P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat struct { - // Thumbprint - The Radius client root certificate thumbprint. - Thumbprint *string `json:"thumbprint,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the Radius client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat. -func (pvscrcrcpf P2SVpnServerConfigRadiusClientRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscrcrcpf.Thumbprint != nil { - objectMap["thumbprint"] = pvscrcrcpf.Thumbprint - } - return json.Marshal(objectMap) -} - -// P2SVpnServerConfigRadiusServerRootCertificate radius Server root certificate of -// P2SVpnServerConfiguration. -type P2SVpnServerConfigRadiusServerRootCertificate struct { - // P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat - Properties of the P2SVpnServerConfiguration Radius Server root certificate. - *P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigRadiusServerRootCertificate. -func (pvscrsrc P2SVpnServerConfigRadiusServerRootCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscrsrc.P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat != nil { - objectMap["properties"] = pvscrsrc.P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat - } - if pvscrsrc.Name != nil { - objectMap["name"] = pvscrsrc.Name - } - if pvscrsrc.Etag != nil { - objectMap["etag"] = pvscrsrc.Etag - } - if pvscrsrc.ID != nil { - objectMap["id"] = pvscrsrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SVpnServerConfigRadiusServerRootCertificate struct. -func (pvscrsrc *P2SVpnServerConfigRadiusServerRootCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat - err = json.Unmarshal(*v, &p2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat) - if err != nil { - return err - } - pvscrsrc.P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat = &p2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pvscrsrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pvscrsrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pvscrsrc.ID = &ID - } - } - } - - return nil -} - -// P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat properties of Radius Server root -// certificate of P2SVpnServerConfiguration. -type P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat struct { - // PublicCertData - The certificate public data. - PublicCertData *string `json:"publicCertData,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the P2SVpnServerConfiguration Radius Server root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat. -func (pvscrsrcpf P2SVpnServerConfigRadiusServerRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscrsrcpf.PublicCertData != nil { - objectMap["publicCertData"] = pvscrsrcpf.PublicCertData - } - return json.Marshal(objectMap) -} - -// P2SVpnServerConfiguration p2SVpnServerConfiguration Resource. -type P2SVpnServerConfiguration struct { - autorest.Response `json:"-"` - *P2SVpnServerConfigurationProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfiguration. -func (pvsc P2SVpnServerConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvsc.P2SVpnServerConfigurationProperties != nil { - objectMap["properties"] = pvsc.P2SVpnServerConfigurationProperties - } - if pvsc.Name != nil { - objectMap["name"] = pvsc.Name - } - if pvsc.ID != nil { - objectMap["id"] = pvsc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SVpnServerConfiguration struct. -func (pvsc *P2SVpnServerConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SVpnServerConfigurationProperties P2SVpnServerConfigurationProperties - err = json.Unmarshal(*v, &p2SVpnServerConfigurationProperties) - if err != nil { - return err - } - pvsc.P2SVpnServerConfigurationProperties = &p2SVpnServerConfigurationProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pvsc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pvsc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pvsc.ID = &ID - } - } - } - - return nil -} - -// P2SVpnServerConfigurationProperties parameters for P2SVpnServerConfiguration -type P2SVpnServerConfigurationProperties struct { - // Name - The name of the P2SVpnServerConfiguration that is unique within a VirtualWan in a resource group. This name can be used to access the resource along with Parent VirtualWan resource name. - Name *string `json:"name,omitempty"` - // VpnProtocols - vpnProtocols for the P2SVpnServerConfiguration. - VpnProtocols *[]VpnGatewayTunnelingProtocol `json:"vpnProtocols,omitempty"` - // P2SVpnServerConfigVpnClientRootCertificates - VPN client root certificate of P2SVpnServerConfiguration. - P2SVpnServerConfigVpnClientRootCertificates *[]P2SVpnServerConfigVpnClientRootCertificate `json:"p2SVpnServerConfigVpnClientRootCertificates,omitempty"` - // P2SVpnServerConfigVpnClientRevokedCertificates - VPN client revoked certificate of P2SVpnServerConfiguration. - P2SVpnServerConfigVpnClientRevokedCertificates *[]P2SVpnServerConfigVpnClientRevokedCertificate `json:"p2SVpnServerConfigVpnClientRevokedCertificates,omitempty"` - // P2SVpnServerConfigRadiusServerRootCertificates - Radius Server root certificate of P2SVpnServerConfiguration. - P2SVpnServerConfigRadiusServerRootCertificates *[]P2SVpnServerConfigRadiusServerRootCertificate `json:"p2SVpnServerConfigRadiusServerRootCertificates,omitempty"` - // P2SVpnServerConfigRadiusClientRootCertificates - Radius client root certificate of P2SVpnServerConfiguration. - P2SVpnServerConfigRadiusClientRootCertificates *[]P2SVpnServerConfigRadiusClientRootCertificate `json:"p2SVpnServerConfigRadiusClientRootCertificates,omitempty"` - // VpnClientIpsecPolicies - VpnClientIpsecPolicies for P2SVpnServerConfiguration. - VpnClientIpsecPolicies *[]IpsecPolicy `json:"vpnClientIpsecPolicies,omitempty"` - // RadiusServerAddress - The radius server address property of the P2SVpnServerConfiguration resource for point to site client connection. - RadiusServerAddress *string `json:"radiusServerAddress,omitempty"` - // RadiusServerSecret - The radius secret property of the P2SVpnServerConfiguration resource for point to site client connection. - RadiusServerSecret *string `json:"radiusServerSecret,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the P2SVpnServerConfiguration resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // P2SVpnGateways - READ-ONLY - P2SVpnGateways *[]SubResource `json:"p2SVpnGateways,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigurationProperties. -func (pvscp P2SVpnServerConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscp.Name != nil { - objectMap["name"] = pvscp.Name - } - if pvscp.VpnProtocols != nil { - objectMap["vpnProtocols"] = pvscp.VpnProtocols - } - if pvscp.P2SVpnServerConfigVpnClientRootCertificates != nil { - objectMap["p2SVpnServerConfigVpnClientRootCertificates"] = pvscp.P2SVpnServerConfigVpnClientRootCertificates - } - if pvscp.P2SVpnServerConfigVpnClientRevokedCertificates != nil { - objectMap["p2SVpnServerConfigVpnClientRevokedCertificates"] = pvscp.P2SVpnServerConfigVpnClientRevokedCertificates - } - if pvscp.P2SVpnServerConfigRadiusServerRootCertificates != nil { - objectMap["p2SVpnServerConfigRadiusServerRootCertificates"] = pvscp.P2SVpnServerConfigRadiusServerRootCertificates - } - if pvscp.P2SVpnServerConfigRadiusClientRootCertificates != nil { - objectMap["p2SVpnServerConfigRadiusClientRootCertificates"] = pvscp.P2SVpnServerConfigRadiusClientRootCertificates - } - if pvscp.VpnClientIpsecPolicies != nil { - objectMap["vpnClientIpsecPolicies"] = pvscp.VpnClientIpsecPolicies - } - if pvscp.RadiusServerAddress != nil { - objectMap["radiusServerAddress"] = pvscp.RadiusServerAddress - } - if pvscp.RadiusServerSecret != nil { - objectMap["radiusServerSecret"] = pvscp.RadiusServerSecret - } - if pvscp.Etag != nil { - objectMap["etag"] = pvscp.Etag - } - return json.Marshal(objectMap) -} - -// P2sVpnServerConfigurationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type P2sVpnServerConfigurationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnServerConfigurationsClient) (P2SVpnServerConfiguration, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnServerConfigurationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnServerConfigurationsCreateOrUpdateFuture.Result. -func (future *P2sVpnServerConfigurationsCreateOrUpdateFuture) result(client P2sVpnServerConfigurationsClient) (pvsc P2SVpnServerConfiguration, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvsc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnServerConfigurationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvsc.Response.Response, err = future.GetResult(sender); err == nil && pvsc.Response.Response.StatusCode != http.StatusNoContent { - pvsc, err = client.CreateOrUpdateResponder(pvsc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsCreateOrUpdateFuture", "Result", pvsc.Response.Response, "Failure responding to request") - } - } - return -} - -// P2sVpnServerConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type P2sVpnServerConfigurationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnServerConfigurationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnServerConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnServerConfigurationsDeleteFuture.Result. -func (future *P2sVpnServerConfigurationsDeleteFuture) result(client P2sVpnServerConfigurationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnServerConfigurationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// P2SVpnServerConfigVpnClientRevokedCertificate VPN client revoked certificate of -// P2SVpnServerConfiguration. -type P2SVpnServerConfigVpnClientRevokedCertificate struct { - // P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat - Properties of the vpn client revoked certificate. - *P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigVpnClientRevokedCertificate. -func (pvscvcrc P2SVpnServerConfigVpnClientRevokedCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscvcrc.P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat != nil { - objectMap["properties"] = pvscvcrc.P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat - } - if pvscvcrc.Name != nil { - objectMap["name"] = pvscvcrc.Name - } - if pvscvcrc.Etag != nil { - objectMap["etag"] = pvscvcrc.Etag - } - if pvscvcrc.ID != nil { - objectMap["id"] = pvscvcrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SVpnServerConfigVpnClientRevokedCertificate struct. -func (pvscvcrc *P2SVpnServerConfigVpnClientRevokedCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat - err = json.Unmarshal(*v, &p2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat) - if err != nil { - return err - } - pvscvcrc.P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat = &p2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pvscvcrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pvscvcrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pvscvcrc.ID = &ID - } - } - } - - return nil -} - -// P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat properties of the revoked VPN client -// certificate of P2SVpnServerConfiguration. -type P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat struct { - // Thumbprint - The revoked VPN client certificate thumbprint. - Thumbprint *string `json:"thumbprint,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN client revoked certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat. -func (pvscvcrcpf P2SVpnServerConfigVpnClientRevokedCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscvcrcpf.Thumbprint != nil { - objectMap["thumbprint"] = pvscvcrcpf.Thumbprint - } - return json.Marshal(objectMap) -} - -// P2SVpnServerConfigVpnClientRootCertificate VPN client root certificate of P2SVpnServerConfiguration. -type P2SVpnServerConfigVpnClientRootCertificate struct { - // P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat - Properties of the P2SVpnServerConfiguration VPN client root certificate. - *P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigVpnClientRootCertificate. -func (pvscvcrc P2SVpnServerConfigVpnClientRootCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscvcrc.P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat != nil { - objectMap["properties"] = pvscvcrc.P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat - } - if pvscvcrc.Name != nil { - objectMap["name"] = pvscvcrc.Name - } - if pvscvcrc.Etag != nil { - objectMap["etag"] = pvscvcrc.Etag - } - if pvscvcrc.ID != nil { - objectMap["id"] = pvscvcrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SVpnServerConfigVpnClientRootCertificate struct. -func (pvscvcrc *P2SVpnServerConfigVpnClientRootCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SVpnServerConfigVpnClientRootCertificatePropertiesFormat P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat - err = json.Unmarshal(*v, &p2SVpnServerConfigVpnClientRootCertificatePropertiesFormat) - if err != nil { - return err - } - pvscvcrc.P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat = &p2SVpnServerConfigVpnClientRootCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pvscvcrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pvscvcrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pvscvcrc.ID = &ID - } - } - } - - return nil -} - -// P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat properties of VPN client root certificate of -// P2SVpnServerConfiguration. -type P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat struct { - // PublicCertData - The certificate public data. - PublicCertData *string `json:"publicCertData,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the P2SVpnServerConfiguration VPN client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat. -func (pvscvcrcpf P2SVpnServerConfigVpnClientRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvscvcrcpf.PublicCertData != nil { - objectMap["publicCertData"] = pvscvcrcpf.PublicCertData - } - return json.Marshal(objectMap) -} - -// PacketCapture parameters that define the create packet capture operation. -type PacketCapture struct { - *PacketCaptureParameters `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for PacketCapture. -func (pc PacketCapture) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pc.PacketCaptureParameters != nil { - objectMap["properties"] = pc.PacketCaptureParameters - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PacketCapture struct. -func (pc *PacketCapture) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var packetCaptureParameters PacketCaptureParameters - err = json.Unmarshal(*v, &packetCaptureParameters) - if err != nil { - return err - } - pc.PacketCaptureParameters = &packetCaptureParameters - } - } - } - - return nil -} - -// PacketCaptureFilter filter that is applied to packet capture request. Multiple filters can be applied. -type PacketCaptureFilter struct { - // Protocol - Protocol to be filtered on. Possible values include: 'PcProtocolTCP', 'PcProtocolUDP', 'PcProtocolAny' - Protocol PcProtocol `json:"protocol,omitempty"` - // LocalIPAddress - Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - LocalIPAddress *string `json:"localIPAddress,omitempty"` - // RemoteIPAddress - Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - RemoteIPAddress *string `json:"remoteIPAddress,omitempty"` - // LocalPort - Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - LocalPort *string `json:"localPort,omitempty"` - // RemotePort - Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - RemotePort *string `json:"remotePort,omitempty"` -} - -// PacketCaptureListResult list of packet capture sessions. -type PacketCaptureListResult struct { - autorest.Response `json:"-"` - // Value - Information about packet capture sessions. - Value *[]PacketCaptureResult `json:"value,omitempty"` -} - -// PacketCaptureParameters parameters that define the create packet capture operation. -type PacketCaptureParameters struct { - // Target - The ID of the targeted resource, only VM is currently supported. - Target *string `json:"target,omitempty"` - // BytesToCapturePerPacket - Number of bytes captured per packet, the remaining bytes are truncated. - BytesToCapturePerPacket *int32 `json:"bytesToCapturePerPacket,omitempty"` - // TotalBytesPerSession - Maximum size of the capture output. - TotalBytesPerSession *int32 `json:"totalBytesPerSession,omitempty"` - // TimeLimitInSeconds - Maximum duration of the capture session in seconds. - TimeLimitInSeconds *int32 `json:"timeLimitInSeconds,omitempty"` - StorageLocation *PacketCaptureStorageLocation `json:"storageLocation,omitempty"` - Filters *[]PacketCaptureFilter `json:"filters,omitempty"` -} - -// PacketCaptureQueryStatusResult status of packet capture session. -type PacketCaptureQueryStatusResult struct { - autorest.Response `json:"-"` - // Name - The name of the packet capture resource. - Name *string `json:"name,omitempty"` - // ID - The ID of the packet capture resource. - ID *string `json:"id,omitempty"` - // CaptureStartTime - The start time of the packet capture session. - CaptureStartTime *date.Time `json:"captureStartTime,omitempty"` - // PacketCaptureStatus - The status of the packet capture session. Possible values include: 'PcStatusNotStarted', 'PcStatusRunning', 'PcStatusStopped', 'PcStatusError', 'PcStatusUnknown' - PacketCaptureStatus PcStatus `json:"packetCaptureStatus,omitempty"` - // StopReason - The reason the current packet capture session was stopped. - StopReason *string `json:"stopReason,omitempty"` - // PacketCaptureError - List of errors of packet capture session. - PacketCaptureError *[]PcError `json:"packetCaptureError,omitempty"` -} - -// PacketCaptureResult information about packet capture session. -type PacketCaptureResult struct { - autorest.Response `json:"-"` - // Name - READ-ONLY; Name of the packet capture session. - Name *string `json:"name,omitempty"` - // ID - READ-ONLY; ID of the packet capture operation. - ID *string `json:"id,omitempty"` - Etag *string `json:"etag,omitempty"` - *PacketCaptureResultProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for PacketCaptureResult. -func (pcr PacketCaptureResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pcr.Etag != nil { - objectMap["etag"] = pcr.Etag - } - if pcr.PacketCaptureResultProperties != nil { - objectMap["properties"] = pcr.PacketCaptureResultProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PacketCaptureResult struct. -func (pcr *PacketCaptureResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pcr.Name = &name - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pcr.ID = &ID - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pcr.Etag = &etag - } - case "properties": - if v != nil { - var packetCaptureResultProperties PacketCaptureResultProperties - err = json.Unmarshal(*v, &packetCaptureResultProperties) - if err != nil { - return err - } - pcr.PacketCaptureResultProperties = &packetCaptureResultProperties - } - } - } - - return nil -} - -// PacketCaptureResultProperties describes the properties of a packet capture session. -type PacketCaptureResultProperties struct { - // ProvisioningState - The provisioning state of the packet capture session. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Target - The ID of the targeted resource, only VM is currently supported. - Target *string `json:"target,omitempty"` - // BytesToCapturePerPacket - Number of bytes captured per packet, the remaining bytes are truncated. - BytesToCapturePerPacket *int32 `json:"bytesToCapturePerPacket,omitempty"` - // TotalBytesPerSession - Maximum size of the capture output. - TotalBytesPerSession *int32 `json:"totalBytesPerSession,omitempty"` - // TimeLimitInSeconds - Maximum duration of the capture session in seconds. - TimeLimitInSeconds *int32 `json:"timeLimitInSeconds,omitempty"` - StorageLocation *PacketCaptureStorageLocation `json:"storageLocation,omitempty"` - Filters *[]PacketCaptureFilter `json:"filters,omitempty"` -} - -// PacketCapturesCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (PacketCaptureResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesCreateFuture.Result. -func (future *PacketCapturesCreateFuture) result(client PacketCapturesClient) (pcr PacketCaptureResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pcr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesCreateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pcr.Response.Response, err = future.GetResult(sender); err == nil && pcr.Response.Response.StatusCode != http.StatusNoContent { - pcr, err = client.CreateResponder(pcr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesCreateFuture", "Result", pcr.Response.Response, "Failure responding to request") - } - } - return -} - -// PacketCapturesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesDeleteFuture.Result. -func (future *PacketCapturesDeleteFuture) result(client PacketCapturesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PacketCapturesGetStatusFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesGetStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (PacketCaptureQueryStatusResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesGetStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesGetStatusFuture.Result. -func (future *PacketCapturesGetStatusFuture) result(client PacketCapturesClient) (pcqsr PacketCaptureQueryStatusResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesGetStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pcqsr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesGetStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pcqsr.Response.Response, err = future.GetResult(sender); err == nil && pcqsr.Response.Response.StatusCode != http.StatusNoContent { - pcqsr, err = client.GetStatusResponder(pcqsr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesGetStatusFuture", "Result", pcqsr.Response.Response, "Failure responding to request") - } - } - return -} - -// PacketCapturesStopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesStopFuture.Result. -func (future *PacketCapturesStopFuture) result(client PacketCapturesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesStopFuture") - return - } - ar.Response = future.Response() - return -} - -// PacketCaptureStorageLocation describes the storage location for a packet capture session. -type PacketCaptureStorageLocation struct { - // StorageID - The ID of the storage account to save the packet capture session. Required if no local file path is provided. - StorageID *string `json:"storageId,omitempty"` - // StoragePath - The URI of the storage path to save the packet capture. Must be a well-formed URI describing the location to save the packet capture. - StoragePath *string `json:"storagePath,omitempty"` - // FilePath - A valid local path on the targeting VM. Must include the name of the capture file (*.cap). For linux virtual machine it must start with /var/captures. Required if no storage ID is provided, otherwise optional. - FilePath *string `json:"filePath,omitempty"` -} - -// PatchRouteFilter route Filter Resource. -type PatchRouteFilter struct { - *RouteFilterPropertiesFormat `json:"properties,omitempty"` - // Name - READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PatchRouteFilter. -func (prf PatchRouteFilter) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if prf.RouteFilterPropertiesFormat != nil { - objectMap["properties"] = prf.RouteFilterPropertiesFormat - } - if prf.Tags != nil { - objectMap["tags"] = prf.Tags - } - if prf.ID != nil { - objectMap["id"] = prf.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PatchRouteFilter struct. -func (prf *PatchRouteFilter) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterPropertiesFormat RouteFilterPropertiesFormat - err = json.Unmarshal(*v, &routeFilterPropertiesFormat) - if err != nil { - return err - } - prf.RouteFilterPropertiesFormat = &routeFilterPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - prf.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - prf.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - prf.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - prf.Tags = tags - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - prf.ID = &ID - } - } - } - - return nil -} - -// PatchRouteFilterRule route Filter Rule Resource -type PatchRouteFilterRule struct { - *RouteFilterRulePropertiesFormat `json:"properties,omitempty"` - // Name - READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PatchRouteFilterRule. -func (prfr PatchRouteFilterRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if prfr.RouteFilterRulePropertiesFormat != nil { - objectMap["properties"] = prfr.RouteFilterRulePropertiesFormat - } - if prfr.ID != nil { - objectMap["id"] = prfr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PatchRouteFilterRule struct. -func (prfr *PatchRouteFilterRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterRulePropertiesFormat RouteFilterRulePropertiesFormat - err = json.Unmarshal(*v, &routeFilterRulePropertiesFormat) - if err != nil { - return err - } - prfr.RouteFilterRulePropertiesFormat = &routeFilterRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - prfr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - prfr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - prfr.ID = &ID - } - } - } - - return nil -} - -// Probe a load balancer probe. -type Probe struct { - autorest.Response `json:"-"` - // ProbePropertiesFormat - Properties of load balancer probe. - *ProbePropertiesFormat `json:"properties,omitempty"` - // Name - Gets name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Probe. -func (p Probe) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if p.ProbePropertiesFormat != nil { - objectMap["properties"] = p.ProbePropertiesFormat - } - if p.Name != nil { - objectMap["name"] = p.Name - } - if p.Etag != nil { - objectMap["etag"] = p.Etag - } - if p.ID != nil { - objectMap["id"] = p.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Probe struct. -func (p *Probe) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var probePropertiesFormat ProbePropertiesFormat - err = json.Unmarshal(*v, &probePropertiesFormat) - if err != nil { - return err - } - p.ProbePropertiesFormat = &probePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - p.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - p.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - p.ID = &ID - } - } - } - - return nil -} - -// ProbePropertiesFormat load balancer probe resource. -type ProbePropertiesFormat struct { - // LoadBalancingRules - READ-ONLY; The load balancer rules that use this probe. - LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` - // Protocol - The protocol of the end point. Possible values are: 'Http', 'Tcp', or 'Https'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' or 'Https' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. Possible values include: 'ProbeProtocolHTTP', 'ProbeProtocolTCP', 'ProbeProtocolHTTPS' - Protocol ProbeProtocol `json:"protocol,omitempty"` - // Port - The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - Port *int32 `json:"port,omitempty"` - // IntervalInSeconds - The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - IntervalInSeconds *int32 `json:"intervalInSeconds,omitempty"` - // NumberOfProbes - The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - NumberOfProbes *int32 `json:"numberOfProbes,omitempty"` - // RequestPath - The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. - RequestPath *string `json:"requestPath,omitempty"` - // ProvisioningState - Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProbePropertiesFormat. -func (ppf ProbePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ppf.Protocol != "" { - objectMap["protocol"] = ppf.Protocol - } - if ppf.Port != nil { - objectMap["port"] = ppf.Port - } - if ppf.IntervalInSeconds != nil { - objectMap["intervalInSeconds"] = ppf.IntervalInSeconds - } - if ppf.NumberOfProbes != nil { - objectMap["numberOfProbes"] = ppf.NumberOfProbes - } - if ppf.RequestPath != nil { - objectMap["requestPath"] = ppf.RequestPath - } - if ppf.ProvisioningState != nil { - objectMap["provisioningState"] = ppf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// Profile network profile resource. -type Profile struct { - autorest.Response `json:"-"` - // ProfilePropertiesFormat - Network profile properties. - *ProfilePropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Profile. -func (p Profile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if p.ProfilePropertiesFormat != nil { - objectMap["properties"] = p.ProfilePropertiesFormat - } - if p.Etag != nil { - objectMap["etag"] = p.Etag - } - if p.ID != nil { - objectMap["id"] = p.ID - } - if p.Location != nil { - objectMap["location"] = p.Location - } - if p.Tags != nil { - objectMap["tags"] = p.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Profile struct. -func (p *Profile) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var profilePropertiesFormat ProfilePropertiesFormat - err = json.Unmarshal(*v, &profilePropertiesFormat) - if err != nil { - return err - } - p.ProfilePropertiesFormat = &profilePropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - p.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - p.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - p.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - p.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - p.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - p.Tags = tags - } - } - } - - return nil -} - -// ProfileListResult response for ListNetworkProfiles API service call. -type ProfileListResult struct { - autorest.Response `json:"-"` - // Value - A list of network profiles that exist in a resource group. - Value *[]Profile `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ProfileListResultIterator provides access to a complete listing of Profile values. -type ProfileListResultIterator struct { - i int - page ProfileListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ProfileListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfileListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ProfileListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ProfileListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ProfileListResultIterator) Response() ProfileListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ProfileListResultIterator) Value() Profile { - if !iter.page.NotDone() { - return Profile{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ProfileListResultIterator type. -func NewProfileListResultIterator(page ProfileListResultPage) ProfileListResultIterator { - return ProfileListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (plr ProfileListResult) IsEmpty() bool { - return plr.Value == nil || len(*plr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (plr ProfileListResult) hasNextLink() bool { - return plr.NextLink != nil && len(*plr.NextLink) != 0 -} - -// profileListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (plr ProfileListResult) profileListResultPreparer(ctx context.Context) (*http.Request, error) { - if !plr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(plr.NextLink))) -} - -// ProfileListResultPage contains a page of Profile values. -type ProfileListResultPage struct { - fn func(context.Context, ProfileListResult) (ProfileListResult, error) - plr ProfileListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ProfileListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfileListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.plr) - if err != nil { - return err - } - page.plr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ProfileListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ProfileListResultPage) NotDone() bool { - return !page.plr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ProfileListResultPage) Response() ProfileListResult { - return page.plr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ProfileListResultPage) Values() []Profile { - if page.plr.IsEmpty() { - return nil - } - return *page.plr.Value -} - -// Creates a new instance of the ProfileListResultPage type. -func NewProfileListResultPage(cur ProfileListResult, getNextPage func(context.Context, ProfileListResult) (ProfileListResult, error)) ProfileListResultPage { - return ProfileListResultPage{ - fn: getNextPage, - plr: cur, - } -} - -// ProfilePropertiesFormat network profile properties. -type ProfilePropertiesFormat struct { - // ContainerNetworkInterfaces - List of child container network interfaces. - ContainerNetworkInterfaces *[]ContainerNetworkInterface `json:"containerNetworkInterfaces,omitempty"` - // ContainerNetworkInterfaceConfigurations - List of chid container network interface configurations. - ContainerNetworkInterfaceConfigurations *[]ContainerNetworkInterfaceConfiguration `json:"containerNetworkInterfaceConfigurations,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the network interface resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProfilePropertiesFormat. -func (ppf ProfilePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ppf.ContainerNetworkInterfaces != nil { - objectMap["containerNetworkInterfaces"] = ppf.ContainerNetworkInterfaces - } - if ppf.ContainerNetworkInterfaceConfigurations != nil { - objectMap["containerNetworkInterfaceConfigurations"] = ppf.ContainerNetworkInterfaceConfigurations - } - return json.Marshal(objectMap) -} - -// ProfilesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ProfilesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ProfilesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ProfilesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ProfilesDeleteFuture.Result. -func (future *ProfilesDeleteFuture) result(client ProfilesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ProfilesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ProtocolConfiguration configuration of the protocol. -type ProtocolConfiguration struct { - HTTPConfiguration *HTTPConfiguration `json:"HTTPConfiguration,omitempty"` -} - -// PublicIPAddress public IP address resource. -type PublicIPAddress struct { - autorest.Response `json:"-"` - // Sku - The public IP address SKU. - Sku *PublicIPAddressSku `json:"sku,omitempty"` - // PublicIPAddressPropertiesFormat - Public IP address properties. - *PublicIPAddressPropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting the IP allocated for the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PublicIPAddress. -func (pia PublicIPAddress) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pia.Sku != nil { - objectMap["sku"] = pia.Sku - } - if pia.PublicIPAddressPropertiesFormat != nil { - objectMap["properties"] = pia.PublicIPAddressPropertiesFormat - } - if pia.Etag != nil { - objectMap["etag"] = pia.Etag - } - if pia.Zones != nil { - objectMap["zones"] = pia.Zones - } - if pia.ID != nil { - objectMap["id"] = pia.ID - } - if pia.Location != nil { - objectMap["location"] = pia.Location - } - if pia.Tags != nil { - objectMap["tags"] = pia.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PublicIPAddress struct. -func (pia *PublicIPAddress) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku PublicIPAddressSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - pia.Sku = &sku - } - case "properties": - if v != nil { - var publicIPAddressPropertiesFormat PublicIPAddressPropertiesFormat - err = json.Unmarshal(*v, &publicIPAddressPropertiesFormat) - if err != nil { - return err - } - pia.PublicIPAddressPropertiesFormat = &publicIPAddressPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pia.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - pia.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pia.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pia.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pia.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - pia.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pia.Tags = tags - } - } - } - - return nil -} - -// PublicIPAddressDNSSettings contains FQDN of the DNS record associated with the public IP address -type PublicIPAddressDNSSettings struct { - // DomainNameLabel - Gets or sets the Domain name label.The concatenation of the domain name label and the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. - DomainNameLabel *string `json:"domainNameLabel,omitempty"` - // Fqdn - Gets the FQDN, Fully qualified domain name of the A DNS record associated with the public IP. This is the concatenation of the domainNameLabel and the regionalized DNS zone. - Fqdn *string `json:"fqdn,omitempty"` - // ReverseFqdn - Gets or Sets the Reverse FQDN. A user-visible, fully qualified domain name that resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. - ReverseFqdn *string `json:"reverseFqdn,omitempty"` -} - -// PublicIPAddressesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PublicIPAddressesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPAddressesClient) (PublicIPAddress, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPAddressesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPAddressesCreateOrUpdateFuture.Result. -func (future *PublicIPAddressesCreateOrUpdateFuture) result(client PublicIPAddressesClient) (pia PublicIPAddress, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pia.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPAddressesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pia.Response.Response, err = future.GetResult(sender); err == nil && pia.Response.Response.StatusCode != http.StatusNoContent { - pia, err = client.CreateOrUpdateResponder(pia.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesCreateOrUpdateFuture", "Result", pia.Response.Response, "Failure responding to request") - } - } - return -} - -// PublicIPAddressesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PublicIPAddressesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPAddressesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPAddressesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPAddressesDeleteFuture.Result. -func (future *PublicIPAddressesDeleteFuture) result(client PublicIPAddressesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPAddressesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PublicIPAddressesUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PublicIPAddressesUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPAddressesClient) (PublicIPAddress, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPAddressesUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPAddressesUpdateTagsFuture.Result. -func (future *PublicIPAddressesUpdateTagsFuture) result(client PublicIPAddressesClient) (pia PublicIPAddress, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pia.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPAddressesUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pia.Response.Response, err = future.GetResult(sender); err == nil && pia.Response.Response.StatusCode != http.StatusNoContent { - pia, err = client.UpdateTagsResponder(pia.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesUpdateTagsFuture", "Result", pia.Response.Response, "Failure responding to request") - } - } - return -} - -// PublicIPAddressListResult response for ListPublicIpAddresses API service call. -type PublicIPAddressListResult struct { - autorest.Response `json:"-"` - // Value - A list of public IP addresses that exists in a resource group. - Value *[]PublicIPAddress `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// PublicIPAddressListResultIterator provides access to a complete listing of PublicIPAddress values. -type PublicIPAddressListResultIterator struct { - i int - page PublicIPAddressListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PublicIPAddressListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PublicIPAddressListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PublicIPAddressListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PublicIPAddressListResultIterator) Response() PublicIPAddressListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PublicIPAddressListResultIterator) Value() PublicIPAddress { - if !iter.page.NotDone() { - return PublicIPAddress{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PublicIPAddressListResultIterator type. -func NewPublicIPAddressListResultIterator(page PublicIPAddressListResultPage) PublicIPAddressListResultIterator { - return PublicIPAddressListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (pialr PublicIPAddressListResult) IsEmpty() bool { - return pialr.Value == nil || len(*pialr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (pialr PublicIPAddressListResult) hasNextLink() bool { - return pialr.NextLink != nil && len(*pialr.NextLink) != 0 -} - -// publicIPAddressListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pialr PublicIPAddressListResult) publicIPAddressListResultPreparer(ctx context.Context) (*http.Request, error) { - if !pialr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pialr.NextLink))) -} - -// PublicIPAddressListResultPage contains a page of PublicIPAddress values. -type PublicIPAddressListResultPage struct { - fn func(context.Context, PublicIPAddressListResult) (PublicIPAddressListResult, error) - pialr PublicIPAddressListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PublicIPAddressListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.pialr) - if err != nil { - return err - } - page.pialr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PublicIPAddressListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PublicIPAddressListResultPage) NotDone() bool { - return !page.pialr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PublicIPAddressListResultPage) Response() PublicIPAddressListResult { - return page.pialr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PublicIPAddressListResultPage) Values() []PublicIPAddress { - if page.pialr.IsEmpty() { - return nil - } - return *page.pialr.Value -} - -// Creates a new instance of the PublicIPAddressListResultPage type. -func NewPublicIPAddressListResultPage(cur PublicIPAddressListResult, getNextPage func(context.Context, PublicIPAddressListResult) (PublicIPAddressListResult, error)) PublicIPAddressListResultPage { - return PublicIPAddressListResultPage{ - fn: getNextPage, - pialr: cur, - } -} - -// PublicIPAddressPropertiesFormat public IP address properties. -type PublicIPAddressPropertiesFormat struct { - // PublicIPAllocationMethod - The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. Possible values include: 'Static', 'Dynamic' - PublicIPAllocationMethod IPAllocationMethod `json:"publicIPAllocationMethod,omitempty"` - // PublicIPAddressVersion - The public IP address version. Possible values are: 'IPv4' and 'IPv6'. Possible values include: 'IPv4', 'IPv6' - PublicIPAddressVersion IPVersion `json:"publicIPAddressVersion,omitempty"` - // IPConfiguration - READ-ONLY; The IP configuration associated with the public IP address. - IPConfiguration *IPConfiguration `json:"ipConfiguration,omitempty"` - // DNSSettings - The FQDN of the DNS record associated with the public IP address. - DNSSettings *PublicIPAddressDNSSettings `json:"dnsSettings,omitempty"` - // IPTags - The list of tags associated with the public IP address. - IPTags *[]IPTag `json:"ipTags,omitempty"` - // IPAddress - The IP address associated with the public IP address resource. - IPAddress *string `json:"ipAddress,omitempty"` - // PublicIPPrefix - The Public IP Prefix this Public IP Address should be allocated from. - PublicIPPrefix *SubResource `json:"publicIPPrefix,omitempty"` - // IdleTimeoutInMinutes - The idle timeout of the public IP address. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // ResourceGUID - The resource GUID property of the public IP resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for PublicIPAddressPropertiesFormat. -func (piapf PublicIPAddressPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if piapf.PublicIPAllocationMethod != "" { - objectMap["publicIPAllocationMethod"] = piapf.PublicIPAllocationMethod - } - if piapf.PublicIPAddressVersion != "" { - objectMap["publicIPAddressVersion"] = piapf.PublicIPAddressVersion - } - if piapf.DNSSettings != nil { - objectMap["dnsSettings"] = piapf.DNSSettings - } - if piapf.IPTags != nil { - objectMap["ipTags"] = piapf.IPTags - } - if piapf.IPAddress != nil { - objectMap["ipAddress"] = piapf.IPAddress - } - if piapf.PublicIPPrefix != nil { - objectMap["publicIPPrefix"] = piapf.PublicIPPrefix - } - if piapf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = piapf.IdleTimeoutInMinutes - } - if piapf.ResourceGUID != nil { - objectMap["resourceGuid"] = piapf.ResourceGUID - } - if piapf.ProvisioningState != nil { - objectMap["provisioningState"] = piapf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// PublicIPAddressSku SKU of a public IP address -type PublicIPAddressSku struct { - // Name - Name of a public IP address SKU. Possible values include: 'PublicIPAddressSkuNameBasic', 'PublicIPAddressSkuNameStandard' - Name PublicIPAddressSkuName `json:"name,omitempty"` -} - -// PublicIPPrefix public IP prefix resource. -type PublicIPPrefix struct { - autorest.Response `json:"-"` - // Sku - The public IP prefix SKU. - Sku *PublicIPPrefixSku `json:"sku,omitempty"` - // PublicIPPrefixPropertiesFormat - Public IP prefix properties. - *PublicIPPrefixPropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting the IP allocated for the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PublicIPPrefix. -func (pip PublicIPPrefix) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pip.Sku != nil { - objectMap["sku"] = pip.Sku - } - if pip.PublicIPPrefixPropertiesFormat != nil { - objectMap["properties"] = pip.PublicIPPrefixPropertiesFormat - } - if pip.Etag != nil { - objectMap["etag"] = pip.Etag - } - if pip.Zones != nil { - objectMap["zones"] = pip.Zones - } - if pip.ID != nil { - objectMap["id"] = pip.ID - } - if pip.Location != nil { - objectMap["location"] = pip.Location - } - if pip.Tags != nil { - objectMap["tags"] = pip.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PublicIPPrefix struct. -func (pip *PublicIPPrefix) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku PublicIPPrefixSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - pip.Sku = &sku - } - case "properties": - if v != nil { - var publicIPPrefixPropertiesFormat PublicIPPrefixPropertiesFormat - err = json.Unmarshal(*v, &publicIPPrefixPropertiesFormat) - if err != nil { - return err - } - pip.PublicIPPrefixPropertiesFormat = &publicIPPrefixPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pip.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - pip.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pip.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pip.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pip.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - pip.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pip.Tags = tags - } - } - } - - return nil -} - -// PublicIPPrefixesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PublicIPPrefixesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPPrefixesClient) (PublicIPPrefix, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPPrefixesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPPrefixesCreateOrUpdateFuture.Result. -func (future *PublicIPPrefixesCreateOrUpdateFuture) result(client PublicIPPrefixesClient) (pip PublicIPPrefix, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pip.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPPrefixesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pip.Response.Response, err = future.GetResult(sender); err == nil && pip.Response.Response.StatusCode != http.StatusNoContent { - pip, err = client.CreateOrUpdateResponder(pip.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesCreateOrUpdateFuture", "Result", pip.Response.Response, "Failure responding to request") - } - } - return -} - -// PublicIPPrefixesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PublicIPPrefixesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPPrefixesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPPrefixesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPPrefixesDeleteFuture.Result. -func (future *PublicIPPrefixesDeleteFuture) result(client PublicIPPrefixesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPPrefixesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PublicIPPrefixesUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PublicIPPrefixesUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPPrefixesClient) (PublicIPPrefix, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPPrefixesUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPPrefixesUpdateTagsFuture.Result. -func (future *PublicIPPrefixesUpdateTagsFuture) result(client PublicIPPrefixesClient) (pip PublicIPPrefix, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pip.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPPrefixesUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pip.Response.Response, err = future.GetResult(sender); err == nil && pip.Response.Response.StatusCode != http.StatusNoContent { - pip, err = client.UpdateTagsResponder(pip.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesUpdateTagsFuture", "Result", pip.Response.Response, "Failure responding to request") - } - } - return -} - -// PublicIPPrefixListResult response for ListPublicIpPrefixes API service call. -type PublicIPPrefixListResult struct { - autorest.Response `json:"-"` - // Value - A list of public IP prefixes that exists in a resource group. - Value *[]PublicIPPrefix `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// PublicIPPrefixListResultIterator provides access to a complete listing of PublicIPPrefix values. -type PublicIPPrefixListResultIterator struct { - i int - page PublicIPPrefixListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PublicIPPrefixListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PublicIPPrefixListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PublicIPPrefixListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PublicIPPrefixListResultIterator) Response() PublicIPPrefixListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PublicIPPrefixListResultIterator) Value() PublicIPPrefix { - if !iter.page.NotDone() { - return PublicIPPrefix{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PublicIPPrefixListResultIterator type. -func NewPublicIPPrefixListResultIterator(page PublicIPPrefixListResultPage) PublicIPPrefixListResultIterator { - return PublicIPPrefixListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (piplr PublicIPPrefixListResult) IsEmpty() bool { - return piplr.Value == nil || len(*piplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (piplr PublicIPPrefixListResult) hasNextLink() bool { - return piplr.NextLink != nil && len(*piplr.NextLink) != 0 -} - -// publicIPPrefixListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (piplr PublicIPPrefixListResult) publicIPPrefixListResultPreparer(ctx context.Context) (*http.Request, error) { - if !piplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(piplr.NextLink))) -} - -// PublicIPPrefixListResultPage contains a page of PublicIPPrefix values. -type PublicIPPrefixListResultPage struct { - fn func(context.Context, PublicIPPrefixListResult) (PublicIPPrefixListResult, error) - piplr PublicIPPrefixListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PublicIPPrefixListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.piplr) - if err != nil { - return err - } - page.piplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PublicIPPrefixListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PublicIPPrefixListResultPage) NotDone() bool { - return !page.piplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PublicIPPrefixListResultPage) Response() PublicIPPrefixListResult { - return page.piplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PublicIPPrefixListResultPage) Values() []PublicIPPrefix { - if page.piplr.IsEmpty() { - return nil - } - return *page.piplr.Value -} - -// Creates a new instance of the PublicIPPrefixListResultPage type. -func NewPublicIPPrefixListResultPage(cur PublicIPPrefixListResult, getNextPage func(context.Context, PublicIPPrefixListResult) (PublicIPPrefixListResult, error)) PublicIPPrefixListResultPage { - return PublicIPPrefixListResultPage{ - fn: getNextPage, - piplr: cur, - } -} - -// PublicIPPrefixPropertiesFormat public IP prefix properties. -type PublicIPPrefixPropertiesFormat struct { - // PublicIPAddressVersion - The public IP address version. Possible values are: 'IPv4' and 'IPv6'. Possible values include: 'IPv4', 'IPv6' - PublicIPAddressVersion IPVersion `json:"publicIPAddressVersion,omitempty"` - // IPTags - The list of tags associated with the public IP prefix. - IPTags *[]IPTag `json:"ipTags,omitempty"` - // PrefixLength - The Length of the Public IP Prefix. - PrefixLength *int32 `json:"prefixLength,omitempty"` - // IPPrefix - The allocated Prefix - IPPrefix *string `json:"ipPrefix,omitempty"` - // PublicIPAddresses - The list of all referenced PublicIPAddresses - PublicIPAddresses *[]ReferencedPublicIPAddress `json:"publicIPAddresses,omitempty"` - // LoadBalancerFrontendIPConfiguration - READ-ONLY; The reference to load balancer frontend IP configuration associated with the public IP prefix. - LoadBalancerFrontendIPConfiguration *SubResource `json:"loadBalancerFrontendIpConfiguration,omitempty"` - // ResourceGUID - The resource GUID property of the public IP prefix resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - The provisioning state of the Public IP prefix resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for PublicIPPrefixPropertiesFormat. -func (pippf PublicIPPrefixPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pippf.PublicIPAddressVersion != "" { - objectMap["publicIPAddressVersion"] = pippf.PublicIPAddressVersion - } - if pippf.IPTags != nil { - objectMap["ipTags"] = pippf.IPTags - } - if pippf.PrefixLength != nil { - objectMap["prefixLength"] = pippf.PrefixLength - } - if pippf.IPPrefix != nil { - objectMap["ipPrefix"] = pippf.IPPrefix - } - if pippf.PublicIPAddresses != nil { - objectMap["publicIPAddresses"] = pippf.PublicIPAddresses - } - if pippf.ResourceGUID != nil { - objectMap["resourceGuid"] = pippf.ResourceGUID - } - if pippf.ProvisioningState != nil { - objectMap["provisioningState"] = pippf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// PublicIPPrefixSku SKU of a public IP prefix -type PublicIPPrefixSku struct { - // Name - Name of a public IP prefix SKU. Possible values include: 'Standard' - Name PublicIPPrefixSkuName `json:"name,omitempty"` -} - -// QueryTroubleshootingParameters parameters that define the resource to query the troubleshooting result. -type QueryTroubleshootingParameters struct { - // TargetResourceID - The target resource ID to query the troubleshooting result. - TargetResourceID *string `json:"targetResourceId,omitempty"` -} - -// ReferencedPublicIPAddress ... -type ReferencedPublicIPAddress struct { - // ID - The PublicIPAddress Reference - ID *string `json:"id,omitempty"` -} - -// Resource common resource representation. -type Resource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.ID != nil { - objectMap["id"] = r.ID - } - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// ResourceNavigationLink resourceNavigationLink resource. -type ResourceNavigationLink struct { - // ResourceNavigationLinkFormat - Resource navigation link properties format. - *ResourceNavigationLinkFormat `json:"properties,omitempty"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceNavigationLink. -func (rnl ResourceNavigationLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rnl.ResourceNavigationLinkFormat != nil { - objectMap["properties"] = rnl.ResourceNavigationLinkFormat - } - if rnl.Name != nil { - objectMap["name"] = rnl.Name - } - if rnl.ID != nil { - objectMap["id"] = rnl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ResourceNavigationLink struct. -func (rnl *ResourceNavigationLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var resourceNavigationLinkFormat ResourceNavigationLinkFormat - err = json.Unmarshal(*v, &resourceNavigationLinkFormat) - if err != nil { - return err - } - rnl.ResourceNavigationLinkFormat = &resourceNavigationLinkFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rnl.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rnl.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rnl.ID = &ID - } - } - } - - return nil -} - -// ResourceNavigationLinkFormat properties of ResourceNavigationLink. -type ResourceNavigationLinkFormat struct { - // LinkedResourceType - Resource type of the linked resource. - LinkedResourceType *string `json:"linkedResourceType,omitempty"` - // Link - Link to the external resource - Link *string `json:"link,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the ResourceNavigationLink resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceNavigationLinkFormat. -func (rnlf ResourceNavigationLinkFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rnlf.LinkedResourceType != nil { - objectMap["linkedResourceType"] = rnlf.LinkedResourceType - } - if rnlf.Link != nil { - objectMap["link"] = rnlf.Link - } - return json.Marshal(objectMap) -} - -// RetentionPolicyParameters parameters that define the retention policy for flow log. -type RetentionPolicyParameters struct { - // Days - Number of days to retain flow log records. - Days *int32 `json:"days,omitempty"` - // Enabled - Flag to enable/disable retention. - Enabled *bool `json:"enabled,omitempty"` -} - -// Route route resource -type Route struct { - autorest.Response `json:"-"` - // RoutePropertiesFormat - Properties of the route. - *RoutePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Route. -func (r Route) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.RoutePropertiesFormat != nil { - objectMap["properties"] = r.RoutePropertiesFormat - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Etag != nil { - objectMap["etag"] = r.Etag - } - if r.ID != nil { - objectMap["id"] = r.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Route struct. -func (r *Route) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routePropertiesFormat RoutePropertiesFormat - err = json.Unmarshal(*v, &routePropertiesFormat) - if err != nil { - return err - } - r.RoutePropertiesFormat = &routePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - r.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - r.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - r.ID = &ID - } - } - } - - return nil -} - -// RouteFilter route Filter Resource. -type RouteFilter struct { - autorest.Response `json:"-"` - *RouteFilterPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for RouteFilter. -func (rf RouteFilter) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rf.RouteFilterPropertiesFormat != nil { - objectMap["properties"] = rf.RouteFilterPropertiesFormat - } - if rf.ID != nil { - objectMap["id"] = rf.ID - } - if rf.Location != nil { - objectMap["location"] = rf.Location - } - if rf.Tags != nil { - objectMap["tags"] = rf.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RouteFilter struct. -func (rf *RouteFilter) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterPropertiesFormat RouteFilterPropertiesFormat - err = json.Unmarshal(*v, &routeFilterPropertiesFormat) - if err != nil { - return err - } - rf.RouteFilterPropertiesFormat = &routeFilterPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rf.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rf.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rf.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rf.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rf.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - rf.Tags = tags - } - } - } - - return nil -} - -// RouteFilterListResult response for the ListRouteFilters API service call. -type RouteFilterListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of route filters in a resource group. - Value *[]RouteFilter `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteFilterListResultIterator provides access to a complete listing of RouteFilter values. -type RouteFilterListResultIterator struct { - i int - page RouteFilterListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteFilterListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteFilterListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteFilterListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteFilterListResultIterator) Response() RouteFilterListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteFilterListResultIterator) Value() RouteFilter { - if !iter.page.NotDone() { - return RouteFilter{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteFilterListResultIterator type. -func NewRouteFilterListResultIterator(page RouteFilterListResultPage) RouteFilterListResultIterator { - return RouteFilterListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rflr RouteFilterListResult) IsEmpty() bool { - return rflr.Value == nil || len(*rflr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rflr RouteFilterListResult) hasNextLink() bool { - return rflr.NextLink != nil && len(*rflr.NextLink) != 0 -} - -// routeFilterListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rflr RouteFilterListResult) routeFilterListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rflr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rflr.NextLink))) -} - -// RouteFilterListResultPage contains a page of RouteFilter values. -type RouteFilterListResultPage struct { - fn func(context.Context, RouteFilterListResult) (RouteFilterListResult, error) - rflr RouteFilterListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteFilterListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rflr) - if err != nil { - return err - } - page.rflr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteFilterListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteFilterListResultPage) NotDone() bool { - return !page.rflr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteFilterListResultPage) Response() RouteFilterListResult { - return page.rflr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteFilterListResultPage) Values() []RouteFilter { - if page.rflr.IsEmpty() { - return nil - } - return *page.rflr.Value -} - -// Creates a new instance of the RouteFilterListResultPage type. -func NewRouteFilterListResultPage(cur RouteFilterListResult, getNextPage func(context.Context, RouteFilterListResult) (RouteFilterListResult, error)) RouteFilterListResultPage { - return RouteFilterListResultPage{ - fn: getNextPage, - rflr: cur, - } -} - -// RouteFilterPropertiesFormat route Filter Resource -type RouteFilterPropertiesFormat struct { - // Rules - Collection of RouteFilterRules contained within a route filter. - Rules *[]RouteFilterRule `json:"rules,omitempty"` - // Peerings - A collection of references to express route circuit peerings. - Peerings *[]ExpressRouteCircuitPeering `json:"peerings,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteFilterPropertiesFormat. -func (rfpf RouteFilterPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rfpf.Rules != nil { - objectMap["rules"] = rfpf.Rules - } - if rfpf.Peerings != nil { - objectMap["peerings"] = rfpf.Peerings - } - return json.Marshal(objectMap) -} - -// RouteFilterRule route Filter Rule Resource -type RouteFilterRule struct { - autorest.Response `json:"-"` - *RouteFilterRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteFilterRule. -func (rfr RouteFilterRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rfr.RouteFilterRulePropertiesFormat != nil { - objectMap["properties"] = rfr.RouteFilterRulePropertiesFormat - } - if rfr.Name != nil { - objectMap["name"] = rfr.Name - } - if rfr.Location != nil { - objectMap["location"] = rfr.Location - } - if rfr.ID != nil { - objectMap["id"] = rfr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RouteFilterRule struct. -func (rfr *RouteFilterRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterRulePropertiesFormat RouteFilterRulePropertiesFormat - err = json.Unmarshal(*v, &routeFilterRulePropertiesFormat) - if err != nil { - return err - } - rfr.RouteFilterRulePropertiesFormat = &routeFilterRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rfr.Name = &name - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rfr.Location = &location - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rfr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rfr.ID = &ID - } - } - } - - return nil -} - -// RouteFilterRuleListResult response for the ListRouteFilterRules API service call -type RouteFilterRuleListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of RouteFilterRules in a resource group. - Value *[]RouteFilterRule `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteFilterRuleListResultIterator provides access to a complete listing of RouteFilterRule values. -type RouteFilterRuleListResultIterator struct { - i int - page RouteFilterRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteFilterRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteFilterRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteFilterRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteFilterRuleListResultIterator) Response() RouteFilterRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteFilterRuleListResultIterator) Value() RouteFilterRule { - if !iter.page.NotDone() { - return RouteFilterRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteFilterRuleListResultIterator type. -func NewRouteFilterRuleListResultIterator(page RouteFilterRuleListResultPage) RouteFilterRuleListResultIterator { - return RouteFilterRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rfrlr RouteFilterRuleListResult) IsEmpty() bool { - return rfrlr.Value == nil || len(*rfrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rfrlr RouteFilterRuleListResult) hasNextLink() bool { - return rfrlr.NextLink != nil && len(*rfrlr.NextLink) != 0 -} - -// routeFilterRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rfrlr RouteFilterRuleListResult) routeFilterRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rfrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rfrlr.NextLink))) -} - -// RouteFilterRuleListResultPage contains a page of RouteFilterRule values. -type RouteFilterRuleListResultPage struct { - fn func(context.Context, RouteFilterRuleListResult) (RouteFilterRuleListResult, error) - rfrlr RouteFilterRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteFilterRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rfrlr) - if err != nil { - return err - } - page.rfrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteFilterRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteFilterRuleListResultPage) NotDone() bool { - return !page.rfrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteFilterRuleListResultPage) Response() RouteFilterRuleListResult { - return page.rfrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteFilterRuleListResultPage) Values() []RouteFilterRule { - if page.rfrlr.IsEmpty() { - return nil - } - return *page.rfrlr.Value -} - -// Creates a new instance of the RouteFilterRuleListResultPage type. -func NewRouteFilterRuleListResultPage(cur RouteFilterRuleListResult, getNextPage func(context.Context, RouteFilterRuleListResult) (RouteFilterRuleListResult, error)) RouteFilterRuleListResultPage { - return RouteFilterRuleListResultPage{ - fn: getNextPage, - rfrlr: cur, - } -} - -// RouteFilterRulePropertiesFormat route Filter Rule Resource -type RouteFilterRulePropertiesFormat struct { - // Access - The access type of the rule. Valid values are: 'Allow', 'Deny'. Possible values include: 'Allow', 'Deny' - Access Access `json:"access,omitempty"` - // RouteFilterRuleType - The rule type of the rule. Valid value is: 'Community' - RouteFilterRuleType *string `json:"routeFilterRuleType,omitempty"` - // Communities - The collection for bgp community values to filter on. e.g. ['12076:5010','12076:5020'] - Communities *[]string `json:"communities,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteFilterRulePropertiesFormat. -func (rfrpf RouteFilterRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rfrpf.Access != "" { - objectMap["access"] = rfrpf.Access - } - if rfrpf.RouteFilterRuleType != nil { - objectMap["routeFilterRuleType"] = rfrpf.RouteFilterRuleType - } - if rfrpf.Communities != nil { - objectMap["communities"] = rfrpf.Communities - } - return json.Marshal(objectMap) -} - -// RouteFilterRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RouteFilterRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFilterRulesClient) (RouteFilterRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFilterRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFilterRulesCreateOrUpdateFuture.Result. -func (future *RouteFilterRulesCreateOrUpdateFuture) result(client RouteFilterRulesClient) (rfr RouteFilterRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rfr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFilterRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rfr.Response.Response, err = future.GetResult(sender); err == nil && rfr.Response.Response.StatusCode != http.StatusNoContent { - rfr, err = client.CreateOrUpdateResponder(rfr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesCreateOrUpdateFuture", "Result", rfr.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteFilterRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteFilterRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFilterRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFilterRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFilterRulesDeleteFuture.Result. -func (future *RouteFilterRulesDeleteFuture) result(client RouteFilterRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFilterRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RouteFilterRulesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteFilterRulesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFilterRulesClient) (RouteFilterRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFilterRulesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFilterRulesUpdateFuture.Result. -func (future *RouteFilterRulesUpdateFuture) result(client RouteFilterRulesClient) (rfr RouteFilterRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rfr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFilterRulesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rfr.Response.Response, err = future.GetResult(sender); err == nil && rfr.Response.Response.StatusCode != http.StatusNoContent { - rfr, err = client.UpdateResponder(rfr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesUpdateFuture", "Result", rfr.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteFiltersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RouteFiltersCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFiltersClient) (RouteFilter, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFiltersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFiltersCreateOrUpdateFuture.Result. -func (future *RouteFiltersCreateOrUpdateFuture) result(client RouteFiltersClient) (rf RouteFilter, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rf.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFiltersCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rf.Response.Response, err = future.GetResult(sender); err == nil && rf.Response.Response.StatusCode != http.StatusNoContent { - rf, err = client.CreateOrUpdateResponder(rf.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersCreateOrUpdateFuture", "Result", rf.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteFiltersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteFiltersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFiltersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFiltersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFiltersDeleteFuture.Result. -func (future *RouteFiltersDeleteFuture) result(client RouteFiltersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFiltersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RouteFiltersUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteFiltersUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFiltersClient) (RouteFilter, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFiltersUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFiltersUpdateFuture.Result. -func (future *RouteFiltersUpdateFuture) result(client RouteFiltersClient) (rf RouteFilter, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rf.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFiltersUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rf.Response.Response, err = future.GetResult(sender); err == nil && rf.Response.Response.StatusCode != http.StatusNoContent { - rf, err = client.UpdateResponder(rf.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersUpdateFuture", "Result", rf.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteListResult response for the ListRoute API service call -type RouteListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of routes in a resource group. - Value *[]Route `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteListResultIterator provides access to a complete listing of Route values. -type RouteListResultIterator struct { - i int - page RouteListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteListResultIterator) Response() RouteListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteListResultIterator) Value() Route { - if !iter.page.NotDone() { - return Route{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteListResultIterator type. -func NewRouteListResultIterator(page RouteListResultPage) RouteListResultIterator { - return RouteListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rlr RouteListResult) IsEmpty() bool { - return rlr.Value == nil || len(*rlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rlr RouteListResult) hasNextLink() bool { - return rlr.NextLink != nil && len(*rlr.NextLink) != 0 -} - -// routeListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rlr RouteListResult) routeListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rlr.NextLink))) -} - -// RouteListResultPage contains a page of Route values. -type RouteListResultPage struct { - fn func(context.Context, RouteListResult) (RouteListResult, error) - rlr RouteListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rlr) - if err != nil { - return err - } - page.rlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteListResultPage) NotDone() bool { - return !page.rlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteListResultPage) Response() RouteListResult { - return page.rlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteListResultPage) Values() []Route { - if page.rlr.IsEmpty() { - return nil - } - return *page.rlr.Value -} - -// Creates a new instance of the RouteListResultPage type. -func NewRouteListResultPage(cur RouteListResult, getNextPage func(context.Context, RouteListResult) (RouteListResult, error)) RouteListResultPage { - return RouteListResultPage{ - fn: getNextPage, - rlr: cur, - } -} - -// RoutePropertiesFormat route resource -type RoutePropertiesFormat struct { - // AddressPrefix - The destination CIDR to which the route applies. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // NextHopType - The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. Possible values include: 'RouteNextHopTypeVirtualNetworkGateway', 'RouteNextHopTypeVnetLocal', 'RouteNextHopTypeInternet', 'RouteNextHopTypeVirtualAppliance', 'RouteNextHopTypeNone' - NextHopType RouteNextHopType `json:"nextHopType,omitempty"` - // NextHopIPAddress - The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. - NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// RoutesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RoutesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RoutesClient) (Route, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RoutesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RoutesCreateOrUpdateFuture.Result. -func (future *RoutesCreateOrUpdateFuture) result(client RoutesClient) (r Route, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - r.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RoutesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if r.Response.Response, err = future.GetResult(sender); err == nil && r.Response.Response.StatusCode != http.StatusNoContent { - r, err = client.CreateOrUpdateResponder(r.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesCreateOrUpdateFuture", "Result", r.Response.Response, "Failure responding to request") - } - } - return -} - -// RoutesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type RoutesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RoutesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RoutesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RoutesDeleteFuture.Result. -func (future *RoutesDeleteFuture) result(client RoutesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RoutesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RouteTable route table resource. -type RouteTable struct { - autorest.Response `json:"-"` - // RouteTablePropertiesFormat - Properties of the route table. - *RouteTablePropertiesFormat `json:"properties,omitempty"` - // Etag - Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for RouteTable. -func (rt RouteTable) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rt.RouteTablePropertiesFormat != nil { - objectMap["properties"] = rt.RouteTablePropertiesFormat - } - if rt.Etag != nil { - objectMap["etag"] = rt.Etag - } - if rt.ID != nil { - objectMap["id"] = rt.ID - } - if rt.Location != nil { - objectMap["location"] = rt.Location - } - if rt.Tags != nil { - objectMap["tags"] = rt.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RouteTable struct. -func (rt *RouteTable) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeTablePropertiesFormat RouteTablePropertiesFormat - err = json.Unmarshal(*v, &routeTablePropertiesFormat) - if err != nil { - return err - } - rt.RouteTablePropertiesFormat = &routeTablePropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rt.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rt.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rt.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rt.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rt.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - rt.Tags = tags - } - } - } - - return nil -} - -// RouteTableListResult response for the ListRouteTable API service call. -type RouteTableListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of route tables in a resource group. - Value *[]RouteTable `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteTableListResultIterator provides access to a complete listing of RouteTable values. -type RouteTableListResultIterator struct { - i int - page RouteTableListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteTableListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTableListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteTableListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteTableListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteTableListResultIterator) Response() RouteTableListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteTableListResultIterator) Value() RouteTable { - if !iter.page.NotDone() { - return RouteTable{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteTableListResultIterator type. -func NewRouteTableListResultIterator(page RouteTableListResultPage) RouteTableListResultIterator { - return RouteTableListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rtlr RouteTableListResult) IsEmpty() bool { - return rtlr.Value == nil || len(*rtlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rtlr RouteTableListResult) hasNextLink() bool { - return rtlr.NextLink != nil && len(*rtlr.NextLink) != 0 -} - -// routeTableListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rtlr RouteTableListResult) routeTableListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rtlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rtlr.NextLink))) -} - -// RouteTableListResultPage contains a page of RouteTable values. -type RouteTableListResultPage struct { - fn func(context.Context, RouteTableListResult) (RouteTableListResult, error) - rtlr RouteTableListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteTableListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTableListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rtlr) - if err != nil { - return err - } - page.rtlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteTableListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteTableListResultPage) NotDone() bool { - return !page.rtlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteTableListResultPage) Response() RouteTableListResult { - return page.rtlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteTableListResultPage) Values() []RouteTable { - if page.rtlr.IsEmpty() { - return nil - } - return *page.rtlr.Value -} - -// Creates a new instance of the RouteTableListResultPage type. -func NewRouteTableListResultPage(cur RouteTableListResult, getNextPage func(context.Context, RouteTableListResult) (RouteTableListResult, error)) RouteTableListResultPage { - return RouteTableListResultPage{ - fn: getNextPage, - rtlr: cur, - } -} - -// RouteTablePropertiesFormat route Table resource -type RouteTablePropertiesFormat struct { - // Routes - Collection of routes contained within a route table. - Routes *[]Route `json:"routes,omitempty"` - // Subnets - READ-ONLY; A collection of references to subnets. - Subnets *[]Subnet `json:"subnets,omitempty"` - // DisableBgpRoutePropagation - Gets or sets whether to disable the routes learned by BGP on that route table. True means disable. - DisableBgpRoutePropagation *bool `json:"disableBgpRoutePropagation,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteTablePropertiesFormat. -func (rtpf RouteTablePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rtpf.Routes != nil { - objectMap["routes"] = rtpf.Routes - } - if rtpf.DisableBgpRoutePropagation != nil { - objectMap["disableBgpRoutePropagation"] = rtpf.DisableBgpRoutePropagation - } - if rtpf.ProvisioningState != nil { - objectMap["provisioningState"] = rtpf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// RouteTablesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RouteTablesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteTablesClient) (RouteTable, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteTablesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteTablesCreateOrUpdateFuture.Result. -func (future *RouteTablesCreateOrUpdateFuture) result(client RouteTablesClient) (rt RouteTable, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rt.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteTablesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rt.Response.Response, err = future.GetResult(sender); err == nil && rt.Response.Response.StatusCode != http.StatusNoContent { - rt, err = client.CreateOrUpdateResponder(rt.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesCreateOrUpdateFuture", "Result", rt.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteTablesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteTablesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteTablesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteTablesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteTablesDeleteFuture.Result. -func (future *RouteTablesDeleteFuture) result(client RouteTablesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteTablesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RouteTablesUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteTablesUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteTablesClient) (RouteTable, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteTablesUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteTablesUpdateTagsFuture.Result. -func (future *RouteTablesUpdateTagsFuture) result(client RouteTablesClient) (rt RouteTable, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rt.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteTablesUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rt.Response.Response, err = future.GetResult(sender); err == nil && rt.Response.Response.StatusCode != http.StatusNoContent { - rt, err = client.UpdateTagsResponder(rt.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesUpdateTagsFuture", "Result", rt.Response.Response, "Failure responding to request") - } - } - return -} - -// SecurityGroup networkSecurityGroup resource. -type SecurityGroup struct { - autorest.Response `json:"-"` - // SecurityGroupPropertiesFormat - Properties of the network security group - *SecurityGroupPropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SecurityGroup. -func (sg SecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sg.SecurityGroupPropertiesFormat != nil { - objectMap["properties"] = sg.SecurityGroupPropertiesFormat - } - if sg.Etag != nil { - objectMap["etag"] = sg.Etag - } - if sg.ID != nil { - objectMap["id"] = sg.ID - } - if sg.Location != nil { - objectMap["location"] = sg.Location - } - if sg.Tags != nil { - objectMap["tags"] = sg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SecurityGroup struct. -func (sg *SecurityGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var securityGroupPropertiesFormat SecurityGroupPropertiesFormat - err = json.Unmarshal(*v, &securityGroupPropertiesFormat) - if err != nil { - return err - } - sg.SecurityGroupPropertiesFormat = &securityGroupPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - sg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - sg.Tags = tags - } - } - } - - return nil -} - -// SecurityGroupListResult response for ListNetworkSecurityGroups API service call. -type SecurityGroupListResult struct { - autorest.Response `json:"-"` - // Value - A list of NetworkSecurityGroup resources. - Value *[]SecurityGroup `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SecurityGroupListResultIterator provides access to a complete listing of SecurityGroup values. -type SecurityGroupListResultIterator struct { - i int - page SecurityGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SecurityGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SecurityGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SecurityGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SecurityGroupListResultIterator) Response() SecurityGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SecurityGroupListResultIterator) Value() SecurityGroup { - if !iter.page.NotDone() { - return SecurityGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SecurityGroupListResultIterator type. -func NewSecurityGroupListResultIterator(page SecurityGroupListResultPage) SecurityGroupListResultIterator { - return SecurityGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sglr SecurityGroupListResult) IsEmpty() bool { - return sglr.Value == nil || len(*sglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sglr SecurityGroupListResult) hasNextLink() bool { - return sglr.NextLink != nil && len(*sglr.NextLink) != 0 -} - -// securityGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sglr SecurityGroupListResult) securityGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sglr.NextLink))) -} - -// SecurityGroupListResultPage contains a page of SecurityGroup values. -type SecurityGroupListResultPage struct { - fn func(context.Context, SecurityGroupListResult) (SecurityGroupListResult, error) - sglr SecurityGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SecurityGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sglr) - if err != nil { - return err - } - page.sglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SecurityGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SecurityGroupListResultPage) NotDone() bool { - return !page.sglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SecurityGroupListResultPage) Response() SecurityGroupListResult { - return page.sglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SecurityGroupListResultPage) Values() []SecurityGroup { - if page.sglr.IsEmpty() { - return nil - } - return *page.sglr.Value -} - -// Creates a new instance of the SecurityGroupListResultPage type. -func NewSecurityGroupListResultPage(cur SecurityGroupListResult, getNextPage func(context.Context, SecurityGroupListResult) (SecurityGroupListResult, error)) SecurityGroupListResultPage { - return SecurityGroupListResultPage{ - fn: getNextPage, - sglr: cur, - } -} - -// SecurityGroupNetworkInterface network interface and all its associated security rules. -type SecurityGroupNetworkInterface struct { - // ID - ID of the network interface. - ID *string `json:"id,omitempty"` - SecurityRuleAssociations *SecurityRuleAssociations `json:"securityRuleAssociations,omitempty"` -} - -// SecurityGroupPropertiesFormat network Security Group resource. -type SecurityGroupPropertiesFormat struct { - // SecurityRules - A collection of security rules of the network security group. - SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` - // DefaultSecurityRules - The default security rules of network security group. - DefaultSecurityRules *[]SecurityRule `json:"defaultSecurityRules,omitempty"` - // NetworkInterfaces - READ-ONLY; A collection of references to network interfaces. - NetworkInterfaces *[]Interface `json:"networkInterfaces,omitempty"` - // Subnets - READ-ONLY; A collection of references to subnets. - Subnets *[]Subnet `json:"subnets,omitempty"` - // ResourceGUID - The resource GUID property of the network security group resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityGroupPropertiesFormat. -func (sgpf SecurityGroupPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sgpf.SecurityRules != nil { - objectMap["securityRules"] = sgpf.SecurityRules - } - if sgpf.DefaultSecurityRules != nil { - objectMap["defaultSecurityRules"] = sgpf.DefaultSecurityRules - } - if sgpf.ResourceGUID != nil { - objectMap["resourceGuid"] = sgpf.ResourceGUID - } - if sgpf.ProvisioningState != nil { - objectMap["provisioningState"] = sgpf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// SecurityGroupResult network configuration diagnostic result corresponded provided traffic query. -type SecurityGroupResult struct { - // SecurityRuleAccessResult - The network traffic is allowed or denied. Possible values are 'Allow' and 'Deny'. Possible values include: 'SecurityRuleAccessAllow', 'SecurityRuleAccessDeny' - SecurityRuleAccessResult SecurityRuleAccess `json:"securityRuleAccessResult,omitempty"` - // EvaluatedNetworkSecurityGroups - READ-ONLY; List of results network security groups diagnostic. - EvaluatedNetworkSecurityGroups *[]EvaluatedNetworkSecurityGroup `json:"evaluatedNetworkSecurityGroups,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityGroupResult. -func (sgr SecurityGroupResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sgr.SecurityRuleAccessResult != "" { - objectMap["securityRuleAccessResult"] = sgr.SecurityRuleAccessResult - } - return json.Marshal(objectMap) -} - -// SecurityGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SecurityGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityGroupsClient) (SecurityGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityGroupsCreateOrUpdateFuture.Result. -func (future *SecurityGroupsCreateOrUpdateFuture) result(client SecurityGroupsClient) (sg SecurityGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sg.Response.Response, err = future.GetResult(sender); err == nil && sg.Response.Response.StatusCode != http.StatusNoContent { - sg, err = client.CreateOrUpdateResponder(sg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsCreateOrUpdateFuture", "Result", sg.Response.Response, "Failure responding to request") - } - } - return -} - -// SecurityGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SecurityGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityGroupsDeleteFuture.Result. -func (future *SecurityGroupsDeleteFuture) result(client SecurityGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SecurityGroupsUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SecurityGroupsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityGroupsClient) (SecurityGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityGroupsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityGroupsUpdateTagsFuture.Result. -func (future *SecurityGroupsUpdateTagsFuture) result(client SecurityGroupsClient) (sg SecurityGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityGroupsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sg.Response.Response, err = future.GetResult(sender); err == nil && sg.Response.Response.StatusCode != http.StatusNoContent { - sg, err = client.UpdateTagsResponder(sg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsUpdateTagsFuture", "Result", sg.Response.Response, "Failure responding to request") - } - } - return -} - -// SecurityGroupViewParameters parameters that define the VM to check security groups for. -type SecurityGroupViewParameters struct { - // TargetResourceID - ID of the target VM. - TargetResourceID *string `json:"targetResourceId,omitempty"` -} - -// SecurityGroupViewResult the information about security rules applied to the specified VM. -type SecurityGroupViewResult struct { - autorest.Response `json:"-"` - // NetworkInterfaces - List of network interfaces on the specified VM. - NetworkInterfaces *[]SecurityGroupNetworkInterface `json:"networkInterfaces,omitempty"` -} - -// SecurityRule network security rule. -type SecurityRule struct { - autorest.Response `json:"-"` - // SecurityRulePropertiesFormat - Properties of the security rule - *SecurityRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityRule. -func (sr SecurityRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sr.SecurityRulePropertiesFormat != nil { - objectMap["properties"] = sr.SecurityRulePropertiesFormat - } - if sr.Name != nil { - objectMap["name"] = sr.Name - } - if sr.Etag != nil { - objectMap["etag"] = sr.Etag - } - if sr.ID != nil { - objectMap["id"] = sr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SecurityRule struct. -func (sr *SecurityRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var securityRulePropertiesFormat SecurityRulePropertiesFormat - err = json.Unmarshal(*v, &securityRulePropertiesFormat) - if err != nil { - return err - } - sr.SecurityRulePropertiesFormat = &securityRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sr.ID = &ID - } - } - } - - return nil -} - -// SecurityRuleAssociations all security rules associated with the network interface. -type SecurityRuleAssociations struct { - NetworkInterfaceAssociation *InterfaceAssociation `json:"networkInterfaceAssociation,omitempty"` - SubnetAssociation *SubnetAssociation `json:"subnetAssociation,omitempty"` - // DefaultSecurityRules - Collection of default security rules of the network security group. - DefaultSecurityRules *[]SecurityRule `json:"defaultSecurityRules,omitempty"` - // EffectiveSecurityRules - Collection of effective security rules. - EffectiveSecurityRules *[]EffectiveNetworkSecurityRule `json:"effectiveSecurityRules,omitempty"` -} - -// SecurityRuleListResult response for ListSecurityRule API service call. Retrieves all security rules that -// belongs to a network security group. -type SecurityRuleListResult struct { - autorest.Response `json:"-"` - // Value - The security rules in a network security group. - Value *[]SecurityRule `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SecurityRuleListResultIterator provides access to a complete listing of SecurityRule values. -type SecurityRuleListResultIterator struct { - i int - page SecurityRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SecurityRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SecurityRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SecurityRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SecurityRuleListResultIterator) Response() SecurityRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SecurityRuleListResultIterator) Value() SecurityRule { - if !iter.page.NotDone() { - return SecurityRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SecurityRuleListResultIterator type. -func NewSecurityRuleListResultIterator(page SecurityRuleListResultPage) SecurityRuleListResultIterator { - return SecurityRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (srlr SecurityRuleListResult) IsEmpty() bool { - return srlr.Value == nil || len(*srlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (srlr SecurityRuleListResult) hasNextLink() bool { - return srlr.NextLink != nil && len(*srlr.NextLink) != 0 -} - -// securityRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (srlr SecurityRuleListResult) securityRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !srlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(srlr.NextLink))) -} - -// SecurityRuleListResultPage contains a page of SecurityRule values. -type SecurityRuleListResultPage struct { - fn func(context.Context, SecurityRuleListResult) (SecurityRuleListResult, error) - srlr SecurityRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SecurityRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.srlr) - if err != nil { - return err - } - page.srlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SecurityRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SecurityRuleListResultPage) NotDone() bool { - return !page.srlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SecurityRuleListResultPage) Response() SecurityRuleListResult { - return page.srlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SecurityRuleListResultPage) Values() []SecurityRule { - if page.srlr.IsEmpty() { - return nil - } - return *page.srlr.Value -} - -// Creates a new instance of the SecurityRuleListResultPage type. -func NewSecurityRuleListResultPage(cur SecurityRuleListResult, getNextPage func(context.Context, SecurityRuleListResult) (SecurityRuleListResult, error)) SecurityRuleListResultPage { - return SecurityRuleListResultPage{ - fn: getNextPage, - srlr: cur, - } -} - -// SecurityRulePropertiesFormat security rule resource. -type SecurityRulePropertiesFormat struct { - // Description - A description for this rule. Restricted to 140 chars. - Description *string `json:"description,omitempty"` - // Protocol - Network protocol this rule applies to. Possible values are 'Tcp', 'Udp', and '*'. Possible values include: 'SecurityRuleProtocolTCP', 'SecurityRuleProtocolUDP', 'SecurityRuleProtocolAsterisk' - Protocol SecurityRuleProtocol `json:"protocol,omitempty"` - // SourcePortRange - The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. - SourcePortRange *string `json:"sourcePortRange,omitempty"` - // DestinationPortRange - The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. - DestinationPortRange *string `json:"destinationPortRange,omitempty"` - // SourceAddressPrefix - The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. - SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` - // SourceAddressPrefixes - The CIDR or source IP ranges. - SourceAddressPrefixes *[]string `json:"sourceAddressPrefixes,omitempty"` - // SourceApplicationSecurityGroups - The application security group specified as source. - SourceApplicationSecurityGroups *[]ApplicationSecurityGroup `json:"sourceApplicationSecurityGroups,omitempty"` - // DestinationAddressPrefix - The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. - DestinationAddressPrefix *string `json:"destinationAddressPrefix,omitempty"` - // DestinationAddressPrefixes - The destination address prefixes. CIDR or destination IP ranges. - DestinationAddressPrefixes *[]string `json:"destinationAddressPrefixes,omitempty"` - // DestinationApplicationSecurityGroups - The application security group specified as destination. - DestinationApplicationSecurityGroups *[]ApplicationSecurityGroup `json:"destinationApplicationSecurityGroups,omitempty"` - // SourcePortRanges - The source port ranges. - SourcePortRanges *[]string `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - The destination port ranges. - DestinationPortRanges *[]string `json:"destinationPortRanges,omitempty"` - // Access - The network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'. Possible values include: 'SecurityRuleAccessAllow', 'SecurityRuleAccessDeny' - Access SecurityRuleAccess `json:"access,omitempty"` - // Priority - The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. - Priority *int32 `json:"priority,omitempty"` - // Direction - The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values are: 'Inbound' and 'Outbound'. Possible values include: 'SecurityRuleDirectionInbound', 'SecurityRuleDirectionOutbound' - Direction SecurityRuleDirection `json:"direction,omitempty"` - // ProvisioningState - The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// SecurityRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SecurityRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityRulesClient) (SecurityRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityRulesCreateOrUpdateFuture.Result. -func (future *SecurityRulesCreateOrUpdateFuture) result(client SecurityRulesClient) (sr SecurityRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { - sr, err = client.CreateOrUpdateResponder(sr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesCreateOrUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") - } - } - return -} - -// SecurityRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SecurityRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityRulesDeleteFuture.Result. -func (future *SecurityRulesDeleteFuture) result(client SecurityRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SecurityRulesEvaluationResult network security rules evaluation result. -type SecurityRulesEvaluationResult struct { - // Name - Name of the network security rule. - Name *string `json:"name,omitempty"` - // ProtocolMatched - Value indicating whether protocol is matched. - ProtocolMatched *bool `json:"protocolMatched,omitempty"` - // SourceMatched - Value indicating whether source is matched. - SourceMatched *bool `json:"sourceMatched,omitempty"` - // SourcePortMatched - Value indicating whether source port is matched. - SourcePortMatched *bool `json:"sourcePortMatched,omitempty"` - // DestinationMatched - Value indicating whether destination is matched. - DestinationMatched *bool `json:"destinationMatched,omitempty"` - // DestinationPortMatched - Value indicating whether destination port is matched. - DestinationPortMatched *bool `json:"destinationPortMatched,omitempty"` -} - -// ServiceAssociationLink serviceAssociationLink resource. -type ServiceAssociationLink struct { - // ServiceAssociationLinkPropertiesFormat - Resource navigation link properties format. - *ServiceAssociationLinkPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceAssociationLink. -func (sal ServiceAssociationLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sal.ServiceAssociationLinkPropertiesFormat != nil { - objectMap["properties"] = sal.ServiceAssociationLinkPropertiesFormat - } - if sal.Name != nil { - objectMap["name"] = sal.Name - } - if sal.ID != nil { - objectMap["id"] = sal.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ServiceAssociationLink struct. -func (sal *ServiceAssociationLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceAssociationLinkPropertiesFormat ServiceAssociationLinkPropertiesFormat - err = json.Unmarshal(*v, &serviceAssociationLinkPropertiesFormat) - if err != nil { - return err - } - sal.ServiceAssociationLinkPropertiesFormat = &serviceAssociationLinkPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sal.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sal.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sal.ID = &ID - } - } - } - - return nil -} - -// ServiceAssociationLinkPropertiesFormat properties of ServiceAssociationLink. -type ServiceAssociationLinkPropertiesFormat struct { - // LinkedResourceType - Resource type of the linked resource. - LinkedResourceType *string `json:"linkedResourceType,omitempty"` - // Link - Link to the external resource. - Link *string `json:"link,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the ServiceAssociationLink resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceAssociationLinkPropertiesFormat. -func (salpf ServiceAssociationLinkPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if salpf.LinkedResourceType != nil { - objectMap["linkedResourceType"] = salpf.LinkedResourceType - } - if salpf.Link != nil { - objectMap["link"] = salpf.Link - } - return json.Marshal(objectMap) -} - -// ServiceDelegationPropertiesFormat properties of a service delegation. -type ServiceDelegationPropertiesFormat struct { - // ServiceName - The name of the service to whom the subnet should be delegated (e.g. Microsoft.Sql/servers) - ServiceName *string `json:"serviceName,omitempty"` - // Actions - Describes the actions permitted to the service upon delegation - Actions *[]string `json:"actions,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceDelegationPropertiesFormat. -func (sdpf ServiceDelegationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sdpf.ServiceName != nil { - objectMap["serviceName"] = sdpf.ServiceName - } - if sdpf.Actions != nil { - objectMap["actions"] = sdpf.Actions - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ServiceEndpointPoliciesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPoliciesClient) (ServiceEndpointPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPoliciesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPoliciesCreateOrUpdateFuture.Result. -func (future *ServiceEndpointPoliciesCreateOrUpdateFuture) result(client ServiceEndpointPoliciesClient) (sep ServiceEndpointPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sep.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPoliciesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sep.Response.Response, err = future.GetResult(sender); err == nil && sep.Response.Response.StatusCode != http.StatusNoContent { - sep, err = client.CreateOrUpdateResponder(sep.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesCreateOrUpdateFuture", "Result", sep.Response.Response, "Failure responding to request") - } - } - return -} - -// ServiceEndpointPoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ServiceEndpointPoliciesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPoliciesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPoliciesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPoliciesDeleteFuture.Result. -func (future *ServiceEndpointPoliciesDeleteFuture) result(client ServiceEndpointPoliciesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPoliciesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ServiceEndpointPoliciesUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ServiceEndpointPoliciesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPoliciesClient) (ServiceEndpointPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPoliciesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPoliciesUpdateFuture.Result. -func (future *ServiceEndpointPoliciesUpdateFuture) result(client ServiceEndpointPoliciesClient) (sep ServiceEndpointPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sep.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPoliciesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sep.Response.Response, err = future.GetResult(sender); err == nil && sep.Response.Response.StatusCode != http.StatusNoContent { - sep, err = client.UpdateResponder(sep.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesUpdateFuture", "Result", sep.Response.Response, "Failure responding to request") - } - } - return -} - -// ServiceEndpointPolicy service End point policy resource. -type ServiceEndpointPolicy struct { - autorest.Response `json:"-"` - // ServiceEndpointPolicyPropertiesFormat - Properties of the service end point policy - *ServiceEndpointPolicyPropertiesFormat `json:"properties,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicy. -func (sep ServiceEndpointPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sep.ServiceEndpointPolicyPropertiesFormat != nil { - objectMap["properties"] = sep.ServiceEndpointPolicyPropertiesFormat - } - if sep.Etag != nil { - objectMap["etag"] = sep.Etag - } - if sep.ID != nil { - objectMap["id"] = sep.ID - } - if sep.Location != nil { - objectMap["location"] = sep.Location - } - if sep.Tags != nil { - objectMap["tags"] = sep.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ServiceEndpointPolicy struct. -func (sep *ServiceEndpointPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceEndpointPolicyPropertiesFormat ServiceEndpointPolicyPropertiesFormat - err = json.Unmarshal(*v, &serviceEndpointPolicyPropertiesFormat) - if err != nil { - return err - } - sep.ServiceEndpointPolicyPropertiesFormat = &serviceEndpointPolicyPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sep.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sep.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sep.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sep.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - sep.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - sep.Tags = tags - } - } - } - - return nil -} - -// ServiceEndpointPolicyDefinition service Endpoint policy definitions. -type ServiceEndpointPolicyDefinition struct { - autorest.Response `json:"-"` - // ServiceEndpointPolicyDefinitionPropertiesFormat - Properties of the service endpoint policy definition - *ServiceEndpointPolicyDefinitionPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyDefinition. -func (sepd ServiceEndpointPolicyDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sepd.ServiceEndpointPolicyDefinitionPropertiesFormat != nil { - objectMap["properties"] = sepd.ServiceEndpointPolicyDefinitionPropertiesFormat - } - if sepd.Name != nil { - objectMap["name"] = sepd.Name - } - if sepd.Etag != nil { - objectMap["etag"] = sepd.Etag - } - if sepd.ID != nil { - objectMap["id"] = sepd.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ServiceEndpointPolicyDefinition struct. -func (sepd *ServiceEndpointPolicyDefinition) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceEndpointPolicyDefinitionPropertiesFormat ServiceEndpointPolicyDefinitionPropertiesFormat - err = json.Unmarshal(*v, &serviceEndpointPolicyDefinitionPropertiesFormat) - if err != nil { - return err - } - sepd.ServiceEndpointPolicyDefinitionPropertiesFormat = &serviceEndpointPolicyDefinitionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sepd.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sepd.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sepd.ID = &ID - } - } - } - - return nil -} - -// ServiceEndpointPolicyDefinitionListResult response for ListServiceEndpointPolicyDefinition API service -// call. Retrieves all service endpoint policy definition that belongs to a service endpoint policy. -type ServiceEndpointPolicyDefinitionListResult struct { - autorest.Response `json:"-"` - // Value - The service endpoint policy definition in a service endpoint policy. - Value *[]ServiceEndpointPolicyDefinition `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ServiceEndpointPolicyDefinitionListResultIterator provides access to a complete listing of -// ServiceEndpointPolicyDefinition values. -type ServiceEndpointPolicyDefinitionListResultIterator struct { - i int - page ServiceEndpointPolicyDefinitionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ServiceEndpointPolicyDefinitionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ServiceEndpointPolicyDefinitionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ServiceEndpointPolicyDefinitionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ServiceEndpointPolicyDefinitionListResultIterator) Response() ServiceEndpointPolicyDefinitionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ServiceEndpointPolicyDefinitionListResultIterator) Value() ServiceEndpointPolicyDefinition { - if !iter.page.NotDone() { - return ServiceEndpointPolicyDefinition{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ServiceEndpointPolicyDefinitionListResultIterator type. -func NewServiceEndpointPolicyDefinitionListResultIterator(page ServiceEndpointPolicyDefinitionListResultPage) ServiceEndpointPolicyDefinitionListResultIterator { - return ServiceEndpointPolicyDefinitionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sepdlr ServiceEndpointPolicyDefinitionListResult) IsEmpty() bool { - return sepdlr.Value == nil || len(*sepdlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sepdlr ServiceEndpointPolicyDefinitionListResult) hasNextLink() bool { - return sepdlr.NextLink != nil && len(*sepdlr.NextLink) != 0 -} - -// serviceEndpointPolicyDefinitionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sepdlr ServiceEndpointPolicyDefinitionListResult) serviceEndpointPolicyDefinitionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sepdlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sepdlr.NextLink))) -} - -// ServiceEndpointPolicyDefinitionListResultPage contains a page of ServiceEndpointPolicyDefinition values. -type ServiceEndpointPolicyDefinitionListResultPage struct { - fn func(context.Context, ServiceEndpointPolicyDefinitionListResult) (ServiceEndpointPolicyDefinitionListResult, error) - sepdlr ServiceEndpointPolicyDefinitionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ServiceEndpointPolicyDefinitionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sepdlr) - if err != nil { - return err - } - page.sepdlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ServiceEndpointPolicyDefinitionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ServiceEndpointPolicyDefinitionListResultPage) NotDone() bool { - return !page.sepdlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ServiceEndpointPolicyDefinitionListResultPage) Response() ServiceEndpointPolicyDefinitionListResult { - return page.sepdlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ServiceEndpointPolicyDefinitionListResultPage) Values() []ServiceEndpointPolicyDefinition { - if page.sepdlr.IsEmpty() { - return nil - } - return *page.sepdlr.Value -} - -// Creates a new instance of the ServiceEndpointPolicyDefinitionListResultPage type. -func NewServiceEndpointPolicyDefinitionListResultPage(cur ServiceEndpointPolicyDefinitionListResult, getNextPage func(context.Context, ServiceEndpointPolicyDefinitionListResult) (ServiceEndpointPolicyDefinitionListResult, error)) ServiceEndpointPolicyDefinitionListResultPage { - return ServiceEndpointPolicyDefinitionListResultPage{ - fn: getNextPage, - sepdlr: cur, - } -} - -// ServiceEndpointPolicyDefinitionPropertiesFormat service Endpoint policy definition resource. -type ServiceEndpointPolicyDefinitionPropertiesFormat struct { - // Description - A description for this rule. Restricted to 140 chars. - Description *string `json:"description,omitempty"` - // Service - service endpoint name. - Service *string `json:"service,omitempty"` - // ServiceResources - A list of service resources. - ServiceResources *[]string `json:"serviceResources,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the service end point policy definition. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyDefinitionPropertiesFormat. -func (sepdpf ServiceEndpointPolicyDefinitionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sepdpf.Description != nil { - objectMap["description"] = sepdpf.Description - } - if sepdpf.Service != nil { - objectMap["service"] = sepdpf.Service - } - if sepdpf.ServiceResources != nil { - objectMap["serviceResources"] = sepdpf.ServiceResources - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPolicyDefinitionsClient) (ServiceEndpointPolicyDefinition, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture.Result. -func (future *ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture) result(client ServiceEndpointPolicyDefinitionsClient) (sepd ServiceEndpointPolicyDefinition, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sepd.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sepd.Response.Response, err = future.GetResult(sender); err == nil && sepd.Response.Response.StatusCode != http.StatusNoContent { - sepd, err = client.CreateOrUpdateResponder(sepd.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture", "Result", sepd.Response.Response, "Failure responding to request") - } - } - return -} - -// ServiceEndpointPolicyDefinitionsDeleteFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ServiceEndpointPolicyDefinitionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPolicyDefinitionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPolicyDefinitionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPolicyDefinitionsDeleteFuture.Result. -func (future *ServiceEndpointPolicyDefinitionsDeleteFuture) result(client ServiceEndpointPolicyDefinitionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPolicyDefinitionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ServiceEndpointPolicyListResult response for ListServiceEndpointPolicies API service call. -type ServiceEndpointPolicyListResult struct { - autorest.Response `json:"-"` - // Value - A list of ServiceEndpointPolicy resources. - Value *[]ServiceEndpointPolicy `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyListResult. -func (seplr ServiceEndpointPolicyListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if seplr.Value != nil { - objectMap["value"] = seplr.Value - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPolicyListResultIterator provides access to a complete listing of ServiceEndpointPolicy -// values. -type ServiceEndpointPolicyListResultIterator struct { - i int - page ServiceEndpointPolicyListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ServiceEndpointPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ServiceEndpointPolicyListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ServiceEndpointPolicyListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ServiceEndpointPolicyListResultIterator) Response() ServiceEndpointPolicyListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ServiceEndpointPolicyListResultIterator) Value() ServiceEndpointPolicy { - if !iter.page.NotDone() { - return ServiceEndpointPolicy{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ServiceEndpointPolicyListResultIterator type. -func NewServiceEndpointPolicyListResultIterator(page ServiceEndpointPolicyListResultPage) ServiceEndpointPolicyListResultIterator { - return ServiceEndpointPolicyListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (seplr ServiceEndpointPolicyListResult) IsEmpty() bool { - return seplr.Value == nil || len(*seplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (seplr ServiceEndpointPolicyListResult) hasNextLink() bool { - return seplr.NextLink != nil && len(*seplr.NextLink) != 0 -} - -// serviceEndpointPolicyListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (seplr ServiceEndpointPolicyListResult) serviceEndpointPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { - if !seplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(seplr.NextLink))) -} - -// ServiceEndpointPolicyListResultPage contains a page of ServiceEndpointPolicy values. -type ServiceEndpointPolicyListResultPage struct { - fn func(context.Context, ServiceEndpointPolicyListResult) (ServiceEndpointPolicyListResult, error) - seplr ServiceEndpointPolicyListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ServiceEndpointPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.seplr) - if err != nil { - return err - } - page.seplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ServiceEndpointPolicyListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ServiceEndpointPolicyListResultPage) NotDone() bool { - return !page.seplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ServiceEndpointPolicyListResultPage) Response() ServiceEndpointPolicyListResult { - return page.seplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ServiceEndpointPolicyListResultPage) Values() []ServiceEndpointPolicy { - if page.seplr.IsEmpty() { - return nil - } - return *page.seplr.Value -} - -// Creates a new instance of the ServiceEndpointPolicyListResultPage type. -func NewServiceEndpointPolicyListResultPage(cur ServiceEndpointPolicyListResult, getNextPage func(context.Context, ServiceEndpointPolicyListResult) (ServiceEndpointPolicyListResult, error)) ServiceEndpointPolicyListResultPage { - return ServiceEndpointPolicyListResultPage{ - fn: getNextPage, - seplr: cur, - } -} - -// ServiceEndpointPolicyPropertiesFormat service Endpoint Policy resource. -type ServiceEndpointPolicyPropertiesFormat struct { - // ServiceEndpointPolicyDefinitions - A collection of service endpoint policy definitions of the service endpoint policy. - ServiceEndpointPolicyDefinitions *[]ServiceEndpointPolicyDefinition `json:"serviceEndpointPolicyDefinitions,omitempty"` - // Subnets - READ-ONLY; A collection of references to subnets. - Subnets *[]Subnet `json:"subnets,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the service endpoint policy resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the service endpoint policy. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyPropertiesFormat. -func (seppf ServiceEndpointPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if seppf.ServiceEndpointPolicyDefinitions != nil { - objectMap["serviceEndpointPolicyDefinitions"] = seppf.ServiceEndpointPolicyDefinitions - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPropertiesFormat the service endpoint properties. -type ServiceEndpointPropertiesFormat struct { - // Service - The type of the endpoint service. - Service *string `json:"service,omitempty"` - // Locations - A list of locations. - Locations *[]string `json:"locations,omitempty"` - // ProvisioningState - The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// String ... -type String struct { - autorest.Response `json:"-"` - Value *string `json:"value,omitempty"` -} - -// Subnet subnet in a virtual network resource. -type Subnet struct { - autorest.Response `json:"-"` - // SubnetPropertiesFormat - Properties of the subnet. - *SubnetPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Subnet. -func (s Subnet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if s.SubnetPropertiesFormat != nil { - objectMap["properties"] = s.SubnetPropertiesFormat - } - if s.Name != nil { - objectMap["name"] = s.Name - } - if s.Etag != nil { - objectMap["etag"] = s.Etag - } - if s.ID != nil { - objectMap["id"] = s.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Subnet struct. -func (s *Subnet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var subnetPropertiesFormat SubnetPropertiesFormat - err = json.Unmarshal(*v, &subnetPropertiesFormat) - if err != nil { - return err - } - s.SubnetPropertiesFormat = &subnetPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - s.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - s.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - s.ID = &ID - } - } - } - - return nil -} - -// SubnetAssociation network interface and its custom security rules. -type SubnetAssociation struct { - // ID - READ-ONLY; Subnet ID. - ID *string `json:"id,omitempty"` - // SecurityRules - Collection of custom security rules. - SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubnetAssociation. -func (sa SubnetAssociation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sa.SecurityRules != nil { - objectMap["securityRules"] = sa.SecurityRules - } - return json.Marshal(objectMap) -} - -// SubnetListResult response for ListSubnets API service callRetrieves all subnet that belongs to a virtual -// network -type SubnetListResult struct { - autorest.Response `json:"-"` - // Value - The subnets in a virtual network. - Value *[]Subnet `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SubnetListResultIterator provides access to a complete listing of Subnet values. -type SubnetListResultIterator struct { - i int - page SubnetListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SubnetListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SubnetListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SubnetListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SubnetListResultIterator) Response() SubnetListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SubnetListResultIterator) Value() Subnet { - if !iter.page.NotDone() { - return Subnet{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SubnetListResultIterator type. -func NewSubnetListResultIterator(page SubnetListResultPage) SubnetListResultIterator { - return SubnetListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (slr SubnetListResult) IsEmpty() bool { - return slr.Value == nil || len(*slr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (slr SubnetListResult) hasNextLink() bool { - return slr.NextLink != nil && len(*slr.NextLink) != 0 -} - -// subnetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (slr SubnetListResult) subnetListResultPreparer(ctx context.Context) (*http.Request, error) { - if !slr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(slr.NextLink))) -} - -// SubnetListResultPage contains a page of Subnet values. -type SubnetListResultPage struct { - fn func(context.Context, SubnetListResult) (SubnetListResult, error) - slr SubnetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SubnetListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.slr) - if err != nil { - return err - } - page.slr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SubnetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SubnetListResultPage) NotDone() bool { - return !page.slr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SubnetListResultPage) Response() SubnetListResult { - return page.slr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SubnetListResultPage) Values() []Subnet { - if page.slr.IsEmpty() { - return nil - } - return *page.slr.Value -} - -// Creates a new instance of the SubnetListResultPage type. -func NewSubnetListResultPage(cur SubnetListResult, getNextPage func(context.Context, SubnetListResult) (SubnetListResult, error)) SubnetListResultPage { - return SubnetListResultPage{ - fn: getNextPage, - slr: cur, - } -} - -// SubnetPropertiesFormat properties of the subnet. -type SubnetPropertiesFormat struct { - // AddressPrefix - The address prefix for the subnet. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // AddressPrefixes - List of address prefixes for the subnet. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` - // NetworkSecurityGroup - The reference of the NetworkSecurityGroup resource. - NetworkSecurityGroup *SecurityGroup `json:"networkSecurityGroup,omitempty"` - // RouteTable - The reference of the RouteTable resource. - RouteTable *RouteTable `json:"routeTable,omitempty"` - // ServiceEndpoints - An array of service endpoints. - ServiceEndpoints *[]ServiceEndpointPropertiesFormat `json:"serviceEndpoints,omitempty"` - // ServiceEndpointPolicies - An array of service endpoint policies. - ServiceEndpointPolicies *[]ServiceEndpointPolicy `json:"serviceEndpointPolicies,omitempty"` - // InterfaceEndpoints - READ-ONLY; An array of references to interface endpoints - InterfaceEndpoints *[]InterfaceEndpoint `json:"interfaceEndpoints,omitempty"` - // IPConfigurations - READ-ONLY; Gets an array of references to the network interface IP configurations using subnet. - IPConfigurations *[]IPConfiguration `json:"ipConfigurations,omitempty"` - // IPConfigurationProfiles - READ-ONLY; Array of IP configuration profiles which reference this subnet. - IPConfigurationProfiles *[]IPConfigurationProfile `json:"ipConfigurationProfiles,omitempty"` - // ResourceNavigationLinks - Gets an array of references to the external resources using subnet. - ResourceNavigationLinks *[]ResourceNavigationLink `json:"resourceNavigationLinks,omitempty"` - // ServiceAssociationLinks - Gets an array of references to services injecting into this subnet. - ServiceAssociationLinks *[]ServiceAssociationLink `json:"serviceAssociationLinks,omitempty"` - // Delegations - Gets an array of references to the delegations on the subnet. - Delegations *[]Delegation `json:"delegations,omitempty"` - // Purpose - READ-ONLY; A read-only string identifying the intention of use for this subnet based on delegations and other user-defined properties. - Purpose *string `json:"purpose,omitempty"` - // ProvisioningState - The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubnetPropertiesFormat. -func (spf SubnetPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spf.AddressPrefix != nil { - objectMap["addressPrefix"] = spf.AddressPrefix - } - if spf.AddressPrefixes != nil { - objectMap["addressPrefixes"] = spf.AddressPrefixes - } - if spf.NetworkSecurityGroup != nil { - objectMap["networkSecurityGroup"] = spf.NetworkSecurityGroup - } - if spf.RouteTable != nil { - objectMap["routeTable"] = spf.RouteTable - } - if spf.ServiceEndpoints != nil { - objectMap["serviceEndpoints"] = spf.ServiceEndpoints - } - if spf.ServiceEndpointPolicies != nil { - objectMap["serviceEndpointPolicies"] = spf.ServiceEndpointPolicies - } - if spf.ResourceNavigationLinks != nil { - objectMap["resourceNavigationLinks"] = spf.ResourceNavigationLinks - } - if spf.ServiceAssociationLinks != nil { - objectMap["serviceAssociationLinks"] = spf.ServiceAssociationLinks - } - if spf.Delegations != nil { - objectMap["delegations"] = spf.Delegations - } - if spf.ProvisioningState != nil { - objectMap["provisioningState"] = spf.ProvisioningState - } - return json.Marshal(objectMap) -} - -// SubnetsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubnetsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubnetsClient) (Subnet, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubnetsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubnetsCreateOrUpdateFuture.Result. -func (future *SubnetsCreateOrUpdateFuture) result(client SubnetsClient) (s Subnet, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SubnetsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.CreateOrUpdateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsCreateOrUpdateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// SubnetsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubnetsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubnetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubnetsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubnetsDeleteFuture.Result. -func (future *SubnetsDeleteFuture) result(client SubnetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SubnetsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SubResource reference to another subresource. -type SubResource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// TagsObject tags object for patch operations. -type TagsObject struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for TagsObject. -func (toVar TagsObject) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if toVar.Tags != nil { - objectMap["tags"] = toVar.Tags - } - return json.Marshal(objectMap) -} - -// Topology topology of the specified resource group. -type Topology struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; GUID representing the operation id. - ID *string `json:"id,omitempty"` - // CreatedDateTime - READ-ONLY; The datetime when the topology was initially created for the resource group. - CreatedDateTime *date.Time `json:"createdDateTime,omitempty"` - // LastModified - READ-ONLY; The datetime when the topology was last modified. - LastModified *date.Time `json:"lastModified,omitempty"` - Resources *[]TopologyResource `json:"resources,omitempty"` -} - -// MarshalJSON is the custom marshaler for Topology. -func (t Topology) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if t.Resources != nil { - objectMap["resources"] = t.Resources - } - return json.Marshal(objectMap) -} - -// TopologyAssociation resources that have an association with the parent resource. -type TopologyAssociation struct { - // Name - The name of the resource that is associated with the parent resource. - Name *string `json:"name,omitempty"` - // ResourceID - The ID of the resource that is associated with the parent resource. - ResourceID *string `json:"resourceId,omitempty"` - // AssociationType - The association type of the child resource to the parent resource. Possible values include: 'Associated', 'Contains' - AssociationType AssociationType `json:"associationType,omitempty"` -} - -// TopologyParameters parameters that define the representation of topology. -type TopologyParameters struct { - // TargetResourceGroupName - The name of the target resource group to perform topology on. - TargetResourceGroupName *string `json:"targetResourceGroupName,omitempty"` - // TargetVirtualNetwork - The reference of the Virtual Network resource. - TargetVirtualNetwork *SubResource `json:"targetVirtualNetwork,omitempty"` - // TargetSubnet - The reference of the Subnet resource. - TargetSubnet *SubResource `json:"targetSubnet,omitempty"` -} - -// TopologyResource the network resource topology information for the given resource group. -type TopologyResource struct { - // Name - Name of the resource. - Name *string `json:"name,omitempty"` - // ID - ID of the resource. - ID *string `json:"id,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Associations - Holds the associations the resource has with other resources in the resource group. - Associations *[]TopologyAssociation `json:"associations,omitempty"` -} - -// TrafficAnalyticsConfigurationProperties parameters that define the configuration of traffic analytics. -type TrafficAnalyticsConfigurationProperties struct { - // Enabled - Flag to enable/disable traffic analytics. - Enabled *bool `json:"enabled,omitempty"` - // WorkspaceID - The resource guid of the attached workspace - WorkspaceID *string `json:"workspaceId,omitempty"` - // WorkspaceRegion - The location of the attached workspace - WorkspaceRegion *string `json:"workspaceRegion,omitempty"` - // WorkspaceResourceID - Resource Id of the attached workspace - WorkspaceResourceID *string `json:"workspaceResourceId,omitempty"` - // TrafficAnalyticsInterval - The interval in minutes which would decide how frequently TA service should do flow analytics - TrafficAnalyticsInterval *int32 `json:"trafficAnalyticsInterval,omitempty"` -} - -// TrafficAnalyticsProperties parameters that define the configuration of traffic analytics. -type TrafficAnalyticsProperties struct { - NetworkWatcherFlowAnalyticsConfiguration *TrafficAnalyticsConfigurationProperties `json:"networkWatcherFlowAnalyticsConfiguration,omitempty"` -} - -// TroubleshootingDetails information gained from troubleshooting of specified resource. -type TroubleshootingDetails struct { - // ID - The id of the get troubleshoot operation. - ID *string `json:"id,omitempty"` - // ReasonType - Reason type of failure. - ReasonType *string `json:"reasonType,omitempty"` - // Summary - A summary of troubleshooting. - Summary *string `json:"summary,omitempty"` - // Detail - Details on troubleshooting results. - Detail *string `json:"detail,omitempty"` - // RecommendedActions - List of recommended actions. - RecommendedActions *[]TroubleshootingRecommendedActions `json:"recommendedActions,omitempty"` -} - -// TroubleshootingParameters parameters that define the resource to troubleshoot. -type TroubleshootingParameters struct { - // TargetResourceID - The target resource to troubleshoot. - TargetResourceID *string `json:"targetResourceId,omitempty"` - *TroubleshootingProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for TroubleshootingParameters. -func (tp TroubleshootingParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if tp.TargetResourceID != nil { - objectMap["targetResourceId"] = tp.TargetResourceID - } - if tp.TroubleshootingProperties != nil { - objectMap["properties"] = tp.TroubleshootingProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for TroubleshootingParameters struct. -func (tp *TroubleshootingParameters) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "targetResourceId": - if v != nil { - var targetResourceID string - err = json.Unmarshal(*v, &targetResourceID) - if err != nil { - return err - } - tp.TargetResourceID = &targetResourceID - } - case "properties": - if v != nil { - var troubleshootingProperties TroubleshootingProperties - err = json.Unmarshal(*v, &troubleshootingProperties) - if err != nil { - return err - } - tp.TroubleshootingProperties = &troubleshootingProperties - } - } - } - - return nil -} - -// TroubleshootingProperties storage location provided for troubleshoot. -type TroubleshootingProperties struct { - // StorageID - The ID for the storage account to save the troubleshoot result. - StorageID *string `json:"storageId,omitempty"` - // StoragePath - The path to the blob to save the troubleshoot result in. - StoragePath *string `json:"storagePath,omitempty"` -} - -// TroubleshootingRecommendedActions recommended actions based on discovered issues. -type TroubleshootingRecommendedActions struct { - // ActionID - ID of the recommended action. - ActionID *string `json:"actionId,omitempty"` - // ActionText - Description of recommended actions. - ActionText *string `json:"actionText,omitempty"` - // ActionURI - The uri linking to a documentation for the recommended troubleshooting actions. - ActionURI *string `json:"actionUri,omitempty"` - // ActionURIText - The information from the URI for the recommended troubleshooting actions. - ActionURIText *string `json:"actionUriText,omitempty"` -} - -// TroubleshootingResult troubleshooting information gained from specified resource. -type TroubleshootingResult struct { - autorest.Response `json:"-"` - // StartTime - The start time of the troubleshooting. - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - The end time of the troubleshooting. - EndTime *date.Time `json:"endTime,omitempty"` - // Code - The result code of the troubleshooting. - Code *string `json:"code,omitempty"` - // Results - Information from troubleshooting. - Results *[]TroubleshootingDetails `json:"results,omitempty"` -} - -// TunnelConnectionHealth virtualNetworkGatewayConnection properties -type TunnelConnectionHealth struct { - // Tunnel - READ-ONLY; Tunnel name. - Tunnel *string `json:"tunnel,omitempty"` - // ConnectionStatus - READ-ONLY; Virtual network Gateway connection status. Possible values include: 'VirtualNetworkGatewayConnectionStatusUnknown', 'VirtualNetworkGatewayConnectionStatusConnecting', 'VirtualNetworkGatewayConnectionStatusConnected', 'VirtualNetworkGatewayConnectionStatusNotConnected' - ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - // IngressBytesTransferred - READ-ONLY; The Ingress Bytes Transferred in this connection - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // EgressBytesTransferred - READ-ONLY; The Egress Bytes Transferred in this connection - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // LastConnectionEstablishedUtcTime - READ-ONLY; The time at which connection was established in Utc format. - LastConnectionEstablishedUtcTime *string `json:"lastConnectionEstablishedUtcTime,omitempty"` -} - -// MarshalJSON is the custom marshaler for TunnelConnectionHealth. -func (tch TunnelConnectionHealth) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Usage describes network resource usage. -type Usage struct { - // ID - READ-ONLY; Resource identifier. - ID *string `json:"id,omitempty"` - // Unit - An enum describing the unit of measurement. - Unit *string `json:"unit,omitempty"` - // CurrentValue - The current value of the usage. - CurrentValue *int64 `json:"currentValue,omitempty"` - // Limit - The limit of usage. - Limit *int64 `json:"limit,omitempty"` - // Name - The name of the type of usage. - Name *UsageName `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for Usage. -func (u Usage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if u.Unit != nil { - objectMap["unit"] = u.Unit - } - if u.CurrentValue != nil { - objectMap["currentValue"] = u.CurrentValue - } - if u.Limit != nil { - objectMap["limit"] = u.Limit - } - if u.Name != nil { - objectMap["name"] = u.Name - } - return json.Marshal(objectMap) -} - -// UsageName the usage names. -type UsageName struct { - // Value - A string describing the resource name. - Value *string `json:"value,omitempty"` - // LocalizedValue - A localized string describing the resource name. - LocalizedValue *string `json:"localizedValue,omitempty"` -} - -// UsagesListResult the list usages operation response. -type UsagesListResult struct { - autorest.Response `json:"-"` - // Value - The list network resource usages. - Value *[]Usage `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// UsagesListResultIterator provides access to a complete listing of Usage values. -type UsagesListResultIterator struct { - i int - page UsagesListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *UsagesListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *UsagesListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter UsagesListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter UsagesListResultIterator) Response() UsagesListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter UsagesListResultIterator) Value() Usage { - if !iter.page.NotDone() { - return Usage{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the UsagesListResultIterator type. -func NewUsagesListResultIterator(page UsagesListResultPage) UsagesListResultIterator { - return UsagesListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ulr UsagesListResult) IsEmpty() bool { - return ulr.Value == nil || len(*ulr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ulr UsagesListResult) hasNextLink() bool { - return ulr.NextLink != nil && len(*ulr.NextLink) != 0 -} - -// usagesListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ulr UsagesListResult) usagesListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ulr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ulr.NextLink))) -} - -// UsagesListResultPage contains a page of Usage values. -type UsagesListResultPage struct { - fn func(context.Context, UsagesListResult) (UsagesListResult, error) - ulr UsagesListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *UsagesListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ulr) - if err != nil { - return err - } - page.ulr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *UsagesListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page UsagesListResultPage) NotDone() bool { - return !page.ulr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page UsagesListResultPage) Response() UsagesListResult { - return page.ulr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page UsagesListResultPage) Values() []Usage { - if page.ulr.IsEmpty() { - return nil - } - return *page.ulr.Value -} - -// Creates a new instance of the UsagesListResultPage type. -func NewUsagesListResultPage(cur UsagesListResult, getNextPage func(context.Context, UsagesListResult) (UsagesListResult, error)) UsagesListResultPage { - return UsagesListResultPage{ - fn: getNextPage, - ulr: cur, - } -} - -// VerificationIPFlowParameters parameters that define the IP flow to be verified. -type VerificationIPFlowParameters struct { - // TargetResourceID - The ID of the target resource to perform next-hop on. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // Direction - The direction of the packet represented as a 5-tuple. Possible values include: 'Inbound', 'Outbound' - Direction Direction `json:"direction,omitempty"` - // Protocol - Protocol to be verified on. Possible values include: 'IPFlowProtocolTCP', 'IPFlowProtocolUDP' - Protocol IPFlowProtocol `json:"protocol,omitempty"` - // LocalPort - The local port. Acceptable values are a single integer in the range (0-65535). Support for * for the source port, which depends on the direction. - LocalPort *string `json:"localPort,omitempty"` - // RemotePort - The remote port. Acceptable values are a single integer in the range (0-65535). Support for * for the source port, which depends on the direction. - RemotePort *string `json:"remotePort,omitempty"` - // LocalIPAddress - The local IP address. Acceptable values are valid IPv4 addresses. - LocalIPAddress *string `json:"localIPAddress,omitempty"` - // RemoteIPAddress - The remote IP address. Acceptable values are valid IPv4 addresses. - RemoteIPAddress *string `json:"remoteIPAddress,omitempty"` - // TargetNicResourceID - The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of them, then this parameter must be specified. Otherwise optional). - TargetNicResourceID *string `json:"targetNicResourceId,omitempty"` -} - -// VerificationIPFlowResult results of IP flow verification on the target resource. -type VerificationIPFlowResult struct { - autorest.Response `json:"-"` - // Access - Indicates whether the traffic is allowed or denied. Possible values include: 'Allow', 'Deny' - Access Access `json:"access,omitempty"` - // RuleName - Name of the rule. If input is not matched against any security rule, it is not displayed. - RuleName *string `json:"ruleName,omitempty"` -} - -// VirtualHub virtualHub Resource. -type VirtualHub struct { - autorest.Response `json:"-"` - *VirtualHubProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualHub. -func (vh VirtualHub) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vh.VirtualHubProperties != nil { - objectMap["properties"] = vh.VirtualHubProperties - } - if vh.ID != nil { - objectMap["id"] = vh.ID - } - if vh.Location != nil { - objectMap["location"] = vh.Location - } - if vh.Tags != nil { - objectMap["tags"] = vh.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualHub struct. -func (vh *VirtualHub) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualHubProperties VirtualHubProperties - err = json.Unmarshal(*v, &virtualHubProperties) - if err != nil { - return err - } - vh.VirtualHubProperties = &virtualHubProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vh.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vh.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vh.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vh.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vh.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vh.Tags = tags - } - } - } - - return nil -} - -// VirtualHubID virtual Hub identifier. -type VirtualHubID struct { - // ID - The resource URI for the Virtual Hub where the ExpressRoute gateway is or will be deployed. The Virtual Hub resource and the ExpressRoute gateway resource reside in the same subscription. - ID *string `json:"id,omitempty"` -} - -// VirtualHubProperties parameters for VirtualHub -type VirtualHubProperties struct { - // VirtualWan - The VirtualWAN to which the VirtualHub belongs - VirtualWan *SubResource `json:"virtualWan,omitempty"` - // VpnGateway - The VpnGateway associated with this VirtualHub - VpnGateway *SubResource `json:"vpnGateway,omitempty"` - // P2SVpnGateway - The P2SVpnGateway associated with this VirtualHub - P2SVpnGateway *SubResource `json:"p2SVpnGateway,omitempty"` - // ExpressRouteGateway - The expressRouteGateway associated with this VirtualHub - ExpressRouteGateway *SubResource `json:"expressRouteGateway,omitempty"` - // VirtualNetworkConnections - list of all vnet connections with this VirtualHub. - VirtualNetworkConnections *[]HubVirtualNetworkConnection `json:"virtualNetworkConnections,omitempty"` - // AddressPrefix - Address-prefix for this VirtualHub. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // RouteTable - The routeTable associated with this virtual hub. - RouteTable *VirtualHubRouteTable `json:"routeTable,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// VirtualHubRoute virtualHub route -type VirtualHubRoute struct { - // AddressPrefixes - list of all addressPrefixes. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` - // NextHopIPAddress - NextHop ip address. - NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` -} - -// VirtualHubRouteTable virtualHub route table -type VirtualHubRouteTable struct { - // Routes - list of all routes. - Routes *[]VirtualHubRoute `json:"routes,omitempty"` -} - -// VirtualHubsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualHubsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (VirtualHub, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsCreateOrUpdateFuture.Result. -func (future *VirtualHubsCreateOrUpdateFuture) result(client VirtualHubsClient) (vh VirtualHub, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vh.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vh.Response.Response, err = future.GetResult(sender); err == nil && vh.Response.Response.StatusCode != http.StatusNoContent { - vh, err = client.CreateOrUpdateResponder(vh.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsCreateOrUpdateFuture", "Result", vh.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualHubsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualHubsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsDeleteFuture.Result. -func (future *VirtualHubsDeleteFuture) result(client VirtualHubsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualHubsUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualHubsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (VirtualHub, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsUpdateTagsFuture.Result. -func (future *VirtualHubsUpdateTagsFuture) result(client VirtualHubsClient) (vh VirtualHub, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vh.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vh.Response.Response, err = future.GetResult(sender); err == nil && vh.Response.Response.StatusCode != http.StatusNoContent { - vh, err = client.UpdateTagsResponder(vh.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsUpdateTagsFuture", "Result", vh.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetwork virtual Network resource. -type VirtualNetwork struct { - autorest.Response `json:"-"` - // VirtualNetworkPropertiesFormat - Properties of the virtual network. - *VirtualNetworkPropertiesFormat `json:"properties,omitempty"` - // Etag - Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetwork. -func (vn VirtualNetwork) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vn.VirtualNetworkPropertiesFormat != nil { - objectMap["properties"] = vn.VirtualNetworkPropertiesFormat - } - if vn.Etag != nil { - objectMap["etag"] = vn.Etag - } - if vn.ID != nil { - objectMap["id"] = vn.ID - } - if vn.Location != nil { - objectMap["location"] = vn.Location - } - if vn.Tags != nil { - objectMap["tags"] = vn.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetwork struct. -func (vn *VirtualNetwork) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkPropertiesFormat VirtualNetworkPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkPropertiesFormat) - if err != nil { - return err - } - vn.VirtualNetworkPropertiesFormat = &virtualNetworkPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vn.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vn.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vn.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vn.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vn.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vn.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkConnectionGatewayReference a reference to VirtualNetworkGateway or LocalNetworkGateway -// resource. -type VirtualNetworkConnectionGatewayReference struct { - // ID - The ID of VirtualNetworkGateway or LocalNetworkGateway resource. - ID *string `json:"id,omitempty"` -} - -// VirtualNetworkGateway a common class for general resource information -type VirtualNetworkGateway struct { - autorest.Response `json:"-"` - // VirtualNetworkGatewayPropertiesFormat - Properties of the virtual network gateway. - *VirtualNetworkGatewayPropertiesFormat `json:"properties,omitempty"` - // Etag - Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGateway. -func (vng VirtualNetworkGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vng.VirtualNetworkGatewayPropertiesFormat != nil { - objectMap["properties"] = vng.VirtualNetworkGatewayPropertiesFormat - } - if vng.Etag != nil { - objectMap["etag"] = vng.Etag - } - if vng.ID != nil { - objectMap["id"] = vng.ID - } - if vng.Location != nil { - objectMap["location"] = vng.Location - } - if vng.Tags != nil { - objectMap["tags"] = vng.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGateway struct. -func (vng *VirtualNetworkGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayPropertiesFormat VirtualNetworkGatewayPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayPropertiesFormat) - if err != nil { - return err - } - vng.VirtualNetworkGatewayPropertiesFormat = &virtualNetworkGatewayPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vng.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vng.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vng.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vng.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vng.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vng.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkGatewayConnection a common class for general resource information -type VirtualNetworkGatewayConnection struct { - autorest.Response `json:"-"` - // VirtualNetworkGatewayConnectionPropertiesFormat - Properties of the virtual network gateway connection. - *VirtualNetworkGatewayConnectionPropertiesFormat `json:"properties,omitempty"` - // Etag - Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnection. -func (vngc VirtualNetworkGatewayConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngc.VirtualNetworkGatewayConnectionPropertiesFormat != nil { - objectMap["properties"] = vngc.VirtualNetworkGatewayConnectionPropertiesFormat - } - if vngc.Etag != nil { - objectMap["etag"] = vngc.Etag - } - if vngc.ID != nil { - objectMap["id"] = vngc.ID - } - if vngc.Location != nil { - objectMap["location"] = vngc.Location - } - if vngc.Tags != nil { - objectMap["tags"] = vngc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayConnection struct. -func (vngc *VirtualNetworkGatewayConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayConnectionPropertiesFormat VirtualNetworkGatewayConnectionPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayConnectionPropertiesFormat) - if err != nil { - return err - } - vngc.VirtualNetworkGatewayConnectionPropertiesFormat = &virtualNetworkGatewayConnectionPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vngc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vngc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vngc.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkGatewayConnectionListEntity a common class for general resource information -type VirtualNetworkGatewayConnectionListEntity struct { - // VirtualNetworkGatewayConnectionListEntityPropertiesFormat - Properties of the virtual network gateway connection. - *VirtualNetworkGatewayConnectionListEntityPropertiesFormat `json:"properties,omitempty"` - // Etag - Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionListEntity. -func (vngcle VirtualNetworkGatewayConnectionListEntity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngcle.VirtualNetworkGatewayConnectionListEntityPropertiesFormat != nil { - objectMap["properties"] = vngcle.VirtualNetworkGatewayConnectionListEntityPropertiesFormat - } - if vngcle.Etag != nil { - objectMap["etag"] = vngcle.Etag - } - if vngcle.ID != nil { - objectMap["id"] = vngcle.ID - } - if vngcle.Location != nil { - objectMap["location"] = vngcle.Location - } - if vngcle.Tags != nil { - objectMap["tags"] = vngcle.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayConnectionListEntity struct. -func (vngcle *VirtualNetworkGatewayConnectionListEntity) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayConnectionListEntityPropertiesFormat VirtualNetworkGatewayConnectionListEntityPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayConnectionListEntityPropertiesFormat) - if err != nil { - return err - } - vngcle.VirtualNetworkGatewayConnectionListEntityPropertiesFormat = &virtualNetworkGatewayConnectionListEntityPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngcle.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngcle.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngcle.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vngcle.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vngcle.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vngcle.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkGatewayConnectionListEntityPropertiesFormat virtualNetworkGatewayConnection properties -type VirtualNetworkGatewayConnectionListEntityPropertiesFormat struct { - // AuthorizationKey - The authorizationKey. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // VirtualNetworkGateway1 - The reference to virtual network gateway resource. - VirtualNetworkGateway1 *VirtualNetworkConnectionGatewayReference `json:"virtualNetworkGateway1,omitempty"` - // VirtualNetworkGateway2 - The reference to virtual network gateway resource. - VirtualNetworkGateway2 *VirtualNetworkConnectionGatewayReference `json:"virtualNetworkGateway2,omitempty"` - // LocalNetworkGateway2 - The reference to local network gateway resource. - LocalNetworkGateway2 *VirtualNetworkConnectionGatewayReference `json:"localNetworkGateway2,omitempty"` - // ConnectionType - Gateway connection type. Possible values are: 'IPsec','Vnet2Vnet','ExpressRoute', and 'VPNClient. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient' - ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` - // ConnectionProtocol - Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' - ConnectionProtocol VirtualNetworkGatewayConnectionProtocol `json:"connectionProtocol,omitempty"` - // RoutingWeight - The routing weight. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // SharedKey - The IPSec shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // ConnectionStatus - READ-ONLY; Virtual network Gateway connection status. Possible values are 'Unknown', 'Connecting', 'Connected' and 'NotConnected'. Possible values include: 'VirtualNetworkGatewayConnectionStatusUnknown', 'VirtualNetworkGatewayConnectionStatusConnecting', 'VirtualNetworkGatewayConnectionStatusConnected', 'VirtualNetworkGatewayConnectionStatusNotConnected' - ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - // TunnelConnectionStatus - READ-ONLY; Collection of all tunnels' connection health status. - TunnelConnectionStatus *[]TunnelConnectionHealth `json:"tunnelConnectionStatus,omitempty"` - // EgressBytesTransferred - READ-ONLY; The egress bytes transferred in this connection. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // IngressBytesTransferred - READ-ONLY; The ingress bytes transferred in this connection. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // Peer - The reference to peerings resource. - Peer *SubResource `json:"peer,omitempty"` - // EnableBgp - EnableBgp flag - EnableBgp *bool `json:"enableBgp,omitempty"` - // UsePolicyBasedTrafficSelectors - Enable policy-based traffic selectors. - UsePolicyBasedTrafficSelectors *bool `json:"usePolicyBasedTrafficSelectors,omitempty"` - // IpsecPolicies - The IPSec Policies to be considered by this connection. - IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` - // ResourceGUID - The resource GUID property of the VirtualNetworkGatewayConnection resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VirtualNetworkGatewayConnection resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // ExpressRouteGatewayBypass - Bypass ExpressRoute Gateway for data forwarding - ExpressRouteGatewayBypass *bool `json:"expressRouteGatewayBypass,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionListEntityPropertiesFormat. -func (vngclepf VirtualNetworkGatewayConnectionListEntityPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngclepf.AuthorizationKey != nil { - objectMap["authorizationKey"] = vngclepf.AuthorizationKey - } - if vngclepf.VirtualNetworkGateway1 != nil { - objectMap["virtualNetworkGateway1"] = vngclepf.VirtualNetworkGateway1 - } - if vngclepf.VirtualNetworkGateway2 != nil { - objectMap["virtualNetworkGateway2"] = vngclepf.VirtualNetworkGateway2 - } - if vngclepf.LocalNetworkGateway2 != nil { - objectMap["localNetworkGateway2"] = vngclepf.LocalNetworkGateway2 - } - if vngclepf.ConnectionType != "" { - objectMap["connectionType"] = vngclepf.ConnectionType - } - if vngclepf.ConnectionProtocol != "" { - objectMap["connectionProtocol"] = vngclepf.ConnectionProtocol - } - if vngclepf.RoutingWeight != nil { - objectMap["routingWeight"] = vngclepf.RoutingWeight - } - if vngclepf.SharedKey != nil { - objectMap["sharedKey"] = vngclepf.SharedKey - } - if vngclepf.Peer != nil { - objectMap["peer"] = vngclepf.Peer - } - if vngclepf.EnableBgp != nil { - objectMap["enableBgp"] = vngclepf.EnableBgp - } - if vngclepf.UsePolicyBasedTrafficSelectors != nil { - objectMap["usePolicyBasedTrafficSelectors"] = vngclepf.UsePolicyBasedTrafficSelectors - } - if vngclepf.IpsecPolicies != nil { - objectMap["ipsecPolicies"] = vngclepf.IpsecPolicies - } - if vngclepf.ResourceGUID != nil { - objectMap["resourceGuid"] = vngclepf.ResourceGUID - } - if vngclepf.ExpressRouteGatewayBypass != nil { - objectMap["expressRouteGatewayBypass"] = vngclepf.ExpressRouteGatewayBypass - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayConnectionListResult response for the ListVirtualNetworkGatewayConnections API -// service call -type VirtualNetworkGatewayConnectionListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of VirtualNetworkGatewayConnection resources that exists in a resource group. - Value *[]VirtualNetworkGatewayConnection `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionListResult. -func (vngclr VirtualNetworkGatewayConnectionListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngclr.Value != nil { - objectMap["value"] = vngclr.Value - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayConnectionListResultIterator provides access to a complete listing of -// VirtualNetworkGatewayConnection values. -type VirtualNetworkGatewayConnectionListResultIterator struct { - i int - page VirtualNetworkGatewayConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkGatewayConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkGatewayConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkGatewayConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkGatewayConnectionListResultIterator) Response() VirtualNetworkGatewayConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkGatewayConnectionListResultIterator) Value() VirtualNetworkGatewayConnection { - if !iter.page.NotDone() { - return VirtualNetworkGatewayConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkGatewayConnectionListResultIterator type. -func NewVirtualNetworkGatewayConnectionListResultIterator(page VirtualNetworkGatewayConnectionListResultPage) VirtualNetworkGatewayConnectionListResultIterator { - return VirtualNetworkGatewayConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vngclr VirtualNetworkGatewayConnectionListResult) IsEmpty() bool { - return vngclr.Value == nil || len(*vngclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vngclr VirtualNetworkGatewayConnectionListResult) hasNextLink() bool { - return vngclr.NextLink != nil && len(*vngclr.NextLink) != 0 -} - -// virtualNetworkGatewayConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vngclr VirtualNetworkGatewayConnectionListResult) virtualNetworkGatewayConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vngclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vngclr.NextLink))) -} - -// VirtualNetworkGatewayConnectionListResultPage contains a page of VirtualNetworkGatewayConnection values. -type VirtualNetworkGatewayConnectionListResultPage struct { - fn func(context.Context, VirtualNetworkGatewayConnectionListResult) (VirtualNetworkGatewayConnectionListResult, error) - vngclr VirtualNetworkGatewayConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkGatewayConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vngclr) - if err != nil { - return err - } - page.vngclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkGatewayConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkGatewayConnectionListResultPage) NotDone() bool { - return !page.vngclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkGatewayConnectionListResultPage) Response() VirtualNetworkGatewayConnectionListResult { - return page.vngclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkGatewayConnectionListResultPage) Values() []VirtualNetworkGatewayConnection { - if page.vngclr.IsEmpty() { - return nil - } - return *page.vngclr.Value -} - -// Creates a new instance of the VirtualNetworkGatewayConnectionListResultPage type. -func NewVirtualNetworkGatewayConnectionListResultPage(cur VirtualNetworkGatewayConnectionListResult, getNextPage func(context.Context, VirtualNetworkGatewayConnectionListResult) (VirtualNetworkGatewayConnectionListResult, error)) VirtualNetworkGatewayConnectionListResultPage { - return VirtualNetworkGatewayConnectionListResultPage{ - fn: getNextPage, - vngclr: cur, - } -} - -// VirtualNetworkGatewayConnectionPropertiesFormat virtualNetworkGatewayConnection properties -type VirtualNetworkGatewayConnectionPropertiesFormat struct { - // AuthorizationKey - The authorizationKey. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // VirtualNetworkGateway1 - The reference to virtual network gateway resource. - VirtualNetworkGateway1 *VirtualNetworkGateway `json:"virtualNetworkGateway1,omitempty"` - // VirtualNetworkGateway2 - The reference to virtual network gateway resource. - VirtualNetworkGateway2 *VirtualNetworkGateway `json:"virtualNetworkGateway2,omitempty"` - // LocalNetworkGateway2 - The reference to local network gateway resource. - LocalNetworkGateway2 *LocalNetworkGateway `json:"localNetworkGateway2,omitempty"` - // ConnectionType - Gateway connection type. Possible values are: 'Ipsec','Vnet2Vnet','ExpressRoute', and 'VPNClient. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient' - ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` - // ConnectionProtocol - Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' - ConnectionProtocol VirtualNetworkGatewayConnectionProtocol `json:"connectionProtocol,omitempty"` - // RoutingWeight - The routing weight. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // SharedKey - The IPSec shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // ConnectionStatus - READ-ONLY; Virtual network Gateway connection status. Possible values are 'Unknown', 'Connecting', 'Connected' and 'NotConnected'. Possible values include: 'VirtualNetworkGatewayConnectionStatusUnknown', 'VirtualNetworkGatewayConnectionStatusConnecting', 'VirtualNetworkGatewayConnectionStatusConnected', 'VirtualNetworkGatewayConnectionStatusNotConnected' - ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - // TunnelConnectionStatus - READ-ONLY; Collection of all tunnels' connection health status. - TunnelConnectionStatus *[]TunnelConnectionHealth `json:"tunnelConnectionStatus,omitempty"` - // EgressBytesTransferred - READ-ONLY; The egress bytes transferred in this connection. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // IngressBytesTransferred - READ-ONLY; The ingress bytes transferred in this connection. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // Peer - The reference to peerings resource. - Peer *SubResource `json:"peer,omitempty"` - // EnableBgp - EnableBgp flag - EnableBgp *bool `json:"enableBgp,omitempty"` - // UsePolicyBasedTrafficSelectors - Enable policy-based traffic selectors. - UsePolicyBasedTrafficSelectors *bool `json:"usePolicyBasedTrafficSelectors,omitempty"` - // IpsecPolicies - The IPSec Policies to be considered by this connection. - IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` - // ResourceGUID - The resource GUID property of the VirtualNetworkGatewayConnection resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VirtualNetworkGatewayConnection resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // ExpressRouteGatewayBypass - Bypass ExpressRoute Gateway for data forwarding - ExpressRouteGatewayBypass *bool `json:"expressRouteGatewayBypass,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionPropertiesFormat. -func (vngcpf VirtualNetworkGatewayConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngcpf.AuthorizationKey != nil { - objectMap["authorizationKey"] = vngcpf.AuthorizationKey - } - if vngcpf.VirtualNetworkGateway1 != nil { - objectMap["virtualNetworkGateway1"] = vngcpf.VirtualNetworkGateway1 - } - if vngcpf.VirtualNetworkGateway2 != nil { - objectMap["virtualNetworkGateway2"] = vngcpf.VirtualNetworkGateway2 - } - if vngcpf.LocalNetworkGateway2 != nil { - objectMap["localNetworkGateway2"] = vngcpf.LocalNetworkGateway2 - } - if vngcpf.ConnectionType != "" { - objectMap["connectionType"] = vngcpf.ConnectionType - } - if vngcpf.ConnectionProtocol != "" { - objectMap["connectionProtocol"] = vngcpf.ConnectionProtocol - } - if vngcpf.RoutingWeight != nil { - objectMap["routingWeight"] = vngcpf.RoutingWeight - } - if vngcpf.SharedKey != nil { - objectMap["sharedKey"] = vngcpf.SharedKey - } - if vngcpf.Peer != nil { - objectMap["peer"] = vngcpf.Peer - } - if vngcpf.EnableBgp != nil { - objectMap["enableBgp"] = vngcpf.EnableBgp - } - if vngcpf.UsePolicyBasedTrafficSelectors != nil { - objectMap["usePolicyBasedTrafficSelectors"] = vngcpf.UsePolicyBasedTrafficSelectors - } - if vngcpf.IpsecPolicies != nil { - objectMap["ipsecPolicies"] = vngcpf.IpsecPolicies - } - if vngcpf.ResourceGUID != nil { - objectMap["resourceGuid"] = vngcpf.ResourceGUID - } - if vngcpf.ExpressRouteGatewayBypass != nil { - objectMap["expressRouteGatewayBypass"] = vngcpf.ExpressRouteGatewayBypass - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (VirtualNetworkGatewayConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsCreateOrUpdateFuture.Result. -func (future *VirtualNetworkGatewayConnectionsCreateOrUpdateFuture) result(client VirtualNetworkGatewayConnectionsClient) (vngc VirtualNetworkGatewayConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vngc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vngc.Response.Response, err = future.GetResult(sender); err == nil && vngc.Response.Response.StatusCode != http.StatusNoContent { - vngc, err = client.CreateOrUpdateResponder(vngc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsCreateOrUpdateFuture", "Result", vngc.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualNetworkGatewayConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsDeleteFuture.Result. -func (future *VirtualNetworkGatewayConnectionsDeleteFuture) result(client VirtualNetworkGatewayConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewayConnectionsResetSharedKeyFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsResetSharedKeyFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (ConnectionResetSharedKey, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsResetSharedKeyFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsResetSharedKeyFuture.Result. -func (future *VirtualNetworkGatewayConnectionsResetSharedKeyFuture) result(client VirtualNetworkGatewayConnectionsClient) (crsk ConnectionResetSharedKey, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsResetSharedKeyFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - crsk.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsResetSharedKeyFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if crsk.Response.Response, err = future.GetResult(sender); err == nil && crsk.Response.Response.StatusCode != http.StatusNoContent { - crsk, err = client.ResetSharedKeyResponder(crsk.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsResetSharedKeyFuture", "Result", crsk.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsSetSharedKeyFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsSetSharedKeyFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (ConnectionSharedKey, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsSetSharedKeyFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsSetSharedKeyFuture.Result. -func (future *VirtualNetworkGatewayConnectionsSetSharedKeyFuture) result(client VirtualNetworkGatewayConnectionsClient) (csk ConnectionSharedKey, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsSetSharedKeyFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - csk.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsSetSharedKeyFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if csk.Response.Response, err = future.GetResult(sender); err == nil && csk.Response.Response.StatusCode != http.StatusNoContent { - csk, err = client.SetSharedKeyResponder(csk.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsSetSharedKeyFuture", "Result", csk.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsUpdateTagsFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (VirtualNetworkGatewayConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsUpdateTagsFuture.Result. -func (future *VirtualNetworkGatewayConnectionsUpdateTagsFuture) result(client VirtualNetworkGatewayConnectionsClient) (vngc VirtualNetworkGatewayConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vngc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vngc.Response.Response, err = future.GetResult(sender); err == nil && vngc.Response.Response.StatusCode != http.StatusNoContent { - vngc, err = client.UpdateTagsResponder(vngc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsUpdateTagsFuture", "Result", vngc.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayIPConfiguration IP configuration for virtual network gateway -type VirtualNetworkGatewayIPConfiguration struct { - // VirtualNetworkGatewayIPConfigurationPropertiesFormat - Properties of the virtual network gateway ip configuration. - *VirtualNetworkGatewayIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayIPConfiguration. -func (vngic VirtualNetworkGatewayIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngic.VirtualNetworkGatewayIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = vngic.VirtualNetworkGatewayIPConfigurationPropertiesFormat - } - if vngic.Name != nil { - objectMap["name"] = vngic.Name - } - if vngic.Etag != nil { - objectMap["etag"] = vngic.Etag - } - if vngic.ID != nil { - objectMap["id"] = vngic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayIPConfiguration struct. -func (vngic *VirtualNetworkGatewayIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayIPConfigurationPropertiesFormat VirtualNetworkGatewayIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayIPConfigurationPropertiesFormat) - if err != nil { - return err - } - vngic.VirtualNetworkGatewayIPConfigurationPropertiesFormat = &virtualNetworkGatewayIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngic.ID = &ID - } - } - } - - return nil -} - -// VirtualNetworkGatewayIPConfigurationPropertiesFormat properties of VirtualNetworkGatewayIPConfiguration -type VirtualNetworkGatewayIPConfigurationPropertiesFormat struct { - // PrivateIPAllocationMethod - The private IP allocation method. Possible values are: 'Static' and 'Dynamic'. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - The reference of the subnet resource. - Subnet *SubResource `json:"subnet,omitempty"` - // PublicIPAddress - The reference of the public IP resource. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayIPConfigurationPropertiesFormat. -func (vngicpf VirtualNetworkGatewayIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngicpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = vngicpf.PrivateIPAllocationMethod - } - if vngicpf.Subnet != nil { - objectMap["subnet"] = vngicpf.Subnet - } - if vngicpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = vngicpf.PublicIPAddress - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayListConnectionsResult response for the VirtualNetworkGatewayListConnections API -// service call -type VirtualNetworkGatewayListConnectionsResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of VirtualNetworkGatewayConnection resources that exists in a resource group. - Value *[]VirtualNetworkGatewayConnectionListEntity `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayListConnectionsResult. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnglcr.Value != nil { - objectMap["value"] = vnglcr.Value - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayListConnectionsResultIterator provides access to a complete listing of -// VirtualNetworkGatewayConnectionListEntity values. -type VirtualNetworkGatewayListConnectionsResultIterator struct { - i int - page VirtualNetworkGatewayListConnectionsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkGatewayListConnectionsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListConnectionsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkGatewayListConnectionsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkGatewayListConnectionsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkGatewayListConnectionsResultIterator) Response() VirtualNetworkGatewayListConnectionsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkGatewayListConnectionsResultIterator) Value() VirtualNetworkGatewayConnectionListEntity { - if !iter.page.NotDone() { - return VirtualNetworkGatewayConnectionListEntity{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkGatewayListConnectionsResultIterator type. -func NewVirtualNetworkGatewayListConnectionsResultIterator(page VirtualNetworkGatewayListConnectionsResultPage) VirtualNetworkGatewayListConnectionsResultIterator { - return VirtualNetworkGatewayListConnectionsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) IsEmpty() bool { - return vnglcr.Value == nil || len(*vnglcr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) hasNextLink() bool { - return vnglcr.NextLink != nil && len(*vnglcr.NextLink) != 0 -} - -// virtualNetworkGatewayListConnectionsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) virtualNetworkGatewayListConnectionsResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnglcr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnglcr.NextLink))) -} - -// VirtualNetworkGatewayListConnectionsResultPage contains a page of -// VirtualNetworkGatewayConnectionListEntity values. -type VirtualNetworkGatewayListConnectionsResultPage struct { - fn func(context.Context, VirtualNetworkGatewayListConnectionsResult) (VirtualNetworkGatewayListConnectionsResult, error) - vnglcr VirtualNetworkGatewayListConnectionsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkGatewayListConnectionsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListConnectionsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnglcr) - if err != nil { - return err - } - page.vnglcr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkGatewayListConnectionsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkGatewayListConnectionsResultPage) NotDone() bool { - return !page.vnglcr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkGatewayListConnectionsResultPage) Response() VirtualNetworkGatewayListConnectionsResult { - return page.vnglcr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkGatewayListConnectionsResultPage) Values() []VirtualNetworkGatewayConnectionListEntity { - if page.vnglcr.IsEmpty() { - return nil - } - return *page.vnglcr.Value -} - -// Creates a new instance of the VirtualNetworkGatewayListConnectionsResultPage type. -func NewVirtualNetworkGatewayListConnectionsResultPage(cur VirtualNetworkGatewayListConnectionsResult, getNextPage func(context.Context, VirtualNetworkGatewayListConnectionsResult) (VirtualNetworkGatewayListConnectionsResult, error)) VirtualNetworkGatewayListConnectionsResultPage { - return VirtualNetworkGatewayListConnectionsResultPage{ - fn: getNextPage, - vnglcr: cur, - } -} - -// VirtualNetworkGatewayListResult response for the ListVirtualNetworkGateways API service call. -type VirtualNetworkGatewayListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of VirtualNetworkGateway resources that exists in a resource group. - Value *[]VirtualNetworkGateway `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayListResult. -func (vnglr VirtualNetworkGatewayListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnglr.Value != nil { - objectMap["value"] = vnglr.Value - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayListResultIterator provides access to a complete listing of VirtualNetworkGateway -// values. -type VirtualNetworkGatewayListResultIterator struct { - i int - page VirtualNetworkGatewayListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkGatewayListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkGatewayListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkGatewayListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkGatewayListResultIterator) Response() VirtualNetworkGatewayListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkGatewayListResultIterator) Value() VirtualNetworkGateway { - if !iter.page.NotDone() { - return VirtualNetworkGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkGatewayListResultIterator type. -func NewVirtualNetworkGatewayListResultIterator(page VirtualNetworkGatewayListResultPage) VirtualNetworkGatewayListResultIterator { - return VirtualNetworkGatewayListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnglr VirtualNetworkGatewayListResult) IsEmpty() bool { - return vnglr.Value == nil || len(*vnglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnglr VirtualNetworkGatewayListResult) hasNextLink() bool { - return vnglr.NextLink != nil && len(*vnglr.NextLink) != 0 -} - -// virtualNetworkGatewayListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnglr VirtualNetworkGatewayListResult) virtualNetworkGatewayListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnglr.NextLink))) -} - -// VirtualNetworkGatewayListResultPage contains a page of VirtualNetworkGateway values. -type VirtualNetworkGatewayListResultPage struct { - fn func(context.Context, VirtualNetworkGatewayListResult) (VirtualNetworkGatewayListResult, error) - vnglr VirtualNetworkGatewayListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkGatewayListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnglr) - if err != nil { - return err - } - page.vnglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkGatewayListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkGatewayListResultPage) NotDone() bool { - return !page.vnglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkGatewayListResultPage) Response() VirtualNetworkGatewayListResult { - return page.vnglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkGatewayListResultPage) Values() []VirtualNetworkGateway { - if page.vnglr.IsEmpty() { - return nil - } - return *page.vnglr.Value -} - -// Creates a new instance of the VirtualNetworkGatewayListResultPage type. -func NewVirtualNetworkGatewayListResultPage(cur VirtualNetworkGatewayListResult, getNextPage func(context.Context, VirtualNetworkGatewayListResult) (VirtualNetworkGatewayListResult, error)) VirtualNetworkGatewayListResultPage { - return VirtualNetworkGatewayListResultPage{ - fn: getNextPage, - vnglr: cur, - } -} - -// VirtualNetworkGatewayPropertiesFormat virtualNetworkGateway properties -type VirtualNetworkGatewayPropertiesFormat struct { - // IPConfigurations - IP configurations for virtual network gateway. - IPConfigurations *[]VirtualNetworkGatewayIPConfiguration `json:"ipConfigurations,omitempty"` - // GatewayType - The type of this virtual network gateway. Possible values are: 'Vpn' and 'ExpressRoute'. Possible values include: 'VirtualNetworkGatewayTypeVpn', 'VirtualNetworkGatewayTypeExpressRoute' - GatewayType VirtualNetworkGatewayType `json:"gatewayType,omitempty"` - // VpnType - The type of this virtual network gateway. Possible values are: 'PolicyBased' and 'RouteBased'. Possible values include: 'PolicyBased', 'RouteBased' - VpnType VpnType `json:"vpnType,omitempty"` - // EnableBgp - Whether BGP is enabled for this virtual network gateway or not. - EnableBgp *bool `json:"enableBgp,omitempty"` - // ActiveActive - ActiveActive flag - ActiveActive *bool `json:"activeActive,omitempty"` - // GatewayDefaultSite - The reference of the LocalNetworkGateway resource which represents local network site having default routes. Assign Null value in case of removing existing default site setting. - GatewayDefaultSite *SubResource `json:"gatewayDefaultSite,omitempty"` - // Sku - The reference of the VirtualNetworkGatewaySku resource which represents the SKU selected for Virtual network gateway. - Sku *VirtualNetworkGatewaySku `json:"sku,omitempty"` - // VpnClientConfiguration - The reference of the VpnClientConfiguration resource which represents the P2S VpnClient configurations. - VpnClientConfiguration *VpnClientConfiguration `json:"vpnClientConfiguration,omitempty"` - // BgpSettings - Virtual network gateway's BGP speaker settings. - BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` - // ResourceGUID - The resource GUID property of the VirtualNetworkGateway resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VirtualNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayPropertiesFormat. -func (vngpf VirtualNetworkGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngpf.IPConfigurations != nil { - objectMap["ipConfigurations"] = vngpf.IPConfigurations - } - if vngpf.GatewayType != "" { - objectMap["gatewayType"] = vngpf.GatewayType - } - if vngpf.VpnType != "" { - objectMap["vpnType"] = vngpf.VpnType - } - if vngpf.EnableBgp != nil { - objectMap["enableBgp"] = vngpf.EnableBgp - } - if vngpf.ActiveActive != nil { - objectMap["activeActive"] = vngpf.ActiveActive - } - if vngpf.GatewayDefaultSite != nil { - objectMap["gatewayDefaultSite"] = vngpf.GatewayDefaultSite - } - if vngpf.Sku != nil { - objectMap["sku"] = vngpf.Sku - } - if vngpf.VpnClientConfiguration != nil { - objectMap["vpnClientConfiguration"] = vngpf.VpnClientConfiguration - } - if vngpf.BgpSettings != nil { - objectMap["bgpSettings"] = vngpf.BgpSettings - } - if vngpf.ResourceGUID != nil { - objectMap["resourceGuid"] = vngpf.ResourceGUID - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VirtualNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysCreateOrUpdateFuture.Result. -func (future *VirtualNetworkGatewaysCreateOrUpdateFuture) result(client VirtualNetworkGatewaysClient) (vng VirtualNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vng.Response.Response, err = future.GetResult(sender); err == nil && vng.Response.Response.StatusCode != http.StatusNoContent { - vng, err = client.CreateOrUpdateResponder(vng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysCreateOrUpdateFuture", "Result", vng.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysDeleteFuture.Result. -func (future *VirtualNetworkGatewaysDeleteFuture) result(client VirtualNetworkGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewaysGeneratevpnclientpackageFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysGeneratevpnclientpackageFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGeneratevpnclientpackageFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGeneratevpnclientpackageFuture.Result. -func (future *VirtualNetworkGatewaysGeneratevpnclientpackageFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGeneratevpnclientpackageFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGeneratevpnclientpackageFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GeneratevpnclientpackageResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGeneratevpnclientpackageFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGenerateVpnProfileFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworkGatewaysGenerateVpnProfileFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGenerateVpnProfileFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGenerateVpnProfileFuture.Result. -func (future *VirtualNetworkGatewaysGenerateVpnProfileFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGenerateVpnProfileFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGenerateVpnProfileFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GenerateVpnProfileResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGenerateVpnProfileFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetAdvertisedRoutesFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworkGatewaysGetAdvertisedRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (GatewayRouteListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetAdvertisedRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetAdvertisedRoutesFuture.Result. -func (future *VirtualNetworkGatewaysGetAdvertisedRoutesFuture) result(client VirtualNetworkGatewaysClient) (grlr GatewayRouteListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetAdvertisedRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - grlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetAdvertisedRoutesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if grlr.Response.Response, err = future.GetResult(sender); err == nil && grlr.Response.Response.StatusCode != http.StatusNoContent { - grlr, err = client.GetAdvertisedRoutesResponder(grlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetAdvertisedRoutesFuture", "Result", grlr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetBgpPeerStatusFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualNetworkGatewaysGetBgpPeerStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (BgpPeerStatusListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetBgpPeerStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetBgpPeerStatusFuture.Result. -func (future *VirtualNetworkGatewaysGetBgpPeerStatusFuture) result(client VirtualNetworkGatewaysClient) (bpslr BgpPeerStatusListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetBgpPeerStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bpslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetBgpPeerStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bpslr.Response.Response, err = future.GetResult(sender); err == nil && bpslr.Response.Response.StatusCode != http.StatusNoContent { - bpslr, err = client.GetBgpPeerStatusResponder(bpslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetBgpPeerStatusFuture", "Result", bpslr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetLearnedRoutesFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualNetworkGatewaysGetLearnedRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (GatewayRouteListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetLearnedRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetLearnedRoutesFuture.Result. -func (future *VirtualNetworkGatewaysGetLearnedRoutesFuture) result(client VirtualNetworkGatewaysClient) (grlr GatewayRouteListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetLearnedRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - grlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetLearnedRoutesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if grlr.Response.Response, err = future.GetResult(sender); err == nil && grlr.Response.Response.StatusCode != http.StatusNoContent { - grlr, err = client.GetLearnedRoutesResponder(grlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetLearnedRoutesFuture", "Result", grlr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VpnClientIPsecParameters, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture.Result. -func (future *VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture) result(client VirtualNetworkGatewaysClient) (vcipp VpnClientIPsecParameters, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vcipp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vcipp.Response.Response, err = future.GetResult(sender); err == nil && vcipp.Response.Response.StatusCode != http.StatusNoContent { - vcipp, err = client.GetVpnclientIpsecParametersResponder(vcipp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture", "Result", vcipp.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetVpnProfilePackageURLFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysGetVpnProfilePackageURLFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetVpnProfilePackageURLFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetVpnProfilePackageURLFuture.Result. -func (future *VirtualNetworkGatewaysGetVpnProfilePackageURLFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnProfilePackageURLFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetVpnProfilePackageURLFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GetVpnProfilePackageURLResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnProfilePackageURLFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaySku virtualNetworkGatewaySku details -type VirtualNetworkGatewaySku struct { - // Name - Gateway SKU name. Possible values include: 'VirtualNetworkGatewaySkuNameBasic', 'VirtualNetworkGatewaySkuNameHighPerformance', 'VirtualNetworkGatewaySkuNameStandard', 'VirtualNetworkGatewaySkuNameUltraPerformance', 'VirtualNetworkGatewaySkuNameVpnGw1', 'VirtualNetworkGatewaySkuNameVpnGw2', 'VirtualNetworkGatewaySkuNameVpnGw3', 'VirtualNetworkGatewaySkuNameVpnGw1AZ', 'VirtualNetworkGatewaySkuNameVpnGw2AZ', 'VirtualNetworkGatewaySkuNameVpnGw3AZ', 'VirtualNetworkGatewaySkuNameErGw1AZ', 'VirtualNetworkGatewaySkuNameErGw2AZ', 'VirtualNetworkGatewaySkuNameErGw3AZ' - Name VirtualNetworkGatewaySkuName `json:"name,omitempty"` - // Tier - Gateway SKU tier. Possible values include: 'VirtualNetworkGatewaySkuTierBasic', 'VirtualNetworkGatewaySkuTierHighPerformance', 'VirtualNetworkGatewaySkuTierStandard', 'VirtualNetworkGatewaySkuTierUltraPerformance', 'VirtualNetworkGatewaySkuTierVpnGw1', 'VirtualNetworkGatewaySkuTierVpnGw2', 'VirtualNetworkGatewaySkuTierVpnGw3', 'VirtualNetworkGatewaySkuTierVpnGw1AZ', 'VirtualNetworkGatewaySkuTierVpnGw2AZ', 'VirtualNetworkGatewaySkuTierVpnGw3AZ', 'VirtualNetworkGatewaySkuTierErGw1AZ', 'VirtualNetworkGatewaySkuTierErGw2AZ', 'VirtualNetworkGatewaySkuTierErGw3AZ' - Tier VirtualNetworkGatewaySkuTier `json:"tier,omitempty"` - // Capacity - The capacity. - Capacity *int32 `json:"capacity,omitempty"` -} - -// VirtualNetworkGatewaysResetFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysResetFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VirtualNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysResetFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysResetFuture.Result. -func (future *VirtualNetworkGatewaysResetFuture) result(client VirtualNetworkGatewaysClient) (vng VirtualNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysResetFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysResetFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vng.Response.Response, err = future.GetResult(sender); err == nil && vng.Response.Response.StatusCode != http.StatusNoContent { - vng, err = client.ResetResponder(vng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysResetFuture", "Result", vng.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysResetVpnClientSharedKeyFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysResetVpnClientSharedKeyFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysResetVpnClientSharedKeyFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysResetVpnClientSharedKeyFuture.Result. -func (future *VirtualNetworkGatewaysResetVpnClientSharedKeyFuture) result(client VirtualNetworkGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysResetVpnClientSharedKeyFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysResetVpnClientSharedKeyFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VpnClientIPsecParameters, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture.Result. -func (future *VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture) result(client VirtualNetworkGatewaysClient) (vcipp VpnClientIPsecParameters, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vcipp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vcipp.Response.Response, err = future.GetResult(sender); err == nil && vcipp.Response.Response.StatusCode != http.StatusNoContent { - vcipp, err = client.SetVpnclientIpsecParametersResponder(vcipp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture", "Result", vcipp.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VirtualNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysUpdateTagsFuture.Result. -func (future *VirtualNetworkGatewaysUpdateTagsFuture) result(client VirtualNetworkGatewaysClient) (vng VirtualNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vng.Response.Response, err = future.GetResult(sender); err == nil && vng.Response.Response.StatusCode != http.StatusNoContent { - vng, err = client.UpdateTagsResponder(vng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysUpdateTagsFuture", "Result", vng.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkListResult response for the ListVirtualNetworks API service call. -type VirtualNetworkListResult struct { - autorest.Response `json:"-"` - // Value - Gets a list of VirtualNetwork resources in a resource group. - Value *[]VirtualNetwork `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualNetworkListResultIterator provides access to a complete listing of VirtualNetwork values. -type VirtualNetworkListResultIterator struct { - i int - page VirtualNetworkListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkListResultIterator) Response() VirtualNetworkListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkListResultIterator) Value() VirtualNetwork { - if !iter.page.NotDone() { - return VirtualNetwork{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkListResultIterator type. -func NewVirtualNetworkListResultIterator(page VirtualNetworkListResultPage) VirtualNetworkListResultIterator { - return VirtualNetworkListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnlr VirtualNetworkListResult) IsEmpty() bool { - return vnlr.Value == nil || len(*vnlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnlr VirtualNetworkListResult) hasNextLink() bool { - return vnlr.NextLink != nil && len(*vnlr.NextLink) != 0 -} - -// virtualNetworkListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnlr VirtualNetworkListResult) virtualNetworkListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnlr.NextLink))) -} - -// VirtualNetworkListResultPage contains a page of VirtualNetwork values. -type VirtualNetworkListResultPage struct { - fn func(context.Context, VirtualNetworkListResult) (VirtualNetworkListResult, error) - vnlr VirtualNetworkListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnlr) - if err != nil { - return err - } - page.vnlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkListResultPage) NotDone() bool { - return !page.vnlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkListResultPage) Response() VirtualNetworkListResult { - return page.vnlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkListResultPage) Values() []VirtualNetwork { - if page.vnlr.IsEmpty() { - return nil - } - return *page.vnlr.Value -} - -// Creates a new instance of the VirtualNetworkListResultPage type. -func NewVirtualNetworkListResultPage(cur VirtualNetworkListResult, getNextPage func(context.Context, VirtualNetworkListResult) (VirtualNetworkListResult, error)) VirtualNetworkListResultPage { - return VirtualNetworkListResultPage{ - fn: getNextPage, - vnlr: cur, - } -} - -// VirtualNetworkListUsageResult response for the virtual networks GetUsage API service call. -type VirtualNetworkListUsageResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; VirtualNetwork usage stats. - Value *[]VirtualNetworkUsage `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkListUsageResult. -func (vnlur VirtualNetworkListUsageResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnlur.NextLink != nil { - objectMap["nextLink"] = vnlur.NextLink - } - return json.Marshal(objectMap) -} - -// VirtualNetworkListUsageResultIterator provides access to a complete listing of VirtualNetworkUsage -// values. -type VirtualNetworkListUsageResultIterator struct { - i int - page VirtualNetworkListUsageResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkListUsageResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListUsageResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkListUsageResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkListUsageResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkListUsageResultIterator) Response() VirtualNetworkListUsageResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkListUsageResultIterator) Value() VirtualNetworkUsage { - if !iter.page.NotDone() { - return VirtualNetworkUsage{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkListUsageResultIterator type. -func NewVirtualNetworkListUsageResultIterator(page VirtualNetworkListUsageResultPage) VirtualNetworkListUsageResultIterator { - return VirtualNetworkListUsageResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnlur VirtualNetworkListUsageResult) IsEmpty() bool { - return vnlur.Value == nil || len(*vnlur.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnlur VirtualNetworkListUsageResult) hasNextLink() bool { - return vnlur.NextLink != nil && len(*vnlur.NextLink) != 0 -} - -// virtualNetworkListUsageResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnlur VirtualNetworkListUsageResult) virtualNetworkListUsageResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnlur.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnlur.NextLink))) -} - -// VirtualNetworkListUsageResultPage contains a page of VirtualNetworkUsage values. -type VirtualNetworkListUsageResultPage struct { - fn func(context.Context, VirtualNetworkListUsageResult) (VirtualNetworkListUsageResult, error) - vnlur VirtualNetworkListUsageResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkListUsageResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListUsageResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnlur) - if err != nil { - return err - } - page.vnlur = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkListUsageResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkListUsageResultPage) NotDone() bool { - return !page.vnlur.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkListUsageResultPage) Response() VirtualNetworkListUsageResult { - return page.vnlur -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkListUsageResultPage) Values() []VirtualNetworkUsage { - if page.vnlur.IsEmpty() { - return nil - } - return *page.vnlur.Value -} - -// Creates a new instance of the VirtualNetworkListUsageResultPage type. -func NewVirtualNetworkListUsageResultPage(cur VirtualNetworkListUsageResult, getNextPage func(context.Context, VirtualNetworkListUsageResult) (VirtualNetworkListUsageResult, error)) VirtualNetworkListUsageResultPage { - return VirtualNetworkListUsageResultPage{ - fn: getNextPage, - vnlur: cur, - } -} - -// VirtualNetworkPeering peerings in a virtual network resource. -type VirtualNetworkPeering struct { - autorest.Response `json:"-"` - // VirtualNetworkPeeringPropertiesFormat - Properties of the virtual network peering. - *VirtualNetworkPeeringPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkPeering. -func (vnp VirtualNetworkPeering) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnp.VirtualNetworkPeeringPropertiesFormat != nil { - objectMap["properties"] = vnp.VirtualNetworkPeeringPropertiesFormat - } - if vnp.Name != nil { - objectMap["name"] = vnp.Name - } - if vnp.Etag != nil { - objectMap["etag"] = vnp.Etag - } - if vnp.ID != nil { - objectMap["id"] = vnp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkPeering struct. -func (vnp *VirtualNetworkPeering) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkPeeringPropertiesFormat VirtualNetworkPeeringPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkPeeringPropertiesFormat) - if err != nil { - return err - } - vnp.VirtualNetworkPeeringPropertiesFormat = &virtualNetworkPeeringPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vnp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vnp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vnp.ID = &ID - } - } - } - - return nil -} - -// VirtualNetworkPeeringListResult response for ListSubnets API service call. Retrieves all subnets that -// belong to a virtual network. -type VirtualNetworkPeeringListResult struct { - autorest.Response `json:"-"` - // Value - The peerings in a virtual network. - Value *[]VirtualNetworkPeering `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualNetworkPeeringListResultIterator provides access to a complete listing of VirtualNetworkPeering -// values. -type VirtualNetworkPeeringListResultIterator struct { - i int - page VirtualNetworkPeeringListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkPeeringListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkPeeringListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkPeeringListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkPeeringListResultIterator) Response() VirtualNetworkPeeringListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkPeeringListResultIterator) Value() VirtualNetworkPeering { - if !iter.page.NotDone() { - return VirtualNetworkPeering{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkPeeringListResultIterator type. -func NewVirtualNetworkPeeringListResultIterator(page VirtualNetworkPeeringListResultPage) VirtualNetworkPeeringListResultIterator { - return VirtualNetworkPeeringListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnplr VirtualNetworkPeeringListResult) IsEmpty() bool { - return vnplr.Value == nil || len(*vnplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnplr VirtualNetworkPeeringListResult) hasNextLink() bool { - return vnplr.NextLink != nil && len(*vnplr.NextLink) != 0 -} - -// virtualNetworkPeeringListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnplr VirtualNetworkPeeringListResult) virtualNetworkPeeringListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnplr.NextLink))) -} - -// VirtualNetworkPeeringListResultPage contains a page of VirtualNetworkPeering values. -type VirtualNetworkPeeringListResultPage struct { - fn func(context.Context, VirtualNetworkPeeringListResult) (VirtualNetworkPeeringListResult, error) - vnplr VirtualNetworkPeeringListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkPeeringListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnplr) - if err != nil { - return err - } - page.vnplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkPeeringListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkPeeringListResultPage) NotDone() bool { - return !page.vnplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkPeeringListResultPage) Response() VirtualNetworkPeeringListResult { - return page.vnplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkPeeringListResultPage) Values() []VirtualNetworkPeering { - if page.vnplr.IsEmpty() { - return nil - } - return *page.vnplr.Value -} - -// Creates a new instance of the VirtualNetworkPeeringListResultPage type. -func NewVirtualNetworkPeeringListResultPage(cur VirtualNetworkPeeringListResult, getNextPage func(context.Context, VirtualNetworkPeeringListResult) (VirtualNetworkPeeringListResult, error)) VirtualNetworkPeeringListResultPage { - return VirtualNetworkPeeringListResultPage{ - fn: getNextPage, - vnplr: cur, - } -} - -// VirtualNetworkPeeringPropertiesFormat properties of the virtual network peering. -type VirtualNetworkPeeringPropertiesFormat struct { - // AllowVirtualNetworkAccess - Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virtual network space. - AllowVirtualNetworkAccess *bool `json:"allowVirtualNetworkAccess,omitempty"` - // AllowForwardedTraffic - Whether the forwarded traffic from the VMs in the remote virtual network will be allowed/disallowed. - AllowForwardedTraffic *bool `json:"allowForwardedTraffic,omitempty"` - // AllowGatewayTransit - If gateway links can be used in remote virtual networking to link to this virtual network. - AllowGatewayTransit *bool `json:"allowGatewayTransit,omitempty"` - // UseRemoteGateways - If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. - UseRemoteGateways *bool `json:"useRemoteGateways,omitempty"` - // RemoteVirtualNetwork - The reference of the remote virtual network. The remote virtual network can be in the same or different region (preview). See here to register for the preview and learn more (https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering). - RemoteVirtualNetwork *SubResource `json:"remoteVirtualNetwork,omitempty"` - // RemoteAddressSpace - The reference of the remote virtual network address space. - RemoteAddressSpace *AddressSpace `json:"remoteAddressSpace,omitempty"` - // PeeringState - The status of the virtual network peering. Possible values are 'Initiated', 'Connected', and 'Disconnected'. Possible values include: 'VirtualNetworkPeeringStateInitiated', 'VirtualNetworkPeeringStateConnected', 'VirtualNetworkPeeringStateDisconnected' - PeeringState VirtualNetworkPeeringState `json:"peeringState,omitempty"` - // ProvisioningState - The provisioning state of the resource. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// VirtualNetworkPeeringsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkPeeringsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkPeeringsClient) (VirtualNetworkPeering, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkPeeringsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkPeeringsCreateOrUpdateFuture.Result. -func (future *VirtualNetworkPeeringsCreateOrUpdateFuture) result(client VirtualNetworkPeeringsClient) (vnp VirtualNetworkPeering, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vnp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkPeeringsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vnp.Response.Response, err = future.GetResult(sender); err == nil && vnp.Response.Response.StatusCode != http.StatusNoContent { - vnp, err = client.CreateOrUpdateResponder(vnp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsCreateOrUpdateFuture", "Result", vnp.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkPeeringsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkPeeringsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkPeeringsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkPeeringsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkPeeringsDeleteFuture.Result. -func (future *VirtualNetworkPeeringsDeleteFuture) result(client VirtualNetworkPeeringsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkPeeringsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkPropertiesFormat properties of the virtual network. -type VirtualNetworkPropertiesFormat struct { - // AddressSpace - The AddressSpace that contains an array of IP address ranges that can be used by subnets. - AddressSpace *AddressSpace `json:"addressSpace,omitempty"` - // DhcpOptions - The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network. - DhcpOptions *DhcpOptions `json:"dhcpOptions,omitempty"` - // Subnets - A list of subnets in a Virtual Network. - Subnets *[]Subnet `json:"subnets,omitempty"` - // VirtualNetworkPeerings - A list of peerings in a Virtual Network. - VirtualNetworkPeerings *[]VirtualNetworkPeering `json:"virtualNetworkPeerings,omitempty"` - // ResourceGUID - The resourceGuid property of the Virtual Network resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // EnableDdosProtection - Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource. - EnableDdosProtection *bool `json:"enableDdosProtection,omitempty"` - // EnableVMProtection - Indicates if VM protection is enabled for all the subnets in the virtual network. - EnableVMProtection *bool `json:"enableVmProtection,omitempty"` - // DdosProtectionPlan - The DDoS protection plan associated with the virtual network. - DdosProtectionPlan *SubResource `json:"ddosProtectionPlan,omitempty"` -} - -// VirtualNetworksCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworksCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworksClient) (VirtualNetwork, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworksCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworksCreateOrUpdateFuture.Result. -func (future *VirtualNetworksCreateOrUpdateFuture) result(client VirtualNetworksClient) (vn VirtualNetwork, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vn.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworksCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vn.Response.Response, err = future.GetResult(sender); err == nil && vn.Response.Response.StatusCode != http.StatusNoContent { - vn, err = client.CreateOrUpdateResponder(vn.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksCreateOrUpdateFuture", "Result", vn.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworksDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualNetworksDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworksClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworksDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworksDeleteFuture.Result. -func (future *VirtualNetworksDeleteFuture) result(client VirtualNetworksClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworksDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworksUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworksUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworksClient) (VirtualNetwork, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworksUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworksUpdateTagsFuture.Result. -func (future *VirtualNetworksUpdateTagsFuture) result(client VirtualNetworksClient) (vn VirtualNetwork, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vn.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworksUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vn.Response.Response, err = future.GetResult(sender); err == nil && vn.Response.Response.StatusCode != http.StatusNoContent { - vn, err = client.UpdateTagsResponder(vn.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksUpdateTagsFuture", "Result", vn.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkTap virtual Network Tap resource -type VirtualNetworkTap struct { - autorest.Response `json:"-"` - // VirtualNetworkTapPropertiesFormat - Virtual Network Tap Properties. - *VirtualNetworkTapPropertiesFormat `json:"properties,omitempty"` - // Etag - Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkTap. -func (vnt VirtualNetworkTap) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnt.VirtualNetworkTapPropertiesFormat != nil { - objectMap["properties"] = vnt.VirtualNetworkTapPropertiesFormat - } - if vnt.Etag != nil { - objectMap["etag"] = vnt.Etag - } - if vnt.ID != nil { - objectMap["id"] = vnt.ID - } - if vnt.Location != nil { - objectMap["location"] = vnt.Location - } - if vnt.Tags != nil { - objectMap["tags"] = vnt.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkTap struct. -func (vnt *VirtualNetworkTap) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkTapPropertiesFormat VirtualNetworkTapPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkTapPropertiesFormat) - if err != nil { - return err - } - vnt.VirtualNetworkTapPropertiesFormat = &virtualNetworkTapPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vnt.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vnt.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vnt.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vnt.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vnt.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vnt.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkTapListResult response for ListVirtualNetworkTap API service call. -type VirtualNetworkTapListResult struct { - autorest.Response `json:"-"` - // Value - A list of VirtualNetworkTaps in a resource group. - Value *[]VirtualNetworkTap `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualNetworkTapListResultIterator provides access to a complete listing of VirtualNetworkTap values. -type VirtualNetworkTapListResultIterator struct { - i int - page VirtualNetworkTapListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkTapListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkTapListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkTapListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkTapListResultIterator) Response() VirtualNetworkTapListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkTapListResultIterator) Value() VirtualNetworkTap { - if !iter.page.NotDone() { - return VirtualNetworkTap{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkTapListResultIterator type. -func NewVirtualNetworkTapListResultIterator(page VirtualNetworkTapListResultPage) VirtualNetworkTapListResultIterator { - return VirtualNetworkTapListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vntlr VirtualNetworkTapListResult) IsEmpty() bool { - return vntlr.Value == nil || len(*vntlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vntlr VirtualNetworkTapListResult) hasNextLink() bool { - return vntlr.NextLink != nil && len(*vntlr.NextLink) != 0 -} - -// virtualNetworkTapListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vntlr VirtualNetworkTapListResult) virtualNetworkTapListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vntlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vntlr.NextLink))) -} - -// VirtualNetworkTapListResultPage contains a page of VirtualNetworkTap values. -type VirtualNetworkTapListResultPage struct { - fn func(context.Context, VirtualNetworkTapListResult) (VirtualNetworkTapListResult, error) - vntlr VirtualNetworkTapListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkTapListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vntlr) - if err != nil { - return err - } - page.vntlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkTapListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkTapListResultPage) NotDone() bool { - return !page.vntlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkTapListResultPage) Response() VirtualNetworkTapListResult { - return page.vntlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkTapListResultPage) Values() []VirtualNetworkTap { - if page.vntlr.IsEmpty() { - return nil - } - return *page.vntlr.Value -} - -// Creates a new instance of the VirtualNetworkTapListResultPage type. -func NewVirtualNetworkTapListResultPage(cur VirtualNetworkTapListResult, getNextPage func(context.Context, VirtualNetworkTapListResult) (VirtualNetworkTapListResult, error)) VirtualNetworkTapListResultPage { - return VirtualNetworkTapListResultPage{ - fn: getNextPage, - vntlr: cur, - } -} - -// VirtualNetworkTapPropertiesFormat virtual Network Tap properties. -type VirtualNetworkTapPropertiesFormat struct { - // NetworkInterfaceTapConfigurations - READ-ONLY; Specifies the list of resource IDs for the network interface IP configuration that needs to be tapped. - NetworkInterfaceTapConfigurations *[]InterfaceTapConfiguration `json:"networkInterfaceTapConfigurations,omitempty"` - // ResourceGUID - READ-ONLY; The resourceGuid property of the virtual network tap. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network tap. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // DestinationNetworkInterfaceIPConfiguration - The reference to the private IP Address of the collector nic that will receive the tap - DestinationNetworkInterfaceIPConfiguration *InterfaceIPConfiguration `json:"destinationNetworkInterfaceIPConfiguration,omitempty"` - // DestinationLoadBalancerFrontEndIPConfiguration - The reference to the private IP address on the internal Load Balancer that will receive the tap - DestinationLoadBalancerFrontEndIPConfiguration *FrontendIPConfiguration `json:"destinationLoadBalancerFrontEndIPConfiguration,omitempty"` - // DestinationPort - The VXLAN destination port that will receive the tapped traffic. - DestinationPort *int32 `json:"destinationPort,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkTapPropertiesFormat. -func (vntpf VirtualNetworkTapPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vntpf.DestinationNetworkInterfaceIPConfiguration != nil { - objectMap["destinationNetworkInterfaceIPConfiguration"] = vntpf.DestinationNetworkInterfaceIPConfiguration - } - if vntpf.DestinationLoadBalancerFrontEndIPConfiguration != nil { - objectMap["destinationLoadBalancerFrontEndIPConfiguration"] = vntpf.DestinationLoadBalancerFrontEndIPConfiguration - } - if vntpf.DestinationPort != nil { - objectMap["destinationPort"] = vntpf.DestinationPort - } - return json.Marshal(objectMap) -} - -// VirtualNetworkTapsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkTapsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkTapsClient) (VirtualNetworkTap, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkTapsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkTapsCreateOrUpdateFuture.Result. -func (future *VirtualNetworkTapsCreateOrUpdateFuture) result(client VirtualNetworkTapsClient) (vnt VirtualNetworkTap, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vnt.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkTapsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vnt.Response.Response, err = future.GetResult(sender); err == nil && vnt.Response.Response.StatusCode != http.StatusNoContent { - vnt, err = client.CreateOrUpdateResponder(vnt.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsCreateOrUpdateFuture", "Result", vnt.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkTapsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkTapsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkTapsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkTapsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkTapsDeleteFuture.Result. -func (future *VirtualNetworkTapsDeleteFuture) result(client VirtualNetworkTapsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkTapsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkTapsUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkTapsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkTapsClient) (VirtualNetworkTap, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkTapsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkTapsUpdateTagsFuture.Result. -func (future *VirtualNetworkTapsUpdateTagsFuture) result(client VirtualNetworkTapsClient) (vnt VirtualNetworkTap, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vnt.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkTapsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vnt.Response.Response, err = future.GetResult(sender); err == nil && vnt.Response.Response.StatusCode != http.StatusNoContent { - vnt, err = client.UpdateTagsResponder(vnt.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsUpdateTagsFuture", "Result", vnt.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkUsage usage details for subnet. -type VirtualNetworkUsage struct { - // CurrentValue - READ-ONLY; Indicates number of IPs used from the Subnet. - CurrentValue *float64 `json:"currentValue,omitempty"` - // ID - READ-ONLY; Subnet identifier. - ID *string `json:"id,omitempty"` - // Limit - READ-ONLY; Indicates the size of the subnet. - Limit *float64 `json:"limit,omitempty"` - // Name - READ-ONLY; The name containing common and localized value for usage. - Name *VirtualNetworkUsageName `json:"name,omitempty"` - // Unit - READ-ONLY; Usage units. Returns 'Count' - Unit *string `json:"unit,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkUsage. -func (vnu VirtualNetworkUsage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualNetworkUsageName usage strings container. -type VirtualNetworkUsageName struct { - // LocalizedValue - READ-ONLY; Localized subnet size and usage string. - LocalizedValue *string `json:"localizedValue,omitempty"` - // Value - READ-ONLY; Subnet size and usage string. - Value *string `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkUsageName. -func (vnun VirtualNetworkUsageName) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualWAN virtualWAN Resource. -type VirtualWAN struct { - autorest.Response `json:"-"` - *VirtualWanProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualWAN. -func (vw VirtualWAN) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vw.VirtualWanProperties != nil { - objectMap["properties"] = vw.VirtualWanProperties - } - if vw.ID != nil { - objectMap["id"] = vw.ID - } - if vw.Location != nil { - objectMap["location"] = vw.Location - } - if vw.Tags != nil { - objectMap["tags"] = vw.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualWAN struct. -func (vw *VirtualWAN) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualWanProperties VirtualWanProperties - err = json.Unmarshal(*v, &virtualWanProperties) - if err != nil { - return err - } - vw.VirtualWanProperties = &virtualWanProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vw.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vw.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vw.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vw.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vw.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vw.Tags = tags - } - } - } - - return nil -} - -// VirtualWanProperties parameters for VirtualWAN -type VirtualWanProperties struct { - // DisableVpnEncryption - Vpn encryption to be disabled or not. - DisableVpnEncryption *bool `json:"disableVpnEncryption,omitempty"` - // VirtualHubs - READ-ONLY; List of VirtualHubs in the VirtualWAN. - VirtualHubs *[]SubResource `json:"virtualHubs,omitempty"` - // VpnSites - READ-ONLY - VpnSites *[]SubResource `json:"vpnSites,omitempty"` - // SecurityProviderName - The Security Provider name. - SecurityProviderName *string `json:"securityProviderName,omitempty"` - // AllowBranchToBranchTraffic - True if branch to branch traffic is allowed. - AllowBranchToBranchTraffic *bool `json:"allowBranchToBranchTraffic,omitempty"` - // AllowVnetToVnetTraffic - True if Vnet to Vnet traffic is allowed. - AllowVnetToVnetTraffic *bool `json:"allowVnetToVnetTraffic,omitempty"` - // Office365LocalBreakoutCategory - The office local breakout category. Possible values include: 'OfficeTrafficCategoryOptimize', 'OfficeTrafficCategoryOptimizeAndAllow', 'OfficeTrafficCategoryAll', 'OfficeTrafficCategoryNone' - Office365LocalBreakoutCategory OfficeTrafficCategory `json:"office365LocalBreakoutCategory,omitempty"` - // P2SVpnServerConfigurations - list of all P2SVpnServerConfigurations associated with the virtual wan. - P2SVpnServerConfigurations *[]P2SVpnServerConfiguration `json:"p2SVpnServerConfigurations,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualWanProperties. -func (vwp VirtualWanProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vwp.DisableVpnEncryption != nil { - objectMap["disableVpnEncryption"] = vwp.DisableVpnEncryption - } - if vwp.SecurityProviderName != nil { - objectMap["securityProviderName"] = vwp.SecurityProviderName - } - if vwp.AllowBranchToBranchTraffic != nil { - objectMap["allowBranchToBranchTraffic"] = vwp.AllowBranchToBranchTraffic - } - if vwp.AllowVnetToVnetTraffic != nil { - objectMap["allowVnetToVnetTraffic"] = vwp.AllowVnetToVnetTraffic - } - if vwp.Office365LocalBreakoutCategory != "" { - objectMap["office365LocalBreakoutCategory"] = vwp.Office365LocalBreakoutCategory - } - if vwp.P2SVpnServerConfigurations != nil { - objectMap["p2SVpnServerConfigurations"] = vwp.P2SVpnServerConfigurations - } - if vwp.ProvisioningState != "" { - objectMap["provisioningState"] = vwp.ProvisioningState - } - return json.Marshal(objectMap) -} - -// VirtualWansCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualWansCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualWansClient) (VirtualWAN, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualWansCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualWansCreateOrUpdateFuture.Result. -func (future *VirtualWansCreateOrUpdateFuture) result(client VirtualWansClient) (vw VirtualWAN, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vw.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualWansCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vw.Response.Response, err = future.GetResult(sender); err == nil && vw.Response.Response.StatusCode != http.StatusNoContent { - vw, err = client.CreateOrUpdateResponder(vw.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansCreateOrUpdateFuture", "Result", vw.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualWansDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualWansDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualWansClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualWansDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualWansDeleteFuture.Result. -func (future *VirtualWansDeleteFuture) result(client VirtualWansClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualWansDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualWanSecurityProvider collection of SecurityProviders. -type VirtualWanSecurityProvider struct { - // Name - Name of the security provider. - Name *string `json:"name,omitempty"` - // URL - Url of the security provider. - URL *string `json:"url,omitempty"` - // Type - Name of the security provider. Possible values include: 'External', 'Native' - Type VirtualWanSecurityProviderType `json:"type,omitempty"` -} - -// VirtualWanSecurityProviders collection of SecurityProviders. -type VirtualWanSecurityProviders struct { - autorest.Response `json:"-"` - SupportedProviders *[]VirtualWanSecurityProvider `json:"supportedProviders,omitempty"` -} - -// VirtualWansUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualWansUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualWansClient) (VirtualWAN, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualWansUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualWansUpdateTagsFuture.Result. -func (future *VirtualWansUpdateTagsFuture) result(client VirtualWansClient) (vw VirtualWAN, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vw.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualWansUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vw.Response.Response, err = future.GetResult(sender); err == nil && vw.Response.Response.StatusCode != http.StatusNoContent { - vw, err = client.UpdateTagsResponder(vw.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansUpdateTagsFuture", "Result", vw.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnClientConfiguration vpnClientConfiguration for P2S client. -type VpnClientConfiguration struct { - // VpnClientAddressPool - The reference of the address space resource which represents Address space for P2S VpnClient. - VpnClientAddressPool *AddressSpace `json:"vpnClientAddressPool,omitempty"` - // VpnClientRootCertificates - VpnClientRootCertificate for virtual network gateway. - VpnClientRootCertificates *[]VpnClientRootCertificate `json:"vpnClientRootCertificates,omitempty"` - // VpnClientRevokedCertificates - VpnClientRevokedCertificate for Virtual network gateway. - VpnClientRevokedCertificates *[]VpnClientRevokedCertificate `json:"vpnClientRevokedCertificates,omitempty"` - // VpnClientProtocols - VpnClientProtocols for Virtual network gateway. - VpnClientProtocols *[]VpnClientProtocol `json:"vpnClientProtocols,omitempty"` - // VpnClientIpsecPolicies - VpnClientIpsecPolicies for virtual network gateway P2S client. - VpnClientIpsecPolicies *[]IpsecPolicy `json:"vpnClientIpsecPolicies,omitempty"` - // RadiusServerAddress - The radius server address property of the VirtualNetworkGateway resource for vpn client connection. - RadiusServerAddress *string `json:"radiusServerAddress,omitempty"` - // RadiusServerSecret - The radius secret property of the VirtualNetworkGateway resource for vpn client connection. - RadiusServerSecret *string `json:"radiusServerSecret,omitempty"` -} - -// VpnClientConnectionHealth vpnClientConnectionHealth properties -type VpnClientConnectionHealth struct { - // TotalIngressBytesTransferred - READ-ONLY; Total of the Ingress Bytes Transferred in this P2S Vpn connection - TotalIngressBytesTransferred *int64 `json:"totalIngressBytesTransferred,omitempty"` - // TotalEgressBytesTransferred - READ-ONLY; Total of the Egress Bytes Transferred in this connection - TotalEgressBytesTransferred *int64 `json:"totalEgressBytesTransferred,omitempty"` - // VpnClientConnectionsCount - The total of p2s vpn clients connected at this time to this P2SVpnGateway. - VpnClientConnectionsCount *int32 `json:"vpnClientConnectionsCount,omitempty"` - // AllocatedIPAddresses - List of allocated ip addresses to the connected p2s vpn clients. - AllocatedIPAddresses *[]string `json:"allocatedIpAddresses,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientConnectionHealth. -func (vcch VpnClientConnectionHealth) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcch.VpnClientConnectionsCount != nil { - objectMap["vpnClientConnectionsCount"] = vcch.VpnClientConnectionsCount - } - if vcch.AllocatedIPAddresses != nil { - objectMap["allocatedIpAddresses"] = vcch.AllocatedIPAddresses - } - return json.Marshal(objectMap) -} - -// VpnClientIPsecParameters an IPSec parameters for a virtual network gateway P2S connection. -type VpnClientIPsecParameters struct { - autorest.Response `json:"-"` - // SaLifeTimeSeconds - The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for P2S client. - SaLifeTimeSeconds *int32 `json:"saLifeTimeSeconds,omitempty"` - // SaDataSizeKilobytes - The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for P2S client.. - SaDataSizeKilobytes *int32 `json:"saDataSizeKilobytes,omitempty"` - // IpsecEncryption - The IPSec encryption algorithm (IKE phase 1). Possible values include: 'IpsecEncryptionNone', 'IpsecEncryptionDES', 'IpsecEncryptionDES3', 'IpsecEncryptionAES128', 'IpsecEncryptionAES192', 'IpsecEncryptionAES256', 'IpsecEncryptionGCMAES128', 'IpsecEncryptionGCMAES192', 'IpsecEncryptionGCMAES256' - IpsecEncryption IpsecEncryption `json:"ipsecEncryption,omitempty"` - // IpsecIntegrity - The IPSec integrity algorithm (IKE phase 1). Possible values include: 'IpsecIntegrityMD5', 'IpsecIntegritySHA1', 'IpsecIntegritySHA256', 'IpsecIntegrityGCMAES128', 'IpsecIntegrityGCMAES192', 'IpsecIntegrityGCMAES256' - IpsecIntegrity IpsecIntegrity `json:"ipsecIntegrity,omitempty"` - // IkeEncryption - The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES256', 'GCMAES128' - IkeEncryption IkeEncryption `json:"ikeEncryption,omitempty"` - // IkeIntegrity - The IKE integrity algorithm (IKE phase 2). Possible values include: 'IkeIntegrityMD5', 'IkeIntegritySHA1', 'IkeIntegritySHA256', 'IkeIntegritySHA384', 'IkeIntegrityGCMAES256', 'IkeIntegrityGCMAES128' - IkeIntegrity IkeIntegrity `json:"ikeIntegrity,omitempty"` - // DhGroup - The DH Groups used in IKE Phase 1 for initial SA. Possible values include: 'None', 'DHGroup1', 'DHGroup2', 'DHGroup14', 'DHGroup2048', 'ECP256', 'ECP384', 'DHGroup24' - DhGroup DhGroup `json:"dhGroup,omitempty"` - // PfsGroup - The Pfs Groups used in IKE Phase 2 for new child SA. Possible values include: 'PfsGroupNone', 'PfsGroupPFS1', 'PfsGroupPFS2', 'PfsGroupPFS2048', 'PfsGroupECP256', 'PfsGroupECP384', 'PfsGroupPFS24', 'PfsGroupPFS14', 'PfsGroupPFSMM' - PfsGroup PfsGroup `json:"pfsGroup,omitempty"` -} - -// VpnClientParameters vpn Client Parameters for package generation -type VpnClientParameters struct { - // ProcessorArchitecture - VPN client Processor Architecture. Possible values are: 'AMD64' and 'X86'. Possible values include: 'Amd64', 'X86' - ProcessorArchitecture ProcessorArchitecture `json:"processorArchitecture,omitempty"` - // AuthenticationMethod - VPN client Authentication Method. Possible values are: 'EAPTLS' and 'EAPMSCHAPv2'. Possible values include: 'EAPTLS', 'EAPMSCHAPv2' - AuthenticationMethod AuthenticationMethod `json:"authenticationMethod,omitempty"` - // RadiusServerAuthCertificate - The public certificate data for the radius server authentication certificate as a Base-64 encoded string. Required only if external radius authentication has been configured with EAPTLS authentication. - RadiusServerAuthCertificate *string `json:"radiusServerAuthCertificate,omitempty"` - // ClientRootCertificates - A list of client root certificates public certificate data encoded as Base-64 strings. Optional parameter for external radius based authentication with EAPTLS. - ClientRootCertificates *[]string `json:"clientRootCertificates,omitempty"` -} - -// VpnClientRevokedCertificate VPN client revoked certificate of virtual network gateway. -type VpnClientRevokedCertificate struct { - // VpnClientRevokedCertificatePropertiesFormat - Properties of the vpn client revoked certificate. - *VpnClientRevokedCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRevokedCertificate. -func (vcrc VpnClientRevokedCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrc.VpnClientRevokedCertificatePropertiesFormat != nil { - objectMap["properties"] = vcrc.VpnClientRevokedCertificatePropertiesFormat - } - if vcrc.Name != nil { - objectMap["name"] = vcrc.Name - } - if vcrc.Etag != nil { - objectMap["etag"] = vcrc.Etag - } - if vcrc.ID != nil { - objectMap["id"] = vcrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnClientRevokedCertificate struct. -func (vcrc *VpnClientRevokedCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnClientRevokedCertificatePropertiesFormat VpnClientRevokedCertificatePropertiesFormat - err = json.Unmarshal(*v, &vpnClientRevokedCertificatePropertiesFormat) - if err != nil { - return err - } - vcrc.VpnClientRevokedCertificatePropertiesFormat = &vpnClientRevokedCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vcrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vcrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vcrc.ID = &ID - } - } - } - - return nil -} - -// VpnClientRevokedCertificatePropertiesFormat properties of the revoked VPN client certificate of virtual -// network gateway. -type VpnClientRevokedCertificatePropertiesFormat struct { - // Thumbprint - The revoked VPN client certificate thumbprint. - Thumbprint *string `json:"thumbprint,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN client revoked certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRevokedCertificatePropertiesFormat. -func (vcrcpf VpnClientRevokedCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrcpf.Thumbprint != nil { - objectMap["thumbprint"] = vcrcpf.Thumbprint - } - return json.Marshal(objectMap) -} - -// VpnClientRootCertificate VPN client root certificate of virtual network gateway -type VpnClientRootCertificate struct { - // VpnClientRootCertificatePropertiesFormat - Properties of the vpn client root certificate. - *VpnClientRootCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRootCertificate. -func (vcrc VpnClientRootCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrc.VpnClientRootCertificatePropertiesFormat != nil { - objectMap["properties"] = vcrc.VpnClientRootCertificatePropertiesFormat - } - if vcrc.Name != nil { - objectMap["name"] = vcrc.Name - } - if vcrc.Etag != nil { - objectMap["etag"] = vcrc.Etag - } - if vcrc.ID != nil { - objectMap["id"] = vcrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnClientRootCertificate struct. -func (vcrc *VpnClientRootCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnClientRootCertificatePropertiesFormat VpnClientRootCertificatePropertiesFormat - err = json.Unmarshal(*v, &vpnClientRootCertificatePropertiesFormat) - if err != nil { - return err - } - vcrc.VpnClientRootCertificatePropertiesFormat = &vpnClientRootCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vcrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vcrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vcrc.ID = &ID - } - } - } - - return nil -} - -// VpnClientRootCertificatePropertiesFormat properties of SSL certificates of application gateway -type VpnClientRootCertificatePropertiesFormat struct { - // PublicCertData - The certificate public data. - PublicCertData *string `json:"publicCertData,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRootCertificatePropertiesFormat. -func (vcrcpf VpnClientRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrcpf.PublicCertData != nil { - objectMap["publicCertData"] = vcrcpf.PublicCertData - } - return json.Marshal(objectMap) -} - -// VpnConnection vpnConnection Resource. -type VpnConnection struct { - autorest.Response `json:"-"` - *VpnConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnConnection. -func (vc VpnConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vc.VpnConnectionProperties != nil { - objectMap["properties"] = vc.VpnConnectionProperties - } - if vc.Name != nil { - objectMap["name"] = vc.Name - } - if vc.ID != nil { - objectMap["id"] = vc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnConnection struct. -func (vc *VpnConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnConnectionProperties VpnConnectionProperties - err = json.Unmarshal(*v, &vpnConnectionProperties) - if err != nil { - return err - } - vc.VpnConnectionProperties = &vpnConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vc.ID = &ID - } - } - } - - return nil -} - -// VpnConnectionProperties parameters for VpnConnection -type VpnConnectionProperties struct { - // RemoteVpnSite - Id of the connected vpn site. - RemoteVpnSite *SubResource `json:"remoteVpnSite,omitempty"` - // RoutingWeight - routing weight for vpn connection. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // ConnectionStatus - The connection status. Possible values include: 'VpnConnectionStatusUnknown', 'VpnConnectionStatusConnecting', 'VpnConnectionStatusConnected', 'VpnConnectionStatusNotConnected' - ConnectionStatus VpnConnectionStatus `json:"connectionStatus,omitempty"` - // VpnConnectionProtocolType - Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' - VpnConnectionProtocolType VirtualNetworkGatewayConnectionProtocol `json:"vpnConnectionProtocolType,omitempty"` - // IngressBytesTransferred - READ-ONLY; Ingress bytes transferred. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // EgressBytesTransferred - READ-ONLY; Egress bytes transferred. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // ConnectionBandwidth - Expected bandwidth in MBPS. - ConnectionBandwidth *int32 `json:"connectionBandwidth,omitempty"` - // SharedKey - SharedKey for the vpn connection. - SharedKey *string `json:"sharedKey,omitempty"` - // EnableBgp - EnableBgp flag - EnableBgp *bool `json:"enableBgp,omitempty"` - // IpsecPolicies - The IPSec Policies to be considered by this connection. - IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` - // EnableRateLimiting - EnableBgp flag - EnableRateLimiting *bool `json:"enableRateLimiting,omitempty"` - // EnableInternetSecurity - Enable internet security - EnableInternetSecurity *bool `json:"enableInternetSecurity,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnConnectionProperties. -func (vcp VpnConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcp.RemoteVpnSite != nil { - objectMap["remoteVpnSite"] = vcp.RemoteVpnSite - } - if vcp.RoutingWeight != nil { - objectMap["routingWeight"] = vcp.RoutingWeight - } - if vcp.ConnectionStatus != "" { - objectMap["connectionStatus"] = vcp.ConnectionStatus - } - if vcp.VpnConnectionProtocolType != "" { - objectMap["vpnConnectionProtocolType"] = vcp.VpnConnectionProtocolType - } - if vcp.ConnectionBandwidth != nil { - objectMap["connectionBandwidth"] = vcp.ConnectionBandwidth - } - if vcp.SharedKey != nil { - objectMap["sharedKey"] = vcp.SharedKey - } - if vcp.EnableBgp != nil { - objectMap["enableBgp"] = vcp.EnableBgp - } - if vcp.IpsecPolicies != nil { - objectMap["ipsecPolicies"] = vcp.IpsecPolicies - } - if vcp.EnableRateLimiting != nil { - objectMap["enableRateLimiting"] = vcp.EnableRateLimiting - } - if vcp.EnableInternetSecurity != nil { - objectMap["enableInternetSecurity"] = vcp.EnableInternetSecurity - } - if vcp.ProvisioningState != "" { - objectMap["provisioningState"] = vcp.ProvisioningState - } - return json.Marshal(objectMap) -} - -// VpnConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnConnectionsClient) (VpnConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnConnectionsCreateOrUpdateFuture.Result. -func (future *VpnConnectionsCreateOrUpdateFuture) result(client VpnConnectionsClient) (vc VpnConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vc.Response.Response, err = future.GetResult(sender); err == nil && vc.Response.Response.StatusCode != http.StatusNoContent { - vc, err = client.CreateOrUpdateResponder(vc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsCreateOrUpdateFuture", "Result", vc.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnConnectionsDeleteFuture.Result. -func (future *VpnConnectionsDeleteFuture) result(client VpnConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnDeviceScriptParameters vpn device configuration script generation parameters -type VpnDeviceScriptParameters struct { - // Vendor - The vendor for the vpn device. - Vendor *string `json:"vendor,omitempty"` - // DeviceFamily - The device family for the vpn device. - DeviceFamily *string `json:"deviceFamily,omitempty"` - // FirmwareVersion - The firmware version for the vpn device. - FirmwareVersion *string `json:"firmwareVersion,omitempty"` -} - -// VpnGateway vpnGateway Resource. -type VpnGateway struct { - autorest.Response `json:"-"` - *VpnGatewayProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VpnGateway. -func (vg VpnGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vg.VpnGatewayProperties != nil { - objectMap["properties"] = vg.VpnGatewayProperties - } - if vg.ID != nil { - objectMap["id"] = vg.ID - } - if vg.Location != nil { - objectMap["location"] = vg.Location - } - if vg.Tags != nil { - objectMap["tags"] = vg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnGateway struct. -func (vg *VpnGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnGatewayProperties VpnGatewayProperties - err = json.Unmarshal(*v, &vpnGatewayProperties) - if err != nil { - return err - } - vg.VpnGatewayProperties = &vpnGatewayProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vg.Tags = tags - } - } - } - - return nil -} - -// VpnGatewayProperties parameters for VpnGateway -type VpnGatewayProperties struct { - // VirtualHub - The VirtualHub to which the gateway belongs - VirtualHub *SubResource `json:"virtualHub,omitempty"` - // Connections - list of all vpn connections to the gateway. - Connections *[]VpnConnection `json:"connections,omitempty"` - // BgpSettings - Local network gateway's BGP speaker settings. - BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // VpnGatewayScaleUnit - The scale unit for this vpn gateway. - VpnGatewayScaleUnit *int32 `json:"vpnGatewayScaleUnit,omitempty"` -} - -// VpnGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (VpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysCreateOrUpdateFuture.Result. -func (future *VpnGatewaysCreateOrUpdateFuture) result(client VpnGatewaysClient) (vg VpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vg.Response.Response, err = future.GetResult(sender); err == nil && vg.Response.Response.StatusCode != http.StatusNoContent { - vg, err = client.CreateOrUpdateResponder(vg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysCreateOrUpdateFuture", "Result", vg.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysDeleteFuture.Result. -func (future *VpnGatewaysDeleteFuture) result(client VpnGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (VpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysUpdateTagsFuture.Result. -func (future *VpnGatewaysUpdateTagsFuture) result(client VpnGatewaysClient) (vg VpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vg.Response.Response, err = future.GetResult(sender); err == nil && vg.Response.Response.StatusCode != http.StatusNoContent { - vg, err = client.UpdateTagsResponder(vg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysUpdateTagsFuture", "Result", vg.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnProfileResponse vpn Profile Response for package generation -type VpnProfileResponse struct { - autorest.Response `json:"-"` - // ProfileURL - URL to the VPN profile - ProfileURL *string `json:"profileUrl,omitempty"` -} - -// VpnSite vpnSite Resource. -type VpnSite struct { - autorest.Response `json:"-"` - *VpnSiteProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; Gets a unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VpnSite. -func (vs VpnSite) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vs.VpnSiteProperties != nil { - objectMap["properties"] = vs.VpnSiteProperties - } - if vs.ID != nil { - objectMap["id"] = vs.ID - } - if vs.Location != nil { - objectMap["location"] = vs.Location - } - if vs.Tags != nil { - objectMap["tags"] = vs.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnSite struct. -func (vs *VpnSite) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnSiteProperties VpnSiteProperties - err = json.Unmarshal(*v, &vpnSiteProperties) - if err != nil { - return err - } - vs.VpnSiteProperties = &vpnSiteProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vs.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vs.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vs.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vs.Tags = tags - } - } - } - - return nil -} - -// VpnSiteID vpnSite Resource. -type VpnSiteID struct { - // VpnSite - READ-ONLY; The resource-uri of the vpn-site for which config is to be fetched. - VpnSite *string `json:"vpnSite,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnSiteID. -func (vsi VpnSiteID) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VpnSiteProperties parameters for VpnSite -type VpnSiteProperties struct { - // VirtualWan - The VirtualWAN to which the vpnSite belongs - VirtualWan *SubResource `json:"virtualWan,omitempty"` - // DeviceProperties - The device properties - DeviceProperties *DeviceProperties `json:"deviceProperties,omitempty"` - // IPAddress - The ip-address for the vpn-site. - IPAddress *string `json:"ipAddress,omitempty"` - // SiteKey - The key for vpn-site that can be used for connections. - SiteKey *string `json:"siteKey,omitempty"` - // AddressSpace - The AddressSpace that contains an array of IP address ranges. - AddressSpace *AddressSpace `json:"addressSpace,omitempty"` - // BgpProperties - The set of bgp properties. - BgpProperties *BgpSettings `json:"bgpProperties,omitempty"` - // ProvisioningState - The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // IsSecuritySite - IsSecuritySite flag - IsSecuritySite *bool `json:"isSecuritySite,omitempty"` -} - -// VpnSitesConfigurationDownloadFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnSitesConfigurationDownloadFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnSitesConfigurationClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnSitesConfigurationDownloadFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnSitesConfigurationDownloadFuture.Result. -func (future *VpnSitesConfigurationDownloadFuture) result(client VpnSitesConfigurationClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationDownloadFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnSitesConfigurationDownloadFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnSitesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnSitesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnSitesClient) (VpnSite, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnSitesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnSitesCreateOrUpdateFuture.Result. -func (future *VpnSitesCreateOrUpdateFuture) result(client VpnSitesClient) (vs VpnSite, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vs.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnSitesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vs.Response.Response, err = future.GetResult(sender); err == nil && vs.Response.Response.StatusCode != http.StatusNoContent { - vs, err = client.CreateOrUpdateResponder(vs.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesCreateOrUpdateFuture", "Result", vs.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnSitesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnSitesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnSitesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnSitesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnSitesDeleteFuture.Result. -func (future *VpnSitesDeleteFuture) result(client VpnSitesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnSitesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnSitesUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnSitesUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnSitesClient) (VpnSite, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnSitesUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnSitesUpdateTagsFuture.Result. -func (future *VpnSitesUpdateTagsFuture) result(client VpnSitesClient) (vs VpnSite, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vs.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnSitesUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vs.Response.Response, err = future.GetResult(sender); err == nil && vs.Response.Response.StatusCode != http.StatusNoContent { - vs, err = client.UpdateTagsResponder(vs.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesUpdateTagsFuture", "Result", vs.Response.Response, "Failure responding to request") - } - } - return -} - -// Watcher network watcher in a resource group. -type Watcher struct { - autorest.Response `json:"-"` - // Etag - A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - *WatcherPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Watcher. -func (w Watcher) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if w.Etag != nil { - objectMap["etag"] = w.Etag - } - if w.WatcherPropertiesFormat != nil { - objectMap["properties"] = w.WatcherPropertiesFormat - } - if w.ID != nil { - objectMap["id"] = w.ID - } - if w.Location != nil { - objectMap["location"] = w.Location - } - if w.Tags != nil { - objectMap["tags"] = w.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Watcher struct. -func (w *Watcher) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - w.Etag = &etag - } - case "properties": - if v != nil { - var watcherPropertiesFormat WatcherPropertiesFormat - err = json.Unmarshal(*v, &watcherPropertiesFormat) - if err != nil { - return err - } - w.WatcherPropertiesFormat = &watcherPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - w.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - w.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - w.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - w.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - w.Tags = tags - } - } - } - - return nil -} - -// WatcherListResult list of network watcher resources. -type WatcherListResult struct { - autorest.Response `json:"-"` - Value *[]Watcher `json:"value,omitempty"` -} - -// WatcherPropertiesFormat the network watcher properties. -type WatcherPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for WatcherPropertiesFormat. -func (wpf WatcherPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// WatchersCheckConnectivityFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersCheckConnectivityFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (ConnectivityInformation, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersCheckConnectivityFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersCheckConnectivityFuture.Result. -func (future *WatchersCheckConnectivityFuture) result(client WatchersClient) (ci ConnectivityInformation, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersCheckConnectivityFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ci.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersCheckConnectivityFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ci.Response.Response, err = future.GetResult(sender); err == nil && ci.Response.Response.StatusCode != http.StatusNoContent { - ci, err = client.CheckConnectivityResponder(ci.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersCheckConnectivityFuture", "Result", ci.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type WatchersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersDeleteFuture.Result. -func (future *WatchersDeleteFuture) result(client WatchersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// WatchersGetAzureReachabilityReportFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetAzureReachabilityReportFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (AzureReachabilityReport, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetAzureReachabilityReportFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetAzureReachabilityReportFuture.Result. -func (future *WatchersGetAzureReachabilityReportFuture) result(client WatchersClient) (arr AzureReachabilityReport, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetAzureReachabilityReportFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - arr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetAzureReachabilityReportFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if arr.Response.Response, err = future.GetResult(sender); err == nil && arr.Response.Response.StatusCode != http.StatusNoContent { - arr, err = client.GetAzureReachabilityReportResponder(arr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetAzureReachabilityReportFuture", "Result", arr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetFlowLogStatusFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetFlowLogStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (FlowLogInformation, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetFlowLogStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetFlowLogStatusFuture.Result. -func (future *WatchersGetFlowLogStatusFuture) result(client WatchersClient) (fli FlowLogInformation, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetFlowLogStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - fli.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetFlowLogStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if fli.Response.Response, err = future.GetResult(sender); err == nil && fli.Response.Response.StatusCode != http.StatusNoContent { - fli, err = client.GetFlowLogStatusResponder(fli.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetFlowLogStatusFuture", "Result", fli.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetNetworkConfigurationDiagnosticFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type WatchersGetNetworkConfigurationDiagnosticFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (ConfigurationDiagnosticResponse, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetNetworkConfigurationDiagnosticFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetNetworkConfigurationDiagnosticFuture.Result. -func (future *WatchersGetNetworkConfigurationDiagnosticFuture) result(client WatchersClient) (cdr ConfigurationDiagnosticResponse, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNetworkConfigurationDiagnosticFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cdr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetNetworkConfigurationDiagnosticFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cdr.Response.Response, err = future.GetResult(sender); err == nil && cdr.Response.Response.StatusCode != http.StatusNoContent { - cdr, err = client.GetNetworkConfigurationDiagnosticResponder(cdr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNetworkConfigurationDiagnosticFuture", "Result", cdr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetNextHopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type WatchersGetNextHopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (NextHopResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetNextHopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetNextHopFuture.Result. -func (future *WatchersGetNextHopFuture) result(client WatchersClient) (nhr NextHopResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNextHopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - nhr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetNextHopFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if nhr.Response.Response, err = future.GetResult(sender); err == nil && nhr.Response.Response.StatusCode != http.StatusNoContent { - nhr, err = client.GetNextHopResponder(nhr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNextHopFuture", "Result", nhr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetTroubleshootingFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetTroubleshootingFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (TroubleshootingResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetTroubleshootingFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetTroubleshootingFuture.Result. -func (future *WatchersGetTroubleshootingFuture) result(client WatchersClient) (tr TroubleshootingResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - tr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetTroubleshootingFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if tr.Response.Response, err = future.GetResult(sender); err == nil && tr.Response.Response.StatusCode != http.StatusNoContent { - tr, err = client.GetTroubleshootingResponder(tr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingFuture", "Result", tr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetTroubleshootingResultFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetTroubleshootingResultFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (TroubleshootingResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetTroubleshootingResultFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetTroubleshootingResultFuture.Result. -func (future *WatchersGetTroubleshootingResultFuture) result(client WatchersClient) (tr TroubleshootingResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingResultFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - tr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetTroubleshootingResultFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if tr.Response.Response, err = future.GetResult(sender); err == nil && tr.Response.Response.StatusCode != http.StatusNoContent { - tr, err = client.GetTroubleshootingResultResponder(tr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingResultFuture", "Result", tr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetVMSecurityRulesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetVMSecurityRulesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (SecurityGroupViewResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetVMSecurityRulesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetVMSecurityRulesFuture.Result. -func (future *WatchersGetVMSecurityRulesFuture) result(client WatchersClient) (sgvr SecurityGroupViewResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetVMSecurityRulesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sgvr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetVMSecurityRulesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sgvr.Response.Response, err = future.GetResult(sender); err == nil && sgvr.Response.Response.StatusCode != http.StatusNoContent { - sgvr, err = client.GetVMSecurityRulesResponder(sgvr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetVMSecurityRulesFuture", "Result", sgvr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersListAvailableProvidersFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersListAvailableProvidersFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (AvailableProvidersList, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersListAvailableProvidersFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersListAvailableProvidersFuture.Result. -func (future *WatchersListAvailableProvidersFuture) result(client WatchersClient) (apl AvailableProvidersList, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersListAvailableProvidersFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - apl.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersListAvailableProvidersFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if apl.Response.Response, err = future.GetResult(sender); err == nil && apl.Response.Response.StatusCode != http.StatusNoContent { - apl, err = client.ListAvailableProvidersResponder(apl.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersListAvailableProvidersFuture", "Result", apl.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersSetFlowLogConfigurationFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersSetFlowLogConfigurationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (FlowLogInformation, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersSetFlowLogConfigurationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersSetFlowLogConfigurationFuture.Result. -func (future *WatchersSetFlowLogConfigurationFuture) result(client WatchersClient) (fli FlowLogInformation, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersSetFlowLogConfigurationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - fli.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersSetFlowLogConfigurationFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if fli.Response.Response, err = future.GetResult(sender); err == nil && fli.Response.Response.StatusCode != http.StatusNoContent { - fli, err = client.SetFlowLogConfigurationResponder(fli.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersSetFlowLogConfigurationFuture", "Result", fli.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersVerifyIPFlowFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type WatchersVerifyIPFlowFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (VerificationIPFlowResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersVerifyIPFlowFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersVerifyIPFlowFuture.Result. -func (future *WatchersVerifyIPFlowFuture) result(client WatchersClient) (vifr VerificationIPFlowResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersVerifyIPFlowFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vifr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersVerifyIPFlowFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vifr.Response.Response, err = future.GetResult(sender); err == nil && vifr.Response.Response.StatusCode != http.StatusNoContent { - vifr, err = client.VerifyIPFlowResponder(vifr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersVerifyIPFlowFuture", "Result", vifr.Response.Response, "Failure responding to request") - } - } - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/operations.go deleted file mode 100644 index 2460d3810..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/operations.go +++ /dev/null @@ -1,140 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// OperationsClient is the network Client -type OperationsClient struct { - BaseClient -} - -// NewOperationsClient creates an instance of the OperationsClient client. -func NewOperationsClient(subscriptionID string) OperationsClient { - return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List lists all of the available Network Rest API operations. -func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.olr.Response.Response != nil { - sc = result.olr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.olr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.OperationsClient", "List", resp, "Failure sending request") - return - } - - result.olr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.OperationsClient", "List", resp, "Failure responding to request") - return - } - if result.olr.hasNextLink() && result.olr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Network/operations"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client OperationsClient) listNextResults(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { - req, err := lastResults.operationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.OperationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.OperationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.OperationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/p2svpngateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/p2svpngateways.go deleted file mode 100644 index d1aaa53be..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/p2svpngateways.go +++ /dev/null @@ -1,661 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// P2sVpnGatewaysClient is the network Client -type P2sVpnGatewaysClient struct { - BaseClient -} - -// NewP2sVpnGatewaysClient creates an instance of the P2sVpnGatewaysClient client. -func NewP2sVpnGatewaysClient(subscriptionID string) P2sVpnGatewaysClient { - return NewP2sVpnGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewP2sVpnGatewaysClientWithBaseURI creates an instance of the P2sVpnGatewaysClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewP2sVpnGatewaysClientWithBaseURI(baseURI string, subscriptionID string) P2sVpnGatewaysClient { - return P2sVpnGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a virtual wan p2s vpn gateway if it doesn't exist else updates the existing gateway. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -// p2SVpnGatewayParameters - parameters supplied to create or Update a virtual wan p2s vpn gateway. -func (client P2sVpnGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters P2SVpnGateway) (result P2sVpnGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, p2SVpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client P2sVpnGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters P2SVpnGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - p2SVpnGatewayParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(p2SVpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) CreateOrUpdateSender(req *http.Request) (future P2sVpnGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a virtual wan p2s vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -func (client P2sVpnGatewaysClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string) (result P2sVpnGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client P2sVpnGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) DeleteSender(req *http.Request) (future P2sVpnGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// GenerateVpnProfile generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the P2SVpnGateway. -// parameters - parameters supplied to the generate P2SVpnGateway VPN client package operation. -func (client P2sVpnGatewaysClient) GenerateVpnProfile(ctx context.Context, resourceGroupName string, gatewayName string, parameters P2SVpnProfileParameters) (result P2sVpnGatewaysGenerateVpnProfileFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.GenerateVpnProfile") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GenerateVpnProfilePreparer(ctx, resourceGroupName, gatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GenerateVpnProfile", nil, "Failure preparing request") - return - } - - result, err = client.GenerateVpnProfileSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GenerateVpnProfile", result.Response(), "Failure sending request") - return - } - - return -} - -// GenerateVpnProfilePreparer prepares the GenerateVpnProfile request. -func (client P2sVpnGatewaysClient) GenerateVpnProfilePreparer(ctx context.Context, resourceGroupName string, gatewayName string, parameters P2SVpnProfileParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/generatevpnprofile", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GenerateVpnProfileSender sends the GenerateVpnProfile request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) GenerateVpnProfileSender(req *http.Request) (future P2sVpnGatewaysGenerateVpnProfileFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GenerateVpnProfileResponder handles the response to the GenerateVpnProfile request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) GenerateVpnProfileResponder(resp *http.Response) (result VpnProfileResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get retrieves the details of a virtual wan p2s vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -func (client P2sVpnGatewaysClient) Get(ctx context.Context, resourceGroupName string, gatewayName string) (result P2SVpnGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client P2sVpnGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) GetResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the P2SVpnGateways in a subscription. -func (client P2sVpnGatewaysClient) List(ctx context.Context) (result ListP2SVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.List") - defer func() { - sc := -1 - if result.lpvgr.Response.Response != nil { - sc = result.lpvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lpvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.lpvgr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.lpvgr.hasNextLink() && result.lpvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client P2sVpnGatewaysClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/p2svpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) ListResponder(resp *http.Response) (result ListP2SVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client P2sVpnGatewaysClient) listNextResults(ctx context.Context, lastResults ListP2SVpnGatewaysResult) (result ListP2SVpnGatewaysResult, err error) { - req, err := lastResults.listP2SVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client P2sVpnGatewaysClient) ListComplete(ctx context.Context) (result ListP2SVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the P2SVpnGateways in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -func (client P2sVpnGatewaysClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListP2SVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lpvgr.Response.Response != nil { - sc = result.lpvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lpvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lpvgr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lpvgr.hasNextLink() && result.lpvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client P2sVpnGatewaysClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) ListByResourceGroupResponder(resp *http.Response) (result ListP2SVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client P2sVpnGatewaysClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListP2SVpnGatewaysResult) (result ListP2SVpnGatewaysResult, err error) { - req, err := lastResults.listP2SVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client P2sVpnGatewaysClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListP2SVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates virtual wan p2s vpn gateway tags. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -// p2SVpnGatewayParameters - parameters supplied to update a virtual wan p2s vpn gateway tags. -func (client P2sVpnGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters TagsObject) (result P2sVpnGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, gatewayName, p2SVpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client P2sVpnGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(p2SVpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) UpdateTagsSender(req *http.Request) (future P2sVpnGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) UpdateTagsResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/p2svpnserverconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/p2svpnserverconfigurations.go deleted file mode 100644 index 259ca0115..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/p2svpnserverconfigurations.go +++ /dev/null @@ -1,394 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// P2sVpnServerConfigurationsClient is the network Client -type P2sVpnServerConfigurationsClient struct { - BaseClient -} - -// NewP2sVpnServerConfigurationsClient creates an instance of the P2sVpnServerConfigurationsClient client. -func NewP2sVpnServerConfigurationsClient(subscriptionID string) P2sVpnServerConfigurationsClient { - return NewP2sVpnServerConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewP2sVpnServerConfigurationsClientWithBaseURI creates an instance of the P2sVpnServerConfigurationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewP2sVpnServerConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) P2sVpnServerConfigurationsClient { - return P2sVpnServerConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a P2SVpnServerConfiguration to associate with a VirtualWan if it doesn't exist else updates -// the existing P2SVpnServerConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWanName - the name of the VirtualWan. -// p2SVpnServerConfigurationName - the name of the P2SVpnServerConfiguration. -// p2SVpnServerConfigurationParameters - parameters supplied to create or Update a P2SVpnServerConfiguration. -func (client P2sVpnServerConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualWanName string, p2SVpnServerConfigurationName string, p2SVpnServerConfigurationParameters P2SVpnServerConfiguration) (result P2sVpnServerConfigurationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnServerConfigurationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualWanName, p2SVpnServerConfigurationName, p2SVpnServerConfigurationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client P2sVpnServerConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualWanName string, p2SVpnServerConfigurationName string, p2SVpnServerConfigurationParameters P2SVpnServerConfiguration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "p2SVpnServerConfigurationName": autorest.Encode("path", p2SVpnServerConfigurationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWanName": autorest.Encode("path", virtualWanName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - p2SVpnServerConfigurationParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWanName}/p2sVpnServerConfigurations/{p2SVpnServerConfigurationName}", pathParameters), - autorest.WithJSON(p2SVpnServerConfigurationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnServerConfigurationsClient) CreateOrUpdateSender(req *http.Request) (future P2sVpnServerConfigurationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client P2sVpnServerConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result P2SVpnServerConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a P2SVpnServerConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnServerConfiguration. -// virtualWanName - the name of the VirtualWan. -// p2SVpnServerConfigurationName - the name of the P2SVpnServerConfiguration. -func (client P2sVpnServerConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, virtualWanName string, p2SVpnServerConfigurationName string) (result P2sVpnServerConfigurationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnServerConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualWanName, p2SVpnServerConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client P2sVpnServerConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualWanName string, p2SVpnServerConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "p2SVpnServerConfigurationName": autorest.Encode("path", p2SVpnServerConfigurationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWanName": autorest.Encode("path", virtualWanName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWanName}/p2sVpnServerConfigurations/{p2SVpnServerConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnServerConfigurationsClient) DeleteSender(req *http.Request) (future P2sVpnServerConfigurationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client P2sVpnServerConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a P2SVpnServerConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnServerConfiguration. -// virtualWanName - the name of the VirtualWan. -// p2SVpnServerConfigurationName - the name of the P2SVpnServerConfiguration. -func (client P2sVpnServerConfigurationsClient) Get(ctx context.Context, resourceGroupName string, virtualWanName string, p2SVpnServerConfigurationName string) (result P2SVpnServerConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnServerConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualWanName, p2SVpnServerConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client P2sVpnServerConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualWanName string, p2SVpnServerConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "p2SVpnServerConfigurationName": autorest.Encode("path", p2SVpnServerConfigurationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWanName": autorest.Encode("path", virtualWanName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWanName}/p2sVpnServerConfigurations/{p2SVpnServerConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnServerConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client P2sVpnServerConfigurationsClient) GetResponder(resp *http.Response) (result P2SVpnServerConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVirtualWan retrieves all P2SVpnServerConfigurations for a particular VirtualWan. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWanName - the name of the VirtualWan. -func (client P2sVpnServerConfigurationsClient) ListByVirtualWan(ctx context.Context, resourceGroupName string, virtualWanName string) (result ListP2SVpnServerConfigurationsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnServerConfigurationsClient.ListByVirtualWan") - defer func() { - sc := -1 - if result.lpvscr.Response.Response != nil { - sc = result.lpvscr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVirtualWanNextResults - req, err := client.ListByVirtualWanPreparer(ctx, resourceGroupName, virtualWanName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "ListByVirtualWan", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVirtualWanSender(req) - if err != nil { - result.lpvscr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "ListByVirtualWan", resp, "Failure sending request") - return - } - - result.lpvscr, err = client.ListByVirtualWanResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "ListByVirtualWan", resp, "Failure responding to request") - return - } - if result.lpvscr.hasNextLink() && result.lpvscr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVirtualWanPreparer prepares the ListByVirtualWan request. -func (client P2sVpnServerConfigurationsClient) ListByVirtualWanPreparer(ctx context.Context, resourceGroupName string, virtualWanName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWanName": autorest.Encode("path", virtualWanName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWanName}/p2sVpnServerConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVirtualWanSender sends the ListByVirtualWan request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnServerConfigurationsClient) ListByVirtualWanSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVirtualWanResponder handles the response to the ListByVirtualWan request. The method always -// closes the http.Response Body. -func (client P2sVpnServerConfigurationsClient) ListByVirtualWanResponder(resp *http.Response) (result ListP2SVpnServerConfigurationsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVirtualWanNextResults retrieves the next set of results, if any. -func (client P2sVpnServerConfigurationsClient) listByVirtualWanNextResults(ctx context.Context, lastResults ListP2SVpnServerConfigurationsResult) (result ListP2SVpnServerConfigurationsResult, err error) { - req, err := lastResults.listP2SVpnServerConfigurationsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "listByVirtualWanNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVirtualWanSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "listByVirtualWanNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVirtualWanResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnServerConfigurationsClient", "listByVirtualWanNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVirtualWanComplete enumerates all values, automatically crossing page boundaries as required. -func (client P2sVpnServerConfigurationsClient) ListByVirtualWanComplete(ctx context.Context, resourceGroupName string, virtualWanName string) (result ListP2SVpnServerConfigurationsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnServerConfigurationsClient.ListByVirtualWan") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVirtualWan(ctx, resourceGroupName, virtualWanName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/packetcaptures.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/packetcaptures.go deleted file mode 100644 index c147f9fcb..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/packetcaptures.go +++ /dev/null @@ -1,520 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PacketCapturesClient is the network Client -type PacketCapturesClient struct { - BaseClient -} - -// NewPacketCapturesClient creates an instance of the PacketCapturesClient client. -func NewPacketCapturesClient(subscriptionID string) PacketCapturesClient { - return NewPacketCapturesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPacketCapturesClientWithBaseURI creates an instance of the PacketCapturesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewPacketCapturesClientWithBaseURI(baseURI string, subscriptionID string) PacketCapturesClient { - return PacketCapturesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create and start a packet capture on the specified VM. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -// parameters - parameters that define the create packet capture operation. -func (client PacketCapturesClient) Create(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture) (result PacketCapturesCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.PacketCaptureParameters", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.PacketCaptureParameters.Target", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.PacketCaptureParameters.StorageLocation", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.PacketCapturesClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client PacketCapturesClient) CreatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "packetCaptureName": autorest.Encode("path", packetCaptureName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client PacketCapturesClient) CreateSender(req *http.Request) (future PacketCapturesCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client PacketCapturesClient) CreateResponder(resp *http.Response) (result PacketCaptureResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified packet capture session. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -func (client PacketCapturesClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCapturesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PacketCapturesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "packetCaptureName": autorest.Encode("path", packetCaptureName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PacketCapturesClient) DeleteSender(req *http.Request) (future PacketCapturesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PacketCapturesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a packet capture session by name. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -func (client PacketCapturesClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCaptureResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PacketCapturesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "packetCaptureName": autorest.Encode("path", packetCaptureName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PacketCapturesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PacketCapturesClient) GetResponder(resp *http.Response) (result PacketCaptureResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetStatus query the status of a running packet capture session. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the Network Watcher resource. -// packetCaptureName - the name given to the packet capture session. -func (client PacketCapturesClient) GetStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCapturesGetStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.GetStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetStatusPreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "GetStatus", nil, "Failure preparing request") - return - } - - result, err = client.GetStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "GetStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// GetStatusPreparer prepares the GetStatus request. -func (client PacketCapturesClient) GetStatusPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "packetCaptureName": autorest.Encode("path", packetCaptureName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetStatusSender sends the GetStatus request. The method will close the -// http.Response Body if it receives an error. -func (client PacketCapturesClient) GetStatusSender(req *http.Request) (future PacketCapturesGetStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetStatusResponder handles the response to the GetStatus request. The method always -// closes the http.Response Body. -func (client PacketCapturesClient) GetStatusResponder(resp *http.Response) (result PacketCaptureQueryStatusResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all packet capture sessions within the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the Network Watcher resource. -func (client PacketCapturesClient) List(ctx context.Context, resourceGroupName string, networkWatcherName string) (result PacketCaptureListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, networkWatcherName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PacketCapturesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PacketCapturesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PacketCapturesClient) ListResponder(resp *http.Response) (result PacketCaptureListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Stop stops a specified packet capture session. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -func (client PacketCapturesClient) Stop(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCapturesStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client PacketCapturesClient) StopPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "packetCaptureName": autorest.Encode("path", packetCaptureName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client PacketCapturesClient) StopSender(req *http.Request) (future PacketCapturesStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client PacketCapturesClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/profiles.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/profiles.go deleted file mode 100644 index d86376e9e..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/profiles.go +++ /dev/null @@ -1,576 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ProfilesClient is the network Client -type ProfilesClient struct { - BaseClient -} - -// NewProfilesClient creates an instance of the ProfilesClient client. -func NewProfilesClient(subscriptionID string) ProfilesClient { - return NewProfilesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewProfilesClientWithBaseURI creates an instance of the ProfilesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewProfilesClientWithBaseURI(baseURI string, subscriptionID string) ProfilesClient { - return ProfilesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network profile. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the network profile. -// parameters - parameters supplied to the create or update network profile operation. -func (client ProfilesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkProfileName string, parameters Profile) (result Profile, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkProfileName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ProfilesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkProfileName string, parameters Profile) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ProfilesClient) CreateOrUpdateResponder(resp *http.Response) (result Profile, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network profile. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the NetworkProfile. -func (client ProfilesClient) Delete(ctx context.Context, resourceGroupName string, networkProfileName string) (result ProfilesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkProfileName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ProfilesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkProfileName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) DeleteSender(req *http.Request) (future ProfilesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ProfilesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified network profile in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the Public IP Prefix. -// expand - expands referenced resources. -func (client ProfilesClient) Get(ctx context.Context, resourceGroupName string, networkProfileName string, expand string) (result Profile, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkProfileName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ProfilesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkProfileName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ProfilesClient) GetResponder(resp *http.Response) (result Profile, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all network profiles in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ProfilesClient) List(ctx context.Context, resourceGroupName string) (result ProfileListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.List") - defer func() { - sc := -1 - if result.plr.Response.Response != nil { - sc = result.plr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.plr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "List", resp, "Failure sending request") - return - } - - result.plr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "List", resp, "Failure responding to request") - return - } - if result.plr.hasNextLink() && result.plr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ProfilesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ProfilesClient) ListResponder(resp *http.Response) (result ProfileListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ProfilesClient) listNextResults(ctx context.Context, lastResults ProfileListResult) (result ProfileListResult, err error) { - req, err := lastResults.profileListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProfilesClient) ListComplete(ctx context.Context, resourceGroupName string) (result ProfileListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the network profiles in a subscription. -func (client ProfilesClient) ListAll(ctx context.Context) (result ProfileListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.ListAll") - defer func() { - sc := -1 - if result.plr.Response.Response != nil { - sc = result.plr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.plr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "ListAll", resp, "Failure sending request") - return - } - - result.plr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.plr.hasNextLink() && result.plr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ProfilesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkProfiles", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ProfilesClient) ListAllResponder(resp *http.Response) (result ProfileListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ProfilesClient) listAllNextResults(ctx context.Context, lastResults ProfileListResult) (result ProfileListResult, err error) { - req, err := lastResults.profileListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProfilesClient) ListAllComplete(ctx context.Context) (result ProfileListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates network profile tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the network profile. -// parameters - parameters supplied to update network profile tags. -func (client ProfilesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkProfileName string, parameters TagsObject) (result Profile, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkProfileName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ProfilesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkProfileName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ProfilesClient) UpdateTagsResponder(resp *http.Response) (result Profile, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/publicipaddresses.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/publicipaddresses.go deleted file mode 100644 index c15c36e51..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/publicipaddresses.go +++ /dev/null @@ -1,927 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PublicIPAddressesClient is the network Client -type PublicIPAddressesClient struct { - BaseClient -} - -// NewPublicIPAddressesClient creates an instance of the PublicIPAddressesClient client. -func NewPublicIPAddressesClient(subscriptionID string) PublicIPAddressesClient { - return NewPublicIPAddressesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPublicIPAddressesClientWithBaseURI creates an instance of the PublicIPAddressesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPublicIPAddressesClientWithBaseURI(baseURI string, subscriptionID string) PublicIPAddressesClient { - return PublicIPAddressesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a static or dynamic public IP address. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the public IP address. -// parameters - parameters supplied to the create or update public IP address operation. -func (client PublicIPAddressesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (result PublicIPAddressesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.PublicIPAddressesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, publicIPAddressName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PublicIPAddressesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) CreateOrUpdateSender(req *http.Request) (future PublicIPAddressesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified public IP address. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the subnet. -func (client PublicIPAddressesClient) Delete(ctx context.Context, resourceGroupName string, publicIPAddressName string) (result PublicIPAddressesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, publicIPAddressName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PublicIPAddressesClient) DeletePreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) DeleteSender(req *http.Request) (future PublicIPAddressesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified public IP address in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the subnet. -// expand - expands referenced resources. -func (client PublicIPAddressesClient) Get(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (result PublicIPAddress, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, publicIPAddressName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PublicIPAddressesClient) GetPreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) GetResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVirtualMachineScaleSetPublicIPAddress get the specified public IP address in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// IPConfigurationName - the name of the IP configuration. -// publicIPAddressName - the name of the public IP Address. -// expand - expands referenced resources. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (result PublicIPAddress, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVirtualMachineScaleSetPublicIPAddressPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetVirtualMachineScaleSetPublicIPAddress", nil, "Failure preparing request") - return - } - - resp, err := client.GetVirtualMachineScaleSetPublicIPAddressSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetVirtualMachineScaleSetPublicIPAddress", resp, "Failure sending request") - return - } - - result, err = client.GetVirtualMachineScaleSetPublicIPAddressResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetVirtualMachineScaleSetPublicIPAddress", resp, "Failure responding to request") - return - } - - return -} - -// GetVirtualMachineScaleSetPublicIPAddressPreparer prepares the GetVirtualMachineScaleSetPublicIPAddress request. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddressPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses/{publicIpAddressName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVirtualMachineScaleSetPublicIPAddressSender sends the GetVirtualMachineScaleSetPublicIPAddress request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddressSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetVirtualMachineScaleSetPublicIPAddressResponder handles the response to the GetVirtualMachineScaleSetPublicIPAddress request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddressResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all public IP addresses in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client PublicIPAddressesClient) List(ctx context.Context, resourceGroupName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.List") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PublicIPAddressesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListComplete(ctx context.Context, resourceGroupName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the public IP addresses in a subscription. -func (client PublicIPAddressesClient) ListAll(ctx context.Context) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListAll") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client PublicIPAddressesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListAllResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listAllNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListAllComplete(ctx context.Context) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListVirtualMachineScaleSetPublicIPAddresses gets information about all public IP addresses on a virtual machine -// scale set level. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddresses(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetPublicIPAddresses") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetPublicIPAddressesNextResults - req, err := client.ListVirtualMachineScaleSetPublicIPAddressesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetPublicIPAddresses", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetPublicIPAddressesSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetPublicIPAddresses", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListVirtualMachineScaleSetPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetPublicIPAddresses", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetPublicIPAddressesPreparer prepares the ListVirtualMachineScaleSetPublicIPAddresses request. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/publicipaddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetPublicIPAddressesSender sends the ListVirtualMachineScaleSetPublicIPAddresses request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetPublicIPAddressesResponder handles the response to the ListVirtualMachineScaleSetPublicIPAddresses request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetPublicIPAddressesNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listVirtualMachineScaleSetPublicIPAddressesNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetPublicIPAddressesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetPublicIPAddressesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetPublicIPAddressesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetPublicIPAddressesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetPublicIPAddressesComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetPublicIPAddresses") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetPublicIPAddresses(ctx, resourceGroupName, virtualMachineScaleSetName) - return -} - -// ListVirtualMachineScaleSetVMPublicIPAddresses gets information about all public IP addresses in a virtual machine IP -// configuration in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the network interface name. -// IPConfigurationName - the IP configuration name. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddresses(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetVMPublicIPAddresses") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetVMPublicIPAddressesNextResults - req, err := client.ListVirtualMachineScaleSetVMPublicIPAddressesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetVMPublicIPAddresses", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetVMPublicIPAddressesSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetVMPublicIPAddresses", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListVirtualMachineScaleSetVMPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetVMPublicIPAddresses", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesPreparer prepares the ListVirtualMachineScaleSetVMPublicIPAddresses request. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2017-03-30" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesSender sends the ListVirtualMachineScaleSetVMPublicIPAddresses request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesResponder handles the response to the ListVirtualMachineScaleSetVMPublicIPAddresses request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetVMPublicIPAddressesNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listVirtualMachineScaleSetVMPublicIPAddressesNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetVMPublicIPAddressesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetVMPublicIPAddressesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetVMPublicIPAddressesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetVMPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetVMPublicIPAddressesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetVMPublicIPAddresses") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetVMPublicIPAddresses(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName) - return -} - -// UpdateTags updates public IP address tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the public IP address. -// parameters - parameters supplied to update public IP address tags. -func (client PublicIPAddressesClient) UpdateTags(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters TagsObject) (result PublicIPAddressesUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, publicIPAddressName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client PublicIPAddressesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) UpdateTagsSender(req *http.Request) (future PublicIPAddressesUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) UpdateTagsResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/publicipprefixes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/publicipprefixes.go deleted file mode 100644 index 5ec713bcc..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/publicipprefixes.go +++ /dev/null @@ -1,583 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PublicIPPrefixesClient is the network Client -type PublicIPPrefixesClient struct { - BaseClient -} - -// NewPublicIPPrefixesClient creates an instance of the PublicIPPrefixesClient client. -func NewPublicIPPrefixesClient(subscriptionID string) PublicIPPrefixesClient { - return NewPublicIPPrefixesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPublicIPPrefixesClientWithBaseURI creates an instance of the PublicIPPrefixesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPublicIPPrefixesClientWithBaseURI(baseURI string, subscriptionID string) PublicIPPrefixesClient { - return PublicIPPrefixesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a static or dynamic public IP prefix. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the public IP prefix. -// parameters - parameters supplied to the create or update public IP prefix operation. -func (client PublicIPPrefixesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters PublicIPPrefix) (result PublicIPPrefixesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, publicIPPrefixName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PublicIPPrefixesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters PublicIPPrefix) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) CreateOrUpdateSender(req *http.Request) (future PublicIPPrefixesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) CreateOrUpdateResponder(resp *http.Response) (result PublicIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified public IP prefix. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the PublicIpPrefix. -func (client PublicIPPrefixesClient) Delete(ctx context.Context, resourceGroupName string, publicIPPrefixName string) (result PublicIPPrefixesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, publicIPPrefixName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PublicIPPrefixesClient) DeletePreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) DeleteSender(req *http.Request) (future PublicIPPrefixesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified public IP prefix in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the Public IP Prefix. -// expand - expands referenced resources. -func (client PublicIPPrefixesClient) Get(ctx context.Context, resourceGroupName string, publicIPPrefixName string, expand string) (result PublicIPPrefix, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, publicIPPrefixName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PublicIPPrefixesClient) GetPreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) GetResponder(resp *http.Response) (result PublicIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all public IP prefixes in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client PublicIPPrefixesClient) List(ctx context.Context, resourceGroupName string) (result PublicIPPrefixListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.List") - defer func() { - sc := -1 - if result.piplr.Response.Response != nil { - sc = result.piplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.piplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "List", resp, "Failure sending request") - return - } - - result.piplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "List", resp, "Failure responding to request") - return - } - if result.piplr.hasNextLink() && result.piplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PublicIPPrefixesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) ListResponder(resp *http.Response) (result PublicIPPrefixListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client PublicIPPrefixesClient) listNextResults(ctx context.Context, lastResults PublicIPPrefixListResult) (result PublicIPPrefixListResult, err error) { - req, err := lastResults.publicIPPrefixListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPPrefixesClient) ListComplete(ctx context.Context, resourceGroupName string) (result PublicIPPrefixListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the public IP prefixes in a subscription. -func (client PublicIPPrefixesClient) ListAll(ctx context.Context) (result PublicIPPrefixListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.ListAll") - defer func() { - sc := -1 - if result.piplr.Response.Response != nil { - sc = result.piplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.piplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "ListAll", resp, "Failure sending request") - return - } - - result.piplr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.piplr.hasNextLink() && result.piplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client PublicIPPrefixesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPPrefixes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) ListAllResponder(resp *http.Response) (result PublicIPPrefixListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client PublicIPPrefixesClient) listAllNextResults(ctx context.Context, lastResults PublicIPPrefixListResult) (result PublicIPPrefixListResult, err error) { - req, err := lastResults.publicIPPrefixListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPPrefixesClient) ListAllComplete(ctx context.Context) (result PublicIPPrefixListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates public IP prefix tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the public IP prefix. -// parameters - parameters supplied to update public IP prefix tags. -func (client PublicIPPrefixesClient) UpdateTags(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters TagsObject) (result PublicIPPrefixesUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, publicIPPrefixName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client PublicIPPrefixesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) UpdateTagsSender(req *http.Request) (future PublicIPPrefixesUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) UpdateTagsResponder(resp *http.Response) (result PublicIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routefilterrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routefilterrules.go deleted file mode 100644 index 88f77bdae..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routefilterrules.go +++ /dev/null @@ -1,489 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RouteFilterRulesClient is the network Client -type RouteFilterRulesClient struct { - BaseClient -} - -// NewRouteFilterRulesClient creates an instance of the RouteFilterRulesClient client. -func NewRouteFilterRulesClient(subscriptionID string) RouteFilterRulesClient { - return NewRouteFilterRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRouteFilterRulesClientWithBaseURI creates an instance of the RouteFilterRulesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewRouteFilterRulesClientWithBaseURI(baseURI string, subscriptionID string) RouteFilterRulesClient { - return RouteFilterRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a route in the specified route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// ruleName - the name of the route filter rule. -// routeFilterRuleParameters - parameters supplied to the create or update route filter rule operation. -func (client RouteFilterRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule) (result RouteFilterRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: routeFilterRuleParameters, - Constraints: []validation.Constraint{{Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat.RouteFilterRuleType", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat.Communities", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.RouteFilterRulesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteFilterRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "ruleName": autorest.Encode("path", ruleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeFilterRuleParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), - autorest.WithJSON(routeFilterRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFilterRulesClient) CreateOrUpdateSender(req *http.Request) (future RouteFilterRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RouteFilterRulesClient) CreateOrUpdateResponder(resp *http.Response) (result RouteFilterRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified rule from a route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// ruleName - the name of the rule. -func (client RouteFilterRulesClient) Delete(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (result RouteFilterRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeFilterName, ruleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RouteFilterRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "ruleName": autorest.Encode("path", ruleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFilterRulesClient) DeleteSender(req *http.Request) (future RouteFilterRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RouteFilterRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified rule from a route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// ruleName - the name of the rule. -func (client RouteFilterRulesClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (result RouteFilterRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, routeFilterName, ruleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RouteFilterRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "ruleName": autorest.Encode("path", ruleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFilterRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RouteFilterRulesClient) GetResponder(resp *http.Response) (result RouteFilterRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByRouteFilter gets all RouteFilterRules in a route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -func (client RouteFilterRulesClient) ListByRouteFilter(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFilterRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.ListByRouteFilter") - defer func() { - sc := -1 - if result.rfrlr.Response.Response != nil { - sc = result.rfrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByRouteFilterNextResults - req, err := client.ListByRouteFilterPreparer(ctx, resourceGroupName, routeFilterName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", nil, "Failure preparing request") - return - } - - resp, err := client.ListByRouteFilterSender(req) - if err != nil { - result.rfrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure sending request") - return - } - - result.rfrlr, err = client.ListByRouteFilterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure responding to request") - return - } - if result.rfrlr.hasNextLink() && result.rfrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByRouteFilterPreparer prepares the ListByRouteFilter request. -func (client RouteFilterRulesClient) ListByRouteFilterPreparer(ctx context.Context, resourceGroupName string, routeFilterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByRouteFilterSender sends the ListByRouteFilter request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFilterRulesClient) ListByRouteFilterSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByRouteFilterResponder handles the response to the ListByRouteFilter request. The method always -// closes the http.Response Body. -func (client RouteFilterRulesClient) ListByRouteFilterResponder(resp *http.Response) (result RouteFilterRuleListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByRouteFilterNextResults retrieves the next set of results, if any. -func (client RouteFilterRulesClient) listByRouteFilterNextResults(ctx context.Context, lastResults RouteFilterRuleListResult) (result RouteFilterRuleListResult, err error) { - req, err := lastResults.routeFilterRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByRouteFilterSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByRouteFilterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByRouteFilterComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteFilterRulesClient) ListByRouteFilterComplete(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFilterRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.ListByRouteFilter") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByRouteFilter(ctx, resourceGroupName, routeFilterName) - return -} - -// Update updates a route in the specified route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// ruleName - the name of the route filter rule. -// routeFilterRuleParameters - parameters supplied to the update route filter rule operation. -func (client RouteFilterRulesClient) Update(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters PatchRouteFilterRule) (result RouteFilterRulesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client RouteFilterRulesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters PatchRouteFilterRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "ruleName": autorest.Encode("path", ruleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeFilterRuleParameters.Name = nil - routeFilterRuleParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), - autorest.WithJSON(routeFilterRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFilterRulesClient) UpdateSender(req *http.Request) (future RouteFilterRulesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client RouteFilterRulesClient) UpdateResponder(resp *http.Response) (result RouteFilterRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routefilters.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routefilters.go deleted file mode 100644 index 972aabec5..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routefilters.go +++ /dev/null @@ -1,586 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RouteFiltersClient is the network Client -type RouteFiltersClient struct { - BaseClient -} - -// NewRouteFiltersClient creates an instance of the RouteFiltersClient client. -func NewRouteFiltersClient(subscriptionID string) RouteFiltersClient { - return NewRouteFiltersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRouteFiltersClientWithBaseURI creates an instance of the RouteFiltersClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRouteFiltersClientWithBaseURI(baseURI string, subscriptionID string) RouteFiltersClient { - return RouteFiltersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a route filter in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// routeFilterParameters - parameters supplied to the create or update route filter operation. -func (client RouteFiltersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter) (result RouteFiltersCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeFilterName, routeFilterParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteFiltersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeFilterParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), - autorest.WithJSON(routeFilterParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFiltersClient) CreateOrUpdateSender(req *http.Request) (future RouteFiltersCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RouteFiltersClient) CreateOrUpdateResponder(resp *http.Response) (result RouteFilter, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -func (client RouteFiltersClient) Delete(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFiltersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeFilterName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RouteFiltersClient) DeletePreparer(ctx context.Context, resourceGroupName string, routeFilterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFiltersClient) DeleteSender(req *http.Request) (future RouteFiltersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RouteFiltersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// expand - expands referenced express route bgp peering resources. -func (client RouteFiltersClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, expand string) (result RouteFilter, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, routeFilterName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RouteFiltersClient) GetPreparer(ctx context.Context, resourceGroupName string, routeFilterName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFiltersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RouteFiltersClient) GetResponder(resp *http.Response) (result RouteFilter, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all route filters in a subscription. -func (client RouteFiltersClient) List(ctx context.Context) (result RouteFilterListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.List") - defer func() { - sc := -1 - if result.rflr.Response.Response != nil { - sc = result.rflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure sending request") - return - } - - result.rflr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure responding to request") - return - } - if result.rflr.hasNextLink() && result.rflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RouteFiltersClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFiltersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RouteFiltersClient) ListResponder(resp *http.Response) (result RouteFilterListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client RouteFiltersClient) listNextResults(ctx context.Context, lastResults RouteFilterListResult) (result RouteFilterListResult, err error) { - req, err := lastResults.routeFilterListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteFiltersClient) ListComplete(ctx context.Context) (result RouteFilterListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all route filters in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client RouteFiltersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result RouteFilterListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.rflr.Response.Response != nil { - sc = result.rflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.rflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.rflr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.rflr.hasNextLink() && result.rflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client RouteFiltersClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFiltersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client RouteFiltersClient) ListByResourceGroupResponder(resp *http.Response) (result RouteFilterListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client RouteFiltersClient) listByResourceGroupNextResults(ctx context.Context, lastResults RouteFilterListResult) (result RouteFilterListResult, err error) { - req, err := lastResults.routeFilterListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteFiltersClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result RouteFilterListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// Update updates a route filter in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// routeFilterParameters - parameters supplied to the update route filter operation. -func (client RouteFiltersClient) Update(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters PatchRouteFilter) (result RouteFiltersUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, routeFilterName, routeFilterParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client RouteFiltersClient) UpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters PatchRouteFilter) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeFilterName": autorest.Encode("path", routeFilterName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeFilterParameters.Name = nil - routeFilterParameters.Etag = nil - routeFilterParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), - autorest.WithJSON(routeFilterParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFiltersClient) UpdateSender(req *http.Request) (future RouteFiltersUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client RouteFiltersClient) UpdateResponder(resp *http.Response) (result RouteFilter, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routes.go deleted file mode 100644 index 29b268b21..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routes.go +++ /dev/null @@ -1,391 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RoutesClient is the network Client -type RoutesClient struct { - BaseClient -} - -// NewRoutesClient creates an instance of the RoutesClient client. -func NewRoutesClient(subscriptionID string) RoutesClient { - return NewRoutesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRoutesClientWithBaseURI creates an instance of the RoutesClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRoutesClientWithBaseURI(baseURI string, subscriptionID string) RoutesClient { - return RoutesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a route in the specified route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// routeName - the name of the route. -// routeParameters - parameters supplied to the create or update route operation. -func (client RoutesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters Route) (result RoutesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeTableName, routeName, routeParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RoutesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters Route) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeName": autorest.Encode("path", routeName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}", pathParameters), - autorest.WithJSON(routeParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) CreateOrUpdateSender(req *http.Request) (future RoutesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result Route, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified route from a route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// routeName - the name of the route. -func (client RoutesClient) Delete(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (result RoutesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeTableName, routeName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RoutesClient) DeletePreparer(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeName": autorest.Encode("path", routeName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) DeleteSender(req *http.Request) (future RoutesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RoutesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified route from a route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// routeName - the name of the route. -func (client RoutesClient) Get(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (result Route, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, routeTableName, routeName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RoutesClient) GetPreparer(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeName": autorest.Encode("path", routeName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RoutesClient) GetResponder(resp *http.Response) (result Route, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all routes in a route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -func (client RoutesClient) List(ctx context.Context, resourceGroupName string, routeTableName string) (result RouteListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.List") - defer func() { - sc := -1 - if result.rlr.Response.Response != nil { - sc = result.rlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending request") - return - } - - result.rlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure responding to request") - return - } - if result.rlr.hasNextLink() && result.rlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RoutesClient) ListPreparer(ctx context.Context, resourceGroupName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RoutesClient) ListResponder(resp *http.Response) (result RouteListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client RoutesClient) listNextResults(ctx context.Context, lastResults RouteListResult) (result RouteListResult, err error) { - req, err := lastResults.routeListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoutesClient) ListComplete(ctx context.Context, resourceGroupName string, routeTableName string) (result RouteListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, routeTableName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routetables.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routetables.go deleted file mode 100644 index c0f333e31..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/routetables.go +++ /dev/null @@ -1,582 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RouteTablesClient is the network Client -type RouteTablesClient struct { - BaseClient -} - -// NewRouteTablesClient creates an instance of the RouteTablesClient client. -func NewRouteTablesClient(subscriptionID string) RouteTablesClient { - return NewRouteTablesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRouteTablesClientWithBaseURI creates an instance of the RouteTablesClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRouteTablesClientWithBaseURI(baseURI string, subscriptionID string) RouteTablesClient { - return RouteTablesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or updates a route table in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// parameters - parameters supplied to the create or update route table operation. -func (client RouteTablesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, parameters RouteTable) (result RouteTablesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeTableName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteTablesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeTableName string, parameters RouteTable) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) CreateOrUpdateSender(req *http.Request) (future RouteTablesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result RouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -func (client RouteTablesClient) Delete(ctx context.Context, resourceGroupName string, routeTableName string) (result RouteTablesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RouteTablesClient) DeletePreparer(ctx context.Context, resourceGroupName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) DeleteSender(req *http.Request) (future RouteTablesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// expand - expands referenced resources. -func (client RouteTablesClient) Get(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (result RouteTable, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, routeTableName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RouteTablesClient) GetPreparer(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) GetResponder(resp *http.Response) (result RouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all route tables in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client RouteTablesClient) List(ctx context.Context, resourceGroupName string) (result RouteTableListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.List") - defer func() { - sc := -1 - if result.rtlr.Response.Response != nil { - sc = result.rtlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rtlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending request") - return - } - - result.rtlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure responding to request") - return - } - if result.rtlr.hasNextLink() && result.rtlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RouteTablesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) ListResponder(resp *http.Response) (result RouteTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client RouteTablesClient) listNextResults(ctx context.Context, lastResults RouteTableListResult) (result RouteTableListResult, err error) { - req, err := lastResults.routeTableListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteTablesClient) ListComplete(ctx context.Context, resourceGroupName string) (result RouteTableListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all route tables in a subscription. -func (client RouteTablesClient) ListAll(ctx context.Context) (result RouteTableListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.ListAll") - defer func() { - sc := -1 - if result.rtlr.Response.Response != nil { - sc = result.rtlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.rtlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending request") - return - } - - result.rtlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.rtlr.hasNextLink() && result.rtlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client RouteTablesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) ListAllResponder(resp *http.Response) (result RouteTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client RouteTablesClient) listAllNextResults(ctx context.Context, lastResults RouteTableListResult) (result RouteTableListResult, err error) { - req, err := lastResults.routeTableListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteTablesClient) ListAllComplete(ctx context.Context) (result RouteTableListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates a route table tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// parameters - parameters supplied to update route table tags. -func (client RouteTablesClient) UpdateTags(ctx context.Context, resourceGroupName string, routeTableName string, parameters TagsObject) (result RouteTablesUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, routeTableName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client RouteTablesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, routeTableName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) UpdateTagsSender(req *http.Request) (future RouteTablesUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) UpdateTagsResponder(resp *http.Response) (result RouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/securitygroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/securitygroups.go deleted file mode 100644 index aa1a05618..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/securitygroups.go +++ /dev/null @@ -1,582 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SecurityGroupsClient is the network Client -type SecurityGroupsClient struct { - BaseClient -} - -// NewSecurityGroupsClient creates an instance of the SecurityGroupsClient client. -func NewSecurityGroupsClient(subscriptionID string) SecurityGroupsClient { - return NewSecurityGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSecurityGroupsClientWithBaseURI creates an instance of the SecurityGroupsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) SecurityGroupsClient { - return SecurityGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network security group in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// parameters - parameters supplied to the create or update network security group operation. -func (client SecurityGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (result SecurityGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkSecurityGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (future SecurityGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -func (client SecurityGroupsClient) Delete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SecurityGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) DeleteSender(req *http.Request) (future SecurityGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// expand - expands referenced resources. -func (client SecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (result SecurityGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SecurityGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) GetResponder(resp *http.Response) (result SecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all network security groups in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client SecurityGroupsClient) List(ctx context.Context, resourceGroupName string) (result SecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.List") - defer func() { - sc := -1 - if result.sglr.Response.Response != nil { - sc = result.sglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.sglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending request") - return - } - - result.sglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.sglr.hasNextLink() && result.sglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SecurityGroupsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) ListResponder(resp *http.Response) (result SecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client SecurityGroupsClient) listNextResults(ctx context.Context, lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { - req, err := lastResults.securityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityGroupsClient) ListComplete(ctx context.Context, resourceGroupName string) (result SecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all network security groups in a subscription. -func (client SecurityGroupsClient) ListAll(ctx context.Context) (result SecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.sglr.Response.Response != nil { - sc = result.sglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.sglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending request") - return - } - - result.sglr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.sglr.hasNextLink() && result.sglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client SecurityGroupsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) ListAllResponder(resp *http.Response) (result SecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client SecurityGroupsClient) listAllNextResults(ctx context.Context, lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { - req, err := lastResults.securityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityGroupsClient) ListAllComplete(ctx context.Context) (result SecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates a network security group tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// parameters - parameters supplied to update network security group tags. -func (client SecurityGroupsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject) (result SecurityGroupsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkSecurityGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client SecurityGroupsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) UpdateTagsSender(req *http.Request) (future SecurityGroupsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) UpdateTagsResponder(resp *http.Response) (result SecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/securityrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/securityrules.go deleted file mode 100644 index 18e106788..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/securityrules.go +++ /dev/null @@ -1,391 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SecurityRulesClient is the network Client -type SecurityRulesClient struct { - BaseClient -} - -// NewSecurityRulesClient creates an instance of the SecurityRulesClient client. -func NewSecurityRulesClient(subscriptionID string) SecurityRulesClient { - return NewSecurityRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSecurityRulesClientWithBaseURI creates an instance of the SecurityRulesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) SecurityRulesClient { - return SecurityRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a security rule in the specified network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// securityRuleName - the name of the security rule. -// securityRuleParameters - parameters supplied to the create or update network security rule operation. -func (client SecurityRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule) (result SecurityRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityRuleName": autorest.Encode("path", securityRuleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), - autorest.WithJSON(securityRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) CreateOrUpdateSender(req *http.Request) (future SecurityRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network security rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// securityRuleName - the name of the security rule. -func (client SecurityRulesClient) Delete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result SecurityRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SecurityRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityRuleName": autorest.Encode("path", securityRuleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) DeleteSender(req *http.Request) (future SecurityRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the specified network security rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// securityRuleName - the name of the security rule. -func (client SecurityRulesClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result SecurityRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SecurityRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityRuleName": autorest.Encode("path", securityRuleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all security rules in a network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -func (client SecurityRulesClient) List(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.List") - defer func() { - sc := -1 - if result.srlr.Response.Response != nil { - sc = result.srlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.srlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending request") - return - } - - result.srlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure responding to request") - return - } - if result.srlr.hasNextLink() && result.srlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SecurityRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client SecurityRulesClient) listNextResults(ctx context.Context, lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) { - req, err := lastResults.securityRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityRulesClient) ListComplete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkSecurityGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/serviceendpointpolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/serviceendpointpolicies.go deleted file mode 100644 index 095db1b88..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/serviceendpointpolicies.go +++ /dev/null @@ -1,583 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServiceEndpointPoliciesClient is the network Client -type ServiceEndpointPoliciesClient struct { - BaseClient -} - -// NewServiceEndpointPoliciesClient creates an instance of the ServiceEndpointPoliciesClient client. -func NewServiceEndpointPoliciesClient(subscriptionID string) ServiceEndpointPoliciesClient { - return NewServiceEndpointPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceEndpointPoliciesClientWithBaseURI creates an instance of the ServiceEndpointPoliciesClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewServiceEndpointPoliciesClientWithBaseURI(baseURI string, subscriptionID string) ServiceEndpointPoliciesClient { - return ServiceEndpointPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a service Endpoint Policies. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// parameters - parameters supplied to the create or update service endpoint policy operation. -func (client ServiceEndpointPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters ServiceEndpointPolicy) (result ServiceEndpointPoliciesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceEndpointPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ServiceEndpointPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters ServiceEndpointPolicy) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) CreateOrUpdateSender(req *http.Request) (future ServiceEndpointPoliciesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceEndpointPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified service endpoint policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -func (client ServiceEndpointPoliciesClient) Delete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (result ServiceEndpointPoliciesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceEndpointPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ServiceEndpointPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) DeleteSender(req *http.Request) (future ServiceEndpointPoliciesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified service Endpoint Policies in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// expand - expands referenced resources. -func (client ServiceEndpointPoliciesClient) Get(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, expand string) (result ServiceEndpointPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceEndpointPolicyName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ServiceEndpointPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) GetResponder(resp *http.Response) (result ServiceEndpointPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the service endpoint policies in a subscription. -func (client ServiceEndpointPoliciesClient) List(ctx context.Context) (result ServiceEndpointPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.List") - defer func() { - sc := -1 - if result.seplr.Response.Response != nil { - sc = result.seplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.seplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "List", resp, "Failure sending request") - return - } - - result.seplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "List", resp, "Failure responding to request") - return - } - if result.seplr.hasNextLink() && result.seplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ServiceEndpointPoliciesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ServiceEndpointPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) ListResponder(resp *http.Response) (result ServiceEndpointPolicyListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ServiceEndpointPoliciesClient) listNextResults(ctx context.Context, lastResults ServiceEndpointPolicyListResult) (result ServiceEndpointPolicyListResult, err error) { - req, err := lastResults.serviceEndpointPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceEndpointPoliciesClient) ListComplete(ctx context.Context) (result ServiceEndpointPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all service endpoint Policies in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ServiceEndpointPoliciesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ServiceEndpointPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.seplr.Response.Response != nil { - sc = result.seplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.seplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.seplr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.seplr.hasNextLink() && result.seplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupResponder(resp *http.Response) (result ServiceEndpointPolicyListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ServiceEndpointPoliciesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ServiceEndpointPolicyListResult) (result ServiceEndpointPolicyListResult, err error) { - req, err := lastResults.serviceEndpointPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ServiceEndpointPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// Update updates service Endpoint Policies. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// parameters - parameters supplied to update service endpoint policy tags. -func (client ServiceEndpointPoliciesClient) Update(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters TagsObject) (result ServiceEndpointPoliciesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceEndpointPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ServiceEndpointPoliciesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) UpdateSender(req *http.Request) (future ServiceEndpointPoliciesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) UpdateResponder(resp *http.Response) (result ServiceEndpointPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/serviceendpointpolicydefinitions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/serviceendpointpolicydefinitions.go deleted file mode 100644 index 487e63eb7..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/serviceendpointpolicydefinitions.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServiceEndpointPolicyDefinitionsClient is the network Client -type ServiceEndpointPolicyDefinitionsClient struct { - BaseClient -} - -// NewServiceEndpointPolicyDefinitionsClient creates an instance of the ServiceEndpointPolicyDefinitionsClient client. -func NewServiceEndpointPolicyDefinitionsClient(subscriptionID string) ServiceEndpointPolicyDefinitionsClient { - return NewServiceEndpointPolicyDefinitionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceEndpointPolicyDefinitionsClientWithBaseURI creates an instance of the -// ServiceEndpointPolicyDefinitionsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewServiceEndpointPolicyDefinitionsClientWithBaseURI(baseURI string, subscriptionID string) ServiceEndpointPolicyDefinitionsClient { - return ServiceEndpointPolicyDefinitionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a service endpoint policy definition in the specified service endpoint policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// serviceEndpointPolicyDefinitionName - the name of the service endpoint policy definition name. -// serviceEndpointPolicyDefinitions - parameters supplied to the create or update service endpoint policy -// operation. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, serviceEndpointPolicyDefinitions ServiceEndpointPolicyDefinition) (result ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, serviceEndpointPolicyDefinitions ServiceEndpointPolicyDefinition) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyDefinitionName": autorest.Encode("path", serviceEndpointPolicyDefinitionName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}", pathParameters), - autorest.WithJSON(serviceEndpointPolicyDefinitions), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdateSender(req *http.Request) (future ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceEndpointPolicyDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified ServiceEndpoint policy definitions. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the Service Endpoint Policy. -// serviceEndpointPolicyDefinitionName - the name of the service endpoint policy definition. -func (client ServiceEndpointPolicyDefinitionsClient) Delete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (result ServiceEndpointPolicyDefinitionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ServiceEndpointPolicyDefinitionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyDefinitionName": autorest.Encode("path", serviceEndpointPolicyDefinitionName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) DeleteSender(req *http.Request) (future ServiceEndpointPolicyDefinitionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the specified service endpoint policy definitions from service endpoint policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy name. -// serviceEndpointPolicyDefinitionName - the name of the service endpoint policy definition name. -func (client ServiceEndpointPolicyDefinitionsClient) Get(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (result ServiceEndpointPolicyDefinition, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ServiceEndpointPolicyDefinitionsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyDefinitionName": autorest.Encode("path", serviceEndpointPolicyDefinitionName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) GetResponder(resp *http.Response) (result ServiceEndpointPolicyDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup gets all service endpoint policy definitions in a service end point policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy name. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (result ServiceEndpointPolicyDefinitionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.sepdlr.Response.Response != nil { - sc = result.sepdlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, serviceEndpointPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.sepdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.sepdlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.sepdlr.hasNextLink() && result.sepdlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupResponder(resp *http.Response) (result ServiceEndpointPolicyDefinitionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ServiceEndpointPolicyDefinitionsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ServiceEndpointPolicyDefinitionListResult) (result ServiceEndpointPolicyDefinitionListResult, err error) { - req, err := lastResults.serviceEndpointPolicyDefinitionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (result ServiceEndpointPolicyDefinitionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, serviceEndpointPolicyName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/subnets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/subnets.go deleted file mode 100644 index 8446bbd16..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/subnets.go +++ /dev/null @@ -1,395 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SubnetsClient is the network Client -type SubnetsClient struct { - BaseClient -} - -// NewSubnetsClient creates an instance of the SubnetsClient client. -func NewSubnetsClient(subscriptionID string) SubnetsClient { - return NewSubnetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSubnetsClientWithBaseURI creates an instance of the SubnetsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSubnetsClientWithBaseURI(baseURI string, subscriptionID string) SubnetsClient { - return SubnetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a subnet in the specified virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -// subnetParameters - parameters supplied to the create or update subnet operation. -func (client SubnetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet) (result SubnetsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SubnetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), - autorest.WithJSON(subnetParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) CreateOrUpdateSender(req *http.Request) (future SubnetsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SubnetsClient) CreateOrUpdateResponder(resp *http.Response) (result Subnet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified subnet. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -func (client SubnetsClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (result SubnetsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkName, subnetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SubnetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) DeleteSender(req *http.Request) (future SubnetsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SubnetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified subnet by virtual network and resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -// expand - expands referenced resources. -func (client SubnetsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (result Subnet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkName, subnetName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SubnetsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SubnetsClient) GetResponder(resp *http.Response) (result Subnet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all subnets in a virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client SubnetsClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result SubnetListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.List") - defer func() { - sc := -1 - if result.slr.Response.Response != nil { - sc = result.slr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.slr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending request") - return - } - - result.slr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure responding to request") - return - } - if result.slr.hasNextLink() && result.slr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SubnetsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SubnetsClient) ListResponder(resp *http.Response) (result SubnetListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client SubnetsClient) listNextResults(ctx context.Context, lastResults SubnetListResult) (result SubnetListResult, err error) { - req, err := lastResults.subnetListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SubnetsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result SubnetListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualNetworkName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/usages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/usages.go deleted file mode 100644 index 7c0d39b64..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/usages.go +++ /dev/null @@ -1,154 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// UsagesClient is the network Client -type UsagesClient struct { - BaseClient -} - -// NewUsagesClient creates an instance of the UsagesClient client. -func NewUsagesClient(subscriptionID string) UsagesClient { - return NewUsagesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewUsagesClientWithBaseURI creates an instance of the UsagesClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewUsagesClientWithBaseURI(baseURI string, subscriptionID string) UsagesClient { - return UsagesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list network usages for a subscription. -// Parameters: -// location - the location where resource usage is queried. -func (client UsagesClient) List(ctx context.Context, location string) (result UsagesListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesClient.List") - defer func() { - sc := -1 - if result.ulr.Response.Response != nil { - sc = result.ulr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: location, - Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._ ]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.UsagesClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ulr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request") - return - } - - result.ulr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure responding to request") - return - } - if result.ulr.hasNextLink() && result.ulr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client UsagesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client UsagesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client UsagesClient) ListResponder(resp *http.Response) (result UsagesListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client UsagesClient) listNextResults(ctx context.Context, lastResults UsagesListResult) (result UsagesListResult, err error) { - req, err := lastResults.usagesListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.UsagesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.UsagesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.UsagesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client UsagesClient) ListComplete(ctx context.Context, location string) (result UsagesListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/version.go deleted file mode 100644 index aea31f6ca..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package network - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// UserAgent returns the UserAgent string to use when sending http.Requests. -func UserAgent() string { - return "Azure-SDK-For-Go/" + Version() + " network/2018-10-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualhubs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualhubs.go deleted file mode 100644 index 9752a33fb..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualhubs.go +++ /dev/null @@ -1,579 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualHubsClient is the network Client -type VirtualHubsClient struct { - BaseClient -} - -// NewVirtualHubsClient creates an instance of the VirtualHubsClient client. -func NewVirtualHubsClient(subscriptionID string) VirtualHubsClient { - return NewVirtualHubsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualHubsClientWithBaseURI creates an instance of the VirtualHubsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualHubsClientWithBaseURI(baseURI string, subscriptionID string) VirtualHubsClient { - return VirtualHubsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VirtualHub resource if it doesn't exist else updates the existing VirtualHub. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// virtualHubParameters - parameters supplied to create or update VirtualHub. -func (client VirtualHubsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters VirtualHub) (result VirtualHubsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, virtualHubParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualHubsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters VirtualHub) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - virtualHubParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithJSON(virtualHubParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) CreateOrUpdateSender(req *http.Request) (future VirtualHubsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualHub, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VirtualHub. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client VirtualHubsClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string) (result VirtualHubsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualHubsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) DeleteSender(req *http.Request) (future VirtualHubsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VirtualHub. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client VirtualHubsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string) (result VirtualHub, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualHubsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) GetResponder(resp *http.Response) (result VirtualHub, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VirtualHubs in a subscription. -func (client VirtualHubsClient) List(ctx context.Context) (result ListVirtualHubsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.List") - defer func() { - sc := -1 - if result.lvhr.Response.Response != nil { - sc = result.lvhr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvhr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "List", resp, "Failure sending request") - return - } - - result.lvhr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "List", resp, "Failure responding to request") - return - } - if result.lvhr.hasNextLink() && result.lvhr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualHubsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualHubs", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) ListResponder(resp *http.Response) (result ListVirtualHubsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualHubsClient) listNextResults(ctx context.Context, lastResults ListVirtualHubsResult) (result ListVirtualHubsResult, err error) { - req, err := lastResults.listVirtualHubsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualHubsClient) ListComplete(ctx context.Context) (result ListVirtualHubsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the VirtualHubs in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -func (client VirtualHubsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVirtualHubsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvhr.Response.Response != nil { - sc = result.lvhr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvhr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvhr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvhr.hasNextLink() && result.lvhr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualHubsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) ListByResourceGroupResponder(resp *http.Response) (result ListVirtualHubsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client VirtualHubsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVirtualHubsResult) (result ListVirtualHubsResult, err error) { - req, err := lastResults.listVirtualHubsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualHubsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVirtualHubsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates VirtualHub tags. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// virtualHubParameters - parameters supplied to update VirtualHub tags. -func (client VirtualHubsClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters TagsObject) (result VirtualHubsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualHubName, virtualHubParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualHubsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithJSON(virtualHubParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) UpdateTagsSender(req *http.Request) (future VirtualHubsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) UpdateTagsResponder(resp *http.Response) (result VirtualHub, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkgatewayconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkgatewayconnections.go deleted file mode 100644 index 664e42a3e..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkgatewayconnections.go +++ /dev/null @@ -1,743 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkGatewayConnectionsClient is the network Client -type VirtualNetworkGatewayConnectionsClient struct { - BaseClient -} - -// NewVirtualNetworkGatewayConnectionsClient creates an instance of the VirtualNetworkGatewayConnectionsClient client. -func NewVirtualNetworkGatewayConnectionsClient(subscriptionID string) VirtualNetworkGatewayConnectionsClient { - return NewVirtualNetworkGatewayConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkGatewayConnectionsClientWithBaseURI creates an instance of the -// VirtualNetworkGatewayConnectionsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualNetworkGatewayConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkGatewayConnectionsClient { - return VirtualNetworkGatewayConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a virtual network gateway connection in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -// parameters - parameters supplied to the create or update virtual network gateway connection operation. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection) (result VirtualNetworkGatewayConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkGatewayConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network Gateway connection. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -func (client VirtualNetworkGatewayConnectionsClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) DeleteSender(req *http.Request) (future VirtualNetworkGatewayConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified virtual network gateway connection by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -func (client VirtualNetworkGatewayConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkGatewayConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) GetResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSharedKey the Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified -// virtual network gateway connection shared key through Network resource provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the virtual network gateway connection shared key name. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result ConnectionSharedKey, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.GetSharedKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", nil, "Failure preparing request") - return - } - - resp, err := client.GetSharedKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure sending request") - return - } - - result, err = client.GetSharedKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure responding to request") - return - } - - return -} - -// GetSharedKeyPreparer prepares the GetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSharedKeySender sends the GetSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetSharedKeyResponder handles the response to the GetSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyResponder(resp *http.Response) (result ConnectionSharedKey, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List the List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections -// created. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworkGatewayConnectionsClient) List(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.List") - defer func() { - sc := -1 - if result.vngclr.Response.Response != nil { - sc = result.vngclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vngclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.vngclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.vngclr.hasNextLink() && result.vngclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworkGatewayConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) ListResponder(resp *http.Response) (result VirtualNetworkGatewayConnectionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualNetworkGatewayConnectionsClient) listNextResults(ctx context.Context, lastResults VirtualNetworkGatewayConnectionListResult) (result VirtualNetworkGatewayConnectionListResult, err error) { - req, err := lastResults.virtualNetworkGatewayConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkGatewayConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ResetSharedKey the VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway -// connection shared key for passed virtual network gateway connection in the specified resource group through Network -// resource provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the virtual network gateway connection reset shared key Name. -// parameters - parameters supplied to the begin reset virtual network gateway connection shared key operation -// through network resource provider. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey) (result VirtualNetworkGatewayConnectionsResetSharedKeyFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.ResetSharedKey") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.KeyLength", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.KeyLength", Name: validation.InclusiveMaximum, Rule: int64(128), Chain: nil}, - {Target: "parameters.KeyLength", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", err.Error()) - } - - req, err := client.ResetSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", nil, "Failure preparing request") - return - } - - result, err = client.ResetSharedKeySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetSharedKeyPreparer prepares the ResetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetSharedKeySender sends the ResetSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeySender(req *http.Request) (future VirtualNetworkGatewayConnectionsResetSharedKeyFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetSharedKeyResponder handles the response to the ResetSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyResponder(resp *http.Response) (result ConnectionResetSharedKey, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetSharedKey the Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection -// shared key for passed virtual network gateway connection in the specified resource group through Network resource -// provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the virtual network gateway connection name. -// parameters - parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation -// throughNetwork resource provider. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey) (result VirtualNetworkGatewayConnectionsSetSharedKeyFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.SetSharedKey") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", err.Error()) - } - - req, err := client.SetSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", nil, "Failure preparing request") - return - } - - result, err = client.SetSharedKeySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", result.Response(), "Failure sending request") - return - } - - return -} - -// SetSharedKeyPreparer prepares the SetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetSharedKeySender sends the SetSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeySender(req *http.Request) (future VirtualNetworkGatewayConnectionsSetSharedKeyFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// SetSharedKeyResponder handles the response to the SetSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyResponder(resp *http.Response) (result ConnectionSharedKey, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates a virtual network gateway connection tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -// parameters - parameters supplied to update virtual network gateway connection tags. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters TagsObject) (result VirtualNetworkGatewayConnectionsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTagsSender(req *http.Request) (future VirtualNetworkGatewayConnectionsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkgateways.go deleted file mode 100644 index 3dc45de4a..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkgateways.go +++ /dev/null @@ -1,1573 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkGatewaysClient is the network Client -type VirtualNetworkGatewaysClient struct { - BaseClient -} - -// NewVirtualNetworkGatewaysClient creates an instance of the VirtualNetworkGatewaysClient client. -func NewVirtualNetworkGatewaysClient(subscriptionID string) VirtualNetworkGatewaysClient { - return NewVirtualNetworkGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkGatewaysClientWithBaseURI creates an instance of the VirtualNetworkGatewaysClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkGatewaysClient { - return VirtualNetworkGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a virtual network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to create or update virtual network gateway operation. -func (client VirtualNetworkGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (result VirtualNetworkGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) DeleteSender(req *http.Request) (future VirtualNetworkGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Generatevpnclientpackage generates VPN client package for P2S client of the virtual network gateway in the specified -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to the generate virtual network gateway VPN client package operation. -func (client VirtualNetworkGatewaysClient) Generatevpnclientpackage(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (result VirtualNetworkGatewaysGeneratevpnclientpackageFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Generatevpnclientpackage") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GeneratevpnclientpackagePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", nil, "Failure preparing request") - return - } - - result, err = client.GeneratevpnclientpackageSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", result.Response(), "Failure sending request") - return - } - - return -} - -// GeneratevpnclientpackagePreparer prepares the Generatevpnclientpackage request. -func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackagePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/generatevpnclientpackage", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GeneratevpnclientpackageSender sends the Generatevpnclientpackage request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageSender(req *http.Request) (future VirtualNetworkGatewaysGeneratevpnclientpackageFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GeneratevpnclientpackageResponder handles the response to the Generatevpnclientpackage request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GenerateVpnProfile generates VPN profile for P2S client of the virtual network gateway in the specified resource -// group. Used for IKEV2 and radius based authentication. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to the generate virtual network gateway VPN client package operation. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfile(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (result VirtualNetworkGatewaysGenerateVpnProfileFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GenerateVpnProfile") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GenerateVpnProfilePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GenerateVpnProfile", nil, "Failure preparing request") - return - } - - result, err = client.GenerateVpnProfileSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GenerateVpnProfile", result.Response(), "Failure sending request") - return - } - - return -} - -// GenerateVpnProfilePreparer prepares the GenerateVpnProfile request. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfilePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/generatevpnprofile", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GenerateVpnProfileSender sends the GenerateVpnProfile request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfileSender(req *http.Request) (future VirtualNetworkGatewaysGenerateVpnProfileFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GenerateVpnProfileResponder handles the response to the GenerateVpnProfile request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfileResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get gets the specified virtual network gateway by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAdvertisedRoutes this operation retrieves a list of routes the virtual network gateway is advertising to the -// specified peer. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// peer - the IP address of the peer -func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (result VirtualNetworkGatewaysGetAdvertisedRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetAdvertisedRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetAdvertisedRoutesPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, peer) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetAdvertisedRoutes", nil, "Failure preparing request") - return - } - - result, err = client.GetAdvertisedRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetAdvertisedRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// GetAdvertisedRoutesPreparer prepares the GetAdvertisedRoutes request. -func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - "peer": autorest.Encode("query", peer), - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getAdvertisedRoutes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetAdvertisedRoutesSender sends the GetAdvertisedRoutes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutesSender(req *http.Request) (future VirtualNetworkGatewaysGetAdvertisedRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetAdvertisedRoutesResponder handles the response to the GetAdvertisedRoutes request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutesResponder(resp *http.Response) (result GatewayRouteListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetBgpPeerStatus the GetBgpPeerStatus operation retrieves the status of all BGP peers. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// peer - the IP address of the peer to retrieve the status of. -func (client VirtualNetworkGatewaysClient) GetBgpPeerStatus(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (result VirtualNetworkGatewaysGetBgpPeerStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetBgpPeerStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetBgpPeerStatusPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, peer) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetBgpPeerStatus", nil, "Failure preparing request") - return - } - - result, err = client.GetBgpPeerStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetBgpPeerStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// GetBgpPeerStatusPreparer prepares the GetBgpPeerStatus request. -func (client VirtualNetworkGatewaysClient) GetBgpPeerStatusPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(peer) > 0 { - queryParameters["peer"] = autorest.Encode("query", peer) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getBgpPeerStatus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetBgpPeerStatusSender sends the GetBgpPeerStatus request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetBgpPeerStatusSender(req *http.Request) (future VirtualNetworkGatewaysGetBgpPeerStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetBgpPeerStatusResponder handles the response to the GetBgpPeerStatus request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetBgpPeerStatusResponder(resp *http.Response) (result BgpPeerStatusListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetLearnedRoutes this operation retrieves a list of routes the virtual network gateway has learned, including routes -// learned from BGP peers. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) GetLearnedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysGetLearnedRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetLearnedRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetLearnedRoutesPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetLearnedRoutes", nil, "Failure preparing request") - return - } - - result, err = client.GetLearnedRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetLearnedRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// GetLearnedRoutesPreparer prepares the GetLearnedRoutes request. -func (client VirtualNetworkGatewaysClient) GetLearnedRoutesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getLearnedRoutes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetLearnedRoutesSender sends the GetLearnedRoutes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetLearnedRoutesSender(req *http.Request) (future VirtualNetworkGatewaysGetLearnedRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetLearnedRoutesResponder handles the response to the GetLearnedRoutes request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetLearnedRoutesResponder(resp *http.Response) (result GatewayRouteListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVpnclientIpsecParameters the Get VpnclientIpsecParameters operation retrieves information about the vpnclient -// ipsec policy for P2S client of virtual network gateway in the specified resource group through Network resource -// provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the virtual network gateway name. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetVpnclientIpsecParameters") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVpnclientIpsecParametersPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnclientIpsecParameters", nil, "Failure preparing request") - return - } - - result, err = client.GetVpnclientIpsecParametersSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnclientIpsecParameters", result.Response(), "Failure sending request") - return - } - - return -} - -// GetVpnclientIpsecParametersPreparer prepares the GetVpnclientIpsecParameters request. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParametersPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getvpnclientipsecparameters", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVpnclientIpsecParametersSender sends the GetVpnclientIpsecParameters request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParametersSender(req *http.Request) (future VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetVpnclientIpsecParametersResponder handles the response to the GetVpnclientIpsecParameters request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParametersResponder(resp *http.Response) (result VpnClientIPsecParameters, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVpnProfilePackageURL gets pre-generated VPN profile for P2S client of the virtual network gateway in the -// specified resource group. The profile needs to be generated first using generateVpnProfile. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURL(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysGetVpnProfilePackageURLFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetVpnProfilePackageURL") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVpnProfilePackageURLPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnProfilePackageURL", nil, "Failure preparing request") - return - } - - result, err = client.GetVpnProfilePackageURLSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnProfilePackageURL", result.Response(), "Failure sending request") - return - } - - return -} - -// GetVpnProfilePackageURLPreparer prepares the GetVpnProfilePackageURL request. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURLPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getvpnprofilepackageurl", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVpnProfilePackageURLSender sends the GetVpnProfilePackageURL request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURLSender(req *http.Request) (future VirtualNetworkGatewaysGetVpnProfilePackageURLFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetVpnProfilePackageURLResponder handles the response to the GetVpnProfilePackageURL request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURLResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all virtual network gateways by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworkGatewaysClient) List(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.vnglr.Response.Response != nil { - sc = result.vnglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vnglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.vnglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.vnglr.hasNextLink() && result.vnglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworkGatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ListResponder(resp *http.Response) (result VirtualNetworkGatewayListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualNetworkGatewaysClient) listNextResults(ctx context.Context, lastResults VirtualNetworkGatewayListResult) (result VirtualNetworkGatewayListResult, err error) { - req, err := lastResults.virtualNetworkGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkGatewaysClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListConnections gets all the connections in a virtual network gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) ListConnections(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewayListConnectionsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.ListConnections") - defer func() { - sc := -1 - if result.vnglcr.Response.Response != nil { - sc = result.vnglcr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listConnectionsNextResults - req, err := client.ListConnectionsPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ListConnections", nil, "Failure preparing request") - return - } - - resp, err := client.ListConnectionsSender(req) - if err != nil { - result.vnglcr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ListConnections", resp, "Failure sending request") - return - } - - result.vnglcr, err = client.ListConnectionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ListConnections", resp, "Failure responding to request") - return - } - if result.vnglcr.hasNextLink() && result.vnglcr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListConnectionsPreparer prepares the ListConnections request. -func (client VirtualNetworkGatewaysClient) ListConnectionsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/connections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListConnectionsSender sends the ListConnections request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ListConnectionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListConnectionsResponder handles the response to the ListConnections request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ListConnectionsResponder(resp *http.Response) (result VirtualNetworkGatewayListConnectionsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listConnectionsNextResults retrieves the next set of results, if any. -func (client VirtualNetworkGatewaysClient) listConnectionsNextResults(ctx context.Context, lastResults VirtualNetworkGatewayListConnectionsResult) (result VirtualNetworkGatewayListConnectionsResult, err error) { - req, err := lastResults.virtualNetworkGatewayListConnectionsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listConnectionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListConnectionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listConnectionsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListConnectionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listConnectionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListConnectionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkGatewaysClient) ListConnectionsComplete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewayListConnectionsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.ListConnections") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListConnections(ctx, resourceGroupName, virtualNetworkGatewayName) - return -} - -// Reset resets the primary of the virtual network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// gatewayVip - virtual network gateway vip address supplied to the begin reset of the active-active feature -// enabled gateway. -func (client VirtualNetworkGatewaysClient) Reset(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, gatewayVip string) (result VirtualNetworkGatewaysResetFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Reset") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, gatewayVip) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", nil, "Failure preparing request") - return - } - - result, err = client.ResetSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetPreparer prepares the Reset request. -func (client VirtualNetworkGatewaysClient) ResetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, gatewayVip string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(gatewayVip) > 0 { - queryParameters["gatewayVip"] = autorest.Encode("query", gatewayVip) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/reset", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetSender sends the Reset request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ResetSender(req *http.Request) (future VirtualNetworkGatewaysResetFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetResponder handles the response to the Reset request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ResetResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ResetVpnClientSharedKey resets the VPN client shared key of the virtual network gateway in the specified resource -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysResetVpnClientSharedKeyFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.ResetVpnClientSharedKey") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetVpnClientSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ResetVpnClientSharedKey", nil, "Failure preparing request") - return - } - - result, err = client.ResetVpnClientSharedKeySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ResetVpnClientSharedKey", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetVpnClientSharedKeyPreparer prepares the ResetVpnClientSharedKey request. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/resetvpnclientsharedkey", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetVpnClientSharedKeySender sends the ResetVpnClientSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKeySender(req *http.Request) (future VirtualNetworkGatewaysResetVpnClientSharedKeyFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetVpnClientSharedKeyResponder handles the response to the ResetVpnClientSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// SetVpnclientIpsecParameters the Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy for P2S -// client of virtual network gateway in the specified resource group through Network resource provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// vpnclientIpsecParams - parameters supplied to the Begin Set vpnclient ipsec parameters of Virtual Network -// Gateway P2S client operation through Network resource provider. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, vpnclientIpsecParams VpnClientIPsecParameters) (result VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.SetVpnclientIpsecParameters") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: vpnclientIpsecParams, - Constraints: []validation.Constraint{{Target: "vpnclientIpsecParams.SaLifeTimeSeconds", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "vpnclientIpsecParams.SaDataSizeKilobytes", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewaysClient", "SetVpnclientIpsecParameters", err.Error()) - } - - req, err := client.SetVpnclientIpsecParametersPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, vpnclientIpsecParams) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SetVpnclientIpsecParameters", nil, "Failure preparing request") - return - } - - result, err = client.SetVpnclientIpsecParametersSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SetVpnclientIpsecParameters", result.Response(), "Failure sending request") - return - } - - return -} - -// SetVpnclientIpsecParametersPreparer prepares the SetVpnclientIpsecParameters request. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParametersPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, vpnclientIpsecParams VpnClientIPsecParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/setvpnclientipsecparameters", pathParameters), - autorest.WithJSON(vpnclientIpsecParams), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetVpnclientIpsecParametersSender sends the SetVpnclientIpsecParameters request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParametersSender(req *http.Request) (future VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// SetVpnclientIpsecParametersResponder handles the response to the SetVpnclientIpsecParameters request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParametersResponder(resp *http.Response) (result VpnClientIPsecParameters, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SupportedVpnDevices gets a xml format representation for supported vpn devices. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevices(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result String, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.SupportedVpnDevices") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.SupportedVpnDevicesPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SupportedVpnDevices", nil, "Failure preparing request") - return - } - - resp, err := client.SupportedVpnDevicesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SupportedVpnDevices", resp, "Failure sending request") - return - } - - result, err = client.SupportedVpnDevicesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SupportedVpnDevices", resp, "Failure responding to request") - return - } - - return -} - -// SupportedVpnDevicesPreparer prepares the SupportedVpnDevices request. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevicesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/supportedvpndevices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SupportedVpnDevicesSender sends the SupportedVpnDevices request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevicesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SupportedVpnDevicesResponder handles the response to the SupportedVpnDevices request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevicesResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates a virtual network gateway tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to update virtual network gateway tags. -func (client VirtualNetworkGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters TagsObject) (result VirtualNetworkGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworkGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) UpdateTagsSender(req *http.Request) (future VirtualNetworkGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// VpnDeviceConfigurationScript gets a xml format representation for vpn device configuration script. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection for which the -// configuration script is generated. -// parameters - parameters supplied to the generate vpn device script operation. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScript(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VpnDeviceScriptParameters) (result String, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.VpnDeviceConfigurationScript") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.VpnDeviceConfigurationScriptPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "VpnDeviceConfigurationScript", nil, "Failure preparing request") - return - } - - resp, err := client.VpnDeviceConfigurationScriptSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "VpnDeviceConfigurationScript", resp, "Failure sending request") - return - } - - result, err = client.VpnDeviceConfigurationScriptResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "VpnDeviceConfigurationScript", resp, "Failure responding to request") - return - } - - return -} - -// VpnDeviceConfigurationScriptPreparer prepares the VpnDeviceConfigurationScript request. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScriptPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VpnDeviceScriptParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/vpndeviceconfigurationscript", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// VpnDeviceConfigurationScriptSender sends the VpnDeviceConfigurationScript request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScriptSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// VpnDeviceConfigurationScriptResponder handles the response to the VpnDeviceConfigurationScript request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScriptResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkpeerings.go deleted file mode 100644 index 2c72cd4f1..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworkpeerings.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkPeeringsClient is the network Client -type VirtualNetworkPeeringsClient struct { - BaseClient -} - -// NewVirtualNetworkPeeringsClient creates an instance of the VirtualNetworkPeeringsClient client. -func NewVirtualNetworkPeeringsClient(subscriptionID string) VirtualNetworkPeeringsClient { - return NewVirtualNetworkPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkPeeringsClientWithBaseURI creates an instance of the VirtualNetworkPeeringsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualNetworkPeeringsClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkPeeringsClient { - return VirtualNetworkPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a peering in the specified virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// virtualNetworkPeeringName - the name of the peering. -// virtualNetworkPeeringParameters - parameters supplied to the create or update virtual network peering -// operation. -func (client VirtualNetworkPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering) (result VirtualNetworkPeeringsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}", pathParameters), - autorest.WithJSON(virtualNetworkPeeringParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkPeeringsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network peering. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// virtualNetworkPeeringName - the name of the virtual network peering. -func (client VirtualNetworkPeeringsClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (result VirtualNetworkPeeringsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) DeleteSender(req *http.Request) (future VirtualNetworkPeeringsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified virtual network peering. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// virtualNetworkPeeringName - the name of the virtual network peering. -func (client VirtualNetworkPeeringsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (result VirtualNetworkPeering, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) GetResponder(resp *http.Response) (result VirtualNetworkPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all virtual network peerings in a virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client VirtualNetworkPeeringsClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkPeeringListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.List") - defer func() { - sc := -1 - if result.vnplr.Response.Response != nil { - sc = result.vnplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vnplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", resp, "Failure sending request") - return - } - - result.vnplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", resp, "Failure responding to request") - return - } - if result.vnplr.hasNextLink() && result.vnplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworkPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) ListResponder(resp *http.Response) (result VirtualNetworkPeeringListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualNetworkPeeringsClient) listNextResults(ctx context.Context, lastResults VirtualNetworkPeeringListResult) (result VirtualNetworkPeeringListResult, err error) { - req, err := lastResults.virtualNetworkPeeringListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkPeeringListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualNetworkName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworks.go deleted file mode 100644 index a7a3c56b3..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworks.go +++ /dev/null @@ -1,778 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworksClient is the network Client -type VirtualNetworksClient struct { - BaseClient -} - -// NewVirtualNetworksClient creates an instance of the VirtualNetworksClient client. -func NewVirtualNetworksClient(subscriptionID string) VirtualNetworksClient { - return NewVirtualNetworksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworksClientWithBaseURI creates an instance of the VirtualNetworksClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualNetworksClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworksClient { - return VirtualNetworksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckIPAddressAvailability checks whether a private IP address is available for use. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// IPAddress - the private IP address to be verified. -func (client VirtualNetworksClient) CheckIPAddressAvailability(ctx context.Context, resourceGroupName string, virtualNetworkName string, IPAddress string) (result IPAddressAvailabilityResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.CheckIPAddressAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CheckIPAddressAvailabilityPreparer(ctx, resourceGroupName, virtualNetworkName, IPAddress) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckIPAddressAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckIPAddressAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckIPAddressAvailabilityPreparer prepares the CheckIPAddressAvailability request. -func (client VirtualNetworksClient) CheckIPAddressAvailabilityPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, IPAddress string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - "ipAddress": autorest.Encode("query", IPAddress), - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/CheckIPAddressAvailability", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckIPAddressAvailabilitySender sends the CheckIPAddressAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) CheckIPAddressAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckIPAddressAvailabilityResponder handles the response to the CheckIPAddressAvailability request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) CheckIPAddressAvailabilityResponder(resp *http.Response) (result IPAddressAvailabilityResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates a virtual network in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// parameters - parameters supplied to the create or update virtual network operation -func (client VirtualNetworksClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork) (result VirtualNetworksCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworksClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworksCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetwork, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client VirtualNetworksClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworksDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworksClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) DeleteSender(req *http.Request) (future VirtualNetworksDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified virtual network by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// expand - expands referenced resources. -func (client VirtualNetworksClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, expand string) (result VirtualNetwork, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworksClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result VirtualNetwork, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all virtual networks in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworksClient) List(ctx context.Context, resourceGroupName string) (result VirtualNetworkListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.List") - defer func() { - sc := -1 - if result.vnlr.Response.Response != nil { - sc = result.vnlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vnlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending request") - return - } - - result.vnlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure responding to request") - return - } - if result.vnlr.hasNextLink() && result.vnlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworksClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) ListResponder(resp *http.Response) (result VirtualNetworkListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) listNextResults(ctx context.Context, lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { - req, err := lastResults.virtualNetworkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworksClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all virtual networks in a subscription. -func (client VirtualNetworksClient) ListAll(ctx context.Context) (result VirtualNetworkListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListAll") - defer func() { - sc := -1 - if result.vnlr.Response.Response != nil { - sc = result.vnlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.vnlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending request") - return - } - - result.vnlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure responding to request") - return - } - if result.vnlr.hasNextLink() && result.vnlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client VirtualNetworksClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) ListAllResponder(resp *http.Response) (result VirtualNetworkListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) listAllNextResults(ctx context.Context, lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { - req, err := lastResults.virtualNetworkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworksClient) ListAllComplete(ctx context.Context) (result VirtualNetworkListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListUsage lists usage stats. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client VirtualNetworksClient) ListUsage(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkListUsageResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListUsage") - defer func() { - sc := -1 - if result.vnlur.Response.Response != nil { - sc = result.vnlur.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listUsageNextResults - req, err := client.ListUsagePreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListUsage", nil, "Failure preparing request") - return - } - - resp, err := client.ListUsageSender(req) - if err != nil { - result.vnlur.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListUsage", resp, "Failure sending request") - return - } - - result.vnlur, err = client.ListUsageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListUsage", resp, "Failure responding to request") - return - } - if result.vnlur.hasNextLink() && result.vnlur.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListUsagePreparer prepares the ListUsage request. -func (client VirtualNetworksClient) ListUsagePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/usages", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListUsageSender sends the ListUsage request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) ListUsageSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListUsageResponder handles the response to the ListUsage request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) ListUsageResponder(resp *http.Response) (result VirtualNetworkListUsageResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listUsageNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) listUsageNextResults(ctx context.Context, lastResults VirtualNetworkListUsageResult) (result VirtualNetworkListUsageResult, err error) { - req, err := lastResults.virtualNetworkListUsageResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listUsageNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListUsageSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listUsageNextResults", resp, "Failure sending next results request") - } - result, err = client.ListUsageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listUsageNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListUsageComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworksClient) ListUsageComplete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkListUsageResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListUsage") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListUsage(ctx, resourceGroupName, virtualNetworkName) - return -} - -// UpdateTags updates a virtual network tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// parameters - parameters supplied to update virtual network tags. -func (client VirtualNetworksClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters TagsObject) (result VirtualNetworksUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualNetworkName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworksClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) UpdateTagsSender(req *http.Request) (future VirtualNetworksUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetwork, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworktaps.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworktaps.go deleted file mode 100644 index 377f9311e..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualnetworktaps.go +++ /dev/null @@ -1,611 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkTapsClient is the network Client -type VirtualNetworkTapsClient struct { - BaseClient -} - -// NewVirtualNetworkTapsClient creates an instance of the VirtualNetworkTapsClient client. -func NewVirtualNetworkTapsClient(subscriptionID string) VirtualNetworkTapsClient { - return NewVirtualNetworkTapsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkTapsClientWithBaseURI creates an instance of the VirtualNetworkTapsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewVirtualNetworkTapsClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkTapsClient { - return VirtualNetworkTapsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Virtual Network Tap. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of the virtual network tap. -// parameters - parameters supplied to the create or update virtual network tap operation. -func (client VirtualNetworkTapsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap) (result VirtualNetworkTapsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - }}, - }}, - }}, - }}, - {Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkTapsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, tapName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkTapsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkTapsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkTap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network tap. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of the virtual network tap. -func (client VirtualNetworkTapsClient) Delete(ctx context.Context, resourceGroupName string, tapName string) (result VirtualNetworkTapsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, tapName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkTapsClient) DeletePreparer(ctx context.Context, resourceGroupName string, tapName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) DeleteSender(req *http.Request) (future VirtualNetworkTapsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified virtual network tap. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of virtual network tap. -func (client VirtualNetworkTapsClient) Get(ctx context.Context, resourceGroupName string, tapName string) (result VirtualNetworkTap, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, tapName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkTapsClient) GetPreparer(ctx context.Context, resourceGroupName string, tapName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) GetResponder(resp *http.Response) (result VirtualNetworkTap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAll gets all the VirtualNetworkTaps in a subscription. -func (client VirtualNetworkTapsClient) ListAll(ctx context.Context) (result VirtualNetworkTapListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListAll") - defer func() { - sc := -1 - if result.vntlr.Response.Response != nil { - sc = result.vntlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.vntlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", resp, "Failure sending request") - return - } - - result.vntlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.vntlr.hasNextLink() && result.vntlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client VirtualNetworkTapsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworkTaps", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) ListAllResponder(resp *http.Response) (result VirtualNetworkTapListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client VirtualNetworkTapsClient) listAllNextResults(ctx context.Context, lastResults VirtualNetworkTapListResult) (result VirtualNetworkTapListResult, err error) { - req, err := lastResults.virtualNetworkTapListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkTapsClient) ListAllComplete(ctx context.Context) (result VirtualNetworkTapListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListByResourceGroup gets all the VirtualNetworkTaps in a subscription. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworkTapsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result VirtualNetworkTapListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.vntlr.Response.Response != nil { - sc = result.vntlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.vntlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.vntlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.vntlr.hasNextLink() && result.vntlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualNetworkTapsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) ListByResourceGroupResponder(resp *http.Response) (result VirtualNetworkTapListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client VirtualNetworkTapsClient) listByResourceGroupNextResults(ctx context.Context, lastResults VirtualNetworkTapListResult) (result VirtualNetworkTapListResult, err error) { - req, err := lastResults.virtualNetworkTapListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkTapsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkTapListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates an VirtualNetworkTap tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of the tap. -// tapParameters - parameters supplied to update VirtualNetworkTap tags. -func (client VirtualNetworkTapsClient) UpdateTags(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject) (result VirtualNetworkTapsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, tapName, tapParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworkTapsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithJSON(tapParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) UpdateTagsSender(req *http.Request) (future VirtualNetworkTapsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetworkTap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualwans.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualwans.go deleted file mode 100644 index eb80b6898..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/virtualwans.go +++ /dev/null @@ -1,579 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualWansClient is the network Client -type VirtualWansClient struct { - BaseClient -} - -// NewVirtualWansClient creates an instance of the VirtualWansClient client. -func NewVirtualWansClient(subscriptionID string) VirtualWansClient { - return NewVirtualWansClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualWansClientWithBaseURI creates an instance of the VirtualWansClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualWansClientWithBaseURI(baseURI string, subscriptionID string) VirtualWansClient { - return VirtualWansClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being created or updated. -// wANParameters - parameters supplied to create or update VirtualWAN. -func (client VirtualWansClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters VirtualWAN) (result VirtualWansCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualWANName, wANParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualWansClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters VirtualWAN) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - wANParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithJSON(wANParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) CreateOrUpdateSender(req *http.Request) (future VirtualWansCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualWAN, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VirtualWAN. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being deleted. -func (client VirtualWansClient) Delete(ctx context.Context, resourceGroupName string, virtualWANName string) (result VirtualWansDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualWANName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualWansClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) DeleteSender(req *http.Request) (future VirtualWansDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VirtualWAN. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being retrieved. -func (client VirtualWansClient) Get(ctx context.Context, resourceGroupName string, virtualWANName string) (result VirtualWAN, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualWANName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualWansClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) GetResponder(resp *http.Response) (result VirtualWAN, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VirtualWANs in a subscription. -func (client VirtualWansClient) List(ctx context.Context) (result ListVirtualWANsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.List") - defer func() { - sc := -1 - if result.lvwnr.Response.Response != nil { - sc = result.lvwnr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvwnr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "List", resp, "Failure sending request") - return - } - - result.lvwnr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "List", resp, "Failure responding to request") - return - } - if result.lvwnr.hasNextLink() && result.lvwnr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualWansClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualWans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) ListResponder(resp *http.Response) (result ListVirtualWANsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VirtualWansClient) listNextResults(ctx context.Context, lastResults ListVirtualWANsResult) (result ListVirtualWANsResult, err error) { - req, err := lastResults.listVirtualWANsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualWansClient) ListComplete(ctx context.Context) (result ListVirtualWANsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the VirtualWANs in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -func (client VirtualWansClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVirtualWANsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvwnr.Response.Response != nil { - sc = result.lvwnr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvwnr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvwnr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvwnr.hasNextLink() && result.lvwnr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualWansClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) ListByResourceGroupResponder(resp *http.Response) (result ListVirtualWANsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client VirtualWansClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVirtualWANsResult) (result ListVirtualWANsResult, err error) { - req, err := lastResults.listVirtualWANsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualWansClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVirtualWANsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates a VirtualWAN tags. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being updated. -// wANParameters - parameters supplied to Update VirtualWAN tags. -func (client VirtualWansClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters TagsObject) (result VirtualWansUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualWANName, wANParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualWansClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithJSON(wANParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) UpdateTagsSender(req *http.Request) (future VirtualWansUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) UpdateTagsResponder(resp *http.Response) (result VirtualWAN, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnconnections.go deleted file mode 100644 index 69f742e46..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnconnections.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnConnectionsClient is the network Client -type VpnConnectionsClient struct { - BaseClient -} - -// NewVpnConnectionsClient creates an instance of the VpnConnectionsClient client. -func NewVpnConnectionsClient(subscriptionID string) VpnConnectionsClient { - return NewVpnConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnConnectionsClientWithBaseURI creates an instance of the VpnConnectionsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VpnConnectionsClient { - return VpnConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing -// connection. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the connection. -// vpnConnectionParameters - parameters supplied to create or Update a VPN Connection. -func (client VpnConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VpnConnection) (result VpnConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, connectionName, vpnConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VpnConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VpnConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnConnectionParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters), - autorest.WithJSON(vpnConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) CreateOrUpdateSender(req *http.Request) (future VpnConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result VpnConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a vpn connection. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the connection. -func (client VpnConnectionsClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result VpnConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VpnConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) DeleteSender(req *http.Request) (future VpnConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a vpn connection. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the vpn connection. -func (client VpnConnectionsClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result VpnConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) GetResponder(resp *http.Response) (result VpnConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVpnGateway retrieves all vpn connections for a particular virtual wan vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client VpnConnectionsClient) ListByVpnGateway(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnConnectionsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.ListByVpnGateway") - defer func() { - sc := -1 - if result.lvcr.Response.Response != nil { - sc = result.lvcr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVpnGatewayNextResults - req, err := client.ListByVpnGatewayPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVpnGatewaySender(req) - if err != nil { - result.lvcr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", resp, "Failure sending request") - return - } - - result.lvcr, err = client.ListByVpnGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", resp, "Failure responding to request") - return - } - if result.lvcr.hasNextLink() && result.lvcr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVpnGatewayPreparer prepares the ListByVpnGateway request. -func (client VpnConnectionsClient) ListByVpnGatewayPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVpnGatewaySender sends the ListByVpnGateway request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) ListByVpnGatewaySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVpnGatewayResponder handles the response to the ListByVpnGateway request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) ListByVpnGatewayResponder(resp *http.Response) (result ListVpnConnectionsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVpnGatewayNextResults retrieves the next set of results, if any. -func (client VpnConnectionsClient) listByVpnGatewayNextResults(ctx context.Context, lastResults ListVpnConnectionsResult) (result ListVpnConnectionsResult, err error) { - req, err := lastResults.listVpnConnectionsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVpnGatewaySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVpnGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVpnGatewayComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnConnectionsClient) ListByVpnGatewayComplete(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnConnectionsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.ListByVpnGateway") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVpnGateway(ctx, resourceGroupName, gatewayName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpngateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpngateways.go deleted file mode 100644 index 99b2a672f..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpngateways.go +++ /dev/null @@ -1,579 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnGatewaysClient is the network Client -type VpnGatewaysClient struct { - BaseClient -} - -// NewVpnGatewaysClient creates an instance of the VpnGatewaysClient client. -func NewVpnGatewaysClient(subscriptionID string) VpnGatewaysClient { - return NewVpnGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnGatewaysClientWithBaseURI creates an instance of the VpnGatewaysClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnGatewaysClientWithBaseURI(baseURI string, subscriptionID string) VpnGatewaysClient { - return VpnGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// vpnGatewayParameters - parameters supplied to create or Update a virtual wan vpn gateway. -func (client VpnGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters VpnGateway) (result VpnGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, vpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VpnGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters VpnGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnGatewayParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(vpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) CreateOrUpdateSender(req *http.Request) (future VpnGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result VpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a virtual wan vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client VpnGatewaysClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string) (result VpnGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VpnGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) DeleteSender(req *http.Request) (future VpnGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a virtual wan vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client VpnGatewaysClient) Get(ctx context.Context, resourceGroupName string, gatewayName string) (result VpnGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) GetResponder(resp *http.Response) (result VpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VpnGateways in a subscription. -func (client VpnGatewaysClient) List(ctx context.Context) (result ListVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.List") - defer func() { - sc := -1 - if result.lvgr.Response.Response != nil { - sc = result.lvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.lvgr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.lvgr.hasNextLink() && result.lvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VpnGatewaysClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) ListResponder(resp *http.Response) (result ListVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VpnGatewaysClient) listNextResults(ctx context.Context, lastResults ListVpnGatewaysResult) (result ListVpnGatewaysResult, err error) { - req, err := lastResults.listVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnGatewaysClient) ListComplete(ctx context.Context) (result ListVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the VpnGateways in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -func (client VpnGatewaysClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvgr.Response.Response != nil { - sc = result.lvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvgr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvgr.hasNextLink() && result.lvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VpnGatewaysClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) ListByResourceGroupResponder(resp *http.Response) (result ListVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client VpnGatewaysClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVpnGatewaysResult) (result ListVpnGatewaysResult, err error) { - req, err := lastResults.listVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnGatewaysClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates virtual wan vpn gateway tags. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// vpnGatewayParameters - parameters supplied to update a virtual wan vpn gateway tags. -func (client VpnGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters TagsObject) (result VpnGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, gatewayName, vpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VpnGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(vpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) UpdateTagsSender(req *http.Request) (future VpnGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) UpdateTagsResponder(resp *http.Response) (result VpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnsites.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnsites.go deleted file mode 100644 index f54871cb4..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnsites.go +++ /dev/null @@ -1,579 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnSitesClient is the network Client -type VpnSitesClient struct { - BaseClient -} - -// NewVpnSitesClient creates an instance of the VpnSitesClient client. -func NewVpnSitesClient(subscriptionID string) VpnSitesClient { - return NewVpnSitesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnSitesClientWithBaseURI creates an instance of the VpnSitesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnSitesClientWithBaseURI(baseURI string, subscriptionID string) VpnSitesClient { - return VpnSitesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VpnSite resource if it doesn't exist else updates the existing VpnSite. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being created or updated. -// vpnSiteParameters - parameters supplied to create or update VpnSite. -func (client VpnSitesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VpnSite) (result VpnSitesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VpnSitesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VpnSite) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnSiteParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithJSON(vpnSiteParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) CreateOrUpdateSender(req *http.Request) (future VpnSitesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) CreateOrUpdateResponder(resp *http.Response) (result VpnSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VpnSite. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being deleted. -func (client VpnSitesClient) Delete(ctx context.Context, resourceGroupName string, vpnSiteName string) (result VpnSitesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, vpnSiteName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VpnSitesClient) DeletePreparer(ctx context.Context, resourceGroupName string, vpnSiteName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) DeleteSender(req *http.Request) (future VpnSitesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VPN site. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being retrieved. -func (client VpnSitesClient) Get(ctx context.Context, resourceGroupName string, vpnSiteName string) (result VpnSite, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, vpnSiteName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnSitesClient) GetPreparer(ctx context.Context, resourceGroupName string, vpnSiteName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) GetResponder(resp *http.Response) (result VpnSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VpnSites in a subscription. -func (client VpnSitesClient) List(ctx context.Context) (result ListVpnSitesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.List") - defer func() { - sc := -1 - if result.lvsr.Response.Response != nil { - sc = result.lvsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", resp, "Failure sending request") - return - } - - result.lvsr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", resp, "Failure responding to request") - return - } - if result.lvsr.hasNextLink() && result.lvsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VpnSitesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnSites", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) ListResponder(resp *http.Response) (result ListVpnSitesResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client VpnSitesClient) listNextResults(ctx context.Context, lastResults ListVpnSitesResult) (result ListVpnSitesResult, err error) { - req, err := lastResults.listVpnSitesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnSitesClient) ListComplete(ctx context.Context) (result ListVpnSitesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the vpnSites in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -func (client VpnSitesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVpnSitesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvsr.Response.Response != nil { - sc = result.lvsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvsr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvsr.hasNextLink() && result.lvsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VpnSitesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) ListByResourceGroupResponder(resp *http.Response) (result ListVpnSitesResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client VpnSitesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVpnSitesResult) (result ListVpnSitesResult, err error) { - req, err := lastResults.listVpnSitesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnSitesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVpnSitesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates VpnSite tags. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being updated. -// vpnSiteParameters - parameters supplied to update VpnSite tags. -func (client VpnSitesClient) UpdateTags(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject) (result VpnSitesUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VpnSitesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithJSON(vpnSiteParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) UpdateTagsSender(req *http.Request) (future VpnSitesUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) UpdateTagsResponder(resp *http.Response) (result VpnSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnsitesconfiguration.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnsitesconfiguration.go deleted file mode 100644 index a9c40f76b..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/vpnsitesconfiguration.go +++ /dev/null @@ -1,113 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnSitesConfigurationClient is the network Client -type VpnSitesConfigurationClient struct { - BaseClient -} - -// NewVpnSitesConfigurationClient creates an instance of the VpnSitesConfigurationClient client. -func NewVpnSitesConfigurationClient(subscriptionID string) VpnSitesConfigurationClient { - return NewVpnSitesConfigurationClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnSitesConfigurationClientWithBaseURI creates an instance of the VpnSitesConfigurationClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVpnSitesConfigurationClientWithBaseURI(baseURI string, subscriptionID string) VpnSitesConfigurationClient { - return VpnSitesConfigurationClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Download gives the sas-url to download the configurations for vpn-sites in a resource group. -// Parameters: -// resourceGroupName - the resource group name. -// virtualWANName - the name of the VirtualWAN for which configuration of all vpn-sites is needed. -// request - parameters supplied to download vpn-sites configuration. -func (client VpnSitesConfigurationClient) Download(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVpnSitesConfigurationRequest) (result VpnSitesConfigurationDownloadFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesConfigurationClient.Download") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DownloadPreparer(ctx, resourceGroupName, virtualWANName, request) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationClient", "Download", nil, "Failure preparing request") - return - } - - result, err = client.DownloadSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationClient", "Download", result.Response(), "Failure sending request") - return - } - - return -} - -// DownloadPreparer prepares the Download request. -func (client VpnSitesConfigurationClient) DownloadPreparer(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVpnSitesConfigurationRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration", pathParameters), - autorest.WithJSON(request), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DownloadSender sends the Download request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesConfigurationClient) DownloadSender(req *http.Request) (future VpnSitesConfigurationDownloadFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DownloadResponder handles the response to the Download request. The method always -// closes the http.Response Body. -func (client VpnSitesConfigurationClient) DownloadResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/watchers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/watchers.go deleted file mode 100644 index 6233d7509..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network/watchers.go +++ /dev/null @@ -1,1560 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// WatchersClient is the network Client -type WatchersClient struct { - BaseClient -} - -// NewWatchersClient creates an instance of the WatchersClient client. -func NewWatchersClient(subscriptionID string) WatchersClient { - return NewWatchersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWatchersClientWithBaseURI creates an instance of the WatchersClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWatchersClientWithBaseURI(baseURI string, subscriptionID string) WatchersClient { - return WatchersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckConnectivity verifies the possibility of establishing a direct TCP connection from a virtual machine to a given -// endpoint including another VM or an arbitrary remote server. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that determine how the connectivity check will be performed. -func (client WatchersClient) CheckConnectivity(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters) (result WatchersCheckConnectivityFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.CheckConnectivity") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Source", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.Source.ResourceID", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.Destination", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "CheckConnectivity", err.Error()) - } - - req, err := client.CheckConnectivityPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "CheckConnectivity", nil, "Failure preparing request") - return - } - - result, err = client.CheckConnectivitySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "CheckConnectivity", result.Response(), "Failure sending request") - return - } - - return -} - -// CheckConnectivityPreparer prepares the CheckConnectivity request. -func (client WatchersClient) CheckConnectivityPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectivityCheck", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckConnectivitySender sends the CheckConnectivity request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) CheckConnectivitySender(req *http.Request) (future WatchersCheckConnectivityFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CheckConnectivityResponder handles the response to the CheckConnectivity request. The method always -// closes the http.Response Body. -func (client WatchersClient) CheckConnectivityResponder(resp *http.Response) (result ConnectivityInformation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates a network watcher in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the network watcher resource. -func (client WatchersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters Watcher) (result Watcher, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client WatchersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters Watcher) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client WatchersClient) CreateOrUpdateResponder(resp *http.Response) (result Watcher, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network watcher resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -func (client WatchersClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string) (result WatchersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client WatchersClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) DeleteSender(req *http.Request) (future WatchersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client WatchersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified network watcher by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -func (client WatchersClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string) (result Watcher, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkWatcherName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client WatchersClient) GetPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetResponder(resp *http.Response) (result Watcher, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAzureReachabilityReport gets the relative latency score for internet service providers from a specified location -// to Azure regions. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that determine Azure reachability report configuration. -func (client WatchersClient) GetAzureReachabilityReport(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters) (result WatchersGetAzureReachabilityReportFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetAzureReachabilityReport") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ProviderLocation", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ProviderLocation.Country", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.StartTime", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.EndTime", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetAzureReachabilityReport", err.Error()) - } - - req, err := client.GetAzureReachabilityReportPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetAzureReachabilityReport", nil, "Failure preparing request") - return - } - - result, err = client.GetAzureReachabilityReportSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetAzureReachabilityReport", result.Response(), "Failure sending request") - return - } - - return -} - -// GetAzureReachabilityReportPreparer prepares the GetAzureReachabilityReport request. -func (client WatchersClient) GetAzureReachabilityReportPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/azureReachabilityReport", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetAzureReachabilityReportSender sends the GetAzureReachabilityReport request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetAzureReachabilityReportSender(req *http.Request) (future WatchersGetAzureReachabilityReportFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetAzureReachabilityReportResponder handles the response to the GetAzureReachabilityReport request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetAzureReachabilityReportResponder(resp *http.Response) (result AzureReachabilityReport, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetFlowLogStatus queries status of flow log and traffic analytics (optional) on a specified resource. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define a resource to query flow log and traffic analytics (optional) status. -func (client WatchersClient) GetFlowLogStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters) (result WatchersGetFlowLogStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetFlowLogStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetFlowLogStatus", err.Error()) - } - - req, err := client.GetFlowLogStatusPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", nil, "Failure preparing request") - return - } - - result, err = client.GetFlowLogStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// GetFlowLogStatusPreparer prepares the GetFlowLogStatus request. -func (client WatchersClient) GetFlowLogStatusPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryFlowLogStatus", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetFlowLogStatusSender sends the GetFlowLogStatus request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetFlowLogStatusSender(req *http.Request) (future WatchersGetFlowLogStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetFlowLogStatusResponder handles the response to the GetFlowLogStatus request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetFlowLogStatusResponder(resp *http.Response) (result FlowLogInformation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetNetworkConfigurationDiagnostic get network configuration diagnostic. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters to get network configuration diagnostic. -func (client WatchersClient) GetNetworkConfigurationDiagnostic(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters) (result WatchersGetNetworkConfigurationDiagnosticFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetNetworkConfigurationDiagnostic") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.Profiles", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetNetworkConfigurationDiagnostic", err.Error()) - } - - req, err := client.GetNetworkConfigurationDiagnosticPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNetworkConfigurationDiagnostic", nil, "Failure preparing request") - return - } - - result, err = client.GetNetworkConfigurationDiagnosticSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNetworkConfigurationDiagnostic", result.Response(), "Failure sending request") - return - } - - return -} - -// GetNetworkConfigurationDiagnosticPreparer prepares the GetNetworkConfigurationDiagnostic request. -func (client WatchersClient) GetNetworkConfigurationDiagnosticPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/networkConfigurationDiagnostic", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetNetworkConfigurationDiagnosticSender sends the GetNetworkConfigurationDiagnostic request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetNetworkConfigurationDiagnosticSender(req *http.Request) (future WatchersGetNetworkConfigurationDiagnosticFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetNetworkConfigurationDiagnosticResponder handles the response to the GetNetworkConfigurationDiagnostic request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetNetworkConfigurationDiagnosticResponder(resp *http.Response) (result ConfigurationDiagnosticResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetNextHop gets the next hop from the specified VM. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the source and destination endpoint. -func (client WatchersClient) GetNextHop(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters) (result WatchersGetNextHopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetNextHop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.SourceIPAddress", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.DestinationIPAddress", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetNextHop", err.Error()) - } - - req, err := client.GetNextHopPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", nil, "Failure preparing request") - return - } - - result, err = client.GetNextHopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", result.Response(), "Failure sending request") - return - } - - return -} - -// GetNextHopPreparer prepares the GetNextHop request. -func (client WatchersClient) GetNextHopPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/nextHop", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetNextHopSender sends the GetNextHop request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetNextHopSender(req *http.Request) (future WatchersGetNextHopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetNextHopResponder handles the response to the GetNextHop request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetNextHopResponder(resp *http.Response) (result NextHopResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetTopology gets the current network topology by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the representation of topology. -func (client WatchersClient) GetTopology(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TopologyParameters) (result Topology, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTopology") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetTopologyPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", nil, "Failure preparing request") - return - } - - resp, err := client.GetTopologySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", resp, "Failure sending request") - return - } - - result, err = client.GetTopologyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", resp, "Failure responding to request") - return - } - - return -} - -// GetTopologyPreparer prepares the GetTopology request. -func (client WatchersClient) GetTopologyPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TopologyParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/topology", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetTopologySender sends the GetTopology request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetTopologySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetTopologyResponder handles the response to the GetTopology request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetTopologyResponder(resp *http.Response) (result Topology, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetTroubleshooting initiate troubleshooting on a specified resource -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define the resource to troubleshoot. -func (client WatchersClient) GetTroubleshooting(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters) (result WatchersGetTroubleshootingFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTroubleshooting") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.TroubleshootingProperties", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.TroubleshootingProperties.StorageID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.TroubleshootingProperties.StoragePath", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetTroubleshooting", err.Error()) - } - - req, err := client.GetTroubleshootingPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", nil, "Failure preparing request") - return - } - - result, err = client.GetTroubleshootingSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", result.Response(), "Failure sending request") - return - } - - return -} - -// GetTroubleshootingPreparer prepares the GetTroubleshooting request. -func (client WatchersClient) GetTroubleshootingPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/troubleshoot", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetTroubleshootingSender sends the GetTroubleshooting request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetTroubleshootingSender(req *http.Request) (future WatchersGetTroubleshootingFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetTroubleshootingResponder handles the response to the GetTroubleshooting request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetTroubleshootingResponder(resp *http.Response) (result TroubleshootingResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetTroubleshootingResult get the last completed troubleshooting result on a specified resource -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define the resource to query the troubleshooting result. -func (client WatchersClient) GetTroubleshootingResult(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters) (result WatchersGetTroubleshootingResultFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTroubleshootingResult") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetTroubleshootingResult", err.Error()) - } - - req, err := client.GetTroubleshootingResultPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", nil, "Failure preparing request") - return - } - - result, err = client.GetTroubleshootingResultSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", result.Response(), "Failure sending request") - return - } - - return -} - -// GetTroubleshootingResultPreparer prepares the GetTroubleshootingResult request. -func (client WatchersClient) GetTroubleshootingResultPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryTroubleshootResult", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetTroubleshootingResultSender sends the GetTroubleshootingResult request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetTroubleshootingResultSender(req *http.Request) (future WatchersGetTroubleshootingResultFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetTroubleshootingResultResponder handles the response to the GetTroubleshootingResult request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetTroubleshootingResultResponder(resp *http.Response) (result TroubleshootingResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVMSecurityRules gets the configured and effective security group rules on the specified VM. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the VM to check security groups for. -func (client WatchersClient) GetVMSecurityRules(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters) (result WatchersGetVMSecurityRulesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetVMSecurityRules") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetVMSecurityRules", err.Error()) - } - - req, err := client.GetVMSecurityRulesPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", nil, "Failure preparing request") - return - } - - result, err = client.GetVMSecurityRulesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", result.Response(), "Failure sending request") - return - } - - return -} - -// GetVMSecurityRulesPreparer prepares the GetVMSecurityRules request. -func (client WatchersClient) GetVMSecurityRulesPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/securityGroupView", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVMSecurityRulesSender sends the GetVMSecurityRules request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetVMSecurityRulesSender(req *http.Request) (future WatchersGetVMSecurityRulesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetVMSecurityRulesResponder handles the response to the GetVMSecurityRules request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetVMSecurityRulesResponder(resp *http.Response) (result SecurityGroupViewResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all network watchers by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client WatchersClient) List(ctx context.Context, resourceGroupName string) (result WatcherListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client WatchersClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client WatchersClient) ListResponder(resp *http.Response) (result WatcherListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAll gets all network watchers by subscription. -func (client WatchersClient) ListAll(ctx context.Context) (result WatcherListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.ListAll") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", resp, "Failure sending request") - return - } - - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", resp, "Failure responding to request") - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client WatchersClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkWatchers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client WatchersClient) ListAllResponder(resp *http.Response) (result WatcherListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAvailableProviders lists all available internet service providers for a specified Azure region. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that scope the list of available providers. -func (client WatchersClient) ListAvailableProviders(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters) (result WatchersListAvailableProvidersFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.ListAvailableProviders") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableProvidersPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAvailableProviders", nil, "Failure preparing request") - return - } - - result, err = client.ListAvailableProvidersSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAvailableProviders", result.Response(), "Failure sending request") - return - } - - return -} - -// ListAvailableProvidersPreparer prepares the ListAvailableProviders request. -func (client WatchersClient) ListAvailableProvidersPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/availableProvidersList", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableProvidersSender sends the ListAvailableProviders request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) ListAvailableProvidersSender(req *http.Request) (future WatchersListAvailableProvidersFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListAvailableProvidersResponder handles the response to the ListAvailableProviders request. The method always -// closes the http.Response Body. -func (client WatchersClient) ListAvailableProvidersResponder(resp *http.Response) (result AvailableProvidersList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetFlowLogConfiguration configures flow log and traffic analytics (optional) on a specified resource. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define the configuration of flow log. -func (client WatchersClient) SetFlowLogConfiguration(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation) (result WatchersSetFlowLogConfigurationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.SetFlowLogConfiguration") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.FlowLogProperties", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.FlowLogProperties.StorageID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.FlowLogProperties.Enabled", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "parameters.FlowAnalyticsConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.Enabled", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceRegion", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceResourceID", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "SetFlowLogConfiguration", err.Error()) - } - - req, err := client.SetFlowLogConfigurationPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", nil, "Failure preparing request") - return - } - - result, err = client.SetFlowLogConfigurationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", result.Response(), "Failure sending request") - return - } - - return -} - -// SetFlowLogConfigurationPreparer prepares the SetFlowLogConfiguration request. -func (client WatchersClient) SetFlowLogConfigurationPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/configureFlowLog", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetFlowLogConfigurationSender sends the SetFlowLogConfiguration request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) SetFlowLogConfigurationSender(req *http.Request) (future WatchersSetFlowLogConfigurationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// SetFlowLogConfigurationResponder handles the response to the SetFlowLogConfiguration request. The method always -// closes the http.Response Body. -func (client WatchersClient) SetFlowLogConfigurationResponder(resp *http.Response) (result FlowLogInformation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates a network watcher tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters supplied to update network watcher tags. -func (client WatchersClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject) (result Watcher, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client WatchersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client WatchersClient) UpdateTagsResponder(resp *http.Response) (result Watcher, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// VerifyIPFlow verify IP flow from the specified VM to a location given the currently configured NSG rules. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the IP flow to be verified. -func (client WatchersClient) VerifyIPFlow(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters) (result WatchersVerifyIPFlowFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.VerifyIPFlow") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.LocalPort", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.RemotePort", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.LocalIPAddress", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.RemoteIPAddress", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "VerifyIPFlow", err.Error()) - } - - req, err := client.VerifyIPFlowPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", nil, "Failure preparing request") - return - } - - result, err = client.VerifyIPFlowSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", result.Response(), "Failure sending request") - return - } - - return -} - -// VerifyIPFlowPreparer prepares the VerifyIPFlow request. -func (client WatchersClient) VerifyIPFlowPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/ipFlowVerify", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// VerifyIPFlowSender sends the VerifyIPFlow request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) VerifyIPFlowSender(req *http.Request) (future WatchersVerifyIPFlowFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// VerifyIPFlowResponder handles the response to the VerifyIPFlow request. The method always -// closes the http.Response Body. -func (client WatchersClient) VerifyIPFlowResponder(resp *http.Response) (result VerificationIPFlowResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go deleted file mode 100644 index c4aee486f..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go +++ /dev/null @@ -1,7 +0,0 @@ -package version - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -// Number contains the semantic version of this SDK. -const Number = "v65.0.0" diff --git a/vendor/github.com/Azure/go-autorest/.gitignore b/vendor/github.com/Azure/go-autorest/.gitignore deleted file mode 100644 index 3350aaf70..000000000 --- a/vendor/github.com/Azure/go-autorest/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# The standard Go .gitignore file follows. (Sourced from: github.com/github/gitignore/master/Go.gitignore) -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -.DS_Store -.idea/ -.vscode/ - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -# go-autorest specific -vendor/ -autorest/azure/example/example diff --git a/vendor/github.com/Azure/go-autorest/CHANGELOG.md b/vendor/github.com/Azure/go-autorest/CHANGELOG.md deleted file mode 100644 index d1f596bfc..000000000 --- a/vendor/github.com/Azure/go-autorest/CHANGELOG.md +++ /dev/null @@ -1,1004 +0,0 @@ -# CHANGELOG - -## v14.2.0 - -- Added package comment to make `github.com/Azure/go-autorest` importable. - -## v14.1.1 - -### Bug Fixes - -- Change `x-ms-authorization-auxiliary` header value separator to comma. - -## v14.1.0 - -### New Features - -- Added `azure.SetEnvironment()` that will update the global environments map with the specified values. - -## v14.0.1 - -### Bug Fixes - -- Fix race condition when refreshing token. -- Fixed some tests to work with Go 1.14. - -## v14.0.0 - -## Breaking Changes - -- By default, the `DoRetryForStatusCodes` functions will no longer infinitely retry a request when the response returns an HTTP status code of 429 (StatusTooManyRequests). To opt in to the old behavior set `autorest.Count429AsRetry` to `false`. - -## New Features - -- Variable `autorest.Max429Delay` can be used to control the maximum delay between retries when a 429 is received with no `Retry-After` header. The default is zero which means there is no cap. - -## v13.4.0 - -## New Features - -- Added field `SendDecorators` to the `Client` type. This can be used to specify a custom chain of SendDecorators per client. -- Added method `Client.Send()` which includes logic for selecting the preferred chain of SendDecorators. - -## v13.3.3 - -### Bug Fixes - -- Fixed connection leak when retrying requests. -- Enabled exponential back-off with a 2-minute cap when retrying on 429. -- Fixed some cases where errors were inadvertently dropped. - -## v13.3.2 - -### Bug Fixes - -- Updated `autorest.AsStringSlice()` to convert slice elements to their string representation. - -## v13.3.1 - -- Updated external dependencies. - -### Bug Fixes - -## v13.3.0 - -### New Features - -- Added support for shared key and shared access signature token authorization. - - `autorest.NewSharedKeyAuthorizer()` and dependent types. - - `autorest.NewSASTokenAuthorizer()` and dependent types. -- Added `ServicePrincipalToken.SetCustomRefresh()` so a custom refresh function can be invoked when a token has expired. - -### Bug Fixes - -- Fixed `cli.AccessTokensPath()` to respect `AZURE_CONFIG_DIR` when set. -- Support parsing error messages in XML responses. - -## v13.2.0 - -### New Features - -- Added the following functions to replace their versions that don't take a context. - - `adal.InitiateDeviceAuthWithContext()` - - `adal.CheckForUserCompletionWithContext()` - - `adal.WaitForUserCompletionWithContext()` - -## v13.1.0 - -### New Features - -- Added support for MSI authentication on Azure App Service and Azure Functions. - -## v13.0.2 - -### Bug Fixes - -- Always retry a request even if the sender returns a non-nil error. - -## v13.0.1 - -## Bug Fixes - -- Fixed `autorest.WithQueryParameters()` so that it properly encodes multi-value query parameters. - -## v13.0.0 - -## Breaking Changes - -The `tracing` package has been rewritten to provide a common interface for consumers to wire in the tracing package of their choice. -What this means is that by default no tracing provider will be compiled into your program and setting the `AZURE_SDK_TRACING_ENABLED` -environment variable will have no effect. To enable this previous behavior you must now add the following import to your source file. -```go - import _ "github.com/Azure/go-autorest/tracing/opencensus" -``` -The APIs required by autorest-generated code have remained but some APIs have been removed and new ones added. -The following APIs and variables have been removed (the majority of them were moved to the `opencensus` package). -- tracing.Transport -- tracing.Enable() -- tracing.EnableWithAIForwarding() -- tracing.Disable() - -The following APIs and types have been added -- tracing.Tracer -- tracing.Register() - -To hook up a tracer simply call `tracing.Register()` passing in a type that satisfies the `tracing.Tracer` interface. - -## v12.4.3 - -### Bug Fixes - -- `autorest.MultiTenantServicePrincipalTokenAuthorizer` will now properly add its auxiliary bearer tokens. - -## v12.4.2 - -### Bug Fixes - -- Improvements to the fixes made in v12.4.1. - - Remove `override` stanza from Gopkg.toml and `replace` directive from go.mod as they don't apply when being consumed as a dependency. - - Switched to latest version of `ocagent` that still depends on protobuf v1.2. - - Add indirect dependencies to the `required` clause with matching `constraint` stanzas so that `dep` dependencies match go.sum. - -## v12.4.1 - -### Bug Fixes - -- Updated OpenCensus and OCAgent versions to versions that don't depend on v1.3+ of protobuf as it was breaking kubernetes. -- Pinned opencensus-proto to a version that's compatible with our versions of OpenCensus and OCAgent. - -## v12.4.0 - -### New Features - -- Added `autorest.WithPrepareDecorators` and `autorest.GetPrepareDecorators` for adding and retrieving a custom chain of PrepareDecorators to the provided context. - -## v12.3.0 - -### New Features - -- Support for multi-tenant via x-ms-authorization-auxiliary header has been added for client credentials with - secret scenario; this basically bundles multiple OAuthConfig and ServicePrincipalToken types into corresponding - MultiTenant* types along with a new authorizer that adds the primary and auxiliary token headers to the reqest. - The authenticaion helpers have been updated to support this scenario; if environment var AZURE_AUXILIARY_TENANT_IDS - is set with a semicolon delimited list of tenants the multi-tenant codepath will kick in to create the appropriate authorizer. - See `adal.NewMultiTenantOAuthConfig`, `adal.NewMultiTenantServicePrincipalToken` and `autorest.NewMultiTenantServicePrincipalTokenAuthorizer` - along with their supporting types and methods. -- Added `autorest.WithSendDecorators` and `autorest.GetSendDecorators` for adding and retrieving a custom chain of SendDecorators to the provided context. -- Added `autorest.DoRetryForStatusCodesWithCap` and `autorest.DelayForBackoffWithCap` to enforce an upper bound on the duration between retries. - -## v12.2.0 - -### New Features - -- Added `autorest.WithXML`, `autorest.AsMerge`, `autorest.WithBytes` preparer decorators. -- Added `autorest.ByUnmarshallingBytes` response decorator. -- Added `Response.IsHTTPStatus` and `Response.HasHTTPStatus` helper methods for inspecting HTTP status code in `autorest.Response` types. - -### Bug Fixes - -- `autorest.DelayWithRetryAfter` now supports HTTP-Dates in the `Retry-After` header and is not limited to just 429 status codes. - -## v12.1.0 - -### New Features - -- Added `to.ByteSlicePtr()`. -- Added blob/queue storage resource ID to `azure.ResourceIdentifier`. - -## v12.0.0 - -### Breaking Changes - -In preparation for modules the following deprecated content has been removed. - - - async.NewFuture() - - async.Future.Done() - - async.Future.WaitForCompletion() - - async.DoPollForAsynchronous() - - The `utils` package - - validation.NewErrorWithValidationError() - - The `version` package - -## v11.9.0 - -### New Features - -- Add `ResourceIdentifiers` field to `azure.Environment` containing resource IDs for public and sovereign clouds. - -## v11.8.0 - -### New Features - -- Added `autorest.NewClientWithOptions()` to support endpoints that require free renegotiation. - -## v11.7.1 - -### Bug Fixes - -- Fix missing support for http(s) proxy when using the default sender. - -## v11.7.0 - -### New Features - -- Added methods to obtain a ServicePrincipalToken on the various credential configuration types in the `auth` package. - -## v11.6.1 - -### Bug Fixes - -- Fix ACR DNS endpoint for government clouds. -- Add Cosmos DB DNS endpoints. -- Update dependencies to resolve build breaks in OpenCensus. - -## v11.6.0 - -### New Features - -- Added type `autorest.BasicAuthorizer` to support Basic authentication. - -## v11.5.2 - -### Bug Fixes - -- Fixed `GetTokenFromCLI` did not work with zsh. - -## v11.5.1 - -### Bug Fixes - -- In `Client.sender()` set the minimum TLS version on HTTP clients to 1.2. - -## v11.5.0 - -### New Features - -- The `auth` package has been refactored so that the environment and file settings are now available. -- The methods used in `auth.NewAuthorizerFromEnvironment()` are now exported so that custom authorization chains can be created. -- Added support for certificate authorization for file-based config. - -## v11.4.0 - -### New Features - -- Added `adal.AddToUserAgent()` so callers can append custom data to the user-agent header used for ADAL requests. -- Exported `adal.UserAgent()` for parity with `autorest.Client`. - -## v11.3.2 - -### Bug Fixes - -- In `Future.WaitForCompletionRef()` if the provided context has a deadline don't add the default deadline. - -## v11.3.1 - -### Bug Fixes - -- For an LRO PUT operation the final GET URL was incorrectly set to the Location polling header in some cases. - -## v11.3.0 - -### New Features - -- Added method `ServicePrincipalToken()` to `DeviceFlowConfig` type. - -## v11.2.8 - -### Bug Fixes - -- Deprecate content in the `version` package. The functionality has been superseded by content in the `autorest` package. - -## v11.2.7 - -### Bug Fixes - -- Fix environment variable name for enabling tracing from `AZURE_SDK_TRACING_ENABELD` to `AZURE_SDK_TRACING_ENABLED`. - Note that for backward compatibility reasons, both will work until the next major version release of the package. - -## v11.2.6 - -### Bug Fixes - -- If zero bytes are read from a polling response body don't attempt to unmarshal them. - -## v11.2.5 - -### Bug Fixes - -- Removed race condition in `autorest.DoRetryForStatusCodes`. - -## v11.2.4 - -### Bug Fixes - -- Function `cli.ProfilePath` now respects environment `AZURE_CONFIG_DIR` if available. - -## v11.2.1 - -NOTE: Versions of Go prior to 1.10 have been removed from CI as they no -longer work with golint. - -### Bug Fixes - -- Method `MSIConfig.Authorizer` now supports user-assigned identities. -- The adal package now reports its own user-agent string. - -## v11.2.0 - -### New Features - -- Added `tracing` package that enables instrumentation of HTTP and API calls. - Setting the env variable `AZURE_SDK_TRACING_ENABLED` or calling `tracing.Enable` - will start instrumenting the code for metrics and traces. - Additionally, setting the env variable `OCAGENT_TRACE_EXPORTER_ENDPOINT` or - calling `tracing.EnableWithAIForwarding` will start the instrumentation and connect to an - App Insights Local Forwarder that is needs to be running. Note that if the - AI Local Forwarder is not running tracking will still be enabled. - By default, instrumentation is disabled. Once enabled, instrumentation can also - be programatically disabled by calling `Disable`. -- Added `DoneWithContext` call for checking LRO status. `Done` has been deprecated. - -### Bug Fixes - -- Don't use the initial request's context for LRO polling. -- Don't override the `refreshLock` and the `http.Client` when unmarshalling `ServicePrincipalToken` if - it is already set. - -## v11.1.1 - -### Bug Fixes - -- When creating a future always include the polling tracker even if there's a failure; this allows the underlying response to be obtained by the caller. - -## v11.1.0 - -### New Features - -- Added `auth.NewAuthorizerFromCLI` to create an authorizer configured from the Azure 2.0 CLI. -- Added `adal.NewOAuthConfigWithAPIVersion` to create an OAuthConfig with the specified API version. - -## v11.0.1 - -### New Features - -- Added `x5c` header to client assertion for certificate Issuer+Subject Name authentication. - -## v11.0.0 - -### Breaking Changes - -- To handle differences between ADFS and AAD the following fields have had their types changed from `string` to `json.Number` - - ExpiresIn - - ExpiresOn - - NotBefore - -### New Features - -- Added `auth.NewAuthorizerFromFileWithResource` to create an authorizer from the config file with the specified resource. -- Setting a client's `PollingDuration` to zero will use the provided context to control a LRO's polling duration. - -## v10.15.5 - -### Bug Fixes - -- In `DoRetryForStatusCodes`, if a request's context is cancelled return the last response. - -## v10.15.4 - -### Bug Fixes - -- If a polling operation returns a failure status code return the associated error. - -## v10.15.3 - -### Bug Fixes - -- Initialize the polling URL and method for an LRO tracker on each iteration, favoring the Azure-AsyncOperation header. - -## v10.15.2 - -### Bug Fixes - -- Use fmt.Fprint when printing request/response so that any escape sequences aren't treated as format specifiers. - -## v10.15.1 - -### Bug Fixes - -- If an LRO API returns a `Failed` provisioning state in the initial response return an error at that point so the caller doesn't have to poll. -- For failed LROs without an OData v4 error include the response body in the error's `AdditionalInfo` field to aid in diagnosing the failure. - -## v10.15.0 - -### New Features - -- Add initial support for request/response logging via setting environment variables. - Setting `AZURE_GO_SDK_LOG_LEVEL` to `LogInfo` will log request/response - without their bodies. To include the bodies set the log level to `LogDebug`. - By default the logger writes to strerr, however it can also write to stdout or a file - if specified in `AZURE_GO_SDK_LOG_FILE`. Note that if the specified file - already exists it will be truncated. - IMPORTANT: by default the logger will redact the Authorization and Ocp-Apim-Subscription-Key - headers. Any other secrets will _not_ be redacted. - -## v10.14.0 - -### New Features - -- Added package version that contains version constants and user-agent data. - -### Bug Fixes - -- Add the user-agent to token requests. - -## v10.13.0 - -- Added support for additionalInfo in ServiceError type. - -## v10.12.0 - -### New Features - -- Added field ServicePrincipalToken.MaxMSIRefreshAttempts to configure the maximun number of attempts to refresh an MSI token. - -## v10.11.4 - -### Bug Fixes - -- If an LRO returns http.StatusOK on the initial response with no async headers return the response body from Future.GetResult(). -- If there is no "final GET URL" return an error from Future.GetResult(). - -## v10.11.3 - -### Bug Fixes - -- In IMDS retry logic, if we don't receive a response don't retry. - - Renamed the retry function so it's clear it's meant for IMDS only. -- For error response bodies that aren't OData-v4 compliant stick the raw JSON in the ServiceError.Details field so the information isn't lost. - - Also add the raw HTTP response to the DetailedResponse. -- Removed superfluous wrapping of response error in azure.DoRetryWithRegistration(). - -## v10.11.2 - -### Bug Fixes - -- Validation for integers handles int and int64 types. - -## v10.11.1 - -### Bug Fixes - -- Adding User information to authorization config as parsed from CLI cache. - -## v10.11.0 - -### New Features - -- Added NewServicePrincipalTokenFromManualTokenSecret for creating a new SPT using a manual token and secret -- Added method ServicePrincipalToken.MarshalTokenJSON() to marshall the inner Token - -## v10.10.0 - -### New Features - -- Most ServicePrincipalTokens can now be marshalled/unmarshall to/from JSON (ServicePrincipalCertificateSecret and ServicePrincipalMSISecret are not supported). -- Added method ServicePrincipalToken.SetRefreshCallbacks(). - -## v10.9.2 - -### Bug Fixes - -- Refreshing a refresh token obtained from a web app authorization code now works. - -## v10.9.1 - -### Bug Fixes - -- The retry logic for MSI token requests now uses exponential backoff per the guidelines. -- IsTemporaryNetworkError() will return true for errors that don't implement the net.Error interface. - -## v10.9.0 - -### Deprecated Methods - -| Old Method | New Method | -| -------------------------: | :---------------------------: | -| azure.NewFuture() | azure.NewFutureFromResponse() | -| Future.WaitForCompletion() | Future.WaitForCompletionRef() | - -### New Features - -- Added azure.NewFutureFromResponse() for creating a Future from the initial response from an async operation. -- Added Future.GetResult() for making the final GET call to retrieve the result from an async operation. - -### Bug Fixes - -- Some futures failed to return their results, this should now be fixed. - -## v10.8.2 - -### Bug Fixes - -- Add nil-gaurd to token retry logic. - -## v10.8.1 - -### Bug Fixes - -- Return a TokenRefreshError if the sender fails on the initial request. -- Don't retry on non-temporary network errors. - -## v10.8.0 - -- Added NewAuthorizerFromEnvironmentWithResource() helper function. - -## v10.7.0 - -### New Features - -- Added \*WithContext() methods to ADAL token refresh operations. - -## v10.6.2 - -- Fixed a bug on device authentication. - -## v10.6.1 - -- Added retries to MSI token get request. - -## v10.6.0 - -- Changed MSI token implementation. Now, the token endpoint is the IMDS endpoint. - -## v10.5.1 - -### Bug Fixes - -- `DeviceFlowConfig.Authorizer()` now prints the device code message when running `go test`. `-v` flag is required. - -## v10.5.0 - -### New Features - -- Added NewPollingRequestWithContext() for use with polling asynchronous operations. - -### Bug Fixes - -- Make retry logic use the request's context instead of the deprecated Cancel object. - -## v10.4.0 - -### New Features - -- Added helper for parsing Azure Resource ID's. -- Added deprecation message to utils.GetEnvVarOrExit() - -## v10.3.0 - -### New Features - -- Added EnvironmentFromURL method to load an Environment from a given URL. This function is particularly useful in the private and hybrid Cloud model, where one may define their own endpoints -- Added TokenAudience endpoint to Environment structure. This is useful in private and hybrid cloud models where TokenAudience endpoint can be different from ResourceManagerEndpoint - -## v10.2.0 - -### New Features - -- Added endpoints for batch management. - -## v10.1.3 - -### Bug Fixes - -- In Client.Do() invoke WithInspection() last so that it will inspect WithAuthorization(). -- Fixed authorization methods to invoke p.Prepare() first, aligning them with the other preparers. - -## v10.1.2 - -- Corrected comment for auth.NewAuthorizerFromFile() function. - -## v10.1.1 - -- Updated version number to match current release. - -## v10.1.0 - -### New Features - -- Expose the polling URL for futures. - -### Bug Fixes - -- Add validation.NewErrorWithValidationError back to prevent breaking changes (it is deprecated). - -## v10.0.0 - -### New Features - -- Added target and innererror fields to ServiceError to comply with OData v4 spec. -- The Done() method on futures will now return a ServiceError object when available (it used to return a partial value of such errors). -- Added helper methods for obtaining authorizers. -- Expose the polling URL for futures. - -### Bug Fixes - -- Switched from glide to dep for dependency management. -- Fixed unmarshaling of ServiceError for JSON bodies that don't conform to the OData spec. -- Fixed a race condition in token refresh. - -### Breaking Changes - -- The ServiceError.Details field type has been changed to match the OData v4 spec. -- Go v1.7 has been dropped from CI. -- API parameter validation failures will now return a unique error type validation.Error. -- The adal.Token type has been decomposed from adal.ServicePrincipalToken (this was necessary in order to fix the token refresh race). - -## v9.10.0 - -- Fix the Service Bus suffix in Azure public env -- Add Service Bus Endpoint (AAD ResourceURI) for use in [Azure Service Bus RBAC Preview](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-role-based-access-control) - -## v9.9.0 - -### New Features - -- Added EventGridKeyAuthorizer for key authorization with event grid topics. - -### Bug Fixes - -- Fixed race condition when auto-refreshing service principal tokens. - -## v9.8.1 - -### Bug Fixes - -- Added http.StatusNoContent (204) to the list of expected status codes for long-running operations. -- Updated runtime version info so it's current. - -## v9.8.0 - -### New Features - -- Added type azure.AsyncOpIncompleteError to be returned from a future's Result() method when the operation has not completed. - -## v9.7.1 - -### Bug Fixes - -- Use correct AAD and Graph endpoints for US Gov environment. - -## v9.7.0 - -### New Features - -- Added support for application/octet-stream MIME types. - -## v9.6.1 - -### Bug Fixes - -- Ensure Authorization header is added to request when polling for registration status. - -## v9.6.0 - -### New Features - -- Added support for acquiring tokens via MSI with a user assigned identity. - -## v9.5.3 - -### Bug Fixes - -- Don't remove encoding of existing URL Query parameters when calling autorest.WithQueryParameters. -- Set correct Content Type when using autorest.WithFormData. - -## v9.5.2 - -### Bug Fixes - -- Check for nil \*http.Response before dereferencing it. - -## v9.5.1 - -### Bug Fixes - -- Don't count http.StatusTooManyRequests (429) against the retry cap. -- Use retry logic when SkipResourceProviderRegistration is set to true. - -## v9.5.0 - -### New Features - -- Added support for username + password, API key, authoriazation code and cognitive services authentication. -- Added field SkipResourceProviderRegistration to clients to provide a way to skip auto-registration of RPs. -- Added utility function AsStringSlice() to convert its parameters to a string slice. - -### Bug Fixes - -- When checking for authentication failures look at the error type not the status code as it could vary. - -## v9.4.2 - -### Bug Fixes - -- Validate parameters when creating credentials. -- Don't retry requests if the returned status is a 401 (http.StatusUnauthorized) as it will never succeed. - -## v9.4.1 - -### Bug Fixes - -- Update the AccessTokensPath() to read access tokens path through AZURE_ACCESS_TOKEN_FILE. If this - environment variable is not set, it will fall back to use default path set by Azure CLI. -- Use case-insensitive string comparison for polling states. - -## v9.4.0 - -### New Features - -- Added WaitForCompletion() to Future as a default polling implementation. - -### Bug Fixes - -- Method Future.Done() shouldn't update polling status for unexpected HTTP status codes. - -## v9.3.1 - -### Bug Fixes - -- DoRetryForStatusCodes will retry if sender.Do returns a non-nil error. - -## v9.3.0 - -### New Features - -- Added PollingMethod() to Future so callers know what kind of polling mechanism is used. -- Added azure.ChangeToGet() which transforms an http.Request into a GET (to be used with LROs). - -## v9.2.0 - -### New Features - -- Added support for custom Azure Stack endpoints. -- Added type azure.Future used to track the status of long-running operations. - -### Bug Fixes - -- Preserve the original error in DoRetryWithRegistration when registration fails. - -## v9.1.1 - -- Fixes a bug regarding the cookie jar on `autorest.Client.Sender`. - -## v9.1.0 - -### New Features - -- In cases where there is a non-empty error from the service, attempt to unmarshal it instead of uniformly calling it an "Unknown" error. -- Support for loading Azure CLI Authentication files. -- Automatically register your subscription with the Azure Resource Provider if it hadn't been previously. - -### Bug Fixes - -- RetriableRequest can now tolerate a ReadSeekable body being read but not reset. -- Adding missing Apache Headers - -## v9.0.0 - -> **IMPORTANT:** This release was intially labeled incorrectly as `v8.4.0`. From the time it was released, it should have been marked `v9.0.0` because it contains breaking changes to the MSI packages. We appologize for any inconvenience this causes. - -Adding MSI Endpoint Support and CLI token rehydration. - -## v8.3.1 - -Pick up bug fix in adal for MSI support. - -## v8.3.0 - -Updates to Error string formats for clarity. Also, adding a copy of the http.Response to errors for an improved debugging experience. - -## v8.2.0 - -### New Features - -- Add support for bearer authentication callbacks -- Support 429 response codes that include "Retry-After" header -- Support validation constraint "Pattern" for map keys - -### Bug Fixes - -- Make RetriableRequest work with multiple versions of Go - -## v8.1.1 - -Updates the RetriableRequest to take advantage of GetBody() added in Go 1.8. - -## v8.1.0 - -Adds RetriableRequest type for more efficient handling of retrying HTTP requests. - -## v8.0.0 - -ADAL refactored into its own package. -Support for UNIX time. - -## v7.3.1 - -- Version Testing now removed from production bits that are shipped with the library. - -## v7.3.0 - -- Exposing new `RespondDecorator`, `ByDiscardingBody`. This allows operations - to acknowledge that they do not need either the entire or a trailing portion - of accepts response body. In doing so, Go's http library can reuse HTTP - connections more readily. -- Adding `PrepareDecorator` to target custom BaseURLs. -- Adding ACR suffix to public cloud environment. -- Updating Glide dependencies. - -## v7.2.5 - -- Fixed the Active Directory endpoint for the China cloud. -- Removes UTF-8 BOM if present in response payload. -- Added telemetry. - -## v7.2.3 - -- Fixing bug in calls to `DelayForBackoff` that caused doubling of delay - duration. - -## v7.2.2 - -- autorest/azure: added ASM and ARM VM DNS suffixes. - -## v7.2.1 - -- fixed parsing of UTC times that are not RFC3339 conformant. - -## v7.2.0 - -- autorest/validation: Reformat validation error for better error message. - -## v7.1.0 - -- preparer: Added support for multipart formdata - WithMultiPartFormdata() -- preparer: Added support for sending file in request body - WithFile -- client: Added RetryDuration parameter. -- autorest/validation: new package for validation code for Azure Go SDK. - -## v7.0.7 - -- Add trailing / to endpoint -- azure: add EnvironmentFromName - -## v7.0.6 - -- Add retry logic for 408, 500, 502, 503 and 504 status codes. -- Change url path and query encoding logic. -- Fix DelayForBackoff for proper exponential delay. -- Add CookieJar in Client. - -## v7.0.5 - -- Add check to start polling only when status is in [200,201,202]. -- Refactoring for unchecked errors. -- azure/persist changes. -- Fix 'file in use' issue in renewing token in deviceflow. -- Store header RetryAfter for subsequent requests in polling. -- Add attribute details in service error. - -## v7.0.4 - -- Better error messages for long running operation failures - -## v7.0.3 - -- Corrected DoPollForAsynchronous to properly handle the initial response - -## v7.0.2 - -- Corrected DoPollForAsynchronous to continue using the polling method first discovered - -## v7.0.1 - -- Fixed empty JSON input error in ByUnmarshallingJSON -- Fixed polling support for GET calls -- Changed format name from TimeRfc1123 to TimeRFC1123 - -## v7.0.0 - -- Added ByCopying responder with supporting TeeReadCloser -- Rewrote Azure asynchronous handling -- Reverted to only unmarshalling JSON -- Corrected handling of RFC3339 time strings and added support for Rfc1123 time format - -The `json.Decoder` does not catch bad data as thoroughly as `json.Unmarshal`. Since -`encoding/json` successfully deserializes all core types, and extended types normally provide -their custom JSON serialization handlers, the code has been reverted back to using -`json.Unmarshal`. The original change to use `json.Decode` was made to reduce duplicate -code; there is no loss of function, and there is a gain in accuracy, by reverting. - -Additionally, Azure services indicate requests to be polled by multiple means. The existing code -only checked for one of those (that is, the presence of the `Azure-AsyncOperation` header). -The new code correctly covers all cases and aligns with the other Azure SDKs. - -## v6.1.0 - -- Introduced `date.ByUnmarshallingJSONDate` and `date.ByUnmarshallingJSONTime` to enable JSON encoded values. - -## v6.0.0 - -- Completely reworked the handling of polled and asynchronous requests -- Removed unnecessary routines -- Reworked `mocks.Sender` to replay a series of `http.Response` objects -- Added `PrepareDecorators` for primitive types (e.g., bool, int32) - -Handling polled and asynchronous requests is no longer part of `Client#Send`. Instead new -`SendDecorators` implement different styles of polled behavior. See`autorest.DoPollForStatusCodes` -and `azure.DoPollForAsynchronous` for examples. - -## v5.0.0 - -- Added new RespondDecorators unmarshalling primitive types -- Corrected application of inspection and authorization PrependDecorators - -## v4.0.0 - -- Added support for Azure long-running operations. -- Added cancelation support to all decorators and functions that may delay. -- Breaking: `DelayForBackoff` now accepts a channel, which may be nil. - -## v3.1.0 - -- Add support for OAuth Device Flow authorization. -- Add support for ServicePrincipalTokens that are backed by an existing token, rather than other secret material. -- Add helpers for persisting and restoring Tokens. -- Increased code coverage in the github.com/Azure/autorest/azure package - -## v3.0.0 - -- Breaking: `NewErrorWithError` no longer takes `statusCode int`. -- Breaking: `NewErrorWithStatusCode` is replaced with `NewErrorWithResponse`. -- Breaking: `Client#Send()` no longer takes `codes ...int` argument. -- Add: XML unmarshaling support with `ByUnmarshallingXML()` -- Stopped vending dependencies locally and switched to [Glide](https://github.com/Masterminds/glide). - Applications using this library should either use Glide or vendor dependencies locally some other way. -- Add: `azure.WithErrorUnlessStatusCode()` decorator to handle Azure errors. -- Fix: use `net/http.DefaultClient` as base client. -- Fix: Missing inspection for polling responses added. -- Add: CopyAndDecode helpers. -- Improved `./autorest/to` with `[]string` helpers. -- Removed golint suppressions in .travis.yml. - -## v2.1.0 - -- Added `StatusCode` to `Error` for more easily obtaining the HTTP Reponse StatusCode (if any) - -## v2.0.0 - -- Changed `to.StringMapPtr` method signature to return a pointer -- Changed `ServicePrincipalCertificateSecret` and `NewServicePrincipalTokenFromCertificate` to support generic certificate and private keys - -## v1.0.0 - -- Added Logging inspectors to trace http.Request / Response -- Added support for User-Agent header -- Changed WithHeader PrepareDecorator to use set vs. add -- Added JSON to error when unmarshalling fails -- Added Client#Send method -- Corrected case of "Azure" in package paths -- Added "to" helpers, Azure helpers, and improved ease-of-use -- Corrected golint issues - -## v1.0.1 - -- Added CHANGELOG.md - -## v1.1.0 - -- Added mechanism to retrieve a ServicePrincipalToken using a certificate-signed JWT -- Added an example of creating a certificate-based ServicePrincipal and retrieving an OAuth token using the certificate - -## v1.1.1 - -- Introduce godeps and vendor dependencies introduced in v1.1.1 diff --git a/vendor/github.com/Azure/go-autorest/GNUmakefile b/vendor/github.com/Azure/go-autorest/GNUmakefile deleted file mode 100644 index a434e73ac..000000000 --- a/vendor/github.com/Azure/go-autorest/GNUmakefile +++ /dev/null @@ -1,23 +0,0 @@ -DIR?=./autorest/ - -default: build - -build: fmt - go install $(DIR) - -test: - go test $(DIR) || exit 1 - -vet: - @echo "go vet ." - @go vet $(DIR)... ; if [ $$? -eq 1 ]; then \ - echo ""; \ - echo "Vet found suspicious constructs. Please check the reported constructs"; \ - echo "and fix them if necessary before submitting the code for review."; \ - exit 1; \ - fi - -fmt: - gofmt -w $(DIR) - -.PHONY: build test vet fmt diff --git a/vendor/github.com/Azure/go-autorest/Gopkg.lock b/vendor/github.com/Azure/go-autorest/Gopkg.lock deleted file mode 100644 index dc6e3e633..000000000 --- a/vendor/github.com/Azure/go-autorest/Gopkg.lock +++ /dev/null @@ -1,324 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:892e39e5c083d0943f1e80ab8351690f183c6a5ab24e1d280adcad424c26255e" - name = "contrib.go.opencensus.io/exporter/ocagent" - packages = ["."] - pruneopts = "UT" - revision = "a8a6f458bbc1d5042322ad1f9b65eeb0b69be9ea" - version = "v0.6.0" - -[[projects]] - digest = "1:8f5acd4d4462b5136af644d25101f0968a7a94ee90fcb2059cec5b7cc42e0b20" - name = "github.com/census-instrumentation/opencensus-proto" - packages = [ - "gen-go/agent/common/v1", - "gen-go/agent/metrics/v1", - "gen-go/agent/trace/v1", - "gen-go/metrics/v1", - "gen-go/resource/v1", - "gen-go/trace/v1", - ] - pruneopts = "UT" - revision = "d89fa54de508111353cb0b06403c00569be780d8" - version = "v0.2.1" - -[[projects]] - digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" - name = "github.com/davecgh/go-spew" - packages = ["spew"] - pruneopts = "UT" - revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" - version = "v1.1.1" - -[[projects]] - digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55" - name = "github.com/dgrijalva/jwt-go" - packages = ["."] - pruneopts = "UT" - revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" - version = "v3.2.0" - -[[projects]] - digest = "1:cf0d2e435fd4ce45b789e93ef24b5f08e86be0e9807a16beb3694e2d8c9af965" - name = "github.com/dimchansky/utfbom" - packages = ["."] - pruneopts = "UT" - revision = "d2133a1ce379ef6fa992b0514a77146c60db9d1c" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:b7cb6054d3dff43b38ad2e92492f220f57ae6087ee797dca298139776749ace8" - name = "github.com/golang/groupcache" - packages = ["lru"] - pruneopts = "UT" - revision = "611e8accdfc92c4187d399e95ce826046d4c8d73" - -[[projects]] - digest = "1:e3839df32927e8d3403cd5aa7253d966e8ff80fc8f10e2e35d146461cd83fcfa" - name = "github.com/golang/protobuf" - packages = [ - "descriptor", - "jsonpb", - "proto", - "protoc-gen-go/descriptor", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/struct", - "ptypes/timestamp", - "ptypes/wrappers", - ] - pruneopts = "UT" - revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7" - version = "v1.3.2" - -[[projects]] - digest = "1:c560cd79300fac84f124b96225181a637a70b60155919a3c36db50b7cca6b806" - name = "github.com/grpc-ecosystem/grpc-gateway" - packages = [ - "internal", - "runtime", - "utilities", - ] - pruneopts = "UT" - revision = "f7120437bb4f6c71f7f5076ad65a45310de2c009" - version = "v1.12.1" - -[[projects]] - digest = "1:5d231480e1c64a726869bc4142d270184c419749d34f167646baa21008eb0a79" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "af06845cf3004701891bf4fdb884bfe4920b3727" - version = "v1.1.0" - -[[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - pruneopts = "UT" - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - digest = "1:99d32780e5238c2621fff621123997c3e3cca96db8be13179013aea77dfab551" - name = "github.com/stretchr/testify" - packages = [ - "assert", - "require", - ] - pruneopts = "UT" - revision = "221dbe5ed46703ee255b1da0dec05086f5035f62" - version = "v1.4.0" - -[[projects]] - digest = "1:7c5e00383399fe13de0b4b65c9fdde16275407ce8ac02d867eafeaa916edcc71" - name = "go.opencensus.io" - packages = [ - ".", - "internal", - "internal/tagencoding", - "metric/metricdata", - "metric/metricproducer", - "plugin/ocgrpc", - "plugin/ochttp", - "plugin/ochttp/propagation/b3", - "plugin/ochttp/propagation/tracecontext", - "resource", - "stats", - "stats/internal", - "stats/view", - "tag", - "trace", - "trace/internal", - "trace/propagation", - "trace/tracestate", - ] - pruneopts = "UT" - revision = "aad2c527c5defcf89b5afab7f37274304195a6b2" - version = "v0.22.2" - -[[projects]] - branch = "master" - digest = "1:f604f5e2ee721b6757d962dfe7bab4f28aae50c456e39cfb2f3819762a44a6ae" - name = "golang.org/x/crypto" - packages = [ - "pkcs12", - "pkcs12/internal/rc2", - ] - pruneopts = "UT" - revision = "e9b2fee46413994441b28dfca259d911d963dfed" - -[[projects]] - branch = "master" - digest = "1:334b27eac455cb6567ea28cd424230b07b1a64334a2f861a8075ac26ce10af43" - name = "golang.org/x/lint" - packages = [ - ".", - "golint", - ] - pruneopts = "UT" - revision = "fdd1cda4f05fd1fd86124f0ef9ce31a0b72c8448" - -[[projects]] - branch = "master" - digest = "1:257a75d024975428ab9192bfc334c3490882f8cb21322ea5784ca8eca000a910" - name = "golang.org/x/net" - packages = [ - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "1ddd1de85cb0337b623b740a609d35817d516a8d" - -[[projects]] - branch = "master" - digest = "1:382bb5a7fb4034db3b6a2d19e5a4a6bcf52f4750530603c01ca18a172fa3089b" - name = "golang.org/x/sync" - packages = ["semaphore"] - pruneopts = "UT" - revision = "cd5d95a43a6e21273425c7ae415d3df9ea832eeb" - -[[projects]] - branch = "master" - digest = "1:4da420ceda5f68e8d748aa2169d0ed44ffadb1bbd6537cf778a49563104189b8" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "ce4227a45e2eb77e5c847278dcc6a626742e2945" - -[[projects]] - digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/language", - "internal/language/compact", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475" - version = "v0.3.2" - -[[projects]] - branch = "master" - digest = "1:4eb5ea8395fb60212dd58b92c9db80bab59d5e99c7435f9a6a0a528c373b60e7" - name = "golang.org/x/tools" - packages = [ - "go/ast/astutil", - "go/gcexportdata", - "go/internal/gcimporter", - "go/types/typeutil", - ] - pruneopts = "UT" - revision = "259af5ff87bdcd4abf2ecda8edc3f13f04f26a42" - -[[projects]] - digest = "1:964bb30febc27fabfbec4759fa530c6ec35e77a7c85fed90b9317ea39a054877" - name = "google.golang.org/api" - packages = ["support/bundler"] - pruneopts = "UT" - revision = "8a410c21381766a810817fd6200fce8838ecb277" - version = "v0.14.0" - -[[projects]] - branch = "master" - digest = "1:a8d5c2c6e746b3485e36908ab2a9e3d77b86b81f8156d88403c7d2b462431dfd" - name = "google.golang.org/genproto" - packages = [ - "googleapis/api/httpbody", - "googleapis/rpc/status", - "protobuf/field_mask", - ] - pruneopts = "UT" - revision = "51378566eb590fa106d1025ea12835a4416dda84" - -[[projects]] - digest = "1:b59ce3ddb11daeeccccc9cb3183b58ebf8e9a779f1c853308cd91612e817a301" - name = "google.golang.org/grpc" - packages = [ - ".", - "backoff", - "balancer", - "balancer/base", - "balancer/roundrobin", - "binarylog/grpc_binarylog_v1", - "codes", - "connectivity", - "credentials", - "credentials/internal", - "encoding", - "encoding/proto", - "grpclog", - "internal", - "internal/backoff", - "internal/balancerload", - "internal/binarylog", - "internal/buffer", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/grpcsync", - "internal/resolver/dns", - "internal/resolver/passthrough", - "internal/syscall", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "serviceconfig", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "1a3960e4bd028ac0cec0a2afd27d7d8e67c11514" - version = "v1.25.1" - -[[projects]] - digest = "1:b75b3deb2bce8bc079e16bb2aecfe01eb80098f5650f9e93e5643ca8b7b73737" - name = "gopkg.in/yaml.v2" - packages = ["."] - pruneopts = "UT" - revision = "1f64d6156d11335c3f22d9330b0ad14fc1e789ce" - version = "v2.2.7" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "contrib.go.opencensus.io/exporter/ocagent", - "github.com/dgrijalva/jwt-go", - "github.com/dimchansky/utfbom", - "github.com/mitchellh/go-homedir", - "github.com/stretchr/testify/require", - "go.opencensus.io/plugin/ochttp", - "go.opencensus.io/plugin/ochttp/propagation/tracecontext", - "go.opencensus.io/stats/view", - "go.opencensus.io/trace", - "golang.org/x/crypto/pkcs12", - "golang.org/x/lint/golint", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/Azure/go-autorest/Gopkg.toml b/vendor/github.com/Azure/go-autorest/Gopkg.toml deleted file mode 100644 index 1fc286596..000000000 --- a/vendor/github.com/Azure/go-autorest/Gopkg.toml +++ /dev/null @@ -1,59 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - -required = ["golang.org/x/lint/golint"] - -[prune] - go-tests = true - unused-packages = true - -[[constraint]] - name = "contrib.go.opencensus.io/exporter/ocagent" - version = "0.6.0" - -[[constraint]] - name = "github.com/dgrijalva/jwt-go" - version = "3.2.0" - -[[constraint]] - name = "github.com/dimchansky/utfbom" - version = "1.1.0" - -[[constraint]] - name = "github.com/mitchellh/go-homedir" - version = "1.1.0" - -[[constraint]] - name = "github.com/stretchr/testify" - version = "1.3.0" - -[[constraint]] - name = "go.opencensus.io" - version = "0.22.0" - -[[constraint]] - branch = "master" - name = "golang.org/x/crypto" diff --git a/vendor/github.com/Azure/go-autorest/LICENSE b/vendor/github.com/Azure/go-autorest/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/README.md b/vendor/github.com/Azure/go-autorest/README.md deleted file mode 100644 index de1e19a44..000000000 --- a/vendor/github.com/Azure/go-autorest/README.md +++ /dev/null @@ -1,165 +0,0 @@ -# go-autorest - -[![GoDoc](https://godoc.org/github.com/Azure/go-autorest/autorest?status.png)](https://godoc.org/github.com/Azure/go-autorest/autorest) -[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/go/Azure.go-autorest?branchName=master)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=625&branchName=master) -[![Go Report Card](https://goreportcard.com/badge/Azure/go-autorest)](https://goreportcard.com/report/Azure/go-autorest) - -Package go-autorest provides an HTTP request client for use with [Autorest](https://github.com/Azure/autorest.go)-generated API client packages. - -An authentication client tested with Azure Active Directory (AAD) is also -provided in this repo in the package -`github.com/Azure/go-autorest/autorest/adal`. Despite its name, this package -is maintained only as part of the Azure Go SDK and is not related to other -"ADAL" libraries in [github.com/AzureAD](https://github.com/AzureAD). - -## Overview - -Package go-autorest implements an HTTP request pipeline suitable for use across -multiple goroutines and provides the shared routines used by packages generated -by [Autorest](https://github.com/Azure/autorest.go). - -The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, -and Responding. A typical pattern is: - -```go - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) - - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) - - err = Respond(resp, - ByDiscardingBody(), - ByClosing()) -``` - -Each phase relies on decorators to modify and / or manage processing. Decorators may first modify -and then pass the data along, pass the data first and then modify the result, or wrap themselves -around passing the data (such as a logger might do). Decorators run in the order provided. For -example, the following: - -```go - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) -``` - -will set the URL to: - -``` - https://microsoft.com/a/b/c -``` - -Preparers and Responders may be shared and re-used (assuming the underlying decorators support -sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders -shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, -all bound together by means of input / output channels. - -Decorators hold their passed state within a closure (such as the path components in the example -above). Be careful to share Preparers and Responders only in a context where such held state -applies. For example, it may not make sense to share a Preparer that applies a query string from a -fixed set of values. Similarly, sharing a Responder that reads the response body into a passed -struct (e.g., `ByUnmarshallingJson`) is likely incorrect. - -Errors raised by autorest objects and methods will conform to the `autorest.Error` interface. - -See the included examples for more detail. For details on the suggested use of this package by -generated clients, see the Client described below. - -## Helpers - -### Handling Swagger Dates - -The Swagger specification (https://swagger.io) that drives AutoRest -(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The -github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure correct -parsing and formatting. - -### Handling Empty Values - -In JSON, missing values have different semantics than empty values. This is especially true for -services using the HTTP PATCH verb. The JSON submitted with a PATCH request generally contains -only those values to modify. Missing values are to be left unchanged. Developers, then, require a -means to both specify an empty value and to leave the value out of the submitted JSON. - -The Go JSON package (`encoding/json`) supports the `omitempty` tag. When specified, it omits -empty values from the rendered JSON. Since Go defines default values for all base types (such as "" -for string and 0 for int) and provides no means to mark a value as actually empty, the JSON package -treats default values as meaning empty, omitting them from the rendered JSON. This means that, using -the Go base types encoded through the default JSON package, it is not possible to create JSON to -clear a value at the server. - -The workaround within the Go community is to use pointers to base types in lieu of base types within -structures that map to JSON. For example, instead of a value of type `string`, the workaround uses -`*string`. While this enables distinguishing empty values from those to be unchanged, creating -pointers to a base type (notably constant, in-line values) requires additional variables. This, for -example, - -```go - s := struct { - S *string - }{ S: &"foo" } -``` -fails, while, this - -```go - v := "foo" - s := struct { - S *string - }{ S: &v } -``` -succeeds. - -To ease using pointers, the subpackage `to` contains helpers that convert to and from pointers for -Go base types which have Swagger analogs. It also provides a helper that converts between -`map[string]string` and `map[string]*string`, enabling the JSON to specify that the value -associated with a key should be cleared. With the helpers, the previous example becomes - -```go - s := struct { - S *string - }{ S: to.StringPtr("foo") } -``` - -## Install - -```bash -go get github.com/Azure/go-autorest/autorest -go get github.com/Azure/go-autorest/autorest/azure -go get github.com/Azure/go-autorest/autorest/date -go get github.com/Azure/go-autorest/autorest/to -``` - -### Using with Go Modules -In [v12.0.1](https://github.com/Azure/go-autorest/pull/386), this repository introduced the following modules. - -- autorest/adal -- autorest/azure/auth -- autorest/azure/cli -- autorest/date -- autorest/mocks -- autorest/to -- autorest/validation -- autorest -- logger -- tracing - -Tagging cumulative SDK releases as a whole (e.g. `v12.3.0`) is still enabled to support consumers of this repo that have not yet migrated to modules. - -## License - -See LICENSE file. - ------ - -This project has adopted the [Microsoft Open Source Code of -Conduct](https://opensource.microsoft.com/codeofconduct/). For more information -see the [Code of Conduct -FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact -[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional -questions or comments. diff --git a/vendor/github.com/Azure/go-autorest/autorest/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md deleted file mode 100644 index b11eb0788..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md +++ /dev/null @@ -1,294 +0,0 @@ -# NOTE: This module will go out of support by March 31, 2023. For authenticating with Azure AD, use module [azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) instead. For help migrating from `adal` to `azidentiy` please consult the [migration guide](https://aka.ms/azsdk/go/identity/migration). General information about the retirement of this and other legacy modules can be found [here](https://azure.microsoft.com/updates/support-for-azure-sdk-libraries-that-do-not-conform-to-our-current-azure-sdk-guidelines-will-be-retired-as-of-31-march-2023/). - -# Azure Active Directory authentication for Go - -This is a standalone package for authenticating with Azure Active -Directory from other Go libraries and applications, in particular the [Azure SDK -for Go](https://github.com/Azure/azure-sdk-for-go). - -Note: Despite the package's name it is not related to other "ADAL" libraries -maintained in the [github.com/AzureAD](https://github.com/AzureAD) org. Issues -should be opened in [this repo's](https://github.com/Azure/go-autorest/issues) -or [the SDK's](https://github.com/Azure/azure-sdk-for-go/issues) issue -trackers. - -## Install - -```bash -go get -u github.com/Azure/go-autorest/autorest/adal -``` - -## Usage - -An Active Directory application is required in order to use this library. An application can be registered in the [Azure Portal](https://portal.azure.com/) by following these [guidelines](https://docs.microsoft.com/azure/active-directory/develop/active-directory-integrating-applications) or using the [Azure CLI](https://github.com/Azure/azure-cli). - -### Register an Azure AD Application with secret - - -1. Register a new application with a `secret` credential - - ``` - az ad app create \ - --display-name example-app \ - --homepage https://example-app/home \ - --identifier-uris https://example-app/app \ - --password secret - ``` - -2. Create a service principal using the `Application ID` from previous step - - ``` - az ad sp create --id "Application ID" - ``` - - * Replace `Application ID` with `appId` from step 1. - -### Register an Azure AD Application with certificate - -1. Create a private key - - ``` - openssl genrsa -out "example-app.key" 2048 - ``` - -2. Create the certificate - - ``` - openssl req -new -key "example-app.key" -subj "/CN=example-app" -out "example-app.csr" - openssl x509 -req -in "example-app.csr" -signkey "example-app.key" -out "example-app.crt" -days 10000 - ``` - -3. Create the PKCS12 version of the certificate containing also the private key - - ``` - openssl pkcs12 -export -out "example-app.pfx" -inkey "example-app.key" -in "example-app.crt" -passout pass: - - ``` - -4. Register a new application with the certificate content form `example-app.crt` - - ``` - certificateContents="$(tail -n+2 "example-app.crt" | head -n-1)" - - az ad app create \ - --display-name example-app \ - --homepage https://example-app/home \ - --identifier-uris https://example-app/app \ - --key-usage Verify --end-date 2018-01-01 \ - --key-value "${certificateContents}" - ``` - -5. Create a service principal using the `Application ID` from previous step - - ``` - az ad sp create --id "APPLICATION_ID" - ``` - - * Replace `APPLICATION_ID` with `appId` from step 4. - - -### Grant the necessary permissions - -Azure relies on a Role-Based Access Control (RBAC) model to manage the access to resources at a fine-grained -level. There is a set of [pre-defined roles](https://docs.microsoft.com/azure/active-directory/role-based-access-built-in-roles) -which can be assigned to a service principal of an Azure AD application depending of your needs. - -``` -az role assignment create --assigner "SERVICE_PRINCIPAL_ID" --role "ROLE_NAME" -``` - -* Replace the `SERVICE_PRINCIPAL_ID` with the `appId` from previous step. -* Replace the `ROLE_NAME` with a role name of your choice. - -It is also possible to define custom role definitions. - -``` -az role definition create --role-definition role-definition.json -``` - -* Check [custom roles](https://docs.microsoft.com/azure/active-directory/role-based-access-control-custom-roles) for more details regarding the content of `role-definition.json` file. - - -### Acquire Access Token - -The common configuration used by all flows: - -```Go -const activeDirectoryEndpoint = "https://login.microsoftonline.com/" -tenantID := "TENANT_ID" -oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID) - -applicationID := "APPLICATION_ID" - -callback := func(token adal.Token) error { - // This is called after the token is acquired -} - -// The resource for which the token is acquired -resource := "https://management.core.windows.net/" -``` - -* Replace the `TENANT_ID` with your tenant ID. -* Replace the `APPLICATION_ID` with the value from previous section. - -#### Client Credentials - -```Go -applicationSecret := "APPLICATION_SECRET" - -spt, err := adal.NewServicePrincipalToken( - *oauthConfig, - appliationID, - applicationSecret, - resource, - callbacks...) -if err != nil { - return nil, err -} - -// Acquire a new access token -err = spt.Refresh() -if (err == nil) { - token := spt.Token -} -``` - -* Replace the `APPLICATION_SECRET` with the `password` value from previous section. - -#### Client Certificate - -```Go -certificatePath := "./example-app.pfx" - -certData, err := ioutil.ReadFile(certificatePath) -if err != nil { - return nil, fmt.Errorf("failed to read the certificate file (%s): %v", certificatePath, err) -} - -// Get the certificate and private key from pfx file -certificate, rsaPrivateKey, err := decodePkcs12(certData, "") -if err != nil { - return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) -} - -spt, err := adal.NewServicePrincipalTokenFromCertificate( - *oauthConfig, - applicationID, - certificate, - rsaPrivateKey, - resource, - callbacks...) - -// Acquire a new access token -err = spt.Refresh() -if (err == nil) { - token := spt.Token -} -``` - -* Update the certificate path to point to the example-app.pfx file which was created in previous section. - - -#### Device Code - -```Go -oauthClient := &http.Client{} - -// Acquire the device code -deviceCode, err := adal.InitiateDeviceAuth( - oauthClient, - *oauthConfig, - applicationID, - resource) -if err != nil { - return nil, fmt.Errorf("Failed to start device auth flow: %s", err) -} - -// Display the authentication message -fmt.Println(*deviceCode.Message) - -// Wait here until the user is authenticated -token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) -if err != nil { - return nil, fmt.Errorf("Failed to finish device auth flow: %s", err) -} - -spt, err := adal.NewServicePrincipalTokenFromManualToken( - *oauthConfig, - applicationID, - resource, - *token, - callbacks...) - -if (err == nil) { - token := spt.Token -} -``` - -#### Username password authenticate - -```Go -spt, err := adal.NewServicePrincipalTokenFromUsernamePassword( - *oauthConfig, - applicationID, - username, - password, - resource, - callbacks...) - -if (err == nil) { - token := spt.Token -} -``` - -#### Authorization code authenticate - -``` Go -spt, err := adal.NewServicePrincipalTokenFromAuthorizationCode( - *oauthConfig, - applicationID, - clientSecret, - authorizationCode, - redirectURI, - resource, - callbacks...) - -err = spt.Refresh() -if (err == nil) { - token := spt.Token -} -``` - -### Command Line Tool - -A command line tool is available in `cmd/adal.go` that can acquire a token for a given resource. It supports all flows mentioned above. - -``` -adal -h - -Usage of ./adal: - -applicationId string - application id - -certificatePath string - path to pk12/PFC application certificate - -mode string - authentication mode (device, secret, cert, refresh) (default "device") - -resource string - resource for which the token is requested - -secret string - application secret - -tenantId string - tenant id - -tokenCachePath string - location of oath token cache (default "/home/cgc/.adal/accessToken.json") -``` - -Example acquire a token for `https://management.core.windows.net/` using device code flow: - -``` -adal -mode device \ - -applicationId "APPLICATION_ID" \ - -tenantId "TENANT_ID" \ - -resource https://management.core.windows.net/ - -``` diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go deleted file mode 100644 index fa5964742..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go +++ /dev/null @@ -1,151 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "errors" - "fmt" - "net/url" -) - -const ( - activeDirectoryEndpointTemplate = "%s/oauth2/%s%s" -) - -// OAuthConfig represents the endpoints needed -// in OAuth operations -type OAuthConfig struct { - AuthorityEndpoint url.URL `json:"authorityEndpoint"` - AuthorizeEndpoint url.URL `json:"authorizeEndpoint"` - TokenEndpoint url.URL `json:"tokenEndpoint"` - DeviceCodeEndpoint url.URL `json:"deviceCodeEndpoint"` -} - -// IsZero returns true if the OAuthConfig object is zero-initialized. -func (oac OAuthConfig) IsZero() bool { - return oac == OAuthConfig{} -} - -func validateStringParam(param, name string) error { - if len(param) == 0 { - return fmt.Errorf("parameter '" + name + "' cannot be empty") - } - return nil -} - -// NewOAuthConfig returns an OAuthConfig with tenant specific urls -func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { - apiVer := "1.0" - return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer) -} - -// NewOAuthConfigWithAPIVersion returns an OAuthConfig with tenant specific urls. -// If apiVersion is not nil the "api-version" query parameter will be appended to the endpoint URLs with the specified value. -func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) { - if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { - return nil, err - } - api := "" - // it's legal for tenantID to be empty so don't validate it - if apiVersion != nil { - if err := validateStringParam(*apiVersion, "apiVersion"); err != nil { - return nil, err - } - api = fmt.Sprintf("?api-version=%s", *apiVersion) - } - u, err := url.Parse(activeDirectoryEndpoint) - if err != nil { - return nil, err - } - authorityURL, err := u.Parse(tenantID) - if err != nil { - return nil, err - } - authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api)) - if err != nil { - return nil, err - } - tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api)) - if err != nil { - return nil, err - } - deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api)) - if err != nil { - return nil, err - } - - return &OAuthConfig{ - AuthorityEndpoint: *authorityURL, - AuthorizeEndpoint: *authorizeURL, - TokenEndpoint: *tokenURL, - DeviceCodeEndpoint: *deviceCodeURL, - }, nil -} - -// MultiTenantOAuthConfig provides endpoints for primary and aulixiary tenant IDs. -type MultiTenantOAuthConfig interface { - PrimaryTenant() *OAuthConfig - AuxiliaryTenants() []*OAuthConfig -} - -// OAuthOptions contains optional OAuthConfig creation arguments. -type OAuthOptions struct { - APIVersion string -} - -func (c OAuthOptions) apiVersion() string { - if c.APIVersion != "" { - return fmt.Sprintf("?api-version=%s", c.APIVersion) - } - return "1.0" -} - -// NewMultiTenantOAuthConfig creates an object that support multitenant OAuth configuration. -// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/authenticate-multi-tenant for more information. -func NewMultiTenantOAuthConfig(activeDirectoryEndpoint, primaryTenantID string, auxiliaryTenantIDs []string, options OAuthOptions) (MultiTenantOAuthConfig, error) { - if len(auxiliaryTenantIDs) == 0 || len(auxiliaryTenantIDs) > 3 { - return nil, errors.New("must specify one to three auxiliary tenants") - } - mtCfg := multiTenantOAuthConfig{ - cfgs: make([]*OAuthConfig, len(auxiliaryTenantIDs)+1), - } - apiVer := options.apiVersion() - pri, err := NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, primaryTenantID, &apiVer) - if err != nil { - return nil, fmt.Errorf("failed to create OAuthConfig for primary tenant: %v", err) - } - mtCfg.cfgs[0] = pri - for i := range auxiliaryTenantIDs { - aux, err := NewOAuthConfig(activeDirectoryEndpoint, auxiliaryTenantIDs[i]) - if err != nil { - return nil, fmt.Errorf("failed to create OAuthConfig for tenant '%s': %v", auxiliaryTenantIDs[i], err) - } - mtCfg.cfgs[i+1] = aux - } - return mtCfg, nil -} - -type multiTenantOAuthConfig struct { - // first config in the slice is the primary tenant - cfgs []*OAuthConfig -} - -func (m multiTenantOAuthConfig) PrimaryTenant() *OAuthConfig { - return m.cfgs[0] -} - -func (m multiTenantOAuthConfig) AuxiliaryTenants() []*OAuthConfig { - return m.cfgs[1:] -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go deleted file mode 100644 index 9daa4b58b..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go +++ /dev/null @@ -1,273 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/* - This file is largely based on rjw57/oauth2device's code, with the follow differences: - * scope -> resource, and only allow a single one - * receive "Message" in the DeviceCode struct and show it to users as the prompt - * azure-xplat-cli has the following behavior that this emulates: - - does not send client_secret during the token exchange - - sends resource again in the token exchange request -*/ - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" -) - -const ( - logPrefix = "autorest/adal/devicetoken:" -) - -var ( - // ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow - ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix) - - // ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow - ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix) - - // ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow - ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix) - - // ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow - ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix) - - // ErrDeviceSlowDown represents the service telling us we're polling too often during device flow - ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix) - - // ErrDeviceCodeEmpty represents an empty device code from the device endpoint while using device flow - ErrDeviceCodeEmpty = fmt.Errorf("%s Error while retrieving device code: Device Code Empty", logPrefix) - - // ErrOAuthTokenEmpty represents an empty OAuth token from the token endpoint when using device flow - ErrOAuthTokenEmpty = fmt.Errorf("%s Error while retrieving OAuth token: Token Empty", logPrefix) - - errCodeSendingFails = "Error occurred while sending request for Device Authorization Code" - errCodeHandlingFails = "Error occurred while handling response from the Device Endpoint" - errTokenSendingFails = "Error occurred while sending request with device code for a token" - errTokenHandlingFails = "Error occurred while handling response from the Token Endpoint (during device flow)" - errStatusNotOK = "Error HTTP status != 200" -) - -// DeviceCode is the object returned by the device auth endpoint -// It contains information to instruct the user to complete the auth flow -type DeviceCode struct { - DeviceCode *string `json:"device_code,omitempty"` - UserCode *string `json:"user_code,omitempty"` - VerificationURL *string `json:"verification_url,omitempty"` - ExpiresIn *int64 `json:"expires_in,string,omitempty"` - Interval *int64 `json:"interval,string,omitempty"` - - Message *string `json:"message"` // Azure specific - Resource string // store the following, stored when initiating, used when exchanging - OAuthConfig OAuthConfig - ClientID string -} - -// TokenError is the object returned by the token exchange endpoint -// when something is amiss -type TokenError struct { - Error *string `json:"error,omitempty"` - ErrorCodes []int `json:"error_codes,omitempty"` - ErrorDescription *string `json:"error_description,omitempty"` - Timestamp *string `json:"timestamp,omitempty"` - TraceID *string `json:"trace_id,omitempty"` -} - -// DeviceToken is the object return by the token exchange endpoint -// It can either look like a Token or an ErrorToken, so put both here -// and check for presence of "Error" to know if we are in error state -type deviceToken struct { - Token - TokenError -} - -// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode -// that can be used with CheckForUserCompletion or WaitForUserCompletion. -// Deprecated: use InitiateDeviceAuthWithContext() instead. -func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { - return InitiateDeviceAuthWithContext(context.Background(), sender, oauthConfig, clientID, resource) -} - -// InitiateDeviceAuthWithContext initiates a device auth flow. It returns a DeviceCode -// that can be used with CheckForUserCompletion or WaitForUserCompletion. -func InitiateDeviceAuthWithContext(ctx context.Context, sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { - v := url.Values{ - "client_id": []string{clientID}, - "resource": []string{resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req.WithContext(ctx)) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK) - } - - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrDeviceCodeEmpty - } - - var code DeviceCode - err = json.Unmarshal(rb, &code) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - code.ClientID = clientID - code.Resource = resource - code.OAuthConfig = oauthConfig - - return &code, nil -} - -// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint -// to see if the device flow has: been completed, timed out, or otherwise failed -// Deprecated: use CheckForUserCompletionWithContext() instead. -func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - return CheckForUserCompletionWithContext(context.Background(), sender, code) -} - -// CheckForUserCompletionWithContext takes a DeviceCode and checks with the Azure AD OAuth endpoint -// to see if the device flow has: been completed, timed out, or otherwise failed -func CheckForUserCompletionWithContext(ctx context.Context, sender Sender, code *DeviceCode) (*Token, error) { - v := url.Values{ - "client_id": []string{code.ClientID}, - "code": []string{*code.DeviceCode}, - "grant_type": []string{OAuthGrantTypeDeviceCode}, - "resource": []string{code.Resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, code.OAuthConfig.TokenEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req.WithContext(ctx)) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK && len(strings.Trim(string(rb), " ")) == 0 { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, errStatusNotOK) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrOAuthTokenEmpty - } - - var token deviceToken - err = json.Unmarshal(rb, &token) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if token.Error == nil { - return &token.Token, nil - } - - switch *token.Error { - case "authorization_pending": - return nil, ErrDeviceAuthorizationPending - case "slow_down": - return nil, ErrDeviceSlowDown - case "access_denied": - return nil, ErrDeviceAccessDenied - case "code_expired": - return nil, ErrDeviceCodeExpired - default: - // return a more meaningful error message if available - if token.ErrorDescription != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, *token.Error, *token.ErrorDescription) - } - return nil, ErrDeviceGeneric - } -} - -// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. -// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. -// Deprecated: use WaitForUserCompletionWithContext() instead. -func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - return WaitForUserCompletionWithContext(context.Background(), sender, code) -} - -// WaitForUserCompletionWithContext calls CheckForUserCompletion repeatedly until a token is granted or an error -// state occurs. This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. -func WaitForUserCompletionWithContext(ctx context.Context, sender Sender, code *DeviceCode) (*Token, error) { - intervalDuration := time.Duration(*code.Interval) * time.Second - waitDuration := intervalDuration - - for { - token, err := CheckForUserCompletionWithContext(ctx, sender, code) - - if err == nil { - return token, nil - } - - switch err { - case ErrDeviceSlowDown: - waitDuration += waitDuration - case ErrDeviceAuthorizationPending: - // noop - default: // everything else is "fatal" to us - return nil, err - } - - if waitDuration > (intervalDuration * 3) { - return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) - } - - select { - case <-time.After(waitDuration): - // noop - case <-ctx.Done(): - return nil, ctx.Err() - } - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go deleted file mode 100644 index 647a61bb8..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build modhack -// +build modhack - -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go b/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go deleted file mode 100644 index 2a974a39b..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go +++ /dev/null @@ -1,135 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "golang.org/x/crypto/pkcs12" -) - -var ( - // ErrMissingCertificate is returned when no local certificate is found in the provided PFX data. - ErrMissingCertificate = errors.New("adal: certificate missing") - - // ErrMissingPrivateKey is returned when no private key is found in the provided PFX data. - ErrMissingPrivateKey = errors.New("adal: private key missing") -) - -// LoadToken restores a Token object from a file located at 'path'. -func LoadToken(path string) (*Token, error) { - file, err := os.Open(path) - if err != nil { - return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - } - defer file.Close() - - var token Token - - dec := json.NewDecoder(file) - if err = dec.Decode(&token); err != nil { - return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err) - } - return &token, nil -} - -// SaveToken persists an oauth token at the given location on disk. -// It moves the new file into place so it can safely be used to replace an existing file -// that maybe accessed by multiple processes. -func SaveToken(path string, mode os.FileMode, token Token) error { - dir := filepath.Dir(path) - err := os.MkdirAll(dir, os.ModePerm) - if err != nil { - return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err) - } - - newFile, err := ioutil.TempFile(dir, "token") - if err != nil { - return fmt.Errorf("failed to create the temp file to write the token: %v", err) - } - tempPath := newFile.Name() - - if err := json.NewEncoder(newFile).Encode(token); err != nil { - return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err) - } - if err := newFile.Close(); err != nil { - return fmt.Errorf("failed to close temp file %s: %v", tempPath, err) - } - - // Atomic replace to avoid multi-writer file corruptions - if err := os.Rename(tempPath, path); err != nil { - return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err) - } - if err := os.Chmod(path, mode); err != nil { - return fmt.Errorf("failed to chmod the token file %s: %v", path, err) - } - return nil -} - -// DecodePfxCertificateData extracts the x509 certificate and RSA private key from the provided PFX data. -// The PFX data must contain a private key along with a certificate whose public key matches that of the -// private key or an error is returned. -// If the private key is not password protected pass the empty string for password. -func DecodePfxCertificateData(pfxData []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) { - blocks, err := pkcs12.ToPEM(pfxData, password) - if err != nil { - return nil, nil, err - } - // first extract the private key - var priv *rsa.PrivateKey - for _, block := range blocks { - if block.Type == "PRIVATE KEY" { - priv, err = x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - return nil, nil, err - } - break - } - } - if priv == nil { - return nil, nil, ErrMissingPrivateKey - } - // now find the certificate with the matching public key of our private key - var cert *x509.Certificate - for _, block := range blocks { - if block.Type == "CERTIFICATE" { - pcert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, nil, err - } - certKey, ok := pcert.PublicKey.(*rsa.PublicKey) - if !ok { - // keep looking - continue - } - if priv.E == certKey.E && priv.N.Cmp(certKey.N) == 0 { - // found a match - cert = pcert - break - } - } - } - if cert == nil { - return nil, nil, ErrMissingCertificate - } - return cert, priv, nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go b/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go deleted file mode 100644 index eb649bce9..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go +++ /dev/null @@ -1,101 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "crypto/tls" - "net" - "net/http" - "net/http/cookiejar" - "sync" - "time" - - "github.com/Azure/go-autorest/tracing" -) - -const ( - contentType = "Content-Type" - mimeTypeFormPost = "application/x-www-form-urlencoded" -) - -// DO NOT ACCESS THIS DIRECTLY. go through sender() -var defaultSender Sender -var defaultSenderInit = &sync.Once{} - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibly decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(sender(), decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} - -func sender() Sender { - // note that we can't init defaultSender in init() since it will - // execute before calling code has had a chance to enable tracing - defaultSenderInit.Do(func() { - // copied from http.DefaultTransport with a TLS minimum version. - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - ForceAttemptHTTP2: true, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, - }, - } - var roundTripper http.RoundTripper = transport - if tracing.IsEnabled() { - roundTripper = tracing.NewTransport(transport) - } - j, _ := cookiejar.New(nil) - defaultSender = &http.Client{Jar: j, Transport: roundTripper} - }) - return defaultSender -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go deleted file mode 100644 index 2a24ab80c..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go +++ /dev/null @@ -1,1430 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "math" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "sync" - "time" - - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/logger" - "github.com/golang-jwt/jwt/v4" -) - -const ( - defaultRefresh = 5 * time.Minute - - // OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow - OAuthGrantTypeDeviceCode = "device_code" - - // OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows - OAuthGrantTypeClientCredentials = "client_credentials" - - // OAuthGrantTypeUserPass is the "grant_type" identifier used in username and password auth flows - OAuthGrantTypeUserPass = "password" - - // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows - OAuthGrantTypeRefreshToken = "refresh_token" - - // OAuthGrantTypeAuthorizationCode is the "grant_type" identifier used in authorization code flows - OAuthGrantTypeAuthorizationCode = "authorization_code" - - // metadataHeader is the header required by MSI extension - metadataHeader = "Metadata" - - // msiEndpoint is the well known endpoint for getting MSI authentications tokens - msiEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" - - // the API version to use for the MSI endpoint - msiAPIVersion = "2018-02-01" - - // the default number of attempts to refresh an MSI authentication token - defaultMaxMSIRefreshAttempts = 5 - - // asMSIEndpointEnv is the environment variable used to store the endpoint on App Service and Functions - msiEndpointEnv = "MSI_ENDPOINT" - - // asMSISecretEnv is the environment variable used to store the request secret on App Service and Functions - msiSecretEnv = "MSI_SECRET" - - // the API version to use for the legacy App Service MSI endpoint - appServiceAPIVersion2017 = "2017-09-01" - - // secret header used when authenticating against app service MSI endpoint - secretHeader = "Secret" - - // the format for expires_on in UTC with AM/PM - expiresOnDateFormatPM = "1/2/2006 15:04:05 PM +00:00" - - // the format for expires_on in UTC without AM/PM - expiresOnDateFormat = "1/2/2006 15:04:05 +00:00" -) - -// OAuthTokenProvider is an interface which should be implemented by an access token retriever -type OAuthTokenProvider interface { - OAuthToken() string -} - -// MultitenantOAuthTokenProvider provides tokens used for multi-tenant authorization. -type MultitenantOAuthTokenProvider interface { - PrimaryOAuthToken() string - AuxiliaryOAuthTokens() []string -} - -// TokenRefreshError is an interface used by errors returned during token refresh. -type TokenRefreshError interface { - error - Response() *http.Response -} - -// Refresher is an interface for token refresh functionality -type Refresher interface { - Refresh() error - RefreshExchange(resource string) error - EnsureFresh() error -} - -// RefresherWithContext is an interface for token refresh functionality -type RefresherWithContext interface { - RefreshWithContext(ctx context.Context) error - RefreshExchangeWithContext(ctx context.Context, resource string) error - EnsureFreshWithContext(ctx context.Context) error -} - -// TokenRefreshCallback is the type representing callbacks that will be called after -// a successful token refresh -type TokenRefreshCallback func(Token) error - -// TokenRefresh is a type representing a custom callback to refresh a token -type TokenRefresh func(ctx context.Context, resource string) (*Token, error) - -// JWTCallback is the type representing callback that will be called to get the federated OIDC JWT -type JWTCallback func() (string, error) - -// Token encapsulates the access token used to authorize Azure requests. -// https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow#service-to-service-access-token-response -type Token struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - - ExpiresIn json.Number `json:"expires_in"` - ExpiresOn json.Number `json:"expires_on"` - NotBefore json.Number `json:"not_before"` - - Resource string `json:"resource"` - Type string `json:"token_type"` -} - -func newToken() Token { - return Token{ - ExpiresIn: "0", - ExpiresOn: "0", - NotBefore: "0", - } -} - -// IsZero returns true if the token object is zero-initialized. -func (t Token) IsZero() bool { - return t == Token{} -} - -// Expires returns the time.Time when the Token expires. -func (t Token) Expires() time.Time { - s, err := t.ExpiresOn.Float64() - if err != nil { - s = -3600 - } - - expiration := date.NewUnixTimeFromSeconds(s) - - return time.Time(expiration).UTC() -} - -// IsExpired returns true if the Token is expired, false otherwise. -func (t Token) IsExpired() bool { - return t.WillExpireIn(0) -} - -// WillExpireIn returns true if the Token will expire after the passed time.Duration interval -// from now, false otherwise. -func (t Token) WillExpireIn(d time.Duration) bool { - return !t.Expires().After(time.Now().Add(d)) -} - -// OAuthToken return the current access token -func (t *Token) OAuthToken() string { - return t.AccessToken -} - -// ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form -// that is submitted when acquiring an oAuth token. -type ServicePrincipalSecret interface { - SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error -} - -// ServicePrincipalNoSecret represents a secret type that contains no secret -// meaning it is not valid for fetching a fresh token. This is used by Manual -type ServicePrincipalNoSecret struct { -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret -// It only returns an error for the ServicePrincipalNoSecret type -func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token") -} - -// MarshalJSON implements the json.Marshaler interface. -func (noSecret ServicePrincipalNoSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalNoSecret", - }) -} - -// ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization. -type ServicePrincipalTokenSecret struct { - ClientSecret string `json:"value"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using the client_secret. -func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("client_secret", tokenSecret.ClientSecret) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (tokenSecret ServicePrincipalTokenSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Value string `json:"value"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalTokenSecret", - Value: tokenSecret.ClientSecret, - }) -} - -// ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs. -type ServicePrincipalCertificateSecret struct { - Certificate *x509.Certificate - PrivateKey *rsa.PrivateKey -} - -// SignJwt returns the JWT signed with the certificate's private key. -func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { - hasher := sha1.New() - _, err := hasher.Write(secret.Certificate.Raw) - if err != nil { - return "", err - } - - thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) - - // The jti (JWT ID) claim provides a unique identifier for the JWT. - jti := make([]byte, 20) - _, err = rand.Read(jti) - if err != nil { - return "", err - } - - token := jwt.New(jwt.SigningMethodRS256) - token.Header["x5t"] = thumbprint - x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)} - token.Header["x5c"] = x5c - token.Claims = jwt.MapClaims{ - "aud": spt.inner.OauthConfig.TokenEndpoint.String(), - "iss": spt.inner.ClientID, - "sub": spt.inner.ClientID, - "jti": base64.URLEncoding.EncodeToString(jti), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(24 * time.Hour).Unix(), - } - - signedString, err := token.SignedString(secret.PrivateKey) - return signedString, err -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate. -func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - jwt, err := secret.SignJwt(spt) - if err != nil { - return err - } - - v.Set("client_assertion", jwt) - v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalCertificateSecret) MarshalJSON() ([]byte, error) { - return nil, errors.New("marshalling ServicePrincipalCertificateSecret is not supported") -} - -// ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension. -type ServicePrincipalMSISecret struct { - msiType msiType - clientResourceID string -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (msiSecret ServicePrincipalMSISecret) MarshalJSON() ([]byte, error) { - return nil, errors.New("marshalling ServicePrincipalMSISecret is not supported") -} - -// ServicePrincipalUsernamePasswordSecret implements ServicePrincipalSecret for username and password auth. -type ServicePrincipalUsernamePasswordSecret struct { - Username string `json:"username"` - Password string `json:"password"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalUsernamePasswordSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("username", secret.Username) - v.Set("password", secret.Password) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalUsernamePasswordSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Username string `json:"username"` - Password string `json:"password"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalUsernamePasswordSecret", - Username: secret.Username, - Password: secret.Password, - }) -} - -// ServicePrincipalAuthorizationCodeSecret implements ServicePrincipalSecret for authorization code auth. -type ServicePrincipalAuthorizationCodeSecret struct { - ClientSecret string `json:"value"` - AuthorizationCode string `json:"authCode"` - RedirectURI string `json:"redirect"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalAuthorizationCodeSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("code", secret.AuthorizationCode) - v.Set("client_secret", secret.ClientSecret) - v.Set("redirect_uri", secret.RedirectURI) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalAuthorizationCodeSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Value string `json:"value"` - AuthCode string `json:"authCode"` - Redirect string `json:"redirect"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalAuthorizationCodeSecret", - Value: secret.ClientSecret, - AuthCode: secret.AuthorizationCode, - Redirect: secret.RedirectURI, - }) -} - -// ServicePrincipalFederatedSecret implements ServicePrincipalSecret for Federated JWTs. -type ServicePrincipalFederatedSecret struct { - jwtCallback JWTCallback -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during OAuth Token Acquisition using a JWT signed by an OIDC issuer. -func (secret *ServicePrincipalFederatedSecret) SetAuthenticationValues(_ *ServicePrincipalToken, v *url.Values) error { - jwt, err := secret.jwtCallback() - if err != nil { - return err - } - - v.Set("client_assertion", jwt) - v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalFederatedSecret) MarshalJSON() ([]byte, error) { - return nil, errors.New("marshalling ServicePrincipalFederatedSecret is not supported") -} - -// ServicePrincipalToken encapsulates a Token created for a Service Principal. -type ServicePrincipalToken struct { - inner servicePrincipalToken - refreshLock *sync.RWMutex - sender Sender - customRefreshFunc TokenRefresh - refreshCallbacks []TokenRefreshCallback - // MaxMSIRefreshAttempts is the maximum number of attempts to refresh an MSI token. - // Settings this to a value less than 1 will use the default value. - MaxMSIRefreshAttempts int -} - -// MarshalTokenJSON returns the marshalled inner token. -func (spt ServicePrincipalToken) MarshalTokenJSON() ([]byte, error) { - return json.Marshal(spt.inner.Token) -} - -// SetRefreshCallbacks replaces any existing refresh callbacks with the specified callbacks. -func (spt *ServicePrincipalToken) SetRefreshCallbacks(callbacks []TokenRefreshCallback) { - spt.refreshCallbacks = callbacks -} - -// SetCustomRefreshFunc sets a custom refresh function used to refresh the token. -func (spt *ServicePrincipalToken) SetCustomRefreshFunc(customRefreshFunc TokenRefresh) { - spt.customRefreshFunc = customRefreshFunc -} - -// MarshalJSON implements the json.Marshaler interface. -func (spt ServicePrincipalToken) MarshalJSON() ([]byte, error) { - return json.Marshal(spt.inner) -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (spt *ServicePrincipalToken) UnmarshalJSON(data []byte) error { - // need to determine the token type - raw := map[string]interface{}{} - err := json.Unmarshal(data, &raw) - if err != nil { - return err - } - secret := raw["secret"].(map[string]interface{}) - switch secret["type"] { - case "ServicePrincipalNoSecret": - spt.inner.Secret = &ServicePrincipalNoSecret{} - case "ServicePrincipalTokenSecret": - spt.inner.Secret = &ServicePrincipalTokenSecret{} - case "ServicePrincipalCertificateSecret": - return errors.New("unmarshalling ServicePrincipalCertificateSecret is not supported") - case "ServicePrincipalMSISecret": - return errors.New("unmarshalling ServicePrincipalMSISecret is not supported") - case "ServicePrincipalUsernamePasswordSecret": - spt.inner.Secret = &ServicePrincipalUsernamePasswordSecret{} - case "ServicePrincipalAuthorizationCodeSecret": - spt.inner.Secret = &ServicePrincipalAuthorizationCodeSecret{} - case "ServicePrincipalFederatedSecret": - return errors.New("unmarshalling ServicePrincipalFederatedSecret is not supported") - default: - return fmt.Errorf("unrecognized token type '%s'", secret["type"]) - } - err = json.Unmarshal(data, &spt.inner) - if err != nil { - return err - } - // Don't override the refreshLock or the sender if those have been already set. - if spt.refreshLock == nil { - spt.refreshLock = &sync.RWMutex{} - } - if spt.sender == nil { - spt.sender = sender() - } - return nil -} - -// internal type used for marshalling/unmarshalling -type servicePrincipalToken struct { - Token Token `json:"token"` - Secret ServicePrincipalSecret `json:"secret"` - OauthConfig OAuthConfig `json:"oauth"` - ClientID string `json:"clientID"` - Resource string `json:"resource"` - AutoRefresh bool `json:"autoRefresh"` - RefreshWithin time.Duration `json:"refreshWithin"` -} - -func validateOAuthConfig(oac OAuthConfig) error { - if oac.IsZero() { - return fmt.Errorf("parameter 'oauthConfig' cannot be zero-initialized") - } - return nil -} - -// NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation. -func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(id, "id"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("parameter 'secret' cannot be nil") - } - spt := &ServicePrincipalToken{ - inner: servicePrincipalToken{ - Token: newToken(), - OauthConfig: oauthConfig, - Secret: secret, - ClientID: id, - Resource: resource, - AutoRefresh: true, - RefreshWithin: defaultRefresh, - }, - refreshLock: &sync.RWMutex{}, - sender: sender(), - refreshCallbacks: callbacks, - } - return spt, nil -} - -// NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token -func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if token.IsZero() { - return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") - } - spt, err := NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalNoSecret{}, - callbacks...) - if err != nil { - return nil, err - } - - spt.inner.Token = token - - return spt, nil -} - -// NewServicePrincipalTokenFromManualTokenSecret creates a ServicePrincipalToken using the supplied token and secret -func NewServicePrincipalTokenFromManualTokenSecret(oauthConfig OAuthConfig, clientID string, resource string, token Token, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("parameter 'secret' cannot be nil") - } - if token.IsZero() { - return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") - } - spt, err := NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - secret, - callbacks...) - if err != nil { - return nil, err - } - - spt.inner.Token = token - - return spt, nil -} - -// NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal -// credentials scoped to the named resource. -func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(secret, "secret"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalTokenSecret{ - ClientSecret: secret, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromCertificate creates a ServicePrincipalToken from the supplied pkcs12 bytes. -func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if certificate == nil { - return nil, fmt.Errorf("parameter 'certificate' cannot be nil") - } - if privateKey == nil { - return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromUsernamePassword creates a ServicePrincipalToken from the username and password. -func NewServicePrincipalTokenFromUsernamePassword(oauthConfig OAuthConfig, clientID string, username string, password string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(username, "username"); err != nil { - return nil, err - } - if err := validateStringParam(password, "password"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalUsernamePasswordSecret{ - Username: username, - Password: password, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromAuthorizationCode creates a ServicePrincipalToken from the -func NewServicePrincipalTokenFromAuthorizationCode(oauthConfig OAuthConfig, clientID string, clientSecret string, authorizationCode string, redirectURI string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(clientSecret, "clientSecret"); err != nil { - return nil, err - } - if err := validateStringParam(authorizationCode, "authorizationCode"); err != nil { - return nil, err - } - if err := validateStringParam(redirectURI, "redirectURI"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalAuthorizationCodeSecret{ - ClientSecret: clientSecret, - AuthorizationCode: authorizationCode, - RedirectURI: redirectURI, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromFederatedToken creates a ServicePrincipalToken from the supplied federated OIDC JWT. -// -// Deprecated: Use NewServicePrincipalTokenFromFederatedTokenWithCallback to refresh jwt dynamically. -func NewServicePrincipalTokenFromFederatedToken(oauthConfig OAuthConfig, clientID string, jwt string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if jwt == "" { - return nil, fmt.Errorf("parameter 'jwt' cannot be empty") - } - return NewServicePrincipalTokenFromFederatedTokenCallback( - oauthConfig, - clientID, - func() (string, error) { - return jwt, nil - }, - resource, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromFederatedTokenCallback creates a ServicePrincipalToken from the supplied federated OIDC JWTCallback. -func NewServicePrincipalTokenFromFederatedTokenCallback(oauthConfig OAuthConfig, clientID string, jwtCallback JWTCallback, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if jwtCallback == nil { - return nil, fmt.Errorf("parameter 'jwtCallback' cannot be empty") - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalFederatedSecret{ - jwtCallback: jwtCallback, - }, - callbacks..., - ) -} - -type msiType int - -const ( - msiTypeUnavailable msiType = iota - msiTypeAppServiceV20170901 - msiTypeCloudShell - msiTypeIMDS -) - -func (m msiType) String() string { - switch m { - case msiTypeAppServiceV20170901: - return "AppServiceV20170901" - case msiTypeCloudShell: - return "CloudShell" - case msiTypeIMDS: - return "IMDS" - default: - return fmt.Sprintf("unhandled MSI type %d", m) - } -} - -// returns the MSI type and endpoint, or an error -func getMSIType() (msiType, string, error) { - if endpointEnvVar := os.Getenv(msiEndpointEnv); endpointEnvVar != "" { - // if the env var MSI_ENDPOINT is set - if secretEnvVar := os.Getenv(msiSecretEnv); secretEnvVar != "" { - // if BOTH the env vars MSI_ENDPOINT and MSI_SECRET are set the msiType is AppService - return msiTypeAppServiceV20170901, endpointEnvVar, nil - } - // if ONLY the env var MSI_ENDPOINT is set the msiType is CloudShell - return msiTypeCloudShell, endpointEnvVar, nil - } - // if MSI_ENDPOINT is NOT set assume the msiType is IMDS - return msiTypeIMDS, msiEndpoint, nil -} - -// GetMSIVMEndpoint gets the MSI endpoint on Virtual Machines. -// NOTE: this always returns the IMDS endpoint, it does not work for app services or cloud shell. -// Deprecated: NewServicePrincipalTokenFromMSI() and variants will automatically detect the endpoint. -func GetMSIVMEndpoint() (string, error) { - return msiEndpoint, nil -} - -// GetMSIAppServiceEndpoint get the MSI endpoint for App Service and Functions. -// It will return an error when not running in an app service/functions environment. -// Deprecated: NewServicePrincipalTokenFromMSI() and variants will automatically detect the endpoint. -func GetMSIAppServiceEndpoint() (string, error) { - msiType, endpoint, err := getMSIType() - if err != nil { - return "", err - } - switch msiType { - case msiTypeAppServiceV20170901: - return endpoint, nil - default: - return "", fmt.Errorf("%s is not app service environment", msiType) - } -} - -// GetMSIEndpoint get the appropriate MSI endpoint depending on the runtime environment -// Deprecated: NewServicePrincipalTokenFromMSI() and variants will automatically detect the endpoint. -func GetMSIEndpoint() (string, error) { - _, endpoint, err := getMSIType() - return endpoint, err -} - -// NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the system assigned identity when creating the token. -// msiEndpoint - empty string, or pass a non-empty string to override the default value. -// Deprecated: use NewServicePrincipalTokenFromManagedIdentity() instead. -func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, "", "", callbacks...) -} - -// NewServicePrincipalTokenFromMSIWithUserAssignedID creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the clientID of specified user assigned identity when creating the token. -// msiEndpoint - empty string, or pass a non-empty string to override the default value. -// Deprecated: use NewServicePrincipalTokenFromManagedIdentity() instead. -func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(userAssignedID, "userAssignedID"); err != nil { - return nil, err - } - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, userAssignedID, "", callbacks...) -} - -// NewServicePrincipalTokenFromMSIWithIdentityResourceID creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the azure resource id of user assigned identity when creating the token. -// msiEndpoint - empty string, or pass a non-empty string to override the default value. -// Deprecated: use NewServicePrincipalTokenFromManagedIdentity() instead. -func NewServicePrincipalTokenFromMSIWithIdentityResourceID(msiEndpoint, resource string, identityResourceID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(identityResourceID, "identityResourceID"); err != nil { - return nil, err - } - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, "", identityResourceID, callbacks...) -} - -// ManagedIdentityOptions contains optional values for configuring managed identity authentication. -type ManagedIdentityOptions struct { - // ClientID is the user-assigned identity to use during authentication. - // It is mutually exclusive with IdentityResourceID. - ClientID string - - // IdentityResourceID is the resource ID of the user-assigned identity to use during authentication. - // It is mutually exclusive with ClientID. - IdentityResourceID string -} - -// NewServicePrincipalTokenFromManagedIdentity creates a ServicePrincipalToken using a managed identity. -// It supports the following managed identity environments. -// - App Service Environment (API version 2017-09-01 only) -// - Cloud shell -// - IMDS with a system or user assigned identity -func NewServicePrincipalTokenFromManagedIdentity(resource string, options *ManagedIdentityOptions, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if options == nil { - options = &ManagedIdentityOptions{} - } - return newServicePrincipalTokenFromMSI("", resource, options.ClientID, options.IdentityResourceID, callbacks...) -} - -func newServicePrincipalTokenFromMSI(msiEndpoint, resource, userAssignedID, identityResourceID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if userAssignedID != "" && identityResourceID != "" { - return nil, errors.New("cannot specify userAssignedID and identityResourceID") - } - msiType, endpoint, err := getMSIType() - if err != nil { - logger.Instance.Writef(logger.LogError, "Error determining managed identity environment: %v\n", err) - return nil, err - } - logger.Instance.Writef(logger.LogInfo, "Managed identity environment is %s, endpoint is %s\n", msiType, endpoint) - if msiEndpoint != "" { - endpoint = msiEndpoint - logger.Instance.Writef(logger.LogInfo, "Managed identity custom endpoint is %s\n", endpoint) - } - msiEndpointURL, err := url.Parse(endpoint) - if err != nil { - return nil, err - } - // cloud shell sends its data in the request body - if msiType != msiTypeCloudShell { - v := url.Values{} - v.Set("resource", resource) - clientIDParam := "client_id" - switch msiType { - case msiTypeAppServiceV20170901: - clientIDParam = "clientid" - v.Set("api-version", appServiceAPIVersion2017) - break - case msiTypeIMDS: - v.Set("api-version", msiAPIVersion) - } - if userAssignedID != "" { - v.Set(clientIDParam, userAssignedID) - } else if identityResourceID != "" { - v.Set("mi_res_id", identityResourceID) - } - msiEndpointURL.RawQuery = v.Encode() - } - - spt := &ServicePrincipalToken{ - inner: servicePrincipalToken{ - Token: newToken(), - OauthConfig: OAuthConfig{ - TokenEndpoint: *msiEndpointURL, - }, - Secret: &ServicePrincipalMSISecret{ - msiType: msiType, - clientResourceID: identityResourceID, - }, - Resource: resource, - AutoRefresh: true, - RefreshWithin: defaultRefresh, - ClientID: userAssignedID, - }, - refreshLock: &sync.RWMutex{}, - sender: sender(), - refreshCallbacks: callbacks, - MaxMSIRefreshAttempts: defaultMaxMSIRefreshAttempts, - } - - return spt, nil -} - -// internal type that implements TokenRefreshError -type tokenRefreshError struct { - message string - resp *http.Response -} - -// Error implements the error interface which is part of the TokenRefreshError interface. -func (tre tokenRefreshError) Error() string { - return tre.message -} - -// Response implements the TokenRefreshError interface, it returns the raw HTTP response from the refresh operation. -func (tre tokenRefreshError) Response() *http.Response { - return tre.resp -} - -func newTokenRefreshError(message string, resp *http.Response) TokenRefreshError { - return tokenRefreshError{message: message, resp: resp} -} - -// EnsureFresh will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (spt *ServicePrincipalToken) EnsureFresh() error { - return spt.EnsureFreshWithContext(context.Background()) -} - -// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (spt *ServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { - // must take the read lock when initially checking the token's expiration - if spt.inner.AutoRefresh && spt.Token().WillExpireIn(spt.inner.RefreshWithin) { - // take the write lock then check again to see if the token was already refreshed - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - if spt.inner.Token.WillExpireIn(spt.inner.RefreshWithin) { - return spt.refreshInternal(ctx, spt.inner.Resource) - } - } - return nil -} - -// InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization -func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { - if spt.refreshCallbacks != nil { - for _, callback := range spt.refreshCallbacks { - err := callback(spt.inner.Token) - if err != nil { - return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err) - } - } - } - return nil -} - -// Refresh obtains a fresh token for the Service Principal. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) Refresh() error { - return spt.RefreshWithContext(context.Background()) -} - -// RefreshWithContext obtains a fresh token for the Service Principal. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(ctx, spt.inner.Resource) -} - -// RefreshExchange refreshes the token, but for a different resource. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { - return spt.RefreshExchangeWithContext(context.Background(), resource) -} - -// RefreshExchangeWithContext refreshes the token, but for a different resource. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(ctx, resource) -} - -func (spt *ServicePrincipalToken) getGrantType() string { - switch spt.inner.Secret.(type) { - case *ServicePrincipalUsernamePasswordSecret: - return OAuthGrantTypeUserPass - case *ServicePrincipalAuthorizationCodeSecret: - return OAuthGrantTypeAuthorizationCode - default: - return OAuthGrantTypeClientCredentials - } -} - -func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource string) error { - if spt.customRefreshFunc != nil { - token, err := spt.customRefreshFunc(ctx, resource) - if err != nil { - return err - } - spt.inner.Token = *token - return spt.InvokeRefreshCallbacks(spt.inner.Token) - } - req, err := http.NewRequest(http.MethodPost, spt.inner.OauthConfig.TokenEndpoint.String(), nil) - if err != nil { - return fmt.Errorf("adal: Failed to build the refresh request. Error = '%v'", err) - } - req.Header.Add("User-Agent", UserAgent()) - req = req.WithContext(ctx) - var resp *http.Response - authBodyFilter := func(b []byte) []byte { - if logger.Level() != logger.LogAuth { - return []byte("**REDACTED** authentication body") - } - return b - } - if msiSecret, ok := spt.inner.Secret.(*ServicePrincipalMSISecret); ok { - switch msiSecret.msiType { - case msiTypeAppServiceV20170901: - req.Method = http.MethodGet - req.Header.Set("secret", os.Getenv(msiSecretEnv)) - break - case msiTypeCloudShell: - req.Header.Set("Metadata", "true") - data := url.Values{} - data.Set("resource", spt.inner.Resource) - if spt.inner.ClientID != "" { - data.Set("client_id", spt.inner.ClientID) - } else if msiSecret.clientResourceID != "" { - data.Set("msi_res_id", msiSecret.clientResourceID) - } - req.Body = ioutil.NopCloser(strings.NewReader(data.Encode())) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - break - case msiTypeIMDS: - req.Method = http.MethodGet - req.Header.Set("Metadata", "true") - break - } - logger.Instance.WriteRequest(req, logger.Filter{Body: authBodyFilter}) - resp, err = retryForIMDS(spt.sender, req, spt.MaxMSIRefreshAttempts) - } else { - v := url.Values{} - v.Set("client_id", spt.inner.ClientID) - v.Set("resource", resource) - - if spt.inner.Token.RefreshToken != "" { - v.Set("grant_type", OAuthGrantTypeRefreshToken) - v.Set("refresh_token", spt.inner.Token.RefreshToken) - // web apps must specify client_secret when refreshing tokens - // see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code#refreshing-the-access-tokens - if spt.getGrantType() == OAuthGrantTypeAuthorizationCode { - err := spt.inner.Secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err - } - } - } else { - v.Set("grant_type", spt.getGrantType()) - err := spt.inner.Secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err - } - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - req.Body = body - logger.Instance.WriteRequest(req, logger.Filter{Body: authBodyFilter}) - resp, err = spt.sender.Do(req) - } - - // don't return a TokenRefreshError here; this will allow retry logic to apply - if err != nil { - return fmt.Errorf("adal: Failed to execute the refresh request. Error = '%v'", err) - } else if resp == nil { - return fmt.Errorf("adal: received nil response and error") - } - - logger.Instance.WriteResponse(resp, logger.Filter{Body: authBodyFilter}) - defer resp.Body.Close() - rb, err := ioutil.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusOK { - if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Failed reading response body: %v Endpoint %s", resp.StatusCode, err, req.URL.String()), resp) - } - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Response body: %s Endpoint %s", resp.StatusCode, string(rb), req.URL.String()), resp) - } - - // for the following error cases don't return a TokenRefreshError. the operation succeeded - // but some transient failure happened during deserialization. by returning a generic error - // the retry logic will kick in (we don't retry on TokenRefreshError). - - if err != nil { - return fmt.Errorf("adal: Failed to read a new service principal token during refresh. Error = '%v'", err) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return fmt.Errorf("adal: Empty service principal token received during refresh") - } - token := struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - - // AAD returns expires_in as a string, ADFS returns it as an int - ExpiresIn json.Number `json:"expires_in"` - // expires_on can be in three formats, a UTC time stamp, or the number of seconds as a string *or* int. - ExpiresOn interface{} `json:"expires_on"` - NotBefore json.Number `json:"not_before"` - - Resource string `json:"resource"` - Type string `json:"token_type"` - }{} - // return a TokenRefreshError in the follow error cases as the token is in an unexpected format - err = json.Unmarshal(rb, &token) - if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Failed to unmarshal the service principal token during refresh. Error = '%v' JSON = '%s'", err, string(rb)), resp) - } - expiresOn := json.Number("") - // ADFS doesn't include the expires_on field - if token.ExpiresOn != nil { - if expiresOn, err = parseExpiresOn(token.ExpiresOn); err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: failed to parse expires_on: %v value '%s'", err, token.ExpiresOn), resp) - } - } - spt.inner.Token.AccessToken = token.AccessToken - spt.inner.Token.RefreshToken = token.RefreshToken - spt.inner.Token.ExpiresIn = token.ExpiresIn - spt.inner.Token.ExpiresOn = expiresOn - spt.inner.Token.NotBefore = token.NotBefore - spt.inner.Token.Resource = token.Resource - spt.inner.Token.Type = token.Type - - return spt.InvokeRefreshCallbacks(spt.inner.Token) -} - -// converts expires_on to the number of seconds -func parseExpiresOn(s interface{}) (json.Number, error) { - // the JSON unmarshaler treats JSON numbers unmarshaled into an interface{} as float64 - asFloat64, ok := s.(float64) - if ok { - // this is the number of seconds as int case - return json.Number(strconv.FormatInt(int64(asFloat64), 10)), nil - } - asStr, ok := s.(string) - if !ok { - return "", fmt.Errorf("unexpected expires_on type %T", s) - } - // convert the expiration date to the number of seconds from the unix epoch - timeToDuration := func(t time.Time) json.Number { - return json.Number(strconv.FormatInt(t.UTC().Unix(), 10)) - } - if _, err := json.Number(asStr).Int64(); err == nil { - // this is the number of seconds case, no conversion required - return json.Number(asStr), nil - } else if eo, err := time.Parse(expiresOnDateFormatPM, asStr); err == nil { - return timeToDuration(eo), nil - } else if eo, err := time.Parse(expiresOnDateFormat, asStr); err == nil { - return timeToDuration(eo), nil - } else { - // unknown format - return json.Number(""), err - } -} - -// retry logic specific to retrieving a token from the IMDS endpoint -func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) { - // copied from client.go due to circular dependency - retries := []int{ - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } - // extra retry status codes specific to IMDS - retries = append(retries, - http.StatusNotFound, - http.StatusGone, - // all remaining 5xx - http.StatusNotImplemented, - http.StatusHTTPVersionNotSupported, - http.StatusVariantAlsoNegotiates, - http.StatusInsufficientStorage, - http.StatusLoopDetected, - http.StatusNotExtended, - http.StatusNetworkAuthenticationRequired) - - // see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance - - const maxDelay time.Duration = 60 * time.Second - - attempt := 0 - delay := time.Duration(0) - - // maxAttempts is user-specified, ensure that its value is greater than zero else no request will be made - if maxAttempts < 1 { - maxAttempts = defaultMaxMSIRefreshAttempts - } - - for attempt < maxAttempts { - if resp != nil && resp.Body != nil { - io.Copy(ioutil.Discard, resp.Body) - resp.Body.Close() - } - resp, err = sender.Do(req) - // we want to retry if err is not nil or the status code is in the list of retry codes - if err == nil && !responseHasStatusCode(resp, retries...) { - return - } - - // perform exponential backoff with a cap. - // must increment attempt before calculating delay. - attempt++ - // the base value of 2 is the "delta backoff" as specified in the guidance doc - delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second) - if delay > maxDelay { - delay = maxDelay - } - - select { - case <-time.After(delay): - // intentionally left blank - case <-req.Context().Done(): - err = req.Context().Err() - return - } - } - return -} - -func responseHasStatusCode(resp *http.Response, codes ...int) bool { - if resp != nil { - for _, i := range codes { - if i == resp.StatusCode { - return true - } - } - } - return false -} - -// SetAutoRefresh enables or disables automatic refreshing of stale tokens. -func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool) { - spt.inner.AutoRefresh = autoRefresh -} - -// SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will -// refresh the token. -func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { - spt.inner.RefreshWithin = d - return -} - -// SetSender sets the http.Client used when obtaining the Service Principal token. An -// undecorated http.Client is used by default. -func (spt *ServicePrincipalToken) SetSender(s Sender) { spt.sender = s } - -// OAuthToken implements the OAuthTokenProvider interface. It returns the current access token. -func (spt *ServicePrincipalToken) OAuthToken() string { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.inner.Token.OAuthToken() -} - -// Token returns a copy of the current token. -func (spt *ServicePrincipalToken) Token() Token { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.inner.Token -} - -// MultiTenantServicePrincipalToken contains tokens for multi-tenant authorization. -type MultiTenantServicePrincipalToken struct { - PrimaryToken *ServicePrincipalToken - AuxiliaryTokens []*ServicePrincipalToken -} - -// PrimaryOAuthToken returns the primary authorization token. -func (mt *MultiTenantServicePrincipalToken) PrimaryOAuthToken() string { - return mt.PrimaryToken.OAuthToken() -} - -// AuxiliaryOAuthTokens returns one to three auxiliary authorization tokens. -func (mt *MultiTenantServicePrincipalToken) AuxiliaryOAuthTokens() []string { - tokens := make([]string, len(mt.AuxiliaryTokens)) - for i := range mt.AuxiliaryTokens { - tokens[i] = mt.AuxiliaryTokens[i].OAuthToken() - } - return tokens -} - -// NewMultiTenantServicePrincipalToken creates a new MultiTenantServicePrincipalToken with the specified credentials and resource. -func NewMultiTenantServicePrincipalToken(multiTenantCfg MultiTenantOAuthConfig, clientID string, secret string, resource string) (*MultiTenantServicePrincipalToken, error) { - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(secret, "secret"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - auxTenants := multiTenantCfg.AuxiliaryTenants() - m := MultiTenantServicePrincipalToken{ - AuxiliaryTokens: make([]*ServicePrincipalToken, len(auxTenants)), - } - primary, err := NewServicePrincipalToken(*multiTenantCfg.PrimaryTenant(), clientID, secret, resource) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for primary tenant: %v", err) - } - m.PrimaryToken = primary - for i := range auxTenants { - aux, err := NewServicePrincipalToken(*auxTenants[i], clientID, secret, resource) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for auxiliary tenant: %v", err) - } - m.AuxiliaryTokens[i] = aux - } - return &m, nil -} - -// NewMultiTenantServicePrincipalTokenFromCertificate creates a new MultiTenantServicePrincipalToken with the specified certificate credentials and resource. -func NewMultiTenantServicePrincipalTokenFromCertificate(multiTenantCfg MultiTenantOAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string) (*MultiTenantServicePrincipalToken, error) { - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if certificate == nil { - return nil, fmt.Errorf("parameter 'certificate' cannot be nil") - } - if privateKey == nil { - return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") - } - auxTenants := multiTenantCfg.AuxiliaryTenants() - m := MultiTenantServicePrincipalToken{ - AuxiliaryTokens: make([]*ServicePrincipalToken, len(auxTenants)), - } - primary, err := NewServicePrincipalTokenWithSecret( - *multiTenantCfg.PrimaryTenant(), - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - ) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for primary tenant: %v", err) - } - m.PrimaryToken = primary - for i := range auxTenants { - aux, err := NewServicePrincipalTokenWithSecret( - *auxTenants[i], - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - ) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for auxiliary tenant: %v", err) - } - m.AuxiliaryTokens[i] = aux - } - return &m, nil -} - -// MSIAvailable returns true if the MSI endpoint is available for authentication. -func MSIAvailable(ctx context.Context, s Sender) bool { - msiType, _, err := getMSIType() - - if err != nil { - return false - } - - if msiType != msiTypeIMDS { - return true - } - - if s == nil { - s = sender() - } - - resp, err := getMSIEndpoint(ctx, s) - - if err == nil { - resp.Body.Close() - } - - return err == nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token_1.13.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token_1.13.go deleted file mode 100644 index 89190a421..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token_1.13.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build go1.13 -// +build go1.13 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package adal - -import ( - "context" - "fmt" - "net/http" - "time" -) - -func getMSIEndpoint(ctx context.Context, sender Sender) (*http.Response, error) { - tempCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - defer cancel() - // http.NewRequestWithContext() was added in Go 1.13 - req, _ := http.NewRequestWithContext(tempCtx, http.MethodGet, msiEndpoint, nil) - q := req.URL.Query() - q.Add("api-version", msiAPIVersion) - req.URL.RawQuery = q.Encode() - return sender.Do(req) -} - -// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (mt *MultiTenantServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.EnsureFreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh primary token: %w", err) - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.EnsureFreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh auxiliary token: %w", err) - } - } - return nil -} - -// RefreshWithContext obtains a fresh token for the Service Principal. -func (mt *MultiTenantServicePrincipalToken) RefreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.RefreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh primary token: %w", err) - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh auxiliary token: %w", err) - } - } - return nil -} - -// RefreshExchangeWithContext refreshes the token, but for a different resource. -func (mt *MultiTenantServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { - if err := mt.PrimaryToken.RefreshExchangeWithContext(ctx, resource); err != nil { - return fmt.Errorf("failed to refresh primary token: %w", err) - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshExchangeWithContext(ctx, resource); err != nil { - return fmt.Errorf("failed to refresh auxiliary token: %w", err) - } - } - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token_legacy.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token_legacy.go deleted file mode 100644 index 27ec4efad..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token_legacy.go +++ /dev/null @@ -1,75 +0,0 @@ -//go:build !go1.13 -// +build !go1.13 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package adal - -import ( - "context" - "net/http" - "time" -) - -func getMSIEndpoint(ctx context.Context, sender Sender) (*http.Response, error) { - tempCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - defer cancel() - req, _ := http.NewRequest(http.MethodGet, msiEndpoint, nil) - req = req.WithContext(tempCtx) - q := req.URL.Query() - q.Add("api-version", msiAPIVersion) - req.URL.RawQuery = q.Encode() - return sender.Do(req) -} - -// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (mt *MultiTenantServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.EnsureFreshWithContext(ctx); err != nil { - return err - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.EnsureFreshWithContext(ctx); err != nil { - return err - } - } - return nil -} - -// RefreshWithContext obtains a fresh token for the Service Principal. -func (mt *MultiTenantServicePrincipalToken) RefreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.RefreshWithContext(ctx); err != nil { - return err - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshWithContext(ctx); err != nil { - return err - } - } - return nil -} - -// RefreshExchangeWithContext refreshes the token, but for a different resource. -func (mt *MultiTenantServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { - if err := mt.PrimaryToken.RefreshExchangeWithContext(ctx, resource); err != nil { - return err - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshExchangeWithContext(ctx, resource); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/version.go b/vendor/github.com/Azure/go-autorest/autorest/adal/version.go deleted file mode 100644 index c867b3484..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/version.go +++ /dev/null @@ -1,45 +0,0 @@ -package adal - -import ( - "fmt" - "runtime" -) - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -const number = "v1.0.0" - -var ( - ua = fmt.Sprintf("Go/%s (%s-%s) go-autorest/adal/%s", - runtime.Version(), - runtime.GOARCH, - runtime.GOOS, - number, - ) -) - -// UserAgent returns a string containing the Go version, system architecture and OS, and the adal version. -func UserAgent() string { - return ua -} - -// AddToUserAgent adds an extension to the current user agent -func AddToUserAgent(extension string) error { - if extension != "" { - ua = fmt.Sprintf("%s %s", ua, extension) - return nil - } - return fmt.Errorf("Extension was empty, User Agent remained as '%s'", ua) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization.go b/vendor/github.com/Azure/go-autorest/autorest/authorization.go deleted file mode 100644 index 1226c4111..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization.go +++ /dev/null @@ -1,353 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "crypto/tls" - "encoding/base64" - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/Azure/go-autorest/autorest/adal" -) - -const ( - bearerChallengeHeader = "Www-Authenticate" - bearer = "Bearer" - tenantID = "tenantID" - apiKeyAuthorizerHeader = "Ocp-Apim-Subscription-Key" - bingAPISdkHeader = "X-BingApis-SDK-Client" - golangBingAPISdkHeaderValue = "Go-SDK" - authorization = "Authorization" - basic = "Basic" -) - -// Authorizer is the interface that provides a PrepareDecorator used to supply request -// authorization. Most often, the Authorizer decorator runs last so it has access to the full -// state of the formed HTTP request. -type Authorizer interface { - WithAuthorization() PrepareDecorator -} - -// NullAuthorizer implements a default, "do nothing" Authorizer. -type NullAuthorizer struct{} - -// WithAuthorization returns a PrepareDecorator that does nothing. -func (na NullAuthorizer) WithAuthorization() PrepareDecorator { - return WithNothing() -} - -// APIKeyAuthorizer implements API Key authorization. -type APIKeyAuthorizer struct { - headers map[string]interface{} - queryParameters map[string]interface{} -} - -// NewAPIKeyAuthorizerWithHeaders creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizerWithHeaders(headers map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(headers, nil) -} - -// NewAPIKeyAuthorizerWithQueryParameters creates an ApiKeyAuthorizer with query parameters. -func NewAPIKeyAuthorizerWithQueryParameters(queryParameters map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(nil, queryParameters) -} - -// NewAPIKeyAuthorizer creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer { - return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Parameters. -func (aka *APIKeyAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return DecoratePreparer(p, WithHeaders(aka.headers), WithQueryParameters(aka.queryParameters)) - } -} - -// CognitiveServicesAuthorizer implements authorization for Cognitive Services. -type CognitiveServicesAuthorizer struct { - subscriptionKey string -} - -// NewCognitiveServicesAuthorizer is -func NewCognitiveServicesAuthorizer(subscriptionKey string) *CognitiveServicesAuthorizer { - return &CognitiveServicesAuthorizer{subscriptionKey: subscriptionKey} -} - -// WithAuthorization is -func (csa *CognitiveServicesAuthorizer) WithAuthorization() PrepareDecorator { - headers := make(map[string]interface{}) - headers[apiKeyAuthorizerHeader] = csa.subscriptionKey - headers[bingAPISdkHeader] = golangBingAPISdkHeaderValue - - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// BearerAuthorizer implements the bearer authorization -type BearerAuthorizer struct { - tokenProvider adal.OAuthTokenProvider -} - -// NewBearerAuthorizer crates a BearerAuthorizer using the given token provider -func NewBearerAuthorizer(tp adal.OAuthTokenProvider) *BearerAuthorizer { - return &BearerAuthorizer{tokenProvider: tp} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the token. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (ba *BearerAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - // the ordering is important here, prefer RefresherWithContext if available - if refresher, ok := ba.tokenProvider.(adal.RefresherWithContext); ok { - err = refresher.EnsureFreshWithContext(r.Context()) - } else if refresher, ok := ba.tokenProvider.(adal.Refresher); ok { - err = refresher.EnsureFresh() - } - if err != nil { - var resp *http.Response - if tokError, ok := err.(adal.TokenRefreshError); ok { - resp = tokError.Response() - } - return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", resp, - "Failed to refresh the Token for request to %s", r.URL) - } - return Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", ba.tokenProvider.OAuthToken()))) - } - return r, err - }) - } -} - -// TokenProvider returns OAuthTokenProvider so that it can be used for authorization outside the REST. -func (ba *BearerAuthorizer) TokenProvider() adal.OAuthTokenProvider { - return ba.tokenProvider -} - -// BearerAuthorizerCallbackFunc is the authentication callback signature. -type BearerAuthorizerCallbackFunc func(tenantID, resource string) (*BearerAuthorizer, error) - -// BearerAuthorizerCallback implements bearer authorization via a callback. -type BearerAuthorizerCallback struct { - sender Sender - callback BearerAuthorizerCallbackFunc -} - -// NewBearerAuthorizerCallback creates a bearer authorization callback. The callback -// is invoked when the HTTP request is submitted. -func NewBearerAuthorizerCallback(s Sender, callback BearerAuthorizerCallbackFunc) *BearerAuthorizerCallback { - if s == nil { - s = sender(tls.RenegotiateNever) - } - return &BearerAuthorizerCallback{sender: s, callback: callback} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value -// is "Bearer " followed by the token. The BearerAuthorizer is obtained via a user-supplied callback. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (bacb *BearerAuthorizerCallback) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - // make a copy of the request and remove the body as it's not - // required and avoids us having to create a copy of it. - rCopy := *r - removeRequestBody(&rCopy) - - resp, err := bacb.sender.Do(&rCopy) - if err != nil { - return r, err - } - DrainResponseBody(resp) - if resp.StatusCode == 401 && hasBearerChallenge(resp.Header) { - bc, err := newBearerChallenge(resp.Header) - if err != nil { - return r, err - } - if bacb.callback != nil { - ba, err := bacb.callback(bc.values[tenantID], bc.values["resource"]) - if err != nil { - return r, err - } - return Prepare(r, ba.WithAuthorization()) - } - } - } - return r, err - }) - } -} - -// returns true if the HTTP response contains a bearer challenge -func hasBearerChallenge(header http.Header) bool { - authHeader := header.Get(bearerChallengeHeader) - if len(authHeader) == 0 || strings.Index(authHeader, bearer) < 0 { - return false - } - return true -} - -type bearerChallenge struct { - values map[string]string -} - -func newBearerChallenge(header http.Header) (bc bearerChallenge, err error) { - challenge := strings.TrimSpace(header.Get(bearerChallengeHeader)) - trimmedChallenge := challenge[len(bearer)+1:] - - // challenge is a set of key=value pairs that are comma delimited - pairs := strings.Split(trimmedChallenge, ",") - if len(pairs) < 1 { - err = fmt.Errorf("challenge '%s' contains no pairs", challenge) - return bc, err - } - - bc.values = make(map[string]string) - for i := range pairs { - trimmedPair := strings.TrimSpace(pairs[i]) - pair := strings.Split(trimmedPair, "=") - if len(pair) == 2 { - // remove the enclosing quotes - key := strings.Trim(pair[0], "\"") - value := strings.Trim(pair[1], "\"") - - switch key { - case "authorization", "authorization_uri": - // strip the tenant ID from the authorization URL - asURL, err := url.Parse(value) - if err != nil { - return bc, err - } - bc.values[tenantID] = asURL.Path[1:] - default: - bc.values[key] = value - } - } - } - - return bc, err -} - -// EventGridKeyAuthorizer implements authorization for event grid using key authentication. -type EventGridKeyAuthorizer struct { - topicKey string -} - -// NewEventGridKeyAuthorizer creates a new EventGridKeyAuthorizer -// with the specified topic key. -func NewEventGridKeyAuthorizer(topicKey string) EventGridKeyAuthorizer { - return EventGridKeyAuthorizer{topicKey: topicKey} -} - -// WithAuthorization returns a PrepareDecorator that adds the aeg-sas-key authentication header. -func (egta EventGridKeyAuthorizer) WithAuthorization() PrepareDecorator { - headers := map[string]interface{}{ - "aeg-sas-key": egta.topicKey, - } - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// BasicAuthorizer implements basic HTTP authorization by adding the Authorization HTTP header -// with the value "Basic " where is a base64-encoded username:password tuple. -type BasicAuthorizer struct { - userName string - password string -} - -// NewBasicAuthorizer creates a new BasicAuthorizer with the specified username and password. -func NewBasicAuthorizer(userName, password string) *BasicAuthorizer { - return &BasicAuthorizer{ - userName: userName, - password: password, - } -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Basic " followed by the base64-encoded username:password tuple. -func (ba *BasicAuthorizer) WithAuthorization() PrepareDecorator { - headers := make(map[string]interface{}) - headers[authorization] = basic + " " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", ba.userName, ba.password))) - - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// MultiTenantServicePrincipalTokenAuthorizer provides authentication across tenants. -type MultiTenantServicePrincipalTokenAuthorizer interface { - WithAuthorization() PrepareDecorator -} - -// NewMultiTenantServicePrincipalTokenAuthorizer crates a BearerAuthorizer using the given token provider -func NewMultiTenantServicePrincipalTokenAuthorizer(tp adal.MultitenantOAuthTokenProvider) MultiTenantServicePrincipalTokenAuthorizer { - return NewMultiTenantBearerAuthorizer(tp) -} - -// MultiTenantBearerAuthorizer implements bearer authorization across multiple tenants. -type MultiTenantBearerAuthorizer struct { - tp adal.MultitenantOAuthTokenProvider -} - -// NewMultiTenantBearerAuthorizer creates a MultiTenantBearerAuthorizer using the given token provider. -func NewMultiTenantBearerAuthorizer(tp adal.MultitenantOAuthTokenProvider) *MultiTenantBearerAuthorizer { - return &MultiTenantBearerAuthorizer{tp: tp} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header using the -// primary token along with the auxiliary authorization header using the auxiliary tokens. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (mt *MultiTenantBearerAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - if refresher, ok := mt.tp.(adal.RefresherWithContext); ok { - err = refresher.EnsureFreshWithContext(r.Context()) - if err != nil { - var resp *http.Response - if tokError, ok := err.(adal.TokenRefreshError); ok { - resp = tokError.Response() - } - return r, NewErrorWithError(err, "azure.multiTenantSPTAuthorizer", "WithAuthorization", resp, - "Failed to refresh one or more Tokens for request to %s", r.URL) - } - } - r, err = Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", mt.tp.PrimaryOAuthToken()))) - if err != nil { - return r, err - } - auxTokens := mt.tp.AuxiliaryOAuthTokens() - for i := range auxTokens { - auxTokens[i] = fmt.Sprintf("Bearer %s", auxTokens[i]) - } - return Prepare(r, WithHeader(headerAuxAuthorization, strings.Join(auxTokens, ", "))) - }) - } -} - -// TokenProvider returns the underlying MultitenantOAuthTokenProvider for this authorizer. -func (mt *MultiTenantBearerAuthorizer) TokenProvider() adal.MultitenantOAuthTokenProvider { - return mt.tp -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization_sas.go b/vendor/github.com/Azure/go-autorest/autorest/authorization_sas.go deleted file mode 100644 index 66501493b..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization_sas.go +++ /dev/null @@ -1,66 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" - "strings" -) - -// SASTokenAuthorizer implements an authorization for SAS Token Authentication -// this can be used for interaction with Blob Storage Endpoints -type SASTokenAuthorizer struct { - sasToken string -} - -// NewSASTokenAuthorizer creates a SASTokenAuthorizer using the given credentials -func NewSASTokenAuthorizer(sasToken string) (*SASTokenAuthorizer, error) { - if strings.TrimSpace(sasToken) == "" { - return nil, fmt.Errorf("sasToken cannot be empty") - } - - token := sasToken - if strings.HasPrefix(sasToken, "?") { - token = strings.TrimPrefix(sasToken, "?") - } - - return &SASTokenAuthorizer{ - sasToken: token, - }, nil -} - -// WithAuthorization returns a PrepareDecorator that adds a shared access signature token to the -// URI's query parameters. This can be used for the Blob, Queue, and File Services. -// -// See https://docs.microsoft.com/en-us/rest/api/storageservices/delegate-access-with-shared-access-signature -func (sas *SASTokenAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - - if r.URL.RawQuery == "" { - r.URL.RawQuery = sas.sasToken - } else if !strings.Contains(r.URL.RawQuery, sas.sasToken) { - r.URL.RawQuery = fmt.Sprintf("%s&%s", r.URL.RawQuery, sas.sasToken) - } - - return Prepare(r) - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization_storage.go b/vendor/github.com/Azure/go-autorest/autorest/authorization_storage.go deleted file mode 100644 index 2af5030a1..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization_storage.go +++ /dev/null @@ -1,307 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "fmt" - "net/http" - "net/url" - "sort" - "strings" - "time" -) - -// SharedKeyType defines the enumeration for the various shared key types. -// See https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key for details on the shared key types. -type SharedKeyType string - -const ( - // SharedKey is used to authorize against blobs, files and queues services. - SharedKey SharedKeyType = "sharedKey" - - // SharedKeyForTable is used to authorize against the table service. - SharedKeyForTable SharedKeyType = "sharedKeyTable" - - // SharedKeyLite is used to authorize against blobs, files and queues services. It's provided for - // backwards compatibility with API versions before 2009-09-19. Prefer SharedKey instead. - SharedKeyLite SharedKeyType = "sharedKeyLite" - - // SharedKeyLiteForTable is used to authorize against the table service. It's provided for - // backwards compatibility with older table API versions. Prefer SharedKeyForTable instead. - SharedKeyLiteForTable SharedKeyType = "sharedKeyLiteTable" -) - -const ( - headerAccept = "Accept" - headerAcceptCharset = "Accept-Charset" - headerContentEncoding = "Content-Encoding" - headerContentLength = "Content-Length" - headerContentMD5 = "Content-MD5" - headerContentLanguage = "Content-Language" - headerIfModifiedSince = "If-Modified-Since" - headerIfMatch = "If-Match" - headerIfNoneMatch = "If-None-Match" - headerIfUnmodifiedSince = "If-Unmodified-Since" - headerDate = "Date" - headerXMSDate = "X-Ms-Date" - headerXMSVersion = "x-ms-version" - headerRange = "Range" -) - -const storageEmulatorAccountName = "devstoreaccount1" - -// SharedKeyAuthorizer implements an authorization for Shared Key -// this can be used for interaction with Blob, File and Queue Storage Endpoints -type SharedKeyAuthorizer struct { - accountName string - accountKey []byte - keyType SharedKeyType -} - -// NewSharedKeyAuthorizer creates a SharedKeyAuthorizer using the provided credentials and shared key type. -func NewSharedKeyAuthorizer(accountName, accountKey string, keyType SharedKeyType) (*SharedKeyAuthorizer, error) { - key, err := base64.StdEncoding.DecodeString(accountKey) - if err != nil { - return nil, fmt.Errorf("malformed storage account key: %v", err) - } - return &SharedKeyAuthorizer{ - accountName: accountName, - accountKey: key, - keyType: keyType, - }, nil -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is " " followed by the computed key. -// This can be used for the Blob, Queue, and File Services -// -// from: https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key -// You may use Shared Key authorization to authorize a request made against the -// 2009-09-19 version and later of the Blob and Queue services, -// and version 2014-02-14 and later of the File services. -func (sk *SharedKeyAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - - sk, err := buildSharedKey(sk.accountName, sk.accountKey, r, sk.keyType) - if err != nil { - return r, err - } - return Prepare(r, WithHeader(headerAuthorization, sk)) - }) - } -} - -func buildSharedKey(accName string, accKey []byte, req *http.Request, keyType SharedKeyType) (string, error) { - canRes, err := buildCanonicalizedResource(accName, req.URL.String(), keyType) - if err != nil { - return "", err - } - - if req.Header == nil { - req.Header = http.Header{} - } - - // ensure date is set - if req.Header.Get(headerDate) == "" && req.Header.Get(headerXMSDate) == "" { - date := time.Now().UTC().Format(http.TimeFormat) - req.Header.Set(headerXMSDate, date) - } - canString, err := buildCanonicalizedString(req.Method, req.Header, canRes, keyType) - if err != nil { - return "", err - } - return createAuthorizationHeader(accName, accKey, canString, keyType), nil -} - -func buildCanonicalizedResource(accountName, uri string, keyType SharedKeyType) (string, error) { - errMsg := "buildCanonicalizedResource error: %s" - u, err := url.Parse(uri) - if err != nil { - return "", fmt.Errorf(errMsg, err.Error()) - } - - cr := bytes.NewBufferString("") - if accountName != storageEmulatorAccountName { - cr.WriteString("/") - cr.WriteString(getCanonicalizedAccountName(accountName)) - } - - if len(u.Path) > 0 { - // Any portion of the CanonicalizedResource string that is derived from - // the resource's URI should be encoded exactly as it is in the URI. - // -- https://msdn.microsoft.com/en-gb/library/azure/dd179428.aspx - cr.WriteString(u.EscapedPath()) - } else { - // a slash is required to indicate the root path - cr.WriteString("/") - } - - params, err := url.ParseQuery(u.RawQuery) - if err != nil { - return "", fmt.Errorf(errMsg, err.Error()) - } - - // See https://github.com/Azure/azure-storage-net/blob/master/Lib/Common/Core/Util/AuthenticationUtility.cs#L277 - if keyType == SharedKey { - if len(params) > 0 { - cr.WriteString("\n") - - keys := []string{} - for key := range params { - keys = append(keys, key) - } - sort.Strings(keys) - - completeParams := []string{} - for _, key := range keys { - if len(params[key]) > 1 { - sort.Strings(params[key]) - } - - completeParams = append(completeParams, fmt.Sprintf("%s:%s", key, strings.Join(params[key], ","))) - } - cr.WriteString(strings.Join(completeParams, "\n")) - } - } else { - // search for "comp" parameter, if exists then add it to canonicalizedresource - if v, ok := params["comp"]; ok { - cr.WriteString("?comp=" + v[0]) - } - } - - return string(cr.Bytes()), nil -} - -func getCanonicalizedAccountName(accountName string) string { - // since we may be trying to access a secondary storage account, we need to - // remove the -secondary part of the storage name - return strings.TrimSuffix(accountName, "-secondary") -} - -func buildCanonicalizedString(verb string, headers http.Header, canonicalizedResource string, keyType SharedKeyType) (string, error) { - contentLength := headers.Get(headerContentLength) - if contentLength == "0" { - contentLength = "" - } - date := headers.Get(headerDate) - if v := headers.Get(headerXMSDate); v != "" { - if keyType == SharedKey || keyType == SharedKeyLite { - date = "" - } else { - date = v - } - } - var canString string - switch keyType { - case SharedKey: - canString = strings.Join([]string{ - verb, - headers.Get(headerContentEncoding), - headers.Get(headerContentLanguage), - contentLength, - headers.Get(headerContentMD5), - headers.Get(headerContentType), - date, - headers.Get(headerIfModifiedSince), - headers.Get(headerIfMatch), - headers.Get(headerIfNoneMatch), - headers.Get(headerIfUnmodifiedSince), - headers.Get(headerRange), - buildCanonicalizedHeader(headers), - canonicalizedResource, - }, "\n") - case SharedKeyForTable: - canString = strings.Join([]string{ - verb, - headers.Get(headerContentMD5), - headers.Get(headerContentType), - date, - canonicalizedResource, - }, "\n") - case SharedKeyLite: - canString = strings.Join([]string{ - verb, - headers.Get(headerContentMD5), - headers.Get(headerContentType), - date, - buildCanonicalizedHeader(headers), - canonicalizedResource, - }, "\n") - case SharedKeyLiteForTable: - canString = strings.Join([]string{ - date, - canonicalizedResource, - }, "\n") - default: - return "", fmt.Errorf("key type '%s' is not supported", keyType) - } - return canString, nil -} - -func buildCanonicalizedHeader(headers http.Header) string { - cm := make(map[string]string) - - for k := range headers { - headerName := strings.TrimSpace(strings.ToLower(k)) - if strings.HasPrefix(headerName, "x-ms-") { - cm[headerName] = headers.Get(k) - } - } - - if len(cm) == 0 { - return "" - } - - keys := []string{} - for key := range cm { - keys = append(keys, key) - } - - sort.Strings(keys) - - ch := bytes.NewBufferString("") - - for _, key := range keys { - ch.WriteString(key) - ch.WriteRune(':') - ch.WriteString(cm[key]) - ch.WriteRune('\n') - } - - return strings.TrimSuffix(string(ch.Bytes()), "\n") -} - -func createAuthorizationHeader(accountName string, accountKey []byte, canonicalizedString string, keyType SharedKeyType) string { - h := hmac.New(sha256.New, accountKey) - h.Write([]byte(canonicalizedString)) - signature := base64.StdEncoding.EncodeToString(h.Sum(nil)) - var key string - switch keyType { - case SharedKey, SharedKeyForTable: - key = "SharedKey" - case SharedKeyLite, SharedKeyLiteForTable: - key = "SharedKeyLite" - } - return fmt.Sprintf("%s %s:%s", key, getCanonicalizedAccountName(accountName), signature) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go deleted file mode 100644 index aafdf021f..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Package autorest implements an HTTP request pipeline suitable for use across multiple go-routines -and provides the shared routines relied on by AutoRest (see https://github.com/Azure/autorest/) -generated Go code. - -The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, -and Responding. A typical pattern is: - - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) - - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) - - err = Respond(resp, - ByDiscardingBody(), - ByClosing()) - -Each phase relies on decorators to modify and / or manage processing. Decorators may first modify -and then pass the data along, pass the data first and then modify the result, or wrap themselves -around passing the data (such as a logger might do). Decorators run in the order provided. For -example, the following: - - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) - -will set the URL to: - - https://microsoft.com/a/b/c - -Preparers and Responders may be shared and re-used (assuming the underlying decorators support -sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders -shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, -all bound together by means of input / output channels. - -Decorators hold their passed state within a closure (such as the path components in the example -above). Be careful to share Preparers and Responders only in a context where such held state -applies. For example, it may not make sense to share a Preparer that applies a query string from a -fixed set of values. Similarly, sharing a Responder that reads the response body into a passed -struct (e.g., ByUnmarshallingJson) is likely incorrect. - -Lastly, the Swagger specification (https://swagger.io) that drives AutoRest -(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The -github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure -correct parsing and formatting. - -Errors raised by autorest objects and methods will conform to the autorest.Error interface. - -See the included examples for more detail. For details on the suggested use of this package by -generated clients, see the Client described below. -*/ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "net/http" - "time" -) - -const ( - // HeaderLocation specifies the HTTP Location header. - HeaderLocation = "Location" - - // HeaderRetryAfter specifies the HTTP Retry-After header. - HeaderRetryAfter = "Retry-After" -) - -// ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set -// and false otherwise. -func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { - if resp == nil { - return false - } - return containsInt(codes, resp.StatusCode) -} - -// GetLocation retrieves the URL from the Location header of the passed response. -func GetLocation(resp *http.Response) string { - return resp.Header.Get(HeaderLocation) -} - -// GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If -// the header is absent or is malformed, it will return the supplied default delay time.Duration. -func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { - retry := resp.Header.Get(HeaderRetryAfter) - if retry == "" { - return defaultDelay - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - return defaultDelay - } - - return d -} - -// NewPollingRequest allocates and returns a new http.Request to poll for the passed response. -func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare(&http.Request{Cancel: cancel}, - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} - -// NewPollingRequestWithContext allocates and returns a new http.Request with the specified context to poll for the passed response. -func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare((&http.Request{}).WithContext(ctx), - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go deleted file mode 100644 index 45575eedb..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ /dev/null @@ -1,995 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/logger" - "github.com/Azure/go-autorest/tracing" -) - -const ( - headerAsyncOperation = "Azure-AsyncOperation" -) - -const ( - operationInProgress string = "InProgress" - operationCanceled string = "Canceled" - operationFailed string = "Failed" - operationSucceeded string = "Succeeded" -) - -var pollingCodes = [...]int{http.StatusNoContent, http.StatusAccepted, http.StatusCreated, http.StatusOK} - -// FutureAPI contains the set of methods on the Future type. -type FutureAPI interface { - // Response returns the last HTTP response. - Response() *http.Response - - // Status returns the last status message of the operation. - Status() string - - // PollingMethod returns the method used to monitor the status of the asynchronous operation. - PollingMethod() PollingMethodType - - // DoneWithContext queries the service to see if the operation has completed. - DoneWithContext(context.Context, autorest.Sender) (bool, error) - - // GetPollingDelay returns a duration the application should wait before checking - // the status of the asynchronous request and true; this value is returned from - // the service via the Retry-After response header. If the header wasn't returned - // then the function returns the zero-value time.Duration and false. - GetPollingDelay() (time.Duration, bool) - - // WaitForCompletionRef will return when one of the following conditions is met: the long - // running operation has completed, the provided context is cancelled, or the client's - // polling duration has been exceeded. It will retry failed polling attempts based on - // the retry value defined in the client up to the maximum retry attempts. - // If no deadline is specified in the context then the client.PollingDuration will be - // used to determine if a default deadline should be used. - // If PollingDuration is greater than zero the value will be used as the context's timeout. - // If PollingDuration is zero then no default deadline will be used. - WaitForCompletionRef(context.Context, autorest.Client) error - - // MarshalJSON implements the json.Marshaler interface. - MarshalJSON() ([]byte, error) - - // MarshalJSON implements the json.Unmarshaler interface. - UnmarshalJSON([]byte) error - - // PollingURL returns the URL used for retrieving the status of the long-running operation. - PollingURL() string - - // GetResult should be called once polling has completed successfully. - // It makes the final GET call to retrieve the resultant payload. - GetResult(autorest.Sender) (*http.Response, error) -} - -var _ FutureAPI = (*Future)(nil) - -// Future provides a mechanism to access the status and results of an asynchronous request. -// Since futures are stateful they should be passed by value to avoid race conditions. -type Future struct { - pt pollingTracker -} - -// NewFutureFromResponse returns a new Future object initialized -// with the initial response from an asynchronous operation. -func NewFutureFromResponse(resp *http.Response) (Future, error) { - pt, err := createPollingTracker(resp) - return Future{pt: pt}, err -} - -// Response returns the last HTTP response. -func (f Future) Response() *http.Response { - if f.pt == nil { - return nil - } - return f.pt.latestResponse() -} - -// Status returns the last status message of the operation. -func (f Future) Status() string { - if f.pt == nil { - return "" - } - return f.pt.pollingStatus() -} - -// PollingMethod returns the method used to monitor the status of the asynchronous operation. -func (f Future) PollingMethod() PollingMethodType { - if f.pt == nil { - return PollingUnknown - } - return f.pt.pollingMethod() -} - -// DoneWithContext queries the service to see if the operation has completed. -func (f *Future) DoneWithContext(ctx context.Context, sender autorest.Sender) (done bool, err error) { - ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.DoneWithContext") - defer func() { - sc := -1 - resp := f.Response() - if resp != nil { - sc = resp.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - - if f.pt == nil { - return false, autorest.NewError("Future", "Done", "future is not initialized") - } - if f.pt.hasTerminated() { - return true, f.pt.pollingError() - } - if err := f.pt.pollForStatus(ctx, sender); err != nil { - return false, err - } - if err := f.pt.checkForErrors(); err != nil { - return f.pt.hasTerminated(), err - } - if err := f.pt.updatePollingState(f.pt.provisioningStateApplicable()); err != nil { - return false, err - } - if err := f.pt.initPollingMethod(); err != nil { - return false, err - } - if err := f.pt.updatePollingMethod(); err != nil { - return false, err - } - return f.pt.hasTerminated(), f.pt.pollingError() -} - -// GetPollingDelay returns a duration the application should wait before checking -// the status of the asynchronous request and true; this value is returned from -// the service via the Retry-After response header. If the header wasn't returned -// then the function returns the zero-value time.Duration and false. -func (f Future) GetPollingDelay() (time.Duration, bool) { - if f.pt == nil { - return 0, false - } - resp := f.pt.latestResponse() - if resp == nil { - return 0, false - } - - retry := resp.Header.Get(autorest.HeaderRetryAfter) - if retry == "" { - return 0, false - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - panic(err) - } - - return d, true -} - -// WaitForCompletionRef will return when one of the following conditions is met: the long -// running operation has completed, the provided context is cancelled, or the client's -// polling duration has been exceeded. It will retry failed polling attempts based on -// the retry value defined in the client up to the maximum retry attempts. -// If no deadline is specified in the context then the client.PollingDuration will be -// used to determine if a default deadline should be used. -// If PollingDuration is greater than zero the value will be used as the context's timeout. -// If PollingDuration is zero then no default deadline will be used. -func (f *Future) WaitForCompletionRef(ctx context.Context, client autorest.Client) (err error) { - ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.WaitForCompletionRef") - defer func() { - sc := -1 - resp := f.Response() - if resp != nil { - sc = resp.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - cancelCtx := ctx - // if the provided context already has a deadline don't override it - _, hasDeadline := ctx.Deadline() - if d := client.PollingDuration; !hasDeadline && d != 0 { - var cancel context.CancelFunc - cancelCtx, cancel = context.WithTimeout(ctx, d) - defer cancel() - } - // if the initial response has a Retry-After, sleep for the specified amount of time before starting to poll - if delay, ok := f.GetPollingDelay(); ok { - logger.Instance.Writeln(logger.LogInfo, "WaitForCompletionRef: initial polling delay") - if delayElapsed := autorest.DelayForBackoff(delay, 0, cancelCtx.Done()); !delayElapsed { - err = cancelCtx.Err() - return - } - } - done, err := f.DoneWithContext(ctx, client) - for attempts := 0; !done; done, err = f.DoneWithContext(ctx, client) { - if attempts >= client.RetryAttempts { - return autorest.NewErrorWithError(err, "Future", "WaitForCompletion", f.pt.latestResponse(), "the number of retries has been exceeded") - } - // we want delayAttempt to be zero in the non-error case so - // that DelayForBackoff doesn't perform exponential back-off - var delayAttempt int - var delay time.Duration - if err == nil { - // check for Retry-After delay, if not present use the client's polling delay - var ok bool - delay, ok = f.GetPollingDelay() - if !ok { - logger.Instance.Writeln(logger.LogInfo, "WaitForCompletionRef: Using client polling delay") - delay = client.PollingDelay - } - } else { - // there was an error polling for status so perform exponential - // back-off based on the number of attempts using the client's retry - // duration. update attempts after delayAttempt to avoid off-by-one. - logger.Instance.Writef(logger.LogError, "WaitForCompletionRef: %s\n", err) - delayAttempt = attempts - delay = client.RetryDuration - attempts++ - } - // wait until the delay elapses or the context is cancelled - delayElapsed := autorest.DelayForBackoff(delay, delayAttempt, cancelCtx.Done()) - if !delayElapsed { - return autorest.NewErrorWithError(cancelCtx.Err(), "Future", "WaitForCompletion", f.pt.latestResponse(), "context has been cancelled") - } - } - return -} - -// MarshalJSON implements the json.Marshaler interface. -func (f Future) MarshalJSON() ([]byte, error) { - return json.Marshal(f.pt) -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (f *Future) UnmarshalJSON(data []byte) error { - // unmarshal into JSON object to determine the tracker type - obj := map[string]interface{}{} - err := json.Unmarshal(data, &obj) - if err != nil { - return err - } - if obj["method"] == nil { - return autorest.NewError("Future", "UnmarshalJSON", "missing 'method' property") - } - method := obj["method"].(string) - switch strings.ToUpper(method) { - case http.MethodDelete: - f.pt = &pollingTrackerDelete{} - case http.MethodPatch: - f.pt = &pollingTrackerPatch{} - case http.MethodPost: - f.pt = &pollingTrackerPost{} - case http.MethodPut: - f.pt = &pollingTrackerPut{} - default: - return autorest.NewError("Future", "UnmarshalJSON", "unsupoorted method '%s'", method) - } - // now unmarshal into the tracker - return json.Unmarshal(data, &f.pt) -} - -// PollingURL returns the URL used for retrieving the status of the long-running operation. -func (f Future) PollingURL() string { - if f.pt == nil { - return "" - } - return f.pt.pollingURL() -} - -// GetResult should be called once polling has completed successfully. -// It makes the final GET call to retrieve the resultant payload. -func (f Future) GetResult(sender autorest.Sender) (*http.Response, error) { - if f.pt.finalGetURL() == "" { - // we can end up in this situation if the async operation returns a 200 - // with no polling URLs. in that case return the response which should - // contain the JSON payload (only do this for successful terminal cases). - if lr := f.pt.latestResponse(); lr != nil && f.pt.hasSucceeded() { - return lr, nil - } - return nil, autorest.NewError("Future", "GetResult", "missing URL for retrieving result") - } - req, err := http.NewRequest(http.MethodGet, f.pt.finalGetURL(), nil) - if err != nil { - return nil, err - } - resp, err := sender.Do(req) - if err == nil && resp.Body != nil { - // copy the body and close it so callers don't have to - defer resp.Body.Close() - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return resp, err - } - resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - return resp, err -} - -type pollingTracker interface { - // these methods can differ per tracker - - // checks the response headers and status code to determine the polling mechanism - updatePollingMethod() error - - // checks the response for tracker-specific error conditions - checkForErrors() error - - // returns true if provisioning state should be checked - provisioningStateApplicable() bool - - // methods common to all trackers - - // initializes a tracker's polling URL and method, called for each iteration. - // these values can be overridden by each polling tracker as required. - initPollingMethod() error - - // initializes the tracker's internal state, call this when the tracker is created - initializeState() error - - // makes an HTTP request to check the status of the LRO - pollForStatus(ctx context.Context, sender autorest.Sender) error - - // updates internal tracker state, call this after each call to pollForStatus - updatePollingState(provStateApl bool) error - - // returns the error response from the service, can be nil - pollingError() error - - // returns the polling method being used - pollingMethod() PollingMethodType - - // returns the state of the LRO as returned from the service - pollingStatus() string - - // returns the URL used for polling status - pollingURL() string - - // returns the URL used for the final GET to retrieve the resource - finalGetURL() string - - // returns true if the LRO is in a terminal state - hasTerminated() bool - - // returns true if the LRO is in a failed terminal state - hasFailed() bool - - // returns true if the LRO is in a successful terminal state - hasSucceeded() bool - - // returns the cached HTTP response after a call to pollForStatus(), can be nil - latestResponse() *http.Response -} - -type pollingTrackerBase struct { - // resp is the last response, either from the submission of the LRO or from polling - resp *http.Response - - // method is the HTTP verb, this is needed for deserialization - Method string `json:"method"` - - // rawBody is the raw JSON response body - rawBody map[string]interface{} - - // denotes if polling is using async-operation or location header - Pm PollingMethodType `json:"pollingMethod"` - - // the URL to poll for status - URI string `json:"pollingURI"` - - // the state of the LRO as returned from the service - State string `json:"lroState"` - - // the URL to GET for the final result - FinalGetURI string `json:"resultURI"` - - // used to hold an error object returned from the service - Err *ServiceError `json:"error,omitempty"` -} - -func (pt *pollingTrackerBase) initializeState() error { - // determine the initial polling state based on response body and/or HTTP status - // code. this is applicable to the initial LRO response, not polling responses! - pt.Method = pt.resp.Request.Method - if err := pt.updateRawBody(); err != nil { - return err - } - switch pt.resp.StatusCode { - case http.StatusOK: - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - if pt.hasFailed() { - pt.updateErrorFromResponse() - return pt.pollingError() - } - } else { - pt.State = operationSucceeded - } - case http.StatusCreated: - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - } else { - pt.State = operationInProgress - } - case http.StatusAccepted: - pt.State = operationInProgress - case http.StatusNoContent: - pt.State = operationSucceeded - default: - pt.State = operationFailed - pt.updateErrorFromResponse() - return pt.pollingError() - } - return pt.initPollingMethod() -} - -func (pt pollingTrackerBase) getProvisioningState() *string { - if pt.rawBody != nil && pt.rawBody["properties"] != nil { - p := pt.rawBody["properties"].(map[string]interface{}) - if ps := p["provisioningState"]; ps != nil { - s := ps.(string) - return &s - } - } - return nil -} - -func (pt *pollingTrackerBase) updateRawBody() error { - pt.rawBody = map[string]interface{}{} - if pt.resp.ContentLength != 0 { - defer pt.resp.Body.Close() - b, err := ioutil.ReadAll(pt.resp.Body) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "updateRawBody", nil, "failed to read response body") - } - // put the body back so it's available to other callers - pt.resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - // observed in 204 responses over HTTP/2.0; the content length is -1 but body is empty - if len(b) == 0 { - return nil - } - if err = json.Unmarshal(b, &pt.rawBody); err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "updateRawBody", nil, "failed to unmarshal response body") - } - } - return nil -} - -func (pt *pollingTrackerBase) pollForStatus(ctx context.Context, sender autorest.Sender) error { - req, err := http.NewRequest(http.MethodGet, pt.URI, nil) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed to create HTTP request") - } - - req = req.WithContext(ctx) - preparer := autorest.CreatePreparer(autorest.GetPrepareDecorators(ctx)...) - req, err = preparer.Prepare(req) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed preparing HTTP request") - } - pt.resp, err = sender.Do(req) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed to send HTTP request") - } - if autorest.ResponseHasStatusCode(pt.resp, pollingCodes[:]...) { - // reset the service error on success case - pt.Err = nil - err = pt.updateRawBody() - } else { - // check response body for error content - pt.updateErrorFromResponse() - err = pt.pollingError() - } - return err -} - -// attempts to unmarshal a ServiceError type from the response body. -// if that fails then make a best attempt at creating something meaningful. -// NOTE: this assumes that the async operation has failed. -func (pt *pollingTrackerBase) updateErrorFromResponse() { - var err error - if pt.resp.ContentLength != 0 { - type respErr struct { - ServiceError *ServiceError `json:"error"` - } - re := respErr{} - defer pt.resp.Body.Close() - var b []byte - if b, err = ioutil.ReadAll(pt.resp.Body); err != nil { - goto Default - } - // put the body back so it's available to other callers - pt.resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - if len(b) == 0 { - goto Default - } - if err = json.Unmarshal(b, &re); err != nil { - goto Default - } - // unmarshalling the error didn't yield anything, try unwrapped error - if re.ServiceError == nil { - err = json.Unmarshal(b, &re.ServiceError) - if err != nil { - goto Default - } - } - // the unmarshaller will ensure re.ServiceError is non-nil - // even if there was no content unmarshalled so check the code. - if re.ServiceError.Code != "" { - pt.Err = re.ServiceError - return - } - } -Default: - se := &ServiceError{ - Code: pt.pollingStatus(), - Message: "The async operation failed.", - } - if err != nil { - se.InnerError = make(map[string]interface{}) - se.InnerError["unmarshalError"] = err.Error() - } - // stick the response body into the error object in hopes - // it contains something useful to help diagnose the failure. - if len(pt.rawBody) > 0 { - se.AdditionalInfo = []map[string]interface{}{ - pt.rawBody, - } - } - pt.Err = se -} - -func (pt *pollingTrackerBase) updatePollingState(provStateApl bool) error { - if pt.Pm == PollingAsyncOperation && pt.rawBody["status"] != nil { - pt.State = pt.rawBody["status"].(string) - } else { - if pt.resp.StatusCode == http.StatusAccepted { - pt.State = operationInProgress - } else if provStateApl { - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - } else { - pt.State = operationSucceeded - } - } else { - return autorest.NewError("pollingTrackerBase", "updatePollingState", "the response from the async operation has an invalid status code") - } - } - // if the operation has failed update the error state - if pt.hasFailed() { - pt.updateErrorFromResponse() - } - return nil -} - -func (pt pollingTrackerBase) pollingError() error { - if pt.Err == nil { - return nil - } - return pt.Err -} - -func (pt pollingTrackerBase) pollingMethod() PollingMethodType { - return pt.Pm -} - -func (pt pollingTrackerBase) pollingStatus() string { - return pt.State -} - -func (pt pollingTrackerBase) pollingURL() string { - return pt.URI -} - -func (pt pollingTrackerBase) finalGetURL() string { - return pt.FinalGetURI -} - -func (pt pollingTrackerBase) hasTerminated() bool { - return strings.EqualFold(pt.State, operationCanceled) || strings.EqualFold(pt.State, operationFailed) || strings.EqualFold(pt.State, operationSucceeded) -} - -func (pt pollingTrackerBase) hasFailed() bool { - return strings.EqualFold(pt.State, operationCanceled) || strings.EqualFold(pt.State, operationFailed) -} - -func (pt pollingTrackerBase) hasSucceeded() bool { - return strings.EqualFold(pt.State, operationSucceeded) -} - -func (pt pollingTrackerBase) latestResponse() *http.Response { - return pt.resp -} - -// error checking common to all trackers -func (pt pollingTrackerBase) baseCheckForErrors() error { - // for Azure-AsyncOperations the response body cannot be nil or empty - if pt.Pm == PollingAsyncOperation { - if pt.resp.Body == nil || pt.resp.ContentLength == 0 { - return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "for Azure-AsyncOperation response body cannot be nil") - } - if pt.rawBody["status"] == nil { - return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "missing status property in Azure-AsyncOperation response body") - } - } - return nil -} - -// default initialization of polling URL/method. each verb tracker will update this as required. -func (pt *pollingTrackerBase) initPollingMethod() error { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - return nil - } - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh != "" { - pt.URI = lh - pt.Pm = PollingLocation - return nil - } - // it's ok if we didn't find a polling header, this will be handled elsewhere - return nil -} - -// DELETE - -type pollingTrackerDelete struct { - pollingTrackerBase -} - -func (pt *pollingTrackerDelete) updatePollingMethod() error { - // for 201 the Location header is required - if pt.resp.StatusCode == http.StatusCreated { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerDelete", "updateHeaders", "missing Location header in 201 response") - } else { - pt.URI = lh - } - pt.Pm = PollingLocation - pt.FinalGetURI = pt.URI - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerDelete) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerDelete) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusNoContent -} - -// PATCH - -type pollingTrackerPatch struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPatch) updatePollingMethod() error { - // by default we can use the original URL for polling and final GET - if pt.URI == "" { - pt.URI = pt.resp.Request.URL.String() - } - if pt.FinalGetURI == "" { - pt.FinalGetURI = pt.resp.Request.URL.String() - } - if pt.Pm == PollingUnknown { - pt.Pm = PollingRequestURI - } - // for 201 it's permissible for no headers to be returned - if pt.resp.StatusCode == http.StatusCreated { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - // note the absence of the "final GET" mechanism for PATCH - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - if ao == "" { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerPatch", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } else { - pt.URI = lh - pt.Pm = PollingLocation - } - } - } - return nil -} - -func (pt pollingTrackerPatch) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerPatch) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusCreated -} - -// POST - -type pollingTrackerPost struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPost) updatePollingMethod() error { - // 201 requires Location header - if pt.resp.StatusCode == http.StatusCreated { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "missing Location header in 201 response") - } else { - pt.URI = lh - pt.FinalGetURI = lh - pt.Pm = PollingLocation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerPost) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerPost) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusNoContent -} - -// PUT - -type pollingTrackerPut struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPut) updatePollingMethod() error { - // by default we can use the original URL for polling and final GET - if pt.URI == "" { - pt.URI = pt.resp.Request.URL.String() - } - if pt.FinalGetURI == "" { - pt.FinalGetURI = pt.resp.Request.URL.String() - } - if pt.Pm == PollingUnknown { - pt.Pm = PollingRequestURI - } - // for 201 it's permissible for no headers to be returned - if pt.resp.StatusCode == http.StatusCreated { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPut", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerPut) checkForErrors() error { - err := pt.baseCheckForErrors() - if err != nil { - return err - } - // if there are no LRO headers then the body cannot be empty - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } - lh, err := getURLFromLocationHeader(pt.resp) - if err != nil { - return err - } - if ao == "" && lh == "" && len(pt.rawBody) == 0 { - return autorest.NewError("pollingTrackerPut", "checkForErrors", "the response did not contain a body") - } - return nil -} - -func (pt pollingTrackerPut) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusCreated -} - -// creates a polling tracker based on the verb of the original request -func createPollingTracker(resp *http.Response) (pollingTracker, error) { - var pt pollingTracker - switch strings.ToUpper(resp.Request.Method) { - case http.MethodDelete: - pt = &pollingTrackerDelete{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPatch: - pt = &pollingTrackerPatch{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPost: - pt = &pollingTrackerPost{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPut: - pt = &pollingTrackerPut{pollingTrackerBase: pollingTrackerBase{resp: resp}} - default: - return nil, autorest.NewError("azure", "createPollingTracker", "unsupported HTTP method %s", resp.Request.Method) - } - if err := pt.initializeState(); err != nil { - return pt, err - } - // this initializes the polling header values, we do this during creation in case the - // initial response send us invalid values; this way the API call will return a non-nil - // error (not doing this means the error shows up in Future.Done) - return pt, pt.updatePollingMethod() -} - -// gets the polling URL from the Azure-AsyncOperation header. -// ensures the URL is well-formed and absolute. -func getURLFromAsyncOpHeader(resp *http.Response) (string, error) { - s := resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) - if s == "" { - return "", nil - } - if !isValidURL(s) { - return "", autorest.NewError("azure", "getURLFromAsyncOpHeader", "invalid polling URL '%s'", s) - } - return s, nil -} - -// gets the polling URL from the Location header. -// ensures the URL is well-formed and absolute. -func getURLFromLocationHeader(resp *http.Response) (string, error) { - s := resp.Header.Get(http.CanonicalHeaderKey(autorest.HeaderLocation)) - if s == "" { - return "", nil - } - if !isValidURL(s) { - return "", autorest.NewError("azure", "getURLFromLocationHeader", "invalid polling URL '%s'", s) - } - return s, nil -} - -// verify that the URL is valid and absolute -func isValidURL(s string) bool { - u, err := url.Parse(s) - return err == nil && u.IsAbs() -} - -// PollingMethodType defines a type used for enumerating polling mechanisms. -type PollingMethodType string - -const ( - // PollingAsyncOperation indicates the polling method uses the Azure-AsyncOperation header. - PollingAsyncOperation PollingMethodType = "AsyncOperation" - - // PollingLocation indicates the polling method uses the Location header. - PollingLocation PollingMethodType = "Location" - - // PollingRequestURI indicates the polling method uses the original request URI. - PollingRequestURI PollingMethodType = "RequestURI" - - // PollingUnknown indicates an unknown polling method and is the default value. - PollingUnknown PollingMethodType = "" -) - -// AsyncOpIncompleteError is the type that's returned from a future that has not completed. -type AsyncOpIncompleteError struct { - // FutureType is the name of the type composed of a azure.Future. - FutureType string -} - -// Error returns an error message including the originating type name of the error. -func (e AsyncOpIncompleteError) Error() string { - return fmt.Sprintf("%s: asynchronous operation has not completed", e.FutureType) -} - -// NewAsyncOpIncompleteError creates a new AsyncOpIncompleteError with the specified parameters. -func NewAsyncOpIncompleteError(futureType string) AsyncOpIncompleteError { - return AsyncOpIncompleteError{ - FutureType: futureType, - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go deleted file mode 100644 index 1328f1764..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go +++ /dev/null @@ -1,388 +0,0 @@ -// Package azure provides Azure-specific implementations used with AutoRest. -// See the included examples for more detail. -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -const ( - // HeaderClientID is the Azure extension header to set a user-specified request ID. - HeaderClientID = "x-ms-client-request-id" - - // HeaderReturnClientID is the Azure extension header to set if the user-specified request ID - // should be included in the response. - HeaderReturnClientID = "x-ms-return-client-request-id" - - // HeaderContentType is the type of the content in the HTTP response. - HeaderContentType = "Content-Type" - - // HeaderRequestID is the Azure extension header of the service generated request ID returned - // in the response. - HeaderRequestID = "x-ms-request-id" -) - -// ServiceError encapsulates the error response from an Azure service. -// It adhears to the OData v4 specification for error responses. -type ServiceError struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details []map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` - AdditionalInfo []map[string]interface{} `json:"additionalInfo"` -} - -func (se ServiceError) Error() string { - result := fmt.Sprintf("Code=%q Message=%q", se.Code, se.Message) - - if se.Target != nil { - result += fmt.Sprintf(" Target=%q", *se.Target) - } - - if se.Details != nil { - d, err := json.Marshal(se.Details) - if err != nil { - result += fmt.Sprintf(" Details=%v", se.Details) - } - result += fmt.Sprintf(" Details=%s", d) - } - - if se.InnerError != nil { - d, err := json.Marshal(se.InnerError) - if err != nil { - result += fmt.Sprintf(" InnerError=%v", se.InnerError) - } - result += fmt.Sprintf(" InnerError=%s", d) - } - - if se.AdditionalInfo != nil { - d, err := json.Marshal(se.AdditionalInfo) - if err != nil { - result += fmt.Sprintf(" AdditionalInfo=%v", se.AdditionalInfo) - } - result += fmt.Sprintf(" AdditionalInfo=%s", d) - } - - return result -} - -// UnmarshalJSON implements the json.Unmarshaler interface for the ServiceError type. -func (se *ServiceError) UnmarshalJSON(b []byte) error { - // http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091 - - type serviceErrorInternal struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target,omitempty"` - AdditionalInfo []map[string]interface{} `json:"additionalInfo,omitempty"` - // not all services conform to the OData v4 spec. - // the following fields are where we've seen discrepancies - - // spec calls for []map[string]interface{} but have seen map[string]interface{} - Details interface{} `json:"details,omitempty"` - - // spec calls for map[string]interface{} but have seen []map[string]interface{} and string - InnerError interface{} `json:"innererror,omitempty"` - } - - sei := serviceErrorInternal{} - if err := json.Unmarshal(b, &sei); err != nil { - return err - } - - // copy the fields we know to be correct - se.AdditionalInfo = sei.AdditionalInfo - se.Code = sei.Code - se.Message = sei.Message - se.Target = sei.Target - - // converts an []interface{} to []map[string]interface{} - arrayOfObjs := func(v interface{}) ([]map[string]interface{}, bool) { - arrayOf, ok := v.([]interface{}) - if !ok { - return nil, false - } - final := []map[string]interface{}{} - for _, item := range arrayOf { - as, ok := item.(map[string]interface{}) - if !ok { - return nil, false - } - final = append(final, as) - } - return final, true - } - - // convert the remaining fields, falling back to raw JSON if necessary - - if c, ok := arrayOfObjs(sei.Details); ok { - se.Details = c - } else if c, ok := sei.Details.(map[string]interface{}); ok { - se.Details = []map[string]interface{}{c} - } else if sei.Details != nil { - // stuff into Details - se.Details = []map[string]interface{}{ - {"raw": sei.Details}, - } - } - - if c, ok := sei.InnerError.(map[string]interface{}); ok { - se.InnerError = c - } else if c, ok := arrayOfObjs(sei.InnerError); ok { - // if there's only one error extract it - if len(c) == 1 { - se.InnerError = c[0] - } else { - // multiple errors, stuff them into the value - se.InnerError = map[string]interface{}{ - "multi": c, - } - } - } else if c, ok := sei.InnerError.(string); ok { - se.InnerError = map[string]interface{}{"error": c} - } else if sei.InnerError != nil { - // stuff into InnerError - se.InnerError = map[string]interface{}{ - "raw": sei.InnerError, - } - } - return nil -} - -// RequestError describes an error response returned by Azure service. -type RequestError struct { - autorest.DetailedError - - // The error returned by the Azure service. - ServiceError *ServiceError `json:"error" xml:"Error"` - - // The request id (from the x-ms-request-id-header) of the request. - RequestID string -} - -// Error returns a human-friendly error message from service error. -func (e RequestError) Error() string { - return fmt.Sprintf("autorest/azure: Service returned an error. Status=%v %v", - e.StatusCode, e.ServiceError) -} - -// IsAzureError returns true if the passed error is an Azure Service error; false otherwise. -func IsAzureError(e error) bool { - _, ok := e.(*RequestError) - return ok -} - -// Resource contains details about an Azure resource. -type Resource struct { - SubscriptionID string - ResourceGroup string - Provider string - ResourceType string - ResourceName string -} - -// String function returns a string in form of azureResourceID -func (r Resource) String() string { - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s", r.SubscriptionID, r.ResourceGroup, r.Provider, r.ResourceType, r.ResourceName) -} - -// ParseResourceID parses a resource ID into a ResourceDetails struct. -// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource?tabs=json#resourceid. -func ParseResourceID(resourceID string) (Resource, error) { - - const resourceIDPatternText = `(?i)subscriptions/(.+)/resourceGroups/(.+)/providers/(.+?)/(.+?)/(.+)` - resourceIDPattern := regexp.MustCompile(resourceIDPatternText) - match := resourceIDPattern.FindStringSubmatch(resourceID) - - if len(match) == 0 { - return Resource{}, fmt.Errorf("parsing failed for %s. Invalid resource Id format", resourceID) - } - - v := strings.Split(match[5], "/") - resourceName := v[len(v)-1] - - result := Resource{ - SubscriptionID: match[1], - ResourceGroup: match[2], - Provider: match[3], - ResourceType: match[4], - ResourceName: resourceName, - } - - return result, nil -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) RequestError { - if v, ok := original.(*RequestError); ok { - return *v - } - - statusCode := autorest.UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - return RequestError{ - DetailedError: autorest.DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - }, - } -} - -// WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id -// header to true such that UUID accompanies the http.Response. -func WithReturningClientID(uuid string) autorest.PrepareDecorator { - preparer := autorest.CreatePreparer( - WithClientID(uuid), - WithReturnClientID(true)) - - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - return preparer.Prepare(r) - }) - } -} - -// WithClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). -func WithClientID(uuid string) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderClientID, uuid) -} - -// WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-return-client-request-id whose boolean value indicates if the value of the -// x-ms-client-request-id header should be included in the http.Response. -func WithReturnClientID(b bool) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderReturnClientID, strconv.FormatBool(b)) -} - -// ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the -// http.Request sent to the service (and returned in the http.Response) -func ExtractClientID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderClientID, resp) -} - -// ExtractRequestID extracts the Azure server generated request identifier from the -// x-ms-request-id header. -func ExtractRequestID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderRequestID, resp) -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an -// azure.RequestError by reading the response body unless the response HTTP status code -// is among the set passed. -// -// If there is a chance service may return responses other than the Azure error -// format and the response cannot be parsed into an error, a decoding error will -// be returned containing the response body. In any case, the Responder will -// return an error if the status code is not satisfied. -// -// If this Responder returns an error, the response body will be replaced with -// an in-memory reader, which needs no further closing. -func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator { - return func(r autorest.Responder) autorest.Responder { - return autorest.ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !autorest.ResponseHasStatusCode(resp, codes...) { - var e RequestError - defer resp.Body.Close() - - encodedAs := autorest.EncodedAsJSON - if strings.Contains(resp.Header.Get("Content-Type"), "xml") { - encodedAs = autorest.EncodedAsXML - } - - // Copy and replace the Body in case it does not contain an error object. - // This will leave the Body available to the caller. - b, decodeErr := autorest.CopyAndDecode(encodedAs, resp.Body, &e) - resp.Body = ioutil.NopCloser(&b) - if decodeErr != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b, decodeErr) - } - if e.ServiceError == nil { - // Check if error is unwrapped ServiceError - decoder := autorest.NewDecoder(encodedAs, bytes.NewReader(b.Bytes())) - if err := decoder.Decode(&e.ServiceError); err != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b, err) - } - - // for example, should the API return the literal value `null` as the response - if e.ServiceError == nil { - e.ServiceError = &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - Details: []map[string]interface{}{ - { - "HttpResponse.Body": b.String(), - }, - }, - } - } - } - - if e.ServiceError != nil && e.ServiceError.Message == "" { - // if we're here it means the returned error wasn't OData v4 compliant. - // try to unmarshal the body in hopes of getting something. - rawBody := map[string]interface{}{} - decoder := autorest.NewDecoder(encodedAs, bytes.NewReader(b.Bytes())) - if err := decoder.Decode(&rawBody); err != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b, err) - } - - e.ServiceError = &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - } - if len(rawBody) > 0 { - e.ServiceError.Details = []map[string]interface{}{rawBody} - } - } - e.Response = resp - e.RequestID = ExtractRequestID(resp) - if e.StatusCode == nil { - e.StatusCode = resp.StatusCode - } - err = &e - } - return err - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go deleted file mode 100644 index b0a53769f..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ /dev/null @@ -1,331 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "strings" -) - -const ( - // EnvironmentFilepathName captures the name of the environment variable containing the path to the file - // to be used while populating the Azure Environment. - EnvironmentFilepathName = "AZURE_ENVIRONMENT_FILEPATH" - - // NotAvailable is used for endpoints and resource IDs that are not available for a given cloud. - NotAvailable = "N/A" -) - -var environments = map[string]Environment{ - "AZURECHINACLOUD": ChinaCloud, - "AZUREGERMANCLOUD": GermanCloud, - "AZURECLOUD": PublicCloud, - "AZUREPUBLICCLOUD": PublicCloud, - "AZUREUSGOVERNMENT": USGovernmentCloud, - "AZUREUSGOVERNMENTCLOUD": USGovernmentCloud, //TODO: deprecate -} - -// ResourceIdentifier contains a set of Azure resource IDs. -type ResourceIdentifier struct { - Graph string `json:"graph"` - KeyVault string `json:"keyVault"` - Datalake string `json:"datalake"` - Batch string `json:"batch"` - OperationalInsights string `json:"operationalInsights"` - OSSRDBMS string `json:"ossRDBMS"` - Storage string `json:"storage"` - Synapse string `json:"synapse"` - ServiceBus string `json:"serviceBus"` - SQLDatabase string `json:"sqlDatabase"` - CosmosDB string `json:"cosmosDB"` - ManagedHSM string `json:"managedHSM"` - MicrosoftGraph string `json:"microsoftGraph"` -} - -// Environment represents a set of endpoints for each of Azure's Clouds. -type Environment struct { - Name string `json:"name"` - ManagementPortalURL string `json:"managementPortalURL"` - PublishSettingsURL string `json:"publishSettingsURL"` - ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` - ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` - GalleryEndpoint string `json:"galleryEndpoint"` - KeyVaultEndpoint string `json:"keyVaultEndpoint"` - ManagedHSMEndpoint string `json:"managedHSMEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - ServiceBusEndpoint string `json:"serviceBusEndpoint"` - BatchManagementEndpoint string `json:"batchManagementEndpoint"` - MicrosoftGraphEndpoint string `json:"microsoftGraphEndpoint"` - StorageEndpointSuffix string `json:"storageEndpointSuffix"` - CosmosDBDNSSuffix string `json:"cosmosDBDNSSuffix"` - MariaDBDNSSuffix string `json:"mariaDBDNSSuffix"` - MySQLDatabaseDNSSuffix string `json:"mySqlDatabaseDNSSuffix"` - PostgresqlDatabaseDNSSuffix string `json:"postgresqlDatabaseDNSSuffix"` - SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` - TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` - KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` - ManagedHSMDNSSuffix string `json:"managedHSMDNSSuffix"` - ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` - ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` - ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` - ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` - TokenAudience string `json:"tokenAudience"` - APIManagementHostNameSuffix string `json:"apiManagementHostNameSuffix"` - SynapseEndpointSuffix string `json:"synapseEndpointSuffix"` - DatalakeSuffix string `json:"datalakeSuffix"` - ResourceIdentifiers ResourceIdentifier `json:"resourceIdentifiers"` -} - -var ( - // PublicCloud is the default public Azure cloud environment - PublicCloud = Environment{ - Name: "AzurePublicCloud", - ManagementPortalURL: "https://manage.windowsazure.com/", - PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.windows.net/", - ResourceManagerEndpoint: "https://management.azure.com/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", - GalleryEndpoint: "https://gallery.azure.com/", - KeyVaultEndpoint: "https://vault.azure.net/", - ManagedHSMEndpoint: "https://managedhsm.azure.net/", - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.windows.net/", - BatchManagementEndpoint: "https://batch.core.windows.net/", - MicrosoftGraphEndpoint: "https://graph.microsoft.com/", - StorageEndpointSuffix: "core.windows.net", - CosmosDBDNSSuffix: "documents.azure.com", - MariaDBDNSSuffix: "mariadb.database.azure.com", - MySQLDatabaseDNSSuffix: "mysql.database.azure.com", - PostgresqlDatabaseDNSSuffix: "postgres.database.azure.com", - SQLDatabaseDNSSuffix: "database.windows.net", - TrafficManagerDNSSuffix: "trafficmanager.net", - KeyVaultDNSSuffix: "vault.azure.net", - ManagedHSMDNSSuffix: "managedhsm.azure.net", - ServiceBusEndpointSuffix: "servicebus.windows.net", - ServiceManagementVMDNSSuffix: "cloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.azure.com", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.azure.com/", - APIManagementHostNameSuffix: "azure-api.net", - SynapseEndpointSuffix: "dev.azuresynapse.net", - DatalakeSuffix: "azuredatalakestore.net", - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.windows.net/", - KeyVault: "https://vault.azure.net", - Datalake: "https://datalake.azure.net/", - Batch: "https://batch.core.windows.net/", - OperationalInsights: "https://api.loganalytics.io", - OSSRDBMS: "https://ossrdbms-aad.database.windows.net", - Storage: "https://storage.azure.com/", - Synapse: "https://dev.azuresynapse.net", - ServiceBus: "https://servicebus.azure.net/", - SQLDatabase: "https://database.windows.net/", - CosmosDB: "https://cosmos.azure.com", - ManagedHSM: "https://managedhsm.azure.net", - MicrosoftGraph: "https://graph.microsoft.com/", - }, - } - - // USGovernmentCloud is the cloud environment for the US Government - USGovernmentCloud = Environment{ - Name: "AzureUSGovernmentCloud", - ManagementPortalURL: "https://manage.windowsazure.us/", - PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", - ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.us/", - GalleryEndpoint: "https://gallery.usgovcloudapi.net/", - KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", - ManagedHSMEndpoint: NotAvailable, - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.usgovcloudapi.net/", - BatchManagementEndpoint: "https://batch.core.usgovcloudapi.net/", - MicrosoftGraphEndpoint: "https://graph.microsoft.us/", - StorageEndpointSuffix: "core.usgovcloudapi.net", - CosmosDBDNSSuffix: "documents.azure.us", - MariaDBDNSSuffix: "mariadb.database.usgovcloudapi.net", - MySQLDatabaseDNSSuffix: "mysql.database.usgovcloudapi.net", - PostgresqlDatabaseDNSSuffix: "postgres.database.usgovcloudapi.net", - SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", - TrafficManagerDNSSuffix: "usgovtrafficmanager.net", - KeyVaultDNSSuffix: "vault.usgovcloudapi.net", - ManagedHSMDNSSuffix: NotAvailable, - ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", - ServiceManagementVMDNSSuffix: "usgovcloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.usgovcloudapi.net", - ContainerRegistryDNSSuffix: "azurecr.us", - TokenAudience: "https://management.usgovcloudapi.net/", - APIManagementHostNameSuffix: "azure-api.us", - SynapseEndpointSuffix: "dev.azuresynapse.usgovcloudapi.net", - DatalakeSuffix: NotAvailable, - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.windows.net/", - KeyVault: "https://vault.usgovcloudapi.net", - Datalake: NotAvailable, - Batch: "https://batch.core.usgovcloudapi.net/", - OperationalInsights: "https://api.loganalytics.us", - OSSRDBMS: "https://ossrdbms-aad.database.usgovcloudapi.net", - Storage: "https://storage.azure.com/", - Synapse: "https://dev.azuresynapse.usgovcloudapi.net", - ServiceBus: "https://servicebus.azure.net/", - SQLDatabase: "https://database.usgovcloudapi.net/", - CosmosDB: "https://cosmos.azure.com", - ManagedHSM: NotAvailable, - MicrosoftGraph: "https://graph.microsoft.us/", - }, - } - - // ChinaCloud is the cloud environment operated in China - ChinaCloud = Environment{ - Name: "AzureChinaCloud", - ManagementPortalURL: "https://manage.chinacloudapi.com/", - PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", - ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", - ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/", - GalleryEndpoint: "https://gallery.chinacloudapi.cn/", - KeyVaultEndpoint: "https://vault.azure.cn/", - ManagedHSMEndpoint: NotAvailable, - GraphEndpoint: "https://graph.chinacloudapi.cn/", - ServiceBusEndpoint: "https://servicebus.chinacloudapi.cn/", - BatchManagementEndpoint: "https://batch.chinacloudapi.cn/", - MicrosoftGraphEndpoint: "https://microsoftgraph.chinacloudapi.cn/", - StorageEndpointSuffix: "core.chinacloudapi.cn", - CosmosDBDNSSuffix: "documents.azure.cn", - MariaDBDNSSuffix: "mariadb.database.chinacloudapi.cn", - MySQLDatabaseDNSSuffix: "mysql.database.chinacloudapi.cn", - PostgresqlDatabaseDNSSuffix: "postgres.database.chinacloudapi.cn", - SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", - TrafficManagerDNSSuffix: "trafficmanager.cn", - KeyVaultDNSSuffix: "vault.azure.cn", - ManagedHSMDNSSuffix: NotAvailable, - ServiceBusEndpointSuffix: "servicebus.chinacloudapi.cn", - ServiceManagementVMDNSSuffix: "chinacloudapp.cn", - ResourceManagerVMDNSSuffix: "cloudapp.chinacloudapi.cn", - ContainerRegistryDNSSuffix: "azurecr.cn", - TokenAudience: "https://management.chinacloudapi.cn/", - APIManagementHostNameSuffix: "azure-api.cn", - SynapseEndpointSuffix: "dev.azuresynapse.azure.cn", - DatalakeSuffix: NotAvailable, - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.chinacloudapi.cn/", - KeyVault: "https://vault.azure.cn", - Datalake: NotAvailable, - Batch: "https://batch.chinacloudapi.cn/", - OperationalInsights: NotAvailable, - OSSRDBMS: "https://ossrdbms-aad.database.chinacloudapi.cn", - Storage: "https://storage.azure.com/", - Synapse: "https://dev.azuresynapse.net", - ServiceBus: "https://servicebus.azure.net/", - SQLDatabase: "https://database.chinacloudapi.cn/", - CosmosDB: "https://cosmos.azure.com", - ManagedHSM: NotAvailable, - MicrosoftGraph: "https://microsoftgraph.chinacloudapi.cn", - }, - } - - // GermanCloud is the cloud environment operated in Germany - GermanCloud = Environment{ - Name: "AzureGermanCloud", - ManagementPortalURL: "http://portal.microsoftazure.de/", - PublishSettingsURL: "https://manage.microsoftazure.de/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.cloudapi.de/", - ResourceManagerEndpoint: "https://management.microsoftazure.de/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.de/", - GalleryEndpoint: "https://gallery.cloudapi.de/", - KeyVaultEndpoint: "https://vault.microsoftazure.de/", - ManagedHSMEndpoint: NotAvailable, - GraphEndpoint: "https://graph.cloudapi.de/", - ServiceBusEndpoint: "https://servicebus.cloudapi.de/", - BatchManagementEndpoint: "https://batch.cloudapi.de/", - MicrosoftGraphEndpoint: NotAvailable, - StorageEndpointSuffix: "core.cloudapi.de", - CosmosDBDNSSuffix: "documents.microsoftazure.de", - MariaDBDNSSuffix: "mariadb.database.cloudapi.de", - MySQLDatabaseDNSSuffix: "mysql.database.cloudapi.de", - PostgresqlDatabaseDNSSuffix: "postgres.database.cloudapi.de", - SQLDatabaseDNSSuffix: "database.cloudapi.de", - TrafficManagerDNSSuffix: "azuretrafficmanager.de", - KeyVaultDNSSuffix: "vault.microsoftazure.de", - ManagedHSMDNSSuffix: NotAvailable, - ServiceBusEndpointSuffix: "servicebus.cloudapi.de", - ServiceManagementVMDNSSuffix: "azurecloudapp.de", - ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", - ContainerRegistryDNSSuffix: NotAvailable, - TokenAudience: "https://management.microsoftazure.de/", - APIManagementHostNameSuffix: NotAvailable, - SynapseEndpointSuffix: NotAvailable, - DatalakeSuffix: NotAvailable, - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.cloudapi.de/", - KeyVault: "https://vault.microsoftazure.de", - Datalake: NotAvailable, - Batch: "https://batch.cloudapi.de/", - OperationalInsights: NotAvailable, - OSSRDBMS: "https://ossrdbms-aad.database.cloudapi.de", - Storage: "https://storage.azure.com/", - Synapse: NotAvailable, - ServiceBus: "https://servicebus.azure.net/", - SQLDatabase: "https://database.cloudapi.de/", - CosmosDB: "https://cosmos.azure.com", - ManagedHSM: NotAvailable, - MicrosoftGraph: NotAvailable, - }, - } -) - -// EnvironmentFromName returns an Environment based on the common name specified. -func EnvironmentFromName(name string) (Environment, error) { - // IMPORTANT - // As per @radhikagupta5: - // This is technical debt, fundamentally here because Kubernetes is not currently accepting - // contributions to the providers. Once that is an option, the provider should be updated to - // directly call `EnvironmentFromFile`. Until then, we rely on dispatching Azure Stack environment creation - // from this method based on the name that is provided to us. - if strings.EqualFold(name, "AZURESTACKCLOUD") { - return EnvironmentFromFile(os.Getenv(EnvironmentFilepathName)) - } - - name = strings.ToUpper(name) - env, ok := environments[name] - if !ok { - return env, fmt.Errorf("autorest/azure: There is no cloud environment matching the name %q", name) - } - - return env, nil -} - -// EnvironmentFromFile loads an Environment from a configuration file available on disk. -// This function is particularly useful in the Hybrid Cloud model, where one must define their own -// endpoints. -func EnvironmentFromFile(location string) (unmarshaled Environment, err error) { - fileContents, err := ioutil.ReadFile(location) - if err != nil { - return - } - - err = json.Unmarshal(fileContents, &unmarshaled) - - return -} - -// SetEnvironment updates the environment map with the specified values. -func SetEnvironment(name string, env Environment) { - environments[strings.ToUpper(name)] = env -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go b/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go deleted file mode 100644 index 507f9e95c..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go +++ /dev/null @@ -1,245 +0,0 @@ -package azure - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -type audience []string - -type authentication struct { - LoginEndpoint string `json:"loginEndpoint"` - Audiences audience `json:"audiences"` -} - -type environmentMetadataInfo struct { - GalleryEndpoint string `json:"galleryEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - PortalEndpoint string `json:"portalEndpoint"` - Authentication authentication `json:"authentication"` -} - -// EnvironmentProperty represent property names that clients can override -type EnvironmentProperty string - -const ( - // EnvironmentName ... - EnvironmentName EnvironmentProperty = "name" - // EnvironmentManagementPortalURL .. - EnvironmentManagementPortalURL EnvironmentProperty = "managementPortalURL" - // EnvironmentPublishSettingsURL ... - EnvironmentPublishSettingsURL EnvironmentProperty = "publishSettingsURL" - // EnvironmentServiceManagementEndpoint ... - EnvironmentServiceManagementEndpoint EnvironmentProperty = "serviceManagementEndpoint" - // EnvironmentResourceManagerEndpoint ... - EnvironmentResourceManagerEndpoint EnvironmentProperty = "resourceManagerEndpoint" - // EnvironmentActiveDirectoryEndpoint ... - EnvironmentActiveDirectoryEndpoint EnvironmentProperty = "activeDirectoryEndpoint" - // EnvironmentGalleryEndpoint ... - EnvironmentGalleryEndpoint EnvironmentProperty = "galleryEndpoint" - // EnvironmentKeyVaultEndpoint ... - EnvironmentKeyVaultEndpoint EnvironmentProperty = "keyVaultEndpoint" - // EnvironmentGraphEndpoint ... - EnvironmentGraphEndpoint EnvironmentProperty = "graphEndpoint" - // EnvironmentServiceBusEndpoint ... - EnvironmentServiceBusEndpoint EnvironmentProperty = "serviceBusEndpoint" - // EnvironmentBatchManagementEndpoint ... - EnvironmentBatchManagementEndpoint EnvironmentProperty = "batchManagementEndpoint" - // EnvironmentStorageEndpointSuffix ... - EnvironmentStorageEndpointSuffix EnvironmentProperty = "storageEndpointSuffix" - // EnvironmentSQLDatabaseDNSSuffix ... - EnvironmentSQLDatabaseDNSSuffix EnvironmentProperty = "sqlDatabaseDNSSuffix" - // EnvironmentTrafficManagerDNSSuffix ... - EnvironmentTrafficManagerDNSSuffix EnvironmentProperty = "trafficManagerDNSSuffix" - // EnvironmentKeyVaultDNSSuffix ... - EnvironmentKeyVaultDNSSuffix EnvironmentProperty = "keyVaultDNSSuffix" - // EnvironmentServiceBusEndpointSuffix ... - EnvironmentServiceBusEndpointSuffix EnvironmentProperty = "serviceBusEndpointSuffix" - // EnvironmentServiceManagementVMDNSSuffix ... - EnvironmentServiceManagementVMDNSSuffix EnvironmentProperty = "serviceManagementVMDNSSuffix" - // EnvironmentResourceManagerVMDNSSuffix ... - EnvironmentResourceManagerVMDNSSuffix EnvironmentProperty = "resourceManagerVMDNSSuffix" - // EnvironmentContainerRegistryDNSSuffix ... - EnvironmentContainerRegistryDNSSuffix EnvironmentProperty = "containerRegistryDNSSuffix" - // EnvironmentTokenAudience ... - EnvironmentTokenAudience EnvironmentProperty = "tokenAudience" -) - -// OverrideProperty represents property name and value that clients can override -type OverrideProperty struct { - Key EnvironmentProperty - Value string -} - -// EnvironmentFromURL loads an Environment from a URL -// This function is particularly useful in the Hybrid Cloud model, where one may define their own -// endpoints. -func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) { - var metadataEnvProperties environmentMetadataInfo - - if resourceManagerEndpoint == "" { - return environment, fmt.Errorf("Metadata resource manager endpoint is empty") - } - - if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil { - return environment, err - } - - // Give priority to user's override values - overrideProperties(&environment, properties) - - if environment.Name == "" { - environment.Name = "HybridEnvironment" - } - stampDNSSuffix := environment.StorageEndpointSuffix - if stampDNSSuffix == "" { - stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/") - environment.StorageEndpointSuffix = stampDNSSuffix - } - if environment.KeyVaultDNSSuffix == "" { - environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix) - } - if environment.KeyVaultEndpoint == "" { - environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix) - } - if environment.TokenAudience == "" { - environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0] - } - if environment.ActiveDirectoryEndpoint == "" { - environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint - } - if environment.ResourceManagerEndpoint == "" { - environment.ResourceManagerEndpoint = resourceManagerEndpoint - } - if environment.GalleryEndpoint == "" { - environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint - } - if environment.GraphEndpoint == "" { - environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint - } - - return environment, nil -} - -func overrideProperties(environment *Environment, properties []OverrideProperty) { - for _, property := range properties { - switch property.Key { - case EnvironmentName: - { - environment.Name = property.Value - } - case EnvironmentManagementPortalURL: - { - environment.ManagementPortalURL = property.Value - } - case EnvironmentPublishSettingsURL: - { - environment.PublishSettingsURL = property.Value - } - case EnvironmentServiceManagementEndpoint: - { - environment.ServiceManagementEndpoint = property.Value - } - case EnvironmentResourceManagerEndpoint: - { - environment.ResourceManagerEndpoint = property.Value - } - case EnvironmentActiveDirectoryEndpoint: - { - environment.ActiveDirectoryEndpoint = property.Value - } - case EnvironmentGalleryEndpoint: - { - environment.GalleryEndpoint = property.Value - } - case EnvironmentKeyVaultEndpoint: - { - environment.KeyVaultEndpoint = property.Value - } - case EnvironmentGraphEndpoint: - { - environment.GraphEndpoint = property.Value - } - case EnvironmentServiceBusEndpoint: - { - environment.ServiceBusEndpoint = property.Value - } - case EnvironmentBatchManagementEndpoint: - { - environment.BatchManagementEndpoint = property.Value - } - case EnvironmentStorageEndpointSuffix: - { - environment.StorageEndpointSuffix = property.Value - } - case EnvironmentSQLDatabaseDNSSuffix: - { - environment.SQLDatabaseDNSSuffix = property.Value - } - case EnvironmentTrafficManagerDNSSuffix: - { - environment.TrafficManagerDNSSuffix = property.Value - } - case EnvironmentKeyVaultDNSSuffix: - { - environment.KeyVaultDNSSuffix = property.Value - } - case EnvironmentServiceBusEndpointSuffix: - { - environment.ServiceBusEndpointSuffix = property.Value - } - case EnvironmentServiceManagementVMDNSSuffix: - { - environment.ServiceManagementVMDNSSuffix = property.Value - } - case EnvironmentResourceManagerVMDNSSuffix: - { - environment.ResourceManagerVMDNSSuffix = property.Value - } - case EnvironmentContainerRegistryDNSSuffix: - { - environment.ContainerRegistryDNSSuffix = property.Value - } - case EnvironmentTokenAudience: - { - environment.TokenAudience = property.Value - } - } - } -} - -func retrieveMetadataEnvironment(endpoint string) (environment environmentMetadataInfo, err error) { - client := autorest.NewClientWithUserAgent("") - managementEndpoint := fmt.Sprintf("%s%s", strings.TrimSuffix(endpoint, "/"), "/metadata/endpoints?api-version=1.0") - req, _ := http.NewRequest("GET", managementEndpoint, nil) - response, err := client.Do(req) - if err != nil { - return environment, err - } - defer response.Body.Close() - jsonResponse, err := ioutil.ReadAll(response.Body) - if err != nil { - return environment, err - } - err = json.Unmarshal(jsonResponse, &environment) - return environment, err -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go deleted file mode 100644 index 5b52357f9..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package azure - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -// DoRetryWithRegistration tries to register the resource provider in case it is unregistered. -// It also handles request retries -func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := autorest.NewRetriableRequest(r) - for currentAttempt := 0; currentAttempt < client.RetryAttempts; currentAttempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - - resp, err = autorest.SendWithSender(s, rr.Request(), - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return resp, err - } - - if resp.StatusCode != http.StatusConflict || client.SkipResourceProviderRegistration { - return resp, err - } - - var re RequestError - if strings.Contains(r.Header.Get("Content-Type"), "xml") { - // XML errors (e.g. Storage Data Plane) only return the inner object - err = autorest.Respond(resp, autorest.ByUnmarshallingXML(&re.ServiceError)) - } else { - err = autorest.Respond(resp, autorest.ByUnmarshallingJSON(&re)) - } - - if err != nil { - return resp, err - } - err = re - - if re.ServiceError != nil && re.ServiceError.Code == "MissingSubscriptionRegistration" { - regErr := register(client, r, re) - if regErr != nil { - return resp, fmt.Errorf("failed auto registering Resource Provider: %s. Original error: %w", regErr, err) - } - } - } - return resp, err - }) - } -} - -func getProvider(re RequestError) (string, error) { - if re.ServiceError != nil && len(re.ServiceError.Details) > 0 { - return re.ServiceError.Details[0]["target"].(string), nil - } - return "", errors.New("provider was not found in the response") -} - -func register(client autorest.Client, originalReq *http.Request, re RequestError) error { - subID := getSubscription(originalReq.URL.Path) - if subID == "" { - return errors.New("missing parameter subscriptionID to register resource provider") - } - providerName, err := getProvider(re) - if err != nil { - return fmt.Errorf("missing parameter provider to register resource provider: %s", err) - } - newURL := url.URL{ - Scheme: originalReq.URL.Scheme, - Host: originalReq.URL.Host, - } - - // taken from the resources SDK - // with almost identical code, this sections are easier to mantain - // It is also not a good idea to import the SDK here - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L252 - pathParameters := map[string]interface{}{ - "resourceProviderNamespace": autorest.Encode("path", providerName), - "subscriptionId": autorest.Encode("path", subID), - } - - const APIVersion = "2016-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - - req, err := preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - type Provider struct { - RegistrationState *string `json:"registrationState,omitempty"` - } - var provider Provider - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - // poll for registered provisioning state - registrationStartTime := time.Now() - for err == nil && (client.PollingDuration == 0 || (client.PollingDuration != 0 && time.Since(registrationStartTime) < client.PollingDuration)) { - // taken from the resources SDK - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L45 - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - req, err = preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - if provider.RegistrationState != nil && - *provider.RegistrationState == "Registered" { - break - } - - delayed := autorest.DelayWithRetryAfter(resp, originalReq.Context().Done()) - if !delayed && !autorest.DelayForBackoff(client.PollingDelay, 0, originalReq.Context().Done()) { - return originalReq.Context().Err() - } - } - if client.PollingDuration != 0 && !(time.Since(registrationStartTime) < client.PollingDuration) { - return errors.New("polling for resource provider registration has exceeded the polling duration") - } - return err -} - -func getSubscription(path string) string { - parts := strings.Split(path, "/") - for i, v := range parts { - if v == "subscriptions" && (i+1) < len(parts) { - return parts[i+1] - } - } - return "" -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go deleted file mode 100644 index bb5f9396e..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/client.go +++ /dev/null @@ -1,328 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "crypto/tls" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "strings" - "time" - - "github.com/Azure/go-autorest/logger" -) - -const ( - // DefaultPollingDelay is a reasonable delay between polling requests. - DefaultPollingDelay = 30 * time.Second - - // DefaultPollingDuration is a reasonable total polling duration. - DefaultPollingDuration = 15 * time.Minute - - // DefaultRetryAttempts is number of attempts for retry status codes (5xx). - DefaultRetryAttempts = 3 - - // DefaultRetryDuration is the duration to wait between retries. - DefaultRetryDuration = 30 * time.Second -) - -var ( - // StatusCodesForRetry are a defined group of status code for which the client will retry - StatusCodesForRetry = []int{ - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } -) - -const ( - requestFormat = `HTTP Request Begin =================================================== -%s -===================================================== HTTP Request End -` - responseFormat = `HTTP Response Begin =================================================== -%s -===================================================== HTTP Response End -` -) - -// Response serves as the base for all responses from generated clients. It provides access to the -// last http.Response. -type Response struct { - *http.Response `json:"-"` -} - -// IsHTTPStatus returns true if the returned HTTP status code matches the provided status code. -// If there was no response (i.e. the underlying http.Response is nil) the return value is false. -func (r Response) IsHTTPStatus(statusCode int) bool { - if r.Response == nil { - return false - } - return r.Response.StatusCode == statusCode -} - -// HasHTTPStatus returns true if the returned HTTP status code matches one of the provided status codes. -// If there was no response (i.e. the underlying http.Response is nil) or not status codes are provided -// the return value is false. -func (r Response) HasHTTPStatus(statusCodes ...int) bool { - return ResponseHasStatusCode(r.Response, statusCodes...) -} - -// LoggingInspector implements request and response inspectors that log the full request and -// response to a supplied log. -type LoggingInspector struct { - Logger *log.Logger -} - -// WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) WithInspection() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - var body, b bytes.Buffer - - defer r.Body.Close() - - r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body)) - if err := r.Write(&b); err != nil { - return nil, fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(requestFormat, b.String()) - - r.Body = ioutil.NopCloser(&body) - return p.Prepare(r) - }) - } -} - -// ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) ByInspecting() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - var body, b bytes.Buffer - defer resp.Body.Close() - resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body)) - if err := resp.Write(&b); err != nil { - return fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(responseFormat, b.String()) - - resp.Body = ioutil.NopCloser(&body) - return r.Respond(resp) - }) - } -} - -// Client is the base for autorest generated clients. It provides default, "do nothing" -// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the -// standard, undecorated http.Client as a default Sender. -// -// Generated clients should also use Error (see NewError and NewErrorWithError) for errors and -// return responses that compose with Response. -// -// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom -// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit -// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence -// sending the request by providing a decorated Sender. -type Client struct { - Authorizer Authorizer - Sender Sender - RequestInspector PrepareDecorator - ResponseInspector RespondDecorator - - // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header - PollingDelay time.Duration - - // PollingDuration sets the maximum polling time after which an error is returned. - // Setting this to zero will use the provided context to control the duration. - PollingDuration time.Duration - - // RetryAttempts sets the total number of times the client will attempt to make an HTTP request. - // Set the value to 1 to disable retries. DO NOT set the value to less than 1. - RetryAttempts int - - // RetryDuration sets the delay duration for retries. - RetryDuration time.Duration - - // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent - // through the Do method. - UserAgent string - - Jar http.CookieJar - - // Set to true to skip attempted registration of resource providers (false by default). - SkipResourceProviderRegistration bool - - // SendDecorators can be used to override the default chain of SendDecorators. - // This can be used to specify things like a custom retry SendDecorator. - // Set this to an empty slice to use no SendDecorators. - SendDecorators []SendDecorator -} - -// NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed -// string. -func NewClientWithUserAgent(ua string) Client { - return newClient(ua, tls.RenegotiateNever) -} - -// ClientOptions contains various Client configuration options. -type ClientOptions struct { - // UserAgent is an optional user-agent string to append to the default user agent. - UserAgent string - - // Renegotiation is an optional setting to control client-side TLS renegotiation. - Renegotiation tls.RenegotiationSupport -} - -// NewClientWithOptions returns an instance of a Client with the specified values. -func NewClientWithOptions(options ClientOptions) Client { - return newClient(options.UserAgent, options.Renegotiation) -} - -func newClient(ua string, renegotiation tls.RenegotiationSupport) Client { - c := Client{ - PollingDelay: DefaultPollingDelay, - PollingDuration: DefaultPollingDuration, - RetryAttempts: DefaultRetryAttempts, - RetryDuration: DefaultRetryDuration, - UserAgent: UserAgent(), - } - c.Sender = c.sender(renegotiation) - c.AddToUserAgent(ua) - return c -} - -// AddToUserAgent adds an extension to the current user agent -func (c *Client) AddToUserAgent(extension string) error { - if extension != "" { - c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension) - return nil - } - return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent) -} - -// Do implements the Sender interface by invoking the active Sender after applying authorization. -// If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent -// is set, apply set the User-Agent header. -func (c Client) Do(r *http.Request) (*http.Response, error) { - if r.UserAgent() == "" { - r, _ = Prepare(r, - WithUserAgent(c.UserAgent)) - } - // NOTE: c.WithInspection() must be last in the list so that it can inspect all preceding operations - r, err := Prepare(r, - c.WithAuthorization(), - c.WithInspection()) - if err != nil { - var resp *http.Response - if detErr, ok := err.(DetailedError); ok { - // if the authorization failed (e.g. invalid credentials) there will - // be a response associated with the error, be sure to return it. - resp = detErr.Response - } - return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") - } - logger.Instance.WriteRequest(r, logger.Filter{ - Header: func(k string, v []string) (bool, []string) { - // remove the auth token from the log - if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Ocp-Apim-Subscription-Key") { - v = []string{"**REDACTED**"} - } - return true, v - }, - }) - resp, err := SendWithSender(c.sender(tls.RenegotiateNever), r) - if resp == nil && err == nil { - err = errors.New("autorest: received nil response and error") - } - logger.Instance.WriteResponse(resp, logger.Filter{}) - Respond(resp, c.ByInspecting()) - return resp, err -} - -// sender returns the Sender to which to send requests. -func (c Client) sender(renengotiation tls.RenegotiationSupport) Sender { - if c.Sender == nil { - return sender(renengotiation) - } - return c.Sender -} - -// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator -// from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer. -func (c Client) WithAuthorization() PrepareDecorator { - return c.authorizer().WithAuthorization() -} - -// authorizer returns the Authorizer to use. -func (c Client) authorizer() Authorizer { - if c.Authorizer == nil { - return NullAuthorizer{} - } - return c.Authorizer -} - -// WithInspection is a convenience method that passes the request to the supplied RequestInspector, -// if present, or returns the WithNothing PrepareDecorator otherwise. -func (c Client) WithInspection() PrepareDecorator { - if c.RequestInspector == nil { - return WithNothing() - } - return c.RequestInspector -} - -// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector, -// if present, or returns the ByIgnoring RespondDecorator otherwise. -func (c Client) ByInspecting() RespondDecorator { - if c.ResponseInspector == nil { - return ByIgnoring() - } - return c.ResponseInspector -} - -// Send sends the provided http.Request using the client's Sender or the default sender. -// It returns the http.Response and possible error. It also accepts a, possibly empty, -// default set of SendDecorators used when sending the request. -// SendDecorators have the following precedence: -// 1. In a request's context via WithSendDecorators() -// 2. Specified on the client in SendDecorators -// 3. The default values specified in this method -func (c Client) Send(req *http.Request, decorators ...SendDecorator) (*http.Response, error) { - if c.SendDecorators != nil { - decorators = c.SendDecorators - } - inCtx := req.Context().Value(ctxSendDecorators{}) - if sd, ok := inCtx.([]SendDecorator); ok { - decorators = sd - } - return SendWithSender(c, req, decorators...) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/date.go b/vendor/github.com/Azure/go-autorest/autorest/date/date.go deleted file mode 100644 index c45710656..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/date.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Package date provides time.Time derivatives that conform to the Swagger.io (https://swagger.io/) -defined date formats: Date and DateTime. Both types may, in most cases, be used in lieu of -time.Time types. And both convert to time.Time through a ToTime method. -*/ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "time" -) - -const ( - fullDate = "2006-01-02" - fullDateJSON = `"2006-01-02"` - dateFormat = "%04d-%02d-%02d" - jsonFormat = `"%04d-%02d-%02d"` -) - -// Date defines a type similar to time.Time but assumes a layout of RFC3339 full-date (i.e., -// 2006-01-02). -type Date struct { - time.Time -} - -// ParseDate create a new Date from the passed string. -func ParseDate(date string) (d Date, err error) { - return parseDate(date, fullDate) -} - -func parseDate(date string, format string) (Date, error) { - d, err := time.Parse(format, date) - return Date{Time: d}, err -} - -// MarshalBinary preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalBinary() ([]byte, error) { - return d.MarshalText() -} - -// UnmarshalBinary reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalBinary(data []byte) error { - return d.UnmarshalText(data) -} - -// MarshalJSON preserves the Date as a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalJSON() (json []byte, err error) { - return []byte(fmt.Sprintf(jsonFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalJSON reconstitutes the Date from a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalJSON(data []byte) (err error) { - d.Time, err = time.Parse(fullDateJSON, string(data)) - return err -} - -// MarshalText preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalText() (text []byte, err error) { - return []byte(fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalText reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalText(data []byte) (err error) { - d.Time, err = time.Parse(fullDate, string(data)) - return err -} - -// String returns the Date formatted as an RFC3339 full-date string (i.e., 2006-01-02). -func (d Date) String() string { - return fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day()) -} - -// ToTime returns a Date as a time.Time -func (d Date) ToTime() time.Time { - return d.Time -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go deleted file mode 100644 index 4e0543207..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/time.go b/vendor/github.com/Azure/go-autorest/autorest/date/time.go deleted file mode 100644 index b453fad04..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/time.go +++ /dev/null @@ -1,103 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "regexp" - "time" -) - -// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -const ( - azureUtcFormatJSON = `"2006-01-02T15:04:05.999999999"` - azureUtcFormat = "2006-01-02T15:04:05.999999999" - rfc3339JSON = `"` + time.RFC3339Nano + `"` - rfc3339 = time.RFC3339Nano - tzOffsetRegex = `(Z|z|\+|-)(\d+:\d+)*"*$` -) - -// Time defines a type similar to time.Time but assumes a layout of RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -type Time struct { - time.Time -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalBinary() ([]byte, error) { - return t.Time.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalJSON() (json []byte, err error) { - return t.Time.MarshalJSON() -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalJSON(data []byte) (err error) { - timeFormat := azureUtcFormatJSON - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339JSON - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// MarshalText preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalText() (text []byte, err error) { - return t.Time.MarshalText() -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalText(data []byte) (err error) { - timeFormat := azureUtcFormat - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339 - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// String returns the Time formatted as an RFC3339 date-time string (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) String() string { - // Note: time.Time.String does not return an RFC3339 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} - -// ToTime returns a Time as a time.Time -func (t Time) ToTime() time.Time { - return t.Time -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go deleted file mode 100644 index 48fb39ba9..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go +++ /dev/null @@ -1,100 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "errors" - "time" -) - -const ( - rfc1123JSON = `"` + time.RFC1123 + `"` - rfc1123 = time.RFC1123 -) - -// TimeRFC1123 defines a type similar to time.Time but assumes a layout of RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -type TimeRFC1123 struct { - time.Time -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalJSON(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123JSON, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalJSON() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") - } - b := []byte(t.Format(rfc1123JSON)) - return b, nil -} - -// MarshalText preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalText() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") - } - - b := []byte(t.Format(rfc1123)) - return b, nil -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalText(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalBinary() ([]byte, error) { - return t.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// ToTime returns a Time as a time.Time -func (t TimeRFC1123) ToTime() time.Time { - return t.Time -} - -// String returns the Time formatted as an RFC1123 date-time string (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) String() string { - // Note: time.Time.String does not return an RFC1123 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go b/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go deleted file mode 100644 index 7073959b2..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go +++ /dev/null @@ -1,123 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "time" -) - -// unixEpoch is the moment in time that should be treated as timestamp 0. -var unixEpoch = time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC) - -// UnixTime marshals and unmarshals a time that is represented as the number -// of seconds (ignoring skip-seconds) since the Unix Epoch. -type UnixTime time.Time - -// Duration returns the time as a Duration since the UnixEpoch. -func (t UnixTime) Duration() time.Duration { - return time.Time(t).Sub(unixEpoch) -} - -// NewUnixTimeFromSeconds creates a UnixTime as a number of seconds from the UnixEpoch. -func NewUnixTimeFromSeconds(seconds float64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second))) -} - -// NewUnixTimeFromNanoseconds creates a UnixTime as a number of nanoseconds from the UnixEpoch. -func NewUnixTimeFromNanoseconds(nanoseconds int64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(nanoseconds)) -} - -// NewUnixTimeFromDuration creates a UnixTime as a duration of time since the UnixEpoch. -func NewUnixTimeFromDuration(dur time.Duration) UnixTime { - return UnixTime(unixEpoch.Add(dur)) -} - -// UnixEpoch retreives the moment considered the Unix Epoch. I.e. The time represented by '0' -func UnixEpoch() time.Time { - return unixEpoch -} - -// MarshalJSON preserves the UnixTime as a JSON number conforming to Unix Timestamp requirements. -// (i.e. the number of seconds since midnight January 1st, 1970 not considering leap seconds.) -func (t UnixTime) MarshalJSON() ([]byte, error) { - buffer := &bytes.Buffer{} - enc := json.NewEncoder(buffer) - err := enc.Encode(float64(time.Time(t).UnixNano()) / 1e9) - if err != nil { - return nil, err - } - return buffer.Bytes(), nil -} - -// UnmarshalJSON reconstitures a UnixTime saved as a JSON number of the number of seconds since -// midnight January 1st, 1970. -func (t *UnixTime) UnmarshalJSON(text []byte) error { - dec := json.NewDecoder(bytes.NewReader(text)) - - var secondsSinceEpoch float64 - if err := dec.Decode(&secondsSinceEpoch); err != nil { - return err - } - - *t = NewUnixTimeFromSeconds(secondsSinceEpoch) - - return nil -} - -// MarshalText stores the number of seconds since the Unix Epoch as a textual floating point number. -func (t UnixTime) MarshalText() ([]byte, error) { - cast := time.Time(t) - return cast.MarshalText() -} - -// UnmarshalText populates a UnixTime with a value stored textually as a floating point number of seconds since the Unix Epoch. -func (t *UnixTime) UnmarshalText(raw []byte) error { - var unmarshaled time.Time - - if err := unmarshaled.UnmarshalText(raw); err != nil { - return err - } - - *t = UnixTime(unmarshaled) - return nil -} - -// MarshalBinary converts a UnixTime into a binary.LittleEndian float64 of nanoseconds since the epoch. -func (t UnixTime) MarshalBinary() ([]byte, error) { - buf := &bytes.Buffer{} - - payload := int64(t.Duration()) - - if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -// UnmarshalBinary converts a from a binary.LittleEndian float64 of nanoseconds since the epoch into a UnixTime. -func (t *UnixTime) UnmarshalBinary(raw []byte) error { - var nanosecondsSinceEpoch int64 - - if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil { - return err - } - *t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch) - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go b/vendor/github.com/Azure/go-autorest/autorest/date/utility.go deleted file mode 100644 index 12addf0eb..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go +++ /dev/null @@ -1,25 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "strings" - "time" -) - -// ParseTime to parse Time string to specified format. -func ParseTime(format string, t string) (d time.Time, err error) { - return time.Parse(format, strings.ToUpper(t)) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/Azure/go-autorest/autorest/error.go deleted file mode 100644 index 35098eda8..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/error.go +++ /dev/null @@ -1,103 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" -) - -const ( - // UndefinedStatusCode is used when HTTP status code is not available for an error. - UndefinedStatusCode = 0 -) - -// DetailedError encloses a error with details of the package, method, and associated HTTP -// status code (if any). -type DetailedError struct { - Original error - - // PackageType is the package type of the object emitting the error. For types, the value - // matches that produced the the '%T' format specifier of the fmt package. For other elements, - // such as functions, it is just the package name (e.g., "autorest"). - PackageType string - - // Method is the name of the method raising the error. - Method string - - // StatusCode is the HTTP Response StatusCode (if non-zero) that led to the error. - StatusCode interface{} - - // Message is the error message. - Message string - - // Service Error is the response body of failed API in bytes - ServiceError []byte - - // Response is the response object that was returned during failure if applicable. - Response *http.Response -} - -// NewError creates a new Error conforming object from the passed packageType, method, and -// message. message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, nil, message, args...) -} - -// NewErrorWithResponse creates a new Error conforming object from the passed -// packageType, method, statusCode of the given resp (UndefinedStatusCode if -// resp is nil), and message. message is treated as a format string to which the -// optional args apply. -func NewErrorWithResponse(packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, resp, message, args...) -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - if v, ok := original.(DetailedError); ok { - return v - } - - statusCode := UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - - return DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - Response: resp, - } -} - -// Error returns a formatted containing all available details (i.e., PackageType, Method, -// StatusCode, Message, and original error (if any)). -func (e DetailedError) Error() string { - if e.Original == nil { - return fmt.Sprintf("%s#%s: %s: StatusCode=%d", e.PackageType, e.Method, e.Message, e.StatusCode) - } - return fmt.Sprintf("%s#%s: %s: StatusCode=%d -- Original Error: %v", e.PackageType, e.Method, e.Message, e.StatusCode, e.Original) -} - -// Unwrap returns the original error. -func (e DetailedError) Unwrap() error { - return e.Original -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/go_mod_tidy_hack.go deleted file mode 100644 index 792f82d4b..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/go_mod_tidy_hack.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build modhack -// +build modhack - -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go deleted file mode 100644 index 121a66fa8..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ /dev/null @@ -1,549 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "context" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "strings" -) - -const ( - mimeTypeJSON = "application/json" - mimeTypeOctetStream = "application/octet-stream" - mimeTypeFormPost = "application/x-www-form-urlencoded" - - headerAuthorization = "Authorization" - headerAuxAuthorization = "x-ms-authorization-auxiliary" - headerContentType = "Content-Type" - headerUserAgent = "User-Agent" -) - -// used as a key type in context.WithValue() -type ctxPrepareDecorators struct{} - -// WithPrepareDecorators adds the specified PrepareDecorators to the provided context. -// If no PrepareDecorators are provided the context is unchanged. -func WithPrepareDecorators(ctx context.Context, prepareDecorator []PrepareDecorator) context.Context { - if len(prepareDecorator) == 0 { - return ctx - } - return context.WithValue(ctx, ctxPrepareDecorators{}, prepareDecorator) -} - -// GetPrepareDecorators returns the PrepareDecorators in the provided context or the provided default PrepareDecorators. -func GetPrepareDecorators(ctx context.Context, defaultPrepareDecorators ...PrepareDecorator) []PrepareDecorator { - inCtx := ctx.Value(ctxPrepareDecorators{}) - if pd, ok := inCtx.([]PrepareDecorator); ok { - return pd - } - return defaultPrepareDecorators -} - -// Preparer is the interface that wraps the Prepare method. -// -// Prepare accepts and possibly modifies an http.Request (e.g., adding Headers). Implementations -// must ensure to not share or hold per-invocation state since Preparers may be shared and re-used. -type Preparer interface { - Prepare(*http.Request) (*http.Request, error) -} - -// PreparerFunc is a method that implements the Preparer interface. -type PreparerFunc func(*http.Request) (*http.Request, error) - -// Prepare implements the Preparer interface on PreparerFunc. -func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) { - return pf(r) -} - -// PrepareDecorator takes and possibly decorates, by wrapping, a Preparer. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then affect the result. -type PrepareDecorator func(Preparer) Preparer - -// CreatePreparer creates, decorates, and returns a Preparer. -// Without decorators, the returned Preparer returns the passed http.Request unmodified. -// Preparers are safe to share and re-use. -func CreatePreparer(decorators ...PrepareDecorator) Preparer { - return DecoratePreparer( - Preparer(PreparerFunc(func(r *http.Request) (*http.Request, error) { return r, nil })), - decorators...) -} - -// DecoratePreparer accepts a Preparer and a, possibly empty, set of PrepareDecorators, which it -// applies to the Preparer. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (change the http.Request and then pass it -// along) or a post-decorator (pass the http.Request along and alter it on return). -func DecoratePreparer(p Preparer, decorators ...PrepareDecorator) Preparer { - for _, decorate := range decorators { - p = decorate(p) - } - return p -} - -// Prepare accepts an http.Request and a, possibly empty, set of PrepareDecorators. -// It creates a Preparer from the decorators which it then applies to the passed http.Request. -func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) { - if r == nil { - return nil, NewError("autorest", "Prepare", "Invoked without an http.Request") - } - return CreatePreparer(decorators...).Prepare(r) -} - -// WithNothing returns a "do nothing" PrepareDecorator that makes no changes to the passed -// http.Request. -func WithNothing() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - return p.Prepare(r) - }) - } -} - -// WithHeader returns a PrepareDecorator that sets the specified HTTP header of the http.Request to -// the passed value. It canonicalizes the passed header name (via http.CanonicalHeaderKey) before -// adding the header. -func WithHeader(header string, value string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - setHeader(r, http.CanonicalHeaderKey(header), value) - } - return r, err - }) - } -} - -// WithHeaders returns a PrepareDecorator that sets the specified HTTP headers of the http.Request to -// the passed value. It canonicalizes the passed headers name (via http.CanonicalHeaderKey) before -// adding them. -func WithHeaders(headers map[string]interface{}) PrepareDecorator { - h := ensureValueStrings(headers) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.Header == nil { - r.Header = make(http.Header) - } - - for name, value := range h { - r.Header.Set(http.CanonicalHeaderKey(name), value) - } - } - return r, err - }) - } -} - -// WithBearerAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the supplied token. -func WithBearerAuthorization(token string) PrepareDecorator { - return WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", token)) -} - -// AsContentType returns a PrepareDecorator that adds an HTTP Content-Type header whose value -// is the passed contentType. -func AsContentType(contentType string) PrepareDecorator { - return WithHeader(headerContentType, contentType) -} - -// WithUserAgent returns a PrepareDecorator that adds an HTTP User-Agent header whose value is the -// passed string. -func WithUserAgent(ua string) PrepareDecorator { - return WithHeader(headerUserAgent, ua) -} - -// AsFormURLEncoded returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/x-www-form-urlencoded". -func AsFormURLEncoded() PrepareDecorator { - return AsContentType(mimeTypeFormPost) -} - -// AsJSON returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/json". -func AsJSON() PrepareDecorator { - return AsContentType(mimeTypeJSON) -} - -// AsOctetStream returns a PrepareDecorator that adds the "application/octet-stream" Content-Type header. -func AsOctetStream() PrepareDecorator { - return AsContentType(mimeTypeOctetStream) -} - -// WithMethod returns a PrepareDecorator that sets the HTTP method of the passed request. The -// decorator does not validate that the passed method string is a known HTTP method. -func WithMethod(method string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r.Method = method - return p.Prepare(r) - }) - } -} - -// AsDelete returns a PrepareDecorator that sets the HTTP method to DELETE. -func AsDelete() PrepareDecorator { return WithMethod("DELETE") } - -// AsGet returns a PrepareDecorator that sets the HTTP method to GET. -func AsGet() PrepareDecorator { return WithMethod("GET") } - -// AsHead returns a PrepareDecorator that sets the HTTP method to HEAD. -func AsHead() PrepareDecorator { return WithMethod("HEAD") } - -// AsMerge returns a PrepareDecorator that sets the HTTP method to MERGE. -func AsMerge() PrepareDecorator { return WithMethod("MERGE") } - -// AsOptions returns a PrepareDecorator that sets the HTTP method to OPTIONS. -func AsOptions() PrepareDecorator { return WithMethod("OPTIONS") } - -// AsPatch returns a PrepareDecorator that sets the HTTP method to PATCH. -func AsPatch() PrepareDecorator { return WithMethod("PATCH") } - -// AsPost returns a PrepareDecorator that sets the HTTP method to POST. -func AsPost() PrepareDecorator { return WithMethod("POST") } - -// AsPut returns a PrepareDecorator that sets the HTTP method to PUT. -func AsPut() PrepareDecorator { return WithMethod("PUT") } - -// WithBaseURL returns a PrepareDecorator that populates the http.Request with a url.URL constructed -// from the supplied baseUrl. Query parameters will be encoded as required. -func WithBaseURL(baseURL string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var u *url.URL - if u, err = url.Parse(baseURL); err != nil { - return r, err - } - if u.Scheme == "" { - return r, fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) - } - if u.RawQuery != "" { - // handle unencoded semicolons (ideally the server would send them already encoded) - u.RawQuery = strings.Replace(u.RawQuery, ";", "%3B", -1) - q, err := url.ParseQuery(u.RawQuery) - if err != nil { - return r, err - } - u.RawQuery = q.Encode() - } - r.URL = u - } - return r, err - }) - } -} - -// WithBytes returns a PrepareDecorator that takes a list of bytes -// which passes the bytes directly to the body -func WithBytes(input *[]byte) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if input == nil { - return r, fmt.Errorf("Input Bytes was nil") - } - - r.ContentLength = int64(len(*input)) - r.Body = ioutil.NopCloser(bytes.NewReader(*input)) - } - return r, err - }) - } -} - -// WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the -// request base URL (i.e., http.Request.URL) with the corresponding values from the passed map. -func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(urlParameters) - for key, value := range parameters { - baseURL = strings.Replace(baseURL, "{"+key+"}", value, -1) - } - return WithBaseURL(baseURL) -} - -// WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the -// http.Request body. -func WithFormData(v url.Values) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - s := v.Encode() - - setHeader(r, http.CanonicalHeaderKey(headerContentType), mimeTypeFormPost) - r.ContentLength = int64(len(s)) - r.Body = ioutil.NopCloser(strings.NewReader(s)) - } - return r, err - }) - } -} - -// WithMultiPartFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) form parameters -// into the http.Request body. -func WithMultiPartFormData(formDataParameters map[string]interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var body bytes.Buffer - writer := multipart.NewWriter(&body) - for key, value := range formDataParameters { - if rc, ok := value.(io.ReadCloser); ok { - var fd io.Writer - if fd, err = writer.CreateFormFile(key, key); err != nil { - return r, err - } - if _, err = io.Copy(fd, rc); err != nil { - return r, err - } - } else { - if err = writer.WriteField(key, ensureValueString(value)); err != nil { - return r, err - } - } - } - if err = writer.Close(); err != nil { - return r, err - } - setHeader(r, http.CanonicalHeaderKey(headerContentType), writer.FormDataContentType()) - r.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - r.ContentLength = int64(body.Len()) - return r, err - } - return r, err - }) - } -} - -// WithFile returns a PrepareDecorator that sends file in request body. -func WithFile(f io.ReadCloser) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := ioutil.ReadAll(f) - if err != nil { - return r, err - } - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - r.ContentLength = int64(len(b)) - } - return r, err - }) - } -} - -// WithBool returns a PrepareDecorator that encodes the passed bool into the body of the request -// and sets the Content-Length header. -func WithBool(v bool) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat32 returns a PrepareDecorator that encodes the passed float32 into the body of the -// request and sets the Content-Length header. -func WithFloat32(v float32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat64 returns a PrepareDecorator that encodes the passed float64 into the body of the -// request and sets the Content-Length header. -func WithFloat64(v float64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt32 returns a PrepareDecorator that encodes the passed int32 into the body of the request -// and sets the Content-Length header. -func WithInt32(v int32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt64 returns a PrepareDecorator that encodes the passed int64 into the body of the request -// and sets the Content-Length header. -func WithInt64(v int64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithString returns a PrepareDecorator that encodes the passed string into the body of the request -// and sets the Content-Length header. -func WithString(v string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - r.ContentLength = int64(len(v)) - r.Body = ioutil.NopCloser(strings.NewReader(v)) - } - return r, err - }) - } -} - -// WithJSON returns a PrepareDecorator that encodes the data passed as JSON into the body of the -// request and sets the Content-Length header. -func WithJSON(v interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := json.Marshal(v) - if err == nil { - r.ContentLength = int64(len(b)) - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - } - return r, err - }) - } -} - -// WithXML returns a PrepareDecorator that encodes the data passed as XML into the body of the -// request and sets the Content-Length header. -func WithXML(v interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := xml.Marshal(v) - if err == nil { - // we have to tack on an XML header - withHeader := xml.Header + string(b) - bytesWithHeader := []byte(withHeader) - - r.ContentLength = int64(len(bytesWithHeader)) - setHeader(r, headerContentLength, fmt.Sprintf("%d", len(bytesWithHeader))) - r.Body = ioutil.NopCloser(bytes.NewReader(bytesWithHeader)) - } - } - return r, err - }) - } -} - -// WithPath returns a PrepareDecorator that adds the supplied path to the request URL. If the path -// is absolute (that is, it begins with a "/"), it replaces the existing path. -func WithPath(path string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPath", "Invoked with a nil URL") - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithEscapedPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. The -// values will be escaped (aka URL encoded) before insertion into the path. -func WithEscapedPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := escapeValueStrings(ensureValueStrings(pathParameters)) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithEscapedPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. -func WithPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(pathParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -func parseURL(u *url.URL, path string) (*url.URL, error) { - p := strings.TrimRight(u.String(), "/") - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - return url.Parse(p + path) -} - -// WithQueryParameters returns a PrepareDecorators that encodes and applies the query parameters -// given in the supplied map (i.e., key=value). -func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorator { - parameters := MapToValues(queryParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithQueryParameters", "Invoked with a nil URL") - } - v := r.URL.Query() - for key, value := range parameters { - for i := range value { - d, err := url.QueryUnescape(value[i]) - if err != nil { - return r, err - } - value[i] = d - } - v[key] = value - } - r.URL.RawQuery = v.Encode() - } - return r, err - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go deleted file mode 100644 index 349e1963a..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/responder.go +++ /dev/null @@ -1,269 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// Responder is the interface that wraps the Respond method. -// -// Respond accepts and reacts to an http.Response. Implementations must ensure to not share or hold -// state since Responders may be shared and re-used. -type Responder interface { - Respond(*http.Response) error -} - -// ResponderFunc is a method that implements the Responder interface. -type ResponderFunc func(*http.Response) error - -// Respond implements the Responder interface on ResponderFunc. -func (rf ResponderFunc) Respond(r *http.Response) error { - return rf(r) -} - -// RespondDecorator takes and possibly decorates, by wrapping, a Responder. Decorators may react to -// the http.Response and pass it along or, first, pass the http.Response along then react. -type RespondDecorator func(Responder) Responder - -// CreateResponder creates, decorates, and returns a Responder. Without decorators, the returned -// Responder returns the passed http.Response unmodified. Responders may or may not be safe to share -// and re-used: It depends on the applied decorators. For example, a standard decorator that closes -// the response body is fine to share whereas a decorator that reads the body into a passed struct -// is not. -// -// To prevent memory leaks, ensure that at least one Responder closes the response body. -func CreateResponder(decorators ...RespondDecorator) Responder { - return DecorateResponder( - Responder(ResponderFunc(func(r *http.Response) error { return nil })), - decorators...) -} - -// DecorateResponder accepts a Responder and a, possibly empty, set of RespondDecorators, which it -// applies to the Responder. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (react to the http.Response and then pass it -// along) or a post-decorator (pass the http.Response along and then react). -func DecorateResponder(r Responder, decorators ...RespondDecorator) Responder { - for _, decorate := range decorators { - r = decorate(r) - } - return r -} - -// Respond accepts an http.Response and a, possibly empty, set of RespondDecorators. -// It creates a Responder from the decorators it then applies to the passed http.Response. -func Respond(r *http.Response, decorators ...RespondDecorator) error { - if r == nil { - return nil - } - return CreateResponder(decorators...).Respond(r) -} - -// ByIgnoring returns a RespondDecorator that ignores the passed http.Response passing it unexamined -// to the next RespondDecorator. -func ByIgnoring() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - return r.Respond(resp) - }) - } -} - -// ByCopying copies the contents of the http.Response Body into the passed bytes.Buffer as -// the Body is read. -func ByCopying(b *bytes.Buffer) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - resp.Body = TeeReadCloser(resp.Body, b) - } - return err - }) - } -} - -// ByDiscardingBody returns a RespondDecorator that first invokes the passed Responder after which -// it copies the remaining bytes (if any) in the response body to ioutil.Discard. Since the passed -// Responder is invoked prior to discarding the response body, the decorator may occur anywhere -// within the set. -func ByDiscardingBody() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { - return fmt.Errorf("Error discarding the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosing returns a RespondDecorator that first invokes the passed Responder after which it -// closes the response body. Since the passed Responder is invoked prior to closing the response -// body, the decorator may occur anywhere within the set. -func ByClosing() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosingIfError returns a RespondDecorator that first invokes the passed Responder after which -// it closes the response if the passed Responder returns an error and the response body exists. -func ByClosingIfError() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err != nil && resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByUnmarshallingBytes returns a RespondDecorator that copies the Bytes returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingBytes(v *[]byte) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - bytes, errInner := ioutil.ReadAll(resp.Body) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else { - *v = bytes - } - } - return err - }) - } -} - -// ByUnmarshallingJSON returns a RespondDecorator that decodes a JSON document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingJSON(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - // Some responses might include a BOM, remove for successful unmarshalling - b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else if len(strings.Trim(string(b), " ")) > 0 { - errInner = json.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling JSON - Error = '%v' JSON = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// ByUnmarshallingXML returns a RespondDecorator that decodes a XML document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingXML(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else { - errInner = xml.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling Xml - Error = '%v' Xml = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an error unless the response -// StatusCode is among the set passed. On error, response body is fully read into a buffer and -// presented in the returned error, as well as in the response body. -func WithErrorUnlessStatusCode(codes ...int) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - derr := NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - if resp.Body != nil { - defer resp.Body.Close() - b, _ := ioutil.ReadAll(resp.Body) - derr.ServiceError = b - resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - err = derr - } - return err - }) - } -} - -// WithErrorUnlessOK returns a RespondDecorator that emits an error if the response StatusCode is -// anything other than HTTP 200. -func WithErrorUnlessOK() RespondDecorator { - return WithErrorUnlessStatusCode(http.StatusOK) -} - -// ExtractHeader extracts all values of the specified header from the http.Response. It returns an -// empty string slice if the passed http.Response is nil or the header does not exist. -func ExtractHeader(header string, resp *http.Response) []string { - if resp != nil && resp.Header != nil { - return resp.Header[http.CanonicalHeaderKey(header)] - } - return nil -} - -// ExtractHeaderValue extracts the first value of the specified header from the http.Response. It -// returns an empty string if the passed http.Response is nil or the header does not exist. -func ExtractHeaderValue(header string, resp *http.Response) string { - h := ExtractHeader(header, resp) - if len(h) > 0 { - return h[0] - } - return "" -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go deleted file mode 100644 index fa11dbed7..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go +++ /dev/null @@ -1,52 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// NewRetriableRequest returns a wrapper around an HTTP request that support retry logic. -func NewRetriableRequest(req *http.Request) *RetriableRequest { - return &RetriableRequest{req: req} -} - -// Request returns the wrapped HTTP request. -func (rr *RetriableRequest) Request() *http.Request { - return rr.req -} - -func (rr *RetriableRequest) prepareFromByteReader() (err error) { - // fall back to making a copy (only do this once) - b := []byte{} - if rr.req.ContentLength > 0 { - b = make([]byte, rr.req.ContentLength) - _, err = io.ReadFull(rr.req.Body, b) - if err != nil { - return err - } - } else { - b, err = ioutil.ReadAll(rr.req.Body) - if err != nil { - return err - } - } - rr.br = bytes.NewReader(b) - rr.req.Body = ioutil.NopCloser(rr.br) - return err -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go deleted file mode 100644 index 4c87030e8..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go +++ /dev/null @@ -1,55 +0,0 @@ -//go:build !go1.8 -// +build !go1.8 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package autorest - -import ( - "bytes" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.br != nil { - _, err = rr.br.Seek(0, 0 /*io.SeekStart*/) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go deleted file mode 100644 index 05847c08b..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go +++ /dev/null @@ -1,67 +0,0 @@ -//go:build go1.8 -// +build go1.8 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package autorest - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - rc io.ReadCloser - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.rc != nil { - rr.req.Body = rr.rc - } else if rr.br != nil { - _, err = rr.br.Seek(0, io.SeekStart) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.req.GetBody != nil { - // this will allow us to preserve the body without having to - // make a copy. note we need to do this on each iteration - rr.rc, err = rr.req.GetBody() - if err != nil { - return err - } - } else if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.GetBody = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go deleted file mode 100644 index 118de8141..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ /dev/null @@ -1,458 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "crypto/tls" - "fmt" - "log" - "math" - "net" - "net/http" - "net/http/cookiejar" - "strconv" - "sync" - "time" - - "github.com/Azure/go-autorest/logger" - "github.com/Azure/go-autorest/tracing" -) - -// there is one sender per TLS renegotiation type, i.e. count of tls.RenegotiationSupport enums -const defaultSendersCount = 3 - -type defaultSender struct { - sender Sender - init *sync.Once -} - -// each type of sender will be created on demand in sender() -var defaultSenders [defaultSendersCount]defaultSender - -func init() { - for i := 0; i < defaultSendersCount; i++ { - defaultSenders[i].init = &sync.Once{} - } -} - -// used as a key type in context.WithValue() -type ctxSendDecorators struct{} - -// WithSendDecorators adds the specified SendDecorators to the provided context. -// If no SendDecorators are provided the context is unchanged. -func WithSendDecorators(ctx context.Context, sendDecorator []SendDecorator) context.Context { - if len(sendDecorator) == 0 { - return ctx - } - return context.WithValue(ctx, ctxSendDecorators{}, sendDecorator) -} - -// GetSendDecorators returns the SendDecorators in the provided context or the provided default SendDecorators. -func GetSendDecorators(ctx context.Context, defaultSendDecorators ...SendDecorator) []SendDecorator { - inCtx := ctx.Value(ctxSendDecorators{}) - if sd, ok := inCtx.([]SendDecorator); ok { - return sd - } - return defaultSendDecorators -} - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibly decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(sender(tls.RenegotiateNever), decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} - -// Send sends, by means of the default http.Client, the passed http.Request, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// Send is a convenience method and not recommended for production. Advanced users should use -// SendWithSender, passing and sharing their own Sender (e.g., instance of http.Client). -// -// Send will not poll or retry requests. -func Send(r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return SendWithSender(sender(tls.RenegotiateNever), r, decorators...) -} - -// SendWithSender sends the passed http.Request, through the provided Sender, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// SendWithSender will not poll or retry requests. -func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return DecorateSender(s, decorators...).Do(r) -} - -func sender(renengotiation tls.RenegotiationSupport) Sender { - // note that we can't init defaultSenders in init() since it will - // execute before calling code has had a chance to enable tracing - defaultSenders[renengotiation].init.Do(func() { - // copied from http.DefaultTransport with a TLS minimum version. - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - ForceAttemptHTTP2: true, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, - Renegotiation: renengotiation, - }, - } - var roundTripper http.RoundTripper = transport - if tracing.IsEnabled() { - roundTripper = tracing.NewTransport(transport) - } - j, _ := cookiejar.New(nil) - defaultSenders[renengotiation].sender = &http.Client{Jar: j, Transport: roundTripper} - }) - return defaultSenders[renengotiation].sender -} - -// AfterDelay returns a SendDecorator that delays for the passed time.Duration before -// invoking the Sender. The delay may be terminated by closing the optional channel on the -// http.Request. If canceled, no further Senders are invoked. -func AfterDelay(d time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if !DelayForBackoff(d, 0, r.Context().Done()) { - return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") - } - return s.Do(r) - }) - } -} - -// AsIs returns a SendDecorator that invokes the passed Sender without modifying the http.Request. -func AsIs() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return s.Do(r) - }) - } -} - -// DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which -// it closes the response if the passed Sender returns an error and the response body exists. -func DoCloseIfError() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - Respond(resp, ByDiscardingBody(), ByClosing()) - } - return resp, err - }) - } -} - -// DoErrorIfStatusCode returns a SendDecorator that emits an error if the response StatusCode is -// among the set passed. Since these are artificial errors, the response body may still require -// closing. -func DoErrorIfStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorIfStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoErrorUnlessStatusCode returns a SendDecorator that emits an error unless the response -// StatusCode is among the set passed. Since these are artificial errors, the response body -// may still require closing. -func DoErrorUnlessStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoPollForStatusCodes returns a SendDecorator that polls if the http.Response contains one of the -// passed status codes. It expects the http.Response to contain a Location header providing the -// URL at which to poll (using GET) and will poll until the time passed is equal to or greater than -// the supplied duration. It will delay between requests for the duration specified in the -// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by -// closing the optional channel on the http.Request. -func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - resp, err = s.Do(r) - - if err == nil && ResponseHasStatusCode(resp, codes...) { - r, err = NewPollingRequestWithContext(r.Context(), resp) - - for err == nil && ResponseHasStatusCode(resp, codes...) { - Respond(resp, - ByDiscardingBody(), - ByClosing()) - resp, err = SendWithSender(s, r, - AfterDelay(GetRetryAfter(resp, delay))) - } - } - - return resp, err - }) - } -} - -// DoRetryForAttempts returns a SendDecorator that retries a failed request for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on -// the http.Request. -func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - for attempt := 0; attempt < attempts; attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - DrainResponseBody(resp) - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - logger.Instance.Writef(logger.LogError, "DoRetryForAttempts: received error for attempt %d: %v\n", attempt+1, err) - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// Count429AsRetry indicates that a 429 response should be included as a retry attempt. -var Count429AsRetry = true - -// Max429Delay is the maximum duration to wait between retries on a 429 if no Retry-After header was received. -var Max429Delay time.Duration - -// DoRetryForStatusCodes returns a SendDecorator that retries for specified statusCodes for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by cancelling the context on the http.Request. -// NOTE: Code http.StatusTooManyRequests (429) will *not* be counted against the number of attempts. -func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return doRetryForStatusCodesImpl(s, r, Count429AsRetry, attempts, backoff, 0, codes...) - }) - } -} - -// DoRetryForStatusCodesWithCap returns a SendDecorator that retries for specified statusCodes for up to the -// specified number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). To cap the maximum possible delay between iterations specify a value greater -// than zero for cap. Retrying may be canceled by cancelling the context on the http.Request. -func DoRetryForStatusCodesWithCap(attempts int, backoff, cap time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return doRetryForStatusCodesImpl(s, r, Count429AsRetry, attempts, backoff, cap, codes...) - }) - } -} - -func doRetryForStatusCodesImpl(s Sender, r *http.Request, count429 bool, attempts int, backoff, cap time.Duration, codes ...int) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - // Increment to add the first call (attempts denotes number of retries) - for attempt, delayCount := 0, 0; attempt < attempts+1; { - err = rr.Prepare() - if err != nil { - return - } - DrainResponseBody(resp) - resp, err = s.Do(rr.Request()) - // we want to retry if err is not nil (e.g. transient network failure). note that for failed authentication - // resp and err will both have a value, so in this case we don't want to retry as it will never succeed. - if err == nil && !ResponseHasStatusCode(resp, codes...) || IsTokenRefreshError(err) { - return resp, err - } - if err != nil { - logger.Instance.Writef(logger.LogError, "DoRetryForStatusCodes: received error for attempt %d: %v\n", attempt+1, err) - } - delayed := DelayWithRetryAfter(resp, r.Context().Done()) - // if this was a 429 set the delay cap as specified. - // applicable only in the absence of a retry-after header. - if resp != nil && resp.StatusCode == http.StatusTooManyRequests { - cap = Max429Delay - } - if !delayed && !DelayForBackoffWithCap(backoff, cap, delayCount, r.Context().Done()) { - return resp, r.Context().Err() - } - // when count429 == false don't count a 429 against the number - // of attempts so that we continue to retry until it succeeds - if count429 || (resp == nil || resp.StatusCode != http.StatusTooManyRequests) { - attempt++ - } - // delay count is tracked separately from attempts to - // ensure that 429 participates in exponential back-off - delayCount++ - } - return resp, err -} - -// DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header. -// The value of Retry-After can be either the number of seconds or a date in RFC1123 format. -// The function returns true after successfully waiting for the specified duration. If there is -// no Retry-After header or the wait is cancelled the return value is false. -func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool { - if resp == nil { - return false - } - var dur time.Duration - ra := resp.Header.Get("Retry-After") - if retryAfter, _ := strconv.Atoi(ra); retryAfter > 0 { - dur = time.Duration(retryAfter) * time.Second - } else if t, err := time.Parse(time.RFC1123, ra); err == nil { - dur = t.Sub(time.Now()) - } - if dur > 0 { - select { - case <-time.After(dur): - return true - case <-cancel: - return false - } - } - return false -} - -// DoRetryForDuration returns a SendDecorator that retries the request until the total time is equal -// to or greater than the specified duration, exponentially backing off between requests using the -// supplied backoff time.Duration (which may be zero). Retrying may be canceled by closing the -// optional channel on the http.Request. -func DoRetryForDuration(d time.Duration, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - end := time.Now().Add(d) - for attempt := 0; time.Now().Before(end); attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - DrainResponseBody(resp) - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - logger.Instance.Writef(logger.LogError, "DoRetryForDuration: received error for attempt %d: %v\n", attempt+1, err) - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// WithLogging returns a SendDecorator that implements simple before and after logging of the -// request. -func WithLogging(logger *log.Logger) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - logger.Printf("Sending %s %s", r.Method, r.URL) - resp, err := s.Do(r) - if err != nil { - logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) - } else { - logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) - } - return resp, err - }) - } -} - -// DelayForBackoff invokes time.After for the supplied backoff duration raised to the power of -// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set -// to zero for no delay. The delay may be canceled by closing the passed channel. If terminated early, -// returns false. -// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt -// count. -func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { - return DelayForBackoffWithCap(backoff, 0, attempt, cancel) -} - -// DelayForBackoffWithCap invokes time.After for the supplied backoff duration raised to the power of -// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set -// to zero for no delay. To cap the maximum possible delay specify a value greater than zero for cap. -// The delay may be canceled by closing the passed channel. If terminated early, returns false. -// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt -// count. -func DelayForBackoffWithCap(backoff, cap time.Duration, attempt int, cancel <-chan struct{}) bool { - d := time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second - if cap > 0 && d > cap { - d = cap - } - logger.Instance.Writef(logger.LogInfo, "DelayForBackoffWithCap: sleeping for %s\n", d) - select { - case <-time.After(d): - return true - case <-cancel: - return false - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go deleted file mode 100644 index 86694bd25..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go +++ /dev/null @@ -1,152 +0,0 @@ -/* -Package to provides helpers to ease working with pointer values of marshalled structures. -*/ -package to - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// String returns a string value for the passed string pointer. It returns the empty string if the -// pointer is nil. -func String(s *string) string { - if s != nil { - return *s - } - return "" -} - -// StringPtr returns a pointer to the passed string. -func StringPtr(s string) *string { - return &s -} - -// StringSlice returns a string slice value for the passed string slice pointer. It returns a nil -// slice if the pointer is nil. -func StringSlice(s *[]string) []string { - if s != nil { - return *s - } - return nil -} - -// StringSlicePtr returns a pointer to the passed string slice. -func StringSlicePtr(s []string) *[]string { - return &s -} - -// StringMap returns a map of strings built from the map of string pointers. The empty string is -// used for nil pointers. -func StringMap(msp map[string]*string) map[string]string { - ms := make(map[string]string, len(msp)) - for k, sp := range msp { - if sp != nil { - ms[k] = *sp - } else { - ms[k] = "" - } - } - return ms -} - -// StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings. -func StringMapPtr(ms map[string]string) *map[string]*string { - msp := make(map[string]*string, len(ms)) - for k, s := range ms { - msp[k] = StringPtr(s) - } - return &msp -} - -// Bool returns a bool value for the passed bool pointer. It returns false if the pointer is nil. -func Bool(b *bool) bool { - if b != nil { - return *b - } - return false -} - -// BoolPtr returns a pointer to the passed bool. -func BoolPtr(b bool) *bool { - return &b -} - -// Int returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int(i *int) int { - if i != nil { - return *i - } - return 0 -} - -// IntPtr returns a pointer to the passed int. -func IntPtr(i int) *int { - return &i -} - -// Int32 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int32(i *int32) int32 { - if i != nil { - return *i - } - return 0 -} - -// Int32Ptr returns a pointer to the passed int32. -func Int32Ptr(i int32) *int32 { - return &i -} - -// Int64 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int64(i *int64) int64 { - if i != nil { - return *i - } - return 0 -} - -// Int64Ptr returns a pointer to the passed int64. -func Int64Ptr(i int64) *int64 { - return &i -} - -// Float32 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float32(i *float32) float32 { - if i != nil { - return *i - } - return 0.0 -} - -// Float32Ptr returns a pointer to the passed float32. -func Float32Ptr(i float32) *float32 { - return &i -} - -// Float64 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float64(i *float64) float64 { - if i != nil { - return *i - } - return 0.0 -} - -// Float64Ptr returns a pointer to the passed float64. -func Float64Ptr(i float64) *float64 { - return &i -} - -// ByteSlicePtr returns a pointer to the passed byte slice. -func ByteSlicePtr(b []byte) *[]byte { - return &b -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go deleted file mode 100644 index b7310f6b8..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package to - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go deleted file mode 100644 index 3467b8fa6..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility.go +++ /dev/null @@ -1,232 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "reflect" - "strings" -) - -// EncodedAs is a series of constants specifying various data encodings -type EncodedAs string - -const ( - // EncodedAsJSON states that data is encoded as JSON - EncodedAsJSON EncodedAs = "JSON" - - // EncodedAsXML states that data is encoded as Xml - EncodedAsXML EncodedAs = "XML" -) - -// Decoder defines the decoding method json.Decoder and xml.Decoder share -type Decoder interface { - Decode(v interface{}) error -} - -// NewDecoder creates a new decoder appropriate to the passed encoding. -// encodedAs specifies the type of encoding and r supplies the io.Reader containing the -// encoded data. -func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { - if encodedAs == EncodedAsJSON { - return json.NewDecoder(r) - } else if encodedAs == EncodedAsXML { - return xml.NewDecoder(r) - } - return nil -} - -// CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy -// is especially useful if there is a chance the data will fail to decode. -// encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v -// is the decoding destination. -func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { - b := bytes.Buffer{} - return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) -} - -// TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. -// It utilizes io.TeeReader to copy the data read and has the same behavior when reading. -// Further, when it is closed, it ensures that rc is closed as well. -func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { - return &teeReadCloser{rc, io.TeeReader(rc, w)} -} - -type teeReadCloser struct { - rc io.ReadCloser - r io.Reader -} - -func (t *teeReadCloser) Read(p []byte) (int, error) { - return t.r.Read(p) -} - -func (t *teeReadCloser) Close() error { - return t.rc.Close() -} - -func containsInt(ints []int, n int) bool { - for _, i := range ints { - if i == n { - return true - } - } - return false -} - -func escapeValueStrings(m map[string]string) map[string]string { - for key, value := range m { - m[key] = url.QueryEscape(value) - } - return m -} - -func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string { - mapOfStrings := make(map[string]string) - for key, value := range mapOfInterface { - mapOfStrings[key] = ensureValueString(value) - } - return mapOfStrings -} - -func ensureValueString(value interface{}) string { - if value == nil { - return "" - } - switch v := value.(type) { - case string: - return v - case []byte: - return string(v) - default: - return fmt.Sprintf("%v", v) - } -} - -// MapToValues method converts map[string]interface{} to url.Values. -func MapToValues(m map[string]interface{}) url.Values { - v := url.Values{} - for key, value := range m { - x := reflect.ValueOf(value) - if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { - for i := 0; i < x.Len(); i++ { - v.Add(key, ensureValueString(x.Index(i))) - } - } else { - v.Add(key, ensureValueString(value)) - } - } - return v -} - -// AsStringSlice method converts interface{} to []string. -// s must be of type slice or array or an error is returned. -// Each element of s will be converted to its string representation. -func AsStringSlice(s interface{}) ([]string, error) { - v := reflect.ValueOf(s) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return nil, NewError("autorest", "AsStringSlice", "the value's type is not a slice or array.") - } - stringSlice := make([]string, 0, v.Len()) - - for i := 0; i < v.Len(); i++ { - stringSlice = append(stringSlice, fmt.Sprintf("%v", v.Index(i))) - } - return stringSlice, nil -} - -// String method converts interface v to string. If interface is a list, it -// joins list elements using the separator. Note that only sep[0] will be used for -// joining if any separator is specified. -func String(v interface{}, sep ...string) string { - if len(sep) == 0 { - return ensureValueString(v) - } - stringSlice, ok := v.([]string) - if ok == false { - var err error - stringSlice, err = AsStringSlice(v) - if err != nil { - panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err)) - } - } - return ensureValueString(strings.Join(stringSlice, sep[0])) -} - -// Encode method encodes url path and query parameters. -func Encode(location string, v interface{}, sep ...string) string { - s := String(v, sep...) - switch strings.ToLower(location) { - case "path": - return pathEscape(s) - case "query": - return queryEscape(s) - default: - return s - } -} - -func pathEscape(s string) string { - return strings.Replace(url.QueryEscape(s), "+", "%20", -1) -} - -func queryEscape(s string) string { - return url.QueryEscape(s) -} - -// ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't). -// This is mainly useful for long-running operations that use the Azure-AsyncOperation -// header, so we change the initial PUT into a GET to retrieve the final result. -func ChangeToGet(req *http.Request) *http.Request { - req.Method = "GET" - req.Body = nil - req.ContentLength = 0 - req.Header.Del("Content-Length") - return req -} - -// IsTemporaryNetworkError returns true if the specified error is a temporary network error or false -// if it's not. If the error doesn't implement the net.Error interface the return value is true. -func IsTemporaryNetworkError(err error) bool { - if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) { - return true - } - return false -} - -// DrainResponseBody reads the response body then closes it. -func DrainResponseBody(resp *http.Response) error { - if resp != nil && resp.Body != nil { - _, err := io.Copy(ioutil.Discard, resp.Body) - resp.Body.Close() - return err - } - return nil -} - -func setHeader(r *http.Request, key, value string) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(key, value) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility_1.13.go b/vendor/github.com/Azure/go-autorest/autorest/utility_1.13.go deleted file mode 100644 index 3133fcc08..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility_1.13.go +++ /dev/null @@ -1,30 +0,0 @@ -//go:build go1.13 -// +build go1.13 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package autorest - -import ( - "errors" - - "github.com/Azure/go-autorest/autorest/adal" -) - -// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError interface. -func IsTokenRefreshError(err error) bool { - var tre adal.TokenRefreshError - return errors.As(err, &tre) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility_legacy.go b/vendor/github.com/Azure/go-autorest/autorest/utility_legacy.go deleted file mode 100644 index 851e152db..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility_legacy.go +++ /dev/null @@ -1,32 +0,0 @@ -//go:build !go1.13 -// +build !go1.13 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package autorest - -import "github.com/Azure/go-autorest/autorest/adal" - -// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError -// interface. If err is a DetailedError it will walk the chain of Original errors. -func IsTokenRefreshError(err error) bool { - if _, ok := err.(adal.TokenRefreshError); ok { - return true - } - if de, ok := err.(DetailedError); ok { - return IsTokenRefreshError(de.Original) - } - return false -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/error.go b/vendor/github.com/Azure/go-autorest/autorest/validation/error.go deleted file mode 100644 index fed156dbf..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/error.go +++ /dev/null @@ -1,48 +0,0 @@ -package validation - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" -) - -// Error is the type that's returned when the validation of an APIs arguments constraints fails. -type Error struct { - // PackageType is the package type of the object emitting the error. For types, the value - // matches that produced the the '%T' format specifier of the fmt package. For other elements, - // such as functions, it is just the package name (e.g., "autorest"). - PackageType string - - // Method is the name of the method raising the error. - Method string - - // Message is the error message. - Message string -} - -// Error returns a string containing the details of the validation failure. -func (e Error) Error() string { - return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message) -} - -// NewError creates a new Error object with the specified parameters. -// message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) Error { - return Error{ - PackageType: packageType, - Method: method, - Message: fmt.Sprintf(message, args...), - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go deleted file mode 100644 index cf1436291..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package validation - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go b/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go deleted file mode 100644 index ff41cfe07..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go +++ /dev/null @@ -1,406 +0,0 @@ -/* -Package validation provides methods for validating parameter value using reflection. -*/ -package validation - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "reflect" - "regexp" - "strings" -) - -// Disabled controls if parameter validation should be globally disabled. The default is false. -var Disabled bool - -// Constraint stores constraint name, target field name -// Rule and chain validations. -type Constraint struct { - - // Target field name for validation. - Target string - - // Constraint name e.g. minLength, MaxLength, Pattern, etc. - Name string - - // Rule for constraint e.g. greater than 10, less than 5 etc. - Rule interface{} - - // Chain Validations for struct type - Chain []Constraint -} - -// Validation stores parameter-wise validation. -type Validation struct { - TargetValue interface{} - Constraints []Constraint -} - -// Constraint list -const ( - Empty = "Empty" - Null = "Null" - ReadOnly = "ReadOnly" - Pattern = "Pattern" - MaxLength = "MaxLength" - MinLength = "MinLength" - MaxItems = "MaxItems" - MinItems = "MinItems" - MultipleOf = "MultipleOf" - UniqueItems = "UniqueItems" - InclusiveMaximum = "InclusiveMaximum" - ExclusiveMaximum = "ExclusiveMaximum" - ExclusiveMinimum = "ExclusiveMinimum" - InclusiveMinimum = "InclusiveMinimum" -) - -// Validate method validates constraints on parameter -// passed in validation array. -func Validate(m []Validation) error { - if Disabled { - return nil - } - for _, item := range m { - v := reflect.ValueOf(item.TargetValue) - for _, constraint := range item.Constraints { - var err error - switch v.Kind() { - case reflect.Ptr: - err = validatePtr(v, constraint) - case reflect.String: - err = validateString(v, constraint) - case reflect.Struct: - err = validateStruct(v, constraint) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - err = validateInt(v, constraint) - case reflect.Float32, reflect.Float64: - err = validateFloat(v, constraint) - case reflect.Array, reflect.Slice, reflect.Map: - err = validateArrayMap(v, constraint) - default: - err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) - } - - if err != nil { - return err - } - } - } - return nil -} - -func validateStruct(x reflect.Value, v Constraint, name ...string) error { - //Get field name from target name which is in format a.b.c - s := strings.Split(v.Target, ".") - f := x.FieldByName(s[len(s)-1]) - if isZero(f) { - return createError(x, v, fmt.Sprintf("field %q doesn't exist", v.Target)) - } - - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(f), - Constraints: []Constraint{v}, - }, - }) -} - -func validatePtr(x reflect.Value, v Constraint) error { - if v.Name == ReadOnly { - if !x.IsNil() { - return createError(x.Elem(), v, "readonly parameter; must send as nil or empty in request") - } - return nil - } - if x.IsNil() { - return checkNil(x, v) - } - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x.Elem()), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func validateInt(x reflect.Value, v Constraint) error { - i := x.Int() - r, ok := toInt64(v.Rule) - if !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - switch v.Name { - case MultipleOf: - if i%r != 0 { - return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) - } - case ExclusiveMinimum: - if i <= r { - return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) - } - case ExclusiveMaximum: - if i >= r { - return createError(x, v, fmt.Sprintf("value must be less than %v", r)) - } - case InclusiveMinimum: - if i < r { - return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) - } - case InclusiveMaximum: - if i > r { - return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) - } - default: - return createError(x, v, fmt.Sprintf("constraint %v is not applicable for type integer", v.Name)) - } - return nil -} - -func validateFloat(x reflect.Value, v Constraint) error { - f := x.Float() - r, ok := v.Rule.(float64) - if !ok { - return createError(x, v, fmt.Sprintf("rule must be float value for %v constraint; got: %v", v.Name, v.Rule)) - } - switch v.Name { - case ExclusiveMinimum: - if f <= r { - return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) - } - case ExclusiveMaximum: - if f >= r { - return createError(x, v, fmt.Sprintf("value must be less than %v", r)) - } - case InclusiveMinimum: - if f < r { - return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) - } - case InclusiveMaximum: - if f > r { - return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) - } - default: - return createError(x, v, fmt.Sprintf("constraint %s is not applicable for type float", v.Name)) - } - return nil -} - -func validateString(x reflect.Value, v Constraint) error { - s := x.String() - switch v.Name { - case Empty: - if len(s) == 0 { - return checkEmpty(x, v) - } - case Pattern: - reg, err := regexp.Compile(v.Rule.(string)) - if err != nil { - return createError(x, v, err.Error()) - } - if !reg.MatchString(s) { - return createError(x, v, fmt.Sprintf("value doesn't match pattern %v", v.Rule)) - } - case MaxLength: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - if len(s) > v.Rule.(int) { - return createError(x, v, fmt.Sprintf("value length must be less than or equal to %v", v.Rule)) - } - case MinLength: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - if len(s) < v.Rule.(int) { - return createError(x, v, fmt.Sprintf("value length must be greater than or equal to %v", v.Rule)) - } - case ReadOnly: - if len(s) > 0 { - return createError(reflect.ValueOf(s), v, "readonly parameter; must send as nil or empty in request") - } - default: - return createError(x, v, fmt.Sprintf("constraint %s is not applicable to string type", v.Name)) - } - - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func validateArrayMap(x reflect.Value, v Constraint) error { - switch v.Name { - case Null: - if x.IsNil() { - return checkNil(x, v) - } - case Empty: - if x.IsNil() || x.Len() == 0 { - return checkEmpty(x, v) - } - case MaxItems: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) - } - if x.Len() > v.Rule.(int) { - return createError(x, v, fmt.Sprintf("maximum item limit is %v; got: %v", v.Rule, x.Len())) - } - case MinItems: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) - } - if x.Len() < v.Rule.(int) { - return createError(x, v, fmt.Sprintf("minimum item limit is %v; got: %v", v.Rule, x.Len())) - } - case UniqueItems: - if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { - if !checkForUniqueInArray(x) { - return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) - } - } else if x.Kind() == reflect.Map { - if !checkForUniqueInMap(x) { - return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) - } - } else { - return createError(x, v, fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", v.Name, x.Kind())) - } - case ReadOnly: - if x.Len() != 0 { - return createError(x, v, "readonly parameter; must send as nil or empty in request") - } - case Pattern: - reg, err := regexp.Compile(v.Rule.(string)) - if err != nil { - return createError(x, v, err.Error()) - } - keys := x.MapKeys() - for _, k := range keys { - if !reg.MatchString(k.String()) { - return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.Rule)) - } - } - default: - return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.Name)) - } - - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func checkNil(x reflect.Value, v Constraint) error { - if _, ok := v.Rule.(bool); !ok { - return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) - } - if v.Rule.(bool) { - return createError(x, v, "value can not be null; required parameter") - } - return nil -} - -func checkEmpty(x reflect.Value, v Constraint) error { - if _, ok := v.Rule.(bool); !ok { - return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) - } - - if v.Rule.(bool) { - return createError(x, v, "value can not be null or empty; required parameter") - } - return nil -} - -func checkForUniqueInArray(x reflect.Value) bool { - if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { - return false - } - arrOfInterface := make([]interface{}, x.Len()) - - for i := 0; i < x.Len(); i++ { - arrOfInterface[i] = x.Index(i).Interface() - } - - m := make(map[interface{}]bool) - for _, val := range arrOfInterface { - if m[val] { - return false - } - m[val] = true - } - return true -} - -func checkForUniqueInMap(x reflect.Value) bool { - if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { - return false - } - mapOfInterface := make(map[interface{}]interface{}, x.Len()) - - keys := x.MapKeys() - for _, k := range keys { - mapOfInterface[k.Interface()] = x.MapIndex(k).Interface() - } - - m := make(map[interface{}]bool) - for _, val := range mapOfInterface { - if m[val] { - return false - } - m[val] = true - } - return true -} - -func getInterfaceValue(x reflect.Value) interface{} { - if x.Kind() == reflect.Invalid { - return nil - } - return x.Interface() -} - -func isZero(x interface{}) bool { - return x == reflect.Zero(reflect.TypeOf(x)).Interface() -} - -func createError(x reflect.Value, v Constraint, err string) error { - return fmt.Errorf("autorest/validation: validation failed: parameter=%s constraint=%s value=%#v details: %s", - v.Target, v.Name, getInterfaceValue(x), err) -} - -func toInt64(v interface{}) (int64, bool) { - if i64, ok := v.(int64); ok { - return i64, true - } - // older generators emit max constants as int, so if int64 fails fall back to int - if i32, ok := v.(int); ok { - return int64(i32), true - } - return 0, false -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go deleted file mode 100644 index 713e23581..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/version.go +++ /dev/null @@ -1,41 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "runtime" -) - -const number = "v14.2.1" - -var ( - userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", - runtime.Version(), - runtime.GOARCH, - runtime.GOOS, - number, - ) -) - -// UserAgent returns a string containing the Go version, system architecture and OS, and the go-autorest version. -func UserAgent() string { - return userAgent -} - -// Version returns the semantic version (see http://semver.org). -func Version() string { - return number -} diff --git a/vendor/github.com/Azure/go-autorest/azure-pipelines.yml b/vendor/github.com/Azure/go-autorest/azure-pipelines.yml deleted file mode 100644 index 6fb8404fd..000000000 --- a/vendor/github.com/Azure/go-autorest/azure-pipelines.yml +++ /dev/null @@ -1,105 +0,0 @@ -variables: - GOPATH: '$(system.defaultWorkingDirectory)/work' - sdkPath: '$(GOPATH)/src/github.com/$(build.repository.name)' - -jobs: - - job: 'goautorest' - displayName: 'Run go-autorest CI Checks' - - strategy: - matrix: - Linux_Go113: - vm.image: 'ubuntu-18.04' - go.version: '1.13' - Linux_Go114: - vm.image: 'ubuntu-18.04' - go.version: '1.14' - - pool: - vmImage: '$(vm.image)' - - steps: - - task: GoTool@0 - inputs: - version: '$(go.version)' - displayName: "Select Go Version" - - - script: | - set -e - mkdir -p '$(GOPATH)/bin' - mkdir -p '$(sdkPath)' - shopt -s extglob - mv !(work) '$(sdkPath)' - echo '##vso[task.prependpath]$(GOPATH)/bin' - displayName: 'Create Go Workspace' - - - script: | - set -e - curl -sSL https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - dep ensure -v - go install ./vendor/golang.org/x/lint/golint - go get github.com/jstemmer/go-junit-report - go get github.com/axw/gocov/gocov - go get github.com/AlekSi/gocov-xml - go get -u github.com/matm/gocov-html - workingDirectory: '$(sdkPath)' - displayName: 'Install Dependencies' - - - script: | - go vet ./autorest/... - go vet ./logger/... - go vet ./tracing/... - workingDirectory: '$(sdkPath)' - displayName: 'Vet' - - - script: | - go build -v ./autorest/... - go build -v ./logger/... - go build -v ./tracing/... - workingDirectory: '$(sdkPath)' - displayName: 'Build' - - - script: | - set -e - go test -race -v -coverprofile=coverage.txt -covermode atomic ./autorest/... ./logger/... ./tracing/... 2>&1 | go-junit-report > report.xml - gocov convert coverage.txt > coverage.json - gocov-xml < coverage.json > coverage.xml - gocov-html < coverage.json > coverage.html - workingDirectory: '$(sdkPath)' - displayName: 'Run Tests' - - - script: grep -L -r --include *.go --exclude-dir vendor -P "Copyright (\d{4}|\(c\)) Microsoft" ./ | tee >&2 - workingDirectory: '$(sdkPath)' - displayName: 'Copyright Header Check' - failOnStderr: true - condition: succeededOrFailed() - - - script: | - gofmt -s -l -w ./autorest/. >&2 - gofmt -s -l -w ./logger/. >&2 - gofmt -s -l -w ./tracing/. >&2 - workingDirectory: '$(sdkPath)' - displayName: 'Format Check' - failOnStderr: true - condition: succeededOrFailed() - - - script: | - golint ./autorest/... >&2 - golint ./logger/... >&2 - golint ./tracing/... >&2 - workingDirectory: '$(sdkPath)' - displayName: 'Linter Check' - failOnStderr: true - condition: succeededOrFailed() - - - task: PublishTestResults@2 - inputs: - testRunner: JUnit - testResultsFiles: $(sdkPath)/report.xml - failTaskOnFailedTests: true - - - task: PublishCodeCoverageResults@1 - inputs: - codeCoverageTool: Cobertura - summaryFileLocation: $(sdkPath)/coverage.xml - additionalCodeCoverageFiles: $(sdkPath)/coverage.html diff --git a/vendor/github.com/Azure/go-autorest/doc.go b/vendor/github.com/Azure/go-autorest/doc.go deleted file mode 100644 index 99ae6ca98..000000000 --- a/vendor/github.com/Azure/go-autorest/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Package go-autorest provides an HTTP request client for use with Autorest-generated API client packages. -*/ -package go_autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/logger/LICENSE b/vendor/github.com/Azure/go-autorest/logger/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/logger/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/logger/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/logger/go_mod_tidy_hack.go deleted file mode 100644 index 0aa27680d..000000000 --- a/vendor/github.com/Azure/go-autorest/logger/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package logger - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/logger/logger.go b/vendor/github.com/Azure/go-autorest/logger/logger.go deleted file mode 100644 index 2f5d8cc1a..000000000 --- a/vendor/github.com/Azure/go-autorest/logger/logger.go +++ /dev/null @@ -1,337 +0,0 @@ -package logger - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "strings" - "sync" - "time" -) - -// LevelType tells a logger the minimum level to log. When code reports a log entry, -// the LogLevel indicates the level of the log entry. The logger only records entries -// whose level is at least the level it was told to log. See the Log* constants. -// For example, if a logger is configured with LogError, then LogError, LogPanic, -// and LogFatal entries will be logged; lower level entries are ignored. -type LevelType uint32 - -const ( - // LogNone tells a logger not to log any entries passed to it. - LogNone LevelType = iota - - // LogFatal tells a logger to log all LogFatal entries passed to it. - LogFatal - - // LogPanic tells a logger to log all LogPanic and LogFatal entries passed to it. - LogPanic - - // LogError tells a logger to log all LogError, LogPanic and LogFatal entries passed to it. - LogError - - // LogWarning tells a logger to log all LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogWarning - - // LogInfo tells a logger to log all LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogInfo - - // LogDebug tells a logger to log all LogDebug, LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogDebug - - // LogAuth is a special case of LogDebug, it tells a logger to also log the body of an authentication request and response. - // NOTE: this can disclose sensitive information, use with care. - LogAuth -) - -const ( - logNone = "NONE" - logFatal = "FATAL" - logPanic = "PANIC" - logError = "ERROR" - logWarning = "WARNING" - logInfo = "INFO" - logDebug = "DEBUG" - logAuth = "AUTH" - logUnknown = "UNKNOWN" -) - -// ParseLevel converts the specified string into the corresponding LevelType. -func ParseLevel(s string) (lt LevelType, err error) { - switch strings.ToUpper(s) { - case logFatal: - lt = LogFatal - case logPanic: - lt = LogPanic - case logError: - lt = LogError - case logWarning: - lt = LogWarning - case logInfo: - lt = LogInfo - case logDebug: - lt = LogDebug - case logAuth: - lt = LogAuth - default: - err = fmt.Errorf("bad log level '%s'", s) - } - return -} - -// String implements the stringer interface for LevelType. -func (lt LevelType) String() string { - switch lt { - case LogNone: - return logNone - case LogFatal: - return logFatal - case LogPanic: - return logPanic - case LogError: - return logError - case LogWarning: - return logWarning - case LogInfo: - return logInfo - case LogDebug: - return logDebug - case LogAuth: - return logAuth - default: - return logUnknown - } -} - -// Filter defines functions for filtering HTTP request/response content. -type Filter struct { - // URL returns a potentially modified string representation of a request URL. - URL func(u *url.URL) string - - // Header returns a potentially modified set of values for the specified key. - // To completely exclude the header key/values return false. - Header func(key string, val []string) (bool, []string) - - // Body returns a potentially modified request/response body. - Body func(b []byte) []byte -} - -func (f Filter) processURL(u *url.URL) string { - if f.URL == nil { - return u.String() - } - return f.URL(u) -} - -func (f Filter) processHeader(k string, val []string) (bool, []string) { - if f.Header == nil { - return true, val - } - return f.Header(k, val) -} - -func (f Filter) processBody(b []byte) []byte { - if f.Body == nil { - return b - } - return f.Body(b) -} - -// Writer defines methods for writing to a logging facility. -type Writer interface { - // Writeln writes the specified message with the standard log entry header and new-line character. - Writeln(level LevelType, message string) - - // Writef writes the specified format specifier with the standard log entry header and no new-line character. - Writef(level LevelType, format string, a ...interface{}) - - // WriteRequest writes the specified HTTP request to the logger if the log level is greater than - // or equal to LogInfo. The request body, if set, is logged at level LogDebug or higher. - // Custom filters can be specified to exclude URL, header, and/or body content from the log. - // By default no request content is excluded. - WriteRequest(req *http.Request, filter Filter) - - // WriteResponse writes the specified HTTP response to the logger if the log level is greater than - // or equal to LogInfo. The response body, if set, is logged at level LogDebug or higher. - // Custom filters can be specified to exclude URL, header, and/or body content from the log. - // By default no response content is excluded. - WriteResponse(resp *http.Response, filter Filter) -} - -// Instance is the default log writer initialized during package init. -// This can be replaced with a custom implementation as required. -var Instance Writer - -// default log level -var logLevel = LogNone - -// Level returns the value specified in AZURE_GO_AUTOREST_LOG_LEVEL. -// If no value was specified the default value is LogNone. -// Custom loggers can call this to retrieve the configured log level. -func Level() LevelType { - return logLevel -} - -func init() { - // separated for testing purposes - initDefaultLogger() -} - -func initDefaultLogger() { - // init with nilLogger so callers don't have to do a nil check on Default - Instance = nilLogger{} - llStr := strings.ToLower(os.Getenv("AZURE_GO_SDK_LOG_LEVEL")) - if llStr == "" { - return - } - var err error - logLevel, err = ParseLevel(llStr) - if err != nil { - fmt.Fprintf(os.Stderr, "go-autorest: failed to parse log level: %s\n", err.Error()) - return - } - if logLevel == LogNone { - return - } - // default to stderr - dest := os.Stderr - lfStr := os.Getenv("AZURE_GO_SDK_LOG_FILE") - if strings.EqualFold(lfStr, "stdout") { - dest = os.Stdout - } else if lfStr != "" { - lf, err := os.Create(lfStr) - if err == nil { - dest = lf - } else { - fmt.Fprintf(os.Stderr, "go-autorest: failed to create log file, using stderr: %s\n", err.Error()) - } - } - Instance = fileLogger{ - logLevel: logLevel, - mu: &sync.Mutex{}, - logFile: dest, - } -} - -// the nil logger does nothing -type nilLogger struct{} - -func (nilLogger) Writeln(LevelType, string) {} - -func (nilLogger) Writef(LevelType, string, ...interface{}) {} - -func (nilLogger) WriteRequest(*http.Request, Filter) {} - -func (nilLogger) WriteResponse(*http.Response, Filter) {} - -// A File is used instead of a Logger so the stream can be flushed after every write. -type fileLogger struct { - logLevel LevelType - mu *sync.Mutex // for synchronizing writes to logFile - logFile *os.File -} - -func (fl fileLogger) Writeln(level LevelType, message string) { - fl.Writef(level, "%s\n", message) -} - -func (fl fileLogger) Writef(level LevelType, format string, a ...interface{}) { - if fl.logLevel >= level { - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprintf(fl.logFile, "%s %s", entryHeader(level), fmt.Sprintf(format, a...)) - fl.logFile.Sync() - } -} - -func (fl fileLogger) WriteRequest(req *http.Request, filter Filter) { - if req == nil || fl.logLevel < LogInfo { - return - } - b := &bytes.Buffer{} - fmt.Fprintf(b, "%s REQUEST: %s %s\n", entryHeader(LogInfo), req.Method, filter.processURL(req.URL)) - // dump headers - for k, v := range req.Header { - if ok, mv := filter.processHeader(k, v); ok { - fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ",")) - } - } - if fl.shouldLogBody(req.Header, req.Body) { - // dump body - body, err := ioutil.ReadAll(req.Body) - if err == nil { - fmt.Fprintln(b, string(filter.processBody(body))) - if nc, ok := req.Body.(io.Seeker); ok { - // rewind to the beginning - nc.Seek(0, io.SeekStart) - } else { - // recreate the body - req.Body = ioutil.NopCloser(bytes.NewReader(body)) - } - } else { - fmt.Fprintf(b, "failed to read body: %v\n", err) - } - } - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprint(fl.logFile, b.String()) - fl.logFile.Sync() -} - -func (fl fileLogger) WriteResponse(resp *http.Response, filter Filter) { - if resp == nil || fl.logLevel < LogInfo { - return - } - b := &bytes.Buffer{} - fmt.Fprintf(b, "%s RESPONSE: %d %s\n", entryHeader(LogInfo), resp.StatusCode, filter.processURL(resp.Request.URL)) - // dump headers - for k, v := range resp.Header { - if ok, mv := filter.processHeader(k, v); ok { - fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ",")) - } - } - if fl.shouldLogBody(resp.Header, resp.Body) { - // dump body - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err == nil { - fmt.Fprintln(b, string(filter.processBody(body))) - resp.Body = ioutil.NopCloser(bytes.NewReader(body)) - } else { - fmt.Fprintf(b, "failed to read body: %v\n", err) - } - } - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprint(fl.logFile, b.String()) - fl.logFile.Sync() -} - -// returns true if the provided body should be included in the log -func (fl fileLogger) shouldLogBody(header http.Header, body io.ReadCloser) bool { - ct := header.Get("Content-Type") - return fl.logLevel >= LogDebug && body != nil && !strings.Contains(ct, "application/octet-stream") -} - -// creates standard header for log entries, it contains a timestamp and the log level -func entryHeader(level LevelType) string { - // this format provides a fixed number of digits so the size of the timestamp is constant - return fmt.Sprintf("(%s) %s:", time.Now().Format("2006-01-02T15:04:05.0000000Z07:00"), level.String()) -} diff --git a/vendor/github.com/Azure/go-autorest/tracing/LICENSE b/vendor/github.com/Azure/go-autorest/tracing/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/tracing/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/tracing/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/tracing/go_mod_tidy_hack.go deleted file mode 100644 index e163975cd..000000000 --- a/vendor/github.com/Azure/go-autorest/tracing/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package tracing - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/tracing/tracing.go b/vendor/github.com/Azure/go-autorest/tracing/tracing.go deleted file mode 100644 index 0e7a6e962..000000000 --- a/vendor/github.com/Azure/go-autorest/tracing/tracing.go +++ /dev/null @@ -1,67 +0,0 @@ -package tracing - -// Copyright 2018 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "net/http" -) - -// Tracer represents an HTTP tracing facility. -type Tracer interface { - NewTransport(base *http.Transport) http.RoundTripper - StartSpan(ctx context.Context, name string) context.Context - EndSpan(ctx context.Context, httpStatusCode int, err error) -} - -var ( - tracer Tracer -) - -// Register will register the provided Tracer. Pass nil to unregister a Tracer. -func Register(t Tracer) { - tracer = t -} - -// IsEnabled returns true if a Tracer has been registered. -func IsEnabled() bool { - return tracer != nil -} - -// NewTransport creates a new instrumenting http.RoundTripper for the -// registered Tracer. If no Tracer has been registered it returns nil. -func NewTransport(base *http.Transport) http.RoundTripper { - if tracer != nil { - return tracer.NewTransport(base) - } - return nil -} - -// StartSpan starts a trace span with the specified name, associating it with the -// provided context. Has no effect if a Tracer has not been registered. -func StartSpan(ctx context.Context, name string) context.Context { - if tracer != nil { - return tracer.StartSpan(ctx, name) - } - return ctx -} - -// EndSpan ends a previously started span stored in the context. -// Has no effect if a Tracer has not been registered. -func EndSpan(ctx context.Context, httpStatusCode int, err error) { - if tracer != nil { - tracer.EndSpan(ctx, httpStatusCode, err) - } -} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/LICENSE b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/LICENSE new file mode 100644 index 000000000..3d8b93bc7 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache/cache.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache/cache.go new file mode 100644 index 000000000..19210883b --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache/cache.go @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package cache allows third parties to implement external storage for caching token data +for distributed systems or multiple local applications access. + +The data stored and extracted will represent the entire cache. Therefore it is recommended +one msal instance per user. This data is considered opaque and there are no guarantees to +implementers on the format being passed. +*/ +package cache + +import "context" + +// Marshaler marshals data from an internal cache to bytes that can be stored. +type Marshaler interface { + Marshal() ([]byte, error) +} + +// Unmarshaler unmarshals data from a storage medium into the internal cache, overwriting it. +type Unmarshaler interface { + Unmarshal([]byte) error +} + +// Serializer can serialize the cache to binary or from binary into the cache. +type Serializer interface { + Marshaler + Unmarshaler +} + +// ExportHints are suggestions for storing data. +type ExportHints struct { + // PartitionKey is a suggested key for partitioning the cache + PartitionKey string +} + +// ReplaceHints are suggestions for loading data. +type ReplaceHints struct { + // PartitionKey is a suggested key for partitioning the cache + PartitionKey string +} + +// ExportReplace exports and replaces in-memory cache data. It doesn't support nil Context or +// define the outcome of passing one. A Context without a timeout must receive a default timeout +// specified by the implementor. Retries must be implemented inside the implementation. +type ExportReplace interface { + // Replace replaces the cache with what is in external storage. Implementors should honor + // Context cancellations and return context.Canceled or context.DeadlineExceeded in those cases. + Replace(ctx context.Context, cache Unmarshaler, hints ReplaceHints) error + // Export writes the binary representation of the cache (cache.Marshal()) to external storage. + // This is considered opaque. Context cancellations should be honored as in Replace. + Export(ctx context.Context, cache Marshaler, hints ExportHints) error +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go new file mode 100644 index 000000000..1841d146f --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go @@ -0,0 +1,719 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package confidential provides a client for authentication of "confidential" applications. +A "confidential" application is defined as an app that run on servers. They are considered +difficult to access and for that reason capable of keeping an application secret. +Confidential clients can hold configuration-time secrets. +*/ +package confidential + +import ( + "context" + "crypto" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "errors" + "fmt" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +/* +Design note: + +confidential.Client uses base.Client as an embedded type. base.Client statically assigns its attributes +during creation. As it doesn't have any pointers in it, anything borrowed from it, such as +Base.AuthParams is a copy that is free to be manipulated here. + +Duplicate Calls shared between public.Client and this package: +There is some duplicate call options provided here that are the same as in public.Client . This +is a design choices. Go proverb(https://www.youtube.com/watch?v=PAAkCSZUG1c&t=9m28s): +"a little copying is better than a little dependency". Yes, we could have another package with +shared options (fail). That divides like 2 options from all others which makes the user look +through more docs. We can have all clients in one package, but I think separate packages +here makes for better naming (public.Client vs client.PublicClient). So I chose a little +duplication. + +.Net People, Take note on X509: +This uses x509.Certificates and private keys. x509 does not store private keys. .Net +has some x509.Certificate2 thing that has private keys, but that is just some bullcrap that .Net +added, it doesn't exist in real life. As such I've put a PEM decoder into here. +*/ + +// TODO(msal): This should have example code for each method on client using Go's example doc framework. +// base usage details should be include in the package documentation. + +// AuthResult contains the results of one token acquisition operation. +// For details see https://aka.ms/msal-net-authenticationresult +type AuthResult = base.AuthResult + +type AuthenticationScheme = authority.AuthenticationScheme + +type Account = shared.Account + +// CertFromPEM converts a PEM file (.pem or .key) for use with [NewCredFromCert]. The file +// must contain the public certificate and the private key. If a PEM block is encrypted and +// password is not an empty string, it attempts to decrypt the PEM blocks using the password. +// Multiple certs are due to certificate chaining for use cases like TLS that sign from root to leaf. +func CertFromPEM(pemData []byte, password string) ([]*x509.Certificate, crypto.PrivateKey, error) { + var certs []*x509.Certificate + var priv crypto.PrivateKey + for { + block, rest := pem.Decode(pemData) + if block == nil { + break + } + + //nolint:staticcheck // x509.IsEncryptedPEMBlock and x509.DecryptPEMBlock are deprecated. They are used here only to support a usecase. + if x509.IsEncryptedPEMBlock(block) { + b, err := x509.DecryptPEMBlock(block, []byte(password)) + if err != nil { + return nil, nil, fmt.Errorf("could not decrypt encrypted PEM block: %v", err) + } + block, _ = pem.Decode(b) + if block == nil { + return nil, nil, fmt.Errorf("encounter encrypted PEM block that did not decode") + } + } + + switch block.Type { + case "CERTIFICATE": + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, nil, fmt.Errorf("block labelled 'CERTIFICATE' could not be parsed by x509: %v", err) + } + certs = append(certs, cert) + case "PRIVATE KEY": + if priv != nil { + return nil, nil, errors.New("found multiple private key blocks") + } + + var err error + priv, err = x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, nil, fmt.Errorf("could not decode private key: %v", err) + } + case "RSA PRIVATE KEY": + if priv != nil { + return nil, nil, errors.New("found multiple private key blocks") + } + var err error + priv, err = x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, nil, fmt.Errorf("could not decode private key: %v", err) + } + } + pemData = rest + } + + if len(certs) == 0 { + return nil, nil, fmt.Errorf("no certificates found") + } + + if priv == nil { + return nil, nil, fmt.Errorf("no private key found") + } + + return certs, priv, nil +} + +// AssertionRequestOptions has required information for client assertion claims +type AssertionRequestOptions = exported.AssertionRequestOptions + +// Credential represents the credential used in confidential client flows. +type Credential struct { + secret string + + cert *x509.Certificate + key crypto.PrivateKey + x5c []string + + assertionCallback func(context.Context, AssertionRequestOptions) (string, error) + + tokenProvider func(context.Context, TokenProviderParameters) (TokenProviderResult, error) +} + +// toInternal returns the accesstokens.Credential that is used internally. The current structure of the +// code requires that client.go, requests.go and confidential.go share a credential type without +// having import recursion. That requires the type used between is in a shared package. Therefore +// we have this. +func (c Credential) toInternal() (*accesstokens.Credential, error) { + if c.secret != "" { + return &accesstokens.Credential{Secret: c.secret}, nil + } + if c.cert != nil { + if c.key == nil { + return nil, errors.New("missing private key for certificate") + } + return &accesstokens.Credential{Cert: c.cert, Key: c.key, X5c: c.x5c}, nil + } + if c.key != nil { + return nil, errors.New("missing certificate for private key") + } + if c.assertionCallback != nil { + return &accesstokens.Credential{AssertionCallback: c.assertionCallback}, nil + } + if c.tokenProvider != nil { + return &accesstokens.Credential{TokenProvider: c.tokenProvider}, nil + } + return nil, errors.New("invalid credential") +} + +// NewCredFromSecret creates a Credential from a secret. +func NewCredFromSecret(secret string) (Credential, error) { + if secret == "" { + return Credential{}, errors.New("secret can't be empty string") + } + return Credential{secret: secret}, nil +} + +// NewCredFromAssertionCallback creates a Credential that invokes a callback to get assertions +// authenticating the application. The callback must be thread safe. +func NewCredFromAssertionCallback(callback func(context.Context, AssertionRequestOptions) (string, error)) Credential { + return Credential{assertionCallback: callback} +} + +// NewCredFromCert creates a Credential from a certificate or chain of certificates and an RSA private key +// as returned by [CertFromPEM]. +func NewCredFromCert(certs []*x509.Certificate, key crypto.PrivateKey) (Credential, error) { + cred := Credential{key: key} + k, ok := key.(*rsa.PrivateKey) + if !ok { + return cred, errors.New("key must be an RSA key") + } + for _, cert := range certs { + if cert == nil { + // not returning an error here because certs may still contain a sufficient cert/key pair + continue + } + certKey, ok := cert.PublicKey.(*rsa.PublicKey) + if ok && k.E == certKey.E && k.N.Cmp(certKey.N) == 0 { + // We know this is the signing cert because its public key matches the given private key. + // This cert must be first in x5c. + cred.cert = cert + cred.x5c = append([]string{base64.StdEncoding.EncodeToString(cert.Raw)}, cred.x5c...) + } else { + cred.x5c = append(cred.x5c, base64.StdEncoding.EncodeToString(cert.Raw)) + } + } + if cred.cert == nil { + return cred, errors.New("key doesn't match any certificate") + } + return cred, nil +} + +// TokenProviderParameters is the authentication parameters passed to token providers +type TokenProviderParameters = exported.TokenProviderParameters + +// TokenProviderResult is the authentication result returned by custom token providers +type TokenProviderResult = exported.TokenProviderResult + +// NewCredFromTokenProvider creates a Credential from a function that provides access tokens. The function +// must be concurrency safe. This is intended only to allow the Azure SDK to cache MSI tokens. It isn't +// useful to applications in general because the token provider must implement all authentication logic. +func NewCredFromTokenProvider(provider func(context.Context, TokenProviderParameters) (TokenProviderResult, error)) Credential { + return Credential{tokenProvider: provider} +} + +// AutoDetectRegion instructs MSAL Go to auto detect region for Azure regional token service. +func AutoDetectRegion() string { + return "TryAutoDetect" +} + +// Client is a representation of authentication client for confidential applications as defined in the +// package doc. A new Client should be created PER SERVICE USER. +// For more information, visit https://docs.microsoft.com/azure/active-directory/develop/msal-client-applications +type Client struct { + base base.Client + cred *accesstokens.Credential +} + +// clientOptions are optional settings for New(). These options are set using various functions +// returning Option calls. +type clientOptions struct { + accessor cache.ExportReplace + authority, azureRegion string + capabilities []string + disableInstanceDiscovery, sendX5C bool + httpClient ops.HTTPClient +} + +// Option is an optional argument to New(). +type Option func(o *clientOptions) + +// WithCache provides an accessor that will read and write authentication data to an externally managed cache. +func WithCache(accessor cache.ExportReplace) Option { + return func(o *clientOptions) { + o.accessor = accessor + } +} + +// WithClientCapabilities allows configuring one or more client capabilities such as "CP1" +func WithClientCapabilities(capabilities []string) Option { + return func(o *clientOptions) { + // there's no danger of sharing the slice's underlying memory with the application because + // this slice is simply passed to base.WithClientCapabilities, which copies its data + o.capabilities = capabilities + } +} + +// WithHTTPClient allows for a custom HTTP client to be set. +func WithHTTPClient(httpClient ops.HTTPClient) Option { + return func(o *clientOptions) { + o.httpClient = httpClient + } +} + +// WithX5C specifies if x5c claim(public key of the certificate) should be sent to STS to enable Subject Name Issuer Authentication. +func WithX5C() Option { + return func(o *clientOptions) { + o.sendX5C = true + } +} + +// WithInstanceDiscovery set to false to disable authority validation (to support private cloud scenarios) +func WithInstanceDiscovery(enabled bool) Option { + return func(o *clientOptions) { + o.disableInstanceDiscovery = !enabled + } +} + +// WithAzureRegion sets the region(preferred) or Confidential.AutoDetectRegion() for auto detecting region. +// Region names as per https://azure.microsoft.com/en-ca/global-infrastructure/geographies/. +// See https://aka.ms/region-map for more details on region names. +// The region value should be short region name for the region where the service is deployed. +// For example "centralus" is short name for region Central US. +// Not all auth flows can use the regional token service. +// Service To Service (client credential flow) tokens can be obtained from the regional service. +// Requires configuration at the tenant level. +// Auto-detection works on a limited number of Azure artifacts (VMs, Azure functions). +// If auto-detection fails, the non-regional endpoint will be used. +// If an invalid region name is provided, the non-regional endpoint MIGHT be used or the token request MIGHT fail. +func WithAzureRegion(val string) Option { + return func(o *clientOptions) { + o.azureRegion = val + } +} + +// New is the constructor for Client. authority is the URL of a token authority such as "https://login.microsoftonline.com/". +// If the Client will connect directly to AD FS, use "adfs" for the tenant. clientID is the application's client ID (also called its +// "application ID"). +func New(authority, clientID string, cred Credential, options ...Option) (Client, error) { + internalCred, err := cred.toInternal() + if err != nil { + return Client{}, err + } + + opts := clientOptions{ + authority: authority, + // if the caller specified a token provider, it will handle all details of authentication, using Client only as a token cache + disableInstanceDiscovery: cred.tokenProvider != nil, + httpClient: shared.DefaultClient, + } + for _, o := range options { + o(&opts) + } + baseOpts := []base.Option{ + base.WithCacheAccessor(opts.accessor), + base.WithClientCapabilities(opts.capabilities), + base.WithInstanceDiscovery(!opts.disableInstanceDiscovery), + base.WithRegionDetection(opts.azureRegion), + base.WithX5C(opts.sendX5C), + } + base, err := base.New(clientID, opts.authority, oauth.New(opts.httpClient), baseOpts...) + if err != nil { + return Client{}, err + } + base.AuthParams.IsConfidentialClient = true + + return Client{base: base, cred: internalCred}, nil +} + +// authCodeURLOptions contains options for AuthCodeURL +type authCodeURLOptions struct { + claims, loginHint, tenantID, domainHint string +} + +// AuthCodeURLOption is implemented by options for AuthCodeURL +type AuthCodeURLOption interface { + authCodeURLOption() +} + +// AuthCodeURL creates a URL used to acquire an authorization code. Users need to call CreateAuthorizationCodeURLParameters and pass it in. +// +// Options: [WithClaims], [WithDomainHint], [WithLoginHint], [WithTenantID] +func (cca Client) AuthCodeURL(ctx context.Context, clientID, redirectURI string, scopes []string, opts ...AuthCodeURLOption) (string, error) { + o := authCodeURLOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return "", err + } + ap, err := cca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return "", err + } + ap.Claims = o.claims + ap.LoginHint = o.loginHint + ap.DomainHint = o.domainHint + return cca.base.AuthCodeURL(ctx, clientID, redirectURI, scopes, ap) +} + +// WithLoginHint pre-populates the login prompt with a username. +func WithLoginHint(username string) interface { + AuthCodeURLOption + options.CallOption +} { + return struct { + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *authCodeURLOptions: + t.loginHint = username + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithDomainHint adds the IdP domain as domain_hint query parameter in the auth url. +func WithDomainHint(domain string) interface { + AuthCodeURLOption + options.CallOption +} { + return struct { + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *authCodeURLOptions: + t.domainHint = domain + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithClaims sets additional claims to request for the token, such as those required by conditional access policies. +// Use this option when Azure AD returned a claims challenge for a prior request. The argument must be decoded. +// This option is valid for any token acquisition method. +func WithClaims(claims string) interface { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenByAuthCodeOptions: + t.claims = claims + case *acquireTokenByCredentialOptions: + t.claims = claims + case *acquireTokenOnBehalfOfOptions: + t.claims = claims + case *acquireTokenSilentOptions: + t.claims = claims + case *authCodeURLOptions: + t.claims = claims + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithAuthenticationScheme is an extensibility mechanism designed to be used only by Azure Arc for proof of possession access tokens. +func WithAuthenticationScheme(authnScheme AuthenticationScheme) interface { + AcquireSilentOption + AcquireByCredentialOption + options.CallOption +} { + return struct { + AcquireSilentOption + AcquireByCredentialOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenSilentOptions: + t.authnScheme = authnScheme + case *acquireTokenByCredentialOptions: + t.authnScheme = authnScheme + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithTenantID specifies a tenant for a single authentication. It may be different than the tenant set in [New]. +// This option is valid for any token acquisition method. +func WithTenantID(tenantID string) interface { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenByAuthCodeOptions: + t.tenantID = tenantID + case *acquireTokenByCredentialOptions: + t.tenantID = tenantID + case *acquireTokenOnBehalfOfOptions: + t.tenantID = tenantID + case *acquireTokenSilentOptions: + t.tenantID = tenantID + case *authCodeURLOptions: + t.tenantID = tenantID + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// acquireTokenSilentOptions are all the optional settings to an AcquireTokenSilent() call. +// These are set by using various AcquireTokenSilentOption functions. +type acquireTokenSilentOptions struct { + account Account + claims, tenantID string + authnScheme AuthenticationScheme +} + +// AcquireSilentOption is implemented by options for AcquireTokenSilent +type AcquireSilentOption interface { + acquireSilentOption() +} + +// WithSilentAccount uses the passed account during an AcquireTokenSilent() call. +func WithSilentAccount(account Account) interface { + AcquireSilentOption + options.CallOption +} { + return struct { + AcquireSilentOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenSilentOptions: + t.account = account + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenSilent acquires a token from either the cache or using a refresh token. +// +// Options: [WithClaims], [WithSilentAccount], [WithTenantID] +func (cca Client) AcquireTokenSilent(ctx context.Context, scopes []string, opts ...AcquireSilentOption) (AuthResult, error) { + o := acquireTokenSilentOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + + if o.claims != "" { + return AuthResult{}, errors.New("call another AcquireToken method to request a new token having these claims") + } + + silentParameters := base.AcquireTokenSilentParameters{ + Scopes: scopes, + Account: o.account, + RequestType: accesstokens.ATConfidential, + Credential: cca.cred, + IsAppCache: o.account.IsZero(), + TenantID: o.tenantID, + AuthnScheme: o.authnScheme, + } + + return cca.base.AcquireTokenSilent(ctx, silentParameters) +} + +// acquireTokenByAuthCodeOptions contains the optional parameters used to acquire an access token using the authorization code flow. +type acquireTokenByAuthCodeOptions struct { + challenge, claims, tenantID string +} + +// AcquireByAuthCodeOption is implemented by options for AcquireTokenByAuthCode +type AcquireByAuthCodeOption interface { + acquireByAuthCodeOption() +} + +// WithChallenge allows you to provide a challenge for the .AcquireTokenByAuthCode() call. +func WithChallenge(challenge string) interface { + AcquireByAuthCodeOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenByAuthCodeOptions: + t.challenge = challenge + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenByAuthCode is a request to acquire a security token from the authority, using an authorization code. +// The specified redirect URI must be the same URI that was used when the authorization code was requested. +// +// Options: [WithChallenge], [WithClaims], [WithTenantID] +func (cca Client) AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, opts ...AcquireByAuthCodeOption) (AuthResult, error) { + o := acquireTokenByAuthCodeOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + + params := base.AcquireTokenAuthCodeParameters{ + Scopes: scopes, + Code: code, + Challenge: o.challenge, + Claims: o.claims, + AppType: accesstokens.ATConfidential, + Credential: cca.cred, // This setting differs from public.Client.AcquireTokenByAuthCode + RedirectURI: redirectURI, + TenantID: o.tenantID, + } + + return cca.base.AcquireTokenByAuthCode(ctx, params) +} + +// acquireTokenByCredentialOptions contains optional configuration for AcquireTokenByCredential +type acquireTokenByCredentialOptions struct { + claims, tenantID string + authnScheme AuthenticationScheme +} + +// AcquireByCredentialOption is implemented by options for AcquireTokenByCredential +type AcquireByCredentialOption interface { + acquireByCredOption() +} + +// AcquireTokenByCredential acquires a security token from the authority, using the client credentials grant. +// +// Options: [WithClaims], [WithTenantID] +func (cca Client) AcquireTokenByCredential(ctx context.Context, scopes []string, opts ...AcquireByCredentialOption) (AuthResult, error) { + o := acquireTokenByCredentialOptions{} + err := options.ApplyOptions(&o, opts) + if err != nil { + return AuthResult{}, err + } + authParams, err := cca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATClientCredentials + authParams.Claims = o.claims + if o.authnScheme != nil { + authParams.AuthnScheme = o.authnScheme + } + token, err := cca.base.Token.Credential(ctx, authParams, cca.cred) + if err != nil { + return AuthResult{}, err + } + return cca.base.AuthResultFromToken(ctx, authParams, token, true) +} + +// acquireTokenOnBehalfOfOptions contains optional configuration for AcquireTokenOnBehalfOf +type acquireTokenOnBehalfOfOptions struct { + claims, tenantID string +} + +// AcquireOnBehalfOfOption is implemented by options for AcquireTokenOnBehalfOf +type AcquireOnBehalfOfOption interface { + acquireOBOOption() +} + +// AcquireTokenOnBehalfOf acquires a security token for an app using middle tier apps access token. +// Refer https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow. +// +// Options: [WithClaims], [WithTenantID] +func (cca Client) AcquireTokenOnBehalfOf(ctx context.Context, userAssertion string, scopes []string, opts ...AcquireOnBehalfOfOption) (AuthResult, error) { + o := acquireTokenOnBehalfOfOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + params := base.AcquireTokenOnBehalfOfParameters{ + Scopes: scopes, + UserAssertion: userAssertion, + Claims: o.claims, + Credential: cca.cred, + TenantID: o.tenantID, + } + return cca.base.AcquireTokenOnBehalfOf(ctx, params) +} + +// Account gets the account in the token cache with the specified homeAccountID. +func (cca Client) Account(ctx context.Context, accountID string) (Account, error) { + return cca.base.Account(ctx, accountID) +} + +// RemoveAccount signs the account out and forgets account from token cache. +func (cca Client) RemoveAccount(ctx context.Context, account Account) error { + return cca.base.RemoveAccount(ctx, account) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/error_design.md b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/error_design.md new file mode 100644 index 000000000..7ef7862fe --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/error_design.md @@ -0,0 +1,111 @@ +# MSAL Error Design + +Author: Abhidnya Patil(abhidnya.patil@microsoft.com) + +Contributors: + +- John Doak(jdoak@microsoft.com) +- Keegan Caruso(Keegan.Caruso@microsoft.com) +- Joel Hendrix(jhendrix@microsoft.com) + +## Background + +Errors in MSAL are intended for app developers to troubleshoot and not for displaying to end-users. + +### Go error handling vs other MSAL languages + +Most modern languages use exception based errors. Simply put, you "throw" an exception and it must be caught at some routine in the upper stack or it will eventually crash the program. + +Go doesn't use exceptions, instead it relies on multiple return values, one of which can be the builtin error interface type. It is up to the user to decide what to do. + +### Go custom error types + +Errors can be created in Go by simply using errors.New() or fmt.Errorf() to create an "error". + +Custom errors can be created in multiple ways. One of the more robust ways is simply to satisfy the error interface: + +```go +type MyCustomErr struct { + Msg string +} +func (m MyCustomErr) Error() string { // This implements "error" + return m.Msg +} +``` + +### MSAL Error Goals + +- Provide diagnostics to the user and for tickets that can be used to track down bugs or client misconfigurations +- Detect errors that are transitory and can be retried +- Allow the user to identify certain errors that the program can respond to, such a informing the user for the need to do an enrollment + +## Implementing Client Side Errors + +Client side errors indicate a misconfiguration or passing of bad arguments that is non-recoverable. Retrying isn't possible. + +These errors can simply be standard Go errors created by errors.New() or fmt.Errorf(). If down the line we need a custom error, we can introduce it, but for now the error messages just need to be clear on what the issue was. + +## Implementing Service Side Errors + +Service side errors occur when an external RPC responds either with an HTTP error code or returns a message that includes an error. + +These errors can be transitory (please slow down) or permanent (HTTP 404). To provide our diagnostic goals, we require the ability to differentiate these errors from other errors. + +The current implementation includes a specialized type that captures any error from the server: + +```go +// CallErr represents an HTTP call error. Has a Verbose() method that allows getting the +// http.Request and Response objects. Implements error. +type CallErr struct { + Req *http.Request + Resp *http.Response + Err error +} + +// Errors implements error.Error(). +func (e CallErr) Error() string { + return e.Err.Error() +} + +// Verbose prints a versbose error message with the request or response. +func (e CallErr) Verbose() string { + e.Resp.Request = nil // This brings in a bunch of TLS stuff we don't need + e.Resp.TLS = nil // Same + return fmt.Sprintf("%s:\nRequest:\n%s\nResponse:\n%s", e.Err, prettyConf.Sprint(e.Req), prettyConf.Sprint(e.Resp)) +} +``` + +A user will always receive the most concise error we provide. They can tell if it is a server side error using Go error package: + +```go +var callErr CallErr +if errors.As(err, &callErr) { + ... +} +``` + +We provide a Verbose() function that can retrieve the most verbose message from any error we provide: + +```go +fmt.Println(errors.Verbose(err)) +``` + +If further differentiation is required, we can add custom errors that use Go error wrapping on top of CallErr to achieve our diagnostic goals (such as detecting when to retry a call due to transient errors). + +CallErr is always thrown from the comm package (which handles all http requests) and looks similar to: + +```go +return nil, errors.CallErr{ + Req: req, + Resp: reply, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d:\n%s", req.URL.String(), req.Method, reply.StatusCode, ErrorResponse), //ErrorResponse is the json body extracted from the http response + } +``` + +## Future Decisions + +The ability to retry calls needs to have centralized responsibility. Either the user is doing it or the client is doing it. + +If the user should be responsible, our errors package will include a CanRetry() function that will inform the user if the error provided to them is retryable. This is based on the http error code and possibly the type of error that was returned. It would also include a sleep time if the server returned an amount of time to wait. + +Otherwise we will do this internally and retries will be left to us. diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go new file mode 100644 index 000000000..c9b8dbed0 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package errors + +import ( + "errors" + "fmt" + "io" + "net/http" + "reflect" + "strings" + + "github.com/kylelemons/godebug/pretty" +) + +var prettyConf = &pretty.Config{ + IncludeUnexported: false, + SkipZeroFields: true, + TrackCycles: true, + Formatter: map[reflect.Type]interface{}{ + reflect.TypeOf((*io.Reader)(nil)).Elem(): func(r io.Reader) string { + b, err := io.ReadAll(r) + if err != nil { + return "could not read io.Reader content" + } + return string(b) + }, + }, +} + +type verboser interface { + Verbose() string +} + +// Verbose prints the most verbose error that the error message has. +func Verbose(err error) string { + build := strings.Builder{} + for { + if err == nil { + break + } + if v, ok := err.(verboser); ok { + build.WriteString(v.Verbose()) + } else { + build.WriteString(err.Error()) + } + err = errors.Unwrap(err) + } + return build.String() +} + +// New is equivalent to errors.New(). +func New(text string) error { + return errors.New(text) +} + +// CallErr represents an HTTP call error. Has a Verbose() method that allows getting the +// http.Request and Response objects. Implements error. +type CallErr struct { + Req *http.Request + // Resp contains response body + Resp *http.Response + Err error +} + +// Errors implements error.Error(). +func (e CallErr) Error() string { + return e.Err.Error() +} + +// Verbose prints a versbose error message with the request or response. +func (e CallErr) Verbose() string { + e.Resp.Request = nil // This brings in a bunch of TLS crap we don't need + e.Resp.TLS = nil // Same + return fmt.Sprintf("%s:\nRequest:\n%s\nResponse:\n%s", e.Err, prettyConf.Sprint(e.Req), prettyConf.Sprint(e.Resp)) +} + +// Is reports whether any error in errors chain matches target. +func Is(err, target error) bool { + return errors.Is(err, target) +} + +// As finds the first error in errors chain that matches target, +// and if so, sets target to that error value and returns true. +// Otherwise, it returns false. +func As(err error, target interface{}) bool { + return errors.As(err, target) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go new file mode 100644 index 000000000..09a0d92f5 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go @@ -0,0 +1,477 @@ +// Package base contains a "Base" client that is used by the external public.Client and confidential.Client. +// Base holds shared attributes that must be available to both clients and methods that act as +// shared calls. +package base + +import ( + "context" + "errors" + "fmt" + "net/url" + "reflect" + "strings" + "sync" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +const ( + // AuthorityPublicCloud is the default AAD authority host + AuthorityPublicCloud = "https://login.microsoftonline.com/common" + scopeSeparator = " " +) + +// manager provides an internal cache. It is defined to allow faking the cache in tests. +// In production it's a *storage.Manager or *storage.PartitionedManager. +type manager interface { + cache.Serializer + Read(context.Context, authority.AuthParams) (storage.TokenResponse, error) + Write(authority.AuthParams, accesstokens.TokenResponse) (shared.Account, error) +} + +// accountManager is a manager that also caches accounts. In production it's a *storage.Manager. +type accountManager interface { + manager + AllAccounts() []shared.Account + Account(homeAccountID string) shared.Account + RemoveAccount(account shared.Account, clientID string) +} + +// AcquireTokenSilentParameters contains the parameters to acquire a token silently (from cache). +type AcquireTokenSilentParameters struct { + Scopes []string + Account shared.Account + RequestType accesstokens.AppType + Credential *accesstokens.Credential + IsAppCache bool + TenantID string + UserAssertion string + AuthorizationType authority.AuthorizeType + Claims string + AuthnScheme authority.AuthenticationScheme +} + +// AcquireTokenAuthCodeParameters contains the parameters required to acquire an access token using the auth code flow. +// To use PKCE, set the CodeChallengeParameter. +// Code challenges are used to secure authorization code grants; for more information, visit +// https://tools.ietf.org/html/rfc7636. +type AcquireTokenAuthCodeParameters struct { + Scopes []string + Code string + Challenge string + Claims string + RedirectURI string + AppType accesstokens.AppType + Credential *accesstokens.Credential + TenantID string +} + +type AcquireTokenOnBehalfOfParameters struct { + Scopes []string + Claims string + Credential *accesstokens.Credential + TenantID string + UserAssertion string +} + +// AuthResult contains the results of one token acquisition operation in PublicClientApplication +// or ConfidentialClientApplication. For details see https://aka.ms/msal-net-authenticationresult +type AuthResult struct { + Account shared.Account + IDToken accesstokens.IDToken + AccessToken string + ExpiresOn time.Time + GrantedScopes []string + DeclinedScopes []string +} + +// AuthResultFromStorage creates an AuthResult from a storage token response (which is generated from the cache). +func AuthResultFromStorage(storageTokenResponse storage.TokenResponse) (AuthResult, error) { + if err := storageTokenResponse.AccessToken.Validate(); err != nil { + return AuthResult{}, fmt.Errorf("problem with access token in StorageTokenResponse: %w", err) + } + + account := storageTokenResponse.Account + accessToken := storageTokenResponse.AccessToken.Secret + grantedScopes := strings.Split(storageTokenResponse.AccessToken.Scopes, scopeSeparator) + + // Checking if there was an ID token in the cache; this will throw an error in the case of confidential client applications. + var idToken accesstokens.IDToken + if !storageTokenResponse.IDToken.IsZero() { + err := idToken.UnmarshalJSON([]byte(storageTokenResponse.IDToken.Secret)) + if err != nil { + return AuthResult{}, fmt.Errorf("problem decoding JWT token: %w", err) + } + } + return AuthResult{account, idToken, accessToken, storageTokenResponse.AccessToken.ExpiresOn.T, grantedScopes, nil}, nil +} + +// NewAuthResult creates an AuthResult. +func NewAuthResult(tokenResponse accesstokens.TokenResponse, account shared.Account) (AuthResult, error) { + if len(tokenResponse.DeclinedScopes) > 0 { + return AuthResult{}, fmt.Errorf("token response failed because declined scopes are present: %s", strings.Join(tokenResponse.DeclinedScopes, ",")) + } + return AuthResult{ + Account: account, + IDToken: tokenResponse.IDToken, + AccessToken: tokenResponse.AccessToken, + ExpiresOn: tokenResponse.ExpiresOn.T, + GrantedScopes: tokenResponse.GrantedScopes.Slice, + }, nil +} + +// Client is a base client that provides access to common methods and primatives that +// can be used by multiple clients. +type Client struct { + Token *oauth.Client + manager accountManager // *storage.Manager or fakeManager in tests + // pmanager is a partitioned cache for OBO authentication. *storage.PartitionedManager or fakeManager in tests + pmanager manager + + AuthParams authority.AuthParams // DO NOT EVER MAKE THIS A POINTER! See "Note" in New(). + cacheAccessor cache.ExportReplace + cacheAccessorMu *sync.RWMutex +} + +// Option is an optional argument to the New constructor. +type Option func(c *Client) error + +// WithCacheAccessor allows you to set some type of cache for storing authentication tokens. +func WithCacheAccessor(ca cache.ExportReplace) Option { + return func(c *Client) error { + if ca != nil { + c.cacheAccessor = ca + } + return nil + } +} + +// WithClientCapabilities allows configuring one or more client capabilities such as "CP1" +func WithClientCapabilities(capabilities []string) Option { + return func(c *Client) error { + var err error + if len(capabilities) > 0 { + cc, err := authority.NewClientCapabilities(capabilities) + if err == nil { + c.AuthParams.Capabilities = cc + } + } + return err + } +} + +// WithKnownAuthorityHosts specifies hosts Client shouldn't validate or request metadata for because they're known to the user +func WithKnownAuthorityHosts(hosts []string) Option { + return func(c *Client) error { + cp := make([]string, len(hosts)) + copy(cp, hosts) + c.AuthParams.KnownAuthorityHosts = cp + return nil + } +} + +// WithX5C specifies if x5c claim(public key of the certificate) should be sent to STS to enable Subject Name Issuer Authentication. +func WithX5C(sendX5C bool) Option { + return func(c *Client) error { + c.AuthParams.SendX5C = sendX5C + return nil + } +} + +func WithRegionDetection(region string) Option { + return func(c *Client) error { + c.AuthParams.AuthorityInfo.Region = region + return nil + } +} + +func WithInstanceDiscovery(instanceDiscoveryEnabled bool) Option { + return func(c *Client) error { + c.AuthParams.AuthorityInfo.ValidateAuthority = instanceDiscoveryEnabled + c.AuthParams.AuthorityInfo.InstanceDiscoveryDisabled = !instanceDiscoveryEnabled + return nil + } +} + +// New is the constructor for Base. +func New(clientID string, authorityURI string, token *oauth.Client, options ...Option) (Client, error) { + //By default, validateAuthority is set to true and instanceDiscoveryDisabled is set to false + authInfo, err := authority.NewInfoFromAuthorityURI(authorityURI, true, false) + if err != nil { + return Client{}, err + } + authParams := authority.NewAuthParams(clientID, authInfo) + client := Client{ // Note: Hey, don't even THINK about making Base into *Base. See "design notes" in public.go and confidential.go + Token: token, + AuthParams: authParams, + cacheAccessorMu: &sync.RWMutex{}, + manager: storage.New(token), + pmanager: storage.NewPartitionedManager(token), + } + for _, o := range options { + if err = o(&client); err != nil { + break + } + } + return client, err + +} + +// AuthCodeURL creates a URL used to acquire an authorization code. +func (b Client) AuthCodeURL(ctx context.Context, clientID, redirectURI string, scopes []string, authParams authority.AuthParams) (string, error) { + endpoints, err := b.Token.ResolveEndpoints(ctx, authParams.AuthorityInfo, "") + if err != nil { + return "", err + } + + baseURL, err := url.Parse(endpoints.AuthorizationEndpoint) + if err != nil { + return "", err + } + + claims, err := authParams.MergeCapabilitiesAndClaims() + if err != nil { + return "", err + } + + v := url.Values{} + v.Add("client_id", clientID) + v.Add("response_type", "code") + v.Add("redirect_uri", redirectURI) + v.Add("scope", strings.Join(scopes, scopeSeparator)) + if authParams.State != "" { + v.Add("state", authParams.State) + } + if claims != "" { + v.Add("claims", claims) + } + if authParams.CodeChallenge != "" { + v.Add("code_challenge", authParams.CodeChallenge) + } + if authParams.CodeChallengeMethod != "" { + v.Add("code_challenge_method", authParams.CodeChallengeMethod) + } + if authParams.LoginHint != "" { + v.Add("login_hint", authParams.LoginHint) + } + if authParams.Prompt != "" { + v.Add("prompt", authParams.Prompt) + } + if authParams.DomainHint != "" { + v.Add("domain_hint", authParams.DomainHint) + } + // There were left over from an implementation that didn't use any of these. We may + // need to add them later, but as of now aren't needed. + /* + if p.ResponseMode != "" { + urlParams.Add("response_mode", p.ResponseMode) + } + */ + baseURL.RawQuery = v.Encode() + return baseURL.String(), nil +} + +func (b Client) AcquireTokenSilent(ctx context.Context, silent AcquireTokenSilentParameters) (AuthResult, error) { + ar := AuthResult{} + // when tenant == "", the caller didn't specify a tenant and WithTenant will choose the client's configured tenant + tenant := silent.TenantID + authParams, err := b.AuthParams.WithTenant(tenant) + if err != nil { + return ar, err + } + authParams.Scopes = silent.Scopes + authParams.HomeAccountID = silent.Account.HomeAccountID + authParams.AuthorizationType = silent.AuthorizationType + authParams.Claims = silent.Claims + authParams.UserAssertion = silent.UserAssertion + if silent.AuthnScheme != nil { + authParams.AuthnScheme = silent.AuthnScheme + } + + m := b.pmanager + if authParams.AuthorizationType != authority.ATOnBehalfOf { + authParams.AuthorizationType = authority.ATRefreshToken + m = b.manager + } + if b.cacheAccessor != nil { + key := authParams.CacheKey(silent.IsAppCache) + b.cacheAccessorMu.RLock() + err = b.cacheAccessor.Replace(ctx, m, cache.ReplaceHints{PartitionKey: key}) + b.cacheAccessorMu.RUnlock() + } + if err != nil { + return ar, err + } + storageTokenResponse, err := m.Read(ctx, authParams) + if err != nil { + return ar, err + } + + // ignore cached access tokens when given claims + if silent.Claims == "" { + ar, err = AuthResultFromStorage(storageTokenResponse) + if err == nil { + ar.AccessToken, err = authParams.AuthnScheme.FormatAccessToken(ar.AccessToken) + return ar, err + } + } + + // redeem a cached refresh token, if available + if reflect.ValueOf(storageTokenResponse.RefreshToken).IsZero() { + return ar, errors.New("no token found") + } + var cc *accesstokens.Credential + if silent.RequestType == accesstokens.ATConfidential { + cc = silent.Credential + } + token, err := b.Token.Refresh(ctx, silent.RequestType, authParams, cc, storageTokenResponse.RefreshToken) + if err != nil { + return ar, err + } + return b.AuthResultFromToken(ctx, authParams, token, true) +} + +func (b Client) AcquireTokenByAuthCode(ctx context.Context, authCodeParams AcquireTokenAuthCodeParameters) (AuthResult, error) { + authParams, err := b.AuthParams.WithTenant(authCodeParams.TenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Claims = authCodeParams.Claims + authParams.Scopes = authCodeParams.Scopes + authParams.Redirecturi = authCodeParams.RedirectURI + authParams.AuthorizationType = authority.ATAuthCode + + var cc *accesstokens.Credential + if authCodeParams.AppType == accesstokens.ATConfidential { + cc = authCodeParams.Credential + authParams.IsConfidentialClient = true + } + + req, err := accesstokens.NewCodeChallengeRequest(authParams, authCodeParams.AppType, cc, authCodeParams.Code, authCodeParams.Challenge) + if err != nil { + return AuthResult{}, err + } + + token, err := b.Token.AuthCode(ctx, req) + if err != nil { + return AuthResult{}, err + } + + return b.AuthResultFromToken(ctx, authParams, token, true) +} + +// AcquireTokenOnBehalfOf acquires a security token for an app using middle tier apps access token. +func (b Client) AcquireTokenOnBehalfOf(ctx context.Context, onBehalfOfParams AcquireTokenOnBehalfOfParameters) (AuthResult, error) { + var ar AuthResult + silentParameters := AcquireTokenSilentParameters{ + Scopes: onBehalfOfParams.Scopes, + RequestType: accesstokens.ATConfidential, + Credential: onBehalfOfParams.Credential, + UserAssertion: onBehalfOfParams.UserAssertion, + AuthorizationType: authority.ATOnBehalfOf, + TenantID: onBehalfOfParams.TenantID, + Claims: onBehalfOfParams.Claims, + } + ar, err := b.AcquireTokenSilent(ctx, silentParameters) + if err == nil { + return ar, err + } + authParams, err := b.AuthParams.WithTenant(onBehalfOfParams.TenantID) + if err != nil { + return AuthResult{}, err + } + authParams.AuthorizationType = authority.ATOnBehalfOf + authParams.Claims = onBehalfOfParams.Claims + authParams.Scopes = onBehalfOfParams.Scopes + authParams.UserAssertion = onBehalfOfParams.UserAssertion + token, err := b.Token.OnBehalfOf(ctx, authParams, onBehalfOfParams.Credential) + if err == nil { + ar, err = b.AuthResultFromToken(ctx, authParams, token, true) + } + return ar, err +} + +func (b Client) AuthResultFromToken(ctx context.Context, authParams authority.AuthParams, token accesstokens.TokenResponse, cacheWrite bool) (AuthResult, error) { + if !cacheWrite { + return NewAuthResult(token, shared.Account{}) + } + var m manager = b.manager + if authParams.AuthorizationType == authority.ATOnBehalfOf { + m = b.pmanager + } + key := token.CacheKey(authParams) + if b.cacheAccessor != nil { + b.cacheAccessorMu.Lock() + defer b.cacheAccessorMu.Unlock() + err := b.cacheAccessor.Replace(ctx, m, cache.ReplaceHints{PartitionKey: key}) + if err != nil { + return AuthResult{}, err + } + } + account, err := m.Write(authParams, token) + if err != nil { + return AuthResult{}, err + } + ar, err := NewAuthResult(token, account) + if err == nil && b.cacheAccessor != nil { + err = b.cacheAccessor.Export(ctx, b.manager, cache.ExportHints{PartitionKey: key}) + } + if err != nil { + return AuthResult{}, err + } + + ar.AccessToken, err = authParams.AuthnScheme.FormatAccessToken(ar.AccessToken) + return ar, err +} + +func (b Client) AllAccounts(ctx context.Context) ([]shared.Account, error) { + if b.cacheAccessor != nil { + b.cacheAccessorMu.RLock() + defer b.cacheAccessorMu.RUnlock() + key := b.AuthParams.CacheKey(false) + err := b.cacheAccessor.Replace(ctx, b.manager, cache.ReplaceHints{PartitionKey: key}) + if err != nil { + return nil, err + } + } + return b.manager.AllAccounts(), nil +} + +func (b Client) Account(ctx context.Context, homeAccountID string) (shared.Account, error) { + if b.cacheAccessor != nil { + b.cacheAccessorMu.RLock() + defer b.cacheAccessorMu.RUnlock() + authParams := b.AuthParams // This is a copy, as we don't have a pointer receiver and .AuthParams is not a pointer. + authParams.AuthorizationType = authority.AccountByID + authParams.HomeAccountID = homeAccountID + key := b.AuthParams.CacheKey(false) + err := b.cacheAccessor.Replace(ctx, b.manager, cache.ReplaceHints{PartitionKey: key}) + if err != nil { + return shared.Account{}, err + } + } + return b.manager.Account(homeAccountID), nil +} + +// RemoveAccount removes all the ATs, RTs and IDTs from the cache associated with this account. +func (b Client) RemoveAccount(ctx context.Context, account shared.Account) error { + if b.cacheAccessor == nil { + b.manager.RemoveAccount(account, b.AuthParams.ClientID) + return nil + } + b.cacheAccessorMu.Lock() + defer b.cacheAccessorMu.Unlock() + key := b.AuthParams.CacheKey(false) + err := b.cacheAccessor.Replace(ctx, b.manager, cache.ReplaceHints{PartitionKey: key}) + if err != nil { + return err + } + b.manager.RemoveAccount(account, b.AuthParams.ClientID) + return b.cacheAccessor.Export(ctx, b.manager, cache.ExportHints{PartitionKey: key}) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go new file mode 100644 index 000000000..f9be90276 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package storage + +import ( + "errors" + "fmt" + "reflect" + "strings" + "time" + + internalTime "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// Contract is the JSON structure that is written to any storage medium when serializing +// the internal cache. This design is shared between MSAL versions in many languages. +// This cannot be changed without design that includes other SDKs. +type Contract struct { + AccessTokens map[string]AccessToken `json:"AccessToken,omitempty"` + RefreshTokens map[string]accesstokens.RefreshToken `json:"RefreshToken,omitempty"` + IDTokens map[string]IDToken `json:"IdToken,omitempty"` + Accounts map[string]shared.Account `json:"Account,omitempty"` + AppMetaData map[string]AppMetaData `json:"AppMetadata,omitempty"` + + AdditionalFields map[string]interface{} +} + +// Contract is the JSON structure that is written to any storage medium when serializing +// the internal cache. This design is shared between MSAL versions in many languages. +// This cannot be changed without design that includes other SDKs. +type InMemoryContract struct { + AccessTokensPartition map[string]map[string]AccessToken + RefreshTokensPartition map[string]map[string]accesstokens.RefreshToken + IDTokensPartition map[string]map[string]IDToken + AccountsPartition map[string]map[string]shared.Account + AppMetaData map[string]AppMetaData +} + +// NewContract is the constructor for Contract. +func NewInMemoryContract() *InMemoryContract { + return &InMemoryContract{ + AccessTokensPartition: map[string]map[string]AccessToken{}, + RefreshTokensPartition: map[string]map[string]accesstokens.RefreshToken{}, + IDTokensPartition: map[string]map[string]IDToken{}, + AccountsPartition: map[string]map[string]shared.Account{}, + AppMetaData: map[string]AppMetaData{}, + } +} + +// NewContract is the constructor for Contract. +func NewContract() *Contract { + return &Contract{ + AccessTokens: map[string]AccessToken{}, + RefreshTokens: map[string]accesstokens.RefreshToken{}, + IDTokens: map[string]IDToken{}, + Accounts: map[string]shared.Account{}, + AppMetaData: map[string]AppMetaData{}, + AdditionalFields: map[string]interface{}{}, + } +} + +// AccessToken is the JSON representation of a MSAL access token for encoding to storage. +type AccessToken struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + Realm string `json:"realm,omitempty"` + CredentialType string `json:"credential_type,omitempty"` + ClientID string `json:"client_id,omitempty"` + Secret string `json:"secret,omitempty"` + Scopes string `json:"target,omitempty"` + ExpiresOn internalTime.Unix `json:"expires_on,omitempty"` + ExtendedExpiresOn internalTime.Unix `json:"extended_expires_on,omitempty"` + CachedAt internalTime.Unix `json:"cached_at,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + TokenType string `json:"token_type,omitempty"` + AuthnSchemeKeyID string `json:"keyid,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewAccessToken is the constructor for AccessToken. +func NewAccessToken(homeID, env, realm, clientID string, cachedAt, expiresOn, extendedExpiresOn time.Time, scopes, token, tokenType, authnSchemeKeyID string) AccessToken { + return AccessToken{ + HomeAccountID: homeID, + Environment: env, + Realm: realm, + CredentialType: "AccessToken", + ClientID: clientID, + Secret: token, + Scopes: scopes, + CachedAt: internalTime.Unix{T: cachedAt.UTC()}, + ExpiresOn: internalTime.Unix{T: expiresOn.UTC()}, + ExtendedExpiresOn: internalTime.Unix{T: extendedExpiresOn.UTC()}, + TokenType: tokenType, + AuthnSchemeKeyID: authnSchemeKeyID, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (a AccessToken) Key() string { + key := strings.Join( + []string{a.HomeAccountID, a.Environment, a.CredentialType, a.ClientID, a.Realm, a.Scopes}, + shared.CacheKeySeparator, + ) + // add token type to key for new access tokens types. skip for bearer token type to + // preserve fwd and back compat between a common cache and msal clients + if !strings.EqualFold(a.TokenType, authority.AccessTokenTypeBearer) { + key = strings.Join([]string{key, a.TokenType}, shared.CacheKeySeparator) + } + return strings.ToLower(key) +} + +// FakeValidate enables tests to fake access token validation +var FakeValidate func(AccessToken) error + +// Validate validates that this AccessToken can be used. +func (a AccessToken) Validate() error { + if FakeValidate != nil { + return FakeValidate(a) + } + if a.CachedAt.T.After(time.Now()) { + return errors.New("access token isn't valid, it was cached at a future time") + } + if a.ExpiresOn.T.Before(time.Now().Add(5 * time.Minute)) { + return fmt.Errorf("access token is expired") + } + if a.CachedAt.T.IsZero() { + return fmt.Errorf("access token does not have CachedAt set") + } + return nil +} + +// IDToken is the JSON representation of an MSAL id token for encoding to storage. +type IDToken struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + Realm string `json:"realm,omitempty"` + CredentialType string `json:"credential_type,omitempty"` + ClientID string `json:"client_id,omitempty"` + Secret string `json:"secret,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + AdditionalFields map[string]interface{} +} + +// IsZero determines if IDToken is the zero value. +func (i IDToken) IsZero() bool { + v := reflect.ValueOf(i) + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if !field.IsZero() { + switch field.Kind() { + case reflect.Map, reflect.Slice: + if field.Len() == 0 { + continue + } + } + return false + } + } + return true +} + +// NewIDToken is the constructor for IDToken. +func NewIDToken(homeID, env, realm, clientID, idToken string) IDToken { + return IDToken{ + HomeAccountID: homeID, + Environment: env, + Realm: realm, + CredentialType: "IDToken", + ClientID: clientID, + Secret: idToken, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (id IDToken) Key() string { + key := strings.Join( + []string{id.HomeAccountID, id.Environment, id.CredentialType, id.ClientID, id.Realm}, + shared.CacheKeySeparator, + ) + return strings.ToLower(key) +} + +// AppMetaData is the JSON representation of application metadata for encoding to storage. +type AppMetaData struct { + FamilyID string `json:"family_id,omitempty"` + ClientID string `json:"client_id,omitempty"` + Environment string `json:"environment,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewAppMetaData is the constructor for AppMetaData. +func NewAppMetaData(familyID, clientID, environment string) AppMetaData { + return AppMetaData{ + FamilyID: familyID, + ClientID: clientID, + Environment: environment, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (a AppMetaData) Key() string { + key := strings.Join( + []string{"AppMetaData", a.Environment, a.ClientID}, + shared.CacheKeySeparator, + ) + return strings.ToLower(key) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go new file mode 100644 index 000000000..c09318330 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go @@ -0,0 +1,442 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package storage + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// PartitionedManager is a partitioned in-memory cache of access tokens, accounts and meta data. +type PartitionedManager struct { + contract *InMemoryContract + contractMu sync.RWMutex + requests aadInstanceDiscoveryer // *oauth.Token + + aadCacheMu sync.RWMutex + aadCache map[string]authority.InstanceDiscoveryMetadata +} + +// NewPartitionedManager is the constructor for PartitionedManager. +func NewPartitionedManager(requests *oauth.Client) *PartitionedManager { + m := &PartitionedManager{requests: requests, aadCache: make(map[string]authority.InstanceDiscoveryMetadata)} + m.contract = NewInMemoryContract() + return m +} + +// Read reads a storage token from the cache if it exists. +func (m *PartitionedManager) Read(ctx context.Context, authParameters authority.AuthParams) (TokenResponse, error) { + tr := TokenResponse{} + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + scopes := authParameters.Scopes + authnSchemeKeyID := authParameters.AuthnScheme.KeyID() + tokenType := authParameters.AuthnScheme.AccessTokenType() + + // fetch metadata if instanceDiscovery is enabled + aliases := []string{authParameters.AuthorityInfo.Host} + if !authParameters.AuthorityInfo.InstanceDiscoveryDisabled { + metadata, err := m.getMetadataEntry(ctx, authParameters.AuthorityInfo) + if err != nil { + return TokenResponse{}, err + } + aliases = metadata.Aliases + } + + userAssertionHash := authParameters.AssertionHash() + partitionKeyFromRequest := userAssertionHash + + // errors returned by read* methods indicate a cache miss and are therefore non-fatal. We continue populating + // TokenResponse fields so that e.g. lack of an ID token doesn't prevent the caller from receiving a refresh token. + accessToken, err := m.readAccessToken(aliases, realm, clientID, userAssertionHash, scopes, partitionKeyFromRequest, tokenType, authnSchemeKeyID) + if err == nil { + tr.AccessToken = accessToken + } + idToken, err := m.readIDToken(aliases, realm, clientID, userAssertionHash, getPartitionKeyIDTokenRead(accessToken)) + if err == nil { + tr.IDToken = idToken + } + + if appMetadata, err := m.readAppMetaData(aliases, clientID); err == nil { + // we need the family ID to identify the correct refresh token, if any + familyID := appMetadata.FamilyID + refreshToken, err := m.readRefreshToken(aliases, familyID, clientID, userAssertionHash, partitionKeyFromRequest) + if err == nil { + tr.RefreshToken = refreshToken + } + } + + account, err := m.readAccount(aliases, realm, userAssertionHash, idToken.HomeAccountID) + if err == nil { + tr.Account = account + } + return tr, nil +} + +// Write writes a token response to the cache and returns the account information the token is stored with. +func (m *PartitionedManager) Write(authParameters authority.AuthParams, tokenResponse accesstokens.TokenResponse) (shared.Account, error) { + authParameters.HomeAccountID = tokenResponse.HomeAccountID() + homeAccountID := authParameters.HomeAccountID + environment := authParameters.AuthorityInfo.Host + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + target := strings.Join(tokenResponse.GrantedScopes.Slice, scopeSeparator) + userAssertionHash := authParameters.AssertionHash() + cachedAt := time.Now() + authnSchemeKeyID := authParameters.AuthnScheme.KeyID() + var account shared.Account + + if len(tokenResponse.RefreshToken) > 0 { + refreshToken := accesstokens.NewRefreshToken(homeAccountID, environment, clientID, tokenResponse.RefreshToken, tokenResponse.FamilyID) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + refreshToken.UserAssertionHash = userAssertionHash + } + if err := m.writeRefreshToken(refreshToken, getPartitionKeyRefreshToken(refreshToken)); err != nil { + return account, err + } + } + + if len(tokenResponse.AccessToken) > 0 { + accessToken := NewAccessToken( + homeAccountID, + environment, + realm, + clientID, + cachedAt, + tokenResponse.ExpiresOn.T, + tokenResponse.ExtExpiresOn.T, + target, + tokenResponse.AccessToken, + tokenResponse.TokenType, + authnSchemeKeyID, + ) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + accessToken.UserAssertionHash = userAssertionHash // get Hash method on this + } + + // Since we have a valid access token, cache it before moving on. + if err := accessToken.Validate(); err == nil { + if err := m.writeAccessToken(accessToken, getPartitionKeyAccessToken(accessToken)); err != nil { + return account, err + } + } else { + return shared.Account{}, err + } + } + + idTokenJwt := tokenResponse.IDToken + if !idTokenJwt.IsZero() { + idToken := NewIDToken(homeAccountID, environment, realm, clientID, idTokenJwt.RawToken) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + idToken.UserAssertionHash = userAssertionHash + } + if err := m.writeIDToken(idToken, getPartitionKeyIDToken(idToken)); err != nil { + return shared.Account{}, err + } + + localAccountID := idTokenJwt.LocalAccountID() + authorityType := authParameters.AuthorityInfo.AuthorityType + + preferredUsername := idTokenJwt.UPN + if idTokenJwt.PreferredUsername != "" { + preferredUsername = idTokenJwt.PreferredUsername + } + + account = shared.NewAccount( + homeAccountID, + environment, + realm, + localAccountID, + authorityType, + preferredUsername, + ) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + account.UserAssertionHash = userAssertionHash + } + if err := m.writeAccount(account, getPartitionKeyAccount(account)); err != nil { + return shared.Account{}, err + } + } + + AppMetaData := NewAppMetaData(tokenResponse.FamilyID, clientID, environment) + + if err := m.writeAppMetaData(AppMetaData); err != nil { + return shared.Account{}, err + } + return account, nil +} + +func (m *PartitionedManager) getMetadataEntry(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + md, err := m.aadMetadataFromCache(ctx, authorityInfo) + if err != nil { + // not in the cache, retrieve it + md, err = m.aadMetadata(ctx, authorityInfo) + } + return md, err +} + +func (m *PartitionedManager) aadMetadataFromCache(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + m.aadCacheMu.RLock() + defer m.aadCacheMu.RUnlock() + metadata, ok := m.aadCache[authorityInfo.Host] + if ok { + return metadata, nil + } + return metadata, errors.New("not found") +} + +func (m *PartitionedManager) aadMetadata(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + discoveryResponse, err := m.requests.AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return authority.InstanceDiscoveryMetadata{}, err + } + + m.aadCacheMu.Lock() + defer m.aadCacheMu.Unlock() + + for _, metadataEntry := range discoveryResponse.Metadata { + for _, aliasedAuthority := range metadataEntry.Aliases { + m.aadCache[aliasedAuthority] = metadataEntry + } + } + if _, ok := m.aadCache[authorityInfo.Host]; !ok { + m.aadCache[authorityInfo.Host] = authority.InstanceDiscoveryMetadata{ + PreferredNetwork: authorityInfo.Host, + PreferredCache: authorityInfo.Host, + } + } + return m.aadCache[authorityInfo.Host], nil +} + +func (m *PartitionedManager) readAccessToken(envAliases []string, realm, clientID, userAssertionHash string, scopes []string, partitionKey, tokenType, authnSchemeKeyID string) (AccessToken, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + if accessTokens, ok := m.contract.AccessTokensPartition[partitionKey]; ok { + // TODO: linear search (over a map no less) is slow for a large number (thousands) of tokens. + // this shows up as the dominating node in a profile. for real-world scenarios this likely isn't + // an issue, however if it does become a problem then we know where to look. + for _, at := range accessTokens { + if at.Realm == realm && at.ClientID == clientID && at.UserAssertionHash == userAssertionHash { + if at.TokenType == tokenType && at.AuthnSchemeKeyID == authnSchemeKeyID { + if checkAlias(at.Environment, envAliases) { + if isMatchingScopes(scopes, at.Scopes) { + return at, nil + } + } + } + } + } + } + return AccessToken{}, fmt.Errorf("access token not found") +} + +func (m *PartitionedManager) writeAccessToken(accessToken AccessToken, partitionKey string) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + key := accessToken.Key() + if m.contract.AccessTokensPartition[partitionKey] == nil { + m.contract.AccessTokensPartition[partitionKey] = make(map[string]AccessToken) + } + m.contract.AccessTokensPartition[partitionKey][key] = accessToken + return nil +} + +func matchFamilyRefreshTokenObo(rt accesstokens.RefreshToken, userAssertionHash string, envAliases []string) bool { + return rt.UserAssertionHash == userAssertionHash && checkAlias(rt.Environment, envAliases) && rt.FamilyID != "" +} + +func matchClientIDRefreshTokenObo(rt accesstokens.RefreshToken, userAssertionHash string, envAliases []string, clientID string) bool { + return rt.UserAssertionHash == userAssertionHash && checkAlias(rt.Environment, envAliases) && rt.ClientID == clientID +} + +func (m *PartitionedManager) readRefreshToken(envAliases []string, familyID, clientID, userAssertionHash, partitionKey string) (accesstokens.RefreshToken, error) { + byFamily := func(rt accesstokens.RefreshToken) bool { + return matchFamilyRefreshTokenObo(rt, userAssertionHash, envAliases) + } + byClient := func(rt accesstokens.RefreshToken) bool { + return matchClientIDRefreshTokenObo(rt, userAssertionHash, envAliases, clientID) + } + + var matchers []func(rt accesstokens.RefreshToken) bool + if familyID == "" { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byClient, byFamily, + } + } else { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byFamily, byClient, + } + } + + // TODO(keegan): All the tests here pass, but Bogdan says this is + // more complicated. I'm opening an issue for this to have him + // review the tests and suggest tests that would break this so + // we can re-write against good tests. His comments as follow: + // The algorithm is a bit more complex than this, I assume there are some tests covering everything. I would keep the order as is. + // The algorithm is: + // If application is NOT part of the family, search by client_ID + // If app is part of the family or if we DO NOT KNOW if it's part of the family, search by family ID, then by client_id (we will know if an app is part of the family after the first token response). + // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/311fe8b16e7c293462806f397e189a6aa1159769/src/client/Microsoft.Identity.Client/Internal/Requests/Silent/CacheSilentStrategy.cs#L95 + m.contractMu.RLock() + defer m.contractMu.RUnlock() + for _, matcher := range matchers { + for _, rt := range m.contract.RefreshTokensPartition[partitionKey] { + if matcher(rt) { + return rt, nil + } + } + } + + return accesstokens.RefreshToken{}, fmt.Errorf("refresh token not found") +} + +func (m *PartitionedManager) writeRefreshToken(refreshToken accesstokens.RefreshToken, partitionKey string) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + key := refreshToken.Key() + if m.contract.AccessTokensPartition[partitionKey] == nil { + m.contract.RefreshTokensPartition[partitionKey] = make(map[string]accesstokens.RefreshToken) + } + m.contract.RefreshTokensPartition[partitionKey][key] = refreshToken + return nil +} + +func (m *PartitionedManager) readIDToken(envAliases []string, realm, clientID, userAssertionHash, partitionKey string) (IDToken, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + for _, idt := range m.contract.IDTokensPartition[partitionKey] { + if idt.Realm == realm && idt.ClientID == clientID && idt.UserAssertionHash == userAssertionHash { + if checkAlias(idt.Environment, envAliases) { + return idt, nil + } + } + } + return IDToken{}, fmt.Errorf("token not found") +} + +func (m *PartitionedManager) writeIDToken(idToken IDToken, partitionKey string) error { + key := idToken.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + if m.contract.IDTokensPartition[partitionKey] == nil { + m.contract.IDTokensPartition[partitionKey] = make(map[string]IDToken) + } + m.contract.IDTokensPartition[partitionKey][key] = idToken + return nil +} + +func (m *PartitionedManager) readAccount(envAliases []string, realm, UserAssertionHash, partitionKey string) (shared.Account, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + // You might ask why, if cache.Accounts is a map, we would loop through all of these instead of using a key. + // We only use a map because the storage contract shared between all language implementations says use a map. + // We can't change that. The other is because the keys are made using a specific "env", but here we are allowing + // a match in multiple envs (envAlias). That means we either need to hash each possible keyand do the lookup + // or just statically check. Since the design is to have a storage.Manager per user, the amount of keys stored + // is really low (say 2). Each hash is more expensive than the entire iteration. + for _, acc := range m.contract.AccountsPartition[partitionKey] { + if checkAlias(acc.Environment, envAliases) && acc.UserAssertionHash == UserAssertionHash && acc.Realm == realm { + return acc, nil + } + } + return shared.Account{}, fmt.Errorf("account not found") +} + +func (m *PartitionedManager) writeAccount(account shared.Account, partitionKey string) error { + key := account.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + if m.contract.AccountsPartition[partitionKey] == nil { + m.contract.AccountsPartition[partitionKey] = make(map[string]shared.Account) + } + m.contract.AccountsPartition[partitionKey][key] = account + return nil +} + +func (m *PartitionedManager) readAppMetaData(envAliases []string, clientID string) (AppMetaData, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + for _, app := range m.contract.AppMetaData { + if checkAlias(app.Environment, envAliases) && app.ClientID == clientID { + return app, nil + } + } + return AppMetaData{}, fmt.Errorf("not found") +} + +func (m *PartitionedManager) writeAppMetaData(AppMetaData AppMetaData) error { + key := AppMetaData.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.AppMetaData[key] = AppMetaData + return nil +} + +// update updates the internal cache object. This is for use in tests, other uses are not +// supported. +func (m *PartitionedManager) update(cache *InMemoryContract) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract = cache +} + +// Marshal implements cache.Marshaler. +func (m *PartitionedManager) Marshal() ([]byte, error) { + return json.Marshal(m.contract) +} + +// Unmarshal implements cache.Unmarshaler. +func (m *PartitionedManager) Unmarshal(b []byte) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + + contract := NewInMemoryContract() + + err := json.Unmarshal(b, contract) + if err != nil { + return err + } + + m.contract = contract + + return nil +} + +func getPartitionKeyAccessToken(item AccessToken) string { + if item.UserAssertionHash != "" { + return item.UserAssertionHash + } + return item.HomeAccountID +} + +func getPartitionKeyRefreshToken(item accesstokens.RefreshToken) string { + if item.UserAssertionHash != "" { + return item.UserAssertionHash + } + return item.HomeAccountID +} + +func getPartitionKeyIDToken(item IDToken) string { + return item.HomeAccountID +} + +func getPartitionKeyAccount(item shared.Account) string { + return item.HomeAccountID +} + +func getPartitionKeyIDTokenRead(item AccessToken) string { + return item.HomeAccountID +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go new file mode 100644 index 000000000..2221e60c4 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go @@ -0,0 +1,583 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package storage holds all cached token information for MSAL. This storage can be +// augmented with third-party extensions to provide persistent storage. In that case, +// reads and writes in upper packages will call Marshal() to take the entire in-memory +// representation and write it to storage and Unmarshal() to update the entire in-memory +// storage with what was in the persistent storage. The persistent storage can only be +// accessed in this way because multiple MSAL clients written in multiple languages can +// access the same storage and must adhere to the same method that was defined +// previously. +package storage + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// aadInstanceDiscoveryer allows faking in tests. +// It is implemented in production by ops/authority.Client +type aadInstanceDiscoveryer interface { + AADInstanceDiscovery(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryResponse, error) +} + +// TokenResponse mimics a token response that was pulled from the cache. +type TokenResponse struct { + RefreshToken accesstokens.RefreshToken + IDToken IDToken // *Credential + AccessToken AccessToken + Account shared.Account +} + +// Manager is an in-memory cache of access tokens, accounts and meta data. This data is +// updated on read/write calls. Unmarshal() replaces all data stored here with whatever +// was given to it on each call. +type Manager struct { + contract *Contract + contractMu sync.RWMutex + requests aadInstanceDiscoveryer // *oauth.Token + + aadCacheMu sync.RWMutex + aadCache map[string]authority.InstanceDiscoveryMetadata +} + +// New is the constructor for Manager. +func New(requests *oauth.Client) *Manager { + m := &Manager{requests: requests, aadCache: make(map[string]authority.InstanceDiscoveryMetadata)} + m.contract = NewContract() + return m +} + +func checkAlias(alias string, aliases []string) bool { + for _, v := range aliases { + if alias == v { + return true + } + } + return false +} + +func isMatchingScopes(scopesOne []string, scopesTwo string) bool { + newScopesTwo := strings.Split(scopesTwo, scopeSeparator) + scopeCounter := 0 + for _, scope := range scopesOne { + for _, otherScope := range newScopesTwo { + if strings.EqualFold(scope, otherScope) { + scopeCounter++ + continue + } + } + } + return scopeCounter == len(scopesOne) +} + +// needsUpgrade returns true if the given key follows the v1.0 schema i.e., +// it contains an uppercase character (v1.1+ keys are all lowercase) +func needsUpgrade(key string) bool { + for _, r := range key { + if 'A' <= r && r <= 'Z' { + return true + } + } + return false +} + +// upgrade a v1.0 cache item by adding a v1.1+ item having the same value and deleting +// the v1.0 item. Callers must hold an exclusive lock on m. +func upgrade[T any](m map[string]T, k string) T { + v1_1Key := strings.ToLower(k) + v, ok := m[k] + if !ok { + // another goroutine did the upgrade while this one was waiting for the write lock + return m[v1_1Key] + } + if v2, ok := m[v1_1Key]; ok { + // cache has an equivalent v1.1+ item, which we prefer because we know it was added + // by a newer version of the module and is therefore more likely to remain valid. + // The v1.0 item may have expired because only v1.0 or earlier would update it. + v = v2 + } else { + // add an equivalent item according to the v1.1 schema + m[v1_1Key] = v + } + delete(m, k) + return v +} + +// Read reads a storage token from the cache if it exists. +func (m *Manager) Read(ctx context.Context, authParameters authority.AuthParams) (TokenResponse, error) { + tr := TokenResponse{} + homeAccountID := authParameters.HomeAccountID + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + scopes := authParameters.Scopes + authnSchemeKeyID := authParameters.AuthnScheme.KeyID() + tokenType := authParameters.AuthnScheme.AccessTokenType() + + // fetch metadata if instanceDiscovery is enabled + aliases := []string{authParameters.AuthorityInfo.Host} + if !authParameters.AuthorityInfo.InstanceDiscoveryDisabled { + metadata, err := m.getMetadataEntry(ctx, authParameters.AuthorityInfo) + if err != nil { + return TokenResponse{}, err + } + aliases = metadata.Aliases + } + + accessToken := m.readAccessToken(homeAccountID, aliases, realm, clientID, scopes, tokenType, authnSchemeKeyID) + tr.AccessToken = accessToken + + if homeAccountID == "" { + // caller didn't specify a user, so there's no reason to search for an ID or refresh token + return tr, nil + } + // errors returned by read* methods indicate a cache miss and are therefore non-fatal. We continue populating + // TokenResponse fields so that e.g. lack of an ID token doesn't prevent the caller from receiving a refresh token. + idToken, err := m.readIDToken(homeAccountID, aliases, realm, clientID) + if err == nil { + tr.IDToken = idToken + } + + if appMetadata, err := m.readAppMetaData(aliases, clientID); err == nil { + // we need the family ID to identify the correct refresh token, if any + familyID := appMetadata.FamilyID + refreshToken, err := m.readRefreshToken(homeAccountID, aliases, familyID, clientID) + if err == nil { + tr.RefreshToken = refreshToken + } + } + + account, err := m.readAccount(homeAccountID, aliases, realm) + if err == nil { + tr.Account = account + } + return tr, nil +} + +const scopeSeparator = " " + +// Write writes a token response to the cache and returns the account information the token is stored with. +func (m *Manager) Write(authParameters authority.AuthParams, tokenResponse accesstokens.TokenResponse) (shared.Account, error) { + homeAccountID := tokenResponse.HomeAccountID() + environment := authParameters.AuthorityInfo.Host + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + target := strings.Join(tokenResponse.GrantedScopes.Slice, scopeSeparator) + cachedAt := time.Now() + authnSchemeKeyID := authParameters.AuthnScheme.KeyID() + + var account shared.Account + + if len(tokenResponse.RefreshToken) > 0 { + refreshToken := accesstokens.NewRefreshToken(homeAccountID, environment, clientID, tokenResponse.RefreshToken, tokenResponse.FamilyID) + if err := m.writeRefreshToken(refreshToken); err != nil { + return account, err + } + } + + if len(tokenResponse.AccessToken) > 0 { + accessToken := NewAccessToken( + homeAccountID, + environment, + realm, + clientID, + cachedAt, + tokenResponse.ExpiresOn.T, + tokenResponse.ExtExpiresOn.T, + target, + tokenResponse.AccessToken, + tokenResponse.TokenType, + authnSchemeKeyID, + ) + + // Since we have a valid access token, cache it before moving on. + if err := accessToken.Validate(); err == nil { + if err := m.writeAccessToken(accessToken); err != nil { + return account, err + } + } + } + + idTokenJwt := tokenResponse.IDToken + if !idTokenJwt.IsZero() { + idToken := NewIDToken(homeAccountID, environment, realm, clientID, idTokenJwt.RawToken) + if err := m.writeIDToken(idToken); err != nil { + return shared.Account{}, err + } + + localAccountID := idTokenJwt.LocalAccountID() + authorityType := authParameters.AuthorityInfo.AuthorityType + + preferredUsername := idTokenJwt.UPN + if idTokenJwt.PreferredUsername != "" { + preferredUsername = idTokenJwt.PreferredUsername + } + + account = shared.NewAccount( + homeAccountID, + environment, + realm, + localAccountID, + authorityType, + preferredUsername, + ) + if err := m.writeAccount(account); err != nil { + return shared.Account{}, err + } + } + + AppMetaData := NewAppMetaData(tokenResponse.FamilyID, clientID, environment) + + if err := m.writeAppMetaData(AppMetaData); err != nil { + return shared.Account{}, err + } + return account, nil +} + +func (m *Manager) getMetadataEntry(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + md, err := m.aadMetadataFromCache(ctx, authorityInfo) + if err != nil { + // not in the cache, retrieve it + md, err = m.aadMetadata(ctx, authorityInfo) + } + return md, err +} + +func (m *Manager) aadMetadataFromCache(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + m.aadCacheMu.RLock() + defer m.aadCacheMu.RUnlock() + metadata, ok := m.aadCache[authorityInfo.Host] + if ok { + return metadata, nil + } + return metadata, errors.New("not found") +} + +func (m *Manager) aadMetadata(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + m.aadCacheMu.Lock() + defer m.aadCacheMu.Unlock() + discoveryResponse, err := m.requests.AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return authority.InstanceDiscoveryMetadata{}, err + } + + for _, metadataEntry := range discoveryResponse.Metadata { + for _, aliasedAuthority := range metadataEntry.Aliases { + m.aadCache[aliasedAuthority] = metadataEntry + } + } + if _, ok := m.aadCache[authorityInfo.Host]; !ok { + m.aadCache[authorityInfo.Host] = authority.InstanceDiscoveryMetadata{ + PreferredNetwork: authorityInfo.Host, + PreferredCache: authorityInfo.Host, + } + } + return m.aadCache[authorityInfo.Host], nil +} + +func (m *Manager) readAccessToken(homeID string, envAliases []string, realm, clientID string, scopes []string, tokenType, authnSchemeKeyID string) AccessToken { + m.contractMu.RLock() + // TODO: linear search (over a map no less) is slow for a large number (thousands) of tokens. + // this shows up as the dominating node in a profile. for real-world scenarios this likely isn't + // an issue, however if it does become a problem then we know where to look. + for k, at := range m.contract.AccessTokens { + if at.HomeAccountID == homeID && at.Realm == realm && at.ClientID == clientID { + if (strings.EqualFold(at.TokenType, tokenType) && at.AuthnSchemeKeyID == authnSchemeKeyID) || (at.TokenType == "" && (tokenType == "" || tokenType == "Bearer")) { + if checkAlias(at.Environment, envAliases) && isMatchingScopes(scopes, at.Scopes) { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + at = upgrade(m.contract.AccessTokens, k) + } + return at + } + } + } + } + m.contractMu.RUnlock() + return AccessToken{} +} + +func (m *Manager) writeAccessToken(accessToken AccessToken) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + key := accessToken.Key() + m.contract.AccessTokens[key] = accessToken + return nil +} + +func (m *Manager) readRefreshToken(homeID string, envAliases []string, familyID, clientID string) (accesstokens.RefreshToken, error) { + byFamily := func(rt accesstokens.RefreshToken) bool { + return matchFamilyRefreshToken(rt, homeID, envAliases) + } + byClient := func(rt accesstokens.RefreshToken) bool { + return matchClientIDRefreshToken(rt, homeID, envAliases, clientID) + } + + var matchers []func(rt accesstokens.RefreshToken) bool + if familyID == "" { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byClient, byFamily, + } + } else { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byFamily, byClient, + } + } + + // TODO(keegan): All the tests here pass, but Bogdan says this is + // more complicated. I'm opening an issue for this to have him + // review the tests and suggest tests that would break this so + // we can re-write against good tests. His comments as follow: + // The algorithm is a bit more complex than this, I assume there are some tests covering everything. I would keep the order as is. + // The algorithm is: + // If application is NOT part of the family, search by client_ID + // If app is part of the family or if we DO NOT KNOW if it's part of the family, search by family ID, then by client_id (we will know if an app is part of the family after the first token response). + // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/311fe8b16e7c293462806f397e189a6aa1159769/src/client/Microsoft.Identity.Client/Internal/Requests/Silent/CacheSilentStrategy.cs#L95 + m.contractMu.RLock() + for _, matcher := range matchers { + for k, rt := range m.contract.RefreshTokens { + if matcher(rt) { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + rt = upgrade(m.contract.RefreshTokens, k) + } + return rt, nil + } + } + } + + m.contractMu.RUnlock() + return accesstokens.RefreshToken{}, fmt.Errorf("refresh token not found") +} + +func matchFamilyRefreshToken(rt accesstokens.RefreshToken, homeID string, envAliases []string) bool { + return rt.HomeAccountID == homeID && checkAlias(rt.Environment, envAliases) && rt.FamilyID != "" +} + +func matchClientIDRefreshToken(rt accesstokens.RefreshToken, homeID string, envAliases []string, clientID string) bool { + return rt.HomeAccountID == homeID && checkAlias(rt.Environment, envAliases) && rt.ClientID == clientID +} + +func (m *Manager) writeRefreshToken(refreshToken accesstokens.RefreshToken) error { + key := refreshToken.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.RefreshTokens[key] = refreshToken + return nil +} + +func (m *Manager) readIDToken(homeID string, envAliases []string, realm, clientID string) (IDToken, error) { + m.contractMu.RLock() + for k, idt := range m.contract.IDTokens { + if idt.HomeAccountID == homeID && idt.Realm == realm && idt.ClientID == clientID { + if checkAlias(idt.Environment, envAliases) { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + idt = upgrade(m.contract.IDTokens, k) + } + return idt, nil + } + } + } + m.contractMu.RUnlock() + return IDToken{}, fmt.Errorf("token not found") +} + +func (m *Manager) writeIDToken(idToken IDToken) error { + key := idToken.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.IDTokens[key] = idToken + return nil +} + +func (m *Manager) AllAccounts() []shared.Account { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + var accounts []shared.Account + for _, v := range m.contract.Accounts { + accounts = append(accounts, v) + } + + return accounts +} + +func (m *Manager) Account(homeAccountID string) shared.Account { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + for _, v := range m.contract.Accounts { + if v.HomeAccountID == homeAccountID { + return v + } + } + + return shared.Account{} +} + +func (m *Manager) readAccount(homeAccountID string, envAliases []string, realm string) (shared.Account, error) { + m.contractMu.RLock() + + // You might ask why, if cache.Accounts is a map, we would loop through all of these instead of using a key. + // We only use a map because the storage contract shared between all language implementations says use a map. + // We can't change that. The other is because the keys are made using a specific "env", but here we are allowing + // a match in multiple envs (envAlias). That means we either need to hash each possible keyand do the lookup + // or just statically check. Since the design is to have a storage.Manager per user, the amount of keys stored + // is really low (say 2). Each hash is more expensive than the entire iteration. + for k, acc := range m.contract.Accounts { + if acc.HomeAccountID == homeAccountID && checkAlias(acc.Environment, envAliases) && acc.Realm == realm { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + acc = upgrade(m.contract.Accounts, k) + } + return acc, nil + } + } + m.contractMu.RUnlock() + return shared.Account{}, fmt.Errorf("account not found") +} + +func (m *Manager) writeAccount(account shared.Account) error { + key := account.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.Accounts[key] = account + return nil +} + +func (m *Manager) readAppMetaData(envAliases []string, clientID string) (AppMetaData, error) { + m.contractMu.RLock() + for k, app := range m.contract.AppMetaData { + if checkAlias(app.Environment, envAliases) && app.ClientID == clientID { + m.contractMu.RUnlock() + if needsUpgrade(k) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + app = upgrade(m.contract.AppMetaData, k) + } + return app, nil + } + } + m.contractMu.RUnlock() + return AppMetaData{}, fmt.Errorf("not found") +} + +func (m *Manager) writeAppMetaData(AppMetaData AppMetaData) error { + key := AppMetaData.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.AppMetaData[key] = AppMetaData + return nil +} + +// RemoveAccount removes all the associated ATs, RTs and IDTs from the cache associated with this account. +func (m *Manager) RemoveAccount(account shared.Account, clientID string) { + m.removeRefreshTokens(account.HomeAccountID, account.Environment, clientID) + m.removeAccessTokens(account.HomeAccountID, account.Environment) + m.removeIDTokens(account.HomeAccountID, account.Environment) + m.removeAccounts(account.HomeAccountID, account.Environment) +} + +func (m *Manager) removeRefreshTokens(homeID string, env string, clientID string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, rt := range m.contract.RefreshTokens { + // Check for RTs associated with the account. + if rt.HomeAccountID == homeID && rt.Environment == env { + // Do RT's app ownership check as a precaution, in case family apps + // and 3rd-party apps share same token cache, although they should not. + if rt.ClientID == clientID || rt.FamilyID != "" { + delete(m.contract.RefreshTokens, key) + } + } + } +} + +func (m *Manager) removeAccessTokens(homeID string, env string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, at := range m.contract.AccessTokens { + // Remove AT's associated with the account + if at.HomeAccountID == homeID && at.Environment == env { + // # To avoid the complexity of locating sibling family app's AT, we skip AT's app ownership check. + // It means ATs for other apps will also be removed, it is OK because: + // non-family apps are not supposed to share token cache to begin with; + // Even if it happens, we keep other app's RT already, so SSO still works. + delete(m.contract.AccessTokens, key) + } + } +} + +func (m *Manager) removeIDTokens(homeID string, env string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, idt := range m.contract.IDTokens { + // Remove ID tokens associated with the account. + if idt.HomeAccountID == homeID && idt.Environment == env { + delete(m.contract.IDTokens, key) + } + } +} + +func (m *Manager) removeAccounts(homeID string, env string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, acc := range m.contract.Accounts { + // Remove the specified account. + if acc.HomeAccountID == homeID && acc.Environment == env { + delete(m.contract.Accounts, key) + } + } +} + +// update updates the internal cache object. This is for use in tests, other uses are not +// supported. +func (m *Manager) update(cache *Contract) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract = cache +} + +// Marshal implements cache.Marshaler. +func (m *Manager) Marshal() ([]byte, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + return json.Marshal(m.contract) +} + +// Unmarshal implements cache.Unmarshaler. +func (m *Manager) Unmarshal(b []byte) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + + contract := NewContract() + + err := json.Unmarshal(b, contract) + if err != nil { + return err + } + + m.contract = contract + + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go new file mode 100644 index 000000000..7b673e3fe --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// package exported contains internal types that are re-exported from a public package +package exported + +// AssertionRequestOptions has information required to generate a client assertion +type AssertionRequestOptions struct { + // ClientID identifies the application for which an assertion is requested. Used as the assertion's "iss" and "sub" claims. + ClientID string + + // TokenEndpoint is the intended token endpoint. Used as the assertion's "aud" claim. + TokenEndpoint string +} + +// TokenProviderParameters is the authentication parameters passed to token providers +type TokenProviderParameters struct { + // Claims contains any additional claims requested for the token + Claims string + // CorrelationID of the authentication request + CorrelationID string + // Scopes requested for the token + Scopes []string + // TenantID identifies the tenant in which to authenticate + TenantID string +} + +// TokenProviderResult is the authentication result returned by custom token providers +type TokenProviderResult struct { + // AccessToken is the requested token + AccessToken string + // ExpiresInSeconds is the lifetime of the token in seconds + ExpiresInSeconds int +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/design.md b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/design.md new file mode 100644 index 000000000..09edb01b7 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/design.md @@ -0,0 +1,140 @@ +# JSON Package Design +Author: John Doak(jdoak@microsoft.com) + +## Why? + +This project needs a special type of marshal/unmarshal not directly supported +by the encoding/json package. + +The need revolves around a few key wants/needs: +- unmarshal and marshal structs representing JSON messages +- fields in the messgage not in the struct must be maintained when unmarshalled +- those same fields must be marshalled back when encoded again + +The initial version used map[string]interface{} to put in the keys that +were known and then any other keys were put into a field called AdditionalFields. + +This has a few negatives: +- Dual marshaling/unmarshalling is required +- Adding a struct field requires manually adding a key by name to be encoded/decoded from the map (which is a loosely coupled construct), which can lead to bugs that aren't detected or have bad side effects +- Tests can become quickly disconnected if those keys aren't put +in tests as well. So you think you have support working, but you +don't. Existing tests were found that didn't test the marshalling output. +- There is no enforcement that if AdditionalFields is required on one struct, it should be on all containers +that don't have custom marshal/unmarshal. + +This package aims to support our needs by providing custom Marshal()/Unmarshal() functions. + +This prevents all the negatives in the initial solution listed above. However, it does add its own negative: +- Custom encoding/decoding via reflection is messy (as can be seen in encoding/json itself) + +Go proverb: Reflection is never clear +Suggested reading: https://blog.golang.org/laws-of-reflection + +## Important design decisions + +- We don't want to understand all JSON decoding rules +- We don't want to deal with all the quoting, commas, etc on decode +- Need support for json.Marshaler/Unmarshaler, so we can support types like time.Time +- If struct does not implement json.Unmarshaler, it must have AdditionalFields defined +- We only support root level objects that are \*struct or struct + +To faciliate these goals, we will utilize the json.Encoder and json.Decoder. +They provide streaming processing (efficient) and return errors on bad JSON. + +Support for json.Marshaler/Unmarshaler allows for us to use non-basic types +that must be specially encoded/decoded (like time.Time objects). + +We don't support types that can't customer unmarshal or have AdditionalFields +in order to prevent future devs from forgetting that important field and +generating bad return values. + +Support for root level objects of \*struct or struct simply acknowledges the +fact that this is designed only for the purposes listed in the Introduction. +Outside that (like encoding a lone number) should be done with the +regular json package (as it will not have additional fields). + +We don't support a few things on json supported reference types and structs: +- \*map: no need for pointers to maps +- \*slice: no need for pointers to slices +- any further pointers on struct after \*struct + +There should never be a need for this in Go. + +## Design + +## State Machines + +This uses state machine designs that based upon the Rob Pike talk on +lexers and parsers: https://www.youtube.com/watch?v=HxaD_trXwRE + +This is the most common pattern for state machines in Go and +the model to follow closesly when dealing with streaming +processing of textual data. + +Our state machines are based on the type: +```go +type stateFn func() (stateFn, error) +``` + +The state machine itself is simply a struct that has methods that +satisfy stateFn. + +Our state machines have a few standard calls +- run(): runs the state machine +- start(): always the first stateFn to be called + +All state machines have the following logic: +* run() is called +* start() is called and returns the next stateFn or error +* stateFn is called + - If returned stateFn(next state) is non-nil, call it + - If error is non-nil, run() returns the error + - If stateFn == nil and err == nil, run() return err == nil + +## Supporting types + +Marshalling/Unmarshalling must support(within top level struct): +- struct +- \*struct +- []struct +- []\*struct +- []map[string]structContainer +- [][]structContainer + +**Term note:** structContainer == type that has a struct or \*struct inside it + +We specifically do not support []interface or map[string]interface +where the interface value would hold some value with a struct in it. + +Those will still marshal/unmarshal, but without support for +AdditionalFields. + +## Marshalling + +The marshalling design will be based around a statemachine design. + +The basic logic is as follows: + +* If struct has custom marshaller, call it and return +* If struct has field "AdditionalFields", it must be a map[string]interface{} +* If struct does not have "AdditionalFields", give an error +* Get struct tag detailing json names to go names, create mapping +* For each public field name + - Write field name out + - If field value is a struct, recursively call our state machine + - Otherwise, use the json.Encoder to write out the value + +## Unmarshalling + +The unmarshalling desin is also based around a statemachine design. The +basic logic is as follows: + +* If struct has custom marhaller, call it +* If struct has field "AdditionalFields", it must be a map[string]interface{} +* Get struct tag detailing json names to go names, create mapping +* For each key found + - If key exists, + - If value is basic type, extract value into struct field using Decoder + - If value is struct type, recursively call statemachine + - If key doesn't exist, add it to AdditionalFields if it exists using Decoder diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/json.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/json.go new file mode 100644 index 000000000..2238521f5 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/json.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package json provide functions for marshalling an unmarshalling types to JSON. These functions are meant to +// be utilized inside of structs that implement json.Unmarshaler and json.Marshaler interfaces. +// This package provides the additional functionality of writing fields that are not in the struct when marshalling +// to a field called AdditionalFields if that field exists and is a map[string]interface{}. +// When marshalling, if the struct has all the same prerequisites, it will uses the keys in AdditionalFields as +// extra fields. This package uses encoding/json underneath. +package json + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + "strings" +) + +const addField = "AdditionalFields" +const ( + marshalJSON = "MarshalJSON" + unmarshalJSON = "UnmarshalJSON" +) + +var ( + leftBrace = []byte("{")[0] + rightBrace = []byte("}")[0] + comma = []byte(",")[0] + leftParen = []byte("[")[0] + rightParen = []byte("]")[0] +) + +var mapStrInterType = reflect.TypeOf(map[string]interface{}{}) + +// stateFn defines a state machine function. This will be used in all state +// machines in this package. +type stateFn func() (stateFn, error) + +// Marshal is used to marshal a type into its JSON representation. It +// wraps the stdlib calls in order to marshal a struct or *struct so +// that a field called "AdditionalFields" of type map[string]interface{} +// with "-" used inside struct tag `json:"-"` can be marshalled as if +// they were fields within the struct. +func Marshal(i interface{}) ([]byte, error) { + buff := bytes.Buffer{} + enc := json.NewEncoder(&buff) + enc.SetEscapeHTML(false) + enc.SetIndent("", "") + + v := reflect.ValueOf(i) + if v.Kind() != reflect.Ptr && v.CanAddr() { + v = v.Addr() + } + err := marshalStruct(v, &buff, enc) + if err != nil { + return nil, err + } + return buff.Bytes(), nil +} + +// Unmarshal unmarshals a []byte representing JSON into i, which must be a *struct. In addition, if the struct has +// a field called AdditionalFields of type map[string]interface{}, JSON data representing fields not in the struct +// will be written as key/value pairs to AdditionalFields. +func Unmarshal(b []byte, i interface{}) error { + if len(b) == 0 { + return nil + } + + jdec := json.NewDecoder(bytes.NewBuffer(b)) + jdec.UseNumber() + return unmarshalStruct(jdec, i) +} + +// MarshalRaw marshals i into a json.RawMessage. If I cannot be marshalled, +// this will panic. This is exposed to help test AdditionalField values +// which are stored as json.RawMessage. +func MarshalRaw(i interface{}) json.RawMessage { + b, err := json.Marshal(i) + if err != nil { + panic(err) + } + return json.RawMessage(b) +} + +// isDelim simply tests to see if a json.Token is a delimeter. +func isDelim(got json.Token) bool { + switch got.(type) { + case json.Delim: + return true + } + return false +} + +// delimIs tests got to see if it is want. +func delimIs(got json.Token, want rune) bool { + switch v := got.(type) { + case json.Delim: + if v == json.Delim(want) { + return true + } + } + return false +} + +// hasMarshalJSON will determine if the value or a pointer to this value has +// the MarshalJSON method. +func hasMarshalJSON(v reflect.Value) bool { + if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid { + _, ok := v.Interface().(json.Marshaler) + return ok + } + + if v.Kind() == reflect.Ptr { + v = v.Elem() + } else { + if !v.CanAddr() { + return false + } + v = v.Addr() + } + + if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid { + _, ok := v.Interface().(json.Marshaler) + return ok + } + return false +} + +// callMarshalJSON will call MarshalJSON() method on the value or a pointer to this value. +// This will panic if the method is not defined. +func callMarshalJSON(v reflect.Value) ([]byte, error) { + if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid { + marsh := v.Interface().(json.Marshaler) + return marsh.MarshalJSON() + } + + if v.Kind() == reflect.Ptr { + v = v.Elem() + } else { + if v.CanAddr() { + v = v.Addr() + } + } + + if method := v.MethodByName(unmarshalJSON); method.Kind() != reflect.Invalid { + marsh := v.Interface().(json.Marshaler) + return marsh.MarshalJSON() + } + + panic(fmt.Sprintf("callMarshalJSON called on type %T that does not have MarshalJSON defined", v.Interface())) +} + +// hasUnmarshalJSON will determine if the value or a pointer to this value has +// the UnmarshalJSON method. +func hasUnmarshalJSON(v reflect.Value) bool { + // You can't unmarshal on a non-pointer type. + if v.Kind() != reflect.Ptr { + if !v.CanAddr() { + return false + } + v = v.Addr() + } + + if method := v.MethodByName(unmarshalJSON); method.Kind() != reflect.Invalid { + _, ok := v.Interface().(json.Unmarshaler) + return ok + } + + return false +} + +// hasOmitEmpty indicates if the field has instructed us to not output +// the field if omitempty is set on the tag. tag is the string +// returned by reflect.StructField.Tag().Get(). +func hasOmitEmpty(tag string) bool { + sl := strings.Split(tag, ",") + for _, str := range sl { + if str == "omitempty" { + return true + } + } + return false +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/mapslice.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/mapslice.go new file mode 100644 index 000000000..cef442f25 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/mapslice.go @@ -0,0 +1,333 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package json + +import ( + "encoding/json" + "fmt" + "reflect" +) + +// unmarshalMap unmarshal's a map. +func unmarshalMap(dec *json.Decoder, m reflect.Value) error { + if m.Kind() != reflect.Ptr || m.Elem().Kind() != reflect.Map { + panic("unmarshalMap called on non-*map value") + } + mapValueType := m.Elem().Type().Elem() + walk := mapWalk{dec: dec, m: m, valueType: mapValueType} + if err := walk.run(); err != nil { + return err + } + return nil +} + +type mapWalk struct { + dec *json.Decoder + key string + m reflect.Value + valueType reflect.Type +} + +// run runs our decoder state machine. +func (m *mapWalk) run() error { + var state = m.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (m *mapWalk) start() (stateFn, error) { + // maps can have custom unmarshaler's. + if hasUnmarshalJSON(m.m) { + err := m.dec.Decode(m.m.Interface()) + if err != nil { + return nil, err + } + return nil, nil + } + + // We only want to use this if the map value is: + // *struct/struct/map/slice + // otherwise use standard decode + t, _ := m.valueBaseType() + switch t.Kind() { + case reflect.Struct, reflect.Map, reflect.Slice: + delim, err := m.dec.Token() + if err != nil { + return nil, err + } + // This indicates the value was set to JSON null. + if delim == nil { + return nil, nil + } + if !delimIs(delim, '{') { + return nil, fmt.Errorf("Unmarshal expected opening {, received %v", delim) + } + return m.next, nil + case reflect.Ptr: + return nil, fmt.Errorf("do not support maps with values of '**type' or '*reference") + } + + // This is a basic map type, so just use Decode(). + if err := m.dec.Decode(m.m.Interface()); err != nil { + return nil, err + } + + return nil, nil +} + +func (m *mapWalk) next() (stateFn, error) { + if m.dec.More() { + key, err := m.dec.Token() + if err != nil { + return nil, err + } + m.key = key.(string) + return m.storeValue, nil + } + // No more entries, so remove final }. + _, err := m.dec.Token() + if err != nil { + return nil, err + } + return nil, nil +} + +func (m *mapWalk) storeValue() (stateFn, error) { + v := m.valueType + for { + switch v.Kind() { + case reflect.Ptr: + v = v.Elem() + continue + case reflect.Struct: + return m.storeStruct, nil + case reflect.Map: + return m.storeMap, nil + case reflect.Slice: + return m.storeSlice, nil + } + return nil, fmt.Errorf("bug: mapWalk.storeValue() called on unsupported type: %v", v.Kind()) + } +} + +func (m *mapWalk) storeStruct() (stateFn, error) { + v := newValue(m.valueType) + if err := unmarshalStruct(m.dec, v.Interface()); err != nil { + return nil, err + } + + if m.valueType.Kind() == reflect.Ptr { + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v) + return m.next, nil + } + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v.Elem()) + + return m.next, nil +} + +func (m *mapWalk) storeMap() (stateFn, error) { + v := reflect.MakeMap(m.valueType) + ptr := newValue(v.Type()) + ptr.Elem().Set(v) + if err := unmarshalMap(m.dec, ptr); err != nil { + return nil, err + } + + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v) + + return m.next, nil +} + +func (m *mapWalk) storeSlice() (stateFn, error) { + v := newValue(m.valueType) + if err := unmarshalSlice(m.dec, v); err != nil { + return nil, err + } + + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v.Elem()) + + return m.next, nil +} + +// valueType returns the underlying Type. So a *struct would yield +// struct, etc... +func (m *mapWalk) valueBaseType() (reflect.Type, bool) { + ptr := false + v := m.valueType + if v.Kind() == reflect.Ptr { + ptr = true + v = v.Elem() + } + return v, ptr +} + +// unmarshalSlice unmarshal's the next value, which must be a slice, into +// ptrSlice, which must be a pointer to a slice. newValue() can be use to +// create the slice. +func unmarshalSlice(dec *json.Decoder, ptrSlice reflect.Value) error { + if ptrSlice.Kind() != reflect.Ptr || ptrSlice.Elem().Kind() != reflect.Slice { + panic("unmarshalSlice called on non-*[]slice value") + } + sliceValueType := ptrSlice.Elem().Type().Elem() + walk := sliceWalk{ + dec: dec, + s: ptrSlice, + valueType: sliceValueType, + } + if err := walk.run(); err != nil { + return err + } + + return nil +} + +type sliceWalk struct { + dec *json.Decoder + s reflect.Value // *[]slice + valueType reflect.Type +} + +// run runs our decoder state machine. +func (s *sliceWalk) run() error { + var state = s.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (s *sliceWalk) start() (stateFn, error) { + // slices can have custom unmarshaler's. + if hasUnmarshalJSON(s.s) { + err := s.dec.Decode(s.s.Interface()) + if err != nil { + return nil, err + } + return nil, nil + } + + // We only want to use this if the slice value is: + // []*struct/[]struct/[]map/[]slice + // otherwise use standard decode + t := s.valueBaseType() + + switch t.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("cannot unmarshal into a ** or *") + case reflect.Struct, reflect.Map, reflect.Slice: + delim, err := s.dec.Token() + if err != nil { + return nil, err + } + // This indicates the value was set to nil. + if delim == nil { + return nil, nil + } + if !delimIs(delim, '[') { + return nil, fmt.Errorf("Unmarshal expected opening [, received %v", delim) + } + return s.next, nil + } + + if err := s.dec.Decode(s.s.Interface()); err != nil { + return nil, err + } + return nil, nil +} + +func (s *sliceWalk) next() (stateFn, error) { + if s.dec.More() { + return s.storeValue, nil + } + // Nothing left in the slice, remove closing ] + _, err := s.dec.Token() + return nil, err +} + +func (s *sliceWalk) storeValue() (stateFn, error) { + t := s.valueBaseType() + switch t.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("do not support 'pointer to pointer' or 'pointer to reference' types") + case reflect.Struct: + return s.storeStruct, nil + case reflect.Map: + return s.storeMap, nil + case reflect.Slice: + return s.storeSlice, nil + } + return nil, fmt.Errorf("bug: sliceWalk.storeValue() called on unsupported type: %v", t.Kind()) +} + +func (s *sliceWalk) storeStruct() (stateFn, error) { + v := newValue(s.valueType) + if err := unmarshalStruct(s.dec, v.Interface()); err != nil { + return nil, err + } + + if s.valueType.Kind() == reflect.Ptr { + s.s.Elem().Set(reflect.Append(s.s.Elem(), v)) + return s.next, nil + } + + s.s.Elem().Set(reflect.Append(s.s.Elem(), v.Elem())) + return s.next, nil +} + +func (s *sliceWalk) storeMap() (stateFn, error) { + v := reflect.MakeMap(s.valueType) + ptr := newValue(v.Type()) + ptr.Elem().Set(v) + + if err := unmarshalMap(s.dec, ptr); err != nil { + return nil, err + } + + s.s.Elem().Set(reflect.Append(s.s.Elem(), v)) + + return s.next, nil +} + +func (s *sliceWalk) storeSlice() (stateFn, error) { + v := newValue(s.valueType) + if err := unmarshalSlice(s.dec, v); err != nil { + return nil, err + } + + s.s.Elem().Set(reflect.Append(s.s.Elem(), v.Elem())) + + return s.next, nil +} + +// valueType returns the underlying Type. So a *struct would yield +// struct, etc... +func (s *sliceWalk) valueBaseType() reflect.Type { + v := s.valueType + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + return v +} + +// newValue() returns a new *type that represents type passed. +func newValue(valueType reflect.Type) reflect.Value { + if valueType.Kind() == reflect.Ptr { + return reflect.New(valueType.Elem()) + } + return reflect.New(valueType) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/marshal.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/marshal.go new file mode 100644 index 000000000..df5dc6e11 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/marshal.go @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package json + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + "unicode" +) + +// marshalStruct takes in i, which must be a *struct or struct and marshals its content +// as JSON into buff (sometimes with writes to buff directly, sometimes via enc). +// This call is recursive for all fields of *struct or struct type. +func marshalStruct(v reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + // We only care about custom Marshalling a struct. + if v.Kind() != reflect.Struct { + return fmt.Errorf("bug: marshal() received a non *struct or struct, received type %T", v.Interface()) + } + + if hasMarshalJSON(v) { + b, err := callMarshalJSON(v) + if err != nil { + return err + } + buff.Write(b) + return nil + } + + t := v.Type() + + // If it has an AdditionalFields field make sure its the right type. + f := v.FieldByName(addField) + if f.Kind() != reflect.Invalid { + if f.Kind() != reflect.Map { + return fmt.Errorf("type %T has field 'AdditionalFields' that is not a map[string]interface{}", v.Interface()) + } + if !f.Type().AssignableTo(mapStrInterType) { + return fmt.Errorf("type %T has field 'AdditionalFields' that is not a map[string]interface{}", v.Interface()) + } + } + + translator, err := findFields(v) + if err != nil { + return err + } + + buff.WriteByte(leftBrace) + for x := 0; x < v.NumField(); x++ { + field := v.Field(x) + + // We don't access private fields. + if unicode.IsLower(rune(t.Field(x).Name[0])) { + continue + } + + if t.Field(x).Name == addField { + if v.Field(x).Len() > 0 { + if err := writeAddFields(field.Interface(), buff, enc); err != nil { + return err + } + buff.WriteByte(comma) + } + continue + } + + // If they have omitempty set, we don't write out the field if + // it is the zero value. + if hasOmitEmpty(t.Field(x).Tag.Get("json")) { + if v.Field(x).IsZero() { + continue + } + } + + // Write out the field name part. + jsonName := translator.jsonName(t.Field(x).Name) + buff.WriteString(fmt.Sprintf("%q:", jsonName)) + + if field.Kind() == reflect.Ptr { + field = field.Elem() + } + + if err := marshalStructField(field, buff, enc); err != nil { + return err + } + } + + buff.Truncate(buff.Len() - 1) // Remove final comma + buff.WriteByte(rightBrace) + + return nil +} + +func marshalStructField(field reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + // Determine if we need a trailing comma. + defer buff.WriteByte(comma) + + switch field.Kind() { + // If it was a *struct or struct, we need to recursively all marshal(). + case reflect.Struct: + if field.CanAddr() { + field = field.Addr() + } + return marshalStruct(field, buff, enc) + case reflect.Map: + return marshalMap(field, buff, enc) + case reflect.Slice: + return marshalSlice(field, buff, enc) + } + + // It is just a basic type, so encode it. + if err := enc.Encode(field.Interface()); err != nil { + return err + } + buff.Truncate(buff.Len() - 1) // Remove Encode() added \n + + return nil +} + +func marshalMap(v reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + if v.Kind() != reflect.Map { + return fmt.Errorf("bug: marshalMap() called on %T", v.Interface()) + } + if v.Len() == 0 { + buff.WriteByte(leftBrace) + buff.WriteByte(rightBrace) + return nil + } + encoder := mapEncode{m: v, buff: buff, enc: enc} + return encoder.run() +} + +type mapEncode struct { + m reflect.Value + buff *bytes.Buffer + enc *json.Encoder + + valueBaseType reflect.Type +} + +// run runs our encoder state machine. +func (m *mapEncode) run() error { + var state = m.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (m *mapEncode) start() (stateFn, error) { + if hasMarshalJSON(m.m) { + b, err := callMarshalJSON(m.m) + if err != nil { + return nil, err + } + m.buff.Write(b) + return nil, nil + } + + valueBaseType := m.m.Type().Elem() + if valueBaseType.Kind() == reflect.Ptr { + valueBaseType = valueBaseType.Elem() + } + m.valueBaseType = valueBaseType + + switch valueBaseType.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("Marshal does not support ** or *") + case reflect.Struct, reflect.Map, reflect.Slice: + return m.encode, nil + } + + // If the map value doesn't have a struct/map/slice, just Encode() it. + if err := m.enc.Encode(m.m.Interface()); err != nil { + return nil, err + } + m.buff.Truncate(m.buff.Len() - 1) // Remove Encode() added \n + return nil, nil +} + +func (m *mapEncode) encode() (stateFn, error) { + m.buff.WriteByte(leftBrace) + + iter := m.m.MapRange() + for iter.Next() { + // Write the key. + k := iter.Key() + m.buff.WriteString(fmt.Sprintf("%q:", k.String())) + + v := iter.Value() + switch m.valueBaseType.Kind() { + case reflect.Struct: + if v.CanAddr() { + v = v.Addr() + } + if err := marshalStruct(v, m.buff, m.enc); err != nil { + return nil, err + } + case reflect.Map: + if err := marshalMap(v, m.buff, m.enc); err != nil { + return nil, err + } + case reflect.Slice: + if err := marshalSlice(v, m.buff, m.enc); err != nil { + return nil, err + } + default: + panic(fmt.Sprintf("critical bug: mapEncode.encode() called with value base type: %v", m.valueBaseType.Kind())) + } + m.buff.WriteByte(comma) + } + m.buff.Truncate(m.buff.Len() - 1) // Remove final comma + m.buff.WriteByte(rightBrace) + + return nil, nil +} + +func marshalSlice(v reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + if v.Kind() != reflect.Slice { + return fmt.Errorf("bug: marshalSlice() called on %T", v.Interface()) + } + if v.Len() == 0 { + buff.WriteByte(leftParen) + buff.WriteByte(rightParen) + return nil + } + encoder := sliceEncode{s: v, buff: buff, enc: enc} + return encoder.run() +} + +type sliceEncode struct { + s reflect.Value + buff *bytes.Buffer + enc *json.Encoder + + valueBaseType reflect.Type +} + +// run runs our encoder state machine. +func (s *sliceEncode) run() error { + var state = s.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (s *sliceEncode) start() (stateFn, error) { + if hasMarshalJSON(s.s) { + b, err := callMarshalJSON(s.s) + if err != nil { + return nil, err + } + s.buff.Write(b) + return nil, nil + } + + valueBaseType := s.s.Type().Elem() + if valueBaseType.Kind() == reflect.Ptr { + valueBaseType = valueBaseType.Elem() + } + s.valueBaseType = valueBaseType + + switch valueBaseType.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("Marshal does not support ** or *") + case reflect.Struct, reflect.Map, reflect.Slice: + return s.encode, nil + } + + // If the map value doesn't have a struct/map/slice, just Encode() it. + if err := s.enc.Encode(s.s.Interface()); err != nil { + return nil, err + } + s.buff.Truncate(s.buff.Len() - 1) // Remove Encode added \n + + return nil, nil +} + +func (s *sliceEncode) encode() (stateFn, error) { + s.buff.WriteByte(leftParen) + for i := 0; i < s.s.Len(); i++ { + v := s.s.Index(i) + switch s.valueBaseType.Kind() { + case reflect.Struct: + if v.CanAddr() { + v = v.Addr() + } + if err := marshalStruct(v, s.buff, s.enc); err != nil { + return nil, err + } + case reflect.Map: + if err := marshalMap(v, s.buff, s.enc); err != nil { + return nil, err + } + case reflect.Slice: + if err := marshalSlice(v, s.buff, s.enc); err != nil { + return nil, err + } + default: + panic(fmt.Sprintf("critical bug: mapEncode.encode() called with value base type: %v", s.valueBaseType.Kind())) + } + s.buff.WriteByte(comma) + } + s.buff.Truncate(s.buff.Len() - 1) // Remove final comma + s.buff.WriteByte(rightParen) + return nil, nil +} + +// writeAddFields writes the AdditionalFields struct field out to JSON as field +// values. i must be a map[string]interface{} or this will panic. +func writeAddFields(i interface{}, buff *bytes.Buffer, enc *json.Encoder) error { + m := i.(map[string]interface{}) + + x := 0 + for k, v := range m { + buff.WriteString(fmt.Sprintf("%q:", k)) + if err := enc.Encode(v); err != nil { + return err + } + buff.Truncate(buff.Len() - 1) // Remove Encode() added \n + + if x+1 != len(m) { + buff.WriteByte(comma) + } + x++ + } + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/struct.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/struct.go new file mode 100644 index 000000000..07751544a --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/struct.go @@ -0,0 +1,290 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package json + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +func unmarshalStruct(jdec *json.Decoder, i interface{}) error { + v := reflect.ValueOf(i) + if v.Kind() != reflect.Ptr { + return fmt.Errorf("Unmarshal() received type %T, which is not a *struct", i) + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return fmt.Errorf("Unmarshal() received type %T, which is not a *struct", i) + } + + if hasUnmarshalJSON(v) { + // Indicates that this type has a custom Unmarshaler. + return jdec.Decode(v.Addr().Interface()) + } + + f := v.FieldByName(addField) + if f.Kind() == reflect.Invalid { + return fmt.Errorf("Unmarshal(%T) only supports structs that have the field AdditionalFields or implements json.Unmarshaler", i) + } + + if f.Kind() != reflect.Map || !f.Type().AssignableTo(mapStrInterType) { + return fmt.Errorf("type %T has field 'AdditionalFields' that is not a map[string]interface{}", i) + } + + dec := newDecoder(jdec, v) + return dec.run() +} + +type decoder struct { + dec *json.Decoder + value reflect.Value // This will be a reflect.Struct + translator translateFields + key string +} + +func newDecoder(dec *json.Decoder, value reflect.Value) *decoder { + return &decoder{value: value, dec: dec} +} + +// run runs our decoder state machine. +func (d *decoder) run() error { + var state = d.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +// start looks for our opening delimeter '{' and then transitions to looping through our fields. +func (d *decoder) start() (stateFn, error) { + var err error + d.translator, err = findFields(d.value) + if err != nil { + return nil, err + } + + delim, err := d.dec.Token() + if err != nil { + return nil, err + } + if !delimIs(delim, '{') { + return nil, fmt.Errorf("Unmarshal expected opening {, received %v", delim) + } + + return d.next, nil +} + +// next gets the next struct field name from the raw json or stops the machine if we get our closing }. +func (d *decoder) next() (stateFn, error) { + if !d.dec.More() { + // Remove the closing }. + if _, err := d.dec.Token(); err != nil { + return nil, err + } + return nil, nil + } + + key, err := d.dec.Token() + if err != nil { + return nil, err + } + + d.key = key.(string) + return d.storeValue, nil +} + +// storeValue takes the next value and stores it our struct. If the field can't be found +// in the struct, it pushes the operation to storeAdditional(). +func (d *decoder) storeValue() (stateFn, error) { + goName := d.translator.goName(d.key) + if goName == "" { + goName = d.key + } + + // We don't have the field in the struct, so it goes in AdditionalFields. + f := d.value.FieldByName(goName) + if f.Kind() == reflect.Invalid { + return d.storeAdditional, nil + } + + // Indicates that this type has a custom Unmarshaler. + if hasUnmarshalJSON(f) { + err := d.dec.Decode(f.Addr().Interface()) + if err != nil { + return nil, err + } + return d.next, nil + } + + t, isPtr, err := fieldBaseType(d.value, goName) + if err != nil { + return nil, fmt.Errorf("type(%s) had field(%s) %w", d.value.Type().Name(), goName, err) + } + + switch t.Kind() { + // We need to recursively call ourselves on any *struct or struct. + case reflect.Struct: + if isPtr { + if f.IsNil() { + f.Set(reflect.New(t)) + } + } else { + f = f.Addr() + } + if err := unmarshalStruct(d.dec, f.Interface()); err != nil { + return nil, err + } + return d.next, nil + case reflect.Map: + v := reflect.MakeMap(f.Type()) + ptr := newValue(f.Type()) + ptr.Elem().Set(v) + if err := unmarshalMap(d.dec, ptr); err != nil { + return nil, err + } + f.Set(ptr.Elem()) + return d.next, nil + case reflect.Slice: + v := reflect.MakeSlice(f.Type(), 0, 0) + ptr := newValue(f.Type()) + ptr.Elem().Set(v) + if err := unmarshalSlice(d.dec, ptr); err != nil { + return nil, err + } + f.Set(ptr.Elem()) + return d.next, nil + } + + if !isPtr { + f = f.Addr() + } + + // For values that are pointers, we need them to be non-nil in order + // to decode into them. + if f.IsNil() { + f.Set(reflect.New(t)) + } + + if err := d.dec.Decode(f.Interface()); err != nil { + return nil, err + } + + return d.next, nil +} + +// storeAdditional pushes the key/value into our .AdditionalFields map. +func (d *decoder) storeAdditional() (stateFn, error) { + rw := json.RawMessage{} + if err := d.dec.Decode(&rw); err != nil { + return nil, err + } + field := d.value.FieldByName(addField) + if field.IsNil() { + field.Set(reflect.MakeMap(field.Type())) + } + field.SetMapIndex(reflect.ValueOf(d.key), reflect.ValueOf(rw)) + return d.next, nil +} + +func fieldBaseType(v reflect.Value, fieldName string) (t reflect.Type, isPtr bool, err error) { + sf, ok := v.Type().FieldByName(fieldName) + if !ok { + return nil, false, fmt.Errorf("bug: fieldBaseType() lookup of field(%s) on type(%s): do not have field", fieldName, v.Type().Name()) + } + t = sf.Type + if t.Kind() == reflect.Ptr { + t = t.Elem() + isPtr = true + } + if t.Kind() == reflect.Ptr { + return nil, isPtr, fmt.Errorf("received pointer to pointer type, not supported") + } + return t, isPtr, nil +} + +type translateField struct { + jsonName string + goName string +} + +// translateFields is a list of translateFields with a handy lookup method. +type translateFields []translateField + +// goName loops through a list of fields looking for one contaning the jsonName and +// returning the goName. If not found, returns the empty string. +// Note: not a map because at this size slices are faster even in tight loops. +func (t translateFields) goName(jsonName string) string { + for _, entry := range t { + if entry.jsonName == jsonName { + return entry.goName + } + } + return "" +} + +// jsonName loops through a list of fields looking for one contaning the goName and +// returning the jsonName. If not found, returns the empty string. +// Note: not a map because at this size slices are faster even in tight loops. +func (t translateFields) jsonName(goName string) string { + for _, entry := range t { + if entry.goName == goName { + return entry.jsonName + } + } + return "" +} + +var umarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() + +// findFields parses a struct and writes the field tags for lookup. It will return an error +// if any field has a type of *struct or struct that does not implement json.Marshaler. +func findFields(v reflect.Value) (translateFields, error) { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if v.Kind() != reflect.Struct { + return nil, fmt.Errorf("findFields received a %s type, expected *struct or struct", v.Type().Name()) + } + tfs := make([]translateField, 0, v.NumField()) + for i := 0; i < v.NumField(); i++ { + tf := translateField{ + goName: v.Type().Field(i).Name, + jsonName: parseTag(v.Type().Field(i).Tag.Get("json")), + } + switch tf.jsonName { + case "", "-": + tf.jsonName = tf.goName + } + tfs = append(tfs, tf) + + f := v.Field(i) + if f.Kind() == reflect.Ptr { + f = f.Elem() + } + if f.Kind() == reflect.Struct { + if f.Type().Implements(umarshalerType) { + return nil, fmt.Errorf("struct type %q which has field %q which "+ + "doesn't implement json.Unmarshaler", v.Type().Name(), v.Type().Field(i).Name) + } + } + } + return tfs, nil +} + +// parseTag just returns the first entry in the tag. tag is the string +// returned by reflect.StructField.Tag().Get(). +func parseTag(tag string) string { + if idx := strings.Index(tag, ","); idx != -1 { + return tag[:idx] + } + return tag +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time/time.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time/time.go new file mode 100644 index 000000000..a1c99621e --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time/time.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package time provides for custom types to translate time from JSON and other formats +// into time.Time objects. +package time + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// Unix provides a type that can marshal and unmarshal a string representation +// of the unix epoch into a time.Time object. +type Unix struct { + T time.Time +} + +// MarshalJSON implements encoding/json.MarshalJSON(). +func (u Unix) MarshalJSON() ([]byte, error) { + if u.T.IsZero() { + return []byte(""), nil + } + return []byte(fmt.Sprintf("%q", strconv.FormatInt(u.T.Unix(), 10))), nil +} + +// UnmarshalJSON implements encoding/json.UnmarshalJSON(). +func (u *Unix) UnmarshalJSON(b []byte) error { + i, err := strconv.Atoi(strings.Trim(string(b), `"`)) + if err != nil { + return fmt.Errorf("unix time(%s) could not be converted from string to int: %w", string(b), err) + } + u.T = time.Unix(int64(i), 0) + return nil +} + +// DurationTime provides a type that can marshal and unmarshal a string representation +// of a duration from now into a time.Time object. +// Note: I'm not sure this is the best way to do this. What happens is we get a field +// called "expires_in" that represents the seconds from now that this expires. We +// turn that into a time we call .ExpiresOn. But maybe we should be recording +// when the token was received at .TokenRecieved and .ExpiresIn should remain as a duration. +// Then we could have a method called ExpiresOn(). Honestly, the whole thing is +// bad because the server doesn't return a concrete time. I think this is +// cleaner, but its not great either. +type DurationTime struct { + T time.Time +} + +// MarshalJSON implements encoding/json.MarshalJSON(). +func (d DurationTime) MarshalJSON() ([]byte, error) { + if d.T.IsZero() { + return []byte(""), nil + } + + dt := time.Until(d.T) + return []byte(fmt.Sprintf("%d", int64(dt*time.Second))), nil +} + +// UnmarshalJSON implements encoding/json.UnmarshalJSON(). +func (d *DurationTime) UnmarshalJSON(b []byte) error { + i, err := strconv.Atoi(strings.Trim(string(b), `"`)) + if err != nil { + return fmt.Errorf("unix time(%s) could not be converted from string to int: %w", string(b), err) + } + d.T = time.Now().Add(time.Duration(i) * time.Second) + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go new file mode 100644 index 000000000..04236ff31 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package local contains a local HTTP server used with interactive authentication. +package local + +import ( + "context" + "fmt" + "net" + "net/http" + "strconv" + "strings" + "time" +) + +var okPage = []byte(` + + + + + Authentication Complete + + +

      Authentication complete. You can return to the application. Feel free to close this browser tab.

      + + +`) + +const failPage = ` + + + + + Authentication Failed + + +

      Authentication failed. You can return to the application. Feel free to close this browser tab.

      +

      Error details: error %s error_description: %s

      + + +` + +// Result is the result from the redirect. +type Result struct { + // Code is the code sent by the authority server. + Code string + // Err is set if there was an error. + Err error +} + +// Server is an HTTP server. +type Server struct { + // Addr is the address the server is listening on. + Addr string + resultCh chan Result + s *http.Server + reqState string +} + +// New creates a local HTTP server and starts it. +func New(reqState string, port int) (*Server, error) { + var l net.Listener + var err error + var portStr string + if port > 0 { + // use port provided by caller + l, err = net.Listen("tcp", fmt.Sprintf("localhost:%d", port)) + portStr = strconv.FormatInt(int64(port), 10) + } else { + // find a free port + for i := 0; i < 10; i++ { + l, err = net.Listen("tcp", "localhost:0") + if err != nil { + continue + } + addr := l.Addr().String() + portStr = addr[strings.LastIndex(addr, ":")+1:] + break + } + } + if err != nil { + return nil, err + } + + serv := &Server{ + Addr: fmt.Sprintf("http://localhost:%s", portStr), + s: &http.Server{Addr: "localhost:0", ReadHeaderTimeout: time.Second}, + reqState: reqState, + resultCh: make(chan Result, 1), + } + serv.s.Handler = http.HandlerFunc(serv.handler) + + if err := serv.start(l); err != nil { + return nil, err + } + + return serv, nil +} + +func (s *Server) start(l net.Listener) error { + go func() { + err := s.s.Serve(l) + if err != nil { + select { + case s.resultCh <- Result{Err: err}: + default: + } + } + }() + + return nil +} + +// Result gets the result of the redirect operation. Once a single result is returned, the server +// is shutdown. ctx deadline will be honored. +func (s *Server) Result(ctx context.Context) Result { + select { + case <-ctx.Done(): + return Result{Err: ctx.Err()} + case r := <-s.resultCh: + return r + } +} + +// Shutdown shuts down the server. +func (s *Server) Shutdown() { + // Note: You might get clever and think you can do this in handler() as a defer, you can't. + _ = s.s.Shutdown(context.Background()) +} + +func (s *Server) putResult(r Result) { + select { + case s.resultCh <- r: + default: + } +} + +func (s *Server) handler(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + + headerErr := q.Get("error") + if headerErr != "" { + desc := q.Get("error_description") + // Note: It is a little weird we handle some errors by not going to the failPage. If they all should, + // change this to s.error() and make s.error() write the failPage instead of an error code. + _, _ = w.Write([]byte(fmt.Sprintf(failPage, headerErr, desc))) + s.putResult(Result{Err: fmt.Errorf(desc)}) + return + } + + respState := q.Get("state") + switch respState { + case s.reqState: + case "": + s.error(w, http.StatusInternalServerError, "server didn't send OAuth state") + return + default: + s.error(w, http.StatusInternalServerError, "mismatched OAuth state, req(%s), resp(%s)", s.reqState, respState) + return + } + + code := q.Get("code") + if code == "" { + s.error(w, http.StatusInternalServerError, "authorization code missing in query string") + return + } + + _, _ = w.Write(okPage) + s.putResult(Result{Code: code}) +} + +func (s *Server) error(w http.ResponseWriter, code int, str string, i ...interface{}) { + err := fmt.Errorf(str, i...) + http.Error(w, err.Error(), code) + s.putResult(Result{Err: err}) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go new file mode 100644 index 000000000..ef8d908a4 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go @@ -0,0 +1,354 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package oauth + +import ( + "context" + "encoding/json" + "fmt" + "io" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported" + internalTime "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs" + "github.com/google/uuid" +) + +// ResolveEndpointer contains the methods for resolving authority endpoints. +type ResolveEndpointer interface { + ResolveEndpoints(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, error) +} + +// AccessTokens contains the methods for fetching tokens from different sources. +type AccessTokens interface { + DeviceCodeResult(ctx context.Context, authParameters authority.AuthParams) (accesstokens.DeviceCodeResult, error) + FromUsernamePassword(ctx context.Context, authParameters authority.AuthParams) (accesstokens.TokenResponse, error) + FromAuthCode(ctx context.Context, req accesstokens.AuthCodeRequest) (accesstokens.TokenResponse, error) + FromRefreshToken(ctx context.Context, appType accesstokens.AppType, authParams authority.AuthParams, cc *accesstokens.Credential, refreshToken string) (accesstokens.TokenResponse, error) + FromClientSecret(ctx context.Context, authParameters authority.AuthParams, clientSecret string) (accesstokens.TokenResponse, error) + FromAssertion(ctx context.Context, authParameters authority.AuthParams, assertion string) (accesstokens.TokenResponse, error) + FromUserAssertionClientSecret(ctx context.Context, authParameters authority.AuthParams, userAssertion string, clientSecret string) (accesstokens.TokenResponse, error) + FromUserAssertionClientCertificate(ctx context.Context, authParameters authority.AuthParams, userAssertion string, assertion string) (accesstokens.TokenResponse, error) + FromDeviceCodeResult(ctx context.Context, authParameters authority.AuthParams, deviceCodeResult accesstokens.DeviceCodeResult) (accesstokens.TokenResponse, error) + FromSamlGrant(ctx context.Context, authParameters authority.AuthParams, samlGrant wstrust.SamlTokenInfo) (accesstokens.TokenResponse, error) +} + +// FetchAuthority will be implemented by authority.Authority. +type FetchAuthority interface { + UserRealm(context.Context, authority.AuthParams) (authority.UserRealm, error) + AADInstanceDiscovery(context.Context, authority.Info) (authority.InstanceDiscoveryResponse, error) +} + +// FetchWSTrust contains the methods for interacting with WSTrust endpoints. +type FetchWSTrust interface { + Mex(ctx context.Context, federationMetadataURL string) (defs.MexDocument, error) + SAMLTokenInfo(ctx context.Context, authParameters authority.AuthParams, cloudAudienceURN string, endpoint defs.Endpoint) (wstrust.SamlTokenInfo, error) +} + +// Client provides tokens for various types of token requests. +type Client struct { + Resolver ResolveEndpointer + AccessTokens AccessTokens + Authority FetchAuthority + WSTrust FetchWSTrust +} + +// New is the constructor for Token. +func New(httpClient ops.HTTPClient) *Client { + r := ops.New(httpClient) + return &Client{ + Resolver: newAuthorityEndpoint(r), + AccessTokens: r.AccessTokens(), + Authority: r.Authority(), + WSTrust: r.WSTrust(), + } +} + +// ResolveEndpoints gets the authorization and token endpoints and creates an AuthorityEndpoints instance. +func (t *Client) ResolveEndpoints(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, error) { + return t.Resolver.ResolveEndpoints(ctx, authorityInfo, userPrincipalName) +} + +// AADInstanceDiscovery attempts to discover a tenant endpoint (used in OIDC auth with an authorization endpoint). +// This is done by AAD which allows for aliasing of tenants (windows.sts.net is the same as login.windows.com). +func (t *Client) AADInstanceDiscovery(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryResponse, error) { + return t.Authority.AADInstanceDiscovery(ctx, authorityInfo) +} + +// AuthCode returns a token based on an authorization code. +func (t *Client) AuthCode(ctx context.Context, req accesstokens.AuthCodeRequest) (accesstokens.TokenResponse, error) { + if err := scopeError(req.AuthParams); err != nil { + return accesstokens.TokenResponse{}, err + } + if err := t.resolveEndpoint(ctx, &req.AuthParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + tResp, err := t.AccessTokens.FromAuthCode(ctx, req) + if err != nil { + return accesstokens.TokenResponse{}, fmt.Errorf("could not retrieve token from auth code: %w", err) + } + return tResp, nil +} + +// Credential acquires a token from the authority using a client credentials grant. +func (t *Client) Credential(ctx context.Context, authParams authority.AuthParams, cred *accesstokens.Credential) (accesstokens.TokenResponse, error) { + if cred.TokenProvider != nil { + now := time.Now() + scopes := make([]string, len(authParams.Scopes)) + copy(scopes, authParams.Scopes) + params := exported.TokenProviderParameters{ + Claims: authParams.Claims, + CorrelationID: uuid.New().String(), + Scopes: scopes, + TenantID: authParams.AuthorityInfo.Tenant, + } + tr, err := cred.TokenProvider(ctx, params) + if err != nil { + if len(scopes) == 0 { + err = fmt.Errorf("token request had an empty authority.AuthParams.Scopes, which may cause the following error: %w", err) + return accesstokens.TokenResponse{}, err + } + return accesstokens.TokenResponse{}, err + } + return accesstokens.TokenResponse{ + TokenType: authParams.AuthnScheme.AccessTokenType(), + AccessToken: tr.AccessToken, + ExpiresOn: internalTime.DurationTime{ + T: now.Add(time.Duration(tr.ExpiresInSeconds) * time.Second), + }, + GrantedScopes: accesstokens.Scopes{Slice: authParams.Scopes}, + }, nil + } + + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + if cred.Secret != "" { + return t.AccessTokens.FromClientSecret(ctx, authParams, cred.Secret) + } + jwt, err := cred.JWT(ctx, authParams) + if err != nil { + return accesstokens.TokenResponse{}, err + } + return t.AccessTokens.FromAssertion(ctx, authParams, jwt) +} + +// Credential acquires a token from the authority using a client credentials grant. +func (t *Client) OnBehalfOf(ctx context.Context, authParams authority.AuthParams, cred *accesstokens.Credential) (accesstokens.TokenResponse, error) { + if err := scopeError(authParams); err != nil { + return accesstokens.TokenResponse{}, err + } + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + if cred.Secret != "" { + return t.AccessTokens.FromUserAssertionClientSecret(ctx, authParams, authParams.UserAssertion, cred.Secret) + } + jwt, err := cred.JWT(ctx, authParams) + if err != nil { + return accesstokens.TokenResponse{}, err + } + tr, err := t.AccessTokens.FromUserAssertionClientCertificate(ctx, authParams, authParams.UserAssertion, jwt) + if err != nil { + return accesstokens.TokenResponse{}, err + } + return tr, nil +} + +func (t *Client) Refresh(ctx context.Context, reqType accesstokens.AppType, authParams authority.AuthParams, cc *accesstokens.Credential, refreshToken accesstokens.RefreshToken) (accesstokens.TokenResponse, error) { + if err := scopeError(authParams); err != nil { + return accesstokens.TokenResponse{}, err + } + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + tr, err := t.AccessTokens.FromRefreshToken(ctx, reqType, authParams, cc, refreshToken.Secret) + if err != nil { + return accesstokens.TokenResponse{}, err + } + return tr, nil +} + +// UsernamePassword retrieves a token where a username and password is used. However, if this is +// a user realm of "Federated", this uses SAML tokens. If "Managed", uses normal username/password. +func (t *Client) UsernamePassword(ctx context.Context, authParams authority.AuthParams) (accesstokens.TokenResponse, error) { + if err := scopeError(authParams); err != nil { + return accesstokens.TokenResponse{}, err + } + + if authParams.AuthorityInfo.AuthorityType == authority.ADFS { + if err := t.resolveEndpoint(ctx, &authParams, authParams.Username); err != nil { + return accesstokens.TokenResponse{}, err + } + return t.AccessTokens.FromUsernamePassword(ctx, authParams) + } + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + userRealm, err := t.Authority.UserRealm(ctx, authParams) + if err != nil { + return accesstokens.TokenResponse{}, fmt.Errorf("problem getting user realm from authority: %w", err) + } + + switch userRealm.AccountType { + case authority.Federated: + mexDoc, err := t.WSTrust.Mex(ctx, userRealm.FederationMetadataURL) + if err != nil { + err = fmt.Errorf("problem getting mex doc from federated url(%s): %w", userRealm.FederationMetadataURL, err) + return accesstokens.TokenResponse{}, err + } + + saml, err := t.WSTrust.SAMLTokenInfo(ctx, authParams, userRealm.CloudAudienceURN, mexDoc.UsernamePasswordEndpoint) + if err != nil { + err = fmt.Errorf("problem getting SAML token info: %w", err) + return accesstokens.TokenResponse{}, err + } + tr, err := t.AccessTokens.FromSamlGrant(ctx, authParams, saml) + if err != nil { + return accesstokens.TokenResponse{}, err + } + return tr, nil + case authority.Managed: + if len(authParams.Scopes) == 0 { + err = fmt.Errorf("token request had an empty authority.AuthParams.Scopes, which may cause the following error: %w", err) + return accesstokens.TokenResponse{}, err + } + return t.AccessTokens.FromUsernamePassword(ctx, authParams) + } + return accesstokens.TokenResponse{}, errors.New("unknown account type") +} + +// DeviceCode is the result of a call to Token.DeviceCode(). +type DeviceCode struct { + // Result is the device code result from the first call in the device code flow. This allows + // the caller to retrieve the displayed code that is used to authorize on the second device. + Result accesstokens.DeviceCodeResult + authParams authority.AuthParams + + accessTokens AccessTokens +} + +// Token returns a token AFTER the user uses the user code on the second device. This will block +// until either: (1) the code is input by the user and the service releases a token, (2) the token +// expires, (3) the Context passed to .DeviceCode() is cancelled or expires, (4) some other service +// error occurs. +func (d DeviceCode) Token(ctx context.Context) (accesstokens.TokenResponse, error) { + if d.accessTokens == nil { + return accesstokens.TokenResponse{}, fmt.Errorf("DeviceCode was either created outside its package or the creating method had an error. DeviceCode is not valid") + } + + var cancel context.CancelFunc + if deadline, ok := ctx.Deadline(); !ok || d.Result.ExpiresOn.Before(deadline) { + ctx, cancel = context.WithDeadline(ctx, d.Result.ExpiresOn) + } else { + ctx, cancel = context.WithCancel(ctx) + } + defer cancel() + + var interval = 50 * time.Millisecond + timer := time.NewTimer(interval) + defer timer.Stop() + + for { + timer.Reset(interval) + select { + case <-ctx.Done(): + return accesstokens.TokenResponse{}, ctx.Err() + case <-timer.C: + interval += interval * 2 + if interval > 5*time.Second { + interval = 5 * time.Second + } + } + + token, err := d.accessTokens.FromDeviceCodeResult(ctx, d.authParams, d.Result) + if err != nil && isWaitDeviceCodeErr(err) { + continue + } + return token, err // This handles if it was a non-wait error or success + } +} + +type deviceCodeError struct { + Error string `json:"error"` +} + +func isWaitDeviceCodeErr(err error) bool { + var c errors.CallErr + if !errors.As(err, &c) { + return false + } + if c.Resp.StatusCode != 400 { + return false + } + var dCErr deviceCodeError + defer c.Resp.Body.Close() + body, err := io.ReadAll(c.Resp.Body) + if err != nil { + return false + } + err = json.Unmarshal(body, &dCErr) + if err != nil { + return false + } + if dCErr.Error == "authorization_pending" || dCErr.Error == "slow_down" { + return true + } + return false +} + +// DeviceCode returns a DeviceCode object that can be used to get the code that must be entered on the second +// device and optionally the token once the code has been entered on the second device. +func (t *Client) DeviceCode(ctx context.Context, authParams authority.AuthParams) (DeviceCode, error) { + if err := scopeError(authParams); err != nil { + return DeviceCode{}, err + } + + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return DeviceCode{}, err + } + + dcr, err := t.AccessTokens.DeviceCodeResult(ctx, authParams) + if err != nil { + return DeviceCode{}, err + } + + return DeviceCode{Result: dcr, authParams: authParams, accessTokens: t.AccessTokens}, nil +} + +func (t *Client) resolveEndpoint(ctx context.Context, authParams *authority.AuthParams, userPrincipalName string) error { + endpoints, err := t.Resolver.ResolveEndpoints(ctx, authParams.AuthorityInfo, userPrincipalName) + if err != nil { + return fmt.Errorf("unable to resolve an endpoint: %s", err) + } + authParams.Endpoints = endpoints + return nil +} + +// scopeError takes an authority.AuthParams and returns an error +// if len(AuthParams.Scope) == 0. +func scopeError(a authority.AuthParams) error { + // TODO(someone): we could look deeper at the message to determine if + // it's a scope error, but this is a good start. + /* + {error":"invalid_scope","error_description":"AADSTS1002012: The provided value for scope + openid offline_access profile is not valid. Client credential flows must have a scope value + with /.default suffixed to the resource identifier (application ID URI)...} + */ + if len(a.Scopes) == 0 { + return fmt.Errorf("token request had an empty authority.AuthParams.Scopes, which is invalid") + } + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go new file mode 100644 index 000000000..a7b7b0742 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go @@ -0,0 +1,457 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package accesstokens exposes a REST client for querying backend systems to get various types of +access tokens (oauth) for use in authentication. + +These calls are of type "application/x-www-form-urlencoded". This means we use url.Values to +represent arguments and then encode them into the POST body message. We receive JSON in +return for the requests. The request definition is defined in https://tools.ietf.org/html/rfc7521#section-4.2 . +*/ +package accesstokens + +import ( + "context" + "crypto" + + /* #nosec */ + "crypto/sha1" + "crypto/x509" + "encoding/base64" + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust" + "github.com/golang-jwt/jwt/v5" + "github.com/google/uuid" +) + +const ( + grantType = "grant_type" + deviceCode = "device_code" + clientID = "client_id" + clientInfo = "client_info" + clientInfoVal = "1" + username = "username" + password = "password" +) + +//go:generate stringer -type=AppType + +// AppType is whether the authorization code flow is for a public or confidential client. +type AppType int8 + +const ( + // ATUnknown is the zero value when the type hasn't been set. + ATUnknown AppType = iota + // ATPublic indicates this if for the Public.Client. + ATPublic + // ATConfidential indicates this if for the Confidential.Client. + ATConfidential +) + +type urlFormCaller interface { + URLFormCall(ctx context.Context, endpoint string, qv url.Values, resp interface{}) error +} + +// DeviceCodeResponse represents the HTTP response received from the device code endpoint +type DeviceCodeResponse struct { + authority.OAuthResponseBase + + UserCode string `json:"user_code"` + DeviceCode string `json:"device_code"` + VerificationURL string `json:"verification_url"` + ExpiresIn int `json:"expires_in"` + Interval int `json:"interval"` + Message string `json:"message"` + + AdditionalFields map[string]interface{} +} + +// Convert converts the DeviceCodeResponse to a DeviceCodeResult +func (dcr DeviceCodeResponse) Convert(clientID string, scopes []string) DeviceCodeResult { + expiresOn := time.Now().UTC().Add(time.Duration(dcr.ExpiresIn) * time.Second) + return NewDeviceCodeResult(dcr.UserCode, dcr.DeviceCode, dcr.VerificationURL, expiresOn, dcr.Interval, dcr.Message, clientID, scopes) +} + +// Credential represents the credential used in confidential client flows. This can be either +// a Secret or Cert/Key. +type Credential struct { + // Secret contains the credential secret if we are doing auth by secret. + Secret string + + // Cert is the public certificate, if we're authenticating by certificate. + Cert *x509.Certificate + // Key is the private key for signing, if we're authenticating by certificate. + Key crypto.PrivateKey + // X5c is the JWT assertion's x5c header value, required for SN/I authentication. + X5c []string + + // AssertionCallback is a function provided by the application, if we're authenticating by assertion. + AssertionCallback func(context.Context, exported.AssertionRequestOptions) (string, error) + + // TokenProvider is a function provided by the application that implements custom authentication + // logic for a confidential client + TokenProvider func(context.Context, exported.TokenProviderParameters) (exported.TokenProviderResult, error) +} + +// JWT gets the jwt assertion when the credential is not using a secret. +func (c *Credential) JWT(ctx context.Context, authParams authority.AuthParams) (string, error) { + if c.AssertionCallback != nil { + options := exported.AssertionRequestOptions{ + ClientID: authParams.ClientID, + TokenEndpoint: authParams.Endpoints.TokenEndpoint, + } + return c.AssertionCallback(ctx, options) + } + + token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ + "aud": authParams.Endpoints.TokenEndpoint, + "exp": json.Number(strconv.FormatInt(time.Now().Add(10*time.Minute).Unix(), 10)), + "iss": authParams.ClientID, + "jti": uuid.New().String(), + "nbf": json.Number(strconv.FormatInt(time.Now().Unix(), 10)), + "sub": authParams.ClientID, + }) + token.Header = map[string]interface{}{ + "alg": "RS256", + "typ": "JWT", + "x5t": base64.StdEncoding.EncodeToString(thumbprint(c.Cert)), + } + + if authParams.SendX5C { + token.Header["x5c"] = c.X5c + } + + assertion, err := token.SignedString(c.Key) + if err != nil { + return "", fmt.Errorf("unable to sign a JWT token using private key: %w", err) + } + return assertion, nil +} + +// thumbprint runs the asn1.Der bytes through sha1 for use in the x5t parameter of JWT. +// https://tools.ietf.org/html/rfc7517#section-4.8 +func thumbprint(cert *x509.Certificate) []byte { + /* #nosec */ + a := sha1.Sum(cert.Raw) + return a[:] +} + +// Client represents the REST calls to get tokens from token generator backends. +type Client struct { + // Comm provides the HTTP transport client. + Comm urlFormCaller + + testing bool +} + +// FromUsernamePassword uses a username and password to get an access token. +func (c Client) FromUsernamePassword(ctx context.Context, authParameters authority.AuthParams) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.Password) + qv.Set(username, authParameters.Username) + qv.Set(password, authParameters.Password) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +// AuthCodeRequest stores the values required to request a token from the authority using an authorization code +type AuthCodeRequest struct { + AuthParams authority.AuthParams + Code string + CodeChallenge string + Credential *Credential + AppType AppType +} + +// NewCodeChallengeRequest returns an AuthCodeRequest that uses a code challenge.. +func NewCodeChallengeRequest(params authority.AuthParams, appType AppType, cc *Credential, code, challenge string) (AuthCodeRequest, error) { + if appType == ATUnknown { + return AuthCodeRequest{}, fmt.Errorf("bug: NewCodeChallengeRequest() called with AppType == ATUnknown") + } + return AuthCodeRequest{ + AuthParams: params, + AppType: appType, + Code: code, + CodeChallenge: challenge, + Credential: cc, + }, nil +} + +// FromAuthCode uses an authorization code to retrieve an access token. +func (c Client) FromAuthCode(ctx context.Context, req AuthCodeRequest) (TokenResponse, error) { + var qv url.Values + + switch req.AppType { + case ATUnknown: + return TokenResponse{}, fmt.Errorf("bug: Token.AuthCode() received request with AppType == ATUnknown") + case ATConfidential: + var err error + if req.Credential == nil { + return TokenResponse{}, fmt.Errorf("AuthCodeRequest had nil Credential for Confidential app") + } + qv, err = prepURLVals(ctx, req.Credential, req.AuthParams) + if err != nil { + return TokenResponse{}, err + } + case ATPublic: + qv = url.Values{} + default: + return TokenResponse{}, fmt.Errorf("bug: Token.AuthCode() received request with AppType == %v, which we do not recongnize", req.AppType) + } + + qv.Set(grantType, grant.AuthCode) + qv.Set("code", req.Code) + qv.Set("code_verifier", req.CodeChallenge) + qv.Set("redirect_uri", req.AuthParams.Redirecturi) + qv.Set(clientID, req.AuthParams.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, req.AuthParams) + if err := addClaims(qv, req.AuthParams); err != nil { + return TokenResponse{}, err + } + + return c.doTokenResp(ctx, req.AuthParams, qv) +} + +// FromRefreshToken uses a refresh token (for refreshing credentials) to get a new access token. +func (c Client) FromRefreshToken(ctx context.Context, appType AppType, authParams authority.AuthParams, cc *Credential, refreshToken string) (TokenResponse, error) { + qv := url.Values{} + if appType == ATConfidential { + var err error + qv, err = prepURLVals(ctx, cc, authParams) + if err != nil { + return TokenResponse{}, err + } + } + if err := addClaims(qv, authParams); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.RefreshToken) + qv.Set(clientID, authParams.ClientID) + qv.Set(clientInfo, clientInfoVal) + qv.Set("refresh_token", refreshToken) + addScopeQueryParam(qv, authParams) + + return c.doTokenResp(ctx, authParams, qv) +} + +// FromClientSecret uses a client's secret (aka password) to get a new token. +func (c Client) FromClientSecret(ctx context.Context, authParameters authority.AuthParams, clientSecret string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.ClientCredential) + qv.Set("client_secret", clientSecret) + qv.Set(clientID, authParameters.ClientID) + addScopeQueryParam(qv, authParameters) + + token, err := c.doTokenResp(ctx, authParameters, qv) + if err != nil { + return token, fmt.Errorf("FromClientSecret(): %w", err) + } + return token, nil +} + +func (c Client) FromAssertion(ctx context.Context, authParameters authority.AuthParams, assertion string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.ClientCredential) + qv.Set("client_assertion_type", grant.ClientAssertion) + qv.Set("client_assertion", assertion) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, authParameters) + + token, err := c.doTokenResp(ctx, authParameters, qv) + if err != nil { + return token, fmt.Errorf("FromAssertion(): %w", err) + } + return token, nil +} + +func (c Client) FromUserAssertionClientSecret(ctx context.Context, authParameters authority.AuthParams, userAssertion string, clientSecret string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.JWT) + qv.Set(clientID, authParameters.ClientID) + qv.Set("client_secret", clientSecret) + qv.Set("assertion", userAssertion) + qv.Set(clientInfo, clientInfoVal) + qv.Set("requested_token_use", "on_behalf_of") + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) FromUserAssertionClientCertificate(ctx context.Context, authParameters authority.AuthParams, userAssertion string, assertion string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.JWT) + qv.Set("client_assertion_type", grant.ClientAssertion) + qv.Set("client_assertion", assertion) + qv.Set(clientID, authParameters.ClientID) + qv.Set("assertion", userAssertion) + qv.Set(clientInfo, clientInfoVal) + qv.Set("requested_token_use", "on_behalf_of") + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) DeviceCodeResult(ctx context.Context, authParameters authority.AuthParams) (DeviceCodeResult, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return DeviceCodeResult{}, err + } + qv.Set(clientID, authParameters.ClientID) + addScopeQueryParam(qv, authParameters) + + endpoint := strings.Replace(authParameters.Endpoints.TokenEndpoint, "token", "devicecode", -1) + + resp := DeviceCodeResponse{} + err := c.Comm.URLFormCall(ctx, endpoint, qv, &resp) + if err != nil { + return DeviceCodeResult{}, err + } + + return resp.Convert(authParameters.ClientID, authParameters.Scopes), nil +} + +func (c Client) FromDeviceCodeResult(ctx context.Context, authParameters authority.AuthParams, deviceCodeResult DeviceCodeResult) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.DeviceCode) + qv.Set(deviceCode, deviceCodeResult.DeviceCode) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) FromSamlGrant(ctx context.Context, authParameters authority.AuthParams, samlGrant wstrust.SamlTokenInfo) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(username, authParameters.Username) + qv.Set(password, authParameters.Password) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + qv.Set("assertion", base64.StdEncoding.WithPadding(base64.StdPadding).EncodeToString([]byte(samlGrant.Assertion))) + addScopeQueryParam(qv, authParameters) + + switch samlGrant.AssertionType { + case grant.SAMLV1: + qv.Set(grantType, grant.SAMLV1) + case grant.SAMLV2: + qv.Set(grantType, grant.SAMLV2) + default: + return TokenResponse{}, fmt.Errorf("GetAccessTokenFromSamlGrant returned unknown SAML assertion type: %q", samlGrant.AssertionType) + } + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) doTokenResp(ctx context.Context, authParams authority.AuthParams, qv url.Values) (TokenResponse, error) { + resp := TokenResponse{} + if authParams.AuthnScheme != nil { + trParams := authParams.AuthnScheme.TokenRequestParams() + for k, v := range trParams { + qv.Set(k, v) + } + } + err := c.Comm.URLFormCall(ctx, authParams.Endpoints.TokenEndpoint, qv, &resp) + if err != nil { + return resp, err + } + resp.ComputeScope(authParams) + if c.testing { + return resp, nil + } + return resp, resp.Validate() +} + +// prepURLVals returns an url.Values that sets various key/values if we are doing secrets +// or JWT assertions. +func prepURLVals(ctx context.Context, cc *Credential, authParams authority.AuthParams) (url.Values, error) { + params := url.Values{} + if cc.Secret != "" { + params.Set("client_secret", cc.Secret) + return params, nil + } + + jwt, err := cc.JWT(ctx, authParams) + if err != nil { + return nil, err + } + params.Set("client_assertion", jwt) + params.Set("client_assertion_type", grant.ClientAssertion) + return params, nil +} + +// openid required to get an id token +// offline_access required to get a refresh token +// profile required to get the client_info field back +var detectDefaultScopes = map[string]bool{ + "openid": true, + "offline_access": true, + "profile": true, +} + +var defaultScopes = []string{"openid", "offline_access", "profile"} + +func AppendDefaultScopes(authParameters authority.AuthParams) []string { + scopes := make([]string, 0, len(authParameters.Scopes)+len(defaultScopes)) + for _, scope := range authParameters.Scopes { + s := strings.TrimSpace(scope) + if s == "" { + continue + } + if detectDefaultScopes[scope] { + continue + } + scopes = append(scopes, scope) + } + scopes = append(scopes, defaultScopes...) + return scopes +} + +// addClaims adds client capabilities and claims from AuthParams to the given url.Values +func addClaims(v url.Values, ap authority.AuthParams) error { + claims, err := ap.MergeCapabilitiesAndClaims() + if err == nil && claims != "" { + v.Set("claims", claims) + } + return err +} + +func addScopeQueryParam(queryParams url.Values, authParameters authority.AuthParams) { + scopes := AppendDefaultScopes(authParameters) + queryParams.Set("scope", strings.Join(scopes, " ")) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/apptype_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/apptype_string.go new file mode 100644 index 000000000..3bec4a67c --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/apptype_string.go @@ -0,0 +1,25 @@ +// Code generated by "stringer -type=AppType"; DO NOT EDIT. + +package accesstokens + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ATUnknown-0] + _ = x[ATPublic-1] + _ = x[ATConfidential-2] +} + +const _AppType_name = "ATUnknownATPublicATConfidential" + +var _AppType_index = [...]uint8{0, 9, 17, 31} + +func (i AppType) String() string { + if i < 0 || i >= AppType(len(_AppType_index)-1) { + return "AppType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _AppType_name[_AppType_index[i]:_AppType_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go new file mode 100644 index 000000000..3107b45c1 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go @@ -0,0 +1,339 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package accesstokens + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "reflect" + "strings" + "time" + + internalTime "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// IDToken consists of all the information used to validate a user. +// https://docs.microsoft.com/azure/active-directory/develop/id-tokens . +type IDToken struct { + PreferredUsername string `json:"preferred_username,omitempty"` + GivenName string `json:"given_name,omitempty"` + FamilyName string `json:"family_name,omitempty"` + MiddleName string `json:"middle_name,omitempty"` + Name string `json:"name,omitempty"` + Oid string `json:"oid,omitempty"` + TenantID string `json:"tid,omitempty"` + Subject string `json:"sub,omitempty"` + UPN string `json:"upn,omitempty"` + Email string `json:"email,omitempty"` + AlternativeID string `json:"alternative_id,omitempty"` + Issuer string `json:"iss,omitempty"` + Audience string `json:"aud,omitempty"` + ExpirationTime int64 `json:"exp,omitempty"` + IssuedAt int64 `json:"iat,omitempty"` + NotBefore int64 `json:"nbf,omitempty"` + RawToken string + + AdditionalFields map[string]interface{} +} + +var null = []byte("null") + +// UnmarshalJSON implements json.Unmarshaler. +func (i *IDToken) UnmarshalJSON(b []byte) error { + if bytes.Equal(null, b) { + return nil + } + + // Because we have a custom unmarshaler, you + // cannot directly call json.Unmarshal here. If you do, it will call this function + // recursively until reach our recursion limit. We have to create a new type + // that doesn't have this method in order to use json.Unmarshal. + type idToken2 IDToken + + jwt := strings.Trim(string(b), `"`) + jwtArr := strings.Split(jwt, ".") + if len(jwtArr) < 2 { + return errors.New("IDToken returned from server is invalid") + } + + jwtPart := jwtArr[1] + jwtDecoded, err := decodeJWT(jwtPart) + if err != nil { + return fmt.Errorf("unable to unmarshal IDToken, problem decoding JWT: %w", err) + } + + token := idToken2{} + err = json.Unmarshal(jwtDecoded, &token) + if err != nil { + return fmt.Errorf("unable to unmarshal IDToken: %w", err) + } + token.RawToken = jwt + + *i = IDToken(token) + return nil +} + +// IsZero indicates if the IDToken is the zero value. +func (i IDToken) IsZero() bool { + v := reflect.ValueOf(i) + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if !field.IsZero() { + switch field.Kind() { + case reflect.Map, reflect.Slice: + if field.Len() == 0 { + continue + } + } + return false + } + } + return true +} + +// LocalAccountID extracts an account's local account ID from an ID token. +func (i IDToken) LocalAccountID() string { + if i.Oid != "" { + return i.Oid + } + return i.Subject +} + +// jwtDecoder is provided to allow tests to provide their own. +var jwtDecoder = decodeJWT + +// ClientInfo is used to create a Home Account ID for an account. +type ClientInfo struct { + UID string `json:"uid"` + UTID string `json:"utid"` + + AdditionalFields map[string]interface{} +} + +// UnmarshalJSON implements json.Unmarshaler.s +func (c *ClientInfo) UnmarshalJSON(b []byte) error { + s := strings.Trim(string(b), `"`) + // Client info may be empty in some flows, e.g. certificate exchange. + if len(s) == 0 { + return nil + } + + // Because we have a custom unmarshaler, you + // cannot directly call json.Unmarshal here. If you do, it will call this function + // recursively until reach our recursion limit. We have to create a new type + // that doesn't have this method in order to use json.Unmarshal. + type clientInfo2 ClientInfo + + raw, err := jwtDecoder(s) + if err != nil { + return fmt.Errorf("TokenResponse client_info field had JWT decode error: %w", err) + } + + var c2 clientInfo2 + + err = json.Unmarshal(raw, &c2) + if err != nil { + return fmt.Errorf("was unable to unmarshal decoded JWT in TokenRespone to ClientInfo: %w", err) + } + + *c = ClientInfo(c2) + return nil +} + +// Scopes represents scopes in a TokenResponse. +type Scopes struct { + Slice []string +} + +// UnmarshalJSON implements json.Unmarshal. +func (s *Scopes) UnmarshalJSON(b []byte) error { + str := strings.Trim(string(b), `"`) + if len(str) == 0 { + return nil + } + sl := strings.Split(str, " ") + s.Slice = sl + return nil +} + +// TokenResponse is the information that is returned from a token endpoint during a token acquisition flow. +type TokenResponse struct { + authority.OAuthResponseBase + + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + TokenType string `json:"token_type"` + + FamilyID string `json:"foci"` + IDToken IDToken `json:"id_token"` + ClientInfo ClientInfo `json:"client_info"` + ExpiresOn internalTime.DurationTime `json:"expires_in"` + ExtExpiresOn internalTime.DurationTime `json:"ext_expires_in"` + GrantedScopes Scopes `json:"scope"` + DeclinedScopes []string // This is derived + + AdditionalFields map[string]interface{} + + scopesComputed bool +} + +// ComputeScope computes the final scopes based on what was granted by the server and +// what our AuthParams were from the authority server. Per OAuth spec, if no scopes are returned, the response should be treated as if all scopes were granted +// This behavior can be observed in client assertion flows, but can happen at any time, this check ensures we treat +// those special responses properly Link to spec: https://tools.ietf.org/html/rfc6749#section-3.3 +func (tr *TokenResponse) ComputeScope(authParams authority.AuthParams) { + if len(tr.GrantedScopes.Slice) == 0 { + tr.GrantedScopes = Scopes{Slice: authParams.Scopes} + } else { + tr.DeclinedScopes = findDeclinedScopes(authParams.Scopes, tr.GrantedScopes.Slice) + } + tr.scopesComputed = true +} + +// HomeAccountID uniquely identifies the authenticated account, if any. It's "" when the token is an app token. +func (tr *TokenResponse) HomeAccountID() string { + id := tr.IDToken.Subject + if uid := tr.ClientInfo.UID; uid != "" { + utid := tr.ClientInfo.UTID + if utid == "" { + utid = uid + } + id = fmt.Sprintf("%s.%s", uid, utid) + } + return id +} + +// Validate validates the TokenResponse has basic valid values. It must be called +// after ComputeScopes() is called. +func (tr *TokenResponse) Validate() error { + if tr.Error != "" { + return fmt.Errorf("%s: %s", tr.Error, tr.ErrorDescription) + } + + if tr.AccessToken == "" { + return errors.New("response is missing access_token") + } + + if !tr.scopesComputed { + return fmt.Errorf("TokenResponse hasn't had ScopesComputed() called") + } + return nil +} + +func (tr *TokenResponse) CacheKey(authParams authority.AuthParams) string { + if authParams.AuthorizationType == authority.ATOnBehalfOf { + return authParams.AssertionHash() + } + if authParams.AuthorizationType == authority.ATClientCredentials { + return authParams.AppKey() + } + if authParams.IsConfidentialClient || authParams.AuthorizationType == authority.ATRefreshToken { + return tr.HomeAccountID() + } + return "" +} + +func findDeclinedScopes(requestedScopes []string, grantedScopes []string) []string { + declined := []string{} + grantedMap := map[string]bool{} + for _, s := range grantedScopes { + grantedMap[strings.ToLower(s)] = true + } + // Comparing the requested scopes with the granted scopes to see if there are any scopes that have been declined. + for _, r := range requestedScopes { + if !grantedMap[strings.ToLower(r)] { + declined = append(declined, r) + } + } + return declined +} + +// decodeJWT decodes a JWT and converts it to a byte array representing a JSON object +// JWT has headers and payload base64url encoded without padding +// https://tools.ietf.org/html/rfc7519#section-3 and +// https://tools.ietf.org/html/rfc7515#section-2 +func decodeJWT(data string) ([]byte, error) { + // https://tools.ietf.org/html/rfc7515#appendix-C + return base64.RawURLEncoding.DecodeString(data) +} + +// RefreshToken is the JSON representation of a MSAL refresh token for encoding to storage. +type RefreshToken struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + CredentialType string `json:"credential_type,omitempty"` + ClientID string `json:"client_id,omitempty"` + FamilyID string `json:"family_id,omitempty"` + Secret string `json:"secret,omitempty"` + Realm string `json:"realm,omitempty"` + Target string `json:"target,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewRefreshToken is the constructor for RefreshToken. +func NewRefreshToken(homeID, env, clientID, refreshToken, familyID string) RefreshToken { + return RefreshToken{ + HomeAccountID: homeID, + Environment: env, + CredentialType: "RefreshToken", + ClientID: clientID, + FamilyID: familyID, + Secret: refreshToken, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (rt RefreshToken) Key() string { + var fourth = rt.FamilyID + if fourth == "" { + fourth = rt.ClientID + } + + key := strings.Join( + []string{rt.HomeAccountID, rt.Environment, rt.CredentialType, fourth}, + shared.CacheKeySeparator, + ) + return strings.ToLower(key) +} + +func (rt RefreshToken) GetSecret() string { + return rt.Secret +} + +// DeviceCodeResult stores the response from the STS device code endpoint. +type DeviceCodeResult struct { + // UserCode is the code the user needs to provide when authentication at the verification URI. + UserCode string + // DeviceCode is the code used in the access token request. + DeviceCode string + // VerificationURL is the the URL where user can authenticate. + VerificationURL string + // ExpiresOn is the expiration time of device code in seconds. + ExpiresOn time.Time + // Interval is the interval at which the STS should be polled at. + Interval int + // Message is the message which should be displayed to the user. + Message string + // ClientID is the UUID issued by the authorization server for your application. + ClientID string + // Scopes is the OpenID scopes used to request access a protected API. + Scopes []string +} + +// NewDeviceCodeResult creates a DeviceCodeResult instance. +func NewDeviceCodeResult(userCode, deviceCode, verificationURL string, expiresOn time.Time, interval int, message, clientID string, scopes []string) DeviceCodeResult { + return DeviceCodeResult{userCode, deviceCode, verificationURL, expiresOn, interval, message, clientID, scopes} +} + +func (dcr DeviceCodeResult) String() string { + return fmt.Sprintf("UserCode: (%v)\nDeviceCode: (%v)\nURL: (%v)\nMessage: (%v)\n", dcr.UserCode, dcr.DeviceCode, dcr.VerificationURL, dcr.Message) + +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go new file mode 100644 index 000000000..9d60734f8 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package authority + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path" + "strings" + "time" + + "github.com/google/uuid" +) + +const ( + authorizationEndpoint = "https://%v/%v/oauth2/v2.0/authorize" + instanceDiscoveryEndpoint = "https://%v/common/discovery/instance" + tenantDiscoveryEndpointWithRegion = "https://%s.%s/%s/v2.0/.well-known/openid-configuration" + regionName = "REGION_NAME" + defaultAPIVersion = "2021-10-01" + imdsEndpoint = "http://169.254.169.254/metadata/instance/compute/location?format=text&api-version=" + defaultAPIVersion + autoDetectRegion = "TryAutoDetect" + AccessTokenTypeBearer = "Bearer" +) + +// These are various hosts that host AAD Instance discovery endpoints. +const ( + defaultHost = "login.microsoftonline.com" + loginMicrosoft = "login.microsoft.com" + loginWindows = "login.windows.net" + loginSTSWindows = "sts.windows.net" + loginMicrosoftOnline = defaultHost +) + +// jsonCaller is an interface that allows us to mock the JSONCall method. +type jsonCaller interface { + JSONCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, body, resp interface{}) error +} + +var aadTrustedHostList = map[string]bool{ + "login.windows.net": true, // Microsoft Azure Worldwide - Used in validation scenarios where host is not this list + "login.chinacloudapi.cn": true, // Microsoft Azure China + "login.microsoftonline.de": true, // Microsoft Azure Blackforest + "login-us.microsoftonline.com": true, // Microsoft Azure US Government - Legacy + "login.microsoftonline.us": true, // Microsoft Azure US Government + "login.microsoftonline.com": true, // Microsoft Azure Worldwide + "login.cloudgovapi.us": true, // Microsoft Azure US Government +} + +// TrustedHost checks if an AAD host is trusted/valid. +func TrustedHost(host string) bool { + if _, ok := aadTrustedHostList[host]; ok { + return true + } + return false +} + +// OAuthResponseBase is the base JSON return message for an OAuth call. +// This is embedded in other calls to get the base fields from every response. +type OAuthResponseBase struct { + Error string `json:"error"` + SubError string `json:"suberror"` + ErrorDescription string `json:"error_description"` + ErrorCodes []int `json:"error_codes"` + CorrelationID string `json:"correlation_id"` + Claims string `json:"claims"` +} + +// TenantDiscoveryResponse is the tenant endpoints from the OpenID configuration endpoint. +type TenantDiscoveryResponse struct { + OAuthResponseBase + + AuthorizationEndpoint string `json:"authorization_endpoint"` + TokenEndpoint string `json:"token_endpoint"` + Issuer string `json:"issuer"` + + AdditionalFields map[string]interface{} +} + +// Validate validates that the response had the correct values required. +func (r *TenantDiscoveryResponse) Validate() error { + switch "" { + case r.AuthorizationEndpoint: + return errors.New("TenantDiscoveryResponse: authorize endpoint was not found in the openid configuration") + case r.TokenEndpoint: + return errors.New("TenantDiscoveryResponse: token endpoint was not found in the openid configuration") + case r.Issuer: + return errors.New("TenantDiscoveryResponse: issuer was not found in the openid configuration") + } + return nil +} + +type InstanceDiscoveryMetadata struct { + PreferredNetwork string `json:"preferred_network"` + PreferredCache string `json:"preferred_cache"` + Aliases []string `json:"aliases"` + + AdditionalFields map[string]interface{} +} + +type InstanceDiscoveryResponse struct { + TenantDiscoveryEndpoint string `json:"tenant_discovery_endpoint"` + Metadata []InstanceDiscoveryMetadata `json:"metadata"` + + AdditionalFields map[string]interface{} +} + +//go:generate stringer -type=AuthorizeType + +// AuthorizeType represents the type of token flow. +type AuthorizeType int + +// These are all the types of token flows. +const ( + ATUnknown AuthorizeType = iota + ATUsernamePassword + ATWindowsIntegrated + ATAuthCode + ATInteractive + ATClientCredentials + ATDeviceCode + ATRefreshToken + AccountByID + ATOnBehalfOf +) + +// These are all authority types +const ( + AAD = "MSSTS" + ADFS = "ADFS" +) + +// AuthenticationScheme is an extensibility mechanism designed to be used only by Azure Arc for proof of possession access tokens. +type AuthenticationScheme interface { + // Extra parameters that are added to the request to the /token endpoint. + TokenRequestParams() map[string]string + // Key ID of the public / private key pair used by the encryption algorithm, if any. + // Tokens obtained by authentication schemes that use this are bound to the KeyId, i.e. + // if a different kid is presented, the access token cannot be used. + KeyID() string + // Creates the access token that goes into an Authorization HTTP header. + FormatAccessToken(accessToken string) (string, error) + //Expected to match the token_type parameter returned by ESTS. Used to disambiguate + // between ATs of different types (e.g. Bearer and PoP) when loading from cache etc. + AccessTokenType() string +} + +// default authn scheme realizing AuthenticationScheme for "Bearer" tokens +type BearerAuthenticationScheme struct{} + +var bearerAuthnScheme BearerAuthenticationScheme + +func (ba *BearerAuthenticationScheme) TokenRequestParams() map[string]string { + return nil +} +func (ba *BearerAuthenticationScheme) KeyID() string { + return "" +} +func (ba *BearerAuthenticationScheme) FormatAccessToken(accessToken string) (string, error) { + return accessToken, nil +} +func (ba *BearerAuthenticationScheme) AccessTokenType() string { + return AccessTokenTypeBearer +} + +// AuthParams represents the parameters used for authorization for token acquisition. +type AuthParams struct { + AuthorityInfo Info + CorrelationID string + Endpoints Endpoints + ClientID string + // Redirecturi is used for auth flows that specify a redirect URI (e.g. local server for interactive auth flow). + Redirecturi string + HomeAccountID string + // Username is the user-name portion for username/password auth flow. + Username string + // Password is the password portion for username/password auth flow. + Password string + // Scopes is the list of scopes the user consents to. + Scopes []string + // AuthorizationType specifies the auth flow being used. + AuthorizationType AuthorizeType + // State is a random value used to prevent cross-site request forgery attacks. + State string + // CodeChallenge is derived from a code verifier and is sent in the auth request. + CodeChallenge string + // CodeChallengeMethod describes the method used to create the CodeChallenge. + CodeChallengeMethod string + // Prompt specifies the user prompt type during interactive auth. + Prompt string + // IsConfidentialClient specifies if it is a confidential client. + IsConfidentialClient bool + // SendX5C specifies if x5c claim(public key of the certificate) should be sent to STS. + SendX5C bool + // UserAssertion is the access token used to acquire token on behalf of user + UserAssertion string + // Capabilities the client will include with each token request, for example "CP1". + // Call [NewClientCapabilities] to construct a value for this field. + Capabilities ClientCapabilities + // Claims required for an access token to satisfy a conditional access policy + Claims string + // KnownAuthorityHosts don't require metadata discovery because they're known to the user + KnownAuthorityHosts []string + // LoginHint is a username with which to pre-populate account selection during interactive auth + LoginHint string + // DomainHint is a directive that can be used to accelerate the user to their federated IdP sign-in page + DomainHint string + // AuthnScheme is an optional scheme for formatting access tokens + AuthnScheme AuthenticationScheme +} + +// NewAuthParams creates an authorization parameters object. +func NewAuthParams(clientID string, authorityInfo Info) AuthParams { + return AuthParams{ + ClientID: clientID, + AuthorityInfo: authorityInfo, + CorrelationID: uuid.New().String(), + AuthnScheme: &bearerAuthnScheme, + } +} + +// WithTenant returns a copy of the AuthParams having the specified tenant ID. If the given +// ID is empty, the copy is identical to the original. This function returns an error in +// several cases: +// - ID isn't specific (for example, it's "common") +// - ID is non-empty and the authority doesn't support tenants (for example, it's an ADFS authority) +// - the client is configured to authenticate only Microsoft accounts via the "consumers" endpoint +// - the resulting authority URL is invalid +func (p AuthParams) WithTenant(ID string) (AuthParams, error) { + switch ID { + case "", p.AuthorityInfo.Tenant: + // keep the default tenant because the caller didn't override it + return p, nil + case "common", "consumers", "organizations": + if p.AuthorityInfo.AuthorityType == AAD { + return p, fmt.Errorf(`tenant ID must be a specific tenant, not "%s"`, ID) + } + // else we'll return a better error below + } + if p.AuthorityInfo.AuthorityType != AAD { + return p, errors.New("the authority doesn't support tenants") + } + if p.AuthorityInfo.Tenant == "consumers" { + return p, errors.New(`client is configured to authenticate only personal Microsoft accounts, via the "consumers" endpoint`) + } + authority := "https://" + path.Join(p.AuthorityInfo.Host, ID) + info, err := NewInfoFromAuthorityURI(authority, p.AuthorityInfo.ValidateAuthority, p.AuthorityInfo.InstanceDiscoveryDisabled) + if err == nil { + info.Region = p.AuthorityInfo.Region + p.AuthorityInfo = info + } + return p, err +} + +// MergeCapabilitiesAndClaims combines client capabilities and challenge claims into a value suitable for an authentication request's "claims" parameter. +func (p AuthParams) MergeCapabilitiesAndClaims() (string, error) { + claims := p.Claims + if len(p.Capabilities.asMap) > 0 { + if claims == "" { + // without claims the result is simply the capabilities + return p.Capabilities.asJSON, nil + } + // Otherwise, merge claims and capabilties into a single JSON object. + // We handle the claims challenge as a map because we don't know its structure. + var challenge map[string]any + if err := json.Unmarshal([]byte(claims), &challenge); err != nil { + return "", fmt.Errorf(`claims must be JSON. Are they base64 encoded? json.Unmarshal returned "%v"`, err) + } + if err := merge(p.Capabilities.asMap, challenge); err != nil { + return "", err + } + b, err := json.Marshal(challenge) + if err != nil { + return "", err + } + claims = string(b) + } + return claims, nil +} + +// merges a into b without overwriting b's values. Returns an error when a and b share a key for which either has a non-object value. +func merge(a, b map[string]any) error { + for k, av := range a { + if bv, ok := b[k]; !ok { + // b doesn't contain this key => simply set it to a's value + b[k] = av + } else { + // b does contain this key => recursively merge a[k] into b[k], provided both are maps. If a[k] or b[k] isn't + // a map, return an error because merging would overwrite some value in b. Errors shouldn't occur in practice + // because the challenge will be from AAD, which knows the capabilities format. + if A, ok := av.(map[string]any); ok { + if B, ok := bv.(map[string]any); ok { + return merge(A, B) + } else { + // b[k] isn't a map + return errors.New("challenge claims conflict with client capabilities") + } + } else { + // a[k] isn't a map + return errors.New("challenge claims conflict with client capabilities") + } + } + } + return nil +} + +// ClientCapabilities stores capabilities in the formats used by AuthParams.MergeCapabilitiesAndClaims. +// [NewClientCapabilities] precomputes these representations because capabilities are static for the +// lifetime of a client and are included with every authentication request i.e., these computations +// always have the same result and would otherwise have to be repeated for every request. +type ClientCapabilities struct { + // asJSON is for the common case: adding the capabilities to an auth request with no challenge claims + asJSON string + // asMap is for merging the capabilities with challenge claims + asMap map[string]any +} + +func NewClientCapabilities(capabilities []string) (ClientCapabilities, error) { + c := ClientCapabilities{} + var err error + if len(capabilities) > 0 { + cpbs := make([]string, len(capabilities)) + for i := 0; i < len(cpbs); i++ { + cpbs[i] = fmt.Sprintf(`"%s"`, capabilities[i]) + } + c.asJSON = fmt.Sprintf(`{"access_token":{"xms_cc":{"values":[%s]}}}`, strings.Join(cpbs, ",")) + // note our JSON is valid but we can't stop users breaking it with garbage like "}" + err = json.Unmarshal([]byte(c.asJSON), &c.asMap) + } + return c, err +} + +// Info consists of information about the authority. +type Info struct { + Host string + CanonicalAuthorityURI string + AuthorityType string + UserRealmURIPrefix string + ValidateAuthority bool + Tenant string + Region string + InstanceDiscoveryDisabled bool +} + +func firstPathSegment(u *url.URL) (string, error) { + pathParts := strings.Split(u.EscapedPath(), "/") + if len(pathParts) >= 2 { + return pathParts[1], nil + } + + return "", errors.New(`authority must be an https URL such as "https://login.microsoftonline.com/"`) +} + +// NewInfoFromAuthorityURI creates an AuthorityInfo instance from the authority URL provided. +func NewInfoFromAuthorityURI(authority string, validateAuthority bool, instanceDiscoveryDisabled bool) (Info, error) { + u, err := url.Parse(strings.ToLower(authority)) + if err != nil || u.Scheme != "https" { + return Info{}, errors.New(`authority must be an https URL such as "https://login.microsoftonline.com/"`) + } + + tenant, err := firstPathSegment(u) + if err != nil { + return Info{}, err + } + authorityType := AAD + if tenant == "adfs" { + authorityType = ADFS + } + + // u.Host includes the port, if any, which is required for private cloud deployments + return Info{ + Host: u.Host, + CanonicalAuthorityURI: fmt.Sprintf("https://%v/%v/", u.Host, tenant), + AuthorityType: authorityType, + UserRealmURIPrefix: fmt.Sprintf("https://%v/common/userrealm/", u.Hostname()), + ValidateAuthority: validateAuthority, + Tenant: tenant, + InstanceDiscoveryDisabled: instanceDiscoveryDisabled, + }, nil +} + +// Endpoints consists of the endpoints from the tenant discovery response. +type Endpoints struct { + AuthorizationEndpoint string + TokenEndpoint string + selfSignedJwtAudience string + authorityHost string +} + +// NewEndpoints creates an Endpoints object. +func NewEndpoints(authorizationEndpoint string, tokenEndpoint string, selfSignedJwtAudience string, authorityHost string) Endpoints { + return Endpoints{authorizationEndpoint, tokenEndpoint, selfSignedJwtAudience, authorityHost} +} + +// UserRealmAccountType refers to the type of user realm. +type UserRealmAccountType string + +// These are the different types of user realms. +const ( + Unknown UserRealmAccountType = "" + Federated UserRealmAccountType = "Federated" + Managed UserRealmAccountType = "Managed" +) + +// UserRealm is used for the username password request to determine user type +type UserRealm struct { + AccountType UserRealmAccountType `json:"account_type"` + DomainName string `json:"domain_name"` + CloudInstanceName string `json:"cloud_instance_name"` + CloudAudienceURN string `json:"cloud_audience_urn"` + + // required if accountType is Federated + FederationProtocol string `json:"federation_protocol"` + FederationMetadataURL string `json:"federation_metadata_url"` + + AdditionalFields map[string]interface{} +} + +func (u UserRealm) validate() error { + switch "" { + case string(u.AccountType): + return errors.New("the account type (Federated or Managed) is missing") + case u.DomainName: + return errors.New("domain name of user realm is missing") + case u.CloudInstanceName: + return errors.New("cloud instance name of user realm is missing") + case u.CloudAudienceURN: + return errors.New("cloud Instance URN is missing") + } + + if u.AccountType == Federated { + switch "" { + case u.FederationProtocol: + return errors.New("federation protocol of user realm is missing") + case u.FederationMetadataURL: + return errors.New("federation metadata URL of user realm is missing") + } + } + return nil +} + +// Client represents the REST calls to authority backends. +type Client struct { + // Comm provides the HTTP transport client. + Comm jsonCaller // *comm.Client +} + +func (c Client) UserRealm(ctx context.Context, authParams AuthParams) (UserRealm, error) { + endpoint := fmt.Sprintf("https://%s/common/UserRealm/%s", authParams.Endpoints.authorityHost, url.PathEscape(authParams.Username)) + qv := url.Values{ + "api-version": []string{"1.0"}, + } + + resp := UserRealm{} + err := c.Comm.JSONCall( + ctx, + endpoint, + http.Header{"client-request-id": []string{authParams.CorrelationID}}, + qv, + nil, + &resp, + ) + if err != nil { + return resp, err + } + + return resp, resp.validate() +} + +func (c Client) GetTenantDiscoveryResponse(ctx context.Context, openIDConfigurationEndpoint string) (TenantDiscoveryResponse, error) { + resp := TenantDiscoveryResponse{} + err := c.Comm.JSONCall( + ctx, + openIDConfigurationEndpoint, + http.Header{}, + nil, + nil, + &resp, + ) + + return resp, err +} + +// AADInstanceDiscovery attempts to discover a tenant endpoint (used in OIDC auth with an authorization endpoint). +// This is done by AAD which allows for aliasing of tenants (windows.sts.net is the same as login.windows.com). +func (c Client) AADInstanceDiscovery(ctx context.Context, authorityInfo Info) (InstanceDiscoveryResponse, error) { + region := "" + var err error + resp := InstanceDiscoveryResponse{} + if authorityInfo.Region != "" && authorityInfo.Region != autoDetectRegion { + region = authorityInfo.Region + } else if authorityInfo.Region == autoDetectRegion { + region = detectRegion(ctx) + } + if region != "" { + environment := authorityInfo.Host + switch environment { + case loginMicrosoft, loginWindows, loginSTSWindows, defaultHost: + environment = loginMicrosoft + } + + resp.TenantDiscoveryEndpoint = fmt.Sprintf(tenantDiscoveryEndpointWithRegion, region, environment, authorityInfo.Tenant) + metadata := InstanceDiscoveryMetadata{ + PreferredNetwork: fmt.Sprintf("%v.%v", region, authorityInfo.Host), + PreferredCache: authorityInfo.Host, + Aliases: []string{fmt.Sprintf("%v.%v", region, authorityInfo.Host), authorityInfo.Host}, + } + resp.Metadata = []InstanceDiscoveryMetadata{metadata} + } else { + qv := url.Values{} + qv.Set("api-version", "1.1") + qv.Set("authorization_endpoint", fmt.Sprintf(authorizationEndpoint, authorityInfo.Host, authorityInfo.Tenant)) + + discoveryHost := defaultHost + if TrustedHost(authorityInfo.Host) { + discoveryHost = authorityInfo.Host + } + + endpoint := fmt.Sprintf(instanceDiscoveryEndpoint, discoveryHost) + err = c.Comm.JSONCall(ctx, endpoint, http.Header{}, qv, nil, &resp) + } + return resp, err +} + +func detectRegion(ctx context.Context) string { + region := os.Getenv(regionName) + if region != "" { + region = strings.ReplaceAll(region, " ", "") + return strings.ToLower(region) + } + // HTTP call to IMDS endpoint to get region + // Refer : https://identitydivision.visualstudio.com/DevEx/_git/AuthLibrariesApiReview?path=%2FPinAuthToRegion%2FAAD%20SDK%20Proposal%20to%20Pin%20Auth%20to%20region.md&_a=preview&version=GBdev + // Set a 2 second timeout for this http client which only does calls to IMDS endpoint + client := http.Client{ + Timeout: time.Duration(2 * time.Second), + } + req, _ := http.NewRequest("GET", imdsEndpoint, nil) + req.Header.Set("Metadata", "true") + resp, err := client.Do(req) + // If the request times out or there is an error, it is retried once + if err != nil || resp.StatusCode != 200 { + resp, err = client.Do(req) + if err != nil || resp.StatusCode != 200 { + return "" + } + } + defer resp.Body.Close() + response, err := io.ReadAll(resp.Body) + if err != nil { + return "" + } + return string(response) +} + +func (a *AuthParams) CacheKey(isAppCache bool) string { + if a.AuthorizationType == ATOnBehalfOf { + return a.AssertionHash() + } + if a.AuthorizationType == ATClientCredentials || isAppCache { + return a.AppKey() + } + if a.AuthorizationType == ATRefreshToken || a.AuthorizationType == AccountByID { + return a.HomeAccountID + } + return "" +} +func (a *AuthParams) AssertionHash() string { + hasher := sha256.New() + // Per documentation this never returns an error : https://pkg.go.dev/hash#pkg-types + _, _ = hasher.Write([]byte(a.UserAssertion)) + sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) + return sha +} + +func (a *AuthParams) AppKey() string { + if a.AuthorityInfo.Tenant != "" { + return fmt.Sprintf("%s_%s_AppTokenCache", a.ClientID, a.AuthorityInfo.Tenant) + } + return fmt.Sprintf("%s__AppTokenCache", a.ClientID) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authorizetype_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authorizetype_string.go new file mode 100644 index 000000000..10039773b --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authorizetype_string.go @@ -0,0 +1,30 @@ +// Code generated by "stringer -type=AuthorizeType"; DO NOT EDIT. + +package authority + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ATUnknown-0] + _ = x[ATUsernamePassword-1] + _ = x[ATWindowsIntegrated-2] + _ = x[ATAuthCode-3] + _ = x[ATInteractive-4] + _ = x[ATClientCredentials-5] + _ = x[ATDeviceCode-6] + _ = x[ATRefreshToken-7] +} + +const _AuthorizeType_name = "ATUnknownATUsernamePasswordATWindowsIntegratedATAuthCodeATInteractiveATClientCredentialsATDeviceCodeATRefreshToken" + +var _AuthorizeType_index = [...]uint8{0, 9, 27, 46, 56, 69, 88, 100, 114} + +func (i AuthorizeType) String() string { + if i < 0 || i >= AuthorizeType(len(_AuthorizeType_index)-1) { + return "AuthorizeType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _AuthorizeType_name[_AuthorizeType_index[i]:_AuthorizeType_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go new file mode 100644 index 000000000..7d9ec7cd3 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package comm provides helpers for communicating with HTTP backends. +package comm + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/http" + "net/url" + "reflect" + "runtime" + "strings" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" + customJSON "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version" + "github.com/google/uuid" +) + +// HTTPClient represents an HTTP client. +// It's usually an *http.Client from the standard library. +type HTTPClient interface { + // Do sends an HTTP request and returns an HTTP response. + Do(req *http.Request) (*http.Response, error) + + // CloseIdleConnections closes any idle connections in a "keep-alive" state. + CloseIdleConnections() +} + +// Client provides a wrapper to our *http.Client that handles compression and serialization needs. +type Client struct { + client HTTPClient +} + +// New returns a new Client object. +func New(httpClient HTTPClient) *Client { + if httpClient == nil { + panic("http.Client cannot == nil") + } + + return &Client{client: httpClient} +} + +// JSONCall connects to the REST endpoint passing the HTTP query values, headers and JSON conversion +// of body in the HTTP body. It automatically handles compression and decompression with gzip. The response is JSON +// unmarshalled into resp. resp must be a pointer to a struct. If the body struct contains a field called +// "AdditionalFields" we use a custom marshal/unmarshal engine. +func (c *Client) JSONCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, body, resp interface{}) error { + if qv == nil { + qv = url.Values{} + } + + v := reflect.ValueOf(resp) + if err := c.checkResp(v); err != nil { + return err + } + + // Choose a JSON marshal/unmarshal depending on if we have AdditionalFields attribute. + var marshal = json.Marshal + var unmarshal = json.Unmarshal + if _, ok := v.Elem().Type().FieldByName("AdditionalFields"); ok { + marshal = customJSON.Marshal + unmarshal = customJSON.Unmarshal + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + u.RawQuery = qv.Encode() + + addStdHeaders(headers) + + req := &http.Request{Method: http.MethodGet, URL: u, Header: headers} + + if body != nil { + // Note: In case your wondering why we are not gzip encoding.... + // I'm not sure if these various services support gzip on send. + headers.Add("Content-Type", "application/json; charset=utf-8") + data, err := marshal(body) + if err != nil { + return fmt.Errorf("bug: conn.Call(): could not marshal the body object: %w", err) + } + req.Body = io.NopCloser(bytes.NewBuffer(data)) + req.Method = http.MethodPost + } + + data, err := c.do(ctx, req) + if err != nil { + return err + } + + if resp != nil { + if err := unmarshal(data, resp); err != nil { + return fmt.Errorf("json decode error: %w\njson message bytes were: %s", err, string(data)) + } + } + return nil +} + +// XMLCall connects to an endpoint and decodes the XML response into resp. This is used when +// sending application/xml . If sending XML via SOAP, use SOAPCall(). +func (c *Client) XMLCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, resp interface{}) error { + if err := c.checkResp(reflect.ValueOf(resp)); err != nil { + return err + } + + if qv == nil { + qv = url.Values{} + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + u.RawQuery = qv.Encode() + + headers.Set("Content-Type", "application/xml; charset=utf-8") // This was not set in he original Mex(), but... + addStdHeaders(headers) + + return c.xmlCall(ctx, u, headers, "", resp) +} + +// SOAPCall returns the SOAP message given an endpoint, action, body of the request and the response object to marshal into. +func (c *Client) SOAPCall(ctx context.Context, endpoint, action string, headers http.Header, qv url.Values, body string, resp interface{}) error { + if body == "" { + return fmt.Errorf("cannot make a SOAP call with body set to empty string") + } + + if err := c.checkResp(reflect.ValueOf(resp)); err != nil { + return err + } + + if qv == nil { + qv = url.Values{} + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + u.RawQuery = qv.Encode() + + headers.Set("Content-Type", "application/soap+xml; charset=utf-8") + headers.Set("SOAPAction", action) + addStdHeaders(headers) + + return c.xmlCall(ctx, u, headers, body, resp) +} + +// xmlCall sends an XML in body and decodes into resp. This simply does the transport and relies on +// an upper level call to set things such as SOAP parameters and Content-Type, if required. +func (c *Client) xmlCall(ctx context.Context, u *url.URL, headers http.Header, body string, resp interface{}) error { + req := &http.Request{Method: http.MethodGet, URL: u, Header: headers} + + if len(body) > 0 { + req.Method = http.MethodPost + req.Body = io.NopCloser(strings.NewReader(body)) + } + + data, err := c.do(ctx, req) + if err != nil { + return err + } + + return xml.Unmarshal(data, resp) +} + +// URLFormCall is used to make a call where we need to send application/x-www-form-urlencoded data +// to the backend and receive JSON back. qv will be encoded into the request body. +func (c *Client) URLFormCall(ctx context.Context, endpoint string, qv url.Values, resp interface{}) error { + if len(qv) == 0 { + return fmt.Errorf("URLFormCall() requires qv to have non-zero length") + } + + if err := c.checkResp(reflect.ValueOf(resp)); err != nil { + return err + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + + headers := http.Header{} + headers.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") + addStdHeaders(headers) + + enc := qv.Encode() + + req := &http.Request{ + Method: http.MethodPost, + URL: u, + Header: headers, + ContentLength: int64(len(enc)), + Body: io.NopCloser(strings.NewReader(enc)), + GetBody: func() (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader(enc)), nil + }, + } + + data, err := c.do(ctx, req) + if err != nil { + return err + } + + v := reflect.ValueOf(resp) + if err := c.checkResp(v); err != nil { + return err + } + + var unmarshal = json.Unmarshal + if _, ok := v.Elem().Type().FieldByName("AdditionalFields"); ok { + unmarshal = customJSON.Unmarshal + } + if resp != nil { + if err := unmarshal(data, resp); err != nil { + return fmt.Errorf("json decode error: %w\nraw message was: %s", err, string(data)) + } + } + return nil +} + +// do makes the HTTP call to the server and returns the contents of the body. +func (c *Client) do(ctx context.Context, req *http.Request) ([]byte, error) { + if _, ok := ctx.Deadline(); !ok { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, 30*time.Second) + defer cancel() + } + req = req.WithContext(ctx) + + reply, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("server response error:\n %w", err) + } + defer reply.Body.Close() + + data, err := c.readBody(reply) + if err != nil { + return nil, fmt.Errorf("could not read the body of an HTTP Response: %w", err) + } + reply.Body = io.NopCloser(bytes.NewBuffer(data)) + + // NOTE: This doesn't happen immediately after the call so that we can get an error message + // from the server and include it in our error. + switch reply.StatusCode { + case 200, 201: + default: + sd := strings.TrimSpace(string(data)) + if sd != "" { + // We probably have the error in the body. + return nil, errors.CallErr{ + Req: req, + Resp: reply, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d:\n%s", req.URL.String(), req.Method, reply.StatusCode, sd), + } + } + return nil, errors.CallErr{ + Req: req, + Resp: reply, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d", req.URL.String(), req.Method, reply.StatusCode), + } + } + + return data, nil +} + +// checkResp checks a response object o make sure it is a pointer to a struct. +func (c *Client) checkResp(v reflect.Value) error { + if v.Kind() != reflect.Ptr { + return fmt.Errorf("bug: resp argument must a *struct, was %T", v.Interface()) + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return fmt.Errorf("bug: resp argument must be a *struct, was %T", v.Interface()) + } + return nil +} + +// readBody reads the body out of an *http.Response. It supports gzip encoded responses. +func (c *Client) readBody(resp *http.Response) ([]byte, error) { + var reader io.Reader = resp.Body + switch resp.Header.Get("Content-Encoding") { + case "": + // Do nothing + case "gzip": + reader = gzipDecompress(resp.Body) + default: + return nil, fmt.Errorf("bug: comm.Client.JSONCall(): content was send with unsupported content-encoding %s", resp.Header.Get("Content-Encoding")) + } + return io.ReadAll(reader) +} + +var testID string + +// addStdHeaders adds the standard headers we use on all calls. +func addStdHeaders(headers http.Header) http.Header { + headers.Set("Accept-Encoding", "gzip") + // So that I can have a static id for tests. + if testID != "" { + headers.Set("client-request-id", testID) + headers.Set("Return-Client-Request-Id", "false") + } else { + headers.Set("client-request-id", uuid.New().String()) + headers.Set("Return-Client-Request-Id", "false") + } + headers.Set("x-client-sku", "MSAL.Go") + headers.Set("x-client-os", runtime.GOOS) + headers.Set("x-client-cpu", runtime.GOARCH) + headers.Set("x-client-ver", version.Version) + return headers +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/compress.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/compress.go new file mode 100644 index 000000000..4d3dbfcf0 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/compress.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package comm + +import ( + "compress/gzip" + "io" +) + +func gzipDecompress(r io.Reader) io.Reader { + gzipReader, _ := gzip.NewReader(r) + + pipeOut, pipeIn := io.Pipe() + go func() { + // decompression bomb would have to come from Azure services. + // If we want to limit, we should do that in comm.do(). + _, err := io.Copy(pipeIn, gzipReader) //nolint + if err != nil { + // don't need the error. + pipeIn.CloseWithError(err) //nolint + gzipReader.Close() + return + } + if err := gzipReader.Close(); err != nil { + // don't need the error. + pipeIn.CloseWithError(err) //nolint + return + } + pipeIn.Close() + }() + return pipeOut +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant/grant.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant/grant.go new file mode 100644 index 000000000..b628f61ac --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant/grant.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package grant holds types of grants issued by authorization services. +package grant + +const ( + Password = "password" + JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer" + SAMLV1 = "urn:ietf:params:oauth:grant-type:saml1_1-bearer" + SAMLV2 = "urn:ietf:params:oauth:grant-type:saml2-bearer" + DeviceCode = "device_code" + AuthCode = "authorization_code" + RefreshToken = "refresh_token" + ClientCredential = "client_credentials" + ClientAssertion = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" +) diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/ops.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/ops.go new file mode 100644 index 000000000..1f9c543fa --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/ops.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package ops provides operations to various backend services using REST clients. + +The REST type provides several clients that can be used to communicate to backends. +Usage is simple: + + rest := ops.New() + + // Creates an authority client and calls the UserRealm() method. + userRealm, err := rest.Authority().UserRealm(ctx, authParameters) + if err != nil { + // Do something + } +*/ +package ops + +import ( + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust" +) + +// HTTPClient represents an HTTP client. +// It's usually an *http.Client from the standard library. +type HTTPClient = comm.HTTPClient + +// REST provides REST clients for communicating with various backends used by MSAL. +type REST struct { + client *comm.Client +} + +// New is the constructor for REST. +func New(httpClient HTTPClient) *REST { + return &REST{client: comm.New(httpClient)} +} + +// Authority returns a client for querying information about various authorities. +func (r *REST) Authority() authority.Client { + return authority.Client{Comm: r.client} +} + +// AccessTokens returns a client that can be used to get various access tokens for +// authorization purposes. +func (r *REST) AccessTokens() accesstokens.Client { + return accesstokens.Client{Comm: r.client} +} + +// WSTrust provides access to various metadata in a WSTrust service. This data can +// be used to gain tokens based on SAML data using the client provided by AccessTokens(). +func (r *REST) WSTrust() wstrust.Client { + return wstrust.Client{Comm: r.client} +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/endpointtype_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/endpointtype_string.go new file mode 100644 index 000000000..a2bb6278a --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/endpointtype_string.go @@ -0,0 +1,25 @@ +// Code generated by "stringer -type=endpointType"; DO NOT EDIT. + +package defs + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[etUnknown-0] + _ = x[etUsernamePassword-1] + _ = x[etWindowsTransport-2] +} + +const _endpointType_name = "etUnknownetUsernamePasswordetWindowsTransport" + +var _endpointType_index = [...]uint8{0, 9, 27, 45} + +func (i endpointType) String() string { + if i < 0 || i >= endpointType(len(_endpointType_index)-1) { + return "endpointType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _endpointType_name[_endpointType_index[i]:_endpointType_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/mex_document_definitions.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/mex_document_definitions.go new file mode 100644 index 000000000..649727002 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/mex_document_definitions.go @@ -0,0 +1,394 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import "encoding/xml" + +type Definitions struct { + XMLName xml.Name `xml:"definitions"` + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + TargetNamespace string `xml:"targetNamespace,attr"` + WSDL string `xml:"wsdl,attr"` + XSD string `xml:"xsd,attr"` + T string `xml:"t,attr"` + SOAPENC string `xml:"soapenc,attr"` + SOAP string `xml:"soap,attr"` + TNS string `xml:"tns,attr"` + MSC string `xml:"msc,attr"` + WSAM string `xml:"wsam,attr"` + SOAP12 string `xml:"soap12,attr"` + WSA10 string `xml:"wsa10,attr"` + WSA string `xml:"wsa,attr"` + WSAW string `xml:"wsaw,attr"` + WSX string `xml:"wsx,attr"` + WSAP string `xml:"wsap,attr"` + WSU string `xml:"wsu,attr"` + Trust string `xml:"trust,attr"` + WSP string `xml:"wsp,attr"` + Policy []Policy `xml:"Policy"` + Types Types `xml:"types"` + Message []Message `xml:"message"` + PortType []PortType `xml:"portType"` + Binding []Binding `xml:"binding"` + Service Service `xml:"service"` +} + +type Policy struct { + Text string `xml:",chardata"` + ID string `xml:"Id,attr"` + ExactlyOne ExactlyOne `xml:"ExactlyOne"` +} + +type ExactlyOne struct { + Text string `xml:",chardata"` + All All `xml:"All"` +} + +type All struct { + Text string `xml:",chardata"` + NegotiateAuthentication NegotiateAuthentication `xml:"NegotiateAuthentication"` + TransportBinding TransportBinding `xml:"TransportBinding"` + UsingAddressing Text `xml:"UsingAddressing"` + EndorsingSupportingTokens EndorsingSupportingTokens `xml:"EndorsingSupportingTokens"` + WSS11 WSS11 `xml:"Wss11"` + Trust10 Trust10 `xml:"Trust10"` + SignedSupportingTokens SignedSupportingTokens `xml:"SignedSupportingTokens"` + Trust13 WSTrust13 `xml:"Trust13"` + SignedEncryptedSupportingTokens SignedEncryptedSupportingTokens `xml:"SignedEncryptedSupportingTokens"` +} + +type NegotiateAuthentication struct { + Text string `xml:",chardata"` + HTTP string `xml:"http,attr"` + XMLName xml.Name +} + +type TransportBinding struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy TransportBindingPolicy `xml:"Policy"` +} + +type TransportBindingPolicy struct { + Text string `xml:",chardata"` + TransportToken TransportToken `xml:"TransportToken"` + AlgorithmSuite AlgorithmSuite `xml:"AlgorithmSuite"` + Layout Layout `xml:"Layout"` + IncludeTimestamp Text `xml:"IncludeTimestamp"` +} + +type TransportToken struct { + Text string `xml:",chardata"` + Policy TransportTokenPolicy `xml:"Policy"` +} + +type TransportTokenPolicy struct { + Text string `xml:",chardata"` + HTTPSToken HTTPSToken `xml:"HttpsToken"` +} + +type HTTPSToken struct { + Text string `xml:",chardata"` + RequireClientCertificate string `xml:"RequireClientCertificate,attr"` +} + +type AlgorithmSuite struct { + Text string `xml:",chardata"` + Policy AlgorithmSuitePolicy `xml:"Policy"` +} + +type AlgorithmSuitePolicy struct { + Text string `xml:",chardata"` + Basic256 Text `xml:"Basic256"` + Basic128 Text `xml:"Basic128"` +} + +type Layout struct { + Text string `xml:",chardata"` + Policy LayoutPolicy `xml:"Policy"` +} + +type LayoutPolicy struct { + Text string `xml:",chardata"` + Strict Text `xml:"Strict"` +} + +type EndorsingSupportingTokens struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy EndorsingSupportingTokensPolicy `xml:"Policy"` +} + +type EndorsingSupportingTokensPolicy struct { + Text string `xml:",chardata"` + X509Token X509Token `xml:"X509Token"` + RSAToken RSAToken `xml:"RsaToken"` + SignedParts SignedParts `xml:"SignedParts"` + KerberosToken KerberosToken `xml:"KerberosToken"` + IssuedToken IssuedToken `xml:"IssuedToken"` + KeyValueToken KeyValueToken `xml:"KeyValueToken"` +} + +type X509Token struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Policy X509TokenPolicy `xml:"Policy"` +} + +type X509TokenPolicy struct { + Text string `xml:",chardata"` + RequireThumbprintReference Text `xml:"RequireThumbprintReference"` + WSSX509V3Token10 Text `xml:"WssX509V3Token10"` +} + +type RSAToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Optional string `xml:"Optional,attr"` + MSSP string `xml:"mssp,attr"` +} + +type SignedParts struct { + Text string `xml:",chardata"` + Header SignedPartsHeader `xml:"Header"` +} + +type SignedPartsHeader struct { + Text string `xml:",chardata"` + Name string `xml:"Name,attr"` + Namespace string `xml:"Namespace,attr"` +} + +type KerberosToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Policy KerberosTokenPolicy `xml:"Policy"` +} + +type KerberosTokenPolicy struct { + Text string `xml:",chardata"` + WSSGSSKerberosV5ApReqToken11 Text `xml:"WssGssKerberosV5ApReqToken11"` +} + +type IssuedToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + RequestSecurityTokenTemplate RequestSecurityTokenTemplate `xml:"RequestSecurityTokenTemplate"` + Policy IssuedTokenPolicy `xml:"Policy"` +} + +type RequestSecurityTokenTemplate struct { + Text string `xml:",chardata"` + KeyType Text `xml:"KeyType"` + EncryptWith Text `xml:"EncryptWith"` + SignatureAlgorithm Text `xml:"SignatureAlgorithm"` + CanonicalizationAlgorithm Text `xml:"CanonicalizationAlgorithm"` + EncryptionAlgorithm Text `xml:"EncryptionAlgorithm"` + KeySize Text `xml:"KeySize"` + KeyWrapAlgorithm Text `xml:"KeyWrapAlgorithm"` +} + +type IssuedTokenPolicy struct { + Text string `xml:",chardata"` + RequireInternalReference Text `xml:"RequireInternalReference"` +} + +type KeyValueToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Optional string `xml:"Optional,attr"` +} + +type WSS11 struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy Wss11Policy `xml:"Policy"` +} + +type Wss11Policy struct { + Text string `xml:",chardata"` + MustSupportRefThumbprint Text `xml:"MustSupportRefThumbprint"` +} + +type Trust10 struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy Trust10Policy `xml:"Policy"` +} + +type Trust10Policy struct { + Text string `xml:",chardata"` + MustSupportIssuedTokens Text `xml:"MustSupportIssuedTokens"` + RequireClientEntropy Text `xml:"RequireClientEntropy"` + RequireServerEntropy Text `xml:"RequireServerEntropy"` +} + +type SignedSupportingTokens struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy SupportingTokensPolicy `xml:"Policy"` +} + +type SupportingTokensPolicy struct { + Text string `xml:",chardata"` + UsernameToken UsernameToken `xml:"UsernameToken"` +} +type UsernameToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Policy UsernameTokenPolicy `xml:"Policy"` +} + +type UsernameTokenPolicy struct { + Text string `xml:",chardata"` + WSSUsernameToken10 WSSUsernameToken10 `xml:"WssUsernameToken10"` +} + +type WSSUsernameToken10 struct { + Text string `xml:",chardata"` + XMLName xml.Name +} + +type WSTrust13 struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy WSTrust13Policy `xml:"Policy"` +} + +type WSTrust13Policy struct { + Text string `xml:",chardata"` + MustSupportIssuedTokens Text `xml:"MustSupportIssuedTokens"` + RequireClientEntropy Text `xml:"RequireClientEntropy"` + RequireServerEntropy Text `xml:"RequireServerEntropy"` +} + +type SignedEncryptedSupportingTokens struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy SupportingTokensPolicy `xml:"Policy"` +} + +type Types struct { + Text string `xml:",chardata"` + Schema Schema `xml:"schema"` +} + +type Schema struct { + Text string `xml:",chardata"` + TargetNamespace string `xml:"targetNamespace,attr"` + Import []Import `xml:"import"` +} + +type Import struct { + Text string `xml:",chardata"` + SchemaLocation string `xml:"schemaLocation,attr"` + Namespace string `xml:"namespace,attr"` +} + +type Message struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Part Part `xml:"part"` +} + +type Part struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Element string `xml:"element,attr"` +} + +type PortType struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Operation Operation `xml:"operation"` +} + +type Operation struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Input OperationIO `xml:"input"` + Output OperationIO `xml:"output"` +} + +type OperationIO struct { + Text string `xml:",chardata"` + Action string `xml:"Action,attr"` + Message string `xml:"message,attr"` + Body OperationIOBody `xml:"body"` +} + +type OperationIOBody struct { + Text string `xml:",chardata"` + Use string `xml:"use,attr"` +} + +type Binding struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Type string `xml:"type,attr"` + PolicyReference PolicyReference `xml:"PolicyReference"` + Binding DefinitionsBinding `xml:"binding"` + Operation BindingOperation `xml:"operation"` +} + +type PolicyReference struct { + Text string `xml:",chardata"` + URI string `xml:"URI,attr"` +} + +type DefinitionsBinding struct { + Text string `xml:",chardata"` + Transport string `xml:"transport,attr"` +} + +type BindingOperation struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Operation BindingOperationOperation `xml:"operation"` + Input BindingOperationIO `xml:"input"` + Output BindingOperationIO `xml:"output"` +} + +type BindingOperationOperation struct { + Text string `xml:",chardata"` + SoapAction string `xml:"soapAction,attr"` + Style string `xml:"style,attr"` +} + +type BindingOperationIO struct { + Text string `xml:",chardata"` + Body OperationIOBody `xml:"body"` +} + +type Service struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Port []Port `xml:"port"` +} + +type Port struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Binding string `xml:"binding,attr"` + Address Address `xml:"address"` + EndpointReference PortEndpointReference `xml:"EndpointReference"` +} + +type Address struct { + Text string `xml:",chardata"` + Location string `xml:"location,attr"` +} + +type PortEndpointReference struct { + Text string `xml:",chardata"` + Address Text `xml:"Address"` + Identity Identity `xml:"Identity"` +} + +type Identity struct { + Text string `xml:",chardata"` + XMLNS string `xml:"xmlns,attr"` + SPN Text `xml:"Spn"` +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/saml_assertion_definitions.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/saml_assertion_definitions.go new file mode 100644 index 000000000..7d0725565 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/saml_assertion_definitions.go @@ -0,0 +1,230 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import "encoding/xml" + +// TODO(msal): Someone (and it ain't gonna be me) needs to document these attributes or +// at the least put a link to RFC. + +type SAMLDefinitions struct { + XMLName xml.Name `xml:"Envelope"` + Text string `xml:",chardata"` + S string `xml:"s,attr"` + A string `xml:"a,attr"` + U string `xml:"u,attr"` + Header Header `xml:"Header"` + Body Body `xml:"Body"` +} + +type Header struct { + Text string `xml:",chardata"` + Action Action `xml:"Action"` + Security Security `xml:"Security"` +} + +type Action struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"mustUnderstand,attr"` +} + +type Security struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"mustUnderstand,attr"` + O string `xml:"o,attr"` + Timestamp Timestamp `xml:"Timestamp"` +} + +type Timestamp struct { + Text string `xml:",chardata"` + ID string `xml:"Id,attr"` + Created Text `xml:"Created"` + Expires Text `xml:"Expires"` +} + +type Text struct { + Text string `xml:",chardata"` +} + +type Body struct { + Text string `xml:",chardata"` + RequestSecurityTokenResponseCollection RequestSecurityTokenResponseCollection `xml:"RequestSecurityTokenResponseCollection"` +} + +type RequestSecurityTokenResponseCollection struct { + Text string `xml:",chardata"` + Trust string `xml:"trust,attr"` + RequestSecurityTokenResponse []RequestSecurityTokenResponse `xml:"RequestSecurityTokenResponse"` +} + +type RequestSecurityTokenResponse struct { + Text string `xml:",chardata"` + Lifetime Lifetime `xml:"Lifetime"` + AppliesTo AppliesTo `xml:"AppliesTo"` + RequestedSecurityToken RequestedSecurityToken `xml:"RequestedSecurityToken"` + RequestedAttachedReference RequestedAttachedReference `xml:"RequestedAttachedReference"` + RequestedUnattachedReference RequestedUnattachedReference `xml:"RequestedUnattachedReference"` + TokenType Text `xml:"TokenType"` + RequestType Text `xml:"RequestType"` + KeyType Text `xml:"KeyType"` +} + +type Lifetime struct { + Text string `xml:",chardata"` + Created WSUTimestamp `xml:"Created"` + Expires WSUTimestamp `xml:"Expires"` +} + +type WSUTimestamp struct { + Text string `xml:",chardata"` + Wsu string `xml:"wsu,attr"` +} + +type AppliesTo struct { + Text string `xml:",chardata"` + Wsp string `xml:"wsp,attr"` + EndpointReference EndpointReference `xml:"EndpointReference"` +} + +type EndpointReference struct { + Text string `xml:",chardata"` + Wsa string `xml:"wsa,attr"` + Address Text `xml:"Address"` +} + +type RequestedSecurityToken struct { + Text string `xml:",chardata"` + AssertionRawXML string `xml:",innerxml"` + Assertion Assertion `xml:"Assertion"` +} + +type Assertion struct { + XMLName xml.Name // Normally its `xml:"Assertion"`, but I think they want to capture the xmlns + Text string `xml:",chardata"` + MajorVersion string `xml:"MajorVersion,attr"` + MinorVersion string `xml:"MinorVersion,attr"` + AssertionID string `xml:"AssertionID,attr"` + Issuer string `xml:"Issuer,attr"` + IssueInstant string `xml:"IssueInstant,attr"` + Saml string `xml:"saml,attr"` + Conditions Conditions `xml:"Conditions"` + AttributeStatement AttributeStatement `xml:"AttributeStatement"` + AuthenticationStatement AuthenticationStatement `xml:"AuthenticationStatement"` + Signature Signature `xml:"Signature"` +} + +type Conditions struct { + Text string `xml:",chardata"` + NotBefore string `xml:"NotBefore,attr"` + NotOnOrAfter string `xml:"NotOnOrAfter,attr"` + AudienceRestrictionCondition AudienceRestrictionCondition `xml:"AudienceRestrictionCondition"` +} + +type AudienceRestrictionCondition struct { + Text string `xml:",chardata"` + Audience Text `xml:"Audience"` +} + +type AttributeStatement struct { + Text string `xml:",chardata"` + Subject Subject `xml:"Subject"` + Attribute []Attribute `xml:"Attribute"` +} + +type Subject struct { + Text string `xml:",chardata"` + NameIdentifier NameIdentifier `xml:"NameIdentifier"` + SubjectConfirmation SubjectConfirmation `xml:"SubjectConfirmation"` +} + +type NameIdentifier struct { + Text string `xml:",chardata"` + Format string `xml:"Format,attr"` +} + +type SubjectConfirmation struct { + Text string `xml:",chardata"` + ConfirmationMethod Text `xml:"ConfirmationMethod"` +} + +type Attribute struct { + Text string `xml:",chardata"` + AttributeName string `xml:"AttributeName,attr"` + AttributeNamespace string `xml:"AttributeNamespace,attr"` + AttributeValue Text `xml:"AttributeValue"` +} + +type AuthenticationStatement struct { + Text string `xml:",chardata"` + AuthenticationMethod string `xml:"AuthenticationMethod,attr"` + AuthenticationInstant string `xml:"AuthenticationInstant,attr"` + Subject Subject `xml:"Subject"` +} + +type Signature struct { + Text string `xml:",chardata"` + Ds string `xml:"ds,attr"` + SignedInfo SignedInfo `xml:"SignedInfo"` + SignatureValue Text `xml:"SignatureValue"` + KeyInfo KeyInfo `xml:"KeyInfo"` +} + +type SignedInfo struct { + Text string `xml:",chardata"` + CanonicalizationMethod Method `xml:"CanonicalizationMethod"` + SignatureMethod Method `xml:"SignatureMethod"` + Reference Reference `xml:"Reference"` +} + +type Method struct { + Text string `xml:",chardata"` + Algorithm string `xml:"Algorithm,attr"` +} + +type Reference struct { + Text string `xml:",chardata"` + URI string `xml:"URI,attr"` + Transforms Transforms `xml:"Transforms"` + DigestMethod Method `xml:"DigestMethod"` + DigestValue Text `xml:"DigestValue"` +} + +type Transforms struct { + Text string `xml:",chardata"` + Transform []Method `xml:"Transform"` +} + +type KeyInfo struct { + Text string `xml:",chardata"` + Xmlns string `xml:"xmlns,attr"` + X509Data X509Data `xml:"X509Data"` +} + +type X509Data struct { + Text string `xml:",chardata"` + X509Certificate Text `xml:"X509Certificate"` +} + +type RequestedAttachedReference struct { + Text string `xml:",chardata"` + SecurityTokenReference SecurityTokenReference `xml:"SecurityTokenReference"` +} + +type SecurityTokenReference struct { + Text string `xml:",chardata"` + TokenType string `xml:"TokenType,attr"` + O string `xml:"o,attr"` + K string `xml:"k,attr"` + KeyIdentifier KeyIdentifier `xml:"KeyIdentifier"` +} + +type KeyIdentifier struct { + Text string `xml:",chardata"` + ValueType string `xml:"ValueType,attr"` +} + +type RequestedUnattachedReference struct { + Text string `xml:",chardata"` + SecurityTokenReference SecurityTokenReference `xml:"SecurityTokenReference"` +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/version_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/version_string.go new file mode 100644 index 000000000..6fe5efa8a --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/version_string.go @@ -0,0 +1,25 @@ +// Code generated by "stringer -type=Version"; DO NOT EDIT. + +package defs + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[TrustUnknown-0] + _ = x[Trust2005-1] + _ = x[Trust13-2] +} + +const _Version_name = "TrustUnknownTrust2005Trust13" + +var _Version_index = [...]uint8{0, 12, 21, 28} + +func (i Version) String() string { + if i < 0 || i >= Version(len(_Version_index)-1) { + return "Version(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Version_name[_Version_index[i]:_Version_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_endpoint.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_endpoint.go new file mode 100644 index 000000000..8fad5efb5 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_endpoint.go @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import ( + "encoding/xml" + "fmt" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + uuid "github.com/google/uuid" +) + +//go:generate stringer -type=Version + +type Version int + +const ( + TrustUnknown Version = iota + Trust2005 + Trust13 +) + +// Endpoint represents a WSTrust endpoint. +type Endpoint struct { + // Version is the version of the endpoint. + Version Version + // URL is the URL of the endpoint. + URL string +} + +type wsTrustTokenRequestEnvelope struct { + XMLName xml.Name `xml:"s:Envelope"` + Text string `xml:",chardata"` + S string `xml:"xmlns:s,attr"` + Wsa string `xml:"xmlns:wsa,attr"` + Wsu string `xml:"xmlns:wsu,attr"` + Header struct { + Text string `xml:",chardata"` + Action struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"s:mustUnderstand,attr"` + } `xml:"wsa:Action"` + MessageID struct { + Text string `xml:",chardata"` + } `xml:"wsa:messageID"` + ReplyTo struct { + Text string `xml:",chardata"` + Address struct { + Text string `xml:",chardata"` + } `xml:"wsa:Address"` + } `xml:"wsa:ReplyTo"` + To struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"s:mustUnderstand,attr"` + } `xml:"wsa:To"` + Security struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"s:mustUnderstand,attr"` + Wsse string `xml:"xmlns:wsse,attr"` + Timestamp struct { + Text string `xml:",chardata"` + ID string `xml:"wsu:Id,attr"` + Created struct { + Text string `xml:",chardata"` + } `xml:"wsu:Created"` + Expires struct { + Text string `xml:",chardata"` + } `xml:"wsu:Expires"` + } `xml:"wsu:Timestamp"` + UsernameToken struct { + Text string `xml:",chardata"` + ID string `xml:"wsu:Id,attr"` + Username struct { + Text string `xml:",chardata"` + } `xml:"wsse:Username"` + Password struct { + Text string `xml:",chardata"` + } `xml:"wsse:Password"` + } `xml:"wsse:UsernameToken"` + } `xml:"wsse:Security"` + } `xml:"s:Header"` + Body struct { + Text string `xml:",chardata"` + RequestSecurityToken struct { + Text string `xml:",chardata"` + Wst string `xml:"xmlns:wst,attr"` + AppliesTo struct { + Text string `xml:",chardata"` + Wsp string `xml:"xmlns:wsp,attr"` + EndpointReference struct { + Text string `xml:",chardata"` + Address struct { + Text string `xml:",chardata"` + } `xml:"wsa:Address"` + } `xml:"wsa:EndpointReference"` + } `xml:"wsp:AppliesTo"` + KeyType struct { + Text string `xml:",chardata"` + } `xml:"wst:KeyType"` + RequestType struct { + Text string `xml:",chardata"` + } `xml:"wst:RequestType"` + } `xml:"wst:RequestSecurityToken"` + } `xml:"s:Body"` +} + +func buildTimeString(t time.Time) string { + // Golang time formats are weird: https://stackoverflow.com/questions/20234104/how-to-format-current-time-using-a-yyyymmddhhmmss-format + return t.Format("2006-01-02T15:04:05.000Z") +} + +func (wte *Endpoint) buildTokenRequestMessage(authType authority.AuthorizeType, cloudAudienceURN string, username string, password string) (string, error) { + var soapAction string + var trustNamespace string + var keyType string + var requestType string + + createdTime := time.Now().UTC() + expiresTime := createdTime.Add(10 * time.Minute) + + switch wte.Version { + case Trust2005: + soapAction = trust2005Spec + trustNamespace = "http://schemas.xmlsoap.org/ws/2005/02/trust" + keyType = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey" + requestType = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue" + case Trust13: + soapAction = trust13Spec + trustNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512" + keyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer" + requestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue" + default: + return "", fmt.Errorf("buildTokenRequestMessage had Version == %q, which is not recognized", wte.Version) + } + + var envelope wsTrustTokenRequestEnvelope + + messageUUID := uuid.New() + + envelope.S = "http://www.w3.org/2003/05/soap-envelope" + envelope.Wsa = "http://www.w3.org/2005/08/addressing" + envelope.Wsu = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" + + envelope.Header.Action.MustUnderstand = "1" + envelope.Header.Action.Text = soapAction + envelope.Header.MessageID.Text = "urn:uuid:" + messageUUID.String() + envelope.Header.ReplyTo.Address.Text = "http://www.w3.org/2005/08/addressing/anonymous" + envelope.Header.To.MustUnderstand = "1" + envelope.Header.To.Text = wte.URL + + switch authType { + case authority.ATUnknown: + return "", fmt.Errorf("buildTokenRequestMessage had no authority type(%v)", authType) + case authority.ATUsernamePassword: + endpointUUID := uuid.New() + + var trustID string + if wte.Version == Trust2005 { + trustID = "UnPwSecTok2005-" + endpointUUID.String() + } else { + trustID = "UnPwSecTok13-" + endpointUUID.String() + } + + envelope.Header.Security.MustUnderstand = "1" + envelope.Header.Security.Wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" + envelope.Header.Security.Timestamp.ID = "MSATimeStamp" + envelope.Header.Security.Timestamp.Created.Text = buildTimeString(createdTime) + envelope.Header.Security.Timestamp.Expires.Text = buildTimeString(expiresTime) + envelope.Header.Security.UsernameToken.ID = trustID + envelope.Header.Security.UsernameToken.Username.Text = username + envelope.Header.Security.UsernameToken.Password.Text = password + default: + // This is just to note that we don't do anything for other cases. + // We aren't missing anything I know of. + } + + envelope.Body.RequestSecurityToken.Wst = trustNamespace + envelope.Body.RequestSecurityToken.AppliesTo.Wsp = "http://schemas.xmlsoap.org/ws/2004/09/policy" + envelope.Body.RequestSecurityToken.AppliesTo.EndpointReference.Address.Text = cloudAudienceURN + envelope.Body.RequestSecurityToken.KeyType.Text = keyType + envelope.Body.RequestSecurityToken.RequestType.Text = requestType + + output, err := xml.Marshal(envelope) + if err != nil { + return "", err + } + + return string(output), nil +} + +func (wte *Endpoint) BuildTokenRequestMessageWIA(cloudAudienceURN string) (string, error) { + return wte.buildTokenRequestMessage(authority.ATWindowsIntegrated, cloudAudienceURN, "", "") +} + +func (wte *Endpoint) BuildTokenRequestMessageUsernamePassword(cloudAudienceURN string, username string, password string) (string, error) { + return wte.buildTokenRequestMessage(authority.ATUsernamePassword, cloudAudienceURN, username, password) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_mex_document.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_mex_document.go new file mode 100644 index 000000000..e3d19886e --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_mex_document.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import ( + "errors" + "fmt" + "strings" +) + +//go:generate stringer -type=endpointType + +type endpointType int + +const ( + etUnknown endpointType = iota + etUsernamePassword + etWindowsTransport +) + +type wsEndpointData struct { + Version Version + EndpointType endpointType +} + +const trust13Spec string = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue" +const trust2005Spec string = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue" + +type MexDocument struct { + UsernamePasswordEndpoint Endpoint + WindowsTransportEndpoint Endpoint + policies map[string]endpointType + bindings map[string]wsEndpointData +} + +func updateEndpoint(cached *Endpoint, found Endpoint) { + if cached == nil || cached.Version == TrustUnknown { + *cached = found + return + } + if (*cached).Version == Trust2005 && found.Version == Trust13 { + *cached = found + return + } +} + +// TODO(msal): Someone needs to write tests for everything below. + +// NewFromDef creates a new MexDocument. +func NewFromDef(defs Definitions) (MexDocument, error) { + policies, err := policies(defs) + if err != nil { + return MexDocument{}, err + } + + bindings, err := bindings(defs, policies) + if err != nil { + return MexDocument{}, err + } + + userPass, windows, err := endpoints(defs, bindings) + if err != nil { + return MexDocument{}, err + } + + return MexDocument{ + UsernamePasswordEndpoint: userPass, + WindowsTransportEndpoint: windows, + policies: policies, + bindings: bindings, + }, nil +} + +func policies(defs Definitions) (map[string]endpointType, error) { + policies := make(map[string]endpointType, len(defs.Policy)) + + for _, policy := range defs.Policy { + if policy.ExactlyOne.All.NegotiateAuthentication.XMLName.Local != "" { + if policy.ExactlyOne.All.TransportBinding.SP != "" && policy.ID != "" { + policies["#"+policy.ID] = etWindowsTransport + } + } + + if policy.ExactlyOne.All.SignedEncryptedSupportingTokens.Policy.UsernameToken.Policy.WSSUsernameToken10.XMLName.Local != "" { + if policy.ExactlyOne.All.TransportBinding.SP != "" && policy.ID != "" { + policies["#"+policy.ID] = etUsernamePassword + } + } + if policy.ExactlyOne.All.SignedSupportingTokens.Policy.UsernameToken.Policy.WSSUsernameToken10.XMLName.Local != "" { + if policy.ExactlyOne.All.TransportBinding.SP != "" && policy.ID != "" { + policies["#"+policy.ID] = etUsernamePassword + } + } + } + + if len(policies) == 0 { + return policies, errors.New("no policies for mex document") + } + + return policies, nil +} + +func bindings(defs Definitions, policies map[string]endpointType) (map[string]wsEndpointData, error) { + bindings := make(map[string]wsEndpointData, len(defs.Binding)) + + for _, binding := range defs.Binding { + policyName := binding.PolicyReference.URI + transport := binding.Binding.Transport + + if transport == "http://schemas.xmlsoap.org/soap/http" { + if policy, ok := policies[policyName]; ok { + bindingName := binding.Name + specVersion := binding.Operation.Operation.SoapAction + + if specVersion == trust13Spec { + bindings[bindingName] = wsEndpointData{Trust13, policy} + } else if specVersion == trust2005Spec { + bindings[bindingName] = wsEndpointData{Trust2005, policy} + } else { + return nil, errors.New("found unknown spec version in mex document") + } + } + } + } + return bindings, nil +} + +func endpoints(defs Definitions, bindings map[string]wsEndpointData) (userPass, windows Endpoint, err error) { + for _, port := range defs.Service.Port { + bindingName := port.Binding + + index := strings.Index(bindingName, ":") + if index != -1 { + bindingName = bindingName[index+1:] + } + + if binding, ok := bindings[bindingName]; ok { + url := strings.TrimSpace(port.EndpointReference.Address.Text) + if url == "" { + return Endpoint{}, Endpoint{}, fmt.Errorf("MexDocument cannot have blank URL endpoint") + } + if binding.Version == TrustUnknown { + return Endpoint{}, Endpoint{}, fmt.Errorf("endpoint version unknown") + } + endpoint := Endpoint{Version: binding.Version, URL: url} + + switch binding.EndpointType { + case etUsernamePassword: + updateEndpoint(&userPass, endpoint) + case etWindowsTransport: + updateEndpoint(&windows, endpoint) + default: + return Endpoint{}, Endpoint{}, errors.New("found unknown port type in MEX document") + } + } + } + return userPass, windows, nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/wstrust.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/wstrust.go new file mode 100644 index 000000000..47cd4c692 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/wstrust.go @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package wstrust provides a client for communicating with a WSTrust (https://en.wikipedia.org/wiki/WS-Trust#:~:text=WS%2DTrust%20is%20a%20WS,in%20a%20secure%20message%20exchange.) +for the purposes of extracting metadata from the service. This data can be used to acquire +tokens using the accesstokens.Client.GetAccessTokenFromSamlGrant() call. +*/ +package wstrust + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs" +) + +type xmlCaller interface { + XMLCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, resp interface{}) error + SOAPCall(ctx context.Context, endpoint, action string, headers http.Header, qv url.Values, body string, resp interface{}) error +} + +type SamlTokenInfo struct { + AssertionType string // Should be either constants SAMLV1Grant or SAMLV2Grant. + Assertion string +} + +// Client represents the REST calls to get tokens from token generator backends. +type Client struct { + // Comm provides the HTTP transport client. + Comm xmlCaller +} + +// TODO(msal): This allows me to call Mex without having a real Def file on line 45. +// This would fail because policies() would not find a policy. This is easy enough to +// fix in test data, but.... Definitions is defined with built in structs. That needs +// to be pulled apart and until then I have this hack in. +var newFromDef = defs.NewFromDef + +// Mex provides metadata about a wstrust service. +func (c Client) Mex(ctx context.Context, federationMetadataURL string) (defs.MexDocument, error) { + resp := defs.Definitions{} + err := c.Comm.XMLCall( + ctx, + federationMetadataURL, + http.Header{}, + nil, + &resp, + ) + if err != nil { + return defs.MexDocument{}, err + } + + return newFromDef(resp) +} + +const ( + SoapActionDefault = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue" + + // Note: Commented out because this action is not supported. It was in the original code + // but only used in a switch where it errored. Since there was only one value, a default + // worked better. However, buildTokenRequestMessage() had 2005 support. I'm not actually + // sure what's going on here. It like we have half support. For now this is here just + // for documentation purposes in case we are going to add support. + // + // SoapActionWSTrust2005 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue" +) + +// SAMLTokenInfo provides SAML information that is used to generate a SAML token. +func (c Client) SAMLTokenInfo(ctx context.Context, authParameters authority.AuthParams, cloudAudienceURN string, endpoint defs.Endpoint) (SamlTokenInfo, error) { + var wsTrustRequestMessage string + var err error + + switch authParameters.AuthorizationType { + case authority.ATWindowsIntegrated: + wsTrustRequestMessage, err = endpoint.BuildTokenRequestMessageWIA(cloudAudienceURN) + if err != nil { + return SamlTokenInfo{}, err + } + case authority.ATUsernamePassword: + wsTrustRequestMessage, err = endpoint.BuildTokenRequestMessageUsernamePassword( + cloudAudienceURN, authParameters.Username, authParameters.Password) + if err != nil { + return SamlTokenInfo{}, err + } + default: + return SamlTokenInfo{}, fmt.Errorf("unknown auth type %v", authParameters.AuthorizationType) + } + + var soapAction string + switch endpoint.Version { + case defs.Trust13: + soapAction = SoapActionDefault + case defs.Trust2005: + return SamlTokenInfo{}, errors.New("WS Trust 2005 support is not implemented") + default: + return SamlTokenInfo{}, fmt.Errorf("the SOAP endpoint for a wstrust call had an invalid version: %v", endpoint.Version) + } + + resp := defs.SAMLDefinitions{} + err = c.Comm.SOAPCall(ctx, endpoint.URL, soapAction, http.Header{}, nil, wsTrustRequestMessage, &resp) + if err != nil { + return SamlTokenInfo{}, err + } + + return c.samlAssertion(resp) +} + +const ( + samlv1Assertion = "urn:oasis:names:tc:SAML:1.0:assertion" + samlv2Assertion = "urn:oasis:names:tc:SAML:2.0:assertion" +) + +func (c Client) samlAssertion(def defs.SAMLDefinitions) (SamlTokenInfo, error) { + for _, tokenResponse := range def.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse { + token := tokenResponse.RequestedSecurityToken + if token.Assertion.XMLName.Local != "" { + assertion := token.AssertionRawXML + + samlVersion := token.Assertion.Saml + switch samlVersion { + case samlv1Assertion: + return SamlTokenInfo{AssertionType: grant.SAMLV1, Assertion: assertion}, nil + case samlv2Assertion: + return SamlTokenInfo{AssertionType: grant.SAMLV2, Assertion: assertion}, nil + } + return SamlTokenInfo{}, fmt.Errorf("couldn't parse SAML assertion, version unknown: %q", samlVersion) + } + } + return SamlTokenInfo{}, errors.New("unknown WS-Trust version") +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/resolvers.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/resolvers.go new file mode 100644 index 000000000..0ade41179 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/resolvers.go @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// TODO(msal): Write some tests. The original code this came from didn't have tests and I'm too +// tired at this point to do it. It, like many other *Manager code I found was broken because +// they didn't have mutex protection. + +package oauth + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" +) + +// ADFS is an active directory federation service authority type. +const ADFS = "ADFS" + +type cacheEntry struct { + Endpoints authority.Endpoints + ValidForDomainsInList map[string]bool +} + +func createcacheEntry(endpoints authority.Endpoints) cacheEntry { + return cacheEntry{endpoints, map[string]bool{}} +} + +// AuthorityEndpoint retrieves endpoints from an authority for auth and token acquisition. +type authorityEndpoint struct { + rest *ops.REST + + mu sync.Mutex + cache map[string]cacheEntry +} + +// newAuthorityEndpoint is the constructor for AuthorityEndpoint. +func newAuthorityEndpoint(rest *ops.REST) *authorityEndpoint { + m := &authorityEndpoint{rest: rest, cache: map[string]cacheEntry{}} + return m +} + +// ResolveEndpoints gets the authorization and token endpoints and creates an AuthorityEndpoints instance +func (m *authorityEndpoint) ResolveEndpoints(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, error) { + + if endpoints, found := m.cachedEndpoints(authorityInfo, userPrincipalName); found { + return endpoints, nil + } + + endpoint, err := m.openIDConfigurationEndpoint(ctx, authorityInfo, userPrincipalName) + if err != nil { + return authority.Endpoints{}, err + } + + resp, err := m.rest.Authority().GetTenantDiscoveryResponse(ctx, endpoint) + if err != nil { + return authority.Endpoints{}, err + } + if err := resp.Validate(); err != nil { + return authority.Endpoints{}, fmt.Errorf("ResolveEndpoints(): %w", err) + } + + tenant := authorityInfo.Tenant + + endpoints := authority.NewEndpoints( + strings.Replace(resp.AuthorizationEndpoint, "{tenant}", tenant, -1), + strings.Replace(resp.TokenEndpoint, "{tenant}", tenant, -1), + strings.Replace(resp.Issuer, "{tenant}", tenant, -1), + authorityInfo.Host) + + m.addCachedEndpoints(authorityInfo, userPrincipalName, endpoints) + + return endpoints, nil +} + +// cachedEndpoints returns a the cached endpoints if they exists. If not, we return false. +func (m *authorityEndpoint) cachedEndpoints(authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, bool) { + m.mu.Lock() + defer m.mu.Unlock() + + if cacheEntry, ok := m.cache[authorityInfo.CanonicalAuthorityURI]; ok { + if authorityInfo.AuthorityType == ADFS { + domain, err := adfsDomainFromUpn(userPrincipalName) + if err == nil { + if _, ok := cacheEntry.ValidForDomainsInList[domain]; ok { + return cacheEntry.Endpoints, true + } + } + } + return cacheEntry.Endpoints, true + } + return authority.Endpoints{}, false +} + +func (m *authorityEndpoint) addCachedEndpoints(authorityInfo authority.Info, userPrincipalName string, endpoints authority.Endpoints) { + m.mu.Lock() + defer m.mu.Unlock() + + updatedCacheEntry := createcacheEntry(endpoints) + + if authorityInfo.AuthorityType == ADFS { + // Since we're here, we've made a call to the backend. We want to ensure we're caching + // the latest values from the server. + if cacheEntry, ok := m.cache[authorityInfo.CanonicalAuthorityURI]; ok { + for k := range cacheEntry.ValidForDomainsInList { + updatedCacheEntry.ValidForDomainsInList[k] = true + } + } + domain, err := adfsDomainFromUpn(userPrincipalName) + if err == nil { + updatedCacheEntry.ValidForDomainsInList[domain] = true + } + } + + m.cache[authorityInfo.CanonicalAuthorityURI] = updatedCacheEntry +} + +func (m *authorityEndpoint) openIDConfigurationEndpoint(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (string, error) { + if authorityInfo.Tenant == "adfs" { + return fmt.Sprintf("https://%s/adfs/.well-known/openid-configuration", authorityInfo.Host), nil + } else if authorityInfo.ValidateAuthority && !authority.TrustedHost(authorityInfo.Host) { + resp, err := m.rest.Authority().AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return "", err + } + return resp.TenantDiscoveryEndpoint, nil + } else if authorityInfo.Region != "" { + resp, err := m.rest.Authority().AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return "", err + } + return resp.TenantDiscoveryEndpoint, nil + + } + + return authorityInfo.CanonicalAuthorityURI + "v2.0/.well-known/openid-configuration", nil +} + +func adfsDomainFromUpn(userPrincipalName string) (string, error) { + parts := strings.Split(userPrincipalName, "@") + if len(parts) < 2 { + return "", errors.New("no @ present in user principal name") + } + return parts[1], nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options/options.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options/options.go new file mode 100644 index 000000000..4561d72db --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options/options.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package options + +import ( + "errors" + "fmt" +) + +// CallOption implements an optional argument to a method call. See +// https://blog.devgenius.io/go-call-option-that-can-be-used-with-multiple-methods-6c81734f3dbe +// for an explanation of the usage pattern. +type CallOption interface { + Do(any) error + callOption() +} + +// ApplyOptions applies all the callOptions to options. options must be a pointer to a struct and +// callOptions must be a list of objects that implement CallOption. +func ApplyOptions[O, C any](options O, callOptions []C) error { + for _, o := range callOptions { + if t, ok := any(o).(CallOption); !ok { + return fmt.Errorf("unexpected option type %T", o) + } else if err := t.Do(options); err != nil { + return err + } + } + return nil +} + +// NewCallOption returns a new CallOption whose Do() method calls function "f". +func NewCallOption(f func(any) error) CallOption { + if f == nil { + // This isn't a practical concern because only an MSAL maintainer can get + // us here, by implementing a do-nothing option. But if someone does that, + // the below ensures the method invoked with the option returns an error. + return callOption(func(any) error { + return errors.New("invalid option: missing implementation") + }) + } + return callOption(f) +} + +// callOption is an adapter for a function to a CallOption +type callOption func(any) error + +func (c callOption) Do(a any) error { + return c(a) +} + +func (callOption) callOption() {} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared/shared.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared/shared.go new file mode 100644 index 000000000..d8ab71356 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared/shared.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package shared + +import ( + "net/http" + "reflect" + "strings" +) + +const ( + // CacheKeySeparator is used in creating the keys of the cache. + CacheKeySeparator = "-" +) + +type Account struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + Realm string `json:"realm,omitempty"` + LocalAccountID string `json:"local_account_id,omitempty"` + AuthorityType string `json:"authority_type,omitempty"` + PreferredUsername string `json:"username,omitempty"` + GivenName string `json:"given_name,omitempty"` + FamilyName string `json:"family_name,omitempty"` + MiddleName string `json:"middle_name,omitempty"` + Name string `json:"name,omitempty"` + AlternativeID string `json:"alternative_account_id,omitempty"` + RawClientInfo string `json:"client_info,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewAccount creates an account. +func NewAccount(homeAccountID, env, realm, localAccountID, authorityType, username string) Account { + return Account{ + HomeAccountID: homeAccountID, + Environment: env, + Realm: realm, + LocalAccountID: localAccountID, + AuthorityType: authorityType, + PreferredUsername: username, + } +} + +// Key creates the key for storing accounts in the cache. +func (acc Account) Key() string { + key := strings.Join([]string{acc.HomeAccountID, acc.Environment, acc.Realm}, CacheKeySeparator) + return strings.ToLower(key) +} + +// IsZero checks the zero value of account. +func (acc Account) IsZero() bool { + v := reflect.ValueOf(acc) + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if !field.IsZero() { + switch field.Kind() { + case reflect.Map, reflect.Slice: + if field.Len() == 0 { + continue + } + } + return false + } + } + return true +} + +// DefaultClient is our default shared HTTP client. +var DefaultClient = &http.Client{} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go new file mode 100644 index 000000000..eb16b405c --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package version keeps the version number of the client package. +package version + +// Version is the version of this client package that is communicated to the server. +const Version = "1.2.0" diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go new file mode 100644 index 000000000..e346ff3df --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go @@ -0,0 +1,748 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package public provides a client for authentication of "public" applications. A "public" +application is defined as an app that runs on client devices (android, ios, windows, linux, ...). +These devices are "untrusted" and access resources via web APIs that must authenticate. +*/ +package public + +/* +Design note: + +public.Client uses client.Base as an embedded type. client.Base statically assigns its attributes +during creation. As it doesn't have any pointers in it, anything borrowed from it, such as +Base.AuthParams is a copy that is free to be manipulated here. +*/ + +// TODO(msal): This should have example code for each method on client using Go's example doc framework. +// base usage details should be includee in the package documentation. + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" + "net/url" + "reflect" + "strconv" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" + "github.com/google/uuid" + "github.com/pkg/browser" +) + +// AuthResult contains the results of one token acquisition operation. +// For details see https://aka.ms/msal-net-authenticationresult +type AuthResult = base.AuthResult + +type AuthenticationScheme = authority.AuthenticationScheme + +type Account = shared.Account + +var errNoAccount = errors.New("no account was specified with public.WithSilentAccount(), or the specified account is invalid") + +// clientOptions configures the Client's behavior. +type clientOptions struct { + accessor cache.ExportReplace + authority string + capabilities []string + disableInstanceDiscovery bool + httpClient ops.HTTPClient +} + +func (p *clientOptions) validate() error { + u, err := url.Parse(p.authority) + if err != nil { + return fmt.Errorf("Authority options cannot be URL parsed: %w", err) + } + if u.Scheme != "https" { + return fmt.Errorf("Authority(%s) did not start with https://", u.String()) + } + return nil +} + +// Option is an optional argument to the New constructor. +type Option func(o *clientOptions) + +// WithAuthority allows for a custom authority to be set. This must be a valid https url. +func WithAuthority(authority string) Option { + return func(o *clientOptions) { + o.authority = authority + } +} + +// WithCache provides an accessor that will read and write authentication data to an externally managed cache. +func WithCache(accessor cache.ExportReplace) Option { + return func(o *clientOptions) { + o.accessor = accessor + } +} + +// WithClientCapabilities allows configuring one or more client capabilities such as "CP1" +func WithClientCapabilities(capabilities []string) Option { + return func(o *clientOptions) { + // there's no danger of sharing the slice's underlying memory with the application because + // this slice is simply passed to base.WithClientCapabilities, which copies its data + o.capabilities = capabilities + } +} + +// WithHTTPClient allows for a custom HTTP client to be set. +func WithHTTPClient(httpClient ops.HTTPClient) Option { + return func(o *clientOptions) { + o.httpClient = httpClient + } +} + +// WithInstanceDiscovery set to false to disable authority validation (to support private cloud scenarios) +func WithInstanceDiscovery(enabled bool) Option { + return func(o *clientOptions) { + o.disableInstanceDiscovery = !enabled + } +} + +// Client is a representation of authentication client for public applications as defined in the +// package doc. For more information, visit https://docs.microsoft.com/azure/active-directory/develop/msal-client-applications. +type Client struct { + base base.Client +} + +// New is the constructor for Client. +func New(clientID string, options ...Option) (Client, error) { + opts := clientOptions{ + authority: base.AuthorityPublicCloud, + httpClient: shared.DefaultClient, + } + + for _, o := range options { + o(&opts) + } + if err := opts.validate(); err != nil { + return Client{}, err + } + + base, err := base.New(clientID, opts.authority, oauth.New(opts.httpClient), base.WithCacheAccessor(opts.accessor), base.WithClientCapabilities(opts.capabilities), base.WithInstanceDiscovery(!opts.disableInstanceDiscovery)) + if err != nil { + return Client{}, err + } + return Client{base}, nil +} + +// authCodeURLOptions contains options for AuthCodeURL +type authCodeURLOptions struct { + claims, loginHint, tenantID, domainHint string +} + +// AuthCodeURLOption is implemented by options for AuthCodeURL +type AuthCodeURLOption interface { + authCodeURLOption() +} + +// AuthCodeURL creates a URL used to acquire an authorization code. +// +// Options: [WithClaims], [WithDomainHint], [WithLoginHint], [WithTenantID] +func (pca Client) AuthCodeURL(ctx context.Context, clientID, redirectURI string, scopes []string, opts ...AuthCodeURLOption) (string, error) { + o := authCodeURLOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return "", err + } + ap, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return "", err + } + ap.Claims = o.claims + ap.LoginHint = o.loginHint + ap.DomainHint = o.domainHint + return pca.base.AuthCodeURL(ctx, clientID, redirectURI, scopes, ap) +} + +// WithClaims sets additional claims to request for the token, such as those required by conditional access policies. +// Use this option when Azure AD returned a claims challenge for a prior request. The argument must be decoded. +// This option is valid for any token acquisition method. +func WithClaims(claims string) interface { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenByAuthCodeOptions: + t.claims = claims + case *acquireTokenByDeviceCodeOptions: + t.claims = claims + case *acquireTokenByUsernamePasswordOptions: + t.claims = claims + case *acquireTokenSilentOptions: + t.claims = claims + case *authCodeURLOptions: + t.claims = claims + case *interactiveAuthOptions: + t.claims = claims + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithAuthenticationScheme is an extensibility mechanism designed to be used only by Azure Arc for proof of possession access tokens. +func WithAuthenticationScheme(authnScheme AuthenticationScheme) interface { + AcquireSilentOption + AcquireInteractiveOption + options.CallOption +} { + return struct { + AcquireSilentOption + AcquireInteractiveOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenSilentOptions: + t.authnScheme = authnScheme + case *interactiveAuthOptions: + t.authnScheme = authnScheme + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithTenantID specifies a tenant for a single authentication. It may be different than the tenant set in [New] by [WithAuthority]. +// This option is valid for any token acquisition method. +func WithTenantID(tenantID string) interface { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenByAuthCodeOptions: + t.tenantID = tenantID + case *acquireTokenByDeviceCodeOptions: + t.tenantID = tenantID + case *acquireTokenByUsernamePasswordOptions: + t.tenantID = tenantID + case *acquireTokenSilentOptions: + t.tenantID = tenantID + case *authCodeURLOptions: + t.tenantID = tenantID + case *interactiveAuthOptions: + t.tenantID = tenantID + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// acquireTokenSilentOptions are all the optional settings to an AcquireTokenSilent() call. +// These are set by using various AcquireTokenSilentOption functions. +type acquireTokenSilentOptions struct { + account Account + claims, tenantID string + authnScheme AuthenticationScheme +} + +// AcquireSilentOption is implemented by options for AcquireTokenSilent +type AcquireSilentOption interface { + acquireSilentOption() +} + +// WithSilentAccount uses the passed account during an AcquireTokenSilent() call. +func WithSilentAccount(account Account) interface { + AcquireSilentOption + options.CallOption +} { + return struct { + AcquireSilentOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenSilentOptions: + t.account = account + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenSilent acquires a token from either the cache or using a refresh token. +// +// Options: [WithClaims], [WithSilentAccount], [WithTenantID] +func (pca Client) AcquireTokenSilent(ctx context.Context, scopes []string, opts ...AcquireSilentOption) (AuthResult, error) { + o := acquireTokenSilentOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + // an account is required to find user tokens in the cache + if reflect.ValueOf(o.account).IsZero() { + return AuthResult{}, errNoAccount + } + + silentParameters := base.AcquireTokenSilentParameters{ + Scopes: scopes, + Account: o.account, + Claims: o.claims, + RequestType: accesstokens.ATPublic, + IsAppCache: false, + TenantID: o.tenantID, + AuthnScheme: o.authnScheme, + } + + return pca.base.AcquireTokenSilent(ctx, silentParameters) +} + +// acquireTokenByUsernamePasswordOptions contains optional configuration for AcquireTokenByUsernamePassword +type acquireTokenByUsernamePasswordOptions struct { + claims, tenantID string +} + +// AcquireByUsernamePasswordOption is implemented by options for AcquireTokenByUsernamePassword +type AcquireByUsernamePasswordOption interface { + acquireByUsernamePasswordOption() +} + +// AcquireTokenByUsernamePassword acquires a security token from the authority, via Username/Password Authentication. +// NOTE: this flow is NOT recommended. +// +// Options: [WithClaims], [WithTenantID] +func (pca Client) AcquireTokenByUsernamePassword(ctx context.Context, scopes []string, username, password string, opts ...AcquireByUsernamePasswordOption) (AuthResult, error) { + o := acquireTokenByUsernamePasswordOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + authParams, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATUsernamePassword + authParams.Claims = o.claims + authParams.Username = username + authParams.Password = password + + token, err := pca.base.Token.UsernamePassword(ctx, authParams) + if err != nil { + return AuthResult{}, err + } + return pca.base.AuthResultFromToken(ctx, authParams, token, true) +} + +type DeviceCodeResult = accesstokens.DeviceCodeResult + +// DeviceCode provides the results of the device code flows first stage (containing the code) +// that must be entered on the second device and provides a method to retrieve the AuthenticationResult +// once that code has been entered and verified. +type DeviceCode struct { + // Result holds the information about the device code (such as the code). + Result DeviceCodeResult + + authParams authority.AuthParams + client Client + dc oauth.DeviceCode +} + +// AuthenticationResult retreives the AuthenticationResult once the user enters the code +// on the second device. Until then it blocks until the .AcquireTokenByDeviceCode() context +// is cancelled or the token expires. +func (d DeviceCode) AuthenticationResult(ctx context.Context) (AuthResult, error) { + token, err := d.dc.Token(ctx) + if err != nil { + return AuthResult{}, err + } + return d.client.base.AuthResultFromToken(ctx, d.authParams, token, true) +} + +// acquireTokenByDeviceCodeOptions contains optional configuration for AcquireTokenByDeviceCode +type acquireTokenByDeviceCodeOptions struct { + claims, tenantID string +} + +// AcquireByDeviceCodeOption is implemented by options for AcquireTokenByDeviceCode +type AcquireByDeviceCodeOption interface { + acquireByDeviceCodeOptions() +} + +// AcquireTokenByDeviceCode acquires a security token from the authority, by acquiring a device code and using that to acquire the token. +// Users need to create an AcquireTokenDeviceCodeParameters instance and pass it in. +// +// Options: [WithClaims], [WithTenantID] +func (pca Client) AcquireTokenByDeviceCode(ctx context.Context, scopes []string, opts ...AcquireByDeviceCodeOption) (DeviceCode, error) { + o := acquireTokenByDeviceCodeOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return DeviceCode{}, err + } + authParams, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return DeviceCode{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATDeviceCode + authParams.Claims = o.claims + + dc, err := pca.base.Token.DeviceCode(ctx, authParams) + if err != nil { + return DeviceCode{}, err + } + + return DeviceCode{Result: dc.Result, authParams: authParams, client: pca, dc: dc}, nil +} + +// acquireTokenByAuthCodeOptions contains the optional parameters used to acquire an access token using the authorization code flow. +type acquireTokenByAuthCodeOptions struct { + challenge, claims, tenantID string +} + +// AcquireByAuthCodeOption is implemented by options for AcquireTokenByAuthCode +type AcquireByAuthCodeOption interface { + acquireByAuthCodeOption() +} + +// WithChallenge allows you to provide a code for the .AcquireTokenByAuthCode() call. +func WithChallenge(challenge string) interface { + AcquireByAuthCodeOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *acquireTokenByAuthCodeOptions: + t.challenge = challenge + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenByAuthCode is a request to acquire a security token from the authority, using an authorization code. +// The specified redirect URI must be the same URI that was used when the authorization code was requested. +// +// Options: [WithChallenge], [WithClaims], [WithTenantID] +func (pca Client) AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, opts ...AcquireByAuthCodeOption) (AuthResult, error) { + o := acquireTokenByAuthCodeOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + + params := base.AcquireTokenAuthCodeParameters{ + Scopes: scopes, + Code: code, + Challenge: o.challenge, + Claims: o.claims, + AppType: accesstokens.ATPublic, + RedirectURI: redirectURI, + TenantID: o.tenantID, + } + + return pca.base.AcquireTokenByAuthCode(ctx, params) +} + +// Accounts gets all the accounts in the token cache. +// If there are no accounts in the cache the returned slice is empty. +func (pca Client) Accounts(ctx context.Context) ([]Account, error) { + return pca.base.AllAccounts(ctx) +} + +// RemoveAccount signs the account out and forgets account from token cache. +func (pca Client) RemoveAccount(ctx context.Context, account Account) error { + return pca.base.RemoveAccount(ctx, account) +} + +// interactiveAuthOptions contains the optional parameters used to acquire an access token for interactive auth code flow. +type interactiveAuthOptions struct { + claims, domainHint, loginHint, redirectURI, tenantID string + openURL func(url string) error + authnScheme AuthenticationScheme +} + +// AcquireInteractiveOption is implemented by options for AcquireTokenInteractive +type AcquireInteractiveOption interface { + acquireInteractiveOption() +} + +// WithLoginHint pre-populates the login prompt with a username. +func WithLoginHint(username string) interface { + AcquireInteractiveOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireInteractiveOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *authCodeURLOptions: + t.loginHint = username + case *interactiveAuthOptions: + t.loginHint = username + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithDomainHint adds the IdP domain as domain_hint query parameter in the auth url. +func WithDomainHint(domain string) interface { + AcquireInteractiveOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireInteractiveOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *authCodeURLOptions: + t.domainHint = domain + case *interactiveAuthOptions: + t.domainHint = domain + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithRedirectURI sets a port for the local server used in interactive authentication, for +// example http://localhost:port. All URI components other than the port are ignored. +func WithRedirectURI(redirectURI string) interface { + AcquireInteractiveOption + options.CallOption +} { + return struct { + AcquireInteractiveOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *interactiveAuthOptions: + t.redirectURI = redirectURI + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithOpenURL allows you to provide a function to open the browser to complete the interactive login, instead of launching the system default browser. +func WithOpenURL(openURL func(url string) error) interface { + AcquireInteractiveOption + options.CallOption +} { + return struct { + AcquireInteractiveOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *interactiveAuthOptions: + t.openURL = openURL + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenInteractive acquires a security token from the authority using the default web browser to select the account. +// https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#interactive-and-non-interactive-authentication +// +// Options: [WithDomainHint], [WithLoginHint], [WithOpenURL], [WithRedirectURI], [WithTenantID] +func (pca Client) AcquireTokenInteractive(ctx context.Context, scopes []string, opts ...AcquireInteractiveOption) (AuthResult, error) { + o := interactiveAuthOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + // the code verifier is a random 32-byte sequence that's been base-64 encoded without padding. + // it's used to prevent MitM attacks during auth code flow, see https://tools.ietf.org/html/rfc7636 + cv, challenge, err := codeVerifier() + if err != nil { + return AuthResult{}, err + } + var redirectURL *url.URL + if o.redirectURI != "" { + redirectURL, err = url.Parse(o.redirectURI) + if err != nil { + return AuthResult{}, err + } + } + if o.openURL == nil { + o.openURL = browser.OpenURL + } + authParams, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATInteractive + authParams.Claims = o.claims + authParams.CodeChallenge = challenge + authParams.CodeChallengeMethod = "S256" + authParams.LoginHint = o.loginHint + authParams.DomainHint = o.domainHint + authParams.State = uuid.New().String() + authParams.Prompt = "select_account" + if o.authnScheme != nil { + authParams.AuthnScheme = o.authnScheme + } + res, err := pca.browserLogin(ctx, redirectURL, authParams, o.openURL) + if err != nil { + return AuthResult{}, err + } + authParams.Redirecturi = res.redirectURI + + req, err := accesstokens.NewCodeChallengeRequest(authParams, accesstokens.ATPublic, nil, res.authCode, cv) + if err != nil { + return AuthResult{}, err + } + + token, err := pca.base.Token.AuthCode(ctx, req) + if err != nil { + return AuthResult{}, err + } + + return pca.base.AuthResultFromToken(ctx, authParams, token, true) +} + +type interactiveAuthResult struct { + authCode string + redirectURI string +} + +// parses the port number from the provided URL. +// returns 0 if nil or no port is specified. +func parsePort(u *url.URL) (int, error) { + if u == nil { + return 0, nil + } + p := u.Port() + if p == "" { + return 0, nil + } + return strconv.Atoi(p) +} + +// browserLogin calls openURL and waits for a user to log in +func (pca Client) browserLogin(ctx context.Context, redirectURI *url.URL, params authority.AuthParams, openURL func(string) error) (interactiveAuthResult, error) { + // start local redirect server so login can call us back + port, err := parsePort(redirectURI) + if err != nil { + return interactiveAuthResult{}, err + } + srv, err := local.New(params.State, port) + if err != nil { + return interactiveAuthResult{}, err + } + defer srv.Shutdown() + params.Scopes = accesstokens.AppendDefaultScopes(params) + authURL, err := pca.base.AuthCodeURL(ctx, params.ClientID, srv.Addr, params.Scopes, params) + if err != nil { + return interactiveAuthResult{}, err + } + // open browser window so user can select credentials + if err := openURL(authURL); err != nil { + return interactiveAuthResult{}, err + } + // now wait until the logic calls us back + res := srv.Result(ctx) + if res.Err != nil { + return interactiveAuthResult{}, res.Err + } + return interactiveAuthResult{ + authCode: res.Code, + redirectURI: srv.Addr, + }, nil +} + +// creates a code verifier string along with its SHA256 hash which +// is used as the challenge when requesting an auth code. +// used in interactive auth flow for PKCE. +func codeVerifier() (codeVerifier string, challenge string, err error) { + cvBytes := make([]byte, 32) + if _, err = rand.Read(cvBytes); err != nil { + return + } + codeVerifier = base64.RawURLEncoding.EncodeToString(cvBytes) + // for PKCE, create a hash of the code verifier + cvh := sha256.Sum256([]byte(codeVerifier)) + challenge = base64.RawURLEncoding.EncodeToString(cvh[:]) + return +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/LICENSE b/vendor/github.com/Code-Hex/go-generics-cache/LICENSE new file mode 100644 index 000000000..28adb0ddb --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 codehex + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/Code-Hex/go-generics-cache/README.md b/vendor/github.com/Code-Hex/go-generics-cache/README.md new file mode 100644 index 000000000..455a6b85a --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/README.md @@ -0,0 +1,81 @@ +# go-generics-cache + +[![.github/workflows/test.yml](https://github.com/Code-Hex/go-generics-cache/actions/workflows/test.yml/badge.svg)](https://github.com/Code-Hex/go-generics-cache/actions/workflows/test.yml) [![codecov](https://codecov.io/gh/Code-Hex/go-generics-cache/branch/main/graph/badge.svg?token=Wm7UEwgiZu)](https://codecov.io/gh/Code-Hex/go-generics-cache) [![Go Reference](https://pkg.go.dev/badge/github.com/Code-Hex/go-generics-cache.svg)](https://pkg.go.dev/github.com/Code-Hex/go-generics-cache) + +go-generics-cache is an in-memory key:value store/cache that is suitable for applications running on a single machine. This in-memory cache uses [Go Generics](https://go.dev/blog/generics-proposal) which is introduced in 1.18. + +- a thread-safe +- implemented with [Go Generics](https://go.dev/blog/generics-proposal) +- TTL supported (with expiration times) +- Simple cache is like `map[string]interface{}` + - See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/policy/simple/example_test.go) +- Cache replacement policies + - **Least recently used (LRU)** + - Discards the least recently used items first. + - See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/policy/lru/example_test.go) + - **Least-frequently used (LFU)** + - Counts how often an item is needed. Those that are used least often are discarded first. + - [An O(1) algorithm for implementing the LFU cache eviction scheme](http://dhruvbird.com/lfu.pdf) + - See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/policy/lfu/example_test.go) + - **First in first out (FIFO)** + - Using this algorithm the cache behaves in the same way as a [FIFO queue](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)). + - The cache evicts the blocks in the order they were added, without any regard to how often or how many times they were accessed before. + - See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/policy/fifo/example_test.go) + - **Most recently used (MRU)** + - In contrast to Least Recently Used (LRU), MRU discards the most recently used items first. + - See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/policy/mru/example_test.go) + - **Clock** + - Clock is a more efficient version of FIFO than Second-chance cache algorithm. + - See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/policy/clock/example_test.go) + +## Requirements + +Go 1.18 or later. + +## Install + + $ go get github.com/Code-Hex/go-generics-cache + +## Usage + +See also [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/example_test.go) or [go playground](https://go.dev/play/p/kDs-6wpRAcX) + +```go +package main + +import ( + "context" + "fmt" + "time" + + cache "github.com/Code-Hex/go-generics-cache" +) + +func main() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // use simple cache algorithm without options. + c := cache.NewContext[string, int](ctx) + c.Set("a", 1) + gota, aok := c.Get("a") + gotb, bok := c.Get("b") + fmt.Println(gota, aok) // 1 true + fmt.Println(gotb, bok) // 0 false + + // Create a cache for Number constraint. key as string, value as int. + nc := cache.NewNumber[string, int]() + nc.Set("age", 26, cache.WithExpiration(time.Hour)) + + incremented := nc.Increment("age", 1) + fmt.Println(incremented) // 27 + + decremented := nc.Decrement("age", 1) + fmt.Println(decremented) // 26 +} +``` + +## Articles + +- English: [Some tips and bothers for Go 1.18 Generics](https://dev.to/codehex/some-tips-and-bothers-for-go-118-generics-lc7) +- Japanese: [Go 1.18 ã® Generics を使ã£ãŸã‚­ãƒ£ãƒƒã‚·ãƒ¥ãƒ©ã‚¤ãƒ–ラリを作ã£ãŸæ™‚ã«è¦‹ã¤ã‘㟠tips ã¨å¾®å¦™ãªç‚¹](https://zenn.dev/codehex/articles/3e6935ee6d853e) diff --git a/vendor/github.com/Code-Hex/go-generics-cache/cache.go b/vendor/github.com/Code-Hex/go-generics-cache/cache.go new file mode 100644 index 000000000..df7572848 --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/cache.go @@ -0,0 +1,301 @@ +package cache + +import ( + "context" + "sync" + "time" + + "github.com/Code-Hex/go-generics-cache/policy/clock" + "github.com/Code-Hex/go-generics-cache/policy/fifo" + "github.com/Code-Hex/go-generics-cache/policy/lfu" + "github.com/Code-Hex/go-generics-cache/policy/lru" + "github.com/Code-Hex/go-generics-cache/policy/mru" + "github.com/Code-Hex/go-generics-cache/policy/simple" +) + +// Interface is a common-cache interface. +type Interface[K comparable, V any] interface { + // Get looks up a key's value from the cache. + Get(key K) (value V, ok bool) + // Set sets a value to the cache with key. replacing any existing value. + Set(key K, val V) + // Keys returns the keys of the cache. The order is relied on algorithms. + Keys() []K + // Delete deletes the item with provided key from the cache. + Delete(key K) +} + +var ( + _ = []Interface[struct{}, any]{ + (*simple.Cache[struct{}, any])(nil), + (*lru.Cache[struct{}, any])(nil), + (*lfu.Cache[struct{}, any])(nil), + (*fifo.Cache[struct{}, any])(nil), + (*mru.Cache[struct{}, any])(nil), + (*clock.Cache[struct{}, any])(nil), + } +) + +// Item is an item +type Item[K comparable, V any] struct { + Key K + Value V + Expiration time.Time + InitialReferenceCount int +} + +// Expired returns true if the item has expired. +func (item *Item[K, V]) Expired() bool { + if item.Expiration.IsZero() { + return false + } + return nowFunc().After(item.Expiration) +} + +// GetReferenceCount returns reference count to be used when setting +// the cache item for the first time. +func (item *Item[K, V]) GetReferenceCount() int { + return item.InitialReferenceCount +} + +var nowFunc = time.Now + +// ItemOption is an option for cache item. +type ItemOption func(*itemOptions) + +type itemOptions struct { + expiration time.Time // default none + referenceCount int +} + +// WithExpiration is an option to set expiration time for any items. +// If the expiration is zero or negative value, it treats as w/o expiration. +func WithExpiration(exp time.Duration) ItemOption { + return func(o *itemOptions) { + o.expiration = nowFunc().Add(exp) + } +} + +// WithReferenceCount is an option to set reference count for any items. +// This option is only applicable to cache policies that have a reference count (e.g., Clock, LFU). +// referenceCount specifies the reference count value to set for the cache item. +// +// the default is 1. +func WithReferenceCount(referenceCount int) ItemOption { + return func(o *itemOptions) { + o.referenceCount = referenceCount + } +} + +// newItem creates a new item with specified any options. +func newItem[K comparable, V any](key K, val V, opts ...ItemOption) *Item[K, V] { + o := new(itemOptions) + for _, optFunc := range opts { + optFunc(o) + } + return &Item[K, V]{ + Key: key, + Value: val, + Expiration: o.expiration, + InitialReferenceCount: o.referenceCount, + } +} + +// Cache is a thread safe cache. +type Cache[K comparable, V any] struct { + cache Interface[K, *Item[K, V]] + // mu is used to do lock in some method process. + mu sync.Mutex + janitor *janitor +} + +// Option is an option for cache. +type Option[K comparable, V any] func(*options[K, V]) + +type options[K comparable, V any] struct { + cache Interface[K, *Item[K, V]] + janitorInterval time.Duration +} + +func newOptions[K comparable, V any]() *options[K, V] { + return &options[K, V]{ + cache: simple.NewCache[K, *Item[K, V]](), + janitorInterval: time.Minute, + } +} + +// AsLRU is an option to make a new Cache as LRU algorithm. +func AsLRU[K comparable, V any](opts ...lru.Option) Option[K, V] { + return func(o *options[K, V]) { + o.cache = lru.NewCache[K, *Item[K, V]](opts...) + } +} + +// AsLFU is an option to make a new Cache as LFU algorithm. +func AsLFU[K comparable, V any](opts ...lfu.Option) Option[K, V] { + return func(o *options[K, V]) { + o.cache = lfu.NewCache[K, *Item[K, V]](opts...) + } +} + +// AsFIFO is an option to make a new Cache as FIFO algorithm. +func AsFIFO[K comparable, V any](opts ...fifo.Option) Option[K, V] { + return func(o *options[K, V]) { + o.cache = fifo.NewCache[K, *Item[K, V]](opts...) + } +} + +// AsMRU is an option to make a new Cache as MRU algorithm. +func AsMRU[K comparable, V any](opts ...mru.Option) Option[K, V] { + return func(o *options[K, V]) { + o.cache = mru.NewCache[K, *Item[K, V]](opts...) + } +} + +// AsClock is an option to make a new Cache as clock algorithm. +func AsClock[K comparable, V any](opts ...clock.Option) Option[K, V] { + return func(o *options[K, V]) { + o.cache = clock.NewCache[K, *Item[K, V]](opts...) + } +} + +// WithJanitorInterval is an option to specify how often cache should delete expired items. +// +// Default is 1 minute. +func WithJanitorInterval[K comparable, V any](d time.Duration) Option[K, V] { + return func(o *options[K, V]) { + o.janitorInterval = d + } +} + +// New creates a new thread safe Cache. +// The janitor will not be stopped which is created by this function. If you +// want to stop the janitor gracefully, You should use the `NewContext` function +// instead of this. +// +// There are several Cache replacement policies available with you specified any options. +func New[K comparable, V any](opts ...Option[K, V]) *Cache[K, V] { + return NewContext(context.Background(), opts...) +} + +// NewContext creates a new thread safe Cache with context. +// This function will be stopped an internal janitor when the context is cancelled. +// +// There are several Cache replacement policies available with you specified any options. +func NewContext[K comparable, V any](ctx context.Context, opts ...Option[K, V]) *Cache[K, V] { + o := newOptions[K, V]() + for _, optFunc := range opts { + optFunc(o) + } + cache := &Cache[K, V]{ + cache: o.cache, + janitor: newJanitor(ctx, o.janitorInterval), + } + cache.janitor.run(cache.DeleteExpired) + return cache +} + +// Get looks up a key's value from the cache. +func (c *Cache[K, V]) Get(key K) (value V, ok bool) { + c.mu.Lock() + defer c.mu.Unlock() + item, ok := c.cache.Get(key) + + if !ok { + return + } + + // Returns nil if the item has been expired. + // Do not delete here and leave it to an external process such as Janitor. + if item.Expired() { + return value, false + } + + return item.Value, true +} + +// DeleteExpired all expired items from the cache. +func (c *Cache[K, V]) DeleteExpired() { + c.mu.Lock() + keys := c.cache.Keys() + c.mu.Unlock() + + for _, key := range keys { + c.mu.Lock() + // if is expired, delete it and return nil instead + item, ok := c.cache.Get(key) + if ok && item.Expired() { + c.cache.Delete(key) + } + c.mu.Unlock() + } +} + +// Set sets a value to the cache with key. replacing any existing value. +func (c *Cache[K, V]) Set(key K, val V, opts ...ItemOption) { + c.mu.Lock() + defer c.mu.Unlock() + item := newItem(key, val, opts...) + c.cache.Set(key, item) +} + +// Keys returns the keys of the cache. the order is relied on algorithms. +func (c *Cache[K, V]) Keys() []K { + c.mu.Lock() + defer c.mu.Unlock() + return c.cache.Keys() +} + +// Delete deletes the item with provided key from the cache. +func (c *Cache[K, V]) Delete(key K) { + c.mu.Lock() + defer c.mu.Unlock() + c.cache.Delete(key) +} + +// Contains reports whether key is within cache. +func (c *Cache[K, V]) Contains(key K) bool { + c.mu.Lock() + defer c.mu.Unlock() + _, ok := c.cache.Get(key) + return ok +} + +// NumberCache is a in-memory cache which is able to store only Number constraint. +type NumberCache[K comparable, V Number] struct { + *Cache[K, V] + // nmu is used to do lock in Increment/Decrement process. + // Note that this must be here as a separate mutex because mu in Cache struct is Locked in Get, + // and if we call mu.Lock in Increment/Decrement, it will cause deadlock. + nmu sync.Mutex +} + +// NewNumber creates a new cache for Number constraint. +func NewNumber[K comparable, V Number](opts ...Option[K, V]) *NumberCache[K, V] { + return &NumberCache[K, V]{ + Cache: New(opts...), + } +} + +// Increment an item of type Number constraint by n. +// Returns the incremented value. +func (nc *NumberCache[K, V]) Increment(key K, n V) V { + // In order to avoid lost update, we must lock whole Increment/Decrement process. + nc.nmu.Lock() + defer nc.nmu.Unlock() + got, _ := nc.Cache.Get(key) + nv := got + n + nc.Cache.Set(key, nv) + return nv +} + +// Decrement an item of type Number constraint by n. +// Returns the decremented value. +func (nc *NumberCache[K, V]) Decrement(key K, n V) V { + nc.nmu.Lock() + defer nc.nmu.Unlock() + got, _ := nc.Cache.Get(key) + nv := got - n + nc.Cache.Set(key, nv) + return nv +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/constraint.go b/vendor/github.com/Code-Hex/go-generics-cache/constraint.go new file mode 100644 index 000000000..4f0ec8db4 --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/constraint.go @@ -0,0 +1,8 @@ +package cache + +import "golang.org/x/exp/constraints" + +// Number is a constraint that permits any numeric types. +type Number interface { + constraints.Integer | constraints.Float | constraints.Complex +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/janitor.go b/vendor/github.com/Code-Hex/go-generics-cache/janitor.go new file mode 100644 index 000000000..5ed89c9b0 --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/janitor.go @@ -0,0 +1,48 @@ +package cache + +import ( + "context" + "sync" + "time" +) + +// janitor for collecting expired items and cleaning them. +type janitor struct { + ctx context.Context + interval time.Duration + done chan struct{} + once sync.Once +} + +func newJanitor(ctx context.Context, interval time.Duration) *janitor { + j := &janitor{ + ctx: ctx, + interval: interval, + done: make(chan struct{}), + } + return j +} + +// stop to stop the janitor. +func (j *janitor) stop() { + j.once.Do(func() { close(j.done) }) +} + +// run with the given cleanup callback function. +func (j *janitor) run(cleanup func()) { + go func() { + ticker := time.NewTicker(j.interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + cleanup() + case <-j.done: + cleanup() // last call + return + case <-j.ctx.Done(): + j.stop() + } + } + }() +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/clock/clock.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/clock/clock.go new file mode 100644 index 000000000..cc4dfd3d7 --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/clock/clock.go @@ -0,0 +1,142 @@ +package clock + +import ( + "container/ring" + + "github.com/Code-Hex/go-generics-cache/policy/internal/policyutil" +) + +// Cache is used The clock cache replacement policy. +// +// The clock algorithm keeps a circular list of pages in memory, with +// the "hand" (iterator) pointing to the last examined page frame in the list. +// When a page fault occurs and no empty frames exist, then the R (referenced) bit +// is inspected at the hand's location. If R is 0, the new page is put in place of +// the page the "hand" points to, and the hand is advanced one position. Otherwise, +// the R bit is cleared, then the clock hand is incremented and the process is +// repeated until a page is replaced. +type Cache[K comparable, V any] struct { + items map[K]*ring.Ring + hand *ring.Ring + head *ring.Ring + capacity int +} + +type entry[K comparable, V any] struct { + key K + val V + referenceCount int +} + +// Option is an option for clock cache. +type Option func(*options) + +type options struct { + capacity int +} + +func newOptions() *options { + return &options{ + capacity: 128, + } +} + +// WithCapacity is an option to set cache capacity. +func WithCapacity(cap int) Option { + return func(o *options) { + o.capacity = cap + } +} + +// NewCache creates a new non-thread safe clock cache whose capacity is the default size (128). +func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] { + o := newOptions() + for _, optFunc := range opts { + optFunc(o) + } + r := ring.New(o.capacity) + return &Cache[K, V]{ + items: make(map[K]*ring.Ring, o.capacity), + hand: r, + head: r, + capacity: o.capacity, + } +} + +// Set sets any item to the cache. replacing any existing item. +// +// If value satisfies "interface{ GetReferenceCount() int }", the value of +// the GetReferenceCount() method is used to set the initial value of reference count. +func (c *Cache[K, V]) Set(key K, val V) { + if e, ok := c.items[key]; ok { + entry := e.Value.(*entry[K, V]) + entry.referenceCount++ + entry.val = val + return + } + c.evict() + c.hand.Value = &entry[K, V]{ + key: key, + val: val, + referenceCount: policyutil.GetReferenceCount(val), + } + c.items[key] = c.hand + c.hand = c.hand.Next() +} + +// Get looks up a key's value from the cache. +func (c *Cache[K, V]) Get(key K) (zero V, _ bool) { + e, ok := c.items[key] + if !ok { + return + } + entry := e.Value.(*entry[K, V]) + entry.referenceCount++ + return entry.val, true +} + +func (c *Cache[K, V]) evict() { + for c.hand.Value != nil && c.hand.Value.(*entry[K, V]).referenceCount > 0 { + c.hand.Value.(*entry[K, V]).referenceCount-- + c.hand = c.hand.Next() + } + if c.hand.Value != nil { + entry := c.hand.Value.(*entry[K, V]) + delete(c.items, entry.key) + c.hand.Value = nil + } +} + +// Keys returns the keys of the cache. the order as same as current ring order. +func (c *Cache[K, V]) Keys() []K { + keys := make([]K, 0, len(c.items)) + r := c.head + if r.Value == nil { + return []K{} + } + // the first element + keys = append(keys, r.Value.(*entry[K, V]).key) + + // iterating + for p := c.head.Next(); p != r; p = p.Next() { + if p.Value == nil { + continue + } + e := p.Value.(*entry[K, V]) + keys = append(keys, e.key) + } + return keys +} + +// Delete deletes the item with provided key from the cache. +func (c *Cache[K, V]) Delete(key K) { + if e, ok := c.items[key]; ok { + delete(c.items, key) + e.Value = nil + } +} + +// Len returns the number of items in the cache. +func (c *Cache[K, V]) Len() int { + return len(c.items) +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/fifo/fifo.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/fifo/fifo.go new file mode 100644 index 000000000..cf62f1815 --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/fifo/fifo.go @@ -0,0 +1,106 @@ +package fifo + +import ( + "container/list" +) + +// Cache is used a FIFO (First in first out) cache replacement policy. +// +// In FIFO the item that enter the cache first is evicted first +// w/o any regard of how often or how many times it was accessed before. +type Cache[K comparable, V any] struct { + items map[K]*list.Element + queue *list.List // keys + capacity int +} + +type entry[K comparable, V any] struct { + key K + val V +} + +// Option is an option for FIFO cache. +type Option func(*options) + +type options struct { + capacity int +} + +func newOptions() *options { + return &options{ + capacity: 128, + } +} + +// WithCapacity is an option to set cache capacity. +func WithCapacity(cap int) Option { + return func(o *options) { + o.capacity = cap + } +} + +// NewCache creates a new non-thread safe FIFO cache whose capacity is the default size (128). +func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] { + o := newOptions() + for _, optFunc := range opts { + optFunc(o) + } + return &Cache[K, V]{ + items: make(map[K]*list.Element, o.capacity), + queue: list.New(), + capacity: o.capacity, + } +} + +// Set sets any item to the cache. replacing any existing item. +func (c *Cache[K, V]) Set(key K, val V) { + if c.queue.Len() == c.capacity { + e := c.dequeue() + delete(c.items, e.Value.(*entry[K, V]).key) + } + c.Delete(key) // delete old key if already exists specified key. + entry := &entry[K, V]{ + key: key, + val: val, + } + e := c.queue.PushBack(entry) + c.items[key] = e +} + +// Get gets an item from the cache. +// Returns the item or zero value, and a bool indicating whether the key was found. +func (c *Cache[K, V]) Get(k K) (val V, ok bool) { + got, found := c.items[k] + if !found { + return + } + return got.Value.(*entry[K, V]).val, true +} + +// Keys returns cache keys. +func (c *Cache[K, V]) Keys() []K { + keys := make([]K, 0, len(c.items)) + for e := c.queue.Front(); e != nil; e = e.Next() { + keys = append(keys, e.Value.(*entry[K, V]).key) + } + return keys +} + +// Delete deletes the item with provided key from the cache. +func (c *Cache[K, V]) Delete(key K) { + if e, ok := c.items[key]; ok { + c.queue.Remove(e) + delete(c.items, key) + } +} + +// Len returns the number of items in the cache. +func (c *Cache[K, V]) Len() int { + return c.queue.Len() +} + +func (c *Cache[K, V]) dequeue() *list.Element { + e := c.queue.Front() + c.queue.Remove(e) + return e +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/internal/policyutil/reference_count.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/internal/policyutil/reference_count.go new file mode 100644 index 000000000..ac024682a --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/internal/policyutil/reference_count.go @@ -0,0 +1,9 @@ +package policyutil + +// GetReferenceCount gets reference count from cache value. +func GetReferenceCount(v any) int { + if getter, ok := v.(interface{ GetReferenceCount() int }); ok { + return getter.GetReferenceCount() + } + return 1 +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/lfu/lfu.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/lfu/lfu.go new file mode 100644 index 000000000..d722f932a --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/lfu/lfu.go @@ -0,0 +1,103 @@ +package lfu + +import ( + "container/heap" +) + +// Cache is used a LFU (Least-frequently used) cache replacement policy. +// +// Counts how often an item is needed. Those that are used least often are discarded first. +// This works very similar to LRU except that instead of storing the value of how recently +// a block was accessed, we store the value of how many times it was accessed. So of course +// while running an access sequence we will replace a block which was used fewest times from our cache. +type Cache[K comparable, V any] struct { + cap int + queue *priorityQueue[K, V] + items map[K]*entry[K, V] +} + +// Option is an option for LFU cache. +type Option func(*options) + +type options struct { + capacity int +} + +func newOptions() *options { + return &options{ + capacity: 128, + } +} + +// WithCapacity is an option to set cache capacity. +func WithCapacity(cap int) Option { + return func(o *options) { + o.capacity = cap + } +} + +// NewCache creates a new non-thread safe LFU cache whose capacity is the default size (128). +func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] { + o := newOptions() + for _, optFunc := range opts { + optFunc(o) + } + return &Cache[K, V]{ + cap: o.capacity, + queue: newPriorityQueue[K, V](o.capacity), + items: make(map[K]*entry[K, V], o.capacity), + } +} + +// Get looks up a key's value from the cache. +func (c *Cache[K, V]) Get(key K) (zero V, _ bool) { + e, ok := c.items[key] + if !ok { + return + } + e.referenced() + heap.Fix(c.queue, e.index) + return e.val, true +} + +// Set sets a value to the cache with key. replacing any existing value. +// +// If value satisfies "interface{ GetReferenceCount() int }", the value of +// the GetReferenceCount() method is used to set the initial value of reference count. +func (c *Cache[K, V]) Set(key K, val V) { + if e, ok := c.items[key]; ok { + c.queue.update(e, val) + return + } + + if len(c.items) == c.cap { + evictedEntry := heap.Pop(c.queue).(*entry[K, V]) + delete(c.items, evictedEntry.key) + } + + e := newEntry(key, val) + heap.Push(c.queue, e) + c.items[key] = e +} + +// Keys returns the keys of the cache. the order is from oldest to newest. +func (c *Cache[K, V]) Keys() []K { + keys := make([]K, 0, len(c.items)) + for _, entry := range *c.queue { + keys = append(keys, entry.key) + } + return keys +} + +// Delete deletes the item with provided key from the cache. +func (c *Cache[K, V]) Delete(key K) { + if e, ok := c.items[key]; ok { + heap.Remove(c.queue, e.index) + delete(c.items, key) + } +} + +// Len returns the number of items in the cache. +func (c *Cache[K, V]) Len() int { + return c.queue.Len() +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/lfu/priority_queue.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/lfu/priority_queue.go new file mode 100644 index 000000000..575890c93 --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/lfu/priority_queue.go @@ -0,0 +1,82 @@ +package lfu + +import ( + "container/heap" + "time" + + "github.com/Code-Hex/go-generics-cache/policy/internal/policyutil" +) + +type entry[K comparable, V any] struct { + index int + key K + val V + referenceCount int + referencedAt time.Time +} + +func newEntry[K comparable, V any](key K, val V) *entry[K, V] { + return &entry[K, V]{ + index: 0, + key: key, + val: val, + referenceCount: policyutil.GetReferenceCount(val), + referencedAt: time.Now(), + } +} + +func (e *entry[K, V]) referenced() { + e.referenceCount++ + e.referencedAt = time.Now() +} + +type priorityQueue[K comparable, V any] []*entry[K, V] + +func newPriorityQueue[K comparable, V any](cap int) *priorityQueue[K, V] { + queue := make(priorityQueue[K, V], 0, cap) + return &queue +} + +// see example of priority queue: https://pkg.go.dev/container/heap +var _ heap.Interface = (*priorityQueue[struct{}, interface{}])(nil) + +func (q priorityQueue[K, V]) Len() int { return len(q) } + +func (q priorityQueue[K, V]) Less(i, j int) bool { + if q[i].referenceCount == q[j].referenceCount { + return q[i].referencedAt.Before(q[j].referencedAt) + } + return q[i].referenceCount < q[j].referenceCount +} + +func (q priorityQueue[K, V]) Swap(i, j int) { + q[i], q[j] = q[j], q[i] + q[i].index = i + q[j].index = j +} + +func (q *priorityQueue[K, V]) Push(x interface{}) { + entry := x.(*entry[K, V]) + entry.index = len(*q) + *q = append(*q, entry) +} + +func (q *priorityQueue[K, V]) Pop() interface{} { + old := *q + n := len(old) + entry := old[n-1] + old[n-1] = nil // avoid memory leak + entry.index = -1 // for safety + new := old[0 : n-1] + for i := 0; i < len(new); i++ { + new[i].index = i + } + *q = new + return entry +} + +func (q *priorityQueue[K, V]) update(e *entry[K, V], val V) { + e.val = val + e.referenced() + heap.Fix(q, e.index) +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/lru/lru.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/lru/lru.go new file mode 100644 index 000000000..d60b8d14f --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/lru/lru.go @@ -0,0 +1,120 @@ +package lru + +import ( + "container/list" +) + +// Cache is used a LRU (Least recently used) cache replacement policy. +// +// Discards the least recently used items first. This algorithm requires +// keeping track of what was used when, which is expensive if one wants +// to make sure the algorithm always discards the least recently used item. +type Cache[K comparable, V any] struct { + cap int + list *list.List + items map[K]*list.Element +} + +type entry[K comparable, V any] struct { + key K + val V +} + +// Option is an option for LRU cache. +type Option func(*options) + +type options struct { + capacity int +} + +func newOptions() *options { + return &options{ + capacity: 128, + } +} + +// WithCapacity is an option to set cache capacity. +func WithCapacity(cap int) Option { + return func(o *options) { + o.capacity = cap + } +} + +// NewCache creates a new non-thread safe LRU cache whose capacity is the default size (128). +func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] { + o := newOptions() + for _, optFunc := range opts { + optFunc(o) + } + return &Cache[K, V]{ + cap: o.capacity, + list: list.New(), + items: make(map[K]*list.Element, o.capacity), + } +} + +// Get looks up a key's value from the cache. +func (c *Cache[K, V]) Get(key K) (zero V, _ bool) { + e, ok := c.items[key] + if !ok { + return + } + // updates cache order + c.list.MoveToFront(e) + return e.Value.(*entry[K, V]).val, true +} + +// Set sets a value to the cache with key. replacing any existing value. +func (c *Cache[K, V]) Set(key K, val V) { + if e, ok := c.items[key]; ok { + // updates cache order + c.list.MoveToFront(e) + entry := e.Value.(*entry[K, V]) + entry.val = val + return + } + + newEntry := &entry[K, V]{ + key: key, + val: val, + } + e := c.list.PushFront(newEntry) + c.items[key] = e + + if c.list.Len() > c.cap { + c.deleteOldest() + } +} + +// Keys returns the keys of the cache. the order is from oldest to newest. +func (c *Cache[K, V]) Keys() []K { + keys := make([]K, 0, len(c.items)) + for ent := c.list.Back(); ent != nil; ent = ent.Prev() { + entry := ent.Value.(*entry[K, V]) + keys = append(keys, entry.key) + } + return keys +} + +// Len returns the number of items in the cache. +func (c *Cache[K, V]) Len() int { + return c.list.Len() +} + +// Delete deletes the item with provided key from the cache. +func (c *Cache[K, V]) Delete(key K) { + if e, ok := c.items[key]; ok { + c.delete(e) + } +} + +func (c *Cache[K, V]) deleteOldest() { + e := c.list.Back() + c.delete(e) +} + +func (c *Cache[K, V]) delete(e *list.Element) { + c.list.Remove(e) + entry := e.Value.(*entry[K, V]) + delete(c.items, entry.key) +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/mru/mru.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/mru/mru.go new file mode 100644 index 000000000..5ec511e3d --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/mru/mru.go @@ -0,0 +1,118 @@ +package mru + +import ( + "container/list" +) + +// Cache is used a MRU (Most recently used) cache replacement policy. +// +// In contrast to Least Recently Used (LRU), MRU discards the most recently used items first. +type Cache[K comparable, V any] struct { + cap int + list *list.List + items map[K]*list.Element +} + +type entry[K comparable, V any] struct { + key K + val V +} + +// Option is an option for MRU cache. +type Option func(*options) + +type options struct { + capacity int +} + +func newOptions() *options { + return &options{ + capacity: 128, + } +} + +// WithCapacity is an option to set cache capacity. +func WithCapacity(cap int) Option { + return func(o *options) { + o.capacity = cap + } +} + +// NewCache creates a new non-thread safe MRU cache whose capacity is the default size (128). +func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] { + o := newOptions() + for _, optFunc := range opts { + optFunc(o) + } + return &Cache[K, V]{ + cap: o.capacity, + list: list.New(), + items: make(map[K]*list.Element, o.capacity), + } +} + +// Get looks up a key's value from the cache. +func (c *Cache[K, V]) Get(key K) (zero V, _ bool) { + e, ok := c.items[key] + if !ok { + return + } + // updates cache order + c.list.MoveToBack(e) + return e.Value.(*entry[K, V]).val, true +} + +// Set sets a value to the cache with key. replacing any existing value. +func (c *Cache[K, V]) Set(key K, val V) { + if e, ok := c.items[key]; ok { + // updates cache order + c.list.MoveToBack(e) + entry := e.Value.(*entry[K, V]) + entry.val = val + return + } + + if c.list.Len() == c.cap { + c.deleteNewest() + } + + newEntry := &entry[K, V]{ + key: key, + val: val, + } + e := c.list.PushBack(newEntry) + c.items[key] = e +} + +// Keys returns the keys of the cache. the order is from recently used. +func (c *Cache[K, V]) Keys() []K { + keys := make([]K, 0, len(c.items)) + for ent := c.list.Back(); ent != nil; ent = ent.Prev() { + entry := ent.Value.(*entry[K, V]) + keys = append(keys, entry.key) + } + return keys +} + +// Len returns the number of items in the cache. +func (c *Cache[K, V]) Len() int { + return c.list.Len() +} + +// Delete deletes the item with provided key from the cache. +func (c *Cache[K, V]) Delete(key K) { + if e, ok := c.items[key]; ok { + c.delete(e) + } +} + +func (c *Cache[K, V]) deleteNewest() { + e := c.list.Front() + c.delete(e) +} + +func (c *Cache[K, V]) delete(e *list.Element) { + c.list.Remove(e) + entry := e.Value.(*entry[K, V]) + delete(c.items, entry.key) +} diff --git a/vendor/github.com/Code-Hex/go-generics-cache/policy/simple/simple.go b/vendor/github.com/Code-Hex/go-generics-cache/policy/simple/simple.go new file mode 100644 index 000000000..2ed4cdbc4 --- /dev/null +++ b/vendor/github.com/Code-Hex/go-generics-cache/policy/simple/simple.go @@ -0,0 +1,61 @@ +package simple + +import ( + "sort" + "time" +) + +// Cache is a simple cache has no clear priority for evict cache. +type Cache[K comparable, V any] struct { + items map[K]*entry[V] +} + +type entry[V any] struct { + val V + createdAt time.Time +} + +// NewCache creates a new non-thread safe cache. +func NewCache[K comparable, V any]() *Cache[K, V] { + return &Cache[K, V]{ + items: make(map[K]*entry[V], 0), + } +} + +// Set sets any item to the cache. replacing any existing item. +// The default item never expires. +func (c *Cache[K, V]) Set(k K, v V) { + c.items[k] = &entry[V]{ + val: v, + createdAt: time.Now(), + } +} + +// Get gets an item from the cache. +// Returns the item or zero value, and a bool indicating whether the key was found. +func (c *Cache[K, V]) Get(k K) (val V, ok bool) { + got, found := c.items[k] + if !found { + return + } + return got.val, true +} + +// Keys returns cache keys. the order is sorted by created. +func (c *Cache[K, _]) Keys() []K { + ret := make([]K, 0, len(c.items)) + for key := range c.items { + ret = append(ret, key) + } + sort.Slice(ret, func(i, j int) bool { + i1 := c.items[ret[i]] + i2 := c.items[ret[j]] + return i1.createdAt.Before(i2.createdAt) + }) + return ret +} + +// Delete deletes the item with provided key from the cache. +func (c *Cache[K, V]) Delete(key K) { + delete(c.items, key) +} diff --git a/vendor/github.com/Microsoft/go-winio/.golangci.yml b/vendor/github.com/Microsoft/go-winio/.golangci.yml index af403bb13..7b503d26a 100644 --- a/vendor/github.com/Microsoft/go-winio/.golangci.yml +++ b/vendor/github.com/Microsoft/go-winio/.golangci.yml @@ -8,12 +8,8 @@ linters: - containedctx # struct contains a context - dupl # duplicate code - errname # erorrs are named correctly - - goconst # strings that should be constants - - godot # comments end in a period - - misspell - nolintlint # "//nolint" directives are properly explained - revive # golint replacement - - stylecheck # golint replacement, less configurable than revive - unconvert # unnecessary conversions - wastedassign @@ -23,10 +19,7 @@ linters: - exhaustive # check exhaustiveness of enum switch statements - gofmt # files are gofmt'ed - gosec # security - - nestif # deeply nested ifs - nilerr # returns nil even with non-nil error - - prealloc # slices that can be pre-allocated - - structcheck # unused struct fields - unparam # unused function params issues: @@ -42,6 +35,18 @@ issues: text: "^line-length-limit: " source: "^//(go:generate|sys) " + #TODO: remove after upgrading to go1.18 + # ignore comment spacing for nolint and sys directives + - linters: + - revive + text: "^comment-spacings: no space between comment delimiter and comment text" + source: "//(cspell:|nolint:|sys |todo)" + + # not on go 1.18 yet, so no any + - linters: + - revive + text: "^use-any: since GO 1.18 'interface{}' can be replaced by 'any'" + # allow unjustified ignores of error checks in defer statements - linters: - nolintlint @@ -56,6 +61,8 @@ issues: linters-settings: + exhaustive: + default-signifies-exhaustive: true govet: enable-all: true disable: @@ -98,6 +105,8 @@ linters-settings: disabled: true - name: flag-parameter # excessive, and a common idiom we use disabled: true + - name: unhandled-error # warns over common fmt.Print* and io.Close; rely on errcheck instead + disabled: true # general config - name: line-length-limit arguments: @@ -138,7 +147,3 @@ linters-settings: - VPCI - WCOW - WIM - stylecheck: - checks: - - "all" - - "-ST1003" # use revive's var naming diff --git a/vendor/github.com/Microsoft/go-winio/hvsock.go b/vendor/github.com/Microsoft/go-winio/hvsock.go index 52f1c280f..c88191658 100644 --- a/vendor/github.com/Microsoft/go-winio/hvsock.go +++ b/vendor/github.com/Microsoft/go-winio/hvsock.go @@ -23,7 +23,7 @@ import ( const afHVSock = 34 // AF_HYPERV // Well known Service and VM IDs -//https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service#vmid-wildcards +// https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service#vmid-wildcards // HvsockGUIDWildcard is the wildcard VmId for accepting connections from all partitions. func HvsockGUIDWildcard() guid.GUID { // 00000000-0000-0000-0000-000000000000 @@ -31,7 +31,7 @@ func HvsockGUIDWildcard() guid.GUID { // 00000000-0000-0000-0000-000000000000 } // HvsockGUIDBroadcast is the wildcard VmId for broadcasting sends to all partitions. -func HvsockGUIDBroadcast() guid.GUID { //ffffffff-ffff-ffff-ffff-ffffffffffff +func HvsockGUIDBroadcast() guid.GUID { // ffffffff-ffff-ffff-ffff-ffffffffffff return guid.GUID{ Data1: 0xffffffff, Data2: 0xffff, @@ -246,7 +246,7 @@ func (l *HvsockListener) Accept() (_ net.Conn, err error) { var addrbuf [addrlen * 2]byte var bytes uint32 - err = syscall.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0 /*rxdatalen*/, addrlen, addrlen, &bytes, &c.o) + err = syscall.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0 /* rxdatalen */, addrlen, addrlen, &bytes, &c.o) if _, err = l.sock.asyncIO(c, nil, bytes, err); err != nil { return nil, l.opErr("accept", os.NewSyscallError("acceptex", err)) } diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/doc.go b/vendor/github.com/Microsoft/go-winio/internal/fs/doc.go new file mode 100644 index 000000000..1f6538817 --- /dev/null +++ b/vendor/github.com/Microsoft/go-winio/internal/fs/doc.go @@ -0,0 +1,2 @@ +// This package contains Win32 filesystem functionality. +package fs diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go b/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go new file mode 100644 index 000000000..509b3ec64 --- /dev/null +++ b/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go @@ -0,0 +1,202 @@ +//go:build windows + +package fs + +import ( + "golang.org/x/sys/windows" + + "github.com/Microsoft/go-winio/internal/stringbuffer" +) + +//go:generate go run github.com/Microsoft/go-winio/tools/mkwinsyscall -output zsyscall_windows.go fs.go + +// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew +//sys CreateFile(name string, access AccessMask, mode FileShareMode, sa *syscall.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) [failretval==windows.InvalidHandle] = CreateFileW + +const NullHandle windows.Handle = 0 + +// AccessMask defines standard, specific, and generic rights. +// +// Bitmask: +// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 +// +---------------+---------------+-------------------------------+ +// |G|G|G|G|Resvd|A| StandardRights| SpecificRights | +// |R|W|E|A| |S| | | +// +-+-------------+---------------+-------------------------------+ +// +// GR Generic Read +// GW Generic Write +// GE Generic Exectue +// GA Generic All +// Resvd Reserved +// AS Access Security System +// +// https://learn.microsoft.com/en-us/windows/win32/secauthz/access-mask +// +// https://learn.microsoft.com/en-us/windows/win32/secauthz/generic-access-rights +// +// https://learn.microsoft.com/en-us/windows/win32/fileio/file-access-rights-constants +type AccessMask = windows.ACCESS_MASK + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // Not actually any. + // + // For CreateFile: "query certain metadata such as file, directory, or device attributes without accessing that file or device" + // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew#parameters + FILE_ANY_ACCESS AccessMask = 0 + + // Specific Object Access + // from ntioapi.h + + FILE_READ_DATA AccessMask = (0x0001) // file & pipe + FILE_LIST_DIRECTORY AccessMask = (0x0001) // directory + + FILE_WRITE_DATA AccessMask = (0x0002) // file & pipe + FILE_ADD_FILE AccessMask = (0x0002) // directory + + FILE_APPEND_DATA AccessMask = (0x0004) // file + FILE_ADD_SUBDIRECTORY AccessMask = (0x0004) // directory + FILE_CREATE_PIPE_INSTANCE AccessMask = (0x0004) // named pipe + + FILE_READ_EA AccessMask = (0x0008) // file & directory + FILE_READ_PROPERTIES AccessMask = FILE_READ_EA + + FILE_WRITE_EA AccessMask = (0x0010) // file & directory + FILE_WRITE_PROPERTIES AccessMask = FILE_WRITE_EA + + FILE_EXECUTE AccessMask = (0x0020) // file + FILE_TRAVERSE AccessMask = (0x0020) // directory + + FILE_DELETE_CHILD AccessMask = (0x0040) // directory + + FILE_READ_ATTRIBUTES AccessMask = (0x0080) // all + + FILE_WRITE_ATTRIBUTES AccessMask = (0x0100) // all + + FILE_ALL_ACCESS AccessMask = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF) + FILE_GENERIC_READ AccessMask = (STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE) + FILE_GENERIC_WRITE AccessMask = (STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE) + FILE_GENERIC_EXECUTE AccessMask = (STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE) + + SPECIFIC_RIGHTS_ALL AccessMask = 0x0000FFFF + + // Standard Access + // from ntseapi.h + + DELETE AccessMask = 0x0001_0000 + READ_CONTROL AccessMask = 0x0002_0000 + WRITE_DAC AccessMask = 0x0004_0000 + WRITE_OWNER AccessMask = 0x0008_0000 + SYNCHRONIZE AccessMask = 0x0010_0000 + + STANDARD_RIGHTS_REQUIRED AccessMask = 0x000F_0000 + + STANDARD_RIGHTS_READ AccessMask = READ_CONTROL + STANDARD_RIGHTS_WRITE AccessMask = READ_CONTROL + STANDARD_RIGHTS_EXECUTE AccessMask = READ_CONTROL + + STANDARD_RIGHTS_ALL AccessMask = 0x001F_0000 +) + +type FileShareMode uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + FILE_SHARE_NONE FileShareMode = 0x00 + FILE_SHARE_READ FileShareMode = 0x01 + FILE_SHARE_WRITE FileShareMode = 0x02 + FILE_SHARE_DELETE FileShareMode = 0x04 + FILE_SHARE_VALID_FLAGS FileShareMode = 0x07 +) + +type FileCreationDisposition uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + // from winbase.h + + CREATE_NEW FileCreationDisposition = 0x01 + CREATE_ALWAYS FileCreationDisposition = 0x02 + OPEN_EXISTING FileCreationDisposition = 0x03 + OPEN_ALWAYS FileCreationDisposition = 0x04 + TRUNCATE_EXISTING FileCreationDisposition = 0x05 +) + +// CreateFile and co. take flags or attributes together as one parameter. +// Define alias until we can use generics to allow both + +// https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants +type FileFlagOrAttribute uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( // from winnt.h + FILE_FLAG_WRITE_THROUGH FileFlagOrAttribute = 0x8000_0000 + FILE_FLAG_OVERLAPPED FileFlagOrAttribute = 0x4000_0000 + FILE_FLAG_NO_BUFFERING FileFlagOrAttribute = 0x2000_0000 + FILE_FLAG_RANDOM_ACCESS FileFlagOrAttribute = 0x1000_0000 + FILE_FLAG_SEQUENTIAL_SCAN FileFlagOrAttribute = 0x0800_0000 + FILE_FLAG_DELETE_ON_CLOSE FileFlagOrAttribute = 0x0400_0000 + FILE_FLAG_BACKUP_SEMANTICS FileFlagOrAttribute = 0x0200_0000 + FILE_FLAG_POSIX_SEMANTICS FileFlagOrAttribute = 0x0100_0000 + FILE_FLAG_OPEN_REPARSE_POINT FileFlagOrAttribute = 0x0020_0000 + FILE_FLAG_OPEN_NO_RECALL FileFlagOrAttribute = 0x0010_0000 + FILE_FLAG_FIRST_PIPE_INSTANCE FileFlagOrAttribute = 0x0008_0000 +) + +type FileSQSFlag = FileFlagOrAttribute + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( // from winbase.h + SECURITY_ANONYMOUS FileSQSFlag = FileSQSFlag(SecurityAnonymous << 16) + SECURITY_IDENTIFICATION FileSQSFlag = FileSQSFlag(SecurityIdentification << 16) + SECURITY_IMPERSONATION FileSQSFlag = FileSQSFlag(SecurityImpersonation << 16) + SECURITY_DELEGATION FileSQSFlag = FileSQSFlag(SecurityDelegation << 16) + + SECURITY_SQOS_PRESENT FileSQSFlag = 0x00100000 + SECURITY_VALID_SQOS_FLAGS FileSQSFlag = 0x001F0000 +) + +// GetFinalPathNameByHandle flags +// +// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew#parameters +type GetFinalPathFlag uint32 + +//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. +const ( + GetFinalPathDefaultFlag GetFinalPathFlag = 0x0 + + FILE_NAME_NORMALIZED GetFinalPathFlag = 0x0 + FILE_NAME_OPENED GetFinalPathFlag = 0x8 + + VOLUME_NAME_DOS GetFinalPathFlag = 0x0 + VOLUME_NAME_GUID GetFinalPathFlag = 0x1 + VOLUME_NAME_NT GetFinalPathFlag = 0x2 + VOLUME_NAME_NONE GetFinalPathFlag = 0x4 +) + +// getFinalPathNameByHandle facilitates calling the Windows API GetFinalPathNameByHandle +// with the given handle and flags. It transparently takes care of creating a buffer of the +// correct size for the call. +// +// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew +func GetFinalPathNameByHandle(h windows.Handle, flags GetFinalPathFlag) (string, error) { + b := stringbuffer.NewWString() + //TODO: can loop infinitely if Win32 keeps returning the same (or a larger) n? + for { + n, err := windows.GetFinalPathNameByHandle(h, b.Pointer(), b.Cap(), uint32(flags)) + if err != nil { + return "", err + } + // If the buffer wasn't large enough, n will be the total size needed (including null terminator). + // Resize and try again. + if n > b.Cap() { + b.ResizeTo(n) + continue + } + // If the buffer is large enough, n will be the size not including the null terminator. + // Convert to a Go string and return. + return b.String(), nil + } +} diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/security.go b/vendor/github.com/Microsoft/go-winio/internal/fs/security.go new file mode 100644 index 000000000..81760ac67 --- /dev/null +++ b/vendor/github.com/Microsoft/go-winio/internal/fs/security.go @@ -0,0 +1,12 @@ +package fs + +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-security_impersonation_level +type SecurityImpersonationLevel int32 // C default enums underlying type is `int`, which is Go `int32` + +// Impersonation levels +const ( + SecurityAnonymous SecurityImpersonationLevel = 0 + SecurityIdentification SecurityImpersonationLevel = 1 + SecurityImpersonation SecurityImpersonationLevel = 2 + SecurityDelegation SecurityImpersonationLevel = 3 +) diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go new file mode 100644 index 000000000..e2f7bb24e --- /dev/null +++ b/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go @@ -0,0 +1,64 @@ +//go:build windows + +// Code generated by 'go generate' using "github.com/Microsoft/go-winio/tools/mkwinsyscall"; DO NOT EDIT. + +package fs + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +var _ unsafe.Pointer + +// Do the interface allocations only once for common +// Errno values. +const ( + errnoERROR_IO_PENDING = 997 +) + +var ( + errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + errERROR_EINVAL error = syscall.EINVAL +) + +// errnoErr returns common boxed Errno values, to prevent +// allocations at runtime. +func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return errERROR_EINVAL + case errnoERROR_IO_PENDING: + return errERROR_IO_PENDING + } + // TODO: add more here, after collecting data on the common + // error values see on Windows. (perhaps when running + // all.bat?) + return e +} + +var ( + modkernel32 = windows.NewLazySystemDLL("kernel32.dll") + + procCreateFileW = modkernel32.NewProc("CreateFileW") +) + +func CreateFile(name string, access AccessMask, mode FileShareMode, sa *syscall.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) { + var _p0 *uint16 + _p0, err = syscall.UTF16PtrFromString(name) + if err != nil { + return + } + return _CreateFile(_p0, access, mode, sa, createmode, attrs, templatefile) +} + +func _CreateFile(name *uint16, access AccessMask, mode FileShareMode, sa *syscall.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) { + r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) + handle = windows.Handle(r0) + if handle == windows.InvalidHandle { + err = errnoErr(e1) + } + return +} diff --git a/vendor/github.com/Microsoft/go-winio/internal/socket/socket.go b/vendor/github.com/Microsoft/go-winio/internal/socket/socket.go index 39e8c05f8..aeb7b7250 100644 --- a/vendor/github.com/Microsoft/go-winio/internal/socket/socket.go +++ b/vendor/github.com/Microsoft/go-winio/internal/socket/socket.go @@ -100,8 +100,8 @@ func (f *runtimeFunc) Load() error { (*byte)(unsafe.Pointer(&f.addr)), uint32(unsafe.Sizeof(f.addr)), &n, - nil, //overlapped - 0, //completionRoutine + nil, // overlapped + 0, // completionRoutine ) }) return f.err diff --git a/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go b/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go new file mode 100644 index 000000000..7ad505702 --- /dev/null +++ b/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go @@ -0,0 +1,132 @@ +package stringbuffer + +import ( + "sync" + "unicode/utf16" +) + +// TODO: worth exporting and using in mkwinsyscall? + +// Uint16BufferSize is the buffer size in the pool, chosen somewhat arbitrarily to accommodate +// large path strings: +// MAX_PATH (260) + size of volume GUID prefix (49) + null terminator = 310. +const MinWStringCap = 310 + +// use *[]uint16 since []uint16 creates an extra allocation where the slice header +// is copied to heap and then referenced via pointer in the interface header that sync.Pool +// stores. +var pathPool = sync.Pool{ // if go1.18+ adds Pool[T], use that to store []uint16 directly + New: func() interface{} { + b := make([]uint16, MinWStringCap) + return &b + }, +} + +func newBuffer() []uint16 { return *(pathPool.Get().(*[]uint16)) } + +// freeBuffer copies the slice header data, and puts a pointer to that in the pool. +// This avoids taking a pointer to the slice header in WString, which can be set to nil. +func freeBuffer(b []uint16) { pathPool.Put(&b) } + +// WString is a wide string buffer ([]uint16) meant for storing UTF-16 encoded strings +// for interacting with Win32 APIs. +// Sizes are specified as uint32 and not int. +// +// It is not thread safe. +type WString struct { + // type-def allows casting to []uint16 directly, use struct to prevent that and allow adding fields in the future. + + // raw buffer + b []uint16 +} + +// NewWString returns a [WString] allocated from a shared pool with an +// initial capacity of at least [MinWStringCap]. +// Since the buffer may have been previously used, its contents are not guaranteed to be empty. +// +// The buffer should be freed via [WString.Free] +func NewWString() *WString { + return &WString{ + b: newBuffer(), + } +} + +func (b *WString) Free() { + if b.empty() { + return + } + freeBuffer(b.b) + b.b = nil +} + +// ResizeTo grows the buffer to at least c and returns the new capacity, freeing the +// previous buffer back into pool. +func (b *WString) ResizeTo(c uint32) uint32 { + // allready sufficient (or n is 0) + if c <= b.Cap() { + return b.Cap() + } + + if c <= MinWStringCap { + c = MinWStringCap + } + // allocate at-least double buffer size, as is done in [bytes.Buffer] and other places + if c <= 2*b.Cap() { + c = 2 * b.Cap() + } + + b2 := make([]uint16, c) + if !b.empty() { + copy(b2, b.b) + freeBuffer(b.b) + } + b.b = b2 + return c +} + +// Buffer returns the underlying []uint16 buffer. +func (b *WString) Buffer() []uint16 { + if b.empty() { + return nil + } + return b.b +} + +// Pointer returns a pointer to the first uint16 in the buffer. +// If the [WString.Free] has already been called, the pointer will be nil. +func (b *WString) Pointer() *uint16 { + if b.empty() { + return nil + } + return &b.b[0] +} + +// String returns the returns the UTF-8 encoding of the UTF-16 string in the buffer. +// +// It assumes that the data is null-terminated. +func (b *WString) String() string { + // Using [windows.UTF16ToString] would require importing "golang.org/x/sys/windows" + // and would make this code Windows-only, which makes no sense. + // So copy UTF16ToString code into here. + // If other windows-specific code is added, switch to [windows.UTF16ToString] + + s := b.b + for i, v := range s { + if v == 0 { + s = s[:i] + break + } + } + return string(utf16.Decode(s)) +} + +// Cap returns the underlying buffer capacity. +func (b *WString) Cap() uint32 { + if b.empty() { + return 0 + } + return b.cap() +} + +func (b *WString) cap() uint32 { return uint32(cap(b.b)) } +func (b *WString) empty() bool { return b == nil || b.cap() == 0 } diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go index ca6e38fc0..25cc81103 100644 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ b/vendor/github.com/Microsoft/go-winio/pipe.go @@ -16,11 +16,12 @@ import ( "unsafe" "golang.org/x/sys/windows" + + "github.com/Microsoft/go-winio/internal/fs" ) //sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe //sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW -//sys createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW //sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo //sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW //sys localAlloc(uFlags uint32, length uint32) (ptr uintptr) = LocalAlloc @@ -163,19 +164,21 @@ func (s pipeAddress) String() string { } // tryDialPipe attempts to dial the pipe at `path` until `ctx` cancellation or timeout. -func tryDialPipe(ctx context.Context, path *string, access uint32) (syscall.Handle, error) { +func tryDialPipe(ctx context.Context, path *string, access fs.AccessMask) (syscall.Handle, error) { for { select { case <-ctx.Done(): return syscall.Handle(0), ctx.Err() default: - h, err := createFile(*path, + wh, err := fs.CreateFile(*path, access, - 0, - nil, - syscall.OPEN_EXISTING, - windows.FILE_FLAG_OVERLAPPED|windows.SECURITY_SQOS_PRESENT|windows.SECURITY_ANONYMOUS, - 0) + 0, // mode + nil, // security attributes + fs.OPEN_EXISTING, + fs.FILE_FLAG_OVERLAPPED|fs.SECURITY_SQOS_PRESENT|fs.SECURITY_ANONYMOUS, + 0, // template file handle + ) + h := syscall.Handle(wh) if err == nil { return h, nil } @@ -219,7 +222,7 @@ func DialPipeContext(ctx context.Context, path string) (net.Conn, error) { func DialPipeAccess(ctx context.Context, path string, access uint32) (net.Conn, error) { var err error var h syscall.Handle - h, err = tryDialPipe(ctx, &path, access) + h, err = tryDialPipe(ctx, &path, fs.AccessMask(access)) if err != nil { return nil, err } @@ -279,6 +282,7 @@ func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (sy } defer localFree(ntPath.Buffer) oa.ObjectName = &ntPath + oa.Attributes = windows.OBJ_CASE_INSENSITIVE // The security descriptor is only needed for the first pipe. if first { diff --git a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go index 83f45a135..469b16f63 100644 --- a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go +++ b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go @@ -63,7 +63,6 @@ var ( procBackupWrite = modkernel32.NewProc("BackupWrite") procCancelIoEx = modkernel32.NewProc("CancelIoEx") procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") - procCreateFileW = modkernel32.NewProc("CreateFileW") procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") @@ -305,24 +304,6 @@ func connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) { return } -func createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createFile(_p0, access, mode, sa, createmode, attrs, templatefile) -} - -func _createFile(name *uint16, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = errnoErr(e1) - } - return -} - func createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) { r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount), 0, 0) newport = syscall.Handle(r0) diff --git a/vendor/github.com/alecthomas/units/renovate.json5 b/vendor/github.com/alecthomas/units/renovate.json5 new file mode 100644 index 000000000..897864b85 --- /dev/null +++ b/vendor/github.com/alecthomas/units/renovate.json5 @@ -0,0 +1,11 @@ +{ + $schema: "https://docs.renovatebot.com/renovate-schema.json", + extends: [ + "config:recommended", + ":semanticCommits", + ":semanticCommitTypeAll(chore)", + ":semanticCommitScope(deps)", + "group:allNonMajor", + "schedule:earlyMondays", // Run once a week. + ], +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/auth/bearer/token.go b/vendor/github.com/aws/aws-sdk-go/aws/auth/bearer/token.go new file mode 100644 index 000000000..dd950a286 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/auth/bearer/token.go @@ -0,0 +1,50 @@ +package bearer + +import ( + "github.com/aws/aws-sdk-go/aws" + "time" +) + +// Token provides a type wrapping a bearer token and expiration metadata. +type Token struct { + Value string + + CanExpire bool + Expires time.Time +} + +// Expired returns if the token's Expires time is before or equal to the time +// provided. If CanExpire is false, Expired will always return false. +func (t Token) Expired(now time.Time) bool { + if !t.CanExpire { + return false + } + now = now.Round(0) + return now.Equal(t.Expires) || now.After(t.Expires) +} + +// TokenProvider provides interface for retrieving bearer tokens. +type TokenProvider interface { + RetrieveBearerToken(aws.Context) (Token, error) +} + +// TokenProviderFunc provides a helper utility to wrap a function as a type +// that implements the TokenProvider interface. +type TokenProviderFunc func(aws.Context) (Token, error) + +// RetrieveBearerToken calls the wrapped function, returning the Token or +// error. +func (fn TokenProviderFunc) RetrieveBearerToken(ctx aws.Context) (Token, error) { + return fn(ctx) +} + +// StaticTokenProvider provides a utility for wrapping a static bearer token +// value within an implementation of a token provider. +type StaticTokenProvider struct { + Token Token +} + +// RetrieveBearerToken returns the static token specified. +func (s StaticTokenProvider) RetrieveBearerToken(aws.Context) (Token, error) { + return s.Token, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/aws/aws-sdk-go/aws/config.go index 776e31b21..c483e0cb8 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/config.go @@ -442,6 +442,17 @@ func (c *Config) WithUseDualStack(enable bool) *Config { return c } +// WithUseFIPSEndpoint sets a config UseFIPSEndpoint value returning a Config +// pointer for chaining. +func (c *Config) WithUseFIPSEndpoint(enable bool) *Config { + if enable { + c.UseFIPSEndpoint = endpoints.FIPSEndpointStateEnabled + } else { + c.UseFIPSEndpoint = endpoints.FIPSEndpointStateDisabled + } + return c +} + // WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value // returning a Config pointer for chaining. func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config { diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/awsinternal.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/awsinternal.go new file mode 100644 index 000000000..140242dd1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/awsinternal.go @@ -0,0 +1,4 @@ +// DO NOT EDIT +package corehandlers + +const isAwsInternal = "" \ No newline at end of file diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go index ab69c7a6f..ac842c55d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go @@ -35,3 +35,13 @@ var AddHostExecEnvUserAgentHander = request.NamedHandler{ request.AddToUserAgent(r, execEnvUAKey+"/"+v) }, } + +var AddAwsInternal = request.NamedHandler{ + Name: "core.AddAwsInternal", + Fn: func(r *request.Request) { + if len(isAwsInternal) == 0 { + return + } + request.AddToUserAgent(r, isAwsInternal) + }, +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go index 785f30d8e..329f788a3 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go @@ -31,6 +31,8 @@ package endpointcreds import ( "encoding/json" + "fmt" + "strings" "time" "github.com/aws/aws-sdk-go/aws" @@ -69,7 +71,37 @@ type Provider struct { // Optional authorization token value if set will be used as the value of // the Authorization header of the endpoint credential request. + // + // When constructed from environment, the provider will use the value of + // AWS_CONTAINER_AUTHORIZATION_TOKEN environment variable as the token + // + // Will be overridden if AuthorizationTokenProvider is configured AuthorizationToken string + + // Optional auth provider func to dynamically load the auth token from a file + // everytime a credential is retrieved + // + // When constructed from environment, the provider will read and use the content + // of the file pointed to by AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE environment variable + // as the auth token everytime credentials are retrieved + // + // Will override AuthorizationToken if configured + AuthorizationTokenProvider AuthTokenProvider +} + +// AuthTokenProvider defines an interface to dynamically load a value to be passed +// for the Authorization header of a credentials request. +type AuthTokenProvider interface { + GetToken() (string, error) +} + +// TokenProviderFunc is a func type implementing AuthTokenProvider interface +// and enables customizing token provider behavior +type TokenProviderFunc func() (string, error) + +// GetToken func retrieves auth token according to TokenProviderFunc implementation +func (p TokenProviderFunc) GetToken() (string, error) { + return p() } // NewProviderClient returns a credentials Provider for retrieving AWS credentials @@ -164,7 +196,20 @@ func (p *Provider) getCredentials(ctx aws.Context) (*getCredentialsOutput, error req := p.Client.NewRequest(op, nil, out) req.SetContext(ctx) req.HTTPRequest.Header.Set("Accept", "application/json") - if authToken := p.AuthorizationToken; len(authToken) != 0 { + + authToken := p.AuthorizationToken + var err error + if p.AuthorizationTokenProvider != nil { + authToken, err = p.AuthorizationTokenProvider.GetToken() + if err != nil { + return nil, fmt.Errorf("get authorization token: %v", err) + } + } + + if strings.ContainsAny(authToken, "\r\n") { + return nil, fmt.Errorf("authorization token contains invalid newline sequence") + } + if len(authToken) != 0 { req.HTTPRequest.Header.Set("Authorization", authToken) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go index 6eda2a555..4138e725d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go @@ -4,13 +4,13 @@ import ( "crypto/sha1" "encoding/hex" "encoding/json" - "fmt" "io/ioutil" "path/filepath" "strings" "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/auth/bearer" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/credentials" @@ -55,6 +55,19 @@ type Provider struct { // The URL that points to the organization's AWS Single Sign-On (AWS SSO) user portal. StartURL string + + // The filepath the cached token will be retrieved from. If unset Provider will + // use the startURL to determine the filepath at. + // + // ~/.aws/sso/cache/.json + // + // If custom cached token filepath is used, the Provider's startUrl + // parameter will be ignored. + CachedTokenFilepath string + + // Used by the SSOCredentialProvider if a token configuration + // profile is used in the shared config + TokenProvider bearer.TokenProvider } // NewCredentials returns a new AWS Single Sign-On (AWS SSO) credential provider. The ConfigProvider is expected to be configured @@ -89,13 +102,31 @@ func (p *Provider) Retrieve() (credentials.Value, error) { // RetrieveWithContext retrieves temporary AWS credentials from the configured Amazon Single Sign-On (AWS SSO) user portal // by exchanging the accessToken present in ~/.aws/sso/cache. func (p *Provider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { - tokenFile, err := loadTokenFile(p.StartURL) - if err != nil { - return credentials.Value{}, err + var accessToken *string + if p.TokenProvider != nil { + token, err := p.TokenProvider.RetrieveBearerToken(ctx) + if err != nil { + return credentials.Value{}, err + } + accessToken = &token.Value + } else { + if p.CachedTokenFilepath == "" { + cachedTokenFilePath, err := getCachedFilePath(p.StartURL) + if err != nil { + return credentials.Value{}, err + } + p.CachedTokenFilepath = cachedTokenFilePath + } + + tokenFile, err := loadTokenFile(p.CachedTokenFilepath) + if err != nil { + return credentials.Value{}, err + } + accessToken = &tokenFile.AccessToken } output, err := p.Client.GetRoleCredentialsWithContext(ctx, &sso.GetRoleCredentialsInput{ - AccessToken: &tokenFile.AccessToken, + AccessToken: accessToken, AccountId: &p.AccountID, RoleName: &p.RoleName, }) @@ -114,32 +145,13 @@ func (p *Provider) RetrieveWithContext(ctx credentials.Context) (credentials.Val }, nil } -func getCacheFileName(url string) (string, error) { +func getCachedFilePath(startUrl string) (string, error) { hash := sha1.New() - _, err := hash.Write([]byte(url)) + _, err := hash.Write([]byte(startUrl)) if err != nil { return "", err } - return strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json", nil -} - -type rfc3339 time.Time - -func (r *rfc3339) UnmarshalJSON(bytes []byte) error { - var value string - - if err := json.Unmarshal(bytes, &value); err != nil { - return err - } - - parse, err := time.Parse(time.RFC3339, value) - if err != nil { - return fmt.Errorf("expected RFC3339 timestamp: %v", err) - } - - *r = rfc3339(parse) - - return nil + return filepath.Join(defaultCacheLocation(), strings.ToLower(hex.EncodeToString(hash.Sum(nil)))+".json"), nil } type token struct { @@ -153,13 +165,8 @@ func (t token) Expired() bool { return nowTime().Round(0).After(time.Time(t.ExpiresAt)) } -func loadTokenFile(startURL string) (t token, err error) { - key, err := getCacheFileName(startURL) - if err != nil { - return token{}, awserr.New(ErrCodeSSOProviderInvalidToken, invalidTokenMessage, err) - } - - fileBytes, err := ioutil.ReadFile(filepath.Join(defaultCacheLocation(), key)) +func loadTokenFile(cachedTokenPath string) (t token, err error) { + fileBytes, err := ioutil.ReadFile(cachedTokenPath) if err != nil { return token{}, awserr.New(ErrCodeSSOProviderInvalidToken, invalidTokenMessage, err) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/sso_cached_token.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/sso_cached_token.go new file mode 100644 index 000000000..f6fa88451 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/sso_cached_token.go @@ -0,0 +1,237 @@ +package ssocreds + +import ( + "crypto/sha1" + "encoding/hex" + "encoding/json" + "fmt" + "github.com/aws/aws-sdk-go/internal/shareddefaults" + "io/ioutil" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +var resolvedOsUserHomeDir = shareddefaults.UserHomeDir + +// StandardCachedTokenFilepath returns the filepath for the cached SSO token file, or +// error if unable get derive the path. Key that will be used to compute a SHA1 +// value that is hex encoded. +// +// Derives the filepath using the Key as: +// +// ~/.aws/sso/cache/.json +func StandardCachedTokenFilepath(key string) (string, error) { + homeDir := resolvedOsUserHomeDir() + if len(homeDir) == 0 { + return "", fmt.Errorf("unable to get USER's home directory for cached token") + } + hash := sha1.New() + if _, err := hash.Write([]byte(key)); err != nil { + return "", fmt.Errorf("unable to compute cached token filepath key SHA1 hash, %v", err) + } + + cacheFilename := strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json" + + return filepath.Join(homeDir, ".aws", "sso", "cache", cacheFilename), nil +} + +type tokenKnownFields struct { + AccessToken string `json:"accessToken,omitempty"` + ExpiresAt *rfc3339 `json:"expiresAt,omitempty"` + + RefreshToken string `json:"refreshToken,omitempty"` + ClientID string `json:"clientId,omitempty"` + ClientSecret string `json:"clientSecret,omitempty"` +} + +type cachedToken struct { + tokenKnownFields + UnknownFields map[string]interface{} `json:"-"` +} + +// MarshalJSON provides custom marshalling because the standard library Go marshaller ignores unknown/unspecified fields +// when marshalling from a struct: https://pkg.go.dev/encoding/json#Marshal +// This function adds some extra validation to the known fields and captures unknown fields. +func (t cachedToken) MarshalJSON() ([]byte, error) { + fields := map[string]interface{}{} + + setTokenFieldString(fields, "accessToken", t.AccessToken) + setTokenFieldRFC3339(fields, "expiresAt", t.ExpiresAt) + + setTokenFieldString(fields, "refreshToken", t.RefreshToken) + setTokenFieldString(fields, "clientId", t.ClientID) + setTokenFieldString(fields, "clientSecret", t.ClientSecret) + + for k, v := range t.UnknownFields { + if _, ok := fields[k]; ok { + return nil, fmt.Errorf("unknown token field %v, duplicates known field", k) + } + fields[k] = v + } + + return json.Marshal(fields) +} + +func setTokenFieldString(fields map[string]interface{}, key, value string) { + if value == "" { + return + } + fields[key] = value +} +func setTokenFieldRFC3339(fields map[string]interface{}, key string, value *rfc3339) { + if value == nil { + return + } + fields[key] = value +} + +// UnmarshalJSON provides custom unmarshalling because the standard library Go unmarshaller ignores unknown/unspecified +// fields when unmarshalling from a struct: https://pkg.go.dev/encoding/json#Unmarshal +// This function adds some extra validation to the known fields and captures unknown fields. +func (t *cachedToken) UnmarshalJSON(b []byte) error { + var fields map[string]interface{} + if err := json.Unmarshal(b, &fields); err != nil { + return nil + } + + t.UnknownFields = map[string]interface{}{} + + for k, v := range fields { + var err error + switch k { + case "accessToken": + err = getTokenFieldString(v, &t.AccessToken) + case "expiresAt": + err = getTokenFieldRFC3339(v, &t.ExpiresAt) + case "refreshToken": + err = getTokenFieldString(v, &t.RefreshToken) + case "clientId": + err = getTokenFieldString(v, &t.ClientID) + case "clientSecret": + err = getTokenFieldString(v, &t.ClientSecret) + default: + t.UnknownFields[k] = v + } + + if err != nil { + return fmt.Errorf("field %q, %v", k, err) + } + } + + return nil +} + +func getTokenFieldString(v interface{}, value *string) error { + var ok bool + *value, ok = v.(string) + if !ok { + return fmt.Errorf("expect value to be string, got %T", v) + } + return nil +} + +func getTokenFieldRFC3339(v interface{}, value **rfc3339) error { + var stringValue string + if err := getTokenFieldString(v, &stringValue); err != nil { + return err + } + + timeValue, err := parseRFC3339(stringValue) + if err != nil { + return err + } + + *value = &timeValue + return nil +} + +func loadCachedToken(filename string) (cachedToken, error) { + fileBytes, err := ioutil.ReadFile(filename) + if err != nil { + return cachedToken{}, fmt.Errorf("failed to read cached SSO token file, %v", err) + } + + var t cachedToken + if err := json.Unmarshal(fileBytes, &t); err != nil { + return cachedToken{}, fmt.Errorf("failed to parse cached SSO token file, %v", err) + } + + if len(t.AccessToken) == 0 || t.ExpiresAt == nil || time.Time(*t.ExpiresAt).IsZero() { + return cachedToken{}, fmt.Errorf( + "cached SSO token must contain accessToken and expiresAt fields") + } + + return t, nil +} + +func storeCachedToken(filename string, t cachedToken, fileMode os.FileMode) (err error) { + tmpFilename := filename + ".tmp-" + strconv.FormatInt(nowTime().UnixNano(), 10) + if err := writeCacheFile(tmpFilename, fileMode, t); err != nil { + return err + } + + if err := os.Rename(tmpFilename, filename); err != nil { + return fmt.Errorf("failed to replace old cached SSO token file, %v", err) + } + + return nil +} + +func writeCacheFile(filename string, fileMode os.FileMode, t cachedToken) (err error) { + var f *os.File + f, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, fileMode) + if err != nil { + return fmt.Errorf("failed to create cached SSO token file %v", err) + } + + defer func() { + closeErr := f.Close() + if err == nil && closeErr != nil { + err = fmt.Errorf("failed to close cached SSO token file, %v", closeErr) + } + }() + + encoder := json.NewEncoder(f) + + if err = encoder.Encode(t); err != nil { + return fmt.Errorf("failed to serialize cached SSO token, %v", err) + } + + return nil +} + +type rfc3339 time.Time + +// UnmarshalJSON decode rfc3339 from JSON format +func (r *rfc3339) UnmarshalJSON(bytes []byte) error { + var value string + var err error + + if err = json.Unmarshal(bytes, &value); err != nil { + return err + } + + *r, err = parseRFC3339(value) + return err +} + +func parseRFC3339(v string) (rfc3339, error) { + parsed, err := time.Parse(time.RFC3339, v) + if err != nil { + return rfc3339{}, fmt.Errorf("expected RFC3339 timestamp: %v", err) + } + + return rfc3339(parsed), nil +} + +// MarshalJSON encode rfc3339 to JSON format time +func (r *rfc3339) MarshalJSON() ([]byte, error) { + value := time.Time(*r).Format(time.RFC3339) + + // Use JSON unmarshal to unescape the quoted value making use of JSON's + // quoting rules. + return json.Marshal(value) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/token_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/token_provider.go new file mode 100644 index 000000000..3388b78b4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/token_provider.go @@ -0,0 +1,148 @@ +package ssocreds + +import ( + "fmt" + "os" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/auth/bearer" + "github.com/aws/aws-sdk-go/service/ssooidc" +) + +// CreateTokenAPIClient provides the interface for the SSOTokenProvider's API +// client for calling CreateToken operation to refresh the SSO token. +type CreateTokenAPIClient interface { + CreateToken(input *ssooidc.CreateTokenInput) (*ssooidc.CreateTokenOutput, error) +} + +// SSOTokenProviderOptions provides the options for configuring the +// SSOTokenProvider. +type SSOTokenProviderOptions struct { + // Client that can be overridden + Client CreateTokenAPIClient + + // The path the file containing the cached SSO token will be read from. + // Initialized the NewSSOTokenProvider's cachedTokenFilepath parameter. + CachedTokenFilepath string +} + +// SSOTokenProvider provides a utility for refreshing SSO AccessTokens for +// Bearer Authentication. The SSOTokenProvider can only be used to refresh +// already cached SSO Tokens. This utility cannot perform the initial SSO +// create token. +// +// The initial SSO create token should be preformed with the AWS CLI before the +// Go application using the SSOTokenProvider will need to retrieve the SSO +// token. If the AWS CLI has not created the token cache file, this provider +// will return an error when attempting to retrieve the cached token. +// +// This provider will attempt to refresh the cached SSO token periodically if +// needed when RetrieveBearerToken is called. +// +// A utility such as the AWS CLI must be used to initially create the SSO +// session and cached token file. +// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html +type SSOTokenProvider struct { + options SSOTokenProviderOptions +} + +// NewSSOTokenProvider returns an initialized SSOTokenProvider that will +// periodically refresh the SSO token cached stored in the cachedTokenFilepath. +// The cachedTokenFilepath file's content will be rewritten by the token +// provider when the token is refreshed. +// +// The client must be configured for the AWS region the SSO token was created for. +func NewSSOTokenProvider(client CreateTokenAPIClient, cachedTokenFilepath string, optFns ...func(o *SSOTokenProviderOptions)) *SSOTokenProvider { + options := SSOTokenProviderOptions{ + Client: client, + CachedTokenFilepath: cachedTokenFilepath, + } + for _, fn := range optFns { + fn(&options) + } + + provider := &SSOTokenProvider{ + options: options, + } + + return provider +} + +// RetrieveBearerToken returns the SSO token stored in the cachedTokenFilepath +// the SSOTokenProvider was created with. If the token has expired +// RetrieveBearerToken will attempt to refresh it. If the token cannot be +// refreshed or is not present an error will be returned. +// +// A utility such as the AWS CLI must be used to initially create the SSO +// session and cached token file. https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html +func (p *SSOTokenProvider) RetrieveBearerToken(ctx aws.Context) (bearer.Token, error) { + cachedToken, err := loadCachedToken(p.options.CachedTokenFilepath) + if err != nil { + return bearer.Token{}, err + } + + if cachedToken.ExpiresAt != nil && nowTime().After(time.Time(*cachedToken.ExpiresAt)) { + cachedToken, err = p.refreshToken(cachedToken) + if err != nil { + return bearer.Token{}, fmt.Errorf("refresh cached SSO token failed, %v", err) + } + } + + expiresAt := toTime((*time.Time)(cachedToken.ExpiresAt)) + return bearer.Token{ + Value: cachedToken.AccessToken, + CanExpire: !expiresAt.IsZero(), + Expires: expiresAt, + }, nil +} + +func (p *SSOTokenProvider) refreshToken(token cachedToken) (cachedToken, error) { + if token.ClientSecret == "" || token.ClientID == "" || token.RefreshToken == "" { + return cachedToken{}, fmt.Errorf("cached SSO token is expired, or not present, and cannot be refreshed") + } + + createResult, err := p.options.Client.CreateToken(&ssooidc.CreateTokenInput{ + ClientId: &token.ClientID, + ClientSecret: &token.ClientSecret, + RefreshToken: &token.RefreshToken, + GrantType: aws.String("refresh_token"), + }) + if err != nil { + return cachedToken{}, fmt.Errorf("unable to refresh SSO token, %v", err) + } + if createResult.ExpiresIn == nil { + return cachedToken{}, fmt.Errorf("missing required field ExpiresIn") + } + if createResult.AccessToken == nil { + return cachedToken{}, fmt.Errorf("missing required field AccessToken") + } + if createResult.RefreshToken == nil { + return cachedToken{}, fmt.Errorf("missing required field RefreshToken") + } + + expiresAt := nowTime().Add(time.Duration(*createResult.ExpiresIn) * time.Second) + + token.AccessToken = *createResult.AccessToken + token.ExpiresAt = (*rfc3339)(&expiresAt) + token.RefreshToken = *createResult.RefreshToken + + fileInfo, err := os.Stat(p.options.CachedTokenFilepath) + if err != nil { + return cachedToken{}, fmt.Errorf("failed to stat cached SSO token file %v", err) + } + + if err = storeCachedToken(p.options.CachedTokenFilepath, token, fileInfo.Mode()); err != nil { + return cachedToken{}, fmt.Errorf("unable to cache refreshed SSO token, %v", err) + } + + return token, nil +} + +func toTime(p *time.Time) (v time.Time) { + if p == nil { + return v + } + + return *p +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go index 260a37cbb..86db488de 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go @@ -9,7 +9,7 @@ to refresh the credentials will be synchronized. But, the SDK is unable to ensure synchronous usage of the AssumeRoleProvider if the value is shared between multiple Credentials, Sessions or service clients. -Assume Role +# Assume Role To assume an IAM role using STS with the SDK you can create a new Credentials with the SDKs's stscreds package. @@ -27,7 +27,7 @@ with the SDKs's stscreds package. // from assumed role. svc := s3.New(sess, &aws.Config{Credentials: creds}) -Assume Role with static MFA Token +# Assume Role with static MFA Token To assume an IAM role with a MFA token you can either specify a MFA token code directly or provide a function to prompt the user each time the credentials @@ -49,7 +49,7 @@ credentials. // from assumed role. svc := s3.New(sess, &aws.Config{Credentials: creds}) -Assume Role with MFA Token Provider +# Assume Role with MFA Token Provider To assume an IAM role with MFA for longer running tasks where the credentials may need to be refreshed setting the TokenProvider field of AssumeRoleProvider @@ -74,7 +74,6 @@ single Credentials with an AssumeRoleProvider can be shared safely. // Create service client value configured for credentials // from assumed role. svc := s3.New(sess, &aws.Config{Credentials: creds}) - */ package stscreds @@ -199,6 +198,10 @@ type AssumeRoleProvider struct { // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). SerialNumber *string + // The SourceIdentity which is used to identity a persistent identity through the whole session. + // For more details see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html + SourceIdentity *string + // The value provided by the MFA device, if the trust policy of the role being // assumed requires MFA (that is, if the policy includes a condition that tests // for MFA). If the role being assumed requires MFA and if the TokenCode value @@ -320,6 +323,7 @@ func (p *AssumeRoleProvider) RetrieveWithContext(ctx credentials.Context) (crede Tags: p.Tags, PolicyArns: p.PolicyArns, TransitiveTagKeys: p.TransitiveTagKeys, + SourceIdentity: p.SourceIdentity, } if p.Policy != nil { input.Policy = p.Policy diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go index 23bb639e0..1ba80b576 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go @@ -9,6 +9,7 @@ package defaults import ( "fmt" + "io/ioutil" "net" "net/http" "net/url" @@ -74,6 +75,7 @@ func Handlers() request.Handlers { handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) handlers.Validate.AfterEachFn = request.HandlerListStopOnError handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) + handlers.Build.PushBackNamed(corehandlers.AddAwsInternal) handlers.Build.PushBackNamed(corehandlers.AddHostExecEnvUserAgentHander) handlers.Build.AfterEachFn = request.HandlerListStopOnError handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) @@ -114,9 +116,31 @@ func CredProviders(cfg *aws.Config, handlers request.Handlers) []credentials.Pro const ( httpProviderAuthorizationEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" + httpProviderAuthFileEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE" httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" ) +// direct representation of the IPv4 address for the ECS container +// "169.254.170.2" +var ecsContainerIPv4 net.IP = []byte{ + 169, 254, 170, 2, +} + +// direct representation of the IPv4 address for the EKS container +// "169.254.170.23" +var eksContainerIPv4 net.IP = []byte{ + 169, 254, 170, 23, +} + +// direct representation of the IPv6 address for the EKS container +// "fd00:ec2::23" +var eksContainerIPv6 net.IP = []byte{ + 0xFD, 0, 0xE, 0xC2, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0x23, +} + // RemoteCredProvider returns a credentials provider for the default remote // endpoints such as EC2 or ECS Roles. func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { @@ -134,19 +158,22 @@ func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.P var lookupHostFn = net.LookupHost -func isLoopbackHost(host string) (bool, error) { - ip := net.ParseIP(host) - if ip != nil { - return ip.IsLoopback(), nil +// isAllowedHost allows host to be loopback or known ECS/EKS container IPs +// +// host can either be an IP address OR an unresolved hostname - resolution will +// be automatically performed in the latter case +func isAllowedHost(host string) (bool, error) { + if ip := net.ParseIP(host); ip != nil { + return isIPAllowed(ip), nil } - // Host is not an ip, perform lookup addrs, err := lookupHostFn(host) if err != nil { return false, err } + for _, addr := range addrs { - if !net.ParseIP(addr).IsLoopback() { + if ip := net.ParseIP(addr); ip == nil || !isIPAllowed(ip) { return false, nil } } @@ -154,6 +181,13 @@ func isLoopbackHost(host string) (bool, error) { return true, nil } +func isIPAllowed(ip net.IP) bool { + return ip.IsLoopback() || + ip.Equal(ecsContainerIPv4) || + ip.Equal(eksContainerIPv4) || + ip.Equal(eksContainerIPv6) +} + func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { var errMsg string @@ -164,10 +198,12 @@ func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) host := aws.URLHostname(parsed) if len(host) == 0 { errMsg = "unable to parse host from local HTTP cred provider URL" - } else if isLoopback, loopbackErr := isLoopbackHost(host); loopbackErr != nil { - errMsg = fmt.Sprintf("failed to resolve host %q, %v", host, loopbackErr) - } else if !isLoopback { - errMsg = fmt.Sprintf("invalid endpoint host, %q, only loopback hosts are allowed.", host) + } else if parsed.Scheme == "http" { + if isAllowedHost, allowHostErr := isAllowedHost(host); allowHostErr != nil { + errMsg = fmt.Sprintf("failed to resolve host %q, %v", host, allowHostErr) + } else if !isAllowedHost { + errMsg = fmt.Sprintf("invalid endpoint host, %q, only loopback/ecs/eks hosts are allowed.", host) + } } } @@ -189,6 +225,15 @@ func httpCredProvider(cfg aws.Config, handlers request.Handlers, u string) crede func(p *endpointcreds.Provider) { p.ExpiryWindow = 5 * time.Minute p.AuthorizationToken = os.Getenv(httpProviderAuthorizationEnvVar) + if authFilePath := os.Getenv(httpProviderAuthFileEnvVar); authFilePath != "" { + p.AuthorizationTokenProvider = endpointcreds.TokenProviderFunc(func() (string, error) { + if contents, err := ioutil.ReadFile(authFilePath); err != nil { + return "", fmt.Errorf("failed to read authorization token from %v: %v", authFilePath, err) + } else { + return string(contents), nil + } + }) + } }, ) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go index 604aeffde..f1f9ba4ec 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go @@ -2,6 +2,7 @@ package ec2metadata import ( "fmt" + "github.com/aws/aws-sdk-go/aws" "net/http" "sync/atomic" "time" @@ -65,7 +66,9 @@ func (t *tokenProvider) fetchTokenHandler(r *request.Request) { switch requestFailureError.StatusCode() { case http.StatusForbidden, http.StatusNotFound, http.StatusMethodNotAllowed: atomic.StoreUint32(&t.disabled, 1) - t.client.Config.Logger.Log(fmt.Sprintf("WARN: failed to get session token, falling back to IMDSv1: %v", requestFailureError)) + if t.client.Config.LogLevel.Matches(aws.LogDebugWithDeprecated) { + t.client.Config.Logger.Log(fmt.Sprintf("WARN: failed to get session token, falling back to IMDSv1: %v", requestFailureError)) + } case http.StatusBadRequest: r.Error = requestFailureError } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index debf74510..6bd644944 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -13,6 +13,8 @@ const ( AwsUsGovPartitionID = "aws-us-gov" // AWS GovCloud (US) partition. AwsIsoPartitionID = "aws-iso" // AWS ISO (US) partition. AwsIsoBPartitionID = "aws-iso-b" // AWS ISOB (US) partition. + AwsIsoEPartitionID = "aws-iso-e" // AWS ISOE (Europe) partition. + AwsIsoFPartitionID = "aws-iso-f" // AWS ISOF partition. ) // AWS Standard partition's regions. @@ -29,6 +31,7 @@ const ( ApSoutheast3RegionID = "ap-southeast-3" // Asia Pacific (Jakarta). ApSoutheast4RegionID = "ap-southeast-4" // Asia Pacific (Melbourne). CaCentral1RegionID = "ca-central-1" // Canada (Central). + CaWest1RegionID = "ca-west-1" // Canada West (Calgary). EuCentral1RegionID = "eu-central-1" // Europe (Frankfurt). EuCentral2RegionID = "eu-central-2" // Europe (Zurich). EuNorth1RegionID = "eu-north-1" // Europe (Stockholm). @@ -37,6 +40,7 @@ const ( EuWest1RegionID = "eu-west-1" // Europe (Ireland). EuWest2RegionID = "eu-west-2" // Europe (London). EuWest3RegionID = "eu-west-3" // Europe (Paris). + IlCentral1RegionID = "il-central-1" // Israel (Tel Aviv). MeCentral1RegionID = "me-central-1" // Middle East (UAE). MeSouth1RegionID = "me-south-1" // Middle East (Bahrain). SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). @@ -69,8 +73,14 @@ const ( UsIsobEast1RegionID = "us-isob-east-1" // US ISOB East (Ohio). ) +// AWS ISOE (Europe) partition's regions. +const () + +// AWS ISOF partition's regions. +const () + // DefaultResolver returns an Endpoint resolver that will be able -// to resolve endpoints for: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), and AWS ISOB (US). +// to resolve endpoints for: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), AWS ISOB (US), AWS ISOE (Europe), and AWS ISOF. // // Use DefaultPartitions() to get the list of the default partitions. func DefaultResolver() Resolver { @@ -78,7 +88,7 @@ func DefaultResolver() Resolver { } // DefaultPartitions returns a list of the partitions the SDK is bundled -// with. The available partitions are: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), and AWS ISOB (US). +// with. The available partitions are: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), AWS ISOB (US), AWS ISOE (Europe), and AWS ISOF. // // partitions := endpoints.DefaultPartitions // for _, p := range partitions { @@ -94,6 +104,8 @@ var defaultPartitions = partitions{ awsusgovPartition, awsisoPartition, awsisobPartition, + awsisoePartition, + awsisofPartition, } // AwsPartition returns the Resolver for AWS Standard. @@ -107,7 +119,7 @@ var awsPartition = partition{ DNSSuffix: "amazonaws.com", RegionRegex: regionRegex{ Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$") + reg, _ := regexp.Compile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$") return reg }(), }, @@ -179,6 +191,9 @@ var awsPartition = partition{ "ca-central-1": region{ Description: "Canada (Central)", }, + "ca-west-1": region{ + Description: "Canada West (Calgary)", + }, "eu-central-1": region{ Description: "Europe (Frankfurt)", }, @@ -203,6 +218,9 @@ var awsPartition = partition{ "eu-west-3": region{ Description: "Europe (Paris)", }, + "il-central-1": region{ + Description: "Israel (Tel Aviv)", + }, "me-central-1": region{ Description: "Middle East (UAE)", }, @@ -277,6 +295,9 @@ var awsPartition = partition{ }: endpoint{ Hostname: "access-analyzer-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -346,6 +367,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -460,6 +484,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "acm-fips.ca-west-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1-fips", + }: endpoint{ + Hostname: "acm-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -484,6 +526,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -685,6 +730,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -732,6 +780,13 @@ var awsPartition = partition{ }, }, }, + "agreement-marketplace": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + }, + }, "airflow": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -1017,6 +1072,21 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "api.detective-fips.ca-central-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-central-1-fips", + }: endpoint{ + Hostname: "api.detective-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -1035,6 +1105,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -1221,6 +1294,14 @@ var awsPartition = partition{ Region: "ca-central-1", }, }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{ + Hostname: "api.ecr.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + }, endpointKey{ Region: "dkr-us-east-1", }: endpoint{ @@ -1429,6 +1510,14 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "api.ecr.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, endpointKey{ Region: "me-central-1", }: endpoint{ @@ -1784,6 +1873,12 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -1793,12 +1888,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, @@ -1822,6 +1932,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, @@ -1867,9 +1980,15 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -1894,6 +2013,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -2074,6 +2196,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -2162,6 +2287,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "apigateway-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "apigateway-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -2195,6 +2329,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "apigateway-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -2231,6 +2374,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -2350,6 +2496,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -2374,6 +2523,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -2435,6 +2587,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -2459,6 +2614,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -2517,21 +2675,81 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "appflow-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "appflow-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "appflow-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "appflow-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "sa-east-1", }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "appflow-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "appflow-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "appflow-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "appflow-fips.us-west-2.amazonaws.com", + }, }, }, "application-autoscaling": service{ @@ -2577,6 +2795,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -2601,6 +2822,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -2644,6 +2868,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -2659,12 +2886,18 @@ var awsPartition = partition{ endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -2674,6 +2907,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -2861,6 +3097,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "appmesh.eu-west-3.api.aws", }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "appmesh.il-central-1.api.aws", + }, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -3006,6 +3251,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -3018,6 +3266,12 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -3196,6 +3450,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -3223,6 +3480,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -3256,6 +3516,12 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -3274,6 +3540,12 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, @@ -3317,12 +3589,21 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, @@ -3341,6 +3622,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -3356,6 +3640,9 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -3417,6 +3704,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena.ap-south-1.api.aws", }, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "athena.ap-south-2.api.aws", + }, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -3444,6 +3740,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena.ap-southeast-3.api.aws", }, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "athena.ap-southeast-4.api.aws", + }, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -3462,6 +3767,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena.eu-central-1.api.aws", }, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "athena.eu-central-2.api.aws", + }, endpointKey{ Region: "eu-north-1", }: endpoint{}, @@ -3480,6 +3794,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena.eu-south-1.api.aws", }, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "athena.eu-south-2.api.aws", + }, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -3543,6 +3866,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "athena.il-central-1.api.aws", + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "athena.me-central-1.api.aws", + }, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -3576,6 +3917,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-east-1.api.aws", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, @@ -3591,6 +3938,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-east-2.amazonaws.com", }, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-east-2.api.aws", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, @@ -3606,6 +3959,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-west-1.api.aws", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -3621,6 +3980,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-west-2.amazonaws.com", }, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-west-2.api.aws", + }, }, }, "auditmanager": service{ @@ -3706,6 +4071,21 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "autoscaling-fips.ca-central-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "autoscaling-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -3730,6 +4110,63 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "autoscaling-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "autoscaling-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "autoscaling-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "autoscaling-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "autoscaling-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "autoscaling-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -3742,15 +4179,39 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "autoscaling-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "autoscaling-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "autoscaling-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "autoscaling-fips.us-west-2.amazonaws.com", + }, }, }, "autoscaling-plans": service{ @@ -3860,6 +4321,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -3887,6 +4351,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -3979,15 +4446,84 @@ var awsPartition = partition{ }, "backupstorage": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -4033,9 +4569,15 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -4096,6 +4638,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -4143,6 +4688,137 @@ var awsPartition = partition{ }, }, }, + "bedrock": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "bedrock-ap-northeast-1", + }: endpoint{ + Hostname: "bedrock.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + endpointKey{ + Region: "bedrock-ap-southeast-1", + }: endpoint{ + Hostname: "bedrock.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + endpointKey{ + Region: "bedrock-eu-central-1", + }: endpoint{ + Hostname: "bedrock.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + endpointKey{ + Region: "bedrock-fips-us-east-1", + }: endpoint{ + Hostname: "bedrock-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "bedrock-fips-us-west-2", + }: endpoint{ + Hostname: "bedrock-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "bedrock-runtime-ap-northeast-1", + }: endpoint{ + Hostname: "bedrock-runtime.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + endpointKey{ + Region: "bedrock-runtime-ap-southeast-1", + }: endpoint{ + Hostname: "bedrock-runtime.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + endpointKey{ + Region: "bedrock-runtime-eu-central-1", + }: endpoint{ + Hostname: "bedrock-runtime.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + endpointKey{ + Region: "bedrock-runtime-fips-us-east-1", + }: endpoint{ + Hostname: "bedrock-runtime-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "bedrock-runtime-fips-us-west-2", + }: endpoint{ + Hostname: "bedrock-runtime-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "bedrock-runtime-us-east-1", + }: endpoint{ + Hostname: "bedrock-runtime.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "bedrock-runtime-us-west-2", + }: endpoint{ + Hostname: "bedrock-runtime.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "bedrock-us-east-1", + }: endpoint{ + Hostname: "bedrock.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "bedrock-us-west-2", + }: endpoint{ + Hostname: "bedrock.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "billingconductor": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -4445,6 +5121,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -4509,6 +5188,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "cloudcontrolapi-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "cloudcontrolapi-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -4542,6 +5230,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "cloudcontrolapi-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -4578,6 +5275,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -4694,6 +5394,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -4718,6 +5421,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -4850,6 +5556,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -4883,6 +5592,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -4978,6 +5690,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -5038,6 +5753,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -5230,6 +5948,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -5257,6 +5978,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -5428,6 +6152,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -5549,6 +6276,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -5573,6 +6303,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -5704,15 +6437,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -5734,6 +6479,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -5788,6 +6536,12 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -5901,6 +6655,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -5987,12 +6744,18 @@ var awsPartition = partition{ }, "cognito-identity": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -6002,6 +6765,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -6041,6 +6807,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "cognito-identity-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ @@ -6050,6 +6825,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -6077,6 +6855,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "cognito-identity-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -6090,12 +6874,18 @@ var awsPartition = partition{ }, "cognito-idp": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -6105,6 +6895,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -6162,6 +6955,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -6453,6 +7249,14 @@ var awsPartition = partition{ Region: "ap-south-1", }, }, + endpointKey{ + Region: "ap-south-2", + }: endpoint{ + Hostname: "compute-optimizer.ap-south-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-2", + }, + }, endpointKey{ Region: "ap-southeast-1", }: endpoint{ @@ -6469,6 +7273,22 @@ var awsPartition = partition{ Region: "ap-southeast-2", }, }, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{ + Hostname: "compute-optimizer.ap-southeast-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-3", + }, + }, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{ + Hostname: "compute-optimizer.ap-southeast-4.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-4", + }, + }, endpointKey{ Region: "ca-central-1", }: endpoint{ @@ -6485,6 +7305,14 @@ var awsPartition = partition{ Region: "eu-central-1", }, }, + endpointKey{ + Region: "eu-central-2", + }: endpoint{ + Hostname: "compute-optimizer.eu-central-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-2", + }, + }, endpointKey{ Region: "eu-north-1", }: endpoint{ @@ -6501,6 +7329,14 @@ var awsPartition = partition{ Region: "eu-south-1", }, }, + endpointKey{ + Region: "eu-south-2", + }: endpoint{ + Hostname: "compute-optimizer.eu-south-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-2", + }, + }, endpointKey{ Region: "eu-west-1", }: endpoint{ @@ -6525,6 +7361,22 @@ var awsPartition = partition{ Region: "eu-west-3", }, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "compute-optimizer.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{ + Hostname: "compute-optimizer.me-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "me-central-1", + }, + }, endpointKey{ Region: "me-south-1", }: endpoint{ @@ -6613,6 +7465,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -6673,6 +7528,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -6746,12 +7604,42 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "connect-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "connect-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "connect-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "connect-fips.us-west-2.amazonaws.com", + }, }, }, "connect-campaigns": service{ @@ -6762,6 +7650,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, @@ -6811,6 +7702,12 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, @@ -6833,21 +7730,39 @@ var awsPartition = partition{ }, "controltower": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -6869,9 +7784,18 @@ var awsPartition = partition{ endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -6881,6 +7805,15 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -6920,6 +7853,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "controltower-fips.us-west-1.amazonaws.com", + }, + endpointKey{ + Region: "us-west-1-fips", + }: endpoint{ + Hostname: "controltower-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -6940,6 +7891,18 @@ var awsPartition = partition{ }, }, }, + "cost-optimization-hub": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-east-1", + }: endpoint{ + Hostname: "cost-optimization-hub.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + }, + }, "cur": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -7464,6 +8427,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -7473,6 +8439,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "datasync-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "datasync-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -7506,6 +8481,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "datasync-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -7542,6 +8526,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -7589,6 +8576,190 @@ var awsPartition = partition{ }, }, }, + "datazone": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.aws", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.aws", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{ + Hostname: "datazone.af-south-1.api.aws", + }, + endpointKey{ + Region: "ap-east-1", + }: endpoint{ + Hostname: "datazone.ap-east-1.api.aws", + }, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{ + Hostname: "datazone.ap-northeast-1.api.aws", + }, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{ + Hostname: "datazone.ap-northeast-2.api.aws", + }, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{ + Hostname: "datazone.ap-northeast-3.api.aws", + }, + endpointKey{ + Region: "ap-south-1", + }: endpoint{ + Hostname: "datazone.ap-south-1.api.aws", + }, + endpointKey{ + Region: "ap-south-2", + }: endpoint{ + Hostname: "datazone.ap-south-2.api.aws", + }, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{ + Hostname: "datazone.ap-southeast-1.api.aws", + }, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{ + Hostname: "datazone.ap-southeast-2.api.aws", + }, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{ + Hostname: "datazone.ap-southeast-3.api.aws", + }, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{ + Hostname: "datazone.ap-southeast-4.api.aws", + }, + endpointKey{ + Region: "ca-central-1", + }: endpoint{ + Hostname: "datazone.ca-central-1.api.aws", + }, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "datazone-fips.ca-central-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{ + Hostname: "datazone.ca-west-1.api.aws", + }, + endpointKey{ + Region: "eu-central-1", + }: endpoint{ + Hostname: "datazone.eu-central-1.api.aws", + }, + endpointKey{ + Region: "eu-central-2", + }: endpoint{ + Hostname: "datazone.eu-central-2.api.aws", + }, + endpointKey{ + Region: "eu-north-1", + }: endpoint{ + Hostname: "datazone.eu-north-1.api.aws", + }, + endpointKey{ + Region: "eu-south-1", + }: endpoint{ + Hostname: "datazone.eu-south-1.api.aws", + }, + endpointKey{ + Region: "eu-south-2", + }: endpoint{ + Hostname: "datazone.eu-south-2.api.aws", + }, + endpointKey{ + Region: "eu-west-1", + }: endpoint{ + Hostname: "datazone.eu-west-1.api.aws", + }, + endpointKey{ + Region: "eu-west-2", + }: endpoint{ + Hostname: "datazone.eu-west-2.api.aws", + }, + endpointKey{ + Region: "eu-west-3", + }: endpoint{ + Hostname: "datazone.eu-west-3.api.aws", + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "datazone.il-central-1.api.aws", + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{ + Hostname: "datazone.me-central-1.api.aws", + }, + endpointKey{ + Region: "me-south-1", + }: endpoint{ + Hostname: "datazone.me-south-1.api.aws", + }, + endpointKey{ + Region: "sa-east-1", + }: endpoint{ + Hostname: "datazone.sa-east-1.api.aws", + }, + endpointKey{ + Region: "us-east-1", + }: endpoint{ + Hostname: "datazone.us-east-1.api.aws", + }, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "datazone-fips.us-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-east-2", + }: endpoint{ + Hostname: "datazone.us-east-2.api.aws", + }, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "datazone-fips.us-east-2.amazonaws.com", + }, + endpointKey{ + Region: "us-west-1", + }: endpoint{ + Hostname: "datazone.us-west-1.api.aws", + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{ + Hostname: "datazone.us-west-2.api.aws", + }, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "datazone-fips.us-west-2.amazonaws.com", + }, + }, + }, "dax": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -7664,6 +8835,12 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "devops-guru-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -7679,6 +8856,15 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "devops-guru-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -7697,6 +8883,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "devops-guru-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ @@ -7730,6 +8925,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "devops-guru-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -7779,6 +8980,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -7839,6 +9043,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -7931,6 +9138,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -7946,6 +9156,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -7970,6 +9183,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -8031,6 +9247,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "dms", }: endpoint{ @@ -8082,6 +9301,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -8301,6 +9523,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -8310,18 +9535,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -8331,6 +9565,48 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "drs-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "drs-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "drs-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "drs-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -8340,15 +9616,39 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "drs-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "drs-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "drs-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "drs-fips.us-west-2.amazonaws.com", + }, }, }, "ds": service{ @@ -8395,6 +9695,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "ds-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ds-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -8428,6 +9737,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "ds-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -8464,6 +9782,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -8569,6 +9890,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "dynamodb-fips.ca-west-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1-fips", + }: endpoint{ + Hostname: "dynamodb-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -8593,6 +9932,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "local", }: endpoint{ @@ -8729,6 +10071,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "ebs-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ebs-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -8762,6 +10113,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "ebs-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -8798,6 +10158,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -8975,6 +10338,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -9084,6 +10450,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -9144,6 +10513,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -9262,6 +10634,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -9322,6 +10697,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -9369,6 +10747,166 @@ var awsPartition = partition{ }, }, }, + "eks-auth": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.aws", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.aws", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{ + Hostname: "eks-auth.af-south-1.api.aws", + }, + endpointKey{ + Region: "ap-east-1", + }: endpoint{ + Hostname: "eks-auth.ap-east-1.api.aws", + }, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{ + Hostname: "eks-auth.ap-northeast-1.api.aws", + }, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{ + Hostname: "eks-auth.ap-northeast-2.api.aws", + }, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{ + Hostname: "eks-auth.ap-northeast-3.api.aws", + }, + endpointKey{ + Region: "ap-south-1", + }: endpoint{ + Hostname: "eks-auth.ap-south-1.api.aws", + }, + endpointKey{ + Region: "ap-south-2", + }: endpoint{ + Hostname: "eks-auth.ap-south-2.api.aws", + }, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{ + Hostname: "eks-auth.ap-southeast-1.api.aws", + }, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{ + Hostname: "eks-auth.ap-southeast-2.api.aws", + }, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{ + Hostname: "eks-auth.ap-southeast-3.api.aws", + }, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{ + Hostname: "eks-auth.ap-southeast-4.api.aws", + }, + endpointKey{ + Region: "ca-central-1", + }: endpoint{ + Hostname: "eks-auth.ca-central-1.api.aws", + }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{ + Hostname: "eks-auth.ca-west-1.api.aws", + }, + endpointKey{ + Region: "eu-central-1", + }: endpoint{ + Hostname: "eks-auth.eu-central-1.api.aws", + }, + endpointKey{ + Region: "eu-central-2", + }: endpoint{ + Hostname: "eks-auth.eu-central-2.api.aws", + }, + endpointKey{ + Region: "eu-north-1", + }: endpoint{ + Hostname: "eks-auth.eu-north-1.api.aws", + }, + endpointKey{ + Region: "eu-south-1", + }: endpoint{ + Hostname: "eks-auth.eu-south-1.api.aws", + }, + endpointKey{ + Region: "eu-south-2", + }: endpoint{ + Hostname: "eks-auth.eu-south-2.api.aws", + }, + endpointKey{ + Region: "eu-west-1", + }: endpoint{ + Hostname: "eks-auth.eu-west-1.api.aws", + }, + endpointKey{ + Region: "eu-west-2", + }: endpoint{ + Hostname: "eks-auth.eu-west-2.api.aws", + }, + endpointKey{ + Region: "eu-west-3", + }: endpoint{ + Hostname: "eks-auth.eu-west-3.api.aws", + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "eks-auth.il-central-1.api.aws", + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{ + Hostname: "eks-auth.me-central-1.api.aws", + }, + endpointKey{ + Region: "me-south-1", + }: endpoint{ + Hostname: "eks-auth.me-south-1.api.aws", + }, + endpointKey{ + Region: "sa-east-1", + }: endpoint{ + Hostname: "eks-auth.sa-east-1.api.aws", + }, + endpointKey{ + Region: "us-east-1", + }: endpoint{ + Hostname: "eks-auth.us-east-1.api.aws", + }, + endpointKey{ + Region: "us-east-2", + }: endpoint{ + Hostname: "eks-auth.us-east-2.api.aws", + }, + endpointKey{ + Region: "us-west-1", + }: endpoint{ + Hostname: "eks-auth.us-west-1.api.aws", + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{ + Hostname: "eks-auth.us-west-2.api.aws", + }, + }, + }, "elasticache": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -9407,6 +10945,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -9440,6 +10981,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -9609,6 +11153,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -10015,6 +11562,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-il-central-1", + }: endpoint{ + Hostname: "elasticfilesystem-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-me-central-1", }: endpoint{ @@ -10078,6 +11634,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "elasticfilesystem-fips.il-central-1.amazonaws.com", + }, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -10186,6 +11751,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -10246,6 +11814,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -10343,6 +11914,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "elasticmapreduce-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "elasticmapreduce-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{ @@ -10378,6 +11958,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "elasticmapreduce-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -10414,6 +12003,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -10438,6 +12030,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "elasticmapreduce.us-east-2.api.aws", + }, endpointKey{ Region: "us-east-2", Variant: fipsVariant, @@ -10521,6 +12119,12 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "email-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -10539,6 +12143,15 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "email-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -10548,6 +12161,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "email-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "email-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ @@ -10557,6 +12188,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -10575,9 +12209,21 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "email-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "email-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -10591,6 +12237,9 @@ var awsPartition = partition{ }, "emr-containers": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-east-1", }: endpoint{}, @@ -10600,6 +12249,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -10609,6 +12261,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -10624,6 +12279,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -10678,6 +12336,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -10724,12 +12385,21 @@ var awsPartition = partition{ }, "emr-serverless": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -10739,6 +12409,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -10754,6 +12427,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -10808,6 +12484,12 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -10868,63 +12550,192 @@ var awsPartition = partition{ endpointKey{ Region: "af-south-1", }: endpoint{}, + endpointKey{ + Region: "af-south-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.af-south-1.api.aws", + }, endpointKey{ Region: "ap-east-1", }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-east-1.api.aws", + }, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-northeast-1.api.aws", + }, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-northeast-2.api.aws", + }, endpointKey{ Region: "ap-northeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-northeast-3.api.aws", + }, endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-south-1.api.aws", + }, endpointKey{ Region: "ap-south-2", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-south-2.api.aws", + }, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-southeast-1.api.aws", + }, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-southeast-2.api.aws", + }, endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-southeast-3.api.aws", + }, endpointKey{ Region: "ap-southeast-4", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ap-southeast-4.api.aws", + }, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ca-central-1.api.aws", + }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.ca-west-1.api.aws", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-central-1.api.aws", + }, endpointKey{ Region: "eu-central-2", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-central-2.api.aws", + }, endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-north-1.api.aws", + }, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-south-1.api.aws", + }, endpointKey{ Region: "eu-south-2", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-south-2.api.aws", + }, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-west-1.api.aws", + }, endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-west-2.api.aws", + }, endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.eu-west-3.api.aws", + }, endpointKey{ Region: "fips", }: endpoint{ @@ -10934,18 +12745,51 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.il-central-1.api.aws", + }, endpointKey{ Region: "me-central-1", }: endpoint{}, + endpointKey{ + Region: "me-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.me-central-1.api.aws", + }, endpointKey{ Region: "me-south-1", }: endpoint{}, + endpointKey{ + Region: "me-south-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.me-south-1.api.aws", + }, endpointKey{ Region: "sa-east-1", }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.sa-east-1.api.aws", + }, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.us-east-1.api.aws", + }, endpointKey{ Region: "us-east-1", Variant: fipsVariant, @@ -10964,6 +12808,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.us-east-2.api.aws", + }, endpointKey{ Region: "us-east-2", Variant: fipsVariant, @@ -10982,6 +12832,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.us-west-1.api.aws", + }, endpointKey{ Region: "us-west-1", Variant: fipsVariant, @@ -11000,6 +12856,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.us-west-2.api.aws", + }, endpointKey{ Region: "us-west-2", Variant: fipsVariant, @@ -11055,6 +12917,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -11115,6 +12980,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -11213,12 +13081,27 @@ var awsPartition = partition{ }, "finspace": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, @@ -11287,6 +13170,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -11347,6 +13233,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -11473,6 +13362,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -11707,6 +13599,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -11978,6 +13873,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -12101,6 +13999,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -12305,16 +14206,6 @@ var awsPartition = partition{ }: endpoint{}, }, }, - "gamesparks": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, "geo": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -12528,6 +14419,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -12537,6 +14431,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -12600,6 +14497,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -12960,6 +14860,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -12987,6 +14890,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -13234,6 +15140,9 @@ var awsPartition = partition{ endpointKey{ Region: "af-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, @@ -13255,12 +15164,18 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, @@ -13276,6 +15191,15 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -13285,6 +15209,9 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -13514,6 +15441,9 @@ var awsPartition = partition{ }, "inspector2": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-east-1", }: endpoint{}, @@ -13523,6 +15453,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -13532,12 +15465,18 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, @@ -13553,6 +15492,42 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "inspector2-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "inspector2-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "inspector2-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "inspector2-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -13562,15 +15537,39 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "inspector2-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "inspector2-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "inspector2-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "inspector2-fips.us-west-2.amazonaws.com", + }, }, }, "internetmonitor": service{ @@ -13646,6 +15645,17 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.ca-central-1.api.aws", }, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "internetmonitor-fips.ca-central-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{ + Hostname: "internetmonitor.ca-west-1.api.aws", + }, endpointKey{ Region: "eu-central-1", }: endpoint{ @@ -13686,6 +15696,11 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.eu-west-3.api.aws", }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "internetmonitor.il-central-1.api.aws", + }, endpointKey{ Region: "me-central-1", }: endpoint{ @@ -13706,31 +15721,48 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.us-east-1.api.aws", }, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "internetmonitor-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{ Hostname: "internetmonitor.us-east-2.api.aws", }, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "internetmonitor-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{ Hostname: "internetmonitor.us-west-1.api.aws", }, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "internetmonitor-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{ Hostname: "internetmonitor.us-west-2.api.aws", }, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "internetmonitor-fips.us-west-2.amazonaws.com", + }, }, }, "iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - }, Endpoints: serviceEndpoints{ endpointKey{ Region: "ap-east-1", @@ -13778,45 +15810,35 @@ var awsPartition = partition{ Region: "fips-ca-central-1", }: endpoint{ Hostname: "iot-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ Hostname: "iot-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-east-2", }: endpoint{ Hostname: "iot-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-west-1", }: endpoint{ Hostname: "iot-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ Hostname: "iot-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ @@ -14455,18 +16477,203 @@ var awsPartition = partition{ }, "iottwinmaker": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "api-ap-northeast-1", + }: endpoint{ + Hostname: "api.iottwinmaker.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + endpointKey{ + Region: "api-ap-northeast-2", + }: endpoint{ + Hostname: "api.iottwinmaker.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + endpointKey{ + Region: "api-ap-south-1", + }: endpoint{ + Hostname: "api.iottwinmaker.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, + endpointKey{ + Region: "api-ap-southeast-1", + }: endpoint{ + Hostname: "api.iottwinmaker.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + endpointKey{ + Region: "api-ap-southeast-2", + }: endpoint{ + Hostname: "api.iottwinmaker.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + endpointKey{ + Region: "api-eu-central-1", + }: endpoint{ + Hostname: "api.iottwinmaker.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + endpointKey{ + Region: "api-eu-west-1", + }: endpoint{ + Hostname: "api.iottwinmaker.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + endpointKey{ + Region: "api-us-east-1", + }: endpoint{ + Hostname: "api.iottwinmaker.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "api-us-west-2", + }: endpoint{ + Hostname: "api.iottwinmaker.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "data-ap-northeast-1", + }: endpoint{ + Hostname: "data.iottwinmaker.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + endpointKey{ + Region: "data-ap-northeast-2", + }: endpoint{ + Hostname: "data.iottwinmaker.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + endpointKey{ + Region: "data-ap-south-1", + }: endpoint{ + Hostname: "data.iottwinmaker.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, + endpointKey{ + Region: "data-ap-southeast-1", + }: endpoint{ + Hostname: "data.iottwinmaker.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + endpointKey{ + Region: "data-ap-southeast-2", + }: endpoint{ + Hostname: "data.iottwinmaker.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + endpointKey{ + Region: "data-eu-central-1", + }: endpoint{ + Hostname: "data.iottwinmaker.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + endpointKey{ + Region: "data-eu-west-1", + }: endpoint{ + Hostname: "data.iottwinmaker.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + endpointKey{ + Region: "data-us-east-1", + }: endpoint{ + Hostname: "data.iottwinmaker.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "data-us-west-2", + }: endpoint{ + Hostname: "data.iottwinmaker.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "fips-api-us-east-1", + }: endpoint{ + Hostname: "api.iottwinmaker-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "fips-api-us-west-2", + }: endpoint{ + Hostname: "api.iottwinmaker-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "fips-data-us-east-1", + }: endpoint{ + Hostname: "data.iottwinmaker-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "fips-data-us-west-2", + }: endpoint{ + Hostname: "data.iottwinmaker-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -14656,9 +16863,18 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -14683,6 +16899,54 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "kafka-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "kafka-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "kafka-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "kafka-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "kafka-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -14695,15 +16959,39 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-west-2.amazonaws.com", + }, }, }, "kafkaconnect": service{ @@ -14778,6 +17066,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -14907,6 +17198,17 @@ var awsPartition = partition{ }: endpoint{ Hostname: "kendra-ranking.ca-central-1.api.aws", }, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kendra-ranking-fips.ca-central-1.api.aws", + }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{ + Hostname: "kendra-ranking.ca-west-1.api.aws", + }, endpointKey{ Region: "eu-central-2", }: endpoint{ @@ -14937,6 +17239,11 @@ var awsPartition = partition{ }: endpoint{ Hostname: "kendra-ranking.eu-west-3.api.aws", }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "kendra-ranking.il-central-1.api.aws", + }, endpointKey{ Region: "me-central-1", }: endpoint{ @@ -14957,11 +17264,23 @@ var awsPartition = partition{ }: endpoint{ Hostname: "kendra-ranking.us-east-1.api.aws", }, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kendra-ranking-fips.us-east-1.api.aws", + }, endpointKey{ Region: "us-east-2", }: endpoint{ Hostname: "kendra-ranking.us-east-2.api.aws", }, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kendra-ranking-fips.us-east-2.api.aws", + }, endpointKey{ Region: "us-west-1", }: endpoint{ @@ -14972,6 +17291,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "kendra-ranking.us-west-2.api.aws", }, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kendra-ranking-fips.us-west-2.api.aws", + }, }, }, "kinesis": service{ @@ -15012,6 +17337,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -15072,6 +17400,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -15151,6 +17482,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -15178,6 +17512,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -15480,6 +17817,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kms-fips.ca-west-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1-fips", + }: endpoint{ + Hostname: "kms-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -15624,6 +17979,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kms-fips.il-central-1.amazonaws.com", + }, + endpointKey{ + Region: "il-central-1-fips", + }: endpoint{ + Hostname: "kms-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -15772,6 +18145,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -15781,6 +18157,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -15844,6 +18223,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -16001,6 +18383,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "lambda.ca-central-1.api.aws", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "lambda.ca-west-1.api.aws", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -16109,6 +18500,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "lambda.il-central-1.api.aws", + }, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -16218,6 +18618,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -16227,18 +18630,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -16284,6 +18696,12 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -16366,6 +18784,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -16426,6 +18847,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -16493,24 +18917,39 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -16556,6 +18995,12 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -16684,6 +19129,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -16744,6 +19192,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -16861,162 +19312,134 @@ var awsPartition = partition{ }, }, "m2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{}, - }, - }, - "machinelearning": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "macie": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "macie-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "macie-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "macie-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "macie-fips.us-west-2.amazonaws.com", - }, - }, - }, - "macie2": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "af-south-1", }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{}, + }, + }, + "machinelearning": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + }, + }, + "macie2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, @@ -17092,6 +19515,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -17158,6 +19584,13 @@ var awsPartition = partition{ }: endpoint{}, }, }, + "managedblockchain-query": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + }, + }, "marketplacecommerceanalytics": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -17213,6 +19646,9 @@ var awsPartition = partition{ }, "mediaconnect": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-east-1", }: endpoint{}, @@ -17222,15 +19658,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -17246,6 +19694,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -17274,6 +19725,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -17283,6 +19737,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -17492,6 +19949,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -17501,6 +19961,12 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -17541,6 +20007,67 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, + "mediapackagev2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -17550,6 +20077,12 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -17615,12 +20148,33 @@ var awsPartition = partition{ }, "meetings-chime": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, @@ -17819,6 +20373,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -17862,6 +20419,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -17871,9 +20431,15 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -17895,6 +20461,12 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -17963,6 +20535,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -17972,18 +20547,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -18029,6 +20613,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -18286,6 +20873,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -18346,6 +20936,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -18413,6 +21006,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -18422,18 +21018,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -18479,6 +21084,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -18707,6 +21315,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -18716,6 +21327,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -18728,12 +21342,18 @@ var awsPartition = partition{ endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -18788,6 +21408,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -18847,6 +21470,24 @@ var awsPartition = partition{ Region: "us-west-2", }, }, + endpointKey{ + Region: "aws-global", + Variant: fipsVariant, + }: endpoint{ + Hostname: "networkmanager-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + endpointKey{ + Region: "fips-aws-global", + }: endpoint{ + Hostname: "networkmanager-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, }, }, "nimble": service{ @@ -18854,18 +21495,33 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -18909,6 +21565,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -18933,6 +21592,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -19046,6 +21708,14 @@ var awsPartition = partition{ Region: "eu-central-1", }, }, + endpointKey{ + Region: "eu-central-2", + }: endpoint{ + Hostname: "oidc.eu-central-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-2", + }, + }, endpointKey{ Region: "eu-north-1", }: endpoint{ @@ -19086,6 +21756,22 @@ var awsPartition = partition{ Region: "eu-west-3", }, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "oidc.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{ + Hostname: "oidc.me-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "me-central-1", + }, + }, endpointKey{ Region: "me-south-1", }: endpoint{ @@ -19188,6 +21874,14 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "omics.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, endpointKey{ Region: "us-east-1", }: endpoint{ @@ -19336,6 +22030,49 @@ var awsPartition = partition{ }, }, }, + "osis": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "outposts": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -19437,6 +22174,12 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -19620,6 +22363,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -19644,6 +22390,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -19826,6 +22575,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -19841,12 +22593,18 @@ var awsPartition = partition{ endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -20093,6 +22851,14 @@ var awsPartition = partition{ Region: "eu-central-1", }, }, + endpointKey{ + Region: "eu-central-2", + }: endpoint{ + Hostname: "portal.sso.eu-central-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-2", + }, + }, endpointKey{ Region: "eu-north-1", }: endpoint{ @@ -20133,6 +22899,22 @@ var awsPartition = partition{ Region: "eu-west-3", }, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "portal.sso.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{ + Hostname: "portal.sso.me-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "me-central-1", + }, + }, endpointKey{ Region: "me-south-1", }: endpoint{ @@ -20203,18 +22985,63 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "profile-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "profile-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "profile-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "profile-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "profile-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "profile-fips.us-west-2.amazonaws.com", + }, }, }, "projects.iot1click": service{ @@ -20279,6 +23106,166 @@ var awsPartition = partition{ }: endpoint{}, }, }, + "qbusiness": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.aws", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.aws", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{ + Hostname: "qbusiness.af-south-1.api.aws", + }, + endpointKey{ + Region: "ap-east-1", + }: endpoint{ + Hostname: "qbusiness.ap-east-1.api.aws", + }, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{ + Hostname: "qbusiness.ap-northeast-1.api.aws", + }, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{ + Hostname: "qbusiness.ap-northeast-2.api.aws", + }, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{ + Hostname: "qbusiness.ap-northeast-3.api.aws", + }, + endpointKey{ + Region: "ap-south-1", + }: endpoint{ + Hostname: "qbusiness.ap-south-1.api.aws", + }, + endpointKey{ + Region: "ap-south-2", + }: endpoint{ + Hostname: "qbusiness.ap-south-2.api.aws", + }, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{ + Hostname: "qbusiness.ap-southeast-1.api.aws", + }, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{ + Hostname: "qbusiness.ap-southeast-2.api.aws", + }, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{ + Hostname: "qbusiness.ap-southeast-3.api.aws", + }, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{ + Hostname: "qbusiness.ap-southeast-4.api.aws", + }, + endpointKey{ + Region: "ca-central-1", + }: endpoint{ + Hostname: "qbusiness.ca-central-1.api.aws", + }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{ + Hostname: "qbusiness.ca-west-1.api.aws", + }, + endpointKey{ + Region: "eu-central-1", + }: endpoint{ + Hostname: "qbusiness.eu-central-1.api.aws", + }, + endpointKey{ + Region: "eu-central-2", + }: endpoint{ + Hostname: "qbusiness.eu-central-2.api.aws", + }, + endpointKey{ + Region: "eu-north-1", + }: endpoint{ + Hostname: "qbusiness.eu-north-1.api.aws", + }, + endpointKey{ + Region: "eu-south-1", + }: endpoint{ + Hostname: "qbusiness.eu-south-1.api.aws", + }, + endpointKey{ + Region: "eu-south-2", + }: endpoint{ + Hostname: "qbusiness.eu-south-2.api.aws", + }, + endpointKey{ + Region: "eu-west-1", + }: endpoint{ + Hostname: "qbusiness.eu-west-1.api.aws", + }, + endpointKey{ + Region: "eu-west-2", + }: endpoint{ + Hostname: "qbusiness.eu-west-2.api.aws", + }, + endpointKey{ + Region: "eu-west-3", + }: endpoint{ + Hostname: "qbusiness.eu-west-3.api.aws", + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "qbusiness.il-central-1.api.aws", + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{ + Hostname: "qbusiness.me-central-1.api.aws", + }, + endpointKey{ + Region: "me-south-1", + }: endpoint{ + Hostname: "qbusiness.me-south-1.api.aws", + }, + endpointKey{ + Region: "sa-east-1", + }: endpoint{ + Hostname: "qbusiness.sa-east-1.api.aws", + }, + endpointKey{ + Region: "us-east-1", + }: endpoint{ + Hostname: "qbusiness.us-east-1.api.aws", + }, + endpointKey{ + Region: "us-east-2", + }: endpoint{ + Hostname: "qbusiness.us-east-2.api.aws", + }, + endpointKey{ + Region: "us-west-1", + }: endpoint{ + Hostname: "qbusiness.us-west-1.api.aws", + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{ + Hostname: "qbusiness.us-west-2.api.aws", + }, + }, + }, "qldb": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -20469,6 +23456,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "ram-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ram-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -20502,6 +23498,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "ram-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -20538,6 +23543,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -20629,6 +23637,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "rbin-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rbin-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -20662,6 +23679,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "rbin-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -20698,6 +23724,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -20798,6 +23827,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.ca-west-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1-fips", + }: endpoint{ + Hostname: "rds-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -20822,6 +23869,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -20837,6 +23887,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "rds-fips.ca-west-1", + }: endpoint{ + Hostname: "rds-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "rds-fips.us-east-1", }: endpoint{ @@ -20891,6 +23950,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "rds.ca-west-1", + }: endpoint{ + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds.ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "rds.us-east-1", }: endpoint{ @@ -21193,6 +24270,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "redshift-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "redshift-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -21226,6 +24312,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "redshift-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -21262,6 +24357,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -21402,6 +24500,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "rekognition-fips.ca-central-1", }: endpoint{ @@ -21733,6 +24834,11 @@ var awsPartition = partition{ }: endpoint{ Hostname: "resource-explorer-2.ap-southeast-2.api.aws", }, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{ + Hostname: "resource-explorer-2.ap-southeast-3.api.aws", + }, endpointKey{ Region: "ap-southeast-4", }: endpoint{ @@ -21758,6 +24864,11 @@ var awsPartition = partition{ }: endpoint{ Hostname: "resource-explorer-2.eu-north-1.api.aws", }, + endpointKey{ + Region: "eu-south-1", + }: endpoint{ + Hostname: "resource-explorer-2.eu-south-1.api.aws", + }, endpointKey{ Region: "eu-west-1", }: endpoint{ @@ -21773,6 +24884,21 @@ var awsPartition = partition{ }: endpoint{ Hostname: "resource-explorer-2.eu-west-3.api.aws", }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "resource-explorer-2.il-central-1.api.aws", + }, + endpointKey{ + Region: "me-central-1", + }: endpoint{ + Hostname: "resource-explorer-2.me-central-1.api.aws", + }, + endpointKey{ + Region: "me-south-1", + }: endpoint{ + Hostname: "resource-explorer-2.me-south-1.api.aws", + }, endpointKey{ Region: "sa-east-1", }: endpoint{ @@ -21838,6 +24964,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -21898,6 +25027,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -21990,6 +25122,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -21999,18 +25134,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -22020,6 +25164,48 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "rolesanywhere-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "rolesanywhere-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "rolesanywhere-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "rolesanywhere-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -22029,15 +25215,39 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rolesanywhere-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rolesanywhere-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rolesanywhere-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rolesanywhere-fips.us-west-2.amazonaws.com", + }, }, }, "route53": service{ @@ -22128,9 +25338,15 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -22155,6 +25371,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -22362,9 +25581,15 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -22389,6 +25614,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -22639,6 +25867,27 @@ var awsPartition = partition{ }: endpoint{ Hostname: "s3-fips.dualstack.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "s3.dualstack.ca-west-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "s3-fips.ca-west-1.amazonaws.com", + }, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "s3-fips.dualstack.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -22724,6 +25973,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "s3-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -22760,6 +26018,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "s3.dualstack.il-central-1.amazonaws.com", + }, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -23408,55 +26675,123 @@ var awsPartition = partition{ endpointKey{ Region: "af-south-1", }: endpoint{}, + endpointKey{ + Region: "af-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-east-1", }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-northeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ca-central-1", Variant: fipsVariant, }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "fips-ca-central-1", }: endpoint{ @@ -23487,40 +26822,87 @@ var awsPartition = partition{ Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, + endpointKey{ + Region: "me-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-1", Variant: fipsVariant, }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-2", Variant: fipsVariant, }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-1", Variant: fipsVariant, }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-2", Variant: fipsVariant, }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, }, }, "sagemaker-geospatial": service{ @@ -23631,6 +27013,9 @@ var awsPartition = partition{ }, "schemas": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-east-1", }: endpoint{}, @@ -23640,6 +27025,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -23649,15 +27037,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -23667,6 +27067,12 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -23725,157 +27131,288 @@ var awsPartition = partition{ endpointKey{ Region: "af-south-1", }: endpoint{}, + endpointKey{ + Region: "af-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-east-1", }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-northeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-south-2", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ap-southeast-4", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "ca-central-1", Variant: fipsVariant, + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, + endpointKey{ + Region: "ca-central-1-fips", }: endpoint{ - Hostname: "secretsmanager-fips.ca-central-1.amazonaws.com", + + Deprecated: boxedTrue, }, endpointKey{ - Region: "ca-central-1-fips", + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: dualStackVariant, + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, + endpointKey{ + Region: "ca-west-1-fips", }: endpoint{ - Hostname: "secretsmanager-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-central-2", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-south-2", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + Variant: dualStackVariant, + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, + endpointKey{ + Region: "me-central-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, + endpointKey{ + Region: "me-south-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-1", Variant: fipsVariant, - }: endpoint{ - Hostname: "secretsmanager-fips.us-east-1.amazonaws.com", - }, + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-1-fips", }: endpoint{ - Hostname: "secretsmanager-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-2", Variant: fipsVariant, - }: endpoint{ - Hostname: "secretsmanager-fips.us-east-2.amazonaws.com", - }, + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-east-2-fips", }: endpoint{ - Hostname: "secretsmanager-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-1", Variant: fipsVariant, - }: endpoint{ - Hostname: "secretsmanager-fips.us-west-1.amazonaws.com", - }, + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-1-fips", }: endpoint{ - Hostname: "secretsmanager-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-2", Variant: fipsVariant, - }: endpoint{ - Hostname: "secretsmanager-fips.us-west-2.amazonaws.com", - }, + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-west-2-fips", }: endpoint{ - Hostname: "secretsmanager-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, + Deprecated: boxedTrue, }, }, @@ -23912,9 +27449,15 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -23975,6 +27518,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -24027,33 +27573,114 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "securitylake-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "securitylake-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "securitylake-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "securitylake-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "sa-east-1", }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "securitylake-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "securitylake-fips.us-east-2.amazonaws.com", + }, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "securitylake-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "securitylake-fips.us-west-2.amazonaws.com", + }, }, }, "serverlessrepo": service{ @@ -24217,6 +27844,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -24320,6 +27950,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -24329,6 +27962,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -24338,15 +27974,24 @@ var awsPartition = partition{ }: endpoint{ Hostname: "servicecatalog-appregistry-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -24401,6 +28046,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -24457,7 +28105,7 @@ var awsPartition = partition{ Region: "af-south-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.af-south-1.amazonaws.com", + Hostname: "servicediscovery.af-south-1.api.aws", }, endpointKey{ Region: "ap-east-1", @@ -24466,7 +28114,7 @@ var awsPartition = partition{ Region: "ap-east-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-east-1.amazonaws.com", + Hostname: "servicediscovery.ap-east-1.api.aws", }, endpointKey{ Region: "ap-northeast-1", @@ -24475,7 +28123,7 @@ var awsPartition = partition{ Region: "ap-northeast-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-northeast-1.amazonaws.com", + Hostname: "servicediscovery.ap-northeast-1.api.aws", }, endpointKey{ Region: "ap-northeast-2", @@ -24484,7 +28132,7 @@ var awsPartition = partition{ Region: "ap-northeast-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-northeast-2.amazonaws.com", + Hostname: "servicediscovery.ap-northeast-2.api.aws", }, endpointKey{ Region: "ap-northeast-3", @@ -24493,7 +28141,7 @@ var awsPartition = partition{ Region: "ap-northeast-3", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-northeast-3.amazonaws.com", + Hostname: "servicediscovery.ap-northeast-3.api.aws", }, endpointKey{ Region: "ap-south-1", @@ -24502,7 +28150,7 @@ var awsPartition = partition{ Region: "ap-south-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-south-1.amazonaws.com", + Hostname: "servicediscovery.ap-south-1.api.aws", }, endpointKey{ Region: "ap-south-2", @@ -24511,7 +28159,7 @@ var awsPartition = partition{ Region: "ap-south-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-south-2.amazonaws.com", + Hostname: "servicediscovery.ap-south-2.api.aws", }, endpointKey{ Region: "ap-southeast-1", @@ -24520,7 +28168,7 @@ var awsPartition = partition{ Region: "ap-southeast-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-southeast-1.amazonaws.com", + Hostname: "servicediscovery.ap-southeast-1.api.aws", }, endpointKey{ Region: "ap-southeast-2", @@ -24529,7 +28177,7 @@ var awsPartition = partition{ Region: "ap-southeast-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-southeast-2.amazonaws.com", + Hostname: "servicediscovery.ap-southeast-2.api.aws", }, endpointKey{ Region: "ap-southeast-3", @@ -24538,7 +28186,7 @@ var awsPartition = partition{ Region: "ap-southeast-3", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-southeast-3.amazonaws.com", + Hostname: "servicediscovery.ap-southeast-3.api.aws", }, endpointKey{ Region: "ap-southeast-4", @@ -24547,7 +28195,7 @@ var awsPartition = partition{ Region: "ap-southeast-4", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ap-southeast-4.amazonaws.com", + Hostname: "servicediscovery.ap-southeast-4.api.aws", }, endpointKey{ Region: "ca-central-1", @@ -24556,7 +28204,7 @@ var awsPartition = partition{ Region: "ca-central-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.ca-central-1.amazonaws.com", + Hostname: "servicediscovery.ca-central-1.api.aws", }, endpointKey{ Region: "ca-central-1", @@ -24564,6 +28212,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "servicediscovery-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery-fips.ca-central-1.api.aws", + }, endpointKey{ Region: "ca-central-1-fips", }: endpoint{ @@ -24580,7 +28234,7 @@ var awsPartition = partition{ Region: "eu-central-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-central-1.amazonaws.com", + Hostname: "servicediscovery.eu-central-1.api.aws", }, endpointKey{ Region: "eu-central-2", @@ -24589,7 +28243,7 @@ var awsPartition = partition{ Region: "eu-central-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-central-2.amazonaws.com", + Hostname: "servicediscovery.eu-central-2.api.aws", }, endpointKey{ Region: "eu-north-1", @@ -24598,7 +28252,7 @@ var awsPartition = partition{ Region: "eu-north-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-north-1.amazonaws.com", + Hostname: "servicediscovery.eu-north-1.api.aws", }, endpointKey{ Region: "eu-south-1", @@ -24607,7 +28261,7 @@ var awsPartition = partition{ Region: "eu-south-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-south-1.amazonaws.com", + Hostname: "servicediscovery.eu-south-1.api.aws", }, endpointKey{ Region: "eu-south-2", @@ -24616,7 +28270,7 @@ var awsPartition = partition{ Region: "eu-south-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-south-2.amazonaws.com", + Hostname: "servicediscovery.eu-south-2.api.aws", }, endpointKey{ Region: "eu-west-1", @@ -24625,7 +28279,7 @@ var awsPartition = partition{ Region: "eu-west-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-west-1.amazonaws.com", + Hostname: "servicediscovery.eu-west-1.api.aws", }, endpointKey{ Region: "eu-west-2", @@ -24634,7 +28288,7 @@ var awsPartition = partition{ Region: "eu-west-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-west-2.amazonaws.com", + Hostname: "servicediscovery.eu-west-2.api.aws", }, endpointKey{ Region: "eu-west-3", @@ -24643,7 +28297,16 @@ var awsPartition = partition{ Region: "eu-west-3", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.eu-west-3.amazonaws.com", + Hostname: "servicediscovery.eu-west-3.api.aws", + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "il-central-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery.il-central-1.api.aws", }, endpointKey{ Region: "me-central-1", @@ -24652,7 +28315,7 @@ var awsPartition = partition{ Region: "me-central-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.me-central-1.amazonaws.com", + Hostname: "servicediscovery.me-central-1.api.aws", }, endpointKey{ Region: "me-south-1", @@ -24661,7 +28324,7 @@ var awsPartition = partition{ Region: "me-south-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.me-south-1.amazonaws.com", + Hostname: "servicediscovery.me-south-1.api.aws", }, endpointKey{ Region: "sa-east-1", @@ -24670,34 +28333,7 @@ var awsPartition = partition{ Region: "sa-east-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.sa-east-1.amazonaws.com", - }, - endpointKey{ - Region: "servicediscovery", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "servicediscovery", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "servicediscovery-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, + Hostname: "servicediscovery.sa-east-1.api.aws", }, endpointKey{ Region: "us-east-1", @@ -24706,7 +28342,7 @@ var awsPartition = partition{ Region: "us-east-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.us-east-1.amazonaws.com", + Hostname: "servicediscovery.us-east-1.api.aws", }, endpointKey{ Region: "us-east-1", @@ -24714,6 +28350,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "servicediscovery-fips.us-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery-fips.us-east-1.api.aws", + }, endpointKey{ Region: "us-east-1-fips", }: endpoint{ @@ -24730,7 +28372,7 @@ var awsPartition = partition{ Region: "us-east-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.us-east-2.amazonaws.com", + Hostname: "servicediscovery.us-east-2.api.aws", }, endpointKey{ Region: "us-east-2", @@ -24738,6 +28380,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "servicediscovery-fips.us-east-2.amazonaws.com", }, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery-fips.us-east-2.api.aws", + }, endpointKey{ Region: "us-east-2-fips", }: endpoint{ @@ -24754,7 +28402,7 @@ var awsPartition = partition{ Region: "us-west-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.us-west-1.amazonaws.com", + Hostname: "servicediscovery.us-west-1.api.aws", }, endpointKey{ Region: "us-west-1", @@ -24762,6 +28410,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "servicediscovery-fips.us-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery-fips.us-west-1.api.aws", + }, endpointKey{ Region: "us-west-1-fips", }: endpoint{ @@ -24778,7 +28432,7 @@ var awsPartition = partition{ Region: "us-west-2", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.us-west-2.amazonaws.com", + Hostname: "servicediscovery.us-west-2.api.aws", }, endpointKey{ Region: "us-west-2", @@ -24786,6 +28440,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "servicediscovery-fips.us-west-2.amazonaws.com", }, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery-fips.us-west-2.api.aws", + }, endpointKey{ Region: "us-west-2-fips", }: endpoint{ @@ -24840,6 +28500,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -24864,6 +28527,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -25007,35 +28673,7 @@ var awsPartition = partition{ }, }, }, - "simspaceweaver": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "sms": service{ + "signer": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "af-south-1", @@ -25082,7 +28720,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-east-1", }: endpoint{ - Hostname: "sms-fips.us-east-1.amazonaws.com", + Hostname: "signer-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, @@ -25091,7 +28729,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-east-2", }: endpoint{ - Hostname: "sms-fips.us-east-2.amazonaws.com", + Hostname: "signer-fips.us-east-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-2", }, @@ -25100,7 +28738,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-west-1", }: endpoint{ - Hostname: "sms-fips.us-west-1.amazonaws.com", + Hostname: "signer-fips.us-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-1", }, @@ -25109,12 +28747,44 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-west-2", }: endpoint{ - Hostname: "sms-fips.us-west-2.amazonaws.com", + Hostname: "signer-fips.us-west-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-2", }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-verification-us-east-1", + }: endpoint{ + Hostname: "verification.signer-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "fips-verification-us-east-2", + }: endpoint{ + Hostname: "verification.signer-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + endpointKey{ + Region: "fips-verification-us-west-1", + }: endpoint{ + Hostname: "verification.signer-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + endpointKey{ + Region: "fips-verification-us-west-2", + }: endpoint{ + Hostname: "verification.signer-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -25128,7 +28798,7 @@ var awsPartition = partition{ Region: "us-east-1", Variant: fipsVariant, }: endpoint{ - Hostname: "sms-fips.us-east-1.amazonaws.com", + Hostname: "signer-fips.us-east-1.amazonaws.com", }, endpointKey{ Region: "us-east-2", @@ -25137,7 +28807,7 @@ var awsPartition = partition{ Region: "us-east-2", Variant: fipsVariant, }: endpoint{ - Hostname: "sms-fips.us-east-2.amazonaws.com", + Hostname: "signer-fips.us-east-2.amazonaws.com", }, endpointKey{ Region: "us-west-1", @@ -25146,7 +28816,217 @@ var awsPartition = partition{ Region: "us-west-1", Variant: fipsVariant, }: endpoint{ - Hostname: "sms-fips.us-west-1.amazonaws.com", + Hostname: "signer-fips.us-west-1.amazonaws.com", + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "signer-fips.us-west-2.amazonaws.com", + }, + endpointKey{ + Region: "verification-af-south-1", + }: endpoint{ + Hostname: "verification.signer.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, + endpointKey{ + Region: "verification-ap-east-1", + }: endpoint{ + Hostname: "verification.signer.ap-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-east-1", + }, + }, + endpointKey{ + Region: "verification-ap-northeast-1", + }: endpoint{ + Hostname: "verification.signer.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + endpointKey{ + Region: "verification-ap-northeast-2", + }: endpoint{ + Hostname: "verification.signer.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + endpointKey{ + Region: "verification-ap-south-1", + }: endpoint{ + Hostname: "verification.signer.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, + endpointKey{ + Region: "verification-ap-southeast-1", + }: endpoint{ + Hostname: "verification.signer.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + endpointKey{ + Region: "verification-ap-southeast-2", + }: endpoint{ + Hostname: "verification.signer.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + endpointKey{ + Region: "verification-ca-central-1", + }: endpoint{ + Hostname: "verification.signer.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + endpointKey{ + Region: "verification-eu-central-1", + }: endpoint{ + Hostname: "verification.signer.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + endpointKey{ + Region: "verification-eu-north-1", + }: endpoint{ + Hostname: "verification.signer.eu-north-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + }, + endpointKey{ + Region: "verification-eu-south-1", + }: endpoint{ + Hostname: "verification.signer.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, + endpointKey{ + Region: "verification-eu-west-1", + }: endpoint{ + Hostname: "verification.signer.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + endpointKey{ + Region: "verification-eu-west-2", + }: endpoint{ + Hostname: "verification.signer.eu-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-2", + }, + }, + endpointKey{ + Region: "verification-eu-west-3", + }: endpoint{ + Hostname: "verification.signer.eu-west-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-3", + }, + }, + endpointKey{ + Region: "verification-me-south-1", + }: endpoint{ + Hostname: "verification.signer.me-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "me-south-1", + }, + }, + endpointKey{ + Region: "verification-sa-east-1", + }: endpoint{ + Hostname: "verification.signer.sa-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + }, + endpointKey{ + Region: "verification-us-east-1", + }: endpoint{ + Hostname: "verification.signer.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + endpointKey{ + Region: "verification-us-east-2", + }: endpoint{ + Hostname: "verification.signer.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + endpointKey{ + Region: "verification-us-west-1", + }: endpoint{ + Hostname: "verification.signer.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + endpointKey{ + Region: "verification-us-west-2", + }: endpoint{ + Hostname: "verification.signer.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + }, + }, + "simspaceweaver": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, + "sms": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "sms-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, }, endpointKey{ Region: "us-west-2", @@ -25591,6 +29471,15 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "sns-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -25615,6 +29504,15 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "sns-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -25651,6 +29549,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -25742,6 +29643,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -25802,6 +29706,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -25896,6 +29803,15 @@ var awsPartition = partition{ }: endpoint{ Hostname: "ssm-fips.ca-central-1.amazonaws.com", }, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-fips.ca-west-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -25929,6 +29845,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-ca-west-1", + }: endpoint{ + Hostname: "ssm-fips.ca-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -25965,6 +29890,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -26012,7 +29940,7 @@ var awsPartition = partition{ }, }, }, - "ssm-incidents": service{ + "ssm-contacts": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "ap-northeast-1", @@ -26047,40 +29975,91 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "ssm-contacts-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "ssm-contacts-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "ssm-contacts-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "ssm-contacts-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "sa-east-1", }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-contacts-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-contacts-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-contacts-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-contacts-fips.us-west-2.amazonaws.com", + }, }, }, - "ssm-sap": service{ + "ssm-incidents": service{ Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -26090,9 +30069,6 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -26100,7 +30076,7 @@ var awsPartition = partition{ Region: "ca-central-1", Variant: fipsVariant, }: endpoint{ - Hostname: "ssm-sap-fips.ca-central-1.amazonaws.com", + Hostname: "ssm-incidents-fips.ca-central-1.amazonaws.com", }, endpointKey{ Region: "eu-central-1", @@ -26108,9 +30084,6 @@ var awsPartition = partition{ endpointKey{ Region: "eu-north-1", }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -26123,7 +30096,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-ca-central-1", }: endpoint{ - Hostname: "ssm-sap-fips.ca-central-1.amazonaws.com", + Hostname: "ssm-incidents-fips.ca-central-1.amazonaws.com", CredentialScope: credentialScope{ Region: "ca-central-1", }, @@ -26132,7 +30105,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-east-1", }: endpoint{ - Hostname: "ssm-sap-fips.us-east-1.amazonaws.com", + Hostname: "ssm-incidents-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, @@ -26141,7 +30114,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-east-2", }: endpoint{ - Hostname: "ssm-sap-fips.us-east-2.amazonaws.com", + Hostname: "ssm-incidents-fips.us-east-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-2", }, @@ -26150,7 +30123,7 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-west-1", }: endpoint{ - Hostname: "ssm-sap-fips.us-west-1.amazonaws.com", + Hostname: "ssm-incidents-fips.us-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-1", }, @@ -26159,15 +30132,12 @@ var awsPartition = partition{ endpointKey{ Region: "fips-us-west-2", }: endpoint{ - Hostname: "ssm-sap-fips.us-west-2.amazonaws.com", + Hostname: "ssm-incidents-fips.us-west-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-2", }, Deprecated: boxedTrue, }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -26178,7 +30148,7 @@ var awsPartition = partition{ Region: "us-east-1", Variant: fipsVariant, }: endpoint{ - Hostname: "ssm-sap-fips.us-east-1.amazonaws.com", + Hostname: "ssm-incidents-fips.us-east-1.amazonaws.com", }, endpointKey{ Region: "us-east-2", @@ -26187,7 +30157,7 @@ var awsPartition = partition{ Region: "us-east-2", Variant: fipsVariant, }: endpoint{ - Hostname: "ssm-sap-fips.us-east-2.amazonaws.com", + Hostname: "ssm-incidents-fips.us-east-2.amazonaws.com", }, endpointKey{ Region: "us-west-1", @@ -26196,7 +30166,7 @@ var awsPartition = partition{ Region: "us-west-1", Variant: fipsVariant, }: endpoint{ - Hostname: "ssm-sap-fips.us-west-1.amazonaws.com", + Hostname: "ssm-incidents-fips.us-west-1.amazonaws.com", }, endpointKey{ Region: "us-west-2", @@ -26205,11 +30175,11 @@ var awsPartition = partition{ Region: "us-west-2", Variant: fipsVariant, }: endpoint{ - Hostname: "ssm-sap-fips.us-west-2.amazonaws.com", + Hostname: "ssm-incidents-fips.us-west-2.amazonaws.com", }, }, }, - "sso": service{ + "ssm-sap": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "af-south-1", @@ -26241,6 +30211,12 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-sap-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -26259,6 +30235,51 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "ssm-sap-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "ssm-sap-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "ssm-sap-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "ssm-sap-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "ssm-sap-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -26268,18 +30289,42 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-sap-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-sap-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-sap-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ssm-sap-fips.us-west-2.amazonaws.com", + }, }, }, - "states": service{ + "sso": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "af-south-1", @@ -26299,9 +30344,6 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -26311,9 +30353,6 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -26329,9 +30368,6 @@ var awsPartition = partition{ endpointKey{ Region: "eu-south-1", }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -26342,41 +30378,8 @@ var awsPartition = partition{ Region: "eu-west-3", }: endpoint{}, endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "states-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "states-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "states-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "states-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -26389,42 +30392,169 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-east-1.amazonaws.com", - }, endpointKey{ Region: "us-east-2", }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-east-2.amazonaws.com", - }, endpointKey{ Region: "us-west-1", }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-west-1.amazonaws.com", - }, endpointKey{ Region: "us-west-2", }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-west-2.amazonaws.com", - }, }, }, - "storagegateway": service{ + "states": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "states-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "states-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "states-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "states-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "states-fips.us-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "states-fips.us-east-2.amazonaws.com", + }, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "states-fips.us-west-1.amazonaws.com", + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "states-fips.us-west-2.amazonaws.com", + }, + }, + }, + "storagegateway": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "af-south-1", @@ -26502,14 +30632,8 @@ var awsPartition = partition{ Region: "eu-west-3", }: endpoint{}, endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "storagegateway-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -26639,6 +30763,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -26663,6 +30790,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "local", }: endpoint{ @@ -26742,6 +30872,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -26766,6 +30899,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -26913,6 +31049,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -26973,6 +31112,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -27058,6 +31200,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -27118,6 +31263,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -27203,6 +31351,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -27227,6 +31378,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -27368,6 +31522,65 @@ var awsPartition = partition{ }, }, }, + "thinclient": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, + "tnb": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "transcribe": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -27517,12 +31730,21 @@ var awsPartition = partition{ }, "transcribestreaming": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, @@ -27680,6 +31902,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -27689,6 +31914,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -27701,12 +31929,18 @@ var awsPartition = partition{ endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -27761,6 +31995,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -27910,6 +32147,91 @@ var awsPartition = partition{ }, }, }, + "verifiedpermissions": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "voice-chime": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -27921,6 +32243,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -28070,9 +32395,21 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, @@ -28665,6 +33002,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-il-central-1", + }: endpoint{ + Hostname: "waf-regional-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-me-central-1", }: endpoint{ @@ -28728,6 +33074,23 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "waf-regional.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, + endpointKey{ + Region: "il-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "waf-regional-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, endpointKey{ Region: "me-central-1", }: endpoint{ @@ -29371,6 +33734,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-il-central-1", + }: endpoint{ + Hostname: "wafv2-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-me-central-1", }: endpoint{ @@ -29434,6 +33806,23 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{ + Hostname: "wafv2.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, + endpointKey{ + Region: "il-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "wafv2-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, endpointKey{ Region: "me-central-1", }: endpoint{ @@ -29793,6 +34182,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -29888,6 +34280,9 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-west-1", + }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -29948,6 +34343,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1", + }: endpoint{}, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -30087,6 +34485,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "airflow": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "api.ecr": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30107,6 +34515,20 @@ var awscnPartition = partition{ }, }, }, + "api.pricing": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + CredentialScope: credentialScope{ + Service: "pricing", + }, + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "api.sagemaker": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30214,6 +34636,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "arc-zonal-shift": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "athena": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30276,6 +34708,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "backupstorage": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "batch": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30504,6 +34946,31 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "datazone": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.amazonwebservices.com.cn", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.amazonwebservices.com.cn", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{ + Hostname: "datazone.cn-north-1.api.amazonwebservices.com.cn", + }, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{ + Hostname: "datazone.cn-northwest-1.api.amazonwebservices.com.cn", + }, + }, + }, "dax": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30631,6 +35098,31 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "eks-auth": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.amazonwebservices.com.cn", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.amazonwebservices.com.cn", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{ + Hostname: "eks-auth.cn-north-1.api.amazonwebservices.com.cn", + }, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{ + Hostname: "eks-auth.cn-northwest-1.api.amazonwebservices.com.cn", + }, + }, + }, "elasticache": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30716,9 +35208,21 @@ var awscnPartition = partition{ endpointKey{ Region: "cn-north-1", }: endpoint{}, + endpointKey{ + Region: "cn-north-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "elasticmapreduce.cn-north-1.api.amazonwebservices.com.cn", + }, endpointKey{ Region: "cn-northwest-1", }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "elasticmapreduce.cn-northwest-1.api.amazonwebservices.com.cn", + }, }, }, "emr-containers": service{ @@ -30731,14 +35235,36 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "emr-serverless": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "es": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "cn-north-1", }: endpoint{}, + endpointKey{ + Region: "cn-north-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.cn-north-1.api.amazonwebservices.com.cn", + }, endpointKey{ Region: "cn-northwest-1", }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.cn-northwest-1.api.amazonwebservices.com.cn", + }, }, }, "events": service{ @@ -30896,6 +35422,16 @@ var awscnPartition = partition{ }, }, }, + "identitystore": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "internetmonitor": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -30922,13 +35458,6 @@ var awscnPartition = partition{ }, }, "iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - }, Endpoints: serviceEndpoints{ endpointKey{ Region: "cn-north-1", @@ -30981,6 +35510,29 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "iottwinmaker": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "api-cn-north-1", + }: endpoint{ + Hostname: "api.iottwinmaker.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "data-cn-north-1", + }: endpoint{ + Hostname: "data.iottwinmaker.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + }, + }, "kafka": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -31095,6 +35647,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "license-manager-linux-subscriptions": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "logs": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -31192,6 +35754,26 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "oidc": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{ + Hostname: "oidc.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{ + Hostname: "oidc.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, "organizations": service{ PartitionEndpoint: "aws-cn-global", IsRegionalized: boxedFalse, @@ -31223,6 +35805,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "pipes": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "polly": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -31230,6 +35822,51 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "portal.sso": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{ + Hostname: "portal.sso.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{ + Hostname: "portal.sso.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, + "qbusiness": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.amazonwebservices.com.cn", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.amazonwebservices.com.cn", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{ + Hostname: "qbusiness.cn-north-1.api.amazonwebservices.com.cn", + }, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{ + Hostname: "qbusiness.cn-northwest-1.api.amazonwebservices.com.cn", + }, + }, + }, "ram": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -31270,6 +35907,13 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "redshift-serverless": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + }, + }, "resource-explorer-2": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -31446,14 +36090,53 @@ var awscnPartition = partition{ }, }, }, + "savingsplans": service{ + IsRegionalized: boxedTrue, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{ + Hostname: "savingsplans.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{ + Hostname: "savingsplans.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, + "schemas": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "secretsmanager": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "cn-north-1", }: endpoint{}, + endpointKey{ + Region: "cn-north-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "cn-northwest-1", }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + Variant: dualStackVariant, + }: endpoint{}, }, }, "securityhub": service{ @@ -31504,7 +36187,7 @@ var awscnPartition = partition{ Region: "cn-north-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.cn-north-1.amazonaws.com.cn", + Hostname: "servicediscovery.cn-north-1.api.amazonwebservices.com.cn", }, endpointKey{ Region: "cn-northwest-1", @@ -31513,7 +36196,7 @@ var awscnPartition = partition{ Region: "cn-northwest-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.cn-northwest-1.amazonaws.com.cn", + Hostname: "servicediscovery.cn-northwest-1.api.amazonwebservices.com.cn", }, }, }, @@ -31532,7 +36215,7 @@ var awscnPartition = partition{ }: endpoint{}, }, }, - "sms": service{ + "signer": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "cn-north-1", @@ -31540,6 +36223,29 @@ var awscnPartition = partition{ endpointKey{ Region: "cn-northwest-1", }: endpoint{}, + endpointKey{ + Region: "verification-cn-north-1", + }: endpoint{ + Hostname: "verification.signer.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + endpointKey{ + Region: "verification-cn-northwest-1", + }: endpoint{ + Hostname: "verification.signer.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, + "sms": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, }, }, "snowball": service{ @@ -31623,14 +36329,36 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "sso": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "states": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "cn-north-1", }: endpoint{}, + endpointKey{ + Region: "cn-north-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "states.cn-north-1.api.amazonwebservices.com.cn", + }, endpointKey{ Region: "cn-northwest-1", }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "states.cn-northwest-1.api.amazonwebservices.com.cn", + }, }, }, "storagegateway": service{ @@ -32404,12 +37132,42 @@ var awsusgovPartition = partition{ }, "appconfigdata": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "appconfigdata.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "appconfigdata.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "appconfigdata.us-gov-east-1.amazonaws.com", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "appconfigdata.us-gov-west-1.amazonaws.com", + }, }, }, "application-autoscaling": service{ @@ -32426,12 +37184,44 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{ + Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", + Protocols: []string{"http", "https"}, + }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", + Protocols: []string{"http", "https"}, + }, + endpointKey{ + Region: "us-gov-east-1-fips", + }: endpoint{ + Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", Protocols: []string{"http", "https"}, + + Deprecated: boxedTrue, }, endpointKey{ Region: "us-gov-west-1", }: endpoint{ + Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", + Protocols: []string{"http", "https"}, + }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", + Protocols: []string{"http", "https"}, + }, + endpointKey{ + Region: "us-gov-west-1-fips", + }: endpoint{ + Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", Protocols: []string{"http", "https"}, + + Deprecated: boxedTrue, }, }, }, @@ -32512,6 +37302,16 @@ var awsusgovPartition = partition{ }, }, }, + "arc-zonal-shift": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + }, + }, "athena": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -32547,6 +37347,12 @@ var awsusgovPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-gov-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, @@ -32562,6 +37368,12 @@ var awsusgovPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-gov-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-gov-west-1.api.aws", + }, }, }, "autoscaling": service{ @@ -32625,6 +37437,16 @@ var awsusgovPartition = partition{ }: endpoint{}, }, }, + "backupstorage": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + }, + }, "batch": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{}, @@ -32673,6 +37495,13 @@ var awsusgovPartition = partition{ }, }, }, + "bedrock": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + }, + }, "cassandra": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -33050,6 +37879,15 @@ var awsusgovPartition = partition{ }, "codepipeline": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "codepipeline-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ @@ -33059,6 +37897,15 @@ var awsusgovPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "codepipeline-fips.us-gov-east-1.amazonaws.com", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, @@ -33070,6 +37917,13 @@ var awsusgovPartition = partition{ }, }, }, + "codestar-connections": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + }, + }, "cognito-identity": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -33233,9 +38087,24 @@ var awsusgovPartition = partition{ }, "connect": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "connect.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "connect.us-gov-west-1.amazonaws.com", + }, }, }, "controltower": service{ @@ -33398,6 +38267,31 @@ var awsusgovPartition = partition{ }, }, }, + "datazone": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.aws", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.aws", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{ + Hostname: "datazone.us-gov-east-1.api.aws", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{ + Hostname: "datazone.us-gov-west-1.api.aws", + }, + }, + }, "directconnect": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -33545,6 +38439,46 @@ var awsusgovPartition = partition{ }, }, }, + "drs": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "drs-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "drs-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "drs-fips.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "drs-fips.us-gov-west-1.amazonaws.com", + }, + }, + }, "ds": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -33780,6 +38714,31 @@ var awsusgovPartition = partition{ }, }, }, + "eks-auth": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.aws", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.aws", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{ + Hostname: "eks-auth.us-gov-east-1.api.aws", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{ + Hostname: "eks-auth.us-gov-west-1.api.aws", + }, + }, + }, "elasticache": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{}, @@ -34000,6 +38959,12 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "elasticmapreduce.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-east-1", Variant: fipsVariant, @@ -34011,6 +38976,13 @@ var awsusgovPartition = partition{ }: endpoint{ Protocols: []string{"https"}, }, + endpointKey{ + Region: "us-gov-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "elasticmapreduce.us-gov-west-1.api.aws", + Protocols: []string{"https"}, + }, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, @@ -34066,6 +39038,12 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-east-1", Variant: fipsVariant, @@ -34084,6 +39062,12 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "aos.us-gov-west-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, @@ -34320,6 +39304,28 @@ var awsusgovPartition = partition{ }, }, }, + "geo": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "geo-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "geo-fips.us-gov-west-1.amazonaws.com", + }, + }, + }, "glacier": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -34386,21 +39392,45 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "glue.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-east-1", Variant: fipsVariant, }: endpoint{ Hostname: "glue-fips.us-gov-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "glue-fips.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "glue.us-gov-west-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, }: endpoint{ Hostname: "glue-fips.us-gov-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "glue-fips.us-gov-west-1.api.aws", + }, }, }, "greengrass": service{ @@ -34518,7 +39548,21 @@ var awsusgovPartition = partition{ }, }, "health": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + SSLCommonName: "health.us-gov-west-1.amazonaws.com", + Protocols: []string{"https"}, + }, + }, Endpoints: serviceEndpoints{ + endpointKey{ + Region: "aws-us-gov-global", + }: endpoint{ + Hostname: "global.health.us-gov.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ @@ -34719,12 +39763,42 @@ var awsusgovPartition = partition{ }, "inspector2": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "inspector2-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "inspector2-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "inspector2-fips.us-gov-east-1.amazonaws.com", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "inspector2-fips.us-gov-west-1.amazonaws.com", + }, }, }, "internetmonitor": service{ @@ -34753,30 +39827,19 @@ var awsusgovPartition = partition{ }, }, "iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - }, Endpoints: serviceEndpoints{ endpointKey{ Region: "fips-us-gov-east-1", }: endpoint{ Hostname: "iot-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ Hostname: "iot-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ @@ -34923,6 +39986,38 @@ var awsusgovPartition = partition{ }, "iottwinmaker": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "api-us-gov-west-1", + }: endpoint{ + Hostname: "api.iottwinmaker.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "data-us-gov-west-1", + }: endpoint{ + Hostname: "data.iottwinmaker.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "fips-api-us-gov-west-1", + }: endpoint{ + Hostname: "api.iottwinmaker-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "fips-data-us-gov-west-1", + }: endpoint{ + Hostname: "data.iottwinmaker-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ @@ -34947,10 +40042,56 @@ var awsusgovPartition = partition{ Endpoints: serviceEndpoints{ endpointKey{ Region: "us-gov-east-1", - }: endpoint{}, + }: endpoint{ + Hostname: "kafka.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + endpointKey{ + Region: "us-gov-east-1-fips", + }: endpoint{ + Hostname: "kafka.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", - }: endpoint{}, + }: endpoint{ + Hostname: "kafka.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "us-gov-west-1-fips", + }: endpoint{ + Hostname: "kafka.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, }, }, "kendra": service{ @@ -35138,21 +40279,45 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "lakeformation.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-east-1", Variant: fipsVariant, }: endpoint{ Hostname: "lakeformation-fips.us-gov-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "lakeformation-fips.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: dualStackVariant, + }: endpoint{ + Hostname: "lakeformation.us-gov-west-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, }: endpoint{ Hostname: "lakeformation-fips.us-gov-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "lakeformation-fips.us-gov-west-1.api.aws", + }, }, }, "lambda": service{ @@ -35247,6 +40412,16 @@ var awsusgovPartition = partition{ }, }, }, + "license-manager-linux-subscriptions": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + }, + }, "logs": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -35287,6 +40462,36 @@ var awsusgovPartition = partition{ }, }, }, + "m2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{}, + }, + }, "managedblockchain": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -35383,6 +40588,46 @@ var awsusgovPartition = partition{ }: endpoint{}, }, }, + "mgn": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "mgn-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "mgn-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "mgn-fips.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "mgn-fips.us-gov-west-1.amazonaws.com", + }, + }, + }, "models.lex": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -35580,6 +40825,24 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + endpointKey{ + Region: "aws-us-gov-global", + Variant: fipsVariant, + }: endpoint{ + Hostname: "networkmanager.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "fips-aws-us-gov-global", + }: endpoint{ + Hostname: "networkmanager.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, }, }, "oidc": service{ @@ -35785,6 +41048,31 @@ var awsusgovPartition = partition{ }, }, }, + "qbusiness": service{ + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + DNSSuffix: "api.aws", + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "api.aws", + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{ + Hostname: "qbusiness.us-gov-east-1.api.aws", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{ + Hostname: "qbusiness.us-gov-west-1.api.aws", + }, + }, + }, "quicksight": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -36026,6 +41314,46 @@ var awsusgovPartition = partition{ }, }, }, + "resiliencehub": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "resiliencehub-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "resiliencehub-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "resiliencehub-fips.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "resiliencehub-fips.us-gov-west-1.amazonaws.com", + }, + }, + }, "resource-explorer-2": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -36106,6 +41434,46 @@ var awsusgovPartition = partition{ }: endpoint{}, }, }, + "rolesanywhere": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "rolesanywhere-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "rolesanywhere-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rolesanywhere-fips.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rolesanywhere-fips.us-gov-west-1.amazonaws.com", + }, + }, + }, "route53": service{ PartitionEndpoint: "aws-us-gov-global", IsRegionalized: boxedFalse, @@ -36143,9 +41511,35 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "route53resolver.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-east-1-fips", + }: endpoint{ + Hostname: "route53resolver.us-gov-east-1.amazonaws.com", + + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "route53resolver.us-gov-west-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1-fips", + }: endpoint{ + Hostname: "route53resolver.us-gov-west-1.amazonaws.com", + + Deprecated: boxedTrue, + }, }, }, "runtime.lex": service{ @@ -36440,17 +41834,33 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-gov-east-1", Variant: fipsVariant, }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, }, }, "secretsmanager": service{ @@ -36458,37 +41868,43 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-gov-east-1", Variant: fipsVariant, - }: endpoint{ - Hostname: "secretsmanager-fips.us-gov-east-1.amazonaws.com", - }, + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-gov-east-1-fips", }: endpoint{ - Hostname: "secretsmanager-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, - }: endpoint{ - Hostname: "secretsmanager-fips.us-gov-west-1.amazonaws.com", - }, + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{}, endpointKey{ Region: "us-gov-west-1-fips", }: endpoint{ - Hostname: "secretsmanager-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, + Deprecated: boxedTrue, }, }, @@ -36678,7 +42094,7 @@ var awsusgovPartition = partition{ Region: "us-gov-east-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.us-gov-east-1.amazonaws.com", + Hostname: "servicediscovery.us-gov-east-1.api.aws", }, endpointKey{ Region: "us-gov-east-1", @@ -36686,6 +42102,12 @@ var awsusgovPartition = partition{ }: endpoint{ Hostname: "servicediscovery-fips.us-gov-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery-fips.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-east-1-fips", }: endpoint{ @@ -36702,7 +42124,7 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", Variant: dualStackVariant, }: endpoint{ - Hostname: "servicediscovery.us-gov-west-1.amazonaws.com", + Hostname: "servicediscovery.us-gov-west-1.api.aws", }, endpointKey{ Region: "us-gov-west-1", @@ -36710,6 +42132,12 @@ var awsusgovPartition = partition{ }: endpoint{ Hostname: "servicediscovery-fips.us-gov-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "servicediscovery-fips.us-gov-west-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1-fips", }: endpoint{ @@ -36772,12 +42200,12 @@ var awsusgovPartition = partition{ }, }, }, - "sms": service{ + "simspaceweaver": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "fips-us-gov-east-1", }: endpoint{ - Hostname: "sms-fips.us-gov-east-1.amazonaws.com", + Hostname: "simspaceweaver.us-gov-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-east-1", }, @@ -36786,7 +42214,7 @@ var awsusgovPartition = partition{ endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ - Hostname: "sms-fips.us-gov-west-1.amazonaws.com", + Hostname: "simspaceweaver.us-gov-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-west-1", }, @@ -36799,7 +42227,29 @@ var awsusgovPartition = partition{ Region: "us-gov-east-1", Variant: fipsVariant, }: endpoint{ - Hostname: "sms-fips.us-gov-east-1.amazonaws.com", + Hostname: "simspaceweaver.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "simspaceweaver.us-gov-west-1.amazonaws.com", + }, + }, + }, + "sms": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "sms-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, }, endpointKey{ Region: "us-gov-west-1", @@ -36906,14 +42356,14 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-west-1", }: endpoint{ - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, }, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, }: endpoint{ Hostname: "sns.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, }, }, }, @@ -37005,6 +42455,24 @@ var awsusgovPartition = partition{ Region: "us-gov-east-1", }, }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "sso.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + endpointKey{ + Region: "us-gov-east-1-fips", + }: endpoint{ + Hostname: "sso.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{ @@ -37013,6 +42481,24 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "sso.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "us-gov-west-1-fips", + }: endpoint{ + Hostname: "sso.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, }, }, "states": service{ @@ -37645,6 +43131,15 @@ var awsusgovPartition = partition{ }, "workspaces": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "workspaces-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ @@ -37654,6 +43149,15 @@ var awsusgovPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "workspaces-fips.us-gov-east-1.amazonaws.com", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, @@ -37816,6 +43320,13 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "athena": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + }, + }, "autoscaling": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -37828,6 +43339,16 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "cloudcontrolapi": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, + }, + }, "cloudformation": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -37887,6 +43408,28 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "datasync": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-iso-west-1", + }: endpoint{ + Hostname: "datasync-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "datasync-fips.us-iso-west-1.c2s.ic.gov", + }, + }, + }, "directconnect": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -37897,6 +43440,16 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "dlm": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, + }, + }, "dms": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{}, @@ -37999,6 +43552,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "ec2": service{ @@ -38031,6 +43587,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "elasticache": service{ @@ -38097,14 +43656,45 @@ var awsisoPartition = partition{ }, "elasticmapreduce": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-iso-east-1", + }: endpoint{ + Hostname: "elasticmapreduce.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-iso-west-1", + }: endpoint{ + Hostname: "elasticmapreduce.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-iso-east-1", }: endpoint{ Protocols: []string{"https"}, }, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "elasticmapreduce.us-iso-east-1.c2s.ic.gov", + Protocols: []string{"https"}, + }, endpointKey{ Region: "us-iso-west-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "elasticmapreduce.us-iso-west-1.c2s.ic.gov", + }, }, }, "es": service{ @@ -38156,6 +43746,19 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "guardduty": service{ + IsRegionalized: boxedTrue, + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + Protocols: []string{"https"}, + }, + }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + }, + }, "health": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -38251,6 +43854,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "logs": service{ @@ -38303,25 +43909,219 @@ var awsisoPartition = partition{ }, "ram": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-iso-east-1", + }: endpoint{ + Hostname: "ram-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-iso-west-1", + }: endpoint{ + Hostname: "ram-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ram-fips.us-iso-east-1.c2s.ic.gov", + }, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ram-fips.us-iso-west-1.c2s.ic.gov", + }, + }, + }, + "rbin": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-iso-east-1", + }: endpoint{ + Hostname: "rbin-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-iso-west-1", + }: endpoint{ + Hostname: "rbin-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rbin-fips.us-iso-east-1.c2s.ic.gov", + }, endpointKey{ Region: "us-iso-west-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rbin-fips.us-iso-west-1.c2s.ic.gov", + }, }, }, "rds": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "rds-fips.us-iso-east-1", + }: endpoint{ + Hostname: "rds-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds-fips.us-iso-west-1", + }: endpoint{ + Hostname: "rds-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds.us-iso-east-1", + }: endpoint{ + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds.us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds.us-iso-west-1", + }: endpoint{ + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds.us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.us-iso-east-1.c2s.ic.gov", + }, + endpointKey{ + Region: "us-iso-east-1-fips", + }: endpoint{ + Hostname: "rds-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-iso-west-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.us-iso-west-1.c2s.ic.gov", + }, + endpointKey{ + Region: "us-iso-west-1-fips", + }: endpoint{ + Hostname: "rds-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, }, }, "redshift": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-iso-east-1", + }: endpoint{ + Hostname: "redshift-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-iso-west-1", + }: endpoint{ + Hostname: "redshift-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "redshift-fips.us-iso-east-1.c2s.ic.gov", + }, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "redshift-fips.us-iso-west-1.c2s.ic.gov", + }, + }, + }, + "resource-groups": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "us-iso-east-1", @@ -38350,6 +44150,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "runtime.sagemaker": service{ @@ -38366,15 +44169,61 @@ var awsisoPartition = partition{ }, }, Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-iso-east-1", + }: endpoint{ + Hostname: "s3-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-iso-west-1", + }: endpoint{ + Hostname: "s3-fips.us-iso-west-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-iso-east-1", }: endpoint{ Protocols: []string{"http", "https"}, SignatureVersions: []string{"s3v4"}, }, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "s3-fips.us-iso-east-1.c2s.ic.gov", + Protocols: []string{"http", "https"}, + SignatureVersions: []string{"s3v4"}, + }, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "s3-fips.dualstack.us-iso-east-1.c2s.ic.gov", + Protocols: []string{"http", "https"}, + SignatureVersions: []string{"s3v4"}, + }, endpointKey{ Region: "us-iso-west-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "s3-fips.us-iso-west-1.c2s.ic.gov", + }, + endpointKey{ + Region: "us-iso-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "s3-fips.dualstack.us-iso-west-1.c2s.ic.gov", + }, }, }, "secretsmanager": service{ @@ -38503,6 +44352,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "transcribe": service{ @@ -38597,6 +44449,13 @@ var awsisobPartition = partition{ }, }, }, + "api.sagemaker": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + }, + }, "appconfig": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -38635,6 +44494,13 @@ var awsisobPartition = partition{ }: endpoint{}, }, }, + "cloudcontrolapi": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + }, + }, "cloudformation": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -38831,9 +44697,24 @@ var awsisobPartition = partition{ }, "elasticmapreduce": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-isob-east-1", + }: endpoint{ + Hostname: "elasticmapreduce.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-isob-east-1", }: endpoint{}, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "elasticmapreduce.us-isob-east-1.sc2s.sgov.gov", + }, }, }, "es": service{ @@ -38965,25 +44846,126 @@ var awsisobPartition = partition{ }: endpoint{}, }, }, + "outposts": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + }, + }, "ram": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-isob-east-1", + }: endpoint{ + Hostname: "ram-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "ram-fips.us-isob-east-1.sc2s.sgov.gov", + }, + }, + }, + "rbin": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-isob-east-1", + }: endpoint{ + Hostname: "rbin-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-isob-east-1", }: endpoint{}, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rbin-fips.us-isob-east-1.sc2s.sgov.gov", + }, }, }, "rds": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "rds-fips.us-isob-east-1", + }: endpoint{ + Hostname: "rds-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds.us-isob-east-1", + }: endpoint{ + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "rds.us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-isob-east-1", }: endpoint{}, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rds-fips.us-isob-east-1.sc2s.sgov.gov", + }, + endpointKey{ + Region: "us-isob-east-1-fips", + }: endpoint{ + Hostname: "rds-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, }, }, "redshift": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-isob-east-1", + }: endpoint{ + Hostname: "redshift-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-isob-east-1", }: endpoint{}, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "redshift-fips.us-isob-east-1.sc2s.sgov.gov", + }, }, }, "resource-groups": service{ @@ -39014,6 +44996,13 @@ var awsisobPartition = partition{ }: endpoint{}, }, }, + "runtime.sagemaker": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + }, + }, "s3": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -39021,6 +45010,34 @@ var awsisobPartition = partition{ SignatureVersions: []string{"s3v4"}, }, }, + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-isob-east-1", + }: endpoint{ + Hostname: "s3-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "s3-fips.us-isob-east-1.sc2s.sgov.gov", + }, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "s3-fips.dualstack.us-isob-east-1.sc2s.sgov.gov", + }, + }, + }, + "secretsmanager": service{ Endpoints: serviceEndpoints{ endpointKey{ Region: "us-isob-east-1", @@ -39138,3 +45155,71 @@ var awsisobPartition = partition{ }, }, } + +// AwsIsoEPartition returns the Resolver for AWS ISOE (Europe). +func AwsIsoEPartition() Partition { + return awsisoePartition.Partition() +} + +var awsisoePartition = partition{ + ID: "aws-iso-e", + Name: "AWS ISOE (Europe)", + DNSSuffix: "cloud.adc-e.uk", + RegionRegex: regionRegex{ + Regexp: func() *regexp.Regexp { + reg, _ := regexp.Compile("^eu\\-isoe\\-\\w+\\-\\d+$") + return reg + }(), + }, + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + Hostname: "{service}.{region}.{dnsSuffix}", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + Regions: regions{}, + Services: services{}, +} + +// AwsIsoFPartition returns the Resolver for AWS ISOF. +func AwsIsoFPartition() Partition { + return awsisofPartition.Partition() +} + +var awsisofPartition = partition{ + ID: "aws-iso-f", + Name: "AWS ISOF", + DNSSuffix: "csp.hci.ic.gov", + RegionRegex: regionRegex{ + Regexp: func() *regexp.Regexp { + reg, _ := regexp.Compile("^us\\-isof\\-\\w+\\-\\d+$") + return reg + }(), + }, + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + Hostname: "{service}.{region}.{dnsSuffix}", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "csp.hci.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + Regions: regions{}, + Services: services{}, +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go index 1d3f4c3ad..ea8e35376 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go @@ -14,6 +14,7 @@ import ( "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/shareddefaults" + "github.com/aws/aws-sdk-go/service/ssooidc" "github.com/aws/aws-sdk-go/service/sts" ) @@ -23,6 +24,10 @@ type CredentialsProviderOptions struct { // WebIdentityRoleProviderOptions configures a WebIdentityRoleProvider, // such as setting its ExpiryWindow. WebIdentityRoleProviderOptions func(*stscreds.WebIdentityRoleProvider) + + // ProcessProviderOptions configures a ProcessProvider, + // such as setting its Timeout. + ProcessProviderOptions func(*processcreds.ProcessProvider) } func resolveCredentials(cfg *aws.Config, @@ -33,7 +38,7 @@ func resolveCredentials(cfg *aws.Config, switch { case len(sessOpts.Profile) != 0: - // User explicitly provided an Profile in the session's configuration + // User explicitly provided a Profile in the session's configuration // so load that profile from shared config first. // Github(aws/aws-sdk-go#2727) return resolveCredsFromProfile(cfg, envCfg, sharedCfg, handlers, sessOpts) @@ -134,7 +139,11 @@ func resolveCredsFromProfile(cfg *aws.Config, case len(sharedCfg.CredentialProcess) != 0: // Get credentials from CredentialProcess - creds = processcreds.NewCredentials(sharedCfg.CredentialProcess) + var optFns []func(*processcreds.ProcessProvider) + if sessOpts.CredentialsProviderOptions != nil && sessOpts.CredentialsProviderOptions.ProcessProviderOptions != nil { + optFns = append(optFns, sessOpts.CredentialsProviderOptions.ProcessProviderOptions) + } + creds = processcreds.NewCredentials(sharedCfg.CredentialProcess, optFns...) default: // Fallback to default credentials provider, include mock errors for @@ -173,8 +182,28 @@ func resolveSSOCredentials(cfg *aws.Config, sharedCfg sharedConfig, handlers req return nil, err } + var optFns []func(provider *ssocreds.Provider) cfgCopy := cfg.Copy() - cfgCopy.Region = &sharedCfg.SSORegion + + if sharedCfg.SSOSession != nil { + cfgCopy.Region = &sharedCfg.SSOSession.SSORegion + cachedPath, err := ssocreds.StandardCachedTokenFilepath(sharedCfg.SSOSession.Name) + if err != nil { + return nil, err + } + // create oidcClient with AnonymousCredentials to avoid recursively resolving credentials + mySession := Must(NewSession(&aws.Config{ + Credentials: credentials.AnonymousCredentials, + })) + oidcClient := ssooidc.New(mySession, cfgCopy) + tokenProvider := ssocreds.NewSSOTokenProvider(oidcClient, cachedPath) + optFns = append(optFns, func(p *ssocreds.Provider) { + p.TokenProvider = tokenProvider + p.CachedTokenFilepath = cachedPath + }) + } else { + cfgCopy.Region = &sharedCfg.SSORegion + } return ssocreds.NewCredentials( &Session{ @@ -184,6 +213,7 @@ func resolveSSOCredentials(cfg *aws.Config, sharedCfg sharedConfig, handlers req sharedCfg.SSOAccountID, sharedCfg.SSORoleName, sharedCfg.SSOStartURL, + optFns..., ), nil } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go index d6fa24776..93bb5de64 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go @@ -171,6 +171,12 @@ type envConfig struct { // AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6 EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState + // Specifies that IMDS clients should not fallback to IMDSv1 if token + // requests fail. + // + // AWS_EC2_METADATA_V1_DISABLED=true + EC2IMDSv1Disabled *bool + // Specifies that SDK clients must resolve a dual-stack endpoint for // services. // @@ -251,6 +257,9 @@ var ( ec2IMDSEndpointModeEnvKey = []string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE", } + ec2MetadataV1DisabledEnvKey = []string{ + "AWS_EC2_METADATA_V1_DISABLED", + } useCABundleKey = []string{ "AWS_CA_BUNDLE", } @@ -393,6 +402,7 @@ func envConfigLoad(enableSharedConfig bool) (envConfig, error) { if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, ec2IMDSEndpointModeEnvKey); err != nil { return envConfig{}, err } + setBoolPtrFromEnvVal(&cfg.EC2IMDSv1Disabled, ec2MetadataV1DisabledEnvKey) if err := setUseDualStackEndpointFromEnvVal(&cfg.UseDualStackEndpoint, awsUseDualStackEndpoint); err != nil { return cfg, err @@ -414,6 +424,24 @@ func setFromEnvVal(dst *string, keys []string) { } } +func setBoolPtrFromEnvVal(dst **bool, keys []string) { + for _, k := range keys { + value := os.Getenv(k) + if len(value) == 0 { + continue + } + + switch { + case strings.EqualFold(value, "false"): + *dst = new(bool) + **dst = false + case strings.EqualFold(value, "true"): + *dst = new(bool) + **dst = true + } + } +} + func setEC2IMDSEndpointMode(mode *endpoints.EC2IMDSEndpointModeState, keys []string) error { for _, k := range keys { value := os.Getenv(k) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go index cbccb60bb..3c88dee52 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go @@ -37,7 +37,7 @@ const ( // ErrSharedConfigSourceCollision will be returned if a section contains both // source_profile and credential_source -var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only one credential type may be specified per profile: source profile, credential source, credential process, web identity token, or sso", nil) +var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only one credential type may be specified per profile: source profile, credential source, credential process, web identity token", nil) // ErrSharedConfigECSContainerEnvVarEmpty will be returned if the environment // variables are empty and Environment was set as the credential source @@ -779,6 +779,14 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, ec2IMDSEndpoint, endpointMode) } + cfg.EC2MetadataEnableFallback = userCfg.EC2MetadataEnableFallback + if cfg.EC2MetadataEnableFallback == nil && envCfg.EC2IMDSv1Disabled != nil { + cfg.EC2MetadataEnableFallback = aws.Bool(!*envCfg.EC2IMDSv1Disabled) + } + if cfg.EC2MetadataEnableFallback == nil && sharedCfg.EC2IMDSv1Disabled != nil { + cfg.EC2MetadataEnableFallback = aws.Bool(!*sharedCfg.EC2IMDSv1Disabled) + } + cfg.S3UseARNRegion = userCfg.S3UseARNRegion if cfg.S3UseARNRegion == nil { cfg.S3UseARNRegion = &envCfg.S3UseARNRegion diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go index 424c82b4d..f3ce8183d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go @@ -26,6 +26,13 @@ const ( roleSessionNameKey = `role_session_name` // optional roleDurationSecondsKey = "duration_seconds" // optional + // Prefix to be used for SSO sections. These are supposed to only exist in + // the shared config file, not the credentials file. + ssoSectionPrefix = `sso-session ` + + // AWS Single Sign-On (AWS SSO) group + ssoSessionNameKey = "sso_session" + // AWS Single Sign-On (AWS SSO) group ssoAccountIDKey = "sso_account_id" ssoRegionKey = "sso_region" @@ -73,6 +80,9 @@ const ( // EC2 IMDS Endpoint ec2MetadataServiceEndpointKey = "ec2_metadata_service_endpoint" + // ECS IMDSv1 disable fallback + ec2MetadataV1DisabledKey = "ec2_metadata_v1_disabled" + // Use DualStack Endpoint Resolution useDualStackEndpoint = "use_dualstack_endpoint" @@ -99,6 +109,10 @@ type sharedConfig struct { CredentialProcess string WebIdentityTokenFile string + // SSO session options + SSOSessionName string + SSOSession *ssoSession + SSOAccountID string SSORegion string SSORoleName string @@ -168,6 +182,12 @@ type sharedConfig struct { // ec2_metadata_service_endpoint=http://fd00:ec2::254 EC2IMDSEndpoint string + // Specifies that IMDS clients should not fallback to IMDSv1 if token + // requests fail. + // + // ec2_metadata_v1_disabled=true + EC2IMDSv1Disabled *bool + // Specifies that SDK clients must resolve a dual-stack endpoint for // services. // @@ -186,6 +206,20 @@ type sharedConfigFile struct { IniData ini.Sections } +// SSOSession provides the shared configuration parameters of the sso-session +// section. +type ssoSession struct { + Name string + SSORegion string + SSOStartURL string +} + +func (s *ssoSession) setFromIniSection(section ini.Section) { + updateString(&s.Name, section, ssoSessionNameKey) + updateString(&s.SSORegion, section, ssoRegionKey) + updateString(&s.SSOStartURL, section, ssoStartURL) +} + // loadSharedConfig retrieves the configuration from the list of files using // the profile provided. The order the files are listed will determine // precedence. Values in subsequent files will overwrite values defined in @@ -266,13 +300,13 @@ func (cfg *sharedConfig) setFromIniFiles(profiles map[string]struct{}, profile s // profile only have credential provider options. cfg.clearAssumeRoleOptions() } else { - // First time a profile has been seen, It must either be a assume role - // credentials, or SSO. Assert if the credential type requires a role ARN, - // the ARN is also set, or validate that the SSO configuration is complete. + // First time a profile has been seen. Assert if the credential type + // requires a role ARN, the ARN is also set if err := cfg.validateCredentialsConfig(profile); err != nil { return err } } + profiles[profile] = struct{}{} if err := cfg.validateCredentialType(); err != nil { @@ -308,6 +342,30 @@ func (cfg *sharedConfig) setFromIniFiles(profiles map[string]struct{}, profile s cfg.SourceProfile = srcCfg } + // If the profile contains an SSO session parameter, the session MUST exist + // as a section in the config file. Load the SSO session using the name + // provided. If the session section is not found or incomplete an error + // will be returned. + if cfg.hasSSOTokenProviderConfiguration() { + skippedFiles = 0 + for _, f := range files { + section, ok := f.IniData.GetSection(fmt.Sprintf(ssoSectionPrefix + strings.TrimSpace(cfg.SSOSessionName))) + if ok { + var ssoSession ssoSession + ssoSession.setFromIniSection(section) + ssoSession.Name = cfg.SSOSessionName + cfg.SSOSession = &ssoSession + break + } + skippedFiles++ + } + if skippedFiles == len(files) { + // If all files were skipped because the sso session section is not found, return + // the sso section not found error. + return fmt.Errorf("failed to find SSO session section, %v", cfg.SSOSessionName) + } + } + return nil } @@ -340,8 +398,15 @@ func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, e updateString(&cfg.Region, section, regionKey) updateString(&cfg.CustomCABundle, section, customCABundleKey) + // we're retaining a behavioral quirk with this field that existed before + // the removal of literal parsing for (aws-sdk-go-v2/#2276): + // - if the key is missing, the config field will not be set + // - if the key is set to a non-numeric, the config field will be set to 0 if section.Has(roleDurationSecondsKey) { - d := time.Duration(section.Int(roleDurationSecondsKey)) * time.Second + var d time.Duration + if v, ok := section.Int(roleDurationSecondsKey); ok { + d = time.Duration(v) * time.Second + } cfg.AssumeRoleDuration = &d } @@ -363,6 +428,10 @@ func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, e cfg.S3UsEast1RegionalEndpoint = sre } + // AWS Single Sign-On (AWS SSO) + // SSO session options + updateString(&cfg.SSOSessionName, section, ssoSessionNameKey) + // AWS Single Sign-On (AWS SSO) updateString(&cfg.SSOAccountID, section, ssoAccountIDKey) updateString(&cfg.SSORegion, section, ssoRegionKey) @@ -374,6 +443,7 @@ func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, e ec2MetadataServiceEndpointModeKey, file.Filename, err) } updateString(&cfg.EC2IMDSEndpoint, section, ec2MetadataServiceEndpointKey) + updateBoolPtr(&cfg.EC2IMDSv1Disabled, section, ec2MetadataV1DisabledKey) updateUseDualStackEndpoint(&cfg.UseDualStackEndpoint, section, useDualStackEndpoint) @@ -461,32 +531,20 @@ func (cfg *sharedConfig) validateCredentialType() error { } func (cfg *sharedConfig) validateSSOConfiguration() error { - if !cfg.hasSSOConfiguration() { + if cfg.hasSSOTokenProviderConfiguration() { + err := cfg.validateSSOTokenProviderConfiguration() + if err != nil { + return err + } return nil } - var missing []string - if len(cfg.SSOAccountID) == 0 { - missing = append(missing, ssoAccountIDKey) - } - - if len(cfg.SSORegion) == 0 { - missing = append(missing, ssoRegionKey) - } - - if len(cfg.SSORoleName) == 0 { - missing = append(missing, ssoRoleNameKey) - } - - if len(cfg.SSOStartURL) == 0 { - missing = append(missing, ssoStartURL) - } - - if len(missing) > 0 { - return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", - cfg.Profile, strings.Join(missing, ", ")) + if cfg.hasLegacySSOConfiguration() { + err := cfg.validateLegacySSOConfiguration() + if err != nil { + return err + } } - return nil } @@ -525,15 +583,76 @@ func (cfg *sharedConfig) clearAssumeRoleOptions() { } func (cfg *sharedConfig) hasSSOConfiguration() bool { - switch { - case len(cfg.SSOAccountID) != 0: - case len(cfg.SSORegion) != 0: - case len(cfg.SSORoleName) != 0: - case len(cfg.SSOStartURL) != 0: - default: - return false + return cfg.hasSSOTokenProviderConfiguration() || cfg.hasLegacySSOConfiguration() +} + +func (c *sharedConfig) hasSSOTokenProviderConfiguration() bool { + return len(c.SSOSessionName) > 0 +} + +func (c *sharedConfig) hasLegacySSOConfiguration() bool { + return len(c.SSORegion) > 0 || len(c.SSOAccountID) > 0 || len(c.SSOStartURL) > 0 || len(c.SSORoleName) > 0 +} + +func (c *sharedConfig) validateSSOTokenProviderConfiguration() error { + var missing []string + + if len(c.SSOSessionName) == 0 { + missing = append(missing, ssoSessionNameKey) } - return true + + if c.SSOSession == nil { + missing = append(missing, ssoSectionPrefix) + } else { + if len(c.SSOSession.SSORegion) == 0 { + missing = append(missing, ssoRegionKey) + } + + if len(c.SSOSession.SSOStartURL) == 0 { + missing = append(missing, ssoStartURL) + } + } + + if len(missing) > 0 { + return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", + c.Profile, strings.Join(missing, ", ")) + } + + if len(c.SSORegion) > 0 && c.SSORegion != c.SSOSession.SSORegion { + return fmt.Errorf("%s in profile %q must match %s in %s", ssoRegionKey, c.Profile, ssoRegionKey, ssoSectionPrefix) + } + + if len(c.SSOStartURL) > 0 && c.SSOStartURL != c.SSOSession.SSOStartURL { + return fmt.Errorf("%s in profile %q must match %s in %s", ssoStartURL, c.Profile, ssoStartURL, ssoSectionPrefix) + } + + return nil +} + +func (c *sharedConfig) validateLegacySSOConfiguration() error { + var missing []string + + if len(c.SSORegion) == 0 { + missing = append(missing, ssoRegionKey) + } + + if len(c.SSOStartURL) == 0 { + missing = append(missing, ssoStartURL) + } + + if len(c.SSOAccountID) == 0 { + missing = append(missing, ssoAccountIDKey) + } + + if len(c.SSORoleName) == 0 { + missing = append(missing, ssoRoleNameKey) + } + + if len(missing) > 0 { + return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", + c.Profile, strings.Join(missing, ", ")) + } + return nil } func oneOrNone(bs ...bool) bool { @@ -566,7 +685,10 @@ func updateBool(dst *bool, section ini.Section, key string) { if !section.Has(key) { return } - *dst = section.Bool(key) + + // retains pre-(aws-sdk-go-v2#2276) behavior where non-bool value would resolve to false + v, _ := section.Bool(key) + *dst = v } // updateBoolPtr will only update the dst with the value in the section key, @@ -575,8 +697,11 @@ func updateBoolPtr(dst **bool, section ini.Section, key string) { if !section.Has(key) { return } + + // retains pre-(aws-sdk-go-v2#2276) behavior where non-bool value would resolve to false + v, _ := section.Bool(key) *dst = new(bool) - **dst = section.Bool(key) + **dst = v } // SharedConfigLoadError is an error for the shared config file failed to load. @@ -703,7 +828,8 @@ func updateUseDualStackEndpoint(dst *endpoints.DualStackEndpointState, section i return } - if section.Bool(key) { + // retains pre-(aws-sdk-go-v2/#2276) behavior where non-bool value would resolve to false + if v, _ := section.Bool(key); v { *dst = endpoints.DualStackEndpointStateEnabled } else { *dst = endpoints.DualStackEndpointStateDisabled @@ -719,7 +845,8 @@ func updateUseFIPSEndpoint(dst *endpoints.FIPSEndpointState, section ini.Section return } - if section.Bool(key) { + // retains pre-(aws-sdk-go-v2/#2276) behavior where non-bool value would resolve to false + if v, _ := section.Bool(key); v { *dst = endpoints.FIPSEndpointStateEnabled } else { *dst = endpoints.FIPSEndpointStateDisabled diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go index 4d78162c0..b542df931 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go @@ -3,21 +3,21 @@ // Provides request signing for request that need to be signed with // AWS V4 Signatures. // -// Standalone Signer +// # Standalone Signer // // Generally using the signer outside of the SDK should not require any additional // logic when using Go v1.5 or higher. The signer does this by taking advantage // of the URL.EscapedPath method. If your request URI requires additional escaping -// you many need to use the URL.Opaque to define what the raw URI should be sent +// you may need to use the URL.Opaque to define what the raw URI should be sent // to the service as. // // The signer will first check the URL.Opaque field, and use its value if set. // The signer does require the URL.Opaque field to be set in the form of: // -// "///" +// "///" // -// // e.g. -// "//example.com/some/path" +// // e.g. +// "//example.com/some/path" // // The leading "//" and hostname are required or the URL.Opaque escaping will // not work correctly. @@ -125,6 +125,7 @@ var requiredSignedHeaders = rules{ "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, + "X-Amz-Expected-Bucket-Owner": struct{}{}, "X-Amz-Grant-Full-control": struct{}{}, "X-Amz-Grant-Read": struct{}{}, "X-Amz-Grant-Read-Acp": struct{}{}, @@ -135,6 +136,7 @@ var requiredSignedHeaders = rules{ "X-Amz-Request-Payer": struct{}{}, "X-Amz-Server-Side-Encryption": struct{}{}, "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, + "X-Amz-Server-Side-Encryption-Context": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, @@ -695,7 +697,8 @@ func (ctx *signingCtx) buildBodyDigest() error { includeSHA256Header := ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "s3-object-lambda" || - ctx.ServiceName == "glacier" + ctx.ServiceName == "glacier" || + ctx.ServiceName == "s3-outposts" s3Presign := ctx.isPresign && (ctx.ServiceName == "s3" || diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go index f34d39820..945a8b45e 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.44.245" +const SDKVersion = "1.50.0" diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go index 34a481afb..b1b686086 100644 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go @@ -154,11 +154,11 @@ func (v ValueType) String() string { // ValueType enums const ( NoneType = ValueType(iota) - DecimalType - IntegerType + DecimalType // deprecated + IntegerType // deprecated StringType QuotedStringType - BoolType + BoolType // deprecated ) // Value is a union container @@ -166,9 +166,9 @@ type Value struct { Type ValueType raw []rune - integer int64 - decimal float64 - boolean bool + integer int64 // deprecated + decimal float64 // deprecated + boolean bool // deprecated str string } @@ -253,24 +253,6 @@ func newLitToken(b []rune) (Token, int, error) { } token = newToken(TokenLit, b[:n], QuotedStringType) - } else if isNumberValue(b) { - var base int - base, n, err = getNumericalValue(b) - if err != nil { - return token, 0, err - } - - value := b[:n] - vType := IntegerType - if contains(value, '.') || hasExponent(value) { - vType = DecimalType - } - token = newToken(TokenLit, value, vType) - token.base = base - } else if isBoolValue(b) { - n, err = getBoolValue(b) - - token = newToken(TokenLit, b[:n], BoolType) } else { n, err = getValue(b) token = newToken(TokenLit, b[:n], StringType) @@ -280,18 +262,33 @@ func newLitToken(b []rune) (Token, int, error) { } // IntValue returns an integer value -func (v Value) IntValue() int64 { - return v.integer +func (v Value) IntValue() (int64, bool) { + i, err := strconv.ParseInt(string(v.raw), 0, 64) + if err != nil { + return 0, false + } + return i, true } // FloatValue returns a float value -func (v Value) FloatValue() float64 { - return v.decimal +func (v Value) FloatValue() (float64, bool) { + f, err := strconv.ParseFloat(string(v.raw), 64) + if err != nil { + return 0, false + } + return f, true } // BoolValue returns a bool value -func (v Value) BoolValue() bool { - return v.boolean +func (v Value) BoolValue() (bool, bool) { + // we don't use ParseBool as it recognizes more than what we've + // historically supported + if isCaselessLitValue(runesTrue, v.raw) { + return true, true + } else if isCaselessLitValue(runesFalse, v.raw) { + return false, true + } + return false, false } func isTrimmable(r rune) bool { diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go index 081cf4334..1d08e138a 100644 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go @@ -145,17 +145,17 @@ func (t Section) ValueType(k string) (ValueType, bool) { } // Bool returns a bool value at k -func (t Section) Bool(k string) bool { +func (t Section) Bool(k string) (bool, bool) { return t.values[k].BoolValue() } // Int returns an integer value at k -func (t Section) Int(k string) int64 { +func (t Section) Int(k string) (int64, bool) { return t.values[k].IntValue() } // Float64 returns a float value at k -func (t Section) Float64(k string) float64 { +func (t Section) Float64(k string) (float64, bool) { return t.values[k].FloatValue() } diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go index 1d273ff0e..ecc521f88 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go @@ -287,6 +287,10 @@ func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) if tag.Get("location") != "header" || tag.Get("enum") == "" { return "", fmt.Errorf("%T is only supported with location header and enum shapes", value) } + if len(value) == 0 { + return "", errValueNotSet + } + buff := &bytes.Buffer{} for i, sv := range value { if sv == nil || len(*sv) == 0 { diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go index 4fffd0427..5366a646d 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go @@ -2,6 +2,7 @@ package restjson import ( "bytes" + "encoding/json" "io" "io/ioutil" "net/http" @@ -40,54 +41,30 @@ func (u *UnmarshalTypedError) UnmarshalError( resp *http.Response, respMeta protocol.ResponseMetadata, ) (error, error) { - - code := resp.Header.Get(errorTypeHeader) - msg := resp.Header.Get(errorMessageHeader) - - body := resp.Body - if len(code) == 0 || len(msg) == 0 { - // If unable to get code from HTTP headers have to parse JSON message - // to determine what kind of exception this will be. - var buf bytes.Buffer - var jsonErr jsonErrorResponse - teeReader := io.TeeReader(resp.Body, &buf) - err := jsonutil.UnmarshalJSONError(&jsonErr, teeReader) - if err != nil { - return nil, err - } - - body = ioutil.NopCloser(&buf) - if len(code) == 0 { - code = jsonErr.Code - } - msg = jsonErr.Message + code, msg, err := unmarshalErrorInfo(resp) + if err != nil { + return nil, err } - // If code has colon separators remove them so can compare against modeled - // exception names. - code = strings.SplitN(code, ":", 2)[0] - - if fn, ok := u.exceptions[code]; ok { - // If exception code is know, use associated constructor to get a value - // for the exception that the JSON body can be unmarshaled into. - v := fn(respMeta) - if err := jsonutil.UnmarshalJSONCaseInsensitive(v, body); err != nil { - return nil, err - } + fn, ok := u.exceptions[code] + if !ok { + return awserr.NewRequestFailure( + awserr.New(code, msg, nil), + respMeta.StatusCode, + respMeta.RequestID, + ), nil + } - if err := rest.UnmarshalResponse(resp, v, true); err != nil { - return nil, err - } + v := fn(respMeta) + if err := jsonutil.UnmarshalJSONCaseInsensitive(v, resp.Body); err != nil { + return nil, err + } - return v, nil + if err := rest.UnmarshalResponse(resp, v, true); err != nil { + return nil, err } - // fallback to unmodeled generic exceptions - return awserr.NewRequestFailure( - awserr.New(code, msg, nil), - respMeta.StatusCode, - respMeta.RequestID, - ), nil + return v, nil } // UnmarshalErrorHandler is a named request handler for unmarshaling restjson @@ -101,36 +78,80 @@ var UnmarshalErrorHandler = request.NamedHandler{ func UnmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() - var jsonErr jsonErrorResponse - err := jsonutil.UnmarshalJSONError(&jsonErr, r.HTTPResponse.Body) + code, msg, err := unmarshalErrorInfo(r.HTTPResponse) if err != nil { r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, - "failed to unmarshal response error", err), + awserr.New(request.ErrCodeSerialization, "failed to unmarshal response error", err), r.HTTPResponse.StatusCode, r.RequestID, ) return } - code := r.HTTPResponse.Header.Get(errorTypeHeader) - if code == "" { - code = jsonErr.Code - } - msg := r.HTTPResponse.Header.Get(errorMessageHeader) - if msg == "" { - msg = jsonErr.Message - } - - code = strings.SplitN(code, ":", 2)[0] r.Error = awserr.NewRequestFailure( - awserr.New(code, jsonErr.Message, nil), + awserr.New(code, msg, nil), r.HTTPResponse.StatusCode, r.RequestID, ) } type jsonErrorResponse struct { + Type string `json:"__type"` Code string `json:"code"` Message string `json:"message"` } + +func (j *jsonErrorResponse) SanitizedCode() string { + code := j.Code + if len(j.Type) > 0 { + code = j.Type + } + return sanitizeCode(code) +} + +// Remove superfluous components from a restJson error code. +// - If a : character is present, then take only the contents before the +// first : character in the value. +// - If a # character is present, then take only the contents after the first +// # character in the value. +// +// All of the following error values resolve to FooError: +// - FooError +// - FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/ +// - aws.protocoltests.restjson#FooError +// - aws.protocoltests.restjson#FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/ +func sanitizeCode(code string) string { + noColon := strings.SplitN(code, ":", 2)[0] + hashSplit := strings.SplitN(noColon, "#", 2) + return hashSplit[len(hashSplit)-1] +} + +// attempt to garner error details from the response, preferring header values +// when present +func unmarshalErrorInfo(resp *http.Response) (code string, msg string, err error) { + code = sanitizeCode(resp.Header.Get(errorTypeHeader)) + msg = resp.Header.Get(errorMessageHeader) + if len(code) > 0 && len(msg) > 0 { + return + } + + // a modeled error will have to be re-deserialized later, so the body must + // be preserved + var buf bytes.Buffer + tee := io.TeeReader(resp.Body, &buf) + defer func() { resp.Body = ioutil.NopCloser(&buf) }() + + var jsonErr jsonErrorResponse + if decodeErr := json.NewDecoder(tee).Decode(&jsonErr); decodeErr != nil && decodeErr != io.EOF { + err = awserr.NewUnmarshalError(decodeErr, "failed to decode response body", buf.Bytes()) + return + } + + if len(code) == 0 { + code = jsonErr.SanitizedCode() + } + if len(msg) == 0 { + msg = jsonErr.Message + } + return +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go index 1ed7b2921..3ec976ab4 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go @@ -683,15 +683,10 @@ func (c *EC2) AllocateAddressRequest(input *AllocateAddressInput) (req *request. // see Bring Your Own IP Addresses (BYOIP) (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html) // in the Amazon Elastic Compute Cloud User Guide. // -// [EC2-VPC] If you release an Elastic IP address, you might be able to recover -// it. You cannot recover an Elastic IP address that you released after it is -// allocated to another Amazon Web Services account. You cannot recover an Elastic -// IP address for EC2-Classic. To attempt to recover an Elastic IP address that -// you released, specify it in this operation. -// -// An Elastic IP address is for use either in the EC2-Classic platform or in -// a VPC. By default, you can allocate 5 Elastic IP addresses for EC2-Classic -// per Region and 5 Elastic IP addresses for EC2-VPC per Region. +// If you release an Elastic IP address, you might be able to recover it. You +// cannot recover an Elastic IP address that you released after it is allocated +// to another Amazon Web Services account. To attempt to recover an Elastic +// IP address that you released, specify it in this operation. // // For more information, see Elastic IP Addresses (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) // in the Amazon Elastic Compute Cloud User Guide. @@ -700,10 +695,6 @@ func (c *EC2) AllocateAddressRequest(input *AllocateAddressInput) (req *request. // telecommunication carrier, to a network interface which resides in a subnet // in a Wavelength Zone (for example an EC2 instance). // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -850,9 +841,12 @@ func (c *EC2) AllocateIpamPoolCidrRequest(input *AllocateIpamPoolCidrInput) (req // AllocateIpamPoolCidr API operation for Amazon Elastic Compute Cloud. // -// Allocate a CIDR from an IPAM pool. In IPAM, an allocation is a CIDR assignment -// from an IPAM pool to another IPAM pool or to a resource. For more information, -// see Allocate CIDRs (https://docs.aws.amazon.com/vpc/latest/ipam/allocate-cidrs-ipam.html) +// Allocate a CIDR from an IPAM pool. The Region you use should be the IPAM +// pool locale. The locale is the Amazon Web Services Region where this IPAM +// pool is available for allocations. +// +// In IPAM, an allocation is a CIDR assignment from an IPAM pool to another +// IPAM pool or to a resource. For more information, see Allocate CIDRs (https://docs.aws.amazon.com/vpc/latest/ipam/allocate-cidrs-ipam.html) // in the Amazon VPC IPAM User Guide. // // This action creates an allocation with strong consistency. The returned CIDR @@ -1193,7 +1187,7 @@ func (c *EC2) AssignPrivateNatGatewayAddressRequest(input *AssignPrivateNatGatew // // Assigns one or more private IPv4 addresses to a private NAT gateway. For // more information, see Work with NAT gateways (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-working-with) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1270,23 +1264,11 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // are in subnets in Wavelength Zones) with an instance or a network interface. // Before you can use an Elastic IP address, you must allocate it to your account. // -// An Elastic IP address is for use in either the EC2-Classic platform or in -// a VPC. For more information, see Elastic IP Addresses (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) -// in the Amazon Elastic Compute Cloud User Guide. -// -// [EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is -// already associated with a different instance, it is disassociated from that -// instance and associated with the specified instance. If you associate an -// Elastic IP address with an instance that has an existing Elastic IP address, -// the existing address is disassociated from the instance, but remains allocated -// to your account. -// -// [VPC in an EC2-Classic account] If you don't specify a private IP address, -// the Elastic IP address is associated with the primary IP address. If the -// Elastic IP address is already associated with a different instance or a network -// interface, you get an error unless you allow reassociation. You cannot associate -// an Elastic IP address with an instance or network interface that has an existing -// Elastic IP address. +// If the Elastic IP address is already associated with a different instance, +// it is disassociated from that instance and associated with the specified +// instance. If you associate an Elastic IP address with an instance that has +// an existing Elastic IP address, the existing address is disassociated from +// the instance, but remains allocated to your account. // // [Subnets in Wavelength Zones] You can associate an IP address from the telecommunication // carrier to the instance or network interface. @@ -1299,10 +1281,6 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // the Elastic IP address is remapped to the same instance. For more information, // see the Elastic IP Addresses section of Amazon EC2 Pricing (http://aws.amazon.com/ec2/pricing/). // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -1469,7 +1447,7 @@ func (c *EC2) AssociateDhcpOptionsRequest(input *AssociateDhcpOptionsInput) (req // on the instance. // // For more information, see DHCP options sets (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1742,6 +1720,86 @@ func (c *EC2) AssociateInstanceEventWindowWithContext(ctx aws.Context, input *As return out, req.Send() } +const opAssociateIpamByoasn = "AssociateIpamByoasn" + +// AssociateIpamByoasnRequest generates a "aws/request.Request" representing the +// client's request for the AssociateIpamByoasn operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AssociateIpamByoasn for more information on using the AssociateIpamByoasn +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the AssociateIpamByoasnRequest method. +// req, resp := client.AssociateIpamByoasnRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateIpamByoasn +func (c *EC2) AssociateIpamByoasnRequest(input *AssociateIpamByoasnInput) (req *request.Request, output *AssociateIpamByoasnOutput) { + op := &request.Operation{ + Name: opAssociateIpamByoasn, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &AssociateIpamByoasnInput{} + } + + output = &AssociateIpamByoasnOutput{} + req = c.newRequest(op, input, output) + return +} + +// AssociateIpamByoasn API operation for Amazon Elastic Compute Cloud. +// +// Associates your Autonomous System Number (ASN) with a BYOIP CIDR that you +// own in the same Amazon Web Services Region. For more information, see Tutorial: +// Bring your ASN to IPAM (https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-byoasn.html) +// in the Amazon VPC IPAM guide. +// +// After the association succeeds, the ASN is eligible for advertisement. You +// can view the association with DescribeByoipCidrs (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeByoipCidrs.html). +// You can advertise the CIDR with AdvertiseByoipCidr (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AdvertiseByoipCidr.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation AssociateIpamByoasn for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateIpamByoasn +func (c *EC2) AssociateIpamByoasn(input *AssociateIpamByoasnInput) (*AssociateIpamByoasnOutput, error) { + req, out := c.AssociateIpamByoasnRequest(input) + return out, req.Send() +} + +// AssociateIpamByoasnWithContext is the same as AssociateIpamByoasn with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateIpamByoasn for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) AssociateIpamByoasnWithContext(ctx aws.Context, input *AssociateIpamByoasnInput, opts ...request.Option) (*AssociateIpamByoasnOutput, error) { + req, out := c.AssociateIpamByoasnRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opAssociateIpamResourceDiscovery = "AssociateIpamResourceDiscovery" // AssociateIpamResourceDiscoveryRequest generates a "aws/request.Request" representing the @@ -1862,12 +1920,22 @@ func (c *EC2) AssociateNatGatewayAddressRequest(input *AssociateNatGatewayAddres // // Associates Elastic IP addresses (EIPs) and private IPv4 addresses with a // public NAT gateway. For more information, see Work with NAT gateways (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-working-with) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // By default, you can associate up to 2 Elastic IP addresses per public NAT // gateway. You can increase the limit by requesting a quota adjustment. For // more information, see Elastic IP address quotas (https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html#vpc-limits-eips) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. +// +// When you associate an EIP or secondary EIPs with a public NAT gateway, the +// network border group of the EIPs must match the network border group of the +// Availability Zone (AZ) that the public NAT gateway is in. If it's not the +// same, the EIP will fail to associate. You can see the network border group +// for the subnet's AZ by viewing the details of the subnet. Similarly, you +// can view the network border group of an EIP by viewing the details of the +// EIP address. For more information about network border groups and EIPs, see +// Allocate an Elastic IP address (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-eips.html#allocate-eip) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1948,7 +2016,7 @@ func (c *EC2) AssociateRouteTableRequest(input *AssociateRouteTableInput) (req * // with multiple subnets. // // For more information, see Route tables (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2022,8 +2090,7 @@ func (c *EC2) AssociateSubnetCidrBlockRequest(input *AssociateSubnetCidrBlockInp // AssociateSubnetCidrBlock API operation for Amazon Elastic Compute Cloud. // // Associates a CIDR block with your subnet. You can only associate a single -// IPv6 CIDR block with your subnet. An IPv6 CIDR block must have a prefix length -// of /64. +// IPv6 CIDR block with your subnet. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2322,9 +2389,6 @@ func (c *EC2) AssociateTrunkInterfaceRequest(input *AssociateTrunkInterfaceInput // AssociateTrunkInterface API operation for Amazon Elastic Compute Cloud. // -// This API action is currently in limited preview only. If you are interested -// in using this feature, contact your account manager. -// // Associates a branch network interface with a trunk network interface. // // Before you create the association, run the create-network-interface (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkInterface.html) @@ -2407,14 +2471,13 @@ func (c *EC2) AssociateVpcCidrBlockRequest(input *AssociateVpcCidrBlockInput) (r // CIDR block, an Amazon-provided IPv6 CIDR block, or an IPv6 CIDR block from // an IPv6 address pool that you provisioned through bring your own IP addresses // (BYOIP (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html)). -// The IPv6 CIDR block size is fixed at /56. // // You must specify one of the following in the request: an IPv4 CIDR block, // an IPv6 pool, or an Amazon-provided IPv6 CIDR block. // // For more information about associating CIDR blocks with your VPC and applicable -// restrictions, see VPC and subnet sizing (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html#VPC_Sizing) -// in the Amazon Virtual Private Cloud User Guide. +// restrictions, see IP addressing for your VPCs and subnets (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-ip-addressing.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2487,12 +2550,10 @@ func (c *EC2) AttachClassicLinkVpcRequest(input *AttachClassicLinkVpcInput) (req // AttachClassicLinkVpc API operation for Amazon Elastic Compute Cloud. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// This action is deprecated. // // Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or -// more of the VPC's security groups. You cannot link an EC2-Classic instance +// more of the VPC security groups. You cannot link an EC2-Classic instance // to more than one VPC at a time. You can only link an instance that's in the // running state. An instance is automatically unlinked from a VPC when it's // stopped - you can link it to the VPC again when you restart it. @@ -2577,9 +2638,9 @@ func (c *EC2) AttachInternetGatewayRequest(input *AttachInternetGatewayInput) (r // AttachInternetGateway API operation for Amazon Elastic Compute Cloud. // // Attaches an internet gateway or a virtual private gateway to a VPC, enabling -// connectivity between the internet and the VPC. For more information about -// your VPC and internet gateway, see the Amazon Virtual Private Cloud User -// Guide (https://docs.aws.amazon.com/vpc/latest/userguide/). +// connectivity between the internet and the VPC. For more information, see +// Internet gateways (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2725,9 +2786,8 @@ func (c *EC2) AttachVerifiedAccessTrustProviderRequest(input *AttachVerifiedAcce // AttachVerifiedAccessTrustProvider API operation for Amazon Elastic Compute Cloud. // -// A trust provider is a third-party entity that creates, maintains, and manages -// identity information for users and devices. One or more trust providers can -// be attached to an Amazon Web Services Verified Access instance. +// Attaches the specified Amazon Web Services Verified Access trust provider +// to the specified Amazon Web Services Verified Access instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3050,8 +3110,8 @@ func (c *EC2) AuthorizeSecurityGroupEgressRequest(input *AuthorizeSecurityGroupE // AuthorizeSecurityGroupEgress API operation for Amazon Elastic Compute Cloud. // -// [VPC only] Adds the specified outbound (egress) rules to a security group -// for use with a VPC. +// Adds the specified outbound (egress) rules to a security group for use with +// a VPC. // // An outbound rule permits instances to send traffic to the specified IPv4 // or IPv6 CIDR address ranges, or to the instances that are associated with @@ -3069,6 +3129,11 @@ func (c *EC2) AuthorizeSecurityGroupEgressRequest(input *AuthorizeSecurityGroupE // // For information about VPC security group quotas, see Amazon VPC quotas (https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html). // +// If you want to reference a security group across VPCs attached to a transit +// gateway using the security group referencing feature (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#create-tgw), +// note that you can only reference security groups for ingress rules. You cannot +// reference a security group for egress rules. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -3159,10 +3224,6 @@ func (c *EC2) AuthorizeSecurityGroupIngressRequest(input *AuthorizeSecurityGroup // For more information about VPC security group quotas, see Amazon VPC quotas // (https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html). // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -5065,9 +5126,9 @@ func (c *EC2) CreateDefaultSubnetRequest(input *CreateDefaultSubnetInput) (req * // // Creates a default subnet with a size /20 IPv4 CIDR block in the specified // Availability Zone in your default VPC. You can have only one default subnet -// per Availability Zone. For more information, see Creating a default subnet +// per Availability Zone. For more information, see Create a default subnet // (https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html#create-default-subnet) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -5142,22 +5203,13 @@ func (c *EC2) CreateDefaultVpcRequest(input *CreateDefaultVpcInput) (req *reques // // Creates a default VPC with a size /16 IPv4 CIDR block and a default subnet // in each Availability Zone. For more information about the components of a -// default VPC, see Default VPC and default subnets (https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html) -// in the Amazon Virtual Private Cloud User Guide. You cannot specify the components -// of the default VPC yourself. +// default VPC, see Default VPCs (https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html) +// in the Amazon VPC User Guide. You cannot specify the components of the default +// VPC yourself. // // If you deleted your previous default VPC, you can create a default VPC. You // cannot have more than one default VPC per Region. // -// If your account supports EC2-Classic, you cannot use this action to create -// a default VPC in a Region that supports EC2-Classic. If you want a default -// VPC in a Region that supports EC2-Classic, see "I really want a default VPC -// for my existing EC2 account. Is that possible?" in the Default VPCs FAQ (http://aws.amazon.com/vpc/faqs/#Default_VPCs). -// -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -5267,7 +5319,7 @@ func (c *EC2) CreateDhcpOptionsRequest(input *CreateDhcpOptionsInput) (req *requ // of options, and if your VPC has an internet gateway, make sure to set the // domain-name-servers option either to AmazonProvidedDNS or to a domain name // server of your choice. For more information, see DHCP options sets (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -5416,10 +5468,12 @@ func (c *EC2) CreateFleetRequest(input *CreateFleetInput) (req *request.Request, // CreateFleet API operation for Amazon Elastic Compute Cloud. // -// Launches an EC2 Fleet. +// Creates an EC2 Fleet that contains the configuration information for On-Demand +// Instances and Spot Instances. Instances are launched immediately if there +// is available capacity. // -// You can create a single EC2 Fleet that includes multiple launch specifications -// that vary by instance type, AMI, Availability Zone, or subnet. +// A single EC2 Fleet can include multiple launch specifications that vary by +// instance type, AMI, Availability Zone, or subnet. // // For more information, see EC2 Fleet (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet.html) // in the Amazon EC2 User Guide. @@ -5667,16 +5721,6 @@ func (c *EC2) CreateImageRequest(input *CreateImageInput) (req *request.Request, // Creates an Amazon EBS-backed AMI from an Amazon EBS-backed instance that // is either running or stopped. // -// By default, when Amazon EC2 creates the new AMI, it reboots the instance -// so that it can take snapshots of the attached volumes while data is at rest, -// in order to ensure a consistent state. You can set the NoReboot parameter -// to true in the API request, or use the --no-reboot option in the CLI to prevent -// Amazon EC2 from shutting down and rebooting the instance. -// -// If you choose to bypass the shutdown and reboot process by setting the NoReboot -// parameter to true in the API request, or by using the --no-reboot option -// in the CLI, we can't guarantee the file system integrity of the created image. -// // If you customized your instance with instance store volumes or Amazon EBS // volumes in addition to the root device volume, the new AMI contains block // device mapping information for those volumes. When you launch an instance @@ -5714,6 +5758,85 @@ func (c *EC2) CreateImageWithContext(ctx aws.Context, input *CreateImageInput, o return out, req.Send() } +const opCreateInstanceConnectEndpoint = "CreateInstanceConnectEndpoint" + +// CreateInstanceConnectEndpointRequest generates a "aws/request.Request" representing the +// client's request for the CreateInstanceConnectEndpoint operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateInstanceConnectEndpoint for more information on using the CreateInstanceConnectEndpoint +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the CreateInstanceConnectEndpointRequest method. +// req, resp := client.CreateInstanceConnectEndpointRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInstanceConnectEndpoint +func (c *EC2) CreateInstanceConnectEndpointRequest(input *CreateInstanceConnectEndpointInput) (req *request.Request, output *CreateInstanceConnectEndpointOutput) { + op := &request.Operation{ + Name: opCreateInstanceConnectEndpoint, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateInstanceConnectEndpointInput{} + } + + output = &CreateInstanceConnectEndpointOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateInstanceConnectEndpoint API operation for Amazon Elastic Compute Cloud. +// +// Creates an EC2 Instance Connect Endpoint. +// +// An EC2 Instance Connect Endpoint allows you to connect to an instance, without +// requiring the instance to have a public IPv4 address. For more information, +// see Connect to your instances without requiring a public IPv4 address using +// EC2 Instance Connect Endpoint (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Connect-using-EC2-Instance-Connect-Endpoint.html) +// in the Amazon EC2 User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation CreateInstanceConnectEndpoint for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInstanceConnectEndpoint +func (c *EC2) CreateInstanceConnectEndpoint(input *CreateInstanceConnectEndpointInput) (*CreateInstanceConnectEndpointOutput, error) { + req, out := c.CreateInstanceConnectEndpointRequest(input) + return out, req.Send() +} + +// CreateInstanceConnectEndpointWithContext is the same as CreateInstanceConnectEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See CreateInstanceConnectEndpoint for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) CreateInstanceConnectEndpointWithContext(ctx aws.Context, input *CreateInstanceConnectEndpointInput, opts ...request.Option) (*CreateInstanceConnectEndpointOutput, error) { + req, out := c.CreateInstanceConnectEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateInstanceEventWindow = "CreateInstanceEventWindow" // CreateInstanceEventWindowRequest generates a "aws/request.Request" representing the @@ -5855,10 +5978,11 @@ func (c *EC2) CreateInstanceExportTaskRequest(input *CreateInstanceExportTaskInp // // Exports a running or stopped instance to an Amazon S3 bucket. // -// For information about the supported operating systems, image formats, and -// known limitations for the types of instances you can export, see Exporting -// an instance as a VM Using VM Import/Export (https://docs.aws.amazon.com/vm-import/latest/userguide/vmexport.html) -// in the VM Import/Export User Guide. +// For information about the prerequisites for your Amazon S3 bucket, supported +// operating systems, image formats, and known limitations for the types of +// instances you can export, see Exporting an instance as a VM Using VM Import/Export +// (https://docs.aws.amazon.com/vm-import/latest/userguide/vmexport.html) in +// the VM Import/Export User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -5934,8 +6058,8 @@ func (c *EC2) CreateInternetGatewayRequest(input *CreateInternetGatewayInput) (r // Creates an internet gateway for use with a VPC. After creating the internet // gateway, you attach it to a VPC using AttachInternetGateway. // -// For more information about your VPC and internet gateway, see the Amazon -// Virtual Private Cloud User Guide (https://docs.aws.amazon.com/vpc/latest/userguide/). +// For more information, see Internet gateways (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -6967,7 +7091,17 @@ func (c *EC2) CreateNatGatewayRequest(input *CreateNatGatewayInput) (req *reques // overlapping networks. // // For more information, see NAT gateways (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. +// +// When you create a public NAT gateway and assign it an EIP or secondary EIPs, +// the network border group of the EIPs must match the network border group +// of the Availability Zone (AZ) that the public NAT gateway is in. If it's +// not the same, the NAT gateway will fail to launch. You can see the network +// border group for the subnet's AZ by viewing the details of the subnet. Similarly, +// you can view the network border group of an EIP by viewing the details of +// the EIP address. For more information about network border groups and EIPs, +// see Allocate an Elastic IP address (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-eips.html#allocate-eip) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -7043,8 +7177,8 @@ func (c *EC2) CreateNetworkAclRequest(input *CreateNetworkAclInput) (req *reques // Creates a network ACL in a VPC. Network ACLs provide an optional layer of // security (in addition to security groups) for the instances in your VPC. // -// For more information, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) -// in the Amazon Virtual Private Cloud User Guide. +// For more information, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -7133,8 +7267,8 @@ func (c *EC2) CreateNetworkAclEntryRequest(input *CreateNetworkAclEntryInput) (r // After you add an entry, you can't modify it; you must either replace it, // or create an entry and delete the old one. // -// For more information about network ACLs, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) -// in the Amazon Virtual Private Cloud User Guide. +// For more information about network ACLs, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -7955,7 +8089,7 @@ func (c *EC2) CreateRouteRequest(input *CreateRouteInput) (req *request.Request, // more specific, so we use that route to determine where to target the traffic. // // For more information about route tables, see Route tables (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -8032,7 +8166,7 @@ func (c *EC2) CreateRouteTableRequest(input *CreateRouteTableInput) (req *reques // you can add routes and associate the table with a subnet. // // For more information, see Route tables (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -8115,16 +8249,13 @@ func (c *EC2) CreateSecurityGroupRequest(input *CreateSecurityGroupInput) (req * // in the Amazon Virtual Private Cloud User Guide. // // When you create a security group, you specify a friendly name of your choice. -// You can have a security group for use in EC2-Classic with the same name as -// a security group for use in a VPC. However, you can't have two security groups -// for use in EC2-Classic with the same name or two security groups for use -// in a VPC with the same name. +// You can't have two security groups for the same VPC with the same name. // -// You have a default security group for use in EC2-Classic and a default security -// group for use in your VPC. If you don't specify a security group when you -// launch an instance, the instance is launched into the appropriate default -// security group. A default security group includes a default rule that grants -// instances unrestricted network access to each other. +// You have a default security group for use in your VPC. If you don't specify +// a security group when you launch an instance, the instance is launched into +// the appropriate default security group. A default security group includes +// a default rule that grants instances unrestricted network access to each +// other. // // You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress, // AuthorizeSecurityGroupEgress, RevokeSecurityGroupIngress, and RevokeSecurityGroupEgress. @@ -8132,10 +8263,6 @@ func (c *EC2) CreateSecurityGroupRequest(input *CreateSecurityGroupInput) (req * // For more information about VPC security group limits, see Amazon VPC Limits // (https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html). // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -8574,8 +8701,7 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // not available for your use. // // If you've associated an IPv6 CIDR block with your VPC, you can associate -// an IPv6 CIDR block with a subnet when you create it. The allowed block size -// for an IPv6 subnet is a /64 netmask. +// an IPv6 CIDR block with a subnet when you create it. // // If you add more than one subnet to a VPC, they're set up in a star topology // with a logical router in the middle. @@ -8585,7 +8711,7 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // all stopped), but no remaining IP addresses available. // // For more information, see Subnets (https://docs.aws.amazon.com/vpc/latest/userguide/configure-subnets.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -8658,9 +8784,11 @@ func (c *EC2) CreateSubnetCidrReservationRequest(input *CreateSubnetCidrReservat // CreateSubnetCidrReservation API operation for Amazon Elastic Compute Cloud. // -// Creates a subnet CIDR reservation. For information about subnet CIDR reservations, -// see Subnet CIDR reservations (https://docs.aws.amazon.com/vpc/latest/userguide/subnet-cidr-reservation.html) -// in the Amazon Virtual Private Cloud User Guide. +// Creates a subnet CIDR reservation. For more information, see Subnet CIDR +// reservations (https://docs.aws.amazon.com/vpc/latest/userguide/subnet-cidr-reservation.html) +// in the Amazon Virtual Private Cloud User Guide and Assign prefixes to network +// interfaces (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-prefix-eni.html) +// in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10070,10 +10198,9 @@ func (c *EC2) CreateVerifiedAccessGroupRequest(input *CreateVerifiedAccessGroupI // // An Amazon Web Services Verified Access group is a collection of Amazon Web // Services Verified Access endpoints who's associated applications have similar -// security requirements. Each instance within an Amazon Web Services Verified -// Access group shares an Amazon Web Services Verified Access policy. For example, -// you can group all Amazon Web Services Verified Access instances associated -// with “sales†applications together and use one common Amazon Web Services +// security requirements. Each instance within a Verified Access group shares +// an Verified Access policy. For example, you can group all Verified Access +// instances associated with "sales" applications together and use one common // Verified Access policy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10224,9 +10351,8 @@ func (c *EC2) CreateVerifiedAccessTrustProviderRequest(input *CreateVerifiedAcce // // A trust provider is a third-party entity that creates, maintains, and manages // identity information for users and devices. When an application request is -// made, the identity information sent by the trust provider will be evaluated -// by Amazon Web Services Verified Access, before allowing or denying the application -// request. +// made, the identity information sent by the trust provider is evaluated by +// Verified Access before allowing or denying the application request. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10390,24 +10516,24 @@ func (c *EC2) CreateVpcRequest(input *CreateVpcInput) (req *request.Request, out // CreateVpc API operation for Amazon Elastic Compute Cloud. // -// Creates a VPC with the specified CIDR blocks. For more information, see VPC -// CIDR blocks (https://docs.aws.amazon.com/vpc/latest/userguide/configure-your-vpc.html#vpc-cidr-blocks) -// in the Amazon Virtual Private Cloud User Guide. +// Creates a VPC with the specified CIDR blocks. For more information, see IP +// addressing for your VPCs and subnets (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-ip-addressing.html) +// in the Amazon VPC User Guide. // // You can optionally request an IPv6 CIDR block for the VPC. You can request -// an Amazon-provided IPv6 CIDR block from Amazon's pool of IPv6 addresses, -// or an IPv6 CIDR block from an IPv6 address pool that you provisioned through +// an Amazon-provided IPv6 CIDR block from Amazon's pool of IPv6 addresses or +// an IPv6 CIDR block from an IPv6 address pool that you provisioned through // bring your own IP addresses (BYOIP (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html)). // // By default, each instance that you launch in the VPC has the default DHCP // options, which include only a default DNS server that we provide (AmazonProvidedDNS). // For more information, see DHCP option sets (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // You can specify the instance tenancy value for the VPC when you create it. // You can't change this value for the VPC after you create it. For more information, // see Dedicated Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) -// in the Amazon Elastic Compute Cloud User Guide. +// in the Amazon EC2 User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10480,11 +10606,11 @@ func (c *EC2) CreateVpcEndpointRequest(input *CreateVpcEndpointInput) (req *requ // CreateVpcEndpoint API operation for Amazon Elastic Compute Cloud. // -// Creates a VPC endpoint for a specified service. An endpoint enables you to -// create a private connection between your VPC and the service. The service -// may be provided by Amazon Web Services, an Amazon Web Services Marketplace +// Creates a VPC endpoint. A VPC endpoint provides a private connection between +// the specified VPC and the specified endpoint service. You can use an endpoint +// service provided by Amazon Web Services, an Amazon Web Services Marketplace // Partner, or another Amazon Web Services account. For more information, see -// the Amazon Web Services PrivateLink Guide (https://docs.aws.amazon.com/vpc/latest/privatelink/). +// the Amazon Web Services PrivateLink User Guide (https://docs.aws.amazon.com/vpc/latest/privatelink/). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -11861,6 +11987,79 @@ func (c *EC2) DeleteFpgaImageWithContext(ctx aws.Context, input *DeleteFpgaImage return out, req.Send() } +const opDeleteInstanceConnectEndpoint = "DeleteInstanceConnectEndpoint" + +// DeleteInstanceConnectEndpointRequest generates a "aws/request.Request" representing the +// client's request for the DeleteInstanceConnectEndpoint operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteInstanceConnectEndpoint for more information on using the DeleteInstanceConnectEndpoint +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DeleteInstanceConnectEndpointRequest method. +// req, resp := client.DeleteInstanceConnectEndpointRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInstanceConnectEndpoint +func (c *EC2) DeleteInstanceConnectEndpointRequest(input *DeleteInstanceConnectEndpointInput) (req *request.Request, output *DeleteInstanceConnectEndpointOutput) { + op := &request.Operation{ + Name: opDeleteInstanceConnectEndpoint, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteInstanceConnectEndpointInput{} + } + + output = &DeleteInstanceConnectEndpointOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteInstanceConnectEndpoint API operation for Amazon Elastic Compute Cloud. +// +// Deletes the specified EC2 Instance Connect Endpoint. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DeleteInstanceConnectEndpoint for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInstanceConnectEndpoint +func (c *EC2) DeleteInstanceConnectEndpoint(input *DeleteInstanceConnectEndpointInput) (*DeleteInstanceConnectEndpointOutput, error) { + req, out := c.DeleteInstanceConnectEndpointRequest(input) + return out, req.Send() +} + +// DeleteInstanceConnectEndpointWithContext is the same as DeleteInstanceConnectEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteInstanceConnectEndpoint for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DeleteInstanceConnectEndpointWithContext(ctx aws.Context, input *DeleteInstanceConnectEndpointInput, opts ...request.Option) (*DeleteInstanceConnectEndpointOutput, error) { + req, out := c.DeleteInstanceConnectEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteInstanceEventWindow = "DeleteInstanceEventWindow" // DeleteInstanceEventWindowRequest generates a "aws/request.Request" representing the @@ -12358,7 +12557,6 @@ func (c *EC2) DeleteKeyPairRequest(input *DeleteKeyPairInput) (req *request.Requ output = &DeleteKeyPairOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(ec2query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -12511,10 +12709,19 @@ func (c *EC2) DeleteLaunchTemplateVersionsRequest(input *DeleteLaunchTemplateVer // DeleteLaunchTemplateVersions API operation for Amazon Elastic Compute Cloud. // -// Deletes one or more versions of a launch template. You cannot delete the -// default version of a launch template; you must first assign a different version -// as the default. If the default version is the only version for the launch -// template, you must delete the entire launch template using DeleteLaunchTemplate. +// Deletes one or more versions of a launch template. +// +// You can't delete the default version of a launch template; you must first +// assign a different version as the default. If the default version is the +// only version for the launch template, you must delete the entire launch template +// using DeleteLaunchTemplate. +// +// You can delete up to 200 launch template versions in a single request. To +// delete more than 200 versions in a single request, use DeleteLaunchTemplate, +// which deletes the launch template and all of its versions. +// +// For more information, see Delete a launch template version (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-launch-template-versions.html#delete-launch-template-version) +// in the EC2 User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -14001,13 +14208,9 @@ func (c *EC2) DeleteSecurityGroupRequest(input *DeleteSecurityGroupInput) (req * // // Deletes a security group. // -// If you attempt to delete a security group that is associated with an instance, -// or is referenced by another security group, the operation fails with InvalidGroup.InUse -// in EC2-Classic or DependencyViolation in EC2-VPC. -// -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// If you attempt to delete a security group that is associated with an instance +// or network interface or is referenced by another security group, the operation +// fails with DependencyViolation. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -15950,7 +16153,9 @@ func (c *EC2) DeleteVpcRequest(input *DeleteVpcInput) (req *request.Request, out // that are associated with the VPC before you can delete it. For example, you // must terminate all instances running in the VPC, delete all security groups // associated with the VPC (except the default one), delete all route tables -// associated with the VPC (except the default one), and so on. +// associated with the VPC (except the default one), and so on. When you delete +// the VPC, it deletes the VPC's default security group, network ACL, and route +// table. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -16258,7 +16463,7 @@ func (c *EC2) DeleteVpcPeeringConnectionRequest(input *DeleteVpcPeeringConnectio // the owner of the accepter VPC can delete the VPC peering connection if it's // in the active state. The owner of the requester VPC can delete a VPC peering // connection in the pending-acceptance state. You cannot delete a VPC peering -// connection that's in the failed state. +// connection that's in the failed or rejected state. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -16608,6 +16813,84 @@ func (c *EC2) DeprovisionByoipCidrWithContext(ctx aws.Context, input *Deprovisio return out, req.Send() } +const opDeprovisionIpamByoasn = "DeprovisionIpamByoasn" + +// DeprovisionIpamByoasnRequest generates a "aws/request.Request" representing the +// client's request for the DeprovisionIpamByoasn operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeprovisionIpamByoasn for more information on using the DeprovisionIpamByoasn +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DeprovisionIpamByoasnRequest method. +// req, resp := client.DeprovisionIpamByoasnRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeprovisionIpamByoasn +func (c *EC2) DeprovisionIpamByoasnRequest(input *DeprovisionIpamByoasnInput) (req *request.Request, output *DeprovisionIpamByoasnOutput) { + op := &request.Operation{ + Name: opDeprovisionIpamByoasn, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeprovisionIpamByoasnInput{} + } + + output = &DeprovisionIpamByoasnOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeprovisionIpamByoasn API operation for Amazon Elastic Compute Cloud. +// +// Deprovisions your Autonomous System Number (ASN) from your Amazon Web Services +// account. This action can only be called after any BYOIP CIDR associations +// are removed from your Amazon Web Services account with DisassociateIpamByoasn +// (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIpamByoasn.html). +// For more information, see Tutorial: Bring your ASN to IPAM (https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-byoasn.html) +// in the Amazon VPC IPAM guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DeprovisionIpamByoasn for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeprovisionIpamByoasn +func (c *EC2) DeprovisionIpamByoasn(input *DeprovisionIpamByoasnInput) (*DeprovisionIpamByoasnOutput, error) { + req, out := c.DeprovisionIpamByoasnRequest(input) + return out, req.Send() +} + +// DeprovisionIpamByoasnWithContext is the same as DeprovisionIpamByoasn with the addition of +// the ability to pass a context and additional request options. +// +// See DeprovisionIpamByoasn for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DeprovisionIpamByoasnWithContext(ctx aws.Context, input *DeprovisionIpamByoasnInput, opts ...request.Option) (*DeprovisionIpamByoasnOutput, error) { + req, out := c.DeprovisionIpamByoasnRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeprovisionIpamPoolCidr = "DeprovisionIpamPoolCidr" // DeprovisionIpamPoolCidrRequest generates a "aws/request.Request" representing the @@ -17114,9 +17397,6 @@ func (c *EC2) DescribeAccountAttributesRequest(input *DescribeAccountAttributesI // Describes attributes of your Amazon Web Services account. The following are // the supported account attributes: // -// - supported-platforms: Indicates whether your account can launch instances -// into EC2-Classic and EC2-VPC, or only into EC2-VPC. -// // - default-vpc: The ID of the default VPC for your account, or none. // // - max-instances: This attribute is no longer supported. The returned value @@ -17124,19 +17404,16 @@ func (c *EC2) DescribeAccountAttributesRequest(input *DescribeAccountAttributesI // For more information, see On-Demand Instance Limits (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-on-demand-instances.html#ec2-on-demand-instances-limits) // in the Amazon Elastic Compute Cloud User Guide. // -// - vpc-max-security-groups-per-interface: The maximum number of security -// groups that you can assign to a network interface. -// // - max-elastic-ips: The maximum number of Elastic IP addresses that you -// can allocate for use with EC2-Classic. +// can allocate. +// +// - supported-platforms: This attribute is deprecated. // // - vpc-max-elastic-ips: The maximum number of Elastic IP addresses that -// you can allocate for use with EC2-VPC. +// you can allocate. // -// We are retiring EC2-Classic on August 15, 2022. We recommend that you migrate -// from EC2-Classic to a VPC. For more information, see Migrate from EC2-Classic -// to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon EC2 User Guide. +// - vpc-max-security-groups-per-interface: The maximum number of security +// groups that you can assign to a network interface. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -17219,6 +17496,15 @@ func (c *EC2) DescribeAddressTransfersRequest(input *DescribeAddressTransfersInp // Elastic IP addresses (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-eips.html#transfer-EIPs-intro) // in the Amazon Virtual Private Cloud User Guide. // +// When you transfer an Elastic IP address, there is a two-step handshake between +// the source and transfer Amazon Web Services accounts. When the source account +// starts the transfer, the transfer account has seven days to accept the Elastic +// IP address transfer. During those seven days, the source account can view +// the pending transfer by using this action. After seven days, the transfer +// expires and ownership of the Elastic IP address returns to the source account. +// Accepted transfers are visible to the source account for three days after +// the transfers have been accepted. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -17343,14 +17629,6 @@ func (c *EC2) DescribeAddressesRequest(input *DescribeAddressesInput) (req *requ // // Describes the specified Elastic IP addresses or all of your Elastic IP addresses. // -// An Elastic IP address is for use in either the EC2-Classic platform or in -// a VPC. For more information, see Elastic IP Addresses (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) -// in the Amazon Elastic Compute Cloud User Guide. -// -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -18017,6 +18295,137 @@ func (c *EC2) DescribeByoipCidrsPagesWithContext(ctx aws.Context, input *Describ return p.Err() } +const opDescribeCapacityBlockOfferings = "DescribeCapacityBlockOfferings" + +// DescribeCapacityBlockOfferingsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeCapacityBlockOfferings operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeCapacityBlockOfferings for more information on using the DescribeCapacityBlockOfferings +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DescribeCapacityBlockOfferingsRequest method. +// req, resp := client.DescribeCapacityBlockOfferingsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCapacityBlockOfferings +func (c *EC2) DescribeCapacityBlockOfferingsRequest(input *DescribeCapacityBlockOfferingsInput) (req *request.Request, output *DescribeCapacityBlockOfferingsOutput) { + op := &request.Operation{ + Name: opDescribeCapacityBlockOfferings, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeCapacityBlockOfferingsInput{} + } + + output = &DescribeCapacityBlockOfferingsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeCapacityBlockOfferings API operation for Amazon Elastic Compute Cloud. +// +// Describes Capacity Block offerings available for purchase. With Capacity +// Blocks, you purchase a specific instance type for a period of time. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DescribeCapacityBlockOfferings for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCapacityBlockOfferings +func (c *EC2) DescribeCapacityBlockOfferings(input *DescribeCapacityBlockOfferingsInput) (*DescribeCapacityBlockOfferingsOutput, error) { + req, out := c.DescribeCapacityBlockOfferingsRequest(input) + return out, req.Send() +} + +// DescribeCapacityBlockOfferingsWithContext is the same as DescribeCapacityBlockOfferings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCapacityBlockOfferings for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeCapacityBlockOfferingsWithContext(ctx aws.Context, input *DescribeCapacityBlockOfferingsInput, opts ...request.Option) (*DescribeCapacityBlockOfferingsOutput, error) { + req, out := c.DescribeCapacityBlockOfferingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeCapacityBlockOfferingsPages iterates over the pages of a DescribeCapacityBlockOfferings operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeCapacityBlockOfferings method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeCapacityBlockOfferings operation. +// pageNum := 0 +// err := client.DescribeCapacityBlockOfferingsPages(params, +// func(page *ec2.DescribeCapacityBlockOfferingsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +func (c *EC2) DescribeCapacityBlockOfferingsPages(input *DescribeCapacityBlockOfferingsInput, fn func(*DescribeCapacityBlockOfferingsOutput, bool) bool) error { + return c.DescribeCapacityBlockOfferingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCapacityBlockOfferingsPagesWithContext same as DescribeCapacityBlockOfferingsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeCapacityBlockOfferingsPagesWithContext(ctx aws.Context, input *DescribeCapacityBlockOfferingsInput, fn func(*DescribeCapacityBlockOfferingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCapacityBlockOfferingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCapacityBlockOfferingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeCapacityBlockOfferingsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeCapacityReservationFleets = "DescribeCapacityReservationFleets" // DescribeCapacityReservationFleetsRequest generates a "aws/request.Request" representing the @@ -18458,15 +18867,13 @@ func (c *EC2) DescribeClassicLinkInstancesRequest(input *DescribeClassicLinkInst // DescribeClassicLinkInstances API operation for Amazon Elastic Compute Cloud. // +// This action is deprecated. +// // Describes one or more of your linked EC2-Classic instances. This request // only returns information about EC2-Classic instances linked to a VPC through // ClassicLink. You cannot use this request to return information about other // instances. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -19533,7 +19940,7 @@ func (c *EC2) DescribeDhcpOptionsRequest(input *DescribeDhcpOptionsInput) (req * // Describes one or more of your DHCP options sets. // // For more information, see DHCP options sets (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -20072,7 +20479,7 @@ func (c *EC2) DescribeFastLaunchImagesRequest(input *DescribeFastLaunchImagesInp // DescribeFastLaunchImages API operation for Amazon Elastic Compute Cloud. // -// Describe details for Windows AMIs that are configured for faster launching. +// Describe details for Windows AMIs that are configured for Windows fast launch. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -22176,6 +22583,137 @@ func (c *EC2) DescribeInstanceAttributeWithContext(ctx aws.Context, input *Descr return out, req.Send() } +const opDescribeInstanceConnectEndpoints = "DescribeInstanceConnectEndpoints" + +// DescribeInstanceConnectEndpointsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeInstanceConnectEndpoints operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeInstanceConnectEndpoints for more information on using the DescribeInstanceConnectEndpoints +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DescribeInstanceConnectEndpointsRequest method. +// req, resp := client.DescribeInstanceConnectEndpointsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceConnectEndpoints +func (c *EC2) DescribeInstanceConnectEndpointsRequest(input *DescribeInstanceConnectEndpointsInput) (req *request.Request, output *DescribeInstanceConnectEndpointsOutput) { + op := &request.Operation{ + Name: opDescribeInstanceConnectEndpoints, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeInstanceConnectEndpointsInput{} + } + + output = &DescribeInstanceConnectEndpointsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeInstanceConnectEndpoints API operation for Amazon Elastic Compute Cloud. +// +// Describes the specified EC2 Instance Connect Endpoints or all EC2 Instance +// Connect Endpoints. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DescribeInstanceConnectEndpoints for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceConnectEndpoints +func (c *EC2) DescribeInstanceConnectEndpoints(input *DescribeInstanceConnectEndpointsInput) (*DescribeInstanceConnectEndpointsOutput, error) { + req, out := c.DescribeInstanceConnectEndpointsRequest(input) + return out, req.Send() +} + +// DescribeInstanceConnectEndpointsWithContext is the same as DescribeInstanceConnectEndpoints with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceConnectEndpoints for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeInstanceConnectEndpointsWithContext(ctx aws.Context, input *DescribeInstanceConnectEndpointsInput, opts ...request.Option) (*DescribeInstanceConnectEndpointsOutput, error) { + req, out := c.DescribeInstanceConnectEndpointsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeInstanceConnectEndpointsPages iterates over the pages of a DescribeInstanceConnectEndpoints operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstanceConnectEndpoints method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstanceConnectEndpoints operation. +// pageNum := 0 +// err := client.DescribeInstanceConnectEndpointsPages(params, +// func(page *ec2.DescribeInstanceConnectEndpointsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +func (c *EC2) DescribeInstanceConnectEndpointsPages(input *DescribeInstanceConnectEndpointsInput, fn func(*DescribeInstanceConnectEndpointsOutput, bool) bool) error { + return c.DescribeInstanceConnectEndpointsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstanceConnectEndpointsPagesWithContext same as DescribeInstanceConnectEndpointsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeInstanceConnectEndpointsPagesWithContext(ctx aws.Context, input *DescribeInstanceConnectEndpointsInput, fn func(*DescribeInstanceConnectEndpointsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstanceConnectEndpointsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceConnectEndpointsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstanceConnectEndpointsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstanceCreditSpecifications = "DescribeInstanceCreditSpecifications" // DescribeInstanceCreditSpecificationsRequest generates a "aws/request.Request" representing the @@ -22694,6 +23232,151 @@ func (c *EC2) DescribeInstanceStatusPagesWithContext(ctx aws.Context, input *Des return p.Err() } +const opDescribeInstanceTopology = "DescribeInstanceTopology" + +// DescribeInstanceTopologyRequest generates a "aws/request.Request" representing the +// client's request for the DescribeInstanceTopology operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeInstanceTopology for more information on using the DescribeInstanceTopology +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DescribeInstanceTopologyRequest method. +// req, resp := client.DescribeInstanceTopologyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceTopology +func (c *EC2) DescribeInstanceTopologyRequest(input *DescribeInstanceTopologyInput) (req *request.Request, output *DescribeInstanceTopologyOutput) { + op := &request.Operation{ + Name: opDescribeInstanceTopology, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeInstanceTopologyInput{} + } + + output = &DescribeInstanceTopologyOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeInstanceTopology API operation for Amazon Elastic Compute Cloud. +// +// Describes a tree-based hierarchy that represents the physical host placement +// of your EC2 instances within an Availability Zone or Local Zone. You can +// use this information to determine the relative proximity of your EC2 instances +// within the Amazon Web Services network to support your tightly coupled workloads. +// +// Limitations +// +// - Supported zones Availability Zone Local Zone +// +// - Supported instance types hpc6a.48xlarge | hpc6id.32xlarge | hpc7a.12xlarge +// | hpc7a.24xlarge | hpc7a.48xlarge | hpc7a.96xlarge | hpc7g.4xlarge | hpc7g.8xlarge +// | hpc7g.16xlarge p3dn.24xlarge | p4d.24xlarge | p4de.24xlarge | p5.48xlarge +// trn1.2xlarge | trn1.32xlarge | trn1n.32xlarge +// +// For more information, see Amazon EC2 instance topology (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-topology.html) +// in the Amazon EC2 User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DescribeInstanceTopology for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceTopology +func (c *EC2) DescribeInstanceTopology(input *DescribeInstanceTopologyInput) (*DescribeInstanceTopologyOutput, error) { + req, out := c.DescribeInstanceTopologyRequest(input) + return out, req.Send() +} + +// DescribeInstanceTopologyWithContext is the same as DescribeInstanceTopology with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceTopology for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeInstanceTopologyWithContext(ctx aws.Context, input *DescribeInstanceTopologyInput, opts ...request.Option) (*DescribeInstanceTopologyOutput, error) { + req, out := c.DescribeInstanceTopologyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeInstanceTopologyPages iterates over the pages of a DescribeInstanceTopology operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstanceTopology method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstanceTopology operation. +// pageNum := 0 +// err := client.DescribeInstanceTopologyPages(params, +// func(page *ec2.DescribeInstanceTopologyOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +func (c *EC2) DescribeInstanceTopologyPages(input *DescribeInstanceTopologyInput, fn func(*DescribeInstanceTopologyOutput, bool) bool) error { + return c.DescribeInstanceTopologyPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstanceTopologyPagesWithContext same as DescribeInstanceTopologyPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeInstanceTopologyPagesWithContext(ctx aws.Context, input *DescribeInstanceTopologyInput, fn func(*DescribeInstanceTopologyOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstanceTopologyInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceTopologyRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstanceTopologyOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstanceTypeOfferings = "DescribeInstanceTypeOfferings" // DescribeInstanceTypeOfferingsRequest generates a "aws/request.Request" representing the @@ -23236,6 +23919,82 @@ func (c *EC2) DescribeInternetGatewaysPagesWithContext(ctx aws.Context, input *D return p.Err() } +const opDescribeIpamByoasn = "DescribeIpamByoasn" + +// DescribeIpamByoasnRequest generates a "aws/request.Request" representing the +// client's request for the DescribeIpamByoasn operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeIpamByoasn for more information on using the DescribeIpamByoasn +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DescribeIpamByoasnRequest method. +// req, resp := client.DescribeIpamByoasnRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIpamByoasn +func (c *EC2) DescribeIpamByoasnRequest(input *DescribeIpamByoasnInput) (req *request.Request, output *DescribeIpamByoasnOutput) { + op := &request.Operation{ + Name: opDescribeIpamByoasn, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeIpamByoasnInput{} + } + + output = &DescribeIpamByoasnOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeIpamByoasn API operation for Amazon Elastic Compute Cloud. +// +// Describes your Autonomous System Numbers (ASNs), their provisioning statuses, +// and the BYOIP CIDRs with which they are associated. For more information, +// see Tutorial: Bring your ASN to IPAM (https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-byoasn.html) +// in the Amazon VPC IPAM guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DescribeIpamByoasn for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIpamByoasn +func (c *EC2) DescribeIpamByoasn(input *DescribeIpamByoasnInput) (*DescribeIpamByoasnOutput, error) { + req, out := c.DescribeIpamByoasnRequest(input) + return out, req.Send() +} + +// DescribeIpamByoasnWithContext is the same as DescribeIpamByoasn with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeIpamByoasn for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeIpamByoasnWithContext(ctx aws.Context, input *DescribeIpamByoasnInput, opts ...request.Option) (*DescribeIpamByoasnOutput, error) { + req, out := c.DescribeIpamByoasnRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeIpamPools = "DescribeIpamPools" // DescribeIpamPoolsRequest generates a "aws/request.Request" representing the @@ -25146,6 +25905,79 @@ func (c *EC2) DescribeLocalGatewaysPagesWithContext(ctx aws.Context, input *Desc return p.Err() } +const opDescribeLockedSnapshots = "DescribeLockedSnapshots" + +// DescribeLockedSnapshotsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeLockedSnapshots operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeLockedSnapshots for more information on using the DescribeLockedSnapshots +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DescribeLockedSnapshotsRequest method. +// req, resp := client.DescribeLockedSnapshotsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLockedSnapshots +func (c *EC2) DescribeLockedSnapshotsRequest(input *DescribeLockedSnapshotsInput) (req *request.Request, output *DescribeLockedSnapshotsOutput) { + op := &request.Operation{ + Name: opDescribeLockedSnapshots, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeLockedSnapshotsInput{} + } + + output = &DescribeLockedSnapshotsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeLockedSnapshots API operation for Amazon Elastic Compute Cloud. +// +// Describes the lock status for a snapshot. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DescribeLockedSnapshots for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLockedSnapshots +func (c *EC2) DescribeLockedSnapshots(input *DescribeLockedSnapshotsInput) (*DescribeLockedSnapshotsOutput, error) { + req, out := c.DescribeLockedSnapshotsRequest(input) + return out, req.Send() +} + +// DescribeLockedSnapshotsWithContext is the same as DescribeLockedSnapshots with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLockedSnapshots for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeLockedSnapshotsWithContext(ctx aws.Context, input *DescribeLockedSnapshotsInput, opts ...request.Option) (*DescribeLockedSnapshotsOutput, error) { + req, out := c.DescribeLockedSnapshotsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeManagedPrefixLists = "DescribeManagedPrefixLists" // DescribeManagedPrefixListsRequest generates a "aws/request.Request" representing the @@ -25328,9 +26160,11 @@ func (c *EC2) DescribeMovingAddressesRequest(input *DescribeMovingAddressesInput // DescribeMovingAddresses API operation for Amazon Elastic Compute Cloud. // -// Describes your Elastic IP addresses that are being moved to the EC2-VPC platform, -// or that are being restored to the EC2-Classic platform. This request does -// not return information about any other Elastic IP addresses in your account. +// This action is deprecated. +// +// Describes your Elastic IP addresses that are being moved from or being restored +// to the EC2-Classic platform. This request does not return information about +// any other Elastic IP addresses in your account. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -25592,8 +26426,8 @@ func (c *EC2) DescribeNetworkAclsRequest(input *DescribeNetworkAclsInput) (req * // // Describes one or more of your network ACLs. // -// For more information, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) -// in the Amazon Virtual Private Cloud User Guide. +// For more information, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -26449,6 +27283,10 @@ func (c *EC2) DescribeNetworkInterfacesRequest(input *DescribeNetworkInterfacesI // // Describes one or more of your network interfaces. // +// If you have a large number of network interfaces, the operation fails unless +// you use pagination or one of the following filters: group-id, mac-address, +// private-dns-name, private-ip-address, private-dns-name, subnet-id, or vpc-id. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -27727,7 +28565,7 @@ func (c *EC2) DescribeRouteTablesRequest(input *DescribeRouteTablesInput) (req * // implicit associations. // // For more information, see Route tables (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -28119,8 +28957,9 @@ func (c *EC2) DescribeSecurityGroupReferencesRequest(input *DescribeSecurityGrou // DescribeSecurityGroupReferences API operation for Amazon Elastic Compute Cloud. // -// [VPC only] Describes the VPCs on the other side of a VPC peering connection -// that are referencing the security groups you've specified in this request. +// Describes the VPCs on the other side of a VPC peering connection or the VPCs +// attached to a transit gateway that are referencing the security groups you've +// specified in this request. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -28331,17 +29170,6 @@ func (c *EC2) DescribeSecurityGroupsRequest(input *DescribeSecurityGroupsInput) // // Describes the specified security groups or all of your security groups. // -// A security group is for use with instances either in the EC2-Classic platform -// or in a specific VPC. For more information, see Amazon EC2 security groups -// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) -// in the Amazon Elastic Compute Cloud User Guide and Security groups for your -// VPC (https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) -// in the Amazon Virtual Private Cloud User Guide. -// -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -29499,10 +30327,14 @@ func (c *EC2) DescribeStaleSecurityGroupsRequest(input *DescribeStaleSecurityGro // DescribeStaleSecurityGroups API operation for Amazon Elastic Compute Cloud. // -// [VPC only] Describes the stale security group rules for security groups in -// a specified VPC. Rules are stale when they reference a deleted security group -// in the same VPC or in a peer VPC, or if they reference a security group in -// a peer VPC for which the VPC peering connection has been deleted. +// Describes the stale security group rules for security groups in a specified +// VPC. Rules are stale when they reference a deleted security group in the +// same VPC, peered VPC, or in separate VPCs attached to a transit gateway (with +// security group referencing support (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#create-tgw) +// enabled). Rules can also be stale if they reference a security group in a +// peer VPC for which the VPC peering connection has been deleted or if they +// reference a security group in a VPC that has been detached from a transit +// gateway. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -29780,8 +30612,8 @@ func (c *EC2) DescribeSubnetsRequest(input *DescribeSubnetsInput) (req *request. // // Describes one or more of your subnets. // -// For more information, see Your VPC and subnets (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) -// in the Amazon Virtual Private Cloud User Guide. +// For more information, see Subnets (https://docs.aws.amazon.com/vpc/latest/userguide/configure-subnets.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -31741,9 +32573,6 @@ func (c *EC2) DescribeTrunkInterfaceAssociationsRequest(input *DescribeTrunkInte // DescribeTrunkInterfaceAssociations API operation for Amazon Elastic Compute Cloud. // -// This API action is currently in limited preview only. If you are interested -// in using this feature, contact your account manager. -// // Describes one or more network interface trunk associations. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -31874,7 +32703,7 @@ func (c *EC2) DescribeVerifiedAccessEndpointsRequest(input *DescribeVerifiedAcce // DescribeVerifiedAccessEndpoints API operation for Amazon Elastic Compute Cloud. // -// Describe Amazon Web Services Verified Access endpoints. +// Describes the specified Amazon Web Services Verified Access endpoints. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32004,7 +32833,7 @@ func (c *EC2) DescribeVerifiedAccessGroupsRequest(input *DescribeVerifiedAccessG // DescribeVerifiedAccessGroups API operation for Amazon Elastic Compute Cloud. // -// Describe details of existing Verified Access groups. +// Describes the specified Verified Access groups. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32134,8 +32963,7 @@ func (c *EC2) DescribeVerifiedAccessInstanceLoggingConfigurationsRequest(input * // DescribeVerifiedAccessInstanceLoggingConfigurations API operation for Amazon Elastic Compute Cloud. // -// Describes the current logging configuration for the Amazon Web Services Verified -// Access instances. +// Describes the specified Amazon Web Services Verified Access instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32265,7 +33093,7 @@ func (c *EC2) DescribeVerifiedAccessInstancesRequest(input *DescribeVerifiedAcce // DescribeVerifiedAccessInstances API operation for Amazon Elastic Compute Cloud. // -// Describe Verified Access instances. +// Describes the specified Amazon Web Services Verified Access instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32395,7 +33223,7 @@ func (c *EC2) DescribeVerifiedAccessTrustProvidersRequest(input *DescribeVerifie // DescribeVerifiedAccessTrustProviders API operation for Amazon Elastic Compute Cloud. // -// Describe details of existing Verified Access trust providers. +// Describes the specified Amazon Web Services Verified Access trust providers. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -33113,11 +33941,9 @@ func (c *EC2) DescribeVpcClassicLinkRequest(input *DescribeVpcClassicLinkInput) // DescribeVpcClassicLink API operation for Amazon Elastic Compute Cloud. // -// Describes the ClassicLink status of one or more VPCs. +// This action is deprecated. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// Describes the ClassicLink status of the specified VPCs. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -33196,17 +34022,13 @@ func (c *EC2) DescribeVpcClassicLinkDnsSupportRequest(input *DescribeVpcClassicL // DescribeVpcClassicLinkDnsSupport API operation for Amazon Elastic Compute Cloud. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// This action is deprecated. // // Describes the ClassicLink DNS support status of one or more VPCs. If enabled, // the DNS hostname of a linked EC2-Classic instance resolves to its private // IP address when addressed from an instance in the VPC to which it's linked. // Similarly, the DNS hostname of an instance in a VPC resolves to its private -// IP address when addressed from a linked EC2-Classic instance. For more information, -// see ClassicLink (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) -// in the Amazon Elastic Compute Cloud User Guide. +// IP address when addressed from a linked EC2-Classic instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -34475,9 +35297,7 @@ func (c *EC2) DetachClassicLinkVpcRequest(input *DetachClassicLinkVpcInput) (req // DetachClassicLinkVpc API operation for Amazon Elastic Compute Cloud. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// This action is deprecated. // // Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance // has been unlinked, the VPC security groups are no longer associated with @@ -34704,7 +35524,8 @@ func (c *EC2) DetachVerifiedAccessTrustProviderRequest(input *DetachVerifiedAcce // DetachVerifiedAccessTrustProvider API operation for Amazon Elastic Compute Cloud. // -// Detach a trust provider from an Amazon Web Services Verified Access instance. +// Detaches the specified Amazon Web Services Verified Access trust provider +// from the specified Amazon Web Services Verified Access instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -34789,6 +35610,10 @@ func (c *EC2) DetachVolumeRequest(input *DetachVolumeInput) (req *request.Reques // When a volume with an Amazon Web Services Marketplace product code is detached // from an instance, the product code is no longer associated with the instance. // +// You can't detach or force detach volumes that are attached to Amazon ECS +// or Fargate tasks. Attempting to do this results in the UnsupportedOperationException +// exception with the Unable to detach volume attached to ECS tasks error message. +// // For more information, see Detach an Amazon EBS volume (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -35174,12 +35999,13 @@ func (c *EC2) DisableFastLaunchRequest(input *DisableFastLaunchInput) (req *requ // DisableFastLaunch API operation for Amazon Elastic Compute Cloud. // -// Discontinue faster launching for a Windows AMI, and clean up existing pre-provisioned -// snapshots. When you disable faster launching, the AMI uses the standard launch -// process for each instance. All pre-provisioned snapshots must be removed -// before you can enable faster launching again. +// Discontinue Windows fast launch for a Windows AMI, and clean up existing +// pre-provisioned snapshots. After you disable Windows fast launch, the AMI +// uses the standard launch process for each new instance. Amazon EC2 must remove +// all pre-provisioned snapshots before you can enable Windows fast launch again. // -// To change these settings, you must own the AMI. +// You can only change these settings for Windows AMIs that you own or that +// have been shared with you. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -35283,6 +36109,178 @@ func (c *EC2) DisableFastSnapshotRestoresWithContext(ctx aws.Context, input *Dis return out, req.Send() } +const opDisableImage = "DisableImage" + +// DisableImageRequest generates a "aws/request.Request" representing the +// client's request for the DisableImage operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisableImage for more information on using the DisableImage +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DisableImageRequest method. +// req, resp := client.DisableImageRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableImage +func (c *EC2) DisableImageRequest(input *DisableImageInput) (req *request.Request, output *DisableImageOutput) { + op := &request.Operation{ + Name: opDisableImage, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DisableImageInput{} + } + + output = &DisableImageOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisableImage API operation for Amazon Elastic Compute Cloud. +// +// Sets the AMI state to disabled and removes all launch permissions from the +// AMI. A disabled AMI can't be used for instance launches. +// +// A disabled AMI can't be shared. If an AMI was public or previously shared, +// it is made private. If an AMI was shared with an Amazon Web Services account, +// organization, or Organizational Unit, they lose access to the disabled AMI. +// +// A disabled AMI does not appear in DescribeImages (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeImages.html) +// API calls by default. +// +// Only the AMI owner can disable an AMI. +// +// You can re-enable a disabled AMI using EnableImage (http://amazonaws.com/AWSEC2/latest/APIReference/API_EnableImage.html). +// +// For more information, see Disable an AMI (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/disable-an-ami.html) +// in the Amazon EC2 User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DisableImage for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableImage +func (c *EC2) DisableImage(input *DisableImageInput) (*DisableImageOutput, error) { + req, out := c.DisableImageRequest(input) + return out, req.Send() +} + +// DisableImageWithContext is the same as DisableImage with the addition of +// the ability to pass a context and additional request options. +// +// See DisableImage for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DisableImageWithContext(ctx aws.Context, input *DisableImageInput, opts ...request.Option) (*DisableImageOutput, error) { + req, out := c.DisableImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDisableImageBlockPublicAccess = "DisableImageBlockPublicAccess" + +// DisableImageBlockPublicAccessRequest generates a "aws/request.Request" representing the +// client's request for the DisableImageBlockPublicAccess operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisableImageBlockPublicAccess for more information on using the DisableImageBlockPublicAccess +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DisableImageBlockPublicAccessRequest method. +// req, resp := client.DisableImageBlockPublicAccessRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableImageBlockPublicAccess +func (c *EC2) DisableImageBlockPublicAccessRequest(input *DisableImageBlockPublicAccessInput) (req *request.Request, output *DisableImageBlockPublicAccessOutput) { + op := &request.Operation{ + Name: opDisableImageBlockPublicAccess, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DisableImageBlockPublicAccessInput{} + } + + output = &DisableImageBlockPublicAccessOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisableImageBlockPublicAccess API operation for Amazon Elastic Compute Cloud. +// +// Disables block public access for AMIs at the account level in the specified +// Amazon Web Services Region. This removes the block public access restriction +// from your account. With the restriction removed, you can publicly share your +// AMIs in the specified Amazon Web Services Region. +// +// The API can take up to 10 minutes to configure this setting. During this +// time, if you run GetImageBlockPublicAccessState (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_GetImageBlockPublicAccessState.html), +// the response will be block-new-sharing. When the API has completed the configuration, +// the response will be unblocked. +// +// For more information, see Block public access to your AMIs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharingamis-intro.html#block-public-access-to-amis) +// in the Amazon EC2 User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DisableImageBlockPublicAccess for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableImageBlockPublicAccess +func (c *EC2) DisableImageBlockPublicAccess(input *DisableImageBlockPublicAccessInput) (*DisableImageBlockPublicAccessOutput, error) { + req, out := c.DisableImageBlockPublicAccessRequest(input) + return out, req.Send() +} + +// DisableImageBlockPublicAccessWithContext is the same as DisableImageBlockPublicAccess with the addition of +// the ability to pass a context and additional request options. +// +// See DisableImageBlockPublicAccess for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DisableImageBlockPublicAccessWithContext(ctx aws.Context, input *DisableImageBlockPublicAccessInput, opts ...request.Option) (*DisableImageBlockPublicAccessOutput, error) { + req, out := c.DisableImageBlockPublicAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDisableImageDeprecation = "DisableImageDeprecation" // DisableImageDeprecationRequest generates a "aws/request.Request" representing the @@ -35511,6 +36509,89 @@ func (c *EC2) DisableSerialConsoleAccessWithContext(ctx aws.Context, input *Disa return out, req.Send() } +const opDisableSnapshotBlockPublicAccess = "DisableSnapshotBlockPublicAccess" + +// DisableSnapshotBlockPublicAccessRequest generates a "aws/request.Request" representing the +// client's request for the DisableSnapshotBlockPublicAccess operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisableSnapshotBlockPublicAccess for more information on using the DisableSnapshotBlockPublicAccess +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DisableSnapshotBlockPublicAccessRequest method. +// req, resp := client.DisableSnapshotBlockPublicAccessRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableSnapshotBlockPublicAccess +func (c *EC2) DisableSnapshotBlockPublicAccessRequest(input *DisableSnapshotBlockPublicAccessInput) (req *request.Request, output *DisableSnapshotBlockPublicAccessOutput) { + op := &request.Operation{ + Name: opDisableSnapshotBlockPublicAccess, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DisableSnapshotBlockPublicAccessInput{} + } + + output = &DisableSnapshotBlockPublicAccessOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisableSnapshotBlockPublicAccess API operation for Amazon Elastic Compute Cloud. +// +// Disables the block public access for snapshots setting at the account level +// for the specified Amazon Web Services Region. After you disable block public +// access for snapshots in a Region, users can publicly share snapshots in that +// Region. +// +// If block public access is enabled in block-all-sharing mode, and you disable +// block public access, all snapshots that were previously publicly shared are +// no longer treated as private and they become publicly accessible again. +// +// For more information, see Block public access for snapshots (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-public-access-snapshots.html) +// in the Amazon Elastic Compute Cloud User Guide . +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DisableSnapshotBlockPublicAccess for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableSnapshotBlockPublicAccess +func (c *EC2) DisableSnapshotBlockPublicAccess(input *DisableSnapshotBlockPublicAccessInput) (*DisableSnapshotBlockPublicAccessOutput, error) { + req, out := c.DisableSnapshotBlockPublicAccessRequest(input) + return out, req.Send() +} + +// DisableSnapshotBlockPublicAccessWithContext is the same as DisableSnapshotBlockPublicAccess with the addition of +// the ability to pass a context and additional request options. +// +// See DisableSnapshotBlockPublicAccess for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DisableSnapshotBlockPublicAccessWithContext(ctx aws.Context, input *DisableSnapshotBlockPublicAccessInput, opts ...request.Option) (*DisableSnapshotBlockPublicAccessOutput, error) { + req, out := c.DisableSnapshotBlockPublicAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDisableTransitGatewayRouteTablePropagation = "DisableTransitGatewayRouteTablePropagation" // DisableTransitGatewayRouteTablePropagationRequest generates a "aws/request.Request" representing the @@ -35703,13 +36784,11 @@ func (c *EC2) DisableVpcClassicLinkRequest(input *DisableVpcClassicLinkInput) (r // DisableVpcClassicLink API operation for Amazon Elastic Compute Cloud. // +// This action is deprecated. +// // Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC // that has EC2-Classic instances linked to it. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -35781,18 +36860,14 @@ func (c *EC2) DisableVpcClassicLinkDnsSupportRequest(input *DisableVpcClassicLin // DisableVpcClassicLinkDnsSupport API operation for Amazon Elastic Compute Cloud. // +// This action is deprecated. +// // Disables ClassicLink DNS support for a VPC. If disabled, DNS hostnames resolve // to public IP addresses when addressed between a linked EC2-Classic instance -// and instances in the VPC to which it's linked. For more information, see -// ClassicLink (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) -// in the Amazon Elastic Compute Cloud User Guide. +// and instances in the VPC to which it's linked. // // You must specify a VPC ID in the request. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -35868,14 +36943,6 @@ func (c *EC2) DisassociateAddressRequest(input *DisassociateAddressInput) (req * // Disassociates an Elastic IP address from the instance or network interface // it's associated with. // -// An Elastic IP address is for use in either the EC2-Classic platform or in -// a VPC. For more information, see Elastic IP Addresses (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) -// in the Amazon Elastic Compute Cloud User Guide. -// -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // This is an idempotent operation. If you perform the operation more than once, // Amazon EC2 doesn't return an error. // @@ -36219,6 +37286,83 @@ func (c *EC2) DisassociateInstanceEventWindowWithContext(ctx aws.Context, input return out, req.Send() } +const opDisassociateIpamByoasn = "DisassociateIpamByoasn" + +// DisassociateIpamByoasnRequest generates a "aws/request.Request" representing the +// client's request for the DisassociateIpamByoasn operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisassociateIpamByoasn for more information on using the DisassociateIpamByoasn +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the DisassociateIpamByoasnRequest method. +// req, resp := client.DisassociateIpamByoasnRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateIpamByoasn +func (c *EC2) DisassociateIpamByoasnRequest(input *DisassociateIpamByoasnInput) (req *request.Request, output *DisassociateIpamByoasnOutput) { + op := &request.Operation{ + Name: opDisassociateIpamByoasn, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DisassociateIpamByoasnInput{} + } + + output = &DisassociateIpamByoasnOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisassociateIpamByoasn API operation for Amazon Elastic Compute Cloud. +// +// Remove the association between your Autonomous System Number (ASN) and your +// BYOIP CIDR. You may want to use this action to disassociate an ASN from a +// CIDR or if you want to swap ASNs. For more information, see Tutorial: Bring +// your ASN to IPAM (https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-byoasn.html) +// in the Amazon VPC IPAM guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DisassociateIpamByoasn for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateIpamByoasn +func (c *EC2) DisassociateIpamByoasn(input *DisassociateIpamByoasnInput) (*DisassociateIpamByoasnOutput, error) { + req, out := c.DisassociateIpamByoasnRequest(input) + return out, req.Send() +} + +// DisassociateIpamByoasnWithContext is the same as DisassociateIpamByoasn with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateIpamByoasn for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DisassociateIpamByoasnWithContext(ctx aws.Context, input *DisassociateIpamByoasnInput, opts ...request.Option) (*DisassociateIpamByoasnOutput, error) { + req, out := c.DisassociateIpamByoasnRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDisassociateIpamResourceDiscovery = "DisassociateIpamResourceDiscovery" // DisassociateIpamResourceDiscoveryRequest generates a "aws/request.Request" representing the @@ -36340,17 +37484,17 @@ func (c *EC2) DisassociateNatGatewayAddressRequest(input *DisassociateNatGateway // Disassociates secondary Elastic IP addresses (EIPs) from a public NAT gateway. // You cannot disassociate your primary EIP. For more information, see Edit // secondary IP address associations (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-edit-secondary) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // While disassociating is in progress, you cannot associate/disassociate additional // EIPs while the connections are being drained. You are, however, allowed to // delete the NAT gateway. // -// An EIP will only be released at the end of MaxDrainDurationSeconds. The EIPs -// stay associated and support the existing connections but do not support any -// new connections (new connections are distributed across the remaining associated -// EIPs). As the existing connections drain out, the EIPs (and the corresponding -// private IPs mapped to them) get released. +// An EIP is released only at the end of MaxDrainDurationSeconds. It stays associated +// and supports the existing connections but does not support any new connections +// (new connections are distributed across the remaining associated EIPs). As +// the existing connections drain out, the EIPs (and the corresponding private +// IP addresses mapped to them) are released. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -36429,7 +37573,7 @@ func (c *EC2) DisassociateRouteTableRequest(input *DisassociateRouteTableInput) // After you perform this action, the subnet no longer uses the routes in the // route table. Instead, it uses the routes in the VPC's main route table. For // more information about route tables, see Route tables (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -36796,9 +37940,6 @@ func (c *EC2) DisassociateTrunkInterfaceRequest(input *DisassociateTrunkInterfac // DisassociateTrunkInterface API operation for Amazon Elastic Compute Cloud. // -// This API action is currently in limited preview only. If you are interested -// in using this feature, contact your account manager. -// // Removes an association between a branch network interface with a trunk network // interface. // @@ -37189,14 +38330,15 @@ func (c *EC2) EnableFastLaunchRequest(input *EnableFastLaunchInput) (req *reques // EnableFastLaunch API operation for Amazon Elastic Compute Cloud. // -// When you enable faster launching for a Windows AMI, images are pre-provisioned, +// When you enable Windows fast launch for a Windows AMI, images are pre-provisioned, // using snapshots to launch instances up to 65% faster. To create the optimized // Windows image, Amazon EC2 launches an instance and runs through Sysprep steps, // rebooting as required. Then it creates a set of reserved snapshots that are // used for subsequent launches. The reserved snapshots are automatically replenished // as they are used, depending on your settings for launch frequency. // -// To change these settings, you must own the AMI. +// You can only change these settings for Windows AMIs that you own or that +// have been shared with you. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -37307,6 +38449,171 @@ func (c *EC2) EnableFastSnapshotRestoresWithContext(ctx aws.Context, input *Enab return out, req.Send() } +const opEnableImage = "EnableImage" + +// EnableImageRequest generates a "aws/request.Request" representing the +// client's request for the EnableImage operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See EnableImage for more information on using the EnableImage +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the EnableImageRequest method. +// req, resp := client.EnableImageRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableImage +func (c *EC2) EnableImageRequest(input *EnableImageInput) (req *request.Request, output *EnableImageOutput) { + op := &request.Operation{ + Name: opEnableImage, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &EnableImageInput{} + } + + output = &EnableImageOutput{} + req = c.newRequest(op, input, output) + return +} + +// EnableImage API operation for Amazon Elastic Compute Cloud. +// +// Re-enables a disabled AMI. The re-enabled AMI is marked as available and +// can be used for instance launches, appears in describe operations, and can +// be shared. Amazon Web Services accounts, organizations, and Organizational +// Units that lost access to the AMI when it was disabled do not regain access +// automatically. Once the AMI is available, it can be shared with them again. +// +// Only the AMI owner can re-enable a disabled AMI. +// +// For more information, see Disable an AMI (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/disable-an-ami.html) +// in the Amazon EC2 User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation EnableImage for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableImage +func (c *EC2) EnableImage(input *EnableImageInput) (*EnableImageOutput, error) { + req, out := c.EnableImageRequest(input) + return out, req.Send() +} + +// EnableImageWithContext is the same as EnableImage with the addition of +// the ability to pass a context and additional request options. +// +// See EnableImage for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) EnableImageWithContext(ctx aws.Context, input *EnableImageInput, opts ...request.Option) (*EnableImageOutput, error) { + req, out := c.EnableImageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opEnableImageBlockPublicAccess = "EnableImageBlockPublicAccess" + +// EnableImageBlockPublicAccessRequest generates a "aws/request.Request" representing the +// client's request for the EnableImageBlockPublicAccess operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See EnableImageBlockPublicAccess for more information on using the EnableImageBlockPublicAccess +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the EnableImageBlockPublicAccessRequest method. +// req, resp := client.EnableImageBlockPublicAccessRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableImageBlockPublicAccess +func (c *EC2) EnableImageBlockPublicAccessRequest(input *EnableImageBlockPublicAccessInput) (req *request.Request, output *EnableImageBlockPublicAccessOutput) { + op := &request.Operation{ + Name: opEnableImageBlockPublicAccess, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &EnableImageBlockPublicAccessInput{} + } + + output = &EnableImageBlockPublicAccessOutput{} + req = c.newRequest(op, input, output) + return +} + +// EnableImageBlockPublicAccess API operation for Amazon Elastic Compute Cloud. +// +// Enables block public access for AMIs at the account level in the specified +// Amazon Web Services Region. This prevents the public sharing of your AMIs. +// However, if you already have public AMIs, they will remain publicly available. +// +// The API can take up to 10 minutes to configure this setting. During this +// time, if you run GetImageBlockPublicAccessState (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_GetImageBlockPublicAccessState.html), +// the response will be unblocked. When the API has completed the configuration, +// the response will be block-new-sharing. +// +// For more information, see Block public access to your AMIs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharingamis-intro.html#block-public-access-to-amis) +// in the Amazon EC2 User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation EnableImageBlockPublicAccess for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableImageBlockPublicAccess +func (c *EC2) EnableImageBlockPublicAccess(input *EnableImageBlockPublicAccessInput) (*EnableImageBlockPublicAccessOutput, error) { + req, out := c.EnableImageBlockPublicAccessRequest(input) + return out, req.Send() +} + +// EnableImageBlockPublicAccessWithContext is the same as EnableImageBlockPublicAccess with the addition of +// the ability to pass a context and additional request options. +// +// See EnableImageBlockPublicAccess for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) EnableImageBlockPublicAccessWithContext(ctx aws.Context, input *EnableImageBlockPublicAccessInput, opts ...request.Option) (*EnableImageBlockPublicAccessOutput, error) { + req, out := c.EnableImageBlockPublicAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opEnableImageDeprecation = "EnableImageDeprecation" // EnableImageDeprecationRequest generates a "aws/request.Request" representing the @@ -37614,6 +38921,92 @@ func (c *EC2) EnableSerialConsoleAccessWithContext(ctx aws.Context, input *Enabl return out, req.Send() } +const opEnableSnapshotBlockPublicAccess = "EnableSnapshotBlockPublicAccess" + +// EnableSnapshotBlockPublicAccessRequest generates a "aws/request.Request" representing the +// client's request for the EnableSnapshotBlockPublicAccess operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See EnableSnapshotBlockPublicAccess for more information on using the EnableSnapshotBlockPublicAccess +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the EnableSnapshotBlockPublicAccessRequest method. +// req, resp := client.EnableSnapshotBlockPublicAccessRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableSnapshotBlockPublicAccess +func (c *EC2) EnableSnapshotBlockPublicAccessRequest(input *EnableSnapshotBlockPublicAccessInput) (req *request.Request, output *EnableSnapshotBlockPublicAccessOutput) { + op := &request.Operation{ + Name: opEnableSnapshotBlockPublicAccess, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &EnableSnapshotBlockPublicAccessInput{} + } + + output = &EnableSnapshotBlockPublicAccessOutput{} + req = c.newRequest(op, input, output) + return +} + +// EnableSnapshotBlockPublicAccess API operation for Amazon Elastic Compute Cloud. +// +// Enables or modifies the block public access for snapshots setting at the +// account level for the specified Amazon Web Services Region. After you enable +// block public access for snapshots in a Region, users can no longer request +// public sharing for snapshots in that Region. Snapshots that are already publicly +// shared are either treated as private or they remain publicly shared, depending +// on the State that you specify. +// +// If block public access is enabled in block-all-sharing mode, and you change +// the mode to block-new-sharing, all snapshots that were previously publicly +// shared are no longer treated as private and they become publicly accessible +// again. +// +// For more information, see Block public access for snapshots (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-public-access-snapshots.html) +// in the Amazon Elastic Compute Cloud User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation EnableSnapshotBlockPublicAccess for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableSnapshotBlockPublicAccess +func (c *EC2) EnableSnapshotBlockPublicAccess(input *EnableSnapshotBlockPublicAccessInput) (*EnableSnapshotBlockPublicAccessOutput, error) { + req, out := c.EnableSnapshotBlockPublicAccessRequest(input) + return out, req.Send() +} + +// EnableSnapshotBlockPublicAccessWithContext is the same as EnableSnapshotBlockPublicAccess with the addition of +// the ability to pass a context and additional request options. +// +// See EnableSnapshotBlockPublicAccess for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) EnableSnapshotBlockPublicAccessWithContext(ctx aws.Context, input *EnableSnapshotBlockPublicAccessInput, opts ...request.Option) (*EnableSnapshotBlockPublicAccessOutput, error) { + req, out := c.EnableSnapshotBlockPublicAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opEnableTransitGatewayRouteTablePropagation = "EnableTransitGatewayRouteTablePropagation" // EnableTransitGatewayRouteTablePropagationRequest generates a "aws/request.Request" representing the @@ -37881,17 +39274,14 @@ func (c *EC2) EnableVpcClassicLinkRequest(input *EnableVpcClassicLinkInput) (req // EnableVpcClassicLink API operation for Amazon Elastic Compute Cloud. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// This action is deprecated. // // Enables a VPC for ClassicLink. You can then link EC2-Classic instances to // your ClassicLink-enabled VPC to allow communication over private IP addresses. // You cannot enable your VPC for ClassicLink if any of your VPC route tables // have existing routes for address ranges within the 10.0.0.0/8 IP address // range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 -// IP address ranges. For more information, see ClassicLink (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) -// in the Amazon Elastic Compute Cloud User Guide. +// IP address ranges. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -37964,17 +39354,13 @@ func (c *EC2) EnableVpcClassicLinkDnsSupportRequest(input *EnableVpcClassicLinkD // EnableVpcClassicLinkDnsSupport API operation for Amazon Elastic Compute Cloud. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// This action is deprecated. // // Enables a VPC to support DNS hostname resolution for ClassicLink. If enabled, // the DNS hostname of a linked EC2-Classic instance resolves to its private // IP address when addressed from an instance in the VPC to which it's linked. // Similarly, the DNS hostname of an instance in a VPC resolves to its private -// IP address when addressed from a linked EC2-Classic instance. For more information, -// see ClassicLink (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) -// in the Amazon Elastic Compute Cloud User Guide. +// IP address when addressed from a linked EC2-Classic instance. // // You must specify a VPC ID in the request. // @@ -39252,6 +40638,9 @@ func (c *EC2) GetFlowLogsIntegrationTemplateRequest(input *GetFlowLogsIntegratio // - Create a set of named queries in Athena that you can use to get started // quickly // +// GetFlowLogsIntegrationTemplate does not support integration between Amazon +// Web Services Transit Gateway Flow Logs and Amazon Athena. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -39488,6 +40877,83 @@ func (c *EC2) GetHostReservationPurchasePreviewWithContext(ctx aws.Context, inpu return out, req.Send() } +const opGetImageBlockPublicAccessState = "GetImageBlockPublicAccessState" + +// GetImageBlockPublicAccessStateRequest generates a "aws/request.Request" representing the +// client's request for the GetImageBlockPublicAccessState operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetImageBlockPublicAccessState for more information on using the GetImageBlockPublicAccessState +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the GetImageBlockPublicAccessStateRequest method. +// req, resp := client.GetImageBlockPublicAccessStateRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetImageBlockPublicAccessState +func (c *EC2) GetImageBlockPublicAccessStateRequest(input *GetImageBlockPublicAccessStateInput) (req *request.Request, output *GetImageBlockPublicAccessStateOutput) { + op := &request.Operation{ + Name: opGetImageBlockPublicAccessState, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetImageBlockPublicAccessStateInput{} + } + + output = &GetImageBlockPublicAccessStateOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetImageBlockPublicAccessState API operation for Amazon Elastic Compute Cloud. +// +// Gets the current state of block public access for AMIs at the account level +// in the specified Amazon Web Services Region. +// +// For more information, see Block public access to your AMIs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharingamis-intro.html#block-public-access-to-amis) +// in the Amazon EC2 User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation GetImageBlockPublicAccessState for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetImageBlockPublicAccessState +func (c *EC2) GetImageBlockPublicAccessState(input *GetImageBlockPublicAccessStateInput) (*GetImageBlockPublicAccessStateOutput, error) { + req, out := c.GetImageBlockPublicAccessStateRequest(input) + return out, req.Send() +} + +// GetImageBlockPublicAccessStateWithContext is the same as GetImageBlockPublicAccessState with the addition of +// the ability to pass a context and additional request options. +// +// See GetImageBlockPublicAccessState for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetImageBlockPublicAccessStateWithContext(ctx aws.Context, input *GetImageBlockPublicAccessStateInput, opts ...request.Option) (*GetImageBlockPublicAccessStateOutput, error) { + req, out := c.GetImageBlockPublicAccessStateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetInstanceTypesFromInstanceRequirements = "GetInstanceTypesFromInstanceRequirements" // GetInstanceTypesFromInstanceRequirementsRequest generates a "aws/request.Request" representing the @@ -39985,6 +41451,79 @@ func (c *EC2) GetIpamDiscoveredAccountsPagesWithContext(ctx aws.Context, input * return p.Err() } +const opGetIpamDiscoveredPublicAddresses = "GetIpamDiscoveredPublicAddresses" + +// GetIpamDiscoveredPublicAddressesRequest generates a "aws/request.Request" representing the +// client's request for the GetIpamDiscoveredPublicAddresses operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetIpamDiscoveredPublicAddresses for more information on using the GetIpamDiscoveredPublicAddresses +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the GetIpamDiscoveredPublicAddressesRequest method. +// req, resp := client.GetIpamDiscoveredPublicAddressesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetIpamDiscoveredPublicAddresses +func (c *EC2) GetIpamDiscoveredPublicAddressesRequest(input *GetIpamDiscoveredPublicAddressesInput) (req *request.Request, output *GetIpamDiscoveredPublicAddressesOutput) { + op := &request.Operation{ + Name: opGetIpamDiscoveredPublicAddresses, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetIpamDiscoveredPublicAddressesInput{} + } + + output = &GetIpamDiscoveredPublicAddressesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetIpamDiscoveredPublicAddresses API operation for Amazon Elastic Compute Cloud. +// +// Gets the public IP addresses that have been discovered by IPAM. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation GetIpamDiscoveredPublicAddresses for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetIpamDiscoveredPublicAddresses +func (c *EC2) GetIpamDiscoveredPublicAddresses(input *GetIpamDiscoveredPublicAddressesInput) (*GetIpamDiscoveredPublicAddressesOutput, error) { + req, out := c.GetIpamDiscoveredPublicAddressesRequest(input) + return out, req.Send() +} + +// GetIpamDiscoveredPublicAddressesWithContext is the same as GetIpamDiscoveredPublicAddresses with the addition of +// the ability to pass a context and additional request options. +// +// See GetIpamDiscoveredPublicAddresses for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetIpamDiscoveredPublicAddressesWithContext(ctx aws.Context, input *GetIpamDiscoveredPublicAddressesInput, opts ...request.Option) (*GetIpamDiscoveredPublicAddressesOutput, error) { + req, out := c.GetIpamDiscoveredPublicAddressesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetIpamDiscoveredResourceCidrs = "GetIpamDiscoveredResourceCidrs" // GetIpamDiscoveredResourceCidrsRequest generates a "aws/request.Request" representing the @@ -40167,7 +41706,9 @@ func (c *EC2) GetIpamPoolAllocationsRequest(input *GetIpamPoolAllocationsInput) // GetIpamPoolAllocations API operation for Amazon Elastic Compute Cloud. // -// Get a list of all the CIDR allocations in an IPAM pool. +// Get a list of all the CIDR allocations in an IPAM pool. The Region you use +// should be the IPAM pool locale. The locale is the Amazon Web Services Region +// where this IPAM pool is available for allocations. // // If you use this action after AllocateIpamPoolCidr (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AllocateIpamPoolCidr.html) // or ReleaseIpamPoolAllocation (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ReleaseIpamPoolAllocation.html), @@ -40888,6 +42429,12 @@ func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsRequest(input *GetNet Name: opGetNetworkInsightsAccessScopeAnalysisFindings, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -40931,6 +42478,57 @@ func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsWithContext(ctx aws.C return out, req.Send() } +// GetNetworkInsightsAccessScopeAnalysisFindingsPages iterates over the pages of a GetNetworkInsightsAccessScopeAnalysisFindings operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetNetworkInsightsAccessScopeAnalysisFindings method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetNetworkInsightsAccessScopeAnalysisFindings operation. +// pageNum := 0 +// err := client.GetNetworkInsightsAccessScopeAnalysisFindingsPages(params, +// func(page *ec2.GetNetworkInsightsAccessScopeAnalysisFindingsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsPages(input *GetNetworkInsightsAccessScopeAnalysisFindingsInput, fn func(*GetNetworkInsightsAccessScopeAnalysisFindingsOutput, bool) bool) error { + return c.GetNetworkInsightsAccessScopeAnalysisFindingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetNetworkInsightsAccessScopeAnalysisFindingsPagesWithContext same as GetNetworkInsightsAccessScopeAnalysisFindingsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsPagesWithContext(ctx aws.Context, input *GetNetworkInsightsAccessScopeAnalysisFindingsInput, fn func(*GetNetworkInsightsAccessScopeAnalysisFindingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetNetworkInsightsAccessScopeAnalysisFindingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetNetworkInsightsAccessScopeAnalysisFindingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetNetworkInsightsAccessScopeAnalysisFindingsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetNetworkInsightsAccessScopeContent = "GetNetworkInsightsAccessScopeContent" // GetNetworkInsightsAccessScopeContentRequest generates a "aws/request.Request" representing the @@ -41170,6 +42768,137 @@ func (c *EC2) GetReservedInstancesExchangeQuoteWithContext(ctx aws.Context, inpu return out, req.Send() } +const opGetSecurityGroupsForVpc = "GetSecurityGroupsForVpc" + +// GetSecurityGroupsForVpcRequest generates a "aws/request.Request" representing the +// client's request for the GetSecurityGroupsForVpc operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetSecurityGroupsForVpc for more information on using the GetSecurityGroupsForVpc +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the GetSecurityGroupsForVpcRequest method. +// req, resp := client.GetSecurityGroupsForVpcRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetSecurityGroupsForVpc +func (c *EC2) GetSecurityGroupsForVpcRequest(input *GetSecurityGroupsForVpcInput) (req *request.Request, output *GetSecurityGroupsForVpcOutput) { + op := &request.Operation{ + Name: opGetSecurityGroupsForVpc, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetSecurityGroupsForVpcInput{} + } + + output = &GetSecurityGroupsForVpcOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSecurityGroupsForVpc API operation for Amazon Elastic Compute Cloud. +// +// Gets security groups that can be associated by the Amazon Web Services account +// making the request with network interfaces in the specified VPC. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation GetSecurityGroupsForVpc for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetSecurityGroupsForVpc +func (c *EC2) GetSecurityGroupsForVpc(input *GetSecurityGroupsForVpcInput) (*GetSecurityGroupsForVpcOutput, error) { + req, out := c.GetSecurityGroupsForVpcRequest(input) + return out, req.Send() +} + +// GetSecurityGroupsForVpcWithContext is the same as GetSecurityGroupsForVpc with the addition of +// the ability to pass a context and additional request options. +// +// See GetSecurityGroupsForVpc for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetSecurityGroupsForVpcWithContext(ctx aws.Context, input *GetSecurityGroupsForVpcInput, opts ...request.Option) (*GetSecurityGroupsForVpcOutput, error) { + req, out := c.GetSecurityGroupsForVpcRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetSecurityGroupsForVpcPages iterates over the pages of a GetSecurityGroupsForVpc operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetSecurityGroupsForVpc method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetSecurityGroupsForVpc operation. +// pageNum := 0 +// err := client.GetSecurityGroupsForVpcPages(params, +// func(page *ec2.GetSecurityGroupsForVpcOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +func (c *EC2) GetSecurityGroupsForVpcPages(input *GetSecurityGroupsForVpcInput, fn func(*GetSecurityGroupsForVpcOutput, bool) bool) error { + return c.GetSecurityGroupsForVpcPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetSecurityGroupsForVpcPagesWithContext same as GetSecurityGroupsForVpcPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetSecurityGroupsForVpcPagesWithContext(ctx aws.Context, input *GetSecurityGroupsForVpcInput, fn func(*GetSecurityGroupsForVpcOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetSecurityGroupsForVpcInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetSecurityGroupsForVpcRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetSecurityGroupsForVpcOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetSerialConsoleAccessStatus = "GetSerialConsoleAccessStatus" // GetSerialConsoleAccessStatusRequest generates a "aws/request.Request" representing the @@ -41247,6 +42976,83 @@ func (c *EC2) GetSerialConsoleAccessStatusWithContext(ctx aws.Context, input *Ge return out, req.Send() } +const opGetSnapshotBlockPublicAccessState = "GetSnapshotBlockPublicAccessState" + +// GetSnapshotBlockPublicAccessStateRequest generates a "aws/request.Request" representing the +// client's request for the GetSnapshotBlockPublicAccessState operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetSnapshotBlockPublicAccessState for more information on using the GetSnapshotBlockPublicAccessState +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the GetSnapshotBlockPublicAccessStateRequest method. +// req, resp := client.GetSnapshotBlockPublicAccessStateRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetSnapshotBlockPublicAccessState +func (c *EC2) GetSnapshotBlockPublicAccessStateRequest(input *GetSnapshotBlockPublicAccessStateInput) (req *request.Request, output *GetSnapshotBlockPublicAccessStateOutput) { + op := &request.Operation{ + Name: opGetSnapshotBlockPublicAccessState, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetSnapshotBlockPublicAccessStateInput{} + } + + output = &GetSnapshotBlockPublicAccessStateOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSnapshotBlockPublicAccessState API operation for Amazon Elastic Compute Cloud. +// +// Gets the current state of block public access for snapshots setting for the +// account and Region. +// +// For more information, see Block public access for snapshots (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-public-access-snapshots.html) +// in the Amazon Elastic Compute Cloud User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation GetSnapshotBlockPublicAccessState for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetSnapshotBlockPublicAccessState +func (c *EC2) GetSnapshotBlockPublicAccessState(input *GetSnapshotBlockPublicAccessStateInput) (*GetSnapshotBlockPublicAccessStateOutput, error) { + req, out := c.GetSnapshotBlockPublicAccessStateRequest(input) + return out, req.Send() +} + +// GetSnapshotBlockPublicAccessStateWithContext is the same as GetSnapshotBlockPublicAccessState with the addition of +// the ability to pass a context and additional request options. +// +// See GetSnapshotBlockPublicAccessState for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetSnapshotBlockPublicAccessStateWithContext(ctx aws.Context, input *GetSnapshotBlockPublicAccessStateInput, opts ...request.Option) (*GetSnapshotBlockPublicAccessStateOutput, error) { + req, out := c.GetSnapshotBlockPublicAccessStateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetSpotPlacementScores = "GetSpotPlacementScores" // GetSpotPlacementScoresRequest generates a "aws/request.Request" representing the @@ -42952,16 +44758,21 @@ func (c *EC2) ImportInstanceRequest(input *ImportInstanceInput) (req *request.Re // ImportInstance API operation for Amazon Elastic Compute Cloud. // -// Creates an import instance task using metadata from the specified disk image. +// We recommend that you use the ImportImage (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportImage.html) +// API. For more information, see Importing a VM as an image using VM Import/Export +// (https://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html) +// in the VM Import/Export User Guide. // -// This API action supports only single-volume VMs. To import multi-volume VMs, -// use ImportImage instead. +// Creates an import instance task using metadata from the specified disk image. // // This API action is not supported by the Command Line Interface (CLI). For // information about using the Amazon EC2 CLI, which is deprecated, see Importing // a VM to Amazon EC2 (https://awsdocs.s3.amazonaws.com/EC2/ec2-clt.pdf#UsingVirtualMachinesinAmazonEC2) // in the Amazon EC2 CLI Reference PDF file. // +// This API action supports only single-volume VMs. To import multi-volume VMs, +// use ImportImage instead. +// // For information about the import manifest referenced by this API action, // see VM Import Manifest (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html). // @@ -43498,6 +45309,96 @@ func (c *EC2) ListSnapshotsInRecycleBinPagesWithContext(ctx aws.Context, input * return p.Err() } +const opLockSnapshot = "LockSnapshot" + +// LockSnapshotRequest generates a "aws/request.Request" representing the +// client's request for the LockSnapshot operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See LockSnapshot for more information on using the LockSnapshot +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the LockSnapshotRequest method. +// req, resp := client.LockSnapshotRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/LockSnapshot +func (c *EC2) LockSnapshotRequest(input *LockSnapshotInput) (req *request.Request, output *LockSnapshotOutput) { + op := &request.Operation{ + Name: opLockSnapshot, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &LockSnapshotInput{} + } + + output = &LockSnapshotOutput{} + req = c.newRequest(op, input, output) + return +} + +// LockSnapshot API operation for Amazon Elastic Compute Cloud. +// +// Locks an Amazon EBS snapshot in either governance or compliance mode to protect +// it against accidental or malicious deletions for a specific duration. A locked +// snapshot can't be deleted. +// +// You can also use this action to modify the lock settings for a snapshot that +// is already locked. The allowed modifications depend on the lock mode and +// lock state: +// +// - If the snapshot is locked in governance mode, you can modify the lock +// mode and the lock duration or lock expiration date. +// +// - If the snapshot is locked in compliance mode and it is in the cooling-off +// period, you can modify the lock mode and the lock duration or lock expiration +// date. +// +// - If the snapshot is locked in compliance mode and the cooling-off period +// has lapsed, you can only increase the lock duration or extend the lock +// expiration date. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation LockSnapshot for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/LockSnapshot +func (c *EC2) LockSnapshot(input *LockSnapshotInput) (*LockSnapshotOutput, error) { + req, out := c.LockSnapshotRequest(input) + return out, req.Send() +} + +// LockSnapshotWithContext is the same as LockSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See LockSnapshot for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) LockSnapshotWithContext(ctx aws.Context, input *LockSnapshotInput, opts ...request.Option) (*LockSnapshotOutput, error) { + req, out := c.LockSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opModifyAddressAttribute = "ModifyAddressAttribute" // ModifyAddressAttributeRequest generates a "aws/request.Request" representing the @@ -44638,10 +46539,10 @@ func (c *EC2) ModifyInstanceAttributeRequest(input *ModifyInstanceAttributeInput // only one attribute at a time. // // Note: Using this action to change the security groups associated with an -// elastic network interface (ENI) attached to an instance in a VPC can result -// in an error if the instance has more than one ENI. To change the security -// groups associated with an ENI attached to an instance that has multiple ENIs, -// we recommend that you use the ModifyNetworkInterfaceAttribute action. +// elastic network interface (ENI) attached to an instance can result in an +// error if the instance has more than one ENI. To change the security groups +// associated with an ENI attached to an instance that has multiple ENIs, we +// recommend that you use the ModifyNetworkInterfaceAttribute action. // // To modify some attributes, the instance must be stopped. For more information, // see Modify a stopped instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) @@ -46040,10 +47941,6 @@ func (c *EC2) ModifyReservedInstancesRequest(input *ModifyReservedInstancesInput // For more information, see Modifying Reserved Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-modifying.html) // in the Amazon EC2 User Guide. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -46994,7 +48891,8 @@ func (c *EC2) ModifyVerifiedAccessEndpointRequest(input *ModifyVerifiedAccessEnd // ModifyVerifiedAccessEndpoint API operation for Amazon Elastic Compute Cloud. // -// Modifies the configuration of an Amazon Web Services Verified Access endpoint. +// Modifies the configuration of the specified Amazon Web Services Verified +// Access endpoint. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47067,7 +48965,7 @@ func (c *EC2) ModifyVerifiedAccessEndpointPolicyRequest(input *ModifyVerifiedAcc // ModifyVerifiedAccessEndpointPolicy API operation for Amazon Elastic Compute Cloud. // -// Modifies the specified Verified Access endpoint policy. +// Modifies the specified Amazon Web Services Verified Access endpoint policy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47140,7 +49038,7 @@ func (c *EC2) ModifyVerifiedAccessGroupRequest(input *ModifyVerifiedAccessGroupI // ModifyVerifiedAccessGroup API operation for Amazon Elastic Compute Cloud. // -// Modifies the specified Verified Access group configuration. +// Modifies the specified Amazon Web Services Verified Access group configuration. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47213,7 +49111,7 @@ func (c *EC2) ModifyVerifiedAccessGroupPolicyRequest(input *ModifyVerifiedAccess // ModifyVerifiedAccessGroupPolicy API operation for Amazon Elastic Compute Cloud. // -// Modifies the specified Verified Access group policy. +// Modifies the specified Amazon Web Services Verified Access group policy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47286,7 +49184,8 @@ func (c *EC2) ModifyVerifiedAccessInstanceRequest(input *ModifyVerifiedAccessIns // ModifyVerifiedAccessInstance API operation for Amazon Elastic Compute Cloud. // -// Modifies the configuration of the specified Verified Access instance. +// Modifies the configuration of the specified Amazon Web Services Verified +// Access instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -48145,22 +50044,8 @@ func (c *EC2) ModifyVpcPeeringConnectionOptionsRequest(input *ModifyVpcPeeringCo // ModifyVpcPeeringConnectionOptions API operation for Amazon Elastic Compute Cloud. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Modifies the VPC peering connection options on one side of a VPC peering -// connection. You can do the following: -// -// - Enable/disable communication over the peering connection between an -// EC2-Classic instance that's linked to your VPC (using ClassicLink) and -// instances in the peer VPC. -// -// - Enable/disable communication over the peering connection between instances -// in your VPC and an EC2-Classic instance that's linked to the peer VPC. -// -// - Enable/disable the ability to resolve public DNS hostnames to private -// IP addresses when queried from instances in the peer VPC. +// connection. // // If the peered VPCs are in the same Amazon Web Services account, you can enable // DNS resolution for queries from the local VPC. This ensures that queries @@ -48255,7 +50140,7 @@ func (c *EC2) ModifyVpcTenancyRequest(input *ModifyVpcTenancyInput) (req *reques // launch. The tenancy of any existing instances in the VPC is not affected. // // For more information, see Dedicated Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) -// in the Amazon Elastic Compute Cloud User Guide. +// in the Amazon EC2 User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -48748,6 +50633,8 @@ func (c *EC2) MoveAddressToVpcRequest(input *MoveAddressToVpcInput) (req *reques // MoveAddressToVpc API operation for Amazon Elastic Compute Cloud. // +// This action is deprecated. +// // Moves an Elastic IP address from the EC2-Classic platform to the EC2-VPC // platform. The Elastic IP address must be allocated to your account for more // than 24 hours, and it must not be associated with an instance. After the @@ -48756,10 +50643,6 @@ func (c *EC2) MoveAddressToVpcRequest(input *MoveAddressToVpcInput) (req *reques // You cannot move an Elastic IP address that was originally allocated for use // in the EC2-VPC platform to the EC2-Classic platform. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -48956,6 +50839,83 @@ func (c *EC2) ProvisionByoipCidrWithContext(ctx aws.Context, input *ProvisionByo return out, req.Send() } +const opProvisionIpamByoasn = "ProvisionIpamByoasn" + +// ProvisionIpamByoasnRequest generates a "aws/request.Request" representing the +// client's request for the ProvisionIpamByoasn operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ProvisionIpamByoasn for more information on using the ProvisionIpamByoasn +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the ProvisionIpamByoasnRequest method. +// req, resp := client.ProvisionIpamByoasnRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ProvisionIpamByoasn +func (c *EC2) ProvisionIpamByoasnRequest(input *ProvisionIpamByoasnInput) (req *request.Request, output *ProvisionIpamByoasnOutput) { + op := &request.Operation{ + Name: opProvisionIpamByoasn, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ProvisionIpamByoasnInput{} + } + + output = &ProvisionIpamByoasnOutput{} + req = c.newRequest(op, input, output) + return +} + +// ProvisionIpamByoasn API operation for Amazon Elastic Compute Cloud. +// +// Provisions your Autonomous System Number (ASN) for use in your Amazon Web +// Services account. This action requires authorization context for Amazon to +// bring the ASN to an Amazon Web Services account. For more information, see +// Tutorial: Bring your ASN to IPAM (https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-byoasn.html) +// in the Amazon VPC IPAM guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation ProvisionIpamByoasn for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ProvisionIpamByoasn +func (c *EC2) ProvisionIpamByoasn(input *ProvisionIpamByoasnInput) (*ProvisionIpamByoasnOutput, error) { + req, out := c.ProvisionIpamByoasnRequest(input) + return out, req.Send() +} + +// ProvisionIpamByoasnWithContext is the same as ProvisionIpamByoasn with the addition of +// the ability to pass a context and additional request options. +// +// See ProvisionIpamByoasn for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) ProvisionIpamByoasnWithContext(ctx aws.Context, input *ProvisionIpamByoasnInput, opts ...request.Option) (*ProvisionIpamByoasnOutput, error) { + req, out := c.ProvisionIpamByoasnRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opProvisionIpamPoolCidr = "ProvisionIpamPoolCidr" // ProvisionIpamPoolCidrRequest generates a "aws/request.Request" representing the @@ -49110,6 +51070,81 @@ func (c *EC2) ProvisionPublicIpv4PoolCidrWithContext(ctx aws.Context, input *Pro return out, req.Send() } +const opPurchaseCapacityBlock = "PurchaseCapacityBlock" + +// PurchaseCapacityBlockRequest generates a "aws/request.Request" representing the +// client's request for the PurchaseCapacityBlock operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PurchaseCapacityBlock for more information on using the PurchaseCapacityBlock +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the PurchaseCapacityBlockRequest method. +// req, resp := client.PurchaseCapacityBlockRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseCapacityBlock +func (c *EC2) PurchaseCapacityBlockRequest(input *PurchaseCapacityBlockInput) (req *request.Request, output *PurchaseCapacityBlockOutput) { + op := &request.Operation{ + Name: opPurchaseCapacityBlock, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PurchaseCapacityBlockInput{} + } + + output = &PurchaseCapacityBlockOutput{} + req = c.newRequest(op, input, output) + return +} + +// PurchaseCapacityBlock API operation for Amazon Elastic Compute Cloud. +// +// Purchase the Capacity Block for use with your account. With Capacity Blocks +// you ensure GPU capacity is available for machine learning (ML) workloads. +// You must specify the ID of the Capacity Block offering you are purchasing. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation PurchaseCapacityBlock for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseCapacityBlock +func (c *EC2) PurchaseCapacityBlock(input *PurchaseCapacityBlockInput) (*PurchaseCapacityBlockOutput, error) { + req, out := c.PurchaseCapacityBlockRequest(input) + return out, req.Send() +} + +// PurchaseCapacityBlockWithContext is the same as PurchaseCapacityBlock with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseCapacityBlock for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) PurchaseCapacityBlockWithContext(ctx aws.Context, input *PurchaseCapacityBlockInput, opts ...request.Option) (*PurchaseCapacityBlockOutput, error) { + req, out := c.PurchaseCapacityBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opPurchaseHostReservation = "PurchaseHostReservation" // PurchaseHostReservationRequest generates a "aws/request.Request" representing the @@ -49243,10 +51278,6 @@ func (c *EC2) PurchaseReservedInstancesOfferingRequest(input *PurchaseReservedIn // and Reserved Instance Marketplace (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) // in the Amazon EC2 User Guide. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -50226,13 +52257,9 @@ func (c *EC2) ReleaseAddressRequest(input *ReleaseAddressInput) (req *request.Re // // Releases the specified Elastic IP address. // -// [EC2-Classic, default VPC] Releasing an Elastic IP address automatically -// disassociates it from any instance that it's associated with. To disassociate -// an Elastic IP address without releasing it, use DisassociateAddress. -// -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// [Default VPC] Releasing an Elastic IP address automatically disassociates +// it from any instance that it's associated with. To disassociate an Elastic +// IP address without releasing it, use DisassociateAddress. // // [Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic // IP address before you can release it. Otherwise, Amazon EC2 returns an error @@ -50244,11 +52271,8 @@ func (c *EC2) ReleaseAddressRequest(input *ReleaseAddressInput) (req *request.Re // already released, you'll get an AuthFailure error if the address is already // allocated to another Amazon Web Services account. // -// [EC2-VPC] After you release an Elastic IP address for use in a VPC, you might -// be able to recover it. For more information, see AllocateAddress. -// -// For more information, see Elastic IP Addresses (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) -// in the Amazon Elastic Compute Cloud User Guide. +// After you release an Elastic IP address, you might be able to recover it. +// For more information, see AllocateAddress. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -50404,11 +52428,13 @@ func (c *EC2) ReleaseIpamPoolAllocationRequest(input *ReleaseIpamPoolAllocationI // ReleaseIpamPoolAllocation API operation for Amazon Elastic Compute Cloud. // -// Release an allocation within an IPAM pool. You can only use this action to -// release manual allocations. To remove an allocation for a resource without -// deleting the resource, set its monitored state to false using ModifyIpamResourceCidr +// Release an allocation within an IPAM pool. The Region you use should be the +// IPAM pool locale. The locale is the Amazon Web Services Region where this +// IPAM pool is available for allocations. You can only use this action to release +// manual allocations. To remove an allocation for a resource without deleting +// the resource, set its monitored state to false using ModifyIpamResourceCidr // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyIpamResourceCidr.html). -// For more information, see Release an allocation (https://docs.aws.amazon.com/vpc/latest/ipam/release-pool-alloc-ipam.html) +// For more information, see Release an allocation (https://docs.aws.amazon.com/vpc/latest/ipam/release-alloc-ipam.html) // in the Amazon VPC IPAM User Guide. // // All EC2 API actions follow an eventual consistency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#eventual-consistency) @@ -50565,8 +52591,8 @@ func (c *EC2) ReplaceNetworkAclAssociationRequest(input *ReplaceNetworkAclAssoci // // Changes which network ACL a subnet is associated with. By default when you // create a subnet, it's automatically associated with the default network ACL. -// For more information, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) -// in the Amazon Virtual Private Cloud User Guide. +// For more information, see Network ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) +// in the Amazon VPC User Guide. // // This is an idempotent operation. // @@ -50643,8 +52669,8 @@ func (c *EC2) ReplaceNetworkAclEntryRequest(input *ReplaceNetworkAclEntryInput) // ReplaceNetworkAclEntry API operation for Amazon Elastic Compute Cloud. // // Replaces an entry (rule) in a network ACL. For more information, see Network -// ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in -// the Amazon Virtual Private Cloud User Guide. +// ACLs (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -50725,7 +52751,7 @@ func (c *EC2) ReplaceRouteRequest(input *ReplaceRouteInput) (req *request.Reques // reset the local route to its default target. // // For more information, see Route tables (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -50802,7 +52828,7 @@ func (c *EC2) ReplaceRouteTableAssociationRequest(input *ReplaceRouteTableAssoci // or virtual private gateway in a VPC. After the operation completes, the subnet // or gateway uses the routes in the new route table. For more information about // route tables, see Route tables (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // You can also use this operation to change which table is the main route table // in the VPC. Specify the main route table's association ID and the route table @@ -51217,10 +53243,6 @@ func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req // see Which is the best Spot request method to use? (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-best-practices.html#which-spot-request-method-to-use) // in the Amazon EC2 User Guide for Linux Instances. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon EC2 User Guide for Linux Instances. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -51829,15 +53851,13 @@ func (c *EC2) RestoreAddressToClassicRequest(input *RestoreAddressToClassicInput // RestoreAddressToClassic API operation for Amazon Elastic Compute Cloud. // +// This action is deprecated. +// // Restores an Elastic IP address that was previously moved to the EC2-VPC platform // back to the EC2-Classic platform. You cannot move an Elastic IP address that // was originally allocated for use in EC2-VPC. The Elastic IP address must // not be associated with an instance or network interface. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -52286,9 +54306,8 @@ func (c *EC2) RevokeSecurityGroupEgressRequest(input *RevokeSecurityGroupEgressI // RevokeSecurityGroupEgress API operation for Amazon Elastic Compute Cloud. // -// [VPC only] Removes the specified outbound (egress) rules from a security -// group for EC2-VPC. This action does not apply to security groups for use -// in EC2-Classic. +// Removes the specified outbound (egress) rules from the specified security +// group. // // You can specify rules using either rule IDs or security group rule properties. // If you use rule properties, the values that you specify (for example, ports) @@ -52299,7 +54318,7 @@ func (c *EC2) RevokeSecurityGroupEgressRequest(input *RevokeSecurityGroupEgressI // ICMP type and code. If the security group rule has a description, you do // not need to specify the description to revoke the rule. // -// [Default VPC] If the values you specify do not match the existing rule's +// For a default VPC, if the values you specify do not match the existing rule's // values, no error is returned, and the output describes the security group // rules that were not revoked. // @@ -52391,9 +54410,13 @@ func (c *EC2) RevokeSecurityGroupIngressRequest(input *RevokeSecurityGroupIngres // type and code. If the security group rule has a description, you do not need // to specify the description to revoke the rule. // -// [EC2-Classic, default VPC] If the values you specify do not match the existing -// rule's values, no error is returned, and the output describes the security -// group rules that were not revoked. +// For a default VPC, if the values you specify do not match the existing rule's +// values, no error is returned, and the output describes the security group +// rules that were not revoked. +// +// For a non-default VPC, if the values you specify do not match the existing +// rule's values, an InvalidPermission.NotFound client error is returned, and +// no rules are revoked. // // Amazon Web Services recommends that you describe the security group to verify // that the rules were removed. @@ -52401,10 +54424,6 @@ func (c *EC2) RevokeSecurityGroupIngressRequest(input *RevokeSecurityGroupIngres // Rule changes are propagated to instances within the security group as quickly // as possible. However, a small delay might occur. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -52482,20 +54501,13 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // You can specify a number of options, or leave the default options. The following // rules apply: // -// - [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet -// from your default VPC for you. If you don't have a default VPC, you must -// specify a subnet ID in the request. -// -// - [EC2-Classic] If don't specify an Availability Zone, we choose one for -// you. -// -// - Some instance types must be launched into a VPC. If you do not have -// a default VPC, or if you do not specify a subnet ID, the request fails. -// For more information, see Instance types available only in a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types). +// - If you don't specify a subnet ID, we choose a default subnet from your +// default VPC for you. If you don't have a default VPC, you must specify +// a subnet ID in the request. // -// - [EC2-VPC] All instances have a network interface with a primary private -// IPv4 address. If you don't specify this address, we choose one from the -// IPv4 range of your subnet. +// - All instances have a network interface with a primary private IPv4 address. +// If you don't specify this address, we choose one from the IPv4 range of +// your subnet. // // - Not all instance types support IPv6 addresses. For more information, // see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). @@ -52529,10 +54541,6 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html), // and Troubleshooting connecting to your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html). // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon EC2 User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -53440,8 +55448,8 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // in the Amazon EC2 User Guide. // // You can use the Stop action to hibernate an instance if the instance is enabled -// for hibernation (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) -// and it meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). +// for hibernation (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enabling-hibernation.html) +// and it meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hibernating-prerequisites.html). // For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon EC2 User Guide. // @@ -53904,17 +55912,17 @@ func (c *EC2) UnassignPrivateNatGatewayAddressRequest(input *UnassignPrivateNatG // Unassigns secondary private IPv4 addresses from a private NAT gateway. You // cannot unassign your primary private IP. For more information, see Edit secondary // IP address associations (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-edit-secondary) -// in the Amazon Virtual Private Cloud User Guide. +// in the Amazon VPC User Guide. // // While unassigning is in progress, you cannot assign/unassign additional IP // addresses while the connections are being drained. You are, however, allowed // to delete the NAT gateway. // // A private IP address will only be released at the end of MaxDrainDurationSeconds. -// The private IP addresses stay associated and support the existing connections +// The private IP addresses stay associated and support the existing connections, // but do not support any new connections (new connections are distributed across // the remaining assigned private IP address). After the existing connections -// drain out, the private IP addresses get released. +// drain out, the private IP addresses are released. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -53944,6 +55952,81 @@ func (c *EC2) UnassignPrivateNatGatewayAddressWithContext(ctx aws.Context, input return out, req.Send() } +const opUnlockSnapshot = "UnlockSnapshot" + +// UnlockSnapshotRequest generates a "aws/request.Request" representing the +// client's request for the UnlockSnapshot operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UnlockSnapshot for more information on using the UnlockSnapshot +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the UnlockSnapshotRequest method. +// req, resp := client.UnlockSnapshotRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnlockSnapshot +func (c *EC2) UnlockSnapshotRequest(input *UnlockSnapshotInput) (req *request.Request, output *UnlockSnapshotOutput) { + op := &request.Operation{ + Name: opUnlockSnapshot, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UnlockSnapshotInput{} + } + + output = &UnlockSnapshotOutput{} + req = c.newRequest(op, input, output) + return +} + +// UnlockSnapshot API operation for Amazon Elastic Compute Cloud. +// +// Unlocks a snapshot that is locked in governance mode or that is locked in +// compliance mode but still in the cooling-off period. You can't unlock a snapshot +// that is locked in compliance mode after the cooling-off period has expired. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation UnlockSnapshot for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnlockSnapshot +func (c *EC2) UnlockSnapshot(input *UnlockSnapshotInput) (*UnlockSnapshotOutput, error) { + req, out := c.UnlockSnapshotRequest(input) + return out, req.Send() +} + +// UnlockSnapshotWithContext is the same as UnlockSnapshot with the addition of +// the ability to pass a context and additional request options. +// +// See UnlockSnapshot for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) UnlockSnapshotWithContext(ctx aws.Context, input *UnlockSnapshotInput, opts ...request.Option) (*UnlockSnapshotOutput, error) { + req, out := c.UnlockSnapshotRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUnmonitorInstances = "UnmonitorInstances" // UnmonitorInstancesRequest generates a "aws/request.Request" representing the @@ -54062,10 +56145,10 @@ func (c *EC2) UpdateSecurityGroupRuleDescriptionsEgressRequest(input *UpdateSecu // UpdateSecurityGroupRuleDescriptionsEgress API operation for Amazon Elastic Compute Cloud. // -// [VPC only] Updates the description of an egress (outbound) security group -// rule. You can replace an existing description, or add a description to a -// rule that did not have one previously. You can remove a description for a -// security group rule by omitting the description parameter in the request. +// Updates the description of an egress (outbound) security group rule. You +// can replace an existing description, or add a description to a rule that +// did not have one previously. You can remove a description for a security +// group rule by omitting the description parameter in the request. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -55650,11 +57733,10 @@ func (s *AdditionalDetail) SetVpcEndpointService(v *AnalysisComponent) *Addition type Address struct { _ struct{} `type:"structure"` - // The ID representing the allocation of the address for use with EC2-VPC. + // The ID representing the allocation of the address. AllocationId *string `locationName:"allocationId" type:"string"` - // The ID representing the association of the address with an instance in a - // VPC. + // The ID representing the association of the address with an instance. AssociationId *string `locationName:"associationId" type:"string"` // The carrier IP address associated. This option is only available for network @@ -55668,8 +57750,7 @@ type Address struct { // The ID of the customer-owned address pool. CustomerOwnedIpv4Pool *string `locationName:"customerOwnedIpv4Pool" type:"string"` - // Indicates whether this Elastic IP address is for use with instances in EC2-Classic - // (standard) or instances in a VPC (vpc). + // The network (vpc). Domain *string `locationName:"domain" type:"string" enum:"DomainType"` // The ID of the instance that the address is associated with (if any). @@ -55944,6 +58025,9 @@ func (s *AddressTransfer) SetTransferOfferExpirationTimestamp(v time.Time) *Addr type AdvertiseByoipCidrInput struct { _ struct{} `type:"structure"` + // The public 2-byte or 4-byte ASN that you want to advertise. + Asn *string `type:"string"` + // The address range, in CIDR notation. This must be the exact range that you // provisioned. You can't advertise only a portion of the provisioned range. // @@ -55955,6 +58039,25 @@ type AdvertiseByoipCidrInput struct { // the required permissions, the error response is DryRunOperation. Otherwise, // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` + + // If you have Local Zones (https://docs.aws.amazon.com/local-zones/latest/ug/how-local-zones-work.html) + // enabled, you can choose a network border group for Local Zones when you provision + // and advertise a BYOIPv4 CIDR. Choose the network border group carefully as + // the EIP and the Amazon Web Services resource it is associated with must reside + // in the same network border group. + // + // You can provision BYOIP address ranges to and advertise them in the following + // Local Zone network border groups: + // + // * us-east-1-dfw-2 + // + // * us-west-2-lax-1 + // + // * us-west-2-phx-2 + // + // You cannot provision or advertise BYOIPv6 address ranges in Local Zones at + // this time. + NetworkBorderGroup *string `type:"string"` } // String returns the string representation. @@ -55988,6 +58091,12 @@ func (s *AdvertiseByoipCidrInput) Validate() error { return nil } +// SetAsn sets the Asn field's value. +func (s *AdvertiseByoipCidrInput) SetAsn(v string) *AdvertiseByoipCidrInput { + s.Asn = &v + return s +} + // SetCidr sets the Cidr field's value. func (s *AdvertiseByoipCidrInput) SetCidr(v string) *AdvertiseByoipCidrInput { s.Cidr = &v @@ -56000,6 +58109,12 @@ func (s *AdvertiseByoipCidrInput) SetDryRun(v bool) *AdvertiseByoipCidrInput { return s } +// SetNetworkBorderGroup sets the NetworkBorderGroup field's value. +func (s *AdvertiseByoipCidrInput) SetNetworkBorderGroup(v string) *AdvertiseByoipCidrInput { + s.NetworkBorderGroup = &v + return s +} + type AdvertiseByoipCidrOutput struct { _ struct{} `type:"structure"` @@ -56034,8 +58149,7 @@ func (s *AdvertiseByoipCidrOutput) SetByoipCidr(v *ByoipCidr) *AdvertiseByoipCid type AllocateAddressInput struct { _ struct{} `type:"structure"` - // [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address - // pool. + // The Elastic IP address to recover or an IPv4 address from an address pool. Address *string `type:"string"` // The ID of a customer-owned address pool. Use this parameter to let Amazon @@ -56043,11 +58157,7 @@ type AllocateAddressInput struct { // address from the address pool. CustomerOwnedIpv4Pool *string `type:"string"` - // Indicates whether the Elastic IP address is for use with instances in a VPC - // or instances in EC2-Classic. - // - // Default: If the Region supports EC2-Classic, the default is standard. Otherwise, - // the default is vpc. + // The network (vpc). Domain *string `type:"string" enum:"DomainType"` // Checks whether you have the required permissions for the action, without @@ -56063,9 +58173,6 @@ type AllocateAddressInput struct { // // Use DescribeAvailabilityZones (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) // to view the network border groups. - // - // You cannot use a network border group with EC2 Classic. If you attempt this - // operation on EC2 Classic, you receive an InvalidParameterCombination error. NetworkBorderGroup *string `type:"string"` // The ID of an address pool that you own. Use this parameter to let Amazon @@ -56140,12 +58247,11 @@ func (s *AllocateAddressInput) SetTagSpecifications(v []*TagSpecification) *Allo type AllocateAddressOutput struct { _ struct{} `type:"structure"` - // [EC2-VPC] The ID that Amazon Web Services assigns to represent the allocation - // of the Elastic IP address for use with instances in a VPC. + // The ID that represents the allocation of the Elastic IP address. AllocationId *string `locationName:"allocationId" type:"string"` // The carrier IP address. This option is only available for network interfaces - // which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + // that reside in a subnet in a Wavelength Zone. CarrierIp *string `locationName:"carrierIp" type:"string"` // The customer-owned IP address. @@ -56154,8 +58260,7 @@ type AllocateAddressOutput struct { // The ID of the customer-owned address pool. CustomerOwnedIpv4Pool *string `locationName:"customerOwnedIpv4Pool" type:"string"` - // Indicates whether the Elastic IP address is for use with instances in a VPC - // (vpc) or instances in EC2-Classic (standard). + // The network (vpc). Domain *string `locationName:"domain" type:"string" enum:"DomainType"` // The set of Availability Zones, Local Zones, or Wavelength Zones from which @@ -56238,6 +58343,19 @@ func (s *AllocateAddressOutput) SetPublicIpv4Pool(v string) *AllocateAddressOutp type AllocateHostsInput struct { _ struct{} `type:"structure"` + // The IDs of the Outpost hardware assets on which to allocate the Dedicated + // Hosts. Targeting specific hardware assets on an Outpost can help to minimize + // latency between your workloads. This parameter is supported only if you specify + // OutpostArn. If you are allocating the Dedicated Hosts in a Region, omit this + // parameter. + // + // * If you specify this parameter, you can omit Quantity. In this case, + // Amazon EC2 allocates a Dedicated Host on each specified hardware asset. + // + // * If you specify both AssetIds and Quantity, then the value for Quantity + // must be equal to the number of asset IDs specified. + AssetIds []*string `locationName:"AssetId" type:"list"` + // Indicates whether the host accepts any untargeted instance launches that // match its instance type configuration, or if it only accepts Host tenancy // instance launches that specify its unique host ID. For more information, @@ -56288,13 +58406,19 @@ type AllocateHostsInput struct { InstanceType *string `locationName:"instanceType" type:"string"` // The Amazon Resource Name (ARN) of the Amazon Web Services Outpost on which - // to allocate the Dedicated Host. + // to allocate the Dedicated Host. If you specify OutpostArn, you can optionally + // specify AssetIds. + // + // If you are allocating the Dedicated Host in a Region, omit this parameter. OutpostArn *string `type:"string"` // The number of Dedicated Hosts to allocate to your account with these parameters. - // - // Quantity is a required field - Quantity *int64 `locationName:"quantity" type:"integer" required:"true"` + // If you are allocating the Dedicated Hosts on an Outpost, and you specify + // AssetIds, you can omit this parameter. In this case, Amazon EC2 allocates + // a Dedicated Host on each specified hardware asset. If you specify both AssetIds + // and Quantity, then the value that you specify for Quantity must be equal + // to the number of asset IDs specified. + Quantity *int64 `locationName:"quantity" type:"integer"` // The tags to apply to the Dedicated Host during creation. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` @@ -56324,9 +58448,6 @@ func (s *AllocateHostsInput) Validate() error { if s.AvailabilityZone == nil { invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) } - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } if invalidParams.Len() > 0 { return invalidParams @@ -56334,6 +58455,12 @@ func (s *AllocateHostsInput) Validate() error { return nil } +// SetAssetIds sets the AssetIds field's value. +func (s *AllocateHostsInput) SetAssetIds(v []*string) *AllocateHostsInput { + s.AssetIds = v + return s +} + // SetAutoPlacement sets the AutoPlacement field's value. func (s *AllocateHostsInput) SetAutoPlacement(v string) *AllocateHostsInput { s.AutoPlacement = &v @@ -56430,6 +58557,10 @@ func (s *AllocateHostsOutput) SetHostIds(v []*string) *AllocateHostsOutput { type AllocateIpamPoolCidrInput struct { _ struct{} `type:"structure"` + // Include a particular CIDR range that can be returned by the pool. Allowed + // CIDRs are only allowed if using netmask length for allocation. + AllowedCidrs []*string `locationName:"AllowedCidr" locationNameList:"item" type:"list"` + // The CIDR you would like to allocate from the IPAM pool. Note the following: // // * If there is no DefaultNetmaskLength allocation rule set on the pool, @@ -56513,6 +58644,12 @@ func (s *AllocateIpamPoolCidrInput) Validate() error { return nil } +// SetAllowedCidrs sets the AllowedCidrs field's value. +func (s *AllocateIpamPoolCidrInput) SetAllowedCidrs(v []*string) *AllocateIpamPoolCidrInput { + s.AllowedCidrs = v + return s +} + // SetCidr sets the Cidr field's value. func (s *AllocateIpamPoolCidrInput) SetCidr(v string) *AllocateIpamPoolCidrInput { s.Cidr = &v @@ -57357,6 +59494,130 @@ func (s *ApplySecurityGroupsToClientVpnTargetNetworkOutput) SetSecurityGroupIds( return s } +// An Autonomous System Number (ASN) and BYOIP CIDR association. +type AsnAssociation struct { + _ struct{} `type:"structure"` + + // The association's ASN. + Asn *string `locationName:"asn" type:"string"` + + // The association's CIDR. + Cidr *string `locationName:"cidr" type:"string"` + + // The association's state. + State *string `locationName:"state" type:"string" enum:"AsnAssociationState"` + + // The association's status message. + StatusMessage *string `locationName:"statusMessage" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AsnAssociation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AsnAssociation) GoString() string { + return s.String() +} + +// SetAsn sets the Asn field's value. +func (s *AsnAssociation) SetAsn(v string) *AsnAssociation { + s.Asn = &v + return s +} + +// SetCidr sets the Cidr field's value. +func (s *AsnAssociation) SetCidr(v string) *AsnAssociation { + s.Cidr = &v + return s +} + +// SetState sets the State field's value. +func (s *AsnAssociation) SetState(v string) *AsnAssociation { + s.State = &v + return s +} + +// SetStatusMessage sets the StatusMessage field's value. +func (s *AsnAssociation) SetStatusMessage(v string) *AsnAssociation { + s.StatusMessage = &v + return s +} + +// Provides authorization for Amazon to bring an Autonomous System Number (ASN) +// to a specific Amazon Web Services account using bring your own ASN (BYOASN). +// For details on the format of the message and signature, see Tutorial: Bring +// your ASN to IPAM (https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-byoasn.html) +// in the Amazon VPC IPAM guide. +type AsnAuthorizationContext struct { + _ struct{} `type:"structure"` + + // The authorization context's message. + // + // Message is a required field + Message *string `type:"string" required:"true"` + + // The authorization context's signature. + // + // Signature is a required field + Signature *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AsnAuthorizationContext) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AsnAuthorizationContext) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AsnAuthorizationContext) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AsnAuthorizationContext"} + if s.Message == nil { + invalidParams.Add(request.NewErrParamRequired("Message")) + } + if s.Signature == nil { + invalidParams.Add(request.NewErrParamRequired("Signature")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMessage sets the Message field's value. +func (s *AsnAuthorizationContext) SetMessage(v string) *AsnAuthorizationContext { + s.Message = &v + return s +} + +// SetSignature sets the Signature field's value. +func (s *AsnAuthorizationContext) SetSignature(v string) *AsnAuthorizationContext { + s.Signature = &v + return s +} + type AssignIpv6AddressesInput struct { _ struct{} `type:"structure"` @@ -57657,7 +59918,7 @@ type AssignPrivateNatGatewayAddressInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The NAT gateway ID. + // The ID of the NAT gateway. // // NatGatewayId is a required field NatGatewayId *string `type:"string" required:"true"` @@ -57734,7 +59995,7 @@ type AssignPrivateNatGatewayAddressOutput struct { // NAT gateway IP addresses. NatGatewayAddresses []*NatGatewayAddress `locationName:"natGatewayAddressSet" locationNameList:"item" type:"list"` - // The NAT gateway ID. + // The ID of the NAT gateway. NatGatewayId *string `locationName:"natGatewayId" type:"string"` } @@ -57803,15 +60064,11 @@ func (s *AssignedPrivateIpAddress) SetPrivateIpAddress(v string) *AssignedPrivat type AssociateAddressInput struct { _ struct{} `type:"structure"` - // [EC2-VPC] The allocation ID. This is required for EC2-VPC. + // The allocation ID. This is required. AllocationId *string `type:"string"` - // [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic - // IP address that is already associated with an instance or network interface - // to be reassociated with the specified instance or network interface. Otherwise, - // the operation fails. In a VPC in an EC2-VPC-only account, reassociation is - // automatic, therefore you can specify false to ensure the operation fails - // if the Elastic IP address is already associated with another resource. + // Reassociation is automatic, but you can specify false to ensure the operation + // fails if the Elastic IP address is already associated with another resource. AllowReassociation *bool `locationName:"allowReassociation" type:"boolean"` // Checks whether you have the required permissions for the action, without @@ -57821,25 +60078,23 @@ type AssociateAddressInput struct { DryRun *bool `locationName:"dryRun" type:"boolean"` // The ID of the instance. The instance must have exactly one attached network - // interface. For EC2-VPC, you can specify either the instance ID or the network - // interface ID, but not both. For EC2-Classic, you must specify an instance - // ID and the instance must be in the running state. + // interface. You can specify either the instance ID or the network interface + // ID, but not both. InstanceId *string `type:"string"` - // [EC2-VPC] The ID of the network interface. If the instance has more than - // one network interface, you must specify a network interface ID. + // The ID of the network interface. If the instance has more than one network + // interface, you must specify a network interface ID. // - // For EC2-VPC, you can specify either the instance ID or the network interface - // ID, but not both. + // You can specify either the instance ID or the network interface ID, but not + // both. NetworkInterfaceId *string `locationName:"networkInterfaceId" type:"string"` - // [EC2-VPC] The primary or secondary private IP address to associate with the - // Elastic IP address. If no private IP address is specified, the Elastic IP - // address is associated with the primary private IP address. + // The primary or secondary private IP address to associate with the Elastic + // IP address. If no private IP address is specified, the Elastic IP address + // is associated with the primary private IP address. PrivateIpAddress *string `locationName:"privateIpAddress" type:"string"` - // [EC2-Classic] The Elastic IP address to associate with the instance. This - // is required for EC2-Classic. + // Deprecated. PublicIp *string `type:"string"` } @@ -57906,8 +60161,8 @@ func (s *AssociateAddressInput) SetPublicIp(v string) *AssociateAddressInput { type AssociateAddressOutput struct { _ struct{} `type:"structure"` - // [EC2-VPC] The ID that represents the association of the Elastic IP address - // with an instance. + // The ID that represents the association of the Elastic IP address with an + // instance. AssociationId *string `locationName:"associationId" type:"string"` } @@ -58469,6 +60724,109 @@ func (s *AssociateInstanceEventWindowOutput) SetInstanceEventWindow(v *InstanceE return s } +type AssociateIpamByoasnInput struct { + _ struct{} `type:"structure"` + + // A public 2-byte or 4-byte ASN. + // + // Asn is a required field + Asn *string `type:"string" required:"true"` + + // The BYOIP CIDR you want to associate with an ASN. + // + // Cidr is a required field + Cidr *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AssociateIpamByoasnInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AssociateIpamByoasnInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateIpamByoasnInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateIpamByoasnInput"} + if s.Asn == nil { + invalidParams.Add(request.NewErrParamRequired("Asn")) + } + if s.Cidr == nil { + invalidParams.Add(request.NewErrParamRequired("Cidr")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAsn sets the Asn field's value. +func (s *AssociateIpamByoasnInput) SetAsn(v string) *AssociateIpamByoasnInput { + s.Asn = &v + return s +} + +// SetCidr sets the Cidr field's value. +func (s *AssociateIpamByoasnInput) SetCidr(v string) *AssociateIpamByoasnInput { + s.Cidr = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *AssociateIpamByoasnInput) SetDryRun(v bool) *AssociateIpamByoasnInput { + s.DryRun = &v + return s +} + +type AssociateIpamByoasnOutput struct { + _ struct{} `type:"structure"` + + // The ASN and BYOIP CIDR association. + AsnAssociation *AsnAssociation `locationName:"asnAssociation" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AssociateIpamByoasnOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AssociateIpamByoasnOutput) GoString() string { + return s.String() +} + +// SetAsnAssociation sets the AsnAssociation field's value. +func (s *AssociateIpamByoasnOutput) SetAsnAssociation(v *AsnAssociation) *AssociateIpamByoasnOutput { + s.AsnAssociation = v + return s +} + type AssociateIpamResourceDiscoveryInput struct { _ struct{} `type:"structure"` @@ -58605,7 +60963,7 @@ type AssociateNatGatewayAddressInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The NAT gateway ID. + // The ID of the NAT gateway. // // NatGatewayId is a required field NatGatewayId *string `type:"string" required:"true"` @@ -58678,7 +61036,7 @@ type AssociateNatGatewayAddressOutput struct { // The IP addresses. NatGatewayAddresses []*NatGatewayAddress `locationName:"natGatewayAddressSet" locationNameList:"item" type:"list"` - // The NAT gateway ID. + // The ID of the NAT gateway. NatGatewayId *string `locationName:"natGatewayId" type:"string"` } @@ -58832,10 +61190,14 @@ func (s *AssociateRouteTableOutput) SetAssociationState(v *RouteTableAssociation type AssociateSubnetCidrBlockInput struct { _ struct{} `type:"structure"` - // The IPv6 CIDR block for your subnet. The subnet must have a /64 prefix length. - // - // Ipv6CidrBlock is a required field - Ipv6CidrBlock *string `locationName:"ipv6CidrBlock" type:"string" required:"true"` + // The IPv6 CIDR block for your subnet. + Ipv6CidrBlock *string `locationName:"ipv6CidrBlock" type:"string"` + + // An IPv6 IPAM pool ID. + Ipv6IpamPoolId *string `type:"string"` + + // An IPv6 netmask length. + Ipv6NetmaskLength *int64 `type:"integer"` // The ID of your subnet. // @@ -58864,9 +61226,6 @@ func (s AssociateSubnetCidrBlockInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *AssociateSubnetCidrBlockInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "AssociateSubnetCidrBlockInput"} - if s.Ipv6CidrBlock == nil { - invalidParams.Add(request.NewErrParamRequired("Ipv6CidrBlock")) - } if s.SubnetId == nil { invalidParams.Add(request.NewErrParamRequired("SubnetId")) } @@ -58883,6 +61242,18 @@ func (s *AssociateSubnetCidrBlockInput) SetIpv6CidrBlock(v string) *AssociateSub return s } +// SetIpv6IpamPoolId sets the Ipv6IpamPoolId field's value. +func (s *AssociateSubnetCidrBlockInput) SetIpv6IpamPoolId(v string) *AssociateSubnetCidrBlockInput { + s.Ipv6IpamPoolId = &v + return s +} + +// SetIpv6NetmaskLength sets the Ipv6NetmaskLength field's value. +func (s *AssociateSubnetCidrBlockInput) SetIpv6NetmaskLength(v int64) *AssociateSubnetCidrBlockInput { + s.Ipv6NetmaskLength = &v + return s +} + // SetSubnetId sets the SubnetId field's value. func (s *AssociateSubnetCidrBlockInput) SetSubnetId(v string) *AssociateSubnetCidrBlockInput { s.SubnetId = &v @@ -59401,7 +61772,7 @@ type AssociateVpcCidrBlockInput struct { _ struct{} `type:"structure"` // Requests an Amazon-provided IPv6 CIDR block with a /56 prefix length for - // the VPC. You cannot specify the range of IPv6 addresses, or the size of the + // the VPC. You cannot specify the range of IPv6 addresses or the size of the // CIDR block. AmazonProvidedIpv6CidrBlock *bool `locationName:"amazonProvidedIpv6CidrBlock" type:"boolean"` @@ -59825,18 +62196,18 @@ type AttachClassicLinkVpcInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The ID of one or more of the VPC's security groups. You cannot specify security - // groups from a different VPC. + // The IDs of the security groups. You cannot specify security groups from a + // different VPC. // // Groups is a required field Groups []*string `locationName:"SecurityGroupId" locationNameList:"groupId" type:"list" required:"true"` - // The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC. + // The ID of the EC2-Classic instance. // // InstanceId is a required field InstanceId *string `locationName:"instanceId" type:"string" required:"true"` - // The ID of a ClassicLink-enabled VPC. + // The ID of the ClassicLink-enabled VPC. // // VpcId is a required field VpcId *string `locationName:"vpcId" type:"string" required:"true"` @@ -60191,12 +62562,12 @@ type AttachVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -60263,10 +62634,10 @@ func (s *AttachVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderI type AttachVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // Details about the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // Details about the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -60492,16 +62863,25 @@ func (s *AttachVpnGatewayOutput) SetVpcAttachment(v *VpcAttachment) *AttachVpnGa return s } -// Describes the ENA Express configuration for the network interface that's -// attached to the instance. +// ENA Express uses Amazon Web Services Scalable Reliable Datagram (SRD) technology +// to increase the maximum bandwidth used per stream and minimize tail latency +// of network traffic between EC2 instances. With ENA Express, you can communicate +// between two EC2 instances in the same subnet within the same account, or +// in different accounts. Both sending and receiving instances must have ENA +// Express enabled. +// +// To improve the reliability of network packet delivery, ENA Express reorders +// network packets on the receiving end by default. However, some UDP-based +// applications are designed to handle network packets that are out of order +// to reduce the overhead for packet delivery at the network layer. When ENA +// Express is enabled, you can specify whether UDP network traffic uses it. type AttachmentEnaSrdSpecification struct { _ struct{} `type:"structure"` - // Indicates whether ENA Express is enabled for the network interface that's - // attached to the instance. + // Indicates whether ENA Express is enabled for the network interface. EnaSrdEnabled *bool `locationName:"enaSrdEnabled" type:"boolean"` - // ENA Express configuration for UDP network traffic. + // Configures ENA Express for UDP network traffic. EnaSrdUdpSpecification *AttachmentEnaSrdUdpSpecification `locationName:"enaSrdUdpSpecification" type:"structure"` } @@ -60535,8 +62915,12 @@ func (s *AttachmentEnaSrdSpecification) SetEnaSrdUdpSpecification(v *AttachmentE return s } -// Describes the ENA Express configuration for UDP traffic on the network interface -// that's attached to the instance. +// ENA Express is compatible with both TCP and UDP transport protocols. When +// it's enabled, TCP traffic automatically uses it. However, some UDP-based +// applications are designed to handle network packets that are out of order, +// without a need for retransmission, such as live video broadcasting or other +// near-real-time applications. For UDP traffic, you can specify whether to +// use ENA Express, based on your application environment needs. type AttachmentEnaSrdUdpSpecification struct { _ struct{} `type:"structure"` @@ -61061,10 +63445,9 @@ type AuthorizeSecurityGroupIngressInput struct { // VPC, you must specify the security group ID. GroupId *string `type:"string"` - // [EC2-Classic, default VPC] The name of the security group. You must specify - // either the security group ID or the security group name in the request. For - // security groups in a nondefault VPC, you must specify the security group - // ID. + // [Default VPC] The name of the security group. You must specify either the + // security group ID or the security group name in the request. For security + // groups in a nondefault VPC, you must specify the security group ID. GroupName *string `type:"string"` // The sets of IP permissions. @@ -61073,24 +63456,23 @@ type AuthorizeSecurityGroupIngressInput struct { // The IP protocol name (tcp, udp, icmp) or number (see Protocol Numbers (http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml)). // To specify icmpv6, use a set of IP permissions. // - // [VPC only] Use -1 to specify all protocols. If you specify -1 or a protocol - // other than tcp, udp, or icmp, traffic on all ports is allowed, regardless - // of any ports you specify. + // Use -1 to specify all protocols. If you specify -1 or a protocol other than + // tcp, udp, or icmp, traffic on all ports is allowed, regardless of any ports + // you specify. // // Alternatively, use a set of IP permissions to specify multiple rules and // a description for the rule. IpProtocol *string `type:"string"` - // [EC2-Classic, default VPC] The name of the source security group. You can't - // specify this parameter in combination with the following parameters: the - // CIDR IP address range, the start of the port range, the IP protocol, and - // the end of the port range. Creates rules that grant full ICMP, UDP, and TCP - // access. To create a rule with a specific IP protocol and port range, use - // a set of IP permissions instead. For EC2-VPC, the source security group must - // be in the same VPC. + // [Default VPC] The name of the source security group. You can't specify this + // parameter in combination with the following parameters: the CIDR IP address + // range, the start of the port range, the IP protocol, and the end of the port + // range. Creates rules that grant full ICMP, UDP, and TCP access. To create + // a rule with a specific IP protocol and port range, use a set of IP permissions + // instead. The source security group must be in the same VPC. SourceSecurityGroupName *string `type:"string"` - // [nondefault VPC] The Amazon Web Services account ID for the source security + // [Nondefault VPC] The Amazon Web Services account ID for the source security // group, if the source security group is in a different account. You can't // specify this parameter in combination with the following parameters: the // CIDR IP address range, the IP protocol, the start of the port range, and @@ -61892,17 +64274,98 @@ func (s *BundleTaskError) SetMessage(v string) *BundleTaskError { return s } +// The Autonomous System Number (ASN) and BYOIP CIDR association. +type Byoasn struct { + _ struct{} `type:"structure"` + + // A public 2-byte or 4-byte ASN. + Asn *string `locationName:"asn" type:"string"` + + // An IPAM ID. + IpamId *string `locationName:"ipamId" type:"string"` + + // The provisioning state of the BYOASN. + State *string `locationName:"state" type:"string" enum:"AsnState"` + + // The status message. + StatusMessage *string `locationName:"statusMessage" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s Byoasn) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s Byoasn) GoString() string { + return s.String() +} + +// SetAsn sets the Asn field's value. +func (s *Byoasn) SetAsn(v string) *Byoasn { + s.Asn = &v + return s +} + +// SetIpamId sets the IpamId field's value. +func (s *Byoasn) SetIpamId(v string) *Byoasn { + s.IpamId = &v + return s +} + +// SetState sets the State field's value. +func (s *Byoasn) SetState(v string) *Byoasn { + s.State = &v + return s +} + +// SetStatusMessage sets the StatusMessage field's value. +func (s *Byoasn) SetStatusMessage(v string) *Byoasn { + s.StatusMessage = &v + return s +} + // Information about an address range that is provisioned for use with your // Amazon Web Services resources through bring your own IP addresses (BYOIP). type ByoipCidr struct { _ struct{} `type:"structure"` + // The BYOIP CIDR associations with ASNs. + AsnAssociations []*AsnAssociation `locationName:"asnAssociationSet" locationNameList:"item" type:"list"` + // The address range, in CIDR notation. Cidr *string `locationName:"cidr" type:"string"` // The description of the address range. Description *string `locationName:"description" type:"string"` + // If you have Local Zones (https://docs.aws.amazon.com/local-zones/latest/ug/how-local-zones-work.html) + // enabled, you can choose a network border group for Local Zones when you provision + // and advertise a BYOIPv4 CIDR. Choose the network border group carefully as + // the EIP and the Amazon Web Services resource it is associated with must reside + // in the same network border group. + // + // You can provision BYOIP address ranges to and advertise them in the following + // Local Zone network border groups: + // + // * us-east-1-dfw-2 + // + // * us-west-2-lax-1 + // + // * us-west-2-phx-2 + // + // You cannot provision or advertise BYOIPv6 address ranges in Local Zones at + // this time. + NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` + // The state of the address pool. State *string `locationName:"state" type:"string" enum:"ByoipCidrState"` @@ -61929,6 +64392,12 @@ func (s ByoipCidr) GoString() string { return s.String() } +// SetAsnAssociations sets the AsnAssociations field's value. +func (s *ByoipCidr) SetAsnAssociations(v []*AsnAssociation) *ByoipCidr { + s.AsnAssociations = v + return s +} + // SetCidr sets the Cidr field's value. func (s *ByoipCidr) SetCidr(v string) *ByoipCidr { s.Cidr = &v @@ -61941,6 +64410,12 @@ func (s *ByoipCidr) SetDescription(v string) *ByoipCidr { return s } +// SetNetworkBorderGroup sets the NetworkBorderGroup field's value. +func (s *ByoipCidr) SetNetworkBorderGroup(v string) *ByoipCidr { + s.NetworkBorderGroup = &v + return s +} + // SetState sets the State field's value. func (s *ByoipCidr) SetState(v string) *ByoipCidr { s.State = &v @@ -62365,7 +64840,8 @@ func (s CancelConversionTaskOutput) GoString() string { type CancelExportTaskInput struct { _ struct{} `type:"structure"` - // The ID of the export task. This is the ID returned by CreateInstanceExportTask. + // The ID of the export task. This is the ID returned by the CreateInstanceExportTask + // and ExportImage operations. // // ExportTaskId is a required field ExportTaskId *string `locationName:"exportTaskId" type:"string" required:"true"` @@ -62959,7 +65435,7 @@ type CancelSpotInstanceRequestsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more Spot Instance request IDs. + // The IDs of the Spot Instance requests. // // SpotInstanceRequestIds is a required field SpotInstanceRequestIds []*string `locationName:"SpotInstanceRequestId" locationNameList:"SpotInstanceRequestId" type:"list" required:"true"` @@ -63012,7 +65488,7 @@ func (s *CancelSpotInstanceRequestsInput) SetSpotInstanceRequestIds(v []*string) type CancelSpotInstanceRequestsOutput struct { _ struct{} `type:"structure"` - // One or more Spot Instance requests. + // The Spot Instance requests. CancelledSpotInstanceRequests []*CancelledSpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` } @@ -63125,6 +65601,119 @@ func (s *CapacityAllocation) SetCount(v int64) *CapacityAllocation { return s } +// The recommended Capacity Block that fits your search requirements. +type CapacityBlockOffering struct { + _ struct{} `type:"structure"` + + // The Availability Zone of the Capacity Block offering. + AvailabilityZone *string `locationName:"availabilityZone" type:"string"` + + // The amount of time of the Capacity Block reservation in hours. + CapacityBlockDurationHours *int64 `locationName:"capacityBlockDurationHours" type:"integer"` + + // The ID of the Capacity Block offering. + CapacityBlockOfferingId *string `locationName:"capacityBlockOfferingId" type:"string"` + + // The currency of the payment for the Capacity Block. + CurrencyCode *string `locationName:"currencyCode" type:"string"` + + // The end date of the Capacity Block offering. + EndDate *time.Time `locationName:"endDate" type:"timestamp"` + + // The number of instances in the Capacity Block offering. + InstanceCount *int64 `locationName:"instanceCount" type:"integer"` + + // The instance type of the Capacity Block offering. + InstanceType *string `locationName:"instanceType" type:"string"` + + // The start date of the Capacity Block offering. + StartDate *time.Time `locationName:"startDate" type:"timestamp"` + + // The tenancy of the Capacity Block. + Tenancy *string `locationName:"tenancy" type:"string" enum:"CapacityReservationTenancy"` + + // The total price to be paid up front. + UpfrontFee *string `locationName:"upfrontFee" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CapacityBlockOffering) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CapacityBlockOffering) GoString() string { + return s.String() +} + +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *CapacityBlockOffering) SetAvailabilityZone(v string) *CapacityBlockOffering { + s.AvailabilityZone = &v + return s +} + +// SetCapacityBlockDurationHours sets the CapacityBlockDurationHours field's value. +func (s *CapacityBlockOffering) SetCapacityBlockDurationHours(v int64) *CapacityBlockOffering { + s.CapacityBlockDurationHours = &v + return s +} + +// SetCapacityBlockOfferingId sets the CapacityBlockOfferingId field's value. +func (s *CapacityBlockOffering) SetCapacityBlockOfferingId(v string) *CapacityBlockOffering { + s.CapacityBlockOfferingId = &v + return s +} + +// SetCurrencyCode sets the CurrencyCode field's value. +func (s *CapacityBlockOffering) SetCurrencyCode(v string) *CapacityBlockOffering { + s.CurrencyCode = &v + return s +} + +// SetEndDate sets the EndDate field's value. +func (s *CapacityBlockOffering) SetEndDate(v time.Time) *CapacityBlockOffering { + s.EndDate = &v + return s +} + +// SetInstanceCount sets the InstanceCount field's value. +func (s *CapacityBlockOffering) SetInstanceCount(v int64) *CapacityBlockOffering { + s.InstanceCount = &v + return s +} + +// SetInstanceType sets the InstanceType field's value. +func (s *CapacityBlockOffering) SetInstanceType(v string) *CapacityBlockOffering { + s.InstanceType = &v + return s +} + +// SetStartDate sets the StartDate field's value. +func (s *CapacityBlockOffering) SetStartDate(v time.Time) *CapacityBlockOffering { + s.StartDate = &v + return s +} + +// SetTenancy sets the Tenancy field's value. +func (s *CapacityBlockOffering) SetTenancy(v string) *CapacityBlockOffering { + s.Tenancy = &v + return s +} + +// SetUpfrontFee sets the UpfrontFee field's value. +func (s *CapacityBlockOffering) SetUpfrontFee(v string) *CapacityBlockOffering { + s.UpfrontFee = &v + return s +} + // Describes a Capacity Reservation. type CapacityReservation struct { _ struct{} `type:"structure"` @@ -63216,6 +65805,9 @@ type CapacityReservation struct { // in the Amazon EC2 User Guide. PlacementGroupArn *string `locationName:"placementGroupArn" type:"string"` + // The type of Capacity Reservation. + ReservationType *string `locationName:"reservationType" type:"string" enum:"CapacityReservationType"` + // The date and time at which the Capacity Reservation was started. StartDate *time.Time `locationName:"startDate" type:"timestamp"` @@ -63384,6 +65976,12 @@ func (s *CapacityReservation) SetPlacementGroupArn(v string) *CapacityReservatio return s } +// SetReservationType sets the ReservationType field's value. +func (s *CapacityReservation) SetReservationType(v string) *CapacityReservation { + s.ReservationType = &v + return s +} + // SetStartDate sets the StartDate field's value. func (s *CapacityReservation) SetStartDate(v time.Time) *CapacityReservation { s.StartDate = &v @@ -64217,6 +66815,8 @@ func (s *CidrBlock) SetCidrBlock(v string) *CidrBlock { return s } +// Deprecated. +// // Describes the ClassicLink DNS support status of a VPC. type ClassicLinkDnsSupport struct { _ struct{} `type:"structure"` @@ -64258,15 +66858,13 @@ func (s *ClassicLinkDnsSupport) SetVpcId(v string) *ClassicLinkDnsSupport { return s } -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// Deprecated. // // Describes a linked EC2-Classic instance. type ClassicLinkInstance struct { _ struct{} `type:"structure"` - // A list of security groups. + // The security groups. Groups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` // The ID of the instance. @@ -66109,6 +68707,242 @@ func (s *ConnectionNotification) SetVpcEndpointId(v string) *ConnectionNotificat return s } +// A security group connection tracking configuration that enables you to set +// the idle timeout for connection tracking on an Elastic network interface. +// For more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) +// in the Amazon Elastic Compute Cloud User Guide. +type ConnectionTrackingConfiguration struct { + _ struct{} `type:"structure"` + + // Timeout (in seconds) for idle TCP connections in an established state. Min: + // 60 seconds. Max: 432000 seconds (5 days). Default: 432000 seconds. Recommended: + // Less than 432000 seconds. + TcpEstablishedTimeout *int64 `locationName:"tcpEstablishedTimeout" type:"integer"` + + // Timeout (in seconds) for idle UDP flows classified as streams which have + // seen more than one request-response transaction. Min: 60 seconds. Max: 180 + // seconds (3 minutes). Default: 180 seconds. + UdpStreamTimeout *int64 `locationName:"udpStreamTimeout" type:"integer"` + + // Timeout (in seconds) for idle UDP flows that have seen traffic only in a + // single direction or a single request-response transaction. Min: 30 seconds. + // Max: 60 seconds. Default: 30 seconds. + UdpTimeout *int64 `locationName:"udpTimeout" type:"integer"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingConfiguration) GoString() string { + return s.String() +} + +// SetTcpEstablishedTimeout sets the TcpEstablishedTimeout field's value. +func (s *ConnectionTrackingConfiguration) SetTcpEstablishedTimeout(v int64) *ConnectionTrackingConfiguration { + s.TcpEstablishedTimeout = &v + return s +} + +// SetUdpStreamTimeout sets the UdpStreamTimeout field's value. +func (s *ConnectionTrackingConfiguration) SetUdpStreamTimeout(v int64) *ConnectionTrackingConfiguration { + s.UdpStreamTimeout = &v + return s +} + +// SetUdpTimeout sets the UdpTimeout field's value. +func (s *ConnectionTrackingConfiguration) SetUdpTimeout(v int64) *ConnectionTrackingConfiguration { + s.UdpTimeout = &v + return s +} + +// A security group connection tracking specification that enables you to set +// the idle timeout for connection tracking on an Elastic network interface. +// For more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) +// in the Amazon Elastic Compute Cloud User Guide. +type ConnectionTrackingSpecification struct { + _ struct{} `type:"structure"` + + // Timeout (in seconds) for idle TCP connections in an established state. Min: + // 60 seconds. Max: 432000 seconds (5 days). Default: 432000 seconds. Recommended: + // Less than 432000 seconds. + TcpEstablishedTimeout *int64 `locationName:"tcpEstablishedTimeout" type:"integer"` + + // Timeout (in seconds) for idle UDP flows classified as streams which have + // seen more than one request-response transaction. Min: 60 seconds. Max: 180 + // seconds (3 minutes). Default: 180 seconds. + UdpStreamTimeout *int64 `locationName:"udpStreamTimeout" type:"integer"` + + // Timeout (in seconds) for idle UDP flows that have seen traffic only in a + // single direction or a single request-response transaction. Min: 30 seconds. + // Max: 60 seconds. Default: 30 seconds. + UdpTimeout *int64 `locationName:"udpTimeout" type:"integer"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingSpecification) GoString() string { + return s.String() +} + +// SetTcpEstablishedTimeout sets the TcpEstablishedTimeout field's value. +func (s *ConnectionTrackingSpecification) SetTcpEstablishedTimeout(v int64) *ConnectionTrackingSpecification { + s.TcpEstablishedTimeout = &v + return s +} + +// SetUdpStreamTimeout sets the UdpStreamTimeout field's value. +func (s *ConnectionTrackingSpecification) SetUdpStreamTimeout(v int64) *ConnectionTrackingSpecification { + s.UdpStreamTimeout = &v + return s +} + +// SetUdpTimeout sets the UdpTimeout field's value. +func (s *ConnectionTrackingSpecification) SetUdpTimeout(v int64) *ConnectionTrackingSpecification { + s.UdpTimeout = &v + return s +} + +// A security group connection tracking specification request that enables you +// to set the idle timeout for connection tracking on an Elastic network interface. +// For more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) +// in the Amazon Elastic Compute Cloud User Guide. +type ConnectionTrackingSpecificationRequest struct { + _ struct{} `type:"structure"` + + // Timeout (in seconds) for idle TCP connections in an established state. Min: + // 60 seconds. Max: 432000 seconds (5 days). Default: 432000 seconds. Recommended: + // Less than 432000 seconds. + TcpEstablishedTimeout *int64 `type:"integer"` + + // Timeout (in seconds) for idle UDP flows classified as streams which have + // seen more than one request-response transaction. Min: 60 seconds. Max: 180 + // seconds (3 minutes). Default: 180 seconds. + UdpStreamTimeout *int64 `type:"integer"` + + // Timeout (in seconds) for idle UDP flows that have seen traffic only in a + // single direction or a single request-response transaction. Min: 30 seconds. + // Max: 60 seconds. Default: 30 seconds. + UdpTimeout *int64 `type:"integer"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingSpecificationRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingSpecificationRequest) GoString() string { + return s.String() +} + +// SetTcpEstablishedTimeout sets the TcpEstablishedTimeout field's value. +func (s *ConnectionTrackingSpecificationRequest) SetTcpEstablishedTimeout(v int64) *ConnectionTrackingSpecificationRequest { + s.TcpEstablishedTimeout = &v + return s +} + +// SetUdpStreamTimeout sets the UdpStreamTimeout field's value. +func (s *ConnectionTrackingSpecificationRequest) SetUdpStreamTimeout(v int64) *ConnectionTrackingSpecificationRequest { + s.UdpStreamTimeout = &v + return s +} + +// SetUdpTimeout sets the UdpTimeout field's value. +func (s *ConnectionTrackingSpecificationRequest) SetUdpTimeout(v int64) *ConnectionTrackingSpecificationRequest { + s.UdpTimeout = &v + return s +} + +// A security group connection tracking specification response that enables +// you to set the idle timeout for connection tracking on an Elastic network +// interface. For more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) +// in the Amazon Elastic Compute Cloud User Guide. +type ConnectionTrackingSpecificationResponse struct { + _ struct{} `type:"structure"` + + // Timeout (in seconds) for idle TCP connections in an established state. Min: + // 60 seconds. Max: 432000 seconds (5 days). Default: 432000 seconds. Recommended: + // Less than 432000 seconds. + TcpEstablishedTimeout *int64 `locationName:"tcpEstablishedTimeout" type:"integer"` + + // Timeout (in seconds) for idle UDP flows classified as streams which have + // seen more than one request-response transaction. Min: 60 seconds. Max: 180 + // seconds (3 minutes). Default: 180 seconds. + UdpStreamTimeout *int64 `locationName:"udpStreamTimeout" type:"integer"` + + // Timeout (in seconds) for idle UDP flows that have seen traffic only in a + // single direction or a single request-response transaction. Min: 30 seconds. + // Max: 60 seconds. Default: 30 seconds. + UdpTimeout *int64 `locationName:"udpTimeout" type:"integer"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingSpecificationResponse) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ConnectionTrackingSpecificationResponse) GoString() string { + return s.String() +} + +// SetTcpEstablishedTimeout sets the TcpEstablishedTimeout field's value. +func (s *ConnectionTrackingSpecificationResponse) SetTcpEstablishedTimeout(v int64) *ConnectionTrackingSpecificationResponse { + s.TcpEstablishedTimeout = &v + return s +} + +// SetUdpStreamTimeout sets the UdpStreamTimeout field's value. +func (s *ConnectionTrackingSpecificationResponse) SetUdpStreamTimeout(v int64) *ConnectionTrackingSpecificationResponse { + s.UdpStreamTimeout = &v + return s +} + +// SetUdpTimeout sets the UdpTimeout field's value. +func (s *ConnectionTrackingSpecificationResponse) SetUdpTimeout(v int64) *ConnectionTrackingSpecificationResponse { + s.UdpTimeout = &v + return s +} + // Describes a conversion task. type ConversionTask struct { _ struct{} `type:"structure"` @@ -66781,6 +69615,10 @@ func (s *CopySnapshotOutput) SetTags(v []*Tag) *CopySnapshotOutput { type CpuOptions struct { _ struct{} `type:"structure"` + // Indicates whether the instance is enabled for AMD SEV-SNP. For more information, + // see AMD SEV-SNP (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html). + AmdSevSnp *string `locationName:"amdSevSnp" type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `locationName:"coreCount" type:"integer"` @@ -66806,6 +69644,12 @@ func (s CpuOptions) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *CpuOptions) SetAmdSevSnp(v string) *CpuOptions { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *CpuOptions) SetCoreCount(v int64) *CpuOptions { s.CoreCount = &v @@ -66823,6 +69667,11 @@ func (s *CpuOptions) SetThreadsPerCore(v int64) *CpuOptions { type CpuOptionsRequest struct { _ struct{} `type:"structure"` + // Indicates whether to enable the instance for AMD SEV-SNP. AMD SEV-SNP is + // supported with M6a, R6a, and C6a instance types only. For more information, + // see AMD SEV-SNP (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html). + AmdSevSnp *string `type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `type:"integer"` @@ -66849,6 +69698,12 @@ func (s CpuOptionsRequest) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *CpuOptionsRequest) SetAmdSevSnp(v string) *CpuOptionsRequest { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *CpuOptionsRequest) SetCoreCount(v int64) *CpuOptionsRequest { s.CoreCount = &v @@ -68834,7 +71689,7 @@ type CreateFleetInput struct { SpotOptions *SpotOptionsRequest `type:"structure"` // The key-value pair for tagging the EC2 Fleet request on creation. For more - // information, see Tagging your resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources). + // information, see Tag your resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources). // // If the fleet type is instant, specify a resource type of fleet to tag the // fleet or instance to tag the instances at launch. @@ -69192,9 +72047,7 @@ type CreateFlowLogsInput struct { // in the Amazon VPC User Guide or Transit Gateway Flow Log records (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-flow-logs.html#flow-log-records) // in the Amazon Web Services Transit Gateway Guide. // - // Specify the fields using the ${field-id} format, separated by spaces. For - // the CLI, surround this parameter value with single quotes on Linux or double - // quotes on Windows. + // Specify the fields using the ${field-id} format, separated by spaces. LogFormat *string `type:"string"` // The name of a new or existing CloudWatch Logs log group where Amazon EC2 @@ -69554,9 +72407,22 @@ func (s *CreateFpgaImageOutput) SetFpgaImageId(v string) *CreateFpgaImageOutput type CreateImageInput struct { _ struct{} `type:"structure"` - // The block device mappings. This parameter cannot be used to modify the encryption - // status of existing volumes or snapshots. To create an AMI with encrypted - // snapshots, use the CopyImage action. + // The block device mappings. + // + // When using the CreateImage action: + // + // * You can't change the volume size using the VolumeSize parameter. If + // you want a different volume size, you must first change the volume size + // of the source instance. + // + // * You can't modify the encryption status of existing volumes or snapshots. + // To create an AMI with volumes or snapshots that have a different encryption + // status (for example, where the source volume and snapshots are unencrypted, + // and you want to create an AMI with encrypted volumes or snapshots), use + // the CopyImage action. + // + // * The only option that can be changed for existing mappings or snapshots + // is DeleteOnTermination. BlockDeviceMappings []*BlockDeviceMapping `locationName:"blockDeviceMapping" locationNameList:"BlockDeviceMapping" type:"list"` // A description for the new image. @@ -69582,17 +72448,20 @@ type CreateImageInput struct { // Name is a required field Name *string `locationName:"name" type:"string" required:"true"` - // By default, when Amazon EC2 creates the new AMI, it reboots the instance - // so that it can take snapshots of the attached volumes while data is at rest, - // in order to ensure a consistent state. You can set the NoReboot parameter - // to true in the API request, or use the --no-reboot option in the CLI to prevent - // Amazon EC2 from shutting down and rebooting the instance. + // Indicates whether or not the instance should be automatically rebooted before + // creating the image. Specify one of the following values: // - // If you choose to bypass the shutdown and reboot process by setting the NoReboot - // parameter to true in the API request, or by using the --no-reboot option - // in the CLI, we can't guarantee the file system integrity of the created image. + // * true - The instance is not rebooted before creating the image. This + // creates crash-consistent snapshots that include only the data that has + // been written to the volumes at the time the snapshots are created. Buffered + // data and data in memory that has not yet been written to the volumes is + // not included in the snapshots. // - // Default: false (follow standard reboot process) + // * false - The instance is rebooted before creating the image. This ensures + // that all buffered data and data in memory is written to the volumes before + // the snapshots are created. + // + // Default: false NoReboot *bool `locationName:"noReboot" type:"boolean"` // The tags to apply to the AMI and snapshots on creation. You can tag the AMI, @@ -69718,6 +72587,152 @@ func (s *CreateImageOutput) SetImageId(v string) *CreateImageOutput { return s } +type CreateInstanceConnectEndpointInput struct { + _ struct{} `type:"structure"` + + // Unique, case-sensitive identifier that you provide to ensure the idempotency + // of the request. + ClientToken *string `type:"string" idempotencyToken:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // Indicates whether your client's IP address is preserved as the source. The + // value is true or false. + // + // * If true, your client's IP address is used when you connect to a resource. + // + // * If false, the elastic network interface IP address is used when you + // connect to a resource. + // + // Default: true + PreserveClientIp *bool `type:"boolean"` + + // One or more security groups to associate with the endpoint. If you don't + // specify a security group, the default security group for your VPC will be + // associated with the endpoint. + SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"SecurityGroupId" type:"list"` + + // The ID of the subnet in which to create the EC2 Instance Connect Endpoint. + // + // SubnetId is a required field + SubnetId *string `type:"string" required:"true"` + + // The tags to apply to the EC2 Instance Connect Endpoint during creation. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateInstanceConnectEndpointInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateInstanceConnectEndpointInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateInstanceConnectEndpointInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateInstanceConnectEndpointInput"} + if s.SubnetId == nil { + invalidParams.Add(request.NewErrParamRequired("SubnetId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateInstanceConnectEndpointInput) SetClientToken(v string) *CreateInstanceConnectEndpointInput { + s.ClientToken = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *CreateInstanceConnectEndpointInput) SetDryRun(v bool) *CreateInstanceConnectEndpointInput { + s.DryRun = &v + return s +} + +// SetPreserveClientIp sets the PreserveClientIp field's value. +func (s *CreateInstanceConnectEndpointInput) SetPreserveClientIp(v bool) *CreateInstanceConnectEndpointInput { + s.PreserveClientIp = &v + return s +} + +// SetSecurityGroupIds sets the SecurityGroupIds field's value. +func (s *CreateInstanceConnectEndpointInput) SetSecurityGroupIds(v []*string) *CreateInstanceConnectEndpointInput { + s.SecurityGroupIds = v + return s +} + +// SetSubnetId sets the SubnetId field's value. +func (s *CreateInstanceConnectEndpointInput) SetSubnetId(v string) *CreateInstanceConnectEndpointInput { + s.SubnetId = &v + return s +} + +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateInstanceConnectEndpointInput) SetTagSpecifications(v []*TagSpecification) *CreateInstanceConnectEndpointInput { + s.TagSpecifications = v + return s +} + +type CreateInstanceConnectEndpointOutput struct { + _ struct{} `type:"structure"` + + // Unique, case-sensitive idempotency token provided by the client in the the + // request. + ClientToken *string `locationName:"clientToken" type:"string"` + + // Information about the EC2 Instance Connect Endpoint. + InstanceConnectEndpoint *Ec2InstanceConnectEndpoint `locationName:"instanceConnectEndpoint" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateInstanceConnectEndpointOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateInstanceConnectEndpointOutput) GoString() string { + return s.String() +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateInstanceConnectEndpointOutput) SetClientToken(v string) *CreateInstanceConnectEndpointOutput { + s.ClientToken = &v + return s +} + +// SetInstanceConnectEndpoint sets the InstanceConnectEndpoint field's value. +func (s *CreateInstanceConnectEndpointOutput) SetInstanceConnectEndpoint(v *Ec2InstanceConnectEndpoint) *CreateInstanceConnectEndpointOutput { + s.InstanceConnectEndpoint = v + return s +} + type CreateInstanceEventWindowInput struct { _ struct{} `type:"structure"` @@ -70069,6 +73084,11 @@ type CreateIpamInput struct { // to find all resources that have a tag with the key Owner and the value TeamA, // specify tag:Owner for the filter name and TeamA for the filter value. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + + // IPAM is offered in a Free Tier and an Advanced Tier. For more information + // about the features available in each tier and the costs associated with the + // tiers, see Amazon VPC pricing > IPAM tab (http://aws.amazon.com/vpc/pricing/). + Tier *string `type:"string" enum:"IpamTier"` } // String returns the string representation. @@ -70119,6 +73139,12 @@ func (s *CreateIpamInput) SetTagSpecifications(v []*TagSpecification) *CreateIpa return s } +// SetTier sets the Tier field's value. +func (s *CreateIpamInput) SetTier(v string) *CreateIpamInput { + s.Tier = &v + return s +} + type CreateIpamOutput struct { _ struct{} `type:"structure"` @@ -70248,6 +73274,9 @@ type CreateIpamPoolInput struct { // pool must be available in the source pool's CIDR range. SourceIpamPoolId *string `type:"string"` + // The resource used to provision CIDRs to a resource planning pool. + SourceResource *IpamPoolSourceResourceRequest `type:"structure"` + // The key/value combination of a tag assigned to the resource. Use the tag // key in the filter name and the tag value as the filter value. For example, // to find all resources that have a tag with the key Owner and the value TeamA, @@ -70379,6 +73408,12 @@ func (s *CreateIpamPoolInput) SetSourceIpamPoolId(v string) *CreateIpamPoolInput return s } +// SetSourceResource sets the SourceResource field's value. +func (s *CreateIpamPoolInput) SetSourceResource(v *IpamPoolSourceResourceRequest) *CreateIpamPoolInput { + s.SourceResource = v + return s +} + // SetTagSpecifications sets the TagSpecifications field's value. func (s *CreateIpamPoolInput) SetTagSpecifications(v []*TagSpecification) *CreateIpamPoolInput { s.TagSpecifications = v @@ -70825,12 +73860,8 @@ type CreateLaunchTemplateInput struct { // The information for the launch template. // - // LaunchTemplateData is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateLaunchTemplateInput's - // String and GoString methods. - // // LaunchTemplateData is a required field - LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true" sensitive:"true"` + LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true"` // A name for the launch template. // @@ -70987,12 +74018,8 @@ type CreateLaunchTemplateVersionInput struct { // The information for the launch template. // - // LaunchTemplateData is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateLaunchTemplateVersionInput's - // String and GoString methods. - // // LaunchTemplateData is a required field - LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true" sensitive:"true"` + LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true"` // The ID of the launch template. // @@ -71804,20 +74831,20 @@ type CreateNatGatewayInput struct { // an address, a private IPv4 address will be automatically assigned. PrivateIpAddress *string `type:"string"` - // Secondary EIP allocation IDs. For more information about secondary addresses, - // see Create a NAT gateway (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-creating) - // in the Amazon Virtual Private Cloud User Guide. + // Secondary EIP allocation IDs. For more information, see Create a NAT gateway + // (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-creating) + // in the Amazon VPC User Guide. SecondaryAllocationIds []*string `locationName:"SecondaryAllocationId" locationNameList:"AllocationId" type:"list"` // [Private NAT gateway only] The number of secondary private IPv4 addresses // you want to assign to the NAT gateway. For more information about secondary // addresses, see Create a NAT gateway (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-creating) - // in the Amazon Virtual Private Cloud User Guide. + // in the Amazon VPC User Guide. SecondaryPrivateIpAddressCount *int64 `min:"1" type:"integer"` // Secondary private IPv4 addresses. For more information about secondary addresses, // see Create a NAT gateway (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html#nat-gateway-creating) - // in the Amazon Virtual Private Cloud User Guide. + // in the Amazon VPC User Guide. SecondaryPrivateIpAddresses []*string `locationName:"SecondaryPrivateIpAddress" locationNameList:"item" type:"list"` // The ID of the subnet in which to create the NAT gateway. @@ -72549,6 +75576,9 @@ type CreateNetworkInterfaceInput struct { // of the request. For more information, see Ensuring Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` + // A connection tracking specification for the network interface. + ConnectionTrackingSpecification *ConnectionTrackingSpecificationRequest `type:"structure"` + // A description for the network interface. Description *string `locationName:"description" type:"string"` @@ -72558,12 +75588,27 @@ type CreateNetworkInterfaceInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + // If you’re creating a network interface in a dual-stack or IPv6-only subnet, + // you have the option to assign a primary IPv6 IP address. A primary IPv6 address + // is an IPv6 GUA address associated with an ENI that you have enabled to use + // a primary IPv6 address. Use this option if the instance that this ENI will + // be attached to relies on its IPv6 address not changing. Amazon Web Services + // will automatically assign an IPv6 address associated with the ENI attached + // to your instance to be the primary IPv6 address. Once you enable an IPv6 + // GUA address to be a primary IPv6, you cannot disable it. When you enable + // an IPv6 GUA address to be a primary IPv6, the first IPv6 GUA will be made + // the primary IPv6 address until the instance is terminated or the network + // interface is detached. If you have multiple IPv6 addresses associated with + // an ENI attached to your instance and you enable a primary IPv6 address, the + // first IPv6 GUA address associated with the ENI becomes the primary IPv6 address. + EnablePrimaryIpv6 *bool `type:"boolean"` + // The IDs of one or more security groups. Groups []*string `locationName:"SecurityGroupId" locationNameList:"SecurityGroupId" type:"list"` // The type of network interface. The default is interface. // - // The only supported values are efa and trunk. + // The only supported values are interface, efa, and trunk. InterfaceType *string `type:"string" enum:"NetworkInterfaceCreationType"` // The number of IPv4 prefixes that Amazon Web Services automatically assigns @@ -72683,6 +75728,12 @@ func (s *CreateNetworkInterfaceInput) SetClientToken(v string) *CreateNetworkInt return s } +// SetConnectionTrackingSpecification sets the ConnectionTrackingSpecification field's value. +func (s *CreateNetworkInterfaceInput) SetConnectionTrackingSpecification(v *ConnectionTrackingSpecificationRequest) *CreateNetworkInterfaceInput { + s.ConnectionTrackingSpecification = v + return s +} + // SetDescription sets the Description field's value. func (s *CreateNetworkInterfaceInput) SetDescription(v string) *CreateNetworkInterfaceInput { s.Description = &v @@ -72695,6 +75746,12 @@ func (s *CreateNetworkInterfaceInput) SetDryRun(v bool) *CreateNetworkInterfaceI return s } +// SetEnablePrimaryIpv6 sets the EnablePrimaryIpv6 field's value. +func (s *CreateNetworkInterfaceInput) SetEnablePrimaryIpv6(v bool) *CreateNetworkInterfaceInput { + s.EnablePrimaryIpv6 = &v + return s +} + // SetGroups sets the Groups field's value. func (s *CreateNetworkInterfaceInput) SetGroups(v []*string) *CreateNetworkInterfaceInput { s.Groups = v @@ -73867,9 +76924,7 @@ type CreateSecurityGroupInput struct { // // Constraints: Up to 255 characters in length // - // Constraints for EC2-Classic: ASCII characters - // - // Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + // Valid characters: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* // // Description is a required field Description *string `locationName:"GroupDescription" type:"string" required:"true"` @@ -73884,9 +76939,7 @@ type CreateSecurityGroupInput struct { // // Constraints: Up to 255 characters in length. Cannot start with sg-. // - // Constraints for EC2-Classic: ASCII characters - // - // Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + // Valid characters: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* // // GroupName is a required field GroupName *string `type:"string" required:"true"` @@ -73894,7 +76947,7 @@ type CreateSecurityGroupInput struct { // The tags to assign to the security group. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` - // [EC2-VPC] The ID of the VPC. Required for EC2-VPC. + // The ID of the VPC. Required for a nondefault VPC. VpcId *string `type:"string"` } @@ -74484,18 +77537,13 @@ type CreateSubnetCidrReservationInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The type of reservation. - // - // The following are valid values: + // The type of reservation. The reservation type determines how the reserved + // IP addresses are assigned to resources. // - // * prefix: The Amazon EC2 Prefix Delegation feature assigns the IP addresses - // to network interfaces that are associated with an instance. For information - // about Prefix Delegation, see Prefix Delegation for Amazon EC2 network - // interfaces (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-prefix-delegation.html) - // in the Amazon Elastic Compute Cloud User Guide. + // * prefix - Amazon Web Services assigns the reserved IP addresses to network + // interfaces. // - // * explicit: You manually assign the IP addresses to resources that reside - // in your subnet. + // * explicit - You assign the reserved IP addresses to network interfaces. // // ReservationType is a required field ReservationType *string `type:"string" required:"true" enum:"SubnetCidrReservationType"` @@ -74624,8 +77672,7 @@ type CreateSubnetInput struct { // // To create a subnet in a Local Zone, set this value to the Local Zone ID, // for example us-west-2-lax-1a. For information about the Regions that support - // Local Zones, see Available Regions (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) - // in the Amazon Elastic Compute Cloud User Guide. + // Local Zones, see Local Zones locations (http://aws.amazon.com/about-aws/global-infrastructure/localzones/locations/). // // To create a subnet in an Outpost, set this value to the Availability Zone // for the Outpost and specify the Outpost ARN. @@ -74647,15 +77694,25 @@ type CreateSubnetInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The IPv6 network range for the subnet, in CIDR notation. The subnet size - // must use a /64 prefix length. - // - // This parameter is required for an IPv6 only subnet. + // An IPv4 IPAM pool ID for the subnet. + Ipv4IpamPoolId *string `type:"string"` + + // An IPv4 netmask length for the subnet. + Ipv4NetmaskLength *int64 `type:"integer"` + + // The IPv6 network range for the subnet, in CIDR notation. This parameter is + // required for an IPv6 only subnet. Ipv6CidrBlock *string `type:"string"` + // An IPv6 IPAM pool ID for the subnet. + Ipv6IpamPoolId *string `type:"string"` + // Indicates whether to create an IPv6 only subnet. Ipv6Native *bool `type:"boolean"` + // An IPv6 netmask length for the subnet. + Ipv6NetmaskLength *int64 `type:"integer"` + // The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost // ARN, you must also specify the Availability Zone of the Outpost subnet. OutpostArn *string `type:"string"` @@ -74724,18 +77781,42 @@ func (s *CreateSubnetInput) SetDryRun(v bool) *CreateSubnetInput { return s } +// SetIpv4IpamPoolId sets the Ipv4IpamPoolId field's value. +func (s *CreateSubnetInput) SetIpv4IpamPoolId(v string) *CreateSubnetInput { + s.Ipv4IpamPoolId = &v + return s +} + +// SetIpv4NetmaskLength sets the Ipv4NetmaskLength field's value. +func (s *CreateSubnetInput) SetIpv4NetmaskLength(v int64) *CreateSubnetInput { + s.Ipv4NetmaskLength = &v + return s +} + // SetIpv6CidrBlock sets the Ipv6CidrBlock field's value. func (s *CreateSubnetInput) SetIpv6CidrBlock(v string) *CreateSubnetInput { s.Ipv6CidrBlock = &v return s } +// SetIpv6IpamPoolId sets the Ipv6IpamPoolId field's value. +func (s *CreateSubnetInput) SetIpv6IpamPoolId(v string) *CreateSubnetInput { + s.Ipv6IpamPoolId = &v + return s +} + // SetIpv6Native sets the Ipv6Native field's value. func (s *CreateSubnetInput) SetIpv6Native(v bool) *CreateSubnetInput { s.Ipv6Native = &v return s } +// SetIpv6NetmaskLength sets the Ipv6NetmaskLength field's value. +func (s *CreateSubnetInput) SetIpv6NetmaskLength(v int64) *CreateSubnetInput { + s.Ipv6NetmaskLength = &v + return s +} + // SetOutpostArn sets the OutpostArn field's value. func (s *CreateSubnetInput) SetOutpostArn(v string) *CreateSubnetInput { s.OutpostArn = &v @@ -75236,6 +78317,10 @@ type CreateTrafficMirrorSessionInput struct { // // If you do not want to mirror the entire packet, use the PacketLength parameter // to specify the number of bytes in each packet to mirror. + // + // For sessions with Network Load Balancer (NLB) Traffic Mirror targets the + // default PacketLength will be set to 8500. Valid values are 1-8500. Setting + // a PacketLength greater than 8500 will result in an error response. PacketLength *int64 `type:"integer"` // The session number determines the order in which sessions are evaluated when @@ -76994,6 +80079,24 @@ type CreateTransitGatewayVpcAttachmentRequestOptions struct { // Enable or disable IPv6 support. The default is disable. Ipv6Support *string `type:"string" enum:"Ipv6SupportValue"` + + // Enables you to reference a security group across VPCs attached to a transit + // gateway (TGW). Use this option to simplify security group management and + // control of instance-to-instance traffic across VPCs that are connected by + // transit gateway. You can also use this option to migrate from VPC peering + // (which was the only option that supported security group referencing) to + // transit gateways (which now also support security group referencing). This + // option is disabled by default and there are no additional costs to use this + // feature. + // + // If you don't enable or disable SecurityGroupReferencingSupport in the request, + // the attachment will inherit the security group referencing support setting + // on the transit gateway. + // + // For important information about this feature, see Create a transit gateway + // attachment to a VPC (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#create-vpc-attachment) + // in the Amazon Web Services Transit Gateway Guide. + SecurityGroupReferencingSupport *string `type:"string" enum:"SecurityGroupReferencingSupportValue"` } // String returns the string representation. @@ -77032,7 +80135,14 @@ func (s *CreateTransitGatewayVpcAttachmentRequestOptions) SetIpv6Support(v strin return s } -// Options for a network interface-type endpoint. +// SetSecurityGroupReferencingSupport sets the SecurityGroupReferencingSupport field's value. +func (s *CreateTransitGatewayVpcAttachmentRequestOptions) SetSecurityGroupReferencingSupport(v string) *CreateTransitGatewayVpcAttachmentRequestOptions { + s.SecurityGroupReferencingSupport = &v + return s +} + +// Describes the network interface options when creating an Amazon Web Services +// Verified Access endpoint using the network-interface type. type CreateVerifiedAccessEndpointEniOptions struct { _ struct{} `type:"structure"` @@ -77103,7 +80213,7 @@ type CreateVerifiedAccessEndpointInput struct { // ApplicationDomain is a required field ApplicationDomain *string `type:"string" required:"true"` - // The Amazon Web Services network component Verified Access attaches to. + // The type of attachment. // // AttachmentType is a required field AttachmentType *string `type:"string" required:"true" enum:"VerifiedAccessEndpointAttachmentType"` @@ -77113,7 +80223,7 @@ type CreateVerifiedAccessEndpointInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access endpoint. + // A description for the Verified Access endpoint. Description *string `type:"string"` // The ARN of the public TLS/SSL certificate in Amazon Web Services Certificate @@ -77129,33 +80239,36 @@ type CreateVerifiedAccessEndpointInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // A custom identifier that gets prepended to a DNS name that is generated for + // A custom identifier that is prepended to the DNS name that is generated for // the endpoint. // // EndpointDomainPrefix is a required field EndpointDomainPrefix *string `type:"string" required:"true"` - // The type of Amazon Web Services Verified Access endpoint to create. + // The type of Verified Access endpoint to create. // // EndpointType is a required field EndpointType *string `type:"string" required:"true" enum:"VerifiedAccessEndpointType"` - // The load balancer details if creating the Amazon Web Services Verified Access - // endpoint as load-balancertype. + // The load balancer details. This parameter is required if the endpoint type + // is load-balancer. LoadBalancerOptions *CreateVerifiedAccessEndpointLoadBalancerOptions `type:"structure"` - // The network interface details if creating the Amazon Web Services Verified - // Access endpoint as network-interfacetype. + // The network interface details. This parameter is required if the endpoint + // type is network-interface. NetworkInterfaceOptions *CreateVerifiedAccessEndpointEniOptions `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` - // The Amazon EC2 security groups to associate with the Amazon Web Services - // Verified Access endpoint. + // The IDs of the security groups to associate with the Verified Access endpoint. + // Required if AttachmentType is set to vpc. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"item" type:"list"` - // The tags to assign to the Amazon Web Services Verified Access endpoint. + // The options for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationRequest `type:"structure"` + + // The tags to assign to the Verified Access endpoint. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` // The ID of the Verified Access group to associate the endpoint with. @@ -77292,6 +80405,12 @@ func (s *CreateVerifiedAccessEndpointInput) SetSecurityGroupIds(v []*string) *Cr return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *CreateVerifiedAccessEndpointInput) SetSseSpecification(v *VerifiedAccessSseSpecificationRequest) *CreateVerifiedAccessEndpointInput { + s.SseSpecification = v + return s +} + // SetTagSpecifications sets the TagSpecifications field's value. func (s *CreateVerifiedAccessEndpointInput) SetTagSpecifications(v []*TagSpecification) *CreateVerifiedAccessEndpointInput { s.TagSpecifications = v @@ -77304,8 +80423,8 @@ func (s *CreateVerifiedAccessEndpointInput) SetVerifiedAccessGroupId(v string) * return s } -// Describes a load balancer when creating an Amazon Web Services Verified Access -// endpoint using the load-balancer type. +// Describes the load balancer options when creating an Amazon Web Services +// Verified Access endpoint using the load-balancer type. type CreateVerifiedAccessEndpointLoadBalancerOptions struct { _ struct{} `type:"structure"` @@ -77380,7 +80499,7 @@ func (s *CreateVerifiedAccessEndpointLoadBalancerOptions) SetSubnetIds(v []*stri type CreateVerifiedAccessEndpointOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access endpoint. + // Details about the Verified Access endpoint. VerifiedAccessEndpoint *VerifiedAccessEndpoint `locationName:"verifiedAccessEndpoint" type:"structure"` } @@ -77416,7 +80535,7 @@ type CreateVerifiedAccessGroupInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access group. + // A description for the Verified Access group. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -77425,13 +80544,16 @@ type CreateVerifiedAccessGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` - // The tags to assign to the Amazon Web Services Verified Access group. + // The options for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationRequest `type:"structure"` + + // The tags to assign to the Verified Access group. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -77492,6 +80614,12 @@ func (s *CreateVerifiedAccessGroupInput) SetPolicyDocument(v string) *CreateVeri return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *CreateVerifiedAccessGroupInput) SetSseSpecification(v *VerifiedAccessSseSpecificationRequest) *CreateVerifiedAccessGroupInput { + s.SseSpecification = v + return s +} + // SetTagSpecifications sets the TagSpecifications field's value. func (s *CreateVerifiedAccessGroupInput) SetTagSpecifications(v []*TagSpecification) *CreateVerifiedAccessGroupInput { s.TagSpecifications = v @@ -77507,7 +80635,7 @@ func (s *CreateVerifiedAccessGroupInput) SetVerifiedAccessInstanceId(v string) * type CreateVerifiedAccessGroupOutput struct { _ struct{} `type:"structure"` - // The ID of the Verified Access group. + // Details about the Verified Access group. VerifiedAccessGroup *VerifiedAccessGroup `locationName:"verifiedAccessGroup" type:"structure"` } @@ -77543,7 +80671,7 @@ type CreateVerifiedAccessInstanceInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access instance. + // A description for the Verified Access instance. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -77552,7 +80680,11 @@ type CreateVerifiedAccessInstanceInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The tags to assign to the Amazon Web Services Verified Access instance. + // Enable or disable support for Federal Information Processing Standards (FIPS) + // on the instance. + FIPSEnabled *bool `type:"boolean"` + + // The tags to assign to the Verified Access instance. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } @@ -77592,6 +80724,12 @@ func (s *CreateVerifiedAccessInstanceInput) SetDryRun(v bool) *CreateVerifiedAcc return s } +// SetFIPSEnabled sets the FIPSEnabled field's value. +func (s *CreateVerifiedAccessInstanceInput) SetFIPSEnabled(v bool) *CreateVerifiedAccessInstanceInput { + s.FIPSEnabled = &v + return s +} + // SetTagSpecifications sets the TagSpecifications field's value. func (s *CreateVerifiedAccessInstanceInput) SetTagSpecifications(v []*TagSpecification) *CreateVerifiedAccessInstanceInput { s.TagSpecifications = v @@ -77601,7 +80739,7 @@ func (s *CreateVerifiedAccessInstanceInput) SetTagSpecifications(v []*TagSpecifi type CreateVerifiedAccessInstanceOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // Details about the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` } @@ -77629,10 +80767,15 @@ func (s *CreateVerifiedAccessInstanceOutput) SetVerifiedAccessInstance(v *Verifi return s } -// Options for a device-identity type trust provider. +// Describes the options when creating an Amazon Web Services Verified Access +// trust provider using the device type. type CreateVerifiedAccessTrustProviderDeviceOptions struct { _ struct{} `type:"structure"` + // The URL Amazon Web Services Verified Access will use to verify the authenticity + // of the device tokens. + PublicSigningKeyUrl *string `type:"string"` + // The ID of the tenant application with the device-identity provider. TenantId *string `type:"string"` } @@ -77655,6 +80798,12 @@ func (s CreateVerifiedAccessTrustProviderDeviceOptions) GoString() string { return s.String() } +// SetPublicSigningKeyUrl sets the PublicSigningKeyUrl field's value. +func (s *CreateVerifiedAccessTrustProviderDeviceOptions) SetPublicSigningKeyUrl(v string) *CreateVerifiedAccessTrustProviderDeviceOptions { + s.PublicSigningKeyUrl = &v + return s +} + // SetTenantId sets the TenantId field's value. func (s *CreateVerifiedAccessTrustProviderDeviceOptions) SetTenantId(v string) *CreateVerifiedAccessTrustProviderDeviceOptions { s.TenantId = &v @@ -77669,13 +80818,15 @@ type CreateVerifiedAccessTrustProviderInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access trust provider. + // A description for the Verified Access trust provider. Description *string `type:"string"` - // The options for device identity based trust providers. + // The options for a device-based trust provider. This parameter is required + // when the provider type is device. DeviceOptions *CreateVerifiedAccessTrustProviderDeviceOptions `type:"structure"` - // The type of device-based trust provider. + // The type of device-based trust provider. This parameter is required when + // the provider type is device. DeviceTrustProviderType *string `type:"string" enum:"DeviceTrustProviderType"` // Checks whether you have the required permissions for the action, without @@ -77684,7 +80835,8 @@ type CreateVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The OpenID Connect details for an oidc-type, user-identity based trust provider. + // The options for a OpenID Connect-compatible user-identity trust provider. + // This parameter is required when the provider type is user. OidcOptions *CreateVerifiedAccessTrustProviderOidcOptions `type:"structure"` // The identifier to be used when working with policy rules. @@ -77692,15 +80844,19 @@ type CreateVerifiedAccessTrustProviderInput struct { // PolicyReferenceName is a required field PolicyReferenceName *string `type:"string" required:"true"` - // The tags to assign to the Amazon Web Services Verified Access trust provider. + // The options for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationRequest `type:"structure"` + + // The tags to assign to the Verified Access trust provider. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` - // The type of trust provider can be either user or device-based. + // The type of trust provider. // // TrustProviderType is a required field TrustProviderType *string `type:"string" required:"true" enum:"TrustProviderType"` - // The type of user-based trust provider. + // The type of user-based trust provider. This parameter is required when the + // provider type is user. UserTrustProviderType *string `type:"string" enum:"UserTrustProviderType"` } @@ -77780,6 +80936,12 @@ func (s *CreateVerifiedAccessTrustProviderInput) SetPolicyReferenceName(v string return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *CreateVerifiedAccessTrustProviderInput) SetSseSpecification(v *VerifiedAccessSseSpecificationRequest) *CreateVerifiedAccessTrustProviderInput { + s.SseSpecification = v + return s +} + // SetTagSpecifications sets the TagSpecifications field's value. func (s *CreateVerifiedAccessTrustProviderInput) SetTagSpecifications(v []*TagSpecification) *CreateVerifiedAccessTrustProviderInput { s.TagSpecifications = v @@ -77798,7 +80960,8 @@ func (s *CreateVerifiedAccessTrustProviderInput) SetUserTrustProviderType(v stri return s } -// Options for an OIDC-based, user-identity type trust provider. +// Describes the options when creating an Amazon Web Services Verified Access +// trust provider using the user type. type CreateVerifiedAccessTrustProviderOidcOptions struct { _ struct{} `type:"structure"` @@ -77809,7 +80972,11 @@ type CreateVerifiedAccessTrustProviderOidcOptions struct { ClientId *string `type:"string"` // The client secret. - ClientSecret *string `type:"string"` + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateVerifiedAccessTrustProviderOidcOptions's + // String and GoString methods. + ClientSecret *string `type:"string" sensitive:"true"` // The OIDC issuer. Issuer *string `type:"string"` @@ -77889,7 +81056,7 @@ func (s *CreateVerifiedAccessTrustProviderOidcOptions) SetUserInfoEndpoint(v str type CreateVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // Details about the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -77920,7 +81087,8 @@ func (s *CreateVerifiedAccessTrustProviderOutput) SetVerifiedAccessTrustProvider type CreateVolumeInput struct { _ struct{} `type:"structure"` - // The Availability Zone in which to create the volume. + // The ID of the Availability Zone in which to create the volume. For example, + // us-east-1a. // // AvailabilityZone is a required field AvailabilityZone *string `type:"string" required:"true"` @@ -77952,15 +81120,15 @@ type CreateVolumeInput struct { // // The following are the supported values for each volume type: // - // * gp3: 3,000-16,000 IOPS + // * gp3: 3,000 - 16,000 IOPS // - // * io1: 100-64,000 IOPS + // * io1: 100 - 64,000 IOPS // - // * io2: 100-64,000 IOPS + // * io2: 100 - 256,000 IOPS // - // io1 and io2 volumes support up to 64,000 IOPS only on Instances built on + // For io2 volumes, you can achieve up to 256,000 IOPS on instances built on // the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). - // Other instance families support performance up to 32,000 IOPS. + // On other instances, you can achieve performance up to 32,000 IOPS. // // This parameter is required for io1 and io2 volumes. The default for gp3 volumes // is 3,000 IOPS. This parameter is not supported for gp2, st1, sc1, or standard @@ -78004,13 +81172,15 @@ type CreateVolumeInput struct { // // The following are the supported volumes sizes for each volume type: // - // * gp2 and gp3: 1-16,384 + // * gp2 and gp3: 1 - 16,384 GiB + // + // * io1: 4 - 16,384 GiB // - // * io1 and io2: 4-16,384 + // * io2: 4 - 65,536 GiB // - // * st1 and sc1: 125-16,384 + // * st1 and sc1: 125 - 16,384 GiB // - // * standard: 1-1,024 + // * standard: 1 - 1024 GiB Size *int64 `type:"integer"` // The snapshot from which to create the volume. You must specify either a snapshot @@ -78427,17 +81597,20 @@ type CreateVpcEndpointInput struct { RouteTableIds []*string `locationName:"RouteTableId" locationNameList:"item" type:"list"` // (Interface endpoint) The IDs of the security groups to associate with the - // endpoint network interface. If this parameter is not specified, we use the + // endpoint network interfaces. If this parameter is not specified, we use the // default security group for the VPC. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"item" type:"list"` - // The service name. + // The name of the endpoint service. // // ServiceName is a required field ServiceName *string `type:"string" required:"true"` + // The subnet configurations for the endpoint. + SubnetConfigurations []*SubnetConfiguration `locationName:"SubnetConfiguration" locationNameList:"item" type:"list"` + // (Interface and Gateway Load Balancer endpoints) The IDs of the subnets in - // which to create an endpoint network interface. For a Gateway Load Balancer + // which to create endpoint network interfaces. For a Gateway Load Balancer // endpoint, you can specify only one subnet. SubnetIds []*string `locationName:"SubnetId" locationNameList:"item" type:"list"` @@ -78449,7 +81622,7 @@ type CreateVpcEndpointInput struct { // Default: Gateway VpcEndpointType *string `type:"string" enum:"VpcEndpointType"` - // The ID of the VPC for the endpoint. + // The ID of the VPC. // // VpcId is a required field VpcId *string `type:"string" required:"true"` @@ -78543,6 +81716,12 @@ func (s *CreateVpcEndpointInput) SetServiceName(v string) *CreateVpcEndpointInpu return s } +// SetSubnetConfigurations sets the SubnetConfigurations field's value. +func (s *CreateVpcEndpointInput) SetSubnetConfigurations(v []*SubnetConfiguration) *CreateVpcEndpointInput { + s.SubnetConfigurations = v + return s +} + // SetSubnetIds sets the SubnetIds field's value. func (s *CreateVpcEndpointInput) SetSubnetIds(v []*string) *CreateVpcEndpointInput { s.SubnetIds = v @@ -80942,6 +84121,95 @@ func (s *DeleteFpgaImageOutput) SetReturn(v bool) *DeleteFpgaImageOutput { return s } +type DeleteInstanceConnectEndpointInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the EC2 Instance Connect Endpoint to delete. + // + // InstanceConnectEndpointId is a required field + InstanceConnectEndpointId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeleteInstanceConnectEndpointInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeleteInstanceConnectEndpointInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteInstanceConnectEndpointInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceConnectEndpointInput"} + if s.InstanceConnectEndpointId == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceConnectEndpointId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DeleteInstanceConnectEndpointInput) SetDryRun(v bool) *DeleteInstanceConnectEndpointInput { + s.DryRun = &v + return s +} + +// SetInstanceConnectEndpointId sets the InstanceConnectEndpointId field's value. +func (s *DeleteInstanceConnectEndpointInput) SetInstanceConnectEndpointId(v string) *DeleteInstanceConnectEndpointInput { + s.InstanceConnectEndpointId = &v + return s +} + +type DeleteInstanceConnectEndpointOutput struct { + _ struct{} `type:"structure"` + + // Information about the EC2 Instance Connect Endpoint. + InstanceConnectEndpoint *Ec2InstanceConnectEndpoint `locationName:"instanceConnectEndpoint" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeleteInstanceConnectEndpointOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeleteInstanceConnectEndpointOutput) GoString() string { + return s.String() +} + +// SetInstanceConnectEndpoint sets the InstanceConnectEndpoint field's value. +func (s *DeleteInstanceConnectEndpointOutput) SetInstanceConnectEndpoint(v *Ec2InstanceConnectEndpoint) *DeleteInstanceConnectEndpointOutput { + s.InstanceConnectEndpoint = v + return s +} + type DeleteInstanceEventWindowInput struct { _ struct{} `type:"structure"` @@ -81238,6 +84506,14 @@ func (s *DeleteIpamOutput) SetIpam(v *Ipam) *DeleteIpamOutput { type DeleteIpamPoolInput struct { _ struct{} `type:"structure"` + // Enables you to quickly delete an IPAM pool and all resources within that + // pool, including provisioned CIDRs, allocations, and other pools. + // + // You can only use this option to delete pools in the private scope or pools + // in the public scope with a source resource. A source resource is a resource + // used to provision CIDRs to a resource planning pool. + Cascade *bool `type:"boolean"` + // A check for whether you have the required permissions for the action without // actually making the request and provides an error response. If you have the // required permissions, the error response is DryRunOperation. Otherwise, it @@ -81281,6 +84557,12 @@ func (s *DeleteIpamPoolInput) Validate() error { return nil } +// SetCascade sets the Cascade field's value. +func (s *DeleteIpamPoolInput) SetCascade(v bool) *DeleteIpamPoolInput { + s.Cascade = &v + return s +} + // SetDryRun sets the DryRun field's value. func (s *DeleteIpamPoolInput) SetDryRun(v bool) *DeleteIpamPoolInput { s.DryRun = &v @@ -81556,6 +84838,12 @@ func (s *DeleteKeyPairInput) SetKeyPairId(v string) *DeleteKeyPairInput { type DeleteKeyPairOutput struct { _ struct{} `type:"structure"` + + // The ID of the key pair. + KeyPairId *string `locationName:"keyPairId" type:"string"` + + // Is true if the request succeeds, and an error otherwise. + Return *bool `locationName:"return" type:"boolean"` } // String returns the string representation. @@ -81576,6 +84864,18 @@ func (s DeleteKeyPairOutput) GoString() string { return s.String() } +// SetKeyPairId sets the KeyPairId field's value. +func (s *DeleteKeyPairOutput) SetKeyPairId(v string) *DeleteKeyPairOutput { + s.KeyPairId = &v + return s +} + +// SetReturn sets the Return field's value. +func (s *DeleteKeyPairOutput) SetReturn(v bool) *DeleteKeyPairOutput { + s.Return = &v + return s +} + type DeleteLaunchTemplateInput struct { _ struct{} `type:"structure"` @@ -81699,7 +84999,8 @@ type DeleteLaunchTemplateVersionsInput struct { // not both. LaunchTemplateName *string `min:"3" type:"string"` - // The version numbers of one or more launch template versions to delete. + // The version numbers of one or more launch template versions to delete. You + // can specify up to 200 launch template version numbers. // // Versions is a required field Versions []*string `locationName:"LaunchTemplateVersion" locationNameList:"item" type:"list" required:"true"` @@ -83701,12 +87002,12 @@ type DeleteSecurityGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The ID of the security group. Required for a nondefault VPC. + // The ID of the security group. GroupId *string `type:"string"` - // [EC2-Classic, default VPC] The name of the security group. You can specify - // either the security group name or the security group ID. For security groups - // in a nondefault VPC, you must specify the security group ID. + // [Default VPC] The name of the security group. You can specify either the + // security group name or the security group ID. For security groups in a nondefault + // VPC, you must specify the security group ID. GroupName *string `type:"string"` } @@ -85553,7 +88854,7 @@ type DeleteVerifiedAccessEndpointInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` @@ -85611,7 +88912,7 @@ func (s *DeleteVerifiedAccessEndpointInput) SetVerifiedAccessEndpointId(v string type DeleteVerifiedAccessEndpointOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access endpoint. + // Details about the Verified Access endpoint. VerifiedAccessEndpoint *VerifiedAccessEndpoint `locationName:"verifiedAccessEndpoint" type:"structure"` } @@ -85653,7 +88954,7 @@ type DeleteVerifiedAccessGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` @@ -85711,7 +89012,7 @@ func (s *DeleteVerifiedAccessGroupInput) SetVerifiedAccessGroupId(v string) *Del type DeleteVerifiedAccessGroupOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access group. + // Details about the Verified Access group. VerifiedAccessGroup *VerifiedAccessGroup `locationName:"verifiedAccessGroup" type:"structure"` } @@ -85753,7 +89054,7 @@ type DeleteVerifiedAccessInstanceInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -85811,7 +89112,7 @@ func (s *DeleteVerifiedAccessInstanceInput) SetVerifiedAccessInstanceId(v string type DeleteVerifiedAccessInstanceOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // Details about the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` } @@ -85853,7 +89154,7 @@ type DeleteVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -85911,7 +89212,7 @@ func (s *DeleteVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderI type DeleteVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // Details about the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -86790,6 +90091,109 @@ func (s *DeprovisionByoipCidrOutput) SetByoipCidr(v *ByoipCidr) *DeprovisionByoi return s } +type DeprovisionIpamByoasnInput struct { + _ struct{} `type:"structure"` + + // An ASN. + // + // Asn is a required field + Asn *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The IPAM ID. + // + // IpamId is a required field + IpamId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeprovisionIpamByoasnInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeprovisionIpamByoasnInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeprovisionIpamByoasnInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeprovisionIpamByoasnInput"} + if s.Asn == nil { + invalidParams.Add(request.NewErrParamRequired("Asn")) + } + if s.IpamId == nil { + invalidParams.Add(request.NewErrParamRequired("IpamId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAsn sets the Asn field's value. +func (s *DeprovisionIpamByoasnInput) SetAsn(v string) *DeprovisionIpamByoasnInput { + s.Asn = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *DeprovisionIpamByoasnInput) SetDryRun(v bool) *DeprovisionIpamByoasnInput { + s.DryRun = &v + return s +} + +// SetIpamId sets the IpamId field's value. +func (s *DeprovisionIpamByoasnInput) SetIpamId(v string) *DeprovisionIpamByoasnInput { + s.IpamId = &v + return s +} + +type DeprovisionIpamByoasnOutput struct { + _ struct{} `type:"structure"` + + // An ASN and BYOIP CIDR association. + Byoasn *Byoasn `locationName:"byoasn" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeprovisionIpamByoasnOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DeprovisionIpamByoasnOutput) GoString() string { + return s.String() +} + +// SetByoasn sets the Byoasn field's value. +func (s *DeprovisionIpamByoasnOutput) SetByoasn(v *Byoasn) *DeprovisionIpamByoasnOutput { + s.Byoasn = v + return s +} + type DeprovisionIpamPoolCidrInput struct { _ struct{} `type:"structure"` @@ -87094,7 +90498,9 @@ type DeregisterInstanceEventNotificationAttributesInput struct { DryRun *bool `type:"boolean"` // Information about the tag keys to deregister. - InstanceTagAttribute *DeregisterInstanceTagAttributeRequest `type:"structure"` + // + // InstanceTagAttribute is a required field + InstanceTagAttribute *DeregisterInstanceTagAttributeRequest `type:"structure" required:"true"` } // String returns the string representation. @@ -87115,6 +90521,19 @@ func (s DeregisterInstanceEventNotificationAttributesInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeregisterInstanceEventNotificationAttributesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeregisterInstanceEventNotificationAttributesInput"} + if s.InstanceTagAttribute == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceTagAttribute")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetDryRun sets the DryRun field's value. func (s *DeregisterInstanceEventNotificationAttributesInput) SetDryRun(v bool) *DeregisterInstanceEventNotificationAttributesInput { s.DryRun = &v @@ -87705,7 +91124,7 @@ func (s *DescribeAddressesAttributeOutput) SetNextToken(v string) *DescribeAddre type DescribeAddressesInput struct { _ struct{} `type:"structure"` - // [EC2-VPC] Information about the allocation IDs. + // Information about the allocation IDs. AllocationIds []*string `locationName:"AllocationId" locationNameList:"AllocationId" type:"list"` // Checks whether you have the required permissions for the action, without @@ -87716,12 +91135,9 @@ type DescribeAddressesInput struct { // One or more filters. Filter names and values are case-sensitive. // - // * allocation-id - [EC2-VPC] The allocation ID for the address. - // - // * association-id - [EC2-VPC] The association ID for the address. + // * allocation-id - The allocation ID for the address. // - // * domain - Indicates whether the address is for use in EC2-Classic (standard) - // or in a VPC (vpc). + // * association-id - The association ID for the address. // // * instance-id - The ID of the instance the address is associated with, // if any. @@ -87729,14 +91145,14 @@ type DescribeAddressesInput struct { // * network-border-group - A unique set of Availability Zones, Local Zones, // or Wavelength Zones from where Amazon Web Services advertises IP addresses. // - // * network-interface-id - [EC2-VPC] The ID of the network interface that - // the address is associated with, if any. + // * network-interface-id - The ID of the network interface that the address + // is associated with, if any. // // * network-interface-owner-id - The Amazon Web Services account ID of the // owner. // - // * private-ip-address - [EC2-VPC] The private IP address associated with - // the Elastic IP address. + // * private-ip-address - The private IP address associated with the Elastic + // IP address. // // * public-ip - The Elastic IP address, or the carrier IP address. // @@ -88363,6 +91779,174 @@ func (s *DescribeByoipCidrsOutput) SetNextToken(v string) *DescribeByoipCidrsOut return s } +type DescribeCapacityBlockOfferingsInput struct { + _ struct{} `type:"structure"` + + // The number of hours for which to reserve Capacity Block. + // + // CapacityDurationHours is a required field + CapacityDurationHours *int64 `type:"integer" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The latest end date for the Capacity Block offering. + EndDateRange *time.Time `type:"timestamp"` + + // The number of instances for which to reserve capacity. + // + // InstanceCount is a required field + InstanceCount *int64 `type:"integer" required:"true"` + + // The type of instance for which the Capacity Block offering reserves capacity. + // + // InstanceType is a required field + InstanceType *string `type:"string" required:"true"` + + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). + MaxResults *int64 `min:"1" type:"integer"` + + // The token to use to retrieve the next page of results. + NextToken *string `type:"string"` + + // The earliest start date for the Capacity Block offering. + StartDateRange *time.Time `type:"timestamp"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeCapacityBlockOfferingsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeCapacityBlockOfferingsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCapacityBlockOfferingsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeCapacityBlockOfferingsInput"} + if s.CapacityDurationHours == nil { + invalidParams.Add(request.NewErrParamRequired("CapacityDurationHours")) + } + if s.InstanceCount == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceCount")) + } + if s.InstanceType == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceType")) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCapacityDurationHours sets the CapacityDurationHours field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetCapacityDurationHours(v int64) *DescribeCapacityBlockOfferingsInput { + s.CapacityDurationHours = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetDryRun(v bool) *DescribeCapacityBlockOfferingsInput { + s.DryRun = &v + return s +} + +// SetEndDateRange sets the EndDateRange field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetEndDateRange(v time.Time) *DescribeCapacityBlockOfferingsInput { + s.EndDateRange = &v + return s +} + +// SetInstanceCount sets the InstanceCount field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetInstanceCount(v int64) *DescribeCapacityBlockOfferingsInput { + s.InstanceCount = &v + return s +} + +// SetInstanceType sets the InstanceType field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetInstanceType(v string) *DescribeCapacityBlockOfferingsInput { + s.InstanceType = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetMaxResults(v int64) *DescribeCapacityBlockOfferingsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetNextToken(v string) *DescribeCapacityBlockOfferingsInput { + s.NextToken = &v + return s +} + +// SetStartDateRange sets the StartDateRange field's value. +func (s *DescribeCapacityBlockOfferingsInput) SetStartDateRange(v time.Time) *DescribeCapacityBlockOfferingsInput { + s.StartDateRange = &v + return s +} + +type DescribeCapacityBlockOfferingsOutput struct { + _ struct{} `type:"structure"` + + // The recommended Capacity Block offering for the dates specified. + CapacityBlockOfferings []*CapacityBlockOffering `locationName:"capacityBlockOfferingSet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeCapacityBlockOfferingsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeCapacityBlockOfferingsOutput) GoString() string { + return s.String() +} + +// SetCapacityBlockOfferings sets the CapacityBlockOfferings field's value. +func (s *DescribeCapacityBlockOfferingsOutput) SetCapacityBlockOfferings(v []*CapacityBlockOffering) *DescribeCapacityBlockOfferingsOutput { + s.CapacityBlockOfferings = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCapacityBlockOfferingsOutput) SetNextToken(v string) *DescribeCapacityBlockOfferingsOutput { + s.NextToken = &v + return s +} + type DescribeCapacityReservationFleetsInput struct { _ struct{} `type:"structure"` @@ -88389,10 +91973,9 @@ type DescribeCapacityReservationFleetsInput struct { // prioritized is supported. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The maximum number of results to return for the request in a single page. - // The remaining results can be seen by sending another request with the returned - // nextToken value. This value can be between 5 and 500. If maxResults is given - // a larger value than 500, you receive an error. + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). MaxResults *int64 `min:"1" type:"integer"` // The token to use to retrieve the next page of results. @@ -88576,10 +92159,9 @@ type DescribeCapacityReservationsInput struct { // the Capacity Reservation was created. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The maximum number of results to return for the request in a single page. - // The remaining results can be seen by sending another request with the returned - // nextToken value. This value can be between 5 and 500. If maxResults is given - // a larger value than 500, you receive an error. + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). MaxResults *int64 `min:"1" type:"integer"` // The token to use to retrieve the next page of results. @@ -88842,7 +92424,7 @@ type DescribeClassicLinkInstancesInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * group-id - The ID of a VPC security group that's associated with the // instance. @@ -88859,11 +92441,10 @@ type DescribeClassicLinkInstancesInput struct { // to find all resources assigned a tag with a specific key, regardless of // the tag value. // - // * vpc-id - The ID of the VPC to which the instance is linked. vpc-id - - // The ID of the VPC that the instance is linked to. + // * vpc-id - The ID of the VPC to which the instance is linked. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // One or more instance IDs. Must be instances linked to a VPC through ClassicLink. + // The instance IDs. Must be instances linked to a VPC through ClassicLink. InstanceIds []*string `locationName:"InstanceId" locationNameList:"InstanceId" type:"list"` // The maximum number of items to return for this request. To get the next page @@ -89998,7 +93579,7 @@ type DescribeDhcpOptionsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * dhcp-options-id - The ID of a DHCP options set. // @@ -90141,10 +93722,10 @@ type DescribeEgressOnlyInternetGatewaysInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // One or more egress-only internet gateway IDs. + // The IDs of the egress-only internet gateways. EgressOnlyInternetGatewayIds []*string `locationName:"EgressOnlyInternetGatewayId" locationNameList:"item" type:"list"` - // One or more filters. + // The filters. // // * tag: - The key/value combination of a tag assigned to the resource. // Use the tag key in the filter name and the tag value as the filter value. @@ -90629,15 +94210,12 @@ type DescribeFastLaunchImagesInput struct { // // * resource-type - The resource type for pre-provisioning. // - // * launch-template - The launch template that is associated with the pre-provisioned - // Windows AMI. - // // * owner-id - The owner ID for the pre-provisioning resource. // // * state - The current state of fast launching for the Windows AMI. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // Details for one or more Windows AMI image IDs. + // Specify one or more Windows AMI image IDs for the request. ImageIds []*string `locationName:"ImageId" locationNameList:"ImageId" type:"list"` // The maximum number of items to return for this request. To get the next page @@ -90740,43 +94318,41 @@ func (s *DescribeFastLaunchImagesOutput) SetNextToken(v string) *DescribeFastLau return s } -// Describe details about a fast-launch enabled Windows image that meets the -// requested criteria. Criteria are defined by the DescribeFastLaunchImages +// Describe details about a Windows image with Windows fast launch enabled that +// meets the requested criteria. Criteria are defined by the DescribeFastLaunchImages // action filters. type DescribeFastLaunchImagesSuccessItem struct { _ struct{} `type:"structure"` - // The image ID that identifies the fast-launch enabled Windows image. + // The image ID that identifies the Windows fast launch enabled image. ImageId *string `locationName:"imageId" type:"string"` - // The launch template that the fast-launch enabled Windows AMI uses when it + // The launch template that the Windows fast launch enabled AMI uses when it // launches Windows instances from pre-provisioned snapshots. LaunchTemplate *FastLaunchLaunchTemplateSpecificationResponse `locationName:"launchTemplate" type:"structure"` // The maximum number of instances that Amazon EC2 can launch at the same time - // to create pre-provisioned snapshots for Windows faster launching. + // to create pre-provisioned snapshots for Windows fast launch. MaxParallelLaunches *int64 `locationName:"maxParallelLaunches" type:"integer"` - // The owner ID for the fast-launch enabled Windows AMI. + // The owner ID for the Windows fast launch enabled AMI. OwnerId *string `locationName:"ownerId" type:"string"` - // The resource type that is used for pre-provisioning the Windows AMI. Supported - // values include: snapshot. + // The resource type that Amazon EC2 uses for pre-provisioning the Windows AMI. + // Supported values include: snapshot. ResourceType *string `locationName:"resourceType" type:"string" enum:"FastLaunchResourceType"` // A group of parameters that are used for pre-provisioning the associated Windows // AMI using snapshots. SnapshotConfiguration *FastLaunchSnapshotConfigurationResponse `locationName:"snapshotConfiguration" type:"structure"` - // The current state of faster launching for the specified Windows AMI. + // The current state of Windows fast launch for the specified Windows AMI. State *string `locationName:"state" type:"string" enum:"FastLaunchStateCode"` - // The reason that faster launching for the Windows AMI changed to the current - // state. + // The reason that Windows fast launch for the AMI changed to the current state. StateTransitionReason *string `locationName:"stateTransitionReason" type:"string"` - // The time that faster launching for the Windows AMI changed to the current - // state. + // The time that Windows fast launch for the AMI changed to the current state. StateTransitionTime *time.Time `locationName:"stateTransitionTime" type:"timestamp"` } @@ -93013,7 +96589,8 @@ type DescribeImagesInput struct { // The filters. // - // * architecture - The image architecture (i386 | x86_64 | arm64). + // * architecture - The image architecture (i386 | x86_64 | arm64 | x86_64_mac + // | arm64_mac). // // * block-device-mapping.delete-on-termination - A Boolean value that indicates // whether the Amazon EBS volume is deleted on instance termination. @@ -93078,6 +96655,10 @@ type DescribeImagesInput struct { // // * root-device-type - The type of the root device volume (ebs | instance-store). // + // * source-instance-id - The ID of the instance that the AMI was created + // from if the AMI was created using CreateImage. This filter is applicable + // only if the AMI was created using CreateImage (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html). + // // * state - The state of the image (available | pending | failed). // // * state-reason-code - The reason code for the state change. @@ -93113,6 +96694,11 @@ type DescribeImagesInput struct { // of what you specify for this parameter. IncludeDeprecated *bool `type:"boolean"` + // Specifies whether to include disabled AMIs. + // + // Default: No disabled AMIs are included in the response. + IncludeDisabled *bool `type:"boolean"` + // The maximum number of items to return for this request. To get the next page // of items, make another request with the token returned in the output. For // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). @@ -93177,6 +96763,12 @@ func (s *DescribeImagesInput) SetIncludeDeprecated(v bool) *DescribeImagesInput return s } +// SetIncludeDisabled sets the IncludeDisabled field's value. +func (s *DescribeImagesInput) SetIncludeDisabled(v bool) *DescribeImagesInput { + s.IncludeDisabled = &v + return s +} + // SetMaxResults sets the MaxResults field's value. func (s *DescribeImagesInput) SetMaxResults(v int64) *DescribeImagesInput { s.MaxResults = &v @@ -93722,6 +97314,159 @@ func (s *DescribeInstanceAttributeOutput) SetUserData(v *AttributeValue) *Descri return s } +type DescribeInstanceConnectEndpointsInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more filters. + // + // * instance-connect-endpoint-id - The ID of the EC2 Instance Connect Endpoint. + // + // * state - The state of the EC2 Instance Connect Endpoint (create-in-progress + // | create-complete | create-failed | delete-in-progress | delete-complete + // | delete-failed). + // + // * subnet-id - The ID of the subnet in which the EC2 Instance Connect Endpoint + // was created. + // + // * tag: - The key/value combination of a tag assigned to the resource. + // Use the tag key in the filter name and the tag value as the filter value. + // For example, to find all resources that have a tag with the key Owner + // and the value TeamA, specify tag:Owner for the filter name and TeamA for + // the filter value. + // + // * tag-key - The key of a tag assigned to the resource. Use this filter + // to find all resources assigned a tag with a specific key, regardless of + // the tag value. + // + // * tag-value - The value of a tag assigned to the resource. Use this filter + // to find all resources that have a tag with a specific value, regardless + // of tag key. + // + // * vpc-id - The ID of the VPC in which the EC2 Instance Connect Endpoint + // was created. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // One or more EC2 Instance Connect Endpoint IDs. + InstanceConnectEndpointIds []*string `locationName:"InstanceConnectEndpointId" locationNameList:"item" type:"list"` + + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). + MaxResults *int64 `min:"1" type:"integer"` + + // The token returned from a previous paginated request. Pagination continues + // from the end of the items returned by the previous request. + NextToken *string `type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceConnectEndpointsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceConnectEndpointsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeInstanceConnectEndpointsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeInstanceConnectEndpointsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeInstanceConnectEndpointsInput) SetDryRun(v bool) *DescribeInstanceConnectEndpointsInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *DescribeInstanceConnectEndpointsInput) SetFilters(v []*Filter) *DescribeInstanceConnectEndpointsInput { + s.Filters = v + return s +} + +// SetInstanceConnectEndpointIds sets the InstanceConnectEndpointIds field's value. +func (s *DescribeInstanceConnectEndpointsInput) SetInstanceConnectEndpointIds(v []*string) *DescribeInstanceConnectEndpointsInput { + s.InstanceConnectEndpointIds = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeInstanceConnectEndpointsInput) SetMaxResults(v int64) *DescribeInstanceConnectEndpointsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInstanceConnectEndpointsInput) SetNextToken(v string) *DescribeInstanceConnectEndpointsInput { + s.NextToken = &v + return s +} + +type DescribeInstanceConnectEndpointsOutput struct { + _ struct{} `type:"structure"` + + // Information about the EC2 Instance Connect Endpoints. + InstanceConnectEndpoints []*Ec2InstanceConnectEndpoint `locationName:"instanceConnectEndpointSet" locationNameList:"item" type:"list"` + + // The token to include in another request to get the next page of items. This + // value is null when there are no more items to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceConnectEndpointsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceConnectEndpointsOutput) GoString() string { + return s.String() +} + +// SetInstanceConnectEndpoints sets the InstanceConnectEndpoints field's value. +func (s *DescribeInstanceConnectEndpointsOutput) SetInstanceConnectEndpoints(v []*Ec2InstanceConnectEndpoint) *DescribeInstanceConnectEndpointsOutput { + s.InstanceConnectEndpoints = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInstanceConnectEndpointsOutput) SetNextToken(v string) *DescribeInstanceConnectEndpointsOutput { + s.NextToken = &v + return s +} + type DescribeInstanceCreditSpecificationsInput struct { _ struct{} `type:"structure"` @@ -94256,6 +98001,164 @@ func (s *DescribeInstanceStatusOutput) SetNextToken(v string) *DescribeInstanceS return s } +type DescribeInstanceTopologyInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The filters. + // + // * availability-zone - The name of the Availability Zone (for example, + // us-west-2a) or Local Zone (for example, us-west-2-lax-1b) that the instance + // is in. + // + // * instance-type - The instance type (for example, p4d.24xlarge) or instance + // family (for example, p4d*). You can use the * wildcard to match zero or + // more characters, or the ? wildcard to match zero or one character. + // + // * zone-id - The ID of the Availability Zone (for example, usw2-az2) or + // Local Zone (for example, usw2-lax1-az1) that the instance is in. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The name of the placement group that each instance is in. + // + // Constraints: Maximum 100 explicitly specified placement group names. + GroupNames []*string `locationName:"GroupName" type:"list"` + + // The instance IDs. + // + // Default: Describes all your instances. + // + // Constraints: Maximum 100 explicitly specified instance IDs. + InstanceIds []*string `locationName:"InstanceId" type:"list"` + + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). + // + // You can't specify this parameter and the instance IDs parameter in the same + // request. + // + // Default: 20 + MaxResults *int64 `min:"1" type:"integer"` + + // The token returned from a previous paginated request. Pagination continues + // from the end of the items returned by the previous request. + NextToken *string `type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceTopologyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceTopologyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeInstanceTopologyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeInstanceTopologyInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeInstanceTopologyInput) SetDryRun(v bool) *DescribeInstanceTopologyInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *DescribeInstanceTopologyInput) SetFilters(v []*Filter) *DescribeInstanceTopologyInput { + s.Filters = v + return s +} + +// SetGroupNames sets the GroupNames field's value. +func (s *DescribeInstanceTopologyInput) SetGroupNames(v []*string) *DescribeInstanceTopologyInput { + s.GroupNames = v + return s +} + +// SetInstanceIds sets the InstanceIds field's value. +func (s *DescribeInstanceTopologyInput) SetInstanceIds(v []*string) *DescribeInstanceTopologyInput { + s.InstanceIds = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeInstanceTopologyInput) SetMaxResults(v int64) *DescribeInstanceTopologyInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInstanceTopologyInput) SetNextToken(v string) *DescribeInstanceTopologyInput { + s.NextToken = &v + return s +} + +type DescribeInstanceTopologyOutput struct { + _ struct{} `type:"structure"` + + // Information about the topology of each instance. + Instances []*InstanceTopology `locationName:"instanceSet" locationNameList:"item" type:"list"` + + // The token to include in another request to get the next page of items. This + // value is null when there are no more items to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceTopologyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeInstanceTopologyOutput) GoString() string { + return s.String() +} + +// SetInstances sets the Instances field's value. +func (s *DescribeInstanceTopologyOutput) SetInstances(v []*InstanceTopology) *DescribeInstanceTopologyOutput { + s.Instances = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInstanceTopologyOutput) SetNextToken(v string) *DescribeInstanceTopologyOutput { + s.NextToken = &v + return s +} + type DescribeInstanceTypeOfferingsInput struct { _ struct{} `type:"structure"` @@ -94400,14 +98303,14 @@ type DescribeInstanceTypesInput struct { // One or more filters. Filter names and values are case-sensitive. // - // * auto-recovery-supported - Indicates whether auto recovery is supported - // (true | false). + // * auto-recovery-supported - Indicates whether Amazon CloudWatch action + // based recovery is supported (true | false). // // * bare-metal - Indicates whether it is a bare metal instance type (true // | false). // - // * burstable-performance-supported - Indicates whether it is a burstable - // performance instance type (true | false). + // * burstable-performance-supported - Indicates whether the instance type + // is a burstable performance T instance type (true | false). // // * current-generation - Indicates whether this instance type is the latest // generation instance type of an instance family (true | false). @@ -94503,12 +98406,22 @@ type DescribeInstanceTypesInput struct { // * network-info.network-performance - The network performance (for example, // "25 Gigabit"). // + // * nitro-enclaves-support - Indicates whether Nitro Enclaves is supported + // (supported | unsupported). + // + // * nitro-tpm-support - Indicates whether NitroTPM is supported (supported + // | unsupported). + // + // * nitro-tpm-info.supported-versions - The supported NitroTPM version (2.0). + // // * processor-info.supported-architecture - The CPU architecture (arm64 // | i386 | x86_64). // // * processor-info.sustained-clock-speed-in-ghz - The CPU clock speed, in // GHz. // + // * processor-info.supported-features - The supported CPU features (amd-sev-snp). + // // * supported-boot-mode - The boot mode (legacy-bios | uefi). // // * supported-root-device-type - The root device type (ebs | instance-store). @@ -94669,7 +98582,7 @@ type DescribeInstancesInput struct { // * availability-zone - The Availability Zone of the instance. // // * block-device-mapping.attach-time - The attach time for an EBS volume - // mapped to the instance, for example, 2010-09-15T17:15:20.000Z. + // mapped to the instance, for example, 2022-09-15T17:15:20.000Z. // // * block-device-mapping.delete-on-termination - A Boolean that indicates // whether the EBS volume is deleted on instance termination. @@ -94682,19 +98595,37 @@ type DescribeInstancesInput struct { // // * block-device-mapping.volume-id - The volume ID of the EBS volume. // + // * boot-mode - The boot mode that was specified by the AMI (legacy-bios + // | uefi | uefi-preferred). + // // * capacity-reservation-id - The ID of the Capacity Reservation into which // the instance was launched. // + // * capacity-reservation-specification.capacity-reservation-preference - + // The instance's Capacity Reservation preference (open | none). + // + // * capacity-reservation-specification.capacity-reservation-target.capacity-reservation-id + // - The ID of the targeted Capacity Reservation. + // + // * capacity-reservation-specification.capacity-reservation-target.capacity-reservation-resource-group-arn + // - The ARN of the targeted Capacity Reservation group. + // // * client-token - The idempotency token you provided when you launched // the instance. // + // * current-instance-boot-mode - The boot mode that is used to launch the + // instance at launch or start (legacy-bios | uefi). + // // * dns-name - The public DNS name of the instance. // - // * group-id - The ID of the security group for the instance. EC2-Classic - // only. + // * ebs-optimized - A Boolean that indicates whether the instance is optimized + // for Amazon EBS I/O. // - // * group-name - The name of the security group for the instance. EC2-Classic - // only. + // * ena-support - A Boolean that indicates whether the instance is enabled + // for enhanced networking with ENA. + // + // * enclave-options.enabled - A Boolean that indicates whether the instance + // is enabled for Amazon Web Services Nitro Enclaves. // // * hibernation-options.configured - A Boolean that indicates whether the // instance is enabled for hibernation. A value of true means that the instance @@ -94709,12 +98640,18 @@ type DescribeInstancesInput struct { // * iam-instance-profile.arn - The instance profile associated with the // instance. Specified as an ARN. // + // * iam-instance-profile.id - The instance profile associated with the instance. + // Specified as an ID. + // + // * iam-instance-profile.name - The instance profile associated with the + // instance. Specified as an name. + // // * image-id - The ID of the image used to launch the instance. // // * instance-id - The ID of the instance. // - // * instance-lifecycle - Indicates whether this is a Spot Instance or a - // Scheduled Instance (spot | scheduled). + // * instance-lifecycle - Indicates whether this is a Spot Instance, a Scheduled + // Instance, or a Capacity Block (spot | scheduled | capacity-block). // // * instance-state-code - The state of the instance, as a 16-bit unsigned // integer. The high byte is used for internal purposes and should be ignored. @@ -94733,6 +98670,8 @@ type DescribeInstancesInput struct { // // * ip-address - The public IPv4 address of the instance. // + // * ipv6-address - The IPv6 address of the instance. + // // * kernel-id - The kernel ID. // // * key-name - The name of the key pair used when the instance was launched. @@ -94745,38 +98684,61 @@ type DescribeInstancesInput struct { // You can use a wildcard (*), for example, 2021-09-29T*, which matches an // entire day. // - // * metadata-options.http-tokens - The metadata request authorization state - // (optional | required) + // * maintenance-options.auto-recovery - The current automatic recovery behavior + // of the instance (disabled | default). + // + // * metadata-options.http-endpoint - The status of access to the HTTP metadata + // endpoint on your instance (enabled | disabled) + // + // * metadata-options.http-protocol-ipv4 - Indicates whether the IPv4 endpoint + // is enabled (disabled | enabled). + // + // * metadata-options.http-protocol-ipv6 - Indicates whether the IPv6 endpoint + // is enabled (disabled | enabled). // // * metadata-options.http-put-response-hop-limit - The HTTP metadata request // put response hop limit (integer, possible values 1 to 64) // - // * metadata-options.http-endpoint - The status of access to the HTTP metadata - // endpoint on your instance (enabled | disabled) + // * metadata-options.http-tokens - The metadata request authorization state + // (optional | required) // // * metadata-options.instance-metadata-tags - The status of access to instance // tags from the instance metadata (enabled | disabled) // + // * metadata-options.state - The state of the metadata option changes (pending + // | applied). + // // * monitoring-state - Indicates whether detailed monitoring is enabled // (disabled | enabled). // - // * network-interface.addresses.private-ip-address - The private IPv4 address - // associated with the network interface. + // * network-interface.addresses.association.allocation-id - The allocation + // ID. // - // * network-interface.addresses.primary - Specifies whether the IPv4 address - // of the network interface is the primary private IPv4 address. + // * network-interface.addresses.association.association-id - The association + // ID. // - // * network-interface.addresses.association.public-ip - The ID of the association - // of an Elastic IP address (IPv4) with a network interface. + // * network-interface.addresses.association.carrier-ip - The carrier IP + // address. + // + // * network-interface.addresses.association.customer-owned-ip - The customer-owned + // IP address. // // * network-interface.addresses.association.ip-owner-id - The owner ID of // the private IPv4 address associated with the network interface. // - // * network-interface.association.public-ip - The address of the Elastic - // IP address (IPv4) bound to the network interface. + // * network-interface.addresses.association.public-dns-name - The public + // DNS name. // - // * network-interface.association.ip-owner-id - The owner of the Elastic - // IP address (IPv4) associated with the network interface. + // * network-interface.addresses.association.public-ip - The ID of the association + // of an Elastic IP address (IPv4) with a network interface. + // + // * network-interface.addresses.primary - Specifies whether the IPv4 address + // of the network interface is the primary private IPv4 address. + // + // * network-interface.addresses.private-dns-name - The private DNS name. + // + // * network-interface.addresses.private-ip-address - The private IPv4 address + // associated with the network interface. // // * network-interface.association.allocation-id - The allocation ID returned // when you allocated the Elastic IP address (IPv4) for your network interface. @@ -94784,30 +98746,50 @@ type DescribeInstancesInput struct { // * network-interface.association.association-id - The association ID returned // when the network interface was associated with an IPv4 address. // + // * network-interface.association.carrier-ip - The customer-owned IP address. + // + // * network-interface.association.customer-owned-ip - The customer-owned + // IP address. + // + // * network-interface.association.ip-owner-id - The owner of the Elastic + // IP address (IPv4) associated with the network interface. + // + // * network-interface.association.public-dns-name - The public DNS name. + // + // * network-interface.association.public-ip - The address of the Elastic + // IP address (IPv4) bound to the network interface. + // + // * network-interface.attachment.attach-time - The time that the network + // interface was attached to an instance. + // // * network-interface.attachment.attachment-id - The ID of the interface // attachment. // + // * network-interface.attachment.delete-on-termination - Specifies whether + // the attachment is deleted when an instance is terminated. + // + // * network-interface.attachment.device-index - The device index to which + // the network interface is attached. + // // * network-interface.attachment.instance-id - The ID of the instance to // which the network interface is attached. // // * network-interface.attachment.instance-owner-id - The owner ID of the // instance to which the network interface is attached. // - // * network-interface.attachment.device-index - The device index to which - // the network interface is attached. + // * network-interface.attachment.network-card-index - The index of the network + // card. // // * network-interface.attachment.status - The status of the attachment (attaching // | attached | detaching | detached). // - // * network-interface.attachment.attach-time - The time that the network - // interface was attached to an instance. - // - // * network-interface.attachment.delete-on-termination - Specifies whether - // the attachment is deleted when an instance is terminated. - // // * network-interface.availability-zone - The Availability Zone for the // network interface. // + // * network-interface.deny-all-igw-traffic - A Boolean that indicates whether + // a network interface with an IPv6 address is unreachable from the public + // internet. + // // * network-interface.description - The description of the network interface. // // * network-interface.group-id - The ID of a security group associated with @@ -94816,18 +98798,39 @@ type DescribeInstancesInput struct { // * network-interface.group-name - The name of a security group associated // with the network interface. // + // * network-interface.ipv4-prefixes.ipv4-prefix - The IPv4 prefixes that + // are assigned to the network interface. + // + // * network-interface.ipv6-address - The IPv6 address associated with the + // network interface. + // // * network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated // with the network interface. // + // * network-interface.ipv6-addresses.is-primary-ipv6 - A Boolean that indicates + // whether this is the primary IPv6 address. + // + // * network-interface.ipv6-native - A Boolean that indicates whether this + // is an IPv6 only network interface. + // + // * network-interface.ipv6-prefixes.ipv6-prefix - The IPv6 prefix assigned + // to the network interface. + // // * network-interface.mac-address - The MAC address of the network interface. // // * network-interface.network-interface-id - The ID of the network interface. // + // * network-interface.outpost-arn - The ARN of the Outpost. + // // * network-interface.owner-id - The ID of the owner of the network interface. // // * network-interface.private-dns-name - The private DNS name of the network // interface. // + // * network-interface.private-ip-address - The private IPv4 address. + // + // * network-interface.public-dns-name - The public DNS name. + // // * network-interface.requester-id - The requester ID for the network interface. // // * network-interface.requester-managed - Indicates whether the network @@ -94844,6 +98847,12 @@ type DescribeInstancesInput struct { // // * network-interface.subnet-id - The ID of the subnet for the network interface. // + // * network-interface.tag-key - The key of a tag assigned to the network + // interface. + // + // * network-interface.tag-value - The value of a tag assigned to the network + // interface. + // // * network-interface.vpc-id - The ID of the VPC for the network interface. // // * outpost-arn - The Amazon Resource Name (ARN) of the Outpost. @@ -94857,8 +98866,29 @@ type DescribeInstancesInput struct { // // * platform - The platform. To list only Windows instances, use windows. // + // * platform-details - The platform (Linux/UNIX | Red Hat BYOL Linux | Red + // Hat Enterprise Linux | Red Hat Enterprise Linux with HA | Red Hat Enterprise + // Linux with SQL Server Standard and HA | Red Hat Enterprise Linux with + // SQL Server Enterprise and HA | Red Hat Enterprise Linux with SQL Server + // Standard | Red Hat Enterprise Linux with SQL Server Web | Red Hat Enterprise + // Linux with SQL Server Enterprise | SQL Server Enterprise | SQL Server + // Standard | SQL Server Web | SUSE Linux | Ubuntu Pro | Windows | Windows + // BYOL | Windows with SQL Server Enterprise | Windows with SQL Server Standard + // | Windows with SQL Server Web). + // // * private-dns-name - The private IPv4 DNS name of the instance. // + // * private-dns-name-options.enable-resource-name-dns-a-record - A Boolean + // that indicates whether to respond to DNS queries for instance hostnames + // with DNS A records. + // + // * private-dns-name-options.enable-resource-name-dns-aaaa-record - A Boolean + // that indicates whether to respond to DNS queries for instance hostnames + // with DNS AAAA records. + // + // * private-dns-name-options.hostname-type - The type of hostname (ip-name + // | resource-name). + // // * private-ip-address - The private IPv4 address of the instance. // // * product-code - The product code associated with the AMI used to launch @@ -94914,6 +98944,19 @@ type DescribeInstancesInput struct { // // * tenancy - The tenancy of an instance (dedicated | default | host). // + // * tpm-support - Indicates if the instance is configured for NitroTPM support + // (v2.0). + // + // * usage-operation - The usage operation value for the instance (RunInstances + // | RunInstances:00g0 | RunInstances:0010 | RunInstances:1010 | RunInstances:1014 + // | RunInstances:1110 | RunInstances:0014 | RunInstances:0210 | RunInstances:0110 + // | RunInstances:0100 | RunInstances:0004 | RunInstances:0200 | RunInstances:000g + // | RunInstances:0g00 | RunInstances:0002 | RunInstances:0800 | RunInstances:0102 + // | RunInstances:0006 | RunInstances:0202). + // + // * usage-operation-update-time - The time that the usage operation was + // last updated, for example, 2022-09-15T17:15:20.000Z. + // // * virtualization-type - The virtualization type of the instance (paravirtual // | hvm). // @@ -95036,7 +99079,7 @@ type DescribeInternetGatewaysInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * attachment.state - The current state of the attachment between the gateway // and the VPC (available). Present only if a VPC is attached. @@ -95059,7 +99102,7 @@ type DescribeInternetGatewaysInput struct { // the tag value. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // One or more internet gateway IDs. + // The IDs of the internet gateways. // // Default: Describes all your internet gateways. InternetGatewayIds []*string `locationName:"internetGatewayId" locationNameList:"item" type:"list"` @@ -95176,6 +99219,113 @@ func (s *DescribeInternetGatewaysOutput) SetNextToken(v string) *DescribeInterne return s } +type DescribeIpamByoasnInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeIpamByoasnInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeIpamByoasnInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeIpamByoasnInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeIpamByoasnInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeIpamByoasnInput) SetDryRun(v bool) *DescribeIpamByoasnInput { + s.DryRun = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeIpamByoasnInput) SetMaxResults(v int64) *DescribeIpamByoasnInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeIpamByoasnInput) SetNextToken(v string) *DescribeIpamByoasnInput { + s.NextToken = &v + return s +} + +type DescribeIpamByoasnOutput struct { + _ struct{} `type:"structure"` + + // ASN and BYOIP CIDR associations. + Byoasns []*Byoasn `locationName:"byoasnSet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeIpamByoasnOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeIpamByoasnOutput) GoString() string { + return s.String() +} + +// SetByoasns sets the Byoasns field's value. +func (s *DescribeIpamByoasnOutput) SetByoasns(v []*Byoasn) *DescribeIpamByoasnOutput { + s.Byoasns = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeIpamByoasnOutput) SetNextToken(v string) *DescribeIpamByoasnOutput { + s.NextToken = &v + return s +} + type DescribeIpamPoolsInput struct { _ struct{} `type:"structure"` @@ -97280,6 +101430,136 @@ func (s *DescribeLocalGatewaysOutput) SetNextToken(v string) *DescribeLocalGatew return s } +type DescribeLockedSnapshotsInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The filters. + // + // * lock-state - The state of the snapshot lock (compliance-cooloff | governance + // | compliance | expired). + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). + MaxResults *int64 `min:"5" type:"integer"` + + // The token returned from a previous paginated request. Pagination continues + // from the end of the items returned by the previous request. + NextToken *string `type:"string"` + + // The IDs of the snapshots for which to view the lock status. + SnapshotIds []*string `locationName:"SnapshotId" locationNameList:"SnapshotId" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeLockedSnapshotsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeLockedSnapshotsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeLockedSnapshotsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeLockedSnapshotsInput"} + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeLockedSnapshotsInput) SetDryRun(v bool) *DescribeLockedSnapshotsInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *DescribeLockedSnapshotsInput) SetFilters(v []*Filter) *DescribeLockedSnapshotsInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeLockedSnapshotsInput) SetMaxResults(v int64) *DescribeLockedSnapshotsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeLockedSnapshotsInput) SetNextToken(v string) *DescribeLockedSnapshotsInput { + s.NextToken = &v + return s +} + +// SetSnapshotIds sets the SnapshotIds field's value. +func (s *DescribeLockedSnapshotsInput) SetSnapshotIds(v []*string) *DescribeLockedSnapshotsInput { + s.SnapshotIds = v + return s +} + +type DescribeLockedSnapshotsOutput struct { + _ struct{} `type:"structure"` + + // The token to include in another request to get the next page of items. This + // value is null when there are no more items to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // Information about the snapshots. + Snapshots []*LockedSnapshotsInfo `locationName:"snapshotSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeLockedSnapshotsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DescribeLockedSnapshotsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeLockedSnapshotsOutput) SetNextToken(v string) *DescribeLockedSnapshotsOutput { + s.NextToken = &v + return s +} + +// SetSnapshots sets the Snapshots field's value. +func (s *DescribeLockedSnapshotsOutput) SetSnapshots(v []*LockedSnapshotsInfo) *DescribeLockedSnapshotsOutput { + s.Snapshots = v + return s +} + type DescribeManagedPrefixListsInput struct { _ struct{} `type:"structure"` @@ -97552,7 +101832,7 @@ type DescribeNatGatewaysInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // One or more filters. + // The filters. // // * nat-gateway-id - The ID of the NAT gateway. // @@ -97579,7 +101859,7 @@ type DescribeNatGatewaysInput struct { // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). MaxResults *int64 `min:"5" type:"integer"` - // One or more NAT gateway IDs. + // The IDs of the NAT gateways. NatGatewayIds []*string `locationName:"NatGatewayId" locationNameList:"item" type:"list"` // The token returned from a previous paginated request. Pagination continues @@ -97698,7 +101978,7 @@ type DescribeNetworkAclsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * association.association-id - The ID of an association ID for the ACL. // @@ -97757,7 +102037,7 @@ type DescribeNetworkAclsInput struct { // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). MaxResults *int64 `min:"5" type:"integer"` - // One or more network ACL IDs. + // The IDs of the network ACLs. // // Default: Describes all your network ACLs. NetworkAclIds []*string `locationName:"NetworkAclId" locationNameList:"item" type:"list"` @@ -98739,23 +103019,23 @@ type DescribeNetworkInterfacesInput struct { // One or more filters. // - // * addresses.private-ip-address - The private IPv4 addresses associated - // with the network interface. - // - // * addresses.primary - Whether the private IPv4 address is the primary - // IP address associated with the network interface. + // * association.allocation-id - The allocation ID returned when you allocated + // the Elastic IP address (IPv4) for your network interface. // - // * addresses.association.public-ip - The association ID returned when the - // network interface was associated with the Elastic IP address (IPv4). + // * association.association-id - The association ID returned when the network + // interface was associated with an IPv4 address. // // * addresses.association.owner-id - The owner ID of the addresses associated // with the network interface. // - // * association.association-id - The association ID returned when the network - // interface was associated with an IPv4 address. + // * addresses.association.public-ip - The association ID returned when the + // network interface was associated with the Elastic IP address (IPv4). // - // * association.allocation-id - The allocation ID returned when you allocated - // the Elastic IP address (IPv4) for your network interface. + // * addresses.primary - Whether the private IPv4 address is the primary + // IP address associated with the network interface. + // + // * addresses.private-ip-address - The private IPv4 addresses associated + // with the network interface. // // * association.ip-owner-id - The owner of the Elastic IP address (IPv4) // associated with the network interface. @@ -98766,11 +103046,11 @@ type DescribeNetworkInterfacesInput struct { // * association.public-dns-name - The public DNS name for the network interface // (IPv4). // - // * attachment.attachment-id - The ID of the interface attachment. - // // * attachment.attach-time - The time that the network interface was attached // to an instance. // + // * attachment.attachment-id - The ID of the interface attachment. + // // * attachment.delete-on-termination - Indicates whether the attachment // is deleted when an instance is terminated. // @@ -98792,17 +103072,15 @@ type DescribeNetworkInterfacesInput struct { // // * group-id - The ID of a security group associated with the network interface. // - // * group-name - The name of a security group associated with the network - // interface. - // // * ipv6-addresses.ipv6-address - An IPv6 address associated with the network // interface. // // * interface-type - The type of network interface (api_gateway_managed - // | aws_codestar_connections_managed | branch | efa | gateway_load_balancer - // | gateway_load_balancer_endpoint | global_accelerator_managed | interface - // | iot_rules_managed | lambda | load_balancer | nat_gateway | network_load_balancer - // | quicksight | transit_gateway | trunk | vpc_endpoint). + // | aws_codestar_connections_managed | branch | ec2_instance_connect_endpoint + // | efa | efs | gateway_load_balancer | gateway_load_balancer_endpoint | + // global_accelerator_managed | interface | iot_rules_managed | lambda | + // load_balancer | nat_gateway | network_load_balancer | quicksight | transit_gateway + // | trunk | vpc_endpoint). // // * mac-address - The MAC address of the network interface. // @@ -98811,11 +103089,11 @@ type DescribeNetworkInterfacesInput struct { // * owner-id - The Amazon Web Services account ID of the network interface // owner. // + // * private-dns-name - The private DNS name of the network interface (IPv4). + // // * private-ip-address - The private IPv4 address or addresses of the network // interface. // - // * private-dns-name - The private DNS name of the network interface (IPv4). - // // * requester-id - The alias or Amazon Web Services account ID of the principal // or service that created the network interface. // @@ -99700,16 +103978,11 @@ type DescribeReservedInstancesInput struct { // // * scope - The scope of the Reserved Instance (Region or Availability Zone). // - // * product-description - The Reserved Instance product platform description. - // Instances that include (Amazon VPC) in the product platform description - // will only be displayed to EC2-Classic account holders and are for use - // with Amazon VPC (Linux/UNIX | Linux/UNIX (Amazon VPC) | SUSE Linux | SUSE - // Linux (Amazon VPC) | Red Hat Enterprise Linux | Red Hat Enterprise Linux - // (Amazon VPC) | Red Hat Enterprise Linux with HA (Amazon VPC) | Windows - // | Windows (Amazon VPC) | Windows with SQL Server Standard | Windows with - // SQL Server Standard (Amazon VPC) | Windows with SQL Server Web | Windows - // with SQL Server Web (Amazon VPC) | Windows with SQL Server Enterprise - // | Windows with SQL Server Enterprise (Amazon VPC)). + // * product-description - The Reserved Instance product platform description + // (Linux/UNIX | Linux with SQL Server Standard | Linux with SQL Server Web + // | Linux with SQL Server Enterprise | SUSE Linux | Red Hat Enterprise Linux + // | Red Hat Enterprise Linux with HA | Windows | Windows with SQL Server + // Standard | Windows with SQL Server Web | Windows with SQL Server Enterprise). // // * reserved-instances-id - The ID of the Reserved Instance. // @@ -99911,9 +104184,6 @@ type DescribeReservedInstancesModificationsInput struct { // * modification-result.target-configuration.instance-type - The instance // type of the new Reserved Instances. // - // * modification-result.target-configuration.platform - The network platform - // of the new Reserved Instances (EC2-Classic | EC2-VPC). - // // * reserved-instances-id - The ID of the Reserved Instances modified. // // * reserved-instances-modification-id - The ID of the modification request. @@ -100042,16 +104312,11 @@ type DescribeReservedInstancesOfferingsInput struct { // all offerings from both Amazon Web Services and the Reserved Instance // Marketplace are listed. // - // * product-description - The Reserved Instance product platform description. - // Instances that include (Amazon VPC) in the product platform description - // will only be displayed to EC2-Classic account holders and are for use - // with Amazon VPC. (Linux/UNIX | Linux/UNIX (Amazon VPC) | SUSE Linux | - // SUSE Linux (Amazon VPC) | Red Hat Enterprise Linux | Red Hat Enterprise - // Linux (Amazon VPC) | Red Hat Enterprise Linux with HA (Amazon VPC) | Windows - // | Windows (Amazon VPC) | Windows with SQL Server Standard | Windows with - // SQL Server Standard (Amazon VPC) | Windows with SQL Server Web | Windows - // with SQL Server Web (Amazon VPC) | Windows with SQL Server Enterprise - // | Windows with SQL Server Enterprise (Amazon VPC)) + // * product-description - The Reserved Instance product platform description + // (Linux/UNIX | Linux with SQL Server Standard | Linux with SQL Server Web + // | Linux with SQL Server Enterprise | SUSE Linux | Red Hat Enterprise Linux + // | Red Hat Enterprise Linux with HA | Windows | Windows with SQL Server + // Standard | Windows with SQL Server Web | Windows with SQL Server Enterprise). // // * reserved-instances-offering-id - The Reserved Instances offering ID. // @@ -100311,7 +104576,7 @@ type DescribeRouteTablesInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * association.route-table-association-id - The ID of an association ID // for the route table. @@ -100387,7 +104652,7 @@ type DescribeRouteTablesInput struct { // from the end of the items returned by the previous request. NextToken *string `type:"string"` - // One or more route table IDs. + // The IDs of the route tables. // // Default: Describes all your route tables. RouteTableIds []*string `locationName:"RouteTableId" locationNameList:"item" type:"list"` @@ -100512,8 +104777,6 @@ type DescribeScheduledInstanceAvailabilityInput struct { // // * instance-type - The instance type (for example, c4.large). // - // * network-platform - The network platform (EC2-Classic or EC2-VPC). - // // * platform - The platform (Linux/UNIX or Windows). Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -100694,8 +104957,6 @@ type DescribeScheduledInstancesInput struct { // // * instance-type - The instance type (for example, c4.large). // - // * network-platform - The network platform (EC2-Classic or EC2-VPC). - // // * platform - The platform (Linux/UNIX or Windows). Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -101132,10 +105393,8 @@ type DescribeSecurityGroupsInput struct { // Default: Describes all of your security groups. GroupIds []*string `locationName:"GroupId" locationNameList:"groupId" type:"list"` - // [EC2-Classic and default VPC only] The names of the security groups. You - // can specify either the security group name or the security group ID. For - // security groups in a nondefault VPC, use the group-name filter to describe - // security groups by name. + // [Default VPC] The names of the security groups. You can specify either the + // security group name or the security group ID. // // Default: Describes all of your security groups. GroupNames []*string `locationName:"GroupName" locationNameList:"GroupName" type:"list"` @@ -102167,7 +106426,7 @@ type DescribeSpotInstanceRequestsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * availability-zone-group - The Availability Zone group. // @@ -102194,8 +106453,8 @@ type DescribeSpotInstanceRequestsInput struct { // in GiB. // // * launch.block-device-mapping.volume-type - The type of EBS volume: gp2 - // for General Purpose SSD, io1 or io2 for Provisioned IOPS SSD, st1 for - // Throughput Optimized HDD, sc1for Cold HDD, or standard for Magnetic. + // or gp3 for General Purpose SSD, io1 or io2 for Provisioned IOPS SSD, st1 + // for Throughput Optimized HDD, sc1 for Cold HDD, or standard for Magnetic. // // * launch.group-id - The ID of the security group for the instance. // @@ -102284,7 +106543,7 @@ type DescribeSpotInstanceRequestsInput struct { // from the end of the items returned by the previous request. NextToken *string `type:"string"` - // One or more Spot Instance request IDs. + // The IDs of the Spot Instance requests. SpotInstanceRequestIds []*string `locationName:"SpotInstanceRequestId" locationNameList:"SpotInstanceRequestId" type:"list"` } @@ -102344,7 +106603,7 @@ type DescribeSpotInstanceRequestsOutput struct { // value is null when there are no more items to return. NextToken *string `locationName:"nextToken" type:"string"` - // One or more Spot Instance requests. + // The Spot Instance requests. SpotInstanceRequests []*SpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` } @@ -102395,7 +106654,7 @@ type DescribeSpotPriceHistoryInput struct { // the price history data, in UTC format (for example, YYYY-MM-DDTHH:MM:SSZ). EndTime *time.Time `locationName:"endTime" type:"timestamp"` - // One or more filters. + // The filters. // // * availability-zone - The Availability Zone for which prices should be // returned. @@ -102411,8 +106670,8 @@ type DescribeSpotPriceHistoryInput struct { // greater than or less than comparison is not supported). // // * timestamp - The time stamp of the Spot price history, in UTC format - // (for example, YYYY-MM-DDTHH:MM:SSZ). You can use wildcards (* and ?). - // Greater than or less than comparison is not supported. + // (for example, ddd MMM dd HH:mm:ss UTC YYYY). You can use wildcards (* + // and ?). Greater than or less than comparison is not supported. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // Filters the results by the specified instance types. @@ -102691,6 +106950,9 @@ type DescribeStoreImageTasksInput struct { // // * bucket - Returns task information for tasks that targeted a specific // bucket. For the filter value, specify the bucket name. + // + // When you specify the ImageIds parameter, any filters that you specify are + // ignored. To use the filters, you must remove the ImageIds parameter. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The AMI IDs for which to show progress. Up to 20 AMI IDs can be included @@ -102701,7 +106963,7 @@ type DescribeStoreImageTasksInput struct { // of items, make another request with the token returned in the output. For // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). // - // You cannot specify this parameter and the ImageIDs parameter in the same + // You cannot specify this parameter and the ImageIds parameter in the same // call. MaxResults *int64 `min:"1" type:"integer"` @@ -102821,7 +107083,7 @@ type DescribeSubnetsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * availability-zone - The Availability Zone for the subnet. You can also // use availabilityZone as the filter name. @@ -102916,7 +107178,7 @@ type DescribeSubnetsInput struct { // from the end of the items returned by the previous request. NextToken *string `type:"string"` - // One or more subnet IDs. + // The IDs of the subnets. // // Default: Describes all your subnets. SubnetIds []*string `locationName:"SubnetId" locationNameList:"SubnetId" type:"list"` @@ -105087,13 +109349,13 @@ type DescribeVerifiedAccessEndpointsInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. VerifiedAccessEndpointIds []*string `locationName:"VerifiedAccessEndpointId" locationNameList:"item" type:"list"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. VerifiedAccessGroupId *string `type:"string"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstanceId *string `type:"string"` } @@ -105177,7 +109439,7 @@ type DescribeVerifiedAccessEndpointsOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The ID of the Amazon Web Services Verified Access endpoint. + // Details about the Verified Access endpoints. VerifiedAccessEndpoints []*VerifiedAccessEndpoint `locationName:"verifiedAccessEndpointSet" locationNameList:"item" type:"list"` } @@ -105230,10 +109492,10 @@ type DescribeVerifiedAccessGroupsInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The ID of the Amazon Web Services Verified Access groups. + // The ID of the Verified Access groups. VerifiedAccessGroupIds []*string `locationName:"VerifiedAccessGroupId" locationNameList:"item" type:"list"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstanceId *string `type:"string"` } @@ -105311,7 +109573,7 @@ type DescribeVerifiedAccessGroupsOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The ID of the Verified Access group. + // Details about the Verified Access groups. VerifiedAccessGroups []*VerifiedAccessGroup `locationName:"verifiedAccessGroupSet" locationNameList:"item" type:"list"` } @@ -105364,7 +109626,7 @@ type DescribeVerifiedAccessInstanceLoggingConfigurationsInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The IDs of the Amazon Web Services Verified Access instances. + // The IDs of the Verified Access instances. VerifiedAccessInstanceIds []*string `locationName:"VerifiedAccessInstanceId" locationNameList:"item" type:"list"` } @@ -105432,8 +109694,7 @@ func (s *DescribeVerifiedAccessInstanceLoggingConfigurationsInput) SetVerifiedAc type DescribeVerifiedAccessInstanceLoggingConfigurationsOutput struct { _ struct{} `type:"structure"` - // The current logging configuration for the Amazon Web Services Verified Access - // instances. + // The logging configuration for the Verified Access instances. LoggingConfigurations []*VerifiedAccessInstanceLoggingConfiguration `locationName:"loggingConfigurationSet" locationNameList:"item" type:"list"` // The token to use to retrieve the next page of results. This value is null @@ -105490,7 +109751,7 @@ type DescribeVerifiedAccessInstancesInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The IDs of the Amazon Web Services Verified Access instances. + // The IDs of the Verified Access instances. VerifiedAccessInstanceIds []*string `locationName:"VerifiedAccessInstanceId" locationNameList:"item" type:"list"` } @@ -105562,7 +109823,7 @@ type DescribeVerifiedAccessInstancesOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The IDs of the Amazon Web Services Verified Access instances. + // Details about the Verified Access instances. VerifiedAccessInstances []*VerifiedAccessInstance `locationName:"verifiedAccessInstanceSet" locationNameList:"item" type:"list"` } @@ -105615,7 +109876,7 @@ type DescribeVerifiedAccessTrustProvidersInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The IDs of the Amazon Web Services Verified Access trust providers. + // The IDs of the Verified Access trust providers. VerifiedAccessTrustProviderIds []*string `locationName:"VerifiedAccessTrustProviderId" locationNameList:"item" type:"list"` } @@ -105687,7 +109948,7 @@ type DescribeVerifiedAccessTrustProvidersOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The IDs of the Amazon Web Services Verified Access trust providers. + // Details about the Verified Access trust providers. VerifiedAccessTrustProviders []*VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProviderSet" locationNameList:"item" type:"list"` } @@ -106440,7 +110701,7 @@ type DescribeVpcClassicLinkDnsSupportInput struct { // from the end of the items returned by the previous request. NextToken *string `locationName:"nextToken" min:"1" type:"string"` - // One or more VPC IDs. + // The IDs of the VPCs. VpcIds []*string `locationNameList:"VpcId" type:"list"` } @@ -106546,7 +110807,7 @@ type DescribeVpcClassicLinkInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * is-classic-link-enabled - Whether the VPC is enabled for ClassicLink // (true | false). @@ -106562,7 +110823,7 @@ type DescribeVpcClassicLinkInput struct { // the tag value. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // One or more VPCs for which you want to describe the ClassicLink status. + // The VPCs for which you want to describe the ClassicLink status. VpcIds []*string `locationName:"VpcId" locationNameList:"VpcId" type:"list"` } @@ -106605,7 +110866,7 @@ func (s *DescribeVpcClassicLinkInput) SetVpcIds(v []*string) *DescribeVpcClassic type DescribeVpcClassicLinkOutput struct { _ struct{} `type:"structure"` - // The ClassicLink status of one or more VPCs. + // The ClassicLink status of the VPCs. Vpcs []*VpcClassicLink `locationName:"vpcSet" locationNameList:"item" type:"list"` } @@ -107438,7 +111699,7 @@ type DescribeVpcPeeringConnectionsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. // @@ -107485,7 +111746,7 @@ type DescribeVpcPeeringConnectionsInput struct { // from the end of the items returned by the previous request. NextToken *string `type:"string"` - // One or more VPC peering connection IDs. + // The IDs of the VPC peering connections. // // Default: Describes all your VPC peering connections. VpcPeeringConnectionIds []*string `locationName:"VpcPeeringConnectionId" locationNameList:"item" type:"list"` @@ -107602,7 +111863,7 @@ type DescribeVpcsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify // must exactly match the VPC's CIDR block for information to be returned @@ -107660,7 +111921,7 @@ type DescribeVpcsInput struct { // from the end of the items returned by the previous request. NextToken *string `type:"string"` - // One or more VPC IDs. + // The IDs of the VPCs. // // Default: Describes all your VPCs. VpcIds []*string `locationName:"VpcId" locationNameList:"VpcId" type:"list"` @@ -108428,12 +112689,12 @@ type DetachVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -108500,10 +112761,10 @@ func (s *DetachVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderI type DetachVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // Details about the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // Details about the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -108724,11 +112985,15 @@ func (s DetachVpnGatewayOutput) GoString() string { return s.String() } -// Options for an Amazon Web Services Verified Access device-identity based -// trust provider. +// Describes the options for an Amazon Web Services Verified Access device-identity +// based trust provider. type DeviceOptions struct { _ struct{} `type:"structure"` + // The URL Amazon Web Services Verified Access will use to verify the authenticity + // of the device tokens. + PublicSigningKeyUrl *string `locationName:"publicSigningKeyUrl" type:"string"` + // The ID of the tenant application with the device-identity provider. TenantId *string `locationName:"tenantId" type:"string"` } @@ -108751,6 +113016,12 @@ func (s DeviceOptions) GoString() string { return s.String() } +// SetPublicSigningKeyUrl sets the PublicSigningKeyUrl field's value. +func (s *DeviceOptions) SetPublicSigningKeyUrl(v string) *DeviceOptions { + s.PublicSigningKeyUrl = &v + return s +} + // SetTenantId sets the TenantId field's value. func (s *DeviceOptions) SetTenantId(v string) *DeviceOptions { s.TenantId = &v @@ -108764,7 +113035,7 @@ type DhcpConfiguration struct { // The name of a DHCP option. Key *string `locationName:"key" type:"string"` - // One or more values for the DHCP option. + // The values for the DHCP option. Values []*AttributeValue `locationName:"valueSet" locationNameList:"item" type:"list"` } @@ -108798,11 +113069,11 @@ func (s *DhcpConfiguration) SetValues(v []*AttributeValue) *DhcpConfiguration { return s } -// Describes a set of DHCP options. +// The set of DHCP options. type DhcpOptions struct { _ struct{} `type:"structure"` - // One or more DHCP options in the set. + // The DHCP options in the set. DhcpConfigurations []*DhcpConfiguration `locationName:"dhcpConfigurationSet" locationNameList:"item" type:"list"` // The ID of the set of DHCP options. @@ -109187,13 +113458,12 @@ type DisableFastLaunchInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // Forces the image settings to turn off faster launching for your Windows AMI. - // This parameter overrides any errors that are encountered while cleaning up - // resources in your account. + // Forces the image settings to turn off Windows fast launch for your Windows + // AMI. This parameter overrides any errors that are encountered while cleaning + // up resources in your account. Force *bool `type:"boolean"` - // The ID of the image for which you’re turning off faster launching, and - // removing pre-provisioned snapshots. + // Specify the ID of the image for which to disable Windows fast launch. // // ImageId is a required field ImageId *string `type:"string" required:"true"` @@ -109251,7 +113521,7 @@ func (s *DisableFastLaunchInput) SetImageId(v string) *DisableFastLaunchInput { type DisableFastLaunchOutput struct { _ struct{} `type:"structure"` - // The ID of the image for which faster-launching has been turned off. + // The ID of the image for which Windows fast launch was disabled. ImageId *string `locationName:"imageId" type:"string"` // The launch template that was used to launch Windows instances from pre-provisioned @@ -109259,27 +113529,28 @@ type DisableFastLaunchOutput struct { LaunchTemplate *FastLaunchLaunchTemplateSpecificationResponse `locationName:"launchTemplate" type:"structure"` // The maximum number of instances that Amazon EC2 can launch at the same time - // to create pre-provisioned snapshots for Windows faster launching. + // to create pre-provisioned snapshots for Windows fast launch. MaxParallelLaunches *int64 `locationName:"maxParallelLaunches" type:"integer"` - // The owner of the Windows AMI for which faster launching was turned off. + // The owner of the Windows AMI for which Windows fast launch was disabled. OwnerId *string `locationName:"ownerId" type:"string"` // The pre-provisioning resource type that must be cleaned after turning off - // faster launching for the Windows AMI. Supported values include: snapshot. + // Windows fast launch for the Windows AMI. Supported values include: snapshot. ResourceType *string `locationName:"resourceType" type:"string" enum:"FastLaunchResourceType"` - // Parameters that were used for faster launching for the Windows AMI before - // faster launching was turned off. This informs the clean-up process. + // Parameters that were used for Windows fast launch for the Windows AMI before + // Windows fast launch was disabled. This informs the clean-up process. SnapshotConfiguration *FastLaunchSnapshotConfigurationResponse `locationName:"snapshotConfiguration" type:"structure"` - // The current state of faster launching for the specified Windows AMI. + // The current state of Windows fast launch for the specified Windows AMI. State *string `locationName:"state" type:"string" enum:"FastLaunchStateCode"` - // The reason that the state changed for faster launching for the Windows AMI. + // The reason that the state changed for Windows fast launch for the Windows + // AMI. StateTransitionReason *string `locationName:"stateTransitionReason" type:"string"` - // The time that the state changed for faster launching for the Windows AMI. + // The time that the state changed for Windows fast launch for the Windows AMI. StateTransitionTime *time.Time `locationName:"stateTransitionTime" type:"timestamp"` } @@ -109724,6 +113995,71 @@ func (s *DisableFastSnapshotRestoresOutput) SetUnsuccessful(v []*DisableFastSnap return s } +type DisableImageBlockPublicAccessInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageBlockPublicAccessInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageBlockPublicAccessInput) GoString() string { + return s.String() +} + +// SetDryRun sets the DryRun field's value. +func (s *DisableImageBlockPublicAccessInput) SetDryRun(v bool) *DisableImageBlockPublicAccessInput { + s.DryRun = &v + return s +} + +type DisableImageBlockPublicAccessOutput struct { + _ struct{} `type:"structure"` + + // Returns unblocked if the request succeeds; otherwise, it returns an error. + ImageBlockPublicAccessState *string `locationName:"imageBlockPublicAccessState" type:"string" enum:"ImageBlockPublicAccessDisabledState"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageBlockPublicAccessOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageBlockPublicAccessOutput) GoString() string { + return s.String() +} + +// SetImageBlockPublicAccessState sets the ImageBlockPublicAccessState field's value. +func (s *DisableImageBlockPublicAccessOutput) SetImageBlockPublicAccessState(v string) *DisableImageBlockPublicAccessOutput { + s.ImageBlockPublicAccessState = &v + return s +} + type DisableImageDeprecationInput struct { _ struct{} `type:"structure"` @@ -109813,6 +114149,95 @@ func (s *DisableImageDeprecationOutput) SetReturn(v bool) *DisableImageDeprecati return s } +type DisableImageInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the AMI. + // + // ImageId is a required field + ImageId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisableImageInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisableImageInput"} + if s.ImageId == nil { + invalidParams.Add(request.NewErrParamRequired("ImageId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DisableImageInput) SetDryRun(v bool) *DisableImageInput { + s.DryRun = &v + return s +} + +// SetImageId sets the ImageId field's value. +func (s *DisableImageInput) SetImageId(v string) *DisableImageInput { + s.ImageId = &v + return s +} + +type DisableImageOutput struct { + _ struct{} `type:"structure"` + + // Returns true if the request succeeds; otherwise, it returns an error. + Return *bool `locationName:"return" type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableImageOutput) GoString() string { + return s.String() +} + +// SetReturn sets the Return field's value. +func (s *DisableImageOutput) SetReturn(v bool) *DisableImageOutput { + s.Return = &v + return s +} + type DisableIpamOrganizationAdminAccountInput struct { _ struct{} `type:"structure"` @@ -109969,6 +114394,71 @@ func (s *DisableSerialConsoleAccessOutput) SetSerialConsoleAccessEnabled(v bool) return s } +type DisableSnapshotBlockPublicAccessInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableSnapshotBlockPublicAccessInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableSnapshotBlockPublicAccessInput) GoString() string { + return s.String() +} + +// SetDryRun sets the DryRun field's value. +func (s *DisableSnapshotBlockPublicAccessInput) SetDryRun(v bool) *DisableSnapshotBlockPublicAccessInput { + s.DryRun = &v + return s +} + +type DisableSnapshotBlockPublicAccessOutput struct { + _ struct{} `type:"structure"` + + // Returns unblocked if the request succeeds. + State *string `locationName:"state" type:"string" enum:"SnapshotBlockPublicAccessState"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableSnapshotBlockPublicAccessOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisableSnapshotBlockPublicAccessOutput) GoString() string { + return s.String() +} + +// SetState sets the State field's value. +func (s *DisableSnapshotBlockPublicAccessOutput) SetState(v string) *DisableSnapshotBlockPublicAccessOutput { + s.State = &v + return s +} + type DisableTransitGatewayRouteTablePropagationInput struct { _ struct{} `type:"structure"` @@ -110325,7 +114815,7 @@ func (s *DisableVpcClassicLinkOutput) SetReturn(v bool) *DisableVpcClassicLinkOu type DisassociateAddressInput struct { _ struct{} `type:"structure"` - // [EC2-VPC] The association ID. Required for EC2-VPC. + // The association ID. This parameter is required. AssociationId *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -110334,7 +114824,7 @@ type DisassociateAddressInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // [EC2-Classic] The Elastic IP address. Required for EC2-Classic. + // Deprecated. PublicIp *string `type:"string"` } @@ -110791,6 +115281,109 @@ func (s *DisassociateInstanceEventWindowOutput) SetInstanceEventWindow(v *Instan return s } +type DisassociateIpamByoasnInput struct { + _ struct{} `type:"structure"` + + // A public 2-byte or 4-byte ASN. + // + // Asn is a required field + Asn *string `type:"string" required:"true"` + + // A BYOIP CIDR. + // + // Cidr is a required field + Cidr *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisassociateIpamByoasnInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisassociateIpamByoasnInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisassociateIpamByoasnInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisassociateIpamByoasnInput"} + if s.Asn == nil { + invalidParams.Add(request.NewErrParamRequired("Asn")) + } + if s.Cidr == nil { + invalidParams.Add(request.NewErrParamRequired("Cidr")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAsn sets the Asn field's value. +func (s *DisassociateIpamByoasnInput) SetAsn(v string) *DisassociateIpamByoasnInput { + s.Asn = &v + return s +} + +// SetCidr sets the Cidr field's value. +func (s *DisassociateIpamByoasnInput) SetCidr(v string) *DisassociateIpamByoasnInput { + s.Cidr = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *DisassociateIpamByoasnInput) SetDryRun(v bool) *DisassociateIpamByoasnInput { + s.DryRun = &v + return s +} + +type DisassociateIpamByoasnOutput struct { + _ struct{} `type:"structure"` + + // An ASN and BYOIP CIDR association. + AsnAssociation *AsnAssociation `locationName:"asnAssociation" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisassociateIpamByoasnOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s DisassociateIpamByoasnOutput) GoString() string { + return s.String() +} + +// SetAsnAssociation sets the AsnAssociation field's value. +func (s *DisassociateIpamByoasnOutput) SetAsnAssociation(v *AsnAssociation) *DisassociateIpamByoasnOutput { + s.AsnAssociation = v + return s +} + type DisassociateIpamResourceDiscoveryInput struct { _ struct{} `type:"structure"` @@ -110899,7 +115492,7 @@ type DisassociateNatGatewayAddressInput struct { // seconds. MaxDrainDurationSeconds *int64 `min:"1" type:"integer"` - // The NAT gateway ID. + // The ID of the NAT gateway. // // NatGatewayId is a required field NatGatewayId *string `type:"string" required:"true"` @@ -110972,7 +115565,7 @@ type DisassociateNatGatewayAddressOutput struct { // Information about the NAT gateway IP addresses. NatGatewayAddresses []*NatGatewayAddress `locationName:"natGatewayAddressSet" locationNameList:"item" type:"list"` - // The NAT gateway ID. + // The ID of the NAT gateway. NatGatewayId *string `locationName:"natGatewayId" type:"string"` } @@ -111789,7 +116382,11 @@ type DiskImageDescription struct { // // For information about the import manifest referenced by this API action, // see VM Import Manifest (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html). - ImportManifestUrl *string `locationName:"importManifestUrl" type:"string"` + // + // ImportManifestUrl is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by DiskImageDescription's + // String and GoString methods. + ImportManifestUrl *string `locationName:"importManifestUrl" type:"string" sensitive:"true"` // The size of the disk image, in GiB. Size *int64 `locationName:"size" type:"long"` @@ -112241,19 +116838,18 @@ type EbsBlockDevice struct { // // The following are the supported values for each volume type: // - // * gp3: 3,000-16,000 IOPS + // * gp3: 3,000 - 16,000 IOPS // - // * io1: 100-64,000 IOPS + // * io1: 100 - 64,000 IOPS // - // * io2: 100-64,000 IOPS + // * io2: 100 - 256,000 IOPS // - // For io1 and io2 volumes, we guarantee 64,000 IOPS only for Instances built - // on the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). - // Other instance families guarantee performance up to 32,000 IOPS. + // For io2 volumes, you can achieve up to 256,000 IOPS on instances built on + // the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // On other instances, you can achieve performance up to 32,000 IOPS. // // This parameter is required for io1 and io2 volumes. The default for gp3 volumes - // is 3,000 IOPS. This parameter is not supported for gp2, st1, sc1, or standard - // volumes. + // is 3,000 IOPS. Iops *int64 `locationName:"iops" type:"integer"` // Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed @@ -112267,8 +116863,7 @@ type EbsBlockDevice struct { // The ARN of the Outpost on which the snapshot is stored. // - // This parameter is only supported on BlockDeviceMapping objects called by - // CreateImage (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html). + // This parameter is not supported when using CreateImage (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html). OutpostArn *string `locationName:"outpostArn" type:"string"` // The ID of the snapshot. @@ -112286,20 +116881,21 @@ type EbsBlockDevice struct { // You can specify a volume size that is equal to or larger than the snapshot // size. // - // The following are the supported volumes sizes for each volume type: + // The following are the supported sizes for each volume type: + // + // * gp2 and gp3: 1 - 16,384 GiB // - // * gp2 and gp3:1-16,384 + // * io1: 4 - 16,384 GiB // - // * io1 and io2: 4-16,384 + // * io2: 4 - 65,536 GiB // - // * st1 and sc1: 125-16,384 + // * st1 and sc1: 125 - 16,384 GiB // - // * standard: 1-1,024 + // * standard: 1 - 1024 GiB VolumeSize *int64 `locationName:"volumeSize" type:"integer"` // The volume type. For more information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) - // in the Amazon EC2 User Guide. If the volume type is io1 or io2, you must - // specify the IOPS that the volume supports. + // in the Amazon EC2 User Guide. VolumeType *string `locationName:"volumeType" type:"string" enum:"VolumeType"` } @@ -112440,6 +117036,9 @@ func (s *EbsInfo) SetNvmeSupport(v string) *EbsInfo { type EbsInstanceBlockDevice struct { _ struct{} `type:"structure"` + // The ARN of the Amazon ECS or Fargate task to which the volume is attached. + AssociatedResource *string `locationName:"associatedResource" type:"string"` + // The time stamp when the attachment initiated. AttachTime *time.Time `locationName:"attachTime" type:"timestamp"` @@ -112451,6 +117050,12 @@ type EbsInstanceBlockDevice struct { // The ID of the EBS volume. VolumeId *string `locationName:"volumeId" type:"string"` + + // The ID of the Amazon Web Services account that owns the volume. + // + // This parameter is returned only for volumes that are attached to Fargate + // tasks. + VolumeOwnerId *string `locationName:"volumeOwnerId" type:"string"` } // String returns the string representation. @@ -112471,6 +117076,12 @@ func (s EbsInstanceBlockDevice) GoString() string { return s.String() } +// SetAssociatedResource sets the AssociatedResource field's value. +func (s *EbsInstanceBlockDevice) SetAssociatedResource(v string) *EbsInstanceBlockDevice { + s.AssociatedResource = &v + return s +} + // SetAttachTime sets the AttachTime field's value. func (s *EbsInstanceBlockDevice) SetAttachTime(v time.Time) *EbsInstanceBlockDevice { s.AttachTime = &v @@ -112495,6 +117106,12 @@ func (s *EbsInstanceBlockDevice) SetVolumeId(v string) *EbsInstanceBlockDevice { return s } +// SetVolumeOwnerId sets the VolumeOwnerId field's value. +func (s *EbsInstanceBlockDevice) SetVolumeOwnerId(v string) *EbsInstanceBlockDevice { + s.VolumeOwnerId = &v + return s +} + // Describes information used to set up an EBS volume specified in a block device // mapping. type EbsInstanceBlockDeviceSpecification struct { @@ -112620,6 +117237,176 @@ func (s *EbsOptimizedInfo) SetMaximumThroughputInMBps(v float64) *EbsOptimizedIn return s } +// The EC2 Instance Connect Endpoint. +type Ec2InstanceConnectEndpoint struct { + _ struct{} `type:"structure"` + + // The Availability Zone of the EC2 Instance Connect Endpoint. + AvailabilityZone *string `locationName:"availabilityZone" type:"string"` + + // The date and time that the EC2 Instance Connect Endpoint was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // The DNS name of the EC2 Instance Connect Endpoint. + DnsName *string `locationName:"dnsName" type:"string"` + + FipsDnsName *string `locationName:"fipsDnsName" type:"string"` + + // The Amazon Resource Name (ARN) of the EC2 Instance Connect Endpoint. + InstanceConnectEndpointArn *string `locationName:"instanceConnectEndpointArn" min:"1" type:"string"` + + // The ID of the EC2 Instance Connect Endpoint. + InstanceConnectEndpointId *string `locationName:"instanceConnectEndpointId" type:"string"` + + // The ID of the elastic network interface that Amazon EC2 automatically created + // when creating the EC2 Instance Connect Endpoint. + NetworkInterfaceIds []*string `locationName:"networkInterfaceIdSet" locationNameList:"item" type:"list"` + + // The ID of the Amazon Web Services account that created the EC2 Instance Connect + // Endpoint. + OwnerId *string `locationName:"ownerId" type:"string"` + + // Indicates whether your client's IP address is preserved as the source. The + // value is true or false. + // + // * If true, your client's IP address is used when you connect to a resource. + // + // * If false, the elastic network interface IP address is used when you + // connect to a resource. + // + // Default: true + PreserveClientIp *bool `locationName:"preserveClientIp" type:"boolean"` + + // The security groups associated with the endpoint. If you didn't specify a + // security group, the default security group for your VPC is associated with + // the endpoint. + SecurityGroupIds []*string `locationName:"securityGroupIdSet" locationNameList:"item" type:"list"` + + // The current state of the EC2 Instance Connect Endpoint. + State *string `locationName:"state" type:"string" enum:"Ec2InstanceConnectEndpointState"` + + // The message for the current state of the EC2 Instance Connect Endpoint. Can + // include a failure message. + StateMessage *string `locationName:"stateMessage" type:"string"` + + // The ID of the subnet in which the EC2 Instance Connect Endpoint was created. + SubnetId *string `locationName:"subnetId" type:"string"` + + // The tags assigned to the EC2 Instance Connect Endpoint. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` + + // The ID of the VPC in which the EC2 Instance Connect Endpoint was created. + VpcId *string `locationName:"vpcId" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s Ec2InstanceConnectEndpoint) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s Ec2InstanceConnectEndpoint) GoString() string { + return s.String() +} + +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *Ec2InstanceConnectEndpoint) SetAvailabilityZone(v string) *Ec2InstanceConnectEndpoint { + s.AvailabilityZone = &v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *Ec2InstanceConnectEndpoint) SetCreatedAt(v time.Time) *Ec2InstanceConnectEndpoint { + s.CreatedAt = &v + return s +} + +// SetDnsName sets the DnsName field's value. +func (s *Ec2InstanceConnectEndpoint) SetDnsName(v string) *Ec2InstanceConnectEndpoint { + s.DnsName = &v + return s +} + +// SetFipsDnsName sets the FipsDnsName field's value. +func (s *Ec2InstanceConnectEndpoint) SetFipsDnsName(v string) *Ec2InstanceConnectEndpoint { + s.FipsDnsName = &v + return s +} + +// SetInstanceConnectEndpointArn sets the InstanceConnectEndpointArn field's value. +func (s *Ec2InstanceConnectEndpoint) SetInstanceConnectEndpointArn(v string) *Ec2InstanceConnectEndpoint { + s.InstanceConnectEndpointArn = &v + return s +} + +// SetInstanceConnectEndpointId sets the InstanceConnectEndpointId field's value. +func (s *Ec2InstanceConnectEndpoint) SetInstanceConnectEndpointId(v string) *Ec2InstanceConnectEndpoint { + s.InstanceConnectEndpointId = &v + return s +} + +// SetNetworkInterfaceIds sets the NetworkInterfaceIds field's value. +func (s *Ec2InstanceConnectEndpoint) SetNetworkInterfaceIds(v []*string) *Ec2InstanceConnectEndpoint { + s.NetworkInterfaceIds = v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *Ec2InstanceConnectEndpoint) SetOwnerId(v string) *Ec2InstanceConnectEndpoint { + s.OwnerId = &v + return s +} + +// SetPreserveClientIp sets the PreserveClientIp field's value. +func (s *Ec2InstanceConnectEndpoint) SetPreserveClientIp(v bool) *Ec2InstanceConnectEndpoint { + s.PreserveClientIp = &v + return s +} + +// SetSecurityGroupIds sets the SecurityGroupIds field's value. +func (s *Ec2InstanceConnectEndpoint) SetSecurityGroupIds(v []*string) *Ec2InstanceConnectEndpoint { + s.SecurityGroupIds = v + return s +} + +// SetState sets the State field's value. +func (s *Ec2InstanceConnectEndpoint) SetState(v string) *Ec2InstanceConnectEndpoint { + s.State = &v + return s +} + +// SetStateMessage sets the StateMessage field's value. +func (s *Ec2InstanceConnectEndpoint) SetStateMessage(v string) *Ec2InstanceConnectEndpoint { + s.StateMessage = &v + return s +} + +// SetSubnetId sets the SubnetId field's value. +func (s *Ec2InstanceConnectEndpoint) SetSubnetId(v string) *Ec2InstanceConnectEndpoint { + s.SubnetId = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *Ec2InstanceConnectEndpoint) SetTags(v []*Tag) *Ec2InstanceConnectEndpoint { + s.Tags = v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *Ec2InstanceConnectEndpoint) SetVpcId(v string) *Ec2InstanceConnectEndpoint { + s.VpcId = &v + return s +} + // Describes the Elastic Fabric Adapters for the instance type. type EfaInfo struct { _ struct{} `type:"structure"` @@ -113136,8 +117923,50 @@ func (s *EnaSrdSpecification) SetEnaSrdUdpSpecification(v *EnaSrdUdpSpecificatio return s } +// Launch instances with ENA Express settings configured from your launch template. +type EnaSrdSpecificationRequest struct { + _ struct{} `type:"structure"` + + // Specifies whether ENA Express is enabled for the network interface when you + // launch an instance from your launch template. + EnaSrdEnabled *bool `type:"boolean"` + + // Contains ENA Express settings for UDP network traffic in your launch template. + EnaSrdUdpSpecification *EnaSrdUdpSpecificationRequest `type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnaSrdSpecificationRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnaSrdSpecificationRequest) GoString() string { + return s.String() +} + +// SetEnaSrdEnabled sets the EnaSrdEnabled field's value. +func (s *EnaSrdSpecificationRequest) SetEnaSrdEnabled(v bool) *EnaSrdSpecificationRequest { + s.EnaSrdEnabled = &v + return s +} + +// SetEnaSrdUdpSpecification sets the EnaSrdUdpSpecification field's value. +func (s *EnaSrdSpecificationRequest) SetEnaSrdUdpSpecification(v *EnaSrdUdpSpecificationRequest) *EnaSrdSpecificationRequest { + s.EnaSrdUdpSpecification = v + return s +} + // ENA Express is compatible with both TCP and UDP transport protocols. When -// it’s enabled, TCP traffic automatically uses it. However, some UDP-based +// it's enabled, TCP traffic automatically uses it. However, some UDP-based // applications are designed to handle network packets that are out of order, // without a need for retransmission, such as live video broadcasting or other // near-real-time applications. For UDP traffic, you can specify whether to @@ -113145,8 +117974,8 @@ func (s *EnaSrdSpecification) SetEnaSrdUdpSpecification(v *EnaSrdUdpSpecificatio type EnaSrdUdpSpecification struct { _ struct{} `type:"structure"` - // Indicates whether UDP traffic uses ENA Express. To specify this setting, - // you must first enable ENA Express. + // Indicates whether UDP traffic to and from the instance uses ENA Express. + // To specify this setting, you must first enable ENA Express. EnaSrdUdpEnabled *bool `type:"boolean"` } @@ -113174,6 +118003,41 @@ func (s *EnaSrdUdpSpecification) SetEnaSrdUdpEnabled(v bool) *EnaSrdUdpSpecifica return s } +// Configures ENA Express for UDP network traffic from your launch template. +type EnaSrdUdpSpecificationRequest struct { + _ struct{} `type:"structure"` + + // Indicates whether UDP traffic uses ENA Express for your instance. To ensure + // that UDP traffic can use ENA Express when you launch an instance, you must + // also set EnaSrdEnabled in the EnaSrdSpecificationRequest to true in your + // launch template. + EnaSrdUdpEnabled *bool `type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnaSrdUdpSpecificationRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnaSrdUdpSpecificationRequest) GoString() string { + return s.String() +} + +// SetEnaSrdUdpEnabled sets the EnaSrdUdpEnabled field's value. +func (s *EnaSrdUdpSpecificationRequest) SetEnaSrdUdpEnabled(v bool) *EnaSrdUdpSpecificationRequest { + s.EnaSrdUdpEnabled = &v + return s +} + type EnableAddressTransferInput struct { _ struct{} `type:"structure"` @@ -113454,7 +118318,7 @@ type EnableFastLaunchInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the image for which you’re enabling faster launching. + // Specify the ID of the image for which to enable Windows fast launch. // // ImageId is a required field ImageId *string `type:"string" required:"true"` @@ -113465,17 +118329,17 @@ type EnableFastLaunchInput struct { LaunchTemplate *FastLaunchLaunchTemplateSpecificationRequest `type:"structure"` // The maximum number of instances that Amazon EC2 can launch at the same time - // to create pre-provisioned snapshots for Windows faster launching. Value must - // be 6 or greater. + // to create pre-provisioned snapshots for Windows fast launch. Value must be + // 6 or greater. MaxParallelLaunches *int64 `type:"integer"` - // The type of resource to use for pre-provisioning the Windows AMI for faster - // launching. Supported values include: snapshot, which is the default value. + // The type of resource to use for pre-provisioning the AMI for Windows fast + // launch. Supported values include: snapshot, which is the default value. ResourceType *string `type:"string"` // Configuration settings for creating and managing the snapshots that are used - // for pre-provisioning the Windows AMI for faster launching. The associated - // ResourceType must be snapshot. + // for pre-provisioning the AMI for Windows fast launch. The associated ResourceType + // must be snapshot. SnapshotConfiguration *FastLaunchSnapshotConfigurationRequest `type:"structure"` } @@ -113554,8 +118418,7 @@ func (s *EnableFastLaunchInput) SetSnapshotConfiguration(v *FastLaunchSnapshotCo type EnableFastLaunchOutput struct { _ struct{} `type:"structure"` - // The image ID that identifies the Windows AMI for which faster launching was - // enabled. + // The image ID that identifies the AMI for which Windows fast launch was enabled. ImageId *string `locationName:"imageId" type:"string"` // The launch template that is used when launching Windows instances from pre-provisioned @@ -113563,14 +118426,14 @@ type EnableFastLaunchOutput struct { LaunchTemplate *FastLaunchLaunchTemplateSpecificationResponse `locationName:"launchTemplate" type:"structure"` // The maximum number of instances that Amazon EC2 can launch at the same time - // to create pre-provisioned snapshots for Windows faster launching. + // to create pre-provisioned snapshots for Windows fast launch. MaxParallelLaunches *int64 `locationName:"maxParallelLaunches" type:"integer"` - // The owner ID for the Windows AMI for which faster launching was enabled. + // The owner ID for the AMI for which Windows fast launch was enabled. OwnerId *string `locationName:"ownerId" type:"string"` - // The type of resource that was defined for pre-provisioning the Windows AMI - // for faster launching. + // The type of resource that was defined for pre-provisioning the AMI for Windows + // fast launch. ResourceType *string `locationName:"resourceType" type:"string" enum:"FastLaunchResourceType"` // Settings to create and manage the pre-provisioned snapshots that Amazon EC2 @@ -113578,13 +118441,13 @@ type EnableFastLaunchOutput struct { // when the associated resourceType is snapshot. SnapshotConfiguration *FastLaunchSnapshotConfigurationResponse `locationName:"snapshotConfiguration" type:"structure"` - // The current state of faster launching for the specified Windows AMI. + // The current state of Windows fast launch for the specified AMI. State *string `locationName:"state" type:"string" enum:"FastLaunchStateCode"` - // The reason that the state changed for faster launching for the Windows AMI. + // The reason that the state changed for Windows fast launch for the AMI. StateTransitionReason *string `locationName:"stateTransitionReason" type:"string"` - // The time that the state changed for faster launching for the Windows AMI. + // The time that the state changed for Windows fast launch for the AMI. StateTransitionTime *time.Time `locationName:"stateTransitionTime" type:"timestamp"` } @@ -114031,6 +118894,98 @@ func (s *EnableFastSnapshotRestoresOutput) SetUnsuccessful(v []*EnableFastSnapsh return s } +type EnableImageBlockPublicAccessInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // Specify block-new-sharing to enable block public access for AMIs at the account + // level in the specified Region. This will block any attempt to publicly share + // your AMIs in the specified Region. + // + // ImageBlockPublicAccessState is a required field + ImageBlockPublicAccessState *string `type:"string" required:"true" enum:"ImageBlockPublicAccessEnabledState"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageBlockPublicAccessInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageBlockPublicAccessInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *EnableImageBlockPublicAccessInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EnableImageBlockPublicAccessInput"} + if s.ImageBlockPublicAccessState == nil { + invalidParams.Add(request.NewErrParamRequired("ImageBlockPublicAccessState")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *EnableImageBlockPublicAccessInput) SetDryRun(v bool) *EnableImageBlockPublicAccessInput { + s.DryRun = &v + return s +} + +// SetImageBlockPublicAccessState sets the ImageBlockPublicAccessState field's value. +func (s *EnableImageBlockPublicAccessInput) SetImageBlockPublicAccessState(v string) *EnableImageBlockPublicAccessInput { + s.ImageBlockPublicAccessState = &v + return s +} + +type EnableImageBlockPublicAccessOutput struct { + _ struct{} `type:"structure"` + + // Returns block-new-sharing if the request succeeds; otherwise, it returns + // an error. + ImageBlockPublicAccessState *string `locationName:"imageBlockPublicAccessState" type:"string" enum:"ImageBlockPublicAccessEnabledState"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageBlockPublicAccessOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageBlockPublicAccessOutput) GoString() string { + return s.String() +} + +// SetImageBlockPublicAccessState sets the ImageBlockPublicAccessState field's value. +func (s *EnableImageBlockPublicAccessOutput) SetImageBlockPublicAccessState(v string) *EnableImageBlockPublicAccessOutput { + s.ImageBlockPublicAccessState = &v + return s +} + type EnableImageDeprecationInput struct { _ struct{} `type:"structure"` @@ -114140,6 +119095,95 @@ func (s *EnableImageDeprecationOutput) SetReturn(v bool) *EnableImageDeprecation return s } +type EnableImageInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the AMI. + // + // ImageId is a required field + ImageId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *EnableImageInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EnableImageInput"} + if s.ImageId == nil { + invalidParams.Add(request.NewErrParamRequired("ImageId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *EnableImageInput) SetDryRun(v bool) *EnableImageInput { + s.DryRun = &v + return s +} + +// SetImageId sets the ImageId field's value. +func (s *EnableImageInput) SetImageId(v string) *EnableImageInput { + s.ImageId = &v + return s +} + +type EnableImageOutput struct { + _ struct{} `type:"structure"` + + // Returns true if the request succeeds; otherwise, it returns an error. + Return *bool `locationName:"return" type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableImageOutput) GoString() string { + return s.String() +} + +// SetReturn sets the Return field's value. +func (s *EnableImageOutput) SetReturn(v bool) *EnableImageOutput { + s.Return = &v + return s +} + type EnableIpamOrganizationAdminAccountInput struct { _ struct{} `type:"structure"` @@ -114361,6 +119405,114 @@ func (s *EnableSerialConsoleAccessOutput) SetSerialConsoleAccessEnabled(v bool) return s } +type EnableSnapshotBlockPublicAccessInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The mode in which to enable block public access for snapshots for the Region. + // Specify one of the following values: + // + // * block-all-sharing - Prevents all public sharing of snapshots in the + // Region. Users in the account will no longer be able to request new public + // sharing. Additionally, snapshots that are already publicly shared are + // treated as private and they are no longer publicly available. If you enable + // block public access for snapshots in block-all-sharing mode, it does not + // change the permissions for snapshots that are already publicly shared. + // Instead, it prevents these snapshots from be publicly visible and publicly + // accessible. Therefore, the attributes for these snapshots still indicate + // that they are publicly shared, even though they are not publicly available. + // + // * block-new-sharing - Prevents only new public sharing of snapshots in + // the Region. Users in the account will no longer be able to request new + // public sharing. However, snapshots that are already publicly shared, remain + // publicly available. + // + // unblocked is not a valid value for EnableSnapshotBlockPublicAccess. + // + // State is a required field + State *string `type:"string" required:"true" enum:"SnapshotBlockPublicAccessState"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableSnapshotBlockPublicAccessInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableSnapshotBlockPublicAccessInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *EnableSnapshotBlockPublicAccessInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EnableSnapshotBlockPublicAccessInput"} + if s.State == nil { + invalidParams.Add(request.NewErrParamRequired("State")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *EnableSnapshotBlockPublicAccessInput) SetDryRun(v bool) *EnableSnapshotBlockPublicAccessInput { + s.DryRun = &v + return s +} + +// SetState sets the State field's value. +func (s *EnableSnapshotBlockPublicAccessInput) SetState(v string) *EnableSnapshotBlockPublicAccessInput { + s.State = &v + return s +} + +type EnableSnapshotBlockPublicAccessOutput struct { + _ struct{} `type:"structure"` + + // The state of block public access for snapshots for the account and Region. + // Returns either block-all-sharing or block-new-sharing if the request succeeds. + State *string `locationName:"state" type:"string" enum:"SnapshotBlockPublicAccessState"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableSnapshotBlockPublicAccessOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s EnableSnapshotBlockPublicAccessOutput) GoString() string { + return s.String() +} + +// SetState sets the State field's value. +func (s *EnableSnapshotBlockPublicAccessOutput) SetState(v string) *EnableSnapshotBlockPublicAccessOutput { + s.State = &v + return s +} + type EnableTransitGatewayRouteTablePropagationInput struct { _ struct{} `type:"structure"` @@ -116559,22 +121711,23 @@ func (s *FailedQueuedPurchaseDeletion) SetReservedInstancesId(v string) *FailedQ return s } -// Request to create a launch template for a fast-launch enabled Windows AMI. +// Request to create a launch template for a Windows fast launch enabled AMI. // // Note - You can specify either the LaunchTemplateName or the LaunchTemplateId, // but not both. type FastLaunchLaunchTemplateSpecificationRequest struct { _ struct{} `type:"structure"` - // The ID of the launch template to use for faster launching for a Windows AMI. + // Specify the ID of the launch template that the AMI should use for Windows + // fast launch. LaunchTemplateId *string `type:"string"` - // The name of the launch template to use for faster launching for a Windows - // AMI. + // Specify the name of the launch template that the AMI should use for Windows + // fast launch. LaunchTemplateName *string `type:"string"` - // The version of the launch template to use for faster launching for a Windows - // AMI. + // Specify the version of the launch template that the AMI should use for Windows + // fast launch. // // Version is a required field Version *string `type:"string" required:"true"` @@ -116629,21 +121782,17 @@ func (s *FastLaunchLaunchTemplateSpecificationRequest) SetVersion(v string) *Fas return s } -// Identifies the launch template to use for faster launching of the Windows -// AMI. +// Identifies the launch template that the AMI uses for Windows fast launch. type FastLaunchLaunchTemplateSpecificationResponse struct { _ struct{} `type:"structure"` - // The ID of the launch template for faster launching of the associated Windows - // AMI. + // The ID of the launch template that the AMI uses for Windows fast launch. LaunchTemplateId *string `locationName:"launchTemplateId" type:"string"` - // The name of the launch template for faster launching of the associated Windows - // AMI. + // The name of the launch template that the AMI uses for Windows fast launch. LaunchTemplateName *string `locationName:"launchTemplateName" type:"string"` - // The version of the launch template for faster launching of the associated - // Windows AMI. + // The version of the launch template that the AMI uses for Windows fast launch. Version *string `locationName:"version" type:"string"` } @@ -116684,12 +121833,12 @@ func (s *FastLaunchLaunchTemplateSpecificationResponse) SetVersion(v string) *Fa } // Configuration settings for creating and managing pre-provisioned snapshots -// for a fast-launch enabled Windows AMI. +// for a Windows fast launch enabled AMI. type FastLaunchSnapshotConfigurationRequest struct { _ struct{} `type:"structure"` - // The number of pre-provisioned snapshots to keep on hand for a fast-launch - // enabled Windows AMI. + // The number of pre-provisioned snapshots to keep on hand for a Windows fast + // launch enabled AMI. TargetResourceCount *int64 `type:"integer"` } @@ -116718,12 +121867,12 @@ func (s *FastLaunchSnapshotConfigurationRequest) SetTargetResourceCount(v int64) } // Configuration settings for creating and managing pre-provisioned snapshots -// for a fast-launch enabled Windows AMI. +// for a Windows fast launch enabled Windows AMI. type FastLaunchSnapshotConfigurationResponse struct { _ struct{} `type:"structure"` - // The number of pre-provisioned snapshots requested to keep on hand for a fast-launch - // enabled Windows AMI. + // The number of pre-provisioned snapshots requested to keep on hand for a Windows + // fast launch enabled AMI. TargetResourceCount *int64 `locationName:"targetResourceCount" type:"integer"` } @@ -117610,8 +122759,9 @@ type FleetLaunchTemplateOverrides struct { // The Availability Zone in which to launch the instances. AvailabilityZone *string `locationName:"availabilityZone" type:"string"` - // The ID of the AMI. An AMI is required to launch an instance. The AMI ID must - // be specified here or in the launch template. + // The ID of the AMI. An AMI is required to launch an instance. This parameter + // is only available for fleets of type instant. For fleets of type maintain + // and request, you must specify the AMI ID in the launch template. ImageId *string `locationName:"imageId" type:"string"` // The attributes for the instance types. When you specify instance attributes, @@ -117742,8 +122892,9 @@ type FleetLaunchTemplateOverridesRequest struct { // The Availability Zone in which to launch the instances. AvailabilityZone *string `type:"string"` - // The ID of the AMI. An AMI is required to launch an instance. The AMI ID must - // be specified here or in the launch template. + // The ID of the AMI. An AMI is required to launch an instance. This parameter + // is only available for fleets of type instant. For fleets of type maintain + // and request, you must specify the AMI ID in the launch template. ImageId *string `type:"string"` // The attributes for the instance types. When you specify instance attributes, @@ -119185,12 +124336,9 @@ type GetCapacityReservationUsageInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The maximum number of results to return for the request in a single page. - // The remaining results can be seen by sending another request with the returned - // nextToken value. This value can be between 5 and 500. If maxResults is given - // a larger value than 500, you receive an error. - // - // Valid range: Minimum value of 1. Maximum value of 1000. + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). MaxResults *int64 `min:"1" type:"integer"` // The token to use to retrieve the next page of results. @@ -119470,6 +124618,10 @@ type GetCoipPoolUsageOutput struct { // The ID of the local gateway route table. LocalGatewayRouteTableId *string `locationName:"localGatewayRouteTableId" type:"string"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` } // String returns the string representation. @@ -119508,6 +124660,12 @@ func (s *GetCoipPoolUsageOutput) SetLocalGatewayRouteTableId(v string) *GetCoipP return s } +// SetNextToken sets the NextToken field's value. +func (s *GetCoipPoolUsageOutput) SetNextToken(v string) *GetCoipPoolUsageOutput { + s.NextToken = &v + return s +} + type GetConsoleOutputInput struct { _ struct{} `type:"structure"` @@ -119928,6 +125086,9 @@ type GetEbsEncryptionByDefaultOutput struct { // Indicates whether encryption by default is enabled. EbsEncryptionByDefault *bool `locationName:"ebsEncryptionByDefault" type:"boolean"` + + // Reserved for future use. + SseType *string `locationName:"sseType" type:"string" enum:"SSEType"` } // String returns the string representation. @@ -119954,6 +125115,12 @@ func (s *GetEbsEncryptionByDefaultOutput) SetEbsEncryptionByDefault(v bool) *Get return s } +// SetSseType sets the SseType field's value. +func (s *GetEbsEncryptionByDefaultOutput) SetSseType(v string) *GetEbsEncryptionByDefaultOutput { + s.SseType = &v + return s +} + type GetFlowLogsIntegrationTemplateInput struct { _ struct{} `type:"structure"` @@ -120093,10 +125260,9 @@ type GetGroupsForCapacityReservationInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The maximum number of results to return for the request in a single page. - // The remaining results can be seen by sending another request with the returned - // nextToken value. This value can be between 5 and 500. If maxResults is given - // a larger value than 500, you receive an error. + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). MaxResults *int64 `min:"1" type:"integer"` // The token to use to retrieve the next page of results. @@ -120323,6 +125489,79 @@ func (s *GetHostReservationPurchasePreviewOutput) SetTotalUpfrontPrice(v string) return s } +type GetImageBlockPublicAccessStateInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetImageBlockPublicAccessStateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetImageBlockPublicAccessStateInput) GoString() string { + return s.String() +} + +// SetDryRun sets the DryRun field's value. +func (s *GetImageBlockPublicAccessStateInput) SetDryRun(v bool) *GetImageBlockPublicAccessStateInput { + s.DryRun = &v + return s +} + +type GetImageBlockPublicAccessStateOutput struct { + _ struct{} `type:"structure"` + + // The current state of block public access for AMIs at the account level in + // the specified Amazon Web Services Region. + // + // Possible values: + // + // * block-new-sharing - Any attempt to publicly share your AMIs in the specified + // Region is blocked. + // + // * unblocked - Your AMIs in the specified Region can be publicly shared. + ImageBlockPublicAccessState *string `locationName:"imageBlockPublicAccessState" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetImageBlockPublicAccessStateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetImageBlockPublicAccessStateOutput) GoString() string { + return s.String() +} + +// SetImageBlockPublicAccessState sets the ImageBlockPublicAccessState field's value. +func (s *GetImageBlockPublicAccessStateOutput) SetImageBlockPublicAccessState(v string) *GetImageBlockPublicAccessStateOutput { + s.ImageBlockPublicAccessState = &v + return s +} + type GetInstanceTypesFromInstanceRequirementsInput struct { _ struct{} `type:"structure"` @@ -120886,6 +126125,159 @@ func (s *GetIpamDiscoveredAccountsOutput) SetNextToken(v string) *GetIpamDiscove return s } +type GetIpamDiscoveredPublicAddressesInput struct { + _ struct{} `type:"structure"` + + // The Amazon Web Services Region for the IP address. + // + // AddressRegion is a required field + AddressRegion *string `type:"string" required:"true"` + + // A check for whether you have the required permissions for the action without + // actually making the request and provides an error response. If you have the + // required permissions, the error response is DryRunOperation. Otherwise, it + // is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // Filters. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // An IPAM resource discovery ID. + // + // IpamResourceDiscoveryId is a required field + IpamResourceDiscoveryId *string `type:"string" required:"true"` + + // The maximum number of IPAM discovered public addresses to return in one page + // of results. + MaxResults *int64 `min:"5" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetIpamDiscoveredPublicAddressesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetIpamDiscoveredPublicAddressesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetIpamDiscoveredPublicAddressesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetIpamDiscoveredPublicAddressesInput"} + if s.AddressRegion == nil { + invalidParams.Add(request.NewErrParamRequired("AddressRegion")) + } + if s.IpamResourceDiscoveryId == nil { + invalidParams.Add(request.NewErrParamRequired("IpamResourceDiscoveryId")) + } + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAddressRegion sets the AddressRegion field's value. +func (s *GetIpamDiscoveredPublicAddressesInput) SetAddressRegion(v string) *GetIpamDiscoveredPublicAddressesInput { + s.AddressRegion = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *GetIpamDiscoveredPublicAddressesInput) SetDryRun(v bool) *GetIpamDiscoveredPublicAddressesInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *GetIpamDiscoveredPublicAddressesInput) SetFilters(v []*Filter) *GetIpamDiscoveredPublicAddressesInput { + s.Filters = v + return s +} + +// SetIpamResourceDiscoveryId sets the IpamResourceDiscoveryId field's value. +func (s *GetIpamDiscoveredPublicAddressesInput) SetIpamResourceDiscoveryId(v string) *GetIpamDiscoveredPublicAddressesInput { + s.IpamResourceDiscoveryId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetIpamDiscoveredPublicAddressesInput) SetMaxResults(v int64) *GetIpamDiscoveredPublicAddressesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetIpamDiscoveredPublicAddressesInput) SetNextToken(v string) *GetIpamDiscoveredPublicAddressesInput { + s.NextToken = &v + return s +} + +type GetIpamDiscoveredPublicAddressesOutput struct { + _ struct{} `type:"structure"` + + // IPAM discovered public addresses. + IpamDiscoveredPublicAddresses []*IpamDiscoveredPublicAddress `locationName:"ipamDiscoveredPublicAddressSet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // The oldest successful resource discovery time. + OldestSampleTime *time.Time `locationName:"oldestSampleTime" type:"timestamp"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetIpamDiscoveredPublicAddressesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetIpamDiscoveredPublicAddressesOutput) GoString() string { + return s.String() +} + +// SetIpamDiscoveredPublicAddresses sets the IpamDiscoveredPublicAddresses field's value. +func (s *GetIpamDiscoveredPublicAddressesOutput) SetIpamDiscoveredPublicAddresses(v []*IpamDiscoveredPublicAddress) *GetIpamDiscoveredPublicAddressesOutput { + s.IpamDiscoveredPublicAddresses = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetIpamDiscoveredPublicAddressesOutput) SetNextToken(v string) *GetIpamDiscoveredPublicAddressesOutput { + s.NextToken = &v + return s +} + +// SetOldestSampleTime sets the OldestSampleTime field's value. +func (s *GetIpamDiscoveredPublicAddressesOutput) SetOldestSampleTime(v time.Time) *GetIpamDiscoveredPublicAddressesOutput { + s.OldestSampleTime = &v + return s +} + type GetIpamDiscoveredResourceCidrsInput struct { _ struct{} `type:"structure"` @@ -122110,7 +127502,11 @@ type GetPasswordDataOutput struct { // The password of the instance. Returns an empty string if the password is // not available. - PasswordData *string `locationName:"passwordData" type:"string"` + // + // PasswordData is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by GetPasswordDataOutput's + // String and GoString methods. + PasswordData *string `locationName:"passwordData" type:"string" sensitive:"true"` // The time the data was last updated. Timestamp *time.Time `locationName:"timestamp" type:"timestamp"` @@ -122335,6 +127731,149 @@ func (s *GetReservedInstancesExchangeQuoteOutput) SetValidationFailureReason(v s return s } +type GetSecurityGroupsForVpcInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The filters. If using multiple filters, the results include security groups + // which match all filters. + // + // * group-id: The security group ID. + // + // * description: The security group's description. + // + // * group-name: The security group name. + // + // * owner-id: The security group owner ID. + // + // * primary-vpc-id: The VPC ID in which the security group was created. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The maximum number of items to return for this request. To get the next page + // of items, make another request with the token returned in the output. For + // more information, see Pagination (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html#api-pagination). + MaxResults *int64 `min:"5" type:"integer"` + + // The token returned from a previous paginated request. Pagination continues + // from the end of the items returned by the previous request. + NextToken *string `type:"string"` + + // The VPC ID where the security group can be used. + // + // VpcId is a required field + VpcId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSecurityGroupsForVpcInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSecurityGroupsForVpcInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetSecurityGroupsForVpcInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetSecurityGroupsForVpcInput"} + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + if s.VpcId == nil { + invalidParams.Add(request.NewErrParamRequired("VpcId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *GetSecurityGroupsForVpcInput) SetDryRun(v bool) *GetSecurityGroupsForVpcInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *GetSecurityGroupsForVpcInput) SetFilters(v []*Filter) *GetSecurityGroupsForVpcInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetSecurityGroupsForVpcInput) SetMaxResults(v int64) *GetSecurityGroupsForVpcInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetSecurityGroupsForVpcInput) SetNextToken(v string) *GetSecurityGroupsForVpcInput { + s.NextToken = &v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *GetSecurityGroupsForVpcInput) SetVpcId(v string) *GetSecurityGroupsForVpcInput { + s.VpcId = &v + return s +} + +type GetSecurityGroupsForVpcOutput struct { + _ struct{} `type:"structure"` + + // The token to include in another request to get the next page of items. This + // value is null when there are no more items to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // The security group that can be used by interfaces in the VPC. + SecurityGroupForVpcs []*SecurityGroupForVpc `locationName:"securityGroupForVpcSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSecurityGroupsForVpcOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSecurityGroupsForVpcOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetSecurityGroupsForVpcOutput) SetNextToken(v string) *GetSecurityGroupsForVpcOutput { + s.NextToken = &v + return s +} + +// SetSecurityGroupForVpcs sets the SecurityGroupForVpcs field's value. +func (s *GetSecurityGroupsForVpcOutput) SetSecurityGroupForVpcs(v []*SecurityGroupForVpc) *GetSecurityGroupsForVpcOutput { + s.SecurityGroupForVpcs = v + return s +} + type GetSerialConsoleAccessStatusInput struct { _ struct{} `type:"structure"` @@ -122402,6 +127941,83 @@ func (s *GetSerialConsoleAccessStatusOutput) SetSerialConsoleAccessEnabled(v boo return s } +type GetSnapshotBlockPublicAccessStateInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSnapshotBlockPublicAccessStateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSnapshotBlockPublicAccessStateInput) GoString() string { + return s.String() +} + +// SetDryRun sets the DryRun field's value. +func (s *GetSnapshotBlockPublicAccessStateInput) SetDryRun(v bool) *GetSnapshotBlockPublicAccessStateInput { + s.DryRun = &v + return s +} + +type GetSnapshotBlockPublicAccessStateOutput struct { + _ struct{} `type:"structure"` + + // The current state of block public access for snapshots. Possible values include: + // + // * block-all-sharing - All public sharing of snapshots is blocked. Users + // in the account can't request new public sharing. Additionally, snapshots + // that were already publicly shared are treated as private and are not publicly + // available. + // + // * block-new-sharing - Only new public sharing of snapshots is blocked. + // Users in the account can't request new public sharing. However, snapshots + // that were already publicly shared, remain publicly available. + // + // * unblocked - Public sharing is not blocked. Users can publicly share + // snapshots. + State *string `locationName:"state" type:"string" enum:"SnapshotBlockPublicAccessState"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSnapshotBlockPublicAccessStateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSnapshotBlockPublicAccessStateOutput) GoString() string { + return s.String() +} + +// SetState sets the State field's value. +func (s *GetSnapshotBlockPublicAccessStateOutput) SetState(v string) *GetSnapshotBlockPublicAccessStateOutput { + s.State = &v + return s +} + type GetSpotPlacementScoresInput struct { _ struct{} `type:"structure"` @@ -122451,8 +128067,6 @@ type GetSpotPlacementScoresInput struct { TargetCapacity *int64 `min:"1" type:"integer" required:"true"` // The unit for the target capacity. - // - // Default: units (translates to number of instances) TargetCapacityUnitType *string `type:"string" enum:"TargetCapacityUnitType"` } @@ -123716,7 +129330,7 @@ type GetVerifiedAccessEndpointPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` @@ -123768,7 +129382,7 @@ func (s *GetVerifiedAccessEndpointPolicyInput) SetVerifiedAccessEndpointId(v str type GetVerifiedAccessEndpointPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. @@ -123814,7 +129428,7 @@ type GetVerifiedAccessGroupPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` @@ -123866,7 +129480,7 @@ func (s *GetVerifiedAccessGroupPolicyInput) SetVerifiedAccessGroupId(v string) * type GetVerifiedAccessGroupPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. @@ -124463,14 +130077,14 @@ func (s *GroupIdentifier) SetGroupName(v string) *GroupIdentifier { } // Indicates whether your instance is configured for hibernation. This parameter -// is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). +// is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hibernating-prerequisites.html). // For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon EC2 User Guide. type HibernationOptions struct { _ struct{} `type:"structure"` - // If this parameter is set to true, your instance is enabled for hibernation; - // otherwise, it is not enabled for hibernation. + // If true, your instance is enabled for hibernation; otherwise, it is not enabled + // for hibernation. Configured *bool `locationName:"configured" type:"boolean"` } @@ -124499,13 +130113,22 @@ func (s *HibernationOptions) SetConfigured(v bool) *HibernationOptions { } // Indicates whether your instance is configured for hibernation. This parameter -// is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). +// is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hibernating-prerequisites.html). // For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon EC2 User Guide. type HibernationOptionsRequest struct { _ struct{} `type:"structure"` - // If you set this parameter to true, your instance is enabled for hibernation. + // Set to true to enable your instance for hibernation. + // + // For Spot Instances, if you set Configured to true, either omit the InstanceInterruptionBehavior + // parameter (for SpotMarketOptions (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotMarketOptions.html)), + // or set it to hibernate. When Configured is true: + // + // * If you omit InstanceInterruptionBehavior, it defaults to hibernate. + // + // * If you set InstanceInterruptionBehavior to a value other than hibernate, + // you'll get an error. // // Default: false Configured *bool `type:"boolean"` @@ -124657,6 +130280,9 @@ type Host struct { // Dedicated Host supports a single instance type only. AllowsMultipleInstanceTypes *string `locationName:"allowsMultipleInstanceTypes" type:"string" enum:"AllowsMultipleInstanceTypes"` + // The ID of the Outpost hardware asset on which the Dedicated Host is allocated. + AssetId *string `locationName:"assetId" type:"string"` + // Whether auto-placement is on or off. AutoPlacement *string `locationName:"autoPlacement" type:"string" enum:"AutoPlacement"` @@ -124745,6 +130371,12 @@ func (s *Host) SetAllowsMultipleInstanceTypes(v string) *Host { return s } +// SetAssetId sets the AssetId field's value. +func (s *Host) SetAssetId(v string) *Host { + s.AssetId = &v + return s +} + // SetAutoPlacement sets the AutoPlacement field's value. func (s *Host) SetAutoPlacement(v string) *Host { s.AutoPlacement = &v @@ -125541,7 +131173,7 @@ type Image struct { // Specifies whether enhanced networking with ENA is enabled. EnaSupport *bool `locationName:"enaSupport" type:"boolean"` - // The hypervisor type of the image. + // The hypervisor type of the image. Only xen is supported. ovm is not supported. Hypervisor *string `locationName:"hypervisor" type:"string" enum:"HypervisorType"` // The ID of the AMI. @@ -125602,6 +131234,11 @@ type Image struct { // or an instance store volume. RootDeviceType *string `locationName:"rootDeviceType" type:"string" enum:"DeviceType"` + // The ID of the instance that the AMI was created from if the AMI was created + // using CreateImage (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html). + // This field only appears if the AMI was created using CreateImage. + SourceInstanceId *string `locationName:"sourceInstanceId" type:"string"` + // Specifies whether enhanced networking with the Intel 82599 Virtual Function // interface is enabled. SriovNetSupport *string `locationName:"sriovNetSupport" type:"string"` @@ -125791,6 +131428,12 @@ func (s *Image) SetRootDeviceType(v string) *Image { return s } +// SetSourceInstanceId sets the SourceInstanceId field's value. +func (s *Image) SetSourceInstanceId(v string) *Image { + s.SourceInstanceId = &v + return s +} + // SetSriovNetSupport sets the SriovNetSupport field's value. func (s *Image) SetSriovNetSupport(v string) *Image { s.SriovNetSupport = &v @@ -125853,7 +131496,11 @@ type ImageDiskContainer struct { // The URL to the Amazon S3-based disk image being imported. The URL can either // be a https URL (https://..) or an Amazon S3 URL (s3://..) - Url *string `type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by ImageDiskContainer's + // String and GoString methods. + Url *string `type:"string" sensitive:"true"` // The S3 bucket for the disk image. UserBucket *UserBucket `type:"structure"` @@ -126097,6 +131744,10 @@ type ImportImageInput struct { Architecture *string `type:"string"` // The boot mode of the virtual machine. + // + // The uefi-preferred boot mode isn't supported for importing images. For more + // information, see Boot modes (https://docs.aws.amazon.com/vm-import/latest/userguide/prerequisites.html#vmimport-boot-modes) + // in the VM Import/Export User Guide. BootMode *string `type:"string" enum:"BootModeValues"` // The client-specific data. @@ -126137,9 +131788,7 @@ type ImportImageInput struct { // // * Key ID // - // * Key alias. The alias ARN contains the arn:aws:kms namespace, followed - // by the Region of the key, the Amazon Web Services account ID of the key - // owner, the alias namespace, and then the key alias. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + // * Key alias // // * ARN using key ID. The ID ARN contains the arn:aws:kms namespace, followed // by the Region of the key, the Amazon Web Services account ID of the key @@ -126177,7 +131826,9 @@ type ImportImageInput struct { // in the VM Import/Export User Guide. LicenseType *string `type:"string"` - // The operating system of the virtual machine. + // The operating system of the virtual machine. If you import a VM that is compatible + // with Unified Extensible Firmware Interface (UEFI) using an EBS snapshot, + // you must specify a value for the platform. // // Valid values: Windows | Linux Platform *string `type:"string"` @@ -127300,9 +132951,7 @@ type ImportSnapshotInput struct { // // * Key ID // - // * Key alias. The alias ARN contains the arn:aws:kms namespace, followed - // by the Region of the key, the Amazon Web Services account ID of the key - // owner, the alias namespace, and then the key alias. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + // * Key alias // // * ARN using key ID. The ID ARN contains the arn:aws:kms namespace, followed // by the Region of the key, the Amazon Web Services account ID of the key @@ -127729,6 +133378,10 @@ type InferenceAcceleratorInfo struct { // Describes the Inference accelerators for the instance type. Accelerators []*InferenceDeviceInfo `locationName:"accelerators" type:"list"` + + // The total size of the memory for the inference accelerators for the instance + // type, in MiB. + TotalInferenceMemoryInMiB *int64 `locationName:"totalInferenceMemoryInMiB" type:"integer"` } // String returns the string representation. @@ -127755,6 +133408,12 @@ func (s *InferenceAcceleratorInfo) SetAccelerators(v []*InferenceDeviceInfo) *In return s } +// SetTotalInferenceMemoryInMiB sets the TotalInferenceMemoryInMiB field's value. +func (s *InferenceAcceleratorInfo) SetTotalInferenceMemoryInMiB(v int64) *InferenceAcceleratorInfo { + s.TotalInferenceMemoryInMiB = &v + return s +} + // Describes the Inference accelerators for the instance type. type InferenceDeviceInfo struct { _ struct{} `type:"structure"` @@ -127765,6 +133424,9 @@ type InferenceDeviceInfo struct { // The manufacturer of the Inference accelerator. Manufacturer *string `locationName:"manufacturer" type:"string"` + // Describes the memory available to the inference accelerator. + MemoryInfo *InferenceDeviceMemoryInfo `locationName:"memoryInfo" type:"structure"` + // The name of the Inference accelerator. Name *string `locationName:"name" type:"string"` } @@ -127799,12 +133461,50 @@ func (s *InferenceDeviceInfo) SetManufacturer(v string) *InferenceDeviceInfo { return s } +// SetMemoryInfo sets the MemoryInfo field's value. +func (s *InferenceDeviceInfo) SetMemoryInfo(v *InferenceDeviceMemoryInfo) *InferenceDeviceInfo { + s.MemoryInfo = v + return s +} + // SetName sets the Name field's value. func (s *InferenceDeviceInfo) SetName(v string) *InferenceDeviceInfo { s.Name = &v return s } +// Describes the memory available to the inference accelerator. +type InferenceDeviceMemoryInfo struct { + _ struct{} `type:"structure"` + + // The size of the memory available to the inference accelerator, in MiB. + SizeInMiB *int64 `locationName:"sizeInMiB" type:"integer"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InferenceDeviceMemoryInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InferenceDeviceMemoryInfo) GoString() string { + return s.String() +} + +// SetSizeInMiB sets the SizeInMiB field's value. +func (s *InferenceDeviceMemoryInfo) SetSizeInMiB(v int64) *InferenceDeviceMemoryInfo { + s.SizeInMiB = &v + return s +} + // Describes an instance. type Instance struct { _ struct{} `type:"structure"` @@ -127913,7 +133613,7 @@ type Instance struct { // The monitoring for the instance. Monitoring *Monitoring `locationName:"monitoring" type:"structure"` - // [EC2-VPC] The network interfaces for the instance. + // The network interfaces for the instance. NetworkInterfaces []*InstanceNetworkInterface `locationName:"networkInterfaceSet" locationNameList:"item" type:"list"` // The Amazon Resource Name (ARN) of the Outpost. @@ -127922,7 +133622,8 @@ type Instance struct { // The location where the instance launched, if applicable. Placement *Placement `locationName:"placement" type:"structure"` - // The value is Windows for Windows instances; otherwise blank. + // The platform. This value is windows for Windows instances; otherwise, it + // is empty. Platform *string `locationName:"platform" type:"string" enum:"PlatformValues"` // The platform details value for the instance. For more information, see AMI @@ -127930,14 +133631,14 @@ type Instance struct { // in the Amazon EC2 User Guide. PlatformDetails *string `locationName:"platformDetails" type:"string"` - // (IPv4 only) The private DNS hostname name assigned to the instance. This + // [IPv4 only] The private DNS hostname name assigned to the instance. This // DNS hostname can only be used inside the Amazon EC2 network. This name is // not available until the instance enters the running state. // - // [EC2-VPC] The Amazon-provided DNS server resolves Amazon-provided private - // DNS hostnames if you've enabled DNS resolution and DNS hostnames in your - // VPC. If you are not using the Amazon-provided DNS server in your VPC, your - // custom domain name servers must resolve the hostname as appropriate. + // The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames + // if you've enabled DNS resolution and DNS hostnames in your VPC. If you are + // not using the Amazon-provided DNS server in your VPC, your custom domain + // name servers must resolve the hostname as appropriate. PrivateDnsName *string `locationName:"privateDnsName" type:"string"` // The options for the instance hostname. @@ -127949,9 +133650,9 @@ type Instance struct { // The product codes attached to this instance, if applicable. ProductCodes []*ProductCode `locationName:"productCodes" locationNameList:"item" type:"list"` - // (IPv4 only) The public DNS name assigned to the instance. This name is not - // available until the instance enters the running state. For EC2-VPC, this - // name is only available if you've enabled DNS hostnames for your VPC. + // [IPv4 only] The public DNS name assigned to the instance. This name is not + // available until the instance enters the running state. This name is only + // available if you've enabled DNS hostnames for your VPC. PublicDnsName *string `locationName:"dnsName" type:"string"` // The public IPv4 address, or the Carrier IP address assigned to the instance, @@ -127993,7 +133694,7 @@ type Instance struct { // The reason for the most recent state transition. This might be an empty string. StateTransitionReason *string `locationName:"reason" type:"string"` - // [EC2-VPC] The ID of the subnet in which the instance is running. + // The ID of the subnet in which the instance is running. SubnetId *string `locationName:"subnetId" type:"string"` // Any tags assigned to the instance. @@ -128015,7 +133716,7 @@ type Instance struct { // The virtualization type of the instance. VirtualizationType *string `locationName:"virtualizationType" type:"string" enum:"VirtualizationType"` - // [EC2-VPC] The ID of the VPC in which the instance is running. + // The ID of the VPC in which the instance is running. VpcId *string `locationName:"vpcId" type:"string"` } @@ -128379,6 +134080,96 @@ func (s *Instance) SetVpcId(v string) *Instance { return s } +// ENA Express uses Amazon Web Services Scalable Reliable Datagram (SRD) technology +// to increase the maximum bandwidth used per stream and minimize tail latency +// of network traffic between EC2 instances. With ENA Express, you can communicate +// between two EC2 instances in the same subnet within the same account, or +// in different accounts. Both sending and receiving instances must have ENA +// Express enabled. +// +// To improve the reliability of network packet delivery, ENA Express reorders +// network packets on the receiving end by default. However, some UDP-based +// applications are designed to handle network packets that are out of order +// to reduce the overhead for packet delivery at the network layer. When ENA +// Express is enabled, you can specify whether UDP network traffic uses it. +type InstanceAttachmentEnaSrdSpecification struct { + _ struct{} `type:"structure"` + + // Indicates whether ENA Express is enabled for the network interface. + EnaSrdEnabled *bool `locationName:"enaSrdEnabled" type:"boolean"` + + // Configures ENA Express for UDP network traffic. + EnaSrdUdpSpecification *InstanceAttachmentEnaSrdUdpSpecification `locationName:"enaSrdUdpSpecification" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InstanceAttachmentEnaSrdSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InstanceAttachmentEnaSrdSpecification) GoString() string { + return s.String() +} + +// SetEnaSrdEnabled sets the EnaSrdEnabled field's value. +func (s *InstanceAttachmentEnaSrdSpecification) SetEnaSrdEnabled(v bool) *InstanceAttachmentEnaSrdSpecification { + s.EnaSrdEnabled = &v + return s +} + +// SetEnaSrdUdpSpecification sets the EnaSrdUdpSpecification field's value. +func (s *InstanceAttachmentEnaSrdSpecification) SetEnaSrdUdpSpecification(v *InstanceAttachmentEnaSrdUdpSpecification) *InstanceAttachmentEnaSrdSpecification { + s.EnaSrdUdpSpecification = v + return s +} + +// ENA Express is compatible with both TCP and UDP transport protocols. When +// it's enabled, TCP traffic automatically uses it. However, some UDP-based +// applications are designed to handle network packets that are out of order, +// without a need for retransmission, such as live video broadcasting or other +// near-real-time applications. For UDP traffic, you can specify whether to +// use ENA Express, based on your application environment needs. +type InstanceAttachmentEnaSrdUdpSpecification struct { + _ struct{} `type:"structure"` + + // Indicates whether UDP traffic to and from the instance uses ENA Express. + // To specify this setting, you must first enable ENA Express. + EnaSrdUdpEnabled *bool `locationName:"enaSrdUdpEnabled" type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InstanceAttachmentEnaSrdUdpSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InstanceAttachmentEnaSrdUdpSpecification) GoString() string { + return s.String() +} + +// SetEnaSrdUdpEnabled sets the EnaSrdUdpEnabled field's value. +func (s *InstanceAttachmentEnaSrdUdpSpecification) SetEnaSrdUdpEnabled(v bool) *InstanceAttachmentEnaSrdUdpSpecification { + s.EnaSrdUdpEnabled = &v + return s +} + // Describes a block device mapping. type InstanceBlockDeviceMapping struct { _ struct{} `type:"structure"` @@ -129202,6 +134993,13 @@ type InstanceIpv6Address struct { // The IPv6 address. Ipv6Address *string `locationName:"ipv6Address" type:"string"` + + // Determines if an IPv6 address associated with a network interface is the + // primary IPv6 address. When you enable an IPv6 GUA address to be a primary + // IPv6, the first IPv6 GUA will be made the primary IPv6 address until the + // instance is terminated or the network interface is detached. For more information, + // see RunInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html). + IsPrimaryIpv6 *bool `locationName:"isPrimaryIpv6" type:"boolean"` } // String returns the string representation. @@ -129228,6 +135026,12 @@ func (s *InstanceIpv6Address) SetIpv6Address(v string) *InstanceIpv6Address { return s } +// SetIsPrimaryIpv6 sets the IsPrimaryIpv6 field's value. +func (s *InstanceIpv6Address) SetIsPrimaryIpv6(v bool) *InstanceIpv6Address { + s.IsPrimaryIpv6 = &v + return s +} + // Describes an IPv6 address. type InstanceIpv6AddressRequest struct { _ struct{} `type:"structure"` @@ -129420,22 +135224,21 @@ type InstanceMetadataOptionsRequest struct { // Possible values: Integers from 1 to 64 HttpPutResponseHopLimit *int64 `type:"integer"` - // IMDSv2 uses token-backed sessions. Set the use of HTTP tokens to optional - // (in other words, set the use of IMDSv2 to optional) or required (in other - // words, set the use of IMDSv2 to required). + // Indicates whether IMDSv2 is required. // - // * optional - When IMDSv2 is optional, you can choose to retrieve instance - // metadata with or without a session token in your request. If you retrieve - // the IAM role credentials without a token, the IMDSv1 role credentials - // are returned. If you retrieve the IAM role credentials using a valid session - // token, the IMDSv2 role credentials are returned. + // * optional - IMDSv2 is optional. You can choose whether to send a session + // token in your instance metadata retrieval requests. If you retrieve IAM + // role credentials without a session token, you receive the IMDSv1 role + // credentials. If you retrieve IAM role credentials using a valid session + // token, you receive the IMDSv2 role credentials. // - // * required - When IMDSv2 is required, you must send a session token with - // any instance metadata retrieval requests. In this state, retrieving the + // * required - IMDSv2 is required. You must send a session token in your + // instance metadata retrieval requests. With this option, retrieving the // IAM role credentials always returns IMDSv2 credentials; IMDSv1 credentials // are not available. // - // Default: optional + // Default: If the value of ImdsSupport for the Amazon Machine Image (AMI) for + // your instance is v2.0, the default is required. HttpTokens *string `type:"string" enum:"HttpTokensState"` // Set to enabled to allow access to instance tags from the instance metadata. @@ -129517,22 +135320,18 @@ type InstanceMetadataOptionsResponse struct { // Possible values: Integers from 1 to 64 HttpPutResponseHopLimit *int64 `locationName:"httpPutResponseHopLimit" type:"integer"` - // IMDSv2 uses token-backed sessions. Indicates whether the use of HTTP tokens - // is optional (in other words, indicates whether the use of IMDSv2 is optional) - // or required (in other words, indicates whether the use of IMDSv2 is required). + // Indicates whether IMDSv2 is required. // - // * optional - When IMDSv2 is optional, you can choose to retrieve instance - // metadata with or without a session token in your request. If you retrieve - // the IAM role credentials without a token, the IMDSv1 role credentials - // are returned. If you retrieve the IAM role credentials using a valid session - // token, the IMDSv2 role credentials are returned. + // * optional - IMDSv2 is optional. You can choose whether to send a session + // token in your instance metadata retrieval requests. If you retrieve IAM + // role credentials without a session token, you receive the IMDSv1 role + // credentials. If you retrieve IAM role credentials using a valid session + // token, you receive the IMDSv2 role credentials. // - // * required - When IMDSv2 is required, you must send a session token with - // any instance metadata retrieval requests. In this state, retrieving the + // * required - IMDSv2 is required. You must send a session token in your + // instance metadata retrieval requests. With this option, retrieving the // IAM role credentials always returns IMDSv2 credentials; IMDSv1 credentials // are not available. - // - // Default: optional HttpTokens *string `locationName:"httpTokens" type:"string" enum:"HttpTokensState"` // Indicates whether access to instance tags from the instance metadata is enabled @@ -129655,6 +135454,12 @@ type InstanceNetworkInterface struct { // The network interface attachment. Attachment *InstanceNetworkInterfaceAttachment `locationName:"attachment" type:"structure"` + // A security group connection tracking configuration that enables you to set + // the timeout for connection tracking on an Elastic network interface. For + // more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) + // in the Amazon Elastic Compute Cloud User Guide. + ConnectionTrackingConfiguration *ConnectionTrackingSpecificationResponse `locationName:"connectionTrackingConfiguration" type:"structure"` + // The description. Description *string `locationName:"description" type:"string"` @@ -129736,6 +135541,12 @@ func (s *InstanceNetworkInterface) SetAttachment(v *InstanceNetworkInterfaceAtta return s } +// SetConnectionTrackingConfiguration sets the ConnectionTrackingConfiguration field's value. +func (s *InstanceNetworkInterface) SetConnectionTrackingConfiguration(v *ConnectionTrackingSpecificationResponse) *InstanceNetworkInterface { + s.ConnectionTrackingConfiguration = v + return s +} + // SetDescription sets the Description field's value. func (s *InstanceNetworkInterface) SetDescription(v string) *InstanceNetworkInterface { s.Description = &v @@ -129916,6 +135727,10 @@ type InstanceNetworkInterfaceAttachment struct { // The index of the device on the instance for the network interface attachment. DeviceIndex *int64 `locationName:"deviceIndex" type:"integer"` + // Contains the ENA Express settings for the network interface that's attached + // to the instance. + EnaSrdSpecification *InstanceAttachmentEnaSrdSpecification `locationName:"enaSrdSpecification" type:"structure"` + // The index of the network card. NetworkCardIndex *int64 `locationName:"networkCardIndex" type:"integer"` @@ -129965,6 +135780,12 @@ func (s *InstanceNetworkInterfaceAttachment) SetDeviceIndex(v int64) *InstanceNe return s } +// SetEnaSrdSpecification sets the EnaSrdSpecification field's value. +func (s *InstanceNetworkInterfaceAttachment) SetEnaSrdSpecification(v *InstanceAttachmentEnaSrdSpecification) *InstanceNetworkInterfaceAttachment { + s.EnaSrdSpecification = v + return s +} + // SetNetworkCardIndex sets the NetworkCardIndex field's value. func (s *InstanceNetworkInterfaceAttachment) SetNetworkCardIndex(v int64) *InstanceNetworkInterfaceAttachment { s.NetworkCardIndex = &v @@ -129994,8 +135815,19 @@ type InstanceNetworkInterfaceSpecification struct { // for eth0, and can only be assigned to a new network interface, not an existing // one. You cannot specify more than one network interface in the request. If // launching into a default subnet, the default value is true. + // + // Starting on February 1, 2024, Amazon Web Services will charge for all public + // IPv4 addresses, including public IPv4 addresses associated with running instances + // and Elastic IP addresses. For more information, see the Public IPv4 Address + // tab on the Amazon VPC pricing page (http://aws.amazon.com/vpc/pricing/). AssociatePublicIpAddress *bool `locationName:"associatePublicIpAddress" type:"boolean"` + // A security group connection tracking specification that enables you to set + // the timeout for connection tracking on an Elastic network interface. For + // more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) + // in the Amazon Elastic Compute Cloud User Guide. + ConnectionTrackingSpecification *ConnectionTrackingSpecificationRequest `type:"structure"` + // If set to true, the interface is deleted when the instance is terminated. // You can specify true only if creating a new network interface when launching // an instance. @@ -130012,6 +135844,10 @@ type InstanceNetworkInterfaceSpecification struct { // the device index. DeviceIndex *int64 `locationName:"deviceIndex" type:"integer"` + // Specifies the ENA Express settings for the network interface that's attached + // to the instance. + EnaSrdSpecification *EnaSrdSpecificationRequest `type:"structure"` + // The IDs of the security groups for the network interface. Applies only if // creating a network interface when launching an instance. Groups []*string `locationName:"SecurityGroupId" locationNameList:"SecurityGroupId" type:"list"` @@ -130066,6 +135902,13 @@ type InstanceNetworkInterfaceSpecification struct { // specify a network interface ID in a launch specification. NetworkInterfaceId *string `locationName:"networkInterfaceId" type:"string"` + // The primary IPv6 address of the network interface. When you enable an IPv6 + // GUA address to be a primary IPv6, the first IPv6 GUA will be made the primary + // IPv6 address until the instance is terminated or the network interface is + // detached. For more information about primary IPv6 addresses, see RunInstances + // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html). + PrimaryIpv6 *bool `type:"boolean"` + // The private IPv4 address of the network interface. Applies only if creating // a network interface when launching an instance. You cannot specify this option // if you're launching more than one instance in a RunInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) @@ -130120,6 +135963,12 @@ func (s *InstanceNetworkInterfaceSpecification) SetAssociatePublicIpAddress(v bo return s } +// SetConnectionTrackingSpecification sets the ConnectionTrackingSpecification field's value. +func (s *InstanceNetworkInterfaceSpecification) SetConnectionTrackingSpecification(v *ConnectionTrackingSpecificationRequest) *InstanceNetworkInterfaceSpecification { + s.ConnectionTrackingSpecification = v + return s +} + // SetDeleteOnTermination sets the DeleteOnTermination field's value. func (s *InstanceNetworkInterfaceSpecification) SetDeleteOnTermination(v bool) *InstanceNetworkInterfaceSpecification { s.DeleteOnTermination = &v @@ -130138,6 +135987,12 @@ func (s *InstanceNetworkInterfaceSpecification) SetDeviceIndex(v int64) *Instanc return s } +// SetEnaSrdSpecification sets the EnaSrdSpecification field's value. +func (s *InstanceNetworkInterfaceSpecification) SetEnaSrdSpecification(v *EnaSrdSpecificationRequest) *InstanceNetworkInterfaceSpecification { + s.EnaSrdSpecification = v + return s +} + // SetGroups sets the Groups field's value. func (s *InstanceNetworkInterfaceSpecification) SetGroups(v []*string) *InstanceNetworkInterfaceSpecification { s.Groups = v @@ -130198,6 +136053,12 @@ func (s *InstanceNetworkInterfaceSpecification) SetNetworkInterfaceId(v string) return s } +// SetPrimaryIpv6 sets the PrimaryIpv6 field's value. +func (s *InstanceNetworkInterfaceSpecification) SetPrimaryIpv6(v bool) *InstanceNetworkInterfaceSpecification { + s.PrimaryIpv6 = &v + return s +} + // SetPrivateIpAddress sets the PrivateIpAddress field's value. func (s *InstanceNetworkInterfaceSpecification) SetPrivateIpAddress(v string) *InstanceNetworkInterfaceSpecification { s.PrivateIpAddress = &v @@ -130285,6 +136146,9 @@ func (s *InstancePrivateIpAddress) SetPrivateIpAddress(v string) *InstancePrivat // The attributes for the instance types. When you specify instance attributes, // Amazon EC2 will identify instance types with these attributes. // +// You must specify VCpuCount and MemoryMiB. All other attributes are optional. +// Any unspecified optional attribute is set to its default. +// // When you specify multiple attributes, you get instance types that satisfy // all of the specified attributes. If you specify multiple values for an attribute, // you get instance types that satisfy any of the specified values. @@ -130299,11 +136163,18 @@ func (s *InstancePrivateIpAddress) SetPrivateIpAddress(v string) *InstancePrivat // - ExcludedInstanceTypes - The instance types to exclude from the list, // even if they match your specified attributes. // -// You must specify VCpuCount and MemoryMiB. All other attributes are optional. -// Any unspecified optional attribute is set to its default. +// If you specify InstanceRequirements, you can't specify InstanceType. // -// For more information, see Attribute-based instance type selection for EC2 -// Fleet (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-attribute-based-instance-type-selection.html), +// Attribute-based instance type selection is only supported when using Auto +// Scaling groups, EC2 Fleet, and Spot Fleet to launch instances. If you plan +// to use the launch template in the launch instance wizard (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html) +// or with the RunInstances API (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html), +// you can't specify InstanceRequirements. +// +// For more information, see Create a mixed instances group using attribute-based +// instance type selection (https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-mixed-instances-group-attribute-based-instance-type-selection.html) +// in the Amazon EC2 Auto Scaling User Guide, and also Attribute-based instance +// type selection for EC2 Fleet (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-attribute-based-instance-type-selection.html), // Attribute-based instance type selection for Spot Fleet (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-attribute-based-instance-type-selection.html), // and Spot placement score (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-placement-score.html) // in the Amazon EC2 User Guide. @@ -130320,11 +136191,13 @@ type InstanceRequirements struct { // Indicates whether instance types must have accelerators by specific manufacturers. // - // * For instance types with NVIDIA devices, specify nvidia. + // * For instance types with Amazon Web Services devices, specify amazon-web-services. // // * For instance types with AMD devices, specify amd. // - // * For instance types with Amazon Web Services devices, specify amazon-web-services. + // * For instance types with Habana devices, specify habana. + // + // * For instance types with NVIDIA devices, specify nvidia. // // * For instance types with Xilinx devices, specify xilinx. // @@ -130333,24 +136206,30 @@ type InstanceRequirements struct { // The accelerators that must be on the instance type. // + // * For instance types with NVIDIA A10G GPUs, specify a10g. + // // * For instance types with NVIDIA A100 GPUs, specify a100. // - // * For instance types with NVIDIA V100 GPUs, specify v100. + // * For instance types with NVIDIA H100 GPUs, specify h100. // - // * For instance types with NVIDIA K80 GPUs, specify k80. + // * For instance types with Amazon Web Services Inferentia chips, specify + // inferentia. // - // * For instance types with NVIDIA T4 GPUs, specify t4. + // * For instance types with NVIDIA GRID K520 GPUs, specify k520. + // + // * For instance types with NVIDIA K80 GPUs, specify k80. // // * For instance types with NVIDIA M60 GPUs, specify m60. // // * For instance types with AMD Radeon Pro V520 GPUs, specify radeon-pro-v520. // - // * For instance types with Xilinx VU9P FPGAs, specify vu9p. + // * For instance types with NVIDIA T4 GPUs, specify t4. // - // * For instance types with Amazon Web Services Inferentia chips, specify - // inferentia. + // * For instance types with NVIDIA T4G GPUs, specify t4g. // - // * For instance types with NVIDIA GRID K520 GPUs, specify k520. + // * For instance types with Xilinx VU9P FPGAs, specify vu9p. + // + // * For instance types with NVIDIA V100 GPUs, specify v100. // // Default: Any accelerator AcceleratorNames []*string `locationName:"acceleratorNameSet" locationNameList:"item" type:"list" enum:"AcceleratorName"` @@ -130720,6 +136599,9 @@ func (s *InstanceRequirements) SetVCpuCount(v *VCpuCountRange) *InstanceRequirem // The attributes for the instance types. When you specify instance attributes, // Amazon EC2 will identify instance types with these attributes. // +// You must specify VCpuCount and MemoryMiB. All other attributes are optional. +// Any unspecified optional attribute is set to its default. +// // When you specify multiple attributes, you get instance types that satisfy // all of the specified attributes. If you specify multiple values for an attribute, // you get instance types that satisfy any of the specified values. @@ -130734,8 +136616,14 @@ func (s *InstanceRequirements) SetVCpuCount(v *VCpuCountRange) *InstanceRequirem // - ExcludedInstanceTypes - The instance types to exclude from the list, // even if they match your specified attributes. // -// You must specify VCpuCount and MemoryMiB. All other attributes are optional. -// Any unspecified optional attribute is set to its default. +// If you specify InstanceRequirements, you can't specify InstanceType. +// +// Attribute-based instance type selection is only supported when using Auto +// Scaling groups, EC2 Fleet, and Spot Fleet to launch instances. If you plan +// to use the launch template in the launch instance wizard (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html), +// or with the RunInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) +// API or AWS::EC2::Instance (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html) +// Amazon Web Services CloudFormation resource, you can't specify InstanceRequirements. // // For more information, see Attribute-based instance type selection for EC2 // Fleet (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-attribute-based-instance-type-selection.html), @@ -130755,11 +136643,13 @@ type InstanceRequirementsRequest struct { // Indicates whether instance types must have accelerators by specific manufacturers. // - // * For instance types with NVIDIA devices, specify nvidia. + // * For instance types with Amazon Web Services devices, specify amazon-web-services. // // * For instance types with AMD devices, specify amd. // - // * For instance types with Amazon Web Services devices, specify amazon-web-services. + // * For instance types with Habana devices, specify habana. + // + // * For instance types with NVIDIA devices, specify nvidia. // // * For instance types with Xilinx devices, specify xilinx. // @@ -130768,24 +136658,30 @@ type InstanceRequirementsRequest struct { // The accelerators that must be on the instance type. // + // * For instance types with NVIDIA A10G GPUs, specify a10g. + // // * For instance types with NVIDIA A100 GPUs, specify a100. // - // * For instance types with NVIDIA V100 GPUs, specify v100. + // * For instance types with NVIDIA H100 GPUs, specify h100. // - // * For instance types with NVIDIA K80 GPUs, specify k80. + // * For instance types with Amazon Web Services Inferentia chips, specify + // inferentia. // - // * For instance types with NVIDIA T4 GPUs, specify t4. + // * For instance types with NVIDIA GRID K520 GPUs, specify k520. + // + // * For instance types with NVIDIA K80 GPUs, specify k80. // // * For instance types with NVIDIA M60 GPUs, specify m60. // // * For instance types with AMD Radeon Pro V520 GPUs, specify radeon-pro-v520. // - // * For instance types with Xilinx VU9P FPGAs, specify vu9p. + // * For instance types with NVIDIA T4 GPUs, specify t4. // - // * For instance types with Amazon Web Services Inferentia chips, specify - // inferentia. + // * For instance types with NVIDIA T4G GPUs, specify t4g. // - // * For instance types with NVIDIA GRID K520 GPUs, specify k520. + // * For instance types with Xilinx VU9P FPGAs, specify vu9p. + // + // * For instance types with NVIDIA V100 GPUs, specify v100. // // Default: Any accelerator AcceleratorNames []*string `locationName:"AcceleratorName" locationNameList:"item" type:"list" enum:"AcceleratorName"` @@ -130931,8 +136827,10 @@ type InstanceRequirementsRequest struct { // MemoryMiB is a required field MemoryMiB *MemoryMiBRequest `type:"structure" required:"true"` - // The minimum and maximum amount of network bandwidth, in gigabits per second - // (Gbps). + // The minimum and maximum amount of baseline network bandwidth, in gigabits + // per second (Gbps). For more information, see Amazon EC2 instance network + // bandwidth (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-network-bandwidth.html) + // in the Amazon EC2 User Guide. // // Default: No minimum or maximum limits NetworkBandwidthGbps *NetworkBandwidthGbpsRequest `type:"structure"` @@ -131804,17 +137702,97 @@ func (s *InstanceTagNotificationAttribute) SetInstanceTagKeys(v []*string) *Inst return s } +// Information about the instance topology. +type InstanceTopology struct { + _ struct{} `type:"structure"` + + // The name of the Availability Zone or Local Zone that the instance is in. + AvailabilityZone *string `locationName:"availabilityZone" type:"string"` + + // The name of the placement group that the instance is in. + GroupName *string `locationName:"groupName" type:"string"` + + // The instance ID. + InstanceId *string `locationName:"instanceId" type:"string"` + + // The instance type. + InstanceType *string `locationName:"instanceType" type:"string"` + + // The network nodes. The nodes are hashed based on your account. Instances + // from different accounts running under the same droplet will return a different + // hashed list of strings. + NetworkNodes []*string `locationName:"networkNodeSet" locationNameList:"item" type:"list"` + + // The ID of the Availability Zone or Local Zone that the instance is in. + ZoneId *string `locationName:"zoneId" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InstanceTopology) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InstanceTopology) GoString() string { + return s.String() +} + +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *InstanceTopology) SetAvailabilityZone(v string) *InstanceTopology { + s.AvailabilityZone = &v + return s +} + +// SetGroupName sets the GroupName field's value. +func (s *InstanceTopology) SetGroupName(v string) *InstanceTopology { + s.GroupName = &v + return s +} + +// SetInstanceId sets the InstanceId field's value. +func (s *InstanceTopology) SetInstanceId(v string) *InstanceTopology { + s.InstanceId = &v + return s +} + +// SetInstanceType sets the InstanceType field's value. +func (s *InstanceTopology) SetInstanceType(v string) *InstanceTopology { + s.InstanceType = &v + return s +} + +// SetNetworkNodes sets the NetworkNodes field's value. +func (s *InstanceTopology) SetNetworkNodes(v []*string) *InstanceTopology { + s.NetworkNodes = v + return s +} + +// SetZoneId sets the ZoneId field's value. +func (s *InstanceTopology) SetZoneId(v string) *InstanceTopology { + s.ZoneId = &v + return s +} + // Describes the instance type. type InstanceTypeInfo struct { _ struct{} `type:"structure"` - // Indicates whether auto recovery is supported. + // Indicates whether Amazon CloudWatch action based recovery is supported. AutoRecoverySupported *bool `locationName:"autoRecoverySupported" type:"boolean"` // Indicates whether the instance is a bare metal instance type. BareMetal *bool `locationName:"bareMetal" type:"boolean"` - // Indicates whether the instance type is a burstable performance instance type. + // Indicates whether the instance type is a burstable performance T instance + // type. For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html). BurstablePerformanceSupported *bool `locationName:"burstablePerformanceSupported" type:"boolean"` // Indicates whether the instance type is current generation. @@ -131860,6 +137838,15 @@ type InstanceTypeInfo struct { // Describes the network settings for the instance type. NetworkInfo *NetworkInfo `locationName:"networkInfo" type:"structure"` + // Indicates whether Nitro Enclaves is supported. + NitroEnclavesSupport *string `locationName:"nitroEnclavesSupport" type:"string" enum:"NitroEnclavesSupport"` + + // Describes the supported NitroTPM versions for the instance type. + NitroTpmInfo *NitroTpmInfo `locationName:"nitroTpmInfo" type:"structure"` + + // Indicates whether NitroTPM is supported. + NitroTpmSupport *string `locationName:"nitroTpmSupport" type:"string" enum:"NitroTpmSupport"` + // Describes the placement group settings for the instance type. PlacementGroupInfo *PlacementGroupInfo `locationName:"placementGroupInfo" type:"structure"` @@ -132003,6 +137990,24 @@ func (s *InstanceTypeInfo) SetNetworkInfo(v *NetworkInfo) *InstanceTypeInfo { return s } +// SetNitroEnclavesSupport sets the NitroEnclavesSupport field's value. +func (s *InstanceTypeInfo) SetNitroEnclavesSupport(v string) *InstanceTypeInfo { + s.NitroEnclavesSupport = &v + return s +} + +// SetNitroTpmInfo sets the NitroTpmInfo field's value. +func (s *InstanceTypeInfo) SetNitroTpmInfo(v *NitroTpmInfo) *InstanceTypeInfo { + s.NitroTpmInfo = v + return s +} + +// SetNitroTpmSupport sets the NitroTpmSupport field's value. +func (s *InstanceTypeInfo) SetNitroTpmSupport(v string) *InstanceTypeInfo { + s.NitroTpmSupport = &v + return s +} + // SetPlacementGroupInfo sets the PlacementGroupInfo field's value. func (s *InstanceTypeInfo) SetPlacementGroupInfo(v *PlacementGroupInfo) *InstanceTypeInfo { s.PlacementGroupInfo = v @@ -132343,21 +138348,20 @@ type IpPermission struct { // The IP protocol name (tcp, udp, icmp, icmpv6) or number (see Protocol Numbers // (http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml)). // - // [VPC only] Use -1 to specify all protocols. When authorizing security group - // rules, specifying -1 or a protocol number other than tcp, udp, icmp, or icmpv6 - // allows traffic on all ports, regardless of any port range you specify. For - // tcp, udp, and icmp, you must specify a port range. For icmpv6, the port range - // is optional; if you omit the port range, traffic for all types and codes - // is allowed. + // Use -1 to specify all protocols. When authorizing security group rules, specifying + // -1 or a protocol number other than tcp, udp, icmp, or icmpv6 allows traffic + // on all ports, regardless of any port range you specify. For tcp, udp, and + // icmp, you must specify a port range. For icmpv6, the port range is optional; + // if you omit the port range, traffic for all types and codes is allowed. IpProtocol *string `locationName:"ipProtocol" type:"string"` // The IPv4 ranges. IpRanges []*IpRange `locationName:"ipRanges" locationNameList:"item" type:"list"` - // [VPC only] The IPv6 ranges. + // The IPv6 ranges. Ipv6Ranges []*Ipv6Range `locationName:"ipv6Ranges" locationNameList:"item" type:"list"` - // [VPC only] The prefix list IDs. + // The prefix list IDs. PrefixListIds []*PrefixListId `locationName:"prefixListIds" locationNameList:"item" type:"list"` // If the protocol is TCP or UDP, this is the end of the port range. If the @@ -132532,11 +138536,19 @@ type Ipam struct { // The state of the IPAM. State *string `locationName:"state" type:"string" enum:"IpamState"` + // The state message. + StateMessage *string `locationName:"stateMessage" type:"string"` + // The key/value combination of a tag assigned to the resource. Use the tag // key in the filter name and the tag value as the filter value. For example, // to find all resources that have a tag with the key Owner and the value TeamA, // specify tag:Owner for the filter name and TeamA for the filter value. Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` + + // IPAM is offered in a Free Tier and an Advanced Tier. For more information + // about the features available in each tier and the costs associated with the + // tiers, see Amazon VPC pricing > IPAM tab (http://aws.amazon.com/vpc/pricing/). + Tier *string `locationName:"tier" type:"string" enum:"IpamTier"` } // String returns the string representation. @@ -132635,12 +138647,24 @@ func (s *Ipam) SetState(v string) *Ipam { return s } +// SetStateMessage sets the StateMessage field's value. +func (s *Ipam) SetStateMessage(v string) *Ipam { + s.StateMessage = &v + return s +} + // SetTags sets the Tags field's value. func (s *Ipam) SetTags(v []*Tag) *Ipam { s.Tags = v return s } +// SetTier sets the Tier field's value. +func (s *Ipam) SetTier(v string) *Ipam { + s.Tier = &v + return s +} + // The historical record of a CIDR within an IPAM scope. For more information, // see View the history of IP addresses (https://docs.aws.amazon.com/vpc/latest/ipam/view-history-cidr-ipam.html) // in the Amazon VPC IPAM User Guide. @@ -132889,6 +138913,203 @@ func (s *IpamDiscoveredAccount) SetLastSuccessfulDiscoveryTime(v time.Time) *Ipa return s } +// A public IP Address discovered by IPAM. +type IpamDiscoveredPublicAddress struct { + _ struct{} `type:"structure"` + + // The IP address. + Address *string `locationName:"address" type:"string"` + + // The allocation ID of the resource the IP address is assigned to. + AddressAllocationId *string `locationName:"addressAllocationId" type:"string"` + + // The ID of the owner of the resource the IP address is assigned to. + AddressOwnerId *string `locationName:"addressOwnerId" type:"string"` + + // The Region of the resource the IP address is assigned to. + AddressRegion *string `locationName:"addressRegion" type:"string"` + + // The IP address type. + AddressType *string `locationName:"addressType" type:"string" enum:"IpamPublicAddressType"` + + // The association status. + AssociationStatus *string `locationName:"associationStatus" type:"string" enum:"IpamPublicAddressAssociationStatus"` + + // The instance ID of the instance the assigned IP address is assigned to. + InstanceId *string `locationName:"instanceId" type:"string"` + + // The resource discovery ID. + IpamResourceDiscoveryId *string `locationName:"ipamResourceDiscoveryId" type:"string"` + + // The network border group that the resource that the IP address is assigned + // to is in. + NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` + + // The description of the network interface that IP address is assigned to. + NetworkInterfaceDescription *string `locationName:"networkInterfaceDescription" type:"string"` + + // The network interface ID of the resource with the assigned IP address. + NetworkInterfaceId *string `locationName:"networkInterfaceId" type:"string"` + + // The ID of the public IPv4 pool that the resource with the assigned IP address + // is from. + PublicIpv4PoolId *string `locationName:"publicIpv4PoolId" type:"string"` + + // The last successful resource discovery time. + SampleTime *time.Time `locationName:"sampleTime" type:"timestamp"` + + // Security groups associated with the resource that the IP address is assigned + // to. + SecurityGroups []*IpamPublicAddressSecurityGroup `locationName:"securityGroupSet" locationNameList:"item" type:"list"` + + // The Amazon Web Services service associated with the IP address. + Service *string `locationName:"service" type:"string" enum:"IpamPublicAddressAwsService"` + + // The resource ARN or ID. + ServiceResource *string `locationName:"serviceResource" type:"string"` + + // The ID of the subnet that the resource with the assigned IP address is in. + SubnetId *string `locationName:"subnetId" type:"string"` + + // Tags associated with the IP address. + Tags *IpamPublicAddressTags `locationName:"tags" type:"structure"` + + // The ID of the VPC that the resource with the assigned IP address is in. + VpcId *string `locationName:"vpcId" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamDiscoveredPublicAddress) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamDiscoveredPublicAddress) GoString() string { + return s.String() +} + +// SetAddress sets the Address field's value. +func (s *IpamDiscoveredPublicAddress) SetAddress(v string) *IpamDiscoveredPublicAddress { + s.Address = &v + return s +} + +// SetAddressAllocationId sets the AddressAllocationId field's value. +func (s *IpamDiscoveredPublicAddress) SetAddressAllocationId(v string) *IpamDiscoveredPublicAddress { + s.AddressAllocationId = &v + return s +} + +// SetAddressOwnerId sets the AddressOwnerId field's value. +func (s *IpamDiscoveredPublicAddress) SetAddressOwnerId(v string) *IpamDiscoveredPublicAddress { + s.AddressOwnerId = &v + return s +} + +// SetAddressRegion sets the AddressRegion field's value. +func (s *IpamDiscoveredPublicAddress) SetAddressRegion(v string) *IpamDiscoveredPublicAddress { + s.AddressRegion = &v + return s +} + +// SetAddressType sets the AddressType field's value. +func (s *IpamDiscoveredPublicAddress) SetAddressType(v string) *IpamDiscoveredPublicAddress { + s.AddressType = &v + return s +} + +// SetAssociationStatus sets the AssociationStatus field's value. +func (s *IpamDiscoveredPublicAddress) SetAssociationStatus(v string) *IpamDiscoveredPublicAddress { + s.AssociationStatus = &v + return s +} + +// SetInstanceId sets the InstanceId field's value. +func (s *IpamDiscoveredPublicAddress) SetInstanceId(v string) *IpamDiscoveredPublicAddress { + s.InstanceId = &v + return s +} + +// SetIpamResourceDiscoveryId sets the IpamResourceDiscoveryId field's value. +func (s *IpamDiscoveredPublicAddress) SetIpamResourceDiscoveryId(v string) *IpamDiscoveredPublicAddress { + s.IpamResourceDiscoveryId = &v + return s +} + +// SetNetworkBorderGroup sets the NetworkBorderGroup field's value. +func (s *IpamDiscoveredPublicAddress) SetNetworkBorderGroup(v string) *IpamDiscoveredPublicAddress { + s.NetworkBorderGroup = &v + return s +} + +// SetNetworkInterfaceDescription sets the NetworkInterfaceDescription field's value. +func (s *IpamDiscoveredPublicAddress) SetNetworkInterfaceDescription(v string) *IpamDiscoveredPublicAddress { + s.NetworkInterfaceDescription = &v + return s +} + +// SetNetworkInterfaceId sets the NetworkInterfaceId field's value. +func (s *IpamDiscoveredPublicAddress) SetNetworkInterfaceId(v string) *IpamDiscoveredPublicAddress { + s.NetworkInterfaceId = &v + return s +} + +// SetPublicIpv4PoolId sets the PublicIpv4PoolId field's value. +func (s *IpamDiscoveredPublicAddress) SetPublicIpv4PoolId(v string) *IpamDiscoveredPublicAddress { + s.PublicIpv4PoolId = &v + return s +} + +// SetSampleTime sets the SampleTime field's value. +func (s *IpamDiscoveredPublicAddress) SetSampleTime(v time.Time) *IpamDiscoveredPublicAddress { + s.SampleTime = &v + return s +} + +// SetSecurityGroups sets the SecurityGroups field's value. +func (s *IpamDiscoveredPublicAddress) SetSecurityGroups(v []*IpamPublicAddressSecurityGroup) *IpamDiscoveredPublicAddress { + s.SecurityGroups = v + return s +} + +// SetService sets the Service field's value. +func (s *IpamDiscoveredPublicAddress) SetService(v string) *IpamDiscoveredPublicAddress { + s.Service = &v + return s +} + +// SetServiceResource sets the ServiceResource field's value. +func (s *IpamDiscoveredPublicAddress) SetServiceResource(v string) *IpamDiscoveredPublicAddress { + s.ServiceResource = &v + return s +} + +// SetSubnetId sets the SubnetId field's value. +func (s *IpamDiscoveredPublicAddress) SetSubnetId(v string) *IpamDiscoveredPublicAddress { + s.SubnetId = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *IpamDiscoveredPublicAddress) SetTags(v *IpamPublicAddressTags) *IpamDiscoveredPublicAddress { + s.Tags = v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *IpamDiscoveredPublicAddress) SetVpcId(v string) *IpamDiscoveredPublicAddress { + s.VpcId = &v + return s +} + // An IPAM discovered resource CIDR. A discovered resource is a resource CIDR // monitored under a resource discovery. The following resources can be discovered: // VPCs, Public IPv4 pools, VPC subnets, and Elastic IP addresses. The discovered @@ -133226,10 +139447,13 @@ type IpamPool struct { // pool within an existing source pool. SourceIpamPoolId *string `locationName:"sourceIpamPoolId" type:"string"` + // The resource used to provision CIDRs to a resource planning pool. + SourceResource *IpamPoolSourceResource `locationName:"sourceResource" type:"structure"` + // The state of the IPAM pool. State *string `locationName:"state" type:"string" enum:"IpamPoolState"` - // A message related to the failed creation of an IPAM pool. + // The state message. StateMessage *string `locationName:"stateMessage" type:"string"` // The key/value combination of a tag assigned to the resource. Use the tag @@ -133377,6 +139601,12 @@ func (s *IpamPool) SetSourceIpamPoolId(v string) *IpamPool { return s } +// SetSourceResource sets the SourceResource field's value. +func (s *IpamPool) SetSourceResource(v *IpamPoolSourceResource) *IpamPool { + s.SourceResource = v + return s +} + // SetState sets the State field's value. func (s *IpamPool) SetState(v string) *IpamPool { s.State = &v @@ -133600,6 +139830,238 @@ func (s *IpamPoolCidrFailureReason) SetMessage(v string) *IpamPoolCidrFailureRea return s } +// The resource used to provision CIDRs to a resource planning pool. +type IpamPoolSourceResource struct { + _ struct{} `type:"structure"` + + // The source resource ID. + ResourceId *string `locationName:"resourceId" type:"string"` + + // The source resource owner. + ResourceOwner *string `locationName:"resourceOwner" type:"string"` + + // The source resource Region. + ResourceRegion *string `locationName:"resourceRegion" type:"string"` + + // The source resource type. + ResourceType *string `locationName:"resourceType" type:"string" enum:"IpamPoolSourceResourceType"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPoolSourceResource) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPoolSourceResource) GoString() string { + return s.String() +} + +// SetResourceId sets the ResourceId field's value. +func (s *IpamPoolSourceResource) SetResourceId(v string) *IpamPoolSourceResource { + s.ResourceId = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *IpamPoolSourceResource) SetResourceOwner(v string) *IpamPoolSourceResource { + s.ResourceOwner = &v + return s +} + +// SetResourceRegion sets the ResourceRegion field's value. +func (s *IpamPoolSourceResource) SetResourceRegion(v string) *IpamPoolSourceResource { + s.ResourceRegion = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *IpamPoolSourceResource) SetResourceType(v string) *IpamPoolSourceResource { + s.ResourceType = &v + return s +} + +// The resource used to provision CIDRs to a resource planning pool. +type IpamPoolSourceResourceRequest struct { + _ struct{} `type:"structure"` + + // The source resource ID. + ResourceId *string `type:"string"` + + // The source resource owner. + ResourceOwner *string `type:"string"` + + // The source resource Region. + ResourceRegion *string `type:"string"` + + // The source resource type. + ResourceType *string `type:"string" enum:"IpamPoolSourceResourceType"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPoolSourceResourceRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPoolSourceResourceRequest) GoString() string { + return s.String() +} + +// SetResourceId sets the ResourceId field's value. +func (s *IpamPoolSourceResourceRequest) SetResourceId(v string) *IpamPoolSourceResourceRequest { + s.ResourceId = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *IpamPoolSourceResourceRequest) SetResourceOwner(v string) *IpamPoolSourceResourceRequest { + s.ResourceOwner = &v + return s +} + +// SetResourceRegion sets the ResourceRegion field's value. +func (s *IpamPoolSourceResourceRequest) SetResourceRegion(v string) *IpamPoolSourceResourceRequest { + s.ResourceRegion = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *IpamPoolSourceResourceRequest) SetResourceType(v string) *IpamPoolSourceResourceRequest { + s.ResourceType = &v + return s +} + +// The security group that the resource with the public IP address is in. +type IpamPublicAddressSecurityGroup struct { + _ struct{} `type:"structure"` + + // The security group's ID. + GroupId *string `locationName:"groupId" type:"string"` + + // The security group's name. + GroupName *string `locationName:"groupName" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPublicAddressSecurityGroup) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPublicAddressSecurityGroup) GoString() string { + return s.String() +} + +// SetGroupId sets the GroupId field's value. +func (s *IpamPublicAddressSecurityGroup) SetGroupId(v string) *IpamPublicAddressSecurityGroup { + s.GroupId = &v + return s +} + +// SetGroupName sets the GroupName field's value. +func (s *IpamPublicAddressSecurityGroup) SetGroupName(v string) *IpamPublicAddressSecurityGroup { + s.GroupName = &v + return s +} + +// A tag for a public IP address discovered by IPAM. +type IpamPublicAddressTag struct { + _ struct{} `type:"structure"` + + // The tag's key. + Key *string `locationName:"key" type:"string"` + + // The tag's value. + Value *string `locationName:"value" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPublicAddressTag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPublicAddressTag) GoString() string { + return s.String() +} + +// SetKey sets the Key field's value. +func (s *IpamPublicAddressTag) SetKey(v string) *IpamPublicAddressTag { + s.Key = &v + return s +} + +// SetValue sets the Value field's value. +func (s *IpamPublicAddressTag) SetValue(v string) *IpamPublicAddressTag { + s.Value = &v + return s +} + +// Tags for a public IP address discovered by IPAM. +type IpamPublicAddressTags struct { + _ struct{} `type:"structure"` + + // Tags for an Elastic IP address. + EipTags []*IpamPublicAddressTag `locationName:"eipTagSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPublicAddressTags) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s IpamPublicAddressTags) GoString() string { + return s.String() +} + +// SetEipTags sets the EipTags field's value. +func (s *IpamPublicAddressTags) SetEipTags(v []*IpamPublicAddressTag) *IpamPublicAddressTags { + s.EipTags = v + return s +} + // The CIDR for an IPAM resource. type IpamResourceCidr struct { _ struct{} `type:"structure"` @@ -134580,7 +141042,7 @@ func (s *Ipv6PrefixSpecificationResponse) SetIpv6Prefix(v string) *Ipv6PrefixSpe return s } -// [EC2-VPC only] Describes an IPv6 range. +// Describes an IPv6 range. type Ipv6Range struct { _ struct{} `type:"structure"` @@ -134884,7 +141346,7 @@ type LaunchSpecification struct { // Deprecated. AddressingType *string `locationName:"addressingType" type:"string"` - // One or more block device mapping entries. + // The block device mapping entries. BlockDeviceMappings []*BlockDeviceMapping `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` // Indicates whether the instance is optimized for EBS I/O. This optimization @@ -134914,8 +141376,8 @@ type LaunchSpecification struct { // Describes the monitoring of an instance. Monitoring *RunInstancesMonitoringEnabled `locationName:"monitoring" type:"structure"` - // One or more network interfaces. If you specify a network interface, you must - // specify subnet IDs and security group IDs using the network interface. + // The network interfaces. If you specify a network interface, you must specify + // subnet IDs and security group IDs using the network interface. NetworkInterfaces []*InstanceNetworkInterfaceSpecification `locationName:"networkInterfaceSet" locationNameList:"item" type:"list"` // The placement information for the instance. @@ -134924,9 +141386,7 @@ type LaunchSpecification struct { // The ID of the RAM disk. RamdiskId *string `locationName:"ramdiskId" type:"string"` - // One or more security groups. When requesting instances in a VPC, you must - // specify the IDs of the security groups. When requesting instances in EC2-Classic, - // you can specify the names or the IDs of the security groups. + // The IDs of the security groups. SecurityGroups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` // The ID of the subnet in which to launch the instance. @@ -135407,7 +141867,9 @@ func (s *LaunchTemplateCapacityReservationSpecificationResponse) SetCapacityRese type LaunchTemplateConfig struct { _ struct{} `type:"structure"` - // The launch template. + // The launch template to use. Make sure that the launch template does not contain + // the NetworkInterfaceId parameter because you can't specify a network interface + // ID in a Spot Fleet. LaunchTemplateSpecification *FleetLaunchTemplateSpecification `locationName:"launchTemplateSpecification" type:"structure"` // Any parameters that you specify override the same parameters in the launch @@ -135464,6 +141926,10 @@ func (s *LaunchTemplateConfig) SetOverrides(v []*LaunchTemplateOverrides) *Launc type LaunchTemplateCpuOptions struct { _ struct{} `type:"structure"` + // Indicates whether the instance is enabled for AMD SEV-SNP. For more information, + // see AMD SEV-SNP (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html). + AmdSevSnp *string `locationName:"amdSevSnp" type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `locationName:"coreCount" type:"integer"` @@ -135489,6 +141955,12 @@ func (s LaunchTemplateCpuOptions) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *LaunchTemplateCpuOptions) SetAmdSevSnp(v string) *LaunchTemplateCpuOptions { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *LaunchTemplateCpuOptions) SetCoreCount(v int64) *LaunchTemplateCpuOptions { s.CoreCount = &v @@ -135506,6 +141978,11 @@ func (s *LaunchTemplateCpuOptions) SetThreadsPerCore(v int64) *LaunchTemplateCpu type LaunchTemplateCpuOptionsRequest struct { _ struct{} `type:"structure"` + // Indicates whether to enable the instance for AMD SEV-SNP. AMD SEV-SNP is + // supported with M6a, R6a, and C6a instance types only. For more information, + // see AMD SEV-SNP (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html). + AmdSevSnp *string `type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `type:"integer"` @@ -135532,6 +142009,12 @@ func (s LaunchTemplateCpuOptionsRequest) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *LaunchTemplateCpuOptionsRequest) SetAmdSevSnp(v string) *LaunchTemplateCpuOptionsRequest { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *LaunchTemplateCpuOptionsRequest) SetCoreCount(v int64) *LaunchTemplateCpuOptionsRequest { s.CoreCount = &v @@ -135658,18 +142141,17 @@ type LaunchTemplateEbsBlockDeviceRequest struct { // // The following are the supported values for each volume type: // - // * gp3: 3,000-16,000 IOPS + // * gp3: 3,000 - 16,000 IOPS // - // * io1: 100-64,000 IOPS + // * io1: 100 - 64,000 IOPS // - // * io2: 100-64,000 IOPS + // * io2: 100 - 256,000 IOPS // - // For io1 and io2 volumes, we guarantee 64,000 IOPS only for Instances built - // on the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). - // Other instance families guarantee performance up to 32,000 IOPS. + // For io2 volumes, you can achieve up to 256,000 IOPS on instances built on + // the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // On other instances, you can achieve performance up to 32,000 IOPS. // - // This parameter is supported for io1, io2, and gp3 volumes only. This parameter - // is not supported for gp2, st1, sc1, or standard volumes. + // This parameter is supported for io1, io2, and gp3 volumes only. Iops *int64 `type:"integer"` // The ARN of the symmetric Key Management Service (KMS) CMK used for encryption. @@ -135687,13 +142169,15 @@ type LaunchTemplateEbsBlockDeviceRequest struct { // a volume size. The following are the supported volumes sizes for each volume // type: // - // * gp2 and gp3: 1-16,384 + // * gp2 and gp3: 1 - 16,384 GiB // - // * io1 and io2: 4-16,384 + // * io1: 4 - 16,384 GiB // - // * st1 and sc1: 125-16,384 + // * io2: 4 - 65,536 GiB // - // * standard: 1-1,024 + // * st1 and sc1: 125 - 16,384 GiB + // + // * standard: 1 - 1024 GiB VolumeSize *int64 `type:"integer"` // The volume type. For more information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) @@ -135873,6 +142357,96 @@ func (s *LaunchTemplateElasticInferenceAcceleratorResponse) SetType(v string) *L return s } +// ENA Express uses Amazon Web Services Scalable Reliable Datagram (SRD) technology +// to increase the maximum bandwidth used per stream and minimize tail latency +// of network traffic between EC2 instances. With ENA Express, you can communicate +// between two EC2 instances in the same subnet within the same account, or +// in different accounts. Both sending and receiving instances must have ENA +// Express enabled. +// +// To improve the reliability of network packet delivery, ENA Express reorders +// network packets on the receiving end by default. However, some UDP-based +// applications are designed to handle network packets that are out of order +// to reduce the overhead for packet delivery at the network layer. When ENA +// Express is enabled, you can specify whether UDP network traffic uses it. +type LaunchTemplateEnaSrdSpecification struct { + _ struct{} `type:"structure"` + + // Indicates whether ENA Express is enabled for the network interface. + EnaSrdEnabled *bool `locationName:"enaSrdEnabled" type:"boolean"` + + // Configures ENA Express for UDP network traffic. + EnaSrdUdpSpecification *LaunchTemplateEnaSrdUdpSpecification `locationName:"enaSrdUdpSpecification" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LaunchTemplateEnaSrdSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LaunchTemplateEnaSrdSpecification) GoString() string { + return s.String() +} + +// SetEnaSrdEnabled sets the EnaSrdEnabled field's value. +func (s *LaunchTemplateEnaSrdSpecification) SetEnaSrdEnabled(v bool) *LaunchTemplateEnaSrdSpecification { + s.EnaSrdEnabled = &v + return s +} + +// SetEnaSrdUdpSpecification sets the EnaSrdUdpSpecification field's value. +func (s *LaunchTemplateEnaSrdSpecification) SetEnaSrdUdpSpecification(v *LaunchTemplateEnaSrdUdpSpecification) *LaunchTemplateEnaSrdSpecification { + s.EnaSrdUdpSpecification = v + return s +} + +// ENA Express is compatible with both TCP and UDP transport protocols. When +// it's enabled, TCP traffic automatically uses it. However, some UDP-based +// applications are designed to handle network packets that are out of order, +// without a need for retransmission, such as live video broadcasting or other +// near-real-time applications. For UDP traffic, you can specify whether to +// use ENA Express, based on your application environment needs. +type LaunchTemplateEnaSrdUdpSpecification struct { + _ struct{} `type:"structure"` + + // Indicates whether UDP traffic to and from the instance uses ENA Express. + // To specify this setting, you must first enable ENA Express. + EnaSrdUdpEnabled *bool `locationName:"enaSrdUdpEnabled" type:"boolean"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LaunchTemplateEnaSrdUdpSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LaunchTemplateEnaSrdUdpSpecification) GoString() string { + return s.String() +} + +// SetEnaSrdUdpEnabled sets the EnaSrdUdpEnabled field's value. +func (s *LaunchTemplateEnaSrdUdpSpecification) SetEnaSrdUdpEnabled(v bool) *LaunchTemplateEnaSrdUdpSpecification { + s.EnaSrdUdpEnabled = &v + return s +} + // Indicates whether the instance is enabled for Amazon Web Services Nitro Enclaves. type LaunchTemplateEnclaveOptions struct { _ struct{} `type:"structure"` @@ -136265,20 +142839,18 @@ type LaunchTemplateInstanceMetadataOptions struct { // Possible values: Integers from 1 to 64 HttpPutResponseHopLimit *int64 `locationName:"httpPutResponseHopLimit" type:"integer"` - // Indicates whether IMDSv2 is optional or required. + // Indicates whether IMDSv2 is required. // - // optional - When IMDSv2 is optional, you can choose to retrieve instance metadata - // with or without a session token in your request. If you retrieve the IAM - // role credentials without a token, the IMDSv1 role credentials are returned. - // If you retrieve the IAM role credentials using a valid session token, the - // IMDSv2 role credentials are returned. + // * optional - IMDSv2 is optional. You can choose whether to send a session + // token in your instance metadata retrieval requests. If you retrieve IAM + // role credentials without a session token, you receive the IMDSv1 role + // credentials. If you retrieve IAM role credentials using a valid session + // token, you receive the IMDSv2 role credentials. // - // required - When IMDSv2 is required, you must send a session token with any - // instance metadata retrieval requests. In this state, retrieving the IAM role - // credentials always returns IMDSv2 credentials; IMDSv1 credentials are not - // available. - // - // Default: optional + // * required - IMDSv2 is required. You must send a session token in your + // instance metadata retrieval requests. With this option, retrieving the + // IAM role credentials always returns IMDSv2 credentials; IMDSv1 credentials + // are not available. HttpTokens *string `locationName:"httpTokens" type:"string" enum:"LaunchTemplateHttpTokensState"` // Set to enabled to allow access to instance tags from the instance metadata. @@ -136378,22 +142950,21 @@ type LaunchTemplateInstanceMetadataOptionsRequest struct { // Possible values: Integers from 1 to 64 HttpPutResponseHopLimit *int64 `type:"integer"` - // IMDSv2 uses token-backed sessions. Set the use of HTTP tokens to optional - // (in other words, set the use of IMDSv2 to optional) or required (in other - // words, set the use of IMDSv2 to required). + // Indicates whether IMDSv2 is required. // - // * optional - When IMDSv2 is optional, you can choose to retrieve instance - // metadata with or without a session token in your request. If you retrieve - // the IAM role credentials without a token, the IMDSv1 role credentials - // are returned. If you retrieve the IAM role credentials using a valid session - // token, the IMDSv2 role credentials are returned. + // * optional - IMDSv2 is optional. You can choose whether to send a session + // token in your instance metadata retrieval requests. If you retrieve IAM + // role credentials without a session token, you receive the IMDSv1 role + // credentials. If you retrieve IAM role credentials using a valid session + // token, you receive the IMDSv2 role credentials. // - // * required - When IMDSv2 is required, you must send a session token with - // any instance metadata retrieval requests. In this state, retrieving the + // * required - IMDSv2 is required. You must send a session token in your + // instance metadata retrieval requests. With this option, retrieving the // IAM role credentials always returns IMDSv2 credentials; IMDSv1 credentials // are not available. // - // Default: optional + // Default: If the value of ImdsSupport for the Amazon Machine Image (AMI) for + // your instance is v2.0, the default is required. HttpTokens *string `type:"string" enum:"LaunchTemplateHttpTokensState"` // Set to enabled to allow access to instance tags from the instance metadata. @@ -136468,8 +143039,19 @@ type LaunchTemplateInstanceNetworkInterfaceSpecification struct { // Indicates whether to associate a public IPv4 address with eth0 for a new // network interface. + // + // Starting on February 1, 2024, Amazon Web Services will charge for all public + // IPv4 addresses, including public IPv4 addresses associated with running instances + // and Elastic IP addresses. For more information, see the Public IPv4 Address + // tab on the Amazon VPC pricing page (http://aws.amazon.com/vpc/pricing/). AssociatePublicIpAddress *bool `locationName:"associatePublicIpAddress" type:"boolean"` + // A security group connection tracking specification that enables you to set + // the timeout for connection tracking on an Elastic network interface. For + // more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) + // in the Amazon Elastic Compute Cloud User Guide. + ConnectionTrackingSpecification *ConnectionTrackingSpecification `locationName:"connectionTrackingSpecification" type:"structure"` + // Indicates whether the network interface is deleted when the instance is terminated. DeleteOnTermination *bool `locationName:"deleteOnTermination" type:"boolean"` @@ -136479,6 +143061,10 @@ type LaunchTemplateInstanceNetworkInterfaceSpecification struct { // The device index for the network interface attachment. DeviceIndex *int64 `locationName:"deviceIndex" type:"integer"` + // Contains the ENA Express settings for instances launched from your launch + // template. + EnaSrdSpecification *LaunchTemplateEnaSrdSpecification `locationName:"enaSrdSpecification" type:"structure"` + // The IDs of one or more security groups. Groups []*string `locationName:"groupSet" locationNameList:"groupId" type:"list"` @@ -136511,6 +143097,13 @@ type LaunchTemplateInstanceNetworkInterfaceSpecification struct { // The ID of the network interface. NetworkInterfaceId *string `locationName:"networkInterfaceId" type:"string"` + // The primary IPv6 address of the network interface. When you enable an IPv6 + // GUA address to be a primary IPv6, the first IPv6 GUA will be made the primary + // IPv6 address until the instance is terminated or the network interface is + // detached. For more information about primary IPv6 addresses, see RunInstances + // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html). + PrimaryIpv6 *bool `locationName:"primaryIpv6" type:"boolean"` + // The primary private IPv4 address of the network interface. PrivateIpAddress *string `locationName:"privateIpAddress" type:"string"` @@ -136554,6 +143147,12 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetAssociatePublic return s } +// SetConnectionTrackingSpecification sets the ConnectionTrackingSpecification field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetConnectionTrackingSpecification(v *ConnectionTrackingSpecification) *LaunchTemplateInstanceNetworkInterfaceSpecification { + s.ConnectionTrackingSpecification = v + return s +} + // SetDeleteOnTermination sets the DeleteOnTermination field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetDeleteOnTermination(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecification { s.DeleteOnTermination = &v @@ -136572,6 +143171,12 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetDeviceIndex(v i return s } +// SetEnaSrdSpecification sets the EnaSrdSpecification field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetEnaSrdSpecification(v *LaunchTemplateEnaSrdSpecification) *LaunchTemplateInstanceNetworkInterfaceSpecification { + s.EnaSrdSpecification = v + return s +} + // SetGroups sets the Groups field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetGroups(v []*string) *LaunchTemplateInstanceNetworkInterfaceSpecification { s.Groups = v @@ -136632,6 +143237,12 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetNetworkInterfac return s } +// SetPrimaryIpv6 sets the PrimaryIpv6 field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetPrimaryIpv6(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecification { + s.PrimaryIpv6 = &v + return s +} + // SetPrivateIpAddress sets the PrivateIpAddress field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetPrivateIpAddress(v string) *LaunchTemplateInstanceNetworkInterfaceSpecification { s.PrivateIpAddress = &v @@ -136669,8 +143280,19 @@ type LaunchTemplateInstanceNetworkInterfaceSpecificationRequest struct { AssociateCarrierIpAddress *bool `type:"boolean"` // Associates a public IPv4 address with eth0 for a new network interface. + // + // Starting on February 1, 2024, Amazon Web Services will charge for all public + // IPv4 addresses, including public IPv4 addresses associated with running instances + // and Elastic IP addresses. For more information, see the Public IPv4 Address + // tab on the Amazon VPC pricing page (http://aws.amazon.com/vpc/pricing/). AssociatePublicIpAddress *bool `type:"boolean"` + // A security group connection tracking specification that enables you to set + // the timeout for connection tracking on an Elastic network interface. For + // more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) + // in the Amazon Elastic Compute Cloud User Guide. + ConnectionTrackingSpecification *ConnectionTrackingSpecificationRequest `type:"structure"` + // Indicates whether the network interface is deleted when the instance is terminated. DeleteOnTermination *bool `type:"boolean"` @@ -136680,6 +143302,9 @@ type LaunchTemplateInstanceNetworkInterfaceSpecificationRequest struct { // The device index for the network interface attachment. DeviceIndex *int64 `type:"integer"` + // Configure ENA Express settings for your launch template. + EnaSrdSpecification *EnaSrdSpecificationRequest `type:"structure"` + // The IDs of one or more security groups. Groups []*string `locationName:"SecurityGroupId" locationNameList:"SecurityGroupId" type:"list"` @@ -136725,6 +143350,13 @@ type LaunchTemplateInstanceNetworkInterfaceSpecificationRequest struct { // The ID of the network interface. NetworkInterfaceId *string `type:"string"` + // The primary IPv6 address of the network interface. When you enable an IPv6 + // GUA address to be a primary IPv6, the first IPv6 GUA will be made the primary + // IPv6 address until the instance is terminated or the network interface is + // detached. For more information about primary IPv6 addresses, see RunInstances + // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html). + PrimaryIpv6 *bool `type:"boolean"` + // The primary private IPv4 address of the network interface. PrivateIpAddress *string `type:"string"` @@ -136768,6 +143400,12 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetAssociat return s } +// SetConnectionTrackingSpecification sets the ConnectionTrackingSpecification field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetConnectionTrackingSpecification(v *ConnectionTrackingSpecificationRequest) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { + s.ConnectionTrackingSpecification = v + return s +} + // SetDeleteOnTermination sets the DeleteOnTermination field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetDeleteOnTermination(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { s.DeleteOnTermination = &v @@ -136786,6 +143424,12 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetDeviceIn return s } +// SetEnaSrdSpecification sets the EnaSrdSpecification field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetEnaSrdSpecification(v *EnaSrdSpecificationRequest) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { + s.EnaSrdSpecification = v + return s +} + // SetGroups sets the Groups field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetGroups(v []*string) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { s.Groups = v @@ -136846,6 +143490,12 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetNetworkI return s } +// SetPrimaryIpv6 sets the PrimaryIpv6 field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetPrimaryIpv6(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { + s.PrimaryIpv6 = &v + return s +} + // SetPrivateIpAddress sets the PrivateIpAddress field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetPrivateIpAddress(v string) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { s.PrivateIpAddress = &v @@ -137075,8 +143725,8 @@ type LaunchTemplatePlacement struct { // Reserved for future use. SpreadDomain *string `locationName:"spreadDomain" type:"string"` - // The tenancy of the instance (if the instance is running in a VPC). An instance - // with a tenancy of dedicated runs on single-tenant hardware. + // The tenancy of the instance. An instance with a tenancy of dedicated runs + // on single-tenant hardware. Tenancy *string `locationName:"tenancy" type:"string" enum:"Tenancy"` } @@ -137184,8 +143834,8 @@ type LaunchTemplatePlacementRequest struct { // Reserved for future use. SpreadDomain *string `type:"string"` - // The tenancy of the instance (if the instance is running in a VPC). An instance - // with a tenancy of dedicated runs on single-tenant hardware. + // The tenancy of the instance. An instance with a tenancy of dedicated runs + // on single-tenant hardware. Tenancy *string `type:"string" enum:"Tenancy"` } @@ -137643,9 +144293,12 @@ type LaunchTemplateTagSpecificationRequest struct { // The type of resource to tag. // - // The Valid Values are all the resource types that can be tagged. However, - // when creating a launch template, you can specify tags for the following resource - // types only: instance | volume | elastic-gpu | network-interface | spot-instances-request + // Valid Values lists all resource types for Amazon EC2 that can be tagged. + // When you create a launch template, you can specify tags for the following + // resource types only: instance | volume | elastic-gpu | network-interface + // | spot-instances-request. If the instance does not include the resource type + // that you specify, the instance launch fails. For example, not all instance + // types include an Elastic GPU. // // To tag a resource after it has been created, see CreateTags (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html). ResourceType *string `type:"string" enum:"ResourceType"` @@ -138996,6 +145649,389 @@ func (s *LocalGatewayVirtualInterfaceGroup) SetTags(v []*Tag) *LocalGatewayVirtu return s } +type LockSnapshotInput struct { + _ struct{} `type:"structure"` + + // The cooling-off period during which you can unlock the snapshot or modify + // the lock settings after locking the snapshot in compliance mode, in hours. + // After the cooling-off period expires, you can't unlock or delete the snapshot, + // decrease the lock duration, or change the lock mode. You can increase the + // lock duration after the cooling-off period expires. + // + // The cooling-off period is optional when locking a snapshot in compliance + // mode. If you are locking the snapshot in governance mode, omit this parameter. + // + // To lock the snapshot in compliance mode immediately without a cooling-off + // period, omit this parameter. + // + // If you are extending the lock duration for a snapshot that is locked in compliance + // mode after the cooling-off period has expired, omit this parameter. If you + // specify a cooling-period in a such a request, the request fails. + // + // Allowed values: Min 1, max 72. + CoolOffPeriod *int64 `min:"1" type:"integer"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The date and time at which the snapshot lock is to automatically expire, + // in the UTC time zone (YYYY-MM-DDThh:mm:ss.sssZ). + // + // You must specify either this parameter or LockDuration, but not both. + ExpirationDate *time.Time `type:"timestamp"` + + // The period of time for which to lock the snapshot, in days. The snapshot + // lock will automatically expire after this period lapses. + // + // You must specify either this parameter or ExpirationDate, but not both. + // + // Allowed values: Min: 1, max 36500 + LockDuration *int64 `min:"1" type:"integer"` + + // The mode in which to lock the snapshot. Specify one of the following: + // + // * governance - Locks the snapshot in governance mode. Snapshots locked + // in governance mode can't be deleted until one of the following conditions + // are met: The lock duration expires. The snapshot is unlocked by a user + // with the appropriate permissions. Users with the appropriate IAM permissions + // can unlock the snapshot, increase or decrease the lock duration, and change + // the lock mode to compliance at any time. If you lock a snapshot in governance + // mode, omit CoolOffPeriod. + // + // * compliance - Locks the snapshot in compliance mode. Snapshots locked + // in compliance mode can't be unlocked by any user. They can be deleted + // only after the lock duration expires. Users can't decrease the lock duration + // or change the lock mode to governance. However, users with appropriate + // IAM permissions can increase the lock duration at any time. If you lock + // a snapshot in compliance mode, you can optionally specify CoolOffPeriod. + // + // LockMode is a required field + LockMode *string `type:"string" required:"true" enum:"LockMode"` + + // The ID of the snapshot to lock. + // + // SnapshotId is a required field + SnapshotId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LockSnapshotInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LockSnapshotInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *LockSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LockSnapshotInput"} + if s.CoolOffPeriod != nil && *s.CoolOffPeriod < 1 { + invalidParams.Add(request.NewErrParamMinValue("CoolOffPeriod", 1)) + } + if s.LockDuration != nil && *s.LockDuration < 1 { + invalidParams.Add(request.NewErrParamMinValue("LockDuration", 1)) + } + if s.LockMode == nil { + invalidParams.Add(request.NewErrParamRequired("LockMode")) + } + if s.SnapshotId == nil { + invalidParams.Add(request.NewErrParamRequired("SnapshotId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCoolOffPeriod sets the CoolOffPeriod field's value. +func (s *LockSnapshotInput) SetCoolOffPeriod(v int64) *LockSnapshotInput { + s.CoolOffPeriod = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *LockSnapshotInput) SetDryRun(v bool) *LockSnapshotInput { + s.DryRun = &v + return s +} + +// SetExpirationDate sets the ExpirationDate field's value. +func (s *LockSnapshotInput) SetExpirationDate(v time.Time) *LockSnapshotInput { + s.ExpirationDate = &v + return s +} + +// SetLockDuration sets the LockDuration field's value. +func (s *LockSnapshotInput) SetLockDuration(v int64) *LockSnapshotInput { + s.LockDuration = &v + return s +} + +// SetLockMode sets the LockMode field's value. +func (s *LockSnapshotInput) SetLockMode(v string) *LockSnapshotInput { + s.LockMode = &v + return s +} + +// SetSnapshotId sets the SnapshotId field's value. +func (s *LockSnapshotInput) SetSnapshotId(v string) *LockSnapshotInput { + s.SnapshotId = &v + return s +} + +type LockSnapshotOutput struct { + _ struct{} `type:"structure"` + + // The compliance mode cooling-off period, in hours. + CoolOffPeriod *int64 `locationName:"coolOffPeriod" type:"integer"` + + // The date and time at which the compliance mode cooling-off period expires, + // in the UTC time zone (YYYY-MM-DDThh:mm:ss.sssZ). + CoolOffPeriodExpiresOn *time.Time `locationName:"coolOffPeriodExpiresOn" type:"timestamp"` + + // The date and time at which the snapshot was locked, in the UTC time zone + // (YYYY-MM-DDThh:mm:ss.sssZ). + LockCreatedOn *time.Time `locationName:"lockCreatedOn" type:"timestamp"` + + // The period of time for which the snapshot is locked, in days. + LockDuration *int64 `locationName:"lockDuration" type:"integer"` + + // The date and time at which the lock duration started, in the UTC time zone + // (YYYY-MM-DDThh:mm:ss.sssZ). + LockDurationStartTime *time.Time `locationName:"lockDurationStartTime" type:"timestamp"` + + // The date and time at which the lock will expire, in the UTC time zone (YYYY-MM-DDThh:mm:ss.sssZ). + LockExpiresOn *time.Time `locationName:"lockExpiresOn" type:"timestamp"` + + // The state of the snapshot lock. Valid states include: + // + // * compliance-cooloff - The snapshot has been locked in compliance mode + // but it is still within the cooling-off period. The snapshot can't be deleted, + // but it can be unlocked and the lock settings can be modified by users + // with appropriate permissions. + // + // * governance - The snapshot is locked in governance mode. The snapshot + // can't be deleted, but it can be unlocked and the lock settings can be + // modified by users with appropriate permissions. + // + // * compliance - The snapshot is locked in compliance mode and the cooling-off + // period has expired. The snapshot can't be unlocked or deleted. The lock + // duration can only be increased by users with appropriate permissions. + // + // * expired - The snapshot was locked in compliance or governance mode but + // the lock duration has expired. The snapshot is not locked and can be deleted. + LockState *string `locationName:"lockState" type:"string" enum:"LockState"` + + // The ID of the snapshot + SnapshotId *string `locationName:"snapshotId" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LockSnapshotOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LockSnapshotOutput) GoString() string { + return s.String() +} + +// SetCoolOffPeriod sets the CoolOffPeriod field's value. +func (s *LockSnapshotOutput) SetCoolOffPeriod(v int64) *LockSnapshotOutput { + s.CoolOffPeriod = &v + return s +} + +// SetCoolOffPeriodExpiresOn sets the CoolOffPeriodExpiresOn field's value. +func (s *LockSnapshotOutput) SetCoolOffPeriodExpiresOn(v time.Time) *LockSnapshotOutput { + s.CoolOffPeriodExpiresOn = &v + return s +} + +// SetLockCreatedOn sets the LockCreatedOn field's value. +func (s *LockSnapshotOutput) SetLockCreatedOn(v time.Time) *LockSnapshotOutput { + s.LockCreatedOn = &v + return s +} + +// SetLockDuration sets the LockDuration field's value. +func (s *LockSnapshotOutput) SetLockDuration(v int64) *LockSnapshotOutput { + s.LockDuration = &v + return s +} + +// SetLockDurationStartTime sets the LockDurationStartTime field's value. +func (s *LockSnapshotOutput) SetLockDurationStartTime(v time.Time) *LockSnapshotOutput { + s.LockDurationStartTime = &v + return s +} + +// SetLockExpiresOn sets the LockExpiresOn field's value. +func (s *LockSnapshotOutput) SetLockExpiresOn(v time.Time) *LockSnapshotOutput { + s.LockExpiresOn = &v + return s +} + +// SetLockState sets the LockState field's value. +func (s *LockSnapshotOutput) SetLockState(v string) *LockSnapshotOutput { + s.LockState = &v + return s +} + +// SetSnapshotId sets the SnapshotId field's value. +func (s *LockSnapshotOutput) SetSnapshotId(v string) *LockSnapshotOutput { + s.SnapshotId = &v + return s +} + +// Information about a locked snapshot. +type LockedSnapshotsInfo struct { + _ struct{} `type:"structure"` + + // The compliance mode cooling-off period, in hours. + CoolOffPeriod *int64 `locationName:"coolOffPeriod" type:"integer"` + + // The date and time at which the compliance mode cooling-off period expires, + // in the UTC time zone (YYYY-MM-DDThh:mm:ss.sssZ). + CoolOffPeriodExpiresOn *time.Time `locationName:"coolOffPeriodExpiresOn" type:"timestamp"` + + // The date and time at which the snapshot was locked, in the UTC time zone + // (YYYY-MM-DDThh:mm:ss.sssZ). + LockCreatedOn *time.Time `locationName:"lockCreatedOn" type:"timestamp"` + + // The period of time for which the snapshot is locked, in days. + LockDuration *int64 `locationName:"lockDuration" type:"integer"` + + // The date and time at which the lock duration started, in the UTC time zone + // (YYYY-MM-DDThh:mm:ss.sssZ). + // + // If you lock a snapshot that is in the pending state, the lock duration starts + // only once the snapshot enters the completed state. + LockDurationStartTime *time.Time `locationName:"lockDurationStartTime" type:"timestamp"` + + // The date and time at which the lock will expire, in the UTC time zone (YYYY-MM-DDThh:mm:ss.sssZ). + LockExpiresOn *time.Time `locationName:"lockExpiresOn" type:"timestamp"` + + // The state of the snapshot lock. Valid states include: + // + // * compliance-cooloff - The snapshot has been locked in compliance mode + // but it is still within the cooling-off period. The snapshot can't be deleted, + // but it can be unlocked and the lock settings can be modified by users + // with appropriate permissions. + // + // * governance - The snapshot is locked in governance mode. The snapshot + // can't be deleted, but it can be unlocked and the lock settings can be + // modified by users with appropriate permissions. + // + // * compliance - The snapshot is locked in compliance mode and the cooling-off + // period has expired. The snapshot can't be unlocked or deleted. The lock + // duration can only be increased by users with appropriate permissions. + // + // * expired - The snapshot was locked in compliance or governance mode but + // the lock duration has expired. The snapshot is not locked and can be deleted. + LockState *string `locationName:"lockState" type:"string" enum:"LockState"` + + // The account ID of the Amazon Web Services account that owns the snapshot. + OwnerId *string `locationName:"ownerId" type:"string"` + + // The ID of the snapshot. + SnapshotId *string `locationName:"snapshotId" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LockedSnapshotsInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s LockedSnapshotsInfo) GoString() string { + return s.String() +} + +// SetCoolOffPeriod sets the CoolOffPeriod field's value. +func (s *LockedSnapshotsInfo) SetCoolOffPeriod(v int64) *LockedSnapshotsInfo { + s.CoolOffPeriod = &v + return s +} + +// SetCoolOffPeriodExpiresOn sets the CoolOffPeriodExpiresOn field's value. +func (s *LockedSnapshotsInfo) SetCoolOffPeriodExpiresOn(v time.Time) *LockedSnapshotsInfo { + s.CoolOffPeriodExpiresOn = &v + return s +} + +// SetLockCreatedOn sets the LockCreatedOn field's value. +func (s *LockedSnapshotsInfo) SetLockCreatedOn(v time.Time) *LockedSnapshotsInfo { + s.LockCreatedOn = &v + return s +} + +// SetLockDuration sets the LockDuration field's value. +func (s *LockedSnapshotsInfo) SetLockDuration(v int64) *LockedSnapshotsInfo { + s.LockDuration = &v + return s +} + +// SetLockDurationStartTime sets the LockDurationStartTime field's value. +func (s *LockedSnapshotsInfo) SetLockDurationStartTime(v time.Time) *LockedSnapshotsInfo { + s.LockDurationStartTime = &v + return s +} + +// SetLockExpiresOn sets the LockExpiresOn field's value. +func (s *LockedSnapshotsInfo) SetLockExpiresOn(v time.Time) *LockedSnapshotsInfo { + s.LockExpiresOn = &v + return s +} + +// SetLockState sets the LockState field's value. +func (s *LockedSnapshotsInfo) SetLockState(v string) *LockedSnapshotsInfo { + s.LockState = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *LockedSnapshotsInfo) SetOwnerId(v string) *LockedSnapshotsInfo { + s.OwnerId = &v + return s +} + +// SetSnapshotId sets the SnapshotId field's value. +func (s *LockedSnapshotsInfo) SetSnapshotId(v string) *LockedSnapshotsInfo { + s.SnapshotId = &v + return s +} + // Details for Site-to-Site VPN tunnel endpoint maintenance events. type MaintenanceDetails struct { _ struct{} `type:"structure"` @@ -141234,7 +148270,8 @@ type ModifyInstanceAttributeInput struct { // Modifies the DeleteOnTermination attribute for volumes that are currently // attached. The volume must be owned by the caller. If no value is specified // for DeleteOnTermination, the default is true and the volume is deleted when - // the instance is terminated. + // the instance is terminated. You can't modify the DeleteOnTermination attribute + // for volumes that are attached to Fargate tasks. // // To add instance store volumes to an Amazon EBS-backed instance, you must // add them when you launch the instance. For more information, see Update the @@ -141270,10 +148307,9 @@ type ModifyInstanceAttributeInput struct { // a PV instance can make it unreachable. EnaSupport *AttributeBooleanValue `locationName:"enaSupport" type:"structure"` - // [EC2-VPC] Replaces the security groups of the instance with the specified - // security groups. You must specify at least one security group, even if it's - // just the default security group for the VPC. You must specify the security - // group ID, not the security group name. + // Replaces the security groups of the instance with the specified security + // groups. You must specify the ID of at least one security group, even if it's + // just the default security group for the VPC. Groups []*string `locationName:"GroupId" locationNameList:"groupId" type:"list"` // The ID of the instance. @@ -142085,7 +149121,7 @@ type ModifyInstanceMetadataOptionsInput struct { HttpEndpoint *string `type:"string" enum:"InstanceMetadataEndpointState"` // Enables or disables the IPv6 endpoint for the instance metadata service. - // This setting applies only if you have enabled the HTTP metadata endpoint. + // Applies only if you enabled the HTTP metadata endpoint. HttpProtocolIpv6 *string `type:"string" enum:"InstanceMetadataProtocolState"` // The desired HTTP PUT response hop limit for instance metadata requests. The @@ -142095,22 +149131,21 @@ type ModifyInstanceMetadataOptionsInput struct { // Possible values: Integers from 1 to 64 HttpPutResponseHopLimit *int64 `type:"integer"` - // IMDSv2 uses token-backed sessions. Set the use of HTTP tokens to optional - // (in other words, set the use of IMDSv2 to optional) or required (in other - // words, set the use of IMDSv2 to required). + // Indicates whether IMDSv2 is required. // - // * optional - When IMDSv2 is optional, you can choose to retrieve instance - // metadata with or without a session token in your request. If you retrieve - // the IAM role credentials without a token, the IMDSv1 role credentials - // are returned. If you retrieve the IAM role credentials using a valid session - // token, the IMDSv2 role credentials are returned. + // * optional - IMDSv2 is optional. You can choose whether to send a session + // token in your instance metadata retrieval requests. If you retrieve IAM + // role credentials without a session token, you receive the IMDSv1 role + // credentials. If you retrieve IAM role credentials using a valid session + // token, you receive the IMDSv2 role credentials. // - // * required - When IMDSv2 is required, you must send a session token with - // any instance metadata retrieval requests. In this state, retrieving the + // * required - IMDSv2 is required. You must send a session token in your + // instance metadata retrieval requests. With this option, retrieving the // IAM role credentials always returns IMDSv2 credentials; IMDSv1 credentials // are not available. // - // Default: optional + // Default: If the value of ImdsSupport for the Amazon Machine Image (AMI) for + // your instance is v2.0, the default is required. HttpTokens *string `type:"string" enum:"HttpTokensState"` // The ID of the instance. @@ -142261,7 +149296,8 @@ type ModifyInstancePlacementInput struct { // The ID of the Dedicated Host with which to associate the instance. HostId *string `locationName:"hostId" type:"string"` - // The ARN of the host resource group in which to place the instance. + // The ARN of the host resource group in which to place the instance. The instance + // must have a tenancy of host to specify this parameter. HostResourceGroupArn *string `type:"string"` // The ID of the instance that you are modifying. @@ -142275,9 +149311,10 @@ type ModifyInstancePlacementInput struct { // The tenancy for the instance. // - // For T3 instances, you can't change the tenancy from dedicated to host, or - // from host to dedicated. Attempting to make one of these unsupported tenancy - // changes results in the InvalidTenancy error code. + // For T3 instances, you must launch the instance on a Dedicated Host to use + // a tenancy of host. You can't change the tenancy from host to dedicated or + // default. Attempting to make one of these unsupported tenancy changes results + // in an InvalidRequest error code. Tenancy *string `locationName:"tenancy" type:"string" enum:"HostTenancy"` } @@ -142419,6 +149456,11 @@ type ModifyIpamInput struct { // The operating Regions to remove. RemoveOperatingRegions []*RemoveIpamOperatingRegion `locationName:"RemoveOperatingRegion" type:"list"` + + // IPAM is offered in a Free Tier and an Advanced Tier. For more information + // about the features available in each tier and the costs associated with the + // tiers, see Amazon VPC pricing > IPAM tab (http://aws.amazon.com/vpc/pricing/). + Tier *string `type:"string" enum:"IpamTier"` } // String returns the string representation. @@ -142482,6 +149524,12 @@ func (s *ModifyIpamInput) SetRemoveOperatingRegions(v []*RemoveIpamOperatingRegi return s } +// SetTier sets the Tier field's value. +func (s *ModifyIpamInput) SetTier(v string) *ModifyIpamInput { + s.Tier = &v + return s +} + type ModifyIpamOutput struct { _ struct{} `type:"structure"` @@ -143486,6 +150534,9 @@ type ModifyNetworkInterfaceAttributeInput struct { // attribute, you must specify the ID of the interface attachment. Attachment *NetworkInterfaceAttachmentChanges `locationName:"attachment" type:"structure"` + // A connection tracking specification. + ConnectionTrackingSpecification *ConnectionTrackingSpecificationRequest `type:"structure"` + // A description for the network interface. Description *AttributeValue `locationName:"description" type:"structure"` @@ -143499,6 +150550,21 @@ type ModifyNetworkInterfaceAttributeInput struct { // attached to the instance. EnaSrdSpecification *EnaSrdSpecification `type:"structure"` + // If you’re modifying a network interface in a dual-stack or IPv6-only subnet, + // you have the option to assign a primary IPv6 IP address. A primary IPv6 address + // is an IPv6 GUA address associated with an ENI that you have enabled to use + // a primary IPv6 address. Use this option if the instance that this ENI will + // be attached to relies on its IPv6 address not changing. Amazon Web Services + // will automatically assign an IPv6 address associated with the ENI attached + // to your instance to be the primary IPv6 address. Once you enable an IPv6 + // GUA address to be a primary IPv6, you cannot disable it. When you enable + // an IPv6 GUA address to be a primary IPv6, the first IPv6 GUA will be made + // the primary IPv6 address until the instance is terminated or the network + // interface is detached. If you have multiple IPv6 addresses associated with + // an ENI attached to your instance and you enable a primary IPv6 address, the + // first IPv6 GUA address associated with the ENI becomes the primary IPv6 address. + EnablePrimaryIpv6 *bool `type:"boolean"` + // Changes the security groups for the network interface. The new set of groups // you specify replaces the current set. You must specify at least one group, // even if it's just the default security group in the VPC. You must specify @@ -143556,6 +150622,12 @@ func (s *ModifyNetworkInterfaceAttributeInput) SetAttachment(v *NetworkInterface return s } +// SetConnectionTrackingSpecification sets the ConnectionTrackingSpecification field's value. +func (s *ModifyNetworkInterfaceAttributeInput) SetConnectionTrackingSpecification(v *ConnectionTrackingSpecificationRequest) *ModifyNetworkInterfaceAttributeInput { + s.ConnectionTrackingSpecification = v + return s +} + // SetDescription sets the Description field's value. func (s *ModifyNetworkInterfaceAttributeInput) SetDescription(v *AttributeValue) *ModifyNetworkInterfaceAttributeInput { s.Description = v @@ -143574,6 +150646,12 @@ func (s *ModifyNetworkInterfaceAttributeInput) SetEnaSrdSpecification(v *EnaSrdS return s } +// SetEnablePrimaryIpv6 sets the EnablePrimaryIpv6 field's value. +func (s *ModifyNetworkInterfaceAttributeInput) SetEnablePrimaryIpv6(v bool) *ModifyNetworkInterfaceAttributeInput { + s.EnablePrimaryIpv6 = &v + return s +} + // SetGroups sets the Groups field's value. func (s *ModifyNetworkInterfaceAttributeInput) SetGroups(v []*string) *ModifyNetworkInterfaceAttributeInput { s.Groups = v @@ -144818,6 +151896,10 @@ type ModifyTrafficMirrorSessionInput struct { // For example, if you set this value to 100, then the first 100 bytes that // meet the filter criteria are copied to the target. Do not specify this parameter // when you want to mirror the entire packet. + // + // For sessions with Network Load Balancer (NLB) traffic mirror targets, the + // default PacketLength will be set to 8500. Valid values are 1-8500. Setting + // a PacketLength greater than 8500 will result in an error response. PacketLength *int64 `type:"integer"` // The properties that you want to remove from the Traffic Mirror session. @@ -145081,6 +152163,20 @@ type ModifyTransitGatewayOptions struct { // Removes CIDR blocks for the transit gateway. RemoveTransitGatewayCidrBlocks []*string `locationNameList:"item" type:"list"` + // Enables you to reference a security group across VPCs attached to a transit + // gateway (TGW). Use this option to simplify security group management and + // control of instance-to-instance traffic across VPCs that are connected by + // transit gateway. You can also use this option to migrate from VPC peering + // (which was the only option that supported security group referencing) to + // transit gateways (which now also support security group referencing). This + // option is disabled by default and there are no additional costs to use this + // feature. + // + // For important information about this feature, see Create a transit gateway + // (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#create-tgw) + // in the Amazon Web Services Transit Gateway Guide. + SecurityGroupReferencingSupport *string `type:"string" enum:"SecurityGroupReferencingSupportValue"` + // Enable or disable Equal Cost Multipath Protocol support. VpnEcmpSupport *string `type:"string" enum:"VpnEcmpSupportValue"` } @@ -145157,6 +152253,12 @@ func (s *ModifyTransitGatewayOptions) SetRemoveTransitGatewayCidrBlocks(v []*str return s } +// SetSecurityGroupReferencingSupport sets the SecurityGroupReferencingSupport field's value. +func (s *ModifyTransitGatewayOptions) SetSecurityGroupReferencingSupport(v string) *ModifyTransitGatewayOptions { + s.SecurityGroupReferencingSupport = &v + return s +} + // SetVpnEcmpSupport sets the VpnEcmpSupport field's value. func (s *ModifyTransitGatewayOptions) SetVpnEcmpSupport(v string) *ModifyTransitGatewayOptions { s.VpnEcmpSupport = &v @@ -145446,6 +152548,20 @@ type ModifyTransitGatewayVpcAttachmentRequestOptions struct { // Enable or disable IPv6 support. The default is enable. Ipv6Support *string `type:"string" enum:"Ipv6SupportValue"` + + // Enables you to reference a security group across VPCs attached to a transit + // gateway (TGW). Use this option to simplify security group management and + // control of instance-to-instance traffic across VPCs that are connected by + // transit gateway. You can also use this option to migrate from VPC peering + // (which was the only option that supported security group referencing) to + // transit gateways (which now also support security group referencing). This + // option is disabled by default and there are no additional costs to use this + // feature. + // + // For important information about this feature, see Create a transit gateway + // attachment to a VPC (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#create-vpc-attachment) + // in the Amazon Web Services Transit Gateway Guide. + SecurityGroupReferencingSupport *string `type:"string" enum:"SecurityGroupReferencingSupportValue"` } // String returns the string representation. @@ -145484,7 +152600,14 @@ func (s *ModifyTransitGatewayVpcAttachmentRequestOptions) SetIpv6Support(v strin return s } -// Options for a network-interface type Verified Access endpoint. +// SetSecurityGroupReferencingSupport sets the SecurityGroupReferencingSupport field's value. +func (s *ModifyTransitGatewayVpcAttachmentRequestOptions) SetSecurityGroupReferencingSupport(v string) *ModifyTransitGatewayVpcAttachmentRequestOptions { + s.SecurityGroupReferencingSupport = &v + return s +} + +// Describes the options when modifying a Verified Access endpoint with the +// network-interface type. type ModifyVerifiedAccessEndpointEniOptions struct { _ struct{} `type:"structure"` @@ -145546,7 +152669,7 @@ type ModifyVerifiedAccessEndpointInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access endpoint. + // A description for the Verified Access endpoint. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -145555,19 +152678,18 @@ type ModifyVerifiedAccessEndpointInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The load balancer details if creating the Amazon Web Services Verified Access - // endpoint as load-balancertype. + // The load balancer details if creating the Verified Access endpoint as load-balancertype. LoadBalancerOptions *ModifyVerifiedAccessEndpointLoadBalancerOptions `type:"structure"` // The network interface options. NetworkInterfaceOptions *ModifyVerifiedAccessEndpointEniOptions `type:"structure"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. VerifiedAccessGroupId *string `type:"string"` } @@ -145721,7 +152843,7 @@ func (s *ModifyVerifiedAccessEndpointLoadBalancerOptions) SetSubnetIds(v []*stri type ModifyVerifiedAccessEndpointOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access endpoint details. + // Details about the Verified Access endpoint. VerifiedAccessEndpoint *VerifiedAccessEndpoint `locationName:"verifiedAccessEndpoint" type:"structure"` } @@ -145763,15 +152885,16 @@ type ModifyVerifiedAccessEndpointPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` // The status of the Verified Access policy. - // - // PolicyEnabled is a required field - PolicyEnabled *bool `type:"boolean" required:"true"` + PolicyEnabled *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The options for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationRequest `type:"structure"` + + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` @@ -145798,9 +152921,6 @@ func (s ModifyVerifiedAccessEndpointPolicyInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *ModifyVerifiedAccessEndpointPolicyInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ModifyVerifiedAccessEndpointPolicyInput"} - if s.PolicyEnabled == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyEnabled")) - } if s.VerifiedAccessEndpointId == nil { invalidParams.Add(request.NewErrParamRequired("VerifiedAccessEndpointId")) } @@ -145835,6 +152955,12 @@ func (s *ModifyVerifiedAccessEndpointPolicyInput) SetPolicyEnabled(v bool) *Modi return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *ModifyVerifiedAccessEndpointPolicyInput) SetSseSpecification(v *VerifiedAccessSseSpecificationRequest) *ModifyVerifiedAccessEndpointPolicyInput { + s.SseSpecification = v + return s +} + // SetVerifiedAccessEndpointId sets the VerifiedAccessEndpointId field's value. func (s *ModifyVerifiedAccessEndpointPolicyInput) SetVerifiedAccessEndpointId(v string) *ModifyVerifiedAccessEndpointPolicyInput { s.VerifiedAccessEndpointId = &v @@ -145844,11 +152970,14 @@ func (s *ModifyVerifiedAccessEndpointPolicyInput) SetVerifiedAccessEndpointId(v type ModifyVerifiedAccessEndpointPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. PolicyEnabled *bool `locationName:"policyEnabled" type:"boolean"` + + // The options in use for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationResponse `locationName:"sseSpecification" type:"structure"` } // String returns the string representation. @@ -145881,6 +153010,12 @@ func (s *ModifyVerifiedAccessEndpointPolicyOutput) SetPolicyEnabled(v bool) *Mod return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *ModifyVerifiedAccessEndpointPolicyOutput) SetSseSpecification(v *VerifiedAccessSseSpecificationResponse) *ModifyVerifiedAccessEndpointPolicyOutput { + s.SseSpecification = v + return s +} + type ModifyVerifiedAccessGroupInput struct { _ struct{} `type:"structure"` @@ -145889,7 +153024,7 @@ type ModifyVerifiedAccessGroupInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access group. + // A description for the Verified Access group. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -145898,12 +153033,12 @@ type ModifyVerifiedAccessGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstanceId *string `type:"string"` } @@ -145971,7 +153106,7 @@ func (s *ModifyVerifiedAccessGroupInput) SetVerifiedAccessInstanceId(v string) * type ModifyVerifiedAccessGroupOutput struct { _ struct{} `type:"structure"` - // Details of Amazon Web Services Verified Access group. + // Details about the Verified Access group. VerifiedAccessGroup *VerifiedAccessGroup `locationName:"verifiedAccessGroup" type:"structure"` } @@ -146013,15 +153148,16 @@ type ModifyVerifiedAccessGroupPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` // The status of the Verified Access policy. - // - // PolicyEnabled is a required field - PolicyEnabled *bool `type:"boolean" required:"true"` + PolicyEnabled *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access group. + // The options for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationRequest `type:"structure"` + + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` @@ -146048,9 +153184,6 @@ func (s ModifyVerifiedAccessGroupPolicyInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *ModifyVerifiedAccessGroupPolicyInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ModifyVerifiedAccessGroupPolicyInput"} - if s.PolicyEnabled == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyEnabled")) - } if s.VerifiedAccessGroupId == nil { invalidParams.Add(request.NewErrParamRequired("VerifiedAccessGroupId")) } @@ -146085,6 +153218,12 @@ func (s *ModifyVerifiedAccessGroupPolicyInput) SetPolicyEnabled(v bool) *ModifyV return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *ModifyVerifiedAccessGroupPolicyInput) SetSseSpecification(v *VerifiedAccessSseSpecificationRequest) *ModifyVerifiedAccessGroupPolicyInput { + s.SseSpecification = v + return s +} + // SetVerifiedAccessGroupId sets the VerifiedAccessGroupId field's value. func (s *ModifyVerifiedAccessGroupPolicyInput) SetVerifiedAccessGroupId(v string) *ModifyVerifiedAccessGroupPolicyInput { s.VerifiedAccessGroupId = &v @@ -146094,11 +153233,14 @@ func (s *ModifyVerifiedAccessGroupPolicyInput) SetVerifiedAccessGroupId(v string type ModifyVerifiedAccessGroupPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. PolicyEnabled *bool `locationName:"policyEnabled" type:"boolean"` + + // The options in use for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationResponse `locationName:"sseSpecification" type:"structure"` } // String returns the string representation. @@ -146131,6 +153273,12 @@ func (s *ModifyVerifiedAccessGroupPolicyOutput) SetPolicyEnabled(v bool) *Modify return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *ModifyVerifiedAccessGroupPolicyOutput) SetSseSpecification(v *VerifiedAccessSseSpecificationResponse) *ModifyVerifiedAccessGroupPolicyOutput { + s.SseSpecification = v + return s +} + type ModifyVerifiedAccessInstanceInput struct { _ struct{} `type:"structure"` @@ -146139,7 +153287,7 @@ type ModifyVerifiedAccessInstanceInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access instance. + // A description for the Verified Access instance. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -146148,7 +153296,7 @@ type ModifyVerifiedAccessInstanceInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -146212,7 +153360,7 @@ func (s *ModifyVerifiedAccessInstanceInput) SetVerifiedAccessInstanceId(v string type ModifyVerifiedAccessInstanceLoggingConfigurationInput struct { _ struct{} `type:"structure"` - // The configuration options for Amazon Web Services Verified Access instances. + // The configuration options for Verified Access instances. // // AccessLogs is a required field AccessLogs *VerifiedAccessLogOptions `type:"structure" required:"true"` @@ -146228,7 +153376,7 @@ type ModifyVerifiedAccessInstanceLoggingConfigurationInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -146300,7 +153448,7 @@ func (s *ModifyVerifiedAccessInstanceLoggingConfigurationInput) SetVerifiedAcces type ModifyVerifiedAccessInstanceLoggingConfigurationOutput struct { _ struct{} `type:"structure"` - // The logging configuration for Amazon Web Services Verified Access instance. + // The logging configuration for the Verified Access instance. LoggingConfiguration *VerifiedAccessInstanceLoggingConfiguration `locationName:"loggingConfiguration" type:"structure"` } @@ -146331,7 +153479,7 @@ func (s *ModifyVerifiedAccessInstanceLoggingConfigurationOutput) SetLoggingConfi type ModifyVerifiedAccessInstanceOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // Details about the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` } @@ -146359,6 +153507,40 @@ func (s *ModifyVerifiedAccessInstanceOutput) SetVerifiedAccessInstance(v *Verifi return s } +// Modifies the configuration of the specified device-based Amazon Web Services +// Verified Access trust provider. +type ModifyVerifiedAccessTrustProviderDeviceOptions struct { + _ struct{} `type:"structure"` + + // The URL Amazon Web Services Verified Access will use to verify the authenticity + // of the device tokens. + PublicSigningKeyUrl *string `type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ModifyVerifiedAccessTrustProviderDeviceOptions) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ModifyVerifiedAccessTrustProviderDeviceOptions) GoString() string { + return s.String() +} + +// SetPublicSigningKeyUrl sets the PublicSigningKeyUrl field's value. +func (s *ModifyVerifiedAccessTrustProviderDeviceOptions) SetPublicSigningKeyUrl(v string) *ModifyVerifiedAccessTrustProviderDeviceOptions { + s.PublicSigningKeyUrl = &v + return s +} + type ModifyVerifiedAccessTrustProviderInput struct { _ struct{} `type:"structure"` @@ -146367,19 +153549,26 @@ type ModifyVerifiedAccessTrustProviderInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access trust provider. + // A description for the Verified Access trust provider. Description *string `type:"string"` + // The options for a device-based trust provider. This parameter is required + // when the provider type is device. + DeviceOptions *ModifyVerifiedAccessTrustProviderDeviceOptions `type:"structure"` + // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The OpenID Connect details for an oidc-type, user-identity based trust provider. + // The options for an OpenID Connect-compatible user-identity trust provider. OidcOptions *ModifyVerifiedAccessTrustProviderOidcOptions `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The options for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationRequest `type:"structure"` + + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -146428,6 +153617,12 @@ func (s *ModifyVerifiedAccessTrustProviderInput) SetDescription(v string) *Modif return s } +// SetDeviceOptions sets the DeviceOptions field's value. +func (s *ModifyVerifiedAccessTrustProviderInput) SetDeviceOptions(v *ModifyVerifiedAccessTrustProviderDeviceOptions) *ModifyVerifiedAccessTrustProviderInput { + s.DeviceOptions = v + return s +} + // SetDryRun sets the DryRun field's value. func (s *ModifyVerifiedAccessTrustProviderInput) SetDryRun(v bool) *ModifyVerifiedAccessTrustProviderInput { s.DryRun = &v @@ -146440,20 +153635,48 @@ func (s *ModifyVerifiedAccessTrustProviderInput) SetOidcOptions(v *ModifyVerifie return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *ModifyVerifiedAccessTrustProviderInput) SetSseSpecification(v *VerifiedAccessSseSpecificationRequest) *ModifyVerifiedAccessTrustProviderInput { + s.SseSpecification = v + return s +} + // SetVerifiedAccessTrustProviderId sets the VerifiedAccessTrustProviderId field's value. func (s *ModifyVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderId(v string) *ModifyVerifiedAccessTrustProviderInput { s.VerifiedAccessTrustProviderId = &v return s } -// OpenID Connect options for an oidc-type, user-identity based trust provider. +// Options for an OpenID Connect-compatible user-identity trust provider. type ModifyVerifiedAccessTrustProviderOidcOptions struct { _ struct{} `type:"structure"` + // The OIDC authorization endpoint. + AuthorizationEndpoint *string `type:"string"` + + // The client identifier. + ClientId *string `type:"string"` + + // The client secret. + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by ModifyVerifiedAccessTrustProviderOidcOptions's + // String and GoString methods. + ClientSecret *string `type:"string" sensitive:"true"` + + // The OIDC issuer. + Issuer *string `type:"string"` + // OpenID Connect (OIDC) scopes are used by an application during authentication // to authorize access to a user's details. Each scope returns a specific set // of user attributes. Scope *string `type:"string"` + + // The OIDC token endpoint. + TokenEndpoint *string `type:"string"` + + // The OIDC user info endpoint. + UserInfoEndpoint *string `type:"string"` } // String returns the string representation. @@ -146474,16 +153697,52 @@ func (s ModifyVerifiedAccessTrustProviderOidcOptions) GoString() string { return s.String() } +// SetAuthorizationEndpoint sets the AuthorizationEndpoint field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetAuthorizationEndpoint(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.AuthorizationEndpoint = &v + return s +} + +// SetClientId sets the ClientId field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetClientId(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.ClientId = &v + return s +} + +// SetClientSecret sets the ClientSecret field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetClientSecret(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.ClientSecret = &v + return s +} + +// SetIssuer sets the Issuer field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetIssuer(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.Issuer = &v + return s +} + // SetScope sets the Scope field's value. func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetScope(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { s.Scope = &v return s } +// SetTokenEndpoint sets the TokenEndpoint field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetTokenEndpoint(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.TokenEndpoint = &v + return s +} + +// SetUserInfoEndpoint sets the UserInfoEndpoint field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetUserInfoEndpoint(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.UserInfoEndpoint = &v + return s +} + type ModifyVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // Details about the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -146614,11 +153873,15 @@ type ModifyVolumeInput struct { // // The following are the supported values for each volume type: // - // * gp3: 3,000-16,000 IOPS + // * gp3: 3,000 - 16,000 IOPS // - // * io1: 100-64,000 IOPS + // * io1: 100 - 64,000 IOPS // - // * io2: 100-64,000 IOPS + // * io2: 100 - 256,000 IOPS + // + // For io2 volumes, you can achieve up to 256,000 IOPS on instances built on + // the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // On other instances, you can achieve performance up to 32,000 IOPS. // // Default: The existing value is retained if you keep the same volume type. // If you change the volume type to io1, io2, or gp3, the default is 3,000. @@ -146636,13 +153899,15 @@ type ModifyVolumeInput struct { // // The following are the supported volumes sizes for each volume type: // - // * gp2 and gp3: 1-16,384 + // * gp2 and gp3: 1 - 16,384 GiB // - // * io1 and io2: 4-16,384 + // * io1: 4 - 16,384 GiB // - // * st1 and sc1: 125-16,384 + // * io2: 4 - 65,536 GiB // - // * standard: 1-1,024 + // * st1 and sc1: 125 - 16,384 GiB + // + // * standard: 1 - 1024 GiB // // Default: The existing size is retained. Size *int64 `type:"integer"` @@ -146995,7 +154260,7 @@ type ModifyVpcEndpointInput struct { AddRouteTableIds []*string `locationName:"AddRouteTableId" locationNameList:"item" type:"list"` // (Interface endpoint) The IDs of the security groups to associate with the - // network interface. + // endpoint network interfaces. AddSecurityGroupIds []*string `locationName:"AddSecurityGroupId" locationNameList:"item" type:"list"` // (Interface and Gateway Load Balancer endpoints) The IDs of the subnets in @@ -147027,7 +154292,7 @@ type ModifyVpcEndpointInput struct { RemoveRouteTableIds []*string `locationName:"RemoveRouteTableId" locationNameList:"item" type:"list"` // (Interface endpoint) The IDs of the security groups to disassociate from - // the network interface. + // the endpoint network interfaces. RemoveSecurityGroupIds []*string `locationName:"RemoveSecurityGroupId" locationNameList:"item" type:"list"` // (Interface endpoint) The IDs of the subnets from which to remove the endpoint. @@ -147037,6 +154302,9 @@ type ModifyVpcEndpointInput struct { // policy. The default policy allows full access to the service. ResetPolicy *bool `type:"boolean"` + // The subnet configurations for the endpoint. + SubnetConfigurations []*SubnetConfiguration `locationName:"SubnetConfiguration" locationNameList:"item" type:"list"` + // The ID of the endpoint. // // VpcEndpointId is a required field @@ -147146,6 +154414,12 @@ func (s *ModifyVpcEndpointInput) SetResetPolicy(v bool) *ModifyVpcEndpointInput return s } +// SetSubnetConfigurations sets the SubnetConfigurations field's value. +func (s *ModifyVpcEndpointInput) SetSubnetConfigurations(v []*SubnetConfiguration) *ModifyVpcEndpointInput { + s.SubnetConfigurations = v + return s +} + // SetVpcEndpointId sets the VpcEndpointId field's value. func (s *ModifyVpcEndpointInput) SetVpcEndpointId(v string) *ModifyVpcEndpointInput { s.VpcEndpointId = &v @@ -148165,15 +155439,20 @@ type ModifyVpnTunnelOptionsInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // Choose whether or not to trigger immediate tunnel replacement. + // Choose whether or not to trigger immediate tunnel replacement. This is only + // applicable when turning on or off EnableTunnelLifecycleControl. // // Valid values: True | False SkipTunnelReplacement *bool `type:"boolean"` // The tunnel options to modify. // + // TunnelOptions is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by ModifyVpnTunnelOptionsInput's + // String and GoString methods. + // // TunnelOptions is a required field - TunnelOptions *ModifyVpnTunnelOptionsSpecification `type:"structure" required:"true"` + TunnelOptions *ModifyVpnTunnelOptionsSpecification `type:"structure" required:"true" sensitive:"true"` // The ID of the Amazon Web Services Site-to-Site VPN connection. // @@ -148286,7 +155565,7 @@ func (s *ModifyVpnTunnelOptionsOutput) SetVpnConnection(v *VpnConnection) *Modif // The Amazon Web Services Site-to-Site VPN tunnel options to modify. type ModifyVpnTunnelOptionsSpecification struct { - _ struct{} `type:"structure"` + _ struct{} `type:"structure" sensitive:"true"` // The action to take after DPD timeout occurs. Specify restart to restart the // IKE initiation. Specify clear to end the IKE session. @@ -148296,11 +155575,13 @@ type ModifyVpnTunnelOptionsSpecification struct { // Default: clear DPDTimeoutAction *string `type:"string"` - // The number of seconds after which a DPD timeout occurs. + // The number of seconds after which a DPD timeout occurs. A DPD timeout of + // 40 seconds means that the VPN endpoint will consider the peer dead 30 seconds + // after the first failed keep-alive. // // Constraints: A value greater than or equal to 30. // - // Default: 30 + // Default: 40 DPDTimeoutSeconds *int64 `type:"integer"` // Turn on or off tunnel endpoint lifecycle control feature. @@ -148371,7 +155652,11 @@ type ModifyVpnTunnelOptionsSpecification struct { // Constraints: Allowed characters are alphanumeric characters, periods (.), // and underscores (_). Must be between 8 and 64 characters in length and cannot // start with zero (0). - PreSharedKey *string `type:"string"` + // + // PreSharedKey is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by ModifyVpnTunnelOptionsSpecification's + // String and GoString methods. + PreSharedKey *string `type:"string" sensitive:"true"` // The percentage of the rekey window (determined by RekeyMarginTimeSeconds) // during which the rekey time is randomly selected. @@ -148912,16 +156197,13 @@ func (s *MoveByoipCidrToIpamOutput) SetByoipCidr(v *ByoipCidr) *MoveByoipCidrToI return s } -// Describes the status of a moving Elastic IP address. +// This action is deprecated. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// Describes the status of a moving Elastic IP address. type MovingAddressStatus struct { _ struct{} `type:"structure"` - // The status of the Elastic IP address that's being moved to the EC2-VPC platform, - // or restored to the EC2-Classic platform. + // The status of the Elastic IP address that's being moved or restored. MoveStatus *string `locationName:"moveStatus" type:"string" enum:"MoveStatus"` // The Elastic IP address. @@ -149234,7 +156516,7 @@ type NetworkAcl struct { // Any associations between the network ACL and one or more subnets Associations []*NetworkAclAssociation `locationName:"associationSet" locationNameList:"item" type:"list"` - // One or more entries (rules) in the network ACL. + // The entries (rules) in the network ACL. Entries []*NetworkAclEntry `locationName:"entrySet" locationNameList:"item" type:"list"` // Indicates whether this is the default network ACL for the VPC. @@ -149566,6 +156848,9 @@ func (s *NetworkBandwidthGbpsRequest) SetMin(v float64) *NetworkBandwidthGbpsReq type NetworkCardInfo struct { _ struct{} `type:"structure"` + // The baseline network performance of the network card, in Gbps. + BaselineBandwidthInGbps *float64 `locationName:"baselineBandwidthInGbps" type:"double"` + // The maximum number of network interfaces for the network card. MaximumNetworkInterfaces *int64 `locationName:"maximumNetworkInterfaces" type:"integer"` @@ -149574,6 +156859,9 @@ type NetworkCardInfo struct { // The network performance of the network card. NetworkPerformance *string `locationName:"networkPerformance" type:"string"` + + // The peak (burst) network performance of the network card, in Gbps. + PeakBandwidthInGbps *float64 `locationName:"peakBandwidthInGbps" type:"double"` } // String returns the string representation. @@ -149594,6 +156882,12 @@ func (s NetworkCardInfo) GoString() string { return s.String() } +// SetBaselineBandwidthInGbps sets the BaselineBandwidthInGbps field's value. +func (s *NetworkCardInfo) SetBaselineBandwidthInGbps(v float64) *NetworkCardInfo { + s.BaselineBandwidthInGbps = &v + return s +} + // SetMaximumNetworkInterfaces sets the MaximumNetworkInterfaces field's value. func (s *NetworkCardInfo) SetMaximumNetworkInterfaces(v int64) *NetworkCardInfo { s.MaximumNetworkInterfaces = &v @@ -149612,6 +156906,12 @@ func (s *NetworkCardInfo) SetNetworkPerformance(v string) *NetworkCardInfo { return s } +// SetPeakBandwidthInGbps sets the PeakBandwidthInGbps field's value. +func (s *NetworkCardInfo) SetPeakBandwidthInGbps(v float64) *NetworkCardInfo { + s.PeakBandwidthInGbps = &v + return s +} + // Describes the networking features of the instance type. type NetworkInfo struct { _ struct{} `type:"structure"` @@ -150328,6 +157628,12 @@ type NetworkInterface struct { // The Availability Zone. AvailabilityZone *string `locationName:"availabilityZone" type:"string"` + // A security group connection tracking configuration that enables you to set + // the timeout for connection tracking on an Elastic network interface. For + // more information, see Connection tracking timeouts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html#connection-tracking-timeouts) + // in the Amazon Elastic Compute Cloud User Guide. + ConnectionTrackingConfiguration *ConnectionTrackingConfiguration `locationName:"connectionTrackingConfiguration" type:"structure"` + // Indicates whether a network interface with an IPv6 address is unreachable // from the public internet. If the value is true, inbound traffic from the // internet is dropped and you cannot assign an elastic IP address to the network @@ -150439,6 +157745,12 @@ func (s *NetworkInterface) SetAvailabilityZone(v string) *NetworkInterface { return s } +// SetConnectionTrackingConfiguration sets the ConnectionTrackingConfiguration field's value. +func (s *NetworkInterface) SetConnectionTrackingConfiguration(v *ConnectionTrackingConfiguration) *NetworkInterface { + s.ConnectionTrackingConfiguration = v + return s +} + // SetDenyAllIgwTraffic sets the DenyAllIgwTraffic field's value. func (s *NetworkInterface) SetDenyAllIgwTraffic(v bool) *NetworkInterface { s.DenyAllIgwTraffic = &v @@ -150906,6 +158218,13 @@ type NetworkInterfaceIpv6Address struct { // The IPv6 address. Ipv6Address *string `locationName:"ipv6Address" type:"string"` + + // Determines if an IPv6 address associated with a network interface is the + // primary IPv6 address. When you enable an IPv6 GUA address to be a primary + // IPv6, the first IPv6 GUA will be made the primary IPv6 address until the + // instance is terminated or the network interface is detached. For more information, + // see ModifyNetworkInterfaceAttribute (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyNetworkInterfaceAttribute.html). + IsPrimaryIpv6 *bool `locationName:"isPrimaryIpv6" type:"boolean"` } // String returns the string representation. @@ -150932,6 +158251,12 @@ func (s *NetworkInterfaceIpv6Address) SetIpv6Address(v string) *NetworkInterface return s } +// SetIsPrimaryIpv6 sets the IsPrimaryIpv6 field's value. +func (s *NetworkInterfaceIpv6Address) SetIsPrimaryIpv6(v bool) *NetworkInterfaceIpv6Address { + s.IsPrimaryIpv6 = &v + return s +} + // Describes a permission for a network interface. type NetworkInterfacePermission struct { _ struct{} `type:"structure"` @@ -151149,7 +158474,40 @@ func (s *NewDhcpConfiguration) SetValues(v []*string) *NewDhcpConfiguration { return s } -// Options for OIDC-based, user-identity type trust provider. +// Describes the supported NitroTPM versions for the instance type. +type NitroTpmInfo struct { + _ struct{} `type:"structure"` + + // Indicates the supported NitroTPM versions. + SupportedVersions []*string `locationName:"supportedVersions" locationNameList:"item" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s NitroTpmInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s NitroTpmInfo) GoString() string { + return s.String() +} + +// SetSupportedVersions sets the SupportedVersions field's value. +func (s *NitroTpmInfo) SetSupportedVersions(v []*string) *NitroTpmInfo { + s.SupportedVersions = v + return s +} + +// Describes the options for an OpenID Connect-compatible user-identity trust +// provider. type OidcOptions struct { _ struct{} `type:"structure"` @@ -151160,7 +158518,11 @@ type OidcOptions struct { ClientId *string `locationName:"clientId" type:"string"` // The client secret. - ClientSecret *string `locationName:"clientSecret" type:"string"` + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by OidcOptions's + // String and GoString methods. + ClientSecret *string `locationName:"clientSecret" type:"string" sensitive:"true"` // The OIDC issuer. Issuer *string `locationName:"issuer" type:"string"` @@ -151259,6 +158621,14 @@ type OnDemandOptions struct { // The maximum amount per hour for On-Demand Instances that you're willing to // pay. + // + // If your fleet includes T instances that are configured as unlimited, and + // if their average CPU usage exceeds the baseline utilization, you will incur + // a charge for surplus credits. The maxTotalPrice does not account for surplus + // credits, and, if you use surplus credits, your final cost might be higher + // than what you specified for maxTotalPrice. For more information, see Surplus + // credits can incur charges (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-unlimited-mode-concepts.html#unlimited-mode-surplus-credits) + // in the EC2 User Guide. MaxTotalPrice *string `locationName:"maxTotalPrice" type:"string"` // The minimum target capacity for On-Demand Instances in the fleet. If the @@ -151361,6 +158731,14 @@ type OnDemandOptionsRequest struct { // The maximum amount per hour for On-Demand Instances that you're willing to // pay. + // + // If your fleet includes T instances that are configured as unlimited, and + // if their average CPU usage exceeds the baseline utilization, you will incur + // a charge for surplus credits. The MaxTotalPrice does not account for surplus + // credits, and, if you use surplus credits, your final cost might be higher + // than what you specified for MaxTotalPrice. For more information, see Surplus + // credits can incur charges (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-unlimited-mode-concepts.html#unlimited-mode-surplus-credits) + // in the EC2 User Guide. MaxTotalPrice *string `type:"string"` // The minimum target capacity for On-Demand Instances in the fleet. If the @@ -152117,10 +159495,6 @@ func (s *PeeringAttachmentStatus) SetMessage(v string) *PeeringAttachmentStatus return s } -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Describes the VPC peering connection options. type PeeringConnectionOptions struct { _ struct{} `type:"structure"` @@ -152129,12 +159503,10 @@ type PeeringConnectionOptions struct { // to private IP addresses when queried from instances in the peer VPC. AllowDnsResolutionFromRemoteVpc *bool `locationName:"allowDnsResolutionFromRemoteVpc" type:"boolean"` - // If true, enables outbound communication from an EC2-Classic instance that's - // linked to a local VPC using ClassicLink to instances in a peer VPC. + // Deprecated. AllowEgressFromLocalClassicLinkToRemoteVpc *bool `locationName:"allowEgressFromLocalClassicLinkToRemoteVpc" type:"boolean"` - // If true, enables outbound communication from instances in a local VPC to - // an EC2-Classic instance that's linked to a peer VPC using ClassicLink. + // Deprecated. AllowEgressFromLocalVpcToRemoteClassicLink *bool `locationName:"allowEgressFromLocalVpcToRemoteClassicLink" type:"boolean"` } @@ -152174,10 +159546,6 @@ func (s *PeeringConnectionOptions) SetAllowEgressFromLocalVpcToRemoteClassicLink return s } -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // The VPC peering connection options. type PeeringConnectionOptionsRequest struct { _ struct{} `type:"structure"` @@ -152186,12 +159554,10 @@ type PeeringConnectionOptionsRequest struct { // addresses when queried from instances in the peer VPC. AllowDnsResolutionFromRemoteVpc *bool `type:"boolean"` - // If true, enables outbound communication from an EC2-Classic instance that's - // linked to a local VPC using ClassicLink to instances in a peer VPC. + // Deprecated. AllowEgressFromLocalClassicLinkToRemoteVpc *bool `type:"boolean"` - // If true, enables outbound communication from instances in a local VPC to - // an EC2-Classic instance that's linked to a peer VPC using ClassicLink. + // Deprecated. AllowEgressFromLocalVpcToRemoteClassicLink *bool `type:"boolean"` } @@ -152725,8 +160091,8 @@ type Placement struct { // Reserved for future use. SpreadDomain *string `locationName:"spreadDomain" type:"string"` - // The tenancy of the instance (if the instance is running in a VPC). An instance - // with a tenancy of dedicated runs on single-tenant hardware. + // The tenancy of the instance. An instance with a tenancy of dedicated runs + // on single-tenant hardware. // // This parameter is not supported for CreateFleet (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet). // The host tenancy is not supported for ImportInstance (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) @@ -153726,9 +161092,17 @@ func (s *PrivateIpAddressSpecification) SetPrivateIpAddress(v string) *PrivateIp type ProcessorInfo struct { _ struct{} `type:"structure"` + // The manufacturer of the processor. + Manufacturer *string `locationName:"manufacturer" type:"string"` + // The architectures supported by the instance type. SupportedArchitectures []*string `locationName:"supportedArchitectures" locationNameList:"item" type:"list" enum:"ArchitectureType"` + // Indicates whether the instance type supports AMD SEV-SNP. If the request + // returns amd-sev-snp, AMD SEV-SNP is supported. Otherwise, it is not supported. + // For more information, see AMD SEV-SNP (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html). + SupportedFeatures []*string `locationName:"supportedFeatures" locationNameList:"item" type:"list" enum:"SupportedAdditionalProcessorFeature"` + // The speed of the processor, in GHz. SustainedClockSpeedInGhz *float64 `locationName:"sustainedClockSpeedInGhz" type:"double"` } @@ -153751,12 +161125,24 @@ func (s ProcessorInfo) GoString() string { return s.String() } +// SetManufacturer sets the Manufacturer field's value. +func (s *ProcessorInfo) SetManufacturer(v string) *ProcessorInfo { + s.Manufacturer = &v + return s +} + // SetSupportedArchitectures sets the SupportedArchitectures field's value. func (s *ProcessorInfo) SetSupportedArchitectures(v []*string) *ProcessorInfo { s.SupportedArchitectures = v return s } +// SetSupportedFeatures sets the SupportedFeatures field's value. +func (s *ProcessorInfo) SetSupportedFeatures(v []*string) *ProcessorInfo { + s.SupportedFeatures = v + return s +} + // SetSustainedClockSpeedInGhz sets the SustainedClockSpeedInGhz field's value. func (s *ProcessorInfo) SetSustainedClockSpeedInGhz(v float64) *ProcessorInfo { s.SustainedClockSpeedInGhz = &v @@ -153863,6 +161249,25 @@ type ProvisionByoipCidrInput struct { // Reserved. MultiRegion *bool `type:"boolean"` + // If you have Local Zones (https://docs.aws.amazon.com/local-zones/latest/ug/how-local-zones-work.html) + // enabled, you can choose a network border group for Local Zones when you provision + // and advertise a BYOIPv4 CIDR. Choose the network border group carefully as + // the EIP and the Amazon Web Services resource it is associated with must reside + // in the same network border group. + // + // You can provision BYOIP address ranges to and advertise them in the following + // Local Zone network border groups: + // + // * us-east-1-dfw-2 + // + // * us-west-2-lax-1 + // + // * us-west-2-phx-2 + // + // You cannot provision or advertise BYOIPv6 address ranges in Local Zones at + // this time. + NetworkBorderGroup *string `type:"string"` + // The tags to apply to the address pool. PoolTagSpecifications []*TagSpecification `locationName:"PoolTagSpecification" locationNameList:"item" type:"list"` @@ -153939,6 +161344,12 @@ func (s *ProvisionByoipCidrInput) SetMultiRegion(v bool) *ProvisionByoipCidrInpu return s } +// SetNetworkBorderGroup sets the NetworkBorderGroup field's value. +func (s *ProvisionByoipCidrInput) SetNetworkBorderGroup(v string) *ProvisionByoipCidrInput { + s.NetworkBorderGroup = &v + return s +} + // SetPoolTagSpecifications sets the PoolTagSpecifications field's value. func (s *ProvisionByoipCidrInput) SetPoolTagSpecifications(v []*TagSpecification) *ProvisionByoipCidrInput { s.PoolTagSpecifications = v @@ -153982,6 +161393,128 @@ func (s *ProvisionByoipCidrOutput) SetByoipCidr(v *ByoipCidr) *ProvisionByoipCid return s } +type ProvisionIpamByoasnInput struct { + _ struct{} `type:"structure"` + + // A public 2-byte or 4-byte ASN. + // + // Asn is a required field + Asn *string `type:"string" required:"true"` + + // An ASN authorization context. + // + // AsnAuthorizationContext is a required field + AsnAuthorizationContext *AsnAuthorizationContext `type:"structure" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // An IPAM ID. + // + // IpamId is a required field + IpamId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ProvisionIpamByoasnInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ProvisionIpamByoasnInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ProvisionIpamByoasnInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProvisionIpamByoasnInput"} + if s.Asn == nil { + invalidParams.Add(request.NewErrParamRequired("Asn")) + } + if s.AsnAuthorizationContext == nil { + invalidParams.Add(request.NewErrParamRequired("AsnAuthorizationContext")) + } + if s.IpamId == nil { + invalidParams.Add(request.NewErrParamRequired("IpamId")) + } + if s.AsnAuthorizationContext != nil { + if err := s.AsnAuthorizationContext.Validate(); err != nil { + invalidParams.AddNested("AsnAuthorizationContext", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAsn sets the Asn field's value. +func (s *ProvisionIpamByoasnInput) SetAsn(v string) *ProvisionIpamByoasnInput { + s.Asn = &v + return s +} + +// SetAsnAuthorizationContext sets the AsnAuthorizationContext field's value. +func (s *ProvisionIpamByoasnInput) SetAsnAuthorizationContext(v *AsnAuthorizationContext) *ProvisionIpamByoasnInput { + s.AsnAuthorizationContext = v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *ProvisionIpamByoasnInput) SetDryRun(v bool) *ProvisionIpamByoasnInput { + s.DryRun = &v + return s +} + +// SetIpamId sets the IpamId field's value. +func (s *ProvisionIpamByoasnInput) SetIpamId(v string) *ProvisionIpamByoasnInput { + s.IpamId = &v + return s +} + +type ProvisionIpamByoasnOutput struct { + _ struct{} `type:"structure"` + + // An ASN and BYOIP CIDR association. + Byoasn *Byoasn `locationName:"byoasn" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ProvisionIpamByoasnOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ProvisionIpamByoasnOutput) GoString() string { + return s.String() +} + +// SetByoasn sets the Byoasn field's value. +func (s *ProvisionIpamByoasnOutput) SetByoasn(v *Byoasn) *ProvisionIpamByoasnOutput { + s.Byoasn = v + return s +} + type ProvisionIpamPoolCidrInput struct { _ struct{} `type:"structure"` @@ -154616,6 +162149,118 @@ func (s *Purchase) SetUpfrontPrice(v string) *Purchase { return s } +type PurchaseCapacityBlockInput struct { + _ struct{} `type:"structure"` + + // The ID of the Capacity Block offering. + // + // CapacityBlockOfferingId is a required field + CapacityBlockOfferingId *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The type of operating system for which to reserve capacity. + // + // InstancePlatform is a required field + InstancePlatform *string `type:"string" required:"true" enum:"CapacityReservationInstancePlatform"` + + // The tags to apply to the Capacity Block during launch. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s PurchaseCapacityBlockInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s PurchaseCapacityBlockInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PurchaseCapacityBlockInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PurchaseCapacityBlockInput"} + if s.CapacityBlockOfferingId == nil { + invalidParams.Add(request.NewErrParamRequired("CapacityBlockOfferingId")) + } + if s.InstancePlatform == nil { + invalidParams.Add(request.NewErrParamRequired("InstancePlatform")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCapacityBlockOfferingId sets the CapacityBlockOfferingId field's value. +func (s *PurchaseCapacityBlockInput) SetCapacityBlockOfferingId(v string) *PurchaseCapacityBlockInput { + s.CapacityBlockOfferingId = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *PurchaseCapacityBlockInput) SetDryRun(v bool) *PurchaseCapacityBlockInput { + s.DryRun = &v + return s +} + +// SetInstancePlatform sets the InstancePlatform field's value. +func (s *PurchaseCapacityBlockInput) SetInstancePlatform(v string) *PurchaseCapacityBlockInput { + s.InstancePlatform = &v + return s +} + +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *PurchaseCapacityBlockInput) SetTagSpecifications(v []*TagSpecification) *PurchaseCapacityBlockInput { + s.TagSpecifications = v + return s +} + +type PurchaseCapacityBlockOutput struct { + _ struct{} `type:"structure"` + + // The Capacity Reservation. + CapacityReservation *CapacityReservation `locationName:"capacityReservation" type:"structure"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s PurchaseCapacityBlockOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s PurchaseCapacityBlockOutput) GoString() string { + return s.String() +} + +// SetCapacityReservation sets the CapacityReservation field's value. +func (s *PurchaseCapacityBlockOutput) SetCapacityReservation(v *CapacityReservation) *PurchaseCapacityBlockOutput { + s.CapacityReservation = v + return s +} + type PurchaseHostReservationInput struct { _ struct{} `type:"structure"` @@ -155229,7 +162874,7 @@ type ReferencedSecurityGroup struct { // The ID of the VPC. VpcId *string `locationName:"vpcId" type:"string"` - // The ID of the VPC peering connection. + // The ID of the VPC peering connection (if applicable). VpcPeeringConnectionId *string `locationName:"vpcPeeringConnectionId" type:"string"` } @@ -155631,7 +163276,9 @@ type RegisterInstanceEventNotificationAttributesInput struct { DryRun *bool `type:"boolean"` // Information about the tag keys to register. - InstanceTagAttribute *RegisterInstanceTagAttributeRequest `type:"structure"` + // + // InstanceTagAttribute is a required field + InstanceTagAttribute *RegisterInstanceTagAttributeRequest `type:"structure" required:"true"` } // String returns the string representation. @@ -155652,6 +163299,19 @@ func (s RegisterInstanceEventNotificationAttributesInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *RegisterInstanceEventNotificationAttributesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RegisterInstanceEventNotificationAttributesInput"} + if s.InstanceTagAttribute == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceTagAttribute")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetDryRun sets the DryRun field's value. func (s *RegisterInstanceEventNotificationAttributesInput) SetDryRun(v bool) *RegisterInstanceEventNotificationAttributesInput { s.DryRun = &v @@ -156431,7 +164091,7 @@ func (s *RejectVpcPeeringConnectionOutput) SetReturn(v bool) *RejectVpcPeeringCo type ReleaseAddressInput struct { _ struct{} `type:"structure"` - // [EC2-VPC] The allocation ID. Required for EC2-VPC. + // The allocation ID. This parameter is required. AllocationId *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -156445,12 +164105,9 @@ type ReleaseAddressInput struct { // // If you provide an incorrect network border group, you receive an InvalidAddress.NotFound // error. - // - // You cannot use a network border group with EC2 Classic. If you attempt this - // operation on EC2 classic, you receive an InvalidParameterCombination error. NetworkBorderGroup *string `type:"string"` - // [EC2-Classic] The Elastic IP address. Required for EC2-Classic. + // Deprecated. PublicIp *string `type:"string"` } @@ -158114,7 +165771,7 @@ func (s *RequestIpamResourceTag) SetValue(v string) *RequestIpamResourceTag { // // You must specify at least one parameter for the launch template data. type RequestLaunchTemplateData struct { - _ struct{} `type:"structure" sensitive:"true"` + _ struct{} `type:"structure"` // The block device mapping. BlockDeviceMappings []*LaunchTemplateBlockDeviceMappingRequest `locationName:"BlockDeviceMapping" locationNameList:"BlockDeviceMapping" type:"list"` @@ -158155,7 +165812,19 @@ type RequestLaunchTemplateData struct { // An elastic GPU to associate with the instance. ElasticGpuSpecifications []*ElasticGpuSpecification `locationName:"ElasticGpuSpecification" locationNameList:"ElasticGpuSpecification" type:"list"` - // The elastic inference accelerator for the instance. + // An elastic inference accelerator to associate with the instance. Elastic + // inference accelerators are a resource you can attach to your Amazon EC2 instances + // to accelerate your Deep Learning (DL) inference workloads. + // + // You cannot specify accelerators from different generations in the same request. + // + // Starting April 15, 2023, Amazon Web Services will not onboard new customers + // to Amazon Elastic Inference (EI), and will help current customers migrate + // their workloads to options that offer better price and performance. After + // April 15, 2023, new customers will not be able to launch instances with Amazon + // EI accelerators in Amazon SageMaker, Amazon ECS, or Amazon EC2. However, + // customers who have used Amazon EI at least once during the past 30-day period + // are considered current customers and will be able to continue using the service. ElasticInferenceAccelerators []*LaunchTemplateElasticInferenceAccelerator `locationName:"ElasticInferenceAccelerator" locationNameList:"item" type:"list"` // Indicates whether the instance is enabled for Amazon Web Services Nitro Enclaves. @@ -158188,8 +165857,14 @@ type RequestLaunchTemplateData struct { // // * resolve:ssm:parameter-name:label // - // For more information, see Use a Systems Manager parameter to find an AMI - // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html#using-systems-manager-parameter-to-find-AMI) + // * resolve:ssm:public-parameter + // + // Currently, EC2 Fleet and Spot Fleet do not support specifying a Systems Manager + // parameter. If the launch template will be used by an EC2 Fleet or Spot Fleet, + // you must specify the AMI ID. + // + // For more information, see Use a Systems Manager parameter instead of an AMI + // ID (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-launch-template.html#use-an-ssm-parameter-instead-of-an-ami-id) // in the Amazon Elastic Compute Cloud User Guide. ImageId *string `type:"string"` @@ -158205,7 +165880,37 @@ type RequestLaunchTemplateData struct { // The attributes for the instance types. When you specify instance attributes, // Amazon EC2 will identify instance types with these attributes. // + // You must specify VCpuCount and MemoryMiB. All other attributes are optional. + // Any unspecified optional attribute is set to its default. + // + // When you specify multiple attributes, you get instance types that satisfy + // all of the specified attributes. If you specify multiple values for an attribute, + // you get instance types that satisfy any of the specified values. + // + // To limit the list of instance types from which Amazon EC2 can identify matching + // instance types, you can use one of the following parameters, but not both + // in the same request: + // + // * AllowedInstanceTypes - The instance types to include in the list. All + // other instance types are ignored, even if they match your specified attributes. + // + // * ExcludedInstanceTypes - The instance types to exclude from the list, + // even if they match your specified attributes. + // // If you specify InstanceRequirements, you can't specify InstanceType. + // + // Attribute-based instance type selection is only supported when using Auto + // Scaling groups, EC2 Fleet, and Spot Fleet to launch instances. If you plan + // to use the launch template in the launch instance wizard (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html), + // or with the RunInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) + // API or AWS::EC2::Instance (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html) + // Amazon Web Services CloudFormation resource, you can't specify InstanceRequirements. + // + // For more information, see Attribute-based instance type selection for EC2 + // Fleet (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-attribute-based-instance-type-selection.html), + // Attribute-based instance type selection for Spot Fleet (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-attribute-based-instance-type-selection.html), + // and Spot placement score (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-placement-score.html) + // in the Amazon EC2 User Guide. InstanceRequirements *InstanceRequirementsRequest `type:"structure"` // The instance type. For more information, see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) @@ -158262,33 +165967,14 @@ type RequestLaunchTemplateData struct { // One or more security group IDs. You can create a security group using CreateSecurityGroup // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html). - // You cannot specify both a security group ID and security name in the same - // request. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"SecurityGroupId" type:"list"` // One or more security group names. For a nondefault VPC, you must use security - // group IDs instead. You cannot specify both a security group ID and security - // name in the same request. + // group IDs instead. SecurityGroups []*string `locationName:"SecurityGroup" locationNameList:"SecurityGroup" type:"list"` // The tags to apply to the resources that are created during instance launch. - // - // You can specify tags for the following resources only: - // - // * Instances - // - // * Volumes - // - // * Elastic graphics - // - // * Spot Instance requests - // - // * Network interfaces - // - // To tag a resource after it has been created, see CreateTags (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html). - // - // To tag the launch template itself, you must use the TagSpecification (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateLaunchTemplate.html) - // parameter. + // These tags are not applied to the launch template. TagSpecifications []*LaunchTemplateTagSpecificationRequest `locationName:"TagSpecification" locationNameList:"LaunchTemplateTagSpecificationRequest" type:"list"` // The user data to make available to the instance. You must provide base64-encoded @@ -158301,7 +165987,11 @@ type RequestLaunchTemplateData struct { // must be provided in the MIME multi-part archive format (https://cloudinit.readthedocs.io/en/latest/topics/format.html#mime-multi-part-archive). // For more information, see Amazon EC2 user data in launch templates (https://docs.aws.amazon.com/batch/latest/userguide/launch-templates.html) // in the Batch User Guide. - UserData *string `type:"string"` + // + // UserData is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by RequestLaunchTemplateData's + // String and GoString methods. + UserData *string `type:"string" sensitive:"true"` } // String returns the string representation. @@ -158859,7 +166549,7 @@ func (s *RequestSpotInstancesInput) SetValidUntil(v time.Time) *RequestSpotInsta type RequestSpotInstancesOutput struct { _ struct{} `type:"structure"` - // One or more Spot Instance requests. + // The Spot Instance requests. SpotInstanceRequests []*SpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` } @@ -158894,8 +166584,8 @@ type RequestSpotLaunchSpecification struct { // Deprecated. AddressingType *string `locationName:"addressingType" type:"string"` - // One or more block device mapping entries. You can't specify both a snapshot - // ID and an encryption value. This is because only blank volumes can be encrypted + // The block device mapping entries. You can't specify both a snapshot ID and + // an encryption value. This is because only blank volumes can be encrypted // on creation. If a snapshot is the basis for a volume, it is not blank and // its encryption status is used for the volume encryption status. BlockDeviceMappings []*BlockDeviceMapping `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` @@ -158929,8 +166619,8 @@ type RequestSpotLaunchSpecification struct { // Default: Disabled Monitoring *RunInstancesMonitoringEnabled `locationName:"monitoring" type:"structure"` - // One or more network interfaces. If you specify a network interface, you must - // specify subnet IDs and security group IDs using the network interface. + // The network interfaces. If you specify a network interface, you must specify + // subnet IDs and security group IDs using the network interface. NetworkInterfaces []*InstanceNetworkInterfaceSpecification `locationName:"NetworkInterface" locationNameList:"item" type:"list"` // The placement information for the instance. @@ -158939,12 +166629,10 @@ type RequestSpotLaunchSpecification struct { // The ID of the RAM disk. RamdiskId *string `locationName:"ramdiskId" type:"string"` - // One or more security group IDs. + // The IDs of the security groups. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"item" type:"list"` - // One or more security groups. When requesting instances in a VPC, you must - // specify the IDs of the security groups. When requesting instances in EC2-Classic, - // you can specify the names or the IDs of the security groups. + // Not supported. SecurityGroups []*string `locationName:"SecurityGroup" locationNameList:"item" type:"list"` // The ID of the subnet in which to launch the instance. @@ -159094,7 +166782,7 @@ func (s *RequestSpotLaunchSpecification) SetUserData(v string) *RequestSpotLaunc type Reservation struct { _ struct{} `type:"structure"` - // [EC2-Classic only] The security groups. + // Not supported. Groups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` // The instances. @@ -159614,8 +167302,7 @@ type ReservedInstancesConfiguration struct { // The instance type for the modified Reserved Instances. InstanceType *string `locationName:"instanceType" type:"string" enum:"InstanceType"` - // The network platform of the modified Reserved Instances, which is either - // EC2-Classic or EC2-VPC. + // The network platform of the modified Reserved Instances. Platform *string `locationName:"platform" type:"string"` // Whether the Reserved Instance is applied to instances in a Region or instances @@ -160934,7 +168621,19 @@ type ResponseLaunchTemplateData struct { // The elastic GPU specification. ElasticGpuSpecifications []*ElasticGpuSpecificationResponse `locationName:"elasticGpuSpecificationSet" locationNameList:"item" type:"list"` - // The elastic inference accelerator for the instance. + // An elastic inference accelerator to associate with the instance. Elastic + // inference accelerators are a resource you can attach to your Amazon EC2 instances + // to accelerate your Deep Learning (DL) inference workloads. + // + // You cannot specify accelerators from different generations in the same request. + // + // Starting April 15, 2023, Amazon Web Services will not onboard new customers + // to Amazon Elastic Inference (EI), and will help current customers migrate + // their workloads to options that offer better price and performance. After + // April 15, 2023, new customers will not be able to launch instances with Amazon + // EI accelerators in Amazon SageMaker, Amazon ECS, or Amazon EC2. However, + // customers who have used Amazon EI at least once during the past 30-day period + // are considered current customers and will be able to continue using the service. ElasticInferenceAccelerators []*LaunchTemplateElasticInferenceAcceleratorResponse `locationName:"elasticInferenceAcceleratorSet" locationNameList:"item" type:"list"` // Indicates whether the instance is enabled for Amazon Web Services Nitro Enclaves. @@ -161623,6 +169322,9 @@ type RestoreSnapshotFromRecycleBinOutput struct { // The ID of the snapshot. SnapshotId *string `locationName:"snapshotId" type:"string"` + // Reserved for future use. + SseType *string `locationName:"sseType" type:"string" enum:"SSEType"` + // The time stamp when the snapshot was initiated. StartTime *time.Time `locationName:"startTime" type:"timestamp"` @@ -161690,6 +169392,12 @@ func (s *RestoreSnapshotFromRecycleBinOutput) SetSnapshotId(v string) *RestoreSn return s } +// SetSseType sets the SseType field's value. +func (s *RestoreSnapshotFromRecycleBinOutput) SetSseType(v string) *RestoreSnapshotFromRecycleBinOutput { + s.SseType = &v + return s +} + // SetStartTime sets the StartTime field's value. func (s *RestoreSnapshotFromRecycleBinOutput) SetStartTime(v time.Time) *RestoreSnapshotFromRecycleBinOutput { s.StartTime = &v @@ -162172,15 +169880,12 @@ type RevokeSecurityGroupIngressInput struct { // types. FromPort *int64 `type:"integer"` - // The ID of the security group. You must specify either the security group - // ID or the security group name in the request. For security groups in a nondefault - // VPC, you must specify the security group ID. + // The ID of the security group. GroupId *string `type:"string"` - // [EC2-Classic, default VPC] The name of the security group. You must specify - // either the security group ID or the security group name in the request. For - // security groups in a nondefault VPC, you must specify the security group - // ID. + // [Default VPC] The name of the security group. You must specify either the + // security group ID or the security group name in the request. For security + // groups in a nondefault VPC, you must specify the security group ID. GroupName *string `type:"string"` // The sets of IP permissions. You can't specify a source security group and @@ -162194,20 +169899,14 @@ type RevokeSecurityGroupIngressInput struct { // The IDs of the security group rules. SecurityGroupRuleIds []*string `locationName:"SecurityGroupRuleId" locationNameList:"item" type:"list"` - // [EC2-Classic, default VPC] The name of the source security group. You can't - // specify this parameter in combination with the following parameters: the - // CIDR IP address range, the start of the port range, the IP protocol, and - // the end of the port range. For EC2-VPC, the source security group must be - // in the same VPC. To revoke a specific rule for an IP protocol and port range, - // use a set of IP permissions instead. + // [Default VPC] The name of the source security group. You can't specify this + // parameter in combination with the following parameters: the CIDR IP address + // range, the start of the port range, the IP protocol, and the end of the port + // range. The source security group must be in the same VPC. To revoke a specific + // rule for an IP protocol and port range, use a set of IP permissions instead. SourceSecurityGroupName *string `type:"string"` - // [EC2-Classic] The Amazon Web Services account ID of the source security group, - // if the source security group is in a different account. You can't specify - // this parameter in combination with the following parameters: the CIDR IP - // address range, the IP protocol, the start of the port range, and the end - // of the port range. To revoke a specific rule for an IP protocol and port - // range, use a set of IP permissions instead. + // Not supported. SourceSecurityGroupOwnerId *string `type:"string"` // If the protocol is TCP or UDP, this is the end of the port range. If the @@ -162936,6 +170635,21 @@ type RunInstancesInput struct { // are considered current customers and will be able to continue using the service. ElasticInferenceAccelerators []*ElasticInferenceAccelerator `locationName:"ElasticInferenceAccelerator" locationNameList:"item" type:"list"` + // If you’re launching an instance into a dual-stack or IPv6-only subnet, + // you can enable assigning a primary IPv6 address. A primary IPv6 address is + // an IPv6 GUA address associated with an ENI that you have enabled to use a + // primary IPv6 address. Use this option if an instance relies on its IPv6 address + // not changing. When you launch the instance, Amazon Web Services will automatically + // assign an IPv6 address associated with the ENI attached to your instance + // to be the primary IPv6 address. Once you enable an IPv6 GUA address to be + // a primary IPv6, you cannot disable it. When you enable an IPv6 GUA address + // to be a primary IPv6, the first IPv6 GUA will be made the primary IPv6 address + // until the instance is terminated or the network interface is detached. If + // you have multiple IPv6 addresses associated with an ENI attached to your + // instance and you enable a primary IPv6 address, the first IPv6 GUA address + // associated with the ENI becomes the primary IPv6 address. + EnablePrimaryIpv6 *bool `type:"boolean"` + // Indicates whether the instance is enabled for Amazon Web Services Nitro Enclaves. // For more information, see What is Amazon Web Services Nitro Enclaves? (https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) // in the Amazon Web Services Nitro Enclaves User Guide. @@ -162944,8 +170658,9 @@ type RunInstancesInput struct { // same instance. EnclaveOptions *EnclaveOptionsRequest `type:"structure"` - // Indicates whether an instance is enabled for hibernation. For more information, - // see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) + // Indicates whether an instance is enabled for hibernation. This parameter + // is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hibernating-prerequisites.html). + // For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon EC2 User Guide. // // You can't enable hibernation and Amazon Web Services Nitro Enclaves on the @@ -162973,13 +170688,11 @@ type RunInstancesInput struct { // The instance type. For more information, see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) // in the Amazon EC2 User Guide. - // - // Default: m1.small InstanceType *string `type:"string" enum:"InstanceType"` - // [EC2-VPC] The number of IPv6 addresses to associate with the primary network - // interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. - // You cannot specify this option and the option to assign specific IPv6 addresses + // The number of IPv6 addresses to associate with the primary network interface. + // Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You + // cannot specify this option and the option to assign specific IPv6 addresses // in the same request. You can specify this option if you've specified a minimum // number of instances to launch. // @@ -162987,10 +170700,10 @@ type RunInstancesInput struct { // request. Ipv6AddressCount *int64 `type:"integer"` - // [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with - // the primary network interface. You cannot specify this option and the option - // to assign a number of IPv6 addresses in the same request. You cannot specify - // this option if you've specified a minimum number of instances to launch. + // The IPv6 addresses from the range of the subnet to associate with the primary + // network interface. You cannot specify this option and the option to assign + // a number of IPv6 addresses in the same request. You cannot specify this option + // if you've specified a minimum number of instances to launch. // // You cannot specify this option and the network interfaces option in the same // request. @@ -163061,11 +170774,12 @@ type RunInstancesInput struct { Placement *Placement `type:"structure"` // The options for the instance hostname. The default values are inherited from - // the subnet. + // the subnet. Applies only if creating a network interface, not attaching an + // existing one. PrivateDnsNameOptions *PrivateDnsNameOptionsRequest `type:"structure"` - // [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 - // address range of the subnet. + // The primary IPv4 address. You must specify a value from the IPv4 address + // range of the subnet. // // Only one private IP address can be designated as primary. You can't specify // this option if you've specified the option to designate a private IP address @@ -163093,7 +170807,7 @@ type RunInstancesInput struct { // as part of the network interface. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"SecurityGroupId" type:"list"` - // [EC2-Classic, default VPC] The names of the security groups. + // [Default VPC] The names of the security groups. // // If you specify a network interface, you must specify any security groups // as part of the network interface. @@ -163101,7 +170815,7 @@ type RunInstancesInput struct { // Default: Amazon EC2 uses the default security group. SecurityGroups []*string `locationName:"SecurityGroup" locationNameList:"SecurityGroup" type:"list"` - // [EC2-VPC] The ID of the subnet to launch the instance into. + // The ID of the subnet to launch the instance into. // // If you specify a network interface, you must specify any subnets as part // of the network interface. @@ -163273,6 +170987,12 @@ func (s *RunInstancesInput) SetElasticInferenceAccelerators(v []*ElasticInferenc return s } +// SetEnablePrimaryIpv6 sets the EnablePrimaryIpv6 field's value. +func (s *RunInstancesInput) SetEnablePrimaryIpv6(v bool) *RunInstancesInput { + s.EnablePrimaryIpv6 = &v + return s +} + // SetEnclaveOptions sets the EnclaveOptions field's value. func (s *RunInstancesInput) SetEnclaveOptions(v *EnclaveOptionsRequest) *RunInstancesInput { s.EnclaveOptions = v @@ -163699,7 +171419,11 @@ type S3Storage struct { UploadPolicy []byte `locationName:"uploadPolicy" type:"blob"` // The signature of the JSON document. - UploadPolicySignature *string `locationName:"uploadPolicySignature" type:"string"` + // + // UploadPolicySignature is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by S3Storage's + // String and GoString methods. + UploadPolicySignature *string `locationName:"uploadPolicySignature" type:"string" sensitive:"true"` } // String returns the string representation. @@ -163769,7 +171493,7 @@ type ScheduledInstance struct { // The instance type. InstanceType *string `locationName:"instanceType" type:"string"` - // The network platform (EC2-Classic or EC2-VPC). + // The network platform. NetworkPlatform *string `locationName:"networkPlatform" type:"string"` // The time for the next schedule to start. @@ -163934,7 +171658,7 @@ type ScheduledInstanceAvailability struct { // The minimum term. The only possible value is 365 days. MinTermDurationInDays *int64 `locationName:"minTermDurationInDays" type:"integer"` - // The network platform (EC2-Classic or EC2-VPC). + // The network platform. NetworkPlatform *string `locationName:"networkPlatform" type:"string"` // The platform (Linux/UNIX or Windows). @@ -164276,16 +172000,8 @@ type ScheduledInstancesEbs struct { // only to instances that support them. Encrypted *bool `type:"boolean"` - // The number of I/O operations per second (IOPS) to provision for an io1 or - // io2 volume, with a maximum ratio of 50 IOPS/GiB for io1, and 500 IOPS/GiB - // for io2. Range is 100 to 64,000 IOPS for volumes in most Regions. Maximum - // IOPS of 64,000 is guaranteed only on instances built on the Nitro System - // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). - // Other instance families guarantee performance up to 32,000 IOPS. For more - // information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) - // in the Amazon EC2 User Guide. - // - // This parameter is valid only for Provisioned IOPS SSD (io1 and io2) volumes. + // The number of I/O operations per second (IOPS) to provision for a gp3, io1, + // or io2 volume. Iops *int64 `type:"integer"` // The ID of the snapshot. @@ -164297,9 +172013,7 @@ type ScheduledInstancesEbs struct { // a volume size, the default is the snapshot size. VolumeSize *int64 `type:"integer"` - // The volume type. gp2 for General Purpose SSD, io1 or io2 for Provisioned - // IOPS SSD, Throughput Optimized HDD for st1, Cold HDD for sc1, or standard - // for Magnetic. + // The volume type. // // Default: gp2 VolumeType *string `type:"string"` @@ -164647,6 +172361,11 @@ type ScheduledInstancesNetworkInterface struct { // for eth0, and can only be assigned to a new network interface, not an existing // one. You cannot specify more than one network interface in the request. If // launching into a default subnet, the default value is true. + // + // Starting on February 1, 2024, Amazon Web Services will charge for all public + // IPv4 addresses, including public IPv4 addresses associated with running instances + // and Elastic IP addresses. For more information, see the Public IPv4 Address + // tab on the Amazon VPC pricing page (http://aws.amazon.com/vpc/pricing/). AssociatePublicIpAddress *bool `type:"boolean"` // Indicates whether to delete the interface when the instance is terminated. @@ -165321,7 +173040,7 @@ type SecurityGroup struct { // The inbound rules associated with the security group. IpPermissions []*IpPermission `locationName:"ipPermissions" locationNameList:"item" type:"list"` - // [VPC only] The outbound rules associated with the security group. + // The outbound rules associated with the security group. IpPermissionsEgress []*IpPermission `locationName:"ipPermissionsEgress" locationNameList:"item" type:"list"` // The Amazon Web Services account ID of the owner of the security group. @@ -165330,7 +173049,7 @@ type SecurityGroup struct { // Any tags assigned to the security group. Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` - // [VPC only] The ID of the VPC for the security group. + // The ID of the VPC for the security group. VpcId *string `locationName:"vpcId" type:"string"` } @@ -165400,6 +173119,83 @@ func (s *SecurityGroup) SetVpcId(v string) *SecurityGroup { return s } +// A security group that can be used by interfaces in the VPC. +type SecurityGroupForVpc struct { + _ struct{} `type:"structure"` + + // The security group's description. + Description *string `locationName:"description" type:"string"` + + // The security group ID. + GroupId *string `locationName:"groupId" type:"string"` + + // The security group name. + GroupName *string `locationName:"groupName" type:"string"` + + // The security group owner ID. + OwnerId *string `locationName:"ownerId" type:"string"` + + // The VPC ID in which the security group was created. + PrimaryVpcId *string `locationName:"primaryVpcId" type:"string"` + + // The security group tags. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SecurityGroupForVpc) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SecurityGroupForVpc) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *SecurityGroupForVpc) SetDescription(v string) *SecurityGroupForVpc { + s.Description = &v + return s +} + +// SetGroupId sets the GroupId field's value. +func (s *SecurityGroupForVpc) SetGroupId(v string) *SecurityGroupForVpc { + s.GroupId = &v + return s +} + +// SetGroupName sets the GroupName field's value. +func (s *SecurityGroupForVpc) SetGroupName(v string) *SecurityGroupForVpc { + s.GroupName = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *SecurityGroupForVpc) SetOwnerId(v string) *SecurityGroupForVpc { + s.OwnerId = &v + return s +} + +// SetPrimaryVpcId sets the PrimaryVpcId field's value. +func (s *SecurityGroupForVpc) SetPrimaryVpcId(v string) *SecurityGroupForVpc { + s.PrimaryVpcId = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *SecurityGroupForVpc) SetTags(v []*Tag) *SecurityGroupForVpc { + s.Tags = v + return s +} + // Describes a security group. type SecurityGroupIdentifier struct { _ struct{} `type:"structure"` @@ -165451,7 +173247,16 @@ type SecurityGroupReference struct { // The ID of the VPC with the referencing security group. ReferencingVpcId *string `locationName:"referencingVpcId" type:"string"` - // The ID of the VPC peering connection. + // The ID of the transit gateway (if applicable). For more information about + // security group referencing for transit gateways, see Create a transit gateway + // attachment to a VPC (https://docs.aws.amazon.com/tgw/tgw-vpc-attachments.html#create-vpc-attachment) + // in the Amazon Web Services Transit Gateway Guide. + TransitGatewayId *string `locationName:"transitGatewayId" type:"string"` + + // The ID of the VPC peering connection (if applicable). For more information + // about security group referencing for peering connections, see Update your + // security groups to reference peer security groups (https://docs.aws.amazon.com/peering/vpc-peering-security-groups.html) + // in the VPC Peering Guide. VpcPeeringConnectionId *string `locationName:"vpcPeeringConnectionId" type:"string"` } @@ -165485,6 +173290,12 @@ func (s *SecurityGroupReference) SetReferencingVpcId(v string) *SecurityGroupRef return s } +// SetTransitGatewayId sets the TransitGatewayId field's value. +func (s *SecurityGroupReference) SetTransitGatewayId(v string) *SecurityGroupReference { + s.TransitGatewayId = &v + return s +} + // SetVpcPeeringConnectionId sets the VpcPeeringConnectionId field's value. func (s *SecurityGroupReference) SetVpcPeeringConnectionId(v string) *SecurityGroupReference { s.VpcPeeringConnectionId = &v @@ -166448,6 +174259,9 @@ type Snapshot struct { // is created. SnapshotId *string `locationName:"snapshotId" type:"string"` + // Reserved for future use. + SseType *string `locationName:"sseType" type:"string" enum:"SSEType"` + // The time stamp when the snapshot was initiated. StartTime *time.Time `locationName:"startTime" type:"timestamp"` @@ -166557,6 +174371,12 @@ func (s *Snapshot) SetSnapshotId(v string) *Snapshot { return s } +// SetSseType sets the SseType field's value. +func (s *Snapshot) SetSseType(v string) *Snapshot { + s.SseType = &v + return s +} + // SetStartTime sets the StartTime field's value. func (s *Snapshot) SetStartTime(v time.Time) *Snapshot { s.StartTime = &v @@ -166628,7 +174448,11 @@ type SnapshotDetail struct { StatusMessage *string `locationName:"statusMessage" type:"string"` // The URL used to access the disk image. - Url *string `locationName:"url" type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by SnapshotDetail's + // String and GoString methods. + Url *string `locationName:"url" type:"string" sensitive:"true"` // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` @@ -166726,7 +174550,11 @@ type SnapshotDiskContainer struct { // The URL to the Amazon S3-based disk image being imported. It can either be // a https URL (https://..) or an Amazon S3 URL (s3://..). - Url *string `type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by SnapshotDiskContainer's + // String and GoString methods. + Url *string `type:"string" sensitive:"true"` // The Amazon S3 bucket for the disk image. UserBucket *UserBucket `type:"structure"` @@ -166799,6 +174627,9 @@ type SnapshotInfo struct { // Snapshot id that can be used to describe this snapshot. SnapshotId *string `locationName:"snapshotId" type:"string"` + // Reserved for future use. + SseType *string `locationName:"sseType" type:"string" enum:"SSEType"` + // Time this snapshot was started. This is the same for all snapshots initiated // by the same request. StartTime *time.Time `locationName:"startTime" type:"timestamp"` @@ -166870,6 +174701,12 @@ func (s *SnapshotInfo) SetSnapshotId(v string) *SnapshotInfo { return s } +// SetSseType sets the SseType field's value. +func (s *SnapshotInfo) SetSseType(v string) *SnapshotInfo { + s.SseType = &v + return s +} + // SetStartTime sets the StartTime field's value. func (s *SnapshotInfo) SetStartTime(v time.Time) *SnapshotInfo { s.StartTime = &v @@ -167001,7 +174838,11 @@ type SnapshotTaskDetail struct { StatusMessage *string `locationName:"statusMessage" type:"string"` // The URL of the disk image from which the snapshot is created. - Url *string `locationName:"url" type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by SnapshotTaskDetail's + // String and GoString methods. + Url *string `locationName:"url" type:"string" sensitive:"true"` // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` @@ -167423,9 +175264,7 @@ type SpotFleetLaunchSpecification struct { // Resource Center and search for the kernel ID. RamdiskId *string `locationName:"ramdiskId" type:"string"` - // One or more security groups. When requesting instances in a VPC, you must - // specify the IDs of the security groups. When requesting instances in EC2-Classic, - // you can specify the names or the IDs of the security groups. + // The security groups. SecurityGroups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` // The maximum price per unit hour that you are willing to pay for a Spot Instance. @@ -167849,6 +175688,14 @@ type SpotFleetRequestConfigData struct { // it reaches the maximum amount you're willing to pay. When the maximum amount // you're willing to pay is reached, the fleet stops launching instances even // if it hasn’t met the target capacity. + // + // If your fleet includes T instances that are configured as unlimited, and + // if their average CPU usage exceeds the baseline utilization, you will incur + // a charge for surplus credits. The onDemandMaxTotalPrice does not account + // for surplus credits, and, if you use surplus credits, your final cost might + // be higher than what you specified for onDemandMaxTotalPrice. For more information, + // see Surplus credits can incur charges (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-unlimited-mode-concepts.html#unlimited-mode-surplus-credits) + // in the EC2 User Guide. OnDemandMaxTotalPrice *string `locationName:"onDemandMaxTotalPrice" type:"string"` // The number of On-Demand units to request. You can choose to set the target @@ -167866,13 +175713,21 @@ type SpotFleetRequestConfigData struct { SpotMaintenanceStrategies *SpotMaintenanceStrategies `locationName:"spotMaintenanceStrategies" type:"structure"` // The maximum amount per hour for Spot Instances that you're willing to pay. - // You can use the spotdMaxTotalPrice parameter, the onDemandMaxTotalPrice parameter, + // You can use the spotMaxTotalPrice parameter, the onDemandMaxTotalPrice parameter, // or both parameters to ensure that your fleet cost does not exceed your budget. // If you set a maximum price per hour for the On-Demand Instances and Spot // Instances in your request, Spot Fleet will launch instances until it reaches // the maximum amount you're willing to pay. When the maximum amount you're // willing to pay is reached, the fleet stops launching instances even if it // hasn’t met the target capacity. + // + // If your fleet includes T instances that are configured as unlimited, and + // if their average CPU usage exceeds the baseline utilization, you will incur + // a charge for surplus credits. The spotMaxTotalPrice does not account for + // surplus credits, and, if you use surplus credits, your final cost might be + // higher than what you specified for spotMaxTotalPrice. For more information, + // see Surplus credits can incur charges (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-unlimited-mode-concepts.html#unlimited-mode-surplus-credits) + // in the EC2 User Guide. SpotMaxTotalPrice *string `locationName:"spotMaxTotalPrice" type:"string"` // The maximum price per unit hour that you are willing to pay for a Spot Instance. @@ -167891,7 +175746,7 @@ type SpotFleetRequestConfigData struct { // (valid only if you use LaunchTemplateConfigs) or in the SpotFleetTagSpecification // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetTagSpecification.html) // (valid only if you use LaunchSpecifications). For information about tagging - // after launch, see Tagging Your Resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources). + // after launch, see Tag your resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources). TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` // The number of units to request for the Spot Fleet. You can choose to set @@ -167903,10 +175758,10 @@ type SpotFleetRequestConfigData struct { // TargetCapacity is a required field TargetCapacity *int64 `locationName:"targetCapacity" type:"integer" required:"true"` - // The unit for the target capacity. TargetCapacityUnitType can only be specified - // when InstanceRequirements is specified. + // The unit for the target capacity. You can specify this parameter only when + // using attribute-based instance type selection. // - // Default: units (translates to number of instances) + // Default: units (the number of instances) TargetCapacityUnitType *string `locationName:"targetCapacityUnitType" type:"string" enum:"TargetCapacityUnitType"` // Indicates whether running Spot Instances are terminated when the Spot Fleet @@ -168537,7 +176392,18 @@ type SpotMarketOptions struct { // Deprecated. BlockDurationMinutes *int64 `type:"integer"` - // The behavior when a Spot Instance is interrupted. The default is terminate. + // The behavior when a Spot Instance is interrupted. + // + // If Configured (for HibernationOptions (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_HibernationOptionsRequest.html)) + // is set to true, the InstanceInterruptionBehavior parameter is automatically + // set to hibernate. If you set it to stop or terminate, you'll get an error. + // + // If Configured (for HibernationOptions (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_HibernationOptionsRequest.html)) + // is set to false or null, the InstanceInterruptionBehavior parameter is automatically + // set to terminate. You can also set it to stop or hibernate. + // + // For more information, see Interruption behavior (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/interruption-behavior.html) + // in the Amazon EC2 User Guide. InstanceInterruptionBehavior *string `type:"string" enum:"InstanceInterruptionBehavior"` // The maximum hourly price that you're willing to pay for a Spot Instance. @@ -168696,6 +176562,14 @@ type SpotOptions struct { // // If you specify a maximum price, your Spot Instances will be interrupted more // frequently than if you do not specify this parameter. + // + // If your fleet includes T instances that are configured as unlimited, and + // if their average CPU usage exceeds the baseline utilization, you will incur + // a charge for surplus credits. The maxTotalPrice does not account for surplus + // credits, and, if you use surplus credits, your final cost might be higher + // than what you specified for maxTotalPrice. For more information, see Surplus + // credits can incur charges (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-unlimited-mode-concepts.html#unlimited-mode-surplus-credits) + // in the EC2 User Guide. MaxTotalPrice *string `locationName:"maxTotalPrice" type:"string"` // The minimum target capacity for Spot Instances in the fleet. If the minimum @@ -168868,6 +176742,14 @@ type SpotOptionsRequest struct { // // If you specify a maximum price, your Spot Instances will be interrupted more // frequently than if you do not specify this parameter. + // + // If your fleet includes T instances that are configured as unlimited, and + // if their average CPU usage exceeds the baseline utilization, you will incur + // a charge for surplus credits. The MaxTotalPrice does not account for surplus + // credits, and, if you use surplus credits, your final cost might be higher + // than what you specified for MaxTotalPrice. For more information, see Surplus + // credits can incur charges (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-unlimited-mode-concepts.html#unlimited-mode-surplus-credits) + // in the EC2 User Guide. MaxTotalPrice *string `type:"string"` // The minimum target capacity for Spot Instances in the fleet. If the minimum @@ -169754,8 +177636,8 @@ type StateReason struct { // the Spot price exceeded available capacity or because of an increase in // the Spot price. // - // * Client.InstanceInitiatedShutdown: The instance was shut down using the - // shutdown -h command from the instance. + // * Client.InstanceInitiatedShutdown: The instance was shut down from the + // operating system of the instance. // // * Client.InstanceTerminated: The instance was terminated or rebooted during // AMI creation. @@ -170472,6 +178354,68 @@ func (s *SubnetCidrReservation) SetTags(v []*Tag) *SubnetCidrReservation { return s } +// Describes the configuration of a subnet for a VPC endpoint. +type SubnetConfiguration struct { + _ struct{} `type:"structure"` + + // The IPv4 address to assign to the endpoint network interface in the subnet. + // You must provide an IPv4 address if the VPC endpoint supports IPv4. + // + // If you specify an IPv4 address when modifying a VPC endpoint, we replace + // the existing endpoint network interface with a new endpoint network interface + // with this IP address. This process temporarily disconnects the subnet and + // the VPC endpoint. + Ipv4 *string `type:"string"` + + // The IPv6 address to assign to the endpoint network interface in the subnet. + // You must provide an IPv6 address if the VPC endpoint supports IPv6. + // + // If you specify an IPv6 address when modifying a VPC endpoint, we replace + // the existing endpoint network interface with a new endpoint network interface + // with this IP address. This process temporarily disconnects the subnet and + // the VPC endpoint. + Ipv6 *string `type:"string"` + + // The ID of the subnet. + SubnetId *string `type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SubnetConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SubnetConfiguration) GoString() string { + return s.String() +} + +// SetIpv4 sets the Ipv4 field's value. +func (s *SubnetConfiguration) SetIpv4(v string) *SubnetConfiguration { + s.Ipv4 = &v + return s +} + +// SetIpv6 sets the Ipv6 field's value. +func (s *SubnetConfiguration) SetIpv6(v string) *SubnetConfiguration { + s.Ipv6 = &v + return s +} + +// SetSubnetId sets the SubnetId field's value. +func (s *SubnetConfiguration) SetSubnetId(v string) *SubnetConfiguration { + s.SubnetId = &v + return s +} + // Describes an association between a subnet and an IPv6 CIDR block. type SubnetIpv6CidrBlockAssociation struct { _ struct{} `type:"structure"` @@ -170829,7 +178773,7 @@ func (s *TagSpecification) SetTags(v []*Tag) *TagSpecification { type TargetCapacitySpecification struct { _ struct{} `type:"structure"` - // The default TotalTargetCapacity, which is either Spot or On-Demand. + // The default target capacity type. DefaultTargetCapacityType *string `locationName:"defaultTargetCapacityType" type:"string" enum:"DefaultTargetCapacityType"` // The number of On-Demand units to request. If you specify a target capacity @@ -170840,13 +178784,10 @@ type TargetCapacitySpecification struct { // for On-Demand units, you cannot specify a target capacity for Spot units. SpotTargetCapacity *int64 `locationName:"spotTargetCapacity" type:"integer"` - // The unit for the target capacity. TargetCapacityUnitType can only be specified - // when InstanceRequirements is specified. - // - // Default: units (translates to number of instances) + // The unit for the target capacity. TargetCapacityUnitType *string `locationName:"targetCapacityUnitType" type:"string" enum:"TargetCapacityUnitType"` - // The number of units to request, filled using DefaultTargetCapacityType. + // The number of units to request, filled the default target capacity type. TotalTargetCapacity *int64 `locationName:"totalTargetCapacity" type:"integer"` } @@ -170910,13 +178851,13 @@ func (s *TargetCapacitySpecification) SetTotalTargetCapacity(v int64) *TargetCap // On-Demand Instances and Spot Instances in your request, EC2 Fleet will launch // instances until it reaches the maximum amount that you're willing to pay. // When the maximum amount you're willing to pay is reached, the fleet stops -// launching instances even if it hasn’t met the target capacity. The MaxTotalPrice +// launching instances even if it hasn't met the target capacity. The MaxTotalPrice // parameters are located in OnDemandOptionsRequest (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_OnDemandOptionsRequest) // and SpotOptionsRequest (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotOptionsRequest). type TargetCapacitySpecificationRequest struct { _ struct{} `type:"structure"` - // The default TotalTargetCapacity, which is either Spot or On-Demand. + // The default target capacity type. DefaultTargetCapacityType *string `type:"string" enum:"DefaultTargetCapacityType"` // The number of On-Demand units to request. @@ -170925,13 +178866,14 @@ type TargetCapacitySpecificationRequest struct { // The number of Spot units to request. SpotTargetCapacity *int64 `type:"integer"` - // The unit for the target capacity. TargetCapacityUnitType can only be specified - // when InstanceRequirements is specified. + // The unit for the target capacity. You can specify this parameter only when + // using attributed-based instance type selection. // - // Default: units (translates to number of instances) + // Default: units (the number of instances) TargetCapacityUnitType *string `type:"string" enum:"TargetCapacityUnitType"` - // The number of units to request, filled using DefaultTargetCapacityType. + // The number of units to request, filled using the default target capacity + // type. // // TotalTargetCapacity is a required field TotalTargetCapacity *int64 `type:"integer" required:"true"` @@ -173591,6 +181533,20 @@ type TransitGatewayOptions struct { // The ID of the default propagation route table. PropagationDefaultRouteTableId *string `locationName:"propagationDefaultRouteTableId" type:"string"` + // Enables you to reference a security group across VPCs attached to a transit + // gateway (TGW). Use this option to simplify security group management and + // control of instance-to-instance traffic across VPCs that are connected by + // transit gateway. You can also use this option to migrate from VPC peering + // (which was the only option that supported security group referencing) to + // transit gateways (which now also support security group referencing). This + // option is disabled by default and there are no additional costs to use this + // feature. + // + // For important information about this feature, see Create a transit gateway + // (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#create-tgw) + // in the Amazon Web Services Transit Gateway Guide. + SecurityGroupReferencingSupport *string `locationName:"securityGroupReferencingSupport" type:"string" enum:"SecurityGroupReferencingSupportValue"` + // The transit gateway CIDR blocks. TransitGatewayCidrBlocks []*string `locationName:"transitGatewayCidrBlocks" locationNameList:"item" type:"list"` @@ -173664,6 +181620,12 @@ func (s *TransitGatewayOptions) SetPropagationDefaultRouteTableId(v string) *Tra return s } +// SetSecurityGroupReferencingSupport sets the SecurityGroupReferencingSupport field's value. +func (s *TransitGatewayOptions) SetSecurityGroupReferencingSupport(v string) *TransitGatewayOptions { + s.SecurityGroupReferencingSupport = &v + return s +} + // SetTransitGatewayCidrBlocks sets the TransitGatewayCidrBlocks field's value. func (s *TransitGatewayOptions) SetTransitGatewayCidrBlocks(v []*string) *TransitGatewayOptions { s.TransitGatewayCidrBlocks = v @@ -174351,6 +182313,20 @@ type TransitGatewayRequestOptions struct { // Indicates whether multicast is enabled on the transit gateway MulticastSupport *string `type:"string" enum:"MulticastSupportValue"` + // Enables you to reference a security group across VPCs attached to a transit + // gateway (TGW). Use this option to simplify security group management and + // control of instance-to-instance traffic across VPCs that are connected by + // transit gateway. You can also use this option to migrate from VPC peering + // (which was the only option that supported security group referencing) to + // transit gateways (which now also support security group referencing). This + // option is disabled by default and there are no additional costs to use this + // feature. + // + // For important information about this feature, see Create a transit gateway + // (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#create-tgw) + // in the Amazon Web Services Transit Gateway Guide. + SecurityGroupReferencingSupport *string `type:"string" enum:"SecurityGroupReferencingSupportValue"` + // One or more IPv4 or IPv6 CIDR blocks for the transit gateway. Must be a size // /24 CIDR block or larger for IPv4, or a size /64 CIDR block or larger for // IPv6. @@ -174414,6 +182390,12 @@ func (s *TransitGatewayRequestOptions) SetMulticastSupport(v string) *TransitGat return s } +// SetSecurityGroupReferencingSupport sets the SecurityGroupReferencingSupport field's value. +func (s *TransitGatewayRequestOptions) SetSecurityGroupReferencingSupport(v string) *TransitGatewayRequestOptions { + s.SecurityGroupReferencingSupport = &v + return s +} + // SetTransitGatewayCidrBlocks sets the TransitGatewayCidrBlocks field's value. func (s *TransitGatewayRequestOptions) SetTransitGatewayCidrBlocks(v []*string) *TransitGatewayRequestOptions { s.TransitGatewayCidrBlocks = v @@ -175097,6 +183079,11 @@ type TransitGatewayVpcAttachmentOptions struct { // Indicates whether IPv6 support is disabled. Ipv6Support *string `locationName:"ipv6Support" type:"string" enum:"Ipv6SupportValue"` + + // For important information about this feature, see Create a transit gateway + // attachment to a VPC (https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#create-vpc-attachment) + // in the Amazon Web Services Transit Gateway Guide. + SecurityGroupReferencingSupport *string `locationName:"securityGroupReferencingSupport" type:"string" enum:"SecurityGroupReferencingSupportValue"` } // String returns the string representation. @@ -175135,9 +183122,12 @@ func (s *TransitGatewayVpcAttachmentOptions) SetIpv6Support(v string) *TransitGa return s } -// Currently available in limited preview only. If you are interested in using -// this feature, contact your account manager. -// +// SetSecurityGroupReferencingSupport sets the SecurityGroupReferencingSupport field's value. +func (s *TransitGatewayVpcAttachmentOptions) SetSecurityGroupReferencingSupport(v string) *TransitGatewayVpcAttachmentOptions { + s.SecurityGroupReferencingSupport = &v + return s +} + // Information about an association between a branch network interface with // a trunk network interface. type TrunkInterfaceAssociation struct { @@ -175275,7 +183265,11 @@ type TunnelOption struct { // The pre-shared key (PSK) to establish initial authentication between the // virtual private gateway and the customer gateway. - PreSharedKey *string `locationName:"preSharedKey" type:"string"` + // + // PreSharedKey is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by TunnelOption's + // String and GoString methods. + PreSharedKey *string `locationName:"preSharedKey" type:"string" sensitive:"true"` // The percentage of the rekey window determined by RekeyMarginTimeSeconds during // which the rekey time is randomly selected. @@ -175658,7 +183652,7 @@ type UnassignPrivateNatGatewayAddressInput struct { // seconds. MaxDrainDurationSeconds *int64 `min:"1" type:"integer"` - // The NAT gateway ID. + // The ID of the NAT gateway. // // NatGatewayId is a required field NatGatewayId *string `type:"string" required:"true"` @@ -175736,7 +183730,7 @@ type UnassignPrivateNatGatewayAddressOutput struct { // Information about the NAT gateway IP addresses. NatGatewayAddresses []*NatGatewayAddress `locationName:"natGatewayAddressSet" locationNameList:"item" type:"list"` - // The NAT gateway ID. + // The ID of the NAT gateway. NatGatewayId *string `locationName:"natGatewayId" type:"string"` } @@ -175770,6 +183764,95 @@ func (s *UnassignPrivateNatGatewayAddressOutput) SetNatGatewayId(v string) *Unas return s } +type UnlockSnapshotInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the snapshot to unlock. + // + // SnapshotId is a required field + SnapshotId *string `type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnlockSnapshotInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnlockSnapshotInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UnlockSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UnlockSnapshotInput"} + if s.SnapshotId == nil { + invalidParams.Add(request.NewErrParamRequired("SnapshotId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *UnlockSnapshotInput) SetDryRun(v bool) *UnlockSnapshotInput { + s.DryRun = &v + return s +} + +// SetSnapshotId sets the SnapshotId field's value. +func (s *UnlockSnapshotInput) SetSnapshotId(v string) *UnlockSnapshotInput { + s.SnapshotId = &v + return s +} + +type UnlockSnapshotOutput struct { + _ struct{} `type:"structure"` + + // The ID of the snapshot. + SnapshotId *string `locationName:"snapshotId" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnlockSnapshotOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnlockSnapshotOutput) GoString() string { + return s.String() +} + +// SetSnapshotId sets the SnapshotId field's value. +func (s *UnlockSnapshotOutput) SetSnapshotId(v string) *UnlockSnapshotOutput { + s.SnapshotId = &v + return s +} + type UnmonitorInstancesInput struct { _ struct{} `type:"structure"` @@ -176042,7 +184125,7 @@ type UpdateSecurityGroupRuleDescriptionsEgressInput struct { GroupId *string `type:"string"` // [Default VPC] The name of the security group. You must specify either the - // security group ID or the security group name in the request. + // security group ID or the security group name. GroupName *string `type:"string"` // The IP permissions for the security group rule. You must specify either the @@ -176147,18 +184230,17 @@ type UpdateSecurityGroupRuleDescriptionsIngressInput struct { // VPC, you must specify the security group ID. GroupId *string `type:"string"` - // [EC2-Classic, default VPC] The name of the security group. You must specify - // either the security group ID or the security group name in the request. For - // security groups in a nondefault VPC, you must specify the security group - // ID. + // [Default VPC] The name of the security group. You must specify either the + // security group ID or the security group name. For security groups in a nondefault + // VPC, you must specify the security group ID. GroupName *string `type:"string"` // The IP permissions for the security group rule. You must specify either IP // permissions or a description. IpPermissions []*IpPermission `locationNameList:"item" type:"list"` - // [VPC only] The description for the ingress security group rules. You must - // specify either a description or IP permissions. + // The description for the ingress security group rules. You must specify either + // a description or IP permissions. SecurityGroupRuleDescriptions []*SecurityGroupRuleDescription `locationName:"SecurityGroupRuleDescription" locationNameList:"item" type:"list"` } @@ -176358,10 +184440,6 @@ func (s *UserData) SetData(v string) *UserData { } // Describes a security group and Amazon Web Services account ID pair. -// -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. type UserIdGroupPair struct { _ struct{} `type:"structure"` @@ -176375,8 +184453,7 @@ type UserIdGroupPair struct { // The ID of the security group. GroupId *string `locationName:"groupId" type:"string"` - // The name of the security group. In a request, use this parameter for a security - // group in EC2-Classic or a default VPC only. For a security group in a nondefault + // [Default VPC] The name of the security group. For a security group in a nondefault // VPC, use the security group ID. // // For a referenced security group in another VPC, this value is not returned @@ -176391,9 +184468,6 @@ type UserIdGroupPair struct { // For a referenced security group in another VPC, the account ID of the referenced // security group is returned in the response. If the referenced security group // is deleted, this value is not returned. - // - // [EC2-Classic] Required when adding or removing rules that reference a security - // group in another Amazon Web Services account. UserId *string `locationName:"userId" type:"string"` // The ID of the VPC for the referenced security group, if applicable. @@ -176761,6 +184835,9 @@ type VerifiedAccessEndpoint struct { // The IDs of the security groups for the endpoint. SecurityGroupIds []*string `locationName:"securityGroupIdSet" locationNameList:"item" type:"list"` + // The options in use for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationResponse `locationName:"sseSpecification" type:"structure"` + // The endpoint status. Status *VerifiedAccessEndpointStatus `locationName:"status" type:"structure"` @@ -176873,6 +184950,12 @@ func (s *VerifiedAccessEndpoint) SetSecurityGroupIds(v []*string) *VerifiedAcces return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *VerifiedAccessEndpoint) SetSseSpecification(v *VerifiedAccessSseSpecificationResponse) *VerifiedAccessEndpoint { + s.SseSpecification = v + return s +} + // SetStatus sets the Status field's value. func (s *VerifiedAccessEndpoint) SetStatus(v *VerifiedAccessEndpointStatus) *VerifiedAccessEndpoint { s.Status = v @@ -177073,6 +185156,9 @@ type VerifiedAccessGroup struct { // The Amazon Web Services account number that owns the group. Owner *string `locationName:"owner" type:"string"` + // The options in use for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationResponse `locationName:"sseSpecification" type:"structure"` + // The tags. Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` @@ -177134,6 +185220,12 @@ func (s *VerifiedAccessGroup) SetOwner(v string) *VerifiedAccessGroup { return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *VerifiedAccessGroup) SetSseSpecification(v *VerifiedAccessSseSpecificationResponse) *VerifiedAccessGroup { + s.SseSpecification = v + return s +} + // SetTags sets the Tags field's value. func (s *VerifiedAccessGroup) SetTags(v []*Tag) *VerifiedAccessGroup { s.Tags = v @@ -177168,6 +185260,10 @@ type VerifiedAccessInstance struct { // A description for the Amazon Web Services Verified Access instance. Description *string `locationName:"description" type:"string"` + // Indicates whether support for Federal Information Processing Standards (FIPS) + // is enabled on the instance. + FipsEnabled *bool `locationName:"fipsEnabled" type:"boolean"` + // The last updated time. LastUpdatedTime *string `locationName:"lastUpdatedTime" type:"string"` @@ -177211,6 +185307,12 @@ func (s *VerifiedAccessInstance) SetDescription(v string) *VerifiedAccessInstanc return s } +// SetFipsEnabled sets the FipsEnabled field's value. +func (s *VerifiedAccessInstance) SetFipsEnabled(v bool) *VerifiedAccessInstance { + s.FipsEnabled = &v + return s +} + // SetLastUpdatedTime sets the LastUpdatedTime field's value. func (s *VerifiedAccessInstance) SetLastUpdatedTime(v string) *VerifiedAccessInstance { s.LastUpdatedTime = &v @@ -177529,16 +185631,24 @@ func (s *VerifiedAccessLogKinesisDataFirehoseDestinationOptions) SetEnabled(v bo return s } -// Describes the destinations for Verified Access logs. +// Options for Verified Access logs. type VerifiedAccessLogOptions struct { _ struct{} `type:"structure"` // Sends Verified Access logs to CloudWatch Logs. CloudWatchLogs *VerifiedAccessLogCloudWatchLogsDestinationOptions `type:"structure"` + // Indicates whether to include trust data sent by trust providers in the logs. + IncludeTrustContext *bool `type:"boolean"` + // Sends Verified Access logs to Kinesis. KinesisDataFirehose *VerifiedAccessLogKinesisDataFirehoseDestinationOptions `type:"structure"` + // The logging version. + // + // Valid values: ocsf-0.1 | ocsf-1.0.0-rc.2 + LogVersion *string `type:"string"` + // Sends Verified Access logs to Amazon S3. S3 *VerifiedAccessLogS3DestinationOptions `type:"structure"` } @@ -177592,12 +185702,24 @@ func (s *VerifiedAccessLogOptions) SetCloudWatchLogs(v *VerifiedAccessLogCloudWa return s } +// SetIncludeTrustContext sets the IncludeTrustContext field's value. +func (s *VerifiedAccessLogOptions) SetIncludeTrustContext(v bool) *VerifiedAccessLogOptions { + s.IncludeTrustContext = &v + return s +} + // SetKinesisDataFirehose sets the KinesisDataFirehose field's value. func (s *VerifiedAccessLogOptions) SetKinesisDataFirehose(v *VerifiedAccessLogKinesisDataFirehoseDestinationOptions) *VerifiedAccessLogOptions { s.KinesisDataFirehose = v return s } +// SetLogVersion sets the LogVersion field's value. +func (s *VerifiedAccessLogOptions) SetLogVersion(v string) *VerifiedAccessLogOptions { + s.LogVersion = &v + return s +} + // SetS3 sets the S3 field's value. func (s *VerifiedAccessLogOptions) SetS3(v *VerifiedAccessLogS3DestinationOptions) *VerifiedAccessLogOptions { s.S3 = v @@ -177746,16 +185868,22 @@ func (s *VerifiedAccessLogS3DestinationOptions) SetPrefix(v string) *VerifiedAcc return s } -// Describes the destinations for Verified Access logs. +// Describes the options for Verified Access logs. type VerifiedAccessLogs struct { _ struct{} `type:"structure"` // CloudWatch Logs logging destination. CloudWatchLogs *VerifiedAccessLogCloudWatchLogsDestination `locationName:"cloudWatchLogs" type:"structure"` + // Indicates whether trust data is included in the logs. + IncludeTrustContext *bool `locationName:"includeTrustContext" type:"boolean"` + // Kinesis logging destination. KinesisDataFirehose *VerifiedAccessLogKinesisDataFirehoseDestination `locationName:"kinesisDataFirehose" type:"structure"` + // The log version. + LogVersion *string `locationName:"logVersion" type:"string"` + // Amazon S3 logging options. S3 *VerifiedAccessLogS3Destination `locationName:"s3" type:"structure"` } @@ -177784,18 +185912,118 @@ func (s *VerifiedAccessLogs) SetCloudWatchLogs(v *VerifiedAccessLogCloudWatchLog return s } +// SetIncludeTrustContext sets the IncludeTrustContext field's value. +func (s *VerifiedAccessLogs) SetIncludeTrustContext(v bool) *VerifiedAccessLogs { + s.IncludeTrustContext = &v + return s +} + // SetKinesisDataFirehose sets the KinesisDataFirehose field's value. func (s *VerifiedAccessLogs) SetKinesisDataFirehose(v *VerifiedAccessLogKinesisDataFirehoseDestination) *VerifiedAccessLogs { s.KinesisDataFirehose = v return s } +// SetLogVersion sets the LogVersion field's value. +func (s *VerifiedAccessLogs) SetLogVersion(v string) *VerifiedAccessLogs { + s.LogVersion = &v + return s +} + // SetS3 sets the S3 field's value. func (s *VerifiedAccessLogs) SetS3(v *VerifiedAccessLogS3Destination) *VerifiedAccessLogs { s.S3 = v return s } +// Verified Access provides server side encryption by default to data at rest +// using Amazon Web Services-owned KMS keys. You also have the option of using +// customer managed KMS keys, which can be specified using the options below. +type VerifiedAccessSseSpecificationRequest struct { + _ struct{} `type:"structure"` + + // Enable or disable the use of customer managed KMS keys for server side encryption. + // + // Valid values: True | False + CustomerManagedKeyEnabled *bool `type:"boolean"` + + // The ARN of the KMS key. + KmsKeyArn *string `type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s VerifiedAccessSseSpecificationRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s VerifiedAccessSseSpecificationRequest) GoString() string { + return s.String() +} + +// SetCustomerManagedKeyEnabled sets the CustomerManagedKeyEnabled field's value. +func (s *VerifiedAccessSseSpecificationRequest) SetCustomerManagedKeyEnabled(v bool) *VerifiedAccessSseSpecificationRequest { + s.CustomerManagedKeyEnabled = &v + return s +} + +// SetKmsKeyArn sets the KmsKeyArn field's value. +func (s *VerifiedAccessSseSpecificationRequest) SetKmsKeyArn(v string) *VerifiedAccessSseSpecificationRequest { + s.KmsKeyArn = &v + return s +} + +// The options in use for server side encryption. +type VerifiedAccessSseSpecificationResponse struct { + _ struct{} `type:"structure"` + + // Indicates whether customer managed KMS keys are in use for server side encryption. + // + // Valid values: True | False + CustomerManagedKeyEnabled *bool `locationName:"customerManagedKeyEnabled" type:"boolean"` + + // The ARN of the KMS key. + KmsKeyArn *string `locationName:"kmsKeyArn" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s VerifiedAccessSseSpecificationResponse) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s VerifiedAccessSseSpecificationResponse) GoString() string { + return s.String() +} + +// SetCustomerManagedKeyEnabled sets the CustomerManagedKeyEnabled field's value. +func (s *VerifiedAccessSseSpecificationResponse) SetCustomerManagedKeyEnabled(v bool) *VerifiedAccessSseSpecificationResponse { + s.CustomerManagedKeyEnabled = &v + return s +} + +// SetKmsKeyArn sets the KmsKeyArn field's value. +func (s *VerifiedAccessSseSpecificationResponse) SetKmsKeyArn(v string) *VerifiedAccessSseSpecificationResponse { + s.KmsKeyArn = &v + return s +} + // Describes a Verified Access trust provider. type VerifiedAccessTrustProvider struct { _ struct{} `type:"structure"` @@ -177806,7 +186034,7 @@ type VerifiedAccessTrustProvider struct { // A description for the Amazon Web Services Verified Access trust provider. Description *string `locationName:"description" type:"string"` - // The options for device-identity type trust provider. + // The options for device-identity trust provider. DeviceOptions *DeviceOptions `locationName:"deviceOptions" type:"structure"` // The type of device-based trust provider. @@ -177815,12 +186043,15 @@ type VerifiedAccessTrustProvider struct { // The last updated time. LastUpdatedTime *string `locationName:"lastUpdatedTime" type:"string"` - // The OpenID Connect details for an oidc-type, user-identity based trust provider. + // The options for an OpenID Connect-compatible user-identity trust provider. OidcOptions *OidcOptions `locationName:"oidcOptions" type:"structure"` // The identifier to be used when working with policy rules. PolicyReferenceName *string `locationName:"policyReferenceName" type:"string"` + // The options in use for server side encryption. + SseSpecification *VerifiedAccessSseSpecificationResponse `locationName:"sseSpecification" type:"structure"` + // The tags. Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` @@ -177894,6 +186125,12 @@ func (s *VerifiedAccessTrustProvider) SetPolicyReferenceName(v string) *Verified return s } +// SetSseSpecification sets the SseSpecification field's value. +func (s *VerifiedAccessTrustProvider) SetSseSpecification(v *VerifiedAccessSseSpecificationResponse) *VerifiedAccessTrustProvider { + s.SseSpecification = v + return s +} + // SetTags sets the Tags field's value. func (s *VerifiedAccessTrustProvider) SetTags(v []*Tag) *VerifiedAccessTrustProvider { s.Tags = v @@ -177996,7 +186233,8 @@ type VgwTelemetry struct { // The Amazon Resource Name (ARN) of the VPN tunnel endpoint certificate. CertificateArn *string `locationName:"certificateArn" type:"string"` - // The date and time of the last change in status. + // The date and time of the last change in status. This field is updated when + // changes in IKE (Phase 1), IPSec (Phase 2), or BGP status are detected. LastStatusChange *time.Time `locationName:"lastStatusChange" type:"timestamp"` // The Internet-routable IP address of the virtual private gateway's outside @@ -178105,6 +186343,9 @@ type Volume struct { // The snapshot from which the volume was created, if applicable. SnapshotId *string `locationName:"snapshotId" type:"string"` + // Reserved for future use. + SseType *string `locationName:"sseType" type:"string" enum:"SSEType"` + // The volume state. State *string `locationName:"status" type:"string" enum:"VolumeState"` @@ -178205,6 +186446,12 @@ func (s *Volume) SetSnapshotId(v string) *Volume { return s } +// SetSseType sets the SseType field's value. +func (s *Volume) SetSseType(v string) *Volume { + s.SseType = &v + return s +} + // SetState sets the State field's value. func (s *Volume) SetState(v string) *Volume { s.State = &v @@ -178239,6 +186486,9 @@ func (s *Volume) SetVolumeType(v string) *Volume { type VolumeAttachment struct { _ struct{} `type:"structure"` + // The ARN of the Amazon ECS or Fargate task to which the volume is attached. + AssociatedResource *string `locationName:"associatedResource" type:"string"` + // The time stamp when the attachment initiated. AttachTime *time.Time `locationName:"attachTime" type:"timestamp"` @@ -178246,11 +186496,22 @@ type VolumeAttachment struct { DeleteOnTermination *bool `locationName:"deleteOnTermination" type:"boolean"` // The device name. + // + // If the volume is attached to a Fargate task, this parameter returns null. Device *string `locationName:"device" type:"string"` // The ID of the instance. + // + // If the volume is attached to a Fargate task, this parameter returns null. InstanceId *string `locationName:"instanceId" type:"string"` + // The service principal of Amazon Web Services service that owns the underlying + // instance to which the volume is attached. + // + // This parameter is returned only for volumes that are attached to Fargate + // tasks. + InstanceOwningService *string `locationName:"instanceOwningService" type:"string"` + // The attachment state of the volume. State *string `locationName:"status" type:"string" enum:"VolumeAttachmentState"` @@ -178276,6 +186537,12 @@ func (s VolumeAttachment) GoString() string { return s.String() } +// SetAssociatedResource sets the AssociatedResource field's value. +func (s *VolumeAttachment) SetAssociatedResource(v string) *VolumeAttachment { + s.AssociatedResource = &v + return s +} + // SetAttachTime sets the AttachTime field's value. func (s *VolumeAttachment) SetAttachTime(v time.Time) *VolumeAttachment { s.AttachTime = &v @@ -178300,6 +186567,12 @@ func (s *VolumeAttachment) SetInstanceId(v string) *VolumeAttachment { return s } +// SetInstanceOwningService sets the InstanceOwningService field's value. +func (s *VolumeAttachment) SetInstanceOwningService(v string) *VolumeAttachment { + s.InstanceOwningService = &v + return s +} + // SetState sets the State field's value. func (s *VolumeAttachment) SetState(v string) *VolumeAttachment { s.State = &v @@ -179119,9 +187392,7 @@ func (s *VpcCidrBlockState) SetStatusMessage(v string) *VpcCidrBlockState { return s } -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. +// Deprecated. // // Describes whether a VPC is enabled for ClassicLink. type VpcClassicLink struct { @@ -179640,10 +187911,6 @@ func (s *VpcPeeringConnection) SetVpcPeeringConnectionId(v string) *VpcPeeringCo return s } -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Describes the VPC peering connection options. type VpcPeeringConnectionOptionsDescription struct { _ struct{} `type:"structure"` @@ -179652,12 +187919,10 @@ type VpcPeeringConnectionOptionsDescription struct { // IP addresses when queried from instances in a peer VPC. AllowDnsResolutionFromRemoteVpc *bool `locationName:"allowDnsResolutionFromRemoteVpc" type:"boolean"` - // Indicates whether a local ClassicLink connection can communicate with the - // peer VPC over the VPC peering connection. + // Deprecated. AllowEgressFromLocalClassicLinkToRemoteVpc *bool `locationName:"allowEgressFromLocalClassicLinkToRemoteVpc" type:"boolean"` - // Indicates whether a local VPC can communicate with a ClassicLink connection - // in the peer VPC over the VPC peering connection. + // Deprecated. AllowEgressFromLocalVpcToRemoteClassicLink *bool `locationName:"allowEgressFromLocalVpcToRemoteClassicLink" type:"boolean"` } @@ -179844,7 +188109,11 @@ type VpnConnection struct { // the native XML format). This element is always present in the CreateVpnConnection // response; however, it's present in the DescribeVpnConnections response only // if the VPN connection is in the pending or available state. - CustomerGatewayConfiguration *string `locationName:"customerGatewayConfiguration" type:"string"` + // + // CustomerGatewayConfiguration is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by VpnConnection's + // String and GoString methods. + CustomerGatewayConfiguration *string `locationName:"customerGatewayConfiguration" type:"string" sensitive:"true"` // The ID of the customer gateway at your end of the VPN connection. CustomerGatewayId *string `locationName:"customerGatewayId" type:"string"` @@ -180594,7 +188863,11 @@ type VpnTunnelOptionsSpecification struct { // Constraints: Allowed characters are alphanumeric characters, periods (.), // and underscores (_). Must be between 8 and 64 characters in length and cannot // start with zero (0). - PreSharedKey *string `type:"string"` + // + // PreSharedKey is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by VpnTunnelOptionsSpecification's + // String and GoString methods. + PreSharedKey *string `type:"string" sensitive:"true"` // The percentage of the rekey window (determined by RekeyMarginTimeSeconds) // during which the rekey time is randomly selected. @@ -180888,26 +189161,30 @@ func (s *WithdrawByoipCidrOutput) SetByoipCidr(v *ByoipCidr) *WithdrawByoipCidrO } const ( - // AcceleratorManufacturerNvidia is a AcceleratorManufacturer enum value - AcceleratorManufacturerNvidia = "nvidia" + // AcceleratorManufacturerAmazonWebServices is a AcceleratorManufacturer enum value + AcceleratorManufacturerAmazonWebServices = "amazon-web-services" // AcceleratorManufacturerAmd is a AcceleratorManufacturer enum value AcceleratorManufacturerAmd = "amd" - // AcceleratorManufacturerAmazonWebServices is a AcceleratorManufacturer enum value - AcceleratorManufacturerAmazonWebServices = "amazon-web-services" + // AcceleratorManufacturerNvidia is a AcceleratorManufacturer enum value + AcceleratorManufacturerNvidia = "nvidia" // AcceleratorManufacturerXilinx is a AcceleratorManufacturer enum value AcceleratorManufacturerXilinx = "xilinx" + + // AcceleratorManufacturerHabana is a AcceleratorManufacturer enum value + AcceleratorManufacturerHabana = "habana" ) // AcceleratorManufacturer_Values returns all elements of the AcceleratorManufacturer enum func AcceleratorManufacturer_Values() []string { return []string{ - AcceleratorManufacturerNvidia, - AcceleratorManufacturerAmd, AcceleratorManufacturerAmazonWebServices, + AcceleratorManufacturerAmd, + AcceleratorManufacturerNvidia, AcceleratorManufacturerXilinx, + AcceleratorManufacturerHabana, } } @@ -180915,43 +189192,55 @@ const ( // AcceleratorNameA100 is a AcceleratorName enum value AcceleratorNameA100 = "a100" - // AcceleratorNameV100 is a AcceleratorName enum value - AcceleratorNameV100 = "v100" + // AcceleratorNameInferentia is a AcceleratorName enum value + AcceleratorNameInferentia = "inferentia" + + // AcceleratorNameK520 is a AcceleratorName enum value + AcceleratorNameK520 = "k520" // AcceleratorNameK80 is a AcceleratorName enum value AcceleratorNameK80 = "k80" - // AcceleratorNameT4 is a AcceleratorName enum value - AcceleratorNameT4 = "t4" - // AcceleratorNameM60 is a AcceleratorName enum value AcceleratorNameM60 = "m60" // AcceleratorNameRadeonProV520 is a AcceleratorName enum value AcceleratorNameRadeonProV520 = "radeon-pro-v520" + // AcceleratorNameT4 is a AcceleratorName enum value + AcceleratorNameT4 = "t4" + // AcceleratorNameVu9p is a AcceleratorName enum value AcceleratorNameVu9p = "vu9p" - // AcceleratorNameInferentia is a AcceleratorName enum value - AcceleratorNameInferentia = "inferentia" + // AcceleratorNameV100 is a AcceleratorName enum value + AcceleratorNameV100 = "v100" - // AcceleratorNameK520 is a AcceleratorName enum value - AcceleratorNameK520 = "k520" + // AcceleratorNameA10g is a AcceleratorName enum value + AcceleratorNameA10g = "a10g" + + // AcceleratorNameH100 is a AcceleratorName enum value + AcceleratorNameH100 = "h100" + + // AcceleratorNameT4g is a AcceleratorName enum value + AcceleratorNameT4g = "t4g" ) // AcceleratorName_Values returns all elements of the AcceleratorName enum func AcceleratorName_Values() []string { return []string{ AcceleratorNameA100, - AcceleratorNameV100, + AcceleratorNameInferentia, + AcceleratorNameK520, AcceleratorNameK80, - AcceleratorNameT4, AcceleratorNameM60, AcceleratorNameRadeonProV520, + AcceleratorNameT4, AcceleratorNameVu9p, - AcceleratorNameInferentia, - AcceleratorNameK520, + AcceleratorNameV100, + AcceleratorNameA10g, + AcceleratorNameH100, + AcceleratorNameT4g, } } @@ -181167,6 +189456,22 @@ func AllowsMultipleInstanceTypes_Values() []string { } } +const ( + // AmdSevSnpSpecificationEnabled is a AmdSevSnpSpecification enum value + AmdSevSnpSpecificationEnabled = "enabled" + + // AmdSevSnpSpecificationDisabled is a AmdSevSnpSpecification enum value + AmdSevSnpSpecificationDisabled = "disabled" +) + +// AmdSevSnpSpecification_Values returns all elements of the AmdSevSnpSpecification enum +func AmdSevSnpSpecification_Values() []string { + return []string{ + AmdSevSnpSpecificationEnabled, + AmdSevSnpSpecificationDisabled, + } +} + const ( // AnalysisStatusRunning is a AnalysisStatus enum value AnalysisStatusRunning = "running" @@ -181259,6 +189564,70 @@ func ArchitectureValues_Values() []string { } } +const ( + // AsnAssociationStateDisassociated is a AsnAssociationState enum value + AsnAssociationStateDisassociated = "disassociated" + + // AsnAssociationStateFailedDisassociation is a AsnAssociationState enum value + AsnAssociationStateFailedDisassociation = "failed-disassociation" + + // AsnAssociationStateFailedAssociation is a AsnAssociationState enum value + AsnAssociationStateFailedAssociation = "failed-association" + + // AsnAssociationStatePendingDisassociation is a AsnAssociationState enum value + AsnAssociationStatePendingDisassociation = "pending-disassociation" + + // AsnAssociationStatePendingAssociation is a AsnAssociationState enum value + AsnAssociationStatePendingAssociation = "pending-association" + + // AsnAssociationStateAssociated is a AsnAssociationState enum value + AsnAssociationStateAssociated = "associated" +) + +// AsnAssociationState_Values returns all elements of the AsnAssociationState enum +func AsnAssociationState_Values() []string { + return []string{ + AsnAssociationStateDisassociated, + AsnAssociationStateFailedDisassociation, + AsnAssociationStateFailedAssociation, + AsnAssociationStatePendingDisassociation, + AsnAssociationStatePendingAssociation, + AsnAssociationStateAssociated, + } +} + +const ( + // AsnStateDeprovisioned is a AsnState enum value + AsnStateDeprovisioned = "deprovisioned" + + // AsnStateFailedDeprovision is a AsnState enum value + AsnStateFailedDeprovision = "failed-deprovision" + + // AsnStateFailedProvision is a AsnState enum value + AsnStateFailedProvision = "failed-provision" + + // AsnStatePendingDeprovision is a AsnState enum value + AsnStatePendingDeprovision = "pending-deprovision" + + // AsnStatePendingProvision is a AsnState enum value + AsnStatePendingProvision = "pending-provision" + + // AsnStateProvisioned is a AsnState enum value + AsnStateProvisioned = "provisioned" +) + +// AsnState_Values returns all elements of the AsnState enum +func AsnState_Values() []string { + return []string{ + AsnStateDeprovisioned, + AsnStateFailedDeprovision, + AsnStateFailedProvision, + AsnStatePendingDeprovision, + AsnStatePendingProvision, + AsnStateProvisioned, + } +} + const ( // AssociatedNetworkTypeVpc is a AssociatedNetworkType enum value AssociatedNetworkTypeVpc = "vpc" @@ -181766,6 +190135,9 @@ const ( // CapacityReservationInstancePlatformRhelwithHaandSqlserverEnterprise is a CapacityReservationInstancePlatform enum value CapacityReservationInstancePlatformRhelwithHaandSqlserverEnterprise = "RHEL with HA and SQL Server Enterprise" + + // CapacityReservationInstancePlatformUbuntuPro is a CapacityReservationInstancePlatform enum value + CapacityReservationInstancePlatformUbuntuPro = "Ubuntu Pro" ) // CapacityReservationInstancePlatform_Values returns all elements of the CapacityReservationInstancePlatform enum @@ -181788,6 +190160,7 @@ func CapacityReservationInstancePlatform_Values() []string { CapacityReservationInstancePlatformRhelwithHa, CapacityReservationInstancePlatformRhelwithHaandSqlserverStandard, CapacityReservationInstancePlatformRhelwithHaandSqlserverEnterprise, + CapacityReservationInstancePlatformUbuntuPro, } } @@ -181822,6 +190195,15 @@ const ( // CapacityReservationStateFailed is a CapacityReservationState enum value CapacityReservationStateFailed = "failed" + + // CapacityReservationStateScheduled is a CapacityReservationState enum value + CapacityReservationStateScheduled = "scheduled" + + // CapacityReservationStatePaymentPending is a CapacityReservationState enum value + CapacityReservationStatePaymentPending = "payment-pending" + + // CapacityReservationStatePaymentFailed is a CapacityReservationState enum value + CapacityReservationStatePaymentFailed = "payment-failed" ) // CapacityReservationState_Values returns all elements of the CapacityReservationState enum @@ -181832,6 +190214,9 @@ func CapacityReservationState_Values() []string { CapacityReservationStateCancelled, CapacityReservationStatePending, CapacityReservationStateFailed, + CapacityReservationStateScheduled, + CapacityReservationStatePaymentPending, + CapacityReservationStatePaymentFailed, } } @@ -181851,6 +190236,22 @@ func CapacityReservationTenancy_Values() []string { } } +const ( + // CapacityReservationTypeDefault is a CapacityReservationType enum value + CapacityReservationTypeDefault = "default" + + // CapacityReservationTypeCapacityBlock is a CapacityReservationType enum value + CapacityReservationTypeCapacityBlock = "capacity-block" +) + +// CapacityReservationType_Values returns all elements of the CapacityReservationType enum +func CapacityReservationType_Values() []string { + return []string{ + CapacityReservationTypeDefault, + CapacityReservationTypeCapacityBlock, + } +} + const ( // CarrierGatewayStatePending is a CarrierGatewayState enum value CarrierGatewayStatePending = "pending" @@ -182201,6 +190602,9 @@ const ( // DefaultTargetCapacityTypeOnDemand is a DefaultTargetCapacityType enum value DefaultTargetCapacityTypeOnDemand = "on-demand" + + // DefaultTargetCapacityTypeCapacityBlock is a DefaultTargetCapacityType enum value + DefaultTargetCapacityTypeCapacityBlock = "capacity-block" ) // DefaultTargetCapacityType_Values returns all elements of the DefaultTargetCapacityType enum @@ -182208,6 +190612,7 @@ func DefaultTargetCapacityType_Values() []string { return []string{ DefaultTargetCapacityTypeSpot, DefaultTargetCapacityTypeOnDemand, + DefaultTargetCapacityTypeCapacityBlock, } } @@ -182277,6 +190682,9 @@ const ( // DeviceTrustProviderTypeCrowdstrike is a DeviceTrustProviderType enum value DeviceTrustProviderTypeCrowdstrike = "crowdstrike" + + // DeviceTrustProviderTypeJumpcloud is a DeviceTrustProviderType enum value + DeviceTrustProviderTypeJumpcloud = "jumpcloud" ) // DeviceTrustProviderType_Values returns all elements of the DeviceTrustProviderType enum @@ -182284,6 +190692,7 @@ func DeviceTrustProviderType_Values() []string { return []string{ DeviceTrustProviderTypeJamf, DeviceTrustProviderTypeCrowdstrike, + DeviceTrustProviderTypeJumpcloud, } } @@ -182487,6 +190896,38 @@ func EbsOptimizedSupport_Values() []string { } } +const ( + // Ec2InstanceConnectEndpointStateCreateInProgress is a Ec2InstanceConnectEndpointState enum value + Ec2InstanceConnectEndpointStateCreateInProgress = "create-in-progress" + + // Ec2InstanceConnectEndpointStateCreateComplete is a Ec2InstanceConnectEndpointState enum value + Ec2InstanceConnectEndpointStateCreateComplete = "create-complete" + + // Ec2InstanceConnectEndpointStateCreateFailed is a Ec2InstanceConnectEndpointState enum value + Ec2InstanceConnectEndpointStateCreateFailed = "create-failed" + + // Ec2InstanceConnectEndpointStateDeleteInProgress is a Ec2InstanceConnectEndpointState enum value + Ec2InstanceConnectEndpointStateDeleteInProgress = "delete-in-progress" + + // Ec2InstanceConnectEndpointStateDeleteComplete is a Ec2InstanceConnectEndpointState enum value + Ec2InstanceConnectEndpointStateDeleteComplete = "delete-complete" + + // Ec2InstanceConnectEndpointStateDeleteFailed is a Ec2InstanceConnectEndpointState enum value + Ec2InstanceConnectEndpointStateDeleteFailed = "delete-failed" +) + +// Ec2InstanceConnectEndpointState_Values returns all elements of the Ec2InstanceConnectEndpointState enum +func Ec2InstanceConnectEndpointState_Values() []string { + return []string{ + Ec2InstanceConnectEndpointStateCreateInProgress, + Ec2InstanceConnectEndpointStateCreateComplete, + Ec2InstanceConnectEndpointStateCreateFailed, + Ec2InstanceConnectEndpointStateDeleteInProgress, + Ec2InstanceConnectEndpointStateDeleteComplete, + Ec2InstanceConnectEndpointStateDeleteFailed, + } +} + const ( // ElasticGpuStateAttached is a ElasticGpuState enum value ElasticGpuStateAttached = "ATTACHED" @@ -183263,6 +191704,30 @@ func ImageAttributeName_Values() []string { } } +const ( + // ImageBlockPublicAccessDisabledStateUnblocked is a ImageBlockPublicAccessDisabledState enum value + ImageBlockPublicAccessDisabledStateUnblocked = "unblocked" +) + +// ImageBlockPublicAccessDisabledState_Values returns all elements of the ImageBlockPublicAccessDisabledState enum +func ImageBlockPublicAccessDisabledState_Values() []string { + return []string{ + ImageBlockPublicAccessDisabledStateUnblocked, + } +} + +const ( + // ImageBlockPublicAccessEnabledStateBlockNewSharing is a ImageBlockPublicAccessEnabledState enum value + ImageBlockPublicAccessEnabledStateBlockNewSharing = "block-new-sharing" +) + +// ImageBlockPublicAccessEnabledState_Values returns all elements of the ImageBlockPublicAccessEnabledState enum +func ImageBlockPublicAccessEnabledState_Values() []string { + return []string{ + ImageBlockPublicAccessEnabledStateBlockNewSharing, + } +} + const ( // ImageStatePending is a ImageState enum value ImageStatePending = "pending" @@ -183284,6 +191749,9 @@ const ( // ImageStateError is a ImageState enum value ImageStateError = "error" + + // ImageStateDisabled is a ImageState enum value + ImageStateDisabled = "disabled" ) // ImageState_Values returns all elements of the ImageState enum @@ -183296,6 +191764,7 @@ func ImageState_Values() []string { ImageStateTransient, ImageStateFailed, ImageStateError, + ImageStateDisabled, } } @@ -183533,6 +192002,9 @@ const ( // InstanceLifecycleTypeScheduled is a InstanceLifecycleType enum value InstanceLifecycleTypeScheduled = "scheduled" + + // InstanceLifecycleTypeCapacityBlock is a InstanceLifecycleType enum value + InstanceLifecycleTypeCapacityBlock = "capacity-block" ) // InstanceLifecycleType_Values returns all elements of the InstanceLifecycleType enum @@ -183540,6 +192012,7 @@ func InstanceLifecycleType_Values() []string { return []string{ InstanceLifecycleTypeSpot, InstanceLifecycleTypeScheduled, + InstanceLifecycleTypeCapacityBlock, } } @@ -185600,6 +194073,426 @@ const ( // InstanceTypeR6idnMetal is a InstanceType enum value InstanceTypeR6idnMetal = "r6idn.metal" + + // InstanceTypeInf2Xlarge is a InstanceType enum value + InstanceTypeInf2Xlarge = "inf2.xlarge" + + // InstanceTypeInf28xlarge is a InstanceType enum value + InstanceTypeInf28xlarge = "inf2.8xlarge" + + // InstanceTypeInf224xlarge is a InstanceType enum value + InstanceTypeInf224xlarge = "inf2.24xlarge" + + // InstanceTypeInf248xlarge is a InstanceType enum value + InstanceTypeInf248xlarge = "inf2.48xlarge" + + // InstanceTypeTrn1n32xlarge is a InstanceType enum value + InstanceTypeTrn1n32xlarge = "trn1n.32xlarge" + + // InstanceTypeI4gLarge is a InstanceType enum value + InstanceTypeI4gLarge = "i4g.large" + + // InstanceTypeI4gXlarge is a InstanceType enum value + InstanceTypeI4gXlarge = "i4g.xlarge" + + // InstanceTypeI4g2xlarge is a InstanceType enum value + InstanceTypeI4g2xlarge = "i4g.2xlarge" + + // InstanceTypeI4g4xlarge is a InstanceType enum value + InstanceTypeI4g4xlarge = "i4g.4xlarge" + + // InstanceTypeI4g8xlarge is a InstanceType enum value + InstanceTypeI4g8xlarge = "i4g.8xlarge" + + // InstanceTypeI4g16xlarge is a InstanceType enum value + InstanceTypeI4g16xlarge = "i4g.16xlarge" + + // InstanceTypeHpc7g4xlarge is a InstanceType enum value + InstanceTypeHpc7g4xlarge = "hpc7g.4xlarge" + + // InstanceTypeHpc7g8xlarge is a InstanceType enum value + InstanceTypeHpc7g8xlarge = "hpc7g.8xlarge" + + // InstanceTypeHpc7g16xlarge is a InstanceType enum value + InstanceTypeHpc7g16xlarge = "hpc7g.16xlarge" + + // InstanceTypeC7gnMedium is a InstanceType enum value + InstanceTypeC7gnMedium = "c7gn.medium" + + // InstanceTypeC7gnLarge is a InstanceType enum value + InstanceTypeC7gnLarge = "c7gn.large" + + // InstanceTypeC7gnXlarge is a InstanceType enum value + InstanceTypeC7gnXlarge = "c7gn.xlarge" + + // InstanceTypeC7gn2xlarge is a InstanceType enum value + InstanceTypeC7gn2xlarge = "c7gn.2xlarge" + + // InstanceTypeC7gn4xlarge is a InstanceType enum value + InstanceTypeC7gn4xlarge = "c7gn.4xlarge" + + // InstanceTypeC7gn8xlarge is a InstanceType enum value + InstanceTypeC7gn8xlarge = "c7gn.8xlarge" + + // InstanceTypeC7gn12xlarge is a InstanceType enum value + InstanceTypeC7gn12xlarge = "c7gn.12xlarge" + + // InstanceTypeC7gn16xlarge is a InstanceType enum value + InstanceTypeC7gn16xlarge = "c7gn.16xlarge" + + // InstanceTypeP548xlarge is a InstanceType enum value + InstanceTypeP548xlarge = "p5.48xlarge" + + // InstanceTypeM7iLarge is a InstanceType enum value + InstanceTypeM7iLarge = "m7i.large" + + // InstanceTypeM7iXlarge is a InstanceType enum value + InstanceTypeM7iXlarge = "m7i.xlarge" + + // InstanceTypeM7i2xlarge is a InstanceType enum value + InstanceTypeM7i2xlarge = "m7i.2xlarge" + + // InstanceTypeM7i4xlarge is a InstanceType enum value + InstanceTypeM7i4xlarge = "m7i.4xlarge" + + // InstanceTypeM7i8xlarge is a InstanceType enum value + InstanceTypeM7i8xlarge = "m7i.8xlarge" + + // InstanceTypeM7i12xlarge is a InstanceType enum value + InstanceTypeM7i12xlarge = "m7i.12xlarge" + + // InstanceTypeM7i16xlarge is a InstanceType enum value + InstanceTypeM7i16xlarge = "m7i.16xlarge" + + // InstanceTypeM7i24xlarge is a InstanceType enum value + InstanceTypeM7i24xlarge = "m7i.24xlarge" + + // InstanceTypeM7i48xlarge is a InstanceType enum value + InstanceTypeM7i48xlarge = "m7i.48xlarge" + + // InstanceTypeM7iFlexLarge is a InstanceType enum value + InstanceTypeM7iFlexLarge = "m7i-flex.large" + + // InstanceTypeM7iFlexXlarge is a InstanceType enum value + InstanceTypeM7iFlexXlarge = "m7i-flex.xlarge" + + // InstanceTypeM7iFlex2xlarge is a InstanceType enum value + InstanceTypeM7iFlex2xlarge = "m7i-flex.2xlarge" + + // InstanceTypeM7iFlex4xlarge is a InstanceType enum value + InstanceTypeM7iFlex4xlarge = "m7i-flex.4xlarge" + + // InstanceTypeM7iFlex8xlarge is a InstanceType enum value + InstanceTypeM7iFlex8xlarge = "m7i-flex.8xlarge" + + // InstanceTypeM7aMedium is a InstanceType enum value + InstanceTypeM7aMedium = "m7a.medium" + + // InstanceTypeM7aLarge is a InstanceType enum value + InstanceTypeM7aLarge = "m7a.large" + + // InstanceTypeM7aXlarge is a InstanceType enum value + InstanceTypeM7aXlarge = "m7a.xlarge" + + // InstanceTypeM7a2xlarge is a InstanceType enum value + InstanceTypeM7a2xlarge = "m7a.2xlarge" + + // InstanceTypeM7a4xlarge is a InstanceType enum value + InstanceTypeM7a4xlarge = "m7a.4xlarge" + + // InstanceTypeM7a8xlarge is a InstanceType enum value + InstanceTypeM7a8xlarge = "m7a.8xlarge" + + // InstanceTypeM7a12xlarge is a InstanceType enum value + InstanceTypeM7a12xlarge = "m7a.12xlarge" + + // InstanceTypeM7a16xlarge is a InstanceType enum value + InstanceTypeM7a16xlarge = "m7a.16xlarge" + + // InstanceTypeM7a24xlarge is a InstanceType enum value + InstanceTypeM7a24xlarge = "m7a.24xlarge" + + // InstanceTypeM7a32xlarge is a InstanceType enum value + InstanceTypeM7a32xlarge = "m7a.32xlarge" + + // InstanceTypeM7a48xlarge is a InstanceType enum value + InstanceTypeM7a48xlarge = "m7a.48xlarge" + + // InstanceTypeM7aMetal48xl is a InstanceType enum value + InstanceTypeM7aMetal48xl = "m7a.metal-48xl" + + // InstanceTypeHpc7a12xlarge is a InstanceType enum value + InstanceTypeHpc7a12xlarge = "hpc7a.12xlarge" + + // InstanceTypeHpc7a24xlarge is a InstanceType enum value + InstanceTypeHpc7a24xlarge = "hpc7a.24xlarge" + + // InstanceTypeHpc7a48xlarge is a InstanceType enum value + InstanceTypeHpc7a48xlarge = "hpc7a.48xlarge" + + // InstanceTypeHpc7a96xlarge is a InstanceType enum value + InstanceTypeHpc7a96xlarge = "hpc7a.96xlarge" + + // InstanceTypeC7gdMedium is a InstanceType enum value + InstanceTypeC7gdMedium = "c7gd.medium" + + // InstanceTypeC7gdLarge is a InstanceType enum value + InstanceTypeC7gdLarge = "c7gd.large" + + // InstanceTypeC7gdXlarge is a InstanceType enum value + InstanceTypeC7gdXlarge = "c7gd.xlarge" + + // InstanceTypeC7gd2xlarge is a InstanceType enum value + InstanceTypeC7gd2xlarge = "c7gd.2xlarge" + + // InstanceTypeC7gd4xlarge is a InstanceType enum value + InstanceTypeC7gd4xlarge = "c7gd.4xlarge" + + // InstanceTypeC7gd8xlarge is a InstanceType enum value + InstanceTypeC7gd8xlarge = "c7gd.8xlarge" + + // InstanceTypeC7gd12xlarge is a InstanceType enum value + InstanceTypeC7gd12xlarge = "c7gd.12xlarge" + + // InstanceTypeC7gd16xlarge is a InstanceType enum value + InstanceTypeC7gd16xlarge = "c7gd.16xlarge" + + // InstanceTypeM7gdMedium is a InstanceType enum value + InstanceTypeM7gdMedium = "m7gd.medium" + + // InstanceTypeM7gdLarge is a InstanceType enum value + InstanceTypeM7gdLarge = "m7gd.large" + + // InstanceTypeM7gdXlarge is a InstanceType enum value + InstanceTypeM7gdXlarge = "m7gd.xlarge" + + // InstanceTypeM7gd2xlarge is a InstanceType enum value + InstanceTypeM7gd2xlarge = "m7gd.2xlarge" + + // InstanceTypeM7gd4xlarge is a InstanceType enum value + InstanceTypeM7gd4xlarge = "m7gd.4xlarge" + + // InstanceTypeM7gd8xlarge is a InstanceType enum value + InstanceTypeM7gd8xlarge = "m7gd.8xlarge" + + // InstanceTypeM7gd12xlarge is a InstanceType enum value + InstanceTypeM7gd12xlarge = "m7gd.12xlarge" + + // InstanceTypeM7gd16xlarge is a InstanceType enum value + InstanceTypeM7gd16xlarge = "m7gd.16xlarge" + + // InstanceTypeR7gdMedium is a InstanceType enum value + InstanceTypeR7gdMedium = "r7gd.medium" + + // InstanceTypeR7gdLarge is a InstanceType enum value + InstanceTypeR7gdLarge = "r7gd.large" + + // InstanceTypeR7gdXlarge is a InstanceType enum value + InstanceTypeR7gdXlarge = "r7gd.xlarge" + + // InstanceTypeR7gd2xlarge is a InstanceType enum value + InstanceTypeR7gd2xlarge = "r7gd.2xlarge" + + // InstanceTypeR7gd4xlarge is a InstanceType enum value + InstanceTypeR7gd4xlarge = "r7gd.4xlarge" + + // InstanceTypeR7gd8xlarge is a InstanceType enum value + InstanceTypeR7gd8xlarge = "r7gd.8xlarge" + + // InstanceTypeR7gd12xlarge is a InstanceType enum value + InstanceTypeR7gd12xlarge = "r7gd.12xlarge" + + // InstanceTypeR7gd16xlarge is a InstanceType enum value + InstanceTypeR7gd16xlarge = "r7gd.16xlarge" + + // InstanceTypeR7aMedium is a InstanceType enum value + InstanceTypeR7aMedium = "r7a.medium" + + // InstanceTypeR7aLarge is a InstanceType enum value + InstanceTypeR7aLarge = "r7a.large" + + // InstanceTypeR7aXlarge is a InstanceType enum value + InstanceTypeR7aXlarge = "r7a.xlarge" + + // InstanceTypeR7a2xlarge is a InstanceType enum value + InstanceTypeR7a2xlarge = "r7a.2xlarge" + + // InstanceTypeR7a4xlarge is a InstanceType enum value + InstanceTypeR7a4xlarge = "r7a.4xlarge" + + // InstanceTypeR7a8xlarge is a InstanceType enum value + InstanceTypeR7a8xlarge = "r7a.8xlarge" + + // InstanceTypeR7a12xlarge is a InstanceType enum value + InstanceTypeR7a12xlarge = "r7a.12xlarge" + + // InstanceTypeR7a16xlarge is a InstanceType enum value + InstanceTypeR7a16xlarge = "r7a.16xlarge" + + // InstanceTypeR7a24xlarge is a InstanceType enum value + InstanceTypeR7a24xlarge = "r7a.24xlarge" + + // InstanceTypeR7a32xlarge is a InstanceType enum value + InstanceTypeR7a32xlarge = "r7a.32xlarge" + + // InstanceTypeR7a48xlarge is a InstanceType enum value + InstanceTypeR7a48xlarge = "r7a.48xlarge" + + // InstanceTypeC7iLarge is a InstanceType enum value + InstanceTypeC7iLarge = "c7i.large" + + // InstanceTypeC7iXlarge is a InstanceType enum value + InstanceTypeC7iXlarge = "c7i.xlarge" + + // InstanceTypeC7i2xlarge is a InstanceType enum value + InstanceTypeC7i2xlarge = "c7i.2xlarge" + + // InstanceTypeC7i4xlarge is a InstanceType enum value + InstanceTypeC7i4xlarge = "c7i.4xlarge" + + // InstanceTypeC7i8xlarge is a InstanceType enum value + InstanceTypeC7i8xlarge = "c7i.8xlarge" + + // InstanceTypeC7i12xlarge is a InstanceType enum value + InstanceTypeC7i12xlarge = "c7i.12xlarge" + + // InstanceTypeC7i16xlarge is a InstanceType enum value + InstanceTypeC7i16xlarge = "c7i.16xlarge" + + // InstanceTypeC7i24xlarge is a InstanceType enum value + InstanceTypeC7i24xlarge = "c7i.24xlarge" + + // InstanceTypeC7i48xlarge is a InstanceType enum value + InstanceTypeC7i48xlarge = "c7i.48xlarge" + + // InstanceTypeMac2M2proMetal is a InstanceType enum value + InstanceTypeMac2M2proMetal = "mac2-m2pro.metal" + + // InstanceTypeR7izLarge is a InstanceType enum value + InstanceTypeR7izLarge = "r7iz.large" + + // InstanceTypeR7izXlarge is a InstanceType enum value + InstanceTypeR7izXlarge = "r7iz.xlarge" + + // InstanceTypeR7iz2xlarge is a InstanceType enum value + InstanceTypeR7iz2xlarge = "r7iz.2xlarge" + + // InstanceTypeR7iz4xlarge is a InstanceType enum value + InstanceTypeR7iz4xlarge = "r7iz.4xlarge" + + // InstanceTypeR7iz8xlarge is a InstanceType enum value + InstanceTypeR7iz8xlarge = "r7iz.8xlarge" + + // InstanceTypeR7iz12xlarge is a InstanceType enum value + InstanceTypeR7iz12xlarge = "r7iz.12xlarge" + + // InstanceTypeR7iz16xlarge is a InstanceType enum value + InstanceTypeR7iz16xlarge = "r7iz.16xlarge" + + // InstanceTypeR7iz32xlarge is a InstanceType enum value + InstanceTypeR7iz32xlarge = "r7iz.32xlarge" + + // InstanceTypeC7aMedium is a InstanceType enum value + InstanceTypeC7aMedium = "c7a.medium" + + // InstanceTypeC7aLarge is a InstanceType enum value + InstanceTypeC7aLarge = "c7a.large" + + // InstanceTypeC7aXlarge is a InstanceType enum value + InstanceTypeC7aXlarge = "c7a.xlarge" + + // InstanceTypeC7a2xlarge is a InstanceType enum value + InstanceTypeC7a2xlarge = "c7a.2xlarge" + + // InstanceTypeC7a4xlarge is a InstanceType enum value + InstanceTypeC7a4xlarge = "c7a.4xlarge" + + // InstanceTypeC7a8xlarge is a InstanceType enum value + InstanceTypeC7a8xlarge = "c7a.8xlarge" + + // InstanceTypeC7a12xlarge is a InstanceType enum value + InstanceTypeC7a12xlarge = "c7a.12xlarge" + + // InstanceTypeC7a16xlarge is a InstanceType enum value + InstanceTypeC7a16xlarge = "c7a.16xlarge" + + // InstanceTypeC7a24xlarge is a InstanceType enum value + InstanceTypeC7a24xlarge = "c7a.24xlarge" + + // InstanceTypeC7a32xlarge is a InstanceType enum value + InstanceTypeC7a32xlarge = "c7a.32xlarge" + + // InstanceTypeC7a48xlarge is a InstanceType enum value + InstanceTypeC7a48xlarge = "c7a.48xlarge" + + // InstanceTypeC7aMetal48xl is a InstanceType enum value + InstanceTypeC7aMetal48xl = "c7a.metal-48xl" + + // InstanceTypeR7aMetal48xl is a InstanceType enum value + InstanceTypeR7aMetal48xl = "r7a.metal-48xl" + + // InstanceTypeR7iLarge is a InstanceType enum value + InstanceTypeR7iLarge = "r7i.large" + + // InstanceTypeR7iXlarge is a InstanceType enum value + InstanceTypeR7iXlarge = "r7i.xlarge" + + // InstanceTypeR7i2xlarge is a InstanceType enum value + InstanceTypeR7i2xlarge = "r7i.2xlarge" + + // InstanceTypeR7i4xlarge is a InstanceType enum value + InstanceTypeR7i4xlarge = "r7i.4xlarge" + + // InstanceTypeR7i8xlarge is a InstanceType enum value + InstanceTypeR7i8xlarge = "r7i.8xlarge" + + // InstanceTypeR7i12xlarge is a InstanceType enum value + InstanceTypeR7i12xlarge = "r7i.12xlarge" + + // InstanceTypeR7i16xlarge is a InstanceType enum value + InstanceTypeR7i16xlarge = "r7i.16xlarge" + + // InstanceTypeR7i24xlarge is a InstanceType enum value + InstanceTypeR7i24xlarge = "r7i.24xlarge" + + // InstanceTypeR7i48xlarge is a InstanceType enum value + InstanceTypeR7i48xlarge = "r7i.48xlarge" + + // InstanceTypeDl2q24xlarge is a InstanceType enum value + InstanceTypeDl2q24xlarge = "dl2q.24xlarge" + + // InstanceTypeMac2M2Metal is a InstanceType enum value + InstanceTypeMac2M2Metal = "mac2-m2.metal" + + // InstanceTypeI4i12xlarge is a InstanceType enum value + InstanceTypeI4i12xlarge = "i4i.12xlarge" + + // InstanceTypeI4i24xlarge is a InstanceType enum value + InstanceTypeI4i24xlarge = "i4i.24xlarge" + + // InstanceTypeC7iMetal24xl is a InstanceType enum value + InstanceTypeC7iMetal24xl = "c7i.metal-24xl" + + // InstanceTypeC7iMetal48xl is a InstanceType enum value + InstanceTypeC7iMetal48xl = "c7i.metal-48xl" + + // InstanceTypeM7iMetal24xl is a InstanceType enum value + InstanceTypeM7iMetal24xl = "m7i.metal-24xl" + + // InstanceTypeM7iMetal48xl is a InstanceType enum value + InstanceTypeM7iMetal48xl = "m7i.metal-48xl" + + // InstanceTypeR7iMetal24xl is a InstanceType enum value + InstanceTypeR7iMetal24xl = "r7i.metal-24xl" + + // InstanceTypeR7iMetal48xl is a InstanceType enum value + InstanceTypeR7iMetal48xl = "r7i.metal-48xl" + + // InstanceTypeR7izMetal16xl is a InstanceType enum value + InstanceTypeR7izMetal16xl = "r7iz.metal-16xl" + + // InstanceTypeR7izMetal32xl is a InstanceType enum value + InstanceTypeR7izMetal32xl = "r7iz.metal-32xl" ) // InstanceType_Values returns all elements of the InstanceType enum @@ -186248,6 +195141,146 @@ func InstanceType_Values() []string { InstanceTypeM6idnMetal, InstanceTypeR6inMetal, InstanceTypeR6idnMetal, + InstanceTypeInf2Xlarge, + InstanceTypeInf28xlarge, + InstanceTypeInf224xlarge, + InstanceTypeInf248xlarge, + InstanceTypeTrn1n32xlarge, + InstanceTypeI4gLarge, + InstanceTypeI4gXlarge, + InstanceTypeI4g2xlarge, + InstanceTypeI4g4xlarge, + InstanceTypeI4g8xlarge, + InstanceTypeI4g16xlarge, + InstanceTypeHpc7g4xlarge, + InstanceTypeHpc7g8xlarge, + InstanceTypeHpc7g16xlarge, + InstanceTypeC7gnMedium, + InstanceTypeC7gnLarge, + InstanceTypeC7gnXlarge, + InstanceTypeC7gn2xlarge, + InstanceTypeC7gn4xlarge, + InstanceTypeC7gn8xlarge, + InstanceTypeC7gn12xlarge, + InstanceTypeC7gn16xlarge, + InstanceTypeP548xlarge, + InstanceTypeM7iLarge, + InstanceTypeM7iXlarge, + InstanceTypeM7i2xlarge, + InstanceTypeM7i4xlarge, + InstanceTypeM7i8xlarge, + InstanceTypeM7i12xlarge, + InstanceTypeM7i16xlarge, + InstanceTypeM7i24xlarge, + InstanceTypeM7i48xlarge, + InstanceTypeM7iFlexLarge, + InstanceTypeM7iFlexXlarge, + InstanceTypeM7iFlex2xlarge, + InstanceTypeM7iFlex4xlarge, + InstanceTypeM7iFlex8xlarge, + InstanceTypeM7aMedium, + InstanceTypeM7aLarge, + InstanceTypeM7aXlarge, + InstanceTypeM7a2xlarge, + InstanceTypeM7a4xlarge, + InstanceTypeM7a8xlarge, + InstanceTypeM7a12xlarge, + InstanceTypeM7a16xlarge, + InstanceTypeM7a24xlarge, + InstanceTypeM7a32xlarge, + InstanceTypeM7a48xlarge, + InstanceTypeM7aMetal48xl, + InstanceTypeHpc7a12xlarge, + InstanceTypeHpc7a24xlarge, + InstanceTypeHpc7a48xlarge, + InstanceTypeHpc7a96xlarge, + InstanceTypeC7gdMedium, + InstanceTypeC7gdLarge, + InstanceTypeC7gdXlarge, + InstanceTypeC7gd2xlarge, + InstanceTypeC7gd4xlarge, + InstanceTypeC7gd8xlarge, + InstanceTypeC7gd12xlarge, + InstanceTypeC7gd16xlarge, + InstanceTypeM7gdMedium, + InstanceTypeM7gdLarge, + InstanceTypeM7gdXlarge, + InstanceTypeM7gd2xlarge, + InstanceTypeM7gd4xlarge, + InstanceTypeM7gd8xlarge, + InstanceTypeM7gd12xlarge, + InstanceTypeM7gd16xlarge, + InstanceTypeR7gdMedium, + InstanceTypeR7gdLarge, + InstanceTypeR7gdXlarge, + InstanceTypeR7gd2xlarge, + InstanceTypeR7gd4xlarge, + InstanceTypeR7gd8xlarge, + InstanceTypeR7gd12xlarge, + InstanceTypeR7gd16xlarge, + InstanceTypeR7aMedium, + InstanceTypeR7aLarge, + InstanceTypeR7aXlarge, + InstanceTypeR7a2xlarge, + InstanceTypeR7a4xlarge, + InstanceTypeR7a8xlarge, + InstanceTypeR7a12xlarge, + InstanceTypeR7a16xlarge, + InstanceTypeR7a24xlarge, + InstanceTypeR7a32xlarge, + InstanceTypeR7a48xlarge, + InstanceTypeC7iLarge, + InstanceTypeC7iXlarge, + InstanceTypeC7i2xlarge, + InstanceTypeC7i4xlarge, + InstanceTypeC7i8xlarge, + InstanceTypeC7i12xlarge, + InstanceTypeC7i16xlarge, + InstanceTypeC7i24xlarge, + InstanceTypeC7i48xlarge, + InstanceTypeMac2M2proMetal, + InstanceTypeR7izLarge, + InstanceTypeR7izXlarge, + InstanceTypeR7iz2xlarge, + InstanceTypeR7iz4xlarge, + InstanceTypeR7iz8xlarge, + InstanceTypeR7iz12xlarge, + InstanceTypeR7iz16xlarge, + InstanceTypeR7iz32xlarge, + InstanceTypeC7aMedium, + InstanceTypeC7aLarge, + InstanceTypeC7aXlarge, + InstanceTypeC7a2xlarge, + InstanceTypeC7a4xlarge, + InstanceTypeC7a8xlarge, + InstanceTypeC7a12xlarge, + InstanceTypeC7a16xlarge, + InstanceTypeC7a24xlarge, + InstanceTypeC7a32xlarge, + InstanceTypeC7a48xlarge, + InstanceTypeC7aMetal48xl, + InstanceTypeR7aMetal48xl, + InstanceTypeR7iLarge, + InstanceTypeR7iXlarge, + InstanceTypeR7i2xlarge, + InstanceTypeR7i4xlarge, + InstanceTypeR7i8xlarge, + InstanceTypeR7i12xlarge, + InstanceTypeR7i16xlarge, + InstanceTypeR7i24xlarge, + InstanceTypeR7i48xlarge, + InstanceTypeDl2q24xlarge, + InstanceTypeMac2M2Metal, + InstanceTypeI4i12xlarge, + InstanceTypeI4i24xlarge, + InstanceTypeC7iMetal24xl, + InstanceTypeC7iMetal48xl, + InstanceTypeM7iMetal24xl, + InstanceTypeM7iMetal48xl, + InstanceTypeR7iMetal24xl, + InstanceTypeR7iMetal48xl, + InstanceTypeR7izMetal16xl, + InstanceTypeR7izMetal32xl, } } @@ -186459,6 +195492,9 @@ const ( // IpamPoolAllocationResourceTypeCustom is a IpamPoolAllocationResourceType enum value IpamPoolAllocationResourceTypeCustom = "custom" + + // IpamPoolAllocationResourceTypeSubnet is a IpamPoolAllocationResourceType enum value + IpamPoolAllocationResourceTypeSubnet = "subnet" ) // IpamPoolAllocationResourceType_Values returns all elements of the IpamPoolAllocationResourceType enum @@ -186468,6 +195504,7 @@ func IpamPoolAllocationResourceType_Values() []string { IpamPoolAllocationResourceTypeVpc, IpamPoolAllocationResourceTypeEc2PublicIpv4Pool, IpamPoolAllocationResourceTypeCustom, + IpamPoolAllocationResourceTypeSubnet, } } @@ -186555,6 +195592,18 @@ func IpamPoolPublicIpSource_Values() []string { } } +const ( + // IpamPoolSourceResourceTypeVpc is a IpamPoolSourceResourceType enum value + IpamPoolSourceResourceTypeVpc = "vpc" +) + +// IpamPoolSourceResourceType_Values returns all elements of the IpamPoolSourceResourceType enum +func IpamPoolSourceResourceType_Values() []string { + return []string{ + IpamPoolSourceResourceTypeVpc, + } +} + const ( // IpamPoolStateCreateInProgress is a IpamPoolState enum value IpamPoolStateCreateInProgress = "create-in-progress" @@ -186611,6 +195660,94 @@ func IpamPoolState_Values() []string { } } +const ( + // IpamPublicAddressAssociationStatusAssociated is a IpamPublicAddressAssociationStatus enum value + IpamPublicAddressAssociationStatusAssociated = "associated" + + // IpamPublicAddressAssociationStatusDisassociated is a IpamPublicAddressAssociationStatus enum value + IpamPublicAddressAssociationStatusDisassociated = "disassociated" +) + +// IpamPublicAddressAssociationStatus_Values returns all elements of the IpamPublicAddressAssociationStatus enum +func IpamPublicAddressAssociationStatus_Values() []string { + return []string{ + IpamPublicAddressAssociationStatusAssociated, + IpamPublicAddressAssociationStatusDisassociated, + } +} + +const ( + // IpamPublicAddressAwsServiceNatGateway is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceNatGateway = "nat-gateway" + + // IpamPublicAddressAwsServiceDatabaseMigrationService is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceDatabaseMigrationService = "database-migration-service" + + // IpamPublicAddressAwsServiceRedshift is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceRedshift = "redshift" + + // IpamPublicAddressAwsServiceElasticContainerService is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceElasticContainerService = "elastic-container-service" + + // IpamPublicAddressAwsServiceRelationalDatabaseService is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceRelationalDatabaseService = "relational-database-service" + + // IpamPublicAddressAwsServiceSiteToSiteVpn is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceSiteToSiteVpn = "site-to-site-vpn" + + // IpamPublicAddressAwsServiceLoadBalancer is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceLoadBalancer = "load-balancer" + + // IpamPublicAddressAwsServiceGlobalAccelerator is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceGlobalAccelerator = "global-accelerator" + + // IpamPublicAddressAwsServiceOther is a IpamPublicAddressAwsService enum value + IpamPublicAddressAwsServiceOther = "other" +) + +// IpamPublicAddressAwsService_Values returns all elements of the IpamPublicAddressAwsService enum +func IpamPublicAddressAwsService_Values() []string { + return []string{ + IpamPublicAddressAwsServiceNatGateway, + IpamPublicAddressAwsServiceDatabaseMigrationService, + IpamPublicAddressAwsServiceRedshift, + IpamPublicAddressAwsServiceElasticContainerService, + IpamPublicAddressAwsServiceRelationalDatabaseService, + IpamPublicAddressAwsServiceSiteToSiteVpn, + IpamPublicAddressAwsServiceLoadBalancer, + IpamPublicAddressAwsServiceGlobalAccelerator, + IpamPublicAddressAwsServiceOther, + } +} + +const ( + // IpamPublicAddressTypeServiceManagedIp is a IpamPublicAddressType enum value + IpamPublicAddressTypeServiceManagedIp = "service-managed-ip" + + // IpamPublicAddressTypeServiceManagedByoip is a IpamPublicAddressType enum value + IpamPublicAddressTypeServiceManagedByoip = "service-managed-byoip" + + // IpamPublicAddressTypeAmazonOwnedEip is a IpamPublicAddressType enum value + IpamPublicAddressTypeAmazonOwnedEip = "amazon-owned-eip" + + // IpamPublicAddressTypeByoip is a IpamPublicAddressType enum value + IpamPublicAddressTypeByoip = "byoip" + + // IpamPublicAddressTypeEc2PublicIp is a IpamPublicAddressType enum value + IpamPublicAddressTypeEc2PublicIp = "ec2-public-ip" +) + +// IpamPublicAddressType_Values returns all elements of the IpamPublicAddressType enum +func IpamPublicAddressType_Values() []string { + return []string{ + IpamPublicAddressTypeServiceManagedIp, + IpamPublicAddressTypeServiceManagedByoip, + IpamPublicAddressTypeAmazonOwnedEip, + IpamPublicAddressTypeByoip, + IpamPublicAddressTypeEc2PublicIp, + } +} + const ( // IpamResourceDiscoveryAssociationStateAssociateInProgress is a IpamResourceDiscoveryAssociationState enum value IpamResourceDiscoveryAssociationStateAssociateInProgress = "associate-in-progress" @@ -186726,6 +195863,9 @@ const ( // IpamResourceTypeIpv6Pool is a IpamResourceType enum value IpamResourceTypeIpv6Pool = "ipv6-pool" + + // IpamResourceTypeEni is a IpamResourceType enum value + IpamResourceTypeEni = "eni" ) // IpamResourceType_Values returns all elements of the IpamResourceType enum @@ -186736,6 +195876,7 @@ func IpamResourceType_Values() []string { IpamResourceTypeEip, IpamResourceTypePublicIpv4Pool, IpamResourceTypeIpv6Pool, + IpamResourceTypeEni, } } @@ -186867,6 +196008,22 @@ func IpamState_Values() []string { } } +const ( + // IpamTierFree is a IpamTier enum value + IpamTierFree = "free" + + // IpamTierAdvanced is a IpamTier enum value + IpamTierAdvanced = "advanced" +) + +// IpamTier_Values returns all elements of the IpamTier enum +func IpamTier_Values() []string { + return []string{ + IpamTierFree, + IpamTierAdvanced, + } +} + const ( // Ipv6SupportValueEnable is a Ipv6SupportValue enum value Ipv6SupportValueEnable = "enable" @@ -187196,6 +196353,9 @@ const ( // LocationTypeAvailabilityZoneId is a LocationType enum value LocationTypeAvailabilityZoneId = "availability-zone-id" + + // LocationTypeOutpost is a LocationType enum value + LocationTypeOutpost = "outpost" ) // LocationType_Values returns all elements of the LocationType enum @@ -187204,6 +196364,47 @@ func LocationType_Values() []string { LocationTypeRegion, LocationTypeAvailabilityZone, LocationTypeAvailabilityZoneId, + LocationTypeOutpost, + } +} + +const ( + // LockModeCompliance is a LockMode enum value + LockModeCompliance = "compliance" + + // LockModeGovernance is a LockMode enum value + LockModeGovernance = "governance" +) + +// LockMode_Values returns all elements of the LockMode enum +func LockMode_Values() []string { + return []string{ + LockModeCompliance, + LockModeGovernance, + } +} + +const ( + // LockStateCompliance is a LockState enum value + LockStateCompliance = "compliance" + + // LockStateGovernance is a LockState enum value + LockStateGovernance = "governance" + + // LockStateComplianceCooloff is a LockState enum value + LockStateComplianceCooloff = "compliance-cooloff" + + // LockStateExpired is a LockState enum value + LockStateExpired = "expired" +) + +// LockState_Values returns all elements of the LockState enum +func LockState_Values() []string { + return []string{ + LockStateCompliance, + LockStateGovernance, + LockStateComplianceCooloff, + LockStateExpired, } } @@ -187230,12 +196431,16 @@ func LogDestinationType_Values() []string { const ( // MarketTypeSpot is a MarketType enum value MarketTypeSpot = "spot" + + // MarketTypeCapacityBlock is a MarketType enum value + MarketTypeCapacityBlock = "capacity-block" ) // MarketType_Values returns all elements of the MarketType enum func MarketType_Values() []string { return []string{ MarketTypeSpot, + MarketTypeCapacityBlock, } } @@ -187571,6 +196776,38 @@ func NetworkInterfaceType_Values() []string { } } +const ( + // NitroEnclavesSupportUnsupported is a NitroEnclavesSupport enum value + NitroEnclavesSupportUnsupported = "unsupported" + + // NitroEnclavesSupportSupported is a NitroEnclavesSupport enum value + NitroEnclavesSupportSupported = "supported" +) + +// NitroEnclavesSupport_Values returns all elements of the NitroEnclavesSupport enum +func NitroEnclavesSupport_Values() []string { + return []string{ + NitroEnclavesSupportUnsupported, + NitroEnclavesSupportSupported, + } +} + +const ( + // NitroTpmSupportUnsupported is a NitroTpmSupport enum value + NitroTpmSupportUnsupported = "unsupported" + + // NitroTpmSupportSupported is a NitroTpmSupport enum value + NitroTpmSupportSupported = "supported" +) + +// NitroTpmSupport_Values returns all elements of the NitroTpmSupport enum +func NitroTpmSupport_Values() []string { + return []string{ + NitroTpmSupportUnsupported, + NitroTpmSupportSupported, + } +} + const ( // OfferingClassTypeStandard is a OfferingClassType enum value OfferingClassTypeStandard = "standard" @@ -188438,6 +197675,9 @@ const ( // ResourceTypeIpamResourceDiscoveryAssociation is a ResourceType enum value ResourceTypeIpamResourceDiscoveryAssociation = "ipam-resource-discovery-association" + + // ResourceTypeInstanceConnectEndpoint is a ResourceType enum value + ResourceTypeInstanceConnectEndpoint = "instance-connect-endpoint" ) // ResourceType_Values returns all elements of the ResourceType enum @@ -188528,6 +197768,7 @@ func ResourceType_Values() []string { ResourceTypeVpcBlockPublicAccessExclusion, ResourceTypeIpamResourceDiscovery, ResourceTypeIpamResourceDiscoveryAssociation, + ResourceTypeInstanceConnectEndpoint, } } @@ -188627,6 +197868,26 @@ func RuleAction_Values() []string { } } +const ( + // SSETypeSseEbs is a SSEType enum value + SSETypeSseEbs = "sse-ebs" + + // SSETypeSseKms is a SSEType enum value + SSETypeSseKms = "sse-kms" + + // SSETypeNone is a SSEType enum value + SSETypeNone = "none" +) + +// SSEType_Values returns all elements of the SSEType enum +func SSEType_Values() []string { + return []string{ + SSETypeSseEbs, + SSETypeSseKms, + SSETypeNone, + } +} + const ( // ScopeAvailabilityZone is a Scope enum value ScopeAvailabilityZone = "Availability Zone" @@ -188643,6 +197904,22 @@ func Scope_Values() []string { } } +const ( + // SecurityGroupReferencingSupportValueEnable is a SecurityGroupReferencingSupportValue enum value + SecurityGroupReferencingSupportValueEnable = "enable" + + // SecurityGroupReferencingSupportValueDisable is a SecurityGroupReferencingSupportValue enum value + SecurityGroupReferencingSupportValueDisable = "disable" +) + +// SecurityGroupReferencingSupportValue_Values returns all elements of the SecurityGroupReferencingSupportValue enum +func SecurityGroupReferencingSupportValue_Values() []string { + return []string{ + SecurityGroupReferencingSupportValueEnable, + SecurityGroupReferencingSupportValueDisable, + } +} + const ( // SelfServicePortalEnabled is a SelfServicePortal enum value SelfServicePortalEnabled = "enabled" @@ -188755,6 +198032,26 @@ func SnapshotAttributeName_Values() []string { } } +const ( + // SnapshotBlockPublicAccessStateBlockAllSharing is a SnapshotBlockPublicAccessState enum value + SnapshotBlockPublicAccessStateBlockAllSharing = "block-all-sharing" + + // SnapshotBlockPublicAccessStateBlockNewSharing is a SnapshotBlockPublicAccessState enum value + SnapshotBlockPublicAccessStateBlockNewSharing = "block-new-sharing" + + // SnapshotBlockPublicAccessStateUnblocked is a SnapshotBlockPublicAccessState enum value + SnapshotBlockPublicAccessStateUnblocked = "unblocked" +) + +// SnapshotBlockPublicAccessState_Values returns all elements of the SnapshotBlockPublicAccessState enum +func SnapshotBlockPublicAccessState_Values() []string { + return []string{ + SnapshotBlockPublicAccessStateBlockAllSharing, + SnapshotBlockPublicAccessStateBlockNewSharing, + SnapshotBlockPublicAccessStateUnblocked, + } +} + const ( // SnapshotStatePending is a SnapshotState enum value SnapshotStatePending = "pending" @@ -188846,6 +198143,9 @@ const ( // SpotInstanceStateFailed is a SpotInstanceState enum value SpotInstanceStateFailed = "failed" + + // SpotInstanceStateDisabled is a SpotInstanceState enum value + SpotInstanceStateDisabled = "disabled" ) // SpotInstanceState_Values returns all elements of the SpotInstanceState enum @@ -188856,6 +198156,7 @@ func SpotInstanceState_Values() []string { SpotInstanceStateClosed, SpotInstanceStateCancelled, SpotInstanceStateFailed, + SpotInstanceStateDisabled, } } @@ -189123,6 +198424,18 @@ func SummaryStatus_Values() []string { } } +const ( + // SupportedAdditionalProcessorFeatureAmdSevSnp is a SupportedAdditionalProcessorFeature enum value + SupportedAdditionalProcessorFeatureAmdSevSnp = "amd-sev-snp" +) + +// SupportedAdditionalProcessorFeature_Values returns all elements of the SupportedAdditionalProcessorFeature enum +func SupportedAdditionalProcessorFeature_Values() []string { + return []string{ + SupportedAdditionalProcessorFeatureAmdSevSnp, + } +} + const ( // TargetCapacityUnitTypeVcpu is a TargetCapacityUnitType enum value TargetCapacityUnitTypeVcpu = "vcpu" @@ -189893,6 +199206,9 @@ const ( // UsageClassTypeOnDemand is a UsageClassType enum value UsageClassTypeOnDemand = "on-demand" + + // UsageClassTypeCapacityBlock is a UsageClassType enum value + UsageClassTypeCapacityBlock = "capacity-block" ) // UsageClassType_Values returns all elements of the UsageClassType enum @@ -189900,6 +199216,7 @@ func UsageClassType_Values() []string { return []string{ UsageClassTypeSpot, UsageClassTypeOnDemand, + UsageClassTypeCapacityBlock, } } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go index 5b5395356..621712d29 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go @@ -11,6 +11,9 @@ import ( ) const ( + // ec2CopySnapshotPresignedUrlCustomization handler name + ec2CopySnapshotPresignedUrlCustomization = "ec2CopySnapshotPresignedUrl" + // customRetryerMinRetryDelay sets min retry delay customRetryerMinRetryDelay = 1 * time.Second @@ -21,7 +24,10 @@ const ( func init() { initRequest = func(r *request.Request) { if r.Operation.Name == opCopySnapshot { // fill the PresignedURL parameter - r.Handlers.Build.PushFront(fillPresignedURL) + r.Handlers.Build.PushFrontNamed(request.NamedHandler{ + Name: ec2CopySnapshotPresignedUrlCustomization, + Fn: fillPresignedURL, + }) } // only set the retryer on request if config doesn't have a retryer @@ -48,13 +54,15 @@ func fillPresignedURL(r *request.Request) { origParams := r.Params.(*CopySnapshotInput) - // Stop if PresignedURL/DestinationRegion is set - if origParams.PresignedUrl != nil || origParams.DestinationRegion != nil { + // Stop if PresignedURL is set + if origParams.PresignedUrl != nil { return } + // Always use config region as destination region for SDKs origParams.DestinationRegion = r.Config.Region - newParams := awsutil.CopyOf(r.Params).(*CopySnapshotInput) + + newParams := awsutil.CopyOf(origParams).(*CopySnapshotInput) // Create a new request based on the existing request. We will use this to // presign the CopySnapshot request against the source region. @@ -82,8 +90,12 @@ func fillPresignedURL(r *request.Request) { clientInfo.Endpoint = resolved.URL clientInfo.SigningRegion = resolved.SigningRegion + // Copy handlers without Presigned URL customization to avoid an infinite loop + handlersWithoutPresignCustomization := r.Handlers.Copy() + handlersWithoutPresignCustomization.Build.RemoveByName(ec2CopySnapshotPresignedUrlCustomization) + // Presign a CopySnapshot request with modified params - req := request.New(*cfg, clientInfo, r.Handlers, r.Retryer, r.Operation, newParams, r.Data) + req := request.New(*cfg, clientInfo, handlersWithoutPresignCustomization, r.Retryer, r.Operation, newParams, r.Data) url, err := req.Presign(5 * time.Minute) // 5 minutes should be enough. if err != nil { // bubble error back up to original request r.Error = err diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go index a970f12fb..6dc68faf7 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go @@ -1283,6 +1283,62 @@ func (c *EC2) WaitUntilSpotInstanceRequestFulfilledWithContext(ctx aws.Context, return w.WaitWithContext(ctx) } +// WaitUntilStoreImageTaskComplete uses the Amazon EC2 API operation +// DescribeStoreImageTasks to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *EC2) WaitUntilStoreImageTaskComplete(input *DescribeStoreImageTasksInput) error { + return c.WaitUntilStoreImageTaskCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStoreImageTaskCompleteWithContext is an extended version of WaitUntilStoreImageTaskComplete. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) WaitUntilStoreImageTaskCompleteWithContext(ctx aws.Context, input *DescribeStoreImageTasksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStoreImageTaskComplete", + MaxAttempts: 40, + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "StoreImageTaskResults[].StoreTaskState", + Expected: "Completed", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "StoreImageTaskResults[].StoreTaskState", + Expected: "Failed", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "StoreImageTaskResults[].StoreTaskState", + Expected: "InProgress", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeStoreImageTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeStoreImageTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + // WaitUntilSubnetAvailable uses the Amazon EC2 API operation // DescribeSubnets to wait for a condition to be met before returning. // If the condition is not met within the max attempt window, an error will diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go index fce3db782..f2127cd2a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go @@ -1802,7 +1802,7 @@ func (c *Lightsail) CreateDiskRequest(input *CreateDiskInput) (req *request.Requ // CreateDisk API operation for Amazon Lightsail. // // Creates a block storage disk that can be attached to an Amazon Lightsail -// instance in the same Availability Zone (e.g., us-east-2a). +// instance in the same Availability Zone (us-east-2a). // // The create disk operation supports tag-based access control via request tags. // For more information, see the Amazon Lightsail Developer Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-controlling-access-using-tags). @@ -1911,7 +1911,7 @@ func (c *Lightsail) CreateDiskFromSnapshotRequest(input *CreateDiskFromSnapshotI // // Creates a block storage disk from a manual or automatic snapshot of a disk. // The resulting disk can be attached to an Amazon Lightsail instance in the -// same Availability Zone (e.g., us-east-2a). +// same Availability Zone (us-east-2a). // // The create disk from snapshot operation supports tag-based access control // via request tags and resource tags applied to the resource identified by @@ -2256,7 +2256,7 @@ func (c *Lightsail) CreateDomainRequest(input *CreateDomainInput) (req *request. // CreateDomain API operation for Amazon Lightsail. // -// Creates a domain resource for the specified domain (e.g., example.com). +// Creates a domain resource for the specified domain (example.com). // // The create domain operation supports tag-based access control via request // tags. For more information, see the Amazon Lightsail Developer Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-controlling-access-using-tags). @@ -7603,7 +7603,7 @@ func (c *Lightsail) GetCertificatesRequest(input *GetCertificatesInput) (req *re // // Returns information about one or more Amazon Lightsail SSL/TLS certificates. // -// To get a summary of a certificate, ommit includeCertificateDetails from your +// To get a summary of a certificate, omit includeCertificateDetails from your // request. The response will include only the certificate Amazon Resource Name // (ARN), certificate name, domain name, and tags. // @@ -11664,7 +11664,7 @@ func (c *Lightsail) GetOperationsForResourceRequest(input *GetOperationsForResou // GetOperationsForResource API operation for Amazon Lightsail. // -// Gets operations for a specific resource (e.g., an instance or a static IP). +// Gets operations for a specific resource (an instance or a static IP). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -13102,6 +13102,104 @@ func (c *Lightsail) GetRelationalDatabasesWithContext(ctx aws.Context, input *Ge return out, req.Send() } +const opGetSetupHistory = "GetSetupHistory" + +// GetSetupHistoryRequest generates a "aws/request.Request" representing the +// client's request for the GetSetupHistory operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetSetupHistory for more information on using the GetSetupHistory +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the GetSetupHistoryRequest method. +// req, resp := client.GetSetupHistoryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetSetupHistory +func (c *Lightsail) GetSetupHistoryRequest(input *GetSetupHistoryInput) (req *request.Request, output *GetSetupHistoryOutput) { + op := &request.Operation{ + Name: opGetSetupHistory, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetSetupHistoryInput{} + } + + output = &GetSetupHistoryOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSetupHistory API operation for Amazon Lightsail. +// +// Returns detailed information for five of the most recent SetupInstanceHttps +// requests that were ran on the target instance. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Lightsail's +// API operation GetSetupHistory for usage and error information. +// +// Returned Error Types: +// +// - AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// - InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain and distribution APIs are only available in the N. Virginia (us-east-1) +// Amazon Web Services Region. Please set your Amazon Web Services Region configuration +// to us-east-1 to create, view, or edit these resources. +// +// - NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// - ServiceException +// A general service exception. +// +// - UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetSetupHistory +func (c *Lightsail) GetSetupHistory(input *GetSetupHistoryInput) (*GetSetupHistoryOutput, error) { + req, out := c.GetSetupHistoryRequest(input) + return out, req.Send() +} + +// GetSetupHistoryWithContext is the same as GetSetupHistory with the addition of +// the ability to pass a context and additional request options. +// +// See GetSetupHistory for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lightsail) GetSetupHistoryWithContext(ctx aws.Context, input *GetSetupHistoryInput, opts ...request.Option) (*GetSetupHistoryOutput, error) { + req, out := c.GetSetupHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetStaticIp = "GetStaticIp" // GetStaticIpRequest generates a "aws/request.Request" representing the @@ -14808,6 +14906,107 @@ func (c *Lightsail) SetResourceAccessForBucketWithContext(ctx aws.Context, input return out, req.Send() } +const opSetupInstanceHttps = "SetupInstanceHttps" + +// SetupInstanceHttpsRequest generates a "aws/request.Request" representing the +// client's request for the SetupInstanceHttps operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See SetupInstanceHttps for more information on using the SetupInstanceHttps +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the SetupInstanceHttpsRequest method. +// req, resp := client.SetupInstanceHttpsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/SetupInstanceHttps +func (c *Lightsail) SetupInstanceHttpsRequest(input *SetupInstanceHttpsInput) (req *request.Request, output *SetupInstanceHttpsOutput) { + op := &request.Operation{ + Name: opSetupInstanceHttps, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &SetupInstanceHttpsInput{} + } + + output = &SetupInstanceHttpsOutput{} + req = c.newRequest(op, input, output) + return +} + +// SetupInstanceHttps API operation for Amazon Lightsail. +// +// Creates an SSL/TLS certificate that secures traffic for your website. After +// the certificate is created, it is installed on the specified Lightsail instance. +// +// If you provide more than one domain name in the request, at least one name +// must be less than or equal to 63 characters in length. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Lightsail's +// API operation SetupInstanceHttps for usage and error information. +// +// Returned Error Types: +// +// - AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// - InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain and distribution APIs are only available in the N. Virginia (us-east-1) +// Amazon Web Services Region. Please set your Amazon Web Services Region configuration +// to us-east-1 to create, view, or edit these resources. +// +// - NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// - ServiceException +// A general service exception. +// +// - UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/SetupInstanceHttps +func (c *Lightsail) SetupInstanceHttps(input *SetupInstanceHttpsInput) (*SetupInstanceHttpsOutput, error) { + req, out := c.SetupInstanceHttpsRequest(input) + return out, req.Send() +} + +// SetupInstanceHttpsWithContext is the same as SetupInstanceHttps with the addition of +// the ability to pass a context and additional request options. +// +// See SetupInstanceHttps for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Lightsail) SetupInstanceHttpsWithContext(ctx aws.Context, input *SetupInstanceHttpsInput, opts ...request.Option) (*SetupInstanceHttpsOutput, error) { + req, out := c.SetupInstanceHttpsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opStartGUISession = "StartGUISession" // StartGUISessionRequest generates a "aws/request.Request" representing the @@ -17666,7 +17865,7 @@ type Alarm struct { // The period, in seconds, over which the statistic is applied. Period *int64 `locationName:"period" min:"60" type:"integer"` - // The Lightsail resource type (e.g., Alarm). + // The Lightsail resource type of the alarm. ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // The current state of the alarm. @@ -18065,12 +18264,12 @@ type AttachDiskInput struct { // This value only applies to Lightsail for Research resources. AutoMounting *bool `locationName:"autoMounting" type:"boolean"` - // The unique Lightsail disk name (e.g., my-disk). + // The unique Lightsail disk name (my-disk). // // DiskName is a required field DiskName *string `locationName:"diskName" type:"string" required:"true"` - // The disk path to expose to the instance (e.g., /dev/xvdf). + // The disk path to expose to the instance (/dev/xvdf). // // DiskPath is a required field DiskPath *string `locationName:"diskPath" type:"string" required:"true"` @@ -18471,7 +18670,7 @@ func (s *AttachStaticIpOutput) SetOperations(v []*Operation) *AttachStaticIpOutp type AttachedDisk struct { _ struct{} `type:"structure"` - // The path of the disk (e.g., /dev/xvdf). + // The path of the disk (/dev/xvdf). Path *string `locationName:"path" type:"string"` // The size of the disk in GB. @@ -18690,13 +18889,13 @@ type Blueprint struct { // This parameter only applies to Lightsail for Research resources. AppCategory *string `locationName:"appCategory" type:"string" enum:"AppCategory"` - // The ID for the virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). + // The ID for the virtual private server image (app_wordpress_4_4 or app_lamp_7_0). BlueprintId *string `locationName:"blueprintId" type:"string"` // The description of the blueprint. Description *string `locationName:"description" type:"string"` - // The group name of the blueprint (e.g., amazon-linux). + // The group name of the blueprint (amazon-linux). Group *string `locationName:"group" type:"string"` // A Boolean value indicating whether the blueprint is active. Inactive blueprints @@ -18714,7 +18913,7 @@ type Blueprint struct { // blueprint runs on all instance sizes. MinPower *int64 `locationName:"minPower" type:"integer"` - // The friendly name of the blueprint (e.g., Amazon Linux). + // The friendly name of the blueprint (Amazon Linux). Name *string `locationName:"name" type:"string"` // The operating system platform (either Linux/Unix-based or Windows Server-based) @@ -18724,11 +18923,10 @@ type Blueprint struct { // The product URL to learn more about the image or blueprint. ProductUrl *string `locationName:"productUrl" type:"string"` - // The type of the blueprint (e.g., os or app). + // The type of the blueprint (os or app). Type *string `locationName:"type" type:"string" enum:"BlueprintType"` - // The version number of the operating system, application, or stack (e.g., - // 2016.03.0). + // The version number of the operating system, application, or stack ( 2016.03.0). Version *string `locationName:"version" type:"string"` // The version code. @@ -18889,7 +19087,7 @@ type Bucket struct { // have read-only access to the bucket. ReadonlyAccessAccounts []*string `locationName:"readonlyAccessAccounts" type:"list"` - // The Lightsail resource type of the bucket (for example, Bucket). + // The Lightsail resource type of the bucket. ResourceType *string `locationName:"resourceType" type:"string"` // An array of objects that describe Lightsail instances that have access to @@ -19254,35 +19452,35 @@ func (s *BucketState) SetMessage(v string) *BucketState { type Bundle struct { _ struct{} `type:"structure"` - // The bundle ID (e.g., micro_1_0). + // The bundle ID (micro_1_0). BundleId *string `locationName:"bundleId" type:"string"` - // The number of vCPUs included in the bundle (e.g., 2). + // The number of vCPUs included in the bundle (2). CpuCount *int64 `locationName:"cpuCount" type:"integer"` - // The size of the SSD (e.g., 30). + // The size of the SSD (30). DiskSizeInGb *int64 `locationName:"diskSizeInGb" type:"integer"` - // The Amazon EC2 instance type (e.g., t2.micro). + // The Amazon EC2 instance type (t2.micro). InstanceType *string `locationName:"instanceType" type:"string"` // A Boolean value indicating whether the bundle is active. IsActive *bool `locationName:"isActive" type:"boolean"` - // A friendly name for the bundle (e.g., Micro). + // A friendly name for the bundle (Micro). Name *string `locationName:"name" type:"string"` - // A numeric value that represents the power of the bundle (e.g., 500). You - // can use the bundle's power value in conjunction with a blueprint's minimum - // power value to determine whether the blueprint will run on the bundle. For - // example, you need a bundle with a power value of 500 or more to create an - // instance that uses a blueprint with a minimum power value of 500. + // A numeric value that represents the power of the bundle (500). You can use + // the bundle's power value in conjunction with a blueprint's minimum power + // value to determine whether the blueprint will run on the bundle. For example, + // you need a bundle with a power value of 500 or more to create an instance + // that uses a blueprint with a minimum power value of 500. Power *int64 `locationName:"power" type:"integer"` - // The price in US dollars (e.g., 5.0) of the bundle. + // The price in US dollars (5.0) of the bundle. Price *float64 `locationName:"price" type:"float"` - // The amount of RAM in GB (e.g., 2.0). + // The amount of RAM in GB (2.0). RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` // Virtual computer blueprints that are supported by a Lightsail for Research @@ -19297,7 +19495,7 @@ type Bundle struct { // bundle. SupportedPlatforms []*string `locationName:"supportedPlatforms" type:"list" enum:"InstancePlatform"` - // The data transfer rate per month in GB (e.g., 2000). + // The data transfer rate per month in GB (2000). TransferPerMonthInGb *int64 `locationName:"transferPerMonthInGb" type:"integer"` } @@ -19655,7 +19853,7 @@ func (s *CacheSettings) SetMinimumTTL(v int64) *CacheSettings { // Describes the full details of an Amazon Lightsail SSL/TLS certificate. // -// To get a summary of a certificate, use the GetCertificates action and ommit +// To get a summary of a certificate, use the GetCertificates action and omit // includeCertificateDetails from your request. The response will include only // the certificate Amazon Resource Name (ARN), certificate name, domain name, // and tags. @@ -19690,7 +19888,7 @@ type Certificate struct { // of the certificate. KeyAlgorithm *string `locationName:"keyAlgorithm" type:"string"` - // The name of the certificate (e.g., my-certificate). + // The name of the certificate (my-certificate). Name *string `locationName:"name" type:"string"` // The timestamp when the certificate expires. @@ -19761,8 +19959,8 @@ type Certificate struct { // The validation status of the certificate. Status *string `locationName:"status" type:"string" enum:"CertificateStatus"` - // An array of strings that specify the alternate domains (e.g., example2.com) - // and subdomains (e.g., blog.example.com) of the certificate. + // An array of strings that specify the alternate domains (example2.com) and + // subdomains (blog.example.com) of the certificate. SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` // The support code. Include this code in your email to support when you have @@ -20113,7 +20311,7 @@ type CloudFormationStackRecord struct { // followed by a GUID. Name *string `locationName:"name" type:"string"` - // The Lightsail resource type (e.g., CloudFormationStackRecord). + // The Lightsail resource type (CloudFormationStackRecord). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // A list of objects describing the source of the CloudFormation stack record. @@ -20200,7 +20398,7 @@ type CloudFormationStackRecordSourceInfo struct { // The name of the record. Name *string `locationName:"name" type:"string"` - // The Lightsail resource type (e.g., ExportSnapshotRecord). + // The Lightsail resource type (ExportSnapshotRecord). ResourceType *string `locationName:"resourceType" type:"string" enum:"CloudFormationStackRecordSourceType"` } @@ -20267,7 +20465,7 @@ type ContactMethod struct { // The protocol of the contact method, such as email or SMS (text messaging). Protocol *string `locationName:"protocol" type:"string" enum:"ContactProtocol"` - // The Lightsail resource type (e.g., ContactMethod). + // The Lightsail resource type of the contact method. ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // The current status of the contact method. @@ -20565,7 +20763,7 @@ type ContainerService struct { // how to specify public domain names for your Lightsail container service. PublicDomainNames map[string][]*string `locationName:"publicDomainNames" type:"map"` - // The Lightsail resource type of the container service (i.e., ContainerService). + // The Lightsail resource type of the container service. ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // The scale specification of the container service. @@ -20766,16 +20964,16 @@ type ContainerServiceDeployment struct { // // A deployment can be in one of the following states: // - // * Activating - The deployment is being created. + // * ACTIVATING - The deployment is being created. // - // * Active - The deployment was successfully created, and it's currently + // * ACTIVE - The deployment was successfully created, and it's currently // running on the container service. The container service can have only // one deployment in an active state at a time. // - // * Inactive - The deployment was previously successfully created, but it + // * INACTIVE - The deployment was previously successfully created, but it // is not currently running on the container service. // - // * Failed - The deployment failed. Use the GetContainerLog action to view + // * FAILED - The deployment failed. Use the GetContainerLog action to view // the log events for the containers in the deployment to try to determine // the reason for the failure. State *string `locationName:"state" type:"string" enum:"ContainerServiceDeploymentState"` @@ -21182,10 +21380,10 @@ type ContainerServicePower struct { // for container services. IsActive *bool `locationName:"isActive" type:"boolean"` - // The friendly name of the power (e.g., nano). + // The friendly name of the power (nano). Name *string `locationName:"name" type:"string"` - // The ID of the power (e.g., nano-1). + // The ID of the power (nano-1). PowerId *string `locationName:"powerId" type:"string"` // The monthly price of the power in USD. @@ -21879,18 +22077,18 @@ type CreateCertificateInput struct { // CertificateName is a required field CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - // The domain name (e.g., example.com) for the certificate. + // The domain name (example.com) for the certificate. // // DomainName is a required field DomainName *string `locationName:"domainName" type:"string" required:"true"` - // An array of strings that specify the alternate domains (e.g., example2.com) - // and subdomains (e.g., blog.example.com) for the certificate. + // An array of strings that specify the alternate domains (example2.com) and + // subdomains (blog.example.com) for the certificate. // // You can specify a maximum of nine alternate domains (in addition to the primary // domain name). // - // Wildcard domain entries (e.g., *.example.com) are not supported. + // Wildcard domain entries (*.example.com) are not supported. SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` // The tag keys and optional values to add to the certificate during create. @@ -22600,9 +22798,9 @@ type CreateDiskFromSnapshotInput struct { // An array of objects that represent the add-ons to enable for the new disk. AddOns []*AddOnRequest `locationName:"addOns" type:"list"` - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Choose the same Availability Zone as the Lightsail instance where you want - // to create the disk. + // The Availability Zone where you want to create the disk (us-east-2a). Choose + // the same Availability Zone as the Lightsail instance where you want to create + // the disk. // // Use the GetRegions operation to list the Availability Zones where Lightsail // is currently available. @@ -22610,13 +22808,13 @@ type CreateDiskFromSnapshotInput struct { // AvailabilityZone is a required field AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // The unique Lightsail disk name (e.g., my-disk). + // The unique Lightsail disk name (my-disk). // // DiskName is a required field DiskName *string `locationName:"diskName" type:"string" required:"true"` - // The name of the disk snapshot (e.g., my-snapshot) from which to create the - // new storage disk. + // The name of the disk snapshot (my-snapshot) from which to create the new + // storage disk. // // Constraint: // @@ -22641,7 +22839,7 @@ type CreateDiskFromSnapshotInput struct { // (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). RestoreDate *string `locationName:"restoreDate" type:"string"` - // The size of the disk in GB (e.g., 32). + // The size of the disk in GB (32). // // SizeInGb is a required field SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` @@ -22820,9 +23018,9 @@ type CreateDiskInput struct { // An array of objects that represent the add-ons to enable for the new disk. AddOns []*AddOnRequest `locationName:"addOns" type:"list"` - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Use the same Availability Zone as the Lightsail instance to which you want - // to attach the disk. + // The Availability Zone where you want to create the disk (us-east-2a). Use + // the same Availability Zone as the Lightsail instance to which you want to + // attach the disk. // // Use the get regions operation to list the Availability Zones where Lightsail // is currently available. @@ -22830,12 +23028,12 @@ type CreateDiskInput struct { // AvailabilityZone is a required field AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // The unique Lightsail disk name (e.g., my-disk). + // The unique Lightsail disk name (my-disk). // // DiskName is a required field DiskName *string `locationName:"diskName" type:"string" required:"true"` - // The size of the disk in GB (e.g., 32). + // The size of the disk in GB (32). // // SizeInGb is a required field SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` @@ -22959,20 +23157,20 @@ func (s *CreateDiskOutput) SetOperations(v []*Operation) *CreateDiskOutput { type CreateDiskSnapshotInput struct { _ struct{} `type:"structure"` - // The unique name of the source disk (e.g., Disk-Virginia-1). + // The unique name of the source disk (Disk-Virginia-1). // // This parameter cannot be defined together with the instance name parameter. // The disk name and instance name parameters are mutually exclusive. DiskName *string `locationName:"diskName" type:"string"` - // The name of the destination disk snapshot (e.g., my-disk-snapshot) based - // on the source disk. + // The name of the destination disk snapshot (my-disk-snapshot) based on the + // source disk. // // DiskSnapshotName is a required field DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` - // The unique name of the source instance (e.g., Amazon_Linux-512MB-Virginia-1). - // When this is defined, a snapshot of the instance's system volume is created. + // The unique name of the source instance (Amazon_Linux-512MB-Virginia-1). When + // this is defined, a snapshot of the instance's system volume is created. // // This parameter cannot be defined together with the disk name parameter. The // instance name and disk name parameters are mutually exclusive. @@ -23262,8 +23460,7 @@ type CreateDomainEntryInput struct { // DomainEntry is a required field DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - // The domain name (e.g., example.com) for which you want to create the domain - // entry. + // The domain name (example.com) for which you want to create the domain entry. // // DomainName is a required field DomainName *string `locationName:"domainName" type:"string" required:"true"` @@ -23351,7 +23548,7 @@ func (s *CreateDomainEntryOutput) SetOperation(v *Operation) *CreateDomainEntryO type CreateDomainInput struct { _ struct{} `type:"structure"` - // The domain name to manage (e.g., example.com). + // The domain name to manage (example.com). // // DomainName is a required field DomainName *string `locationName:"domainName" type:"string" required:"true"` @@ -23674,7 +23871,7 @@ type CreateInstancesFromSnapshotInput struct { AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). + // instance), including the pricing plan (micro_1_0). // // BundleId is a required field BundleId *string `locationName:"bundleId" type:"string" required:"true"` @@ -23938,7 +24135,7 @@ type CreateInstancesInput struct { // AvailabilityZone is a required field AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // The ID for a virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). + // The ID for a virtual private server image (app_wordpress_4_4 or app_lamp_7_0). // Use the get blueprints operation to return a list of available images (or // blueprints). // @@ -23951,15 +24148,15 @@ type CreateInstancesInput struct { BlueprintId *string `locationName:"blueprintId" type:"string" required:"true"` // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). + // instance), including the pricing plan (micro_1_0). // // BundleId is a required field BundleId *string `locationName:"bundleId" type:"string" required:"true"` - // (Deprecated) The name for your custom image. + // (Discontinued) The name for your custom image. // // In releases prior to June 12, 2017, this parameter was ignored by the API. - // It is now deprecated. + // It is now discontinued. // // Deprecated: CustomImageName has been deprecated CustomImageName *string `locationName:"customImageName" deprecated:"true" type:"string"` @@ -24260,10 +24457,10 @@ type CreateLoadBalancerInput struct { _ struct{} `type:"structure"` // The optional alternative domains and subdomains to use with your SSL/TLS - // certificate (e.g., www.example.com, example.com, m.example.com, blog.example.com). + // certificate (www.example.com, example.com, m.example.com, blog.example.com). CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` - // The domain name with which your certificate is associated (e.g., example.com). + // The domain name with which your certificate is associated (example.com). // // If you specify certificateDomainName, then certificateName is required (and // vice-versa). @@ -24277,7 +24474,7 @@ type CreateLoadBalancerInput struct { // The path you provided to perform the load balancer health check. If you didn't // specify a health check path, Lightsail uses the root path of your website - // (e.g., "/"). + // ("/"). // // You may want to specify a custom health check path other than the root of // your application if your home page loads slowly or has a lot of media or @@ -24447,10 +24644,10 @@ type CreateLoadBalancerTlsCertificateInput struct { // An array of strings listing alternative domains and subdomains for your SSL/TLS // certificate. Lightsail will de-dupe the names for you. You can have a maximum // of 9 alternative names (in addition to the 1 primary domain). We do not support - // wildcards (e.g., *.example.com). + // wildcards (*.example.com). CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` - // The domain name (e.g., example.com) for your SSL/TLS certificate. + // The domain name (example.com) for your SSL/TLS certificate. // // CertificateDomainName is a required field CertificateDomainName *string `locationName:"certificateDomainName" type:"string" required:"true"` @@ -25925,7 +26122,7 @@ func (s DeleteContainerServiceOutput) GoString() string { type DeleteDiskInput struct { _ struct{} `type:"structure"` - // The unique name of the disk you want to delete (e.g., my-disk). + // The unique name of the disk you want to delete (my-disk). // // DiskName is a required field DiskName *string `locationName:"diskName" type:"string" required:"true"` @@ -26013,7 +26210,7 @@ func (s *DeleteDiskOutput) SetOperations(v []*Operation) *DeleteDiskOutput { type DeleteDiskSnapshotInput struct { _ struct{} `type:"structure"` - // The name of the disk snapshot you want to delete (e.g., my-disk-snapshot). + // The name of the disk snapshot you want to delete (my-disk-snapshot). // // DiskSnapshotName is a required field DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` @@ -27169,8 +27366,7 @@ func (s *DetachCertificateFromDistributionOutput) SetOperation(v *Operation) *De type DetachDiskInput struct { _ struct{} `type:"structure"` - // The unique name of the disk you want to detach from your instance (e.g., - // my-disk). + // The unique name of the disk you want to detach from your instance (my-disk). // // DiskName is a required field DiskName *string `locationName:"diskName" type:"string" required:"true"` @@ -27525,10 +27721,10 @@ type Disk struct { // The resources to which the disk is attached. AttachedTo *string `locationName:"attachedTo" type:"string"` - // (Deprecated) The attachment state of the disk. + // (Discontinued) The attachment state of the disk. // // In releases prior to November 14, 2017, this parameter returned attached - // for system disks in the API response. It is now deprecated, but still included + // for system disks in the API response. It is now discontinued, but still included // in the response. Use isAttached instead. // // Deprecated: AttachmentState has been deprecated @@ -27542,10 +27738,10 @@ type Disk struct { // The date when the disk was created. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - // (Deprecated) The number of GB in use by the disk. + // (Discontinued) The number of GB in use by the disk. // // In releases prior to November 14, 2017, this parameter was not included in - // the API response. It is now deprecated. + // the API response. It is now discontinued. // // Deprecated: GbInUse has been deprecated GbInUse *int64 `locationName:"gbInUse" deprecated:"true" type:"integer"` @@ -27569,7 +27765,7 @@ type Disk struct { // The disk path. Path *string `locationName:"path" type:"string"` - // The Lightsail resource type (e.g., Disk). + // The Lightsail resource type (Disk). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // The size of the disk in GB. @@ -27728,7 +27924,7 @@ type DiskInfo struct { // The disk path. Path *string `locationName:"path" type:"string"` - // The size of the disk in GB (e.g., 32). + // The size of the disk in GB (32). SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` } @@ -27778,7 +27974,7 @@ func (s *DiskInfo) SetSizeInGb(v int64) *DiskInfo { type DiskMap struct { _ struct{} `type:"structure"` - // The new disk name (e.g., my-new-disk). + // The new disk name (my-new-disk). NewDiskName *string `locationName:"newDiskName" type:"string"` // The original disk path exposed to the instance (for example, /dev/sdh). @@ -27847,13 +28043,13 @@ type DiskSnapshot struct { // The AWS Region and Availability Zone where the disk snapshot was created. Location *ResourceLocation `locationName:"location" type:"structure"` - // The name of the disk snapshot (e.g., my-disk-snapshot). + // The name of the disk snapshot (my-disk-snapshot). Name *string `locationName:"name" type:"string"` // The progress of the snapshot. Progress *string `locationName:"progress" type:"string"` - // The Lightsail resource type (e.g., DiskSnapshot). + // The Lightsail resource type (DiskSnapshot). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // The size of the disk in GB. @@ -27984,7 +28180,7 @@ func (s *DiskSnapshot) SetTags(v []*Tag) *DiskSnapshot { type DiskSnapshotInfo struct { _ struct{} `type:"structure"` - // The size of the disk in GB (e.g., 32). + // The size of the disk in GB (32). SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` } @@ -28146,7 +28342,7 @@ func (s *DnsRecordCreationState) SetMessage(v string) *DnsRecordCreationState { type Domain struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the domain recordset (e.g., arn:aws:lightsail:global:123456789101:Domain/824cede0-abc7-4f84-8dbc-12345EXAMPLE). + // The Amazon Resource Name (ARN) of the domain recordset (arn:aws:lightsail:global:123456789101:Domain/824cede0-abc7-4f84-8dbc-12345EXAMPLE). Arn *string `locationName:"arn" type:"string"` // The date when the domain recordset was created. @@ -28268,15 +28464,15 @@ type DomainEntry struct { // The name of the domain. Name *string `locationName:"name" type:"string"` - // (Deprecated) The options for the domain entry. + // (Discontinued) The options for the domain entry. // // In releases prior to November 29, 2017, this parameter was not included in - // the API response. It is now deprecated. + // the API response. It is now discontinued. // // Deprecated: Options has been deprecated Options map[string]*string `locationName:"options" deprecated:"true" type:"map"` - // The target IP address (e.g., 192.0.2.0), or AWS name server (e.g., ns-111.awsdns-22.com.). + // The target IP address (192.0.2.0), or AWS name server (ns-111.awsdns-22.com.). // // For Lightsail load balancers, the value looks like ab1234c56789c6b86aba6fb203d443bc-123456789.us-east-2.elb.amazonaws.com. // For Lightsail distributions, the value looks like exampled1182ne.cloudfront.net. @@ -28837,7 +29033,7 @@ type ExportSnapshotRecord struct { // The export snapshot record name. Name *string `locationName:"name" type:"string"` - // The Lightsail resource type (e.g., ExportSnapshotRecord). + // The Lightsail resource type (ExportSnapshotRecord). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // A list of objects describing the source of the export snapshot record. @@ -28938,7 +29134,7 @@ type ExportSnapshotRecordSourceInfo struct { // The name of the source instance or disk snapshot. Name *string `locationName:"name" type:"string"` - // The Lightsail resource type (e.g., InstanceSnapshot or DiskSnapshot). + // The Lightsail resource type (InstanceSnapshot or DiskSnapshot). ResourceType *string `locationName:"resourceType" type:"string" enum:"ExportSnapshotRecordSourceType"` } @@ -29248,7 +29444,8 @@ type GetAutoSnapshotsOutput struct { // The name of the source instance or disk for the automatic snapshots. ResourceName *string `locationName:"resourceName" type:"string"` - // The resource type (e.g., Instance or Disk). + // The resource type of the automatic snapshot. The possible values are Instance, + // and Disk. ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` } @@ -30007,6 +30204,13 @@ type GetCertificatesInput struct { // When omitted, the response includes only the certificate names, Amazon Resource // Names (ARNs), domain names, and tags. IncludeCertificateDetails *bool `locationName:"includeCertificateDetails" type:"boolean"` + + // The token to advance to the next page of results from your request. + // + // To get a page token, perform an initial GetCertificates request. If your + // results are paginated, the response will return a next page token that you + // can specify as the page token in a subsequent request. + PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation. @@ -30045,11 +30249,23 @@ func (s *GetCertificatesInput) SetIncludeCertificateDetails(v bool) *GetCertific return s } +// SetPageToken sets the PageToken field's value. +func (s *GetCertificatesInput) SetPageToken(v string) *GetCertificatesInput { + s.PageToken = &v + return s +} + type GetCertificatesOutput struct { _ struct{} `type:"structure"` // An object that describes certificates. Certificates []*CertificateSummary `locationName:"certificates" type:"list"` + + // If NextPageToken is returned there are more results available. The value + // of NextPageToken is a unique pagination token for each page. Make the call + // again using the returned token to retrieve the next page. Keep all other + // arguments unchanged. + NextPageToken *string `locationName:"nextPageToken" type:"string"` } // String returns the string representation. @@ -30076,6 +30292,12 @@ func (s *GetCertificatesOutput) SetCertificates(v []*CertificateSummary) *GetCer return s } +// SetNextPageToken sets the NextPageToken field's value. +func (s *GetCertificatesOutput) SetNextPageToken(v string) *GetCertificatesOutput { + s.NextPageToken = &v + return s +} + type GetCloudFormationStackRecordsInput struct { _ struct{} `type:"structure"` @@ -30965,7 +31187,7 @@ type GetCostEstimateInput struct { // // * Specified in Coordinated Universal Time (UTC). // - // * Specified in the Unix time format. For example, if you wish to use an + // * Specified in the Unix time format. For example, if you want to use an // end time of October 1, 2018, at 9 PM UTC, specify 1538427600 as the end // time. // @@ -30986,7 +31208,7 @@ type GetCostEstimateInput struct { // // * Specified in Coordinated Universal Time (UTC). // - // * Specified in the Unix time format. For example, if you wish to use a + // * Specified in the Unix time format. For example, if you want to use a // start time of October 1, 2018, at 8 PM UTC, specify 1538424000 as the // start time. // @@ -31086,7 +31308,7 @@ func (s *GetCostEstimateOutput) SetResourcesBudgetEstimate(v []*ResourceBudgetEs type GetDiskInput struct { _ struct{} `type:"structure"` - // The name of the disk (e.g., my-disk). + // The name of the disk (my-disk). // // DiskName is a required field DiskName *string `locationName:"diskName" type:"string" required:"true"` @@ -31163,7 +31385,7 @@ func (s *GetDiskOutput) SetDisk(v *Disk) *GetDiskOutput { type GetDiskSnapshotInput struct { _ struct{} `type:"structure"` - // The name of the disk snapshot (e.g., my-disk-snapshot). + // The name of the disk snapshot (my-disk-snapshot). // // DiskSnapshotName is a required field DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` @@ -31491,8 +31713,7 @@ func (s *GetDistributionLatestCacheResetInput) SetDistributionName(v string) *Ge type GetDistributionLatestCacheResetOutput struct { _ struct{} `type:"structure"` - // The timestamp of the last cache reset (e.g., 1479734909.17) in Unix time - // format. + // The timestamp of the last cache reset (1479734909.17) in Unix time format. CreateTime *time.Time `locationName:"createTime" type:"timestamp"` // The status of the last cache reset. @@ -33831,10 +34052,11 @@ func (s *GetOperationsForResourceInput) SetResourceName(v string) *GetOperations type GetOperationsForResourceOutput struct { _ struct{} `type:"structure"` - // (Deprecated) Returns the number of pages of results that remain. + // (Discontinued) Returns the number of pages of results that remain. // // In releases prior to June 12, 2017, this parameter returned null by the API. - // It is now deprecated, and the API returns the next page token parameter instead. + // It is now discontinued, and the API returns the next page token parameter + // instead. // // Deprecated: NextPageCount has been deprecated NextPageCount *string `locationName:"nextPageCount" deprecated:"true" type:"string"` @@ -33976,12 +34198,12 @@ type GetRegionsInput struct { // A Boolean value indicating whether to also include Availability Zones in // your get regions request. Availability Zones are indicated with a letter: - // e.g., us-east-2a. + // us-east-2a. IncludeAvailabilityZones *bool `locationName:"includeAvailabilityZones" type:"boolean"` // A Boolean value indicating whether to also include Availability Zones for // databases in your get regions request. Availability Zones are indicated with - // a letter (e.g., us-east-2a). + // a letter (us-east-2a). IncludeRelationalDatabaseAvailabilityZones *bool `locationName:"includeRelationalDatabaseAvailabilityZones" type:"boolean"` } @@ -35361,6 +35583,113 @@ func (s *GetRelationalDatabasesOutput) SetRelationalDatabases(v []*RelationalDat return s } +type GetSetupHistoryInput struct { + _ struct{} `type:"structure"` + + // The token to advance to the next page of results from your request. + // + // To get a page token, perform an initial GetSetupHistory request. If your + // results are paginated, the response will return a next page token that you + // can specify as the page token in a subsequent request. + PageToken *string `locationName:"pageToken" min:"24" type:"string"` + + // The name of the resource for which you are requesting information. + // + // ResourceName is a required field + ResourceName *string `locationName:"resourceName" type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSetupHistoryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSetupHistoryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetSetupHistoryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetSetupHistoryInput"} + if s.PageToken != nil && len(*s.PageToken) < 24 { + invalidParams.Add(request.NewErrParamMinLen("PageToken", 24)) + } + if s.ResourceName == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPageToken sets the PageToken field's value. +func (s *GetSetupHistoryInput) SetPageToken(v string) *GetSetupHistoryInput { + s.PageToken = &v + return s +} + +// SetResourceName sets the ResourceName field's value. +func (s *GetSetupHistoryInput) SetResourceName(v string) *GetSetupHistoryInput { + s.ResourceName = &v + return s +} + +type GetSetupHistoryOutput struct { + _ struct{} `type:"structure"` + + // The token to advance to the next page of results from your request. + // + // A next page token is not returned if there are no more results to display. + // + // To get the next page of results, perform another GetSetupHistory request + // and specify the next page token using the pageToken parameter. + NextPageToken *string `locationName:"nextPageToken" min:"24" type:"string"` + + // The historical information that's returned. + SetupHistory []*SetupHistory `locationName:"setupHistory" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSetupHistoryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s GetSetupHistoryOutput) GoString() string { + return s.String() +} + +// SetNextPageToken sets the NextPageToken field's value. +func (s *GetSetupHistoryOutput) SetNextPageToken(v string) *GetSetupHistoryOutput { + s.NextPageToken = &v + return s +} + +// SetSetupHistory sets the SetupHistory field's value. +func (s *GetSetupHistoryOutput) SetSetupHistory(v []*SetupHistory) *GetSetupHistoryOutput { + s.SetupHistory = v + return s +} + type GetStaticIpInput struct { _ struct{} `type:"structure"` @@ -35777,9 +36106,9 @@ func (s *ImportKeyPairOutput) SetOperation(v *Operation) *ImportKeyPairOutput { // Describes the origin resource of an Amazon Lightsail content delivery network // (CDN) distribution. // -// An origin can be a Lightsail instance, bucket, or load balancer. A distribution -// pulls content from an origin, caches it, and serves it to viewers via a worldwide -// network of edge servers. +// An origin can be a Lightsail instance, bucket, container service, or load +// balancer. A distribution pulls content from an origin, caches it, and serves +// it to viewers via a worldwide network of edge servers. type InputOrigin struct { _ struct{} `type:"structure"` @@ -35837,20 +36166,20 @@ type Instance struct { // An array of objects representing the add-ons enabled on the instance. AddOns []*AddOn `locationName:"addOns" type:"list"` - // The Amazon Resource Name (ARN) of the instance (e.g., arn:aws:lightsail:us-east-2:123456789101:Instance/244ad76f-8aad-4741-809f-12345EXAMPLE). + // The Amazon Resource Name (ARN) of the instance (arn:aws:lightsail:us-east-2:123456789101:Instance/244ad76f-8aad-4741-809f-12345EXAMPLE). Arn *string `locationName:"arn" type:"string"` - // The blueprint ID (e.g., os_amlinux_2016_03). + // The blueprint ID (os_amlinux_2016_03). BlueprintId *string `locationName:"blueprintId" type:"string"` - // The friendly name of the blueprint (e.g., Amazon Linux). + // The friendly name of the blueprint (Amazon Linux). BlueprintName *string `locationName:"blueprintName" type:"string"` - // The bundle for the instance (e.g., micro_1_0). + // The bundle for the instance (micro_1_0). BundleId *string `locationName:"bundleId" type:"string"` - // The timestamp when the instance was created (e.g., 1479734909.17) in Unix - // time format. + // The timestamp when the instance was created (1479734909.17) in Unix time + // format. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` // The size of the vCPU and the amount of RAM for the instance. @@ -35874,7 +36203,7 @@ type Instance struct { // The metadata options for the Amazon Lightsail instance. MetadataOptions *InstanceMetadataOptions `locationName:"metadataOptions" type:"structure"` - // The name the user gave the instance (e.g., Amazon_Linux-1GB-Ohio-1). + // The name the user gave the instance (Amazon_Linux-1GB-Ohio-1). Name *string `locationName:"name" type:"string"` // Information about the public ports and monthly data transfer rates for the @@ -35890,10 +36219,10 @@ type Instance struct { // The type of resource (usually Instance). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - // The name of the SSH key being used to connect to the instance (e.g., LightsailDefaultKeyPair). + // The name of the SSH key being used to connect to the instance (LightsailDefaultKeyPair). SshKeyName *string `locationName:"sshKeyName" type:"string"` - // The status code and the state (e.g., running) for the instance. + // The status code and the state (running) for the instance. State *InstanceState `locationName:"state" type:"structure"` // The support code. Include this code in your email to support when you have @@ -35905,7 +36234,7 @@ type Instance struct { // tags in Lightsail, see the Amazon Lightsail Developer Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags). Tags []*Tag `locationName:"tags" type:"list"` - // The user name for connecting to the instance (e.g., ec2-user). + // The user name for connecting to the instance (ec2-user). Username *string `locationName:"username" type:"string"` } @@ -36065,7 +36394,7 @@ type InstanceAccessDetails struct { _ struct{} `type:"structure"` // For SSH access, the public key to use when accessing your instance For OpenSSH - // clients (e.g., command line SSH), you should save this value to tempkey-cert.pub. + // clients (command line SSH), you should save this value to tempkey-cert.pub. CertKey *string `locationName:"certKey" type:"string"` // For SSH access, the date on which the temporary keys expire. @@ -36100,8 +36429,8 @@ type InstanceAccessDetails struct { // create an instance, it can take up to 15 minutes for the instance to be ready. PasswordData *PasswordData `locationName:"passwordData" type:"structure"` - // For SSH access, the temporary private key. For OpenSSH clients (e.g., command - // line SSH), you should save this value to tempkey). + // For SSH access, the temporary private key. For OpenSSH clients (command line + // SSH), you should save this value to tempkey). PrivateKey *string `locationName:"privateKey" type:"string"` // The protocol for these Amazon Lightsail instance access details. @@ -36199,7 +36528,7 @@ type InstanceEntry struct { // AvailabilityZone is a required field AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // The instance type (e.g., t2.micro) to use for the new Amazon EC2 instance. + // The instance type (t2.micro) to use for the new Amazon EC2 instance. // // InstanceType is a required field InstanceType *string `locationName:"instanceType" type:"string" required:"true"` @@ -36334,7 +36663,7 @@ type InstanceHardware struct { // The disks attached to the instance. Disks []*Disk `locationName:"disks" type:"list"` - // The amount of RAM in GB on the instance (e.g., 1.0). + // The amount of RAM in GB on the instance (1.0). RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` } @@ -36968,25 +37297,25 @@ func (s *InstancePortState) SetToPort(v int64) *InstancePortState { type InstanceSnapshot struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the snapshot (e.g., arn:aws:lightsail:us-east-2:123456789101:InstanceSnapshot/d23b5706-3322-4d83-81e5-12345EXAMPLE). + // The Amazon Resource Name (ARN) of the snapshot (arn:aws:lightsail:us-east-2:123456789101:InstanceSnapshot/d23b5706-3322-4d83-81e5-12345EXAMPLE). Arn *string `locationName:"arn" type:"string"` - // The timestamp when the snapshot was created (e.g., 1479907467.024). + // The timestamp when the snapshot was created (1479907467.024). CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` // An array of disk objects containing information about all block storage disks. FromAttachedDisks []*Disk `locationName:"fromAttachedDisks" type:"list"` - // The blueprint ID from which you created the snapshot (e.g., os_debian_8_3). - // A blueprint is a virtual private server (or instance) image used to create - // instances quickly. + // The blueprint ID from which you created the snapshot (os_debian_8_3). A blueprint + // is a virtual private server (or instance) image used to create instances + // quickly. FromBlueprintId *string `locationName:"fromBlueprintId" type:"string"` - // The bundle ID from which you created the snapshot (e.g., micro_1_0). + // The bundle ID from which you created the snapshot (micro_1_0). FromBundleId *string `locationName:"fromBundleId" type:"string"` // The Amazon Resource Name (ARN) of the instance from which the snapshot was - // created (e.g., arn:aws:lightsail:us-east-2:123456789101:Instance/64b8404c-ccb1-430b-8daf-12345EXAMPLE). + // created (arn:aws:lightsail:us-east-2:123456789101:Instance/64b8404c-ccb1-430b-8daf-12345EXAMPLE). FromInstanceArn *string `locationName:"fromInstanceArn" type:"string"` // The instance from which the snapshot was created. @@ -37144,10 +37473,10 @@ func (s *InstanceSnapshot) SetTags(v []*Tag) *InstanceSnapshot { type InstanceSnapshotInfo struct { _ struct{} `type:"structure"` - // The blueprint ID from which the source instance (e.g., os_debian_8_3). + // The blueprint ID from which the source instance (os_debian_8_3). FromBlueprintId *string `locationName:"fromBlueprintId" type:"string"` - // The bundle ID from which the source instance was created (e.g., micro_1_0). + // The bundle ID from which the source instance was created (micro_1_0). FromBundleId *string `locationName:"fromBundleId" type:"string"` // A list of objects describing the disks that were attached to the source instance. @@ -37197,7 +37526,7 @@ type InstanceState struct { // The status code for the instance. Code *int64 `locationName:"code" type:"integer"` - // The state of the instance (e.g., running or pending). + // The state of the instance (running or pending). Name *string `locationName:"name" type:"string"` } @@ -37363,10 +37692,10 @@ func (s *IsVpcPeeredOutput) SetIsPeered(v bool) *IsVpcPeeredOutput { type KeyPair struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the key pair (e.g., arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE). + // The Amazon Resource Name (ARN) of the key pair (arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE). Arn *string `locationName:"arn" type:"string"` - // The timestamp when the key pair was created (e.g., 1479816991.349). + // The timestamp when the key pair was created (1479816991.349). CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` // The RSA fingerprint of the key pair. @@ -37523,7 +37852,7 @@ type LightsailDistribution struct { // The public DNS of the origin. OriginPublicDNS *string `locationName:"originPublicDNS" type:"string"` - // The Lightsail resource type (e.g., Distribution). + // The Lightsail resource type (Distribution). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // The status of the distribution. @@ -37715,11 +38044,11 @@ type LoadBalancer struct { // The possible values are ipv4 for IPv4 only, and dualstack for IPv4 and IPv6. IpAddressType *string `locationName:"ipAddressType" type:"string" enum:"IpAddressType"` - // The AWS Region where your load balancer was created (e.g., us-east-2a). Lightsail + // The AWS Region where your load balancer was created (us-east-2a). Lightsail // automatically creates your load balancer across Availability Zones. Location *ResourceLocation `locationName:"location" type:"structure"` - // The name of the load balancer (e.g., my-load-balancer). + // The name of the load balancer (my-load-balancer). Name *string `locationName:"name" type:"string"` // The protocol you have enabled for your load balancer. Valid values are below. @@ -37731,7 +38060,7 @@ type LoadBalancer struct { // 80. For HTTPS, use port 443. PublicPorts []*int64 `locationName:"publicPorts" type:"list"` - // The resource type (e.g., LoadBalancer. + // The resource type (LoadBalancer. ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` // The status of your load balancer. Valid values are below. @@ -37968,7 +38297,7 @@ type LoadBalancerTlsCertificate struct { // certificate. Location *ResourceLocation `locationName:"location" type:"structure"` - // The name of the SSL/TLS certificate (e.g., my-certificate). + // The name of the SSL/TLS certificate (my-certificate). Name *string `locationName:"name" type:"string"` // The timestamp when the SSL/TLS certificate expires. @@ -37981,7 +38310,7 @@ type LoadBalancerTlsCertificate struct { // Lightsail. RenewalSummary *LoadBalancerTlsCertificateRenewalSummary `locationName:"renewalSummary" type:"structure"` - // The resource type (e.g., LoadBalancerTlsCertificate). + // The resource type (LoadBalancerTlsCertificate). // // * Instance - A Lightsail instance (a virtual private server) // @@ -38026,8 +38355,8 @@ type LoadBalancerTlsCertificate struct { // the certificate. Subject *string `locationName:"subject" type:"string"` - // An array of strings that specify the alternate domains (e.g., example2.com) - // and subdomains (e.g., blog.example.com) for the certificate. + // An array of strings that specify the alternate domains (example2.com) and + // subdomains (blog.example.com) for the certificate. SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` // The support code. Include this code in your email to support when you have @@ -38639,7 +38968,7 @@ type MetricDatapoint struct { // The sum. Sum *float64 `locationName:"sum" type:"double"` - // The timestamp (e.g., 1479816991.349). + // The timestamp (1479816991.349). Timestamp *time.Time `locationName:"timestamp" type:"timestamp"` // The unit. @@ -39022,7 +39351,7 @@ func (s *OpenInstancePublicPortsOutput) SetOperation(v *Operation) *OpenInstance type Operation struct { _ struct{} `type:"structure"` - // The timestamp when the operation was initialized (e.g., 1479816991.349). + // The timestamp when the operation was initialized (1479816991.349). CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` // The error code. @@ -39040,7 +39369,7 @@ type Operation struct { // The Amazon Web Services Region and Availability Zone. Location *ResourceLocation `locationName:"location" type:"structure"` - // Details about the operation (e.g., Debian-1GB-Ohio-1). + // Details about the operation (Debian-1GB-Ohio-1). OperationDetails *string `locationName:"operationDetails" type:"string"` // The type of operation. @@ -39055,7 +39384,7 @@ type Operation struct { // The status of the operation. Status *string `locationName:"status" type:"string" enum:"OperationStatus"` - // The timestamp when the status was changed (e.g., 1479816991.349). + // The timestamp when the status was changed (1479816991.349). StatusChangedAt *time.Time `locationName:"statusChangedAt" type:"timestamp"` } @@ -39238,7 +39567,7 @@ type Origin struct { // The AWS Region name of the origin resource. RegionName *string `locationName:"regionName" type:"string" enum:"RegionName"` - // The resource type of the origin resource (e.g., Instance). + // The resource type of the origin resource (Instance). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` } @@ -40411,17 +40740,17 @@ type Region struct { // The Availability Zones. Follows the format us-east-2a (case-sensitive). AvailabilityZones []*AvailabilityZone `locationName:"availabilityZones" type:"list"` - // The continent code (e.g., NA, meaning North America). + // The continent code (NA, meaning North America). ContinentCode *string `locationName:"continentCode" type:"string"` - // The description of the Amazon Web Services Region (e.g., This region is recommended + // The description of the Amazon Web Services Region (This region is recommended // to serve users in the eastern United States and eastern Canada). Description *string `locationName:"description" type:"string"` - // The display name (e.g., Ohio). + // The display name (Ohio). DisplayName *string `locationName:"displayName" type:"string"` - // The region name (e.g., us-east-2). + // The region name (us-east-2). Name *string `locationName:"name" type:"string" enum:"RegionName"` // The Availability Zones for databases. Follows the format us-east-2a (case-sensitive). @@ -41743,8 +42072,7 @@ func (s *ResetDistributionCacheInput) SetDistributionName(v string) *ResetDistri type ResetDistributionCacheOutput struct { _ struct{} `type:"structure"` - // The timestamp of the reset cache request (e.g., 1479734909.17) in Unix time - // format. + // The timestamp of the reset cache request (1479734909.17) in Unix time format. CreateTime *time.Time `locationName:"createTime" type:"timestamp"` // An array of objects that describe the result of the action, such as the status @@ -42216,7 +42544,7 @@ type SetIpAddressTypeInput struct { // The resource type. // - // The possible values are Distribution, Instance, and LoadBalancer. + // The resource values are Distribution, Instance, and LoadBalancer. // // Distribution-related APIs are available only in the N. Virginia (us-east-1) // Amazon Web Services Region. Set your Amazon Web Services Region configuration @@ -42432,6 +42760,412 @@ func (s *SetResourceAccessForBucketOutput) SetOperations(v []*Operation) *SetRes return s } +// Returns details about the commands that were run. +type SetupExecutionDetails struct { + _ struct{} `type:"structure"` + + // The command that was executed. + Command *string `locationName:"command" type:"string"` + + // The timestamp for when the request was run. + DateTime *time.Time `locationName:"dateTime" type:"timestamp"` + + // The name of the target resource. + Name *string `locationName:"name" type:"string"` + + // The text written by the command to stderr. + StandardError *string `locationName:"standardError" type:"string"` + + // The text written by the command to stdout. + StandardOutput *string `locationName:"standardOutput" type:"string"` + + // The status of the SetupInstanceHttps request. + Status *string `locationName:"status" type:"string" enum:"SetupStatus"` + + // The current version of the script.. + Version *string `locationName:"version" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupExecutionDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupExecutionDetails) GoString() string { + return s.String() +} + +// SetCommand sets the Command field's value. +func (s *SetupExecutionDetails) SetCommand(v string) *SetupExecutionDetails { + s.Command = &v + return s +} + +// SetDateTime sets the DateTime field's value. +func (s *SetupExecutionDetails) SetDateTime(v time.Time) *SetupExecutionDetails { + s.DateTime = &v + return s +} + +// SetName sets the Name field's value. +func (s *SetupExecutionDetails) SetName(v string) *SetupExecutionDetails { + s.Name = &v + return s +} + +// SetStandardError sets the StandardError field's value. +func (s *SetupExecutionDetails) SetStandardError(v string) *SetupExecutionDetails { + s.StandardError = &v + return s +} + +// SetStandardOutput sets the StandardOutput field's value. +func (s *SetupExecutionDetails) SetStandardOutput(v string) *SetupExecutionDetails { + s.StandardOutput = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *SetupExecutionDetails) SetStatus(v string) *SetupExecutionDetails { + s.Status = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *SetupExecutionDetails) SetVersion(v string) *SetupExecutionDetails { + s.Version = &v + return s +} + +// Returns a list of the commands that were ran on the target resource. +// +// The status of each command is also returned. +type SetupHistory struct { + _ struct{} `type:"structure"` + + // Describes the full details of the request. + ExecutionDetails []*SetupExecutionDetails `locationName:"executionDetails" type:"list"` + + // A GUID that's used to identify the operation. + OperationId *string `locationName:"operationId" type:"string"` + + // Information about the specified request. + Request *SetupRequest `locationName:"request" type:"structure"` + + // The target resource name for the request. + Resource *SetupHistoryResource `locationName:"resource" type:"structure"` + + // The status of the request. + Status *string `locationName:"status" type:"string" enum:"SetupStatus"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupHistory) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupHistory) GoString() string { + return s.String() +} + +// SetExecutionDetails sets the ExecutionDetails field's value. +func (s *SetupHistory) SetExecutionDetails(v []*SetupExecutionDetails) *SetupHistory { + s.ExecutionDetails = v + return s +} + +// SetOperationId sets the OperationId field's value. +func (s *SetupHistory) SetOperationId(v string) *SetupHistory { + s.OperationId = &v + return s +} + +// SetRequest sets the Request field's value. +func (s *SetupHistory) SetRequest(v *SetupRequest) *SetupHistory { + s.Request = v + return s +} + +// SetResource sets the Resource field's value. +func (s *SetupHistory) SetResource(v *SetupHistoryResource) *SetupHistory { + s.Resource = v + return s +} + +// SetStatus sets the Status field's value. +func (s *SetupHistory) SetStatus(v string) *SetupHistory { + s.Status = &v + return s +} + +// The Lightsail resource that SetupHistory was ran on. +type SetupHistoryResource struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the Lightsail resource. + Arn *string `locationName:"arn" type:"string"` + + // The timestamp for when the resource was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // Describes the resource location. + Location *ResourceLocation `locationName:"location" type:"structure"` + + // The name of the Lightsail resource. + Name *string `locationName:"name" type:"string"` + + // The Lightsail resource type. For example, Instance. + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupHistoryResource) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupHistoryResource) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *SetupHistoryResource) SetArn(v string) *SetupHistoryResource { + s.Arn = &v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *SetupHistoryResource) SetCreatedAt(v time.Time) *SetupHistoryResource { + s.CreatedAt = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *SetupHistoryResource) SetLocation(v *ResourceLocation) *SetupHistoryResource { + s.Location = v + return s +} + +// SetName sets the Name field's value. +func (s *SetupHistoryResource) SetName(v string) *SetupHistoryResource { + s.Name = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *SetupHistoryResource) SetResourceType(v string) *SetupHistoryResource { + s.ResourceType = &v + return s +} + +type SetupInstanceHttpsInput struct { + _ struct{} `type:"structure"` + + // The certificate authority that issues the SSL/TLS certificate. + // + // CertificateProvider is a required field + CertificateProvider *string `locationName:"certificateProvider" type:"string" required:"true" enum:"CertificateProvider"` + + // The name of the domain and subdomains that were specified for the SSL/TLS + // certificate. + // + // DomainNames is a required field + DomainNames []*string `locationName:"domainNames" min:"1" type:"list" required:"true"` + + // The contact method for SSL/TLS certificate renewal alerts. You can enter + // one email address. + // + // EmailAddress is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by SetupInstanceHttpsInput's + // String and GoString methods. + // + // EmailAddress is a required field + EmailAddress *string `locationName:"emailAddress" min:"6" type:"string" required:"true" sensitive:"true"` + + // The name of the Lightsail instance. + // + // InstanceName is a required field + InstanceName *string `locationName:"instanceName" type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupInstanceHttpsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupInstanceHttpsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *SetupInstanceHttpsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SetupInstanceHttpsInput"} + if s.CertificateProvider == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateProvider")) + } + if s.DomainNames == nil { + invalidParams.Add(request.NewErrParamRequired("DomainNames")) + } + if s.DomainNames != nil && len(s.DomainNames) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DomainNames", 1)) + } + if s.EmailAddress == nil { + invalidParams.Add(request.NewErrParamRequired("EmailAddress")) + } + if s.EmailAddress != nil && len(*s.EmailAddress) < 6 { + invalidParams.Add(request.NewErrParamMinLen("EmailAddress", 6)) + } + if s.InstanceName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificateProvider sets the CertificateProvider field's value. +func (s *SetupInstanceHttpsInput) SetCertificateProvider(v string) *SetupInstanceHttpsInput { + s.CertificateProvider = &v + return s +} + +// SetDomainNames sets the DomainNames field's value. +func (s *SetupInstanceHttpsInput) SetDomainNames(v []*string) *SetupInstanceHttpsInput { + s.DomainNames = v + return s +} + +// SetEmailAddress sets the EmailAddress field's value. +func (s *SetupInstanceHttpsInput) SetEmailAddress(v string) *SetupInstanceHttpsInput { + s.EmailAddress = &v + return s +} + +// SetInstanceName sets the InstanceName field's value. +func (s *SetupInstanceHttpsInput) SetInstanceName(v string) *SetupInstanceHttpsInput { + s.InstanceName = &v + return s +} + +type SetupInstanceHttpsOutput struct { + _ struct{} `type:"structure"` + + // The available API operations for SetupInstanceHttps. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupInstanceHttpsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupInstanceHttpsOutput) GoString() string { + return s.String() +} + +// SetOperations sets the Operations field's value. +func (s *SetupInstanceHttpsOutput) SetOperations(v []*Operation) *SetupInstanceHttpsOutput { + s.Operations = v + return s +} + +// Returns information that was submitted during the SetupInstanceHttps request. +// Email information is redacted for privacy. +type SetupRequest struct { + _ struct{} `type:"structure"` + + // The Certificate Authority (CA) that issues the SSL/TLS certificate. + CertificateProvider *string `locationName:"certificateProvider" type:"string" enum:"CertificateProvider"` + + // The name of the domain and subdomains that the SSL/TLS certificate secures. + DomainNames []*string `locationName:"domainNames" min:"1" type:"list"` + + // The name of the Lightsail instance. + InstanceName *string `locationName:"instanceName" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SetupRequest) GoString() string { + return s.String() +} + +// SetCertificateProvider sets the CertificateProvider field's value. +func (s *SetupRequest) SetCertificateProvider(v string) *SetupRequest { + s.CertificateProvider = &v + return s +} + +// SetDomainNames sets the DomainNames field's value. +func (s *SetupRequest) SetDomainNames(v []*string) *SetupRequest { + s.DomainNames = v + return s +} + +// SetInstanceName sets the InstanceName field's value. +func (s *SetupRequest) SetInstanceName(v string) *SetupRequest { + s.InstanceName = &v + return s +} + type StartGUISessionInput struct { _ struct{} `type:"structure"` @@ -42671,13 +43405,13 @@ func (s *StartRelationalDatabaseOutput) SetOperations(v []*Operation) *StartRela type StaticIp struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the static IP (e.g., arn:aws:lightsail:us-east-2:123456789101:StaticIp/9cbb4a9e-f8e3-4dfe-b57e-12345EXAMPLE). + // The Amazon Resource Name (ARN) of the static IP (arn:aws:lightsail:us-east-2:123456789101:StaticIp/9cbb4a9e-f8e3-4dfe-b57e-12345EXAMPLE). Arn *string `locationName:"arn" type:"string"` - // The instance where the static IP is attached (e.g., Amazon_Linux-1GB-Ohio-1). + // The instance where the static IP is attached (Amazon_Linux-1GB-Ohio-1). AttachedTo *string `locationName:"attachedTo" type:"string"` - // The timestamp when the static IP was created (e.g., 1479735304.222). + // The timestamp when the static IP was created (1479735304.222). CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` // The static IP address. @@ -42689,7 +43423,7 @@ type StaticIp struct { // The region and Availability Zone where the static IP was created. Location *ResourceLocation `locationName:"location" type:"structure"` - // The name of the static IP (e.g., StaticIP-Ohio-EXAMPLE). + // The name of the static IP (StaticIP-Ohio-EXAMPLE). Name *string `locationName:"name" type:"string"` // The resource type (usually StaticIp). @@ -44493,7 +45227,7 @@ type UpdateLoadBalancerAttributeInput struct { // AttributeValue is a required field AttributeValue *string `locationName:"attributeValue" min:"1" type:"string" required:"true"` - // The name of the load balancer that you want to modify (e.g., my-load-balancer. + // The name of the load balancer that you want to modify (my-load-balancer. // // LoadBalancerName is a required field LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` @@ -45147,6 +45881,18 @@ func CertificateDomainValidationStatus_Values() []string { } } +const ( + // CertificateProviderLetsEncrypt is a CertificateProvider enum value + CertificateProviderLetsEncrypt = "LetsEncrypt" +) + +// CertificateProvider_Values returns all elements of the CertificateProvider enum +func CertificateProvider_Values() []string { + return []string{ + CertificateProviderLetsEncrypt, + } +} + const ( // CertificateStatusPendingValidation is a CertificateStatus enum value CertificateStatusPendingValidation = "PENDING_VALIDATION" @@ -46805,6 +47551,9 @@ const ( // OperationTypeStopGuisession is a OperationType enum value OperationTypeStopGuisession = "StopGUISession" + + // OperationTypeSetupInstanceHttps is a OperationType enum value + OperationTypeSetupInstanceHttps = "SetupInstanceHttps" ) // OperationType_Values returns all elements of the OperationType enum @@ -46892,6 +47641,7 @@ func OperationType_Values() []string { OperationTypeUpdateInstanceMetadataOptions, OperationTypeStartGuisession, OperationTypeStopGuisession, + OperationTypeSetupInstanceHttps, } } @@ -47299,6 +48049,26 @@ func ResourceType_Values() []string { } } +const ( + // SetupStatusSucceeded is a SetupStatus enum value + SetupStatusSucceeded = "succeeded" + + // SetupStatusFailed is a SetupStatus enum value + SetupStatusFailed = "failed" + + // SetupStatusInProgress is a SetupStatus enum value + SetupStatusInProgress = "inProgress" +) + +// SetupStatus_Values returns all elements of the SetupStatus enum +func SetupStatus_Values() []string { + return []string{ + SetupStatusSucceeded, + SetupStatusFailed, + SetupStatusInProgress, + } +} + const ( // StatusStartExpired is a Status enum value StatusStartExpired = "startExpired" diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/api.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/api.go new file mode 100644 index 000000000..04f6c811b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/api.go @@ -0,0 +1,2252 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package ssooidc + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awsutil" + "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/private/protocol" +) + +const opCreateToken = "CreateToken" + +// CreateTokenRequest generates a "aws/request.Request" representing the +// client's request for the CreateToken operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateToken for more information on using the CreateToken +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the CreateTokenRequest method. +// req, resp := client.CreateTokenRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateToken +func (c *SSOOIDC) CreateTokenRequest(input *CreateTokenInput) (req *request.Request, output *CreateTokenOutput) { + op := &request.Operation{ + Name: opCreateToken, + HTTPMethod: "POST", + HTTPPath: "/token", + } + + if input == nil { + input = &CreateTokenInput{} + } + + output = &CreateTokenOutput{} + req = c.newRequest(op, input, output) + req.Config.Credentials = credentials.AnonymousCredentials + return +} + +// CreateToken API operation for AWS SSO OIDC. +// +// Creates and returns access and refresh tokens for clients that are authenticated +// using client secrets. The access token can be used to fetch short-term credentials +// for the assigned AWS accounts or to access application APIs using bearer +// authentication. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS SSO OIDC's +// API operation CreateToken for usage and error information. +// +// Returned Error Types: +// +// - InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter might be missing or out of range. +// +// - InvalidClientException +// Indicates that the clientId or clientSecret in the request is invalid. For +// example, this can occur when a client sends an incorrect clientId or an expired +// clientSecret. +// +// - InvalidGrantException +// Indicates that a request contains an invalid grant. This can occur if a client +// makes a CreateToken request with an invalid grant type. +// +// - UnauthorizedClientException +// Indicates that the client is not currently authorized to make the request. +// This can happen when a clientId is not issued for a public client. +// +// - UnsupportedGrantTypeException +// Indicates that the grant type in the request is not supported by the service. +// +// - InvalidScopeException +// Indicates that the scope provided in the request is invalid. +// +// - AuthorizationPendingException +// Indicates that a request to authorize a client with an access user session +// token is pending. +// +// - SlowDownException +// Indicates that the client is making the request too frequently and is more +// than the service can handle. +// +// - AccessDeniedException +// You do not have sufficient access to perform this action. +// +// - ExpiredTokenException +// Indicates that the token issued by the service is expired and is no longer +// valid. +// +// - InternalServerException +// Indicates that an error from the service occurred while trying to process +// a request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateToken +func (c *SSOOIDC) CreateToken(input *CreateTokenInput) (*CreateTokenOutput, error) { + req, out := c.CreateTokenRequest(input) + return out, req.Send() +} + +// CreateTokenWithContext is the same as CreateToken with the addition of +// the ability to pass a context and additional request options. +// +// See CreateToken for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSOOIDC) CreateTokenWithContext(ctx aws.Context, input *CreateTokenInput, opts ...request.Option) (*CreateTokenOutput, error) { + req, out := c.CreateTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateTokenWithIAM = "CreateTokenWithIAM" + +// CreateTokenWithIAMRequest generates a "aws/request.Request" representing the +// client's request for the CreateTokenWithIAM operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateTokenWithIAM for more information on using the CreateTokenWithIAM +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the CreateTokenWithIAMRequest method. +// req, resp := client.CreateTokenWithIAMRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateTokenWithIAM +func (c *SSOOIDC) CreateTokenWithIAMRequest(input *CreateTokenWithIAMInput) (req *request.Request, output *CreateTokenWithIAMOutput) { + op := &request.Operation{ + Name: opCreateTokenWithIAM, + HTTPMethod: "POST", + HTTPPath: "/token?aws_iam=t", + } + + if input == nil { + input = &CreateTokenWithIAMInput{} + } + + output = &CreateTokenWithIAMOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateTokenWithIAM API operation for AWS SSO OIDC. +// +// Creates and returns access and refresh tokens for clients and applications +// that are authenticated using IAM entities. The access token can be used to +// fetch short-term credentials for the assigned AWS accounts or to access application +// APIs using bearer authentication. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS SSO OIDC's +// API operation CreateTokenWithIAM for usage and error information. +// +// Returned Error Types: +// +// - InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter might be missing or out of range. +// +// - InvalidClientException +// Indicates that the clientId or clientSecret in the request is invalid. For +// example, this can occur when a client sends an incorrect clientId or an expired +// clientSecret. +// +// - InvalidGrantException +// Indicates that a request contains an invalid grant. This can occur if a client +// makes a CreateToken request with an invalid grant type. +// +// - UnauthorizedClientException +// Indicates that the client is not currently authorized to make the request. +// This can happen when a clientId is not issued for a public client. +// +// - UnsupportedGrantTypeException +// Indicates that the grant type in the request is not supported by the service. +// +// - InvalidScopeException +// Indicates that the scope provided in the request is invalid. +// +// - AuthorizationPendingException +// Indicates that a request to authorize a client with an access user session +// token is pending. +// +// - SlowDownException +// Indicates that the client is making the request too frequently and is more +// than the service can handle. +// +// - AccessDeniedException +// You do not have sufficient access to perform this action. +// +// - ExpiredTokenException +// Indicates that the token issued by the service is expired and is no longer +// valid. +// +// - InternalServerException +// Indicates that an error from the service occurred while trying to process +// a request. +// +// - InvalidRequestRegionException +// Indicates that a token provided as input to the request was issued by and +// is only usable by calling IAM Identity Center endpoints in another region. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateTokenWithIAM +func (c *SSOOIDC) CreateTokenWithIAM(input *CreateTokenWithIAMInput) (*CreateTokenWithIAMOutput, error) { + req, out := c.CreateTokenWithIAMRequest(input) + return out, req.Send() +} + +// CreateTokenWithIAMWithContext is the same as CreateTokenWithIAM with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTokenWithIAM for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSOOIDC) CreateTokenWithIAMWithContext(ctx aws.Context, input *CreateTokenWithIAMInput, opts ...request.Option) (*CreateTokenWithIAMOutput, error) { + req, out := c.CreateTokenWithIAMRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opRegisterClient = "RegisterClient" + +// RegisterClientRequest generates a "aws/request.Request" representing the +// client's request for the RegisterClient operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See RegisterClient for more information on using the RegisterClient +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the RegisterClientRequest method. +// req, resp := client.RegisterClientRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/RegisterClient +func (c *SSOOIDC) RegisterClientRequest(input *RegisterClientInput) (req *request.Request, output *RegisterClientOutput) { + op := &request.Operation{ + Name: opRegisterClient, + HTTPMethod: "POST", + HTTPPath: "/client/register", + } + + if input == nil { + input = &RegisterClientInput{} + } + + output = &RegisterClientOutput{} + req = c.newRequest(op, input, output) + req.Config.Credentials = credentials.AnonymousCredentials + return +} + +// RegisterClient API operation for AWS SSO OIDC. +// +// Registers a client with IAM Identity Center. This allows clients to initiate +// device authorization. The output should be persisted for reuse through many +// authentication requests. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS SSO OIDC's +// API operation RegisterClient for usage and error information. +// +// Returned Error Types: +// +// - InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter might be missing or out of range. +// +// - InvalidScopeException +// Indicates that the scope provided in the request is invalid. +// +// - InvalidClientMetadataException +// Indicates that the client information sent in the request during registration +// is invalid. +// +// - InternalServerException +// Indicates that an error from the service occurred while trying to process +// a request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/RegisterClient +func (c *SSOOIDC) RegisterClient(input *RegisterClientInput) (*RegisterClientOutput, error) { + req, out := c.RegisterClientRequest(input) + return out, req.Send() +} + +// RegisterClientWithContext is the same as RegisterClient with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterClient for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSOOIDC) RegisterClientWithContext(ctx aws.Context, input *RegisterClientInput, opts ...request.Option) (*RegisterClientOutput, error) { + req, out := c.RegisterClientRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opStartDeviceAuthorization = "StartDeviceAuthorization" + +// StartDeviceAuthorizationRequest generates a "aws/request.Request" representing the +// client's request for the StartDeviceAuthorization operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StartDeviceAuthorization for more information on using the StartDeviceAuthorization +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// // Example sending a request using the StartDeviceAuthorizationRequest method. +// req, resp := client.StartDeviceAuthorizationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/StartDeviceAuthorization +func (c *SSOOIDC) StartDeviceAuthorizationRequest(input *StartDeviceAuthorizationInput) (req *request.Request, output *StartDeviceAuthorizationOutput) { + op := &request.Operation{ + Name: opStartDeviceAuthorization, + HTTPMethod: "POST", + HTTPPath: "/device_authorization", + } + + if input == nil { + input = &StartDeviceAuthorizationInput{} + } + + output = &StartDeviceAuthorizationOutput{} + req = c.newRequest(op, input, output) + req.Config.Credentials = credentials.AnonymousCredentials + return +} + +// StartDeviceAuthorization API operation for AWS SSO OIDC. +// +// Initiates device authorization by requesting a pair of verification codes +// from the authorization service. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS SSO OIDC's +// API operation StartDeviceAuthorization for usage and error information. +// +// Returned Error Types: +// +// - InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter might be missing or out of range. +// +// - InvalidClientException +// Indicates that the clientId or clientSecret in the request is invalid. For +// example, this can occur when a client sends an incorrect clientId or an expired +// clientSecret. +// +// - UnauthorizedClientException +// Indicates that the client is not currently authorized to make the request. +// This can happen when a clientId is not issued for a public client. +// +// - SlowDownException +// Indicates that the client is making the request too frequently and is more +// than the service can handle. +// +// - InternalServerException +// Indicates that an error from the service occurred while trying to process +// a request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/StartDeviceAuthorization +func (c *SSOOIDC) StartDeviceAuthorization(input *StartDeviceAuthorizationInput) (*StartDeviceAuthorizationOutput, error) { + req, out := c.StartDeviceAuthorizationRequest(input) + return out, req.Send() +} + +// StartDeviceAuthorizationWithContext is the same as StartDeviceAuthorization with the addition of +// the ability to pass a context and additional request options. +// +// See StartDeviceAuthorization for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSOOIDC) StartDeviceAuthorizationWithContext(ctx aws.Context, input *StartDeviceAuthorizationInput, opts ...request.Option) (*StartDeviceAuthorizationOutput, error) { + req, out := c.StartDeviceAuthorizationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// You do not have sufficient access to perform this action. +type AccessDeniedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be access_denied. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AccessDeniedException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AccessDeniedException) GoString() string { + return s.String() +} + +func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { + return &AccessDeniedException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccessDeniedException) Code() string { + return "AccessDeniedException" +} + +// Message returns the exception's message. +func (s *AccessDeniedException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccessDeniedException) OrigErr() error { + return nil +} + +func (s *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccessDeniedException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccessDeniedException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that a request to authorize a client with an access user session +// token is pending. +type AuthorizationPendingException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be authorization_pending. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AuthorizationPendingException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s AuthorizationPendingException) GoString() string { + return s.String() +} + +func newErrorAuthorizationPendingException(v protocol.ResponseMetadata) error { + return &AuthorizationPendingException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AuthorizationPendingException) Code() string { + return "AuthorizationPendingException" +} + +// Message returns the exception's message. +func (s *AuthorizationPendingException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AuthorizationPendingException) OrigErr() error { + return nil +} + +func (s *AuthorizationPendingException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AuthorizationPendingException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AuthorizationPendingException) RequestID() string { + return s.RespMetadata.RequestID +} + +type CreateTokenInput struct { + _ struct{} `type:"structure"` + + // The unique identifier string for the client or application. This value comes + // from the result of the RegisterClient API. + // + // ClientId is a required field + ClientId *string `locationName:"clientId" type:"string" required:"true"` + + // A secret string generated for the client. This value should come from the + // persisted result of the RegisterClient API. + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenInput's + // String and GoString methods. + // + // ClientSecret is a required field + ClientSecret *string `locationName:"clientSecret" type:"string" required:"true" sensitive:"true"` + + // Used only when calling this API for the Authorization Code grant type. The + // short-term code is used to identify this authorization request. This grant + // type is currently unsupported for the CreateToken API. + Code *string `locationName:"code" type:"string"` + + // Used only when calling this API for the Device Code grant type. This short-term + // code is used to identify this authorization request. This comes from the + // result of the StartDeviceAuthorization API. + DeviceCode *string `locationName:"deviceCode" type:"string"` + + // Supports the following OAuth grant types: Device Code and Refresh Token. + // Specify either of the following values, depending on the grant type that + // you want: + // + // * Device Code - urn:ietf:params:oauth:grant-type:device_code + // + // * Refresh Token - refresh_token + // + // For information about how to obtain the device code, see the StartDeviceAuthorization + // topic. + // + // GrantType is a required field + GrantType *string `locationName:"grantType" type:"string" required:"true"` + + // Used only when calling this API for the Authorization Code grant type. This + // value specifies the location of the client or application that has registered + // to receive the authorization code. + RedirectUri *string `locationName:"redirectUri" type:"string"` + + // Used only when calling this API for the Refresh Token grant type. This token + // is used to refresh short-term tokens, such as the access token, that might + // expire. + // + // For more information about the features and limitations of the current IAM + // Identity Center OIDC implementation, see Considerations for Using this Guide + // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). + // + // RefreshToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenInput's + // String and GoString methods. + RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` + + // The list of scopes for which authorization is requested. The access token + // that is issued is limited to the scopes that are granted. If this value is + // not specified, IAM Identity Center authorizes all scopes that are configured + // for the client during the call to RegisterClient. + Scope []*string `locationName:"scope" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateTokenInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateTokenInput"} + if s.ClientId == nil { + invalidParams.Add(request.NewErrParamRequired("ClientId")) + } + if s.ClientSecret == nil { + invalidParams.Add(request.NewErrParamRequired("ClientSecret")) + } + if s.GrantType == nil { + invalidParams.Add(request.NewErrParamRequired("GrantType")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientId sets the ClientId field's value. +func (s *CreateTokenInput) SetClientId(v string) *CreateTokenInput { + s.ClientId = &v + return s +} + +// SetClientSecret sets the ClientSecret field's value. +func (s *CreateTokenInput) SetClientSecret(v string) *CreateTokenInput { + s.ClientSecret = &v + return s +} + +// SetCode sets the Code field's value. +func (s *CreateTokenInput) SetCode(v string) *CreateTokenInput { + s.Code = &v + return s +} + +// SetDeviceCode sets the DeviceCode field's value. +func (s *CreateTokenInput) SetDeviceCode(v string) *CreateTokenInput { + s.DeviceCode = &v + return s +} + +// SetGrantType sets the GrantType field's value. +func (s *CreateTokenInput) SetGrantType(v string) *CreateTokenInput { + s.GrantType = &v + return s +} + +// SetRedirectUri sets the RedirectUri field's value. +func (s *CreateTokenInput) SetRedirectUri(v string) *CreateTokenInput { + s.RedirectUri = &v + return s +} + +// SetRefreshToken sets the RefreshToken field's value. +func (s *CreateTokenInput) SetRefreshToken(v string) *CreateTokenInput { + s.RefreshToken = &v + return s +} + +// SetScope sets the Scope field's value. +func (s *CreateTokenInput) SetScope(v []*string) *CreateTokenInput { + s.Scope = v + return s +} + +type CreateTokenOutput struct { + _ struct{} `type:"structure"` + + // A bearer token to access AWS accounts and applications assigned to a user. + // + // AccessToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenOutput's + // String and GoString methods. + AccessToken *string `locationName:"accessToken" type:"string" sensitive:"true"` + + // Indicates the time in seconds when an access token will expire. + ExpiresIn *int64 `locationName:"expiresIn" type:"integer"` + + // The idToken is not implemented or supported. For more information about the + // features and limitations of the current IAM Identity Center OIDC implementation, + // see Considerations for Using this Guide in the IAM Identity Center OIDC API + // Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). + // + // A JSON Web Token (JWT) that identifies who is associated with the issued + // access token. + // + // IdToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenOutput's + // String and GoString methods. + IdToken *string `locationName:"idToken" type:"string" sensitive:"true"` + + // A token that, if present, can be used to refresh a previously issued access + // token that might have expired. + // + // For more information about the features and limitations of the current IAM + // Identity Center OIDC implementation, see Considerations for Using this Guide + // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). + // + // RefreshToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenOutput's + // String and GoString methods. + RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` + + // Used to notify the client that the returned token is an access token. The + // supported token type is Bearer. + TokenType *string `locationName:"tokenType" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenOutput) GoString() string { + return s.String() +} + +// SetAccessToken sets the AccessToken field's value. +func (s *CreateTokenOutput) SetAccessToken(v string) *CreateTokenOutput { + s.AccessToken = &v + return s +} + +// SetExpiresIn sets the ExpiresIn field's value. +func (s *CreateTokenOutput) SetExpiresIn(v int64) *CreateTokenOutput { + s.ExpiresIn = &v + return s +} + +// SetIdToken sets the IdToken field's value. +func (s *CreateTokenOutput) SetIdToken(v string) *CreateTokenOutput { + s.IdToken = &v + return s +} + +// SetRefreshToken sets the RefreshToken field's value. +func (s *CreateTokenOutput) SetRefreshToken(v string) *CreateTokenOutput { + s.RefreshToken = &v + return s +} + +// SetTokenType sets the TokenType field's value. +func (s *CreateTokenOutput) SetTokenType(v string) *CreateTokenOutput { + s.TokenType = &v + return s +} + +type CreateTokenWithIAMInput struct { + _ struct{} `type:"structure"` + + // Used only when calling this API for the JWT Bearer grant type. This value + // specifies the JSON Web Token (JWT) issued by a trusted token issuer. To authorize + // a trusted token issuer, configure the JWT Bearer GrantOptions for the application. + // + // Assertion is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenWithIAMInput's + // String and GoString methods. + Assertion *string `locationName:"assertion" type:"string" sensitive:"true"` + + // The unique identifier string for the client or application. This value is + // an application ARN that has OAuth grants configured. + // + // ClientId is a required field + ClientId *string `locationName:"clientId" type:"string" required:"true"` + + // Used only when calling this API for the Authorization Code grant type. This + // short-term code is used to identify this authorization request. The code + // is obtained through a redirect from IAM Identity Center to a redirect URI + // persisted in the Authorization Code GrantOptions for the application. + Code *string `locationName:"code" type:"string"` + + // Supports the following OAuth grant types: Authorization Code, Refresh Token, + // JWT Bearer, and Token Exchange. Specify one of the following values, depending + // on the grant type that you want: + // + // * Authorization Code - authorization_code + // + // * Refresh Token - refresh_token + // + // * JWT Bearer - urn:ietf:params:oauth:grant-type:jwt-bearer + // + // * Token Exchange - urn:ietf:params:oauth:grant-type:token-exchange + // + // GrantType is a required field + GrantType *string `locationName:"grantType" type:"string" required:"true"` + + // Used only when calling this API for the Authorization Code grant type. This + // value specifies the location of the client or application that has registered + // to receive the authorization code. + RedirectUri *string `locationName:"redirectUri" type:"string"` + + // Used only when calling this API for the Refresh Token grant type. This token + // is used to refresh short-term tokens, such as the access token, that might + // expire. + // + // For more information about the features and limitations of the current IAM + // Identity Center OIDC implementation, see Considerations for Using this Guide + // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). + // + // RefreshToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenWithIAMInput's + // String and GoString methods. + RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` + + // Used only when calling this API for the Token Exchange grant type. This value + // specifies the type of token that the requester can receive. The following + // values are supported: + // + // * Access Token - urn:ietf:params:oauth:token-type:access_token + // + // * Refresh Token - urn:ietf:params:oauth:token-type:refresh_token + RequestedTokenType *string `locationName:"requestedTokenType" type:"string"` + + // The list of scopes for which authorization is requested. The access token + // that is issued is limited to the scopes that are granted. If the value is + // not specified, IAM Identity Center authorizes all scopes configured for the + // application, including the following default scopes: openid, aws, sts:identity_context. + Scope []*string `locationName:"scope" type:"list"` + + // Used only when calling this API for the Token Exchange grant type. This value + // specifies the subject of the exchange. The value of the subject token must + // be an access token issued by IAM Identity Center to a different client or + // application. The access token must have authorized scopes that indicate the + // requested application as a target audience. + // + // SubjectToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenWithIAMInput's + // String and GoString methods. + SubjectToken *string `locationName:"subjectToken" type:"string" sensitive:"true"` + + // Used only when calling this API for the Token Exchange grant type. This value + // specifies the type of token that is passed as the subject of the exchange. + // The following value is supported: + // + // * Access Token - urn:ietf:params:oauth:token-type:access_token + SubjectTokenType *string `locationName:"subjectTokenType" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenWithIAMInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenWithIAMInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateTokenWithIAMInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateTokenWithIAMInput"} + if s.ClientId == nil { + invalidParams.Add(request.NewErrParamRequired("ClientId")) + } + if s.GrantType == nil { + invalidParams.Add(request.NewErrParamRequired("GrantType")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAssertion sets the Assertion field's value. +func (s *CreateTokenWithIAMInput) SetAssertion(v string) *CreateTokenWithIAMInput { + s.Assertion = &v + return s +} + +// SetClientId sets the ClientId field's value. +func (s *CreateTokenWithIAMInput) SetClientId(v string) *CreateTokenWithIAMInput { + s.ClientId = &v + return s +} + +// SetCode sets the Code field's value. +func (s *CreateTokenWithIAMInput) SetCode(v string) *CreateTokenWithIAMInput { + s.Code = &v + return s +} + +// SetGrantType sets the GrantType field's value. +func (s *CreateTokenWithIAMInput) SetGrantType(v string) *CreateTokenWithIAMInput { + s.GrantType = &v + return s +} + +// SetRedirectUri sets the RedirectUri field's value. +func (s *CreateTokenWithIAMInput) SetRedirectUri(v string) *CreateTokenWithIAMInput { + s.RedirectUri = &v + return s +} + +// SetRefreshToken sets the RefreshToken field's value. +func (s *CreateTokenWithIAMInput) SetRefreshToken(v string) *CreateTokenWithIAMInput { + s.RefreshToken = &v + return s +} + +// SetRequestedTokenType sets the RequestedTokenType field's value. +func (s *CreateTokenWithIAMInput) SetRequestedTokenType(v string) *CreateTokenWithIAMInput { + s.RequestedTokenType = &v + return s +} + +// SetScope sets the Scope field's value. +func (s *CreateTokenWithIAMInput) SetScope(v []*string) *CreateTokenWithIAMInput { + s.Scope = v + return s +} + +// SetSubjectToken sets the SubjectToken field's value. +func (s *CreateTokenWithIAMInput) SetSubjectToken(v string) *CreateTokenWithIAMInput { + s.SubjectToken = &v + return s +} + +// SetSubjectTokenType sets the SubjectTokenType field's value. +func (s *CreateTokenWithIAMInput) SetSubjectTokenType(v string) *CreateTokenWithIAMInput { + s.SubjectTokenType = &v + return s +} + +type CreateTokenWithIAMOutput struct { + _ struct{} `type:"structure"` + + // A bearer token to access AWS accounts and applications assigned to a user. + // + // AccessToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenWithIAMOutput's + // String and GoString methods. + AccessToken *string `locationName:"accessToken" type:"string" sensitive:"true"` + + // Indicates the time in seconds when an access token will expire. + ExpiresIn *int64 `locationName:"expiresIn" type:"integer"` + + // A JSON Web Token (JWT) that identifies the user associated with the issued + // access token. + // + // IdToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenWithIAMOutput's + // String and GoString methods. + IdToken *string `locationName:"idToken" type:"string" sensitive:"true"` + + // Indicates the type of tokens that are issued by IAM Identity Center. The + // following values are supported: + // + // * Access Token - urn:ietf:params:oauth:token-type:access_token + // + // * Refresh Token - urn:ietf:params:oauth:token-type:refresh_token + IssuedTokenType *string `locationName:"issuedTokenType" type:"string"` + + // A token that, if present, can be used to refresh a previously issued access + // token that might have expired. + // + // For more information about the features and limitations of the current IAM + // Identity Center OIDC implementation, see Considerations for Using this Guide + // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). + // + // RefreshToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateTokenWithIAMOutput's + // String and GoString methods. + RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` + + // The list of scopes for which authorization is granted. The access token that + // is issued is limited to the scopes that are granted. + Scope []*string `locationName:"scope" type:"list"` + + // Used to notify the requester that the returned token is an access token. + // The supported token type is Bearer. + TokenType *string `locationName:"tokenType" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenWithIAMOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s CreateTokenWithIAMOutput) GoString() string { + return s.String() +} + +// SetAccessToken sets the AccessToken field's value. +func (s *CreateTokenWithIAMOutput) SetAccessToken(v string) *CreateTokenWithIAMOutput { + s.AccessToken = &v + return s +} + +// SetExpiresIn sets the ExpiresIn field's value. +func (s *CreateTokenWithIAMOutput) SetExpiresIn(v int64) *CreateTokenWithIAMOutput { + s.ExpiresIn = &v + return s +} + +// SetIdToken sets the IdToken field's value. +func (s *CreateTokenWithIAMOutput) SetIdToken(v string) *CreateTokenWithIAMOutput { + s.IdToken = &v + return s +} + +// SetIssuedTokenType sets the IssuedTokenType field's value. +func (s *CreateTokenWithIAMOutput) SetIssuedTokenType(v string) *CreateTokenWithIAMOutput { + s.IssuedTokenType = &v + return s +} + +// SetRefreshToken sets the RefreshToken field's value. +func (s *CreateTokenWithIAMOutput) SetRefreshToken(v string) *CreateTokenWithIAMOutput { + s.RefreshToken = &v + return s +} + +// SetScope sets the Scope field's value. +func (s *CreateTokenWithIAMOutput) SetScope(v []*string) *CreateTokenWithIAMOutput { + s.Scope = v + return s +} + +// SetTokenType sets the TokenType field's value. +func (s *CreateTokenWithIAMOutput) SetTokenType(v string) *CreateTokenWithIAMOutput { + s.TokenType = &v + return s +} + +// Indicates that the token issued by the service is expired and is no longer +// valid. +type ExpiredTokenException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be expired_token. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ExpiredTokenException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ExpiredTokenException) GoString() string { + return s.String() +} + +func newErrorExpiredTokenException(v protocol.ResponseMetadata) error { + return &ExpiredTokenException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ExpiredTokenException) Code() string { + return "ExpiredTokenException" +} + +// Message returns the exception's message. +func (s *ExpiredTokenException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ExpiredTokenException) OrigErr() error { + return nil +} + +func (s *ExpiredTokenException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ExpiredTokenException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ExpiredTokenException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that an error from the service occurred while trying to process +// a request. +type InternalServerException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be server_error. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InternalServerException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InternalServerException) GoString() string { + return s.String() +} + +func newErrorInternalServerException(v protocol.ResponseMetadata) error { + return &InternalServerException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InternalServerException) Code() string { + return "InternalServerException" +} + +// Message returns the exception's message. +func (s *InternalServerException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalServerException) OrigErr() error { + return nil +} + +func (s *InternalServerException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InternalServerException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InternalServerException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that the clientId or clientSecret in the request is invalid. For +// example, this can occur when a client sends an incorrect clientId or an expired +// clientSecret. +type InvalidClientException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be invalid_client. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidClientException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidClientException) GoString() string { + return s.String() +} + +func newErrorInvalidClientException(v protocol.ResponseMetadata) error { + return &InvalidClientException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidClientException) Code() string { + return "InvalidClientException" +} + +// Message returns the exception's message. +func (s *InvalidClientException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidClientException) OrigErr() error { + return nil +} + +func (s *InvalidClientException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidClientException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidClientException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that the client information sent in the request during registration +// is invalid. +type InvalidClientMetadataException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be invalid_client_metadata. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidClientMetadataException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidClientMetadataException) GoString() string { + return s.String() +} + +func newErrorInvalidClientMetadataException(v protocol.ResponseMetadata) error { + return &InvalidClientMetadataException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidClientMetadataException) Code() string { + return "InvalidClientMetadataException" +} + +// Message returns the exception's message. +func (s *InvalidClientMetadataException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidClientMetadataException) OrigErr() error { + return nil +} + +func (s *InvalidClientMetadataException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidClientMetadataException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidClientMetadataException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that a request contains an invalid grant. This can occur if a client +// makes a CreateToken request with an invalid grant type. +type InvalidGrantException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be invalid_grant. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidGrantException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidGrantException) GoString() string { + return s.String() +} + +func newErrorInvalidGrantException(v protocol.ResponseMetadata) error { + return &InvalidGrantException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidGrantException) Code() string { + return "InvalidGrantException" +} + +// Message returns the exception's message. +func (s *InvalidGrantException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidGrantException) OrigErr() error { + return nil +} + +func (s *InvalidGrantException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidGrantException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidGrantException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that something is wrong with the input to the request. For example, +// a required parameter might be missing or out of range. +type InvalidRequestException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be invalid_request. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidRequestException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidRequestException) GoString() string { + return s.String() +} + +func newErrorInvalidRequestException(v protocol.ResponseMetadata) error { + return &InvalidRequestException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidRequestException) Code() string { + return "InvalidRequestException" +} + +// Message returns the exception's message. +func (s *InvalidRequestException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidRequestException) OrigErr() error { + return nil +} + +func (s *InvalidRequestException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidRequestException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidRequestException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that a token provided as input to the request was issued by and +// is only usable by calling IAM Identity Center endpoints in another region. +type InvalidRequestRegionException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Indicates the IAM Identity Center endpoint which the requester may call with + // this token. + Endpoint *string `locationName:"endpoint" type:"string"` + + // Single error code. For this exception the value will be invalid_request. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` + + // Indicates the region which the requester may call with this token. + Region *string `locationName:"region" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidRequestRegionException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidRequestRegionException) GoString() string { + return s.String() +} + +func newErrorInvalidRequestRegionException(v protocol.ResponseMetadata) error { + return &InvalidRequestRegionException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidRequestRegionException) Code() string { + return "InvalidRequestRegionException" +} + +// Message returns the exception's message. +func (s *InvalidRequestRegionException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidRequestRegionException) OrigErr() error { + return nil +} + +func (s *InvalidRequestRegionException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidRequestRegionException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidRequestRegionException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that the scope provided in the request is invalid. +type InvalidScopeException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be invalid_scope. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidScopeException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s InvalidScopeException) GoString() string { + return s.String() +} + +func newErrorInvalidScopeException(v protocol.ResponseMetadata) error { + return &InvalidScopeException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidScopeException) Code() string { + return "InvalidScopeException" +} + +// Message returns the exception's message. +func (s *InvalidScopeException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidScopeException) OrigErr() error { + return nil +} + +func (s *InvalidScopeException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidScopeException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidScopeException) RequestID() string { + return s.RespMetadata.RequestID +} + +type RegisterClientInput struct { + _ struct{} `type:"structure"` + + // The friendly name of the client. + // + // ClientName is a required field + ClientName *string `locationName:"clientName" type:"string" required:"true"` + + // The type of client. The service supports only public as a client type. Anything + // other than public will be rejected by the service. + // + // ClientType is a required field + ClientType *string `locationName:"clientType" type:"string" required:"true"` + + // The list of scopes that are defined by the client. Upon authorization, this + // list is used to restrict permissions when granting an access token. + Scopes []*string `locationName:"scopes" type:"list"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s RegisterClientInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s RegisterClientInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RegisterClientInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RegisterClientInput"} + if s.ClientName == nil { + invalidParams.Add(request.NewErrParamRequired("ClientName")) + } + if s.ClientType == nil { + invalidParams.Add(request.NewErrParamRequired("ClientType")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientName sets the ClientName field's value. +func (s *RegisterClientInput) SetClientName(v string) *RegisterClientInput { + s.ClientName = &v + return s +} + +// SetClientType sets the ClientType field's value. +func (s *RegisterClientInput) SetClientType(v string) *RegisterClientInput { + s.ClientType = &v + return s +} + +// SetScopes sets the Scopes field's value. +func (s *RegisterClientInput) SetScopes(v []*string) *RegisterClientInput { + s.Scopes = v + return s +} + +type RegisterClientOutput struct { + _ struct{} `type:"structure"` + + // An endpoint that the client can use to request authorization. + AuthorizationEndpoint *string `locationName:"authorizationEndpoint" type:"string"` + + // The unique identifier string for each client. This client uses this identifier + // to get authenticated by the service in subsequent calls. + ClientId *string `locationName:"clientId" type:"string"` + + // Indicates the time at which the clientId and clientSecret were issued. + ClientIdIssuedAt *int64 `locationName:"clientIdIssuedAt" type:"long"` + + // A secret string generated for the client. The client will use this string + // to get authenticated by the service in subsequent calls. + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by RegisterClientOutput's + // String and GoString methods. + ClientSecret *string `locationName:"clientSecret" type:"string" sensitive:"true"` + + // Indicates the time at which the clientId and clientSecret will become invalid. + ClientSecretExpiresAt *int64 `locationName:"clientSecretExpiresAt" type:"long"` + + // An endpoint that the client can use to create tokens. + TokenEndpoint *string `locationName:"tokenEndpoint" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s RegisterClientOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s RegisterClientOutput) GoString() string { + return s.String() +} + +// SetAuthorizationEndpoint sets the AuthorizationEndpoint field's value. +func (s *RegisterClientOutput) SetAuthorizationEndpoint(v string) *RegisterClientOutput { + s.AuthorizationEndpoint = &v + return s +} + +// SetClientId sets the ClientId field's value. +func (s *RegisterClientOutput) SetClientId(v string) *RegisterClientOutput { + s.ClientId = &v + return s +} + +// SetClientIdIssuedAt sets the ClientIdIssuedAt field's value. +func (s *RegisterClientOutput) SetClientIdIssuedAt(v int64) *RegisterClientOutput { + s.ClientIdIssuedAt = &v + return s +} + +// SetClientSecret sets the ClientSecret field's value. +func (s *RegisterClientOutput) SetClientSecret(v string) *RegisterClientOutput { + s.ClientSecret = &v + return s +} + +// SetClientSecretExpiresAt sets the ClientSecretExpiresAt field's value. +func (s *RegisterClientOutput) SetClientSecretExpiresAt(v int64) *RegisterClientOutput { + s.ClientSecretExpiresAt = &v + return s +} + +// SetTokenEndpoint sets the TokenEndpoint field's value. +func (s *RegisterClientOutput) SetTokenEndpoint(v string) *RegisterClientOutput { + s.TokenEndpoint = &v + return s +} + +// Indicates that the client is making the request too frequently and is more +// than the service can handle. +type SlowDownException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be slow_down. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SlowDownException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s SlowDownException) GoString() string { + return s.String() +} + +func newErrorSlowDownException(v protocol.ResponseMetadata) error { + return &SlowDownException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *SlowDownException) Code() string { + return "SlowDownException" +} + +// Message returns the exception's message. +func (s *SlowDownException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *SlowDownException) OrigErr() error { + return nil +} + +func (s *SlowDownException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *SlowDownException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *SlowDownException) RequestID() string { + return s.RespMetadata.RequestID +} + +type StartDeviceAuthorizationInput struct { + _ struct{} `type:"structure"` + + // The unique identifier string for the client that is registered with IAM Identity + // Center. This value should come from the persisted result of the RegisterClient + // API operation. + // + // ClientId is a required field + ClientId *string `locationName:"clientId" type:"string" required:"true"` + + // A secret string that is generated for the client. This value should come + // from the persisted result of the RegisterClient API operation. + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by StartDeviceAuthorizationInput's + // String and GoString methods. + // + // ClientSecret is a required field + ClientSecret *string `locationName:"clientSecret" type:"string" required:"true" sensitive:"true"` + + // The URL for the Amazon Web Services access portal. For more information, + // see Using the Amazon Web Services access portal (https://docs.aws.amazon.com/singlesignon/latest/userguide/using-the-portal.html) + // in the IAM Identity Center User Guide. + // + // StartUrl is a required field + StartUrl *string `locationName:"startUrl" type:"string" required:"true"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s StartDeviceAuthorizationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s StartDeviceAuthorizationInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StartDeviceAuthorizationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StartDeviceAuthorizationInput"} + if s.ClientId == nil { + invalidParams.Add(request.NewErrParamRequired("ClientId")) + } + if s.ClientSecret == nil { + invalidParams.Add(request.NewErrParamRequired("ClientSecret")) + } + if s.StartUrl == nil { + invalidParams.Add(request.NewErrParamRequired("StartUrl")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientId sets the ClientId field's value. +func (s *StartDeviceAuthorizationInput) SetClientId(v string) *StartDeviceAuthorizationInput { + s.ClientId = &v + return s +} + +// SetClientSecret sets the ClientSecret field's value. +func (s *StartDeviceAuthorizationInput) SetClientSecret(v string) *StartDeviceAuthorizationInput { + s.ClientSecret = &v + return s +} + +// SetStartUrl sets the StartUrl field's value. +func (s *StartDeviceAuthorizationInput) SetStartUrl(v string) *StartDeviceAuthorizationInput { + s.StartUrl = &v + return s +} + +type StartDeviceAuthorizationOutput struct { + _ struct{} `type:"structure"` + + // The short-lived code that is used by the device when polling for a session + // token. + DeviceCode *string `locationName:"deviceCode" type:"string"` + + // Indicates the number of seconds in which the verification code will become + // invalid. + ExpiresIn *int64 `locationName:"expiresIn" type:"integer"` + + // Indicates the number of seconds the client must wait between attempts when + // polling for a session. + Interval *int64 `locationName:"interval" type:"integer"` + + // A one-time user verification code. This is needed to authorize an in-use + // device. + UserCode *string `locationName:"userCode" type:"string"` + + // The URI of the verification page that takes the userCode to authorize the + // device. + VerificationUri *string `locationName:"verificationUri" type:"string"` + + // An alternate URL that the client can use to automatically launch a browser. + // This process skips the manual step in which the user visits the verification + // page and enters their code. + VerificationUriComplete *string `locationName:"verificationUriComplete" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s StartDeviceAuthorizationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s StartDeviceAuthorizationOutput) GoString() string { + return s.String() +} + +// SetDeviceCode sets the DeviceCode field's value. +func (s *StartDeviceAuthorizationOutput) SetDeviceCode(v string) *StartDeviceAuthorizationOutput { + s.DeviceCode = &v + return s +} + +// SetExpiresIn sets the ExpiresIn field's value. +func (s *StartDeviceAuthorizationOutput) SetExpiresIn(v int64) *StartDeviceAuthorizationOutput { + s.ExpiresIn = &v + return s +} + +// SetInterval sets the Interval field's value. +func (s *StartDeviceAuthorizationOutput) SetInterval(v int64) *StartDeviceAuthorizationOutput { + s.Interval = &v + return s +} + +// SetUserCode sets the UserCode field's value. +func (s *StartDeviceAuthorizationOutput) SetUserCode(v string) *StartDeviceAuthorizationOutput { + s.UserCode = &v + return s +} + +// SetVerificationUri sets the VerificationUri field's value. +func (s *StartDeviceAuthorizationOutput) SetVerificationUri(v string) *StartDeviceAuthorizationOutput { + s.VerificationUri = &v + return s +} + +// SetVerificationUriComplete sets the VerificationUriComplete field's value. +func (s *StartDeviceAuthorizationOutput) SetVerificationUriComplete(v string) *StartDeviceAuthorizationOutput { + s.VerificationUriComplete = &v + return s +} + +// Indicates that the client is not currently authorized to make the request. +// This can happen when a clientId is not issued for a public client. +type UnauthorizedClientException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be unauthorized_client. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnauthorizedClientException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnauthorizedClientException) GoString() string { + return s.String() +} + +func newErrorUnauthorizedClientException(v protocol.ResponseMetadata) error { + return &UnauthorizedClientException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *UnauthorizedClientException) Code() string { + return "UnauthorizedClientException" +} + +// Message returns the exception's message. +func (s *UnauthorizedClientException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *UnauthorizedClientException) OrigErr() error { + return nil +} + +func (s *UnauthorizedClientException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *UnauthorizedClientException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *UnauthorizedClientException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Indicates that the grant type in the request is not supported by the service. +type UnsupportedGrantTypeException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // Single error code. For this exception the value will be unsupported_grant_type. + Error_ *string `locationName:"error" type:"string"` + + // Human-readable text providing additional information, used to assist the + // client developer in understanding the error that occurred. + Error_description *string `locationName:"error_description" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnsupportedGrantTypeException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s UnsupportedGrantTypeException) GoString() string { + return s.String() +} + +func newErrorUnsupportedGrantTypeException(v protocol.ResponseMetadata) error { + return &UnsupportedGrantTypeException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *UnsupportedGrantTypeException) Code() string { + return "UnsupportedGrantTypeException" +} + +// Message returns the exception's message. +func (s *UnsupportedGrantTypeException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *UnsupportedGrantTypeException) OrigErr() error { + return nil +} + +func (s *UnsupportedGrantTypeException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *UnsupportedGrantTypeException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *UnsupportedGrantTypeException) RequestID() string { + return s.RespMetadata.RequestID +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/doc.go new file mode 100644 index 000000000..083568c61 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/doc.go @@ -0,0 +1,67 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package ssooidc provides the client and types for making API +// requests to AWS SSO OIDC. +// +// IAM Identity Center OpenID Connect (OIDC) is a web service that enables a +// client (such as CLI or a native application) to register with IAM Identity +// Center. The service also enables the client to fetch the user’s access +// token upon successful authentication and authorization with IAM Identity +// Center. +// +// IAM Identity Center uses the sso and identitystore API namespaces. +// +// # Considerations for Using This Guide +// +// Before you begin using this guide, we recommend that you first review the +// following important information about how the IAM Identity Center OIDC service +// works. +// +// - The IAM Identity Center OIDC service currently implements only the portions +// of the OAuth 2.0 Device Authorization Grant standard (https://tools.ietf.org/html/rfc8628 +// (https://tools.ietf.org/html/rfc8628)) that are necessary to enable single +// sign-on authentication with the CLI. +// +// - With older versions of the CLI, the service only emits OIDC access tokens, +// so to obtain a new token, users must explicitly re-authenticate. To access +// the OIDC flow that supports token refresh and doesn’t require re-authentication, +// update to the latest CLI version (1.27.10 for CLI V1 and 2.9.0 for CLI +// V2) with support for OIDC token refresh and configurable IAM Identity +// Center session durations. For more information, see Configure Amazon Web +// Services access portal session duration (https://docs.aws.amazon.com/singlesignon/latest/userguide/configure-user-session.html). +// +// - The access tokens provided by this service grant access to all Amazon +// Web Services account entitlements assigned to an IAM Identity Center user, +// not just a particular application. +// +// - The documentation in this guide does not describe the mechanism to convert +// the access token into Amazon Web Services Auth (“sigv4â€) credentials +// for use with IAM-protected Amazon Web Services service endpoints. For +// more information, see GetRoleCredentials (https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) +// in the IAM Identity Center Portal API Reference Guide. +// +// For general information about IAM Identity Center, see What is IAM Identity +// Center? (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) +// in the IAM Identity Center User Guide. +// +// See https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10 for more information on this service. +// +// See ssooidc package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ssooidc/ +// +// # Using the Client +// +// To contact AWS SSO OIDC with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. +// +// See the SDK's documentation for more information on how to use the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws.Config documentation for more information on configuring SDK clients. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS SSO OIDC client SSOOIDC for more +// information on creating client for this service. +// https://docs.aws.amazon.com/sdk-for-go/api/service/ssooidc/#New +package ssooidc diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/errors.go new file mode 100644 index 000000000..e6242e492 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/errors.go @@ -0,0 +1,115 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package ssooidc + +import ( + "github.com/aws/aws-sdk-go/private/protocol" +) + +const ( + + // ErrCodeAccessDeniedException for service response error code + // "AccessDeniedException". + // + // You do not have sufficient access to perform this action. + ErrCodeAccessDeniedException = "AccessDeniedException" + + // ErrCodeAuthorizationPendingException for service response error code + // "AuthorizationPendingException". + // + // Indicates that a request to authorize a client with an access user session + // token is pending. + ErrCodeAuthorizationPendingException = "AuthorizationPendingException" + + // ErrCodeExpiredTokenException for service response error code + // "ExpiredTokenException". + // + // Indicates that the token issued by the service is expired and is no longer + // valid. + ErrCodeExpiredTokenException = "ExpiredTokenException" + + // ErrCodeInternalServerException for service response error code + // "InternalServerException". + // + // Indicates that an error from the service occurred while trying to process + // a request. + ErrCodeInternalServerException = "InternalServerException" + + // ErrCodeInvalidClientException for service response error code + // "InvalidClientException". + // + // Indicates that the clientId or clientSecret in the request is invalid. For + // example, this can occur when a client sends an incorrect clientId or an expired + // clientSecret. + ErrCodeInvalidClientException = "InvalidClientException" + + // ErrCodeInvalidClientMetadataException for service response error code + // "InvalidClientMetadataException". + // + // Indicates that the client information sent in the request during registration + // is invalid. + ErrCodeInvalidClientMetadataException = "InvalidClientMetadataException" + + // ErrCodeInvalidGrantException for service response error code + // "InvalidGrantException". + // + // Indicates that a request contains an invalid grant. This can occur if a client + // makes a CreateToken request with an invalid grant type. + ErrCodeInvalidGrantException = "InvalidGrantException" + + // ErrCodeInvalidRequestException for service response error code + // "InvalidRequestException". + // + // Indicates that something is wrong with the input to the request. For example, + // a required parameter might be missing or out of range. + ErrCodeInvalidRequestException = "InvalidRequestException" + + // ErrCodeInvalidRequestRegionException for service response error code + // "InvalidRequestRegionException". + // + // Indicates that a token provided as input to the request was issued by and + // is only usable by calling IAM Identity Center endpoints in another region. + ErrCodeInvalidRequestRegionException = "InvalidRequestRegionException" + + // ErrCodeInvalidScopeException for service response error code + // "InvalidScopeException". + // + // Indicates that the scope provided in the request is invalid. + ErrCodeInvalidScopeException = "InvalidScopeException" + + // ErrCodeSlowDownException for service response error code + // "SlowDownException". + // + // Indicates that the client is making the request too frequently and is more + // than the service can handle. + ErrCodeSlowDownException = "SlowDownException" + + // ErrCodeUnauthorizedClientException for service response error code + // "UnauthorizedClientException". + // + // Indicates that the client is not currently authorized to make the request. + // This can happen when a clientId is not issued for a public client. + ErrCodeUnauthorizedClientException = "UnauthorizedClientException" + + // ErrCodeUnsupportedGrantTypeException for service response error code + // "UnsupportedGrantTypeException". + // + // Indicates that the grant type in the request is not supported by the service. + ErrCodeUnsupportedGrantTypeException = "UnsupportedGrantTypeException" +) + +var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ + "AccessDeniedException": newErrorAccessDeniedException, + "AuthorizationPendingException": newErrorAuthorizationPendingException, + "ExpiredTokenException": newErrorExpiredTokenException, + "InternalServerException": newErrorInternalServerException, + "InvalidClientException": newErrorInvalidClientException, + "InvalidClientMetadataException": newErrorInvalidClientMetadataException, + "InvalidGrantException": newErrorInvalidGrantException, + "InvalidRequestException": newErrorInvalidRequestException, + "InvalidRequestRegionException": newErrorInvalidRequestRegionException, + "InvalidScopeException": newErrorInvalidScopeException, + "SlowDownException": newErrorSlowDownException, + "UnauthorizedClientException": newErrorUnauthorizedClientException, + "UnsupportedGrantTypeException": newErrorUnsupportedGrantTypeException, +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/service.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/service.go new file mode 100644 index 000000000..782bae369 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/service.go @@ -0,0 +1,106 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package ssooidc + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/signer/v4" + "github.com/aws/aws-sdk-go/private/protocol" + "github.com/aws/aws-sdk-go/private/protocol/restjson" +) + +// SSOOIDC provides the API operation methods for making requests to +// AWS SSO OIDC. See this package's package overview docs +// for details on the service. +// +// SSOOIDC methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type SSOOIDC struct { + *client.Client +} + +// Used for custom client initialization logic +var initClient func(*client.Client) + +// Used for custom request initialization logic +var initRequest func(*request.Request) + +// Service information constants +const ( + ServiceName = "SSO OIDC" // Name of service. + EndpointsID = "oidc" // ID to lookup a service endpoint with. + ServiceID = "SSO OIDC" // ServiceID is a unique identifier of a specific service. +) + +// New creates a new instance of the SSOOIDC client with a session. +// If additional configuration is needed for the client instance use the optional +// aws.Config parameter to add your extra config. +// +// Example: +// +// mySession := session.Must(session.NewSession()) +// +// // Create a SSOOIDC client from just a session. +// svc := ssooidc.New(mySession) +// +// // Create a SSOOIDC client with additional configuration +// svc := ssooidc.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *SSOOIDC { + c := p.ClientConfig(EndpointsID, cfgs...) + if c.SigningNameDerived || len(c.SigningName) == 0 { + c.SigningName = "sso-oauth" + } + return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *SSOOIDC { + svc := &SSOOIDC{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + ServiceID: ServiceID, + SigningName: signingName, + SigningRegion: signingRegion, + PartitionID: partitionID, + Endpoint: endpoint, + APIVersion: "2019-06-10", + ResolvedRegion: resolvedRegion, + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed( + protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), + ) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a SSOOIDC operation and runs any +// custom request initialization. +func (c *SSOOIDC) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) + + // Run custom request initialization if present + if initRequest != nil { + initRequest(req) + } + + return req +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go index 63729d0a7..2c395f5f6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go @@ -85,9 +85,9 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) // in the IAM User Guide. // -// When you create a role, you create two policies: A role trust policy that -// specifies who can assume the role and a permissions policy that specifies -// what can be done with the role. You specify the trusted principal who is +// When you create a role, you create two policies: a role trust policy that +// specifies who can assume the role, and a permissions policy that specifies +// what can be done with the role. You specify the trusted principal that is // allowed to assume the role in the role trust policy. // // To assume a role from a different account, your Amazon Web Services account @@ -96,9 +96,9 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // are allowed to delegate that access to users in the account. // // A user who wants to access a role in a different account must also have permissions -// that are delegated from the user account administrator. The administrator -// must attach a policy that allows the user to call AssumeRole for the ARN -// of the role in the other account. +// that are delegated from the account administrator. The administrator must +// attach a policy that allows the user to call AssumeRole for the ARN of the +// role in the other account. // // To allow a user to assume a role in the same account, you can do either of // the following: @@ -517,10 +517,8 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // a user. You can also supply the user with a consistent identity throughout // the lifetime of an application. // -// To learn more about Amazon Cognito, see Amazon Cognito Overview (https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#d0e840) -// in Amazon Web Services SDK for Android Developer Guide and Amazon Cognito -// Overview (https://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html#d0e664) -// in the Amazon Web Services SDK for iOS Developer Guide. +// To learn more about Amazon Cognito, see Amazon Cognito identity pools (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) +// in Amazon Cognito Developer Guide. // // Calling AssumeRoleWithWebIdentity does not require the use of Amazon Web // Services security credentials. Therefore, you can distribute an application @@ -984,11 +982,11 @@ func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *requ // call the operation. // // No permissions are required to perform this operation. If an administrator -// adds a policy to your IAM user or role that explicitly denies access to the -// sts:GetCallerIdentity action, you can still perform this operation. Permissions -// are not required because the same information is returned when an IAM user -// or role is denied access. To view an example response, see I Am Not Authorized -// to Perform: iam:DeleteVirtualMFADevice (https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa) +// attaches a policy to your identity that explicitly denies access to the sts:GetCallerIdentity +// action, you can still perform this operation. Permissions are not required +// because the same information is returned when access is denied. To view an +// example response, see I Am Not Authorized to Perform: iam:DeleteVirtualMFADevice +// (https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1063,18 +1061,26 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // GetFederationToken API operation for AWS Security Token Service. // // Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) for a federated user. -// A typical use is in a proxy application that gets temporary security credentials -// on behalf of distributed applications inside a corporate network. You must -// call the GetFederationToken operation using the long-term security credentials -// of an IAM user. As a result, this call is appropriate in contexts where those -// credentials can be safely stored, usually in a server-based application. +// key ID, a secret access key, and a security token) for a user. A typical +// use is in a proxy application that gets temporary security credentials on +// behalf of distributed applications inside a corporate network. +// +// You must call the GetFederationToken operation using the long-term security +// credentials of an IAM user. As a result, this call is appropriate in contexts +// where those credentials can be safeguarded, usually in a server-based application. // For a comparison of GetFederationToken with the other API operations that // produce temporary credentials, see Requesting Temporary Security Credentials // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) // and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) // in the IAM User Guide. // +// Although it is possible to call GetFederationToken using the security credentials +// of an Amazon Web Services account root user rather than an IAM user that +// you create for the purpose of a proxy application, we do not recommend it. +// For more information, see Safeguard your root user credentials and don't +// use them for everyday tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) +// in the IAM User Guide. +// // You can create a mobile-based or browser-based app that can authenticate // users using a web identity provider like Login with Amazon, Facebook, Google, // or an OpenID Connect-compatible identity provider. In this case, we recommend @@ -1083,21 +1089,13 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) // in the IAM User Guide. // -// You can also call GetFederationToken using the security credentials of an -// Amazon Web Services account root user, but we do not recommend it. Instead, -// we recommend that you create an IAM user for the purpose of the proxy application. -// Then attach a policy to the IAM user that limits federated users to only -// the actions and resources that they need to access. For more information, -// see IAM Best Practices (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) -// in the IAM User Guide. -// // # Session duration // // The temporary credentials are valid for the specified duration, from 900 // seconds (15 minutes) up to a maximum of 129,600 seconds (36 hours). The default // session duration is 43,200 seconds (12 hours). Temporary credentials obtained -// by using the Amazon Web Services account root user credentials have a maximum -// duration of 3,600 seconds (1 hour). +// by using the root user credentials have a maximum duration of 3,600 seconds +// (1 hour). // // # Permissions // @@ -1267,12 +1265,13 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // or IAM user. The credentials consist of an access key ID, a secret access // key, and a security token. Typically, you use GetSessionToken if you want // to use MFA to protect programmatic calls to specific Amazon Web Services -// API operations like Amazon EC2 StopInstances. MFA-enabled IAM users would -// need to call GetSessionToken and submit an MFA code that is associated with -// their MFA device. Using the temporary security credentials that are returned -// from the call, IAM users can then make programmatic calls to API operations -// that require MFA authentication. If you do not supply a correct MFA code, -// then the API returns an access denied error. For a comparison of GetSessionToken +// API operations like Amazon EC2 StopInstances. +// +// MFA-enabled IAM users must call GetSessionToken and submit an MFA code that +// is associated with their MFA device. Using the temporary security credentials +// that the call returns, IAM users can then make programmatic calls to API +// operations that require MFA authentication. An incorrect MFA code causes +// the API to return an access denied error. For a comparison of GetSessionToken // with the other API operations that produce temporary credentials, see Requesting // Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) // and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) @@ -1287,13 +1286,12 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // # Session Duration // // The GetSessionToken operation must be called by using the long-term Amazon -// Web Services security credentials of the Amazon Web Services account root -// user or an IAM user. Credentials that are created by IAM users are valid -// for the duration that you specify. This duration can range from 900 seconds -// (15 minutes) up to a maximum of 129,600 seconds (36 hours), with a default -// of 43,200 seconds (12 hours). Credentials based on account credentials can -// range from 900 seconds (15 minutes) up to 3,600 seconds (1 hour), with a -// default of 1 hour. +// Web Services security credentials of an IAM user. Credentials that are created +// by IAM users are valid for the duration that you specify. This duration can +// range from 900 seconds (15 minutes) up to a maximum of 129,600 seconds (36 +// hours), with a default of 43,200 seconds (12 hours). Credentials based on +// account credentials can range from 900 seconds (15 minutes) up to 3,600 seconds +// (1 hour), with a default of 1 hour. // // # Permissions // @@ -1305,20 +1303,20 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // // - You cannot call any STS API except AssumeRole or GetCallerIdentity. // -// We recommend that you do not call GetSessionToken with Amazon Web Services -// account root user credentials. Instead, follow our best practices (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users) -// by creating one or more IAM users, giving them the necessary permissions, -// and using IAM users for everyday interaction with Amazon Web Services. +// The credentials that GetSessionToken returns are based on permissions associated +// with the IAM user whose credentials were used to call the operation. The +// temporary credentials have the same permissions as the IAM user. // -// The credentials that are returned by GetSessionToken are based on permissions -// associated with the user whose credentials were used to call the operation. -// If GetSessionToken is called using Amazon Web Services account root user -// credentials, the temporary credentials have root user permissions. Similarly, -// if GetSessionToken is called using the credentials of an IAM user, the temporary -// credentials have the same permissions as the IAM user. +// Although it is possible to call GetSessionToken using the security credentials +// of an Amazon Web Services account root user rather than an IAM user, we do +// not recommend it. If GetSessionToken is called using root user credentials, +// the temporary credentials have root user permissions. For more information, +// see Safeguard your root user credentials and don't use them for everyday +// tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) +// in the IAM User Guide // // For more information about using GetSessionToken to create temporary credentials, -// go to Temporary Credentials for Users in Untrusted Environments (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) +// see Temporary Credentials for Users in Untrusted Environments (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1462,6 +1460,17 @@ type AssumeRoleInput struct { // in the IAM User Guide. PolicyArns []*PolicyDescriptorType `type:"list"` + // A list of previously acquired trusted context assertions in the format of + // a JSON array. The trusted context assertion is signed and encrypted by Amazon + // Web Services STS. + // + // The following is an example of a ProvidedContext value that includes a single + // trusted context assertion and the ARN of the context provider from which + // the trusted context assertion was generated. + // + // [{"ProviderArn":"arn:aws:iam::aws:contextProvider/IdentityCenter","ContextAssertion":"trusted-context-assertion"}] + ProvidedContexts []*ProvidedContext `type:"list"` + // The Amazon Resource Name (ARN) of the role to assume. // // RoleArn is a required field @@ -1635,6 +1644,16 @@ func (s *AssumeRoleInput) Validate() error { } } } + if s.ProvidedContexts != nil { + for i, v := range s.ProvidedContexts { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ProvidedContexts", i), err.(request.ErrInvalidParams)) + } + } + } if s.Tags != nil { for i, v := range s.Tags { if v == nil { @@ -1676,6 +1695,12 @@ func (s *AssumeRoleInput) SetPolicyArns(v []*PolicyDescriptorType) *AssumeRoleIn return s } +// SetProvidedContexts sets the ProvidedContexts field's value. +func (s *AssumeRoleInput) SetProvidedContexts(v []*ProvidedContext) *AssumeRoleInput { + s.ProvidedContexts = v + return s +} + // SetRoleArn sets the RoleArn field's value. func (s *AssumeRoleInput) SetRoleArn(v string) *AssumeRoleInput { s.RoleArn = &v @@ -1900,8 +1925,12 @@ type AssumeRoleWithSAMLInput struct { // For more information, see Configuring a Relying Party and Adding Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) // in the IAM User Guide. // + // SAMLAssertion is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by AssumeRoleWithSAMLInput's + // String and GoString methods. + // // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true"` + SAMLAssertion *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation. @@ -2036,7 +2065,7 @@ type AssumeRoleWithSAMLOutput struct { // IAM. // // The combination of NameQualifier and Subject can be used to uniquely identify - // a federated user. + // a user. // // The following pseudocode shows how the hash value is calculated: // @@ -2264,10 +2293,15 @@ type AssumeRoleWithWebIdentityInput struct { // The OAuth 2.0 access token or OpenID Connect ID token that is provided by // the identity provider. Your application must get this token by authenticating // the user who is using your application with a web identity provider before - // the application makes an AssumeRoleWithWebIdentity call. + // the application makes an AssumeRoleWithWebIdentity call. Only tokens with + // RSA algorithms (RS256) are supported. + // + // WebIdentityToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by AssumeRoleWithWebIdentityInput's + // String and GoString methods. // // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true"` + WebIdentityToken *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation. @@ -2573,8 +2607,12 @@ type Credentials struct { // The secret access key that can be used to sign requests. // + // SecretAccessKey is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by Credentials's + // String and GoString methods. + // // SecretAccessKey is a required field - SecretAccessKey *string `type:"string" required:"true"` + SecretAccessKey *string `type:"string" required:"true" sensitive:"true"` // The token that users must pass to the service API to use the temporary credentials. // @@ -2922,10 +2960,9 @@ type GetFederationTokenInput struct { // The duration, in seconds, that the session should last. Acceptable durations // for federation sessions range from 900 seconds (15 minutes) to 129,600 seconds // (36 hours), with 43,200 seconds (12 hours) as the default. Sessions obtained - // using Amazon Web Services account root user credentials are restricted to - // a maximum of 3,600 seconds (one hour). If the specified duration is longer - // than one hour, the session obtained by using root user credentials defaults - // to one hour. + // using root user credentials are restricted to a maximum of 3,600 seconds + // (one hour). If the specified duration is longer than one hour, the session + // obtained by using root user credentials defaults to one hour. DurationSeconds *int64 `min:"900" type:"integer"` // The name of the federated user. The name is used as an identifier for the @@ -3376,6 +3413,67 @@ func (s *PolicyDescriptorType) SetArn(v string) *PolicyDescriptorType { return s } +// Contains information about the provided context. This includes the signed +// and encrypted trusted context assertion and the context provider ARN from +// which the trusted context assertion was generated. +type ProvidedContext struct { + _ struct{} `type:"structure"` + + // The signed and encrypted trusted context assertion generated by the context + // provider. The trusted context assertion is signed and encrypted by Amazon + // Web Services STS. + ContextAssertion *string `min:"4" type:"string"` + + // The context provider ARN from which the trusted context assertion was generated. + ProviderArn *string `min:"20" type:"string"` +} + +// String returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ProvidedContext) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation. +// +// API parameter values that are decorated as "sensitive" in the API will not +// be included in the string output. The member name will be present, but the +// value will be replaced with "sensitive". +func (s ProvidedContext) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ProvidedContext) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProvidedContext"} + if s.ContextAssertion != nil && len(*s.ContextAssertion) < 4 { + invalidParams.Add(request.NewErrParamMinLen("ContextAssertion", 4)) + } + if s.ProviderArn != nil && len(*s.ProviderArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("ProviderArn", 20)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetContextAssertion sets the ContextAssertion field's value. +func (s *ProvidedContext) SetContextAssertion(v string) *ProvidedContext { + s.ContextAssertion = &v + return s +} + +// SetProviderArn sets the ProviderArn field's value. +func (s *ProvidedContext) SetProviderArn(v string) *ProvidedContext { + s.ProviderArn = &v + return s +} + // You can pass custom key-value pair attributes when you assume a role or federate // a user. These are called session tags. You can then use the session tags // to control access to resources. For more information, see Tagging Amazon diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go index c40f5a2a5..ea1d9eb0c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go @@ -4,10 +4,9 @@ // requests to AWS Security Token Service. // // Security Token Service (STS) enables you to request temporary, limited-privilege -// credentials for Identity and Access Management (IAM) users or for users that -// you authenticate (federated users). This guide provides descriptions of the -// STS API. For more information about using this service, see Temporary Security -// Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). +// credentials for users. This guide provides descriptions of the STS API. For +// more information about using this service, see Temporary Security Credentials +// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). // // See https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 for more information on this service. // diff --git a/vendor/github.com/bboreham/go-loser/.gitignore b/vendor/github.com/bboreham/go-loser/.gitignore new file mode 100644 index 000000000..3b735ec4a --- /dev/null +++ b/vendor/github.com/bboreham/go-loser/.gitignore @@ -0,0 +1,21 @@ +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work diff --git a/vendor/github.com/bboreham/go-loser/LICENSE b/vendor/github.com/bboreham/go-loser/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/github.com/bboreham/go-loser/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/github.com/bboreham/go-loser/README.md b/vendor/github.com/bboreham/go-loser/README.md new file mode 100644 index 000000000..9e6cbc3cc --- /dev/null +++ b/vendor/github.com/bboreham/go-loser/README.md @@ -0,0 +1,8 @@ +# go-loser +Loser Tree data structure, for fast k-way merge + +I will be speaking about this at [GopherCon](https://www.gophercon.com/agenda/session/1160355) on 27th Sept 2023. + +There are currently two versions of the code on two Git branches: [main](https://github.com/bboreham/go-loser/tree/main), which works for built-in types like `int` and `string`, and [any](https://github.com/bboreham/go-loser/tree/any) which works on any type but requires you to pass in a function pointer to do `less` comparisons. + +See https://en.wikipedia.org/wiki/K-way_merge_algorithm#Tournament_Tree for more details on the algorithm. diff --git a/vendor/github.com/bboreham/go-loser/tree.go b/vendor/github.com/bboreham/go-loser/tree.go new file mode 100644 index 000000000..ba097abed --- /dev/null +++ b/vendor/github.com/bboreham/go-loser/tree.go @@ -0,0 +1,153 @@ +// Loser tree, from https://en.wikipedia.org/wiki/K-way_merge_algorithm#Tournament_Tree + +package loser + +import "golang.org/x/exp/constraints" + +type Value constraints.Ordered + +type Sequence[E Value] interface { + At() E // Returns the current value. + Next() bool // Advances and returns true if there is a value at this new position. +} + +func New[E Value, S Sequence[E]](sequences []S, maxVal E) *Tree[E, S] { + nSequences := len(sequences) + t := Tree[E, S]{ + maxVal: maxVal, + nodes: make([]node[E, S], nSequences*2), + } + for i, s := range sequences { + t.nodes[i+nSequences].items = s + t.moveNext(i + nSequences) // Must call Next on each item so that At() has a value. + } + if nSequences > 0 { + t.nodes[0].index = -1 // flag to be initialized on first call to Next(). + } + return &t +} + +// Call the close function on all sequences that are still open. +func (t *Tree[E, S]) Close() { + for _, e := range t.nodes[len(t.nodes)/2 : len(t.nodes)] { + if e.index == -1 { + continue + } + } +} + +// A loser tree is a binary tree laid out such that nodes N and N+1 have parent N/2. +// We store M leaf nodes in positions M...2M-1, and M-1 internal nodes in positions 1..M-1. +// Node 0 is a special node, containing the winner of the contest. +type Tree[E Value, S Sequence[E]] struct { + maxVal E + nodes []node[E, S] +} + +type node[E Value, S Sequence[E]] struct { + index int // This is the loser for all nodes except the 0th, where it is the winner. + value E // Value copied from the loser node, or winner for node 0. + items S // Only populated for leaf nodes. +} + +func (t *Tree[E, S]) moveNext(index int) bool { + n := &t.nodes[index] + if n.items.Next() { + n.value = n.items.At() + return true + } + n.value = t.maxVal + n.index = -1 + return false +} + +func (t *Tree[E, S]) Winner() S { + return t.nodes[t.nodes[0].index].items +} + +func (t *Tree[E, S]) At() E { + return t.nodes[0].value +} + +func (t *Tree[E, S]) Next() bool { + nodes := t.nodes + if len(nodes) == 0 { + return false + } + if nodes[0].index == -1 { // If tree has not been initialized yet, do that. + t.initialize() + return nodes[nodes[0].index].index != -1 + } + if nodes[nodes[0].index].index == -1 { // already exhausted + return false + } + t.moveNext(nodes[0].index) + t.replayGames(nodes[0].index) + return nodes[nodes[0].index].index != -1 +} + +// Current winner has been advanced independently; fix up the loser tree. +func (t *Tree[E, S]) Fix(closed bool) { + nodes := t.nodes + cur := &nodes[nodes[0].index] + if closed { + cur.value = t.maxVal + cur.index = -1 + } else { + cur.value = cur.items.At() + } + t.replayGames(nodes[0].index) +} + +func (t *Tree[E, S]) IsEmpty() bool { + nodes := t.nodes + if nodes[0].index == -1 { // If tree has not been initialized yet, do that. + t.initialize() + } + return nodes[nodes[0].index].index == -1 +} + +func (t *Tree[E, S]) initialize() { + winner := t.playGame(1) + t.nodes[0].index = winner + t.nodes[0].value = t.nodes[winner].value +} + +// Find the winner at position pos; if it is a non-leaf node, store the loser. +// pos must be >= 1 and < len(t.nodes) +func (t *Tree[E, S]) playGame(pos int) int { + nodes := t.nodes + if pos >= len(nodes)/2 { + return pos + } + left := t.playGame(pos * 2) + right := t.playGame(pos*2 + 1) + var loser, winner int + if nodes[left].value < nodes[right].value { + loser, winner = right, left + } else { + loser, winner = left, right + } + nodes[pos].index = loser + nodes[pos].value = nodes[loser].value + return winner +} + +// Starting at pos, which is a winner, re-consider all values up to the root. +func (t *Tree[E, S]) replayGames(pos int) { + nodes := t.nodes + winningValue := nodes[pos].value + for n := parent(pos); n != 0; n = parent(n) { + node := &nodes[n] + if node.value < winningValue { + // Record pos as the loser here, and the old loser is the new winner. + node.index, pos = pos, node.index + node.value, winningValue = winningValue, node.value + } + } + // pos is now the winner; store it in node 0. + nodes[0].index = pos + nodes[0].value = winningValue +} + +func parent(i int) int { return i >> 1 } diff --git a/vendor/github.com/cncf/xds/go/udpa/annotations/migrate.pb.go b/vendor/github.com/cncf/xds/go/udpa/annotations/migrate.pb.go index 46fb820cf..be9f4678c 100644 --- a/vendor/github.com/cncf/xds/go/udpa/annotations/migrate.pb.go +++ b/vendor/github.com/cncf/xds/go/udpa/annotations/migrate.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: udpa/annotations/migrate.proto package annotations import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type MigrateAnnotation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/udpa/annotations/security.pb.go b/vendor/github.com/cncf/xds/go/udpa/annotations/security.pb.go index e061f5843..aaac45ea3 100644 --- a/vendor/github.com/cncf/xds/go/udpa/annotations/security.pb.go +++ b/vendor/github.com/cncf/xds/go/udpa/annotations/security.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: udpa/annotations/security.proto package annotations import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type FieldSecurityAnnotation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/udpa/annotations/sensitive.pb.go b/vendor/github.com/cncf/xds/go/udpa/annotations/sensitive.pb.go index 0334e8f45..0a46801db 100644 --- a/vendor/github.com/cncf/xds/go/udpa/annotations/sensitive.pb.go +++ b/vendor/github.com/cncf/xds/go/udpa/annotations/sensitive.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: udpa/annotations/sensitive.proto package annotations import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -21,10 +20,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - var file_udpa_annotations_sensitive_proto_extTypes = []protoimpl.ExtensionInfo{ { ExtendedType: (*descriptorpb.FieldOptions)(nil), diff --git a/vendor/github.com/cncf/xds/go/udpa/annotations/status.pb.go b/vendor/github.com/cncf/xds/go/udpa/annotations/status.pb.go index 3f239dd06..25b93a7fe 100644 --- a/vendor/github.com/cncf/xds/go/udpa/annotations/status.pb.go +++ b/vendor/github.com/cncf/xds/go/udpa/annotations/status.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: udpa/annotations/status.proto package annotations import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type PackageVersionStatus int32 const ( diff --git a/vendor/github.com/cncf/xds/go/udpa/annotations/versioning.pb.go b/vendor/github.com/cncf/xds/go/udpa/annotations/versioning.pb.go index 49ced5fb7..7af3ed3f5 100644 --- a/vendor/github.com/cncf/xds/go/udpa/annotations/versioning.pb.go +++ b/vendor/github.com/cncf/xds/go/udpa/annotations/versioning.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: udpa/annotations/versioning.proto package annotations import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type VersioningAnnotation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/xds/annotations/v3/migrate.pb.go b/vendor/github.com/cncf/xds/go/xds/annotations/v3/migrate.pb.go index e29c098b5..cf1ee18ed 100644 --- a/vendor/github.com/cncf/xds/go/xds/annotations/v3/migrate.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/annotations/v3/migrate.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/annotations/v3/migrate.proto package v3 import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type MigrateAnnotation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/xds/annotations/v3/security.pb.go b/vendor/github.com/cncf/xds/go/xds/annotations/v3/security.pb.go index c716366bb..084664ffb 100644 --- a/vendor/github.com/cncf/xds/go/xds/annotations/v3/security.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/annotations/v3/security.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/annotations/v3/security.proto package v3 import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type FieldSecurityAnnotation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/xds/annotations/v3/sensitive.pb.go b/vendor/github.com/cncf/xds/go/xds/annotations/v3/sensitive.pb.go index 2aa60b962..b603aa4c8 100644 --- a/vendor/github.com/cncf/xds/go/xds/annotations/v3/sensitive.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/annotations/v3/sensitive.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/annotations/v3/sensitive.proto package v3 import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -21,10 +20,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - var file_xds_annotations_v3_sensitive_proto_extTypes = []protoimpl.ExtensionInfo{ { ExtendedType: (*descriptorpb.FieldOptions)(nil), diff --git a/vendor/github.com/cncf/xds/go/xds/annotations/v3/status.pb.go b/vendor/github.com/cncf/xds/go/xds/annotations/v3/status.pb.go index 3a2015e62..cc624ac91 100644 --- a/vendor/github.com/cncf/xds/go/xds/annotations/v3/status.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/annotations/v3/status.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/annotations/v3/status.proto package v3 import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type PackageVersionStatus int32 const ( diff --git a/vendor/github.com/cncf/xds/go/xds/annotations/v3/versioning.pb.go b/vendor/github.com/cncf/xds/go/xds/annotations/v3/versioning.pb.go index c789b4c04..225268937 100644 --- a/vendor/github.com/cncf/xds/go/xds/annotations/v3/versioning.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/annotations/v3/versioning.pb.go @@ -1,13 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/annotations/v3/versioning.proto package v3 import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type VersioningAnnotation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/authority.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/authority.pb.go index b4c8ce1cc..d6655c7c8 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/authority.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/authority.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/authority.proto @@ -9,7 +9,6 @@ package v3 import ( _ "github.com/cncf/xds/go/xds/annotations/v3" _ "github.com/envoyproxy/protoc-gen-validate/validate" - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -23,10 +22,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type Authority struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/cidr.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/cidr.pb.go index 482db87f6..0e9a4deba 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/cidr.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/cidr.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/cidr.proto @@ -9,7 +9,6 @@ package v3 import ( _ "github.com/cncf/xds/go/xds/annotations/v3" _ "github.com/envoyproxy/protoc-gen-validate/validate" - proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" @@ -24,10 +23,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type CidrRange struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/collection_entry.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/collection_entry.pb.go index f325e11f6..8f598cb64 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/collection_entry.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/collection_entry.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/collection_entry.proto @@ -9,8 +9,7 @@ package v3 import ( _ "github.com/cncf/xds/go/xds/annotations/v3" _ "github.com/envoyproxy/protoc-gen-validate/validate" - proto "github.com/golang/protobuf/proto" - any "github.com/golang/protobuf/ptypes/any" + any1 "github.com/golang/protobuf/ptypes/any" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -24,16 +23,13 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type CollectionEntry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to ResourceSpecifier: + // // *CollectionEntry_Locator // *CollectionEntry_InlineEntry_ ResourceSpecifier isCollectionEntry_ResourceSpecifier `protobuf_oneof:"resource_specifier"` @@ -113,9 +109,9 @@ type CollectionEntry_InlineEntry struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` - Resource *any.Any `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` + Resource *any1.Any `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` } func (x *CollectionEntry_InlineEntry) Reset() { @@ -164,7 +160,7 @@ func (x *CollectionEntry_InlineEntry) GetVersion() string { return "" } -func (x *CollectionEntry_InlineEntry) GetResource() *any.Any { +func (x *CollectionEntry_InlineEntry) GetResource() *any1.Any { if x != nil { return x.Resource } @@ -231,7 +227,7 @@ var file_xds_core_v3_collection_entry_proto_goTypes = []interface{}{ (*CollectionEntry)(nil), // 0: xds.core.v3.CollectionEntry (*CollectionEntry_InlineEntry)(nil), // 1: xds.core.v3.CollectionEntry.InlineEntry (*ResourceLocator)(nil), // 2: xds.core.v3.ResourceLocator - (*any.Any)(nil), // 3: google.protobuf.Any + (*any1.Any)(nil), // 3: google.protobuf.Any } var file_xds_core_v3_collection_entry_proto_depIdxs = []int32{ 2, // 0: xds.core.v3.CollectionEntry.locator:type_name -> xds.core.v3.ResourceLocator diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/context_params.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/context_params.pb.go index 7473f9099..2d0e2b6ee 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/context_params.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/context_params.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/context_params.proto @@ -8,7 +8,6 @@ package v3 import ( _ "github.com/cncf/xds/go/xds/annotations/v3" - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -22,10 +21,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type ContextParams struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/extension.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/extension.pb.go index 4b801ee08..ba0c24646 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/extension.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/extension.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/extension.proto @@ -8,8 +8,7 @@ package v3 import ( _ "github.com/envoyproxy/protoc-gen-validate/validate" - proto "github.com/golang/protobuf/proto" - any "github.com/golang/protobuf/ptypes/any" + any1 "github.com/golang/protobuf/ptypes/any" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -23,17 +22,13 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type TypedExtensionConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - TypedConfig *any.Any `protobuf:"bytes,2,opt,name=typed_config,json=typedConfig,proto3" json:"typed_config,omitempty"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + TypedConfig *any1.Any `protobuf:"bytes,2,opt,name=typed_config,json=typedConfig,proto3" json:"typed_config,omitempty"` } func (x *TypedExtensionConfig) Reset() { @@ -75,7 +70,7 @@ func (x *TypedExtensionConfig) GetName() string { return "" } -func (x *TypedExtensionConfig) GetTypedConfig() *any.Any { +func (x *TypedExtensionConfig) GetTypedConfig() *any1.Any { if x != nil { return x.TypedConfig } @@ -121,7 +116,7 @@ func file_xds_core_v3_extension_proto_rawDescGZIP() []byte { var file_xds_core_v3_extension_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_xds_core_v3_extension_proto_goTypes = []interface{}{ (*TypedExtensionConfig)(nil), // 0: xds.core.v3.TypedExtensionConfig - (*any.Any)(nil), // 1: google.protobuf.Any + (*any1.Any)(nil), // 1: google.protobuf.Any } var file_xds_core_v3_extension_proto_depIdxs = []int32{ 1, // 0: xds.core.v3.TypedExtensionConfig.typed_config:type_name -> google.protobuf.Any diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/resource.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/resource.pb.go index 42882efa7..915e3c730 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/resource.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/resource.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/resource.proto @@ -8,8 +8,7 @@ package v3 import ( _ "github.com/cncf/xds/go/xds/annotations/v3" - proto "github.com/golang/protobuf/proto" - any "github.com/golang/protobuf/ptypes/any" + any1 "github.com/golang/protobuf/ptypes/any" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -23,10 +22,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type Resource struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -34,7 +29,7 @@ type Resource struct { Name *ResourceName `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` - Resource *any.Any `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` + Resource *any1.Any `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` } func (x *Resource) Reset() { @@ -83,7 +78,7 @@ func (x *Resource) GetVersion() string { return "" } -func (x *Resource) GetResource() *any.Any { +func (x *Resource) GetResource() *any1.Any { if x != nil { return x.Resource } @@ -134,7 +129,7 @@ var file_xds_core_v3_resource_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_xds_core_v3_resource_proto_goTypes = []interface{}{ (*Resource)(nil), // 0: xds.core.v3.Resource (*ResourceName)(nil), // 1: xds.core.v3.ResourceName - (*any.Any)(nil), // 2: google.protobuf.Any + (*any1.Any)(nil), // 2: google.protobuf.Any } var file_xds_core_v3_resource_proto_depIdxs = []int32{ 1, // 0: xds.core.v3.Resource.name:type_name -> xds.core.v3.ResourceName diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/resource_locator.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/resource_locator.pb.go index d0cdd8a3d..bc28d50bb 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/resource_locator.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/resource_locator.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/resource_locator.proto @@ -9,7 +9,6 @@ package v3 import ( _ "github.com/cncf/xds/go/xds/annotations/v3" _ "github.com/envoyproxy/protoc-gen-validate/validate" - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -23,10 +22,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type ResourceLocator_Scheme int32 const ( @@ -86,6 +81,7 @@ type ResourceLocator struct { Authority string `protobuf:"bytes,3,opt,name=authority,proto3" json:"authority,omitempty"` ResourceType string `protobuf:"bytes,4,opt,name=resource_type,json=resourceType,proto3" json:"resource_type,omitempty"` // Types that are assignable to ContextParamSpecifier: + // // *ResourceLocator_ExactContext ContextParamSpecifier isResourceLocator_ContextParamSpecifier `protobuf_oneof:"context_param_specifier"` Directives []*ResourceLocator_Directive `protobuf:"bytes,6,rep,name=directives,proto3" json:"directives,omitempty"` @@ -188,6 +184,7 @@ type ResourceLocator_Directive struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Directive: + // // *ResourceLocator_Directive_Alt // *ResourceLocator_Directive_Entry Directive isResourceLocator_Directive_Directive `protobuf_oneof:"directive"` diff --git a/vendor/github.com/cncf/xds/go/xds/core/v3/resource_name.pb.go b/vendor/github.com/cncf/xds/go/xds/core/v3/resource_name.pb.go index 0ef98bb7c..92a54df4f 100644 --- a/vendor/github.com/cncf/xds/go/xds/core/v3/resource_name.pb.go +++ b/vendor/github.com/cncf/xds/go/xds/core/v3/resource_name.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.28.1 // protoc v3.18.0 // source: xds/core/v3/resource_name.proto @@ -9,7 +9,6 @@ package v3 import ( _ "github.com/cncf/xds/go/xds/annotations/v3" _ "github.com/envoyproxy/protoc-gen-validate/validate" - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -23,10 +22,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type ResourceName struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/github.com/digitalocean/godo/CHANGELOG.md b/vendor/github.com/digitalocean/godo/CHANGELOG.md index 7233c389b..eb84bc9a8 100644 --- a/vendor/github.com/digitalocean/godo/CHANGELOG.md +++ b/vendor/github.com/digitalocean/godo/CHANGELOG.md @@ -1,5 +1,77 @@ # Change Log +## [v1.108.0] - 2024-01-17 + +- #660 - @dweinshenker - Enable CRUD operations for replicas with storage_size_mib + +## [v1.107.0] - 2023-12-07 + +- #658 - @markusthoemmes - APPS-8033 Add the RUN_RESTARTED log type +- #656 - @dweinshenker - Enhancement: add database user update +- #657 - @markusthoemmes - apps: Add registry_credentials field, GHCR registry type and the egress spec + +## [v1.106.0] - 2023-11-14 + +- #654 - @dweinshenker - Remove unclean_leader_election_enable for topic configuration + +## [v1.105.1] - 2023-11-07 + +- #652 - @andrewsomething - Retry on HTTP/2 internal errors. +- #648 - @alexandear - test: use fmt.Fprintf instead of fmt.Fprintf(fmt.Sprintf(...)) +- #651 - @alexandear - test: Replace deprecated io/ioutil with io +- #647 - @alexandear - test: add missing error check + +## [v1.105.0] - 2023-10-16 + +- #643 - @dweinshenker - Add support for scalable storage on database clusters +- #641 - @dweinshenker - Fix Kafka Partition Count +- #645 - @gregmankes - APPS-7325 - update app godo spec +- #642 - @dependabot[bot] - Bump golang.org/x/net from 0.7.0 to 0.17.0 + +## [v1.104.1] - 2023-10-10 + +* #640 - @andrewsomething - Drop required Go version to 1.20 and document policy. +* #640 - @andrewsomething - Fix library version. + +## [v1.104.0] - 2023-10-10 + +- #637 - @mikesmithgh - chore: change uptime alert comparison type +- #638 - @markusthoemmes - APPS-7700 Add ability to specify digest for an image + +## [v1.103.0] - 2023-10-03 + +- #635 - @andrewsomething - Bump github.com/stretchr/testify to v1.8.4 +- #634 - @andrewsomething - Bump Go version to v1.21.0 +- #632 - @danaelhe - Make Retrys by Default for NewFromToken() +- #633 - @dwilsondo - Add DBaaS engine Kafka +- #621 - @testwill - chore: use fmt.Fprintf instead of fmt.Fprint(fmt.Sprintf(...)) + +## [v1.102.1] - 2023-08-17 + +- #629 - @andrewsomething - Provide a custom retryablehttp.ErrorHandler for more consistent returns using retries. + +## [v1.102.0] - 2023-08-14 + +- #624 - @danaelhe - Update README.md with Retryable Info +- #626 - @andrewsomething - Allow configuring go-retryablehttp.Logger +- #625 - @andrewsomething - Export the HTTP client + +## [v1.101.0] - 2023-08-09 + +- #619 - @danaelhe - Add retryablehttp Client Option + +## [v1.100.0] - 2023-07-20 + +- #618 - @asaha - load balancers: introduce new type field +- #620 - @andrewsomething - account: add name field. + +## [v1.99.0] - 2023-04-24 + +- #616 - @bentranter - Bump CI version for Go 1.20 +- #615 - @bentranter - Remove beta support for tokens API +- #604 - @dvigueras - Add support for "Validate a Container Registry Name" +- #613 - @ibilalkayy - updated the README file by showing up the build status icon + ## [v1.98.0] - 2023-03-09 - #608 - @anitgandhi - client: don't process body upon 204 response diff --git a/vendor/github.com/digitalocean/godo/CONTRIBUTING.md b/vendor/github.com/digitalocean/godo/CONTRIBUTING.md index 23bbe202c..388a5bda5 100644 --- a/vendor/github.com/digitalocean/godo/CONTRIBUTING.md +++ b/vendor/github.com/digitalocean/godo/CONTRIBUTING.md @@ -67,3 +67,11 @@ github-changelog-generator -org digitalocean -repo godo 5. Update the `Tag version` and `Release title` field with the new godo version. Be sure the version has a `v` prefixed in both places. Ex `v1.8.0`. 6. Copy the changelog bullet points to the description field. 7. Publish the release. + +## Go Version Support + +This project follows the support [policy of Go](https://go.dev/doc/devel/release#policy) +as its support policy. The two latest major releases of Go are supported by the project. +[CI workflows](.github/workflows/ci.yml) should test against both supported versions. +[go.mod](./go.mod) should specify the oldest of the supported versions to give +downstream users of godo flexibility. diff --git a/vendor/github.com/digitalocean/godo/README.md b/vendor/github.com/digitalocean/godo/README.md index 9a3ec2dad..fd3cdbd51 100644 --- a/vendor/github.com/digitalocean/godo/README.md +++ b/vendor/github.com/digitalocean/godo/README.md @@ -1,6 +1,6 @@ # Godo -[![Build Status](https://travis-ci.org/digitalocean/godo.svg)](https://travis-ci.org/digitalocean/godo) +[![GitHub Actions CI](https://github.com/digitalocean/godo/actions/workflows/ci.yml/badge.svg)](https://github.com/digitalocean/godo/actions/workflows/ci.yml) [![GoDoc](https://godoc.org/github.com/digitalocean/godo?status.svg)](https://godoc.org/github.com/digitalocean/godo) Godo is a Go client library for accessing the DigitalOcean V2 API. @@ -155,6 +155,31 @@ func ListRepositoriesV2(ctx context.Context, client *godo.Client, registryName s } ``` +### Automatic Retries and Exponential Backoff + +The Godo client can be configured to use automatic retries and exponentional backoff for requests that fail with 429 or 500-level response codes via [go-retryablehttp](https://github.com/hashicorp/go-retryablehttp). To configure Godo to enable usage of go-retryablehttp, the `RetryConfig.RetryMax` must be set. + +```go +tokenSrc := oauth2.StaticTokenSource(&oauth2.Token{ + AccessToken: "dop_v1_xxxxxx", +}) + +oauth_client := oauth2.NewClient(oauth2.NoContext, tokenSrc) + +waitMax := godo.PtrTo(6.0) +waitMin := godo.PtrTo(3.0) + +retryConfig := godo.RetryConfig{ + RetryMax: 3, + RetryWaitMin: waitMin, + RetryWaitMax: waitMax, +} + +client, err := godo.New(oauth_client, godo.WithRetryAndBackoffs(retryConfig)) +``` + +Please refer to the [RetryConfig Godo documentation](https://pkg.go.dev/github.com/digitalocean/godo#RetryConfig) for more information. + ## Versioning Each version of the client is tagged and the version is updated accordingly. diff --git a/vendor/github.com/digitalocean/godo/account.go b/vendor/github.com/digitalocean/godo/account.go index 48582c9ee..7f619008e 100644 --- a/vendor/github.com/digitalocean/godo/account.go +++ b/vendor/github.com/digitalocean/godo/account.go @@ -27,6 +27,7 @@ type Account struct { ReservedIPLimit int `json:"reserved_ip_limit,omitempty"` VolumeLimit int `json:"volume_limit,omitempty"` Email string `json:"email,omitempty"` + Name string `json:"name,omitempty"` UUID string `json:"uuid,omitempty"` EmailVerified bool `json:"email_verified,omitempty"` Status string `json:"status,omitempty"` diff --git a/vendor/github.com/digitalocean/godo/apps.gen.go b/vendor/github.com/digitalocean/godo/apps.gen.go index 8bb88858d..7ec24c334 100644 --- a/vendor/github.com/digitalocean/godo/apps.gen.go +++ b/vendor/github.com/digitalocean/godo/apps.gen.go @@ -1,4 +1,5 @@ -// Code generated automatically. DO NOT EDIT. +// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT. +// $ bundle -pkg godo -prefix ./dev/dist/godo package godo @@ -68,7 +69,7 @@ const ( // AppAlertSlackWebhook Configuration of a Slack alerting destination. type AppAlertSlackWebhook struct { - // URL for the Slack webhook. The value will be encrypted on the app spec after it is submitted. + // URL for the Slack webhook. URL string `json:"url,omitempty"` // Name of the Slack channel. Channel string `json:"channel,omitempty"` @@ -120,7 +121,7 @@ const ( AppAlertSpecOperator_LessThan AppAlertSpecOperator = "LESS_THAN" ) -// AppAlertSpecRule - CPU_UTILIZATION: Represents CPU for a given container instance. Only applicable at the component level. - MEM_UTILIZATION: Represents RAM for a given container instance. Only applicable at the component level. - RESTART_COUNT: Represents restart count for a given container instance. Only applicable at the component level. - DEPLOYMENT_FAILED: Represents whether a deployment has failed. Only applicable at the app level. - DEPLOYMENT_LIVE: Represents whether a deployment has succeeded. Only applicable at the app level. - DOMAIN_FAILED: Represents whether a domain configuration has failed. Only applicable at the app level. - DOMAIN_LIVE: Represents whether a domain configuration has succeeded. Only applicable at the app level. - FUNCTIONS_ACTIVATION_COUNT: Represents an activation count for a given functions instance. Only applicable to functions components. - FUNCTIONS_AVERAGE_DURATION_MS: Represents the average duration for function runtimes. Only applicable to functions components. - FUNCTIONS_ERROR_RATE_PER_MINUTE: Represents an error rate per minute for a given functions instance. Only applicable to functions components. - FUNCTIONS_AVERAGE_WAIT_TIME_MS: Represents the average wait time for functions. Only applicable to functions components. - FUNCTIONS_ERROR_COUNT: Represents an error count for a given functions instance. Only applicable to functions components. - FUNCTIONS_GB_RATE_PER_SECOND: Represents the rate of memory consumption (GB x seconds) for functions. Only applicable to functions components. +// AppAlertSpecRule - CPU_UTILIZATION: Represents CPU for a given container instance. Only applicable at the component level. - MEM_UTILIZATION: Represents RAM for a given container instance. Only applicable at the component level. - RESTART_COUNT: Represents restart count for a given container instance. Only applicable at the component level. - DEPLOYMENT_FAILED: Represents whether a deployment has failed. Only applicable at the app level. - DEPLOYMENT_LIVE: Represents whether a deployment has succeeded. Only applicable at the app level. - DEPLOYMENT_STARTED: Represents whether a deployment has started. Only applicable at the app level. - DEPLOYMENT_CANCELED: Represents whether a deployment has been canceled. Only applicable at the app level. - DOMAIN_FAILED: Represents whether a domain configuration has failed. Only applicable at the app level. - DOMAIN_LIVE: Represents whether a domain configuration has succeeded. Only applicable at the app level. - FUNCTIONS_ACTIVATION_COUNT: Represents an activation count for a given functions instance. Only applicable to functions components. - FUNCTIONS_AVERAGE_DURATION_MS: Represents the average duration for function runtimes. Only applicable to functions components. - FUNCTIONS_ERROR_RATE_PER_MINUTE: Represents an error rate per minute for a given functions instance. Only applicable to functions components. - FUNCTIONS_AVERAGE_WAIT_TIME_MS: Represents the average wait time for functions. Only applicable to functions components. - FUNCTIONS_ERROR_COUNT: Represents an error count for a given functions instance. Only applicable to functions components. - FUNCTIONS_GB_RATE_PER_SECOND: Represents the rate of memory consumption (GB x seconds) for functions. Only applicable to functions components. type AppAlertSpecRule string // List of AppAlertSpecRule @@ -131,6 +132,8 @@ const ( AppAlertSpecRule_RestartCount AppAlertSpecRule = "RESTART_COUNT" AppAlertSpecRule_DeploymentFailed AppAlertSpecRule = "DEPLOYMENT_FAILED" AppAlertSpecRule_DeploymentLive AppAlertSpecRule = "DEPLOYMENT_LIVE" + AppAlertSpecRule_DeploymentStarted AppAlertSpecRule = "DEPLOYMENT_STARTED" + AppAlertSpecRule_DeploymentCanceled AppAlertSpecRule = "DEPLOYMENT_CANCELED" AppAlertSpecRule_DomainFailed AppAlertSpecRule = "DOMAIN_FAILED" AppAlertSpecRule_DomainLive AppAlertSpecRule = "DOMAIN_LIVE" AppAlertSpecRule_FunctionsActivationCount AppAlertSpecRule = "FUNCTIONS_ACTIVATION_COUNT" @@ -153,6 +156,26 @@ const ( AppAlertSpecWindow_OneHour AppAlertSpecWindow = "ONE_HOUR" ) +// AppAutoscalingSpec struct for AppAutoscalingSpec +type AppAutoscalingSpec struct { + // The minimum amount of instances for this component. + MinInstanceCount int64 `json:"min_instance_count,omitempty"` + // The maximum amount of instances for this component. + MaxInstanceCount int64 `json:"max_instance_count,omitempty"` + Metrics *AppAutoscalingSpecMetrics `json:"metrics,omitempty"` +} + +// AppAutoscalingSpecMetricCPU struct for AppAutoscalingSpecMetricCPU +type AppAutoscalingSpecMetricCPU struct { + // The average target CPU utilization for the component. + Percent int64 `json:"percent,omitempty"` +} + +// AppAutoscalingSpecMetrics struct for AppAutoscalingSpecMetrics +type AppAutoscalingSpecMetrics struct { + CPU *AppAutoscalingSpecMetricCPU `json:"cpu,omitempty"` +} + // AppBuildConfig struct for AppBuildConfig type AppBuildConfig struct { CNBVersioning *AppBuildConfigCNBVersioning `json:"cnb_versioning,omitempty"` @@ -221,6 +244,20 @@ const ( AppDomainSpecType_Alias AppDomainSpecType = "ALIAS" ) +// AppEgressSpec Specification for app egress configurations. +type AppEgressSpec struct { + Type AppEgressSpecType `json:"type,omitempty"` +} + +// AppEgressSpecType the model 'AppEgressSpecType' +type AppEgressSpecType string + +// List of AppEgressSpecType +const ( + APPEGRESSSPECTYPE_Autoassign AppEgressSpecType = "AUTOASSIGN" + APPEGRESSSPECTYPE_DedicatedIp AppEgressSpecType = "DEDICATED_IP" +) + // AppFunctionsSpec struct for AppFunctionsSpec type AppFunctionsSpec struct { // The name. Must be unique across all components within the same app. @@ -232,7 +269,7 @@ type AppFunctionsSpec struct { SourceDir string `json:"source_dir,omitempty"` // A list of environment variables made available to the component. Envs []*AppVariableDefinition `json:"envs,omitempty"` - // A list of HTTP routes that should be routed to this component. + // (Deprecated) A list of HTTP routes that should be routed to this component. Routes []*AppRouteSpec `json:"routes,omitempty"` // A list of configured alerts the user has enabled. Alerts []*AppAlertSpec `json:"alerts,omitempty"` @@ -291,7 +328,7 @@ type AppIngressSpecRuleRoutingRedirect struct { Port int64 `json:"port,omitempty"` // The scheme to redirect to. Supported values are `http` or `https`. Default: `https`. Scheme string `json:"scheme,omitempty"` - // The redirect code to use. Defaults to `302`. Supported values are 300, 301, 302, 303, 304, 305, 307, 308. + // The redirect code to use. Defaults to `302`. Supported values are 300, 301, 302, 303, 304, 307, 308. RedirectCode int64 `json:"redirect_code,omitempty"` } @@ -384,9 +421,9 @@ type AppLogDestinationSpecPapertrail struct { // AppRouteSpec struct for AppRouteSpec type AppRouteSpec struct { - // An HTTP path prefix. Paths must start with / and must be unique across all components within an app. + // (Deprecated) An HTTP path prefix. Paths must start with / and must be unique across all components within an app. Path string `json:"path,omitempty"` - // An optional flag to preserve the path that is forwarded to the backend service. By default, the HTTP request path will be trimmed from the left when forwarded to the component. For example, a component with `path=/api` will have requests to `/api/list` trimmed to `/list`. If this value is `true`, the path will remain `/api/list`. Note: this is not applicable for Functions Components. + // (Deprecated) An optional flag to preserve the path that is forwarded to the backend service. By default, the HTTP request path will be trimmed from the left when forwarded to the component. For example, a component with `path=/api` will have requests to `/api/list` trimmed to `/list`. If this value is `true`, the path will remain `/api/list`. Note: this is not applicable for Functions Components. PreservePathPrefix bool `json:"preserve_path_prefix,omitempty"` } @@ -411,10 +448,12 @@ type AppServiceSpec struct { // A list of environment variables made available to the component. Envs []*AppVariableDefinition `json:"envs,omitempty"` InstanceSizeSlug string `json:"instance_size_slug,omitempty"` - InstanceCount int64 `json:"instance_count,omitempty"` + // The amount of instances that this component should be scaled to. + InstanceCount int64 `json:"instance_count,omitempty"` + Autoscaling *AppAutoscalingSpec `json:"autoscaling,omitempty"` // The internal port on which this service's run command will listen. Default: 8080 If there is not an environment variable with the name `PORT`, one will be automatically added with its value set to the value of this field. HTTPPort int64 `json:"http_port,omitempty"` - // A list of HTTP routes that should be routed to this component. + // (Deprecated) A list of HTTP routes that should be routed to this component. Routes []*AppRouteSpec `json:"routes,omitempty"` HealthCheck *AppServiceSpecHealthCheck `json:"health_check,omitempty"` CORS *AppCORSPolicy `json:"cors,omitempty"` @@ -470,6 +509,7 @@ type AppSpec struct { // A list of alerts which apply to the app. Alerts []*AppAlertSpec `json:"alerts,omitempty"` Ingress *AppIngressSpec `json:"ingress,omitempty"` + Egress *AppEgressSpec `json:"egress,omitempty"` Features []string `json:"features,omitempty"` } @@ -495,7 +535,7 @@ type AppStaticSiteSpec struct { ErrorDocument string `json:"error_document,omitempty"` // A list of environment variables made available to the component. Envs []*AppVariableDefinition `json:"envs,omitempty"` - // A list of HTTP routes that should be routed to this component. + // (Deprecated) A list of HTTP routes that should be routed to this component. Routes []*AppRouteSpec `json:"routes,omitempty"` CORS *AppCORSPolicy `json:"cors,omitempty"` // The name of the document to use as the fallback for any requests to documents that are not found when serving this static site. Only 1 of `catchall_document` or `error_document` can be set. @@ -533,8 +573,9 @@ type AppWorkerSpec struct { // A list of environment variables made available to the component. Envs []*AppVariableDefinition `json:"envs,omitempty"` // The instance size to use for this component. - InstanceSizeSlug string `json:"instance_size_slug,omitempty"` - InstanceCount int64 `json:"instance_count,omitempty"` + InstanceSizeSlug string `json:"instance_size_slug,omitempty"` + InstanceCount int64 `json:"instance_count,omitempty"` + Autoscaling *AppAutoscalingSpec `json:"autoscaling,omitempty"` // A list of configured alerts which apply to the component. Alerts []*AppAlertSpec `json:"alerts,omitempty"` // A list of configured log forwarding destinations. @@ -559,6 +600,12 @@ type Buildpack struct { DocsLink string `json:"docs_link,omitempty"` } +// DeploymentCauseDetailsAutoscalerAction struct for DeploymentCauseDetailsAutoscalerAction +type DeploymentCauseDetailsAutoscalerAction struct { + // Marker for the deployment being autoscaled. Necessary because the generation tooling can't handle empty messages. + Autoscaled bool `json:"autoscaled,omitempty"` +} + // DeploymentCauseDetailsDigitalOceanUser struct for DeploymentCauseDetailsDigitalOceanUser type DeploymentCauseDetailsDigitalOceanUser struct { UUID string `json:"uuid,omitempty"` @@ -651,10 +698,11 @@ type DeploymentCauseDetails struct { GitPush *DeploymentCauseDetailsGitPush `json:"git_push,omitempty"` DOCRPush *DeploymentCauseDetailsDOCRPush `json:"docr_push,omitempty"` Internal bool `json:"internal,omitempty"` + Autoscaler *DeploymentCauseDetailsAutoscalerAction `json:"autoscaler,omitempty"` Type DeploymentCauseDetailsType `json:"type,omitempty"` } -// DeploymentCauseDetailsType - MANUAL: A deployment that was manually created - DEPLOY_ON_PUSH: A deployment that was automatically created by a Deploy on Push hook - MAINTENANCE: A deployment created for App Platform maintenance - MANUAL_ROLLBACK: A rollback deployment that was manually created - AUTO_ROLLBACK: An automatic rollback deployment created as a result of a previous deployment failing - UPDATE_DATABASE_TRUSTED_SOURCES: A deployment that was created due to an update in database trusted sources. +// DeploymentCauseDetailsType - MANUAL: A deployment that was manually created - DEPLOY_ON_PUSH: A deployment that was automatically created by a Deploy on Push hook - MAINTENANCE: A deployment created for App Platform maintenance - MANUAL_ROLLBACK: A rollback deployment that was manually created - AUTO_ROLLBACK: An automatic rollback deployment created as a result of a previous deployment failing - UPDATE_DATABASE_TRUSTED_SOURCES: A deployment that was created due to an update in database trusted sources. - AUTOSCALED: A deployment that was created due to an autoscaler update. type DeploymentCauseDetailsType string // List of DeploymentCauseDetailsType @@ -666,6 +714,7 @@ const ( DeploymentCauseDetailsType_ManualRollback DeploymentCauseDetailsType = "MANUAL_ROLLBACK" DeploymentCauseDetailsType_AutoRollback DeploymentCauseDetailsType = "AUTO_ROLLBACK" DeploymentCauseDetailsType_UpdateDatabaseTrustedSources DeploymentCauseDetailsType = "UPDATE_DATABASE_TRUSTED_SOURCES" + DeploymentCauseDetailsType_Autoscaled DeploymentCauseDetailsType = "AUTOSCALED" ) // DeploymentFunctions struct for DeploymentFunctions @@ -975,18 +1024,22 @@ type ImageSourceSpec struct { Registry string `json:"registry,omitempty"` // The repository name. Repository string `json:"repository,omitempty"` - // The repository tag. Defaults to `latest` if not provided. - Tag string `json:"tag,omitempty"` - DeployOnPush *ImageSourceSpecDeployOnPush `json:"deploy_on_push,omitempty"` + // The repository tag. Defaults to `latest` if not provided and no digest is provided. Cannot be specified if digest is provided. + Tag string `json:"tag,omitempty"` + // The image digest. Cannot be specified if tag is provided. + Digest string `json:"digest,omitempty"` + // The credentials to be able to pull the image. The value will be encrypted on first submission. On following submissions, the encrypted value should be used. - \"$username:$access_token\" for registries of type `DOCKER_HUB`. - \"$username:$access_token\" for registries of type `GHCR`. + RegistryCredentials string `json:"registry_credentials,omitempty"` + DeployOnPush *ImageSourceSpecDeployOnPush `json:"deploy_on_push,omitempty"` } // ImageSourceSpecDeployOnPush struct for ImageSourceSpecDeployOnPush type ImageSourceSpecDeployOnPush struct { - // Automatically deploy new images. Only for DOCR images. + // Automatically deploy new images. Only for DOCR images. Can't be enabled when a specific digest is specified. Enabled bool `json:"enabled,omitempty"` } -// ImageSourceSpecRegistryType - DOCR: The DigitalOcean container registry type. - DOCKER_HUB: The DockerHub container registry type. +// ImageSourceSpecRegistryType - DOCR: The DigitalOcean container registry type. - DOCKER_HUB: The DockerHub container registry type. - GHCR: The GitHub container registry type. type ImageSourceSpecRegistryType string // List of ImageSourceSpecRegistryType @@ -994,6 +1047,7 @@ const ( ImageSourceSpecRegistryType_Unspecified ImageSourceSpecRegistryType = "UNSPECIFIED" ImageSourceSpecRegistryType_DOCR ImageSourceSpecRegistryType = "DOCR" ImageSourceSpecRegistryType_DockerHub ImageSourceSpecRegistryType = "DOCKER_HUB" + ImageSourceSpecRegistryType_Ghcr ImageSourceSpecRegistryType = "GHCR" ) // AppInstanceSize struct for AppInstanceSize diff --git a/vendor/github.com/digitalocean/godo/apps.go b/vendor/github.com/digitalocean/godo/apps.go index 422b48acc..880ce0921 100644 --- a/vendor/github.com/digitalocean/godo/apps.go +++ b/vendor/github.com/digitalocean/godo/apps.go @@ -21,6 +21,8 @@ const ( AppLogTypeDeploy AppLogType = "DEPLOY" // AppLogTypeRun represents run logs. AppLogTypeRun AppLogType = "RUN" + // AppLogTypeRunRestarted represents logs of crashed/restarted instances during runtime. + AppLogTypeRunRestarted AppLogType = "RUN_RESTARTED" ) // AppsService is an interface for interfacing with the App Platform endpoints diff --git a/vendor/github.com/digitalocean/godo/apps_accessors.go b/vendor/github.com/digitalocean/godo/apps_accessors.go index 82bba4347..059d64731 100644 --- a/vendor/github.com/digitalocean/godo/apps_accessors.go +++ b/vendor/github.com/digitalocean/godo/apps_accessors.go @@ -1,4 +1,11 @@ -// Code generated automatically. DO NOT EDIT. +// Copyright 2017 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by gen-accessors; DO NOT EDIT. +// Instead, please run "go generate ./..." as described here: +// https://github.com/google/go-github/blob/master/CONTRIBUTING.md#submitting-a-patch package godo @@ -350,6 +357,46 @@ func (a *AppAlertSpec) GetWindow() AppAlertSpecWindow { return a.Window } +// GetMaxInstanceCount returns the MaxInstanceCount field. +func (a *AppAutoscalingSpec) GetMaxInstanceCount() int64 { + if a == nil { + return 0 + } + return a.MaxInstanceCount +} + +// GetMetrics returns the Metrics field. +func (a *AppAutoscalingSpec) GetMetrics() *AppAutoscalingSpecMetrics { + if a == nil { + return nil + } + return a.Metrics +} + +// GetMinInstanceCount returns the MinInstanceCount field. +func (a *AppAutoscalingSpec) GetMinInstanceCount() int64 { + if a == nil { + return 0 + } + return a.MinInstanceCount +} + +// GetPercent returns the Percent field. +func (a *AppAutoscalingSpecMetricCPU) GetPercent() int64 { + if a == nil { + return 0 + } + return a.Percent +} + +// GetCPU returns the CPU field. +func (a *AppAutoscalingSpecMetrics) GetCPU() *AppAutoscalingSpecMetricCPU { + if a == nil { + return nil + } + return a.CPU +} + // GetCNBVersioning returns the CNBVersioning field. func (a *AppBuildConfig) GetCNBVersioning() *AppBuildConfigCNBVersioning { if a == nil { @@ -710,6 +757,14 @@ func (a *AppDomainValidation) GetTXTValue() string { return a.TXTValue } +// GetType returns the Type field. +func (a *AppEgressSpec) GetType() AppEgressSpecType { + if a == nil { + return "" + } + return a.Type +} + // GetAlerts returns the Alerts field. func (a *AppFunctionsSpec) GetAlerts() []*AppAlertSpec { if a == nil { @@ -1438,6 +1493,14 @@ func (a *AppServiceSpec) GetAlerts() []*AppAlertSpec { return a.Alerts } +// GetAutoscaling returns the Autoscaling field. +func (a *AppServiceSpec) GetAutoscaling() *AppAutoscalingSpec { + if a == nil { + return nil + } + return a.Autoscaling +} + // GetBuildCommand returns the BuildCommand field. func (a *AppServiceSpec) GetBuildCommand() string { if a == nil { @@ -1678,6 +1741,14 @@ func (a *AppSpec) GetDomains() []*AppDomainSpec { return a.Domains } +// GetEgress returns the Egress field. +func (a *AppSpec) GetEgress() *AppEgressSpec { + if a == nil { + return nil + } + return a.Egress +} + // GetEnvs returns the Envs field. func (a *AppSpec) GetEnvs() []*AppVariableDefinition { if a == nil { @@ -1974,6 +2045,14 @@ func (a *AppWorkerSpec) GetAlerts() []*AppAlertSpec { return a.Alerts } +// GetAutoscaling returns the Autoscaling field. +func (a *AppWorkerSpec) GetAutoscaling() *AppAutoscalingSpec { + if a == nil { + return nil + } + return a.Autoscaling +} + // GetBuildCommand returns the BuildCommand field. func (a *AppWorkerSpec) GetBuildCommand() string { if a == nil { @@ -2294,6 +2373,14 @@ func (d *Deployment) GetWorkers() []*DeploymentWorker { return d.Workers } +// GetAutoscaler returns the Autoscaler field. +func (d *DeploymentCauseDetails) GetAutoscaler() *DeploymentCauseDetailsAutoscalerAction { + if d == nil { + return nil + } + return d.Autoscaler +} + // GetDigitalOceanUserAction returns the DigitalOceanUserAction field. func (d *DeploymentCauseDetails) GetDigitalOceanUserAction() *DeploymentCauseDetailsDigitalOceanUserAction { if d == nil { @@ -2334,6 +2421,14 @@ func (d *DeploymentCauseDetails) GetType() DeploymentCauseDetailsType { return d.Type } +// GetAutoscaled returns the Autoscaled field. +func (d *DeploymentCauseDetailsAutoscalerAction) GetAutoscaled() bool { + if d == nil { + return false + } + return d.Autoscaled +} + // GetEmail returns the Email field. func (d *DeploymentCauseDetailsDigitalOceanUser) GetEmail() string { if d == nil { @@ -3094,6 +3189,14 @@ func (i *ImageSourceSpec) GetDeployOnPush() *ImageSourceSpecDeployOnPush { return i.DeployOnPush } +// GetDigest returns the Digest field. +func (i *ImageSourceSpec) GetDigest() string { + if i == nil { + return "" + } + return i.Digest +} + // GetRegistry returns the Registry field. func (i *ImageSourceSpec) GetRegistry() string { if i == nil { @@ -3102,6 +3205,14 @@ func (i *ImageSourceSpec) GetRegistry() string { return i.Registry } +// GetRegistryCredentials returns the RegistryCredentials field. +func (i *ImageSourceSpec) GetRegistryCredentials() string { + if i == nil { + return "" + } + return i.RegistryCredentials +} + // GetRegistryType returns the RegistryType field. func (i *ImageSourceSpec) GetRegistryType() ImageSourceSpecRegistryType { if i == nil { diff --git a/vendor/github.com/digitalocean/godo/databases.go b/vendor/github.com/digitalocean/godo/databases.go index a0240735e..c0a4510a7 100644 --- a/vendor/github.com/digitalocean/godo/databases.go +++ b/vendor/github.com/digitalocean/godo/databases.go @@ -32,6 +32,8 @@ const ( databaseOptionsPath = databaseBasePath + "/options" databaseUpgradeMajorVersionPath = databaseBasePath + "/%s/upgrade" databasePromoteReplicaToPrimaryPath = databaseReplicaPath + "/promote" + databaseTopicPath = databaseBasePath + "/%s/topics/%s" + databaseTopicsPath = databaseBasePath + "/%s/topics" ) // SQL Mode constants allow for MySQL-specific SQL flavor configuration. @@ -116,6 +118,7 @@ type DatabasesService interface { GetUser(context.Context, string, string) (*DatabaseUser, *Response, error) ListUsers(context.Context, string, *ListOptions) ([]DatabaseUser, *Response, error) CreateUser(context.Context, string, *DatabaseCreateUserRequest) (*DatabaseUser, *Response, error) + UpdateUser(context.Context, string, string, *DatabaseUpdateUserRequest) (*DatabaseUser, *Response, error) DeleteUser(context.Context, string, string) (*Response, error) ResetUserAuth(context.Context, string, string, *DatabaseResetUserAuthRequest) (*DatabaseUser, *Response, error) ListDBs(context.Context, string, *ListOptions) ([]DatabaseDB, *Response, error) @@ -146,6 +149,11 @@ type DatabasesService interface { UpdateMySQLConfig(context.Context, string, *MySQLConfig) (*Response, error) ListOptions(todo context.Context) (*DatabaseOptions, *Response, error) UpgradeMajorVersion(context.Context, string, *UpgradeVersionRequest) (*Response, error) + ListTopics(context.Context, string, *ListOptions) ([]DatabaseTopic, *Response, error) + CreateTopic(context.Context, string, *DatabaseCreateTopicRequest) (*DatabaseTopic, *Response, error) + GetTopic(context.Context, string, string) (*DatabaseTopic, *Response, error) + DeleteTopic(context.Context, string, string) (*Response, error) + UpdateTopic(context.Context, string, string, *DatabaseUpdateTopicRequest) (*Response, error) } // DatabasesServiceOp handles communication with the Databases related methods @@ -179,6 +187,7 @@ type Database struct { PrivateNetworkUUID string `json:"private_network_uuid,omitempty"` Tags []string `json:"tags,omitempty"` ProjectID string `json:"project_id,omitempty"` + StorageSizeMib uint64 `json:"storage_size_mib,omitempty"` } // DatabaseCA represents a database ca. @@ -188,13 +197,15 @@ type DatabaseCA struct { // DatabaseConnection represents a database connection type DatabaseConnection struct { - URI string `json:"uri,omitempty"` - Database string `json:"database,omitempty"` - Host string `json:"host,omitempty"` - Port int `json:"port,omitempty"` - User string `json:"user,omitempty"` - Password string `json:"password,omitempty"` - SSL bool `json:"ssl,omitempty"` + Protocol string `json:"protocol"` + URI string `json:"uri,omitempty"` + Database string `json:"database,omitempty"` + Host string `json:"host,omitempty"` + Port int `json:"port,omitempty"` + User string `json:"user,omitempty"` + Password string `json:"password,omitempty"` + SSL bool `json:"ssl,omitempty"` + ApplicationPorts map[string]uint32 `json:"application_ports,omitempty"` } // DatabaseUser represents a user in the database @@ -202,7 +213,22 @@ type DatabaseUser struct { Name string `json:"name,omitempty"` Role string `json:"role,omitempty"` Password string `json:"password,omitempty"` + AccessCert string `json:"access_cert,omitempty"` + AccessKey string `json:"access_key,omitempty"` MySQLSettings *DatabaseMySQLUserSettings `json:"mysql_settings,omitempty"` + Settings *DatabaseUserSettings `json:"settings,omitempty"` +} + +// KafkaACL contains Kafka specific user access control information +type KafkaACL struct { + ID string `json:"id,omitempty"` + Permission string `json:"permission,omitempty"` + Topic string `json:"topic,omitempty"` +} + +// DatabaseUserSettings contains Kafka-specific user settings +type DatabaseUserSettings struct { + ACL []*KafkaACL `json:"acl,omitempty"` } // DatabaseMySQLUserSettings contains MySQL-specific user settings @@ -243,12 +269,14 @@ type DatabaseCreateRequest struct { Tags []string `json:"tags,omitempty"` BackupRestore *DatabaseBackupRestore `json:"backup_restore,omitempty"` ProjectID string `json:"project_id"` + StorageSizeMib uint64 `json:"storage_size_mib,omitempty"` } // DatabaseResizeRequest can be used to initiate a database resize operation. type DatabaseResizeRequest struct { - SizeSlug string `json:"size,omitempty"` - NumNodes int `json:"num_nodes,omitempty"` + SizeSlug string `json:"size,omitempty"` + NumNodes int `json:"num_nodes,omitempty"` + StorageSizeMib uint64 `json:"storage_size_mib,omitempty"` } // DatabaseMigrateRequest can be used to initiate a database migrate operation. @@ -271,6 +299,72 @@ type DatabaseDB struct { Name string `json:"name"` } +// DatabaseTopic represents a Kafka topic +type DatabaseTopic struct { + Name string `json:"name"` + Partitions []*TopicPartition `json:"partitions,omitempty"` + ReplicationFactor *uint32 `json:"replication_factor,omitempty"` + State string `json:"state,omitempty"` + Config *TopicConfig `json:"config,omitempty"` +} + +// TopicPartition represents the state of a Kafka topic partition +type TopicPartition struct { + EarliestOffset uint64 `json:"earliest_offset,omitempty"` + InSyncReplicas uint32 `json:"in_sync_replicas,omitempty"` + Id uint32 `json:"id,omitempty"` + Size uint64 `json:"size,omitempty"` + ConsumerGroups []*TopicConsumerGroup `json:"consumer_groups,omitempty"` +} + +// TopicConsumerGroup represents a consumer group for a particular Kafka topic +type TopicConsumerGroup struct { + Name string `json:"name,omitempty"` + Offset uint64 `json:"offset,omitempty"` +} + +// TopicConfig represents all configurable options for a Kafka topic +type TopicConfig struct { + CleanupPolicy string `json:"cleanup_policy,omitempty"` + CompressionType string `json:"compression_type,omitempty"` + DeleteRetentionMS *uint64 `json:"delete_retention_ms,omitempty"` + FileDeleteDelayMS *uint64 `json:"file_delete_delay_ms,omitempty"` + FlushMessages *uint64 `json:"flush_messages,omitempty"` + FlushMS *uint64 `json:"flush_ms,omitempty"` + IndexIntervalBytes *uint64 `json:"index_interval_bytes,omitempty"` + MaxCompactionLagMS *uint64 `json:"max_compaction_lag_ms,omitempty"` + MaxMessageBytes *uint64 `json:"max_message_bytes,omitempty"` + MessageDownConversionEnable *bool `json:"message_down_conversion_enable,omitempty"` + MessageFormatVersion string `json:"message_format_version,omitempty"` + MessageTimestampDifferenceMaxMS *uint64 `json:"message_timestamp_difference_max_ms,omitempty"` + MessageTimestampType string `json:"message_timestamp_type,omitempty"` + MinCleanableDirtyRatio *float32 `json:"min_cleanable_dirty_ratio,omitempty"` + MinCompactionLagMS *uint64 `json:"min_compaction_lag_ms,omitempty"` + MinInsyncReplicas *uint32 `json:"min_insync_replicas,omitempty"` + Preallocate *bool `json:"preallocate,omitempty"` + RetentionBytes *int64 `json:"retention_bytes,omitempty"` + RetentionMS *int64 `json:"retention_ms,omitempty"` + SegmentBytes *uint64 `json:"segment_bytes,omitempty"` + SegmentIndexBytes *uint64 `json:"segment_index_bytes,omitempty"` + SegmentJitterMS *uint64 `json:"segment_jitter_ms,omitempty"` + SegmentMS *uint64 `json:"segment_ms,omitempty"` +} + +// DatabaseCreateTopicRequest is used to create a new topic within a kafka cluster +type DatabaseCreateTopicRequest struct { + Name string `json:"name"` + PartitionCount *uint32 `json:"partition_count,omitempty"` + ReplicationFactor *uint32 `json:"replication_factor,omitempty"` + Config *TopicConfig `json:"config,omitempty"` +} + +// DatabaseUpdateTopicRequest ... +type DatabaseUpdateTopicRequest struct { + PartitionCount *uint32 `json:"partition_count,omitempty"` + ReplicationFactor *uint32 `json:"replication_factor,omitempty"` + Config *TopicConfig `json:"config,omitempty"` +} + // DatabaseReplica represents a read-only replica of a particular database type DatabaseReplica struct { ID string `json:"id"` @@ -282,6 +376,7 @@ type DatabaseReplica struct { CreatedAt time.Time `json:"created_at"` PrivateNetworkUUID string `json:"private_network_uuid,omitempty"` Tags []string `json:"tags,omitempty"` + StorageSizeMib uint64 `json:"storage_size_mib,omitempty"` } // DatabasePool represents a database connection pool @@ -316,11 +411,18 @@ type DatabaseUpdatePoolRequest struct { type DatabaseCreateUserRequest struct { Name string `json:"name"` MySQLSettings *DatabaseMySQLUserSettings `json:"mysql_settings,omitempty"` + Settings *DatabaseUserSettings `json:"settings,omitempty"` +} + +// DatabaseUpdateUserRequest is used to update an existing database user +type DatabaseUpdateUserRequest struct { + Settings *DatabaseUserSettings `json:"settings,omitempty"` } // DatabaseResetUserAuthRequest is used to reset a users DB auth type DatabaseResetUserAuthRequest struct { MySQLSettings *DatabaseMySQLUserSettings `json:"mysql_settings,omitempty"` + Settings *DatabaseUserSettings `json:"settings,omitempty"` } // DatabaseCreateDBRequest is used to create a new engine-specific database within the cluster @@ -335,6 +437,7 @@ type DatabaseCreateReplicaRequest struct { Size string `json:"size"` PrivateNetworkUUID string `json:"private_network_uuid"` Tags []string `json:"tags,omitempty"` + StorageSizeMib uint64 `json:"storage_size_mib,omitempty"` } // DatabaseUpdateFirewallRulesRequest is used to set the firewall rules for a database @@ -551,12 +654,21 @@ type databaseOptionsRoot struct { Options *DatabaseOptions `json:"options"` } +type databaseTopicRoot struct { + Topic *DatabaseTopic `json:"topic"` +} + +type databaseTopicsRoot struct { + Topics []DatabaseTopic `json:"topics"` +} + // DatabaseOptions represents the available database engines type DatabaseOptions struct { MongoDBOptions DatabaseEngineOptions `json:"mongodb"` MySQLOptions DatabaseEngineOptions `json:"mysql"` PostgresSQLOptions DatabaseEngineOptions `json:"pg"` RedisOptions DatabaseEngineOptions `json:"redis"` + KafkaOptions DatabaseEngineOptions `json:"kafka"` } // DatabaseEngineOptions represents the configuration options that are available for a given database engine @@ -766,6 +878,21 @@ func (svc *DatabasesServiceOp) CreateUser(ctx context.Context, databaseID string return root.User, resp, nil } +// UpdateUser will update an existing database user +func (svc *DatabasesServiceOp) UpdateUser(ctx context.Context, databaseID, userID string, updateUser *DatabaseUpdateUserRequest) (*DatabaseUser, *Response, error) { + path := fmt.Sprintf(databaseUserPath, databaseID, userID) + req, err := svc.client.NewRequest(ctx, http.MethodPut, path, updateUser) + if err != nil { + return nil, nil, err + } + root := new(databaseUserRoot) + resp, err := svc.client.Do(ctx, req, root) + if err != nil { + return nil, resp, err + } + return root.User, resp, nil +} + // ResetUserAuth will reset user authentication func (svc *DatabasesServiceOp) ResetUserAuth(ctx context.Context, databaseID, userID string, resetAuth *DatabaseResetUserAuthRequest) (*DatabaseUser, *Response, error) { path := fmt.Sprintf(databaseResetUserAuthPath, databaseID, userID) @@ -1257,3 +1384,81 @@ func (svc *DatabasesServiceOp) UpgradeMajorVersion(ctx context.Context, database return resp, nil } + +// ListTopics returns all topics for a given kafka cluster +func (svc *DatabasesServiceOp) ListTopics(ctx context.Context, databaseID string, opts *ListOptions) ([]DatabaseTopic, *Response, error) { + path := fmt.Sprintf(databaseTopicsPath, databaseID) + path, err := addOptions(path, opts) + if err != nil { + return nil, nil, err + } + req, err := svc.client.NewRequest(ctx, http.MethodGet, path, nil) + if err != nil { + return nil, nil, err + } + root := new(databaseTopicsRoot) + resp, err := svc.client.Do(ctx, req, root) + if err != nil { + return nil, resp, err + } + return root.Topics, resp, nil +} + +// GetTopic returns a single kafka topic by name +func (svc *DatabasesServiceOp) GetTopic(ctx context.Context, databaseID, name string) (*DatabaseTopic, *Response, error) { + path := fmt.Sprintf(databaseTopicPath, databaseID, name) + req, err := svc.client.NewRequest(ctx, http.MethodGet, path, nil) + if err != nil { + return nil, nil, err + } + root := new(databaseTopicRoot) + resp, err := svc.client.Do(ctx, req, root) + if err != nil { + return nil, resp, err + } + return root.Topic, resp, nil +} + +// CreateTopic will create a new kafka topic +func (svc *DatabasesServiceOp) CreateTopic(ctx context.Context, databaseID string, createTopic *DatabaseCreateTopicRequest) (*DatabaseTopic, *Response, error) { + path := fmt.Sprintf(databaseTopicsPath, databaseID) + req, err := svc.client.NewRequest(ctx, http.MethodPost, path, createTopic) + if err != nil { + return nil, nil, err + } + root := new(databaseTopicRoot) + resp, err := svc.client.Do(ctx, req, root) + if err != nil { + return nil, resp, err + } + return root.Topic, resp, nil +} + +// UpdateTopic updates a single kafka topic +func (svc *DatabasesServiceOp) UpdateTopic(ctx context.Context, databaseID string, name string, updateTopic *DatabaseUpdateTopicRequest) (*Response, error) { + path := fmt.Sprintf(databaseTopicPath, databaseID, name) + req, err := svc.client.NewRequest(ctx, http.MethodPut, path, updateTopic) + if err != nil { + return nil, err + } + root := new(databaseTopicRoot) + resp, err := svc.client.Do(ctx, req, root) + if err != nil { + return resp, err + } + return resp, nil +} + +// DeleteTopic will delete an existing kafka topic +func (svc *DatabasesServiceOp) DeleteTopic(ctx context.Context, databaseID, name string) (*Response, error) { + path := fmt.Sprintf(databaseTopicPath, databaseID, name) + req, err := svc.client.NewRequest(ctx, http.MethodDelete, path, nil) + if err != nil { + return nil, err + } + resp, err := svc.client.Do(ctx, req, nil) + if err != nil { + return resp, err + } + return resp, nil +} diff --git a/vendor/github.com/digitalocean/godo/godo.go b/vendor/github.com/digitalocean/godo/godo.go index 14fac268c..95d203232 100644 --- a/vendor/github.com/digitalocean/godo/godo.go +++ b/vendor/github.com/digitalocean/godo/godo.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "reflect" @@ -16,25 +15,32 @@ import ( "time" "github.com/google/go-querystring/query" + "github.com/hashicorp/go-retryablehttp" "golang.org/x/oauth2" "golang.org/x/time/rate" ) const ( - libraryVersion = "1.98.0" + libraryVersion = "1.108.0" defaultBaseURL = "https://api.digitalocean.com/" userAgent = "godo/" + libraryVersion mediaType = "application/json" - headerRateLimit = "RateLimit-Limit" - headerRateRemaining = "RateLimit-Remaining" - headerRateReset = "RateLimit-Reset" + headerRateLimit = "RateLimit-Limit" + headerRateRemaining = "RateLimit-Remaining" + headerRateReset = "RateLimit-Reset" + headerRequestID = "x-request-id" + internalHeaderRetryAttempts = "X-Godo-Retry-Attempts" + + defaultRetryMax = 4 + defaultRetryWaitMax = 30 + defaultRetryWaitMin = 1 ) // Client manages communication with DigitalOcean V2 API. type Client struct { // HTTP client used to communicate with the DO API. - client *http.Client + HTTPClient *http.Client // Base URL for API requests. BaseURL *url.URL @@ -81,7 +87,6 @@ type Client struct { Storage StorageService StorageActions StorageActionsService Tags TagsService - Tokens TokensService UptimeChecks UptimeChecksService VPCs VPCsService @@ -93,6 +98,30 @@ type Client struct { // Optional rate limiter to ensure QoS. rateLimiter *rate.Limiter + + // Optional retry values. Setting the RetryConfig.RetryMax value enables automatically retrying requests + // that fail with 429 or 500-level response codes using the go-retryablehttp client + RetryConfig RetryConfig +} + +// RetryConfig sets the values used for enabling retries and backoffs for +// requests that fail with 429 or 500-level response codes using the go-retryablehttp client. +// RetryConfig.RetryMax must be configured to enable this behavior. RetryConfig.RetryWaitMin and +// RetryConfig.RetryWaitMax are optional, with the default values being 1.0 and 30.0, respectively. +// +// You can use +// +// godo.PtrTo(1.0) +// +// to explicitly set the RetryWaitMin and RetryWaitMax values. +// +// Note: Opting to use the go-retryablehttp client will overwrite any custom HTTP client passed into New(). +// Only the oauth2.TokenSource and Timeout will be maintained. +type RetryConfig struct { + RetryMax int + RetryWaitMin *float64 // Minimum time to wait + RetryWaitMax *float64 // Maximum time to wait + Logger interface{} // Customer logger instance. Must implement either go-retryablehttp.Logger or go-retryablehttp.LeveledLogger } // RequestCompletionCallback defines the type of the request callback function @@ -154,6 +183,9 @@ type ErrorResponse struct { // RequestID returned from the API, useful to contact support. RequestID string `json:"request_id"` + + // Attempts is the number of times the request was attempted when retries are enabled. + Attempts int } // Rate contains the rate limit for the current client. @@ -201,7 +233,20 @@ func NewFromToken(token string) *Client { cleanToken := strings.Trim(strings.TrimSpace(token), "'") ctx := context.Background() ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: cleanToken}) - return NewClient(oauth2.NewClient(ctx, ts)) + + oauthClient := oauth2.NewClient(ctx, ts) + client, err := New(oauthClient, WithRetryAndBackoffs( + RetryConfig{ + RetryMax: defaultRetryMax, + RetryWaitMin: PtrTo(float64(defaultRetryWaitMin)), + RetryWaitMax: PtrTo(float64(defaultRetryWaitMax)), + }, + )) + if err != nil { + panic(err) + } + + return client } // NewClient returns a new DigitalOcean API client, using the given @@ -217,7 +262,7 @@ func NewClient(httpClient *http.Client) *Client { baseURL, _ := url.Parse(defaultBaseURL) - c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent} + c := &Client{HTTPClient: httpClient, BaseURL: baseURL, UserAgent: userAgent} c.Account = &AccountServiceOp{client: c} c.Actions = &ActionsServiceOp{client: c} @@ -252,7 +297,6 @@ func NewClient(httpClient *http.Client) *Client { c.Storage = &StorageServiceOp{client: c} c.StorageActions = &StorageActionsServiceOp{client: c} c.Tags = &TagsServiceOp{client: c} - c.Tokens = &TokensServiceOp{client: c} c.UptimeChecks = &UptimeChecksServiceOp{client: c} c.VPCs = &VPCsServiceOp{client: c} @@ -273,6 +317,59 @@ func New(httpClient *http.Client, opts ...ClientOpt) (*Client, error) { } } + // if retryMax is set it will use the retryablehttp client. + if c.RetryConfig.RetryMax > 0 { + retryableClient := retryablehttp.NewClient() + retryableClient.RetryMax = c.RetryConfig.RetryMax + + if c.RetryConfig.RetryWaitMin != nil { + retryableClient.RetryWaitMin = time.Duration(*c.RetryConfig.RetryWaitMin * float64(time.Second)) + } + if c.RetryConfig.RetryWaitMax != nil { + retryableClient.RetryWaitMax = time.Duration(*c.RetryConfig.RetryWaitMax * float64(time.Second)) + } + + // By default this is nil and does not log. + retryableClient.Logger = c.RetryConfig.Logger + + // if timeout is set, it is maintained before overwriting client with StandardClient() + retryableClient.HTTPClient.Timeout = c.HTTPClient.Timeout + + // This custom ErrorHandler is required to provide errors that are consistent + // with a *godo.ErrorResponse and a non-nil *godo.Response while providing + // insight into retries using an internal header. + retryableClient.ErrorHandler = func(resp *http.Response, err error, numTries int) (*http.Response, error) { + if resp != nil { + resp.Header.Add(internalHeaderRetryAttempts, strconv.Itoa(numTries)) + + return resp, err + } + + return resp, err + } + + retryableClient.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) { + // In addition to the default retry policy, we also retry HTTP/2 INTERNAL_ERROR errors. + // See: https://github.com/golang/go/issues/51323 + if err != nil && strings.Contains(err.Error(), "INTERNAL_ERROR") && strings.Contains(reflect.TypeOf(err).String(), "http2") { + return true, nil + } + + return retryablehttp.DefaultRetryPolicy(ctx, resp, err) + } + + var source *oauth2.Transport + if _, ok := c.HTTPClient.Transport.(*oauth2.Transport); ok { + source = c.HTTPClient.Transport.(*oauth2.Transport) + } + c.HTTPClient = retryableClient.StandardClient() + c.HTTPClient.Transport = &oauth2.Transport{ + Base: c.HTTPClient.Transport, + Source: source.Source, + } + + } + return c, nil } @@ -317,6 +414,18 @@ func SetStaticRateLimit(rps float64) ClientOpt { } } +// WithRetryAndBackoffs sets retry values. Setting the RetryConfig.RetryMax value enables automatically retrying requests +// that fail with 429 or 500-level response codes using the go-retryablehttp client +func WithRetryAndBackoffs(retryConfig RetryConfig) ClientOpt { + return func(c *Client) error { + c.RetryConfig.RetryMax = retryConfig.RetryMax + c.RetryConfig.RetryWaitMax = retryConfig.RetryWaitMax + c.RetryConfig.RetryWaitMin = retryConfig.RetryWaitMin + c.RetryConfig.Logger = retryConfig.Logger + return nil + } +} + // NewRequest creates an API request. A relative URL can be provided in urlStr, which will be resolved to the // BaseURL of the Client. Relative URLS should always be specified without a preceding slash. If specified, the // value pointed to by body is JSON encoded and included in as the request body. @@ -407,7 +516,7 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Res } } - resp, err := DoRequestWithClient(ctx, c.client, req) + resp, err := DoRequestWithClient(ctx, c.HTTPClient, req) if err != nil { return nil, err } @@ -424,7 +533,7 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Res // won't reuse it anyway. const maxBodySlurpSize = 2 << 10 if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize { - io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize) + io.CopyN(io.Discard, resp.Body, maxBodySlurpSize) } if rerr := resp.Body.Close(); err == nil { @@ -474,12 +583,17 @@ func DoRequestWithClient( } func (r *ErrorResponse) Error() string { + var attempted string + if r.Attempts > 0 { + attempted = fmt.Sprintf("; giving up after %d attempt(s)", r.Attempts) + } + if r.RequestID != "" { - return fmt.Sprintf("%v %v: %d (request %q) %v", - r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.RequestID, r.Message) + return fmt.Sprintf("%v %v: %d (request %q) %v%s", + r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.RequestID, r.Message, attempted) } - return fmt.Sprintf("%v %v: %d %v", - r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.Message) + return fmt.Sprintf("%v %v: %d %v%s", + r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.Message, attempted) } // CheckResponse checks the API response for errors, and returns them if present. A response is considered an @@ -492,7 +606,7 @@ func CheckResponse(r *http.Response) error { } errorResponse := &ErrorResponse{Response: r} - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err == nil && len(data) > 0 { err := json.Unmarshal(data, errorResponse) if err != nil { @@ -501,7 +615,12 @@ func CheckResponse(r *http.Response) error { } if errorResponse.RequestID == "" { - errorResponse.RequestID = r.Header.Get("x-request-id") + errorResponse.RequestID = r.Header.Get(headerRequestID) + } + + attempts, strconvErr := strconv.Atoi(r.Header.Get(internalHeaderRetryAttempts)) + if strconvErr == nil { + errorResponse.Attempts = attempts } return errorResponse diff --git a/vendor/github.com/digitalocean/godo/load_balancers.go b/vendor/github.com/digitalocean/godo/load_balancers.go index 6a9a70efe..7e1cfc164 100644 --- a/vendor/github.com/digitalocean/godo/load_balancers.go +++ b/vendor/github.com/digitalocean/godo/load_balancers.go @@ -6,10 +6,17 @@ import ( "net/http" ) -const loadBalancersBasePath = "/v2/load_balancers" -const forwardingRulesPath = "forwarding_rules" +const ( + dropletsPath = "droplets" + forwardingRulesPath = "forwarding_rules" + loadBalancersBasePath = "/v2/load_balancers" +) -const dropletsPath = "droplets" +// Load Balancer types. +const ( + LoadBalancerTypeGlobal = "GLOBAL" + LoadBalancerTypeRegional = "REGIONAL" +) // LoadBalancersService is an interface for managing load balancers with the DigitalOcean API. // See: https://docs.digitalocean.com/reference/api/api-reference/#tag/Load-Balancers @@ -35,6 +42,7 @@ type LoadBalancer struct { SizeSlug string `json:"size,omitempty"` // SizeUnit is mutually exclusive with SizeSlug. Only one should be specified SizeUnit uint32 `json:"size_unit,omitempty"` + Type string `json:"type,omitempty"` Algorithm string `json:"algorithm,omitempty"` Status string `json:"status,omitempty"` Created string `json:"created_at,omitempty"` @@ -74,6 +82,7 @@ func (l LoadBalancer) AsRequest() *LoadBalancerRequest { Algorithm: l.Algorithm, SizeSlug: l.SizeSlug, SizeUnit: l.SizeUnit, + Type: l.Type, ForwardingRules: append([]ForwardingRule(nil), l.ForwardingRules...), DropletIDs: append([]int(nil), l.DropletIDs...), Tag: l.Tag, @@ -190,6 +199,7 @@ type LoadBalancerRequest struct { SizeSlug string `json:"size,omitempty"` // SizeUnit is mutually exclusive with SizeSlug. Only one should be specified SizeUnit uint32 `json:"size_unit,omitempty"` + Type string `json:"type,omitempty"` ForwardingRules []ForwardingRule `json:"forwarding_rules,omitempty"` HealthCheck *HealthCheck `json:"health_check,omitempty"` StickySessions *StickySessions `json:"sticky_sessions,omitempty"` diff --git a/vendor/github.com/digitalocean/godo/registry.go b/vendor/github.com/digitalocean/godo/registry.go index 2fe9d2bd9..b0c243281 100644 --- a/vendor/github.com/digitalocean/godo/registry.go +++ b/vendor/github.com/digitalocean/godo/registry.go @@ -37,6 +37,7 @@ type RegistryService interface { GetOptions(context.Context) (*RegistryOptions, *Response, error) GetSubscription(context.Context) (*RegistrySubscription, *Response, error) UpdateSubscription(context.Context, *RegistrySubscriptionUpdateRequest) (*RegistrySubscription, *Response, error) + ValidateName(context.Context, *RegistryValidateNameRequest) (*Response, error) } var _ RegistryService = &RegistryServiceOp{} @@ -233,6 +234,12 @@ type RegistrySubscriptionUpdateRequest struct { TierSlug string `json:"tier_slug"` } +// RegistryValidateNameRequest represents a request to validate that a +// container registry name is available for use. +type RegistryValidateNameRequest struct { + Name string `json:"name"` +} + // Get retrieves the details of a Registry. func (svc *RegistryServiceOp) Get(ctx context.Context) (*Registry, *Response, error) { req, err := svc.client.NewRequest(ctx, http.MethodGet, registryPath, nil) @@ -589,3 +596,17 @@ func (svc *RegistryServiceOp) UpdateSubscription(ctx context.Context, request *R } return root.Subscription, resp, nil } + +// ValidateName validates that a container registry name is available for use. +func (svc *RegistryServiceOp) ValidateName(ctx context.Context, request *RegistryValidateNameRequest) (*Response, error) { + path := fmt.Sprintf("%s/validate-name", registryPath) + req, err := svc.client.NewRequest(ctx, http.MethodPost, path, request) + if err != nil { + return nil, err + } + resp, err := svc.client.Do(ctx, req, nil) + if err != nil { + return resp, err + } + return resp, nil +} diff --git a/vendor/github.com/digitalocean/godo/tokens.go b/vendor/github.com/digitalocean/godo/tokens.go deleted file mode 100644 index 13aa418df..000000000 --- a/vendor/github.com/digitalocean/godo/tokens.go +++ /dev/null @@ -1,228 +0,0 @@ -package godo - -import ( - "context" - "fmt" - "net/http" - "time" -) - -const ( - accessTokensBasePath = "v2/tokens" - tokenScopesBasePath = accessTokensBasePath + "/scopes" -) - -// TokensService is an interface for managing DigitalOcean API access tokens. -// It is not currently generally available. Follow the release notes for -// updates: https://docs.digitalocean.com/release-notes/api/ -type TokensService interface { - List(context.Context, *ListOptions) ([]Token, *Response, error) - Get(context.Context, int) (*Token, *Response, error) - Create(context.Context, *TokenCreateRequest) (*Token, *Response, error) - Update(context.Context, int, *TokenUpdateRequest) (*Token, *Response, error) - Revoke(context.Context, int) (*Response, error) - ListScopes(context.Context, *ListOptions) ([]TokenScope, *Response, error) - ListScopesByNamespace(context.Context, string, *ListOptions) ([]TokenScope, *Response, error) -} - -// TokensServiceOp handles communication with the tokens related methods of the -// DigitalOcean API. -type TokensServiceOp struct { - client *Client -} - -var _ TokensService = &TokensServiceOp{} - -// Token represents a DigitalOcean API token. -type Token struct { - ID int `json:"id"` - Name string `json:"name"` - Scopes []string `json:"scopes"` - ExpirySeconds *int `json:"expiry_seconds"` - CreatedAt time.Time `json:"created_at"` - LastUsedAt string `json:"last_used_at"` - - // AccessToken contains the actual Oauth token string. It is only included - // in the create response. - AccessToken string `json:"access_token,omitempty"` -} - -// tokenRoot represents a response from the DigitalOcean API -type tokenRoot struct { - Token *Token `json:"token"` -} - -type tokensRoot struct { - Tokens []Token `json:"tokens"` - Links *Links `json:"links"` - Meta *Meta `json:"meta"` -} - -// TokenCreateRequest represents a request to create a token. -type TokenCreateRequest struct { - Name string `json:"name"` - Scopes []string `json:"scopes"` - ExpirySeconds *int `json:"expiry_seconds,omitempty"` -} - -// TokenUpdateRequest represents a request to update a token. -type TokenUpdateRequest struct { - Name string `json:"name,omitempty"` - Scopes []string `json:"scopes,omitempty"` -} - -// TokenScope is a representation of a scope for the public API. -type TokenScope struct { - Name string `json:"name"` -} - -type tokenScopesRoot struct { - TokenScopes []TokenScope `json:"scopes"` - Links *Links `json:"links"` - Meta *Meta `json:"meta"` -} - -type tokenScopeNamespaceParam struct { - Namespace string `url:"namespace,omitempty"` -} - -// List all DigitalOcean API access tokens. -func (c TokensServiceOp) List(ctx context.Context, opt *ListOptions) ([]Token, *Response, error) { - path, err := addOptions(accessTokensBasePath, opt) - if err != nil { - return nil, nil, err - } - - req, err := c.client.NewRequest(ctx, http.MethodGet, path, nil) - if err != nil { - return nil, nil, err - } - - root := new(tokensRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - if l := root.Links; l != nil { - resp.Links = l - } - if m := root.Meta; m != nil { - resp.Meta = m - } - - return root.Tokens, resp, err -} - -// Get a specific DigitalOcean API access token. -func (c TokensServiceOp) Get(ctx context.Context, tokenID int) (*Token, *Response, error) { - path := fmt.Sprintf("%s/%d", accessTokensBasePath, tokenID) - req, err := c.client.NewRequest(ctx, http.MethodGet, path, nil) - if err != nil { - return nil, nil, err - } - - root := new(tokenRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - - return root.Token, resp, err -} - -// Create a new DigitalOcean API access token. -func (c TokensServiceOp) Create(ctx context.Context, createRequest *TokenCreateRequest) (*Token, *Response, error) { - req, err := c.client.NewRequest(ctx, http.MethodPost, accessTokensBasePath, createRequest) - if err != nil { - return nil, nil, err - } - - root := new(tokenRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - - return root.Token, resp, err -} - -// Update the name or scopes of a specific DigitalOcean API access token. -func (c TokensServiceOp) Update(ctx context.Context, tokenID int, updateRequest *TokenUpdateRequest) (*Token, *Response, error) { - path := fmt.Sprintf("%s/%d", accessTokensBasePath, tokenID) - req, err := c.client.NewRequest(ctx, http.MethodPatch, path, updateRequest) - if err != nil { - return nil, nil, err - } - - root := new(tokenRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - - return root.Token, resp, err -} - -// Revoke a specific DigitalOcean API access token. -func (c TokensServiceOp) Revoke(ctx context.Context, tokenID int) (*Response, error) { - path := fmt.Sprintf("%s/%d", accessTokensBasePath, tokenID) - req, err := c.client.NewRequest(ctx, http.MethodDelete, path, nil) - if err != nil { - return nil, err - } - - resp, err := c.client.Do(ctx, req, nil) - - return resp, err -} - -// ListScopes lists all available scopes that can be granted to a token. -func (c TokensServiceOp) ListScopes(ctx context.Context, opt *ListOptions) ([]TokenScope, *Response, error) { - path, err := addOptions(tokenScopesBasePath, opt) - if err != nil { - return nil, nil, err - } - - return listTokenScopes(ctx, c, path) -} - -// ListScopesByNamespace lists available scopes in a namespace that can be granted -// to a token (e.g. the namespace for the `droplet:read“ scope is `droplet`). -func (c TokensServiceOp) ListScopesByNamespace(ctx context.Context, namespace string, opt *ListOptions) ([]TokenScope, *Response, error) { - path, err := addOptions(tokenScopesBasePath, opt) - if err != nil { - return nil, nil, err - } - - namespaceOpt := tokenScopeNamespaceParam{ - Namespace: namespace, - } - - path, err = addOptions(path, namespaceOpt) - if err != nil { - return nil, nil, err - } - - return listTokenScopes(ctx, c, path) -} - -func listTokenScopes(ctx context.Context, c TokensServiceOp, path string) ([]TokenScope, *Response, error) { - req, err := c.client.NewRequest(ctx, http.MethodGet, path, nil) - if err != nil { - return nil, nil, err - } - - root := new(tokenScopesRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - if l := root.Links; l != nil { - resp.Links = l - } - if m := root.Meta; m != nil { - resp.Meta = m - } - - return root.TokenScopes, resp, err -} diff --git a/vendor/github.com/digitalocean/godo/uptime.go b/vendor/github.com/digitalocean/godo/uptime.go index 915d6c713..f312e0e88 100644 --- a/vendor/github.com/digitalocean/godo/uptime.go +++ b/vendor/github.com/digitalocean/godo/uptime.go @@ -7,7 +7,13 @@ import ( "path" ) -const uptimeChecksBasePath = "/v2/uptime/checks" +const ( + uptimeChecksBasePath = "/v2/uptime/checks" + // UptimeAlertGreaterThan is the comparison > + UptimeAlertGreaterThan UptimeAlertComp = "greater_than" + // UptimeAlertLessThan is the comparison < + UptimeAlertLessThan UptimeAlertComp = "less_than" +) // UptimeChecksService is an interface for creating and managing Uptime checks with the DigitalOcean API. // See: https://docs.digitalocean.com/reference/api/api-reference/#tag/Uptime @@ -42,13 +48,13 @@ type UptimeCheck struct { // UptimeAlert represents a DigitalOcean Uptime Alert configuration. type UptimeAlert struct { - ID string `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - Threshold int `json:"threshold"` - Comparison string `json:"comparison"` - Notifications *Notifications `json:"notifications"` - Period string `json:"period"` + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Threshold int `json:"threshold"` + Comparison UptimeAlertComp `json:"comparison"` + Notifications *Notifications `json:"notifications"` + Period string `json:"period"` } // Notifications represents a DigitalOcean Notifications configuration. @@ -97,24 +103,27 @@ type UpdateUptimeCheckRequest struct { // CreateUptimeUptimeAlertRequest represents the request to create a new Uptime Alert. type CreateUptimeAlertRequest struct { - Name string `json:"name"` - Type string `json:"type"` - Threshold int `json:"threshold"` - Comparison string `json:"comparison"` - Notifications *Notifications `json:"notifications"` - Period string `json:"period"` + Name string `json:"name"` + Type string `json:"type"` + Threshold int `json:"threshold"` + Comparison UptimeAlertComp `json:"comparison"` + Notifications *Notifications `json:"notifications"` + Period string `json:"period"` } -// UpdateUptimeAlertRequest represents the request to create a new alert. +// UpdateUptimeAlertRequest represents the request to update an alert. type UpdateUptimeAlertRequest struct { - Name string `json:"name"` - Type string `json:"type"` - Threshold int `json:"threshold"` - Comparison string `json:"comparison"` - Notifications *Notifications `json:"notifications"` - Period string `json:"period"` + Name string `json:"name"` + Type string `json:"type"` + Threshold int `json:"threshold"` + Comparison UptimeAlertComp `json:"comparison"` + Notifications *Notifications `json:"notifications"` + Period string `json:"period"` } +// UptimeAlertComp represents an uptime alert comparison operation +type UptimeAlertComp string + type uptimeChecksRoot struct { UptimeChecks []UptimeCheck `json:"checks"` Links *Links `json:"links"` diff --git a/vendor/github.com/distribution/reference/.gitattributes b/vendor/github.com/distribution/reference/.gitattributes new file mode 100644 index 000000000..d207b1802 --- /dev/null +++ b/vendor/github.com/distribution/reference/.gitattributes @@ -0,0 +1 @@ +*.go text eol=lf diff --git a/vendor/github.com/distribution/reference/.gitignore b/vendor/github.com/distribution/reference/.gitignore new file mode 100644 index 000000000..dc07e6b04 --- /dev/null +++ b/vendor/github.com/distribution/reference/.gitignore @@ -0,0 +1,2 @@ +# Cover profiles +*.out diff --git a/vendor/github.com/distribution/reference/.golangci.yml b/vendor/github.com/distribution/reference/.golangci.yml new file mode 100644 index 000000000..793f0bb7e --- /dev/null +++ b/vendor/github.com/distribution/reference/.golangci.yml @@ -0,0 +1,18 @@ +linters: + enable: + - bodyclose + - dupword # Checks for duplicate words in the source code + - gofmt + - goimports + - ineffassign + - misspell + - revive + - staticcheck + - unconvert + - unused + - vet + disable: + - errcheck + +run: + deadline: 2m diff --git a/vendor/github.com/distribution/reference/CODE-OF-CONDUCT.md b/vendor/github.com/distribution/reference/CODE-OF-CONDUCT.md new file mode 100644 index 000000000..48f6704c6 --- /dev/null +++ b/vendor/github.com/distribution/reference/CODE-OF-CONDUCT.md @@ -0,0 +1,5 @@ +# Code of Conduct + +We follow the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md). + +Please contact the [CNCF Code of Conduct Committee](mailto:conduct@cncf.io) in order to report violations of the Code of Conduct. diff --git a/vendor/github.com/distribution/reference/CONTRIBUTING.md b/vendor/github.com/distribution/reference/CONTRIBUTING.md new file mode 100644 index 000000000..ab2194665 --- /dev/null +++ b/vendor/github.com/distribution/reference/CONTRIBUTING.md @@ -0,0 +1,114 @@ +# Contributing to the reference library + +## Community help + +If you need help, please ask in the [#distribution](https://cloud-native.slack.com/archives/C01GVR8SY4R) channel on CNCF community slack. +[Click here for an invite to the CNCF community slack](https://slack.cncf.io/) + +## Reporting security issues + +The maintainers take security seriously. If you discover a security +issue, please bring it to their attention right away! + +Please **DO NOT** file a public issue, instead send your report privately to +[cncf-distribution-security@lists.cncf.io](mailto:cncf-distribution-security@lists.cncf.io). + +## Reporting an issue properly + +By following these simple rules you will get better and faster feedback on your issue. + + - search the bugtracker for an already reported issue + +### If you found an issue that describes your problem: + + - please read other user comments first, and confirm this is the same issue: a given error condition might be indicative of different problems - you may also find a workaround in the comments + - please refrain from adding "same thing here" or "+1" comments + - you don't need to comment on an issue to get notified of updates: just hit the "subscribe" button + - comment if you have some new, technical and relevant information to add to the case + - __DO NOT__ comment on closed issues or merged PRs. If you think you have a related problem, open up a new issue and reference the PR or issue. + +### If you have not found an existing issue that describes your problem: + + 1. create a new issue, with a succinct title that describes your issue: + - bad title: "It doesn't work with my docker" + - good title: "Private registry push fail: 400 error with E_INVALID_DIGEST" + 2. copy the output of (or similar for other container tools): + - `docker version` + - `docker info` + - `docker exec registry --version` + 3. copy the command line you used to launch your Registry + 4. restart your docker daemon in debug mode (add `-D` to the daemon launch arguments) + 5. reproduce your problem and get your docker daemon logs showing the error + 6. if relevant, copy your registry logs that show the error + 7. provide any relevant detail about your specific Registry configuration (e.g., storage backend used) + 8. indicate if you are using an enterprise proxy, Nginx, or anything else between you and your Registry + +## Contributing Code + +Contributions should be made via pull requests. Pull requests will be reviewed +by one or more maintainers or reviewers and merged when acceptable. + +You should follow the basic GitHub workflow: + + 1. Use your own [fork](https://help.github.com/en/articles/about-forks) + 2. Create your [change](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#successful-changes) + 3. Test your code + 4. [Commit](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#commit-messages) your work, always [sign your commits](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#commit-messages) + 5. Push your change to your fork and create a [Pull Request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork) + +Refer to [containerd's contribution guide](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#successful-changes) +for tips on creating a successful contribution. + +## Sign your work + +The sign-off is a simple line at the end of the explanation for the patch. Your +signature certifies that you wrote the patch or otherwise have the right to pass +it on as an open-source patch. The rules are pretty simple: if you can certify +the below (from [developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +Then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +Use your real name (sorry, no pseudonyms or anonymous contributions.) + +If you set your `user.name` and `user.email` git configs, you can sign your +commit automatically with `git commit -s`. diff --git a/vendor/github.com/distribution/reference/GOVERNANCE.md b/vendor/github.com/distribution/reference/GOVERNANCE.md new file mode 100644 index 000000000..200045b05 --- /dev/null +++ b/vendor/github.com/distribution/reference/GOVERNANCE.md @@ -0,0 +1,144 @@ +# distribution/reference Project Governance + +Distribution [Code of Conduct](./CODE-OF-CONDUCT.md) can be found here. + +For specific guidance on practical contribution steps please +see our [CONTRIBUTING.md](./CONTRIBUTING.md) guide. + +## Maintainership + +There are different types of maintainers, with different responsibilities, but +all maintainers have 3 things in common: + +1) They share responsibility in the project's success. +2) They have made a long-term, recurring time investment to improve the project. +3) They spend that time doing whatever needs to be done, not necessarily what +is the most interesting or fun. + +Maintainers are often under-appreciated, because their work is harder to appreciate. +It's easy to appreciate a really cool and technically advanced feature. It's harder +to appreciate the absence of bugs, the slow but steady improvement in stability, +or the reliability of a release process. But those things distinguish a good +project from a great one. + +## Reviewers + +A reviewer is a core role within the project. +They share in reviewing issues and pull requests and their LGTM counts towards the +required LGTM count to merge a code change into the project. + +Reviewers are part of the organization but do not have write access. +Becoming a reviewer is a core aspect in the journey to becoming a maintainer. + +## Adding maintainers + +Maintainers are first and foremost contributors that have shown they are +committed to the long term success of a project. Contributors wanting to become +maintainers are expected to be deeply involved in contributing code, pull +request review, and triage of issues in the project for more than three months. + +Just contributing does not make you a maintainer, it is about building trust +with the current maintainers of the project and being a person that they can +depend on and trust to make decisions in the best interest of the project. + +Periodically, the existing maintainers curate a list of contributors that have +shown regular activity on the project over the prior months. From this list, +maintainer candidates are selected and proposed in a pull request or a +maintainers communication channel. + +After a candidate has been announced to the maintainers, the existing +maintainers are given five business days to discuss the candidate, raise +objections and cast their vote. Votes may take place on the communication +channel or via pull request comment. Candidates must be approved by at least 66% +of the current maintainers by adding their vote on the mailing list. The +reviewer role has the same process but only requires 33% of current maintainers. +Only maintainers of the repository that the candidate is proposed for are +allowed to vote. + +If a candidate is approved, a maintainer will contact the candidate to invite +the candidate to open a pull request that adds the contributor to the +MAINTAINERS file. The voting process may take place inside a pull request if a +maintainer has already discussed the candidacy with the candidate and a +maintainer is willing to be a sponsor by opening the pull request. The candidate +becomes a maintainer once the pull request is merged. + +## Stepping down policy + +Life priorities, interests, and passions can change. If you're a maintainer but +feel you must remove yourself from the list, inform other maintainers that you +intend to step down, and if possible, help find someone to pick up your work. +At the very least, ensure your work can be continued where you left off. + +After you've informed other maintainers, create a pull request to remove +yourself from the MAINTAINERS file. + +## Removal of inactive maintainers + +Similar to the procedure for adding new maintainers, existing maintainers can +be removed from the list if they do not show significant activity on the +project. Periodically, the maintainers review the list of maintainers and their +activity over the last three months. + +If a maintainer has shown insufficient activity over this period, a neutral +person will contact the maintainer to ask if they want to continue being +a maintainer. If the maintainer decides to step down as a maintainer, they +open a pull request to be removed from the MAINTAINERS file. + +If the maintainer wants to remain a maintainer, but is unable to perform the +required duties they can be removed with a vote of at least 66% of the current +maintainers. In this case, maintainers should first propose the change to +maintainers via the maintainers communication channel, then open a pull request +for voting. The voting period is five business days. The voting pull request +should not come as a surpise to any maintainer and any discussion related to +performance must not be discussed on the pull request. + +## How are decisions made? + +Docker distribution is an open-source project with an open design philosophy. +This means that the repository is the source of truth for EVERY aspect of the +project, including its philosophy, design, road map, and APIs. *If it's part of +the project, it's in the repo. If it's in the repo, it's part of the project.* + +As a result, all decisions can be expressed as changes to the repository. An +implementation change is a change to the source code. An API change is a change +to the API specification. A philosophy change is a change to the philosophy +manifesto, and so on. + +All decisions affecting distribution, big and small, follow the same 3 steps: + +* Step 1: Open a pull request. Anyone can do this. + +* Step 2: Discuss the pull request. Anyone can do this. + +* Step 3: Merge or refuse the pull request. Who does this depends on the nature +of the pull request and which areas of the project it affects. + +## Helping contributors with the DCO + +The [DCO or `Sign your work`](./CONTRIBUTING.md#sign-your-work) +requirement is not intended as a roadblock or speed bump. + +Some contributors are not as familiar with `git`, or have used a web +based editor, and thus asking them to `git commit --amend -s` is not the best +way forward. + +In this case, maintainers can update the commits based on clause (c) of the DCO. +The most trivial way for a contributor to allow the maintainer to do this, is to +add a DCO signature in a pull requests's comment, or a maintainer can simply +note that the change is sufficiently trivial that it does not substantially +change the existing contribution - i.e., a spelling change. + +When you add someone's DCO, please also add your own to keep a log. + +## I'm a maintainer. Should I make pull requests too? + +Yes. Nobody should ever push to master directly. All changes should be +made through a pull request. + +## Conflict Resolution + +If you have a technical dispute that you feel has reached an impasse with a +subset of the community, any contributor may open an issue, specifically +calling for a resolution vote of the current core maintainers to resolve the +dispute. The same voting quorums required (2/3) for adding and removing +maintainers will apply to conflict resolution. diff --git a/vendor/github.com/docker/distribution/LICENSE b/vendor/github.com/distribution/reference/LICENSE similarity index 100% rename from vendor/github.com/docker/distribution/LICENSE rename to vendor/github.com/distribution/reference/LICENSE diff --git a/vendor/github.com/distribution/reference/MAINTAINERS b/vendor/github.com/distribution/reference/MAINTAINERS new file mode 100644 index 000000000..9e0a60c8b --- /dev/null +++ b/vendor/github.com/distribution/reference/MAINTAINERS @@ -0,0 +1,26 @@ +# Distribution project maintainers & reviewers +# +# See GOVERNANCE.md for maintainer versus reviewer roles +# +# MAINTAINERS (cncf-distribution-maintainers@lists.cncf.io) +# GitHub ID, Name, Email address +"chrispat","Chris Patterson","chrispat@github.com" +"clarkbw","Bryan Clark","clarkbw@github.com" +"corhere","Cory Snider","csnider@mirantis.com" +"deleteriousEffect","Hayley Swimelar","hswimelar@gitlab.com" +"heww","He Weiwei","hweiwei@vmware.com" +"joaodrp","João Pereira","jpereira@gitlab.com" +"justincormack","Justin Cormack","justin.cormack@docker.com" +"squizzi","Kyle Squizzato","ksquizzato@mirantis.com" +"milosgajdos","Milos Gajdos","milosthegajdos@gmail.com" +"sargun","Sargun Dhillon","sargun@sargun.me" +"wy65701436","Wang Yan","wangyan@vmware.com" +"stevelasker","Steve Lasker","steve.lasker@microsoft.com" +# +# REVIEWERS +# GitHub ID, Name, Email address +"dmcgowan","Derek McGowan","derek@mcgstyle.net" +"stevvooe","Stephen Day","stevvooe@gmail.com" +"thajeztah","Sebastiaan van Stijn","github@gone.nl" +"DavidSpek", "David van der Spek", "vanderspek.david@gmail.com" +"Jamstah", "James Hewitt", "james.hewitt@gmail.com" diff --git a/vendor/github.com/distribution/reference/Makefile b/vendor/github.com/distribution/reference/Makefile new file mode 100644 index 000000000..c78576b75 --- /dev/null +++ b/vendor/github.com/distribution/reference/Makefile @@ -0,0 +1,25 @@ +# Project packages. +PACKAGES=$(shell go list ./...) + +# Flags passed to `go test` +BUILDFLAGS ?= +TESTFLAGS ?= + +.PHONY: all build test coverage +.DEFAULT: all + +all: build + +build: ## no binaries to build, so just check compilation suceeds + go build ${BUILDFLAGS} ./... + +test: ## run tests + go test ${TESTFLAGS} ./... + +coverage: ## generate coverprofiles from the unit tests + rm -f coverage.txt + go test ${TESTFLAGS} -cover -coverprofile=cover.out ./... + +.PHONY: help +help: + @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_\/%-]+:.*?##/ { printf " \033[36m%-27s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) diff --git a/vendor/github.com/distribution/reference/README.md b/vendor/github.com/distribution/reference/README.md new file mode 100644 index 000000000..e2531e49c --- /dev/null +++ b/vendor/github.com/distribution/reference/README.md @@ -0,0 +1,30 @@ +# Distribution reference + +Go library to handle references to container images. + + + +[![Build Status](https://github.com/distribution/reference/actions/workflows/test.yml/badge.svg?branch=main&event=push)](https://github.com/distribution/reference/actions?query=workflow%3ACI) +[![GoDoc](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/distribution/reference) +[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE) +[![codecov](https://codecov.io/gh/distribution/reference/branch/main/graph/badge.svg)](https://codecov.io/gh/distribution/reference) +[![FOSSA Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fdistribution%2Freference.svg?type=shield)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fdistribution%2Freference?ref=badge_shield) + +This repository contains a library for handling refrences to container images held in container registries. Please see [godoc](https://pkg.go.dev/github.com/distribution/reference) for details. + +## Contribution + +Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute +issues, fixes, and patches to this project. + +## Communication + +For async communication and long running discussions please use issues and pull requests on the github repo. +This will be the best place to discuss design and implementation. + +For sync communication we have a #distribution channel in the [CNCF Slack](https://slack.cncf.io/) +that everyone is welcome to join and chat about development. + +## Licenses + +The distribution codebase is released under the [Apache 2.0 license](LICENSE). diff --git a/vendor/github.com/distribution/reference/SECURITY.md b/vendor/github.com/distribution/reference/SECURITY.md new file mode 100644 index 000000000..aaf983c0f --- /dev/null +++ b/vendor/github.com/distribution/reference/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +## Reporting a Vulnerability + +The maintainers take security seriously. If you discover a security issue, please bring it to their attention right away! + +Please DO NOT file a public issue, instead send your report privately to cncf-distribution-security@lists.cncf.io. diff --git a/vendor/github.com/distribution/reference/distribution-logo.svg b/vendor/github.com/distribution/reference/distribution-logo.svg new file mode 100644 index 000000000..cc9f4073b --- /dev/null +++ b/vendor/github.com/distribution/reference/distribution-logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vendor/github.com/distribution/reference/helpers.go b/vendor/github.com/distribution/reference/helpers.go new file mode 100644 index 000000000..d10c7ef83 --- /dev/null +++ b/vendor/github.com/distribution/reference/helpers.go @@ -0,0 +1,42 @@ +package reference + +import "path" + +// IsNameOnly returns true if reference only contains a repo name. +func IsNameOnly(ref Named) bool { + if _, ok := ref.(NamedTagged); ok { + return false + } + if _, ok := ref.(Canonical); ok { + return false + } + return true +} + +// FamiliarName returns the familiar name string +// for the given named, familiarizing if needed. +func FamiliarName(ref Named) string { + if nn, ok := ref.(normalizedNamed); ok { + return nn.Familiar().Name() + } + return ref.Name() +} + +// FamiliarString returns the familiar string representation +// for the given reference, familiarizing if needed. +func FamiliarString(ref Reference) string { + if nn, ok := ref.(normalizedNamed); ok { + return nn.Familiar().String() + } + return ref.String() +} + +// FamiliarMatch reports whether ref matches the specified pattern. +// See [path.Match] for supported patterns. +func FamiliarMatch(pattern string, ref Reference) (bool, error) { + matched, err := path.Match(pattern, FamiliarString(ref)) + if namedRef, isNamed := ref.(Named); isNamed && !matched { + matched, _ = path.Match(pattern, FamiliarName(namedRef)) + } + return matched, err +} diff --git a/vendor/github.com/distribution/reference/normalize.go b/vendor/github.com/distribution/reference/normalize.go new file mode 100644 index 000000000..a30229d01 --- /dev/null +++ b/vendor/github.com/distribution/reference/normalize.go @@ -0,0 +1,224 @@ +package reference + +import ( + "fmt" + "strings" + + "github.com/opencontainers/go-digest" +) + +const ( + // legacyDefaultDomain is the legacy domain for Docker Hub (which was + // originally named "the Docker Index"). This domain is still used for + // authentication and image search, which were part of the "v1" Docker + // registry specification. + // + // This domain will continue to be supported, but there are plans to consolidate + // legacy domains to new "canonical" domains. Once those domains are decided + // on, we must update the normalization functions, but preserve compatibility + // with existing installs, clients, and user configuration. + legacyDefaultDomain = "index.docker.io" + + // defaultDomain is the default domain used for images on Docker Hub. + // It is used to normalize "familiar" names to canonical names, for example, + // to convert "ubuntu" to "docker.io/library/ubuntu:latest". + // + // Note that actual domain of Docker Hub's registry is registry-1.docker.io. + // This domain will continue to be supported, but there are plans to consolidate + // legacy domains to new "canonical" domains. Once those domains are decided + // on, we must update the normalization functions, but preserve compatibility + // with existing installs, clients, and user configuration. + defaultDomain = "docker.io" + + // officialRepoPrefix is the namespace used for official images on Docker Hub. + // It is used to normalize "familiar" names to canonical names, for example, + // to convert "ubuntu" to "docker.io/library/ubuntu:latest". + officialRepoPrefix = "library/" + + // defaultTag is the default tag if no tag is provided. + defaultTag = "latest" +) + +// normalizedNamed represents a name which has been +// normalized and has a familiar form. A familiar name +// is what is used in Docker UI. An example normalized +// name is "docker.io/library/ubuntu" and corresponding +// familiar name of "ubuntu". +type normalizedNamed interface { + Named + Familiar() Named +} + +// ParseNormalizedNamed parses a string into a named reference +// transforming a familiar name from Docker UI to a fully +// qualified reference. If the value may be an identifier +// use ParseAnyReference. +func ParseNormalizedNamed(s string) (Named, error) { + if ok := anchoredIdentifierRegexp.MatchString(s); ok { + return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) + } + domain, remainder := splitDockerDomain(s) + var remote string + if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { + remote = remainder[:tagSep] + } else { + remote = remainder + } + if strings.ToLower(remote) != remote { + return nil, fmt.Errorf("invalid reference format: repository name (%s) must be lowercase", remote) + } + + ref, err := Parse(domain + "/" + remainder) + if err != nil { + return nil, err + } + named, isNamed := ref.(Named) + if !isNamed { + return nil, fmt.Errorf("reference %s has no name", ref.String()) + } + return named, nil +} + +// namedTaggedDigested is a reference that has both a tag and a digest. +type namedTaggedDigested interface { + NamedTagged + Digested +} + +// ParseDockerRef normalizes the image reference following the docker convention, +// which allows for references to contain both a tag and a digest. It returns a +// reference that is either tagged or digested. For references containing both +// a tag and a digest, it returns a digested reference. For example, the following +// reference: +// +// docker.io/library/busybox:latest@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa +// +// Is returned as a digested reference (with the ":latest" tag removed): +// +// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa +// +// References that are already "tagged" or "digested" are returned unmodified: +// +// // Already a digested reference +// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa +// +// // Already a named reference +// docker.io/library/busybox:latest +func ParseDockerRef(ref string) (Named, error) { + named, err := ParseNormalizedNamed(ref) + if err != nil { + return nil, err + } + if canonical, ok := named.(namedTaggedDigested); ok { + // The reference is both tagged and digested; only return digested. + newNamed, err := WithName(canonical.Name()) + if err != nil { + return nil, err + } + return WithDigest(newNamed, canonical.Digest()) + } + return TagNameOnly(named), nil +} + +// splitDockerDomain splits a repository name to domain and remote-name. +// If no valid domain is found, the default domain is used. Repository name +// needs to be already validated before. +func splitDockerDomain(name string) (domain, remainder string) { + i := strings.IndexRune(name, '/') + if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != localhost && strings.ToLower(name[:i]) == name[:i]) { + domain, remainder = defaultDomain, name + } else { + domain, remainder = name[:i], name[i+1:] + } + if domain == legacyDefaultDomain { + domain = defaultDomain + } + if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { + remainder = officialRepoPrefix + remainder + } + return +} + +// familiarizeName returns a shortened version of the name familiar +// to the Docker UI. Familiar names have the default domain +// "docker.io" and "library/" repository prefix removed. +// For example, "docker.io/library/redis" will have the familiar +// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". +// Returns a familiarized named only reference. +func familiarizeName(named namedRepository) repository { + repo := repository{ + domain: named.Domain(), + path: named.Path(), + } + + if repo.domain == defaultDomain { + repo.domain = "" + // Handle official repositories which have the pattern "library/" + if strings.HasPrefix(repo.path, officialRepoPrefix) { + // TODO(thaJeztah): this check may be too strict, as it assumes the + // "library/" namespace does not have nested namespaces. While this + // is true (currently), technically it would be possible for Docker + // Hub to use those (e.g. "library/distros/ubuntu:latest"). + // See https://github.com/distribution/distribution/pull/3769#issuecomment-1302031785. + if remainder := strings.TrimPrefix(repo.path, officialRepoPrefix); !strings.ContainsRune(remainder, '/') { + repo.path = remainder + } + } + } + return repo +} + +func (r reference) Familiar() Named { + return reference{ + namedRepository: familiarizeName(r.namedRepository), + tag: r.tag, + digest: r.digest, + } +} + +func (r repository) Familiar() Named { + return familiarizeName(r) +} + +func (t taggedReference) Familiar() Named { + return taggedReference{ + namedRepository: familiarizeName(t.namedRepository), + tag: t.tag, + } +} + +func (c canonicalReference) Familiar() Named { + return canonicalReference{ + namedRepository: familiarizeName(c.namedRepository), + digest: c.digest, + } +} + +// TagNameOnly adds the default tag "latest" to a reference if it only has +// a repo name. +func TagNameOnly(ref Named) Named { + if IsNameOnly(ref) { + namedTagged, err := WithTag(ref, defaultTag) + if err != nil { + // Default tag must be valid, to create a NamedTagged + // type with non-validated input the WithTag function + // should be used instead + panic(err) + } + return namedTagged + } + return ref +} + +// ParseAnyReference parses a reference string as a possible identifier, +// full digest, or familiar name. +func ParseAnyReference(ref string) (Reference, error) { + if ok := anchoredIdentifierRegexp.MatchString(ref); ok { + return digestReference("sha256:" + ref), nil + } + if dgst, err := digest.Parse(ref); err == nil { + return digestReference(dgst), nil + } + + return ParseNormalizedNamed(ref) +} diff --git a/vendor/github.com/docker/distribution/reference/reference.go b/vendor/github.com/distribution/reference/reference.go similarity index 93% rename from vendor/github.com/docker/distribution/reference/reference.go rename to vendor/github.com/distribution/reference/reference.go index b7cd00b0d..e98c44daa 100644 --- a/vendor/github.com/docker/distribution/reference/reference.go +++ b/vendor/github.com/distribution/reference/reference.go @@ -4,11 +4,14 @@ // Grammar // // reference := name [ ":" tag ] [ "@" digest ] -// name := [domain '/'] path-component ['/' path-component]* -// domain := domain-component ['.' domain-component]* [':' port-number] +// name := [domain '/'] remote-name +// domain := host [':' port-number] +// host := domain-name | IPv4address | \[ IPv6address \] ; rfc3986 appendix-A +// domain-name := domain-component ['.' domain-component]* // domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ // port-number := /[0-9]+/ // path-component := alpha-numeric [separator alpha-numeric]* +// path (or "remote-name") := path-component ['/' path-component]* // alpha-numeric := /[a-z0-9]+/ // separator := /[_.]|__|[-]*/ // @@ -21,7 +24,6 @@ // digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value // // identifier := /[a-f0-9]{64}/ -// short-identifier := /[a-f0-9]{6,64}/ package reference import ( @@ -145,7 +147,7 @@ type namedRepository interface { Path() string } -// Domain returns the domain part of the Named reference +// Domain returns the domain part of the [Named] reference. func Domain(named Named) string { if r, ok := named.(namedRepository); ok { return r.Domain() @@ -154,7 +156,7 @@ func Domain(named Named) string { return domain } -// Path returns the name without the domain part of the Named reference +// Path returns the name without the domain part of the [Named] reference. func Path(named Named) (name string) { if r, ok := named.(namedRepository); ok { return r.Path() @@ -175,7 +177,8 @@ func splitDomain(name string) (string, string) { // hostname and name string. If no valid hostname is // found, the hostname is empty and the full value // is returned as name -// DEPRECATED: Use Domain or Path +// +// Deprecated: Use [Domain] or [Path]. func SplitHostname(named Named) (string, string) { if r, ok := named.(namedRepository); ok { return r.Domain(), r.Path() @@ -185,7 +188,6 @@ func SplitHostname(named Named) (string, string) { // Parse parses s and returns a syntactically valid Reference. // If an error was encountered it is returned, along with a nil Reference. -// NOTE: Parse will not handle short digests. func Parse(s string) (Reference, error) { matches := ReferenceRegexp.FindStringSubmatch(s) if matches == nil { @@ -237,7 +239,6 @@ func Parse(s string) (Reference, error) { // the Named interface. The reference must have a name and be in the canonical // form, otherwise an error is returned. // If an error was encountered it is returned, along with a nil Reference. -// NOTE: ParseNamed will not handle short digests. func ParseNamed(s string) (Named, error) { named, err := ParseNormalizedNamed(s) if err != nil { @@ -320,11 +321,13 @@ func WithDigest(name Named, digest digest.Digest) (Canonical, error) { // TrimNamed removes any tag or digest from the named reference. func TrimNamed(ref Named) Named { - domain, path := SplitHostname(ref) - return repository{ - domain: domain, - path: path, + repo := repository{} + if r, ok := ref.(namedRepository); ok { + repo.domain, repo.path = r.Domain(), r.Path() + } else { + repo.domain, repo.path = splitDomain(ref.Name()) } + return repo } func getBestReferenceType(ref reference) Reference { diff --git a/vendor/github.com/distribution/reference/regexp.go b/vendor/github.com/distribution/reference/regexp.go new file mode 100644 index 000000000..65bc49d79 --- /dev/null +++ b/vendor/github.com/distribution/reference/regexp.go @@ -0,0 +1,163 @@ +package reference + +import ( + "regexp" + "strings" +) + +// DigestRegexp matches well-formed digests, including algorithm (e.g. "sha256:"). +var DigestRegexp = regexp.MustCompile(digestPat) + +// DomainRegexp matches hostname or IP-addresses, optionally including a port +// number. It defines the structure of potential domain components that may be +// part of image names. This is purposely a subset of what is allowed by DNS to +// ensure backwards compatibility with Docker image names. It may be a subset of +// DNS domain name, an IPv4 address in decimal format, or an IPv6 address between +// square brackets (excluding zone identifiers as defined by [RFC 6874] or special +// addresses such as IPv4-Mapped). +// +// [RFC 6874]: https://www.rfc-editor.org/rfc/rfc6874. +var DomainRegexp = regexp.MustCompile(domainAndPort) + +// IdentifierRegexp is the format for string identifier used as a +// content addressable identifier using sha256. These identifiers +// are like digests without the algorithm, since sha256 is used. +var IdentifierRegexp = regexp.MustCompile(identifier) + +// NameRegexp is the format for the name component of references, including +// an optional domain and port, but without tag or digest suffix. +var NameRegexp = regexp.MustCompile(namePat) + +// ReferenceRegexp is the full supported format of a reference. The regexp +// is anchored and has capturing groups for name, tag, and digest +// components. +var ReferenceRegexp = regexp.MustCompile(referencePat) + +// TagRegexp matches valid tag names. From [docker/docker:graph/tags.go]. +// +// [docker/docker:graph/tags.go]: https://github.com/moby/moby/blob/v1.6.0/graph/tags.go#L26-L28 +var TagRegexp = regexp.MustCompile(tag) + +const ( + // alphanumeric defines the alphanumeric atom, typically a + // component of names. This only allows lower case characters and digits. + alphanumeric = `[a-z0-9]+` + + // separator defines the separators allowed to be embedded in name + // components. This allows one period, one or two underscore and multiple + // dashes. Repeated dashes and underscores are intentionally treated + // differently. In order to support valid hostnames as name components, + // supporting repeated dash was added. Additionally double underscore is + // now allowed as a separator to loosen the restriction for previously + // supported names. + separator = `(?:[._]|__|[-]+)` + + // localhost is treated as a special value for domain-name. Any other + // domain-name without a "." or a ":port" are considered a path component. + localhost = `localhost` + + // domainNameComponent restricts the registry domain component of a + // repository name to start with a component as defined by DomainRegexp. + domainNameComponent = `(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])` + + // optionalPort matches an optional port-number including the port separator + // (e.g. ":80"). + optionalPort = `(?::[0-9]+)?` + + // tag matches valid tag names. From docker/docker:graph/tags.go. + tag = `[\w][\w.-]{0,127}` + + // digestPat matches well-formed digests, including algorithm (e.g. "sha256:"). + // + // TODO(thaJeztah): this should follow the same rules as https://pkg.go.dev/github.com/opencontainers/go-digest@v1.0.0#DigestRegexp + // so that go-digest defines the canonical format. Note that the go-digest is + // more relaxed: + // - it allows multiple algorithms (e.g. "sha256+b64:") to allow + // future expansion of supported algorithms. + // - it allows the "" value to use urlsafe base64 encoding as defined + // in [rfc4648, section 5]. + // + // [rfc4648, section 5]: https://www.rfc-editor.org/rfc/rfc4648#section-5. + digestPat = `[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}` + + // identifier is the format for a content addressable identifier using sha256. + // These identifiers are like digests without the algorithm, since sha256 is used. + identifier = `([a-f0-9]{64})` + + // ipv6address are enclosed between square brackets and may be represented + // in many ways, see rfc5952. Only IPv6 in compressed or uncompressed format + // are allowed, IPv6 zone identifiers (rfc6874) or Special addresses such as + // IPv4-Mapped are deliberately excluded. + ipv6address = `\[(?:[a-fA-F0-9:]+)\]` +) + +var ( + // domainName defines the structure of potential domain components + // that may be part of image names. This is purposely a subset of what is + // allowed by DNS to ensure backwards compatibility with Docker image + // names. This includes IPv4 addresses on decimal format. + domainName = domainNameComponent + anyTimes(`\.`+domainNameComponent) + + // host defines the structure of potential domains based on the URI + // Host subcomponent on rfc3986. It may be a subset of DNS domain name, + // or an IPv4 address in decimal format, or an IPv6 address between square + // brackets (excluding zone identifiers as defined by rfc6874 or special + // addresses such as IPv4-Mapped). + host = `(?:` + domainName + `|` + ipv6address + `)` + + // allowed by the URI Host subcomponent on rfc3986 to ensure backwards + // compatibility with Docker image names. + domainAndPort = host + optionalPort + + // anchoredTagRegexp matches valid tag names, anchored at the start and + // end of the matched string. + anchoredTagRegexp = regexp.MustCompile(anchored(tag)) + + // anchoredDigestRegexp matches valid digests, anchored at the start and + // end of the matched string. + anchoredDigestRegexp = regexp.MustCompile(anchored(digestPat)) + + // pathComponent restricts path-components to start with an alphanumeric + // character, with following parts able to be separated by a separator + // (one period, one or two underscore and multiple dashes). + pathComponent = alphanumeric + anyTimes(separator+alphanumeric) + + // remoteName matches the remote-name of a repository. It consists of one + // or more forward slash (/) delimited path-components: + // + // pathComponent[[/pathComponent] ...] // e.g., "library/ubuntu" + remoteName = pathComponent + anyTimes(`/`+pathComponent) + namePat = optional(domainAndPort+`/`) + remoteName + + // anchoredNameRegexp is used to parse a name value, capturing the + // domain and trailing components. + anchoredNameRegexp = regexp.MustCompile(anchored(optional(capture(domainAndPort), `/`), capture(remoteName))) + + referencePat = anchored(capture(namePat), optional(`:`, capture(tag)), optional(`@`, capture(digestPat))) + + // anchoredIdentifierRegexp is used to check or match an + // identifier value, anchored at start and end of string. + anchoredIdentifierRegexp = regexp.MustCompile(anchored(identifier)) +) + +// optional wraps the expression in a non-capturing group and makes the +// production optional. +func optional(res ...string) string { + return `(?:` + strings.Join(res, "") + `)?` +} + +// anyTimes wraps the expression in a non-capturing group that can occur +// any number of times. +func anyTimes(res ...string) string { + return `(?:` + strings.Join(res, "") + `)*` +} + +// capture wraps the expression in a capturing group. +func capture(res ...string) string { + return `(` + strings.Join(res, "") + `)` +} + +// anchored anchors the regular expression by adding start and end delimiters. +func anchored(res ...string) string { + return `^` + strings.Join(res, "") + `$` +} diff --git a/vendor/github.com/distribution/reference/sort.go b/vendor/github.com/distribution/reference/sort.go new file mode 100644 index 000000000..416c37b07 --- /dev/null +++ b/vendor/github.com/distribution/reference/sort.go @@ -0,0 +1,75 @@ +/* + Copyright The containerd 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 reference + +import ( + "sort" +) + +// Sort sorts string references preferring higher information references. +// +// The precedence is as follows: +// +// 1. [Named] + [Tagged] + [Digested] (e.g., "docker.io/library/busybox:latest@sha256:") +// 2. [Named] + [Tagged] (e.g., "docker.io/library/busybox:latest") +// 3. [Named] + [Digested] (e.g., "docker.io/library/busybo@sha256:") +// 4. [Named] (e.g., "docker.io/library/busybox") +// 5. [Digested] (e.g., "docker.io@sha256:") +// 6. Parse error +func Sort(references []string) []string { + var prefs []Reference + var bad []string + + for _, ref := range references { + pref, err := ParseAnyReference(ref) + if err != nil { + bad = append(bad, ref) + } else { + prefs = append(prefs, pref) + } + } + sort.Slice(prefs, func(a, b int) bool { + ar := refRank(prefs[a]) + br := refRank(prefs[b]) + if ar == br { + return prefs[a].String() < prefs[b].String() + } + return ar < br + }) + sort.Strings(bad) + var refs []string + for _, pref := range prefs { + refs = append(refs, pref.String()) + } + return append(refs, bad...) +} + +func refRank(ref Reference) uint8 { + if _, ok := ref.(Named); ok { + if _, ok = ref.(Tagged); ok { + if _, ok = ref.(Digested); ok { + return 1 + } + return 2 + } + if _, ok = ref.(Digested); ok { + return 3 + } + return 4 + } + return 5 +} diff --git a/vendor/github.com/docker/distribution/digestset/set.go b/vendor/github.com/docker/distribution/digestset/set.go deleted file mode 100644 index 71327dca7..000000000 --- a/vendor/github.com/docker/distribution/digestset/set.go +++ /dev/null @@ -1,247 +0,0 @@ -package digestset - -import ( - "errors" - "sort" - "strings" - "sync" - - digest "github.com/opencontainers/go-digest" -) - -var ( - // ErrDigestNotFound is used when a matching digest - // could not be found in a set. - ErrDigestNotFound = errors.New("digest not found") - - // ErrDigestAmbiguous is used when multiple digests - // are found in a set. None of the matching digests - // should be considered valid matches. - ErrDigestAmbiguous = errors.New("ambiguous digest string") -) - -// Set is used to hold a unique set of digests which -// may be easily referenced by easily referenced by a string -// representation of the digest as well as short representation. -// The uniqueness of the short representation is based on other -// digests in the set. If digests are omitted from this set, -// collisions in a larger set may not be detected, therefore it -// is important to always do short representation lookups on -// the complete set of digests. To mitigate collisions, an -// appropriately long short code should be used. -type Set struct { - mutex sync.RWMutex - entries digestEntries -} - -// NewSet creates an empty set of digests -// which may have digests added. -func NewSet() *Set { - return &Set{ - entries: digestEntries{}, - } -} - -// checkShortMatch checks whether two digests match as either whole -// values or short values. This function does not test equality, -// rather whether the second value could match against the first -// value. -func checkShortMatch(alg digest.Algorithm, hex, shortAlg, shortHex string) bool { - if len(hex) == len(shortHex) { - if hex != shortHex { - return false - } - if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - } else if !strings.HasPrefix(hex, shortHex) { - return false - } else if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - return true -} - -// Lookup looks for a digest matching the given string representation. -// If no digests could be found ErrDigestNotFound will be returned -// with an empty digest value. If multiple matches are found -// ErrDigestAmbiguous will be returned with an empty digest value. -func (dst *Set) Lookup(d string) (digest.Digest, error) { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - if len(dst.entries) == 0 { - return "", ErrDigestNotFound - } - var ( - searchFunc func(int) bool - alg digest.Algorithm - hex string - ) - dgst, err := digest.Parse(d) - if err == digest.ErrDigestInvalidFormat { - hex = d - searchFunc = func(i int) bool { - return dst.entries[i].val >= d - } - } else { - hex = dgst.Hex() - alg = dgst.Algorithm() - searchFunc = func(i int) bool { - if dst.entries[i].val == hex { - return dst.entries[i].alg >= alg - } - return dst.entries[i].val >= hex - } - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) || !checkShortMatch(dst.entries[idx].alg, dst.entries[idx].val, string(alg), hex) { - return "", ErrDigestNotFound - } - if dst.entries[idx].alg == alg && dst.entries[idx].val == hex { - return dst.entries[idx].digest, nil - } - if idx+1 < len(dst.entries) && checkShortMatch(dst.entries[idx+1].alg, dst.entries[idx+1].val, string(alg), hex) { - return "", ErrDigestAmbiguous - } - - return dst.entries[idx].digest, nil -} - -// Add adds the given digest to the set. An error will be returned -// if the given digest is invalid. If the digest already exists in the -// set, this operation will be a no-op. -func (dst *Set) Add(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) { - dst.entries = append(dst.entries, entry) - return nil - } else if dst.entries[idx].digest == d { - return nil - } - - entries := append(dst.entries, nil) - copy(entries[idx+1:], entries[idx:len(entries)-1]) - entries[idx] = entry - dst.entries = entries - return nil -} - -// Remove removes the given digest from the set. An err will be -// returned if the given digest is invalid. If the digest does -// not exist in the set, this operation will be a no-op. -func (dst *Set) Remove(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - // Not found if idx is after or value at idx is not digest - if idx == len(dst.entries) || dst.entries[idx].digest != d { - return nil - } - - entries := dst.entries - copy(entries[idx:], entries[idx+1:]) - entries = entries[:len(entries)-1] - dst.entries = entries - - return nil -} - -// All returns all the digests in the set -func (dst *Set) All() []digest.Digest { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - retValues := make([]digest.Digest, len(dst.entries)) - for i := range dst.entries { - retValues[i] = dst.entries[i].digest - } - - return retValues -} - -// ShortCodeTable returns a map of Digest to unique short codes. The -// length represents the minimum value, the maximum length may be the -// entire value of digest if uniqueness cannot be achieved without the -// full value. This function will attempt to make short codes as short -// as possible to be unique. -func ShortCodeTable(dst *Set, length int) map[digest.Digest]string { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - m := make(map[digest.Digest]string, len(dst.entries)) - l := length - resetIdx := 0 - for i := 0; i < len(dst.entries); i++ { - var short string - extended := true - for extended { - extended = false - if len(dst.entries[i].val) <= l { - short = dst.entries[i].digest.String() - } else { - short = dst.entries[i].val[:l] - for j := i + 1; j < len(dst.entries); j++ { - if checkShortMatch(dst.entries[j].alg, dst.entries[j].val, "", short) { - if j > resetIdx { - resetIdx = j - } - extended = true - } else { - break - } - } - if extended { - l++ - } - } - } - m[dst.entries[i].digest] = short - if i >= resetIdx { - l = length - } - } - return m -} - -type digestEntry struct { - alg digest.Algorithm - val string - digest digest.Digest -} - -type digestEntries []*digestEntry - -func (d digestEntries) Len() int { - return len(d) -} - -func (d digestEntries) Less(i, j int) bool { - if d[i].val != d[j].val { - return d[i].val < d[j].val - } - return d[i].alg < d[j].alg -} - -func (d digestEntries) Swap(i, j int) { - d[i], d[j] = d[j], d[i] -} diff --git a/vendor/github.com/docker/distribution/reference/helpers.go b/vendor/github.com/docker/distribution/reference/helpers.go deleted file mode 100644 index 978df7eab..000000000 --- a/vendor/github.com/docker/distribution/reference/helpers.go +++ /dev/null @@ -1,42 +0,0 @@ -package reference - -import "path" - -// IsNameOnly returns true if reference only contains a repo name. -func IsNameOnly(ref Named) bool { - if _, ok := ref.(NamedTagged); ok { - return false - } - if _, ok := ref.(Canonical); ok { - return false - } - return true -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -func FamiliarName(ref Named) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().Name() - } - return ref.Name() -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -func FamiliarString(ref Reference) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().String() - } - return ref.String() -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See https://godoc.org/path#Match for supported patterns. -func FamiliarMatch(pattern string, ref Reference) (bool, error) { - matched, err := path.Match(pattern, FamiliarString(ref)) - if namedRef, isNamed := ref.(Named); isNamed && !matched { - matched, _ = path.Match(pattern, FamiliarName(namedRef)) - } - return matched, err -} diff --git a/vendor/github.com/docker/distribution/reference/normalize.go b/vendor/github.com/docker/distribution/reference/normalize.go deleted file mode 100644 index b3dfb7a6d..000000000 --- a/vendor/github.com/docker/distribution/reference/normalize.go +++ /dev/null @@ -1,199 +0,0 @@ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/docker/distribution/digestset" - "github.com/opencontainers/go-digest" -) - -var ( - legacyDefaultDomain = "index.docker.io" - defaultDomain = "docker.io" - officialRepoName = "library" - defaultTag = "latest" -) - -// normalizedNamed represents a name which has been -// normalized and has a familiar form. A familiar name -// is what is used in Docker UI. An example normalized -// name is "docker.io/library/ubuntu" and corresponding -// familiar name of "ubuntu". -type normalizedNamed interface { - Named - Familiar() Named -} - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -func ParseNormalizedNamed(s string) (Named, error) { - if ok := anchoredIdentifierRegexp.MatchString(s); ok { - return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) - } - domain, remainder := splitDockerDomain(s) - var remoteName string - if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { - remoteName = remainder[:tagSep] - } else { - remoteName = remainder - } - if strings.ToLower(remoteName) != remoteName { - return nil, errors.New("invalid reference format: repository name must be lowercase") - } - - ref, err := Parse(domain + "/" + remainder) - if err != nil { - return nil, err - } - named, isNamed := ref.(Named) - if !isNamed { - return nil, fmt.Errorf("reference %s has no name", ref.String()) - } - return named, nil -} - -// ParseDockerRef normalizes the image reference following the docker convention. This is added -// mainly for backward compatibility. -// The reference returned can only be either tagged or digested. For reference contains both tag -// and digest, the function returns digested reference, e.g. docker.io/library/busybox:latest@ -// sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa will be returned as -// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa. -func ParseDockerRef(ref string) (Named, error) { - named, err := ParseNormalizedNamed(ref) - if err != nil { - return nil, err - } - if _, ok := named.(NamedTagged); ok { - if canonical, ok := named.(Canonical); ok { - // The reference is both tagged and digested, only - // return digested. - newNamed, err := WithName(canonical.Name()) - if err != nil { - return nil, err - } - newCanonical, err := WithDigest(newNamed, canonical.Digest()) - if err != nil { - return nil, err - } - return newCanonical, nil - } - } - return TagNameOnly(named), nil -} - -// splitDockerDomain splits a repository name to domain and remotename string. -// If no valid domain is found, the default domain is used. Repository name -// needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoName + "/" + remainder - } - return -} - -// familiarizeName returns a shortened version of the name familiar -// to to the Docker UI. Familiar names have the default domain -// "docker.io" and "library/" repository prefix removed. -// For example, "docker.io/library/redis" will have the familiar -// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". -// Returns a familiarized named only reference. -func familiarizeName(named namedRepository) repository { - repo := repository{ - domain: named.Domain(), - path: named.Path(), - } - - if repo.domain == defaultDomain { - repo.domain = "" - // Handle official repositories which have the pattern "library/" - if split := strings.Split(repo.path, "/"); len(split) == 2 && split[0] == officialRepoName { - repo.path = split[1] - } - } - return repo -} - -func (r reference) Familiar() Named { - return reference{ - namedRepository: familiarizeName(r.namedRepository), - tag: r.tag, - digest: r.digest, - } -} - -func (r repository) Familiar() Named { - return familiarizeName(r) -} - -func (t taggedReference) Familiar() Named { - return taggedReference{ - namedRepository: familiarizeName(t.namedRepository), - tag: t.tag, - } -} - -func (c canonicalReference) Familiar() Named { - return canonicalReference{ - namedRepository: familiarizeName(c.namedRepository), - digest: c.digest, - } -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -func TagNameOnly(ref Named) Named { - if IsNameOnly(ref) { - namedTagged, err := WithTag(ref, defaultTag) - if err != nil { - // Default tag must be valid, to create a NamedTagged - // type with non-validated input the WithTag function - // should be used instead - panic(err) - } - return namedTagged - } - return ref -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -func ParseAnyReference(ref string) (Reference, error) { - if ok := anchoredIdentifierRegexp.MatchString(ref); ok { - return digestReference("sha256:" + ref), nil - } - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - - return ParseNormalizedNamed(ref) -} - -// ParseAnyReferenceWithSet parses a reference string as a possible short -// identifier to be matched in a digest set, a full digest, or familiar name. -func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { - if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { - dgst, err := ds.Lookup(ref) - if err == nil { - return digestReference(dgst), nil - } - } else { - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - } - - return ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/docker/distribution/reference/regexp.go b/vendor/github.com/docker/distribution/reference/regexp.go deleted file mode 100644 index 786034932..000000000 --- a/vendor/github.com/docker/distribution/reference/regexp.go +++ /dev/null @@ -1,143 +0,0 @@ -package reference - -import "regexp" - -var ( - // alphaNumericRegexp defines the alpha numeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphaNumericRegexp = match(`[a-z0-9]+`) - - // separatorRegexp defines the separators allowed to be embedded in name - // components. This allow one period, one or two underscore and multiple - // dashes. - separatorRegexp = match(`(?:[._]|__|[-]*)`) - - // nameComponentRegexp restricts registry path component names to start - // with at least one letter or number, with following parts able to be - // separated by one period, one or two underscore and multiple dashes. - nameComponentRegexp = expression( - alphaNumericRegexp, - optional(repeated(separatorRegexp, alphaNumericRegexp))) - - // domainComponentRegexp restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp - // and followed by an optional port. - domainComponentRegexp = match(`(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])`) - - // DomainRegexp defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. - DomainRegexp = expression( - domainComponentRegexp, - optional(repeated(literal(`.`), domainComponentRegexp)), - optional(literal(`:`), match(`[0-9]+`))) - - // TagRegexp matches valid tag names. From docker/docker:graph/tags.go. - TagRegexp = match(`[\w][\w.-]{0,127}`) - - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = anchored(TagRegexp) - - // DigestRegexp matches valid digests. - DigestRegexp = match(`[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}`) - - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = anchored(DigestRegexp) - - // NameRegexp is the format for the name component of references. The - // regexp has capturing groups for the domain and name part omitting - // the separating forward slash from either. - NameRegexp = expression( - optional(DomainRegexp, literal(`/`)), - nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp))) - - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = anchored( - optional(capture(DomainRegexp), literal(`/`)), - capture(nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp)))) - - // ReferenceRegexp is the full supported format of a reference. The regexp - // is anchored and has capturing groups for name, tag, and digest - // components. - ReferenceRegexp = anchored(capture(NameRegexp), - optional(literal(":"), capture(TagRegexp)), - optional(literal("@"), capture(DigestRegexp))) - - // IdentifierRegexp is the format for string identifier used as a - // content addressable identifier using sha256. These identifiers - // are like digests without the algorithm, since sha256 is used. - IdentifierRegexp = match(`([a-f0-9]{64})`) - - // ShortIdentifierRegexp is the format used to represent a prefix - // of an identifier. A prefix may be used to match a sha256 identifier - // within a list of trusted identifiers. - ShortIdentifierRegexp = match(`([a-f0-9]{6,64})`) - - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = anchored(IdentifierRegexp) - - // anchoredShortIdentifierRegexp is used to check if a value - // is a possible identifier prefix, anchored at start and end - // of string. - anchoredShortIdentifierRegexp = anchored(ShortIdentifierRegexp) -) - -// match compiles the string to a regular expression. -var match = regexp.MustCompile - -// literal compiles s into a literal regular expression, escaping any regexp -// reserved characters. -func literal(s string) *regexp.Regexp { - re := match(regexp.QuoteMeta(s)) - - if _, complete := re.LiteralPrefix(); !complete { - panic("must be a literal") - } - - return re -} - -// expression defines a full expression, where each regular expression must -// follow the previous. -func expression(res ...*regexp.Regexp) *regexp.Regexp { - var s string - for _, re := range res { - s += re.String() - } - - return match(s) -} - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `?`) -} - -// repeated wraps the regexp in a non-capturing group to get one or more -// matches. -func repeated(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `+`) -} - -// group wraps the regexp in a non-capturing group. -func group(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(?:` + expression(res...).String() + `)`) -} - -// capture wraps the expression in a capturing group. -func capture(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(` + expression(res...).String() + `)`) -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...*regexp.Regexp) *regexp.Regexp { - return match(`^` + expression(res...).String() + `$`) -} diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS index b31418192..48d04f9a9 100644 --- a/vendor/github.com/docker/docker/AUTHORS +++ b/vendor/github.com/docker/docker/AUTHORS @@ -27,6 +27,7 @@ Adam Miller Adam Mills Adam Pointer Adam Singer +Adam Thornton Adam Walz Adam Williams AdamKorcz @@ -173,6 +174,7 @@ Andy Rothfusz Andy Smith Andy Wilson Andy Zhang +Aneesh Kulkarni Anes Hasicic Angel Velazquez Anil Belur @@ -236,6 +238,7 @@ Ben Golub Ben Gould Ben Hall Ben Langfeld +Ben Lovy Ben Sargent Ben Severson Ben Toews @@ -262,7 +265,7 @@ Billy Ridgway Bily Zhang Bin Liu Bingshen Wang -Bjorn Neergaard +Bjorn Neergaard Blake Geno Boaz Shuster bobby abbott @@ -279,6 +282,7 @@ Brandon Liu Brandon Philips Brandon Rhodes Brendan Dixon +Brennan Kinney <5098581+polarathene@users.noreply.github.com> Brent Salisbury Brett Higgins Brett Kochendorfer @@ -363,6 +367,7 @@ chenyuzhu Chetan Birajdar Chewey Chia-liang Kao +Chiranjeevi Tirunagari chli Cholerae Hu Chris Alfonso @@ -433,8 +438,8 @@ Cristian Staretu cristiano balducci Cristina Yenyxe Gonzalez Garcia Cruceru Calin-Cristian +cui fliter CUI Wei -cuishuang Cuong Manh Le Cyprian Gracz Cyril F @@ -513,6 +518,7 @@ David Dooling David Gageot David Gebler David Glasser +David Karlsson <35727626+dvdksn@users.noreply.github.com> David Lawrence David Lechner David M. Karr @@ -602,6 +608,7 @@ Donald Huang Dong Chen Donghwa Kim Donovan Jones +Dorin Geman Doron Podoleanu Doug Davis Doug MacEachern @@ -636,6 +643,7 @@ Emily Rose Emir Ozer Eng Zer Jun Enguerran +Enrico Weigelt, metux IT consult Eohyung Lee epeterso er0k @@ -676,6 +684,7 @@ Evan Allrich Evan Carmi Evan Hazlett Evan Krall +Evan Lezar Evan Phoenix Evan Wies Evelyn Xu @@ -744,6 +753,7 @@ Frank Groeneveld Frank Herrmann Frank Macreery Frank Rosquin +Frank Villaro-Dixon Frank Yang Fred Lifton Frederick F. Kautz IV @@ -983,6 +993,7 @@ Jean Rouge Jean-Baptiste Barth Jean-Baptiste Dalido Jean-Christophe Berthon +Jean-Michel Rouet Jean-Paul Calderone Jean-Pierre Huynh Jean-Tiare Le Bigot @@ -1013,6 +1024,7 @@ Jeroen Jacobs Jesse Dearing Jesse Dubay Jessica Frazelle +Jeyanthinath Muthuram Jezeniel Zapanta Jhon Honce Ji.Zhilong @@ -1141,6 +1153,7 @@ junxu Jussi Nummelin Justas Brazauskas Justen Martin +Justin Chadwell Justin Cormack Justin Force Justin Keller <85903732+jk-vb@users.noreply.github.com> @@ -1183,6 +1196,7 @@ Ke Xu Kei Ohmura Keith Hudgins Keli Hu +Ken Bannister Ken Cochrane Ken Herner Ken ICHIKAWA @@ -1192,7 +1206,7 @@ Kenjiro Nakayama Kent Johnson Kenta Tada Kevin "qwazerty" Houdebert -Kevin Alvarez +Kevin Alvarez Kevin Burke Kevin Clark Kevin Feyrer @@ -1225,6 +1239,7 @@ Konstantin Gribov Konstantin L Konstantin Pelykh Kostadin Plachkov +kpcyrd Krasi Georgiev Krasimir Georgiev Kris-Mikael Krister @@ -1306,6 +1321,7 @@ Lorenzo Fontana Lotus Fenn Louis Delossantos Louis Opter +Luboslav Pivarc Luca Favatella Luca Marturana Luca Orlandi @@ -1344,6 +1360,7 @@ Manuel Meurer Manuel Rüger Manuel Woelker mapk0y +Marat Radchenko Marc Abramowitz Marc Kuo Marc Tamsky @@ -1383,6 +1400,7 @@ Martijn van Oosterhout Martin Braun Martin Dojcak Martin Honermeyer +Martin Jirku Martin Kelly Martin Mosegaard Amdisen Martin Muzatko @@ -1461,6 +1479,7 @@ Michael Holzheu Michael Hudson-Doyle Michael Huettermann Michael Irwin +Michael Kebe Michael Kuehn Michael Käufl Michael Neale @@ -1509,10 +1528,11 @@ Mike Lundy Mike MacCana Mike Naberezny Mike Snitzer +Mike Sul mikelinjie <294893458@qq.com> Mikhail Sobolev Miklos Szegedi -Milas Bowman +Milas Bowman Milind Chawre Miloslav TrmaÄ mingqing @@ -1524,6 +1544,7 @@ mlarcher Mohammad Banikazemi Mohammad Nasirifar Mohammed Aaqib Ansari +Mohd Sadiq Mohit Soni Moorthy RS Morgan Bauer @@ -1606,6 +1627,7 @@ Noah Treuhaft NobodyOnSE noducks Nolan Darilek +Nolan Miles Noriki Nakamura nponeccop Nurahmadie @@ -1661,6 +1683,7 @@ Paul Lietar Paul Liljenberg Paul Morie Paul Nasrat +Paul Seiffert Paul Weaver Paulo Gomes Paulo Ribeiro @@ -1674,6 +1697,7 @@ Pavlos Ratis Pavol Vargovcik Pawel Konczalski PaweÅ‚ Gronowski +payall4u Peeyush Gupta Peggy Li Pei Su @@ -1703,7 +1727,9 @@ Phil Estes Phil Sphicas Phil Spitler Philip Alexander Etling +Philip K. Warren Philip Monroe +Philipp Fruck Philipp Gillé Philipp Wahala Philipp Weissensteiner @@ -1741,6 +1767,7 @@ Quentin Brossard Quentin Perez Quentin Tayssier r0n22 +Rachit Sharma Radostin Stoyanov Rafal Jeczalik Rafe Colton @@ -1773,6 +1800,7 @@ Rich Horwood Rich Moyse Rich Seymour Richard Burnison +Richard Hansen Richard Harvey Richard Mathie Richard Metzler @@ -1788,6 +1816,7 @@ Ritesh H Shukla Riyaz Faizullabhoy Rob Cowsill <42620235+rcowsill@users.noreply.github.com> Rob Gulewich +Rob Murray Rob Vesse Robert Bachmann Robert Bittle @@ -1869,6 +1898,7 @@ ryancooper7 RyanDeng Ryo Nakao Ryoga Saito +Régis Behmo Rémy Greinhofer s. rannou Sabin Basyal @@ -1885,6 +1915,7 @@ Sam J Sharpe Sam Neirinck Sam Reis Sam Rijs +Sam Thibault Sam Whited Sambuddha Basu Sami Wagiaalla @@ -1908,6 +1939,7 @@ Satoshi Tagomori Scott Bessler Scott Collier Scott Johnston +Scott Moser Scott Percival Scott Stamp Scott Walls @@ -1923,6 +1955,7 @@ Sebastiaan van Steenis Sebastiaan van Stijn Sebastian Höffner Sebastian Radloff +Sebastian Thomschke Sebastien Goasguen Senthil Kumar Selvaraj Senthil Kumaran @@ -1996,6 +2029,7 @@ Stanislav Bondarenko Stanislav Levin Steeve Morin Stefan Berger +Stefan Gehrig Stefan J. Wernli Stefan Praszalowicz Stefan S. @@ -2003,6 +2037,7 @@ Stefan Scherer Stefan Staudenmeyer Stefan Weil Steffen Butzer +Stephan Henningsen Stephan Spindler Stephen Benjamin Stephen Crosby @@ -2204,6 +2239,7 @@ Vinod Kulkarni Vishal Doshi Vishnu Kannan Vitaly Ostrosablin +Vitor Anjos Vitor Monteiro Vivek Agarwal Vivek Dasgupta @@ -2250,6 +2286,7 @@ Wenxuan Zhao Wenyu You <21551128@zju.edu.cn> Wenzhi Liang Wes Morgan +Wesley Pettit Wewang Xiaorenfine Wiktor Kwapisiewicz Will Dietz @@ -2289,7 +2326,7 @@ xiekeyang Ximo Guanter Gonzálbez xin.li Xinbo Weng -Xinfeng Liu +Xinfeng Liu Xinzi Zhou Xiuming Chen Xuecong Liao @@ -2355,6 +2392,7 @@ Zen Lin(Zhinan Lin) Zhang Kun Zhang Wei Zhang Wentao +zhangguanzhang ZhangHang zhangxianwei Zhenan Ye <21551168@zju.edu.cn> @@ -2381,6 +2419,7 @@ Zuhayr Elahi Zunayed Ali Ãlvaro Lázaro Ãtila Camurça Alves +å´å°ç™½ <296015668@qq.com> å°¹å‰å³° å±ˆéª å¾ä¿Šæ° diff --git a/vendor/github.com/docker/docker/api/README.md b/vendor/github.com/docker/docker/api/README.md index f136c3433..381f19881 100644 --- a/vendor/github.com/docker/docker/api/README.md +++ b/vendor/github.com/docker/docker/api/README.md @@ -37,6 +37,6 @@ There is hopefully enough example material in the file for you to copy a similar When you make edits to `swagger.yaml`, you may want to check the generated API documentation to ensure it renders correctly. -Run `make swagger-docs` and a preview will be running at `http://localhost`. Some of the styling may be incorrect, but you'll be able to ensure that it is generating the correct documentation. +Run `make swagger-docs` and a preview will be running at `http://localhost:9000`. Some of the styling may be incorrect, but you'll be able to ensure that it is generating the correct documentation. The production documentation is generated by vendoring `swagger.yaml` into [docker/docker.github.io](https://github.com/docker/docker.github.io). diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go index cba66bc46..37e553d41 100644 --- a/vendor/github.com/docker/docker/api/common.go +++ b/vendor/github.com/docker/docker/api/common.go @@ -3,7 +3,7 @@ package api // import "github.com/docker/docker/api" // Common constants for daemon and client. const ( // DefaultVersion of Current REST API - DefaultVersion = "1.43" + DefaultVersion = "1.44" // NoBaseImageSpecifier is the symbol used by the FROM // command to specify that no base image is to be used. diff --git a/vendor/github.com/docker/docker/api/common_unix.go b/vendor/github.com/docker/docker/api/common_unix.go deleted file mode 100644 index 19fc63d65..000000000 --- a/vendor/github.com/docker/docker/api/common_unix.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows -// +build !windows - -package api // import "github.com/docker/docker/api" - -// MinVersion represents Minimum REST API version supported -const MinVersion = "1.12" diff --git a/vendor/github.com/docker/docker/api/common_windows.go b/vendor/github.com/docker/docker/api/common_windows.go deleted file mode 100644 index 590ba5479..000000000 --- a/vendor/github.com/docker/docker/api/common_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -package api // import "github.com/docker/docker/api" - -// MinVersion represents Minimum REST API version supported -// Technically the first daemon API version released on Windows is v1.25 in -// engine version 1.13. However, some clients are explicitly using downlevel -// APIs (e.g. docker-compose v2.1 file format) and that is just too restrictive. -// Hence also allowing 1.24 on Windows. -const MinVersion string = "1.24" diff --git a/vendor/github.com/docker/docker/api/swagger.yaml b/vendor/github.com/docker/docker/api/swagger.yaml index 7635b9f66..567939580 100644 --- a/vendor/github.com/docker/docker/api/swagger.yaml +++ b/vendor/github.com/docker/docker/api/swagger.yaml @@ -19,10 +19,10 @@ produces: consumes: - "application/json" - "text/plain" -basePath: "/v1.43" +basePath: "/v1.44" info: title: "Docker Engine API" - version: "1.43" + version: "1.44" x-logo: url: "https://docs.docker.com/assets/images/logo-docker-main.png" description: | @@ -55,8 +55,8 @@ info: the URL is not supported by the daemon, a HTTP `400 Bad Request` error message is returned. - If you omit the version-prefix, the current version of the API (v1.43) is used. - For example, calling `/info` is the same as calling `/v1.43/info`. Using the + If you omit the version-prefix, the current version of the API (v1.44) is used. + For example, calling `/info` is the same as calling `/v1.44/info`. Using the API without a version-prefix is deprecated and will be removed in a future release. Engine releases in the near future should support this version of the API, @@ -388,6 +388,16 @@ definitions: description: "Create mount point on host if missing" type: "boolean" default: false + ReadOnlyNonRecursive: + description: | + Make the mount non-recursively read-only, but still leave the mount recursive + (unless NonRecursive is set to true in conjunction). + type: "boolean" + default: false + ReadOnlyForceRecursive: + description: "Raise an error if the mount cannot be made recursively read-only." + type: "boolean" + default: false VolumeOptions: description: "Optional configuration for the `volume` type." type: "object" @@ -794,6 +804,12 @@ definitions: 1000000 (1 ms). 0 means inherit. type: "integer" format: "int64" + StartInterval: + description: | + The time to wait between checks in nanoseconds during the start period. + It should be 0 or at least 1000000 (1 ms). 0 means inherit. + type: "integer" + format: "int64" Health: description: | @@ -1297,7 +1313,10 @@ definitions: type: "boolean" x-nullable: true MacAddress: - description: "MAC address of the container." + description: | + MAC address of the container. + + Deprecated: this field is deprecated in API v1.44 and up. Use EndpointSettings.MacAddress instead. type: "string" x-nullable: true OnBuild: @@ -1347,16 +1366,16 @@ definitions: EndpointsConfig: description: | A mapping of network name to endpoint configuration for that network. + The endpoint configuration can be left empty to connect to that + network with no particular endpoint configuration. type: "object" additionalProperties: $ref: "#/definitions/EndpointSettings" example: # putting an example here, instead of using the example values from - # /definitions/EndpointSettings, because containers/create currently - # does not support attaching to multiple networks, so the example request - # would be confusing if it showed that multiple networks can be contained - # in the EndpointsConfig. - # TODO remove once we support multiple networks on container create (see https://github.com/moby/moby/blob/07e6b843594e061f82baa5fa23c2ff7d536c2a05/daemon/create.go#L323) + # /definitions/EndpointSettings, because EndpointSettings contains + # operational data returned when inspecting a container that we don't + # accept here. EndpointsConfig: isolated_nw: IPAMConfig: @@ -1365,19 +1384,22 @@ definitions: LinkLocalIPs: - "169.254.34.68" - "fe80::3468" + MacAddress: "02:42:ac:12:05:02" Links: - "container_1" - "container_2" Aliases: - "server_x" - "server_y" + database_nw: {} NetworkSettings: description: "NetworkSettings exposes the network settings in the API" type: "object" properties: Bridge: - description: Name of the network's bridge (for example, `docker0`). + description: | + Name of the default bridge interface when dockerd's --bridge flag is set. type: "string" example: "docker0" SandboxID: @@ -1387,34 +1409,40 @@ definitions: HairpinMode: description: | Indicates if hairpin NAT should be enabled on the virtual interface. + + Deprecated: This field is never set and will be removed in a future release. type: "boolean" example: false LinkLocalIPv6Address: - description: IPv6 unicast address using the link-local prefix. + description: | + IPv6 unicast address using the link-local prefix. + + Deprecated: This field is never set and will be removed in a future release. type: "string" - example: "fe80::42:acff:fe11:1" + example: "" LinkLocalIPv6PrefixLen: - description: Prefix length of the IPv6 unicast address. + description: | + Prefix length of the IPv6 unicast address. + + Deprecated: This field is never set and will be removed in a future release. type: "integer" - example: "64" + example: "" Ports: $ref: "#/definitions/PortMap" SandboxKey: - description: SandboxKey identifies the sandbox + description: SandboxKey is the full path of the netns handle type: "string" example: "/var/run/docker/netns/8ab54b426c38" - # TODO is SecondaryIPAddresses actually used? SecondaryIPAddresses: - description: "" + description: "Deprecated: This field is never set and will be removed in a future release." type: "array" items: $ref: "#/definitions/Address" x-nullable: true - # TODO is SecondaryIPv6Addresses actually used? SecondaryIPv6Addresses: - description: "" + description: "Deprecated: This field is never set and will be removed in a future release." type: "array" items: $ref: "#/definitions/Address" @@ -1723,10 +1751,15 @@ definitions: The ID of the container that was used to create the image. Depending on how the image was created, this field may be empty. + + **Deprecated**: this field is kept for backward compatibility, but + will be removed in API v1.45. type: "string" - x-nullable: false example: "65974bc86f1770ae4bff79f651ebdbce166ae9aada632ee3fa9af3a264911735" ContainerConfig: + description: | + **Deprecated**: this field is kept for backward compatibility, but + will be removed in API v1.45. $ref: "#/definitions/ContainerConfig" DockerVersion: description: | @@ -1781,13 +1814,7 @@ definitions: description: | Total size of the image including all layers it is composed of. - In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Images are now stored - self-contained, and no longer use a parent-chain, making this field - an equivalent of the Size field. - - > **Deprecated**: this field is kept for backward compatibility, but - > will be removed in API v1.44. + Deprecated: this field is omitted in API v1.44, but kept for backward compatibility. Use Size instead. type: "integer" format: "int64" example: 1239828 @@ -1829,6 +1856,7 @@ definitions: x-nullable: true ImageSummary: type: "object" + x-go-name: "Summary" required: - Id - ParentId @@ -1925,12 +1953,7 @@ definitions: description: |- Total size of the image including all layers it is composed of. - In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Images are now stored - self-contained, and no longer use a parent-chain, making this field - an equivalent of the Size field. - - Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. + Deprecated: this field is omitted in API v1.44, but kept for backward compatibility. Use Size instead. type: "integer" format: "int64" example: 172064416 @@ -2448,6 +2471,11 @@ definitions: example: - "container_1" - "container_2" + MacAddress: + description: | + MAC address for the endpoint on this network. The network driver might ignore this parameter. + type: "string" + example: "02:42:ac:11:00:04" Aliases: type: "array" items: @@ -2498,11 +2526,6 @@ definitions: type: "integer" format: "int64" example: 64 - MacAddress: - description: | - MAC address for the endpoint on this network. - type: "string" - example: "02:42:ac:11:00:04" DriverOpts: description: | DriverOpts is a mapping of driver options and values. These options @@ -2514,6 +2537,21 @@ definitions: example: com.example.some-label: "some-value" com.example.some-other-label: "some-other-value" + DNSNames: + description: | + List of all DNS names an endpoint has on a specific network. This + list is based on the container name, network aliases, container short + ID, and hostname. + + These DNS names are non-fully qualified but can contain several dots. + You can get fully qualified DNS names by appending `.`. + For instance, if container name is `my.ctr` and the network is named + `testnet`, `DNSNames` will contain `my.ctr` and the FQDN will be + `my.ctr.testnet`. + type: array + items: + type: string + example: ["foobar", "server_x", "server_y", "my.ctr"] EndpointIPAMConfig: description: | @@ -3011,8 +3049,6 @@ definitions: Name: "journald" - Type: "Log" Name: "json-file" - - Type: "Log" - Name: "logentries" - Type: "Log" Name: "splunk" - Type: "Log" @@ -3547,6 +3583,32 @@ definitions: Level: type: "string" description: "SELinux level label" + Seccomp: + type: "object" + description: "Options for configuring seccomp on the container" + properties: + Mode: + type: "string" + enum: + - "default" + - "unconfined" + - "custom" + Profile: + description: "The custom seccomp profile as a json object" + type: "string" + AppArmor: + type: "object" + description: "Options for configuring AppArmor on the container" + properties: + Mode: + type: "string" + enum: + - "default" + - "disabled" + NoNewPrivileges: + type: "boolean" + description: "Configuration of the no_new_privs bit in the container" + TTY: description: "Whether a pseudo-TTY should be allocated." type: "boolean" @@ -3941,6 +4003,44 @@ definitions: - "remove" - "orphaned" + ContainerStatus: + type: "object" + description: "represents the status of a container." + properties: + ContainerID: + type: "string" + PID: + type: "integer" + ExitCode: + type: "integer" + + PortStatus: + type: "object" + description: "represents the port status of a task's host ports whose service has published host ports" + properties: + Ports: + type: "array" + items: + $ref: "#/definitions/EndpointPortConfig" + + TaskStatus: + type: "object" + description: "represents the status of a task." + properties: + Timestamp: + type: "string" + format: "dateTime" + State: + $ref: "#/definitions/TaskState" + Message: + type: "string" + Err: + type: "string" + ContainerStatus: + $ref: "#/definitions/ContainerStatus" + PortStatus: + $ref: "#/definitions/PortStatus" + Task: type: "object" properties: @@ -3976,26 +4076,7 @@ definitions: AssignedGenericResources: $ref: "#/definitions/GenericResources" Status: - type: "object" - properties: - Timestamp: - type: "string" - format: "dateTime" - State: - $ref: "#/definitions/TaskState" - Message: - type: "string" - Err: - type: "string" - ContainerStatus: - type: "object" - properties: - ContainerID: - type: "string" - PID: - type: "integer" - ExitCode: - type: "integer" + $ref: "#/definitions/TaskStatus" DesiredState: $ref: "#/definitions/TaskState" JobIteration: @@ -4211,7 +4292,10 @@ definitions: - "stop-first" - "start-first" Networks: - description: "Specifies which networks the service should attach to." + description: | + Specifies which networks the service should attach to. + + Deprecated: This field is deprecated since v1.44. The Networks field in TaskSpec should be used instead. type: "array" items: $ref: "#/definitions/NetworkAttachmentConfig" @@ -4445,6 +4529,7 @@ definitions: ImageDeleteResponseItem: type: "object" + x-go-name: "DeleteResponse" properties: Untagged: description: "The image ID of an image that was untagged" @@ -4453,6 +4538,29 @@ definitions: description: "The image ID of an image that was deleted" type: "string" + ServiceCreateResponse: + type: "object" + description: | + contains the information returned to a client on the + creation of a new service. + properties: + ID: + description: "The ID of the created service." + type: "string" + x-nullable: false + example: "ak7w3gjqoa3kuz8xcpnyy0pvl" + Warnings: + description: | + Optional warning message. + + FIXME(thaJeztah): this should have "omitempty" in the generated type. + type: "array" + x-nullable: true + items: + type: "string" + example: + - "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" + ServiceUpdateResponse: type: "object" properties: @@ -4462,7 +4570,8 @@ definitions: items: type: "string" example: - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" + Warnings: + - "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" ContainerSummary: type: "object" @@ -5296,7 +5405,25 @@ definitions: - "WARNING: No memory limit support" - "WARNING: bridge-nf-call-iptables is disabled" - "WARNING: bridge-nf-call-ip6tables is disabled" + CDISpecDirs: + description: | + List of directories where (Container Device Interface) CDI + specifications are located. + + These specifications define vendor-specific modifications to an OCI + runtime specification for a container being created. + An empty list indicates that CDI device injection is disabled. + + Note that since using CDI device injection requires the daemon to have + experimental enabled. For non-experimental daemons an empty list will + always be returned. + type: "array" + items: + type: "string" + example: + - "/etc/cdi" + - "/var/run/cdi" # PluginsInfo is a temp struct holding Plugins name # registered with docker daemon. It is used by Info struct @@ -5334,7 +5461,7 @@ definitions: type: "array" items: type: "string" - example: ["awslogs", "fluentd", "gcplogs", "gelf", "journald", "json-file", "logentries", "splunk", "syslog"] + example: ["awslogs", "fluentd", "gcplogs", "gelf", "journald", "json-file", "splunk", "syslog"] RegistryServiceConfig: @@ -5532,6 +5659,28 @@ definitions: items: type: "string" example: ["--debug", "--systemd-cgroup=false"] + status: + description: | + Information specific to the runtime. + + While this API specification does not define data provided by runtimes, + the following well-known properties may be provided by runtimes: + + `org.opencontainers.runtime-spec.features`: features structure as defined + in the [OCI Runtime Specification](https://github.com/opencontainers/runtime-spec/blob/main/features.md), + in a JSON string representation. + +


      + + > **Note**: The information returned in this field, including the + > formatting of values and labels, should not be considered stable, + > and may change without notice. + type: "object" + x-nullable: true + additionalProperties: + type: "string" + example: + "org.opencontainers.runtime-spec.features": "{\"ociVersionMin\":\"1.0.0\",\"ociVersionMax\":\"1.1.0\",\"...\":\"...\"}" Commit: description: | @@ -6416,6 +6565,7 @@ paths: Aliases: - "server_x" - "server_y" + database_nw: {} required: true responses: @@ -6563,7 +6713,7 @@ paths: StopSignal: "SIGTERM" StopTimeout: 10 Created: "2015-01-06T15:47:31.485331387Z" - Driver: "devicemapper" + Driver: "overlay2" ExecIDs: - "b35395de42bc8abd327f9dd65d913b9ba28c74d2f0734eeeae84fa1c616a0fca" - "3fc1232e5cd20c8de182ed81178503dc6437f4e7ef12b52cc5e8de020652f1c4" @@ -7994,6 +8144,7 @@ paths: - `label=key` or `label="key=value"` of an image label - `reference`=(`[:]`) - `since`=(`[:]`, `` or ``) + - `until=` type: "string" - name: "shared-size" in: "query" @@ -8245,7 +8396,7 @@ paths: /images/create: post: summary: "Create an image" - description: "Create an image by either pulling it from a registry or importing it." + description: "Pull or import an image." operationId: "ImageCreate" consumes: - "text/plain" @@ -8596,28 +8747,36 @@ paths: is_official: type: "boolean" is_automated: + description: | + Whether this repository has automated builds enabled. + +


      + + > **Deprecated**: This field is deprecated and will always + > be "false" in future. type: "boolean" + example: false name: type: "string" star_count: type: "integer" examples: application/json: - - description: "" - is_official: false + - description: "A minimal Docker image based on Alpine Linux with a complete package index and only 5 MB in size!" + is_official: true is_automated: false - name: "wma55/u1210sshd" - star_count: 0 - - description: "" - is_official: false + name: "alpine" + star_count: 10093 + - description: "Busybox base image." + is_official: true is_automated: false - name: "jdswinbank/sshd" - star_count: 0 - - description: "" - is_official: false + name: "Busybox base image." + star_count: 3037 + - description: "The PostgreSQL object-relational database system provides reliability and data integrity." + is_official: true is_automated: false - name: "vgauthier/sshd" - star_count: 0 + name: "postgres" + star_count: 12408 500: description: "Server error" schema: @@ -8637,9 +8796,13 @@ paths: description: | A JSON encoded value of the filters (a `map[string][]string`) to process on the images list. Available filters: - - `is-automated=(true|false)` + - `is-automated=(true|false)` (deprecated, see below) - `is-official=(true|false)` - `stars=` Matches images that has at least 'number' stars. + + The `is-automated` filter is deprecated. The `is_automated` field has + been deprecated by Docker Hub's search API. Consequently, searching + for `is-automated=true` will yield no results. type: "string" tags: ["Image"] /images/prune: @@ -9032,7 +9195,6 @@ paths: Created: 1466724217 Size: 1092588 SharedSize: 0 - VirtualSize: 1092588 Labels: {} Containers: 1 Containers: @@ -9895,6 +10057,10 @@ paths: example: Id: "22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30" Warning: "" + 400: + description: "bad parameter" + schema: + $ref: "#/definitions/ErrorResponse" 403: description: | Forbidden operation. This happens when trying to create a network named after a pre-defined network, @@ -9924,13 +10090,7 @@ paths: type: "string" CheckDuplicate: description: | - Check for networks with duplicate names. Since Network is - primarily keyed based on a random ID and not on the name, and - network name is strictly a user-friendly alias to the network - which is uniquely identified using ID, there is no guaranteed - way to check for duplicates. CheckDuplicate is there to provide - a best effort checking of any networks which has the same name - but it is not guaranteed to catch all name collisions. + Deprecated: CheckDuplicate is now always enabled. type: "boolean" Driver: description: "Name of the network driver plugin to use." @@ -9998,14 +10158,19 @@ paths: /networks/{id}/connect: post: summary: "Connect a container to a network" + description: "The network must be either a local-scoped network or a swarm-scoped network with the `attachable` option set. A network cannot be re-attached to a running container" operationId: "NetworkConnect" consumes: - "application/json" responses: 200: description: "No error" + 400: + description: "bad parameter" + schema: + $ref: "#/definitions/ErrorResponse" 403: - description: "Operation not supported for swarm scoped networks" + description: "Operation forbidden" schema: $ref: "#/definitions/ErrorResponse" 404: @@ -10040,6 +10205,7 @@ paths: IPAMConfig: IPv4Address: "172.24.56.89" IPv6Address: "2001:db8::5689" + MacAddress: "02:42:ac:12:05:02" tags: ["Network"] /networks/{id}/disconnect: @@ -11033,18 +11199,7 @@ paths: 201: description: "no error" schema: - type: "object" - title: "ServiceCreateResponse" - properties: - ID: - description: "The ID of the created service." - type: "string" - Warning: - description: "Optional warning message" - type: "string" - example: - ID: "ak7w3gjqoa3kuz8xcpnyy0pvl" - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" + $ref: "#/definitions/ServiceCreateResponse" 400: description: "bad parameter" schema: diff --git a/vendor/github.com/docker/docker/api/types/auth.go b/vendor/github.com/docker/docker/api/types/auth.go deleted file mode 100644 index 9ee329a2f..000000000 --- a/vendor/github.com/docker/docker/api/types/auth.go +++ /dev/null @@ -1,7 +0,0 @@ -package types // import "github.com/docker/docker/api/types" -import "github.com/docker/docker/api/types/registry" - -// AuthConfig contains authorization information for connecting to a Registry. -// -// Deprecated: use github.com/docker/docker/api/types/registry.AuthConfig -type AuthConfig = registry.AuthConfig diff --git a/vendor/github.com/docker/docker/api/types/checkpoint/list.go b/vendor/github.com/docker/docker/api/types/checkpoint/list.go new file mode 100644 index 000000000..94a9c0a47 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/checkpoint/list.go @@ -0,0 +1,7 @@ +package checkpoint + +// Summary represents the details of a checkpoint when listing endpoints. +type Summary struct { + // Name is the name of the checkpoint. + Name string +} diff --git a/vendor/github.com/docker/docker/api/types/checkpoint/options.go b/vendor/github.com/docker/docker/api/types/checkpoint/options.go new file mode 100644 index 000000000..9477458c2 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/checkpoint/options.go @@ -0,0 +1,19 @@ +package checkpoint + +// CreateOptions holds parameters to create a checkpoint from a container. +type CreateOptions struct { + CheckpointID string + CheckpointDir string + Exit bool +} + +// ListOptions holds parameters to list checkpoints for a container. +type ListOptions struct { + CheckpointDir string +} + +// DeleteOptions holds parameters to delete a checkpoint from a container. +type DeleteOptions struct { + CheckpointID string + CheckpointDir string +} diff --git a/vendor/github.com/docker/docker/api/types/client.go b/vendor/github.com/docker/docker/api/types/client.go index d8cd30613..24b00a275 100644 --- a/vendor/github.com/docker/docker/api/types/client.go +++ b/vendor/github.com/docker/docker/api/types/client.go @@ -11,44 +11,6 @@ import ( units "github.com/docker/go-units" ) -// CheckpointCreateOptions holds parameters to create a checkpoint from a container -type CheckpointCreateOptions struct { - CheckpointID string - CheckpointDir string - Exit bool -} - -// CheckpointListOptions holds parameters to list checkpoints for a container -type CheckpointListOptions struct { - CheckpointDir string -} - -// CheckpointDeleteOptions holds parameters to delete a checkpoint from a container -type CheckpointDeleteOptions struct { - CheckpointID string - CheckpointDir string -} - -// ContainerAttachOptions holds parameters to attach to a container. -type ContainerAttachOptions struct { - Stream bool - Stdin bool - Stdout bool - Stderr bool - DetachKeys string - Logs bool -} - -// ContainerCommitOptions holds parameters to commit changes into a container. -type ContainerCommitOptions struct { - Reference string - Comment string - Author string - Changes []string - Pause bool - Config *container.Config -} - // ContainerExecInspect holds information returned by exec inspect. type ContainerExecInspect struct { ExecID string `json:"ID"` @@ -58,42 +20,6 @@ type ContainerExecInspect struct { Pid int } -// ContainerListOptions holds parameters to list containers with. -type ContainerListOptions struct { - Size bool - All bool - Latest bool - Since string - Before string - Limit int - Filters filters.Args -} - -// ContainerLogsOptions holds parameters to filter logs with. -type ContainerLogsOptions struct { - ShowStdout bool - ShowStderr bool - Since string - Until string - Timestamps bool - Follow bool - Tail string - Details bool -} - -// ContainerRemoveOptions holds parameters to remove containers. -type ContainerRemoveOptions struct { - RemoveVolumes bool - RemoveLinks bool - Force bool -} - -// ContainerStartOptions holds parameters to start containers. -type ContainerStartOptions struct { - CheckpointID string - CheckpointDir string -} - // CopyToContainerOptions holds information // about files to copy into a container type CopyToContainerOptions struct { @@ -307,14 +233,6 @@ type ImageSearchOptions struct { Limit int } -// ResizeOptions holds parameters to resize a tty. -// It can be used to resize container ttys and -// exec process ttys too. -type ResizeOptions struct { - Height uint - Width uint -} - // NodeListOptions holds parameters to list nodes with. type NodeListOptions struct { Filters filters.Args @@ -340,15 +258,6 @@ type ServiceCreateOptions struct { QueryRegistry bool } -// ServiceCreateResponse contains the information returned to a client -// on the creation of a new service. -type ServiceCreateResponse struct { - // ID is the ID of the created service. - ID string - // Warnings is a set of non-fatal warning messages to pass on to the user. - Warnings []string `json:",omitempty"` -} - // Values for RegistryAuthFrom in ServiceUpdateOptions const ( RegistryAuthFromSpec = "spec" diff --git a/vendor/github.com/docker/docker/api/types/configs.go b/vendor/github.com/docker/docker/api/types/configs.go index 7d5930bbe..945b6efad 100644 --- a/vendor/github.com/docker/docker/api/types/configs.go +++ b/vendor/github.com/docker/docker/api/types/configs.go @@ -1,32 +1,5 @@ package types // import "github.com/docker/docker/api/types" -import ( - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// configs holds structs used for internal communication between the -// frontend (such as an http server) and the backend (such as the -// docker daemon). - -// ContainerCreateConfig is the parameter set to ContainerCreate() -type ContainerCreateConfig struct { - Name string - Config *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig - Platform *ocispec.Platform - AdjustCPUShares bool -} - -// ContainerRmConfig holds arguments for the container remove -// operation. This struct is used to tell the backend what operations -// to perform. -type ContainerRmConfig struct { - ForceRemove, RemoveVolume, RemoveLink bool -} - // ExecConfig is a small subset of the Config struct that holds the configuration // for the exec feature of docker. type ExecConfig struct { @@ -43,25 +16,3 @@ type ExecConfig struct { WorkingDir string // Working directory Cmd []string // Execution commands and args } - -// PluginRmConfig holds arguments for plugin remove. -type PluginRmConfig struct { - ForceRemove bool -} - -// PluginEnableConfig holds arguments for plugin enable -type PluginEnableConfig struct { - Timeout int -} - -// PluginDisableConfig holds arguments for plugin disable. -type PluginDisableConfig struct { - ForceDisable bool -} - -// NetworkListConfig stores the options available for listing networks -type NetworkListConfig struct { - // TODO(@cpuguy83): naming is hard, this is pulled from what was being used in the router before moving here - Detailed bool - Verbose bool -} diff --git a/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go b/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go deleted file mode 100644 index 6b4b47390..000000000 --- a/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go +++ /dev/null @@ -1,6 +0,0 @@ -package container - -// ContainerChangeResponseItem change item in response to ContainerChanges operation -// -// Deprecated: use [FilesystemChange]. -type ContainerChangeResponseItem = FilesystemChange diff --git a/vendor/github.com/docker/docker/api/types/container/config.go b/vendor/github.com/docker/docker/api/types/container/config.go index 077583e66..be41d6315 100644 --- a/vendor/github.com/docker/docker/api/types/container/config.go +++ b/vendor/github.com/docker/docker/api/types/container/config.go @@ -5,6 +5,7 @@ import ( "time" "github.com/docker/docker/api/types/strslice" + dockerspec "github.com/docker/docker/image/spec/specs-go/v1" "github.com/docker/go-connections/nat" ) @@ -33,25 +34,7 @@ type StopOptions struct { } // HealthConfig holds configuration settings for the HEALTHCHECK feature. -type HealthConfig struct { - // Test is the test to perform to check that the container is healthy. - // An empty slice means to inherit the default. - // The options are: - // {} : inherit healthcheck - // {"NONE"} : disable healthcheck - // {"CMD", args...} : exec arguments directly - // {"CMD-SHELL", command} : run command with system's default shell - Test []string `json:",omitempty"` - - // Zero means to inherit. Durations are expressed as integer nanoseconds. - Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. - Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. - StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. - - // Retries is the number of consecutive failures needed to consider a container as unhealthy. - // Zero means inherit. - Retries int `json:",omitempty"` -} +type HealthConfig = dockerspec.HealthcheckConfig // ExecStartOptions holds the options to start container's exec. type ExecStartOptions struct { @@ -87,10 +70,13 @@ type Config struct { WorkingDir string // Current directory (PWD) in the command will be launched Entrypoint strslice.StrSlice // Entrypoint to run when starting the container NetworkDisabled bool `json:",omitempty"` // Is network disabled - MacAddress string `json:",omitempty"` // Mac Address of the container - OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile - Labels map[string]string // List of labels set to this container - StopSignal string `json:",omitempty"` // Signal to stop a container - StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container - Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT + // Mac Address of the container. + // + // Deprecated: this field is deprecated since API v1.44. Use EndpointSettings.MacAddress instead. + MacAddress string `json:",omitempty"` + OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile + Labels map[string]string // List of labels set to this container + StopSignal string `json:",omitempty"` // Signal to stop a container + StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container + Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT } diff --git a/vendor/github.com/docker/docker/api/types/container/errors.go b/vendor/github.com/docker/docker/api/types/container/errors.go new file mode 100644 index 000000000..32c978037 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/errors.go @@ -0,0 +1,9 @@ +package container + +type errInvalidParameter struct{ error } + +func (e *errInvalidParameter) InvalidParameter() {} + +func (e *errInvalidParameter) Unwrap() error { + return e.error +} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig.go b/vendor/github.com/docker/docker/api/types/container/hostconfig.go index d4e6f5537..efb96266e 100644 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig.go @@ -1,10 +1,12 @@ package container // import "github.com/docker/docker/api/types/container" import ( + "fmt" "strings" "github.com/docker/docker/api/types/blkiodev" "github.com/docker/docker/api/types/mount" + "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/strslice" "github.com/docker/go-connections/nat" units "github.com/docker/go-units" @@ -132,12 +134,12 @@ type NetworkMode string // IsNone indicates whether container isn't using a network stack. func (n NetworkMode) IsNone() bool { - return n == "none" + return n == network.NetworkNone } // IsDefault indicates whether container uses the default network stack. func (n NetworkMode) IsDefault() bool { - return n == "default" + return n == network.NetworkDefault } // IsPrivate indicates whether container uses its private network stack. @@ -271,33 +273,42 @@ type DeviceMapping struct { // RestartPolicy represents the restart policies of the container. type RestartPolicy struct { - Name string + Name RestartPolicyMode MaximumRetryCount int } +type RestartPolicyMode string + +const ( + RestartPolicyDisabled RestartPolicyMode = "no" + RestartPolicyAlways RestartPolicyMode = "always" + RestartPolicyOnFailure RestartPolicyMode = "on-failure" + RestartPolicyUnlessStopped RestartPolicyMode = "unless-stopped" +) + // IsNone indicates whether the container has the "no" restart policy. // This means the container will not automatically restart when exiting. func (rp *RestartPolicy) IsNone() bool { - return rp.Name == "no" || rp.Name == "" + return rp.Name == RestartPolicyDisabled || rp.Name == "" } // IsAlways indicates whether the container has the "always" restart policy. // This means the container will automatically restart regardless of the exit status. func (rp *RestartPolicy) IsAlways() bool { - return rp.Name == "always" + return rp.Name == RestartPolicyAlways } // IsOnFailure indicates whether the container has the "on-failure" restart policy. // This means the container will automatically restart of exiting with a non-zero exit status. func (rp *RestartPolicy) IsOnFailure() bool { - return rp.Name == "on-failure" + return rp.Name == RestartPolicyOnFailure } // IsUnlessStopped indicates whether the container has the // "unless-stopped" restart policy. This means the container will // automatically restart unless user has put it to stopped state. func (rp *RestartPolicy) IsUnlessStopped() bool { - return rp.Name == "unless-stopped" + return rp.Name == RestartPolicyUnlessStopped } // IsSame compares two RestartPolicy to see if they are the same @@ -305,6 +316,33 @@ func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool { return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount } +// ValidateRestartPolicy validates the given RestartPolicy. +func ValidateRestartPolicy(policy RestartPolicy) error { + switch policy.Name { + case RestartPolicyAlways, RestartPolicyUnlessStopped, RestartPolicyDisabled: + if policy.MaximumRetryCount != 0 { + msg := "invalid restart policy: maximum retry count can only be used with 'on-failure'" + if policy.MaximumRetryCount < 0 { + msg += " and cannot be negative" + } + return &errInvalidParameter{fmt.Errorf(msg)} + } + return nil + case RestartPolicyOnFailure: + if policy.MaximumRetryCount < 0 { + return &errInvalidParameter{fmt.Errorf("invalid restart policy: maximum retry count cannot be negative")} + } + return nil + case "": + // Versions before v25.0.0 created an empty restart-policy "name" as + // default. Allow an empty name with "any" MaximumRetryCount for + // backward-compatibility. + return nil + default: + return &errInvalidParameter{fmt.Errorf("invalid restart policy: unknown policy '%s'; use one of '%s', '%s', '%s', or '%s'", policy.Name, RestartPolicyDisabled, RestartPolicyAlways, RestartPolicyOnFailure, RestartPolicyUnlessStopped)} + } +} + // LogMode is a type to define the available modes for logging // These modes affect how logs are handled when log messages start piling up. type LogMode string diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go index 24c4fa8d9..421329237 100644 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go @@ -1,8 +1,9 @@ //go:build !windows -// +build !windows package container // import "github.com/docker/docker/api/types/container" +import "github.com/docker/docker/api/types/network" + // IsValid indicates if an isolation technology is valid func (i Isolation) IsValid() bool { return i.IsDefault() @@ -11,15 +12,15 @@ func (i Isolation) IsValid() bool { // NetworkName returns the name of the network stack. func (n NetworkMode) NetworkName() string { if n.IsBridge() { - return "bridge" + return network.NetworkBridge } else if n.IsHost() { - return "host" + return network.NetworkHost } else if n.IsContainer() { return "container" } else if n.IsNone() { - return "none" + return network.NetworkNone } else if n.IsDefault() { - return "default" + return network.NetworkDefault } else if n.IsUserDefined() { return n.UserDefined() } @@ -28,12 +29,12 @@ func (n NetworkMode) NetworkName() string { // IsBridge indicates whether container uses the bridge network stack func (n NetworkMode) IsBridge() bool { - return n == "bridge" + return n == network.NetworkBridge } // IsHost indicates whether container uses the host network stack. func (n NetworkMode) IsHost() bool { - return n == "host" + return n == network.NetworkHost } // IsUserDefined indicates user-created network diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go index 99f803a5b..154667f4f 100644 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go @@ -1,9 +1,11 @@ package container // import "github.com/docker/docker/api/types/container" +import "github.com/docker/docker/api/types/network" + // IsBridge indicates whether container uses the bridge network stack // in windows it is given the name NAT func (n NetworkMode) IsBridge() bool { - return n == "nat" + return n == network.NetworkNat } // IsHost indicates whether container uses the host network stack. @@ -25,11 +27,11 @@ func (i Isolation) IsValid() bool { // NetworkName returns the name of the network stack. func (n NetworkMode) NetworkName() string { if n.IsDefault() { - return "default" + return network.NetworkDefault } else if n.IsBridge() { - return "nat" + return network.NetworkNat } else if n.IsNone() { - return "none" + return network.NetworkNone } else if n.IsContainer() { return "container" } else if n.IsUserDefined() { diff --git a/vendor/github.com/docker/docker/api/types/container/options.go b/vendor/github.com/docker/docker/api/types/container/options.go new file mode 100644 index 000000000..7a2300576 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/options.go @@ -0,0 +1,67 @@ +package container + +import "github.com/docker/docker/api/types/filters" + +// ResizeOptions holds parameters to resize a TTY. +// It can be used to resize container TTYs and +// exec process TTYs too. +type ResizeOptions struct { + Height uint + Width uint +} + +// AttachOptions holds parameters to attach to a container. +type AttachOptions struct { + Stream bool + Stdin bool + Stdout bool + Stderr bool + DetachKeys string + Logs bool +} + +// CommitOptions holds parameters to commit changes into a container. +type CommitOptions struct { + Reference string + Comment string + Author string + Changes []string + Pause bool + Config *Config +} + +// RemoveOptions holds parameters to remove containers. +type RemoveOptions struct { + RemoveVolumes bool + RemoveLinks bool + Force bool +} + +// StartOptions holds parameters to start containers. +type StartOptions struct { + CheckpointID string + CheckpointDir string +} + +// ListOptions holds parameters to list containers with. +type ListOptions struct { + Size bool + All bool + Latest bool + Since string + Before string + Limit int + Filters filters.Args +} + +// LogsOptions holds parameters to filter logs with. +type LogsOptions struct { + ShowStdout bool + ShowStderr bool + Since string + Until string + Timestamps bool + Follow bool + Tail string + Details bool +} diff --git a/vendor/github.com/docker/docker/api/types/events/events.go b/vendor/github.com/docker/docker/api/types/events/events.go index 9fe07e26f..6dbcd9223 100644 --- a/vendor/github.com/docker/docker/api/types/events/events.go +++ b/vendor/github.com/docker/docker/api/types/events/events.go @@ -1,7 +1,7 @@ package events // import "github.com/docker/docker/api/types/events" // Type is used for event-types. -type Type = string +type Type string // List of known event types. const ( @@ -18,6 +18,86 @@ const ( VolumeEventType Type = "volume" // VolumeEventType is the event type that volumes generate. ) +// Action is used for event-actions. +type Action string + +const ( + ActionCreate Action = "create" + ActionStart Action = "start" + ActionRestart Action = "restart" + ActionStop Action = "stop" + ActionCheckpoint Action = "checkpoint" + ActionPause Action = "pause" + ActionUnPause Action = "unpause" + ActionAttach Action = "attach" + ActionDetach Action = "detach" + ActionResize Action = "resize" + ActionUpdate Action = "update" + ActionRename Action = "rename" + ActionKill Action = "kill" + ActionDie Action = "die" + ActionOOM Action = "oom" + ActionDestroy Action = "destroy" + ActionRemove Action = "remove" + ActionCommit Action = "commit" + ActionTop Action = "top" + ActionCopy Action = "copy" + ActionArchivePath Action = "archive-path" + ActionExtractToDir Action = "extract-to-dir" + ActionExport Action = "export" + ActionImport Action = "import" + ActionSave Action = "save" + ActionLoad Action = "load" + ActionTag Action = "tag" + ActionUnTag Action = "untag" + ActionPush Action = "push" + ActionPull Action = "pull" + ActionPrune Action = "prune" + ActionDelete Action = "delete" + ActionEnable Action = "enable" + ActionDisable Action = "disable" + ActionConnect Action = "connect" + ActionDisconnect Action = "disconnect" + ActionReload Action = "reload" + ActionMount Action = "mount" + ActionUnmount Action = "unmount" + + // ActionExecCreate is the prefix used for exec_create events. These + // event-actions are commonly followed by a colon and space (": "), + // and the command that's defined for the exec, for example: + // + // exec_create: /bin/sh -c 'echo hello' + // + // This is far from ideal; it's a compromise to allow filtering and + // to preserve backward-compatibility. + ActionExecCreate Action = "exec_create" + // ActionExecStart is the prefix used for exec_create events. These + // event-actions are commonly followed by a colon and space (": "), + // and the command that's defined for the exec, for example: + // + // exec_start: /bin/sh -c 'echo hello' + // + // This is far from ideal; it's a compromise to allow filtering and + // to preserve backward-compatibility. + ActionExecStart Action = "exec_start" + ActionExecDie Action = "exec_die" + ActionExecDetach Action = "exec_detach" + + // ActionHealthStatus is the prefix to use for health_status events. + // + // Health-status events can either have a pre-defined status, in which + // case the "health_status" action is followed by a colon, or can be + // "free-form", in which case they're followed by the output of the + // health-check output. + // + // This is far form ideal, and a compromise to allow filtering, and + // to preserve backward-compatibility. + ActionHealthStatus Action = "health_status" + ActionHealthStatusRunning Action = "health_status: running" + ActionHealthStatusHealthy Action = "health_status: healthy" + ActionHealthStatusUnhealthy Action = "health_status: unhealthy" +) + // Actor describes something that generates events, // like a container, or a network, or a volume. // It has a defined name and a set of attributes. @@ -37,7 +117,7 @@ type Message struct { From string `json:"from,omitempty"` // Deprecated: use Actor.Attributes["image"] instead. Type Type - Action string + Action Action Actor Actor // Engine events are local scope. Cluster events are swarm scope. Scope string `json:"scope,omitempty"` diff --git a/vendor/github.com/docker/docker/api/types/image/delete_response.go b/vendor/github.com/docker/docker/api/types/image/delete_response.go new file mode 100644 index 000000000..998620dc6 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/image/delete_response.go @@ -0,0 +1,15 @@ +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// DeleteResponse delete response +// swagger:model DeleteResponse +type DeleteResponse struct { + + // The image ID of an image that was deleted + Deleted string `json:"Deleted,omitempty"` + + // The image ID of an image that was untagged + Untagged string `json:"Untagged,omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/image/image.go b/vendor/github.com/docker/docker/api/types/image/image.go new file mode 100644 index 000000000..167df28c7 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/image/image.go @@ -0,0 +1,9 @@ +package image + +import "time" + +// Metadata contains engine-local data about the image. +type Metadata struct { + // LastTagTime is the date and time at which the image was last tagged. + LastTagTime time.Time `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/image/summary.go b/vendor/github.com/docker/docker/api/types/image/summary.go new file mode 100644 index 000000000..f1e3e2ef0 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/image/summary.go @@ -0,0 +1,89 @@ +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// Summary summary +// swagger:model Summary +type Summary struct { + + // Number of containers using this image. Includes both stopped and running + // containers. + // + // This size is not calculated by default, and depends on which API endpoint + // is used. `-1` indicates that the value has not been set / calculated. + // + // Required: true + Containers int64 `json:"Containers"` + + // Date and time at which the image was created as a Unix timestamp + // (number of seconds sinds EPOCH). + // + // Required: true + Created int64 `json:"Created"` + + // ID is the content-addressable ID of an image. + // + // This identifier is a content-addressable digest calculated from the + // image's configuration (which includes the digests of layers used by + // the image). + // + // Note that this digest differs from the `RepoDigests` below, which + // holds digests of image manifests that reference the image. + // + // Required: true + ID string `json:"Id"` + + // User-defined key/value metadata. + // Required: true + Labels map[string]string `json:"Labels"` + + // ID of the parent image. + // + // Depending on how the image was created, this field may be empty and + // is only set for images that were built/created locally. This field + // is empty if the image was pulled from an image registry. + // + // Required: true + ParentID string `json:"ParentId"` + + // List of content-addressable digests of locally available image manifests + // that the image is referenced from. Multiple manifests can refer to the + // same image. + // + // These digests are usually only available if the image was either pulled + // from a registry, or if the image was pushed to a registry, which is when + // the manifest is generated and its digest calculated. + // + // Required: true + RepoDigests []string `json:"RepoDigests"` + + // List of image names/tags in the local image cache that reference this + // image. + // + // Multiple image tags can refer to the same image, and this list may be + // empty if no tags reference the image, in which case the image is + // "untagged", in which case it can still be referenced by its ID. + // + // Required: true + RepoTags []string `json:"RepoTags"` + + // Total size of image layers that are shared between this image and other + // images. + // + // This size is not calculated by default. `-1` indicates that the value + // has not been set / calculated. + // + // Required: true + SharedSize int64 `json:"SharedSize"` + + // Total size of the image including all layers it is composed of. + // + // Required: true + Size int64 `json:"Size"` + + // Total size of the image including all layers it is composed of. + // + // Deprecated: this field is omitted in API v1.44, but kept for backward compatibility. Use Size instead. + VirtualSize int64 `json:"VirtualSize,omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go b/vendor/github.com/docker/docker/api/types/image_delete_response_item.go deleted file mode 100644 index b9a65a0d8..000000000 --- a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageDeleteResponseItem image delete response item -// swagger:model ImageDeleteResponseItem -type ImageDeleteResponseItem struct { - - // The image ID of an image that was deleted - Deleted string `json:"Deleted,omitempty"` - - // The image ID of an image that was untagged - Untagged string `json:"Untagged,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/image_summary.go b/vendor/github.com/docker/docker/api/types/image_summary.go deleted file mode 100644 index 0f6f14484..000000000 --- a/vendor/github.com/docker/docker/api/types/image_summary.go +++ /dev/null @@ -1,94 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageSummary image summary -// swagger:model ImageSummary -type ImageSummary struct { - - // Number of containers using this image. Includes both stopped and running - // containers. - // - // This size is not calculated by default, and depends on which API endpoint - // is used. `-1` indicates that the value has not been set / calculated. - // - // Required: true - Containers int64 `json:"Containers"` - - // Date and time at which the image was created as a Unix timestamp - // (number of seconds sinds EPOCH). - // - // Required: true - Created int64 `json:"Created"` - - // ID is the content-addressable ID of an image. - // - // This identifier is a content-addressable digest calculated from the - // image's configuration (which includes the digests of layers used by - // the image). - // - // Note that this digest differs from the `RepoDigests` below, which - // holds digests of image manifests that reference the image. - // - // Required: true - ID string `json:"Id"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // ID of the parent image. - // - // Depending on how the image was created, this field may be empty and - // is only set for images that were built/created locally. This field - // is empty if the image was pulled from an image registry. - // - // Required: true - ParentID string `json:"ParentId"` - - // List of content-addressable digests of locally available image manifests - // that the image is referenced from. Multiple manifests can refer to the - // same image. - // - // These digests are usually only available if the image was either pulled - // from a registry, or if the image was pushed to a registry, which is when - // the manifest is generated and its digest calculated. - // - // Required: true - RepoDigests []string `json:"RepoDigests"` - - // List of image names/tags in the local image cache that reference this - // image. - // - // Multiple image tags can refer to the same image, and this list may be - // empty if no tags reference the image, in which case the image is - // "untagged", in which case it can still be referenced by its ID. - // - // Required: true - RepoTags []string `json:"RepoTags"` - - // Total size of image layers that are shared between this image and other - // images. - // - // This size is not calculated by default. `-1` indicates that the value - // has not been set / calculated. - // - // Required: true - SharedSize int64 `json:"SharedSize"` - - // Total size of the image including all layers it is composed of. - // - // Required: true - Size int64 `json:"Size"` - - // Total size of the image including all layers it is composed of. - // - // In versions of Docker before v1.10, this field was calculated from - // the image itself and all of its parent images. Images are now stored - // self-contained, and no longer use a parent-chain, making this field - // an equivalent of the Size field. - // - // Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. - VirtualSize int64 `json:"VirtualSize,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/mount/mount.go b/vendor/github.com/docker/docker/api/types/mount/mount.go index ac4ce6223..57edf2ef1 100644 --- a/vendor/github.com/docker/docker/api/types/mount/mount.go +++ b/vendor/github.com/docker/docker/api/types/mount/mount.go @@ -29,7 +29,7 @@ type Mount struct { // Source is not supported for tmpfs (must be an empty value) Source string `json:",omitempty"` Target string `json:",omitempty"` - ReadOnly bool `json:",omitempty"` + ReadOnly bool `json:",omitempty"` // attempts recursive read-only if possible Consistency Consistency `json:",omitempty"` BindOptions *BindOptions `json:",omitempty"` @@ -85,6 +85,11 @@ type BindOptions struct { Propagation Propagation `json:",omitempty"` NonRecursive bool `json:",omitempty"` CreateMountpoint bool `json:",omitempty"` + // ReadOnlyNonRecursive makes the mount non-recursively read-only, but still leaves the mount recursive + // (unless NonRecursive is set to true in conjunction). + ReadOnlyNonRecursive bool `json:",omitempty"` + // ReadOnlyForceRecursive raises an error if the mount cannot be made recursively read-only. + ReadOnlyForceRecursive bool `json:",omitempty"` } // VolumeOptions represents the options for a mount of type volume. diff --git a/vendor/github.com/docker/docker/api/types/network/endpoint.go b/vendor/github.com/docker/docker/api/types/network/endpoint.go new file mode 100644 index 000000000..4b3c06a52 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/network/endpoint.go @@ -0,0 +1,144 @@ +package network + +import ( + "errors" + "fmt" + "net" + + "github.com/docker/docker/internal/multierror" +) + +// EndpointSettings stores the network endpoint details +type EndpointSettings struct { + // Configurations + IPAMConfig *EndpointIPAMConfig + Links []string + Aliases []string // Aliases holds the list of extra, user-specified DNS names for this endpoint. + MacAddress string + // Operational data + NetworkID string + EndpointID string + Gateway string + IPAddress string + IPPrefixLen int + IPv6Gateway string + GlobalIPv6Address string + GlobalIPv6PrefixLen int + DriverOpts map[string]string + // DNSNames holds all the (non fully qualified) DNS names associated to this endpoint. First entry is used to + // generate PTR records. + DNSNames []string +} + +// Copy makes a deep copy of `EndpointSettings` +func (es *EndpointSettings) Copy() *EndpointSettings { + epCopy := *es + if es.IPAMConfig != nil { + epCopy.IPAMConfig = es.IPAMConfig.Copy() + } + + if es.Links != nil { + links := make([]string, 0, len(es.Links)) + epCopy.Links = append(links, es.Links...) + } + + if es.Aliases != nil { + aliases := make([]string, 0, len(es.Aliases)) + epCopy.Aliases = append(aliases, es.Aliases...) + } + + if len(es.DNSNames) > 0 { + epCopy.DNSNames = make([]string, len(es.DNSNames)) + copy(epCopy.DNSNames, es.DNSNames) + } + + return &epCopy +} + +// EndpointIPAMConfig represents IPAM configurations for the endpoint +type EndpointIPAMConfig struct { + IPv4Address string `json:",omitempty"` + IPv6Address string `json:",omitempty"` + LinkLocalIPs []string `json:",omitempty"` +} + +// Copy makes a copy of the endpoint ipam config +func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { + cfgCopy := *cfg + cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) + cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) + return &cfgCopy +} + +// NetworkSubnet describes a user-defined subnet for a specific network. It's only used to validate if an +// EndpointIPAMConfig is valid for a specific network. +type NetworkSubnet interface { + // Contains checks whether the NetworkSubnet contains [addr]. + Contains(addr net.IP) bool + // IsStatic checks whether the subnet was statically allocated (ie. user-defined). + IsStatic() bool +} + +// IsInRange checks whether static IP addresses are valid in a specific network. +func (cfg *EndpointIPAMConfig) IsInRange(v4Subnets []NetworkSubnet, v6Subnets []NetworkSubnet) error { + var errs []error + + if err := validateEndpointIPAddress(cfg.IPv4Address, v4Subnets); err != nil { + errs = append(errs, err) + } + if err := validateEndpointIPAddress(cfg.IPv6Address, v6Subnets); err != nil { + errs = append(errs, err) + } + + return multierror.Join(errs...) +} + +func validateEndpointIPAddress(epAddr string, ipamSubnets []NetworkSubnet) error { + if epAddr == "" { + return nil + } + + var staticSubnet bool + parsedAddr := net.ParseIP(epAddr) + for _, subnet := range ipamSubnets { + if subnet.IsStatic() { + staticSubnet = true + if subnet.Contains(parsedAddr) { + return nil + } + } + } + + if staticSubnet { + return fmt.Errorf("no configured subnet or ip-range contain the IP address %s", epAddr) + } + + return errors.New("user specified IP address is supported only when connecting to networks with user configured subnets") +} + +// Validate checks whether cfg is valid. +func (cfg *EndpointIPAMConfig) Validate() error { + if cfg == nil { + return nil + } + + var errs []error + + if cfg.IPv4Address != "" { + if addr := net.ParseIP(cfg.IPv4Address); addr == nil || addr.To4() == nil || addr.IsUnspecified() { + errs = append(errs, fmt.Errorf("invalid IPv4 address: %s", cfg.IPv4Address)) + } + } + if cfg.IPv6Address != "" { + if addr := net.ParseIP(cfg.IPv6Address); addr == nil || addr.To4() != nil || addr.IsUnspecified() { + errs = append(errs, fmt.Errorf("invalid IPv6 address: %s", cfg.IPv6Address)) + } + } + for _, addr := range cfg.LinkLocalIPs { + if parsed := net.ParseIP(addr); parsed == nil || parsed.IsUnspecified() { + errs = append(errs, fmt.Errorf("invalid link-local IP address: %s", addr)) + } + } + + return multierror.Join(errs...) +} diff --git a/vendor/github.com/docker/docker/api/types/network/ipam.go b/vendor/github.com/docker/docker/api/types/network/ipam.go new file mode 100644 index 000000000..17f370ef7 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/network/ipam.go @@ -0,0 +1,151 @@ +package network + +import ( + "errors" + "fmt" + "net/netip" + + "github.com/docker/docker/internal/multierror" +) + +// IPAM represents IP Address Management +type IPAM struct { + Driver string + Options map[string]string // Per network IPAM driver options + Config []IPAMConfig +} + +// IPAMConfig represents IPAM configurations +type IPAMConfig struct { + Subnet string `json:",omitempty"` + IPRange string `json:",omitempty"` + Gateway string `json:",omitempty"` + AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` +} + +type ipFamily string + +const ( + ip4 ipFamily = "IPv4" + ip6 ipFamily = "IPv6" +) + +// HasIPv6Subnets checks whether there's any IPv6 subnets in the ipam parameter. It ignores any invalid Subnet and nil +// ipam. +func HasIPv6Subnets(ipam *IPAM) bool { + if ipam == nil { + return false + } + + for _, cfg := range ipam.Config { + subnet, err := netip.ParsePrefix(cfg.Subnet) + if err != nil { + continue + } + + if subnet.Addr().Is6() { + return true + } + } + + return false +} + +// ValidateIPAM checks whether the network's IPAM passed as argument is valid. It returns a joinError of the list of +// errors found. +func ValidateIPAM(ipam *IPAM) error { + if ipam == nil { + return nil + } + + var errs []error + for _, cfg := range ipam.Config { + subnet, err := netip.ParsePrefix(cfg.Subnet) + if err != nil { + errs = append(errs, fmt.Errorf("invalid subnet %s: invalid CIDR block notation", cfg.Subnet)) + continue + } + subnetFamily := ip4 + if subnet.Addr().Is6() { + subnetFamily = ip6 + } + + if subnet != subnet.Masked() { + errs = append(errs, fmt.Errorf("invalid subnet %s: it should be %s", subnet, subnet.Masked())) + } + + if ipRangeErrs := validateIPRange(cfg.IPRange, subnet, subnetFamily); len(ipRangeErrs) > 0 { + errs = append(errs, ipRangeErrs...) + } + + if err := validateAddress(cfg.Gateway, subnet, subnetFamily); err != nil { + errs = append(errs, fmt.Errorf("invalid gateway %s: %w", cfg.Gateway, err)) + } + + for auxName, aux := range cfg.AuxAddress { + if err := validateAddress(aux, subnet, subnetFamily); err != nil { + errs = append(errs, fmt.Errorf("invalid auxiliary address %s: %w", auxName, err)) + } + } + } + + if err := multierror.Join(errs...); err != nil { + return fmt.Errorf("invalid network config:\n%w", err) + } + + return nil +} + +func validateIPRange(ipRange string, subnet netip.Prefix, subnetFamily ipFamily) []error { + if ipRange == "" { + return nil + } + prefix, err := netip.ParsePrefix(ipRange) + if err != nil { + return []error{fmt.Errorf("invalid ip-range %s: invalid CIDR block notation", ipRange)} + } + family := ip4 + if prefix.Addr().Is6() { + family = ip6 + } + + if family != subnetFamily { + return []error{fmt.Errorf("invalid ip-range %s: parent subnet is an %s block", ipRange, subnetFamily)} + } + + var errs []error + if prefix.Bits() < subnet.Bits() { + errs = append(errs, fmt.Errorf("invalid ip-range %s: CIDR block is bigger than its parent subnet %s", ipRange, subnet)) + } + if prefix != prefix.Masked() { + errs = append(errs, fmt.Errorf("invalid ip-range %s: it should be %s", prefix, prefix.Masked())) + } + if !subnet.Overlaps(prefix) { + errs = append(errs, fmt.Errorf("invalid ip-range %s: parent subnet %s doesn't contain ip-range", ipRange, subnet)) + } + + return errs +} + +func validateAddress(address string, subnet netip.Prefix, subnetFamily ipFamily) error { + if address == "" { + return nil + } + addr, err := netip.ParseAddr(address) + if err != nil { + return errors.New("invalid address") + } + family := ip4 + if addr.Is6() { + family = ip6 + } + + if family != subnetFamily { + return fmt.Errorf("parent subnet is an %s block", subnetFamily) + } + if !subnet.Contains(addr) { + return fmt.Errorf("parent subnet %s doesn't contain this address", subnet) + } + + return nil +} diff --git a/vendor/github.com/docker/docker/api/types/network/network.go b/vendor/github.com/docker/docker/api/types/network/network.go index 437b184c6..f1f300f3d 100644 --- a/vendor/github.com/docker/docker/api/types/network/network.go +++ b/vendor/github.com/docker/docker/api/types/network/network.go @@ -1,69 +1,34 @@ package network // import "github.com/docker/docker/api/types/network" + import ( "github.com/docker/docker/api/types/filters" ) +const ( + // NetworkDefault is a platform-independent alias to choose the platform-specific default network stack. + NetworkDefault = "default" + // NetworkHost is the name of the predefined network used when the NetworkMode host is selected (only available on Linux) + NetworkHost = "host" + // NetworkNone is the name of the predefined network used when the NetworkMode none is selected (available on both Linux and Windows) + NetworkNone = "none" + // NetworkBridge is the name of the default network on Linux + NetworkBridge = "bridge" + // NetworkNat is the name of the default network on Windows + NetworkNat = "nat" +) + // Address represents an IP address type Address struct { Addr string PrefixLen int } -// IPAM represents IP Address Management -type IPAM struct { - Driver string - Options map[string]string // Per network IPAM driver options - Config []IPAMConfig -} - -// IPAMConfig represents IPAM configurations -type IPAMConfig struct { - Subnet string `json:",omitempty"` - IPRange string `json:",omitempty"` - Gateway string `json:",omitempty"` - AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` -} - -// EndpointIPAMConfig represents IPAM configurations for the endpoint -type EndpointIPAMConfig struct { - IPv4Address string `json:",omitempty"` - IPv6Address string `json:",omitempty"` - LinkLocalIPs []string `json:",omitempty"` -} - -// Copy makes a copy of the endpoint ipam config -func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { - cfgCopy := *cfg - cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) - cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) - return &cfgCopy -} - // PeerInfo represents one peer of an overlay network type PeerInfo struct { Name string IP string } -// EndpointSettings stores the network endpoint details -type EndpointSettings struct { - // Configurations - IPAMConfig *EndpointIPAMConfig - Links []string - Aliases []string - // Operational data - NetworkID string - EndpointID string - Gateway string - IPAddress string - IPPrefixLen int - IPv6Gateway string - GlobalIPv6Address string - GlobalIPv6PrefixLen int - MacAddress string - DriverOpts map[string]string -} - // Task carries the information about one backend task type Task struct { Name string @@ -80,25 +45,6 @@ type ServiceInfo struct { Tasks []Task } -// Copy makes a deep copy of `EndpointSettings` -func (es *EndpointSettings) Copy() *EndpointSettings { - epCopy := *es - if es.IPAMConfig != nil { - epCopy.IPAMConfig = es.IPAMConfig.Copy() - } - - if es.Links != nil { - links := make([]string, 0, len(es.Links)) - epCopy.Links = append(links, es.Links...) - } - - if es.Aliases != nil { - aliases := make([]string, 0, len(es.Aliases)) - epCopy.Aliases = append(aliases, es.Aliases...) - } - return &epCopy -} - // NetworkingConfig represents the container's networking configuration for each of its interfaces // Carries the networking configs specified in the `docker run` and `docker network connect` commands type NetworkingConfig struct { diff --git a/vendor/github.com/docker/docker/api/types/registry/registry.go b/vendor/github.com/docker/docker/api/types/registry/registry.go index b83f5d7b2..05cb31075 100644 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ b/vendor/github.com/docker/docker/api/types/registry/registry.go @@ -92,7 +92,9 @@ type SearchResult struct { IsOfficial bool `json:"is_official"` // Name is the name of the repository Name string `json:"name"` - // IsAutomated indicates whether the result is automated + // IsAutomated indicates whether the result is automated. + // + // Deprecated: the "is_automated" field is deprecated and will always be "false" in the future. IsAutomated bool `json:"is_automated"` // Description is a textual description of the repository Description string `json:"description"` diff --git a/vendor/github.com/docker/docker/api/types/swarm/container.go b/vendor/github.com/docker/docker/api/types/swarm/container.go index af5e1c0bc..65f61d2d2 100644 --- a/vendor/github.com/docker/docker/api/types/swarm/container.go +++ b/vendor/github.com/docker/docker/api/types/swarm/container.go @@ -32,6 +32,42 @@ type SELinuxContext struct { Level string } +// SeccompMode is the type used for the enumeration of possible seccomp modes +// in SeccompOpts +type SeccompMode string + +const ( + SeccompModeDefault SeccompMode = "default" + SeccompModeUnconfined SeccompMode = "unconfined" + SeccompModeCustom SeccompMode = "custom" +) + +// SeccompOpts defines the options for configuring seccomp on a swarm-managed +// container. +type SeccompOpts struct { + // Mode is the SeccompMode used for the container. + Mode SeccompMode `json:",omitempty"` + // Profile is the custom seccomp profile as a json object to be used with + // the container. Mode should be set to SeccompModeCustom when using a + // custom profile in this manner. + Profile []byte `json:",omitempty"` +} + +// AppArmorMode is type used for the enumeration of possible AppArmor modes in +// AppArmorOpts +type AppArmorMode string + +const ( + AppArmorModeDefault AppArmorMode = "default" + AppArmorModeDisabled AppArmorMode = "disabled" +) + +// AppArmorOpts defines the options for configuring AppArmor on a swarm-managed +// container. Currently, custom AppArmor profiles are not supported. +type AppArmorOpts struct { + Mode AppArmorMode `json:",omitempty"` +} + // CredentialSpec for managed service account (Windows only) type CredentialSpec struct { Config string @@ -41,8 +77,11 @@ type CredentialSpec struct { // Privileges defines the security options for the container. type Privileges struct { - CredentialSpec *CredentialSpec - SELinuxContext *SELinuxContext + CredentialSpec *CredentialSpec + SELinuxContext *SELinuxContext + Seccomp *SeccompOpts `json:",omitempty"` + AppArmor *AppArmorOpts `json:",omitempty"` + NoNewPrivileges bool } // ContainerSpec represents the spec of a container. diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go index 98c2806c3..292bd7afc 100644 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go +++ b/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go @@ -1,3 +1,3 @@ -//go:generate protoc -I . --gogofast_out=import_path=github.com/docker/docker/api/types/swarm/runtime:. plugin.proto +//go:generate protoc --gogofaster_out=import_path=github.com/docker/docker/api/types/swarm/runtime:. plugin.proto package runtime // import "github.com/docker/docker/api/types/swarm/runtime" diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go index e45045866..32aaf0d51 100644 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go +++ b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go @@ -1,23 +1,15 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: plugin.proto -/* - Package runtime is a generated protocol buffer package. - - It is generated from these files: - plugin.proto - - It has these top-level messages: - PluginSpec - PluginPrivilege -*/ package runtime -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" - -import io "io" +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" +) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal @@ -28,22 +20,50 @@ var _ = math.Inf // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // PluginSpec defines the base payload which clients can specify for creating // a service with the plugin runtime. type PluginSpec struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Remote string `protobuf:"bytes,2,opt,name=remote,proto3" json:"remote,omitempty"` - Privileges []*PluginPrivilege `protobuf:"bytes,3,rep,name=privileges" json:"privileges,omitempty"` + Privileges []*PluginPrivilege `protobuf:"bytes,3,rep,name=privileges,proto3" json:"privileges,omitempty"` Disabled bool `protobuf:"varint,4,opt,name=disabled,proto3" json:"disabled,omitempty"` - Env []string `protobuf:"bytes,5,rep,name=env" json:"env,omitempty"` + Env []string `protobuf:"bytes,5,rep,name=env,proto3" json:"env,omitempty"` +} + +func (m *PluginSpec) Reset() { *m = PluginSpec{} } +func (m *PluginSpec) String() string { return proto.CompactTextString(m) } +func (*PluginSpec) ProtoMessage() {} +func (*PluginSpec) Descriptor() ([]byte, []int) { + return fileDescriptor_22a625af4bc1cc87, []int{0} +} +func (m *PluginSpec) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PluginSpec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PluginSpec.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PluginSpec) XXX_Merge(src proto.Message) { + xxx_messageInfo_PluginSpec.Merge(m, src) +} +func (m *PluginSpec) XXX_Size() int { + return m.Size() +} +func (m *PluginSpec) XXX_DiscardUnknown() { + xxx_messageInfo_PluginSpec.DiscardUnknown(m) } -func (m *PluginSpec) Reset() { *m = PluginSpec{} } -func (m *PluginSpec) String() string { return proto.CompactTextString(m) } -func (*PluginSpec) ProtoMessage() {} -func (*PluginSpec) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{0} } +var xxx_messageInfo_PluginSpec proto.InternalMessageInfo func (m *PluginSpec) GetName() string { if m != nil { @@ -85,13 +105,41 @@ func (m *PluginSpec) GetEnv() []string { type PluginPrivilege struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Value []string `protobuf:"bytes,3,rep,name=value" json:"value,omitempty"` + Value []string `protobuf:"bytes,3,rep,name=value,proto3" json:"value,omitempty"` } -func (m *PluginPrivilege) Reset() { *m = PluginPrivilege{} } -func (m *PluginPrivilege) String() string { return proto.CompactTextString(m) } -func (*PluginPrivilege) ProtoMessage() {} -func (*PluginPrivilege) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{1} } +func (m *PluginPrivilege) Reset() { *m = PluginPrivilege{} } +func (m *PluginPrivilege) String() string { return proto.CompactTextString(m) } +func (*PluginPrivilege) ProtoMessage() {} +func (*PluginPrivilege) Descriptor() ([]byte, []int) { + return fileDescriptor_22a625af4bc1cc87, []int{1} +} +func (m *PluginPrivilege) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PluginPrivilege) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PluginPrivilege.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PluginPrivilege) XXX_Merge(src proto.Message) { + xxx_messageInfo_PluginPrivilege.Merge(m, src) +} +func (m *PluginPrivilege) XXX_Size() int { + return m.Size() +} +func (m *PluginPrivilege) XXX_DiscardUnknown() { + xxx_messageInfo_PluginPrivilege.DiscardUnknown(m) +} + +var xxx_messageInfo_PluginPrivilege proto.InternalMessageInfo func (m *PluginPrivilege) GetName() string { if m != nil { @@ -118,10 +166,32 @@ func init() { proto.RegisterType((*PluginSpec)(nil), "PluginSpec") proto.RegisterType((*PluginPrivilege)(nil), "PluginPrivilege") } + +func init() { proto.RegisterFile("plugin.proto", fileDescriptor_22a625af4bc1cc87) } + +var fileDescriptor_22a625af4bc1cc87 = []byte{ + // 225 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0xc8, 0x29, 0x4d, + 0xcf, 0xcc, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x57, 0x9a, 0xc1, 0xc8, 0xc5, 0x15, 0x00, 0x16, + 0x08, 0x2e, 0x48, 0x4d, 0x16, 0x12, 0xe2, 0x62, 0xc9, 0x4b, 0xcc, 0x4d, 0x95, 0x60, 0x54, 0x60, + 0xd4, 0xe0, 0x0c, 0x02, 0xb3, 0x85, 0xc4, 0xb8, 0xd8, 0x8a, 0x52, 0x73, 0xf3, 0x4b, 0x52, 0x25, + 0x98, 0xc0, 0xa2, 0x50, 0x9e, 0x90, 0x01, 0x17, 0x57, 0x41, 0x51, 0x66, 0x59, 0x66, 0x4e, 0x6a, + 0x7a, 0x6a, 0xb1, 0x04, 0xb3, 0x02, 0xb3, 0x06, 0xb7, 0x91, 0x80, 0x1e, 0xc4, 0xb0, 0x00, 0x98, + 0x44, 0x10, 0x92, 0x1a, 0x21, 0x29, 0x2e, 0x8e, 0x94, 0xcc, 0xe2, 0xc4, 0xa4, 0x9c, 0xd4, 0x14, + 0x09, 0x16, 0x05, 0x46, 0x0d, 0x8e, 0x20, 0x38, 0x5f, 0x48, 0x80, 0x8b, 0x39, 0x35, 0xaf, 0x4c, + 0x82, 0x55, 0x81, 0x59, 0x83, 0x33, 0x08, 0xc4, 0x54, 0x8a, 0xe5, 0xe2, 0x47, 0x33, 0x0c, 0xab, + 0xf3, 0x14, 0xb8, 0xb8, 0x53, 0x52, 0x8b, 0x93, 0x8b, 0x32, 0x0b, 0x4a, 0x32, 0xf3, 0xf3, 0xa0, + 0x6e, 0x44, 0x16, 0x12, 0x12, 0xe1, 0x62, 0x2d, 0x4b, 0xcc, 0x29, 0x4d, 0x05, 0xbb, 0x91, 0x33, + 0x08, 0xc2, 0x71, 0x92, 0x38, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, + 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x24, 0x36, + 0x70, 0xd0, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x37, 0xea, 0xe2, 0xca, 0x2a, 0x01, 0x00, + 0x00, +} + func (m *PluginSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } @@ -129,66 +199,69 @@ func (m *PluginSpec) Marshal() (dAtA []byte, err error) { } func (m *PluginSpec) MarshalTo(dAtA []byte) (int, error) { - var i int + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PluginSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) _ = i var l int _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if len(m.Remote) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Remote))) - i += copy(dAtA[i:], m.Remote) - } - if len(m.Privileges) > 0 { - for _, msg := range m.Privileges { - dAtA[i] = 0x1a - i++ - i = encodeVarintPlugin(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n + if len(m.Env) > 0 { + for iNdEx := len(m.Env) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Env[iNdEx]) + copy(dAtA[i:], m.Env[iNdEx]) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Env[iNdEx]))) + i-- + dAtA[i] = 0x2a } } if m.Disabled { - dAtA[i] = 0x20 - i++ + i-- if m.Disabled { dAtA[i] = 1 } else { dAtA[i] = 0 } - i++ + i-- + dAtA[i] = 0x20 } - if len(m.Env) > 0 { - for _, s := range m.Env { - dAtA[i] = 0x2a - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) + if len(m.Privileges) > 0 { + for iNdEx := len(m.Privileges) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Privileges[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPlugin(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a } } - return i, nil + if len(m.Remote) > 0 { + i -= len(m.Remote) + copy(dAtA[i:], m.Remote) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Remote))) + i-- + dAtA[i] = 0x12 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil } func (m *PluginPrivilege) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } @@ -196,50 +269,56 @@ func (m *PluginPrivilege) Marshal() (dAtA []byte, err error) { } func (m *PluginPrivilege) MarshalTo(dAtA []byte) (int, error) { - var i int + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PluginPrivilege) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) _ = i var l int _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) + if len(m.Value) > 0 { + for iNdEx := len(m.Value) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Value[iNdEx]) + copy(dAtA[i:], m.Value[iNdEx]) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Value[iNdEx]))) + i-- + dAtA[i] = 0x1a + } } if len(m.Description) > 0 { - dAtA[i] = 0x12 - i++ + i -= len(m.Description) + copy(dAtA[i:], m.Description) i = encodeVarintPlugin(dAtA, i, uint64(len(m.Description))) - i += copy(dAtA[i:], m.Description) + i-- + dAtA[i] = 0x12 } - if len(m.Value) > 0 { - for _, s := range m.Value { - dAtA[i] = 0x1a - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa } - return i, nil + return len(dAtA) - i, nil } func encodeVarintPlugin(dAtA []byte, offset int, v uint64) int { + offset -= sovPlugin(v) + base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) - return offset + 1 + return base } func (m *PluginSpec) Size() (n int) { + if m == nil { + return 0 + } var l int _ = l l = len(m.Name) @@ -269,6 +348,9 @@ func (m *PluginSpec) Size() (n int) { } func (m *PluginPrivilege) Size() (n int) { + if m == nil { + return 0 + } var l int _ = l l = len(m.Name) @@ -289,14 +371,7 @@ func (m *PluginPrivilege) Size() (n int) { } func sovPlugin(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n + return (math_bits.Len64(x|1) + 6) / 7 } func sozPlugin(x uint64) (n int) { return sovPlugin(uint64((x << 1) ^ uint64((int64(x) >> 63)))) @@ -316,7 +391,7 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - wire |= (uint64(b) & 0x7F) << shift + wire |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -344,7 +419,7 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -354,6 +429,9 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { return ErrInvalidLengthPlugin } postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -373,7 +451,7 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -383,6 +461,9 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { return ErrInvalidLengthPlugin } postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -402,7 +483,7 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= (int(b) & 0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } @@ -411,6 +492,9 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { return ErrInvalidLengthPlugin } postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -433,7 +517,7 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= (int(b) & 0x7F) << shift + v |= int(b&0x7F) << shift if b < 0x80 { break } @@ -453,7 +537,7 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -463,6 +547,9 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { return ErrInvalidLengthPlugin } postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -474,7 +561,7 @@ func (m *PluginSpec) Unmarshal(dAtA []byte) error { if err != nil { return err } - if skippy < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthPlugin } if (iNdEx + skippy) > l { @@ -504,7 +591,7 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - wire |= (uint64(b) & 0x7F) << shift + wire |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -532,7 +619,7 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -542,6 +629,9 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { return ErrInvalidLengthPlugin } postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -561,7 +651,7 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -571,6 +661,9 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { return ErrInvalidLengthPlugin } postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -590,7 +683,7 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -600,6 +693,9 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { return ErrInvalidLengthPlugin } postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPlugin + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -611,7 +707,7 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { if err != nil { return err } - if skippy < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthPlugin } if (iNdEx + skippy) > l { @@ -629,6 +725,7 @@ func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { func skipPlugin(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 + depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { @@ -660,10 +757,8 @@ func skipPlugin(dAtA []byte) (n int, err error) { break } } - return iNdEx, nil case 1: iNdEx += 8 - return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { @@ -680,75 +775,34 @@ func skipPlugin(dAtA []byte) (n int, err error) { break } } - iNdEx += length if length < 0 { return 0, ErrInvalidLengthPlugin } - return iNdEx, nil + iNdEx += length case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipPlugin(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil + depth++ case 4: - return iNdEx, nil + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupPlugin + } + depth-- case 5: iNdEx += 4 - return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } + if iNdEx < 0 { + return 0, ErrInvalidLengthPlugin + } + if depth == 0 { + return iNdEx, nil + } } - panic("unreachable") + return 0, io.ErrUnexpectedEOF } var ( - ErrInvalidLengthPlugin = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowPlugin = fmt.Errorf("proto: integer overflow") + ErrInvalidLengthPlugin = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPlugin = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupPlugin = fmt.Errorf("proto: unexpected end of group") ) - -func init() { proto.RegisterFile("plugin.proto", fileDescriptorPlugin) } - -var fileDescriptorPlugin = []byte{ - // 256 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x4d, 0x4b, 0xc3, 0x30, - 0x18, 0xc7, 0x89, 0xdd, 0xc6, 0xfa, 0x4c, 0x70, 0x04, 0x91, 0xe2, 0xa1, 0x94, 0x9d, 0x7a, 0x6a, - 0x45, 0x2f, 0x82, 0x37, 0x0f, 0x9e, 0x47, 0xbc, 0x09, 0x1e, 0xd2, 0xf6, 0xa1, 0x06, 0x9b, 0x17, - 0x92, 0xb4, 0xe2, 0x37, 0xf1, 0x23, 0x79, 0xf4, 0x23, 0x48, 0x3f, 0x89, 0x98, 0x75, 0x32, 0x64, - 0xa7, 0xff, 0x4b, 0xc2, 0x9f, 0x1f, 0x0f, 0x9c, 0x9a, 0xae, 0x6f, 0x85, 0x2a, 0x8c, 0xd5, 0x5e, - 0x6f, 0x3e, 0x08, 0xc0, 0x36, 0x14, 0x8f, 0x06, 0x6b, 0x4a, 0x61, 0xa6, 0xb8, 0xc4, 0x84, 0x64, - 0x24, 0x8f, 0x59, 0xf0, 0xf4, 0x02, 0x16, 0x16, 0xa5, 0xf6, 0x98, 0x9c, 0x84, 0x76, 0x4a, 0xf4, - 0x0a, 0xc0, 0x58, 0x31, 0x88, 0x0e, 0x5b, 0x74, 0x49, 0x94, 0x45, 0xf9, 0xea, 0x7a, 0x5d, 0xec, - 0xc6, 0xb6, 0xfb, 0x07, 0x76, 0xf0, 0x87, 0x5e, 0xc2, 0xb2, 0x11, 0x8e, 0x57, 0x1d, 0x36, 0xc9, - 0x2c, 0x23, 0xf9, 0x92, 0xfd, 0x65, 0xba, 0x86, 0x08, 0xd5, 0x90, 0xcc, 0xb3, 0x28, 0x8f, 0xd9, - 0xaf, 0xdd, 0x3c, 0xc3, 0xd9, 0xbf, 0xb1, 0xa3, 0x78, 0x19, 0xac, 0x1a, 0x74, 0xb5, 0x15, 0xc6, - 0x0b, 0xad, 0x26, 0xc6, 0xc3, 0x8a, 0x9e, 0xc3, 0x7c, 0xe0, 0x5d, 0x8f, 0x81, 0x31, 0x66, 0xbb, - 0x70, 0xff, 0xf0, 0x39, 0xa6, 0xe4, 0x6b, 0x4c, 0xc9, 0xf7, 0x98, 0x92, 0xa7, 0xdb, 0x56, 0xf8, - 0x97, 0xbe, 0x2a, 0x6a, 0x2d, 0xcb, 0x46, 0xd7, 0xaf, 0x68, 0xf7, 0xc2, 0x8d, 0x28, 0xfd, 0xbb, - 0x41, 0x57, 0xba, 0x37, 0x6e, 0x65, 0x69, 0x7b, 0xe5, 0x85, 0xc4, 0xbb, 0x49, 0xab, 0x45, 0x38, - 0xe4, 0xcd, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x99, 0xa8, 0xd9, 0x9b, 0x58, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto index 9ef169046..e311b36ba 100644 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto +++ b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto @@ -1,7 +1,5 @@ syntax = "proto3"; -option go_package = "github.com/docker/docker/api/types/swarm/runtime;runtime"; - // PluginSpec defines the base payload which clients can specify for creating // a service with the plugin runtime. message PluginSpec { diff --git a/vendor/github.com/docker/docker/api/types/swarm/service.go b/vendor/github.com/docker/docker/api/types/swarm/service.go index 6eb452d24..5b6d5ec12 100644 --- a/vendor/github.com/docker/docker/api/types/swarm/service.go +++ b/vendor/github.com/docker/docker/api/types/swarm/service.go @@ -34,9 +34,9 @@ type ServiceSpec struct { UpdateConfig *UpdateConfig `json:",omitempty"` RollbackConfig *UpdateConfig `json:",omitempty"` - // Networks field in ServiceSpec is deprecated. The - // same field in TaskSpec should be used instead. - // This field will be removed in a future release. + // Networks specifies which networks the service should attach to. + // + // Deprecated: This field is deprecated since v1.44. The Networks field in TaskSpec should be used instead. Networks []NetworkAttachmentConfig `json:",omitempty"` EndpointSpec *EndpointSpec `json:",omitempty"` } diff --git a/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go b/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go new file mode 100644 index 000000000..9a268ff1b --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go @@ -0,0 +1,20 @@ +package swarm + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ServiceCreateResponse contains the information returned to a client on the +// creation of a new service. +// +// swagger:model ServiceCreateResponse +type ServiceCreateResponse struct { + + // The ID of the created service. + ID string `json:"ID,omitempty"` + + // Optional warning message. + // + // FIXME(thaJeztah): this should have "omitempty" in the generated type. + // + Warnings []string `json:"Warnings"` +} diff --git a/vendor/github.com/docker/docker/api/types/service_update_response.go b/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go similarity index 95% rename from vendor/github.com/docker/docker/api/types/service_update_response.go rename to vendor/github.com/docker/docker/api/types/swarm/service_update_response.go index 74ea64b1b..0417467da 100644 --- a/vendor/github.com/docker/docker/api/types/service_update_response.go +++ b/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go @@ -1,4 +1,4 @@ -package types +package swarm // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command diff --git a/vendor/github.com/docker/docker/api/types/system/info.go b/vendor/github.com/docker/docker/api/types/system/info.go new file mode 100644 index 000000000..89d4a0098 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/system/info.go @@ -0,0 +1,116 @@ +package system + +import ( + "github.com/docker/docker/api/types/container" + "github.com/docker/docker/api/types/registry" + "github.com/docker/docker/api/types/swarm" +) + +// Info contains response of Engine API: +// GET "/info" +type Info struct { + ID string + Containers int + ContainersRunning int + ContainersPaused int + ContainersStopped int + Images int + Driver string + DriverStatus [][2]string + SystemStatus [][2]string `json:",omitempty"` // SystemStatus is only propagated by the Swarm standalone API + Plugins PluginsInfo + MemoryLimit bool + SwapLimit bool + KernelMemory bool `json:",omitempty"` // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes + KernelMemoryTCP bool `json:",omitempty"` // KernelMemoryTCP is not supported on cgroups v2. + CPUCfsPeriod bool `json:"CpuCfsPeriod"` + CPUCfsQuota bool `json:"CpuCfsQuota"` + CPUShares bool + CPUSet bool + PidsLimit bool + IPv4Forwarding bool + BridgeNfIptables bool + BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` + Debug bool + NFd int + OomKillDisable bool + NGoroutines int + SystemTime string + LoggingDriver string + CgroupDriver string + CgroupVersion string `json:",omitempty"` + NEventsListener int + KernelVersion string + OperatingSystem string + OSVersion string + OSType string + Architecture string + IndexServerAddress string + RegistryConfig *registry.ServiceConfig + NCPU int + MemTotal int64 + GenericResources []swarm.GenericResource + DockerRootDir string + HTTPProxy string `json:"HttpProxy"` + HTTPSProxy string `json:"HttpsProxy"` + NoProxy string + Name string + Labels []string + ExperimentalBuild bool + ServerVersion string + Runtimes map[string]RuntimeWithStatus + DefaultRuntime string + Swarm swarm.Info + // LiveRestoreEnabled determines whether containers should be kept + // running when the daemon is shutdown or upon daemon start if + // running containers are detected + LiveRestoreEnabled bool + Isolation container.Isolation + InitBinary string + ContainerdCommit Commit + RuncCommit Commit + InitCommit Commit + SecurityOptions []string + ProductLicense string `json:",omitempty"` + DefaultAddressPools []NetworkAddressPool `json:",omitempty"` + CDISpecDirs []string + + // Legacy API fields for older API versions. + legacyFields + + // Warnings contains a slice of warnings that occurred while collecting + // system information. These warnings are intended to be informational + // messages for the user, and are not intended to be parsed / used for + // other purposes, as they do not have a fixed format. + Warnings []string +} + +type legacyFields struct { + ExecutionDriver string `json:",omitempty"` // Deprecated: deprecated since API v1.25, but returned for older versions. +} + +// PluginsInfo is a temp struct holding Plugins name +// registered with docker daemon. It is used by [Info] struct +type PluginsInfo struct { + // List of Volume plugins registered + Volume []string + // List of Network plugins registered + Network []string + // List of Authorization plugins registered + Authorization []string + // List of Log plugins registered + Log []string +} + +// Commit holds the Git-commit (SHA1) that a binary was built from, as reported +// in the version-string of external tools, such as containerd, or runC. +type Commit struct { + ID string // ID is the actual commit ID of external tool. + Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time. +} + +// NetworkAddressPool is a temp struct used by [Info] struct. +type NetworkAddressPool struct { + Base string + Size int +} diff --git a/vendor/github.com/docker/docker/api/types/system/runtime.go b/vendor/github.com/docker/docker/api/types/system/runtime.go new file mode 100644 index 000000000..d077295a0 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/system/runtime.go @@ -0,0 +1,20 @@ +package system + +// Runtime describes an OCI runtime +type Runtime struct { + // "Legacy" runtime configuration for runc-compatible runtimes. + + Path string `json:"path,omitempty"` + Args []string `json:"runtimeArgs,omitempty"` + + // Shimv2 runtime configuration. Mutually exclusive with the legacy config above. + + Type string `json:"runtimeType,omitempty"` + Options map[string]interface{} `json:"options,omitempty"` +} + +// RuntimeWithStatus extends [Runtime] to hold [RuntimeStatus]. +type RuntimeWithStatus struct { + Runtime + Status map[string]string `json:"status,omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/system/security_opts.go b/vendor/github.com/docker/docker/api/types/system/security_opts.go new file mode 100644 index 000000000..edff3eb1a --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/system/security_opts.go @@ -0,0 +1,48 @@ +package system + +import ( + "errors" + "fmt" + "strings" +) + +// SecurityOpt contains the name and options of a security option +type SecurityOpt struct { + Name string + Options []KeyValue +} + +// DecodeSecurityOptions decodes a security options string slice to a +// type-safe [SecurityOpt]. +func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { + so := []SecurityOpt{} + for _, opt := range opts { + // support output from a < 1.13 docker daemon + if !strings.Contains(opt, "=") { + so = append(so, SecurityOpt{Name: opt}) + continue + } + secopt := SecurityOpt{} + for _, s := range strings.Split(opt, ",") { + k, v, ok := strings.Cut(s, "=") + if !ok { + return nil, fmt.Errorf("invalid security option %q", s) + } + if k == "" || v == "" { + return nil, errors.New("invalid empty security option") + } + if k == "name" { + secopt.Name = v + continue + } + secopt.Options = append(secopt.Options, KeyValue{Key: k, Value: v}) + } + so = append(so, secopt) + } + return so, nil +} + +// KeyValue holds a key/value pair. +type KeyValue struct { + Key, Value string +} diff --git a/vendor/github.com/docker/docker/api/types/types.go b/vendor/github.com/docker/docker/api/types/types.go index b413e0200..5c56a0caf 100644 --- a/vendor/github.com/docker/docker/api/types/types.go +++ b/vendor/github.com/docker/docker/api/types/types.go @@ -1,18 +1,15 @@ package types // import "github.com/docker/docker/api/types" import ( - "errors" - "fmt" "io" "os" - "strings" "time" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/volume" "github.com/docker/go-connections/nat" @@ -80,6 +77,8 @@ type ImageInspect struct { // Container is the ID of the container that was used to create the image. // // Depending on how the image was created, this field may be empty. + // + // Deprecated: this field is omitted in API v1.45, but kept for backward compatibility. Container string // ContainerConfig is an optional field containing the configuration of the @@ -87,6 +86,8 @@ type ImageInspect struct { // // Previous versions of Docker builder used this field to store build cache, // and it is not in active use anymore. + // + // Deprecated: this field is omitted in API v1.45, but kept for backward compatibility. ContainerConfig *container.Config // DockerVersion is the version of Docker that was used to build the image. @@ -118,12 +119,7 @@ type ImageInspect struct { // VirtualSize is the total size of the image including all layers it is // composed of. // - // In versions of Docker before v1.10, this field was calculated from - // the image itself and all of its parent images. Docker v1.10 and up - // store images self-contained, and no longer use a parent-chain, making - // this field an equivalent of the Size field. - // - // Deprecated: Unused in API 1.43 and up, but kept for backward compatibility with older API versions. + // Deprecated: this field is omitted in API v1.44, but kept for backward compatibility. Use Size instead. VirtualSize int64 `json:"VirtualSize,omitempty"` // GraphDriver holds information about the storage driver used to store the @@ -137,13 +133,7 @@ type ImageInspect struct { // Metadata of the image in the local cache. // // This information is local to the daemon, and not part of the image itself. - Metadata ImageMetadata -} - -// ImageMetadata contains engine-local data about the image -type ImageMetadata struct { - // LastTagTime is the date and time at which the image was last tagged. - LastTagTime time.Time `json:",omitempty"` + Metadata image.Metadata } // Container contains response of Engine API: @@ -237,148 +227,6 @@ type Version struct { BuildTime string `json:",omitempty"` } -// Commit holds the Git-commit (SHA1) that a binary was built from, as reported -// in the version-string of external tools, such as containerd, or runC. -type Commit struct { - ID string // ID is the actual commit ID of external tool. - Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time. -} - -// Info contains response of Engine API: -// GET "/info" -type Info struct { - ID string - Containers int - ContainersRunning int - ContainersPaused int - ContainersStopped int - Images int - Driver string - DriverStatus [][2]string - SystemStatus [][2]string `json:",omitempty"` // SystemStatus is only propagated by the Swarm standalone API - Plugins PluginsInfo - MemoryLimit bool - SwapLimit bool - KernelMemory bool `json:",omitempty"` // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes - KernelMemoryTCP bool `json:",omitempty"` // KernelMemoryTCP is not supported on cgroups v2. - CPUCfsPeriod bool `json:"CpuCfsPeriod"` - CPUCfsQuota bool `json:"CpuCfsQuota"` - CPUShares bool - CPUSet bool - PidsLimit bool - IPv4Forwarding bool - BridgeNfIptables bool - BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` - Debug bool - NFd int - OomKillDisable bool - NGoroutines int - SystemTime string - LoggingDriver string - CgroupDriver string - CgroupVersion string `json:",omitempty"` - NEventsListener int - KernelVersion string - OperatingSystem string - OSVersion string - OSType string - Architecture string - IndexServerAddress string - RegistryConfig *registry.ServiceConfig - NCPU int - MemTotal int64 - GenericResources []swarm.GenericResource - DockerRootDir string - HTTPProxy string `json:"HttpProxy"` - HTTPSProxy string `json:"HttpsProxy"` - NoProxy string - Name string - Labels []string - ExperimentalBuild bool - ServerVersion string - Runtimes map[string]Runtime - DefaultRuntime string - Swarm swarm.Info - // LiveRestoreEnabled determines whether containers should be kept - // running when the daemon is shutdown or upon daemon start if - // running containers are detected - LiveRestoreEnabled bool - Isolation container.Isolation - InitBinary string - ContainerdCommit Commit - RuncCommit Commit - InitCommit Commit - SecurityOptions []string - ProductLicense string `json:",omitempty"` - DefaultAddressPools []NetworkAddressPool `json:",omitempty"` - - // Warnings contains a slice of warnings that occurred while collecting - // system information. These warnings are intended to be informational - // messages for the user, and are not intended to be parsed / used for - // other purposes, as they do not have a fixed format. - Warnings []string -} - -// KeyValue holds a key/value pair -type KeyValue struct { - Key, Value string -} - -// NetworkAddressPool is a temp struct used by Info struct -type NetworkAddressPool struct { - Base string - Size int -} - -// SecurityOpt contains the name and options of a security option -type SecurityOpt struct { - Name string - Options []KeyValue -} - -// DecodeSecurityOptions decodes a security options string slice to a type safe -// SecurityOpt -func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { - so := []SecurityOpt{} - for _, opt := range opts { - // support output from a < 1.13 docker daemon - if !strings.Contains(opt, "=") { - so = append(so, SecurityOpt{Name: opt}) - continue - } - secopt := SecurityOpt{} - for _, s := range strings.Split(opt, ",") { - k, v, ok := strings.Cut(s, "=") - if !ok { - return nil, fmt.Errorf("invalid security option %q", s) - } - if k == "" || v == "" { - return nil, errors.New("invalid empty security option") - } - if k == "name" { - secopt.Name = v - continue - } - secopt.Options = append(secopt.Options, KeyValue{Key: k, Value: v}) - } - so = append(so, secopt) - } - return so, nil -} - -// PluginsInfo is a temp struct holding Plugins name -// registered with docker daemon. It is used by Info struct -type PluginsInfo struct { - // List of Volume plugins registered - Volume []string - // List of Network plugins registered - Network []string - // List of Authorization plugins registered - Authorization []string - // List of Log plugins registered - Log []string -} - // ExecStartCheck is a temp struct used by execStart // Config fields is part of ExecConfig in runconfig package type ExecStartCheck struct { @@ -491,17 +339,27 @@ type SummaryNetworkSettings struct { Networks map[string]*network.EndpointSettings } -// NetworkSettingsBase holds basic information about networks +// NetworkSettingsBase holds networking state for a container when inspecting it. type NetworkSettingsBase struct { - Bridge string // Bridge is the Bridge name the network uses(e.g. `docker0`) - SandboxID string // SandboxID uniquely represents a container's network stack - HairpinMode bool // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface - LinkLocalIPv6Address string // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix - LinkLocalIPv6PrefixLen int // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address - Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port - SandboxKey string // SandboxKey identifies the sandbox - SecondaryIPAddresses []network.Address - SecondaryIPv6Addresses []network.Address + Bridge string // Bridge contains the name of the default bridge interface iff it was set through the daemon --bridge flag. + SandboxID string // SandboxID uniquely represents a container's network stack + SandboxKey string // SandboxKey identifies the sandbox + Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port + + // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface + // + // Deprecated: This field is never set and will be removed in a future release. + HairpinMode bool + // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix + // + // Deprecated: This field is never set and will be removed in a future release. + LinkLocalIPv6Address string + // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address + // + // Deprecated: This field is never set and will be removed in a future release. + LinkLocalIPv6PrefixLen int + SecondaryIPAddresses []network.Address // Deprecated: This field is never set and will be removed in a future release. + SecondaryIPv6Addresses []network.Address // Deprecated: This field is never set and will be removed in a future release. } // DefaultNetworkSettings holds network information @@ -594,14 +452,9 @@ type EndpointResource struct { // NetworkCreate is the expected body of the "create network" http request message type NetworkCreate struct { - // Check for networks with duplicate names. - // Network is primarily keyed based on a random ID and not on the name. - // Network name is strictly a user-friendly alias to the network - // which is uniquely identified using ID. - // And there is no guaranteed way to check for duplicates. - // Option CheckDuplicate is there to provide a best effort checking of any networks - // which has the same name but it is not guaranteed to catch all name collisions. - CheckDuplicate bool + // Deprecated: CheckDuplicate is deprecated since API v1.44, but it defaults to true when sent by the client + // package to older daemons. + CheckDuplicate bool `json:",omitempty"` Driver string Scope string EnableIPv6 bool @@ -645,33 +498,6 @@ type NetworkInspectOptions struct { Verbose bool } -// Checkpoint represents the details of a checkpoint -type Checkpoint struct { - Name string // Name is the name of the checkpoint -} - -// Runtime describes an OCI runtime -type Runtime struct { - // "Legacy" runtime configuration for runc-compatible runtimes. - - Path string `json:"path,omitempty"` - Args []string `json:"runtimeArgs,omitempty"` - - // Shimv2 runtime configuration. Mutually exclusive with the legacy config above. - - Type string `json:"runtimeType,omitempty"` - Options map[string]interface{} `json:"options,omitempty"` - - // This is exposed here only for internal use - ShimConfig *ShimConfig `json:"-"` -} - -// ShimConfig is used by runtime to configure containerd shims -type ShimConfig struct { - Binary string - Opts interface{} -} - // DiskUsageObject represents an object type used for disk usage query filtering. type DiskUsageObject string @@ -697,7 +523,7 @@ type DiskUsageOptions struct { // GET "/system/df" type DiskUsage struct { LayersSize int64 - Images []*ImageSummary + Images []*image.Summary Containers []*Container Volumes []*volume.Volume BuildCache []*BuildCache @@ -721,7 +547,7 @@ type VolumesPruneReport struct { // ImagesPruneReport contains the response for Engine API: // POST "/images/prune" type ImagesPruneReport struct { - ImagesDeleted []ImageDeleteResponseItem + ImagesDeleted []image.DeleteResponse SpaceReclaimed uint64 } diff --git a/vendor/github.com/docker/docker/api/types/types_deprecated.go b/vendor/github.com/docker/docker/api/types/types_deprecated.go new file mode 100644 index 000000000..e332a7bb6 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/types_deprecated.go @@ -0,0 +1,138 @@ +package types + +import ( + "github.com/docker/docker/api/types/checkpoint" + "github.com/docker/docker/api/types/container" + "github.com/docker/docker/api/types/image" + "github.com/docker/docker/api/types/swarm" + "github.com/docker/docker/api/types/system" +) + +// CheckpointCreateOptions holds parameters to create a checkpoint from a container. +// +// Deprecated: use [checkpoint.CreateOptions]. +type CheckpointCreateOptions = checkpoint.CreateOptions + +// CheckpointListOptions holds parameters to list checkpoints for a container +// +// Deprecated: use [checkpoint.ListOptions]. +type CheckpointListOptions = checkpoint.ListOptions + +// CheckpointDeleteOptions holds parameters to delete a checkpoint from a container +// +// Deprecated: use [checkpoint.DeleteOptions]. +type CheckpointDeleteOptions = checkpoint.DeleteOptions + +// Checkpoint represents the details of a checkpoint when listing endpoints. +// +// Deprecated: use [checkpoint.Summary]. +type Checkpoint = checkpoint.Summary + +// Info contains response of Engine API: +// GET "/info" +// +// Deprecated: use [system.Info]. +type Info = system.Info + +// Commit holds the Git-commit (SHA1) that a binary was built from, as reported +// in the version-string of external tools, such as containerd, or runC. +// +// Deprecated: use [system.Commit]. +type Commit = system.Commit + +// PluginsInfo is a temp struct holding Plugins name +// registered with docker daemon. It is used by [system.Info] struct +// +// Deprecated: use [system.PluginsInfo]. +type PluginsInfo = system.PluginsInfo + +// NetworkAddressPool is a temp struct used by [system.Info] struct. +// +// Deprecated: use [system.NetworkAddressPool]. +type NetworkAddressPool = system.NetworkAddressPool + +// Runtime describes an OCI runtime. +// +// Deprecated: use [system.Runtime]. +type Runtime = system.Runtime + +// SecurityOpt contains the name and options of a security option. +// +// Deprecated: use [system.SecurityOpt]. +type SecurityOpt = system.SecurityOpt + +// KeyValue holds a key/value pair. +// +// Deprecated: use [system.KeyValue]. +type KeyValue = system.KeyValue + +// ImageDeleteResponseItem image delete response item. +// +// Deprecated: use [image.DeleteResponse]. +type ImageDeleteResponseItem = image.DeleteResponse + +// ImageSummary image summary. +// +// Deprecated: use [image.Summary]. +type ImageSummary = image.Summary + +// ImageMetadata contains engine-local data about the image. +// +// Deprecated: use [image.Metadata]. +type ImageMetadata = image.Metadata + +// ServiceCreateResponse contains the information returned to a client +// on the creation of a new service. +// +// Deprecated: use [swarm.ServiceCreateResponse]. +type ServiceCreateResponse = swarm.ServiceCreateResponse + +// ServiceUpdateResponse service update response. +// +// Deprecated: use [swarm.ServiceUpdateResponse]. +type ServiceUpdateResponse = swarm.ServiceUpdateResponse + +// ContainerStartOptions holds parameters to start containers. +// +// Deprecated: use [container.StartOptions]. +type ContainerStartOptions = container.StartOptions + +// ResizeOptions holds parameters to resize a TTY. +// It can be used to resize container TTYs and +// exec process TTYs too. +// +// Deprecated: use [container.ResizeOptions]. +type ResizeOptions = container.ResizeOptions + +// ContainerAttachOptions holds parameters to attach to a container. +// +// Deprecated: use [container.AttachOptions]. +type ContainerAttachOptions = container.AttachOptions + +// ContainerCommitOptions holds parameters to commit changes into a container. +// +// Deprecated: use [container.CommitOptions]. +type ContainerCommitOptions = container.CommitOptions + +// ContainerListOptions holds parameters to list containers with. +// +// Deprecated: use [container.ListOptions]. +type ContainerListOptions = container.ListOptions + +// ContainerLogsOptions holds parameters to filter logs with. +// +// Deprecated: use [container.LogsOptions]. +type ContainerLogsOptions = container.LogsOptions + +// ContainerRemoveOptions holds parameters to remove containers. +// +// Deprecated: use [container.RemoveOptions]. +type ContainerRemoveOptions = container.RemoveOptions + +// DecodeSecurityOptions decodes a security options string slice to a type safe +// [system.SecurityOpt]. +// +// Deprecated: use [system.DecodeSecurityOptions]. +func DecodeSecurityOptions(opts []string) ([]system.SecurityOpt, error) { + return system.DecodeSecurityOptions(opts) +} diff --git a/vendor/github.com/docker/docker/client/README.md b/vendor/github.com/docker/docker/client/README.md index 992f18117..f8af3ab90 100644 --- a/vendor/github.com/docker/docker/client/README.md +++ b/vendor/github.com/docker/docker/client/README.md @@ -1,8 +1,10 @@ # Go client for the Docker Engine API -The `docker` command uses this package to communicate with the daemon. It can also be used by your own Go applications to do anything the command-line interface does – running containers, pulling images, managing swarms, etc. +The `docker` command uses this package to communicate with the daemon. It can +also be used by your own Go applications to do anything the command-line +interface does – running containers, pulling images, managing swarms, etc. -For example, to list running containers (the equivalent of `docker ps`): +For example, to list all containers (the equivalent of `docker ps --all`): ```go package main @@ -11,25 +13,26 @@ import ( "context" "fmt" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" ) func main() { - cli, err := client.NewClientWithOpts(client.FromEnv) + apiClient, err := client.NewClientWithOpts(client.FromEnv) if err != nil { panic(err) } + defer apiClient.Close() - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) + containers, err := apiClient.ContainerList(context.Background(), container.ListOptions{All: true}) if err != nil { panic(err) } - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) + for _, ctr := range containers { + fmt.Printf("%s %s (status: %s)\n", ctr.ID, ctr.Image, ctr.Status) } } ``` -[Full documentation is available on GoDoc.](https://godoc.org/github.com/docker/docker/client) +[Full documentation is available on pkg.go.dev.](https://pkg.go.dev/github.com/docker/docker/client) diff --git a/vendor/github.com/docker/docker/client/build_prune.go b/vendor/github.com/docker/docker/client/build_prune.go index 2b6606236..1a830f413 100644 --- a/vendor/github.com/docker/docker/client/build_prune.go +++ b/vendor/github.com/docker/docker/client/build_prune.go @@ -13,7 +13,7 @@ import ( // BuildCachePrune requests the daemon to delete unused cache data func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) { - if err := cli.NewVersionError("1.31", "build prune"); err != nil { + if err := cli.NewVersionError(ctx, "1.31", "build prune"); err != nil { return nil, err } diff --git a/vendor/github.com/docker/docker/client/checkpoint_create.go b/vendor/github.com/docker/docker/client/checkpoint_create.go index 921024fe4..9746d288d 100644 --- a/vendor/github.com/docker/docker/client/checkpoint_create.go +++ b/vendor/github.com/docker/docker/client/checkpoint_create.go @@ -3,11 +3,11 @@ package client // import "github.com/docker/docker/client" import ( "context" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/checkpoint" ) // CheckpointCreate creates a checkpoint from the given container with the given name -func (cli *Client) CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error { +func (cli *Client) CheckpointCreate(ctx context.Context, container string, options checkpoint.CreateOptions) error { resp, err := cli.post(ctx, "/containers/"+container+"/checkpoints", nil, options, nil) ensureReaderClosed(resp) return err diff --git a/vendor/github.com/docker/docker/client/checkpoint_delete.go b/vendor/github.com/docker/docker/client/checkpoint_delete.go index 54f55fa76..b968c2b23 100644 --- a/vendor/github.com/docker/docker/client/checkpoint_delete.go +++ b/vendor/github.com/docker/docker/client/checkpoint_delete.go @@ -4,11 +4,11 @@ import ( "context" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/checkpoint" ) // CheckpointDelete deletes the checkpoint with the given name from the given container -func (cli *Client) CheckpointDelete(ctx context.Context, containerID string, options types.CheckpointDeleteOptions) error { +func (cli *Client) CheckpointDelete(ctx context.Context, containerID string, options checkpoint.DeleteOptions) error { query := url.Values{} if options.CheckpointDir != "" { query.Set("dir", options.CheckpointDir) diff --git a/vendor/github.com/docker/docker/client/checkpoint_list.go b/vendor/github.com/docker/docker/client/checkpoint_list.go index 39cfb959f..8feb1f3f7 100644 --- a/vendor/github.com/docker/docker/client/checkpoint_list.go +++ b/vendor/github.com/docker/docker/client/checkpoint_list.go @@ -5,12 +5,12 @@ import ( "encoding/json" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/checkpoint" ) // CheckpointList returns the checkpoints of the given container in the docker host -func (cli *Client) CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) { - var checkpoints []types.Checkpoint +func (cli *Client) CheckpointList(ctx context.Context, container string, options checkpoint.ListOptions) ([]checkpoint.Summary, error) { + var checkpoints []checkpoint.Summary query := url.Values{} if options.CheckpointDir != "" { diff --git a/vendor/github.com/docker/docker/client/client.go b/vendor/github.com/docker/docker/client/client.go index 54fa36cca..0b496b0fa 100644 --- a/vendor/github.com/docker/docker/client/client.go +++ b/vendor/github.com/docker/docker/client/client.go @@ -19,7 +19,7 @@ For example, to list running containers (the equivalent of "docker ps"): "context" "fmt" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" ) @@ -29,13 +29,13 @@ For example, to list running containers (the equivalent of "docker ps"): panic(err) } - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) + containers, err := cli.ContainerList(context.Background(), container.ListOptions{}) if err != nil { panic(err) } - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) + for _, ctr := range containers { + fmt.Printf("%s %s\n", ctr.ID, ctr.Image) } } */ @@ -43,17 +43,21 @@ package client // import "github.com/docker/docker/client" import ( "context" + "crypto/tls" "net" "net/http" "net/url" "path" "strings" + "time" "github.com/docker/docker/api" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions" "github.com/docker/go-connections/sockets" "github.com/pkg/errors" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + "go.opentelemetry.io/otel/trace" ) // DummyHost is a hostname used for local communication. @@ -86,8 +90,12 @@ import ( // [Go stdlib]: https://github.com/golang/go/blob/6244b1946bc2101b01955468f1be502dbadd6807/src/net/http/transport.go#L558-L569 const DummyHost = "api.moby.localhost" -// ErrRedirect is the error returned by checkRedirect when the request is non-GET. -var ErrRedirect = errors.New("unexpected redirect in response") +// fallbackAPIVersion is the version to fallback to if API-version negotiation +// fails. This version is the highest version of the API before API-version +// negotiation was introduced. If negotiation fails (or no API version was +// included in the API response), we assume the API server uses the most +// recent version before negotiation was introduced. +const fallbackAPIVersion = "1.24" // Client is the API client that performs all operations // against a docker server. @@ -106,7 +114,12 @@ type Client struct { client *http.Client // version of the server to talk to. version string - // custom http headers configured by users. + // userAgent is the User-Agent header to use for HTTP requests. It takes + // precedence over User-Agent headers set in customHTTPHeaders, and other + // header variables. When set to an empty string, the User-Agent header + // is removed, and no header is sent. + userAgent *string + // custom HTTP headers configured by users. customHTTPHeaders map[string]string // manualOverride is set to true when the version was set by users. manualOverride bool @@ -119,22 +132,33 @@ type Client struct { // negotiated indicates that API version negotiation took place negotiated bool + + tp trace.TracerProvider + + // When the client transport is an *http.Transport (default) we need to do some extra things (like closing idle connections). + // Store the original transport as the http.Client transport will be wrapped with tracing libs. + baseTransport *http.Transport } -// CheckRedirect specifies the policy for dealing with redirect responses: -// If the request is non-GET return ErrRedirect, otherwise use the last response. +// ErrRedirect is the error returned by checkRedirect when the request is non-GET. +var ErrRedirect = errors.New("unexpected redirect in response") + +// CheckRedirect specifies the policy for dealing with redirect responses. It +// can be set on [http.Client.CheckRedirect] to prevent HTTP redirects for +// non-GET requests. It returns an [ErrRedirect] for non-GET request, otherwise +// returns a [http.ErrUseLastResponse], which is special-cased by http.Client +// to use the last response. // -// Go 1.8 changes behavior for HTTP redirects (specifically 301, 307, and 308) -// in the client. The Docker client (and by extension docker API client) can be -// made to send a request like POST /containers//start where what would normally -// be in the name section of the URL is empty. This triggers an HTTP 301 from -// the daemon. +// Go 1.8 changed behavior for HTTP redirects (specifically 301, 307, and 308) +// in the client. The client (and by extension API client) can be made to send +// a request like "POST /containers//start" where what would normally be in the +// name section of the URL is empty. This triggers an HTTP 301 from the daemon. // -// In go 1.8 this 301 will be converted to a GET request, and ends up getting +// In go 1.8 this 301 is converted to a GET request, and ends up getting // a 404 from the daemon. This behavior change manifests in the client in that // before, the 301 was not followed and the client did not generate an error, -// but now results in a message like Error response from daemon: page not found. -func CheckRedirect(req *http.Request, via []*http.Request) error { +// but now results in a message like "Error response from daemon: page not found". +func CheckRedirect(_ *http.Request, via []*http.Request) error { if via[0].Method == http.MethodGet { return http.ErrUseLastResponse } @@ -145,11 +169,11 @@ func CheckRedirect(req *http.Request, via []*http.Request) error { // default API host and version. It also initializes the custom HTTP headers to // add to each request. // -// It takes an optional list of Opt functional arguments, which are applied in +// It takes an optional list of [Opt] functional arguments, which are applied in // the order they're provided, which allows modifying the defaults when creating // the client. For example, the following initializes a client that configures -// itself with values from environment variables (client.FromEnv), and has -// automatic API version negotiation enabled (client.WithAPIVersionNegotiation()). +// itself with values from environment variables ([FromEnv]), and has automatic +// API version negotiation enabled ([WithAPIVersionNegotiation]). // // cli, err := client.NewClientWithOpts( // client.FromEnv, @@ -179,23 +203,43 @@ func NewClientWithOpts(ops ...Opt) (*Client, error) { } } + if tr, ok := c.client.Transport.(*http.Transport); ok { + // Store the base transport before we wrap it in tracing libs below + // This is used, as an example, to close idle connections when the client is closed + c.baseTransport = tr + } + if c.scheme == "" { - c.scheme = "http" - - tlsConfig := resolveTLSConfig(c.client.Transport) - if tlsConfig != nil { - // TODO(stevvooe): This isn't really the right way to write clients in Go. - // `NewClient` should probably only take an `*http.Client` and work from there. - // Unfortunately, the model of having a host-ish/url-thingy as the connection - // string has us confusing protocol and transport layers. We continue doing - // this to avoid breaking existing clients but this should be addressed. + // TODO(stevvooe): This isn't really the right way to write clients in Go. + // `NewClient` should probably only take an `*http.Client` and work from there. + // Unfortunately, the model of having a host-ish/url-thingy as the connection + // string has us confusing protocol and transport layers. We continue doing + // this to avoid breaking existing clients but this should be addressed. + if c.tlsConfig() != nil { c.scheme = "https" + } else { + c.scheme = "http" } } + c.client.Transport = otelhttp.NewTransport( + c.client.Transport, + otelhttp.WithTracerProvider(c.tp), + otelhttp.WithSpanNameFormatter(func(_ string, req *http.Request) string { + return req.Method + " " + req.URL.Path + }), + ) + return c, nil } +func (cli *Client) tlsConfig() *tls.Config { + if cli.baseTransport == nil { + return nil + } + return cli.baseTransport.TLSClientConfig +} + func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) { transport := &http.Transport{} err := sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) @@ -210,19 +254,28 @@ func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) { // Close the transport used by the client func (cli *Client) Close() error { - if t, ok := cli.client.Transport.(*http.Transport); ok { - t.CloseIdleConnections() + if cli.baseTransport != nil { + cli.baseTransport.CloseIdleConnections() + return nil } return nil } -// getAPIPath returns the versioned request path to call the api. -// It appends the query parameters to the path if they are not empty. -func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) string { - var apiPath string +// checkVersion manually triggers API version negotiation (if configured). +// This allows for version-dependent code to use the same version as will +// be negotiated when making the actual requests, and for which cases +// we cannot do the negotiation lazily. +func (cli *Client) checkVersion(ctx context.Context) { if cli.negotiateVersion && !cli.negotiated { cli.NegotiateAPIVersion(ctx) } +} + +// getAPIPath returns the versioned request path to call the API. +// It appends the query parameters to the path if they are not empty. +func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) string { + var apiPath string + cli.checkVersion(ctx) if cli.version != "" { v := strings.TrimPrefix(cli.version, "v") apiPath = path.Join(cli.basePath, "/v"+v, p) @@ -244,8 +297,8 @@ func (cli *Client) ClientVersion() string { // by the client, it uses the client's maximum version. // // If a manual override is in place, either through the "DOCKER_API_VERSION" -// (EnvOverrideAPIVersion) environment variable, or if the client is initialized -// with a fixed version (WithVersion(xx)), no negotiation is performed. +// ([EnvOverrideAPIVersion]) environment variable, or if the client is initialized +// with a fixed version ([WithVersion]), no negotiation is performed. // // If the API server's ping response does not contain an API version, or if the // client did not get a successful ping response, it assumes it is connected with @@ -265,8 +318,8 @@ func (cli *Client) NegotiateAPIVersion(ctx context.Context) { // version. // // If a manual override is in place, either through the "DOCKER_API_VERSION" -// (EnvOverrideAPIVersion) environment variable, or if the client is initialized -// with a fixed version (WithVersion(xx)), no negotiation is performed. +// ([EnvOverrideAPIVersion]) environment variable, or if the client is initialized +// with a fixed version ([WithVersion]), no negotiation is performed. // // If the API server's ping response does not contain an API version, we assume // we are connected with an old daemon without API version negotiation support, @@ -283,7 +336,7 @@ func (cli *Client) NegotiateAPIVersionPing(pingResponse types.Ping) { func (cli *Client) negotiateAPIVersionPing(pingResponse types.Ping) { // default to the latest version before versioning headers existed if pingResponse.APIVersion == "" { - pingResponse.APIVersion = "1.24" + pingResponse.APIVersion = fallbackAPIVersion } // if the client is not initialized with a version, start with the latest supported version @@ -338,17 +391,40 @@ func ParseHostURL(host string) (*url.URL, error) { }, nil } +func (cli *Client) dialerFromTransport() func(context.Context, string, string) (net.Conn, error) { + if cli.baseTransport == nil || cli.baseTransport.DialContext == nil { + return nil + } + + if cli.baseTransport.TLSClientConfig != nil { + // When using a tls config we don't use the configured dialer but instead a fallback dialer... + // Note: It seems like this should use the normal dialer and wrap the returned net.Conn in a tls.Conn + // I honestly don't know why it doesn't do that, but it doesn't and such a change is entirely unrelated to the change in this commit. + return nil + } + return cli.baseTransport.DialContext +} + // Dialer returns a dialer for a raw stream connection, with an HTTP/1.1 header, -// that can be used for proxying the daemon connection. +// that can be used for proxying the daemon connection. It is used by +// ["docker dial-stdio"]. // -// Used by `docker dial-stdio` (docker/cli#889). +// ["docker dial-stdio"]: https://github.com/docker/cli/pull/1014 func (cli *Client) Dialer() func(context.Context) (net.Conn, error) { return func(ctx context.Context) (net.Conn, error) { - if transport, ok := cli.client.Transport.(*http.Transport); ok { - if transport.DialContext != nil && transport.TLSClientConfig == nil { - return transport.DialContext(ctx, cli.proto, cli.addr) + if dialFn := cli.dialerFromTransport(); dialFn != nil { + return dialFn(ctx, cli.proto, cli.addr) + } + switch cli.proto { + case "unix": + return net.Dial(cli.proto, cli.addr) + case "npipe": + return sockets.DialPipe(cli.addr, 32*time.Second) + default: + if tlsConfig := cli.tlsConfig(); tlsConfig != nil { + return tls.Dial(cli.proto, cli.addr, tlsConfig) } + return net.Dial(cli.proto, cli.addr) } - return fallbackDial(cli.proto, cli.addr, resolveTLSConfig(cli.client.Transport)) } } diff --git a/vendor/github.com/docker/docker/client/client_unix.go b/vendor/github.com/docker/docker/client/client_unix.go index 319b738d3..9fe78ea43 100644 --- a/vendor/github.com/docker/docker/client/client_unix.go +++ b/vendor/github.com/docker/docker/client/client_unix.go @@ -1,5 +1,4 @@ //go:build !windows -// +build !windows package client // import "github.com/docker/docker/client" diff --git a/vendor/github.com/docker/docker/client/config_create.go b/vendor/github.com/docker/docker/client/config_create.go index f6b1881fc..3deb4a8e2 100644 --- a/vendor/github.com/docker/docker/client/config_create.go +++ b/vendor/github.com/docker/docker/client/config_create.go @@ -11,7 +11,7 @@ import ( // ConfigCreate creates a new config. func (cli *Client) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) { var response types.ConfigCreateResponse - if err := cli.NewVersionError("1.30", "config create"); err != nil { + if err := cli.NewVersionError(ctx, "1.30", "config create"); err != nil { return response, err } resp, err := cli.post(ctx, "/configs/create", nil, config, nil) diff --git a/vendor/github.com/docker/docker/client/config_inspect.go b/vendor/github.com/docker/docker/client/config_inspect.go index 9be7882c3..2c6c7cb36 100644 --- a/vendor/github.com/docker/docker/client/config_inspect.go +++ b/vendor/github.com/docker/docker/client/config_inspect.go @@ -14,7 +14,7 @@ func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.C if id == "" { return swarm.Config{}, nil, objectNotFoundError{object: "config", id: id} } - if err := cli.NewVersionError("1.30", "config inspect"); err != nil { + if err := cli.NewVersionError(ctx, "1.30", "config inspect"); err != nil { return swarm.Config{}, nil, err } resp, err := cli.get(ctx, "/configs/"+id, nil, nil) diff --git a/vendor/github.com/docker/docker/client/config_list.go b/vendor/github.com/docker/docker/client/config_list.go index 565acc6e2..14dd3813e 100644 --- a/vendor/github.com/docker/docker/client/config_list.go +++ b/vendor/github.com/docker/docker/client/config_list.go @@ -12,7 +12,7 @@ import ( // ConfigList returns the list of configs. func (cli *Client) ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) { - if err := cli.NewVersionError("1.30", "config list"); err != nil { + if err := cli.NewVersionError(ctx, "1.30", "config list"); err != nil { return nil, err } query := url.Values{} diff --git a/vendor/github.com/docker/docker/client/config_remove.go b/vendor/github.com/docker/docker/client/config_remove.go index 24b94e9c1..d05b0113a 100644 --- a/vendor/github.com/docker/docker/client/config_remove.go +++ b/vendor/github.com/docker/docker/client/config_remove.go @@ -4,7 +4,7 @@ import "context" // ConfigRemove removes a config. func (cli *Client) ConfigRemove(ctx context.Context, id string) error { - if err := cli.NewVersionError("1.30", "config remove"); err != nil { + if err := cli.NewVersionError(ctx, "1.30", "config remove"); err != nil { return err } resp, err := cli.delete(ctx, "/configs/"+id, nil, nil) diff --git a/vendor/github.com/docker/docker/client/config_update.go b/vendor/github.com/docker/docker/client/config_update.go index 1ac298543..6995861df 100644 --- a/vendor/github.com/docker/docker/client/config_update.go +++ b/vendor/github.com/docker/docker/client/config_update.go @@ -9,7 +9,7 @@ import ( // ConfigUpdate attempts to update a config func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { - if err := cli.NewVersionError("1.30", "config update"); err != nil { + if err := cli.NewVersionError(ctx, "1.30", "config update"); err != nil { return err } query := url.Values{} diff --git a/vendor/github.com/docker/docker/client/container_attach.go b/vendor/github.com/docker/docker/client/container_attach.go index ba92117d3..6a32e5f66 100644 --- a/vendor/github.com/docker/docker/client/container_attach.go +++ b/vendor/github.com/docker/docker/client/container_attach.go @@ -2,9 +2,11 @@ package client // import "github.com/docker/docker/client" import ( "context" + "net/http" "net/url" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" ) // ContainerAttach attaches a connection to a container in the server. @@ -31,7 +33,7 @@ import ( // // You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this // stream. -func (cli *Client) ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) { +func (cli *Client) ContainerAttach(ctx context.Context, container string, options container.AttachOptions) (types.HijackedResponse, error) { query := url.Values{} if options.Stream { query.Set("stream", "1") @@ -52,8 +54,7 @@ func (cli *Client) ContainerAttach(ctx context.Context, container string, option query.Set("logs", "1") } - headers := map[string][]string{ + return cli.postHijacked(ctx, "/containers/"+container+"/attach", query, nil, http.Header{ "Content-Type": {"text/plain"}, - } - return cli.postHijacked(ctx, "/containers/"+container+"/attach", query, nil, headers) + }) } diff --git a/vendor/github.com/docker/docker/client/container_commit.go b/vendor/github.com/docker/docker/client/container_commit.go index cd7f76346..26b3f0915 100644 --- a/vendor/github.com/docker/docker/client/container_commit.go +++ b/vendor/github.com/docker/docker/client/container_commit.go @@ -6,12 +6,13 @@ import ( "errors" "net/url" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" ) // ContainerCommit applies changes to a container and creates a new tagged image. -func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) { +func (cli *Client) ContainerCommit(ctx context.Context, container string, options container.CommitOptions) (types.IDResponse, error) { var repository, tag string if options.Reference != "" { ref, err := reference.ParseNormalizedNamed(options.Reference) diff --git a/vendor/github.com/docker/docker/client/container_create.go b/vendor/github.com/docker/docker/client/container_create.go index 193a2bb56..409f5b492 100644 --- a/vendor/github.com/docker/docker/client/container_create.go +++ b/vendor/github.com/docker/docker/client/container_create.go @@ -23,10 +23,23 @@ type configWrapper struct { func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error) { var response container.CreateResponse - if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + + if err := cli.NewVersionError(ctx, "1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil { + return response, err + } + if err := cli.NewVersionError(ctx, "1.41", "specify container image platform"); platform != nil && err != nil { return response, err } - if err := cli.NewVersionError("1.41", "specify container image platform"); platform != nil && err != nil { + if err := cli.NewVersionError(ctx, "1.44", "specify health-check start interval"); config != nil && config.Healthcheck != nil && config.Healthcheck.StartInterval != 0 && err != nil { + return response, err + } + if err := cli.NewVersionError(ctx, "1.44", "specify mac-address per network"); hasEndpointSpecificMacAddress(networkingConfig) && err != nil { return response, err } @@ -45,6 +58,11 @@ func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config } } + // Since API 1.44, the container-wide MacAddress is deprecated and will trigger a WARNING if it's specified. + if versions.GreaterThanOrEqualTo(cli.ClientVersion(), "1.44") { + config.MacAddress = "" //nolint:staticcheck // ignore SA1019: field is deprecated, but still used on API < v1.44. + } + query := url.Values{} if p := formatPlatform(platform); p != "" { query.Set("platform", p) @@ -81,3 +99,16 @@ func formatPlatform(platform *ocispec.Platform) string { } return path.Join(platform.OS, platform.Architecture, platform.Variant) } + +// hasEndpointSpecificMacAddress checks whether one of the endpoint in networkingConfig has a MacAddress defined. +func hasEndpointSpecificMacAddress(networkingConfig *network.NetworkingConfig) bool { + if networkingConfig == nil { + return false + } + for _, endpoint := range networkingConfig.EndpointsConfig { + if endpoint.MacAddress != "" { + return true + } + } + return false +} diff --git a/vendor/github.com/docker/docker/client/container_exec.go b/vendor/github.com/docker/docker/client/container_exec.go index 6a2cb006f..3fff0c828 100644 --- a/vendor/github.com/docker/docker/client/container_exec.go +++ b/vendor/github.com/docker/docker/client/container_exec.go @@ -3,6 +3,7 @@ package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" + "net/http" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions" @@ -12,7 +13,14 @@ import ( func (cli *Client) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) { var response types.IDResponse - if err := cli.NewVersionError("1.25", "env"); len(config.Env) != 0 && err != nil { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + + if err := cli.NewVersionError(ctx, "1.25", "env"); len(config.Env) != 0 && err != nil { return response, err } if versions.LessThan(cli.ClientVersion(), "1.42") { @@ -46,10 +54,9 @@ func (cli *Client) ContainerExecAttach(ctx context.Context, execID string, confi if versions.LessThan(cli.ClientVersion(), "1.42") { config.ConsoleSize = nil } - headers := map[string][]string{ + return cli.postHijacked(ctx, "/exec/"+execID+"/start", nil, config, http.Header{ "Content-Type": {"application/json"}, - } - return cli.postHijacked(ctx, "/exec/"+execID+"/start", nil, config, headers) + }) } // ContainerExecInspect returns information about a specific exec process on the docker host. diff --git a/vendor/github.com/docker/docker/client/container_list.go b/vendor/github.com/docker/docker/client/container_list.go index bd491b3db..782e1b3c6 100644 --- a/vendor/github.com/docker/docker/client/container_list.go +++ b/vendor/github.com/docker/docker/client/container_list.go @@ -7,11 +7,12 @@ import ( "strconv" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" ) // ContainerList returns the list of containers in the docker host. -func (cli *Client) ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) { +func (cli *Client) ContainerList(ctx context.Context, options container.ListOptions) ([]types.Container, error) { query := url.Values{} if options.All { @@ -37,7 +38,6 @@ func (cli *Client) ContainerList(ctx context.Context, options types.ContainerLis if options.Filters.Len() > 0 { //nolint:staticcheck // ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - if err != nil { return nil, err } diff --git a/vendor/github.com/docker/docker/client/container_logs.go b/vendor/github.com/docker/docker/client/container_logs.go index 9bdf2b0fa..61197d840 100644 --- a/vendor/github.com/docker/docker/client/container_logs.go +++ b/vendor/github.com/docker/docker/client/container_logs.go @@ -6,7 +6,7 @@ import ( "net/url" "time" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" timetypes "github.com/docker/docker/api/types/time" "github.com/pkg/errors" ) @@ -33,7 +33,7 @@ import ( // // You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this // stream. -func (cli *Client) ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) { +func (cli *Client) ContainerLogs(ctx context.Context, container string, options container.LogsOptions) (io.ReadCloser, error) { query := url.Values{} if options.ShowStdout { query.Set("stdout", "1") diff --git a/vendor/github.com/docker/docker/client/container_prune.go b/vendor/github.com/docker/docker/client/container_prune.go index 04383deaa..ca5092384 100644 --- a/vendor/github.com/docker/docker/client/container_prune.go +++ b/vendor/github.com/docker/docker/client/container_prune.go @@ -13,7 +13,7 @@ import ( func (cli *Client) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) { var report types.ContainersPruneReport - if err := cli.NewVersionError("1.25", "container prune"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "container prune"); err != nil { return report, err } diff --git a/vendor/github.com/docker/docker/client/container_remove.go b/vendor/github.com/docker/docker/client/container_remove.go index c21de609b..39f7b106a 100644 --- a/vendor/github.com/docker/docker/client/container_remove.go +++ b/vendor/github.com/docker/docker/client/container_remove.go @@ -4,11 +4,11 @@ import ( "context" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" ) // ContainerRemove kills and removes a container from the docker host. -func (cli *Client) ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error { +func (cli *Client) ContainerRemove(ctx context.Context, containerID string, options container.RemoveOptions) error { query := url.Values{} if options.RemoveVolumes { query.Set("v", "1") diff --git a/vendor/github.com/docker/docker/client/container_resize.go b/vendor/github.com/docker/docker/client/container_resize.go index a9d4c0c79..5cfd01d47 100644 --- a/vendor/github.com/docker/docker/client/container_resize.go +++ b/vendor/github.com/docker/docker/client/container_resize.go @@ -5,16 +5,16 @@ import ( "net/url" "strconv" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" ) // ContainerResize changes the size of the tty for a container. -func (cli *Client) ContainerResize(ctx context.Context, containerID string, options types.ResizeOptions) error { +func (cli *Client) ContainerResize(ctx context.Context, containerID string, options container.ResizeOptions) error { return cli.resize(ctx, "/containers/"+containerID, options.Height, options.Width) } // ContainerExecResize changes the size of the tty for an exec process running inside a container. -func (cli *Client) ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error { +func (cli *Client) ContainerExecResize(ctx context.Context, execID string, options container.ResizeOptions) error { return cli.resize(ctx, "/exec/"+execID, options.Height, options.Width) } diff --git a/vendor/github.com/docker/docker/client/container_restart.go b/vendor/github.com/docker/docker/client/container_restart.go index 1e0ad9998..825d3e4e9 100644 --- a/vendor/github.com/docker/docker/client/container_restart.go +++ b/vendor/github.com/docker/docker/client/container_restart.go @@ -17,8 +17,16 @@ func (cli *Client) ContainerRestart(ctx context.Context, containerID string, opt if options.Timeout != nil { query.Set("t", strconv.Itoa(*options.Timeout)) } - if options.Signal != "" && versions.GreaterThanOrEqualTo(cli.version, "1.42") { - query.Set("signal", options.Signal) + if options.Signal != "" { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + if versions.GreaterThanOrEqualTo(cli.version, "1.42") { + query.Set("signal", options.Signal) + } } resp, err := cli.post(ctx, "/containers/"+containerID+"/restart", query, nil, nil) ensureReaderClosed(resp) diff --git a/vendor/github.com/docker/docker/client/container_start.go b/vendor/github.com/docker/docker/client/container_start.go index c2e0b15dc..33ba85f24 100644 --- a/vendor/github.com/docker/docker/client/container_start.go +++ b/vendor/github.com/docker/docker/client/container_start.go @@ -4,11 +4,11 @@ import ( "context" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" ) // ContainerStart sends a request to the docker daemon to start a container. -func (cli *Client) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error { +func (cli *Client) ContainerStart(ctx context.Context, containerID string, options container.StartOptions) error { query := url.Values{} if len(options.CheckpointID) != 0 { query.Set("checkpoint", options.CheckpointID) diff --git a/vendor/github.com/docker/docker/client/container_stats.go b/vendor/github.com/docker/docker/client/container_stats.go index 0a6488dde..3fabb75f3 100644 --- a/vendor/github.com/docker/docker/client/container_stats.go +++ b/vendor/github.com/docker/docker/client/container_stats.go @@ -21,8 +21,10 @@ func (cli *Client) ContainerStats(ctx context.Context, containerID string, strea return types.ContainerStats{}, err } - osType := getDockerOS(resp.header.Get("Server")) - return types.ContainerStats{Body: resp.body, OSType: osType}, err + return types.ContainerStats{ + Body: resp.body, + OSType: getDockerOS(resp.header.Get("Server")), + }, nil } // ContainerStatsOneShot gets a single stat entry from a container. @@ -37,6 +39,8 @@ func (cli *Client) ContainerStatsOneShot(ctx context.Context, containerID string return types.ContainerStats{}, err } - osType := getDockerOS(resp.header.Get("Server")) - return types.ContainerStats{Body: resp.body, OSType: osType}, err + return types.ContainerStats{ + Body: resp.body, + OSType: getDockerOS(resp.header.Get("Server")), + }, nil } diff --git a/vendor/github.com/docker/docker/client/container_stop.go b/vendor/github.com/docker/docker/client/container_stop.go index 2a43ce227..ac0cab69d 100644 --- a/vendor/github.com/docker/docker/client/container_stop.go +++ b/vendor/github.com/docker/docker/client/container_stop.go @@ -21,8 +21,16 @@ func (cli *Client) ContainerStop(ctx context.Context, containerID string, option if options.Timeout != nil { query.Set("t", strconv.Itoa(*options.Timeout)) } - if options.Signal != "" && versions.GreaterThanOrEqualTo(cli.version, "1.42") { - query.Set("signal", options.Signal) + if options.Signal != "" { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + if versions.GreaterThanOrEqualTo(cli.version, "1.42") { + query.Set("signal", options.Signal) + } } resp, err := cli.post(ctx, "/containers/"+containerID+"/stop", query, nil, nil) ensureReaderClosed(resp) diff --git a/vendor/github.com/docker/docker/client/container_wait.go b/vendor/github.com/docker/docker/client/container_wait.go index 2375eb1e8..b8d3bdef0 100644 --- a/vendor/github.com/docker/docker/client/container_wait.go +++ b/vendor/github.com/docker/docker/client/container_wait.go @@ -30,6 +30,12 @@ const containerWaitErrorMsgLimit = 2 * 1024 /* Max: 2KiB */ // synchronize ContainerWait with other calls, such as specifying a // "next-exit" condition before issuing a ContainerStart request. func (cli *Client) ContainerWait(ctx context.Context, containerID string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error) { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) if versions.LessThan(cli.ClientVersion(), "1.30") { return cli.legacyContainerWait(ctx, containerID) } @@ -66,8 +72,12 @@ func (cli *Client) ContainerWait(ctx context.Context, containerID string, condit // // If there's a JSON parsing error, read the real error message // off the body and send it to the client. - _, _ = io.ReadAll(io.LimitReader(stream, containerWaitErrorMsgLimit)) - errC <- errors.New(responseText.String()) + if errors.As(err, new(*json.SyntaxError)) { + _, _ = io.ReadAll(io.LimitReader(stream, containerWaitErrorMsgLimit)) + errC <- errors.New(responseText.String()) + } else { + errC <- err + } return } diff --git a/vendor/github.com/docker/docker/client/distribution_inspect.go b/vendor/github.com/docker/docker/client/distribution_inspect.go index efab066d3..68ef31b78 100644 --- a/vendor/github.com/docker/docker/client/distribution_inspect.go +++ b/vendor/github.com/docker/docker/client/distribution_inspect.go @@ -3,6 +3,7 @@ package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" + "net/http" "net/url" "github.com/docker/docker/api/types/registry" @@ -16,13 +17,13 @@ func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegist return distributionInspect, objectNotFoundError{object: "distribution", id: image} } - if err := cli.NewVersionError("1.30", "distribution inspect"); err != nil { + if err := cli.NewVersionError(ctx, "1.30", "distribution inspect"); err != nil { return distributionInspect, err } - var headers map[string][]string + var headers http.Header if encodedRegistryAuth != "" { - headers = map[string][]string{ + headers = http.Header{ registry.AuthHeader: {encodedRegistryAuth}, } } diff --git a/vendor/github.com/docker/docker/client/errors.go b/vendor/github.com/docker/docker/client/errors.go index 6878144c4..4b96b0208 100644 --- a/vendor/github.com/docker/docker/client/errors.go +++ b/vendor/github.com/docker/docker/client/errors.go @@ -1,6 +1,7 @@ package client // import "github.com/docker/docker/client" import ( + "context" "fmt" "github.com/docker/docker/api/types/versions" @@ -31,20 +32,10 @@ func ErrorConnectionFailed(host string) error { return errConnectionFailed{host: host} } -// Deprecated: use the errdefs.NotFound() interface instead. Kept for backward compatibility -type notFound interface { - error - NotFound() bool -} - // IsErrNotFound returns true if the error is a NotFound error, which is returned -// by the API when some object is not found. +// by the API when some object is not found. It is an alias for [errdefs.IsNotFound]. func IsErrNotFound(err error) bool { - if errdefs.IsNotFound(err) { - return true - } - var e notFound - return errors.As(err, &e) + return errdefs.IsNotFound(err) } type objectNotFoundError struct { @@ -58,9 +49,18 @@ func (e objectNotFoundError) Error() string { return fmt.Sprintf("Error: No such %s: %s", e.object, e.id) } -// NewVersionError returns an error if the APIVersion required -// if less than the current supported version -func (cli *Client) NewVersionError(APIrequired, feature string) error { +// NewVersionError returns an error if the APIVersion required is less than the +// current supported version. +// +// It performs API-version negotiation if the Client is configured with this +// option, otherwise it assumes the latest API version is used. +func (cli *Client) NewVersionError(ctx context.Context, APIrequired, feature string) error { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) if cli.version != "" && versions.LessThan(cli.version, APIrequired) { return fmt.Errorf("%q requires API version %s, but the Docker daemon API version is %s", feature, APIrequired, cli.version) } diff --git a/vendor/github.com/docker/docker/client/hijack.go b/vendor/github.com/docker/docker/client/hijack.go index 7e84865f6..839d4c5cd 100644 --- a/vendor/github.com/docker/docker/client/hijack.go +++ b/vendor/github.com/docker/docker/client/hijack.go @@ -3,18 +3,16 @@ package client // import "github.com/docker/docker/client" import ( "bufio" "context" - "crypto/tls" "fmt" "net" "net/http" - "net/http/httputil" "net/url" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions" - "github.com/docker/go-connections/sockets" "github.com/pkg/errors" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" ) // postHijacked sends a POST request and hijacks the connection. @@ -23,11 +21,11 @@ func (cli *Client) postHijacked(ctx context.Context, path string, query url.Valu if err != nil { return types.HijackedResponse{}, err } - req, err := cli.buildRequest(http.MethodPost, cli.getAPIPath(ctx, path, query), bodyEncoded, headers) + req, err := cli.buildRequest(ctx, http.MethodPost, cli.getAPIPath(ctx, path, query), bodyEncoded, headers) if err != nil { return types.HijackedResponse{}, err } - conn, mediaType, err := cli.setupHijackConn(ctx, req, "tcp") + conn, mediaType, err := cli.setupHijackConn(req, "tcp") if err != nil { return types.HijackedResponse{}, err } @@ -37,29 +35,18 @@ func (cli *Client) postHijacked(ctx context.Context, path string, query url.Valu // DialHijack returns a hijacked connection with negotiated protocol proto. func (cli *Client) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) { - req, err := http.NewRequest(http.MethodPost, url, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) if err != nil { return nil, err } req = cli.addHeaders(req, meta) - conn, _, err := cli.setupHijackConn(ctx, req, proto) + conn, _, err := cli.setupHijackConn(req, proto) return conn, err } -// fallbackDial is used when WithDialer() was not called. -// See cli.Dialer(). -func fallbackDial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { - if tlsConfig != nil && proto != "unix" && proto != "npipe" { - return tls.Dial(proto, addr, tlsConfig) - } - if proto == "npipe" { - return sockets.DialPipe(addr, 32*time.Second) - } - return net.Dial(proto, addr) -} - -func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto string) (net.Conn, string, error) { +func (cli *Client) setupHijackConn(req *http.Request, proto string) (_ net.Conn, _ string, retErr error) { + ctx := req.Context() req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", proto) @@ -68,6 +55,11 @@ func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto if err != nil { return nil, "", errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") } + defer func() { + if retErr != nil { + conn.Close() + } + }() // When we set up a TCP connection for hijack, there could be long periods // of inactivity (a long running command with no output) that in certain @@ -79,35 +71,29 @@ func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto _ = tcpConn.SetKeepAlivePeriod(30 * time.Second) } - clientconn := httputil.NewClientConn(conn, nil) - defer clientconn.Close() + hc := &hijackedConn{conn, bufio.NewReader(conn)} // Server hijacks the connection, error 'connection closed' expected - resp, err := clientconn.Do(req) - - //nolint:staticcheck // ignore SA1019 for connecting to old (pre go1.8) daemons - if err != httputil.ErrPersistEOF { - if err != nil { - return nil, "", err - } - if resp.StatusCode != http.StatusSwitchingProtocols { - _ = resp.Body.Close() - return nil, "", fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode) - } + resp, err := otelhttp.NewTransport(hc).RoundTrip(req) + if err != nil { + return nil, "", err + } + if resp.StatusCode != http.StatusSwitchingProtocols { + _ = resp.Body.Close() + return nil, "", fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode) } - c, br := clientconn.Hijack() - if br.Buffered() > 0 { + if hc.r.Buffered() > 0 { // If there is buffered content, wrap the connection. We return an // object that implements CloseWrite if the underlying connection // implements it. - if _, ok := c.(types.CloseWriter); ok { - c = &hijackedConnCloseWriter{&hijackedConn{c, br}} + if _, ok := hc.Conn.(types.CloseWriter); ok { + conn = &hijackedConnCloseWriter{hc} } else { - c = &hijackedConn{c, br} + conn = hc } } else { - br.Reset(nil) + hc.r.Reset(nil) } var mediaType string @@ -116,7 +102,7 @@ func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto mediaType = resp.Header.Get("Content-Type") } - return c, mediaType, nil + return conn, mediaType, nil } // hijackedConn wraps a net.Conn and is returned by setupHijackConn in the case @@ -128,6 +114,13 @@ type hijackedConn struct { r *bufio.Reader } +func (c *hijackedConn) RoundTrip(req *http.Request) (*http.Response, error) { + if err := req.Write(c.Conn); err != nil { + return nil, err + } + return http.ReadResponse(c.r, req) +} + func (c *hijackedConn) Read(b []byte) (int, error) { return c.r.Read(b) } diff --git a/vendor/github.com/docker/docker/client/image_build.go b/vendor/github.com/docker/docker/client/image_build.go index d16e1d8ea..d294ddc8b 100644 --- a/vendor/github.com/docker/docker/client/image_build.go +++ b/vendor/github.com/docker/docker/client/image_build.go @@ -18,18 +18,18 @@ import ( // The Body in the response implements an io.ReadCloser and it's up to the caller to // close it. func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) { - query, err := cli.imageBuildOptionsToQuery(options) + query, err := cli.imageBuildOptionsToQuery(ctx, options) if err != nil { return types.ImageBuildResponse{}, err } - headers := http.Header(make(map[string][]string)) buf, err := json.Marshal(options.AuthConfigs) if err != nil { return types.ImageBuildResponse{}, err } - headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) + headers := http.Header{} + headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) headers.Set("Content-Type", "application/x-tar") serverResp, err := cli.postRaw(ctx, "/build", query, buildContext, headers) @@ -37,15 +37,13 @@ func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, optio return types.ImageBuildResponse{}, err } - osType := getDockerOS(serverResp.header.Get("Server")) - return types.ImageBuildResponse{ Body: serverResp.body, - OSType: osType, + OSType: getDockerOS(serverResp.header.Get("Server")), }, nil } -func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (url.Values, error) { +func (cli *Client) imageBuildOptionsToQuery(ctx context.Context, options types.ImageBuildOptions) (url.Values, error) { query := url.Values{ "t": options.Tags, "securityopt": options.SecurityOpt, @@ -75,7 +73,7 @@ func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (ur } if options.Squash { - if err := cli.NewVersionError("1.25", "squash"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "squash"); err != nil { return query, err } query.Set("squash", "1") @@ -125,7 +123,7 @@ func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (ur query.Set("session", options.SessionID) } if options.Platform != "" { - if err := cli.NewVersionError("1.32", "platform"); err != nil { + if err := cli.NewVersionError(ctx, "1.32", "platform"); err != nil { return query, err } query.Set("platform", strings.ToLower(options.Platform)) diff --git a/vendor/github.com/docker/docker/client/image_create.go b/vendor/github.com/docker/docker/client/image_create.go index 6a9b708f7..29cd0b437 100644 --- a/vendor/github.com/docker/docker/client/image_create.go +++ b/vendor/github.com/docker/docker/client/image_create.go @@ -3,10 +3,11 @@ package client // import "github.com/docker/docker/client" import ( "context" "io" + "net/http" "net/url" "strings" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" ) @@ -33,6 +34,7 @@ func (cli *Client) ImageCreate(ctx context.Context, parentReference string, opti } func (cli *Client) tryImageCreate(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/images/create", query, nil, headers) + return cli.post(ctx, "/images/create", query, nil, http.Header{ + registry.AuthHeader: {registryAuth}, + }) } diff --git a/vendor/github.com/docker/docker/client/image_import.go b/vendor/github.com/docker/docker/client/image_import.go index c5de42cb7..cd376a14e 100644 --- a/vendor/github.com/docker/docker/client/image_import.go +++ b/vendor/github.com/docker/docker/client/image_import.go @@ -6,7 +6,7 @@ import ( "net/url" "strings" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" ) diff --git a/vendor/github.com/docker/docker/client/image_list.go b/vendor/github.com/docker/docker/client/image_list.go index 950d51333..f3f2280e3 100644 --- a/vendor/github.com/docker/docker/client/image_list.go +++ b/vendor/github.com/docker/docker/client/image_list.go @@ -7,12 +7,20 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/versions" ) // ImageList returns a list of images in the docker host. -func (cli *Client) ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) { - var images []types.ImageSummary +func (cli *Client) ImageList(ctx context.Context, options types.ImageListOptions) ([]image.Summary, error) { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + + var images []image.Summary query := url.Values{} optionFilters := options.Filters diff --git a/vendor/github.com/docker/docker/client/image_load.go b/vendor/github.com/docker/docker/client/image_load.go index 91016e493..c825206ea 100644 --- a/vendor/github.com/docker/docker/client/image_load.go +++ b/vendor/github.com/docker/docker/client/image_load.go @@ -3,6 +3,7 @@ package client // import "github.com/docker/docker/client" import ( "context" "io" + "net/http" "net/url" "github.com/docker/docker/api/types" @@ -17,8 +18,9 @@ func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) ( if quiet { v.Set("quiet", "1") } - headers := map[string][]string{"Content-Type": {"application/x-tar"}} - resp, err := cli.postRaw(ctx, "/images/load", v, input, headers) + resp, err := cli.postRaw(ctx, "/images/load", v, input, http.Header{ + "Content-Type": {"application/x-tar"}, + }) if err != nil { return types.ImageLoadResponse{}, err } diff --git a/vendor/github.com/docker/docker/client/image_prune.go b/vendor/github.com/docker/docker/client/image_prune.go index 56af6d7f9..6b82d6ab6 100644 --- a/vendor/github.com/docker/docker/client/image_prune.go +++ b/vendor/github.com/docker/docker/client/image_prune.go @@ -13,7 +13,7 @@ import ( func (cli *Client) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (types.ImagesPruneReport, error) { var report types.ImagesPruneReport - if err := cli.NewVersionError("1.25", "image prune"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "image prune"); err != nil { return report, err } diff --git a/vendor/github.com/docker/docker/client/image_pull.go b/vendor/github.com/docker/docker/client/image_pull.go index a23975591..d92049d58 100644 --- a/vendor/github.com/docker/docker/client/image_pull.go +++ b/vendor/github.com/docker/docker/client/image_pull.go @@ -6,7 +6,7 @@ import ( "net/url" "strings" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/errdefs" ) diff --git a/vendor/github.com/docker/docker/client/image_push.go b/vendor/github.com/docker/docker/client/image_push.go index dd1b8f347..6839a89e0 100644 --- a/vendor/github.com/docker/docker/client/image_push.go +++ b/vendor/github.com/docker/docker/client/image_push.go @@ -4,9 +4,10 @@ import ( "context" "errors" "io" + "net/http" "net/url" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" @@ -50,6 +51,7 @@ func (cli *Client) ImagePush(ctx context.Context, image string, options types.Im } func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers) + return cli.post(ctx, "/images/"+imageID+"/push", query, nil, http.Header{ + registry.AuthHeader: {registryAuth}, + }) } diff --git a/vendor/github.com/docker/docker/client/image_remove.go b/vendor/github.com/docker/docker/client/image_remove.go index 6a9fb3f41..b936d2083 100644 --- a/vendor/github.com/docker/docker/client/image_remove.go +++ b/vendor/github.com/docker/docker/client/image_remove.go @@ -6,10 +6,11 @@ import ( "net/url" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/image" ) // ImageRemove removes an image from the docker host. -func (cli *Client) ImageRemove(ctx context.Context, imageID string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { +func (cli *Client) ImageRemove(ctx context.Context, imageID string, options types.ImageRemoveOptions) ([]image.DeleteResponse, error) { query := url.Values{} if options.Force { @@ -19,7 +20,7 @@ func (cli *Client) ImageRemove(ctx context.Context, imageID string, options type query.Set("noprune", "1") } - var dels []types.ImageDeleteResponseItem + var dels []image.DeleteResponse resp, err := cli.delete(ctx, "/images/"+imageID, query, nil) defer ensureReaderClosed(resp) if err != nil { diff --git a/vendor/github.com/docker/docker/client/image_search.go b/vendor/github.com/docker/docker/client/image_search.go index 5f0c49ed3..8971b139a 100644 --- a/vendor/github.com/docker/docker/client/image_search.go +++ b/vendor/github.com/docker/docker/client/image_search.go @@ -3,6 +3,7 @@ package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" + "net/http" "net/url" "strconv" @@ -48,6 +49,7 @@ func (cli *Client) ImageSearch(ctx context.Context, term string, options types.I } func (cli *Client) tryImageSearch(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.get(ctx, "/images/search", query, headers) + return cli.get(ctx, "/images/search", query, http.Header{ + registry.AuthHeader: {registryAuth}, + }) } diff --git a/vendor/github.com/docker/docker/client/image_tag.go b/vendor/github.com/docker/docker/client/image_tag.go index 5652bfc25..ea6b4a1e6 100644 --- a/vendor/github.com/docker/docker/client/image_tag.go +++ b/vendor/github.com/docker/docker/client/image_tag.go @@ -4,7 +4,7 @@ import ( "context" "net/url" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/pkg/errors" ) diff --git a/vendor/github.com/docker/docker/client/info.go b/vendor/github.com/docker/docker/client/info.go index c856704e2..cc3fcc467 100644 --- a/vendor/github.com/docker/docker/client/info.go +++ b/vendor/github.com/docker/docker/client/info.go @@ -6,12 +6,12 @@ import ( "fmt" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/system" ) // Info returns information about the docker server. -func (cli *Client) Info(ctx context.Context) (types.Info, error) { - var info types.Info +func (cli *Client) Info(ctx context.Context) (system.Info, error) { + var info system.Info serverResp, err := cli.get(ctx, "/info", url.Values{}, nil) defer ensureReaderClosed(serverResp) if err != nil { diff --git a/vendor/github.com/docker/docker/client/interface.go b/vendor/github.com/docker/docker/client/interface.go index 7993c5a48..302f5fb13 100644 --- a/vendor/github.com/docker/docker/client/interface.go +++ b/vendor/github.com/docker/docker/client/interface.go @@ -14,6 +14,7 @@ import ( "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" + "github.com/docker/docker/api/types/system" "github.com/docker/docker/api/types/volume" ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) @@ -45,30 +46,30 @@ type CommonAPIClient interface { // ContainerAPIClient defines API client methods for the containers type ContainerAPIClient interface { - ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) - ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) + ContainerAttach(ctx context.Context, container string, options container.AttachOptions) (types.HijackedResponse, error) + ContainerCommit(ctx context.Context, container string, options container.CommitOptions) (types.IDResponse, error) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error) ContainerDiff(ctx context.Context, container string) ([]container.FilesystemChange, error) ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) - ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error + ContainerExecResize(ctx context.Context, execID string, options container.ResizeOptions) error ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) ContainerInspect(ctx context.Context, container string) (types.ContainerJSON, error) ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (types.ContainerJSON, []byte, error) ContainerKill(ctx context.Context, container, signal string) error - ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) - ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) + ContainerList(ctx context.Context, options container.ListOptions) ([]types.Container, error) + ContainerLogs(ctx context.Context, container string, options container.LogsOptions) (io.ReadCloser, error) ContainerPause(ctx context.Context, container string) error - ContainerRemove(ctx context.Context, container string, options types.ContainerRemoveOptions) error + ContainerRemove(ctx context.Context, container string, options container.RemoveOptions) error ContainerRename(ctx context.Context, container, newContainerName string) error - ContainerResize(ctx context.Context, container string, options types.ResizeOptions) error + ContainerResize(ctx context.Context, container string, options container.ResizeOptions) error ContainerRestart(ctx context.Context, container string, options container.StopOptions) error ContainerStatPath(ctx context.Context, container, path string) (types.ContainerPathStat, error) ContainerStats(ctx context.Context, container string, stream bool) (types.ContainerStats, error) ContainerStatsOneShot(ctx context.Context, container string) (types.ContainerStats, error) - ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error + ContainerStart(ctx context.Context, container string, options container.StartOptions) error ContainerStop(ctx context.Context, container string, options container.StopOptions) error ContainerTop(ctx context.Context, container string, arguments []string) (container.ContainerTopOKBody, error) ContainerUnpause(ctx context.Context, container string) error @@ -93,11 +94,11 @@ type ImageAPIClient interface { ImageHistory(ctx context.Context, image string) ([]image.HistoryResponseItem, error) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) ImageInspectWithRaw(ctx context.Context, image string) (types.ImageInspect, []byte, error) - ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) + ImageList(ctx context.Context, options types.ImageListOptions) ([]image.Summary, error) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) ImagePull(ctx context.Context, ref string, options types.ImagePullOptions) (io.ReadCloser, error) ImagePush(ctx context.Context, ref string, options types.ImagePushOptions) (io.ReadCloser, error) - ImageRemove(ctx context.Context, image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) + ImageRemove(ctx context.Context, image string, options types.ImageRemoveOptions) ([]image.DeleteResponse, error) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) ImageSave(ctx context.Context, images []string) (io.ReadCloser, error) ImageTag(ctx context.Context, image, ref string) error @@ -140,13 +141,13 @@ type PluginAPIClient interface { // ServiceAPIClient defines API client methods for the services type ServiceAPIClient interface { - ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) + ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (swarm.ServiceCreateResponse, error) ServiceInspectWithRaw(ctx context.Context, serviceID string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) ServiceRemove(ctx context.Context, serviceID string) error - ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) - ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) - TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) + ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (swarm.ServiceUpdateResponse, error) + ServiceLogs(ctx context.Context, serviceID string, options container.LogsOptions) (io.ReadCloser, error) + TaskLogs(ctx context.Context, taskID string, options container.LogsOptions) (io.ReadCloser, error) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) } @@ -165,7 +166,7 @@ type SwarmAPIClient interface { // SystemAPIClient defines API client methods for the system type SystemAPIClient interface { Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) - Info(ctx context.Context) (types.Info, error) + Info(ctx context.Context) (system.Info, error) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error) Ping(ctx context.Context) (types.Ping, error) diff --git a/vendor/github.com/docker/docker/client/interface_experimental.go b/vendor/github.com/docker/docker/client/interface_experimental.go index 402ffb512..c585c1045 100644 --- a/vendor/github.com/docker/docker/client/interface_experimental.go +++ b/vendor/github.com/docker/docker/client/interface_experimental.go @@ -3,7 +3,7 @@ package client // import "github.com/docker/docker/client" import ( "context" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/checkpoint" ) type apiClientExperimental interface { @@ -12,7 +12,7 @@ type apiClientExperimental interface { // CheckpointAPIClient defines API client methods for the checkpoints type CheckpointAPIClient interface { - CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error - CheckpointDelete(ctx context.Context, container string, options types.CheckpointDeleteOptions) error - CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) + CheckpointCreate(ctx context.Context, container string, options checkpoint.CreateOptions) error + CheckpointDelete(ctx context.Context, container string, options checkpoint.DeleteOptions) error + CheckpointList(ctx context.Context, container string, options checkpoint.ListOptions) ([]checkpoint.Summary, error) } diff --git a/vendor/github.com/docker/docker/client/network_create.go b/vendor/github.com/docker/docker/client/network_create.go index 278d9383a..668e87d65 100644 --- a/vendor/github.com/docker/docker/client/network_create.go +++ b/vendor/github.com/docker/docker/client/network_create.go @@ -5,14 +5,26 @@ import ( "encoding/json" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/versions" ) // NetworkCreate creates a new network in the docker host. func (cli *Client) NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + networkCreateRequest := types.NetworkCreateRequest{ NetworkCreate: options, Name: name, } + if versions.LessThan(cli.version, "1.44") { + networkCreateRequest.CheckDuplicate = true //nolint:staticcheck // ignore SA1019: CheckDuplicate is deprecated since API v1.44. + } + var response types.NetworkCreateResponse serverResp, err := cli.post(ctx, "/networks/create", nil, networkCreateRequest, nil) defer ensureReaderClosed(serverResp) diff --git a/vendor/github.com/docker/docker/client/network_prune.go b/vendor/github.com/docker/docker/client/network_prune.go index cebb18821..7b5f831ef 100644 --- a/vendor/github.com/docker/docker/client/network_prune.go +++ b/vendor/github.com/docker/docker/client/network_prune.go @@ -13,7 +13,7 @@ import ( func (cli *Client) NetworksPrune(ctx context.Context, pruneFilters filters.Args) (types.NetworksPruneReport, error) { var report types.NetworksPruneReport - if err := cli.NewVersionError("1.25", "network prune"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "network prune"); err != nil { return report, err } diff --git a/vendor/github.com/docker/docker/client/node_list.go b/vendor/github.com/docker/docker/client/node_list.go index c212906bc..1a9e6bfb1 100644 --- a/vendor/github.com/docker/docker/client/node_list.go +++ b/vendor/github.com/docker/docker/client/node_list.go @@ -16,7 +16,6 @@ func (cli *Client) NodeList(ctx context.Context, options types.NodeListOptions) if options.Filters.Len() > 0 { filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { return nil, err } diff --git a/vendor/github.com/docker/docker/client/options.go b/vendor/github.com/docker/docker/client/options.go index 099ad4184..ddb0ca399 100644 --- a/vendor/github.com/docker/docker/client/options.go +++ b/vendor/github.com/docker/docker/client/options.go @@ -11,25 +11,25 @@ import ( "github.com/docker/go-connections/sockets" "github.com/docker/go-connections/tlsconfig" "github.com/pkg/errors" + "go.opentelemetry.io/otel/trace" ) -// Opt is a configuration option to initialize a client +// Opt is a configuration option to initialize a [Client]. type Opt func(*Client) error -// FromEnv configures the client with values from environment variables. +// FromEnv configures the client with values from environment variables. It +// is the equivalent of using the [WithTLSClientConfigFromEnv], [WithHostFromEnv], +// and [WithVersionFromEnv] options. // // FromEnv uses the following environment variables: // -// DOCKER_HOST (EnvOverrideHost) to set the URL to the docker server. -// -// DOCKER_API_VERSION (EnvOverrideAPIVersion) to set the version of the API to -// use, leave empty for latest. -// -// DOCKER_CERT_PATH (EnvOverrideCertPath) to specify the directory from which to -// load the TLS certificates (ca.pem, cert.pem, key.pem). -// -// DOCKER_TLS_VERIFY (EnvTLSVerify) to enable or disable TLS verification (off by -// default). +// - DOCKER_HOST ([EnvOverrideHost]) to set the URL to the docker server. +// - DOCKER_API_VERSION ([EnvOverrideAPIVersion]) to set the version of the +// API to use, leave empty for latest. +// - DOCKER_CERT_PATH ([EnvOverrideCertPath]) to specify the directory from +// which to load the TLS certificates ("ca.pem", "cert.pem", "key.pem'). +// - DOCKER_TLS_VERIFY ([EnvTLSVerify]) to enable or disable TLS verification +// (off by default). func FromEnv(c *Client) error { ops := []Opt{ WithTLSClientConfigFromEnv(), @@ -45,7 +45,8 @@ func FromEnv(c *Client) error { } // WithDialContext applies the dialer to the client transport. This can be -// used to set the Timeout and KeepAlive settings of the client. +// used to set the Timeout and KeepAlive settings of the client. It returns +// an error if the client does not have a [http.Transport] configured. func WithDialContext(dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) Opt { return func(c *Client) error { if transport, ok := c.client.Transport.(*http.Transport); ok { @@ -75,7 +76,7 @@ func WithHost(host string) Opt { } // WithHostFromEnv overrides the client host with the host specified in the -// DOCKER_HOST (EnvOverrideHost) environment variable. If DOCKER_HOST is not set, +// DOCKER_HOST ([EnvOverrideHost]) environment variable. If DOCKER_HOST is not set, // or set to an empty value, the host is not modified. func WithHostFromEnv() Opt { return func(c *Client) error { @@ -86,7 +87,7 @@ func WithHostFromEnv() Opt { } } -// WithHTTPClient overrides the client http client with the specified one +// WithHTTPClient overrides the client's HTTP client with the specified one. func WithHTTPClient(client *http.Client) Opt { return func(c *Client) error { if client != nil { @@ -96,7 +97,7 @@ func WithHTTPClient(client *http.Client) Opt { } } -// WithTimeout configures the time limit for requests made by the HTTP client +// WithTimeout configures the time limit for requests made by the HTTP client. func WithTimeout(timeout time.Duration) Opt { return func(c *Client) error { c.client.Timeout = timeout @@ -104,7 +105,19 @@ func WithTimeout(timeout time.Duration) Opt { } } -// WithHTTPHeaders overrides the client default http headers +// WithUserAgent configures the User-Agent header to use for HTTP requests. +// It overrides any User-Agent set in headers. When set to an empty string, +// the User-Agent header is removed, and no header is sent. +func WithUserAgent(ua string) Opt { + return func(c *Client) error { + c.userAgent = &ua + return nil + } +} + +// WithHTTPHeaders appends custom HTTP headers to the client's default headers. +// It does not allow for built-in headers (such as "User-Agent", if set) to +// be overridden. Also see [WithUserAgent]. func WithHTTPHeaders(headers map[string]string) Opt { return func(c *Client) error { c.customHTTPHeaders = headers @@ -112,7 +125,7 @@ func WithHTTPHeaders(headers map[string]string) Opt { } } -// WithScheme overrides the client scheme with the specified one +// WithScheme overrides the client scheme with the specified one. func WithScheme(scheme string) Opt { return func(c *Client) error { c.scheme = scheme @@ -120,51 +133,50 @@ func WithScheme(scheme string) Opt { } } -// WithTLSClientConfig applies a tls config to the client transport. +// WithTLSClientConfig applies a TLS config to the client transport. func WithTLSClientConfig(cacertPath, certPath, keyPath string) Opt { return func(c *Client) error { - opts := tlsconfig.Options{ + transport, ok := c.client.Transport.(*http.Transport) + if !ok { + return errors.Errorf("cannot apply tls config to transport: %T", c.client.Transport) + } + config, err := tlsconfig.Client(tlsconfig.Options{ CAFile: cacertPath, CertFile: certPath, KeyFile: keyPath, ExclusiveRootPools: true, - } - config, err := tlsconfig.Client(opts) + }) if err != nil { return errors.Wrap(err, "failed to create tls config") } - if transport, ok := c.client.Transport.(*http.Transport); ok { - transport.TLSClientConfig = config - return nil - } - return errors.Errorf("cannot apply tls config to transport: %T", c.client.Transport) + transport.TLSClientConfig = config + return nil } } // WithTLSClientConfigFromEnv configures the client's TLS settings with the -// settings in the DOCKER_CERT_PATH and DOCKER_TLS_VERIFY environment variables. -// If DOCKER_CERT_PATH is not set or empty, TLS configuration is not modified. +// settings in the DOCKER_CERT_PATH ([EnvOverrideCertPath]) and DOCKER_TLS_VERIFY +// ([EnvTLSVerify]) environment variables. If DOCKER_CERT_PATH is not set or empty, +// TLS configuration is not modified. // // WithTLSClientConfigFromEnv uses the following environment variables: // -// DOCKER_CERT_PATH (EnvOverrideCertPath) to specify the directory from which to -// load the TLS certificates (ca.pem, cert.pem, key.pem). -// -// DOCKER_TLS_VERIFY (EnvTLSVerify) to enable or disable TLS verification (off by -// default). +// - DOCKER_CERT_PATH ([EnvOverrideCertPath]) to specify the directory from +// which to load the TLS certificates ("ca.pem", "cert.pem", "key.pem"). +// - DOCKER_TLS_VERIFY ([EnvTLSVerify]) to enable or disable TLS verification +// (off by default). func WithTLSClientConfigFromEnv() Opt { return func(c *Client) error { dockerCertPath := os.Getenv(EnvOverrideCertPath) if dockerCertPath == "" { return nil } - options := tlsconfig.Options{ + tlsc, err := tlsconfig.Client(tlsconfig.Options{ CAFile: filepath.Join(dockerCertPath, "ca.pem"), CertFile: filepath.Join(dockerCertPath, "cert.pem"), KeyFile: filepath.Join(dockerCertPath, "key.pem"), InsecureSkipVerify: os.Getenv(EnvTLSVerify) == "", - } - tlsc, err := tlsconfig.Client(options) + }) if err != nil { return err } @@ -178,7 +190,8 @@ func WithTLSClientConfigFromEnv() Opt { } // WithVersion overrides the client version with the specified one. If an empty -// version is specified, the value will be ignored to allow version negotiation. +// version is provided, the value is ignored to allow version negotiation +// (see [WithAPIVersionNegotiation]). func WithVersion(version string) Opt { return func(c *Client) error { if version != "" { @@ -190,8 +203,9 @@ func WithVersion(version string) Opt { } // WithVersionFromEnv overrides the client version with the version specified in -// the DOCKER_API_VERSION environment variable. If DOCKER_API_VERSION is not set, -// the version is not modified. +// the DOCKER_API_VERSION ([EnvOverrideAPIVersion]) environment variable. +// If DOCKER_API_VERSION is not set, or set to an empty value, the version +// is not modified. func WithVersionFromEnv() Opt { return func(c *Client) error { return WithVersion(os.Getenv(EnvOverrideAPIVersion))(c) @@ -201,10 +215,19 @@ func WithVersionFromEnv() Opt { // WithAPIVersionNegotiation enables automatic API version negotiation for the client. // With this option enabled, the client automatically negotiates the API version // to use when making requests. API version negotiation is performed on the first -// request; subsequent requests will not re-negotiate. +// request; subsequent requests do not re-negotiate. func WithAPIVersionNegotiation() Opt { return func(c *Client) error { c.negotiateVersion = true return nil } } + +// WithTraceProvider sets the trace provider for the client. +// If this is not set then the global trace provider will be used. +func WithTraceProvider(provider trace.TracerProvider) Opt { + return func(c *Client) error { + c.tp = provider + return nil + } +} diff --git a/vendor/github.com/docker/docker/client/ping.go b/vendor/github.com/docker/docker/client/ping.go index 347ae71e0..dfd1042fa 100644 --- a/vendor/github.com/docker/docker/client/ping.go +++ b/vendor/github.com/docker/docker/client/ping.go @@ -21,11 +21,11 @@ func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { // Using cli.buildRequest() + cli.doRequest() instead of cli.sendRequest() // because ping requests are used during API version negotiation, so we want // to hit the non-versioned /_ping endpoint, not /v1.xx/_ping - req, err := cli.buildRequest(http.MethodHead, path.Join(cli.basePath, "/_ping"), nil, nil) + req, err := cli.buildRequest(ctx, http.MethodHead, path.Join(cli.basePath, "/_ping"), nil, nil) if err != nil { return ping, err } - serverResp, err := cli.doRequest(ctx, req) + serverResp, err := cli.doRequest(req) if err == nil { defer ensureReaderClosed(serverResp) switch serverResp.statusCode { @@ -37,11 +37,9 @@ func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { return ping, err } - req, err = cli.buildRequest(http.MethodGet, path.Join(cli.basePath, "/_ping"), nil, nil) - if err != nil { - return ping, err - } - serverResp, err = cli.doRequest(ctx, req) + // HEAD failed; fallback to GET. + req.Method = http.MethodGet + serverResp, err = cli.doRequest(req) defer ensureReaderClosed(serverResp) if err != nil { return ping, err diff --git a/vendor/github.com/docker/docker/client/plugin_install.go b/vendor/github.com/docker/docker/client/plugin_install.go index 3a740ec4f..69184619a 100644 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ b/vendor/github.com/docker/docker/client/plugin_install.go @@ -4,9 +4,10 @@ import ( "context" "encoding/json" "io" + "net/http" "net/url" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" @@ -68,13 +69,15 @@ func (cli *Client) PluginInstall(ctx context.Context, name string, options types } func (cli *Client) tryPluginPrivileges(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.get(ctx, "/plugins/privileges", query, headers) + return cli.get(ctx, "/plugins/privileges", query, http.Header{ + registry.AuthHeader: {registryAuth}, + }) } func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges types.PluginPrivileges, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/plugins/pull", query, privileges, headers) + return cli.post(ctx, "/plugins/pull", query, privileges, http.Header{ + registry.AuthHeader: {registryAuth}, + }) } func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, options types.PluginInstallOptions) (types.PluginPrivileges, error) { diff --git a/vendor/github.com/docker/docker/client/plugin_push.go b/vendor/github.com/docker/docker/client/plugin_push.go index 18f9754c4..8f68a86ee 100644 --- a/vendor/github.com/docker/docker/client/plugin_push.go +++ b/vendor/github.com/docker/docker/client/plugin_push.go @@ -3,14 +3,16 @@ package client // import "github.com/docker/docker/client" import ( "context" "io" + "net/http" "github.com/docker/docker/api/types/registry" ) // PluginPush pushes a plugin to a registry func (cli *Client) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, headers) + resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, http.Header{ + registry.AuthHeader: {registryAuth}, + }) if err != nil { return nil, err } diff --git a/vendor/github.com/docker/docker/client/plugin_upgrade.go b/vendor/github.com/docker/docker/client/plugin_upgrade.go index 995d1fd2c..5cade450f 100644 --- a/vendor/github.com/docker/docker/client/plugin_upgrade.go +++ b/vendor/github.com/docker/docker/client/plugin_upgrade.go @@ -3,9 +3,10 @@ package client // import "github.com/docker/docker/client" import ( "context" "io" + "net/http" "net/url" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/pkg/errors" @@ -13,7 +14,7 @@ import ( // PluginUpgrade upgrades a plugin func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) { - if err := cli.NewVersionError("1.26", "plugin upgrade"); err != nil { + if err := cli.NewVersionError(ctx, "1.26", "plugin upgrade"); err != nil { return nil, err } query := url.Values{} @@ -35,6 +36,7 @@ func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types } func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges types.PluginPrivileges, name, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/plugins/"+name+"/upgrade", query, privileges, headers) + return cli.post(ctx, "/plugins/"+name+"/upgrade", query, privileges, http.Header{ + registry.AuthHeader: {registryAuth}, + }) } diff --git a/vendor/github.com/docker/docker/client/request.go b/vendor/github.com/docker/docker/client/request.go index bcedcf3bd..efe07bb9e 100644 --- a/vendor/github.com/docker/docker/client/request.go +++ b/vendor/github.com/docker/docker/client/request.go @@ -10,6 +10,7 @@ import ( "net/http" "net/url" "os" + "reflect" "strings" "github.com/docker/docker/api/types" @@ -27,17 +28,17 @@ type serverResponse struct { } // head sends an http request to the docker API using the method HEAD. -func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { +func (cli *Client) head(ctx context.Context, path string, query url.Values, headers http.Header) (serverResponse, error) { return cli.sendRequest(ctx, http.MethodHead, path, query, nil, headers) } // get sends an http request to the docker API using the method GET with a specific Go context. -func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { +func (cli *Client) get(ctx context.Context, path string, query url.Values, headers http.Header) (serverResponse, error) { return cli.sendRequest(ctx, http.MethodGet, path, query, nil, headers) } // post sends an http request to the docker API using the method POST with a specific Go context. -func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { +func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers http.Header) (serverResponse, error) { body, headers, err := encodeBody(obj, headers) if err != nil { return serverResponse{}, err @@ -45,34 +46,44 @@ func (cli *Client) post(ctx context.Context, path string, query url.Values, obj return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) } -func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { +func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (serverResponse, error) { return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) } -func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { +func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers http.Header) (serverResponse, error) { body, headers, err := encodeBody(obj, headers) if err != nil { return serverResponse{}, err } - return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) + return cli.putRaw(ctx, path, query, body, headers) } // putRaw sends an http request to the docker API using the method PUT. -func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { +func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (serverResponse, error) { + // PUT requests are expected to always have a body (apparently) + // so explicitly pass an empty body to sendRequest to signal that + // it should set the Content-Type header if not already present. + if body == nil { + body = http.NoBody + } return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) } // delete sends an http request to the docker API using the method DELETE. -func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { +func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers http.Header) (serverResponse, error) { return cli.sendRequest(ctx, http.MethodDelete, path, query, nil, headers) } -type headers map[string][]string - -func encodeBody(obj interface{}, headers headers) (io.Reader, headers, error) { +func encodeBody(obj interface{}, headers http.Header) (io.Reader, http.Header, error) { if obj == nil { return nil, headers, nil } + // encoding/json encodes a nil pointer as the JSON document `null`, + // irrespective of whether the type implements json.Marshaler or encoding.TextMarshaler. + // That is almost certainly not what the caller intended as the request body. + if reflect.TypeOf(obj).Kind() == reflect.Ptr && reflect.ValueOf(obj).IsNil() { + return nil, headers, nil + } body, err := encodeData(obj) if err != nil { @@ -85,13 +96,8 @@ func encodeBody(obj interface{}, headers headers) (io.Reader, headers, error) { return body, headers, nil } -func (cli *Client) buildRequest(method, path string, body io.Reader, headers headers) (*http.Request, error) { - expectedPayload := (method == http.MethodPost || method == http.MethodPut) - if expectedPayload && body == nil { - body = bytes.NewReader([]byte{}) - } - - req, err := http.NewRequest(method, path, body) +func (cli *Client) buildRequest(ctx context.Context, method, path string, body io.Reader, headers http.Header) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, method, path, body) if err != nil { return nil, err } @@ -104,19 +110,19 @@ func (cli *Client) buildRequest(method, path string, body io.Reader, headers hea req.Host = DummyHost } - if expectedPayload && req.Header.Get("Content-Type") == "" { + if body != nil && req.Header.Get("Content-Type") == "" { req.Header.Set("Content-Type", "text/plain") } return req, nil } -func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers headers) (serverResponse, error) { - req, err := cli.buildRequest(method, cli.getAPIPath(ctx, path, query), body, headers) +func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers http.Header) (serverResponse, error) { + req, err := cli.buildRequest(ctx, method, cli.getAPIPath(ctx, path, query), body, headers) if err != nil { return serverResponse{}, err } - resp, err := cli.doRequest(ctx, req) + resp, err := cli.doRequest(req) switch { case errors.Is(err, context.Canceled): return serverResponse{}, errdefs.Cancelled(err) @@ -128,10 +134,9 @@ func (cli *Client) sendRequest(ctx context.Context, method, path string, query u return resp, errdefs.FromStatusCode(err, resp.statusCode) } -func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResponse, error) { +func (cli *Client) doRequest(req *http.Request) (serverResponse, error) { serverResp := serverResponse{statusCode: -1, reqURL: req.URL} - req = req.WithContext(ctx) resp, err := cli.client.Do(req) if err != nil { if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") { @@ -148,19 +153,19 @@ func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResp return serverResp, err } - if nErr, ok := err.(*url.Error); ok { - if nErr, ok := nErr.Err.(*net.OpError); ok { + if uErr, ok := err.(*url.Error); ok { + if nErr, ok := uErr.Err.(*net.OpError); ok { if os.IsPermission(nErr.Err) { return serverResp, errors.Wrapf(err, "permission denied while trying to connect to the Docker daemon socket at %v", cli.host) } } } - if err, ok := err.(net.Error); ok { - if err.Timeout() { + if nErr, ok := err.(net.Error); ok { + if nErr.Timeout() { return serverResp, ErrorConnectionFailed(cli.host) } - if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") { + if strings.Contains(nErr.Error(), "connection refused") || strings.Contains(nErr.Error(), "dial unix") { return serverResp, ErrorConnectionFailed(cli.host) } } @@ -221,26 +226,20 @@ func (cli *Client) checkResponseErr(serverResp serverResponse) error { return fmt.Errorf("request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), serverResp.reqURL) } - var ct string - if serverResp.header != nil { - ct = serverResp.header.Get("Content-Type") - } - - var errorMessage string - if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) && ct == "application/json" { + var daemonErr error + if serverResp.header.Get("Content-Type") == "application/json" && (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) { var errorResponse types.ErrorResponse if err := json.Unmarshal(body, &errorResponse); err != nil { return errors.Wrap(err, "Error reading JSON") } - errorMessage = strings.TrimSpace(errorResponse.Message) + daemonErr = errors.New(strings.TrimSpace(errorResponse.Message)) } else { - errorMessage = strings.TrimSpace(string(body)) + daemonErr = errors.New(strings.TrimSpace(string(body))) } - - return errors.Wrap(errors.New(errorMessage), "Error response from daemon") + return errors.Wrap(daemonErr, "Error response from daemon") } -func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request { +func (cli *Client) addHeaders(req *http.Request, headers http.Header) *http.Request { // Add CLI Config's HTTP Headers BEFORE we set the Docker headers // then the user can't change OUR headers for k, v := range cli.customHTTPHeaders { @@ -253,6 +252,14 @@ func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request for k, v := range headers { req.Header[http.CanonicalHeaderKey(k)] = v } + + if cli.userAgent != nil { + if *cli.userAgent == "" { + req.Header.Del("User-Agent") + } else { + req.Header.Set("User-Agent", *cli.userAgent) + } + } return req } diff --git a/vendor/github.com/docker/docker/client/secret_create.go b/vendor/github.com/docker/docker/client/secret_create.go index c65d38a19..7b7f1ba74 100644 --- a/vendor/github.com/docker/docker/client/secret_create.go +++ b/vendor/github.com/docker/docker/client/secret_create.go @@ -11,7 +11,7 @@ import ( // SecretCreate creates a new secret. func (cli *Client) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) { var response types.SecretCreateResponse - if err := cli.NewVersionError("1.25", "secret create"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "secret create"); err != nil { return response, err } resp, err := cli.post(ctx, "/secrets/create", nil, secret, nil) diff --git a/vendor/github.com/docker/docker/client/secret_inspect.go b/vendor/github.com/docker/docker/client/secret_inspect.go index 5906874b1..a9cb59889 100644 --- a/vendor/github.com/docker/docker/client/secret_inspect.go +++ b/vendor/github.com/docker/docker/client/secret_inspect.go @@ -11,7 +11,7 @@ import ( // SecretInspectWithRaw returns the secret information with raw data func (cli *Client) SecretInspectWithRaw(ctx context.Context, id string) (swarm.Secret, []byte, error) { - if err := cli.NewVersionError("1.25", "secret inspect"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "secret inspect"); err != nil { return swarm.Secret{}, nil, err } if id == "" { diff --git a/vendor/github.com/docker/docker/client/secret_list.go b/vendor/github.com/docker/docker/client/secret_list.go index a0289c9f4..4d21639ef 100644 --- a/vendor/github.com/docker/docker/client/secret_list.go +++ b/vendor/github.com/docker/docker/client/secret_list.go @@ -12,7 +12,7 @@ import ( // SecretList returns the list of secrets. func (cli *Client) SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) { - if err := cli.NewVersionError("1.25", "secret list"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "secret list"); err != nil { return nil, err } query := url.Values{} diff --git a/vendor/github.com/docker/docker/client/secret_remove.go b/vendor/github.com/docker/docker/client/secret_remove.go index f47f68b6e..079ed6739 100644 --- a/vendor/github.com/docker/docker/client/secret_remove.go +++ b/vendor/github.com/docker/docker/client/secret_remove.go @@ -4,7 +4,7 @@ import "context" // SecretRemove removes a secret. func (cli *Client) SecretRemove(ctx context.Context, id string) error { - if err := cli.NewVersionError("1.25", "secret remove"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "secret remove"); err != nil { return err } resp, err := cli.delete(ctx, "/secrets/"+id, nil, nil) diff --git a/vendor/github.com/docker/docker/client/secret_update.go b/vendor/github.com/docker/docker/client/secret_update.go index 2e939e8ce..9dfe67198 100644 --- a/vendor/github.com/docker/docker/client/secret_update.go +++ b/vendor/github.com/docker/docker/client/secret_update.go @@ -9,7 +9,7 @@ import ( // SecretUpdate attempts to update a secret. func (cli *Client) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { - if err := cli.NewVersionError("1.25", "secret update"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "secret update"); err != nil { return err } query := url.Values{} diff --git a/vendor/github.com/docker/docker/client/service_create.go b/vendor/github.com/docker/docker/client/service_create.go index b6065b8ee..2ebb5ee3a 100644 --- a/vendor/github.com/docker/docker/client/service_create.go +++ b/vendor/github.com/docker/docker/client/service_create.go @@ -4,26 +4,28 @@ import ( "context" "encoding/json" "fmt" + "net/http" "strings" - "github.com/docker/distribution/reference" + "github.com/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" + "github.com/docker/docker/api/types/versions" "github.com/opencontainers/go-digest" "github.com/pkg/errors" ) // ServiceCreate creates a new service. -func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) { - var response types.ServiceCreateResponse - headers := map[string][]string{ - "version": {cli.version}, - } +func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (swarm.ServiceCreateResponse, error) { + var response swarm.ServiceCreateResponse - if options.EncodedRegistryAuth != "" { - headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} - } + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) // Make sure containerSpec is not nil when no runtime is set or the runtime is set to container if service.TaskTemplate.ContainerSpec == nil && (service.TaskTemplate.Runtime == "" || service.TaskTemplate.Runtime == swarm.RuntimeContainer) { @@ -53,6 +55,16 @@ func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, } } + headers := http.Header{} + if versions.LessThan(cli.version, "1.30") { + // the custom "version" header was used by engine API before 20.10 + // (API 1.30) to switch between client- and server-side lookup of + // image digests. + headers["version"] = []string{cli.version} + } + if options.EncodedRegistryAuth != "" { + headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} + } resp, err := cli.post(ctx, "/services/create", nil, service, headers) defer ensureReaderClosed(resp) if err != nil { diff --git a/vendor/github.com/docker/docker/client/service_logs.go b/vendor/github.com/docker/docker/client/service_logs.go index 906fd4059..e9e30a2ab 100644 --- a/vendor/github.com/docker/docker/client/service_logs.go +++ b/vendor/github.com/docker/docker/client/service_logs.go @@ -6,14 +6,14 @@ import ( "net/url" "time" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" timetypes "github.com/docker/docker/api/types/time" "github.com/pkg/errors" ) // ServiceLogs returns the logs generated by a service in an io.ReadCloser. // It's up to the caller to close the stream. -func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { +func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options container.LogsOptions) (io.ReadCloser, error) { query := url.Values{} if options.ShowStdout { query.Set("stdout", "1") diff --git a/vendor/github.com/docker/docker/client/service_update.go b/vendor/github.com/docker/docker/client/service_update.go index ff8cded8b..e05eebf56 100644 --- a/vendor/github.com/docker/docker/client/service_update.go +++ b/vendor/github.com/docker/docker/client/service_update.go @@ -3,30 +3,31 @@ package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" + "net/http" "net/url" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" + "github.com/docker/docker/api/types/versions" ) // ServiceUpdate updates a Service. The version number is required to avoid conflicting writes. // It should be the value as set *before* the update. You can find this value in the Meta field // of swarm.Service, which can be found using ServiceInspectWithRaw. -func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) { +func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (swarm.ServiceUpdateResponse, error) { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + var ( query = url.Values{} - response = types.ServiceUpdateResponse{} + response = swarm.ServiceUpdateResponse{} ) - headers := map[string][]string{ - "version": {cli.version}, - } - - if options.EncodedRegistryAuth != "" { - headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} - } - if options.RegistryAuthFrom != "" { query.Set("registryAuthFrom", options.RegistryAuthFrom) } @@ -60,6 +61,16 @@ func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version } } + headers := http.Header{} + if versions.LessThan(cli.version, "1.30") { + // the custom "version" header was used by engine API before 20.10 + // (API 1.30) to switch between client- and server-side lookup of + // image digests. + headers["version"] = []string{cli.version} + } + if options.EncodedRegistryAuth != "" { + headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} + } resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers) defer ensureReaderClosed(resp) if err != nil { diff --git a/vendor/github.com/docker/docker/client/task_logs.go b/vendor/github.com/docker/docker/client/task_logs.go index 6222fab57..b8c20e71d 100644 --- a/vendor/github.com/docker/docker/client/task_logs.go +++ b/vendor/github.com/docker/docker/client/task_logs.go @@ -6,13 +6,13 @@ import ( "net/url" "time" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" timetypes "github.com/docker/docker/api/types/time" ) // TaskLogs returns the logs generated by a task in an io.ReadCloser. // It's up to the caller to close the stream. -func (cli *Client) TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { +func (cli *Client) TaskLogs(ctx context.Context, taskID string, options container.LogsOptions) (io.ReadCloser, error) { query := url.Values{} if options.ShowStdout { query.Set("stdout", "1") diff --git a/vendor/github.com/docker/docker/client/transport.go b/vendor/github.com/docker/docker/client/transport.go deleted file mode 100644 index 554134436..000000000 --- a/vendor/github.com/docker/docker/client/transport.go +++ /dev/null @@ -1,17 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "crypto/tls" - "net/http" -) - -// resolveTLSConfig attempts to resolve the TLS configuration from the -// RoundTripper. -func resolveTLSConfig(transport http.RoundTripper) *tls.Config { - switch tr := transport.(type) { - case *http.Transport: - return tr.TLSClientConfig - default: - return nil - } -} diff --git a/vendor/github.com/docker/docker/client/volume_prune.go b/vendor/github.com/docker/docker/client/volume_prune.go index 6e324708f..9333f6ee7 100644 --- a/vendor/github.com/docker/docker/client/volume_prune.go +++ b/vendor/github.com/docker/docker/client/volume_prune.go @@ -13,7 +13,7 @@ import ( func (cli *Client) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (types.VolumesPruneReport, error) { var report types.VolumesPruneReport - if err := cli.NewVersionError("1.25", "volume prune"); err != nil { + if err := cli.NewVersionError(ctx, "1.25", "volume prune"); err != nil { return report, err } diff --git a/vendor/github.com/docker/docker/client/volume_remove.go b/vendor/github.com/docker/docker/client/volume_remove.go index 1f2643836..31e08cb97 100644 --- a/vendor/github.com/docker/docker/client/volume_remove.go +++ b/vendor/github.com/docker/docker/client/volume_remove.go @@ -10,8 +10,14 @@ import ( // VolumeRemove removes a volume from the docker host. func (cli *Client) VolumeRemove(ctx context.Context, volumeID string, force bool) error { query := url.Values{} - if versions.GreaterThanOrEqualTo(cli.version, "1.25") { - if force { + if force { + // Make sure we negotiated (if the client is configured to do so), + // as code below contains API-version specific handling of options. + // + // Normally, version-negotiation (if enabled) would not happen until + // the API request is made. + cli.checkVersion(ctx) + if versions.GreaterThanOrEqualTo(cli.version, "1.25") { query.Set("force", "1") } } diff --git a/vendor/github.com/docker/docker/client/volume_update.go b/vendor/github.com/docker/docker/client/volume_update.go index 33bd31e53..151863f07 100644 --- a/vendor/github.com/docker/docker/client/volume_update.go +++ b/vendor/github.com/docker/docker/client/volume_update.go @@ -11,7 +11,7 @@ import ( // VolumeUpdate updates a volume. This only works for Cluster Volumes, and // only some fields can be updated. func (cli *Client) VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error { - if err := cli.NewVersionError("1.42", "volume update"); err != nil { + if err := cli.NewVersionError(ctx, "1.42", "volume update"); err != nil { return err } diff --git a/vendor/github.com/docker/docker/errdefs/defs.go b/vendor/github.com/docker/docker/errdefs/defs.go index 61e7456b4..a5523c3e9 100644 --- a/vendor/github.com/docker/docker/errdefs/defs.go +++ b/vendor/github.com/docker/docker/errdefs/defs.go @@ -1,4 +1,4 @@ -package errdefs // import "github.com/docker/docker/errdefs" +package errdefs // ErrNotFound signals that the requested object doesn't exist type ErrNotFound interface { diff --git a/vendor/github.com/docker/docker/errdefs/helpers.go b/vendor/github.com/docker/docker/errdefs/helpers.go index fe06fb6f7..042de4b7b 100644 --- a/vendor/github.com/docker/docker/errdefs/helpers.go +++ b/vendor/github.com/docker/docker/errdefs/helpers.go @@ -1,4 +1,4 @@ -package errdefs // import "github.com/docker/docker/errdefs" +package errdefs import "context" diff --git a/vendor/github.com/docker/docker/errdefs/http_helpers.go b/vendor/github.com/docker/docker/errdefs/http_helpers.go index 77bda389d..ebcd78930 100644 --- a/vendor/github.com/docker/docker/errdefs/http_helpers.go +++ b/vendor/github.com/docker/docker/errdefs/http_helpers.go @@ -1,4 +1,4 @@ -package errdefs // import "github.com/docker/docker/errdefs" +package errdefs import ( "net/http" diff --git a/vendor/github.com/docker/docker/errdefs/is.go b/vendor/github.com/docker/docker/errdefs/is.go index 3abf07d0c..f94034cbd 100644 --- a/vendor/github.com/docker/docker/errdefs/is.go +++ b/vendor/github.com/docker/docker/errdefs/is.go @@ -1,9 +1,18 @@ -package errdefs // import "github.com/docker/docker/errdefs" +package errdefs + +import ( + "context" + "errors" +) type causer interface { Cause() error } +type wrapErr interface { + Unwrap() error +} + func getImplementer(err error) error { switch e := err.(type) { case @@ -23,6 +32,8 @@ func getImplementer(err error) error { return err case causer: return getImplementer(e.Cause()) + case wrapErr: + return getImplementer(e.Unwrap()) default: return err } @@ -105,3 +116,8 @@ func IsDataLoss(err error) bool { _, ok := getImplementer(err).(ErrDataLoss) return ok } + +// IsContext returns if the passed in error is due to context cancellation or deadline exceeded. +func IsContext(err error) bool { + return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} diff --git a/vendor/github.com/docker/docker/image/spec/specs-go/v1/image.go b/vendor/github.com/docker/docker/image/spec/specs-go/v1/image.go new file mode 100644 index 000000000..167261763 --- /dev/null +++ b/vendor/github.com/docker/docker/image/spec/specs-go/v1/image.go @@ -0,0 +1,54 @@ +package v1 + +import ( + "time" + + ocispec "github.com/opencontainers/image-spec/specs-go/v1" +) + +const DockerOCIImageMediaType = "application/vnd.docker.container.image.v1+json" + +// DockerOCIImage is a ocispec.Image extended with Docker specific Config. +type DockerOCIImage struct { + ocispec.Image + + // Shadow ocispec.Image.Config + Config DockerOCIImageConfig `json:"config,omitempty"` +} + +// DockerOCIImageConfig is a ocispec.ImageConfig extended with Docker specific fields. +type DockerOCIImageConfig struct { + ocispec.ImageConfig + + DockerOCIImageConfigExt +} + +// DockerOCIImageConfigExt contains Docker-specific fields in DockerImageConfig. +type DockerOCIImageConfigExt struct { + Healthcheck *HealthcheckConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy + + OnBuild []string `json:",omitempty"` // ONBUILD metadata that were defined on the image Dockerfile + Shell []string `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT +} + +// HealthcheckConfig holds configuration settings for the HEALTHCHECK feature. +type HealthcheckConfig struct { + // Test is the test to perform to check that the container is healthy. + // An empty slice means to inherit the default. + // The options are: + // {} : inherit healthcheck + // {"NONE"} : disable healthcheck + // {"CMD", args...} : exec arguments directly + // {"CMD-SHELL", command} : run command with system's default shell + Test []string `json:",omitempty"` + + // Zero means to inherit. Durations are expressed as integer nanoseconds. + Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. + Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. + StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. + StartInterval time.Duration `json:",omitempty"` // The interval to attempt healthchecks at during the start period + + // Retries is the number of consecutive failures needed to consider a container as unhealthy. + // Zero means inherit. + Retries int `json:",omitempty"` +} diff --git a/vendor/github.com/docker/docker/internal/multierror/multierror.go b/vendor/github.com/docker/docker/internal/multierror/multierror.go new file mode 100644 index 000000000..cf4d6a595 --- /dev/null +++ b/vendor/github.com/docker/docker/internal/multierror/multierror.go @@ -0,0 +1,46 @@ +package multierror + +import ( + "strings" +) + +// Join is a drop-in replacement for errors.Join with better formatting. +func Join(errs ...error) error { + n := 0 + for _, err := range errs { + if err != nil { + n++ + } + } + if n == 0 { + return nil + } + e := &joinError{ + errs: make([]error, 0, n), + } + for _, err := range errs { + if err != nil { + e.errs = append(e.errs, err) + } + } + return e +} + +type joinError struct { + errs []error +} + +func (e *joinError) Error() string { + if len(e.errs) == 1 { + return strings.TrimSpace(e.errs[0].Error()) + } + stringErrs := make([]string, 0, len(e.errs)) + for _, subErr := range e.errs { + stringErrs = append(stringErrs, strings.Replace(subErr.Error(), "\n", "\n\t", -1)) + } + return "* " + strings.Join(stringErrs, "\n* ") +} + +func (e *joinError) Unwrap() []error { + return e.errs +} diff --git a/vendor/github.com/emicklei/go-restful/v3/CHANGES.md b/vendor/github.com/emicklei/go-restful/v3/CHANGES.md index 02a73ccfd..5edd5a7ca 100644 --- a/vendor/github.com/emicklei/go-restful/v3/CHANGES.md +++ b/vendor/github.com/emicklei/go-restful/v3/CHANGES.md @@ -1,6 +1,15 @@ # Change history of go-restful -## [v3.10.1] - 2022-11-19 +## [v3.11.0] - 2023-08-19 + +- restored behavior as <= v3.9.0 with option to change path strategy using TrimRightSlashEnabled. + +## [v3.10.2] - 2023-03-09 - DO NOT USE + +- introduced MergePathStrategy to be able to revert behaviour of path concatenation to 3.9.0 + see comment in Readme how to customize this behaviour. + +## [v3.10.1] - 2022-11-19 - DO NOT USE - fix broken 3.10.0 by using path package for joining paths diff --git a/vendor/github.com/emicklei/go-restful/v3/README.md b/vendor/github.com/emicklei/go-restful/v3/README.md index 0625359dc..e3e30080e 100644 --- a/vendor/github.com/emicklei/go-restful/v3/README.md +++ b/vendor/github.com/emicklei/go-restful/v3/README.md @@ -79,7 +79,7 @@ func (u UserResource) findUser(request *restful.Request, response *restful.Respo - Content encoding (gzip,deflate) of request and response payloads - Automatic responses on OPTIONS (using a filter) - Automatic CORS request handling (using a filter) -- API declaration for Swagger UI ([go-restful-openapi](https://github.com/emicklei/go-restful-openapi), see [go-restful-swagger12](https://github.com/emicklei/go-restful-swagger12)) +- API declaration for Swagger UI ([go-restful-openapi](https://github.com/emicklei/go-restful-openapi)) - Panic recovery to produce HTTP 500, customizable using RecoverHandler(...) - Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...) - Configurable (trace) logging @@ -96,6 +96,7 @@ There are several hooks to customize the behavior of the go-restful package. - Compression - Encoders for other serializers - Use [jsoniter](https://github.com/json-iterator/go) by building this package using a build tag, e.g. `go build -tags=jsoniter .` +- Use the package variable `TrimRightSlashEnabled` (default true) to control the behavior of matching routes that end with a slash `/` ## Resources @@ -108,4 +109,4 @@ There are several hooks to customize the behavior of the go-restful package. Type ```git shortlog -s``` for a full list of contributors. -© 2012 - 2022, http://ernestmicklei.com. MIT License. Contributions are welcome. +© 2012 - 2023, http://ernestmicklei.com. MIT License. Contributions are welcome. diff --git a/vendor/github.com/emicklei/go-restful/v3/route.go b/vendor/github.com/emicklei/go-restful/v3/route.go index ea05b3da8..306c44be7 100644 --- a/vendor/github.com/emicklei/go-restful/v3/route.go +++ b/vendor/github.com/emicklei/go-restful/v3/route.go @@ -40,7 +40,8 @@ type Route struct { ParameterDocs []*Parameter ResponseErrors map[int]ResponseError DefaultResponse *ResponseError - ReadSample, WriteSample interface{} // structs that model an example request or response payload + ReadSample, WriteSample interface{} // structs that model an example request or response payload + WriteSamples []interface{} // if more than one return types is possible (oneof) then this will contain multiple values // Extra information used to store custom information about the route. Metadata map[string]interface{} @@ -164,7 +165,13 @@ func tokenizePath(path string) []string { if "/" == path { return nil } - return strings.Split(strings.TrimLeft(path, "/"), "/") + if TrimRightSlashEnabled { + // 3.9.0 + return strings.Split(strings.Trim(path, "/"), "/") + } else { + // 3.10.2 + return strings.Split(strings.TrimLeft(path, "/"), "/") + } } // for debugging @@ -177,4 +184,8 @@ func (r *Route) EnableContentEncoding(enabled bool) { r.contentEncodingEnabled = &enabled } -var TrimRightSlashEnabled = false +// TrimRightSlashEnabled controls whether +// - path on route building is using path.Join +// - the path of the incoming request is trimmed of its slash suffux. +// Value of true matches the behavior of <= 3.9.0 +var TrimRightSlashEnabled = true diff --git a/vendor/github.com/emicklei/go-restful/v3/route_builder.go b/vendor/github.com/emicklei/go-restful/v3/route_builder.go index 830ebf148..75168c12e 100644 --- a/vendor/github.com/emicklei/go-restful/v3/route_builder.go +++ b/vendor/github.com/emicklei/go-restful/v3/route_builder.go @@ -31,17 +31,18 @@ type RouteBuilder struct { typeNameHandleFunc TypeNameHandleFunction // required // documentation - doc string - notes string - operation string - readSample, writeSample interface{} - parameters []*Parameter - errorMap map[int]ResponseError - defaultResponse *ResponseError - metadata map[string]interface{} - extensions map[string]interface{} - deprecated bool - contentEncodingEnabled *bool + doc string + notes string + operation string + readSample interface{} + writeSamples []interface{} + parameters []*Parameter + errorMap map[int]ResponseError + defaultResponse *ResponseError + metadata map[string]interface{} + extensions map[string]interface{} + deprecated bool + contentEncodingEnabled *bool } // Do evaluates each argument with the RouteBuilder itself. @@ -135,9 +136,9 @@ func (b RouteBuilder) ParameterNamed(name string) (p *Parameter) { return p } -// Writes tells what resource type will be written as the response payload. Optional. -func (b *RouteBuilder) Writes(sample interface{}) *RouteBuilder { - b.writeSample = sample +// Writes tells which one of the resource types will be written as the response payload. Optional. +func (b *RouteBuilder) Writes(samples ...interface{}) *RouteBuilder { + b.writeSamples = samples // oneof return b } @@ -342,19 +343,29 @@ func (b *RouteBuilder) Build() Route { ResponseErrors: b.errorMap, DefaultResponse: b.defaultResponse, ReadSample: b.readSample, - WriteSample: b.writeSample, + WriteSamples: b.writeSamples, Metadata: b.metadata, Deprecated: b.deprecated, contentEncodingEnabled: b.contentEncodingEnabled, allowedMethodsWithoutContentType: b.allowedMethodsWithoutContentType, } + // set WriteSample if one specified + if len(b.writeSamples) == 1 { + route.WriteSample = b.writeSamples[0] + } route.Extensions = b.extensions route.postBuild() return route } -func concatPath(path1, path2 string) string { - return path.Join(path1, path2) +// merge two paths using the current (package global) merge path strategy. +func concatPath(rootPath, routePath string) string { + + if TrimRightSlashEnabled { + return strings.TrimRight(rootPath, "/") + "/" + strings.TrimLeft(routePath, "/") + } else { + return path.Join(rootPath, routePath) + } } var anonymousFuncCount int32 diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/deprecation.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/deprecation.pb.go index 2a73462bf..75ba29582 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/deprecation.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/deprecation.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/annotations/deprecation.proto package annotations diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/resource.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/resource.pb.go index 597d6da5c..5da50ae67 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/resource.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/annotations/resource.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/annotations/resource.proto package annotations diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.go index 7f61c14b8..6ad40af64 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/address.proto package corev3 @@ -138,6 +138,7 @@ type EnvoyInternalAddress struct { unknownFields protoimpl.UnknownFields // Types that are assignable to AddressNameSpecifier: + // // *EnvoyInternalAddress_ServerListenerName AddressNameSpecifier isEnvoyInternalAddress_AddressNameSpecifier `protobuf_oneof:"address_name_specifier"` // Specifies an endpoint identifier to distinguish between multiple endpoints for the same internal listener in a @@ -219,18 +220,19 @@ type SocketAddress struct { Protocol SocketAddress_Protocol `protobuf:"varint,1,opt,name=protocol,proto3,enum=envoy.config.core.v3.SocketAddress_Protocol" json:"protocol,omitempty"` // The address for this socket. :ref:`Listeners ` will bind - // to the address. An empty address is not allowed. Specify ``0.0.0.0`` or ``::`` + // to the address. An empty address is not allowed. Specify “0.0.0.0“ or “::“ // to bind to any address. [#comment:TODO(zuercher) reinstate when implemented: // It is possible to distinguish a Listener address via the prefix/suffix matching // in :ref:`FilterChainMatch `.] When used // within an upstream :ref:`BindConfig `, the address // controls the source address of outbound connections. For :ref:`clusters // `, the cluster type determines whether the - // address must be an IP (``STATIC`` or ``EDS`` clusters) or a hostname resolved by DNS - // (``STRICT_DNS`` or ``LOGICAL_DNS`` clusters). Address resolution can be customized + // address must be an IP (“STATIC“ or “EDS“ clusters) or a hostname resolved by DNS + // (“STRICT_DNS“ or “LOGICAL_DNS“ clusters). Address resolution can be customized // via :ref:`resolver_name `. Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` // Types that are assignable to PortSpecifier: + // // *SocketAddress_PortValue // *SocketAddress_NamedPort PortSpecifier isSocketAddress_PortSpecifier `protobuf_oneof:"port_specifier"` @@ -238,12 +240,12 @@ type SocketAddress struct { // this is empty, a context dependent default applies. If the address is a concrete // IP address, no resolution will occur. If address is a hostname this // should be set for resolution other than DNS. Specifying a custom resolver with - // ``STRICT_DNS`` or ``LOGICAL_DNS`` will generate an error at runtime. + // “STRICT_DNS“ or “LOGICAL_DNS“ will generate an error at runtime. ResolverName string `protobuf:"bytes,5,opt,name=resolver_name,json=resolverName,proto3" json:"resolver_name,omitempty"` // When binding to an IPv6 address above, this enables `IPv4 compatibility - // `_. Binding to ``::`` will + // `_. Binding to “::“ will // allow both IPv4 and IPv6 connections, with peer IPv4 addresses mapped into - // IPv6 space as ``::FFFF:``. + // IPv6 space as “::FFFF:“. Ipv4Compat bool `protobuf:"varint,6,opt,name=ipv4_compat,json=ipv4Compat,proto3" json:"ipv4_compat,omitempty"` } @@ -481,7 +483,7 @@ func (x *ExtraSourceAddress) GetSocketOptions() *SocketOptionsOverride { return nil } -// [#next-free-field: 6] +// [#next-free-field: 7] type BindConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -489,31 +491,32 @@ type BindConfig struct { // The address to bind to when creating a socket. SourceAddress *SocketAddress `protobuf:"bytes,1,opt,name=source_address,json=sourceAddress,proto3" json:"source_address,omitempty"` - // Whether to set the ``IP_FREEBIND`` option when creating the socket. When this + // Whether to set the “IP_FREEBIND“ option when creating the socket. When this // flag is set to true, allows the :ref:`source_address // ` to be an IP address // that is not configured on the system running Envoy. When this flag is set - // to false, the option ``IP_FREEBIND`` is disabled on the socket. When this + // to false, the option “IP_FREEBIND“ is disabled on the socket. When this // flag is not set (default), the socket is not modified, i.e. the option is // neither enabled nor disabled. Freebind *wrappers.BoolValue `protobuf:"bytes,2,opt,name=freebind,proto3" json:"freebind,omitempty"` // Additional socket options that may not be present in Envoy source code or // precompiled binaries. SocketOptions []*SocketOption `protobuf:"bytes,3,rep,name=socket_options,json=socketOptions,proto3" json:"socket_options,omitempty"` - // Extra source addresses appended to the address specified in the `source_address` - // field. This enables to specify multiple source addresses. Currently, only one extra - // address can be supported, and the extra address should have a different IP version - // with the address in the `source_address` field. The address which has the same IP - // version with the target host's address IP version will be used as bind address. If more - // than one extra address specified, only the first address matched IP version will be - // returned. If there is no same IP version address found, the address in the `source_address` - // will be returned. + // Extra source addresses appended to the address specified in the “source_address“ + // field. This enables to specify multiple source addresses. + // The source address selection is determined by :ref:`local_address_selector + // `. ExtraSourceAddresses []*ExtraSourceAddress `protobuf:"bytes,5,rep,name=extra_source_addresses,json=extraSourceAddresses,proto3" json:"extra_source_addresses,omitempty"` // Deprecated by // :ref:`extra_source_addresses ` // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/address.proto. AdditionalSourceAddresses []*SocketAddress `protobuf:"bytes,4,rep,name=additional_source_addresses,json=additionalSourceAddresses,proto3" json:"additional_source_addresses,omitempty"` + // Custom local address selector to override the default (i.e. + // :ref:`DefaultLocalAddressSelector + // `). + // [#extension-category: envoy.upstream.local_address_selector] + LocalAddressSelector *TypedExtensionConfig `protobuf:"bytes,6,opt,name=local_address_selector,json=localAddressSelector,proto3" json:"local_address_selector,omitempty"` } func (x *BindConfig) Reset() { @@ -576,7 +579,7 @@ func (x *BindConfig) GetExtraSourceAddresses() []*ExtraSourceAddress { return nil } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/config/core/v3/address.proto. func (x *BindConfig) GetAdditionalSourceAddresses() []*SocketAddress { if x != nil { return x.AdditionalSourceAddresses @@ -584,6 +587,13 @@ func (x *BindConfig) GetAdditionalSourceAddresses() []*SocketAddress { return nil } +func (x *BindConfig) GetLocalAddressSelector() *TypedExtensionConfig { + if x != nil { + return x.LocalAddressSelector + } + return nil +} + // Addresses specify either a logical or physical address and port, which are // used to tell Envoy where to bind/listen, connect to upstream and find // management servers. @@ -593,6 +603,7 @@ type Address struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Address: + // // *Address_SocketAddress // *Address_Pipe // *Address_EnvoyInternalAddress @@ -690,7 +701,7 @@ type CidrRange struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // IPv4 or IPv6 address, e.g. ``192.0.0.0`` or ``2001:db8::``. + // IPv4 or IPv6 address, e.g. “192.0.0.0“ or “2001:db8::“. AddressPrefix string `protobuf:"bytes,1,opt,name=address_prefix,json=addressPrefix,proto3" json:"address_prefix,omitempty"` // Length of prefix, e.g. 0, 32. Defaults to 0 when unset. PrefixLen *wrappers.UInt32Value `protobuf:"bytes,2,opt,name=prefix_len,json=prefixLen,proto3" json:"prefix_len,omitempty"` @@ -748,153 +759,162 @@ var file_envoy_config_core_v3_address_proto_rawDesc = []byte{ 0x0a, 0x22, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x14, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x1a, 0x28, 0x65, 0x6e, 0x76, 0x6f, + 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x1a, 0x24, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, - 0x2f, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x23, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, - 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1d, 0x75, 0x64, 0x70, 0x61, 0x2f, - 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x73, 0x74, 0x61, 0x74, - 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x21, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, - 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x76, 0x65, 0x72, 0x73, 0x69, - 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, - 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x60, 0x0a, 0x04, 0x50, 0x69, 0x70, 0x65, 0x12, 0x1b, 0x0a, 0x04, - 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, - 0x02, 0x10, 0x01, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x1c, 0x0a, 0x04, 0x6d, 0x6f, 0x64, - 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x2a, 0x03, 0x18, 0xff, - 0x03, 0x52, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x3a, 0x1d, 0x9a, 0xc5, 0x88, 0x1e, 0x18, 0x0a, 0x16, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, - 0x65, 0x2e, 0x50, 0x69, 0x70, 0x65, 0x22, 0x8a, 0x01, 0x0a, 0x14, 0x45, 0x6e, 0x76, 0x6f, 0x79, - 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, - 0x32, 0x0a, 0x14, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, - 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, - 0x12, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x65, 0x72, 0x4e, - 0x61, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, - 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, - 0x6e, 0x74, 0x49, 0x64, 0x42, 0x1d, 0x0a, 0x16, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, - 0x6e, 0x61, 0x6d, 0x65, 0x5f, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, - 0xf8, 0x42, 0x01, 0x22, 0xf6, 0x02, 0x0a, 0x0d, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, - 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x52, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, - 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, - 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x2e, 0x50, 0x72, 0x6f, - 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x82, 0x01, 0x02, 0x10, 0x01, 0x52, - 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x21, 0x0a, 0x07, 0x61, 0x64, 0x64, - 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, - 0x02, 0x10, 0x01, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x2a, 0x0a, 0x0a, - 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, - 0x42, 0x09, 0xfa, 0x42, 0x06, 0x2a, 0x04, 0x18, 0xff, 0xff, 0x03, 0x48, 0x00, 0x52, 0x09, 0x70, - 0x6f, 0x72, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1f, 0x0a, 0x0a, 0x6e, 0x61, 0x6d, 0x65, - 0x64, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x09, - 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x73, - 0x6f, 0x6c, 0x76, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1f, - 0x0a, 0x0b, 0x69, 0x70, 0x76, 0x34, 0x5f, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x18, 0x06, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x0a, 0x69, 0x70, 0x76, 0x34, 0x43, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x22, - 0x1c, 0x0a, 0x08, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x07, 0x0a, 0x03, 0x54, - 0x43, 0x50, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x55, 0x44, 0x50, 0x10, 0x01, 0x3a, 0x26, 0x9a, - 0xc5, 0x88, 0x1e, 0x21, 0x0a, 0x1f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, - 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, - 0x64, 0x72, 0x65, 0x73, 0x73, 0x42, 0x15, 0x0a, 0x0e, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x73, 0x70, - 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0x90, 0x02, 0x0a, - 0x0c, 0x54, 0x63, 0x70, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x12, 0x47, 0x0a, - 0x10, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x72, 0x6f, 0x62, 0x65, - 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0f, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, - 0x50, 0x72, 0x6f, 0x62, 0x65, 0x73, 0x12, 0x43, 0x0a, 0x0e, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, - 0x69, 0x76, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0d, 0x6b, 0x65, - 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x4b, 0x0a, 0x12, 0x6b, - 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, - 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x11, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, - 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x3a, 0x25, 0x9a, 0xc5, 0x88, 0x1e, 0x20, 0x0a, - 0x1e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, - 0x72, 0x65, 0x2e, 0x54, 0x63, 0x70, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x22, - 0xb1, 0x01, 0x0a, 0x12, 0x45, 0x78, 0x74, 0x72, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, - 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x47, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, - 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, - 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x42, 0x08, 0xfa, 0x42, - 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, - 0x52, 0x0a, 0x0e, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, - 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x4f, 0x76, 0x65, 0x72, - 0x72, 0x69, 0x64, 0x65, 0x52, 0x0d, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x22, 0xd2, 0x03, 0x0a, 0x0a, 0x42, 0x69, 0x6e, 0x64, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x12, 0x4a, 0x0a, 0x0e, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x61, 0x64, 0x64, - 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, - 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, - 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x52, - 0x0d, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x36, - 0x0a, 0x08, 0x66, 0x72, 0x65, 0x65, 0x62, 0x69, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x66, 0x72, - 0x65, 0x65, 0x62, 0x69, 0x6e, 0x64, 0x12, 0x49, 0x0a, 0x0e, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, - 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, - 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, - 0x6f, 0x6e, 0x52, 0x0d, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x12, 0x5e, 0x0a, 0x16, 0x65, 0x78, 0x74, 0x72, 0x61, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x28, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x45, 0x78, 0x74, 0x72, 0x61, 0x53, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x52, 0x14, 0x65, 0x78, 0x74, - 0x72, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, - 0x73, 0x12, 0x70, 0x0a, 0x1b, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x5f, - 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, - 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, - 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x42, 0x0b, 0x18, 0x01, 0x92, - 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x52, 0x19, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, - 0x6f, 0x6e, 0x61, 0x6c, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, - 0x73, 0x65, 0x73, 0x3a, 0x23, 0x9a, 0xc5, 0x88, 0x1e, 0x1e, 0x0a, 0x1c, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x42, 0x69, - 0x6e, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x9f, 0x02, 0x0a, 0x07, 0x41, 0x64, 0x64, - 0x72, 0x65, 0x73, 0x73, 0x12, 0x4c, 0x0a, 0x0e, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x61, - 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x65, + 0x2f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x1a, 0x28, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, + 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x6f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, + 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x23, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x64, 0x65, + 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, + 0x1d, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x21, + 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69, + 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x60, 0x0a, 0x04, 0x50, 0x69, + 0x70, 0x65, 0x12, 0x1b, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, + 0x1c, 0x0a, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x42, 0x08, 0xfa, + 0x42, 0x05, 0x2a, 0x03, 0x18, 0xff, 0x03, 0x52, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x3a, 0x1d, 0x9a, + 0xc5, 0x88, 0x1e, 0x18, 0x0a, 0x16, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, + 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x69, 0x70, 0x65, 0x22, 0x8a, 0x01, 0x0a, + 0x14, 0x45, 0x6e, 0x76, 0x6f, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x41, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x32, 0x0a, 0x14, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, + 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x12, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x4c, 0x69, 0x73, + 0x74, 0x65, 0x6e, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x6e, 0x64, + 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, + 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x49, 0x64, 0x42, 0x1d, 0x0a, 0x16, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x5f, 0x73, 0x70, 0x65, 0x63, 0x69, + 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0xf6, 0x02, 0x0a, 0x0d, 0x53, 0x6f, + 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x52, 0x0a, 0x08, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x42, 0x08, 0xfa, 0x42, 0x05, + 0x82, 0x01, 0x02, 0x10, 0x01, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, + 0x21, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x12, 0x2a, 0x0a, 0x0a, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x42, 0x09, 0xfa, 0x42, 0x06, 0x2a, 0x04, 0x18, 0xff, 0xff, + 0x03, 0x48, 0x00, 0x52, 0x09, 0x70, 0x6f, 0x72, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1f, + 0x0a, 0x0a, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x09, 0x48, 0x00, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x50, 0x6f, 0x72, 0x74, 0x12, + 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, 0x72, + 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x69, 0x70, 0x76, 0x34, 0x5f, 0x63, 0x6f, 0x6d, + 0x70, 0x61, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x69, 0x70, 0x76, 0x34, 0x43, + 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x22, 0x1c, 0x0a, 0x08, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, + 0x6c, 0x12, 0x07, 0x0a, 0x03, 0x54, 0x43, 0x50, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x55, 0x44, + 0x50, 0x10, 0x01, 0x3a, 0x26, 0x9a, 0xc5, 0x88, 0x1e, 0x21, 0x0a, 0x1f, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x6f, + 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x42, 0x15, 0x0a, 0x0e, 0x70, + 0x6f, 0x72, 0x74, 0x5f, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, + 0x42, 0x01, 0x22, 0x90, 0x02, 0x0a, 0x0c, 0x54, 0x63, 0x70, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, + 0x69, 0x76, 0x65, 0x12, 0x47, 0x0a, 0x10, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, + 0x5f, 0x70, 0x72, 0x6f, 0x62, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0f, 0x6b, 0x65, 0x65, + 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x73, 0x12, 0x43, 0x0a, 0x0e, + 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x52, 0x0d, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x54, 0x69, 0x6d, + 0x65, 0x12, 0x4b, 0x0a, 0x12, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x5f, 0x69, + 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x11, 0x6b, 0x65, 0x65, + 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x3a, 0x25, + 0x9a, 0xc5, 0x88, 0x1e, 0x20, 0x0a, 0x1e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, + 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x54, 0x63, 0x70, 0x4b, 0x65, 0x65, 0x70, + 0x61, 0x6c, 0x69, 0x76, 0x65, 0x22, 0xb1, 0x01, 0x0a, 0x12, 0x45, 0x78, 0x74, 0x72, 0x61, 0x53, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x47, 0x0a, 0x07, + 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x07, 0x61, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x52, 0x0a, 0x0e, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, + 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x4f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x52, 0x0d, 0x73, 0x6f, 0x63, 0x6b, + 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xb4, 0x04, 0x0a, 0x0a, 0x42, 0x69, + 0x6e, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x4a, 0x0a, 0x0e, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, + 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x52, 0x0d, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x12, 0x36, 0x0a, 0x08, 0x66, 0x72, 0x65, 0x65, 0x62, 0x69, 0x6e, 0x64, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x52, 0x08, 0x66, 0x72, 0x65, 0x65, 0x62, 0x69, 0x6e, 0x64, 0x12, 0x49, 0x0a, 0x0e, + 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, + 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x5e, 0x0a, 0x16, 0x65, 0x78, 0x74, 0x72, 0x61, + 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x45, + 0x78, 0x74, 0x72, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x52, 0x14, 0x65, 0x78, 0x74, 0x72, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x64, + 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x12, 0x70, 0x0a, 0x1b, 0x61, 0x64, 0x64, 0x69, 0x74, + 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x61, 0x64, 0x64, + 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, - 0x73, 0x48, 0x00, 0x52, 0x0d, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, - 0x73, 0x73, 0x12, 0x30, 0x0a, 0x04, 0x70, 0x69, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, - 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x50, 0x69, 0x70, 0x65, 0x48, 0x00, 0x52, 0x04, - 0x70, 0x69, 0x70, 0x65, 0x12, 0x62, 0x0a, 0x16, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x5f, 0x69, 0x6e, - 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x45, 0x6e, 0x76, 0x6f, + 0x73, 0x42, 0x0b, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x18, 0x01, 0x52, 0x19, + 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x12, 0x60, 0x0a, 0x16, 0x6c, 0x6f, 0x63, + 0x61, 0x6c, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x73, 0x65, 0x6c, 0x65, 0x63, + 0x74, 0x6f, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, + 0x2e, 0x54, 0x79, 0x70, 0x65, 0x64, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x43, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x14, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x41, 0x64, 0x64, 0x72, + 0x65, 0x73, 0x73, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x3a, 0x23, 0x9a, 0xc5, 0x88, + 0x1e, 0x1e, 0x0a, 0x1c, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, + 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x42, 0x69, 0x6e, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x22, 0x9f, 0x02, 0x0a, 0x07, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x4c, 0x0a, 0x0e, + 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, + 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x48, 0x00, 0x52, 0x0d, 0x73, 0x6f, 0x63, + 0x6b, 0x65, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x30, 0x0a, 0x04, 0x70, 0x69, + 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, + 0x50, 0x69, 0x70, 0x65, 0x48, 0x00, 0x52, 0x04, 0x70, 0x69, 0x70, 0x65, 0x12, 0x62, 0x0a, 0x16, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, + 0x2e, 0x76, 0x33, 0x2e, 0x45, 0x6e, 0x76, 0x6f, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, + 0x6c, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x48, 0x00, 0x52, 0x14, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, - 0x48, 0x00, 0x52, 0x14, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, - 0x6c, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x3a, 0x20, 0x9a, 0xc5, 0x88, 0x1e, 0x1b, 0x0a, - 0x19, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, - 0x72, 0x65, 0x2e, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x42, 0x0e, 0x0a, 0x07, 0x61, 0x64, - 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0xa6, 0x01, 0x0a, 0x09, 0x43, - 0x69, 0x64, 0x72, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x2e, 0x0a, 0x0e, 0x61, 0x64, 0x64, 0x72, - 0x65, 0x73, 0x73, 0x5f, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x0d, 0x61, 0x64, 0x64, 0x72, 0x65, - 0x73, 0x73, 0x50, 0x72, 0x65, 0x66, 0x69, 0x78, 0x12, 0x45, 0x0a, 0x0a, 0x70, 0x72, 0x65, 0x66, - 0x69, 0x78, 0x5f, 0x6c, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, - 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x2a, - 0x03, 0x18, 0x80, 0x01, 0x52, 0x09, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x4c, 0x65, 0x6e, 0x3a, - 0x22, 0x9a, 0xc5, 0x88, 0x1e, 0x1d, 0x0a, 0x1b, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x69, 0x64, 0x72, 0x52, 0x61, - 0x6e, 0x67, 0x65, 0x42, 0x80, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x3a, 0x20, 0x9a, 0xc5, 0x88, 0x1e, 0x1b, 0x0a, 0x19, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, + 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x41, 0x64, 0x64, 0x72, 0x65, + 0x73, 0x73, 0x42, 0x0e, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x03, 0xf8, + 0x42, 0x01, 0x22, 0xa6, 0x01, 0x0a, 0x09, 0x43, 0x69, 0x64, 0x72, 0x52, 0x61, 0x6e, 0x67, 0x65, + 0x12, 0x2e, 0x0a, 0x0e, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x70, 0x72, 0x65, 0x66, + 0x69, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, + 0x01, 0x52, 0x0d, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x50, 0x72, 0x65, 0x66, 0x69, 0x78, + 0x12, 0x45, 0x0a, 0x0a, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x5f, 0x6c, 0x65, 0x6e, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x2a, 0x03, 0x18, 0x80, 0x01, 0x52, 0x09, 0x70, 0x72, + 0x65, 0x66, 0x69, 0x78, 0x4c, 0x65, 0x6e, 0x3a, 0x22, 0x9a, 0xc5, 0x88, 0x1e, 0x1d, 0x0a, 0x1b, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x43, 0x69, 0x64, 0x72, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x42, 0x80, 0x01, 0xba, 0x80, + 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0c, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, - 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, - 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -925,6 +945,7 @@ var file_envoy_config_core_v3_address_proto_goTypes = []interface{}{ (*SocketOptionsOverride)(nil), // 10: envoy.config.core.v3.SocketOptionsOverride (*wrappers.BoolValue)(nil), // 11: google.protobuf.BoolValue (*SocketOption)(nil), // 12: envoy.config.core.v3.SocketOption + (*TypedExtensionConfig)(nil), // 13: envoy.config.core.v3.TypedExtensionConfig } var file_envoy_config_core_v3_address_proto_depIdxs = []int32{ 0, // 0: envoy.config.core.v3.SocketAddress.protocol:type_name -> envoy.config.core.v3.SocketAddress.Protocol @@ -938,15 +959,16 @@ var file_envoy_config_core_v3_address_proto_depIdxs = []int32{ 12, // 8: envoy.config.core.v3.BindConfig.socket_options:type_name -> envoy.config.core.v3.SocketOption 5, // 9: envoy.config.core.v3.BindConfig.extra_source_addresses:type_name -> envoy.config.core.v3.ExtraSourceAddress 3, // 10: envoy.config.core.v3.BindConfig.additional_source_addresses:type_name -> envoy.config.core.v3.SocketAddress - 3, // 11: envoy.config.core.v3.Address.socket_address:type_name -> envoy.config.core.v3.SocketAddress - 1, // 12: envoy.config.core.v3.Address.pipe:type_name -> envoy.config.core.v3.Pipe - 2, // 13: envoy.config.core.v3.Address.envoy_internal_address:type_name -> envoy.config.core.v3.EnvoyInternalAddress - 9, // 14: envoy.config.core.v3.CidrRange.prefix_len:type_name -> google.protobuf.UInt32Value - 15, // [15:15] is the sub-list for method output_type - 15, // [15:15] is the sub-list for method input_type - 15, // [15:15] is the sub-list for extension type_name - 15, // [15:15] is the sub-list for extension extendee - 0, // [0:15] is the sub-list for field type_name + 13, // 11: envoy.config.core.v3.BindConfig.local_address_selector:type_name -> envoy.config.core.v3.TypedExtensionConfig + 3, // 12: envoy.config.core.v3.Address.socket_address:type_name -> envoy.config.core.v3.SocketAddress + 1, // 13: envoy.config.core.v3.Address.pipe:type_name -> envoy.config.core.v3.Pipe + 2, // 14: envoy.config.core.v3.Address.envoy_internal_address:type_name -> envoy.config.core.v3.EnvoyInternalAddress + 9, // 15: envoy.config.core.v3.CidrRange.prefix_len:type_name -> google.protobuf.UInt32Value + 16, // [16:16] is the sub-list for method output_type + 16, // [16:16] is the sub-list for method input_type + 16, // [16:16] is the sub-list for extension type_name + 16, // [16:16] is the sub-list for extension extendee + 0, // [0:16] is the sub-list for field type_name } func init() { file_envoy_config_core_v3_address_proto_init() } @@ -954,6 +976,7 @@ func file_envoy_config_core_v3_address_proto_init() { if File_envoy_config_core_v3_address_proto != nil { return } + file_envoy_config_core_v3_extension_proto_init() file_envoy_config_core_v3_socket_option_proto_init() if !protoimpl.UnsafeEnabled { file_envoy_config_core_v3_address_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.validate.go index 25610ab04..1bf3f9958 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.validate.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/address.pb.validate.go @@ -1006,6 +1006,35 @@ func (m *BindConfig) validate(all bool) error { } + if all { + switch v := interface{}(m.GetLocalAddressSelector()).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, BindConfigValidationError{ + field: "LocalAddressSelector", + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, BindConfigValidationError{ + field: "LocalAddressSelector", + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(m.GetLocalAddressSelector()).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return BindConfigValidationError{ + field: "LocalAddressSelector", + reason: "embedded message failed validation", + cause: err, + } + } + } + if len(errors) > 0 { return BindConfigMultiError(errors) } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/backoff.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/backoff.pb.go index 63066573a..06b61820c 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/backoff.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/backoff.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/backoff.proto package corev3 @@ -114,15 +114,15 @@ var file_envoy_config_core_v3_backoff_proto_rawDesc = []byte{ 0x01, 0x02, 0x2a, 0x00, 0x52, 0x0b, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x3a, 0x28, 0x9a, 0xc5, 0x88, 0x1e, 0x23, 0x0a, 0x21, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x42, 0x61, 0x63, 0x6b, - 0x6f, 0x66, 0x66, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x42, 0x80, 0x01, 0x0a, 0x22, - 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, - 0x76, 0x33, 0x42, 0x0c, 0x42, 0x61, 0x63, 0x6b, 0x6f, 0x66, 0x66, 0x50, 0x72, 0x6f, 0x74, 0x6f, - 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, - 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, + 0x6f, 0x66, 0x66, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x42, 0x80, 0x01, 0xba, 0x80, + 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0c, 0x42, 0x61, 0x63, 0x6b, + 0x6f, 0x66, 0x66, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, + 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, + 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.go index d9ec4f4f8..8935f058a 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/base.proto package corev3 @@ -220,6 +220,9 @@ const ( // the header already exists. If the header doesn't exist then this will add the header // with specified key and value. HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD HeaderValueOption_HeaderAppendAction = 2 + // This action will overwrite the specified value by discarding any existing values if + // the header already exists. If the header doesn't exist then this will be no-op. + HeaderValueOption_OVERWRITE_IF_EXISTS HeaderValueOption_HeaderAppendAction = 3 ) // Enum value maps for HeaderValueOption_HeaderAppendAction. @@ -228,11 +231,13 @@ var ( 0: "APPEND_IF_EXISTS_OR_ADD", 1: "ADD_IF_ABSENT", 2: "OVERWRITE_IF_EXISTS_OR_ADD", + 3: "OVERWRITE_IF_EXISTS", } HeaderValueOption_HeaderAppendAction_value = map[string]int32{ "APPEND_IF_EXISTS_OR_ADD": 0, "ADD_IF_ABSENT": 1, "OVERWRITE_IF_EXISTS_OR_ADD": 2, + "OVERWRITE_IF_EXISTS": 3, } ) @@ -419,7 +424,7 @@ type Extension struct { // [#comment:TODO(yanavlasov): Link to the doc with existing configuration protos.] // [#comment:TODO(yanavlasov): Add tests when PR #9391 lands.] // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/base.proto. TypeDescriptor string `protobuf:"bytes,3,opt,name=type_descriptor,json=typeDescriptor,proto3" json:"type_descriptor,omitempty"` // The version is a property of the extension and maintained independently // of other extensions and the Envoy API. @@ -477,7 +482,7 @@ func (x *Extension) GetCategory() string { return "" } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/config/core/v3/base.proto. func (x *Extension) GetTypeDescriptor() string { if x != nil { return x.TypeDescriptor @@ -550,6 +555,7 @@ type Node struct { // E.g. "envoy" or "grpc" UserAgentName string `protobuf:"bytes,6,opt,name=user_agent_name,json=userAgentName,proto3" json:"user_agent_name,omitempty"` // Types that are assignable to UserAgentVersionType: + // // *Node_UserAgentVersion // *Node_UserAgentBuildVersion UserAgentVersionType isNode_UserAgentVersionType `protobuf_oneof:"user_agent_version_type"` @@ -557,16 +563,16 @@ type Node struct { Extensions []*Extension `protobuf:"bytes,9,rep,name=extensions,proto3" json:"extensions,omitempty"` // Client feature support list. These are well known features described // in the Envoy API repository for a given major version of an API. Client features - // use reverse DNS naming scheme, for example ``com.acme.feature``. + // use reverse DNS naming scheme, for example “com.acme.feature“. // See :ref:`the list of features ` that xDS client may // support. ClientFeatures []string `protobuf:"bytes,10,rep,name=client_features,json=clientFeatures,proto3" json:"client_features,omitempty"` // Known listening ports on the node as a generic hint to the management server // for filtering :ref:`listeners ` to be returned. For example, // if there is a listener bound to port 80, the list can optionally contain the - // SocketAddress ``(0.0.0.0,80)``. The field is optional and just a hint. + // SocketAddress “(0.0.0.0,80)“. The field is optional and just a hint. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/base.proto. ListeningAddresses []*Address `protobuf:"bytes,11,rep,name=listening_addresses,json=listeningAddresses,proto3" json:"listening_addresses,omitempty"` } @@ -679,7 +685,7 @@ func (x *Node) GetClientFeatures() []string { return nil } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/config/core/v3/base.proto. func (x *Node) GetListeningAddresses() []*Address { if x != nil { return x.ListeningAddresses @@ -724,28 +730,29 @@ func (*Node_UserAgentBuildVersion) isNode_UserAgentVersionType() {} // object to match against. There are some well defined metadata used today for // this purpose: // -// * ``{"envoy.lb": {"canary": }}`` This indicates the canary status of an -// endpoint and is also used during header processing -// (x-envoy-upstream-canary) and for stats purposes. +// - “{"envoy.lb": {"canary": }}“ This indicates the canary status of an +// endpoint and is also used during header processing +// (x-envoy-upstream-canary) and for stats purposes. +// // [#next-major-version: move to type/metadata/v2] type Metadata struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Key is the reverse DNS filter name, e.g. com.acme.widget. The ``envoy.*`` + // Key is the reverse DNS filter name, e.g. com.acme.widget. The “envoy.*“ // namespace is reserved for Envoy's built-in filters. - // If both ``filter_metadata`` and + // If both “filter_metadata“ and // :ref:`typed_filter_metadata ` // fields are present in the metadata with same keys, - // only ``typed_filter_metadata`` field will be parsed. + // only “typed_filter_metadata“ field will be parsed. FilterMetadata map[string]*_struct.Struct `protobuf:"bytes,1,rep,name=filter_metadata,json=filterMetadata,proto3" json:"filter_metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // Key is the reverse DNS filter name, e.g. com.acme.widget. The ``envoy.*`` + // Key is the reverse DNS filter name, e.g. com.acme.widget. The “envoy.*“ // namespace is reserved for Envoy's built-in filters. // The value is encoded as google.protobuf.Any. // If both :ref:`filter_metadata ` - // and ``typed_filter_metadata`` fields are present in the metadata with same keys, - // only ``typed_filter_metadata`` field will be parsed. + // and “typed_filter_metadata“ fields are present in the metadata with same keys, + // only “typed_filter_metadata“ field will be parsed. TypedFilterMetadata map[string]*any1.Any `protobuf:"bytes,2,rep,name=typed_filter_metadata,json=typedFilterMetadata,proto3" json:"typed_filter_metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -1099,8 +1106,13 @@ type HeaderValue struct { // // The same :ref:`format specifier ` as used for // :ref:`HTTP access logging ` applies here, however - // unknown header values are replaced with the empty string instead of ``-``. + // unknown header values are replaced with the empty string instead of “-“. + // Header value is encoded as string. This does not work for non-utf8 characters. + // Only one of “value“ or “raw_value“ can be set. Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + // Header value is encoded as bytes which can support non-utf8 characters. + // Only one of “value“ or “raw_value“ can be set. + RawValue []byte `protobuf:"bytes,3,opt,name=raw_value,json=rawValue,proto3" json:"raw_value,omitempty"` } func (x *HeaderValue) Reset() { @@ -1149,6 +1161,13 @@ func (x *HeaderValue) GetValue() string { return "" } +func (x *HeaderValue) GetRawValue() []byte { + if x != nil { + return x.RawValue + } + return nil +} + // Header name/value pair plus option to control append behavior. type HeaderValueOption struct { state protoimpl.MessageState @@ -1163,11 +1182,12 @@ type HeaderValueOption struct { // :ref:`append_action ` as replacement. // // .. note:: - // The :ref:`external authorization service ` and - // :ref:`external processor service ` have - // default value (``false``) for this field. // - // Deprecated: Do not use. + // The :ref:`external authorization service ` and + // :ref:`external processor service ` have + // default value (``false``) for this field. + // + // Deprecated: Marked as deprecated in envoy/config/core/v3/base.proto. Append *wrappers.BoolValue `protobuf:"bytes,2,opt,name=append,proto3" json:"append,omitempty"` // Describes the action taken to append/overwrite the given value for an existing header // or to only add this header if it's absent. @@ -1218,7 +1238,7 @@ func (x *HeaderValueOption) GetHeader() *HeaderValue { return nil } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/config/core/v3/base.proto. func (x *HeaderValueOption) GetAppend() *wrappers.BoolValue { if x != nil { return x.Append @@ -1345,6 +1365,7 @@ type DataSource struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Specifier: + // // *DataSource_Filename // *DataSource_InlineBytes // *DataSource_InlineString @@ -1586,6 +1607,7 @@ type AsyncDataSource struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Specifier: + // // *AsyncDataSource_Local // *AsyncDataSource_Remote Specifier isAsyncDataSource_Specifier `protobuf_oneof:"specifier"` @@ -1678,6 +1700,7 @@ type TransportSocket struct { // See the supported transport socket implementations for further documentation. // // Types that are assignable to ConfigType: + // // *TransportSocket_TypedConfig ConfigType isTransportSocket_ConfigType `protobuf_oneof:"config_type"` } @@ -1750,11 +1773,11 @@ func (*TransportSocket_TypedConfig) isTransportSocket_ConfigType() {} // // .. note:: // -// Parsing of the runtime key's data is implemented such that it may be represented as a -// :ref:`FractionalPercent ` proto represented as JSON/YAML -// and may also be represented as an integer with the assumption that the value is an integral -// percentage out of 100. For instance, a runtime key lookup returning the value "42" would parse -// as a ``FractionalPercent`` whose numerator is 42 and denominator is HUNDRED. +// Parsing of the runtime key's data is implemented such that it may be represented as a +// :ref:`FractionalPercent ` proto represented as JSON/YAML +// and may also be represented as an integer with the assumption that the value is an integral +// percentage out of 100. For instance, a runtime key lookup returning the value "42" would parse +// as a ``FractionalPercent`` whose numerator is 42 and denominator is HUNDRED. type RuntimeFractionalPercent struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1921,8 +1944,8 @@ var file_envoy_config_core_v3_base_proto_rawDesc = []byte{ 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x12, 0x34, 0x0a, 0x0f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0x18, 0x01, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, - 0x33, 0x2e, 0x30, 0x52, 0x0e, 0x74, 0x79, 0x70, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, + 0x30, 0x18, 0x01, 0x52, 0x0e, 0x74, 0x79, 0x70, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x12, 0x3c, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x42, 0x75, 0x69, 0x6c, @@ -1971,7 +1994,7 @@ var file_envoy_config_core_v3_base_proto_rawDesc = []byte{ 0x6e, 0x67, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, - 0x73, 0x42, 0x0b, 0x18, 0x01, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x52, 0x12, + 0x73, 0x42, 0x0b, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x18, 0x01, 0x52, 0x12, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x69, 0x6e, 0x67, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x1a, 0x60, 0x0a, 0x16, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, @@ -2051,162 +2074,169 @@ var file_envoy_config_core_v3_base_proto_rawDesc = []byte{ 0x75, 0x65, 0x72, 0x79, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x12, 0x19, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x7f, - 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x23, 0x0a, - 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x11, 0xfa, 0x42, 0x0e, 0x72, - 0x0c, 0x10, 0x01, 0x28, 0x80, 0x80, 0x01, 0xc0, 0x01, 0x01, 0xc8, 0x01, 0x00, 0x52, 0x03, 0x6b, - 0x65, 0x79, 0x12, 0x25, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x09, 0x42, 0x0f, 0xfa, 0x42, 0x0c, 0x72, 0x0a, 0x28, 0x80, 0x80, 0x01, 0xc0, 0x01, 0x02, 0xc8, - 0x01, 0x00, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x24, 0x9a, 0xc5, 0x88, 0x1e, 0x1f, - 0x0a, 0x1d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, - 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x22, - 0xc0, 0x03, 0x0a, 0x11, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, - 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, - 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, - 0x10, 0x01, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x3f, 0x0a, 0x06, 0x61, 0x70, - 0x70, 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, - 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0b, 0x18, 0x01, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, - 0x33, 0x2e, 0x30, 0x52, 0x06, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x12, 0x69, 0x0a, 0x0d, 0x61, - 0x70, 0x70, 0x65, 0x6e, 0x64, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x0e, 0x32, 0x3a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x48, 0x65, 0x61, 0x64, - 0x65, 0x72, 0x41, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x08, - 0xfa, 0x42, 0x05, 0x82, 0x01, 0x02, 0x10, 0x01, 0x52, 0x0c, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, - 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x28, 0x0a, 0x10, 0x6b, 0x65, 0x65, 0x70, 0x5f, 0x65, - 0x6d, 0x70, 0x74, 0x79, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, - 0x52, 0x0e, 0x6b, 0x65, 0x65, 0x70, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x22, 0x64, 0x0a, 0x12, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x41, 0x70, 0x70, 0x65, 0x6e, 0x64, - 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1b, 0x0a, 0x17, 0x41, 0x50, 0x50, 0x45, 0x4e, 0x44, - 0x5f, 0x49, 0x46, 0x5f, 0x45, 0x58, 0x49, 0x53, 0x54, 0x53, 0x5f, 0x4f, 0x52, 0x5f, 0x41, 0x44, - 0x44, 0x10, 0x00, 0x12, 0x11, 0x0a, 0x0d, 0x41, 0x44, 0x44, 0x5f, 0x49, 0x46, 0x5f, 0x41, 0x42, - 0x53, 0x45, 0x4e, 0x54, 0x10, 0x01, 0x12, 0x1e, 0x0a, 0x1a, 0x4f, 0x56, 0x45, 0x52, 0x57, 0x52, - 0x49, 0x54, 0x45, 0x5f, 0x49, 0x46, 0x5f, 0x45, 0x58, 0x49, 0x53, 0x54, 0x53, 0x5f, 0x4f, 0x52, - 0x5f, 0x41, 0x44, 0x44, 0x10, 0x02, 0x3a, 0x2a, 0x9a, 0xc5, 0x88, 0x1e, 0x25, 0x0a, 0x23, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, - 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, - 0x6f, 0x6e, 0x22, 0x6c, 0x0a, 0x09, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x70, 0x12, - 0x3b, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x21, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, - 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x07, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x3a, 0x22, 0x9a, 0xc5, - 0x88, 0x1e, 0x1d, 0x0a, 0x1b, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, - 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x70, - 0x22, 0x2f, 0x0a, 0x10, 0x57, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x44, 0x69, 0x72, 0x65, 0x63, - 0x74, 0x6f, 0x72, 0x79, 0x12, 0x1b, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x04, 0x70, 0x61, 0x74, - 0x68, 0x22, 0xf4, 0x01, 0x0a, 0x0a, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x12, 0x25, 0x0a, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x08, 0x66, - 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x23, 0x0a, 0x0c, 0x69, 0x6e, 0x6c, 0x69, 0x6e, - 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, - 0x0b, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x25, 0x0a, 0x0d, - 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0c, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x53, 0x74, 0x72, - 0x69, 0x6e, 0x67, 0x12, 0x3c, 0x0a, 0x14, 0x65, 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, - 0x6e, 0x74, 0x5f, 0x76, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, - 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x13, 0x65, 0x6e, - 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, - 0x65, 0x3a, 0x23, 0x9a, 0xc5, 0x88, 0x1e, 0x1e, 0x0a, 0x1c, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x44, 0x61, 0x74, 0x61, - 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x42, 0x10, 0x0a, 0x09, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, - 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0xd4, 0x01, 0x0a, 0x0b, 0x52, 0x65, 0x74, - 0x72, 0x79, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x4b, 0x0a, 0x0e, 0x72, 0x65, 0x74, 0x72, - 0x79, 0x5f, 0x62, 0x61, 0x63, 0x6b, 0x5f, 0x6f, 0x66, 0x66, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x25, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, - 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x42, 0x61, 0x63, 0x6b, 0x6f, 0x66, 0x66, 0x53, - 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, 0x0c, 0x72, 0x65, 0x74, 0x72, 0x79, 0x42, 0x61, - 0x63, 0x6b, 0x4f, 0x66, 0x66, 0x12, 0x52, 0x0a, 0x0b, 0x6e, 0x75, 0x6d, 0x5f, 0x72, 0x65, 0x74, - 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, - 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x13, 0xf2, 0x98, 0xfe, 0x8f, 0x05, 0x0d, - 0x0a, 0x0b, 0x6d, 0x61, 0x78, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x73, 0x52, 0x0a, 0x6e, - 0x75, 0x6d, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x73, 0x3a, 0x24, 0x9a, 0xc5, 0x88, 0x1e, 0x1f, - 0x0a, 0x1d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, - 0x6f, 0x72, 0x65, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x22, - 0xe8, 0x01, 0x0a, 0x10, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x12, 0x42, 0x0a, 0x08, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x75, 0x72, 0x69, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, - 0x74, 0x70, 0x55, 0x72, 0x69, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, - 0x07, 0x68, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, 0x12, 0x1f, 0x0a, 0x06, 0x73, 0x68, 0x61, 0x32, - 0x35, 0x36, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, - 0x01, 0x52, 0x06, 0x73, 0x68, 0x61, 0x32, 0x35, 0x36, 0x12, 0x44, 0x0a, 0x0c, 0x72, 0x65, 0x74, - 0x72, 0x79, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x21, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, - 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x6c, 0x69, - 0x63, 0x79, 0x52, 0x0b, 0x72, 0x65, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x3a, - 0x29, 0x9a, 0xc5, 0x88, 0x1e, 0x24, 0x0a, 0x22, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, - 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x22, 0xc9, 0x01, 0x0a, 0x0f, 0x41, - 0x73, 0x79, 0x6e, 0x63, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x38, - 0x0a, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, - 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x48, - 0x00, 0x52, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x12, 0x40, 0x0a, 0x06, 0x72, 0x65, 0x6d, 0x6f, - 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xcd, + 0x01, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x23, + 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x11, 0xfa, 0x42, 0x0e, + 0x72, 0x0c, 0x10, 0x01, 0x28, 0x80, 0x80, 0x01, 0xc8, 0x01, 0x00, 0xc0, 0x01, 0x01, 0x52, 0x03, + 0x6b, 0x65, 0x79, 0x12, 0x37, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x42, 0x21, 0xfa, 0x42, 0x0c, 0x72, 0x0a, 0x28, 0x80, 0x80, 0x01, 0xc8, 0x01, 0x00, + 0xc0, 0x01, 0x02, 0xf2, 0x98, 0xfe, 0x8f, 0x05, 0x0c, 0x12, 0x0a, 0x76, 0x61, 0x6c, 0x75, 0x65, + 0x5f, 0x74, 0x79, 0x70, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x3a, 0x0a, 0x09, + 0x72, 0x61, 0x77, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x42, + 0x1d, 0xfa, 0x42, 0x08, 0x7a, 0x06, 0x10, 0x00, 0x18, 0x80, 0x80, 0x01, 0xf2, 0x98, 0xfe, 0x8f, + 0x05, 0x0c, 0x12, 0x0a, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x52, 0x08, + 0x72, 0x61, 0x77, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x24, 0x9a, 0xc5, 0x88, 0x1e, 0x1f, 0x0a, + 0x1d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, + 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xd9, + 0x03, 0x0a, 0x11, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x64, + 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, + 0x01, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x3f, 0x0a, 0x06, 0x61, 0x70, 0x70, + 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, + 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0b, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, + 0x18, 0x01, 0x52, 0x06, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x12, 0x69, 0x0a, 0x0d, 0x61, 0x70, + 0x70, 0x65, 0x6e, 0x64, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0e, 0x32, 0x3a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, + 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, + 0x72, 0x41, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x08, 0xfa, + 0x42, 0x05, 0x82, 0x01, 0x02, 0x10, 0x01, 0x52, 0x0c, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x41, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x28, 0x0a, 0x10, 0x6b, 0x65, 0x65, 0x70, 0x5f, 0x65, 0x6d, + 0x70, 0x74, 0x79, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x0e, 0x6b, 0x65, 0x65, 0x70, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x22, + 0x7d, 0x0a, 0x12, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x41, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x41, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1b, 0x0a, 0x17, 0x41, 0x50, 0x50, 0x45, 0x4e, 0x44, 0x5f, + 0x49, 0x46, 0x5f, 0x45, 0x58, 0x49, 0x53, 0x54, 0x53, 0x5f, 0x4f, 0x52, 0x5f, 0x41, 0x44, 0x44, + 0x10, 0x00, 0x12, 0x11, 0x0a, 0x0d, 0x41, 0x44, 0x44, 0x5f, 0x49, 0x46, 0x5f, 0x41, 0x42, 0x53, + 0x45, 0x4e, 0x54, 0x10, 0x01, 0x12, 0x1e, 0x0a, 0x1a, 0x4f, 0x56, 0x45, 0x52, 0x57, 0x52, 0x49, + 0x54, 0x45, 0x5f, 0x49, 0x46, 0x5f, 0x45, 0x58, 0x49, 0x53, 0x54, 0x53, 0x5f, 0x4f, 0x52, 0x5f, + 0x41, 0x44, 0x44, 0x10, 0x02, 0x12, 0x17, 0x0a, 0x13, 0x4f, 0x56, 0x45, 0x52, 0x57, 0x52, 0x49, + 0x54, 0x45, 0x5f, 0x49, 0x46, 0x5f, 0x45, 0x58, 0x49, 0x53, 0x54, 0x53, 0x10, 0x03, 0x3a, 0x2a, + 0x9a, 0xc5, 0x88, 0x1e, 0x25, 0x0a, 0x23, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, + 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, + 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x6c, 0x0a, 0x09, 0x48, 0x65, + 0x61, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x70, 0x12, 0x3b, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x65, + 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, + 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x68, 0x65, 0x61, + 0x64, 0x65, 0x72, 0x73, 0x3a, 0x22, 0x9a, 0xc5, 0x88, 0x1e, 0x1d, 0x0a, 0x1b, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, + 0x65, 0x61, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x70, 0x22, 0x2f, 0x0a, 0x10, 0x57, 0x61, 0x74, 0x63, + 0x68, 0x65, 0x64, 0x44, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x79, 0x12, 0x1b, 0x0a, 0x04, + 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, + 0x02, 0x10, 0x01, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x22, 0xf4, 0x01, 0x0a, 0x0a, 0x44, 0x61, + 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x25, 0x0a, 0x08, 0x66, 0x69, 0x6c, 0x65, + 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, + 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x12, + 0x23, 0x0a, 0x0c, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x0b, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x42, + 0x79, 0x74, 0x65, 0x73, 0x12, 0x25, 0x0a, 0x0d, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x73, + 0x74, 0x72, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0c, 0x69, + 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x12, 0x3c, 0x0a, 0x14, 0x65, + 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x76, 0x61, 0x72, 0x69, 0x61, + 0x62, 0x6c, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, + 0x10, 0x01, 0x48, 0x00, 0x52, 0x13, 0x65, 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, + 0x74, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x3a, 0x23, 0x9a, 0xc5, 0x88, 0x1e, 0x1e, + 0x0a, 0x1c, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, + 0x6f, 0x72, 0x65, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x42, 0x10, + 0x0a, 0x09, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, + 0x22, 0xd4, 0x01, 0x0a, 0x0b, 0x52, 0x65, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, + 0x12, 0x4b, 0x0a, 0x0e, 0x72, 0x65, 0x74, 0x72, 0x79, 0x5f, 0x62, 0x61, 0x63, 0x6b, 0x5f, 0x6f, + 0x66, 0x66, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, - 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x48, 0x00, 0x52, 0x06, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x3a, 0x28, 0x9a, 0xc5, 0x88, 0x1e, + 0x42, 0x61, 0x63, 0x6b, 0x6f, 0x66, 0x66, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, + 0x0c, 0x72, 0x65, 0x74, 0x72, 0x79, 0x42, 0x61, 0x63, 0x6b, 0x4f, 0x66, 0x66, 0x12, 0x52, 0x0a, + 0x0b, 0x6e, 0x75, 0x6d, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x42, 0x13, 0xf2, 0x98, 0xfe, 0x8f, 0x05, 0x0d, 0x0a, 0x0b, 0x6d, 0x61, 0x78, 0x5f, 0x72, 0x65, + 0x74, 0x72, 0x69, 0x65, 0x73, 0x52, 0x0a, 0x6e, 0x75, 0x6d, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, + 0x73, 0x3a, 0x24, 0x9a, 0xc5, 0x88, 0x1e, 0x1f, 0x0a, 0x1d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x52, 0x65, 0x74, 0x72, + 0x79, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x22, 0xe8, 0x01, 0x0a, 0x10, 0x52, 0x65, 0x6d, 0x6f, + 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x42, 0x0a, 0x08, + 0x68, 0x74, 0x74, 0x70, 0x5f, 0x75, 0x72, 0x69, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, + 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, + 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, 0x42, 0x08, 0xfa, + 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x07, 0x68, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, + 0x12, 0x1f, 0x0a, 0x06, 0x73, 0x68, 0x61, 0x32, 0x35, 0x36, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x06, 0x73, 0x68, 0x61, 0x32, 0x35, + 0x36, 0x12, 0x44, 0x0a, 0x0c, 0x72, 0x65, 0x74, 0x72, 0x79, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, + 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x52, + 0x65, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x0b, 0x72, 0x65, 0x74, 0x72, + 0x79, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x3a, 0x29, 0x9a, 0xc5, 0x88, 0x1e, 0x24, 0x0a, 0x22, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x22, 0xc9, 0x01, 0x0a, 0x0f, 0x41, 0x73, 0x79, 0x6e, 0x63, 0x44, 0x61, 0x74, 0x61, + 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x38, 0x0a, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x44, 0x61, 0x74, + 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x48, 0x00, 0x52, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, + 0x12, 0x40, 0x0a, 0x06, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x26, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, + 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x61, + 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x48, 0x00, 0x52, 0x06, 0x72, 0x65, 0x6d, 0x6f, + 0x74, 0x65, 0x3a, 0x28, 0x9a, 0xc5, 0x88, 0x1e, 0x23, 0x0a, 0x21, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x41, 0x73, 0x79, + 0x6e, 0x63, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x42, 0x10, 0x0a, 0x09, + 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0xb0, + 0x01, 0x0a, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x53, 0x6f, 0x63, 0x6b, + 0x65, 0x74, 0x12, 0x1b, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, + 0x39, 0x0a, 0x0c, 0x74, 0x79, 0x70, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x48, 0x00, 0x52, 0x0b, 0x74, + 0x79, 0x70, 0x65, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x3a, 0x28, 0x9a, 0xc5, 0x88, 0x1e, 0x23, 0x0a, 0x21, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, - 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x41, 0x73, 0x79, 0x6e, 0x63, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x42, 0x10, 0x0a, 0x09, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, - 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0xb0, 0x01, 0x0a, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, - 0x70, 0x6f, 0x72, 0x74, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x12, 0x1b, 0x0a, 0x04, 0x6e, 0x61, - 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, - 0x01, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x0c, 0x74, 0x79, 0x70, 0x65, 0x64, - 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x41, 0x6e, 0x79, 0x48, 0x00, 0x52, 0x0b, 0x74, 0x79, 0x70, 0x65, 0x64, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x3a, 0x28, 0x9a, 0xc5, 0x88, 0x1e, 0x23, 0x0a, 0x21, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x54, 0x72, 0x61, - 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x42, 0x0d, 0x0a, 0x0b, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x4a, 0x04, 0x08, 0x02, 0x10, - 0x03, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0xbf, 0x01, 0x0a, 0x18, 0x52, 0x75, - 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x46, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x50, - 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x4f, 0x0a, 0x0d, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, - 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x46, 0x72, - 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x42, - 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x0c, 0x64, 0x65, 0x66, 0x61, 0x75, - 0x6c, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x72, 0x75, 0x6e, 0x74, 0x69, - 0x6d, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x72, 0x75, - 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x4b, 0x65, 0x79, 0x3a, 0x31, 0x9a, 0xc5, 0x88, 0x1e, 0x2c, 0x0a, - 0x2a, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, - 0x72, 0x65, 0x2e, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x46, 0x72, 0x61, 0x63, 0x74, 0x69, - 0x6f, 0x6e, 0x61, 0x6c, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x22, 0x55, 0x0a, 0x0c, 0x43, - 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x50, 0x6c, 0x61, 0x6e, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x69, - 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x3a, 0x25, 0x9a, 0xc5, 0x88, - 0x1e, 0x20, 0x0a, 0x1e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, - 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x50, 0x6c, 0x61, - 0x6e, 0x65, 0x2a, 0x28, 0x0a, 0x0f, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x69, - 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x0b, 0x0a, 0x07, 0x44, 0x45, 0x46, 0x41, 0x55, 0x4c, 0x54, - 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x49, 0x47, 0x48, 0x10, 0x01, 0x2a, 0x89, 0x01, 0x0a, - 0x0d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x12, 0x16, - 0x0a, 0x12, 0x4d, 0x45, 0x54, 0x48, 0x4f, 0x44, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, - 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x47, 0x45, 0x54, 0x10, 0x01, 0x12, - 0x08, 0x0a, 0x04, 0x48, 0x45, 0x41, 0x44, 0x10, 0x02, 0x12, 0x08, 0x0a, 0x04, 0x50, 0x4f, 0x53, - 0x54, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x50, 0x55, 0x54, 0x10, 0x04, 0x12, 0x0a, 0x0a, 0x06, - 0x44, 0x45, 0x4c, 0x45, 0x54, 0x45, 0x10, 0x05, 0x12, 0x0b, 0x0a, 0x07, 0x43, 0x4f, 0x4e, 0x4e, - 0x45, 0x43, 0x54, 0x10, 0x06, 0x12, 0x0b, 0x0a, 0x07, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x53, - 0x10, 0x07, 0x12, 0x09, 0x0a, 0x05, 0x54, 0x52, 0x41, 0x43, 0x45, 0x10, 0x08, 0x12, 0x09, 0x0a, - 0x05, 0x50, 0x41, 0x54, 0x43, 0x48, 0x10, 0x09, 0x2a, 0x3e, 0x0a, 0x10, 0x54, 0x72, 0x61, 0x66, - 0x66, 0x69, 0x63, 0x44, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0f, 0x0a, 0x0b, - 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b, 0x0a, - 0x07, 0x49, 0x4e, 0x42, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x4f, 0x55, - 0x54, 0x42, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x02, 0x42, 0x7d, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, + 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x53, 0x6f, + 0x63, 0x6b, 0x65, 0x74, 0x42, 0x0d, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x74, + 0x79, 0x70, 0x65, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x22, 0xbf, 0x01, 0x0a, 0x18, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x46, 0x72, 0x61, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x4f, + 0x0a, 0x0d, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, + 0x70, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x46, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, + 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, + 0x01, 0x52, 0x0c, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, + 0x1f, 0x0a, 0x0b, 0x72, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x72, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x4b, 0x65, 0x79, + 0x3a, 0x31, 0x9a, 0xc5, 0x88, 0x1e, 0x2c, 0x0a, 0x2a, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, + 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x52, 0x75, 0x6e, 0x74, 0x69, + 0x6d, 0x65, 0x46, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x50, 0x65, 0x72, 0x63, + 0x65, 0x6e, 0x74, 0x22, 0x55, 0x0a, 0x0c, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x50, 0x6c, + 0x61, 0x6e, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, + 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, + 0x69, 0x65, 0x72, 0x3a, 0x25, 0x9a, 0xc5, 0x88, 0x1e, 0x20, 0x0a, 0x1e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x50, 0x6c, 0x61, 0x6e, 0x65, 0x2a, 0x28, 0x0a, 0x0f, 0x52, 0x6f, + 0x75, 0x74, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x0b, 0x0a, + 0x07, 0x44, 0x45, 0x46, 0x41, 0x55, 0x4c, 0x54, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x49, + 0x47, 0x48, 0x10, 0x01, 0x2a, 0x89, 0x01, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x12, 0x16, 0x0a, 0x12, 0x4d, 0x45, 0x54, 0x48, 0x4f, 0x44, + 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x07, + 0x0a, 0x03, 0x47, 0x45, 0x54, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x45, 0x41, 0x44, 0x10, + 0x02, 0x12, 0x08, 0x0a, 0x04, 0x50, 0x4f, 0x53, 0x54, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x50, + 0x55, 0x54, 0x10, 0x04, 0x12, 0x0a, 0x0a, 0x06, 0x44, 0x45, 0x4c, 0x45, 0x54, 0x45, 0x10, 0x05, + 0x12, 0x0b, 0x0a, 0x07, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x10, 0x06, 0x12, 0x0b, 0x0a, + 0x07, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x53, 0x10, 0x07, 0x12, 0x09, 0x0a, 0x05, 0x54, 0x52, + 0x41, 0x43, 0x45, 0x10, 0x08, 0x12, 0x09, 0x0a, 0x05, 0x50, 0x41, 0x54, 0x43, 0x48, 0x10, 0x09, + 0x2a, 0x3e, 0x0a, 0x10, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x44, 0x69, 0x72, 0x65, 0x63, + 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, + 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x49, 0x4e, 0x42, 0x4f, 0x55, 0x4e, 0x44, + 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x4f, 0x55, 0x54, 0x42, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x02, + 0x42, 0x7d, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x09, 0x42, 0x61, 0x73, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, - 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.validate.go index 696a39463..7e2dd5390 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.validate.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/base.pb.validate.go @@ -1667,6 +1667,17 @@ func (m *HeaderValue) validate(all bool) error { errors = append(errors, err) } + if l := len(m.GetRawValue()); l < 0 || l > 16384 { + err := HeaderValueValidationError{ + field: "RawValue", + reason: "value length must be between 0 and 16384 bytes, inclusive", + } + if !all { + return err + } + errors = append(errors, err) + } + if len(errors) > 0 { return HeaderValueMultiError(errors) } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/config_source.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/config_source.pb.go index f0584ffed..32fc76d39 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/config_source.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/config_source.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/config_source.proto package corev3 @@ -36,11 +36,11 @@ const ( // versioning. If a client does not support v2 (e.g. due to deprecation), this // is an invalid value. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/config_source.proto. ApiVersion_AUTO ApiVersion = 0 // Use xDS v2 API. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/config_source.proto. ApiVersion_V2 ApiVersion = 1 // Use xDS v3 API. ApiVersion_V3 ApiVersion = 2 @@ -94,7 +94,7 @@ const ( // Ideally this would be 'reserved 0' but one can't reserve the default // value. Instead we throw an exception if this is ever used. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/config_source.proto. ApiConfigSource_DEPRECATED_AND_UNAVAILABLE_DO_NOT_USE ApiConfigSource_ApiType = 0 // REST-JSON v2 API. The `canonical JSON encoding // `_ for @@ -182,8 +182,8 @@ type ApiConfigSource struct { // // .. note:: // - // The cluster with name ``cluster_name`` must be statically defined and its - // type must not be ``EDS``. + // The cluster with name ``cluster_name`` must be statically defined and its + // type must not be ``EDS``. ClusterNames []string `protobuf:"bytes,2,rep,name=cluster_names,json=clusterNames,proto3" json:"cluster_names,omitempty"` // Multiple gRPC services be provided for GRPC. If > 1 cluster is defined, // services will be cycled through if any kind of failure occurs. @@ -200,7 +200,7 @@ type ApiConfigSource struct { // A list of config validators that will be executed when a new update is // received from the ApiConfigSource. Note that each validator handles a // specific xDS service type, and only the validators corresponding to the - // type url (in ``:ref: DiscoveryResponse`` or ``:ref: DeltaDiscoveryResponse``) + // type url (in “:ref: DiscoveryResponse“ or “:ref: DeltaDiscoveryResponse“) // will be invoked. // If the validator returns false or throws an exception, the config will be rejected by // the client, and a NACK will be sent. @@ -407,7 +407,8 @@ type RateLimitSettings struct { // default value of 100 will be used. MaxTokens *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=max_tokens,json=maxTokens,proto3" json:"max_tokens,omitempty"` // Rate at which tokens will be filled per second. If not set, a default fill rate of 10 tokens - // per second will be used. + // per second will be used. The minimal fill rate is once per year. Lower + // fill rates will be set to once per year. FillRate *wrappers.DoubleValue `protobuf:"bytes,2,opt,name=fill_rate,json=fillRate,proto3" json:"fill_rate,omitempty"` } @@ -469,27 +470,27 @@ type PathConfigSource struct { // // .. note:: // - // The path to the source must exist at config load time. + // The path to the source must exist at config load time. // // .. note:: // - // If ``watched_directory`` is *not* configured, Envoy will watch the file path for *moves*. - // This is because in general only moves are atomic. The same method of swapping files as is - // demonstrated in the :ref:`runtime documentation ` can be - // used here also. If ``watched_directory`` is configured, no watch will be placed directly on - // this path. Instead, the configured ``watched_directory`` will be used to trigger reloads of - // this path. This is required in certain deployment scenarios. See below for more information. + // If ``watched_directory`` is *not* configured, Envoy will watch the file path for *moves*. + // This is because in general only moves are atomic. The same method of swapping files as is + // demonstrated in the :ref:`runtime documentation ` can be + // used here also. If ``watched_directory`` is configured, no watch will be placed directly on + // this path. Instead, the configured ``watched_directory`` will be used to trigger reloads of + // this path. This is required in certain deployment scenarios. See below for more information. Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` // If configured, this directory will be watched for *moves*. When an entry in this directory is - // moved to, the ``path`` will be reloaded. This is required in certain deployment scenarios. + // moved to, the “path“ will be reloaded. This is required in certain deployment scenarios. // // Specifically, if trying to load an xDS resource using a // `Kubernetes ConfigMap `_, the // following configuration might be used: // 1. Store xds.yaml inside a ConfigMap. - // 2. Mount the ConfigMap to ``/config_map/xds`` - // 3. Configure path ``/config_map/xds/xds.yaml`` - // 4. Configure watched directory ``/config_map/xds`` + // 2. Mount the ConfigMap to “/config_map/xds“ + // 3. Configure path “/config_map/xds/xds.yaml“ + // 4. Configure watched directory “/config_map/xds“ // // The above configuration will ensure that Envoy watches the owning directory for moves which is // required due to how Kubernetes manages ConfigMap symbolic links during atomic updates. @@ -555,11 +556,12 @@ type ConfigSource struct { unknownFields protoimpl.UnknownFields // Authorities that this config source may be used for. An authority specified in a xdstp:// URL - // is resolved to a ``ConfigSource`` prior to configuration fetch. This field provides the + // is resolved to a “ConfigSource“ prior to configuration fetch. This field provides the // association between authority name and configuration source. // [#not-implemented-hide:] Authorities []*v3.Authority `protobuf:"bytes,7,rep,name=authorities,proto3" json:"authorities,omitempty"` // Types that are assignable to ConfigSourceSpecifier: + // // *ConfigSource_Path // *ConfigSource_PathConfigSource // *ConfigSource_ApiConfigSource @@ -626,7 +628,7 @@ func (m *ConfigSource) GetConfigSourceSpecifier() isConfigSource_ConfigSourceSpe return nil } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/config/core/v3/config_source.proto. func (x *ConfigSource) GetPath() string { if x, ok := x.GetConfigSourceSpecifier().(*ConfigSource_Path); ok { return x.Path @@ -681,9 +683,9 @@ type isConfigSource_ConfigSourceSpecifier interface { } type ConfigSource_Path struct { - // Deprecated in favor of ``path_config_source``. Use that field instead. + // Deprecated in favor of “path_config_source“. Use that field instead. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/config_source.proto. Path string `protobuf:"bytes,1,opt,name=path,proto3,oneof"` } @@ -747,7 +749,7 @@ type ExtensionConfigSource struct { ConfigSource *ConfigSource `protobuf:"bytes,1,opt,name=config_source,json=configSource,proto3" json:"config_source,omitempty"` // Optional default configuration to use as the initial configuration if // there is a failure to receive the initial extension configuration or if - // ``apply_default_config_without_warming`` flag is set. + // “apply_default_config_without_warming“ flag is set. DefaultConfig *any1.Any `protobuf:"bytes,2,opt,name=default_config,json=defaultConfig,proto3" json:"default_config,omitempty"` // Use the default config as the initial configuration without warming and // waiting for the first discovery response. Requires the default configuration @@ -894,7 +896,7 @@ var file_envoy_config_core_v3_config_source_proto_rawDesc = []byte{ 0x22, 0x92, 0x01, 0x0a, 0x07, 0x41, 0x70, 0x69, 0x54, 0x79, 0x70, 0x65, 0x12, 0x33, 0x0a, 0x25, 0x44, 0x45, 0x50, 0x52, 0x45, 0x43, 0x41, 0x54, 0x45, 0x44, 0x5f, 0x41, 0x4e, 0x44, 0x5f, 0x55, 0x4e, 0x41, 0x56, 0x41, 0x49, 0x4c, 0x41, 0x42, 0x4c, 0x45, 0x5f, 0x44, 0x4f, 0x5f, 0x4e, 0x4f, - 0x54, 0x5f, 0x55, 0x53, 0x45, 0x10, 0x00, 0x1a, 0x08, 0x08, 0x01, 0xa8, 0xf7, 0xb4, 0x8b, 0x02, + 0x54, 0x5f, 0x55, 0x53, 0x45, 0x10, 0x00, 0x1a, 0x08, 0xa8, 0xf7, 0xb4, 0x8b, 0x02, 0x01, 0x08, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x52, 0x45, 0x53, 0x54, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x47, 0x52, 0x50, 0x43, 0x10, 0x02, 0x12, 0x0e, 0x0a, 0x0a, 0x44, 0x45, 0x4c, 0x54, 0x41, 0x5f, 0x47, 0x52, 0x50, 0x43, 0x10, 0x03, 0x12, 0x13, 0x0a, 0x0f, 0x41, 0x47, 0x47, 0x52, 0x45, 0x47, 0x41, @@ -944,8 +946,8 @@ var file_envoy_config_core_v3_config_source_proto_rawDesc = []byte{ 0x0b, 0x32, 0x16, 0x2e, 0x78, 0x64, 0x73, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x52, 0x0b, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x69, 0x65, 0x73, 0x12, 0x21, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0x18, 0x01, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, - 0x30, 0x48, 0x00, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x56, 0x0a, 0x12, 0x70, 0x61, 0x74, + 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x18, + 0x01, 0x48, 0x00, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x56, 0x0a, 0x12, 0x70, 0x61, 0x74, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x50, 0x61, 0x74, @@ -999,18 +1001,18 @@ var file_envoy_config_core_v3_config_source_proto_rawDesc = []byte{ 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x92, 0x01, 0x02, 0x08, 0x01, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x55, 0x72, 0x6c, 0x73, 0x2a, 0x40, 0x0a, 0x0a, 0x41, 0x70, 0x69, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x15, 0x0a, 0x04, 0x41, 0x55, 0x54, - 0x4f, 0x10, 0x00, 0x1a, 0x0b, 0x08, 0x01, 0x8a, 0xf4, 0x9b, 0xb3, 0x05, 0x03, 0x33, 0x2e, 0x30, - 0x12, 0x13, 0x0a, 0x02, 0x56, 0x32, 0x10, 0x01, 0x1a, 0x0b, 0x08, 0x01, 0x8a, 0xf4, 0x9b, 0xb3, - 0x05, 0x03, 0x33, 0x2e, 0x30, 0x12, 0x06, 0x0a, 0x02, 0x56, 0x33, 0x10, 0x02, 0x42, 0x85, 0x01, - 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, - 0x65, 0x2e, 0x76, 0x33, 0x42, 0x11, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x53, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, - 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, - 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, - 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, - 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, - 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x4f, 0x10, 0x00, 0x1a, 0x0b, 0x8a, 0xf4, 0x9b, 0xb3, 0x05, 0x03, 0x33, 0x2e, 0x30, 0x08, 0x01, + 0x12, 0x13, 0x0a, 0x02, 0x56, 0x32, 0x10, 0x01, 0x1a, 0x0b, 0x8a, 0xf4, 0x9b, 0xb3, 0x05, 0x03, + 0x33, 0x2e, 0x30, 0x08, 0x01, 0x12, 0x06, 0x0a, 0x02, 0x56, 0x33, 0x10, 0x02, 0x42, 0x85, 0x01, + 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x11, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, + 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, + 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, + 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/event_service_config.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/event_service_config.pb.go index 56dab5b98..f9deb0c90 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/event_service_config.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/event_service_config.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/event_service_config.proto package corev3 @@ -30,6 +30,7 @@ type EventServiceConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ConfigSourceSpecifier: + // // *EventServiceConfig_GrpcService ConfigSourceSpecifier isEventServiceConfig_ConfigSourceSpecifier `protobuf_oneof:"config_source_specifier"` } @@ -117,16 +118,16 @@ var file_envoy_config_core_v3_event_service_config_proto_rawDesc = []byte{ 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x1e, 0x0a, 0x17, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, - 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x8b, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x17, - 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, - 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, - 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, - 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, - 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, - 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x8b, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, + 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, + 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x17, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, + 0x76, 0x69, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, + 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, + 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, + 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/extension.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/extension.pb.go index ecf3e6b5c..3fa0aab89 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/extension.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/extension.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/extension.proto package corev3 @@ -34,9 +34,9 @@ type TypedExtensionConfig struct { // it serves the role of an opaque identifier. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The typed config for the extension. The type URL will be used to identify - // the extension. In the case that the type URL is ``xds.type.v3.TypedStruct`` - // (or, for historical reasons, ``udpa.type.v1.TypedStruct``), the inner type - // URL of ``TypedStruct`` will be utilized. See the + // the extension. In the case that the type URL is “xds.type.v3.TypedStruct“ + // (or, for historical reasons, “udpa.type.v1.TypedStruct“), the inner type + // URL of “TypedStruct“ will be utilized. See the // :ref:`extension configuration overview // ` for further details. TypedConfig *any1.Any `protobuf:"bytes,2,opt,name=typed_config,json=typedConfig,proto3" json:"typed_config,omitempty"` @@ -107,15 +107,15 @@ var file_envoy_config_core_v3_extension_proto_rawDesc = []byte{ 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x42, 0x08, 0xfa, 0x42, 0x05, 0xa2, 0x01, 0x02, 0x08, 0x01, 0x52, 0x0b, 0x74, 0x79, 0x70, 0x65, - 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x82, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0e, - 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, - 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, - 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, - 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, + 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x82, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, + 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, + 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, + 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, + 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, + 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, + 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, + 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_method_list.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_method_list.pb.go index 5e0e91178..30dbf0ecb 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_method_list.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_method_list.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/grpc_method_list.proto package corev3 @@ -156,16 +156,16 @@ var file_envoy_config_core_v3_grpc_method_list_proto_rawDesc = []byte{ 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4c, 0x69, 0x73, 0x74, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x3a, 0x27, 0x9a, 0xc5, 0x88, 0x1e, 0x22, 0x0a, 0x20, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x47, 0x72, 0x70, - 0x63, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4c, 0x69, 0x73, 0x74, 0x42, 0x87, 0x01, 0x0a, 0x22, - 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, - 0x76, 0x33, 0x42, 0x13, 0x47, 0x72, 0x70, 0x63, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4c, 0x69, - 0x73, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, - 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, - 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, - 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, - 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, - 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x63, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4c, 0x69, 0x73, 0x74, 0x42, 0x87, 0x01, 0xba, 0x80, + 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x13, 0x47, 0x72, 0x70, 0x63, + 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, + 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, + 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, + 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_service.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_service.pb.go index 1bab4b9e8..a8b3b061a 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_service.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/grpc_service.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/grpc_service.proto package corev3 @@ -36,6 +36,7 @@ type GrpcService struct { unknownFields protoimpl.UnknownFields // Types that are assignable to TargetSpecifier: + // // *GrpcService_EnvoyGrpc_ // *GrpcService_GoogleGrpc_ TargetSpecifier isGrpcService_TargetSpecifier `protobuf_oneof:"target_specifier"` @@ -43,7 +44,7 @@ type GrpcService struct { // request. Timeout *duration.Duration `protobuf:"bytes,3,opt,name=timeout,proto3" json:"timeout,omitempty"` // Additional metadata to include in streams initiated to the GrpcService. This can be used for - // scenarios in which additional ad hoc authorization headers (e.g. ``x-foo-bar: baz-key``) are to + // scenarios in which additional ad hoc authorization headers (e.g. “x-foo-bar: baz-key“) are to // be injected. For more information, including details on header value syntax, see the // documentation on :ref:`custom request headers // `. @@ -148,7 +149,7 @@ type GrpcService_EnvoyGrpc struct { // in the :ref:`Cluster ` :ref:`transport_socket // `. ClusterName string `protobuf:"bytes,1,opt,name=cluster_name,json=clusterName,proto3" json:"cluster_name,omitempty"` - // The ``:authority`` header in the grpc request. If this field is not set, the authority header value will be ``cluster_name``. + // The “:authority“ header in the grpc request. If this field is not set, the authority header value will be “cluster_name“. // Note that this authority does not override the SNI. The SNI is provided by the transport socket of the cluster. Authority string `protobuf:"bytes,2,opt,name=authority,proto3" json:"authority,omitempty"` // Indicates the retry policy for re-establishing the gRPC stream @@ -229,11 +230,12 @@ type GrpcService_GoogleGrpc struct { // service. // // .. csv-table:: - // :header: Name, Type, Description - // :widths: 1, 1, 2 // - // streams_total, Counter, Total number of streams opened - // streams_closed_, Counter, Total streams closed with + // :header: Name, Type, Description + // :widths: 1, 1, 2 + // + // streams_total, Counter, Total number of streams opened + // streams_closed_, Counter, Total streams closed with StatPrefix string `protobuf:"bytes,4,opt,name=stat_prefix,json=statPrefix,proto3" json:"stat_prefix,omitempty"` // The name of the Google gRPC credentials factory to use. This must have been registered with // Envoy. If this is empty, a default credentials factory will be used that sets up channel @@ -452,6 +454,7 @@ type GrpcService_GoogleGrpc_ChannelCredentials struct { unknownFields protoimpl.UnknownFields // Types that are assignable to CredentialSpecifier: + // // *GrpcService_GoogleGrpc_ChannelCredentials_SslCredentials // *GrpcService_GoogleGrpc_ChannelCredentials_GoogleDefault // *GrpcService_GoogleGrpc_ChannelCredentials_LocalCredentials @@ -551,6 +554,7 @@ type GrpcService_GoogleGrpc_CallCredentials struct { unknownFields protoimpl.UnknownFields // Types that are assignable to CredentialSpecifier: + // // *GrpcService_GoogleGrpc_CallCredentials_AccessToken // *GrpcService_GoogleGrpc_CallCredentials_GoogleComputeEngine // *GrpcService_GoogleGrpc_CallCredentials_GoogleRefreshToken @@ -886,6 +890,7 @@ type GrpcService_GoogleGrpc_CallCredentials_MetadataCredentialsFromPlugin struct // [#extension-category: envoy.grpc_credentials] // // Types that are assignable to ConfigType: + // // *GrpcService_GoogleGrpc_CallCredentials_MetadataCredentialsFromPlugin_TypedConfig ConfigType isGrpcService_GoogleGrpc_CallCredentials_MetadataCredentialsFromPlugin_ConfigType `protobuf_oneof:"config_type"` } @@ -1096,6 +1101,7 @@ type GrpcService_GoogleGrpc_ChannelArgs_Value struct { // delivered via the API. // // Types that are assignable to ValueSpecifier: + // // *GrpcService_GoogleGrpc_ChannelArgs_Value_StringValue // *GrpcService_GoogleGrpc_ChannelArgs_Value_IntValue ValueSpecifier isGrpcService_GoogleGrpc_ChannelArgs_Value_ValueSpecifier `protobuf_oneof:"value_specifier"` @@ -1222,8 +1228,8 @@ var file_envoy_config_core_v3_grpc_service_proto_rawDesc = []byte{ 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x0b, 0x63, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2f, 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x42, 0x11, 0xfa, 0x42, 0x0e, 0x72, 0x0c, 0x10, 0x00, 0x28, 0x80, 0x80, 0x01, 0xc0, - 0x01, 0x02, 0xc8, 0x01, 0x00, 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, + 0x28, 0x09, 0x42, 0x11, 0xfa, 0x42, 0x0e, 0x72, 0x0c, 0x10, 0x00, 0x28, 0x80, 0x80, 0x01, 0xc8, + 0x01, 0x00, 0xc0, 0x01, 0x02, 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x44, 0x0a, 0x0c, 0x72, 0x65, 0x74, 0x72, 0x79, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x52, 0x65, @@ -1467,15 +1473,15 @@ var file_envoy_config_core_v3_grpc_service_proto_rawDesc = []byte{ 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x42, 0x17, 0x0a, 0x10, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, - 0x42, 0x01, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x42, 0x84, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, - 0x10, 0x47, 0x72, 0x70, 0x63, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, - 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, + 0x42, 0x01, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x42, 0x84, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, + 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, + 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, + 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x10, 0x47, 0x72, 0x70, 0x63, 0x53, 0x65, 0x72, + 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, + 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, + 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, + 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.go index 8578ce93f..34b68b42d 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.go @@ -1,13 +1,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/health_check.proto package corev3 import ( _ "github.com/cncf/xds/go/udpa/annotations" + _ "github.com/envoyproxy/go-control-plane/envoy/annotations" v31 "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3" v3 "github.com/envoyproxy/go-control-plane/envoy/type/v3" _ "github.com/envoyproxy/protoc-gen-validate/validate" @@ -32,7 +33,7 @@ const ( type HealthStatus int32 const ( - // The health status is not known. This is interpreted by Envoy as ``HEALTHY``. + // The health status is not known. This is interpreted by Envoy as “HEALTHY“. HealthStatus_UNKNOWN HealthStatus = 0 // Healthy. HealthStatus_HEALTHY HealthStatus = 1 @@ -42,10 +43,10 @@ const ( // ``_ // or // ``_. - // This is interpreted by Envoy as ``UNHEALTHY``. + // This is interpreted by Envoy as “UNHEALTHY“. HealthStatus_DRAINING HealthStatus = 3 // Health check timed out. This is part of HDS and is interpreted by Envoy as - // ``UNHEALTHY``. + // “UNHEALTHY“. HealthStatus_TIMEOUT HealthStatus = 4 // Degraded. HealthStatus_DEGRADED HealthStatus = 5 @@ -146,7 +147,7 @@ func (x *HealthStatusSet) GetStatuses() []HealthStatus { return nil } -// [#next-free-field: 25] +// [#next-free-field: 26] type HealthCheck struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -165,14 +166,14 @@ type HealthCheck struct { // interval Envoy will add interval_jitter to the wait time. IntervalJitter *duration.Duration `protobuf:"bytes,3,opt,name=interval_jitter,json=intervalJitter,proto3" json:"interval_jitter,omitempty"` // An optional jitter amount as a percentage of interval_ms. If specified, - // during every interval Envoy will add ``interval_ms`` * - // ``interval_jitter_percent`` / 100 to the wait time. + // during every interval Envoy will add “interval_ms“ * + // “interval_jitter_percent“ / 100 to the wait time. // // If interval_jitter_ms and interval_jitter_percent are both set, both of // them will be used to increase the wait time. IntervalJitterPercent uint32 `protobuf:"varint,18,opt,name=interval_jitter_percent,json=intervalJitterPercent,proto3" json:"interval_jitter_percent,omitempty"` // The number of unhealthy health checks required before a host is marked - // unhealthy. Note that for ``http`` health checking if a host responds with a code not in + // unhealthy. Note that for “http“ health checking if a host responds with a code not in // :ref:`expected_statuses ` // or :ref:`retriable_statuses `, // this threshold is ignored and the host is considered immediately unhealthy. @@ -186,6 +187,7 @@ type HealthCheck struct { // Reuse health check connection between health checks. Default is true. ReuseConnection *wrappers.BoolValue `protobuf:"bytes,7,opt,name=reuse_connection,json=reuseConnection,proto3" json:"reuse_connection,omitempty"` // Types that are assignable to HealthChecker: + // // *HealthCheck_HttpHealthCheck_ // *HealthCheck_TcpHealthCheck_ // *HealthCheck_GrpcHealthCheck_ @@ -205,7 +207,7 @@ type HealthCheck struct { // (including new hosts) when the cluster has received no traffic. // // This is useful for when we want to send frequent health checks with - // ``no_traffic_interval`` but then revert to lower frequency ``no_traffic_healthy_interval`` once + // “no_traffic_interval“ but then revert to lower frequency “no_traffic_healthy_interval“ once // a host in the cluster is marked as healthy. // // Once a cluster has been used for traffic routing, Envoy will shift back to using the @@ -233,9 +235,19 @@ type HealthCheck struct { // // The default value for "healthy edge interval" is the same as the default interval. HealthyEdgeInterval *duration.Duration `protobuf:"bytes,16,opt,name=healthy_edge_interval,json=healthyEdgeInterval,proto3" json:"healthy_edge_interval,omitempty"` + // .. attention:: + // This field is deprecated in favor of the extension + // :ref:`event_logger ` and + // :ref:`event_log_path ` + // in the file sink extension. + // // Specifies the path to the :ref:`health check event log `. - // If empty, no event log will be written. + // + // Deprecated: Marked as deprecated in envoy/config/core/v3/health_check.proto. EventLogPath string `protobuf:"bytes,17,opt,name=event_log_path,json=eventLogPath,proto3" json:"event_log_path,omitempty"` + // A list of event log sinks to process the health check event. + // [#extension-category: envoy.health_check.event_sinks] + EventLogger []*TypedExtensionConfig `protobuf:"bytes,25,rep,name=event_logger,json=eventLogger,proto3" json:"event_logger,omitempty"` // [#not-implemented-hide:] // The gRPC service for the health check event service. // If empty, health check events won't be sent to a remote endpoint. @@ -252,22 +264,22 @@ type HealthCheck struct { // // .. code-block:: yaml // - // transport_socket_match_criteria: - // useMTLS: true + // transport_socket_match_criteria: + // useMTLS: true // // Will match the following :ref:`cluster socket match ` // // .. code-block:: yaml // - // transport_socket_matches: - // - name: "useMTLS" - // match: - // useMTLS: true - // transport_socket: - // name: envoy.transport_sockets.tls - // config: { ... } # tls socket configuration + // transport_socket_matches: + // - name: "useMTLS" + // match: + // useMTLS: true + // transport_socket: + // name: envoy.transport_sockets.tls + // config: { ... } # tls socket configuration // - // If this field is set, then for health checks it will supersede an entry of ``envoy.transport_socket`` in the + // If this field is set, then for health checks it will supersede an entry of “envoy.transport_socket“ in the // :ref:`LbEndpoint.Metadata `. // This allows using different transport socket capabilities for health checking versus proxying to the // endpoint. @@ -444,6 +456,7 @@ func (x *HealthCheck) GetHealthyEdgeInterval() *duration.Duration { return nil } +// Deprecated: Marked as deprecated in envoy/config/core/v3/health_check.proto. func (x *HealthCheck) GetEventLogPath() string { if x != nil { return x.EventLogPath @@ -451,6 +464,13 @@ func (x *HealthCheck) GetEventLogPath() string { return "" } +func (x *HealthCheck) GetEventLogger() []*TypedExtensionConfig { + if x != nil { + return x.EventLogger + } + return nil +} + func (x *HealthCheck) GetEventService() *EventServiceConfig { if x != nil { return x.EventService @@ -518,6 +538,7 @@ type HealthCheck_Payload struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Payload: + // // *HealthCheck_Payload_Text // *HealthCheck_Payload_Binary Payload isHealthCheck_Payload_Payload `protobuf_oneof:"payload"` @@ -606,19 +627,19 @@ type HealthCheck_HttpHealthCheck struct { // :ref:`hostname ` field. Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"` // Specifies the HTTP path that will be requested during health checking. For example - // ``/healthcheck``. + // “/healthcheck“. Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` // [#not-implemented-hide:] HTTP specific payload. Send *HealthCheck_Payload `protobuf:"bytes,3,opt,name=send,proto3" json:"send,omitempty"` - // Specifies a list of HTTP expected responses to match in the first ``response_buffer_size`` bytes of the response body. + // Specifies a list of HTTP expected responses to match in the first “response_buffer_size“ bytes of the response body. // If it is set, both the expected response check and status code determine the health check. // When checking the response, “fuzzy†matching is performed such that each payload block must be found, // and in the order specified, but not necessarily contiguous. // // .. note:: // - // It is recommended to set ``response_buffer_size`` based on the total Payload size for efficiency. - // The default buffer size is 1024 bytes when it is not set. + // It is recommended to set ``response_buffer_size`` based on the total Payload size for efficiency. + // The default buffer size is 1024 bytes when it is not set. Receive []*HealthCheck_Payload `protobuf:"bytes,4,rep,name=receive,proto3" json:"receive,omitempty"` // Specifies the size of response buffer in bytes that is used to Payload match. // The default value is 1024. Setting to 0 implies that the Payload will be matched against the entire response. @@ -841,7 +862,7 @@ type HealthCheck_RedisHealthCheck struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // If set, optionally perform ``EXISTS `` instead of ``PING``. A return value + // If set, optionally perform “EXISTS “ instead of “PING“. A return value // from Redis of 0 (does not exist) is considered a passing healthcheck. A return value other // than 0 is considered a failure. This allows the user to mark a Redis instance for maintenance // by setting the specified key to any value and waiting for traffic to drain. @@ -980,6 +1001,7 @@ type HealthCheck_CustomHealthCheck struct { // [#extension-category: envoy.health_checkers] // // Types that are assignable to ConfigType: + // // *HealthCheck_CustomHealthCheck_TypedConfig ConfigType isHealthCheck_CustomHealthCheck_ConfigType `protobuf_oneof:"config_type"` } @@ -1114,288 +1136,298 @@ var file_envoy_config_core_v3_health_check_proto_rawDesc = []byte{ 0x1a, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x1a, 0x22, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, - 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x18, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, - 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, - 0x19, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x72, - 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x1a, 0x1d, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x1a, 0x21, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, - 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x60, - 0x0a, 0x0f, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x53, 0x65, - 0x74, 0x12, 0x4d, 0x0a, 0x08, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x18, 0x01, 0x20, - 0x03, 0x28, 0x0e, 0x32, 0x22, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x42, 0x0d, 0xfa, 0x42, 0x0a, 0x92, 0x01, 0x07, 0x22, - 0x05, 0x82, 0x01, 0x02, 0x10, 0x01, 0x52, 0x08, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, - 0x22, 0x91, 0x1e, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, - 0x12, 0x3f, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0a, 0xfa, 0x42, - 0x07, 0xaa, 0x01, 0x04, 0x08, 0x01, 0x2a, 0x00, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, - 0x74, 0x12, 0x41, 0x0a, 0x08, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0a, - 0xfa, 0x42, 0x07, 0xaa, 0x01, 0x04, 0x08, 0x01, 0x2a, 0x00, 0x52, 0x08, 0x69, 0x6e, 0x74, 0x65, - 0x72, 0x76, 0x61, 0x6c, 0x12, 0x40, 0x0a, 0x0e, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, - 0x6a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, + 0x6f, 0x1a, 0x24, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, + 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, + 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x22, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, + 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x2f, 0x73, + 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x18, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, + 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, + 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, + 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x23, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x64, 0x65, 0x70, + 0x72, 0x65, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1d, + 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x21, 0x75, + 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, + 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, + 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x60, 0x0a, 0x0f, 0x48, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x53, 0x65, 0x74, 0x12, 0x4d, 0x0a, 0x08, + 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x22, + 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, + 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x53, 0x74, 0x61, 0x74, + 0x75, 0x73, 0x42, 0x0d, 0xfa, 0x42, 0x0a, 0x92, 0x01, 0x07, 0x22, 0x05, 0x82, 0x01, 0x02, 0x10, + 0x01, 0x52, 0x08, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x22, 0xed, 0x1e, 0x0a, 0x0b, + 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x3f, 0x0a, 0x07, 0x74, + 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, - 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, - 0x4a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x12, 0x42, 0x0a, 0x0f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, - 0x61, 0x6c, 0x5f, 0x6a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0a, 0xfa, 0x42, 0x07, 0xaa, 0x01, 0x04, 0x08, + 0x01, 0x2a, 0x00, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x41, 0x0a, 0x08, + 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0a, 0xfa, 0x42, 0x07, 0xaa, 0x01, + 0x04, 0x08, 0x01, 0x2a, 0x00, 0x52, 0x08, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, + 0x40, 0x0a, 0x0e, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x6a, 0x69, 0x74, 0x74, 0x65, + 0x72, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x0d, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4a, 0x69, 0x74, 0x74, 0x65, + 0x72, 0x12, 0x42, 0x0a, 0x0f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x5f, 0x6a, 0x69, + 0x74, 0x74, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x4a, + 0x69, 0x74, 0x74, 0x65, 0x72, 0x12, 0x36, 0x0a, 0x17, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, + 0x6c, 0x5f, 0x6a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, + 0x18, 0x12, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x15, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, + 0x4a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x57, 0x0a, + 0x13, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, + 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, + 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, + 0x10, 0x01, 0x52, 0x12, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x54, 0x68, 0x72, + 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x53, 0x0a, 0x11, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, + 0x79, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, + 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x10, 0x68, 0x65, 0x61, 0x6c, 0x74, + 0x68, 0x79, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x37, 0x0a, 0x08, 0x61, + 0x6c, 0x74, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x61, 0x6c, 0x74, + 0x50, 0x6f, 0x72, 0x74, 0x12, 0x45, 0x0a, 0x10, 0x72, 0x65, 0x75, 0x73, 0x65, 0x5f, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0f, 0x72, 0x65, 0x75, 0x73, + 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x5f, 0x0a, 0x11, 0x68, + 0x74, 0x74, 0x70, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, + 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x48, 0x65, + 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x00, 0x52, 0x0f, 0x68, 0x74, 0x74, + 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x5c, 0x0a, 0x10, + 0x74, 0x63, 0x70, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, + 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, + 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x54, 0x63, 0x70, 0x48, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x00, 0x52, 0x0e, 0x74, 0x63, 0x70, 0x48, + 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x5f, 0x0a, 0x11, 0x67, 0x72, + 0x70, 0x63, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x18, + 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x48, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x00, 0x52, 0x0f, 0x67, 0x72, 0x70, 0x63, + 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x65, 0x0a, 0x13, 0x63, + 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, 0x68, 0x65, + 0x63, 0x6b, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, + 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x43, 0x75, 0x73, 0x74, + 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x00, 0x52, + 0x11, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, + 0x63, 0x6b, 0x12, 0x53, 0x0a, 0x13, 0x6e, 0x6f, 0x5f, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, + 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0e, 0x69, 0x6e, 0x74, 0x65, - 0x72, 0x76, 0x61, 0x6c, 0x4a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x12, 0x36, 0x0a, 0x17, 0x69, 0x6e, - 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x5f, 0x6a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x5f, 0x70, 0x65, - 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x15, 0x69, 0x6e, 0x74, - 0x65, 0x72, 0x76, 0x61, 0x6c, 0x4a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x50, 0x65, 0x72, 0x63, 0x65, - 0x6e, 0x74, 0x12, 0x57, 0x0a, 0x13, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, - 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xfa, - 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x12, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x79, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x53, 0x0a, 0x11, 0x68, - 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, - 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x10, - 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, - 0x12, 0x37, 0x0a, 0x08, 0x61, 0x6c, 0x74, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x06, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x07, 0x61, 0x6c, 0x74, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x45, 0x0a, 0x10, 0x72, 0x65, 0x75, - 0x73, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x07, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x0f, 0x72, 0x65, 0x75, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, - 0x12, 0x5f, 0x0a, 0x11, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, - 0x63, 0x68, 0x65, 0x63, 0x6b, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, - 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x48, - 0x74, 0x74, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x00, - 0x52, 0x0f, 0x68, 0x74, 0x74, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, - 0x6b, 0x12, 0x5c, 0x0a, 0x10, 0x74, 0x63, 0x70, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, - 0x63, 0x68, 0x65, 0x63, 0x6b, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, - 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x54, - 0x63, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x00, 0x52, - 0x0e, 0x74, 0x63, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, - 0x5f, 0x0a, 0x11, 0x67, 0x72, 0x70, 0x63, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, - 0x68, 0x65, 0x63, 0x6b, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x65, 0x6e, 0x76, - 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, - 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x47, 0x72, - 0x70, 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x00, 0x52, - 0x0f, 0x67, 0x72, 0x70, 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, - 0x12, 0x65, 0x0a, 0x13, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, - 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, - 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, - 0x63, 0x6b, 0x48, 0x00, 0x52, 0x11, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, - 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x53, 0x0a, 0x13, 0x6e, 0x6f, 0x5f, 0x74, 0x72, - 0x61, 0x66, 0x66, 0x69, 0x63, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x0c, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, - 0x08, 0xfa, 0x42, 0x05, 0xaa, 0x01, 0x02, 0x2a, 0x00, 0x52, 0x11, 0x6e, 0x6f, 0x54, 0x72, 0x61, - 0x66, 0x66, 0x69, 0x63, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x62, 0x0a, 0x1b, - 0x6e, 0x6f, 0x5f, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x79, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x18, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x08, 0xfa, 0x42, - 0x05, 0xaa, 0x01, 0x02, 0x2a, 0x00, 0x52, 0x18, 0x6e, 0x6f, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, - 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, - 0x12, 0x52, 0x0a, 0x12, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x69, 0x6e, - 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, + 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x08, 0xfa, 0x42, 0x05, 0xaa, + 0x01, 0x02, 0x2a, 0x00, 0x52, 0x11, 0x6e, 0x6f, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x49, + 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x62, 0x0a, 0x1b, 0x6e, 0x6f, 0x5f, 0x74, 0x72, + 0x61, 0x66, 0x66, 0x69, 0x63, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x18, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x08, 0xfa, 0x42, 0x05, 0xaa, 0x01, 0x02, 0x2a, - 0x00, 0x52, 0x11, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x49, 0x6e, 0x74, 0x65, - 0x72, 0x76, 0x61, 0x6c, 0x12, 0x5b, 0x0a, 0x17, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, - 0x79, 0x5f, 0x65, 0x64, 0x67, 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, - 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x42, 0x08, 0xfa, 0x42, 0x05, 0xaa, 0x01, 0x02, 0x2a, 0x00, 0x52, 0x15, 0x75, 0x6e, 0x68, 0x65, - 0x61, 0x6c, 0x74, 0x68, 0x79, 0x45, 0x64, 0x67, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, - 0x6c, 0x12, 0x57, 0x0a, 0x15, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x65, 0x64, 0x67, - 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, + 0x00, 0x52, 0x18, 0x6e, 0x6f, 0x54, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x48, 0x65, 0x61, 0x6c, + 0x74, 0x68, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x52, 0x0a, 0x12, 0x75, + 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, + 0x6c, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x42, 0x08, 0xfa, 0x42, 0x05, 0xaa, 0x01, 0x02, 0x2a, 0x00, 0x52, 0x11, 0x75, 0x6e, + 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, + 0x5b, 0x0a, 0x17, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x65, 0x64, 0x67, + 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x08, 0xfa, 0x42, 0x05, - 0xaa, 0x01, 0x02, 0x2a, 0x00, 0x52, 0x13, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x45, 0x64, - 0x67, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x24, 0x0a, 0x0e, 0x65, 0x76, - 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x6f, 0x67, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x11, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x0c, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x4c, 0x6f, 0x67, 0x50, 0x61, 0x74, 0x68, - 0x12, 0x4d, 0x0a, 0x0d, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, - 0x65, 0x18, 0x16, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x45, - 0x76, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x52, 0x0c, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, - 0x46, 0x0a, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x5f, 0x6c, 0x6f, 0x67, 0x5f, 0x68, 0x65, - 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x5f, 0x66, 0x61, 0x69, 0x6c, 0x75, - 0x72, 0x65, 0x73, 0x18, 0x13, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1c, 0x61, 0x6c, 0x77, 0x61, 0x79, - 0x73, 0x4c, 0x6f, 0x67, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x46, - 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x73, 0x12, 0x4d, 0x0a, 0x0b, 0x74, 0x6c, 0x73, 0x5f, 0x6f, - 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, - 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, - 0x54, 0x6c, 0x73, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x0a, 0x74, 0x6c, 0x73, 0x4f, - 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x5e, 0x0a, 0x1f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, - 0x6f, 0x72, 0x74, 0x5f, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x5f, 0x6d, 0x61, 0x74, 0x63, 0x68, - 0x5f, 0x63, 0x72, 0x69, 0x74, 0x65, 0x72, 0x69, 0x61, 0x18, 0x17, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x52, 0x1c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, - 0x6f, 0x72, 0x74, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x43, 0x72, - 0x69, 0x74, 0x65, 0x72, 0x69, 0x61, 0x1a, 0x80, 0x01, 0x0a, 0x07, 0x50, 0x61, 0x79, 0x6c, 0x6f, - 0x61, 0x64, 0x12, 0x1d, 0x0a, 0x04, 0x74, 0x65, 0x78, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x04, 0x74, 0x65, 0x78, - 0x74, 0x12, 0x18, 0x0a, 0x06, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0c, 0x48, 0x00, 0x52, 0x06, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x3a, 0x2c, 0x9a, 0xc5, 0x88, - 0x1e, 0x27, 0x0a, 0x25, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, - 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, - 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x42, 0x0e, 0x0a, 0x07, 0x70, 0x61, 0x79, - 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x1a, 0xcc, 0x07, 0x0a, 0x0f, 0x48, 0x74, - 0x74, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x1f, 0x0a, - 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, - 0x72, 0x06, 0xc0, 0x01, 0x02, 0xc8, 0x01, 0x00, 0x52, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x12, 0x21, - 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0d, 0xfa, 0x42, - 0x0a, 0x72, 0x08, 0x10, 0x01, 0xc0, 0x01, 0x02, 0xc8, 0x01, 0x00, 0x52, 0x04, 0x70, 0x61, 0x74, - 0x68, 0x12, 0x3d, 0x0a, 0x04, 0x73, 0x65, 0x6e, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, - 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, - 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x04, 0x73, 0x65, 0x6e, 0x64, - 0x12, 0x43, 0x0a, 0x07, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x18, 0x04, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, - 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x07, 0x72, 0x65, - 0x63, 0x65, 0x69, 0x76, 0x65, 0x12, 0x57, 0x0a, 0x14, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x5f, 0x62, 0x75, 0x66, 0x66, 0x65, 0x72, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x0e, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x32, 0x02, 0x28, 0x00, 0x52, 0x12, 0x72, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x75, 0x66, 0x66, 0x65, 0x72, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x67, - 0x0a, 0x16, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, - 0x73, 0x5f, 0x74, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, + 0xaa, 0x01, 0x02, 0x2a, 0x00, 0x52, 0x15, 0x75, 0x6e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, + 0x45, 0x64, 0x67, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x57, 0x0a, 0x15, + 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x5f, 0x65, 0x64, 0x67, 0x65, 0x5f, 0x69, 0x6e, 0x74, + 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, + 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x08, 0xfa, 0x42, 0x05, 0xaa, 0x01, 0x02, 0x2a, 0x00, + 0x52, 0x13, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x79, 0x45, 0x64, 0x67, 0x65, 0x49, 0x6e, 0x74, + 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x31, 0x0a, 0x0e, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x6c, + 0x6f, 0x67, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x11, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0x92, + 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x18, 0x01, 0x52, 0x0c, 0x65, 0x76, 0x65, 0x6e, + 0x74, 0x4c, 0x6f, 0x67, 0x50, 0x61, 0x74, 0x68, 0x12, 0x4d, 0x0a, 0x0c, 0x65, 0x76, 0x65, 0x6e, + 0x74, 0x5f, 0x6c, 0x6f, 0x67, 0x67, 0x65, 0x72, 0x18, 0x19, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, - 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x09, 0xfa, 0x42, 0x06, 0x92, 0x01, 0x03, 0x10, - 0xe8, 0x07, 0x52, 0x13, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, - 0x72, 0x73, 0x54, 0x6f, 0x41, 0x64, 0x64, 0x12, 0x4b, 0x0a, 0x19, 0x72, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x5f, 0x74, 0x6f, 0x5f, 0x72, 0x65, - 0x6d, 0x6f, 0x76, 0x65, 0x18, 0x08, 0x20, 0x03, 0x28, 0x09, 0x42, 0x10, 0xfa, 0x42, 0x0d, 0x92, - 0x01, 0x0a, 0x22, 0x08, 0x72, 0x06, 0xc0, 0x01, 0x01, 0xc8, 0x01, 0x00, 0x52, 0x16, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x54, 0x6f, 0x52, 0x65, - 0x6d, 0x6f, 0x76, 0x65, 0x12, 0x46, 0x0a, 0x11, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, - 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x64, 0x45, 0x78, 0x74, 0x65, 0x6e, + 0x73, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0b, 0x65, 0x76, 0x65, 0x6e, + 0x74, 0x4c, 0x6f, 0x67, 0x67, 0x65, 0x72, 0x12, 0x4d, 0x0a, 0x0d, 0x65, 0x76, 0x65, 0x6e, 0x74, + 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x18, 0x16, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, + 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, + 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0c, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x53, + 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x46, 0x0a, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, + 0x5f, 0x6c, 0x6f, 0x67, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, + 0x6b, 0x5f, 0x66, 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x73, 0x18, 0x13, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x1c, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x4c, 0x6f, 0x67, 0x48, 0x65, 0x61, 0x6c, 0x74, + 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x46, 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x73, 0x12, 0x4d, + 0x0a, 0x0b, 0x74, 0x6c, 0x73, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x15, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, + 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x54, 0x6c, 0x73, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x52, 0x0a, 0x74, 0x6c, 0x73, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x5e, 0x0a, + 0x1f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x73, 0x6f, 0x63, 0x6b, 0x65, + 0x74, 0x5f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x63, 0x72, 0x69, 0x74, 0x65, 0x72, 0x69, 0x61, + 0x18, 0x17, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x52, + 0x1c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, + 0x4d, 0x61, 0x74, 0x63, 0x68, 0x43, 0x72, 0x69, 0x74, 0x65, 0x72, 0x69, 0x61, 0x1a, 0x80, 0x01, + 0x0a, 0x07, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x1d, 0x0a, 0x04, 0x74, 0x65, 0x78, + 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, + 0x48, 0x00, 0x52, 0x04, 0x74, 0x65, 0x78, 0x74, 0x12, 0x18, 0x0a, 0x06, 0x62, 0x69, 0x6e, 0x61, + 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x06, 0x62, 0x69, 0x6e, 0x61, + 0x72, 0x79, 0x3a, 0x2c, 0x9a, 0xc5, 0x88, 0x1e, 0x27, 0x0a, 0x25, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, + 0x42, 0x0e, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x03, 0xf8, 0x42, 0x01, + 0x1a, 0xcc, 0x07, 0x0a, 0x0f, 0x48, 0x74, 0x74, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, + 0x68, 0x65, 0x63, 0x6b, 0x12, 0x1f, 0x0a, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc8, 0x01, 0x00, 0xc0, 0x01, 0x02, 0x52, + 0x04, 0x68, 0x6f, 0x73, 0x74, 0x12, 0x21, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x42, 0x0d, 0xfa, 0x42, 0x0a, 0x72, 0x08, 0x10, 0x01, 0xc8, 0x01, 0x00, 0xc0, + 0x01, 0x02, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x3d, 0x0a, 0x04, 0x73, 0x65, 0x6e, 0x64, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, + 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, + 0x64, 0x52, 0x04, 0x73, 0x65, 0x6e, 0x64, 0x12, 0x43, 0x0a, 0x07, 0x72, 0x65, 0x63, 0x65, 0x69, + 0x76, 0x65, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, + 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, + 0x6f, 0x61, 0x64, 0x52, 0x07, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x12, 0x57, 0x0a, 0x14, + 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x62, 0x75, 0x66, 0x66, 0x65, 0x72, 0x5f, + 0x73, 0x69, 0x7a, 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, + 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x32, 0x02, 0x28, + 0x00, 0x52, 0x12, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x75, 0x66, 0x66, 0x65, + 0x72, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x67, 0x0a, 0x16, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x5f, 0x74, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x18, + 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, + 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x09, + 0xfa, 0x42, 0x06, 0x92, 0x01, 0x03, 0x10, 0xe8, 0x07, 0x52, 0x13, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x54, 0x6f, 0x41, 0x64, 0x64, 0x12, 0x4b, + 0x0a, 0x19, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, + 0x73, 0x5f, 0x74, 0x6f, 0x5f, 0x72, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x18, 0x08, 0x20, 0x03, 0x28, + 0x09, 0x42, 0x10, 0xfa, 0x42, 0x0d, 0x92, 0x01, 0x0a, 0x22, 0x08, 0x72, 0x06, 0xc8, 0x01, 0x00, + 0xc0, 0x01, 0x01, 0x52, 0x16, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, + 0x65, 0x72, 0x73, 0x54, 0x6f, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x12, 0x46, 0x0a, 0x11, 0x65, + 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, + 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, + 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x52, 0x61, 0x6e, 0x67, + 0x65, 0x52, 0x10, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x65, 0x73, 0x12, 0x48, 0x0a, 0x12, 0x72, 0x65, 0x74, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, + 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x2e, - 0x49, 0x6e, 0x74, 0x36, 0x34, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x10, 0x65, 0x78, 0x70, 0x65, - 0x63, 0x74, 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x12, 0x48, 0x0a, 0x12, - 0x72, 0x65, 0x74, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, - 0x65, 0x73, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x52, 0x61, - 0x6e, 0x67, 0x65, 0x52, 0x11, 0x72, 0x65, 0x74, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x53, 0x74, - 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x12, 0x54, 0x0a, 0x11, 0x63, 0x6f, 0x64, 0x65, 0x63, 0x5f, - 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, - 0x0e, 0x32, 0x1e, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, - 0x33, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x63, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, - 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x82, 0x01, 0x02, 0x10, 0x01, 0x52, 0x0f, 0x63, 0x6f, 0x64, - 0x65, 0x63, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x56, 0x0a, 0x14, - 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x5f, 0x6d, 0x61, 0x74, - 0x63, 0x68, 0x65, 0x72, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x65, 0x6e, 0x76, - 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, - 0x76, 0x33, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, - 0x52, 0x12, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x4d, 0x61, 0x74, - 0x63, 0x68, 0x65, 0x72, 0x12, 0x47, 0x0a, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x0d, - 0x20, 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x42, 0x0a, 0xfa, 0x42, 0x07, 0x82, 0x01, - 0x04, 0x10, 0x01, 0x20, 0x06, 0x52, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x3a, 0x34, 0x9a, - 0xc5, 0x88, 0x1e, 0x2f, 0x0a, 0x2d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, - 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, - 0x65, 0x63, 0x6b, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, - 0x65, 0x63, 0x6b, 0x4a, 0x04, 0x08, 0x05, 0x10, 0x06, 0x4a, 0x04, 0x08, 0x07, 0x10, 0x08, 0x52, - 0x0c, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x52, 0x09, 0x75, - 0x73, 0x65, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x32, 0x1a, 0xc9, 0x01, 0x0a, 0x0e, 0x54, 0x63, 0x70, - 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x3d, 0x0a, 0x04, 0x73, - 0x65, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, - 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, - 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x04, 0x73, 0x65, 0x6e, 0x64, 0x12, 0x43, 0x0a, 0x07, 0x72, 0x65, - 0x63, 0x65, 0x69, 0x76, 0x65, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, + 0x49, 0x6e, 0x74, 0x36, 0x34, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x11, 0x72, 0x65, 0x74, 0x72, + 0x69, 0x61, 0x62, 0x6c, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x12, 0x54, 0x0a, + 0x11, 0x63, 0x6f, 0x64, 0x65, 0x63, 0x5f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, + 0x70, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x63, 0x43, 0x6c, + 0x69, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x82, 0x01, 0x02, + 0x10, 0x01, 0x52, 0x0f, 0x63, 0x6f, 0x64, 0x65, 0x63, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, + 0x79, 0x70, 0x65, 0x12, 0x56, 0x0a, 0x14, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x6e, + 0x61, 0x6d, 0x65, 0x5f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x18, 0x0b, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x24, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, + 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, + 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x52, 0x12, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x4e, 0x61, 0x6d, 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x47, 0x0a, 0x06, 0x6d, + 0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, - 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x50, - 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x07, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x3a, - 0x33, 0x9a, 0xc5, 0x88, 0x1e, 0x2e, 0x0a, 0x2c, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, - 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x54, 0x63, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, - 0x68, 0x65, 0x63, 0x6b, 0x1a, 0x5b, 0x0a, 0x10, 0x52, 0x65, 0x64, 0x69, 0x73, 0x48, 0x65, 0x61, - 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x3a, 0x35, 0x9a, 0xc5, 0x88, 0x1e, - 0x30, 0x0a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, - 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, - 0x2e, 0x52, 0x65, 0x64, 0x69, 0x73, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, - 0x6b, 0x1a, 0xf4, 0x01, 0x0a, 0x0f, 0x47, 0x72, 0x70, 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, - 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x29, 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, - 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, - 0x72, 0x06, 0xc0, 0x01, 0x02, 0xc8, 0x01, 0x00, 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, - 0x69, 0x74, 0x79, 0x12, 0x5d, 0x0a, 0x10, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x6d, - 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, - 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x09, 0xfa, 0x42, 0x06, 0x92, 0x01, 0x03, 0x10, 0xe8, - 0x07, 0x52, 0x0f, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, - 0x74, 0x61, 0x3a, 0x34, 0x9a, 0xc5, 0x88, 0x1e, 0x2f, 0x0a, 0x2d, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, - 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x48, 0x65, 0x61, - 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x1a, 0xc0, 0x01, 0x0a, 0x11, 0x43, 0x75, 0x73, - 0x74, 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x1b, - 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, - 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x0c, 0x74, - 0x79, 0x70, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x48, 0x00, 0x52, 0x0b, 0x74, 0x79, 0x70, 0x65, 0x64, - 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x3a, 0x36, 0x9a, 0xc5, 0x88, 0x1e, 0x31, 0x0a, 0x2f, 0x65, + 0x76, 0x33, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, + 0x42, 0x0a, 0xfa, 0x42, 0x07, 0x82, 0x01, 0x04, 0x10, 0x01, 0x20, 0x06, 0x52, 0x06, 0x6d, 0x65, + 0x74, 0x68, 0x6f, 0x64, 0x3a, 0x34, 0x9a, 0xc5, 0x88, 0x1e, 0x2f, 0x0a, 0x2d, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, + 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x48, + 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x4a, 0x04, 0x08, 0x05, 0x10, 0x06, + 0x4a, 0x04, 0x08, 0x07, 0x10, 0x08, 0x52, 0x0c, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, + 0x6e, 0x61, 0x6d, 0x65, 0x52, 0x09, 0x75, 0x73, 0x65, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x32, 0x1a, + 0xc9, 0x01, 0x0a, 0x0e, 0x54, 0x63, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, + 0x63, 0x6b, 0x12, 0x3d, 0x0a, 0x04, 0x73, 0x65, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, + 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, + 0x65, 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x04, 0x73, 0x65, 0x6e, + 0x64, 0x12, 0x43, 0x0a, 0x07, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x18, 0x02, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, + 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x07, 0x72, + 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x3a, 0x33, 0x9a, 0xc5, 0x88, 0x1e, 0x2e, 0x0a, 0x2c, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, - 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x43, 0x75, 0x73, - 0x74, 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x42, 0x0d, - 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x4a, 0x04, 0x08, - 0x02, 0x10, 0x03, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x64, 0x0a, 0x0a, 0x54, - 0x6c, 0x73, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x6c, 0x70, - 0x6e, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x09, 0x52, 0x0d, 0x61, 0x6c, 0x70, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, - 0x3a, 0x2f, 0x9a, 0xc5, 0x88, 0x1e, 0x2a, 0x0a, 0x28, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, - 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x54, 0x6c, 0x73, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x3a, 0x24, 0x9a, 0xc5, 0x88, 0x1e, 0x1f, 0x0a, 0x1d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x54, 0x63, 0x70, + 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x1a, 0x5b, 0x0a, 0x10, 0x52, + 0x65, 0x64, 0x69, 0x73, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, + 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, + 0x79, 0x3a, 0x35, 0x9a, 0xc5, 0x88, 0x1e, 0x30, 0x0a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, - 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x42, 0x15, 0x0a, 0x0e, 0x68, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x4a, 0x04, - 0x08, 0x0a, 0x10, 0x0b, 0x2a, 0x60, 0x0a, 0x0c, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x53, 0x74, - 0x61, 0x74, 0x75, 0x73, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, - 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x48, 0x45, 0x41, 0x4c, 0x54, 0x48, 0x59, 0x10, 0x01, 0x12, 0x0d, - 0x0a, 0x09, 0x55, 0x4e, 0x48, 0x45, 0x41, 0x4c, 0x54, 0x48, 0x59, 0x10, 0x02, 0x12, 0x0c, 0x0a, - 0x08, 0x44, 0x52, 0x41, 0x49, 0x4e, 0x49, 0x4e, 0x47, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x54, - 0x49, 0x4d, 0x45, 0x4f, 0x55, 0x54, 0x10, 0x04, 0x12, 0x0c, 0x0a, 0x08, 0x44, 0x45, 0x47, 0x52, - 0x41, 0x44, 0x45, 0x44, 0x10, 0x05, 0x42, 0x84, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x10, 0x48, - 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, - 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, - 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, - 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x52, 0x65, 0x64, 0x69, 0x73, 0x48, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x1a, 0xf4, 0x01, 0x0a, 0x0f, 0x47, 0x72, 0x70, + 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x21, 0x0a, 0x0c, + 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0b, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, + 0x29, 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc8, 0x01, 0x00, 0xc0, 0x01, 0x02, 0x52, + 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x5d, 0x0a, 0x10, 0x69, 0x6e, + 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x65, 0x61, 0x64, + 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x09, 0xfa, + 0x42, 0x06, 0x92, 0x01, 0x03, 0x10, 0xe8, 0x07, 0x52, 0x0f, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, + 0x6c, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x3a, 0x34, 0x9a, 0xc5, 0x88, 0x1e, 0x2f, + 0x0a, 0x2d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, + 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, + 0x47, 0x72, 0x70, 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x1a, + 0xc0, 0x01, 0x0a, 0x11, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, + 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x1b, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x04, 0x6e, 0x61, + 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x0c, 0x74, 0x79, 0x70, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x48, 0x00, + 0x52, 0x0b, 0x74, 0x79, 0x70, 0x65, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x3a, 0x36, 0x9a, + 0xc5, 0x88, 0x1e, 0x31, 0x0a, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, + 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, + 0x65, 0x63, 0x6b, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, + 0x43, 0x68, 0x65, 0x63, 0x6b, 0x42, 0x0d, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, + 0x74, 0x79, 0x70, 0x65, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x1a, 0x64, 0x0a, 0x0a, 0x54, 0x6c, 0x73, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x6c, 0x70, 0x6e, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, + 0x6c, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0d, 0x61, 0x6c, 0x70, 0x6e, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, 0x3a, 0x2f, 0x9a, 0xc5, 0x88, 0x1e, 0x2a, 0x0a, 0x28, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x2e, 0x54, 0x6c, + 0x73, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x24, 0x9a, 0xc5, 0x88, 0x1e, 0x1f, 0x0a, + 0x1d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, + 0x72, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x42, 0x15, + 0x0a, 0x0e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x65, 0x72, + 0x12, 0x03, 0xf8, 0x42, 0x01, 0x4a, 0x04, 0x08, 0x0a, 0x10, 0x0b, 0x2a, 0x60, 0x0a, 0x0c, 0x48, + 0x65, 0x61, 0x6c, 0x74, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x0b, 0x0a, 0x07, 0x55, + 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x48, 0x45, 0x41, 0x4c, + 0x54, 0x48, 0x59, 0x10, 0x01, 0x12, 0x0d, 0x0a, 0x09, 0x55, 0x4e, 0x48, 0x45, 0x41, 0x4c, 0x54, + 0x48, 0x59, 0x10, 0x02, 0x12, 0x0c, 0x0a, 0x08, 0x44, 0x52, 0x41, 0x49, 0x4e, 0x49, 0x4e, 0x47, + 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x54, 0x49, 0x4d, 0x45, 0x4f, 0x55, 0x54, 0x10, 0x04, 0x12, + 0x0c, 0x0a, 0x08, 0x44, 0x45, 0x47, 0x52, 0x41, 0x44, 0x45, 0x44, 0x10, 0x05, 0x42, 0x84, 0x01, + 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x10, 0x48, 0x65, + 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, + 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, + 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1426,15 +1458,16 @@ var file_envoy_config_core_v3_health_check_proto_goTypes = []interface{}{ (*duration.Duration)(nil), // 10: google.protobuf.Duration (*wrappers.UInt32Value)(nil), // 11: google.protobuf.UInt32Value (*wrappers.BoolValue)(nil), // 12: google.protobuf.BoolValue - (*EventServiceConfig)(nil), // 13: envoy.config.core.v3.EventServiceConfig - (*_struct.Struct)(nil), // 14: google.protobuf.Struct - (*wrappers.UInt64Value)(nil), // 15: google.protobuf.UInt64Value - (*HeaderValueOption)(nil), // 16: envoy.config.core.v3.HeaderValueOption - (*v3.Int64Range)(nil), // 17: envoy.type.v3.Int64Range - (v3.CodecClientType)(0), // 18: envoy.type.v3.CodecClientType - (*v31.StringMatcher)(nil), // 19: envoy.type.matcher.v3.StringMatcher - (RequestMethod)(0), // 20: envoy.config.core.v3.RequestMethod - (*any1.Any)(nil), // 21: google.protobuf.Any + (*TypedExtensionConfig)(nil), // 13: envoy.config.core.v3.TypedExtensionConfig + (*EventServiceConfig)(nil), // 14: envoy.config.core.v3.EventServiceConfig + (*_struct.Struct)(nil), // 15: google.protobuf.Struct + (*wrappers.UInt64Value)(nil), // 16: google.protobuf.UInt64Value + (*HeaderValueOption)(nil), // 17: envoy.config.core.v3.HeaderValueOption + (*v3.Int64Range)(nil), // 18: envoy.type.v3.Int64Range + (v3.CodecClientType)(0), // 19: envoy.type.v3.CodecClientType + (*v31.StringMatcher)(nil), // 20: envoy.type.matcher.v3.StringMatcher + (RequestMethod)(0), // 21: envoy.config.core.v3.RequestMethod + (*any1.Any)(nil), // 22: google.protobuf.Any } var file_envoy_config_core_v3_health_check_proto_depIdxs = []int32{ 0, // 0: envoy.config.core.v3.HealthStatusSet.statuses:type_name -> envoy.config.core.v3.HealthStatus @@ -1455,27 +1488,28 @@ var file_envoy_config_core_v3_health_check_proto_depIdxs = []int32{ 10, // 15: envoy.config.core.v3.HealthCheck.unhealthy_interval:type_name -> google.protobuf.Duration 10, // 16: envoy.config.core.v3.HealthCheck.unhealthy_edge_interval:type_name -> google.protobuf.Duration 10, // 17: envoy.config.core.v3.HealthCheck.healthy_edge_interval:type_name -> google.protobuf.Duration - 13, // 18: envoy.config.core.v3.HealthCheck.event_service:type_name -> envoy.config.core.v3.EventServiceConfig - 9, // 19: envoy.config.core.v3.HealthCheck.tls_options:type_name -> envoy.config.core.v3.HealthCheck.TlsOptions - 14, // 20: envoy.config.core.v3.HealthCheck.transport_socket_match_criteria:type_name -> google.protobuf.Struct - 3, // 21: envoy.config.core.v3.HealthCheck.HttpHealthCheck.send:type_name -> envoy.config.core.v3.HealthCheck.Payload - 3, // 22: envoy.config.core.v3.HealthCheck.HttpHealthCheck.receive:type_name -> envoy.config.core.v3.HealthCheck.Payload - 15, // 23: envoy.config.core.v3.HealthCheck.HttpHealthCheck.response_buffer_size:type_name -> google.protobuf.UInt64Value - 16, // 24: envoy.config.core.v3.HealthCheck.HttpHealthCheck.request_headers_to_add:type_name -> envoy.config.core.v3.HeaderValueOption - 17, // 25: envoy.config.core.v3.HealthCheck.HttpHealthCheck.expected_statuses:type_name -> envoy.type.v3.Int64Range - 17, // 26: envoy.config.core.v3.HealthCheck.HttpHealthCheck.retriable_statuses:type_name -> envoy.type.v3.Int64Range - 18, // 27: envoy.config.core.v3.HealthCheck.HttpHealthCheck.codec_client_type:type_name -> envoy.type.v3.CodecClientType - 19, // 28: envoy.config.core.v3.HealthCheck.HttpHealthCheck.service_name_matcher:type_name -> envoy.type.matcher.v3.StringMatcher - 20, // 29: envoy.config.core.v3.HealthCheck.HttpHealthCheck.method:type_name -> envoy.config.core.v3.RequestMethod - 3, // 30: envoy.config.core.v3.HealthCheck.TcpHealthCheck.send:type_name -> envoy.config.core.v3.HealthCheck.Payload - 3, // 31: envoy.config.core.v3.HealthCheck.TcpHealthCheck.receive:type_name -> envoy.config.core.v3.HealthCheck.Payload - 16, // 32: envoy.config.core.v3.HealthCheck.GrpcHealthCheck.initial_metadata:type_name -> envoy.config.core.v3.HeaderValueOption - 21, // 33: envoy.config.core.v3.HealthCheck.CustomHealthCheck.typed_config:type_name -> google.protobuf.Any - 34, // [34:34] is the sub-list for method output_type - 34, // [34:34] is the sub-list for method input_type - 34, // [34:34] is the sub-list for extension type_name - 34, // [34:34] is the sub-list for extension extendee - 0, // [0:34] is the sub-list for field type_name + 13, // 18: envoy.config.core.v3.HealthCheck.event_logger:type_name -> envoy.config.core.v3.TypedExtensionConfig + 14, // 19: envoy.config.core.v3.HealthCheck.event_service:type_name -> envoy.config.core.v3.EventServiceConfig + 9, // 20: envoy.config.core.v3.HealthCheck.tls_options:type_name -> envoy.config.core.v3.HealthCheck.TlsOptions + 15, // 21: envoy.config.core.v3.HealthCheck.transport_socket_match_criteria:type_name -> google.protobuf.Struct + 3, // 22: envoy.config.core.v3.HealthCheck.HttpHealthCheck.send:type_name -> envoy.config.core.v3.HealthCheck.Payload + 3, // 23: envoy.config.core.v3.HealthCheck.HttpHealthCheck.receive:type_name -> envoy.config.core.v3.HealthCheck.Payload + 16, // 24: envoy.config.core.v3.HealthCheck.HttpHealthCheck.response_buffer_size:type_name -> google.protobuf.UInt64Value + 17, // 25: envoy.config.core.v3.HealthCheck.HttpHealthCheck.request_headers_to_add:type_name -> envoy.config.core.v3.HeaderValueOption + 18, // 26: envoy.config.core.v3.HealthCheck.HttpHealthCheck.expected_statuses:type_name -> envoy.type.v3.Int64Range + 18, // 27: envoy.config.core.v3.HealthCheck.HttpHealthCheck.retriable_statuses:type_name -> envoy.type.v3.Int64Range + 19, // 28: envoy.config.core.v3.HealthCheck.HttpHealthCheck.codec_client_type:type_name -> envoy.type.v3.CodecClientType + 20, // 29: envoy.config.core.v3.HealthCheck.HttpHealthCheck.service_name_matcher:type_name -> envoy.type.matcher.v3.StringMatcher + 21, // 30: envoy.config.core.v3.HealthCheck.HttpHealthCheck.method:type_name -> envoy.config.core.v3.RequestMethod + 3, // 31: envoy.config.core.v3.HealthCheck.TcpHealthCheck.send:type_name -> envoy.config.core.v3.HealthCheck.Payload + 3, // 32: envoy.config.core.v3.HealthCheck.TcpHealthCheck.receive:type_name -> envoy.config.core.v3.HealthCheck.Payload + 17, // 33: envoy.config.core.v3.HealthCheck.GrpcHealthCheck.initial_metadata:type_name -> envoy.config.core.v3.HeaderValueOption + 22, // 34: envoy.config.core.v3.HealthCheck.CustomHealthCheck.typed_config:type_name -> google.protobuf.Any + 35, // [35:35] is the sub-list for method output_type + 35, // [35:35] is the sub-list for method input_type + 35, // [35:35] is the sub-list for extension type_name + 35, // [35:35] is the sub-list for extension extendee + 0, // [0:35] is the sub-list for field type_name } func init() { file_envoy_config_core_v3_health_check_proto_init() } @@ -1485,6 +1519,7 @@ func file_envoy_config_core_v3_health_check_proto_init() { } file_envoy_config_core_v3_base_proto_init() file_envoy_config_core_v3_event_service_config_proto_init() + file_envoy_config_core_v3_extension_proto_init() if !protoimpl.UnsafeEnabled { file_envoy_config_core_v3_health_check_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*HealthStatusSet); i { diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.validate.go index 5abf42ff3..837a3e1fa 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.validate.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/health_check.pb.validate.go @@ -609,6 +609,40 @@ func (m *HealthCheck) validate(all bool) error { // no validation rules for EventLogPath + for idx, item := range m.GetEventLogger() { + _, _ = idx, item + + if all { + switch v := interface{}(item).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, HealthCheckValidationError{ + field: fmt.Sprintf("EventLogger[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, HealthCheckValidationError{ + field: fmt.Sprintf("EventLogger[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return HealthCheckValidationError{ + field: fmt.Sprintf("EventLogger[%v]", idx), + reason: "embedded message failed validation", + cause: err, + } + } + } + + } + if all { switch v := interface{}(m.GetEventService()).(type) { case interface{ ValidateAll() error }: diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_service.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_service.pb.go new file mode 100644 index 000000000..0ae3e527b --- /dev/null +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_service.pb.go @@ -0,0 +1,194 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.30.0 +// protoc v4.23.4 +// source: envoy/config/core/v3/http_service.proto + +package corev3 + +import ( + _ "github.com/cncf/xds/go/udpa/annotations" + _ "github.com/envoyproxy/protoc-gen-validate/validate" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// HTTP service configuration. +type HttpService struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The service's HTTP URI. For example: + // + // .. code-block:: yaml + // + // http_uri: + // uri: https://www.myserviceapi.com/v1/data + // cluster: www.myserviceapi.com|443 + HttpUri *HttpUri `protobuf:"bytes,1,opt,name=http_uri,json=httpUri,proto3" json:"http_uri,omitempty"` + // Specifies a list of HTTP headers that should be added to each request + // handled by this virtual host. + RequestHeadersToAdd []*HeaderValueOption `protobuf:"bytes,2,rep,name=request_headers_to_add,json=requestHeadersToAdd,proto3" json:"request_headers_to_add,omitempty"` +} + +func (x *HttpService) Reset() { + *x = HttpService{} + if protoimpl.UnsafeEnabled { + mi := &file_envoy_config_core_v3_http_service_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HttpService) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HttpService) ProtoMessage() {} + +func (x *HttpService) ProtoReflect() protoreflect.Message { + mi := &file_envoy_config_core_v3_http_service_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HttpService.ProtoReflect.Descriptor instead. +func (*HttpService) Descriptor() ([]byte, []int) { + return file_envoy_config_core_v3_http_service_proto_rawDescGZIP(), []int{0} +} + +func (x *HttpService) GetHttpUri() *HttpUri { + if x != nil { + return x.HttpUri + } + return nil +} + +func (x *HttpService) GetRequestHeadersToAdd() []*HeaderValueOption { + if x != nil { + return x.RequestHeadersToAdd + } + return nil +} + +var File_envoy_config_core_v3_http_service_proto protoreflect.FileDescriptor + +var file_envoy_config_core_v3_http_service_proto_rawDesc = []byte{ + 0x0a, 0x27, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, + 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x73, 0x65, 0x72, 0x76, + 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x14, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x1a, + 0x1f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, + 0x72, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x1a, 0x23, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, + 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x75, 0x72, 0x69, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1d, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, + 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, + 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb0, 0x01, + 0x0a, 0x0b, 0x48, 0x74, 0x74, 0x70, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x38, 0x0a, + 0x08, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x75, 0x72, 0x69, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1d, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, + 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, 0x52, 0x07, + 0x68, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, 0x12, 0x67, 0x0a, 0x16, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x5f, 0x74, 0x6f, 0x5f, 0x61, 0x64, + 0x64, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, + 0x65, 0x61, 0x64, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x42, 0x09, 0xfa, 0x42, 0x06, 0x92, 0x01, 0x03, 0x10, 0xe8, 0x07, 0x52, 0x13, 0x72, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x54, 0x6f, 0x41, 0x64, 0x64, + 0x42, 0x84, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, + 0x10, 0x48, 0x74, 0x74, 0x70, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, + 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, + 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_envoy_config_core_v3_http_service_proto_rawDescOnce sync.Once + file_envoy_config_core_v3_http_service_proto_rawDescData = file_envoy_config_core_v3_http_service_proto_rawDesc +) + +func file_envoy_config_core_v3_http_service_proto_rawDescGZIP() []byte { + file_envoy_config_core_v3_http_service_proto_rawDescOnce.Do(func() { + file_envoy_config_core_v3_http_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_envoy_config_core_v3_http_service_proto_rawDescData) + }) + return file_envoy_config_core_v3_http_service_proto_rawDescData +} + +var file_envoy_config_core_v3_http_service_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_envoy_config_core_v3_http_service_proto_goTypes = []interface{}{ + (*HttpService)(nil), // 0: envoy.config.core.v3.HttpService + (*HttpUri)(nil), // 1: envoy.config.core.v3.HttpUri + (*HeaderValueOption)(nil), // 2: envoy.config.core.v3.HeaderValueOption +} +var file_envoy_config_core_v3_http_service_proto_depIdxs = []int32{ + 1, // 0: envoy.config.core.v3.HttpService.http_uri:type_name -> envoy.config.core.v3.HttpUri + 2, // 1: envoy.config.core.v3.HttpService.request_headers_to_add:type_name -> envoy.config.core.v3.HeaderValueOption + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_envoy_config_core_v3_http_service_proto_init() } +func file_envoy_config_core_v3_http_service_proto_init() { + if File_envoy_config_core_v3_http_service_proto != nil { + return + } + file_envoy_config_core_v3_base_proto_init() + file_envoy_config_core_v3_http_uri_proto_init() + if !protoimpl.UnsafeEnabled { + file_envoy_config_core_v3_http_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*HttpService); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_envoy_config_core_v3_http_service_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_envoy_config_core_v3_http_service_proto_goTypes, + DependencyIndexes: file_envoy_config_core_v3_http_service_proto_depIdxs, + MessageInfos: file_envoy_config_core_v3_http_service_proto_msgTypes, + }.Build() + File_envoy_config_core_v3_http_service_proto = out.File + file_envoy_config_core_v3_http_service_proto_rawDesc = nil + file_envoy_config_core_v3_http_service_proto_goTypes = nil + file_envoy_config_core_v3_http_service_proto_depIdxs = nil +} diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_service.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_service.pb.validate.go new file mode 100644 index 000000000..2d9590507 --- /dev/null +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_service.pb.validate.go @@ -0,0 +1,209 @@ +// Code generated by protoc-gen-validate. DO NOT EDIT. +// source: envoy/config/core/v3/http_service.proto + +package corev3 + +import ( + "bytes" + "errors" + "fmt" + "net" + "net/mail" + "net/url" + "regexp" + "sort" + "strings" + "time" + "unicode/utf8" + + "google.golang.org/protobuf/types/known/anypb" +) + +// ensure the imports are used +var ( + _ = bytes.MinRead + _ = errors.New("") + _ = fmt.Print + _ = utf8.UTFMax + _ = (*regexp.Regexp)(nil) + _ = (*strings.Reader)(nil) + _ = net.IPv4len + _ = time.Duration(0) + _ = (*url.URL)(nil) + _ = (*mail.Address)(nil) + _ = anypb.Any{} + _ = sort.Sort +) + +// Validate checks the field values on HttpService with the rules defined in +// the proto definition for this message. If any rules are violated, the first +// error encountered is returned, or nil if there are no violations. +func (m *HttpService) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on HttpService with the rules defined in +// the proto definition for this message. If any rules are violated, the +// result is a list of violation errors wrapped in HttpServiceMultiError, or +// nil if none found. +func (m *HttpService) ValidateAll() error { + return m.validate(true) +} + +func (m *HttpService) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + if all { + switch v := interface{}(m.GetHttpUri()).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, HttpServiceValidationError{ + field: "HttpUri", + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, HttpServiceValidationError{ + field: "HttpUri", + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(m.GetHttpUri()).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return HttpServiceValidationError{ + field: "HttpUri", + reason: "embedded message failed validation", + cause: err, + } + } + } + + if len(m.GetRequestHeadersToAdd()) > 1000 { + err := HttpServiceValidationError{ + field: "RequestHeadersToAdd", + reason: "value must contain no more than 1000 item(s)", + } + if !all { + return err + } + errors = append(errors, err) + } + + for idx, item := range m.GetRequestHeadersToAdd() { + _, _ = idx, item + + if all { + switch v := interface{}(item).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, HttpServiceValidationError{ + field: fmt.Sprintf("RequestHeadersToAdd[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, HttpServiceValidationError{ + field: fmt.Sprintf("RequestHeadersToAdd[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return HttpServiceValidationError{ + field: fmt.Sprintf("RequestHeadersToAdd[%v]", idx), + reason: "embedded message failed validation", + cause: err, + } + } + } + + } + + if len(errors) > 0 { + return HttpServiceMultiError(errors) + } + + return nil +} + +// HttpServiceMultiError is an error wrapping multiple validation errors +// returned by HttpService.ValidateAll() if the designated constraints aren't met. +type HttpServiceMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m HttpServiceMultiError) Error() string { + var msgs []string + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m HttpServiceMultiError) AllErrors() []error { return m } + +// HttpServiceValidationError is the validation error returned by +// HttpService.Validate if the designated constraints aren't met. +type HttpServiceValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e HttpServiceValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e HttpServiceValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e HttpServiceValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e HttpServiceValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e HttpServiceValidationError) ErrorName() string { return "HttpServiceValidationError" } + +// Error satisfies the builtin error interface +func (e HttpServiceValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sHttpService.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = HttpServiceValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = HttpServiceValidationError{} diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.go index 47dc67144..39bb22f7e 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/http_uri.proto package corev3 @@ -35,15 +35,15 @@ type HttpUri struct { // // .. code-block:: yaml // - // uri: https://www.googleapis.com/oauth2/v1/certs - // + // uri: https://www.googleapis.com/oauth2/v1/certs Uri string `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` - // Specify how ``uri`` is to be fetched. Today, this requires an explicit + // Specify how “uri“ is to be fetched. Today, this requires an explicit // cluster, but in the future we may support dynamic cluster creation or // inline DNS resolution. See `issue // `_. // // Types that are assignable to HttpUpstreamType: + // // *HttpUri_Cluster HttpUpstreamType isHttpUri_HttpUpstreamType `protobuf_oneof:"http_upstream_type"` // Sets the maximum duration in milliseconds that a response can take to arrive upon request. @@ -122,8 +122,7 @@ type HttpUri_Cluster struct { // // .. code-block:: yaml // - // cluster: jwks_cluster - // + // cluster: jwks_cluster Cluster string `protobuf:"bytes,2,opt,name=cluster,proto3,oneof"` } @@ -143,28 +142,29 @@ var file_envoy_config_core_v3_http_uri_proto_rawDesc = []byte{ 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xc7, 0x01, 0x0a, 0x07, 0x48, 0x74, 0x74, 0x70, 0x55, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xcf, 0x01, 0x0a, 0x07, 0x48, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, 0x12, 0x19, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x03, 0x75, 0x72, 0x69, 0x12, 0x23, 0x0a, 0x07, 0x63, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x07, 0x63, 0x6c, 0x75, 0x73, 0x74, - 0x65, 0x72, 0x12, 0x3f, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x03, 0x20, + 0x65, 0x72, 0x12, 0x47, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0a, - 0xfa, 0x42, 0x07, 0xaa, 0x01, 0x04, 0x08, 0x01, 0x32, 0x00, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, - 0x6f, 0x75, 0x74, 0x3a, 0x20, 0x9a, 0xc5, 0x88, 0x1e, 0x1b, 0x0a, 0x19, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, - 0x74, 0x70, 0x55, 0x72, 0x69, 0x42, 0x19, 0x0a, 0x12, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x75, 0x70, - 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x12, 0x03, 0xf8, 0x42, 0x01, - 0x42, 0x80, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x12, + 0xfa, 0x42, 0x0f, 0xaa, 0x01, 0x0c, 0x08, 0x01, 0x1a, 0x06, 0x08, 0x80, 0x80, 0x80, 0x80, 0x10, + 0x32, 0x00, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x3a, 0x20, 0x9a, 0xc5, 0x88, + 0x1e, 0x1b, 0x0a, 0x19, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, + 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, 0x42, 0x19, 0x0a, + 0x12, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x75, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x74, + 0x79, 0x70, 0x65, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x80, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, + 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0c, 0x48, 0x74, 0x74, 0x70, 0x55, 0x72, 0x69, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, - 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, - 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.validate.go index 0e3ab815e..2c0a69c41 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.validate.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/http_uri.pb.validate.go @@ -92,12 +92,13 @@ func (m *HttpUri) validate(all bool) error { errors = append(errors, err) } else { + lt := time.Duration(4294967296*time.Second + 0*time.Nanosecond) gte := time.Duration(0*time.Second + 0*time.Nanosecond) - if dur < gte { + if dur < gte || dur >= lt { err := HttpUriValidationError{ field: "Timeout", - reason: "value must be greater than or equal to 0s", + reason: "value must be inside range [0s, 1193046h28m16s)", } if !all { return err diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.go index 16a141143..6ab658340 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/protocol.proto package corev3 @@ -197,7 +197,7 @@ func (x *QuicKeepAliveSettings) GetInitialInterval() *duration.Duration { } // QUIC protocol options which apply to both downstream and upstream connections. -// [#next-free-field: 6] +// [#next-free-field: 8] type QuicProtocolOptions struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -217,21 +217,27 @@ type QuicProtocolOptions struct { // QUIC stream send and receive buffers. Once the buffer reaches this pointer, watermark callbacks will fire to // stop the flow of data to the stream buffers. InitialStreamWindowSize *wrappers.UInt32Value `protobuf:"bytes,2,opt,name=initial_stream_window_size,json=initialStreamWindowSize,proto3" json:"initial_stream_window_size,omitempty"` - // Similar to ``initial_stream_window_size``, but for connection-level + // Similar to “initial_stream_window_size“, but for connection-level // flow-control. Valid values rage from 1 to 25165824 (24MB, maximum supported by QUICHE) and defaults to 65536 (2^16). - // window. Currently, this has the same minimum/default as ``initial_stream_window_size``. + // window. Currently, this has the same minimum/default as “initial_stream_window_size“. // // NOTE: 16384 (2^14) is the minimum window size supported in Google QUIC. We only support increasing the default // window size now, so it's also the minimum. InitialConnectionWindowSize *wrappers.UInt32Value `protobuf:"bytes,3,opt,name=initial_connection_window_size,json=initialConnectionWindowSize,proto3" json:"initial_connection_window_size,omitempty"` // The number of timeouts that can occur before port migration is triggered for QUIC clients. - // This defaults to 1. If set to 0, port migration will not occur on path degrading. + // This defaults to 4. If set to 0, port migration will not occur on path degrading. // Timeout here refers to QUIC internal path degrading timeout mechanism, such as PTO. // This has no effect on server sessions. NumTimeoutsToTriggerPortMigration *wrappers.UInt32Value `protobuf:"bytes,4,opt,name=num_timeouts_to_trigger_port_migration,json=numTimeoutsToTriggerPortMigration,proto3" json:"num_timeouts_to_trigger_port_migration,omitempty"` // Probes the peer at the configured interval to solicit traffic, i.e. ACK or PATH_RESPONSE, from the peer to push back connection idle timeout. // If absent, use the default keepalive behavior of which a client connection sends PINGs every 15s, and a server connection doesn't do anything. ConnectionKeepalive *QuicKeepAliveSettings `protobuf:"bytes,5,opt,name=connection_keepalive,json=connectionKeepalive,proto3" json:"connection_keepalive,omitempty"` + // A comma-separated list of strings representing QUIC connection options defined in + // `QUICHE `_ and to be sent by upstream connections. + ConnectionOptions string `protobuf:"bytes,6,opt,name=connection_options,json=connectionOptions,proto3" json:"connection_options,omitempty"` + // A comma-separated list of strings representing QUIC client connection options defined in + // `QUICHE `_ and to be sent by upstream connections. + ClientConnectionOptions string `protobuf:"bytes,7,opt,name=client_connection_options,json=clientConnectionOptions,proto3" json:"client_connection_options,omitempty"` } func (x *QuicProtocolOptions) Reset() { @@ -301,6 +307,20 @@ func (x *QuicProtocolOptions) GetConnectionKeepalive() *QuicKeepAliveSettings { return nil } +func (x *QuicProtocolOptions) GetConnectionOptions() string { + if x != nil { + return x.ConnectionOptions + } + return "" +} + +func (x *QuicProtocolOptions) GetClientConnectionOptions() string { + if x != nil { + return x.ClientConnectionOptions + } + return "" +} + type UpstreamHttpProtocolOptions struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -315,7 +335,7 @@ type UpstreamHttpProtocolOptions struct { // Automatic validate upstream presented certificate for new upstream connections based on the // downstream HTTP host/authority header or any other arbitrary header when :ref:`override_auto_sni_header ` // is set, as seen by the :ref:`router filter `. - // This field is intended to be set with ``auto_sni`` field. + // This field is intended to be set with “auto_sni“ field. // Does nothing if a filter before the http router filter sets the corresponding metadata. AutoSanValidation bool `protobuf:"varint,2,opt,name=auto_san_validation,json=autoSanValidation,proto3" json:"auto_san_validation,omitempty"` // An optional alternative to the host/authority header to be used for setting the SNI value. @@ -323,7 +343,7 @@ type UpstreamHttpProtocolOptions struct { // :ref:`router filter `. // If unset, host/authority header will be used for populating the SNI. If the specified header // is not found or the value is empty, host/authority header will be used instead. - // This field is intended to be set with ``auto_sni`` and/or ``auto_san_validation`` fields. + // This field is intended to be set with “auto_sni“ and/or “auto_san_validation“ fields. // If none of these fields are set then setting this would be a no-op. // Does nothing if a filter before the http router filter sets the corresponding metadata. OverrideAutoSniHeader string `protobuf:"bytes,3,opt,name=override_auto_sni_header,json=overrideAutoSniHeader,proto3" json:"override_auto_sni_header,omitempty"` @@ -402,9 +422,9 @@ type AlternateProtocolsCacheOptions struct { // // .. note: // - // The implementation is approximate and enforced independently on each worker thread, thus - // it is possible for the maximum entries in the cache to go slightly above the configured - // value depending on timing. This is similar to how other circuit breakers work. + // The implementation is approximate and enforced independently on each worker thread, thus + // it is possible for the maximum entries in the cache to go slightly above the configured + // value depending on timing. This is similar to how other circuit breakers work. MaxEntries *wrappers.UInt32Value `protobuf:"bytes,2,opt,name=max_entries,json=maxEntries,proto3" json:"max_entries,omitempty"` // Allows configuring a persistent // :ref:`key value store ` to flush @@ -415,10 +435,10 @@ type AlternateProtocolsCacheOptions struct { // Allows pre-populating the cache with entries, as described above. PrepopulatedEntries []*AlternateProtocolsCacheOptions_AlternateProtocolsCacheEntry `protobuf:"bytes,4,rep,name=prepopulated_entries,json=prepopulatedEntries,proto3" json:"prepopulated_entries,omitempty"` // Optional list of hostnames suffixes for which Alt-Svc entries can be shared. For example, if - // this list contained the value ``.c.example.com``, then an Alt-Svc entry for ``foo.c.example.com`` - // could be shared with ``bar.c.example.com`` but would not be shared with ``baz.example.com``. On - // the other hand, if the list contained the value ``.example.com`` then all three hosts could share - // Alt-Svc entries. Each entry must start with ``.``. If a hostname matches multiple suffixes, the + // this list contained the value “.c.example.com“, then an Alt-Svc entry for “foo.c.example.com“ + // could be shared with “bar.c.example.com“ but would not be shared with “baz.example.com“. On + // the other hand, if the list contained the value “.example.com“ then all three hosts could share + // Alt-Svc entries. Each entry must start with “.“. If a hostname matches multiple suffixes, the // first listed suffix will be used. // // Since lookup in this list is O(n), it is recommended that the number of suffixes be limited. @@ -509,8 +529,9 @@ type HttpProtocolOptions struct { // If not specified, this defaults to 1 hour. To disable idle timeouts explicitly set this to 0. // // .. warning:: - // Disabling this timeout has a highly likelihood of yielding connection leaks due to lost TCP - // FIN packets, etc. + // + // Disabling this timeout has a highly likelihood of yielding connection leaks due to lost TCP + // FIN packets, etc. // // If the :ref:`overload action ` "envoy.overload_actions.reduce_timeouts" // is configured, this timeout is scaled for downstream connections according to the value for @@ -626,16 +647,16 @@ type Http1ProtocolOptions struct { // Handle HTTP requests with absolute URLs in the requests. These requests // are generally sent by clients to forward/explicit proxies. This allows clients to configure // envoy as their HTTP proxy. In Unix, for example, this is typically done by setting the - // ``http_proxy`` environment variable. + // “http_proxy“ environment variable. AllowAbsoluteUrl *wrappers.BoolValue `protobuf:"bytes,1,opt,name=allow_absolute_url,json=allowAbsoluteUrl,proto3" json:"allow_absolute_url,omitempty"` // Handle incoming HTTP/1.0 and HTTP 0.9 requests. // This is off by default, and not fully standards compliant. There is support for pre-HTTP/1.1 // style connect logic, dechunking, and handling lack of client host iff - // ``default_host_for_http_10`` is configured. + // “default_host_for_http_10“ is configured. AcceptHttp_10 bool `protobuf:"varint,2,opt,name=accept_http_10,json=acceptHttp10,proto3" json:"accept_http_10,omitempty"` - // A default host for HTTP/1.0 requests. This is highly suggested if ``accept_http_10`` is true as + // A default host for HTTP/1.0 requests. This is highly suggested if “accept_http_10“ is true as // Envoy does not otherwise support HTTP/1.0 without a Host header. - // This is a no-op if ``accept_http_10`` is not true. + // This is a no-op if “accept_http_10“ is not true. DefaultHostForHttp_10 string `protobuf:"bytes,3,opt,name=default_host_for_http_10,json=defaultHostForHttp10,proto3" json:"default_host_for_http_10,omitempty"` // Describes how the keys for response headers should be formatted. By default, all header keys // are lower cased. @@ -644,20 +665,22 @@ type Http1ProtocolOptions struct { // // .. attention:: // - // Note that this only happens when Envoy is chunk encoding which occurs when: - // - The request is HTTP/1.1. - // - Is neither a HEAD only request nor a HTTP Upgrade. - // - Not a response to a HEAD request. - // - The content length header is not present. + // Note that this only happens when Envoy is chunk encoding which occurs when: + // - The request is HTTP/1.1. + // - Is neither a HEAD only request nor a HTTP Upgrade. + // - Not a response to a HEAD request. + // - The content length header is not present. EnableTrailers bool `protobuf:"varint,5,opt,name=enable_trailers,json=enableTrailers,proto3" json:"enable_trailers,omitempty"` - // Allows Envoy to process requests/responses with both ``Content-Length`` and ``Transfer-Encoding`` + // Allows Envoy to process requests/responses with both “Content-Length“ and “Transfer-Encoding“ // headers set. By default such messages are rejected, but if option is enabled - Envoy will // remove Content-Length header and process message. // See `RFC7230, sec. 3.3.3 `_ for details. // // .. attention:: - // Enabling this option might lead to request smuggling vulnerability, especially if traffic - // is proxied via multiple layers of proxies. + // + // Enabling this option might lead to request smuggling vulnerability, especially if traffic + // is proxied via multiple layers of proxies. + // // [#comment:TODO: This field is ignored when the // :ref:`header validation configuration ` // is present.] @@ -919,8 +942,8 @@ type Http2ProtocolOptions struct { // HTTP/2 codec buffers. Once the buffer reaches this pointer, watermark callbacks will fire to // stop the flow of data to the codec buffers. InitialStreamWindowSize *wrappers.UInt32Value `protobuf:"bytes,3,opt,name=initial_stream_window_size,json=initialStreamWindowSize,proto3" json:"initial_stream_window_size,omitempty"` - // Similar to ``initial_stream_window_size``, but for connection-level flow-control - // window. Currently, this has the same minimum/maximum/default as ``initial_stream_window_size``. + // Similar to “initial_stream_window_size“, but for connection-level flow-control + // window. Currently, this has the same minimum/maximum/default as “initial_stream_window_size“. InitialConnectionWindowSize *wrappers.UInt32Value `protobuf:"bytes,4,opt,name=initial_connection_window_size,json=initialConnectionWindowSize,proto3" json:"initial_connection_window_size,omitempty"` // Allows proxying Websocket and other upgrades over H2 connect. AllowConnect bool `protobuf:"varint,5,opt,name=allow_connect,json=allowConnect,proto3" json:"allow_connect,omitempty"` @@ -933,18 +956,18 @@ type Http2ProtocolOptions struct { AllowMetadata bool `protobuf:"varint,6,opt,name=allow_metadata,json=allowMetadata,proto3" json:"allow_metadata,omitempty"` // Limit the number of pending outbound downstream frames of all types (frames that are waiting to // be written into the socket). Exceeding this limit triggers flood mitigation and connection is - // terminated. The ``http2.outbound_flood`` stat tracks the number of terminated connections due + // terminated. The “http2.outbound_flood“ stat tracks the number of terminated connections due // to flood mitigation. The default limit is 10000. MaxOutboundFrames *wrappers.UInt32Value `protobuf:"bytes,7,opt,name=max_outbound_frames,json=maxOutboundFrames,proto3" json:"max_outbound_frames,omitempty"` // Limit the number of pending outbound downstream frames of types PING, SETTINGS and RST_STREAM, // preventing high memory utilization when receiving continuous stream of these frames. Exceeding // this limit triggers flood mitigation and connection is terminated. The - // ``http2.outbound_control_flood`` stat tracks the number of terminated connections due to flood + // “http2.outbound_control_flood“ stat tracks the number of terminated connections due to flood // mitigation. The default limit is 1000. MaxOutboundControlFrames *wrappers.UInt32Value `protobuf:"bytes,8,opt,name=max_outbound_control_frames,json=maxOutboundControlFrames,proto3" json:"max_outbound_control_frames,omitempty"` // Limit the number of consecutive inbound frames of types HEADERS, CONTINUATION and DATA with an // empty payload and no end stream flag. Those frames have no legitimate use and are abusive, but - // might be a result of a broken HTTP/2 implementation. The `http2.inbound_empty_frames_flood`` + // might be a result of a broken HTTP/2 implementation. The `http2.inbound_empty_frames_flood“ // stat tracks the number of connections terminated due to flood mitigation. // Setting this to 0 will terminate connection upon receiving first frame with an empty payload // and no end stream flag. The default limit is 1. @@ -953,25 +976,25 @@ type Http2ProtocolOptions struct { // of PRIORITY frames received over the lifetime of connection exceeds the value calculated // using this formula:: // - // ``max_inbound_priority_frames_per_stream`` * (1 + ``opened_streams``) + // ``max_inbound_priority_frames_per_stream`` * (1 + ``opened_streams``) // - // the connection is terminated. For downstream connections the ``opened_streams`` is incremented when + // the connection is terminated. For downstream connections the “opened_streams“ is incremented when // Envoy receives complete response headers from the upstream server. For upstream connection the - // ``opened_streams`` is incremented when Envoy send the HEADERS frame for a new stream. The - // ``http2.inbound_priority_frames_flood`` stat tracks + // “opened_streams“ is incremented when Envoy send the HEADERS frame for a new stream. The + // “http2.inbound_priority_frames_flood“ stat tracks // the number of connections terminated due to flood mitigation. The default limit is 100. MaxInboundPriorityFramesPerStream *wrappers.UInt32Value `protobuf:"bytes,10,opt,name=max_inbound_priority_frames_per_stream,json=maxInboundPriorityFramesPerStream,proto3" json:"max_inbound_priority_frames_per_stream,omitempty"` // Limit the number of inbound WINDOW_UPDATE frames allowed per DATA frame sent. If the number // of WINDOW_UPDATE frames received over the lifetime of connection exceeds the value calculated // using this formula:: // - // 5 + 2 * (``opened_streams`` + - // ``max_inbound_window_update_frames_per_data_frame_sent`` * ``outbound_data_frames``) + // 5 + 2 * (``opened_streams`` + + // ``max_inbound_window_update_frames_per_data_frame_sent`` * ``outbound_data_frames``) // - // the connection is terminated. For downstream connections the ``opened_streams`` is incremented when + // the connection is terminated. For downstream connections the “opened_streams“ is incremented when // Envoy receives complete response headers from the upstream server. For upstream connections the - // ``opened_streams`` is incremented when Envoy sends the HEADERS frame for a new stream. The - // ``http2.inbound_priority_frames_flood`` stat tracks the number of connections terminated due to + // “opened_streams“ is incremented when Envoy sends the HEADERS frame for a new stream. The + // “http2.inbound_priority_frames_flood“ stat tracks the number of connections terminated due to // flood mitigation. The default max_inbound_window_update_frames_per_data_frame_sent value is 10. // Setting this to 1 should be enough to support HTTP/2 implementations with basic flow control, // but more complex implementations that try to estimate available bandwidth require at least 2. @@ -989,7 +1012,7 @@ type Http2ProtocolOptions struct { // // See `RFC7540, sec. 8.1 `_ for details. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/protocol.proto. StreamErrorOnInvalidHttpMessaging bool `protobuf:"varint,12,opt,name=stream_error_on_invalid_http_messaging,json=streamErrorOnInvalidHttpMessaging,proto3" json:"stream_error_on_invalid_http_messaging,omitempty"` // Allows invalid HTTP messaging and headers. When this option is disabled (default), then // the whole HTTP/2 connection is terminated upon receiving invalid HEADERS frame. However, @@ -1014,11 +1037,11 @@ type Http2ProtocolOptions struct { // // .. code-block:: text // - // ID Field Name - // ---------------- - // 0x1 hpack_table_size - // 0x3 max_concurrent_streams - // 0x4 initial_stream_window_size + // ID Field Name + // ---------------- + // 0x1 hpack_table_size + // 0x3 max_concurrent_streams + // 0x4 initial_stream_window_size // // Collisions will trigger config validation failure on load/update. Likewise, inconsistencies // between custom parameters with the same identifier will trigger a failure. @@ -1145,7 +1168,7 @@ func (x *Http2ProtocolOptions) GetMaxInboundWindowUpdateFramesPerDataFrameSent() return nil } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/config/core/v3/protocol.proto. func (x *Http2ProtocolOptions) GetStreamErrorOnInvalidHttpMessaging() bool { if x != nil { return x.StreamErrorOnInvalidHttpMessaging @@ -1313,6 +1336,7 @@ type SchemeHeaderTransformation struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Transformation: + // // *SchemeHeaderTransformation_SchemeToOverwrite Transformation isSchemeHeaderTransformation_Transformation `protobuf_oneof:"transformation"` } @@ -1447,6 +1471,7 @@ type Http1ProtocolOptions_HeaderKeyFormat struct { unknownFields protoimpl.UnknownFields // Types that are assignable to HeaderFormat: + // // *Http1ProtocolOptions_HeaderKeyFormat_ProperCaseWords_ // *Http1ProtocolOptions_HeaderKeyFormat_StatefulFormatter HeaderFormat isHttp1ProtocolOptions_HeaderKeyFormat_HeaderFormat `protobuf_oneof:"header_format"` @@ -1668,7 +1693,7 @@ var file_envoy_config_core_v3_protocol_proto_rawDesc = []byte{ 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0c, 0xfa, 0x42, 0x09, 0xaa, 0x01, 0x06, 0x22, 0x00, 0x32, 0x02, 0x08, 0x01, 0x52, 0x0f, 0x69, 0x6e, 0x69, - 0x74, 0x69, 0x61, 0x6c, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x22, 0xa8, 0x04, 0x0a, + 0x74, 0x69, 0x61, 0x6c, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x22, 0x93, 0x05, 0x0a, 0x13, 0x51, 0x75, 0x69, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x5b, 0x0a, 0x16, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x18, 0x01, @@ -1703,345 +1728,352 @@ var file_envoy_config_core_v3_protocol_proto_rawDesc = []byte{ 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x51, 0x75, 0x69, 0x63, 0x4b, 0x65, 0x65, 0x70, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x13, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, - 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x22, 0xe4, 0x01, 0x0a, 0x1b, 0x55, 0x70, 0x73, 0x74, - 0x72, 0x65, 0x61, 0x6d, 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, - 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x61, 0x75, 0x74, 0x6f, 0x5f, - 0x73, 0x6e, 0x69, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x61, 0x75, 0x74, 0x6f, 0x53, - 0x6e, 0x69, 0x12, 0x2e, 0x0a, 0x13, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x73, 0x61, 0x6e, 0x5f, 0x76, - 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, - 0x11, 0x61, 0x75, 0x74, 0x6f, 0x53, 0x61, 0x6e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x12, 0x44, 0x0a, 0x18, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x5f, 0x61, - 0x75, 0x74, 0x6f, 0x5f, 0x73, 0x6e, 0x69, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc0, 0x01, 0x01, 0xd0, 0x01, - 0x01, 0x52, 0x15, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x53, - 0x6e, 0x69, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x3a, 0x34, 0x9a, 0xc5, 0x88, 0x1e, 0x2f, 0x0a, - 0x2d, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, - 0x72, 0x65, 0x2e, 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x48, 0x74, 0x74, 0x70, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x86, - 0x04, 0x0a, 0x1e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x63, 0x6f, 0x6c, 0x73, 0x43, 0x61, 0x63, 0x68, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x12, 0x1b, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, - 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x46, - 0x0a, 0x0b, 0x6d, 0x61, 0x78, 0x5f, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, 0x20, 0x00, 0x52, 0x0a, 0x6d, 0x61, 0x78, 0x45, - 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x12, 0x5f, 0x0a, 0x16, 0x6b, 0x65, 0x79, 0x5f, 0x76, 0x61, - 0x6c, 0x75, 0x65, 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x54, 0x79, - 0x70, 0x65, 0x64, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x52, 0x13, 0x6b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x53, 0x74, 0x6f, 0x72, - 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x84, 0x01, 0x0a, 0x14, 0x70, 0x72, 0x65, 0x70, - 0x6f, 0x70, 0x75, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, - 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x51, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, + 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x12, 0x2d, 0x0a, 0x12, 0x63, 0x6f, 0x6e, 0x6e, 0x65, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x06, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x11, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x3a, 0x0a, 0x19, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, + 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x17, 0x63, 0x6c, 0x69, 0x65, 0x6e, + 0x74, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x22, 0xe4, 0x01, 0x0a, 0x1b, 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x48, + 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x73, 0x6e, 0x69, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x61, 0x75, 0x74, 0x6f, 0x53, 0x6e, 0x69, 0x12, 0x2e, 0x0a, + 0x13, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x73, 0x61, 0x6e, 0x5f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x61, 0x75, 0x74, 0x6f, + 0x53, 0x61, 0x6e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x44, 0x0a, + 0x18, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x5f, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x73, + 0x6e, 0x69, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x42, + 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xd0, 0x01, 0x01, 0xc0, 0x01, 0x01, 0x52, 0x15, 0x6f, 0x76, + 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x53, 0x6e, 0x69, 0x48, 0x65, 0x61, + 0x64, 0x65, 0x72, 0x3a, 0x34, 0x9a, 0xc5, 0x88, 0x1e, 0x2f, 0x0a, 0x2d, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x55, 0x70, + 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, + 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x86, 0x04, 0x0a, 0x1e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, - 0x43, 0x61, 0x63, 0x68, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x41, 0x6c, 0x74, - 0x65, 0x72, 0x6e, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, 0x43, - 0x61, 0x63, 0x68, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x13, 0x70, 0x72, 0x65, 0x70, 0x6f, - 0x70, 0x75, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x45, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x12, 0x2d, - 0x0a, 0x12, 0x63, 0x61, 0x6e, 0x6f, 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x73, 0x75, 0x66, 0x66, - 0x69, 0x78, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x09, 0x52, 0x11, 0x63, 0x61, 0x6e, 0x6f, - 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x53, 0x75, 0x66, 0x66, 0x69, 0x78, 0x65, 0x73, 0x1a, 0x68, 0x0a, - 0x1c, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, - 0x6f, 0x6c, 0x73, 0x43, 0x61, 0x63, 0x68, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x27, 0x0a, - 0x08, 0x68, 0x6f, 0x73, 0x74, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, - 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc0, 0x01, 0x01, 0xd0, 0x01, 0x01, 0x52, 0x08, 0x68, 0x6f, - 0x73, 0x74, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0d, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x2a, 0x06, 0x10, 0xff, 0xff, 0x03, 0x20, - 0x00, 0x52, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x22, 0xaf, 0x05, 0x0a, 0x13, 0x48, 0x74, 0x74, 0x70, - 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, - 0x3c, 0x0a, 0x0c, 0x69, 0x64, 0x6c, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x52, 0x0b, 0x69, 0x64, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x51, 0x0a, - 0x17, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, - 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, + 0x43, 0x61, 0x63, 0x68, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x1b, 0x0a, 0x04, + 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, + 0x02, 0x10, 0x01, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x46, 0x0a, 0x0b, 0x6d, 0x61, 0x78, + 0x5f, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x15, 0x6d, 0x61, 0x78, 0x43, 0x6f, - 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x12, 0x51, 0x0a, 0x11, 0x6d, 0x61, 0x78, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x5f, - 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, - 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, - 0x28, 0x01, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x43, 0x6f, - 0x75, 0x6e, 0x74, 0x12, 0x49, 0x0a, 0x13, 0x6d, 0x61, 0x78, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, - 0x6d, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, + 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, + 0x04, 0x2a, 0x02, 0x20, 0x00, 0x52, 0x0a, 0x6d, 0x61, 0x78, 0x45, 0x6e, 0x74, 0x72, 0x69, 0x65, + 0x73, 0x12, 0x5f, 0x0a, 0x16, 0x6b, 0x65, 0x79, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x73, + 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x64, 0x45, 0x78, + 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x13, 0x6b, + 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x43, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x12, 0x84, 0x01, 0x0a, 0x14, 0x70, 0x72, 0x65, 0x70, 0x6f, 0x70, 0x75, 0x6c, 0x61, + 0x74, 0x65, 0x64, 0x5f, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x51, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, + 0x74, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, 0x43, 0x61, 0x63, 0x68, 0x65, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, + 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, 0x43, 0x61, 0x63, 0x68, 0x65, 0x45, + 0x6e, 0x74, 0x72, 0x79, 0x52, 0x13, 0x70, 0x72, 0x65, 0x70, 0x6f, 0x70, 0x75, 0x6c, 0x61, 0x74, + 0x65, 0x64, 0x45, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x63, 0x61, 0x6e, + 0x6f, 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x73, 0x75, 0x66, 0x66, 0x69, 0x78, 0x65, 0x73, 0x18, + 0x05, 0x20, 0x03, 0x28, 0x09, 0x52, 0x11, 0x63, 0x61, 0x6e, 0x6f, 0x6e, 0x69, 0x63, 0x61, 0x6c, + 0x53, 0x75, 0x66, 0x66, 0x69, 0x78, 0x65, 0x73, 0x1a, 0x68, 0x0a, 0x1c, 0x41, 0x6c, 0x74, 0x65, + 0x72, 0x6e, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x73, 0x43, 0x61, + 0x63, 0x68, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x27, 0x0a, 0x08, 0x68, 0x6f, 0x73, 0x74, + 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, + 0x06, 0xd0, 0x01, 0x01, 0xc0, 0x01, 0x01, 0x52, 0x08, 0x68, 0x6f, 0x73, 0x74, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x1f, 0x0a, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x42, + 0x0b, 0xfa, 0x42, 0x08, 0x2a, 0x06, 0x10, 0xff, 0xff, 0x03, 0x20, 0x00, 0x52, 0x04, 0x70, 0x6f, + 0x72, 0x74, 0x22, 0xaf, 0x05, 0x0a, 0x13, 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x3c, 0x0a, 0x0c, 0x69, 0x64, + 0x6c, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x11, 0x6d, 0x61, 0x78, - 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x8d, - 0x01, 0x0a, 0x1f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x5f, - 0x75, 0x6e, 0x64, 0x65, 0x72, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x73, 0x5f, 0x61, 0x63, 0x74, 0x69, - 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x46, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, - 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x57, 0x69, 0x74, 0x68, 0x55, - 0x6e, 0x64, 0x65, 0x72, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x73, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, - 0x52, 0x1c, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x57, 0x69, 0x74, 0x68, 0x55, 0x6e, 0x64, - 0x65, 0x72, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x73, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x5b, - 0x0a, 0x1b, 0x6d, 0x61, 0x78, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x5f, 0x70, - 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x18, 0x6d, 0x61, 0x78, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x50, 0x65, - 0x72, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x4e, 0x0a, 0x1c, 0x48, + 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x69, 0x64, 0x6c, + 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x51, 0x0a, 0x17, 0x6d, 0x61, 0x78, 0x5f, + 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x15, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x69, 0x6f, 0x6e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x51, 0x0a, 0x11, 0x6d, + 0x61, 0x78, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, + 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, 0x28, 0x01, 0x52, 0x0f, 0x6d, + 0x61, 0x78, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x49, + 0x0a, 0x13, 0x6d, 0x61, 0x78, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x64, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, + 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x11, 0x6d, 0x61, 0x78, 0x53, 0x74, 0x72, 0x65, 0x61, + 0x6d, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x8d, 0x01, 0x0a, 0x1f, 0x68, 0x65, + 0x61, 0x64, 0x65, 0x72, 0x73, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x5f, 0x75, 0x6e, 0x64, 0x65, 0x72, + 0x73, 0x63, 0x6f, 0x72, 0x65, 0x73, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, + 0x01, 0x28, 0x0e, 0x32, 0x46, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x57, 0x69, 0x74, 0x68, 0x55, 0x6e, 0x64, 0x65, 0x72, 0x73, - 0x63, 0x6f, 0x72, 0x65, 0x73, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x09, 0x0a, 0x05, 0x41, - 0x4c, 0x4c, 0x4f, 0x57, 0x10, 0x00, 0x12, 0x12, 0x0a, 0x0e, 0x52, 0x45, 0x4a, 0x45, 0x43, 0x54, - 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x44, 0x52, - 0x4f, 0x50, 0x5f, 0x48, 0x45, 0x41, 0x44, 0x45, 0x52, 0x10, 0x02, 0x3a, 0x2c, 0x9a, 0xc5, 0x88, - 0x1e, 0x27, 0x0a, 0x25, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, - 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, - 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x93, 0x09, 0x0a, 0x14, 0x48, 0x74, - 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, - 0x6e, 0x73, 0x12, 0x48, 0x0a, 0x12, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x61, 0x62, 0x73, 0x6f, - 0x6c, 0x75, 0x74, 0x65, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x63, 0x6f, 0x72, 0x65, 0x73, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x1c, 0x68, 0x65, 0x61, + 0x64, 0x65, 0x72, 0x73, 0x57, 0x69, 0x74, 0x68, 0x55, 0x6e, 0x64, 0x65, 0x72, 0x73, 0x63, 0x6f, + 0x72, 0x65, 0x73, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x5b, 0x0a, 0x1b, 0x6d, 0x61, 0x78, + 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x10, 0x61, 0x6c, 0x6c, 0x6f, - 0x77, 0x41, 0x62, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x65, 0x55, 0x72, 0x6c, 0x12, 0x24, 0x0a, 0x0e, - 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x31, 0x30, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x48, 0x74, 0x74, 0x70, - 0x31, 0x30, 0x12, 0x36, 0x0a, 0x18, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x68, 0x6f, - 0x73, 0x74, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x31, 0x30, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x14, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x48, 0x6f, 0x73, - 0x74, 0x46, 0x6f, 0x72, 0x48, 0x74, 0x74, 0x70, 0x31, 0x30, 0x12, 0x66, 0x0a, 0x11, 0x68, 0x65, - 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, - 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, - 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, 0x61, - 0x74, 0x52, 0x0f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, - 0x61, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x74, 0x72, 0x61, - 0x69, 0x6c, 0x65, 0x72, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x65, 0x6e, 0x61, - 0x62, 0x6c, 0x65, 0x54, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x61, - 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x65, 0x64, 0x5f, 0x6c, 0x65, 0x6e, - 0x67, 0x74, 0x68, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x12, 0x61, 0x6c, 0x6c, 0x6f, 0x77, - 0x43, 0x68, 0x75, 0x6e, 0x6b, 0x65, 0x64, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x12, 0x7a, 0x0a, - 0x2d, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, - 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, - 0x64, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x07, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x27, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, - 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4f, 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, 0x74, - 0x74, 0x70, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x73, 0x65, 0x6e, - 0x64, 0x5f, 0x66, 0x75, 0x6c, 0x6c, 0x79, 0x5f, 0x71, 0x75, 0x61, 0x6c, 0x69, 0x66, 0x69, 0x65, - 0x64, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x15, 0x73, 0x65, 0x6e, - 0x64, 0x46, 0x75, 0x6c, 0x6c, 0x79, 0x51, 0x75, 0x61, 0x6c, 0x69, 0x66, 0x69, 0x65, 0x64, 0x55, - 0x72, 0x6c, 0x12, 0x4e, 0x0a, 0x10, 0x75, 0x73, 0x65, 0x5f, 0x62, 0x61, 0x6c, 0x73, 0x61, 0x5f, - 0x70, 0x61, 0x72, 0x73, 0x65, 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, - 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, - 0x08, 0x01, 0x52, 0x0e, 0x75, 0x73, 0x65, 0x42, 0x61, 0x6c, 0x73, 0x61, 0x50, 0x61, 0x72, 0x73, - 0x65, 0x72, 0x12, 0x3a, 0x0a, 0x14, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x75, 0x73, 0x74, - 0x6f, 0x6d, 0x5f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x08, - 0x42, 0x08, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, 0x01, 0x52, 0x12, 0x61, 0x6c, 0x6c, 0x6f, - 0x77, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x1a, 0x9f, - 0x03, 0x0a, 0x0f, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, - 0x61, 0x74, 0x12, 0x78, 0x0a, 0x11, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x5f, 0x63, 0x61, 0x73, - 0x65, 0x5f, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x4a, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, - 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, - 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, - 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, - 0x43, 0x61, 0x73, 0x65, 0x57, 0x6f, 0x72, 0x64, 0x73, 0x48, 0x00, 0x52, 0x0f, 0x70, 0x72, 0x6f, - 0x70, 0x65, 0x72, 0x43, 0x61, 0x73, 0x65, 0x57, 0x6f, 0x72, 0x64, 0x73, 0x12, 0x5b, 0x0a, 0x12, - 0x73, 0x74, 0x61, 0x74, 0x65, 0x66, 0x75, 0x6c, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x74, - 0x65, 0x72, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x18, 0x6d, 0x61, + 0x78, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x50, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x4e, 0x0a, 0x1c, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, + 0x73, 0x57, 0x69, 0x74, 0x68, 0x55, 0x6e, 0x64, 0x65, 0x72, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x73, + 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x09, 0x0a, 0x05, 0x41, 0x4c, 0x4c, 0x4f, 0x57, 0x10, + 0x00, 0x12, 0x12, 0x0a, 0x0e, 0x52, 0x45, 0x4a, 0x45, 0x43, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, + 0x45, 0x53, 0x54, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x44, 0x52, 0x4f, 0x50, 0x5f, 0x48, 0x45, + 0x41, 0x44, 0x45, 0x52, 0x10, 0x02, 0x3a, 0x2c, 0x9a, 0xc5, 0x88, 0x1e, 0x27, 0x0a, 0x25, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, + 0x2e, 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x93, 0x09, 0x0a, 0x14, 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x48, 0x0a, + 0x12, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x61, 0x62, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x65, 0x5f, + 0x75, 0x72, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, + 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x10, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x41, 0x62, 0x73, 0x6f, + 0x6c, 0x75, 0x74, 0x65, 0x55, 0x72, 0x6c, 0x12, 0x24, 0x0a, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70, + 0x74, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x31, 0x30, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x0c, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x48, 0x74, 0x74, 0x70, 0x31, 0x30, 0x12, 0x36, 0x0a, + 0x18, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x5f, 0x66, 0x6f, + 0x72, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x31, 0x30, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x14, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x48, 0x6f, 0x73, 0x74, 0x46, 0x6f, 0x72, 0x48, + 0x74, 0x74, 0x70, 0x31, 0x30, 0x12, 0x66, 0x0a, 0x11, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, + 0x6b, 0x65, 0x79, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x3a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, + 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, + 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x52, 0x0f, 0x68, 0x65, + 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x27, 0x0a, + 0x0f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x73, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x54, 0x72, + 0x61, 0x69, 0x6c, 0x65, 0x72, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, + 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x65, 0x64, 0x5f, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x18, 0x06, + 0x20, 0x01, 0x28, 0x08, 0x52, 0x12, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x43, 0x68, 0x75, 0x6e, 0x6b, + 0x65, 0x64, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x12, 0x7a, 0x0a, 0x2d, 0x6f, 0x76, 0x65, 0x72, + 0x72, 0x69, 0x64, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x65, 0x72, 0x72, 0x6f, + 0x72, 0x5f, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x68, 0x74, 0x74, + 0x70, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x27, 0x6f, 0x76, 0x65, + 0x72, 0x72, 0x69, 0x64, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x45, 0x72, 0x72, 0x6f, 0x72, + 0x4f, 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, 0x74, 0x74, 0x70, 0x4d, 0x65, 0x73, + 0x73, 0x61, 0x67, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x75, 0x6c, + 0x6c, 0x79, 0x5f, 0x71, 0x75, 0x61, 0x6c, 0x69, 0x66, 0x69, 0x65, 0x64, 0x5f, 0x75, 0x72, 0x6c, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x15, 0x73, 0x65, 0x6e, 0x64, 0x46, 0x75, 0x6c, 0x6c, + 0x79, 0x51, 0x75, 0x61, 0x6c, 0x69, 0x66, 0x69, 0x65, 0x64, 0x55, 0x72, 0x6c, 0x12, 0x4e, 0x0a, + 0x10, 0x75, 0x73, 0x65, 0x5f, 0x62, 0x61, 0x6c, 0x73, 0x61, 0x5f, 0x70, 0x61, 0x72, 0x73, 0x65, + 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, + 0x6c, 0x75, 0x65, 0x42, 0x08, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, 0x01, 0x52, 0x0e, 0x75, + 0x73, 0x65, 0x42, 0x61, 0x6c, 0x73, 0x61, 0x50, 0x61, 0x72, 0x73, 0x65, 0x72, 0x12, 0x3a, 0x0a, + 0x14, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x6d, 0x65, + 0x74, 0x68, 0x6f, 0x64, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x08, 0x42, 0x08, 0xd2, 0xc6, 0xa4, + 0xe1, 0x06, 0x02, 0x08, 0x01, 0x52, 0x12, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x43, 0x75, 0x73, 0x74, + 0x6f, 0x6d, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x1a, 0x9f, 0x03, 0x0a, 0x0f, 0x48, 0x65, + 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x78, 0x0a, + 0x11, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x5f, 0x63, 0x61, 0x73, 0x65, 0x5f, 0x77, 0x6f, 0x72, + 0x64, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x4a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, - 0x54, 0x79, 0x70, 0x65, 0x64, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x43, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x48, 0x00, 0x52, 0x11, 0x73, 0x74, 0x61, 0x74, 0x65, 0x66, 0x75, 0x6c, - 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x1a, 0x60, 0x0a, 0x0f, 0x50, 0x72, 0x6f, - 0x70, 0x65, 0x72, 0x43, 0x61, 0x73, 0x65, 0x57, 0x6f, 0x72, 0x64, 0x73, 0x3a, 0x4d, 0x9a, 0xc5, - 0x88, 0x1e, 0x48, 0x0a, 0x46, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, - 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, - 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x70, - 0x65, 0x72, 0x43, 0x61, 0x73, 0x65, 0x57, 0x6f, 0x72, 0x64, 0x73, 0x3a, 0x3d, 0x9a, 0xc5, 0x88, - 0x1e, 0x38, 0x0a, 0x36, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, + 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, + 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x43, 0x61, 0x73, 0x65, 0x57, + 0x6f, 0x72, 0x64, 0x73, 0x48, 0x00, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x43, 0x61, + 0x73, 0x65, 0x57, 0x6f, 0x72, 0x64, 0x73, 0x12, 0x5b, 0x0a, 0x12, 0x73, 0x74, 0x61, 0x74, 0x65, + 0x66, 0x75, 0x6c, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x18, 0x08, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x64, + 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x48, + 0x00, 0x52, 0x11, 0x73, 0x74, 0x61, 0x74, 0x65, 0x66, 0x75, 0x6c, 0x46, 0x6f, 0x72, 0x6d, 0x61, + 0x74, 0x74, 0x65, 0x72, 0x1a, 0x60, 0x0a, 0x0f, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x43, 0x61, + 0x73, 0x65, 0x57, 0x6f, 0x72, 0x64, 0x73, 0x3a, 0x4d, 0x9a, 0xc5, 0x88, 0x1e, 0x48, 0x0a, 0x46, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, + 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x43, 0x61, 0x73, + 0x65, 0x57, 0x6f, 0x72, 0x64, 0x73, 0x3a, 0x3d, 0x9a, 0xc5, 0x88, 0x1e, 0x38, 0x0a, 0x36, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, + 0x2e, 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x46, + 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x42, 0x14, 0x0a, 0x0d, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, + 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x3a, 0x2d, 0x9a, 0xc5, 0x88, + 0x1e, 0x28, 0x0a, 0x26, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x31, 0x50, 0x72, 0x6f, 0x74, 0x6f, - 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, - 0x72, 0x4b, 0x65, 0x79, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x42, 0x14, 0x0a, 0x0d, 0x68, 0x65, - 0x61, 0x64, 0x65, 0x72, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x03, 0xf8, 0x42, 0x01, - 0x3a, 0x2d, 0x9a, 0xc5, 0x88, 0x1e, 0x28, 0x0a, 0x26, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, - 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x31, - 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, - 0xc1, 0x02, 0x0a, 0x11, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x53, 0x65, 0x74, - 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x43, 0x0a, 0x08, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, - 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x42, 0x0c, 0xfa, 0x42, 0x09, 0xaa, 0x01, 0x06, 0x32, 0x04, 0x10, 0xc0, 0x84, 0x3d, - 0x52, 0x08, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x43, 0x0a, 0x07, 0x74, 0x69, - 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, - 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0e, 0xfa, 0x42, 0x0b, 0xaa, 0x01, 0x08, 0x08, 0x01, - 0x32, 0x04, 0x10, 0xc0, 0x84, 0x3d, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, - 0x3f, 0x0a, 0x0f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x5f, 0x6a, 0x69, 0x74, 0x74, - 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, - 0x52, 0x0e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x4a, 0x69, 0x74, 0x74, 0x65, 0x72, - 0x12, 0x61, 0x0a, 0x18, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, - 0x64, 0x6c, 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x04, 0x20, 0x01, + 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xc1, 0x02, 0x0a, 0x11, 0x4b, + 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, + 0x12, 0x43, 0x0a, 0x08, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0c, 0xfa, - 0x42, 0x09, 0xaa, 0x01, 0x06, 0x32, 0x04, 0x10, 0xc0, 0x84, 0x3d, 0x52, 0x16, 0x63, 0x6f, 0x6e, - 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x6c, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, - 0x76, 0x61, 0x6c, 0x22, 0xd3, 0x0e, 0x0a, 0x14, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, - 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x46, 0x0a, 0x10, - 0x68, 0x70, 0x61, 0x63, 0x6b, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x42, 0x09, 0xaa, 0x01, 0x06, 0x32, 0x04, 0x10, 0xc0, 0x84, 0x3d, 0x52, 0x08, 0x69, 0x6e, 0x74, + 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x43, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x42, 0x0e, 0xfa, 0x42, 0x0b, 0xaa, 0x01, 0x08, 0x08, 0x01, 0x32, 0x04, 0x10, 0xc0, 0x84, + 0x3d, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x3f, 0x0a, 0x0f, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x5f, 0x6a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, + 0x2e, 0x76, 0x33, 0x2e, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x52, 0x0e, 0x69, 0x6e, 0x74, + 0x65, 0x72, 0x76, 0x61, 0x6c, 0x4a, 0x69, 0x74, 0x74, 0x65, 0x72, 0x12, 0x61, 0x0a, 0x18, 0x63, + 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x6c, 0x65, 0x5f, 0x69, + 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0c, 0xfa, 0x42, 0x09, 0xaa, 0x01, 0x06, + 0x32, 0x04, 0x10, 0xc0, 0x84, 0x3d, 0x52, 0x16, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, + 0x6f, 0x6e, 0x49, 0x64, 0x6c, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x22, 0xd0, + 0x0e, 0x0a, 0x14, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x46, 0x0a, 0x10, 0x68, 0x70, 0x61, 0x63, 0x6b, + 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, + 0x0e, 0x68, 0x70, 0x61, 0x63, 0x6b, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, + 0x61, 0x0a, 0x16, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, + 0x74, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0d, 0xfa, + 0x42, 0x0a, 0x2a, 0x08, 0x18, 0xff, 0xff, 0xff, 0xff, 0x07, 0x28, 0x01, 0x52, 0x14, 0x6d, 0x61, + 0x78, 0x43, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, + 0x6d, 0x73, 0x12, 0x6a, 0x0a, 0x1a, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x73, 0x74, + 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x5f, 0x73, 0x69, 0x7a, 0x65, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0e, 0x68, 0x70, 0x61, 0x63, 0x6b, 0x54, 0x61, 0x62, 0x6c, 0x65, - 0x53, 0x69, 0x7a, 0x65, 0x12, 0x61, 0x0a, 0x16, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x63, - 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x42, 0x0d, 0xfa, 0x42, 0x0a, 0x2a, 0x08, 0x18, 0xff, 0xff, 0xff, 0xff, 0x07, 0x28, - 0x01, 0x52, 0x14, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, - 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x12, 0x6a, 0x0a, 0x1a, 0x69, 0x6e, 0x69, 0x74, 0x69, - 0x61, 0x6c, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, - 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, - 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0f, 0xfa, 0x42, 0x0c, 0x2a, 0x0a, - 0x18, 0xff, 0xff, 0xff, 0xff, 0x07, 0x28, 0xff, 0xff, 0x03, 0x52, 0x17, 0x69, 0x6e, 0x69, 0x74, - 0x69, 0x61, 0x6c, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x53, - 0x69, 0x7a, 0x65, 0x12, 0x72, 0x0a, 0x1e, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x63, - 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, - 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, + 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0f, 0xfa, 0x42, 0x0c, 0x2a, 0x0a, 0x18, 0xff, 0xff, 0xff, 0xff, + 0x07, 0x28, 0xff, 0xff, 0x03, 0x52, 0x17, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x53, 0x74, + 0x72, 0x65, 0x61, 0x6d, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x72, + 0x0a, 0x1e, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, + 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x5f, 0x73, 0x69, 0x7a, 0x65, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, + 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0f, 0xfa, 0x42, 0x0c, 0x2a, 0x0a, 0x18, 0xff, 0xff, 0xff, 0xff, + 0x07, 0x28, 0xff, 0xff, 0x03, 0x52, 0x1b, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x43, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x53, 0x69, + 0x7a, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, + 0x65, 0x63, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x61, 0x6c, 0x6c, 0x6f, 0x77, + 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x6c, 0x6c, 0x6f, 0x77, + 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x0d, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x55, + 0x0a, 0x13, 0x6d, 0x61, 0x78, 0x5f, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x66, + 0x72, 0x61, 0x6d, 0x65, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, - 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0f, 0xfa, 0x42, 0x0c, 0x2a, 0x0a, - 0x18, 0xff, 0xff, 0xff, 0xff, 0x07, 0x28, 0xff, 0xff, 0x03, 0x52, 0x1b, 0x69, 0x6e, 0x69, 0x74, - 0x69, 0x61, 0x6c, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x57, 0x69, 0x6e, - 0x64, 0x6f, 0x77, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x61, 0x6c, 0x6c, 0x6f, 0x77, - 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, - 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x12, 0x25, 0x0a, 0x0e, - 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x06, - 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x4d, 0x65, 0x74, 0x61, 0x64, - 0x61, 0x74, 0x61, 0x12, 0x55, 0x0a, 0x13, 0x6d, 0x61, 0x78, 0x5f, 0x6f, 0x75, 0x74, 0x62, 0x6f, - 0x75, 0x6e, 0x64, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, - 0xfa, 0x42, 0x04, 0x2a, 0x02, 0x28, 0x01, 0x52, 0x11, 0x6d, 0x61, 0x78, 0x4f, 0x75, 0x74, 0x62, - 0x6f, 0x75, 0x6e, 0x64, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x12, 0x64, 0x0a, 0x1b, 0x6d, 0x61, - 0x78, 0x5f, 0x6f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, - 0x6f, 0x6c, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, - 0x42, 0x04, 0x2a, 0x02, 0x28, 0x01, 0x52, 0x18, 0x6d, 0x61, 0x78, 0x4f, 0x75, 0x74, 0x62, 0x6f, - 0x75, 0x6e, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, - 0x12, 0x84, 0x01, 0x0a, 0x31, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x75, - 0x74, 0x69, 0x76, 0x65, 0x5f, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x66, 0x72, 0x61, - 0x6d, 0x65, 0x73, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x5f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x5f, 0x70, - 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, - 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x2b, 0x6d, 0x61, 0x78, 0x43, - 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x75, 0x74, 0x69, 0x76, 0x65, 0x49, 0x6e, 0x62, 0x6f, 0x75, 0x6e, - 0x64, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x57, 0x69, 0x74, 0x68, 0x45, 0x6d, 0x70, 0x74, 0x79, - 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x6f, 0x0a, 0x26, 0x6d, 0x61, 0x78, 0x5f, 0x69, - 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x5f, - 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, - 0x6d, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x21, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x62, 0x6f, 0x75, 0x6e, - 0x64, 0x50, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x50, - 0x65, 0x72, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x91, 0x01, 0x0a, 0x34, 0x6d, 0x61, 0x78, - 0x5f, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x5f, - 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x5f, 0x70, 0x65, - 0x72, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x5f, 0x73, 0x65, 0x6e, - 0x74, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, 0x28, 0x01, 0x52, 0x2c, - 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, - 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x50, 0x65, 0x72, 0x44, - 0x61, 0x74, 0x61, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x53, 0x65, 0x6e, 0x74, 0x12, 0x5e, 0x0a, 0x26, - 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6f, 0x6e, 0x5f, - 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6d, 0x65, 0x73, - 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x08, 0x42, 0x0b, 0x18, 0x01, - 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x52, 0x21, 0x73, 0x74, 0x72, 0x65, 0x61, - 0x6d, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4f, 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, - 0x74, 0x74, 0x70, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x12, 0x7a, 0x0a, 0x2d, - 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, - 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, - 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x0e, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x27, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x45, - 0x72, 0x72, 0x6f, 0x72, 0x4f, 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, 0x74, 0x74, - 0x70, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x7a, 0x0a, 0x1a, 0x63, 0x75, 0x73, 0x74, - 0x6f, 0x6d, 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x5f, 0x70, 0x61, 0x72, 0x61, - 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3c, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, - 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, - 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, - 0x73, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x52, 0x18, 0x63, 0x75, 0x73, 0x74, - 0x6f, 0x6d, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, - 0x74, 0x65, 0x72, 0x73, 0x12, 0x5a, 0x0a, 0x14, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, - 0x6f, 0x6e, 0x5f, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x18, 0x0f, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, - 0x69, 0x76, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x13, 0x63, 0x6f, 0x6e, - 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, - 0x12, 0x50, 0x0a, 0x11, 0x75, 0x73, 0x65, 0x5f, 0x6f, 0x67, 0x68, 0x74, 0x74, 0x70, 0x32, 0x5f, - 0x63, 0x6f, 0x64, 0x65, 0x63, 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, - 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, - 0x01, 0x52, 0x0f, 0x75, 0x73, 0x65, 0x4f, 0x67, 0x68, 0x74, 0x74, 0x70, 0x32, 0x43, 0x6f, 0x64, - 0x65, 0x63, 0x1a, 0xe5, 0x01, 0x0a, 0x11, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x50, - 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x12, 0x51, 0x0a, 0x0a, 0x69, 0x64, 0x65, 0x6e, - 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, - 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x13, 0xfa, 0x42, 0x08, 0x2a, - 0x06, 0x18, 0xff, 0xff, 0x03, 0x28, 0x00, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, - 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x3c, 0x0a, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, + 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, + 0x28, 0x01, 0x52, 0x11, 0x6d, 0x61, 0x78, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x46, + 0x72, 0x61, 0x6d, 0x65, 0x73, 0x12, 0x64, 0x0a, 0x1b, 0x6d, 0x61, 0x78, 0x5f, 0x6f, 0x75, 0x74, + 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x5f, 0x66, 0x72, + 0x61, 0x6d, 0x65, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, - 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, - 0x10, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x3f, 0x9a, 0xc5, 0x88, 0x1e, 0x3a, - 0x0a, 0x38, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, - 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, - 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, - 0x73, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x3a, 0x2d, 0x9a, 0xc5, 0x88, 0x1e, - 0x28, 0x0a, 0x26, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, - 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, - 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xa5, 0x01, 0x0a, 0x13, 0x47, 0x72, - 0x70, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x12, 0x60, 0x0a, 0x16, 0x68, 0x74, 0x74, 0x70, 0x32, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x63, 0x6f, 0x6c, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, - 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x14, 0x68, + 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, 0x28, + 0x01, 0x52, 0x18, 0x6d, 0x61, 0x78, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x43, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x12, 0x84, 0x01, 0x0a, 0x31, + 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x75, 0x74, 0x69, 0x76, 0x65, 0x5f, + 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x5f, 0x77, + 0x69, 0x74, 0x68, 0x5f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x5f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, + 0x64, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, + 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x2b, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x63, + 0x75, 0x74, 0x69, 0x76, 0x65, 0x49, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x46, 0x72, 0x61, 0x6d, + 0x65, 0x73, 0x57, 0x69, 0x74, 0x68, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x50, 0x61, 0x79, 0x6c, 0x6f, + 0x61, 0x64, 0x12, 0x6f, 0x0a, 0x26, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x6e, 0x62, 0x6f, 0x75, 0x6e, + 0x64, 0x5f, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, + 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x18, 0x0a, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x52, 0x21, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x50, 0x72, 0x69, 0x6f, + 0x72, 0x69, 0x74, 0x79, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x50, 0x65, 0x72, 0x53, 0x74, 0x72, + 0x65, 0x61, 0x6d, 0x12, 0x91, 0x01, 0x0a, 0x34, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x6e, 0x62, 0x6f, + 0x75, 0x6e, 0x64, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x64, 0x61, 0x74, + 0x61, 0x5f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x5f, 0x73, 0x65, 0x6e, 0x74, 0x18, 0x0b, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x42, 0x07, 0xfa, 0x42, 0x04, 0x2a, 0x02, 0x28, 0x01, 0x52, 0x2c, 0x6d, 0x61, 0x78, 0x49, 0x6e, + 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x55, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x46, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x50, 0x65, 0x72, 0x44, 0x61, 0x74, 0x61, 0x46, 0x72, + 0x61, 0x6d, 0x65, 0x53, 0x65, 0x6e, 0x74, 0x12, 0x5e, 0x0a, 0x26, 0x73, 0x74, 0x72, 0x65, 0x61, + 0x6d, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x76, 0x61, 0x6c, + 0x69, 0x64, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, + 0x67, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x08, 0x42, 0x0b, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, + 0x2e, 0x30, 0x18, 0x01, 0x52, 0x21, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x45, 0x72, 0x72, 0x6f, + 0x72, 0x4f, 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, 0x74, 0x74, 0x70, 0x4d, 0x65, + 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x12, 0x7a, 0x0a, 0x2d, 0x6f, 0x76, 0x65, 0x72, 0x72, + 0x69, 0x64, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, + 0x5f, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x68, 0x74, 0x74, 0x70, + 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x27, 0x6f, 0x76, 0x65, 0x72, + 0x72, 0x69, 0x64, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4f, + 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, 0x74, 0x74, 0x70, 0x4d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x12, 0x7a, 0x0a, 0x1a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x73, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, + 0x73, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3c, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x3a, 0x2c, 0x9a, 0xc5, 0x88, 0x1e, 0x27, 0x0a, 0x25, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x47, 0x72, - 0x70, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x22, 0xb1, 0x02, 0x0a, 0x14, 0x48, 0x74, 0x74, 0x70, 0x33, 0x50, 0x72, 0x6f, 0x74, 0x6f, - 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x5d, 0x0a, 0x15, 0x71, 0x75, - 0x69, 0x63, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x5f, 0x6f, 0x70, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x6f, 0x6e, 0x73, 0x2e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x50, 0x61, 0x72, 0x61, + 0x6d, 0x65, 0x74, 0x65, 0x72, 0x52, 0x18, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x53, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x73, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x12, + 0x5a, 0x0a, 0x14, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6b, 0x65, + 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, + 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x53, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x13, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, + 0x6f, 0x6e, 0x4b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x12, 0x50, 0x0a, 0x11, 0x75, + 0x73, 0x65, 0x5f, 0x6f, 0x67, 0x68, 0x74, 0x74, 0x70, 0x32, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x63, + 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x42, 0x08, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, 0x01, 0x52, 0x0f, 0x75, 0x73, + 0x65, 0x4f, 0x67, 0x68, 0x74, 0x74, 0x70, 0x32, 0x43, 0x6f, 0x64, 0x65, 0x63, 0x1a, 0xe2, 0x01, + 0x0a, 0x11, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, + 0x74, 0x65, 0x72, 0x12, 0x4e, 0x0a, 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, + 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, + 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x10, 0xfa, 0x42, 0x0d, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x2a, + 0x06, 0x18, 0xff, 0xff, 0x03, 0x28, 0x00, 0x52, 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, + 0x69, 0x65, 0x72, 0x12, 0x3c, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x3a, 0x3f, 0x9a, 0xc5, 0x88, 0x1e, 0x3a, 0x0a, 0x38, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, 0x70, + 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, + 0x65, 0x72, 0x3a, 0x2d, 0x9a, 0xc5, 0x88, 0x1e, 0x28, 0x0a, 0x26, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x48, 0x74, 0x74, + 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x22, 0xa5, 0x01, 0x0a, 0x13, 0x47, 0x72, 0x70, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, + 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x60, 0x0a, 0x16, 0x68, 0x74, 0x74, + 0x70, 0x32, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x5f, 0x6f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, - 0x2e, 0x51, 0x75, 0x69, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, - 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x13, 0x71, 0x75, 0x69, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, - 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x7a, 0x0a, 0x2d, 0x6f, 0x76, 0x65, - 0x72, 0x72, 0x69, 0x64, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x65, 0x72, 0x72, - 0x6f, 0x72, 0x5f, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x68, 0x74, - 0x74, 0x70, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x27, 0x6f, 0x76, - 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x45, 0x72, 0x72, 0x6f, - 0x72, 0x4f, 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x48, 0x74, 0x74, 0x70, 0x4d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x3e, 0x0a, 0x16, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x65, - 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x08, 0x42, 0x08, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, 0x01, 0x52, - 0x14, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x43, 0x6f, - 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x22, 0x74, 0x0a, 0x1a, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x65, 0x48, - 0x65, 0x61, 0x64, 0x65, 0x72, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x12, 0x44, 0x0a, 0x13, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x65, 0x5f, 0x74, 0x6f, - 0x5f, 0x6f, 0x76, 0x65, 0x72, 0x77, 0x72, 0x69, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x42, 0x12, 0xfa, 0x42, 0x0f, 0x72, 0x0d, 0x52, 0x04, 0x68, 0x74, 0x74, 0x70, 0x52, 0x05, 0x68, - 0x74, 0x74, 0x70, 0x73, 0x48, 0x00, 0x52, 0x11, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x65, 0x54, 0x6f, - 0x4f, 0x76, 0x65, 0x72, 0x77, 0x72, 0x69, 0x74, 0x65, 0x42, 0x10, 0x0a, 0x0e, 0x74, 0x72, 0x61, - 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x81, 0x01, 0x0a, 0x22, + 0x2e, 0x48, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x14, 0x68, 0x74, 0x74, 0x70, 0x32, 0x50, 0x72, 0x6f, 0x74, + 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x2c, 0x9a, 0xc5, 0x88, + 0x1e, 0x27, 0x0a, 0x25, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, + 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x47, 0x72, 0x70, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, + 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xb1, 0x02, 0x0a, 0x14, 0x48, 0x74, + 0x74, 0x70, 0x33, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x12, 0x5d, 0x0a, 0x15, 0x71, 0x75, 0x69, 0x63, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x63, 0x6f, 0x6c, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x29, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x51, 0x75, 0x69, 0x63, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x13, 0x71, 0x75, + 0x69, 0x63, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x12, 0x7a, 0x0a, 0x2d, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x5f, 0x73, 0x74, + 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, + 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, + 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, + 0x61, 0x6c, 0x75, 0x65, 0x52, 0x27, 0x6f, 0x76, 0x65, 0x72, 0x72, 0x69, 0x64, 0x65, 0x53, 0x74, + 0x72, 0x65, 0x61, 0x6d, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4f, 0x6e, 0x49, 0x6e, 0x76, 0x61, 0x6c, + 0x69, 0x64, 0x48, 0x74, 0x74, 0x70, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x3e, 0x0a, + 0x16, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x5f, + 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x42, 0x08, 0xd2, + 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, 0x01, 0x52, 0x14, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x45, 0x78, + 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x22, 0x74, 0x0a, + 0x1a, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x65, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x54, 0x72, 0x61, + 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x44, 0x0a, 0x13, 0x73, + 0x63, 0x68, 0x65, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x6f, 0x76, 0x65, 0x72, 0x77, 0x72, 0x69, + 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x12, 0xfa, 0x42, 0x0f, 0x72, 0x0d, 0x52, + 0x04, 0x68, 0x74, 0x74, 0x70, 0x52, 0x05, 0x68, 0x74, 0x74, 0x70, 0x73, 0x48, 0x00, 0x52, 0x11, + 0x73, 0x63, 0x68, 0x65, 0x6d, 0x65, 0x54, 0x6f, 0x4f, 0x76, 0x65, 0x72, 0x77, 0x72, 0x69, 0x74, + 0x65, 0x42, 0x10, 0x0a, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x42, 0x81, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0d, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x50, 0x72, 0x6f, 0x74, @@ -2049,8 +2081,7 @@ var file_envoy_config_core_v3_protocol_proto_rawDesc = []byte{ 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, - 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, - 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.validate.go index 9e9a9155e..feb1489c2 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.validate.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/protocol.pb.validate.go @@ -412,6 +412,10 @@ func (m *QuicProtocolOptions) validate(all bool) error { } } + // no validation rules for ConnectionOptions + + // no validation rules for ClientConnectionOptions + if len(errors) > 0 { return QuicProtocolOptionsMultiError(errors) } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/proxy_protocol.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/proxy_protocol.pb.go index 90b7aaebe..56e3119f4 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/proxy_protocol.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/proxy_protocol.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/proxy_protocol.proto package corev3 @@ -274,16 +274,16 @@ var file_envoy_config_core_v3_proxy_protocol_proto_rawDesc = []byte{ 0x6c, 0x50, 0x61, 0x73, 0x73, 0x54, 0x68, 0x72, 0x6f, 0x75, 0x67, 0x68, 0x54, 0x4c, 0x56, 0x73, 0x52, 0x0f, 0x70, 0x61, 0x73, 0x73, 0x54, 0x68, 0x72, 0x6f, 0x75, 0x67, 0x68, 0x54, 0x6c, 0x76, 0x73, 0x22, 0x19, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x06, 0x0a, 0x02, - 0x56, 0x31, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x56, 0x32, 0x10, 0x01, 0x42, 0x86, 0x01, 0x0a, - 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, - 0x2e, 0x76, 0x33, 0x42, 0x12, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, - 0x6f, 0x6c, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, - 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, - 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, - 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, - 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, - 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x56, 0x31, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x56, 0x32, 0x10, 0x01, 0x42, 0x86, 0x01, 0xba, + 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x12, 0x50, 0x72, 0x6f, + 0x78, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, + 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, + 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, + 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/resolver.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/resolver.pb.go index 9094e47f7..3c0a2fe07 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/resolver.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/resolver.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/resolver.proto package corev3 @@ -172,15 +172,15 @@ var file_envoy_config_core_v3_resolver_proto_rawDesc = []byte{ 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x44, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, 0x72, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x12, 0x64, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, - 0x72, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x42, 0x81, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, - 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, - 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, - 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, - 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, + 0x72, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x42, 0x81, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, + 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, + 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, + 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, + 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, + 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, + 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, + 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, + 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/socket_option.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/socket_option.pb.go index 5ade94fca..646973476 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/socket_option.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/socket_option.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/socket_option.proto package corev3 @@ -81,13 +81,13 @@ func (SocketOption_SocketState) EnumDescriptor() ([]byte, []int) { // // .. code-block:: json // -// { -// "description": "support tcp keep alive", -// "state": 0, -// "level": 1, -// "name": 9, -// "int_value": 1, -// } +// { +// "description": "support tcp keep alive", +// "state": 0, +// "level": 1, +// "name": 9, +// "int_value": 1, +// } // // 1 means SOL_SOCKET and 9 means SO_KEEPALIVE on Linux. // With the above configuration, `TCP Keep-Alives `_ @@ -110,6 +110,7 @@ type SocketOption struct { // The numeric name as passed to setsockopt Name int64 `protobuf:"varint,3,opt,name=name,proto3" json:"name,omitempty"` // Types that are assignable to Value: + // // *SocketOption_IntValue // *SocketOption_BufValue Value isSocketOption_Value `protobuf_oneof:"value"` @@ -305,15 +306,15 @@ var file_envoy_config_core_v3_socket_option_proto_rawDesc = []byte{ 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x73, 0x6f, 0x63, 0x6b, 0x65, 0x74, - 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x42, 0x85, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x11, - 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, - 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x42, 0x85, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, + 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, + 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x11, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, + 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, + 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, + 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.go index 745b4c186..6692c1d5d 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/substitution_format_string.proto package corev3 @@ -24,45 +24,97 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// Optional configuration options to be used with json_format. +type JsonFormatOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The output JSON string properties will be sorted. + SortProperties bool `protobuf:"varint,1,opt,name=sort_properties,json=sortProperties,proto3" json:"sort_properties,omitempty"` +} + +func (x *JsonFormatOptions) Reset() { + *x = JsonFormatOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *JsonFormatOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*JsonFormatOptions) ProtoMessage() {} + +func (x *JsonFormatOptions) ProtoReflect() protoreflect.Message { + mi := &file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use JsonFormatOptions.ProtoReflect.Descriptor instead. +func (*JsonFormatOptions) Descriptor() ([]byte, []int) { + return file_envoy_config_core_v3_substitution_format_string_proto_rawDescGZIP(), []int{0} +} + +func (x *JsonFormatOptions) GetSortProperties() bool { + if x != nil { + return x.SortProperties + } + return false +} + // Configuration to use multiple :ref:`command operators ` // to generate a new string in either plain text or JSON format. -// [#next-free-field: 7] +// [#next-free-field: 8] type SubstitutionFormatString struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Format: + // // *SubstitutionFormatString_TextFormat // *SubstitutionFormatString_JsonFormat // *SubstitutionFormatString_TextFormatSource Format isSubstitutionFormatString_Format `protobuf_oneof:"format"` // If set to true, when command operators are evaluated to null, // - // * for ``text_format``, the output of the empty operator is changed from ``-`` to an - // empty string, so that empty values are omitted entirely. - // * for ``json_format`` the keys with null values are omitted in the output structure. + // - for “text_format“, the output of the empty operator is changed from “-“ to an + // empty string, so that empty values are omitted entirely. + // - for “json_format“ the keys with null values are omitted in the output structure. OmitEmptyValues bool `protobuf:"varint,3,opt,name=omit_empty_values,json=omitEmptyValues,proto3" json:"omit_empty_values,omitempty"` - // Specify a ``content_type`` field. - // If this field is not set then ``text/plain`` is used for ``text_format`` and - // ``application/json`` is used for ``json_format``. + // Specify a “content_type“ field. + // If this field is not set then “text/plain“ is used for “text_format“ and + // “application/json“ is used for “json_format“. // // .. validated-code-block:: yaml - // :type-name: envoy.config.core.v3.SubstitutionFormatString // - // content_type: "text/html; charset=UTF-8" + // :type-name: envoy.config.core.v3.SubstitutionFormatString // + // content_type: "text/html; charset=UTF-8" ContentType string `protobuf:"bytes,4,opt,name=content_type,json=contentType,proto3" json:"content_type,omitempty"` // Specifies a collection of Formatter plugins that can be called from the access log configuration. // See the formatters extensions documentation for details. // [#extension-category: envoy.formatter] Formatters []*TypedExtensionConfig `protobuf:"bytes,6,rep,name=formatters,proto3" json:"formatters,omitempty"` + // If json_format is used, the options will be applied to the output JSON string. + JsonFormatOptions *JsonFormatOptions `protobuf:"bytes,7,opt,name=json_format_options,json=jsonFormatOptions,proto3" json:"json_format_options,omitempty"` } func (x *SubstitutionFormatString) Reset() { *x = SubstitutionFormatString{} if protoimpl.UnsafeEnabled { - mi := &file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[0] + mi := &file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -75,7 +127,7 @@ func (x *SubstitutionFormatString) String() string { func (*SubstitutionFormatString) ProtoMessage() {} func (x *SubstitutionFormatString) ProtoReflect() protoreflect.Message { - mi := &file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[0] + mi := &file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -88,7 +140,7 @@ func (x *SubstitutionFormatString) ProtoReflect() protoreflect.Message { // Deprecated: Use SubstitutionFormatString.ProtoReflect.Descriptor instead. func (*SubstitutionFormatString) Descriptor() ([]byte, []int) { - return file_envoy_config_core_v3_substitution_format_string_proto_rawDescGZIP(), []int{0} + return file_envoy_config_core_v3_substitution_format_string_proto_rawDescGZIP(), []int{1} } func (m *SubstitutionFormatString) GetFormat() isSubstitutionFormatString_Format { @@ -98,7 +150,7 @@ func (m *SubstitutionFormatString) GetFormat() isSubstitutionFormatString_Format return nil } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/config/core/v3/substitution_format_string.proto. func (x *SubstitutionFormatString) GetTextFormat() string { if x, ok := x.GetFormat().(*SubstitutionFormatString_TextFormat); ok { return x.TextFormat @@ -141,6 +193,13 @@ func (x *SubstitutionFormatString) GetFormatters() []*TypedExtensionConfig { return nil } +func (x *SubstitutionFormatString) GetJsonFormatOptions() *JsonFormatOptions { + if x != nil { + return x.JsonFormatOptions + } + return nil +} + type isSubstitutionFormatString_Format interface { isSubstitutionFormatString_Format() } @@ -149,22 +208,23 @@ type SubstitutionFormatString_TextFormat struct { // Specify a format with command operators to form a text string. // Its details is described in :ref:`format string`. // - // For example, setting ``text_format`` like below, + // For example, setting “text_format“ like below, // // .. validated-code-block:: yaml - // :type-name: envoy.config.core.v3.SubstitutionFormatString // - // text_format: "%LOCAL_REPLY_BODY%:%RESPONSE_CODE%:path=%REQ(:path)%\n" + // :type-name: envoy.config.core.v3.SubstitutionFormatString + // + // text_format: "%LOCAL_REPLY_BODY%:%RESPONSE_CODE%:path=%REQ(:path)%\n" // // generates plain text similar to: // // .. code-block:: text // - // upstream connect error:503:path=/foo + // upstream connect error:503:path=/foo // // Deprecated in favor of :ref:`text_format_source `. To migrate text format strings, use the :ref:`inline_string ` field. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/config/core/v3/substitution_format_string.proto. TextFormat string `protobuf:"bytes,1,opt,name=text_format,json=textFormat,proto3,oneof"` } @@ -176,21 +236,21 @@ type SubstitutionFormatString_JsonFormat struct { // See the documentation for a specific command operator for details. // // .. validated-code-block:: yaml - // :type-name: envoy.config.core.v3.SubstitutionFormatString // - // json_format: - // status: "%RESPONSE_CODE%" - // message: "%LOCAL_REPLY_BODY%" + // :type-name: envoy.config.core.v3.SubstitutionFormatString + // + // json_format: + // status: "%RESPONSE_CODE%" + // message: "%LOCAL_REPLY_BODY%" // // The following JSON object would be created: // // .. code-block:: json // - // { - // "status": 500, - // "message": "My error message" - // } - // + // { + // "status": 500, + // "message": "My error message" + // } JsonFormat *_struct.Struct `protobuf:"bytes,2,opt,name=json_format,json=jsonFormat,proto3,oneof"` } @@ -198,20 +258,20 @@ type SubstitutionFormatString_TextFormatSource struct { // Specify a format with command operators to form a text string. // Its details is described in :ref:`format string`. // - // For example, setting ``text_format`` like below, + // For example, setting “text_format“ like below, // // .. validated-code-block:: yaml - // :type-name: envoy.config.core.v3.SubstitutionFormatString // - // text_format_source: - // inline_string: "%LOCAL_REPLY_BODY%:%RESPONSE_CODE%:path=%REQ(:path)%\n" + // :type-name: envoy.config.core.v3.SubstitutionFormatString + // + // text_format_source: + // inline_string: "%LOCAL_REPLY_BODY%:%RESPONSE_CODE%:path=%REQ(:path)%\n" // // generates plain text similar to: // // .. code-block:: text // - // upstream connect error:503:path=/foo - // + // upstream connect error:503:path=/foo TextFormatSource *DataSource `protobuf:"bytes,5,opt,name=text_format_source,json=textFormatSource,proto3,oneof"` } @@ -241,42 +301,51 @@ var file_envoy_config_core_v3_substitution_format_string_proto_rawDesc = []byte{ 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, - 0x99, 0x03, 0x0a, 0x18, 0x53, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, - 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x12, 0x2e, 0x0a, 0x0b, - 0x74, 0x65, 0x78, 0x74, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x42, 0x0b, 0x18, 0x01, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x48, 0x00, - 0x52, 0x0a, 0x74, 0x65, 0x78, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x44, 0x0a, 0x0b, - 0x6a, 0x73, 0x6f, 0x6e, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, - 0x01, 0x02, 0x10, 0x01, 0x48, 0x00, 0x52, 0x0a, 0x6a, 0x73, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, - 0x61, 0x74, 0x12, 0x50, 0x0a, 0x12, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, - 0x74, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, - 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x48, 0x00, 0x52, 0x10, 0x74, 0x65, 0x78, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x53, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x12, 0x2a, 0x0a, 0x11, 0x6f, 0x6d, 0x69, 0x74, 0x5f, 0x65, 0x6d, 0x70, - 0x74, 0x79, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, - 0x0f, 0x6f, 0x6d, 0x69, 0x74, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x73, - 0x12, 0x2e, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc0, 0x01, 0x02, - 0xc8, 0x01, 0x00, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, - 0x12, 0x4a, 0x0a, 0x0a, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x73, 0x18, 0x06, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x54, 0x79, 0x70, 0x65, - 0x64, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x52, 0x0a, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x73, 0x42, 0x0d, 0x0a, 0x06, - 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x91, 0x01, 0x0a, 0x22, - 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, - 0x76, 0x33, 0x42, 0x1d, 0x53, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, - 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, - 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, - 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x3c, 0x0a, 0x11, 0x4a, 0x73, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x4f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x73, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x72, 0x6f, + 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x73, + 0x6f, 0x72, 0x74, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x22, 0xf2, 0x03, + 0x0a, 0x18, 0x53, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x6f, + 0x72, 0x6d, 0x61, 0x74, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x12, 0x2e, 0x0a, 0x0b, 0x74, 0x65, + 0x78, 0x74, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, + 0x0b, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x18, 0x01, 0x48, 0x00, 0x52, 0x0a, + 0x74, 0x65, 0x78, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x44, 0x0a, 0x0b, 0x6a, 0x73, + 0x6f, 0x6e, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, + 0x10, 0x01, 0x48, 0x00, 0x52, 0x0a, 0x6a, 0x73, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, + 0x12, 0x50, 0x0a, 0x12, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x5f, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, + 0x2e, 0x76, 0x33, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x48, 0x00, + 0x52, 0x10, 0x74, 0x65, 0x78, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x53, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x12, 0x2a, 0x0a, 0x11, 0x6f, 0x6d, 0x69, 0x74, 0x5f, 0x65, 0x6d, 0x70, 0x74, 0x79, + 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x6f, + 0x6d, 0x69, 0x74, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, 0x2e, + 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc8, 0x01, 0x00, 0xc0, 0x01, + 0x02, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x4a, + 0x0a, 0x0a, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x73, 0x18, 0x06, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x64, 0x45, + 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0a, + 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x73, 0x12, 0x57, 0x0a, 0x13, 0x6a, 0x73, + 0x6f, 0x6e, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x2e, 0x4a, + 0x73, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x52, 0x11, 0x6a, 0x73, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x42, 0x0d, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x03, 0xf8, + 0x42, 0x01, 0x42, 0x91, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x22, 0x69, + 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, + 0x33, 0x42, 0x1d, 0x53, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x46, + 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, + 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, + 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -291,22 +360,24 @@ func file_envoy_config_core_v3_substitution_format_string_proto_rawDescGZIP() [] return file_envoy_config_core_v3_substitution_format_string_proto_rawDescData } -var file_envoy_config_core_v3_substitution_format_string_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_envoy_config_core_v3_substitution_format_string_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_envoy_config_core_v3_substitution_format_string_proto_goTypes = []interface{}{ - (*SubstitutionFormatString)(nil), // 0: envoy.config.core.v3.SubstitutionFormatString - (*_struct.Struct)(nil), // 1: google.protobuf.Struct - (*DataSource)(nil), // 2: envoy.config.core.v3.DataSource - (*TypedExtensionConfig)(nil), // 3: envoy.config.core.v3.TypedExtensionConfig + (*JsonFormatOptions)(nil), // 0: envoy.config.core.v3.JsonFormatOptions + (*SubstitutionFormatString)(nil), // 1: envoy.config.core.v3.SubstitutionFormatString + (*_struct.Struct)(nil), // 2: google.protobuf.Struct + (*DataSource)(nil), // 3: envoy.config.core.v3.DataSource + (*TypedExtensionConfig)(nil), // 4: envoy.config.core.v3.TypedExtensionConfig } var file_envoy_config_core_v3_substitution_format_string_proto_depIdxs = []int32{ - 1, // 0: envoy.config.core.v3.SubstitutionFormatString.json_format:type_name -> google.protobuf.Struct - 2, // 1: envoy.config.core.v3.SubstitutionFormatString.text_format_source:type_name -> envoy.config.core.v3.DataSource - 3, // 2: envoy.config.core.v3.SubstitutionFormatString.formatters:type_name -> envoy.config.core.v3.TypedExtensionConfig - 3, // [3:3] is the sub-list for method output_type - 3, // [3:3] is the sub-list for method input_type - 3, // [3:3] is the sub-list for extension type_name - 3, // [3:3] is the sub-list for extension extendee - 0, // [0:3] is the sub-list for field type_name + 2, // 0: envoy.config.core.v3.SubstitutionFormatString.json_format:type_name -> google.protobuf.Struct + 3, // 1: envoy.config.core.v3.SubstitutionFormatString.text_format_source:type_name -> envoy.config.core.v3.DataSource + 4, // 2: envoy.config.core.v3.SubstitutionFormatString.formatters:type_name -> envoy.config.core.v3.TypedExtensionConfig + 0, // 3: envoy.config.core.v3.SubstitutionFormatString.json_format_options:type_name -> envoy.config.core.v3.JsonFormatOptions + 4, // [4:4] is the sub-list for method output_type + 4, // [4:4] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name } func init() { file_envoy_config_core_v3_substitution_format_string_proto_init() } @@ -318,6 +389,18 @@ func file_envoy_config_core_v3_substitution_format_string_proto_init() { file_envoy_config_core_v3_extension_proto_init() if !protoimpl.UnsafeEnabled { file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*JsonFormatOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SubstitutionFormatString); i { case 0: return &v.state @@ -330,7 +413,7 @@ func file_envoy_config_core_v3_substitution_format_string_proto_init() { } } } - file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[0].OneofWrappers = []interface{}{ + file_envoy_config_core_v3_substitution_format_string_proto_msgTypes[1].OneofWrappers = []interface{}{ (*SubstitutionFormatString_TextFormat)(nil), (*SubstitutionFormatString_JsonFormat)(nil), (*SubstitutionFormatString_TextFormatSource)(nil), @@ -341,7 +424,7 @@ func file_envoy_config_core_v3_substitution_format_string_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_envoy_config_core_v3_substitution_format_string_proto_rawDesc, NumEnums: 0, - NumMessages: 1, + NumMessages: 2, NumExtensions: 0, NumServices: 0, }, diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.validate.go index 2f3615c0b..c805d8286 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.validate.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/substitution_format_string.pb.validate.go @@ -35,6 +35,110 @@ var ( _ = sort.Sort ) +// Validate checks the field values on JsonFormatOptions with the rules defined +// in the proto definition for this message. If any rules are violated, the +// first error encountered is returned, or nil if there are no violations. +func (m *JsonFormatOptions) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on JsonFormatOptions with the rules +// defined in the proto definition for this message. If any rules are +// violated, the result is a list of violation errors wrapped in +// JsonFormatOptionsMultiError, or nil if none found. +func (m *JsonFormatOptions) ValidateAll() error { + return m.validate(true) +} + +func (m *JsonFormatOptions) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + // no validation rules for SortProperties + + if len(errors) > 0 { + return JsonFormatOptionsMultiError(errors) + } + + return nil +} + +// JsonFormatOptionsMultiError is an error wrapping multiple validation errors +// returned by JsonFormatOptions.ValidateAll() if the designated constraints +// aren't met. +type JsonFormatOptionsMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m JsonFormatOptionsMultiError) Error() string { + var msgs []string + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m JsonFormatOptionsMultiError) AllErrors() []error { return m } + +// JsonFormatOptionsValidationError is the validation error returned by +// JsonFormatOptions.Validate if the designated constraints aren't met. +type JsonFormatOptionsValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e JsonFormatOptionsValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e JsonFormatOptionsValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e JsonFormatOptionsValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e JsonFormatOptionsValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e JsonFormatOptionsValidationError) ErrorName() string { + return "JsonFormatOptionsValidationError" +} + +// Error satisfies the builtin error interface +func (e JsonFormatOptionsValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sJsonFormatOptions.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = JsonFormatOptionsValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = JsonFormatOptionsValidationError{} + // Validate checks the field values on SubstitutionFormatString with the rules // defined in the proto definition for this message. If any rules are // violated, the first error encountered is returned, or nil if there are no violations. @@ -104,6 +208,35 @@ func (m *SubstitutionFormatString) validate(all bool) error { } + if all { + switch v := interface{}(m.GetJsonFormatOptions()).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, SubstitutionFormatStringValidationError{ + field: "JsonFormatOptions", + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, SubstitutionFormatStringValidationError{ + field: "JsonFormatOptions", + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(m.GetJsonFormatOptions()).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return SubstitutionFormatStringValidationError{ + field: "JsonFormatOptions", + reason: "embedded message failed validation", + cause: err, + } + } + } + oneofFormatPresent := false switch v := m.Format.(type) { case *SubstitutionFormatString_TextFormat: diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/udp_socket_config.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/udp_socket_config.pb.go index d5ff6d382..b7f9f8229 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/udp_socket_config.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/config/core/v3/udp_socket_config.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/config/core/v3/udp_socket_config.proto package corev3 @@ -110,16 +110,16 @@ var file_envoy_config_core_v3_udp_socket_config_proto_rawDesc = []byte{ 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x5f, 0x67, 0x72, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x09, 0x70, 0x72, - 0x65, 0x66, 0x65, 0x72, 0x47, 0x72, 0x6f, 0x42, 0x88, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x14, - 0x55, 0x64, 0x70, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, - 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, - 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, - 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x65, 0x66, 0x65, 0x72, 0x47, 0x72, 0x6f, 0x42, 0x88, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, + 0x10, 0x02, 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x63, + 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x14, 0x55, 0x64, 0x70, 0x53, 0x6f, 0x63, 0x6b, 0x65, + 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, + 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x63, 0x6f, 0x72, 0x65, + 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/ads.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/ads.pb.go index 72cbf33d4..65abb236d 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/ads.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/ads.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/service/discovery/v3/ads.proto package discoveryv3 @@ -101,16 +101,16 @@ var file_envoy_service_discovery_v3_ads_proto_rawDesc = []byte{ 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x33, 0x2e, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, - 0x01, 0x42, 0x8d, 0x01, 0x0a, 0x28, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, - 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, - 0x65, 0x2e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x33, 0x42, 0x08, - 0x41, 0x64, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x4d, 0x67, 0x69, 0x74, 0x68, - 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, - 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, - 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x2f, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2f, 0x76, 0x33, 0x3b, 0x64, 0x69, - 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, - 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x01, 0x42, 0x8d, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x28, 0x69, 0x6f, + 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, + 0x65, 0x72, 0x79, 0x2e, 0x76, 0x33, 0x42, 0x08, 0x41, 0x64, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x50, 0x01, 0x5a, 0x4d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, + 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, + 0x72, 0x79, 0x2f, 0x76, 0x33, 0x3b, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x76, + 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/discovery.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/discovery.pb.go index 9586ffd58..a39aac288 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/discovery.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3/discovery.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/service/discovery/v3/discovery.proto package discoveryv3 @@ -171,12 +171,12 @@ type DiscoveryRequest struct { // which will be explicitly enumerated in resource_names. ResourceNames []string `protobuf:"bytes,3,rep,name=resource_names,json=resourceNames,proto3" json:"resource_names,omitempty"` // [#not-implemented-hide:] - // Alternative to ``resource_names`` field that allows specifying dynamic + // Alternative to “resource_names“ field that allows specifying dynamic // parameters along with each resource name. Clients that populate this // field must be able to handle responses from the server where resources // are wrapped in a Resource message. // Note that it is legal for a request to have some resources listed - // in ``resource_names`` and others in ``resource_locators``. + // in “resource_names“ and others in “resource_locators“. ResourceLocators []*ResourceLocator `protobuf:"bytes,7,rep,name=resource_locators,json=resourceLocators,proto3" json:"resource_locators,omitempty"` // Type of the resource that is being requested, e.g. // "type.googleapis.com/envoy.api.v2.ClusterLoadAssignment". This is implicit @@ -190,7 +190,7 @@ type DiscoveryRequest struct { // delta, where it is populated only for new explicit ACKs). ResponseNonce string `protobuf:"bytes,5,opt,name=response_nonce,json=responseNonce,proto3" json:"response_nonce,omitempty"` // This is populated when the previous :ref:`DiscoveryResponse ` - // failed to update configuration. The ``message`` field in ``error_details`` provides the Envoy + // failed to update configuration. The “message“ field in “error_details“ provides the Envoy // internal exception related to the failure. It is only intended for consumption during manual // debugging, the string provided is not guaranteed to be stable across Envoy versions. ErrorDetail *status.Status `protobuf:"bytes,6,opt,name=error_detail,json=errorDetail,proto3" json:"error_detail,omitempty"` @@ -290,17 +290,17 @@ type DiscoveryResponse struct { // [#not-implemented-hide:] // Canary is used to support two Envoy command line flags: // - // * --terminate-on-canary-transition-failure. When set, Envoy is able to - // terminate if it detects that configuration is stuck at canary. Consider - // this example sequence of updates: + // - --terminate-on-canary-transition-failure. When set, Envoy is able to + // terminate if it detects that configuration is stuck at canary. Consider + // this example sequence of updates: // - Management server applies a canary config successfully. // - Management server rolls back to a production config. // - Envoy rejects the new production config. - // Since there is no sensible way to continue receiving configuration - // updates, Envoy will then terminate and apply production config from a - // clean slate. - // * --dry-run-canary. When set, a canary response will never be applied, only - // validated via a dry run. + // Since there is no sensible way to continue receiving configuration + // updates, Envoy will then terminate and apply production config from a + // clean slate. + // - --dry-run-canary. When set, a canary response will never be applied, only + // validated via a dry run. Canary bool `protobuf:"varint,3,opt,name=canary,proto3" json:"canary,omitempty"` // Type URL for resources. Identifies the xDS API when muxing over ADS. // Must be consistent with the type_url in the 'resources' repeated Any (if non-empty). @@ -433,9 +433,9 @@ type DeltaDiscoveryRequest struct { // The node making the request. Node *v3.Node `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` // Type of the resource that is being requested, e.g. - // ``type.googleapis.com/envoy.api.v2.ClusterLoadAssignment``. This does not need to be set if - // resources are only referenced via ``xds_resource_subscribe`` and - // ``xds_resources_unsubscribe``. + // “type.googleapis.com/envoy.api.v2.ClusterLoadAssignment“. This does not need to be set if + // resources are only referenced via “xds_resource_subscribe“ and + // “xds_resources_unsubscribe“. TypeUrl string `protobuf:"bytes,2,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` // DeltaDiscoveryRequests allow the client to add or remove individual // resources to the set of tracked resources in the context of a stream. @@ -462,16 +462,16 @@ type DeltaDiscoveryRequest struct { // A list of Resource names to remove from the list of tracked resources. ResourceNamesUnsubscribe []string `protobuf:"bytes,4,rep,name=resource_names_unsubscribe,json=resourceNamesUnsubscribe,proto3" json:"resource_names_unsubscribe,omitempty"` // [#not-implemented-hide:] - // Alternative to ``resource_names_subscribe`` field that allows specifying dynamic parameters + // Alternative to “resource_names_subscribe“ field that allows specifying dynamic parameters // along with each resource name. // Note that it is legal for a request to have some resources listed - // in ``resource_names_subscribe`` and others in ``resource_locators_subscribe``. + // in “resource_names_subscribe“ and others in “resource_locators_subscribe“. ResourceLocatorsSubscribe []*ResourceLocator `protobuf:"bytes,8,rep,name=resource_locators_subscribe,json=resourceLocatorsSubscribe,proto3" json:"resource_locators_subscribe,omitempty"` // [#not-implemented-hide:] - // Alternative to ``resource_names_unsubscribe`` field that allows specifying dynamic parameters + // Alternative to “resource_names_unsubscribe“ field that allows specifying dynamic parameters // along with each resource name. // Note that it is legal for a request to have some resources listed - // in ``resource_names_unsubscribe`` and others in ``resource_locators_unsubscribe``. + // in “resource_names_unsubscribe“ and others in “resource_locators_unsubscribe“. ResourceLocatorsUnsubscribe []*ResourceLocator `protobuf:"bytes,9,rep,name=resource_locators_unsubscribe,json=resourceLocatorsUnsubscribe,proto3" json:"resource_locators_unsubscribe,omitempty"` // Informs the server of the versions of the resources the xDS client knows of, to enable the // client to continue the same logical xDS session even in the face of gRPC stream reconnection. @@ -488,7 +488,7 @@ type DeltaDiscoveryRequest struct { // Otherwise (unlike in DiscoveryRequest) response_nonce must be omitted. ResponseNonce string `protobuf:"bytes,6,opt,name=response_nonce,json=responseNonce,proto3" json:"response_nonce,omitempty"` // This is populated when the previous :ref:`DiscoveryResponse ` - // failed to update configuration. The ``message`` field in ``error_details`` + // failed to update configuration. The “message“ field in “error_details“ // provides the Envoy internal exception related to the failure. ErrorDetail *status.Status `protobuf:"bytes,7,opt,name=error_detail,json=errorDetail,proto3" json:"error_detail,omitempty"` } @@ -710,6 +710,7 @@ type DynamicParameterConstraints struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Type: + // // *DynamicParameterConstraints_Constraint // *DynamicParameterConstraints_OrConstraints // *DynamicParameterConstraints_AndConstraints @@ -824,12 +825,12 @@ type Resource struct { unknownFields protoimpl.UnknownFields // The resource's name, to distinguish it from others of the same type of resource. - // Only one of ``name`` or ``resource_name`` may be set. + // Only one of “name“ or “resource_name“ may be set. Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - // Alternative to the ``name`` field, to be used when the server supports + // Alternative to the “name“ field, to be used when the server supports // multiple variants of the named resource that are differentiated by // dynamic parameter constraints. - // Only one of ``name`` or ``resource_name`` may be set. + // Only one of “name“ or “resource_name“ may be set. ResourceName *ResourceName `protobuf:"bytes,8,opt,name=resource_name,json=resourceName,proto3" json:"resource_name,omitempty"` // The aliases are a list of other names that this resource can go by. Aliases []string `protobuf:"bytes,4,rep,name=aliases,proto3" json:"aliases,omitempty"` @@ -957,6 +958,7 @@ type DynamicParameterConstraints_SingleConstraint struct { // The key to match against. Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // Types that are assignable to ConstraintType: + // // *DynamicParameterConstraints_SingleConstraint_Value // *DynamicParameterConstraints_SingleConstraint_Exists_ ConstraintType isDynamicParameterConstraints_SingleConstraint_ConstraintType `protobuf_oneof:"constraint_type"` @@ -1427,16 +1429,16 @@ var file_envoy_service_discovery_v3_discovery_proto_rawDesc = []byte{ 0x61, 0x63, 0x68, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x64, 0x6f, 0x4e, 0x6f, 0x74, 0x43, 0x61, 0x63, 0x68, 0x65, 0x3a, 0x1c, 0x9a, 0xc5, 0x88, 0x1e, 0x17, 0x0a, 0x15, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x32, 0x2e, 0x52, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x42, 0x93, 0x01, 0x0a, 0x28, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x73, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x2e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2e, 0x76, - 0x33, 0x42, 0x0e, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x50, 0x01, 0x5a, 0x4d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, - 0x65, 0x72, 0x79, 0x2f, 0x76, 0x33, 0x3b, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, - 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x75, 0x72, 0x63, 0x65, 0x42, 0x93, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, + 0x28, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x64, 0x69, 0x73, + 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2e, 0x76, 0x33, 0x42, 0x0e, 0x44, 0x69, 0x73, 0x63, 0x6f, + 0x76, 0x65, 0x72, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x4d, 0x67, 0x69, 0x74, + 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, + 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, + 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x2f, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x2f, 0x76, 0x33, 0x3b, 0x64, + 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/filter_state.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/filter_state.pb.go index 4ad1d1ce3..659489053 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/filter_state.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/filter_state.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/filter_state.proto package matcherv3 @@ -31,6 +31,7 @@ type FilterStateMatcher struct { // The filter state key to retrieve the object. Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // Types that are assignable to Matcher: + // // *FilterStateMatcher_StringMatch Matcher isFilterStateMatcher_Matcher `protobuf_oneof:"matcher"` } @@ -120,16 +121,16 @@ var file_envoy_type_matcher_v3_filter_state_proto_rawDesc = []byte{ 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x48, 0x00, 0x52, 0x0b, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x42, 0x0e, 0x0a, 0x07, 0x6d, 0x61, - 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x89, 0x01, 0x0a, 0x23, 0x69, - 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, - 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, - 0x76, 0x33, 0x42, 0x10, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, - 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, - 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, - 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x89, 0x01, 0xba, 0x80, 0xc8, + 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, + 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, + 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x10, 0x46, 0x69, 0x6c, 0x74, + 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, + 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, + 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, + 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/http_inputs.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/http_inputs.pb.go index be7272b47..01bf97506 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/http_inputs.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/http_inputs.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/http_inputs.proto package matcherv3 @@ -304,36 +304,36 @@ var file_envoy_type_matcher_v3_http_inputs_proto_rawDesc = []byte{ 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x2c, 0x0a, 0x0b, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, - 0x08, 0x72, 0x06, 0xc0, 0x01, 0x01, 0xc8, 0x01, 0x00, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, + 0x08, 0x72, 0x06, 0xc8, 0x01, 0x00, 0xc0, 0x01, 0x01, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0x4c, 0x0a, 0x1c, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x54, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x2c, 0x0a, 0x0b, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, - 0x06, 0xc0, 0x01, 0x01, 0xc8, 0x01, 0x00, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4e, + 0x06, 0xc8, 0x01, 0x00, 0xc0, 0x01, 0x01, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0x4c, 0x0a, 0x1c, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x2c, 0x0a, 0x0b, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6e, 0x61, - 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc0, - 0x01, 0x01, 0xc8, 0x01, 0x00, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, + 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc8, + 0x01, 0x00, 0xc0, 0x01, 0x01, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0x4d, 0x0a, 0x1d, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x2c, 0x0a, 0x0b, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, - 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc0, 0x01, - 0x01, 0xc8, 0x01, 0x00, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, + 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc8, 0x01, + 0x00, 0xc0, 0x01, 0x01, 0x52, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0x4b, 0x0a, 0x1f, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x51, 0x75, 0x65, 0x72, 0x79, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x28, 0x0a, 0x0b, 0x71, 0x75, 0x65, 0x72, 0x79, 0x5f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x0a, 0x71, 0x75, 0x65, 0x72, 0x79, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x42, 0x88, 0x01, - 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, - 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0f, 0x48, 0x74, 0x74, 0x70, 0x49, 0x6e, 0x70, 0x75, 0x74, - 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, - 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, - 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, - 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, - 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, + 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0f, 0x48, + 0x74, 0x74, 0x70, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, + 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, + 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, + 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/metadata.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/metadata.pb.go index ef57a33bd..91534f4b1 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/metadata.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/metadata.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/metadata.proto package matcherv3 @@ -107,6 +107,7 @@ type MetadataMatcher_PathSegment struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Segment: + // // *MetadataMatcher_PathSegment_Key Segment isMetadataMatcher_PathSegment_Segment `protobuf_oneof:"segment"` } @@ -207,15 +208,15 @@ var file_envoy_type_matcher_v3_metadata_proto_rawDesc = []byte{ 0x42, 0x01, 0x3a, 0x29, 0x9a, 0xc5, 0x88, 0x1e, 0x24, 0x0a, 0x22, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x86, 0x01, - 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, - 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0d, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, - 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, - 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, - 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, + 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0d, 0x4d, + 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, + 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, + 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, + 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/node.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/node.pb.go index b2e12c84a..1274f799c 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/node.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/node.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/node.proto package matcherv3 @@ -107,15 +107,15 @@ var file_envoy_type_matcher_v3_node_proto_rawDesc = []byte{ 0x52, 0x0d, 0x6e, 0x6f, 0x64, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x73, 0x3a, 0x25, 0x9a, 0xc5, 0x88, 0x1e, 0x20, 0x0a, 0x1e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x4d, - 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x82, 0x01, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, - 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x09, - 0x4e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, - 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, - 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, - 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, - 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, - 0x72, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x82, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, + 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, + 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, + 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x09, 0x4e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x74, + 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, + 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/number.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/number.pb.go index 251d139a1..99733ecf4 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/number.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/number.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/number.proto package matcherv3 @@ -30,6 +30,7 @@ type DoubleMatcher struct { unknownFields protoimpl.UnknownFields // Types that are assignable to MatchPattern: + // // *DoubleMatcher_Range // *DoubleMatcher_Exact MatchPattern isDoubleMatcher_MatchPattern `protobuf_oneof:"match_pattern"` @@ -131,15 +132,15 @@ var file_envoy_type_matcher_v3_number_proto_rawDesc = []byte{ 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x44, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x14, 0x0a, 0x0d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x84, - 0x01, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, - 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x50, 0x72, - 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, - 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, - 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, - 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, 0xc8, - 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, + 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, + 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0b, + 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, + 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, + 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, + 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, + 0x68, 0x65, 0x72, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/path.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/path.pb.go index ddadfb0ca..8854b2c48 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/path.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/path.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/path.proto package matcherv3 @@ -29,6 +29,7 @@ type PathMatcher struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Rule: + // // *PathMatcher_Path Rule isPathMatcher_Rule `protobuf_oneof:"rule"` } @@ -84,9 +85,9 @@ type isPathMatcher_Rule interface { } type PathMatcher_Path struct { - // The ``path`` must match the URL path portion of the :path header. The query and fragment + // The “path“ must match the URL path portion of the :path header. The query and fragment // string (if present) are removed in the URL path portion. - // For example, the path ``/data`` will match the ``:path`` header ``/data#fragment?param=value``. + // For example, the path “/data“ will match the “:path“ header “/data#fragment?param=value“. Path *StringMatcher `protobuf:"bytes,1,opt,name=path,proto3,oneof"` } @@ -115,15 +116,15 @@ var file_envoy_type_matcher_v3_path_proto_rawDesc = []byte{ 0x9a, 0xc5, 0x88, 0x1e, 0x20, 0x0a, 0x1e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x50, 0x61, 0x74, 0x68, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x0b, 0x0a, 0x04, 0x72, 0x75, 0x6c, 0x65, 0x12, 0x03, 0xf8, - 0x42, 0x01, 0x42, 0x82, 0x01, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, - 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, - 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x09, 0x50, 0x61, 0x74, 0x68, - 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, - 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, - 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, - 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, - 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x42, 0x01, 0x42, 0x82, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, + 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, + 0x76, 0x33, 0x42, 0x09, 0x50, 0x61, 0x74, 0x68, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, + 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, + 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, + 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/regex.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/regex.pb.go index 38a3bce81..c95338e39 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/regex.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/regex.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/regex.proto package matcherv3 @@ -31,6 +31,7 @@ type RegexMatcher struct { unknownFields protoimpl.UnknownFields // Types that are assignable to EngineType: + // // *RegexMatcher_GoogleRe2 EngineType isRegexMatcher_EngineType `protobuf_oneof:"engine_type"` // The regex match string. The string must be supported by the configured engine. The regex is matched @@ -77,7 +78,7 @@ func (m *RegexMatcher) GetEngineType() isRegexMatcher_EngineType { return nil } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/type/matcher/v3/regex.proto. func (x *RegexMatcher) GetGoogleRe2() *RegexMatcher_GoogleRE2 { if x, ok := x.GetEngineType().(*RegexMatcher_GoogleRe2); ok { return x.GoogleRe2 @@ -99,7 +100,7 @@ type isRegexMatcher_EngineType interface { type RegexMatcher_GoogleRe2 struct { // Google's RE2 regex engine. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/type/matcher/v3/regex.proto. GoogleRe2 *RegexMatcher_GoogleRE2 `protobuf:"bytes,1,opt,name=google_re2,json=googleRe2,proto3,oneof"` } @@ -129,7 +130,7 @@ type RegexMatchAndSubstitute struct { // defined by the chosen regular expression engine. Google's `RE2 // `_ regular expression engine uses a // backslash followed by the capture group number to denote a numbered - // capture group. E.g., ``\1`` refers to capture group 1, and ``\2`` refers + // capture group. E.g., “\1“ refers to capture group 1, and “\2“ refers // to capture group 2. Substitution string `protobuf:"bytes,2,opt,name=substitution,proto3" json:"substitution,omitempty"` } @@ -184,14 +185,14 @@ func (x *RegexMatchAndSubstitute) GetSubstitution() string { // the documented `syntax `_. The engine is designed // to complete execution in linear time as well as limit the amount of memory used. // -// Envoy supports program size checking via runtime. The runtime keys ``re2.max_program_size.error_level`` -// and ``re2.max_program_size.warn_level`` can be set to integers as the maximum program size or +// Envoy supports program size checking via runtime. The runtime keys “re2.max_program_size.error_level“ +// and “re2.max_program_size.warn_level“ can be set to integers as the maximum program size or // complexity that a compiled regex can have before an exception is thrown or a warning is -// logged, respectively. ``re2.max_program_size.error_level`` defaults to 100, and -// ``re2.max_program_size.warn_level`` has no default if unset (will not check/log a warning). +// logged, respectively. “re2.max_program_size.error_level“ defaults to 100, and +// “re2.max_program_size.warn_level“ has no default if unset (will not check/log a warning). // -// Envoy emits two stats for tracking the program size of regexes: the histogram ``re2.program_size``, -// which records the program size, and the counter ``re2.exceeded_warn_level``, which is incremented +// Envoy emits two stats for tracking the program size of regexes: the histogram “re2.program_size“, +// which records the program size, and the counter “re2.exceeded_warn_level“, which is incremented // each time the program size exceeds the warn level threshold. type RegexMatcher_GoogleRE2 struct { state protoimpl.MessageState @@ -208,11 +209,10 @@ type RegexMatcher_GoogleRE2 struct { // // .. note:: // - // Although this field is deprecated, the program size will still be checked against the - // global ``re2.max_program_size.error_level`` runtime value. - // + // Although this field is deprecated, the program size will still be checked against the + // global ``re2.max_program_size.error_level`` runtime value. // - // Deprecated: Do not use. + // Deprecated: Marked as deprecated in envoy/type/matcher/v3/regex.proto. MaxProgramSize *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=max_program_size,json=maxProgramSize,proto3" json:"max_program_size,omitempty"` } @@ -248,7 +248,7 @@ func (*RegexMatcher_GoogleRE2) Descriptor() ([]byte, []int) { return file_envoy_type_matcher_v3_regex_proto_rawDescGZIP(), []int{0, 0} } -// Deprecated: Do not use. +// Deprecated: Marked as deprecated in envoy/type/matcher/v3/regex.proto. func (x *RegexMatcher_GoogleRE2) GetMaxProgramSize() *wrappers.UInt32Value { if x != nil { return x.MaxProgramSize @@ -278,15 +278,15 @@ var file_envoy_type_matcher_v3_regex_proto_rawDesc = []byte{ 0x2d, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x52, 0x65, 0x67, 0x65, 0x78, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x52, 0x45, 0x32, 0x42, 0x0b, - 0x18, 0x01, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x48, 0x00, 0x52, 0x09, 0x67, + 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x18, 0x01, 0x48, 0x00, 0x52, 0x09, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x52, 0x65, 0x32, 0x12, 0x1d, 0x0a, 0x05, 0x72, 0x65, 0x67, 0x65, 0x78, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x05, 0x72, 0x65, 0x67, 0x65, 0x78, 0x1a, 0x92, 0x01, 0x0a, 0x09, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x52, 0x45, 0x32, 0x12, 0x53, 0x0a, 0x10, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0b, 0x18, - 0x01, 0x92, 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x52, 0x0e, 0x6d, 0x61, 0x78, 0x50, + 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0b, 0x92, + 0xc7, 0x86, 0xd8, 0x04, 0x03, 0x33, 0x2e, 0x30, 0x18, 0x01, 0x52, 0x0e, 0x6d, 0x61, 0x78, 0x50, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x53, 0x69, 0x7a, 0x65, 0x3a, 0x30, 0x9a, 0xc5, 0x88, 0x1e, 0x2b, 0x0a, 0x29, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x67, 0x65, 0x78, 0x4d, 0x61, 0x74, 0x63, 0x68, @@ -302,20 +302,20 @@ var file_envoy_type_matcher_v3_regex_proto_rawDesc = []byte{ 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x8a, 0x01, 0x02, 0x10, 0x01, 0x52, 0x07, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x2f, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0b, - 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc0, 0x01, 0x02, 0xc8, 0x01, 0x00, 0x52, 0x0c, 0x73, 0x75, 0x62, + 0xfa, 0x42, 0x08, 0x72, 0x06, 0xc8, 0x01, 0x00, 0xc0, 0x01, 0x02, 0x52, 0x0c, 0x73, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x31, 0x9a, 0xc5, 0x88, 0x1e, 0x2c, 0x0a, 0x2a, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x67, 0x65, 0x78, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x41, - 0x6e, 0x64, 0x53, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x65, 0x42, 0x83, 0x01, 0x0a, - 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, - 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0a, 0x52, 0x65, 0x67, 0x65, 0x78, 0x50, 0x72, 0x6f, 0x74, 0x6f, - 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, - 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, - 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x6e, 0x64, 0x53, 0x75, 0x62, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x65, 0x42, 0x83, 0x01, 0xba, + 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, + 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0a, 0x52, 0x65, + 0x67, 0x65, 0x78, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, + 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, + 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, + 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/status_code_input.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/status_code_input.pb.go index 2209a7d5c..618f84d59 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/status_code_input.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/status_code_input.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/status_code_input.proto package matcherv3 @@ -115,16 +115,16 @@ var file_envoy_type_matcher_v3_status_code_input_proto_rawDesc = []byte{ 0x61, 0x74, 0x63, 0x68, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x22, 0x27, 0x0a, 0x25, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x49, 0x6e, 0x70, - 0x75, 0x74, 0x42, 0x8d, 0x01, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, - 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, - 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x14, 0x53, 0x74, 0x61, 0x74, - 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, - 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, - 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, - 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, - 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x75, 0x74, 0x42, 0x8d, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, + 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, + 0x76, 0x33, 0x42, 0x14, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x49, 0x6e, + 0x70, 0x75, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, + 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, + 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, + 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/string.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/string.pb.go index 65d589aa6..3fec38dec 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/string.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/string.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/string.proto package matcherv3 @@ -30,6 +30,7 @@ type StringMatcher struct { unknownFields protoimpl.UnknownFields // Types that are assignable to MatchPattern: + // // *StringMatcher_Exact // *StringMatcher_Prefix // *StringMatcher_Suffix @@ -38,7 +39,7 @@ type StringMatcher struct { MatchPattern isStringMatcher_MatchPattern `protobuf_oneof:"match_pattern"` // If true, indicates the exact/prefix/suffix/contains matching should be case insensitive. This // has no effect for the safe_regex match. - // For example, the matcher ``data`` will match both input string ``Data`` and ``data`` if set to true. + // For example, the matcher “data“ will match both input string “Data“ and “data“ if set to true. IgnoreCase bool `protobuf:"varint,6,opt,name=ignore_case,json=ignoreCase,proto3" json:"ignore_case,omitempty"` } @@ -132,7 +133,7 @@ type StringMatcher_Exact struct { // // Examples: // - // * ``abc`` only matches the value ``abc``. + // * “abc“ only matches the value “abc“. Exact string `protobuf:"bytes,1,opt,name=exact,proto3,oneof"` } @@ -142,7 +143,7 @@ type StringMatcher_Prefix struct { // // Examples: // - // * ``abc`` matches the value ``abc.xyz`` + // * “abc“ matches the value “abc.xyz“ Prefix string `protobuf:"bytes,2,opt,name=prefix,proto3,oneof"` } @@ -152,7 +153,7 @@ type StringMatcher_Suffix struct { // // Examples: // - // * ``abc`` matches the value ``xyz.abc`` + // * “abc“ matches the value “xyz.abc“ Suffix string `protobuf:"bytes,3,opt,name=suffix,proto3,oneof"` } @@ -167,7 +168,7 @@ type StringMatcher_Contains struct { // // Examples: // - // * ``abc`` matches the value ``xyz.abc.def`` + // * “abc“ matches the value “xyz.abc.def“ Contains string `protobuf:"bytes,7,opt,name=contains,proto3,oneof"` } @@ -273,16 +274,16 @@ var file_envoy_type_matcher_v3_string_proto_rawDesc = []byte{ 0x92, 0x01, 0x02, 0x08, 0x01, 0x52, 0x08, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x73, 0x3a, 0x2b, 0x9a, 0xc5, 0x88, 0x1e, 0x26, 0x0a, 0x24, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, - 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x84, 0x01, 0x0a, - 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, - 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0b, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, - 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, - 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x84, 0x01, 0xba, + 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, + 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0b, 0x53, 0x74, + 0x72, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, + 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, + 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, + 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, + 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, + 0x72, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/struct.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/struct.pb.go index 294fa99d8..1ecb4ce09 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/struct.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/struct.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/struct.proto package matcherv3 @@ -23,54 +23,54 @@ const ( ) // StructMatcher provides a general interface to check if a given value is matched in -// google.protobuf.Struct. It uses ``path`` to retrieve the value +// google.protobuf.Struct. It uses “path“ to retrieve the value // from the struct and then check if it's matched to the specified value. // // For example, for the following Struct: // // .. code-block:: yaml // -// fields: -// a: -// struct_value: -// fields: -// b: -// struct_value: -// fields: -// c: -// string_value: pro -// t: -// list_value: -// values: -// - string_value: m -// - string_value: n +// fields: +// a: +// struct_value: +// fields: +// b: +// struct_value: +// fields: +// c: +// string_value: pro +// t: +// list_value: +// values: +// - string_value: m +// - string_value: n // // The following MetadataMatcher is matched as the path [a, b, c] will retrieve a string value "pro" // from the Metadata which is matched to the specified prefix match. // // .. code-block:: yaml // -// path: -// - key: a -// - key: b -// - key: c -// value: -// string_match: -// prefix: pr +// path: +// - key: a +// - key: b +// - key: c +// value: +// string_match: +// prefix: pr // // The following StructMatcher is matched as the code will match one of the string values in the // list at the path [a, t]. // // .. code-block:: yaml // -// path: -// - key: a -// - key: t -// value: -// list_match: -// one_of: -// string_match: -// exact: m +// path: +// - key: a +// - key: t +// value: +// list_match: +// one_of: +// string_match: +// exact: m // // An example use of StructMatcher is to match metadata in envoy.v*.core.Node. type StructMatcher struct { @@ -137,6 +137,7 @@ type StructMatcher_PathSegment struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Segment: + // // *StructMatcher_PathSegment_Key Segment isStructMatcher_PathSegment_Segment `protobuf_oneof:"segment"` } @@ -232,16 +233,16 @@ var file_envoy_type_matcher_v3_struct_proto_rawDesc = []byte{ 0x74, 0x42, 0x0e, 0x0a, 0x07, 0x73, 0x65, 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x3a, 0x27, 0x9a, 0xc5, 0x88, 0x1e, 0x22, 0x0a, 0x20, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x53, 0x74, 0x72, - 0x75, 0x63, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x84, 0x01, 0x0a, 0x23, 0x69, - 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, - 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, - 0x76, 0x33, 0x42, 0x0b, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, - 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, - 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, - 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, - 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, - 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x75, 0x63, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x84, 0x01, 0xba, 0x80, 0xc8, + 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, + 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, + 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0b, 0x53, 0x74, 0x72, 0x75, + 0x63, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, + 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, + 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, + 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, + 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, + 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.go index 0a694d085..851261eb6 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/matcher/v3/value.proto package matcherv3 @@ -24,7 +24,7 @@ const ( // Specifies the way to match a ProtobufWkt::Value. Primitive values and ListValue are supported. // StructValue is not supported and is always not matched. -// [#next-free-field: 7] +// [#next-free-field: 8] type ValueMatcher struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -33,12 +33,14 @@ type ValueMatcher struct { // Specifies how to match a value. // // Types that are assignable to MatchPattern: + // // *ValueMatcher_NullMatch_ // *ValueMatcher_DoubleMatch // *ValueMatcher_StringMatch // *ValueMatcher_BoolMatch // *ValueMatcher_PresentMatch // *ValueMatcher_ListMatch + // *ValueMatcher_OrMatch MatchPattern isValueMatcher_MatchPattern `protobuf_oneof:"match_pattern"` } @@ -123,6 +125,13 @@ func (x *ValueMatcher) GetListMatch() *ListMatcher { return nil } +func (x *ValueMatcher) GetOrMatch() *OrMatcher { + if x, ok := x.GetMatchPattern().(*ValueMatcher_OrMatch); ok { + return x.OrMatch + } + return nil +} + type isValueMatcher_MatchPattern interface { isValueMatcher_MatchPattern() } @@ -163,6 +172,11 @@ type ValueMatcher_ListMatch struct { ListMatch *ListMatcher `protobuf:"bytes,6,opt,name=list_match,json=listMatch,proto3,oneof"` } +type ValueMatcher_OrMatch struct { + // If specified, a match occurs if and only if any of the alternatives in the match accept the value. + OrMatch *OrMatcher `protobuf:"bytes,7,opt,name=or_match,json=orMatch,proto3,oneof"` +} + func (*ValueMatcher_NullMatch_) isValueMatcher_MatchPattern() {} func (*ValueMatcher_DoubleMatch) isValueMatcher_MatchPattern() {} @@ -175,6 +189,8 @@ func (*ValueMatcher_PresentMatch) isValueMatcher_MatchPattern() {} func (*ValueMatcher_ListMatch) isValueMatcher_MatchPattern() {} +func (*ValueMatcher_OrMatch) isValueMatcher_MatchPattern() {} + // Specifies the way to match a list value. type ListMatcher struct { state protoimpl.MessageState @@ -182,6 +198,7 @@ type ListMatcher struct { unknownFields protoimpl.UnknownFields // Types that are assignable to MatchPattern: + // // *ListMatcher_OneOf MatchPattern isListMatcher_MatchPattern `protobuf_oneof:"match_pattern"` } @@ -243,6 +260,54 @@ type ListMatcher_OneOf struct { func (*ListMatcher_OneOf) isListMatcher_MatchPattern() {} +// Specifies a list of alternatives for the match. +type OrMatcher struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ValueMatchers []*ValueMatcher `protobuf:"bytes,1,rep,name=value_matchers,json=valueMatchers,proto3" json:"value_matchers,omitempty"` +} + +func (x *OrMatcher) Reset() { + *x = OrMatcher{} + if protoimpl.UnsafeEnabled { + mi := &file_envoy_type_matcher_v3_value_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OrMatcher) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OrMatcher) ProtoMessage() {} + +func (x *OrMatcher) ProtoReflect() protoreflect.Message { + mi := &file_envoy_type_matcher_v3_value_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OrMatcher.ProtoReflect.Descriptor instead. +func (*OrMatcher) Descriptor() ([]byte, []int) { + return file_envoy_type_matcher_v3_value_proto_rawDescGZIP(), []int{2} +} + +func (x *OrMatcher) GetValueMatchers() []*ValueMatcher { + if x != nil { + return x.ValueMatchers + } + return nil +} + // NullMatch is an empty message to specify a null value. type ValueMatcher_NullMatch struct { state protoimpl.MessageState @@ -253,7 +318,7 @@ type ValueMatcher_NullMatch struct { func (x *ValueMatcher_NullMatch) Reset() { *x = ValueMatcher_NullMatch{} if protoimpl.UnsafeEnabled { - mi := &file_envoy_type_matcher_v3_value_proto_msgTypes[2] + mi := &file_envoy_type_matcher_v3_value_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -266,7 +331,7 @@ func (x *ValueMatcher_NullMatch) String() string { func (*ValueMatcher_NullMatch) ProtoMessage() {} func (x *ValueMatcher_NullMatch) ProtoReflect() protoreflect.Message { - mi := &file_envoy_type_matcher_v3_value_proto_msgTypes[2] + mi := &file_envoy_type_matcher_v3_value_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -298,7 +363,7 @@ var file_envoy_type_matcher_v3_value_proto_rawDesc = []byte{ 0x6f, 0x1a, 0x21, 0x75, 0x64, 0x70, 0x61, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, - 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xfe, 0x03, + 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xbd, 0x04, 0x0a, 0x0c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x4e, 0x0a, 0x0a, 0x6e, 0x75, 0x6c, 0x6c, 0x5f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, @@ -323,32 +388,42 @@ var file_envoy_type_matcher_v3_value_proto_rawDesc = []byte{ 0x32, 0x22, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x48, 0x00, 0x52, 0x09, 0x6c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x74, 0x63, - 0x68, 0x1a, 0x3d, 0x0a, 0x09, 0x4e, 0x75, 0x6c, 0x6c, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x3a, 0x30, - 0x9a, 0xc5, 0x88, 0x1e, 0x2b, 0x0a, 0x29, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, - 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4d, - 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4e, 0x75, 0x6c, 0x6c, 0x4d, 0x61, 0x74, 0x63, 0x68, - 0x3a, 0x26, 0x9a, 0xc5, 0x88, 0x1e, 0x21, 0x0a, 0x1f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, - 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x14, 0x0a, 0x0d, 0x6d, 0x61, 0x74, 0x63, - 0x68, 0x5f, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0x88, - 0x01, 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x3c, - 0x0a, 0x06, 0x6f, 0x6e, 0x65, 0x5f, 0x6f, 0x66, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, - 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4d, 0x61, 0x74, 0x63, - 0x68, 0x65, 0x72, 0x48, 0x00, 0x52, 0x05, 0x6f, 0x6e, 0x65, 0x4f, 0x66, 0x3a, 0x25, 0x9a, 0xc5, - 0x88, 0x1e, 0x20, 0x0a, 0x1e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, - 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x74, 0x63, - 0x68, 0x65, 0x72, 0x42, 0x14, 0x0a, 0x0d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x61, 0x74, - 0x74, 0x65, 0x72, 0x6e, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x83, 0x01, 0x0a, 0x23, 0x69, 0x6f, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, - 0x33, 0x42, 0x0a, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, - 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, - 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, - 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, - 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, - 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x68, 0x12, 0x3d, 0x0a, 0x08, 0x6f, 0x72, 0x5f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, + 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x4f, 0x72, 0x4d, 0x61, + 0x74, 0x63, 0x68, 0x65, 0x72, 0x48, 0x00, 0x52, 0x07, 0x6f, 0x72, 0x4d, 0x61, 0x74, 0x63, 0x68, + 0x1a, 0x3d, 0x0a, 0x09, 0x4e, 0x75, 0x6c, 0x6c, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x3a, 0x30, 0x9a, + 0xc5, 0x88, 0x1e, 0x2b, 0x0a, 0x29, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, + 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4d, 0x61, + 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4e, 0x75, 0x6c, 0x6c, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x3a, + 0x26, 0x9a, 0xc5, 0x88, 0x1e, 0x21, 0x0a, 0x1f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, + 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x42, 0x14, 0x0a, 0x0d, 0x6d, 0x61, 0x74, 0x63, 0x68, + 0x5f, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0x88, 0x01, + 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x3c, 0x0a, + 0x06, 0x6f, 0x6e, 0x65, 0x5f, 0x6f, 0x66, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x72, 0x48, 0x00, 0x52, 0x05, 0x6f, 0x6e, 0x65, 0x4f, 0x66, 0x3a, 0x25, 0x9a, 0xc5, 0x88, + 0x1e, 0x20, 0x0a, 0x1e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, + 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x72, 0x42, 0x14, 0x0a, 0x0d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x61, 0x74, 0x74, + 0x65, 0x72, 0x6e, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x22, 0x61, 0x0a, 0x09, 0x4f, 0x72, 0x4d, 0x61, + 0x74, 0x63, 0x68, 0x65, 0x72, 0x12, 0x54, 0x0a, 0x0e, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x6d, + 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x23, 0x2e, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x72, 0x2e, 0x76, 0x33, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x72, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x92, 0x01, 0x02, 0x08, 0x02, 0x52, 0x0d, 0x76, 0x61, + 0x6c, 0x75, 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x73, 0x42, 0x83, 0x01, 0xba, 0x80, + 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x23, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, + 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x2e, 0x76, 0x33, 0x42, 0x0a, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, + 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, + 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, + 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x6d, 0x61, 0x74, + 0x63, 0x68, 0x65, 0x72, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x72, 0x76, + 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -363,25 +438,28 @@ func file_envoy_type_matcher_v3_value_proto_rawDescGZIP() []byte { return file_envoy_type_matcher_v3_value_proto_rawDescData } -var file_envoy_type_matcher_v3_value_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_envoy_type_matcher_v3_value_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_envoy_type_matcher_v3_value_proto_goTypes = []interface{}{ (*ValueMatcher)(nil), // 0: envoy.type.matcher.v3.ValueMatcher (*ListMatcher)(nil), // 1: envoy.type.matcher.v3.ListMatcher - (*ValueMatcher_NullMatch)(nil), // 2: envoy.type.matcher.v3.ValueMatcher.NullMatch - (*DoubleMatcher)(nil), // 3: envoy.type.matcher.v3.DoubleMatcher - (*StringMatcher)(nil), // 4: envoy.type.matcher.v3.StringMatcher + (*OrMatcher)(nil), // 2: envoy.type.matcher.v3.OrMatcher + (*ValueMatcher_NullMatch)(nil), // 3: envoy.type.matcher.v3.ValueMatcher.NullMatch + (*DoubleMatcher)(nil), // 4: envoy.type.matcher.v3.DoubleMatcher + (*StringMatcher)(nil), // 5: envoy.type.matcher.v3.StringMatcher } var file_envoy_type_matcher_v3_value_proto_depIdxs = []int32{ - 2, // 0: envoy.type.matcher.v3.ValueMatcher.null_match:type_name -> envoy.type.matcher.v3.ValueMatcher.NullMatch - 3, // 1: envoy.type.matcher.v3.ValueMatcher.double_match:type_name -> envoy.type.matcher.v3.DoubleMatcher - 4, // 2: envoy.type.matcher.v3.ValueMatcher.string_match:type_name -> envoy.type.matcher.v3.StringMatcher + 3, // 0: envoy.type.matcher.v3.ValueMatcher.null_match:type_name -> envoy.type.matcher.v3.ValueMatcher.NullMatch + 4, // 1: envoy.type.matcher.v3.ValueMatcher.double_match:type_name -> envoy.type.matcher.v3.DoubleMatcher + 5, // 2: envoy.type.matcher.v3.ValueMatcher.string_match:type_name -> envoy.type.matcher.v3.StringMatcher 1, // 3: envoy.type.matcher.v3.ValueMatcher.list_match:type_name -> envoy.type.matcher.v3.ListMatcher - 0, // 4: envoy.type.matcher.v3.ListMatcher.one_of:type_name -> envoy.type.matcher.v3.ValueMatcher - 5, // [5:5] is the sub-list for method output_type - 5, // [5:5] is the sub-list for method input_type - 5, // [5:5] is the sub-list for extension type_name - 5, // [5:5] is the sub-list for extension extendee - 0, // [0:5] is the sub-list for field type_name + 2, // 4: envoy.type.matcher.v3.ValueMatcher.or_match:type_name -> envoy.type.matcher.v3.OrMatcher + 0, // 5: envoy.type.matcher.v3.ListMatcher.one_of:type_name -> envoy.type.matcher.v3.ValueMatcher + 0, // 6: envoy.type.matcher.v3.OrMatcher.value_matchers:type_name -> envoy.type.matcher.v3.ValueMatcher + 7, // [7:7] is the sub-list for method output_type + 7, // [7:7] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name } func init() { file_envoy_type_matcher_v3_value_proto_init() } @@ -417,6 +495,18 @@ func file_envoy_type_matcher_v3_value_proto_init() { } } file_envoy_type_matcher_v3_value_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*OrMatcher); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_envoy_type_matcher_v3_value_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ValueMatcher_NullMatch); i { case 0: return &v.state @@ -436,6 +526,7 @@ func file_envoy_type_matcher_v3_value_proto_init() { (*ValueMatcher_BoolMatch)(nil), (*ValueMatcher_PresentMatch)(nil), (*ValueMatcher_ListMatch)(nil), + (*ValueMatcher_OrMatch)(nil), } file_envoy_type_matcher_v3_value_proto_msgTypes[1].OneofWrappers = []interface{}{ (*ListMatcher_OneOf)(nil), @@ -446,7 +537,7 @@ func file_envoy_type_matcher_v3_value_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_envoy_type_matcher_v3_value_proto_rawDesc, NumEnums: 0, - NumMessages: 3, + NumMessages: 4, NumExtensions: 0, NumServices: 0, }, diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.validate.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.validate.go index cff13d9b9..5bbf95eba 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.validate.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3/value.pb.validate.go @@ -253,6 +253,48 @@ func (m *ValueMatcher) validate(all bool) error { } } + case *ValueMatcher_OrMatch: + if v == nil { + err := ValueMatcherValidationError{ + field: "MatchPattern", + reason: "oneof value cannot be a typed-nil", + } + if !all { + return err + } + errors = append(errors, err) + } + oneofMatchPatternPresent = true + + if all { + switch v := interface{}(m.GetOrMatch()).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, ValueMatcherValidationError{ + field: "OrMatch", + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, ValueMatcherValidationError{ + field: "OrMatch", + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(m.GetOrMatch()).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return ValueMatcherValidationError{ + field: "OrMatch", + reason: "embedded message failed validation", + cause: err, + } + } + } + default: _ = v // ensures v is used } @@ -501,6 +543,150 @@ var _ interface { ErrorName() string } = ListMatcherValidationError{} +// Validate checks the field values on OrMatcher with the rules defined in the +// proto definition for this message. If any rules are violated, the first +// error encountered is returned, or nil if there are no violations. +func (m *OrMatcher) Validate() error { + return m.validate(false) +} + +// ValidateAll checks the field values on OrMatcher with the rules defined in +// the proto definition for this message. If any rules are violated, the +// result is a list of violation errors wrapped in OrMatcherMultiError, or nil +// if none found. +func (m *OrMatcher) ValidateAll() error { + return m.validate(true) +} + +func (m *OrMatcher) validate(all bool) error { + if m == nil { + return nil + } + + var errors []error + + if len(m.GetValueMatchers()) < 2 { + err := OrMatcherValidationError{ + field: "ValueMatchers", + reason: "value must contain at least 2 item(s)", + } + if !all { + return err + } + errors = append(errors, err) + } + + for idx, item := range m.GetValueMatchers() { + _, _ = idx, item + + if all { + switch v := interface{}(item).(type) { + case interface{ ValidateAll() error }: + if err := v.ValidateAll(); err != nil { + errors = append(errors, OrMatcherValidationError{ + field: fmt.Sprintf("ValueMatchers[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + case interface{ Validate() error }: + if err := v.Validate(); err != nil { + errors = append(errors, OrMatcherValidationError{ + field: fmt.Sprintf("ValueMatchers[%v]", idx), + reason: "embedded message failed validation", + cause: err, + }) + } + } + } else if v, ok := interface{}(item).(interface{ Validate() error }); ok { + if err := v.Validate(); err != nil { + return OrMatcherValidationError{ + field: fmt.Sprintf("ValueMatchers[%v]", idx), + reason: "embedded message failed validation", + cause: err, + } + } + } + + } + + if len(errors) > 0 { + return OrMatcherMultiError(errors) + } + + return nil +} + +// OrMatcherMultiError is an error wrapping multiple validation errors returned +// by OrMatcher.ValidateAll() if the designated constraints aren't met. +type OrMatcherMultiError []error + +// Error returns a concatenation of all the error messages it wraps. +func (m OrMatcherMultiError) Error() string { + var msgs []string + for _, err := range m { + msgs = append(msgs, err.Error()) + } + return strings.Join(msgs, "; ") +} + +// AllErrors returns a list of validation violation errors. +func (m OrMatcherMultiError) AllErrors() []error { return m } + +// OrMatcherValidationError is the validation error returned by +// OrMatcher.Validate if the designated constraints aren't met. +type OrMatcherValidationError struct { + field string + reason string + cause error + key bool +} + +// Field function returns field value. +func (e OrMatcherValidationError) Field() string { return e.field } + +// Reason function returns reason value. +func (e OrMatcherValidationError) Reason() string { return e.reason } + +// Cause function returns cause value. +func (e OrMatcherValidationError) Cause() error { return e.cause } + +// Key function returns key value. +func (e OrMatcherValidationError) Key() bool { return e.key } + +// ErrorName returns error name. +func (e OrMatcherValidationError) ErrorName() string { return "OrMatcherValidationError" } + +// Error satisfies the builtin error interface +func (e OrMatcherValidationError) Error() string { + cause := "" + if e.cause != nil { + cause = fmt.Sprintf(" | caused by: %v", e.cause) + } + + key := "" + if e.key { + key = "key for " + } + + return fmt.Sprintf( + "invalid %sOrMatcher.%s: %s%s", + key, + e.field, + e.reason, + cause) +} + +var _ error = OrMatcherValidationError{} + +var _ interface { + Field() string + Reason() string + Key() bool + Cause() error + ErrorName() string +} = OrMatcherValidationError{} + // Validate checks the field values on ValueMatcher_NullMatch with the rules // defined in the proto definition for this message. If any rules are // violated, the first error encountered is returned, or nil if there are no violations. diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/hash_policy.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/hash_policy.pb.go index c03381ddc..2cda6f3dc 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/hash_policy.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/hash_policy.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/hash_policy.proto package typev3 @@ -29,6 +29,7 @@ type HashPolicy struct { unknownFields protoimpl.UnknownFields // Types that are assignable to PolicySpecifier: + // // *HashPolicy_SourceIp_ // *HashPolicy_FilterState_ PolicySpecifier isHashPolicy_PolicySpecifier `protobuf_oneof:"policy_specifier"` @@ -225,15 +226,15 @@ var file_envoy_type_v3_hash_policy_proto_rawDesc = []byte{ 0x01, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x3a, 0x1c, 0x9a, 0xc5, 0x88, 0x1e, 0x17, 0x0a, 0x15, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x48, 0x61, 0x73, 0x68, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x42, 0x17, 0x0a, 0x10, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x5f, 0x73, - 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x75, 0x0a, - 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, - 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0f, 0x48, 0x61, - 0x73, 0x68, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, - 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, - 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, - 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, - 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x75, 0xba, + 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, + 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0f, 0x48, 0x61, 0x73, 0x68, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, + 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, + 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, + 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, + 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http.pb.go index 7d21a85f6..c92aa2d6d 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/http.proto package typev3 @@ -83,14 +83,14 @@ var file_envoy_type_v3_http_proto_rawDesc = []byte{ 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2a, 0x32, 0x0a, 0x0f, 0x43, 0x6f, 0x64, 0x65, 0x63, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x09, 0x0a, 0x05, 0x48, 0x54, 0x54, 0x50, 0x31, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x48, 0x54, 0x54, 0x50, 0x32, 0x10, - 0x01, 0x12, 0x09, 0x0a, 0x05, 0x48, 0x54, 0x54, 0x50, 0x33, 0x10, 0x02, 0x42, 0x6f, 0x0a, 0x1b, - 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x09, 0x48, 0x74, 0x74, - 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, - 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, - 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, - 0x79, 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, + 0x01, 0x12, 0x09, 0x0a, 0x05, 0x48, 0x54, 0x54, 0x50, 0x33, 0x10, 0x02, 0x42, 0x6f, 0xba, 0x80, + 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, + 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, + 0x2e, 0x76, 0x33, 0x42, 0x09, 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, + 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, + 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http_status.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http_status.pb.go index 52cd8b77d..6ca1677a1 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http_status.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/http_status.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/http_status.proto package typev3 @@ -379,15 +379,15 @@ var file_envoy_type_v3_http_status_proto_rawDesc = []byte{ 0x64, 0x10, 0xfc, 0x03, 0x12, 0x10, 0x0a, 0x0b, 0x4e, 0x6f, 0x74, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x10, 0xfe, 0x03, 0x12, 0x22, 0x0a, 0x1d, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x41, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, - 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x10, 0xff, 0x03, 0x42, 0x75, 0x0a, 0x1b, 0x69, 0x6f, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0f, 0x48, 0x74, 0x74, 0x70, 0x53, - 0x74, 0x61, 0x74, 0x75, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, - 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, - 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, - 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, - 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, - 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x10, 0xff, 0x03, 0x42, 0x75, 0xba, 0x80, 0xc8, 0xd1, + 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, + 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, + 0x33, 0x42, 0x0f, 0x48, 0x74, 0x74, 0x70, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, + 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, + 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/percent.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/percent.pb.go index 22f1ff493..727374bb3 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/percent.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/percent.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/percent.proto package typev3 @@ -225,14 +225,14 @@ var file_envoy_type_v3_percent_proto_rawDesc = []byte{ 0x12, 0x0b, 0x0a, 0x07, 0x4d, 0x49, 0x4c, 0x4c, 0x49, 0x4f, 0x4e, 0x10, 0x02, 0x3a, 0x23, 0x9a, 0xc5, 0x88, 0x1e, 0x1e, 0x0a, 0x1c, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x46, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x50, 0x65, 0x72, 0x63, 0x65, - 0x6e, 0x74, 0x42, 0x72, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, - 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, - 0x33, 0x42, 0x0c, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, - 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, - 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, - 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, - 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x6e, 0x74, 0x42, 0x72, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, + 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0c, 0x50, 0x65, 0x72, 0x63, 0x65, + 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, + 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, + 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, + 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, + 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/range.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/range.pb.go index 80323c862..fa10eee0f 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/range.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/range.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/range.proto package typev3 @@ -223,14 +223,14 @@ var file_envoy_type_v3_range_proto_rawDesc = []byte{ 0x28, 0x01, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x03, 0x65, 0x6e, 0x64, 0x3a, 0x1d, 0x9a, 0xc5, 0x88, 0x1e, 0x18, 0x0a, 0x16, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x44, - 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x42, 0x70, 0x0a, 0x1b, 0x69, 0x6f, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x0a, 0x52, 0x61, 0x6e, 0x67, 0x65, - 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, - 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, - 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, - 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x42, 0x70, 0xba, 0x80, 0xc8, 0xd1, + 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, + 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, + 0x33, 0x42, 0x0a, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, + 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, + 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, + 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_strategy.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_strategy.pb.go index adab81a8c..b342e2217 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_strategy.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_strategy.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/ratelimit_strategy.proto package typev3 @@ -76,6 +76,7 @@ type RateLimitStrategy struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Strategy: + // // *RateLimitStrategy_BlanketRule_ // *RateLimitStrategy_RequestsPerTimeUnit_ // *RateLimitStrategy_TokenBucket @@ -177,14 +178,14 @@ func (*RateLimitStrategy_TokenBucket) isRateLimitStrategy_Strategy() {} // Allows to specify the desired requests per second (RPS, QPS), requests per minute (QPM, RPM), // etc., without specifying a rate limiting algorithm implementation. // -// ``RequestsPerTimeUnit`` strategy does not demand any specific rate limiting algorithm to be +// “RequestsPerTimeUnit“ strategy does not demand any specific rate limiting algorithm to be // used (in contrast to the :ref:`TokenBucket `, // for example). It implies that the implementation details of rate limiting algorithm are // irrelevant as long as the configured number of "requests per time unit" is achieved. // -// Note that the ``TokenBucket`` is still a valid implementation of the ``RequestsPerTimeUnit`` +// Note that the “TokenBucket“ is still a valid implementation of the “RequestsPerTimeUnit“ // strategy, and may be chosen to enforce the rate limit. However, there's no guarantee it will be -// the ``TokenBucket`` in particular, and not the Leaky Bucket, the Sliding Window, or any other +// the “TokenBucket“ in particular, and not the Leaky Bucket, the Sliding Window, or any other // rate limiting algorithm that fulfills the requirements. type RateLimitStrategy_RequestsPerTimeUnit struct { state protoimpl.MessageState @@ -193,18 +194,18 @@ type RateLimitStrategy_RequestsPerTimeUnit struct { // The desired number of requests per :ref:`time_unit // ` to allow. - // If set to ``0``, deny all (equivalent to ``BlanketRule.DENY_ALL``). + // If set to “0“, deny all (equivalent to “BlanketRule.DENY_ALL“). // // .. note:: - // Note that the algorithm implementation determines the course of action for the requests - // over the limit. As long as the ``requests_per_time_unit`` converges on the desired value, - // it's allowed to treat this field as a soft-limit: allow bursts, redistribute the allowance - // over time, etc. // + // Note that the algorithm implementation determines the course of action for the requests + // over the limit. As long as the ``requests_per_time_unit`` converges on the desired value, + // it's allowed to treat this field as a soft-limit: allow bursts, redistribute the allowance + // over time, etc. RequestsPerTimeUnit uint64 `protobuf:"varint,1,opt,name=requests_per_time_unit,json=requestsPerTimeUnit,proto3" json:"requests_per_time_unit,omitempty"` // The unit of time. Ignored when :ref:`requests_per_time_unit // ` - // is ``0`` (deny all). + // is “0“ (deny all). TimeUnit RateLimitUnit `protobuf:"varint,2,opt,name=time_unit,json=timeUnit,proto3,enum=envoy.type.v3.RateLimitUnit" json:"time_unit,omitempty"` } @@ -301,15 +302,15 @@ var file_envoy_type_v3_ratelimit_strategy_proto_rawDesc = []byte{ 0x6e, 0x6b, 0x65, 0x74, 0x52, 0x75, 0x6c, 0x65, 0x12, 0x0d, 0x0a, 0x09, 0x41, 0x4c, 0x4c, 0x4f, 0x57, 0x5f, 0x41, 0x4c, 0x4c, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x44, 0x45, 0x4e, 0x59, 0x5f, 0x41, 0x4c, 0x4c, 0x10, 0x01, 0x42, 0x0f, 0x0a, 0x08, 0x73, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, - 0x79, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x84, 0x01, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, + 0x79, 0x12, 0x03, 0xf8, 0x42, 0x01, 0x42, 0x84, 0x01, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, + 0x02, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, 0x01, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x16, 0x52, 0x61, 0x74, 0x65, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, - 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, 0xc8, - 0xd1, 0x06, 0x02, 0x10, 0x02, 0xd2, 0xc6, 0xa4, 0xe1, 0x06, 0x02, 0x08, 0x01, 0x62, 0x06, 0x70, + 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_unit.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_unit.pb.go index e98d9c598..6677a074a 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_unit.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/ratelimit_unit.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/ratelimit_unit.proto package typev3 @@ -104,14 +104,14 @@ var file_envoy_type_v3_ratelimit_unit_proto_rawDesc = []byte{ 0x4d, 0x49, 0x4e, 0x55, 0x54, 0x45, 0x10, 0x02, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x4f, 0x55, 0x52, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x44, 0x41, 0x59, 0x10, 0x04, 0x12, 0x09, 0x0a, 0x05, 0x4d, 0x4f, 0x4e, 0x54, 0x48, 0x10, 0x05, 0x12, 0x08, 0x0a, 0x04, 0x59, 0x45, 0x41, 0x52, 0x10, 0x06, - 0x42, 0x78, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, - 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, - 0x12, 0x52, 0x61, 0x74, 0x65, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x55, 0x6e, 0x69, 0x74, 0x50, 0x72, - 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, - 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, - 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, - 0x76, 0x33, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x42, 0x78, 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, + 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, + 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x12, 0x52, 0x61, 0x74, 0x65, 0x6c, 0x69, 0x6d, + 0x69, 0x74, 0x55, 0x6e, 0x69, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, + 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, + 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, + 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/semantic_version.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/semantic_version.pb.go index 1909162f8..10416e602 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/semantic_version.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/semantic_version.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/semantic_version.proto package typev3 @@ -106,15 +106,15 @@ var file_envoy_type_v3_semantic_version_proto_rawDesc = []byte{ 0x72, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x3a, 0x21, 0x9a, 0xc5, 0x88, 0x1e, 0x1c, 0x0a, 0x1a, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x53, 0x65, 0x6d, 0x61, 0x6e, - 0x74, 0x69, 0x63, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x7a, 0x0a, 0x1b, 0x69, 0x6f, - 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, - 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x14, 0x53, 0x65, 0x6d, 0x61, 0x6e, - 0x74, 0x69, 0x63, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, - 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, - 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, - 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, - 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x74, 0x69, 0x63, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x7a, 0xba, 0x80, 0xc8, 0xd1, + 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, + 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, + 0x33, 0x42, 0x14, 0x53, 0x65, 0x6d, 0x61, 0x6e, 0x74, 0x69, 0x63, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, + 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, + 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, + 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, + 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/token_bucket.pb.go b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/token_bucket.pb.go index dd629581c..5363e5abe 100644 --- a/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/token_bucket.pb.go +++ b/vendor/github.com/envoyproxy/go-control-plane/envoy/type/v3/token_bucket.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.21.12 +// protoc-gen-go v1.30.0 +// protoc v4.23.4 // source: envoy/type/v3/token_bucket.proto package typev3 @@ -37,8 +37,8 @@ type TokenBucket struct { // to a single token. TokensPerFill *wrappers.UInt32Value `protobuf:"bytes,2,opt,name=tokens_per_fill,json=tokensPerFill,proto3" json:"tokens_per_fill,omitempty"` // The fill interval that tokens are added to the bucket. During each fill interval - // ``tokens_per_fill`` are added to the bucket. The bucket will never contain more than - // ``max_tokens`` tokens. + // “tokens_per_fill“ are added to the bucket. The bucket will never contain more than + // “max_tokens“ tokens. FillInterval *duration.Duration `protobuf:"bytes,3,opt,name=fill_interval,json=fillInterval,proto3" json:"fill_interval,omitempty"` } @@ -126,14 +126,14 @@ var file_envoy_type_v3_token_bucket_proto_rawDesc = []byte{ 0x00, 0x52, 0x0c, 0x66, 0x69, 0x6c, 0x6c, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x3a, 0x1d, 0x9a, 0xc5, 0x88, 0x1e, 0x18, 0x0a, 0x16, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x42, 0x76, - 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, - 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x10, 0x54, - 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, - 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, - 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, - 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, - 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0xba, 0x80, - 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0xba, 0x80, 0xc8, 0xd1, 0x06, 0x02, 0x10, 0x02, 0x0a, 0x1b, 0x69, 0x6f, 0x2e, 0x65, 0x6e, 0x76, + 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2e, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2e, 0x74, 0x79, + 0x70, 0x65, 0x2e, 0x76, 0x33, 0x42, 0x10, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x75, 0x63, 0x6b, + 0x65, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, + 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x70, 0x72, 0x6f, 0x78, 0x79, + 0x2f, 0x67, 0x6f, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2d, 0x70, 0x6c, 0x61, 0x6e, + 0x65, 0x2f, 0x65, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x76, 0x33, 0x3b, + 0x74, 0x79, 0x70, 0x65, 0x76, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/envoyproxy/protoc-gen-validate/NOTICE b/vendor/github.com/envoyproxy/protoc-gen-validate/NOTICE deleted file mode 100644 index 60884a059..000000000 --- a/vendor/github.com/envoyproxy/protoc-gen-validate/NOTICE +++ /dev/null @@ -1,4 +0,0 @@ -protoc-gen-validate -Copyright 2019 Envoy Project Authors - -Licensed under Apache License 2.0. See LICENSE for terms. diff --git a/vendor/github.com/envoyproxy/protoc-gen-validate/validate/validate.proto b/vendor/github.com/envoyproxy/protoc-gen-validate/validate/validate.proto index 705d382aa..5aa965393 100644 --- a/vendor/github.com/envoyproxy/protoc-gen-validate/validate/validate.proto +++ b/vendor/github.com/envoyproxy/protoc-gen-validate/validate/validate.proto @@ -534,7 +534,7 @@ message StringRules { // at a maximum optional uint64 max_bytes = 5; - // Pattern specifes that this field must match against the specified + // Pattern specifies that this field must match against the specified // regular expression (RE2 syntax). The included expression should elide // any delimiters. optional string pattern = 6; @@ -646,7 +646,7 @@ message BytesRules { // at a maximum optional uint64 max_len = 3; - // Pattern specifes that this field must match against the specified + // Pattern specifies that this field must match against the specified // regular expression (RE2 syntax). The included expression should elide // any delimiters. optional string pattern = 4; @@ -732,11 +732,11 @@ message RepeatedRules { optional uint64 max_items = 2; // Unique specifies that all elements in this field must be unique. This - // contraint is only applicable to scalar and enum types (messages are not + // constraint is only applicable to scalar and enum types (messages are not // supported). optional bool unique = 3; - // Items specifies the contraints to be applied to each item in the field. + // Items specifies the constraints to be applied to each item in the field. // Repeated message fields will still execute validation against each item // unless skip is specified here. optional FieldRules items = 4; diff --git a/vendor/github.com/facette/natsort/LICENSE b/vendor/github.com/facette/natsort/LICENSE new file mode 100644 index 000000000..cc8f232b3 --- /dev/null +++ b/vendor/github.com/facette/natsort/LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2015, Vincent Batoufflet and Marc Falzon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the authors nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/facette/natsort/README.md b/vendor/github.com/facette/natsort/README.md new file mode 100644 index 000000000..a4362b728 --- /dev/null +++ b/vendor/github.com/facette/natsort/README.md @@ -0,0 +1,104 @@ +# natsort: natural strings sorting in Go + +This is an implementation of the "Alphanum Algorithm" by [Dave Koelle][0] in Go. + +[![GoDoc](https://godoc.org/facette.io/natsort?status.svg)](https://godoc.org/facette.io/natsort) + +## Usage + +```go +package main + +import ( + "fmt" + "strings" + + "facette.io/natsort" +) + +func main() { + list := []string{ + "1000X Radonius Maximus", + "10X Radonius", + "200X Radonius", + "20X Radonius", + "20X Radonius Prime", + "30X Radonius", + "40X Radonius", + "Allegia 50 Clasteron", + "Allegia 500 Clasteron", + "Allegia 50B Clasteron", + "Allegia 51 Clasteron", + "Allegia 6R Clasteron", + "Alpha 100", + "Alpha 2", + "Alpha 200", + "Alpha 2A", + "Alpha 2A-8000", + "Alpha 2A-900", + "Callisto Morphamax", + "Callisto Morphamax 500", + "Callisto Morphamax 5000", + "Callisto Morphamax 600", + "Callisto Morphamax 6000 SE", + "Callisto Morphamax 6000 SE2", + "Callisto Morphamax 700", + "Callisto Morphamax 7000", + "Xiph Xlater 10000", + "Xiph Xlater 2000", + "Xiph Xlater 300", + "Xiph Xlater 40", + "Xiph Xlater 5", + "Xiph Xlater 50", + "Xiph Xlater 500", + "Xiph Xlater 5000", + "Xiph Xlater 58", + } + + natsort.Sort(list) + + fmt.Println(strings.Join(list, "\n")) +} +``` + +Output: + +``` +10X Radonius +20X Radonius +20X Radonius Prime +30X Radonius +40X Radonius +200X Radonius +1000X Radonius Maximus +Allegia 6R Clasteron +Allegia 50 Clasteron +Allegia 50B Clasteron +Allegia 51 Clasteron +Allegia 500 Clasteron +Alpha 2 +Alpha 2A +Alpha 2A-900 +Alpha 2A-8000 +Alpha 100 +Alpha 200 +Callisto Morphamax +Callisto Morphamax 500 +Callisto Morphamax 600 +Callisto Morphamax 700 +Callisto Morphamax 5000 +Callisto Morphamax 6000 SE +Callisto Morphamax 6000 SE2 +Callisto Morphamax 7000 +Xiph Xlater 5 +Xiph Xlater 40 +Xiph Xlater 50 +Xiph Xlater 58 +Xiph Xlater 300 +Xiph Xlater 500 +Xiph Xlater 2000 +Xiph Xlater 5000 +Xiph Xlater 10000 +``` + +[0]: http://davekoelle.com/alphanum.html diff --git a/vendor/github.com/facette/natsort/natsort.go b/vendor/github.com/facette/natsort/natsort.go new file mode 100644 index 000000000..5c3c28d5a --- /dev/null +++ b/vendor/github.com/facette/natsort/natsort.go @@ -0,0 +1,85 @@ +// Package natsort implements natural strings sorting +package natsort + +import ( + "regexp" + "sort" + "strconv" +) + +type stringSlice []string + +func (s stringSlice) Len() int { + return len(s) +} + +func (s stringSlice) Less(a, b int) bool { + return Compare(s[a], s[b]) +} + +func (s stringSlice) Swap(a, b int) { + s[a], s[b] = s[b], s[a] +} + +var chunkifyRegexp = regexp.MustCompile(`(\d+|\D+)`) + +func chunkify(s string) []string { + return chunkifyRegexp.FindAllString(s, -1) +} + +// Sort sorts a list of strings in a natural order +func Sort(l []string) { + sort.Sort(stringSlice(l)) +} + +// Compare returns true if the first string precedes the second one according to natural order +func Compare(a, b string) bool { + chunksA := chunkify(a) + chunksB := chunkify(b) + + nChunksA := len(chunksA) + nChunksB := len(chunksB) + + for i := range chunksA { + if i >= nChunksB { + return false + } + + aInt, aErr := strconv.Atoi(chunksA[i]) + bInt, bErr := strconv.Atoi(chunksB[i]) + + // If both chunks are numeric, compare them as integers + if aErr == nil && bErr == nil { + if aInt == bInt { + if i == nChunksA-1 { + // We reached the last chunk of A, thus B is greater than A + return true + } else if i == nChunksB-1 { + // We reached the last chunk of B, thus A is greater than B + return false + } + + continue + } + + return aInt < bInt + } + + // So far both strings are equal, continue to next chunk + if chunksA[i] == chunksB[i] { + if i == nChunksA-1 { + // We reached the last chunk of A, thus B is greater than A + return true + } else if i == nChunksB-1 { + // We reached the last chunk of B, thus A is greater than B + return false + } + + continue + } + + return chunksA[i] < chunksB[i] + } + + return false +} diff --git a/vendor/github.com/fatih/color/color_windows.go b/vendor/github.com/fatih/color/color_windows.go new file mode 100644 index 000000000..be01c558e --- /dev/null +++ b/vendor/github.com/fatih/color/color_windows.go @@ -0,0 +1,19 @@ +package color + +import ( + "os" + + "golang.org/x/sys/windows" +) + +func init() { + // Opt-in for ansi color support for current process. + // https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#output-sequences + var outMode uint32 + out := windows.Handle(os.Stdout.Fd()) + if err := windows.GetConsoleMode(out, &outMode); err != nil { + return + } + outMode |= windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING + _ = windows.SetConsoleMode(out, outMode) +} diff --git a/vendor/github.com/felixge/httpsnoop/.travis.yml b/vendor/github.com/felixge/httpsnoop/.travis.yml deleted file mode 100644 index bfc421200..000000000 --- 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 2d84889ae..4e12afdd9 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 ddcecd13e..cf6b42f3d 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 b77cc7c00..bec7b71b3 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 31cbdfb8e..101cedde6 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 ab99c07c7..e0951df15 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 000000000..ffc7b992b --- /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 1d89d85ce..391cc076b 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 77f9593bd..e0e575754 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 d4e6080fe..e480733d1 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 1a95ad8e7..28497f1dd 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 54c77fbb0..921c1c1e4 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 29087469b..063a0915a 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 a9bb1c3c4..d34a23c01 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 ae392867c..9bc91e5d6 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 30a5bf0f0..24c99cc49 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 b09ef7683..99012ae65 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=$(<= 0, higher meaning "less important" | positive and negative, with 0 for "info" and higher meaning "more important" | +| Error log entries | always logged, don't have a verbosity level | normal log entries with level >= `LevelError` | +| Passing logger via context | `NewContext`, `FromContext` | no API | +| Adding a name to a logger | `WithName` | no API | +| Modify verbosity of log entries in a call chain | `V` | no API | +| Grouping of key/value pairs | not supported | `WithGroup`, `GroupValue` | +| Pass context for extracting additional values | no API | API variants like `InfoCtx` | + +The high-level slog API is explicitly meant to be one of many different APIs +that can be layered on top of a shared `slog.Handler`. logr is one such +alternative API, with [interoperability](#slog-interoperability) provided by +some conversion functions. + ### Inspiration Before you consider this package, please read [this blog post by the @@ -118,6 +143,103 @@ There are implementations for the following logging libraries: - **github.com/go-kit/log**: [gokitlogr](https://github.com/tonglil/gokitlogr) (also compatible with github.com/go-kit/kit/log since v0.12.0) - **bytes.Buffer** (writing to a buffer): [bufrlogr](https://github.com/tonglil/buflogr) (useful for ensuring values were logged, like during testing) +## slog interoperability + +Interoperability goes both ways, using the `logr.Logger` API with a `slog.Handler` +and using the `slog.Logger` API with a `logr.LogSink`. `FromSlogHandler` and +`ToSlogHandler` convert between a `logr.Logger` and a `slog.Handler`. +As usual, `slog.New` can be used to wrap such a `slog.Handler` in the high-level +slog API. + +### Using a `logr.LogSink` as backend for slog + +Ideally, a logr sink implementation should support both logr and slog by +implementing both the normal logr interface(s) and `SlogSink`. Because +of a conflict in the parameters of the common `Enabled` method, it is [not +possible to implement both slog.Handler and logr.Sink in the same +type](https://github.com/golang/go/issues/59110). + +If both are supported, log calls can go from the high-level APIs to the backend +without the need to convert parameters. `FromSlogHandler` and `ToSlogHandler` can +convert back and forth without adding additional wrappers, with one exception: +when `Logger.V` was used to adjust the verbosity for a `slog.Handler`, then +`ToSlogHandler` has to use a wrapper which adjusts the verbosity for future +log calls. + +Such an implementation should also support values that implement specific +interfaces from both packages for logging (`logr.Marshaler`, `slog.LogValuer`, +`slog.GroupValue`). logr does not convert those. + +Not supporting slog has several drawbacks: +- Recording source code locations works correctly if the handler gets called + through `slog.Logger`, but may be wrong in other cases. That's because a + `logr.Sink` does its own stack unwinding instead of using the program counter + provided by the high-level API. +- slog levels <= 0 can be mapped to logr levels by negating the level without a + loss of information. But all slog levels > 0 (e.g. `slog.LevelWarning` as + used by `slog.Logger.Warn`) must be mapped to 0 before calling the sink + because logr does not support "more important than info" levels. +- The slog group concept is supported by prefixing each key in a key/value + pair with the group names, separated by a dot. For structured output like + JSON it would be better to group the key/value pairs inside an object. +- Special slog values and interfaces don't work as expected. +- The overhead is likely to be higher. + +These drawbacks are severe enough that applications using a mixture of slog and +logr should switch to a different backend. + +### Using a `slog.Handler` as backend for logr + +Using a plain `slog.Handler` without support for logr works better than the +other direction: +- All logr verbosity levels can be mapped 1:1 to their corresponding slog level + by negating them. +- Stack unwinding is done by the `SlogSink` and the resulting program + counter is passed to the `slog.Handler`. +- Names added via `Logger.WithName` are gathered and recorded in an additional + attribute with `logger` as key and the names separated by slash as value. +- `Logger.Error` is turned into a log record with `slog.LevelError` as level + and an additional attribute with `err` as key, if an error was provided. + +The main drawback is that `logr.Marshaler` will not be supported. Types should +ideally support both `logr.Marshaler` and `slog.Valuer`. If compatibility +with logr implementations without slog support is not important, then +`slog.Valuer` is sufficient. + +### Context support for slog + +Storing a logger in a `context.Context` is not supported by +slog. `NewContextWithSlogLogger` and `FromContextAsSlogLogger` can be +used to fill this gap. They store and retrieve a `slog.Logger` pointer +under the same context key that is also used by `NewContext` and +`FromContext` for `logr.Logger` value. + +When `NewContextWithSlogLogger` is followed by `FromContext`, the latter will +automatically convert the `slog.Logger` to a +`logr.Logger`. `FromContextAsSlogLogger` does the same for the other direction. + +With this approach, binaries which use either slog or logr are as efficient as +possible with no unnecessary allocations. This is also why the API stores a +`slog.Logger` pointer: when storing a `slog.Handler`, creating a `slog.Logger` +on retrieval would need to allocate one. + +The downside is that switching back and forth needs more allocations. Because +logr is the API that is already in use by different packages, in particular +Kubernetes, the recommendation is to use the `logr.Logger` API in code which +uses contextual logging. + +An alternative to adding values to a logger and storing that logger in the +context is to store the values in the context and to configure a logging +backend to extract those values when emitting log entries. This only works when +log calls are passed the context, which is not supported by the logr API. + +With the slog API, it is possible, but not +required. https://github.com/veqryn/slog-context is a package for slog which +provides additional support code for this approach. It also contains wrappers +for the context functions in logr, so developers who prefer to not use the logr +APIs directly can use those instead and the resulting code will still be +interoperable with logr. + ## FAQ ### Conceptual @@ -241,7 +363,9 @@ Otherwise, you can start out with `0` as "you always want to see this", Then gradually choose levels in between as you need them, working your way down from 10 (for debug and trace style logs) and up from 1 (for chattier -info-type logs.) +info-type logs). For reference, slog pre-defines -4 for debug logs +(corresponds to 4 in logr), which matches what is +[recommended for Kubernetes](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md#what-method-to-use). #### How do I choose my keys? diff --git a/vendor/github.com/go-logr/logr/SECURITY.md b/vendor/github.com/go-logr/logr/SECURITY.md new file mode 100644 index 000000000..1ca756fc7 --- /dev/null +++ b/vendor/github.com/go-logr/logr/SECURITY.md @@ -0,0 +1,18 @@ +# Security Policy + +If you have discovered a security vulnerability in this project, please report it +privately. **Do not disclose it as a public issue.** This gives us time to work with you +to fix the issue before public exposure, reducing the chance that the exploit will be +used before a patch is released. + +You may submit the report in the following ways: + +- send an email to go-logr-security@googlegroups.com +- send us a [private vulnerability report](https://github.com/go-logr/logr/security/advisories/new) + +Please provide the following information in your report: + +- A description of the vulnerability and its impact +- How to reproduce the issue + +We ask that you give us 90 days to work on a fix before public exposure. diff --git a/vendor/github.com/go-logr/logr/context.go b/vendor/github.com/go-logr/logr/context.go new file mode 100644 index 000000000..de8bcc3ad --- /dev/null +++ b/vendor/github.com/go-logr/logr/context.go @@ -0,0 +1,33 @@ +/* +Copyright 2023 The logr 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 logr + +// contextKey is how we find Loggers in a context.Context. With Go < 1.21, +// the value is always a Logger value. With Go >= 1.21, the value can be a +// Logger value or a slog.Logger pointer. +type contextKey struct{} + +// notFoundError exists to carry an IsNotFound method. +type notFoundError struct{} + +func (notFoundError) Error() string { + return "no logr.Logger was present" +} + +func (notFoundError) IsNotFound() bool { + return true +} diff --git a/vendor/github.com/go-logr/logr/context_noslog.go b/vendor/github.com/go-logr/logr/context_noslog.go new file mode 100644 index 000000000..f012f9a18 --- /dev/null +++ b/vendor/github.com/go-logr/logr/context_noslog.go @@ -0,0 +1,49 @@ +//go:build !go1.21 +// +build !go1.21 + +/* +Copyright 2019 The logr 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 logr + +import ( + "context" +) + +// FromContext returns a Logger from ctx or an error if no Logger is found. +func FromContext(ctx context.Context) (Logger, error) { + if v, ok := ctx.Value(contextKey{}).(Logger); ok { + return v, nil + } + + return Logger{}, notFoundError{} +} + +// FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this +// returns a Logger that discards all log messages. +func FromContextOrDiscard(ctx context.Context) Logger { + if v, ok := ctx.Value(contextKey{}).(Logger); ok { + return v + } + + return Discard() +} + +// NewContext returns a new Context, derived from ctx, which carries the +// provided Logger. +func NewContext(ctx context.Context, logger Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) +} diff --git a/vendor/github.com/go-logr/logr/context_slog.go b/vendor/github.com/go-logr/logr/context_slog.go new file mode 100644 index 000000000..065ef0b82 --- /dev/null +++ b/vendor/github.com/go-logr/logr/context_slog.go @@ -0,0 +1,83 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2019 The logr 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 logr + +import ( + "context" + "fmt" + "log/slog" +) + +// FromContext returns a Logger from ctx or an error if no Logger is found. +func FromContext(ctx context.Context) (Logger, error) { + v := ctx.Value(contextKey{}) + if v == nil { + return Logger{}, notFoundError{} + } + + switch v := v.(type) { + case Logger: + return v, nil + case *slog.Logger: + return FromSlogHandler(v.Handler()), nil + default: + // Not reached. + panic(fmt.Sprintf("unexpected value type for logr context key: %T", v)) + } +} + +// FromContextAsSlogLogger returns a slog.Logger from ctx or nil if no such Logger is found. +func FromContextAsSlogLogger(ctx context.Context) *slog.Logger { + v := ctx.Value(contextKey{}) + if v == nil { + return nil + } + + switch v := v.(type) { + case Logger: + return slog.New(ToSlogHandler(v)) + case *slog.Logger: + return v + default: + // Not reached. + panic(fmt.Sprintf("unexpected value type for logr context key: %T", v)) + } +} + +// FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this +// returns a Logger that discards all log messages. +func FromContextOrDiscard(ctx context.Context) Logger { + if logger, err := FromContext(ctx); err == nil { + return logger + } + return Discard() +} + +// NewContext returns a new Context, derived from ctx, which carries the +// provided Logger. +func NewContext(ctx context.Context, logger Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) +} + +// NewContextWithSlogLogger returns a new Context, derived from ctx, which carries the +// provided slog.Logger. +func NewContextWithSlogLogger(ctx context.Context, logger *slog.Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) +} diff --git a/vendor/github.com/go-logr/logr/funcr/funcr.go b/vendor/github.com/go-logr/logr/funcr/funcr.go index e52f0cd01..fb2f866f4 100644 --- a/vendor/github.com/go-logr/logr/funcr/funcr.go +++ b/vendor/github.com/go-logr/logr/funcr/funcr.go @@ -100,6 +100,11 @@ type Options struct { // details, see docs for Go's time.Layout. TimestampFormat string + // LogInfoLevel tells funcr what key to use to log the info level. + // If not specified, the info level will be logged as "level". + // If this is set to "", the info level will not be logged at all. + LogInfoLevel *string + // Verbosity tells funcr which V logs to produce. Higher values enable // more logs. Info logs at or below this level will be written, while logs // above this level will be discarded. @@ -116,17 +121,17 @@ type Options struct { // Equivalent hooks are offered for key-value pairs saved via // logr.Logger.WithValues or Formatter.AddValues (see RenderValuesHook) and // for user-provided pairs (see RenderArgsHook). - RenderBuiltinsHook func(kvList []interface{}) []interface{} + RenderBuiltinsHook func(kvList []any) []any // RenderValuesHook is the same as RenderBuiltinsHook, except that it is // only called for key-value pairs saved via logr.Logger.WithValues. See // RenderBuiltinsHook for more details. - RenderValuesHook func(kvList []interface{}) []interface{} + RenderValuesHook func(kvList []any) []any // RenderArgsHook is the same as RenderBuiltinsHook, except that it is only // called for key-value pairs passed directly to Info and Error. See // RenderBuiltinsHook for more details. - RenderArgsHook func(kvList []interface{}) []interface{} + RenderArgsHook func(kvList []any) []any // MaxLogDepth tells funcr how many levels of nested fields (e.g. a struct // that contains a struct, etc.) it may log. Every time it finds a struct, @@ -163,7 +168,7 @@ func (l fnlogger) WithName(name string) logr.LogSink { return &l } -func (l fnlogger) WithValues(kvList ...interface{}) logr.LogSink { +func (l fnlogger) WithValues(kvList ...any) logr.LogSink { l.Formatter.AddValues(kvList) return &l } @@ -173,12 +178,12 @@ func (l fnlogger) WithCallDepth(depth int) logr.LogSink { return &l } -func (l fnlogger) Info(level int, msg string, kvList ...interface{}) { +func (l fnlogger) Info(level int, msg string, kvList ...any) { prefix, args := l.FormatInfo(level, msg, kvList) l.write(prefix, args) } -func (l fnlogger) Error(err error, msg string, kvList ...interface{}) { +func (l fnlogger) Error(err error, msg string, kvList ...any) { prefix, args := l.FormatError(err, msg, kvList) l.write(prefix, args) } @@ -213,6 +218,10 @@ func newFormatter(opts Options, outfmt outputFormat) Formatter { if opts.MaxLogDepth == 0 { opts.MaxLogDepth = defaultMaxLogDepth } + if opts.LogInfoLevel == nil { + opts.LogInfoLevel = new(string) + *opts.LogInfoLevel = "level" + } f := Formatter{ outputFormat: outfmt, prefix: "", @@ -227,12 +236,15 @@ func newFormatter(opts Options, outfmt outputFormat) Formatter { // implementation. It should be constructed with NewFormatter. Some of // its methods directly implement logr.LogSink. type Formatter struct { - outputFormat outputFormat - prefix string - values []interface{} - valuesStr string - depth int - opts *Options + outputFormat outputFormat + prefix string + values []any + valuesStr string + parentValuesStr string + depth int + opts *Options + group string // for slog groups + groupDepth int } // outputFormat indicates which outputFormat to use. @@ -246,40 +258,69 @@ const ( ) // PseudoStruct is a list of key-value pairs that gets logged as a struct. -type PseudoStruct []interface{} +type PseudoStruct []any // render produces a log line, ready to use. -func (f Formatter) render(builtins, args []interface{}) string { +func (f Formatter) render(builtins, args []any) string { // Empirically bytes.Buffer is faster than strings.Builder for this. buf := bytes.NewBuffer(make([]byte, 0, 1024)) if f.outputFormat == outputJSON { - buf.WriteByte('{') + buf.WriteByte('{') // for the whole line } + vals := builtins if hook := f.opts.RenderBuiltinsHook; hook != nil { vals = hook(f.sanitize(vals)) } f.flatten(buf, vals, false, false) // keys are ours, no need to escape continuing := len(builtins) > 0 - if len(f.valuesStr) > 0 { + + if f.parentValuesStr != "" { if continuing { - if f.outputFormat == outputJSON { - buf.WriteByte(',') - } else { - buf.WriteByte(' ') - } + buf.WriteByte(f.comma()) } + buf.WriteString(f.parentValuesStr) continuing = true + } + + groupDepth := f.groupDepth + if f.group != "" { + if f.valuesStr != "" || len(args) != 0 { + if continuing { + buf.WriteByte(f.comma()) + } + buf.WriteString(f.quoted(f.group, true)) // escape user-provided keys + buf.WriteByte(f.colon()) + buf.WriteByte('{') // for the group + continuing = false + } else { + // The group was empty + groupDepth-- + } + } + + if f.valuesStr != "" { + if continuing { + buf.WriteByte(f.comma()) + } buf.WriteString(f.valuesStr) + continuing = true } + vals = args if hook := f.opts.RenderArgsHook; hook != nil { vals = hook(f.sanitize(vals)) } f.flatten(buf, vals, continuing, true) // escape user-provided keys + + for i := 0; i < groupDepth; i++ { + buf.WriteByte('}') // for the groups + } + if f.outputFormat == outputJSON { - buf.WriteByte('}') + buf.WriteByte('}') // for the whole line } + return buf.String() } @@ -292,15 +333,22 @@ func (f Formatter) render(builtins, args []interface{}) string { // This function returns a potentially modified version of kvList, which // ensures that there is a value for every key (adding a value if needed) and // that each key is a string (substituting a key if needed). -func (f Formatter) flatten(buf *bytes.Buffer, kvList []interface{}, continuing bool, escapeKeys bool) []interface{} { +func (f Formatter) flatten(buf *bytes.Buffer, kvList []any, continuing bool, escapeKeys bool) []any { // This logic overlaps with sanitize() but saves one type-cast per key, // which can be measurable. if len(kvList)%2 != 0 { kvList = append(kvList, noValue) } + copied := false for i := 0; i < len(kvList); i += 2 { k, ok := kvList[i].(string) if !ok { + if !copied { + newList := make([]any, len(kvList)) + copy(newList, kvList) + kvList = newList + copied = true + } k = f.nonStringKey(kvList[i]) kvList[i] = k } @@ -308,7 +356,7 @@ func (f Formatter) flatten(buf *bytes.Buffer, kvList []interface{}, continuing b if i > 0 || continuing { if f.outputFormat == outputJSON { - buf.WriteByte(',') + buf.WriteByte(f.comma()) } else { // In theory the format could be something we don't understand. In // practice, we control it, so it won't be. @@ -316,25 +364,36 @@ func (f Formatter) flatten(buf *bytes.Buffer, kvList []interface{}, continuing b } } - if escapeKeys { - buf.WriteString(prettyString(k)) - } else { - // this is faster - buf.WriteByte('"') - buf.WriteString(k) - buf.WriteByte('"') - } - if f.outputFormat == outputJSON { - buf.WriteByte(':') - } else { - buf.WriteByte('=') - } + buf.WriteString(f.quoted(k, escapeKeys)) + buf.WriteByte(f.colon()) buf.WriteString(f.pretty(v)) } return kvList } -func (f Formatter) pretty(value interface{}) string { +func (f Formatter) quoted(str string, escape bool) string { + if escape { + return prettyString(str) + } + // this is faster + return `"` + str + `"` +} + +func (f Formatter) comma() byte { + if f.outputFormat == outputJSON { + return ',' + } + return ' ' +} + +func (f Formatter) colon() byte { + if f.outputFormat == outputJSON { + return ':' + } + return '=' +} + +func (f Formatter) pretty(value any) string { return f.prettyWithFlags(value, 0, 0) } @@ -343,7 +402,7 @@ const ( ) // TODO: This is not fast. Most of the overhead goes here. -func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) string { +func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string { if depth > f.opts.MaxLogDepth { return `""` } @@ -407,12 +466,12 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s } for i := 0; i < len(v); i += 2 { if i > 0 { - buf.WriteByte(',') + buf.WriteByte(f.comma()) } k, _ := v[i].(string) // sanitize() above means no need to check success // arbitrary keys might need escaping buf.WriteString(prettyString(k)) - buf.WriteByte(':') + buf.WriteByte(f.colon()) buf.WriteString(f.prettyWithFlags(v[i+1], 0, depth+1)) } if flags&flagRawStruct == 0 { @@ -481,7 +540,7 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s continue } if printComma { - buf.WriteByte(',') + buf.WriteByte(f.comma()) } printComma = true // if we got here, we are rendering a field if fld.Anonymous && fld.Type.Kind() == reflect.Struct && name == "" { @@ -492,10 +551,8 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s name = fld.Name } // field names can't contain characters which need escaping - buf.WriteByte('"') - buf.WriteString(name) - buf.WriteByte('"') - buf.WriteByte(':') + buf.WriteString(f.quoted(name, false)) + buf.WriteByte(f.colon()) buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), 0, depth+1)) } if flags&flagRawStruct == 0 { @@ -520,7 +577,7 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s buf.WriteByte('[') for i := 0; i < v.Len(); i++ { if i > 0 { - buf.WriteByte(',') + buf.WriteByte(f.comma()) } e := v.Index(i) buf.WriteString(f.prettyWithFlags(e.Interface(), 0, depth+1)) @@ -534,7 +591,7 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s i := 0 for it.Next() { if i > 0 { - buf.WriteByte(',') + buf.WriteByte(f.comma()) } // If a map key supports TextMarshaler, use it. keystr := "" @@ -556,7 +613,7 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s } } buf.WriteString(keystr) - buf.WriteByte(':') + buf.WriteByte(f.colon()) buf.WriteString(f.prettyWithFlags(it.Value().Interface(), 0, depth+1)) i++ } @@ -614,7 +671,7 @@ func isEmpty(v reflect.Value) bool { return false } -func invokeMarshaler(m logr.Marshaler) (ret interface{}) { +func invokeMarshaler(m logr.Marshaler) (ret any) { defer func() { if r := recover(); r != nil { ret = fmt.Sprintf("", r) @@ -675,12 +732,12 @@ func (f Formatter) caller() Caller { const noValue = "" -func (f Formatter) nonStringKey(v interface{}) string { +func (f Formatter) nonStringKey(v any) string { return fmt.Sprintf("", f.snippet(v)) } // snippet produces a short snippet string of an arbitrary value. -func (f Formatter) snippet(v interface{}) string { +func (f Formatter) snippet(v any) string { const snipLen = 16 snip := f.pretty(v) @@ -693,7 +750,7 @@ func (f Formatter) snippet(v interface{}) string { // sanitize ensures that a list of key-value pairs has a value for every key // (adding a value if needed) and that each key is a string (substituting a key // if needed). -func (f Formatter) sanitize(kvList []interface{}) []interface{} { +func (f Formatter) sanitize(kvList []any) []any { if len(kvList)%2 != 0 { kvList = append(kvList, noValue) } @@ -706,6 +763,53 @@ func (f Formatter) sanitize(kvList []interface{}) []interface{} { return kvList } +// startGroup opens a new group scope (basically a sub-struct), which locks all +// the current saved values and starts them anew. This is needed to satisfy +// slog. +func (f *Formatter) startGroup(group string) { + // Unnamed groups are just inlined. + if group == "" { + return + } + + // Any saved values can no longer be changed. + buf := bytes.NewBuffer(make([]byte, 0, 1024)) + continuing := false + + if f.parentValuesStr != "" { + buf.WriteString(f.parentValuesStr) + continuing = true + } + + if f.group != "" && f.valuesStr != "" { + if continuing { + buf.WriteByte(f.comma()) + } + buf.WriteString(f.quoted(f.group, true)) // escape user-provided keys + buf.WriteByte(f.colon()) + buf.WriteByte('{') // for the group + continuing = false + } + + if f.valuesStr != "" { + if continuing { + buf.WriteByte(f.comma()) + } + buf.WriteString(f.valuesStr) + } + + // NOTE: We don't close the scope here - that's done later, when a log line + // is actually rendered (because we have N scopes to close). + + f.parentValuesStr = buf.String() + + // Start collecting new values. + f.group = group + f.groupDepth++ + f.valuesStr = "" + f.values = nil +} + // Init configures this Formatter from runtime info, such as the call depth // imposed by logr itself. // Note that this receiver is a pointer, so depth can be saved. @@ -727,8 +831,8 @@ func (f Formatter) GetDepth() int { // FormatInfo renders an Info log message into strings. The prefix will be // empty when no names were set (via AddNames), or when the output is // configured for JSON. -func (f Formatter) FormatInfo(level int, msg string, kvList []interface{}) (prefix, argsStr string) { - args := make([]interface{}, 0, 64) // using a constant here impacts perf +func (f Formatter) FormatInfo(level int, msg string, kvList []any) (prefix, argsStr string) { + args := make([]any, 0, 64) // using a constant here impacts perf prefix = f.prefix if f.outputFormat == outputJSON { args = append(args, "logger", prefix) @@ -740,15 +844,18 @@ func (f Formatter) FormatInfo(level int, msg string, kvList []interface{}) (pref if policy := f.opts.LogCaller; policy == All || policy == Info { args = append(args, "caller", f.caller()) } - args = append(args, "level", level, "msg", msg) + if key := *f.opts.LogInfoLevel; key != "" { + args = append(args, key, level) + } + args = append(args, "msg", msg) return prefix, f.render(args, kvList) } // FormatError renders an Error log message into strings. The prefix will be -// empty when no names were set (via AddNames), or when the output is +// empty when no names were set (via AddNames), or when the output is // configured for JSON. -func (f Formatter) FormatError(err error, msg string, kvList []interface{}) (prefix, argsStr string) { - args := make([]interface{}, 0, 64) // using a constant here impacts perf +func (f Formatter) FormatError(err error, msg string, kvList []any) (prefix, argsStr string) { + args := make([]any, 0, 64) // using a constant here impacts perf prefix = f.prefix if f.outputFormat == outputJSON { args = append(args, "logger", prefix) @@ -761,12 +868,12 @@ func (f Formatter) FormatError(err error, msg string, kvList []interface{}) (pre args = append(args, "caller", f.caller()) } args = append(args, "msg", msg) - var loggableErr interface{} + var loggableErr any if err != nil { loggableErr = err.Error() } args = append(args, "error", loggableErr) - return f.prefix, f.render(args, kvList) + return prefix, f.render(args, kvList) } // AddName appends the specified name. funcr uses '/' characters to separate @@ -781,7 +888,7 @@ func (f *Formatter) AddName(name string) { // AddValues adds key-value pairs to the set of saved values to be logged with // each log line. -func (f *Formatter) AddValues(kvList []interface{}) { +func (f *Formatter) AddValues(kvList []any) { // Three slice args forces a copy. n := len(f.values) f.values = append(f.values[:n:n], kvList...) diff --git a/vendor/github.com/go-logr/logr/funcr/slogsink.go b/vendor/github.com/go-logr/logr/funcr/slogsink.go new file mode 100644 index 000000000..7bd84761e --- /dev/null +++ b/vendor/github.com/go-logr/logr/funcr/slogsink.go @@ -0,0 +1,105 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2023 The logr 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 funcr + +import ( + "context" + "log/slog" + + "github.com/go-logr/logr" +) + +var _ logr.SlogSink = &fnlogger{} + +const extraSlogSinkDepth = 3 // 2 for slog, 1 for SlogSink + +func (l fnlogger) Handle(_ context.Context, record slog.Record) error { + kvList := make([]any, 0, 2*record.NumAttrs()) + record.Attrs(func(attr slog.Attr) bool { + kvList = attrToKVs(attr, kvList) + return true + }) + + if record.Level >= slog.LevelError { + l.WithCallDepth(extraSlogSinkDepth).Error(nil, record.Message, kvList...) + } else { + level := l.levelFromSlog(record.Level) + l.WithCallDepth(extraSlogSinkDepth).Info(level, record.Message, kvList...) + } + return nil +} + +func (l fnlogger) WithAttrs(attrs []slog.Attr) logr.SlogSink { + kvList := make([]any, 0, 2*len(attrs)) + for _, attr := range attrs { + kvList = attrToKVs(attr, kvList) + } + l.AddValues(kvList) + return &l +} + +func (l fnlogger) WithGroup(name string) logr.SlogSink { + l.startGroup(name) + return &l +} + +// attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups +// and other details of slog. +func attrToKVs(attr slog.Attr, kvList []any) []any { + attrVal := attr.Value.Resolve() + if attrVal.Kind() == slog.KindGroup { + groupVal := attrVal.Group() + grpKVs := make([]any, 0, 2*len(groupVal)) + for _, attr := range groupVal { + grpKVs = attrToKVs(attr, grpKVs) + } + if attr.Key == "" { + // slog says we have to inline these + kvList = append(kvList, grpKVs...) + } else { + kvList = append(kvList, attr.Key, PseudoStruct(grpKVs)) + } + } else if attr.Key != "" { + kvList = append(kvList, attr.Key, attrVal.Any()) + } + + return kvList +} + +// levelFromSlog adjusts the level by the logger's verbosity and negates it. +// It ensures that the result is >= 0. This is necessary because the result is +// passed to a LogSink and that API did not historically document whether +// levels could be negative or what that meant. +// +// Some example usage: +// +// logrV0 := getMyLogger() +// logrV2 := logrV0.V(2) +// slogV2 := slog.New(logr.ToSlogHandler(logrV2)) +// slogV2.Debug("msg") // =~ logrV2.V(4) =~ logrV0.V(6) +// slogV2.Info("msg") // =~ logrV2.V(0) =~ logrV0.V(2) +// slogv2.Warn("msg") // =~ logrV2.V(-4) =~ logrV0.V(0) +func (l fnlogger) levelFromSlog(level slog.Level) int { + result := -level + if result < 0 { + result = 0 // because LogSink doesn't expect negative V levels + } + return int(result) +} diff --git a/vendor/github.com/go-logr/logr/logr.go b/vendor/github.com/go-logr/logr/logr.go index e027aea3f..b4428e105 100644 --- a/vendor/github.com/go-logr/logr/logr.go +++ b/vendor/github.com/go-logr/logr/logr.go @@ -127,9 +127,9 @@ limitations under the License. // such a value can call its methods without having to check whether the // instance is ready for use. // -// Calling methods with the null logger (Logger{}) as instance will crash -// because it has no LogSink. Therefore this null logger should never be passed -// around. For cases where passing a logger is optional, a pointer to Logger +// The zero logger (= Logger{}) is identical to Discard() and discards all log +// entries. Code that receives a Logger by value can simply call it, the methods +// will never crash. For cases where passing a logger is optional, a pointer to Logger // should be used. // // # Key Naming Conventions @@ -207,10 +207,6 @@ limitations under the License. // those. package logr -import ( - "context" -) - // New returns a new Logger instance. This is primarily used by libraries // implementing LogSink, rather than end users. Passing a nil sink will create // a Logger which discards all log lines. @@ -258,6 +254,12 @@ type Logger struct { // Enabled tests whether this Logger is enabled. For example, commandline // flags might be used to set the logging verbosity and disable some info logs. func (l Logger) Enabled() bool { + // Some implementations of LogSink look at the caller in Enabled (e.g. + // different verbosity levels per package or file), but we only pass one + // CallDepth in (via Init). This means that all calls from Logger to the + // LogSink's Enabled, Info, and Error methods must have the same number of + // frames. In other words, Logger methods can't call other Logger methods + // which call these LogSink methods unless we do it the same in all paths. return l.sink != nil && l.sink.Enabled(l.level) } @@ -267,11 +269,11 @@ func (l Logger) Enabled() bool { // line. The key/value pairs can then be used to add additional variable // information. The key/value pairs must alternate string keys and arbitrary // values. -func (l Logger) Info(msg string, keysAndValues ...interface{}) { +func (l Logger) Info(msg string, keysAndValues ...any) { if l.sink == nil { return } - if l.Enabled() { + if l.sink.Enabled(l.level) { // see comment in Enabled if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { withHelper.GetCallStackHelper()() } @@ -289,7 +291,7 @@ func (l Logger) Info(msg string, keysAndValues ...interface{}) { // while the err argument should be used to attach the actual error that // triggered this log line, if present. The err parameter is optional // and nil may be passed instead of an error instance. -func (l Logger) Error(err error, msg string, keysAndValues ...interface{}) { +func (l Logger) Error(err error, msg string, keysAndValues ...any) { if l.sink == nil { return } @@ -314,9 +316,16 @@ func (l Logger) V(level int) Logger { return l } +// GetV returns the verbosity level of the logger. If the logger's LogSink is +// nil as in the Discard logger, this will always return 0. +func (l Logger) GetV() int { + // 0 if l.sink nil because of the if check in V above. + return l.level +} + // WithValues returns a new Logger instance with additional key/value pairs. // See Info for documentation on how key/value pairs work. -func (l Logger) WithValues(keysAndValues ...interface{}) Logger { +func (l Logger) WithValues(keysAndValues ...any) Logger { if l.sink == nil { return l } @@ -397,45 +406,6 @@ func (l Logger) IsZero() bool { return l.sink == nil } -// contextKey is how we find Loggers in a context.Context. -type contextKey struct{} - -// FromContext returns a Logger from ctx or an error if no Logger is found. -func FromContext(ctx context.Context) (Logger, error) { - if v, ok := ctx.Value(contextKey{}).(Logger); ok { - return v, nil - } - - return Logger{}, notFoundError{} -} - -// notFoundError exists to carry an IsNotFound method. -type notFoundError struct{} - -func (notFoundError) Error() string { - return "no logr.Logger was present" -} - -func (notFoundError) IsNotFound() bool { - return true -} - -// FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this -// returns a Logger that discards all log messages. -func FromContextOrDiscard(ctx context.Context) Logger { - if v, ok := ctx.Value(contextKey{}).(Logger); ok { - return v - } - - return Discard() -} - -// NewContext returns a new Context, derived from ctx, which carries the -// provided Logger. -func NewContext(ctx context.Context, logger Logger) context.Context { - return context.WithValue(ctx, contextKey{}, logger) -} - // RuntimeInfo holds information that the logr "core" library knows which // LogSinks might want to know. type RuntimeInfo struct { @@ -467,15 +437,15 @@ type LogSink interface { // The level argument is provided for optional logging. This method will // only be called when Enabled(level) is true. See Logger.Info for more // details. - Info(level int, msg string, keysAndValues ...interface{}) + Info(level int, msg string, keysAndValues ...any) // Error logs an error, with the given message and key/value pairs as // context. See Logger.Error for more details. - Error(err error, msg string, keysAndValues ...interface{}) + Error(err error, msg string, keysAndValues ...any) // WithValues returns a new LogSink with additional key/value pairs. See // Logger.WithValues for more details. - WithValues(keysAndValues ...interface{}) LogSink + WithValues(keysAndValues ...any) LogSink // WithName returns a new LogSink with the specified name appended. See // Logger.WithName for more details. @@ -546,5 +516,5 @@ type Marshaler interface { // with exported fields // // It may return any value of any type. - MarshalLog() interface{} + MarshalLog() any } diff --git a/vendor/github.com/go-logr/logr/sloghandler.go b/vendor/github.com/go-logr/logr/sloghandler.go new file mode 100644 index 000000000..82d1ba494 --- /dev/null +++ b/vendor/github.com/go-logr/logr/sloghandler.go @@ -0,0 +1,192 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2023 The logr 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 logr + +import ( + "context" + "log/slog" +) + +type slogHandler struct { + // May be nil, in which case all logs get discarded. + sink LogSink + // Non-nil if sink is non-nil and implements SlogSink. + slogSink SlogSink + + // groupPrefix collects values from WithGroup calls. It gets added as + // prefix to value keys when handling a log record. + groupPrefix string + + // levelBias can be set when constructing the handler to influence the + // slog.Level of log records. A positive levelBias reduces the + // slog.Level value. slog has no API to influence this value after the + // handler got created, so it can only be set indirectly through + // Logger.V. + levelBias slog.Level +} + +var _ slog.Handler = &slogHandler{} + +// groupSeparator is used to concatenate WithGroup names and attribute keys. +const groupSeparator = "." + +// GetLevel is used for black box unit testing. +func (l *slogHandler) GetLevel() slog.Level { + return l.levelBias +} + +func (l *slogHandler) Enabled(_ context.Context, level slog.Level) bool { + return l.sink != nil && (level >= slog.LevelError || l.sink.Enabled(l.levelFromSlog(level))) +} + +func (l *slogHandler) Handle(ctx context.Context, record slog.Record) error { + if l.slogSink != nil { + // Only adjust verbosity level of log entries < slog.LevelError. + if record.Level < slog.LevelError { + record.Level -= l.levelBias + } + return l.slogSink.Handle(ctx, record) + } + + // No need to check for nil sink here because Handle will only be called + // when Enabled returned true. + + kvList := make([]any, 0, 2*record.NumAttrs()) + record.Attrs(func(attr slog.Attr) bool { + kvList = attrToKVs(attr, l.groupPrefix, kvList) + return true + }) + if record.Level >= slog.LevelError { + l.sinkWithCallDepth().Error(nil, record.Message, kvList...) + } else { + level := l.levelFromSlog(record.Level) + l.sinkWithCallDepth().Info(level, record.Message, kvList...) + } + return nil +} + +// sinkWithCallDepth adjusts the stack unwinding so that when Error or Info +// are called by Handle, code in slog gets skipped. +// +// This offset currently (Go 1.21.0) works for calls through +// slog.New(ToSlogHandler(...)). There's no guarantee that the call +// chain won't change. Wrapping the handler will also break unwinding. It's +// still better than not adjusting at all.... +// +// This cannot be done when constructing the handler because FromSlogHandler needs +// access to the original sink without this adjustment. A second copy would +// work, but then WithAttrs would have to be called for both of them. +func (l *slogHandler) sinkWithCallDepth() LogSink { + if sink, ok := l.sink.(CallDepthLogSink); ok { + return sink.WithCallDepth(2) + } + return l.sink +} + +func (l *slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + if l.sink == nil || len(attrs) == 0 { + return l + } + + clone := *l + if l.slogSink != nil { + clone.slogSink = l.slogSink.WithAttrs(attrs) + clone.sink = clone.slogSink + } else { + kvList := make([]any, 0, 2*len(attrs)) + for _, attr := range attrs { + kvList = attrToKVs(attr, l.groupPrefix, kvList) + } + clone.sink = l.sink.WithValues(kvList...) + } + return &clone +} + +func (l *slogHandler) WithGroup(name string) slog.Handler { + if l.sink == nil { + return l + } + if name == "" { + // slog says to inline empty groups + return l + } + clone := *l + if l.slogSink != nil { + clone.slogSink = l.slogSink.WithGroup(name) + clone.sink = clone.slogSink + } else { + clone.groupPrefix = addPrefix(clone.groupPrefix, name) + } + return &clone +} + +// attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups +// and other details of slog. +func attrToKVs(attr slog.Attr, groupPrefix string, kvList []any) []any { + attrVal := attr.Value.Resolve() + if attrVal.Kind() == slog.KindGroup { + groupVal := attrVal.Group() + grpKVs := make([]any, 0, 2*len(groupVal)) + prefix := groupPrefix + if attr.Key != "" { + prefix = addPrefix(groupPrefix, attr.Key) + } + for _, attr := range groupVal { + grpKVs = attrToKVs(attr, prefix, grpKVs) + } + kvList = append(kvList, grpKVs...) + } else if attr.Key != "" { + kvList = append(kvList, addPrefix(groupPrefix, attr.Key), attrVal.Any()) + } + + return kvList +} + +func addPrefix(prefix, name string) string { + if prefix == "" { + return name + } + if name == "" { + return prefix + } + return prefix + groupSeparator + name +} + +// levelFromSlog adjusts the level by the logger's verbosity and negates it. +// It ensures that the result is >= 0. This is necessary because the result is +// passed to a LogSink and that API did not historically document whether +// levels could be negative or what that meant. +// +// Some example usage: +// +// logrV0 := getMyLogger() +// logrV2 := logrV0.V(2) +// slogV2 := slog.New(logr.ToSlogHandler(logrV2)) +// slogV2.Debug("msg") // =~ logrV2.V(4) =~ logrV0.V(6) +// slogV2.Info("msg") // =~ logrV2.V(0) =~ logrV0.V(2) +// slogv2.Warn("msg") // =~ logrV2.V(-4) =~ logrV0.V(0) +func (l *slogHandler) levelFromSlog(level slog.Level) int { + result := -level + result += l.levelBias // in case the original Logger had a V level + if result < 0 { + result = 0 // because LogSink doesn't expect negative V levels + } + return int(result) +} diff --git a/vendor/github.com/go-logr/logr/slogr.go b/vendor/github.com/go-logr/logr/slogr.go new file mode 100644 index 000000000..28a83d024 --- /dev/null +++ b/vendor/github.com/go-logr/logr/slogr.go @@ -0,0 +1,100 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2023 The logr 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 logr + +import ( + "context" + "log/slog" +) + +// FromSlogHandler returns a Logger which writes to the slog.Handler. +// +// The logr verbosity level is mapped to slog levels such that V(0) becomes +// slog.LevelInfo and V(4) becomes slog.LevelDebug. +func FromSlogHandler(handler slog.Handler) Logger { + if handler, ok := handler.(*slogHandler); ok { + if handler.sink == nil { + return Discard() + } + return New(handler.sink).V(int(handler.levelBias)) + } + return New(&slogSink{handler: handler}) +} + +// ToSlogHandler returns a slog.Handler which writes to the same sink as the Logger. +// +// The returned logger writes all records with level >= slog.LevelError as +// error log entries with LogSink.Error, regardless of the verbosity level of +// the Logger: +// +// logger := +// slog.New(ToSlogHandler(logger.V(10))).Error(...) -> logSink.Error(...) +// +// The level of all other records gets reduced by the verbosity +// level of the Logger and the result is negated. If it happens +// to be negative, then it gets replaced by zero because a LogSink +// is not expected to handled negative levels: +// +// slog.New(ToSlogHandler(logger)).Debug(...) -> logger.GetSink().Info(level=4, ...) +// slog.New(ToSlogHandler(logger)).Warning(...) -> logger.GetSink().Info(level=0, ...) +// slog.New(ToSlogHandler(logger)).Info(...) -> logger.GetSink().Info(level=0, ...) +// slog.New(ToSlogHandler(logger.V(4))).Info(...) -> logger.GetSink().Info(level=4, ...) +func ToSlogHandler(logger Logger) slog.Handler { + if sink, ok := logger.GetSink().(*slogSink); ok && logger.GetV() == 0 { + return sink.handler + } + + handler := &slogHandler{sink: logger.GetSink(), levelBias: slog.Level(logger.GetV())} + if slogSink, ok := handler.sink.(SlogSink); ok { + handler.slogSink = slogSink + } + return handler +} + +// SlogSink is an optional interface that a LogSink can implement to support +// logging through the slog.Logger or slog.Handler APIs better. It then should +// also support special slog values like slog.Group. When used as a +// slog.Handler, the advantages are: +// +// - stack unwinding gets avoided in favor of logging the pre-recorded PC, +// as intended by slog +// - proper grouping of key/value pairs via WithGroup +// - verbosity levels > slog.LevelInfo can be recorded +// - less overhead +// +// Both APIs (Logger and slog.Logger/Handler) then are supported equally +// well. Developers can pick whatever API suits them better and/or mix +// packages which use either API in the same binary with a common logging +// implementation. +// +// This interface is necessary because the type implementing the LogSink +// interface cannot also implement the slog.Handler interface due to the +// different prototype of the common Enabled method. +// +// An implementation could support both interfaces in two different types, but then +// additional interfaces would be needed to convert between those types in FromSlogHandler +// and ToSlogHandler. +type SlogSink interface { + LogSink + + Handle(ctx context.Context, record slog.Record) error + WithAttrs(attrs []slog.Attr) SlogSink + WithGroup(name string) SlogSink +} diff --git a/vendor/github.com/go-logr/logr/slogsink.go b/vendor/github.com/go-logr/logr/slogsink.go new file mode 100644 index 000000000..4060fcbc2 --- /dev/null +++ b/vendor/github.com/go-logr/logr/slogsink.go @@ -0,0 +1,120 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2023 The logr 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 logr + +import ( + "context" + "log/slog" + "runtime" + "time" +) + +var ( + _ LogSink = &slogSink{} + _ CallDepthLogSink = &slogSink{} + _ Underlier = &slogSink{} +) + +// Underlier is implemented by the LogSink returned by NewFromLogHandler. +type Underlier interface { + // GetUnderlying returns the Handler used by the LogSink. + GetUnderlying() slog.Handler +} + +const ( + // nameKey is used to log the `WithName` values as an additional attribute. + nameKey = "logger" + + // errKey is used to log the error parameter of Error as an additional attribute. + errKey = "err" +) + +type slogSink struct { + callDepth int + name string + handler slog.Handler +} + +func (l *slogSink) Init(info RuntimeInfo) { + l.callDepth = info.CallDepth +} + +func (l *slogSink) GetUnderlying() slog.Handler { + return l.handler +} + +func (l *slogSink) WithCallDepth(depth int) LogSink { + newLogger := *l + newLogger.callDepth += depth + return &newLogger +} + +func (l *slogSink) Enabled(level int) bool { + return l.handler.Enabled(context.Background(), slog.Level(-level)) +} + +func (l *slogSink) Info(level int, msg string, kvList ...interface{}) { + l.log(nil, msg, slog.Level(-level), kvList...) +} + +func (l *slogSink) Error(err error, msg string, kvList ...interface{}) { + l.log(err, msg, slog.LevelError, kvList...) +} + +func (l *slogSink) log(err error, msg string, level slog.Level, kvList ...interface{}) { + var pcs [1]uintptr + // skip runtime.Callers, this function, Info/Error, and all helper functions above that. + runtime.Callers(3+l.callDepth, pcs[:]) + + record := slog.NewRecord(time.Now(), level, msg, pcs[0]) + if l.name != "" { + record.AddAttrs(slog.String(nameKey, l.name)) + } + if err != nil { + record.AddAttrs(slog.Any(errKey, err)) + } + record.Add(kvList...) + _ = l.handler.Handle(context.Background(), record) +} + +func (l slogSink) WithName(name string) LogSink { + if l.name != "" { + l.name += "/" + } + l.name += name + return &l +} + +func (l slogSink) WithValues(kvList ...interface{}) LogSink { + l.handler = l.handler.WithAttrs(kvListToAttrs(kvList...)) + return &l +} + +func kvListToAttrs(kvList ...interface{}) []slog.Attr { + // We don't need the record itself, only its Add method. + record := slog.NewRecord(time.Time{}, 0, "", 0) + record.Add(kvList...) + attrs := make([]slog.Attr, 0, record.NumAttrs()) + record.Attrs(func(attr slog.Attr) bool { + attrs = append(attrs, attr) + return true + }) + return attrs +} diff --git a/vendor/github.com/go-openapi/errors/.golangci.yml b/vendor/github.com/go-openapi/errors/.golangci.yml index 4e1fc0c7d..cf88ead32 100644 --- a/vendor/github.com/go-openapi/errors/.golangci.yml +++ b/vendor/github.com/go-openapi/errors/.golangci.yml @@ -4,45 +4,59 @@ linters-settings: golint: min-confidence: 0 gocyclo: - min-complexity: 30 + min-complexity: 45 maligned: suggest-new: true dupl: - threshold: 100 + threshold: 200 goconst: min-len: 2 - min-occurrences: 4 + min-occurrences: 3 + linters: enable-all: true disable: + - errname # this repo doesn't follow the convention advised by this linter - maligned + - unparam - lll + - gochecknoinits - gochecknoglobals + - funlen - godox - gocognit - whitespace - wsl - - funlen - - gochecknoglobals - - gochecknoinits - - scopelint - wrapcheck - - exhaustivestruct - - exhaustive - - nlreturn - testpackage - - gci - - gofumpt - - goerr113 + - nlreturn - gomnd - - tparallel + - exhaustivestruct + - goerr113 + - errorlint - nestif - godot - - errorlint + - gofumpt - paralleltest - tparallel - - cyclop - - errname - - varnamelen + - thelper + - ifshort - exhaustruct - - maintidx + - varnamelen + - gci + - depguard + - errchkjson + - inamedparam + - nonamedreturns + - musttag + - ireturn + - forcetypeassert + - cyclop + # deprecated linters + - deadcode + - interfacer + - scopelint + - varcheck + - structcheck + - golint + - nosnakecase diff --git a/vendor/github.com/go-openapi/errors/README.md b/vendor/github.com/go-openapi/errors/README.md index 4aac049e6..6d57ea55c 100644 --- a/vendor/github.com/go-openapi/errors/README.md +++ b/vendor/github.com/go-openapi/errors/README.md @@ -1,11 +1,8 @@ -# OpenAPI errors +# OpenAPI errors [![Build Status](https://github.com/go-openapi/errors/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/errors/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/errors/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/errors) -[![Build Status](https://travis-ci.org/go-openapi/errors.svg?branch=master)](https://travis-ci.org/go-openapi/errors) -[![codecov](https://codecov.io/gh/go-openapi/errors/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/errors) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) [![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/errors/master/LICENSE) [![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/errors.svg)](https://pkg.go.dev/github.com/go-openapi/errors) -[![GolangCI](https://golangci.com/badges/github.com/go-openapi/errors.svg)](https://golangci.com) [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/errors)](https://goreportcard.com/report/github.com/go-openapi/errors) Shared errors and error interface used throughout the various libraries found in the go-openapi toolkit. diff --git a/vendor/github.com/go-openapi/errors/api.go b/vendor/github.com/go-openapi/errors/api.go index 77f1f92c5..5320cb963 100644 --- a/vendor/github.com/go-openapi/errors/api.go +++ b/vendor/github.com/go-openapi/errors/api.go @@ -55,9 +55,15 @@ func (a apiError) MarshalJSON() ([]byte, error) { // New creates a new API error with a code and a message func New(code int32, message string, args ...interface{}) Error { if len(args) > 0 { - return &apiError{code, fmt.Sprintf(message, args...)} + return &apiError{ + code: code, + message: fmt.Sprintf(message, args...), + } + } + return &apiError{ + code: code, + message: message, } - return &apiError{code, message} } // NotFound creates a new not found error @@ -112,7 +118,7 @@ func flattenComposite(errs *CompositeError) *CompositeError { for _, er := range errs.Errors { switch e := er.(type) { case *CompositeError: - if len(e.Errors) > 0 { + if e != nil && len(e.Errors) > 0 { flat := flattenComposite(e) if len(flat.Errors) > 0 { res = append(res, flat.Errors...) @@ -130,10 +136,14 @@ func flattenComposite(errs *CompositeError) *CompositeError { // MethodNotAllowed creates a new method not allowed error func MethodNotAllowed(requested string, allow []string) Error { msg := fmt.Sprintf("method %s is not allowed, but [%s] are", requested, strings.Join(allow, ",")) - return &MethodNotAllowedError{code: http.StatusMethodNotAllowed, Allowed: allow, message: msg} + return &MethodNotAllowedError{ + code: http.StatusMethodNotAllowed, + Allowed: allow, + message: msg, + } } -// ServeError the error handler interface implementation +// ServeError implements the http error handler interface func ServeError(rw http.ResponseWriter, r *http.Request, err error) { rw.Header().Set("Content-Type", "application/json") switch e := err.(type) { diff --git a/vendor/github.com/go-openapi/errors/schema.go b/vendor/github.com/go-openapi/errors/schema.go index da5f6c78c..cf7ac2ed4 100644 --- a/vendor/github.com/go-openapi/errors/schema.go +++ b/vendor/github.com/go-openapi/errors/schema.go @@ -120,6 +120,10 @@ func (c *CompositeError) Error() string { return c.message } +func (c *CompositeError) Unwrap() []error { + return c.Errors +} + // MarshalJSON implements the JSON encoding interface func (c CompositeError) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ @@ -133,7 +137,7 @@ func (c CompositeError) MarshalJSON() ([]byte, error) { func CompositeValidationError(errors ...error) *CompositeError { return &CompositeError{ code: CompositeErrorCode, - Errors: append([]error{}, errors...), + Errors: append(make([]error, 0, len(errors)), errors...), message: "validation failure list", } } diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go index 7df9853de..de60dc7dd 100644 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ b/vendor/github.com/go-openapi/jsonpointer/pointer.go @@ -26,6 +26,7 @@ package jsonpointer import ( + "encoding/json" "errors" "fmt" "reflect" @@ -40,6 +41,7 @@ const ( pointerSeparator = `/` invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator + notFound = `Can't find the pointer in the document` ) var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() @@ -48,13 +50,13 @@ var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() // JSONPointable is an interface for structs to implement when they need to customize the // json pointer process type JSONPointable interface { - JSONLookup(string) (interface{}, error) + JSONLookup(string) (any, error) } // JSONSetable is an interface for structs to implement when they need to customize the // json pointer process type JSONSetable interface { - JSONSet(string, interface{}) error + JSONSet(string, any) error } // New creates a new json pointer for the given string @@ -81,9 +83,7 @@ func (p *Pointer) parse(jsonPointerString string) error { err = errors.New(invalidStart) } else { referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - for _, referenceToken := range referenceTokens[1:] { - p.referenceTokens = append(p.referenceTokens, referenceToken) - } + p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) } } @@ -91,26 +91,26 @@ func (p *Pointer) parse(jsonPointerString string) error { } // Get uses the pointer to retrieve a value from a JSON document -func (p *Pointer) Get(document interface{}) (interface{}, reflect.Kind, error) { +func (p *Pointer) Get(document any) (any, reflect.Kind, error) { return p.get(document, swag.DefaultJSONNameProvider) } // Set uses the pointer to set a value from a JSON document -func (p *Pointer) Set(document interface{}, value interface{}) (interface{}, error) { +func (p *Pointer) Set(document any, value any) (any, error) { return document, p.set(document, value, swag.DefaultJSONNameProvider) } // GetForToken gets a value for a json pointer token 1 level deep -func GetForToken(document interface{}, decodedToken string) (interface{}, reflect.Kind, error) { +func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) } // SetForToken gets a value for a json pointer token 1 level deep -func SetForToken(document interface{}, decodedToken string, value interface{}) (interface{}, error) { +func SetForToken(document any, decodedToken string, value any) (any, error) { return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) } -func getSingleImpl(node interface{}, decodedToken string, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { +func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { rValue := reflect.Indirect(reflect.ValueOf(node)) kind := rValue.Kind() @@ -159,7 +159,7 @@ func getSingleImpl(node interface{}, decodedToken string, nameProvider *swag.Nam } -func setSingleImpl(node, data interface{}, decodedToken string, nameProvider *swag.NameProvider) error { +func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error { rValue := reflect.Indirect(reflect.ValueOf(node)) if ns, ok := node.(JSONSetable); ok { // pointer impl @@ -210,7 +210,7 @@ func setSingleImpl(node, data interface{}, decodedToken string, nameProvider *sw } -func (p *Pointer) get(node interface{}, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { +func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { if nameProvider == nil { nameProvider = swag.DefaultJSONNameProvider @@ -241,7 +241,7 @@ func (p *Pointer) get(node interface{}, nameProvider *swag.NameProvider) (interf return node, kind, nil } -func (p *Pointer) set(node, data interface{}, nameProvider *swag.NameProvider) error { +func (p *Pointer) set(node, data any, nameProvider *swag.NameProvider) error { knd := reflect.ValueOf(node).Kind() if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { @@ -363,6 +363,127 @@ func (p *Pointer) String() string { return pointerString } +func (p *Pointer) Offset(document string) (int64, error) { + dec := json.NewDecoder(strings.NewReader(document)) + var offset int64 + for _, ttk := range p.DecodedTokens() { + tk, err := dec.Token() + if err != nil { + return 0, err + } + switch tk := tk.(type) { + case json.Delim: + switch tk { + case '{': + offset, err = offsetSingleObject(dec, ttk) + if err != nil { + return 0, err + } + case '[': + offset, err = offsetSingleArray(dec, ttk) + if err != nil { + return 0, err + } + default: + return 0, fmt.Errorf("invalid token %#v", tk) + } + default: + return 0, fmt.Errorf("invalid token %#v", tk) + } + } + return offset, nil +} + +func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { + for dec.More() { + offset := dec.InputOffset() + tk, err := dec.Token() + if err != nil { + return 0, err + } + switch tk := tk.(type) { + case json.Delim: + switch tk { + case '{': + if err := drainSingle(dec); err != nil { + return 0, err + } + case '[': + if err := drainSingle(dec); err != nil { + return 0, err + } + } + case string: + if tk == decodedToken { + return offset, nil + } + default: + return 0, fmt.Errorf("invalid token %#v", tk) + } + } + return 0, fmt.Errorf("token reference %q not found", decodedToken) +} + +func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { + idx, err := strconv.Atoi(decodedToken) + if err != nil { + return 0, fmt.Errorf("token reference %q is not a number: %v", decodedToken, err) + } + var i int + for i = 0; i < idx && dec.More(); i++ { + tk, err := dec.Token() + if err != nil { + return 0, err + } + switch tk := tk.(type) { + case json.Delim: + switch tk { + case '{': + if err := drainSingle(dec); err != nil { + return 0, err + } + case '[': + if err := drainSingle(dec); err != nil { + return 0, err + } + } + } + } + if !dec.More() { + return 0, fmt.Errorf("token reference %q not found", decodedToken) + } + return dec.InputOffset(), nil +} + +// drainSingle drains a single level of object or array. +// The decoder has to guarantee the begining delim (i.e. '{' or '[') has been consumed. +func drainSingle(dec *json.Decoder) error { + for dec.More() { + tk, err := dec.Token() + if err != nil { + return err + } + switch tk := tk.(type) { + case json.Delim: + switch tk { + case '{': + if err := drainSingle(dec); err != nil { + return err + } + case '[': + if err := drainSingle(dec); err != nil { + return err + } + } + } + } + // Consumes the ending delim + if _, err := dec.Token(); err != nil { + return err + } + return nil +} + // Specific JSON pointer encoding here // ~0 => ~ // ~1 => / diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go index c458b49b2..582f0fd4c 100644 --- a/vendor/github.com/go-openapi/spec/info.go +++ b/vendor/github.com/go-openapi/spec/info.go @@ -16,6 +16,7 @@ package spec import ( "encoding/json" + "strconv" "strings" "github.com/go-openapi/jsonpointer" @@ -40,6 +41,24 @@ func (e Extensions) GetString(key string) (string, bool) { return "", false } +// GetInt gets a int value from the extensions +func (e Extensions) GetInt(key string) (int, bool) { + realKey := strings.ToLower(key) + + if v, ok := e.GetString(realKey); ok { + if r, err := strconv.Atoi(v); err == nil { + return r, true + } + } + + if v, ok := e[realKey]; ok { + if r, rOk := v.(float64); rOk { + return int(r), true + } + } + return -1, false +} + // GetBool gets a string value from the extensions func (e Extensions) GetBool(key string) (bool, bool) { if v, ok := e[strings.ToLower(key)]; ok { diff --git a/vendor/github.com/go-openapi/spec/properties.go b/vendor/github.com/go-openapi/spec/properties.go index 2af13787a..91d2435f0 100644 --- a/vendor/github.com/go-openapi/spec/properties.go +++ b/vendor/github.com/go-openapi/spec/properties.go @@ -42,8 +42,8 @@ func (items OrderSchemaItems) MarshalJSON() ([]byte, error) { func (items OrderSchemaItems) Len() int { return len(items) } func (items OrderSchemaItems) Swap(i, j int) { items[i], items[j] = items[j], items[i] } func (items OrderSchemaItems) Less(i, j int) (ret bool) { - ii, oki := items[i].Extensions.GetString("x-order") - ij, okj := items[j].Extensions.GetString("x-order") + ii, oki := items[i].Extensions.GetInt("x-order") + ij, okj := items[j].Extensions.GetInt("x-order") if oki { if okj { defer func() { @@ -56,7 +56,7 @@ func (items OrderSchemaItems) Less(i, j int) (ret bool) { ret = reflect.ValueOf(ii).String() < reflect.ValueOf(ij).String() } }() - return reflect.ValueOf(ii).Int() < reflect.ValueOf(ij).Int() + return ii < ij } return true } else if okj { diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go index 4efb6f868..16c3076fe 100644 --- a/vendor/github.com/go-openapi/spec/responses.go +++ b/vendor/github.com/go-openapi/spec/responses.go @@ -19,6 +19,7 @@ import ( "fmt" "reflect" "strconv" + "strings" "github.com/go-openapi/swag" ) @@ -62,6 +63,7 @@ func (r *Responses) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { return err } + if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { return err } @@ -107,20 +109,31 @@ func (r ResponsesProps) MarshalJSON() ([]byte, error) { // UnmarshalJSON unmarshals responses from JSON func (r *ResponsesProps) UnmarshalJSON(data []byte) error { - var res map[string]Response + var res map[string]json.RawMessage if err := json.Unmarshal(data, &res); err != nil { - return nil + return err } + if v, ok := res["default"]; ok { - r.Default = &v + var defaultRes Response + if err := json.Unmarshal(v, &defaultRes); err != nil { + return err + } + r.Default = &defaultRes delete(res, "default") } for k, v := range res { - if nk, err := strconv.Atoi(k); err == nil { - if r.StatusCodeResponses == nil { - r.StatusCodeResponses = map[int]Response{} + if !strings.HasPrefix(k, "x-") { + var statusCodeResp Response + if err := json.Unmarshal(v, &statusCodeResp); err != nil { + return err + } + if nk, err := strconv.Atoi(k); err == nil { + if r.StatusCodeResponses == nil { + r.StatusCodeResponses = map[int]Response{} + } + r.StatusCodeResponses[nk] = statusCodeResp } - r.StatusCodeResponses[nk] = v } } return nil diff --git a/vendor/github.com/go-openapi/strfmt/.golangci.yml b/vendor/github.com/go-openapi/strfmt/.golangci.yml index be4899cb1..22f8d21cc 100644 --- a/vendor/github.com/go-openapi/strfmt/.golangci.yml +++ b/vendor/github.com/go-openapi/strfmt/.golangci.yml @@ -4,56 +4,58 @@ linters-settings: golint: min-confidence: 0 gocyclo: - min-complexity: 31 + min-complexity: 45 maligned: suggest-new: true dupl: - threshold: 100 + threshold: 200 goconst: min-len: 2 - min-occurrences: 4 + min-occurrences: 3 linters: - enable: - - revive - - goimports - - gosec + enable-all: true + disable: + - maligned - unparam - - unconvert - - predeclared - - prealloc - - misspell - - # disable: - # - maligned - # - lll - # - gochecknoinits - # - gochecknoglobals - # - godox - # - gocognit - # - whitespace - # - wsl - # - funlen - # - wrapcheck - # - testpackage - # - nlreturn - # - gofumpt - # - goerr113 - # - gci - # - gomnd - # - godot - # - exhaustivestruct - # - paralleltest - # - varnamelen - # - ireturn - # - exhaustruct - # #- thelper - -issues: - exclude-rules: - - path: bson.go - text: "should be .*ObjectID" - linters: - - golint - - stylecheck - + - lll + - gochecknoinits + - gochecknoglobals + - funlen + - godox + - gocognit + - whitespace + - wsl + - wrapcheck + - testpackage + - nlreturn + - gomnd + - exhaustivestruct + - goerr113 + - errorlint + - nestif + - godot + - gofumpt + - paralleltest + - tparallel + - thelper + - ifshort + - exhaustruct + - varnamelen + - gci + - depguard + - errchkjson + - inamedparam + - nonamedreturns + - musttag + - ireturn + - forcetypeassert + - cyclop + # deprecated linters + - deadcode + - interfacer + - scopelint + - varcheck + - structcheck + - golint + - nosnakecase diff --git a/vendor/github.com/go-openapi/strfmt/README.md b/vendor/github.com/go-openapi/strfmt/README.md index 0cf89d776..f6b39c6c5 100644 --- a/vendor/github.com/go-openapi/strfmt/README.md +++ b/vendor/github.com/go-openapi/strfmt/README.md @@ -1,8 +1,7 @@ -# Strfmt [![Build Status](https://travis-ci.org/go-openapi/strfmt.svg?branch=master)](https://travis-ci.org/go-openapi/strfmt) [![codecov](https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/strfmt) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - +# Strfmt [![Build Status](https://github.com/go-openapi/strfmt/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/strfmt/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/strfmt) +[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) [![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/strfmt/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/strfmt?status.svg)](http://godoc.org/github.com/go-openapi/strfmt) -[![GolangCI](https://golangci.com/badges/github.com/go-openapi/strfmt.svg)](https://golangci.com) [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/strfmt)](https://goreportcard.com/report/github.com/go-openapi/strfmt) This package exposes a registry of data types to support string formats in the go-openapi toolkit. diff --git a/vendor/github.com/go-openapi/strfmt/bson.go b/vendor/github.com/go-openapi/strfmt/bson.go index a8a3604a2..cfa9a526f 100644 --- a/vendor/github.com/go-openapi/strfmt/bson.go +++ b/vendor/github.com/go-openapi/strfmt/bson.go @@ -39,10 +39,10 @@ func IsBSONObjectID(str string) bool { // ObjectId represents a BSON object ID (alias to go.mongodb.org/mongo-driver/bson/primitive.ObjectID) // // swagger:strfmt bsonobjectid -type ObjectId bsonprim.ObjectID //nolint:revive +type ObjectId bsonprim.ObjectID //nolint:revive,stylecheck // NewObjectId creates a ObjectId from a Hex String -func NewObjectId(hex string) ObjectId { //nolint:revive +func NewObjectId(hex string) ObjectId { //nolint:revive,stylecheck oid, err := bsonprim.ObjectIDFromHex(hex) if err != nil { panic(err) @@ -135,7 +135,7 @@ func (id *ObjectId) UnmarshalBSON(data []byte) error { // BSON document if the error is nil. func (id ObjectId) MarshalBSONValue() (bsontype.Type, []byte, error) { oid := bsonprim.ObjectID(id) - return bsontype.ObjectID, oid[:], nil + return bson.TypeObjectID, oid[:], nil } // UnmarshalBSONValue is an interface implemented by types that can unmarshal a diff --git a/vendor/github.com/go-openapi/strfmt/default.go b/vendor/github.com/go-openapi/strfmt/default.go index a89a4de3f..281371406 100644 --- a/vendor/github.com/go-openapi/strfmt/default.go +++ b/vendor/github.com/go-openapi/strfmt/default.go @@ -25,6 +25,7 @@ import ( "strings" "github.com/asaskevich/govalidator" + "github.com/google/uuid" "go.mongodb.org/mongo-driver/bson" ) @@ -57,24 +58,35 @@ const ( // - long top-level domain names (e.g. example.london) are permitted // - symbol unicode points are permitted (e.g. emoji) (not for top-level domain) HostnamePattern = `^([a-zA-Z0-9\p{S}\p{L}]((-?[a-zA-Z0-9\p{S}\p{L}]{0,62})?)|([a-zA-Z0-9\p{S}\p{L}](([a-zA-Z0-9-\p{S}\p{L}]{0,61}[a-zA-Z0-9\p{S}\p{L}])?)(\.)){1,}([a-zA-Z\p{L}]){2,63})$` + + // json null type + jsonNull = "null" +) + +const ( // UUIDPattern Regex for UUID that allows uppercase - UUIDPattern = `(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$` + // + // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + UUIDPattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$)|(^[0-9a-f]{32}$)` + // UUID3Pattern Regex for UUID3 that allows uppercase - UUID3Pattern = `(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$` + // + // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + UUID3Pattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$)|(^[0-9a-f]{12}3[0-9a-f]{3}?[0-9a-f]{16}$)` + // UUID4Pattern Regex for UUID4 that allows uppercase - UUID4Pattern = `(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$` + // + // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + UUID4Pattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$)|(^[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}$)` + // UUID5Pattern Regex for UUID5 that allows uppercase - UUID5Pattern = `(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$` - // json null type - jsonNull = "null" + // + // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. + UUID5Pattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$)|(^[0-9a-f]{12}5[0-9a-f]{3}[89ab][0-9a-f]{15}$)` ) var ( rxHostname = regexp.MustCompile(HostnamePattern) - rxUUID = regexp.MustCompile(UUIDPattern) - rxUUID3 = regexp.MustCompile(UUID3Pattern) - rxUUID4 = regexp.MustCompile(UUID4Pattern) - rxUUID5 = regexp.MustCompile(UUID5Pattern) ) // IsHostname returns true when the string is a valid hostname @@ -99,24 +111,28 @@ func IsHostname(str string) bool { return valid } -// IsUUID returns true is the string matches a UUID, upper case is allowed +// IsUUID returns true is the string matches a UUID (in any version, including v6 and v7), upper case is allowed func IsUUID(str string) bool { - return rxUUID.MatchString(str) + _, err := uuid.Parse(str) + return err == nil } -// IsUUID3 returns true is the string matches a UUID, upper case is allowed +// IsUUID3 returns true is the string matches a UUID v3, upper case is allowed func IsUUID3(str string) bool { - return rxUUID3.MatchString(str) + id, err := uuid.Parse(str) + return err == nil && id.Version() == uuid.Version(3) } -// IsUUID4 returns true is the string matches a UUID, upper case is allowed +// IsUUID4 returns true is the string matches a UUID v4, upper case is allowed func IsUUID4(str string) bool { - return rxUUID4.MatchString(str) + id, err := uuid.Parse(str) + return err == nil && id.Version() == uuid.Version(4) } -// IsUUID5 returns true is the string matches a UUID, upper case is allowed +// IsUUID5 returns true is the string matches a UUID v5, upper case is allowed func IsUUID5(str string) bool { - return rxUUID5.MatchString(str) + id, err := uuid.Parse(str) + return err == nil && id.Version() == uuid.Version(5) } // IsEmail validates an email address. diff --git a/vendor/github.com/go-openapi/strfmt/format.go b/vendor/github.com/go-openapi/strfmt/format.go index ad3b3c355..ce99ce521 100644 --- a/vendor/github.com/go-openapi/strfmt/format.go +++ b/vendor/github.com/go-openapi/strfmt/format.go @@ -94,7 +94,7 @@ func NewSeededFormats(seeds []knownFormat, normalizer NameNormalizer) Registry { } // MapStructureHookFunc is a decode hook function for mapstructure -func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { //nolint:gocyclo,cyclop +func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { return func(from reflect.Type, to reflect.Type, obj interface{}) (interface{}, error) { if from.Kind() != reflect.String { return obj, nil diff --git a/vendor/github.com/go-openapi/strfmt/time.go b/vendor/github.com/go-openapi/strfmt/time.go index 9bef4c3b3..f08ba4da5 100644 --- a/vendor/github.com/go-openapi/strfmt/time.go +++ b/vendor/github.com/go-openapi/strfmt/time.go @@ -76,6 +76,8 @@ const ( ISO8601TimeWithReducedPrecisionLocaltime = "2006-01-02T15:04" // ISO8601TimeUniversalSortableDateTimePattern represents a ISO8601 universal sortable date time pattern. ISO8601TimeUniversalSortableDateTimePattern = "2006-01-02 15:04:05" + // short form of ISO8601TimeUniversalSortableDateTimePattern + ISO8601TimeUniversalSortableDateTimePatternShortForm = "2006-01-02" // DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6 DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$` ) @@ -84,7 +86,7 @@ var ( rxDateTime = regexp.MustCompile(DateTimePattern) // DateTimeFormats is the collection of formats used by ParseDateTime() - DateTimeFormats = []string{RFC3339Micro, RFC3339MicroNoColon, RFC3339Millis, RFC3339MillisNoColon, time.RFC3339, time.RFC3339Nano, ISO8601LocalTime, ISO8601TimeWithReducedPrecision, ISO8601TimeWithReducedPrecisionLocaltime, ISO8601TimeUniversalSortableDateTimePattern} + DateTimeFormats = []string{RFC3339Micro, RFC3339MicroNoColon, RFC3339Millis, RFC3339MillisNoColon, time.RFC3339, time.RFC3339Nano, ISO8601LocalTime, ISO8601TimeWithReducedPrecision, ISO8601TimeWithReducedPrecisionLocaltime, ISO8601TimeUniversalSortableDateTimePattern, ISO8601TimeUniversalSortableDateTimePatternShortForm} // MarshalFormat sets the time resolution format used for marshaling time (set to milliseconds) MarshalFormat = RFC3339Millis @@ -245,7 +247,7 @@ func (t DateTime) MarshalBSONValue() (bsontype.Type, []byte, error) { buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, uint64(i64)) - return bsontype.DateTime, buf, nil + return bson.TypeDateTime, buf, nil } // UnmarshalBSONValue is an interface implemented by types that can unmarshal a @@ -253,7 +255,7 @@ func (t DateTime) MarshalBSONValue() (bsontype.Type, []byte, error) { // assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it // wishes to retain the data after returning. func (t *DateTime) UnmarshalBSONValue(tpe bsontype.Type, data []byte) error { - if tpe == bsontype.Null { + if tpe == bson.TypeNull { *t = DateTime{} return nil } diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go index f78ab684a..d971fbe34 100644 --- a/vendor/github.com/go-openapi/swag/util.go +++ b/vendor/github.com/go-openapi/swag/util.go @@ -341,12 +341,21 @@ type zeroable interface { // IsZero returns true when the value passed into the function is a zero value. // This allows for safer checking of interface values. func IsZero(data interface{}) bool { + v := reflect.ValueOf(data) + // check for nil data + switch v.Kind() { + case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + if v.IsNil() { + return true + } + } + // check for things that have an IsZero method instead if vv, ok := data.(zeroable); ok { return vv.IsZero() } + // continue with slightly more complex reflection - v := reflect.ValueOf(data) switch v.Kind() { case reflect.String: return v.Len() == 0 @@ -358,14 +367,13 @@ func IsZero(data interface{}) bool { return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() case reflect.Struct, reflect.Array: return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) case reflect.Invalid: return true + default: + return false } - return false } // AddInitialisms add additional initialisms diff --git a/vendor/github.com/go-resty/resty/v2/BUILD.bazel b/vendor/github.com/go-resty/resty/v2/BUILD.bazel index 03bb44c3e..f461c29db 100644 --- a/vendor/github.com/go-resty/resty/v2/BUILD.bazel +++ b/vendor/github.com/go-resty/resty/v2/BUILD.bazel @@ -9,6 +9,7 @@ go_library( name = "resty", srcs = [ "client.go", + "digest.go", "middleware.go", "redirect.go", "request.go", @@ -16,6 +17,8 @@ go_library( "resty.go", "retry.go", "trace.go", + "transport_js.go", + "transport_other.go", "transport.go", "transport112.go", "util.go", diff --git a/vendor/github.com/go-resty/resty/v2/LICENSE b/vendor/github.com/go-resty/resty/v2/LICENSE index 27326a653..0c2d38a38 100644 --- a/vendor/github.com/go-resty/resty/v2/LICENSE +++ b/vendor/github.com/go-resty/resty/v2/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015-2021 Jeevanandam M., https://myjeeva.com +Copyright (c) 2015-2023 Jeevanandam M., https://myjeeva.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/go-resty/resty/v2/README.md b/vendor/github.com/go-resty/resty/v2/README.md index 8ec651828..d6d501ef8 100644 --- a/vendor/github.com/go-resty/resty/v2/README.md +++ b/vendor/github.com/go-resty/resty/v2/README.md @@ -4,7 +4,7 @@

      Features section describes in detail about Resty capabilities

      -

      Build Status Code Coverage Go Report Card Release Version GoDoc License Mentioned in Awesome Go

      +

      Build Status Code Coverage Go Report Card Release Version GoDoc License Mentioned in Awesome Go

      Resty Communication Channels

      @@ -13,7 +13,7 @@ ## News - * v2.7.0 [released](https://github.com/go-resty/resty/releases/tag/v2.7.0) and tagged on Nov 03, 2021. + * v2.11.0 [released](https://github.com/go-resty/resty/releases/tag/v2.11.0) and tagged on Dec 27, 2023. * v2.0.0 [released](https://github.com/go-resty/resty/releases/tag/v2.0.0) and tagged on Jul 16, 2019. * v1.12.0 [released](https://github.com/go-resty/resty/releases/tag/v1.12.0) and tagged on Feb 27, 2019. * v1.0 released and tagged on Sep 25, 2017. - Resty's first version was released on Sep 15, 2015 then it grew gradually as a very handy and helpful library. Its been a two years since first release. I'm very thankful to Resty users and its [contributors](https://github.com/go-resty/resty/graphs/contributors). @@ -86,6 +86,8 @@ #### Supported Go Versions +Recommended to use `go1.16` and above. + Initially Resty started supporting `go modules` since `v1.10.0` release. Starting Resty v2 and higher versions, it fully embraces [go modules](https://github.com/golang/go/wiki/Modules) package release. It requires a Go version capable of understanding `/vN` suffixed imports: @@ -108,7 +110,7 @@ Resty author also published following projects for Go Community. ```bash # Go Modules -require github.com/go-resty/resty/v2 v2.7.0 +require github.com/go-resty/resty/v2 v2.11.0 ``` ## Usage @@ -265,7 +267,7 @@ resp, err := client.R(). Post("https://myapp.com/login") // POST of raw bytes for file upload. For example: upload file to Dropbox -fileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf") +fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf") // See we are not setting content-type header, since go-resty automatically detects Content-Type for you resp, err := client.R(). @@ -369,13 +371,13 @@ import jsoniter "github.com/json-iterator/go" json := jsoniter.ConfigCompatibleWithStandardLibrary -client := resty.New() -client.JSONMarshal = json.Marshal -client.JSONUnmarshal = json.Unmarshal +client := resty.New(). + SetJSONMarshaler(json.Marshal). + SetJSONUnmarshaler(json.Unmarshal) // similarly user could do for XML too with - -client.XMLMarshal -client.XMLUnmarshal +client.SetXMLMarshaler(xml.Marshal). + SetXMLUnmarshaler(xml.Unmarshal) ``` ### Multipart File(s) upload @@ -383,8 +385,8 @@ client.XMLUnmarshal #### Using io.Reader ```go -profileImgBytes, _ := ioutil.ReadFile("/Users/jeeva/test-img.png") -notesBytes, _ := ioutil.ReadFile("/Users/jeeva/text-file.txt") +profileImgBytes, _ := os.ReadFile("/Users/jeeva/test-img.png") +notesBytes, _ := os.ReadFile("/Users/jeeva/text-file.txt") // Create a Resty Client client := resty.New() @@ -475,7 +477,7 @@ resp, err := client.R(). client := resty.New() // Setting output directory path, If directory not exists then resty creates one! -// This is optional one, if you're planning using absoule path in +// This is optional one, if you're planning using absolute path in // `Request.SetOutput` and can used together. client.SetOutputDirectory("/Users/jeeva/Downloads") @@ -635,7 +637,7 @@ client.SetCertificates(cert1, cert2, cert3) ```go // Custom Root certificates from string -// You can pass you certificates throught env variables as strings +// You can pass you certificates through env variables as strings // you can add one or more root certificates, its get appended client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----") client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----") @@ -654,7 +656,7 @@ if err != nil { client.SetCertificates(cert1, cert2, cert3) ``` -#### Proxy Settings - Client as well as at Request Level +#### Proxy Settings Default `Go` supports Proxy via environment variable `HTTP_PROXY`. Resty provides support via `SetProxy` & `RemoveProxy`. Choose as per your need. @@ -700,8 +702,9 @@ client. }) ``` -Above setup will result in resty retrying requests returned non nil error up to -3 times with delay increased after each attempt. +By default, resty will retry requests that return a non-nil error during execution. +Therefore, the above setup will result in resty retrying requests with non-nil errors up to 3 times, +with the delay increasing after each attempt. You can optionally provide client with [custom retry conditions](https://pkg.go.dev/github.com/go-resty/resty/v2#RetryConditionFunc): @@ -718,10 +721,26 @@ client.AddRetryCondition( ) ``` -Above example will make resty retry requests ended with `429 Too Many Requests` -status code. +The above example will make resty retry requests that end with a `429 Too Many Requests` status code. +It's important to note that when you specify conditions using `AddRetryCondition`, +it will override the default retry behavior, which retries on errors encountered during the request. +If you want to retry on errors encountered during the request, similar to the default behavior, +you'll need to configure it as follows: + +```go +// Create a Resty Client +client := resty.New() + +client.AddRetryCondition( + func(r *resty.Response, err error) bool { + // Including "err != nil" emulates the default retry behavior for errors encountered during the request. + return err != nil || r.StatusCode() == http.StatusTooManyRequests + }, +) +``` -Multiple retry conditions can be added. +Multiple retry conditions can be added. +Note that if multiple conditions are specified, a retry will occur if any of the conditions are met. It is also possible to use `resty.Backoff(...)` to get arbitrary retry scenarios implemented. [Reference](retry_test.go). @@ -803,7 +822,7 @@ client.SetCookies(cookies) client.SetQueryParam("user_id", "00001") client.SetQueryParams(map[string]string{ // sample of those who use this manner "api_key": "api-key-here", - "api_secert": "api-secert", + "api_secret": "api-secret", }) client.R().SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") @@ -845,7 +864,7 @@ client := resty.New() client.SetTransport(&transport).SetScheme("http").SetHostURL(unixSocket) // No need to write the host's URL on the request, just the path. -client.R().Get("/index.html") +client.R().Get("http://localhost/index.html") ``` #### Bazel Support diff --git a/vendor/github.com/go-resty/resty/v2/client.go b/vendor/github.com/go-resty/resty/v2/client.go index 1a03efa37..446ba8517 100644 --- a/vendor/github.com/go-resty/resty/v2/client.go +++ b/vendor/github.com/go-resty/resty/v2/client.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -14,10 +14,10 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "net/http" "net/url" + "os" "reflect" "regexp" "strings" @@ -55,13 +55,15 @@ var ( hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length") hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding") hdrLocationKey = http.CanonicalHeaderKey("Location") + hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization") + hdrWwwAuthenticateKey = http.CanonicalHeaderKey("WWW-Authenticate") plainTextType = "text/plain; charset=utf-8" jsonContentType = "application/json" formContentType = "application/x-www-form-urlencoded" - jsonCheck = regexp.MustCompile(`(?i:(application|text)/(json|.*\+json|json\-.*)(;|$))`) - xmlCheck = regexp.MustCompile(`(?i:(application|text)/(xml|.*\+xml)(;|$))`) + jsonCheck = regexp.MustCompile(`(?i:(application|text)/(.*json.*)(;|$))`) + xmlCheck = regexp.MustCompile(`(?i:(application|text)/(.*xml.*)(;|$))`) hdrUserAgentValue = "go-resty/" + Version + " (https://github.com/go-resty/resty)" bufPool = &sync.Pool{New: func() interface{} { return &bytes.Buffer{} }} @@ -85,6 +87,9 @@ type ( // ErrorHook type is for reacting to request errors, called after all retries were attempted ErrorHook func(*Request, error) + + // SuccessHook type is for reacting to request success + SuccessHook func(*Client, *Response) ) // Client struct is used to create Resty client with client level settings, @@ -98,6 +103,7 @@ type Client struct { QueryParam url.Values FormData url.Values PathParams map[string]string + RawPathParams map[string]string Header http.Header UserInfo *User Token string @@ -113,6 +119,7 @@ type Client struct { RetryConditions []RetryConditionFunc RetryHooks []OnRetryFunc RetryAfter RetryAfterFunc + RetryResetReaders bool JSONMarshal func(v interface{}) ([]byte, error) JSONUnmarshal func(data []byte, v interface{}) error XMLMarshal func(v interface{}) ([]byte, error) @@ -122,24 +129,30 @@ type Client struct { // value when `SetAuthToken` option is used. HeaderAuthorizationKey string - jsonEscapeHTML bool - setContentLength bool - closeConnection bool - notParseResponse bool - trace bool - debugBodySizeLimit int64 - outputDirectory string - scheme string - log Logger - httpClient *http.Client - proxyURL *url.URL - beforeRequest []RequestMiddleware - udBeforeRequest []RequestMiddleware - preReqHook PreRequestHook - afterResponse []ResponseMiddleware - requestLog RequestLogCallback - responseLog ResponseLogCallback - errorHooks []ErrorHook + jsonEscapeHTML bool + setContentLength bool + closeConnection bool + notParseResponse bool + trace bool + debugBodySizeLimit int64 + outputDirectory string + scheme string + log Logger + httpClient *http.Client + proxyURL *url.URL + beforeRequest []RequestMiddleware + udBeforeRequest []RequestMiddleware + udBeforeRequestLock sync.RWMutex + preReqHook PreRequestHook + successHooks []SuccessHook + afterResponse []ResponseMiddleware + afterResponseLock sync.RWMutex + requestLog RequestLogCallback + responseLog ResponseLogCallback + errorHooks []ErrorHook + invalidHooks []ErrorHook + panicHooks []ErrorHook + rateLimiter RateLimiter } // User type is to hold an username and password information @@ -153,11 +166,12 @@ type User struct { // SetHostURL method is to set Host URL in the client instance. It will be used with request // raised from this client with relative URL -// // Setting HTTP address -// client.SetHostURL("http://myjeeva.com") // -// // Setting HTTPS address -// client.SetHostURL("https://myjeeva.com") +// // Setting HTTP address +// client.SetHostURL("http://myjeeva.com") +// +// // Setting HTTPS address +// client.SetHostURL("https://myjeeva.com") // // Deprecated: use SetBaseURL instead. To be removed in v3.0.0 release. func (c *Client) SetHostURL(url string) *Client { @@ -167,11 +181,12 @@ func (c *Client) SetHostURL(url string) *Client { // SetBaseURL method is to set Base URL in the client instance. It will be used with request // raised from this client with relative URL -// // Setting HTTP address -// client.SetBaseURL("http://myjeeva.com") // -// // Setting HTTPS address -// client.SetBaseURL("https://myjeeva.com") +// // Setting HTTP address +// client.SetBaseURL("http://myjeeva.com") +// +// // Setting HTTPS address +// client.SetBaseURL("https://myjeeva.com") // // Since v2.7.0 func (c *Client) SetBaseURL(url string) *Client { @@ -188,9 +203,9 @@ func (c *Client) SetBaseURL(url string) *Client { // // For Example: To set `Content-Type` and `Accept` as `application/json` // -// client. -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") +// client. +// SetHeader("Content-Type", "application/json"). +// SetHeader("Accept", "application/json") func (c *Client) SetHeader(header, value string) *Client { c.Header.Set(header, value) return c @@ -204,10 +219,10 @@ func (c *Client) SetHeader(header, value string) *Client { // // For Example: To set `Content-Type` and `Accept` as `application/json` // -// client.SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) +// client.SetHeaders(map[string]string{ +// "Content-Type": "application/json", +// "Accept": "application/json", +// }) func (c *Client) SetHeaders(headers map[string]string) *Client { for h, v := range headers { c.Header.Set(h, v) @@ -218,9 +233,10 @@ func (c *Client) SetHeaders(headers map[string]string) *Client { // SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request. // // For Example: To set `all_lowercase` and `UPPERCASE` as `available`. -// client.R(). -// SetHeaderVerbatim("all_lowercase", "available"). -// SetHeaderVerbatim("UPPERCASE", "available") +// +// client.R(). +// SetHeaderVerbatim("all_lowercase", "available"). +// SetHeaderVerbatim("UPPERCASE", "available") // // Also you can override header value, which was set at client instance level. // @@ -235,7 +251,7 @@ func (c *Client) SetHeaderVerbatim(header, value string) *Client { // For Example: sometimes we don't want to save cookies in api contacting, we can remove the default // CookieJar in resty client. // -// client.SetCookieJar(nil) +// client.SetCookieJar(nil) func (c *Client) SetCookieJar(jar http.CookieJar) *Client { c.httpClient.Jar = jar return c @@ -243,10 +259,11 @@ func (c *Client) SetCookieJar(jar http.CookieJar) *Client { // SetCookie method appends a single cookie in the client instance. // These cookies will be added to all the request raised from this client instance. -// client.SetCookie(&http.Cookie{ -// Name:"go-resty", -// Value:"This is cookie value", -// }) +// +// client.SetCookie(&http.Cookie{ +// Name:"go-resty", +// Value:"This is cookie value", +// }) func (c *Client) SetCookie(hc *http.Cookie) *Client { c.Cookies = append(c.Cookies, hc) return c @@ -254,19 +271,20 @@ func (c *Client) SetCookie(hc *http.Cookie) *Client { // SetCookies method sets an array of cookies in the client instance. // These cookies will be added to all the request raised from this client instance. -// cookies := []*http.Cookie{ -// &http.Cookie{ -// Name:"go-resty-1", -// Value:"This is cookie 1 value", -// }, -// &http.Cookie{ -// Name:"go-resty-2", -// Value:"This is cookie 2 value", -// }, -// } -// -// // Setting a cookies into resty -// client.SetCookies(cookies) +// +// cookies := []*http.Cookie{ +// &http.Cookie{ +// Name:"go-resty-1", +// Value:"This is cookie 1 value", +// }, +// &http.Cookie{ +// Name:"go-resty-2", +// Value:"This is cookie 2 value", +// }, +// } +// +// // Setting a cookies into resty +// client.SetCookies(cookies) func (c *Client) SetCookies(cs []*http.Cookie) *Client { c.Cookies = append(c.Cookies, cs...) return c @@ -280,9 +298,10 @@ func (c *Client) SetCookies(cs []*http.Cookie) *Client { // this client instance. Also it can be overridden at request level Query Param options. // // See `Request.SetQueryParam` or `Request.SetQueryParams`. -// client. -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") +// +// client. +// SetQueryParam("search", "kitchen papers"). +// SetQueryParam("size", "large") func (c *Client) SetQueryParam(param, value string) *Client { c.QueryParam.Set(param, value) return c @@ -296,10 +315,11 @@ func (c *Client) SetQueryParam(param, value string) *Client { // client instance. Also it can be overridden at request level Query Param options. // // See `Request.SetQueryParams` or `Request.SetQueryParam`. -// client.SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) +// +// client.SetQueryParams(map[string]string{ +// "search": "kitchen papers", +// "size": "large", +// }) func (c *Client) SetQueryParams(params map[string]string) *Client { for p, v := range params { c.SetQueryParam(p, v) @@ -308,15 +328,16 @@ func (c *Client) SetQueryParams(params map[string]string) *Client { } // SetFormData method sets Form parameters and their values in the client instance. -// It's applicable only HTTP method `POST` and `PUT` and requets content type would be set as +// It's applicable only HTTP method `POST` and `PUT` and request content type would be set as // `application/x-www-form-urlencoded`. These form data will be added to all the request raised from // this client instance. Also it can be overridden at request level form data. // // See `Request.SetFormData`. -// client.SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) +// +// client.SetFormData(map[string]string{ +// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", +// "user_id": "3455454545", +// }) func (c *Client) SetFormData(data map[string]string) *Client { for k, v := range data { c.FormData.Set(k, v) @@ -325,12 +346,14 @@ func (c *Client) SetFormData(data map[string]string) *Client { } // SetBasicAuth method sets the basic authentication header in the HTTP request. For Example: -// Authorization: Basic +// +// Authorization: Basic // // For Example: To set the header for username "go-resty" and password "welcome" -// client.SetBasicAuth("go-resty", "welcome") // -// This basic auth information gets added to all the request rasied from this client instance. +// client.SetBasicAuth("go-resty", "welcome") +// +// This basic auth information gets added to all the request raised from this client instance. // Also it can be overridden or set one at the request level is supported. // // See `Request.SetBasicAuth`. @@ -341,13 +364,14 @@ func (c *Client) SetBasicAuth(username, password string) *Client { // SetAuthToken method sets the auth token of the `Authorization` header for all HTTP requests. // The default auth scheme is `Bearer`, it can be customized with the method `SetAuthScheme`. For Example: -// Authorization: +// +// Authorization: // // For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F // -// client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") +// client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") // -// This auth token gets added to all the requests rasied from this client instance. +// This auth token gets added to all the requests raised from this client instance. // Also it can be overridden or set one at the request level is supported. // // See `Request.SetAuthToken`. @@ -357,19 +381,21 @@ func (c *Client) SetAuthToken(token string) *Client { } // SetAuthScheme method sets the auth scheme type in the HTTP request. For Example: -// Authorization: +// +// Authorization: // // For Example: To set the scheme to use OAuth // -// client.SetAuthScheme("OAuth") +// client.SetAuthScheme("OAuth") // -// This auth scheme gets added to all the requests rasied from this client instance. +// This auth scheme gets added to all the requests raised from this client instance. // Also it can be overridden or set one at the request level is supported. // // Information about auth schemes can be found in RFC7235 which is linked to below // along with the page containing the currently defined official authentication schemes: -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes +// +// https://tools.ietf.org/html/rfc7235 +// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes // // See `Request.SetAuthToken`. func (c *Client) SetAuthScheme(scheme string) *Client { @@ -377,19 +403,50 @@ func (c *Client) SetAuthScheme(scheme string) *Client { return c } +// SetDigestAuth method sets the Digest Access auth scheme for the client. If a server responds with 401 and sends +// a Digest challenge in the WWW-Authenticate Header, requests will be resent with the appropriate Authorization Header. +// +// For Example: To set the Digest scheme with user "Mufasa" and password "Circle Of Life" +// +// client.SetDigestAuth("Mufasa", "Circle Of Life") +// +// Information about Digest Access Authentication can be found in RFC7616: +// +// https://datatracker.ietf.org/doc/html/rfc7616 +// +// See `Request.SetDigestAuth`. +func (c *Client) SetDigestAuth(username, password string) *Client { + oldTransport := c.httpClient.Transport + c.OnBeforeRequest(func(c *Client, _ *Request) error { + c.httpClient.Transport = &digestTransport{ + digestCredentials: digestCredentials{username, password}, + transport: oldTransport, + } + return nil + }) + c.OnAfterResponse(func(c *Client, _ *Response) error { + c.httpClient.Transport = oldTransport + return nil + }) + return c +} + // R method creates a new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc. func (c *Client) R() *Request { r := &Request{ - QueryParam: url.Values{}, - FormData: url.Values{}, - Header: http.Header{}, - Cookies: make([]*http.Cookie, 0), + QueryParam: url.Values{}, + FormData: url.Values{}, + Header: http.Header{}, + Cookies: make([]*http.Cookie, 0), + PathParams: map[string]string{}, + RawPathParams: map[string]string{}, + Debug: c.Debug, client: c, multipartFiles: []*File{}, multipartFields: []*MultipartField{}, - PathParams: map[string]string{}, - jsonEscapeHTML: true, + jsonEscapeHTML: c.jsonEscapeHTML, + log: c.log, } return r } @@ -400,31 +457,41 @@ func (c *Client) NewRequest() *Request { return c.R() } -// OnBeforeRequest method appends request middleware into the before request chain. -// Its gets applied after default Resty request middlewares and before request -// been sent from Resty to host server. -// client.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { -// // Now you have access to Client and Request instance -// // manipulate it as per your need +// OnBeforeRequest method appends a request middleware into the before request chain. +// The user defined middlewares get applied before the default Resty request middlewares. +// After all middlewares have been applied, the request is sent from Resty to the host server. // -// return nil // if its success otherwise return error -// }) +// client.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { +// // Now you have access to Client and Request instance +// // manipulate it as per your need +// +// return nil // if its success otherwise return error +// }) func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client { + c.udBeforeRequestLock.Lock() + defer c.udBeforeRequestLock.Unlock() + c.udBeforeRequest = append(c.udBeforeRequest, m) + return c } // OnAfterResponse method appends response middleware into the after response chain. // Once we receive response from host server, default Resty response middleware -// gets applied and then user assigened response middlewares applied. -// client.OnAfterResponse(func(c *resty.Client, r *resty.Response) error { -// // Now you have access to Client and Response instance -// // manipulate it as per your need +// gets applied and then user assigned response middlewares applied. // -// return nil // if its success otherwise return error -// }) +// client.OnAfterResponse(func(c *resty.Client, r *resty.Response) error { +// // Now you have access to Client and Response instance +// // manipulate it as per your need +// +// return nil // if its success otherwise return error +// }) func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { + c.afterResponseLock.Lock() + defer c.afterResponseLock.Unlock() + c.afterResponse = append(c.afterResponse, m) + return c } @@ -433,21 +500,62 @@ func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { // If there was a response from the server, the error will be wrapped in *ResponseError // which has the last response received from the server. // -// client.OnError(func(req *resty.Request, err error) { -// if v, ok := err.(*resty.ResponseError); ok { -// // Do something with v.Response -// } -// // Log the error, increment a metric, etc... -// }) +// client.OnError(func(req *resty.Request, err error) { +// if v, ok := err.(*resty.ResponseError); ok { +// // Do something with v.Response +// } +// // Log the error, increment a metric, etc... +// }) +// +// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one +// set will be invoked for each call to Request.Execute() that completes. func (c *Client) OnError(h ErrorHook) *Client { c.errorHooks = append(c.errorHooks, h) return c } +// OnSuccess method adds a callback that will be run whenever a request execution +// succeeds. This is called after all retries have been attempted (if any). +// +// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one +// set will be invoked for each call to Request.Execute() that completes. +// +// Since v2.8.0 +func (c *Client) OnSuccess(h SuccessHook) *Client { + c.successHooks = append(c.successHooks, h) + return c +} + +// OnInvalid method adds a callback that will be run whenever a request execution +// fails before it starts because the request is invalid. +// +// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one +// set will be invoked for each call to Request.Execute() that completes. +// +// Since v2.8.0 +func (c *Client) OnInvalid(h ErrorHook) *Client { + c.invalidHooks = append(c.invalidHooks, h) + return c +} + +// OnPanic method adds a callback that will be run whenever a request execution +// panics. +// +// Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one +// set will be invoked for each call to Request.Execute() that completes. +// If an OnSuccess, OnError, or OnInvalid callback panics, then the exactly +// one rule can be violated. +// +// Since v2.8.0 +func (c *Client) OnPanic(h ErrorHook) *Client { + c.panicHooks = append(c.panicHooks, h) + return c +} + // SetPreRequestHook method sets the given pre-request function into resty client. // It is called right before the request is fired. // -// Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for mutilple. +// Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for multiple. func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { if c.preReqHook != nil { c.log.Warnf("Overwriting an existing pre-request hook: %s", functionName(h)) @@ -459,14 +567,18 @@ func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { // SetDebug method enables the debug mode on Resty client. Client logs details of every request and response. // For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. // For `Response` it logs information such as Status, Response Time, Headers, Body if it has one. -// client.SetDebug(true) +// +// client.SetDebug(true) +// +// Also it can be enabled at request level for particular request, see `Request.SetDebug`. func (c *Client) SetDebug(d bool) *Client { c.Debug = d return c } // SetDebugBodyLimit sets the maximum size for which the response and request body will be logged in debug mode. -// client.SetDebugBodyLimit(1000000) +// +// client.SetDebugBodyLimit(1000000) func (c *Client) SetDebugBodyLimit(sl int64) *Client { c.debugBodySizeLimit = sl return c @@ -497,7 +609,8 @@ func (c *Client) OnResponseLog(rl ResponseLogCallback) *Client { // SetDisableWarn method disables the warning message on Resty client. // // For Example: Resty warns the user when BasicAuth used on non-TLS mode. -// client.SetDisableWarn(true) +// +// client.SetDisableWarn(true) func (c *Client) SetDisableWarn(d bool) *Client { c.DisableWarn = d return c @@ -506,7 +619,8 @@ func (c *Client) SetDisableWarn(d bool) *Client { // SetAllowGetMethodPayload method allows the GET method with payload on Resty client. // // For Example: Resty allows the user sends request with a payload on HTTP GET method. -// client.SetAllowGetMethodPayload(true) +// +// client.SetAllowGetMethodPayload(true) func (c *Client) SetAllowGetMethodPayload(a bool) *Client { c.AllowGetMethodPayload = a return c @@ -522,7 +636,8 @@ func (c *Client) SetLogger(l Logger) *Client { // SetContentLength method enables the HTTP header `Content-Length` value for every request. // By default Resty won't set `Content-Length`. -// client.SetContentLength(true) +// +// client.SetContentLength(true) // // Also you have an option to enable for particular request. See `Request.SetContentLength` func (c *Client) SetContentLength(l bool) *Client { @@ -531,7 +646,8 @@ func (c *Client) SetContentLength(l bool) *Client { } // SetTimeout method sets timeout for request raised from client. -// client.SetTimeout(time.Duration(1 * time.Minute)) +// +// client.SetTimeout(time.Duration(1 * time.Minute)) func (c *Client) SetTimeout(timeout time.Duration) *Client { c.httpClient.Timeout = timeout return c @@ -540,21 +656,22 @@ func (c *Client) SetTimeout(timeout time.Duration) *Client { // SetError method is to register the global or client common `Error` object into Resty. // It is used for automatic unmarshalling if response status code is greater than 399 and // content type either JSON or XML. Can be pointer or non-pointer. -// client.SetError(&Error{}) -// // OR -// client.SetError(Error{}) +// +// client.SetError(&Error{}) +// // OR +// client.SetError(Error{}) func (c *Client) SetError(err interface{}) *Client { c.Error = typeOf(err) return c } -// SetRedirectPolicy method sets the client redirect poilicy. Resty provides ready to use +// SetRedirectPolicy method sets the client redirect policy. Resty provides ready to use // redirect policies. Wanna create one for yourself refer to `redirect.go`. // -// client.SetRedirectPolicy(FlexibleRedirectPolicy(20)) +// client.SetRedirectPolicy(FlexibleRedirectPolicy(20)) // -// // Need multiple redirect policies together -// client.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net")) +// // Need multiple redirect policies together +// client.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net")) func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client { for _, p := range policies { if _, ok := p.(RedirectPolicy); !ok { @@ -607,6 +724,42 @@ func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client { return c } +// SetJSONMarshaler method sets the JSON marshaler function to marshal the request body. +// By default, Resty uses `encoding/json` package to marshal the request body. +// +// Since v2.8.0 +func (c *Client) SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client { + c.JSONMarshal = marshaler + return c +} + +// SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body. +// By default, Resty uses `encoding/json` package to unmarshal the response body. +// +// Since v2.8.0 +func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client { + c.JSONUnmarshal = unmarshaler + return c +} + +// SetXMLMarshaler method sets the XML marshaler function to marshal the request body. +// By default, Resty uses `encoding/xml` package to marshal the request body. +// +// Since v2.8.0 +func (c *Client) SetXMLMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client { + c.XMLMarshal = marshaler + return c +} + +// SetXMLUnmarshaler method sets the XML unmarshaler function to unmarshal the response body. +// By default, Resty uses `encoding/xml` package to unmarshal the response body. +// +// Since v2.8.0 +func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client { + c.XMLUnmarshal = unmarshaler + return c +} + // AddRetryCondition method adds a retry condition function to array of functions // that are checked to determine if the request is retried. The request will // retry if any of the functions return true and error is nil. @@ -638,18 +791,28 @@ func (c *Client) AddRetryHook(hook OnRetryFunc) *Client { return c } +// SetRetryResetReaders method enables the Resty client to seek the start of all +// file readers given as multipart files, if the given object implements `io.ReadSeeker`. +// +// Since ... +func (c *Client) SetRetryResetReaders(b bool) *Client { + c.RetryResetReaders = b + return c +} + // SetTLSClientConfig method sets TLSClientConfig for underling client Transport. // // For Example: -// // One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial -// client.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) // -// // or One can disable security check (https) -// client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) +// // One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial +// client.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) +// +// // or One can disable security check (https) +// client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) // // Note: This method overwrites existing `TLSClientConfig`. func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { c.log.Errorf("%v", err) return c @@ -659,13 +822,14 @@ func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { } // SetProxy method sets the Proxy URL and Port for Resty client. -// client.SetProxy("http://proxyserver:8888") +// +// client.SetProxy("http://proxyserver:8888") // // OR Without this `SetProxy` method, you could also set Proxy via environment variable. // // Refer to godoc `http.ProxyFromEnvironment`. func (c *Client) SetProxy(proxyURL string) *Client { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { c.log.Errorf("%v", err) return c @@ -683,9 +847,10 @@ func (c *Client) SetProxy(proxyURL string) *Client { } // RemoveProxy method removes the proxy configuration from Resty client -// client.RemoveProxy() +// +// client.RemoveProxy() func (c *Client) RemoveProxy() *Client { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { c.log.Errorf("%v", err) return c @@ -707,9 +872,10 @@ func (c *Client) SetCertificates(certs ...tls.Certificate) *Client { } // SetRootCertificate method helps to add one or more root certificates into Resty client -// client.SetRootCertificate("/path/to/root/pemFile.pem") +// +// client.SetRootCertificate("/path/to/root/pemFile.pem") func (c *Client) SetRootCertificate(pemFilePath string) *Client { - rootPemData, err := ioutil.ReadFile(pemFilePath) + rootPemData, err := os.ReadFile(pemFilePath) if err != nil { c.log.Errorf("%v", err) return c @@ -729,7 +895,8 @@ func (c *Client) SetRootCertificate(pemFilePath string) *Client { } // SetRootCertificateFromString method helps to add one or more root certificates into Resty client -// client.SetRootCertificateFromString("pem file content") +// +// client.SetRootCertificateFromString("pem file content") func (c *Client) SetRootCertificateFromString(pemContent string) *Client { config, err := c.tlsConfig() if err != nil { @@ -747,12 +914,22 @@ func (c *Client) SetRootCertificateFromString(pemContent string) *Client { // SetOutputDirectory method sets output directory for saving HTTP response into file. // If the output directory not exists then resty creates one. This setting is optional one, // if you're planning using absolute path in `Request.SetOutput` and can used together. -// client.SetOutputDirectory("/save/http/response/here") +// +// client.SetOutputDirectory("/save/http/response/here") func (c *Client) SetOutputDirectory(dirPath string) *Client { c.outputDirectory = dirPath return c } +// SetRateLimiter sets an optional `RateLimiter`. If set the rate limiter will control +// all requests made with this client. +// +// Since v2.9.0 +func (c *Client) SetRateLimiter(rl RateLimiter) *Client { + c.rateLimiter = rl + return c +} + // SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` // compatible interface implementation in the resty client. // @@ -763,14 +940,14 @@ func (c *Client) SetOutputDirectory(dirPath string) *Client { // // - It overwrites the Resty client transport instance and it's configurations. // -// transport := &http.Transport{ -// // somthing like Proxying to httptest.Server, etc... -// Proxy: func(req *http.Request) (*url.URL, error) { -// return url.Parse(server.URL) -// }, -// } +// transport := &http.Transport{ +// // something like Proxying to httptest.Server, etc... +// Proxy: func(req *http.Request) (*url.URL, error) { +// return url.Parse(server.URL) +// }, +// } // -// client.SetTransport(transport) +// client.SetTransport(transport) func (c *Client) SetTransport(transport http.RoundTripper) *Client { if transport != nil { c.httpClient.Transport = transport @@ -779,7 +956,8 @@ func (c *Client) SetTransport(transport http.RoundTripper) *Client { } // SetScheme method sets custom scheme in the Resty client. It's way to override default. -// client.SetScheme("http") +// +// client.SetScheme("http") func (c *Client) SetScheme(scheme string) *Client { if !IsStringEmpty(scheme) { c.scheme = strings.TrimSpace(scheme) @@ -807,12 +985,15 @@ func (c *Client) SetDoNotParseResponse(parse bool) *Client { // SetPathParam method sets single URL path key-value pair in the // Resty client instance. -// client.SetPathParam("userId", "sample@sample.com") // -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details +// client.SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// // It replaces the value of the key while composing the request URL. +// The value will be escaped using `url.PathEscape` function. // // Also it can be overridden at request level Path Params options, // see `Request.SetPathParam` or `Request.SetPathParams`. @@ -823,15 +1004,19 @@ func (c *Client) SetPathParam(param, value string) *Client { // SetPathParams method sets multiple URL path key-value pairs at one go in the // Resty client instance. -// client.SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details +// +// client.SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details +// // It replaces the value of the key while composing the request URL. +// The values will be escaped using `url.PathEscape` function. // // Also it can be overridden at request level Path Params options, // see `Request.SetPathParam` or `Request.SetPathParams`. @@ -842,6 +1027,60 @@ func (c *Client) SetPathParams(params map[string]string) *Client { return c } +// SetRawPathParam method sets single URL path key-value pair in the +// Resty client instance. +// +// client.SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// +// client.SetPathParam("path", "groups/developers") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/groups%2Fdevelopers/details +// +// It replaces the value of the key while composing the request URL. +// The value will be used as it is and will not be escaped. +// +// Also it can be overridden at request level Path Params options, +// see `Request.SetPathParam` or `Request.SetPathParams`. +// +// Since v2.8.0 +func (c *Client) SetRawPathParam(param, value string) *Client { + c.RawPathParams[param] = value + return c +} + +// SetRawPathParams method sets multiple URL path key-value pairs at one go in the +// Resty client instance. +// +// client.SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details +// +// It replaces the value of the key while composing the request URL. +// The values will be used as they are and will not be escaped. +// +// Also it can be overridden at request level Path Params options, +// see `Request.SetPathParam` or `Request.SetPathParams`. +// +// Since v2.8.0 +func (c *Client) SetRawPathParams(params map[string]string) *Client { + for p, v := range params { + c.SetRawPathParam(p, v) + } + return c +} + // SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. // // Note: This option only applicable to standard JSON Marshaller. @@ -853,11 +1092,11 @@ func (c *Client) SetJSONEscapeHTML(b bool) *Client { // EnableTrace method enables the Resty client trace for the requests fired from // the client using `httptrace.ClientTrace` and provides insights. // -// client := resty.New().EnableTrace() +// client := resty.New().EnableTrace() // -// resp, err := client.R().Get("https://httpbin.org/get") -// fmt.Println("Error:", err) -// fmt.Println("Trace Info:", resp.Request.TraceInfo()) +// resp, err := client.R().Get("https://httpbin.org/get") +// fmt.Println("Error:", err) +// fmt.Println("Trace Info:", resp.Request.TraceInfo()) // // Also `Request.EnableTrace` available too to get trace info for single request. // @@ -893,6 +1132,14 @@ func (c *Client) GetClient() *http.Client { // Executes method executes the given `Request` object and returns response // error. func (c *Client) execute(req *Request) (*Response, error) { + // Lock the user-defined pre-request hooks. + c.udBeforeRequestLock.RLock() + defer c.udBeforeRequestLock.RUnlock() + + // Lock the post-request hooks. + c.afterResponseLock.RLock() + defer c.afterResponseLock.RUnlock() + // Apply Request middleware var err error @@ -904,6 +1151,14 @@ func (c *Client) execute(req *Request) (*Response, error) { } } + // If there is a rate limiter set for this client, the Execute call + // will return an error if the rate limit is exceeded. + if req.client.rateLimiter != nil { + if !req.client.rateLimiter.Allow() { + return nil, wrapNoRetryErr(ErrRateLimitExceeded) + } + } + // resty middlewares for _, f := range c.beforeRequest { if err = f(c, req); err != nil { @@ -957,7 +1212,7 @@ func (c *Client) execute(req *Request) (*Response, error) { } } - if response.body, err = ioutil.ReadAll(body); err != nil { + if response.body, err = io.ReadAll(body); err != nil { response.setReceivedAt() return response, err } @@ -979,7 +1234,7 @@ func (c *Client) execute(req *Request) (*Response, error) { // getting TLS client config if not exists then create one func (c *Client) tlsConfig() (*tls.Config, error) { - transport, err := c.transport() + transport, err := c.Transport() if err != nil { return nil, err } @@ -991,7 +1246,9 @@ func (c *Client) tlsConfig() (*tls.Config, error) { // Transport method returns `*http.Transport` currently in use or error // in case currently used `transport` is not a `*http.Transport`. -func (c *Client) transport() (*http.Transport, error) { +// +// Since v2.8.0 become exported method. +func (c *Client) Transport() (*http.Transport, error) { if transport, ok := c.httpClient.Transport.(*http.Transport); ok { return transport, nil } @@ -1019,7 +1276,7 @@ func (e *ResponseError) Unwrap() error { return e.Err } -// Helper to run onErrorHooks hooks. +// Helper to run errorHooks hooks. // It wraps the error in a ResponseError if the resp is not nil // so hooks can access it. func (c *Client) onErrorHooks(req *Request, resp *Response, err error) { @@ -1030,6 +1287,24 @@ func (c *Client) onErrorHooks(req *Request, resp *Response, err error) { for _, h := range c.errorHooks { h(req, err) } + } else { + for _, h := range c.successHooks { + h(c, resp) + } + } +} + +// Helper to run panicHooks hooks. +func (c *Client) onPanicHooks(req *Request, err error) { + for _, h := range c.panicHooks { + h(req, err) + } +} + +// Helper to run invalidHooks hooks. +func (c *Client) onInvalidHooks(req *Request, err error) { + for _, h := range c.invalidHooks { + h(req, err) } } @@ -1078,6 +1353,7 @@ func createClient(hc *http.Client) *Client { RetryWaitTime: defaultWaitTime, RetryMaxWaitTime: defaultMaxWaitTime, PathParams: make(map[string]string), + RawPathParams: make(map[string]string), JSONMarshal: json.Marshal, JSONUnmarshal: json.Unmarshal, XMLMarshal: xml.Marshal, diff --git a/vendor/github.com/go-resty/resty/v2/digest.go b/vendor/github.com/go-resty/resty/v2/digest.go new file mode 100644 index 000000000..9dd3a13b5 --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/digest.go @@ -0,0 +1,295 @@ +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com) +// 2023 Segev Dagan (https://github.com/segevda) +// All rights reserved. +// resty source code and usage is governed by a MIT style +// license that can be found in the LICENSE file. + +package resty + +import ( + "crypto/md5" + "crypto/rand" + "crypto/sha256" + "crypto/sha512" + "errors" + "fmt" + "hash" + "io" + "net/http" + "strings" +) + +var ( + ErrDigestBadChallenge = errors.New("digest: challenge is bad") + ErrDigestCharset = errors.New("digest: unsupported charset") + ErrDigestAlgNotSupported = errors.New("digest: algorithm is not supported") + ErrDigestQopNotSupported = errors.New("digest: no supported qop in list") + ErrDigestNoQop = errors.New("digest: qop must be specified") +) + +var hashFuncs = map[string]func() hash.Hash{ + "": md5.New, + "MD5": md5.New, + "MD5-sess": md5.New, + "SHA-256": sha256.New, + "SHA-256-sess": sha256.New, + "SHA-512-256": sha512.New, + "SHA-512-256-sess": sha512.New, +} + +type digestCredentials struct { + username, password string +} + +type digestTransport struct { + digestCredentials + transport http.RoundTripper +} + +func (dt *digestTransport) RoundTrip(req *http.Request) (*http.Response, error) { + // Copy the request, so we don't modify the input. + req2 := new(http.Request) + *req2 = *req + req2.Header = make(http.Header) + for k, s := range req.Header { + req2.Header[k] = s + } + + // Fix http: ContentLength=xxx with Body length 0 + if req2.Body == nil { + req2.ContentLength = 0 + } else if req2.GetBody != nil { + var err error + req2.Body, err = req2.GetBody() + if err != nil { + return nil, err + } + } + + // Make a request to get the 401 that contains the challenge. + resp, err := dt.transport.RoundTrip(req) + if err != nil || resp.StatusCode != http.StatusUnauthorized { + return resp, err + } + chal := resp.Header.Get(hdrWwwAuthenticateKey) + if chal == "" { + return resp, ErrDigestBadChallenge + } + + c, err := parseChallenge(chal) + if err != nil { + return resp, err + } + + // Form credentials based on the challenge + cr := dt.newCredentials(req2, c) + auth, err := cr.authorize() + if err != nil { + return resp, err + } + err = resp.Body.Close() + if err != nil { + return nil, err + } + + // Make authenticated request + req2.Header.Set(hdrAuthorizationKey, auth) + return dt.transport.RoundTrip(req2) +} + +func (dt *digestTransport) newCredentials(req *http.Request, c *challenge) *credentials { + return &credentials{ + username: dt.username, + userhash: c.userhash, + realm: c.realm, + nonce: c.nonce, + digestURI: req.URL.RequestURI(), + algorithm: c.algorithm, + sessionAlg: strings.HasSuffix(c.algorithm, "-sess"), + opaque: c.opaque, + messageQop: c.qop, + nc: 0, + method: req.Method, + password: dt.password, + } +} + +type challenge struct { + realm string + domain string + nonce string + opaque string + stale string + algorithm string + qop string + userhash string +} + +func parseChallenge(input string) (*challenge, error) { + const ws = " \n\r\t" + const qs = `"` + s := strings.Trim(input, ws) + if !strings.HasPrefix(s, "Digest ") { + return nil, ErrDigestBadChallenge + } + s = strings.Trim(s[7:], ws) + sl := strings.Split(s, ",") + c := &challenge{} + var r []string + for i := range sl { + sl[i] = strings.TrimSpace(sl[i]) + r = strings.SplitN(sl[i], "=", 2) + if len(r) != 2 { + return nil, ErrDigestBadChallenge + } + r[0] = strings.TrimSpace(r[0]) + r[1] = strings.TrimSpace(r[1]) + switch r[0] { + case "realm": + c.realm = strings.Trim(r[1], qs) + case "domain": + c.domain = strings.Trim(r[1], qs) + case "nonce": + c.nonce = strings.Trim(r[1], qs) + case "opaque": + c.opaque = strings.Trim(r[1], qs) + case "stale": + c.stale = strings.Trim(r[1], qs) + case "algorithm": + c.algorithm = strings.Trim(r[1], qs) + case "qop": + c.qop = strings.Trim(r[1], qs) + case "charset": + if strings.ToUpper(strings.Trim(r[1], qs)) != "UTF-8" { + return nil, ErrDigestCharset + } + case "userhash": + c.userhash = strings.Trim(r[1], qs) + default: + return nil, ErrDigestBadChallenge + } + } + return c, nil +} + +type credentials struct { + username string + userhash string + realm string + nonce string + digestURI string + algorithm string + sessionAlg bool + cNonce string + opaque string + messageQop string + nc int + method string + password string +} + +func (c *credentials) authorize() (string, error) { + if _, ok := hashFuncs[c.algorithm]; !ok { + return "", ErrDigestAlgNotSupported + } + + if err := c.validateQop(); err != nil { + return "", err + } + + resp, err := c.resp() + if err != nil { + return "", err + } + + sl := make([]string, 0, 10) + if c.userhash == "true" { + // RFC 7616 3.4.4 + c.username = c.h(fmt.Sprintf("%s:%s", c.username, c.realm)) + sl = append(sl, fmt.Sprintf(`userhash=%s`, c.userhash)) + } + sl = append(sl, fmt.Sprintf(`username="%s"`, c.username)) + sl = append(sl, fmt.Sprintf(`realm="%s"`, c.realm)) + sl = append(sl, fmt.Sprintf(`nonce="%s"`, c.nonce)) + sl = append(sl, fmt.Sprintf(`uri="%s"`, c.digestURI)) + sl = append(sl, fmt.Sprintf(`response="%s"`, resp)) + sl = append(sl, fmt.Sprintf(`algorithm=%s`, c.algorithm)) + if c.opaque != "" { + sl = append(sl, fmt.Sprintf(`opaque="%s"`, c.opaque)) + } + if c.messageQop != "" { + sl = append(sl, fmt.Sprintf("qop=%s", c.messageQop)) + sl = append(sl, fmt.Sprintf("nc=%08x", c.nc)) + sl = append(sl, fmt.Sprintf(`cnonce="%s"`, c.cNonce)) + } + + return fmt.Sprintf("Digest %s", strings.Join(sl, ", ")), nil +} + +func (c *credentials) validateQop() error { + // Currently only supporting auth quality of protection. TODO: add auth-int support + // NOTE: cURL support auth-int qop for requests other than POST and PUT (i.e. w/o body) by hashing an empty string + // is this applicable for resty? see: https://github.com/curl/curl/blob/307b7543ea1e73ab04e062bdbe4b5bb409eaba3a/lib/vauth/digest.c#L774 + if c.messageQop == "" { + return ErrDigestNoQop + } + possibleQops := strings.Split(c.messageQop, ", ") + var authSupport bool + for _, qop := range possibleQops { + if qop == "auth" { + authSupport = true + break + } + } + if !authSupport { + return ErrDigestQopNotSupported + } + + c.messageQop = "auth" + + return nil +} + +func (c *credentials) h(data string) string { + hfCtor := hashFuncs[c.algorithm] + hf := hfCtor() + _, _ = hf.Write([]byte(data)) // Hash.Write never returns an error + return fmt.Sprintf("%x", hf.Sum(nil)) +} + +func (c *credentials) resp() (string, error) { + c.nc++ + + b := make([]byte, 16) + _, err := io.ReadFull(rand.Reader, b) + if err != nil { + return "", err + } + c.cNonce = fmt.Sprintf("%x", b)[:32] + + ha1 := c.ha1() + ha2 := c.ha2() + + return c.kd(ha1, fmt.Sprintf("%s:%08x:%s:%s:%s", + c.nonce, c.nc, c.cNonce, c.messageQop, ha2)), nil +} + +func (c *credentials) kd(secret, data string) string { + return c.h(fmt.Sprintf("%s:%s", secret, data)) +} + +// RFC 7616 3.4.2 +func (c *credentials) ha1() string { + ret := c.h(fmt.Sprintf("%s:%s:%s", c.username, c.realm, c.password)) + if c.sessionAlg { + return c.h(fmt.Sprintf("%s:%s:%s", ret, c.nonce, c.cNonce)) + } + + return ret +} + +// RFC 7616 3.4.3 +func (c *credentials) ha2() string { + // currently no auth-int support + return c.h(fmt.Sprintf("%s:%s", c.method, c.digestURI)) +} diff --git a/vendor/github.com/go-resty/resty/v2/middleware.go b/vendor/github.com/go-resty/resty/v2/middleware.go index 0e8ac2b69..ac2bbc9e8 100644 --- a/vendor/github.com/go-resty/resty/v2/middleware.go +++ b/vendor/github.com/go-resty/resty/v2/middleware.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -9,13 +9,13 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" + "strconv" "strings" "time" ) @@ -27,15 +27,76 @@ const debugRequestLogKey = "__restyDebugRequestLog" //_______________________________________________________________________ func parseRequestURL(c *Client, r *Request) error { - // GitHub #103 Path Params - if len(r.PathParams) > 0 { + if l := len(c.PathParams) + len(c.RawPathParams) + len(r.PathParams) + len(r.RawPathParams); l > 0 { + params := make(map[string]string, l) + + // GitHub #103 Path Params for p, v := range r.PathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) + params[p] = url.PathEscape(v) } - } - if len(c.PathParams) > 0 { for p, v := range c.PathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) + if _, ok := params[p]; !ok { + params[p] = url.PathEscape(v) + } + } + + // GitHub #663 Raw Path Params + for p, v := range r.RawPathParams { + if _, ok := params[p]; !ok { + params[p] = v + } + } + for p, v := range c.RawPathParams { + if _, ok := params[p]; !ok { + params[p] = v + } + } + + if len(params) > 0 { + var prev int + buf := acquireBuffer() + defer releaseBuffer(buf) + // search for the next or first opened curly bracket + for curr := strings.Index(r.URL, "{"); curr > prev; curr = prev + strings.Index(r.URL[prev:], "{") { + // write everything form the previous position up to the current + if curr > prev { + buf.WriteString(r.URL[prev:curr]) + } + // search for the closed curly bracket from current position + next := curr + strings.Index(r.URL[curr:], "}") + // if not found, then write the remainder and exit + if next < curr { + buf.WriteString(r.URL[curr:]) + prev = len(r.URL) + break + } + // special case for {}, without parameter's name + if next == curr+1 { + buf.WriteString("{}") + } else { + // check for the replacement + key := r.URL[curr+1 : next] + value, ok := params[key] + /// keep the original string if the replacement not found + if !ok { + value = r.URL[curr : next+1] + } + buf.WriteString(value) + } + + // set the previous position after the closed curly bracket + prev = next + 1 + if prev >= len(r.URL) { + break + } + } + if buf.Len() > 0 { + // write remainder + if prev < len(r.URL) { + buf.WriteString(r.URL[prev:]) + } + r.URL = buf.String() + } } } @@ -53,7 +114,12 @@ func parseRequestURL(c *Client, r *Request) error { r.URL = "/" + r.URL } - reqURL, err = url.Parse(c.HostURL + r.URL) + // TODO: change to use c.BaseURL only in v3.0.0 + baseURL := c.BaseURL + if len(baseURL) == 0 { + baseURL = c.HostURL + } + reqURL, err = url.Parse(baseURL + r.URL) if err != nil { return err } @@ -65,32 +131,26 @@ func parseRequestURL(c *Client, r *Request) error { } // Adding Query Param - query := make(url.Values) - for k, v := range c.QueryParam { - for _, iv := range v { - query.Add(k, iv) - } - } - - for k, v := range r.QueryParam { - // remove query param from client level by key - // since overrides happens for that key in the request - query.Del(k) + if len(c.QueryParam)+len(r.QueryParam) > 0 { + for k, v := range c.QueryParam { + // skip query parameter if it was set in request + if _, ok := r.QueryParam[k]; ok { + continue + } - for _, iv := range v { - query.Add(k, iv) + r.QueryParam[k] = v[:] } - } - // GitHub #123 Preserve query string order partially. - // Since not feasible in `SetQuery*` resty methods, because - // standard package `url.Encode(...)` sorts the query params - // alphabetically - if len(query) > 0 { - if IsStringEmpty(reqURL.RawQuery) { - reqURL.RawQuery = query.Encode() - } else { - reqURL.RawQuery = reqURL.RawQuery + "&" + query.Encode() + // GitHub #123 Preserve query string order partially. + // Since not feasible in `SetQuery*` resty methods, because + // standard package `url.Encode(...)` sorts the query params + // alphabetically + if len(r.QueryParam) > 0 { + if IsStringEmpty(reqURL.RawQuery) { + reqURL.RawQuery = r.QueryParam.Encode() + } else { + reqURL.RawQuery = reqURL.RawQuery + "&" + r.QueryParam.Encode() + } } } @@ -100,71 +160,57 @@ func parseRequestURL(c *Client, r *Request) error { } func parseRequestHeader(c *Client, r *Request) error { - hdr := make(http.Header) - for k := range c.Header { - hdr[k] = append(hdr[k], c.Header[k]...) - } - - for k := range r.Header { - hdr.Del(k) - hdr[k] = append(hdr[k], r.Header[k]...) + for k, v := range c.Header { + if _, ok := r.Header[k]; ok { + continue + } + r.Header[k] = v[:] } - if IsStringEmpty(hdr.Get(hdrUserAgentKey)) { - hdr.Set(hdrUserAgentKey, hdrUserAgentValue) + if IsStringEmpty(r.Header.Get(hdrUserAgentKey)) { + r.Header.Set(hdrUserAgentKey, hdrUserAgentValue) } - ct := hdr.Get(hdrContentTypeKey) - if IsStringEmpty(hdr.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && - (IsJSONType(ct) || IsXMLType(ct)) { - hdr.Set(hdrAcceptKey, hdr.Get(hdrContentTypeKey)) + if ct := r.Header.Get(hdrContentTypeKey); IsStringEmpty(r.Header.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && (IsJSONType(ct) || IsXMLType(ct)) { + r.Header.Set(hdrAcceptKey, r.Header.Get(hdrContentTypeKey)) } - r.Header = hdr - return nil } -func parseRequestBody(c *Client, r *Request) (err error) { +func parseRequestBody(c *Client, r *Request) error { if isPayloadSupported(r.Method, c.AllowGetMethodPayload) { - // Handling Multipart - if r.isMultiPart && !(r.Method == MethodPatch) { - if err = handleMultipart(c, r); err != nil { - return + switch { + case r.isMultiPart: // Handling Multipart + if err := handleMultipart(c, r); err != nil { + return err } - - goto CL - } - - // Handling Form Data - if len(c.FormData) > 0 || len(r.FormData) > 0 { + case len(c.FormData) > 0 || len(r.FormData) > 0: // Handling Form Data handleFormData(c, r) - - goto CL - } - - // Handling Request body - if r.Body != nil { + case r.Body != nil: // Handling Request body handleContentType(c, r) - if err = handleRequestBody(c, r); err != nil { - return + if err := handleRequestBody(c, r); err != nil { + return err } } } -CL: // by default resty won't set content length, you can if you want to :) - if (c.setContentLength || r.setContentLength) && r.bodyBuf != nil { - r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len())) + if c.setContentLength || r.setContentLength { + if r.bodyBuf == nil { + r.Header.Set(hdrContentLengthKey, "0") + } else { + r.Header.Set(hdrContentLengthKey, strconv.Itoa(r.bodyBuf.Len())) + } } - return + return nil } func createHTTPRequest(c *Client, r *Request) (err error) { if r.bodyBuf == nil { - if reader, ok := r.Body.(io.Reader); ok { + if reader, ok := r.Body.(io.Reader); ok && isPayloadSupported(r.Method, c.AllowGetMethodPayload) { r.RawRequest, err = http.NewRequest(r.Method, r.URL, reader) } else if c.setContentLength || r.setContentLength { r.RawRequest, err = http.NewRequest(r.Method, r.URL, http.NoBody) @@ -172,7 +218,9 @@ func createHTTPRequest(c *Client, r *Request) (err error) { r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil) } } else { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, r.bodyBuf) + // fix data race: must deep copy. + bodyBuf := bytes.NewBuffer(append([]byte{}, r.bodyBuf.Bytes()...)) + r.RawRequest, err = http.NewRequest(r.Method, r.URL, bodyBuf) } if err != nil { @@ -214,7 +262,7 @@ func createHTTPRequest(c *Client, r *Request) (err error) { // assign get body func for the underlying raw request instance r.RawRequest.GetBody = func() (io.ReadCloser, error) { if bodyCopy != nil { - return ioutil.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil + return io.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil } return nil, nil } @@ -235,7 +283,7 @@ func addCredentials(c *Client, r *Request) error { if !c.DisableWarn { if isBasicAuth && !strings.HasPrefix(r.URL, "https") { - c.log.Warnf("Using Basic Auth in HTTP mode is not secure, use HTTPS") + r.log.Warnf("Using Basic Auth in HTTP mode is not secure, use HTTPS") } } @@ -260,15 +308,25 @@ func addCredentials(c *Client, r *Request) error { } func requestLogger(c *Client, r *Request) error { - if c.Debug { + if r.Debug { rr := r.RawRequest - rl := &RequestLog{Header: copyHeaders(rr.Header), Body: r.fmtBodyString(c.debugBodySizeLimit)} + rh := copyHeaders(rr.Header) + if c.GetClient().Jar != nil { + for _, cookie := range c.GetClient().Jar.Cookies(r.RawRequest.URL) { + s := fmt.Sprintf("%s=%s", cookie.Name, cookie.Value) + if c := rh.Get("Cookie"); c != "" { + rh.Set("Cookie", c+"; "+s) + } else { + rh.Set("Cookie", s) + } + } + } + rl := &RequestLog{Header: rh, Body: r.fmtBodyString(c.debugBodySizeLimit)} if c.requestLog != nil { if err := c.requestLog(rl); err != nil { return err } } - // fmt.Sprintf("COOKIES:\n%s\n", composeCookies(c.GetClient().Jar, *rr.URL)) + reqLog := "\n==============================================================================\n" + "~~~ REQUEST ~~~\n" + @@ -290,7 +348,7 @@ func requestLogger(c *Client, r *Request) error { //_______________________________________________________________________ func responseLogger(c *Client, res *Response) error { - if c.Debug { + if res.Request.Debug { rl := &ResponseLog{Header: copyHeaders(res.Header()), Body: res.fmtBodyString(c.debugBodySizeLimit)} if c.responseLog != nil { if err := c.responseLog(rl); err != nil { @@ -313,7 +371,7 @@ func responseLogger(c *Client, res *Response) error { } debugLog += "==============================================================================\n" - c.log.Debugf("%s", debugLog) + res.Request.log.Debugf("%s", debugLog) } return nil @@ -321,6 +379,7 @@ func responseLogger(c *Client, res *Response) error { func parseResponseBody(c *Client, res *Response) (err error) { if res.StatusCode() == http.StatusNoContent { + res.Request.Error = nil return } // Handles only JSON or XML content type @@ -343,7 +402,10 @@ func parseResponseBody(c *Client, res *Response) (err error) { } if res.Request.Error != nil { - err = Unmarshalc(c, ct, res.body, res.Request.Error) + unmarshalErr := Unmarshalc(c, ct, res.body, res.Request.Error) + if unmarshalErr != nil { + c.log.Warnf("Cannot unmarshal response body: %s", unmarshalErr) + } } } } @@ -351,13 +413,13 @@ func parseResponseBody(c *Client, res *Response) (err error) { return } -func handleMultipart(c *Client, r *Request) (err error) { +func handleMultipart(c *Client, r *Request) error { r.bodyBuf = acquireBuffer() w := multipart.NewWriter(r.bodyBuf) for k, v := range c.FormData { for _, iv := range v { - if err = w.WriteField(k, iv); err != nil { + if err := w.WriteField(k, iv); err != nil { return err } } @@ -366,12 +428,11 @@ func handleMultipart(c *Client, r *Request) (err error) { for k, v := range r.FormData { for _, iv := range v { if strings.HasPrefix(k, "@") { // file - err = addFile(w, k[1:], iv) - if err != nil { - return + if err := addFile(w, k[1:], iv); err != nil { + return err } } else { // form value - if err = w.WriteField(k, iv); err != nil { + if err := w.WriteField(k, iv); err != nil { return err } } @@ -379,50 +440,33 @@ func handleMultipart(c *Client, r *Request) (err error) { } // #21 - adding io.Reader support - if len(r.multipartFiles) > 0 { - for _, f := range r.multipartFiles { - err = addFileReader(w, f) - if err != nil { - return - } + for _, f := range r.multipartFiles { + if err := addFileReader(w, f); err != nil { + return err } } // GitHub #130 adding multipart field support with content type - if len(r.multipartFields) > 0 { - for _, mf := range r.multipartFields { - if err = addMultipartFormField(w, mf); err != nil { - return - } + for _, mf := range r.multipartFields { + if err := addMultipartFormField(w, mf); err != nil { + return err } } r.Header.Set(hdrContentTypeKey, w.FormDataContentType()) - err = w.Close() - - return + return w.Close() } func handleFormData(c *Client, r *Request) { - formData := url.Values{} - for k, v := range c.FormData { - for _, iv := range v { - formData.Add(k, iv) + if _, ok := r.FormData[k]; ok { + continue } + r.FormData[k] = v[:] } - for k, v := range r.FormData { - // remove form data field from client level by key - // since overrides happens for that key in the request - formData.Del(k) - - for _, iv := range v { - formData.Add(k, iv) - } - } - - r.bodyBuf = bytes.NewBuffer([]byte(formData.Encode())) + r.bodyBuf = acquireBuffer() + r.bodyBuf.WriteString(r.FormData.Encode()) r.Header.Set(hdrContentTypeKey, formContentType) r.isFormData = true } @@ -435,45 +479,42 @@ func handleContentType(c *Client, r *Request) { } } -func handleRequestBody(c *Client, r *Request) (err error) { +func handleRequestBody(c *Client, r *Request) error { var bodyBytes []byte - contentType := r.Header.Get(hdrContentTypeKey) - kind := kindOf(r.Body) r.bodyBuf = nil - if reader, ok := r.Body.(io.Reader); ok { + switch body := r.Body.(type) { + case io.Reader: if c.setContentLength || r.setContentLength { // keep backward compatibility r.bodyBuf = acquireBuffer() - _, err = r.bodyBuf.ReadFrom(reader) + if _, err := r.bodyBuf.ReadFrom(body); err != nil { + return err + } r.Body = nil } else { // Otherwise buffer less processing for `io.Reader`, sounds good. - return - } - } else if b, ok := r.Body.([]byte); ok { - bodyBytes = b - } else if s, ok := r.Body.(string); ok { - bodyBytes = []byte(s) - } else if IsJSONType(contentType) && - (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { - r.bodyBuf, err = jsonMarshal(c, r, r.Body) - if err != nil { - return + return nil + } + case []byte: + bodyBytes = body + case string: + bodyBytes = []byte(body) + default: + contentType := r.Header.Get(hdrContentTypeKey) + kind := kindOf(r.Body) + var err error + if IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { + r.bodyBuf, err = jsonMarshal(c, r, r.Body) + } else if IsXMLType(contentType) && (kind == reflect.Struct) { + bodyBytes, err = c.XMLMarshal(r.Body) } - } else if IsXMLType(contentType) && (kind == reflect.Struct) { - bodyBytes, err = c.XMLMarshal(r.Body) if err != nil { - return + return err } } if bodyBytes == nil && r.bodyBuf == nil { - err = errors.New("unsupported 'Body' type/value") - } - - // if any errors during body bytes handling, return it - if err != nil { - return + return errors.New("unsupported 'Body' type/value") } // []byte into Buffer @@ -482,7 +523,7 @@ func handleRequestBody(c *Client, r *Request) (err error) { _, _ = r.bodyBuf.Write(bodyBytes) } - return + return nil } func saveResponseIntoFile(c *Client, res *Response) error { @@ -521,20 +562,25 @@ func saveResponseIntoFile(c *Client, res *Response) error { func getBodyCopy(r *Request) (*bytes.Buffer, error) { // If r.bodyBuf present, return the copy if r.bodyBuf != nil { - return bytes.NewBuffer(r.bodyBuf.Bytes()), nil + bodyCopy := acquireBuffer() + if _, err := io.Copy(bodyCopy, bytes.NewReader(r.bodyBuf.Bytes())); err != nil { + // cannot use io.Copy(bodyCopy, r.bodyBuf) because io.Copy reset r.bodyBuf + return nil, err + } + return bodyCopy, nil } // Maybe body is `io.Reader`. // Note: Resty user have to watchout for large body size of `io.Reader` if r.RawRequest.Body != nil { - b, err := ioutil.ReadAll(r.RawRequest.Body) + b, err := io.ReadAll(r.RawRequest.Body) if err != nil { return nil, err } // Restore the Body closeq(r.RawRequest.Body) - r.RawRequest.Body = ioutil.NopCloser(bytes.NewBuffer(b)) + r.RawRequest.Body = io.NopCloser(bytes.NewBuffer(b)) // Return the Body bytes return bytes.NewBuffer(b), nil diff --git a/vendor/github.com/go-resty/resty/v2/redirect.go b/vendor/github.com/go-resty/resty/v2/redirect.go index 7d7e43bc1..ed58d7352 100644 --- a/vendor/github.com/go-resty/resty/v2/redirect.go +++ b/vendor/github.com/go-resty/resty/v2/redirect.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -12,11 +12,16 @@ import ( "strings" ) +var ( + // Since v2.8.0 + ErrAutoRedirectDisabled = errors.New("auto redirect is disabled") +) + type ( // RedirectPolicy to regulate the redirects in the resty client. // Objects implementing the RedirectPolicy interface can be registered as // - // Apply function should return nil to continue the redirect jounery, otherwise + // Apply function should return nil to continue the redirect journey, otherwise // return error to stop the redirect. RedirectPolicy interface { Apply(req *http.Request, via []*http.Request) error @@ -33,15 +38,17 @@ func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error } // NoRedirectPolicy is used to disable redirects in the HTTP client -// resty.SetRedirectPolicy(NoRedirectPolicy()) +// +// resty.SetRedirectPolicy(NoRedirectPolicy()) func NoRedirectPolicy() RedirectPolicy { return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - return errors.New("auto redirect is disabled") + return ErrAutoRedirectDisabled }) } // FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client. -// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) +// +// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy { return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { if len(via) >= noOfRedirect { @@ -54,7 +61,8 @@ func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy { // DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client. // Redirect is allowed for only mentioned host in the policy. -// resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) +// +// resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy { hosts := make(map[string]bool) for _, h := range hostnames { @@ -85,7 +93,7 @@ func getHostname(host string) (hostname string) { } // By default Golang will not redirect request headers -// after go throughing various discussion comments from thread +// after go throwing various discussion comments from thread // https://github.com/golang/go/issues/4800 // Resty will add all the headers during a redirect for the same host func checkHostAndAddHeaders(cur *http.Request, pre *http.Request) { diff --git a/vendor/github.com/go-resty/resty/v2/request.go b/vendor/github.com/go-resty/resty/v2/request.go index 672df88c3..fec097638 100644 --- a/vendor/github.com/go-resty/resty/v2/request.go +++ b/vendor/github.com/go-resty/resty/v2/request.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -27,22 +27,24 @@ import ( // resty client. Request provides an options to override client level // settings and also an options for the request composition. type Request struct { - URL string - Method string - Token string - AuthScheme string - QueryParam url.Values - FormData url.Values - PathParams map[string]string - Header http.Header - Time time.Time - Body interface{} - Result interface{} - Error interface{} - RawRequest *http.Request - SRV *SRVRecord - UserInfo *User - Cookies []*http.Cookie + URL string + Method string + Token string + AuthScheme string + QueryParam url.Values + FormData url.Values + PathParams map[string]string + RawPathParams map[string]string + Header http.Header + Time time.Time + Body interface{} + Result interface{} + Error interface{} + RawRequest *http.Request + SRV *SRVRecord + UserInfo *User + Cookies []*http.Cookie + Debug bool // Attempt is to represent the request attempt made during a Resty // request execution flow, including retry count. @@ -65,6 +67,7 @@ type Request struct { client *Client bodyBuf *bytes.Buffer clientTrace *clientTrace + log Logger multipartFiles []*File multipartFields []*MultipartField retryConditions []RetryConditionFunc @@ -91,9 +94,10 @@ func (r *Request) SetContext(ctx context.Context) *Request { // SetHeader method is to set a single header field and its value in the current request. // // For Example: To set `Content-Type` and `Accept` as `application/json`. -// client.R(). -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") +// +// client.R(). +// SetHeader("Content-Type", "application/json"). +// SetHeader("Accept", "application/json") // // Also you can override header value, which was set at client instance level. func (r *Request) SetHeader(header, value string) *Request { @@ -105,11 +109,12 @@ func (r *Request) SetHeader(header, value string) *Request { // // For Example: To set `Content-Type` and `Accept` as `application/json` // -// client.R(). -// SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) +// client.R(). +// SetHeaders(map[string]string{ +// "Content-Type": "application/json", +// "Accept": "application/json", +// }) +// // Also you can override header value, which was set at client instance level. func (r *Request) SetHeaders(headers map[string]string) *Request { for h, v := range headers { @@ -122,10 +127,11 @@ func (r *Request) SetHeaders(headers map[string]string) *Request { // // For Example: To set `Accept` as `text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8` // -// client.R(). -// SetHeaderMultiValues(map[string][]string{ -// "Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"}, -// }) +// client.R(). +// SetHeaderMultiValues(map[string][]string{ +// "Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"}, +// }) +// // Also you can override header value, which was set at client instance level. func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request { for key, values := range headers { @@ -137,9 +143,10 @@ func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request { // SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request. // // For Example: To set `all_lowercase` and `UPPERCASE` as `available`. -// client.R(). -// SetHeaderVerbatim("all_lowercase", "available"). -// SetHeaderVerbatim("UPPERCASE", "available") +// +// client.R(). +// SetHeaderVerbatim("all_lowercase", "available"). +// SetHeaderVerbatim("UPPERCASE", "available") // // Also you can override header value, which was set at client instance level. // @@ -153,9 +160,11 @@ func (r *Request) SetHeaderVerbatim(header, value string) *Request { // It will be formed as query string for the request. // // For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// client.R(). -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") +// +// client.R(). +// SetQueryParam("search", "kitchen papers"). +// SetQueryParam("size", "large") +// // Also you can override query params value, which was set at client instance level. func (r *Request) SetQueryParam(param, value string) *Request { r.QueryParam.Set(param, value) @@ -166,11 +175,13 @@ func (r *Request) SetQueryParam(param, value string) *Request { // It will be formed as query string for the request. // // For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// client.R(). -// SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) +// +// client.R(). +// SetQueryParams(map[string]string{ +// "search": "kitchen papers", +// "size": "large", +// }) +// // Also you can override query params value, which was set at client instance level. func (r *Request) SetQueryParams(params map[string]string) *Request { for p, v := range params { @@ -184,10 +195,12 @@ func (r *Request) SetQueryParams(params map[string]string) *Request { // query string for the request. // // For Example: `status=pending&status=approved&status=open` in the URL after `?` mark. -// client.R(). -// SetQueryParamsFromValues(url.Values{ -// "status": []string{"pending", "approved", "open"}, -// }) +// +// client.R(). +// SetQueryParamsFromValues(url.Values{ +// "status": []string{"pending", "approved", "open"}, +// }) +// // Also you can override query params value, which was set at client instance level. func (r *Request) SetQueryParamsFromValues(params url.Values) *Request { for p, v := range params { @@ -201,8 +214,9 @@ func (r *Request) SetQueryParamsFromValues(params url.Values) *Request { // SetQueryString method provides ability to use string as an input to set URL query string for the request. // // Using String as an input -// client.R(). -// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") +// +// client.R(). +// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") func (r *Request) SetQueryString(query string) *Request { params, err := url.ParseQuery(strings.TrimSpace(query)) if err == nil { @@ -212,7 +226,7 @@ func (r *Request) SetQueryString(query string) *Request { } } } else { - r.client.log.Errorf("%v", err) + r.log.Errorf("%v", err) } return r } @@ -220,11 +234,13 @@ func (r *Request) SetQueryString(query string) *Request { // SetFormData method sets Form parameters and their values in the current request. // It's applicable only HTTP method `POST` and `PUT` and requests content type would be set as // `application/x-www-form-urlencoded`. -// client.R(). -// SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) +// +// client.R(). +// SetFormData(map[string]string{ +// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", +// "user_id": "3455454545", +// }) +// // Also you can override form data value, which was set at client instance level. func (r *Request) SetFormData(data map[string]string) *Request { for k, v := range data { @@ -235,10 +251,12 @@ func (r *Request) SetFormData(data map[string]string) *Request { // SetFormDataFromValues method appends multiple form parameters with multi-value // (`url.Values`) at one go in the current request. -// client.R(). -// SetFormDataFromValues(url.Values{ -// "search_criteria": []string{"book", "glass", "pencil"}, -// }) +// +// client.R(). +// SetFormDataFromValues(url.Values{ +// "search_criteria": []string{"book", "glass", "pencil"}, +// }) +// // Also you can override form data value, which was set at client instance level. func (r *Request) SetFormDataFromValues(data url.Values) *Request { for k, v := range data { @@ -257,36 +275,40 @@ func (r *Request) SetFormDataFromValues(data url.Values) *Request { // Note: `io.Reader` is processed as bufferless mode while sending request. // // For Example: Struct as a body input, based on content type, it will be marshalled. -// client.R(). -// SetBody(User{ -// Username: "jeeva@myjeeva.com", -// Password: "welcome2resty", -// }) +// +// client.R(). +// SetBody(User{ +// Username: "jeeva@myjeeva.com", +// Password: "welcome2resty", +// }) // // Map as a body input, based on content type, it will be marshalled. -// client.R(). -// SetBody(map[string]interface{}{ -// "username": "jeeva@myjeeva.com", -// "password": "welcome2resty", -// "address": &Address{ -// Address1: "1111 This is my street", -// Address2: "Apt 201", -// City: "My City", -// State: "My State", -// ZipCode: 00000, -// }, -// }) +// +// client.R(). +// SetBody(map[string]interface{}{ +// "username": "jeeva@myjeeva.com", +// "password": "welcome2resty", +// "address": &Address{ +// Address1: "1111 This is my street", +// Address2: "Apt 201", +// City: "My City", +// State: "My State", +// ZipCode: 00000, +// }, +// }) // // String as a body input. Suitable for any need as a string input. -// client.R(). -// SetBody(`{ -// "username": "jeeva@getrightcare.com", -// "password": "admin" -// }`) +// +// client.R(). +// SetBody(`{ +// "username": "jeeva@getrightcare.com", +// "password": "admin" +// }`) // // []byte as a body input. Suitable for raw request such as file upload, serialize & deserialize, etc. -// client.R(). -// SetBody([]byte("This is my raw request, sent as-is")) +// +// client.R(). +// SetBody([]byte("This is my raw request, sent as-is")) func (r *Request) SetBody(body interface{}) *Request { r.Body = body return r @@ -296,14 +318,18 @@ func (r *Request) SetBody(body interface{}) *Request { // if response status code is between 200 and 299 and content type either JSON or XML. // // Note: Result object can be pointer or non-pointer. -// client.R().SetResult(&AuthToken{}) -// // OR -// client.R().SetResult(AuthToken{}) +// +// client.R().SetResult(&AuthToken{}) +// // OR +// client.R().SetResult(AuthToken{}) // // Accessing a result value from response instance. -// response.Result().(*AuthToken) +// +// response.Result().(*AuthToken) func (r *Request) SetResult(res interface{}) *Request { - r.Result = getPointer(res) + if res != nil { + r.Result = getPointer(res) + } return r } @@ -311,18 +337,21 @@ func (r *Request) SetResult(res interface{}) *Request { // if response status code is greater than 399 and content type either JSON or XML. // // Note: Error object can be pointer or non-pointer. -// client.R().SetError(&AuthError{}) -// // OR -// client.R().SetError(AuthError{}) +// +// client.R().SetError(&AuthError{}) +// // OR +// client.R().SetError(AuthError{}) // // Accessing a error value from response instance. -// response.Error().(*AuthError) +// +// response.Error().(*AuthError) func (r *Request) SetError(err interface{}) *Request { r.Error = getPointer(err) return r } // SetFile method is to set single file field name and its path for multipart upload. +// // client.R(). // SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf") func (r *Request) SetFile(param, filePath string) *Request { @@ -332,6 +361,7 @@ func (r *Request) SetFile(param, filePath string) *Request { } // SetFiles method is to set multiple file field name and its path for multipart upload. +// // client.R(). // SetFiles(map[string]string{ // "my_file1": "/Users/jeeva/Gas Bill - Sep.pdf", @@ -347,6 +377,7 @@ func (r *Request) SetFiles(files map[string]string) *Request { } // SetFileReader method is to set single file using io.Reader for multipart upload. +// // client.R(). // SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)). // SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes)) @@ -384,8 +415,9 @@ func (r *Request) SetMultipartField(param, fileName, contentType string, reader // SetMultipartFields method is to set multiple data fields using io.Reader for multipart upload. // // For Example: -// client.R().SetMultipartFields( -// &resty.MultipartField{ +// +// client.R().SetMultipartFields( +// &resty.MultipartField{ // Param: "uploadManifest1", // FileName: "upload-file-1.json", // ContentType: "application/json", @@ -399,7 +431,8 @@ func (r *Request) SetMultipartField(param, fileName, contentType string, reader // }) // // If you have slice already, then simply call- -// client.R().SetMultipartFields(fields...) +// +// client.R().SetMultipartFields(fields...) func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request { r.isMultiPart = true r.multipartFields = append(r.multipartFields, fields...) @@ -411,7 +444,8 @@ func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request { // request. // // See `Client.SetContentLength` -// client.R().SetContentLength(true) +// +// client.R().SetContentLength(true) func (r *Request) SetContentLength(l bool) *Request { r.setContentLength = l return r @@ -420,10 +454,12 @@ func (r *Request) SetContentLength(l bool) *Request { // SetBasicAuth method sets the basic authentication header in the current HTTP request. // // For Example: -// Authorization: Basic +// +// Authorization: Basic // // To set the header for username "go-resty" and password "welcome" -// client.R().SetBasicAuth("go-resty", "welcome") +// +// client.R().SetBasicAuth("go-resty", "welcome") // // This method overrides the credentials set by method `Client.SetBasicAuth`. func (r *Request) SetBasicAuth(username, password string) *Request { @@ -432,11 +468,12 @@ func (r *Request) SetBasicAuth(username, password string) *Request { } // SetAuthToken method sets the auth token header(Default Scheme: Bearer) in the current HTTP request. Header example: -// Authorization: Bearer +// +// Authorization: Bearer // // For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F // -// client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") +// client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") // // This method overrides the Auth token set by method `Client.SetAuthToken`. func (r *Request) SetAuthToken(token string) *Request { @@ -445,19 +482,21 @@ func (r *Request) SetAuthToken(token string) *Request { } // SetAuthScheme method sets the auth token scheme type in the HTTP request. For Example: -// Authorization: +// +// Authorization: // // For Example: To set the scheme to use OAuth // -// client.R().SetAuthScheme("OAuth") +// client.R().SetAuthScheme("OAuth") // -// This auth header scheme gets added to all the request rasied from this client instance. +// This auth header scheme gets added to all the request raised from this client instance. // Also it can be overridden or set one at the request level is supported. // // Information about Auth schemes can be found in RFC7235 which is linked to below along with the page containing // the currently defined official authentication schemes: -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes +// +// https://tools.ietf.org/html/rfc7235 +// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes // // This method overrides the Authorization scheme set by method `Client.SetAuthScheme`. func (r *Request) SetAuthScheme(scheme string) *Request { @@ -465,13 +504,43 @@ func (r *Request) SetAuthScheme(scheme string) *Request { return r } +// SetDigestAuth method sets the Digest Access auth scheme for the HTTP request. If a server responds with 401 and sends +// a Digest challenge in the WWW-Authenticate Header, the request will be resent with the appropriate Authorization Header. +// +// For Example: To set the Digest scheme with username "Mufasa" and password "Circle Of Life" +// +// client.R().SetDigestAuth("Mufasa", "Circle Of Life") +// +// Information about Digest Access Authentication can be found in RFC7616: +// +// https://datatracker.ietf.org/doc/html/rfc7616 +// +// This method overrides the username and password set by method `Client.SetDigestAuth`. +func (r *Request) SetDigestAuth(username, password string) *Request { + oldTransport := r.client.httpClient.Transport + r.client.OnBeforeRequest(func(c *Client, _ *Request) error { + c.httpClient.Transport = &digestTransport{ + digestCredentials: digestCredentials{username, password}, + transport: oldTransport, + } + return nil + }) + r.client.OnAfterResponse(func(c *Client, _ *Response) error { + c.httpClient.Transport = oldTransport + return nil + }) + + return r +} + // SetOutput method sets the output file for current HTTP request. Current HTTP response will be // saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used. // If is it relative path then output file goes under the output directory, as mentioned // in the `Client.SetOutputDirectory`. -// client.R(). -// SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip"). -// Get("http://bit.ly/1LouEKr") +// +// client.R(). +// SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip"). +// Get("http://bit.ly/1LouEKr") // // Note: In this scenario `Response.Body` might be nil. func (r *Request) SetOutput(file string) *Request { @@ -482,9 +551,10 @@ func (r *Request) SetOutput(file string) *Request { // SetSRV method sets the details to query the service SRV record and execute the // request. -// client.R(). -// SetSRV(SRVRecord{"web", "testservice.com"}). -// Get("/get") +// +// client.R(). +// SetSRV(SRVRecord{"web", "testservice.com"}). +// Get("/get") func (r *Request) SetSRV(srv *SRVRecord) *Request { r.SRV = srv return r @@ -503,13 +573,24 @@ func (r *Request) SetDoNotParseResponse(parse bool) *Request { // SetPathParam method sets single URL path key-value pair in the // Resty current request instance. -// client.R().SetPathParam("userId", "sample@sample.com") // -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details -// It replaces the value of the key while composing the request URL. Also you can -// override Path Params value, which was set at client instance level. +// client.R().SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// +// client.R().SetPathParam("path", "groups/developers") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/groups%2Fdevelopers/details +// +// It replaces the value of the key while composing the request URL. +// The values will be escaped using `url.PathEscape` function. +// +// Also you can override Path Params value, which was set at client instance +// level. func (r *Request) SetPathParam(param, value string) *Request { r.PathParams[param] = value return r @@ -517,16 +598,22 @@ func (r *Request) SetPathParam(param, value string) *Request { // SetPathParams method sets multiple URL path key-value pairs at one go in the // Resty current request instance. -// client.R().SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details -// It replaces the value of the key while composing request URL. Also you can -// override Path Params value, which was set at client instance level. +// +// client.R().SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details +// +// It replaces the value of the key while composing request URL. +// The value will be used as it is and will not be escaped. +// +// Also you can override Path Params value, which was set at client instance +// level. func (r *Request) SetPathParams(params map[string]string) *Request { for p, v := range params { r.SetPathParam(p, v) @@ -534,6 +621,60 @@ func (r *Request) SetPathParams(params map[string]string) *Request { return r } +// SetRawPathParam method sets single URL path key-value pair in the +// Resty current request instance. +// +// client.R().SetPathParam("userId", "sample@sample.com") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/sample@sample.com/details +// +// client.R().SetPathParam("path", "groups/developers") +// +// Result: +// URL - /v1/users/{userId}/details +// Composed URL - /v1/users/groups/developers/details +// +// It replaces the value of the key while composing the request URL. +// The value will be used as it is and will not be escaped. +// +// Also you can override Path Params value, which was set at client instance +// level. +// +// Since v2.8.0 +func (r *Request) SetRawPathParam(param, value string) *Request { + r.RawPathParams[param] = value + return r +} + +// SetRawPathParams method sets multiple URL path key-value pairs at one go in the +// Resty current request instance. +// +// client.R().SetPathParams(map[string]string{ +// "userId": "sample@sample.com", +// "subAccountId": "100002", +// "path": "groups/developers", +// }) +// +// Result: +// URL - /v1/users/{userId}/{subAccountId}/{path}/details +// Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details +// +// It replaces the value of the key while composing request URL. +// The values will be used as they are and will not be escaped. +// +// Also you can override Path Params value, which was set at client instance +// level. +// +// Since v2.8.0 +func (r *Request) SetRawPathParams(params map[string]string) *Request { + for p, v := range params { + r.SetRawPathParam(p, v) + } + return r +} + // ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling // when `Content-Type` response header is unavailable. func (r *Request) ExpectContentType(contentType string) *Request { @@ -558,10 +699,11 @@ func (r *Request) SetJSONEscapeHTML(b bool) *Request { } // SetCookie method appends a single cookie in the current request instance. -// client.R().SetCookie(&http.Cookie{ -// Name:"go-resty", -// Value:"This is cookie value", -// }) +// +// client.R().SetCookie(&http.Cookie{ +// Name:"go-resty", +// Value:"This is cookie value", +// }) // // Note: Method appends the Cookie value into existing Cookie if already existing. // @@ -572,19 +714,20 @@ func (r *Request) SetCookie(hc *http.Cookie) *Request { } // SetCookies method sets an array of cookies in the current request instance. -// cookies := []*http.Cookie{ -// &http.Cookie{ -// Name:"go-resty-1", -// Value:"This is cookie 1 value", -// }, -// &http.Cookie{ -// Name:"go-resty-2", -// Value:"This is cookie 2 value", -// }, -// } -// -// // Setting a cookies into resty's current request -// client.R().SetCookies(cookies) +// +// cookies := []*http.Cookie{ +// &http.Cookie{ +// Name:"go-resty-1", +// Value:"This is cookie 1 value", +// }, +// &http.Cookie{ +// Name:"go-resty-2", +// Value:"This is cookie 2 value", +// }, +// } +// +// // Setting a cookies into resty's current request +// client.R().SetCookies(cookies) // // Note: Method appends the Cookie value into existing Cookie if already existing. // @@ -594,6 +737,26 @@ func (r *Request) SetCookies(rs []*http.Cookie) *Request { return r } +// SetLogger method sets given writer for logging Resty request and response details. +// By default, requests and responses inherit their logger from the client. +// +// Compliant to interface `resty.Logger`. +func (r *Request) SetLogger(l Logger) *Request { + r.log = l + return r +} + +// SetDebug method enables the debug mode on current request Resty request, It logs +// the details current request and response. +// For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. +// For `Response` it logs information such as Status, Response Time, Headers, Body if it has one. +// +// client.R().SetDebug(true) +func (r *Request) SetDebug(d bool) *Request { + r.Debug = d + return r +} + // AddRetryCondition method adds a retry condition function to the request's // array of functions that are checked to determine if the request is retried. // The request will retry if any of the functions return true and error is nil. @@ -613,11 +776,11 @@ func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request { // EnableTrace method enables trace for the current request // using `httptrace.ClientTrace` and provides insights. // -// client := resty.New() +// client := resty.New() // -// resp, err := client.R().EnableTrace().Get("https://httpbin.org/get") -// fmt.Println("Error:", err) -// fmt.Println("Trace Info:", resp.Request.TraceInfo()) +// resp, err := client.R().EnableTrace().Get("https://httpbin.org/get") +// fmt.Println("Error:", err) +// fmt.Println("Trace Info:", resp.Request.TraceInfo()) // // See `Client.EnableTrace` available too to get trace info for all requests. // @@ -721,25 +884,40 @@ func (r *Request) Patch(url string) (*Response, error) { // Send method performs the HTTP request using the method and URL already defined // for current `Request`. -// req := client.R() -// req.Method = resty.GET -// req.URL = "http://httpbin.org/get" -// resp, err := client.R().Send() +// +// req := client.R() +// req.Method = resty.GET +// req.URL = "http://httpbin.org/get" +// resp, err := req.Send() func (r *Request) Send() (*Response, error) { return r.Execute(r.Method, r.URL) } // Execute method performs the HTTP request with given HTTP method and URL // for current `Request`. -// resp, err := client.R().Execute(resty.GET, "http://httpbin.org/get") +// +// resp, err := client.R().Execute(resty.GET, "http://httpbin.org/get") func (r *Request) Execute(method, url string) (*Response, error) { var addrs []*net.SRV var resp *Response var err error + defer func() { + if rec := recover(); rec != nil { + if err, ok := rec.(error); ok { + r.client.onPanicHooks(r, err) + } else { + r.client.onPanicHooks(r, fmt.Errorf("panic %v", rec)) + } + panic(rec) + } + }() + if r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) { // No OnError hook here since this is a request validation error - return nil, fmt.Errorf("multipart content is not allowed in HTTP verb [%v]", method) + err := fmt.Errorf("multipart content is not allowed in HTTP verb [%v]", method) + r.client.onInvalidHooks(r, err) + return nil, err } if r.SRV != nil { @@ -768,7 +946,7 @@ func (r *Request) Execute(method, url string) (*Response, error) { resp, err = r.client.execute(r) if err != nil { - r.client.log.Errorf("%v, Attempt %v", err, r.Attempt) + r.log.Warnf("%v, Attempt %v", err, r.Attempt) } return resp, err @@ -778,10 +956,14 @@ func (r *Request) Execute(method, url string) (*Response, error) { MaxWaitTime(r.client.RetryMaxWaitTime), RetryConditions(append(r.retryConditions, r.client.RetryConditions...)), RetryHooks(r.client.RetryHooks), + ResetMultipartReaders(r.client.RetryResetReaders), ) - r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) + if err != nil { + r.log.Errorf("%v", err) + } + r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) return resp, unwrapNoRetryErr(err) } @@ -832,7 +1014,7 @@ func (r *Request) fmtBodyString(sl int64) (body string) { contentType := r.Header.Get(hdrContentTypeKey) kind := kindOf(r.Body) if canJSONMarshal(contentType, kind) { - prtBodyBytes, err = json.MarshalIndent(&r.Body, "", " ") + prtBodyBytes, err = noescapeJSONMarshalIndent(&r.Body) } else if IsXMLType(contentType) && (kind == reflect.Struct) { prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ") } else if b, ok := r.Body.(string); ok { @@ -894,3 +1076,18 @@ var noescapeJSONMarshal = func(v interface{}) (*bytes.Buffer, error) { return buf, nil } + +var noescapeJSONMarshalIndent = func(v interface{}) ([]byte, error) { + buf := acquireBuffer() + defer releaseBuffer(buf) + + encoder := json.NewEncoder(buf) + encoder.SetEscapeHTML(false) + encoder.SetIndent("", " ") + + if err := encoder.Encode(v); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} diff --git a/vendor/github.com/go-resty/resty/v2/response.go b/vendor/github.com/go-resty/resty/v2/response.go index 8ae0e10ba..63c95c418 100644 --- a/vendor/github.com/go-resty/resty/v2/response.go +++ b/vendor/github.com/go-resty/resty/v2/response.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -37,7 +37,20 @@ func (r *Response) Body() []byte { return r.body } +// SetBody method is to set Response body in byte slice. Typically, +// its helpful for test cases. +// +// resp.SetBody([]byte("This is test body content")) +// resp.SetBody(nil) +// +// Since v2.10.0 +func (r *Response) SetBody(b []byte) *Response { + r.body = b + return r +} + // Status method returns the HTTP status string for the executed request. +// // Example: 200 OK func (r *Response) Status() string { if r.RawResponse == nil { @@ -47,6 +60,7 @@ func (r *Response) Status() string { } // StatusCode method returns the HTTP status code for the executed request. +// // Example: 200 func (r *Response) StatusCode() int { if r.RawResponse == nil { @@ -91,7 +105,7 @@ func (r *Response) Cookies() []*http.Cookie { // String method returns the body of the server response as String. func (r *Response) String() string { - if r.body == nil { + if len(r.body) == 0 { return "" } return strings.TrimSpace(string(r.body)) @@ -154,7 +168,7 @@ func (r *Response) setReceivedAt() { } func (r *Response) fmtBodyString(sl int64) string { - if r.body != nil { + if len(r.body) > 0 { if int64(len(r.body)) > sl { return fmt.Sprintf("***** RESPONSE TOO LARGE (size - %d) *****", len(r.body)) } diff --git a/vendor/github.com/go-resty/resty/v2/resty.go b/vendor/github.com/go-resty/resty/v2/resty.go index 6f9c8b4cd..21dcd5655 100644 --- a/vendor/github.com/go-resty/resty/v2/resty.go +++ b/vendor/github.com/go-resty/resty/v2/resty.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -14,7 +14,7 @@ import ( ) // Version # of resty -const Version = "2.7.0" +const Version = "2.10.0" // New method creates a new Resty client. func New() *Client { diff --git a/vendor/github.com/go-resty/resty/v2/retry.go b/vendor/github.com/go-resty/resty/v2/retry.go index 00b8514a5..c5eda26be 100644 --- a/vendor/github.com/go-resty/resty/v2/retry.go +++ b/vendor/github.com/go-resty/resty/v2/retry.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -6,6 +6,7 @@ package resty import ( "context" + "io" "math" "math/rand" "sync" @@ -43,6 +44,7 @@ type ( maxWaitTime time.Duration retryConditions []RetryConditionFunc retryHooks []OnRetryFunc + resetReaders bool } ) @@ -81,6 +83,14 @@ func RetryHooks(hooks []OnRetryFunc) Option { } } +// ResetMultipartReaders sets a boolean value which will lead the start being seeked out +// on all multipart file readers, if they implement io.ReadSeeker +func ResetMultipartReaders(value bool) Option { + return func(o *Options) { + o.resetReaders = value + } +} + // Backoff retries with increasing timeout duration up until X amount of retries // (Default is 3 attempts, Override with option Retries(n)) func Backoff(operation func() (*Response, error), options ...Option) error { @@ -125,6 +135,12 @@ func Backoff(operation func() (*Response, error), options ...Option) error { return err } + if opts.resetReaders { + if err := resetFileReaders(resp.Request.multipartFiles); err != nil { + return err + } + } + for _, hook := range opts.retryHooks { hook(resp, err) } @@ -193,6 +209,9 @@ func jitterBackoff(min, max time.Duration, attempt int) time.Duration { temp := math.Min(capLevel, base*math.Exp2(float64(attempt))) ri := time.Duration(temp / 2) + if ri == 0 { + ri = time.Nanosecond + } result := randDuration(ri) if result < min { @@ -219,3 +238,15 @@ func newRnd() *rand.Rand { var src = rand.NewSource(seed) return rand.New(src) } + +func resetFileReaders(files []*File) error { + for _, f := range files { + if rs, ok := f.Reader.(io.ReadSeeker); ok { + if _, err := rs.Seek(0, io.SeekStart); err != nil { + return err + } + } + } + + return nil +} diff --git a/vendor/github.com/go-resty/resty/v2/trace.go b/vendor/github.com/go-resty/resty/v2/trace.go index 23cf70335..be7555c23 100644 --- a/vendor/github.com/go-resty/resty/v2/trace.go +++ b/vendor/github.com/go-resty/resty/v2/trace.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/go-resty/resty/v2/transport.go b/vendor/github.com/go-resty/resty/v2/transport.go index e15b48c55..191cd5193 100644 --- a/vendor/github.com/go-resty/resty/v2/transport.go +++ b/vendor/github.com/go-resty/resty/v2/transport.go @@ -1,6 +1,7 @@ +//go:build go1.13 // +build go1.13 -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -24,7 +25,7 @@ func createTransport(localAddr net.Addr) *http.Transport { } return &http.Transport{ Proxy: http.ProxyFromEnvironment, - DialContext: dialer.DialContext, + DialContext: transportDialContext(dialer), ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, diff --git a/vendor/github.com/go-resty/resty/v2/transport112.go b/vendor/github.com/go-resty/resty/v2/transport112.go index fbbbc5911..d4aa4175f 100644 --- a/vendor/github.com/go-resty/resty/v2/transport112.go +++ b/vendor/github.com/go-resty/resty/v2/transport112.go @@ -1,6 +1,7 @@ +//go:build !go1.13 // +build !go1.13 -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/go-resty/resty/v2/transport_js.go b/vendor/github.com/go-resty/resty/v2/transport_js.go new file mode 100644 index 000000000..6227aa9ca --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/transport_js.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js && wasm +// +build js,wasm + +package resty + +import ( + "context" + "net" +) + +func transportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { + return nil +} diff --git a/vendor/github.com/go-resty/resty/v2/transport_other.go b/vendor/github.com/go-resty/resty/v2/transport_other.go new file mode 100644 index 000000000..73553c36f --- /dev/null +++ b/vendor/github.com/go-resty/resty/v2/transport_other.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !(js && wasm) +// +build !js !wasm + +package resty + +import ( + "context" + "net" +) + +func transportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { + return dialer.DialContext +} diff --git a/vendor/github.com/go-resty/resty/v2/util.go b/vendor/github.com/go-resty/resty/v2/util.go index 1d563befd..27b466dc1 100644 --- a/vendor/github.com/go-resty/resty/v2/util.go +++ b/vendor/github.com/go-resty/resty/v2/util.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. +// Copyright (c) 2015-2023 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. // resty source code and usage is governed by a MIT style // license that can be found in the LICENSE file. @@ -6,6 +6,7 @@ package resty import ( "bytes" + "errors" "fmt" "io" "log" @@ -64,6 +65,16 @@ func (l *logger) output(format string, v ...interface{}) { l.l.Printf(format, v...) } +//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ +// Rate Limiter interface +//_______________________________________________________________________ + +type RateLimiter interface { + Allow() bool +} + +var ErrRateLimitExceeded = errors.New("rate limit exceeded") + //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ // Package Helper methods //_______________________________________________________________________ @@ -328,25 +339,7 @@ func silently(_ ...interface{}) {} func composeHeaders(c *Client, r *Request, hdrs http.Header) string { str := make([]string, 0, len(hdrs)) for _, k := range sortHeaderKeys(hdrs) { - var v string - if k == "Cookie" { - cv := strings.TrimSpace(strings.Join(hdrs[k], ", ")) - if c.GetClient().Jar != nil { - for _, c := range c.GetClient().Jar.Cookies(r.RawRequest.URL) { - if cv != "" { - cv = cv + "; " + c.String() - } else { - cv = c.String() - } - } - } - v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, cv)) - } else { - v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", "))) - } - if v != "" { - str = append(str, "\t"+v) - } + str = append(str, "\t"+strings.TrimSpace(fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", ")))) } return strings.Join(str, "\n") } diff --git a/vendor/github.com/gogo/protobuf/jsonpb/jsonpb.go b/vendor/github.com/gogo/protobuf/jsonpb/jsonpb.go new file mode 100644 index 000000000..e8134ec8b --- /dev/null +++ b/vendor/github.com/gogo/protobuf/jsonpb/jsonpb.go @@ -0,0 +1,1435 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2015 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/* +Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON. +It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json. + +This package produces a different output than the standard "encoding/json" package, +which does not operate correctly on protocol buffers. +*/ +package jsonpb + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "reflect" + "sort" + "strconv" + "strings" + "time" + + "github.com/gogo/protobuf/proto" + "github.com/gogo/protobuf/types" +) + +const secondInNanos = int64(time.Second / time.Nanosecond) +const maxSecondsInDuration = 315576000000 + +// Marshaler is a configurable object for converting between +// protocol buffer objects and a JSON representation for them. +type Marshaler struct { + // Whether to render enum values as integers, as opposed to string values. + EnumsAsInts bool + + // Whether to render fields with zero values. + EmitDefaults bool + + // A string to indent each level by. The presence of this field will + // also cause a space to appear between the field separator and + // value, and for newlines to be appear between fields and array + // elements. + Indent string + + // Whether to use the original (.proto) name for fields. + OrigName bool + + // A custom URL resolver to use when marshaling Any messages to JSON. + // If unset, the default resolution strategy is to extract the + // fully-qualified type name from the type URL and pass that to + // proto.MessageType(string). + AnyResolver AnyResolver +} + +// AnyResolver takes a type URL, present in an Any message, and resolves it into +// an instance of the associated message. +type AnyResolver interface { + Resolve(typeUrl string) (proto.Message, error) +} + +func defaultResolveAny(typeUrl string) (proto.Message, error) { + // Only the part of typeUrl after the last slash is relevant. + mname := typeUrl + if slash := strings.LastIndex(mname, "/"); slash >= 0 { + mname = mname[slash+1:] + } + mt := proto.MessageType(mname) + if mt == nil { + return nil, fmt.Errorf("unknown message type %q", mname) + } + return reflect.New(mt.Elem()).Interface().(proto.Message), nil +} + +// JSONPBMarshaler is implemented by protobuf messages that customize the +// way they are marshaled to JSON. Messages that implement this should +// also implement JSONPBUnmarshaler so that the custom format can be +// parsed. +// +// The JSON marshaling must follow the proto to JSON specification: +// https://developers.google.com/protocol-buffers/docs/proto3#json +type JSONPBMarshaler interface { + MarshalJSONPB(*Marshaler) ([]byte, error) +} + +// JSONPBUnmarshaler is implemented by protobuf messages that customize +// the way they are unmarshaled from JSON. Messages that implement this +// should also implement JSONPBMarshaler so that the custom format can be +// produced. +// +// The JSON unmarshaling must follow the JSON to proto specification: +// https://developers.google.com/protocol-buffers/docs/proto3#json +type JSONPBUnmarshaler interface { + UnmarshalJSONPB(*Unmarshaler, []byte) error +} + +// Marshal marshals a protocol buffer into JSON. +func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error { + v := reflect.ValueOf(pb) + if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) { + return errors.New("Marshal called with nil") + } + // Check for unset required fields first. + if err := checkRequiredFields(pb); err != nil { + return err + } + writer := &errWriter{writer: out} + return m.marshalObject(writer, pb, "", "") +} + +// MarshalToString converts a protocol buffer object to JSON string. +func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) { + var buf bytes.Buffer + if err := m.Marshal(&buf, pb); err != nil { + return "", err + } + return buf.String(), nil +} + +type int32Slice []int32 + +var nonFinite = map[string]float64{ + `"NaN"`: math.NaN(), + `"Infinity"`: math.Inf(1), + `"-Infinity"`: math.Inf(-1), +} + +// For sorting extensions ids to ensure stable output. +func (s int32Slice) Len() int { return len(s) } +func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } +func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +type isWkt interface { + XXX_WellKnownType() string +} + +var ( + wktType = reflect.TypeOf((*isWkt)(nil)).Elem() + messageType = reflect.TypeOf((*proto.Message)(nil)).Elem() +) + +// marshalObject writes a struct to the Writer. +func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error { + if jsm, ok := v.(JSONPBMarshaler); ok { + b, err := jsm.MarshalJSONPB(m) + if err != nil { + return err + } + if typeURL != "" { + // we are marshaling this object to an Any type + var js map[string]*json.RawMessage + if err = json.Unmarshal(b, &js); err != nil { + return fmt.Errorf("type %T produced invalid JSON: %v", v, err) + } + turl, err := json.Marshal(typeURL) + if err != nil { + return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err) + } + js["@type"] = (*json.RawMessage)(&turl) + if m.Indent != "" { + b, err = json.MarshalIndent(js, indent, m.Indent) + } else { + b, err = json.Marshal(js) + } + if err != nil { + return err + } + } + + out.write(string(b)) + return out.err + } + + s := reflect.ValueOf(v).Elem() + + // Handle well-known types. + if wkt, ok := v.(isWkt); ok { + switch wkt.XXX_WellKnownType() { + case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", + "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": + // "Wrappers use the same representation in JSON + // as the wrapped primitive type, ..." + sprop := proto.GetProperties(s.Type()) + return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent) + case "Any": + // Any is a bit more involved. + return m.marshalAny(out, v, indent) + case "Duration": + s, ns := s.Field(0).Int(), s.Field(1).Int() + if s < -maxSecondsInDuration || s > maxSecondsInDuration { + return fmt.Errorf("seconds out of range %v", s) + } + if ns <= -secondInNanos || ns >= secondInNanos { + return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos) + } + if (s > 0 && ns < 0) || (s < 0 && ns > 0) { + return errors.New("signs of seconds and nanos do not match") + } + // Generated output always contains 0, 3, 6, or 9 fractional digits, + // depending on required precision, followed by the suffix "s". + f := "%d.%09d" + if ns < 0 { + ns = -ns + if s == 0 { + f = "-%d.%09d" + } + } + x := fmt.Sprintf(f, s, ns) + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + out.write(`"`) + out.write(x) + out.write(`s"`) + return out.err + case "Struct", "ListValue": + // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice. + // TODO: pass the correct Properties if needed. + return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent) + case "Timestamp": + // "RFC 3339, where generated output will always be Z-normalized + // and uses 0, 3, 6 or 9 fractional digits." + s, ns := s.Field(0).Int(), s.Field(1).Int() + if ns < 0 || ns >= secondInNanos { + return fmt.Errorf("ns out of range [0, %v)", secondInNanos) + } + t := time.Unix(s, ns).UTC() + // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). + x := t.Format("2006-01-02T15:04:05.000000000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + out.write(`"`) + out.write(x) + out.write(`Z"`) + return out.err + case "Value": + // Value has a single oneof. + kind := s.Field(0) + if kind.IsNil() { + // "absence of any variant indicates an error" + return errors.New("nil Value") + } + // oneof -> *T -> T -> T.F + x := kind.Elem().Elem().Field(0) + // TODO: pass the correct Properties if needed. + return m.marshalValue(out, &proto.Properties{}, x, indent) + } + } + + out.write("{") + if m.Indent != "" { + out.write("\n") + } + + firstField := true + + if typeURL != "" { + if err := m.marshalTypeURL(out, indent, typeURL); err != nil { + return err + } + firstField = false + } + + for i := 0; i < s.NumField(); i++ { + value := s.Field(i) + valueField := s.Type().Field(i) + if strings.HasPrefix(valueField.Name, "XXX_") { + continue + } + + //this is not a protobuf field + if valueField.Tag.Get("protobuf") == "" && valueField.Tag.Get("protobuf_oneof") == "" { + continue + } + + // IsNil will panic on most value kinds. + switch value.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface: + if value.IsNil() { + continue + } + } + + if !m.EmitDefaults { + switch value.Kind() { + case reflect.Bool: + if !value.Bool() { + continue + } + case reflect.Int32, reflect.Int64: + if value.Int() == 0 { + continue + } + case reflect.Uint32, reflect.Uint64: + if value.Uint() == 0 { + continue + } + case reflect.Float32, reflect.Float64: + if value.Float() == 0 { + continue + } + case reflect.String: + if value.Len() == 0 { + continue + } + case reflect.Map, reflect.Ptr, reflect.Slice: + if value.IsNil() { + continue + } + } + } + + // Oneof fields need special handling. + if valueField.Tag.Get("protobuf_oneof") != "" { + // value is an interface containing &T{real_value}. + sv := value.Elem().Elem() // interface -> *T -> T + value = sv.Field(0) + valueField = sv.Type().Field(0) + } + prop := jsonProperties(valueField, m.OrigName) + if !firstField { + m.writeSep(out) + } + // If the map value is a cast type, it may not implement proto.Message, therefore + // allow the struct tag to declare the underlying message type. Change the property + // of the child types, use CustomType as a passer. CastType currently property is + // not used in json encoding. + if value.Kind() == reflect.Map { + if tag := valueField.Tag.Get("protobuf"); tag != "" { + for _, v := range strings.Split(tag, ",") { + if !strings.HasPrefix(v, "castvaluetype=") { + continue + } + v = strings.TrimPrefix(v, "castvaluetype=") + prop.MapValProp.CustomType = v + break + } + } + } + if err := m.marshalField(out, prop, value, indent); err != nil { + return err + } + firstField = false + } + + // Handle proto2 extensions. + if ep, ok := v.(proto.Message); ok { + extensions := proto.RegisteredExtensions(v) + // Sort extensions for stable output. + ids := make([]int32, 0, len(extensions)) + for id, desc := range extensions { + if !proto.HasExtension(ep, desc) { + continue + } + ids = append(ids, id) + } + sort.Sort(int32Slice(ids)) + for _, id := range ids { + desc := extensions[id] + if desc == nil { + // unknown extension + continue + } + ext, extErr := proto.GetExtension(ep, desc) + if extErr != nil { + return extErr + } + value := reflect.ValueOf(ext) + var prop proto.Properties + prop.Parse(desc.Tag) + prop.JSONName = fmt.Sprintf("[%s]", desc.Name) + if !firstField { + m.writeSep(out) + } + if err := m.marshalField(out, &prop, value, indent); err != nil { + return err + } + firstField = false + } + + } + + if m.Indent != "" { + out.write("\n") + out.write(indent) + } + out.write("}") + return out.err +} + +func (m *Marshaler) writeSep(out *errWriter) { + if m.Indent != "" { + out.write(",\n") + } else { + out.write(",") + } +} + +func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error { + // "If the Any contains a value that has a special JSON mapping, + // it will be converted as follows: {"@type": xxx, "value": yyy}. + // Otherwise, the value will be converted into a JSON object, + // and the "@type" field will be inserted to indicate the actual data type." + v := reflect.ValueOf(any).Elem() + turl := v.Field(0).String() + val := v.Field(1).Bytes() + + var msg proto.Message + var err error + if m.AnyResolver != nil { + msg, err = m.AnyResolver.Resolve(turl) + } else { + msg, err = defaultResolveAny(turl) + } + if err != nil { + return err + } + + if err := proto.Unmarshal(val, msg); err != nil { + return err + } + + if _, ok := msg.(isWkt); ok { + out.write("{") + if m.Indent != "" { + out.write("\n") + } + if err := m.marshalTypeURL(out, indent, turl); err != nil { + return err + } + m.writeSep(out) + if m.Indent != "" { + out.write(indent) + out.write(m.Indent) + out.write(`"value": `) + } else { + out.write(`"value":`) + } + if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil { + return err + } + if m.Indent != "" { + out.write("\n") + out.write(indent) + } + out.write("}") + return out.err + } + + return m.marshalObject(out, msg, indent, turl) +} + +func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error { + if m.Indent != "" { + out.write(indent) + out.write(m.Indent) + } + out.write(`"@type":`) + if m.Indent != "" { + out.write(" ") + } + b, err := json.Marshal(typeURL) + if err != nil { + return err + } + out.write(string(b)) + return out.err +} + +// marshalField writes field description and value to the Writer. +func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { + if m.Indent != "" { + out.write(indent) + out.write(m.Indent) + } + out.write(`"`) + out.write(prop.JSONName) + out.write(`":`) + if m.Indent != "" { + out.write(" ") + } + if err := m.marshalValue(out, prop, v, indent); err != nil { + return err + } + return nil +} + +// marshalValue writes the value to the Writer. +func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { + + v = reflect.Indirect(v) + + // Handle nil pointer + if v.Kind() == reflect.Invalid { + out.write("null") + return out.err + } + + // Handle repeated elements. + if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 { + out.write("[") + comma := "" + for i := 0; i < v.Len(); i++ { + sliceVal := v.Index(i) + out.write(comma) + if m.Indent != "" { + out.write("\n") + out.write(indent) + out.write(m.Indent) + out.write(m.Indent) + } + if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil { + return err + } + comma = "," + } + if m.Indent != "" { + out.write("\n") + out.write(indent) + out.write(m.Indent) + } + out.write("]") + return out.err + } + + // Handle well-known types. + // Most are handled up in marshalObject (because 99% are messages). + if v.Type().Implements(wktType) { + wkt := v.Interface().(isWkt) + switch wkt.XXX_WellKnownType() { + case "NullValue": + out.write("null") + return out.err + } + } + + if t, ok := v.Interface().(time.Time); ok { + ts, err := types.TimestampProto(t) + if err != nil { + return err + } + return m.marshalValue(out, prop, reflect.ValueOf(ts), indent) + } + + if d, ok := v.Interface().(time.Duration); ok { + dur := types.DurationProto(d) + return m.marshalValue(out, prop, reflect.ValueOf(dur), indent) + } + + // Handle enumerations. + if !m.EnumsAsInts && prop.Enum != "" { + // Unknown enum values will are stringified by the proto library as their + // value. Such values should _not_ be quoted or they will be interpreted + // as an enum string instead of their value. + enumStr := v.Interface().(fmt.Stringer).String() + var valStr string + if v.Kind() == reflect.Ptr { + valStr = strconv.Itoa(int(v.Elem().Int())) + } else { + valStr = strconv.Itoa(int(v.Int())) + } + + if m, ok := v.Interface().(interface { + MarshalJSON() ([]byte, error) + }); ok { + data, err := m.MarshalJSON() + if err != nil { + return err + } + enumStr = string(data) + enumStr, err = strconv.Unquote(enumStr) + if err != nil { + return err + } + } + + isKnownEnum := enumStr != valStr + + if isKnownEnum { + out.write(`"`) + } + out.write(enumStr) + if isKnownEnum { + out.write(`"`) + } + return out.err + } + + // Handle nested messages. + if v.Kind() == reflect.Struct { + i := v + if v.CanAddr() { + i = v.Addr() + } else { + i = reflect.New(v.Type()) + i.Elem().Set(v) + } + iface := i.Interface() + if iface == nil { + out.write(`null`) + return out.err + } + + if m, ok := v.Interface().(interface { + MarshalJSON() ([]byte, error) + }); ok { + data, err := m.MarshalJSON() + if err != nil { + return err + } + out.write(string(data)) + return nil + } + + pm, ok := iface.(proto.Message) + if !ok { + if prop.CustomType == "" { + return fmt.Errorf("%v does not implement proto.Message", v.Type()) + } + t := proto.MessageType(prop.CustomType) + if t == nil || !i.Type().ConvertibleTo(t) { + return fmt.Errorf("%v declared custom type %s but it is not convertible to %v", v.Type(), prop.CustomType, t) + } + pm = i.Convert(t).Interface().(proto.Message) + } + return m.marshalObject(out, pm, indent+m.Indent, "") + } + + // Handle maps. + // Since Go randomizes map iteration, we sort keys for stable output. + if v.Kind() == reflect.Map { + out.write(`{`) + keys := v.MapKeys() + sort.Sort(mapKeys(keys)) + for i, k := range keys { + if i > 0 { + out.write(`,`) + } + if m.Indent != "" { + out.write("\n") + out.write(indent) + out.write(m.Indent) + out.write(m.Indent) + } + + // TODO handle map key prop properly + b, err := json.Marshal(k.Interface()) + if err != nil { + return err + } + s := string(b) + + // If the JSON is not a string value, encode it again to make it one. + if !strings.HasPrefix(s, `"`) { + b, err := json.Marshal(s) + if err != nil { + return err + } + s = string(b) + } + + out.write(s) + out.write(`:`) + if m.Indent != "" { + out.write(` `) + } + + vprop := prop + if prop != nil && prop.MapValProp != nil { + vprop = prop.MapValProp + } + if err := m.marshalValue(out, vprop, v.MapIndex(k), indent+m.Indent); err != nil { + return err + } + } + if m.Indent != "" { + out.write("\n") + out.write(indent) + out.write(m.Indent) + } + out.write(`}`) + return out.err + } + + // Handle non-finite floats, e.g. NaN, Infinity and -Infinity. + if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { + f := v.Float() + var sval string + switch { + case math.IsInf(f, 1): + sval = `"Infinity"` + case math.IsInf(f, -1): + sval = `"-Infinity"` + case math.IsNaN(f): + sval = `"NaN"` + } + if sval != "" { + out.write(sval) + return out.err + } + } + + // Default handling defers to the encoding/json library. + b, err := json.Marshal(v.Interface()) + if err != nil { + return err + } + needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) + if needToQuote { + out.write(`"`) + } + out.write(string(b)) + if needToQuote { + out.write(`"`) + } + return out.err +} + +// Unmarshaler is a configurable object for converting from a JSON +// representation to a protocol buffer object. +type Unmarshaler struct { + // Whether to allow messages to contain unknown fields, as opposed to + // failing to unmarshal. + AllowUnknownFields bool + + // A custom URL resolver to use when unmarshaling Any messages from JSON. + // If unset, the default resolution strategy is to extract the + // fully-qualified type name from the type URL and pass that to + // proto.MessageType(string). + AnyResolver AnyResolver +} + +// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. +// This function is lenient and will decode any options permutations of the +// related Marshaler. +func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error { + inputValue := json.RawMessage{} + if err := dec.Decode(&inputValue); err != nil { + return err + } + if err := u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil); err != nil { + return err + } + return checkRequiredFields(pb) +} + +// Unmarshal unmarshals a JSON object stream into a protocol +// buffer. This function is lenient and will decode any options +// permutations of the related Marshaler. +func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error { + dec := json.NewDecoder(r) + return u.UnmarshalNext(dec, pb) +} + +// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. +// This function is lenient and will decode any options permutations of the +// related Marshaler. +func UnmarshalNext(dec *json.Decoder, pb proto.Message) error { + return new(Unmarshaler).UnmarshalNext(dec, pb) +} + +// Unmarshal unmarshals a JSON object stream into a protocol +// buffer. This function is lenient and will decode any options +// permutations of the related Marshaler. +func Unmarshal(r io.Reader, pb proto.Message) error { + return new(Unmarshaler).Unmarshal(r, pb) +} + +// UnmarshalString will populate the fields of a protocol buffer based +// on a JSON string. This function is lenient and will decode any options +// permutations of the related Marshaler. +func UnmarshalString(str string, pb proto.Message) error { + return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb) +} + +// unmarshalValue converts/copies a value into the target. +// prop may be nil. +func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error { + targetType := target.Type() + + // Allocate memory for pointer fields. + if targetType.Kind() == reflect.Ptr { + // If input value is "null" and target is a pointer type, then the field should be treated as not set + // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue. + _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler) + if string(inputValue) == "null" && targetType != reflect.TypeOf(&types.Value{}) && !isJSONPBUnmarshaler { + return nil + } + target.Set(reflect.New(targetType.Elem())) + + return u.unmarshalValue(target.Elem(), inputValue, prop) + } + + if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok { + return jsu.UnmarshalJSONPB(u, []byte(inputValue)) + } + + // Handle well-known types that are not pointers. + if w, ok := target.Addr().Interface().(isWkt); ok { + switch w.XXX_WellKnownType() { + case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", + "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": + return u.unmarshalValue(target.Field(0), inputValue, prop) + case "Any": + // Use json.RawMessage pointer type instead of value to support pre-1.8 version. + // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see + // https://github.com/golang/go/issues/14493 + var jsonFields map[string]*json.RawMessage + if err := json.Unmarshal(inputValue, &jsonFields); err != nil { + return err + } + + val, ok := jsonFields["@type"] + if !ok || val == nil { + return errors.New("Any JSON doesn't have '@type'") + } + + var turl string + if err := json.Unmarshal([]byte(*val), &turl); err != nil { + return fmt.Errorf("can't unmarshal Any's '@type': %q", *val) + } + target.Field(0).SetString(turl) + + var m proto.Message + var err error + if u.AnyResolver != nil { + m, err = u.AnyResolver.Resolve(turl) + } else { + m, err = defaultResolveAny(turl) + } + if err != nil { + return err + } + + if _, ok := m.(isWkt); ok { + val, ok := jsonFields["value"] + if !ok { + return errors.New("Any JSON doesn't have 'value'") + } + + if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil { + return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) + } + } else { + delete(jsonFields, "@type") + nestedProto, uerr := json.Marshal(jsonFields) + if uerr != nil { + return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", uerr) + } + + if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil { + return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) + } + } + + b, err := proto.Marshal(m) + if err != nil { + return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err) + } + target.Field(1).SetBytes(b) + + return nil + case "Duration": + unq, err := unquote(string(inputValue)) + if err != nil { + return err + } + + d, err := time.ParseDuration(unq) + if err != nil { + return fmt.Errorf("bad Duration: %v", err) + } + + ns := d.Nanoseconds() + s := ns / 1e9 + ns %= 1e9 + target.Field(0).SetInt(s) + target.Field(1).SetInt(ns) + return nil + case "Timestamp": + unq, err := unquote(string(inputValue)) + if err != nil { + return err + } + + t, err := time.Parse(time.RFC3339Nano, unq) + if err != nil { + return fmt.Errorf("bad Timestamp: %v", err) + } + + target.Field(0).SetInt(t.Unix()) + target.Field(1).SetInt(int64(t.Nanosecond())) + return nil + case "Struct": + var m map[string]json.RawMessage + if err := json.Unmarshal(inputValue, &m); err != nil { + return fmt.Errorf("bad StructValue: %v", err) + } + target.Field(0).Set(reflect.ValueOf(map[string]*types.Value{})) + for k, jv := range m { + pv := &types.Value{} + if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil { + return fmt.Errorf("bad value in StructValue for key %q: %v", k, err) + } + target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv)) + } + return nil + case "ListValue": + var s []json.RawMessage + if err := json.Unmarshal(inputValue, &s); err != nil { + return fmt.Errorf("bad ListValue: %v", err) + } + + target.Field(0).Set(reflect.ValueOf(make([]*types.Value, len(s)))) + for i, sv := range s { + if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil { + return err + } + } + return nil + case "Value": + ivStr := string(inputValue) + if ivStr == "null" { + target.Field(0).Set(reflect.ValueOf(&types.Value_NullValue{})) + } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil { + target.Field(0).Set(reflect.ValueOf(&types.Value_NumberValue{NumberValue: v})) + } else if v, err := unquote(ivStr); err == nil { + target.Field(0).Set(reflect.ValueOf(&types.Value_StringValue{StringValue: v})) + } else if v, err := strconv.ParseBool(ivStr); err == nil { + target.Field(0).Set(reflect.ValueOf(&types.Value_BoolValue{BoolValue: v})) + } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil { + lv := &types.ListValue{} + target.Field(0).Set(reflect.ValueOf(&types.Value_ListValue{ListValue: lv})) + return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop) + } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil { + sv := &types.Struct{} + target.Field(0).Set(reflect.ValueOf(&types.Value_StructValue{StructValue: sv})) + return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop) + } else { + return fmt.Errorf("unrecognized type for Value %q", ivStr) + } + return nil + } + } + + if t, ok := target.Addr().Interface().(*time.Time); ok { + ts := &types.Timestamp{} + if err := u.unmarshalValue(reflect.ValueOf(ts).Elem(), inputValue, prop); err != nil { + return err + } + tt, err := types.TimestampFromProto(ts) + if err != nil { + return err + } + *t = tt + return nil + } + + if d, ok := target.Addr().Interface().(*time.Duration); ok { + dur := &types.Duration{} + if err := u.unmarshalValue(reflect.ValueOf(dur).Elem(), inputValue, prop); err != nil { + return err + } + dd, err := types.DurationFromProto(dur) + if err != nil { + return err + } + *d = dd + return nil + } + + // Handle enums, which have an underlying type of int32, + // and may appear as strings. + // The case of an enum appearing as a number is handled + // at the bottom of this function. + if inputValue[0] == '"' && prop != nil && prop.Enum != "" { + vmap := proto.EnumValueMap(prop.Enum) + // Don't need to do unquoting; valid enum names + // are from a limited character set. + s := inputValue[1 : len(inputValue)-1] + n, ok := vmap[string(s)] + if !ok { + return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum) + } + if target.Kind() == reflect.Ptr { // proto2 + target.Set(reflect.New(targetType.Elem())) + target = target.Elem() + } + if targetType.Kind() != reflect.Int32 { + return fmt.Errorf("invalid target %q for enum %s", targetType.Kind(), prop.Enum) + } + target.SetInt(int64(n)) + return nil + } + + if prop != nil && len(prop.CustomType) > 0 && target.CanAddr() { + if m, ok := target.Addr().Interface().(interface { + UnmarshalJSON([]byte) error + }); ok { + return json.Unmarshal(inputValue, m) + } + } + + // Handle nested messages. + if targetType.Kind() == reflect.Struct { + var jsonFields map[string]json.RawMessage + if err := json.Unmarshal(inputValue, &jsonFields); err != nil { + return err + } + + consumeField := func(prop *proto.Properties) (json.RawMessage, bool) { + // Be liberal in what names we accept; both orig_name and camelName are okay. + fieldNames := acceptedJSONFieldNames(prop) + + vOrig, okOrig := jsonFields[fieldNames.orig] + vCamel, okCamel := jsonFields[fieldNames.camel] + if !okOrig && !okCamel { + return nil, false + } + // If, for some reason, both are present in the data, favour the camelName. + var raw json.RawMessage + if okOrig { + raw = vOrig + delete(jsonFields, fieldNames.orig) + } + if okCamel { + raw = vCamel + delete(jsonFields, fieldNames.camel) + } + return raw, true + } + + sprops := proto.GetProperties(targetType) + for i := 0; i < target.NumField(); i++ { + ft := target.Type().Field(i) + if strings.HasPrefix(ft.Name, "XXX_") { + continue + } + valueForField, ok := consumeField(sprops.Prop[i]) + if !ok { + continue + } + + if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil { + return err + } + } + // Check for any oneof fields. + if len(jsonFields) > 0 { + for _, oop := range sprops.OneofTypes { + raw, ok := consumeField(oop.Prop) + if !ok { + continue + } + nv := reflect.New(oop.Type.Elem()) + target.Field(oop.Field).Set(nv) + if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil { + return err + } + } + } + // Handle proto2 extensions. + if len(jsonFields) > 0 { + if ep, ok := target.Addr().Interface().(proto.Message); ok { + for _, ext := range proto.RegisteredExtensions(ep) { + name := fmt.Sprintf("[%s]", ext.Name) + raw, ok := jsonFields[name] + if !ok { + continue + } + delete(jsonFields, name) + nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem()) + if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil { + return err + } + if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil { + return err + } + } + } + } + if !u.AllowUnknownFields && len(jsonFields) > 0 { + // Pick any field to be the scapegoat. + var f string + for fname := range jsonFields { + f = fname + break + } + return fmt.Errorf("unknown field %q in %v", f, targetType) + } + return nil + } + + // Handle arrays + if targetType.Kind() == reflect.Slice { + if targetType.Elem().Kind() == reflect.Uint8 { + outRef := reflect.New(targetType) + outVal := outRef.Interface() + //CustomType with underlying type []byte + if _, ok := outVal.(interface { + UnmarshalJSON([]byte) error + }); ok { + if err := json.Unmarshal(inputValue, outVal); err != nil { + return err + } + target.Set(outRef.Elem()) + return nil + } + // Special case for encoded bytes. Pre-go1.5 doesn't support unmarshalling + // strings into aliased []byte types. + // https://github.com/golang/go/commit/4302fd0409da5e4f1d71471a6770dacdc3301197 + // https://github.com/golang/go/commit/c60707b14d6be26bf4213114d13070bff00d0b0a + var out []byte + if err := json.Unmarshal(inputValue, &out); err != nil { + return err + } + target.SetBytes(out) + return nil + } + + var slc []json.RawMessage + if err := json.Unmarshal(inputValue, &slc); err != nil { + return err + } + if slc != nil { + l := len(slc) + target.Set(reflect.MakeSlice(targetType, l, l)) + for i := 0; i < l; i++ { + if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil { + return err + } + } + } + return nil + } + + // Handle maps (whose keys are always strings) + if targetType.Kind() == reflect.Map { + var mp map[string]json.RawMessage + if err := json.Unmarshal(inputValue, &mp); err != nil { + return err + } + if mp != nil { + target.Set(reflect.MakeMap(targetType)) + for ks, raw := range mp { + // Unmarshal map key. The core json library already decoded the key into a + // string, so we handle that specially. Other types were quoted post-serialization. + var k reflect.Value + if targetType.Key().Kind() == reflect.String { + k = reflect.ValueOf(ks) + } else { + k = reflect.New(targetType.Key()).Elem() + var kprop *proto.Properties + if prop != nil && prop.MapKeyProp != nil { + kprop = prop.MapKeyProp + } + if err := u.unmarshalValue(k, json.RawMessage(ks), kprop); err != nil { + return err + } + } + + if !k.Type().AssignableTo(targetType.Key()) { + k = k.Convert(targetType.Key()) + } + + // Unmarshal map value. + v := reflect.New(targetType.Elem()).Elem() + var vprop *proto.Properties + if prop != nil && prop.MapValProp != nil { + vprop = prop.MapValProp + } + if err := u.unmarshalValue(v, raw, vprop); err != nil { + return err + } + target.SetMapIndex(k, v) + } + } + return nil + } + + // Non-finite numbers can be encoded as strings. + isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64 + if isFloat { + if num, ok := nonFinite[string(inputValue)]; ok { + target.SetFloat(num) + return nil + } + } + + // integers & floats can be encoded as strings. In this case we drop + // the quotes and proceed as normal. + isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 || + targetType.Kind() == reflect.Int32 || targetType.Kind() == reflect.Uint32 || + targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64 + if isNum && strings.HasPrefix(string(inputValue), `"`) { + inputValue = inputValue[1 : len(inputValue)-1] + } + + // Use the encoding/json for parsing other value types. + return json.Unmarshal(inputValue, target.Addr().Interface()) +} + +func unquote(s string) (string, error) { + var ret string + err := json.Unmarshal([]byte(s), &ret) + return ret, err +} + +// jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute. +func jsonProperties(f reflect.StructField, origName bool) *proto.Properties { + var prop proto.Properties + prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f) + if origName || prop.JSONName == "" { + prop.JSONName = prop.OrigName + } + return &prop +} + +type fieldNames struct { + orig, camel string +} + +func acceptedJSONFieldNames(prop *proto.Properties) fieldNames { + opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName} + if prop.JSONName != "" { + opts.camel = prop.JSONName + } + return opts +} + +// Writer wrapper inspired by https://blog.golang.org/errors-are-values +type errWriter struct { + writer io.Writer + err error +} + +func (w *errWriter) write(str string) { + if w.err != nil { + return + } + _, w.err = w.writer.Write([]byte(str)) +} + +// Map fields may have key types of non-float scalars, strings and enums. +// The easiest way to sort them in some deterministic order is to use fmt. +// If this turns out to be inefficient we can always consider other options, +// such as doing a Schwartzian transform. +// +// Numeric keys are sorted in numeric order per +// https://developers.google.com/protocol-buffers/docs/proto#maps. +type mapKeys []reflect.Value + +func (s mapKeys) Len() int { return len(s) } +func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s mapKeys) Less(i, j int) bool { + if k := s[i].Kind(); k == s[j].Kind() { + switch k { + case reflect.String: + return s[i].String() < s[j].String() + case reflect.Int32, reflect.Int64: + return s[i].Int() < s[j].Int() + case reflect.Uint32, reflect.Uint64: + return s[i].Uint() < s[j].Uint() + } + } + return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) +} + +// checkRequiredFields returns an error if any required field in the given proto message is not set. +// This function is used by both Marshal and Unmarshal. While required fields only exist in a +// proto2 message, a proto3 message can contain proto2 message(s). +func checkRequiredFields(pb proto.Message) error { + // Most well-known type messages do not contain required fields. The "Any" type may contain + // a message that has required fields. + // + // When an Any message is being marshaled, the code will invoked proto.Unmarshal on Any.Value + // field in order to transform that into JSON, and that should have returned an error if a + // required field is not set in the embedded message. + // + // When an Any message is being unmarshaled, the code will have invoked proto.Marshal on the + // embedded message to store the serialized message in Any.Value field, and that should have + // returned an error if a required field is not set. + if _, ok := pb.(isWkt); ok { + return nil + } + + v := reflect.ValueOf(pb) + // Skip message if it is not a struct pointer. + if v.Kind() != reflect.Ptr { + return nil + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return nil + } + + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + sfield := v.Type().Field(i) + + if sfield.PkgPath != "" { + // blank PkgPath means the field is exported; skip if not exported + continue + } + + if strings.HasPrefix(sfield.Name, "XXX_") { + continue + } + + // Oneof field is an interface implemented by wrapper structs containing the actual oneof + // field, i.e. an interface containing &T{real_value}. + if sfield.Tag.Get("protobuf_oneof") != "" { + if field.Kind() != reflect.Interface { + continue + } + v := field.Elem() + if v.Kind() != reflect.Ptr || v.IsNil() { + continue + } + v = v.Elem() + if v.Kind() != reflect.Struct || v.NumField() < 1 { + continue + } + field = v.Field(0) + sfield = v.Type().Field(0) + } + + protoTag := sfield.Tag.Get("protobuf") + if protoTag == "" { + continue + } + var prop proto.Properties + prop.Init(sfield.Type, sfield.Name, protoTag, &sfield) + + switch field.Kind() { + case reflect.Map: + if field.IsNil() { + continue + } + // Check each map value. + keys := field.MapKeys() + for _, k := range keys { + v := field.MapIndex(k) + if err := checkRequiredFieldsInValue(v); err != nil { + return err + } + } + case reflect.Slice: + // Handle non-repeated type, e.g. bytes. + if !prop.Repeated { + if prop.Required && field.IsNil() { + return fmt.Errorf("required field %q is not set", prop.Name) + } + continue + } + + // Handle repeated type. + if field.IsNil() { + continue + } + // Check each slice item. + for i := 0; i < field.Len(); i++ { + v := field.Index(i) + if err := checkRequiredFieldsInValue(v); err != nil { + return err + } + } + case reflect.Ptr: + if field.IsNil() { + if prop.Required { + return fmt.Errorf("required field %q is not set", prop.Name) + } + continue + } + if err := checkRequiredFieldsInValue(field); err != nil { + return err + } + } + } + + // Handle proto2 extensions. + for _, ext := range proto.RegisteredExtensions(pb) { + if !proto.HasExtension(pb, ext) { + continue + } + ep, err := proto.GetExtension(pb, ext) + if err != nil { + return err + } + err = checkRequiredFieldsInValue(reflect.ValueOf(ep)) + if err != nil { + return err + } + } + + return nil +} + +func checkRequiredFieldsInValue(v reflect.Value) error { + if v.Type().Implements(messageType) { + return checkRequiredFields(v.Interface().(proto.Message)) + } + return nil +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md deleted file mode 100644 index 32966f598..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md +++ /dev/null @@ -1,22 +0,0 @@ -## Migration Guide (v4.0.0) - -Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), the import path will be: - - "github.com/golang-jwt/jwt/v4" - -The `/v4` version will be backwards compatible with existing `v3.x.y` tags in this repo, as well as -`github.com/dgrijalva/jwt-go`. For most users this should be a drop-in replacement, if you're having -troubles migrating, please open an issue. - -You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually or by using tools such as `sed` or `gofmt`. - -And then you'd typically run: - -``` -go get github.com/golang-jwt/jwt/v4 -go mod tidy -``` - -## Older releases (before v3.2.0) - -The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/vendor/github.com/golang-jwt/jwt/v4/README.md b/vendor/github.com/golang-jwt/jwt/v4/README.md deleted file mode 100644 index 30f2f2a6f..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# jwt-go - -[![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v4.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) - -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](https://datatracker.ietf.org/doc/html/rfc7519). - -Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) this project adds Go module support, but maintains backwards compatibility with older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. -See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. - -> After the original author of the library suggested migrating the maintenance of `jwt-go`, a dedicated team of open source maintainers decided to clone the existing library into this repository. See [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a detailed discussion on this topic. - - -**SECURITY NOTICE:** Some older versions of Go have a security issue in the crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue [dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more detail. - -**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. - -### Supported Go versions - -Our support of Go versions is aligned with Go's [version release policy](https://golang.org/doc/devel/release#policy). -So we will support a major version of Go until there are two newer major releases. -We no longer support building jwt-go with unsupported Go versions, as these contain security vulnerabilities -which will not be fixed. - -## What the heck is a JWT? - -JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. - -In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) encoded. The last part is the signature, encoded the same way. - -The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. - -The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about reserved keys and the proper way to add your own. - -## What's in the box? - -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. - -## Installation Guidelines - -1. To install the jwt package, you first need to have [Go](https://go.dev/doc/install) installed, then you can use the command below to add `jwt-go` as a dependency in your Go program. - -```sh -go get -u github.com/golang-jwt/jwt/v4 -``` - -2. Import it in your code: - -```go -import "github.com/golang-jwt/jwt/v4" -``` - -## Examples - -See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) for examples of usage: - -* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#example-Parse-Hmac) -* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#example-New-Hmac) -* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#pkg-examples) - -## Extensions - -This library publishes all the necessary components for adding your own signing methods or key functions. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod` or provide a `jwt.Keyfunc`. - -A common use case would be integrating with different 3rd party signature providers, like key management services from various cloud providers or Hardware Security Modules (HSMs) or to implement additional standards. - -| Extension | Purpose | Repo | -| --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -| GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | -| AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | -| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | - -*Disclaimer*: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers - -## Compliance - -This library was last reviewed to comply with [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few notable differences: - -* In order to protect against accidental use of [Unsecured JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. - -## Project Status & Versioning - -This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). - -This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `main`. Periodically, versions will be tagged from `main`. You can find all the releases on [the project releases page](https://github.com/golang-jwt/jwt/releases). - -**BREAKING CHANGES:*** -A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. - -## Usage Tips - -### Signing vs Encryption - -A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: - -* The author of the token was in the possession of the signing secret -* The data has not been modified since it was signed - -It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. The companion project https://github.com/golang-jwt/jwe aims at a (very) experimental implementation of the JWE standard. - -### Choosing a Signing Method - -There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. - -Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. - -Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. - -### Signing Methods and Key Types - -Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: - -* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation -* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation - -### JWT and OAuth - -It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. - -Without going too far down the rabbit hole, here's a description of the interaction of these technologies: - -* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. -* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. -* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. - -### Troubleshooting - -This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types. - -## More - -Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v4). - -The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. - -[golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version of the JWT logo, which is distributed under the terms of the [MIT License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt). diff --git a/vendor/github.com/golang-jwt/jwt/v4/claims.go b/vendor/github.com/golang-jwt/jwt/v4/claims.go deleted file mode 100644 index 364cec877..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/claims.go +++ /dev/null @@ -1,269 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// Claims must just have a Valid method that determines -// if the token is invalid for any supported reason -type Claims interface { - Valid() error -} - -// RegisteredClaims are a structured version of the JWT Claims Set, -// restricted to Registered Claim Names, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 -// -// This type can be used on its own, but then additional private and -// public claims embedded in the JWT will not be parsed. The typical usecase -// therefore is to embedded this in a user-defined claim type. -// -// See examples for how to use this with your own claim types. -type RegisteredClaims struct { - // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 - Issuer string `json:"iss,omitempty"` - - // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 - Subject string `json:"sub,omitempty"` - - // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 - Audience ClaimStrings `json:"aud,omitempty"` - - // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 - ExpiresAt *NumericDate `json:"exp,omitempty"` - - // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 - NotBefore *NumericDate `json:"nbf,omitempty"` - - // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 - IssuedAt *NumericDate `json:"iat,omitempty"` - - // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 - ID string `json:"jti,omitempty"` -} - -// Valid validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c RegisteredClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if !c.VerifyExpiresAt(now, false) { - delta := now.Sub(c.ExpiresAt.Time) - vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) - vErr.Errors |= ValidationErrorExpired - } - - if !c.VerifyIssuedAt(now, false) { - vErr.Inner = ErrTokenUsedBeforeIssued - vErr.Errors |= ValidationErrorIssuedAt - } - - if !c.VerifyNotBefore(now, false) { - vErr.Inner = ErrTokenNotValidYet - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// VerifyAudience compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud(c.Audience, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). -// If req is false, it will return true, if exp is unset. -func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool { - if c.ExpiresAt == nil { - return verifyExp(nil, cmp, req) - } - - return verifyExp(&c.ExpiresAt.Time, cmp, req) -} - -// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool { - if c.IssuedAt == nil { - return verifyIat(nil, cmp, req) - } - - return verifyIat(&c.IssuedAt.Time, cmp, req) -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool { - if c.NotBefore == nil { - return verifyNbf(nil, cmp, req) - } - - return verifyNbf(&c.NotBefore.Time, cmp, req) -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// StandardClaims are a structured version of the JWT Claims Set, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the -// specification exactly, since they were based on an earlier draft of the -// specification and not updated. The main difference is that they only -// support integer-based date fields and singular audiences. This might lead to -// incompatibilities with other JWT implementations. The use of this is discouraged, instead -// the newer RegisteredClaims struct should be used. -// -// Deprecated: Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct. -type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if !c.VerifyExpiresAt(now, false) { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) - vErr.Errors |= ValidationErrorExpired - } - - if !c.VerifyIssuedAt(now, false) { - vErr.Inner = ErrTokenUsedBeforeIssued - vErr.Errors |= ValidationErrorIssuedAt - } - - if !c.VerifyNotBefore(now, false) { - vErr.Inner = ErrTokenNotValidYet - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// VerifyAudience compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud([]string{c.Audience}, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). -// If req is false, it will return true, if exp is unset. -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - if c.ExpiresAt == 0 { - return verifyExp(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.ExpiresAt, 0) - return verifyExp(&t, time.Unix(cmp, 0), req) -} - -// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - if c.IssuedAt == 0 { - return verifyIat(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.IssuedAt, 0) - return verifyIat(&t, time.Unix(cmp, 0), req) -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - if c.NotBefore == 0 { - return verifyNbf(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.NotBefore, 0) - return verifyNbf(&t, time.Unix(cmp, 0), req) -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// ----- helpers - -func verifyAud(aud []string, cmp string, required bool) bool { - if len(aud) == 0 { - return !required - } - // use a var here to keep constant time compare when looping over a number of claims - result := false - - var stringClaims string - for _, a := range aud { - if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { - result = true - } - stringClaims = stringClaims + a - } - - // case where "" is sent in one or many aud claims - if len(stringClaims) == 0 { - return !required - } - - return result -} - -func verifyExp(exp *time.Time, now time.Time, required bool) bool { - if exp == nil { - return !required - } - return now.Before(*exp) -} - -func verifyIat(iat *time.Time, now time.Time, required bool) bool { - if iat == nil { - return !required - } - return now.After(*iat) || now.Equal(*iat) -} - -func verifyNbf(nbf *time.Time, now time.Time, required bool) bool { - if nbf == nil { - return !required - } - return now.After(*nbf) || now.Equal(*nbf) -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - return subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/ed25519.go b/vendor/github.com/golang-jwt/jwt/v4/ed25519.go deleted file mode 100644 index 07d3aacd6..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/ed25519.go +++ /dev/null @@ -1,85 +0,0 @@ -package jwt - -import ( - "errors" - - "crypto" - "crypto/ed25519" - "crypto/rand" -) - -var ( - ErrEd25519Verification = errors.New("ed25519: verification error") -) - -// SigningMethodEd25519 implements the EdDSA family. -// Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification -type SigningMethodEd25519 struct{} - -// Specific instance for EdDSA -var ( - SigningMethodEdDSA *SigningMethodEd25519 -) - -func init() { - SigningMethodEdDSA = &SigningMethodEd25519{} - RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod { - return SigningMethodEdDSA - }) -} - -func (m *SigningMethodEd25519) Alg() string { - return "EdDSA" -} - -// Verify implements token verification for the SigningMethod. -// For this verify method, key must be an ed25519.PublicKey -func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error { - var err error - var ed25519Key ed25519.PublicKey - var ok bool - - if ed25519Key, ok = key.(ed25519.PublicKey); !ok { - return ErrInvalidKeyType - } - - if len(ed25519Key) != ed25519.PublicKeySize { - return ErrInvalidKey - } - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - // Verify the signature - if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { - return ErrEd25519Verification - } - - return nil -} - -// Sign implements token signing for the SigningMethod. -// For this signing method, key must be an ed25519.PrivateKey -func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) { - var ed25519Key crypto.Signer - var ok bool - - if ed25519Key, ok = key.(crypto.Signer); !ok { - return "", ErrInvalidKeyType - } - - if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { - return "", ErrInvalidKey - } - - // Sign the string and return the encoded result - // ed25519 performs a two-pass hash as part of its algorithm. Therefore, we need to pass a non-prehashed message into the Sign function, as indicated by crypto.Hash(0) - sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) - if err != nil { - return "", err - } - return EncodeSegment(sig), nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/errors.go b/vendor/github.com/golang-jwt/jwt/v4/errors.go deleted file mode 100644 index 10ac8835c..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/errors.go +++ /dev/null @@ -1,112 +0,0 @@ -package jwt - -import ( - "errors" -) - -// Error constants -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - - ErrTokenMalformed = errors.New("token is malformed") - ErrTokenUnverifiable = errors.New("token is unverifiable") - ErrTokenSignatureInvalid = errors.New("token signature is invalid") - - ErrTokenInvalidAudience = errors.New("token has invalid audience") - ErrTokenExpired = errors.New("token is expired") - ErrTokenUsedBeforeIssued = errors.New("token used before issued") - ErrTokenInvalidIssuer = errors.New("token has invalid issuer") - ErrTokenNotValidYet = errors.New("token is not valid yet") - ErrTokenInvalidId = errors.New("token has invalid id") - ErrTokenInvalidClaims = errors.New("token has invalid claims") -) - -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// NewValidationError is a helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// ValidationError represents an error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text -} - -// Error is the implementation of the err interface. -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" - } -} - -// Unwrap gives errors.Is and errors.As access to the inner error. -func (e *ValidationError) Unwrap() error { - return e.Inner -} - -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 -} - -// Is checks if this ValidationError is of the supplied error. We are first checking for the exact error message -// by comparing the inner error message. If that fails, we compare using the error flags. This way we can use -// custom error messages (mainly for backwards compatability) and still leverage errors.Is using the global error variables. -func (e *ValidationError) Is(err error) bool { - // Check, if our inner error is a direct match - if errors.Is(errors.Unwrap(e), err) { - return true - } - - // Otherwise, we need to match using our error flags - switch err { - case ErrTokenMalformed: - return e.Errors&ValidationErrorMalformed != 0 - case ErrTokenUnverifiable: - return e.Errors&ValidationErrorUnverifiable != 0 - case ErrTokenSignatureInvalid: - return e.Errors&ValidationErrorSignatureInvalid != 0 - case ErrTokenInvalidAudience: - return e.Errors&ValidationErrorAudience != 0 - case ErrTokenExpired: - return e.Errors&ValidationErrorExpired != 0 - case ErrTokenUsedBeforeIssued: - return e.Errors&ValidationErrorIssuedAt != 0 - case ErrTokenInvalidIssuer: - return e.Errors&ValidationErrorIssuer != 0 - case ErrTokenNotValidYet: - return e.Errors&ValidationErrorNotValidYet != 0 - case ErrTokenInvalidId: - return e.Errors&ValidationErrorId != 0 - case ErrTokenInvalidClaims: - return e.Errors&ValidationErrorClaimsInvalid != 0 - } - - return false -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/hmac.go b/vendor/github.com/golang-jwt/jwt/v4/hmac.go deleted file mode 100644 index 011f68a27..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/hmac.go +++ /dev/null @@ -1,95 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/hmac" - "errors" -) - -// SigningMethodHMAC implements the HMAC-SHA family of signing methods. -// Expects key type of []byte for both signing and validation -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash -} - -// Specific instances for HS256 and company -var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC - ErrSignatureInvalid = errors.New("signature is invalid") -) - -func init() { - // HS256 - SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { - return SigningMethodHS256 - }) - - // HS384 - SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { - return SigningMethodHS384 - }) - - // HS512 - SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { - return SigningMethodHS512 - }) -} - -func (m *SigningMethodHMAC) Alg() string { - return m.Name -} - -// Verify implements token verification for the SigningMethod. Returns nil if the signature is valid. -func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { - // Verify the key is the right type - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKeyType - } - - // Decode signature, for comparison - sig, err := DecodeSegment(signature) - if err != nil { - return err - } - - // Can we use the specified hashing method? - if !m.Hash.Available() { - return ErrHashUnavailable - } - - // This signing method is symmetric, so we validate the signature - // by reproducing the signature from the signing string and key, then - // comparing that against the provided signature. - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - if !hmac.Equal(sig, hasher.Sum(nil)) { - return ErrSignatureInvalid - } - - // No validation errors. Signature is good. - return nil -} - -// Sign implements token signing for the SigningMethod. -// Key must be []byte -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { - if keyBytes, ok := key.([]byte); ok { - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - - return EncodeSegment(hasher.Sum(nil)), nil - } - - return "", ErrInvalidKeyType -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/map_claims.go b/vendor/github.com/golang-jwt/jwt/v4/map_claims.go deleted file mode 100644 index 2700d64a0..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/map_claims.go +++ /dev/null @@ -1,151 +0,0 @@ -package jwt - -import ( - "encoding/json" - "errors" - "time" - // "fmt" -) - -// MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. -// This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// VerifyAudience Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - var aud []string - switch v := m["aud"].(type) { - case string: - aud = append(aud, v) - case []string: - aud = v - case []interface{}: - for _, a := range v { - vs, ok := a.(string) - if !ok { - return false - } - aud = append(aud, vs) - } - } - return verifyAud(aud, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). -// If req is false, it will return true, if exp is unset. -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["exp"] - if !ok { - return !req - } - - switch exp := v.(type) { - case float64: - if exp == 0 { - return verifyExp(nil, cmpTime, req) - } - - return verifyExp(&newNumericDateFromSeconds(exp).Time, cmpTime, req) - case json.Number: - v, _ := exp.Float64() - - return verifyExp(&newNumericDateFromSeconds(v).Time, cmpTime, req) - } - - return false -} - -// VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["iat"] - if !ok { - return !req - } - - switch iat := v.(type) { - case float64: - if iat == 0 { - return verifyIat(nil, cmpTime, req) - } - - return verifyIat(&newNumericDateFromSeconds(iat).Time, cmpTime, req) - case json.Number: - v, _ := iat.Float64() - - return verifyIat(&newNumericDateFromSeconds(v).Time, cmpTime, req) - } - - return false -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["nbf"] - if !ok { - return !req - } - - switch nbf := v.(type) { - case float64: - if nbf == 0 { - return verifyNbf(nil, cmpTime, req) - } - - return verifyNbf(&newNumericDateFromSeconds(nbf).Time, cmpTime, req) - case json.Number: - v, _ := nbf.Float64() - - return verifyNbf(&newNumericDateFromSeconds(v).Time, cmpTime, req) - } - - return false -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) -} - -// Valid validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if !m.VerifyExpiresAt(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenExpired - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if !m.VerifyIssuedAt(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenUsedBeforeIssued - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if !m.VerifyNotBefore(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenNotValidYet - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/none.go b/vendor/github.com/golang-jwt/jwt/v4/none.go deleted file mode 100644 index f19835d20..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/none.go +++ /dev/null @@ -1,52 +0,0 @@ -package jwt - -// SigningMethodNone implements the none signing method. This is required by the spec -// but you probably should never use it. -var SigningMethodNone *signingMethodNone - -const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" - -var NoneSignatureTypeDisallowedError error - -type signingMethodNone struct{} -type unsafeNoneMagicConstant string - -func init() { - SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) - - RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { - return SigningMethodNone - }) -} - -func (m *signingMethodNone) Alg() string { - return "none" -} - -// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { - // Key must be UnsafeAllowNoneSignatureType to prevent accidentally - // accepting 'none' signing method - if _, ok := key.(unsafeNoneMagicConstant); !ok { - return NoneSignatureTypeDisallowedError - } - // If signing method is none, signature must be an empty string - if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) - } - - // Accept 'none' signing method. - return nil -} - -// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { - if _, ok := key.(unsafeNoneMagicConstant); ok { - return "", nil - } - return "", NoneSignatureTypeDisallowedError -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/parser.go b/vendor/github.com/golang-jwt/jwt/v4/parser.go deleted file mode 100644 index c0a6f6927..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/parser.go +++ /dev/null @@ -1,177 +0,0 @@ -package jwt - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type Parser struct { - // If populated, only these methods will be considered valid. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - ValidMethods []string - - // Use JSON Number format in JSON decoder. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - UseJSONNumber bool - - // Skip claims validation during token parsing. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - SkipClaimsValidation bool -} - -// NewParser creates a new Parser with the specified options -func NewParser(options ...ParserOption) *Parser { - p := &Parser{} - - // loop through our parsing options and apply them - for _, option := range options { - option(p) - } - - return p -} - -// Parse parses, validates, verifies the signature and returns the parsed token. -// keyFunc will receive the parsed token and should return the key for validating. -func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) -} - -// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims -// interface. This provides default values which can be overridden and allows a caller to use their own type, rather -// than the default MapClaims implementation of Claims. -// -// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), -// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the -// proper memory for it before passing in the overall claims, otherwise you might run into a panic. -func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - token, parts, err := p.ParseUnverified(tokenString, claims) - if err != nil { - return token, err - } - - // Verify signing method is in the required set - if p.ValidMethods != nil { - var signingMethodValid = false - var alg = token.Method.Alg() - for _, m := range p.ValidMethods { - if m == alg { - signingMethodValid = true - break - } - } - if !signingMethodValid { - // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) - } - } - - // Lookup key - var key interface{} - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) - } - if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} - } - - vErr := &ValidationError{} - - // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } - } - } - - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid - } - - if vErr.valid() { - token.Valid = true - return token, nil - } - - return token, vErr -} - -// ParseUnverified parses the token but doesn't validate the signature. -// -// WARNING: Don't use this method unless you know what you're doing. -// -// It's only ever useful in cases where you know the signature is valid (because it has -// been checked previously in the stack) and you want to extract values from it. -func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { - parts = strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) - } - - token = &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) - } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - token.Claims = claims - - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - // Handle decode error - if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) - } - } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) - } - - return token, parts, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/parser_option.go b/vendor/github.com/golang-jwt/jwt/v4/parser_option.go deleted file mode 100644 index 6ea6f9527..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/parser_option.go +++ /dev/null @@ -1,29 +0,0 @@ -package jwt - -// ParserOption is used to implement functional-style options that modify the behavior of the parser. To add -// new options, just create a function (ideally beginning with With or Without) that returns an anonymous function that -// takes a *Parser type as input and manipulates its configuration accordingly. -type ParserOption func(*Parser) - -// WithValidMethods is an option to supply algorithm methods that the parser will check. Only those methods will be considered valid. -// It is heavily encouraged to use this option in order to prevent attacks such as https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. -func WithValidMethods(methods []string) ParserOption { - return func(p *Parser) { - p.ValidMethods = methods - } -} - -// WithJSONNumber is an option to configure the underlying JSON parser with UseNumber -func WithJSONNumber() ParserOption { - return func(p *Parser) { - p.UseJSONNumber = true - } -} - -// WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know -// what you are doing. -func WithoutClaimsValidation() ParserOption { - return func(p *Parser) { - p.SkipClaimsValidation = true - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/signing_method.go b/vendor/github.com/golang-jwt/jwt/v4/signing_method.go deleted file mode 100644 index 241ae9c60..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/signing_method.go +++ /dev/null @@ -1,46 +0,0 @@ -package jwt - -import ( - "sync" -) - -var signingMethods = map[string]func() SigningMethod{} -var signingMethodLock = new(sync.RWMutex) - -// SigningMethod can be used add new methods for signing or verifying tokens. -type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') -} - -// RegisterSigningMethod registers the "alg" name and a factory function for signing method. -// This is typically done during init() in the method's implementation -func RegisterSigningMethod(alg string, f func() SigningMethod) { - signingMethodLock.Lock() - defer signingMethodLock.Unlock() - - signingMethods[alg] = f -} - -// GetSigningMethod retrieves a signing method from an "alg" string -func GetSigningMethod(alg string) (method SigningMethod) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - if methodF, ok := signingMethods[alg]; ok { - method = methodF() - } - return -} - -// GetAlgorithms returns a list of registered "alg" names -func GetAlgorithms() (algs []string) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - for alg := range signingMethods { - algs = append(algs, alg) - } - return -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/token.go b/vendor/github.com/golang-jwt/jwt/v4/token.go deleted file mode 100644 index 786b275ce..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/token.go +++ /dev/null @@ -1,143 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" - "time" -) - -// DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515 -// states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations -// of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global -// variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. -// To use the non-recommended decoding, set this boolean to `true` prior to using this package. -var DecodePaddingAllowed bool - -// DecodeStrict will switch the codec used for decoding JWTs into strict mode. -// In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5. -// Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. -// To use strict decoding, set this boolean to `true` prior to using this package. -var DecodeStrict bool - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Keyfunc will be used by the Parse methods as a callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// Token represents a JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// New creates a new Token with the specified signing method and an empty map of claims. -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -// NewWithClaims creates a new Token with the specified signing method and claims. -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// SignedString creates and returns a complete, signed JWT. -// The token is signed using the SigningMethod specified in the token. -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// SigningString generates the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - var jsonValue []byte - - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - header := EncodeSegment(jsonValue) - - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - claim := EncodeSegment(jsonValue) - - return strings.Join([]string{header, claim}, "."), nil -} - -// Parse parses, validates, verifies the signature and returns the parsed token. -// keyFunc will receive the parsed token and should return the cryptographic key -// for verifying the signature. -// The caller is strongly encouraged to set the WithValidMethods option to -// validate the 'alg' claim in the token matches the expected algorithm. -// For more details about the importance of validating the 'alg' claim, -// see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ -func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).Parse(tokenString, keyFunc) -} - -// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). -// -// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), -// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the -// proper memory for it before passing in the overall claims, otherwise you might run into a panic. -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) -} - -// EncodeSegment encodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a non-exported function, since it -// should only be used internally -func EncodeSegment(seg []byte) string { - return base64.RawURLEncoding.EncodeToString(seg) -} - -// DecodeSegment decodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a non-exported function, since it -// should only be used internally -func DecodeSegment(seg string) ([]byte, error) { - encoding := base64.RawURLEncoding - - if DecodePaddingAllowed { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - encoding = base64.URLEncoding - } - - if DecodeStrict { - encoding = encoding.Strict() - } - return encoding.DecodeString(seg) -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/types.go b/vendor/github.com/golang-jwt/jwt/v4/types.go deleted file mode 100644 index ac8e140eb..000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/types.go +++ /dev/null @@ -1,145 +0,0 @@ -package jwt - -import ( - "encoding/json" - "fmt" - "math" - "reflect" - "strconv" - "time" -) - -// TimePrecision sets the precision of times and dates within this library. -// This has an influence on the precision of times when comparing expiry or -// other related time fields. Furthermore, it is also the precision of times -// when serializing. -// -// For backwards compatibility the default precision is set to seconds, so that -// no fractional timestamps are generated. -var TimePrecision = time.Second - -// MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially -// its MarshalJSON function. -// -// If it is set to true (the default), it will always serialize the type as an -// array of strings, even if it just contains one element, defaulting to the behaviour -// of the underlying []string. If it is set to false, it will serialize to a single -// string, if it contains one element. Otherwise, it will serialize to an array of strings. -var MarshalSingleStringAsArray = true - -// NumericDate represents a JSON numeric date value, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-2. -type NumericDate struct { - time.Time -} - -// NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. -// It will truncate the timestamp according to the precision specified in TimePrecision. -func NewNumericDate(t time.Time) *NumericDate { - return &NumericDate{t.Truncate(TimePrecision)} -} - -// newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a -// UNIX epoch with the float fraction representing non-integer seconds. -func newNumericDateFromSeconds(f float64) *NumericDate { - round, frac := math.Modf(f) - return NewNumericDate(time.Unix(int64(round), int64(frac*1e9))) -} - -// MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch -// represented in NumericDate to a byte array, using the precision specified in TimePrecision. -func (date NumericDate) MarshalJSON() (b []byte, err error) { - var prec int - if TimePrecision < time.Second { - prec = int(math.Log10(float64(time.Second) / float64(TimePrecision))) - } - truncatedDate := date.Truncate(TimePrecision) - - // For very large timestamps, UnixNano would overflow an int64, but this - // function requires nanosecond level precision, so we have to use the - // following technique to get round the issue: - // 1. Take the normal unix timestamp to form the whole number part of the - // output, - // 2. Take the result of the Nanosecond function, which retuns the offset - // within the second of the particular unix time instance, to form the - // decimal part of the output - // 3. Concatenate them to produce the final result - seconds := strconv.FormatInt(truncatedDate.Unix(), 10) - nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64) - - output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...) - - return output, nil -} - -// UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a -// NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch -// with either integer or non-integer seconds. -func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { - var ( - number json.Number - f float64 - ) - - if err = json.Unmarshal(b, &number); err != nil { - return fmt.Errorf("could not parse NumericData: %w", err) - } - - if f, err = number.Float64(); err != nil { - return fmt.Errorf("could not convert json number value to float: %w", err) - } - - n := newNumericDateFromSeconds(f) - *date = *n - - return nil -} - -// ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string. -// This type is necessary, since the "aud" claim can either be a single string or an array. -type ClaimStrings []string - -func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { - var value interface{} - - if err = json.Unmarshal(data, &value); err != nil { - return err - } - - var aud []string - - switch v := value.(type) { - case string: - aud = append(aud, v) - case []string: - aud = ClaimStrings(v) - case []interface{}: - for _, vv := range v { - vs, ok := vv.(string) - if !ok { - return &json.UnsupportedTypeError{Type: reflect.TypeOf(vv)} - } - aud = append(aud, vs) - } - case nil: - return nil - default: - return &json.UnsupportedTypeError{Type: reflect.TypeOf(v)} - } - - *s = aud - - return -} - -func (s ClaimStrings) MarshalJSON() (b []byte, err error) { - // This handles a special case in the JWT RFC. If the string array, e.g. used by the "aud" field, - // only contains one element, it MAY be serialized as a single string. This may or may not be - // desired based on the ecosystem of other JWT library used, so we make it configurable by the - // variable MarshalSingleStringAsArray. - if len(s) == 1 && !MarshalSingleStringAsArray { - return json.Marshal(s[0]) - } - - return json.Marshal([]string(s)) -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/.gitignore b/vendor/github.com/golang-jwt/jwt/v5/.gitignore similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/.gitignore rename to vendor/github.com/golang-jwt/jwt/v5/.gitignore diff --git a/vendor/github.com/golang-jwt/jwt/v4/LICENSE b/vendor/github.com/golang-jwt/jwt/v5/LICENSE similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/LICENSE rename to vendor/github.com/golang-jwt/jwt/v5/LICENSE diff --git a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md new file mode 100644 index 000000000..ff9c57e1d --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md @@ -0,0 +1,195 @@ +# Migration Guide (v5.0.0) + +Version `v5` contains a major rework of core functionalities in the `jwt-go` +library. This includes support for several validation options as well as a +re-design of the `Claims` interface. Lastly, we reworked how errors work under +the hood, which should provide a better overall developer experience. + +Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), +the import path will be: + + "github.com/golang-jwt/jwt/v5" + +For most users, changing the import path *should* suffice. However, since we +intentionally changed and cleaned some of the public API, existing programs +might need to be updated. The following sections describe significant changes +and corresponding updates for existing programs. + +## Parsing and Validation Options + +Under the hood, a new `Validator` struct takes care of validating the claims. A +long awaited feature has been the option to fine-tune the validation of tokens. +This is now possible with several `ParserOption` functions that can be appended +to most `Parse` functions, such as `ParseWithClaims`. The most important options +and changes are: + * Added `WithLeeway` to support specifying the leeway that is allowed when + validating time-based claims, such as `exp` or `nbf`. + * Changed default behavior to not check the `iat` claim. Usage of this claim + is OPTIONAL according to the JWT RFC. The claim itself is also purely + informational according to the RFC, so a strict validation failure is not + recommended. If you want to check for sensible values in these claims, + please use the `WithIssuedAt` parser option. + * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for + expected `aud`, `sub` and `iss`. + * Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow + previously global settings to enable base64 strict encoding and the parsing + of base64 strings with padding. The latter is strictly speaking against the + standard, but unfortunately some of the major identity providers issue some + of these incorrect tokens. Both options are disabled by default. + +## Changes to the `Claims` interface + +### Complete Restructuring + +Previously, the claims interface was satisfied with an implementation of a +`Valid() error` function. This had several issues: + * The different claim types (struct claims, map claims, etc.) then contained + similar (but not 100 % identical) code of how this validation was done. This + lead to a lot of (almost) duplicate code and was hard to maintain + * It was not really semantically close to what a "claim" (or a set of claims) + really is; which is a list of defined key/value pairs with a certain + semantic meaning. + +Since all the validation functionality is now extracted into the validator, all +`VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. +Instead, the interface now represents a list of getters to retrieve values with +a specific meaning. This allows us to completely decouple the validation logic +with the underlying storage representation of the claim, which could be a +struct, a map or even something stored in a database. + +```go +type Claims interface { + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) +} +``` + +Users that previously directly called the `Valid` function on their claims, +e.g., to perform validation independently of parsing/verifying a token, can now +use the `jwt.NewValidator` function to create a `Validator` independently of the +`Parser`. + +```go +var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second)) +v.Validate(myClaims) +``` + +### Supported Claim Types and Removal of `StandardClaims` + +The two standard claim types supported by this library, `MapClaims` and +`RegisteredClaims` both implement the necessary functions of this interface. The +old `StandardClaims` struct, which has already been deprecated in `v4` is now +removed. + +Users using custom claims, in most cases, will not experience any changes in the +behavior as long as they embedded `RegisteredClaims`. If they created a new +claim type from scratch, they now need to implemented the proper getter +functions. + +### Migrating Application Specific Logic of the old `Valid` + +Previously, users could override the `Valid` method in a custom claim, for +example to extend the validation with application-specific claims. However, this +was always very dangerous, since once could easily disable the standard +validation and signature checking. + +In order to avoid that, while still supporting the use-case, a new +`ClaimsValidator` interface has been introduced. This interface consists of the +`Validate() error` function. If the validator sees, that a `Claims` struct +implements this interface, the errors returned to the `Validate` function will +be *appended* to the regular standard validation. It is not possible to disable +the standard validation anymore (even only by accident). + +Usage examples can be found in [example_test.go](./example_test.go), to build +claims structs like the following. + +```go +// MyCustomClaims includes all registered claims, plus Foo. +type MyCustomClaims struct { + Foo string `json:"foo"` + jwt.RegisteredClaims +} + +// Validate can be used to execute additional application-specific claims +// validation. +func (m MyCustomClaims) Validate() error { + if m.Foo != "bar" { + return errors.New("must be foobar") + } + + return nil +} +``` + +## Changes to the `Token` and `Parser` struct + +The previously global functions `DecodeSegment` and `EncodeSegment` were moved +to the `Parser` and `Token` struct respectively. This will allow us in the +future to configure the behavior of these two based on options supplied on the +parser or the token (creation). This also removes two previously global +variables and moves them to parser options `WithStrictDecoding` and +`WithPaddingAllowed`. + +In order to do that, we had to adjust the way signing methods work. Previously +they were given a base64 encoded signature in `Verify` and were expected to +return a base64 encoded version of the signature in `Sign`, both as a `string`. +However, this made it necessary to have `DecodeSegment` and `EncodeSegment` +global and was a less than perfect design because we were repeating +encoding/decoding steps for all signing methods. Now, `Sign` and `Verify` +operate on a decoded signature as a `[]byte`, which feels more natural for a +cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of +the final encoding/decoding part. + +In addition to that, we also changed the `Signature` field on `Token` from a +`string` to `[]byte` and this is also now populated with the decoded form. This +is also more consistent, because the other parts of the JWT, mainly `Header` and +`Claims` were already stored in decoded form in `Token`. Only the signature was +stored in base64 encoded form, which was redundant with the information in the +`Raw` field, which contains the complete token as base64. + +```go +type Token struct { + Raw string // Raw contains the raw token + Method SigningMethod // Method is the signing method used or to be used + Header map[string]interface{} // Header is the first segment of the token in decoded form + Claims Claims // Claims is the second segment of the token in decoded form + Signature []byte // Signature is the third segment of the token in decoded form + Valid bool // Valid specifies if the token is valid +} +``` + +Most (if not all) of these changes should not impact the normal usage of this +library. Only users directly accessing the `Signature` field as well as +developers of custom signing methods should be affected. + +# Migration Guide (v4.0.0) + +Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), +the import path will be: + + "github.com/golang-jwt/jwt/v4" + +The `/v4` version will be backwards compatible with existing `v3.x.y` tags in +this repo, as well as `github.com/dgrijalva/jwt-go`. For most users this should +be a drop-in replacement, if you're having troubles migrating, please open an +issue. + +You can replace all occurrences of `github.com/dgrijalva/jwt-go` or +`github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually +or by using tools such as `sed` or `gofmt`. + +And then you'd typically run: + +``` +go get github.com/golang-jwt/jwt/v4 +go mod tidy +``` + +# Older releases (before v3.2.0) + +The original migration guide for older releases can be found at +https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/vendor/github.com/golang-jwt/jwt/v5/README.md b/vendor/github.com/golang-jwt/jwt/v5/README.md new file mode 100644 index 000000000..964598a31 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/README.md @@ -0,0 +1,167 @@ +# jwt-go + +[![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) +[![Go +Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) +[![Coverage Status](https://coveralls.io/repos/github/golang-jwt/jwt/badge.svg?branch=main)](https://coveralls.io/github/golang-jwt/jwt?branch=main) + +A [go](http://www.golang.org) (or 'golang' for search engine friendliness) +implementation of [JSON Web +Tokens](https://datatracker.ietf.org/doc/html/rfc7519). + +Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) +this project adds Go module support, but maintains backwards compatibility with +older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. See the +[`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version +v5.0.0 introduces major improvements to the validation of tokens, but is not +entirely backwards compatible. + +> After the original author of the library suggested migrating the maintenance +> of `jwt-go`, a dedicated team of open source maintainers decided to clone the +> existing library into this repository. See +> [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a +> detailed discussion on this topic. + + +**SECURITY NOTICE:** Some older versions of Go have a security issue in the +crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue +[dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more +detail. + +**SECURITY NOTICE:** It's important that you [validate the `alg` presented is +what you +expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). +This library attempts to make it easy to do the right thing by requiring key +types match the expected alg, but you should take the extra step to verify it in +your usage. See the examples provided. + +### Supported Go versions + +Our support of Go versions is aligned with Go's [version release +policy](https://golang.org/doc/devel/release#policy). So we will support a major +version of Go until there are two newer major releases. We no longer support +building jwt-go with unsupported Go versions, as these contain security +vulnerabilities which will not be fixed. + +## What the heck is a JWT? + +JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web +Tokens. + +In short, it's a signed JSON object that does something useful (for example, +authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is +made of three parts, separated by `.`'s. The first two parts are JSON objects, +that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) +encoded. The last part is the signature, encoded the same way. + +The first part is called the header. It contains the necessary information for +verifying the last part, the signature. For example, which encryption method +was used for signing and what key was used. + +The part in the middle is the interesting bit. It's called the Claims and +contains the actual stuff you care about. Refer to [RFC +7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about +reserved keys and the proper way to add your own. + +## What's in the box? + +This library supports the parsing and verification as well as the generation and +signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, +RSA-PSS, and ECDSA, though hooks are present for adding your own. + +## Installation Guidelines + +1. To install the jwt package, you first need to have + [Go](https://go.dev/doc/install) installed, then you can use the command + below to add `jwt-go` as a dependency in your Go program. + +```sh +go get -u github.com/golang-jwt/jwt/v5 +``` + +2. Import it in your code: + +```go +import "github.com/golang-jwt/jwt/v5" +``` + +## Usage + +A detailed usage guide, including how to sign and verify tokens can be found on +our [documentation website](https://golang-jwt.github.io/jwt/usage/create/). + +## Examples + +See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) +for examples of usage: + +* [Simple example of parsing and validating a + token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) +* [Simple example of building and signing a + token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) +* [Directory of + Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) + +## Compliance + +This library was last reviewed to comply with [RFC +7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few +notable differences: + +* In order to protect against accidental use of [Unsecured + JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using + `alg=none` will only be accepted if the constant + `jwt.UnsafeAllowNoneSignatureType` is provided as the key. + +## Project Status & Versioning + +This library is considered production ready. Feedback and feature requests are +appreciated. The API should be considered stable. There should be very few +backwards-incompatible changes outside of major version updates (and only with +good reason). + +This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull +requests will land on `main`. Periodically, versions will be tagged from +`main`. You can find all the releases on [the project releases +page](https://github.com/golang-jwt/jwt/releases). + +**BREAKING CHANGES:*** A full list of breaking changes is available in +`VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating +your code. + +## Extensions + +This library publishes all the necessary components for adding your own signing +methods or key functions. Simply implement the `SigningMethod` interface and +register a factory method using `RegisterSigningMethod` or provide a +`jwt.Keyfunc`. + +A common use case would be integrating with different 3rd party signature +providers, like key management services from various cloud providers or Hardware +Security Modules (HSMs) or to implement additional standards. + +| Extension | Purpose | Repo | +| --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | +| AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | +| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | + +*Disclaimer*: Unless otherwise specified, these integrations are maintained by +third parties and should not be considered as a primary offer by any of the +mentioned cloud providers + +## More + +Go package documentation can be found [on +pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). Additional +documentation can be found on [our project +page](https://golang-jwt.github.io/jwt/). + +The command line utility included in this project (cmd/jwt) provides a +straightforward example of token creation and parsing as well as a useful tool +for debugging your own integration. You'll also find several implementation +examples in the documentation. + +[golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version +of the JWT logo, which is distributed under the terms of the [MIT +License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt). diff --git a/vendor/github.com/golang-jwt/jwt/v4/SECURITY.md b/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/SECURITY.md rename to vendor/github.com/golang-jwt/jwt/v5/SECURITY.md diff --git a/vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md b/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md similarity index 96% rename from vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md rename to vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md index afbfc4e40..b5039e49c 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md +++ b/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md @@ -1,17 +1,19 @@ -## `jwt-go` Version History +# `jwt-go` Version History -#### 4.0.0 +The following version history is kept for historic purposes. To retrieve the current changes of each version, please refer to the change-log of the specific release versions on https://github.com/golang-jwt/jwt/releases. + +## 4.0.0 * Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`. -#### 3.2.2 +## 3.2.2 * Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)). * Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)). * Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)). * Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)). -#### 3.2.1 +## 3.2.1 * **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt` @@ -117,17 +119,17 @@ It is likely the only integration change required here will be to change `func(t * Refactored the RSA implementation to be easier to read * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` -#### 1.0.2 +## 1.0.2 * Fixed bug in parsing public keys from certificates * Added more tests around the parsing of keys for RS256 * Code refactoring in RS256 implementation. No functional changes -#### 1.0.1 +## 1.0.1 * Fixed panic if RS256 signing method was passed an invalid key -#### 1.0.0 +## 1.0.0 * First versioned release * API stabilized diff --git a/vendor/github.com/golang-jwt/jwt/v5/claims.go b/vendor/github.com/golang-jwt/jwt/v5/claims.go new file mode 100644 index 000000000..d50ff3dad --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/claims.go @@ -0,0 +1,16 @@ +package jwt + +// Claims represent any form of a JWT Claims Set according to +// https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a +// common basis for validation, it is required that an implementation is able to +// supply at least the claim names provided in +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`, +// `iat`, `nbf`, `iss`, `sub` and `aud`. +type Claims interface { + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/doc.go b/vendor/github.com/golang-jwt/jwt/v5/doc.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/doc.go rename to vendor/github.com/golang-jwt/jwt/v5/doc.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go similarity index 88% rename from vendor/github.com/golang-jwt/jwt/v4/ecdsa.go rename to vendor/github.com/golang-jwt/jwt/v5/ecdsa.go index eac023fc6..ca85659ba 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go +++ b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go @@ -55,22 +55,14 @@ func (m *SigningMethodECDSA) Alg() string { // Verify implements token verification for the SigningMethod. // For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error { // Get the key var ecdsaKey *ecdsa.PublicKey switch k := key.(type) { case *ecdsa.PublicKey: ecdsaKey = k default: - return ErrInvalidKeyType + return newError("ECDSA verify expects *ecsda.PublicKey", ErrInvalidKeyType) } if len(sig) != 2*m.KeySize { @@ -97,19 +89,19 @@ func (m *SigningMethodECDSA) Verify(signingString, signature string, key interfa // Sign implements token signing for the SigningMethod. // For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) { // Get the key var ecdsaKey *ecdsa.PrivateKey switch k := key.(type) { case *ecdsa.PrivateKey: ecdsaKey = k default: - return "", ErrInvalidKeyType + return nil, newError("ECDSA sign expects *ecsda.PrivateKey", ErrInvalidKeyType) } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -120,7 +112,7 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string curveBits := ecdsaKey.Curve.Params().BitSize if m.CurveBits != curveBits { - return "", ErrInvalidKey + return nil, ErrInvalidKey } keyBytes := curveBits / 8 @@ -135,8 +127,8 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. - return EncodeSegment(out), nil + return out, nil } else { - return "", err + return nil, err } } diff --git a/vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go rename to vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go new file mode 100644 index 000000000..c2138119e --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go @@ -0,0 +1,79 @@ +package jwt + +import ( + "crypto" + "crypto/ed25519" + "crypto/rand" + "errors" +) + +var ( + ErrEd25519Verification = errors.New("ed25519: verification error") +) + +// SigningMethodEd25519 implements the EdDSA family. +// Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification +type SigningMethodEd25519 struct{} + +// Specific instance for EdDSA +var ( + SigningMethodEdDSA *SigningMethodEd25519 +) + +func init() { + SigningMethodEdDSA = &SigningMethodEd25519{} + RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod { + return SigningMethodEdDSA + }) +} + +func (m *SigningMethodEd25519) Alg() string { + return "EdDSA" +} + +// Verify implements token verification for the SigningMethod. +// For this verify method, key must be an ed25519.PublicKey +func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error { + var ed25519Key ed25519.PublicKey + var ok bool + + if ed25519Key, ok = key.(ed25519.PublicKey); !ok { + return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType) + } + + if len(ed25519Key) != ed25519.PublicKeySize { + return ErrInvalidKey + } + + // Verify the signature + if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { + return ErrEd25519Verification + } + + return nil +} + +// Sign implements token signing for the SigningMethod. +// For this signing method, key must be an ed25519.PrivateKey +func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) { + var ed25519Key crypto.Signer + var ok bool + + if ed25519Key, ok = key.(crypto.Signer); !ok { + return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType) + } + + if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { + return nil, ErrInvalidKey + } + + // Sign the string and return the result. ed25519 performs a two-pass hash + // as part of its algorithm. Therefore, we need to pass a non-prehashed + // message into the Sign function, as indicated by crypto.Hash(0) + sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) + if err != nil { + return nil, err + } + + return sig, nil +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go rename to vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors.go b/vendor/github.com/golang-jwt/jwt/v5/errors.go new file mode 100644 index 000000000..23bb616dd --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/errors.go @@ -0,0 +1,49 @@ +package jwt + +import ( + "errors" + "strings" +) + +var ( + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") + ErrTokenMalformed = errors.New("token is malformed") + ErrTokenUnverifiable = errors.New("token is unverifiable") + ErrTokenSignatureInvalid = errors.New("token signature is invalid") + ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") + ErrTokenInvalidAudience = errors.New("token has invalid audience") + ErrTokenExpired = errors.New("token is expired") + ErrTokenUsedBeforeIssued = errors.New("token used before issued") + ErrTokenInvalidIssuer = errors.New("token has invalid issuer") + ErrTokenInvalidSubject = errors.New("token has invalid subject") + ErrTokenNotValidYet = errors.New("token is not valid yet") + ErrTokenInvalidId = errors.New("token has invalid id") + ErrTokenInvalidClaims = errors.New("token has invalid claims") + ErrInvalidType = errors.New("invalid type for claim") +) + +// joinedError is an error type that works similar to what [errors.Join] +// produces, with the exception that it has a nice error string; mainly its +// error messages are concatenated using a comma, rather than a newline. +type joinedError struct { + errs []error +} + +func (je joinedError) Error() string { + msg := []string{} + for _, err := range je.errs { + msg = append(msg, err.Error()) + } + + return strings.Join(msg, ", ") +} + +// joinErrors joins together multiple errors. Useful for scenarios where +// multiple errors next to each other occur, e.g., in claims validation. +func joinErrors(errs ...error) error { + return &joinedError{ + errs: errs, + } +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go new file mode 100644 index 000000000..a893d355e --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go @@ -0,0 +1,47 @@ +//go:build go1.20 +// +build go1.20 + +package jwt + +import ( + "fmt" +) + +// Unwrap implements the multiple error unwrapping for this error type, which is +// possible in Go 1.20. +func (je joinedError) Unwrap() []error { + return je.errs +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. This makes use of Go 1.20's possibility to +// include more than one %w formatting directive in [fmt.Errorf]. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + var format string + var args []any + if message != "" { + format = "%w: %s" + args = []any{err, message} + } else { + format = "%w" + args = []any{err} + } + + for _, e := range more { + format += ": %w" + args = append(args, e) + } + + err = fmt.Errorf(format, args...) + return err +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go new file mode 100644 index 000000000..2ad542f00 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go @@ -0,0 +1,78 @@ +//go:build !go1.20 +// +build !go1.20 + +package jwt + +import ( + "errors" + "fmt" +) + +// Is implements checking for multiple errors using [errors.Is], since multiple +// error unwrapping is not possible in versions less than Go 1.20. +func (je joinedError) Is(err error) bool { + for _, e := range je.errs { + if errors.Is(e, err) { + return true + } + } + + return false +} + +// wrappedErrors is a workaround for wrapping multiple errors in environments +// where Go 1.20 is not available. It basically uses the already implemented +// functionality of joinedError to handle multiple errors with supplies a +// custom error message that is identical to the one we produce in Go 1.20 using +// multiple %w directives. +type wrappedErrors struct { + msg string + joinedError +} + +// Error returns the stored error string +func (we wrappedErrors) Error() string { + return we.msg +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. Since we cannot use of Go 1.20's possibility +// to include more than one %w formatting directive in [fmt.Errorf], we have to +// emulate that. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + // We cannot wrap multiple errors here with %w, so we have to be a little + // bit creative. Basically, we are using %s instead of %w to produce the + // same error message and then throw the result into a custom error struct. + var format string + var args []any + if message != "" { + format = "%s: %s" + args = []any{err, message} + } else { + format = "%s" + args = []any{err} + } + errs := []error{err} + + for _, e := range more { + format += ": %s" + args = append(args, e) + errs = append(errs, e) + } + + err = &wrappedErrors{ + msg: fmt.Sprintf(format, args...), + joinedError: joinedError{errs: errs}, + } + return err +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/hmac.go b/vendor/github.com/golang-jwt/jwt/v5/hmac.go new file mode 100644 index 000000000..96c62722d --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/hmac.go @@ -0,0 +1,104 @@ +package jwt + +import ( + "crypto" + "crypto/hmac" + "errors" +) + +// SigningMethodHMAC implements the HMAC-SHA family of signing methods. +// Expects key type of []byte for both signing and validation +type SigningMethodHMAC struct { + Name string + Hash crypto.Hash +} + +// Specific instances for HS256 and company +var ( + SigningMethodHS256 *SigningMethodHMAC + SigningMethodHS384 *SigningMethodHMAC + SigningMethodHS512 *SigningMethodHMAC + ErrSignatureInvalid = errors.New("signature is invalid") +) + +func init() { + // HS256 + SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { + return SigningMethodHS256 + }) + + // HS384 + SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { + return SigningMethodHS384 + }) + + // HS512 + SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { + return SigningMethodHS512 + }) +} + +func (m *SigningMethodHMAC) Alg() string { + return m.Name +} + +// Verify implements token verification for the SigningMethod. Returns nil if +// the signature is valid. Key must be []byte. +// +// Note it is not advised to provide a []byte which was converted from a 'human +// readable' string using a subset of ASCII characters. To maximize entropy, you +// should ideally be providing a []byte key which was produced from a +// cryptographically random source, e.g. crypto/rand. Additional information +// about this, and why we intentionally are not supporting string as a key can +// be found on our usage guide +// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types. +func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return newError("HMAC verify expects []byte", ErrInvalidKeyType) + } + + // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } + + // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } + + // No validation errors. Signature is good. + return nil +} + +// Sign implements token signing for the SigningMethod. Key must be []byte. +// +// Note it is not advised to provide a []byte which was converted from a 'human +// readable' string using a subset of ASCII characters. To maximize entropy, you +// should ideally be providing a []byte key which was produced from a +// cryptographically random source, e.g. crypto/rand. Additional information +// about this, and why we intentionally are not supporting string as a key can +// be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. +func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { + if keyBytes, ok := key.([]byte); ok { + if !m.Hash.Available() { + return nil, newError("HMAC sign expects []byte", ErrInvalidKeyType) + } + + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + + return hasher.Sum(nil), nil + } + + return nil, ErrInvalidKeyType +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go new file mode 100644 index 000000000..b2b51a1f8 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go @@ -0,0 +1,109 @@ +package jwt + +import ( + "encoding/json" + "fmt" +) + +// MapClaims is a claims type that uses the map[string]interface{} for JSON +// decoding. This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// GetExpirationTime implements the Claims interface. +func (m MapClaims) GetExpirationTime() (*NumericDate, error) { + return m.parseNumericDate("exp") +} + +// GetNotBefore implements the Claims interface. +func (m MapClaims) GetNotBefore() (*NumericDate, error) { + return m.parseNumericDate("nbf") +} + +// GetIssuedAt implements the Claims interface. +func (m MapClaims) GetIssuedAt() (*NumericDate, error) { + return m.parseNumericDate("iat") +} + +// GetAudience implements the Claims interface. +func (m MapClaims) GetAudience() (ClaimStrings, error) { + return m.parseClaimsString("aud") +} + +// GetIssuer implements the Claims interface. +func (m MapClaims) GetIssuer() (string, error) { + return m.parseString("iss") +} + +// GetSubject implements the Claims interface. +func (m MapClaims) GetSubject() (string, error) { + return m.parseString("sub") +} + +// parseNumericDate tries to parse a key in the map claims type as a number +// date. This will succeed, if the underlying type is either a [float64] or a +// [json.Number]. Otherwise, nil will be returned. +func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { + v, ok := m[key] + if !ok { + return nil, nil + } + + switch exp := v.(type) { + case float64: + if exp == 0 { + return nil, nil + } + + return newNumericDateFromSeconds(exp), nil + case json.Number: + v, _ := exp.Float64() + + return newNumericDateFromSeconds(v), nil + } + + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) +} + +// parseClaimsString tries to parse a key in the map claims type as a +// [ClaimsStrings] type, which can either be a string or an array of string. +func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { + var cs []string + switch v := m[key].(type) { + case string: + cs = append(cs, v) + case []string: + cs = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + cs = append(cs, vs) + } + } + + return cs, nil +} + +// parseString tries to parse a key in the map claims type as a [string] type. +// If the key does not exist, an empty string is returned. If the key has the +// wrong type, an error is returned. +func (m MapClaims) parseString(key string) (string, error) { + var ( + ok bool + raw interface{} + iss string + ) + raw, ok = m[key] + if !ok { + return "", nil + } + + iss, ok = raw.(string) + if !ok { + return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + + return iss, nil +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/none.go b/vendor/github.com/golang-jwt/jwt/v5/none.go new file mode 100644 index 000000000..685c2ea30 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/none.go @@ -0,0 +1,50 @@ +package jwt + +// SigningMethodNone implements the none signing method. This is required by the spec +// but you probably should never use it. +var SigningMethodNone *signingMethodNone + +const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" + +var NoneSignatureTypeDisallowedError error + +type signingMethodNone struct{} +type unsafeNoneMagicConstant string + +func init() { + SigningMethodNone = &signingMethodNone{} + NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable) + + RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { + return SigningMethodNone + }) +} + +func (m *signingMethodNone) Alg() string { + return "none" +} + +// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Verify(signingString string, sig []byte, key interface{}) (err error) { + // Key must be UnsafeAllowNoneSignatureType to prevent accidentally + // accepting 'none' signing method + if _, ok := key.(unsafeNoneMagicConstant); !ok { + return NoneSignatureTypeDisallowedError + } + // If signing method is none, signature must be an empty string + if len(sig) != 0 { + return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) + } + + // Accept 'none' signing method. + return nil +} + +// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Sign(signingString string, key interface{}) ([]byte, error) { + if _, ok := key.(unsafeNoneMagicConstant); ok { + return []byte{}, nil + } + + return nil, NoneSignatureTypeDisallowedError +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser.go b/vendor/github.com/golang-jwt/jwt/v5/parser.go new file mode 100644 index 000000000..ecf99af78 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/parser.go @@ -0,0 +1,238 @@ +package jwt + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "strings" +) + +type Parser struct { + // If populated, only these methods will be considered valid. + validMethods []string + + // Use JSON Number format in JSON decoder. + useJSONNumber bool + + // Skip claims validation during token parsing. + skipClaimsValidation bool + + validator *Validator + + decodeStrict bool + + decodePaddingAllowed bool +} + +// NewParser creates a new Parser with the specified options +func NewParser(options ...ParserOption) *Parser { + p := &Parser{ + validator: &Validator{}, + } + + // Loop through our parsing options and apply them + for _, option := range options { + option(p) + } + + return p +} + +// Parse parses, validates, verifies the signature and returns the parsed token. +// keyFunc will receive the parsed token and should return the key for validating. +func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) +} + +// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims +// interface. This provides default values which can be overridden and allows a caller to use their own type, rather +// than the default MapClaims implementation of Claims. +// +// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), +// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the +// proper memory for it before passing in the overall claims, otherwise you might run into a panic. +func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } + + // Verify signing method is in the required set + if p.validMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.validMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) + } + } + + // Decode signature + token.Signature, err = p.DecodeSegment(parts[2]) + if err != nil { + return token, newError("could not base64 decode signature", ErrTokenMalformed, err) + } + text := strings.Join(parts[0:2], ".") + + // Lookup key(s) + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, newError("no keyfunc was provided", ErrTokenUnverifiable) + } + + got, err := keyFunc(token) + if err != nil { + return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) + } + + switch have := got.(type) { + case VerificationKeySet: + if len(have.Keys) == 0 { + return token, newError("keyfunc returned empty verification key set", ErrTokenUnverifiable) + } + // Iterate through keys and verify signature, skipping the rest when a match is found. + // Return the last error if no match is found. + for _, key := range have.Keys { + if err = token.Method.Verify(text, token.Signature, key); err == nil { + break + } + } + default: + err = token.Method.Verify(text, token.Signature, have) + } + if err != nil { + return token, newError("", ErrTokenSignatureInvalid, err) + } + + // Validate Claims + if !p.skipClaimsValidation { + // Make sure we have at least a default validator + if p.validator == nil { + p.validator = NewValidator() + } + + if err := p.validator.Validate(claims); err != nil { + return token, newError("", ErrTokenInvalidClaims, err) + } + } + + // No errors so far, token is valid. + token.Valid = true + + return token, nil +} + +// ParseUnverified parses the token but doesn't validate the signature. +// +// WARNING: Don't use this method unless you know what you're doing. +// +// It's only ever useful in cases where you know the signature is valid (since it has already +// been or will be checked elsewhere in the stack) and you want to extract values from it. +func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed) + } + + token = &Token{Raw: tokenString} + + // parse Header + var headerBytes []byte + if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { + return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) + } + + // parse Claims + token.Claims = claims + + claimBytes, err := p.DecodeSegment(parts[1]) + if err != nil { + return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) + } + + // If `useJSONNumber` is enabled then we must use *json.Decoder to decode + // the claims. However, this comes with a performance penalty so only use + // it if we must and, otherwise, simple use json.Unmarshal. + if !p.useJSONNumber { + // JSON Unmarshal. Special case for map type to avoid weird pointer behavior. + if c, ok := token.Claims.(MapClaims); ok { + err = json.Unmarshal(claimBytes, &c) + } else { + err = json.Unmarshal(claimBytes, &claims) + } + } else { + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + dec.UseNumber() + // JSON Decode. Special case for map type to avoid weird pointer behavior. + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + } + if err != nil { + return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) + } + + // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) + } + } else { + return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) + } + + return token, parts, nil +} + +// DecodeSegment decodes a JWT specific base64url encoding. This function will +// take into account whether the [Parser] is configured with additional options, +// such as [WithStrictDecoding] or [WithPaddingAllowed]. +func (p *Parser) DecodeSegment(seg string) ([]byte, error) { + encoding := base64.RawURLEncoding + + if p.decodePaddingAllowed { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + encoding = base64.URLEncoding + } + + if p.decodeStrict { + encoding = encoding.Strict() + } + return encoding.DecodeString(seg) +} + +// Parse parses, validates, verifies the signature and returns the parsed token. +// keyFunc will receive the parsed token and should return the cryptographic key +// for verifying the signature. The caller is strongly encouraged to set the +// WithValidMethods option to validate the 'alg' claim in the token matches the +// expected algorithm. For more details about the importance of validating the +// 'alg' claim, see +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ +func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).Parse(tokenString, keyFunc) +} + +// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). +// +// Note: If you provide a custom claim implementation that embeds one of the +// standard claims (such as RegisteredClaims), make sure that a) you either +// embed a non-pointer version of the claims or b) if you are using a pointer, +// allocate the proper memory for it before passing in the overall claims, +// otherwise you might run into a panic. +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go new file mode 100644 index 000000000..88a780fbd --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go @@ -0,0 +1,128 @@ +package jwt + +import "time" + +// ParserOption is used to implement functional-style options that modify the +// behavior of the parser. To add new options, just create a function (ideally +// beginning with With or Without) that returns an anonymous function that takes +// a *Parser type as input and manipulates its configuration accordingly. +type ParserOption func(*Parser) + +// WithValidMethods is an option to supply algorithm methods that the parser +// will check. Only those methods will be considered valid. It is heavily +// encouraged to use this option in order to prevent attacks such as +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. +func WithValidMethods(methods []string) ParserOption { + return func(p *Parser) { + p.validMethods = methods + } +} + +// WithJSONNumber is an option to configure the underlying JSON parser with +// UseNumber. +func WithJSONNumber() ParserOption { + return func(p *Parser) { + p.useJSONNumber = true + } +} + +// WithoutClaimsValidation is an option to disable claims validation. This +// option should only be used if you exactly know what you are doing. +func WithoutClaimsValidation() ParserOption { + return func(p *Parser) { + p.skipClaimsValidation = true + } +} + +// WithLeeway returns the ParserOption for specifying the leeway window. +func WithLeeway(leeway time.Duration) ParserOption { + return func(p *Parser) { + p.validator.leeway = leeway + } +} + +// WithTimeFunc returns the ParserOption for specifying the time func. The +// primary use-case for this is testing. If you are looking for a way to account +// for clock-skew, WithLeeway should be used instead. +func WithTimeFunc(f func() time.Time) ParserOption { + return func(p *Parser) { + p.validator.timeFunc = f + } +} + +// WithIssuedAt returns the ParserOption to enable verification +// of issued-at. +func WithIssuedAt() ParserOption { + return func(p *Parser) { + p.validator.verifyIat = true + } +} + +// WithExpirationRequired returns the ParserOption to make exp claim required. +// By default exp claim is optional. +func WithExpirationRequired() ParserOption { + return func(p *Parser) { + p.validator.requireExp = true + } +} + +// WithAudience configures the validator to require the specified audience in +// the `aud` claim. Validation will fail if the audience is not listed in the +// token or the `aud` claim is missing. +// +// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an audience is expected. +func WithAudience(aud string) ParserOption { + return func(p *Parser) { + p.validator.expectedAud = aud + } +} + +// WithIssuer configures the validator to require the specified issuer in the +// `iss` claim. Validation will fail if a different issuer is specified in the +// token or the `iss` claim is missing. +// +// NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an issuer is expected. +func WithIssuer(iss string) ParserOption { + return func(p *Parser) { + p.validator.expectedIss = iss + } +} + +// WithSubject configures the validator to require the specified subject in the +// `sub` claim. Validation will fail if a different subject is specified in the +// token or the `sub` claim is missing. +// +// NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if a subject is expected. +func WithSubject(sub string) ParserOption { + return func(p *Parser) { + p.validator.expectedSub = sub + } +} + +// WithPaddingAllowed will enable the codec used for decoding JWTs to allow +// padding. Note that the JWS RFC7515 states that the tokens will utilize a +// Base64url encoding with no padding. Unfortunately, some implementations of +// JWT are producing non-standard tokens, and thus require support for decoding. +func WithPaddingAllowed() ParserOption { + return func(p *Parser) { + p.decodePaddingAllowed = true + } +} + +// WithStrictDecoding will switch the codec used for decoding JWTs into strict +// mode. In this mode, the decoder requires that trailing padding bits are zero, +// as described in RFC 4648 section 3.5. +func WithStrictDecoding() ParserOption { + return func(p *Parser) { + p.decodeStrict = true + } +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go b/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go new file mode 100644 index 000000000..77951a531 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go @@ -0,0 +1,63 @@ +package jwt + +// RegisteredClaims are a structured version of the JWT Claims Set, +// restricted to Registered Claim Names, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 +// +// This type can be used on its own, but then additional private and +// public claims embedded in the JWT will not be parsed. The typical use-case +// therefore is to embedded this in a user-defined claim type. +// +// See examples for how to use this with your own claim types. +type RegisteredClaims struct { + // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 + Issuer string `json:"iss,omitempty"` + + // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 + Subject string `json:"sub,omitempty"` + + // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 + Audience ClaimStrings `json:"aud,omitempty"` + + // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 + ExpiresAt *NumericDate `json:"exp,omitempty"` + + // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 + NotBefore *NumericDate `json:"nbf,omitempty"` + + // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 + IssuedAt *NumericDate `json:"iat,omitempty"` + + // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 + ID string `json:"jti,omitempty"` +} + +// GetExpirationTime implements the Claims interface. +func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) { + return c.ExpiresAt, nil +} + +// GetNotBefore implements the Claims interface. +func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) { + return c.NotBefore, nil +} + +// GetIssuedAt implements the Claims interface. +func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) { + return c.IssuedAt, nil +} + +// GetAudience implements the Claims interface. +func (c RegisteredClaims) GetAudience() (ClaimStrings, error) { + return c.Audience, nil +} + +// GetIssuer implements the Claims interface. +func (c RegisteredClaims) GetIssuer() (string, error) { + return c.Issuer, nil +} + +// GetSubject implements the Claims interface. +func (c RegisteredClaims) GetSubject() (string, error) { + return c.Subject, nil +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa.go b/vendor/github.com/golang-jwt/jwt/v5/rsa.go similarity index 84% rename from vendor/github.com/golang-jwt/jwt/v4/rsa.go rename to vendor/github.com/golang-jwt/jwt/v5/rsa.go index b910b19c0..83cbee6ae 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/rsa.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa.go @@ -46,20 +46,12 @@ func (m *SigningMethodRSA) Alg() string { // Verify implements token verification for the SigningMethod // For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error { var rsaKey *rsa.PublicKey var ok bool if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return ErrInvalidKeyType + return newError("RSA verify expects *rsa.PublicKey", ErrInvalidKeyType) } // Create hasher @@ -75,18 +67,18 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface // Sign implements token signing for the SigningMethod // For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) { var rsaKey *rsa.PrivateKey var ok bool // Validate type of key if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return "", ErrInvalidKey + return nil, newError("RSA sign expects *rsa.PrivateKey", ErrInvalidKeyType) } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -94,8 +86,8 @@ func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, // Sign the string and return the encoded bytes if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return EncodeSegment(sigBytes), nil + return sigBytes, nil } else { - return "", err + return nil, err } } diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go similarity index 88% rename from vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go rename to vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go index 4fd6f9e61..28c386ec4 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go @@ -82,21 +82,13 @@ func init() { // Verify implements token verification for the SigningMethod. // For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error { var rsaKey *rsa.PublicKey switch k := key.(type) { case *rsa.PublicKey: rsaKey = k default: - return ErrInvalidKey + return newError("RSA-PSS verify expects *rsa.PublicKey", ErrInvalidKeyType) } // Create hasher @@ -116,19 +108,19 @@ func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interf // Sign implements token signing for the SigningMethod. // For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) { var rsaKey *rsa.PrivateKey switch k := key.(type) { case *rsa.PrivateKey: rsaKey = k default: - return "", ErrInvalidKeyType + return nil, newError("RSA-PSS sign expects *rsa.PrivateKey", ErrInvalidKeyType) } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -136,8 +128,8 @@ func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (strin // Sign the string and return the encoded bytes if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return EncodeSegment(sigBytes), nil + return sigBytes, nil } else { - return "", err + return nil, err } } diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go similarity index 93% rename from vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go rename to vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go index 1966c450b..b3aeebbe1 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go +++ b/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go @@ -75,7 +75,7 @@ func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.Pr return pkey, nil } -// ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key +// ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { var err error @@ -91,7 +91,9 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { if cert, err := x509.ParseCertificate(block.Bytes); err == nil { parsedKey = cert.PublicKey } else { - return nil, err + if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil { + return nil, err + } } } diff --git a/vendor/github.com/golang-jwt/jwt/v5/signing_method.go b/vendor/github.com/golang-jwt/jwt/v5/signing_method.go new file mode 100644 index 000000000..0d73631c1 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/signing_method.go @@ -0,0 +1,49 @@ +package jwt + +import ( + "sync" +) + +var signingMethods = map[string]func() SigningMethod{} +var signingMethodLock = new(sync.RWMutex) + +// SigningMethod can be used add new methods for signing or verifying tokens. It +// takes a decoded signature as an input in the Verify function and produces a +// signature in Sign. The signature is then usually base64 encoded as part of a +// JWT. +type SigningMethod interface { + Verify(signingString string, sig []byte, key interface{}) error // Returns nil if signature is valid + Sign(signingString string, key interface{}) ([]byte, error) // Returns signature or error + Alg() string // returns the alg identifier for this method (example: 'HS256') +} + +// RegisterSigningMethod registers the "alg" name and a factory function for signing method. +// This is typically done during init() in the method's implementation +func RegisterSigningMethod(alg string, f func() SigningMethod) { + signingMethodLock.Lock() + defer signingMethodLock.Unlock() + + signingMethods[alg] = f +} + +// GetSigningMethod retrieves a signing method from an "alg" string +func GetSigningMethod(alg string) (method SigningMethod) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + + if methodF, ok := signingMethods[alg]; ok { + method = methodF() + } + return +} + +// GetAlgorithms returns a list of registered "alg" names +func GetAlgorithms() (algs []string) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + + for alg := range signingMethods { + algs = append(algs, alg) + } + return +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/staticcheck.conf b/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/staticcheck.conf rename to vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf diff --git a/vendor/github.com/golang-jwt/jwt/v5/token.go b/vendor/github.com/golang-jwt/jwt/v5/token.go new file mode 100644 index 000000000..352873a2d --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/token.go @@ -0,0 +1,100 @@ +package jwt + +import ( + "crypto" + "encoding/base64" + "encoding/json" +) + +// Keyfunc will be used by the Parse methods as a callback function to supply +// the key for verification. The function receives the parsed, but unverified +// Token. This allows you to use properties in the Header of the token (such as +// `kid`) to identify which key to use. +// +// The returned interface{} may be a single key or a VerificationKeySet containing +// multiple keys. +type Keyfunc func(*Token) (interface{}, error) + +// VerificationKey represents a public or secret key for verifying a token's signature. +type VerificationKey interface { + crypto.PublicKey | []uint8 +} + +// VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token. +type VerificationKeySet struct { + Keys []VerificationKey +} + +// Token represents a JWT Token. Different fields will be used depending on +// whether you're creating or parsing/verifying a token. +type Token struct { + Raw string // Raw contains the raw token. Populated when you [Parse] a token + Method SigningMethod // Method is the signing method used or to be used + Header map[string]interface{} // Header is the first segment of the token in decoded form + Claims Claims // Claims is the second segment of the token in decoded form + Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token + Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token +} + +// New creates a new [Token] with the specified signing method and an empty map +// of claims. Additional options can be specified, but are currently unused. +func New(method SigningMethod, opts ...TokenOption) *Token { + return NewWithClaims(method, MapClaims{}, opts...) +} + +// NewWithClaims creates a new [Token] with the specified signing method and +// claims. Additional options can be specified, but are currently unused. +func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// SignedString creates and returns a complete, signed JWT. The token is signed +// using the SigningMethod specified in the token. Please refer to +// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types +// for an overview of the different signing methods and their respective key +// types. +func (t *Token) SignedString(key interface{}) (string, error) { + sstr, err := t.SigningString() + if err != nil { + return "", err + } + + sig, err := t.Method.Sign(sstr, key) + if err != nil { + return "", err + } + + return sstr + "." + t.EncodeSegment(sig), nil +} + +// SigningString generates the signing string. This is the most expensive part +// of the whole deal. Unless you need this for something special, just go +// straight for the SignedString. +func (t *Token) SigningString() (string, error) { + h, err := json.Marshal(t.Header) + if err != nil { + return "", err + } + + c, err := json.Marshal(t.Claims) + if err != nil { + return "", err + } + + return t.EncodeSegment(h) + "." + t.EncodeSegment(c), nil +} + +// EncodeSegment encodes a JWT specific base64url encoding with padding +// stripped. In the future, this function might take into account a +// [TokenOption]. Therefore, this function exists as a method of [Token], rather +// than a global function. +func (*Token) EncodeSegment(seg []byte) string { + return base64.RawURLEncoding.EncodeToString(seg) +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/token_option.go b/vendor/github.com/golang-jwt/jwt/v5/token_option.go new file mode 100644 index 000000000..b4ae3badf --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/token_option.go @@ -0,0 +1,5 @@ +package jwt + +// TokenOption is a reserved type, which provides some forward compatibility, +// if we ever want to introduce token creation-related options. +type TokenOption func(*Token) diff --git a/vendor/github.com/golang-jwt/jwt/v5/types.go b/vendor/github.com/golang-jwt/jwt/v5/types.go new file mode 100644 index 000000000..b2655a9e6 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/types.go @@ -0,0 +1,149 @@ +package jwt + +import ( + "encoding/json" + "fmt" + "math" + "strconv" + "time" +) + +// TimePrecision sets the precision of times and dates within this library. This +// has an influence on the precision of times when comparing expiry or other +// related time fields. Furthermore, it is also the precision of times when +// serializing. +// +// For backwards compatibility the default precision is set to seconds, so that +// no fractional timestamps are generated. +var TimePrecision = time.Second + +// MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, +// especially its MarshalJSON function. +// +// If it is set to true (the default), it will always serialize the type as an +// array of strings, even if it just contains one element, defaulting to the +// behavior of the underlying []string. If it is set to false, it will serialize +// to a single string, if it contains one element. Otherwise, it will serialize +// to an array of strings. +var MarshalSingleStringAsArray = true + +// NumericDate represents a JSON numeric date value, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-2. +type NumericDate struct { + time.Time +} + +// NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. +// It will truncate the timestamp according to the precision specified in TimePrecision. +func NewNumericDate(t time.Time) *NumericDate { + return &NumericDate{t.Truncate(TimePrecision)} +} + +// newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a +// UNIX epoch with the float fraction representing non-integer seconds. +func newNumericDateFromSeconds(f float64) *NumericDate { + round, frac := math.Modf(f) + return NewNumericDate(time.Unix(int64(round), int64(frac*1e9))) +} + +// MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch +// represented in NumericDate to a byte array, using the precision specified in TimePrecision. +func (date NumericDate) MarshalJSON() (b []byte, err error) { + var prec int + if TimePrecision < time.Second { + prec = int(math.Log10(float64(time.Second) / float64(TimePrecision))) + } + truncatedDate := date.Truncate(TimePrecision) + + // For very large timestamps, UnixNano would overflow an int64, but this + // function requires nanosecond level precision, so we have to use the + // following technique to get round the issue: + // + // 1. Take the normal unix timestamp to form the whole number part of the + // output, + // 2. Take the result of the Nanosecond function, which returns the offset + // within the second of the particular unix time instance, to form the + // decimal part of the output + // 3. Concatenate them to produce the final result + seconds := strconv.FormatInt(truncatedDate.Unix(), 10) + nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64) + + output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...) + + return output, nil +} + +// UnmarshalJSON is an implementation of the json.RawMessage interface and +// deserializes a [NumericDate] from a JSON representation, i.e. a +// [json.Number]. This number represents an UNIX epoch with either integer or +// non-integer seconds. +func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { + var ( + number json.Number + f float64 + ) + + if err = json.Unmarshal(b, &number); err != nil { + return fmt.Errorf("could not parse NumericData: %w", err) + } + + if f, err = number.Float64(); err != nil { + return fmt.Errorf("could not convert json number value to float: %w", err) + } + + n := newNumericDateFromSeconds(f) + *date = *n + + return nil +} + +// ClaimStrings is basically just a slice of strings, but it can be either +// serialized from a string array or just a string. This type is necessary, +// since the "aud" claim can either be a single string or an array. +type ClaimStrings []string + +func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { + var value interface{} + + if err = json.Unmarshal(data, &value); err != nil { + return err + } + + var aud []string + + switch v := value.(type) { + case string: + aud = append(aud, v) + case []string: + aud = ClaimStrings(v) + case []interface{}: + for _, vv := range v { + vs, ok := vv.(string) + if !ok { + return ErrInvalidType + } + aud = append(aud, vs) + } + case nil: + return nil + default: + return ErrInvalidType + } + + *s = aud + + return +} + +func (s ClaimStrings) MarshalJSON() (b []byte, err error) { + // This handles a special case in the JWT RFC. If the string array, e.g. + // used by the "aud" field, only contains one element, it MAY be serialized + // as a single string. This may or may not be desired based on the ecosystem + // of other JWT library used, so we make it configurable by the variable + // MarshalSingleStringAsArray. + if len(s) == 1 && !MarshalSingleStringAsArray { + return json.Marshal(s[0]) + } + + return json.Marshal([]string(s)) +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/validator.go b/vendor/github.com/golang-jwt/jwt/v5/validator.go new file mode 100644 index 000000000..008ecd871 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/validator.go @@ -0,0 +1,316 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// ClaimsValidator is an interface that can be implemented by custom claims who +// wish to execute any additional claims validation based on +// application-specific logic. The Validate function is then executed in +// addition to the regular claims validation and any error returned is appended +// to the final validation result. +// +// type MyCustomClaims struct { +// Foo string `json:"foo"` +// jwt.RegisteredClaims +// } +// +// func (m MyCustomClaims) Validate() error { +// if m.Foo != "bar" { +// return errors.New("must be foobar") +// } +// return nil +// } +type ClaimsValidator interface { + Claims + Validate() error +} + +// Validator is the core of the new Validation API. It is automatically used by +// a [Parser] during parsing and can be modified with various parser options. +// +// The [NewValidator] function should be used to create an instance of this +// struct. +type Validator struct { + // leeway is an optional leeway that can be provided to account for clock skew. + leeway time.Duration + + // timeFunc is used to supply the current time that is needed for + // validation. If unspecified, this defaults to time.Now. + timeFunc func() time.Time + + // requireExp specifies whether the exp claim is required + requireExp bool + + // verifyIat specifies whether the iat (Issued At) claim will be verified. + // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this + // only specifies the age of the token, but no validation check is + // necessary. However, if wanted, it can be checked if the iat is + // unrealistic, i.e., in the future. + verifyIat bool + + // expectedAud contains the audience this token expects. Supplying an empty + // string will disable aud checking. + expectedAud string + + // expectedIss contains the issuer this token expects. Supplying an empty + // string will disable iss checking. + expectedIss string + + // expectedSub contains the subject this token expects. Supplying an empty + // string will disable sub checking. + expectedSub string +} + +// NewValidator can be used to create a stand-alone validator with the supplied +// options. This validator can then be used to validate already parsed claims. +// +// Note: Under normal circumstances, explicitly creating a validator is not +// needed and can potentially be dangerous; instead functions of the [Parser] +// class should be used. +// +// The [Validator] is only checking the *validity* of the claims, such as its +// expiration time, but it does NOT perform *signature verification* of the +// token. +func NewValidator(opts ...ParserOption) *Validator { + p := NewParser(opts...) + return p.validator +} + +// Validate validates the given claims. It will also perform any custom +// validation if claims implements the [ClaimsValidator] interface. +// +// Note: It will NOT perform any *signature verification* on the token that +// contains the claims and expects that the [Claim] was already successfully +// verified. +func (v *Validator) Validate(claims Claims) error { + var ( + now time.Time + errs []error = make([]error, 0, 6) + err error + ) + + // Check, if we have a time func + if v.timeFunc != nil { + now = v.timeFunc() + } else { + now = time.Now() + } + + // We always need to check the expiration time, but usage of the claim + // itself is OPTIONAL by default. requireExp overrides this behavior + // and makes the exp claim mandatory. + if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil { + errs = append(errs, err) + } + + // We always need to check not-before, but usage of the claim itself is + // OPTIONAL. + if err = v.verifyNotBefore(claims, now, false); err != nil { + errs = append(errs, err) + } + + // Check issued-at if the option is enabled + if v.verifyIat { + if err = v.verifyIssuedAt(claims, now, false); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected audience, we also require the audience claim + if v.expectedAud != "" { + if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected issuer, we also require the issuer claim + if v.expectedIss != "" { + if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected subject, we also require the subject claim + if v.expectedSub != "" { + if err = v.verifySubject(claims, v.expectedSub, true); err != nil { + errs = append(errs, err) + } + } + + // Finally, we want to give the claim itself some possibility to do some + // additional custom validation based on a custom Validate function. + cvt, ok := claims.(ClaimsValidator) + if ok { + if err := cvt.Validate(); err != nil { + errs = append(errs, err) + } + } + + if len(errs) == 0 { + return nil + } + + return joinErrors(errs...) +} + +// verifyExpiresAt compares the exp claim in claims against cmp. This function +// will succeed if cmp < exp. Additional leeway is taken into account. +// +// If exp is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { + exp, err := claims.GetExpirationTime() + if err != nil { + return err + } + + if exp == nil { + return errorIfRequired(required, "exp") + } + + return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) +} + +// verifyIssuedAt compares the iat claim in claims against cmp. This function +// will succeed if cmp >= iat. Additional leeway is taken into account. +// +// If iat is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { + iat, err := claims.GetIssuedAt() + if err != nil { + return err + } + + if iat == nil { + return errorIfRequired(required, "iat") + } + + return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) +} + +// verifyNotBefore compares the nbf claim in claims against cmp. This function +// will return true if cmp >= nbf. Additional leeway is taken into account. +// +// If nbf is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { + nbf, err := claims.GetNotBefore() + if err != nil { + return err + } + + if nbf == nil { + return errorIfRequired(required, "nbf") + } + + return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) +} + +// verifyAudience compares the aud claim against cmp. +// +// If aud is not set or an empty list, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyAudience(claims Claims, cmp string, required bool) error { + aud, err := claims.GetAudience() + if err != nil { + return err + } + + if len(aud) == 0 { + return errorIfRequired(required, "aud") + } + + // use a var here to keep constant time compare when looping over a number of claims + result := false + + var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } + + // case where "" is sent in one or many aud claims + if stringClaims == "" { + return errorIfRequired(required, "aud") + } + + return errorIfFalse(result, ErrTokenInvalidAudience) +} + +// verifyIssuer compares the iss claim in claims against cmp. +// +// If iss is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyIssuer(claims Claims, cmp string, required bool) error { + iss, err := claims.GetIssuer() + if err != nil { + return err + } + + if iss == "" { + return errorIfRequired(required, "iss") + } + + return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) +} + +// verifySubject compares the sub claim against cmp. +// +// If sub is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifySubject(claims Claims, cmp string, required bool) error { + sub, err := claims.GetSubject() + if err != nil { + return err + } + + if sub == "" { + return errorIfRequired(required, "sub") + } + + return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) +} + +// errorIfFalse returns the error specified in err, if the value is true. +// Otherwise, nil is returned. +func errorIfFalse(value bool, err error) error { + if value { + return nil + } else { + return err + } +} + +// errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is +// true. Otherwise, nil is returned. +func errorIfRequired(required bool, claim string) error { + if required { + return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) + } else { + return nil + } +} diff --git a/vendor/github.com/google/gnostic/LICENSE b/vendor/github.com/google/gnostic-models/LICENSE similarity index 100% rename from vendor/github.com/google/gnostic/LICENSE rename to vendor/github.com/google/gnostic-models/LICENSE diff --git a/vendor/github.com/google/gnostic/compiler/README.md b/vendor/github.com/google/gnostic-models/compiler/README.md similarity index 100% rename from vendor/github.com/google/gnostic/compiler/README.md rename to vendor/github.com/google/gnostic-models/compiler/README.md diff --git a/vendor/github.com/google/gnostic/compiler/context.go b/vendor/github.com/google/gnostic-models/compiler/context.go similarity index 100% rename from vendor/github.com/google/gnostic/compiler/context.go rename to vendor/github.com/google/gnostic-models/compiler/context.go diff --git a/vendor/github.com/google/gnostic/compiler/error.go b/vendor/github.com/google/gnostic-models/compiler/error.go similarity index 100% rename from vendor/github.com/google/gnostic/compiler/error.go rename to vendor/github.com/google/gnostic-models/compiler/error.go diff --git a/vendor/github.com/google/gnostic/compiler/extensions.go b/vendor/github.com/google/gnostic-models/compiler/extensions.go similarity index 97% rename from vendor/github.com/google/gnostic/compiler/extensions.go rename to vendor/github.com/google/gnostic-models/compiler/extensions.go index 5b5a916d2..250c81e8c 100644 --- a/vendor/github.com/google/gnostic/compiler/extensions.go +++ b/vendor/github.com/google/gnostic-models/compiler/extensions.go @@ -24,7 +24,7 @@ import ( "github.com/golang/protobuf/ptypes/any" yaml "gopkg.in/yaml.v3" - extensions "github.com/google/gnostic/extensions" + extensions "github.com/google/gnostic-models/extensions" ) // ExtensionHandler describes a binary that is called by the compiler to handle specification extensions. diff --git a/vendor/github.com/google/gnostic-models/compiler/helpers.go b/vendor/github.com/google/gnostic-models/compiler/helpers.go new file mode 100644 index 000000000..975d65e8f --- /dev/null +++ b/vendor/github.com/google/gnostic-models/compiler/helpers.go @@ -0,0 +1,397 @@ +// Copyright 2017 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package compiler + +import ( + "fmt" + "regexp" + "sort" + "strconv" + + "gopkg.in/yaml.v3" + + "github.com/google/gnostic-models/jsonschema" +) + +// compiler helper functions, usually called from generated code + +// UnpackMap gets a *yaml.Node if possible. +func UnpackMap(in *yaml.Node) (*yaml.Node, bool) { + if in == nil { + return nil, false + } + return in, true +} + +// SortedKeysForMap returns the sorted keys of a yamlv2.MapSlice. +func SortedKeysForMap(m *yaml.Node) []string { + keys := make([]string, 0) + if m.Kind == yaml.MappingNode { + for i := 0; i < len(m.Content); i += 2 { + keys = append(keys, m.Content[i].Value) + } + } + sort.Strings(keys) + return keys +} + +// MapHasKey returns true if a yamlv2.MapSlice contains a specified key. +func MapHasKey(m *yaml.Node, key string) bool { + if m == nil { + return false + } + if m.Kind == yaml.MappingNode { + for i := 0; i < len(m.Content); i += 2 { + itemKey := m.Content[i].Value + if key == itemKey { + return true + } + } + } + return false +} + +// MapValueForKey gets the value of a map value for a specified key. +func MapValueForKey(m *yaml.Node, key string) *yaml.Node { + if m == nil { + return nil + } + if m.Kind == yaml.MappingNode { + for i := 0; i < len(m.Content); i += 2 { + itemKey := m.Content[i].Value + if key == itemKey { + return m.Content[i+1] + } + } + } + return nil +} + +// ConvertInterfaceArrayToStringArray converts an array of interfaces to an array of strings, if possible. +func ConvertInterfaceArrayToStringArray(interfaceArray []interface{}) []string { + stringArray := make([]string, 0) + for _, item := range interfaceArray { + v, ok := item.(string) + if ok { + stringArray = append(stringArray, v) + } + } + return stringArray +} + +// SequenceNodeForNode returns a node if it is a SequenceNode. +func SequenceNodeForNode(node *yaml.Node) (*yaml.Node, bool) { + if node.Kind != yaml.SequenceNode { + return nil, false + } + return node, true +} + +// BoolForScalarNode returns the bool value of a node. +func BoolForScalarNode(node *yaml.Node) (bool, bool) { + if node == nil { + return false, false + } + if node.Kind == yaml.DocumentNode { + return BoolForScalarNode(node.Content[0]) + } + if node.Kind != yaml.ScalarNode { + return false, false + } + if node.Tag != "!!bool" { + return false, false + } + v, err := strconv.ParseBool(node.Value) + if err != nil { + return false, false + } + return v, true +} + +// IntForScalarNode returns the integer value of a node. +func IntForScalarNode(node *yaml.Node) (int64, bool) { + if node == nil { + return 0, false + } + if node.Kind == yaml.DocumentNode { + return IntForScalarNode(node.Content[0]) + } + if node.Kind != yaml.ScalarNode { + return 0, false + } + if node.Tag != "!!int" { + return 0, false + } + v, err := strconv.ParseInt(node.Value, 10, 64) + if err != nil { + return 0, false + } + return v, true +} + +// FloatForScalarNode returns the float value of a node. +func FloatForScalarNode(node *yaml.Node) (float64, bool) { + if node == nil { + return 0.0, false + } + if node.Kind == yaml.DocumentNode { + return FloatForScalarNode(node.Content[0]) + } + if node.Kind != yaml.ScalarNode { + return 0.0, false + } + if (node.Tag != "!!int") && (node.Tag != "!!float") { + return 0.0, false + } + v, err := strconv.ParseFloat(node.Value, 64) + if err != nil { + return 0.0, false + } + return v, true +} + +// StringForScalarNode returns the string value of a node. +func StringForScalarNode(node *yaml.Node) (string, bool) { + if node == nil { + return "", false + } + if node.Kind == yaml.DocumentNode { + return StringForScalarNode(node.Content[0]) + } + switch node.Kind { + case yaml.ScalarNode: + switch node.Tag { + case "!!int": + return node.Value, true + case "!!str": + return node.Value, true + case "!!timestamp": + return node.Value, true + case "!!null": + return "", true + default: + return "", false + } + default: + return "", false + } +} + +// StringArrayForSequenceNode converts a sequence node to an array of strings, if possible. +func StringArrayForSequenceNode(node *yaml.Node) []string { + stringArray := make([]string, 0) + for _, item := range node.Content { + v, ok := StringForScalarNode(item) + if ok { + stringArray = append(stringArray, v) + } + } + return stringArray +} + +// MissingKeysInMap identifies which keys from a list of required keys are not in a map. +func MissingKeysInMap(m *yaml.Node, requiredKeys []string) []string { + missingKeys := make([]string, 0) + for _, k := range requiredKeys { + if !MapHasKey(m, k) { + missingKeys = append(missingKeys, k) + } + } + return missingKeys +} + +// InvalidKeysInMap returns keys in a map that don't match a list of allowed keys and patterns. +func InvalidKeysInMap(m *yaml.Node, allowedKeys []string, allowedPatterns []*regexp.Regexp) []string { + invalidKeys := make([]string, 0) + if m == nil || m.Kind != yaml.MappingNode { + return invalidKeys + } + for i := 0; i < len(m.Content); i += 2 { + key := m.Content[i].Value + found := false + // does the key match an allowed key? + for _, allowedKey := range allowedKeys { + if key == allowedKey { + found = true + break + } + } + if !found { + // does the key match an allowed pattern? + for _, allowedPattern := range allowedPatterns { + if allowedPattern.MatchString(key) { + found = true + break + } + } + if !found { + invalidKeys = append(invalidKeys, key) + } + } + } + return invalidKeys +} + +// NewNullNode creates a new Null node. +func NewNullNode() *yaml.Node { + node := &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!null", + } + return node +} + +// NewMappingNode creates a new Mapping node. +func NewMappingNode() *yaml.Node { + return &yaml.Node{ + Kind: yaml.MappingNode, + Content: make([]*yaml.Node, 0), + } +} + +// NewSequenceNode creates a new Sequence node. +func NewSequenceNode() *yaml.Node { + node := &yaml.Node{ + Kind: yaml.SequenceNode, + Content: make([]*yaml.Node, 0), + } + return node +} + +// NewScalarNodeForString creates a new node to hold a string. +func NewScalarNodeForString(s string) *yaml.Node { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!str", + Value: s, + } +} + +// NewSequenceNodeForStringArray creates a new node to hold an array of strings. +func NewSequenceNodeForStringArray(strings []string) *yaml.Node { + node := &yaml.Node{ + Kind: yaml.SequenceNode, + Content: make([]*yaml.Node, 0), + } + for _, s := range strings { + node.Content = append(node.Content, NewScalarNodeForString(s)) + } + return node +} + +// NewScalarNodeForBool creates a new node to hold a bool. +func NewScalarNodeForBool(b bool) *yaml.Node { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!bool", + Value: fmt.Sprintf("%t", b), + } +} + +// NewScalarNodeForFloat creates a new node to hold a float. +func NewScalarNodeForFloat(f float64) *yaml.Node { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!float", + Value: fmt.Sprintf("%g", f), + } +} + +// NewScalarNodeForInt creates a new node to hold an integer. +func NewScalarNodeForInt(i int64) *yaml.Node { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!int", + Value: fmt.Sprintf("%d", i), + } +} + +// PluralProperties returns the string "properties" pluralized. +func PluralProperties(count int) string { + if count == 1 { + return "property" + } + return "properties" +} + +// StringArrayContainsValue returns true if a string array contains a specified value. +func StringArrayContainsValue(array []string, value string) bool { + for _, item := range array { + if item == value { + return true + } + } + return false +} + +// StringArrayContainsValues returns true if a string array contains all of a list of specified values. +func StringArrayContainsValues(array []string, values []string) bool { + for _, value := range values { + if !StringArrayContainsValue(array, value) { + return false + } + } + return true +} + +// StringValue returns the string value of an item. +func StringValue(item interface{}) (value string, ok bool) { + value, ok = item.(string) + if ok { + return value, ok + } + intValue, ok := item.(int) + if ok { + return strconv.Itoa(intValue), true + } + return "", false +} + +// Description returns a human-readable represention of an item. +func Description(item interface{}) string { + value, ok := item.(*yaml.Node) + if ok { + return jsonschema.Render(value) + } + return fmt.Sprintf("%+v", item) +} + +// Display returns a description of a node for use in error messages. +func Display(node *yaml.Node) string { + switch node.Kind { + case yaml.ScalarNode: + switch node.Tag { + case "!!str": + return fmt.Sprintf("%s (string)", node.Value) + } + } + return fmt.Sprintf("%+v (%T)", node, node) +} + +// Marshal creates a yaml version of a structure in our preferred style +func Marshal(in *yaml.Node) []byte { + clearStyle(in) + //bytes, _ := yaml.Marshal(&yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{in}}) + bytes, _ := yaml.Marshal(in) + + return bytes +} + +func clearStyle(node *yaml.Node) { + node.Style = 0 + for _, c := range node.Content { + clearStyle(c) + } +} diff --git a/vendor/github.com/google/gnostic/compiler/main.go b/vendor/github.com/google/gnostic-models/compiler/main.go similarity index 100% rename from vendor/github.com/google/gnostic/compiler/main.go rename to vendor/github.com/google/gnostic-models/compiler/main.go diff --git a/vendor/github.com/google/gnostic/compiler/reader.go b/vendor/github.com/google/gnostic-models/compiler/reader.go similarity index 100% rename from vendor/github.com/google/gnostic/compiler/reader.go rename to vendor/github.com/google/gnostic-models/compiler/reader.go diff --git a/vendor/github.com/google/gnostic/extensions/README.md b/vendor/github.com/google/gnostic-models/extensions/README.md similarity index 100% rename from vendor/github.com/google/gnostic/extensions/README.md rename to vendor/github.com/google/gnostic-models/extensions/README.md diff --git a/vendor/github.com/google/gnostic/extensions/extension.pb.go b/vendor/github.com/google/gnostic-models/extensions/extension.pb.go similarity index 99% rename from vendor/github.com/google/gnostic/extensions/extension.pb.go rename to vendor/github.com/google/gnostic-models/extensions/extension.pb.go index a6a4ccca6..a71df8abe 100644 --- a/vendor/github.com/google/gnostic/extensions/extension.pb.go +++ b/vendor/github.com/google/gnostic-models/extensions/extension.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.18.1 +// protoc-gen-go v1.27.1 +// protoc v3.19.3 // source: extensions/extension.proto package gnostic_extension_v1 diff --git a/vendor/github.com/google/gnostic/extensions/extension.proto b/vendor/github.com/google/gnostic-models/extensions/extension.proto similarity index 100% rename from vendor/github.com/google/gnostic/extensions/extension.proto rename to vendor/github.com/google/gnostic-models/extensions/extension.proto diff --git a/vendor/github.com/google/gnostic/extensions/extensions.go b/vendor/github.com/google/gnostic-models/extensions/extensions.go similarity index 100% rename from vendor/github.com/google/gnostic/extensions/extensions.go rename to vendor/github.com/google/gnostic-models/extensions/extensions.go diff --git a/vendor/github.com/google/gnostic/jsonschema/README.md b/vendor/github.com/google/gnostic-models/jsonschema/README.md similarity index 100% rename from vendor/github.com/google/gnostic/jsonschema/README.md rename to vendor/github.com/google/gnostic-models/jsonschema/README.md diff --git a/vendor/github.com/google/gnostic-models/jsonschema/base.go b/vendor/github.com/google/gnostic-models/jsonschema/base.go new file mode 100644 index 000000000..5fcc4885a --- /dev/null +++ b/vendor/github.com/google/gnostic-models/jsonschema/base.go @@ -0,0 +1,97 @@ +// Copyright 2017 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// THIS FILE IS AUTOMATICALLY GENERATED. + +package jsonschema + +import ( + "encoding/base64" +) + +func baseSchemaBytes() ([]byte, error){ + return base64.StdEncoding.DecodeString( +`ewogICAgImlkIjogImh0dHA6Ly9qc29uLXNjaGVtYS5vcmcvZHJhZnQtMDQvc2NoZW1hIyIsCiAgICAi +JHNjaGVtYSI6ICJodHRwOi8vanNvbi1zY2hlbWEub3JnL2RyYWZ0LTA0L3NjaGVtYSMiLAogICAgImRl +c2NyaXB0aW9uIjogIkNvcmUgc2NoZW1hIG1ldGEtc2NoZW1hIiwKICAgICJkZWZpbml0aW9ucyI6IHsK +ICAgICAgICAic2NoZW1hQXJyYXkiOiB7CiAgICAgICAgICAgICJ0eXBlIjogImFycmF5IiwKICAgICAg +ICAgICAgIm1pbkl0ZW1zIjogMSwKICAgICAgICAgICAgIml0ZW1zIjogeyAiJHJlZiI6ICIjIiB9CiAg +ICAgICAgfSwKICAgICAgICAicG9zaXRpdmVJbnRlZ2VyIjogewogICAgICAgICAgICAidHlwZSI6ICJp +bnRlZ2VyIiwKICAgICAgICAgICAgIm1pbmltdW0iOiAwCiAgICAgICAgfSwKICAgICAgICAicG9zaXRp +dmVJbnRlZ2VyRGVmYXVsdDAiOiB7CiAgICAgICAgICAgICJhbGxPZiI6IFsgeyAiJHJlZiI6ICIjL2Rl +ZmluaXRpb25zL3Bvc2l0aXZlSW50ZWdlciIgfSwgeyAiZGVmYXVsdCI6IDAgfSBdCiAgICAgICAgfSwK +ICAgICAgICAic2ltcGxlVHlwZXMiOiB7CiAgICAgICAgICAgICJlbnVtIjogWyAiYXJyYXkiLCAiYm9v +bGVhbiIsICJpbnRlZ2VyIiwgIm51bGwiLCAibnVtYmVyIiwgIm9iamVjdCIsICJzdHJpbmciIF0KICAg +ICAgICB9LAogICAgICAgICJzdHJpbmdBcnJheSI6IHsKICAgICAgICAgICAgInR5cGUiOiAiYXJyYXki +LAogICAgICAgICAgICAiaXRlbXMiOiB7ICJ0eXBlIjogInN0cmluZyIgfSwKICAgICAgICAgICAgIm1p +bkl0ZW1zIjogMSwKICAgICAgICAgICAgInVuaXF1ZUl0ZW1zIjogdHJ1ZQogICAgICAgIH0KICAgIH0s +CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICAgImlkIjogewog +ICAgICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICAgICAiZm9ybWF0IjogInVyaSIKICAg +ICAgICB9LAogICAgICAgICIkc2NoZW1hIjogewogICAgICAgICAgICAidHlwZSI6ICJzdHJpbmciLAog +ICAgICAgICAgICAiZm9ybWF0IjogInVyaSIKICAgICAgICB9LAogICAgICAgICJ0aXRsZSI6IHsKICAg +ICAgICAgICAgInR5cGUiOiAic3RyaW5nIgogICAgICAgIH0sCiAgICAgICAgImRlc2NyaXB0aW9uIjog +ewogICAgICAgICAgICAidHlwZSI6ICJzdHJpbmciCiAgICAgICAgfSwKICAgICAgICAiZGVmYXVsdCI6 +IHt9LAogICAgICAgICJtdWx0aXBsZU9mIjogewogICAgICAgICAgICAidHlwZSI6ICJudW1iZXIiLAog +ICAgICAgICAgICAibWluaW11bSI6IDAsCiAgICAgICAgICAgICJleGNsdXNpdmVNaW5pbXVtIjogdHJ1 +ZQogICAgICAgIH0sCiAgICAgICAgIm1heGltdW0iOiB7CiAgICAgICAgICAgICJ0eXBlIjogIm51bWJl +ciIKICAgICAgICB9LAogICAgICAgICJleGNsdXNpdmVNYXhpbXVtIjogewogICAgICAgICAgICAidHlw +ZSI6ICJib29sZWFuIiwKICAgICAgICAgICAgImRlZmF1bHQiOiBmYWxzZQogICAgICAgIH0sCiAgICAg +ICAgIm1pbmltdW0iOiB7CiAgICAgICAgICAgICJ0eXBlIjogIm51bWJlciIKICAgICAgICB9LAogICAg +ICAgICJleGNsdXNpdmVNaW5pbXVtIjogewogICAgICAgICAgICAidHlwZSI6ICJib29sZWFuIiwKICAg +ICAgICAgICAgImRlZmF1bHQiOiBmYWxzZQogICAgICAgIH0sCiAgICAgICAgIm1heExlbmd0aCI6IHsg +IiRyZWYiOiAiIy9kZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXIiIH0sCiAgICAgICAgIm1pbkxlbmd0 +aCI6IHsgIiRyZWYiOiAiIy9kZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXJEZWZhdWx0MCIgfSwKICAg +ICAgICAicGF0dGVybiI6IHsKICAgICAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAgICAg +ImZvcm1hdCI6ICJyZWdleCIKICAgICAgICB9LAogICAgICAgICJhZGRpdGlvbmFsSXRlbXMiOiB7CiAg +ICAgICAgICAgICJhbnlPZiI6IFsKICAgICAgICAgICAgICAgIHsgInR5cGUiOiAiYm9vbGVhbiIgfSwK +ICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIyIgfQogICAgICAgICAgICBdLAogICAgICAgICAgICAi +ZGVmYXVsdCI6IHt9CiAgICAgICAgfSwKICAgICAgICAiaXRlbXMiOiB7CiAgICAgICAgICAgICJhbnlP +ZiI6IFsKICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIyIgfSwKICAgICAgICAgICAgICAgIHsgIiRy +ZWYiOiAiIy9kZWZpbml0aW9ucy9zY2hlbWFBcnJheSIgfQogICAgICAgICAgICBdLAogICAgICAgICAg +ICAiZGVmYXVsdCI6IHt9CiAgICAgICAgfSwKICAgICAgICAibWF4SXRlbXMiOiB7ICIkcmVmIjogIiMv +ZGVmaW5pdGlvbnMvcG9zaXRpdmVJbnRlZ2VyIiB9LAogICAgICAgICJtaW5JdGVtcyI6IHsgIiRyZWYi +OiAiIy9kZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXJEZWZhdWx0MCIgfSwKICAgICAgICAidW5pcXVl +SXRlbXMiOiB7CiAgICAgICAgICAgICJ0eXBlIjogImJvb2xlYW4iLAogICAgICAgICAgICAiZGVmYXVs +dCI6IGZhbHNlCiAgICAgICAgfSwKICAgICAgICAibWF4UHJvcGVydGllcyI6IHsgIiRyZWYiOiAiIy9k +ZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXIiIH0sCiAgICAgICAgIm1pblByb3BlcnRpZXMiOiB7ICIk +cmVmIjogIiMvZGVmaW5pdGlvbnMvcG9zaXRpdmVJbnRlZ2VyRGVmYXVsdDAiIH0sCiAgICAgICAgInJl +cXVpcmVkIjogeyAiJHJlZiI6ICIjL2RlZmluaXRpb25zL3N0cmluZ0FycmF5IiB9LAogICAgICAgICJh +ZGRpdGlvbmFsUHJvcGVydGllcyI6IHsKICAgICAgICAgICAgImFueU9mIjogWwogICAgICAgICAgICAg +ICAgeyAidHlwZSI6ICJib29sZWFuIiB9LAogICAgICAgICAgICAgICAgeyAiJHJlZiI6ICIjIiB9CiAg +ICAgICAgICAgIF0sCiAgICAgICAgICAgICJkZWZhdWx0Ijoge30KICAgICAgICB9LAogICAgICAgICJk +ZWZpbml0aW9ucyI6IHsKICAgICAgICAgICAgInR5cGUiOiAib2JqZWN0IiwKICAgICAgICAgICAgImFk +ZGl0aW9uYWxQcm9wZXJ0aWVzIjogeyAiJHJlZiI6ICIjIiB9LAogICAgICAgICAgICAiZGVmYXVsdCI6 +IHt9CiAgICAgICAgfSwKICAgICAgICAicHJvcGVydGllcyI6IHsKICAgICAgICAgICAgInR5cGUiOiAi +b2JqZWN0IiwKICAgICAgICAgICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogeyAiJHJlZiI6ICIjIiB9 +LAogICAgICAgICAgICAiZGVmYXVsdCI6IHt9CiAgICAgICAgfSwKICAgICAgICAicGF0dGVyblByb3Bl +cnRpZXMiOiB7CiAgICAgICAgICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAgICAgICAgICJhZGRpdGlv +bmFsUHJvcGVydGllcyI6IHsgIiRyZWYiOiAiIyIgfSwKICAgICAgICAgICAgImRlZmF1bHQiOiB7fQog +ICAgICAgIH0sCiAgICAgICAgImRlcGVuZGVuY2llcyI6IHsKICAgICAgICAgICAgInR5cGUiOiAib2Jq +ZWN0IiwKICAgICAgICAgICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogewogICAgICAgICAgICAgICAg +ImFueU9mIjogWwogICAgICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIyIgfSwKICAgICAgICAgICAg +ICAgICAgICB7ICIkcmVmIjogIiMvZGVmaW5pdGlvbnMvc3RyaW5nQXJyYXkiIH0KICAgICAgICAgICAg +ICAgIF0KICAgICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICAgImVudW0iOiB7CiAgICAgICAgICAg +ICJ0eXBlIjogImFycmF5IiwKICAgICAgICAgICAgIm1pbkl0ZW1zIjogMSwKICAgICAgICAgICAgInVu +aXF1ZUl0ZW1zIjogdHJ1ZQogICAgICAgIH0sCiAgICAgICAgInR5cGUiOiB7CiAgICAgICAgICAgICJh +bnlPZiI6IFsKICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIy9kZWZpbml0aW9ucy9zaW1wbGVUeXBl +cyIgfSwKICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgICAidHlwZSI6ICJhcnJheSIs +CiAgICAgICAgICAgICAgICAgICAgIml0ZW1zIjogeyAiJHJlZiI6ICIjL2RlZmluaXRpb25zL3NpbXBs +ZVR5cGVzIiB9LAogICAgICAgICAgICAgICAgICAgICJtaW5JdGVtcyI6IDEsCiAgICAgICAgICAgICAg +ICAgICAgInVuaXF1ZUl0ZW1zIjogdHJ1ZQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICBdCiAg +ICAgICAgfSwKICAgICAgICAiYWxsT2YiOiB7ICIkcmVmIjogIiMvZGVmaW5pdGlvbnMvc2NoZW1hQXJy +YXkiIH0sCiAgICAgICAgImFueU9mIjogeyAiJHJlZiI6ICIjL2RlZmluaXRpb25zL3NjaGVtYUFycmF5 +IiB9LAogICAgICAgICJvbmVPZiI6IHsgIiRyZWYiOiAiIy9kZWZpbml0aW9ucy9zY2hlbWFBcnJheSIg +fSwKICAgICAgICAibm90IjogeyAiJHJlZiI6ICIjIiB9CiAgICB9LAogICAgImRlcGVuZGVuY2llcyI6 +IHsKICAgICAgICAiZXhjbHVzaXZlTWF4aW11bSI6IFsgIm1heGltdW0iIF0sCiAgICAgICAgImV4Y2x1 +c2l2ZU1pbmltdW0iOiBbICJtaW5pbXVtIiBdCiAgICB9LAogICAgImRlZmF1bHQiOiB7fQp9Cg==`)} diff --git a/vendor/github.com/google/gnostic/jsonschema/display.go b/vendor/github.com/google/gnostic-models/jsonschema/display.go similarity index 92% rename from vendor/github.com/google/gnostic/jsonschema/display.go rename to vendor/github.com/google/gnostic-models/jsonschema/display.go index 8677ed49a..028a760a9 100644 --- a/vendor/github.com/google/gnostic/jsonschema/display.go +++ b/vendor/github.com/google/gnostic-models/jsonschema/display.go @@ -46,23 +46,8 @@ func (schema *Schema) describeSchema(indent string) string { if schema.Schema != nil { result += indent + "$schema: " + *(schema.Schema) + "\n" } - if schema.ReadOnly != nil && *schema.ReadOnly { - result += indent + fmt.Sprintf("readOnly: %+v\n", *(schema.ReadOnly)) - } - if schema.WriteOnly != nil && *schema.WriteOnly { - result += indent + fmt.Sprintf("writeOnly: %+v\n", *(schema.WriteOnly)) - } if schema.ID != nil { - switch strings.TrimSuffix(*schema.Schema, "#") { - case "http://json-schema.org/draft-04/schema#": - fallthrough - case "#": - fallthrough - case "": - result += indent + "id: " + *(schema.ID) + "\n" - default: - result += indent + "$id: " + *(schema.ID) + "\n" - } + result += indent + "id: " + *(schema.ID) + "\n" } if schema.MultipleOf != nil { result += indent + fmt.Sprintf("multipleOf: %+v\n", *(schema.MultipleOf)) diff --git a/vendor/github.com/google/gnostic-models/jsonschema/models.go b/vendor/github.com/google/gnostic-models/jsonschema/models.go new file mode 100644 index 000000000..4781bdc5f --- /dev/null +++ b/vendor/github.com/google/gnostic-models/jsonschema/models.go @@ -0,0 +1,228 @@ +// Copyright 2017 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package jsonschema supports the reading, writing, and manipulation +// of JSON Schemas. +package jsonschema + +import "gopkg.in/yaml.v3" + +// The Schema struct models a JSON Schema and, because schemas are +// defined hierarchically, contains many references to itself. +// All fields are pointers and are nil if the associated values +// are not specified. +type Schema struct { + Schema *string // $schema + ID *string // id keyword used for $ref resolution scope + Ref *string // $ref, i.e. JSON Pointers + + // http://json-schema.org/latest/json-schema-validation.html + // 5.1. Validation keywords for numeric instances (number and integer) + MultipleOf *SchemaNumber + Maximum *SchemaNumber + ExclusiveMaximum *bool + Minimum *SchemaNumber + ExclusiveMinimum *bool + + // 5.2. Validation keywords for strings + MaxLength *int64 + MinLength *int64 + Pattern *string + + // 5.3. Validation keywords for arrays + AdditionalItems *SchemaOrBoolean + Items *SchemaOrSchemaArray + MaxItems *int64 + MinItems *int64 + UniqueItems *bool + + // 5.4. Validation keywords for objects + MaxProperties *int64 + MinProperties *int64 + Required *[]string + AdditionalProperties *SchemaOrBoolean + Properties *[]*NamedSchema + PatternProperties *[]*NamedSchema + Dependencies *[]*NamedSchemaOrStringArray + + // 5.5. Validation keywords for any instance type + Enumeration *[]SchemaEnumValue + Type *StringOrStringArray + AllOf *[]*Schema + AnyOf *[]*Schema + OneOf *[]*Schema + Not *Schema + Definitions *[]*NamedSchema + + // 6. Metadata keywords + Title *string + Description *string + Default *yaml.Node + + // 7. Semantic validation with "format" + Format *string +} + +// These helper structs represent "combination" types that generally can +// have values of one type or another. All are used to represent parts +// of Schemas. + +// SchemaNumber represents a value that can be either an Integer or a Float. +type SchemaNumber struct { + Integer *int64 + Float *float64 +} + +// NewSchemaNumberWithInteger creates and returns a new object +func NewSchemaNumberWithInteger(i int64) *SchemaNumber { + result := &SchemaNumber{} + result.Integer = &i + return result +} + +// NewSchemaNumberWithFloat creates and returns a new object +func NewSchemaNumberWithFloat(f float64) *SchemaNumber { + result := &SchemaNumber{} + result.Float = &f + return result +} + +// SchemaOrBoolean represents a value that can be either a Schema or a Boolean. +type SchemaOrBoolean struct { + Schema *Schema + Boolean *bool +} + +// NewSchemaOrBooleanWithSchema creates and returns a new object +func NewSchemaOrBooleanWithSchema(s *Schema) *SchemaOrBoolean { + result := &SchemaOrBoolean{} + result.Schema = s + return result +} + +// NewSchemaOrBooleanWithBoolean creates and returns a new object +func NewSchemaOrBooleanWithBoolean(b bool) *SchemaOrBoolean { + result := &SchemaOrBoolean{} + result.Boolean = &b + return result +} + +// StringOrStringArray represents a value that can be either +// a String or an Array of Strings. +type StringOrStringArray struct { + String *string + StringArray *[]string +} + +// NewStringOrStringArrayWithString creates and returns a new object +func NewStringOrStringArrayWithString(s string) *StringOrStringArray { + result := &StringOrStringArray{} + result.String = &s + return result +} + +// NewStringOrStringArrayWithStringArray creates and returns a new object +func NewStringOrStringArrayWithStringArray(a []string) *StringOrStringArray { + result := &StringOrStringArray{} + result.StringArray = &a + return result +} + +// SchemaOrStringArray represents a value that can be either +// a Schema or an Array of Strings. +type SchemaOrStringArray struct { + Schema *Schema + StringArray *[]string +} + +// SchemaOrSchemaArray represents a value that can be either +// a Schema or an Array of Schemas. +type SchemaOrSchemaArray struct { + Schema *Schema + SchemaArray *[]*Schema +} + +// NewSchemaOrSchemaArrayWithSchema creates and returns a new object +func NewSchemaOrSchemaArrayWithSchema(s *Schema) *SchemaOrSchemaArray { + result := &SchemaOrSchemaArray{} + result.Schema = s + return result +} + +// NewSchemaOrSchemaArrayWithSchemaArray creates and returns a new object +func NewSchemaOrSchemaArrayWithSchemaArray(a []*Schema) *SchemaOrSchemaArray { + result := &SchemaOrSchemaArray{} + result.SchemaArray = &a + return result +} + +// SchemaEnumValue represents a value that can be part of an +// enumeration in a Schema. +type SchemaEnumValue struct { + String *string + Bool *bool +} + +// NamedSchema is a name-value pair that is used to emulate maps +// with ordered keys. +type NamedSchema struct { + Name string + Value *Schema +} + +// NewNamedSchema creates and returns a new object +func NewNamedSchema(name string, value *Schema) *NamedSchema { + return &NamedSchema{Name: name, Value: value} +} + +// NamedSchemaOrStringArray is a name-value pair that is used +// to emulate maps with ordered keys. +type NamedSchemaOrStringArray struct { + Name string + Value *SchemaOrStringArray +} + +// Access named subschemas by name + +func namedSchemaArrayElementWithName(array *[]*NamedSchema, name string) *Schema { + if array == nil { + return nil + } + for _, pair := range *array { + if pair.Name == name { + return pair.Value + } + } + return nil +} + +// PropertyWithName returns the selected element. +func (s *Schema) PropertyWithName(name string) *Schema { + return namedSchemaArrayElementWithName(s.Properties, name) +} + +// PatternPropertyWithName returns the selected element. +func (s *Schema) PatternPropertyWithName(name string) *Schema { + return namedSchemaArrayElementWithName(s.PatternProperties, name) +} + +// DefinitionWithName returns the selected element. +func (s *Schema) DefinitionWithName(name string) *Schema { + return namedSchemaArrayElementWithName(s.Definitions, name) +} + +// AddProperty adds a named property. +func (s *Schema) AddProperty(name string, property *Schema) { + *s.Properties = append(*s.Properties, NewNamedSchema(name, property)) +} diff --git a/vendor/github.com/google/gnostic/jsonschema/operations.go b/vendor/github.com/google/gnostic-models/jsonschema/operations.go similarity index 100% rename from vendor/github.com/google/gnostic/jsonschema/operations.go rename to vendor/github.com/google/gnostic-models/jsonschema/operations.go diff --git a/vendor/github.com/google/gnostic/jsonschema/reader.go b/vendor/github.com/google/gnostic-models/jsonschema/reader.go similarity index 99% rename from vendor/github.com/google/gnostic/jsonschema/reader.go rename to vendor/github.com/google/gnostic-models/jsonschema/reader.go index a909a3412..b8583d466 100644 --- a/vendor/github.com/google/gnostic/jsonschema/reader.go +++ b/vendor/github.com/google/gnostic-models/jsonschema/reader.go @@ -165,6 +165,7 @@ func NewSchemaFromObject(jsonData *yaml.Node) *Schema { default: fmt.Printf("schemaValue: unexpected node %+v\n", jsonData) + return nil } return nil diff --git a/vendor/github.com/google/gnostic/jsonschema/schema.json b/vendor/github.com/google/gnostic-models/jsonschema/schema.json similarity index 100% rename from vendor/github.com/google/gnostic/jsonschema/schema.json rename to vendor/github.com/google/gnostic-models/jsonschema/schema.json diff --git a/vendor/github.com/google/gnostic/jsonschema/writer.go b/vendor/github.com/google/gnostic-models/jsonschema/writer.go similarity index 92% rename from vendor/github.com/google/gnostic/jsonschema/writer.go rename to vendor/github.com/google/gnostic-models/jsonschema/writer.go index 15b1f9050..340dc5f93 100644 --- a/vendor/github.com/google/gnostic/jsonschema/writer.go +++ b/vendor/github.com/google/gnostic-models/jsonschema/writer.go @@ -16,7 +16,6 @@ package jsonschema import ( "fmt" - "strings" "gopkg.in/yaml.v3" ) @@ -34,11 +33,7 @@ func renderMappingNode(node *yaml.Node, indent string) (result string) { value := node.Content[i+1] switch value.Kind { case yaml.ScalarNode: - if value.Tag == "!!bool" { - result += value.Value - } else { - result += "\"" + value.Value + "\"" - } + result += "\"" + value.Value + "\"" case yaml.MappingNode: result += renderMappingNode(value, innerIndent) case yaml.SequenceNode: @@ -63,11 +58,7 @@ func renderSequenceNode(node *yaml.Node, indent string) (result string) { item := node.Content[i] switch item.Kind { case yaml.ScalarNode: - if item.Tag == "!!bool" { - result += innerIndent + item.Value - } else { - result += innerIndent + "\"" + item.Value + "\"" - } + result += innerIndent + "\"" + item.Value + "\"" case yaml.MappingNode: result += innerIndent + renderMappingNode(item, innerIndent) + "" default: @@ -269,26 +260,11 @@ func (schema *Schema) nodeValue() *yaml.Node { content = appendPair(content, "title", nodeForString(*schema.Title)) } if schema.ID != nil { - switch strings.TrimSuffix(*schema.Schema, "#") { - case "http://json-schema.org/draft-04/schema": - fallthrough - case "#": - fallthrough - case "": - content = appendPair(content, "id", nodeForString(*schema.ID)) - default: - content = appendPair(content, "$id", nodeForString(*schema.ID)) - } + content = appendPair(content, "id", nodeForString(*schema.ID)) } if schema.Schema != nil { content = appendPair(content, "$schema", nodeForString(*schema.Schema)) } - if schema.ReadOnly != nil && *schema.ReadOnly { - content = appendPair(content, "readOnly", nodeForBoolean(*schema.ReadOnly)) - } - if schema.WriteOnly != nil && *schema.WriteOnly { - content = appendPair(content, "writeOnly", nodeForBoolean(*schema.WriteOnly)) - } if schema.Type != nil { content = appendPair(content, "type", schema.Type.nodeValue()) } diff --git a/vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.go b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.go similarity index 99% rename from vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.go rename to vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.go index 28c2777d5..d71fe6d54 100644 --- a/vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.go +++ b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.go @@ -23,7 +23,7 @@ import ( "gopkg.in/yaml.v3" - "github.com/google/gnostic/compiler" + "github.com/google/gnostic-models/compiler" ) // Version returns the package name (and OpenAPI version). @@ -7887,12 +7887,7 @@ func (m *Oauth2Scopes) ToRawInfo() *yaml.Node { if m == nil { return info } - if m.AdditionalProperties != nil { - for _, item := range m.AdditionalProperties { - info.Content = append(info.Content, compiler.NewScalarNodeForString(item.Name)) - info.Content = append(info.Content, compiler.NewScalarNodeForString(item.Value)) - } - } + // &{Name:additionalProperties Type:NamedString StringEnumValues:[] MapType:string Repeated:true Pattern: Implicit:true Description:} return info } diff --git a/vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.pb.go b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.pb.go similarity index 99% rename from vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.pb.go rename to vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.pb.go index 06b60157c..65c4c913c 100644 --- a/vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.pb.go +++ b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.pb.go @@ -16,8 +16,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.18.1 +// protoc-gen-go v1.27.1 +// protoc v3.19.3 // source: openapiv2/OpenAPIv2.proto package openapi_v2 diff --git a/vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.proto b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto similarity index 100% rename from vendor/github.com/google/gnostic/openapiv2/OpenAPIv2.proto rename to vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto diff --git a/vendor/github.com/google/gnostic/openapiv2/README.md b/vendor/github.com/google/gnostic-models/openapiv2/README.md similarity index 100% rename from vendor/github.com/google/gnostic/openapiv2/README.md rename to vendor/github.com/google/gnostic-models/openapiv2/README.md diff --git a/vendor/github.com/google/gnostic-models/openapiv2/document.go b/vendor/github.com/google/gnostic-models/openapiv2/document.go new file mode 100644 index 000000000..e96ac0d6d --- /dev/null +++ b/vendor/github.com/google/gnostic-models/openapiv2/document.go @@ -0,0 +1,42 @@ +// Copyright 2020 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openapi_v2 + +import ( + "gopkg.in/yaml.v3" + + "github.com/google/gnostic-models/compiler" +) + +// ParseDocument reads an OpenAPI v2 description from a YAML/JSON representation. +func ParseDocument(b []byte) (*Document, error) { + info, err := compiler.ReadInfoFromBytes("", b) + if err != nil { + return nil, err + } + root := info.Content[0] + return NewDocument(root, compiler.NewContextWithExtensions("$root", root, nil, nil)) +} + +// YAMLValue produces a serialized YAML representation of the document. +func (d *Document) YAMLValue(comment string) ([]byte, error) { + rawInfo := d.ToRawInfo() + rawInfo = &yaml.Node{ + Kind: yaml.DocumentNode, + Content: []*yaml.Node{rawInfo}, + HeadComment: comment, + } + return yaml.Marshal(rawInfo) +} diff --git a/vendor/github.com/google/gnostic/openapiv2/openapi-2.0.json b/vendor/github.com/google/gnostic-models/openapiv2/openapi-2.0.json similarity index 100% rename from vendor/github.com/google/gnostic/openapiv2/openapi-2.0.json rename to vendor/github.com/google/gnostic-models/openapiv2/openapi-2.0.json diff --git a/vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.go b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go similarity index 99% rename from vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.go rename to vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go index d54a84db7..4b1131ce1 100644 --- a/vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.go +++ b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go @@ -23,7 +23,7 @@ import ( "gopkg.in/yaml.v3" - "github.com/google/gnostic/compiler" + "github.com/google/gnostic-models/compiler" ) // Version returns the package name (and OpenAPI version). @@ -8560,12 +8560,7 @@ func (m *Strings) ToRawInfo() *yaml.Node { if m == nil { return info } - if m.AdditionalProperties != nil { - for _, item := range m.AdditionalProperties { - info.Content = append(info.Content, compiler.NewScalarNodeForString(item.Name)) - info.Content = append(info.Content, compiler.NewScalarNodeForString(item.Value)) - } - } + // &{Name:additionalProperties Type:NamedString StringEnumValues:[] MapType:string Repeated:true Pattern: Implicit:true Description:} return info } diff --git a/vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.pb.go b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.pb.go similarity index 99% rename from vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.pb.go rename to vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.pb.go index 90a56f552..945b8d11f 100644 --- a/vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.pb.go +++ b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.pb.go @@ -16,8 +16,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.0 -// protoc v3.19.4 +// protoc-gen-go v1.27.1 +// protoc v3.19.3 // source: openapiv3/OpenAPIv3.proto package openapi_v3 @@ -6760,13 +6760,12 @@ var file_openapiv3_OpenAPIv3_proto_rawDesc = []byte{ 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x33, 0x2e, 0x4e, 0x61, 0x6d, 0x65, 0x64, 0x41, 0x6e, 0x79, 0x52, 0x16, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x56, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x3e, 0x0a, 0x0e, 0x6f, 0x72, 0x67, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x5f, 0x76, 0x33, 0x42, 0x0c, 0x4f, 0x70, 0x65, 0x6e, 0x41, 0x50, 0x49, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x2e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2f, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x2f, 0x6f, 0x70, 0x65, 0x6e, - 0x61, 0x70, 0x69, 0x76, 0x33, 0x3b, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x5f, 0x76, 0x33, - 0xa2, 0x02, 0x03, 0x4f, 0x41, 0x53, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x5a, 0x16, 0x2e, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x76, 0x33, 0x3b, 0x6f, 0x70, + 0x65, 0x6e, 0x61, 0x70, 0x69, 0x5f, 0x76, 0x33, 0xa2, 0x02, 0x03, 0x4f, 0x41, 0x53, 0x62, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.proto b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto similarity index 99% rename from vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.proto rename to vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto index 7aede5ed9..1be335b89 100644 --- a/vendor/github.com/google/gnostic/openapiv3/OpenAPIv3.proto +++ b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto @@ -42,7 +42,7 @@ option java_package = "org.openapi_v3"; option objc_class_prefix = "OAS"; // The Go package name. -option go_package = "github.com/google/gnostic/openapiv3;openapi_v3"; +option go_package = "./openapiv3;openapi_v3"; message AdditionalPropertiesItem { oneof oneof { diff --git a/vendor/github.com/google/gnostic-models/openapiv3/README.md b/vendor/github.com/google/gnostic-models/openapiv3/README.md new file mode 100644 index 000000000..5ee12d92e --- /dev/null +++ b/vendor/github.com/google/gnostic-models/openapiv3/README.md @@ -0,0 +1,21 @@ +# OpenAPI v3 Protocol Buffer Models + +This directory contains a Protocol Buffer-language model and related code for +supporting OpenAPI v3. + +Gnostic applications and plugins can use OpenAPIv3.proto to generate Protocol +Buffer support code for their preferred languages. + +OpenAPIv3.go is used by Gnostic to read JSON and YAML OpenAPI descriptions into +the Protocol Buffer-based datastructures generated from OpenAPIv3.proto. + +OpenAPIv3.proto and OpenAPIv3.go are generated by the Gnostic compiler +generator, and OpenAPIv3.pb.go is generated by protoc, the Protocol Buffer +compiler, and protoc-gen-go, the Protocol Buffer Go code generation plugin. + +openapi-3.1.json is a JSON schema for OpenAPI 3.1 that is automatically +generated from the OpenAPI 3.1 specification. It is not an official JSON Schema +for OpenAPI. + +The schema-generator directory contains support code which generates +openapi-3.1.json from the OpenAPI 3.1 specification document (Markdown). diff --git a/vendor/github.com/google/gnostic-models/openapiv3/document.go b/vendor/github.com/google/gnostic-models/openapiv3/document.go new file mode 100644 index 000000000..1cee46773 --- /dev/null +++ b/vendor/github.com/google/gnostic-models/openapiv3/document.go @@ -0,0 +1,42 @@ +// Copyright 2020 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openapi_v3 + +import ( + "gopkg.in/yaml.v3" + + "github.com/google/gnostic-models/compiler" +) + +// ParseDocument reads an OpenAPI v3 description from a YAML/JSON representation. +func ParseDocument(b []byte) (*Document, error) { + info, err := compiler.ReadInfoFromBytes("", b) + if err != nil { + return nil, err + } + root := info.Content[0] + return NewDocument(root, compiler.NewContextWithExtensions("$root", root, nil, nil)) +} + +// YAMLValue produces a serialized YAML representation of the document. +func (d *Document) YAMLValue(comment string) ([]byte, error) { + rawInfo := d.ToRawInfo() + rawInfo = &yaml.Node{ + Kind: yaml.DocumentNode, + Content: []*yaml.Node{rawInfo}, + HeadComment: comment, + } + return yaml.Marshal(rawInfo) +} diff --git a/vendor/github.com/google/gnostic/compiler/helpers.go b/vendor/github.com/google/gnostic/compiler/helpers.go deleted file mode 100644 index 97ffaa513..000000000 --- a/vendor/github.com/google/gnostic/compiler/helpers.go +++ /dev/null @@ -1,397 +0,0 @@ -// Copyright 2017 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package compiler - -import ( - "fmt" - "regexp" - "sort" - "strconv" - - "gopkg.in/yaml.v3" - - "github.com/google/gnostic/jsonschema" -) - -// compiler helper functions, usually called from generated code - -// UnpackMap gets a *yaml.Node if possible. -func UnpackMap(in *yaml.Node) (*yaml.Node, bool) { - if in == nil { - return nil, false - } - return in, true -} - -// SortedKeysForMap returns the sorted keys of a yamlv2.MapSlice. -func SortedKeysForMap(m *yaml.Node) []string { - keys := make([]string, 0) - if m.Kind == yaml.MappingNode { - for i := 0; i < len(m.Content); i += 2 { - keys = append(keys, m.Content[i].Value) - } - } - sort.Strings(keys) - return keys -} - -// MapHasKey returns true if a yamlv2.MapSlice contains a specified key. -func MapHasKey(m *yaml.Node, key string) bool { - if m == nil { - return false - } - if m.Kind == yaml.MappingNode { - for i := 0; i < len(m.Content); i += 2 { - itemKey := m.Content[i].Value - if key == itemKey { - return true - } - } - } - return false -} - -// MapValueForKey gets the value of a map value for a specified key. -func MapValueForKey(m *yaml.Node, key string) *yaml.Node { - if m == nil { - return nil - } - if m.Kind == yaml.MappingNode { - for i := 0; i < len(m.Content); i += 2 { - itemKey := m.Content[i].Value - if key == itemKey { - return m.Content[i+1] - } - } - } - return nil -} - -// ConvertInterfaceArrayToStringArray converts an array of interfaces to an array of strings, if possible. -func ConvertInterfaceArrayToStringArray(interfaceArray []interface{}) []string { - stringArray := make([]string, 0) - for _, item := range interfaceArray { - v, ok := item.(string) - if ok { - stringArray = append(stringArray, v) - } - } - return stringArray -} - -// SequenceNodeForNode returns a node if it is a SequenceNode. -func SequenceNodeForNode(node *yaml.Node) (*yaml.Node, bool) { - if node.Kind != yaml.SequenceNode { - return nil, false - } - return node, true -} - -// BoolForScalarNode returns the bool value of a node. -func BoolForScalarNode(node *yaml.Node) (bool, bool) { - if node == nil { - return false, false - } - if node.Kind == yaml.DocumentNode { - return BoolForScalarNode(node.Content[0]) - } - if node.Kind != yaml.ScalarNode { - return false, false - } - if node.Tag != "!!bool" { - return false, false - } - v, err := strconv.ParseBool(node.Value) - if err != nil { - return false, false - } - return v, true -} - -// IntForScalarNode returns the integer value of a node. -func IntForScalarNode(node *yaml.Node) (int64, bool) { - if node == nil { - return 0, false - } - if node.Kind == yaml.DocumentNode { - return IntForScalarNode(node.Content[0]) - } - if node.Kind != yaml.ScalarNode { - return 0, false - } - if node.Tag != "!!int" { - return 0, false - } - v, err := strconv.ParseInt(node.Value, 10, 64) - if err != nil { - return 0, false - } - return v, true -} - -// FloatForScalarNode returns the float value of a node. -func FloatForScalarNode(node *yaml.Node) (float64, bool) { - if node == nil { - return 0.0, false - } - if node.Kind == yaml.DocumentNode { - return FloatForScalarNode(node.Content[0]) - } - if node.Kind != yaml.ScalarNode { - return 0.0, false - } - if (node.Tag != "!!int") && (node.Tag != "!!float") { - return 0.0, false - } - v, err := strconv.ParseFloat(node.Value, 64) - if err != nil { - return 0.0, false - } - return v, true -} - -// StringForScalarNode returns the string value of a node. -func StringForScalarNode(node *yaml.Node) (string, bool) { - if node == nil { - return "", false - } - if node.Kind == yaml.DocumentNode { - return StringForScalarNode(node.Content[0]) - } - switch node.Kind { - case yaml.ScalarNode: - switch node.Tag { - case "!!int": - return node.Value, true - case "!!str": - return node.Value, true - case "!!timestamp": - return node.Value, true - case "!!null": - return "", true - default: - return "", false - } - default: - return "", false - } -} - -// StringArrayForSequenceNode converts a sequence node to an array of strings, if possible. -func StringArrayForSequenceNode(node *yaml.Node) []string { - stringArray := make([]string, 0) - for _, item := range node.Content { - v, ok := StringForScalarNode(item) - if ok { - stringArray = append(stringArray, v) - } - } - return stringArray -} - -// MissingKeysInMap identifies which keys from a list of required keys are not in a map. -func MissingKeysInMap(m *yaml.Node, requiredKeys []string) []string { - missingKeys := make([]string, 0) - for _, k := range requiredKeys { - if !MapHasKey(m, k) { - missingKeys = append(missingKeys, k) - } - } - return missingKeys -} - -// InvalidKeysInMap returns keys in a map that don't match a list of allowed keys and patterns. -func InvalidKeysInMap(m *yaml.Node, allowedKeys []string, allowedPatterns []*regexp.Regexp) []string { - invalidKeys := make([]string, 0) - if m == nil || m.Kind != yaml.MappingNode { - return invalidKeys - } - for i := 0; i < len(m.Content); i += 2 { - key := m.Content[i].Value - found := false - // does the key match an allowed key? - for _, allowedKey := range allowedKeys { - if key == allowedKey { - found = true - break - } - } - if !found { - // does the key match an allowed pattern? - for _, allowedPattern := range allowedPatterns { - if allowedPattern.MatchString(key) { - found = true - break - } - } - if !found { - invalidKeys = append(invalidKeys, key) - } - } - } - return invalidKeys -} - -// NewNullNode creates a new Null node. -func NewNullNode() *yaml.Node { - node := &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: "!!null", - } - return node -} - -// NewMappingNode creates a new Mapping node. -func NewMappingNode() *yaml.Node { - return &yaml.Node{ - Kind: yaml.MappingNode, - Content: make([]*yaml.Node, 0), - } -} - -// NewSequenceNode creates a new Sequence node. -func NewSequenceNode() *yaml.Node { - node := &yaml.Node{ - Kind: yaml.SequenceNode, - Content: make([]*yaml.Node, 0), - } - return node -} - -// NewScalarNodeForString creates a new node to hold a string. -func NewScalarNodeForString(s string) *yaml.Node { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: "!!str", - Value: s, - } -} - -// NewSequenceNodeForStringArray creates a new node to hold an array of strings. -func NewSequenceNodeForStringArray(strings []string) *yaml.Node { - node := &yaml.Node{ - Kind: yaml.SequenceNode, - Content: make([]*yaml.Node, 0), - } - for _, s := range strings { - node.Content = append(node.Content, NewScalarNodeForString(s)) - } - return node -} - -// NewScalarNodeForBool creates a new node to hold a bool. -func NewScalarNodeForBool(b bool) *yaml.Node { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: "!!bool", - Value: fmt.Sprintf("%t", b), - } -} - -// NewScalarNodeForFloat creates a new node to hold a float. -func NewScalarNodeForFloat(f float64) *yaml.Node { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: "!!float", - Value: fmt.Sprintf("%g", f), - } -} - -// NewScalarNodeForInt creates a new node to hold an integer. -func NewScalarNodeForInt(i int64) *yaml.Node { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: "!!int", - Value: fmt.Sprintf("%d", i), - } -} - -// PluralProperties returns the string "properties" pluralized. -func PluralProperties(count int) string { - if count == 1 { - return "property" - } - return "properties" -} - -// StringArrayContainsValue returns true if a string array contains a specified value. -func StringArrayContainsValue(array []string, value string) bool { - for _, item := range array { - if item == value { - return true - } - } - return false -} - -// StringArrayContainsValues returns true if a string array contains all of a list of specified values. -func StringArrayContainsValues(array []string, values []string) bool { - for _, value := range values { - if !StringArrayContainsValue(array, value) { - return false - } - } - return true -} - -// StringValue returns the string value of an item. -func StringValue(item interface{}) (value string, ok bool) { - value, ok = item.(string) - if ok { - return value, ok - } - intValue, ok := item.(int) - if ok { - return strconv.Itoa(intValue), true - } - return "", false -} - -// Description returns a human-readable represention of an item. -func Description(item interface{}) string { - value, ok := item.(*yaml.Node) - if ok { - return jsonschema.Render(value) - } - return fmt.Sprintf("%+v", item) -} - -// Display returns a description of a node for use in error messages. -func Display(node *yaml.Node) string { - switch node.Kind { - case yaml.ScalarNode: - switch node.Tag { - case "!!str": - return fmt.Sprintf("%s (string)", node.Value) - } - } - return fmt.Sprintf("%+v (%T)", node, node) -} - -// Marshal creates a yaml version of a structure in our preferred style -func Marshal(in *yaml.Node) []byte { - clearStyle(in) - //bytes, _ := yaml.Marshal(&yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{in}}) - bytes, _ := yaml.Marshal(in) - - return bytes -} - -func clearStyle(node *yaml.Node) { - node.Style = 0 - for _, c := range node.Content { - clearStyle(c) - } -} diff --git a/vendor/github.com/google/gnostic/jsonschema/base.go b/vendor/github.com/google/gnostic/jsonschema/base.go deleted file mode 100644 index 0af8b148b..000000000 --- a/vendor/github.com/google/gnostic/jsonschema/base.go +++ /dev/null @@ -1,84 +0,0 @@ - -// THIS FILE IS AUTOMATICALLY GENERATED. - -package jsonschema - -import ( - "encoding/base64" -) - -func baseSchemaBytes() ([]byte, error){ - return base64.StdEncoding.DecodeString( -`ewogICAgImlkIjogImh0dHA6Ly9qc29uLXNjaGVtYS5vcmcvZHJhZnQtMDQvc2NoZW1hIyIsCiAgICAi -JHNjaGVtYSI6ICJodHRwOi8vanNvbi1zY2hlbWEub3JnL2RyYWZ0LTA0L3NjaGVtYSMiLAogICAgImRl -c2NyaXB0aW9uIjogIkNvcmUgc2NoZW1hIG1ldGEtc2NoZW1hIiwKICAgICJkZWZpbml0aW9ucyI6IHsK -ICAgICAgICAic2NoZW1hQXJyYXkiOiB7CiAgICAgICAgICAgICJ0eXBlIjogImFycmF5IiwKICAgICAg -ICAgICAgIm1pbkl0ZW1zIjogMSwKICAgICAgICAgICAgIml0ZW1zIjogeyAiJHJlZiI6ICIjIiB9CiAg -ICAgICAgfSwKICAgICAgICAicG9zaXRpdmVJbnRlZ2VyIjogewogICAgICAgICAgICAidHlwZSI6ICJp -bnRlZ2VyIiwKICAgICAgICAgICAgIm1pbmltdW0iOiAwCiAgICAgICAgfSwKICAgICAgICAicG9zaXRp -dmVJbnRlZ2VyRGVmYXVsdDAiOiB7CiAgICAgICAgICAgICJhbGxPZiI6IFsgeyAiJHJlZiI6ICIjL2Rl -ZmluaXRpb25zL3Bvc2l0aXZlSW50ZWdlciIgfSwgeyAiZGVmYXVsdCI6IDAgfSBdCiAgICAgICAgfSwK -ICAgICAgICAic2ltcGxlVHlwZXMiOiB7CiAgICAgICAgICAgICJlbnVtIjogWyAiYXJyYXkiLCAiYm9v -bGVhbiIsICJpbnRlZ2VyIiwgIm51bGwiLCAibnVtYmVyIiwgIm9iamVjdCIsICJzdHJpbmciIF0KICAg -ICAgICB9LAogICAgICAgICJzdHJpbmdBcnJheSI6IHsKICAgICAgICAgICAgInR5cGUiOiAiYXJyYXki -LAogICAgICAgICAgICAiaXRlbXMiOiB7ICJ0eXBlIjogInN0cmluZyIgfSwKICAgICAgICAgICAgIm1p -bkl0ZW1zIjogMSwKICAgICAgICAgICAgInVuaXF1ZUl0ZW1zIjogdHJ1ZQogICAgICAgIH0KICAgIH0s -CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICAgImlkIjogewog -ICAgICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICAgICAiZm9ybWF0IjogInVyaSIKICAg -ICAgICB9LAogICAgICAgICIkc2NoZW1hIjogewogICAgICAgICAgICAidHlwZSI6ICJzdHJpbmciLAog -ICAgICAgICAgICAiZm9ybWF0IjogInVyaSIKICAgICAgICB9LAogICAgICAgICJ0aXRsZSI6IHsKICAg -ICAgICAgICAgInR5cGUiOiAic3RyaW5nIgogICAgICAgIH0sCiAgICAgICAgImRlc2NyaXB0aW9uIjog -ewogICAgICAgICAgICAidHlwZSI6ICJzdHJpbmciCiAgICAgICAgfSwKICAgICAgICAiZGVmYXVsdCI6 -IHt9LAogICAgICAgICJtdWx0aXBsZU9mIjogewogICAgICAgICAgICAidHlwZSI6ICJudW1iZXIiLAog -ICAgICAgICAgICAibWluaW11bSI6IDAsCiAgICAgICAgICAgICJleGNsdXNpdmVNaW5pbXVtIjogdHJ1 -ZQogICAgICAgIH0sCiAgICAgICAgIm1heGltdW0iOiB7CiAgICAgICAgICAgICJ0eXBlIjogIm51bWJl -ciIKICAgICAgICB9LAogICAgICAgICJleGNsdXNpdmVNYXhpbXVtIjogewogICAgICAgICAgICAidHlw -ZSI6ICJib29sZWFuIiwKICAgICAgICAgICAgImRlZmF1bHQiOiBmYWxzZQogICAgICAgIH0sCiAgICAg -ICAgIm1pbmltdW0iOiB7CiAgICAgICAgICAgICJ0eXBlIjogIm51bWJlciIKICAgICAgICB9LAogICAg -ICAgICJleGNsdXNpdmVNaW5pbXVtIjogewogICAgICAgICAgICAidHlwZSI6ICJib29sZWFuIiwKICAg -ICAgICAgICAgImRlZmF1bHQiOiBmYWxzZQogICAgICAgIH0sCiAgICAgICAgIm1heExlbmd0aCI6IHsg -IiRyZWYiOiAiIy9kZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXIiIH0sCiAgICAgICAgIm1pbkxlbmd0 -aCI6IHsgIiRyZWYiOiAiIy9kZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXJEZWZhdWx0MCIgfSwKICAg -ICAgICAicGF0dGVybiI6IHsKICAgICAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAgICAg -ImZvcm1hdCI6ICJyZWdleCIKICAgICAgICB9LAogICAgICAgICJhZGRpdGlvbmFsSXRlbXMiOiB7CiAg -ICAgICAgICAgICJhbnlPZiI6IFsKICAgICAgICAgICAgICAgIHsgInR5cGUiOiAiYm9vbGVhbiIgfSwK -ICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIyIgfQogICAgICAgICAgICBdLAogICAgICAgICAgICAi -ZGVmYXVsdCI6IHt9CiAgICAgICAgfSwKICAgICAgICAiaXRlbXMiOiB7CiAgICAgICAgICAgICJhbnlP -ZiI6IFsKICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIyIgfSwKICAgICAgICAgICAgICAgIHsgIiRy -ZWYiOiAiIy9kZWZpbml0aW9ucy9zY2hlbWFBcnJheSIgfQogICAgICAgICAgICBdLAogICAgICAgICAg -ICAiZGVmYXVsdCI6IHt9CiAgICAgICAgfSwKICAgICAgICAibWF4SXRlbXMiOiB7ICIkcmVmIjogIiMv -ZGVmaW5pdGlvbnMvcG9zaXRpdmVJbnRlZ2VyIiB9LAogICAgICAgICJtaW5JdGVtcyI6IHsgIiRyZWYi -OiAiIy9kZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXJEZWZhdWx0MCIgfSwKICAgICAgICAidW5pcXVl -SXRlbXMiOiB7CiAgICAgICAgICAgICJ0eXBlIjogImJvb2xlYW4iLAogICAgICAgICAgICAiZGVmYXVs -dCI6IGZhbHNlCiAgICAgICAgfSwKICAgICAgICAibWF4UHJvcGVydGllcyI6IHsgIiRyZWYiOiAiIy9k -ZWZpbml0aW9ucy9wb3NpdGl2ZUludGVnZXIiIH0sCiAgICAgICAgIm1pblByb3BlcnRpZXMiOiB7ICIk -cmVmIjogIiMvZGVmaW5pdGlvbnMvcG9zaXRpdmVJbnRlZ2VyRGVmYXVsdDAiIH0sCiAgICAgICAgInJl -cXVpcmVkIjogeyAiJHJlZiI6ICIjL2RlZmluaXRpb25zL3N0cmluZ0FycmF5IiB9LAogICAgICAgICJh -ZGRpdGlvbmFsUHJvcGVydGllcyI6IHsKICAgICAgICAgICAgImFueU9mIjogWwogICAgICAgICAgICAg -ICAgeyAidHlwZSI6ICJib29sZWFuIiB9LAogICAgICAgICAgICAgICAgeyAiJHJlZiI6ICIjIiB9CiAg -ICAgICAgICAgIF0sCiAgICAgICAgICAgICJkZWZhdWx0Ijoge30KICAgICAgICB9LAogICAgICAgICJk -ZWZpbml0aW9ucyI6IHsKICAgICAgICAgICAgInR5cGUiOiAib2JqZWN0IiwKICAgICAgICAgICAgImFk -ZGl0aW9uYWxQcm9wZXJ0aWVzIjogeyAiJHJlZiI6ICIjIiB9LAogICAgICAgICAgICAiZGVmYXVsdCI6 -IHt9CiAgICAgICAgfSwKICAgICAgICAicHJvcGVydGllcyI6IHsKICAgICAgICAgICAgInR5cGUiOiAi -b2JqZWN0IiwKICAgICAgICAgICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogeyAiJHJlZiI6ICIjIiB9 -LAogICAgICAgICAgICAiZGVmYXVsdCI6IHt9CiAgICAgICAgfSwKICAgICAgICAicGF0dGVyblByb3Bl -cnRpZXMiOiB7CiAgICAgICAgICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAgICAgICAgICJhZGRpdGlv -bmFsUHJvcGVydGllcyI6IHsgIiRyZWYiOiAiIyIgfSwKICAgICAgICAgICAgImRlZmF1bHQiOiB7fQog -ICAgICAgIH0sCiAgICAgICAgImRlcGVuZGVuY2llcyI6IHsKICAgICAgICAgICAgInR5cGUiOiAib2Jq -ZWN0IiwKICAgICAgICAgICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogewogICAgICAgICAgICAgICAg -ImFueU9mIjogWwogICAgICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIyIgfSwKICAgICAgICAgICAg -ICAgICAgICB7ICIkcmVmIjogIiMvZGVmaW5pdGlvbnMvc3RyaW5nQXJyYXkiIH0KICAgICAgICAgICAg -ICAgIF0KICAgICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICAgImVudW0iOiB7CiAgICAgICAgICAg -ICJ0eXBlIjogImFycmF5IiwKICAgICAgICAgICAgIm1pbkl0ZW1zIjogMSwKICAgICAgICAgICAgInVu -aXF1ZUl0ZW1zIjogdHJ1ZQogICAgICAgIH0sCiAgICAgICAgInR5cGUiOiB7CiAgICAgICAgICAgICJh -bnlPZiI6IFsKICAgICAgICAgICAgICAgIHsgIiRyZWYiOiAiIy9kZWZpbml0aW9ucy9zaW1wbGVUeXBl -cyIgfSwKICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgICAidHlwZSI6ICJhcnJheSIs -CiAgICAgICAgICAgICAgICAgICAgIml0ZW1zIjogeyAiJHJlZiI6ICIjL2RlZmluaXRpb25zL3NpbXBs -ZVR5cGVzIiB9LAogICAgICAgICAgICAgICAgICAgICJtaW5JdGVtcyI6IDEsCiAgICAgICAgICAgICAg -ICAgICAgInVuaXF1ZUl0ZW1zIjogdHJ1ZQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICBdCiAg -ICAgICAgfSwKICAgICAgICAiYWxsT2YiOiB7ICIkcmVmIjogIiMvZGVmaW5pdGlvbnMvc2NoZW1hQXJy -YXkiIH0sCiAgICAgICAgImFueU9mIjogeyAiJHJlZiI6ICIjL2RlZmluaXRpb25zL3NjaGVtYUFycmF5 -IiB9LAogICAgICAgICJvbmVPZiI6IHsgIiRyZWYiOiAiIy9kZWZpbml0aW9ucy9zY2hlbWFBcnJheSIg -fSwKICAgICAgICAibm90IjogeyAiJHJlZiI6ICIjIiB9CiAgICB9LAogICAgImRlcGVuZGVuY2llcyI6 -IHsKICAgICAgICAiZXhjbHVzaXZlTWF4aW11bSI6IFsgIm1heGltdW0iIF0sCiAgICAgICAgImV4Y2x1 -c2l2ZU1pbmltdW0iOiBbICJtaW5pbXVtIiBdCiAgICB9LAogICAgImRlZmF1bHQiOiB7fQp9Cg==`)} \ No newline at end of file diff --git a/vendor/github.com/google/gnostic/jsonschema/models.go b/vendor/github.com/google/gnostic/jsonschema/models.go deleted file mode 100644 index 0d877249a..000000000 --- a/vendor/github.com/google/gnostic/jsonschema/models.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2017 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package jsonschema supports the reading, writing, and manipulation -// of JSON Schemas. -package jsonschema - -import "gopkg.in/yaml.v3" - -// The Schema struct models a JSON Schema and, because schemas are -// defined hierarchically, contains many references to itself. -// All fields are pointers and are nil if the associated values -// are not specified. -type Schema struct { - Schema *string // $schema - ID *string // id keyword used for $ref resolution scope - Ref *string // $ref, i.e. JSON Pointers - ReadOnly *bool - WriteOnly *bool - - // http://json-schema.org/latest/json-schema-validation.html - // 5.1. Validation keywords for numeric instances (number and integer) - MultipleOf *SchemaNumber - Maximum *SchemaNumber - ExclusiveMaximum *bool - Minimum *SchemaNumber - ExclusiveMinimum *bool - - // 5.2. Validation keywords for strings - MaxLength *int64 - MinLength *int64 - Pattern *string - - // 5.3. Validation keywords for arrays - AdditionalItems *SchemaOrBoolean - Items *SchemaOrSchemaArray - MaxItems *int64 - MinItems *int64 - UniqueItems *bool - - // 5.4. Validation keywords for objects - MaxProperties *int64 - MinProperties *int64 - Required *[]string - AdditionalProperties *SchemaOrBoolean - Properties *[]*NamedSchema - PatternProperties *[]*NamedSchema - Dependencies *[]*NamedSchemaOrStringArray - - // 5.5. Validation keywords for any instance type - Enumeration *[]SchemaEnumValue - Type *StringOrStringArray - AllOf *[]*Schema - AnyOf *[]*Schema - OneOf *[]*Schema - Not *Schema - Definitions *[]*NamedSchema - - // 6. Metadata keywords - Title *string - Description *string - Default *yaml.Node - - // 7. Semantic validation with "format" - Format *string -} - -// These helper structs represent "combination" types that generally can -// have values of one type or another. All are used to represent parts -// of Schemas. - -// SchemaNumber represents a value that can be either an Integer or a Float. -type SchemaNumber struct { - Integer *int64 - Float *float64 -} - -// NewSchemaNumberWithInteger creates and returns a new object -func NewSchemaNumberWithInteger(i int64) *SchemaNumber { - result := &SchemaNumber{} - result.Integer = &i - return result -} - -// NewSchemaNumberWithFloat creates and returns a new object -func NewSchemaNumberWithFloat(f float64) *SchemaNumber { - result := &SchemaNumber{} - result.Float = &f - return result -} - -// SchemaOrBoolean represents a value that can be either a Schema or a Boolean. -type SchemaOrBoolean struct { - Schema *Schema - Boolean *bool -} - -// NewSchemaOrBooleanWithSchema creates and returns a new object -func NewSchemaOrBooleanWithSchema(s *Schema) *SchemaOrBoolean { - result := &SchemaOrBoolean{} - result.Schema = s - return result -} - -// NewSchemaOrBooleanWithBoolean creates and returns a new object -func NewSchemaOrBooleanWithBoolean(b bool) *SchemaOrBoolean { - result := &SchemaOrBoolean{} - result.Boolean = &b - return result -} - -// StringOrStringArray represents a value that can be either -// a String or an Array of Strings. -type StringOrStringArray struct { - String *string - StringArray *[]string -} - -// NewStringOrStringArrayWithString creates and returns a new object -func NewStringOrStringArrayWithString(s string) *StringOrStringArray { - result := &StringOrStringArray{} - result.String = &s - return result -} - -// NewStringOrStringArrayWithStringArray creates and returns a new object -func NewStringOrStringArrayWithStringArray(a []string) *StringOrStringArray { - result := &StringOrStringArray{} - result.StringArray = &a - return result -} - -// SchemaOrStringArray represents a value that can be either -// a Schema or an Array of Strings. -type SchemaOrStringArray struct { - Schema *Schema - StringArray *[]string -} - -// SchemaOrSchemaArray represents a value that can be either -// a Schema or an Array of Schemas. -type SchemaOrSchemaArray struct { - Schema *Schema - SchemaArray *[]*Schema -} - -// NewSchemaOrSchemaArrayWithSchema creates and returns a new object -func NewSchemaOrSchemaArrayWithSchema(s *Schema) *SchemaOrSchemaArray { - result := &SchemaOrSchemaArray{} - result.Schema = s - return result -} - -// NewSchemaOrSchemaArrayWithSchemaArray creates and returns a new object -func NewSchemaOrSchemaArrayWithSchemaArray(a []*Schema) *SchemaOrSchemaArray { - result := &SchemaOrSchemaArray{} - result.SchemaArray = &a - return result -} - -// SchemaEnumValue represents a value that can be part of an -// enumeration in a Schema. -type SchemaEnumValue struct { - String *string - Bool *bool -} - -// NamedSchema is a name-value pair that is used to emulate maps -// with ordered keys. -type NamedSchema struct { - Name string - Value *Schema -} - -// NewNamedSchema creates and returns a new object -func NewNamedSchema(name string, value *Schema) *NamedSchema { - return &NamedSchema{Name: name, Value: value} -} - -// NamedSchemaOrStringArray is a name-value pair that is used -// to emulate maps with ordered keys. -type NamedSchemaOrStringArray struct { - Name string - Value *SchemaOrStringArray -} - -// Access named subschemas by name - -func namedSchemaArrayElementWithName(array *[]*NamedSchema, name string) *Schema { - if array == nil { - return nil - } - for _, pair := range *array { - if pair.Name == name { - return pair.Value - } - } - return nil -} - -// PropertyWithName returns the selected element. -func (s *Schema) PropertyWithName(name string) *Schema { - return namedSchemaArrayElementWithName(s.Properties, name) -} - -// PatternPropertyWithName returns the selected element. -func (s *Schema) PatternPropertyWithName(name string) *Schema { - return namedSchemaArrayElementWithName(s.PatternProperties, name) -} - -// DefinitionWithName returns the selected element. -func (s *Schema) DefinitionWithName(name string) *Schema { - return namedSchemaArrayElementWithName(s.Definitions, name) -} - -// AddProperty adds a named property. -func (s *Schema) AddProperty(name string, property *Schema) { - *s.Properties = append(*s.Properties, NewNamedSchema(name, property)) -} diff --git a/vendor/github.com/google/gnostic/openapiv2/document.go b/vendor/github.com/google/gnostic/openapiv2/document.go deleted file mode 100644 index 0021ae871..000000000 --- a/vendor/github.com/google/gnostic/openapiv2/document.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2020 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package openapi_v2 - -import ( - "gopkg.in/yaml.v3" - - "github.com/google/gnostic/compiler" -) - -// ParseDocument reads an OpenAPI v2 description from a YAML/JSON representation. -func ParseDocument(b []byte) (*Document, error) { - info, err := compiler.ReadInfoFromBytes("", b) - if err != nil { - return nil, err - } - root := info.Content[0] - return NewDocument(root, compiler.NewContextWithExtensions("$root", root, nil, nil)) -} - -// YAMLValue produces a serialized YAML representation of the document. -func (d *Document) YAMLValue(comment string) ([]byte, error) { - rawInfo := d.ToRawInfo() - rawInfo = &yaml.Node{ - Kind: yaml.DocumentNode, - Content: []*yaml.Node{rawInfo}, - HeadComment: comment, - } - return yaml.Marshal(rawInfo) -} diff --git a/vendor/github.com/google/gnostic/openapiv3/README.md b/vendor/github.com/google/gnostic/openapiv3/README.md deleted file mode 100644 index 83603b82a..000000000 --- a/vendor/github.com/google/gnostic/openapiv3/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# OpenAPI v3 Protocol Buffer Models - -This directory contains a Protocol Buffer-language model and related code for -supporting OpenAPI v3. - -Gnostic applications and plugins can use OpenAPIv3.proto to generate Protocol -Buffer support code for their preferred languages. - -OpenAPIv3.go is used by Gnostic to read JSON and YAML OpenAPI descriptions into -the Protocol Buffer-based datastructures generated from OpenAPIv3.proto. - -OpenAPIv3.proto and OpenAPIv3.go are generated by the Gnostic compiler -generator, and OpenAPIv3.pb.go is generated by protoc, the Protocol Buffer -compiler, and protoc-gen-go, the Protocol Buffer Go code generation plugin. - -openapi-3.1.json is a JSON schema for OpenAPI 3.1 that is automatically -generated from the OpenAPI 3.1 specification. It is not an official JSON Schema -for OpenAPI. - -The schema-generator directory contains support code which generates -openapi-3.1.json from the OpenAPI 3.1 specification document (Markdown). - -### How to rebuild - -`protoc -I=. -I=third_party --go_out=. --go_opt=paths=source_relative openapiv3/*.proto` \ No newline at end of file diff --git a/vendor/github.com/google/gnostic/openapiv3/annotations.pb.go b/vendor/github.com/google/gnostic/openapiv3/annotations.pb.go deleted file mode 100644 index ae242f304..000000000 --- a/vendor/github.com/google/gnostic/openapiv3/annotations.pb.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2022 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.0 -// protoc v3.19.4 -// source: openapiv3/annotations.proto - -package openapi_v3 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - descriptorpb "google.golang.org/protobuf/types/descriptorpb" - reflect "reflect" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -var file_openapiv3_annotations_proto_extTypes = []protoimpl.ExtensionInfo{ - { - ExtendedType: (*descriptorpb.FileOptions)(nil), - ExtensionType: (*Document)(nil), - Field: 1143, - Name: "openapi.v3.document", - Tag: "bytes,1143,opt,name=document", - Filename: "openapiv3/annotations.proto", - }, - { - ExtendedType: (*descriptorpb.MethodOptions)(nil), - ExtensionType: (*Operation)(nil), - Field: 1143, - Name: "openapi.v3.operation", - Tag: "bytes,1143,opt,name=operation", - Filename: "openapiv3/annotations.proto", - }, - { - ExtendedType: (*descriptorpb.MessageOptions)(nil), - ExtensionType: (*Schema)(nil), - Field: 1143, - Name: "openapi.v3.schema", - Tag: "bytes,1143,opt,name=schema", - Filename: "openapiv3/annotations.proto", - }, - { - ExtendedType: (*descriptorpb.FieldOptions)(nil), - ExtensionType: (*Schema)(nil), - Field: 1143, - Name: "openapi.v3.property", - Tag: "bytes,1143,opt,name=property", - Filename: "openapiv3/annotations.proto", - }, -} - -// Extension fields to descriptorpb.FileOptions. -var ( - // optional openapi.v3.Document document = 1143; - E_Document = &file_openapiv3_annotations_proto_extTypes[0] -) - -// Extension fields to descriptorpb.MethodOptions. -var ( - // optional openapi.v3.Operation operation = 1143; - E_Operation = &file_openapiv3_annotations_proto_extTypes[1] -) - -// Extension fields to descriptorpb.MessageOptions. -var ( - // optional openapi.v3.Schema schema = 1143; - E_Schema = &file_openapiv3_annotations_proto_extTypes[2] -) - -// Extension fields to descriptorpb.FieldOptions. -var ( - // optional openapi.v3.Schema property = 1143; - E_Property = &file_openapiv3_annotations_proto_extTypes[3] -) - -var File_openapiv3_annotations_proto protoreflect.FileDescriptor - -var file_openapiv3_annotations_proto_rawDesc = []byte{ - 0x0a, 0x1b, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x76, 0x33, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, - 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x6f, - 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x33, 0x1a, 0x19, 0x6f, 0x70, 0x65, 0x6e, 0x61, - 0x70, 0x69, 0x76, 0x33, 0x2f, 0x4f, 0x70, 0x65, 0x6e, 0x41, 0x50, 0x49, 0x76, 0x33, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x3a, 0x4f, 0x0a, 0x08, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, - 0x6e, 0x74, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0x18, 0xf7, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, - 0x69, 0x2e, 0x76, 0x33, 0x2e, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x52, 0x08, 0x64, - 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x3a, 0x54, 0x0a, 0x09, 0x6f, 0x70, 0x65, 0x72, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4f, 0x70, 0x74, - 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xf7, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x6f, 0x70, - 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x33, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x52, 0x09, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x4c, 0x0a, - 0x06, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, - 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xf7, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x12, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x63, 0x68, - 0x65, 0x6d, 0x61, 0x52, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x3a, 0x4e, 0x0a, 0x08, 0x70, - 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x79, 0x12, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4f, - 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xf7, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x2e, 0x76, 0x33, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, - 0x61, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x79, 0x42, 0x5a, 0x0a, 0x0e, 0x6f, - 0x72, 0x67, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x5f, 0x76, 0x33, 0x42, 0x10, 0x41, - 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, - 0x01, 0x5a, 0x2e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x2f, 0x6f, 0x70, 0x65, - 0x6e, 0x61, 0x70, 0x69, 0x76, 0x33, 0x3b, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x5f, 0x76, - 0x33, 0xa2, 0x02, 0x03, 0x4f, 0x41, 0x53, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var file_openapiv3_annotations_proto_goTypes = []interface{}{ - (*descriptorpb.FileOptions)(nil), // 0: google.protobuf.FileOptions - (*descriptorpb.MethodOptions)(nil), // 1: google.protobuf.MethodOptions - (*descriptorpb.MessageOptions)(nil), // 2: google.protobuf.MessageOptions - (*descriptorpb.FieldOptions)(nil), // 3: google.protobuf.FieldOptions - (*Document)(nil), // 4: openapi.v3.Document - (*Operation)(nil), // 5: openapi.v3.Operation - (*Schema)(nil), // 6: openapi.v3.Schema -} -var file_openapiv3_annotations_proto_depIdxs = []int32{ - 0, // 0: openapi.v3.document:extendee -> google.protobuf.FileOptions - 1, // 1: openapi.v3.operation:extendee -> google.protobuf.MethodOptions - 2, // 2: openapi.v3.schema:extendee -> google.protobuf.MessageOptions - 3, // 3: openapi.v3.property:extendee -> google.protobuf.FieldOptions - 4, // 4: openapi.v3.document:type_name -> openapi.v3.Document - 5, // 5: openapi.v3.operation:type_name -> openapi.v3.Operation - 6, // 6: openapi.v3.schema:type_name -> openapi.v3.Schema - 6, // 7: openapi.v3.property:type_name -> openapi.v3.Schema - 8, // [8:8] is the sub-list for method output_type - 8, // [8:8] is the sub-list for method input_type - 4, // [4:8] is the sub-list for extension type_name - 0, // [0:4] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_openapiv3_annotations_proto_init() } -func file_openapiv3_annotations_proto_init() { - if File_openapiv3_annotations_proto != nil { - return - } - file_openapiv3_OpenAPIv3_proto_init() - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_openapiv3_annotations_proto_rawDesc, - NumEnums: 0, - NumMessages: 0, - NumExtensions: 4, - NumServices: 0, - }, - GoTypes: file_openapiv3_annotations_proto_goTypes, - DependencyIndexes: file_openapiv3_annotations_proto_depIdxs, - ExtensionInfos: file_openapiv3_annotations_proto_extTypes, - }.Build() - File_openapiv3_annotations_proto = out.File - file_openapiv3_annotations_proto_rawDesc = nil - file_openapiv3_annotations_proto_goTypes = nil - file_openapiv3_annotations_proto_depIdxs = nil -} diff --git a/vendor/github.com/google/gnostic/openapiv3/annotations.proto b/vendor/github.com/google/gnostic/openapiv3/annotations.proto deleted file mode 100644 index 0bd87810d..000000000 --- a/vendor/github.com/google/gnostic/openapiv3/annotations.proto +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2022 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package openapi.v3; - -import "openapiv3/OpenAPIv3.proto"; -import "google/protobuf/descriptor.proto"; - -// This option lets the proto compiler generate Java code inside the package -// name (see below) instead of inside an outer class. It creates a simpler -// developer experience by reducing one-level of name nesting and be -// consistent with most programming languages that don't support outer classes. -option java_multiple_files = true; - -// The Java outer classname should be the filename in UpperCamelCase. This -// class is only used to hold proto descriptor, so developers don't need to -// work with it directly. -option java_outer_classname = "AnnotationsProto"; - -// The Java package name must be proto package name with proper prefix. -option java_package = "org.openapi_v3"; - -// A reasonable prefix for the Objective-C symbols generated from the package. -// It should at a minimum be 3 characters long, all uppercase, and convention -// is to use an abbreviation of the package name. Something short, but -// hopefully unique enough to not conflict with things that may come along in -// the future. 'GPB' is reserved for the protocol buffer implementation itself. -option objc_class_prefix = "OAS"; - -// The Go package name. -option go_package = "github.com/google/gnostic/openapiv3;openapi_v3"; - -extend google.protobuf.FileOptions { - Document document = 1143; -} - -extend google.protobuf.MethodOptions { - Operation operation = 1143; -} - -extend google.protobuf.MessageOptions { - Schema schema = 1143; -} - -extend google.protobuf.FieldOptions { - Schema property = 1143; -} \ No newline at end of file diff --git a/vendor/github.com/google/gnostic/openapiv3/document.go b/vendor/github.com/google/gnostic/openapiv3/document.go deleted file mode 100644 index ef10d1d90..000000000 --- a/vendor/github.com/google/gnostic/openapiv3/document.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2020 Google LLC. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package openapi_v3 - -import ( - "gopkg.in/yaml.v3" - - "github.com/google/gnostic/compiler" -) - -// ParseDocument reads an OpenAPI v3 description from a YAML/JSON representation. -func ParseDocument(b []byte) (*Document, error) { - info, err := compiler.ReadInfoFromBytes("", b) - if err != nil { - return nil, err - } - root := info.Content[0] - return NewDocument(root, compiler.NewContextWithExtensions("$root", root, nil, nil)) -} - -// YAMLValue produces a serialized YAML representation of the document. -func (d *Document) YAMLValue(comment string) ([]byte, error) { - rawInfo := d.ToRawInfo() - rawInfo = &yaml.Node{ - Kind: yaml.DocumentNode, - Content: []*yaml.Node{rawInfo}, - HeadComment: comment, - } - return yaml.Marshal(rawInfo) -} diff --git a/vendor/github.com/google/gnostic/openapiv3/openapi-3.0.json b/vendor/github.com/google/gnostic/openapiv3/openapi-3.0.json deleted file mode 100644 index d5caed162..000000000 --- a/vendor/github.com/google/gnostic/openapiv3/openapi-3.0.json +++ /dev/null @@ -1,1251 +0,0 @@ -{ - "title": "A JSON Schema for OpenAPI 3.0.", - "id": "http://openapis.org/v3/schema.json#", - "$schema": "http://json-schema.org/draft-04/schema#", - "type": "object", - "description": "This is the root document object of the OpenAPI document.", - "required": [ - "openapi", - "info", - "paths" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "openapi": { - "type": "string" - }, - "info": { - "$ref": "#/definitions/info" - }, - "servers": { - "type": "array", - "items": { - "$ref": "#/definitions/server" - }, - "uniqueItems": true - }, - "paths": { - "$ref": "#/definitions/paths" - }, - "components": { - "$ref": "#/definitions/components" - }, - "security": { - "type": "array", - "items": { - "$ref": "#/definitions/securityRequirement" - }, - "uniqueItems": true - }, - "tags": { - "type": "array", - "items": { - "$ref": "#/definitions/tag" - }, - "uniqueItems": true - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - } - }, - "definitions": { - "info": { - "type": "object", - "description": "The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.", - "required": [ - "title", - "version" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "termsOfService": { - "type": "string" - }, - "contact": { - "$ref": "#/definitions/contact" - }, - "license": { - "$ref": "#/definitions/license" - }, - "version": { - "type": "string" - } - } - }, - "contact": { - "type": "object", - "description": "Contact information for the exposed API.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "url": { - "type": "string", - "format": "uri" - }, - "email": { - "type": "string", - "format": "email" - } - } - }, - "license": { - "type": "object", - "description": "License information for the exposed API.", - "required": [ - "name" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "url": { - "type": "string" - } - } - }, - "server": { - "type": "object", - "description": "An object representing a Server.", - "required": [ - "url" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "url": { - "type": "string" - }, - "description": { - "type": "string" - }, - "variables": { - "$ref": "#/definitions/serverVariables" - } - } - }, - "serverVariable": { - "type": "object", - "description": "An object representing a Server Variable for server URL template substitution.", - "required": [ - "default" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "enum": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - }, - "default": { - "type": "string" - }, - "description": { - "type": "string" - } - } - }, - "components": { - "type": "object", - "description": "Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "schemas": { - "$ref": "#/definitions/schemasOrReferences" - }, - "responses": { - "$ref": "#/definitions/responsesOrReferences" - }, - "parameters": { - "$ref": "#/definitions/parametersOrReferences" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "requestBodies": { - "$ref": "#/definitions/requestBodiesOrReferences" - }, - "headers": { - "$ref": "#/definitions/headersOrReferences" - }, - "securitySchemes": { - "$ref": "#/definitions/securitySchemesOrReferences" - }, - "links": { - "$ref": "#/definitions/linksOrReferences" - }, - "callbacks": { - "$ref": "#/definitions/callbacksOrReferences" - } - } - }, - "paths": { - "type": "object", - "description": "Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the `Server Object` in order to construct the full URL. The Paths MAY be empty, due to ACL constraints.", - "additionalProperties": false, - "patternProperties": { - "^/": { - "$ref": "#/definitions/pathItem" - }, - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - } - }, - "pathItem": { - "type": "object", - "description": "Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "$ref": { - "type": "string" - }, - "summary": { - "type": "string" - }, - "description": { - "type": "string" - }, - "get": { - "$ref": "#/definitions/operation" - }, - "put": { - "$ref": "#/definitions/operation" - }, - "post": { - "$ref": "#/definitions/operation" - }, - "delete": { - "$ref": "#/definitions/operation" - }, - "options": { - "$ref": "#/definitions/operation" - }, - "head": { - "$ref": "#/definitions/operation" - }, - "patch": { - "$ref": "#/definitions/operation" - }, - "trace": { - "$ref": "#/definitions/operation" - }, - "servers": { - "type": "array", - "items": { - "$ref": "#/definitions/server" - }, - "uniqueItems": true - }, - "parameters": { - "type": "array", - "items": { - "$ref": "#/definitions/parameterOrReference" - }, - "uniqueItems": true - } - } - }, - "operation": { - "type": "object", - "description": "Describes a single API operation on a path.", - "required": [ - "responses" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - }, - "summary": { - "type": "string" - }, - "description": { - "type": "string" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - }, - "operationId": { - "type": "string" - }, - "parameters": { - "type": "array", - "items": { - "$ref": "#/definitions/parameterOrReference" - }, - "uniqueItems": true - }, - "requestBody": { - "$ref": "#/definitions/requestBodyOrReference" - }, - "responses": { - "$ref": "#/definitions/responses" - }, - "callbacks": { - "$ref": "#/definitions/callbacksOrReferences" - }, - "deprecated": { - "type": "boolean" - }, - "security": { - "type": "array", - "items": { - "$ref": "#/definitions/securityRequirement" - }, - "uniqueItems": true - }, - "servers": { - "type": "array", - "items": { - "$ref": "#/definitions/server" - }, - "uniqueItems": true - } - } - }, - "externalDocs": { - "type": "object", - "description": "Allows referencing an external resource for extended documentation.", - "required": [ - "url" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "url": { - "type": "string" - } - } - }, - "parameter": { - "type": "object", - "description": "Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.", - "required": [ - "name", - "in" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "in": { - "type": "string" - }, - "description": { - "type": "string" - }, - "required": { - "type": "boolean" - }, - "deprecated": { - "type": "boolean" - }, - "allowEmptyValue": { - "type": "boolean" - }, - "style": { - "type": "string" - }, - "explode": { - "type": "boolean" - }, - "allowReserved": { - "type": "boolean" - }, - "schema": { - "$ref": "#/definitions/schemaOrReference" - }, - "example": { - "$ref": "#/definitions/any" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - } - } - }, - "requestBody": { - "type": "object", - "description": "Describes a single request body.", - "required": [ - "content" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - }, - "required": { - "type": "boolean" - } - } - }, - "mediaType": { - "type": "object", - "description": "Each Media Type Object provides schema and examples for the media type identified by its key.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "schema": { - "$ref": "#/definitions/schemaOrReference" - }, - "example": { - "$ref": "#/definitions/any" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "encoding": { - "$ref": "#/definitions/encodings" - } - } - }, - "encoding": { - "type": "object", - "description": "A single encoding definition applied to a single schema property.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "contentType": { - "type": "string" - }, - "headers": { - "$ref": "#/definitions/headersOrReferences" - }, - "style": { - "type": "string" - }, - "explode": { - "type": "boolean" - }, - "allowReserved": { - "type": "boolean" - } - } - }, - "responses": { - "type": "object", - "description": "A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors. The `default` MAY be used as a default response object for all HTTP codes that are not covered individually by the specification. The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call.", - "additionalProperties": false, - "patternProperties": { - "^([0-9X]{3})$": { - "$ref": "#/definitions/responseOrReference" - }, - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "default": { - "$ref": "#/definitions/responseOrReference" - } - } - }, - "response": { - "type": "object", - "description": "Describes a single response from an API Operation, including design-time, static `links` to operations based on the response.", - "required": [ - "description" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "headers": { - "$ref": "#/definitions/headersOrReferences" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - }, - "links": { - "$ref": "#/definitions/linksOrReferences" - } - } - }, - "callback": { - "type": "object", - "description": "A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.", - "additionalProperties": false, - "patternProperties": { - "^": { - "$ref": "#/definitions/pathItem" - }, - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - } - }, - "example": { - "type": "object", - "description": "", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "summary": { - "type": "string" - }, - "description": { - "type": "string" - }, - "value": { - "$ref": "#/definitions/any" - }, - "externalValue": { - "type": "string" - } - } - }, - "link": { - "type": "object", - "description": "The `Link object` represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "operationRef": { - "type": "string" - }, - "operationId": { - "type": "string" - }, - "parameters": { - "$ref": "#/definitions/anysOrExpressions" - }, - "requestBody": { - "$ref": "#/definitions/anyOrExpression" - }, - "description": { - "type": "string" - }, - "server": { - "$ref": "#/definitions/server" - } - } - }, - "header": { - "type": "object", - "description": "The Header Object follows the structure of the Parameter Object with the following changes: 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. 1. `in` MUST NOT be specified, it is implicitly in `header`. 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`).", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "required": { - "type": "boolean" - }, - "deprecated": { - "type": "boolean" - }, - "allowEmptyValue": { - "type": "boolean" - }, - "style": { - "type": "string" - }, - "explode": { - "type": "boolean" - }, - "allowReserved": { - "type": "boolean" - }, - "schema": { - "$ref": "#/definitions/schemaOrReference" - }, - "example": { - "$ref": "#/definitions/any" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - } - } - }, - "tag": { - "type": "object", - "description": "Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.", - "required": [ - "name" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - } - } - }, - "reference": { - "type": "object", - "description": "A simple object to allow referencing other components in the specification, internally and externally. The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules. For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.", - "required": [ - "$ref" - ], - "additionalProperties": false, - "properties": { - "$ref": { - "type": "string" - }, - "summary": { - "type": "string" - }, - "description": { - "type": "string" - } - } - }, - "schema": { - "type": "object", - "description": "The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00. For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "nullable": { - "type": "boolean" - }, - "discriminator": { - "$ref": "#/definitions/discriminator" - }, - "readOnly": { - "type": "boolean" - }, - "writeOnly": { - "type": "boolean" - }, - "xml": { - "$ref": "#/definitions/xml" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - }, - "example": { - "$ref": "#/definitions/any" - }, - "deprecated": { - "type": "boolean" - }, - "title": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/title" - }, - "multipleOf": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" - }, - "maximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" - }, - "exclusiveMaximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" - }, - "minimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" - }, - "exclusiveMinimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" - }, - "maxLength": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maxLength" - }, - "minLength": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minLength" - }, - "pattern": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" - }, - "maxItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maxItems" - }, - "minItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minItems" - }, - "uniqueItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" - }, - "maxProperties": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maxProperties" - }, - "minProperties": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minProperties" - }, - "required": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/required" - }, - "enum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" - }, - "type": { - "type": "string" - }, - "allOf": { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - }, - "oneOf": { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - }, - "anyOf": { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - }, - "not": { - "$ref": "#/definitions/schema" - }, - "items": { - "anyOf": [ - { - "$ref": "#/definitions/schemaOrReference" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - } - ] - }, - "properties": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/schemaOrReference" - } - }, - "additionalProperties": { - "oneOf": [ - { - "$ref": "#/definitions/schemaOrReference" - }, - { - "type": "boolean" - } - ] - }, - "default": { - "$ref": "#/definitions/defaultType" - }, - "description": { - "type": "string" - }, - "format": { - "type": "string" - } - } - }, - "discriminator": { - "type": "object", - "description": "When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. When using the discriminator, _inline_ schemas will not be considered.", - "required": [ - "propertyName" - ], - "additionalProperties": false, - "properties": { - "propertyName": { - "type": "string" - }, - "mapping": { - "$ref": "#/definitions/strings" - } - } - }, - "xml": { - "type": "object", - "description": "A metadata object that allows for more fine-tuned XML model definitions. When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. See examples for expected behavior.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "namespace": { - "type": "string" - }, - "prefix": { - "type": "string" - }, - "attribute": { - "type": "boolean" - }, - "wrapped": { - "type": "boolean" - } - } - }, - "securityScheme": { - "type": "object", - "description": "Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header or as a query parameter), OAuth2's common flows (implicit, password, application and access code) as defined in RFC6749, and OpenID Connect Discovery.", - "required": [ - "type" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "type": { - "type": "string" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - }, - "in": { - "type": "string" - }, - "scheme": { - "type": "string" - }, - "bearerFormat": { - "type": "string" - }, - "flows": { - "$ref": "#/definitions/oauthFlows" - }, - "openIdConnectUrl": { - "type": "string" - } - } - }, - "oauthFlows": { - "type": "object", - "description": "Allows configuration of the supported OAuth Flows.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "implicit": { - "$ref": "#/definitions/oauthFlow" - }, - "password": { - "$ref": "#/definitions/oauthFlow" - }, - "clientCredentials": { - "$ref": "#/definitions/oauthFlow" - }, - "authorizationCode": { - "$ref": "#/definitions/oauthFlow" - } - } - }, - "oauthFlow": { - "type": "object", - "description": "Configuration details for a supported OAuth Flow", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "authorizationUrl": { - "type": "string" - }, - "tokenUrl": { - "type": "string" - }, - "refreshUrl": { - "type": "string" - }, - "scopes": { - "$ref": "#/definitions/strings" - } - } - }, - "securityRequirement": { - "type": "object", - "description": "Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object. Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. When a list of Security Requirement Objects is defined on the Open API object or Operation Object, only one of Security Requirement Objects in the list needs to be satisfied to authorize the request.", - "additionalProperties": false, - "patternProperties": { - "^[a-zA-Z0-9\\.\\-_]+$": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - } - }, - "anyOrExpression": { - "oneOf": [ - { - "$ref": "#/definitions/any" - }, - { - "$ref": "#/definitions/expression" - } - ] - }, - "callbackOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/callback" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "exampleOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/example" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "headerOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/header" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "linkOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/link" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "parameterOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/parameter" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "requestBodyOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/requestBody" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "responseOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/response" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "schemaOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/schema" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "securitySchemeOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/securityScheme" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "anysOrExpressions": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/anyOrExpression" - } - }, - "callbacksOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/callbackOrReference" - } - }, - "encodings": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/encoding" - } - }, - "examplesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/exampleOrReference" - } - }, - "headersOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/headerOrReference" - } - }, - "linksOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/linkOrReference" - } - }, - "mediaTypes": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/mediaType" - } - }, - "parametersOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/parameterOrReference" - } - }, - "requestBodiesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/requestBodyOrReference" - } - }, - "responsesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/responseOrReference" - } - }, - "schemasOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/schemaOrReference" - } - }, - "securitySchemesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/securitySchemeOrReference" - } - }, - "serverVariables": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/serverVariable" - } - }, - "strings": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "object": { - "type": "object", - "additionalProperties": true - }, - "any": { - "additionalProperties": true - }, - "expression": { - "type": "object", - "additionalProperties": true - }, - "specificationExtension": { - "description": "Any property starting with x- is valid.", - "oneOf": [ - { - "type": "null" - }, - { - "type": "number" - }, - { - "type": "boolean" - }, - { - "type": "string" - }, - { - "type": "object" - }, - { - "type": "array" - } - ] - }, - "defaultType": { - "oneOf": [ - { - "type": "null" - }, - { - "type": "array" - }, - { - "type": "object" - }, - { - "type": "number" - }, - { - "type": "boolean" - }, - { - "type": "string" - } - ] - } - } -} diff --git a/vendor/github.com/google/gnostic/openapiv3/openapi-3.1.json b/vendor/github.com/google/gnostic/openapiv3/openapi-3.1.json deleted file mode 100644 index ed0b83adf..000000000 --- a/vendor/github.com/google/gnostic/openapiv3/openapi-3.1.json +++ /dev/null @@ -1,1250 +0,0 @@ -{ - "title": "A JSON Schema for OpenAPI 3.0.", - "id": "http://openapis.org/v3/schema.json#", - "$schema": "http://json-schema.org/draft-04/schema#", - "type": "object", - "description": "This is the root document object of the OpenAPI document.", - "required": [ - "openapi", - "info", - "paths" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "openapi": { - "type": "string" - }, - "info": { - "$ref": "#/definitions/info" - }, - "servers": { - "type": "array", - "items": { - "$ref": "#/definitions/server" - }, - "uniqueItems": true - }, - "paths": { - "$ref": "#/definitions/paths" - }, - "components": { - "$ref": "#/definitions/components" - }, - "security": { - "type": "array", - "items": { - "$ref": "#/definitions/securityRequirement" - }, - "uniqueItems": true - }, - "tags": { - "type": "array", - "items": { - "$ref": "#/definitions/tag" - }, - "uniqueItems": true - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - } - }, - "definitions": { - "info": { - "type": "object", - "description": "The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.", - "required": [ - "title", - "version" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "termsOfService": { - "type": "string" - }, - "contact": { - "$ref": "#/definitions/contact" - }, - "license": { - "$ref": "#/definitions/license" - }, - "version": { - "type": "string" - }, - "summary": { - "type": "string" - } - } - }, - "contact": { - "type": "object", - "description": "Contact information for the exposed API.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "url": { - "type": "string", - "format": "uri" - }, - "email": { - "type": "string", - "format": "email" - } - } - }, - "license": { - "type": "object", - "description": "License information for the exposed API.", - "required": [ - "name" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "url": { - "type": "string" - } - } - }, - "server": { - "type": "object", - "description": "An object representing a Server.", - "required": [ - "url" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "url": { - "type": "string" - }, - "description": { - "type": "string" - }, - "variables": { - "$ref": "#/definitions/serverVariables" - } - } - }, - "serverVariable": { - "type": "object", - "description": "An object representing a Server Variable for server URL template substitution.", - "required": [ - "default" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "enum": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - }, - "default": { - "type": "string" - }, - "description": { - "type": "string" - } - } - }, - "components": { - "type": "object", - "description": "Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "schemas": { - "$ref": "#/definitions/schemasOrReferences" - }, - "responses": { - "$ref": "#/definitions/responsesOrReferences" - }, - "parameters": { - "$ref": "#/definitions/parametersOrReferences" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "requestBodies": { - "$ref": "#/definitions/requestBodiesOrReferences" - }, - "headers": { - "$ref": "#/definitions/headersOrReferences" - }, - "securitySchemes": { - "$ref": "#/definitions/securitySchemesOrReferences" - }, - "links": { - "$ref": "#/definitions/linksOrReferences" - }, - "callbacks": { - "$ref": "#/definitions/callbacksOrReferences" - } - } - }, - "paths": { - "type": "object", - "description": "Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the `Server Object` in order to construct the full URL. The Paths MAY be empty, due to ACL constraints.", - "additionalProperties": false, - "patternProperties": { - "^/": { - "$ref": "#/definitions/pathItem" - }, - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - } - }, - "pathItem": { - "type": "object", - "description": "Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "$ref": { - "type": "string" - }, - "summary": { - "type": "string" - }, - "description": { - "type": "string" - }, - "get": { - "$ref": "#/definitions/operation" - }, - "put": { - "$ref": "#/definitions/operation" - }, - "post": { - "$ref": "#/definitions/operation" - }, - "delete": { - "$ref": "#/definitions/operation" - }, - "options": { - "$ref": "#/definitions/operation" - }, - "head": { - "$ref": "#/definitions/operation" - }, - "patch": { - "$ref": "#/definitions/operation" - }, - "trace": { - "$ref": "#/definitions/operation" - }, - "servers": { - "type": "array", - "items": { - "$ref": "#/definitions/server" - }, - "uniqueItems": true - }, - "parameters": { - "type": "array", - "items": { - "$ref": "#/definitions/parameterOrReference" - }, - "uniqueItems": true - } - } - }, - "operation": { - "type": "object", - "description": "Describes a single API operation on a path.", - "required": [ - "responses" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - }, - "summary": { - "type": "string" - }, - "description": { - "type": "string" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - }, - "operationId": { - "type": "string" - }, - "parameters": { - "type": "array", - "items": { - "$ref": "#/definitions/parameterOrReference" - }, - "uniqueItems": true - }, - "requestBody": { - "$ref": "#/definitions/requestBodyOrReference" - }, - "responses": { - "$ref": "#/definitions/responses" - }, - "callbacks": { - "$ref": "#/definitions/callbacksOrReferences" - }, - "deprecated": { - "type": "boolean" - }, - "security": { - "type": "array", - "items": { - "$ref": "#/definitions/securityRequirement" - }, - "uniqueItems": true - }, - "servers": { - "type": "array", - "items": { - "$ref": "#/definitions/server" - }, - "uniqueItems": true - } - } - }, - "externalDocs": { - "type": "object", - "description": "Allows referencing an external resource for extended documentation.", - "required": [ - "url" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "url": { - "type": "string" - } - } - }, - "parameter": { - "type": "object", - "description": "Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.", - "required": [ - "name", - "in" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "in": { - "type": "string" - }, - "description": { - "type": "string" - }, - "required": { - "type": "boolean" - }, - "deprecated": { - "type": "boolean" - }, - "allowEmptyValue": { - "type": "boolean" - }, - "style": { - "type": "string" - }, - "explode": { - "type": "boolean" - }, - "allowReserved": { - "type": "boolean" - }, - "schema": { - "$ref": "#/definitions/schemaOrReference" - }, - "example": { - "$ref": "#/definitions/any" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - } - } - }, - "requestBody": { - "type": "object", - "description": "Describes a single request body.", - "required": [ - "content" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - }, - "required": { - "type": "boolean" - } - } - }, - "mediaType": { - "type": "object", - "description": "Each Media Type Object provides schema and examples for the media type identified by its key.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "schema": { - "$ref": "#/definitions/schemaOrReference" - }, - "example": { - "$ref": "#/definitions/any" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "encoding": { - "$ref": "#/definitions/encodings" - } - } - }, - "encoding": { - "type": "object", - "description": "A single encoding definition applied to a single schema property.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "contentType": { - "type": "string" - }, - "headers": { - "$ref": "#/definitions/headersOrReferences" - }, - "style": { - "type": "string" - }, - "explode": { - "type": "boolean" - }, - "allowReserved": { - "type": "boolean" - } - } - }, - "responses": { - "type": "object", - "description": "A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors. The `default` MAY be used as a default response object for all HTTP codes that are not covered individually by the specification. The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call.", - "additionalProperties": false, - "patternProperties": { - "^([0-9X]{3})$": { - "$ref": "#/definitions/responseOrReference" - }, - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "default": { - "$ref": "#/definitions/responseOrReference" - } - } - }, - "response": { - "type": "object", - "description": "Describes a single response from an API Operation, including design-time, static `links` to operations based on the response.", - "required": [ - "description" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "headers": { - "$ref": "#/definitions/headersOrReferences" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - }, - "links": { - "$ref": "#/definitions/linksOrReferences" - } - } - }, - "callback": { - "type": "object", - "description": "A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.", - "additionalProperties": false, - "patternProperties": { - "^": { - "$ref": "#/definitions/pathItem" - }, - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - } - }, - "example": { - "type": "object", - "description": "", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "summary": { - "type": "string" - }, - "description": { - "type": "string" - }, - "value": { - "$ref": "#/definitions/any" - }, - "externalValue": { - "type": "string" - } - } - }, - "link": { - "type": "object", - "description": "The `Link object` represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "operationRef": { - "type": "string" - }, - "operationId": { - "type": "string" - }, - "parameters": { - "$ref": "#/definitions/anyOrExpression" - }, - "requestBody": { - "$ref": "#/definitions/anyOrExpression" - }, - "description": { - "type": "string" - }, - "server": { - "$ref": "#/definitions/server" - } - } - }, - "header": { - "type": "object", - "description": "The Header Object follows the structure of the Parameter Object with the following changes: 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. 1. `in` MUST NOT be specified, it is implicitly in `header`. 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`).", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "description": { - "type": "string" - }, - "required": { - "type": "boolean" - }, - "deprecated": { - "type": "boolean" - }, - "allowEmptyValue": { - "type": "boolean" - }, - "style": { - "type": "string" - }, - "explode": { - "type": "boolean" - }, - "allowReserved": { - "type": "boolean" - }, - "schema": { - "$ref": "#/definitions/schemaOrReference" - }, - "example": { - "$ref": "#/definitions/any" - }, - "examples": { - "$ref": "#/definitions/examplesOrReferences" - }, - "content": { - "$ref": "#/definitions/mediaTypes" - } - } - }, - "tag": { - "type": "object", - "description": "Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.", - "required": [ - "name" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - } - } - }, - "reference": { - "type": "object", - "description": "A simple object to allow referencing other components in the specification, internally and externally. The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules. For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.", - "required": [ - "$ref" - ], - "additionalProperties": false, - "properties": { - "$ref": { - "type": "string" - }, - "summary": { - "type": "string" - }, - "description": { - "type": "string" - } - } - }, - "schema": { - "type": "object", - "description": "The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00. For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "nullable": { - "type": "boolean" - }, - "discriminator": { - "$ref": "#/definitions/discriminator" - }, - "readOnly": { - "type": "boolean" - }, - "writeOnly": { - "type": "boolean" - }, - "xml": { - "$ref": "#/definitions/xml" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - }, - "example": { - "$ref": "#/definitions/any" - }, - "deprecated": { - "type": "boolean" - }, - "title": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/title" - }, - "multipleOf": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" - }, - "maximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" - }, - "exclusiveMaximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" - }, - "minimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" - }, - "exclusiveMinimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" - }, - "maxLength": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maxLength" - }, - "minLength": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minLength" - }, - "pattern": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" - }, - "maxItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maxItems" - }, - "minItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minItems" - }, - "uniqueItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" - }, - "maxProperties": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maxProperties" - }, - "minProperties": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minProperties" - }, - "required": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/required" - }, - "enum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" - }, - "type": { - "type": "string" - }, - "allOf": { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - }, - "oneOf": { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - }, - "anyOf": { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - }, - "not": { - "$ref": "#/definitions/schema" - }, - "items": { - "anyOf": [ - { - "$ref": "#/definitions/schemaOrReference" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/schemaOrReference" - }, - "minItems": 1 - } - ] - }, - "properties": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/schemaOrReference" - } - }, - "additionalProperties": { - "oneOf": [ - { - "$ref": "#/definitions/schemaOrReference" - }, - { - "type": "boolean" - } - ] - }, - "default": { - "$ref": "#/definitions/defaultType" - }, - "description": { - "type": "string" - }, - "format": { - "type": "string" - } - } - }, - "discriminator": { - "type": "object", - "description": "When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. When using the discriminator, _inline_ schemas will not be considered.", - "required": [ - "propertyName" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "propertyName": { - "type": "string" - }, - "mapping": { - "$ref": "#/definitions/strings" - } - } - }, - "xml": { - "type": "object", - "description": "A metadata object that allows for more fine-tuned XML model definitions. When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. See examples for expected behavior.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "name": { - "type": "string" - }, - "namespace": { - "type": "string" - }, - "prefix": { - "type": "string" - }, - "attribute": { - "type": "boolean" - }, - "wrapped": { - "type": "boolean" - } - } - }, - "securityScheme": { - "type": "object", - "description": "Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2's common flows (implicit, password, application and access code) as defined in RFC6749, and OpenID Connect. Please note that currently (2019) the implicit flow is about to be deprecated OAuth 2.0 Security Best Current Practice. Recommended for most use case is Authorization Code Grant flow with PKCE.", - "required": [ - "type" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "type": { - "type": "string" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - }, - "in": { - "type": "string" - }, - "scheme": { - "type": "string" - }, - "bearerFormat": { - "type": "string" - }, - "flows": { - "$ref": "#/definitions/oauthFlows" - }, - "openIdConnectUrl": { - "type": "string" - } - } - }, - "oauthFlows": { - "type": "object", - "description": "Allows configuration of the supported OAuth Flows.", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "implicit": { - "$ref": "#/definitions/oauthFlow" - }, - "password": { - "$ref": "#/definitions/oauthFlow" - }, - "clientCredentials": { - "$ref": "#/definitions/oauthFlow" - }, - "authorizationCode": { - "$ref": "#/definitions/oauthFlow" - } - } - }, - "oauthFlow": { - "type": "object", - "description": "Configuration details for a supported OAuth Flow", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/specificationExtension" - } - }, - "properties": { - "authorizationUrl": { - "type": "string" - }, - "tokenUrl": { - "type": "string" - }, - "refreshUrl": { - "type": "string" - }, - "scopes": { - "$ref": "#/definitions/strings" - } - } - }, - "securityRequirement": { - "type": "object", - "description": "Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object. Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. When a list of Security Requirement Objects is defined on the OpenAPI Object or Operation Object, only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request.", - "additionalProperties": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - }, - "anyOrExpression": { - "oneOf": [ - { - "$ref": "#/definitions/any" - }, - { - "$ref": "#/definitions/expression" - } - ] - }, - "callbackOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/callback" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "exampleOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/example" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "headerOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/header" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "linkOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/link" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "parameterOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/parameter" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "requestBodyOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/requestBody" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "responseOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/response" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "schemaOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/schema" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "securitySchemeOrReference": { - "oneOf": [ - { - "$ref": "#/definitions/securityScheme" - }, - { - "$ref": "#/definitions/reference" - } - ] - }, - "callbacksOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/callbackOrReference" - } - }, - "encodings": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/encoding" - } - }, - "examplesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/exampleOrReference" - } - }, - "headersOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/headerOrReference" - } - }, - "linksOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/linkOrReference" - } - }, - "mediaTypes": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/mediaType" - } - }, - "parametersOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/parameterOrReference" - } - }, - "requestBodiesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/requestBodyOrReference" - } - }, - "responsesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/responseOrReference" - } - }, - "schemasOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/schemaOrReference" - } - }, - "securitySchemesOrReferences": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/securitySchemeOrReference" - } - }, - "serverVariables": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/serverVariable" - } - }, - "strings": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "object": { - "type": "object", - "additionalProperties": true - }, - "any": { - "additionalProperties": true - }, - "expression": { - "type": "object", - "additionalProperties": true - }, - "specificationExtension": { - "description": "Any property starting with x- is valid.", - "oneOf": [ - { - "type": "null" - }, - { - "type": "number" - }, - { - "type": "boolean" - }, - { - "type": "string" - }, - { - "type": "object" - }, - { - "type": "array" - } - ] - }, - "defaultType": { - "oneOf": [ - { - "type": "null" - }, - { - "type": "array" - }, - { - "type": "object" - }, - { - "type": "number" - }, - { - "type": "boolean" - }, - { - "type": "string" - } - ] - } - } -} diff --git a/vendor/github.com/google/go-cmp/cmp/compare.go b/vendor/github.com/google/go-cmp/cmp/compare.go index 087320da7..0f5b8a48c 100644 --- a/vendor/github.com/google/go-cmp/cmp/compare.go +++ b/vendor/github.com/google/go-cmp/cmp/compare.go @@ -5,7 +5,7 @@ // Package cmp determines equality of values. // // This package is intended to be a more powerful and safer alternative to -// reflect.DeepEqual for comparing whether two values are semantically equal. +// [reflect.DeepEqual] for comparing whether two values are semantically equal. // It is intended to only be used in tests, as performance is not a goal and // it may panic if it cannot compare the values. Its propensity towards // panicking means that its unsuitable for production environments where a @@ -18,16 +18,17 @@ // For example, an equality function may report floats as equal so long as // they are within some tolerance of each other. // -// - Types with an Equal method may use that method to determine equality. -// This allows package authors to determine the equality operation -// for the types that they define. +// - Types with an Equal method (e.g., [time.Time.Equal]) may use that method +// to determine equality. This allows package authors to determine +// the equality operation for the types that they define. // // - If no custom equality functions are used and no Equal method is defined, // equality is determined by recursively comparing the primitive kinds on -// both values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, +// both values, much like [reflect.DeepEqual]. Unlike [reflect.DeepEqual], // unexported fields are not compared by default; they result in panics -// unless suppressed by using an Ignore option (see cmpopts.IgnoreUnexported) -// or explicitly compared using the Exporter option. +// unless suppressed by using an [Ignore] option +// (see [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported]) +// or explicitly compared using the [Exporter] option. package cmp import ( @@ -45,14 +46,14 @@ import ( // Equal reports whether x and y are equal by recursively applying the // following rules in the given order to x and y and all of their sub-values: // -// - Let S be the set of all Ignore, Transformer, and Comparer options that +// - Let S be the set of all [Ignore], [Transformer], and [Comparer] options that // remain after applying all path filters, value filters, and type filters. -// If at least one Ignore exists in S, then the comparison is ignored. -// If the number of Transformer and Comparer options in S is non-zero, +// If at least one [Ignore] exists in S, then the comparison is ignored. +// If the number of [Transformer] and [Comparer] options in S is non-zero, // then Equal panics because it is ambiguous which option to use. -// If S contains a single Transformer, then use that to transform +// If S contains a single [Transformer], then use that to transform // the current values and recursively call Equal on the output values. -// If S contains a single Comparer, then use that to compare the current values. +// If S contains a single [Comparer], then use that to compare the current values. // Otherwise, evaluation proceeds to the next rule. // // - If the values have an Equal method of the form "(T) Equal(T) bool" or @@ -66,21 +67,22 @@ import ( // Functions are only equal if they are both nil, otherwise they are unequal. // // Structs are equal if recursively calling Equal on all fields report equal. -// If a struct contains unexported fields, Equal panics unless an Ignore option -// (e.g., cmpopts.IgnoreUnexported) ignores that field or the Exporter option -// explicitly permits comparing the unexported field. +// If a struct contains unexported fields, Equal panics unless an [Ignore] option +// (e.g., [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported]) ignores that field +// or the [Exporter] option explicitly permits comparing the unexported field. // // Slices are equal if they are both nil or both non-nil, where recursively // calling Equal on all non-ignored slice or array elements report equal. // Empty non-nil slices and nil slices are not equal; to equate empty slices, -// consider using cmpopts.EquateEmpty. +// consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty]. // // Maps are equal if they are both nil or both non-nil, where recursively // calling Equal on all non-ignored map entries report equal. // Map keys are equal according to the == operator. -// To use custom comparisons for map keys, consider using cmpopts.SortMaps. +// To use custom comparisons for map keys, consider using +// [github.com/google/go-cmp/cmp/cmpopts.SortMaps]. // Empty non-nil maps and nil maps are not equal; to equate empty maps, -// consider using cmpopts.EquateEmpty. +// consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty]. // // Pointers and interfaces are equal if they are both nil or both non-nil, // where they have the same underlying concrete type and recursively diff --git a/vendor/github.com/google/go-cmp/cmp/export.go b/vendor/github.com/google/go-cmp/cmp/export.go new file mode 100644 index 000000000..29f82fe6b --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/export.go @@ -0,0 +1,31 @@ +// Copyright 2017, 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 cmp + +import ( + "reflect" + "unsafe" +) + +// retrieveUnexportedField uses unsafe to forcibly retrieve any field from +// a struct such that the value has read-write permissions. +// +// The parent struct, v, must be addressable, while f must be a StructField +// describing the field to retrieve. If addr is false, +// then the returned value will be shallowed copied to be non-addressable. +func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value { + ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem() + if !addr { + // A field is addressable if and only if the struct is addressable. + // If the original parent value was not addressable, shallow copy the + // value to make it non-addressable to avoid leaking an implementation + // detail of how forcibly exporting a field works. + if ve.Kind() == reflect.Interface && ve.IsNil() { + return reflect.Zero(f.Type) + } + return reflect.ValueOf(ve.Interface()).Convert(f.Type) + } + return ve +} diff --git a/vendor/github.com/google/go-cmp/cmp/export_panic.go b/vendor/github.com/google/go-cmp/cmp/export_panic.go deleted file mode 100644 index ae851fe53..000000000 --- a/vendor/github.com/google/go-cmp/cmp/export_panic.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017, 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. - -//go:build purego -// +build purego - -package cmp - -import "reflect" - -const supportExporters = false - -func retrieveUnexportedField(reflect.Value, reflect.StructField, bool) reflect.Value { - panic("no support for forcibly accessing unexported fields") -} diff --git a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go b/vendor/github.com/google/go-cmp/cmp/export_unsafe.go deleted file mode 100644 index e2c0f74e8..000000000 --- a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017, 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. - -//go:build !purego -// +build !purego - -package cmp - -import ( - "reflect" - "unsafe" -) - -const supportExporters = true - -// retrieveUnexportedField uses unsafe to forcibly retrieve any field from -// a struct such that the value has read-write permissions. -// -// The parent struct, v, must be addressable, while f must be a StructField -// describing the field to retrieve. If addr is false, -// then the returned value will be shallowed copied to be non-addressable. -func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value { - ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem() - if !addr { - // A field is addressable if and only if the struct is addressable. - // If the original parent value was not addressable, shallow copy the - // value to make it non-addressable to avoid leaking an implementation - // detail of how forcibly exporting a field works. - if ve.Kind() == reflect.Interface && ve.IsNil() { - return reflect.Zero(f.Type) - } - return reflect.ValueOf(ve.Interface()).Convert(f.Type) - } - return ve -} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer.go new file mode 100644 index 000000000..e5dfff69a --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer.go @@ -0,0 +1,34 @@ +// Copyright 2018, 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 value + +import ( + "reflect" + "unsafe" +) + +// Pointer is an opaque typed pointer and is guaranteed to be comparable. +type Pointer struct { + p unsafe.Pointer + t reflect.Type +} + +// PointerOf returns a Pointer from v, which must be a +// reflect.Ptr, reflect.Slice, or reflect.Map. +func PointerOf(v reflect.Value) Pointer { + // The proper representation of a pointer is unsafe.Pointer, + // which is necessary if the GC ever uses a moving collector. + return Pointer{unsafe.Pointer(v.Pointer()), v.Type()} +} + +// IsNil reports whether the pointer is nil. +func (p Pointer) IsNil() bool { + return p.p == nil +} + +// Uintptr returns the pointer as a uintptr. +func (p Pointer) Uintptr() uintptr { + return uintptr(p.p) +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go deleted file mode 100644 index 1a71bfcbd..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2018, 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. - -//go:build purego -// +build purego - -package value - -import "reflect" - -// Pointer is an opaque typed pointer and is guaranteed to be comparable. -type Pointer struct { - p uintptr - t reflect.Type -} - -// PointerOf returns a Pointer from v, which must be a -// reflect.Ptr, reflect.Slice, or reflect.Map. -func PointerOf(v reflect.Value) Pointer { - // NOTE: Storing a pointer as an uintptr is technically incorrect as it - // assumes that the GC implementation does not use a moving collector. - return Pointer{v.Pointer(), v.Type()} -} - -// IsNil reports whether the pointer is nil. -func (p Pointer) IsNil() bool { - return p.p == 0 -} - -// Uintptr returns the pointer as a uintptr. -func (p Pointer) Uintptr() uintptr { - return p.p -} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go deleted file mode 100644 index 16e6860af..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2018, 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. - -//go:build !purego -// +build !purego - -package value - -import ( - "reflect" - "unsafe" -) - -// Pointer is an opaque typed pointer and is guaranteed to be comparable. -type Pointer struct { - p unsafe.Pointer - t reflect.Type -} - -// PointerOf returns a Pointer from v, which must be a -// reflect.Ptr, reflect.Slice, or reflect.Map. -func PointerOf(v reflect.Value) Pointer { - // The proper representation of a pointer is unsafe.Pointer, - // which is necessary if the GC ever uses a moving collector. - return Pointer{unsafe.Pointer(v.Pointer()), v.Type()} -} - -// IsNil reports whether the pointer is nil. -func (p Pointer) IsNil() bool { - return p.p == nil -} - -// Uintptr returns the pointer as a uintptr. -func (p Pointer) Uintptr() uintptr { - return uintptr(p.p) -} diff --git a/vendor/github.com/google/go-cmp/cmp/options.go b/vendor/github.com/google/go-cmp/cmp/options.go index 1f9ca9c48..754496f3b 100644 --- a/vendor/github.com/google/go-cmp/cmp/options.go +++ b/vendor/github.com/google/go-cmp/cmp/options.go @@ -13,15 +13,15 @@ import ( "github.com/google/go-cmp/cmp/internal/function" ) -// Option configures for specific behavior of Equal and Diff. In particular, -// the fundamental Option functions (Ignore, Transformer, and Comparer), +// Option configures for specific behavior of [Equal] and [Diff]. In particular, +// the fundamental Option functions ([Ignore], [Transformer], and [Comparer]), // configure how equality is determined. // -// The fundamental options may be composed with filters (FilterPath and -// FilterValues) to control the scope over which they are applied. +// The fundamental options may be composed with filters ([FilterPath] and +// [FilterValues]) to control the scope over which they are applied. // -// The cmp/cmpopts package provides helper functions for creating options that -// may be used with Equal and Diff. +// The [github.com/google/go-cmp/cmp/cmpopts] package provides helper functions +// for creating options that may be used with [Equal] and [Diff]. type Option interface { // filter applies all filters and returns the option that remains. // Each option may only read s.curPath and call s.callTTBFunc. @@ -56,9 +56,9 @@ type core struct{} func (core) isCore() {} -// Options is a list of Option values that also satisfies the Option interface. +// Options is a list of [Option] values that also satisfies the [Option] interface. // Helper comparison packages may return an Options value when packing multiple -// Option values into a single Option. When this package processes an Options, +// [Option] values into a single [Option]. When this package processes an Options, // it will be implicitly expanded into a flat list. // // Applying a filter on an Options is equivalent to applying that same filter @@ -105,16 +105,16 @@ func (opts Options) String() string { return fmt.Sprintf("Options{%s}", strings.Join(ss, ", ")) } -// FilterPath returns a new Option where opt is only evaluated if filter f -// returns true for the current Path in the value tree. +// FilterPath returns a new [Option] where opt is only evaluated if filter f +// returns true for the current [Path] in the value tree. // // This filter is called even if a slice element or map entry is missing and // provides an opportunity to ignore such cases. The filter function must be // symmetric such that the filter result is identical regardless of whether the // missing value is from x or y. // -// The option passed in may be an Ignore, Transformer, Comparer, Options, or -// a previously filtered Option. +// The option passed in may be an [Ignore], [Transformer], [Comparer], [Options], or +// a previously filtered [Option]. func FilterPath(f func(Path) bool, opt Option) Option { if f == nil { panic("invalid path filter function") @@ -142,7 +142,7 @@ func (f pathFilter) String() string { return fmt.Sprintf("FilterPath(%s, %v)", function.NameOf(reflect.ValueOf(f.fnc)), f.opt) } -// FilterValues returns a new Option where opt is only evaluated if filter f, +// FilterValues returns a new [Option] where opt is only evaluated if filter f, // which is a function of the form "func(T, T) bool", returns true for the // current pair of values being compared. If either value is invalid or // the type of the values is not assignable to T, then this filter implicitly @@ -154,8 +154,8 @@ func (f pathFilter) String() string { // If T is an interface, it is possible that f is called with two values with // different concrete types that both implement T. // -// The option passed in may be an Ignore, Transformer, Comparer, Options, or -// a previously filtered Option. +// The option passed in may be an [Ignore], [Transformer], [Comparer], [Options], or +// a previously filtered [Option]. func FilterValues(f interface{}, opt Option) Option { v := reflect.ValueOf(f) if !function.IsType(v.Type(), function.ValueFilter) || v.IsNil() { @@ -192,9 +192,9 @@ func (f valuesFilter) String() string { return fmt.Sprintf("FilterValues(%s, %v)", function.NameOf(f.fnc), f.opt) } -// Ignore is an Option that causes all comparisons to be ignored. -// This value is intended to be combined with FilterPath or FilterValues. -// It is an error to pass an unfiltered Ignore option to Equal. +// Ignore is an [Option] that causes all comparisons to be ignored. +// This value is intended to be combined with [FilterPath] or [FilterValues]. +// It is an error to pass an unfiltered Ignore option to [Equal]. func Ignore() Option { return ignore{} } type ignore struct{ core } @@ -234,6 +234,8 @@ func (validator) apply(s *state, vx, vy reflect.Value) { name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType if _, ok := reflect.New(t).Interface().(error); ok { help = "consider using cmpopts.EquateErrors to compare error values" + } else if t.Comparable() { + help = "consider using cmpopts.EquateComparable to compare comparable Go types" } } else { // Unnamed type with unexported fields. Derive PkgPath from field. @@ -254,7 +256,7 @@ const identRx = `[_\p{L}][_\p{L}\p{N}]*` var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`) -// Transformer returns an Option that applies a transformation function that +// Transformer returns an [Option] that applies a transformation function that // converts values of a certain type into that of another. // // The transformer f must be a function "func(T) R" that converts values of @@ -265,13 +267,14 @@ var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`) // same transform to the output of itself (e.g., in the case where the // input and output types are the same), an implicit filter is added such that // a transformer is applicable only if that exact transformer is not already -// in the tail of the Path since the last non-Transform step. +// in the tail of the [Path] since the last non-[Transform] step. // For situations where the implicit filter is still insufficient, -// consider using cmpopts.AcyclicTransformer, which adds a filter -// to prevent the transformer from being recursively applied upon itself. +// consider using [github.com/google/go-cmp/cmp/cmpopts.AcyclicTransformer], +// which adds a filter to prevent the transformer from +// being recursively applied upon itself. // -// The name is a user provided label that is used as the Transform.Name in the -// transformation PathStep (and eventually shown in the Diff output). +// The name is a user provided label that is used as the [Transform.Name] in the +// transformation [PathStep] (and eventually shown in the [Diff] output). // The name must be a valid identifier or qualified identifier in Go syntax. // If empty, an arbitrary name is used. func Transformer(name string, f interface{}) Option { @@ -329,7 +332,7 @@ func (tr transformer) String() string { return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc)) } -// Comparer returns an Option that determines whether two values are equal +// Comparer returns an [Option] that determines whether two values are equal // to each other. // // The comparer f must be a function "func(T, T) bool" and is implicitly @@ -377,35 +380,32 @@ func (cm comparer) String() string { return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc)) } -// Exporter returns an Option that specifies whether Equal is allowed to +// Exporter returns an [Option] that specifies whether [Equal] is allowed to // introspect into the unexported fields of certain struct types. // // Users of this option must understand that comparing on unexported fields // from external packages is not safe since changes in the internal -// implementation of some external package may cause the result of Equal +// implementation of some external package may cause the result of [Equal] // to unexpectedly change. However, it may be valid to use this option on types // defined in an internal package where the semantic meaning of an unexported // field is in the control of the user. // -// In many cases, a custom Comparer should be used instead that defines +// In many cases, a custom [Comparer] should be used instead that defines // equality as a function of the public API of a type rather than the underlying // unexported implementation. // -// For example, the reflect.Type documentation defines equality to be determined +// For example, the [reflect.Type] documentation defines equality to be determined // by the == operator on the interface (essentially performing a shallow pointer -// comparison) and most attempts to compare *regexp.Regexp types are interested +// comparison) and most attempts to compare *[regexp.Regexp] types are interested // in only checking that the regular expression strings are equal. -// Both of these are accomplished using Comparers: +// Both of these are accomplished using [Comparer] options: // // Comparer(func(x, y reflect.Type) bool { return x == y }) // Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() }) // -// In other cases, the cmpopts.IgnoreUnexported option can be used to ignore -// all unexported fields on specified struct types. +// In other cases, the [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported] +// option can be used to ignore all unexported fields on specified struct types. func Exporter(f func(reflect.Type) bool) Option { - if !supportExporters { - panic("Exporter is not supported on purego builds") - } return exporter(f) } @@ -415,10 +415,10 @@ func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableO panic("not implemented") } -// AllowUnexported returns an Options that allows Equal to forcibly introspect +// AllowUnexported returns an [Option] that allows [Equal] to forcibly introspect // unexported fields of the specified struct types. // -// See Exporter for the proper use of this option. +// See [Exporter] for the proper use of this option. func AllowUnexported(types ...interface{}) Option { m := make(map[reflect.Type]bool) for _, typ := range types { @@ -432,7 +432,7 @@ func AllowUnexported(types ...interface{}) Option { } // Result represents the comparison result for a single node and -// is provided by cmp when calling Report (see Reporter). +// is provided by cmp when calling Report (see [Reporter]). type Result struct { _ [0]func() // Make Result incomparable flags resultFlags @@ -445,7 +445,7 @@ func (r Result) Equal() bool { } // ByIgnore reports whether the node is equal because it was ignored. -// This never reports true if Equal reports false. +// This never reports true if [Result.Equal] reports false. func (r Result) ByIgnore() bool { return r.flags&reportByIgnore != 0 } @@ -455,7 +455,7 @@ func (r Result) ByMethod() bool { return r.flags&reportByMethod != 0 } -// ByFunc reports whether a Comparer function determined equality. +// ByFunc reports whether a [Comparer] function determined equality. func (r Result) ByFunc() bool { return r.flags&reportByFunc != 0 } @@ -478,7 +478,7 @@ const ( reportByCycle ) -// Reporter is an Option that can be passed to Equal. When Equal traverses +// Reporter is an [Option] that can be passed to [Equal]. When [Equal] traverses // the value trees, it calls PushStep as it descends into each node in the // tree and PopStep as it ascend out of the node. The leaves of the tree are // either compared (determined to be equal or not equal) or ignored and reported diff --git a/vendor/github.com/google/go-cmp/cmp/path.go b/vendor/github.com/google/go-cmp/cmp/path.go index a0a588502..c3c145642 100644 --- a/vendor/github.com/google/go-cmp/cmp/path.go +++ b/vendor/github.com/google/go-cmp/cmp/path.go @@ -14,9 +14,9 @@ import ( "github.com/google/go-cmp/cmp/internal/value" ) -// Path is a list of PathSteps describing the sequence of operations to get +// Path is a list of [PathStep] describing the sequence of operations to get // from some root type to the current position in the value tree. -// The first Path element is always an operation-less PathStep that exists +// The first Path element is always an operation-less [PathStep] that exists // simply to identify the initial type. // // When traversing structs with embedded structs, the embedded struct will @@ -29,8 +29,13 @@ type Path []PathStep // a value's tree structure. Users of this package never need to implement // these types as values of this type will be returned by this package. // -// Implementations of this interface are -// StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform. +// Implementations of this interface: +// - [StructField] +// - [SliceIndex] +// - [MapIndex] +// - [Indirect] +// - [TypeAssertion] +// - [Transform] type PathStep interface { String() string @@ -70,8 +75,9 @@ func (pa *Path) pop() { *pa = (*pa)[:len(*pa)-1] } -// Last returns the last PathStep in the Path. -// If the path is empty, this returns a non-nil PathStep that reports a nil Type. +// Last returns the last [PathStep] in the Path. +// If the path is empty, this returns a non-nil [PathStep] +// that reports a nil [PathStep.Type]. func (pa Path) Last() PathStep { return pa.Index(-1) } @@ -79,7 +85,8 @@ func (pa Path) Last() PathStep { // Index returns the ith step in the Path and supports negative indexing. // A negative index starts counting from the tail of the Path such that -1 // refers to the last step, -2 refers to the second-to-last step, and so on. -// If index is invalid, this returns a non-nil PathStep that reports a nil Type. +// If index is invalid, this returns a non-nil [PathStep] +// that reports a nil [PathStep.Type]. func (pa Path) Index(i int) PathStep { if i < 0 { i = len(pa) + i @@ -168,7 +175,8 @@ func (ps pathStep) String() string { return fmt.Sprintf("{%s}", s) } -// StructField represents a struct field access on a field called Name. +// StructField is a [PathStep] that represents a struct field access +// on a field called [StructField.Name]. type StructField struct{ *structField } type structField struct { pathStep @@ -204,10 +212,11 @@ func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) } func (sf StructField) Name() string { return sf.name } // Index is the index of the field in the parent struct type. -// See reflect.Type.Field. +// See [reflect.Type.Field]. func (sf StructField) Index() int { return sf.idx } -// SliceIndex is an index operation on a slice or array at some index Key. +// SliceIndex is a [PathStep] that represents an index operation on +// a slice or array at some index [SliceIndex.Key]. type SliceIndex struct{ *sliceIndex } type sliceIndex struct { pathStep @@ -247,12 +256,12 @@ func (si SliceIndex) Key() int { // all of the indexes to be shifted. If an index is -1, then that // indicates that the element does not exist in the associated slice. // -// Key is guaranteed to return -1 if and only if the indexes returned -// by SplitKeys are not the same. SplitKeys will never return -1 for +// [SliceIndex.Key] is guaranteed to return -1 if and only if the indexes +// returned by SplitKeys are not the same. SplitKeys will never return -1 for // both indexes. func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey } -// MapIndex is an index operation on a map at some index Key. +// MapIndex is a [PathStep] that represents an index operation on a map at some index Key. type MapIndex struct{ *mapIndex } type mapIndex struct { pathStep @@ -266,7 +275,7 @@ func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", // Key is the value of the map key. func (mi MapIndex) Key() reflect.Value { return mi.key } -// Indirect represents pointer indirection on the parent type. +// Indirect is a [PathStep] that represents pointer indirection on the parent type. type Indirect struct{ *indirect } type indirect struct { pathStep @@ -276,7 +285,7 @@ func (in Indirect) Type() reflect.Type { return in.typ } func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy } func (in Indirect) String() string { return "*" } -// TypeAssertion represents a type assertion on an interface. +// TypeAssertion is a [PathStep] that represents a type assertion on an interface. type TypeAssertion struct{ *typeAssertion } type typeAssertion struct { pathStep @@ -286,7 +295,8 @@ func (ta TypeAssertion) Type() reflect.Type { return ta.typ } func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy } func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", value.TypeString(ta.typ, false)) } -// Transform is a transformation from the parent type to the current type. +// Transform is a [PathStep] that represents a transformation +// from the parent type to the current type. type Transform struct{ *transform } type transform struct { pathStep @@ -297,13 +307,13 @@ func (tf Transform) Type() reflect.Type { return tf.typ } func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy } func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) } -// Name is the name of the Transformer. +// Name is the name of the [Transformer]. func (tf Transform) Name() string { return tf.trans.name } // Func is the function pointer to the transformer function. func (tf Transform) Func() reflect.Value { return tf.trans.fnc } -// Option returns the originally constructed Transformer option. +// Option returns the originally constructed [Transformer] option. // The == operator can be used to detect the exact option used. func (tf Transform) Option() Option { return tf.trans } diff --git a/vendor/github.com/google/go-cmp/cmp/report_reflect.go b/vendor/github.com/google/go-cmp/cmp/report_reflect.go index 2ab41fad3..e39f42284 100644 --- a/vendor/github.com/google/go-cmp/cmp/report_reflect.go +++ b/vendor/github.com/google/go-cmp/cmp/report_reflect.go @@ -199,7 +199,7 @@ func (opts formatOptions) FormatValue(v reflect.Value, parentKind reflect.Kind, break } sf := t.Field(i) - if supportExporters && !isExported(sf.Name) { + if !isExported(sf.Name) { vv = retrieveUnexportedField(v, sf, true) } s := opts.WithTypeMode(autoType).FormatValue(vv, t.Kind(), ptrs) diff --git a/vendor/github.com/google/pprof/profile/encode.go b/vendor/github.com/google/pprof/profile/encode.go index c8a1beb8a..860bb304c 100644 --- a/vendor/github.com/google/pprof/profile/encode.go +++ b/vendor/github.com/google/pprof/profile/encode.go @@ -258,10 +258,10 @@ func (p *Profile) postDecode() error { // If this a main linux kernel mapping with a relocation symbol suffix // ("[kernel.kallsyms]_text"), extract said suffix. // It is fairly hacky to handle at this level, but the alternatives appear even worse. - if strings.HasPrefix(m.File, "[kernel.kallsyms]") { - m.KernelRelocationSymbol = strings.ReplaceAll(m.File, "[kernel.kallsyms]", "") + const prefix = "[kernel.kallsyms]" + if strings.HasPrefix(m.File, prefix) { + m.KernelRelocationSymbol = m.File[len(prefix):] } - } functions := make(map[uint64]*Function, len(p.Function)) @@ -530,6 +530,7 @@ func (p *Line) decoder() []decoder { func (p *Line) encode(b *buffer) { encodeUint64Opt(b, 1, p.functionIDX) encodeInt64Opt(b, 2, p.Line) + encodeInt64Opt(b, 3, p.Column) } var lineDecoder = []decoder{ @@ -538,6 +539,8 @@ var lineDecoder = []decoder{ func(b *buffer, m message) error { return decodeUint64(b, &m.(*Line).functionIDX) }, // optional int64 line = 2 func(b *buffer, m message) error { return decodeInt64(b, &m.(*Line).Line) }, + // optional int64 column = 3 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Line).Column) }, } func (p *Function) decoder() []decoder { diff --git a/vendor/github.com/google/pprof/profile/legacy_java_profile.go b/vendor/github.com/google/pprof/profile/legacy_java_profile.go index 91f45e53c..4580bab18 100644 --- a/vendor/github.com/google/pprof/profile/legacy_java_profile.go +++ b/vendor/github.com/google/pprof/profile/legacy_java_profile.go @@ -56,7 +56,7 @@ func javaCPUProfile(b []byte, period int64, parse func(b []byte) (uint64, []byte } // Strip out addresses for better merge. - if err = p.Aggregate(true, true, true, true, false); err != nil { + if err = p.Aggregate(true, true, true, true, false, false); err != nil { return nil, err } @@ -99,7 +99,7 @@ func parseJavaProfile(b []byte) (*Profile, error) { } // Strip out addresses for better merge. - if err = p.Aggregate(true, true, true, true, false); err != nil { + if err = p.Aggregate(true, true, true, true, false, false); err != nil { return nil, err } diff --git a/vendor/github.com/google/pprof/profile/merge.go b/vendor/github.com/google/pprof/profile/merge.go index 4b66282cb..eee0132e7 100644 --- a/vendor/github.com/google/pprof/profile/merge.go +++ b/vendor/github.com/google/pprof/profile/merge.go @@ -326,12 +326,13 @@ func (l *Location) key() locationKey { key.addr -= l.Mapping.Start key.mappingID = l.Mapping.ID } - lines := make([]string, len(l.Line)*2) + lines := make([]string, len(l.Line)*3) for i, line := range l.Line { if line.Function != nil { lines[i*2] = strconv.FormatUint(line.Function.ID, 16) } lines[i*2+1] = strconv.FormatInt(line.Line, 16) + lines[i*2+2] = strconv.FormatInt(line.Column, 16) } key.lines = strings.Join(lines, "|") return key @@ -418,6 +419,7 @@ func (pm *profileMerger) mapLine(src Line) Line { ln := Line{ Function: pm.mapFunction(src.Function), Line: src.Line, + Column: src.Column, } return ln } diff --git a/vendor/github.com/google/pprof/profile/profile.go b/vendor/github.com/google/pprof/profile/profile.go index 60ef7e926..62df80a55 100644 --- a/vendor/github.com/google/pprof/profile/profile.go +++ b/vendor/github.com/google/pprof/profile/profile.go @@ -145,6 +145,7 @@ type Location struct { type Line struct { Function *Function Line int64 + Column int64 functionIDX uint64 } @@ -436,7 +437,7 @@ func (p *Profile) CheckValid() error { // Aggregate merges the locations in the profile into equivalence // classes preserving the request attributes. It also updates the // samples to point to the merged locations. -func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, address bool) error { +func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, columnnumber, address bool) error { for _, m := range p.Mapping { m.HasInlineFrames = m.HasInlineFrames && inlineFrame m.HasFunctions = m.HasFunctions && function @@ -458,7 +459,7 @@ func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, address } // Aggregate locations - if !inlineFrame || !address || !linenumber { + if !inlineFrame || !address || !linenumber || !columnnumber { for _, l := range p.Location { if !inlineFrame && len(l.Line) > 1 { l.Line = l.Line[len(l.Line)-1:] @@ -466,6 +467,12 @@ func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, address if !linenumber { for i := range l.Line { l.Line[i].Line = 0 + l.Line[i].Column = 0 + } + } + if !columnnumber { + for i := range l.Line { + l.Line[i].Column = 0 } } if !address { @@ -627,10 +634,11 @@ func (l *Location) string() string { for li := range l.Line { lnStr := "??" if fn := l.Line[li].Function; fn != nil { - lnStr = fmt.Sprintf("%s %s:%d s=%d", + lnStr = fmt.Sprintf("%s %s:%d:%d s=%d", fn.Name, fn.Filename, l.Line[li].Line, + l.Line[li].Column, fn.StartLine) if fn.Name != fn.SystemName { lnStr = lnStr + "(" + fn.SystemName + ")" diff --git a/vendor/github.com/google/s2a-go/README.md b/vendor/github.com/google/s2a-go/README.md index d566950f3..fe0f5c1da 100644 --- a/vendor/github.com/google/s2a-go/README.md +++ b/vendor/github.com/google/s2a-go/README.md @@ -10,8 +10,5 @@ Session Agent during the TLS handshake, and to encrypt traffic to the peer after the TLS handshake is complete. This repository contains the source code for the Secure Session Agent's Go -client libraries, which allow gRPC-Go applications to use the Secure Session -Agent. This repository supports the Bazel and Golang build systems. - -All code in this repository is experimental and subject to change. We do not -guarantee API stability at this time. +client libraries, which allow gRPC and HTTP Go applications to use the Secure Session +Agent. diff --git a/vendor/github.com/google/s2a-go/internal/handshaker/service/service.go b/vendor/github.com/google/s2a-go/internal/handshaker/service/service.go index 49573af88..ed4496537 100644 --- a/vendor/github.com/google/s2a-go/internal/handshaker/service/service.go +++ b/vendor/github.com/google/s2a-go/internal/handshaker/service/service.go @@ -21,50 +21,27 @@ package service import ( "context" - "net" - "os" - "strings" "sync" - "time" - "google.golang.org/appengine" - "google.golang.org/appengine/socket" grpc "google.golang.org/grpc" - "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" ) -// An environment variable, if true, opportunistically use AppEngine-specific dialer to call S2A. -const enableAppEngineDialerEnv = "S2A_ENABLE_APP_ENGINE_DIALER" - var ( - // appEngineDialerHook is an AppEngine-specific dial option that is set - // during init time. If nil, then the application is not running on Google - // AppEngine. - appEngineDialerHook func(context.Context) grpc.DialOption // mu guards hsConnMap and hsDialer. mu sync.Mutex // hsConnMap represents a mapping from an S2A handshaker service address // to a corresponding connection to an S2A handshaker service instance. hsConnMap = make(map[string]*grpc.ClientConn) // hsDialer will be reassigned in tests. - hsDialer = grpc.Dial + hsDialer = grpc.DialContext ) -func init() { - if !appengine.IsAppEngine() && !appengine.IsDevAppServer() { - return - } - appEngineDialerHook = func(ctx context.Context) grpc.DialOption { - return grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { - return socket.DialTimeout(ctx, "tcp", addr, timeout) - }) - } -} - // Dial dials the S2A handshaker service. If a connection has already been // established, this function returns it. Otherwise, a new connection is // created. -func Dial(handshakerServiceAddress string) (*grpc.ClientConn, error) { +func Dial(ctx context.Context, handshakerServiceAddress string, transportCreds credentials.TransportCredentials) (*grpc.ClientConn, error) { mu.Lock() defer mu.Unlock() @@ -72,17 +49,14 @@ func Dial(handshakerServiceAddress string) (*grpc.ClientConn, error) { if !ok { // Create a new connection to the S2A handshaker service. Note that // this connection stays open until the application is closed. - grpcOpts := []grpc.DialOption{ - grpc.WithInsecure(), - } - if enableAppEngineDialer() && appEngineDialerHook != nil { - if grpclog.V(1) { - grpclog.Info("Using AppEngine-specific dialer to talk to S2A.") - } - grpcOpts = append(grpcOpts, appEngineDialerHook(context.Background())) + var grpcOpts []grpc.DialOption + if transportCreds != nil { + grpcOpts = append(grpcOpts, grpc.WithTransportCredentials(transportCreds)) + } else { + grpcOpts = append(grpcOpts, grpc.WithTransportCredentials(insecure.NewCredentials())) } var err error - hsConn, err = hsDialer(handshakerServiceAddress, grpcOpts...) + hsConn, err = hsDialer(ctx, handshakerServiceAddress, grpcOpts...) if err != nil { return nil, err } @@ -90,10 +64,3 @@ func Dial(handshakerServiceAddress string) (*grpc.ClientConn, error) { } return hsConn, nil } - -func enableAppEngineDialer() bool { - if strings.ToLower(os.Getenv(enableAppEngineDialerEnv)) == "true" { - return true - } - return false -} diff --git a/vendor/github.com/google/s2a-go/internal/record/ticketsender.go b/vendor/github.com/google/s2a-go/internal/record/ticketsender.go index 33fa3c55d..e51199ab3 100644 --- a/vendor/github.com/google/s2a-go/internal/record/ticketsender.go +++ b/vendor/github.com/google/s2a-go/internal/record/ticketsender.go @@ -83,13 +83,15 @@ func (t *ticketSender) sendTicketsToS2A(sessionTickets [][]byte, callComplete ch t.ensureProcessSessionTickets.Done() } }() - hsConn, err := service.Dial(t.hsAddr) + ctx, cancel := context.WithTimeout(context.Background(), sessionTimeout) + defer cancel() + // The transportCreds only needs to be set when talking to S2AV2 and also + // if mTLS is required. + hsConn, err := service.Dial(ctx, t.hsAddr, nil) if err != nil { return err } client := s2apb.NewS2AServiceClient(hsConn) - ctx, cancel := context.WithTimeout(context.Background(), sessionTimeout) - defer cancel() session, err := client.SetUpSession(ctx) if err != nil { return err diff --git a/vendor/github.com/google/s2a-go/internal/v2/s2av2.go b/vendor/github.com/google/s2a-go/internal/v2/s2av2.go index ff172883f..85a8379d8 100644 --- a/vendor/github.com/google/s2a-go/internal/v2/s2av2.go +++ b/vendor/github.com/google/s2a-go/internal/v2/s2av2.go @@ -33,6 +33,7 @@ import ( "github.com/google/s2a-go/internal/handshaker/service" "github.com/google/s2a-go/internal/tokenmanager" "github.com/google/s2a-go/internal/v2/tlsconfigstore" + "github.com/google/s2a-go/retry" "github.com/google/s2a-go/stream" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -44,18 +45,19 @@ import ( const ( s2aSecurityProtocol = "tls" - defaultS2ATimeout = 3 * time.Second + defaultS2ATimeout = 6 * time.Second ) // An environment variable, which sets the timeout enforced on the connection to the S2A service for handshake. const s2aTimeoutEnv = "S2A_TIMEOUT" type s2av2TransportCreds struct { - info *credentials.ProtocolInfo - isClient bool - serverName string - s2av2Address string - tokenManager *tokenmanager.AccessTokenManager + info *credentials.ProtocolInfo + isClient bool + serverName string + s2av2Address string + transportCreds credentials.TransportCredentials + tokenManager *tokenmanager.AccessTokenManager // localIdentity should only be used by the client. localIdentity *commonpbv1.Identity // localIdentities should only be used by the server. @@ -68,7 +70,7 @@ type s2av2TransportCreds struct { // NewClientCreds returns a client-side transport credentials object that uses // the S2Av2 to establish a secure connection with a server. -func NewClientCreds(s2av2Address string, localIdentity *commonpbv1.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, fallbackClientHandshakeFunc fallback.ClientHandshake, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error), serverAuthorizationPolicy []byte) (credentials.TransportCredentials, error) { +func NewClientCreds(s2av2Address string, transportCreds credentials.TransportCredentials, localIdentity *commonpbv1.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, fallbackClientHandshakeFunc fallback.ClientHandshake, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error), serverAuthorizationPolicy []byte) (credentials.TransportCredentials, error) { // Create an AccessTokenManager instance to use to authenticate to S2Av2. accessTokenManager, err := tokenmanager.NewSingleTokenAccessTokenManager() @@ -79,6 +81,7 @@ func NewClientCreds(s2av2Address string, localIdentity *commonpbv1.Identity, ver isClient: true, serverName: "", s2av2Address: s2av2Address, + transportCreds: transportCreds, localIdentity: localIdentity, verificationMode: verificationMode, fallbackClientHandshake: fallbackClientHandshakeFunc, @@ -98,7 +101,7 @@ func NewClientCreds(s2av2Address string, localIdentity *commonpbv1.Identity, ver // NewServerCreds returns a server-side transport credentials object that uses // the S2Av2 to establish a secure connection with a client. -func NewServerCreds(s2av2Address string, localIdentities []*commonpbv1.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error)) (credentials.TransportCredentials, error) { +func NewServerCreds(s2av2Address string, transportCreds credentials.TransportCredentials, localIdentities []*commonpbv1.Identity, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error)) (credentials.TransportCredentials, error) { // Create an AccessTokenManager instance to use to authenticate to S2Av2. accessTokenManager, err := tokenmanager.NewSingleTokenAccessTokenManager() creds := &s2av2TransportCreds{ @@ -107,6 +110,7 @@ func NewServerCreds(s2av2Address string, localIdentities []*commonpbv1.Identity, }, isClient: false, s2av2Address: s2av2Address, + transportCreds: transportCreds, localIdentities: localIdentities, verificationMode: verificationMode, getS2AStream: getS2AStream, @@ -131,7 +135,13 @@ func (c *s2av2TransportCreds) ClientHandshake(ctx context.Context, serverAuthori serverName := removeServerNamePort(serverAuthority) timeoutCtx, cancel := context.WithTimeout(ctx, GetS2ATimeout()) defer cancel() - s2AStream, err := createStream(timeoutCtx, c.s2av2Address, c.getS2AStream) + var s2AStream stream.S2AStream + var err error + retry.Run(timeoutCtx, + func() error { + s2AStream, err = createStream(timeoutCtx, c.s2av2Address, c.transportCreds, c.getS2AStream) + return err + }) if err != nil { grpclog.Infof("Failed to connect to S2Av2: %v", err) if c.fallbackClientHandshake != nil { @@ -152,31 +162,34 @@ func (c *s2av2TransportCreds) ClientHandshake(ctx context.Context, serverAuthori tokenManager = *c.tokenManager } - if c.serverName == "" { - config, err = tlsconfigstore.GetTLSConfigurationForClient(serverName, s2AStream, tokenManager, c.localIdentity, c.verificationMode, c.serverAuthorizationPolicy) - if err != nil { - grpclog.Info("Failed to get client TLS config from S2Av2: %v", err) - if c.fallbackClientHandshake != nil { - return c.fallbackClientHandshake(ctx, serverAuthority, rawConn, err) - } - return nil, nil, err - } - } else { - config, err = tlsconfigstore.GetTLSConfigurationForClient(c.serverName, s2AStream, tokenManager, c.localIdentity, c.verificationMode, c.serverAuthorizationPolicy) - if err != nil { - grpclog.Info("Failed to get client TLS config from S2Av2: %v", err) - if c.fallbackClientHandshake != nil { - return c.fallbackClientHandshake(ctx, serverAuthority, rawConn, err) - } - return nil, nil, err + sn := serverName + if c.serverName != "" { + sn = c.serverName + } + retry.Run(timeoutCtx, + func() error { + config, err = tlsconfigstore.GetTLSConfigurationForClient(sn, s2AStream, tokenManager, c.localIdentity, c.verificationMode, c.serverAuthorizationPolicy) + return err + }) + if err != nil { + grpclog.Info("Failed to get client TLS config from S2Av2: %v", err) + if c.fallbackClientHandshake != nil { + return c.fallbackClientHandshake(ctx, serverAuthority, rawConn, err) } + return nil, nil, err } if grpclog.V(1) { grpclog.Infof("Got client TLS config from S2Av2.") } - creds := credentials.NewTLS(config) - conn, authInfo, err := creds.ClientHandshake(ctx, serverName, rawConn) + creds := credentials.NewTLS(config) + var conn net.Conn + var authInfo credentials.AuthInfo + retry.Run(timeoutCtx, + func() error { + conn, authInfo, err = creds.ClientHandshake(timeoutCtx, serverName, rawConn) + return err + }) if err != nil { grpclog.Infof("Failed to do client handshake using S2Av2: %v", err) if c.fallbackClientHandshake != nil { @@ -196,7 +209,13 @@ func (c *s2av2TransportCreds) ServerHandshake(rawConn net.Conn) (net.Conn, crede } ctx, cancel := context.WithTimeout(context.Background(), GetS2ATimeout()) defer cancel() - s2AStream, err := createStream(ctx, c.s2av2Address, c.getS2AStream) + var s2AStream stream.S2AStream + var err error + retry.Run(ctx, + func() error { + s2AStream, err = createStream(ctx, c.s2av2Address, c.transportCreds, c.getS2AStream) + return err + }) if err != nil { grpclog.Infof("Failed to connect to S2Av2: %v", err) return nil, nil, err @@ -213,7 +232,12 @@ func (c *s2av2TransportCreds) ServerHandshake(rawConn net.Conn) (net.Conn, crede tokenManager = *c.tokenManager } - config, err := tlsconfigstore.GetTLSConfigurationForServer(s2AStream, tokenManager, c.localIdentities, c.verificationMode) + var config *tls.Config + retry.Run(ctx, + func() error { + config, err = tlsconfigstore.GetTLSConfigurationForServer(s2AStream, tokenManager, c.localIdentities, c.verificationMode) + return err + }) if err != nil { grpclog.Infof("Failed to get server TLS config from S2Av2: %v", err) return nil, nil, err @@ -221,8 +245,20 @@ func (c *s2av2TransportCreds) ServerHandshake(rawConn net.Conn) (net.Conn, crede if grpclog.V(1) { grpclog.Infof("Got server TLS config from S2Av2.") } + creds := credentials.NewTLS(config) - return creds.ServerHandshake(rawConn) + var conn net.Conn + var authInfo credentials.AuthInfo + retry.Run(ctx, + func() error { + conn, authInfo, err = creds.ServerHandshake(rawConn) + return err + }) + if err != nil { + grpclog.Infof("Failed to do server handshake using S2Av2: %v", err) + return nil, nil, err + } + return conn, authInfo, err } // Info returns protocol info of s2av2TransportCreds. @@ -278,11 +314,12 @@ func (c *s2av2TransportCreds) Clone() credentials.TransportCredentials { func NewClientTLSConfig( ctx context.Context, s2av2Address string, + transportCreds credentials.TransportCredentials, tokenManager tokenmanager.AccessTokenManager, verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode, serverName string, serverAuthorizationPolicy []byte) (*tls.Config, error) { - s2AStream, err := createStream(ctx, s2av2Address, nil) + s2AStream, err := createStream(ctx, s2av2Address, transportCreds, nil) if err != nil { grpclog.Infof("Failed to connect to S2Av2: %v", err) return nil, err @@ -325,12 +362,12 @@ func (x s2AGrpcStream) CloseSend() error { return x.stream.CloseSend() } -func createStream(ctx context.Context, s2av2Address string, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error)) (stream.S2AStream, error) { +func createStream(ctx context.Context, s2av2Address string, transportCreds credentials.TransportCredentials, getS2AStream func(ctx context.Context, s2av2Address string) (stream.S2AStream, error)) (stream.S2AStream, error) { if getS2AStream != nil { return getS2AStream(ctx, s2av2Address) } // TODO(rmehta19): Consider whether to close the connection to S2Av2. - conn, err := service.Dial(s2av2Address) + conn, err := service.Dial(ctx, s2av2Address, transportCreds) if err != nil { return nil, err } diff --git a/vendor/github.com/google/s2a-go/retry/retry.go b/vendor/github.com/google/s2a-go/retry/retry.go new file mode 100644 index 000000000..f7e0a2377 --- /dev/null +++ b/vendor/github.com/google/s2a-go/retry/retry.go @@ -0,0 +1,144 @@ +/* + * + * Copyright 2023 Google LLC + * + * 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 + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package retry provides a retry helper for talking to S2A gRPC server. +// The implementation is modeled after +// https://github.com/googleapis/google-cloud-go/blob/main/compute/metadata/retry.go +package retry + +import ( + "context" + "math/rand" + "time" + + "google.golang.org/grpc/grpclog" +) + +const ( + maxRetryAttempts = 5 + maxRetryForLoops = 10 +) + +type defaultBackoff struct { + max time.Duration + mul float64 + cur time.Duration +} + +// Pause returns a duration, which is used as the backoff wait time +// before the next retry. +func (b *defaultBackoff) Pause() time.Duration { + d := time.Duration(1 + rand.Int63n(int64(b.cur))) + b.cur = time.Duration(float64(b.cur) * b.mul) + if b.cur > b.max { + b.cur = b.max + } + return d +} + +// Sleep will wait for the specified duration or return on context +// expiration. +func Sleep(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + select { + case <-ctx.Done(): + t.Stop() + return ctx.Err() + case <-t.C: + return nil + } +} + +// NewRetryer creates an instance of S2ARetryer using the defaultBackoff +// implementation. +var NewRetryer = func() *S2ARetryer { + return &S2ARetryer{bo: &defaultBackoff{ + cur: 100 * time.Millisecond, + max: 30 * time.Second, + mul: 2, + }} +} + +type backoff interface { + Pause() time.Duration +} + +// S2ARetryer implements a retry helper for talking to S2A gRPC server. +type S2ARetryer struct { + bo backoff + attempts int +} + +// Attempts return the number of retries attempted. +func (r *S2ARetryer) Attempts() int { + return r.attempts +} + +// Retry returns a boolean indicating whether retry should be performed +// and the backoff duration. +func (r *S2ARetryer) Retry(err error) (time.Duration, bool) { + if err == nil { + return 0, false + } + if r.attempts >= maxRetryAttempts { + return 0, false + } + r.attempts++ + return r.bo.Pause(), true +} + +// Run uses S2ARetryer to execute the function passed in, until success or reaching +// max number of retry attempts. +func Run(ctx context.Context, f func() error) { + retryer := NewRetryer() + forLoopCnt := 0 + var err error + for { + err = f() + if bo, shouldRetry := retryer.Retry(err); shouldRetry { + if grpclog.V(1) { + grpclog.Infof("will attempt retry: %v", err) + } + if ctx.Err() != nil { + if grpclog.V(1) { + grpclog.Infof("exit retry loop due to context error: %v", ctx.Err()) + } + break + } + if errSleep := Sleep(ctx, bo); errSleep != nil { + if grpclog.V(1) { + grpclog.Infof("exit retry loop due to sleep error: %v", errSleep) + } + break + } + // This shouldn't happen, just make sure we are not stuck in the for loops. + forLoopCnt++ + if forLoopCnt > maxRetryForLoops { + if grpclog.V(1) { + grpclog.Infof("exit the for loop after too many retries") + } + break + } + continue + } + if grpclog.V(1) { + grpclog.Infof("retry conditions not met, exit the loop") + } + break + } +} diff --git a/vendor/github.com/google/s2a-go/s2a.go b/vendor/github.com/google/s2a-go/s2a.go index 1c1349de4..5ecb06f93 100644 --- a/vendor/github.com/google/s2a-go/s2a.go +++ b/vendor/github.com/google/s2a-go/s2a.go @@ -35,6 +35,7 @@ import ( "github.com/google/s2a-go/internal/handshaker/service" "github.com/google/s2a-go/internal/tokenmanager" "github.com/google/s2a-go/internal/v2" + "github.com/google/s2a-go/retry" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" @@ -111,7 +112,7 @@ func NewClientCreds(opts *ClientOptions) (credentials.TransportCredentials, erro if opts.FallbackOpts != nil && opts.FallbackOpts.FallbackClientHandshakeFunc != nil { fallbackFunc = opts.FallbackOpts.FallbackClientHandshakeFunc } - return v2.NewClientCreds(opts.S2AAddress, localIdentity, verificationMode, fallbackFunc, opts.getS2AStream, opts.serverAuthorizationPolicy) + return v2.NewClientCreds(opts.S2AAddress, opts.TransportCreds, localIdentity, verificationMode, fallbackFunc, opts.getS2AStream, opts.serverAuthorizationPolicy) } // NewServerCreds returns a server-side transport credentials object that uses @@ -146,7 +147,7 @@ func NewServerCreds(opts *ServerOptions) (credentials.TransportCredentials, erro }, nil } verificationMode := getVerificationMode(opts.VerificationMode) - return v2.NewServerCreds(opts.S2AAddress, localIdentities, verificationMode, opts.getS2AStream) + return v2.NewServerCreds(opts.S2AAddress, opts.TransportCreds, localIdentities, verificationMode, opts.getS2AStream) } // ClientHandshake initiates a client-side TLS handshake using the S2A. @@ -155,17 +156,17 @@ func (c *s2aTransportCreds) ClientHandshake(ctx context.Context, serverAuthority return nil, nil, errors.New("client handshake called using server transport credentials") } + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + defer cancel() + // Connect to the S2A. - hsConn, err := service.Dial(c.s2aAddr) + hsConn, err := service.Dial(ctx, c.s2aAddr, nil) if err != nil { grpclog.Infof("Failed to connect to S2A: %v", err) return nil, nil, err } - var cancel context.CancelFunc - ctx, cancel = context.WithCancel(ctx) - defer cancel() - opts := &handshaker.ClientHandshakerOptions{ MinTLSVersion: c.minTLSVersion, MaxTLSVersion: c.maxTLSVersion, @@ -203,16 +204,16 @@ func (c *s2aTransportCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credent return nil, nil, errors.New("server handshake called using client transport credentials") } + ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) + defer cancel() + // Connect to the S2A. - hsConn, err := service.Dial(c.s2aAddr) + hsConn, err := service.Dial(ctx, c.s2aAddr, nil) if err != nil { grpclog.Infof("Failed to connect to S2A: %v", err) return nil, nil, err } - ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) - defer cancel() - opts := &handshaker.ServerHandshakerOptions{ MinTLSVersion: c.minTLSVersion, MaxTLSVersion: c.maxTLSVersion, @@ -312,6 +313,7 @@ func NewTLSClientConfigFactory(opts *ClientOptions) (TLSClientConfigFactory, err grpclog.Infof("Access token manager not initialized: %v", err) return &s2aTLSClientConfigFactory{ s2av2Address: opts.S2AAddress, + transportCreds: opts.TransportCreds, tokenManager: nil, verificationMode: getVerificationMode(opts.VerificationMode), serverAuthorizationPolicy: opts.serverAuthorizationPolicy, @@ -319,6 +321,7 @@ func NewTLSClientConfigFactory(opts *ClientOptions) (TLSClientConfigFactory, err } return &s2aTLSClientConfigFactory{ s2av2Address: opts.S2AAddress, + transportCreds: opts.TransportCreds, tokenManager: tokenManager, verificationMode: getVerificationMode(opts.VerificationMode), serverAuthorizationPolicy: opts.serverAuthorizationPolicy, @@ -327,6 +330,7 @@ func NewTLSClientConfigFactory(opts *ClientOptions) (TLSClientConfigFactory, err type s2aTLSClientConfigFactory struct { s2av2Address string + transportCreds credentials.TransportCredentials tokenManager tokenmanager.AccessTokenManager verificationMode s2av2pb.ValidatePeerCertificateChainReq_VerificationMode serverAuthorizationPolicy []byte @@ -338,7 +342,7 @@ func (f *s2aTLSClientConfigFactory) Build( if opts != nil && opts.ServerName != "" { serverName = opts.ServerName } - return v2.NewClientTLSConfig(ctx, f.s2av2Address, f.tokenManager, f.verificationMode, serverName, f.serverAuthorizationPolicy) + return v2.NewClientTLSConfig(ctx, f.s2av2Address, f.transportCreds, f.tokenManager, f.verificationMode, serverName, f.serverAuthorizationPolicy) } func getVerificationMode(verificationMode VerificationModeType) s2av2pb.ValidatePeerCertificateChainReq_VerificationMode { @@ -390,9 +394,15 @@ func NewS2ADialTLSContextFunc(opts *ClientOptions) func(ctx context.Context, net } timeoutCtx, cancel := context.WithTimeout(ctx, v2.GetS2ATimeout()) defer cancel() - s2aTLSConfig, err := factory.Build(timeoutCtx, &TLSClientConfigOptions{ - ServerName: serverName, - }) + + var s2aTLSConfig *tls.Config + retry.Run(timeoutCtx, + func() error { + s2aTLSConfig, err = factory.Build(timeoutCtx, &TLSClientConfigOptions{ + ServerName: serverName, + }) + return err + }) if err != nil { grpclog.Infof("error building S2A TLS config: %v", err) return fallback(err) @@ -401,7 +411,12 @@ func NewS2ADialTLSContextFunc(opts *ClientOptions) func(ctx context.Context, net s2aDialer := &tls.Dialer{ Config: s2aTLSConfig, } - c, err := s2aDialer.DialContext(ctx, network, addr) + var c net.Conn + retry.Run(timeoutCtx, + func() error { + c, err = s2aDialer.DialContext(timeoutCtx, network, addr) + return err + }) if err != nil { grpclog.Infof("error dialing with S2A to %s: %v", addr, err) return fallback(err) diff --git a/vendor/github.com/google/s2a-go/s2a_options.go b/vendor/github.com/google/s2a-go/s2a_options.go index 94feafb9c..fcdbc1621 100644 --- a/vendor/github.com/google/s2a-go/s2a_options.go +++ b/vendor/github.com/google/s2a-go/s2a_options.go @@ -26,6 +26,7 @@ import ( "github.com/google/s2a-go/fallback" "github.com/google/s2a-go/stream" + "google.golang.org/grpc/credentials" s2apb "github.com/google/s2a-go/internal/proto/common_go_proto" ) @@ -92,6 +93,9 @@ type ClientOptions struct { LocalIdentity Identity // S2AAddress is the address of the S2A. S2AAddress string + // Optional transport credentials. + // If set, this will be used for the gRPC connection to the S2A server. + TransportCreds credentials.TransportCredentials // EnsureProcessSessionTickets waits for all session tickets to be sent to // S2A before a process completes. // @@ -173,6 +177,9 @@ type ServerOptions struct { LocalIdentities []Identity // S2AAddress is the address of the S2A. S2AAddress string + // Optional transport credentials. + // If set, this will be used for the gRPC connection to the S2A server. + TransportCreds credentials.TransportCredentials // If true, enables the use of legacy S2Av1. EnableLegacyMode bool // VerificationMode specifies the mode that S2A must use to verify the diff --git a/vendor/github.com/google/s2a-go/testdata/mds_client_cert.pem b/vendor/github.com/google/s2a-go/testdata/mds_client_cert.pem new file mode 100644 index 000000000..60c4cf069 --- /dev/null +++ b/vendor/github.com/google/s2a-go/testdata/mds_client_cert.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCDCCAfACFFlYsYCFit01ZpYmfjxpo7/6wMEbMA0GCSqGSIb3DQEBCwUAMEgx +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEPMA0GA1UECgwGR29vZ2xlMRswGQYD +VQQDDBJ0ZXN0LXMyYS1tdGxzLXJvb3QwHhcNMjMwODIyMTY0NTE4WhcNNDMwODIy +MTY0NTE4WjA5MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExHTAbBgNVBAMMFHRl +c3QtczJhLW10bHMtY2xpZW50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEAqrQQMyxNtmdCB+uY3szgRsfPrKC+TV9Fusnd8PfaCVuGTGcSBKM018nV2TDn +3IYFQ1HgLpGwGwOFDBb3y0o9i2/l2VJySriX1GSNX6nDmVasQlO1wuOLCP7/LRmO +7b6Kise5W0IFhYaptKyWnekn2pS0tAjimqpfn2w0U6FDGtQUqg/trQQmGtTSJHjb +A+OFd0EFC18KGP8Q+jOMaMkJRmpeEiAPyHPDoMhqQNT26RApv9j2Uzo4SuXzHH6T +cAdm1+zG+EXY/UZKX9oDkSbwIJvN+gCmNyORLalJ12gsGYOCjMd8K0mlXBqrmmbO +VHVbUm9062lhE7x59AA8DK4DoQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQCPOvtL +dq2hxFHlIy0YUK8jp/DtwJZPwzx1id5FtWwd0CxBS1StIgmkHMxtkJGz1iyQLplI +je+Msd4sTsb5zZi/8kGKehi8Wj4lghp4oP30cpob41OvM68M9RC/wSOVk9igSww+ +l3zof6wKRIswsi5VHrL16ruIVVoDlyFbKr8yk+cp9OPOV8hNNN7ewY9xC8OgnTt8 +YtdaLe6uTplKBLW+j3GtshigRhyfkGJyPFYL4LAeDJCHlC1qmBnkyP0ijMp6vneM +E8TLavnMTMcpihWTWpyKeRkO6HDRsP4AofQAp7VAiAdSOplga+w2qgrVICV+m8MK +BTq2PBvc59T6OFLq +-----END CERTIFICATE----- diff --git a/vendor/github.com/google/s2a-go/testdata/mds_client_key.pem b/vendor/github.com/google/s2a-go/testdata/mds_client_key.pem new file mode 100644 index 000000000..9d112d1e9 --- /dev/null +++ b/vendor/github.com/google/s2a-go/testdata/mds_client_key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqtBAzLE22Z0IH +65jezOBGx8+soL5NX0W6yd3w99oJW4ZMZxIEozTXydXZMOfchgVDUeAukbAbA4UM +FvfLSj2Lb+XZUnJKuJfUZI1fqcOZVqxCU7XC44sI/v8tGY7tvoqKx7lbQgWFhqm0 +rJad6SfalLS0COKaql+fbDRToUMa1BSqD+2tBCYa1NIkeNsD44V3QQULXwoY/xD6 +M4xoyQlGal4SIA/Ic8OgyGpA1PbpECm/2PZTOjhK5fMcfpNwB2bX7Mb4Rdj9Rkpf +2gORJvAgm836AKY3I5EtqUnXaCwZg4KMx3wrSaVcGquaZs5UdVtSb3TraWETvHn0 +ADwMrgOhAgMBAAECggEAUccupZ1ZY4OHTi0PkNk8rpwFwTFGyeFVEf2ofkr24RnA +NnUAXEllxOUUNlcoFOz9s3kTeavg3qgqgpa0QmdAIb9LMXg+ec6CKkW7trMpGho8 +LxBUWNfSoU4sKEqAvyPT0lWJVo9D/up6/avbAi6TIbOw+Djzel4ZrlHTpabxc3WT +EilXzn4q54b3MzxCQeQjcnzTieW4Q5semG2kLiXFToHIY2di01P/O8awUjgrD+uW +/Cb6H49MnHm9VPkqea1iwZeMQd6Gh5FrC7RezsBjdB1JBcfsv6PFt2ySInjB8SF+ +XR5Gr3Cc5sh9s0LfprZ9Dq0rlSWmwasPMI1COK6SswKBgQDczgeWd3erQ1JX9LEI +wollawqC9y7uJhEsw1hrPqA3uqZYiLUc7Nmi4laZ12mcGoXNDS3R3XmD58qGmGaU +lxEVTb8KDVWBgw450VoBKzSMQnCP6zn4nZxTYxeqMKjDGf6TRB6TZc843qsG3eRC +k91yxrCQ/0HV6PT48C+lieDzLwKBgQDF6aNKiyrswr457undBnM1H8q/Y6xC5ZlK +UtiQdhuyBnicvz0U8WPxBY/8gha0OXWuSnBqq/z77iFVNv/zT6p9K7kM7nBGd8cB +8KO6FNbyaHWFrhCI5zNzRTH4oha0hfvUOoti09vqavCtWD4L+D/63ba1wNLKPO9o +4gWbCnUCLwKBgQC/vus372csgrnvR761LLrEJ8BpGt7WUJh5luoht7DKtHvgRleB +Vu1oVcV+s2Iy/ZVUDC3OIdZ0hcWKPK5YOxfKuEk+IXYvke+4peTTPwHTC59UW6Fs +FPK8N0FFuhvT0a8RlAY5WiAp8rPysp6WcnHMSl7qi8BQUozp4Sp/RsziYQKBgBXv +r4mzoy5a53rEYGd/L4XT4EUWZyGDEVqLlDVu4eL5lKTLDZokp08vrqXuRVX0iHap +CYzJQ2EpI8iuL/BoBB2bmwcz5n3pCMXORld5t9lmeqA2it6hwbIlGUTVsm6P6zm6 +w3hQwy9YaxTLkxUAjxbfPEEo/jQsTNzzMGve3NlBAoGAbgJExpDyMDnaD2Vi5eyr +63b54BsqeLHqxJmADifyRCj7G1SJMm3zMKkNNOS0vsXgoiId973STFf1XQiojiv8 +Slbxyv5rczcY0n3LOuQYcM5OzsjzpNFZsT2dDnMfNRUF3rx3Geu/FuJ9scF1b00r +fVMrcL3jSf/W1Xh4TgtyoU8= +-----END PRIVATE KEY----- diff --git a/vendor/github.com/google/s2a-go/testdata/mds_root_cert.pem b/vendor/github.com/google/s2a-go/testdata/mds_root_cert.pem new file mode 100644 index 000000000..44e436f6e --- /dev/null +++ b/vendor/github.com/google/s2a-go/testdata/mds_root_cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDcTCCAlmgAwIBAgIUDUkgI+2FZtuUHyUUi0ZBH7JvN00wDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQ8wDQYDVQQKDAZHb29nbGUx +GzAZBgNVBAMMEnRlc3QtczJhLW10bHMtcm9vdDAeFw0yMzA4MjEyMTI5MTVaFw00 +MzA4MjEyMTI5MTVaMEgxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEPMA0GA1UE +CgwGR29vZ2xlMRswGQYDVQQDDBJ0ZXN0LXMyYS1tdGxzLXJvb3QwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCbFEQfpvla27bATedrN4BAWsI9GSwSnJLW +QWzXcnAk6cKxQBAhnaKHRxHY8ttLhNTtxQeub894CLzJvHE/0xDhuMzjtCCCZ7i2 +r08tKZ1KcEzPJCPNlxlzAXPA45XU3LRlbGvju/PBPhm6n1hCEKTNI/KETJ5DEaYg +Cf2LcXVsl/zW20MwDZ+e2w/9a2a6n6DdpW1ekOR550hXAUOIxvmXRBeYeGLFvp1n +rQgZBhRaxP03UB+PQD2oMi/4mfsS96uGCXdzzX8qV46O8m132HUbnA/wagIwboEe +d7Bx237dERDyHw5GFnll7orgA0FOtoEufXdeQxWVvTjO0+PVPgsvAgMBAAGjUzBR +MB0GA1UdDgQWBBRyMtg/yutV8hw8vOq0i8x0eBQi7DAfBgNVHSMEGDAWgBRyMtg/ +yutV8hw8vOq0i8x0eBQi7DAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA +A4IBAQArN/gdqWMxd5Rvq2eJMTp6I4RepJOT7Go4sMsRsy1caJqqcoS2EvREDZMN +XNEBcyQBB5kYd6TCcZGoLnEtWYXQ4jjEiXG1g7/+rWxyqw0ZYuP7FWzuHg3Uor/x +fApbEKwptP5ywVc+33h4qreGcqXkVCCn+sAcstGgrqubdGZW2T5gazUMyammOOuN +9IWL1PbvXmgEKD+80NUIrk09zanYyrElGdU/zw/kUbZ3Jf6WUBtJGhTzRQ1qZeKa +VnpCbLoG3vObEB8mxDUAlIzwAtfvw4U32BVIZA8xrocz6OOoAnSW1bTlo3EOIo/G +MTV7jmY9TBPtfhRuO/cG650+F+cw +-----END CERTIFICATE----- diff --git a/vendor/github.com/google/s2a-go/testdata/mds_server_cert.pem b/vendor/github.com/google/s2a-go/testdata/mds_server_cert.pem new file mode 100644 index 000000000..68c606134 --- /dev/null +++ b/vendor/github.com/google/s2a-go/testdata/mds_server_cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDbjCCAlagAwIBAgIUbexZ5sZl86Al9dsI2PkOgtqKnkgwDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQ8wDQYDVQQKDAZHb29nbGUx +GzAZBgNVBAMMEnRlc3QtczJhLW10bHMtcm9vdDAeFw0yMzA4MjIwMDMyMDRaFw00 +MzA4MjIwMDMyMDRaMDkxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEdMBsGA1UE +AwwUdGVzdC1zMmEtbXRscy1zZXJ2ZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCMEzybsGPqfh92GLwy43mt8kQDF3ztr8y06RwU1hVnY7QqYK4obpvh +HkJVnTz9gwNBF3n5nUalqRzactlf2PCydN9oSYNCO8svVmo7vw1CleKAKFAiV5Qn +H76QlqD15oJreh7nSM8R4qj5KukIHvt0cN0gD6CJQzIURDtsKJwkW3yQjYyT/FAK +GYtFrB6buDn3Eg3Hsw6z7uj7CzLBsSl7BIGrQILbpbI9nFNT3rUTUhXZKY/3UtJA +Ob66AjTmMbD16RGYZR4JsPx6CstheifJ6YSI79r5KgD37zX0jMXFWimvb2SmZmFe +LoohtC8K7uTyjm/dROx6nHXdDt5TQYXHAgMBAAGjXzBdMBsGA1UdEQQUMBKHEAAA +AAAAAAAAAAAAAAAAAAAwHQYDVR0OBBYEFI3i2+tIk6YYn0MIxC0q93jk1VsUMB8G +A1UdIwQYMBaAFHIy2D/K61XyHDy86rSLzHR4FCLsMA0GCSqGSIb3DQEBCwUAA4IB +AQAUhk+s/lrIAULBbU7E22C8f93AzTxE1mhyHGNlfPPJP3t1Dl+h4X4WkFpkz5gT +EcNXB//Vvoq99HbEK5/92sxsIPexKdJBdcggeHXIgLDkOrEZEb0Nnh9eaAuU2QDn +JW44hMB+aF6mEaJvOHE6DRkQw3hwFYFisFKKHtlQ3TyOhw5CHGzSExPZusdSFNIe +2E7V/0QzGPJEFnEFUNe9N8nTH2P385Paoi+5+Iizlp/nztVXfzv0Cj/i+qGgtDUs +HB+gBU2wxMw8eYyuNzACH70wqGR1Parj8/JoyYhx0S4+Gjzy3JH3CcAMaxyfH/dI +4Wcvfz/isxgmH1UqIt3oc6ad +-----END CERTIFICATE----- diff --git a/vendor/github.com/google/s2a-go/testdata/mds_server_key.pem b/vendor/github.com/google/s2a-go/testdata/mds_server_key.pem new file mode 100644 index 000000000..b14ad0f72 --- /dev/null +++ b/vendor/github.com/google/s2a-go/testdata/mds_server_key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCMEzybsGPqfh92 +GLwy43mt8kQDF3ztr8y06RwU1hVnY7QqYK4obpvhHkJVnTz9gwNBF3n5nUalqRza +ctlf2PCydN9oSYNCO8svVmo7vw1CleKAKFAiV5QnH76QlqD15oJreh7nSM8R4qj5 +KukIHvt0cN0gD6CJQzIURDtsKJwkW3yQjYyT/FAKGYtFrB6buDn3Eg3Hsw6z7uj7 +CzLBsSl7BIGrQILbpbI9nFNT3rUTUhXZKY/3UtJAOb66AjTmMbD16RGYZR4JsPx6 +CstheifJ6YSI79r5KgD37zX0jMXFWimvb2SmZmFeLoohtC8K7uTyjm/dROx6nHXd +Dt5TQYXHAgMBAAECggEAIB5zGdIG/yh/Z1GBqfuOFaxFGx5iJ5BVlLAVH9P9IXFz +yPnVRXEjbinFlSMSbqEBeIX9EpcVMXxHIPIP1RIGEy2IYr3kiqXyT771ahDDZh6/ +Spqz0UQatSPqyvW3H9uE0Uc12dvQm23JSCUmPRX5m7gbhDQBIChXzdzdcU4Yi59V +4xmJUvbsAcLw5CBM6kwV+1NGVH9+3mUdhrr9M6B6+sVB/xnaqMGEDfQGiwL8U7EY +QOuc46KXu3Pd/qCdVLn60IrdjSzDJKeC5UZZ+ejNAo+DfbtOovBj3qu3OCUg4XVy +0CDBJ1sTdLvUfF4Gb+crjPsd+qBbXcjVfqdadwhsoQKBgQDBF1Pys/NitW8okJwp +2fiDIASP3TiI+MthWHGyuoZGPvmXQ3H6iuLSm8c/iYI2WPTf53Xff1VcFm1GmQms +GCsYM8Ax94zCeO6Ei1sYYxwcBloEZfOeV37MPA4pjJF4Lt+n5nveNxP+lrsjksJz +wToSEgWPDT1b/xcdt4/5j9J85wKBgQC5tiLx+33mwH4DoaFRmSl0+VuSNYFw6DTQ +SQ+kWqWGH4NENc9wf4Dj2VUZQhpXNhXVSxj+aP2d/ck1NrTJAWqYEXCDtFQOGSa2 +cGPRr+Fhy5NIEaEvR7IXcMBZzx3koYmWVBHricyrXs5FvHrT3N14mGDUG8n24U3f +R799bau0IQKBgQC97UM+lHCPJCWNggiJRgSifcje9VtZp1btjoBvq/bNe74nYkjn +htsrC91Fiu1Qpdlfr50K1IXSyaB886VG6JLjAGxI+dUzqJ38M9LLvxj0G+9JKjsi +AbAQFfZcOg8QZxLJZPVsE0MQhZTXndC06VhEVAOxvPUg214Sde8hK61/+wKBgCRw +O10VhnePT2pw/VEgZ0T/ZFtEylgYB7zSiRIrgwzVBBGPKVueePC8BPmGwdpYz2Hh +cU8B1Ll6QU+Co2hJMdwSl+wPpup5PuJPHRbYlrV0lzpt0x2OyL/WrLcyb2Ab3f40 +EqwPhqwdVwXR3JvTW1U9OMqFhVQ+kuP7lPQMX8NhAoGBAJOgZ7Tokipc4Mi68Olw +SCaOPvjjy4sW2rTRuKyjc1wTAzy7SJ3vXHfGkkN99nTLJFwAyJhWUpnRdwAXGi+x +gyOa95ImsEfRSwEjbluWfF8/P0IU8GR+ZTqT4NnNCOsi8T/xst4Szd1ECJNnnZDe +1ChfPP1AH+/75MJCvu6wQBQv +-----END PRIVATE KEY----- diff --git a/vendor/github.com/google/s2a-go/testdata/self_signed_cert.pem b/vendor/github.com/google/s2a-go/testdata/self_signed_cert.pem new file mode 100644 index 000000000..ad1bad598 --- /dev/null +++ b/vendor/github.com/google/s2a-go/testdata/self_signed_cert.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDITCCAgkCFBS8mLoytMpMWBwpAtnRaq3eIKnsMA0GCSqGSIb3DQEBCwUAME0x +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTENMAsGA1UECgwEVGVzdDEiMCAGA1UE +AwwZdGVzdC1zMmEtbXRscy1zZWxmLXNpZ25lZDAeFw0yMzA4MjIyMTE2MDFaFw00 +MzA4MjIyMTE2MDFaME0xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTENMAsGA1UE +CgwEVGVzdDEiMCAGA1UEAwwZdGVzdC1zMmEtbXRscy1zZWxmLXNpZ25lZDCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKFFPsYasKZeCFLEXl3RpE/ZOXFe +2lhutIalSpZvCmso+mQGoZ4cHK7At+kDjBi5CrnXkYcw7quQAhHgU0frhWdj7tsW +HUUtq7T8eaGWKBnVD9fl+MjtAl1BmhXwV9qRBbj4EesSKGDSGpKf66dOtzw83JbB +cU7XlPAH1c1zo2GXC1himcZ+SVGHVrOjn4NmeFs8g94/Dke8dWkHwv5YTMVugFK4 +5KxKgSOKkr4ka7PCBzgxCnW4wYSZNRHcxrqkiArO2HAQq0ACr7u+fVDYH//9mP2Z +ADo/zch7O5yhkiNbjXJIRrptDWEuVYMRloYDhT773h7bV/Q0Wo0NQGtasJ8CAwEA +ATANBgkqhkiG9w0BAQsFAAOCAQEAPjbH0TMyegF/MDvglkc0sXr6DqlmTxDCZZmG +lYPZ5Xy062+rxIHghMARbvO4BxepiG37KsP2agvOldm4TtU8nQ8LyswmSIFm4BQ+ +XQWwdsWyYyd8l0d5sXAdaN6AXwy50fvqCepmEqyreMY6dtLzlwo9gVCBFB7QuAPt +Nc14phpEUZt/KPNuY6cUlB7bz3tmnFbwxUrWj1p0KBEYsr7+KEVZxR+z0wtlU7S9 +ZBrmUvx0fq5Ef7JWtHW0w4ofg1op742sdYl+53C26GZ76ts4MmqVz2/94DScgRaU +gT0GLVuuCZXRDVeTXqTb4mditRCfzFPe9cCegYhGhSqBs8yh5A== +-----END CERTIFICATE----- diff --git a/vendor/github.com/google/s2a-go/testdata/self_signed_key.pem b/vendor/github.com/google/s2a-go/testdata/self_signed_key.pem new file mode 100644 index 000000000..bcf08e4f1 --- /dev/null +++ b/vendor/github.com/google/s2a-go/testdata/self_signed_key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQChRT7GGrCmXghS +xF5d0aRP2TlxXtpYbrSGpUqWbwprKPpkBqGeHByuwLfpA4wYuQq515GHMO6rkAIR +4FNH64VnY+7bFh1FLau0/HmhligZ1Q/X5fjI7QJdQZoV8FfakQW4+BHrEihg0hqS +n+unTrc8PNyWwXFO15TwB9XNc6NhlwtYYpnGfklRh1azo5+DZnhbPIPePw5HvHVp +B8L+WEzFboBSuOSsSoEjipK+JGuzwgc4MQp1uMGEmTUR3Ma6pIgKzthwEKtAAq+7 +vn1Q2B///Zj9mQA6P83IezucoZIjW41ySEa6bQ1hLlWDEZaGA4U++94e21f0NFqN +DUBrWrCfAgMBAAECggEAR8e8YwyqJ8KezcgdgIC5M9kp2i4v3UCZFX0or8CI0J2S +pUbWVLuKgLXCpfIwPyjNf15Vpei/spkMcsx4BQDthdFTFSzIpmvni0z9DlD5VFYj +ESOJElV7wepbHPy2/c+izmuL/ic81aturGiFyRgeMq+cN3WuaztFTXkPTrzzsZGF +p/Mx3gqm7Hoc3d2xlv+8L5GjCtEJPlQgZJV+s3ennBjOAd8CC7d9qJetE3Er46pn +r5jedV3bQRZYBzmooYNHjbAs26++wYac/jTE0/U6nKS17eWq4BQZUtlMXUw5N81B +7LKn7C03rj2KCn+Nf5uin9ALmoy888LXCDdvL/NZkQKBgQDduv1Heu+tOZuNYUdQ +Hswmd8sVNAAWGZxdxixHMv58zrgbLFXSX6K89X2l5Sj9XON8TH46MuSFdjSwwWw5 +fBrhVEhA5srcqpvVWIBE05yqPpt0s1NQktMWJKELWlG8jOhVKwM5OYDpdxtwehpz +1g70XJz+nF/LTV8RdTK+OWDDpQKBgQC6MhdbGHUz/56dY3gZpE5TXnN2hkNbZCgk +emr6z85VHhQflZbedhCzB9PUnZnCKWOGQHQdxRTtRfd46LVboZqCdYO1ZNQv6toP +ysS7dTpZZFy7CpQaW0Y6/jS65jW6xIDKR1W40vgltZ3sfpG37JaowpzWdw2WuOnw +Bg0rcJAf8wKBgQCqE+p/z97UwuF8eufWnyj9QNo382E1koOMspv4KTdnyLETtthF +vDH6O1wbykG8xmmASLRyM+NyNA+KnXNETNvZh2q8zctBpGRQK8iIAsGjHM7ln0AD +B/x+ea5GJQuZU4RK/+lDFca6TjBwAFkWDVX/PqL18kDQkxKfM4SuwRhmOQKBgDGh +eoJIsa0LnP787Z2AI3Srf4F/ZmLs/ppCm1OBotEjdF+64v0nYWonUvqgi8SqfaHi +elEZIGvis4ViGj1zhRjzNAlc+AZRxpBhDzGcnNIJI4Kj3jhsTfsZmXqcNIQ1LtM8 +Uogyi/yZPaA1WKg7Aym2vlGYaGHdplXZdxc2KOSrAoGABRkD9l2OVcwK7RyNgFxo +mjxx0tfUdDBhHIi2igih1FiHpeP9E+4/kE/K7PnU9DoDrL1jW1MTpXaYV4seOylk +k9z/9QfcRa9ePD2N4FqbHWSYp5n3aLoIcGq/9jyjTwayZbbIhWO+vNuHE9wIvecZ +8x3gNkxJRb4NaLIoNzAhCoo= +-----END PRIVATE KEY----- diff --git a/vendor/github.com/google/uuid/.travis.yml b/vendor/github.com/google/uuid/.travis.yml deleted file mode 100644 index d8156a60b..000000000 --- a/vendor/github.com/google/uuid/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: - - 1.4.3 - - 1.5.3 - - tip - -script: - - go test -v ./... diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md new file mode 100644 index 000000000..c9fb829dc --- /dev/null +++ b/vendor/github.com/google/uuid/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +## [1.5.0](https://github.com/google/uuid/compare/v1.4.0...v1.5.0) (2023-12-12) + + +### Features + +* Validate UUID without creating new UUID ([#141](https://github.com/google/uuid/issues/141)) ([9ee7366](https://github.com/google/uuid/commit/9ee7366e66c9ad96bab89139418a713dc584ae29)) + +## [1.4.0](https://github.com/google/uuid/compare/v1.3.1...v1.4.0) (2023-10-26) + + +### Features + +* UUIDs slice type with Strings() convenience method ([#133](https://github.com/google/uuid/issues/133)) ([cd5fbbd](https://github.com/google/uuid/commit/cd5fbbdd02f3e3467ac18940e07e062be1f864b4)) + +### Fixes + +* Clarify that Parse's job is to parse but not necessarily validate strings. (Documents current behavior) + +## [1.3.1](https://github.com/google/uuid/compare/v1.3.0...v1.3.1) (2023-08-18) + + +### Bug Fixes + +* Use .EqualFold() to parse urn prefixed UUIDs ([#118](https://github.com/google/uuid/issues/118)) ([574e687](https://github.com/google/uuid/commit/574e6874943741fb99d41764c705173ada5293f0)) + +## Changelog diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md index 04fdf09f1..a502fdc51 100644 --- a/vendor/github.com/google/uuid/CONTRIBUTING.md +++ b/vendor/github.com/google/uuid/CONTRIBUTING.md @@ -2,6 +2,22 @@ We definitely welcome patches and contribution to this project! +### Tips + +Commits must be formatted according to the [Conventional Commits Specification](https://www.conventionalcommits.org). + +Always try to include a test case! If it is not possible or not necessary, +please explain why in the pull request description. + +### Releasing + +Commits that would precipitate a SemVer change, as described in the Conventional +Commits Specification, will trigger [`release-please`](https://github.com/google-github-actions/release-please-action) +to create a release candidate pull request. Once submitted, `release-please` +will create a release. + +For tips on how to work with `release-please`, see its documentation. + ### Legal requirements In order to protect both you and ourselves, you will need to sign the diff --git a/vendor/github.com/google/uuid/README.md b/vendor/github.com/google/uuid/README.md index f765a46f9..3e9a61889 100644 --- a/vendor/github.com/google/uuid/README.md +++ b/vendor/github.com/google/uuid/README.md @@ -1,6 +1,6 @@ -# uuid ![build status](https://travis-ci.org/google/uuid.svg?branch=master) +# uuid The uuid package generates and inspects UUIDs based on -[RFC 4122](http://tools.ietf.org/html/rfc4122) +[RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) and DCE 1.1: Authentication and Security Services. This package is based on the github.com/pborman/uuid package (previously named @@ -9,10 +9,12 @@ a UUID is a 16 byte array rather than a byte slice. One loss due to this change is the ability to represent an invalid UUID (vs a NIL UUID). ###### Install -`go get github.com/google/uuid` +```sh +go get github.com/google/uuid +``` ###### Documentation -[![GoDoc](https://godoc.org/github.com/google/uuid?status.svg)](http://godoc.org/github.com/google/uuid) +[![Go Reference](https://pkg.go.dev/badge/github.com/google/uuid.svg)](https://pkg.go.dev/github.com/google/uuid) Full `go doc` style documentation for the package can be viewed online without installing this package by using the GoDoc site here: diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go index 24b78edc9..b2a0bc871 100644 --- a/vendor/github.com/google/uuid/node_js.go +++ b/vendor/github.com/google/uuid/node_js.go @@ -7,6 +7,6 @@ package uuid // getHardwareInterface returns nil values for the JS version of the code. -// This remvoves the "net" dependency, because it is not used in the browser. +// This removes the "net" dependency, because it is not used in the browser. // Using the "net" library inflates the size of the transpiled JS code by 673k bytes. func getHardwareInterface(name string) (string, []byte) { return "", nil } diff --git a/vendor/github.com/google/uuid/time.go b/vendor/github.com/google/uuid/time.go index e6ef06cdc..c35112927 100644 --- a/vendor/github.com/google/uuid/time.go +++ b/vendor/github.com/google/uuid/time.go @@ -108,12 +108,23 @@ func setClockSequence(seq int) { } // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in -// uuid. The time is only defined for version 1 and 2 UUIDs. +// uuid. The time is only defined for version 1, 2, 6 and 7 UUIDs. func (uuid UUID) Time() Time { - time := int64(binary.BigEndian.Uint32(uuid[0:4])) - time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 - time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 - return Time(time) + var t Time + switch uuid.Version() { + case 6: + time := binary.BigEndian.Uint64(uuid[:8]) // Ignore uuid[6] version b0110 + t = Time(time) + case 7: + time := binary.BigEndian.Uint64(uuid[:8]) + t = Time((time>>16)*10000 + g1582ns100) + default: // forward compatible + time := int64(binary.BigEndian.Uint32(uuid[0:4])) + time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 + time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 + t = Time(time) + } + return t } // ClockSequence returns the clock sequence encoded in uuid. diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go index a57207aeb..5232b4867 100644 --- a/vendor/github.com/google/uuid/uuid.go +++ b/vendor/github.com/google/uuid/uuid.go @@ -56,11 +56,15 @@ func IsInvalidLengthError(err error) bool { return ok } -// Parse decodes s into a UUID or returns an error. Both the standard UUID -// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the -// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex -// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx. +// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both +// the standard UUID forms defined in RFC 4122 +// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, +// Parse accepts non-standard strings such as the raw hex encoding +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, +// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are +// examined in the latter case. Parse should not be used to validate strings as +// it parses non-standard encodings as indicated above. func Parse(s string) (UUID, error) { var uuid UUID switch len(s) { @@ -69,7 +73,7 @@ func Parse(s string) (UUID, error) { // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx case 36 + 9: - if strings.ToLower(s[:9]) != "urn:uuid:" { + if !strings.EqualFold(s[:9], "urn:uuid:") { return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) } s = s[9:] @@ -101,7 +105,8 @@ func Parse(s string) (UUID, error) { 9, 11, 14, 16, 19, 21, - 24, 26, 28, 30, 32, 34} { + 24, 26, 28, 30, 32, 34, + } { v, ok := xtob(s[x], s[x+1]) if !ok { return uuid, errors.New("invalid UUID format") @@ -117,7 +122,7 @@ func ParseBytes(b []byte) (UUID, error) { switch len(b) { case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) { + if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) { return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) } b = b[9:] @@ -145,7 +150,8 @@ func ParseBytes(b []byte) (UUID, error) { 9, 11, 14, 16, 19, 21, - 24, 26, 28, 30, 32, 34} { + 24, 26, 28, 30, 32, 34, + } { v, ok := xtob(b[x], b[x+1]) if !ok { return uuid, errors.New("invalid UUID format") @@ -180,6 +186,59 @@ func Must(uuid UUID, err error) UUID { return uuid } +// Validate returns an error if s is not a properly formatted UUID in one of the following formats: +// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} +// It returns an error if the format is invalid, otherwise nil. +func Validate(s string) error { + switch len(s) { + // Standard UUID format + case 36: + + // UUID with "urn:uuid:" prefix + case 36 + 9: + if !strings.EqualFold(s[:9], "urn:uuid:") { + return fmt.Errorf("invalid urn prefix: %q", s[:9]) + } + s = s[9:] + + // UUID enclosed in braces + case 36 + 2: + if s[0] != '{' || s[len(s)-1] != '}' { + return fmt.Errorf("invalid bracketed UUID format") + } + s = s[1 : len(s)-1] + + // UUID without hyphens + case 32: + for i := 0; i < len(s); i += 2 { + _, ok := xtob(s[i], s[i+1]) + if !ok { + return errors.New("invalid UUID format") + } + } + + default: + return invalidLengthError{len(s)} + } + + // Check for standard UUID format + if len(s) == 36 { + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return errors.New("invalid UUID format") + } + for _, x := range []int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { + if _, ok := xtob(s[x], s[x+1]); !ok { + return errors.New("invalid UUID format") + } + } + } + + return nil +} + // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // , or "" if uuid is invalid. func (uuid UUID) String() string { @@ -292,3 +351,15 @@ func DisableRandPool() { poolMu.Lock() poolPos = randPoolSize } + +// UUIDs is a slice of UUID types. +type UUIDs []UUID + +// Strings returns a string slice containing the string form of each UUID in uuids. +func (uuids UUIDs) Strings() []string { + var uuidStrs = make([]string, len(uuids)) + for i, uuid := range uuids { + uuidStrs[i] = uuid.String() + } + return uuidStrs +} diff --git a/vendor/github.com/google/uuid/version6.go b/vendor/github.com/google/uuid/version6.go new file mode 100644 index 000000000..339a959a7 --- /dev/null +++ b/vendor/github.com/google/uuid/version6.go @@ -0,0 +1,56 @@ +// Copyright 2023 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "encoding/binary" + +// UUID version 6 is a field-compatible version of UUIDv1, reordered for improved DB locality. +// It is expected that UUIDv6 will primarily be used in contexts where there are existing v1 UUIDs. +// Systems that do not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead. +// +// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#uuidv6 +// +// NewV6 returns a Version 6 UUID based on the current NodeID and clock +// sequence, and the current time. If the NodeID has not been set by SetNodeID +// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// be set NewV6 set NodeID is random bits automatically . If clock sequence has not been set by +// SetClockSequence then it will be set automatically. If GetTime fails to +// return the current NewV6 returns Nil and an error. +func NewV6() (UUID, error) { + var uuid UUID + now, seq, err := GetTime() + if err != nil { + return uuid, err + } + + /* + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_high | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_mid | time_low_and_version | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |clk_seq_hi_res | clk_seq_low | node (0-1) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | node (2-5) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + + binary.BigEndian.PutUint64(uuid[0:], uint64(now)) + binary.BigEndian.PutUint16(uuid[8:], seq) + + uuid[6] = 0x60 | (uuid[6] & 0x0F) + uuid[8] = 0x80 | (uuid[8] & 0x3F) + + nodeMu.Lock() + if nodeID == zeroID { + setNodeInterface("") + } + copy(uuid[10:], nodeID[:]) + nodeMu.Unlock() + + return uuid, nil +} diff --git a/vendor/github.com/google/uuid/version7.go b/vendor/github.com/google/uuid/version7.go new file mode 100644 index 000000000..ba9dd5eb6 --- /dev/null +++ b/vendor/github.com/google/uuid/version7.go @@ -0,0 +1,75 @@ +// Copyright 2023 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "io" +) + +// UUID version 7 features a time-ordered value field derived from the widely +// implemented and well known Unix Epoch timestamp source, +// the number of milliseconds seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. +// As well as improved entropy characteristics over versions 1 or 6. +// +// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#name-uuid-version-7 +// +// Implementations SHOULD utilize UUID version 7 over UUID version 1 and 6 if possible. +// +// NewV7 returns a Version 7 UUID based on the current time(Unix Epoch). +// Uses the randomness pool if it was enabled with EnableRandPool. +// On error, NewV7 returns Nil and an error +func NewV7() (UUID, error) { + uuid, err := NewRandom() + if err != nil { + return uuid, err + } + makeV7(uuid[:]) + return uuid, nil +} + +// NewV7FromReader returns a Version 7 UUID based on the current time(Unix Epoch). +// it use NewRandomFromReader fill random bits. +// On error, NewV7FromReader returns Nil and an error. +func NewV7FromReader(r io.Reader) (UUID, error) { + uuid, err := NewRandomFromReader(r) + if err != nil { + return uuid, err + } + + makeV7(uuid[:]) + return uuid, nil +} + +// makeV7 fill 48 bits time (uuid[0] - uuid[5]), set version b0111 (uuid[6]) +// uuid[8] already has the right version number (Variant is 10) +// see function NewV7 and NewV7FromReader +func makeV7(uuid []byte) { + /* + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | unix_ts_ms | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | unix_ts_ms | ver | rand_a | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |var| rand_b | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | rand_b | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + _ = uuid[15] // bounds check + + t := timeNow().UnixMilli() + + uuid[0] = byte(t >> 40) + uuid[1] = byte(t >> 32) + uuid[2] = byte(t >> 24) + uuid[3] = byte(t >> 16) + uuid[4] = byte(t >> 8) + uuid[5] = byte(t) + + uuid[6] = 0x70 | (uuid[6] & 0x0F) + // uuid[8] has already has right version +} diff --git a/vendor/github.com/googleapis/enterprise-certificate-proxy/client/client.go b/vendor/github.com/googleapis/enterprise-certificate-proxy/client/client.go index b3283b815..ea5beb5aa 100644 --- a/vendor/github.com/googleapis/enterprise-certificate-proxy/client/client.go +++ b/vendor/github.com/googleapis/enterprise-certificate-proxy/client/client.go @@ -35,6 +35,8 @@ import ( const signAPI = "EnterpriseCertSigner.Sign" const certificateChainAPI = "EnterpriseCertSigner.CertificateChain" const publicKeyAPI = "EnterpriseCertSigner.Public" +const encryptAPI = "EnterpriseCertSigner.Encrypt" +const decryptAPI = "EnterpriseCertSigner.Decrypt" // A Connection wraps a pair of unidirectional streams as an io.ReadWriteCloser. type Connection struct { @@ -54,13 +56,28 @@ func (c *Connection) Close() error { func init() { gob.Register(crypto.SHA256) + gob.Register(crypto.SHA384) + gob.Register(crypto.SHA512) gob.Register(&rsa.PSSOptions{}) + gob.Register(&rsa.OAEPOptions{}) } -// SignArgs contains arguments to a crypto Signer.Sign method. +// SignArgs contains arguments for a Sign API call. type SignArgs struct { Digest []byte // The content to sign. - Opts crypto.SignerOpts // Options for signing, such as Hash identifier. + Opts crypto.SignerOpts // Options for signing. Must implement HashFunc(). +} + +// EncryptArgs contains arguments for an Encrypt API call. +type EncryptArgs struct { + Plaintext []byte // The plaintext to encrypt. + Opts any // Options for encryption. Ex: an instance of crypto.Hash. +} + +// DecryptArgs contains arguments to for a Decrypt API call. +type DecryptArgs struct { + Ciphertext []byte // The ciphertext to decrypt. + Opts crypto.DecrypterOpts // Options for decryption. Ex: an instance of *rsa.OAEPOptions. } // Key implements credential.Credential by holding the executed signer subprocess. @@ -98,7 +115,7 @@ func (k *Key) Public() crypto.PublicKey { return k.publicKey } -// Sign signs a message digest, using the specified signer options. +// Sign signs a message digest, using the specified signer opts. Implements crypto.Signer interface. func (k *Key) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) (signed []byte, err error) { if opts != nil && opts.HashFunc() != 0 && len(digest) != opts.HashFunc().Size() { return nil, fmt.Errorf("Digest length of %v bytes does not match Hash function size of %v bytes", len(digest), opts.HashFunc().Size()) @@ -107,6 +124,18 @@ func (k *Key) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) (signed [ return } +// Encrypt encrypts a plaintext msg into ciphertext, using the specified encrypt opts. +func (k *Key) Encrypt(_ io.Reader, msg []byte, opts any) (ciphertext []byte, err error) { + err = k.client.Call(encryptAPI, EncryptArgs{Plaintext: msg, Opts: opts}, &ciphertext) + return +} + +// Decrypt decrypts a ciphertext msg into plaintext, using the specified decrypter opts. Implements crypto.Decrypter interface. +func (k *Key) Decrypt(_ io.Reader, msg []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) { + err = k.client.Call(decryptAPI, DecryptArgs{Ciphertext: msg, Opts: opts}, &plaintext) + return +} + // ErrCredUnavailable is a sentinel error that indicates ECP Cred is unavailable, // possibly due to missing config or missing binary path. var ErrCredUnavailable = errors.New("Cred is unavailable") @@ -120,7 +149,12 @@ var ErrCredUnavailable = errors.New("Cred is unavailable") // The config file also specifies which certificate the signer should use. func Cred(configFilePath string) (*Key, error) { if configFilePath == "" { - configFilePath = util.GetDefaultConfigFilePath() + envFilePath := util.GetConfigFilePathFromEnv() + if envFilePath != "" { + configFilePath = envFilePath + } else { + configFilePath = util.GetDefaultConfigFilePath() + } } enterpriseCertSignerPath, err := util.LoadSignerBinaryPath(configFilePath) if err != nil { diff --git a/vendor/github.com/googleapis/enterprise-certificate-proxy/client/util/util.go b/vendor/github.com/googleapis/enterprise-certificate-proxy/client/util/util.go index 1640ec1c9..f374a7f55 100644 --- a/vendor/github.com/googleapis/enterprise-certificate-proxy/client/util/util.go +++ b/vendor/github.com/googleapis/enterprise-certificate-proxy/client/util/util.go @@ -22,6 +22,7 @@ import ( "os/user" "path/filepath" "runtime" + "strings" ) const configFileName = "certificate_config.json" @@ -63,6 +64,9 @@ func LoadSignerBinaryPath(configFilePath string) (path string, err error) { if signerBinaryPath == "" { return "", ErrConfigUnavailable } + + signerBinaryPath = strings.ReplaceAll(signerBinaryPath, "~", guessHomeDir()) + signerBinaryPath = strings.ReplaceAll(signerBinaryPath, "$HOME", guessHomeDir()) return signerBinaryPath, nil } @@ -89,3 +93,8 @@ func getDefaultConfigFileDirectory() (directory string) { func GetDefaultConfigFilePath() (path string) { return filepath.Join(getDefaultConfigFileDirectory(), configFileName) } + +// GetConfigFilePathFromEnv returns the path associated with environment variable GOOGLE_API_CERTIFICATE_CONFIG +func GetConfigFilePathFromEnv() (path string) { + return os.Getenv("GOOGLE_API_CERTIFICATE_CONFIG") +} diff --git a/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json b/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json index 91d60a809..ef508417b 100644 --- a/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json +++ b/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json @@ -1,3 +1,3 @@ { - "v2": "2.11.0" + "v2": "2.12.0" } diff --git a/vendor/github.com/googleapis/gax-go/v2/CHANGES.md b/vendor/github.com/googleapis/gax-go/v2/CHANGES.md index e17b196f6..ae7114947 100644 --- a/vendor/github.com/googleapis/gax-go/v2/CHANGES.md +++ b/vendor/github.com/googleapis/gax-go/v2/CHANGES.md @@ -1,5 +1,13 @@ # Changelog +## [2.12.0](https://github.com/googleapis/gax-go/compare/v2.11.0...v2.12.0) (2023-06-26) + + +### Features + +* **v2/callctx:** add new callctx package ([#291](https://github.com/googleapis/gax-go/issues/291)) ([11503ed](https://github.com/googleapis/gax-go/commit/11503ed98df4ae1bbdedf91ff64d47e63f187d68)) +* **v2:** add BuildHeaders and InsertMetadataIntoOutgoingContext to header ([#290](https://github.com/googleapis/gax-go/issues/290)) ([6a4b89f](https://github.com/googleapis/gax-go/commit/6a4b89f5551a40262e7c3caf2e1bdc7321b76ea1)) + ## [2.11.0](https://github.com/googleapis/gax-go/compare/v2.10.0...v2.11.0) (2023-06-13) diff --git a/vendor/github.com/googleapis/gax-go/v2/callctx/callctx.go b/vendor/github.com/googleapis/gax-go/v2/callctx/callctx.go new file mode 100644 index 000000000..af15fb582 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/v2/callctx/callctx.go @@ -0,0 +1,74 @@ +// Copyright 2023, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Package callctx provides helpers for storing and retrieving values out of +// [context.Context]. These values are used by our client libraries in various +// ways across the stack. +package callctx + +import ( + "context" + "fmt" +) + +const ( + headerKey = contextKey("header") +) + +// contextKey is a private type used to store/retrieve context values. +type contextKey string + +// HeadersFromContext retrieves headers set from [SetHeaders]. These headers +// can then be cast to http.Header or metadata.MD to send along on requests. +func HeadersFromContext(ctx context.Context) map[string][]string { + m, ok := ctx.Value(headerKey).(map[string][]string) + if !ok { + return nil + } + return m +} + +// SetHeaders stores key value pairs in the returned context that can later +// be retrieved by [HeadersFromContext]. Values stored in this manner will +// automatically be retrieved by client libraries and sent as outgoing headers +// on all requests. keyvals should have a corresponding value for every key +// provided. If there is an odd number of keyvals this method will panic. +func SetHeaders(ctx context.Context, keyvals ...string) context.Context { + if len(keyvals)%2 != 0 { + panic(fmt.Sprintf("callctx: an even number of key value pairs must be provided, got %d", len(keyvals))) + } + h, ok := ctx.Value(headerKey).(map[string][]string) + if !ok { + h = make(map[string][]string) + } + for i := 0; i < len(keyvals); i = i + 2 { + h[keyvals[i]] = append(h[keyvals[i]], keyvals[i+1]) + } + return context.WithValue(ctx, headerKey, h) +} diff --git a/vendor/github.com/googleapis/gax-go/v2/header.go b/vendor/github.com/googleapis/gax-go/v2/header.go index 6488461f4..453fab7ec 100644 --- a/vendor/github.com/googleapis/gax-go/v2/header.go +++ b/vendor/github.com/googleapis/gax-go/v2/header.go @@ -31,9 +31,15 @@ package gax import ( "bytes" + "context" + "fmt" + "net/http" "runtime" "strings" "unicode" + + "github.com/googleapis/gax-go/v2/callctx" + "google.golang.org/grpc/metadata" ) var ( @@ -117,3 +123,46 @@ func XGoogHeader(keyval ...string) string { } return buf.String()[1:] } + +// InsertMetadataIntoOutgoingContext is for use by the Google Cloud Libraries +// only. +// +// InsertMetadataIntoOutgoingContext returns a new context that merges the +// provided keyvals metadata pairs with any existing metadata/headers in the +// provided context. keyvals should have a corresponding value for every key +// provided. If there is an odd number of keyvals this method will panic. +// Existing values for keys will not be overwritten, instead provided values +// will be appended to the list of existing values. +func InsertMetadataIntoOutgoingContext(ctx context.Context, keyvals ...string) context.Context { + return metadata.NewOutgoingContext(ctx, insertMetadata(ctx, keyvals...)) +} + +// BuildHeaders is for use by the Google Cloud Libraries only. +// +// BuildHeaders returns a new http.Header that merges the provided +// keyvals header pairs with any existing metadata/headers in the provided +// context. keyvals should have a corresponding value for every key provided. +// If there is an odd number of keyvals this method will panic. +// Existing values for keys will not be overwritten, instead provided values +// will be appended to the list of existing values. +func BuildHeaders(ctx context.Context, keyvals ...string) http.Header { + return http.Header(insertMetadata(ctx, keyvals...)) +} + +func insertMetadata(ctx context.Context, keyvals ...string) metadata.MD { + if len(keyvals)%2 != 0 { + panic(fmt.Sprintf("gax: an even number of key value pairs must be provided, got %d", len(keyvals))) + } + out, ok := metadata.FromOutgoingContext(ctx) + if !ok { + out = metadata.MD(make(map[string][]string)) + } + headers := callctx.HeadersFromContext(ctx) + for k, v := range headers { + out[k] = append(out[k], v...) + } + for i := 0; i < len(keyvals); i = i + 2 { + out[keyvals[i]] = append(out[keyvals[i]], keyvals[i+1]) + } + return out +} diff --git a/vendor/github.com/googleapis/gax-go/v2/internal/version.go b/vendor/github.com/googleapis/gax-go/v2/internal/version.go index 374dcdb11..7425b5ffb 100644 --- a/vendor/github.com/googleapis/gax-go/v2/internal/version.go +++ b/vendor/github.com/googleapis/gax-go/v2/internal/version.go @@ -30,4 +30,4 @@ package internal // Version is the current tagged release of the library. -const Version = "2.11.0" +const Version = "2.12.0" diff --git a/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md b/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md index 9e2567b98..e13f9e17e 100644 --- a/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md +++ b/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md @@ -1,3 +1,92 @@ +## v1.8.0 (2023-11-30) + +New features and improvements: + +* [GH-2800](https://github.com/gophercloud/gophercloud/pull/2800) [v1] Fix options initialization in ServiceClient.Request (fixes #2798) +* [GH-2823](https://github.com/gophercloud/gophercloud/pull/2823) [v1] Add more godoc to GuestFormat +* [GH-2826](https://github.com/gophercloud/gophercloud/pull/2826) Allow objects.CreateTempURL with names containing /v1/ + +CI changes: + +* [GH-2802](https://github.com/gophercloud/gophercloud/pull/2802) [v1] Add job for bobcat stable/2023.2 +* [GH-2819](https://github.com/gophercloud/gophercloud/pull/2819) [v1] Test files alongside code +* [GH-2814](https://github.com/gophercloud/gophercloud/pull/2814) Make fixtures part of tests +* [GH-2796](https://github.com/gophercloud/gophercloud/pull/2796) [v1] ci/unit: switch to coverallsapp/github-action +* [GH-2840](https://github.com/gophercloud/gophercloud/pull/2840) unit tests: Fix the installation of tools + +## v1.7.0 (2023-09-22) + +New features and improvements: + +* [GH-2782](https://github.com/gophercloud/gophercloud/pull/2782) [v1] (manual clean backport) Add tag field to compute block_device_v2 + +CI changes: + +* [GH-2760](https://github.com/gophercloud/gophercloud/pull/2760) [v1 backports] semver auto labels +* [GH-2775](https://github.com/gophercloud/gophercloud/pull/2775) [v1] Fix typos in comments +* [GH-2783](https://github.com/gophercloud/gophercloud/pull/2783) [v1] (clean manual backport) ci/functional: fix ubuntu version & add antelope +* [GH-2785](https://github.com/gophercloud/gophercloud/pull/2785) [v1] Acceptance: Handle numerical version names in version comparison helpers +* [GH-2787](https://github.com/gophercloud/gophercloud/pull/2787) backport-v1: fixes to semver label +* [GH-2788](https://github.com/gophercloud/gophercloud/pull/2788) [v1] Make acceptance tests internal + + +## v1.6.0 (2023-08-30) + +New features and improvements: + +* [GH-2712](https://github.com/gophercloud/gophercloud/pull/2712) [v1] README: minor change to test backport workflow +* [GH-2713](https://github.com/gophercloud/gophercloud/pull/2713) [v1] tests: run MultiAttach with a capable Cinder Type +* [GH-2714](https://github.com/gophercloud/gophercloud/pull/2714) [v1] Add CRUD support for encryption in volume v3 types +* [GH-2715](https://github.com/gophercloud/gophercloud/pull/2715) [v1] Add projectID to fwaas_v2 policy CreateOpts and ListOpts +* [GH-2716](https://github.com/gophercloud/gophercloud/pull/2716) [v1] Add projectID to fwaas_v2 CreateOpts +* [GH-2717](https://github.com/gophercloud/gophercloud/pull/2717) [v1] [manila]: add reset and force delete actions to a snapshot +* [GH-2718](https://github.com/gophercloud/gophercloud/pull/2718) [v1] [cinder]: add reset and force delete actions to volumes and snapshots +* [GH-2721](https://github.com/gophercloud/gophercloud/pull/2721) [v1] orchestration: Explicit error in optionsmap creation +* [GH-2723](https://github.com/gophercloud/gophercloud/pull/2723) [v1] Add conductor API to Baremetal V1 +* [GH-2729](https://github.com/gophercloud/gophercloud/pull/2729) [v1] networking/v2/ports: allow list filter by security group + +CI changes: + +* [GH-2675](https://github.com/gophercloud/gophercloud/pull/2675) [v1][CI] Drop periodic jobs from stable branch +* [GH-2683](https://github.com/gophercloud/gophercloud/pull/2683) [v1] CI tweaks + + +## v1.5.0 (2023-06-21) + +New features and improvements: + +* [GH-2634](https://github.com/gophercloud/gophercloud/pull/2634) baremetal: update inspection inventory with recent additions +* [GH-2635](https://github.com/gophercloud/gophercloud/pull/2635) [manila]: Add Share Replicas support +* [GH-2637](https://github.com/gophercloud/gophercloud/pull/2637) [FWaaS_v2]: Add FWaaS_V2 workflow and enable tests +* [GH-2639](https://github.com/gophercloud/gophercloud/pull/2639) Implement errors.Unwrap() on unexpected status code errors +* [GH-2648](https://github.com/gophercloud/gophercloud/pull/2648) [manila]: implement share transfer API + + +## v1.4.0 (2023-05-25) + +New features and improvements: + +* [GH-2465](https://github.com/gophercloud/gophercloud/pull/2465) keystone: add v3 limits update operation +* [GH-2596](https://github.com/gophercloud/gophercloud/pull/2596) keystone: add v3 limits get operation +* [GH-2618](https://github.com/gophercloud/gophercloud/pull/2618) keystone: add v3 limits delete operation +* [GH-2616](https://github.com/gophercloud/gophercloud/pull/2616) Add CRUD support for register limit APIs +* [GH-2610](https://github.com/gophercloud/gophercloud/pull/2610) Add PUT/HEAD/DELETE for identity/v3/OS-INHERIT +* [GH-2597](https://github.com/gophercloud/gophercloud/pull/2597) Add validation and optimise objects.BulkDelete +* [GH-2602](https://github.com/gophercloud/gophercloud/pull/2602) [swift v1]: introduce a TempURLKey argument for objects.CreateTempURLOpts struct +* [GH-2623](https://github.com/gophercloud/gophercloud/pull/2623) Add the ability to remove ingress/egress policies from fwaas_v2 groups +* [GH-2625](https://github.com/gophercloud/gophercloud/pull/2625) neutron: Support trunk_details extension + +CI changes: + +* [GH-2608](https://github.com/gophercloud/gophercloud/pull/2608) Drop train and ussuri jobs +* [GH-2589](https://github.com/gophercloud/gophercloud/pull/2589) Bump EmilienM/devstack-action from 0.10 to 0.11 +* [GH-2604](https://github.com/gophercloud/gophercloud/pull/2604) Bump mheap/github-action-required-labels from 3 to 4 +* [GH-2620](https://github.com/gophercloud/gophercloud/pull/2620) Pin goimport dep to a version that works with go 1.14 +* [GH-2619](https://github.com/gophercloud/gophercloud/pull/2619) Fix version comparison for acceptance tests +* [GH-2627](https://github.com/gophercloud/gophercloud/pull/2627) Limits: Fix ToDo to create registered limit and use it +* [GH-2629](https://github.com/gophercloud/gophercloud/pull/2629) [manila]: Add share from snapshot restore functional test + + ## v1.3.0 (2023-03-28) * [GH-2464](https://github.com/gophercloud/gophercloud/pull/2464) keystone: add v3 limits create operation diff --git a/vendor/github.com/gophercloud/gophercloud/README.md b/vendor/github.com/gophercloud/gophercloud/README.md index 89b08156f..4e6e57dad 100644 --- a/vendor/github.com/gophercloud/gophercloud/README.md +++ b/vendor/github.com/gophercloud/gophercloud/README.md @@ -1,6 +1,5 @@ # Gophercloud: an OpenStack SDK for Go -[![Build Status](https://travis-ci.org/gophercloud/gophercloud.svg?branch=master)](https://travis-ci.org/gophercloud/gophercloud) -[![Coverage Status](https://coveralls.io/repos/github/gophercloud/gophercloud/badge.svg?branch=master)](https://coveralls.io/github/gophercloud/gophercloud?branch=master) +[![Coverage Status](https://coveralls.io/repos/github/gophercloud/gophercloud/badge.svg?branch=v1)](https://coveralls.io/github/gophercloud/gophercloud?branch=v1) Gophercloud is an OpenStack Go SDK. @@ -40,7 +39,7 @@ You will need to retrieve the following: Credentials, a pre-generated token, or any other supported authentication mechanism. -For users that have the OpenStack dashboard installed, there's a shortcut. If +For users who have the OpenStack dashboard installed, there's a shortcut. If you visit the `project/api_access` path in Horizon and click on the "Download OpenStack RC File" button at the top right hand corner, you can download either a `clouds.yaml` file or an `openrc` bash file that exports all diff --git a/vendor/github.com/gophercloud/gophercloud/errors.go b/vendor/github.com/gophercloud/gophercloud/errors.go index edba02bad..8ab592ca4 100644 --- a/vendor/github.com/gophercloud/gophercloud/errors.go +++ b/vendor/github.com/gophercloud/gophercloud/errors.go @@ -116,61 +116,109 @@ type ErrDefault400 struct { ErrUnexpectedResponseCode } +func (e ErrDefault400) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault401 is the default error type returned on a 401 HTTP response code. type ErrDefault401 struct { ErrUnexpectedResponseCode } +func (e ErrDefault401) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault403 is the default error type returned on a 403 HTTP response code. type ErrDefault403 struct { ErrUnexpectedResponseCode } +func (e ErrDefault403) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault404 is the default error type returned on a 404 HTTP response code. type ErrDefault404 struct { ErrUnexpectedResponseCode } +func (e ErrDefault404) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault405 is the default error type returned on a 405 HTTP response code. type ErrDefault405 struct { ErrUnexpectedResponseCode } +func (e ErrDefault405) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault408 is the default error type returned on a 408 HTTP response code. type ErrDefault408 struct { ErrUnexpectedResponseCode } +func (e ErrDefault408) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault409 is the default error type returned on a 409 HTTP response code. type ErrDefault409 struct { ErrUnexpectedResponseCode } +func (e ErrDefault409) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault429 is the default error type returned on a 429 HTTP response code. type ErrDefault429 struct { ErrUnexpectedResponseCode } +func (e ErrDefault429) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault500 is the default error type returned on a 500 HTTP response code. type ErrDefault500 struct { ErrUnexpectedResponseCode } +func (e ErrDefault500) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault502 is the default error type returned on a 502 HTTP response code. type ErrDefault502 struct { ErrUnexpectedResponseCode } +func (e ErrDefault502) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault503 is the default error type returned on a 503 HTTP response code. type ErrDefault503 struct { ErrUnexpectedResponseCode } +func (e ErrDefault503) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + // ErrDefault504 is the default error type returned on a 504 HTTP response code. type ErrDefault504 struct { ErrUnexpectedResponseCode } +func (e ErrDefault504) Unwrap() error { + return e.ErrUnexpectedResponseCode +} + func (e ErrDefault400) Error() string { e.DefaultErrString = fmt.Sprintf( "Bad request with: [%s %s], error message: %s", diff --git a/vendor/github.com/gophercloud/gophercloud/provider_client.go b/vendor/github.com/gophercloud/gophercloud/provider_client.go index c603d6dbe..ce291a3ab 100644 --- a/vendor/github.com/gophercloud/gophercloud/provider_client.go +++ b/vendor/github.com/gophercloud/gophercloud/provider_client.go @@ -14,7 +14,7 @@ import ( // DefaultUserAgent is the default User-Agent string set in the request header. const ( - DefaultUserAgent = "gophercloud/v1.3.0" + DefaultUserAgent = "gophercloud/v1.8.0" DefaultMaxBackoffRetries = 60 ) diff --git a/vendor/github.com/gophercloud/gophercloud/service_client.go b/vendor/github.com/gophercloud/gophercloud/service_client.go index dd54abe30..94a161e34 100644 --- a/vendor/github.com/gophercloud/gophercloud/service_client.go +++ b/vendor/github.com/gophercloud/gophercloud/service_client.go @@ -47,7 +47,7 @@ func (client *ServiceClient) ServiceURL(parts ...string) string { return client.ResourceBaseURL() + strings.Join(parts, "/") } -func (client *ServiceClient) initReqOpts(url string, JSONBody interface{}, JSONResponse interface{}, opts *RequestOpts) { +func (client *ServiceClient) initReqOpts(JSONBody interface{}, JSONResponse interface{}, opts *RequestOpts) { if v, ok := (JSONBody).(io.Reader); ok { opts.RawBody = v } else if JSONBody != nil { @@ -57,14 +57,6 @@ func (client *ServiceClient) initReqOpts(url string, JSONBody interface{}, JSONR if JSONResponse != nil { opts.JSONResponse = JSONResponse } - - if opts.MoreHeaders == nil { - opts.MoreHeaders = make(map[string]string) - } - - if client.Microversion != "" { - client.setMicroversionHeader(opts) - } } // Get calls `Request` with the "GET" HTTP verb. @@ -72,7 +64,7 @@ func (client *ServiceClient) Get(url string, JSONResponse interface{}, opts *Req if opts == nil { opts = new(RequestOpts) } - client.initReqOpts(url, nil, JSONResponse, opts) + client.initReqOpts(nil, JSONResponse, opts) return client.Request("GET", url, opts) } @@ -81,7 +73,7 @@ func (client *ServiceClient) Post(url string, JSONBody interface{}, JSONResponse if opts == nil { opts = new(RequestOpts) } - client.initReqOpts(url, JSONBody, JSONResponse, opts) + client.initReqOpts(JSONBody, JSONResponse, opts) return client.Request("POST", url, opts) } @@ -90,7 +82,7 @@ func (client *ServiceClient) Put(url string, JSONBody interface{}, JSONResponse if opts == nil { opts = new(RequestOpts) } - client.initReqOpts(url, JSONBody, JSONResponse, opts) + client.initReqOpts(JSONBody, JSONResponse, opts) return client.Request("PUT", url, opts) } @@ -99,7 +91,7 @@ func (client *ServiceClient) Patch(url string, JSONBody interface{}, JSONRespons if opts == nil { opts = new(RequestOpts) } - client.initReqOpts(url, JSONBody, JSONResponse, opts) + client.initReqOpts(JSONBody, JSONResponse, opts) return client.Request("PATCH", url, opts) } @@ -108,7 +100,7 @@ func (client *ServiceClient) Delete(url string, opts *RequestOpts) (*http.Respon if opts == nil { opts = new(RequestOpts) } - client.initReqOpts(url, nil, nil, opts) + client.initReqOpts(nil, nil, opts) return client.Request("DELETE", url, opts) } @@ -117,7 +109,7 @@ func (client *ServiceClient) Head(url string, opts *RequestOpts) (*http.Response if opts == nil { opts = new(RequestOpts) } - client.initReqOpts(url, nil, nil, opts) + client.initReqOpts(nil, nil, opts) return client.Request("HEAD", url, opts) } @@ -142,10 +134,19 @@ func (client *ServiceClient) setMicroversionHeader(opts *RequestOpts) { // Request carries out the HTTP operation for the service client func (client *ServiceClient) Request(method, url string, options *RequestOpts) (*http.Response, error) { + if options.MoreHeaders == nil { + options.MoreHeaders = make(map[string]string) + } + + if client.Microversion != "" { + client.setMicroversionHeader(options) + } + if len(client.MoreHeaders) > 0 { if options == nil { options = new(RequestOpts) } + for k, v := range client.MoreHeaders { options.MoreHeaders[k] = v } diff --git a/vendor/github.com/hashicorp/consul/api/.copywrite.hcl b/vendor/github.com/hashicorp/consul/api/.copywrite.hcl new file mode 100644 index 000000000..7e4c0b58a --- /dev/null +++ b/vendor/github.com/hashicorp/consul/api/.copywrite.hcl @@ -0,0 +1,8 @@ +schema_version = 1 + +project { + license = "MPL-2.0" + copyright_year = 2024 + + header_ignore = [] +} diff --git a/vendor/github.com/hashicorp/consul/api/LICENSE b/vendor/github.com/hashicorp/consul/api/LICENSE index c72625e4c..7c5baa45e 100644 --- a/vendor/github.com/hashicorp/consul/api/LICENSE +++ b/vendor/github.com/hashicorp/consul/api/LICENSE @@ -1,92 +1,92 @@ -Copyright (c) 2013 HashiCorp, Inc. +Copyright (c) 2020 HashiCorp, Inc. Mozilla Public License, version 2.0 1. Definitions -1.1. “Contributor†+1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. -1.2. “Contributor Version†+1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. + Contributor and that particular Contributor's Contribution. -1.3. “Contribution†+1.3. "Contribution" means Covered Software of a particular Contributor. -1.4. “Covered Software†+1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. -1.5. “Incompatible With Secondary Licenses†+1.5. "Incompatible With Secondary Licenses" means a. that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. + b. that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the terms of + a Secondary License. -1.6. “Executable Form†+1.6. "Executable Form" means any form of the work other than Source Code Form. -1.7. “Larger Work†+1.7. "Larger Work" - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. + means a work that combines Covered Software with other material, in a + separate file or files, that is not Covered Software. -1.8. “License†+1.8. "License" means this document. -1.9. “Licensable†+1.9. "Licensable" - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. + means having the right to grant, to the maximum extent possible, whether + at the time of the initial grant or subsequently, any and all of the + rights conveyed by this License. -1.10. “Modifications†+1.10. "Modifications" means any of the following: - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or + a. any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered Software; or b. any new file in Source Code Form that contains any Covered Software. -1.11. “Patent Claims†of a Contributor +1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the License, + by the making, using, selling, offering for sale, having made, import, + or transfer of either its Contributions or its Contributor Version. -1.12. “Secondary License†+1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. -1.13. “Source Code Form†+1.13. "Source Code Form" means the form of the work preferred for making modifications. -1.14. “You†(or “Yourâ€) +1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this - License. For legal entities, “You†includes any entity that controls, is + License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this - definition, “control†means (a) the power, direct or indirect, to cause + definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. @@ -102,57 +102,59 @@ Mozilla Public License, version 2.0 a. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. + sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. 2.2. Effective Date - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. + The licenses granted in Section 2.1 with respect to any Contribution + become effective for each Contribution on the date the Contributor first + distributes such Contribution. 2.3. Limitations on Grant Scope - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: + The licenses granted in this Section 2 are the only rights granted under + this License. No additional rights or licenses will be implied from the + distribution or licensing of Covered Software under this License. + Notwithstanding Section 2.1(b) above, no patent license is granted by a + Contributor: a. for any code that a Contributor has removed from Covered Software; or - b. for infringements caused by: (i) Your and any other third party’s + b. for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. + c. under Patent Claims infringed by Covered Software in the absence of + its Contributions. - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). + This License does not grant any rights in the trademarks, service marks, + or logos of any Contributor (except as may be necessary to comply with + the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). + distribute the Covered Software under a subsequent version of this + License (see Section 10.2) or under the terms of a Secondary License (if + permitted under the terms of Section 3.3). 2.5. Representation - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. + Each Contributor represents that the Contributor believes its + Contributions are its original creation(s) or it has sufficient rights to + grant the rights to its Contributions conveyed by this License. 2.6. Fair Use - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. + This License is not intended to limit any rights You have under + applicable copyright doctrines of fair use, fair dealing, or other + equivalents. 2.7. Conditions @@ -165,11 +167,12 @@ Mozilla Public License, version 2.0 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. + Modifications that You create or to which You contribute, must be under + the terms of this License. You must inform recipients that the Source + Code Form of the Covered Software is governed by the terms of this + License, and how they can obtain a copy of this License. You may not + attempt to alter or restrict the recipients' rights in the Source Code + Form. 3.2. Distribution of Executable Form @@ -181,39 +184,40 @@ Mozilla Public License, version 2.0 reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. + b. You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter the + recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). + provided that You also comply with the requirements of this License for + the Covered Software. If the Larger Work is a combination of Covered + Software with a work governed by one or more Secondary Licenses, and the + Covered Software is not Incompatible With Secondary Licenses, this + License permits You to additionally distribute such Covered Software + under the terms of such Secondary License(s), so that the recipient of + the Larger Work may, at their option, further distribute the Covered + Software under the terms of either this License or such Secondary + License(s). 3.4. Notices - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. + You may not remove or alter the substance of any license notices + (including copyright notices, patent notices, disclaimers of warranty, or + limitations of liability) contained within the Source Code Form of the + Covered Software, except that You may alter any license notices to the + extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any + Software. However, You may do so only on Your own behalf, and not on + behalf of any Contributor. You must make it absolutely clear that any + such warranty, support, indemnity, or liability obligation is offered by + You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any @@ -222,14 +226,14 @@ Mozilla Public License, version 2.0 4. Inability to Comply Due to Statute or Regulation If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. + with respect to some or all of the Covered Software due to statute, + judicial order, or regulation then You must: (a) comply with the terms of + this License to the maximum extent possible; and (b) describe the + limitations and the code they affect. Such description must be placed in a + text file included with all distributions of the Covered Software under + this License. Except to the extent prohibited by statute or regulation, + such description must be sufficiently detailed for a recipient of ordinary + skill to be able to understand it. 5. Termination @@ -237,21 +241,22 @@ Mozilla Public License, version 2.0 fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. + explicitly and finally terminates Your grants, and (b) on an ongoing + basis, if such Contributor fails to notify You of the non-compliance by + some reasonable means prior to 60 days after You have come back into + compliance. Moreover, Your grants from a particular Contributor are + reinstated on an ongoing basis if such Contributor notifies You of the + non-compliance by some reasonable means, this is the first time You have + received notice of non-compliance with this License from such + Contributor, and You become compliant prior to 30 days after Your receipt + of the notice. 5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. + infringement claim (excluding declaratory judgment actions, + counter-claims, and cross-claims) alleging that a Contributor Version + directly or indirectly infringes any patent, then the rights granted to + You by any and all Contributors for the Covered Software under Section + 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been @@ -260,16 +265,16 @@ Mozilla Public License, version 2.0 6. Disclaimer of Warranty - Covered Software is provided under this License on an “as is†basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. + Covered Software is provided under this License on an "as is" basis, + without warranty of any kind, either expressed, implied, or statutory, + including, without limitation, warranties that the Covered Software is free + of defects, merchantable, fit for a particular purpose or non-infringing. + The entire risk as to the quality and performance of the Covered Software + is with You. Should any Covered Software prove defective in any respect, + You (not any Contributor) assume the cost of any necessary servicing, + repair, or correction. This disclaimer of warranty constitutes an essential + part of this License. No use of any Covered Software is authorized under + this License except under this disclaimer. 7. Limitation of Liability @@ -281,27 +286,29 @@ Mozilla Public License, version 2.0 goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. + shall not apply to liability for death or personal injury resulting from + such party's negligence to the extent applicable law prohibits such + limitation. Some jurisdictions do not allow the exclusion or limitation of + incidental or consequential damages, so this exclusion and limitation may + not apply to You. 8. Litigation - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. + Any litigation relating to this License may be brought only in the courts + of a jurisdiction where the defendant maintains its principal place of + business and such litigation shall be governed by laws of that + jurisdiction, without reference to its conflict-of-law provisions. Nothing + in this Section shall prevent a party's ability to bring cross-claims or + counter-claims. 9. Miscellaneous - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. + This License represents the complete agreement concerning the subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. Any law or regulation which provides that + the language of a contract shall be construed against the drafter shall not + be used to construe this License against a Contributor. 10. Versions of the License @@ -315,23 +322,24 @@ Mozilla Public License, version 2.0 10.2. Effect of New Versions - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license + You may distribute the Covered Software under the terms of the version + of the License under which You originally received the Covered Software, + or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). + create a new license for such software, you may create and use a + modified version of this License if you rename the license and remove + any references to the name of the license steward (except to note that + such modified license differs from this License). -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. +10.4. Distributing Source Code Form that is Incompatible With Secondary + Licenses If You choose to distribute Source Code Form that is + Incompatible With Secondary Licenses under the terms of this version of + the License, the notice described in Exhibit B of this License must be + attached. Exhibit A - Source Code Form License Notice @@ -342,15 +350,16 @@ Exhibit A - Source Code Form License Notice obtain one at http://mozilla.org/MPL/2.0/. -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. +If it is not possible or desirable to put the notice in a particular file, +then You may include the notice in a location (such as a LICENSE file in a +relevant directory) where a recipient would be likely to look for such a +notice. You may add additional accurate notices of copyright ownership. -Exhibit B - “Incompatible With Secondary Licenses†Notice +Exhibit B - "Incompatible With Secondary Licenses" Notice - This Source Code Form is “Incompatible - With Secondary Licensesâ€, as defined by + This Source Code Form is "Incompatible + With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/consul/api/acl.go b/vendor/github.com/hashicorp/consul/api/acl.go index 3e13ccc88..f95e597af 100644 --- a/vendor/github.com/hashicorp/consul/api/acl.go +++ b/vendor/github.com/hashicorp/consul/api/acl.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -16,6 +19,15 @@ const ( // ACLManagementType is the management type token ACLManagementType = "management" + + // ACLTemplatedPolicy names + ACLTemplatedPolicyServiceName = "builtin/service" + ACLTemplatedPolicyNodeName = "builtin/node" + ACLTemplatedPolicyDNSName = "builtin/dns" + ACLTemplatedPolicyNomadServerName = "builtin/nomad-server" + ACLTemplatedPolicyWorkloadIdentityName = "builtin/workload-identity" + ACLTemplatedPolicyAPIGatewayName = "builtin/api-gateway" + ACLTemplatedPolicyNomadClientName = "builtin/nomad-client" ) type ACLLink struct { @@ -37,6 +49,7 @@ type ACLToken struct { Roles []*ACLTokenRoleLink `json:",omitempty"` ServiceIdentities []*ACLServiceIdentity `json:",omitempty"` NodeIdentities []*ACLNodeIdentity `json:",omitempty"` + TemplatedPolicies []*ACLTemplatedPolicy `json:",omitempty"` Local bool AuthMethod string `json:",omitempty"` ExpirationTTL time.Duration `json:",omitempty"` @@ -85,6 +98,7 @@ type ACLTokenListEntry struct { Roles []*ACLTokenRoleLink `json:",omitempty"` ServiceIdentities []*ACLServiceIdentity `json:",omitempty"` NodeIdentities []*ACLNodeIdentity `json:",omitempty"` + TemplatedPolicies []*ACLTemplatedPolicy `json:",omitempty"` Local bool AuthMethod string `json:",omitempty"` ExpirationTime *time.Time `json:",omitempty"` @@ -145,6 +159,28 @@ type ACLNodeIdentity struct { Datacenter string } +// ACLTemplatedPolicy represents a template used to generate a `synthetic` policy +// given some input variables. +type ACLTemplatedPolicy struct { + TemplateName string + TemplateVariables *ACLTemplatedPolicyVariables `json:",omitempty"` + + // Datacenters are an artifact of Nodeidentity & ServiceIdentity. + // It is used to facilitate the future migration away from both + Datacenters []string `json:",omitempty"` +} + +type ACLTemplatedPolicyResponse struct { + TemplateName string + Schema string + Template string + Description string +} + +type ACLTemplatedPolicyVariables struct { + Name string +} + // ACLPolicy represents an ACL Policy. type ACLPolicy struct { ID string @@ -193,6 +229,7 @@ type ACLRole struct { Policies []*ACLRolePolicyLink `json:",omitempty"` ServiceIdentities []*ACLServiceIdentity `json:",omitempty"` NodeIdentities []*ACLNodeIdentity `json:",omitempty"` + TemplatedPolicies []*ACLTemplatedPolicy `json:",omitempty"` Hash []byte CreateIndex uint64 ModifyIndex uint64 @@ -215,6 +252,12 @@ const ( // BindingRuleBindTypeRole binds to pre-existing roles with the given name. BindingRuleBindTypeRole BindingRuleBindType = "role" + + // BindingRuleBindTypeNode binds to a node identity with given name. + BindingRuleBindTypeNode BindingRuleBindType = "node" + + // BindingRuleBindTypeTemplatedPolicy binds to a templated policy with given template name and variables. + BindingRuleBindTypeTemplatedPolicy BindingRuleBindType = "templated-policy" ) type ACLBindingRule struct { @@ -224,6 +267,7 @@ type ACLBindingRule struct { Selector string BindType BindingRuleBindType BindName string + BindVars *ACLTemplatedPolicyVariables `json:",omitempty"` CreateIndex uint64 ModifyIndex uint64 @@ -269,6 +313,13 @@ type ACLAuthMethod struct { Partition string `json:",omitempty"` } +type ACLTokenFilterOptions struct { + AuthMethod string `json:",omitempty"` + Policy string `json:",omitempty"` + Role string `json:",omitempty"` + ServiceName string `json:",omitempty"` +} + func (m *ACLAuthMethod) MarshalJSON() ([]byte, error) { type Alias ACLAuthMethod exported := &struct { @@ -892,6 +943,44 @@ func (a *ACL) TokenList(q *QueryOptions) ([]*ACLTokenListEntry, *QueryMeta, erro return entries, qm, nil } +// TokenListFiltered lists all tokens that match the given filter options. +// The listing does not contain any SecretIDs as those may only be retrieved by a call to TokenRead. +func (a *ACL) TokenListFiltered(t ACLTokenFilterOptions, q *QueryOptions) ([]*ACLTokenListEntry, *QueryMeta, error) { + r := a.c.newRequest("GET", "/v1/acl/tokens") + r.setQueryOptions(q) + + if t.AuthMethod != "" { + r.params.Set("authmethod", t.AuthMethod) + } + if t.Policy != "" { + r.params.Set("policy", t.Policy) + } + if t.Role != "" { + r.params.Set("role", t.Role) + } + if t.ServiceName != "" { + r.params.Set("servicename", t.ServiceName) + } + + rtt, resp, err := a.c.doRequest(r) + if err != nil { + return nil, nil, err + } + defer closeResponseBody(resp) + if err := requireOK(resp); err != nil { + return nil, nil, err + } + qm := &QueryMeta{} + parseQueryMeta(resp, qm) + qm.RequestTime = rtt + + var entries []*ACLTokenListEntry + if err := decodeBody(resp, &entries); err != nil { + return nil, nil, err + } + return entries, qm, nil +} + // PolicyCreate will create a new policy. It is not allowed for the policy parameters // ID field to be set as this will be generated by Consul while processing the request. func (a *ACL) PolicyCreate(policy *ACLPolicy, q *WriteOptions) (*ACLPolicy, *WriteMeta, error) { @@ -1575,3 +1664,78 @@ func (a *ACL) OIDCCallback(auth *ACLOIDCCallbackParams, q *WriteOptions) (*ACLTo } return &out, wm, nil } + +// TemplatedPolicyReadByName retrieves the templated policy details (by name). Returns nil if not found. +func (a *ACL) TemplatedPolicyReadByName(templateName string, q *QueryOptions) (*ACLTemplatedPolicyResponse, *QueryMeta, error) { + r := a.c.newRequest("GET", "/v1/acl/templated-policy/name/"+templateName) + r.setQueryOptions(q) + rtt, resp, err := a.c.doRequest(r) + if err != nil { + return nil, nil, err + } + defer closeResponseBody(resp) + found, resp, err := requireNotFoundOrOK(resp) + if err != nil { + return nil, nil, err + } + + qm := &QueryMeta{} + parseQueryMeta(resp, qm) + qm.RequestTime = rtt + + if !found { + return nil, qm, nil + } + + var out ACLTemplatedPolicyResponse + if err := decodeBody(resp, &out); err != nil { + return nil, nil, err + } + + return &out, qm, nil +} + +// TemplatedPolicyList retrieves a listing of all templated policies. +func (a *ACL) TemplatedPolicyList(q *QueryOptions) (map[string]ACLTemplatedPolicyResponse, *QueryMeta, error) { + r := a.c.newRequest("GET", "/v1/acl/templated-policies") + r.setQueryOptions(q) + rtt, resp, err := a.c.doRequest(r) + if err != nil { + return nil, nil, err + } + defer closeResponseBody(resp) + if err := requireOK(resp); err != nil { + return nil, nil, err + } + qm := &QueryMeta{} + parseQueryMeta(resp, qm) + qm.RequestTime = rtt + + var entries map[string]ACLTemplatedPolicyResponse + if err := decodeBody(resp, &entries); err != nil { + return nil, nil, err + } + return entries, qm, nil +} + +// TemplatedPolicyPreview is used to preview the policy rendered by the templated policy. +func (a *ACL) TemplatedPolicyPreview(tp *ACLTemplatedPolicy, q *WriteOptions) (*ACLPolicy, *WriteMeta, error) { + r := a.c.newRequest("POST", "/v1/acl/templated-policy/preview/"+tp.TemplateName) + r.setWriteOptions(q) + r.obj = tp.TemplateVariables + + rtt, resp, err := a.c.doRequest(r) + if err != nil { + return nil, nil, err + } + defer closeResponseBody(resp) + if err := requireOK(resp); err != nil { + return nil, nil, err + } + wm := &WriteMeta{RequestTime: rtt} + var out ACLPolicy + if err := decodeBody(resp, &out); err != nil { + return nil, nil, err + } + return &out, wm, nil +} diff --git a/vendor/github.com/hashicorp/consul/api/agent.go b/vendor/github.com/hashicorp/consul/api/agent.go index 7904e7b71..24e2c50d6 100644 --- a/vendor/github.com/hashicorp/consul/api/agent.go +++ b/vendor/github.com/hashicorp/consul/api/agent.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -104,7 +107,8 @@ type AgentService struct { Namespace string `json:",omitempty" bexpr:"-" hash:"ignore"` Partition string `json:",omitempty" bexpr:"-" hash:"ignore"` // Datacenter is only ever returned and is ignored if presented. - Datacenter string `json:",omitempty" bexpr:"-" hash:"ignore"` + Datacenter string `json:",omitempty" bexpr:"-" hash:"ignore"` + Locality *Locality `json:",omitempty" bexpr:"-" hash:"ignore"` } // AgentServiceChecksInfo returns information about a Service and its checks @@ -270,6 +274,8 @@ type MembersOpts struct { // Segment is the LAN segment to show members for. Setting this to the // AllSegments value above will show members in all segments. Segment string + + Filter string } // AgentServiceRegistration is used to register a new service @@ -291,6 +297,7 @@ type AgentServiceRegistration struct { Connect *AgentServiceConnect `json:",omitempty"` Namespace string `json:",omitempty" bexpr:"-" hash:"ignore"` Partition string `json:",omitempty" bexpr:"-" hash:"ignore"` + Locality *Locality `json:",omitempty" bexpr:"-" hash:"ignore"` } // ServiceRegisterOpts is used to pass extra options to the service register. @@ -300,6 +307,10 @@ type ServiceRegisterOpts struct { // having to manually deregister checks. ReplaceExistingChecks bool + // Token is used to provide a per-request ACL token + // which overrides the agent's default token. + Token string + // ctx is an optional context pass through to the underlying HTTP // request layer. Use WithContext() to set the context. ctx context.Context @@ -338,6 +349,7 @@ type AgentServiceCheck struct { Method string `json:",omitempty"` Body string `json:",omitempty"` TCP string `json:",omitempty"` + TCPUseTLS bool `json:",omitempty"` UDP string `json:",omitempty"` Status string `json:",omitempty"` Notes string `json:",omitempty"` @@ -498,6 +510,24 @@ func (a *Agent) Host() (map[string]interface{}, error) { return out, nil } +// Version is used to retrieve information about the running Consul version and build. +func (a *Agent) Version() (map[string]interface{}, error) { + r := a.c.newRequest("GET", "/v1/agent/version") + _, resp, err := a.c.doRequest(r) + if err != nil { + return nil, err + } + defer closeResponseBody(resp) + if err := requireOK(resp); err != nil { + return nil, err + } + var out map[string]interface{} + if err := decodeBody(resp, &out); err != nil { + return nil, err + } + return out, nil +} + // Metrics is used to query the agent we are speaking to for // its current internal metric data func (a *Agent) Metrics() (*MetricsInfo, error) { @@ -767,6 +797,10 @@ func (a *Agent) MembersOpts(opts MembersOpts) ([]*AgentMember, error) { r.params.Set("wan", "1") } + if opts.Filter != "" { + r.params.Set("filter", opts.Filter) + } + _, resp, err := a.c.doRequest(r) if err != nil { return nil, err @@ -805,6 +839,9 @@ func (a *Agent) serviceRegister(service *AgentServiceRegistration, opts ServiceR if opts.ReplaceExistingChecks { r.params.Set("replace-existing-checks", "true") } + if opts.Token != "" { + r.header.Set("X-Consul-Token", opts.Token) + } _, resp, err := a.c.doRequest(r) if err != nil { return err @@ -961,7 +998,14 @@ func (a *Agent) UpdateTTLOpts(checkID, output, status string, q *QueryOptions) e // CheckRegister is used to register a new check with // the local agent func (a *Agent) CheckRegister(check *AgentCheckRegistration) error { + return a.CheckRegisterOpts(check, nil) +} + +// CheckRegisterOpts is used to register a new check with +// the local agent using query options +func (a *Agent) CheckRegisterOpts(check *AgentCheckRegistration, q *QueryOptions) error { r := a.c.newRequest("PUT", "/v1/agent/check/register") + r.setQueryOptions(q) r.obj = check _, resp, err := a.c.doRequest(r) if err != nil { @@ -1050,8 +1094,17 @@ func (a *Agent) ForceLeavePrune(node string) error { // ForceLeaveOpts is used to have the agent eject a failed node or remove it // completely from the list of members. +// +// DEPRECATED - Use ForceLeaveOptions instead. func (a *Agent) ForceLeaveOpts(node string, opts ForceLeaveOpts) error { + return a.ForceLeaveOptions(node, opts, nil) +} + +// ForceLeaveOptions is used to have the agent eject a failed node or remove it +// completely from the list of members. Allows usage of QueryOptions on-top of ForceLeaveOpts +func (a *Agent) ForceLeaveOptions(node string, opts ForceLeaveOpts, q *QueryOptions) error { r := a.c.newRequest("PUT", "/v1/agent/force-leave/"+node) + r.setQueryOptions(q) if opts.Prune { r.params.Set("prune", "1") } @@ -1340,6 +1393,10 @@ func (a *Agent) UpdateConfigFileRegistrationToken(token string, q *WriteOptions) return a.updateToken("config_file_service_registration", token, q) } +func (a *Agent) UpdateDNSToken(token string, q *WriteOptions) (*WriteMeta, error) { + return a.updateToken("dns", token, q) +} + // updateToken can be used to update one of an agent's ACL tokens after the agent has // started. The tokens are may not be persisted, so will need to be updated again if // the agent is restarted unless the agent is configured to persist them. diff --git a/vendor/github.com/hashicorp/consul/api/api.go b/vendor/github.com/hashicorp/consul/api/api.go index 772f8693b..f62c0c5a1 100644 --- a/vendor/github.com/hashicorp/consul/api/api.go +++ b/vendor/github.com/hashicorp/consul/api/api.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -833,12 +836,21 @@ func (r *request) setQueryOptions(q *QueryOptions) { return } if q.Namespace != "" { + // For backwards-compatibility with existing tests, + // use the short-hand query param name "ns" + // rather than the alternative long-hand "namespace" r.params.Set("ns", q.Namespace) } if q.Partition != "" { + // For backwards-compatibility with existing tests, + // use the long-hand query param name "partition" + // rather than the alternative short-hand "ap" r.params.Set("partition", q.Partition) } if q.Datacenter != "" { + // For backwards-compatibility with existing tests, + // use the short-hand query param name "dc" + // rather than the alternative long-hand "datacenter" r.params.Set("dc", q.Datacenter) } if q.Peer != "" { @@ -946,12 +958,16 @@ func (r *request) setWriteOptions(q *WriteOptions) { if q == nil { return } + // For backwards-compatibility, continue to use the shorthand "ns" + // rather than "namespace" if q.Namespace != "" { r.params.Set("ns", q.Namespace) } if q.Partition != "" { r.params.Set("partition", q.Partition) } + // For backwards-compatibility, continue to use the shorthand "dc" + // rather than "datacenter" if q.Datacenter != "" { r.params.Set("dc", q.Datacenter) } @@ -984,6 +1000,19 @@ func (r *request) toHTTP() (*http.Request, error) { return nil, err } + // validate that socket communications that do not use the host, detect + // slashes in the host name and replace it with local host. + // this is required since go started validating req.host in 1.20.6 and 1.19.11. + // prior to that they would strip out the slashes for you. They removed that + // behavior and added more strict validation as part of a CVE. + // This issue is being tracked by the Go team: + // https://github.com/golang/go/issues/61431 + // If there is a resolution in this issue, we will remove this code. + // In the time being, this is the accepted workaround. + if strings.HasPrefix(r.url.Host, "/") { + r.url.Host = "localhost" + } + req.URL.Host = r.url.Host req.URL.Scheme = r.url.Scheme req.Host = r.url.Host diff --git a/vendor/github.com/hashicorp/consul/api/catalog.go b/vendor/github.com/hashicorp/consul/api/catalog.go index 84a2bdbc6..0040ca6e7 100644 --- a/vendor/github.com/hashicorp/consul/api/catalog.go +++ b/vendor/github.com/hashicorp/consul/api/catalog.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -19,8 +22,9 @@ type Node struct { Meta map[string]string CreateIndex uint64 ModifyIndex uint64 - Partition string `json:",omitempty"` - PeerName string `json:",omitempty"` + Partition string `json:",omitempty"` + PeerName string `json:",omitempty"` + Locality *Locality `json:",omitempty"` } type ServiceAddress struct { @@ -45,6 +49,7 @@ type CatalogService struct { ServiceWeights Weights ServiceEnableTagOverride bool ServiceProxy *AgentServiceConnectProxyConfig + ServiceLocality *Locality `json:",omitempty"` CreateIndex uint64 Checks HealthChecks ModifyIndex uint64 @@ -73,7 +78,8 @@ type CatalogRegistration struct { Check *AgentCheck Checks HealthChecks SkipNodeUpdate bool - Partition string `json:",omitempty"` + Partition string `json:",omitempty"` + Locality *Locality `json:",omitempty"` } type CatalogDeregistration struct { diff --git a/vendor/github.com/hashicorp/consul/api/config_entry.go b/vendor/github.com/hashicorp/consul/api/config_entry.go index 4e9682ee6..ffc18a85e 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -23,6 +26,8 @@ const ( ServiceIntentions string = "service-intentions" MeshConfig string = "mesh" ExportedServices string = "exported-services" + SamenessGroup string = "sameness-group" + RateLimitIPConfig string = "control-plane-request-limit" ProxyConfigGlobal string = "global" MeshConfigMesh string = "mesh" @@ -30,11 +35,20 @@ const ( TCPRoute string = "tcp-route" InlineCertificate string = "inline-certificate" HTTPRoute string = "http-route" + JWTProvider string = "jwt-provider" ) const ( - BuiltinAWSLambdaExtension string = "builtin/aws/lambda" - BuiltinLuaExtension string = "builtin/lua" + BuiltinAWSLambdaExtension string = "builtin/aws/lambda" + BuiltinExtAuthzExtension string = "builtin/ext-authz" + BuiltinLuaExtension string = "builtin/lua" + BuiltinOTELAccessLoggingExtension string = "builtin/otel-access-logging" + BuiltinPropertyOverrideExtension string = "builtin/property-override" + BuiltinWasmExtension string = "builtin/wasm" + // BuiltinValidateExtension should not be exposed directly or accepted as a valid configured + // extension type, as it is only used indirectly via troubleshooting tools. It is included here + // for common reference alongside other builtin extensions. + BuiltinValidateExtension string = "builtin/proxy/validate" ) type ConfigEntry interface { @@ -102,6 +116,21 @@ type TransparentProxyConfig struct { DialedDirectly bool `json:",omitempty" alias:"dialed_directly"` } +type MutualTLSMode string + +const ( + // MutualTLSModeDefault represents no specific mode and should + // be used to indicate that a different layer of the configuration + // chain should take precedence. + MutualTLSModeDefault MutualTLSMode = "" + + // MutualTLSModeStrict requires mTLS for incoming traffic. + MutualTLSModeStrict MutualTLSMode = "strict" + + // MutualTLSModePermissive allows incoming non-mTLS traffic. + MutualTLSModePermissive MutualTLSMode = "permissive" +) + // ExposeConfig describes HTTP paths to expose through Envoy outside of Connect. // Users can expose individual paths and/or all HTTP/GRPC paths for checks. type ExposeConfig struct { @@ -115,9 +144,11 @@ type ExposeConfig struct { // EnvoyExtension has configuration for an extension that patches Envoy resources. type EnvoyExtension struct { - Name string - Required bool - Arguments map[string]interface{} `bexpr:"-"` + Name string + Required bool + Arguments map[string]interface{} `bexpr:"-"` + ConsulVersion string + EnvoyVersion string } type ExposePath struct { @@ -254,6 +285,15 @@ type PassiveHealthCheck struct { // when an outlier status is detected through consecutive 5xx. // This setting can be used to disable ejection or to ramp it up slowly. EnforcingConsecutive5xx *uint32 `json:",omitempty" alias:"enforcing_consecutive_5xx"` + + // The maximum % of an upstream cluster that can be ejected due to outlier detection. + // Defaults to 10% but will eject at least one host regardless of the value. + MaxEjectionPercent *uint32 `json:",omitempty" alias:"max_ejection_percent"` + + // The base time that a host is ejected for. The real time is equal to the base time + // multiplied by the number of times the host has been ejected and is capped by + // max_ejection_time (Default 300s). Defaults to 30000ms or 30s. + BaseEjectionTime *time.Duration `json:",omitempty" alias:"base_ejection_time"` } // UpstreamLimits describes the limits that are associated with a specific @@ -275,6 +315,48 @@ type UpstreamLimits struct { MaxConcurrentRequests *int `alias:"max_concurrent_requests"` } +// RateLimits is rate limiting configuration that is applied to +// inbound traffic for a service. +// Rate limiting is a Consul enterprise feature. +type RateLimits struct { + InstanceLevel InstanceLevelRateLimits `alias:"instance_level"` +} + +// InstanceLevelRateLimits represents rate limit configuration +// that are applied per service instance. +type InstanceLevelRateLimits struct { + // RequestsPerSecond is the average number of requests per second that can be + // made without being throttled. This field is required if RequestsMaxBurst + // is set. The allowed number of requests may exceed RequestsPerSecond up to + // the value specified in RequestsMaxBurst. + // + // Internally, this is the refill rate of the token bucket used for rate limiting. + RequestsPerSecond int `alias:"requests_per_second"` + + // RequestsMaxBurst is the maximum number of requests that can be sent + // in a burst. Should be equal to or greater than RequestsPerSecond. + // If unset, defaults to RequestsPerSecond. + // + // Internally, this is the maximum size of the token bucket used for rate limiting. + RequestsMaxBurst int `alias:"requests_max_burst"` + + // Routes is a list of rate limits applied to specific routes. + // For a given request, the first matching route will be applied, if any + // Overrides any top-level configuration. + Routes []InstanceLevelRouteRateLimits +} + +// InstanceLevelRouteRateLimits represents rate limit configuration +// applied to a route matching one of PathExact/PathPrefix/PathRegex. +type InstanceLevelRouteRateLimits struct { + PathExact string `alias:"path_exact"` + PathPrefix string `alias:"path_prefix"` + PathRegex string `alias:"path_regex"` + + RequestsPerSecond int `alias:"requests_per_second"` + RequestsMaxBurst int `alias:"requests_max_burst"` +} + type ServiceConfigEntry struct { Kind string Name string @@ -283,6 +365,7 @@ type ServiceConfigEntry struct { Protocol string `json:",omitempty"` Mode ProxyMode `json:",omitempty"` TransparentProxy *TransparentProxyConfig `json:",omitempty" alias:"transparent_proxy"` + MutualTLSMode MutualTLSMode `json:",omitempty" alias:"mutual_tls_mode"` MeshGateway MeshGatewayConfig `json:",omitempty" alias:"mesh_gateway"` Expose ExposeConfig `json:",omitempty"` ExternalSNI string `json:",omitempty" alias:"external_sni"` @@ -292,6 +375,7 @@ type ServiceConfigEntry struct { LocalConnectTimeoutMs int `json:",omitempty" alias:"local_connect_timeout_ms"` LocalRequestTimeoutMs int `json:",omitempty" alias:"local_request_timeout_ms"` BalanceInboundConnections string `json:",omitempty" alias:"balance_inbound_connections"` + RateLimits *RateLimits `json:",omitempty" alias:"rate_limits"` EnvoyExtensions []EnvoyExtension `json:",omitempty" alias:"envoy_extensions"` Meta map[string]string `json:",omitempty"` CreateIndex uint64 @@ -307,17 +391,20 @@ func (s *ServiceConfigEntry) GetCreateIndex() uint64 { return s.CreateIndex func (s *ServiceConfigEntry) GetModifyIndex() uint64 { return s.ModifyIndex } type ProxyConfigEntry struct { - Kind string - Name string - Partition string `json:",omitempty"` - Namespace string `json:",omitempty"` - Mode ProxyMode `json:",omitempty"` - TransparentProxy *TransparentProxyConfig `json:",omitempty" alias:"transparent_proxy"` - Config map[string]interface{} `json:",omitempty"` - MeshGateway MeshGatewayConfig `json:",omitempty" alias:"mesh_gateway"` - Expose ExposeConfig `json:",omitempty"` - AccessLogs *AccessLogsConfig `json:",omitempty" alias:"access_logs"` - EnvoyExtensions []EnvoyExtension `json:",omitempty" alias:"envoy_extensions"` + Kind string + Name string + Partition string `json:",omitempty"` + Namespace string `json:",omitempty"` + Mode ProxyMode `json:",omitempty"` + TransparentProxy *TransparentProxyConfig `json:",omitempty" alias:"transparent_proxy"` + MutualTLSMode MutualTLSMode `json:",omitempty" alias:"mutual_tls_mode"` + Config map[string]interface{} `json:",omitempty"` + MeshGateway MeshGatewayConfig `json:",omitempty" alias:"mesh_gateway"` + Expose ExposeConfig `json:",omitempty"` + AccessLogs *AccessLogsConfig `json:",omitempty" alias:"access_logs"` + EnvoyExtensions []EnvoyExtension `json:",omitempty" alias:"envoy_extensions"` + FailoverPolicy *ServiceResolverFailoverPolicy `json:",omitempty" alias:"failover_policy"` + PrioritizeByLocality *ServiceResolverPrioritizeByLocality `json:",omitempty" alias:"prioritize_by_locality"` Meta map[string]string `json:",omitempty"` CreateIndex uint64 @@ -354,6 +441,8 @@ func makeConfigEntry(kind, name string) (ConfigEntry, error) { return &MeshConfigEntry{}, nil case ExportedServices: return &ExportedServicesConfigEntry{Name: name}, nil + case SamenessGroup: + return &SamenessGroupConfigEntry{Kind: kind, Name: name}, nil case APIGateway: return &APIGatewayConfigEntry{Kind: kind, Name: name}, nil case TCPRoute: @@ -362,6 +451,10 @@ func makeConfigEntry(kind, name string) (ConfigEntry, error) { return &InlineCertificateConfigEntry{Kind: kind, Name: name}, nil case HTTPRoute: return &HTTPRouteConfigEntry{Kind: kind, Name: name}, nil + case RateLimitIPConfig: + return &RateLimitIPConfigEntry{Kind: kind, Name: name}, nil + case JWTProvider: + return &JWTProviderConfigEntry{Kind: kind, Name: name}, nil default: return nil, fmt.Errorf("invalid config entry kind: %s", kind) } diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_discoverychain.go b/vendor/github.com/hashicorp/consul/api/config_entry_discoverychain.go index acc05e13e..eeb3a1074 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_discoverychain.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_discoverychain.go @@ -1,8 +1,13 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( "encoding/json" "time" + + "github.com/hashicorp/go-multierror" ) type ServiceRouterConfigEntry struct { @@ -169,6 +174,10 @@ type ServiceResolverConfigEntry struct { ConnectTimeout time.Duration `json:",omitempty" alias:"connect_timeout"` RequestTimeout time.Duration `json:",omitempty" alias:"request_timeout"` + // PrioritizeByLocality controls whether the locality of services within the + // local partition will be used to prioritize connectivity. + PrioritizeByLocality *ServiceResolverPrioritizeByLocality `json:",omitempty" alias:"prioritize_by_locality"` + // LoadBalancer determines the load balancing policy and configuration for services // issuing requests to this upstream service. LoadBalancer *LoadBalancer `json:",omitempty" alias:"load_balancer"` @@ -182,14 +191,19 @@ func (e *ServiceResolverConfigEntry) MarshalJSON() ([]byte, error) { type Alias ServiceResolverConfigEntry exported := &struct { ConnectTimeout string `json:",omitempty"` + RequestTimeout string `json:",omitempty"` *Alias }{ ConnectTimeout: e.ConnectTimeout.String(), + RequestTimeout: e.RequestTimeout.String(), Alias: (*Alias)(e), } if e.ConnectTimeout == 0 { exported.ConnectTimeout = "" } + if e.RequestTimeout == 0 { + exported.RequestTimeout = "" + } return json.Marshal(exported) } @@ -198,20 +212,27 @@ func (e *ServiceResolverConfigEntry) UnmarshalJSON(data []byte) error { type Alias ServiceResolverConfigEntry aux := &struct { ConnectTimeout string + RequestTimeout string *Alias }{ Alias: (*Alias)(e), } - if err := json.Unmarshal(data, &aux); err != nil { + var err error + if err = json.Unmarshal(data, &aux); err != nil { return err } - var err error + var merr *multierror.Error if aux.ConnectTimeout != "" { if e.ConnectTimeout, err = time.ParseDuration(aux.ConnectTimeout); err != nil { - return err + merr = multierror.Append(merr, err) } } - return nil + if aux.RequestTimeout != "" { + if e.RequestTimeout, err = time.ParseDuration(aux.RequestTimeout); err != nil { + merr = multierror.Append(merr, err) + } + } + return merr.ErrorOrNil() } func (e *ServiceResolverConfigEntry) GetKind() string { return e.Kind } @@ -234,15 +255,18 @@ type ServiceResolverRedirect struct { Partition string `json:",omitempty"` Datacenter string `json:",omitempty"` Peer string `json:",omitempty"` + SamenessGroup string `json:",omitempty" alias:"sameness_group"` } type ServiceResolverFailover struct { Service string `json:",omitempty"` ServiceSubset string `json:",omitempty" alias:"service_subset"` // Referencing other partitions is not supported. - Namespace string `json:",omitempty"` - Datacenters []string `json:",omitempty"` - Targets []ServiceResolverFailoverTarget `json:",omitempty"` + Namespace string `json:",omitempty"` + Datacenters []string `json:",omitempty"` + Targets []ServiceResolverFailoverTarget `json:",omitempty"` + Policy *ServiceResolverFailoverPolicy `json:",omitempty"` + SamenessGroup string `json:",omitempty" alias:"sameness_group"` } type ServiceResolverFailoverTarget struct { @@ -254,6 +278,20 @@ type ServiceResolverFailoverTarget struct { Peer string `json:",omitempty"` } +type ServiceResolverFailoverPolicy struct { + // Mode specifies the type of failover that will be performed. Valid values are + // "sequential", "" (equivalent to "sequential") and "order-by-locality". + Mode string `json:",omitempty"` + Regions []string `json:",omitempty"` +} + +type ServiceResolverPrioritizeByLocality struct { + // Mode specifies the type of prioritization that will be performed + // when selecting nodes in the local partition. + // Valid values are: "" (default "none"), "none", and "failover". + Mode string `json:",omitempty"` +} + // LoadBalancer determines the load balancing policy and configuration for services // issuing requests to this upstream service. type LoadBalancer struct { diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_exports.go b/vendor/github.com/hashicorp/consul/api/config_entry_exports.go index 52b0491f7..97920e40d 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_exports.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_exports.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import "encoding/json" @@ -51,6 +54,9 @@ type ServiceConsumer struct { // Peer is the name of the peer to export the service to. Peer string `json:",omitempty" alias:"peer_name"` + + // SamenessGroup is the name of the sameness group to export the service to. + SamenessGroup string `json:",omitempty" alias:"sameness_group"` } func (e *ExportedServicesConfigEntry) GetKind() string { return ExportedServices } diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_gateways.go b/vendor/github.com/hashicorp/consul/api/config_entry_gateways.go index 05e43832c..baf274e2d 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_gateways.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_gateways.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // IngressGatewayConfigEntry manages the configuration for an ingress service @@ -281,6 +284,10 @@ type APIGatewayListener struct { Protocol string // TLS is the TLS settings for the listener. TLS APIGatewayTLSConfiguration + // Override is the policy that overrides all other policy and route specific configuration + Override *APIGatewayPolicy `json:",omitempty"` + // Default is the policy that is the default for the listener and route, routes can override this behavior + Default *APIGatewayPolicy `json:",omitempty"` } // APIGatewayTLSConfiguration specifies the configuration of a listener’s @@ -299,3 +306,39 @@ type APIGatewayTLSConfiguration struct { // Only applicable to connections negotiated via TLS 1.2 or earlier CipherSuites []string `json:",omitempty" alias:"cipher_suites"` } + +// APIGatewayPolicy holds the policy that configures the gateway listener, this is used in the `Override` and `Default` fields of a listener +type APIGatewayPolicy struct { + // JWT holds the JWT configuration for the Listener + JWT *APIGatewayJWTRequirement `json:",omitempty"` +} + +// APIGatewayJWTRequirement holds the list of JWT providers to be verified against +type APIGatewayJWTRequirement struct { + // Providers is a list of providers to consider when verifying a JWT. + Providers []*APIGatewayJWTProvider `json:",omitempty"` +} + +// APIGatewayJWTProvider holds the provider and claim verification information +type APIGatewayJWTProvider struct { + // Name is the name of the JWT provider. There MUST be a corresponding + // "jwt-provider" config entry with this name. + Name string `json:",omitempty"` + + // VerifyClaims is a list of additional claims to verify in a JWT's payload. + VerifyClaims []*APIGatewayJWTClaimVerification `json:",omitempty" alias:"verify_claims"` +} + +// APIGatewayJWTClaimVerification holds the actual claim information to be verified +type APIGatewayJWTClaimVerification struct { + // Path is the path to the claim in the token JSON. + Path []string `json:",omitempty"` + + // Value is the expected value at the given path: + // - If the type at the path is a list then we verify + // that this value is contained in the list. + // + // - If the type at the path is a string then we verify + // that this value matches. + Value string `json:",omitempty"` +} diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_inline_certificate.go b/vendor/github.com/hashicorp/consul/api/config_entry_inline_certificate.go index bbf12ccaa..47a1ead05 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_inline_certificate.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_inline_certificate.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // InlineCertificateConfigEntry -- TODO stub diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_intentions.go b/vendor/github.com/hashicorp/consul/api/config_entry_intentions.go index 0bff5e8e3..3f03b0875 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_intentions.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_intentions.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import "time" @@ -9,6 +12,7 @@ type ServiceIntentionsConfigEntry struct { Namespace string `json:",omitempty"` Sources []*SourceIntention + JWT *IntentionJWTRequirement `json:",omitempty"` Meta map[string]string `json:",omitempty"` @@ -17,15 +21,16 @@ type ServiceIntentionsConfigEntry struct { } type SourceIntention struct { - Name string - Peer string `json:",omitempty"` - Partition string `json:",omitempty"` - Namespace string `json:",omitempty"` - Action IntentionAction `json:",omitempty"` - Permissions []*IntentionPermission `json:",omitempty"` - Precedence int - Type IntentionSourceType - Description string `json:",omitempty"` + Name string + Peer string `json:",omitempty"` + Partition string `json:",omitempty"` + Namespace string `json:",omitempty"` + SamenessGroup string `json:",omitempty" alias:"sameness_group"` + Action IntentionAction `json:",omitempty"` + Permissions []*IntentionPermission `json:",omitempty"` + Precedence int + Type IntentionSourceType + Description string `json:",omitempty"` LegacyID string `json:",omitempty" alias:"legacy_id"` LegacyMeta map[string]string `json:",omitempty" alias:"legacy_meta"` @@ -44,6 +49,7 @@ func (e *ServiceIntentionsConfigEntry) GetModifyIndex() uint64 { return e.Mo type IntentionPermission struct { Action IntentionAction HTTP *IntentionHTTPPermission `json:",omitempty"` + JWT *IntentionJWTRequirement `json:",omitempty"` } type IntentionHTTPPermission struct { @@ -65,3 +71,30 @@ type IntentionHTTPHeaderPermission struct { Regex string `json:",omitempty"` Invert bool `json:",omitempty"` } + +type IntentionJWTRequirement struct { + // Providers is a list of providers to consider when verifying a JWT. + Providers []*IntentionJWTProvider `json:",omitempty"` +} + +type IntentionJWTProvider struct { + // Name is the name of the JWT provider. There MUST be a corresponding + // "jwt-provider" config entry with this name. + Name string `json:",omitempty"` + + // VerifyClaims is a list of additional claims to verify in a JWT's payload. + VerifyClaims []*IntentionJWTClaimVerification `json:",omitempty" alias:"verify_claims"` +} + +type IntentionJWTClaimVerification struct { + // Path is the path to the claim in the token JSON. + Path []string `json:",omitempty"` + + // Value is the expected value at the given path: + // - If the type at the path is a list then we verify + // that this value is contained in the list. + // + // - If the type at the path is a string then we verify + // that this value matches. + Value string `json:",omitempty"` +} diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_jwt_provider.go b/vendor/github.com/hashicorp/consul/api/config_entry_jwt_provider.go new file mode 100644 index 000000000..270f0d564 --- /dev/null +++ b/vendor/github.com/hashicorp/consul/api/config_entry_jwt_provider.go @@ -0,0 +1,310 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +import ( + "time" +) + +const ( + DiscoveryTypeStrictDNS ClusterDiscoveryType = "STRICT_DNS" + DiscoveryTypeStatic ClusterDiscoveryType = "STATIC" + DiscoveryTypeLogicalDNS ClusterDiscoveryType = "LOGICAL_DNS" + DiscoveryTypeEDS ClusterDiscoveryType = "EDS" + DiscoveryTypeOriginalDST ClusterDiscoveryType = "ORIGINAL_DST" +) + +type JWTProviderConfigEntry struct { + // Kind is the kind of configuration entry and must be "jwt-provider". + Kind string `json:",omitempty"` + + // Name is the name of the provider being configured. + Name string `json:",omitempty"` + + // JSONWebKeySet defines a JSON Web Key Set, its location on disk, or the + // means with which to fetch a key set from a remote server. + JSONWebKeySet *JSONWebKeySet `json:",omitempty" alias:"json_web_key_set"` + + // Issuer is the entity that must have issued the JWT. + // This value must match the "iss" claim of the token. + Issuer string `json:",omitempty"` + + // Audiences is the set of audiences the JWT is allowed to access. + // If specified, all JWTs verified with this provider must address + // at least one of these to be considered valid. + Audiences []string `json:",omitempty"` + + // Locations where the JWT will be present in requests. + // Envoy will check all of these locations to extract a JWT. + // If no locations are specified Envoy will default to: + // 1. Authorization header with Bearer schema: + // "Authorization: Bearer " + // 2. access_token query parameter. + Locations []*JWTLocation `json:",omitempty"` + + // Forwarding defines rules for forwarding verified JWTs to the backend. + Forwarding *JWTForwardingConfig `json:",omitempty"` + + // ClockSkewSeconds specifies the maximum allowable time difference + // from clock skew when validating the "exp" (Expiration) and "nbf" + // (Not Before) claims. + // + // Default value is 30 seconds. + ClockSkewSeconds int `json:",omitempty" alias:"clock_skew_seconds"` + + // CacheConfig defines configuration for caching the validation + // result for previously seen JWTs. Caching results can speed up + // verification when individual tokens are expected to be handled + // multiple times. + CacheConfig *JWTCacheConfig `json:",omitempty" alias:"cache_config"` + + Meta map[string]string `json:",omitempty"` + + // CreateIndex is the Raft index this entry was created at. This is a + // read-only field. + CreateIndex uint64 `json:",omitempty"` + + // ModifyIndex is used for the Check-And-Set operations and can also be fed + // back into the WaitIndex of the QueryOptions in order to perform blocking + // queries. + ModifyIndex uint64 `json:",omitempty"` + + // Partition is the partition the JWTProviderConfigEntry applies to. + // Partitioning is a Consul Enterprise feature. + Partition string `json:",omitempty"` + + // Namespace is the namespace the JWTProviderConfigEntry applies to. + // Namespacing is a Consul Enterprise feature. + Namespace string `json:",omitempty"` +} + +// JWTLocation is a location where the JWT could be present in requests. +// +// Only one of Header, QueryParam, or Cookie can be specified. +type JWTLocation struct { + // Header defines how to extract a JWT from an HTTP request header. + Header *JWTLocationHeader `json:",omitempty"` + + // QueryParam defines how to extract a JWT from an HTTP request + // query parameter. + QueryParam *JWTLocationQueryParam `json:",omitempty" alias:"query_param"` + + // Cookie defines how to extract a JWT from an HTTP request cookie. + Cookie *JWTLocationCookie `json:",omitempty"` +} + +// JWTLocationHeader defines how to extract a JWT from an HTTP +// request header. +type JWTLocationHeader struct { + // Name is the name of the header containing the token. + Name string `json:",omitempty"` + + // ValuePrefix is an optional prefix that precedes the token in the + // header value. + // For example, "Bearer " is a standard value prefix for a header named + // "Authorization", but the prefix is not part of the token itself: + // "Authorization: Bearer " + ValuePrefix string `json:",omitempty" alias:"value_prefix"` + + // Forward defines whether the header with the JWT should be + // forwarded after the token has been verified. If false, the + // header will not be forwarded to the backend. + // + // Default value is false. + Forward bool `json:",omitempty"` +} + +// JWTLocationQueryParam defines how to extract a JWT from an HTTP request query parameter. +type JWTLocationQueryParam struct { + // Name is the name of the query param containing the token. + Name string `json:",omitempty"` +} + +// JWTLocationCookie defines how to extract a JWT from an HTTP request cookie. +type JWTLocationCookie struct { + // Name is the name of the cookie containing the token. + Name string `json:",omitempty"` +} + +type JWTForwardingConfig struct { + // HeaderName is a header name to use when forwarding a verified + // JWT to the backend. The verified JWT could have been extracted + // from any location (query param, header, or cookie). + // + // The header value will be base64-URL-encoded, and will not be + // padded unless PadForwardPayloadHeader is true. + HeaderName string `json:",omitempty" alias:"header_name"` + + // PadForwardPayloadHeader determines whether padding should be added + // to the base64 encoded token forwarded with ForwardPayloadHeader. + // + // Default value is false. + PadForwardPayloadHeader bool `json:",omitempty" alias:"pad_forward_payload_header"` +} + +// JSONWebKeySet defines a key set, its location on disk, or the +// means with which to fetch a key set from a remote server. +// +// Exactly one of Local or Remote must be specified. +type JSONWebKeySet struct { + // Local specifies a local source for the key set. + Local *LocalJWKS `json:",omitempty"` + + // Remote specifies how to fetch a key set from a remote server. + Remote *RemoteJWKS `json:",omitempty"` +} + +// LocalJWKS specifies a location for a local JWKS. +// +// Only one of String and Filename can be specified. +type LocalJWKS struct { + // JWKS contains a base64 encoded JWKS. + JWKS string `json:",omitempty"` + + // Filename configures a location on disk where the JWKS can be + // found. If specified, the file must be present on the disk of ALL + // proxies with intentions referencing this provider. + Filename string `json:",omitempty"` +} + +// RemoteJWKS specifies how to fetch a JWKS from a remote server. +type RemoteJWKS struct { + // URI is the URI of the server to query for the JWKS. + URI string `json:",omitempty"` + + // RequestTimeoutMs is the number of milliseconds to + // time out when making a request for the JWKS. + RequestTimeoutMs int `json:",omitempty" alias:"request_timeout_ms"` + + // CacheDuration is the duration after which cached keys + // should be expired. + // + // Default value is 5 minutes. + CacheDuration time.Duration `json:",omitempty" alias:"cache_duration"` + + // FetchAsynchronously indicates that the JWKS should be fetched + // when a client request arrives. Client requests will be paused + // until the JWKS is fetched. + // If false, the proxy listener will wait for the JWKS to be + // fetched before being activated. + // + // Default value is false. + FetchAsynchronously bool `json:",omitempty" alias:"fetch_asynchronously"` + + // RetryPolicy defines a retry policy for fetching JWKS. + // + // There is no retry by default. + RetryPolicy *JWKSRetryPolicy `json:",omitempty" alias:"retry_policy"` + + // JWKSCluster defines how the specified Remote JWKS URI is to be fetched. + JWKSCluster *JWKSCluster `json:",omitempty" alias:"jwks_cluster"` +} + +type JWKSCluster struct { + // DiscoveryType refers to the service discovery type to use for resolving the cluster. + // + // This defaults to STRICT_DNS. + // Other options include STATIC, LOGICAL_DNS, EDS or ORIGINAL_DST. + DiscoveryType ClusterDiscoveryType `json:",omitempty" alias:"discovery_type"` + + // TLSCertificates refers to the data containing certificate authority certificates to use + // in verifying a presented peer certificate. + // If not specified and a peer certificate is presented it will not be verified. + // + // Must be either CaCertificateProviderInstance or TrustedCA. + TLSCertificates *JWKSTLSCertificate `json:",omitempty" alias:"tls_certificates"` + + // The timeout for new network connections to hosts in the cluster. + // If not set, a default value of 5s will be used. + ConnectTimeout time.Duration `json:",omitempty" alias:"connect_timeout"` +} + +type ClusterDiscoveryType string + +// JWKSTLSCertificate refers to the data containing certificate authority certificates to use +// in verifying a presented peer certificate. +// If not specified and a peer certificate is presented it will not be verified. +// +// Must be either CaCertificateProviderInstance or TrustedCA. +type JWKSTLSCertificate struct { + // CaCertificateProviderInstance Certificate provider instance for fetching TLS certificates. + CaCertificateProviderInstance *JWKSTLSCertProviderInstance `json:",omitempty" alias:"ca_certificate_provider_instance"` + + // TrustedCA defines TLS certificate data containing certificate authority certificates + // to use in verifying a presented peer certificate. + // + // Exactly one of Filename, EnvironmentVariable, InlineString or InlineBytes must be specified. + TrustedCA *JWKSTLSCertTrustedCA `json:",omitempty" alias:"trusted_ca"` +} + +// JWKSTLSCertTrustedCA defines TLS certificate data containing certificate authority certificates +// to use in verifying a presented peer certificate. +// +// Exactly one of Filename, EnvironmentVariable, InlineString or InlineBytes must be specified. +type JWKSTLSCertTrustedCA struct { + Filename string `json:",omitempty" alias:"filename"` + EnvironmentVariable string `json:",omitempty" alias:"environment_variable"` + InlineString string `json:",omitempty" alias:"inline_string"` + InlineBytes []byte `json:",omitempty" alias:"inline_bytes"` +} + +type JWKSTLSCertProviderInstance struct { + // InstanceName refers to the certificate provider instance name + // + // The default value is "default". + InstanceName string `json:",omitempty" alias:"instance_name"` + + // CertificateName is used to specify certificate instances or types. For example, "ROOTCA" to specify + // a root-certificate (validation context) or "example.com" to specify a certificate for a + // particular domain. + // + // The default value is the empty string. + CertificateName string `json:",omitempty" alias:"certificate_name"` +} + +type JWKSRetryPolicy struct { + // NumRetries is the number of times to retry fetching the JWKS. + // The retry strategy uses jittered exponential backoff with + // a base interval of 1s and max of 10s. + // + // Default value is 0. + NumRetries int `json:",omitempty" alias:"num_retries"` + + // Backoff policy + // + // Defaults to Envoy's backoff policy + RetryPolicyBackOff *RetryPolicyBackOff `json:",omitempty" alias:"retry_policy_back_off"` +} + +type RetryPolicyBackOff struct { + // BaseInterval to be used for the next back off computation + // + // The default value from envoy is 1s + BaseInterval time.Duration `json:",omitempty" alias:"base_interval"` + + // MaxInternal to be used to specify the maximum interval between retries. + // Optional but should be greater or equal to BaseInterval. + // + // Defaults to 10 times BaseInterval + MaxInterval time.Duration `json:",omitempty" alias:"max_interval"` +} + +type JWTCacheConfig struct { + // Size specifies the maximum number of JWT verification + // results to cache. + // + // Defaults to 0, meaning that JWT caching is disabled. + Size int `json:",omitempty"` +} + +func (e *JWTProviderConfigEntry) GetKind() string { + return JWTProvider +} + +func (e *JWTProviderConfigEntry) GetName() string { return e.Name } +func (e *JWTProviderConfigEntry) GetMeta() map[string]string { return e.Meta } +func (e *JWTProviderConfigEntry) GetCreateIndex() uint64 { return e.CreateIndex } +func (e *JWTProviderConfigEntry) GetModifyIndex() uint64 { return e.ModifyIndex } +func (e *JWTProviderConfigEntry) GetPartition() string { return e.Partition } +func (e *JWTProviderConfigEntry) GetNamespace() string { return e.Namespace } diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_mesh.go b/vendor/github.com/hashicorp/consul/api/config_entry_mesh.go index 98b882247..1a1ebb8b5 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_mesh.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_mesh.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -19,6 +22,10 @@ type MeshConfigEntry struct { // in transparent mode. TransparentProxy TransparentProxyMeshConfig `alias:"transparent_proxy"` + // AllowEnablingPermissiveMutualTLS must be true in order to allow setting + // MutualTLSMode=permissive in either service-defaults or proxy-defaults. + AllowEnablingPermissiveMutualTLS bool `json:",omitempty" alias:"allow_enabling_permissive_mutual_tls"` + TLS *MeshTLSConfig `json:",omitempty"` HTTP *MeshHTTPConfig `json:",omitempty"` diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_rate_limit_ip.go b/vendor/github.com/hashicorp/consul/api/config_entry_rate_limit_ip.go new file mode 100644 index 000000000..7af2a2658 --- /dev/null +++ b/vendor/github.com/hashicorp/consul/api/config_entry_rate_limit_ip.go @@ -0,0 +1,91 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +type ReadWriteRatesConfig struct { + ReadRate float64 `alias:"read_rate"` + WriteRate float64 `alias:"write_rate"` +} + +type RateLimitIPConfigEntry struct { + // Kind of the config entry. This will be set to structs.RateLimitIPConfig + Kind string + Name string + Mode string // {permissive, enforcing, disabled} + + Meta map[string]string `json:",omitempty"` + // overall limits + ReadRate float64 `alias:"read_rate"` + WriteRate float64 `alias:"write_rate"` + + //limits specific to a type of call + ACL *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryACL OperationCategory = "ACL" + Catalog *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryCatalog OperationCategory = "Catalog" + ConfigEntry *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryConfigEntry OperationCategory = "ConfigEntry" + ConnectCA *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryConnectCA OperationCategory = "ConnectCA" + Coordinate *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryCoordinate OperationCategory = "Coordinate" + DiscoveryChain *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryDiscoveryChain OperationCategory = "DiscoveryChain" + ServerDiscovery *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryServerDiscovery OperationCategory = "ServerDiscovery" + Health *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryHealth OperationCategory = "Health" + Intention *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryIntention OperationCategory = "Intention" + KV *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryKV OperationCategory = "KV" + Tenancy *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryPartition OperationCategory = "Tenancy" + PreparedQuery *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryPreparedQuery OperationCategory = "PreparedQuery" + Session *ReadWriteRatesConfig `json:",omitempty"` // OperationCategorySession OperationCategory = "Session" + Txn *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryTxn OperationCategory = "Txn" + AutoConfig *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryAutoConfig OperationCategory = "AutoConfig" + FederationState *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryFederationState OperationCategory = "FederationState" + Internal *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryInternal OperationCategory = "Internal" + PeerStream *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryPeerStream OperationCategory = "PeerStream" + Peering *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryPeering OperationCategory = "Peering" + DataPlane *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryDataPlane OperationCategory = "DataPlane" + DNS *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryDNS OperationCategory = "DNS" + Subscribe *ReadWriteRatesConfig `json:",omitempty"` // OperationCategorySubscribe OperationCategory = "Subscribe" + Resource *ReadWriteRatesConfig `json:",omitempty"` // OperationCategoryResource OperationCategory = "Resource" + + // Partition is the partition the config entry is associated with. + // Partitioning is a Consul Enterprise feature. + Partition string `json:",omitempty"` + + // Namespace is the namespace the config entry is associated with. + // Namespacing is a Consul Enterprise feature. + Namespace string `json:",omitempty"` + + // CreateIndex is the Raft index this entry was created at. This is a + // read-only field. + CreateIndex uint64 + + // ModifyIndex is used for the Check-And-Set operations and can also be fed + // back into the WaitIndex of the QueryOptions in order to perform blocking + // queries. + ModifyIndex uint64 +} + +func (r *RateLimitIPConfigEntry) GetKind() string { + return RateLimitIPConfig +} +func (r *RateLimitIPConfigEntry) GetName() string { + if r == nil { + return "" + } + return r.Name +} +func (r *RateLimitIPConfigEntry) GetPartition() string { + return r.Partition +} +func (r *RateLimitIPConfigEntry) GetNamespace() string { + return r.Namespace +} +func (r *RateLimitIPConfigEntry) GetMeta() map[string]string { + if r == nil { + return nil + } + return r.Meta +} +func (r *RateLimitIPConfigEntry) GetCreateIndex() uint64 { + return r.CreateIndex +} +func (r *RateLimitIPConfigEntry) GetModifyIndex() uint64 { + return r.ModifyIndex +} diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_routes.go b/vendor/github.com/hashicorp/consul/api/config_entry_routes.go index 2edf9b23a..bbaa032d5 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_routes.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_routes.go @@ -1,5 +1,10 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api +import "time" + // TCPRouteConfigEntry -- TODO stub type TCPRouteConfigEntry struct { // Kind of the config entry. This should be set to api.TCPRoute. @@ -192,8 +197,17 @@ type HTTPQueryMatch struct { // HTTPFilters specifies a list of filters used to modify a request // before it is routed to an upstream. type HTTPFilters struct { - Headers []HTTPHeaderFilter - URLRewrite *URLRewrite + Headers []HTTPHeaderFilter + URLRewrite *URLRewrite + RetryFilter *RetryFilter + TimeoutFilter *TimeoutFilter + JWT *JWTFilter +} + +// HTTPResponseFilters specifies a list of filters used to modify a +// response returned by an upstream +type HTTPResponseFilters struct { + Headers []HTTPHeaderFilter } // HTTPHeaderFilter specifies how HTTP headers should be modified. @@ -207,12 +221,32 @@ type URLRewrite struct { Path string } +type RetryFilter struct { + NumRetries uint32 + RetryOn []string + RetryOnStatusCodes []uint32 + RetryOnConnectFailure bool +} + +type TimeoutFilter struct { + RequestTimeout time.Duration + IdleTimeout time.Duration +} + +// JWTFilter specifies the JWT configuration for a route +type JWTFilter struct { + Providers []*APIGatewayJWTProvider `json:",omitempty"` +} + // HTTPRouteRule specifies the routing rules used to determine what upstream // service an HTTP request is routed to. type HTTPRouteRule struct { // Filters is a list of HTTP-based filters used to modify a request prior // to routing it to the upstream service Filters HTTPFilters + // ResponseFilters is a list of HTTP-based filters used to modify a response + // returned by the upstream service + ResponseFilters HTTPResponseFilters // Matches specified the matching criteria used in the routing table. If a // request matches the given HTTPMatch configuration, then traffic is routed // to services specified in the Services field. @@ -228,10 +262,15 @@ type HTTPService struct { // Weight is an arbitrary integer used in calculating how much // traffic should be sent to the given service. Weight int + // Filters is a list of HTTP-based filters used to modify a request prior // to routing it to the upstream service Filters HTTPFilters + // ResponseFilters is a list of HTTP-based filters used to modify the + // response returned from the upstream service + ResponseFilters HTTPResponseFilters + // Partition is the partition the config entry is associated with. // Partitioning is a Consul Enterprise feature. Partition string `json:",omitempty"` diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_sameness_group.go b/vendor/github.com/hashicorp/consul/api/config_entry_sameness_group.go new file mode 100644 index 000000000..1217efe7d --- /dev/null +++ b/vendor/github.com/hashicorp/consul/api/config_entry_sameness_group.go @@ -0,0 +1,29 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +type SamenessGroupConfigEntry struct { + Kind string + Name string + Partition string `json:",omitempty"` + DefaultForFailover bool `json:",omitempty" alias:"default_for_failover"` + IncludeLocal bool `json:",omitempty" alias:"include_local"` + Members []SamenessGroupMember + Meta map[string]string `json:",omitempty"` + CreateIndex uint64 + ModifyIndex uint64 +} + +type SamenessGroupMember struct { + Partition string `json:",omitempty"` + Peer string `json:",omitempty"` +} + +func (s *SamenessGroupConfigEntry) GetKind() string { return s.Kind } +func (s *SamenessGroupConfigEntry) GetName() string { return s.Name } +func (s *SamenessGroupConfigEntry) GetPartition() string { return s.Partition } +func (s *SamenessGroupConfigEntry) GetNamespace() string { return "" } +func (s *SamenessGroupConfigEntry) GetCreateIndex() uint64 { return s.CreateIndex } +func (s *SamenessGroupConfigEntry) GetModifyIndex() uint64 { return s.ModifyIndex } +func (s *SamenessGroupConfigEntry) GetMeta() map[string]string { return s.Meta } diff --git a/vendor/github.com/hashicorp/consul/api/config_entry_status.go b/vendor/github.com/hashicorp/consul/api/config_entry_status.go index 83523643b..997066f24 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry_status.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry_status.go @@ -1,7 +1,13 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( + "fmt" "time" + + "golang.org/x/exp/slices" ) // ResourceReference is a reference to a ConfigEntry @@ -43,7 +49,7 @@ type Condition struct { // Type is a value from a bounded set of types that an object might have Type string // Status is a value from a bounded set of statuses that an object might have - Status string + Status ConditionStatus // Reason is a value from a bounded set of reasons for a given status Reason string // Message is a message that gives more detailed information about @@ -55,3 +61,298 @@ type Condition struct { // LastTransitionTime is the time at which this Condition was created LastTransitionTime *time.Time } + +type ( + ConditionStatus string +) + +const ( + ConditionStatusTrue ConditionStatus = "True" + ConditionStatusFalse ConditionStatus = "False" + ConditionStatusUnknown ConditionStatus = "Unknown" +) + +// GatewayConditionType is a type of condition associated with a +// Gateway. This type should be used with the GatewayStatus.Conditions +// field. +type GatewayConditionType string + +// GatewayConditionReason defines the set of reasons that explain why a +// particular Gateway condition type has been raised. +type GatewayConditionReason string + +// the following are directly from the k8s spec +const ( + // This condition is true when the controller managing the Gateway is + // syntactically and semantically valid enough to produce some configuration + // in the underlying data plane. This does not indicate whether or not the + // configuration has been propagated to the data plane. + // + // Possible reasons for this condition to be True are: + // + // * "Accepted" + // + // Possible reasons for this condition to be False are: + // + // * InvalidCertificates + // + GatewayConditionAccepted GatewayConditionType = "Accepted" + + // This reason is used with the "Accepted" condition when the condition is + // True. + GatewayReasonAccepted GatewayConditionReason = "Accepted" + + // This reason is used with the "Accepted" condition when the gateway has multiple invalid + // certificates and cannot bind to any routes + GatewayReasonInvalidCertificates GatewayConditionReason = "InvalidCertificates" + + // This reason is used with the "Accepted" condition when the gateway has multiple invalid + // JWT providers and cannot bind to any routes + GatewayReasonInvalidJWTProviders GatewayConditionReason = "InvalidJWTProviders" + + // This condition indicates that the gateway was unable to resolve + // conflicting specification requirements for this Listener. If a + // Listener is conflicted, its network port should not be configured + // on any network elements. + // + // Possible reasons for this condition to be true are: + // + // * "RouteConflict" + // + // Possible reasons for this condition to be False are: + // + // * "NoConflict" + // + // Controllers may raise this condition with other reasons, + // but should prefer to use the reasons listed above to improve + // interoperability. + GatewayConditionConflicted GatewayConditionType = "Conflicted" + // This reason is used with the "Conflicted" condition when the condition + // is False. + GatewayReasonNoConflict GatewayConditionReason = "NoConflict" + // This reason is used with the "Conflicted" condition when the route is + // in a conflicted state, such as when a TCPListener attempts to bind to two routes + GatewayReasonRouteConflict GatewayConditionReason = "RouteConflict" + + // This condition indicates whether the controller was able to + // resolve all the object references for the Gateway. When setting this + // condition to False, a ResourceReference to the misconfigured Listener should + // be provided. + // + // Possible reasons for this condition to be true are: + // + // * "ResolvedRefs" + // + // Possible reasons for this condition to be False are: + // + // * "InvalidCertificateRef" + // * "InvalidRouteKinds" + // * "RefNotPermitted" + // + GatewayConditionResolvedRefs GatewayConditionType = "ResolvedRefs" + + // This reason is used with the "ResolvedRefs" condition when the condition + // is true. + GatewayReasonResolvedRefs GatewayConditionReason = "ResolvedRefs" + + // This reason is used with the "ResolvedRefs" condition when a + // Listener has a TLS configuration with at least one TLS CertificateRef + // that is invalid or does not exist. + // A CertificateRef is considered invalid when it refers to a nonexistent + // or unsupported resource or kind, or when the data within that resource + // is malformed. + // This reason must be used only when the reference is allowed, either by + // referencing an object in the same namespace as the Gateway, or when + // a cross-namespace reference has been explicitly allowed by a ReferenceGrant. + // If the reference is not allowed, the reason RefNotPermitted must be used + // instead. + GatewayListenerReasonInvalidCertificateRef GatewayConditionReason = "InvalidCertificateRef" + + // This reason is used with the "ResolvedRefs" condition when a + // Listener has a JWT configuration with at least one JWTProvider + // that is invalid or does not exist. + // A JWTProvider is considered invalid when it refers to a nonexistent + // or unsupported resource or kind, or when the data within that resource + // is malformed. + GatewayListenerReasonInvalidJWTProviderRef GatewayConditionReason = "InvalidJWTProviderRef" +) + +var validGatewayConditionReasonsMapping = map[GatewayConditionType]map[ConditionStatus][]GatewayConditionReason{ + GatewayConditionAccepted: { + ConditionStatusTrue: { + GatewayReasonAccepted, + }, + ConditionStatusFalse: { + GatewayReasonInvalidCertificates, + GatewayReasonInvalidJWTProviders, + }, + ConditionStatusUnknown: {}, + }, + GatewayConditionConflicted: { + ConditionStatusTrue: { + GatewayReasonRouteConflict, + }, + ConditionStatusFalse: { + GatewayReasonNoConflict, + }, + ConditionStatusUnknown: {}, + }, + GatewayConditionResolvedRefs: { + ConditionStatusTrue: { + GatewayReasonResolvedRefs, + }, + ConditionStatusFalse: { + GatewayListenerReasonInvalidCertificateRef, + GatewayListenerReasonInvalidJWTProviderRef, + }, + ConditionStatusUnknown: {}, + }, +} + +func ValidateGatewayConditionReason(name GatewayConditionType, status ConditionStatus, reason GatewayConditionReason) error { + if err := checkConditionStatus(status); err != nil { + return err + } + + reasons, ok := validGatewayConditionReasonsMapping[name] + if !ok { + return fmt.Errorf("unrecognized GatewayConditionType %q", name) + } + + reasonsForStatus, ok := reasons[status] + if !ok { + return fmt.Errorf("unrecognized ConditionStatus %q", status) + } + + if !slices.Contains(reasonsForStatus, reason) { + return fmt.Errorf("gateway condition reason %q not allowed for gateway condition type %q with status %q", reason, name, status) + } + return nil +} + +// RouteConditionType is a type of condition for a route. +type RouteConditionType string + +// RouteConditionReason is a reason for a route condition. +type RouteConditionReason string + +// The following statuses are taken from the K8's Spec +// With the exception of: "RouteReasonInvalidDiscoveryChain" and "NoUpstreamServicesTargeted" +const ( + // This condition indicates whether the route has been accepted or rejected + // by a Gateway, and why. + // + // Possible reasons for this condition to be true are: + // + // * "Accepted" + // + // Possible reasons for this condition to be False are: + // + // * "InvalidDiscoveryChain" + // * "NoUpstreamServicesTargeted" + // + // + // Controllers may raise this condition with other reasons, + // but should prefer to use the reasons listed above to improve + // interoperability. + RouteConditionAccepted RouteConditionType = "Accepted" + + // This reason is used with the "Accepted" condition when the Route has been + // accepted by the Gateway. + RouteReasonAccepted RouteConditionReason = "Accepted" + + // This reason is used with the "Accepted" condition when the route has an + // invalid discovery chain, this includes conditions like the protocol being invalid + // or the discovery chain failing to compile + RouteReasonInvalidDiscoveryChain RouteConditionReason = "InvalidDiscoveryChain" + + // This reason is used with the "Accepted" condition when the route + RouteReasonNoUpstreamServicesTargeted RouteConditionReason = "NoUpstreamServicesTargeted" +) + +// the following statuses are custom to Consul +const ( + // This condition indicates whether the route was able to successfully bind the + // Listener on the gateway + // Possible reasons for this condition to be true are: + // + // * "Bound" + // + // Possible reasons for this condition to be false are: + // + // * "FailedToBind" + // * "GatewayNotFound" + // + RouteConditionBound RouteConditionType = "Bound" + + // This reason is used with the "Bound" condition when the condition + // is true + RouteReasonBound RouteConditionReason = "Bound" + + // This reason is used with the "Bound" condition when the route failed + // to bind to the gateway + RouteReasonFailedToBind RouteConditionReason = "FailedToBind" + + // This reason is used with the "Bound" condition when the route fails + // to find the gateway + RouteReasonGatewayNotFound RouteConditionReason = "GatewayNotFound" + + // This reason is used with the "Accepted" condition when the route references non-existent + // JWTProviders + RouteReasonJWTProvidersNotFound RouteConditionReason = "JWTProvidersNotFound" +) + +var validRouteConditionReasonsMapping = map[RouteConditionType]map[ConditionStatus][]RouteConditionReason{ + RouteConditionAccepted: { + ConditionStatusTrue: { + RouteReasonAccepted, + }, + ConditionStatusFalse: { + RouteReasonInvalidDiscoveryChain, + RouteReasonNoUpstreamServicesTargeted, + }, + ConditionStatusUnknown: {}, + }, + RouteConditionBound: { + ConditionStatusTrue: { + RouteReasonBound, + }, + ConditionStatusFalse: { + RouteReasonGatewayNotFound, + RouteReasonFailedToBind, + RouteReasonJWTProvidersNotFound, + }, + ConditionStatusUnknown: {}, + }, +} + +func ValidateRouteConditionReason(name RouteConditionType, status ConditionStatus, reason RouteConditionReason) error { + if err := checkConditionStatus(status); err != nil { + return err + } + + reasons, ok := validRouteConditionReasonsMapping[name] + if !ok { + return fmt.Errorf("unrecognized RouteConditionType %s", name) + } + + reasonsForStatus, ok := reasons[status] + if !ok { + return fmt.Errorf("unrecognized ConditionStatus %s", name) + } + + if !slices.Contains(reasonsForStatus, reason) { + return fmt.Errorf("route condition reason %s not allowed for route condition type %s with status %s", reason, name, status) + } + + return nil +} + +func checkConditionStatus(status ConditionStatus) error { + switch status { + case ConditionStatusTrue, ConditionStatusFalse, ConditionStatusUnknown: + return nil + default: + return fmt.Errorf("unrecognized condition status: %q", status) + } +} diff --git a/vendor/github.com/hashicorp/consul/api/connect.go b/vendor/github.com/hashicorp/consul/api/connect.go index a40d1e232..77be00034 100644 --- a/vendor/github.com/hashicorp/consul/api/connect.go +++ b/vendor/github.com/hashicorp/consul/api/connect.go @@ -1,5 +1,11 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api +// TelemetryCollectorName is the service name for the Consul Telemetry Collector +const TelemetryCollectorName string = "consul-telemetry-collector" + // Connect can be used to work with endpoints related to Connect, the // feature for securely connecting services within Consul. type Connect struct { diff --git a/vendor/github.com/hashicorp/consul/api/connect_ca.go b/vendor/github.com/hashicorp/consul/api/connect_ca.go index 69c652dac..8a5c9f870 100644 --- a/vendor/github.com/hashicorp/consul/api/connect_ca.go +++ b/vendor/github.com/hashicorp/consul/api/connect_ca.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/connect_intention.go b/vendor/github.com/hashicorp/consul/api/connect_intention.go index 0c2500fd0..e91c03e8b 100644 --- a/vendor/github.com/hashicorp/consul/api/connect_intention.go +++ b/vendor/github.com/hashicorp/consul/api/connect_intention.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -40,6 +43,10 @@ type Intention struct { // same level of tenancy (partition is local to cluster, peer is remote). SourcePeer string `json:",omitempty"` + // SourceSamenessGroup cannot be wildcards "*" and + // is not compatible with legacy intentions. + SourceSamenessGroup string `json:",omitempty"` + // SourceType is the type of the value for the source. SourceType IntentionSourceType diff --git a/vendor/github.com/hashicorp/consul/api/coordinate.go b/vendor/github.com/hashicorp/consul/api/coordinate.go index 7ef6ce274..b0269adae 100644 --- a/vendor/github.com/hashicorp/consul/api/coordinate.go +++ b/vendor/github.com/hashicorp/consul/api/coordinate.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/debug.go b/vendor/github.com/hashicorp/consul/api/debug.go index b7e80b88d..e6b5dc52d 100644 --- a/vendor/github.com/hashicorp/consul/api/debug.go +++ b/vendor/github.com/hashicorp/consul/api/debug.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/discovery_chain.go b/vendor/github.com/hashicorp/consul/api/discovery_chain.go index 4217603cf..4b6260cf3 100644 --- a/vendor/github.com/hashicorp/consul/api/discovery_chain.go +++ b/vendor/github.com/hashicorp/consul/api/discovery_chain.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -221,6 +224,7 @@ func (r *DiscoveryResolver) UnmarshalJSON(data []byte) error { // compiled form of ServiceResolverFailover type DiscoveryFailover struct { Targets []string + Policy ServiceResolverFailoverPolicy `json:",omitempty"` } // DiscoveryTarget represents all of the inputs necessary to use a resolver diff --git a/vendor/github.com/hashicorp/consul/api/event.go b/vendor/github.com/hashicorp/consul/api/event.go index ceded6598..efba89d3b 100644 --- a/vendor/github.com/hashicorp/consul/api/event.go +++ b/vendor/github.com/hashicorp/consul/api/event.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/health.go b/vendor/github.com/hashicorp/consul/api/health.go index a89b4b727..a02300204 100644 --- a/vendor/github.com/hashicorp/consul/api/health.go +++ b/vendor/github.com/hashicorp/consul/api/health.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -64,6 +67,7 @@ type HealthCheckDefinition struct { TLSServerName string TLSSkipVerify bool TCP string + TCPUseTLS bool UDP string GRPC string OSService string diff --git a/vendor/github.com/hashicorp/consul/api/internal.go b/vendor/github.com/hashicorp/consul/api/internal.go new file mode 100644 index 000000000..b5f400f4b --- /dev/null +++ b/vendor/github.com/hashicorp/consul/api/internal.go @@ -0,0 +1,67 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +import "context" + +// Internal can be used to query endpoints that are intended for +// Hashicorp internal-use only. +type Internal struct { + c *Client +} + +// Internal returns a handle to endpoints that are for internal +// Hashicorp usage only. There is not guarantee that these will +// be backwards-compatible or supported, so usage of these is +// not encouraged. +func (c *Client) Internal() *Internal { + return &Internal{c} +} + +type AssignServiceManualVIPsRequest struct { + Service string + ManualVIPs []string +} + +type AssignServiceManualVIPsResponse struct { + ServiceFound bool `json:"Found"` + UnassignedFrom []PeeredServiceName +} + +type PeeredServiceName struct { + ServiceName CompoundServiceName + Peer string +} + +func (i *Internal) AssignServiceVirtualIP( + ctx context.Context, + service string, + manualVIPs []string, + wo *WriteOptions, +) (*AssignServiceManualVIPsResponse, *QueryMeta, error) { + req := i.c.newRequest("PUT", "/v1/internal/service-virtual-ip") + req.setWriteOptions(wo) + req.ctx = ctx + req.obj = AssignServiceManualVIPsRequest{ + Service: service, + ManualVIPs: manualVIPs, + } + rtt, resp, err := i.c.doRequest(req) + if err != nil { + return nil, nil, err + } + defer closeResponseBody(resp) + if err := requireOK(resp); err != nil { + return nil, nil, err + } + + qm := &QueryMeta{RequestTime: rtt} + parseQueryMeta(resp, qm) + + var out AssignServiceManualVIPsResponse + if err := decodeBody(resp, &out); err != nil { + return nil, nil, err + } + return &out, qm, nil +} diff --git a/vendor/github.com/hashicorp/consul/api/kv.go b/vendor/github.com/hashicorp/consul/api/kv.go index 85a9d7750..b9d330a6f 100644 --- a/vendor/github.com/hashicorp/consul/api/kv.go +++ b/vendor/github.com/hashicorp/consul/api/kv.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/lock.go b/vendor/github.com/hashicorp/consul/api/lock.go index 221a7add3..e9529f7bd 100644 --- a/vendor/github.com/hashicorp/consul/api/lock.go +++ b/vendor/github.com/hashicorp/consul/api/lock.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/namespace.go b/vendor/github.com/hashicorp/consul/api/namespace.go index 65cc6f3f3..98afd2299 100644 --- a/vendor/github.com/hashicorp/consul/api/namespace.go +++ b/vendor/github.com/hashicorp/consul/api/namespace.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/operator.go b/vendor/github.com/hashicorp/consul/api/operator.go index 079e22486..667dcd872 100644 --- a/vendor/github.com/hashicorp/consul/api/operator.go +++ b/vendor/github.com/hashicorp/consul/api/operator.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // Operator can be used to perform low-level operator tasks for Consul. diff --git a/vendor/github.com/hashicorp/consul/api/operator_area.go b/vendor/github.com/hashicorp/consul/api/operator_area.go index f9fa1339e..9228d89b4 100644 --- a/vendor/github.com/hashicorp/consul/api/operator_area.go +++ b/vendor/github.com/hashicorp/consul/api/operator_area.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // The /v1/operator/area endpoints are available only in Consul Enterprise and diff --git a/vendor/github.com/hashicorp/consul/api/operator_audit.go b/vendor/github.com/hashicorp/consul/api/operator_audit.go new file mode 100644 index 000000000..5240d38a7 --- /dev/null +++ b/vendor/github.com/hashicorp/consul/api/operator_audit.go @@ -0,0 +1,40 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// The /v1/operator/audit-hash endpoint is available only in Consul Enterprise and +// interact with its audit logging subsystem. + +package api + +type AuditHashRequest struct { + Input string +} + +type AuditHashResponse struct { + Hash string +} + +func (op *Operator) AuditHash(a *AuditHashRequest, q *QueryOptions) (*AuditHashResponse, error) { + r := op.c.newRequest("POST", "/v1/operator/audit-hash") + r.setQueryOptions(q) + r.obj = a + + rtt, resp, err := op.c.doRequest(r) + if err != nil { + return nil, err + } + defer closeResponseBody(resp) + if err := requireOK(resp); err != nil { + return nil, err + } + + wm := &WriteMeta{} + wm.RequestTime = rtt + + var out AuditHashResponse + if err := decodeBody(resp, &out); err != nil { + return nil, err + } + + return &out, nil +} diff --git a/vendor/github.com/hashicorp/consul/api/operator_autopilot.go b/vendor/github.com/hashicorp/consul/api/operator_autopilot.go index 6ab576970..7628bf6f2 100644 --- a/vendor/github.com/hashicorp/consul/api/operator_autopilot.go +++ b/vendor/github.com/hashicorp/consul/api/operator_autopilot.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/operator_keyring.go b/vendor/github.com/hashicorp/consul/api/operator_keyring.go index 6db31a252..aefec9e27 100644 --- a/vendor/github.com/hashicorp/consul/api/operator_keyring.go +++ b/vendor/github.com/hashicorp/consul/api/operator_keyring.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // keyringRequest is used for performing Keyring operations diff --git a/vendor/github.com/hashicorp/consul/api/operator_license.go b/vendor/github.com/hashicorp/consul/api/operator_license.go index 74eed3baa..1e3496da0 100644 --- a/vendor/github.com/hashicorp/consul/api/operator_license.go +++ b/vendor/github.com/hashicorp/consul/api/operator_license.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/operator_raft.go b/vendor/github.com/hashicorp/consul/api/operator_raft.go index 1da20e899..f0f5794aa 100644 --- a/vendor/github.com/hashicorp/consul/api/operator_raft.go +++ b/vendor/github.com/hashicorp/consul/api/operator_raft.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // RaftServer has information about a server in the Raft configuration. @@ -25,6 +28,9 @@ type RaftServer struct { // it's a non-voting server, which will be added in a future release of // Consul. Voter bool + + // LastIndex is the last log index this server has a record of in its Raft log. + LastIndex uint64 } // RaftConfiguration is returned when querying for the current Raft configuration. @@ -62,9 +68,14 @@ func (op *Operator) RaftGetConfiguration(q *QueryOptions) (*RaftConfiguration, e } // RaftLeaderTransfer is used to transfer the current raft leader to another node -func (op *Operator) RaftLeaderTransfer(q *QueryOptions) (*TransferLeaderResponse, error) { +// Optionally accepts a non-empty id of another node to transfer leadership to. +func (op *Operator) RaftLeaderTransfer(id string, q *QueryOptions) (*TransferLeaderResponse, error) { r := op.c.newRequest("POST", "/v1/operator/raft/transfer-leader") r.setQueryOptions(q) + + if id != "" { + r.params.Set("id", id) + } _, resp, err := op.c.doRequest(r) if err != nil { return nil, err diff --git a/vendor/github.com/hashicorp/consul/api/operator_segment.go b/vendor/github.com/hashicorp/consul/api/operator_segment.go index 92b05d3c0..6115a7ab4 100644 --- a/vendor/github.com/hashicorp/consul/api/operator_segment.go +++ b/vendor/github.com/hashicorp/consul/api/operator_segment.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // SegmentList returns all the available LAN segments. diff --git a/vendor/github.com/hashicorp/consul/api/operator_usage.go b/vendor/github.com/hashicorp/consul/api/operator_usage.go index d07e774d8..8977449dd 100644 --- a/vendor/github.com/hashicorp/consul/api/operator_usage.go +++ b/vendor/github.com/hashicorp/consul/api/operator_usage.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api type Usage struct { @@ -7,6 +10,7 @@ type Usage struct { // ServiceUsage contains information about the number of services and service instances for a datacenter. type ServiceUsage struct { + Nodes int Services int ServiceInstances int ConnectServiceInstances map[string]int diff --git a/vendor/github.com/hashicorp/consul/api/partition.go b/vendor/github.com/hashicorp/consul/api/partition.go index 88edfb7b0..8467c3118 100644 --- a/vendor/github.com/hashicorp/consul/api/partition.go +++ b/vendor/github.com/hashicorp/consul/api/partition.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/peering.go b/vendor/github.com/hashicorp/consul/api/peering.go index 34602c878..dd7780f63 100644 --- a/vendor/github.com/hashicorp/consul/api/peering.go +++ b/vendor/github.com/hashicorp/consul/api/peering.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( @@ -44,6 +47,16 @@ type PeeringRemoteInfo struct { Partition string // Datacenter is the remote peer's datacenter. Datacenter string + Locality *Locality `json:",omitempty"` +} + +// Locality identifies where a given entity is running. +type Locality struct { + // Region is region the zone belongs to. + Region string + + // Zone is the zone the entity is running in. + Zone string } type Peering struct { diff --git a/vendor/github.com/hashicorp/consul/api/prepared_query.go b/vendor/github.com/hashicorp/consul/api/prepared_query.go index f47a58373..8ebc852f3 100644 --- a/vendor/github.com/hashicorp/consul/api/prepared_query.go +++ b/vendor/github.com/hashicorp/consul/api/prepared_query.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // QueryFailoverOptions sets options about how we fail over if there are no @@ -26,6 +29,14 @@ type QueryFailoverTarget struct { // Datacenter specifies a datacenter to try during failover. Datacenter string + + // Partition specifies a partition to try during failover + // Note: Partition are available only in Consul Enterprise + Partition string `json:",omitempty"` + + // Namespace specifies a namespace to try during failover + // Note: Namespaces are available only in Consul Enterprise + Namespace string `json:",omitempty"` } // QueryDNSOptions controls settings when query results are served over DNS. @@ -40,9 +51,17 @@ type ServiceQuery struct { // Service is the service to query. Service string + // SamenessGroup specifies a sameness group to query. The first member of the Sameness Group will + // be targeted first on PQ execution and subsequent members will be targeted during failover scenarios. + // This field is mutually exclusive with Failover. + SamenessGroup string `json:",omitempty"` + // Namespace of the service to query Namespace string `json:",omitempty"` + // Partition of the service to query + Partition string `json:",omitempty"` + // Near allows baking in the name of a node to automatically distance- // sort from. The magic "_agent" value is supported, which sorts near // the agent which initiated the request by default. @@ -50,7 +69,7 @@ type ServiceQuery struct { // Failover controls what we do if there are no healthy nodes in the // local datacenter. - Failover QueryFailoverOptions + Failover QueryFailoverOptions `json:",omitempty"` // IgnoreCheckIDs is an optional list of health check IDs to ignore when // considering which nodes are healthy. It is useful as an emergency measure diff --git a/vendor/github.com/hashicorp/consul/api/raw.go b/vendor/github.com/hashicorp/consul/api/raw.go index 745a208c9..639513d29 100644 --- a/vendor/github.com/hashicorp/consul/api/raw.go +++ b/vendor/github.com/hashicorp/consul/api/raw.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // Raw can be used to do raw queries against custom endpoints diff --git a/vendor/github.com/hashicorp/consul/api/semaphore.go b/vendor/github.com/hashicorp/consul/api/semaphore.go index 066ce33a9..9d98ff5c2 100644 --- a/vendor/github.com/hashicorp/consul/api/semaphore.go +++ b/vendor/github.com/hashicorp/consul/api/semaphore.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/session.go b/vendor/github.com/hashicorp/consul/api/session.go index 3f61acfbb..69fd77d27 100644 --- a/vendor/github.com/hashicorp/consul/api/session.go +++ b/vendor/github.com/hashicorp/consul/api/session.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/snapshot.go b/vendor/github.com/hashicorp/consul/api/snapshot.go index b526b79c3..bcc80e5b3 100644 --- a/vendor/github.com/hashicorp/consul/api/snapshot.go +++ b/vendor/github.com/hashicorp/consul/api/snapshot.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/consul/api/status.go b/vendor/github.com/hashicorp/consul/api/status.go index 86f943bc7..8c52eb222 100644 --- a/vendor/github.com/hashicorp/consul/api/status.go +++ b/vendor/github.com/hashicorp/consul/api/status.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api // Status can be used to query the Status endpoints diff --git a/vendor/github.com/hashicorp/consul/api/txn.go b/vendor/github.com/hashicorp/consul/api/txn.go index 4aa06d9f5..59adafdac 100644 --- a/vendor/github.com/hashicorp/consul/api/txn.go +++ b/vendor/github.com/hashicorp/consul/api/txn.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package api import ( diff --git a/vendor/github.com/hashicorp/cronexpr/LICENSE b/vendor/github.com/hashicorp/cronexpr/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/vendor/github.com/hashicorp/cronexpr/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/github.com/hashicorp/go-hclog/LICENSE b/vendor/github.com/hashicorp/go-hclog/LICENSE index abaf1e45f..9938fb50e 100644 --- a/vendor/github.com/hashicorp/go-hclog/LICENSE +++ b/vendor/github.com/hashicorp/go-hclog/LICENSE @@ -1,6 +1,4 @@ -MIT License - -Copyright (c) 2017 HashiCorp +Copyright (c) 2017 HashiCorp, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/hashicorp/go-hclog/colorize_unix.go b/vendor/github.com/hashicorp/go-hclog/colorize_unix.go index 99cc176a4..d00816b38 100644 --- a/vendor/github.com/hashicorp/go-hclog/colorize_unix.go +++ b/vendor/github.com/hashicorp/go-hclog/colorize_unix.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + //go:build !windows // +build !windows @@ -7,23 +10,35 @@ import ( "github.com/mattn/go-isatty" ) +// hasFD is used to check if the writer has an Fd value to check +// if it's a terminal. +type hasFD interface { + Fd() uintptr +} + // setColorization will mutate the values of this logger // to appropriately configure colorization options. It provides // a wrapper to the output stream on Windows systems. func (l *intLogger) setColorization(opts *LoggerOptions) { - switch opts.Color { - case ColorOff: - fallthrough - case ForceColor: + if opts.Color != AutoColor { return - case AutoColor: - fi := l.checkWriterIsFile() - isUnixTerm := isatty.IsTerminal(fi.Fd()) - isCygwinTerm := isatty.IsCygwinTerminal(fi.Fd()) - isTerm := isUnixTerm || isCygwinTerm - if !isTerm { + } + + if sc, ok := l.writer.w.(SupportsColor); ok { + if !sc.SupportsColor() { l.headerColor = ColorOff l.writer.color = ColorOff } + return + } + + fi, ok := l.writer.w.(hasFD) + if !ok { + return + } + + if !isatty.IsTerminal(fi.Fd()) { + l.headerColor = ColorOff + l.writer.color = ColorOff } } diff --git a/vendor/github.com/hashicorp/go-hclog/colorize_windows.go b/vendor/github.com/hashicorp/go-hclog/colorize_windows.go index 26f8cef8d..2c3fb9ea6 100644 --- a/vendor/github.com/hashicorp/go-hclog/colorize_windows.go +++ b/vendor/github.com/hashicorp/go-hclog/colorize_windows.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + //go:build windows // +build windows @@ -7,32 +10,32 @@ import ( "os" colorable "github.com/mattn/go-colorable" - "github.com/mattn/go-isatty" ) // setColorization will mutate the values of this logger // to appropriately configure colorization options. It provides // a wrapper to the output stream on Windows systems. func (l *intLogger) setColorization(opts *LoggerOptions) { - switch opts.Color { - case ColorOff: + if opts.Color == ColorOff { + return + } + + fi, ok := l.writer.w.(*os.File) + if !ok { + l.writer.color = ColorOff + l.headerColor = ColorOff return - case ForceColor: - fi := l.checkWriterIsFile() - l.writer.w = colorable.NewColorable(fi) - case AutoColor: - fi := l.checkWriterIsFile() - isUnixTerm := isatty.IsTerminal(os.Stdout.Fd()) - isCygwinTerm := isatty.IsCygwinTerminal(os.Stdout.Fd()) - isTerm := isUnixTerm || isCygwinTerm - if !isTerm { - l.writer.color = ColorOff - l.headerColor = ColorOff - return - } - - if l.headerColor == ColorOff { - l.writer.w = colorable.NewColorable(fi) - } + } + + cfi := colorable.NewColorable(fi) + + // NewColorable detects if color is possible and if it's not, then it + // returns the original value. So we can test if we got the original + // value back to know if color is possible. + if cfi == fi { + l.writer.color = ColorOff + l.headerColor = ColorOff + } else { + l.writer.w = cfi } } diff --git a/vendor/github.com/hashicorp/go-hclog/context.go b/vendor/github.com/hashicorp/go-hclog/context.go index 7815f5019..eb5aba556 100644 --- a/vendor/github.com/hashicorp/go-hclog/context.go +++ b/vendor/github.com/hashicorp/go-hclog/context.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( diff --git a/vendor/github.com/hashicorp/go-hclog/exclude.go b/vendor/github.com/hashicorp/go-hclog/exclude.go index cfd4307a8..4b73ba553 100644 --- a/vendor/github.com/hashicorp/go-hclog/exclude.go +++ b/vendor/github.com/hashicorp/go-hclog/exclude.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( diff --git a/vendor/github.com/hashicorp/go-hclog/global.go b/vendor/github.com/hashicorp/go-hclog/global.go index 48ff1f3a4..a7403f593 100644 --- a/vendor/github.com/hashicorp/go-hclog/global.go +++ b/vendor/github.com/hashicorp/go-hclog/global.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( diff --git a/vendor/github.com/hashicorp/go-hclog/interceptlogger.go b/vendor/github.com/hashicorp/go-hclog/interceptlogger.go index ff42f1bfc..e9b1c1885 100644 --- a/vendor/github.com/hashicorp/go-hclog/interceptlogger.go +++ b/vendor/github.com/hashicorp/go-hclog/interceptlogger.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( diff --git a/vendor/github.com/hashicorp/go-hclog/intlogger.go b/vendor/github.com/hashicorp/go-hclog/intlogger.go index 89d26c9b0..b45064acf 100644 --- a/vendor/github.com/hashicorp/go-hclog/intlogger.go +++ b/vendor/github.com/hashicorp/go-hclog/intlogger.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( @@ -8,7 +11,6 @@ import ( "fmt" "io" "log" - "os" "reflect" "runtime" "sort" @@ -86,6 +88,8 @@ type intLogger struct { // create subloggers with their own level setting independentLevels bool + + subloggerHook func(sub Logger) Logger } // New returns a configured logger. @@ -152,6 +156,7 @@ func newLogger(opts *LoggerOptions) *intLogger { independentLevels: opts.IndependentLevels, headerColor: headerColor, fieldColor: fieldColor, + subloggerHook: opts.SubloggerHook, } if opts.IncludeLocation { l.callerOffset = offsetIntLogger + opts.AdditionalLocationOffset @@ -167,6 +172,10 @@ func newLogger(opts *LoggerOptions) *intLogger { l.timeFormat = opts.TimeFormat } + if l.subloggerHook == nil { + l.subloggerHook = identityHook + } + l.setColorization(opts) atomic.StoreInt32(l.level, int32(level)) @@ -174,6 +183,10 @@ func newLogger(opts *LoggerOptions) *intLogger { return l } +func identityHook(logger Logger) Logger { + return logger +} + // offsetIntLogger is the stack frame offset in the call stack for the caller to // one of the Warn, Info, Log, etc methods. const offsetIntLogger = 3 @@ -775,7 +788,7 @@ func (l *intLogger) With(args ...interface{}) Logger { sl.implied = append(sl.implied, MissingKey, extra) } - return sl + return l.subloggerHook(sl) } // Create a new sub-Logger that a name decending from the current name. @@ -789,7 +802,7 @@ func (l *intLogger) Named(name string) Logger { sl.name = name } - return sl + return l.subloggerHook(sl) } // Create a new sub-Logger with an explicit name. This ignores the current @@ -800,7 +813,7 @@ func (l *intLogger) ResetNamed(name string) Logger { sl.name = name - return sl + return l.subloggerHook(sl) } func (l *intLogger) ResetOutput(opts *LoggerOptions) error { @@ -876,16 +889,6 @@ func (l *intLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer { } } -// checks if the underlying io.Writer is a file, and -// panics if not. For use by colorization. -func (l *intLogger) checkWriterIsFile() *os.File { - fi, ok := l.writer.w.(*os.File) - if !ok { - panic("Cannot enable coloring of non-file Writers") - } - return fi -} - // Accept implements the SinkAdapter interface func (i *intLogger) Accept(name string, level Level, msg string, args ...interface{}) { i.log(name, level, msg, args...) diff --git a/vendor/github.com/hashicorp/go-hclog/logger.go b/vendor/github.com/hashicorp/go-hclog/logger.go index 3cdb2837d..947ac0c9a 100644 --- a/vendor/github.com/hashicorp/go-hclog/logger.go +++ b/vendor/github.com/hashicorp/go-hclog/logger.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( @@ -89,6 +92,13 @@ const ( ForceColor ) +// SupportsColor is an optional interface that can be implemented by the output +// value. If implemented and SupportsColor() returns true, then AutoColor will +// enable colorization. +type SupportsColor interface { + SupportsColor() bool +} + // LevelFromString returns a Level type for the named log level, or "NoLevel" if // the level string is invalid. This facilitates setting the log level via // config or environment variable by name in a predictable way. @@ -292,6 +302,13 @@ type LoggerOptions struct { // logger will not affect any subloggers, and SetLevel on any subloggers // will not affect the parent or sibling loggers. IndependentLevels bool + + // SubloggerHook registers a function that is called when a sublogger via + // Named, With, or ResetNamed is created. If defined, the function is passed + // the newly created Logger and the returned Logger is returned from the + // original function. This option allows customization via interception and + // wrapping of Logger instances. + SubloggerHook func(sub Logger) Logger } // InterceptLogger describes the interface for using a logger diff --git a/vendor/github.com/hashicorp/go-hclog/nulllogger.go b/vendor/github.com/hashicorp/go-hclog/nulllogger.go index 55e89dd31..d43da809e 100644 --- a/vendor/github.com/hashicorp/go-hclog/nulllogger.go +++ b/vendor/github.com/hashicorp/go-hclog/nulllogger.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( diff --git a/vendor/github.com/hashicorp/go-hclog/stdlog.go b/vendor/github.com/hashicorp/go-hclog/stdlog.go index 641f20ccb..03739b61f 100644 --- a/vendor/github.com/hashicorp/go-hclog/stdlog.go +++ b/vendor/github.com/hashicorp/go-hclog/stdlog.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( diff --git a/vendor/github.com/hashicorp/go-hclog/writer.go b/vendor/github.com/hashicorp/go-hclog/writer.go index 421a1f06c..4ee219bf0 100644 --- a/vendor/github.com/hashicorp/go-hclog/writer.go +++ b/vendor/github.com/hashicorp/go-hclog/writer.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MIT + package hclog import ( diff --git a/vendor/github.com/hashicorp/go-retryablehttp/CHANGELOG.md b/vendor/github.com/hashicorp/go-retryablehttp/CHANGELOG.md new file mode 100644 index 000000000..33686e4da --- /dev/null +++ b/vendor/github.com/hashicorp/go-retryablehttp/CHANGELOG.md @@ -0,0 +1,9 @@ +## 0.7.4 (Jun 6, 2023) + +BUG FIXES + +- client: fixing an issue where the Content-Type header wouldn't be sent with an empty payload when using HTTP/2 [GH-194] + +## 0.7.3 (May 15, 2023) + +Initial release diff --git a/vendor/github.com/hashicorp/go-retryablehttp/CODEOWNERS b/vendor/github.com/hashicorp/go-retryablehttp/CODEOWNERS new file mode 100644 index 000000000..f8389c995 --- /dev/null +++ b/vendor/github.com/hashicorp/go-retryablehttp/CODEOWNERS @@ -0,0 +1 @@ +* @hashicorp/release-engineering \ No newline at end of file diff --git a/vendor/github.com/hashicorp/go-retryablehttp/LICENSE b/vendor/github.com/hashicorp/go-retryablehttp/LICENSE index e87a115e4..f4f97ee58 100644 --- a/vendor/github.com/hashicorp/go-retryablehttp/LICENSE +++ b/vendor/github.com/hashicorp/go-retryablehttp/LICENSE @@ -1,3 +1,5 @@ +Copyright (c) 2015 HashiCorp, Inc. + Mozilla Public License, version 2.0 1. Definitions diff --git a/vendor/github.com/hashicorp/go-retryablehttp/client.go b/vendor/github.com/hashicorp/go-retryablehttp/client.go index f40d2411c..cad96bd97 100644 --- a/vendor/github.com/hashicorp/go-retryablehttp/client.go +++ b/vendor/github.com/hashicorp/go-retryablehttp/client.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + // Package retryablehttp provides a familiar HTTP client interface with // automatic retries and exponential backoff. It is a thin wrapper over the // standard net/http client library and exposes nearly the same public API. @@ -257,10 +260,17 @@ func getBodyReaderAndContentLength(rawBody interface{}) (ReaderFunc, int64, erro if err != nil { return nil, 0, err } - bodyReader = func() (io.Reader, error) { - return bytes.NewReader(buf), nil + if len(buf) == 0 { + bodyReader = func() (io.Reader, error) { + return http.NoBody, nil + } + contentLength = 0 + } else { + bodyReader = func() (io.Reader, error) { + return bytes.NewReader(buf), nil + } + contentLength = int64(len(buf)) } - contentLength = int64(len(buf)) // No body provided, nothing to do case nil: diff --git a/vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go b/vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go index 8f3ee3584..8c407adb3 100644 --- a/vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go +++ b/vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package retryablehttp import ( diff --git a/vendor/github.com/hashicorp/go-version/CHANGELOG.md b/vendor/github.com/hashicorp/go-version/CHANGELOG.md new file mode 100644 index 000000000..5f16dd140 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/CHANGELOG.md @@ -0,0 +1,45 @@ +# 1.6.0 (June 28, 2022) + +FEATURES: + +- Add `Prerelease` function to `Constraint` to return true if the version includes a prerelease field ([#100](https://github.com/hashicorp/go-version/pull/100)) + +# 1.5.0 (May 18, 2022) + +FEATURES: + +- Use `encoding` `TextMarshaler` & `TextUnmarshaler` instead of JSON equivalents ([#95](https://github.com/hashicorp/go-version/pull/95)) +- Add JSON handlers to allow parsing from/to JSON ([#93](https://github.com/hashicorp/go-version/pull/93)) + +# 1.4.0 (January 5, 2022) + +FEATURES: + + - Introduce `MustConstraints()` ([#87](https://github.com/hashicorp/go-version/pull/87)) + - `Constraints`: Introduce `Equals()` and `sort.Interface` methods ([#88](https://github.com/hashicorp/go-version/pull/88)) + +# 1.3.0 (March 31, 2021) + +Please note that CHANGELOG.md does not exist in the source code prior to this release. + +FEATURES: + - Add `Core` function to return a version without prerelease or metadata ([#85](https://github.com/hashicorp/go-version/pull/85)) + +# 1.2.1 (June 17, 2020) + +BUG FIXES: + - Prevent `Version.Equal` method from panicking on `nil` encounter ([#73](https://github.com/hashicorp/go-version/pull/73)) + +# 1.2.0 (April 23, 2019) + +FEATURES: + - Add `GreaterThanOrEqual` and `LessThanOrEqual` helper methods ([#53](https://github.com/hashicorp/go-version/pull/53)) + +# 1.1.0 (Jan 07, 2019) + +FEATURES: + - Add `NewSemver` constructor ([#45](https://github.com/hashicorp/go-version/pull/45)) + +# 1.0.0 (August 24, 2018) + +Initial release. diff --git a/vendor/github.com/hashicorp/go-version/LICENSE b/vendor/github.com/hashicorp/go-version/LICENSE new file mode 100644 index 000000000..c33dcc7c9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/LICENSE @@ -0,0 +1,354 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. “Contributor†+ + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. “Contributor Version†+ + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution†+ + means Covered Software of a particular Contributor. + +1.4. “Covered Software†+ + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. “Incompatible With Secondary Licenses†+ means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of version + 1.1 or earlier of the License, but not also under the terms of a + Secondary License. + +1.6. “Executable Form†+ + means any form of the work other than Source Code Form. + +1.7. “Larger Work†+ + means a work that combines Covered Software with other material, in a separate + file or files, that is not Covered Software. + +1.8. “License†+ + means this document. + +1.9. “Licensable†+ + means having the right to grant, to the maximum extent possible, whether at the + time of the initial grant or subsequently, any and all of the rights conveyed by + this License. + +1.10. “Modifications†+ + means any of the following: + + a. any file in Source Code Form that results from an addition to, deletion + from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims†of a Contributor + + means any patent claim(s), including without limitation, method, process, + and apparatus claims, in any patent Licensable by such Contributor that + would be infringed, but for the grant of the License, by the making, + using, selling, offering for sale, having made, import, or transfer of + either its Contributions or its Contributor Version. + +1.12. “Secondary License†+ + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form†+ + means the form of the work preferred for making modifications. + +1.14. “You†(or “Yourâ€) + + means an individual or a legal entity exercising rights under this + License. For legal entities, “You†includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, “control†means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or as + part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its Contributions + or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become + effective for each Contribution on the date the Contributor first distributes + such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this + License. No additional rights or licenses will be implied from the distribution + or licensing of Covered Software under this License. Notwithstanding Section + 2.1(b) above, no patent license is granted by a Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party’s + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of its + Contributions. + + This License does not grant any rights in the trademarks, service marks, or + logos of any Contributor (except as may be necessary to comply with the + notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this License + (see Section 10.2) or under the terms of a Secondary License (if permitted + under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions + are its original creation(s) or it has sufficient rights to grant the + rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under applicable + copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under the + terms of this License. You must inform recipients that the Source Code Form + of the Covered Software is governed by the terms of this License, and how + they can obtain a copy of this License. You may not attempt to alter or + restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this License, + or sublicense it under different terms, provided that the license for + the Executable Form does not attempt to limit or alter the recipients’ + rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for the + Covered Software. If the Larger Work is a combination of Covered Software + with a work governed by one or more Secondary Licenses, and the Covered + Software is not Incompatible With Secondary Licenses, this License permits + You to additionally distribute such Covered Software under the terms of + such Secondary License(s), so that the recipient of the Larger Work may, at + their option, further distribute the Covered Software under the terms of + either this License or such Secondary License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices (including + copyright notices, patent notices, disclaimers of warranty, or limitations + of liability) contained within the Source Code Form of the Covered + Software, except that You may alter any license notices to the extent + required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on behalf + of any Contributor. You must make it absolutely clear that any such + warranty, support, indemnity, or liability obligation is offered by You + alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, judicial + order, or regulation then You must: (a) comply with the terms of this License + to the maximum extent possible; and (b) describe the limitations and the code + they affect. Such description must be placed in a text file included with all + distributions of the Covered Software under this License. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing basis, + if such Contributor fails to notify You of the non-compliance by some + reasonable means prior to 60 days after You have come back into compliance. + Moreover, Your grants from a particular Contributor are reinstated on an + ongoing basis if such Contributor notifies You of the non-compliance by + some reasonable means, this is the first time You have received notice of + non-compliance with this License from such Contributor, and You become + compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, counter-claims, + and cross-claims) alleging that a Contributor Version directly or + indirectly infringes any patent, then the rights granted to You by any and + all Contributors for the Covered Software under Section 2.1 of this License + shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an “as is†basis, without + warranty of any kind, either expressed, implied, or statutory, including, + without limitation, warranties that the Covered Software is free of defects, + merchantable, fit for a particular purpose or non-infringing. The entire + risk as to the quality and performance of the Covered Software is with You. + Should any Covered Software prove defective in any respect, You (not any + Contributor) assume the cost of any necessary servicing, repair, or + correction. This disclaimer of warranty constitutes an essential part of this + License. No use of any Covered Software is authorized under this License + except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from such + party’s negligence to the extent applicable law prohibits such limitation. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts of + a jurisdiction where the defendant maintains its principal place of business + and such litigation shall be governed by laws of that jurisdiction, without + reference to its conflict-of-law provisions. Nothing in this Section shall + prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject matter + hereof. If any provision of this License is held to be unenforceable, such + provision shall be reformed only to the extent necessary to make it + enforceable. Any law or regulation which provides that the language of a + contract shall be construed against the drafter shall not be used to construe + this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of + the License under which You originally received the Covered Software, or + under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a modified + version of this License if you rename the license and remove any + references to the name of the license steward (except to note that such + modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + If You choose to distribute Source Code Form that is Incompatible With + Secondary Licenses under the terms of this version of the License, the + notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then +You may include the notice in a location (such as a LICENSE file in a relevant +directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses†Notice + + This Source Code Form is “Incompatible + With Secondary Licensesâ€, as defined by + the Mozilla Public License, v. 2.0. + diff --git a/vendor/github.com/hashicorp/go-version/README.md b/vendor/github.com/hashicorp/go-version/README.md new file mode 100644 index 000000000..4d2505090 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/README.md @@ -0,0 +1,66 @@ +# Versioning Library for Go +[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/main.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/main) +[![GoDoc](https://godoc.org/github.com/hashicorp/go-version?status.svg)](https://godoc.org/github.com/hashicorp/go-version) + +go-version is a library for parsing versions and version constraints, +and verifying versions against a set of constraints. go-version +can sort a collection of versions properly, handles prerelease/beta +versions, can increment versions, etc. + +Versions used with go-version must follow [SemVer](http://semver.org/). + +## Installation and Usage + +Package documentation can be found on +[GoDoc](http://godoc.org/github.com/hashicorp/go-version). + +Installation can be done with a normal `go get`: + +``` +$ go get github.com/hashicorp/go-version +``` + +#### Version Parsing and Comparison + +```go +v1, err := version.NewVersion("1.2") +v2, err := version.NewVersion("1.5+metadata") + +// Comparison example. There is also GreaterThan, Equal, and just +// a simple Compare that returns an int allowing easy >=, <=, etc. +if v1.LessThan(v2) { + fmt.Printf("%s is less than %s", v1, v2) +} +``` + +#### Version Constraints + +```go +v1, err := version.NewVersion("1.2") + +// Constraints example. +constraints, err := version.NewConstraint(">= 1.0, < 1.4") +if constraints.Check(v1) { + fmt.Printf("%s satisfies constraints %s", v1, constraints) +} +``` + +#### Version Sorting + +```go +versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"} +versions := make([]*version.Version, len(versionsRaw)) +for i, raw := range versionsRaw { + v, _ := version.NewVersion(raw) + versions[i] = v +} + +// After this, the versions are properly sorted +sort.Sort(version.Collection(versions)) +``` + +## Issues and Contributing + +If you find an issue with this library, please report an issue. If you'd +like, we welcome any contributions. Fork this library and submit a pull +request. diff --git a/vendor/github.com/hashicorp/go-version/constraint.go b/vendor/github.com/hashicorp/go-version/constraint.go new file mode 100644 index 000000000..da5d1aca1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/constraint.go @@ -0,0 +1,296 @@ +package version + +import ( + "fmt" + "reflect" + "regexp" + "sort" + "strings" +) + +// Constraint represents a single constraint for a version, such as +// ">= 1.0". +type Constraint struct { + f constraintFunc + op operator + check *Version + original string +} + +func (c *Constraint) Equals(con *Constraint) bool { + return c.op == con.op && c.check.Equal(con.check) +} + +// Constraints is a slice of constraints. We make a custom type so that +// we can add methods to it. +type Constraints []*Constraint + +type constraintFunc func(v, c *Version) bool + +var constraintOperators map[string]constraintOperation + +type constraintOperation struct { + op operator + f constraintFunc +} + +var constraintRegexp *regexp.Regexp + +func init() { + constraintOperators = map[string]constraintOperation{ + "": {op: equal, f: constraintEqual}, + "=": {op: equal, f: constraintEqual}, + "!=": {op: notEqual, f: constraintNotEqual}, + ">": {op: greaterThan, f: constraintGreaterThan}, + "<": {op: lessThan, f: constraintLessThan}, + ">=": {op: greaterThanEqual, f: constraintGreaterThanEqual}, + "<=": {op: lessThanEqual, f: constraintLessThanEqual}, + "~>": {op: pessimistic, f: constraintPessimistic}, + } + + ops := make([]string, 0, len(constraintOperators)) + for k := range constraintOperators { + ops = append(ops, regexp.QuoteMeta(k)) + } + + constraintRegexp = regexp.MustCompile(fmt.Sprintf( + `^\s*(%s)\s*(%s)\s*$`, + strings.Join(ops, "|"), + VersionRegexpRaw)) +} + +// NewConstraint will parse one or more constraints from the given +// constraint string. The string must be a comma-separated list of +// constraints. +func NewConstraint(v string) (Constraints, error) { + vs := strings.Split(v, ",") + result := make([]*Constraint, len(vs)) + for i, single := range vs { + c, err := parseSingle(single) + if err != nil { + return nil, err + } + + result[i] = c + } + + return Constraints(result), nil +} + +// MustConstraints is a helper that wraps a call to a function +// returning (Constraints, error) and panics if error is non-nil. +func MustConstraints(c Constraints, err error) Constraints { + if err != nil { + panic(err) + } + + return c +} + +// Check tests if a version satisfies all the constraints. +func (cs Constraints) Check(v *Version) bool { + for _, c := range cs { + if !c.Check(v) { + return false + } + } + + return true +} + +// Equals compares Constraints with other Constraints +// for equality. This may not represent logical equivalence +// of compared constraints. +// e.g. even though '>0.1,>0.2' is logically equivalent +// to '>0.2' it is *NOT* treated as equal. +// +// Missing operator is treated as equal to '=', whitespaces +// are ignored and constraints are sorted before comaparison. +func (cs Constraints) Equals(c Constraints) bool { + if len(cs) != len(c) { + return false + } + + // make copies to retain order of the original slices + left := make(Constraints, len(cs)) + copy(left, cs) + sort.Stable(left) + right := make(Constraints, len(c)) + copy(right, c) + sort.Stable(right) + + // compare sorted slices + for i, con := range left { + if !con.Equals(right[i]) { + return false + } + } + + return true +} + +func (cs Constraints) Len() int { + return len(cs) +} + +func (cs Constraints) Less(i, j int) bool { + if cs[i].op < cs[j].op { + return true + } + if cs[i].op > cs[j].op { + return false + } + + return cs[i].check.LessThan(cs[j].check) +} + +func (cs Constraints) Swap(i, j int) { + cs[i], cs[j] = cs[j], cs[i] +} + +// Returns the string format of the constraints +func (cs Constraints) String() string { + csStr := make([]string, len(cs)) + for i, c := range cs { + csStr[i] = c.String() + } + + return strings.Join(csStr, ",") +} + +// Check tests if a constraint is validated by the given version. +func (c *Constraint) Check(v *Version) bool { + return c.f(v, c.check) +} + +// Prerelease returns true if the version underlying this constraint +// contains a prerelease field. +func (c *Constraint) Prerelease() bool { + return len(c.check.Prerelease()) > 0 +} + +func (c *Constraint) String() string { + return c.original +} + +func parseSingle(v string) (*Constraint, error) { + matches := constraintRegexp.FindStringSubmatch(v) + if matches == nil { + return nil, fmt.Errorf("Malformed constraint: %s", v) + } + + check, err := NewVersion(matches[2]) + if err != nil { + return nil, err + } + + cop := constraintOperators[matches[1]] + + return &Constraint{ + f: cop.f, + op: cop.op, + check: check, + original: v, + }, nil +} + +func prereleaseCheck(v, c *Version) bool { + switch vPre, cPre := v.Prerelease() != "", c.Prerelease() != ""; { + case cPre && vPre: + // A constraint with a pre-release can only match a pre-release version + // with the same base segments. + return reflect.DeepEqual(c.Segments64(), v.Segments64()) + + case !cPre && vPre: + // A constraint without a pre-release can only match a version without a + // pre-release. + return false + + case cPre && !vPre: + // OK, except with the pessimistic operator + case !cPre && !vPre: + // OK + } + return true +} + +//------------------------------------------------------------------- +// Constraint functions +//------------------------------------------------------------------- + +type operator rune + +const ( + equal operator = '=' + notEqual operator = '≠' + greaterThan operator = '>' + lessThan operator = '<' + greaterThanEqual operator = '≥' + lessThanEqual operator = '≤' + pessimistic operator = '~' +) + +func constraintEqual(v, c *Version) bool { + return v.Equal(c) +} + +func constraintNotEqual(v, c *Version) bool { + return !v.Equal(c) +} + +func constraintGreaterThan(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) == 1 +} + +func constraintLessThan(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) == -1 +} + +func constraintGreaterThanEqual(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) >= 0 +} + +func constraintLessThanEqual(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) <= 0 +} + +func constraintPessimistic(v, c *Version) bool { + // Using a pessimistic constraint with a pre-release, restricts versions to pre-releases + if !prereleaseCheck(v, c) || (c.Prerelease() != "" && v.Prerelease() == "") { + return false + } + + // If the version being checked is naturally less than the constraint, then there + // is no way for the version to be valid against the constraint + if v.LessThan(c) { + return false + } + // We'll use this more than once, so grab the length now so it's a little cleaner + // to write the later checks + cs := len(c.segments) + + // If the version being checked has less specificity than the constraint, then there + // is no way for the version to be valid against the constraint + if cs > len(v.segments) { + return false + } + + // Check the segments in the constraint against those in the version. If the version + // being checked, at any point, does not have the same values in each index of the + // constraints segments, then it cannot be valid against the constraint. + for i := 0; i < c.si-1; i++ { + if v.segments[i] != c.segments[i] { + return false + } + } + + // Check the last part of the segment in the constraint. If the version segment at + // this index is less than the constraints segment at this index, then it cannot + // be valid against the constraint + if c.segments[cs-1] > v.segments[cs-1] { + return false + } + + // If nothing has rejected the version by now, it's valid + return true +} diff --git a/vendor/github.com/hashicorp/go-version/version.go b/vendor/github.com/hashicorp/go-version/version.go new file mode 100644 index 000000000..e87df6990 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/version.go @@ -0,0 +1,407 @@ +package version + +import ( + "bytes" + "fmt" + "reflect" + "regexp" + "strconv" + "strings" +) + +// The compiled regular expression used to test the validity of a version. +var ( + versionRegexp *regexp.Regexp + semverRegexp *regexp.Regexp +) + +// The raw regular expression string used for testing the validity +// of a version. +const ( + VersionRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` + + `(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-?([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` + + `(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` + + `?` + + // SemverRegexpRaw requires a separator between version and prerelease + SemverRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` + + `(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` + + `(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` + + `?` +) + +// Version represents a single version. +type Version struct { + metadata string + pre string + segments []int64 + si int + original string +} + +func init() { + versionRegexp = regexp.MustCompile("^" + VersionRegexpRaw + "$") + semverRegexp = regexp.MustCompile("^" + SemverRegexpRaw + "$") +} + +// NewVersion parses the given version and returns a new +// Version. +func NewVersion(v string) (*Version, error) { + return newVersion(v, versionRegexp) +} + +// NewSemver parses the given version and returns a new +// Version that adheres strictly to SemVer specs +// https://semver.org/ +func NewSemver(v string) (*Version, error) { + return newVersion(v, semverRegexp) +} + +func newVersion(v string, pattern *regexp.Regexp) (*Version, error) { + matches := pattern.FindStringSubmatch(v) + if matches == nil { + return nil, fmt.Errorf("Malformed version: %s", v) + } + segmentsStr := strings.Split(matches[1], ".") + segments := make([]int64, len(segmentsStr)) + for i, str := range segmentsStr { + val, err := strconv.ParseInt(str, 10, 64) + if err != nil { + return nil, fmt.Errorf( + "Error parsing version: %s", err) + } + + segments[i] = val + } + + // Even though we could support more than three segments, if we + // got less than three, pad it with 0s. This is to cover the basic + // default usecase of semver, which is MAJOR.MINOR.PATCH at the minimum + for i := len(segments); i < 3; i++ { + segments = append(segments, 0) + } + + pre := matches[7] + if pre == "" { + pre = matches[4] + } + + return &Version{ + metadata: matches[10], + pre: pre, + segments: segments, + si: len(segmentsStr), + original: v, + }, nil +} + +// Must is a helper that wraps a call to a function returning (*Version, error) +// and panics if error is non-nil. +func Must(v *Version, err error) *Version { + if err != nil { + panic(err) + } + + return v +} + +// Compare compares this version to another version. This +// returns -1, 0, or 1 if this version is smaller, equal, +// or larger than the other version, respectively. +// +// If you want boolean results, use the LessThan, Equal, +// GreaterThan, GreaterThanOrEqual or LessThanOrEqual methods. +func (v *Version) Compare(other *Version) int { + // A quick, efficient equality check + if v.String() == other.String() { + return 0 + } + + segmentsSelf := v.Segments64() + segmentsOther := other.Segments64() + + // If the segments are the same, we must compare on prerelease info + if reflect.DeepEqual(segmentsSelf, segmentsOther) { + preSelf := v.Prerelease() + preOther := other.Prerelease() + if preSelf == "" && preOther == "" { + return 0 + } + if preSelf == "" { + return 1 + } + if preOther == "" { + return -1 + } + + return comparePrereleases(preSelf, preOther) + } + + // Get the highest specificity (hS), or if they're equal, just use segmentSelf length + lenSelf := len(segmentsSelf) + lenOther := len(segmentsOther) + hS := lenSelf + if lenSelf < lenOther { + hS = lenOther + } + // Compare the segments + // Because a constraint could have more/less specificity than the version it's + // checking, we need to account for a lopsided or jagged comparison + for i := 0; i < hS; i++ { + if i > lenSelf-1 { + // This means Self had the lower specificity + // Check to see if the remaining segments in Other are all zeros + if !allZero(segmentsOther[i:]) { + // if not, it means that Other has to be greater than Self + return -1 + } + break + } else if i > lenOther-1 { + // this means Other had the lower specificity + // Check to see if the remaining segments in Self are all zeros - + if !allZero(segmentsSelf[i:]) { + //if not, it means that Self has to be greater than Other + return 1 + } + break + } + lhs := segmentsSelf[i] + rhs := segmentsOther[i] + if lhs == rhs { + continue + } else if lhs < rhs { + return -1 + } + // Otherwis, rhs was > lhs, they're not equal + return 1 + } + + // if we got this far, they're equal + return 0 +} + +func allZero(segs []int64) bool { + for _, s := range segs { + if s != 0 { + return false + } + } + return true +} + +func comparePart(preSelf string, preOther string) int { + if preSelf == preOther { + return 0 + } + + var selfInt int64 + selfNumeric := true + selfInt, err := strconv.ParseInt(preSelf, 10, 64) + if err != nil { + selfNumeric = false + } + + var otherInt int64 + otherNumeric := true + otherInt, err = strconv.ParseInt(preOther, 10, 64) + if err != nil { + otherNumeric = false + } + + // if a part is empty, we use the other to decide + if preSelf == "" { + if otherNumeric { + return -1 + } + return 1 + } + + if preOther == "" { + if selfNumeric { + return 1 + } + return -1 + } + + if selfNumeric && !otherNumeric { + return -1 + } else if !selfNumeric && otherNumeric { + return 1 + } else if !selfNumeric && !otherNumeric && preSelf > preOther { + return 1 + } else if selfInt > otherInt { + return 1 + } + + return -1 +} + +func comparePrereleases(v string, other string) int { + // the same pre release! + if v == other { + return 0 + } + + // split both pre releases for analyse their parts + selfPreReleaseMeta := strings.Split(v, ".") + otherPreReleaseMeta := strings.Split(other, ".") + + selfPreReleaseLen := len(selfPreReleaseMeta) + otherPreReleaseLen := len(otherPreReleaseMeta) + + biggestLen := otherPreReleaseLen + if selfPreReleaseLen > otherPreReleaseLen { + biggestLen = selfPreReleaseLen + } + + // loop for parts to find the first difference + for i := 0; i < biggestLen; i = i + 1 { + partSelfPre := "" + if i < selfPreReleaseLen { + partSelfPre = selfPreReleaseMeta[i] + } + + partOtherPre := "" + if i < otherPreReleaseLen { + partOtherPre = otherPreReleaseMeta[i] + } + + compare := comparePart(partSelfPre, partOtherPre) + // if parts are equals, continue the loop + if compare != 0 { + return compare + } + } + + return 0 +} + +// Core returns a new version constructed from only the MAJOR.MINOR.PATCH +// segments of the version, without prerelease or metadata. +func (v *Version) Core() *Version { + segments := v.Segments64() + segmentsOnly := fmt.Sprintf("%d.%d.%d", segments[0], segments[1], segments[2]) + return Must(NewVersion(segmentsOnly)) +} + +// Equal tests if two versions are equal. +func (v *Version) Equal(o *Version) bool { + if v == nil || o == nil { + return v == o + } + + return v.Compare(o) == 0 +} + +// GreaterThan tests if this version is greater than another version. +func (v *Version) GreaterThan(o *Version) bool { + return v.Compare(o) > 0 +} + +// GreaterThanOrEqual tests if this version is greater than or equal to another version. +func (v *Version) GreaterThanOrEqual(o *Version) bool { + return v.Compare(o) >= 0 +} + +// LessThan tests if this version is less than another version. +func (v *Version) LessThan(o *Version) bool { + return v.Compare(o) < 0 +} + +// LessThanOrEqual tests if this version is less than or equal to another version. +func (v *Version) LessThanOrEqual(o *Version) bool { + return v.Compare(o) <= 0 +} + +// Metadata returns any metadata that was part of the version +// string. +// +// Metadata is anything that comes after the "+" in the version. +// For example, with "1.2.3+beta", the metadata is "beta". +func (v *Version) Metadata() string { + return v.metadata +} + +// Prerelease returns any prerelease data that is part of the version, +// or blank if there is no prerelease data. +// +// Prerelease information is anything that comes after the "-" in the +// version (but before any metadata). For example, with "1.2.3-beta", +// the prerelease information is "beta". +func (v *Version) Prerelease() string { + return v.pre +} + +// Segments returns the numeric segments of the version as a slice of ints. +// +// This excludes any metadata or pre-release information. For example, +// for a version "1.2.3-beta", segments will return a slice of +// 1, 2, 3. +func (v *Version) Segments() []int { + segmentSlice := make([]int, len(v.segments)) + for i, v := range v.segments { + segmentSlice[i] = int(v) + } + return segmentSlice +} + +// Segments64 returns the numeric segments of the version as a slice of int64s. +// +// This excludes any metadata or pre-release information. For example, +// for a version "1.2.3-beta", segments will return a slice of +// 1, 2, 3. +func (v *Version) Segments64() []int64 { + result := make([]int64, len(v.segments)) + copy(result, v.segments) + return result +} + +// String returns the full version string included pre-release +// and metadata information. +// +// This value is rebuilt according to the parsed segments and other +// information. Therefore, ambiguities in the version string such as +// prefixed zeroes (1.04.0 => 1.4.0), `v` prefix (v1.0.0 => 1.0.0), and +// missing parts (1.0 => 1.0.0) will be made into a canonicalized form +// as shown in the parenthesized examples. +func (v *Version) String() string { + var buf bytes.Buffer + fmtParts := make([]string, len(v.segments)) + for i, s := range v.segments { + // We can ignore err here since we've pre-parsed the values in segments + str := strconv.FormatInt(s, 10) + fmtParts[i] = str + } + fmt.Fprintf(&buf, strings.Join(fmtParts, ".")) + if v.pre != "" { + fmt.Fprintf(&buf, "-%s", v.pre) + } + if v.metadata != "" { + fmt.Fprintf(&buf, "+%s", v.metadata) + } + + return buf.String() +} + +// Original returns the original parsed version as-is, including any +// potential whitespace, `v` prefix, etc. +func (v *Version) Original() string { + return v.original +} + +// UnmarshalText implements encoding.TextUnmarshaler interface. +func (v *Version) UnmarshalText(b []byte) error { + temp, err := NewVersion(string(b)) + if err != nil { + return err + } + + *v = *temp + + return nil +} + +// MarshalText implements encoding.TextMarshaler interface. +func (v *Version) MarshalText() ([]byte, error) { + return []byte(v.String()), nil +} diff --git a/vendor/github.com/hashicorp/go-version/version_collection.go b/vendor/github.com/hashicorp/go-version/version_collection.go new file mode 100644 index 000000000..cc888d43e --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/version_collection.go @@ -0,0 +1,17 @@ +package version + +// Collection is a type that implements the sort.Interface interface +// so that versions can be sorted. +type Collection []*Version + +func (v Collection) Len() int { + return len(v) +} + +func (v Collection) Less(i, j int) bool { + return v[i].LessThan(v[j]) +} + +func (v Collection) Swap(i, j int) { + v[i], v[j] = v[j], v[i] +} diff --git a/vendor/github.com/hashicorp/nomad/api/allocations.go b/vendor/github.com/hashicorp/nomad/api/allocations.go index 0159a9e12..121a75934 100644 --- a/vendor/github.com/hashicorp/nomad/api/allocations.go +++ b/vendor/github.com/hashicorp/nomad/api/allocations.go @@ -30,6 +30,7 @@ const ( AllocClientStatusComplete = "complete" AllocClientStatusFailed = "failed" AllocClientStatusLost = "lost" + AllocClientStatusUnknown = "unknown" ) const ( @@ -270,6 +271,7 @@ type Allocation struct { PreviousAllocation string NextAllocation string RescheduleTracker *RescheduleTracker + NetworkStatus *AllocNetworkStatus PreemptedAllocations []string PreemptedByAllocation string CreateIndex uint64 @@ -283,6 +285,7 @@ type Allocation struct { type AllocationMetric struct { NodesEvaluated int NodesFiltered int + NodesInPool int NodesAvailable map[string]int ClassFiltered map[string]int ConstraintFiltered map[string]int @@ -326,6 +329,7 @@ func (a *Allocation) Stub() *AllocationListStub { TaskStates: a.TaskStates, DeploymentStatus: a.DeploymentStatus, FollowupEvalID: a.FollowupEvalID, + NextAllocation: a.NextAllocation, RescheduleTracker: a.RescheduleTracker, PreemptedAllocations: a.PreemptedAllocations, PreemptedByAllocation: a.PreemptedByAllocation, @@ -379,6 +383,7 @@ type AllocationListStub struct { TaskStates map[string]*TaskState DeploymentStatus *AllocDeploymentStatus FollowupEvalID string + NextAllocation string RescheduleTracker *RescheduleTracker PreemptedAllocations []string PreemptedByAllocation string @@ -398,6 +403,15 @@ type AllocDeploymentStatus struct { ModifyIndex uint64 } +// AllocNetworkStatus captures the status of an allocation's network during runtime. +// Depending on the network mode, an allocation's address may need to be known to other +// systems in Nomad such as service registration. +type AllocNetworkStatus struct { + InterfaceName string + Address string + DNS *DNSConfig +} + type AllocatedResources struct { Tasks map[string]*AllocatedTaskResources Shared AllocatedSharedResources diff --git a/vendor/github.com/hashicorp/nomad/api/api.go b/vendor/github.com/hashicorp/nomad/api/api.go index 1bf97f05f..ac755e254 100644 --- a/vendor/github.com/hashicorp/nomad/api/api.go +++ b/vendor/github.com/hashicorp/nomad/api/api.go @@ -895,13 +895,16 @@ func (c *Client) websocket(endpoint string, q *QueryOptions) (*websocket.Conn, * conn, resp, err := dialer.Dial(rhttp.URL.String(), rhttp.Header) // check resp status code, as it's more informative than handshake error we get from ws library - if resp != nil && resp.StatusCode != 101 { + if resp != nil && resp.StatusCode != http.StatusSwitchingProtocols { var buf bytes.Buffer if resp.Header.Get("Content-Encoding") == "gzip" { greader, err := gzip.NewReader(resp.Body) if err != nil { - return nil, nil, fmt.Errorf("Unexpected response code: %d", resp.StatusCode) + return nil, nil, newUnexpectedResponseError( + fromStatusCode(resp.StatusCode), + withExpectedStatuses([]int{http.StatusSwitchingProtocols}), + withError(err)) } io.Copy(&buf, greader) } else { @@ -909,7 +912,11 @@ func (c *Client) websocket(endpoint string, q *QueryOptions) (*websocket.Conn, * } resp.Body.Close() - return nil, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes()) + return nil, nil, newUnexpectedResponseError( + fromStatusCode(resp.StatusCode), + withExpectedStatuses([]int{http.StatusSwitchingProtocols}), + withBody(fmt.Sprint(buf.Bytes())), + ) } return conn, resp, err @@ -1129,24 +1136,6 @@ func encodeBody(obj interface{}) (io.Reader, error) { return buf, nil } -// requireOK is used to wrap doRequest and check for a 200 -func requireOK(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { - if e != nil { - if resp != nil { - resp.Body.Close() - } - return d, nil, e - } - if resp.StatusCode != 200 { - var buf bytes.Buffer - _, _ = io.Copy(&buf, resp.Body) - _ = resp.Body.Close() - body := strings.TrimSpace(buf.String()) - return d, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, body) - } - return d, resp, nil -} - // Context returns the context used for canceling HTTP requests related to this query func (o *QueryOptions) Context() context.Context { if o != nil && o.ctx != nil { diff --git a/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go b/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go index 2ce523a72..5176f5b82 100644 --- a/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go +++ b/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go @@ -15,6 +15,7 @@ const ( Evals Context = "evals" Jobs Context = "jobs" Nodes Context = "nodes" + NodePools Context = "node_pools" Namespaces Context = "namespaces" Quotas Context = "quotas" Recommendations Context = "recommendations" diff --git a/vendor/github.com/hashicorp/nomad/api/error_unexpected_response.go b/vendor/github.com/hashicorp/nomad/api/error_unexpected_response.go new file mode 100644 index 000000000..b843fc7ab --- /dev/null +++ b/vendor/github.com/hashicorp/nomad/api/error_unexpected_response.go @@ -0,0 +1,178 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strings" + "time" + + "golang.org/x/exp/slices" +) + +// UnexpectedResponseError tracks the components for API errors encountered when +// requireOK and requireStatusIn's conditions are not met. +type UnexpectedResponseError struct { + expected []int + statusCode int + statusText string + body string + err error + additional error +} + +func (e UnexpectedResponseError) HasExpectedStatuses() bool { return len(e.expected) > 0 } +func (e UnexpectedResponseError) ExpectedStatuses() []int { return e.expected } +func (e UnexpectedResponseError) HasStatusCode() bool { return e.statusCode != 0 } +func (e UnexpectedResponseError) StatusCode() int { return e.statusCode } +func (e UnexpectedResponseError) HasStatusText() bool { return e.statusText != "" } +func (e UnexpectedResponseError) StatusText() string { return e.statusText } +func (e UnexpectedResponseError) HasBody() bool { return e.body != "" } +func (e UnexpectedResponseError) Body() string { return e.body } +func (e UnexpectedResponseError) HasError() bool { return e.err != nil } +func (e UnexpectedResponseError) Unwrap() error { return e.err } +func (e UnexpectedResponseError) HasAdditional() bool { return e.additional != nil } +func (e UnexpectedResponseError) Additional() error { return e.additional } +func newUnexpectedResponseError(src unexpectedResponseErrorSource, opts ...unexpectedResponseErrorOption) UnexpectedResponseError { + nErr := src() + for _, opt := range opts { + opt(nErr) + } + if nErr.statusText == "" { + // the stdlib's http.StatusText function is a good place to start + nErr.statusFromCode(http.StatusText) + } + + return *nErr +} + +// Use textual representation of the given integer code. Called when status text +// is not set using the WithStatusText option. +func (e UnexpectedResponseError) statusFromCode(f func(int) string) { + e.statusText = f(e.statusCode) + if !e.HasStatusText() { + e.statusText = "unknown status code" + } +} + +func (e UnexpectedResponseError) Error() string { + var eTxt strings.Builder + eTxt.WriteString("Unexpected response code") + if e.HasBody() || e.HasStatusCode() { + eTxt.WriteString(": ") + } + if e.HasStatusCode() { + eTxt.WriteString(fmt.Sprint(e.statusCode)) + if e.HasBody() { + eTxt.WriteRune(' ') + } + } + if e.HasBody() { + eTxt.WriteString(fmt.Sprintf("(%s)", e.body)) + } + + if e.HasAdditional() { + eTxt.WriteString(fmt.Sprintf(". Additionally, an error occurred while constructing this error (%s); the body might be truncated or missing.", e.additional.Error())) + } + + return eTxt.String() +} + +// UnexpectedResponseErrorOptions are functions passed to NewUnexpectedResponseError +// to customize the created error. +type unexpectedResponseErrorOption func(*UnexpectedResponseError) + +// withError allows the addition of a Go error that may have been encountered +// while processing the response. For example, if there is an error constructing +// the gzip reader to process a gzip-encoded response body. +func withError(e error) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.err = e } +} + +// withBody overwrites the Body value with the provided custom value +func withBody(b string) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.body = b } +} + +// withStatusText overwrites the StatusText value the provided custom value +func withStatusText(st string) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.statusText = st } +} + +// withExpectedStatuses provides a list of statuses that the receiving function +// expected to receive. This can be used by API callers to provide more feedback +// to end-users. +func withExpectedStatuses(s []int) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.expected = slices.Clone(s) } +} + +// unexpectedResponseErrorSource provides the basis for a NewUnexpectedResponseError. +type unexpectedResponseErrorSource func() *UnexpectedResponseError + +// fromHTTPResponse read an open HTTP response, drains and closes its body as +// the data for the UnexpectedResponseError. +func fromHTTPResponse(resp *http.Response) unexpectedResponseErrorSource { + return func() *UnexpectedResponseError { + u := new(UnexpectedResponseError) + + if resp != nil { + // collect and close the body + var buf bytes.Buffer + if _, e := io.Copy(&buf, resp.Body); e != nil { + u.additional = e + } + + // Body has been tested as safe to close more than once + _ = resp.Body.Close() + body := strings.TrimSpace(buf.String()) + + // make and return the error + u.statusCode = resp.StatusCode + u.statusText = strings.TrimSpace(strings.TrimPrefix(resp.Status, fmt.Sprint(resp.StatusCode))) + u.body = body + } + return u + } +} + +// fromStatusCode attempts to resolve the status code to status text using +// the resolving function provided inside of the NewUnexpectedResponseError +// implementation. +func fromStatusCode(sc int) unexpectedResponseErrorSource { + return func() *UnexpectedResponseError { return &UnexpectedResponseError{statusCode: sc} } +} + +// doRequestWrapper is a function that wraps the client's doRequest method +// and can be used to provide error and response handling +type doRequestWrapper = func(time.Duration, *http.Response, error) (time.Duration, *http.Response, error) + +// requireOK is used to wrap doRequest and check for a 200 +func requireOK(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { + f := requireStatusIn(http.StatusOK) + return f(d, resp, e) +} + +// requireStatusIn is a doRequestWrapper generator that takes expected HTTP +// response codes and validates that the received response code is among them +func requireStatusIn(statuses ...int) doRequestWrapper { + return func(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { + if e != nil { + if resp != nil { + _ = resp.Body.Close() + } + return d, nil, e + } + + for _, status := range statuses { + if resp.StatusCode == status { + return d, resp, nil + } + } + + return d, nil, newUnexpectedResponseError(fromHTTPResponse(resp), withExpectedStatuses(statuses)) + } +} diff --git a/vendor/github.com/hashicorp/nomad/api/event_stream.go b/vendor/github.com/hashicorp/nomad/api/event_stream.go index 60e08fbe1..7721d15cc 100644 --- a/vendor/github.com/hashicorp/nomad/api/event_stream.go +++ b/vendor/github.com/hashicorp/nomad/api/event_stream.go @@ -19,6 +19,7 @@ const ( TopicAllocation Topic = "Allocation" TopicJob Topic = "Job" TopicNode Topic = "Node" + TopicNodePool Topic = "NodePool" TopicService Topic = "Service" TopicAll Topic = "*" ) @@ -99,6 +100,16 @@ func (e *Event) Node() (*Node, error) { return out.Node, nil } +// NodePool returns a NodePool struct from a given event payload. If the Event +// Topic is NodePool this will return a valid NodePool. +func (e *Event) NodePool() (*NodePool, error) { + out, err := e.decodePayload() + if err != nil { + return nil, err + } + return out.NodePool, nil +} + // Service returns a ServiceRegistration struct from a given event payload. If // the Event Topic is Service this will return a valid ServiceRegistration. func (e *Event) Service() (*ServiceRegistration, error) { @@ -115,6 +126,7 @@ type eventPayload struct { Evaluation *Evaluation `mapstructure:"Evaluation"` Job *Job `mapstructure:"Job"` Node *Node `mapstructure:"Node"` + NodePool *NodePool `mapstructure:"NodePool"` Service *ServiceRegistration `mapstructure:"Service"` } diff --git a/vendor/github.com/hashicorp/nomad/api/jobs.go b/vendor/github.com/hashicorp/nomad/api/jobs.go index 64b25c710..3b60f695b 100644 --- a/vendor/github.com/hashicorp/nomad/api/jobs.go +++ b/vendor/github.com/hashicorp/nomad/api/jobs.go @@ -29,6 +29,9 @@ const ( // on all clients. JobTypeSysbatch = "sysbatch" + // JobDefaultPriority is the default priority if not specified. + JobDefaultPriority = 50 + // PeriodicSpecCron is used for a cron spec. PeriodicSpecCron = "cron" @@ -444,6 +447,9 @@ func (j *Jobs) PlanOpts(job *Job, opts *PlanOptions, q *WriteOptions) (*JobPlanR if job == nil { return nil, nil, errors.New("must pass non-nil job") } + if job.ID == nil { + return nil, nil, errors.New("job is missing ID") + } // Setup the request req := &JobPlanRequest{ @@ -790,9 +796,11 @@ func (m *Multiregion) Copy() *Multiregion { copyRegion.Name = region.Name copyRegion.Count = pointerOf(*region.Count) copyRegion.Datacenters = append(copyRegion.Datacenters, region.Datacenters...) + copyRegion.NodePool = region.NodePool for k, v := range region.Meta { copyRegion.Meta[k] = v } + copy.Regions = append(copy.Regions, copyRegion) } return copy @@ -807,6 +815,7 @@ type MultiregionRegion struct { Name string `hcl:",label"` Count *int `hcl:"count,optional"` Datacenters []string `hcl:"datacenters,optional"` + NodePool string `hcl:"node_pool,optional"` Meta map[string]string `hcl:"meta,block"` } @@ -940,6 +949,7 @@ type Job struct { Priority *int `hcl:"priority,optional"` AllAtOnce *bool `mapstructure:"all_at_once" hcl:"all_at_once,optional"` Datacenters []string `hcl:"datacenters,optional"` + NodePool *string `hcl:"node_pool,optional"` Constraints []*Constraint `hcl:"constraint,block"` Affinities []*Affinity `hcl:"affinity,block"` TaskGroups []*TaskGroup `hcl:"group,block"` @@ -1003,7 +1013,7 @@ func (j *Job) Canonicalize() { j.Namespace = pointerOf(DefaultNamespace) } if j.Priority == nil { - j.Priority = pointerOf(0) + j.Priority = pointerOf(JobDefaultPriority) } if j.Stop == nil { j.Stop = pointerOf(false) @@ -1011,8 +1021,8 @@ func (j *Job) Canonicalize() { if j.Region == nil { j.Region = pointerOf(GlobalRegion) } - if j.Namespace == nil { - j.Namespace = pointerOf("default") + if j.NodePool == nil { + j.NodePool = pointerOf("") } if j.Type == nil { j.Type = pointerOf("service") diff --git a/vendor/github.com/hashicorp/nomad/api/namespace.go b/vendor/github.com/hashicorp/nomad/api/namespace.go index 80f9fe88e..d1b4fbbee 100644 --- a/vendor/github.com/hashicorp/nomad/api/namespace.go +++ b/vendor/github.com/hashicorp/nomad/api/namespace.go @@ -70,20 +70,31 @@ func (n *Namespaces) Delete(namespace string, q *WriteOptions) (*WriteMeta, erro // Namespace is used to serialize a namespace. type Namespace struct { - Name string - Description string - Quota string - Capabilities *NamespaceCapabilities `hcl:"capabilities,block"` - Meta map[string]string - CreateIndex uint64 - ModifyIndex uint64 + Name string + Description string + Quota string + Capabilities *NamespaceCapabilities `hcl:"capabilities,block"` + NodePoolConfiguration *NamespaceNodePoolConfiguration `hcl:"node_pool_config,block"` + Meta map[string]string + CreateIndex uint64 + ModifyIndex uint64 } +// NamespaceCapabilities represents a set of capabilities allowed for this +// namespace, to be checked at job submission time. type NamespaceCapabilities struct { EnabledTaskDrivers []string `hcl:"enabled_task_drivers"` DisabledTaskDrivers []string `hcl:"disabled_task_drivers"` } +// NamespaceNodePoolConfiguration stores configuration about node pools for a +// namespace. +type NamespaceNodePoolConfiguration struct { + Default string + Allowed []string + Denied []string +} + // NamespaceIndexSort is a wrapper to sort Namespaces by CreateIndex. We // reverse the test so that we get the highest index first. type NamespaceIndexSort []*Namespace diff --git a/vendor/github.com/hashicorp/nomad/api/node_pools.go b/vendor/github.com/hashicorp/nomad/api/node_pools.go new file mode 100644 index 000000000..d3f18bd87 --- /dev/null +++ b/vendor/github.com/hashicorp/nomad/api/node_pools.go @@ -0,0 +1,131 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +import ( + "errors" + "fmt" + "net/url" +) + +const ( + // NodePoolAll is the node pool that always includes all nodes. + NodePoolAll = "all" + + // NodePoolDefault is the default node pool. + NodePoolDefault = "default" +) + +// NodePools is used to access node pools endpoints. +type NodePools struct { + client *Client +} + +// NodePools returns a handle on the node pools endpoints. +func (c *Client) NodePools() *NodePools { + return &NodePools{client: c} +} + +// List is used to list all node pools. +func (n *NodePools) List(q *QueryOptions) ([]*NodePool, *QueryMeta, error) { + var resp []*NodePool + qm, err := n.client.query("/v1/node/pools", &resp, q) + if err != nil { + return nil, nil, err + } + return resp, qm, nil +} + +// PrefixList is used to list node pools that match a given prefix. +func (n *NodePools) PrefixList(prefix string, q *QueryOptions) ([]*NodePool, *QueryMeta, error) { + if q == nil { + q = &QueryOptions{} + } + q.Prefix = prefix + return n.List(q) +} + +// Info is used to fetch details of a specific node pool. +func (n *NodePools) Info(name string, q *QueryOptions) (*NodePool, *QueryMeta, error) { + if name == "" { + return nil, nil, errors.New("missing node pool name") + } + + var resp NodePool + qm, err := n.client.query("/v1/node/pool/"+url.PathEscape(name), &resp, q) + if err != nil { + return nil, nil, err + } + return &resp, qm, nil +} + +// Register is used to create or update a node pool. +func (n *NodePools) Register(pool *NodePool, w *WriteOptions) (*WriteMeta, error) { + if pool == nil { + return nil, errors.New("missing node pool") + } + if pool.Name == "" { + return nil, errors.New("missing node pool name") + } + + wm, err := n.client.put("/v1/node/pools", pool, nil, w) + if err != nil { + return nil, err + } + return wm, nil +} + +// Delete is used to delete a node pool. +func (n *NodePools) Delete(name string, w *WriteOptions) (*WriteMeta, error) { + if name == "" { + return nil, errors.New("missing node pool name") + } + + wm, err := n.client.delete("/v1/node/pool/"+url.PathEscape(name), nil, nil, w) + if err != nil { + return nil, err + } + return wm, nil +} + +// ListJobs is used to list all the jobs in a node pool. +func (n *NodePools) ListJobs(poolName string, q *QueryOptions) ([]*JobListStub, *QueryMeta, error) { + var resp []*JobListStub + qm, err := n.client.query( + fmt.Sprintf("/v1/node/pool/%s/jobs", url.PathEscape(poolName)), + &resp, q) + if err != nil { + return nil, nil, err + } + return resp, qm, nil +} + +// ListNodes is used to list all the nodes in a node pool. +func (n *NodePools) ListNodes(poolName string, q *QueryOptions) ([]*NodeListStub, *QueryMeta, error) { + var resp []*NodeListStub + qm, err := n.client.query( + fmt.Sprintf("/v1/node/pool/%s/nodes", url.PathEscape(poolName)), + &resp, q) + if err != nil { + return nil, nil, err + } + return resp, qm, nil +} + +// NodePool is used to serialize a node pool. +type NodePool struct { + Name string `hcl:"name,label"` + Description string `hcl:"description,optional"` + Meta map[string]string `hcl:"meta,block"` + SchedulerConfiguration *NodePoolSchedulerConfiguration `hcl:"scheduler_config,block"` + CreateIndex uint64 + ModifyIndex uint64 +} + +// NodePoolSchedulerConfiguration is used to serialize the scheduler +// configuration of a node pool. +type NodePoolSchedulerConfiguration struct { + SchedulerAlgorithm SchedulerAlgorithm `hcl:"scheduler_algorithm,optional"` + MemoryOversubscriptionEnabled *bool `hcl:"memory_oversubscription_enabled,optional"` +} diff --git a/vendor/github.com/hashicorp/nomad/api/nodes.go b/vendor/github.com/hashicorp/nomad/api/nodes.go index dfc5646be..697c7d731 100644 --- a/vendor/github.com/hashicorp/nomad/api/nodes.go +++ b/vendor/github.com/hashicorp/nomad/api/nodes.go @@ -553,6 +553,7 @@ type Node struct { Links map[string]string Meta map[string]string NodeClass string + NodePool string CgroupParent string Drain bool DrainStrategy *DrainStrategy @@ -914,6 +915,7 @@ type NodeListStub struct { Datacenter string Name string NodeClass string + NodePool string Version string Drain bool SchedulingEligibility string diff --git a/vendor/github.com/hashicorp/nomad/api/operator.go b/vendor/github.com/hashicorp/nomad/api/operator.go index ba8d41cec..32faf3546 100644 --- a/vendor/github.com/hashicorp/nomad/api/operator.go +++ b/vendor/github.com/hashicorp/nomad/api/operator.go @@ -6,8 +6,8 @@ package api import ( "encoding/json" "errors" - "fmt" "io" + "net/http" "strconv" "strings" "time" @@ -341,13 +341,15 @@ func (op *Operator) LicenseGet(q *QueryOptions) (*LicenseReply, *QueryMeta, erro } defer resp.Body.Close() - if resp.StatusCode == 204 { + if resp.StatusCode == http.StatusNoContent { return nil, nil, errors.New("Nomad Enterprise only endpoint") } - if resp.StatusCode != 200 { - body, _ := io.ReadAll(resp.Body) - return nil, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, body) + if resp.StatusCode != http.StatusOK { + return nil, nil, newUnexpectedResponseError( + fromHTTPResponse(resp), + withExpectedStatuses([]int{http.StatusOK, http.StatusNoContent}), + ) } err = json.NewDecoder(resp.Body).Decode(&reply) diff --git a/vendor/github.com/hashicorp/nomad/api/services.go b/vendor/github.com/hashicorp/nomad/api/services.go index 450236547..95f027810 100644 --- a/vendor/github.com/hashicorp/nomad/api/services.go +++ b/vendor/github.com/hashicorp/nomad/api/services.go @@ -212,6 +212,7 @@ type ServiceCheck struct { Interval time.Duration `hcl:"interval,optional"` Timeout time.Duration `hcl:"timeout,optional"` InitialStatus string `mapstructure:"initial_status" hcl:"initial_status,optional"` + TLSServerName string `mapstructure:"tls_server_name" hcl:"tls_server_name,optional"` TLSSkipVerify bool `mapstructure:"tls_skip_verify" hcl:"tls_skip_verify,optional"` Header map[string][]string `hcl:"header,block"` Method string `hcl:"method,optional"` diff --git a/vendor/github.com/hashicorp/nomad/api/tasks.go b/vendor/github.com/hashicorp/nomad/api/tasks.go index e928b3a04..188fa8649 100644 --- a/vendor/github.com/hashicorp/nomad/api/tasks.go +++ b/vendor/github.com/hashicorp/nomad/api/tasks.go @@ -641,12 +641,19 @@ func (g *TaskGroup) AddSpread(s *Spread) *TaskGroup { type LogConfig struct { MaxFiles *int `mapstructure:"max_files" hcl:"max_files,optional"` MaxFileSizeMB *int `mapstructure:"max_file_size" hcl:"max_file_size,optional"` + + // COMPAT(1.6.0): Enabled had to be swapped for Disabled to fix a backwards + // compatibility bug when restoring pre-1.5.4 jobs. Remove in 1.6.0 + Enabled *bool `mapstructure:"enabled" hcl:"enabled,optional"` + + Disabled *bool `mapstructure:"disabled" hcl:"disabled,optional"` } func DefaultLogConfig() *LogConfig { return &LogConfig{ MaxFiles: pointerOf(10), MaxFileSizeMB: pointerOf(10), + Disabled: pointerOf(false), } } @@ -657,6 +664,9 @@ func (l *LogConfig) Canonicalize() { if l.MaxFileSizeMB == nil { l.MaxFileSizeMB = pointerOf(10) } + if l.Disabled == nil { + l.Disabled = pointerOf(false) + } } // DispatchPayloadConfig configures how a task gets its input from a job dispatch @@ -909,6 +919,7 @@ type Vault struct { Policies []string `hcl:"policies,optional"` Namespace *string `mapstructure:"namespace" hcl:"namespace,optional"` Env *bool `hcl:"env,optional"` + DisableFile *bool `mapstructure:"disable_file" hcl:"disable_file,optional"` ChangeMode *string `mapstructure:"change_mode" hcl:"change_mode,optional"` ChangeSignal *string `mapstructure:"change_signal" hcl:"change_signal,optional"` } @@ -917,6 +928,9 @@ func (v *Vault) Canonicalize() { if v.Env == nil { v.Env = pointerOf(true) } + if v.DisableFile == nil { + v.DisableFile = pointerOf(false) + } if v.Namespace == nil { v.Namespace = pointerOf("") } diff --git a/vendor/github.com/hashicorp/nomad/api/variables.go b/vendor/github.com/hashicorp/nomad/api/variables.go index 91dc13cf4..86458c13a 100644 --- a/vendor/github.com/hashicorp/nomad/api/variables.go +++ b/vendor/github.com/hashicorp/nomad/api/variables.go @@ -4,14 +4,11 @@ package api import ( - "bytes" "encoding/json" "errors" "fmt" - "io" "net/http" "strings" - "time" ) const ( @@ -457,39 +454,3 @@ type ErrCASConflict struct { func (e ErrCASConflict) Error() string { return fmt.Sprintf("cas conflict: expected ModifyIndex %v; found %v", e.CheckIndex, e.Conflict.ModifyIndex) } - -// doRequestWrapper is a function that wraps the client's doRequest method -// and can be used to provide error and response handling -type doRequestWrapper = func(time.Duration, *http.Response, error) (time.Duration, *http.Response, error) - -// requireStatusIn is a doRequestWrapper generator that takes expected HTTP -// response codes and validates that the received response code is among them -func requireStatusIn(statuses ...int) doRequestWrapper { - fn := func(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { - if e != nil { - if resp != nil { - _ = resp.Body.Close() - } - return d, nil, e - } - - for _, status := range statuses { - if resp.StatusCode == status { - return d, resp, nil - } - } - - return d, nil, generateUnexpectedResponseCodeError(resp) - } - return fn -} - -// generateUnexpectedResponseCodeError creates a standardized error -// when the the API client's newRequest method receives an unexpected -// HTTP response code when accessing the variable's HTTP API -func generateUnexpectedResponseCodeError(resp *http.Response) error { - var buf bytes.Buffer - _, _ = io.Copy(&buf, resp.Body) - _ = resp.Body.Close() - return fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes()) -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/action.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/action.go deleted file mode 100644 index e915d7524..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/action.go +++ /dev/null @@ -1,328 +0,0 @@ -package hcloud - -import ( - "context" - "fmt" - "net/url" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Action represents an action in the Hetzner Cloud. -type Action struct { - ID int - Status ActionStatus - Command string - Progress int - Started time.Time - Finished time.Time - ErrorCode string - ErrorMessage string - Resources []*ActionResource -} - -// ActionStatus represents an action's status. -type ActionStatus string - -// List of action statuses. -const ( - ActionStatusRunning ActionStatus = "running" - ActionStatusSuccess ActionStatus = "success" - ActionStatusError ActionStatus = "error" -) - -// ActionResource references other resources from an action. -type ActionResource struct { - ID int - Type ActionResourceType -} - -// ActionResourceType represents an action's resource reference type. -type ActionResourceType string - -// List of action resource reference types. -const ( - ActionResourceTypeServer ActionResourceType = "server" - ActionResourceTypeImage ActionResourceType = "image" - ActionResourceTypeISO ActionResourceType = "iso" - ActionResourceTypeFloatingIP ActionResourceType = "floating_ip" - ActionResourceTypeVolume ActionResourceType = "volume" -) - -// ActionError is the error of an action. -type ActionError struct { - Code string - Message string -} - -func (e ActionError) Error() string { - return fmt.Sprintf("%s (%s)", e.Message, e.Code) -} - -func (a *Action) Error() error { - if a.ErrorCode != "" && a.ErrorMessage != "" { - return ActionError{ - Code: a.ErrorCode, - Message: a.ErrorMessage, - } - } - return nil -} - -// ActionClient is a client for the actions API. -type ActionClient struct { - client *Client -} - -// GetByID retrieves an action by its ID. If the action does not exist, nil is returned. -func (c *ActionClient) GetByID(ctx context.Context, id int) (*Action, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/actions/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.ActionGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return ActionFromSchema(body.Action), resp, nil -} - -// ActionListOpts specifies options for listing actions. -type ActionListOpts struct { - ListOpts - ID []int - Status []ActionStatus - Sort []string -} - -func (l ActionListOpts) values() url.Values { - vals := l.ListOpts.values() - for _, id := range l.ID { - vals.Add("id", fmt.Sprintf("%d", id)) - } - for _, status := range l.Status { - vals.Add("status", string(status)) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of actions for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *ActionClient) List(ctx context.Context, opts ActionListOpts) ([]*Action, *Response, error) { - path := "/actions?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.ActionListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - actions := make([]*Action, 0, len(body.Actions)) - for _, i := range body.Actions { - actions = append(actions, ActionFromSchema(i)) - } - return actions, resp, nil -} - -// All returns all actions. -func (c *ActionClient) All(ctx context.Context) ([]*Action, error) { - allActions := []*Action{} - - opts := ActionListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - actions, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allActions = append(allActions, actions...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allActions, nil -} - -// AllWithOpts returns all actions for the given options. -func (c *ActionClient) AllWithOpts(ctx context.Context, opts ActionListOpts) ([]*Action, error) { - allActions := []*Action{} - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - actions, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allActions = append(allActions, actions...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allActions, nil -} - -// WatchOverallProgress watches several actions' progress until they complete -// with success or error. This watching happens in a goroutine and updates are -// provided through the two returned channels: -// -// - The first channel receives percentage updates of the progress, based on -// the number of completed versus total watched actions. The return value -// is an int between 0 and 100. -// - The second channel returned receives errors for actions that did not -// complete successfully, as well as any errors that happened while -// querying the API. -// -// By default the method keeps watching until all actions have finished -// processing. If you want to be able to cancel the method or configure a -// timeout, use the [context.Context]. Once the method has stopped watching, -// both returned channels are closed. -// -// WatchOverallProgress uses the [WithPollBackoffFunc] of the [Client] to wait -// until sending the next request. -func (c *ActionClient) WatchOverallProgress(ctx context.Context, actions []*Action) (<-chan int, <-chan error) { - errCh := make(chan error, len(actions)) - progressCh := make(chan int) - - go func() { - defer close(errCh) - defer close(progressCh) - - successIDs := make([]int, 0, len(actions)) - watchIDs := make(map[int]struct{}, len(actions)) - for _, action := range actions { - watchIDs[action.ID] = struct{}{} - } - - retries := 0 - - for { - select { - case <-ctx.Done(): - errCh <- ctx.Err() - return - case <-time.After(c.client.pollBackoffFunc(retries)): - retries++ - } - - opts := ActionListOpts{} - for watchID := range watchIDs { - opts.ID = append(opts.ID, watchID) - } - - as, err := c.AllWithOpts(ctx, opts) - if err != nil { - errCh <- err - return - } - - for _, a := range as { - switch a.Status { - case ActionStatusRunning: - continue - case ActionStatusSuccess: - delete(watchIDs, a.ID) - successIDs := append(successIDs, a.ID) - sendProgress(progressCh, int(float64(len(actions)-len(successIDs))/float64(len(actions))*100)) - case ActionStatusError: - delete(watchIDs, a.ID) - errCh <- fmt.Errorf("action %d failed: %w", a.ID, a.Error()) - } - } - - if len(watchIDs) == 0 { - return - } - } - }() - - return progressCh, errCh -} - -// WatchProgress watches one action's progress until it completes with success -// or error. This watching happens in a goroutine and updates are provided -// through the two returned channels: -// -// - The first channel receives percentage updates of the progress, based on -// the progress percentage indicated by the API. The return value is an int -// between 0 and 100. -// - The second channel receives any errors that happened while querying the -// API, as well as the error of the action if it did not complete -// successfully, or nil if it did. -// -// By default the method keeps watching until the action has finished -// processing. If you want to be able to cancel the method or configure a -// timeout, use the [context.Context]. Once the method has stopped watching, -// both returned channels are closed. -// -// WatchProgress uses the [WithPollBackoffFunc] of the [Client] to wait until -// sending the next request. -func (c *ActionClient) WatchProgress(ctx context.Context, action *Action) (<-chan int, <-chan error) { - errCh := make(chan error, 1) - progressCh := make(chan int) - - go func() { - defer close(errCh) - defer close(progressCh) - - retries := 0 - - for { - select { - case <-ctx.Done(): - errCh <- ctx.Err() - return - case <-time.After(c.client.pollBackoffFunc(retries)): - retries++ - } - - a, _, err := c.GetByID(ctx, action.ID) - if err != nil { - errCh <- err - return - } - - switch a.Status { - case ActionStatusRunning: - sendProgress(progressCh, a.Progress) - case ActionStatusSuccess: - sendProgress(progressCh, 100) - errCh <- nil - return - case ActionStatusError: - errCh <- a.Error() - return - } - } - }() - - return progressCh, errCh -} - -func sendProgress(progressCh chan int, p int) { - select { - case progressCh <- p: - break - default: - break - } -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/certificate.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/certificate.go deleted file mode 100644 index 627855231..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/certificate.go +++ /dev/null @@ -1,387 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// CertificateType is the type of available certificate types. -type CertificateType string - -// Available certificate types. -const ( - CertificateTypeUploaded CertificateType = "uploaded" - CertificateTypeManaged CertificateType = "managed" -) - -// CertificateStatusType is defines the type for the various managed -// certificate status. -type CertificateStatusType string - -// Possible certificate status. -const ( - CertificateStatusTypePending CertificateStatusType = "pending" - CertificateStatusTypeFailed CertificateStatusType = "failed" - - // only in issuance. - CertificateStatusTypeCompleted CertificateStatusType = "completed" - - // only in renewal. - CertificateStatusTypeScheduled CertificateStatusType = "scheduled" - CertificateStatusTypeUnavailable CertificateStatusType = "unavailable" -) - -// CertificateUsedByRefType is the type of used by references for -// certificates. -type CertificateUsedByRefType string - -// Possible users of certificates. -const ( - CertificateUsedByRefTypeLoadBalancer CertificateUsedByRefType = "load_balancer" -) - -// CertificateUsedByRef points to a resource that uses this certificate. -type CertificateUsedByRef struct { - ID int - Type CertificateUsedByRefType -} - -// CertificateStatus indicates the status of a managed certificate. -type CertificateStatus struct { - Issuance CertificateStatusType - Renewal CertificateStatusType - Error *Error -} - -// IsFailed returns true if either the Issuance or the Renewal of a certificate -// failed. In this case the FailureReason field details the nature of the -// failure. -func (st *CertificateStatus) IsFailed() bool { - return st.Issuance == CertificateStatusTypeFailed || st.Renewal == CertificateStatusTypeFailed -} - -// Certificate represents an certificate in the Hetzner Cloud. -type Certificate struct { - ID int - Name string - Labels map[string]string - Type CertificateType - Certificate string - Created time.Time - NotValidBefore time.Time - NotValidAfter time.Time - DomainNames []string - Fingerprint string - Status *CertificateStatus - UsedBy []CertificateUsedByRef -} - -// CertificateCreateResult is the result of creating a certificate. -type CertificateCreateResult struct { - Certificate *Certificate - Action *Action -} - -// CertificateClient is a client for the Certificates API. -type CertificateClient struct { - client *Client -} - -// GetByID retrieves a Certificate by its ID. If the Certificate does not exist, nil is returned. -func (c *CertificateClient) GetByID(ctx context.Context, id int) (*Certificate, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/certificates/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.CertificateGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return CertificateFromSchema(body.Certificate), resp, nil -} - -// GetByName retrieves a Certificate by its name. If the Certificate does not exist, nil is returned. -func (c *CertificateClient) GetByName(ctx context.Context, name string) (*Certificate, *Response, error) { - if name == "" { - return nil, nil, nil - } - Certificate, response, err := c.List(ctx, CertificateListOpts{Name: name}) - if len(Certificate) == 0 { - return nil, response, err - } - return Certificate[0], response, err -} - -// Get retrieves a Certificate by its ID if the input can be parsed as an integer, otherwise it -// retrieves a Certificate by its name. If the Certificate does not exist, nil is returned. -func (c *CertificateClient) Get(ctx context.Context, idOrName string) (*Certificate, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// CertificateListOpts specifies options for listing Certificates. -type CertificateListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l CertificateListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of Certificates for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *CertificateClient) List(ctx context.Context, opts CertificateListOpts) ([]*Certificate, *Response, error) { - path := "/certificates?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.CertificateListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - Certificates := make([]*Certificate, 0, len(body.Certificates)) - for _, s := range body.Certificates { - Certificates = append(Certificates, CertificateFromSchema(s)) - } - return Certificates, resp, nil -} - -// All returns all Certificates. -func (c *CertificateClient) All(ctx context.Context) ([]*Certificate, error) { - allCertificates := []*Certificate{} - - opts := CertificateListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - Certificate, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allCertificates = append(allCertificates, Certificate...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allCertificates, nil -} - -// AllWithOpts returns all Certificates for the given options. -func (c *CertificateClient) AllWithOpts(ctx context.Context, opts CertificateListOpts) ([]*Certificate, error) { - var allCertificates []*Certificate - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - Certificates, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allCertificates = append(allCertificates, Certificates...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allCertificates, nil -} - -// CertificateCreateOpts specifies options for creating a new Certificate. -type CertificateCreateOpts struct { - Name string - Type CertificateType - Certificate string - PrivateKey string - Labels map[string]string - DomainNames []string -} - -// Validate checks if options are valid. -func (o CertificateCreateOpts) Validate() error { - if o.Name == "" { - return errors.New("missing name") - } - switch o.Type { - case "", CertificateTypeUploaded: - return o.validateUploaded() - case CertificateTypeManaged: - return o.validateManaged() - default: - return fmt.Errorf("invalid type: %s", o.Type) - } -} - -func (o CertificateCreateOpts) validateManaged() error { - if len(o.DomainNames) == 0 { - return errors.New("no domain names") - } - return nil -} - -func (o CertificateCreateOpts) validateUploaded() error { - if o.Certificate == "" { - return errors.New("missing certificate") - } - if o.PrivateKey == "" { - return errors.New("missing private key") - } - return nil -} - -// Create creates a new certificate uploaded certificate. -// -// Create returns an error for certificates of any other type. Use -// CreateCertificate to create such certificates. -func (c *CertificateClient) Create(ctx context.Context, opts CertificateCreateOpts) (*Certificate, *Response, error) { - if !(opts.Type == "" || opts.Type == CertificateTypeUploaded) { - return nil, nil, fmt.Errorf("invalid certificate type: %s", opts.Type) - } - result, resp, err := c.CreateCertificate(ctx, opts) - if err != nil { - return nil, resp, err - } - return result.Certificate, resp, nil -} - -// CreateCertificate creates a new certificate of any type. -func (c *CertificateClient) CreateCertificate( - ctx context.Context, opts CertificateCreateOpts, -) (CertificateCreateResult, *Response, error) { - var ( - action *Action - reqBody schema.CertificateCreateRequest - ) - - if err := opts.Validate(); err != nil { - return CertificateCreateResult{}, nil, err - } - - reqBody.Name = opts.Name - - switch opts.Type { - case "", CertificateTypeUploaded: - reqBody.Type = string(CertificateTypeUploaded) - reqBody.Certificate = opts.Certificate - reqBody.PrivateKey = opts.PrivateKey - case CertificateTypeManaged: - reqBody.Type = string(CertificateTypeManaged) - reqBody.DomainNames = opts.DomainNames - default: - return CertificateCreateResult{}, nil, fmt.Errorf("invalid certificate type: %v", opts.Type) - } - - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return CertificateCreateResult{}, nil, err - } - req, err := c.client.NewRequest(ctx, "POST", "/certificates", bytes.NewReader(reqBodyData)) - if err != nil { - return CertificateCreateResult{}, nil, err - } - - respBody := schema.CertificateCreateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return CertificateCreateResult{}, resp, err - } - cert := CertificateFromSchema(respBody.Certificate) - if respBody.Action != nil { - action = ActionFromSchema(*respBody.Action) - } - - return CertificateCreateResult{Certificate: cert, Action: action}, resp, nil -} - -// CertificateUpdateOpts specifies options for updating a Certificate. -type CertificateUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a Certificate. -func (c *CertificateClient) Update(ctx context.Context, certificate *Certificate, opts CertificateUpdateOpts) (*Certificate, *Response, error) { - reqBody := schema.CertificateUpdateRequest{} - if opts.Name != "" { - reqBody.Name = &opts.Name - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/certificates/%d", certificate.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.CertificateUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return CertificateFromSchema(respBody.Certificate), resp, nil -} - -// Delete deletes a certificate. -func (c *CertificateClient) Delete(ctx context.Context, certificate *Certificate) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/certificates/%d", certificate.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// RetryIssuance retries the issuance of a failed managed certificate. -func (c *CertificateClient) RetryIssuance(ctx context.Context, certificate *Certificate) (*Action, *Response, error) { - var respBody schema.CertificateIssuanceRetryResponse - - req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("/certificates/%d/actions/retry", certificate.ID), nil) - if err != nil { - return nil, nil, err - } - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, nil, err - } - action := ActionFromSchema(respBody.Action) - return action, resp, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/client.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/client.go deleted file mode 100644 index f3b5a833f..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/client.go +++ /dev/null @@ -1,460 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "net/http" - "net/http/httputil" - "net/url" - "strconv" - "strings" - "time" - - "github.com/prometheus/client_golang/prometheus" - "golang.org/x/net/http/httpguts" - - "github.com/hetznercloud/hcloud-go/hcloud/internal/instrumentation" - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Endpoint is the base URL of the API. -const Endpoint = "https://api.hetzner.cloud/v1" - -// UserAgent is the value for the library part of the User-Agent header -// that is sent with each request. -const UserAgent = "hcloud-go/" + Version - -// A BackoffFunc returns the duration to wait before performing the -// next retry. The retries argument specifies how many retries have -// already been performed. When called for the first time, retries is 0. -type BackoffFunc func(retries int) time.Duration - -// ConstantBackoff returns a BackoffFunc which backs off for -// constant duration d. -func ConstantBackoff(d time.Duration) BackoffFunc { - return func(_ int) time.Duration { - return d - } -} - -// ExponentialBackoff returns a BackoffFunc which implements an exponential -// backoff. -// It uses the formula: -// -// b^retries * d -func ExponentialBackoff(b float64, d time.Duration) BackoffFunc { - return func(retries int) time.Duration { - return time.Duration(math.Pow(b, float64(retries))) * d - } -} - -// Client is a client for the Hetzner Cloud API. -type Client struct { - endpoint string - token string - tokenValid bool - backoffFunc BackoffFunc - pollBackoffFunc BackoffFunc - httpClient *http.Client - applicationName string - applicationVersion string - userAgent string - debugWriter io.Writer - instrumentationRegistry *prometheus.Registry - - Action ActionClient - Certificate CertificateClient - Datacenter DatacenterClient - Firewall FirewallClient - FloatingIP FloatingIPClient - Image ImageClient - ISO ISOClient - LoadBalancer LoadBalancerClient - LoadBalancerType LoadBalancerTypeClient - Location LocationClient - Network NetworkClient - Pricing PricingClient - Server ServerClient - ServerType ServerTypeClient - SSHKey SSHKeyClient - Volume VolumeClient - PlacementGroup PlacementGroupClient - RDNS RDNSClient - PrimaryIP PrimaryIPClient -} - -// A ClientOption is used to configure a Client. -type ClientOption func(*Client) - -// WithEndpoint configures a Client to use the specified API endpoint. -func WithEndpoint(endpoint string) ClientOption { - return func(client *Client) { - client.endpoint = strings.TrimRight(endpoint, "/") - } -} - -// WithToken configures a Client to use the specified token for authentication. -func WithToken(token string) ClientOption { - return func(client *Client) { - client.token = token - client.tokenValid = httpguts.ValidHeaderFieldValue(token) - } -} - -// WithPollInterval configures a Client to use the specified interval when -// polling from the API. -// -// Deprecated: Setting the poll interval is deprecated, you can now configure -// [WithPollBackoffFunc] with a [ConstantBackoff] to get the same results. To -// migrate your code, replace your usage like this: -// -// // before -// hcloud.WithPollInterval(2 * time.Second) -// // now -// hcloud.WithPollBackoffFunc(hcloud.ConstantBackoff(2 * time.Second)) -func WithPollInterval(pollInterval time.Duration) ClientOption { - return WithPollBackoffFunc(ConstantBackoff(pollInterval)) -} - -// WithPollBackoffFunc configures a Client to use the specified backoff -// function when polling from the API. -func WithPollBackoffFunc(f BackoffFunc) ClientOption { - return func(client *Client) { - client.backoffFunc = f - } -} - -// WithBackoffFunc configures a Client to use the specified backoff function. -// The backoff function is used for retrying HTTP requests. -func WithBackoffFunc(f BackoffFunc) ClientOption { - return func(client *Client) { - client.backoffFunc = f - } -} - -// WithApplication configures a Client with the given application name and -// application version. The version may be blank. Programs are encouraged -// to at least set an application name. -func WithApplication(name, version string) ClientOption { - return func(client *Client) { - client.applicationName = name - client.applicationVersion = version - } -} - -// WithDebugWriter configures a Client to print debug information to the given -// writer. To, for example, print debug information on stderr, set it to os.Stderr. -func WithDebugWriter(debugWriter io.Writer) ClientOption { - return func(client *Client) { - client.debugWriter = debugWriter - } -} - -// WithHTTPClient configures a Client to perform HTTP requests with httpClient. -func WithHTTPClient(httpClient *http.Client) ClientOption { - return func(client *Client) { - client.httpClient = httpClient - } -} - -// WithInstrumentation configures a Client to collect metrics about the performed HTTP requests. -func WithInstrumentation(registry *prometheus.Registry) ClientOption { - return func(client *Client) { - client.instrumentationRegistry = registry - } -} - -// NewClient creates a new client. -func NewClient(options ...ClientOption) *Client { - client := &Client{ - endpoint: Endpoint, - tokenValid: true, - httpClient: &http.Client{}, - backoffFunc: ExponentialBackoff(2, 500*time.Millisecond), - pollBackoffFunc: ConstantBackoff(500 * time.Millisecond), - } - - for _, option := range options { - option(client) - } - - client.buildUserAgent() - if client.instrumentationRegistry != nil { - i := instrumentation.New("api", client.instrumentationRegistry) - client.httpClient.Transport = i.InstrumentedRoundTripper() - } - - client.Action = ActionClient{client: client} - client.Datacenter = DatacenterClient{client: client} - client.FloatingIP = FloatingIPClient{client: client} - client.Image = ImageClient{client: client} - client.ISO = ISOClient{client: client} - client.Location = LocationClient{client: client} - client.Network = NetworkClient{client: client} - client.Pricing = PricingClient{client: client} - client.Server = ServerClient{client: client} - client.ServerType = ServerTypeClient{client: client} - client.SSHKey = SSHKeyClient{client: client} - client.Volume = VolumeClient{client: client} - client.LoadBalancer = LoadBalancerClient{client: client} - client.LoadBalancerType = LoadBalancerTypeClient{client: client} - client.Certificate = CertificateClient{client: client} - client.Firewall = FirewallClient{client: client} - client.PlacementGroup = PlacementGroupClient{client: client} - client.RDNS = RDNSClient{client: client} - client.PrimaryIP = PrimaryIPClient{client: client} - - return client -} - -// NewRequest creates an HTTP request against the API. The returned request -// is assigned with ctx and has all necessary headers set (auth, user agent, etc.). -func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { - url := c.endpoint + path - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - req.Header.Set("User-Agent", c.userAgent) - - if !c.tokenValid { - return nil, errors.New("Authorization token contains invalid characters") - } else if c.token != "" { - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token)) - } - - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - req = req.WithContext(ctx) - return req, nil -} - -// Do performs an HTTP request against the API. -func (c *Client) Do(r *http.Request, v interface{}) (*Response, error) { - var retries int - var body []byte - var err error - if r.ContentLength > 0 { - body, err = io.ReadAll(r.Body) - if err != nil { - r.Body.Close() - return nil, err - } - r.Body.Close() - } - for { - if r.ContentLength > 0 { - r.Body = io.NopCloser(bytes.NewReader(body)) - } - - if c.debugWriter != nil { - dumpReq, err := dumpRequest(r) - if err != nil { - return nil, err - } - fmt.Fprintf(c.debugWriter, "--- Request:\n%s\n\n", dumpReq) - } - - resp, err := c.httpClient.Do(r) - if err != nil { - return nil, err - } - response := &Response{Response: resp} - body, err := io.ReadAll(resp.Body) - if err != nil { - resp.Body.Close() - return response, err - } - resp.Body.Close() - resp.Body = io.NopCloser(bytes.NewReader(body)) - - if c.debugWriter != nil { - dumpResp, err := httputil.DumpResponse(resp, true) - if err != nil { - return nil, err - } - fmt.Fprintf(c.debugWriter, "--- Response:\n%s\n\n", dumpResp) - } - - if err = response.readMeta(body); err != nil { - return response, fmt.Errorf("hcloud: error reading response meta data: %s", err) - } - - if resp.StatusCode >= 400 && resp.StatusCode <= 599 { - err = errorFromResponse(resp, body) - if err == nil { - err = fmt.Errorf("hcloud: server responded with status code %d", resp.StatusCode) - } else if isConflict(err) { - c.backoff(retries) - retries++ - continue - } - return response, err - } - if v != nil { - if w, ok := v.(io.Writer); ok { - _, err = io.Copy(w, bytes.NewReader(body)) - } else { - err = json.Unmarshal(body, v) - } - } - - return response, err - } -} - -func isConflict(error error) bool { - err, ok := error.(Error) - if !ok { - return false - } - return err.Code == ErrorCodeConflict -} - -func (c *Client) backoff(retries int) { - time.Sleep(c.backoffFunc(retries)) -} - -func (c *Client) all(f func(int) (*Response, error)) error { - var ( - page = 1 - ) - for { - resp, err := f(page) - if err != nil { - return err - } - if resp.Meta.Pagination == nil || resp.Meta.Pagination.NextPage == 0 { - return nil - } - page = resp.Meta.Pagination.NextPage - } -} - -func (c *Client) buildUserAgent() { - switch { - case c.applicationName != "" && c.applicationVersion != "": - c.userAgent = c.applicationName + "/" + c.applicationVersion + " " + UserAgent - case c.applicationName != "" && c.applicationVersion == "": - c.userAgent = c.applicationName + " " + UserAgent - default: - c.userAgent = UserAgent - } -} - -func dumpRequest(r *http.Request) ([]byte, error) { - // Duplicate the request, so we can redact the auth header - rDuplicate := r.Clone(context.Background()) - rDuplicate.Header.Set("Authorization", "REDACTED") - - // To get the request body we need to read it before the request was actually sent. - // See https://github.com/golang/go/issues/29792 - dumpReq, err := httputil.DumpRequestOut(rDuplicate, true) - if err != nil { - return nil, err - } - - // Set original request body to the duplicate created by DumpRequestOut. The request body is not duplicated - // by .Clone() and instead just referenced, so it would be completely read otherwise. - r.Body = rDuplicate.Body - - return dumpReq, nil -} - -func errorFromResponse(resp *http.Response, body []byte) error { - if !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { - return nil - } - - var respBody schema.ErrorResponse - if err := json.Unmarshal(body, &respBody); err != nil { - return nil - } - if respBody.Error.Code == "" && respBody.Error.Message == "" { - return nil - } - return ErrorFromSchema(respBody.Error) -} - -// Response represents a response from the API. It embeds http.Response. -type Response struct { - *http.Response - Meta Meta -} - -func (r *Response) readMeta(body []byte) error { - if h := r.Header.Get("RateLimit-Limit"); h != "" { - r.Meta.Ratelimit.Limit, _ = strconv.Atoi(h) - } - if h := r.Header.Get("RateLimit-Remaining"); h != "" { - r.Meta.Ratelimit.Remaining, _ = strconv.Atoi(h) - } - if h := r.Header.Get("RateLimit-Reset"); h != "" { - if ts, err := strconv.ParseInt(h, 10, 64); err == nil { - r.Meta.Ratelimit.Reset = time.Unix(ts, 0) - } - } - - if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { - var s schema.MetaResponse - if err := json.Unmarshal(body, &s); err != nil { - return err - } - if s.Meta.Pagination != nil { - p := PaginationFromSchema(*s.Meta.Pagination) - r.Meta.Pagination = &p - } - } - - return nil -} - -// Meta represents meta information included in an API response. -type Meta struct { - Pagination *Pagination - Ratelimit Ratelimit -} - -// Pagination represents pagination meta information. -type Pagination struct { - Page int - PerPage int - PreviousPage int - NextPage int - LastPage int - TotalEntries int -} - -// Ratelimit represents ratelimit information. -type Ratelimit struct { - Limit int - Remaining int - Reset time.Time -} - -// ListOpts specifies options for listing resources. -type ListOpts struct { - Page int // Page (starting at 1) - PerPage int // Items per page (0 means default) - LabelSelector string // Label selector for filtering by labels -} - -func (l ListOpts) values() url.Values { - vals := url.Values{} - if l.Page > 0 { - vals.Add("page", strconv.Itoa(l.Page)) - } - if l.PerPage > 0 { - vals.Add("per_page", strconv.Itoa(l.PerPage)) - } - if len(l.LabelSelector) > 0 { - vals.Add("label_selector", l.LabelSelector) - } - return vals -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/datacenter.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/datacenter.go deleted file mode 100644 index 5a841f945..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/datacenter.go +++ /dev/null @@ -1,133 +0,0 @@ -package hcloud - -import ( - "context" - "fmt" - "net/url" - "strconv" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Datacenter represents a datacenter in the Hetzner Cloud. -type Datacenter struct { - ID int - Name string - Description string - Location *Location - ServerTypes DatacenterServerTypes -} - -// DatacenterServerTypes represents the server types available and supported in a datacenter. -type DatacenterServerTypes struct { - Supported []*ServerType - Available []*ServerType -} - -// DatacenterClient is a client for the datacenter API. -type DatacenterClient struct { - client *Client -} - -// GetByID retrieves a datacenter by its ID. If the datacenter does not exist, nil is returned. -func (c *DatacenterClient) GetByID(ctx context.Context, id int) (*Datacenter, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/datacenters/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.DatacenterGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, resp, err - } - return DatacenterFromSchema(body.Datacenter), resp, nil -} - -// GetByName retrieves an datacenter by its name. If the datacenter does not exist, nil is returned. -func (c *DatacenterClient) GetByName(ctx context.Context, name string) (*Datacenter, *Response, error) { - if name == "" { - return nil, nil, nil - } - datacenters, response, err := c.List(ctx, DatacenterListOpts{Name: name}) - if len(datacenters) == 0 { - return nil, response, err - } - return datacenters[0], response, err -} - -// Get retrieves a datacenter by its ID if the input can be parsed as an integer, otherwise it -// retrieves a datacenter by its name. If the datacenter does not exist, nil is returned. -func (c *DatacenterClient) Get(ctx context.Context, idOrName string) (*Datacenter, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// DatacenterListOpts specifies options for listing datacenters. -type DatacenterListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l DatacenterListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of datacenters for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *DatacenterClient) List(ctx context.Context, opts DatacenterListOpts) ([]*Datacenter, *Response, error) { - path := "/datacenters?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.DatacenterListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - datacenters := make([]*Datacenter, 0, len(body.Datacenters)) - for _, i := range body.Datacenters { - datacenters = append(datacenters, DatacenterFromSchema(i)) - } - return datacenters, resp, nil -} - -// All returns all datacenters. -func (c *DatacenterClient) All(ctx context.Context) ([]*Datacenter, error) { - allDatacenters := []*Datacenter{} - - opts := DatacenterListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - datacenters, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allDatacenters = append(allDatacenters, datacenters...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allDatacenters, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/error.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/error.go deleted file mode 100644 index ff04d07b2..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/error.go +++ /dev/null @@ -1,126 +0,0 @@ -package hcloud - -import ( - "fmt" - "net" -) - -// ErrorCode represents an error code returned from the API. -type ErrorCode string - -// Error codes returned from the API. -const ( - ErrorCodeServiceError ErrorCode = "service_error" // Generic service error - ErrorCodeRateLimitExceeded ErrorCode = "rate_limit_exceeded" // Rate limit exceeded - ErrorCodeUnknownError ErrorCode = "unknown_error" // Unknown error - ErrorCodeNotFound ErrorCode = "not_found" // Resource not found - ErrorCodeInvalidInput ErrorCode = "invalid_input" // Validation error - ErrorCodeForbidden ErrorCode = "forbidden" // Insufficient permissions - ErrorCodeJSONError ErrorCode = "json_error" // Invalid JSON in request - ErrorCodeLocked ErrorCode = "locked" // Item is locked (Another action is running) - ErrorCodeResourceLimitExceeded ErrorCode = "resource_limit_exceeded" // Resource limit exceeded - ErrorCodeResourceUnavailable ErrorCode = "resource_unavailable" // Resource currently unavailable - ErrorCodeUniquenessError ErrorCode = "uniqueness_error" // One or more fields must be unique - ErrorCodeProtected ErrorCode = "protected" // The actions you are trying is protected - ErrorCodeMaintenance ErrorCode = "maintenance" // Cannot perform operation due to maintenance - ErrorCodeConflict ErrorCode = "conflict" // The resource has changed during the request, please retry - ErrorCodeRobotUnavailable ErrorCode = "robot_unavailable" // Robot was not available. The caller may retry the operation after a short delay - ErrorCodeResourceLocked ErrorCode = "resource_locked" // The resource is locked. The caller should contact support - ErrorUnsupportedError ErrorCode = "unsupported_error" // The given resource does not support this - - // Server related error codes. - ErrorCodeInvalidServerType ErrorCode = "invalid_server_type" // The server type does not fit for the given server or is deprecated - ErrorCodeServerNotStopped ErrorCode = "server_not_stopped" // The action requires a stopped server - ErrorCodeNetworksOverlap ErrorCode = "networks_overlap" // The network IP range overlaps with one of the server networks - ErrorCodePlacementError ErrorCode = "placement_error" // An error during the placement occurred - ErrorCodeServerAlreadyAttached ErrorCode = "server_already_attached" // The server is already attached to the resource - - // Load Balancer related error codes. - ErrorCodeIPNotOwned ErrorCode = "ip_not_owned" // The IP you are trying to add as a target is not owned by the Project owner - ErrorCodeSourcePortAlreadyUsed ErrorCode = "source_port_already_used" // The source port you are trying to add is already in use - ErrorCodeCloudResourceIPNotAllowed ErrorCode = "cloud_resource_ip_not_allowed" // The IP you are trying to add as a target belongs to a Hetzner Cloud resource - ErrorCodeServerNotAttachedToNetwork ErrorCode = "server_not_attached_to_network" // The server you are trying to add as a target is not attached to the same network as the Load Balancer - ErrorCodeTargetAlreadyDefined ErrorCode = "target_already_defined" // The Load Balancer target you are trying to define is already defined - ErrorCodeInvalidLoadBalancerType ErrorCode = "invalid_load_balancer_type" // The Load Balancer type does not fit for the given Load Balancer - ErrorCodeLoadBalancerAlreadyAttached ErrorCode = "load_balancer_already_attached" // The Load Balancer is already attached to a network - ErrorCodeTargetsWithoutUsePrivateIP ErrorCode = "targets_without_use_private_ip" // The Load Balancer has targets that use the public IP instead of the private IP - ErrorCodeLoadBalancerNotAttachedToNetwork ErrorCode = "load_balancer_not_attached_to_network" // The Load Balancer is not attached to a network - - // Network related error codes. - ErrorCodeIPNotAvailable ErrorCode = "ip_not_available" // The provided Network IP is not available - ErrorCodeNoSubnetAvailable ErrorCode = "no_subnet_available" // No Subnet or IP is available for the Load Balancer/Server within the network - ErrorCodeVSwitchAlreadyUsed ErrorCode = "vswitch_id_already_used" // The given Robot vSwitch ID is already registered in another network - - // Volume related error codes. - ErrorCodeNoSpaceLeftInLocation ErrorCode = "no_space_left_in_location" // There is no volume space left in the given location - ErrorCodeVolumeAlreadyAttached ErrorCode = "volume_already_attached" // Volume is already attached to a server, detach first - - // Firewall related error codes. - ErrorCodeFirewallAlreadyApplied ErrorCode = "firewall_already_applied" // Firewall was already applied on resource - ErrorCodeFirewallAlreadyRemoved ErrorCode = "firewall_already_removed" // Firewall was already removed from the resource - ErrorCodeIncompatibleNetworkType ErrorCode = "incompatible_network_type" // The Network type is incompatible for the given resource - ErrorCodeResourceInUse ErrorCode = "resource_in_use" // Firewall must not be in use to be deleted - ErrorCodeServerAlreadyAdded ErrorCode = "server_already_added" // Server added more than one time to resource - ErrorCodeFirewallResourceNotFound ErrorCode = "firewall_resource_not_found" // Resource a firewall should be attached to / detached from not found - - // Certificate related error codes. - ErrorCodeCAARecordDoesNotAllowCA ErrorCode = "caa_record_does_not_allow_ca" // CAA record does not allow certificate authority - ErrorCodeCADNSValidationFailed ErrorCode = "ca_dns_validation_failed" // Certificate Authority: DNS validation failed - ErrorCodeCATooManyAuthorizationsFailedRecently ErrorCode = "ca_too_many_authorizations_failed_recently" // Certificate Authority: Too many authorizations failed recently - ErrorCodeCATooManyCertificatedIssuedForRegisteredDomain ErrorCode = "ca_too_many_certificates_issued_for_registered_domain" // Certificate Authority: Too many certificates issued for registered domain - ErrorCodeCATooManyDuplicateCertificates ErrorCode = "ca_too_many_duplicate_certificates" // Certificate Authority: Too many duplicate certificates - ErrorCodeCloudNotVerifyDomainDelegatedToZone ErrorCode = "could_not_verify_domain_delegated_to_zone" // Could not verify domain delegated to zone - ErrorCodeDNSZoneNotFound ErrorCode = "dns_zone_not_found" // DNS zone not found - - // Deprecated error codes - // The actual value of this error code is limit_reached. The new error code - // rate_limit_exceeded for ratelimiting was introduced before Hetzner Cloud - // launched into the public. To make clients using the old error code still - // work as expected, we set the value of the old error code to that of the - // new error code. - ErrorCodeLimitReached = ErrorCodeRateLimitExceeded -) - -// Error is an error returned from the API. -type Error struct { - Code ErrorCode - Message string - Details interface{} -} - -func (e Error) Error() string { - return fmt.Sprintf("%s (%s)", e.Message, e.Code) -} - -// ErrorDetailsInvalidInput contains the details of an 'invalid_input' error. -type ErrorDetailsInvalidInput struct { - Fields []ErrorDetailsInvalidInputField -} - -// ErrorDetailsInvalidInputField contains the validation errors reported on a field. -type ErrorDetailsInvalidInputField struct { - Name string - Messages []string -} - -// IsError returns whether err is an API error with the given error code. -func IsError(err error, code ErrorCode) bool { - apiErr, ok := err.(Error) - return ok && apiErr.Code == code -} - -type InvalidIPError struct { - IP string -} - -func (e InvalidIPError) Error() string { - return fmt.Sprintf("could not parse ip address %s", e.IP) -} - -type DNSNotFoundError struct { - IP net.IP -} - -func (e DNSNotFoundError) Error() string { - return fmt.Sprintf("dns for ip %s not found", e.IP.String()) -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/firewall.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/firewall.go deleted file mode 100644 index 514f23a4d..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/firewall.go +++ /dev/null @@ -1,388 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Firewall represents a Firewall in the Hetzner Cloud. -type Firewall struct { - ID int - Name string - Labels map[string]string - Created time.Time - Rules []FirewallRule - AppliedTo []FirewallResource -} - -// FirewallRule represents a Firewall's rules. -type FirewallRule struct { - Direction FirewallRuleDirection - SourceIPs []net.IPNet - DestinationIPs []net.IPNet - Protocol FirewallRuleProtocol - Port *string - Description *string -} - -// FirewallRuleDirection specifies the direction of a Firewall rule. -type FirewallRuleDirection string - -const ( - // FirewallRuleDirectionIn specifies a rule for inbound traffic. - FirewallRuleDirectionIn FirewallRuleDirection = "in" - - // FirewallRuleDirectionOut specifies a rule for outbound traffic. - FirewallRuleDirectionOut FirewallRuleDirection = "out" -) - -// FirewallRuleProtocol specifies the protocol of a Firewall rule. -type FirewallRuleProtocol string - -const ( - // FirewallRuleProtocolTCP specifies a TCP rule. - FirewallRuleProtocolTCP FirewallRuleProtocol = "tcp" - // FirewallRuleProtocolUDP specifies a UDP rule. - FirewallRuleProtocolUDP FirewallRuleProtocol = "udp" - // FirewallRuleProtocolICMP specifies an ICMP rule. - FirewallRuleProtocolICMP FirewallRuleProtocol = "icmp" - // FirewallRuleProtocolESP specifies an esp rule. - FirewallRuleProtocolESP FirewallRuleProtocol = "esp" - // FirewallRuleProtocolGRE specifies an gre rule. - FirewallRuleProtocolGRE FirewallRuleProtocol = "gre" -) - -// FirewallResourceType specifies the resource to apply a Firewall on. -type FirewallResourceType string - -const ( - // FirewallResourceTypeServer specifies a Server. - FirewallResourceTypeServer FirewallResourceType = "server" - // FirewallResourceTypeLabelSelector specifies a LabelSelector. - FirewallResourceTypeLabelSelector FirewallResourceType = "label_selector" -) - -// FirewallResource represents a resource to apply the new Firewall on. -type FirewallResource struct { - Type FirewallResourceType - Server *FirewallResourceServer - LabelSelector *FirewallResourceLabelSelector -} - -// FirewallResourceServer represents a Server to apply a Firewall on. -type FirewallResourceServer struct { - ID int -} - -// FirewallResourceLabelSelector represents a LabelSelector to apply a Firewall on. -type FirewallResourceLabelSelector struct { - Selector string -} - -// FirewallClient is a client for the Firewalls API. -type FirewallClient struct { - client *Client -} - -// GetByID retrieves a Firewall by its ID. If the Firewall does not exist, nil is returned. -func (c *FirewallClient) GetByID(ctx context.Context, id int) (*Firewall, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/firewalls/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.FirewallGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return FirewallFromSchema(body.Firewall), resp, nil -} - -// GetByName retrieves a Firewall by its name. If the Firewall does not exist, nil is returned. -func (c *FirewallClient) GetByName(ctx context.Context, name string) (*Firewall, *Response, error) { - if name == "" { - return nil, nil, nil - } - firewalls, response, err := c.List(ctx, FirewallListOpts{Name: name}) - if len(firewalls) == 0 { - return nil, response, err - } - return firewalls[0], response, err -} - -// Get retrieves a Firewall by its ID if the input can be parsed as an integer, otherwise it -// retrieves a Firewall by its name. If the Firewall does not exist, nil is returned. -func (c *FirewallClient) Get(ctx context.Context, idOrName string) (*Firewall, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// FirewallListOpts specifies options for listing Firewalls. -type FirewallListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l FirewallListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of Firewalls for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *FirewallClient) List(ctx context.Context, opts FirewallListOpts) ([]*Firewall, *Response, error) { - path := "/firewalls?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.FirewallListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - firewalls := make([]*Firewall, 0, len(body.Firewalls)) - for _, s := range body.Firewalls { - firewalls = append(firewalls, FirewallFromSchema(s)) - } - return firewalls, resp, nil -} - -// All returns all Firewalls. -func (c *FirewallClient) All(ctx context.Context) ([]*Firewall, error) { - allFirewalls := []*Firewall{} - - opts := FirewallListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - firewalls, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allFirewalls = append(allFirewalls, firewalls...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allFirewalls, nil -} - -// AllWithOpts returns all Firewalls for the given options. -func (c *FirewallClient) AllWithOpts(ctx context.Context, opts FirewallListOpts) ([]*Firewall, error) { - var allFirewalls []*Firewall - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - firewalls, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allFirewalls = append(allFirewalls, firewalls...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allFirewalls, nil -} - -// FirewallCreateOpts specifies options for creating a new Firewall. -type FirewallCreateOpts struct { - Name string - Labels map[string]string - Rules []FirewallRule - ApplyTo []FirewallResource -} - -// Validate checks if options are valid. -func (o FirewallCreateOpts) Validate() error { - if o.Name == "" { - return errors.New("missing name") - } - return nil -} - -// FirewallCreateResult is the result of a create Firewall call. -type FirewallCreateResult struct { - Firewall *Firewall - Actions []*Action -} - -// Create creates a new Firewall. -func (c *FirewallClient) Create(ctx context.Context, opts FirewallCreateOpts) (FirewallCreateResult, *Response, error) { - if err := opts.Validate(); err != nil { - return FirewallCreateResult{}, nil, err - } - reqBody := firewallCreateOptsToSchema(opts) - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return FirewallCreateResult{}, nil, err - } - req, err := c.client.NewRequest(ctx, "POST", "/firewalls", bytes.NewReader(reqBodyData)) - if err != nil { - return FirewallCreateResult{}, nil, err - } - - respBody := schema.FirewallCreateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return FirewallCreateResult{}, resp, err - } - result := FirewallCreateResult{ - Firewall: FirewallFromSchema(respBody.Firewall), - Actions: ActionsFromSchema(respBody.Actions), - } - return result, resp, nil -} - -// FirewallUpdateOpts specifies options for updating a Firewall. -type FirewallUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a Firewall. -func (c *FirewallClient) Update(ctx context.Context, firewall *Firewall, opts FirewallUpdateOpts) (*Firewall, *Response, error) { - reqBody := schema.FirewallUpdateRequest{} - if opts.Name != "" { - reqBody.Name = &opts.Name - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/firewalls/%d", firewall.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.FirewallUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return FirewallFromSchema(respBody.Firewall), resp, nil -} - -// Delete deletes a Firewall. -func (c *FirewallClient) Delete(ctx context.Context, firewall *Firewall) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/firewalls/%d", firewall.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// FirewallSetRulesOpts specifies options for setting rules of a Firewall. -type FirewallSetRulesOpts struct { - Rules []FirewallRule -} - -// SetRules sets the rules of a Firewall. -func (c *FirewallClient) SetRules(ctx context.Context, firewall *Firewall, opts FirewallSetRulesOpts) ([]*Action, *Response, error) { - reqBody := firewallSetRulesOptsToSchema(opts) - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/firewalls/%d/actions/set_rules", firewall.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.FirewallActionSetRulesResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionsFromSchema(respBody.Actions), resp, nil -} - -func (c *FirewallClient) ApplyResources(ctx context.Context, firewall *Firewall, resources []FirewallResource) ([]*Action, *Response, error) { - applyTo := make([]schema.FirewallResource, len(resources)) - for i, r := range resources { - applyTo[i] = firewallResourceToSchema(r) - } - - reqBody := schema.FirewallActionApplyToResourcesRequest{ApplyTo: applyTo} - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/firewalls/%d/actions/apply_to_resources", firewall.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.FirewallActionApplyToResourcesResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionsFromSchema(respBody.Actions), resp, nil -} - -func (c *FirewallClient) RemoveResources(ctx context.Context, firewall *Firewall, resources []FirewallResource) ([]*Action, *Response, error) { - removeFrom := make([]schema.FirewallResource, len(resources)) - for i, r := range resources { - removeFrom[i] = firewallResourceToSchema(r) - } - - reqBody := schema.FirewallActionRemoveFromResourcesRequest{RemoveFrom: removeFrom} - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/firewalls/%d/actions/remove_from_resources", firewall.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.FirewallActionRemoveFromResourcesResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionsFromSchema(respBody.Actions), resp, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/floating_ip.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/floating_ip.go deleted file mode 100644 index e2643a638..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/floating_ip.go +++ /dev/null @@ -1,404 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// FloatingIP represents a Floating IP in the Hetzner Cloud. -type FloatingIP struct { - ID int - Description string - Created time.Time - IP net.IP - Network *net.IPNet - Type FloatingIPType - Server *Server - DNSPtr map[string]string - HomeLocation *Location - Blocked bool - Protection FloatingIPProtection - Labels map[string]string - Name string -} - -// DNSPtrForIP returns the reverse DNS pointer of the IP address. -// Deprecated: Use GetDNSPtrForIP instead. -func (f *FloatingIP) DNSPtrForIP(ip net.IP) string { - return f.DNSPtr[ip.String()] -} - -// FloatingIPProtection represents the protection level of a Floating IP. -type FloatingIPProtection struct { - Delete bool -} - -// FloatingIPType represents the type of a Floating IP. -type FloatingIPType string - -// Floating IP types. -const ( - FloatingIPTypeIPv4 FloatingIPType = "ipv4" - FloatingIPTypeIPv6 FloatingIPType = "ipv6" -) - -// changeDNSPtr changes or resets the reverse DNS pointer for a IP address. -// Pass a nil ptr to reset the reverse DNS pointer to its default value. -func (f *FloatingIP) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { - reqBody := schema.FloatingIPActionChangeDNSPtrRequest{ - IP: ip.String(), - DNSPtr: ptr, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/floating_ips/%d/actions/change_dns_ptr", f.ID) - req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.FloatingIPActionChangeDNSPtrResponse{} - resp, err := client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// GetDNSPtrForIP searches for the dns assigned to the given IP address. -// It returns an error if there is no dns set for the given IP address. -func (f *FloatingIP) GetDNSPtrForIP(ip net.IP) (string, error) { - dns, ok := f.DNSPtr[ip.String()] - if !ok { - return "", DNSNotFoundError{ip} - } - - return dns, nil -} - -// FloatingIPClient is a client for the Floating IP API. -type FloatingIPClient struct { - client *Client -} - -// GetByID retrieves a Floating IP by its ID. If the Floating IP does not exist, -// nil is returned. -func (c *FloatingIPClient) GetByID(ctx context.Context, id int) (*FloatingIP, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/floating_ips/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.FloatingIPGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, resp, err - } - return FloatingIPFromSchema(body.FloatingIP), resp, nil -} - -// GetByName retrieves a Floating IP by its name. If the Floating IP does not exist, nil is returned. -func (c *FloatingIPClient) GetByName(ctx context.Context, name string) (*FloatingIP, *Response, error) { - if name == "" { - return nil, nil, nil - } - floatingIPs, response, err := c.List(ctx, FloatingIPListOpts{Name: name}) - if len(floatingIPs) == 0 { - return nil, response, err - } - return floatingIPs[0], response, err -} - -// Get retrieves a Floating IP by its ID if the input can be parsed as an integer, otherwise it -// retrieves a Floating IP by its name. If the Floating IP does not exist, nil is returned. -func (c *FloatingIPClient) Get(ctx context.Context, idOrName string) (*FloatingIP, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// FloatingIPListOpts specifies options for listing Floating IPs. -type FloatingIPListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l FloatingIPListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of Floating IPs for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *FloatingIPClient) List(ctx context.Context, opts FloatingIPListOpts) ([]*FloatingIP, *Response, error) { - path := "/floating_ips?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.FloatingIPListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - floatingIPs := make([]*FloatingIP, 0, len(body.FloatingIPs)) - for _, s := range body.FloatingIPs { - floatingIPs = append(floatingIPs, FloatingIPFromSchema(s)) - } - return floatingIPs, resp, nil -} - -// All returns all Floating IPs. -func (c *FloatingIPClient) All(ctx context.Context) ([]*FloatingIP, error) { - return c.AllWithOpts(ctx, FloatingIPListOpts{ListOpts: ListOpts{PerPage: 50}}) -} - -// AllWithOpts returns all Floating IPs for the given options. -func (c *FloatingIPClient) AllWithOpts(ctx context.Context, opts FloatingIPListOpts) ([]*FloatingIP, error) { - allFloatingIPs := []*FloatingIP{} - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - floatingIPs, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allFloatingIPs = append(allFloatingIPs, floatingIPs...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allFloatingIPs, nil -} - -// FloatingIPCreateOpts specifies options for creating a Floating IP. -type FloatingIPCreateOpts struct { - Type FloatingIPType - HomeLocation *Location - Server *Server - Description *string - Name *string - Labels map[string]string -} - -// Validate checks if options are valid. -func (o FloatingIPCreateOpts) Validate() error { - switch o.Type { - case FloatingIPTypeIPv4, FloatingIPTypeIPv6: - break - default: - return errors.New("missing or invalid type") - } - if o.HomeLocation == nil && o.Server == nil { - return errors.New("one of home location or server is required") - } - return nil -} - -// FloatingIPCreateResult is the result of creating a Floating IP. -type FloatingIPCreateResult struct { - FloatingIP *FloatingIP - Action *Action -} - -// Create creates a Floating IP. -func (c *FloatingIPClient) Create(ctx context.Context, opts FloatingIPCreateOpts) (FloatingIPCreateResult, *Response, error) { - if err := opts.Validate(); err != nil { - return FloatingIPCreateResult{}, nil, err - } - - reqBody := schema.FloatingIPCreateRequest{ - Type: string(opts.Type), - Description: opts.Description, - Name: opts.Name, - } - if opts.HomeLocation != nil { - reqBody.HomeLocation = Ptr(opts.HomeLocation.Name) - } - if opts.Server != nil { - reqBody.Server = Ptr(opts.Server.ID) - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return FloatingIPCreateResult{}, nil, err - } - - req, err := c.client.NewRequest(ctx, "POST", "/floating_ips", bytes.NewReader(reqBodyData)) - if err != nil { - return FloatingIPCreateResult{}, nil, err - } - - var respBody schema.FloatingIPCreateResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return FloatingIPCreateResult{}, resp, err - } - var action *Action - if respBody.Action != nil { - action = ActionFromSchema(*respBody.Action) - } - return FloatingIPCreateResult{ - FloatingIP: FloatingIPFromSchema(respBody.FloatingIP), - Action: action, - }, resp, nil -} - -// Delete deletes a Floating IP. -func (c *FloatingIPClient) Delete(ctx context.Context, floatingIP *FloatingIP) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/floating_ips/%d", floatingIP.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// FloatingIPUpdateOpts specifies options for updating a Floating IP. -type FloatingIPUpdateOpts struct { - Description string - Labels map[string]string - Name string -} - -// Update updates a Floating IP. -func (c *FloatingIPClient) Update(ctx context.Context, floatingIP *FloatingIP, opts FloatingIPUpdateOpts) (*FloatingIP, *Response, error) { - reqBody := schema.FloatingIPUpdateRequest{ - Description: opts.Description, - Name: opts.Name, - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/floating_ips/%d", floatingIP.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.FloatingIPUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return FloatingIPFromSchema(respBody.FloatingIP), resp, nil -} - -// Assign assigns a Floating IP to a server. -func (c *FloatingIPClient) Assign(ctx context.Context, floatingIP *FloatingIP, server *Server) (*Action, *Response, error) { - reqBody := schema.FloatingIPActionAssignRequest{ - Server: server.ID, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/floating_ips/%d/actions/assign", floatingIP.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.FloatingIPActionAssignResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// Unassign unassigns a Floating IP from the currently assigned server. -func (c *FloatingIPClient) Unassign(ctx context.Context, floatingIP *FloatingIP) (*Action, *Response, error) { - var reqBody schema.FloatingIPActionUnassignRequest - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/floating_ips/%d/actions/unassign", floatingIP.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.FloatingIPActionUnassignResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// ChangeDNSPtr changes or resets the reverse DNS pointer for a Floating IP address. -// Pass a nil ptr to reset the reverse DNS pointer to its default value. -func (c *FloatingIPClient) ChangeDNSPtr(ctx context.Context, floatingIP *FloatingIP, ip string, ptr *string) (*Action, *Response, error) { - netIP := net.ParseIP(ip) - if netIP == nil { - return nil, nil, InvalidIPError{ip} - } - return floatingIP.changeDNSPtr(ctx, c.client, net.ParseIP(ip), ptr) -} - -// FloatingIPChangeProtectionOpts specifies options for changing the resource protection level of a Floating IP. -type FloatingIPChangeProtectionOpts struct { - Delete *bool -} - -// ChangeProtection changes the resource protection level of a Floating IP. -func (c *FloatingIPClient) ChangeProtection(ctx context.Context, floatingIP *FloatingIP, opts FloatingIPChangeProtectionOpts) (*Action, *Response, error) { - reqBody := schema.FloatingIPActionChangeProtectionRequest{ - Delete: opts.Delete, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/floating_ips/%d/actions/change_protection", floatingIP.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.FloatingIPActionChangeProtectionResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/hcloud.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/hcloud.go deleted file mode 100644 index 7adc8745a..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/hcloud.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package hcloud is a library for the Hetzner Cloud API. -package hcloud - -// Version is the library's version following Semantic Versioning. -const Version = "1.42.0" // x-release-please-version diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/image.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/image.go deleted file mode 100644 index 04d61b50c..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/image.go +++ /dev/null @@ -1,312 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Image represents an Image in the Hetzner Cloud. -type Image struct { - ID int - Name string - Type ImageType - Status ImageStatus - Description string - ImageSize float32 - DiskSize float32 - Created time.Time - CreatedFrom *Server - BoundTo *Server - RapidDeploy bool - - OSFlavor string - OSVersion string - Architecture Architecture - - Protection ImageProtection - Deprecated time.Time // The zero value denotes the image is not deprecated. - Labels map[string]string - Deleted time.Time -} - -// IsDeprecated returns whether the image is deprecated. -func (image *Image) IsDeprecated() bool { - return !image.Deprecated.IsZero() -} - -// IsDeleted returns whether the image is deleted. -func (image *Image) IsDeleted() bool { - return !image.Deleted.IsZero() -} - -// ImageProtection represents the protection level of an image. -type ImageProtection struct { - Delete bool -} - -// ImageType specifies the type of an image. -type ImageType string - -const ( - // ImageTypeSnapshot represents a snapshot image. - ImageTypeSnapshot ImageType = "snapshot" - // ImageTypeBackup represents a backup image. - ImageTypeBackup ImageType = "backup" - // ImageTypeSystem represents a system image. - ImageTypeSystem ImageType = "system" - // ImageTypeApp represents a one click app image. - ImageTypeApp ImageType = "app" -) - -// ImageStatus specifies the status of an image. -type ImageStatus string - -const ( - // ImageStatusCreating is the status when an image is being created. - ImageStatusCreating ImageStatus = "creating" - // ImageStatusAvailable is the status when an image is available. - ImageStatusAvailable ImageStatus = "available" -) - -// ImageClient is a client for the image API. -type ImageClient struct { - client *Client -} - -// GetByID retrieves an image by its ID. If the image does not exist, nil is returned. -func (c *ImageClient) GetByID(ctx context.Context, id int) (*Image, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/images/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.ImageGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return ImageFromSchema(body.Image), resp, nil -} - -// GetByName retrieves an image by its name. If the image does not exist, nil is returned. -// -// Deprecated: Use [ImageClient.GetByNameAndArchitecture] instead. -func (c *ImageClient) GetByName(ctx context.Context, name string) (*Image, *Response, error) { - if name == "" { - return nil, nil, nil - } - images, response, err := c.List(ctx, ImageListOpts{Name: name}) - if len(images) == 0 { - return nil, response, err - } - return images[0], response, err -} - -// GetByNameAndArchitecture retrieves an image by its name and architecture. If the image does not exist, -// nil is returned. -// In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should -// check for this in your calling method. -func (c *ImageClient) GetByNameAndArchitecture(ctx context.Context, name string, architecture Architecture) (*Image, *Response, error) { - if name == "" { - return nil, nil, nil - } - images, response, err := c.List(ctx, ImageListOpts{Name: name, Architecture: []Architecture{architecture}, IncludeDeprecated: true}) - if len(images) == 0 { - return nil, response, err - } - return images[0], response, err -} - -// Get retrieves an image by its ID if the input can be parsed as an integer, otherwise it -// retrieves an image by its name. If the image does not exist, nil is returned. -// -// Deprecated: Use [ImageClient.GetForArchitecture] instead. -func (c *ImageClient) Get(ctx context.Context, idOrName string) (*Image, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, id) - } - return c.GetByName(ctx, idOrName) -} - -// GetForArchitecture retrieves an image by its ID if the input can be parsed as an integer, otherwise it -// retrieves an image by its name and architecture. If the image does not exist, nil is returned. -// -// In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should -// check for this in your calling method. -func (c *ImageClient) GetForArchitecture(ctx context.Context, idOrName string, architecture Architecture) (*Image, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, id) - } - return c.GetByNameAndArchitecture(ctx, idOrName, architecture) -} - -// ImageListOpts specifies options for listing images. -type ImageListOpts struct { - ListOpts - Type []ImageType - BoundTo *Server - Name string - Sort []string - Status []ImageStatus - IncludeDeprecated bool - Architecture []Architecture -} - -func (l ImageListOpts) values() url.Values { - vals := l.ListOpts.values() - for _, typ := range l.Type { - vals.Add("type", string(typ)) - } - if l.BoundTo != nil { - vals.Add("bound_to", strconv.Itoa(l.BoundTo.ID)) - } - if l.Name != "" { - vals.Add("name", l.Name) - } - if l.IncludeDeprecated { - vals.Add("include_deprecated", strconv.FormatBool(l.IncludeDeprecated)) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - for _, status := range l.Status { - vals.Add("status", string(status)) - } - for _, arch := range l.Architecture { - vals.Add("architecture", string(arch)) - } - return vals -} - -// List returns a list of images for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *ImageClient) List(ctx context.Context, opts ImageListOpts) ([]*Image, *Response, error) { - path := "/images?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.ImageListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - images := make([]*Image, 0, len(body.Images)) - for _, i := range body.Images { - images = append(images, ImageFromSchema(i)) - } - return images, resp, nil -} - -// All returns all images. -func (c *ImageClient) All(ctx context.Context) ([]*Image, error) { - return c.AllWithOpts(ctx, ImageListOpts{ListOpts: ListOpts{PerPage: 50}}) -} - -// AllWithOpts returns all images for the given options. -func (c *ImageClient) AllWithOpts(ctx context.Context, opts ImageListOpts) ([]*Image, error) { - allImages := []*Image{} - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - images, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allImages = append(allImages, images...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allImages, nil -} - -// Delete deletes an image. -func (c *ImageClient) Delete(ctx context.Context, image *Image) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/images/%d", image.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// ImageUpdateOpts specifies options for updating an image. -type ImageUpdateOpts struct { - Description *string - Type ImageType - Labels map[string]string -} - -// Update updates an image. -func (c *ImageClient) Update(ctx context.Context, image *Image, opts ImageUpdateOpts) (*Image, *Response, error) { - reqBody := schema.ImageUpdateRequest{ - Description: opts.Description, - } - if opts.Type != "" { - reqBody.Type = Ptr(string(opts.Type)) - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/images/%d", image.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ImageUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ImageFromSchema(respBody.Image), resp, nil -} - -// ImageChangeProtectionOpts specifies options for changing the resource protection level of an image. -type ImageChangeProtectionOpts struct { - Delete *bool -} - -// ChangeProtection changes the resource protection level of an image. -func (c *ImageClient) ChangeProtection(ctx context.Context, image *Image, opts ImageChangeProtectionOpts) (*Action, *Response, error) { - reqBody := schema.ImageActionChangeProtectionRequest{ - Delete: opts.Delete, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/images/%d/actions/change_protection", image.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ImageActionChangeProtectionResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/internal/instrumentation/metrics.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/internal/instrumentation/metrics.go deleted file mode 100644 index 69a7165ba..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/internal/instrumentation/metrics.go +++ /dev/null @@ -1,89 +0,0 @@ -package instrumentation - -import ( - "fmt" - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -type Instrumenter struct { - subsystemIdentifier string // will be used as part of the metric name (hcloud__requests_total) - instrumentationRegistry *prometheus.Registry -} - -// New creates a new Instrumenter. The subsystemIdentifier will be used as part of the metric names (e.g. hcloud__requests_total). -func New(subsystemIdentifier string, instrumentationRegistry *prometheus.Registry) *Instrumenter { - return &Instrumenter{subsystemIdentifier: subsystemIdentifier, instrumentationRegistry: instrumentationRegistry} -} - -// InstrumentedRoundTripper returns an instrumented round tripper. -func (i *Instrumenter) InstrumentedRoundTripper() http.RoundTripper { - inFlightRequestsGauge := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: fmt.Sprintf("hcloud_%s_in_flight_requests", i.subsystemIdentifier), - Help: fmt.Sprintf("A gauge of in-flight requests to the hcloud %s.", i.subsystemIdentifier), - }) - - requestsPerEndpointCounter := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: fmt.Sprintf("hcloud_%s_requests_total", i.subsystemIdentifier), - Help: fmt.Sprintf("A counter for requests to the hcloud %s per endpoint.", i.subsystemIdentifier), - }, - []string{"code", "method", "api_endpoint"}, - ) - - requestLatencyHistogram := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: fmt.Sprintf("hcloud_%s_request_duration_seconds", i.subsystemIdentifier), - Help: fmt.Sprintf("A histogram of request latencies to the hcloud %s .", i.subsystemIdentifier), - Buckets: prometheus.DefBuckets, - }, - []string{"method"}, - ) - - i.instrumentationRegistry.MustRegister(requestsPerEndpointCounter, requestLatencyHistogram, inFlightRequestsGauge) - - return promhttp.InstrumentRoundTripperInFlight(inFlightRequestsGauge, - promhttp.InstrumentRoundTripperDuration(requestLatencyHistogram, - i.instrumentRoundTripperEndpoint(requestsPerEndpointCounter, - http.DefaultTransport, - ), - ), - ) -} - -// instrumentRoundTripperEndpoint implements a hcloud specific round tripper to count requests per API endpoint -// numeric IDs are removed from the URI Path. -// -// Sample: -// -// /volumes/1234/actions/attach --> /volumes/actions/attach -func (i *Instrumenter) instrumentRoundTripperEndpoint(counter *prometheus.CounterVec, next http.RoundTripper) promhttp.RoundTripperFunc { - return func(r *http.Request) (*http.Response, error) { - resp, err := next.RoundTrip(r) - if err == nil { - statusCode := strconv.Itoa(resp.StatusCode) - counter.WithLabelValues(statusCode, strings.ToLower(resp.Request.Method), preparePathForLabel(resp.Request.URL.Path)).Inc() - } - - return resp, err - } -} - -func preparePathForLabel(path string) string { - path = strings.ToLower(path) - - // replace all numbers and chars that are not a-z, / or _ - reg := regexp.MustCompile("[^a-z/_]+") - path = reg.ReplaceAllString(path, "") - - // replace all artifacts of number replacement (//) - path = strings.ReplaceAll(path, "//", "/") - - // replace the /v/ that indicated the API version - return strings.Replace(path, "/v/", "/", 1) -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/iso.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/iso.go deleted file mode 100644 index d5814cb80..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/iso.go +++ /dev/null @@ -1,156 +0,0 @@ -package hcloud - -import ( - "context" - "fmt" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// ISO represents an ISO image in the Hetzner Cloud. -type ISO struct { - ID int - Name string - Description string - Type ISOType - Architecture *Architecture - Deprecated time.Time -} - -// IsDeprecated returns true if the ISO is deprecated. -func (iso *ISO) IsDeprecated() bool { - return !iso.Deprecated.IsZero() -} - -// ISOType specifies the type of an ISO image. -type ISOType string - -const ( - // ISOTypePublic is the type of a public ISO image. - ISOTypePublic ISOType = "public" - - // ISOTypePrivate is the type of a private ISO image. - ISOTypePrivate ISOType = "private" -) - -// ISOClient is a client for the ISO API. -type ISOClient struct { - client *Client -} - -// GetByID retrieves an ISO by its ID. -func (c *ISOClient) GetByID(ctx context.Context, id int) (*ISO, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/isos/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.ISOGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, resp, err - } - return ISOFromSchema(body.ISO), resp, nil -} - -// GetByName retrieves an ISO by its name. -func (c *ISOClient) GetByName(ctx context.Context, name string) (*ISO, *Response, error) { - if name == "" { - return nil, nil, nil - } - isos, response, err := c.List(ctx, ISOListOpts{Name: name}) - if len(isos) == 0 { - return nil, response, err - } - return isos[0], response, err -} - -// Get retrieves an ISO by its ID if the input can be parsed as an integer, otherwise it retrieves an ISO by its name. -func (c *ISOClient) Get(ctx context.Context, idOrName string) (*ISO, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// ISOListOpts specifies options for listing isos. -type ISOListOpts struct { - ListOpts - Name string - Sort []string - // Architecture filters the ISOs by Architecture. Note that custom ISOs do not have any architecture set, and you - // must use IncludeWildcardArchitecture to include them. - Architecture []Architecture - // IncludeWildcardArchitecture must be set to also return custom ISOs that have no architecture set, if you are - // also setting the Architecture field. - IncludeWildcardArchitecture bool -} - -func (l ISOListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - for _, arch := range l.Architecture { - vals.Add("architecture", string(arch)) - } - if l.IncludeWildcardArchitecture { - vals.Add("include_architecture_wildcard", "true") - } - return vals -} - -// List returns a list of ISOs for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *ISOClient) List(ctx context.Context, opts ISOListOpts) ([]*ISO, *Response, error) { - path := "/isos?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.ISOListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - isos := make([]*ISO, 0, len(body.ISOs)) - for _, i := range body.ISOs { - isos = append(isos, ISOFromSchema(i)) - } - return isos, resp, nil -} - -// All returns all ISOs. -func (c *ISOClient) All(ctx context.Context) ([]*ISO, error) { - allISOs := []*ISO{} - - opts := ISOListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - isos, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allISOs = append(allISOs, isos...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allISOs, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/load_balancer.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/load_balancer.go deleted file mode 100644 index 81e2e03bb..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/load_balancer.go +++ /dev/null @@ -1,1079 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "net" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// LoadBalancer represents a Load Balancer in the Hetzner Cloud. -type LoadBalancer struct { - ID int - Name string - PublicNet LoadBalancerPublicNet - PrivateNet []LoadBalancerPrivateNet - Location *Location - LoadBalancerType *LoadBalancerType - Algorithm LoadBalancerAlgorithm - Services []LoadBalancerService - Targets []LoadBalancerTarget - Protection LoadBalancerProtection - Labels map[string]string - Created time.Time - IncludedTraffic uint64 - OutgoingTraffic uint64 - IngoingTraffic uint64 -} - -// LoadBalancerPublicNet represents a Load Balancer's public network. -type LoadBalancerPublicNet struct { - Enabled bool - IPv4 LoadBalancerPublicNetIPv4 - IPv6 LoadBalancerPublicNetIPv6 -} - -// LoadBalancerPublicNetIPv4 represents a Load Balancer's public IPv4 address. -type LoadBalancerPublicNetIPv4 struct { - IP net.IP - DNSPtr string -} - -// LoadBalancerPublicNetIPv6 represents a Load Balancer's public IPv6 address. -type LoadBalancerPublicNetIPv6 struct { - IP net.IP - DNSPtr string -} - -// LoadBalancerPrivateNet represents a Load Balancer's private network. -type LoadBalancerPrivateNet struct { - Network *Network - IP net.IP -} - -// LoadBalancerService represents a Load Balancer service. -type LoadBalancerService struct { - Protocol LoadBalancerServiceProtocol - ListenPort int - DestinationPort int - Proxyprotocol bool - HTTP LoadBalancerServiceHTTP - HealthCheck LoadBalancerServiceHealthCheck -} - -// LoadBalancerServiceHTTP stores configuration for a service using the HTTP protocol. -type LoadBalancerServiceHTTP struct { - CookieName string - CookieLifetime time.Duration - Certificates []*Certificate - RedirectHTTP bool - StickySessions bool -} - -// LoadBalancerServiceHealthCheck stores configuration for a service health check. -type LoadBalancerServiceHealthCheck struct { - Protocol LoadBalancerServiceProtocol - Port int - Interval time.Duration - Timeout time.Duration - Retries int - HTTP *LoadBalancerServiceHealthCheckHTTP -} - -// LoadBalancerServiceHealthCheckHTTP stores configuration for a service health check -// using the HTTP protocol. -type LoadBalancerServiceHealthCheckHTTP struct { - Domain string - Path string - Response string - StatusCodes []string - TLS bool -} - -// LoadBalancerAlgorithmType specifies the algorithm type a Load Balancer -// uses for distributing requests. -type LoadBalancerAlgorithmType string - -const ( - // LoadBalancerAlgorithmTypeRoundRobin is an algorithm which distributes - // requests to targets in a round robin fashion. - LoadBalancerAlgorithmTypeRoundRobin LoadBalancerAlgorithmType = "round_robin" - // LoadBalancerAlgorithmTypeLeastConnections is an algorithm which distributes - // requests to targets with the least number of connections. - LoadBalancerAlgorithmTypeLeastConnections LoadBalancerAlgorithmType = "least_connections" -) - -// LoadBalancerAlgorithm configures the algorithm a Load Balancer uses -// for distributing requests. -type LoadBalancerAlgorithm struct { - Type LoadBalancerAlgorithmType -} - -// LoadBalancerTargetType specifies the type of a Load Balancer target. -type LoadBalancerTargetType string - -const ( - // LoadBalancerTargetTypeServer is a target type which points to a specific - // server. - LoadBalancerTargetTypeServer LoadBalancerTargetType = "server" - - // LoadBalancerTargetTypeLabelSelector is a target type which selects the - // servers a Load Balancer points to using labels assigned to the servers. - LoadBalancerTargetTypeLabelSelector LoadBalancerTargetType = "label_selector" - - // LoadBalancerTargetTypeIP is a target type which points to an IP. - LoadBalancerTargetTypeIP LoadBalancerTargetType = "ip" -) - -// LoadBalancerServiceProtocol specifies the protocol of a Load Balancer service. -type LoadBalancerServiceProtocol string - -const ( - // LoadBalancerServiceProtocolTCP specifies a TCP service. - LoadBalancerServiceProtocolTCP LoadBalancerServiceProtocol = "tcp" - // LoadBalancerServiceProtocolHTTP specifies an HTTP service. - LoadBalancerServiceProtocolHTTP LoadBalancerServiceProtocol = "http" - // LoadBalancerServiceProtocolHTTPS specifies an HTTPS service. - LoadBalancerServiceProtocolHTTPS LoadBalancerServiceProtocol = "https" -) - -// LoadBalancerTarget represents a Load Balancer target. -type LoadBalancerTarget struct { - Type LoadBalancerTargetType - Server *LoadBalancerTargetServer - LabelSelector *LoadBalancerTargetLabelSelector - IP *LoadBalancerTargetIP - HealthStatus []LoadBalancerTargetHealthStatus - Targets []LoadBalancerTarget - UsePrivateIP bool -} - -// LoadBalancerTargetServer configures a Load Balancer target -// pointing at a specific server. -type LoadBalancerTargetServer struct { - Server *Server -} - -// LoadBalancerTargetLabelSelector configures a Load Balancer target pointing -// at the servers matching the selector. This includes the target pointing at -// nothing, if no servers match the Selector. -type LoadBalancerTargetLabelSelector struct { - Selector string -} - -// LoadBalancerTargetIP configures a Load Balancer target pointing to a Hetzner -// Online IP address. -type LoadBalancerTargetIP struct { - IP string -} - -// LoadBalancerTargetHealthStatusStatus describes a target's health status. -type LoadBalancerTargetHealthStatusStatus string - -const ( - // LoadBalancerTargetHealthStatusStatusUnknown denotes that the health status is unknown. - LoadBalancerTargetHealthStatusStatusUnknown LoadBalancerTargetHealthStatusStatus = "unknown" - // LoadBalancerTargetHealthStatusStatusHealthy denotes a healthy target. - LoadBalancerTargetHealthStatusStatusHealthy LoadBalancerTargetHealthStatusStatus = "healthy" - // LoadBalancerTargetHealthStatusStatusUnhealthy denotes an unhealthy target. - LoadBalancerTargetHealthStatusStatusUnhealthy LoadBalancerTargetHealthStatusStatus = "unhealthy" -) - -// LoadBalancerTargetHealthStatus describes a target's health for a specific service. -type LoadBalancerTargetHealthStatus struct { - ListenPort int - Status LoadBalancerTargetHealthStatusStatus -} - -// LoadBalancerProtection represents the protection level of a Load Balancer. -type LoadBalancerProtection struct { - Delete bool -} - -// changeDNSPtr changes or resets the reverse DNS pointer for a IP address. -// Pass a nil ptr to reset the reverse DNS pointer to its default value. -func (lb *LoadBalancer) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionChangeDNSPtrRequest{ - IP: ip.String(), - DNSPtr: ptr, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/change_dns_ptr", lb.ID) - req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.LoadBalancerActionChangeDNSPtrResponse{} - resp, err := client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// GetDNSPtrForIP searches for the dns assigned to the given IP address. -// It returns an error if there is no dns set for the given IP address. -func (lb *LoadBalancer) GetDNSPtrForIP(ip net.IP) (string, error) { - if net.IP.Equal(lb.PublicNet.IPv4.IP, ip) { - return lb.PublicNet.IPv4.DNSPtr, nil - } else if net.IP.Equal(lb.PublicNet.IPv6.IP, ip) { - return lb.PublicNet.IPv6.DNSPtr, nil - } - - return "", DNSNotFoundError{ip} -} - -// LoadBalancerClient is a client for the Load Balancers API. -type LoadBalancerClient struct { - client *Client -} - -// GetByID retrieves a Load Balancer by its ID. If the Load Balancer does not exist, nil is returned. -func (c *LoadBalancerClient) GetByID(ctx context.Context, id int) (*LoadBalancer, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/load_balancers/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.LoadBalancerGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return LoadBalancerFromSchema(body.LoadBalancer), resp, nil -} - -// GetByName retrieves a Load Balancer by its name. If the Load Balancer does not exist, nil is returned. -func (c *LoadBalancerClient) GetByName(ctx context.Context, name string) (*LoadBalancer, *Response, error) { - if name == "" { - return nil, nil, nil - } - LoadBalancer, response, err := c.List(ctx, LoadBalancerListOpts{Name: name}) - if len(LoadBalancer) == 0 { - return nil, response, err - } - return LoadBalancer[0], response, err -} - -// Get retrieves a Load Balancer by its ID if the input can be parsed as an integer, otherwise it -// retrieves a Load Balancer by its name. If the Load Balancer does not exist, nil is returned. -func (c *LoadBalancerClient) Get(ctx context.Context, idOrName string) (*LoadBalancer, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// LoadBalancerListOpts specifies options for listing Load Balancers. -type LoadBalancerListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l LoadBalancerListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of Load Balancers for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *LoadBalancerClient) List(ctx context.Context, opts LoadBalancerListOpts) ([]*LoadBalancer, *Response, error) { - path := "/load_balancers?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.LoadBalancerListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - LoadBalancers := make([]*LoadBalancer, 0, len(body.LoadBalancers)) - for _, s := range body.LoadBalancers { - LoadBalancers = append(LoadBalancers, LoadBalancerFromSchema(s)) - } - return LoadBalancers, resp, nil -} - -// All returns all Load Balancers. -func (c *LoadBalancerClient) All(ctx context.Context) ([]*LoadBalancer, error) { - allLoadBalancer := []*LoadBalancer{} - - opts := LoadBalancerListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - LoadBalancer, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allLoadBalancer = append(allLoadBalancer, LoadBalancer...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allLoadBalancer, nil -} - -// AllWithOpts returns all Load Balancers for the given options. -func (c *LoadBalancerClient) AllWithOpts(ctx context.Context, opts LoadBalancerListOpts) ([]*LoadBalancer, error) { - var allLoadBalancers []*LoadBalancer - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - LoadBalancers, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allLoadBalancers = append(allLoadBalancers, LoadBalancers...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allLoadBalancers, nil -} - -// LoadBalancerUpdateOpts specifies options for updating a Load Balancer. -type LoadBalancerUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a Load Balancer. -func (c *LoadBalancerClient) Update(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerUpdateOpts) (*LoadBalancer, *Response, error) { - reqBody := schema.LoadBalancerUpdateRequest{} - if opts.Name != "" { - reqBody.Name = &opts.Name - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.LoadBalancerUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return LoadBalancerFromSchema(respBody.LoadBalancer), resp, nil -} - -// LoadBalancerCreateOpts specifies options for creating a new Load Balancer. -type LoadBalancerCreateOpts struct { - Name string - LoadBalancerType *LoadBalancerType - Algorithm *LoadBalancerAlgorithm - Location *Location - NetworkZone NetworkZone - Labels map[string]string - Targets []LoadBalancerCreateOptsTarget - Services []LoadBalancerCreateOptsService - PublicInterface *bool - Network *Network -} - -// LoadBalancerCreateOptsTarget holds options for specifying a target -// when creating a new Load Balancer. -type LoadBalancerCreateOptsTarget struct { - Type LoadBalancerTargetType - Server LoadBalancerCreateOptsTargetServer - LabelSelector LoadBalancerCreateOptsTargetLabelSelector - IP LoadBalancerCreateOptsTargetIP - UsePrivateIP *bool -} - -// LoadBalancerCreateOptsTargetServer holds options for specifying a server target -// when creating a new Load Balancer. -type LoadBalancerCreateOptsTargetServer struct { - Server *Server -} - -// LoadBalancerCreateOptsTargetLabelSelector holds options for specifying a label selector target -// when creating a new Load Balancer. -type LoadBalancerCreateOptsTargetLabelSelector struct { - Selector string -} - -// LoadBalancerCreateOptsTargetIP holds options for specifying an IP target -// when creating a new Load Balancer. -type LoadBalancerCreateOptsTargetIP struct { - IP string -} - -// LoadBalancerCreateOptsService holds options for specifying a service -// when creating a new Load Balancer. -type LoadBalancerCreateOptsService struct { - Protocol LoadBalancerServiceProtocol - ListenPort *int - DestinationPort *int - Proxyprotocol *bool - HTTP *LoadBalancerCreateOptsServiceHTTP - HealthCheck *LoadBalancerCreateOptsServiceHealthCheck -} - -// LoadBalancerCreateOptsServiceHTTP holds options for specifying an HTTP service -// when creating a new Load Balancer. -type LoadBalancerCreateOptsServiceHTTP struct { - CookieName *string - CookieLifetime *time.Duration - Certificates []*Certificate - RedirectHTTP *bool - StickySessions *bool -} - -// LoadBalancerCreateOptsServiceHealthCheck holds options for specifying a service -// health check when creating a new Load Balancer. -type LoadBalancerCreateOptsServiceHealthCheck struct { - Protocol LoadBalancerServiceProtocol - Port *int - Interval *time.Duration - Timeout *time.Duration - Retries *int - HTTP *LoadBalancerCreateOptsServiceHealthCheckHTTP -} - -// LoadBalancerCreateOptsServiceHealthCheckHTTP holds options for specifying a service -// HTTP health check when creating a new Load Balancer. -type LoadBalancerCreateOptsServiceHealthCheckHTTP struct { - Domain *string - Path *string - Response *string - StatusCodes []string - TLS *bool -} - -// LoadBalancerCreateResult is the result of a create Load Balancer call. -type LoadBalancerCreateResult struct { - LoadBalancer *LoadBalancer - Action *Action -} - -// Create creates a new Load Balancer. -func (c *LoadBalancerClient) Create(ctx context.Context, opts LoadBalancerCreateOpts) (LoadBalancerCreateResult, *Response, error) { - reqBody := loadBalancerCreateOptsToSchema(opts) - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return LoadBalancerCreateResult{}, nil, err - } - req, err := c.client.NewRequest(ctx, "POST", "/load_balancers", bytes.NewReader(reqBodyData)) - if err != nil { - return LoadBalancerCreateResult{}, nil, err - } - - respBody := schema.LoadBalancerCreateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return LoadBalancerCreateResult{}, resp, err - } - return LoadBalancerCreateResult{ - LoadBalancer: LoadBalancerFromSchema(respBody.LoadBalancer), - Action: ActionFromSchema(respBody.Action), - }, resp, nil -} - -// Delete deletes a Load Balancer. -func (c *LoadBalancerClient) Delete(ctx context.Context, loadBalancer *LoadBalancer) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/load_balancers/%d", loadBalancer.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -func (c *LoadBalancerClient) addTarget(ctx context.Context, loadBalancer *LoadBalancer, reqBody schema.LoadBalancerActionAddTargetRequest) (*Action, *Response, error) { - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/add_target", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.LoadBalancerActionAddTargetResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -func (c *LoadBalancerClient) removeTarget(ctx context.Context, loadBalancer *LoadBalancer, reqBody schema.LoadBalancerActionRemoveTargetRequest) (*Action, *Response, error) { - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/remove_target", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.LoadBalancerActionRemoveTargetResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// LoadBalancerAddServerTargetOpts specifies options for adding a server target -// to a Load Balancer. -type LoadBalancerAddServerTargetOpts struct { - Server *Server - UsePrivateIP *bool -} - -// AddServerTarget adds a server target to a Load Balancer. -func (c *LoadBalancerClient) AddServerTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddServerTargetOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionAddTargetRequest{ - Type: string(LoadBalancerTargetTypeServer), - Server: &schema.LoadBalancerActionAddTargetRequestServer{ - ID: opts.Server.ID, - }, - UsePrivateIP: opts.UsePrivateIP, - } - return c.addTarget(ctx, loadBalancer, reqBody) -} - -// RemoveServerTarget removes a server target from a Load Balancer. -func (c *LoadBalancerClient) RemoveServerTarget(ctx context.Context, loadBalancer *LoadBalancer, server *Server) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionRemoveTargetRequest{ - Type: string(LoadBalancerTargetTypeServer), - Server: &schema.LoadBalancerActionRemoveTargetRequestServer{ - ID: server.ID, - }, - } - return c.removeTarget(ctx, loadBalancer, reqBody) -} - -// LoadBalancerAddLabelSelectorTargetOpts specifies options for adding a label selector target -// to a Load Balancer. -type LoadBalancerAddLabelSelectorTargetOpts struct { - Selector string - UsePrivateIP *bool -} - -// AddLabelSelectorTarget adds a label selector target to a Load Balancer. -func (c *LoadBalancerClient) AddLabelSelectorTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddLabelSelectorTargetOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionAddTargetRequest{ - Type: string(LoadBalancerTargetTypeLabelSelector), - LabelSelector: &schema.LoadBalancerActionAddTargetRequestLabelSelector{ - Selector: opts.Selector, - }, - UsePrivateIP: opts.UsePrivateIP, - } - return c.addTarget(ctx, loadBalancer, reqBody) -} - -// RemoveLabelSelectorTarget removes a label selector target from a Load Balancer. -func (c *LoadBalancerClient) RemoveLabelSelectorTarget(ctx context.Context, loadBalancer *LoadBalancer, labelSelector string) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionRemoveTargetRequest{ - Type: string(LoadBalancerTargetTypeLabelSelector), - LabelSelector: &schema.LoadBalancerActionRemoveTargetRequestLabelSelector{ - Selector: labelSelector, - }, - } - return c.removeTarget(ctx, loadBalancer, reqBody) -} - -// LoadBalancerAddIPTargetOpts specifies options for adding an IP target to a -// Load Balancer. -type LoadBalancerAddIPTargetOpts struct { - IP net.IP -} - -// AddIPTarget adds an IP target to a Load Balancer. -func (c *LoadBalancerClient) AddIPTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddIPTargetOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionAddTargetRequest{ - Type: string(LoadBalancerTargetTypeIP), - IP: &schema.LoadBalancerActionAddTargetRequestIP{IP: opts.IP.String()}, - } - return c.addTarget(ctx, loadBalancer, reqBody) -} - -// RemoveIPTarget removes an IP target from a Load Balancer. -func (c *LoadBalancerClient) RemoveIPTarget(ctx context.Context, loadBalancer *LoadBalancer, ip net.IP) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionRemoveTargetRequest{ - Type: string(LoadBalancerTargetTypeIP), - IP: &schema.LoadBalancerActionRemoveTargetRequestIP{ - IP: ip.String(), - }, - } - return c.removeTarget(ctx, loadBalancer, reqBody) -} - -// LoadBalancerAddServiceOpts specifies options for adding a service to a Load Balancer. -type LoadBalancerAddServiceOpts struct { - Protocol LoadBalancerServiceProtocol - ListenPort *int - DestinationPort *int - Proxyprotocol *bool - HTTP *LoadBalancerAddServiceOptsHTTP - HealthCheck *LoadBalancerAddServiceOptsHealthCheck -} - -// LoadBalancerAddServiceOptsHTTP holds options for specifying an HTTP service -// when adding a service to a Load Balancer. -type LoadBalancerAddServiceOptsHTTP struct { - CookieName *string - CookieLifetime *time.Duration - Certificates []*Certificate - RedirectHTTP *bool - StickySessions *bool -} - -// LoadBalancerAddServiceOptsHealthCheck holds options for specifying an health check -// when adding a service to a Load Balancer. -type LoadBalancerAddServiceOptsHealthCheck struct { - Protocol LoadBalancerServiceProtocol - Port *int - Interval *time.Duration - Timeout *time.Duration - Retries *int - HTTP *LoadBalancerAddServiceOptsHealthCheckHTTP -} - -// LoadBalancerAddServiceOptsHealthCheckHTTP holds options for specifying an -// HTTP health check when adding a service to a Load Balancer. -type LoadBalancerAddServiceOptsHealthCheckHTTP struct { - Domain *string - Path *string - Response *string - StatusCodes []string - TLS *bool -} - -// AddService adds a service to a Load Balancer. -func (c *LoadBalancerClient) AddService(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddServiceOpts) (*Action, *Response, error) { - reqBody := loadBalancerAddServiceOptsToSchema(opts) - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/add_service", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.LoadBalancerActionAddServiceResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// LoadBalancerUpdateServiceOpts specifies options for updating a service. -type LoadBalancerUpdateServiceOpts struct { - Protocol LoadBalancerServiceProtocol - DestinationPort *int - Proxyprotocol *bool - HTTP *LoadBalancerUpdateServiceOptsHTTP - HealthCheck *LoadBalancerUpdateServiceOptsHealthCheck -} - -// LoadBalancerUpdateServiceOptsHTTP specifies options for updating an HTTP(S) service. -type LoadBalancerUpdateServiceOptsHTTP struct { - CookieName *string - CookieLifetime *time.Duration - Certificates []*Certificate - RedirectHTTP *bool - StickySessions *bool -} - -// LoadBalancerUpdateServiceOptsHealthCheck specifies options for updating -// a service's health check. -type LoadBalancerUpdateServiceOptsHealthCheck struct { - Protocol LoadBalancerServiceProtocol - Port *int - Interval *time.Duration - Timeout *time.Duration - Retries *int - HTTP *LoadBalancerUpdateServiceOptsHealthCheckHTTP -} - -// LoadBalancerUpdateServiceOptsHealthCheckHTTP specifies options for updating -// the HTTP-specific settings of a service's health check. -type LoadBalancerUpdateServiceOptsHealthCheckHTTP struct { - Domain *string - Path *string - Response *string - StatusCodes []string - TLS *bool -} - -// UpdateService updates a Load Balancer service. -func (c *LoadBalancerClient) UpdateService(ctx context.Context, loadBalancer *LoadBalancer, listenPort int, opts LoadBalancerUpdateServiceOpts) (*Action, *Response, error) { - reqBody := loadBalancerUpdateServiceOptsToSchema(opts) - reqBody.ListenPort = listenPort - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/update_service", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.LoadBalancerActionUpdateServiceResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// DeleteService deletes a Load Balancer service. -func (c *LoadBalancerClient) DeleteService(ctx context.Context, loadBalancer *LoadBalancer, listenPort int) (*Action, *Response, error) { - reqBody := schema.LoadBalancerDeleteServiceRequest{ - ListenPort: listenPort, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/delete_service", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.LoadBalancerDeleteServiceResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// LoadBalancerChangeProtectionOpts specifies options for changing the resource protection level of a Load Balancer. -type LoadBalancerChangeProtectionOpts struct { - Delete *bool -} - -// ChangeProtection changes the resource protection level of a Load Balancer. -func (c *LoadBalancerClient) ChangeProtection(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeProtectionOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionChangeProtectionRequest{ - Delete: opts.Delete, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/change_protection", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.LoadBalancerActionChangeProtectionResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// LoadBalancerChangeAlgorithmOpts specifies options for changing the algorithm of a Load Balancer. -type LoadBalancerChangeAlgorithmOpts struct { - Type LoadBalancerAlgorithmType -} - -// ChangeAlgorithm changes the algorithm of a Load Balancer. -func (c *LoadBalancerClient) ChangeAlgorithm(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeAlgorithmOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionChangeAlgorithmRequest{ - Type: string(opts.Type), - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/change_algorithm", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.LoadBalancerActionChangeAlgorithmResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// LoadBalancerAttachToNetworkOpts specifies options for attaching a Load Balancer to a network. -type LoadBalancerAttachToNetworkOpts struct { - Network *Network - IP net.IP -} - -// AttachToNetwork attaches a Load Balancer to a network. -func (c *LoadBalancerClient) AttachToNetwork(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAttachToNetworkOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionAttachToNetworkRequest{ - Network: opts.Network.ID, - } - if opts.IP != nil { - reqBody.IP = Ptr(opts.IP.String()) - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/attach_to_network", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.LoadBalancerActionAttachToNetworkResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// LoadBalancerDetachFromNetworkOpts specifies options for detaching a Load Balancer from a network. -type LoadBalancerDetachFromNetworkOpts struct { - Network *Network -} - -// DetachFromNetwork detaches a Load Balancer from a network. -func (c *LoadBalancerClient) DetachFromNetwork(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerDetachFromNetworkOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionDetachFromNetworkRequest{ - Network: opts.Network.ID, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/detach_from_network", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.LoadBalancerActionDetachFromNetworkResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// EnablePublicInterface enables the Load Balancer's public network interface. -func (c *LoadBalancerClient) EnablePublicInterface(ctx context.Context, loadBalancer *LoadBalancer) (*Action, *Response, error) { - path := fmt.Sprintf("/load_balancers/%d/actions/enable_public_interface", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - respBody := schema.LoadBalancerActionEnablePublicInterfaceResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// DisablePublicInterface disables the Load Balancer's public network interface. -func (c *LoadBalancerClient) DisablePublicInterface(ctx context.Context, loadBalancer *LoadBalancer) (*Action, *Response, error) { - path := fmt.Sprintf("/load_balancers/%d/actions/disable_public_interface", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - respBody := schema.LoadBalancerActionDisablePublicInterfaceResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// LoadBalancerChangeTypeOpts specifies options for changing a Load Balancer's type. -type LoadBalancerChangeTypeOpts struct { - LoadBalancerType *LoadBalancerType // new Load Balancer type -} - -// ChangeType changes a Load Balancer's type. -func (c *LoadBalancerClient) ChangeType(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeTypeOpts) (*Action, *Response, error) { - reqBody := schema.LoadBalancerActionChangeTypeRequest{} - if opts.LoadBalancerType.ID != 0 { - reqBody.LoadBalancerType = opts.LoadBalancerType.ID - } else { - reqBody.LoadBalancerType = opts.LoadBalancerType.Name - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/load_balancers/%d/actions/change_type", loadBalancer.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.LoadBalancerActionChangeTypeResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// LoadBalancerMetricType is the type of available metrics for Load Balancers. -type LoadBalancerMetricType string - -// Available types of Load Balancer metrics. See Hetzner Cloud API -// documentation for details. -const ( - LoadBalancerMetricOpenConnections LoadBalancerMetricType = "open_connections" - LoadBalancerMetricConnectionsPerSecond LoadBalancerMetricType = "connections_per_second" - LoadBalancerMetricRequestsPerSecond LoadBalancerMetricType = "requests_per_second" - LoadBalancerMetricBandwidth LoadBalancerMetricType = "bandwidth" -) - -// LoadBalancerGetMetricsOpts configures the call to get metrics for a Load -// Balancer. -type LoadBalancerGetMetricsOpts struct { - Types []LoadBalancerMetricType - Start time.Time - End time.Time - Step int -} - -func (o *LoadBalancerGetMetricsOpts) addQueryParams(req *http.Request) error { - query := req.URL.Query() - - if len(o.Types) == 0 { - return fmt.Errorf("no metric types specified") - } - for _, typ := range o.Types { - query.Add("type", string(typ)) - } - - if o.Start.IsZero() { - return fmt.Errorf("no start time specified") - } - query.Add("start", o.Start.Format(time.RFC3339)) - - if o.End.IsZero() { - return fmt.Errorf("no end time specified") - } - query.Add("end", o.End.Format(time.RFC3339)) - - if o.Step > 0 { - query.Add("step", strconv.Itoa(o.Step)) - } - req.URL.RawQuery = query.Encode() - - return nil -} - -// LoadBalancerMetrics contains the metrics requested for a Load Balancer. -type LoadBalancerMetrics struct { - Start time.Time - End time.Time - Step float64 - TimeSeries map[string][]LoadBalancerMetricsValue -} - -// LoadBalancerMetricsValue represents a single value in a time series of metrics. -type LoadBalancerMetricsValue struct { - Timestamp float64 - Value string -} - -// GetMetrics obtains metrics for a Load Balancer. -func (c *LoadBalancerClient) GetMetrics( - ctx context.Context, lb *LoadBalancer, opts LoadBalancerGetMetricsOpts, -) (*LoadBalancerMetrics, *Response, error) { - var respBody schema.LoadBalancerGetMetricsResponse - - if lb == nil { - return nil, nil, fmt.Errorf("illegal argument: load balancer is nil") - } - - path := fmt.Sprintf("/load_balancers/%d/metrics", lb.ID) - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, fmt.Errorf("new request: %v", err) - } - if err := opts.addQueryParams(req); err != nil { - return nil, nil, fmt.Errorf("add query params: %v", err) - } - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, nil, fmt.Errorf("get metrics: %v", err) - } - ms, err := loadBalancerMetricsFromSchema(&respBody) - if err != nil { - return nil, nil, fmt.Errorf("convert response body: %v", err) - } - return ms, resp, nil -} - -// ChangeDNSPtr changes or resets the reverse DNS pointer for a Load Balancer. -// Pass a nil ptr to reset the reverse DNS pointer to its default value. -func (c *LoadBalancerClient) ChangeDNSPtr(ctx context.Context, lb *LoadBalancer, ip string, ptr *string) (*Action, *Response, error) { - netIP := net.ParseIP(ip) - if netIP == nil { - return nil, nil, InvalidIPError{ip} - } - return lb.changeDNSPtr(ctx, c.client, net.ParseIP(ip), ptr) -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/load_balancer_type.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/load_balancer_type.go deleted file mode 100644 index 5ac748147..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/load_balancer_type.go +++ /dev/null @@ -1,130 +0,0 @@ -package hcloud - -import ( - "context" - "fmt" - "net/url" - "strconv" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// LoadBalancerType represents a LoadBalancer type in the Hetzner Cloud. -type LoadBalancerType struct { - ID int - Name string - Description string - MaxConnections int - MaxServices int - MaxTargets int - MaxAssignedCertificates int - Pricings []LoadBalancerTypeLocationPricing -} - -// LoadBalancerTypeClient is a client for the Load Balancer types API. -type LoadBalancerTypeClient struct { - client *Client -} - -// GetByID retrieves a Load Balancer type by its ID. If the Load Balancer type does not exist, nil is returned. -func (c *LoadBalancerTypeClient) GetByID(ctx context.Context, id int) (*LoadBalancerType, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/load_balancer_types/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.LoadBalancerTypeGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return LoadBalancerTypeFromSchema(body.LoadBalancerType), resp, nil -} - -// GetByName retrieves a Load Balancer type by its name. If the Load Balancer type does not exist, nil is returned. -func (c *LoadBalancerTypeClient) GetByName(ctx context.Context, name string) (*LoadBalancerType, *Response, error) { - if name == "" { - return nil, nil, nil - } - LoadBalancerTypes, response, err := c.List(ctx, LoadBalancerTypeListOpts{Name: name}) - if len(LoadBalancerTypes) == 0 { - return nil, response, err - } - return LoadBalancerTypes[0], response, err -} - -// Get retrieves a Load Balancer type by its ID if the input can be parsed as an integer, otherwise it -// retrieves a Load Balancer type by its name. If the Load Balancer type does not exist, nil is returned. -func (c *LoadBalancerTypeClient) Get(ctx context.Context, idOrName string) (*LoadBalancerType, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// LoadBalancerTypeListOpts specifies options for listing Load Balancer types. -type LoadBalancerTypeListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l LoadBalancerTypeListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of Load Balancer types for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *LoadBalancerTypeClient) List(ctx context.Context, opts LoadBalancerTypeListOpts) ([]*LoadBalancerType, *Response, error) { - path := "/load_balancer_types?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.LoadBalancerTypeListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - LoadBalancerTypes := make([]*LoadBalancerType, 0, len(body.LoadBalancerTypes)) - for _, s := range body.LoadBalancerTypes { - LoadBalancerTypes = append(LoadBalancerTypes, LoadBalancerTypeFromSchema(s)) - } - return LoadBalancerTypes, resp, nil -} - -// All returns all Load Balancer types. -func (c *LoadBalancerTypeClient) All(ctx context.Context) ([]*LoadBalancerType, error) { - allLoadBalancerTypes := []*LoadBalancerType{} - - opts := LoadBalancerTypeListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - LoadBalancerTypes, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allLoadBalancerTypes = append(allLoadBalancerTypes, LoadBalancerTypes...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allLoadBalancerTypes, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/location.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/location.go deleted file mode 100644 index c749bdf0b..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/location.go +++ /dev/null @@ -1,130 +0,0 @@ -package hcloud - -import ( - "context" - "fmt" - "net/url" - "strconv" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Location represents a location in the Hetzner Cloud. -type Location struct { - ID int - Name string - Description string - Country string - City string - Latitude float64 - Longitude float64 - NetworkZone NetworkZone -} - -// LocationClient is a client for the location API. -type LocationClient struct { - client *Client -} - -// GetByID retrieves a location by its ID. If the location does not exist, nil is returned. -func (c *LocationClient) GetByID(ctx context.Context, id int) (*Location, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/locations/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.LocationGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, resp, err - } - return LocationFromSchema(body.Location), resp, nil -} - -// GetByName retrieves an location by its name. If the location does not exist, nil is returned. -func (c *LocationClient) GetByName(ctx context.Context, name string) (*Location, *Response, error) { - if name == "" { - return nil, nil, nil - } - locations, response, err := c.List(ctx, LocationListOpts{Name: name}) - if len(locations) == 0 { - return nil, response, err - } - return locations[0], response, err -} - -// Get retrieves a location by its ID if the input can be parsed as an integer, otherwise it -// retrieves a location by its name. If the location does not exist, nil is returned. -func (c *LocationClient) Get(ctx context.Context, idOrName string) (*Location, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// LocationListOpts specifies options for listing location. -type LocationListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l LocationListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of locations for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *LocationClient) List(ctx context.Context, opts LocationListOpts) ([]*Location, *Response, error) { - path := "/locations?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.LocationListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - locations := make([]*Location, 0, len(body.Locations)) - for _, i := range body.Locations { - locations = append(locations, LocationFromSchema(i)) - } - return locations, resp, nil -} - -// All returns all locations. -func (c *LocationClient) All(ctx context.Context) ([]*Location, error) { - allLocations := []*Location{} - - opts := LocationListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - locations, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allLocations = append(allLocations, locations...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allLocations, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/network.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/network.go deleted file mode 100644 index 5a196816d..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/network.go +++ /dev/null @@ -1,469 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// NetworkZone specifies a network zone. -type NetworkZone string - -// List of available Network Zones. -const ( - NetworkZoneEUCentral NetworkZone = "eu-central" - NetworkZoneUSEast NetworkZone = "us-east" - NetworkZoneUSWest NetworkZone = "us-west" -) - -// NetworkSubnetType specifies a type of a subnet. -type NetworkSubnetType string - -// List of available network subnet types. -const ( - NetworkSubnetTypeCloud NetworkSubnetType = "cloud" - NetworkSubnetTypeServer NetworkSubnetType = "server" - NetworkSubnetTypeVSwitch NetworkSubnetType = "vswitch" -) - -// Network represents a network in the Hetzner Cloud. -type Network struct { - ID int - Name string - Created time.Time - IPRange *net.IPNet - Subnets []NetworkSubnet - Routes []NetworkRoute - Servers []*Server - Protection NetworkProtection - Labels map[string]string -} - -// NetworkSubnet represents a subnet of a network in the Hetzner Cloud. -type NetworkSubnet struct { - Type NetworkSubnetType - IPRange *net.IPNet - NetworkZone NetworkZone - Gateway net.IP - VSwitchID int -} - -// NetworkRoute represents a route of a network. -type NetworkRoute struct { - Destination *net.IPNet - Gateway net.IP -} - -// NetworkProtection represents the protection level of a network. -type NetworkProtection struct { - Delete bool -} - -// NetworkClient is a client for the network API. -type NetworkClient struct { - client *Client -} - -// GetByID retrieves a network by its ID. If the network does not exist, nil is returned. -func (c *NetworkClient) GetByID(ctx context.Context, id int) (*Network, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/networks/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.NetworkGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return NetworkFromSchema(body.Network), resp, nil -} - -// GetByName retrieves a network by its name. If the network does not exist, nil is returned. -func (c *NetworkClient) GetByName(ctx context.Context, name string) (*Network, *Response, error) { - if name == "" { - return nil, nil, nil - } - Networks, response, err := c.List(ctx, NetworkListOpts{Name: name}) - if len(Networks) == 0 { - return nil, response, err - } - return Networks[0], response, err -} - -// Get retrieves a network by its ID if the input can be parsed as an integer, otherwise it -// retrieves a network by its name. If the network does not exist, nil is returned. -func (c *NetworkClient) Get(ctx context.Context, idOrName string) (*Network, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// NetworkListOpts specifies options for listing networks. -type NetworkListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l NetworkListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of networks for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *NetworkClient) List(ctx context.Context, opts NetworkListOpts) ([]*Network, *Response, error) { - path := "/networks?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.NetworkListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - Networks := make([]*Network, 0, len(body.Networks)) - for _, s := range body.Networks { - Networks = append(Networks, NetworkFromSchema(s)) - } - return Networks, resp, nil -} - -// All returns all networks. -func (c *NetworkClient) All(ctx context.Context) ([]*Network, error) { - return c.AllWithOpts(ctx, NetworkListOpts{ListOpts: ListOpts{PerPage: 50}}) -} - -// AllWithOpts returns all networks for the given options. -func (c *NetworkClient) AllWithOpts(ctx context.Context, opts NetworkListOpts) ([]*Network, error) { - var allNetworks []*Network - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - Networks, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allNetworks = append(allNetworks, Networks...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allNetworks, nil -} - -// Delete deletes a network. -func (c *NetworkClient) Delete(ctx context.Context, network *Network) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/networks/%d", network.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// NetworkUpdateOpts specifies options for updating a network. -type NetworkUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a network. -func (c *NetworkClient) Update(ctx context.Context, network *Network, opts NetworkUpdateOpts) (*Network, *Response, error) { - reqBody := schema.NetworkUpdateRequest{ - Name: opts.Name, - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/networks/%d", network.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return NetworkFromSchema(respBody.Network), resp, nil -} - -// NetworkCreateOpts specifies options for creating a new network. -type NetworkCreateOpts struct { - Name string - IPRange *net.IPNet - Subnets []NetworkSubnet - Routes []NetworkRoute - Labels map[string]string -} - -// Validate checks if options are valid. -func (o NetworkCreateOpts) Validate() error { - if o.Name == "" { - return errors.New("missing name") - } - if o.IPRange == nil || o.IPRange.String() == "" { - return errors.New("missing IP range") - } - return nil -} - -// Create creates a new network. -func (c *NetworkClient) Create(ctx context.Context, opts NetworkCreateOpts) (*Network, *Response, error) { - if err := opts.Validate(); err != nil { - return nil, nil, err - } - reqBody := schema.NetworkCreateRequest{ - Name: opts.Name, - IPRange: opts.IPRange.String(), - } - for _, subnet := range opts.Subnets { - s := schema.NetworkSubnet{ - Type: string(subnet.Type), - IPRange: subnet.IPRange.String(), - NetworkZone: string(subnet.NetworkZone), - } - if subnet.VSwitchID != 0 { - s.VSwitchID = subnet.VSwitchID - } - reqBody.Subnets = append(reqBody.Subnets, s) - } - for _, route := range opts.Routes { - reqBody.Routes = append(reqBody.Routes, schema.NetworkRoute{ - Destination: route.Destination.String(), - Gateway: route.Gateway.String(), - }) - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - req, err := c.client.NewRequest(ctx, "POST", "/networks", bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkCreateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return NetworkFromSchema(respBody.Network), resp, nil -} - -// NetworkChangeIPRangeOpts specifies options for changing the IP range of a network. -type NetworkChangeIPRangeOpts struct { - IPRange *net.IPNet -} - -// ChangeIPRange changes the IP range of a network. -func (c *NetworkClient) ChangeIPRange(ctx context.Context, network *Network, opts NetworkChangeIPRangeOpts) (*Action, *Response, error) { - reqBody := schema.NetworkActionChangeIPRangeRequest{ - IPRange: opts.IPRange.String(), - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/networks/%d/actions/change_ip_range", network.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkActionChangeIPRangeResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// NetworkAddSubnetOpts specifies options for adding a subnet to a network. -type NetworkAddSubnetOpts struct { - Subnet NetworkSubnet -} - -// AddSubnet adds a subnet to a network. -func (c *NetworkClient) AddSubnet(ctx context.Context, network *Network, opts NetworkAddSubnetOpts) (*Action, *Response, error) { - reqBody := schema.NetworkActionAddSubnetRequest{ - Type: string(opts.Subnet.Type), - NetworkZone: string(opts.Subnet.NetworkZone), - } - if opts.Subnet.IPRange != nil { - reqBody.IPRange = opts.Subnet.IPRange.String() - } - if opts.Subnet.VSwitchID != 0 { - reqBody.VSwitchID = opts.Subnet.VSwitchID - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/networks/%d/actions/add_subnet", network.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkActionAddSubnetResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// NetworkDeleteSubnetOpts specifies options for deleting a subnet from a network. -type NetworkDeleteSubnetOpts struct { - Subnet NetworkSubnet -} - -// DeleteSubnet deletes a subnet from a network. -func (c *NetworkClient) DeleteSubnet(ctx context.Context, network *Network, opts NetworkDeleteSubnetOpts) (*Action, *Response, error) { - reqBody := schema.NetworkActionDeleteSubnetRequest{ - IPRange: opts.Subnet.IPRange.String(), - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/networks/%d/actions/delete_subnet", network.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkActionDeleteSubnetResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// NetworkAddRouteOpts specifies options for adding a route to a network. -type NetworkAddRouteOpts struct { - Route NetworkRoute -} - -// AddRoute adds a route to a network. -func (c *NetworkClient) AddRoute(ctx context.Context, network *Network, opts NetworkAddRouteOpts) (*Action, *Response, error) { - reqBody := schema.NetworkActionAddRouteRequest{ - Destination: opts.Route.Destination.String(), - Gateway: opts.Route.Gateway.String(), - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/networks/%d/actions/add_route", network.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkActionAddSubnetResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// NetworkDeleteRouteOpts specifies options for deleting a route from a network. -type NetworkDeleteRouteOpts struct { - Route NetworkRoute -} - -// DeleteRoute deletes a route from a network. -func (c *NetworkClient) DeleteRoute(ctx context.Context, network *Network, opts NetworkDeleteRouteOpts) (*Action, *Response, error) { - reqBody := schema.NetworkActionDeleteRouteRequest{ - Destination: opts.Route.Destination.String(), - Gateway: opts.Route.Gateway.String(), - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/networks/%d/actions/delete_route", network.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkActionDeleteSubnetResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// NetworkChangeProtectionOpts specifies options for changing the resource protection level of a network. -type NetworkChangeProtectionOpts struct { - Delete *bool -} - -// ChangeProtection changes the resource protection level of a network. -func (c *NetworkClient) ChangeProtection(ctx context.Context, network *Network, opts NetworkChangeProtectionOpts) (*Action, *Response, error) { - reqBody := schema.NetworkActionChangeProtectionRequest{ - Delete: opts.Delete, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/networks/%d/actions/change_protection", network.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.NetworkActionChangeProtectionResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/placement_group.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/placement_group.go deleted file mode 100644 index 07fedad5e..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/placement_group.go +++ /dev/null @@ -1,247 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// PlacementGroup represents a Placement Group in the Hetzner Cloud. -type PlacementGroup struct { - ID int - Name string - Labels map[string]string - Created time.Time - Servers []int - Type PlacementGroupType -} - -// PlacementGroupType specifies the type of a Placement Group. -type PlacementGroupType string - -const ( - // PlacementGroupTypeSpread spreads all servers in the group on different vhosts. - PlacementGroupTypeSpread PlacementGroupType = "spread" -) - -// PlacementGroupClient is a client for the Placement Groups API. -type PlacementGroupClient struct { - client *Client -} - -// GetByID retrieves a PlacementGroup by its ID. If the PlacementGroup does not exist, nil is returned. -func (c *PlacementGroupClient) GetByID(ctx context.Context, id int) (*PlacementGroup, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/placement_groups/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.PlacementGroupGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return PlacementGroupFromSchema(body.PlacementGroup), resp, nil -} - -// GetByName retrieves a PlacementGroup by its name. If the PlacementGroup does not exist, nil is returned. -func (c *PlacementGroupClient) GetByName(ctx context.Context, name string) (*PlacementGroup, *Response, error) { - if name == "" { - return nil, nil, nil - } - placementGroups, response, err := c.List(ctx, PlacementGroupListOpts{Name: name}) - if len(placementGroups) == 0 { - return nil, response, err - } - return placementGroups[0], response, err -} - -// Get retrieves a PlacementGroup by its ID if the input can be parsed as an integer, otherwise it -// retrieves a PlacementGroup by its name. If the PlacementGroup does not exist, nil is returned. -func (c *PlacementGroupClient) Get(ctx context.Context, idOrName string) (*PlacementGroup, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// PlacementGroupListOpts specifies options for listing PlacementGroup. -type PlacementGroupListOpts struct { - ListOpts - Name string - Type PlacementGroupType - Sort []string -} - -func (l PlacementGroupListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - if l.Type != "" { - vals.Add("type", string(l.Type)) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of PlacementGroups for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *PlacementGroupClient) List(ctx context.Context, opts PlacementGroupListOpts) ([]*PlacementGroup, *Response, error) { - path := "/placement_groups?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.PlacementGroupListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - placementGroups := make([]*PlacementGroup, 0, len(body.PlacementGroups)) - for _, g := range body.PlacementGroups { - placementGroups = append(placementGroups, PlacementGroupFromSchema(g)) - } - return placementGroups, resp, nil -} - -// All returns all PlacementGroups. -func (c *PlacementGroupClient) All(ctx context.Context) ([]*PlacementGroup, error) { - opts := PlacementGroupListOpts{ - ListOpts: ListOpts{ - PerPage: 50, - }, - } - - return c.AllWithOpts(ctx, opts) -} - -// AllWithOpts returns all PlacementGroups for the given options. -func (c *PlacementGroupClient) AllWithOpts(ctx context.Context, opts PlacementGroupListOpts) ([]*PlacementGroup, error) { - var allPlacementGroups []*PlacementGroup - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - placementGroups, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allPlacementGroups = append(allPlacementGroups, placementGroups...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allPlacementGroups, nil -} - -// PlacementGroupCreateOpts specifies options for creating a new PlacementGroup. -type PlacementGroupCreateOpts struct { - Name string - Labels map[string]string - Type PlacementGroupType -} - -// Validate checks if options are valid. -func (o PlacementGroupCreateOpts) Validate() error { - if o.Name == "" { - return errors.New("missing name") - } - return nil -} - -// PlacementGroupCreateResult is the result of a create PlacementGroup call. -type PlacementGroupCreateResult struct { - PlacementGroup *PlacementGroup - Action *Action -} - -// Create creates a new PlacementGroup. -func (c *PlacementGroupClient) Create(ctx context.Context, opts PlacementGroupCreateOpts) (PlacementGroupCreateResult, *Response, error) { - if err := opts.Validate(); err != nil { - return PlacementGroupCreateResult{}, nil, err - } - reqBody := placementGroupCreateOptsToSchema(opts) - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return PlacementGroupCreateResult{}, nil, err - } - req, err := c.client.NewRequest(ctx, "POST", "/placement_groups", bytes.NewReader(reqBodyData)) - if err != nil { - return PlacementGroupCreateResult{}, nil, err - } - - respBody := schema.PlacementGroupCreateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return PlacementGroupCreateResult{}, nil, err - } - result := PlacementGroupCreateResult{ - PlacementGroup: PlacementGroupFromSchema(respBody.PlacementGroup), - } - if respBody.Action != nil { - result.Action = ActionFromSchema(*respBody.Action) - } - - return result, resp, nil -} - -// PlacementGroupUpdateOpts specifies options for updating a PlacementGroup. -type PlacementGroupUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a PlacementGroup. -func (c *PlacementGroupClient) Update(ctx context.Context, placementGroup *PlacementGroup, opts PlacementGroupUpdateOpts) (*PlacementGroup, *Response, error) { - reqBody := schema.PlacementGroupUpdateRequest{} - if opts.Name != "" { - reqBody.Name = &opts.Name - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/placement_groups/%d", placementGroup.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.PlacementGroupUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - - return PlacementGroupFromSchema(respBody.PlacementGroup), resp, nil -} - -// Delete deletes a PlacementGroup. -func (c *PlacementGroupClient) Delete(ctx context.Context, placementGroup *PlacementGroup) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/placement_groups/%d", placementGroup.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/pricing.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/pricing.go deleted file mode 100644 index 836f391ff..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/pricing.go +++ /dev/null @@ -1,139 +0,0 @@ -package hcloud - -import ( - "context" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Pricing specifies pricing information for various resources. -type Pricing struct { - Image ImagePricing - FloatingIP FloatingIPPricing - FloatingIPs []FloatingIPTypePricing - PrimaryIPs []PrimaryIPPricing - Traffic TrafficPricing - ServerBackup ServerBackupPricing - ServerTypes []ServerTypePricing - LoadBalancerTypes []LoadBalancerTypePricing - Volume VolumePricing -} - -// Price represents a price. Net amount, gross amount, as well as VAT rate are -// specified as strings and it is the user's responsibility to convert them to -// appropriate types for calculations. -type Price struct { - Currency string - VATRate string - Net string - Gross string -} - -// PrimaryIPPrice represents a price. Net amount and gross amount are -// specified as strings and it is the user's responsibility to convert them to -// appropriate types for calculations. -type PrimaryIPPrice struct { - Net string - Gross string -} - -// ImagePricing provides pricing information for imaegs. -type ImagePricing struct { - PerGBMonth Price -} - -// FloatingIPPricing provides pricing information for Floating IPs. -type FloatingIPPricing struct { - Monthly Price -} - -// FloatingIPTypePricing provides pricing information for Floating IPs per Type. -type FloatingIPTypePricing struct { - Type FloatingIPType - Pricings []FloatingIPTypeLocationPricing -} - -// PrimaryIPTypePricing defines the schema of pricing information for a primary IP -// type at a datacenter. -type PrimaryIPTypePricing struct { - Datacenter string // Deprecated: the API does not return pricing for the individual DCs anymore - Location string - Hourly PrimaryIPPrice - Monthly PrimaryIPPrice -} - -// PrimaryIPTypePricing provides pricing information for PrimaryIPs. -type PrimaryIPPricing struct { - Type string - Pricings []PrimaryIPTypePricing -} - -// FloatingIPTypeLocationPricing provides pricing information for a Floating IP type -// at a location. -type FloatingIPTypeLocationPricing struct { - Location *Location - Monthly Price -} - -// TrafficPricing provides pricing information for traffic. -type TrafficPricing struct { - PerTB Price -} - -// VolumePricing provides pricing information for a Volume. -type VolumePricing struct { - PerGBMonthly Price -} - -// ServerBackupPricing provides pricing information for server backups. -type ServerBackupPricing struct { - Percentage string -} - -// ServerTypePricing provides pricing information for a server type. -type ServerTypePricing struct { - ServerType *ServerType - Pricings []ServerTypeLocationPricing -} - -// ServerTypeLocationPricing provides pricing information for a server type -// at a location. -type ServerTypeLocationPricing struct { - Location *Location - Hourly Price - Monthly Price -} - -// LoadBalancerTypePricing provides pricing information for a Load Balancer type. -type LoadBalancerTypePricing struct { - LoadBalancerType *LoadBalancerType - Pricings []LoadBalancerTypeLocationPricing -} - -// LoadBalancerTypeLocationPricing provides pricing information for a Load Balancer type -// at a location. -type LoadBalancerTypeLocationPricing struct { - Location *Location - Hourly Price - Monthly Price -} - -// PricingClient is a client for the pricing API. -type PricingClient struct { - client *Client -} - -// Get retrieves pricing information. -func (c *PricingClient) Get(ctx context.Context) (Pricing, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", "/pricing", nil) - if err != nil { - return Pricing{}, nil, err - } - - var body schema.PricingGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return Pricing{}, nil, err - } - return PricingFromSchema(body.Pricing), resp, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/primary_ip.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/primary_ip.go deleted file mode 100644 index e328b9b36..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/primary_ip.go +++ /dev/null @@ -1,395 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "net" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// PrimaryIP defines a Primary IP. -type PrimaryIP struct { - ID int - IP net.IP - Network *net.IPNet - Labels map[string]string - Name string - Type PrimaryIPType - Protection PrimaryIPProtection - DNSPtr map[string]string - AssigneeID int - AssigneeType string - AutoDelete bool - Blocked bool - Created time.Time - Datacenter *Datacenter -} - -// PrimaryIPProtection represents the protection level of a Primary IP. -type PrimaryIPProtection struct { - Delete bool -} - -// PrimaryIPDNSPTR contains reverse DNS information for a -// IPv4 or IPv6 Primary IP. -type PrimaryIPDNSPTR struct { - DNSPtr string - IP string -} - -// GetDNSPtrForIP searches for the dns assigned to the given IP address. -// It returns an error if there is no dns set for the given IP address. -func (p *PrimaryIP) GetDNSPtrForIP(ip net.IP) (string, error) { - dns, ok := p.DNSPtr[ip.String()] - if !ok { - return "", DNSNotFoundError{ip} - } - - return dns, nil -} - -// PrimaryIPType represents the type of Primary IP. -type PrimaryIPType string - -// PrimaryIPType Primary IP types. -const ( - PrimaryIPTypeIPv4 PrimaryIPType = "ipv4" - PrimaryIPTypeIPv6 PrimaryIPType = "ipv6" -) - -// PrimaryIPCreateOpts defines the request to -// create a Primary IP. -type PrimaryIPCreateOpts struct { - AssigneeID *int `json:"assignee_id,omitempty"` - AssigneeType string `json:"assignee_type"` - AutoDelete *bool `json:"auto_delete,omitempty"` - Datacenter string `json:"datacenter,omitempty"` - Labels map[string]string `json:"labels,omitempty"` - Name string `json:"name"` - Type PrimaryIPType `json:"type"` -} - -// PrimaryIPCreateResult defines the response -// when creating a Primary IP. -type PrimaryIPCreateResult struct { - PrimaryIP *PrimaryIP - Action *Action -} - -// PrimaryIPUpdateOpts defines the request to -// update a Primary IP. -type PrimaryIPUpdateOpts struct { - AutoDelete *bool `json:"auto_delete,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` - Name string `json:"name,omitempty"` -} - -// PrimaryIPAssignOpts defines the request to -// assign a Primary IP to an assignee (usually a server). -type PrimaryIPAssignOpts struct { - ID int - AssigneeID int `json:"assignee_id"` - AssigneeType string `json:"assignee_type"` -} - -// PrimaryIPAssignResult defines the response -// when assigning a Primary IP to a assignee. -type PrimaryIPAssignResult struct { - Action schema.Action `json:"action"` -} - -// PrimaryIPChangeDNSPtrOpts defines the request to -// change a DNS PTR entry from a Primary IP. -type PrimaryIPChangeDNSPtrOpts struct { - ID int - DNSPtr string `json:"dns_ptr"` - IP string `json:"ip"` -} - -// PrimaryIPChangeDNSPtrResult defines the response -// when assigning a Primary IP to a assignee. -type PrimaryIPChangeDNSPtrResult struct { - Action schema.Action `json:"action"` -} - -// PrimaryIPChangeProtectionOpts defines the request to -// change protection configuration of a Primary IP. -type PrimaryIPChangeProtectionOpts struct { - ID int - Delete bool `json:"delete"` -} - -// PrimaryIPChangeProtectionResult defines the response -// when changing a protection of a PrimaryIP. -type PrimaryIPChangeProtectionResult struct { - Action schema.Action `json:"action"` -} - -// PrimaryIPClient is a client for the Primary IP API. -type PrimaryIPClient struct { - client *Client -} - -// GetByID retrieves a Primary IP by its ID. If the Primary IP does not exist, nil is returned. -func (c *PrimaryIPClient) GetByID(ctx context.Context, id int) (*PrimaryIP, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/primary_ips/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.PrimaryIPGetResult - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return PrimaryIPFromSchema(body.PrimaryIP), resp, nil -} - -// GetByIP retrieves a Primary IP by its IP Address. If the Primary IP does not exist, nil is returned. -func (c *PrimaryIPClient) GetByIP(ctx context.Context, ip string) (*PrimaryIP, *Response, error) { - if ip == "" { - return nil, nil, nil - } - primaryIPs, response, err := c.List(ctx, PrimaryIPListOpts{IP: ip}) - if len(primaryIPs) == 0 { - return nil, response, err - } - return primaryIPs[0], response, err -} - -// GetByName retrieves a Primary IP by its name. If the Primary IP does not exist, nil is returned. -func (c *PrimaryIPClient) GetByName(ctx context.Context, name string) (*PrimaryIP, *Response, error) { - if name == "" { - return nil, nil, nil - } - primaryIPs, response, err := c.List(ctx, PrimaryIPListOpts{Name: name}) - if len(primaryIPs) == 0 { - return nil, response, err - } - return primaryIPs[0], response, err -} - -// Get retrieves a Primary IP by its ID if the input can be parsed as an integer, otherwise it -// retrieves a Primary IP by its name. If the Primary IP does not exist, nil is returned. -func (c *PrimaryIPClient) Get(ctx context.Context, idOrName string) (*PrimaryIP, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// PrimaryIPListOpts specifies options for listing Primary IPs. -type PrimaryIPListOpts struct { - ListOpts - Name string - IP string - Sort []string -} - -func (l PrimaryIPListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - if l.IP != "" { - vals.Add("ip", l.IP) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of Primary IPs for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *PrimaryIPClient) List(ctx context.Context, opts PrimaryIPListOpts) ([]*PrimaryIP, *Response, error) { - path := "/primary_ips?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.PrimaryIPListResult - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - primaryIPs := make([]*PrimaryIP, 0, len(body.PrimaryIPs)) - for _, s := range body.PrimaryIPs { - primaryIPs = append(primaryIPs, PrimaryIPFromSchema(s)) - } - return primaryIPs, resp, nil -} - -// All returns all Primary IPs. -func (c *PrimaryIPClient) All(ctx context.Context) ([]*PrimaryIP, error) { - return c.AllWithOpts(ctx, PrimaryIPListOpts{ListOpts: ListOpts{PerPage: 50}}) -} - -// AllWithOpts returns all Primary IPs for the given options. -func (c *PrimaryIPClient) AllWithOpts(ctx context.Context, opts PrimaryIPListOpts) ([]*PrimaryIP, error) { - var allPrimaryIPs []*PrimaryIP - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - primaryIPs, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allPrimaryIPs = append(allPrimaryIPs, primaryIPs...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allPrimaryIPs, nil -} - -// Create creates a Primary IP. -func (c *PrimaryIPClient) Create(ctx context.Context, reqBody PrimaryIPCreateOpts) (*PrimaryIPCreateResult, *Response, error) { - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return &PrimaryIPCreateResult{}, nil, err - } - - req, err := c.client.NewRequest(ctx, "POST", "/primary_ips", bytes.NewReader(reqBodyData)) - if err != nil { - return &PrimaryIPCreateResult{}, nil, err - } - - var respBody schema.PrimaryIPCreateResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return &PrimaryIPCreateResult{}, resp, err - } - var action *Action - if respBody.Action != nil { - action = ActionFromSchema(*respBody.Action) - } - primaryIP := PrimaryIPFromSchema(respBody.PrimaryIP) - return &PrimaryIPCreateResult{ - PrimaryIP: primaryIP, - Action: action, - }, resp, nil -} - -// Delete deletes a Primary IP. -func (c *PrimaryIPClient) Delete(ctx context.Context, primaryIP *PrimaryIP) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/primary_ips/%d", primaryIP.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// Update updates a Primary IP. -func (c *PrimaryIPClient) Update(ctx context.Context, primaryIP *PrimaryIP, reqBody PrimaryIPUpdateOpts) (*PrimaryIP, *Response, error) { - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/primary_ips/%d", primaryIP.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.PrimaryIPUpdateResult - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return PrimaryIPFromSchema(respBody.PrimaryIP), resp, nil -} - -// Assign a Primary IP to a resource. -func (c *PrimaryIPClient) Assign(ctx context.Context, opts PrimaryIPAssignOpts) (*Action, *Response, error) { - reqBodyData, err := json.Marshal(opts) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/primary_ips/%d/actions/assign", opts.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody PrimaryIPAssignResult - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// Unassign a Primary IP from a resource. -func (c *PrimaryIPClient) Unassign(ctx context.Context, id int) (*Action, *Response, error) { - path := fmt.Sprintf("/primary_ips/%d/actions/unassign", id) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader([]byte{})) - if err != nil { - return nil, nil, err - } - - var respBody PrimaryIPAssignResult - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// ChangeDNSPtr Change the reverse DNS from a Primary IP. -func (c *PrimaryIPClient) ChangeDNSPtr(ctx context.Context, opts PrimaryIPChangeDNSPtrOpts) (*Action, *Response, error) { - reqBodyData, err := json.Marshal(opts) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/primary_ips/%d/actions/change_dns_ptr", opts.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody PrimaryIPChangeDNSPtrResult - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// ChangeProtection Changes the protection configuration of a Primary IP. -func (c *PrimaryIPClient) ChangeProtection(ctx context.Context, opts PrimaryIPChangeProtectionOpts) (*Action, *Response, error) { - reqBodyData, err := json.Marshal(opts) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/primary_ips/%d/actions/change_protection", opts.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody PrimaryIPChangeProtectionResult - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/resource.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/resource.go deleted file mode 100644 index 8a734dfd6..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/resource.go +++ /dev/null @@ -1,7 +0,0 @@ -package hcloud - -// Resource defines the schema of a resource. -type Resource struct { - ID int - Type string -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema.go deleted file mode 100644 index b72db88d2..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema.go +++ /dev/null @@ -1,1250 +0,0 @@ -package hcloud - -import ( - "fmt" - "net" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// This file provides converter functions to convert models in the -// schema package to models in the hcloud package and vice versa. - -// ActionFromSchema converts a schema.Action to an Action. -func ActionFromSchema(s schema.Action) *Action { - action := &Action{ - ID: s.ID, - Status: ActionStatus(s.Status), - Command: s.Command, - Progress: s.Progress, - Started: s.Started, - Resources: []*ActionResource{}, - } - if s.Finished != nil { - action.Finished = *s.Finished - } - if s.Error != nil { - action.ErrorCode = s.Error.Code - action.ErrorMessage = s.Error.Message - } - for _, r := range s.Resources { - action.Resources = append(action.Resources, &ActionResource{ - ID: r.ID, - Type: ActionResourceType(r.Type), - }) - } - return action -} - -// ActionsFromSchema converts a slice of schema.Action to a slice of Action. -func ActionsFromSchema(s []schema.Action) []*Action { - actions := make([]*Action, len(s)) - for i, a := range s { - actions[i] = ActionFromSchema(a) - } - return actions -} - -// FloatingIPFromSchema converts a schema.FloatingIP to a FloatingIP. -func FloatingIPFromSchema(s schema.FloatingIP) *FloatingIP { - f := &FloatingIP{ - ID: s.ID, - Type: FloatingIPType(s.Type), - HomeLocation: LocationFromSchema(s.HomeLocation), - Created: s.Created, - Blocked: s.Blocked, - Protection: FloatingIPProtection{ - Delete: s.Protection.Delete, - }, - Name: s.Name, - } - if s.Description != nil { - f.Description = *s.Description - } - if s.Server != nil { - f.Server = &Server{ID: *s.Server} - } - if f.Type == FloatingIPTypeIPv4 { - f.IP = net.ParseIP(s.IP) - } else { - f.IP, f.Network, _ = net.ParseCIDR(s.IP) - } - f.DNSPtr = map[string]string{} - for _, entry := range s.DNSPtr { - f.DNSPtr[entry.IP] = entry.DNSPtr - } - f.Labels = map[string]string{} - for key, value := range s.Labels { - f.Labels[key] = value - } - return f -} - -// PrimaryIPFromSchema converts a schema.PrimaryIP to a PrimaryIP. -func PrimaryIPFromSchema(s schema.PrimaryIP) *PrimaryIP { - f := &PrimaryIP{ - ID: s.ID, - Type: PrimaryIPType(s.Type), - AutoDelete: s.AutoDelete, - - Created: s.Created, - Blocked: s.Blocked, - Protection: PrimaryIPProtection{ - Delete: s.Protection.Delete, - }, - Name: s.Name, - AssigneeType: s.AssigneeType, - AssigneeID: s.AssigneeID, - Datacenter: DatacenterFromSchema(s.Datacenter), - } - - if f.Type == PrimaryIPTypeIPv4 { - f.IP = net.ParseIP(s.IP) - } else { - f.IP, f.Network, _ = net.ParseCIDR(s.IP) - } - f.DNSPtr = map[string]string{} - for _, entry := range s.DNSPtr { - f.DNSPtr[entry.IP] = entry.DNSPtr - } - f.Labels = map[string]string{} - for key, value := range s.Labels { - f.Labels[key] = value - } - return f -} - -// ISOFromSchema converts a schema.ISO to an ISO. -func ISOFromSchema(s schema.ISO) *ISO { - iso := &ISO{ - ID: s.ID, - Name: s.Name, - Description: s.Description, - Type: ISOType(s.Type), - Deprecated: s.Deprecated, - } - if s.Architecture != nil { - iso.Architecture = Ptr(Architecture(*s.Architecture)) - } - return iso -} - -// LocationFromSchema converts a schema.Location to a Location. -func LocationFromSchema(s schema.Location) *Location { - return &Location{ - ID: s.ID, - Name: s.Name, - Description: s.Description, - Country: s.Country, - City: s.City, - Latitude: s.Latitude, - Longitude: s.Longitude, - NetworkZone: NetworkZone(s.NetworkZone), - } -} - -// DatacenterFromSchema converts a schema.Datacenter to a Datacenter. -func DatacenterFromSchema(s schema.Datacenter) *Datacenter { - d := &Datacenter{ - ID: s.ID, - Name: s.Name, - Description: s.Description, - Location: LocationFromSchema(s.Location), - ServerTypes: DatacenterServerTypes{ - Available: []*ServerType{}, - Supported: []*ServerType{}, - }, - } - for _, t := range s.ServerTypes.Available { - d.ServerTypes.Available = append(d.ServerTypes.Available, &ServerType{ID: t}) - } - for _, t := range s.ServerTypes.Supported { - d.ServerTypes.Supported = append(d.ServerTypes.Supported, &ServerType{ID: t}) - } - return d -} - -// ServerFromSchema converts a schema.Server to a Server. -func ServerFromSchema(s schema.Server) *Server { - server := &Server{ - ID: s.ID, - Name: s.Name, - Status: ServerStatus(s.Status), - Created: s.Created, - PublicNet: ServerPublicNetFromSchema(s.PublicNet), - ServerType: ServerTypeFromSchema(s.ServerType), - IncludedTraffic: s.IncludedTraffic, - RescueEnabled: s.RescueEnabled, - Datacenter: DatacenterFromSchema(s.Datacenter), - Locked: s.Locked, - PrimaryDiskSize: s.PrimaryDiskSize, - Protection: ServerProtection{ - Delete: s.Protection.Delete, - Rebuild: s.Protection.Rebuild, - }, - } - if s.Image != nil { - server.Image = ImageFromSchema(*s.Image) - } - if s.BackupWindow != nil { - server.BackupWindow = *s.BackupWindow - } - if s.OutgoingTraffic != nil { - server.OutgoingTraffic = *s.OutgoingTraffic - } - if s.IngoingTraffic != nil { - server.IngoingTraffic = *s.IngoingTraffic - } - if s.ISO != nil { - server.ISO = ISOFromSchema(*s.ISO) - } - server.Labels = map[string]string{} - for key, value := range s.Labels { - server.Labels[key] = value - } - for _, id := range s.Volumes { - server.Volumes = append(server.Volumes, &Volume{ID: id}) - } - for _, privNet := range s.PrivateNet { - server.PrivateNet = append(server.PrivateNet, ServerPrivateNetFromSchema(privNet)) - } - if s.PlacementGroup != nil { - server.PlacementGroup = PlacementGroupFromSchema(*s.PlacementGroup) - } - return server -} - -// ServerPublicNetFromSchema converts a schema.ServerPublicNet to a ServerPublicNet. -func ServerPublicNetFromSchema(s schema.ServerPublicNet) ServerPublicNet { - publicNet := ServerPublicNet{ - IPv4: ServerPublicNetIPv4FromSchema(s.IPv4), - IPv6: ServerPublicNetIPv6FromSchema(s.IPv6), - } - for _, id := range s.FloatingIPs { - publicNet.FloatingIPs = append(publicNet.FloatingIPs, &FloatingIP{ID: id}) - } - for _, fw := range s.Firewalls { - publicNet.Firewalls = append(publicNet.Firewalls, - &ServerFirewallStatus{ - Firewall: Firewall{ID: fw.ID}, - Status: FirewallStatus(fw.Status)}, - ) - } - return publicNet -} - -// ServerPublicNetIPv4FromSchema converts a schema.ServerPublicNetIPv4 to -// a ServerPublicNetIPv4. -func ServerPublicNetIPv4FromSchema(s schema.ServerPublicNetIPv4) ServerPublicNetIPv4 { - return ServerPublicNetIPv4{ - ID: s.ID, - IP: net.ParseIP(s.IP), - Blocked: s.Blocked, - DNSPtr: s.DNSPtr, - } -} - -// ServerPublicNetIPv6FromSchema converts a schema.ServerPublicNetIPv6 to -// a ServerPublicNetIPv6. -func ServerPublicNetIPv6FromSchema(s schema.ServerPublicNetIPv6) ServerPublicNetIPv6 { - ipv6 := ServerPublicNetIPv6{ - ID: s.ID, - Blocked: s.Blocked, - DNSPtr: map[string]string{}, - } - ipv6.IP, ipv6.Network, _ = net.ParseCIDR(s.IP) - - for _, dnsPtr := range s.DNSPtr { - ipv6.DNSPtr[dnsPtr.IP] = dnsPtr.DNSPtr - } - return ipv6 -} - -// ServerPrivateNetFromSchema converts a schema.ServerPrivateNet to a ServerPrivateNet. -func ServerPrivateNetFromSchema(s schema.ServerPrivateNet) ServerPrivateNet { - n := ServerPrivateNet{ - Network: &Network{ID: s.Network}, - IP: net.ParseIP(s.IP), - MACAddress: s.MACAddress, - } - for _, ip := range s.AliasIPs { - n.Aliases = append(n.Aliases, net.ParseIP(ip)) - } - return n -} - -// ServerTypeFromSchema converts a schema.ServerType to a ServerType. -func ServerTypeFromSchema(s schema.ServerType) *ServerType { - st := &ServerType{ - ID: s.ID, - Name: s.Name, - Description: s.Description, - Cores: s.Cores, - Memory: s.Memory, - Disk: s.Disk, - StorageType: StorageType(s.StorageType), - CPUType: CPUType(s.CPUType), - Architecture: Architecture(s.Architecture), - } - for _, price := range s.Prices { - st.Pricings = append(st.Pricings, ServerTypeLocationPricing{ - Location: &Location{Name: price.Location}, - Hourly: Price{ - Net: price.PriceHourly.Net, - Gross: price.PriceHourly.Gross, - }, - Monthly: Price{ - Net: price.PriceMonthly.Net, - Gross: price.PriceMonthly.Gross, - }, - }) - } - return st -} - -// SSHKeyFromSchema converts a schema.SSHKey to a SSHKey. -func SSHKeyFromSchema(s schema.SSHKey) *SSHKey { - sshKey := &SSHKey{ - ID: s.ID, - Name: s.Name, - Fingerprint: s.Fingerprint, - PublicKey: s.PublicKey, - Created: s.Created, - } - sshKey.Labels = map[string]string{} - for key, value := range s.Labels { - sshKey.Labels[key] = value - } - return sshKey -} - -// ImageFromSchema converts a schema.Image to an Image. -func ImageFromSchema(s schema.Image) *Image { - i := &Image{ - ID: s.ID, - Type: ImageType(s.Type), - Status: ImageStatus(s.Status), - Description: s.Description, - DiskSize: s.DiskSize, - Created: s.Created, - RapidDeploy: s.RapidDeploy, - OSFlavor: s.OSFlavor, - Architecture: Architecture(s.Architecture), - Protection: ImageProtection{ - Delete: s.Protection.Delete, - }, - Deprecated: s.Deprecated, - Deleted: s.Deleted, - } - if s.Name != nil { - i.Name = *s.Name - } - if s.ImageSize != nil { - i.ImageSize = *s.ImageSize - } - if s.OSVersion != nil { - i.OSVersion = *s.OSVersion - } - if s.CreatedFrom != nil { - i.CreatedFrom = &Server{ - ID: s.CreatedFrom.ID, - Name: s.CreatedFrom.Name, - } - } - if s.BoundTo != nil { - i.BoundTo = &Server{ - ID: *s.BoundTo, - } - } - i.Labels = map[string]string{} - for key, value := range s.Labels { - i.Labels[key] = value - } - return i -} - -// VolumeFromSchema converts a schema.Volume to a Volume. -func VolumeFromSchema(s schema.Volume) *Volume { - v := &Volume{ - ID: s.ID, - Name: s.Name, - Location: LocationFromSchema(s.Location), - Size: s.Size, - Status: VolumeStatus(s.Status), - LinuxDevice: s.LinuxDevice, - Protection: VolumeProtection{ - Delete: s.Protection.Delete, - }, - Created: s.Created, - } - if s.Server != nil { - v.Server = &Server{ID: *s.Server} - } - v.Labels = map[string]string{} - for key, value := range s.Labels { - v.Labels[key] = value - } - return v -} - -// NetworkFromSchema converts a schema.Network to a Network. -func NetworkFromSchema(s schema.Network) *Network { - n := &Network{ - ID: s.ID, - Name: s.Name, - Created: s.Created, - Protection: NetworkProtection{ - Delete: s.Protection.Delete, - }, - Labels: map[string]string{}, - } - - _, n.IPRange, _ = net.ParseCIDR(s.IPRange) - - for _, subnet := range s.Subnets { - n.Subnets = append(n.Subnets, NetworkSubnetFromSchema(subnet)) - } - for _, route := range s.Routes { - n.Routes = append(n.Routes, NetworkRouteFromSchema(route)) - } - for _, serverID := range s.Servers { - n.Servers = append(n.Servers, &Server{ID: serverID}) - } - for key, value := range s.Labels { - n.Labels[key] = value - } - - return n -} - -// NetworkSubnetFromSchema converts a schema.NetworkSubnet to a NetworkSubnet. -func NetworkSubnetFromSchema(s schema.NetworkSubnet) NetworkSubnet { - sn := NetworkSubnet{ - Type: NetworkSubnetType(s.Type), - NetworkZone: NetworkZone(s.NetworkZone), - Gateway: net.ParseIP(s.Gateway), - VSwitchID: s.VSwitchID, - } - _, sn.IPRange, _ = net.ParseCIDR(s.IPRange) - return sn -} - -// NetworkRouteFromSchema converts a schema.NetworkRoute to a NetworkRoute. -func NetworkRouteFromSchema(s schema.NetworkRoute) NetworkRoute { - r := NetworkRoute{ - Gateway: net.ParseIP(s.Gateway), - } - _, r.Destination, _ = net.ParseCIDR(s.Destination) - return r -} - -// LoadBalancerTypeFromSchema converts a schema.LoadBalancerType to a LoadBalancerType. -func LoadBalancerTypeFromSchema(s schema.LoadBalancerType) *LoadBalancerType { - lt := &LoadBalancerType{ - ID: s.ID, - Name: s.Name, - Description: s.Description, - MaxConnections: s.MaxConnections, - MaxServices: s.MaxServices, - MaxTargets: s.MaxTargets, - MaxAssignedCertificates: s.MaxAssignedCertificates, - } - for _, price := range s.Prices { - lt.Pricings = append(lt.Pricings, LoadBalancerTypeLocationPricing{ - Location: &Location{Name: price.Location}, - Hourly: Price{ - Net: price.PriceHourly.Net, - Gross: price.PriceHourly.Gross, - }, - Monthly: Price{ - Net: price.PriceMonthly.Net, - Gross: price.PriceMonthly.Gross, - }, - }) - } - return lt -} - -// LoadBalancerFromSchema converts a schema.LoadBalancer to a LoadBalancer. -func LoadBalancerFromSchema(s schema.LoadBalancer) *LoadBalancer { - l := &LoadBalancer{ - ID: s.ID, - Name: s.Name, - PublicNet: LoadBalancerPublicNet{ - Enabled: s.PublicNet.Enabled, - IPv4: LoadBalancerPublicNetIPv4{ - IP: net.ParseIP(s.PublicNet.IPv4.IP), - DNSPtr: s.PublicNet.IPv4.DNSPtr, - }, - IPv6: LoadBalancerPublicNetIPv6{ - IP: net.ParseIP(s.PublicNet.IPv6.IP), - DNSPtr: s.PublicNet.IPv6.DNSPtr, - }, - }, - Location: LocationFromSchema(s.Location), - LoadBalancerType: LoadBalancerTypeFromSchema(s.LoadBalancerType), - Algorithm: LoadBalancerAlgorithm{Type: LoadBalancerAlgorithmType(s.Algorithm.Type)}, - Protection: LoadBalancerProtection{ - Delete: s.Protection.Delete, - }, - Labels: map[string]string{}, - Created: s.Created, - IncludedTraffic: s.IncludedTraffic, - } - for _, privateNet := range s.PrivateNet { - l.PrivateNet = append(l.PrivateNet, LoadBalancerPrivateNet{ - Network: &Network{ID: privateNet.Network}, - IP: net.ParseIP(privateNet.IP), - }) - } - if s.OutgoingTraffic != nil { - l.OutgoingTraffic = *s.OutgoingTraffic - } - if s.IngoingTraffic != nil { - l.IngoingTraffic = *s.IngoingTraffic - } - for _, service := range s.Services { - l.Services = append(l.Services, LoadBalancerServiceFromSchema(service)) - } - for _, target := range s.Targets { - l.Targets = append(l.Targets, LoadBalancerTargetFromSchema(target)) - } - for key, value := range s.Labels { - l.Labels[key] = value - } - return l -} - -// LoadBalancerServiceFromSchema converts a schema.LoadBalancerService to a LoadBalancerService. -func LoadBalancerServiceFromSchema(s schema.LoadBalancerService) LoadBalancerService { - ls := LoadBalancerService{ - Protocol: LoadBalancerServiceProtocol(s.Protocol), - ListenPort: s.ListenPort, - DestinationPort: s.DestinationPort, - Proxyprotocol: s.Proxyprotocol, - HealthCheck: LoadBalancerServiceHealthCheckFromSchema(s.HealthCheck), - } - if s.HTTP != nil { - ls.HTTP = LoadBalancerServiceHTTP{ - CookieName: s.HTTP.CookieName, - CookieLifetime: time.Duration(s.HTTP.CookieLifetime) * time.Second, - RedirectHTTP: s.HTTP.RedirectHTTP, - StickySessions: s.HTTP.StickySessions, - } - for _, certificateID := range s.HTTP.Certificates { - ls.HTTP.Certificates = append(ls.HTTP.Certificates, &Certificate{ID: certificateID}) - } - } - return ls -} - -// LoadBalancerServiceHealthCheckFromSchema converts a schema.LoadBalancerServiceHealthCheck to a LoadBalancerServiceHealthCheck. -func LoadBalancerServiceHealthCheckFromSchema(s *schema.LoadBalancerServiceHealthCheck) LoadBalancerServiceHealthCheck { - lsh := LoadBalancerServiceHealthCheck{ - Protocol: LoadBalancerServiceProtocol(s.Protocol), - Port: s.Port, - Interval: time.Duration(s.Interval) * time.Second, - Retries: s.Retries, - Timeout: time.Duration(s.Timeout) * time.Second, - } - if s.HTTP != nil { - lsh.HTTP = &LoadBalancerServiceHealthCheckHTTP{ - Domain: s.HTTP.Domain, - Path: s.HTTP.Path, - Response: s.HTTP.Response, - StatusCodes: s.HTTP.StatusCodes, - TLS: s.HTTP.TLS, - } - } - return lsh -} - -// LoadBalancerTargetFromSchema converts a schema.LoadBalancerTarget to a LoadBalancerTarget. -func LoadBalancerTargetFromSchema(s schema.LoadBalancerTarget) LoadBalancerTarget { - lt := LoadBalancerTarget{ - Type: LoadBalancerTargetType(s.Type), - UsePrivateIP: s.UsePrivateIP, - } - if s.Server != nil { - lt.Server = &LoadBalancerTargetServer{ - Server: &Server{ID: s.Server.ID}, - } - } - if s.LabelSelector != nil { - lt.LabelSelector = &LoadBalancerTargetLabelSelector{ - Selector: s.LabelSelector.Selector, - } - } - if s.IP != nil { - lt.IP = &LoadBalancerTargetIP{IP: s.IP.IP} - } - - for _, healthStatus := range s.HealthStatus { - lt.HealthStatus = append(lt.HealthStatus, LoadBalancerTargetHealthStatusFromSchema(healthStatus)) - } - for _, target := range s.Targets { - lt.Targets = append(lt.Targets, LoadBalancerTargetFromSchema(target)) - } - return lt -} - -// LoadBalancerTargetHealthStatusFromSchema converts a schema.LoadBalancerTarget to a LoadBalancerTarget. -func LoadBalancerTargetHealthStatusFromSchema(s schema.LoadBalancerTargetHealthStatus) LoadBalancerTargetHealthStatus { - return LoadBalancerTargetHealthStatus{ - ListenPort: s.ListenPort, - Status: LoadBalancerTargetHealthStatusStatus(s.Status), - } -} - -// CertificateFromSchema converts a schema.Certificate to a Certificate. -func CertificateFromSchema(s schema.Certificate) *Certificate { - c := &Certificate{ - ID: s.ID, - Name: s.Name, - Type: CertificateType(s.Type), - Certificate: s.Certificate, - Created: s.Created, - NotValidBefore: s.NotValidBefore, - NotValidAfter: s.NotValidAfter, - DomainNames: s.DomainNames, - Fingerprint: s.Fingerprint, - } - if s.Status != nil { - c.Status = &CertificateStatus{ - Issuance: CertificateStatusType(s.Status.Issuance), - Renewal: CertificateStatusType(s.Status.Renewal), - } - if s.Status.Error != nil { - certErr := ErrorFromSchema(*s.Status.Error) - c.Status.Error = &certErr - } - } - if len(s.Labels) > 0 { - c.Labels = s.Labels - } - if len(s.UsedBy) > 0 { - c.UsedBy = make([]CertificateUsedByRef, len(s.UsedBy)) - for i, ref := range s.UsedBy { - c.UsedBy[i] = CertificateUsedByRef{ID: ref.ID, Type: CertificateUsedByRefType(ref.Type)} - } - } - - return c -} - -// PaginationFromSchema converts a schema.MetaPagination to a Pagination. -func PaginationFromSchema(s schema.MetaPagination) Pagination { - return Pagination{ - Page: s.Page, - PerPage: s.PerPage, - PreviousPage: s.PreviousPage, - NextPage: s.NextPage, - LastPage: s.LastPage, - TotalEntries: s.TotalEntries, - } -} - -// ErrorFromSchema converts a schema.Error to an Error. -func ErrorFromSchema(s schema.Error) Error { - e := Error{ - Code: ErrorCode(s.Code), - Message: s.Message, - } - - if d, ok := s.Details.(schema.ErrorDetailsInvalidInput); ok { - details := ErrorDetailsInvalidInput{ - Fields: []ErrorDetailsInvalidInputField{}, - } - for _, field := range d.Fields { - details.Fields = append(details.Fields, ErrorDetailsInvalidInputField{ - Name: field.Name, - Messages: field.Messages, - }) - } - e.Details = details - } - return e -} - -// PricingFromSchema converts a schema.Pricing to a Pricing. -func PricingFromSchema(s schema.Pricing) Pricing { - p := Pricing{ - Image: ImagePricing{ - PerGBMonth: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: s.Image.PricePerGBMonth.Net, - Gross: s.Image.PricePerGBMonth.Gross, - }, - }, - FloatingIP: FloatingIPPricing{ - Monthly: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: s.FloatingIP.PriceMonthly.Net, - Gross: s.FloatingIP.PriceMonthly.Gross, - }, - }, - Traffic: TrafficPricing{ - PerTB: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: s.Traffic.PricePerTB.Net, - Gross: s.Traffic.PricePerTB.Gross, - }, - }, - ServerBackup: ServerBackupPricing{ - Percentage: s.ServerBackup.Percentage, - }, - Volume: VolumePricing{ - PerGBMonthly: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: s.Volume.PricePerGBPerMonth.Net, - Gross: s.Volume.PricePerGBPerMonth.Gross, - }, - }, - } - for _, floatingIPType := range s.FloatingIPs { - var pricings []FloatingIPTypeLocationPricing - for _, price := range floatingIPType.Prices { - p := FloatingIPTypeLocationPricing{ - Location: &Location{Name: price.Location}, - Monthly: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: price.PriceMonthly.Net, - Gross: price.PriceMonthly.Gross, - }, - } - pricings = append(pricings, p) - } - p.FloatingIPs = append(p.FloatingIPs, FloatingIPTypePricing{Type: FloatingIPType(floatingIPType.Type), Pricings: pricings}) - } - for _, primaryIPType := range s.PrimaryIPs { - var pricings []PrimaryIPTypePricing - for _, price := range primaryIPType.Prices { - p := PrimaryIPTypePricing{ - Location: price.Location, - Monthly: PrimaryIPPrice{ - Net: price.PriceMonthly.Net, - Gross: price.PriceMonthly.Gross, - }, - Hourly: PrimaryIPPrice{ - Net: price.PriceHourly.Net, - Gross: price.PriceHourly.Gross, - }, - } - pricings = append(pricings, p) - } - p.PrimaryIPs = append(p.PrimaryIPs, PrimaryIPPricing{Type: primaryIPType.Type, Pricings: pricings}) - } - for _, serverType := range s.ServerTypes { - var pricings []ServerTypeLocationPricing - for _, price := range serverType.Prices { - pricings = append(pricings, ServerTypeLocationPricing{ - Location: &Location{Name: price.Location}, - Hourly: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: price.PriceHourly.Net, - Gross: price.PriceHourly.Gross, - }, - Monthly: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: price.PriceMonthly.Net, - Gross: price.PriceMonthly.Gross, - }, - }) - } - p.ServerTypes = append(p.ServerTypes, ServerTypePricing{ - ServerType: &ServerType{ - ID: serverType.ID, - Name: serverType.Name, - }, - Pricings: pricings, - }) - } - for _, loadBalancerType := range s.LoadBalancerTypes { - var pricings []LoadBalancerTypeLocationPricing - for _, price := range loadBalancerType.Prices { - pricings = append(pricings, LoadBalancerTypeLocationPricing{ - Location: &Location{Name: price.Location}, - Hourly: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: price.PriceHourly.Net, - Gross: price.PriceHourly.Gross, - }, - Monthly: Price{ - Currency: s.Currency, - VATRate: s.VATRate, - Net: price.PriceMonthly.Net, - Gross: price.PriceMonthly.Gross, - }, - }) - } - p.LoadBalancerTypes = append(p.LoadBalancerTypes, LoadBalancerTypePricing{ - LoadBalancerType: &LoadBalancerType{ - ID: loadBalancerType.ID, - Name: loadBalancerType.Name, - }, - Pricings: pricings, - }) - } - return p -} - -// FirewallFromSchema converts a schema.Firewall to a Firewall. -func FirewallFromSchema(s schema.Firewall) *Firewall { - f := &Firewall{ - ID: s.ID, - Name: s.Name, - Labels: map[string]string{}, - Created: s.Created, - } - for key, value := range s.Labels { - f.Labels[key] = value - } - for _, res := range s.AppliedTo { - r := FirewallResource{Type: FirewallResourceType(res.Type)} - switch r.Type { - case FirewallResourceTypeLabelSelector: - r.LabelSelector = &FirewallResourceLabelSelector{Selector: res.LabelSelector.Selector} - case FirewallResourceTypeServer: - r.Server = &FirewallResourceServer{ID: res.Server.ID} - } - f.AppliedTo = append(f.AppliedTo, r) - } - for _, rule := range s.Rules { - sourceIPs := []net.IPNet{} - for _, sourceIP := range rule.SourceIPs { - _, mask, err := net.ParseCIDR(sourceIP) - if err == nil && mask != nil { - sourceIPs = append(sourceIPs, *mask) - } - } - destinationIPs := []net.IPNet{} - for _, destinationIP := range rule.DestinationIPs { - _, mask, err := net.ParseCIDR(destinationIP) - if err == nil && mask != nil { - destinationIPs = append(destinationIPs, *mask) - } - } - f.Rules = append(f.Rules, FirewallRule{ - Direction: FirewallRuleDirection(rule.Direction), - SourceIPs: sourceIPs, - DestinationIPs: destinationIPs, - Protocol: FirewallRuleProtocol(rule.Protocol), - Port: rule.Port, - Description: rule.Description, - }) - } - return f -} - -// PlacementGroupFromSchema converts a schema.PlacementGroup to a PlacementGroup. -func PlacementGroupFromSchema(s schema.PlacementGroup) *PlacementGroup { - g := &PlacementGroup{ - ID: s.ID, - Name: s.Name, - Labels: s.Labels, - Created: s.Created, - Servers: s.Servers, - Type: PlacementGroupType(s.Type), - } - return g -} - -func placementGroupCreateOptsToSchema(opts PlacementGroupCreateOpts) schema.PlacementGroupCreateRequest { - req := schema.PlacementGroupCreateRequest{ - Name: opts.Name, - Type: string(opts.Type), - } - if opts.Labels != nil { - req.Labels = &opts.Labels - } - return req -} - -func loadBalancerCreateOptsToSchema(opts LoadBalancerCreateOpts) schema.LoadBalancerCreateRequest { - req := schema.LoadBalancerCreateRequest{ - Name: opts.Name, - PublicInterface: opts.PublicInterface, - } - if opts.Algorithm != nil { - req.Algorithm = &schema.LoadBalancerCreateRequestAlgorithm{ - Type: string(opts.Algorithm.Type), - } - } - if opts.LoadBalancerType.ID != 0 { - req.LoadBalancerType = opts.LoadBalancerType.ID - } else if opts.LoadBalancerType.Name != "" { - req.LoadBalancerType = opts.LoadBalancerType.Name - } - if opts.Location != nil { - if opts.Location.ID != 0 { - req.Location = Ptr(strconv.Itoa(opts.Location.ID)) - } else { - req.Location = Ptr(opts.Location.Name) - } - } - if opts.NetworkZone != "" { - req.NetworkZone = Ptr(string(opts.NetworkZone)) - } - if opts.Labels != nil { - req.Labels = &opts.Labels - } - if opts.Network != nil { - req.Network = Ptr(opts.Network.ID) - } - for _, target := range opts.Targets { - schemaTarget := schema.LoadBalancerCreateRequestTarget{ - UsePrivateIP: target.UsePrivateIP, - } - switch target.Type { - case LoadBalancerTargetTypeServer: - schemaTarget.Type = string(LoadBalancerTargetTypeServer) - schemaTarget.Server = &schema.LoadBalancerCreateRequestTargetServer{ID: target.Server.Server.ID} - case LoadBalancerTargetTypeLabelSelector: - schemaTarget.Type = string(LoadBalancerTargetTypeLabelSelector) - schemaTarget.LabelSelector = &schema.LoadBalancerCreateRequestTargetLabelSelector{Selector: target.LabelSelector.Selector} - case LoadBalancerTargetTypeIP: - schemaTarget.Type = string(LoadBalancerTargetTypeIP) - schemaTarget.IP = &schema.LoadBalancerCreateRequestTargetIP{IP: target.IP.IP} - } - req.Targets = append(req.Targets, schemaTarget) - } - for _, service := range opts.Services { - schemaService := schema.LoadBalancerCreateRequestService{ - Protocol: string(service.Protocol), - ListenPort: service.ListenPort, - DestinationPort: service.DestinationPort, - Proxyprotocol: service.Proxyprotocol, - } - if service.HTTP != nil { - schemaService.HTTP = &schema.LoadBalancerCreateRequestServiceHTTP{ - RedirectHTTP: service.HTTP.RedirectHTTP, - StickySessions: service.HTTP.StickySessions, - CookieName: service.HTTP.CookieName, - } - if service.HTTP.CookieLifetime != nil { - if sec := service.HTTP.CookieLifetime.Seconds(); sec != 0 { - schemaService.HTTP.CookieLifetime = Ptr(int(sec)) - } - } - if service.HTTP.Certificates != nil { - certificates := []int{} - for _, certificate := range service.HTTP.Certificates { - certificates = append(certificates, certificate.ID) - } - schemaService.HTTP.Certificates = &certificates - } - } - if service.HealthCheck != nil { - schemaHealthCheck := &schema.LoadBalancerCreateRequestServiceHealthCheck{ - Protocol: string(service.HealthCheck.Protocol), - Port: service.HealthCheck.Port, - Retries: service.HealthCheck.Retries, - } - if service.HealthCheck.Interval != nil { - schemaHealthCheck.Interval = Ptr(int(service.HealthCheck.Interval.Seconds())) - } - if service.HealthCheck.Timeout != nil { - schemaHealthCheck.Timeout = Ptr(int(service.HealthCheck.Timeout.Seconds())) - } - if service.HealthCheck.HTTP != nil { - schemaHealthCheckHTTP := &schema.LoadBalancerCreateRequestServiceHealthCheckHTTP{ - Domain: service.HealthCheck.HTTP.Domain, - Path: service.HealthCheck.HTTP.Path, - Response: service.HealthCheck.HTTP.Response, - TLS: service.HealthCheck.HTTP.TLS, - } - if service.HealthCheck.HTTP.StatusCodes != nil { - schemaHealthCheckHTTP.StatusCodes = &service.HealthCheck.HTTP.StatusCodes - } - schemaHealthCheck.HTTP = schemaHealthCheckHTTP - } - schemaService.HealthCheck = schemaHealthCheck - } - req.Services = append(req.Services, schemaService) - } - return req -} - -func loadBalancerAddServiceOptsToSchema(opts LoadBalancerAddServiceOpts) schema.LoadBalancerActionAddServiceRequest { - req := schema.LoadBalancerActionAddServiceRequest{ - Protocol: string(opts.Protocol), - ListenPort: opts.ListenPort, - DestinationPort: opts.DestinationPort, - Proxyprotocol: opts.Proxyprotocol, - } - if opts.HTTP != nil { - req.HTTP = &schema.LoadBalancerActionAddServiceRequestHTTP{ - CookieName: opts.HTTP.CookieName, - RedirectHTTP: opts.HTTP.RedirectHTTP, - StickySessions: opts.HTTP.StickySessions, - } - if opts.HTTP.CookieLifetime != nil { - req.HTTP.CookieLifetime = Ptr(int(opts.HTTP.CookieLifetime.Seconds())) - } - if opts.HTTP.Certificates != nil { - certificates := []int{} - for _, certificate := range opts.HTTP.Certificates { - certificates = append(certificates, certificate.ID) - } - req.HTTP.Certificates = &certificates - } - } - if opts.HealthCheck != nil { - req.HealthCheck = &schema.LoadBalancerActionAddServiceRequestHealthCheck{ - Protocol: string(opts.HealthCheck.Protocol), - Port: opts.HealthCheck.Port, - Retries: opts.HealthCheck.Retries, - } - if opts.HealthCheck.Interval != nil { - req.HealthCheck.Interval = Ptr(int(opts.HealthCheck.Interval.Seconds())) - } - if opts.HealthCheck.Timeout != nil { - req.HealthCheck.Timeout = Ptr(int(opts.HealthCheck.Timeout.Seconds())) - } - if opts.HealthCheck.HTTP != nil { - req.HealthCheck.HTTP = &schema.LoadBalancerActionAddServiceRequestHealthCheckHTTP{ - Domain: opts.HealthCheck.HTTP.Domain, - Path: opts.HealthCheck.HTTP.Path, - Response: opts.HealthCheck.HTTP.Response, - TLS: opts.HealthCheck.HTTP.TLS, - } - if opts.HealthCheck.HTTP.StatusCodes != nil { - req.HealthCheck.HTTP.StatusCodes = &opts.HealthCheck.HTTP.StatusCodes - } - } - } - return req -} - -func loadBalancerUpdateServiceOptsToSchema(opts LoadBalancerUpdateServiceOpts) schema.LoadBalancerActionUpdateServiceRequest { - req := schema.LoadBalancerActionUpdateServiceRequest{ - DestinationPort: opts.DestinationPort, - Proxyprotocol: opts.Proxyprotocol, - } - if opts.Protocol != "" { - req.Protocol = Ptr(string(opts.Protocol)) - } - if opts.HTTP != nil { - req.HTTP = &schema.LoadBalancerActionUpdateServiceRequestHTTP{ - CookieName: opts.HTTP.CookieName, - RedirectHTTP: opts.HTTP.RedirectHTTP, - StickySessions: opts.HTTP.StickySessions, - } - if opts.HTTP.CookieLifetime != nil { - req.HTTP.CookieLifetime = Ptr(int(opts.HTTP.CookieLifetime.Seconds())) - } - if opts.HTTP.Certificates != nil { - certificates := []int{} - for _, certificate := range opts.HTTP.Certificates { - certificates = append(certificates, certificate.ID) - } - req.HTTP.Certificates = &certificates - } - } - if opts.HealthCheck != nil { - req.HealthCheck = &schema.LoadBalancerActionUpdateServiceRequestHealthCheck{ - Port: opts.HealthCheck.Port, - Retries: opts.HealthCheck.Retries, - } - if opts.HealthCheck.Interval != nil { - req.HealthCheck.Interval = Ptr(int(opts.HealthCheck.Interval.Seconds())) - } - if opts.HealthCheck.Timeout != nil { - req.HealthCheck.Timeout = Ptr(int(opts.HealthCheck.Timeout.Seconds())) - } - if opts.HealthCheck.Protocol != "" { - req.HealthCheck.Protocol = Ptr(string(opts.HealthCheck.Protocol)) - } - if opts.HealthCheck.HTTP != nil { - req.HealthCheck.HTTP = &schema.LoadBalancerActionUpdateServiceRequestHealthCheckHTTP{ - Domain: opts.HealthCheck.HTTP.Domain, - Path: opts.HealthCheck.HTTP.Path, - Response: opts.HealthCheck.HTTP.Response, - TLS: opts.HealthCheck.HTTP.TLS, - } - if opts.HealthCheck.HTTP.StatusCodes != nil { - req.HealthCheck.HTTP.StatusCodes = &opts.HealthCheck.HTTP.StatusCodes - } - } - } - return req -} - -func firewallCreateOptsToSchema(opts FirewallCreateOpts) schema.FirewallCreateRequest { - req := schema.FirewallCreateRequest{ - Name: opts.Name, - } - if opts.Labels != nil { - req.Labels = &opts.Labels - } - for _, rule := range opts.Rules { - schemaRule := schema.FirewallRule{ - Direction: string(rule.Direction), - Protocol: string(rule.Protocol), - Port: rule.Port, - Description: rule.Description, - } - switch rule.Direction { - case FirewallRuleDirectionOut: - schemaRule.DestinationIPs = make([]string, len(rule.DestinationIPs)) - for i, destinationIP := range rule.DestinationIPs { - schemaRule.DestinationIPs[i] = destinationIP.String() - } - case FirewallRuleDirectionIn: - schemaRule.SourceIPs = make([]string, len(rule.SourceIPs)) - for i, sourceIP := range rule.SourceIPs { - schemaRule.SourceIPs[i] = sourceIP.String() - } - } - req.Rules = append(req.Rules, schemaRule) - } - for _, res := range opts.ApplyTo { - schemaFirewallResource := schema.FirewallResource{ - Type: string(res.Type), - } - switch res.Type { - case FirewallResourceTypeServer: - schemaFirewallResource.Server = &schema.FirewallResourceServer{ - ID: res.Server.ID, - } - case FirewallResourceTypeLabelSelector: - schemaFirewallResource.LabelSelector = &schema.FirewallResourceLabelSelector{Selector: res.LabelSelector.Selector} - } - - req.ApplyTo = append(req.ApplyTo, schemaFirewallResource) - } - return req -} - -func firewallSetRulesOptsToSchema(opts FirewallSetRulesOpts) schema.FirewallActionSetRulesRequest { - req := schema.FirewallActionSetRulesRequest{Rules: []schema.FirewallRule{}} - for _, rule := range opts.Rules { - schemaRule := schema.FirewallRule{ - Direction: string(rule.Direction), - Protocol: string(rule.Protocol), - Port: rule.Port, - Description: rule.Description, - } - switch rule.Direction { - case FirewallRuleDirectionOut: - schemaRule.DestinationIPs = make([]string, len(rule.DestinationIPs)) - for i, destinationIP := range rule.DestinationIPs { - schemaRule.DestinationIPs[i] = destinationIP.String() - } - case FirewallRuleDirectionIn: - schemaRule.SourceIPs = make([]string, len(rule.SourceIPs)) - for i, sourceIP := range rule.SourceIPs { - schemaRule.SourceIPs[i] = sourceIP.String() - } - } - req.Rules = append(req.Rules, schemaRule) - } - return req -} - -func firewallResourceToSchema(resource FirewallResource) schema.FirewallResource { - s := schema.FirewallResource{ - Type: string(resource.Type), - } - switch resource.Type { - case FirewallResourceTypeLabelSelector: - s.LabelSelector = &schema.FirewallResourceLabelSelector{Selector: resource.LabelSelector.Selector} - case FirewallResourceTypeServer: - s.Server = &schema.FirewallResourceServer{ID: resource.Server.ID} - } - return s -} - -func serverMetricsFromSchema(s *schema.ServerGetMetricsResponse) (*ServerMetrics, error) { - ms := ServerMetrics{ - Start: s.Metrics.Start, - End: s.Metrics.End, - Step: s.Metrics.Step, - } - - timeSeries := make(map[string][]ServerMetricsValue) - for tsName, v := range s.Metrics.TimeSeries { - vals := make([]ServerMetricsValue, len(v.Values)) - - for i, rawVal := range v.Values { - var val ServerMetricsValue - - tup, ok := rawVal.([]interface{}) - if !ok { - return nil, fmt.Errorf("failed to convert value to tuple: %v", rawVal) - } - if len(tup) != 2 { - return nil, fmt.Errorf("invalid tuple size: %d: %v", len(tup), rawVal) - } - ts, ok := tup[0].(float64) - if !ok { - return nil, fmt.Errorf("convert to float64: %v", tup[0]) - } - val.Timestamp = ts - - v, ok := tup[1].(string) - if !ok { - return nil, fmt.Errorf("not a string: %v", tup[1]) - } - val.Value = v - vals[i] = val - } - - timeSeries[tsName] = vals - } - ms.TimeSeries = timeSeries - - return &ms, nil -} - -func loadBalancerMetricsFromSchema(s *schema.LoadBalancerGetMetricsResponse) (*LoadBalancerMetrics, error) { - ms := LoadBalancerMetrics{ - Start: s.Metrics.Start, - End: s.Metrics.End, - Step: s.Metrics.Step, - } - - timeSeries := make(map[string][]LoadBalancerMetricsValue) - for tsName, v := range s.Metrics.TimeSeries { - vals := make([]LoadBalancerMetricsValue, len(v.Values)) - - for i, rawVal := range v.Values { - var val LoadBalancerMetricsValue - - tup, ok := rawVal.([]interface{}) - if !ok { - return nil, fmt.Errorf("failed to convert value to tuple: %v", rawVal) - } - if len(tup) != 2 { - return nil, fmt.Errorf("invalid tuple size: %d: %v", len(tup), rawVal) - } - ts, ok := tup[0].(float64) - if !ok { - return nil, fmt.Errorf("convert to float64: %v", tup[0]) - } - val.Timestamp = ts - - v, ok := tup[1].(string) - if !ok { - return nil, fmt.Errorf("not a string: %v", tup[1]) - } - val.Value = v - vals[i] = val - } - - timeSeries[tsName] = vals - } - ms.TimeSeries = timeSeries - - return &ms, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/action.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/action.go deleted file mode 100644 index df4d7cf71..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/action.go +++ /dev/null @@ -1,39 +0,0 @@ -package schema - -import "time" - -// Action defines the schema of an action. -type Action struct { - ID int `json:"id"` - Status string `json:"status"` - Command string `json:"command"` - Progress int `json:"progress"` - Started time.Time `json:"started"` - Finished *time.Time `json:"finished"` - Error *ActionError `json:"error"` - Resources []ActionResourceReference `json:"resources"` -} - -// ActionResourceReference defines the schema of an action resource reference. -type ActionResourceReference struct { - ID int `json:"id"` - Type string `json:"type"` -} - -// ActionError defines the schema of an error embedded -// in an action. -type ActionError struct { - Code string `json:"code"` - Message string `json:"message"` -} - -// ActionGetResponse is the schema of the response when -// retrieving a single action. -type ActionGetResponse struct { - Action Action `json:"action"` -} - -// ActionListResponse defines the schema of the response when listing actions. -type ActionListResponse struct { - Actions []Action `json:"actions"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/certificate.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/certificate.go deleted file mode 100644 index a81b807a2..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/certificate.go +++ /dev/null @@ -1,76 +0,0 @@ -package schema - -import "time" - -// CertificateUsedByRef defines the schema of a resource using a certificate. -type CertificateUsedByRef struct { - ID int `json:"id"` - Type string `json:"type"` -} - -type CertificateStatusRef struct { - Issuance string `json:"issuance"` - Renewal string `json:"renewal"` - Error *Error `json:"error,omitempty"` -} - -// Certificate defines the schema of an certificate. -type Certificate struct { - ID int `json:"id"` - Name string `json:"name"` - Labels map[string]string `json:"labels"` - Type string `json:"type"` - Certificate string `json:"certificate"` - Created time.Time `json:"created"` - NotValidBefore time.Time `json:"not_valid_before"` - NotValidAfter time.Time `json:"not_valid_after"` - DomainNames []string `json:"domain_names"` - Fingerprint string `json:"fingerprint"` - Status *CertificateStatusRef `json:"status"` - UsedBy []CertificateUsedByRef `json:"used_by"` -} - -// CertificateListResponse defines the schema of the response when -// listing Certificates. -type CertificateListResponse struct { - Certificates []Certificate `json:"certificates"` -} - -// CertificateGetResponse defines the schema of the response when -// retrieving a single Certificate. -type CertificateGetResponse struct { - Certificate Certificate `json:"certificate"` -} - -// CertificateCreateRequest defines the schema of the request to create a certificate. -type CertificateCreateRequest struct { - Name string `json:"name"` - Type string `json:"type"` - DomainNames []string `json:"domain_names,omitempty"` - Certificate string `json:"certificate,omitempty"` - PrivateKey string `json:"private_key,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// CertificateCreateResponse defines the schema of the response when creating a certificate. -type CertificateCreateResponse struct { - Certificate Certificate `json:"certificate"` - Action *Action `json:"action"` -} - -// CertificateUpdateRequest defines the schema of the request to update a certificate. -type CertificateUpdateRequest struct { - Name *string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// CertificateUpdateResponse defines the schema of the response when updating a certificate. -type CertificateUpdateResponse struct { - Certificate Certificate `json:"certificate"` -} - -// CertificateIssuanceRetryResponse defines the schema for the response of the -// retry issuance endpoint. -type CertificateIssuanceRetryResponse struct { - Action Action `json:"action"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/datacenter.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/datacenter.go deleted file mode 100644 index 3e8178e89..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/datacenter.go +++ /dev/null @@ -1,23 +0,0 @@ -package schema - -// Datacenter defines the schema of a datacenter. -type Datacenter struct { - ID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Location Location `json:"location"` - ServerTypes struct { - Supported []int `json:"supported"` - Available []int `json:"available"` - } `json:"server_types"` -} - -// DatacenterGetResponse defines the schema of the response when retrieving a single datacenter. -type DatacenterGetResponse struct { - Datacenter Datacenter `json:"datacenter"` -} - -// DatacenterListResponse defines the schema of the response when listing datacenters. -type DatacenterListResponse struct { - Datacenters []Datacenter `json:"datacenters"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/firewall.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/firewall.go deleted file mode 100644 index b085bbb13..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/firewall.go +++ /dev/null @@ -1,105 +0,0 @@ -package schema - -import "time" - -// Firewall defines the schema of a Firewall. -type Firewall struct { - ID int `json:"id"` - Name string `json:"name"` - Labels map[string]string `json:"labels"` - Created time.Time `json:"created"` - Rules []FirewallRule `json:"rules"` - AppliedTo []FirewallResource `json:"applied_to"` -} - -// FirewallRule defines the schema of a Firewall rule. -type FirewallRule struct { - Direction string `json:"direction"` - SourceIPs []string `json:"source_ips,omitempty"` - DestinationIPs []string `json:"destination_ips,omitempty"` - Protocol string `json:"protocol"` - Port *string `json:"port,omitempty"` - Description *string `json:"description,omitempty"` -} - -// FirewallListResponse defines the schema of the response when listing Firewalls. -type FirewallListResponse struct { - Firewalls []Firewall `json:"firewalls"` -} - -// FirewallGetResponse defines the schema of the response when retrieving a single Firewall. -type FirewallGetResponse struct { - Firewall Firewall `json:"firewall"` -} - -// FirewallCreateRequest defines the schema of the request to create a Firewall. -type FirewallCreateRequest struct { - Name string `json:"name"` - Labels *map[string]string `json:"labels,omitempty"` - Rules []FirewallRule `json:"rules,omitempty"` - ApplyTo []FirewallResource `json:"apply_to,omitempty"` -} - -// FirewallResource defines the schema of a resource to apply the new Firewall on. -type FirewallResource struct { - Type string `json:"type"` - Server *FirewallResourceServer `json:"server,omitempty"` - LabelSelector *FirewallResourceLabelSelector `json:"label_selector,omitempty"` -} - -// FirewallResourceLabelSelector defines the schema of a LabelSelector to apply a Firewall on. -type FirewallResourceLabelSelector struct { - Selector string `json:"selector"` -} - -// FirewallResourceServer defines the schema of a Server to apply a Firewall on. -type FirewallResourceServer struct { - ID int `json:"id"` -} - -// FirewallCreateResponse defines the schema of the response when creating a Firewall. -type FirewallCreateResponse struct { - Firewall Firewall `json:"firewall"` - Actions []Action `json:"actions"` -} - -// FirewallUpdateRequest defines the schema of the request to update a Firewall. -type FirewallUpdateRequest struct { - Name *string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// FirewallUpdateResponse defines the schema of the response when updating a Firewall. -type FirewallUpdateResponse struct { - Firewall Firewall `json:"firewall"` -} - -// FirewallActionSetRulesRequest defines the schema of the request when setting Firewall rules. -type FirewallActionSetRulesRequest struct { - Rules []FirewallRule `json:"rules"` -} - -// FirewallActionSetRulesResponse defines the schema of the response when setting Firewall rules. -type FirewallActionSetRulesResponse struct { - Actions []Action `json:"actions"` -} - -// FirewallActionApplyToResourcesRequest defines the schema of the request when applying a Firewall on resources. -type FirewallActionApplyToResourcesRequest struct { - ApplyTo []FirewallResource `json:"apply_to"` -} - -// FirewallActionApplyToResourcesResponse defines the schema of the response when applying a Firewall on resources. -type FirewallActionApplyToResourcesResponse struct { - Actions []Action `json:"actions"` -} - -// FirewallActionRemoveFromResourcesRequest defines the schema of the request when removing a Firewall from resources. -type FirewallActionRemoveFromResourcesRequest struct { - RemoveFrom []FirewallResource `json:"remove_from"` -} - -// FirewallActionRemoveFromResourcesResponse defines the schema of the response when removing a Firewall from resources. -type FirewallActionRemoveFromResourcesResponse struct { - Actions []Action `json:"actions"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/floating_ip.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/floating_ip.go deleted file mode 100644 index 37295dad9..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/floating_ip.go +++ /dev/null @@ -1,118 +0,0 @@ -package schema - -import "time" - -// FloatingIP defines the schema of a Floating IP. -type FloatingIP struct { - ID int `json:"id"` - Description *string `json:"description"` - Created time.Time `json:"created"` - IP string `json:"ip"` - Type string `json:"type"` - Server *int `json:"server"` - DNSPtr []FloatingIPDNSPtr `json:"dns_ptr"` - HomeLocation Location `json:"home_location"` - Blocked bool `json:"blocked"` - Protection FloatingIPProtection `json:"protection"` - Labels map[string]string `json:"labels"` - Name string `json:"name"` -} - -// FloatingIPProtection represents the protection level of a Floating IP. -type FloatingIPProtection struct { - Delete bool `json:"delete"` -} - -// FloatingIPDNSPtr contains reverse DNS information for a -// IPv4 or IPv6 Floating IP. -type FloatingIPDNSPtr struct { - IP string `json:"ip"` - DNSPtr string `json:"dns_ptr"` -} - -// FloatingIPGetResponse defines the schema of the response when -// retrieving a single Floating IP. -type FloatingIPGetResponse struct { - FloatingIP FloatingIP `json:"floating_ip"` -} - -// FloatingIPUpdateRequest defines the schema of the request to update a Floating IP. -type FloatingIPUpdateRequest struct { - Description string `json:"description,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` - Name string `json:"name,omitempty"` -} - -// FloatingIPUpdateResponse defines the schema of the response when updating a Floating IP. -type FloatingIPUpdateResponse struct { - FloatingIP FloatingIP `json:"floating_ip"` -} - -// FloatingIPListResponse defines the schema of the response when -// listing Floating IPs. -type FloatingIPListResponse struct { - FloatingIPs []FloatingIP `json:"floating_ips"` -} - -// FloatingIPCreateRequest defines the schema of the request to -// create a Floating IP. -type FloatingIPCreateRequest struct { - Type string `json:"type"` - HomeLocation *string `json:"home_location,omitempty"` - Server *int `json:"server,omitempty"` - Description *string `json:"description,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` - Name *string `json:"name,omitempty"` -} - -// FloatingIPCreateResponse defines the schema of the response -// when creating a Floating IP. -type FloatingIPCreateResponse struct { - FloatingIP FloatingIP `json:"floating_ip"` - Action *Action `json:"action"` -} - -// FloatingIPActionAssignRequest defines the schema of the request to -// create an assign Floating IP action. -type FloatingIPActionAssignRequest struct { - Server int `json:"server"` -} - -// FloatingIPActionAssignResponse defines the schema of the response when -// creating an assign action. -type FloatingIPActionAssignResponse struct { - Action Action `json:"action"` -} - -// FloatingIPActionUnassignRequest defines the schema of the request to -// create an unassign Floating IP action. -type FloatingIPActionUnassignRequest struct{} - -// FloatingIPActionUnassignResponse defines the schema of the response when -// creating an unassign action. -type FloatingIPActionUnassignResponse struct { - Action Action `json:"action"` -} - -// FloatingIPActionChangeDNSPtrRequest defines the schema for the request to -// change a Floating IP's reverse DNS pointer. -type FloatingIPActionChangeDNSPtrRequest struct { - IP string `json:"ip"` - DNSPtr *string `json:"dns_ptr"` -} - -// FloatingIPActionChangeDNSPtrResponse defines the schema of the response when -// creating a change_dns_ptr Floating IP action. -type FloatingIPActionChangeDNSPtrResponse struct { - Action Action `json:"action"` -} - -// FloatingIPActionChangeProtectionRequest defines the schema of the request to change the resource protection of a Floating IP. -type FloatingIPActionChangeProtectionRequest struct { - Delete *bool `json:"delete,omitempty"` -} - -// FloatingIPActionChangeProtectionResponse defines the schema of the response when changing the resource protection of a Floating IP. -type FloatingIPActionChangeProtectionResponse struct { - Action Action `json:"action"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/image.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/image.go deleted file mode 100644 index 76775b131..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/image.go +++ /dev/null @@ -1,70 +0,0 @@ -package schema - -import "time" - -// Image defines the schema of an image. -type Image struct { - ID int `json:"id"` - Status string `json:"status"` - Type string `json:"type"` - Name *string `json:"name"` - Description string `json:"description"` - ImageSize *float32 `json:"image_size"` - DiskSize float32 `json:"disk_size"` - Created time.Time `json:"created"` - CreatedFrom *ImageCreatedFrom `json:"created_from"` - BoundTo *int `json:"bound_to"` - OSFlavor string `json:"os_flavor"` - OSVersion *string `json:"os_version"` - Architecture string `json:"architecture"` - RapidDeploy bool `json:"rapid_deploy"` - Protection ImageProtection `json:"protection"` - Deprecated time.Time `json:"deprecated"` - Deleted time.Time `json:"deleted"` - Labels map[string]string `json:"labels"` -} - -// ImageProtection represents the protection level of a image. -type ImageProtection struct { - Delete bool `json:"delete"` -} - -// ImageCreatedFrom defines the schema of the images created from reference. -type ImageCreatedFrom struct { - ID int `json:"id"` - Name string `json:"name"` -} - -// ImageGetResponse defines the schema of the response when -// retrieving a single image. -type ImageGetResponse struct { - Image Image `json:"image"` -} - -// ImageListResponse defines the schema of the response when -// listing images. -type ImageListResponse struct { - Images []Image `json:"images"` -} - -// ImageUpdateRequest defines the schema of the request to update an image. -type ImageUpdateRequest struct { - Description *string `json:"description,omitempty"` - Type *string `json:"type,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// ImageUpdateResponse defines the schema of the response when updating an image. -type ImageUpdateResponse struct { - Image Image `json:"image"` -} - -// ImageActionChangeProtectionRequest defines the schema of the request to change the resource protection of an image. -type ImageActionChangeProtectionRequest struct { - Delete *bool `json:"delete,omitempty"` -} - -// ImageActionChangeProtectionResponse defines the schema of the response when changing the resource protection of an image. -type ImageActionChangeProtectionResponse struct { - Action Action `json:"action"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/iso.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/iso.go deleted file mode 100644 index dfcc4e347..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/iso.go +++ /dev/null @@ -1,23 +0,0 @@ -package schema - -import "time" - -// ISO defines the schema of an ISO image. -type ISO struct { - ID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Type string `json:"type"` - Architecture *string `json:"architecture"` - Deprecated time.Time `json:"deprecated"` -} - -// ISOGetResponse defines the schema of the response when retrieving a single ISO. -type ISOGetResponse struct { - ISO ISO `json:"iso"` -} - -// ISOListResponse defines the schema of the response when listing ISOs. -type ISOListResponse struct { - ISOs []ISO `json:"isos"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/load_balancer.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/load_balancer.go deleted file mode 100644 index 68adf5eb6..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/load_balancer.go +++ /dev/null @@ -1,418 +0,0 @@ -package schema - -import "time" - -type LoadBalancer struct { - ID int `json:"id"` - Name string `json:"name"` - PublicNet LoadBalancerPublicNet `json:"public_net"` - PrivateNet []LoadBalancerPrivateNet `json:"private_net"` - Location Location `json:"location"` - LoadBalancerType LoadBalancerType `json:"load_balancer_type"` - Protection LoadBalancerProtection `json:"protection"` - Labels map[string]string `json:"labels"` - Created time.Time `json:"created"` - Services []LoadBalancerService `json:"services"` - Targets []LoadBalancerTarget `json:"targets"` - Algorithm LoadBalancerAlgorithm `json:"algorithm"` - IncludedTraffic uint64 `json:"included_traffic"` - OutgoingTraffic *uint64 `json:"outgoing_traffic"` - IngoingTraffic *uint64 `json:"ingoing_traffic"` -} - -type LoadBalancerPublicNet struct { - Enabled bool `json:"enabled"` - IPv4 LoadBalancerPublicNetIPv4 `json:"ipv4"` - IPv6 LoadBalancerPublicNetIPv6 `json:"ipv6"` -} - -type LoadBalancerPublicNetIPv4 struct { - IP string `json:"ip"` - DNSPtr string `json:"dns_ptr"` -} - -type LoadBalancerPublicNetIPv6 struct { - IP string `json:"ip"` - DNSPtr string `json:"dns_ptr"` -} - -type LoadBalancerPrivateNet struct { - Network int `json:"network"` - IP string `json:"ip"` -} - -type LoadBalancerAlgorithm struct { - Type string `json:"type"` -} - -type LoadBalancerProtection struct { - Delete bool `json:"delete"` -} - -type LoadBalancerService struct { - Protocol string `json:"protocol"` - ListenPort int `json:"listen_port"` - DestinationPort int `json:"destination_port"` - Proxyprotocol bool `json:"proxyprotocol"` - HTTP *LoadBalancerServiceHTTP `json:"http"` - HealthCheck *LoadBalancerServiceHealthCheck `json:"health_check"` -} - -type LoadBalancerServiceHTTP struct { - CookieName string `json:"cookie_name"` - CookieLifetime int `json:"cookie_lifetime"` - Certificates []int `json:"certificates"` - RedirectHTTP bool `json:"redirect_http"` - StickySessions bool `json:"sticky_sessions"` -} - -type LoadBalancerServiceHealthCheck struct { - Protocol string `json:"protocol"` - Port int `json:"port"` - Interval int `json:"interval"` - Timeout int `json:"timeout"` - Retries int `json:"retries"` - HTTP *LoadBalancerServiceHealthCheckHTTP `json:"http"` -} - -type LoadBalancerServiceHealthCheckHTTP struct { - Domain string `json:"domain"` - Path string `json:"path"` - Response string `json:"response"` - StatusCodes []string `json:"status_codes"` - TLS bool `json:"tls"` -} - -type LoadBalancerTarget struct { - Type string `json:"type"` - Server *LoadBalancerTargetServer `json:"server"` - LabelSelector *LoadBalancerTargetLabelSelector `json:"label_selector"` - IP *LoadBalancerTargetIP `json:"ip"` - HealthStatus []LoadBalancerTargetHealthStatus `json:"health_status"` - UsePrivateIP bool `json:"use_private_ip"` - Targets []LoadBalancerTarget `json:"targets,omitempty"` -} - -type LoadBalancerTargetHealthStatus struct { - ListenPort int `json:"listen_port"` - Status string `json:"status"` -} - -type LoadBalancerTargetServer struct { - ID int `json:"id"` -} - -type LoadBalancerTargetLabelSelector struct { - Selector string `json:"selector"` -} - -type LoadBalancerTargetIP struct { - IP string `json:"ip"` -} - -type LoadBalancerListResponse struct { - LoadBalancers []LoadBalancer `json:"load_balancers"` -} - -type LoadBalancerGetResponse struct { - LoadBalancer LoadBalancer `json:"load_balancer"` -} - -type LoadBalancerActionAddTargetRequest struct { - Type string `json:"type"` - Server *LoadBalancerActionAddTargetRequestServer `json:"server,omitempty"` - LabelSelector *LoadBalancerActionAddTargetRequestLabelSelector `json:"label_selector,omitempty"` - IP *LoadBalancerActionAddTargetRequestIP `json:"ip,omitempty"` - UsePrivateIP *bool `json:"use_private_ip,omitempty"` -} - -type LoadBalancerActionAddTargetRequestServer struct { - ID int `json:"id"` -} - -type LoadBalancerActionAddTargetRequestLabelSelector struct { - Selector string `json:"selector"` -} - -type LoadBalancerActionAddTargetRequestIP struct { - IP string `json:"ip"` -} - -type LoadBalancerActionAddTargetResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionRemoveTargetRequest struct { - Type string `json:"type"` - Server *LoadBalancerActionRemoveTargetRequestServer `json:"server,omitempty"` - LabelSelector *LoadBalancerActionRemoveTargetRequestLabelSelector `json:"label_selector,omitempty"` - IP *LoadBalancerActionRemoveTargetRequestIP `json:"ip,omitempty"` -} - -type LoadBalancerActionRemoveTargetRequestServer struct { - ID int `json:"id"` -} - -type LoadBalancerActionRemoveTargetRequestLabelSelector struct { - Selector string `json:"selector"` -} - -type LoadBalancerActionRemoveTargetRequestIP struct { - IP string `json:"ip"` -} - -type LoadBalancerActionRemoveTargetResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionAddServiceRequest struct { - Protocol string `json:"protocol"` - ListenPort *int `json:"listen_port,omitempty"` - DestinationPort *int `json:"destination_port,omitempty"` - Proxyprotocol *bool `json:"proxyprotocol,omitempty"` - HTTP *LoadBalancerActionAddServiceRequestHTTP `json:"http,omitempty"` - HealthCheck *LoadBalancerActionAddServiceRequestHealthCheck `json:"health_check,omitempty"` -} - -type LoadBalancerActionAddServiceRequestHTTP struct { - CookieName *string `json:"cookie_name,omitempty"` - CookieLifetime *int `json:"cookie_lifetime,omitempty"` - Certificates *[]int `json:"certificates,omitempty"` - RedirectHTTP *bool `json:"redirect_http,omitempty"` - StickySessions *bool `json:"sticky_sessions,omitempty"` -} - -type LoadBalancerActionAddServiceRequestHealthCheck struct { - Protocol string `json:"protocol"` - Port *int `json:"port,omitempty"` - Interval *int `json:"interval,omitempty"` - Timeout *int `json:"timeout,omitempty"` - Retries *int `json:"retries,omitempty"` - HTTP *LoadBalancerActionAddServiceRequestHealthCheckHTTP `json:"http,omitempty"` -} - -type LoadBalancerActionAddServiceRequestHealthCheckHTTP struct { - Domain *string `json:"domain,omitempty"` - Path *string `json:"path,omitempty"` - Response *string `json:"response,omitempty"` - StatusCodes *[]string `json:"status_codes,omitempty"` - TLS *bool `json:"tls,omitempty"` -} - -type LoadBalancerActionAddServiceResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionUpdateServiceRequest struct { - ListenPort int `json:"listen_port"` - Protocol *string `json:"protocol,omitempty"` - DestinationPort *int `json:"destination_port,omitempty"` - Proxyprotocol *bool `json:"proxyprotocol,omitempty"` - HTTP *LoadBalancerActionUpdateServiceRequestHTTP `json:"http,omitempty"` - HealthCheck *LoadBalancerActionUpdateServiceRequestHealthCheck `json:"health_check,omitempty"` -} - -type LoadBalancerActionUpdateServiceRequestHTTP struct { - CookieName *string `json:"cookie_name,omitempty"` - CookieLifetime *int `json:"cookie_lifetime,omitempty"` - Certificates *[]int `json:"certificates,omitempty"` - RedirectHTTP *bool `json:"redirect_http,omitempty"` - StickySessions *bool `json:"sticky_sessions,omitempty"` -} - -type LoadBalancerActionUpdateServiceRequestHealthCheck struct { - Protocol *string `json:"protocol,omitempty"` - Port *int `json:"port,omitempty"` - Interval *int `json:"interval,omitempty"` - Timeout *int `json:"timeout,omitempty"` - Retries *int `json:"retries,omitempty"` - HTTP *LoadBalancerActionUpdateServiceRequestHealthCheckHTTP `json:"http,omitempty"` -} - -type LoadBalancerActionUpdateServiceRequestHealthCheckHTTP struct { - Domain *string `json:"domain,omitempty"` - Path *string `json:"path,omitempty"` - Response *string `json:"response,omitempty"` - StatusCodes *[]string `json:"status_codes,omitempty"` - TLS *bool `json:"tls,omitempty"` -} - -type LoadBalancerActionUpdateServiceResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerDeleteServiceRequest struct { - ListenPort int `json:"listen_port"` -} - -type LoadBalancerDeleteServiceResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerCreateRequest struct { - Name string `json:"name"` - LoadBalancerType interface{} `json:"load_balancer_type"` // int or string - Algorithm *LoadBalancerCreateRequestAlgorithm `json:"algorithm,omitempty"` - Location *string `json:"location,omitempty"` - NetworkZone *string `json:"network_zone,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` - Targets []LoadBalancerCreateRequestTarget `json:"targets,omitempty"` - Services []LoadBalancerCreateRequestService `json:"services,omitempty"` - PublicInterface *bool `json:"public_interface,omitempty"` - Network *int `json:"network,omitempty"` -} - -type LoadBalancerCreateRequestAlgorithm struct { - Type string `json:"type"` -} - -type LoadBalancerCreateRequestTarget struct { - Type string `json:"type"` - Server *LoadBalancerCreateRequestTargetServer `json:"server,omitempty"` - LabelSelector *LoadBalancerCreateRequestTargetLabelSelector `json:"label_selector,omitempty"` - IP *LoadBalancerCreateRequestTargetIP `json:"ip,omitempty"` - UsePrivateIP *bool `json:"use_private_ip,omitempty"` -} - -type LoadBalancerCreateRequestTargetServer struct { - ID int `json:"id"` -} - -type LoadBalancerCreateRequestTargetLabelSelector struct { - Selector string `json:"selector"` -} - -type LoadBalancerCreateRequestTargetIP struct { - IP string `json:"ip"` -} - -type LoadBalancerCreateRequestService struct { - Protocol string `json:"protocol"` - ListenPort *int `json:"listen_port,omitempty"` - DestinationPort *int `json:"destination_port,omitempty"` - Proxyprotocol *bool `json:"proxyprotocol,omitempty"` - HTTP *LoadBalancerCreateRequestServiceHTTP `json:"http,omitempty"` - HealthCheck *LoadBalancerCreateRequestServiceHealthCheck `json:"health_check,omitempty"` -} - -type LoadBalancerCreateRequestServiceHTTP struct { - CookieName *string `json:"cookie_name,omitempty"` - CookieLifetime *int `json:"cookie_lifetime,omitempty"` - Certificates *[]int `json:"certificates,omitempty"` - RedirectHTTP *bool `json:"redirect_http,omitempty"` - StickySessions *bool `json:"sticky_sessions,omitempty"` -} - -type LoadBalancerCreateRequestServiceHealthCheck struct { - Protocol string `json:"protocol"` - Port *int `json:"port,omitempty"` - Interval *int `json:"interval,omitempty"` - Timeout *int `json:"timeout,omitempty"` - Retries *int `json:"retries,omitempty"` - HTTP *LoadBalancerCreateRequestServiceHealthCheckHTTP `json:"http,omitempty"` -} - -type LoadBalancerCreateRequestServiceHealthCheckHTTP struct { - Domain *string `json:"domain,omitempty"` - Path *string `json:"path,omitempty"` - Response *string `json:"response,omitempty"` - StatusCodes *[]string `json:"status_codes,omitempty"` - TLS *bool `json:"tls,omitempty"` -} - -type LoadBalancerCreateResponse struct { - LoadBalancer LoadBalancer `json:"load_balancer"` - Action Action `json:"action"` -} - -type LoadBalancerActionChangeProtectionRequest struct { - Delete *bool `json:"delete,omitempty"` -} - -type LoadBalancerActionChangeProtectionResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerUpdateRequest struct { - Name *string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -type LoadBalancerUpdateResponse struct { - LoadBalancer LoadBalancer `json:"load_balancer"` -} - -type LoadBalancerActionChangeAlgorithmRequest struct { - Type string `json:"type"` -} - -type LoadBalancerActionChangeAlgorithmResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionAttachToNetworkRequest struct { - Network int `json:"network"` - IP *string `json:"ip,omitempty"` -} - -type LoadBalancerActionAttachToNetworkResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionDetachFromNetworkRequest struct { - Network int `json:"network"` -} - -type LoadBalancerActionDetachFromNetworkResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionEnablePublicInterfaceRequest struct{} - -type LoadBalancerActionEnablePublicInterfaceResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionDisablePublicInterfaceRequest struct{} - -type LoadBalancerActionDisablePublicInterfaceResponse struct { - Action Action `json:"action"` -} - -type LoadBalancerActionChangeTypeRequest struct { - LoadBalancerType interface{} `json:"load_balancer_type"` // int or string -} - -type LoadBalancerActionChangeTypeResponse struct { - Action Action `json:"action"` -} - -// LoadBalancerGetMetricsResponse defines the schema of the response when -// requesting metrics for a Load Balancer. -type LoadBalancerGetMetricsResponse struct { - Metrics struct { - Start time.Time `json:"start"` - End time.Time `json:"end"` - Step float64 `json:"step"` - TimeSeries map[string]LoadBalancerTimeSeriesVals `json:"time_series"` - } `json:"metrics"` -} - -// LoadBalancerTimeSeriesVals contains the values for a Load Balancer time -// series. -type LoadBalancerTimeSeriesVals struct { - Values []interface{} `json:"values"` -} - -// LoadBalancerActionChangeDNSPtrRequest defines the schema for the request to -// change a Load Balancer reverse DNS pointer. -type LoadBalancerActionChangeDNSPtrRequest struct { - IP string `json:"ip"` - DNSPtr *string `json:"dns_ptr"` -} - -// LoadBalancerActionChangeDNSPtrResponse defines the schema of the response when -// creating a change_dns_ptr Floating IP action. -type LoadBalancerActionChangeDNSPtrResponse struct { - Action Action `json:"action"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/load_balancer_type.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/load_balancer_type.go deleted file mode 100644 index b0baf0489..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/load_balancer_type.go +++ /dev/null @@ -1,25 +0,0 @@ -package schema - -// LoadBalancerType defines the schema of a LoadBalancer type. -type LoadBalancerType struct { - ID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - MaxConnections int `json:"max_connections"` - MaxServices int `json:"max_services"` - MaxTargets int `json:"max_targets"` - MaxAssignedCertificates int `json:"max_assigned_certificates"` - Prices []PricingLoadBalancerTypePrice `json:"prices"` -} - -// LoadBalancerTypeListResponse defines the schema of the response when -// listing LoadBalancer types. -type LoadBalancerTypeListResponse struct { - LoadBalancerTypes []LoadBalancerType `json:"load_balancer_types"` -} - -// LoadBalancerTypeGetResponse defines the schema of the response when -// retrieving a single LoadBalancer type. -type LoadBalancerTypeGetResponse struct { - LoadBalancerType LoadBalancerType `json:"load_balancer_type"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/location.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/location.go deleted file mode 100644 index 3dd58ad5e..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/location.go +++ /dev/null @@ -1,23 +0,0 @@ -package schema - -// Location defines the schema of a location. -type Location struct { - ID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Country string `json:"country"` - City string `json:"city"` - Latitude float64 `json:"latitude"` - Longitude float64 `json:"longitude"` - NetworkZone string `json:"network_zone"` -} - -// LocationGetResponse defines the schema of the response when retrieving a single location. -type LocationGetResponse struct { - Location Location `json:"location"` -} - -// LocationListResponse defines the schema of the response when listing locations. -type LocationListResponse struct { - Locations []Location `json:"locations"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/network.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/network.go deleted file mode 100644 index 87e184d95..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/network.go +++ /dev/null @@ -1,152 +0,0 @@ -package schema - -import "time" - -// Network defines the schema of a network. -type Network struct { - ID int `json:"id"` - Name string `json:"name"` - Created time.Time `json:"created"` - IPRange string `json:"ip_range"` - Subnets []NetworkSubnet `json:"subnets"` - Routes []NetworkRoute `json:"routes"` - Servers []int `json:"servers"` - Protection NetworkProtection `json:"protection"` - Labels map[string]string `json:"labels"` -} - -// NetworkSubnet represents a subnet of a network. -type NetworkSubnet struct { - Type string `json:"type"` - IPRange string `json:"ip_range"` - NetworkZone string `json:"network_zone"` - Gateway string `json:"gateway,omitempty"` - VSwitchID int `json:"vswitch_id,omitempty"` -} - -// NetworkRoute represents a route of a network. -type NetworkRoute struct { - Destination string `json:"destination"` - Gateway string `json:"gateway"` -} - -// NetworkProtection represents the protection level of a network. -type NetworkProtection struct { - Delete bool `json:"delete"` -} - -// NetworkUpdateRequest defines the schema of the request to update a network. -type NetworkUpdateRequest struct { - Name string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// NetworkUpdateResponse defines the schema of the response when updating a network. -type NetworkUpdateResponse struct { - Network Network `json:"network"` -} - -// NetworkListResponse defines the schema of the response when -// listing networks. -type NetworkListResponse struct { - Networks []Network `json:"networks"` -} - -// NetworkGetResponse defines the schema of the response when -// retrieving a single network. -type NetworkGetResponse struct { - Network Network `json:"network"` -} - -// NetworkCreateRequest defines the schema of the request to create a network. -type NetworkCreateRequest struct { - Name string `json:"name"` - IPRange string `json:"ip_range"` - Subnets []NetworkSubnet `json:"subnets,omitempty"` - Routes []NetworkRoute `json:"routes,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// NetworkCreateResponse defines the schema of the response when -// creating a network. -type NetworkCreateResponse struct { - Network Network `json:"network"` -} - -// NetworkActionChangeIPRangeRequest defines the schema of the request to -// change the IP range of a network. -type NetworkActionChangeIPRangeRequest struct { - IPRange string `json:"ip_range"` -} - -// NetworkActionChangeIPRangeResponse defines the schema of the response when -// changing the IP range of a network. -type NetworkActionChangeIPRangeResponse struct { - Action Action `json:"action"` -} - -// NetworkActionAddSubnetRequest defines the schema of the request to -// add a subnet to a network. -type NetworkActionAddSubnetRequest struct { - Type string `json:"type"` - IPRange string `json:"ip_range,omitempty"` - NetworkZone string `json:"network_zone"` - Gateway string `json:"gateway"` - VSwitchID int `json:"vswitch_id,omitempty"` -} - -// NetworkActionAddSubnetResponse defines the schema of the response when -// adding a subnet to a network. -type NetworkActionAddSubnetResponse struct { - Action Action `json:"action"` -} - -// NetworkActionDeleteSubnetRequest defines the schema of the request to -// delete a subnet from a network. -type NetworkActionDeleteSubnetRequest struct { - IPRange string `json:"ip_range"` -} - -// NetworkActionDeleteSubnetResponse defines the schema of the response when -// deleting a subnet from a network. -type NetworkActionDeleteSubnetResponse struct { - Action Action `json:"action"` -} - -// NetworkActionAddRouteRequest defines the schema of the request to -// add a route to a network. -type NetworkActionAddRouteRequest struct { - Destination string `json:"destination"` - Gateway string `json:"gateway"` -} - -// NetworkActionAddRouteResponse defines the schema of the response when -// adding a route to a network. -type NetworkActionAddRouteResponse struct { - Action Action `json:"action"` -} - -// NetworkActionDeleteRouteRequest defines the schema of the request to -// delete a route from a network. -type NetworkActionDeleteRouteRequest struct { - Destination string `json:"destination"` - Gateway string `json:"gateway"` -} - -// NetworkActionDeleteRouteResponse defines the schema of the response when -// deleting a route from a network. -type NetworkActionDeleteRouteResponse struct { - Action Action `json:"action"` -} - -// NetworkActionChangeProtectionRequest defines the schema of the request to -// change the resource protection of a network. -type NetworkActionChangeProtectionRequest struct { - Delete *bool `json:"delete,omitempty"` -} - -// NetworkActionChangeProtectionResponse defines the schema of the response when -// changing the resource protection of a network. -type NetworkActionChangeProtectionResponse struct { - Action Action `json:"action"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/placement_group.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/placement_group.go deleted file mode 100644 index 6bee4390c..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/placement_group.go +++ /dev/null @@ -1,40 +0,0 @@ -package schema - -import "time" - -type PlacementGroup struct { - ID int `json:"id"` - Name string `json:"name"` - Labels map[string]string `json:"labels"` - Created time.Time `json:"created"` - Servers []int `json:"servers"` - Type string `json:"type"` -} - -type PlacementGroupListResponse struct { - PlacementGroups []PlacementGroup `json:"placement_groups"` -} - -type PlacementGroupGetResponse struct { - PlacementGroup PlacementGroup `json:"placement_group"` -} - -type PlacementGroupCreateRequest struct { - Name string `json:"name"` - Labels *map[string]string `json:"labels,omitempty"` - Type string `json:"type"` -} - -type PlacementGroupCreateResponse struct { - PlacementGroup PlacementGroup `json:"placement_group"` - Action *Action `json:"action"` -} - -type PlacementGroupUpdateRequest struct { - Name *string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -type PlacementGroupUpdateResponse struct { - PlacementGroup PlacementGroup `json:"placement_group"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/pricing.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/pricing.go deleted file mode 100644 index 0c06c73d2..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/pricing.go +++ /dev/null @@ -1,110 +0,0 @@ -package schema - -// Pricing defines the schema for pricing information. -type Pricing struct { - Currency string `json:"currency"` - VATRate string `json:"vat_rate"` - Image PricingImage `json:"image"` - FloatingIP PricingFloatingIP `json:"floating_ip"` - FloatingIPs []PricingFloatingIPType `json:"floating_ips"` - PrimaryIPs []PricingPrimaryIP `json:"primary_ips"` - Traffic PricingTraffic `json:"traffic"` - ServerBackup PricingServerBackup `json:"server_backup"` - ServerTypes []PricingServerType `json:"server_types"` - LoadBalancerTypes []PricingLoadBalancerType `json:"load_balancer_types"` - Volume PricingVolume `json:"volume"` -} - -// Price defines the schema of a single price with net and gross amount. -type Price struct { - Net string `json:"net"` - Gross string `json:"gross"` -} - -// PricingImage defines the schema of pricing information for an image. -type PricingImage struct { - PricePerGBMonth Price `json:"price_per_gb_month"` -} - -// PricingFloatingIP defines the schema of pricing information for a Floating IP. -type PricingFloatingIP struct { - PriceMonthly Price `json:"price_monthly"` -} - -// PricingFloatingIPType defines the schema of pricing information for a Floating IP per type. -type PricingFloatingIPType struct { - Type string `json:"type"` - Prices []PricingFloatingIPTypePrice `json:"prices"` -} - -// PricingFloatingIPTypePrice defines the schema of pricing information for a Floating IP -// type at a location. -type PricingFloatingIPTypePrice struct { - Location string `json:"location"` - PriceMonthly Price `json:"price_monthly"` -} - -// PricingTraffic defines the schema of pricing information for traffic. -type PricingTraffic struct { - PricePerTB Price `json:"price_per_tb"` -} - -// PricingVolume defines the schema of pricing information for a Volume. -type PricingVolume struct { - PricePerGBPerMonth Price `json:"price_per_gb_month"` -} - -// PricingServerBackup defines the schema of pricing information for server backups. -type PricingServerBackup struct { - Percentage string `json:"percentage"` -} - -// PricingServerType defines the schema of pricing information for a server type. -type PricingServerType struct { - ID int `json:"id"` - Name string `json:"name"` - Prices []PricingServerTypePrice `json:"prices"` -} - -// PricingServerTypePrice defines the schema of pricing information for a server -// type at a location. -type PricingServerTypePrice struct { - Location string `json:"location"` - PriceHourly Price `json:"price_hourly"` - PriceMonthly Price `json:"price_monthly"` -} - -// PricingLoadBalancerType defines the schema of pricing information for a Load Balancer type. -type PricingLoadBalancerType struct { - ID int `json:"id"` - Name string `json:"name"` - Prices []PricingLoadBalancerTypePrice `json:"prices"` -} - -// PricingLoadBalancerTypePrice defines the schema of pricing information for a Load Balancer -// type at a location. -type PricingLoadBalancerTypePrice struct { - Location string `json:"location"` - PriceHourly Price `json:"price_hourly"` - PriceMonthly Price `json:"price_monthly"` -} - -// PricingGetResponse defines the schema of the response when retrieving pricing information. -type PricingGetResponse struct { - Pricing Pricing `json:"pricing"` -} - -// PricingPrimaryIPTypePrice defines the schema of pricing information for a primary IP. -// type at a datacenter. -type PricingPrimaryIPTypePrice struct { - Datacenter string `json:"datacenter"` // Deprecated: the API does not return pricing for the individual DCs anymore - Location string `json:"location"` - PriceHourly Price `json:"price_hourly"` - PriceMonthly Price `json:"price_monthly"` -} - -// PricingPrimaryIP define the schema of pricing information for a primary IP at a datacenter. -type PricingPrimaryIP struct { - Type string `json:"type"` - Prices []PricingPrimaryIPTypePrice `json:"prices"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/primary_ip.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/primary_ip.go deleted file mode 100644 index d232a732d..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/primary_ip.go +++ /dev/null @@ -1,55 +0,0 @@ -package schema - -import "time" - -// PrimaryIP defines a Primary IP. -type PrimaryIP struct { - ID int `json:"id"` - IP string `json:"ip"` - Labels map[string]string `json:"labels"` - Name string `json:"name"` - Type string `json:"type"` - Protection PrimaryIPProtection `json:"protection"` - DNSPtr []PrimaryIPDNSPTR `json:"dns_ptr"` - AssigneeID int `json:"assignee_id"` - AssigneeType string `json:"assignee_type"` - AutoDelete bool `json:"auto_delete"` - Blocked bool `json:"blocked"` - Created time.Time `json:"created"` - Datacenter Datacenter `json:"datacenter"` -} - -// PrimaryIPProtection represents the protection level of a Primary IP. -type PrimaryIPProtection struct { - Delete bool `json:"delete"` -} - -// PrimaryIPDNSPTR contains reverse DNS information for a -// IPv4 or IPv6 Primary IP. -type PrimaryIPDNSPTR struct { - DNSPtr string `json:"dns_ptr"` - IP string `json:"ip"` -} - -// PrimaryIPCreateResponse defines the schema of the response -// when creating a Primary IP. -type PrimaryIPCreateResponse struct { - PrimaryIP PrimaryIP `json:"primary_ip"` - Action *Action `json:"action"` -} - -// PrimaryIPGetResult defines the response when retrieving a single Primary IP. -type PrimaryIPGetResult struct { - PrimaryIP PrimaryIP `json:"primary_ip"` -} - -// PrimaryIPListResult defines the response when listing Primary IPs. -type PrimaryIPListResult struct { - PrimaryIPs []PrimaryIP `json:"primary_ips"` -} - -// PrimaryIPUpdateResult defines the response -// when updating a Primary IP. -type PrimaryIPUpdateResult struct { - PrimaryIP PrimaryIP `json:"primary_ip"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server.go deleted file mode 100644 index 4786b1f9a..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server.go +++ /dev/null @@ -1,435 +0,0 @@ -package schema - -import "time" - -// Server defines the schema of a server. -type Server struct { - ID int `json:"id"` - Name string `json:"name"` - Status string `json:"status"` - Created time.Time `json:"created"` - PublicNet ServerPublicNet `json:"public_net"` - PrivateNet []ServerPrivateNet `json:"private_net"` - ServerType ServerType `json:"server_type"` - IncludedTraffic uint64 `json:"included_traffic"` - OutgoingTraffic *uint64 `json:"outgoing_traffic"` - IngoingTraffic *uint64 `json:"ingoing_traffic"` - BackupWindow *string `json:"backup_window"` - RescueEnabled bool `json:"rescue_enabled"` - ISO *ISO `json:"iso"` - Locked bool `json:"locked"` - Datacenter Datacenter `json:"datacenter"` - Image *Image `json:"image"` - Protection ServerProtection `json:"protection"` - Labels map[string]string `json:"labels"` - Volumes []int `json:"volumes"` - PrimaryDiskSize int `json:"primary_disk_size"` - PlacementGroup *PlacementGroup `json:"placement_group"` -} - -// ServerProtection defines the schema of a server's resource protection. -type ServerProtection struct { - Delete bool `json:"delete"` - Rebuild bool `json:"rebuild"` -} - -// ServerPublicNet defines the schema of a server's -// public network information. -type ServerPublicNet struct { - IPv4 ServerPublicNetIPv4 `json:"ipv4"` - IPv6 ServerPublicNetIPv6 `json:"ipv6"` - FloatingIPs []int `json:"floating_ips"` - Firewalls []ServerFirewall `json:"firewalls"` -} - -// ServerPublicNetIPv4 defines the schema of a server's public -// network information for an IPv4. -type ServerPublicNetIPv4 struct { - ID int `json:"id"` - IP string `json:"ip"` - Blocked bool `json:"blocked"` - DNSPtr string `json:"dns_ptr"` -} - -// ServerPublicNetIPv6 defines the schema of a server's public -// network information for an IPv6. -type ServerPublicNetIPv6 struct { - ID int `json:"id"` - IP string `json:"ip"` - Blocked bool `json:"blocked"` - DNSPtr []ServerPublicNetIPv6DNSPtr `json:"dns_ptr"` -} - -// ServerPublicNetIPv6DNSPtr defines the schema of a server's -// public network information for an IPv6 reverse DNS. -type ServerPublicNetIPv6DNSPtr struct { - IP string `json:"ip"` - DNSPtr string `json:"dns_ptr"` -} - -// ServerFirewall defines the schema of a Server's Firewalls on -// a certain network interface. -type ServerFirewall struct { - ID int `json:"id"` - Status string `json:"status"` -} - -// ServerPrivateNet defines the schema of a server's private network information. -type ServerPrivateNet struct { - Network int `json:"network"` - IP string `json:"ip"` - AliasIPs []string `json:"alias_ips"` - MACAddress string `json:"mac_address"` -} - -// ServerGetResponse defines the schema of the response when -// retrieving a single server. -type ServerGetResponse struct { - Server Server `json:"server"` -} - -// ServerListResponse defines the schema of the response when -// listing servers. -type ServerListResponse struct { - Servers []Server `json:"servers"` -} - -// ServerCreateRequest defines the schema for the request to -// create a server. -type ServerCreateRequest struct { - Name string `json:"name"` - ServerType interface{} `json:"server_type"` // int or string - Image interface{} `json:"image"` // int or string - SSHKeys []int `json:"ssh_keys,omitempty"` - Location string `json:"location,omitempty"` - Datacenter string `json:"datacenter,omitempty"` - UserData string `json:"user_data,omitempty"` - StartAfterCreate *bool `json:"start_after_create,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` - Automount *bool `json:"automount,omitempty"` - Volumes []int `json:"volumes,omitempty"` - Networks []int `json:"networks,omitempty"` - Firewalls []ServerCreateFirewalls `json:"firewalls,omitempty"` - PlacementGroup int `json:"placement_group,omitempty"` - PublicNet *ServerCreatePublicNet `json:"public_net,omitempty"` -} - -// ServerCreatePublicNet defines the public network configuration of a server. -type ServerCreatePublicNet struct { - EnableIPv4 bool `json:"enable_ipv4"` - EnableIPv6 bool `json:"enable_ipv6"` - IPv4ID int `json:"ipv4,omitempty"` - IPv6ID int `json:"ipv6,omitempty"` -} - -// ServerCreateFirewalls defines which Firewalls to apply when creating a Server. -type ServerCreateFirewalls struct { - Firewall int `json:"firewall"` -} - -// ServerCreateResponse defines the schema of the response when -// creating a server. -type ServerCreateResponse struct { - Server Server `json:"server"` - Action Action `json:"action"` - RootPassword *string `json:"root_password"` - NextActions []Action `json:"next_actions"` -} - -// ServerDeleteResponse defines the schema of the response when -// deleting a server. -type ServerDeleteResponse struct { - Action Action `json:"action"` -} - -// ServerUpdateRequest defines the schema of the request to update a server. -type ServerUpdateRequest struct { - Name string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// ServerUpdateResponse defines the schema of the response when updating a server. -type ServerUpdateResponse struct { - Server Server `json:"server"` -} - -// ServerActionPoweronRequest defines the schema for the request to -// create a poweron server action. -type ServerActionPoweronRequest struct{} - -// ServerActionPoweronResponse defines the schema of the response when -// creating a poweron server action. -type ServerActionPoweronResponse struct { - Action Action `json:"action"` -} - -// ServerActionPoweroffRequest defines the schema for the request to -// create a poweroff server action. -type ServerActionPoweroffRequest struct{} - -// ServerActionPoweroffResponse defines the schema of the response when -// creating a poweroff server action. -type ServerActionPoweroffResponse struct { - Action Action `json:"action"` -} - -// ServerActionRebootRequest defines the schema for the request to -// create a reboot server action. -type ServerActionRebootRequest struct{} - -// ServerActionRebootResponse defines the schema of the response when -// creating a reboot server action. -type ServerActionRebootResponse struct { - Action Action `json:"action"` -} - -// ServerActionResetRequest defines the schema for the request to -// create a reset server action. -type ServerActionResetRequest struct{} - -// ServerActionResetResponse defines the schema of the response when -// creating a reset server action. -type ServerActionResetResponse struct { - Action Action `json:"action"` -} - -// ServerActionShutdownRequest defines the schema for the request to -// create a shutdown server action. -type ServerActionShutdownRequest struct{} - -// ServerActionShutdownResponse defines the schema of the response when -// creating a shutdown server action. -type ServerActionShutdownResponse struct { - Action Action `json:"action"` -} - -// ServerActionResetPasswordRequest defines the schema for the request to -// create a reset_password server action. -type ServerActionResetPasswordRequest struct{} - -// ServerActionResetPasswordResponse defines the schema of the response when -// creating a reset_password server action. -type ServerActionResetPasswordResponse struct { - Action Action `json:"action"` - RootPassword string `json:"root_password"` -} - -// ServerActionCreateImageRequest defines the schema for the request to -// create a create_image server action. -type ServerActionCreateImageRequest struct { - Type *string `json:"type"` - Description *string `json:"description"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// ServerActionCreateImageResponse defines the schema of the response when -// creating a create_image server action. -type ServerActionCreateImageResponse struct { - Action Action `json:"action"` - Image Image `json:"image"` -} - -// ServerActionEnableRescueRequest defines the schema for the request to -// create a enable_rescue server action. -type ServerActionEnableRescueRequest struct { - Type *string `json:"type,omitempty"` - SSHKeys []int `json:"ssh_keys,omitempty"` -} - -// ServerActionEnableRescueResponse defines the schema of the response when -// creating a enable_rescue server action. -type ServerActionEnableRescueResponse struct { - Action Action `json:"action"` - RootPassword string `json:"root_password"` -} - -// ServerActionDisableRescueRequest defines the schema for the request to -// create a disable_rescue server action. -type ServerActionDisableRescueRequest struct{} - -// ServerActionDisableRescueResponse defines the schema of the response when -// creating a disable_rescue server action. -type ServerActionDisableRescueResponse struct { - Action Action `json:"action"` -} - -// ServerActionRebuildRequest defines the schema for the request to -// rebuild a server. -type ServerActionRebuildRequest struct { - Image interface{} `json:"image"` // int or string -} - -// ServerActionRebuildResponse defines the schema of the response when -// creating a rebuild server action. -type ServerActionRebuildResponse struct { - Action Action `json:"action"` - RootPassword *string `json:"root_password"` -} - -// ServerActionAttachISORequest defines the schema for the request to -// attach an ISO to a server. -type ServerActionAttachISORequest struct { - ISO interface{} `json:"iso"` // int or string -} - -// ServerActionAttachISOResponse defines the schema of the response when -// creating a attach_iso server action. -type ServerActionAttachISOResponse struct { - Action Action `json:"action"` -} - -// ServerActionDetachISORequest defines the schema for the request to -// detach an ISO from a server. -type ServerActionDetachISORequest struct{} - -// ServerActionDetachISOResponse defines the schema of the response when -// creating a detach_iso server action. -type ServerActionDetachISOResponse struct { - Action Action `json:"action"` -} - -// ServerActionEnableBackupRequest defines the schema for the request to -// enable backup for a server. -type ServerActionEnableBackupRequest struct { - BackupWindow *string `json:"backup_window,omitempty"` -} - -// ServerActionEnableBackupResponse defines the schema of the response when -// creating a enable_backup server action. -type ServerActionEnableBackupResponse struct { - Action Action `json:"action"` -} - -// ServerActionDisableBackupRequest defines the schema for the request to -// disable backup for a server. -type ServerActionDisableBackupRequest struct{} - -// ServerActionDisableBackupResponse defines the schema of the response when -// creating a disable_backup server action. -type ServerActionDisableBackupResponse struct { - Action Action `json:"action"` -} - -// ServerActionChangeTypeRequest defines the schema for the request to -// change a server's type. -type ServerActionChangeTypeRequest struct { - ServerType interface{} `json:"server_type"` // int or string - UpgradeDisk bool `json:"upgrade_disk"` -} - -// ServerActionChangeTypeResponse defines the schema of the response when -// creating a change_type server action. -type ServerActionChangeTypeResponse struct { - Action Action `json:"action"` -} - -// ServerActionChangeDNSPtrRequest defines the schema for the request to -// change a server's reverse DNS pointer. -type ServerActionChangeDNSPtrRequest struct { - IP string `json:"ip"` - DNSPtr *string `json:"dns_ptr"` -} - -// ServerActionChangeDNSPtrResponse defines the schema of the response when -// creating a change_dns_ptr server action. -type ServerActionChangeDNSPtrResponse struct { - Action Action `json:"action"` -} - -// ServerActionChangeProtectionRequest defines the schema of the request to -// change the resource protection of a server. -type ServerActionChangeProtectionRequest struct { - Rebuild *bool `json:"rebuild,omitempty"` - Delete *bool `json:"delete,omitempty"` -} - -// ServerActionChangeProtectionResponse defines the schema of the response when -// changing the resource protection of a server. -type ServerActionChangeProtectionResponse struct { - Action Action `json:"action"` -} - -// ServerActionRequestConsoleRequest defines the schema of the request to -// request a WebSocket VNC console. -type ServerActionRequestConsoleRequest struct{} - -// ServerActionRequestConsoleResponse defines the schema of the response when -// requesting a WebSocket VNC console. -type ServerActionRequestConsoleResponse struct { - Action Action `json:"action"` - WSSURL string `json:"wss_url"` - Password string `json:"password"` -} - -// ServerActionAttachToNetworkRequest defines the schema for the request to -// attach a network to a server. -type ServerActionAttachToNetworkRequest struct { - Network int `json:"network"` - IP *string `json:"ip,omitempty"` - AliasIPs []*string `json:"alias_ips,omitempty"` -} - -// ServerActionAttachToNetworkResponse defines the schema of the response when -// creating an attach_to_network server action. -type ServerActionAttachToNetworkResponse struct { - Action Action `json:"action"` -} - -// ServerActionDetachFromNetworkRequest defines the schema for the request to -// detach a network from a server. -type ServerActionDetachFromNetworkRequest struct { - Network int `json:"network"` -} - -// ServerActionDetachFromNetworkResponse defines the schema of the response when -// creating a detach_from_network server action. -type ServerActionDetachFromNetworkResponse struct { - Action Action `json:"action"` -} - -// ServerActionChangeAliasIPsRequest defines the schema for the request to -// change a server's alias IPs in a network. -type ServerActionChangeAliasIPsRequest struct { - Network int `json:"network"` - AliasIPs []string `json:"alias_ips"` -} - -// ServerActionChangeAliasIPsResponse defines the schema of the response when -// creating an change_alias_ips server action. -type ServerActionChangeAliasIPsResponse struct { - Action Action `json:"action"` -} - -// ServerGetMetricsResponse defines the schema of the response when requesting -// metrics for a server. -type ServerGetMetricsResponse struct { - Metrics struct { - Start time.Time `json:"start"` - End time.Time `json:"end"` - Step float64 `json:"step"` - TimeSeries map[string]ServerTimeSeriesVals `json:"time_series"` - } `json:"metrics"` -} - -// ServerTimeSeriesVals contains the values for a Server time series. -type ServerTimeSeriesVals struct { - Values []interface{} `json:"values"` -} - -// ServerActionAddToPlacementGroupRequest defines the schema for the request to -// add a server to a placement group. -type ServerActionAddToPlacementGroupRequest struct { - PlacementGroup int `json:"placement_group"` -} - -// ServerActionAddToPlacementGroupResponse defines the schema of the response when -// creating an add_to_placement_group server action. -type ServerActionAddToPlacementGroupResponse struct { - Action Action `json:"action"` -} - -// ServerActionRemoveFromPlacementGroupResponse defines the schema of the response when -// creating a remove_from_placement_group server action. -type ServerActionRemoveFromPlacementGroupResponse struct { - Action Action `json:"action"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server_type.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server_type.go deleted file mode 100644 index e2fe2f726..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server_type.go +++ /dev/null @@ -1,27 +0,0 @@ -package schema - -// ServerType defines the schema of a server type. -type ServerType struct { - ID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Cores int `json:"cores"` - Memory float32 `json:"memory"` - Disk int `json:"disk"` - StorageType string `json:"storage_type"` - CPUType string `json:"cpu_type"` - Architecture string `json:"architecture"` - Prices []PricingServerTypePrice `json:"prices"` -} - -// ServerTypeListResponse defines the schema of the response when -// listing server types. -type ServerTypeListResponse struct { - ServerTypes []ServerType `json:"server_types"` -} - -// ServerTypeGetResponse defines the schema of the response when -// retrieving a single server type. -type ServerTypeGetResponse struct { - ServerType ServerType `json:"server_type"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/ssh_key.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/ssh_key.go deleted file mode 100644 index f230b3ddd..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/ssh_key.go +++ /dev/null @@ -1,50 +0,0 @@ -package schema - -import "time" - -// SSHKey defines the schema of a SSH key. -type SSHKey struct { - ID int `json:"id"` - Name string `json:"name"` - Fingerprint string `json:"fingerprint"` - PublicKey string `json:"public_key"` - Labels map[string]string `json:"labels"` - Created time.Time `json:"created"` -} - -// SSHKeyCreateRequest defines the schema of the request -// to create a SSH key. -type SSHKeyCreateRequest struct { - Name string `json:"name"` - PublicKey string `json:"public_key"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// SSHKeyCreateResponse defines the schema of the response -// when creating a SSH key. -type SSHKeyCreateResponse struct { - SSHKey SSHKey `json:"ssh_key"` -} - -// SSHKeyListResponse defines the schema of the response -// when listing SSH keys. -type SSHKeyListResponse struct { - SSHKeys []SSHKey `json:"ssh_keys"` -} - -// SSHKeyGetResponse defines the schema of the response -// when retrieving a single SSH key. -type SSHKeyGetResponse struct { - SSHKey SSHKey `json:"ssh_key"` -} - -// SSHKeyUpdateRequest defines the schema of the request to update a SSH key. -type SSHKeyUpdateRequest struct { - Name string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// SSHKeyUpdateResponse defines the schema of the response when updating a SSH key. -type SSHKeyUpdateResponse struct { - SSHKey SSHKey `json:"ssh_key"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/volume.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/volume.go deleted file mode 100644 index ad745ea97..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/volume.go +++ /dev/null @@ -1,110 +0,0 @@ -package schema - -import "time" - -// Volume defines the schema of a volume. -type Volume struct { - ID int `json:"id"` - Name string `json:"name"` - Server *int `json:"server"` - Status string `json:"status"` - Location Location `json:"location"` - Size int `json:"size"` - Protection VolumeProtection `json:"protection"` - Labels map[string]string `json:"labels"` - LinuxDevice string `json:"linux_device"` - Created time.Time `json:"created"` -} - -// VolumeCreateRequest defines the schema of the request -// to create a volume. -type VolumeCreateRequest struct { - Name string `json:"name"` - Size int `json:"size"` - Server *int `json:"server,omitempty"` - Location interface{} `json:"location,omitempty"` // int, string, or nil - Labels *map[string]string `json:"labels,omitempty"` - Automount *bool `json:"automount,omitempty"` - Format *string `json:"format,omitempty"` -} - -// VolumeCreateResponse defines the schema of the response -// when creating a volume. -type VolumeCreateResponse struct { - Volume Volume `json:"volume"` - Action *Action `json:"action"` - NextActions []Action `json:"next_actions"` -} - -// VolumeListResponse defines the schema of the response -// when listing volumes. -type VolumeListResponse struct { - Volumes []Volume `json:"volumes"` -} - -// VolumeGetResponse defines the schema of the response -// when retrieving a single volume. -type VolumeGetResponse struct { - Volume Volume `json:"volume"` -} - -// VolumeUpdateRequest defines the schema of the request to update a volume. -type VolumeUpdateRequest struct { - Name string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// VolumeUpdateResponse defines the schema of the response when updating a volume. -type VolumeUpdateResponse struct { - Volume Volume `json:"volume"` -} - -// VolumeProtection defines the schema of a volume's resource protection. -type VolumeProtection struct { - Delete bool `json:"delete"` -} - -// VolumeActionChangeProtectionRequest defines the schema of the request to -// change the resource protection of a volume. -type VolumeActionChangeProtectionRequest struct { - Delete *bool `json:"delete,omitempty"` -} - -// VolumeActionChangeProtectionResponse defines the schema of the response when -// changing the resource protection of a volume. -type VolumeActionChangeProtectionResponse struct { - Action Action `json:"action"` -} - -// VolumeActionAttachVolumeRequest defines the schema of the request to -// attach a volume to a server. -type VolumeActionAttachVolumeRequest struct { - Server int `json:"server"` - Automount *bool `json:"automount,omitempty"` -} - -// VolumeActionAttachVolumeResponse defines the schema of the response when -// attaching a volume to a server. -type VolumeActionAttachVolumeResponse struct { - Action Action `json:"action"` -} - -// VolumeActionDetachVolumeRequest defines the schema of the request to -// create an detach volume action. -type VolumeActionDetachVolumeRequest struct{} - -// VolumeActionDetachVolumeResponse defines the schema of the response when -// creating an detach volume action. -type VolumeActionDetachVolumeResponse struct { - Action Action `json:"action"` -} - -// VolumeActionResizeVolumeRequest defines the schema of the request to resize a volume. -type VolumeActionResizeVolumeRequest struct { - Size int `json:"size"` -} - -// VolumeActionResizeVolumeResponse defines the schema of the response when resizing a volume. -type VolumeActionResizeVolumeResponse struct { - Action Action `json:"action"` -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/server.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/server.go deleted file mode 100644 index 52ea7fa5c..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/server.go +++ /dev/null @@ -1,1221 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Server represents a server in the Hetzner Cloud. -type Server struct { - ID int - Name string - Status ServerStatus - Created time.Time - PublicNet ServerPublicNet - PrivateNet []ServerPrivateNet - ServerType *ServerType - Datacenter *Datacenter - IncludedTraffic uint64 - OutgoingTraffic uint64 - IngoingTraffic uint64 - BackupWindow string - RescueEnabled bool - Locked bool - ISO *ISO - Image *Image - Protection ServerProtection - Labels map[string]string - Volumes []*Volume - PrimaryDiskSize int - PlacementGroup *PlacementGroup -} - -// ServerProtection represents the protection level of a server. -type ServerProtection struct { - Delete, Rebuild bool -} - -// ServerStatus specifies a server's status. -type ServerStatus string - -const ( - // ServerStatusInitializing is the status when a server is initializing. - ServerStatusInitializing ServerStatus = "initializing" - - // ServerStatusOff is the status when a server is off. - ServerStatusOff ServerStatus = "off" - - // ServerStatusRunning is the status when a server is running. - ServerStatusRunning ServerStatus = "running" - - // ServerStatusStarting is the status when a server is being started. - ServerStatusStarting ServerStatus = "starting" - - // ServerStatusStopping is the status when a server is being stopped. - ServerStatusStopping ServerStatus = "stopping" - - // ServerStatusMigrating is the status when a server is being migrated. - ServerStatusMigrating ServerStatus = "migrating" - - // ServerStatusRebuilding is the status when a server is being rebuilt. - ServerStatusRebuilding ServerStatus = "rebuilding" - - // ServerStatusDeleting is the status when a server is being deleted. - ServerStatusDeleting ServerStatus = "deleting" - - // ServerStatusUnknown is the status when a server's state is unknown. - ServerStatusUnknown ServerStatus = "unknown" -) - -// FirewallStatus specifies a Firewall's status. -type FirewallStatus string - -const ( - // FirewallStatusPending is the status when a Firewall is pending. - FirewallStatusPending FirewallStatus = "pending" - - // FirewallStatusApplied is the status when a Firewall is applied. - FirewallStatusApplied FirewallStatus = "applied" -) - -// ServerPublicNet represents a server's public network. -type ServerPublicNet struct { - IPv4 ServerPublicNetIPv4 - IPv6 ServerPublicNetIPv6 - FloatingIPs []*FloatingIP - Firewalls []*ServerFirewallStatus -} - -// ServerPublicNetIPv4 represents a server's public IPv4 address. -type ServerPublicNetIPv4 struct { - ID int - IP net.IP - Blocked bool - DNSPtr string -} - -func (n *ServerPublicNetIPv4) IsUnspecified() bool { - return n.IP == nil || n.IP.Equal(net.IPv4zero) -} - -// ServerPublicNetIPv6 represents a Server's public IPv6 network and address. -type ServerPublicNetIPv6 struct { - ID int - IP net.IP - Network *net.IPNet - Blocked bool - DNSPtr map[string]string -} - -func (n *ServerPublicNetIPv6) IsUnspecified() bool { - return n.IP == nil || n.IP.Equal(net.IPv6unspecified) -} - -// ServerPrivateNet defines the schema of a Server's private network information. -type ServerPrivateNet struct { - Network *Network - IP net.IP - Aliases []net.IP - MACAddress string -} - -// DNSPtrForIP returns the reverse dns pointer of the ip address. -func (n *ServerPublicNetIPv6) DNSPtrForIP(ip net.IP) string { - return n.DNSPtr[ip.String()] -} - -// ServerFirewallStatus represents a Firewall and its status on a Server's -// network interface. -type ServerFirewallStatus struct { - Firewall Firewall - Status FirewallStatus -} - -// ServerRescueType represents rescue types. -type ServerRescueType string - -// List of rescue types. -const ( - ServerRescueTypeLinux32 ServerRescueType = "linux32" - ServerRescueTypeLinux64 ServerRescueType = "linux64" -) - -// changeDNSPtr changes or resets the reverse DNS pointer for a IP address. -// Pass a nil ptr to reset the reverse DNS pointer to its default value. -func (s *Server) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { - reqBody := schema.ServerActionChangeDNSPtrRequest{ - IP: ip.String(), - DNSPtr: ptr, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/change_dns_ptr", s.ID) - req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionChangeDNSPtrResponse{} - resp, err := client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// GetDNSPtrForIP searches for the dns assigned to the given IP address. -// It returns an error if there is no dns set for the given IP address. -func (s *Server) GetDNSPtrForIP(ip net.IP) (string, error) { - if net.IP.Equal(s.PublicNet.IPv4.IP, ip) { - return s.PublicNet.IPv4.DNSPtr, nil - } else if dns, ok := s.PublicNet.IPv6.DNSPtr[ip.String()]; ok { - return dns, nil - } - - return "", DNSNotFoundError{ip} -} - -// ServerClient is a client for the servers API. -type ServerClient struct { - client *Client -} - -// GetByID retrieves a server by its ID. If the server does not exist, nil is returned. -func (c *ServerClient) GetByID(ctx context.Context, id int) (*Server, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/servers/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.ServerGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return ServerFromSchema(body.Server), resp, nil -} - -// GetByName retrieves a server by its name. If the server does not exist, nil is returned. -func (c *ServerClient) GetByName(ctx context.Context, name string) (*Server, *Response, error) { - if name == "" { - return nil, nil, nil - } - servers, response, err := c.List(ctx, ServerListOpts{Name: name}) - if len(servers) == 0 { - return nil, response, err - } - return servers[0], response, err -} - -// Get retrieves a server by its ID if the input can be parsed as an integer, otherwise it -// retrieves a server by its name. If the server does not exist, nil is returned. -func (c *ServerClient) Get(ctx context.Context, idOrName string) (*Server, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// ServerListOpts specifies options for listing servers. -type ServerListOpts struct { - ListOpts - Name string - Status []ServerStatus - Sort []string -} - -func (l ServerListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, status := range l.Status { - vals.Add("status", string(status)) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of servers for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *ServerClient) List(ctx context.Context, opts ServerListOpts) ([]*Server, *Response, error) { - path := "/servers?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.ServerListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - servers := make([]*Server, 0, len(body.Servers)) - for _, s := range body.Servers { - servers = append(servers, ServerFromSchema(s)) - } - return servers, resp, nil -} - -// All returns all servers. -func (c *ServerClient) All(ctx context.Context) ([]*Server, error) { - return c.AllWithOpts(ctx, ServerListOpts{ListOpts: ListOpts{PerPage: 50}}) -} - -// AllWithOpts returns all servers for the given options. -func (c *ServerClient) AllWithOpts(ctx context.Context, opts ServerListOpts) ([]*Server, error) { - allServers := []*Server{} - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - servers, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allServers = append(allServers, servers...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allServers, nil -} - -// ServerCreateOpts specifies options for creating a new server. -type ServerCreateOpts struct { - Name string - ServerType *ServerType - Image *Image - SSHKeys []*SSHKey - Location *Location - Datacenter *Datacenter - UserData string - StartAfterCreate *bool - Labels map[string]string - Automount *bool - Volumes []*Volume - Networks []*Network - Firewalls []*ServerCreateFirewall - PlacementGroup *PlacementGroup - PublicNet *ServerCreatePublicNet -} - -type ServerCreatePublicNet struct { - EnableIPv4 bool - EnableIPv6 bool - IPv4 *PrimaryIP - IPv6 *PrimaryIP -} - -// ServerCreateFirewall defines which Firewalls to apply when creating a Server. -type ServerCreateFirewall struct { - Firewall Firewall -} - -// Validate checks if options are valid. -func (o ServerCreateOpts) Validate() error { - if o.Name == "" { - return errors.New("missing name") - } - if o.ServerType == nil || (o.ServerType.ID == 0 && o.ServerType.Name == "") { - return errors.New("missing server type") - } - if o.Image == nil || (o.Image.ID == 0 && o.Image.Name == "") { - return errors.New("missing image") - } - if o.Location != nil && o.Datacenter != nil { - return errors.New("location and datacenter are mutually exclusive") - } - if o.PublicNet != nil { - if !o.PublicNet.EnableIPv4 && !o.PublicNet.EnableIPv6 && - len(o.Networks) == 0 && (o.StartAfterCreate == nil || *o.StartAfterCreate) { - return errors.New("missing networks or StartAfterCreate == false when EnableIPv4 and EnableIPv6 is false") - } - } - return nil -} - -// ServerCreateResult is the result of a create server call. -type ServerCreateResult struct { - Server *Server - Action *Action - RootPassword string - NextActions []*Action -} - -// Create creates a new server. -func (c *ServerClient) Create(ctx context.Context, opts ServerCreateOpts) (ServerCreateResult, *Response, error) { - if err := opts.Validate(); err != nil { - return ServerCreateResult{}, nil, err - } - - var reqBody schema.ServerCreateRequest - reqBody.UserData = opts.UserData - reqBody.Name = opts.Name - reqBody.Automount = opts.Automount - reqBody.StartAfterCreate = opts.StartAfterCreate - if opts.ServerType.ID != 0 { - reqBody.ServerType = opts.ServerType.ID - } else if opts.ServerType.Name != "" { - reqBody.ServerType = opts.ServerType.Name - } - if opts.Image.ID != 0 { - reqBody.Image = opts.Image.ID - } else if opts.Image.Name != "" { - reqBody.Image = opts.Image.Name - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - for _, sshKey := range opts.SSHKeys { - reqBody.SSHKeys = append(reqBody.SSHKeys, sshKey.ID) - } - for _, volume := range opts.Volumes { - reqBody.Volumes = append(reqBody.Volumes, volume.ID) - } - for _, network := range opts.Networks { - reqBody.Networks = append(reqBody.Networks, network.ID) - } - for _, firewall := range opts.Firewalls { - reqBody.Firewalls = append(reqBody.Firewalls, schema.ServerCreateFirewalls{ - Firewall: firewall.Firewall.ID, - }) - } - - if opts.PublicNet != nil { - reqBody.PublicNet = &schema.ServerCreatePublicNet{ - EnableIPv4: opts.PublicNet.EnableIPv4, - EnableIPv6: opts.PublicNet.EnableIPv6, - } - if opts.PublicNet.IPv4 != nil { - reqBody.PublicNet.IPv4ID = opts.PublicNet.IPv4.ID - } - if opts.PublicNet.IPv6 != nil { - reqBody.PublicNet.IPv6ID = opts.PublicNet.IPv6.ID - } - } - if opts.Location != nil { - if opts.Location.ID != 0 { - reqBody.Location = strconv.Itoa(opts.Location.ID) - } else { - reqBody.Location = opts.Location.Name - } - } - if opts.Datacenter != nil { - if opts.Datacenter.ID != 0 { - reqBody.Datacenter = strconv.Itoa(opts.Datacenter.ID) - } else { - reqBody.Datacenter = opts.Datacenter.Name - } - } - if opts.PlacementGroup != nil { - reqBody.PlacementGroup = opts.PlacementGroup.ID - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return ServerCreateResult{}, nil, err - } - - req, err := c.client.NewRequest(ctx, "POST", "/servers", bytes.NewReader(reqBodyData)) - if err != nil { - return ServerCreateResult{}, nil, err - } - - var respBody schema.ServerCreateResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return ServerCreateResult{}, resp, err - } - result := ServerCreateResult{ - Server: ServerFromSchema(respBody.Server), - Action: ActionFromSchema(respBody.Action), - NextActions: ActionsFromSchema(respBody.NextActions), - } - if respBody.RootPassword != nil { - result.RootPassword = *respBody.RootPassword - } - return result, resp, nil -} - -// ServerDeleteResult is the result of a delete server call. -type ServerDeleteResult struct { - Action *Action -} - -// Delete deletes a server. -// -// Deprecated: Use [ServerClient.DeleteWithResult] instead. -func (c *ServerClient) Delete(ctx context.Context, server *Server) (*Response, error) { - _, resp, err := c.DeleteWithResult(ctx, server) - return resp, err -} - -// DeleteWithResult deletes a server and returns the parsed response containing the action. -func (c *ServerClient) DeleteWithResult(ctx context.Context, server *Server) (*ServerDeleteResult, *Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/servers/%d", server.ID), nil) - if err != nil { - return &ServerDeleteResult{}, nil, err - } - - var respBody schema.ServerDeleteResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return &ServerDeleteResult{}, resp, err - } - - return &ServerDeleteResult{ - Action: ActionFromSchema(respBody.Action), - }, resp, nil -} - -// ServerUpdateOpts specifies options for updating a server. -type ServerUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a server. -func (c *ServerClient) Update(ctx context.Context, server *Server, opts ServerUpdateOpts) (*Server, *Response, error) { - reqBody := schema.ServerUpdateRequest{ - Name: opts.Name, - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d", server.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ServerFromSchema(respBody.Server), resp, nil -} - -// Poweron starts a server. -func (c *ServerClient) Poweron(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/poweron", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionPoweronResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// Reboot reboots a server. -func (c *ServerClient) Reboot(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/reboot", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionRebootResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// Reset resets a server. -func (c *ServerClient) Reset(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/reset", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionResetResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// Shutdown shuts down a server. -func (c *ServerClient) Shutdown(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/shutdown", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionShutdownResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// Poweroff stops a server. -func (c *ServerClient) Poweroff(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/poweroff", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionPoweroffResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// ServerResetPasswordResult is the result of resetting a server's password. -type ServerResetPasswordResult struct { - Action *Action - RootPassword string -} - -// ResetPassword resets a server's password. -func (c *ServerClient) ResetPassword(ctx context.Context, server *Server) (ServerResetPasswordResult, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/reset_password", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return ServerResetPasswordResult{}, nil, err - } - - respBody := schema.ServerActionResetPasswordResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return ServerResetPasswordResult{}, resp, err - } - return ServerResetPasswordResult{ - Action: ActionFromSchema(respBody.Action), - RootPassword: respBody.RootPassword, - }, resp, nil -} - -// ServerCreateImageOpts specifies options for creating an image from a server. -type ServerCreateImageOpts struct { - Type ImageType - Description *string - Labels map[string]string -} - -// Validate checks if options are valid. -func (o ServerCreateImageOpts) Validate() error { - switch o.Type { - case ImageTypeSnapshot, ImageTypeBackup: - break - case "": - break - default: - return errors.New("invalid type") - } - - return nil -} - -// ServerCreateImageResult is the result of creating an image from a server. -type ServerCreateImageResult struct { - Action *Action - Image *Image -} - -// CreateImage creates an image from a server. -func (c *ServerClient) CreateImage(ctx context.Context, server *Server, opts *ServerCreateImageOpts) (ServerCreateImageResult, *Response, error) { - var reqBody schema.ServerActionCreateImageRequest - if opts != nil { - if err := opts.Validate(); err != nil { - return ServerCreateImageResult{}, nil, fmt.Errorf("invalid options: %s", err) - } - if opts.Description != nil { - reqBody.Description = opts.Description - } - if opts.Type != "" { - reqBody.Type = Ptr(string(opts.Type)) - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return ServerCreateImageResult{}, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/create_image", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return ServerCreateImageResult{}, nil, err - } - - respBody := schema.ServerActionCreateImageResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return ServerCreateImageResult{}, resp, err - } - return ServerCreateImageResult{ - Action: ActionFromSchema(respBody.Action), - Image: ImageFromSchema(respBody.Image), - }, resp, nil -} - -// ServerEnableRescueOpts specifies options for enabling rescue mode for a server. -type ServerEnableRescueOpts struct { - Type ServerRescueType - SSHKeys []*SSHKey -} - -// ServerEnableRescueResult is the result of enabling rescue mode for a server. -type ServerEnableRescueResult struct { - Action *Action - RootPassword string -} - -// EnableRescue enables rescue mode for a server. -func (c *ServerClient) EnableRescue(ctx context.Context, server *Server, opts ServerEnableRescueOpts) (ServerEnableRescueResult, *Response, error) { - reqBody := schema.ServerActionEnableRescueRequest{ - Type: Ptr(string(opts.Type)), - } - for _, sshKey := range opts.SSHKeys { - reqBody.SSHKeys = append(reqBody.SSHKeys, sshKey.ID) - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return ServerEnableRescueResult{}, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/enable_rescue", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return ServerEnableRescueResult{}, nil, err - } - - respBody := schema.ServerActionEnableRescueResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return ServerEnableRescueResult{}, resp, err - } - result := ServerEnableRescueResult{ - Action: ActionFromSchema(respBody.Action), - RootPassword: respBody.RootPassword, - } - return result, resp, nil -} - -// DisableRescue disables rescue mode for a server. -func (c *ServerClient) DisableRescue(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/disable_rescue", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionDisableRescueResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// ServerRebuildOpts specifies options for rebuilding a server. -type ServerRebuildOpts struct { - Image *Image -} - -// ServerRebuildResult is the result of a create server call. -type ServerRebuildResult struct { - Action *Action - RootPassword string -} - -// Rebuild rebuilds a server. -// -// Deprecated: Use [ServerClient.RebuildWithResult] instead. -func (c *ServerClient) Rebuild(ctx context.Context, server *Server, opts ServerRebuildOpts) (*Action, *Response, error) { - result, resp, err := c.RebuildWithResult(ctx, server, opts) - - return result.Action, resp, err -} - -// RebuildWithResult rebuilds a server. -func (c *ServerClient) RebuildWithResult(ctx context.Context, server *Server, opts ServerRebuildOpts) (ServerRebuildResult, *Response, error) { - reqBody := schema.ServerActionRebuildRequest{} - if opts.Image.ID != 0 { - reqBody.Image = opts.Image.ID - } else { - reqBody.Image = opts.Image.Name - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return ServerRebuildResult{}, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/rebuild", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return ServerRebuildResult{}, nil, err - } - - respBody := schema.ServerActionRebuildResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return ServerRebuildResult{}, resp, err - } - - result := ServerRebuildResult{ - Action: ActionFromSchema(respBody.Action), - } - if respBody.RootPassword != nil { - result.RootPassword = *respBody.RootPassword - } - - return result, resp, nil -} - -// AttachISO attaches an ISO to a server. -func (c *ServerClient) AttachISO(ctx context.Context, server *Server, iso *ISO) (*Action, *Response, error) { - reqBody := schema.ServerActionAttachISORequest{} - if iso.ID != 0 { - reqBody.ISO = iso.ID - } else { - reqBody.ISO = iso.Name - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/attach_iso", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionAttachISOResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// DetachISO detaches the currently attached ISO from a server. -func (c *ServerClient) DetachISO(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/detach_iso", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionDetachISOResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// EnableBackup enables backup for a server. Pass in an empty backup window to let the -// API pick a window for you. See the API documentation at docs.hetzner.cloud for a list -// of valid backup windows. -func (c *ServerClient) EnableBackup(ctx context.Context, server *Server, window string) (*Action, *Response, error) { - reqBody := schema.ServerActionEnableBackupRequest{} - if window != "" { - reqBody.BackupWindow = Ptr(window) - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/enable_backup", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionEnableBackupResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// DisableBackup disables backup for a server. -func (c *ServerClient) DisableBackup(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/disable_backup", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionDisableBackupResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// ServerChangeTypeOpts specifies options for changing a server's type. -type ServerChangeTypeOpts struct { - ServerType *ServerType // new server type - UpgradeDisk bool // whether disk should be upgraded -} - -// ChangeType changes a server's type. -func (c *ServerClient) ChangeType(ctx context.Context, server *Server, opts ServerChangeTypeOpts) (*Action, *Response, error) { - reqBody := schema.ServerActionChangeTypeRequest{ - UpgradeDisk: opts.UpgradeDisk, - } - if opts.ServerType.ID != 0 { - reqBody.ServerType = opts.ServerType.ID - } else { - reqBody.ServerType = opts.ServerType.Name - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/change_type", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionChangeTypeResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// ChangeDNSPtr changes or resets the reverse DNS pointer for a server IP address. -// Pass a nil ptr to reset the reverse DNS pointer to its default value. -func (c *ServerClient) ChangeDNSPtr(ctx context.Context, server *Server, ip string, ptr *string) (*Action, *Response, error) { - netIP := net.ParseIP(ip) - if netIP == nil { - return nil, nil, InvalidIPError{ip} - } - return server.changeDNSPtr(ctx, c.client, net.ParseIP(ip), ptr) -} - -// ServerChangeProtectionOpts specifies options for changing the resource protection level of a server. -type ServerChangeProtectionOpts struct { - Rebuild *bool - Delete *bool -} - -// ChangeProtection changes the resource protection level of a server. -func (c *ServerClient) ChangeProtection(ctx context.Context, server *Server, opts ServerChangeProtectionOpts) (*Action, *Response, error) { - reqBody := schema.ServerActionChangeProtectionRequest{ - Rebuild: opts.Rebuild, - Delete: opts.Delete, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/change_protection", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionChangeProtectionResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// ServerRequestConsoleResult is the result of requesting a WebSocket VNC console. -type ServerRequestConsoleResult struct { - Action *Action - WSSURL string - Password string -} - -// RequestConsole requests a WebSocket VNC console. -func (c *ServerClient) RequestConsole(ctx context.Context, server *Server) (ServerRequestConsoleResult, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/request_console", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return ServerRequestConsoleResult{}, nil, err - } - - respBody := schema.ServerActionRequestConsoleResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return ServerRequestConsoleResult{}, resp, err - } - return ServerRequestConsoleResult{ - Action: ActionFromSchema(respBody.Action), - WSSURL: respBody.WSSURL, - Password: respBody.Password, - }, resp, nil -} - -// ServerAttachToNetworkOpts specifies options for attaching a server to a network. -type ServerAttachToNetworkOpts struct { - Network *Network - IP net.IP - AliasIPs []net.IP -} - -// AttachToNetwork attaches a server to a network. -func (c *ServerClient) AttachToNetwork(ctx context.Context, server *Server, opts ServerAttachToNetworkOpts) (*Action, *Response, error) { - reqBody := schema.ServerActionAttachToNetworkRequest{ - Network: opts.Network.ID, - } - if opts.IP != nil { - reqBody.IP = Ptr(opts.IP.String()) - } - for _, aliasIP := range opts.AliasIPs { - reqBody.AliasIPs = append(reqBody.AliasIPs, Ptr(aliasIP.String())) - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/attach_to_network", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionAttachToNetworkResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// ServerDetachFromNetworkOpts specifies options for detaching a server from a network. -type ServerDetachFromNetworkOpts struct { - Network *Network -} - -// DetachFromNetwork detaches a server from a network. -func (c *ServerClient) DetachFromNetwork(ctx context.Context, server *Server, opts ServerDetachFromNetworkOpts) (*Action, *Response, error) { - reqBody := schema.ServerActionDetachFromNetworkRequest{ - Network: opts.Network.ID, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/servers/%d/actions/detach_from_network", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionDetachFromNetworkResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// ServerChangeAliasIPsOpts specifies options for changing the alias ips of an already attached network. -type ServerChangeAliasIPsOpts struct { - Network *Network - AliasIPs []net.IP -} - -// ChangeAliasIPs changes a server's alias IPs in a network. -func (c *ServerClient) ChangeAliasIPs(ctx context.Context, server *Server, opts ServerChangeAliasIPsOpts) (*Action, *Response, error) { - reqBody := schema.ServerActionChangeAliasIPsRequest{ - Network: opts.Network.ID, - AliasIPs: []string{}, - } - for _, aliasIP := range opts.AliasIPs { - reqBody.AliasIPs = append(reqBody.AliasIPs, aliasIP.String()) - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - path := fmt.Sprintf("/servers/%d/actions/change_alias_ips", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionDetachFromNetworkResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// ServerMetricType is the type of available metrics for servers. -type ServerMetricType string - -// Available types of server metrics. See Hetzner Cloud API documentation for -// details. -const ( - ServerMetricCPU ServerMetricType = "cpu" - ServerMetricDisk ServerMetricType = "disk" - ServerMetricNetwork ServerMetricType = "network" -) - -// ServerGetMetricsOpts configures the call to get metrics for a Server. -type ServerGetMetricsOpts struct { - Types []ServerMetricType - Start time.Time - End time.Time - Step int -} - -func (o *ServerGetMetricsOpts) addQueryParams(req *http.Request) error { - query := req.URL.Query() - - if len(o.Types) == 0 { - return fmt.Errorf("no metric types specified") - } - for _, typ := range o.Types { - query.Add("type", string(typ)) - } - - if o.Start.IsZero() { - return fmt.Errorf("no start time specified") - } - query.Add("start", o.Start.Format(time.RFC3339)) - - if o.End.IsZero() { - return fmt.Errorf("no end time specified") - } - query.Add("end", o.End.Format(time.RFC3339)) - - if o.Step > 0 { - query.Add("step", strconv.Itoa(o.Step)) - } - req.URL.RawQuery = query.Encode() - - return nil -} - -// ServerMetrics contains the metrics requested for a Server. -type ServerMetrics struct { - Start time.Time - End time.Time - Step float64 - TimeSeries map[string][]ServerMetricsValue -} - -// ServerMetricsValue represents a single value in a time series of metrics. -type ServerMetricsValue struct { - Timestamp float64 - Value string -} - -// GetMetrics obtains metrics for Server. -func (c *ServerClient) GetMetrics(ctx context.Context, server *Server, opts ServerGetMetricsOpts) (*ServerMetrics, *Response, error) { - var respBody schema.ServerGetMetricsResponse - - if server == nil { - return nil, nil, fmt.Errorf("illegal argument: server is nil") - } - - path := fmt.Sprintf("/servers/%d/metrics", server.ID) - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, fmt.Errorf("new request: %v", err) - } - if err := opts.addQueryParams(req); err != nil { - return nil, nil, fmt.Errorf("add query params: %v", err) - } - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, nil, fmt.Errorf("get metrics: %v", err) - } - ms, err := serverMetricsFromSchema(&respBody) - if err != nil { - return nil, nil, fmt.Errorf("convert response body: %v", err) - } - return ms, resp, nil -} - -func (c *ServerClient) AddToPlacementGroup(ctx context.Context, server *Server, placementGroup *PlacementGroup) (*Action, *Response, error) { - reqBody := schema.ServerActionAddToPlacementGroupRequest{ - PlacementGroup: placementGroup.ID, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - path := fmt.Sprintf("/servers/%d/actions/add_to_placement_group", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionAddToPlacementGroupResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -func (c *ServerClient) RemoveFromPlacementGroup(ctx context.Context, server *Server) (*Action, *Response, error) { - path := fmt.Sprintf("/servers/%d/actions/remove_from_placement_group", server.ID) - req, err := c.client.NewRequest(ctx, "POST", path, nil) - if err != nil { - return nil, nil, err - } - - respBody := schema.ServerActionRemoveFromPlacementGroupResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/server_type.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/server_type.go deleted file mode 100644 index 37ebb7f09..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/server_type.go +++ /dev/null @@ -1,154 +0,0 @@ -package hcloud - -import ( - "context" - "fmt" - "net/url" - "strconv" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// ServerType represents a server type in the Hetzner Cloud. -type ServerType struct { - ID int - Name string - Description string - Cores int - Memory float32 - Disk int - StorageType StorageType - CPUType CPUType - Architecture Architecture - Pricings []ServerTypeLocationPricing -} - -// StorageType specifies the type of storage. -type StorageType string - -const ( - // StorageTypeLocal is the type for local storage. - StorageTypeLocal StorageType = "local" - - // StorageTypeCeph is the type for remote storage. - StorageTypeCeph StorageType = "ceph" -) - -// CPUType specifies the type of the CPU. -type CPUType string - -const ( - // CPUTypeShared is the type for shared CPU. - CPUTypeShared CPUType = "shared" - - // CPUTypeDedicated is the type for dedicated CPU. - CPUTypeDedicated CPUType = "dedicated" -) - -// ServerTypeClient is a client for the server types API. -type ServerTypeClient struct { - client *Client -} - -// GetByID retrieves a server type by its ID. If the server type does not exist, nil is returned. -func (c *ServerTypeClient) GetByID(ctx context.Context, id int) (*ServerType, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/server_types/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.ServerTypeGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return ServerTypeFromSchema(body.ServerType), resp, nil -} - -// GetByName retrieves a server type by its name. If the server type does not exist, nil is returned. -func (c *ServerTypeClient) GetByName(ctx context.Context, name string) (*ServerType, *Response, error) { - if name == "" { - return nil, nil, nil - } - serverTypes, response, err := c.List(ctx, ServerTypeListOpts{Name: name}) - if len(serverTypes) == 0 { - return nil, response, err - } - return serverTypes[0], response, err -} - -// Get retrieves a server type by its ID if the input can be parsed as an integer, otherwise it -// retrieves a server type by its name. If the server type does not exist, nil is returned. -func (c *ServerTypeClient) Get(ctx context.Context, idOrName string) (*ServerType, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// ServerTypeListOpts specifies options for listing server types. -type ServerTypeListOpts struct { - ListOpts - Name string - Sort []string -} - -func (l ServerTypeListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of server types for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *ServerTypeClient) List(ctx context.Context, opts ServerTypeListOpts) ([]*ServerType, *Response, error) { - path := "/server_types?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.ServerTypeListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - serverTypes := make([]*ServerType, 0, len(body.ServerTypes)) - for _, s := range body.ServerTypes { - serverTypes = append(serverTypes, ServerTypeFromSchema(s)) - } - return serverTypes, resp, nil -} - -// All returns all server types. -func (c *ServerTypeClient) All(ctx context.Context) ([]*ServerType, error) { - allServerTypes := []*ServerType{} - - opts := ServerTypeListOpts{} - opts.PerPage = 50 - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - serverTypes, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allServerTypes = append(allServerTypes, serverTypes...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allServerTypes, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/ssh_key.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/ssh_key.go deleted file mode 100644 index f450c8b92..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/ssh_key.go +++ /dev/null @@ -1,237 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// SSHKey represents a SSH key in the Hetzner Cloud. -type SSHKey struct { - ID int - Name string - Fingerprint string - PublicKey string - Labels map[string]string - Created time.Time -} - -// SSHKeyClient is a client for the SSH keys API. -type SSHKeyClient struct { - client *Client -} - -// GetByID retrieves a SSH key by its ID. If the SSH key does not exist, nil is returned. -func (c *SSHKeyClient) GetByID(ctx context.Context, id int) (*SSHKey, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/ssh_keys/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.SSHKeyGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return SSHKeyFromSchema(body.SSHKey), resp, nil -} - -// GetByName retrieves a SSH key by its name. If the SSH key does not exist, nil is returned. -func (c *SSHKeyClient) GetByName(ctx context.Context, name string) (*SSHKey, *Response, error) { - if name == "" { - return nil, nil, nil - } - sshKeys, response, err := c.List(ctx, SSHKeyListOpts{Name: name}) - if len(sshKeys) == 0 { - return nil, response, err - } - return sshKeys[0], response, err -} - -// GetByFingerprint retreives a SSH key by its fingerprint. If the SSH key does not exist, nil is returned. -func (c *SSHKeyClient) GetByFingerprint(ctx context.Context, fingerprint string) (*SSHKey, *Response, error) { - sshKeys, response, err := c.List(ctx, SSHKeyListOpts{Fingerprint: fingerprint}) - if len(sshKeys) == 0 { - return nil, response, err - } - return sshKeys[0], response, err -} - -// Get retrieves a SSH key by its ID if the input can be parsed as an integer, otherwise it -// retrieves a SSH key by its name. If the SSH key does not exist, nil is returned. -func (c *SSHKeyClient) Get(ctx context.Context, idOrName string) (*SSHKey, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// SSHKeyListOpts specifies options for listing SSH keys. -type SSHKeyListOpts struct { - ListOpts - Name string - Fingerprint string - Sort []string -} - -func (l SSHKeyListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - if l.Fingerprint != "" { - vals.Add("fingerprint", l.Fingerprint) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of SSH keys for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *SSHKeyClient) List(ctx context.Context, opts SSHKeyListOpts) ([]*SSHKey, *Response, error) { - path := "/ssh_keys?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.SSHKeyListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - sshKeys := make([]*SSHKey, 0, len(body.SSHKeys)) - for _, s := range body.SSHKeys { - sshKeys = append(sshKeys, SSHKeyFromSchema(s)) - } - return sshKeys, resp, nil -} - -// All returns all SSH keys. -func (c *SSHKeyClient) All(ctx context.Context) ([]*SSHKey, error) { - return c.AllWithOpts(ctx, SSHKeyListOpts{ListOpts: ListOpts{PerPage: 50}}) -} - -// AllWithOpts returns all SSH keys with the given options. -func (c *SSHKeyClient) AllWithOpts(ctx context.Context, opts SSHKeyListOpts) ([]*SSHKey, error) { - allSSHKeys := []*SSHKey{} - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - sshKeys, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allSSHKeys = append(allSSHKeys, sshKeys...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allSSHKeys, nil -} - -// SSHKeyCreateOpts specifies parameters for creating a SSH key. -type SSHKeyCreateOpts struct { - Name string - PublicKey string - Labels map[string]string -} - -// Validate checks if options are valid. -func (o SSHKeyCreateOpts) Validate() error { - if o.Name == "" { - return errors.New("missing name") - } - if o.PublicKey == "" { - return errors.New("missing public key") - } - return nil -} - -// Create creates a new SSH key with the given options. -func (c *SSHKeyClient) Create(ctx context.Context, opts SSHKeyCreateOpts) (*SSHKey, *Response, error) { - if err := opts.Validate(); err != nil { - return nil, nil, err - } - reqBody := schema.SSHKeyCreateRequest{ - Name: opts.Name, - PublicKey: opts.PublicKey, - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - req, err := c.client.NewRequest(ctx, "POST", "/ssh_keys", bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.SSHKeyCreateResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return SSHKeyFromSchema(respBody.SSHKey), resp, nil -} - -// Delete deletes a SSH key. -func (c *SSHKeyClient) Delete(ctx context.Context, sshKey *SSHKey) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/ssh_keys/%d", sshKey.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// SSHKeyUpdateOpts specifies options for updating a SSH key. -type SSHKeyUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a SSH key. -func (c *SSHKeyClient) Update(ctx context.Context, sshKey *SSHKey, opts SSHKeyUpdateOpts) (*SSHKey, *Response, error) { - reqBody := schema.SSHKeyUpdateRequest{ - Name: opts.Name, - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/ssh_keys/%d", sshKey.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.SSHKeyUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return SSHKeyFromSchema(respBody.SSHKey), resp, nil -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/testing.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/testing.go deleted file mode 100644 index a3cfb2f0c..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/testing.go +++ /dev/null @@ -1,18 +0,0 @@ -package hcloud - -import ( - "testing" - "time" -) - -const apiTimestampFormat = "2006-01-02T15:04:05-07:00" - -func mustParseTime(t *testing.T, layout, value string) time.Time { - t.Helper() - - ts, err := time.Parse(layout, value) - if err != nil { - t.Fatalf("parse time: layout %v: value %v: %v", layout, value, err) - } - return ts -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/volume.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/volume.go deleted file mode 100644 index f939d89bb..000000000 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/volume.go +++ /dev/null @@ -1,403 +0,0 @@ -package hcloud - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "net/url" - "strconv" - "time" - - "github.com/hetznercloud/hcloud-go/hcloud/schema" -) - -// Volume represents a volume in the Hetzner Cloud. -type Volume struct { - ID int - Name string - Status VolumeStatus - Server *Server - Location *Location - Size int - Protection VolumeProtection - Labels map[string]string - LinuxDevice string - Created time.Time -} - -// VolumeProtection represents the protection level of a volume. -type VolumeProtection struct { - Delete bool -} - -// VolumeClient is a client for the volume API. -type VolumeClient struct { - client *Client -} - -// VolumeStatus specifies a volume's status. -type VolumeStatus string - -const ( - // VolumeStatusCreating is the status when a volume is being created. - VolumeStatusCreating VolumeStatus = "creating" - - // VolumeStatusAvailable is the status when a volume is available. - VolumeStatusAvailable VolumeStatus = "available" -) - -// GetByID retrieves a volume by its ID. If the volume does not exist, nil is returned. -func (c *VolumeClient) GetByID(ctx context.Context, id int) (*Volume, *Response, error) { - req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/volumes/%d", id), nil) - if err != nil { - return nil, nil, err - } - - var body schema.VolumeGetResponse - resp, err := c.client.Do(req, &body) - if err != nil { - if IsError(err, ErrorCodeNotFound) { - return nil, resp, nil - } - return nil, nil, err - } - return VolumeFromSchema(body.Volume), resp, nil -} - -// GetByName retrieves a volume by its name. If the volume does not exist, nil is returned. -func (c *VolumeClient) GetByName(ctx context.Context, name string) (*Volume, *Response, error) { - if name == "" { - return nil, nil, nil - } - volumes, response, err := c.List(ctx, VolumeListOpts{Name: name}) - if len(volumes) == 0 { - return nil, response, err - } - return volumes[0], response, err -} - -// Get retrieves a volume by its ID if the input can be parsed as an integer, otherwise it -// retrieves a volume by its name. If the volume does not exist, nil is returned. -func (c *VolumeClient) Get(ctx context.Context, idOrName string) (*Volume, *Response, error) { - if id, err := strconv.Atoi(idOrName); err == nil { - return c.GetByID(ctx, int(id)) - } - return c.GetByName(ctx, idOrName) -} - -// VolumeListOpts specifies options for listing volumes. -type VolumeListOpts struct { - ListOpts - Name string - Status []VolumeStatus - Sort []string -} - -func (l VolumeListOpts) values() url.Values { - vals := l.ListOpts.values() - if l.Name != "" { - vals.Add("name", l.Name) - } - for _, status := range l.Status { - vals.Add("status", string(status)) - } - for _, sort := range l.Sort { - vals.Add("sort", sort) - } - return vals -} - -// List returns a list of volumes for a specific page. -// -// Please note that filters specified in opts are not taken into account -// when their value corresponds to their zero value or when they are empty. -func (c *VolumeClient) List(ctx context.Context, opts VolumeListOpts) ([]*Volume, *Response, error) { - path := "/volumes?" + opts.values().Encode() - req, err := c.client.NewRequest(ctx, "GET", path, nil) - if err != nil { - return nil, nil, err - } - - var body schema.VolumeListResponse - resp, err := c.client.Do(req, &body) - if err != nil { - return nil, nil, err - } - volumes := make([]*Volume, 0, len(body.Volumes)) - for _, s := range body.Volumes { - volumes = append(volumes, VolumeFromSchema(s)) - } - return volumes, resp, nil -} - -// All returns all volumes. -func (c *VolumeClient) All(ctx context.Context) ([]*Volume, error) { - return c.AllWithOpts(ctx, VolumeListOpts{ListOpts: ListOpts{PerPage: 50}}) -} - -// AllWithOpts returns all volumes with the given options. -func (c *VolumeClient) AllWithOpts(ctx context.Context, opts VolumeListOpts) ([]*Volume, error) { - allVolumes := []*Volume{} - - err := c.client.all(func(page int) (*Response, error) { - opts.Page = page - volumes, resp, err := c.List(ctx, opts) - if err != nil { - return resp, err - } - allVolumes = append(allVolumes, volumes...) - return resp, nil - }) - if err != nil { - return nil, err - } - - return allVolumes, nil -} - -// VolumeCreateOpts specifies parameters for creating a volume. -type VolumeCreateOpts struct { - Name string - Size int - Server *Server - Location *Location - Labels map[string]string - Automount *bool - Format *string -} - -// Validate checks if options are valid. -func (o VolumeCreateOpts) Validate() error { - if o.Name == "" { - return errors.New("missing name") - } - if o.Size <= 0 { - return errors.New("size must be greater than 0") - } - if o.Server == nil && o.Location == nil { - return errors.New("one of server or location must be provided") - } - if o.Server != nil && o.Location != nil { - return errors.New("only one of server or location must be provided") - } - if o.Server == nil && (o.Automount != nil && *o.Automount) { - return errors.New("server must be provided when automount is true") - } - return nil -} - -// VolumeCreateResult is the result of creating a volume. -type VolumeCreateResult struct { - Volume *Volume - Action *Action - NextActions []*Action -} - -// Create creates a new volume with the given options. -func (c *VolumeClient) Create(ctx context.Context, opts VolumeCreateOpts) (VolumeCreateResult, *Response, error) { - if err := opts.Validate(); err != nil { - return VolumeCreateResult{}, nil, err - } - reqBody := schema.VolumeCreateRequest{ - Name: opts.Name, - Size: opts.Size, - Automount: opts.Automount, - Format: opts.Format, - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - if opts.Server != nil { - reqBody.Server = Ptr(opts.Server.ID) - } - if opts.Location != nil { - if opts.Location.ID != 0 { - reqBody.Location = opts.Location.ID - } else { - reqBody.Location = opts.Location.Name - } - } - - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return VolumeCreateResult{}, nil, err - } - - req, err := c.client.NewRequest(ctx, "POST", "/volumes", bytes.NewReader(reqBodyData)) - if err != nil { - return VolumeCreateResult{}, nil, err - } - - var respBody schema.VolumeCreateResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return VolumeCreateResult{}, resp, err - } - - var action *Action - if respBody.Action != nil { - action = ActionFromSchema(*respBody.Action) - } - - return VolumeCreateResult{ - Volume: VolumeFromSchema(respBody.Volume), - Action: action, - NextActions: ActionsFromSchema(respBody.NextActions), - }, resp, nil -} - -// Delete deletes a volume. -func (c *VolumeClient) Delete(ctx context.Context, volume *Volume) (*Response, error) { - req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/volumes/%d", volume.ID), nil) - if err != nil { - return nil, err - } - return c.client.Do(req, nil) -} - -// VolumeUpdateOpts specifies options for updating a volume. -type VolumeUpdateOpts struct { - Name string - Labels map[string]string -} - -// Update updates a volume. -func (c *VolumeClient) Update(ctx context.Context, volume *Volume, opts VolumeUpdateOpts) (*Volume, *Response, error) { - reqBody := schema.VolumeUpdateRequest{ - Name: opts.Name, - } - if opts.Labels != nil { - reqBody.Labels = &opts.Labels - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/volumes/%d", volume.ID) - req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.VolumeUpdateResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return VolumeFromSchema(respBody.Volume), resp, nil -} - -// VolumeAttachOpts specifies options for attaching a volume. -type VolumeAttachOpts struct { - Server *Server - Automount *bool -} - -// AttachWithOpts attaches a volume to a server. -func (c *VolumeClient) AttachWithOpts(ctx context.Context, volume *Volume, opts VolumeAttachOpts) (*Action, *Response, error) { - reqBody := schema.VolumeActionAttachVolumeRequest{ - Server: opts.Server.ID, - Automount: opts.Automount, - } - - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/volumes/%d/actions/attach", volume.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.VolumeActionAttachVolumeResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// Attach attaches a volume to a server. -func (c *VolumeClient) Attach(ctx context.Context, volume *Volume, server *Server) (*Action, *Response, error) { - return c.AttachWithOpts(ctx, volume, VolumeAttachOpts{Server: server}) -} - -// Detach detaches a volume from a server. -func (c *VolumeClient) Detach(ctx context.Context, volume *Volume) (*Action, *Response, error) { - var reqBody schema.VolumeActionDetachVolumeRequest - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/volumes/%d/actions/detach", volume.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - var respBody schema.VolumeActionDetachVolumeResponse - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, nil -} - -// VolumeChangeProtectionOpts specifies options for changing the resource protection level of a volume. -type VolumeChangeProtectionOpts struct { - Delete *bool -} - -// ChangeProtection changes the resource protection level of a volume. -func (c *VolumeClient) ChangeProtection(ctx context.Context, volume *Volume, opts VolumeChangeProtectionOpts) (*Action, *Response, error) { - reqBody := schema.VolumeActionChangeProtectionRequest{ - Delete: opts.Delete, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/volumes/%d/actions/change_protection", volume.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.VolumeActionChangeProtectionResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} - -// Resize changes the size of a volume. -func (c *VolumeClient) Resize(ctx context.Context, volume *Volume, size int) (*Action, *Response, error) { - reqBody := schema.VolumeActionResizeVolumeRequest{ - Size: size, - } - reqBodyData, err := json.Marshal(reqBody) - if err != nil { - return nil, nil, err - } - - path := fmt.Sprintf("/volumes/%d/actions/resize", volume.ID) - req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) - if err != nil { - return nil, nil, err - } - - respBody := schema.VolumeActionResizeVolumeResponse{} - resp, err := c.client.Do(req, &respBody) - if err != nil { - return nil, resp, err - } - return ActionFromSchema(respBody.Action), resp, err -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/LICENSE b/vendor/github.com/hetznercloud/hcloud-go/v2/LICENSE similarity index 100% rename from vendor/github.com/hetznercloud/hcloud-go/LICENSE rename to vendor/github.com/hetznercloud/hcloud-go/v2/LICENSE diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/action.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/action.go new file mode 100644 index 000000000..4d3821804 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/action.go @@ -0,0 +1,366 @@ +package hcloud + +import ( + "context" + "fmt" + "net/url" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Action represents an action in the Hetzner Cloud. +type Action struct { + ID int64 + Status ActionStatus + Command string + Progress int + Started time.Time + Finished time.Time + ErrorCode string + ErrorMessage string + Resources []*ActionResource +} + +// ActionStatus represents an action's status. +type ActionStatus string + +// List of action statuses. +const ( + ActionStatusRunning ActionStatus = "running" + ActionStatusSuccess ActionStatus = "success" + ActionStatusError ActionStatus = "error" +) + +// ActionResource references other resources from an action. +type ActionResource struct { + ID int64 + Type ActionResourceType +} + +// ActionResourceType represents an action's resource reference type. +type ActionResourceType string + +// List of action resource reference types. +const ( + ActionResourceTypeServer ActionResourceType = "server" + ActionResourceTypeImage ActionResourceType = "image" + ActionResourceTypeISO ActionResourceType = "iso" + ActionResourceTypeFloatingIP ActionResourceType = "floating_ip" + ActionResourceTypeVolume ActionResourceType = "volume" +) + +// ActionError is the error of an action. +type ActionError struct { + Code string + Message string +} + +func (e ActionError) Error() string { + return fmt.Sprintf("%s (%s)", e.Message, e.Code) +} + +func (a *Action) Error() error { + if a.ErrorCode != "" && a.ErrorMessage != "" { + return ActionError{ + Code: a.ErrorCode, + Message: a.ErrorMessage, + } + } + return nil +} + +// ActionClient is a client for the actions API. +type ActionClient struct { + action *ResourceActionClient +} + +// GetByID retrieves an action by its ID. If the action does not exist, nil is returned. +func (c *ActionClient) GetByID(ctx context.Context, id int64) (*Action, *Response, error) { + return c.action.GetByID(ctx, id) +} + +// ActionListOpts specifies options for listing actions. +type ActionListOpts struct { + ListOpts + ID []int64 + Status []ActionStatus + Sort []string +} + +func (l ActionListOpts) values() url.Values { + vals := l.ListOpts.Values() + for _, id := range l.ID { + vals.Add("id", fmt.Sprintf("%d", id)) + } + for _, status := range l.Status { + vals.Add("status", string(status)) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of actions for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *ActionClient) List(ctx context.Context, opts ActionListOpts) ([]*Action, *Response, error) { + return c.action.List(ctx, opts) +} + +// All returns all actions. +func (c *ActionClient) All(ctx context.Context) ([]*Action, error) { + return c.action.All(ctx, ActionListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all actions for the given options. +func (c *ActionClient) AllWithOpts(ctx context.Context, opts ActionListOpts) ([]*Action, error) { + return c.action.All(ctx, opts) +} + +// WatchOverallProgress watches several actions' progress until they complete +// with success or error. This watching happens in a goroutine and updates are +// provided through the two returned channels: +// +// - The first channel receives percentage updates of the progress, based on +// the number of completed versus total watched actions. The return value +// is an int between 0 and 100. +// - The second channel returned receives errors for actions that did not +// complete successfully, as well as any errors that happened while +// querying the API. +// +// By default, the method keeps watching until all actions have finished +// processing. If you want to be able to cancel the method or configure a +// timeout, use the [context.Context]. Once the method has stopped watching, +// both returned channels are closed. +// +// WatchOverallProgress uses the [WithPollBackoffFunc] of the [Client] to wait +// until sending the next request. +func (c *ActionClient) WatchOverallProgress(ctx context.Context, actions []*Action) (<-chan int, <-chan error) { + errCh := make(chan error, len(actions)) + progressCh := make(chan int) + + go func() { + defer close(errCh) + defer close(progressCh) + + completedIDs := make([]int64, 0, len(actions)) + watchIDs := make(map[int64]struct{}, len(actions)) + for _, action := range actions { + watchIDs[action.ID] = struct{}{} + } + + retries := 0 + previousProgress := 0 + + for { + select { + case <-ctx.Done(): + errCh <- ctx.Err() + return + case <-time.After(c.action.client.pollBackoffFunc(retries)): + retries++ + } + + opts := ActionListOpts{} + for watchID := range watchIDs { + opts.ID = append(opts.ID, watchID) + } + + as, err := c.AllWithOpts(ctx, opts) + if err != nil { + errCh <- err + return + } + if len(as) == 0 { + // No actions returned for the provided IDs, they do not exist in the API. + // We need to catch and fail early for this, otherwise the loop will continue + // indefinitely. + errCh <- fmt.Errorf("failed to wait for actions: remaining actions (%v) are not returned from API", opts.ID) + return + } + + progress := 0 + for _, a := range as { + switch a.Status { + case ActionStatusRunning: + progress += a.Progress + case ActionStatusSuccess: + delete(watchIDs, a.ID) + completedIDs = append(completedIDs, a.ID) + case ActionStatusError: + delete(watchIDs, a.ID) + completedIDs = append(completedIDs, a.ID) + errCh <- fmt.Errorf("action %d failed: %w", a.ID, a.Error()) + } + } + + progress += len(completedIDs) * 100 + if progress != 0 && progress != previousProgress { + sendProgress(progressCh, progress/len(actions)) + previousProgress = progress + } + + if len(watchIDs) == 0 { + return + } + } + }() + + return progressCh, errCh +} + +// WatchProgress watches one action's progress until it completes with success +// or error. This watching happens in a goroutine and updates are provided +// through the two returned channels: +// +// - The first channel receives percentage updates of the progress, based on +// the progress percentage indicated by the API. The return value is an int +// between 0 and 100. +// - The second channel receives any errors that happened while querying the +// API, as well as the error of the action if it did not complete +// successfully, or nil if it did. +// +// By default, the method keeps watching until the action has finished +// processing. If you want to be able to cancel the method or configure a +// timeout, use the [context.Context]. Once the method has stopped watching, +// both returned channels are closed. +// +// WatchProgress uses the [WithPollBackoffFunc] of the [Client] to wait until +// sending the next request. +func (c *ActionClient) WatchProgress(ctx context.Context, action *Action) (<-chan int, <-chan error) { + errCh := make(chan error, 1) + progressCh := make(chan int) + + go func() { + defer close(errCh) + defer close(progressCh) + + retries := 0 + + for { + select { + case <-ctx.Done(): + errCh <- ctx.Err() + return + case <-time.After(c.action.client.pollBackoffFunc(retries)): + retries++ + } + + a, _, err := c.GetByID(ctx, action.ID) + if err != nil { + errCh <- err + return + } + if a == nil { + errCh <- fmt.Errorf("failed to wait for action %d: action not returned from API", action.ID) + return + } + + switch a.Status { + case ActionStatusRunning: + sendProgress(progressCh, a.Progress) + case ActionStatusSuccess: + sendProgress(progressCh, 100) + errCh <- nil + return + case ActionStatusError: + errCh <- a.Error() + return + } + } + }() + + return progressCh, errCh +} + +// sendProgress allows the user to only read from the error channel and ignore any progress updates. +func sendProgress(progressCh chan int, p int) { + select { + case progressCh <- p: + break + default: + break + } +} + +// ResourceActionClient is a client for the actions API exposed by the resource. +type ResourceActionClient struct { + resource string + client *Client +} + +func (c *ResourceActionClient) getBaseURL() string { + if c.resource == "" { + return "" + } + + return "/" + c.resource +} + +// GetByID retrieves an action by its ID. If the action does not exist, nil is returned. +func (c *ResourceActionClient) GetByID(ctx context.Context, id int64) (*Action, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("%s/actions/%d", c.getBaseURL(), id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.ActionGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return ActionFromSchema(body.Action), resp, nil +} + +// List returns a list of actions for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *ResourceActionClient) List(ctx context.Context, opts ActionListOpts) ([]*Action, *Response, error) { + req, err := c.client.NewRequest( + ctx, + "GET", + fmt.Sprintf("%s/actions?%s", c.getBaseURL(), opts.values().Encode()), + nil, + ) + if err != nil { + return nil, nil, err + } + + var body schema.ActionListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + actions := make([]*Action, 0, len(body.Actions)) + for _, i := range body.Actions { + actions = append(actions, ActionFromSchema(i)) + } + return actions, resp, nil +} + +// All returns all actions for the given options. +func (c *ResourceActionClient) All(ctx context.Context, opts ActionListOpts) ([]*Action, error) { + allActions := []*Action{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + actions, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allActions = append(allActions, actions...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allActions, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/architecture.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/architecture.go similarity index 100% rename from vendor/github.com/hetznercloud/hcloud-go/hcloud/architecture.go rename to vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/architecture.go diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/certificate.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/certificate.go new file mode 100644 index 000000000..1c1d9c7ae --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/certificate.go @@ -0,0 +1,370 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// CertificateType is the type of available certificate types. +type CertificateType string + +// Available certificate types. +const ( + CertificateTypeUploaded CertificateType = "uploaded" + CertificateTypeManaged CertificateType = "managed" +) + +// CertificateStatusType is defines the type for the various managed +// certificate status. +type CertificateStatusType string + +// Possible certificate status. +const ( + CertificateStatusTypePending CertificateStatusType = "pending" + CertificateStatusTypeFailed CertificateStatusType = "failed" + + // only in issuance. + CertificateStatusTypeCompleted CertificateStatusType = "completed" + + // only in renewal. + CertificateStatusTypeScheduled CertificateStatusType = "scheduled" + CertificateStatusTypeUnavailable CertificateStatusType = "unavailable" +) + +// CertificateUsedByRefType is the type of used by references for +// certificates. +type CertificateUsedByRefType string + +// Possible users of certificates. +const ( + CertificateUsedByRefTypeLoadBalancer CertificateUsedByRefType = "load_balancer" +) + +// CertificateUsedByRef points to a resource that uses this certificate. +type CertificateUsedByRef struct { + ID int64 + Type CertificateUsedByRefType +} + +// CertificateStatus indicates the status of a managed certificate. +type CertificateStatus struct { + Issuance CertificateStatusType + Renewal CertificateStatusType + Error *Error +} + +// IsFailed returns true if either the Issuance or the Renewal of a certificate +// failed. In this case the FailureReason field details the nature of the +// failure. +func (st *CertificateStatus) IsFailed() bool { + return st.Issuance == CertificateStatusTypeFailed || st.Renewal == CertificateStatusTypeFailed +} + +// Certificate represents a certificate in the Hetzner Cloud. +type Certificate struct { + ID int64 + Name string + Labels map[string]string + Type CertificateType + Certificate string + Created time.Time + NotValidBefore time.Time + NotValidAfter time.Time + DomainNames []string + Fingerprint string + Status *CertificateStatus + UsedBy []CertificateUsedByRef +} + +// CertificateCreateResult is the result of creating a certificate. +type CertificateCreateResult struct { + Certificate *Certificate + Action *Action +} + +// CertificateClient is a client for the Certificates API. +type CertificateClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves a Certificate by its ID. If the Certificate does not exist, nil is returned. +func (c *CertificateClient) GetByID(ctx context.Context, id int64) (*Certificate, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/certificates/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.CertificateGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return CertificateFromSchema(body.Certificate), resp, nil +} + +// GetByName retrieves a Certificate by its name. If the Certificate does not exist, nil is returned. +func (c *CertificateClient) GetByName(ctx context.Context, name string) (*Certificate, *Response, error) { + if name == "" { + return nil, nil, nil + } + Certificate, response, err := c.List(ctx, CertificateListOpts{Name: name}) + if len(Certificate) == 0 { + return nil, response, err + } + return Certificate[0], response, err +} + +// Get retrieves a Certificate by its ID if the input can be parsed as an integer, otherwise it +// retrieves a Certificate by its name. If the Certificate does not exist, nil is returned. +func (c *CertificateClient) Get(ctx context.Context, idOrName string) (*Certificate, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// CertificateListOpts specifies options for listing Certificates. +type CertificateListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l CertificateListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of Certificates for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *CertificateClient) List(ctx context.Context, opts CertificateListOpts) ([]*Certificate, *Response, error) { + path := "/certificates?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.CertificateListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + Certificates := make([]*Certificate, 0, len(body.Certificates)) + for _, s := range body.Certificates { + Certificates = append(Certificates, CertificateFromSchema(s)) + } + return Certificates, resp, nil +} + +// All returns all Certificates. +func (c *CertificateClient) All(ctx context.Context) ([]*Certificate, error) { + return c.AllWithOpts(ctx, CertificateListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all Certificates for the given options. +func (c *CertificateClient) AllWithOpts(ctx context.Context, opts CertificateListOpts) ([]*Certificate, error) { + allCertificates := []*Certificate{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + Certificates, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allCertificates = append(allCertificates, Certificates...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allCertificates, nil +} + +// CertificateCreateOpts specifies options for creating a new Certificate. +type CertificateCreateOpts struct { + Name string + Type CertificateType + Certificate string + PrivateKey string + Labels map[string]string + DomainNames []string +} + +// Validate checks if options are valid. +func (o CertificateCreateOpts) Validate() error { + if o.Name == "" { + return errors.New("missing name") + } + switch o.Type { + case "", CertificateTypeUploaded: + return o.validateUploaded() + case CertificateTypeManaged: + return o.validateManaged() + default: + return fmt.Errorf("invalid type: %s", o.Type) + } +} + +func (o CertificateCreateOpts) validateManaged() error { + if len(o.DomainNames) == 0 { + return errors.New("no domain names") + } + return nil +} + +func (o CertificateCreateOpts) validateUploaded() error { + if o.Certificate == "" { + return errors.New("missing certificate") + } + if o.PrivateKey == "" { + return errors.New("missing private key") + } + return nil +} + +// Create creates a new uploaded certificate. +// +// Create returns an error for certificates of any other type. Use +// CreateCertificate to create such certificates. +func (c *CertificateClient) Create(ctx context.Context, opts CertificateCreateOpts) (*Certificate, *Response, error) { + if !(opts.Type == "" || opts.Type == CertificateTypeUploaded) { + return nil, nil, fmt.Errorf("invalid certificate type: %s", opts.Type) + } + result, resp, err := c.CreateCertificate(ctx, opts) + if err != nil { + return nil, resp, err + } + return result.Certificate, resp, nil +} + +// CreateCertificate creates a new certificate of any type. +func (c *CertificateClient) CreateCertificate( + ctx context.Context, opts CertificateCreateOpts, +) (CertificateCreateResult, *Response, error) { + var ( + action *Action + reqBody schema.CertificateCreateRequest + ) + + if err := opts.Validate(); err != nil { + return CertificateCreateResult{}, nil, err + } + + reqBody.Name = opts.Name + + switch opts.Type { + case "", CertificateTypeUploaded: + reqBody.Type = string(CertificateTypeUploaded) + reqBody.Certificate = opts.Certificate + reqBody.PrivateKey = opts.PrivateKey + case CertificateTypeManaged: + reqBody.Type = string(CertificateTypeManaged) + reqBody.DomainNames = opts.DomainNames + default: + return CertificateCreateResult{}, nil, fmt.Errorf("invalid certificate type: %v", opts.Type) + } + + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return CertificateCreateResult{}, nil, err + } + req, err := c.client.NewRequest(ctx, "POST", "/certificates", bytes.NewReader(reqBodyData)) + if err != nil { + return CertificateCreateResult{}, nil, err + } + + respBody := schema.CertificateCreateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return CertificateCreateResult{}, resp, err + } + cert := CertificateFromSchema(respBody.Certificate) + if respBody.Action != nil { + action = ActionFromSchema(*respBody.Action) + } + + return CertificateCreateResult{Certificate: cert, Action: action}, resp, nil +} + +// CertificateUpdateOpts specifies options for updating a Certificate. +type CertificateUpdateOpts struct { + Name string + Labels map[string]string +} + +// Update updates a Certificate. +func (c *CertificateClient) Update(ctx context.Context, certificate *Certificate, opts CertificateUpdateOpts) (*Certificate, *Response, error) { + reqBody := schema.CertificateUpdateRequest{} + if opts.Name != "" { + reqBody.Name = &opts.Name + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/certificates/%d", certificate.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.CertificateUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return CertificateFromSchema(respBody.Certificate), resp, nil +} + +// Delete deletes a certificate. +func (c *CertificateClient) Delete(ctx context.Context, certificate *Certificate) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/certificates/%d", certificate.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// RetryIssuance retries the issuance of a failed managed certificate. +func (c *CertificateClient) RetryIssuance(ctx context.Context, certificate *Certificate) (*Action, *Response, error) { + var respBody schema.CertificateIssuanceRetryResponse + + req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("/certificates/%d/actions/retry", certificate.ID), nil) + if err != nil { + return nil, nil, err + } + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, nil, err + } + action := ActionFromSchema(respBody.Action) + return action, resp, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/client.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/client.go new file mode 100644 index 000000000..917bb513a --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/client.go @@ -0,0 +1,456 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/http/httputil" + "net/url" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "golang.org/x/net/http/httpguts" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/internal/instrumentation" + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Endpoint is the base URL of the API. +const Endpoint = "https://api.hetzner.cloud/v1" + +// UserAgent is the value for the library part of the User-Agent header +// that is sent with each request. +const UserAgent = "hcloud-go/" + Version + +// A BackoffFunc returns the duration to wait before performing the +// next retry. The retries argument specifies how many retries have +// already been performed. When called for the first time, retries is 0. +type BackoffFunc func(retries int) time.Duration + +// ConstantBackoff returns a BackoffFunc which backs off for +// constant duration d. +func ConstantBackoff(d time.Duration) BackoffFunc { + return func(_ int) time.Duration { + return d + } +} + +// ExponentialBackoff returns a BackoffFunc which implements an exponential +// backoff. +// It uses the formula: +// +// b^retries * d +func ExponentialBackoff(b float64, d time.Duration) BackoffFunc { + return func(retries int) time.Duration { + return time.Duration(math.Pow(b, float64(retries))) * d + } +} + +// Client is a client for the Hetzner Cloud API. +type Client struct { + endpoint string + token string + tokenValid bool + backoffFunc BackoffFunc + pollBackoffFunc BackoffFunc + httpClient *http.Client + applicationName string + applicationVersion string + userAgent string + debugWriter io.Writer + instrumentationRegistry prometheus.Registerer + + Action ActionClient + Certificate CertificateClient + Datacenter DatacenterClient + Firewall FirewallClient + FloatingIP FloatingIPClient + Image ImageClient + ISO ISOClient + LoadBalancer LoadBalancerClient + LoadBalancerType LoadBalancerTypeClient + Location LocationClient + Network NetworkClient + Pricing PricingClient + Server ServerClient + ServerType ServerTypeClient + SSHKey SSHKeyClient + Volume VolumeClient + PlacementGroup PlacementGroupClient + RDNS RDNSClient + PrimaryIP PrimaryIPClient +} + +// A ClientOption is used to configure a Client. +type ClientOption func(*Client) + +// WithEndpoint configures a Client to use the specified API endpoint. +func WithEndpoint(endpoint string) ClientOption { + return func(client *Client) { + client.endpoint = strings.TrimRight(endpoint, "/") + } +} + +// WithToken configures a Client to use the specified token for authentication. +func WithToken(token string) ClientOption { + return func(client *Client) { + client.token = token + client.tokenValid = httpguts.ValidHeaderFieldValue(token) + } +} + +// WithPollInterval configures a Client to use the specified interval when +// polling from the API. +// +// Deprecated: Setting the poll interval is deprecated, you can now configure +// [WithPollBackoffFunc] with a [ConstantBackoff] to get the same results. To +// migrate your code, replace your usage like this: +// +// // before +// hcloud.WithPollInterval(2 * time.Second) +// // now +// hcloud.WithPollBackoffFunc(hcloud.ConstantBackoff(2 * time.Second)) +func WithPollInterval(pollInterval time.Duration) ClientOption { + return WithPollBackoffFunc(ConstantBackoff(pollInterval)) +} + +// WithPollBackoffFunc configures a Client to use the specified backoff +// function when polling from the API. +func WithPollBackoffFunc(f BackoffFunc) ClientOption { + return func(client *Client) { + client.pollBackoffFunc = f + } +} + +// WithBackoffFunc configures a Client to use the specified backoff function. +// The backoff function is used for retrying HTTP requests. +func WithBackoffFunc(f BackoffFunc) ClientOption { + return func(client *Client) { + client.backoffFunc = f + } +} + +// WithApplication configures a Client with the given application name and +// application version. The version may be blank. Programs are encouraged +// to at least set an application name. +func WithApplication(name, version string) ClientOption { + return func(client *Client) { + client.applicationName = name + client.applicationVersion = version + } +} + +// WithDebugWriter configures a Client to print debug information to the given +// writer. To, for example, print debug information on stderr, set it to os.Stderr. +func WithDebugWriter(debugWriter io.Writer) ClientOption { + return func(client *Client) { + client.debugWriter = debugWriter + } +} + +// WithHTTPClient configures a Client to perform HTTP requests with httpClient. +func WithHTTPClient(httpClient *http.Client) ClientOption { + return func(client *Client) { + client.httpClient = httpClient + } +} + +// WithInstrumentation configures a Client to collect metrics about the performed HTTP requests. +func WithInstrumentation(registry prometheus.Registerer) ClientOption { + return func(client *Client) { + client.instrumentationRegistry = registry + } +} + +// NewClient creates a new client. +func NewClient(options ...ClientOption) *Client { + client := &Client{ + endpoint: Endpoint, + tokenValid: true, + httpClient: &http.Client{}, + backoffFunc: ExponentialBackoff(2, 500*time.Millisecond), + pollBackoffFunc: ConstantBackoff(500 * time.Millisecond), + } + + for _, option := range options { + option(client) + } + + client.buildUserAgent() + if client.instrumentationRegistry != nil { + i := instrumentation.New("api", client.instrumentationRegistry) + client.httpClient.Transport = i.InstrumentedRoundTripper() + } + + client.Action = ActionClient{action: &ResourceActionClient{client: client}} + client.Datacenter = DatacenterClient{client: client} + client.FloatingIP = FloatingIPClient{client: client, Action: &ResourceActionClient{client: client, resource: "floating_ips"}} + client.Image = ImageClient{client: client, Action: &ResourceActionClient{client: client, resource: "images"}} + client.ISO = ISOClient{client: client} + client.Location = LocationClient{client: client} + client.Network = NetworkClient{client: client, Action: &ResourceActionClient{client: client, resource: "networks"}} + client.Pricing = PricingClient{client: client} + client.Server = ServerClient{client: client, Action: &ResourceActionClient{client: client, resource: "servers"}} + client.ServerType = ServerTypeClient{client: client} + client.SSHKey = SSHKeyClient{client: client} + client.Volume = VolumeClient{client: client, Action: &ResourceActionClient{client: client, resource: "volumes"}} + client.LoadBalancer = LoadBalancerClient{client: client, Action: &ResourceActionClient{client: client, resource: "load_balancers"}} + client.LoadBalancerType = LoadBalancerTypeClient{client: client} + client.Certificate = CertificateClient{client: client, Action: &ResourceActionClient{client: client, resource: "certificates"}} + client.Firewall = FirewallClient{client: client, Action: &ResourceActionClient{client: client, resource: "firewalls"}} + client.PlacementGroup = PlacementGroupClient{client: client} + client.RDNS = RDNSClient{client: client} + client.PrimaryIP = PrimaryIPClient{client: client, Action: &ResourceActionClient{client: client, resource: "primary_ips"}} + + return client +} + +// NewRequest creates an HTTP request against the API. The returned request +// is assigned with ctx and has all necessary headers set (auth, user agent, etc.). +func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { + url := c.endpoint + path + req, err := http.NewRequest(method, url, body) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", c.userAgent) + + if !c.tokenValid { + return nil, errors.New("Authorization token contains invalid characters") + } else if c.token != "" { + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token)) + } + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + req = req.WithContext(ctx) + return req, nil +} + +// Do performs an HTTP request against the API. +func (c *Client) Do(r *http.Request, v interface{}) (*Response, error) { + var retries int + var body []byte + var err error + if r.ContentLength > 0 { + body, err = io.ReadAll(r.Body) + if err != nil { + r.Body.Close() + return nil, err + } + r.Body.Close() + } + for { + if r.ContentLength > 0 { + r.Body = io.NopCloser(bytes.NewReader(body)) + } + + if c.debugWriter != nil { + dumpReq, err := dumpRequest(r) + if err != nil { + return nil, err + } + fmt.Fprintf(c.debugWriter, "--- Request:\n%s\n\n", dumpReq) + } + + resp, err := c.httpClient.Do(r) + if err != nil { + return nil, err + } + response := &Response{Response: resp} + body, err := io.ReadAll(resp.Body) + if err != nil { + resp.Body.Close() + return response, err + } + resp.Body.Close() + resp.Body = io.NopCloser(bytes.NewReader(body)) + + if c.debugWriter != nil { + dumpResp, err := httputil.DumpResponse(resp, true) + if err != nil { + return nil, err + } + fmt.Fprintf(c.debugWriter, "--- Response:\n%s\n\n", dumpResp) + } + + if err = response.readMeta(body); err != nil { + return response, fmt.Errorf("hcloud: error reading response meta data: %s", err) + } + + if response.StatusCode >= 400 && response.StatusCode <= 599 { + err = errorFromResponse(response, body) + if err == nil { + err = fmt.Errorf("hcloud: server responded with status code %d", resp.StatusCode) + } else if IsError(err, ErrorCodeConflict) { + c.backoff(retries) + retries++ + continue + } + return response, err + } + if v != nil { + if w, ok := v.(io.Writer); ok { + _, err = io.Copy(w, bytes.NewReader(body)) + } else { + err = json.Unmarshal(body, v) + } + } + + return response, err + } +} + +func (c *Client) backoff(retries int) { + time.Sleep(c.backoffFunc(retries)) +} + +func (c *Client) all(f func(int) (*Response, error)) error { + var ( + page = 1 + ) + for { + resp, err := f(page) + if err != nil { + return err + } + if resp.Meta.Pagination == nil || resp.Meta.Pagination.NextPage == 0 { + return nil + } + page = resp.Meta.Pagination.NextPage + } +} + +func (c *Client) buildUserAgent() { + switch { + case c.applicationName != "" && c.applicationVersion != "": + c.userAgent = c.applicationName + "/" + c.applicationVersion + " " + UserAgent + case c.applicationName != "" && c.applicationVersion == "": + c.userAgent = c.applicationName + " " + UserAgent + default: + c.userAgent = UserAgent + } +} + +func dumpRequest(r *http.Request) ([]byte, error) { + // Duplicate the request, so we can redact the auth header + rDuplicate := r.Clone(context.Background()) + rDuplicate.Header.Set("Authorization", "REDACTED") + + // To get the request body we need to read it before the request was actually sent. + // See https://github.com/golang/go/issues/29792 + dumpReq, err := httputil.DumpRequestOut(rDuplicate, true) + if err != nil { + return nil, err + } + + // Set original request body to the duplicate created by DumpRequestOut. The request body is not duplicated + // by .Clone() and instead just referenced, so it would be completely read otherwise. + r.Body = rDuplicate.Body + + return dumpReq, nil +} + +func errorFromResponse(resp *Response, body []byte) error { + if !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { + return nil + } + + var respBody schema.ErrorResponse + if err := json.Unmarshal(body, &respBody); err != nil { + return nil + } + if respBody.Error.Code == "" && respBody.Error.Message == "" { + return nil + } + + hcErr := ErrorFromSchema(respBody.Error) + hcErr.response = resp + return hcErr +} + +// Response represents a response from the API. It embeds http.Response. +type Response struct { + *http.Response + Meta Meta +} + +func (r *Response) readMeta(body []byte) error { + if h := r.Header.Get("RateLimit-Limit"); h != "" { + r.Meta.Ratelimit.Limit, _ = strconv.Atoi(h) + } + if h := r.Header.Get("RateLimit-Remaining"); h != "" { + r.Meta.Ratelimit.Remaining, _ = strconv.Atoi(h) + } + if h := r.Header.Get("RateLimit-Reset"); h != "" { + if ts, err := strconv.ParseInt(h, 10, 64); err == nil { + r.Meta.Ratelimit.Reset = time.Unix(ts, 0) + } + } + + if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { + var s schema.MetaResponse + if err := json.Unmarshal(body, &s); err != nil { + return err + } + if s.Meta.Pagination != nil { + p := PaginationFromSchema(*s.Meta.Pagination) + r.Meta.Pagination = &p + } + } + + return nil +} + +// Meta represents meta information included in an API response. +type Meta struct { + Pagination *Pagination + Ratelimit Ratelimit +} + +// Pagination represents pagination meta information. +type Pagination struct { + Page int + PerPage int + PreviousPage int + NextPage int + LastPage int + TotalEntries int +} + +// Ratelimit represents ratelimit information. +type Ratelimit struct { + Limit int + Remaining int + Reset time.Time +} + +// ListOpts specifies options for listing resources. +type ListOpts struct { + Page int // Page (starting at 1) + PerPage int // Items per page (0 means default) + LabelSelector string // Label selector for filtering by labels +} + +// Values returns the ListOpts as URL values. +func (l ListOpts) Values() url.Values { + vals := url.Values{} + if l.Page > 0 { + vals.Add("page", strconv.Itoa(l.Page)) + } + if l.PerPage > 0 { + vals.Add("per_page", strconv.Itoa(l.PerPage)) + } + if len(l.LabelSelector) > 0 { + vals.Add("label_selector", l.LabelSelector) + } + return vals +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/datacenter.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/datacenter.go new file mode 100644 index 000000000..42c443da3 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/datacenter.go @@ -0,0 +1,136 @@ +package hcloud + +import ( + "context" + "fmt" + "net/url" + "strconv" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Datacenter represents a datacenter in the Hetzner Cloud. +type Datacenter struct { + ID int64 + Name string + Description string + Location *Location + ServerTypes DatacenterServerTypes +} + +// DatacenterServerTypes represents the server types available and supported in a datacenter. +type DatacenterServerTypes struct { + Supported []*ServerType + AvailableForMigration []*ServerType + Available []*ServerType +} + +// DatacenterClient is a client for the datacenter API. +type DatacenterClient struct { + client *Client +} + +// GetByID retrieves a datacenter by its ID. If the datacenter does not exist, nil is returned. +func (c *DatacenterClient) GetByID(ctx context.Context, id int64) (*Datacenter, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/datacenters/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.DatacenterGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, resp, err + } + return DatacenterFromSchema(body.Datacenter), resp, nil +} + +// GetByName retrieves a datacenter by its name. If the datacenter does not exist, nil is returned. +func (c *DatacenterClient) GetByName(ctx context.Context, name string) (*Datacenter, *Response, error) { + if name == "" { + return nil, nil, nil + } + datacenters, response, err := c.List(ctx, DatacenterListOpts{Name: name}) + if len(datacenters) == 0 { + return nil, response, err + } + return datacenters[0], response, err +} + +// Get retrieves a datacenter by its ID if the input can be parsed as an integer, otherwise it +// retrieves a datacenter by its name. If the datacenter does not exist, nil is returned. +func (c *DatacenterClient) Get(ctx context.Context, idOrName string) (*Datacenter, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// DatacenterListOpts specifies options for listing datacenters. +type DatacenterListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l DatacenterListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of datacenters for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *DatacenterClient) List(ctx context.Context, opts DatacenterListOpts) ([]*Datacenter, *Response, error) { + path := "/datacenters?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.DatacenterListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + datacenters := make([]*Datacenter, 0, len(body.Datacenters)) + for _, i := range body.Datacenters { + datacenters = append(datacenters, DatacenterFromSchema(i)) + } + return datacenters, resp, nil +} + +// All returns all datacenters. +func (c *DatacenterClient) All(ctx context.Context) ([]*Datacenter, error) { + return c.AllWithOpts(ctx, DatacenterListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all datacenters for the given options. +func (c *DatacenterClient) AllWithOpts(ctx context.Context, opts DatacenterListOpts) ([]*Datacenter, error) { + allDatacenters := []*Datacenter{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + datacenters, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allDatacenters = append(allDatacenters, datacenters...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allDatacenters, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/deprecation.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/deprecation.go new file mode 100644 index 000000000..17c6949cb --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/deprecation.go @@ -0,0 +1,59 @@ +package hcloud + +import "time" + +// Deprecatable is a shared interface implemented by all Resources that have a defined deprecation workflow. +type Deprecatable interface { + // IsDeprecated returns true if the resource is marked as deprecated. + IsDeprecated() bool + + // UnavailableAfter returns the time that the deprecated resource will be removed from the API. + // This only returns a valid value if [Deprecatable.IsDeprecated] returned true. + UnavailableAfter() time.Time + + // DeprecationAnnounced returns the time that the deprecation of this resource was announced. + // This only returns a valid value if [Deprecatable.IsDeprecated] returned true. + DeprecationAnnounced() time.Time +} + +// DeprecationInfo contains the information published when a resource is actually deprecated. +type DeprecationInfo struct { + Announced time.Time + UnavailableAfter time.Time +} + +// DeprecatableResource implements the [Deprecatable] interface and can be embedded in structs for Resources that can be +// deprecated. +type DeprecatableResource struct { + Deprecation *DeprecationInfo +} + +// IsDeprecated returns true if the resource is marked as deprecated. +func (d DeprecatableResource) IsDeprecated() bool { + return d.Deprecation != nil +} + +// UnavailableAfter returns the time that the deprecated resource will be removed from the API. +// This only returns a valid value if [Deprecatable.IsDeprecated] returned true. +func (d DeprecatableResource) UnavailableAfter() time.Time { + if !d.IsDeprecated() { + // Return "null" time if resource is not deprecated + return time.Unix(0, 0) + } + + return d.Deprecation.UnavailableAfter +} + +// DeprecationAnnounced returns the time that the deprecation of this resource was announced. +// This only returns a valid value if [Deprecatable.IsDeprecated] returned true. +func (d DeprecatableResource) DeprecationAnnounced() time.Time { + if !d.IsDeprecated() { + // Return "null" time if resource is not deprecated + return time.Unix(0, 0) + } + + return d.Deprecation.Announced +} + +// Make sure that all expected Resources actually implement the interface. +var _ Deprecatable = ServerType{} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/error.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/error.go new file mode 100644 index 000000000..653043e6d --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/error.go @@ -0,0 +1,141 @@ +package hcloud + +import ( + "fmt" + "net" +) + +// ErrorCode represents an error code returned from the API. +type ErrorCode string + +// Error codes returned from the API. +const ( + ErrorCodeServiceError ErrorCode = "service_error" // Generic service error + ErrorCodeRateLimitExceeded ErrorCode = "rate_limit_exceeded" // Rate limit exceeded + ErrorCodeUnknownError ErrorCode = "unknown_error" // Unknown error + ErrorCodeNotFound ErrorCode = "not_found" // Resource not found + ErrorCodeInvalidInput ErrorCode = "invalid_input" // Validation error + ErrorCodeForbidden ErrorCode = "forbidden" // Insufficient permissions + ErrorCodeUnauthorized ErrorCode = "unauthorized" // Request was made with an invalid or unknown token + ErrorCodeJSONError ErrorCode = "json_error" // Invalid JSON in request + ErrorCodeLocked ErrorCode = "locked" // Item is locked (Another action is running) + ErrorCodeResourceLimitExceeded ErrorCode = "resource_limit_exceeded" // Resource limit exceeded + ErrorCodeResourceUnavailable ErrorCode = "resource_unavailable" // Resource currently unavailable + ErrorCodeUniquenessError ErrorCode = "uniqueness_error" // One or more fields must be unique + ErrorCodeProtected ErrorCode = "protected" // The actions you are trying is protected + ErrorCodeMaintenance ErrorCode = "maintenance" // Cannot perform operation due to maintenance + ErrorCodeConflict ErrorCode = "conflict" // The resource has changed during the request, please retry + ErrorCodeRobotUnavailable ErrorCode = "robot_unavailable" // Robot was not available. The caller may retry the operation after a short delay + ErrorCodeResourceLocked ErrorCode = "resource_locked" // The resource is locked. The caller should contact support + ErrorUnsupportedError ErrorCode = "unsupported_error" // The given resource does not support this + + // Server related error codes. + + ErrorCodeInvalidServerType ErrorCode = "invalid_server_type" // The server type does not fit for the given server or is deprecated + ErrorCodeServerNotStopped ErrorCode = "server_not_stopped" // The action requires a stopped server + ErrorCodeNetworksOverlap ErrorCode = "networks_overlap" // The network IP range overlaps with one of the server networks + ErrorCodePlacementError ErrorCode = "placement_error" // An error during the placement occurred + ErrorCodeServerAlreadyAttached ErrorCode = "server_already_attached" // The server is already attached to the resource + + // Load Balancer related error codes. + + ErrorCodeIPNotOwned ErrorCode = "ip_not_owned" // The IP you are trying to add as a target is not owned by the Project owner + ErrorCodeSourcePortAlreadyUsed ErrorCode = "source_port_already_used" // The source port you are trying to add is already in use + ErrorCodeCloudResourceIPNotAllowed ErrorCode = "cloud_resource_ip_not_allowed" // The IP you are trying to add as a target belongs to a Hetzner Cloud resource + ErrorCodeServerNotAttachedToNetwork ErrorCode = "server_not_attached_to_network" // The server you are trying to add as a target is not attached to the same network as the Load Balancer + ErrorCodeTargetAlreadyDefined ErrorCode = "target_already_defined" // The Load Balancer target you are trying to define is already defined + ErrorCodeInvalidLoadBalancerType ErrorCode = "invalid_load_balancer_type" // The Load Balancer type does not fit for the given Load Balancer + ErrorCodeLoadBalancerAlreadyAttached ErrorCode = "load_balancer_already_attached" // The Load Balancer is already attached to a network + ErrorCodeTargetsWithoutUsePrivateIP ErrorCode = "targets_without_use_private_ip" // The Load Balancer has targets that use the public IP instead of the private IP + ErrorCodeLoadBalancerNotAttachedToNetwork ErrorCode = "load_balancer_not_attached_to_network" // The Load Balancer is not attached to a network + + // Network related error codes. + + ErrorCodeIPNotAvailable ErrorCode = "ip_not_available" // The provided Network IP is not available + ErrorCodeNoSubnetAvailable ErrorCode = "no_subnet_available" // No Subnet or IP is available for the Load Balancer/Server within the network + ErrorCodeVSwitchAlreadyUsed ErrorCode = "vswitch_id_already_used" // The given Robot vSwitch ID is already registered in another network + + // Volume related error codes. + + ErrorCodeNoSpaceLeftInLocation ErrorCode = "no_space_left_in_location" // There is no volume space left in the given location + ErrorCodeVolumeAlreadyAttached ErrorCode = "volume_already_attached" // Volume is already attached to a server, detach first + + // Firewall related error codes. + + ErrorCodeFirewallAlreadyApplied ErrorCode = "firewall_already_applied" // Firewall was already applied on resource + ErrorCodeFirewallAlreadyRemoved ErrorCode = "firewall_already_removed" // Firewall was already removed from the resource + ErrorCodeIncompatibleNetworkType ErrorCode = "incompatible_network_type" // The Network type is incompatible for the given resource + ErrorCodeResourceInUse ErrorCode = "resource_in_use" // Firewall must not be in use to be deleted + ErrorCodeServerAlreadyAdded ErrorCode = "server_already_added" // Server added more than one time to resource + ErrorCodeFirewallResourceNotFound ErrorCode = "firewall_resource_not_found" // Resource a firewall should be attached to / detached from not found + + // Certificate related error codes. + + ErrorCodeCAARecordDoesNotAllowCA ErrorCode = "caa_record_does_not_allow_ca" // CAA record does not allow certificate authority + ErrorCodeCADNSValidationFailed ErrorCode = "ca_dns_validation_failed" // Certificate Authority: DNS validation failed + ErrorCodeCATooManyAuthorizationsFailedRecently ErrorCode = "ca_too_many_authorizations_failed_recently" // Certificate Authority: Too many authorizations failed recently + ErrorCodeCATooManyCertificatedIssuedForRegisteredDomain ErrorCode = "ca_too_many_certificates_issued_for_registered_domain" // Certificate Authority: Too many certificates issued for registered domain + ErrorCodeCATooManyDuplicateCertificates ErrorCode = "ca_too_many_duplicate_certificates" // Certificate Authority: Too many duplicate certificates + ErrorCodeCloudNotVerifyDomainDelegatedToZone ErrorCode = "could_not_verify_domain_delegated_to_zone" // Could not verify domain delegated to zone + ErrorCodeDNSZoneNotFound ErrorCode = "dns_zone_not_found" // DNS zone not found + + // Deprecated error codes. + + // Deprecated: The actual value of this error code is limit_reached. The + // new error code rate_limit_exceeded for rate limiting was introduced + // before Hetzner Cloud launched into the public. To make clients using the + // old error code still work as expected, we set the value of the old error + // code to that of the new error code. + ErrorCodeLimitReached = ErrorCodeRateLimitExceeded +) + +// Error is an error returned from the API. +type Error struct { + Code ErrorCode + Message string + Details interface{} + + response *Response +} + +func (e Error) Error() string { + return fmt.Sprintf("%s (%s)", e.Message, e.Code) +} + +// Response returns the [Response] that contained the error if available. +func (e Error) Response() *Response { + return e.response +} + +// ErrorDetailsInvalidInput contains the details of an 'invalid_input' error. +type ErrorDetailsInvalidInput struct { + Fields []ErrorDetailsInvalidInputField +} + +// ErrorDetailsInvalidInputField contains the validation errors reported on a field. +type ErrorDetailsInvalidInputField struct { + Name string + Messages []string +} + +// IsError returns whether err is an API error with the given error code. +func IsError(err error, code ErrorCode) bool { + apiErr, ok := err.(Error) + return ok && apiErr.Code == code +} + +type InvalidIPError struct { + IP string +} + +func (e InvalidIPError) Error() string { + return fmt.Sprintf("could not parse ip address %s", e.IP) +} + +type DNSNotFoundError struct { + IP net.IP +} + +func (e DNSNotFoundError) Error() string { + return fmt.Sprintf("dns for ip %s not found", e.IP.String()) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/firewall.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/firewall.go new file mode 100644 index 000000000..512c32ffe --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/firewall.go @@ -0,0 +1,371 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Firewall represents a Firewall in the Hetzner Cloud. +type Firewall struct { + ID int64 + Name string + Labels map[string]string + Created time.Time + Rules []FirewallRule + AppliedTo []FirewallResource +} + +// FirewallRule represents a Firewall's rules. +type FirewallRule struct { + Direction FirewallRuleDirection + SourceIPs []net.IPNet + DestinationIPs []net.IPNet + Protocol FirewallRuleProtocol + Port *string + Description *string +} + +// FirewallRuleDirection specifies the direction of a Firewall rule. +type FirewallRuleDirection string + +const ( + // FirewallRuleDirectionIn specifies a rule for inbound traffic. + FirewallRuleDirectionIn FirewallRuleDirection = "in" + + // FirewallRuleDirectionOut specifies a rule for outbound traffic. + FirewallRuleDirectionOut FirewallRuleDirection = "out" +) + +// FirewallRuleProtocol specifies the protocol of a Firewall rule. +type FirewallRuleProtocol string + +const ( + // FirewallRuleProtocolTCP specifies a TCP rule. + FirewallRuleProtocolTCP FirewallRuleProtocol = "tcp" + // FirewallRuleProtocolUDP specifies a UDP rule. + FirewallRuleProtocolUDP FirewallRuleProtocol = "udp" + // FirewallRuleProtocolICMP specifies an ICMP rule. + FirewallRuleProtocolICMP FirewallRuleProtocol = "icmp" + // FirewallRuleProtocolESP specifies an esp rule. + FirewallRuleProtocolESP FirewallRuleProtocol = "esp" + // FirewallRuleProtocolGRE specifies an gre rule. + FirewallRuleProtocolGRE FirewallRuleProtocol = "gre" +) + +// FirewallResourceType specifies the resource to apply a Firewall on. +type FirewallResourceType string + +const ( + // FirewallResourceTypeServer specifies a Server. + FirewallResourceTypeServer FirewallResourceType = "server" + // FirewallResourceTypeLabelSelector specifies a LabelSelector. + FirewallResourceTypeLabelSelector FirewallResourceType = "label_selector" +) + +// FirewallResource represents a resource to apply the new Firewall on. +type FirewallResource struct { + Type FirewallResourceType + Server *FirewallResourceServer + LabelSelector *FirewallResourceLabelSelector +} + +// FirewallResourceServer represents a Server to apply a Firewall on. +type FirewallResourceServer struct { + ID int64 +} + +// FirewallResourceLabelSelector represents a LabelSelector to apply a Firewall on. +type FirewallResourceLabelSelector struct { + Selector string +} + +// FirewallClient is a client for the Firewalls API. +type FirewallClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves a Firewall by its ID. If the Firewall does not exist, nil is returned. +func (c *FirewallClient) GetByID(ctx context.Context, id int64) (*Firewall, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/firewalls/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.FirewallGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return FirewallFromSchema(body.Firewall), resp, nil +} + +// GetByName retrieves a Firewall by its name. If the Firewall does not exist, nil is returned. +func (c *FirewallClient) GetByName(ctx context.Context, name string) (*Firewall, *Response, error) { + if name == "" { + return nil, nil, nil + } + firewalls, response, err := c.List(ctx, FirewallListOpts{Name: name}) + if len(firewalls) == 0 { + return nil, response, err + } + return firewalls[0], response, err +} + +// Get retrieves a Firewall by its ID if the input can be parsed as an integer, otherwise it +// retrieves a Firewall by its name. If the Firewall does not exist, nil is returned. +func (c *FirewallClient) Get(ctx context.Context, idOrName string) (*Firewall, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// FirewallListOpts specifies options for listing Firewalls. +type FirewallListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l FirewallListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of Firewalls for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *FirewallClient) List(ctx context.Context, opts FirewallListOpts) ([]*Firewall, *Response, error) { + path := "/firewalls?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.FirewallListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + firewalls := make([]*Firewall, 0, len(body.Firewalls)) + for _, s := range body.Firewalls { + firewalls = append(firewalls, FirewallFromSchema(s)) + } + return firewalls, resp, nil +} + +// All returns all Firewalls. +func (c *FirewallClient) All(ctx context.Context) ([]*Firewall, error) { + return c.AllWithOpts(ctx, FirewallListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all Firewalls for the given options. +func (c *FirewallClient) AllWithOpts(ctx context.Context, opts FirewallListOpts) ([]*Firewall, error) { + allFirewalls := []*Firewall{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + firewalls, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allFirewalls = append(allFirewalls, firewalls...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allFirewalls, nil +} + +// FirewallCreateOpts specifies options for creating a new Firewall. +type FirewallCreateOpts struct { + Name string + Labels map[string]string + Rules []FirewallRule + ApplyTo []FirewallResource +} + +// Validate checks if options are valid. +func (o FirewallCreateOpts) Validate() error { + if o.Name == "" { + return errors.New("missing name") + } + return nil +} + +// FirewallCreateResult is the result of a create Firewall call. +type FirewallCreateResult struct { + Firewall *Firewall + Actions []*Action +} + +// Create creates a new Firewall. +func (c *FirewallClient) Create(ctx context.Context, opts FirewallCreateOpts) (FirewallCreateResult, *Response, error) { + if err := opts.Validate(); err != nil { + return FirewallCreateResult{}, nil, err + } + reqBody := firewallCreateOptsToSchema(opts) + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return FirewallCreateResult{}, nil, err + } + req, err := c.client.NewRequest(ctx, "POST", "/firewalls", bytes.NewReader(reqBodyData)) + if err != nil { + return FirewallCreateResult{}, nil, err + } + + respBody := schema.FirewallCreateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return FirewallCreateResult{}, resp, err + } + result := FirewallCreateResult{ + Firewall: FirewallFromSchema(respBody.Firewall), + Actions: ActionsFromSchema(respBody.Actions), + } + return result, resp, nil +} + +// FirewallUpdateOpts specifies options for updating a Firewall. +type FirewallUpdateOpts struct { + Name string + Labels map[string]string +} + +// Update updates a Firewall. +func (c *FirewallClient) Update(ctx context.Context, firewall *Firewall, opts FirewallUpdateOpts) (*Firewall, *Response, error) { + reqBody := schema.FirewallUpdateRequest{} + if opts.Name != "" { + reqBody.Name = &opts.Name + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/firewalls/%d", firewall.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.FirewallUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return FirewallFromSchema(respBody.Firewall), resp, nil +} + +// Delete deletes a Firewall. +func (c *FirewallClient) Delete(ctx context.Context, firewall *Firewall) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/firewalls/%d", firewall.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// FirewallSetRulesOpts specifies options for setting rules of a Firewall. +type FirewallSetRulesOpts struct { + Rules []FirewallRule +} + +// SetRules sets the rules of a Firewall. +func (c *FirewallClient) SetRules(ctx context.Context, firewall *Firewall, opts FirewallSetRulesOpts) ([]*Action, *Response, error) { + reqBody := firewallSetRulesOptsToSchema(opts) + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/firewalls/%d/actions/set_rules", firewall.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.FirewallActionSetRulesResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionsFromSchema(respBody.Actions), resp, nil +} + +func (c *FirewallClient) ApplyResources(ctx context.Context, firewall *Firewall, resources []FirewallResource) ([]*Action, *Response, error) { + applyTo := make([]schema.FirewallResource, len(resources)) + for i, r := range resources { + applyTo[i] = firewallResourceToSchema(r) + } + + reqBody := schema.FirewallActionApplyToResourcesRequest{ApplyTo: applyTo} + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/firewalls/%d/actions/apply_to_resources", firewall.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.FirewallActionApplyToResourcesResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionsFromSchema(respBody.Actions), resp, nil +} + +func (c *FirewallClient) RemoveResources(ctx context.Context, firewall *Firewall, resources []FirewallResource) ([]*Action, *Response, error) { + removeFrom := make([]schema.FirewallResource, len(resources)) + for i, r := range resources { + removeFrom[i] = firewallResourceToSchema(r) + } + + reqBody := schema.FirewallActionRemoveFromResourcesRequest{RemoveFrom: removeFrom} + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/firewalls/%d/actions/remove_from_resources", firewall.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.FirewallActionRemoveFromResourcesResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionsFromSchema(respBody.Actions), resp, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/floating_ip.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/floating_ip.go new file mode 100644 index 000000000..0e6962ab9 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/floating_ip.go @@ -0,0 +1,405 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// FloatingIP represents a Floating IP in the Hetzner Cloud. +type FloatingIP struct { + ID int64 + Description string + Created time.Time + IP net.IP + Network *net.IPNet + Type FloatingIPType + Server *Server + DNSPtr map[string]string + HomeLocation *Location + Blocked bool + Protection FloatingIPProtection + Labels map[string]string + Name string +} + +// DNSPtrForIP returns the reverse DNS pointer of the IP address. +// Deprecated: Use GetDNSPtrForIP instead. +func (f *FloatingIP) DNSPtrForIP(ip net.IP) string { + return f.DNSPtr[ip.String()] +} + +// FloatingIPProtection represents the protection level of a Floating IP. +type FloatingIPProtection struct { + Delete bool +} + +// FloatingIPType represents the type of Floating IP. +type FloatingIPType string + +// Floating IP types. +const ( + FloatingIPTypeIPv4 FloatingIPType = "ipv4" + FloatingIPTypeIPv6 FloatingIPType = "ipv6" +) + +// changeDNSPtr changes or resets the reverse DNS pointer for an IP address. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (f *FloatingIP) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { + reqBody := schema.FloatingIPActionChangeDNSPtrRequest{ + IP: ip.String(), + DNSPtr: ptr, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/floating_ips/%d/actions/change_dns_ptr", f.ID) + req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.FloatingIPActionChangeDNSPtrResponse{} + resp, err := client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// GetDNSPtrForIP searches for the dns assigned to the given IP address. +// It returns an error if there is no dns set for the given IP address. +func (f *FloatingIP) GetDNSPtrForIP(ip net.IP) (string, error) { + dns, ok := f.DNSPtr[ip.String()] + if !ok { + return "", DNSNotFoundError{ip} + } + + return dns, nil +} + +// FloatingIPClient is a client for the Floating IP API. +type FloatingIPClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves a Floating IP by its ID. If the Floating IP does not exist, +// nil is returned. +func (c *FloatingIPClient) GetByID(ctx context.Context, id int64) (*FloatingIP, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/floating_ips/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.FloatingIPGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, resp, err + } + return FloatingIPFromSchema(body.FloatingIP), resp, nil +} + +// GetByName retrieves a Floating IP by its name. If the Floating IP does not exist, nil is returned. +func (c *FloatingIPClient) GetByName(ctx context.Context, name string) (*FloatingIP, *Response, error) { + if name == "" { + return nil, nil, nil + } + floatingIPs, response, err := c.List(ctx, FloatingIPListOpts{Name: name}) + if len(floatingIPs) == 0 { + return nil, response, err + } + return floatingIPs[0], response, err +} + +// Get retrieves a Floating IP by its ID if the input can be parsed as an integer, otherwise it +// retrieves a Floating IP by its name. If the Floating IP does not exist, nil is returned. +func (c *FloatingIPClient) Get(ctx context.Context, idOrName string) (*FloatingIP, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// FloatingIPListOpts specifies options for listing Floating IPs. +type FloatingIPListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l FloatingIPListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of Floating IPs for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *FloatingIPClient) List(ctx context.Context, opts FloatingIPListOpts) ([]*FloatingIP, *Response, error) { + path := "/floating_ips?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.FloatingIPListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + floatingIPs := make([]*FloatingIP, 0, len(body.FloatingIPs)) + for _, s := range body.FloatingIPs { + floatingIPs = append(floatingIPs, FloatingIPFromSchema(s)) + } + return floatingIPs, resp, nil +} + +// All returns all Floating IPs. +func (c *FloatingIPClient) All(ctx context.Context) ([]*FloatingIP, error) { + return c.AllWithOpts(ctx, FloatingIPListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all Floating IPs for the given options. +func (c *FloatingIPClient) AllWithOpts(ctx context.Context, opts FloatingIPListOpts) ([]*FloatingIP, error) { + allFloatingIPs := []*FloatingIP{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + floatingIPs, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allFloatingIPs = append(allFloatingIPs, floatingIPs...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allFloatingIPs, nil +} + +// FloatingIPCreateOpts specifies options for creating a Floating IP. +type FloatingIPCreateOpts struct { + Type FloatingIPType + HomeLocation *Location + Server *Server + Description *string + Name *string + Labels map[string]string +} + +// Validate checks if options are valid. +func (o FloatingIPCreateOpts) Validate() error { + switch o.Type { + case FloatingIPTypeIPv4, FloatingIPTypeIPv6: + break + default: + return errors.New("missing or invalid type") + } + if o.HomeLocation == nil && o.Server == nil { + return errors.New("one of home location or server is required") + } + return nil +} + +// FloatingIPCreateResult is the result of creating a Floating IP. +type FloatingIPCreateResult struct { + FloatingIP *FloatingIP + Action *Action +} + +// Create creates a Floating IP. +func (c *FloatingIPClient) Create(ctx context.Context, opts FloatingIPCreateOpts) (FloatingIPCreateResult, *Response, error) { + if err := opts.Validate(); err != nil { + return FloatingIPCreateResult{}, nil, err + } + + reqBody := schema.FloatingIPCreateRequest{ + Type: string(opts.Type), + Description: opts.Description, + Name: opts.Name, + } + if opts.HomeLocation != nil { + reqBody.HomeLocation = Ptr(opts.HomeLocation.Name) + } + if opts.Server != nil { + reqBody.Server = Ptr(opts.Server.ID) + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return FloatingIPCreateResult{}, nil, err + } + + req, err := c.client.NewRequest(ctx, "POST", "/floating_ips", bytes.NewReader(reqBodyData)) + if err != nil { + return FloatingIPCreateResult{}, nil, err + } + + var respBody schema.FloatingIPCreateResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return FloatingIPCreateResult{}, resp, err + } + var action *Action + if respBody.Action != nil { + action = ActionFromSchema(*respBody.Action) + } + return FloatingIPCreateResult{ + FloatingIP: FloatingIPFromSchema(respBody.FloatingIP), + Action: action, + }, resp, nil +} + +// Delete deletes a Floating IP. +func (c *FloatingIPClient) Delete(ctx context.Context, floatingIP *FloatingIP) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/floating_ips/%d", floatingIP.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// FloatingIPUpdateOpts specifies options for updating a Floating IP. +type FloatingIPUpdateOpts struct { + Description string + Labels map[string]string + Name string +} + +// Update updates a Floating IP. +func (c *FloatingIPClient) Update(ctx context.Context, floatingIP *FloatingIP, opts FloatingIPUpdateOpts) (*FloatingIP, *Response, error) { + reqBody := schema.FloatingIPUpdateRequest{ + Description: opts.Description, + Name: opts.Name, + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/floating_ips/%d", floatingIP.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.FloatingIPUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return FloatingIPFromSchema(respBody.FloatingIP), resp, nil +} + +// Assign assigns a Floating IP to a server. +func (c *FloatingIPClient) Assign(ctx context.Context, floatingIP *FloatingIP, server *Server) (*Action, *Response, error) { + reqBody := schema.FloatingIPActionAssignRequest{ + Server: server.ID, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/floating_ips/%d/actions/assign", floatingIP.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.FloatingIPActionAssignResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// Unassign unassigns a Floating IP from the currently assigned server. +func (c *FloatingIPClient) Unassign(ctx context.Context, floatingIP *FloatingIP) (*Action, *Response, error) { + var reqBody schema.FloatingIPActionUnassignRequest + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/floating_ips/%d/actions/unassign", floatingIP.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.FloatingIPActionUnassignResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// ChangeDNSPtr changes or resets the reverse DNS pointer for a Floating IP address. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (c *FloatingIPClient) ChangeDNSPtr(ctx context.Context, floatingIP *FloatingIP, ip string, ptr *string) (*Action, *Response, error) { + netIP := net.ParseIP(ip) + if netIP == nil { + return nil, nil, InvalidIPError{ip} + } + return floatingIP.changeDNSPtr(ctx, c.client, net.ParseIP(ip), ptr) +} + +// FloatingIPChangeProtectionOpts specifies options for changing the resource protection level of a Floating IP. +type FloatingIPChangeProtectionOpts struct { + Delete *bool +} + +// ChangeProtection changes the resource protection level of a Floating IP. +func (c *FloatingIPClient) ChangeProtection(ctx context.Context, floatingIP *FloatingIP, opts FloatingIPChangeProtectionOpts) (*Action, *Response, error) { + reqBody := schema.FloatingIPActionChangeProtectionRequest{ + Delete: opts.Delete, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/floating_ips/%d/actions/change_protection", floatingIP.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.FloatingIPActionChangeProtectionResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/hcloud.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/hcloud.go new file mode 100644 index 000000000..fe8550bf7 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/hcloud.go @@ -0,0 +1,5 @@ +// Package hcloud is a library for the Hetzner Cloud API. +package hcloud + +// Version is the library's version following Semantic Versioning. +const Version = "2.6.0" // x-release-please-version diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/helper.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/helper.go similarity index 100% rename from vendor/github.com/hetznercloud/hcloud-go/hcloud/helper.go rename to vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/helper.go diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/image.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/image.go new file mode 100644 index 000000000..185c38d4d --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/image.go @@ -0,0 +1,313 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Image represents an Image in the Hetzner Cloud. +type Image struct { + ID int64 + Name string + Type ImageType + Status ImageStatus + Description string + ImageSize float32 + DiskSize float32 + Created time.Time + CreatedFrom *Server + BoundTo *Server + RapidDeploy bool + + OSFlavor string + OSVersion string + Architecture Architecture + + Protection ImageProtection + Deprecated time.Time // The zero value denotes the image is not deprecated. + Labels map[string]string + Deleted time.Time +} + +// IsDeprecated returns whether the image is deprecated. +func (image *Image) IsDeprecated() bool { + return !image.Deprecated.IsZero() +} + +// IsDeleted returns whether the image is deleted. +func (image *Image) IsDeleted() bool { + return !image.Deleted.IsZero() +} + +// ImageProtection represents the protection level of an image. +type ImageProtection struct { + Delete bool +} + +// ImageType specifies the type of an image. +type ImageType string + +const ( + // ImageTypeSnapshot represents a snapshot image. + ImageTypeSnapshot ImageType = "snapshot" + // ImageTypeBackup represents a backup image. + ImageTypeBackup ImageType = "backup" + // ImageTypeSystem represents a system image. + ImageTypeSystem ImageType = "system" + // ImageTypeApp represents a one click app image. + ImageTypeApp ImageType = "app" +) + +// ImageStatus specifies the status of an image. +type ImageStatus string + +const ( + // ImageStatusCreating is the status when an image is being created. + ImageStatusCreating ImageStatus = "creating" + // ImageStatusAvailable is the status when an image is available. + ImageStatusAvailable ImageStatus = "available" +) + +// ImageClient is a client for the image API. +type ImageClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves an image by its ID. If the image does not exist, nil is returned. +func (c *ImageClient) GetByID(ctx context.Context, id int64) (*Image, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/images/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.ImageGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return ImageFromSchema(body.Image), resp, nil +} + +// GetByName retrieves an image by its name. If the image does not exist, nil is returned. +// +// Deprecated: Use [ImageClient.GetByNameAndArchitecture] instead. +func (c *ImageClient) GetByName(ctx context.Context, name string) (*Image, *Response, error) { + if name == "" { + return nil, nil, nil + } + images, response, err := c.List(ctx, ImageListOpts{Name: name}) + if len(images) == 0 { + return nil, response, err + } + return images[0], response, err +} + +// GetByNameAndArchitecture retrieves an image by its name and architecture. If the image does not exist, +// nil is returned. +// In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should +// check for this in your calling method. +func (c *ImageClient) GetByNameAndArchitecture(ctx context.Context, name string, architecture Architecture) (*Image, *Response, error) { + if name == "" { + return nil, nil, nil + } + images, response, err := c.List(ctx, ImageListOpts{Name: name, Architecture: []Architecture{architecture}, IncludeDeprecated: true}) + if len(images) == 0 { + return nil, response, err + } + return images[0], response, err +} + +// Get retrieves an image by its ID if the input can be parsed as an integer, otherwise it +// retrieves an image by its name. If the image does not exist, nil is returned. +// +// Deprecated: Use [ImageClient.GetForArchitecture] instead. +func (c *ImageClient) Get(ctx context.Context, idOrName string) (*Image, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// GetForArchitecture retrieves an image by its ID if the input can be parsed as an integer, otherwise it +// retrieves an image by its name and architecture. If the image does not exist, nil is returned. +// +// In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should +// check for this in your calling method. +func (c *ImageClient) GetForArchitecture(ctx context.Context, idOrName string, architecture Architecture) (*Image, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByNameAndArchitecture(ctx, idOrName, architecture) +} + +// ImageListOpts specifies options for listing images. +type ImageListOpts struct { + ListOpts + Type []ImageType + BoundTo *Server + Name string + Sort []string + Status []ImageStatus + IncludeDeprecated bool + Architecture []Architecture +} + +func (l ImageListOpts) values() url.Values { + vals := l.ListOpts.Values() + for _, typ := range l.Type { + vals.Add("type", string(typ)) + } + if l.BoundTo != nil { + vals.Add("bound_to", strconv.FormatInt(l.BoundTo.ID, 10)) + } + if l.Name != "" { + vals.Add("name", l.Name) + } + if l.IncludeDeprecated { + vals.Add("include_deprecated", strconv.FormatBool(l.IncludeDeprecated)) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + for _, status := range l.Status { + vals.Add("status", string(status)) + } + for _, arch := range l.Architecture { + vals.Add("architecture", string(arch)) + } + return vals +} + +// List returns a list of images for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *ImageClient) List(ctx context.Context, opts ImageListOpts) ([]*Image, *Response, error) { + path := "/images?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.ImageListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + images := make([]*Image, 0, len(body.Images)) + for _, i := range body.Images { + images = append(images, ImageFromSchema(i)) + } + return images, resp, nil +} + +// All returns all images. +func (c *ImageClient) All(ctx context.Context) ([]*Image, error) { + return c.AllWithOpts(ctx, ImageListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all images for the given options. +func (c *ImageClient) AllWithOpts(ctx context.Context, opts ImageListOpts) ([]*Image, error) { + allImages := []*Image{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + images, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allImages = append(allImages, images...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allImages, nil +} + +// Delete deletes an image. +func (c *ImageClient) Delete(ctx context.Context, image *Image) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/images/%d", image.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// ImageUpdateOpts specifies options for updating an image. +type ImageUpdateOpts struct { + Description *string + Type ImageType + Labels map[string]string +} + +// Update updates an image. +func (c *ImageClient) Update(ctx context.Context, image *Image, opts ImageUpdateOpts) (*Image, *Response, error) { + reqBody := schema.ImageUpdateRequest{ + Description: opts.Description, + } + if opts.Type != "" { + reqBody.Type = Ptr(string(opts.Type)) + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/images/%d", image.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ImageUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ImageFromSchema(respBody.Image), resp, nil +} + +// ImageChangeProtectionOpts specifies options for changing the resource protection level of an image. +type ImageChangeProtectionOpts struct { + Delete *bool +} + +// ChangeProtection changes the resource protection level of an image. +func (c *ImageClient) ChangeProtection(ctx context.Context, image *Image, opts ImageChangeProtectionOpts) (*Action, *Response, error) { + reqBody := schema.ImageActionChangeProtectionRequest{ + Delete: opts.Delete, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/images/%d/actions/change_protection", image.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ImageActionChangeProtectionResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/interface_gen.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/interface_gen.go new file mode 100644 index 000000000..d367899dd --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/interface_gen.go @@ -0,0 +1,22 @@ +package hcloud + +//go:generate go run github.com/vburenin/ifacemaker -f action.go -s ActionClient -i IActionClient -p hcloud -o zz_action_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f action.go -s ResourceActionClient -i IResourceActionClient -p hcloud -o zz_resource_action_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f datacenter.go -s DatacenterClient -i IDatacenterClient -p hcloud -o zz_datacenter_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f floating_ip.go -s FloatingIPClient -i IFloatingIPClient -p hcloud -o zz_floating_ip_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f image.go -s ImageClient -i IImageClient -p hcloud -o zz_image_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f iso.go -s ISOClient -i IISOClient -p hcloud -o zz_iso_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f location.go -s LocationClient -i ILocationClient -p hcloud -o zz_location_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f network.go -s NetworkClient -i INetworkClient -p hcloud -o zz_network_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f pricing.go -s PricingClient -i IPricingClient -p hcloud -o zz_pricing_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f server.go -s ServerClient -i IServerClient -p hcloud -o zz_server_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f server_type.go -s ServerTypeClient -i IServerTypeClient -p hcloud -o zz_server_type_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f ssh_key.go -s SSHKeyClient -i ISSHKeyClient -p hcloud -o zz_ssh_key_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f volume.go -s VolumeClient -i IVolumeClient -p hcloud -o zz_volume_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f load_balancer.go -s LoadBalancerClient -i ILoadBalancerClient -p hcloud -o zz_load_balancer_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f load_balancer_type.go -s LoadBalancerTypeClient -i ILoadBalancerTypeClient -p hcloud -o zz_load_balancer_type_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f certificate.go -s CertificateClient -i ICertificateClient -p hcloud -o zz_certificate_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f firewall.go -s FirewallClient -i IFirewallClient -p hcloud -o zz_firewall_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f placement_group.go -s PlacementGroupClient -i IPlacementGroupClient -p hcloud -o zz_placement_group_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f rdns.go -s RDNSClient -i IRDNSClient -p hcloud -o zz_rdns_client_iface.go +//go:generate go run github.com/vburenin/ifacemaker -f primary_ip.go -s PrimaryIPClient -i IPrimaryIPClient -p hcloud -o zz_primary_ip_client_iface.go diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/internal/instrumentation/metrics.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/internal/instrumentation/metrics.go new file mode 100644 index 000000000..e52bd606a --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/internal/instrumentation/metrics.go @@ -0,0 +1,117 @@ +package instrumentation + +import ( + "fmt" + "net/http" + "regexp" + "strconv" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +type Instrumenter struct { + subsystemIdentifier string // will be used as part of the metric name (hcloud__requests_total) + instrumentationRegistry prometheus.Registerer +} + +// New creates a new Instrumenter. The subsystemIdentifier will be used as part of the metric names (e.g. hcloud__requests_total). +func New(subsystemIdentifier string, instrumentationRegistry prometheus.Registerer) *Instrumenter { + return &Instrumenter{subsystemIdentifier: subsystemIdentifier, instrumentationRegistry: instrumentationRegistry} +} + +// InstrumentedRoundTripper returns an instrumented round tripper. +func (i *Instrumenter) InstrumentedRoundTripper() http.RoundTripper { + inFlightRequestsGauge := registerOrReuse( + i.instrumentationRegistry, + prometheus.NewGauge(prometheus.GaugeOpts{ + Name: fmt.Sprintf("hcloud_%s_in_flight_requests", i.subsystemIdentifier), + Help: fmt.Sprintf("A gauge of in-flight requests to the hcloud %s.", i.subsystemIdentifier), + }), + ) + + requestsPerEndpointCounter := registerOrReuse( + i.instrumentationRegistry, + prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: fmt.Sprintf("hcloud_%s_requests_total", i.subsystemIdentifier), + Help: fmt.Sprintf("A counter for requests to the hcloud %s per endpoint.", i.subsystemIdentifier), + }, + []string{"code", "method", "api_endpoint"}, + ), + ) + + requestLatencyHistogram := registerOrReuse( + i.instrumentationRegistry, + prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: fmt.Sprintf("hcloud_%s_request_duration_seconds", i.subsystemIdentifier), + Help: fmt.Sprintf("A histogram of request latencies to the hcloud %s .", i.subsystemIdentifier), + Buckets: prometheus.DefBuckets, + }, + []string{"method"}, + ), + ) + + return promhttp.InstrumentRoundTripperInFlight(inFlightRequestsGauge, + promhttp.InstrumentRoundTripperDuration(requestLatencyHistogram, + i.instrumentRoundTripperEndpoint(requestsPerEndpointCounter, + http.DefaultTransport, + ), + ), + ) +} + +// instrumentRoundTripperEndpoint implements a hcloud specific round tripper to count requests per API endpoint +// numeric IDs are removed from the URI Path. +// +// Sample: +// +// /volumes/1234/actions/attach --> /volumes/actions/attach +func (i *Instrumenter) instrumentRoundTripperEndpoint(counter *prometheus.CounterVec, next http.RoundTripper) promhttp.RoundTripperFunc { + return func(r *http.Request) (*http.Response, error) { + resp, err := next.RoundTrip(r) + if err == nil { + statusCode := strconv.Itoa(resp.StatusCode) + counter.WithLabelValues(statusCode, strings.ToLower(resp.Request.Method), preparePathForLabel(resp.Request.URL.Path)).Inc() + } + + return resp, err + } +} + +// registerOrReuse will try to register the passed Collector, but in case a conflicting collector was already registered, +// it will instead return that collector. Make sure to always use the collector return by this method. +// Similar to [Registry.MustRegister] it will panic if any other error occurs. +func registerOrReuse[C prometheus.Collector](registry prometheus.Registerer, collector C) C { + err := registry.Register(collector) + if err != nil { + // If we get a AlreadyRegisteredError we can return the existing collector + if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + if existingCollector, ok := are.ExistingCollector.(C); ok { + collector = existingCollector + } else { + panic("received incompatible existing collector") + } + } else { + panic(err) + } + } + + return collector +} + +func preparePathForLabel(path string) string { + path = strings.ToLower(path) + + // replace all numbers and chars that are not a-z, / or _ + reg := regexp.MustCompile("[^a-z/_]+") + path = reg.ReplaceAllString(path, "") + + // replace all artifacts of number replacement (//) + path = strings.ReplaceAll(path, "//", "/") + + // replace the /v/ that indicated the API version + return strings.Replace(path, "/v/", "/", 1) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/iso.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/iso.go new file mode 100644 index 000000000..08f7072ce --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/iso.go @@ -0,0 +1,159 @@ +package hcloud + +import ( + "context" + "fmt" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// ISO represents an ISO image in the Hetzner Cloud. +type ISO struct { + ID int64 + Name string + Description string + Type ISOType + Architecture *Architecture + // Deprecated: Use [ISO.Deprecation] instead. + Deprecated time.Time + DeprecatableResource +} + +// ISOType specifies the type of an ISO image. +type ISOType string + +const ( + // ISOTypePublic is the type of a public ISO image. + ISOTypePublic ISOType = "public" + + // ISOTypePrivate is the type of a private ISO image. + ISOTypePrivate ISOType = "private" +) + +// ISOClient is a client for the ISO API. +type ISOClient struct { + client *Client +} + +// GetByID retrieves an ISO by its ID. +func (c *ISOClient) GetByID(ctx context.Context, id int64) (*ISO, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/isos/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.ISOGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, resp, err + } + return ISOFromSchema(body.ISO), resp, nil +} + +// GetByName retrieves an ISO by its name. +func (c *ISOClient) GetByName(ctx context.Context, name string) (*ISO, *Response, error) { + if name == "" { + return nil, nil, nil + } + isos, response, err := c.List(ctx, ISOListOpts{Name: name}) + if len(isos) == 0 { + return nil, response, err + } + return isos[0], response, err +} + +// Get retrieves an ISO by its ID if the input can be parsed as an integer, otherwise it retrieves an ISO by its name. +func (c *ISOClient) Get(ctx context.Context, idOrName string) (*ISO, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// ISOListOpts specifies options for listing isos. +type ISOListOpts struct { + ListOpts + Name string + Sort []string + // Architecture filters the ISOs by Architecture. Note that custom ISOs do not have any architecture set, and you + // must use IncludeWildcardArchitecture to include them. + Architecture []Architecture + // IncludeWildcardArchitecture must be set to also return custom ISOs that have no architecture set, if you are + // also setting the Architecture field. + // Deprecated: Use [ISOListOpts.IncludeArchitectureWildcard] instead. + IncludeWildcardArchitecture bool + // IncludeWildcardArchitecture must be set to also return custom ISOs that have no architecture set, if you are + // also setting the Architecture field. + IncludeArchitectureWildcard bool +} + +func (l ISOListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + for _, arch := range l.Architecture { + vals.Add("architecture", string(arch)) + } + if l.IncludeArchitectureWildcard || l.IncludeWildcardArchitecture { + vals.Add("include_architecture_wildcard", "true") + } + return vals +} + +// List returns a list of ISOs for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *ISOClient) List(ctx context.Context, opts ISOListOpts) ([]*ISO, *Response, error) { + path := "/isos?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.ISOListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + isos := make([]*ISO, 0, len(body.ISOs)) + for _, i := range body.ISOs { + isos = append(isos, ISOFromSchema(i)) + } + return isos, resp, nil +} + +// All returns all ISOs. +func (c *ISOClient) All(ctx context.Context) ([]*ISO, error) { + return c.AllWithOpts(ctx, ISOListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all ISOs for the given options. +func (c *ISOClient) AllWithOpts(ctx context.Context, opts ISOListOpts) ([]*ISO, error) { + allISOs := []*ISO{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + isos, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allISOs = append(allISOs, isos...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allISOs, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/labels.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/labels.go similarity index 87% rename from vendor/github.com/hetznercloud/hcloud-go/hcloud/labels.go rename to vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/labels.go index e22000a8f..3dc7d781f 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/labels.go +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/labels.go @@ -6,8 +6,8 @@ import ( ) var keyRegexp = regexp.MustCompile( - `^([a-z0-9A-Z]((?:[\-_.]|[a-z0-9A-Z]){0,253}[a-z0-9A-Z])?/)?[a-z0-9A-Z]((?:[\-_.]|[a-z0-9A-Z]|){0,62}[a-z0-9A-Z])?$`) -var valueRegexp = regexp.MustCompile(`^(([a-z0-9A-Z](?:[\-_.]|[a-z0-9A-Z]){0,62})?[a-z0-9A-Z]$|$)`) + `^([a-z0-9A-Z]((?:[\-_.]|[a-z0-9A-Z]){0,253}[a-z0-9A-Z])?/)?[a-z0-9A-Z]((?:[\-_.]|[a-z0-9A-Z]|){0,61}[a-z0-9A-Z])?$`) +var valueRegexp = regexp.MustCompile(`^(([a-z0-9A-Z](?:[\-_.]|[a-z0-9A-Z]){0,61})?[a-z0-9A-Z]$|$)`) func ValidateResourceLabels(labels map[string]interface{}) (bool, error) { for k, v := range labels { diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/load_balancer.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/load_balancer.go new file mode 100644 index 000000000..fb40057b7 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/load_balancer.go @@ -0,0 +1,1062 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// LoadBalancer represents a Load Balancer in the Hetzner Cloud. +type LoadBalancer struct { + ID int64 + Name string + PublicNet LoadBalancerPublicNet + PrivateNet []LoadBalancerPrivateNet + Location *Location + LoadBalancerType *LoadBalancerType + Algorithm LoadBalancerAlgorithm + Services []LoadBalancerService + Targets []LoadBalancerTarget + Protection LoadBalancerProtection + Labels map[string]string + Created time.Time + IncludedTraffic uint64 + OutgoingTraffic uint64 + IngoingTraffic uint64 +} + +// LoadBalancerPublicNet represents a Load Balancer's public network. +type LoadBalancerPublicNet struct { + Enabled bool + IPv4 LoadBalancerPublicNetIPv4 + IPv6 LoadBalancerPublicNetIPv6 +} + +// LoadBalancerPublicNetIPv4 represents a Load Balancer's public IPv4 address. +type LoadBalancerPublicNetIPv4 struct { + IP net.IP + DNSPtr string +} + +// LoadBalancerPublicNetIPv6 represents a Load Balancer's public IPv6 address. +type LoadBalancerPublicNetIPv6 struct { + IP net.IP + DNSPtr string +} + +// LoadBalancerPrivateNet represents a Load Balancer's private network. +type LoadBalancerPrivateNet struct { + Network *Network + IP net.IP +} + +// LoadBalancerService represents a Load Balancer service. +type LoadBalancerService struct { + Protocol LoadBalancerServiceProtocol + ListenPort int + DestinationPort int + Proxyprotocol bool + HTTP LoadBalancerServiceHTTP + HealthCheck LoadBalancerServiceHealthCheck +} + +// LoadBalancerServiceHTTP stores configuration for a service using the HTTP protocol. +type LoadBalancerServiceHTTP struct { + CookieName string + CookieLifetime time.Duration + Certificates []*Certificate + RedirectHTTP bool + StickySessions bool +} + +// LoadBalancerServiceHealthCheck stores configuration for a service health check. +type LoadBalancerServiceHealthCheck struct { + Protocol LoadBalancerServiceProtocol + Port int + Interval time.Duration + Timeout time.Duration + Retries int + HTTP *LoadBalancerServiceHealthCheckHTTP +} + +// LoadBalancerServiceHealthCheckHTTP stores configuration for a service health check +// using the HTTP protocol. +type LoadBalancerServiceHealthCheckHTTP struct { + Domain string + Path string + Response string + StatusCodes []string + TLS bool +} + +// LoadBalancerAlgorithmType specifies the algorithm type a Load Balancer +// uses for distributing requests. +type LoadBalancerAlgorithmType string + +const ( + // LoadBalancerAlgorithmTypeRoundRobin is an algorithm which distributes + // requests to targets in a round-robin fashion. + LoadBalancerAlgorithmTypeRoundRobin LoadBalancerAlgorithmType = "round_robin" + // LoadBalancerAlgorithmTypeLeastConnections is an algorithm which distributes + // requests to targets with the least number of connections. + LoadBalancerAlgorithmTypeLeastConnections LoadBalancerAlgorithmType = "least_connections" +) + +// LoadBalancerAlgorithm configures the algorithm a Load Balancer uses +// for distributing requests. +type LoadBalancerAlgorithm struct { + Type LoadBalancerAlgorithmType +} + +// LoadBalancerTargetType specifies the type of Load Balancer target. +type LoadBalancerTargetType string + +const ( + // LoadBalancerTargetTypeServer is a target type which points to a specific + // server. + LoadBalancerTargetTypeServer LoadBalancerTargetType = "server" + + // LoadBalancerTargetTypeLabelSelector is a target type which selects the + // servers a Load Balancer points to using labels assigned to the servers. + LoadBalancerTargetTypeLabelSelector LoadBalancerTargetType = "label_selector" + + // LoadBalancerTargetTypeIP is a target type which points to an IP. + LoadBalancerTargetTypeIP LoadBalancerTargetType = "ip" +) + +// LoadBalancerServiceProtocol specifies the protocol of a Load Balancer service. +type LoadBalancerServiceProtocol string + +const ( + // LoadBalancerServiceProtocolTCP specifies a TCP service. + LoadBalancerServiceProtocolTCP LoadBalancerServiceProtocol = "tcp" + // LoadBalancerServiceProtocolHTTP specifies an HTTP service. + LoadBalancerServiceProtocolHTTP LoadBalancerServiceProtocol = "http" + // LoadBalancerServiceProtocolHTTPS specifies an HTTPS service. + LoadBalancerServiceProtocolHTTPS LoadBalancerServiceProtocol = "https" +) + +// LoadBalancerTarget represents a Load Balancer target. +type LoadBalancerTarget struct { + Type LoadBalancerTargetType + Server *LoadBalancerTargetServer + LabelSelector *LoadBalancerTargetLabelSelector + IP *LoadBalancerTargetIP + HealthStatus []LoadBalancerTargetHealthStatus + Targets []LoadBalancerTarget + UsePrivateIP bool +} + +// LoadBalancerTargetServer configures a Load Balancer target +// pointing at a specific server. +type LoadBalancerTargetServer struct { + Server *Server +} + +// LoadBalancerTargetLabelSelector configures a Load Balancer target pointing +// at the servers matching the selector. This includes the target pointing at +// nothing, if no servers match the Selector. +type LoadBalancerTargetLabelSelector struct { + Selector string +} + +// LoadBalancerTargetIP configures a Load Balancer target pointing to a Hetzner +// Online IP address. +type LoadBalancerTargetIP struct { + IP string +} + +// LoadBalancerTargetHealthStatusStatus describes a target's health status. +type LoadBalancerTargetHealthStatusStatus string + +const ( + // LoadBalancerTargetHealthStatusStatusUnknown denotes that the health status is unknown. + LoadBalancerTargetHealthStatusStatusUnknown LoadBalancerTargetHealthStatusStatus = "unknown" + // LoadBalancerTargetHealthStatusStatusHealthy denotes a healthy target. + LoadBalancerTargetHealthStatusStatusHealthy LoadBalancerTargetHealthStatusStatus = "healthy" + // LoadBalancerTargetHealthStatusStatusUnhealthy denotes an unhealthy target. + LoadBalancerTargetHealthStatusStatusUnhealthy LoadBalancerTargetHealthStatusStatus = "unhealthy" +) + +// LoadBalancerTargetHealthStatus describes a target's health for a specific service. +type LoadBalancerTargetHealthStatus struct { + ListenPort int + Status LoadBalancerTargetHealthStatusStatus +} + +// LoadBalancerProtection represents the protection level of a Load Balancer. +type LoadBalancerProtection struct { + Delete bool +} + +// changeDNSPtr changes or resets the reverse DNS pointer for an IP address. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (lb *LoadBalancer) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionChangeDNSPtrRequest{ + IP: ip.String(), + DNSPtr: ptr, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/change_dns_ptr", lb.ID) + req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.LoadBalancerActionChangeDNSPtrResponse{} + resp, err := client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// GetDNSPtrForIP searches for the dns assigned to the given IP address. +// It returns an error if there is no dns set for the given IP address. +func (lb *LoadBalancer) GetDNSPtrForIP(ip net.IP) (string, error) { + if net.IP.Equal(lb.PublicNet.IPv4.IP, ip) { + return lb.PublicNet.IPv4.DNSPtr, nil + } else if net.IP.Equal(lb.PublicNet.IPv6.IP, ip) { + return lb.PublicNet.IPv6.DNSPtr, nil + } + + return "", DNSNotFoundError{ip} +} + +// LoadBalancerClient is a client for the Load Balancers API. +type LoadBalancerClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves a Load Balancer by its ID. If the Load Balancer does not exist, nil is returned. +func (c *LoadBalancerClient) GetByID(ctx context.Context, id int64) (*LoadBalancer, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/load_balancers/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.LoadBalancerGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return LoadBalancerFromSchema(body.LoadBalancer), resp, nil +} + +// GetByName retrieves a Load Balancer by its name. If the Load Balancer does not exist, nil is returned. +func (c *LoadBalancerClient) GetByName(ctx context.Context, name string) (*LoadBalancer, *Response, error) { + if name == "" { + return nil, nil, nil + } + LoadBalancer, response, err := c.List(ctx, LoadBalancerListOpts{Name: name}) + if len(LoadBalancer) == 0 { + return nil, response, err + } + return LoadBalancer[0], response, err +} + +// Get retrieves a Load Balancer by its ID if the input can be parsed as an integer, otherwise it +// retrieves a Load Balancer by its name. If the Load Balancer does not exist, nil is returned. +func (c *LoadBalancerClient) Get(ctx context.Context, idOrName string) (*LoadBalancer, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// LoadBalancerListOpts specifies options for listing Load Balancers. +type LoadBalancerListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l LoadBalancerListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of Load Balancers for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *LoadBalancerClient) List(ctx context.Context, opts LoadBalancerListOpts) ([]*LoadBalancer, *Response, error) { + path := "/load_balancers?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.LoadBalancerListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + LoadBalancers := make([]*LoadBalancer, 0, len(body.LoadBalancers)) + for _, s := range body.LoadBalancers { + LoadBalancers = append(LoadBalancers, LoadBalancerFromSchema(s)) + } + return LoadBalancers, resp, nil +} + +// All returns all Load Balancers. +func (c *LoadBalancerClient) All(ctx context.Context) ([]*LoadBalancer, error) { + return c.AllWithOpts(ctx, LoadBalancerListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all Load Balancers for the given options. +func (c *LoadBalancerClient) AllWithOpts(ctx context.Context, opts LoadBalancerListOpts) ([]*LoadBalancer, error) { + allLoadBalancers := []*LoadBalancer{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + LoadBalancers, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allLoadBalancers = append(allLoadBalancers, LoadBalancers...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allLoadBalancers, nil +} + +// LoadBalancerUpdateOpts specifies options for updating a Load Balancer. +type LoadBalancerUpdateOpts struct { + Name string + Labels map[string]string +} + +// Update updates a Load Balancer. +func (c *LoadBalancerClient) Update(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerUpdateOpts) (*LoadBalancer, *Response, error) { + reqBody := schema.LoadBalancerUpdateRequest{} + if opts.Name != "" { + reqBody.Name = &opts.Name + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.LoadBalancerUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return LoadBalancerFromSchema(respBody.LoadBalancer), resp, nil +} + +// LoadBalancerCreateOpts specifies options for creating a new Load Balancer. +type LoadBalancerCreateOpts struct { + Name string + LoadBalancerType *LoadBalancerType + Algorithm *LoadBalancerAlgorithm + Location *Location + NetworkZone NetworkZone + Labels map[string]string + Targets []LoadBalancerCreateOptsTarget + Services []LoadBalancerCreateOptsService + PublicInterface *bool + Network *Network +} + +// LoadBalancerCreateOptsTarget holds options for specifying a target +// when creating a new Load Balancer. +type LoadBalancerCreateOptsTarget struct { + Type LoadBalancerTargetType + Server LoadBalancerCreateOptsTargetServer + LabelSelector LoadBalancerCreateOptsTargetLabelSelector + IP LoadBalancerCreateOptsTargetIP + UsePrivateIP *bool +} + +// LoadBalancerCreateOptsTargetServer holds options for specifying a server target +// when creating a new Load Balancer. +type LoadBalancerCreateOptsTargetServer struct { + Server *Server +} + +// LoadBalancerCreateOptsTargetLabelSelector holds options for specifying a label selector target +// when creating a new Load Balancer. +type LoadBalancerCreateOptsTargetLabelSelector struct { + Selector string +} + +// LoadBalancerCreateOptsTargetIP holds options for specifying an IP target +// when creating a new Load Balancer. +type LoadBalancerCreateOptsTargetIP struct { + IP string +} + +// LoadBalancerCreateOptsService holds options for specifying a service +// when creating a new Load Balancer. +type LoadBalancerCreateOptsService struct { + Protocol LoadBalancerServiceProtocol + ListenPort *int + DestinationPort *int + Proxyprotocol *bool + HTTP *LoadBalancerCreateOptsServiceHTTP + HealthCheck *LoadBalancerCreateOptsServiceHealthCheck +} + +// LoadBalancerCreateOptsServiceHTTP holds options for specifying an HTTP service +// when creating a new Load Balancer. +type LoadBalancerCreateOptsServiceHTTP struct { + CookieName *string + CookieLifetime *time.Duration + Certificates []*Certificate + RedirectHTTP *bool + StickySessions *bool +} + +// LoadBalancerCreateOptsServiceHealthCheck holds options for specifying a service +// health check when creating a new Load Balancer. +type LoadBalancerCreateOptsServiceHealthCheck struct { + Protocol LoadBalancerServiceProtocol + Port *int + Interval *time.Duration + Timeout *time.Duration + Retries *int + HTTP *LoadBalancerCreateOptsServiceHealthCheckHTTP +} + +// LoadBalancerCreateOptsServiceHealthCheckHTTP holds options for specifying a service +// HTTP health check when creating a new Load Balancer. +type LoadBalancerCreateOptsServiceHealthCheckHTTP struct { + Domain *string + Path *string + Response *string + StatusCodes []string + TLS *bool +} + +// LoadBalancerCreateResult is the result of a create Load Balancer call. +type LoadBalancerCreateResult struct { + LoadBalancer *LoadBalancer + Action *Action +} + +// Create creates a new Load Balancer. +func (c *LoadBalancerClient) Create(ctx context.Context, opts LoadBalancerCreateOpts) (LoadBalancerCreateResult, *Response, error) { + reqBody := loadBalancerCreateOptsToSchema(opts) + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return LoadBalancerCreateResult{}, nil, err + } + req, err := c.client.NewRequest(ctx, "POST", "/load_balancers", bytes.NewReader(reqBodyData)) + if err != nil { + return LoadBalancerCreateResult{}, nil, err + } + + respBody := schema.LoadBalancerCreateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return LoadBalancerCreateResult{}, resp, err + } + return LoadBalancerCreateResult{ + LoadBalancer: LoadBalancerFromSchema(respBody.LoadBalancer), + Action: ActionFromSchema(respBody.Action), + }, resp, nil +} + +// Delete deletes a Load Balancer. +func (c *LoadBalancerClient) Delete(ctx context.Context, loadBalancer *LoadBalancer) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/load_balancers/%d", loadBalancer.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +func (c *LoadBalancerClient) addTarget(ctx context.Context, loadBalancer *LoadBalancer, reqBody schema.LoadBalancerActionAddTargetRequest) (*Action, *Response, error) { + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/add_target", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.LoadBalancerActionAddTargetResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +func (c *LoadBalancerClient) removeTarget(ctx context.Context, loadBalancer *LoadBalancer, reqBody schema.LoadBalancerActionRemoveTargetRequest) (*Action, *Response, error) { + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/remove_target", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.LoadBalancerActionRemoveTargetResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// LoadBalancerAddServerTargetOpts specifies options for adding a server target +// to a Load Balancer. +type LoadBalancerAddServerTargetOpts struct { + Server *Server + UsePrivateIP *bool +} + +// AddServerTarget adds a server target to a Load Balancer. +func (c *LoadBalancerClient) AddServerTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddServerTargetOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionAddTargetRequest{ + Type: string(LoadBalancerTargetTypeServer), + Server: &schema.LoadBalancerActionAddTargetRequestServer{ + ID: opts.Server.ID, + }, + UsePrivateIP: opts.UsePrivateIP, + } + return c.addTarget(ctx, loadBalancer, reqBody) +} + +// RemoveServerTarget removes a server target from a Load Balancer. +func (c *LoadBalancerClient) RemoveServerTarget(ctx context.Context, loadBalancer *LoadBalancer, server *Server) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionRemoveTargetRequest{ + Type: string(LoadBalancerTargetTypeServer), + Server: &schema.LoadBalancerActionRemoveTargetRequestServer{ + ID: server.ID, + }, + } + return c.removeTarget(ctx, loadBalancer, reqBody) +} + +// LoadBalancerAddLabelSelectorTargetOpts specifies options for adding a label selector target +// to a Load Balancer. +type LoadBalancerAddLabelSelectorTargetOpts struct { + Selector string + UsePrivateIP *bool +} + +// AddLabelSelectorTarget adds a label selector target to a Load Balancer. +func (c *LoadBalancerClient) AddLabelSelectorTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddLabelSelectorTargetOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionAddTargetRequest{ + Type: string(LoadBalancerTargetTypeLabelSelector), + LabelSelector: &schema.LoadBalancerActionAddTargetRequestLabelSelector{ + Selector: opts.Selector, + }, + UsePrivateIP: opts.UsePrivateIP, + } + return c.addTarget(ctx, loadBalancer, reqBody) +} + +// RemoveLabelSelectorTarget removes a label selector target from a Load Balancer. +func (c *LoadBalancerClient) RemoveLabelSelectorTarget(ctx context.Context, loadBalancer *LoadBalancer, labelSelector string) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionRemoveTargetRequest{ + Type: string(LoadBalancerTargetTypeLabelSelector), + LabelSelector: &schema.LoadBalancerActionRemoveTargetRequestLabelSelector{ + Selector: labelSelector, + }, + } + return c.removeTarget(ctx, loadBalancer, reqBody) +} + +// LoadBalancerAddIPTargetOpts specifies options for adding an IP target to a +// Load Balancer. +type LoadBalancerAddIPTargetOpts struct { + IP net.IP +} + +// AddIPTarget adds an IP target to a Load Balancer. +func (c *LoadBalancerClient) AddIPTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddIPTargetOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionAddTargetRequest{ + Type: string(LoadBalancerTargetTypeIP), + IP: &schema.LoadBalancerActionAddTargetRequestIP{IP: opts.IP.String()}, + } + return c.addTarget(ctx, loadBalancer, reqBody) +} + +// RemoveIPTarget removes an IP target from a Load Balancer. +func (c *LoadBalancerClient) RemoveIPTarget(ctx context.Context, loadBalancer *LoadBalancer, ip net.IP) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionRemoveTargetRequest{ + Type: string(LoadBalancerTargetTypeIP), + IP: &schema.LoadBalancerActionRemoveTargetRequestIP{ + IP: ip.String(), + }, + } + return c.removeTarget(ctx, loadBalancer, reqBody) +} + +// LoadBalancerAddServiceOpts specifies options for adding a service to a Load Balancer. +type LoadBalancerAddServiceOpts struct { + Protocol LoadBalancerServiceProtocol + ListenPort *int + DestinationPort *int + Proxyprotocol *bool + HTTP *LoadBalancerAddServiceOptsHTTP + HealthCheck *LoadBalancerAddServiceOptsHealthCheck +} + +// LoadBalancerAddServiceOptsHTTP holds options for specifying an HTTP service +// when adding a service to a Load Balancer. +type LoadBalancerAddServiceOptsHTTP struct { + CookieName *string + CookieLifetime *time.Duration + Certificates []*Certificate + RedirectHTTP *bool + StickySessions *bool +} + +// LoadBalancerAddServiceOptsHealthCheck holds options for specifying a health check +// when adding a service to a Load Balancer. +type LoadBalancerAddServiceOptsHealthCheck struct { + Protocol LoadBalancerServiceProtocol + Port *int + Interval *time.Duration + Timeout *time.Duration + Retries *int + HTTP *LoadBalancerAddServiceOptsHealthCheckHTTP +} + +// LoadBalancerAddServiceOptsHealthCheckHTTP holds options for specifying an +// HTTP health check when adding a service to a Load Balancer. +type LoadBalancerAddServiceOptsHealthCheckHTTP struct { + Domain *string + Path *string + Response *string + StatusCodes []string + TLS *bool +} + +// AddService adds a service to a Load Balancer. +func (c *LoadBalancerClient) AddService(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddServiceOpts) (*Action, *Response, error) { + reqBody := loadBalancerAddServiceOptsToSchema(opts) + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/add_service", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.LoadBalancerActionAddServiceResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// LoadBalancerUpdateServiceOpts specifies options for updating a service. +type LoadBalancerUpdateServiceOpts struct { + Protocol LoadBalancerServiceProtocol + DestinationPort *int + Proxyprotocol *bool + HTTP *LoadBalancerUpdateServiceOptsHTTP + HealthCheck *LoadBalancerUpdateServiceOptsHealthCheck +} + +// LoadBalancerUpdateServiceOptsHTTP specifies options for updating an HTTP(S) service. +type LoadBalancerUpdateServiceOptsHTTP struct { + CookieName *string + CookieLifetime *time.Duration + Certificates []*Certificate + RedirectHTTP *bool + StickySessions *bool +} + +// LoadBalancerUpdateServiceOptsHealthCheck specifies options for updating +// a service's health check. +type LoadBalancerUpdateServiceOptsHealthCheck struct { + Protocol LoadBalancerServiceProtocol + Port *int + Interval *time.Duration + Timeout *time.Duration + Retries *int + HTTP *LoadBalancerUpdateServiceOptsHealthCheckHTTP +} + +// LoadBalancerUpdateServiceOptsHealthCheckHTTP specifies options for updating +// the HTTP-specific settings of a service's health check. +type LoadBalancerUpdateServiceOptsHealthCheckHTTP struct { + Domain *string + Path *string + Response *string + StatusCodes []string + TLS *bool +} + +// UpdateService updates a Load Balancer service. +func (c *LoadBalancerClient) UpdateService(ctx context.Context, loadBalancer *LoadBalancer, listenPort int, opts LoadBalancerUpdateServiceOpts) (*Action, *Response, error) { + reqBody := loadBalancerUpdateServiceOptsToSchema(opts) + reqBody.ListenPort = listenPort + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/update_service", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.LoadBalancerActionUpdateServiceResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// DeleteService deletes a Load Balancer service. +func (c *LoadBalancerClient) DeleteService(ctx context.Context, loadBalancer *LoadBalancer, listenPort int) (*Action, *Response, error) { + reqBody := schema.LoadBalancerDeleteServiceRequest{ + ListenPort: listenPort, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/delete_service", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.LoadBalancerDeleteServiceResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// LoadBalancerChangeProtectionOpts specifies options for changing the resource protection level of a Load Balancer. +type LoadBalancerChangeProtectionOpts struct { + Delete *bool +} + +// ChangeProtection changes the resource protection level of a Load Balancer. +func (c *LoadBalancerClient) ChangeProtection(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeProtectionOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionChangeProtectionRequest{ + Delete: opts.Delete, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/change_protection", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.LoadBalancerActionChangeProtectionResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// LoadBalancerChangeAlgorithmOpts specifies options for changing the algorithm of a Load Balancer. +type LoadBalancerChangeAlgorithmOpts struct { + Type LoadBalancerAlgorithmType +} + +// ChangeAlgorithm changes the algorithm of a Load Balancer. +func (c *LoadBalancerClient) ChangeAlgorithm(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeAlgorithmOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionChangeAlgorithmRequest{ + Type: string(opts.Type), + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/change_algorithm", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.LoadBalancerActionChangeAlgorithmResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// LoadBalancerAttachToNetworkOpts specifies options for attaching a Load Balancer to a network. +type LoadBalancerAttachToNetworkOpts struct { + Network *Network + IP net.IP +} + +// AttachToNetwork attaches a Load Balancer to a network. +func (c *LoadBalancerClient) AttachToNetwork(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAttachToNetworkOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionAttachToNetworkRequest{ + Network: opts.Network.ID, + } + if opts.IP != nil { + reqBody.IP = Ptr(opts.IP.String()) + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/attach_to_network", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.LoadBalancerActionAttachToNetworkResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// LoadBalancerDetachFromNetworkOpts specifies options for detaching a Load Balancer from a network. +type LoadBalancerDetachFromNetworkOpts struct { + Network *Network +} + +// DetachFromNetwork detaches a Load Balancer from a network. +func (c *LoadBalancerClient) DetachFromNetwork(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerDetachFromNetworkOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionDetachFromNetworkRequest{ + Network: opts.Network.ID, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/detach_from_network", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.LoadBalancerActionDetachFromNetworkResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// EnablePublicInterface enables the Load Balancer's public network interface. +func (c *LoadBalancerClient) EnablePublicInterface(ctx context.Context, loadBalancer *LoadBalancer) (*Action, *Response, error) { + path := fmt.Sprintf("/load_balancers/%d/actions/enable_public_interface", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + respBody := schema.LoadBalancerActionEnablePublicInterfaceResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// DisablePublicInterface disables the Load Balancer's public network interface. +func (c *LoadBalancerClient) DisablePublicInterface(ctx context.Context, loadBalancer *LoadBalancer) (*Action, *Response, error) { + path := fmt.Sprintf("/load_balancers/%d/actions/disable_public_interface", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + respBody := schema.LoadBalancerActionDisablePublicInterfaceResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// LoadBalancerChangeTypeOpts specifies options for changing a Load Balancer's type. +type LoadBalancerChangeTypeOpts struct { + LoadBalancerType *LoadBalancerType // new Load Balancer type +} + +// ChangeType changes a Load Balancer's type. +func (c *LoadBalancerClient) ChangeType(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeTypeOpts) (*Action, *Response, error) { + reqBody := schema.LoadBalancerActionChangeTypeRequest{} + if opts.LoadBalancerType.ID != 0 { + reqBody.LoadBalancerType = opts.LoadBalancerType.ID + } else { + reqBody.LoadBalancerType = opts.LoadBalancerType.Name + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/load_balancers/%d/actions/change_type", loadBalancer.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.LoadBalancerActionChangeTypeResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// LoadBalancerMetricType is the type of available metrics for Load Balancers. +type LoadBalancerMetricType string + +// Available types of Load Balancer metrics. See Hetzner Cloud API +// documentation for details. +const ( + LoadBalancerMetricOpenConnections LoadBalancerMetricType = "open_connections" + LoadBalancerMetricConnectionsPerSecond LoadBalancerMetricType = "connections_per_second" + LoadBalancerMetricRequestsPerSecond LoadBalancerMetricType = "requests_per_second" + LoadBalancerMetricBandwidth LoadBalancerMetricType = "bandwidth" +) + +// LoadBalancerGetMetricsOpts configures the call to get metrics for a Load +// Balancer. +type LoadBalancerGetMetricsOpts struct { + Types []LoadBalancerMetricType + Start time.Time + End time.Time + Step int +} + +func (o *LoadBalancerGetMetricsOpts) addQueryParams(req *http.Request) error { + query := req.URL.Query() + + if len(o.Types) == 0 { + return fmt.Errorf("no metric types specified") + } + for _, typ := range o.Types { + query.Add("type", string(typ)) + } + + if o.Start.IsZero() { + return fmt.Errorf("no start time specified") + } + query.Add("start", o.Start.Format(time.RFC3339)) + + if o.End.IsZero() { + return fmt.Errorf("no end time specified") + } + query.Add("end", o.End.Format(time.RFC3339)) + + if o.Step > 0 { + query.Add("step", strconv.Itoa(o.Step)) + } + req.URL.RawQuery = query.Encode() + + return nil +} + +// LoadBalancerMetrics contains the metrics requested for a Load Balancer. +type LoadBalancerMetrics struct { + Start time.Time + End time.Time + Step float64 + TimeSeries map[string][]LoadBalancerMetricsValue +} + +// LoadBalancerMetricsValue represents a single value in a time series of metrics. +type LoadBalancerMetricsValue struct { + Timestamp float64 + Value string +} + +// GetMetrics obtains metrics for a Load Balancer. +func (c *LoadBalancerClient) GetMetrics( + ctx context.Context, lb *LoadBalancer, opts LoadBalancerGetMetricsOpts, +) (*LoadBalancerMetrics, *Response, error) { + var respBody schema.LoadBalancerGetMetricsResponse + + if lb == nil { + return nil, nil, fmt.Errorf("illegal argument: load balancer is nil") + } + + path := fmt.Sprintf("/load_balancers/%d/metrics", lb.ID) + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, fmt.Errorf("new request: %v", err) + } + if err := opts.addQueryParams(req); err != nil { + return nil, nil, fmt.Errorf("add query params: %v", err) + } + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, nil, fmt.Errorf("get metrics: %v", err) + } + ms, err := loadBalancerMetricsFromSchema(&respBody) + if err != nil { + return nil, nil, fmt.Errorf("convert response body: %v", err) + } + return ms, resp, nil +} + +// ChangeDNSPtr changes or resets the reverse DNS pointer for a Load Balancer. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (c *LoadBalancerClient) ChangeDNSPtr(ctx context.Context, lb *LoadBalancer, ip string, ptr *string) (*Action, *Response, error) { + netIP := net.ParseIP(ip) + if netIP == nil { + return nil, nil, InvalidIPError{ip} + } + return lb.changeDNSPtr(ctx, c.client, net.ParseIP(ip), ptr) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/load_balancer_type.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/load_balancer_type.go new file mode 100644 index 000000000..605021276 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/load_balancer_type.go @@ -0,0 +1,133 @@ +package hcloud + +import ( + "context" + "fmt" + "net/url" + "strconv" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// LoadBalancerType represents a LoadBalancer type in the Hetzner Cloud. +type LoadBalancerType struct { + ID int64 + Name string + Description string + MaxConnections int + MaxServices int + MaxTargets int + MaxAssignedCertificates int + Pricings []LoadBalancerTypeLocationPricing + Deprecated *string +} + +// LoadBalancerTypeClient is a client for the Load Balancer types API. +type LoadBalancerTypeClient struct { + client *Client +} + +// GetByID retrieves a Load Balancer type by its ID. If the Load Balancer type does not exist, nil is returned. +func (c *LoadBalancerTypeClient) GetByID(ctx context.Context, id int64) (*LoadBalancerType, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/load_balancer_types/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.LoadBalancerTypeGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return LoadBalancerTypeFromSchema(body.LoadBalancerType), resp, nil +} + +// GetByName retrieves a Load Balancer type by its name. If the Load Balancer type does not exist, nil is returned. +func (c *LoadBalancerTypeClient) GetByName(ctx context.Context, name string) (*LoadBalancerType, *Response, error) { + if name == "" { + return nil, nil, nil + } + LoadBalancerTypes, response, err := c.List(ctx, LoadBalancerTypeListOpts{Name: name}) + if len(LoadBalancerTypes) == 0 { + return nil, response, err + } + return LoadBalancerTypes[0], response, err +} + +// Get retrieves a Load Balancer type by its ID if the input can be parsed as an integer, otherwise it +// retrieves a Load Balancer type by its name. If the Load Balancer type does not exist, nil is returned. +func (c *LoadBalancerTypeClient) Get(ctx context.Context, idOrName string) (*LoadBalancerType, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// LoadBalancerTypeListOpts specifies options for listing Load Balancer types. +type LoadBalancerTypeListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l LoadBalancerTypeListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of Load Balancer types for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *LoadBalancerTypeClient) List(ctx context.Context, opts LoadBalancerTypeListOpts) ([]*LoadBalancerType, *Response, error) { + path := "/load_balancer_types?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.LoadBalancerTypeListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + LoadBalancerTypes := make([]*LoadBalancerType, 0, len(body.LoadBalancerTypes)) + for _, s := range body.LoadBalancerTypes { + LoadBalancerTypes = append(LoadBalancerTypes, LoadBalancerTypeFromSchema(s)) + } + return LoadBalancerTypes, resp, nil +} + +// All returns all Load Balancer types. +func (c *LoadBalancerTypeClient) All(ctx context.Context) ([]*LoadBalancerType, error) { + return c.AllWithOpts(ctx, LoadBalancerTypeListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all Load Balancer types for the given options. +func (c *LoadBalancerTypeClient) AllWithOpts(ctx context.Context, opts LoadBalancerTypeListOpts) ([]*LoadBalancerType, error) { + allLoadBalancerTypes := []*LoadBalancerType{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + LoadBalancerTypes, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allLoadBalancerTypes = append(allLoadBalancerTypes, LoadBalancerTypes...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allLoadBalancerTypes, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/location.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/location.go new file mode 100644 index 000000000..bd5eb7981 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/location.go @@ -0,0 +1,132 @@ +package hcloud + +import ( + "context" + "fmt" + "net/url" + "strconv" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Location represents a location in the Hetzner Cloud. +type Location struct { + ID int64 + Name string + Description string + Country string + City string + Latitude float64 + Longitude float64 + NetworkZone NetworkZone +} + +// LocationClient is a client for the location API. +type LocationClient struct { + client *Client +} + +// GetByID retrieves a location by its ID. If the location does not exist, nil is returned. +func (c *LocationClient) GetByID(ctx context.Context, id int64) (*Location, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/locations/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.LocationGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, resp, err + } + return LocationFromSchema(body.Location), resp, nil +} + +// GetByName retrieves an location by its name. If the location does not exist, nil is returned. +func (c *LocationClient) GetByName(ctx context.Context, name string) (*Location, *Response, error) { + if name == "" { + return nil, nil, nil + } + locations, response, err := c.List(ctx, LocationListOpts{Name: name}) + if len(locations) == 0 { + return nil, response, err + } + return locations[0], response, err +} + +// Get retrieves a location by its ID if the input can be parsed as an integer, otherwise it +// retrieves a location by its name. If the location does not exist, nil is returned. +func (c *LocationClient) Get(ctx context.Context, idOrName string) (*Location, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// LocationListOpts specifies options for listing location. +type LocationListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l LocationListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of locations for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *LocationClient) List(ctx context.Context, opts LocationListOpts) ([]*Location, *Response, error) { + path := "/locations?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.LocationListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + locations := make([]*Location, 0, len(body.Locations)) + for _, i := range body.Locations { + locations = append(locations, LocationFromSchema(i)) + } + return locations, resp, nil +} + +// All returns all locations. +func (c *LocationClient) All(ctx context.Context) ([]*Location, error) { + return c.AllWithOpts(ctx, LocationListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all locations for the given options. +func (c *LocationClient) AllWithOpts(ctx context.Context, opts LocationListOpts) ([]*Location, error) { + allLocations := []*Location{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + locations, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allLocations = append(allLocations, locations...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allLocations, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/network.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/network.go new file mode 100644 index 000000000..2688c93c4 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/network.go @@ -0,0 +1,484 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// NetworkZone specifies a network zone. +type NetworkZone string + +// List of available Network Zones. +const ( + NetworkZoneEUCentral NetworkZone = "eu-central" + NetworkZoneUSEast NetworkZone = "us-east" + NetworkZoneUSWest NetworkZone = "us-west" +) + +// NetworkSubnetType specifies a type of a subnet. +type NetworkSubnetType string + +// List of available network subnet types. +const ( + NetworkSubnetTypeCloud NetworkSubnetType = "cloud" + NetworkSubnetTypeServer NetworkSubnetType = "server" + NetworkSubnetTypeVSwitch NetworkSubnetType = "vswitch" +) + +// Network represents a network in the Hetzner Cloud. +type Network struct { + ID int64 + Name string + Created time.Time + IPRange *net.IPNet + Subnets []NetworkSubnet + Routes []NetworkRoute + Servers []*Server + Protection NetworkProtection + Labels map[string]string + + // ExposeRoutesToVSwitch indicates if the routes from this network should be exposed to the vSwitch connection. + ExposeRoutesToVSwitch bool +} + +// NetworkSubnet represents a subnet of a network in the Hetzner Cloud. +type NetworkSubnet struct { + Type NetworkSubnetType + IPRange *net.IPNet + NetworkZone NetworkZone + Gateway net.IP + VSwitchID int64 +} + +// NetworkRoute represents a route of a network. +type NetworkRoute struct { + Destination *net.IPNet + Gateway net.IP +} + +// NetworkProtection represents the protection level of a network. +type NetworkProtection struct { + Delete bool +} + +// NetworkClient is a client for the network API. +type NetworkClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves a network by its ID. If the network does not exist, nil is returned. +func (c *NetworkClient) GetByID(ctx context.Context, id int64) (*Network, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/networks/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.NetworkGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return NetworkFromSchema(body.Network), resp, nil +} + +// GetByName retrieves a network by its name. If the network does not exist, nil is returned. +func (c *NetworkClient) GetByName(ctx context.Context, name string) (*Network, *Response, error) { + if name == "" { + return nil, nil, nil + } + Networks, response, err := c.List(ctx, NetworkListOpts{Name: name}) + if len(Networks) == 0 { + return nil, response, err + } + return Networks[0], response, err +} + +// Get retrieves a network by its ID if the input can be parsed as an integer, otherwise it +// retrieves a network by its name. If the network does not exist, nil is returned. +func (c *NetworkClient) Get(ctx context.Context, idOrName string) (*Network, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// NetworkListOpts specifies options for listing networks. +type NetworkListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l NetworkListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of networks for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *NetworkClient) List(ctx context.Context, opts NetworkListOpts) ([]*Network, *Response, error) { + path := "/networks?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.NetworkListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + Networks := make([]*Network, 0, len(body.Networks)) + for _, s := range body.Networks { + Networks = append(Networks, NetworkFromSchema(s)) + } + return Networks, resp, nil +} + +// All returns all networks. +func (c *NetworkClient) All(ctx context.Context) ([]*Network, error) { + return c.AllWithOpts(ctx, NetworkListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all networks for the given options. +func (c *NetworkClient) AllWithOpts(ctx context.Context, opts NetworkListOpts) ([]*Network, error) { + allNetworks := []*Network{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + Networks, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allNetworks = append(allNetworks, Networks...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allNetworks, nil +} + +// Delete deletes a network. +func (c *NetworkClient) Delete(ctx context.Context, network *Network) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/networks/%d", network.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// NetworkUpdateOpts specifies options for updating a network. +type NetworkUpdateOpts struct { + Name string + Labels map[string]string + // ExposeRoutesToVSwitch indicates if the routes from this network should be exposed to the vSwitch connection. + // The exposing only takes effect if a vSwitch connection is active. + ExposeRoutesToVSwitch *bool +} + +// Update updates a network. +func (c *NetworkClient) Update(ctx context.Context, network *Network, opts NetworkUpdateOpts) (*Network, *Response, error) { + reqBody := schema.NetworkUpdateRequest{ + Name: opts.Name, + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + if opts.ExposeRoutesToVSwitch != nil { + reqBody.ExposeRoutesToVSwitch = opts.ExposeRoutesToVSwitch + } + + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/networks/%d", network.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return NetworkFromSchema(respBody.Network), resp, nil +} + +// NetworkCreateOpts specifies options for creating a new network. +type NetworkCreateOpts struct { + Name string + IPRange *net.IPNet + Subnets []NetworkSubnet + Routes []NetworkRoute + Labels map[string]string + // ExposeRoutesToVSwitch indicates if the routes from this network should be exposed to the vSwitch connection. + // The exposing only takes effect if a vSwitch connection is active. + ExposeRoutesToVSwitch bool +} + +// Validate checks if options are valid. +func (o NetworkCreateOpts) Validate() error { + if o.Name == "" { + return errors.New("missing name") + } + if o.IPRange == nil || o.IPRange.String() == "" { + return errors.New("missing IP range") + } + return nil +} + +// Create creates a new network. +func (c *NetworkClient) Create(ctx context.Context, opts NetworkCreateOpts) (*Network, *Response, error) { + if err := opts.Validate(); err != nil { + return nil, nil, err + } + reqBody := schema.NetworkCreateRequest{ + Name: opts.Name, + IPRange: opts.IPRange.String(), + ExposeRoutesToVSwitch: opts.ExposeRoutesToVSwitch, + } + for _, subnet := range opts.Subnets { + s := schema.NetworkSubnet{ + Type: string(subnet.Type), + IPRange: subnet.IPRange.String(), + NetworkZone: string(subnet.NetworkZone), + } + if subnet.VSwitchID != 0 { + s.VSwitchID = subnet.VSwitchID + } + reqBody.Subnets = append(reqBody.Subnets, s) + } + for _, route := range opts.Routes { + reqBody.Routes = append(reqBody.Routes, schema.NetworkRoute{ + Destination: route.Destination.String(), + Gateway: route.Gateway.String(), + }) + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + req, err := c.client.NewRequest(ctx, "POST", "/networks", bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkCreateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return NetworkFromSchema(respBody.Network), resp, nil +} + +// NetworkChangeIPRangeOpts specifies options for changing the IP range of a network. +type NetworkChangeIPRangeOpts struct { + IPRange *net.IPNet +} + +// ChangeIPRange changes the IP range of a network. +func (c *NetworkClient) ChangeIPRange(ctx context.Context, network *Network, opts NetworkChangeIPRangeOpts) (*Action, *Response, error) { + reqBody := schema.NetworkActionChangeIPRangeRequest{ + IPRange: opts.IPRange.String(), + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/networks/%d/actions/change_ip_range", network.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkActionChangeIPRangeResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// NetworkAddSubnetOpts specifies options for adding a subnet to a network. +type NetworkAddSubnetOpts struct { + Subnet NetworkSubnet +} + +// AddSubnet adds a subnet to a network. +func (c *NetworkClient) AddSubnet(ctx context.Context, network *Network, opts NetworkAddSubnetOpts) (*Action, *Response, error) { + reqBody := schema.NetworkActionAddSubnetRequest{ + Type: string(opts.Subnet.Type), + NetworkZone: string(opts.Subnet.NetworkZone), + } + if opts.Subnet.IPRange != nil { + reqBody.IPRange = opts.Subnet.IPRange.String() + } + if opts.Subnet.VSwitchID != 0 { + reqBody.VSwitchID = opts.Subnet.VSwitchID + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/networks/%d/actions/add_subnet", network.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkActionAddSubnetResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// NetworkDeleteSubnetOpts specifies options for deleting a subnet from a network. +type NetworkDeleteSubnetOpts struct { + Subnet NetworkSubnet +} + +// DeleteSubnet deletes a subnet from a network. +func (c *NetworkClient) DeleteSubnet(ctx context.Context, network *Network, opts NetworkDeleteSubnetOpts) (*Action, *Response, error) { + reqBody := schema.NetworkActionDeleteSubnetRequest{ + IPRange: opts.Subnet.IPRange.String(), + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/networks/%d/actions/delete_subnet", network.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkActionDeleteSubnetResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// NetworkAddRouteOpts specifies options for adding a route to a network. +type NetworkAddRouteOpts struct { + Route NetworkRoute +} + +// AddRoute adds a route to a network. +func (c *NetworkClient) AddRoute(ctx context.Context, network *Network, opts NetworkAddRouteOpts) (*Action, *Response, error) { + reqBody := schema.NetworkActionAddRouteRequest{ + Destination: opts.Route.Destination.String(), + Gateway: opts.Route.Gateway.String(), + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/networks/%d/actions/add_route", network.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkActionAddSubnetResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// NetworkDeleteRouteOpts specifies options for deleting a route from a network. +type NetworkDeleteRouteOpts struct { + Route NetworkRoute +} + +// DeleteRoute deletes a route from a network. +func (c *NetworkClient) DeleteRoute(ctx context.Context, network *Network, opts NetworkDeleteRouteOpts) (*Action, *Response, error) { + reqBody := schema.NetworkActionDeleteRouteRequest{ + Destination: opts.Route.Destination.String(), + Gateway: opts.Route.Gateway.String(), + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/networks/%d/actions/delete_route", network.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkActionDeleteSubnetResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// NetworkChangeProtectionOpts specifies options for changing the resource protection level of a network. +type NetworkChangeProtectionOpts struct { + Delete *bool +} + +// ChangeProtection changes the resource protection level of a network. +func (c *NetworkClient) ChangeProtection(ctx context.Context, network *Network, opts NetworkChangeProtectionOpts) (*Action, *Response, error) { + reqBody := schema.NetworkActionChangeProtectionRequest{ + Delete: opts.Delete, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/networks/%d/actions/change_protection", network.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.NetworkActionChangeProtectionResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/placement_group.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/placement_group.go new file mode 100644 index 000000000..5ad3515e0 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/placement_group.go @@ -0,0 +1,247 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// PlacementGroup represents a Placement Group in the Hetzner Cloud. +type PlacementGroup struct { + ID int64 + Name string + Labels map[string]string + Created time.Time + Servers []int64 + Type PlacementGroupType +} + +// PlacementGroupType specifies the type of a Placement Group. +type PlacementGroupType string + +const ( + // PlacementGroupTypeSpread spreads all servers in the group on different vhosts. + PlacementGroupTypeSpread PlacementGroupType = "spread" +) + +// PlacementGroupClient is a client for the Placement Groups API. +type PlacementGroupClient struct { + client *Client +} + +// GetByID retrieves a PlacementGroup by its ID. If the PlacementGroup does not exist, nil is returned. +func (c *PlacementGroupClient) GetByID(ctx context.Context, id int64) (*PlacementGroup, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/placement_groups/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.PlacementGroupGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return PlacementGroupFromSchema(body.PlacementGroup), resp, nil +} + +// GetByName retrieves a PlacementGroup by its name. If the PlacementGroup does not exist, nil is returned. +func (c *PlacementGroupClient) GetByName(ctx context.Context, name string) (*PlacementGroup, *Response, error) { + if name == "" { + return nil, nil, nil + } + placementGroups, response, err := c.List(ctx, PlacementGroupListOpts{Name: name}) + if len(placementGroups) == 0 { + return nil, response, err + } + return placementGroups[0], response, err +} + +// Get retrieves a PlacementGroup by its ID if the input can be parsed as an integer, otherwise it +// retrieves a PlacementGroup by its name. If the PlacementGroup does not exist, nil is returned. +func (c *PlacementGroupClient) Get(ctx context.Context, idOrName string) (*PlacementGroup, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// PlacementGroupListOpts specifies options for listing PlacementGroup. +type PlacementGroupListOpts struct { + ListOpts + Name string + Type PlacementGroupType + Sort []string +} + +func (l PlacementGroupListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + if l.Type != "" { + vals.Add("type", string(l.Type)) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of PlacementGroups for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *PlacementGroupClient) List(ctx context.Context, opts PlacementGroupListOpts) ([]*PlacementGroup, *Response, error) { + path := "/placement_groups?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.PlacementGroupListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + placementGroups := make([]*PlacementGroup, 0, len(body.PlacementGroups)) + for _, g := range body.PlacementGroups { + placementGroups = append(placementGroups, PlacementGroupFromSchema(g)) + } + return placementGroups, resp, nil +} + +// All returns all PlacementGroups. +func (c *PlacementGroupClient) All(ctx context.Context) ([]*PlacementGroup, error) { + opts := PlacementGroupListOpts{ + ListOpts: ListOpts{ + PerPage: 50, + }, + } + + return c.AllWithOpts(ctx, opts) +} + +// AllWithOpts returns all PlacementGroups for the given options. +func (c *PlacementGroupClient) AllWithOpts(ctx context.Context, opts PlacementGroupListOpts) ([]*PlacementGroup, error) { + allPlacementGroups := []*PlacementGroup{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + placementGroups, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allPlacementGroups = append(allPlacementGroups, placementGroups...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allPlacementGroups, nil +} + +// PlacementGroupCreateOpts specifies options for creating a new PlacementGroup. +type PlacementGroupCreateOpts struct { + Name string + Labels map[string]string + Type PlacementGroupType +} + +// Validate checks if options are valid. +func (o PlacementGroupCreateOpts) Validate() error { + if o.Name == "" { + return errors.New("missing name") + } + return nil +} + +// PlacementGroupCreateResult is the result of a create PlacementGroup call. +type PlacementGroupCreateResult struct { + PlacementGroup *PlacementGroup + Action *Action +} + +// Create creates a new PlacementGroup. +func (c *PlacementGroupClient) Create(ctx context.Context, opts PlacementGroupCreateOpts) (PlacementGroupCreateResult, *Response, error) { + if err := opts.Validate(); err != nil { + return PlacementGroupCreateResult{}, nil, err + } + reqBody := placementGroupCreateOptsToSchema(opts) + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return PlacementGroupCreateResult{}, nil, err + } + req, err := c.client.NewRequest(ctx, "POST", "/placement_groups", bytes.NewReader(reqBodyData)) + if err != nil { + return PlacementGroupCreateResult{}, nil, err + } + + respBody := schema.PlacementGroupCreateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return PlacementGroupCreateResult{}, nil, err + } + result := PlacementGroupCreateResult{ + PlacementGroup: PlacementGroupFromSchema(respBody.PlacementGroup), + } + if respBody.Action != nil { + result.Action = ActionFromSchema(*respBody.Action) + } + + return result, resp, nil +} + +// PlacementGroupUpdateOpts specifies options for updating a PlacementGroup. +type PlacementGroupUpdateOpts struct { + Name string + Labels map[string]string +} + +// Update updates a PlacementGroup. +func (c *PlacementGroupClient) Update(ctx context.Context, placementGroup *PlacementGroup, opts PlacementGroupUpdateOpts) (*PlacementGroup, *Response, error) { + reqBody := schema.PlacementGroupUpdateRequest{} + if opts.Name != "" { + reqBody.Name = &opts.Name + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/placement_groups/%d", placementGroup.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.PlacementGroupUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + + return PlacementGroupFromSchema(respBody.PlacementGroup), resp, nil +} + +// Delete deletes a PlacementGroup. +func (c *PlacementGroupClient) Delete(ctx context.Context, placementGroup *PlacementGroup) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/placement_groups/%d", placementGroup.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/pricing.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/pricing.go new file mode 100644 index 000000000..2a1b96b76 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/pricing.go @@ -0,0 +1,139 @@ +package hcloud + +import ( + "context" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Pricing specifies pricing information for various resources. +type Pricing struct { + Image ImagePricing + FloatingIP FloatingIPPricing + FloatingIPs []FloatingIPTypePricing + PrimaryIPs []PrimaryIPPricing + Traffic TrafficPricing + ServerBackup ServerBackupPricing + ServerTypes []ServerTypePricing + LoadBalancerTypes []LoadBalancerTypePricing + Volume VolumePricing +} + +// Price represents a price. Net amount, gross amount, as well as VAT rate are +// specified as strings and it is the user's responsibility to convert them to +// appropriate types for calculations. +type Price struct { + Currency string + VATRate string + Net string + Gross string +} + +// PrimaryIPPrice represents a price. Net amount and gross amount are +// specified as strings and it is the user's responsibility to convert them to +// appropriate types for calculations. +type PrimaryIPPrice struct { + Net string + Gross string +} + +// ImagePricing provides pricing information for imaegs. +type ImagePricing struct { + PerGBMonth Price +} + +// FloatingIPPricing provides pricing information for Floating IPs. +type FloatingIPPricing struct { + Monthly Price +} + +// FloatingIPTypePricing provides pricing information for Floating IPs per Type. +type FloatingIPTypePricing struct { + Type FloatingIPType + Pricings []FloatingIPTypeLocationPricing +} + +// PrimaryIPTypePricing defines the schema of pricing information for a primary IP +// type at a datacenter. +type PrimaryIPTypePricing struct { + Datacenter string // Deprecated: the API does not return pricing for the individual DCs anymore + Location string + Hourly PrimaryIPPrice + Monthly PrimaryIPPrice +} + +// PrimaryIPTypePricing provides pricing information for PrimaryIPs. +type PrimaryIPPricing struct { + Type string + Pricings []PrimaryIPTypePricing +} + +// FloatingIPTypeLocationPricing provides pricing information for a Floating IP type +// at a location. +type FloatingIPTypeLocationPricing struct { + Location *Location + Monthly Price +} + +// TrafficPricing provides pricing information for traffic. +type TrafficPricing struct { + PerTB Price +} + +// VolumePricing provides pricing information for a Volume. +type VolumePricing struct { + PerGBMonthly Price +} + +// ServerBackupPricing provides pricing information for server backups. +type ServerBackupPricing struct { + Percentage string +} + +// ServerTypePricing provides pricing information for a server type. +type ServerTypePricing struct { + ServerType *ServerType + Pricings []ServerTypeLocationPricing +} + +// ServerTypeLocationPricing provides pricing information for a server type +// at a location. +type ServerTypeLocationPricing struct { + Location *Location + Hourly Price + Monthly Price +} + +// LoadBalancerTypePricing provides pricing information for a Load Balancer type. +type LoadBalancerTypePricing struct { + LoadBalancerType *LoadBalancerType + Pricings []LoadBalancerTypeLocationPricing +} + +// LoadBalancerTypeLocationPricing provides pricing information for a Load Balancer type +// at a location. +type LoadBalancerTypeLocationPricing struct { + Location *Location + Hourly Price + Monthly Price +} + +// PricingClient is a client for the pricing API. +type PricingClient struct { + client *Client +} + +// Get retrieves pricing information. +func (c *PricingClient) Get(ctx context.Context) (Pricing, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", "/pricing", nil) + if err != nil { + return Pricing{}, nil, err + } + + var body schema.PricingGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return Pricing{}, nil, err + } + return PricingFromSchema(body.Pricing), resp, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/primary_ip.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/primary_ip.go new file mode 100644 index 000000000..5d241e6d4 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/primary_ip.go @@ -0,0 +1,422 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// PrimaryIP defines a Primary IP. +type PrimaryIP struct { + ID int64 + IP net.IP + Network *net.IPNet + Labels map[string]string + Name string + Type PrimaryIPType + Protection PrimaryIPProtection + DNSPtr map[string]string + AssigneeID int64 + AssigneeType string + AutoDelete bool + Blocked bool + Created time.Time + Datacenter *Datacenter +} + +// PrimaryIPProtection represents the protection level of a Primary IP. +type PrimaryIPProtection struct { + Delete bool +} + +// PrimaryIPDNSPTR contains reverse DNS information for a +// IPv4 or IPv6 Primary IP. +type PrimaryIPDNSPTR struct { + DNSPtr string + IP string +} + +// changeDNSPtr changes or resets the reverse DNS pointer for a IP address. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (p *PrimaryIP) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { + reqBody := schema.PrimaryIPActionChangeDNSPtrRequest{ + IP: ip.String(), + DNSPtr: ptr, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/primary_ips/%d/actions/change_dns_ptr", p.ID) + req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody PrimaryIPChangeDNSPtrResult + resp, err := client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// GetDNSPtrForIP searches for the dns assigned to the given IP address. +// It returns an error if there is no dns set for the given IP address. +func (p *PrimaryIP) GetDNSPtrForIP(ip net.IP) (string, error) { + dns, ok := p.DNSPtr[ip.String()] + if !ok { + return "", DNSNotFoundError{ip} + } + + return dns, nil +} + +// PrimaryIPType represents the type of Primary IP. +type PrimaryIPType string + +// PrimaryIPType Primary IP types. +const ( + PrimaryIPTypeIPv4 PrimaryIPType = "ipv4" + PrimaryIPTypeIPv6 PrimaryIPType = "ipv6" +) + +// PrimaryIPCreateOpts defines the request to +// create a Primary IP. +type PrimaryIPCreateOpts struct { + AssigneeID *int64 `json:"assignee_id,omitempty"` + AssigneeType string `json:"assignee_type"` + AutoDelete *bool `json:"auto_delete,omitempty"` + Datacenter string `json:"datacenter,omitempty"` + Labels map[string]string `json:"labels,omitempty"` + Name string `json:"name"` + Type PrimaryIPType `json:"type"` +} + +// PrimaryIPCreateResult defines the response +// when creating a Primary IP. +type PrimaryIPCreateResult struct { + PrimaryIP *PrimaryIP + Action *Action +} + +// PrimaryIPUpdateOpts defines the request to +// update a Primary IP. +type PrimaryIPUpdateOpts struct { + AutoDelete *bool `json:"auto_delete,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + Name string `json:"name,omitempty"` +} + +// PrimaryIPAssignOpts defines the request to +// assign a Primary IP to an assignee (usually a server). +type PrimaryIPAssignOpts struct { + ID int64 + AssigneeID int64 `json:"assignee_id"` + AssigneeType string `json:"assignee_type"` +} + +// PrimaryIPAssignResult defines the response +// when assigning a Primary IP to a assignee. +type PrimaryIPAssignResult struct { + Action schema.Action `json:"action"` +} + +// PrimaryIPChangeDNSPtrOpts defines the request to +// change a DNS PTR entry from a Primary IP. +type PrimaryIPChangeDNSPtrOpts struct { + ID int64 + DNSPtr string `json:"dns_ptr"` + IP string `json:"ip"` +} + +// PrimaryIPChangeDNSPtrResult defines the response +// when assigning a Primary IP to a assignee. +type PrimaryIPChangeDNSPtrResult struct { + Action schema.Action `json:"action"` +} + +// PrimaryIPChangeProtectionOpts defines the request to +// change protection configuration of a Primary IP. +type PrimaryIPChangeProtectionOpts struct { + ID int64 + Delete bool `json:"delete"` +} + +// PrimaryIPChangeProtectionResult defines the response +// when changing a protection of a PrimaryIP. +type PrimaryIPChangeProtectionResult struct { + Action schema.Action `json:"action"` +} + +// PrimaryIPClient is a client for the Primary IP API. +type PrimaryIPClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves a Primary IP by its ID. If the Primary IP does not exist, nil is returned. +func (c *PrimaryIPClient) GetByID(ctx context.Context, id int64) (*PrimaryIP, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/primary_ips/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.PrimaryIPGetResult + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return PrimaryIPFromSchema(body.PrimaryIP), resp, nil +} + +// GetByIP retrieves a Primary IP by its IP Address. If the Primary IP does not exist, nil is returned. +func (c *PrimaryIPClient) GetByIP(ctx context.Context, ip string) (*PrimaryIP, *Response, error) { + if ip == "" { + return nil, nil, nil + } + primaryIPs, response, err := c.List(ctx, PrimaryIPListOpts{IP: ip}) + if len(primaryIPs) == 0 { + return nil, response, err + } + return primaryIPs[0], response, err +} + +// GetByName retrieves a Primary IP by its name. If the Primary IP does not exist, nil is returned. +func (c *PrimaryIPClient) GetByName(ctx context.Context, name string) (*PrimaryIP, *Response, error) { + if name == "" { + return nil, nil, nil + } + primaryIPs, response, err := c.List(ctx, PrimaryIPListOpts{Name: name}) + if len(primaryIPs) == 0 { + return nil, response, err + } + return primaryIPs[0], response, err +} + +// Get retrieves a Primary IP by its ID if the input can be parsed as an integer, otherwise it +// retrieves a Primary IP by its name. If the Primary IP does not exist, nil is returned. +func (c *PrimaryIPClient) Get(ctx context.Context, idOrName string) (*PrimaryIP, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// PrimaryIPListOpts specifies options for listing Primary IPs. +type PrimaryIPListOpts struct { + ListOpts + Name string + IP string + Sort []string +} + +func (l PrimaryIPListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + if l.IP != "" { + vals.Add("ip", l.IP) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of Primary IPs for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *PrimaryIPClient) List(ctx context.Context, opts PrimaryIPListOpts) ([]*PrimaryIP, *Response, error) { + path := "/primary_ips?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.PrimaryIPListResult + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + primaryIPs := make([]*PrimaryIP, 0, len(body.PrimaryIPs)) + for _, s := range body.PrimaryIPs { + primaryIPs = append(primaryIPs, PrimaryIPFromSchema(s)) + } + return primaryIPs, resp, nil +} + +// All returns all Primary IPs. +func (c *PrimaryIPClient) All(ctx context.Context) ([]*PrimaryIP, error) { + return c.AllWithOpts(ctx, PrimaryIPListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all Primary IPs for the given options. +func (c *PrimaryIPClient) AllWithOpts(ctx context.Context, opts PrimaryIPListOpts) ([]*PrimaryIP, error) { + allPrimaryIPs := []*PrimaryIP{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + primaryIPs, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allPrimaryIPs = append(allPrimaryIPs, primaryIPs...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allPrimaryIPs, nil +} + +// Create creates a Primary IP. +func (c *PrimaryIPClient) Create(ctx context.Context, reqBody PrimaryIPCreateOpts) (*PrimaryIPCreateResult, *Response, error) { + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return &PrimaryIPCreateResult{}, nil, err + } + + req, err := c.client.NewRequest(ctx, "POST", "/primary_ips", bytes.NewReader(reqBodyData)) + if err != nil { + return &PrimaryIPCreateResult{}, nil, err + } + + var respBody schema.PrimaryIPCreateResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return &PrimaryIPCreateResult{}, resp, err + } + var action *Action + if respBody.Action != nil { + action = ActionFromSchema(*respBody.Action) + } + primaryIP := PrimaryIPFromSchema(respBody.PrimaryIP) + return &PrimaryIPCreateResult{ + PrimaryIP: primaryIP, + Action: action, + }, resp, nil +} + +// Delete deletes a Primary IP. +func (c *PrimaryIPClient) Delete(ctx context.Context, primaryIP *PrimaryIP) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/primary_ips/%d", primaryIP.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// Update updates a Primary IP. +func (c *PrimaryIPClient) Update(ctx context.Context, primaryIP *PrimaryIP, reqBody PrimaryIPUpdateOpts) (*PrimaryIP, *Response, error) { + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/primary_ips/%d", primaryIP.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.PrimaryIPUpdateResult + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return PrimaryIPFromSchema(respBody.PrimaryIP), resp, nil +} + +// Assign a Primary IP to a resource. +func (c *PrimaryIPClient) Assign(ctx context.Context, opts PrimaryIPAssignOpts) (*Action, *Response, error) { + reqBodyData, err := json.Marshal(opts) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/primary_ips/%d/actions/assign", opts.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody PrimaryIPAssignResult + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// Unassign a Primary IP from a resource. +func (c *PrimaryIPClient) Unassign(ctx context.Context, id int64) (*Action, *Response, error) { + path := fmt.Sprintf("/primary_ips/%d/actions/unassign", id) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader([]byte{})) + if err != nil { + return nil, nil, err + } + + var respBody PrimaryIPAssignResult + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// ChangeDNSPtr Change the reverse DNS from a Primary IP. +func (c *PrimaryIPClient) ChangeDNSPtr(ctx context.Context, opts PrimaryIPChangeDNSPtrOpts) (*Action, *Response, error) { + reqBodyData, err := json.Marshal(opts) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/primary_ips/%d/actions/change_dns_ptr", opts.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody PrimaryIPChangeDNSPtrResult + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// ChangeProtection Changes the protection configuration of a Primary IP. +func (c *PrimaryIPClient) ChangeProtection(ctx context.Context, opts PrimaryIPChangeProtectionOpts) (*Action, *Response, error) { + reqBodyData, err := json.Marshal(opts) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/primary_ips/%d/actions/change_protection", opts.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody PrimaryIPChangeProtectionResult + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/rdns.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/rdns.go similarity index 80% rename from vendor/github.com/hetznercloud/hcloud-go/hcloud/rdns.go rename to vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/rdns.go index 891ea2bf8..f53c030da 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/rdns.go +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/rdns.go @@ -7,7 +7,7 @@ import ( ) // RDNSSupporter defines functions to change and lookup reverse dns entries. -// currently implemented by Server, FloatingIP and LoadBalancer. +// currently implemented by Server, FloatingIP, PrimaryIP and LoadBalancer. type RDNSSupporter interface { // changeDNSPtr changes or resets the reverse DNS pointer for a IP address. // Pass a nil ptr to reset the reverse DNS pointer to its default value. @@ -17,7 +17,7 @@ type RDNSSupporter interface { GetDNSPtrForIP(ip net.IP) (string, error) } -// RDNSClient simplifys the handling objects which support reverse dns entries. +// RDNSClient simplifies the handling objects which support reverse dns entries. type RDNSClient struct { client *Client } @@ -44,3 +44,9 @@ func RDNSLookup(i interface{}, ip net.IP) (string, error) { return rdns.GetDNSPtrForIP(ip) } + +// Make sure that all expected Resources actually implement the interface. +var _ RDNSSupporter = &FloatingIP{} +var _ RDNSSupporter = &PrimaryIP{} +var _ RDNSSupporter = &Server{} +var _ RDNSSupporter = &LoadBalancer{} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/resource.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/resource.go new file mode 100644 index 000000000..a74b2cf7a --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/resource.go @@ -0,0 +1,7 @@ +package hcloud + +// Resource defines the schema of a resource. +type Resource struct { + ID int64 + Type string +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema.go new file mode 100644 index 000000000..097b282ce --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema.go @@ -0,0 +1,370 @@ +package hcloud + +import ( + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// This file provides converter functions to convert models in the +// schema package to models in the hcloud package and vice versa. + +var c converter + +// ActionFromSchema converts a schema.Action to an Action. +func ActionFromSchema(s schema.Action) *Action { + return c.ActionFromSchema(s) +} + +// SchemaFromAction converts an Action to a schema.Action. +func SchemaFromAction(a *Action) schema.Action { + return c.SchemaFromAction(a) +} + +// ActionsFromSchema converts a slice of schema.Action to a slice of Action. +func ActionsFromSchema(s []schema.Action) []*Action { + return c.ActionsFromSchema(s) +} + +// SchemaFromActions converts a slice of Action to a slice of schema.Action. +func SchemaFromActions(a []*Action) []schema.Action { + return c.SchemaFromActions(a) +} + +// FloatingIPFromSchema converts a schema.FloatingIP to a FloatingIP. +func FloatingIPFromSchema(s schema.FloatingIP) *FloatingIP { + return c.FloatingIPFromSchema(s) +} + +// SchemaFromFloatingIP converts a FloatingIP to a schema.FloatingIP. +func SchemaFromFloatingIP(f *FloatingIP) schema.FloatingIP { + return c.SchemaFromFloatingIP(f) +} + +// PrimaryIPFromSchema converts a schema.PrimaryIP to a PrimaryIP. +func PrimaryIPFromSchema(s schema.PrimaryIP) *PrimaryIP { + return c.PrimaryIPFromSchema(s) +} + +// SchemaFromPrimaryIP converts a PrimaryIP to a schema.PrimaryIP. +func SchemaFromPrimaryIP(p *PrimaryIP) schema.PrimaryIP { + return c.SchemaFromPrimaryIP(p) +} + +// ISOFromSchema converts a schema.ISO to an ISO. +func ISOFromSchema(s schema.ISO) *ISO { + return c.ISOFromSchema(s) +} + +// SchemaFromISO converts an ISO to a schema.ISO. +func SchemaFromISO(i *ISO) schema.ISO { + return c.SchemaFromISO(i) +} + +// LocationFromSchema converts a schema.Location to a Location. +func LocationFromSchema(s schema.Location) *Location { + return c.LocationFromSchema(s) +} + +// SchemaFromLocation converts a Location to a schema.Location. +func SchemaFromLocation(l *Location) schema.Location { + return c.SchemaFromLocation(l) +} + +// DatacenterFromSchema converts a schema.Datacenter to a Datacenter. +func DatacenterFromSchema(s schema.Datacenter) *Datacenter { + return c.DatacenterFromSchema(s) +} + +// SchemaFromDatacenter converts a Datacenter to a schema.Datacenter. +func SchemaFromDatacenter(d *Datacenter) schema.Datacenter { + return c.SchemaFromDatacenter(d) +} + +// ServerFromSchema converts a schema.Server to a Server. +func ServerFromSchema(s schema.Server) *Server { + return c.ServerFromSchema(s) +} + +// SchemaFromServer converts a Server to a schema.Server. +func SchemaFromServer(s *Server) schema.Server { + return c.SchemaFromServer(s) +} + +// ServerPublicNetFromSchema converts a schema.ServerPublicNet to a ServerPublicNet. +func ServerPublicNetFromSchema(s schema.ServerPublicNet) ServerPublicNet { + return c.ServerPublicNetFromSchema(s) +} + +// SchemaFromServerPublicNet converts a ServerPublicNet to a schema.ServerPublicNet. +func SchemaFromServerPublicNet(s ServerPublicNet) schema.ServerPublicNet { + return c.SchemaFromServerPublicNet(s) +} + +// ServerPublicNetIPv4FromSchema converts a schema.ServerPublicNetIPv4 to +// a ServerPublicNetIPv4. +func ServerPublicNetIPv4FromSchema(s schema.ServerPublicNetIPv4) ServerPublicNetIPv4 { + return c.ServerPublicNetIPv4FromSchema(s) +} + +// SchemaFromServerPublicNetIPv4 converts a ServerPublicNetIPv4 to +// a schema.ServerPublicNetIPv4. +func SchemaFromServerPublicNetIPv4(s ServerPublicNetIPv4) schema.ServerPublicNetIPv4 { + return c.SchemaFromServerPublicNetIPv4(s) +} + +// ServerPublicNetIPv6FromSchema converts a schema.ServerPublicNetIPv6 to +// a ServerPublicNetIPv6. +func ServerPublicNetIPv6FromSchema(s schema.ServerPublicNetIPv6) ServerPublicNetIPv6 { + return c.ServerPublicNetIPv6FromSchema(s) +} + +// SchemaFromServerPublicNetIPv6 converts a ServerPublicNetIPv6 to +// a schema.ServerPublicNetIPv6. +func SchemaFromServerPublicNetIPv6(s ServerPublicNetIPv6) schema.ServerPublicNetIPv6 { + return c.SchemaFromServerPublicNetIPv6(s) +} + +// ServerPrivateNetFromSchema converts a schema.ServerPrivateNet to a ServerPrivateNet. +func ServerPrivateNetFromSchema(s schema.ServerPrivateNet) ServerPrivateNet { + return c.ServerPrivateNetFromSchema(s) +} + +// SchemaFromServerPrivateNet converts a ServerPrivateNet to a schema.ServerPrivateNet. +func SchemaFromServerPrivateNet(s ServerPrivateNet) schema.ServerPrivateNet { + return c.SchemaFromServerPrivateNet(s) +} + +// ServerTypeFromSchema converts a schema.ServerType to a ServerType. +func ServerTypeFromSchema(s schema.ServerType) *ServerType { + return c.ServerTypeFromSchema(s) +} + +// SchemaFromServerType converts a ServerType to a schema.ServerType. +func SchemaFromServerType(s *ServerType) schema.ServerType { + return c.SchemaFromServerType(s) +} + +// SSHKeyFromSchema converts a schema.SSHKey to a SSHKey. +func SSHKeyFromSchema(s schema.SSHKey) *SSHKey { + return c.SSHKeyFromSchema(s) +} + +// SchemaFromSSHKey converts a SSHKey to a schema.SSHKey. +func SchemaFromSSHKey(s *SSHKey) schema.SSHKey { + return c.SchemaFromSSHKey(s) +} + +// ImageFromSchema converts a schema.Image to an Image. +func ImageFromSchema(s schema.Image) *Image { + return c.ImageFromSchema(s) +} + +// SchemaFromImage converts an Image to a schema.Image. +func SchemaFromImage(i *Image) schema.Image { + return c.SchemaFromImage(i) +} + +// VolumeFromSchema converts a schema.Volume to a Volume. +func VolumeFromSchema(s schema.Volume) *Volume { + return c.VolumeFromSchema(s) +} + +// SchemaFromVolume converts a Volume to a schema.Volume. +func SchemaFromVolume(v *Volume) schema.Volume { + return c.SchemaFromVolume(v) +} + +// NetworkFromSchema converts a schema.Network to a Network. +func NetworkFromSchema(s schema.Network) *Network { + return c.NetworkFromSchema(s) +} + +// SchemaFromNetwork converts a Network to a schema.Network. +func SchemaFromNetwork(n *Network) schema.Network { + return c.SchemaFromNetwork(n) +} + +// NetworkSubnetFromSchema converts a schema.NetworkSubnet to a NetworkSubnet. +func NetworkSubnetFromSchema(s schema.NetworkSubnet) NetworkSubnet { + return c.NetworkSubnetFromSchema(s) +} + +// SchemaFromNetworkSubnet converts a NetworkSubnet to a schema.NetworkSubnet. +func SchemaFromNetworkSubnet(n NetworkSubnet) schema.NetworkSubnet { + return c.SchemaFromNetworkSubnet(n) +} + +// NetworkRouteFromSchema converts a schema.NetworkRoute to a NetworkRoute. +func NetworkRouteFromSchema(s schema.NetworkRoute) NetworkRoute { + return c.NetworkRouteFromSchema(s) +} + +// SchemaFromNetworkRoute converts a NetworkRoute to a schema.NetworkRoute. +func SchemaFromNetworkRoute(n NetworkRoute) schema.NetworkRoute { + return c.SchemaFromNetworkRoute(n) +} + +// LoadBalancerTypeFromSchema converts a schema.LoadBalancerType to a LoadBalancerType. +func LoadBalancerTypeFromSchema(s schema.LoadBalancerType) *LoadBalancerType { + return c.LoadBalancerTypeFromSchema(s) +} + +// SchemaFromLoadBalancerType converts a LoadBalancerType to a schema.LoadBalancerType. +func SchemaFromLoadBalancerType(l *LoadBalancerType) schema.LoadBalancerType { + return c.SchemaFromLoadBalancerType(l) +} + +// LoadBalancerFromSchema converts a schema.LoadBalancer to a LoadBalancer. +func LoadBalancerFromSchema(s schema.LoadBalancer) *LoadBalancer { + return c.LoadBalancerFromSchema(s) +} + +// SchemaFromLoadBalancer converts a LoadBalancer to a schema.LoadBalancer. +func SchemaFromLoadBalancer(l *LoadBalancer) schema.LoadBalancer { + return c.SchemaFromLoadBalancer(l) +} + +// LoadBalancerServiceFromSchema converts a schema.LoadBalancerService to a LoadBalancerService. +func LoadBalancerServiceFromSchema(s schema.LoadBalancerService) LoadBalancerService { + return c.LoadBalancerServiceFromSchema(s) +} + +// SchemaFromLoadBalancerService converts a LoadBalancerService to a schema.LoadBalancerService. +func SchemaFromLoadBalancerService(l LoadBalancerService) schema.LoadBalancerService { + return c.SchemaFromLoadBalancerService(l) +} + +// LoadBalancerServiceHealthCheckFromSchema converts a schema.LoadBalancerServiceHealthCheck to a LoadBalancerServiceHealthCheck. +func LoadBalancerServiceHealthCheckFromSchema(s *schema.LoadBalancerServiceHealthCheck) LoadBalancerServiceHealthCheck { + return c.LoadBalancerServiceHealthCheckFromSchema(s) +} + +// SchemaFromLoadBalancerServiceHealthCheck converts a LoadBalancerServiceHealthCheck to a schema.LoadBalancerServiceHealthCheck. +func SchemaFromLoadBalancerServiceHealthCheck(l LoadBalancerServiceHealthCheck) *schema.LoadBalancerServiceHealthCheck { + return c.SchemaFromLoadBalancerServiceHealthCheck(l) +} + +// LoadBalancerTargetFromSchema converts a schema.LoadBalancerTarget to a LoadBalancerTarget. +func LoadBalancerTargetFromSchema(s schema.LoadBalancerTarget) LoadBalancerTarget { + return c.LoadBalancerTargetFromSchema(s) +} + +// SchemaFromLoadBalancerTarget converts a LoadBalancerTarget to a schema.LoadBalancerTarget. +func SchemaFromLoadBalancerTarget(l LoadBalancerTarget) schema.LoadBalancerTarget { + return c.SchemaFromLoadBalancerTarget(l) +} + +// LoadBalancerTargetHealthStatusFromSchema converts a schema.LoadBalancerTarget to a LoadBalancerTarget. +func LoadBalancerTargetHealthStatusFromSchema(s schema.LoadBalancerTargetHealthStatus) LoadBalancerTargetHealthStatus { + return c.LoadBalancerTargetHealthStatusFromSchema(s) +} + +// SchemaFromLoadBalancerTargetHealthStatus converts a LoadBalancerTarget to a schema.LoadBalancerTarget. +func SchemaFromLoadBalancerTargetHealthStatus(l LoadBalancerTargetHealthStatus) schema.LoadBalancerTargetHealthStatus { + return c.SchemaFromLoadBalancerTargetHealthStatus(l) +} + +// CertificateFromSchema converts a schema.Certificate to a Certificate. +func CertificateFromSchema(s schema.Certificate) *Certificate { + return c.CertificateFromSchema(s) +} + +// SchemaFromCertificate converts a Certificate to a schema.Certificate. +func SchemaFromCertificate(ct *Certificate) schema.Certificate { + return c.SchemaFromCertificate(ct) +} + +// PaginationFromSchema converts a schema.MetaPagination to a Pagination. +func PaginationFromSchema(s schema.MetaPagination) Pagination { + return c.PaginationFromSchema(s) +} + +// SchemaFromPagination converts a Pagination to a schema.MetaPagination. +func SchemaFromPagination(p Pagination) schema.MetaPagination { + return c.SchemaFromPagination(p) +} + +// ErrorFromSchema converts a schema.Error to an Error. +func ErrorFromSchema(s schema.Error) Error { + return c.ErrorFromSchema(s) +} + +// SchemaFromError converts an Error to a schema.Error. +func SchemaFromError(e Error) schema.Error { + return c.SchemaFromError(e) +} + +// PricingFromSchema converts a schema.Pricing to a Pricing. +func PricingFromSchema(s schema.Pricing) Pricing { + return c.PricingFromSchema(s) +} + +// SchemaFromPricing converts a Pricing to a schema.Pricing. +func SchemaFromPricing(p Pricing) schema.Pricing { + return c.SchemaFromPricing(p) +} + +// FirewallFromSchema converts a schema.Firewall to a Firewall. +func FirewallFromSchema(s schema.Firewall) *Firewall { + return c.FirewallFromSchema(s) +} + +// SchemaFromFirewall converts a Firewall to a schema.Firewall. +func SchemaFromFirewall(f *Firewall) schema.Firewall { + return c.SchemaFromFirewall(f) +} + +// PlacementGroupFromSchema converts a schema.PlacementGroup to a PlacementGroup. +func PlacementGroupFromSchema(s schema.PlacementGroup) *PlacementGroup { + return c.PlacementGroupFromSchema(s) +} + +// SchemaFromPlacementGroup converts a PlacementGroup to a schema.PlacementGroup. +func SchemaFromPlacementGroup(p *PlacementGroup) schema.PlacementGroup { + return c.SchemaFromPlacementGroup(p) +} + +// DeprecationFromSchema converts a [schema.DeprecationInfo] to a [DeprecationInfo]. +func DeprecationFromSchema(s *schema.DeprecationInfo) *DeprecationInfo { + return c.DeprecationFromSchema(s) +} + +// SchemaFromDeprecation converts a [DeprecationInfo] to a [schema.DeprecationInfo]. +func SchemaFromDeprecation(d *DeprecationInfo) *schema.DeprecationInfo { + return c.SchemaFromDeprecation(d) +} + +func placementGroupCreateOptsToSchema(opts PlacementGroupCreateOpts) schema.PlacementGroupCreateRequest { + return c.SchemaFromPlacementGroupCreateOpts(opts) +} + +func loadBalancerCreateOptsToSchema(opts LoadBalancerCreateOpts) schema.LoadBalancerCreateRequest { + return c.SchemaFromLoadBalancerCreateOpts(opts) +} + +func loadBalancerAddServiceOptsToSchema(opts LoadBalancerAddServiceOpts) schema.LoadBalancerActionAddServiceRequest { + return c.SchemaFromLoadBalancerAddServiceOpts(opts) +} + +func loadBalancerUpdateServiceOptsToSchema(opts LoadBalancerUpdateServiceOpts) schema.LoadBalancerActionUpdateServiceRequest { + return c.SchemaFromLoadBalancerUpdateServiceOpts(opts) +} + +func firewallCreateOptsToSchema(opts FirewallCreateOpts) schema.FirewallCreateRequest { + return c.SchemaFromFirewallCreateOpts(opts) +} + +func firewallSetRulesOptsToSchema(opts FirewallSetRulesOpts) schema.FirewallActionSetRulesRequest { + return c.SchemaFromFirewallSetRulesOpts(opts) +} + +func firewallResourceToSchema(resource FirewallResource) schema.FirewallResource { + return c.SchemaFromFirewallResource(resource) +} + +func serverMetricsFromSchema(s *schema.ServerGetMetricsResponse) (*ServerMetrics, error) { + return c.ServerMetricsFromSchema(s) +} + +func loadBalancerMetricsFromSchema(s *schema.LoadBalancerGetMetricsResponse) (*LoadBalancerMetrics, error) { + return c.LoadBalancerMetricsFromSchema(s) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/action.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/action.go new file mode 100644 index 000000000..49ac96a22 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/action.go @@ -0,0 +1,39 @@ +package schema + +import "time" + +// Action defines the schema of an action. +type Action struct { + ID int64 `json:"id"` + Status string `json:"status"` + Command string `json:"command"` + Progress int `json:"progress"` + Started time.Time `json:"started"` + Finished *time.Time `json:"finished"` + Error *ActionError `json:"error"` + Resources []ActionResourceReference `json:"resources"` +} + +// ActionResourceReference defines the schema of an action resource reference. +type ActionResourceReference struct { + ID int64 `json:"id"` + Type string `json:"type"` +} + +// ActionError defines the schema of an error embedded +// in an action. +type ActionError struct { + Code string `json:"code"` + Message string `json:"message"` +} + +// ActionGetResponse is the schema of the response when +// retrieving a single action. +type ActionGetResponse struct { + Action Action `json:"action"` +} + +// ActionListResponse defines the schema of the response when listing actions. +type ActionListResponse struct { + Actions []Action `json:"actions"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/certificate.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/certificate.go new file mode 100644 index 000000000..eb7b03ce2 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/certificate.go @@ -0,0 +1,76 @@ +package schema + +import "time" + +// CertificateUsedByRef defines the schema of a resource using a certificate. +type CertificateUsedByRef struct { + ID int64 `json:"id"` + Type string `json:"type"` +} + +type CertificateStatusRef struct { + Issuance string `json:"issuance"` + Renewal string `json:"renewal"` + Error *Error `json:"error,omitempty"` +} + +// Certificate defines the schema of an certificate. +type Certificate struct { + ID int64 `json:"id"` + Name string `json:"name"` + Labels map[string]string `json:"labels"` + Type string `json:"type"` + Certificate string `json:"certificate"` + Created time.Time `json:"created"` + NotValidBefore time.Time `json:"not_valid_before"` + NotValidAfter time.Time `json:"not_valid_after"` + DomainNames []string `json:"domain_names"` + Fingerprint string `json:"fingerprint"` + Status *CertificateStatusRef `json:"status"` + UsedBy []CertificateUsedByRef `json:"used_by"` +} + +// CertificateListResponse defines the schema of the response when +// listing Certificates. +type CertificateListResponse struct { + Certificates []Certificate `json:"certificates"` +} + +// CertificateGetResponse defines the schema of the response when +// retrieving a single Certificate. +type CertificateGetResponse struct { + Certificate Certificate `json:"certificate"` +} + +// CertificateCreateRequest defines the schema of the request to create a certificate. +type CertificateCreateRequest struct { + Name string `json:"name"` + Type string `json:"type"` + DomainNames []string `json:"domain_names,omitempty"` + Certificate string `json:"certificate,omitempty"` + PrivateKey string `json:"private_key,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// CertificateCreateResponse defines the schema of the response when creating a certificate. +type CertificateCreateResponse struct { + Certificate Certificate `json:"certificate"` + Action *Action `json:"action"` +} + +// CertificateUpdateRequest defines the schema of the request to update a certificate. +type CertificateUpdateRequest struct { + Name *string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// CertificateUpdateResponse defines the schema of the response when updating a certificate. +type CertificateUpdateResponse struct { + Certificate Certificate `json:"certificate"` +} + +// CertificateIssuanceRetryResponse defines the schema for the response of the +// retry issuance endpoint. +type CertificateIssuanceRetryResponse struct { + Action Action `json:"action"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/datacenter.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/datacenter.go new file mode 100644 index 000000000..54590d2a2 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/datacenter.go @@ -0,0 +1,27 @@ +package schema + +// Datacenter defines the schema of a datacenter. +type Datacenter struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Location Location `json:"location"` + ServerTypes DatacenterServerTypes `json:"server_types"` +} + +// DatacenterServerTypes defines the schema of the server types available in a datacenter. +type DatacenterServerTypes struct { + Supported []int64 `json:"supported"` + AvailableForMigration []int64 `json:"available_for_migration"` + Available []int64 `json:"available"` +} + +// DatacenterGetResponse defines the schema of the response when retrieving a single datacenter. +type DatacenterGetResponse struct { + Datacenter Datacenter `json:"datacenter"` +} + +// DatacenterListResponse defines the schema of the response when listing datacenters. +type DatacenterListResponse struct { + Datacenters []Datacenter `json:"datacenters"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/deprecation.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/deprecation.go new file mode 100644 index 000000000..87292f78b --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/deprecation.go @@ -0,0 +1,12 @@ +package schema + +import "time" + +type DeprecationInfo struct { + Announced time.Time `json:"announced"` + UnavailableAfter time.Time `json:"unavailable_after"` +} + +type DeprecatableResource struct { + Deprecation *DeprecationInfo `json:"deprecation"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/error.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/error.go similarity index 100% rename from vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/error.go rename to vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/error.go diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/firewall.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/firewall.go new file mode 100644 index 000000000..371e648f1 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/firewall.go @@ -0,0 +1,105 @@ +package schema + +import "time" + +// Firewall defines the schema of a Firewall. +type Firewall struct { + ID int64 `json:"id"` + Name string `json:"name"` + Labels map[string]string `json:"labels"` + Created time.Time `json:"created"` + Rules []FirewallRule `json:"rules"` + AppliedTo []FirewallResource `json:"applied_to"` +} + +// FirewallRule defines the schema of a Firewall rule. +type FirewallRule struct { + Direction string `json:"direction"` + SourceIPs []string `json:"source_ips,omitempty"` + DestinationIPs []string `json:"destination_ips,omitempty"` + Protocol string `json:"protocol"` + Port *string `json:"port,omitempty"` + Description *string `json:"description,omitempty"` +} + +// FirewallListResponse defines the schema of the response when listing Firewalls. +type FirewallListResponse struct { + Firewalls []Firewall `json:"firewalls"` +} + +// FirewallGetResponse defines the schema of the response when retrieving a single Firewall. +type FirewallGetResponse struct { + Firewall Firewall `json:"firewall"` +} + +// FirewallCreateRequest defines the schema of the request to create a Firewall. +type FirewallCreateRequest struct { + Name string `json:"name"` + Labels *map[string]string `json:"labels,omitempty"` + Rules []FirewallRule `json:"rules,omitempty"` + ApplyTo []FirewallResource `json:"apply_to,omitempty"` +} + +// FirewallResource defines the schema of a resource to apply the new Firewall on. +type FirewallResource struct { + Type string `json:"type"` + Server *FirewallResourceServer `json:"server,omitempty"` + LabelSelector *FirewallResourceLabelSelector `json:"label_selector,omitempty"` +} + +// FirewallResourceLabelSelector defines the schema of a LabelSelector to apply a Firewall on. +type FirewallResourceLabelSelector struct { + Selector string `json:"selector"` +} + +// FirewallResourceServer defines the schema of a Server to apply a Firewall on. +type FirewallResourceServer struct { + ID int64 `json:"id"` +} + +// FirewallCreateResponse defines the schema of the response when creating a Firewall. +type FirewallCreateResponse struct { + Firewall Firewall `json:"firewall"` + Actions []Action `json:"actions"` +} + +// FirewallUpdateRequest defines the schema of the request to update a Firewall. +type FirewallUpdateRequest struct { + Name *string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// FirewallUpdateResponse defines the schema of the response when updating a Firewall. +type FirewallUpdateResponse struct { + Firewall Firewall `json:"firewall"` +} + +// FirewallActionSetRulesRequest defines the schema of the request when setting Firewall rules. +type FirewallActionSetRulesRequest struct { + Rules []FirewallRule `json:"rules"` +} + +// FirewallActionSetRulesResponse defines the schema of the response when setting Firewall rules. +type FirewallActionSetRulesResponse struct { + Actions []Action `json:"actions"` +} + +// FirewallActionApplyToResourcesRequest defines the schema of the request when applying a Firewall on resources. +type FirewallActionApplyToResourcesRequest struct { + ApplyTo []FirewallResource `json:"apply_to"` +} + +// FirewallActionApplyToResourcesResponse defines the schema of the response when applying a Firewall on resources. +type FirewallActionApplyToResourcesResponse struct { + Actions []Action `json:"actions"` +} + +// FirewallActionRemoveFromResourcesRequest defines the schema of the request when removing a Firewall from resources. +type FirewallActionRemoveFromResourcesRequest struct { + RemoveFrom []FirewallResource `json:"remove_from"` +} + +// FirewallActionRemoveFromResourcesResponse defines the schema of the response when removing a Firewall from resources. +type FirewallActionRemoveFromResourcesResponse struct { + Actions []Action `json:"actions"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/floating_ip.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/floating_ip.go new file mode 100644 index 000000000..6256b0d96 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/floating_ip.go @@ -0,0 +1,118 @@ +package schema + +import "time" + +// FloatingIP defines the schema of a Floating IP. +type FloatingIP struct { + ID int64 `json:"id"` + Description *string `json:"description"` + Created time.Time `json:"created"` + IP string `json:"ip"` + Type string `json:"type"` + Server *int64 `json:"server"` + DNSPtr []FloatingIPDNSPtr `json:"dns_ptr"` + HomeLocation Location `json:"home_location"` + Blocked bool `json:"blocked"` + Protection FloatingIPProtection `json:"protection"` + Labels map[string]string `json:"labels"` + Name string `json:"name"` +} + +// FloatingIPProtection represents the protection level of a Floating IP. +type FloatingIPProtection struct { + Delete bool `json:"delete"` +} + +// FloatingIPDNSPtr contains reverse DNS information for a +// IPv4 or IPv6 Floating IP. +type FloatingIPDNSPtr struct { + IP string `json:"ip"` + DNSPtr string `json:"dns_ptr"` +} + +// FloatingIPGetResponse defines the schema of the response when +// retrieving a single Floating IP. +type FloatingIPGetResponse struct { + FloatingIP FloatingIP `json:"floating_ip"` +} + +// FloatingIPUpdateRequest defines the schema of the request to update a Floating IP. +type FloatingIPUpdateRequest struct { + Description string `json:"description,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + Name string `json:"name,omitempty"` +} + +// FloatingIPUpdateResponse defines the schema of the response when updating a Floating IP. +type FloatingIPUpdateResponse struct { + FloatingIP FloatingIP `json:"floating_ip"` +} + +// FloatingIPListResponse defines the schema of the response when +// listing Floating IPs. +type FloatingIPListResponse struct { + FloatingIPs []FloatingIP `json:"floating_ips"` +} + +// FloatingIPCreateRequest defines the schema of the request to +// create a Floating IP. +type FloatingIPCreateRequest struct { + Type string `json:"type"` + HomeLocation *string `json:"home_location,omitempty"` + Server *int64 `json:"server,omitempty"` + Description *string `json:"description,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + Name *string `json:"name,omitempty"` +} + +// FloatingIPCreateResponse defines the schema of the response +// when creating a Floating IP. +type FloatingIPCreateResponse struct { + FloatingIP FloatingIP `json:"floating_ip"` + Action *Action `json:"action"` +} + +// FloatingIPActionAssignRequest defines the schema of the request to +// create an assign Floating IP action. +type FloatingIPActionAssignRequest struct { + Server int64 `json:"server"` +} + +// FloatingIPActionAssignResponse defines the schema of the response when +// creating an assign action. +type FloatingIPActionAssignResponse struct { + Action Action `json:"action"` +} + +// FloatingIPActionUnassignRequest defines the schema of the request to +// create an unassign Floating IP action. +type FloatingIPActionUnassignRequest struct{} + +// FloatingIPActionUnassignResponse defines the schema of the response when +// creating an unassign action. +type FloatingIPActionUnassignResponse struct { + Action Action `json:"action"` +} + +// FloatingIPActionChangeDNSPtrRequest defines the schema for the request to +// change a Floating IP's reverse DNS pointer. +type FloatingIPActionChangeDNSPtrRequest struct { + IP string `json:"ip"` + DNSPtr *string `json:"dns_ptr"` +} + +// FloatingIPActionChangeDNSPtrResponse defines the schema of the response when +// creating a change_dns_ptr Floating IP action. +type FloatingIPActionChangeDNSPtrResponse struct { + Action Action `json:"action"` +} + +// FloatingIPActionChangeProtectionRequest defines the schema of the request to change the resource protection of a Floating IP. +type FloatingIPActionChangeProtectionRequest struct { + Delete *bool `json:"delete,omitempty"` +} + +// FloatingIPActionChangeProtectionResponse defines the schema of the response when changing the resource protection of a Floating IP. +type FloatingIPActionChangeProtectionResponse struct { + Action Action `json:"action"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/image.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/image.go new file mode 100644 index 000000000..eacc20f89 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/image.go @@ -0,0 +1,70 @@ +package schema + +import "time" + +// Image defines the schema of an image. +type Image struct { + ID int64 `json:"id"` + Status string `json:"status"` + Type string `json:"type"` + Name *string `json:"name"` + Description string `json:"description"` + ImageSize *float32 `json:"image_size"` + DiskSize float32 `json:"disk_size"` + Created *time.Time `json:"created"` + CreatedFrom *ImageCreatedFrom `json:"created_from"` + BoundTo *int64 `json:"bound_to"` + OSFlavor string `json:"os_flavor"` + OSVersion *string `json:"os_version"` + Architecture string `json:"architecture"` + RapidDeploy bool `json:"rapid_deploy"` + Protection ImageProtection `json:"protection"` + Deprecated *time.Time `json:"deprecated"` + Deleted *time.Time `json:"deleted"` + Labels map[string]string `json:"labels"` +} + +// ImageProtection represents the protection level of a image. +type ImageProtection struct { + Delete bool `json:"delete"` +} + +// ImageCreatedFrom defines the schema of the images created from reference. +type ImageCreatedFrom struct { + ID int64 `json:"id"` + Name string `json:"name"` +} + +// ImageGetResponse defines the schema of the response when +// retrieving a single image. +type ImageGetResponse struct { + Image Image `json:"image"` +} + +// ImageListResponse defines the schema of the response when +// listing images. +type ImageListResponse struct { + Images []Image `json:"images"` +} + +// ImageUpdateRequest defines the schema of the request to update an image. +type ImageUpdateRequest struct { + Description *string `json:"description,omitempty"` + Type *string `json:"type,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// ImageUpdateResponse defines the schema of the response when updating an image. +type ImageUpdateResponse struct { + Image Image `json:"image"` +} + +// ImageActionChangeProtectionRequest defines the schema of the request to change the resource protection of an image. +type ImageActionChangeProtectionRequest struct { + Delete *bool `json:"delete,omitempty"` +} + +// ImageActionChangeProtectionResponse defines the schema of the response when changing the resource protection of an image. +type ImageActionChangeProtectionResponse struct { + Action Action `json:"action"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/iso.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/iso.go new file mode 100644 index 000000000..4cf48cc1a --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/iso.go @@ -0,0 +1,21 @@ +package schema + +// ISO defines the schema of an ISO image. +type ISO struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Type string `json:"type"` + Architecture *string `json:"architecture"` + DeprecatableResource +} + +// ISOGetResponse defines the schema of the response when retrieving a single ISO. +type ISOGetResponse struct { + ISO ISO `json:"iso"` +} + +// ISOListResponse defines the schema of the response when listing ISOs. +type ISOListResponse struct { + ISOs []ISO `json:"isos"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/load_balancer.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/load_balancer.go new file mode 100644 index 000000000..7e1c4f5da --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/load_balancer.go @@ -0,0 +1,418 @@ +package schema + +import "time" + +type LoadBalancer struct { + ID int64 `json:"id"` + Name string `json:"name"` + PublicNet LoadBalancerPublicNet `json:"public_net"` + PrivateNet []LoadBalancerPrivateNet `json:"private_net"` + Location Location `json:"location"` + LoadBalancerType LoadBalancerType `json:"load_balancer_type"` + Protection LoadBalancerProtection `json:"protection"` + Labels map[string]string `json:"labels"` + Created time.Time `json:"created"` + Services []LoadBalancerService `json:"services"` + Targets []LoadBalancerTarget `json:"targets"` + Algorithm LoadBalancerAlgorithm `json:"algorithm"` + IncludedTraffic uint64 `json:"included_traffic"` + OutgoingTraffic *uint64 `json:"outgoing_traffic"` + IngoingTraffic *uint64 `json:"ingoing_traffic"` +} + +type LoadBalancerPublicNet struct { + Enabled bool `json:"enabled"` + IPv4 LoadBalancerPublicNetIPv4 `json:"ipv4"` + IPv6 LoadBalancerPublicNetIPv6 `json:"ipv6"` +} + +type LoadBalancerPublicNetIPv4 struct { + IP string `json:"ip"` + DNSPtr string `json:"dns_ptr"` +} + +type LoadBalancerPublicNetIPv6 struct { + IP string `json:"ip"` + DNSPtr string `json:"dns_ptr"` +} + +type LoadBalancerPrivateNet struct { + Network int64 `json:"network"` + IP string `json:"ip"` +} + +type LoadBalancerAlgorithm struct { + Type string `json:"type"` +} + +type LoadBalancerProtection struct { + Delete bool `json:"delete"` +} + +type LoadBalancerService struct { + Protocol string `json:"protocol"` + ListenPort int `json:"listen_port"` + DestinationPort int `json:"destination_port"` + Proxyprotocol bool `json:"proxyprotocol"` + HTTP *LoadBalancerServiceHTTP `json:"http"` + HealthCheck *LoadBalancerServiceHealthCheck `json:"health_check"` +} + +type LoadBalancerServiceHTTP struct { + CookieName string `json:"cookie_name"` + CookieLifetime int `json:"cookie_lifetime"` + Certificates []int64 `json:"certificates"` + RedirectHTTP bool `json:"redirect_http"` + StickySessions bool `json:"sticky_sessions"` +} + +type LoadBalancerServiceHealthCheck struct { + Protocol string `json:"protocol"` + Port int `json:"port"` + Interval int `json:"interval"` + Timeout int `json:"timeout"` + Retries int `json:"retries"` + HTTP *LoadBalancerServiceHealthCheckHTTP `json:"http"` +} + +type LoadBalancerServiceHealthCheckHTTP struct { + Domain string `json:"domain"` + Path string `json:"path"` + Response string `json:"response"` + StatusCodes []string `json:"status_codes"` + TLS bool `json:"tls"` +} + +type LoadBalancerTarget struct { + Type string `json:"type"` + Server *LoadBalancerTargetServer `json:"server"` + LabelSelector *LoadBalancerTargetLabelSelector `json:"label_selector"` + IP *LoadBalancerTargetIP `json:"ip"` + HealthStatus []LoadBalancerTargetHealthStatus `json:"health_status"` + UsePrivateIP bool `json:"use_private_ip"` + Targets []LoadBalancerTarget `json:"targets,omitempty"` +} + +type LoadBalancerTargetHealthStatus struct { + ListenPort int `json:"listen_port"` + Status string `json:"status"` +} + +type LoadBalancerTargetServer struct { + ID int64 `json:"id"` +} + +type LoadBalancerTargetLabelSelector struct { + Selector string `json:"selector"` +} + +type LoadBalancerTargetIP struct { + IP string `json:"ip"` +} + +type LoadBalancerListResponse struct { + LoadBalancers []LoadBalancer `json:"load_balancers"` +} + +type LoadBalancerGetResponse struct { + LoadBalancer LoadBalancer `json:"load_balancer"` +} + +type LoadBalancerActionAddTargetRequest struct { + Type string `json:"type"` + Server *LoadBalancerActionAddTargetRequestServer `json:"server,omitempty"` + LabelSelector *LoadBalancerActionAddTargetRequestLabelSelector `json:"label_selector,omitempty"` + IP *LoadBalancerActionAddTargetRequestIP `json:"ip,omitempty"` + UsePrivateIP *bool `json:"use_private_ip,omitempty"` +} + +type LoadBalancerActionAddTargetRequestServer struct { + ID int64 `json:"id"` +} + +type LoadBalancerActionAddTargetRequestLabelSelector struct { + Selector string `json:"selector"` +} + +type LoadBalancerActionAddTargetRequestIP struct { + IP string `json:"ip"` +} + +type LoadBalancerActionAddTargetResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionRemoveTargetRequest struct { + Type string `json:"type"` + Server *LoadBalancerActionRemoveTargetRequestServer `json:"server,omitempty"` + LabelSelector *LoadBalancerActionRemoveTargetRequestLabelSelector `json:"label_selector,omitempty"` + IP *LoadBalancerActionRemoveTargetRequestIP `json:"ip,omitempty"` +} + +type LoadBalancerActionRemoveTargetRequestServer struct { + ID int64 `json:"id"` +} + +type LoadBalancerActionRemoveTargetRequestLabelSelector struct { + Selector string `json:"selector"` +} + +type LoadBalancerActionRemoveTargetRequestIP struct { + IP string `json:"ip"` +} + +type LoadBalancerActionRemoveTargetResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionAddServiceRequest struct { + Protocol string `json:"protocol"` + ListenPort *int `json:"listen_port,omitempty"` + DestinationPort *int `json:"destination_port,omitempty"` + Proxyprotocol *bool `json:"proxyprotocol,omitempty"` + HTTP *LoadBalancerActionAddServiceRequestHTTP `json:"http,omitempty"` + HealthCheck *LoadBalancerActionAddServiceRequestHealthCheck `json:"health_check,omitempty"` +} + +type LoadBalancerActionAddServiceRequestHTTP struct { + CookieName *string `json:"cookie_name,omitempty"` + CookieLifetime *int `json:"cookie_lifetime,omitempty"` + Certificates *[]int64 `json:"certificates,omitempty"` + RedirectHTTP *bool `json:"redirect_http,omitempty"` + StickySessions *bool `json:"sticky_sessions,omitempty"` +} + +type LoadBalancerActionAddServiceRequestHealthCheck struct { + Protocol string `json:"protocol"` + Port *int `json:"port,omitempty"` + Interval *int `json:"interval,omitempty"` + Timeout *int `json:"timeout,omitempty"` + Retries *int `json:"retries,omitempty"` + HTTP *LoadBalancerActionAddServiceRequestHealthCheckHTTP `json:"http,omitempty"` +} + +type LoadBalancerActionAddServiceRequestHealthCheckHTTP struct { + Domain *string `json:"domain,omitempty"` + Path *string `json:"path,omitempty"` + Response *string `json:"response,omitempty"` + StatusCodes *[]string `json:"status_codes,omitempty"` + TLS *bool `json:"tls,omitempty"` +} + +type LoadBalancerActionAddServiceResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionUpdateServiceRequest struct { + ListenPort int `json:"listen_port"` + Protocol *string `json:"protocol,omitempty"` + DestinationPort *int `json:"destination_port,omitempty"` + Proxyprotocol *bool `json:"proxyprotocol,omitempty"` + HTTP *LoadBalancerActionUpdateServiceRequestHTTP `json:"http,omitempty"` + HealthCheck *LoadBalancerActionUpdateServiceRequestHealthCheck `json:"health_check,omitempty"` +} + +type LoadBalancerActionUpdateServiceRequestHTTP struct { + CookieName *string `json:"cookie_name,omitempty"` + CookieLifetime *int `json:"cookie_lifetime,omitempty"` + Certificates *[]int64 `json:"certificates,omitempty"` + RedirectHTTP *bool `json:"redirect_http,omitempty"` + StickySessions *bool `json:"sticky_sessions,omitempty"` +} + +type LoadBalancerActionUpdateServiceRequestHealthCheck struct { + Protocol *string `json:"protocol,omitempty"` + Port *int `json:"port,omitempty"` + Interval *int `json:"interval,omitempty"` + Timeout *int `json:"timeout,omitempty"` + Retries *int `json:"retries,omitempty"` + HTTP *LoadBalancerActionUpdateServiceRequestHealthCheckHTTP `json:"http,omitempty"` +} + +type LoadBalancerActionUpdateServiceRequestHealthCheckHTTP struct { + Domain *string `json:"domain,omitempty"` + Path *string `json:"path,omitempty"` + Response *string `json:"response,omitempty"` + StatusCodes *[]string `json:"status_codes,omitempty"` + TLS *bool `json:"tls,omitempty"` +} + +type LoadBalancerActionUpdateServiceResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerDeleteServiceRequest struct { + ListenPort int `json:"listen_port"` +} + +type LoadBalancerDeleteServiceResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerCreateRequest struct { + Name string `json:"name"` + LoadBalancerType interface{} `json:"load_balancer_type"` // int or string + Algorithm *LoadBalancerCreateRequestAlgorithm `json:"algorithm,omitempty"` + Location *string `json:"location,omitempty"` + NetworkZone *string `json:"network_zone,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + Targets []LoadBalancerCreateRequestTarget `json:"targets,omitempty"` + Services []LoadBalancerCreateRequestService `json:"services,omitempty"` + PublicInterface *bool `json:"public_interface,omitempty"` + Network *int64 `json:"network,omitempty"` +} + +type LoadBalancerCreateRequestAlgorithm struct { + Type string `json:"type"` +} + +type LoadBalancerCreateRequestTarget struct { + Type string `json:"type"` + Server *LoadBalancerCreateRequestTargetServer `json:"server,omitempty"` + LabelSelector *LoadBalancerCreateRequestTargetLabelSelector `json:"label_selector,omitempty"` + IP *LoadBalancerCreateRequestTargetIP `json:"ip,omitempty"` + UsePrivateIP *bool `json:"use_private_ip,omitempty"` +} + +type LoadBalancerCreateRequestTargetServer struct { + ID int64 `json:"id"` +} + +type LoadBalancerCreateRequestTargetLabelSelector struct { + Selector string `json:"selector"` +} + +type LoadBalancerCreateRequestTargetIP struct { + IP string `json:"ip"` +} + +type LoadBalancerCreateRequestService struct { + Protocol string `json:"protocol"` + ListenPort *int `json:"listen_port,omitempty"` + DestinationPort *int `json:"destination_port,omitempty"` + Proxyprotocol *bool `json:"proxyprotocol,omitempty"` + HTTP *LoadBalancerCreateRequestServiceHTTP `json:"http,omitempty"` + HealthCheck *LoadBalancerCreateRequestServiceHealthCheck `json:"health_check,omitempty"` +} + +type LoadBalancerCreateRequestServiceHTTP struct { + CookieName *string `json:"cookie_name,omitempty"` + CookieLifetime *int `json:"cookie_lifetime,omitempty"` + Certificates *[]int64 `json:"certificates,omitempty"` + RedirectHTTP *bool `json:"redirect_http,omitempty"` + StickySessions *bool `json:"sticky_sessions,omitempty"` +} + +type LoadBalancerCreateRequestServiceHealthCheck struct { + Protocol string `json:"protocol"` + Port *int `json:"port,omitempty"` + Interval *int `json:"interval,omitempty"` + Timeout *int `json:"timeout,omitempty"` + Retries *int `json:"retries,omitempty"` + HTTP *LoadBalancerCreateRequestServiceHealthCheckHTTP `json:"http,omitempty"` +} + +type LoadBalancerCreateRequestServiceHealthCheckHTTP struct { + Domain *string `json:"domain,omitempty"` + Path *string `json:"path,omitempty"` + Response *string `json:"response,omitempty"` + StatusCodes *[]string `json:"status_codes,omitempty"` + TLS *bool `json:"tls,omitempty"` +} + +type LoadBalancerCreateResponse struct { + LoadBalancer LoadBalancer `json:"load_balancer"` + Action Action `json:"action"` +} + +type LoadBalancerActionChangeProtectionRequest struct { + Delete *bool `json:"delete,omitempty"` +} + +type LoadBalancerActionChangeProtectionResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerUpdateRequest struct { + Name *string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +type LoadBalancerUpdateResponse struct { + LoadBalancer LoadBalancer `json:"load_balancer"` +} + +type LoadBalancerActionChangeAlgorithmRequest struct { + Type string `json:"type"` +} + +type LoadBalancerActionChangeAlgorithmResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionAttachToNetworkRequest struct { + Network int64 `json:"network"` + IP *string `json:"ip,omitempty"` +} + +type LoadBalancerActionAttachToNetworkResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionDetachFromNetworkRequest struct { + Network int64 `json:"network"` +} + +type LoadBalancerActionDetachFromNetworkResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionEnablePublicInterfaceRequest struct{} + +type LoadBalancerActionEnablePublicInterfaceResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionDisablePublicInterfaceRequest struct{} + +type LoadBalancerActionDisablePublicInterfaceResponse struct { + Action Action `json:"action"` +} + +type LoadBalancerActionChangeTypeRequest struct { + LoadBalancerType interface{} `json:"load_balancer_type"` // int or string +} + +type LoadBalancerActionChangeTypeResponse struct { + Action Action `json:"action"` +} + +// LoadBalancerGetMetricsResponse defines the schema of the response when +// requesting metrics for a Load Balancer. +type LoadBalancerGetMetricsResponse struct { + Metrics struct { + Start time.Time `json:"start"` + End time.Time `json:"end"` + Step float64 `json:"step"` + TimeSeries map[string]LoadBalancerTimeSeriesVals `json:"time_series"` + } `json:"metrics"` +} + +// LoadBalancerTimeSeriesVals contains the values for a Load Balancer time +// series. +type LoadBalancerTimeSeriesVals struct { + Values []interface{} `json:"values"` +} + +// LoadBalancerActionChangeDNSPtrRequest defines the schema for the request to +// change a Load Balancer reverse DNS pointer. +type LoadBalancerActionChangeDNSPtrRequest struct { + IP string `json:"ip"` + DNSPtr *string `json:"dns_ptr"` +} + +// LoadBalancerActionChangeDNSPtrResponse defines the schema of the response when +// creating a change_dns_ptr Floating IP action. +type LoadBalancerActionChangeDNSPtrResponse struct { + Action Action `json:"action"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/load_balancer_type.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/load_balancer_type.go new file mode 100644 index 000000000..b0193d3a8 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/load_balancer_type.go @@ -0,0 +1,26 @@ +package schema + +// LoadBalancerType defines the schema of a LoadBalancer type. +type LoadBalancerType struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + MaxConnections int `json:"max_connections"` + MaxServices int `json:"max_services"` + MaxTargets int `json:"max_targets"` + MaxAssignedCertificates int `json:"max_assigned_certificates"` + Prices []PricingLoadBalancerTypePrice `json:"prices"` + Deprecated *string `json:"deprecated"` +} + +// LoadBalancerTypeListResponse defines the schema of the response when +// listing LoadBalancer types. +type LoadBalancerTypeListResponse struct { + LoadBalancerTypes []LoadBalancerType `json:"load_balancer_types"` +} + +// LoadBalancerTypeGetResponse defines the schema of the response when +// retrieving a single LoadBalancer type. +type LoadBalancerTypeGetResponse struct { + LoadBalancerType LoadBalancerType `json:"load_balancer_type"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/location.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/location.go new file mode 100644 index 000000000..e07306071 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/location.go @@ -0,0 +1,23 @@ +package schema + +// Location defines the schema of a location. +type Location struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Country string `json:"country"` + City string `json:"city"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + NetworkZone string `json:"network_zone"` +} + +// LocationGetResponse defines the schema of the response when retrieving a single location. +type LocationGetResponse struct { + Location Location `json:"location"` +} + +// LocationListResponse defines the schema of the response when listing locations. +type LocationListResponse struct { + Locations []Location `json:"locations"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/meta.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/meta.go similarity index 100% rename from vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/meta.go rename to vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/meta.go diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/network.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/network.go new file mode 100644 index 000000000..2344aea45 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/network.go @@ -0,0 +1,155 @@ +package schema + +import "time" + +// Network defines the schema of a network. +type Network struct { + ID int64 `json:"id"` + Name string `json:"name"` + Created time.Time `json:"created"` + IPRange string `json:"ip_range"` + Subnets []NetworkSubnet `json:"subnets"` + Routes []NetworkRoute `json:"routes"` + Servers []int64 `json:"servers"` + Protection NetworkProtection `json:"protection"` + Labels map[string]string `json:"labels"` + ExposeRoutesToVSwitch bool `json:"expose_routes_to_vswitch"` +} + +// NetworkSubnet represents a subnet of a network. +type NetworkSubnet struct { + Type string `json:"type"` + IPRange string `json:"ip_range"` + NetworkZone string `json:"network_zone"` + Gateway string `json:"gateway,omitempty"` + VSwitchID int64 `json:"vswitch_id,omitempty"` +} + +// NetworkRoute represents a route of a network. +type NetworkRoute struct { + Destination string `json:"destination"` + Gateway string `json:"gateway"` +} + +// NetworkProtection represents the protection level of a network. +type NetworkProtection struct { + Delete bool `json:"delete"` +} + +// NetworkUpdateRequest defines the schema of the request to update a network. +type NetworkUpdateRequest struct { + Name string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + ExposeRoutesToVSwitch *bool `json:"expose_routes_to_vswitch,omitempty"` +} + +// NetworkUpdateResponse defines the schema of the response when updating a network. +type NetworkUpdateResponse struct { + Network Network `json:"network"` +} + +// NetworkListResponse defines the schema of the response when +// listing networks. +type NetworkListResponse struct { + Networks []Network `json:"networks"` +} + +// NetworkGetResponse defines the schema of the response when +// retrieving a single network. +type NetworkGetResponse struct { + Network Network `json:"network"` +} + +// NetworkCreateRequest defines the schema of the request to create a network. +type NetworkCreateRequest struct { + Name string `json:"name"` + IPRange string `json:"ip_range"` + Subnets []NetworkSubnet `json:"subnets,omitempty"` + Routes []NetworkRoute `json:"routes,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + ExposeRoutesToVSwitch bool `json:"expose_routes_to_vswitch"` +} + +// NetworkCreateResponse defines the schema of the response when +// creating a network. +type NetworkCreateResponse struct { + Network Network `json:"network"` +} + +// NetworkActionChangeIPRangeRequest defines the schema of the request to +// change the IP range of a network. +type NetworkActionChangeIPRangeRequest struct { + IPRange string `json:"ip_range"` +} + +// NetworkActionChangeIPRangeResponse defines the schema of the response when +// changing the IP range of a network. +type NetworkActionChangeIPRangeResponse struct { + Action Action `json:"action"` +} + +// NetworkActionAddSubnetRequest defines the schema of the request to +// add a subnet to a network. +type NetworkActionAddSubnetRequest struct { + Type string `json:"type"` + IPRange string `json:"ip_range,omitempty"` + NetworkZone string `json:"network_zone"` + Gateway string `json:"gateway"` + VSwitchID int64 `json:"vswitch_id,omitempty"` +} + +// NetworkActionAddSubnetResponse defines the schema of the response when +// adding a subnet to a network. +type NetworkActionAddSubnetResponse struct { + Action Action `json:"action"` +} + +// NetworkActionDeleteSubnetRequest defines the schema of the request to +// delete a subnet from a network. +type NetworkActionDeleteSubnetRequest struct { + IPRange string `json:"ip_range"` +} + +// NetworkActionDeleteSubnetResponse defines the schema of the response when +// deleting a subnet from a network. +type NetworkActionDeleteSubnetResponse struct { + Action Action `json:"action"` +} + +// NetworkActionAddRouteRequest defines the schema of the request to +// add a route to a network. +type NetworkActionAddRouteRequest struct { + Destination string `json:"destination"` + Gateway string `json:"gateway"` +} + +// NetworkActionAddRouteResponse defines the schema of the response when +// adding a route to a network. +type NetworkActionAddRouteResponse struct { + Action Action `json:"action"` +} + +// NetworkActionDeleteRouteRequest defines the schema of the request to +// delete a route from a network. +type NetworkActionDeleteRouteRequest struct { + Destination string `json:"destination"` + Gateway string `json:"gateway"` +} + +// NetworkActionDeleteRouteResponse defines the schema of the response when +// deleting a route from a network. +type NetworkActionDeleteRouteResponse struct { + Action Action `json:"action"` +} + +// NetworkActionChangeProtectionRequest defines the schema of the request to +// change the resource protection of a network. +type NetworkActionChangeProtectionRequest struct { + Delete *bool `json:"delete,omitempty"` +} + +// NetworkActionChangeProtectionResponse defines the schema of the response when +// changing the resource protection of a network. +type NetworkActionChangeProtectionResponse struct { + Action Action `json:"action"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/placement_group.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/placement_group.go new file mode 100644 index 000000000..671bd6bed --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/placement_group.go @@ -0,0 +1,40 @@ +package schema + +import "time" + +type PlacementGroup struct { + ID int64 `json:"id"` + Name string `json:"name"` + Labels map[string]string `json:"labels"` + Created time.Time `json:"created"` + Servers []int64 `json:"servers"` + Type string `json:"type"` +} + +type PlacementGroupListResponse struct { + PlacementGroups []PlacementGroup `json:"placement_groups"` +} + +type PlacementGroupGetResponse struct { + PlacementGroup PlacementGroup `json:"placement_group"` +} + +type PlacementGroupCreateRequest struct { + Name string `json:"name"` + Labels *map[string]string `json:"labels,omitempty"` + Type string `json:"type"` +} + +type PlacementGroupCreateResponse struct { + PlacementGroup PlacementGroup `json:"placement_group"` + Action *Action `json:"action"` +} + +type PlacementGroupUpdateRequest struct { + Name *string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +type PlacementGroupUpdateResponse struct { + PlacementGroup PlacementGroup `json:"placement_group"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/pricing.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/pricing.go new file mode 100644 index 000000000..192352f5d --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/pricing.go @@ -0,0 +1,110 @@ +package schema + +// Pricing defines the schema for pricing information. +type Pricing struct { + Currency string `json:"currency"` + VATRate string `json:"vat_rate"` + Image PricingImage `json:"image"` + FloatingIP PricingFloatingIP `json:"floating_ip"` + FloatingIPs []PricingFloatingIPType `json:"floating_ips"` + PrimaryIPs []PricingPrimaryIP `json:"primary_ips"` + Traffic PricingTraffic `json:"traffic"` + ServerBackup PricingServerBackup `json:"server_backup"` + ServerTypes []PricingServerType `json:"server_types"` + LoadBalancerTypes []PricingLoadBalancerType `json:"load_balancer_types"` + Volume PricingVolume `json:"volume"` +} + +// Price defines the schema of a single price with net and gross amount. +type Price struct { + Net string `json:"net"` + Gross string `json:"gross"` +} + +// PricingImage defines the schema of pricing information for an image. +type PricingImage struct { + PricePerGBMonth Price `json:"price_per_gb_month"` +} + +// PricingFloatingIP defines the schema of pricing information for a Floating IP. +type PricingFloatingIP struct { + PriceMonthly Price `json:"price_monthly"` +} + +// PricingFloatingIPType defines the schema of pricing information for a Floating IP per type. +type PricingFloatingIPType struct { + Type string `json:"type"` + Prices []PricingFloatingIPTypePrice `json:"prices"` +} + +// PricingFloatingIPTypePrice defines the schema of pricing information for a Floating IP +// type at a location. +type PricingFloatingIPTypePrice struct { + Location string `json:"location"` + PriceMonthly Price `json:"price_monthly"` +} + +// PricingTraffic defines the schema of pricing information for traffic. +type PricingTraffic struct { + PricePerTB Price `json:"price_per_tb"` +} + +// PricingVolume defines the schema of pricing information for a Volume. +type PricingVolume struct { + PricePerGBPerMonth Price `json:"price_per_gb_month"` +} + +// PricingServerBackup defines the schema of pricing information for server backups. +type PricingServerBackup struct { + Percentage string `json:"percentage"` +} + +// PricingServerType defines the schema of pricing information for a server type. +type PricingServerType struct { + ID int64 `json:"id"` + Name string `json:"name"` + Prices []PricingServerTypePrice `json:"prices"` +} + +// PricingServerTypePrice defines the schema of pricing information for a server +// type at a location. +type PricingServerTypePrice struct { + Location string `json:"location"` + PriceHourly Price `json:"price_hourly"` + PriceMonthly Price `json:"price_monthly"` +} + +// PricingLoadBalancerType defines the schema of pricing information for a Load Balancer type. +type PricingLoadBalancerType struct { + ID int64 `json:"id"` + Name string `json:"name"` + Prices []PricingLoadBalancerTypePrice `json:"prices"` +} + +// PricingLoadBalancerTypePrice defines the schema of pricing information for a Load Balancer +// type at a location. +type PricingLoadBalancerTypePrice struct { + Location string `json:"location"` + PriceHourly Price `json:"price_hourly"` + PriceMonthly Price `json:"price_monthly"` +} + +// PricingGetResponse defines the schema of the response when retrieving pricing information. +type PricingGetResponse struct { + Pricing Pricing `json:"pricing"` +} + +// PricingPrimaryIPTypePrice defines the schema of pricing information for a primary IP. +// type at a datacenter. +type PricingPrimaryIPTypePrice struct { + Datacenter string `json:"datacenter"` // Deprecated: the API does not return pricing for the individual DCs anymore + Location string `json:"location"` + PriceHourly Price `json:"price_hourly"` + PriceMonthly Price `json:"price_monthly"` +} + +// PricingPrimaryIP define the schema of pricing information for a primary IP at a datacenter. +type PricingPrimaryIP struct { + Type string `json:"type"` + Prices []PricingPrimaryIPTypePrice `json:"prices"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/primary_ip.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/primary_ip.go new file mode 100644 index 000000000..b685c386f --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/primary_ip.go @@ -0,0 +1,62 @@ +package schema + +import "time" + +// PrimaryIP defines a Primary IP. +type PrimaryIP struct { + ID int64 `json:"id"` + IP string `json:"ip"` + Labels map[string]string `json:"labels"` + Name string `json:"name"` + Type string `json:"type"` + Protection PrimaryIPProtection `json:"protection"` + DNSPtr []PrimaryIPDNSPTR `json:"dns_ptr"` + AssigneeID int64 `json:"assignee_id"` + AssigneeType string `json:"assignee_type"` + AutoDelete bool `json:"auto_delete"` + Blocked bool `json:"blocked"` + Created time.Time `json:"created"` + Datacenter Datacenter `json:"datacenter"` +} + +// PrimaryIPProtection represents the protection level of a Primary IP. +type PrimaryIPProtection struct { + Delete bool `json:"delete"` +} + +// PrimaryIPDNSPTR contains reverse DNS information for a +// IPv4 or IPv6 Primary IP. +type PrimaryIPDNSPTR struct { + DNSPtr string `json:"dns_ptr"` + IP string `json:"ip"` +} + +// PrimaryIPCreateResponse defines the schema of the response +// when creating a Primary IP. +type PrimaryIPCreateResponse struct { + PrimaryIP PrimaryIP `json:"primary_ip"` + Action *Action `json:"action"` +} + +// PrimaryIPGetResult defines the response when retrieving a single Primary IP. +type PrimaryIPGetResult struct { + PrimaryIP PrimaryIP `json:"primary_ip"` +} + +// PrimaryIPListResult defines the response when listing Primary IPs. +type PrimaryIPListResult struct { + PrimaryIPs []PrimaryIP `json:"primary_ips"` +} + +// PrimaryIPUpdateResult defines the response +// when updating a Primary IP. +type PrimaryIPUpdateResult struct { + PrimaryIP PrimaryIP `json:"primary_ip"` +} + +// PrimaryIPActionChangeDNSPtrRequest defines the schema for the request to +// change a Primary IP's reverse DNS pointer. +type PrimaryIPActionChangeDNSPtrRequest struct { + IP string `json:"ip"` + DNSPtr *string `json:"dns_ptr"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/server.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/server.go new file mode 100644 index 000000000..068b3e81f --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/server.go @@ -0,0 +1,436 @@ +package schema + +import "time" + +// Server defines the schema of a server. +type Server struct { + ID int64 `json:"id"` + Name string `json:"name"` + Status string `json:"status"` + Created time.Time `json:"created"` + PublicNet ServerPublicNet `json:"public_net"` + PrivateNet []ServerPrivateNet `json:"private_net"` + ServerType ServerType `json:"server_type"` + IncludedTraffic uint64 `json:"included_traffic"` + OutgoingTraffic *uint64 `json:"outgoing_traffic"` + IngoingTraffic *uint64 `json:"ingoing_traffic"` + BackupWindow *string `json:"backup_window"` + RescueEnabled bool `json:"rescue_enabled"` + ISO *ISO `json:"iso"` + Locked bool `json:"locked"` + Datacenter Datacenter `json:"datacenter"` + Image *Image `json:"image"` + Protection ServerProtection `json:"protection"` + Labels map[string]string `json:"labels"` + Volumes []int64 `json:"volumes"` + PrimaryDiskSize int `json:"primary_disk_size"` + PlacementGroup *PlacementGroup `json:"placement_group"` + LoadBalancers []int64 `json:"load_balancers"` +} + +// ServerProtection defines the schema of a server's resource protection. +type ServerProtection struct { + Delete bool `json:"delete"` + Rebuild bool `json:"rebuild"` +} + +// ServerPublicNet defines the schema of a server's +// public network information. +type ServerPublicNet struct { + IPv4 ServerPublicNetIPv4 `json:"ipv4"` + IPv6 ServerPublicNetIPv6 `json:"ipv6"` + FloatingIPs []int64 `json:"floating_ips"` + Firewalls []ServerFirewall `json:"firewalls"` +} + +// ServerPublicNetIPv4 defines the schema of a server's public +// network information for an IPv4. +type ServerPublicNetIPv4 struct { + ID int64 `json:"id"` + IP string `json:"ip"` + Blocked bool `json:"blocked"` + DNSPtr string `json:"dns_ptr"` +} + +// ServerPublicNetIPv6 defines the schema of a server's public +// network information for an IPv6. +type ServerPublicNetIPv6 struct { + ID int64 `json:"id"` + IP string `json:"ip"` + Blocked bool `json:"blocked"` + DNSPtr []ServerPublicNetIPv6DNSPtr `json:"dns_ptr"` +} + +// ServerPublicNetIPv6DNSPtr defines the schema of a server's +// public network information for an IPv6 reverse DNS. +type ServerPublicNetIPv6DNSPtr struct { + IP string `json:"ip"` + DNSPtr string `json:"dns_ptr"` +} + +// ServerFirewall defines the schema of a Server's Firewalls on +// a certain network interface. +type ServerFirewall struct { + ID int64 `json:"id"` + Status string `json:"status"` +} + +// ServerPrivateNet defines the schema of a server's private network information. +type ServerPrivateNet struct { + Network int64 `json:"network"` + IP string `json:"ip"` + AliasIPs []string `json:"alias_ips"` + MACAddress string `json:"mac_address"` +} + +// ServerGetResponse defines the schema of the response when +// retrieving a single server. +type ServerGetResponse struct { + Server Server `json:"server"` +} + +// ServerListResponse defines the schema of the response when +// listing servers. +type ServerListResponse struct { + Servers []Server `json:"servers"` +} + +// ServerCreateRequest defines the schema for the request to +// create a server. +type ServerCreateRequest struct { + Name string `json:"name"` + ServerType interface{} `json:"server_type"` // int or string + Image interface{} `json:"image"` // int or string + SSHKeys []int64 `json:"ssh_keys,omitempty"` + Location string `json:"location,omitempty"` + Datacenter string `json:"datacenter,omitempty"` + UserData string `json:"user_data,omitempty"` + StartAfterCreate *bool `json:"start_after_create,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + Automount *bool `json:"automount,omitempty"` + Volumes []int64 `json:"volumes,omitempty"` + Networks []int64 `json:"networks,omitempty"` + Firewalls []ServerCreateFirewalls `json:"firewalls,omitempty"` + PlacementGroup int64 `json:"placement_group,omitempty"` + PublicNet *ServerCreatePublicNet `json:"public_net,omitempty"` +} + +// ServerCreatePublicNet defines the public network configuration of a server. +type ServerCreatePublicNet struct { + EnableIPv4 bool `json:"enable_ipv4"` + EnableIPv6 bool `json:"enable_ipv6"` + IPv4ID int64 `json:"ipv4,omitempty"` + IPv6ID int64 `json:"ipv6,omitempty"` +} + +// ServerCreateFirewalls defines which Firewalls to apply when creating a Server. +type ServerCreateFirewalls struct { + Firewall int64 `json:"firewall"` +} + +// ServerCreateResponse defines the schema of the response when +// creating a server. +type ServerCreateResponse struct { + Server Server `json:"server"` + Action Action `json:"action"` + RootPassword *string `json:"root_password"` + NextActions []Action `json:"next_actions"` +} + +// ServerDeleteResponse defines the schema of the response when +// deleting a server. +type ServerDeleteResponse struct { + Action Action `json:"action"` +} + +// ServerUpdateRequest defines the schema of the request to update a server. +type ServerUpdateRequest struct { + Name string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// ServerUpdateResponse defines the schema of the response when updating a server. +type ServerUpdateResponse struct { + Server Server `json:"server"` +} + +// ServerActionPoweronRequest defines the schema for the request to +// create a poweron server action. +type ServerActionPoweronRequest struct{} + +// ServerActionPoweronResponse defines the schema of the response when +// creating a poweron server action. +type ServerActionPoweronResponse struct { + Action Action `json:"action"` +} + +// ServerActionPoweroffRequest defines the schema for the request to +// create a poweroff server action. +type ServerActionPoweroffRequest struct{} + +// ServerActionPoweroffResponse defines the schema of the response when +// creating a poweroff server action. +type ServerActionPoweroffResponse struct { + Action Action `json:"action"` +} + +// ServerActionRebootRequest defines the schema for the request to +// create a reboot server action. +type ServerActionRebootRequest struct{} + +// ServerActionRebootResponse defines the schema of the response when +// creating a reboot server action. +type ServerActionRebootResponse struct { + Action Action `json:"action"` +} + +// ServerActionResetRequest defines the schema for the request to +// create a reset server action. +type ServerActionResetRequest struct{} + +// ServerActionResetResponse defines the schema of the response when +// creating a reset server action. +type ServerActionResetResponse struct { + Action Action `json:"action"` +} + +// ServerActionShutdownRequest defines the schema for the request to +// create a shutdown server action. +type ServerActionShutdownRequest struct{} + +// ServerActionShutdownResponse defines the schema of the response when +// creating a shutdown server action. +type ServerActionShutdownResponse struct { + Action Action `json:"action"` +} + +// ServerActionResetPasswordRequest defines the schema for the request to +// create a reset_password server action. +type ServerActionResetPasswordRequest struct{} + +// ServerActionResetPasswordResponse defines the schema of the response when +// creating a reset_password server action. +type ServerActionResetPasswordResponse struct { + Action Action `json:"action"` + RootPassword string `json:"root_password"` +} + +// ServerActionCreateImageRequest defines the schema for the request to +// create a create_image server action. +type ServerActionCreateImageRequest struct { + Type *string `json:"type"` + Description *string `json:"description"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// ServerActionCreateImageResponse defines the schema of the response when +// creating a create_image server action. +type ServerActionCreateImageResponse struct { + Action Action `json:"action"` + Image Image `json:"image"` +} + +// ServerActionEnableRescueRequest defines the schema for the request to +// create a enable_rescue server action. +type ServerActionEnableRescueRequest struct { + Type *string `json:"type,omitempty"` + SSHKeys []int64 `json:"ssh_keys,omitempty"` +} + +// ServerActionEnableRescueResponse defines the schema of the response when +// creating a enable_rescue server action. +type ServerActionEnableRescueResponse struct { + Action Action `json:"action"` + RootPassword string `json:"root_password"` +} + +// ServerActionDisableRescueRequest defines the schema for the request to +// create a disable_rescue server action. +type ServerActionDisableRescueRequest struct{} + +// ServerActionDisableRescueResponse defines the schema of the response when +// creating a disable_rescue server action. +type ServerActionDisableRescueResponse struct { + Action Action `json:"action"` +} + +// ServerActionRebuildRequest defines the schema for the request to +// rebuild a server. +type ServerActionRebuildRequest struct { + Image interface{} `json:"image"` // int or string +} + +// ServerActionRebuildResponse defines the schema of the response when +// creating a rebuild server action. +type ServerActionRebuildResponse struct { + Action Action `json:"action"` + RootPassword *string `json:"root_password"` +} + +// ServerActionAttachISORequest defines the schema for the request to +// attach an ISO to a server. +type ServerActionAttachISORequest struct { + ISO interface{} `json:"iso"` // int or string +} + +// ServerActionAttachISOResponse defines the schema of the response when +// creating a attach_iso server action. +type ServerActionAttachISOResponse struct { + Action Action `json:"action"` +} + +// ServerActionDetachISORequest defines the schema for the request to +// detach an ISO from a server. +type ServerActionDetachISORequest struct{} + +// ServerActionDetachISOResponse defines the schema of the response when +// creating a detach_iso server action. +type ServerActionDetachISOResponse struct { + Action Action `json:"action"` +} + +// ServerActionEnableBackupRequest defines the schema for the request to +// enable backup for a server. +type ServerActionEnableBackupRequest struct { + BackupWindow *string `json:"backup_window,omitempty"` +} + +// ServerActionEnableBackupResponse defines the schema of the response when +// creating a enable_backup server action. +type ServerActionEnableBackupResponse struct { + Action Action `json:"action"` +} + +// ServerActionDisableBackupRequest defines the schema for the request to +// disable backup for a server. +type ServerActionDisableBackupRequest struct{} + +// ServerActionDisableBackupResponse defines the schema of the response when +// creating a disable_backup server action. +type ServerActionDisableBackupResponse struct { + Action Action `json:"action"` +} + +// ServerActionChangeTypeRequest defines the schema for the request to +// change a server's type. +type ServerActionChangeTypeRequest struct { + ServerType interface{} `json:"server_type"` // int or string + UpgradeDisk bool `json:"upgrade_disk"` +} + +// ServerActionChangeTypeResponse defines the schema of the response when +// creating a change_type server action. +type ServerActionChangeTypeResponse struct { + Action Action `json:"action"` +} + +// ServerActionChangeDNSPtrRequest defines the schema for the request to +// change a server's reverse DNS pointer. +type ServerActionChangeDNSPtrRequest struct { + IP string `json:"ip"` + DNSPtr *string `json:"dns_ptr"` +} + +// ServerActionChangeDNSPtrResponse defines the schema of the response when +// creating a change_dns_ptr server action. +type ServerActionChangeDNSPtrResponse struct { + Action Action `json:"action"` +} + +// ServerActionChangeProtectionRequest defines the schema of the request to +// change the resource protection of a server. +type ServerActionChangeProtectionRequest struct { + Rebuild *bool `json:"rebuild,omitempty"` + Delete *bool `json:"delete,omitempty"` +} + +// ServerActionChangeProtectionResponse defines the schema of the response when +// changing the resource protection of a server. +type ServerActionChangeProtectionResponse struct { + Action Action `json:"action"` +} + +// ServerActionRequestConsoleRequest defines the schema of the request to +// request a WebSocket VNC console. +type ServerActionRequestConsoleRequest struct{} + +// ServerActionRequestConsoleResponse defines the schema of the response when +// requesting a WebSocket VNC console. +type ServerActionRequestConsoleResponse struct { + Action Action `json:"action"` + WSSURL string `json:"wss_url"` + Password string `json:"password"` +} + +// ServerActionAttachToNetworkRequest defines the schema for the request to +// attach a network to a server. +type ServerActionAttachToNetworkRequest struct { + Network int64 `json:"network"` + IP *string `json:"ip,omitempty"` + AliasIPs []*string `json:"alias_ips,omitempty"` +} + +// ServerActionAttachToNetworkResponse defines the schema of the response when +// creating an attach_to_network server action. +type ServerActionAttachToNetworkResponse struct { + Action Action `json:"action"` +} + +// ServerActionDetachFromNetworkRequest defines the schema for the request to +// detach a network from a server. +type ServerActionDetachFromNetworkRequest struct { + Network int64 `json:"network"` +} + +// ServerActionDetachFromNetworkResponse defines the schema of the response when +// creating a detach_from_network server action. +type ServerActionDetachFromNetworkResponse struct { + Action Action `json:"action"` +} + +// ServerActionChangeAliasIPsRequest defines the schema for the request to +// change a server's alias IPs in a network. +type ServerActionChangeAliasIPsRequest struct { + Network int64 `json:"network"` + AliasIPs []string `json:"alias_ips"` +} + +// ServerActionChangeAliasIPsResponse defines the schema of the response when +// creating an change_alias_ips server action. +type ServerActionChangeAliasIPsResponse struct { + Action Action `json:"action"` +} + +// ServerGetMetricsResponse defines the schema of the response when requesting +// metrics for a server. +type ServerGetMetricsResponse struct { + Metrics struct { + Start time.Time `json:"start"` + End time.Time `json:"end"` + Step float64 `json:"step"` + TimeSeries map[string]ServerTimeSeriesVals `json:"time_series"` + } `json:"metrics"` +} + +// ServerTimeSeriesVals contains the values for a Server time series. +type ServerTimeSeriesVals struct { + Values []interface{} `json:"values"` +} + +// ServerActionAddToPlacementGroupRequest defines the schema for the request to +// add a server to a placement group. +type ServerActionAddToPlacementGroupRequest struct { + PlacementGroup int64 `json:"placement_group"` +} + +// ServerActionAddToPlacementGroupResponse defines the schema of the response when +// creating an add_to_placement_group server action. +type ServerActionAddToPlacementGroupResponse struct { + Action Action `json:"action"` +} + +// ServerActionRemoveFromPlacementGroupResponse defines the schema of the response when +// creating a remove_from_placement_group server action. +type ServerActionRemoveFromPlacementGroupResponse struct { + Action Action `json:"action"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/server_type.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/server_type.go new file mode 100644 index 000000000..21a87da9a --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/server_type.go @@ -0,0 +1,30 @@ +package schema + +// ServerType defines the schema of a server type. +type ServerType struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Cores int `json:"cores"` + Memory float32 `json:"memory"` + Disk int `json:"disk"` + StorageType string `json:"storage_type"` + CPUType string `json:"cpu_type"` + Architecture string `json:"architecture"` + IncludedTraffic int64 `json:"included_traffic"` + Prices []PricingServerTypePrice `json:"prices"` + Deprecated bool `json:"deprecated"` + DeprecatableResource +} + +// ServerTypeListResponse defines the schema of the response when +// listing server types. +type ServerTypeListResponse struct { + ServerTypes []ServerType `json:"server_types"` +} + +// ServerTypeGetResponse defines the schema of the response when +// retrieving a single server type. +type ServerTypeGetResponse struct { + ServerType ServerType `json:"server_type"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/ssh_key.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/ssh_key.go new file mode 100644 index 000000000..7e095bc5a --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/ssh_key.go @@ -0,0 +1,50 @@ +package schema + +import "time" + +// SSHKey defines the schema of a SSH key. +type SSHKey struct { + ID int64 `json:"id"` + Name string `json:"name"` + Fingerprint string `json:"fingerprint"` + PublicKey string `json:"public_key"` + Labels map[string]string `json:"labels"` + Created time.Time `json:"created"` +} + +// SSHKeyCreateRequest defines the schema of the request +// to create a SSH key. +type SSHKeyCreateRequest struct { + Name string `json:"name"` + PublicKey string `json:"public_key"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// SSHKeyCreateResponse defines the schema of the response +// when creating a SSH key. +type SSHKeyCreateResponse struct { + SSHKey SSHKey `json:"ssh_key"` +} + +// SSHKeyListResponse defines the schema of the response +// when listing SSH keys. +type SSHKeyListResponse struct { + SSHKeys []SSHKey `json:"ssh_keys"` +} + +// SSHKeyGetResponse defines the schema of the response +// when retrieving a single SSH key. +type SSHKeyGetResponse struct { + SSHKey SSHKey `json:"ssh_key"` +} + +// SSHKeyUpdateRequest defines the schema of the request to update a SSH key. +type SSHKeyUpdateRequest struct { + Name string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// SSHKeyUpdateResponse defines the schema of the response when updating a SSH key. +type SSHKeyUpdateResponse struct { + SSHKey SSHKey `json:"ssh_key"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/volume.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/volume.go new file mode 100644 index 000000000..0dd391bcc --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema/volume.go @@ -0,0 +1,110 @@ +package schema + +import "time" + +// Volume defines the schema of a volume. +type Volume struct { + ID int64 `json:"id"` + Name string `json:"name"` + Server *int64 `json:"server"` + Status string `json:"status"` + Location Location `json:"location"` + Size int `json:"size"` + Protection VolumeProtection `json:"protection"` + Labels map[string]string `json:"labels"` + LinuxDevice string `json:"linux_device"` + Created time.Time `json:"created"` +} + +// VolumeCreateRequest defines the schema of the request +// to create a volume. +type VolumeCreateRequest struct { + Name string `json:"name"` + Size int `json:"size"` + Server *int64 `json:"server,omitempty"` + Location interface{} `json:"location,omitempty"` // int, string, or nil + Labels *map[string]string `json:"labels,omitempty"` + Automount *bool `json:"automount,omitempty"` + Format *string `json:"format,omitempty"` +} + +// VolumeCreateResponse defines the schema of the response +// when creating a volume. +type VolumeCreateResponse struct { + Volume Volume `json:"volume"` + Action *Action `json:"action"` + NextActions []Action `json:"next_actions"` +} + +// VolumeListResponse defines the schema of the response +// when listing volumes. +type VolumeListResponse struct { + Volumes []Volume `json:"volumes"` +} + +// VolumeGetResponse defines the schema of the response +// when retrieving a single volume. +type VolumeGetResponse struct { + Volume Volume `json:"volume"` +} + +// VolumeUpdateRequest defines the schema of the request to update a volume. +type VolumeUpdateRequest struct { + Name string `json:"name,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` +} + +// VolumeUpdateResponse defines the schema of the response when updating a volume. +type VolumeUpdateResponse struct { + Volume Volume `json:"volume"` +} + +// VolumeProtection defines the schema of a volume's resource protection. +type VolumeProtection struct { + Delete bool `json:"delete"` +} + +// VolumeActionChangeProtectionRequest defines the schema of the request to +// change the resource protection of a volume. +type VolumeActionChangeProtectionRequest struct { + Delete *bool `json:"delete,omitempty"` +} + +// VolumeActionChangeProtectionResponse defines the schema of the response when +// changing the resource protection of a volume. +type VolumeActionChangeProtectionResponse struct { + Action Action `json:"action"` +} + +// VolumeActionAttachVolumeRequest defines the schema of the request to +// attach a volume to a server. +type VolumeActionAttachVolumeRequest struct { + Server int64 `json:"server"` + Automount *bool `json:"automount,omitempty"` +} + +// VolumeActionAttachVolumeResponse defines the schema of the response when +// attaching a volume to a server. +type VolumeActionAttachVolumeResponse struct { + Action Action `json:"action"` +} + +// VolumeActionDetachVolumeRequest defines the schema of the request to +// create an detach volume action. +type VolumeActionDetachVolumeRequest struct{} + +// VolumeActionDetachVolumeResponse defines the schema of the response when +// creating an detach volume action. +type VolumeActionDetachVolumeResponse struct { + Action Action `json:"action"` +} + +// VolumeActionResizeVolumeRequest defines the schema of the request to resize a volume. +type VolumeActionResizeVolumeRequest struct { + Size int `json:"size"` +} + +// VolumeActionResizeVolumeResponse defines the schema of the response when resizing a volume. +type VolumeActionResizeVolumeResponse struct { + Action Action `json:"action"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema_assign.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema_assign.go new file mode 100644 index 000000000..8894e3506 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema_assign.go @@ -0,0 +1,15 @@ +//go:build !goverter + +package hcloud + +/* +This file is needed so that c is assigned to a converterImpl{}. +If we did this in schema.go, goverter would fail because of a +compiler error (converterImpl might not be defined). +Because this file is not compiled by goverter, we can safely +assign c here. +*/ + +func init() { + c = &converterImpl{} +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema_gen.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema_gen.go new file mode 100644 index 000000000..1008bddd8 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/schema_gen.go @@ -0,0 +1,928 @@ +package hcloud + +import ( + "encoding/json" + "fmt" + "net" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +//go:generate go run github.com/jmattheis/goverter/cmd/goverter gen ./... + +/* +This file generates conversions methods between the schema and the hcloud package. +Goverter (https://github.com/jmattheis/goverter) is used to generate these conversion +methods. Goverter is configured using comments in and on the [converter] interface. +A struct implementing the interface methods, [converterImpl], is generated in zz_schema.go. +The generated methods are then wrapped in schema.go to be exported. + +You can find a documentation of goverter here: https://goverter.jmattheis.de/ +*/ + +// goverter:converter +// +// Specify where and in which package to output the generated +// conversion methods. +// goverter:output:file zz_schema.go +// goverter:output:package github.com/hetznercloud/hcloud-go/v2/hcloud +// +// In case of *T -> T conversion, use zero value if *T is nil. +// goverter:useZeroValueOnPointerInconsistency yes +// +// Do not deep copy in case of *T -> *T conversion. +// goverter:skipCopySameType yes +// +// Explicit conversion methods are needed for non-trivial cases +// where the target, source or both are of primitive types. Struct +// to struct conversions can be handled by goverter directly. +// goverter:extend ipFromString +// goverter:extend stringFromIP +// goverter:extend ipNetFromString +// goverter:extend stringFromIPNet +// goverter:extend timeToTimePtr +// goverter:extend serverFromInt64 +// goverter:extend int64FromServer +// goverter:extend networkFromInt64 +// goverter:extend int64FromNetwork +// goverter:extend loadBalancerFromInt64 +// goverter:extend int64FromLoadBalancer +// goverter:extend volumeFromInt64 +// goverter:extend int64FromVolume +// goverter:extend certificateFromInt64 +// goverter:extend int64FromCertificate +// goverter:extend locationFromString +// goverter:extend stringFromLocation +// goverter:extend serverTypeFromInt64 +// goverter:extend int64FromServerType +// goverter:extend floatingIPFromInt64 +// goverter:extend int64FromFloatingIP +// goverter:extend mapFromFloatingIPDNSPtrSchema +// goverter:extend floatingIPDNSPtrSchemaFromMap +// goverter:extend mapFromPrimaryIPDNSPtrSchema +// goverter:extend primaryIPDNSPtrSchemaFromMap +// goverter:extend mapFromServerPublicNetIPv6DNSPtrSchema +// goverter:extend serverPublicNetIPv6DNSPtrSchemaFromMap +// goverter:extend firewallStatusFromSchemaServerFirewall +// goverter:extend serverFirewallSchemaFromFirewallStatus +// goverter:extend durationFromIntSeconds +// goverter:extend intSecondsFromDuration +// goverter:extend serverFromImageCreatedFromSchema +// goverter:extend anyFromLoadBalancerType +// goverter:extend serverMetricsTimeSeriesFromSchema +// goverter:extend loadBalancerMetricsTimeSeriesFromSchema +// goverter:extend stringPtrFromLoadBalancerServiceProtocol +// goverter:extend stringPtrFromNetworkZone +// goverter:extend schemaFromLoadBalancerCreateOptsTargetLabelSelector +// goverter:extend schemaFromLoadBalancerCreateOptsTargetServer +// goverter:extend schemaFromLoadBalancerCreateOptsTargetIP +// goverter:extend stringMapToStringMapPtr +type converter interface { + + // goverter:map Error.Code ErrorCode + // goverter:map Error.Message ErrorMessage + ActionFromSchema(schema.Action) *Action + + // goverter:map . Error | schemaActionErrorFromAction + SchemaFromAction(*Action) schema.Action + + ActionsFromSchema([]schema.Action) []*Action + + SchemaFromActions([]*Action) []schema.Action + + // goverter:map . IP | ipFromFloatingIPSchema + // goverter:map . Network | networkFromFloatingIPSchema + FloatingIPFromSchema(schema.FloatingIP) *FloatingIP + + // goverter:map . IP | floatingIPToIPString + SchemaFromFloatingIP(*FloatingIP) schema.FloatingIP + + // goverter:map . IP | ipFromPrimaryIPSchema + // goverter:map . Network | networkFromPrimaryIPSchema + PrimaryIPFromSchema(schema.PrimaryIP) *PrimaryIP + + // goverter:map . IP | primaryIPToIPString + SchemaFromPrimaryIP(*PrimaryIP) schema.PrimaryIP + + ISOFromSchema(schema.ISO) *ISO + + // We cannot use goverter settings when mapping a struct to a struct pointer + // See [converter.ISOFromSchema] + // See https://github.com/jmattheis/goverter/issues/114 + // goverter:map DeprecatableResource.Deprecation.UnavailableAfter Deprecated + intISOFromSchema(schema.ISO) ISO + + SchemaFromISO(*ISO) schema.ISO + + LocationFromSchema(schema.Location) *Location + + SchemaFromLocation(*Location) schema.Location + + DatacenterFromSchema(schema.Datacenter) *Datacenter + + SchemaFromDatacenter(*Datacenter) schema.Datacenter + + ServerFromSchema(schema.Server) *Server + + // goverter:map OutgoingTraffic | mapZeroUint64ToNil + // goverter:map IngoingTraffic | mapZeroUint64ToNil + // goverter:map BackupWindow | mapEmptyStringToNil + SchemaFromServer(*Server) schema.Server + + ServerPublicNetFromSchema(schema.ServerPublicNet) ServerPublicNet + + SchemaFromServerPublicNet(ServerPublicNet) schema.ServerPublicNet + + ServerPublicNetIPv4FromSchema(schema.ServerPublicNetIPv4) ServerPublicNetIPv4 + + SchemaFromServerPublicNetIPv4(ServerPublicNetIPv4) schema.ServerPublicNetIPv4 + + // goverter:map . IP | ipFromServerPublicNetIPv6Schema + // goverter:map . Network | ipNetFromServerPublicNetIPv6Schema + ServerPublicNetIPv6FromSchema(schema.ServerPublicNetIPv6) ServerPublicNetIPv6 + + // goverter:map Network IP + SchemaFromServerPublicNetIPv6(ServerPublicNetIPv6) schema.ServerPublicNetIPv6 + + // goverter:map AliasIPs Aliases + ServerPrivateNetFromSchema(schema.ServerPrivateNet) ServerPrivateNet + + // goverter:map Aliases AliasIPs + SchemaFromServerPrivateNet(ServerPrivateNet) schema.ServerPrivateNet + + // goverter:map Prices Pricings + ServerTypeFromSchema(schema.ServerType) *ServerType + + // goverter:map Pricings Prices + // goverter:map DeprecatableResource.Deprecation Deprecated | isDeprecationNotNil + SchemaFromServerType(*ServerType) schema.ServerType + + ImageFromSchema(schema.Image) *Image + + SchemaFromImage(*Image) schema.Image + + // Needed because of how goverter works internally, see https://github.com/jmattheis/goverter/issues/114 + // goverter:map ImageSize | mapZeroFloat32ToNil + intSchemaFromImage(Image) schema.Image + + // goverter:ignore Currency + // goverter:ignore VATRate + PriceFromSchema(schema.Price) Price + + SSHKeyFromSchema(schema.SSHKey) *SSHKey + + SchemaFromSSHKey(*SSHKey) schema.SSHKey + + VolumeFromSchema(schema.Volume) *Volume + + SchemaFromVolume(*Volume) schema.Volume + + NetworkFromSchema(schema.Network) *Network + + SchemaFromNetwork(*Network) schema.Network + + NetworkSubnetFromSchema(schema.NetworkSubnet) NetworkSubnet + + SchemaFromNetworkSubnet(NetworkSubnet) schema.NetworkSubnet + + NetworkRouteFromSchema(schema.NetworkRoute) NetworkRoute + + SchemaFromNetworkRoute(NetworkRoute) schema.NetworkRoute + + LoadBalancerFromSchema(schema.LoadBalancer) *LoadBalancer + + // goverter:map OutgoingTraffic | mapZeroUint64ToNil + // goverter:map IngoingTraffic | mapZeroUint64ToNil + SchemaFromLoadBalancer(*LoadBalancer) schema.LoadBalancer + + // goverter:map Prices Pricings + LoadBalancerTypeFromSchema(schema.LoadBalancerType) *LoadBalancerType + + // goverter:map Pricings Prices + SchemaFromLoadBalancerType(*LoadBalancerType) schema.LoadBalancerType + + // goverter:map PriceHourly Hourly + // goverter:map PriceMonthly Monthly + LoadBalancerTypeLocationPricingFromSchema(schema.PricingLoadBalancerTypePrice) LoadBalancerTypeLocationPricing + + // goverter:map Hourly PriceHourly + // goverter:map Monthly PriceMonthly + SchemaFromLoadBalancerTypeLocationPricing(LoadBalancerTypeLocationPricing) schema.PricingLoadBalancerTypePrice + + LoadBalancerServiceFromSchema(schema.LoadBalancerService) LoadBalancerService + + SchemaFromLoadBalancerService(LoadBalancerService) schema.LoadBalancerService + + LoadBalancerServiceHealthCheckFromSchema(*schema.LoadBalancerServiceHealthCheck) LoadBalancerServiceHealthCheck + + SchemaFromLoadBalancerServiceHealthCheck(LoadBalancerServiceHealthCheck) *schema.LoadBalancerServiceHealthCheck + + LoadBalancerTargetFromSchema(schema.LoadBalancerTarget) LoadBalancerTarget + + SchemaFromLoadBalancerTarget(LoadBalancerTarget) schema.LoadBalancerTarget + + // goverter:map ID Server + LoadBalancerTargetServerFromSchema(schema.LoadBalancerTargetServer) LoadBalancerTargetServer + + // goverter:map Server ID + SchemaFromLoadBalancerServerTarget(LoadBalancerTargetServer) schema.LoadBalancerTargetServer + + LoadBalancerTargetHealthStatusFromSchema(schema.LoadBalancerTargetHealthStatus) LoadBalancerTargetHealthStatus + + SchemaFromLoadBalancerTargetHealthStatus(LoadBalancerTargetHealthStatus) schema.LoadBalancerTargetHealthStatus + + CertificateFromSchema(schema.Certificate) *Certificate + + SchemaFromCertificate(*Certificate) schema.Certificate + + PaginationFromSchema(schema.MetaPagination) Pagination + + SchemaFromPagination(Pagination) schema.MetaPagination + + // goverter:ignore response + // goverter:map Details | errorDetailsFromSchema + ErrorFromSchema(schema.Error) Error + + // goverter:map Details | schemaFromErrorDetails + // goverter:map Details DetailsRaw | rawSchemaFromErrorDetails + SchemaFromError(Error) schema.Error + + // goverter:map . Image | imagePricingFromSchema + // goverter:map . FloatingIP | floatingIPPricingFromSchema + // goverter:map . FloatingIPs | floatingIPTypePricingFromSchema + // goverter:map . PrimaryIPs | primaryIPPricingFromSchema + // goverter:map . Traffic | trafficPricingFromSchema + // goverter:map . ServerTypes | serverTypePricingFromSchema + // goverter:map . LoadBalancerTypes | loadBalancerTypePricingFromSchema + // goverter:map . Volume | volumePricingFromSchema + PricingFromSchema(schema.Pricing) Pricing + + // goverter:map PriceHourly Hourly + // goverter:map PriceMonthly Monthly + serverTypePricingFromSchema(schema.PricingServerTypePrice) ServerTypeLocationPricing + + // goverter:map Image.PerGBMonth.Currency Currency + // goverter:map Image.PerGBMonth.VATRate VATRate + SchemaFromPricing(Pricing) schema.Pricing + + // goverter:map PerGBMonth PricePerGBMonth + schemaFromImagePricing(ImagePricing) schema.PricingImage + + // goverter:map Monthly PriceMonthly + schemaFromFloatingIPPricing(FloatingIPPricing) schema.PricingFloatingIP + + // goverter:map Pricings Prices + schemaFromFloatingIPTypePricing(FloatingIPTypePricing) schema.PricingFloatingIPType + + // goverter:map Monthly PriceMonthly + schemaFromFloatingIPTypeLocationPricing(FloatingIPTypeLocationPricing) schema.PricingFloatingIPTypePrice + + // goverter:map Pricings Prices + schemaFromPrimaryIPPricing(PrimaryIPPricing) schema.PricingPrimaryIP + + // goverter:map Monthly PriceMonthly + // goverter:map Hourly PriceHourly + schemaFromPrimaryIPTypePricing(PrimaryIPTypePricing) schema.PricingPrimaryIPTypePrice + + // goverter:map PerTB PricePerTB + schemaFromTrafficPricing(TrafficPricing) schema.PricingTraffic + + // goverter:map Pricings Prices + // goverter:map ServerType.ID ID + // goverter:map ServerType.Name Name + schemaFromServerTypePricing(ServerTypePricing) schema.PricingServerType + + // goverter:map Pricings Prices + // goverter:map LoadBalancerType.ID ID + // goverter:map LoadBalancerType.Name Name + schemaFromLoadBalancerTypePricing(LoadBalancerTypePricing) schema.PricingLoadBalancerType + + // goverter:map PerGBMonthly PricePerGBPerMonth + schemaFromVolumePricing(VolumePricing) schema.PricingVolume + + // goverter:map Monthly PriceMonthly + // goverter:map Hourly PriceHourly + schemaFromServerTypeLocationPricing(ServerTypeLocationPricing) schema.PricingServerTypePrice + + FirewallFromSchema(schema.Firewall) *Firewall + + SchemaFromFirewall(*Firewall) schema.Firewall + + PlacementGroupFromSchema(schema.PlacementGroup) *PlacementGroup + + SchemaFromPlacementGroup(*PlacementGroup) schema.PlacementGroup + + SchemaFromPlacementGroupCreateOpts(PlacementGroupCreateOpts) schema.PlacementGroupCreateRequest + + SchemaFromLoadBalancerCreateOpts(LoadBalancerCreateOpts) schema.LoadBalancerCreateRequest + + // goverter:map Server.ID ID + SchemaFromLoadBalancerCreateOptsTargetServer(LoadBalancerCreateOptsTargetServer) schema.LoadBalancerCreateRequestTargetServer + + SchemaFromLoadBalancerAddServiceOpts(LoadBalancerAddServiceOpts) schema.LoadBalancerActionAddServiceRequest + + // goverter:ignore ListenPort + SchemaFromLoadBalancerUpdateServiceOpts(LoadBalancerUpdateServiceOpts) schema.LoadBalancerActionUpdateServiceRequest + + SchemaFromFirewallCreateOpts(FirewallCreateOpts) schema.FirewallCreateRequest + + SchemaFromFirewallSetRulesOpts(FirewallSetRulesOpts) schema.FirewallActionSetRulesRequest + + SchemaFromFirewallResource(FirewallResource) schema.FirewallResource + + // goverter:autoMap Metrics + ServerMetricsFromSchema(*schema.ServerGetMetricsResponse) (*ServerMetrics, error) + + // goverter:autoMap Metrics + LoadBalancerMetricsFromSchema(*schema.LoadBalancerGetMetricsResponse) (*LoadBalancerMetrics, error) + + DeprecationFromSchema(*schema.DeprecationInfo) *DeprecationInfo + + SchemaFromDeprecation(*DeprecationInfo) *schema.DeprecationInfo +} + +func schemaActionErrorFromAction(a Action) *schema.ActionError { + if a.ErrorCode != "" && a.ErrorMessage != "" { + return &schema.ActionError{ + Code: a.ErrorCode, + Message: a.ErrorMessage, + } + } + return nil +} + +func ipFromFloatingIPSchema(s schema.FloatingIP) net.IP { + if s.Type == string(FloatingIPTypeIPv4) { + return net.ParseIP(s.IP) + } + ip, _, _ := net.ParseCIDR(s.IP) + return ip +} + +func networkFromFloatingIPSchema(s schema.FloatingIP) *net.IPNet { + if s.Type == string(FloatingIPTypeIPv4) { + return nil + } + _, n, _ := net.ParseCIDR(s.IP) + return n +} + +func ipFromPrimaryIPSchema(s schema.PrimaryIP) net.IP { + if s.Type == string(FloatingIPTypeIPv4) { + return net.ParseIP(s.IP) + } + ip, _, _ := net.ParseCIDR(s.IP) + return ip +} + +func networkFromPrimaryIPSchema(s schema.PrimaryIP) *net.IPNet { + if s.Type == string(FloatingIPTypeIPv4) { + return nil + } + _, n, _ := net.ParseCIDR(s.IP) + return n +} + +func serverFromInt64(id int64) Server { + return Server{ID: id} +} + +func int64FromServer(s Server) int64 { + return s.ID +} + +func networkFromInt64(id int64) Network { + return Network{ID: id} +} + +func int64FromNetwork(network Network) int64 { + return network.ID +} + +func loadBalancerFromInt64(id int64) LoadBalancer { + return LoadBalancer{ID: id} +} + +func int64FromLoadBalancer(lb LoadBalancer) int64 { + return lb.ID +} + +func volumeFromInt64(id int64) *Volume { + return &Volume{ID: id} +} + +func int64FromVolume(volume *Volume) int64 { + if volume == nil { + return 0 + } + return volume.ID +} + +func serverTypeFromInt64(id int64) *ServerType { + return &ServerType{ID: id} +} + +func int64FromServerType(s *ServerType) int64 { + if s == nil { + return 0 + } + return s.ID +} + +func certificateFromInt64(id int64) *Certificate { + return &Certificate{ID: id} +} + +func int64FromCertificate(c *Certificate) int64 { + if c == nil { + return 0 + } + return c.ID +} + +func locationFromString(s string) Location { + return Location{Name: s} +} + +func stringFromLocation(l Location) string { + return l.Name +} + +func mapFromFloatingIPDNSPtrSchema(dnsPtr []schema.FloatingIPDNSPtr) map[string]string { + m := make(map[string]string, len(dnsPtr)) + for _, entry := range dnsPtr { + m[entry.IP] = entry.DNSPtr + } + return m +} + +func floatingIPDNSPtrSchemaFromMap(m map[string]string) []schema.FloatingIPDNSPtr { + dnsPtr := make([]schema.FloatingIPDNSPtr, 0, len(m)) + for ip, ptr := range m { + dnsPtr = append(dnsPtr, schema.FloatingIPDNSPtr{ + IP: ip, + DNSPtr: ptr, + }) + } + return dnsPtr +} + +func mapFromPrimaryIPDNSPtrSchema(dnsPtr []schema.PrimaryIPDNSPTR) map[string]string { + m := make(map[string]string, len(dnsPtr)) + for _, entry := range dnsPtr { + m[entry.IP] = entry.DNSPtr + } + return m +} + +func primaryIPDNSPtrSchemaFromMap(m map[string]string) []schema.PrimaryIPDNSPTR { + dnsPtr := make([]schema.PrimaryIPDNSPTR, 0, len(m)) + for ip, ptr := range m { + dnsPtr = append(dnsPtr, schema.PrimaryIPDNSPTR{ + IP: ip, + DNSPtr: ptr, + }) + } + return dnsPtr +} + +func mapFromServerPublicNetIPv6DNSPtrSchema(dnsPtr []schema.ServerPublicNetIPv6DNSPtr) map[string]string { + m := make(map[string]string, len(dnsPtr)) + for _, entry := range dnsPtr { + m[entry.IP] = entry.DNSPtr + } + return m +} + +func serverPublicNetIPv6DNSPtrSchemaFromMap(m map[string]string) []schema.ServerPublicNetIPv6DNSPtr { + dnsPtr := make([]schema.ServerPublicNetIPv6DNSPtr, 0, len(m)) + for ip, ptr := range m { + dnsPtr = append(dnsPtr, schema.ServerPublicNetIPv6DNSPtr{ + IP: ip, + DNSPtr: ptr, + }) + } + return dnsPtr +} + +func floatingIPToIPString(ip FloatingIP) string { + if ip.Type == FloatingIPTypeIPv4 { + return ip.IP.String() + } + return ip.Network.String() +} + +func primaryIPToIPString(ip PrimaryIP) string { + if ip.Type == PrimaryIPTypeIPv4 { + return ip.IP.String() + } + return ip.Network.String() +} + +func floatingIPFromInt64(id int64) *FloatingIP { + return &FloatingIP{ID: id} +} + +func int64FromFloatingIP(f *FloatingIP) int64 { + if f == nil { + return 0 + } + return f.ID +} + +func firewallStatusFromSchemaServerFirewall(fw schema.ServerFirewall) *ServerFirewallStatus { + return &ServerFirewallStatus{ + Firewall: Firewall{ID: fw.ID}, + Status: FirewallStatus(fw.Status), + } +} + +func serverFirewallSchemaFromFirewallStatus(s *ServerFirewallStatus) schema.ServerFirewall { + return schema.ServerFirewall{ + ID: s.Firewall.ID, + Status: string(s.Status), + } +} + +func ipFromServerPublicNetIPv6Schema(s schema.ServerPublicNetIPv6) net.IP { + ip, _, _ := net.ParseCIDR(s.IP) + return ip +} + +func ipNetFromServerPublicNetIPv6Schema(s schema.ServerPublicNetIPv6) *net.IPNet { + _, n, _ := net.ParseCIDR(s.IP) + return n +} + +func serverFromImageCreatedFromSchema(s schema.ImageCreatedFrom) Server { + return Server{ + ID: s.ID, + Name: s.Name, + } +} + +func ipFromString(s string) net.IP { + return net.ParseIP(s) +} + +func stringFromIP(ip net.IP) string { + if ip == nil { + return "" + } + return ip.String() +} + +func ipNetFromString(s string) net.IPNet { + _, n, _ := net.ParseCIDR(s) + if n == nil { + return net.IPNet{} + } + return *n +} + +func stringFromIPNet(ip net.IPNet) string { + return ip.String() +} + +func timeToTimePtr(t time.Time) *time.Time { + // Some hcloud structs don't use pointers for nullable times, so the zero value + // should be treated as nil. + if t == (time.Time{}) { + return nil + } + return &t +} + +func durationFromIntSeconds(s int) time.Duration { + return time.Duration(s) * time.Second +} + +func intSecondsFromDuration(d time.Duration) int { + return int(d.Seconds()) +} + +func errorDetailsFromSchema(d interface{}) interface{} { + if d, ok := d.(schema.ErrorDetailsInvalidInput); ok { + details := ErrorDetailsInvalidInput{ + Fields: make([]ErrorDetailsInvalidInputField, len(d.Fields)), + } + for i, field := range d.Fields { + details.Fields[i] = ErrorDetailsInvalidInputField{ + Name: field.Name, + Messages: field.Messages, + } + } + return details + } + return nil +} + +func schemaFromErrorDetails(d interface{}) interface{} { + if d, ok := d.(ErrorDetailsInvalidInput); ok { + details := schema.ErrorDetailsInvalidInput{ + Fields: make([]struct { + Name string `json:"name"` + Messages []string `json:"messages"` + }, len(d.Fields)), + } + for i, field := range d.Fields { + details.Fields[i] = struct { + Name string `json:"name"` + Messages []string `json:"messages"` + }{Name: field.Name, Messages: field.Messages} + } + return details + } + return nil +} + +func imagePricingFromSchema(s schema.Pricing) ImagePricing { + return ImagePricing{ + PerGBMonth: Price{ + Net: s.Image.PricePerGBMonth.Net, + Gross: s.Image.PricePerGBMonth.Gross, + Currency: s.Currency, + VATRate: s.VATRate, + }, + } +} + +func floatingIPPricingFromSchema(s schema.Pricing) FloatingIPPricing { + return FloatingIPPricing{ + Monthly: Price{ + Net: s.FloatingIP.PriceMonthly.Net, + Gross: s.FloatingIP.PriceMonthly.Gross, + Currency: s.Currency, + VATRate: s.VATRate, + }, + } +} + +func floatingIPTypePricingFromSchema(s schema.Pricing) []FloatingIPTypePricing { + p := make([]FloatingIPTypePricing, len(s.FloatingIPs)) + for i, floatingIPType := range s.FloatingIPs { + var pricings = make([]FloatingIPTypeLocationPricing, len(floatingIPType.Prices)) + for i, price := range floatingIPType.Prices { + pricings[i] = FloatingIPTypeLocationPricing{ + Location: &Location{Name: price.Location}, + Monthly: Price{ + Currency: s.Currency, + VATRate: s.VATRate, + Net: price.PriceMonthly.Net, + Gross: price.PriceMonthly.Gross, + }, + } + } + p[i] = FloatingIPTypePricing{Type: FloatingIPType(floatingIPType.Type), Pricings: pricings} + } + return p +} + +func primaryIPPricingFromSchema(s schema.Pricing) []PrimaryIPPricing { + p := make([]PrimaryIPPricing, len(s.FloatingIPs)) + for i, primaryIPType := range s.PrimaryIPs { + var pricings = make([]PrimaryIPTypePricing, len(primaryIPType.Prices)) + for i, price := range primaryIPType.Prices { + pricings[i] = PrimaryIPTypePricing{ + Location: price.Location, + Monthly: PrimaryIPPrice{ + Net: price.PriceMonthly.Net, + Gross: price.PriceMonthly.Gross, + }, + Hourly: PrimaryIPPrice{ + Net: price.PriceHourly.Net, + Gross: price.PriceHourly.Gross, + }, + } + } + p[i] = PrimaryIPPricing{Type: primaryIPType.Type, Pricings: pricings} + } + return p +} + +func trafficPricingFromSchema(s schema.Pricing) TrafficPricing { + return TrafficPricing{ + PerTB: Price{ + Net: s.Traffic.PricePerTB.Net, + Gross: s.Traffic.PricePerTB.Gross, + Currency: s.Currency, + VATRate: s.VATRate, + }, + } +} + +func serverTypePricingFromSchema(s schema.Pricing) []ServerTypePricing { + p := make([]ServerTypePricing, len(s.ServerTypes)) + for i, serverType := range s.ServerTypes { + var pricings = make([]ServerTypeLocationPricing, len(serverType.Prices)) + for i, price := range serverType.Prices { + pricings[i] = ServerTypeLocationPricing{ + Location: &Location{Name: price.Location}, + Hourly: Price{ + Currency: s.Currency, + VATRate: s.VATRate, + Net: price.PriceHourly.Net, + Gross: price.PriceHourly.Gross, + }, + Monthly: Price{ + Currency: s.Currency, + VATRate: s.VATRate, + Net: price.PriceMonthly.Net, + Gross: price.PriceMonthly.Gross, + }, + } + } + p[i] = ServerTypePricing{ + ServerType: &ServerType{ + ID: serverType.ID, + Name: serverType.Name, + }, + Pricings: pricings, + } + } + return p +} + +func loadBalancerTypePricingFromSchema(s schema.Pricing) []LoadBalancerTypePricing { + p := make([]LoadBalancerTypePricing, len(s.LoadBalancerTypes)) + for i, loadBalancerType := range s.LoadBalancerTypes { + var pricings = make([]LoadBalancerTypeLocationPricing, len(loadBalancerType.Prices)) + for i, price := range loadBalancerType.Prices { + pricings[i] = LoadBalancerTypeLocationPricing{ + Location: &Location{Name: price.Location}, + Hourly: Price{ + Currency: s.Currency, + VATRate: s.VATRate, + Net: price.PriceHourly.Net, + Gross: price.PriceHourly.Gross, + }, + Monthly: Price{ + Currency: s.Currency, + VATRate: s.VATRate, + Net: price.PriceMonthly.Net, + Gross: price.PriceMonthly.Gross, + }, + } + } + p[i] = LoadBalancerTypePricing{ + LoadBalancerType: &LoadBalancerType{ + ID: loadBalancerType.ID, + Name: loadBalancerType.Name, + }, + Pricings: pricings, + } + } + return p +} + +func volumePricingFromSchema(s schema.Pricing) VolumePricing { + return VolumePricing{ + PerGBMonthly: Price{ + Net: s.Volume.PricePerGBPerMonth.Net, + Gross: s.Volume.PricePerGBPerMonth.Gross, + Currency: s.Currency, + VATRate: s.VATRate, + }, + } +} + +func anyFromLoadBalancerType(t *LoadBalancerType) interface{} { + if t == nil { + return nil + } + if t.ID != 0 { + return t.ID + } + return t.Name +} + +func serverMetricsTimeSeriesFromSchema(s schema.ServerTimeSeriesVals) ([]ServerMetricsValue, error) { + vals := make([]ServerMetricsValue, len(s.Values)) + + for i, rawVal := range s.Values { + var val ServerMetricsValue + + tup, ok := rawVal.([]interface{}) + if !ok { + return nil, fmt.Errorf("failed to convert value to tuple: %v", rawVal) + } + if len(tup) != 2 { + return nil, fmt.Errorf("invalid tuple size: %d: %v", len(tup), rawVal) + } + ts, ok := tup[0].(float64) + if !ok { + return nil, fmt.Errorf("convert to float64: %v", tup[0]) + } + val.Timestamp = ts + + v, ok := tup[1].(string) + if !ok { + return nil, fmt.Errorf("not a string: %v", tup[1]) + } + val.Value = v + vals[i] = val + } + + return vals, nil +} + +func loadBalancerMetricsTimeSeriesFromSchema(s schema.LoadBalancerTimeSeriesVals) ([]LoadBalancerMetricsValue, error) { + vals := make([]LoadBalancerMetricsValue, len(s.Values)) + + for i, rawVal := range s.Values { + var val LoadBalancerMetricsValue + + tup, ok := rawVal.([]interface{}) + if !ok { + return nil, fmt.Errorf("failed to convert value to tuple: %v", rawVal) + } + if len(tup) != 2 { + return nil, fmt.Errorf("invalid tuple size: %d: %v", len(tup), rawVal) + } + ts, ok := tup[0].(float64) + if !ok { + return nil, fmt.Errorf("convert to float64: %v", tup[0]) + } + val.Timestamp = ts + + v, ok := tup[1].(string) + if !ok { + return nil, fmt.Errorf("not a string: %v", tup[1]) + } + val.Value = v + vals[i] = val + } + + return vals, nil +} + +func mapEmptyStringToNil(s string) *string { + if s == "" { + return nil + } + return &s +} + +func stringPtrFromLoadBalancerServiceProtocol(p LoadBalancerServiceProtocol) *string { + return mapEmptyStringToNil(string(p)) +} + +func stringPtrFromNetworkZone(z NetworkZone) *string { + return mapEmptyStringToNil(string(z)) +} + +func mapZeroUint64ToNil(i uint64) *uint64 { + if i == 0 { + return nil + } + return &i +} + +func schemaFromLoadBalancerCreateOptsTargetLabelSelector(l LoadBalancerCreateOptsTargetLabelSelector) *schema.LoadBalancerCreateRequestTargetLabelSelector { + if l.Selector == "" { + return nil + } + return &schema.LoadBalancerCreateRequestTargetLabelSelector{Selector: l.Selector} +} + +func schemaFromLoadBalancerCreateOptsTargetIP(l LoadBalancerCreateOptsTargetIP) *schema.LoadBalancerCreateRequestTargetIP { + if l.IP == "" { + return nil + } + return &schema.LoadBalancerCreateRequestTargetIP{IP: l.IP} +} + +func schemaFromLoadBalancerCreateOptsTargetServer(l LoadBalancerCreateOptsTargetServer) *schema.LoadBalancerCreateRequestTargetServer { + if l.Server == nil { + return nil + } + return &schema.LoadBalancerCreateRequestTargetServer{ID: l.Server.ID} +} + +func stringMapToStringMapPtr(m map[string]string) *map[string]string { + if m == nil { + return nil + } + return &m +} + +func rawSchemaFromErrorDetails(v interface{}) json.RawMessage { + d := schemaFromErrorDetails(v) + if v == nil { + return nil + } + msg, _ := json.Marshal(d) + return msg +} + +func mapZeroFloat32ToNil(f float32) *float32 { + if f == 0 { + return nil + } + return &f +} + +func isDeprecationNotNil(d *DeprecationInfo) bool { + return d != nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/server.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/server.go new file mode 100644 index 000000000..fe8bf934c --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/server.go @@ -0,0 +1,1223 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Server represents a server in the Hetzner Cloud. +type Server struct { + ID int64 + Name string + Status ServerStatus + Created time.Time + PublicNet ServerPublicNet + PrivateNet []ServerPrivateNet + ServerType *ServerType + Datacenter *Datacenter + IncludedTraffic uint64 + OutgoingTraffic uint64 + IngoingTraffic uint64 + BackupWindow string + RescueEnabled bool + Locked bool + ISO *ISO + Image *Image + Protection ServerProtection + Labels map[string]string + Volumes []*Volume + PrimaryDiskSize int + PlacementGroup *PlacementGroup + LoadBalancers []*LoadBalancer +} + +// ServerProtection represents the protection level of a server. +type ServerProtection struct { + Delete, Rebuild bool +} + +// ServerStatus specifies a server's status. +type ServerStatus string + +const ( + // ServerStatusInitializing is the status when a server is initializing. + ServerStatusInitializing ServerStatus = "initializing" + + // ServerStatusOff is the status when a server is off. + ServerStatusOff ServerStatus = "off" + + // ServerStatusRunning is the status when a server is running. + ServerStatusRunning ServerStatus = "running" + + // ServerStatusStarting is the status when a server is being started. + ServerStatusStarting ServerStatus = "starting" + + // ServerStatusStopping is the status when a server is being stopped. + ServerStatusStopping ServerStatus = "stopping" + + // ServerStatusMigrating is the status when a server is being migrated. + ServerStatusMigrating ServerStatus = "migrating" + + // ServerStatusRebuilding is the status when a server is being rebuilt. + ServerStatusRebuilding ServerStatus = "rebuilding" + + // ServerStatusDeleting is the status when a server is being deleted. + ServerStatusDeleting ServerStatus = "deleting" + + // ServerStatusUnknown is the status when a server's state is unknown. + ServerStatusUnknown ServerStatus = "unknown" +) + +// FirewallStatus specifies a Firewall's status. +type FirewallStatus string + +const ( + // FirewallStatusPending is the status when a Firewall is pending. + FirewallStatusPending FirewallStatus = "pending" + + // FirewallStatusApplied is the status when a Firewall is applied. + FirewallStatusApplied FirewallStatus = "applied" +) + +// ServerPublicNet represents a server's public network. +type ServerPublicNet struct { + IPv4 ServerPublicNetIPv4 + IPv6 ServerPublicNetIPv6 + FloatingIPs []*FloatingIP + Firewalls []*ServerFirewallStatus +} + +// ServerPublicNetIPv4 represents a server's public IPv4 address. +type ServerPublicNetIPv4 struct { + ID int64 + IP net.IP + Blocked bool + DNSPtr string +} + +func (n *ServerPublicNetIPv4) IsUnspecified() bool { + return n.IP == nil || n.IP.Equal(net.IPv4zero) +} + +// ServerPublicNetIPv6 represents a Server's public IPv6 network and address. +type ServerPublicNetIPv6 struct { + ID int64 + IP net.IP + Network *net.IPNet + Blocked bool + DNSPtr map[string]string +} + +func (n *ServerPublicNetIPv6) IsUnspecified() bool { + return n.IP == nil || n.IP.Equal(net.IPv6unspecified) +} + +// ServerPrivateNet defines the schema of a Server's private network information. +type ServerPrivateNet struct { + Network *Network + IP net.IP + Aliases []net.IP + MACAddress string +} + +// DNSPtrForIP returns the reverse dns pointer of the ip address. +func (n *ServerPublicNetIPv6) DNSPtrForIP(ip net.IP) string { + return n.DNSPtr[ip.String()] +} + +// ServerFirewallStatus represents a Firewall and its status on a Server's +// network interface. +type ServerFirewallStatus struct { + Firewall Firewall + Status FirewallStatus +} + +// ServerRescueType represents rescue types. +type ServerRescueType string + +// List of rescue types. +const ( + ServerRescueTypeLinux32 ServerRescueType = "linux32" + ServerRescueTypeLinux64 ServerRescueType = "linux64" +) + +// changeDNSPtr changes or resets the reverse DNS pointer for a IP address. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (s *Server) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { + reqBody := schema.ServerActionChangeDNSPtrRequest{ + IP: ip.String(), + DNSPtr: ptr, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/change_dns_ptr", s.ID) + req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionChangeDNSPtrResponse{} + resp, err := client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// GetDNSPtrForIP searches for the dns assigned to the given IP address. +// It returns an error if there is no dns set for the given IP address. +func (s *Server) GetDNSPtrForIP(ip net.IP) (string, error) { + if net.IP.Equal(s.PublicNet.IPv4.IP, ip) { + return s.PublicNet.IPv4.DNSPtr, nil + } else if dns, ok := s.PublicNet.IPv6.DNSPtr[ip.String()]; ok { + return dns, nil + } + + return "", DNSNotFoundError{ip} +} + +// ServerClient is a client for the servers API. +type ServerClient struct { + client *Client + Action *ResourceActionClient +} + +// GetByID retrieves a server by its ID. If the server does not exist, nil is returned. +func (c *ServerClient) GetByID(ctx context.Context, id int64) (*Server, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/servers/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.ServerGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return ServerFromSchema(body.Server), resp, nil +} + +// GetByName retrieves a server by its name. If the server does not exist, nil is returned. +func (c *ServerClient) GetByName(ctx context.Context, name string) (*Server, *Response, error) { + if name == "" { + return nil, nil, nil + } + servers, response, err := c.List(ctx, ServerListOpts{Name: name}) + if len(servers) == 0 { + return nil, response, err + } + return servers[0], response, err +} + +// Get retrieves a server by its ID if the input can be parsed as an integer, otherwise it +// retrieves a server by its name. If the server does not exist, nil is returned. +func (c *ServerClient) Get(ctx context.Context, idOrName string) (*Server, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// ServerListOpts specifies options for listing servers. +type ServerListOpts struct { + ListOpts + Name string + Status []ServerStatus + Sort []string +} + +func (l ServerListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, status := range l.Status { + vals.Add("status", string(status)) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of servers for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *ServerClient) List(ctx context.Context, opts ServerListOpts) ([]*Server, *Response, error) { + path := "/servers?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.ServerListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + servers := make([]*Server, 0, len(body.Servers)) + for _, s := range body.Servers { + servers = append(servers, ServerFromSchema(s)) + } + return servers, resp, nil +} + +// All returns all servers. +func (c *ServerClient) All(ctx context.Context) ([]*Server, error) { + return c.AllWithOpts(ctx, ServerListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all servers for the given options. +func (c *ServerClient) AllWithOpts(ctx context.Context, opts ServerListOpts) ([]*Server, error) { + allServers := []*Server{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + servers, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allServers = append(allServers, servers...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allServers, nil +} + +// ServerCreateOpts specifies options for creating a new server. +type ServerCreateOpts struct { + Name string + ServerType *ServerType + Image *Image + SSHKeys []*SSHKey + Location *Location + Datacenter *Datacenter + UserData string + StartAfterCreate *bool + Labels map[string]string + Automount *bool + Volumes []*Volume + Networks []*Network + Firewalls []*ServerCreateFirewall + PlacementGroup *PlacementGroup + PublicNet *ServerCreatePublicNet +} + +type ServerCreatePublicNet struct { + EnableIPv4 bool + EnableIPv6 bool + IPv4 *PrimaryIP + IPv6 *PrimaryIP +} + +// ServerCreateFirewall defines which Firewalls to apply when creating a Server. +type ServerCreateFirewall struct { + Firewall Firewall +} + +// Validate checks if options are valid. +func (o ServerCreateOpts) Validate() error { + if o.Name == "" { + return errors.New("missing name") + } + if o.ServerType == nil || (o.ServerType.ID == 0 && o.ServerType.Name == "") { + return errors.New("missing server type") + } + if o.Image == nil || (o.Image.ID == 0 && o.Image.Name == "") { + return errors.New("missing image") + } + if o.Location != nil && o.Datacenter != nil { + return errors.New("location and datacenter are mutually exclusive") + } + if o.PublicNet != nil { + if !o.PublicNet.EnableIPv4 && !o.PublicNet.EnableIPv6 && + len(o.Networks) == 0 && (o.StartAfterCreate == nil || *o.StartAfterCreate) { + return errors.New("missing networks or StartAfterCreate == false when EnableIPv4 and EnableIPv6 is false") + } + } + return nil +} + +// ServerCreateResult is the result of a create server call. +type ServerCreateResult struct { + Server *Server + Action *Action + RootPassword string + NextActions []*Action +} + +// Create creates a new server. +func (c *ServerClient) Create(ctx context.Context, opts ServerCreateOpts) (ServerCreateResult, *Response, error) { + if err := opts.Validate(); err != nil { + return ServerCreateResult{}, nil, err + } + + var reqBody schema.ServerCreateRequest + reqBody.UserData = opts.UserData + reqBody.Name = opts.Name + reqBody.Automount = opts.Automount + reqBody.StartAfterCreate = opts.StartAfterCreate + if opts.ServerType.ID != 0 { + reqBody.ServerType = opts.ServerType.ID + } else if opts.ServerType.Name != "" { + reqBody.ServerType = opts.ServerType.Name + } + if opts.Image.ID != 0 { + reqBody.Image = opts.Image.ID + } else if opts.Image.Name != "" { + reqBody.Image = opts.Image.Name + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + for _, sshKey := range opts.SSHKeys { + reqBody.SSHKeys = append(reqBody.SSHKeys, sshKey.ID) + } + for _, volume := range opts.Volumes { + reqBody.Volumes = append(reqBody.Volumes, volume.ID) + } + for _, network := range opts.Networks { + reqBody.Networks = append(reqBody.Networks, network.ID) + } + for _, firewall := range opts.Firewalls { + reqBody.Firewalls = append(reqBody.Firewalls, schema.ServerCreateFirewalls{ + Firewall: firewall.Firewall.ID, + }) + } + + if opts.PublicNet != nil { + reqBody.PublicNet = &schema.ServerCreatePublicNet{ + EnableIPv4: opts.PublicNet.EnableIPv4, + EnableIPv6: opts.PublicNet.EnableIPv6, + } + if opts.PublicNet.IPv4 != nil { + reqBody.PublicNet.IPv4ID = opts.PublicNet.IPv4.ID + } + if opts.PublicNet.IPv6 != nil { + reqBody.PublicNet.IPv6ID = opts.PublicNet.IPv6.ID + } + } + if opts.Location != nil { + if opts.Location.ID != 0 { + reqBody.Location = strconv.FormatInt(opts.Location.ID, 10) + } else { + reqBody.Location = opts.Location.Name + } + } + if opts.Datacenter != nil { + if opts.Datacenter.ID != 0 { + reqBody.Datacenter = strconv.FormatInt(opts.Datacenter.ID, 10) + } else { + reqBody.Datacenter = opts.Datacenter.Name + } + } + if opts.PlacementGroup != nil { + reqBody.PlacementGroup = opts.PlacementGroup.ID + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return ServerCreateResult{}, nil, err + } + + req, err := c.client.NewRequest(ctx, "POST", "/servers", bytes.NewReader(reqBodyData)) + if err != nil { + return ServerCreateResult{}, nil, err + } + + var respBody schema.ServerCreateResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return ServerCreateResult{}, resp, err + } + result := ServerCreateResult{ + Server: ServerFromSchema(respBody.Server), + Action: ActionFromSchema(respBody.Action), + NextActions: ActionsFromSchema(respBody.NextActions), + } + if respBody.RootPassword != nil { + result.RootPassword = *respBody.RootPassword + } + return result, resp, nil +} + +// ServerDeleteResult is the result of a delete server call. +type ServerDeleteResult struct { + Action *Action +} + +// Delete deletes a server. +// +// Deprecated: Use [ServerClient.DeleteWithResult] instead. +func (c *ServerClient) Delete(ctx context.Context, server *Server) (*Response, error) { + _, resp, err := c.DeleteWithResult(ctx, server) + return resp, err +} + +// DeleteWithResult deletes a server and returns the parsed response containing the action. +func (c *ServerClient) DeleteWithResult(ctx context.Context, server *Server) (*ServerDeleteResult, *Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/servers/%d", server.ID), nil) + if err != nil { + return &ServerDeleteResult{}, nil, err + } + + var respBody schema.ServerDeleteResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return &ServerDeleteResult{}, resp, err + } + + return &ServerDeleteResult{ + Action: ActionFromSchema(respBody.Action), + }, resp, nil +} + +// ServerUpdateOpts specifies options for updating a server. +type ServerUpdateOpts struct { + Name string + Labels map[string]string +} + +// Update updates a server. +func (c *ServerClient) Update(ctx context.Context, server *Server, opts ServerUpdateOpts) (*Server, *Response, error) { + reqBody := schema.ServerUpdateRequest{ + Name: opts.Name, + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d", server.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ServerFromSchema(respBody.Server), resp, nil +} + +// Poweron starts a server. +func (c *ServerClient) Poweron(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/poweron", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionPoweronResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// Reboot reboots a server. +func (c *ServerClient) Reboot(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/reboot", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionRebootResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// Reset resets a server. +func (c *ServerClient) Reset(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/reset", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionResetResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// Shutdown shuts down a server. +func (c *ServerClient) Shutdown(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/shutdown", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionShutdownResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// Poweroff stops a server. +func (c *ServerClient) Poweroff(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/poweroff", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionPoweroffResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// ServerResetPasswordResult is the result of resetting a server's password. +type ServerResetPasswordResult struct { + Action *Action + RootPassword string +} + +// ResetPassword resets a server's password. +func (c *ServerClient) ResetPassword(ctx context.Context, server *Server) (ServerResetPasswordResult, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/reset_password", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return ServerResetPasswordResult{}, nil, err + } + + respBody := schema.ServerActionResetPasswordResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return ServerResetPasswordResult{}, resp, err + } + return ServerResetPasswordResult{ + Action: ActionFromSchema(respBody.Action), + RootPassword: respBody.RootPassword, + }, resp, nil +} + +// ServerCreateImageOpts specifies options for creating an image from a server. +type ServerCreateImageOpts struct { + Type ImageType + Description *string + Labels map[string]string +} + +// Validate checks if options are valid. +func (o ServerCreateImageOpts) Validate() error { + switch o.Type { + case ImageTypeSnapshot, ImageTypeBackup: + break + case "": + break + default: + return errors.New("invalid type") + } + + return nil +} + +// ServerCreateImageResult is the result of creating an image from a server. +type ServerCreateImageResult struct { + Action *Action + Image *Image +} + +// CreateImage creates an image from a server. +func (c *ServerClient) CreateImage(ctx context.Context, server *Server, opts *ServerCreateImageOpts) (ServerCreateImageResult, *Response, error) { + var reqBody schema.ServerActionCreateImageRequest + if opts != nil { + if err := opts.Validate(); err != nil { + return ServerCreateImageResult{}, nil, fmt.Errorf("invalid options: %s", err) + } + if opts.Description != nil { + reqBody.Description = opts.Description + } + if opts.Type != "" { + reqBody.Type = Ptr(string(opts.Type)) + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return ServerCreateImageResult{}, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/create_image", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return ServerCreateImageResult{}, nil, err + } + + respBody := schema.ServerActionCreateImageResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return ServerCreateImageResult{}, resp, err + } + return ServerCreateImageResult{ + Action: ActionFromSchema(respBody.Action), + Image: ImageFromSchema(respBody.Image), + }, resp, nil +} + +// ServerEnableRescueOpts specifies options for enabling rescue mode for a server. +type ServerEnableRescueOpts struct { + Type ServerRescueType + SSHKeys []*SSHKey +} + +// ServerEnableRescueResult is the result of enabling rescue mode for a server. +type ServerEnableRescueResult struct { + Action *Action + RootPassword string +} + +// EnableRescue enables rescue mode for a server. +func (c *ServerClient) EnableRescue(ctx context.Context, server *Server, opts ServerEnableRescueOpts) (ServerEnableRescueResult, *Response, error) { + reqBody := schema.ServerActionEnableRescueRequest{ + Type: Ptr(string(opts.Type)), + } + for _, sshKey := range opts.SSHKeys { + reqBody.SSHKeys = append(reqBody.SSHKeys, sshKey.ID) + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return ServerEnableRescueResult{}, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/enable_rescue", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return ServerEnableRescueResult{}, nil, err + } + + respBody := schema.ServerActionEnableRescueResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return ServerEnableRescueResult{}, resp, err + } + result := ServerEnableRescueResult{ + Action: ActionFromSchema(respBody.Action), + RootPassword: respBody.RootPassword, + } + return result, resp, nil +} + +// DisableRescue disables rescue mode for a server. +func (c *ServerClient) DisableRescue(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/disable_rescue", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionDisableRescueResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// ServerRebuildOpts specifies options for rebuilding a server. +type ServerRebuildOpts struct { + Image *Image +} + +// ServerRebuildResult is the result of a create server call. +type ServerRebuildResult struct { + Action *Action + RootPassword string +} + +// Rebuild rebuilds a server. +// +// Deprecated: Use [ServerClient.RebuildWithResult] instead. +func (c *ServerClient) Rebuild(ctx context.Context, server *Server, opts ServerRebuildOpts) (*Action, *Response, error) { + result, resp, err := c.RebuildWithResult(ctx, server, opts) + + return result.Action, resp, err +} + +// RebuildWithResult rebuilds a server. +func (c *ServerClient) RebuildWithResult(ctx context.Context, server *Server, opts ServerRebuildOpts) (ServerRebuildResult, *Response, error) { + reqBody := schema.ServerActionRebuildRequest{} + if opts.Image.ID != 0 { + reqBody.Image = opts.Image.ID + } else { + reqBody.Image = opts.Image.Name + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return ServerRebuildResult{}, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/rebuild", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return ServerRebuildResult{}, nil, err + } + + respBody := schema.ServerActionRebuildResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return ServerRebuildResult{}, resp, err + } + + result := ServerRebuildResult{ + Action: ActionFromSchema(respBody.Action), + } + if respBody.RootPassword != nil { + result.RootPassword = *respBody.RootPassword + } + + return result, resp, nil +} + +// AttachISO attaches an ISO to a server. +func (c *ServerClient) AttachISO(ctx context.Context, server *Server, iso *ISO) (*Action, *Response, error) { + reqBody := schema.ServerActionAttachISORequest{} + if iso.ID != 0 { + reqBody.ISO = iso.ID + } else { + reqBody.ISO = iso.Name + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/attach_iso", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionAttachISOResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// DetachISO detaches the currently attached ISO from a server. +func (c *ServerClient) DetachISO(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/detach_iso", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionDetachISOResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// EnableBackup enables backup for a server. Pass in an empty backup window to let the +// API pick a window for you. See the API documentation at docs.hetzner.cloud for a list +// of valid backup windows. +func (c *ServerClient) EnableBackup(ctx context.Context, server *Server, window string) (*Action, *Response, error) { + reqBody := schema.ServerActionEnableBackupRequest{} + if window != "" { + reqBody.BackupWindow = Ptr(window) + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/enable_backup", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionEnableBackupResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// DisableBackup disables backup for a server. +func (c *ServerClient) DisableBackup(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/disable_backup", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionDisableBackupResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// ServerChangeTypeOpts specifies options for changing a server's type. +type ServerChangeTypeOpts struct { + ServerType *ServerType // new server type + UpgradeDisk bool // whether disk should be upgraded +} + +// ChangeType changes a server's type. +func (c *ServerClient) ChangeType(ctx context.Context, server *Server, opts ServerChangeTypeOpts) (*Action, *Response, error) { + reqBody := schema.ServerActionChangeTypeRequest{ + UpgradeDisk: opts.UpgradeDisk, + } + if opts.ServerType.ID != 0 { + reqBody.ServerType = opts.ServerType.ID + } else { + reqBody.ServerType = opts.ServerType.Name + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/change_type", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionChangeTypeResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// ChangeDNSPtr changes or resets the reverse DNS pointer for a server IP address. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (c *ServerClient) ChangeDNSPtr(ctx context.Context, server *Server, ip string, ptr *string) (*Action, *Response, error) { + netIP := net.ParseIP(ip) + if netIP == nil { + return nil, nil, InvalidIPError{ip} + } + return server.changeDNSPtr(ctx, c.client, net.ParseIP(ip), ptr) +} + +// ServerChangeProtectionOpts specifies options for changing the resource protection level of a server. +type ServerChangeProtectionOpts struct { + Rebuild *bool + Delete *bool +} + +// ChangeProtection changes the resource protection level of a server. +func (c *ServerClient) ChangeProtection(ctx context.Context, server *Server, opts ServerChangeProtectionOpts) (*Action, *Response, error) { + reqBody := schema.ServerActionChangeProtectionRequest{ + Rebuild: opts.Rebuild, + Delete: opts.Delete, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/change_protection", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionChangeProtectionResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// ServerRequestConsoleResult is the result of requesting a WebSocket VNC console. +type ServerRequestConsoleResult struct { + Action *Action + WSSURL string + Password string +} + +// RequestConsole requests a WebSocket VNC console. +func (c *ServerClient) RequestConsole(ctx context.Context, server *Server) (ServerRequestConsoleResult, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/request_console", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return ServerRequestConsoleResult{}, nil, err + } + + respBody := schema.ServerActionRequestConsoleResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return ServerRequestConsoleResult{}, resp, err + } + return ServerRequestConsoleResult{ + Action: ActionFromSchema(respBody.Action), + WSSURL: respBody.WSSURL, + Password: respBody.Password, + }, resp, nil +} + +// ServerAttachToNetworkOpts specifies options for attaching a server to a network. +type ServerAttachToNetworkOpts struct { + Network *Network + IP net.IP + AliasIPs []net.IP +} + +// AttachToNetwork attaches a server to a network. +func (c *ServerClient) AttachToNetwork(ctx context.Context, server *Server, opts ServerAttachToNetworkOpts) (*Action, *Response, error) { + reqBody := schema.ServerActionAttachToNetworkRequest{ + Network: opts.Network.ID, + } + if opts.IP != nil { + reqBody.IP = Ptr(opts.IP.String()) + } + for _, aliasIP := range opts.AliasIPs { + reqBody.AliasIPs = append(reqBody.AliasIPs, Ptr(aliasIP.String())) + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/attach_to_network", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionAttachToNetworkResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// ServerDetachFromNetworkOpts specifies options for detaching a server from a network. +type ServerDetachFromNetworkOpts struct { + Network *Network +} + +// DetachFromNetwork detaches a server from a network. +func (c *ServerClient) DetachFromNetwork(ctx context.Context, server *Server, opts ServerDetachFromNetworkOpts) (*Action, *Response, error) { + reqBody := schema.ServerActionDetachFromNetworkRequest{ + Network: opts.Network.ID, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/servers/%d/actions/detach_from_network", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionDetachFromNetworkResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// ServerChangeAliasIPsOpts specifies options for changing the alias ips of an already attached network. +type ServerChangeAliasIPsOpts struct { + Network *Network + AliasIPs []net.IP +} + +// ChangeAliasIPs changes a server's alias IPs in a network. +func (c *ServerClient) ChangeAliasIPs(ctx context.Context, server *Server, opts ServerChangeAliasIPsOpts) (*Action, *Response, error) { + reqBody := schema.ServerActionChangeAliasIPsRequest{ + Network: opts.Network.ID, + AliasIPs: []string{}, + } + for _, aliasIP := range opts.AliasIPs { + reqBody.AliasIPs = append(reqBody.AliasIPs, aliasIP.String()) + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + path := fmt.Sprintf("/servers/%d/actions/change_alias_ips", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionDetachFromNetworkResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// ServerMetricType is the type of available metrics for servers. +type ServerMetricType string + +// Available types of server metrics. See Hetzner Cloud API documentation for +// details. +const ( + ServerMetricCPU ServerMetricType = "cpu" + ServerMetricDisk ServerMetricType = "disk" + ServerMetricNetwork ServerMetricType = "network" +) + +// ServerGetMetricsOpts configures the call to get metrics for a Server. +type ServerGetMetricsOpts struct { + Types []ServerMetricType + Start time.Time + End time.Time + Step int +} + +func (o *ServerGetMetricsOpts) addQueryParams(req *http.Request) error { + query := req.URL.Query() + + if len(o.Types) == 0 { + return fmt.Errorf("no metric types specified") + } + for _, typ := range o.Types { + query.Add("type", string(typ)) + } + + if o.Start.IsZero() { + return fmt.Errorf("no start time specified") + } + query.Add("start", o.Start.Format(time.RFC3339)) + + if o.End.IsZero() { + return fmt.Errorf("no end time specified") + } + query.Add("end", o.End.Format(time.RFC3339)) + + if o.Step > 0 { + query.Add("step", strconv.Itoa(o.Step)) + } + req.URL.RawQuery = query.Encode() + + return nil +} + +// ServerMetrics contains the metrics requested for a Server. +type ServerMetrics struct { + Start time.Time + End time.Time + Step float64 + TimeSeries map[string][]ServerMetricsValue +} + +// ServerMetricsValue represents a single value in a time series of metrics. +type ServerMetricsValue struct { + Timestamp float64 + Value string +} + +// GetMetrics obtains metrics for Server. +func (c *ServerClient) GetMetrics(ctx context.Context, server *Server, opts ServerGetMetricsOpts) (*ServerMetrics, *Response, error) { + var respBody schema.ServerGetMetricsResponse + + if server == nil { + return nil, nil, fmt.Errorf("illegal argument: server is nil") + } + + path := fmt.Sprintf("/servers/%d/metrics", server.ID) + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, fmt.Errorf("new request: %v", err) + } + if err := opts.addQueryParams(req); err != nil { + return nil, nil, fmt.Errorf("add query params: %v", err) + } + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, nil, fmt.Errorf("get metrics: %v", err) + } + ms, err := serverMetricsFromSchema(&respBody) + if err != nil { + return nil, nil, fmt.Errorf("convert response body: %v", err) + } + return ms, resp, nil +} + +func (c *ServerClient) AddToPlacementGroup(ctx context.Context, server *Server, placementGroup *PlacementGroup) (*Action, *Response, error) { + reqBody := schema.ServerActionAddToPlacementGroupRequest{ + PlacementGroup: placementGroup.ID, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + path := fmt.Sprintf("/servers/%d/actions/add_to_placement_group", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionAddToPlacementGroupResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +func (c *ServerClient) RemoveFromPlacementGroup(ctx context.Context, server *Server) (*Action, *Response, error) { + path := fmt.Sprintf("/servers/%d/actions/remove_from_placement_group", server.ID) + req, err := c.client.NewRequest(ctx, "POST", path, nil) + if err != nil { + return nil, nil, err + } + + respBody := schema.ServerActionRemoveFromPlacementGroupResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/server_type.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/server_type.go new file mode 100644 index 000000000..029fe1ff6 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/server_type.go @@ -0,0 +1,159 @@ +package hcloud + +import ( + "context" + "fmt" + "net/url" + "strconv" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// ServerType represents a server type in the Hetzner Cloud. +type ServerType struct { + ID int64 + Name string + Description string + Cores int + Memory float32 + Disk int + StorageType StorageType + CPUType CPUType + Architecture Architecture + // IncludedTraffic is the free traffic per month in bytes + IncludedTraffic int64 + Pricings []ServerTypeLocationPricing + DeprecatableResource +} + +// StorageType specifies the type of storage. +type StorageType string + +const ( + // StorageTypeLocal is the type for local storage. + StorageTypeLocal StorageType = "local" + + // StorageTypeCeph is the type for remote storage. + StorageTypeCeph StorageType = "ceph" +) + +// CPUType specifies the type of the CPU. +type CPUType string + +const ( + // CPUTypeShared is the type for shared CPU. + CPUTypeShared CPUType = "shared" + + // CPUTypeDedicated is the type for dedicated CPU. + CPUTypeDedicated CPUType = "dedicated" +) + +// ServerTypeClient is a client for the server types API. +type ServerTypeClient struct { + client *Client +} + +// GetByID retrieves a server type by its ID. If the server type does not exist, nil is returned. +func (c *ServerTypeClient) GetByID(ctx context.Context, id int64) (*ServerType, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/server_types/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.ServerTypeGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return ServerTypeFromSchema(body.ServerType), resp, nil +} + +// GetByName retrieves a server type by its name. If the server type does not exist, nil is returned. +func (c *ServerTypeClient) GetByName(ctx context.Context, name string) (*ServerType, *Response, error) { + if name == "" { + return nil, nil, nil + } + serverTypes, response, err := c.List(ctx, ServerTypeListOpts{Name: name}) + if len(serverTypes) == 0 { + return nil, response, err + } + return serverTypes[0], response, err +} + +// Get retrieves a server type by its ID if the input can be parsed as an integer, otherwise it +// retrieves a server type by its name. If the server type does not exist, nil is returned. +func (c *ServerTypeClient) Get(ctx context.Context, idOrName string) (*ServerType, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// ServerTypeListOpts specifies options for listing server types. +type ServerTypeListOpts struct { + ListOpts + Name string + Sort []string +} + +func (l ServerTypeListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of server types for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *ServerTypeClient) List(ctx context.Context, opts ServerTypeListOpts) ([]*ServerType, *Response, error) { + path := "/server_types?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.ServerTypeListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + serverTypes := make([]*ServerType, 0, len(body.ServerTypes)) + for _, s := range body.ServerTypes { + serverTypes = append(serverTypes, ServerTypeFromSchema(s)) + } + return serverTypes, resp, nil +} + +// All returns all server types. +func (c *ServerTypeClient) All(ctx context.Context) ([]*ServerType, error) { + return c.AllWithOpts(ctx, ServerTypeListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all server types for the given options. +func (c *ServerTypeClient) AllWithOpts(ctx context.Context, opts ServerTypeListOpts) ([]*ServerType, error) { + allServerTypes := []*ServerType{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + serverTypes, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allServerTypes = append(allServerTypes, serverTypes...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allServerTypes, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/ssh_key.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/ssh_key.go new file mode 100644 index 000000000..45d4558f9 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/ssh_key.go @@ -0,0 +1,237 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// SSHKey represents a SSH key in the Hetzner Cloud. +type SSHKey struct { + ID int64 + Name string + Fingerprint string + PublicKey string + Labels map[string]string + Created time.Time +} + +// SSHKeyClient is a client for the SSH keys API. +type SSHKeyClient struct { + client *Client +} + +// GetByID retrieves a SSH key by its ID. If the SSH key does not exist, nil is returned. +func (c *SSHKeyClient) GetByID(ctx context.Context, id int64) (*SSHKey, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/ssh_keys/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.SSHKeyGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return SSHKeyFromSchema(body.SSHKey), resp, nil +} + +// GetByName retrieves a SSH key by its name. If the SSH key does not exist, nil is returned. +func (c *SSHKeyClient) GetByName(ctx context.Context, name string) (*SSHKey, *Response, error) { + if name == "" { + return nil, nil, nil + } + sshKeys, response, err := c.List(ctx, SSHKeyListOpts{Name: name}) + if len(sshKeys) == 0 { + return nil, response, err + } + return sshKeys[0], response, err +} + +// GetByFingerprint retreives a SSH key by its fingerprint. If the SSH key does not exist, nil is returned. +func (c *SSHKeyClient) GetByFingerprint(ctx context.Context, fingerprint string) (*SSHKey, *Response, error) { + sshKeys, response, err := c.List(ctx, SSHKeyListOpts{Fingerprint: fingerprint}) + if len(sshKeys) == 0 { + return nil, response, err + } + return sshKeys[0], response, err +} + +// Get retrieves a SSH key by its ID if the input can be parsed as an integer, otherwise it +// retrieves a SSH key by its name. If the SSH key does not exist, nil is returned. +func (c *SSHKeyClient) Get(ctx context.Context, idOrName string) (*SSHKey, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// SSHKeyListOpts specifies options for listing SSH keys. +type SSHKeyListOpts struct { + ListOpts + Name string + Fingerprint string + Sort []string +} + +func (l SSHKeyListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + if l.Fingerprint != "" { + vals.Add("fingerprint", l.Fingerprint) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of SSH keys for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *SSHKeyClient) List(ctx context.Context, opts SSHKeyListOpts) ([]*SSHKey, *Response, error) { + path := "/ssh_keys?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.SSHKeyListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + sshKeys := make([]*SSHKey, 0, len(body.SSHKeys)) + for _, s := range body.SSHKeys { + sshKeys = append(sshKeys, SSHKeyFromSchema(s)) + } + return sshKeys, resp, nil +} + +// All returns all SSH keys. +func (c *SSHKeyClient) All(ctx context.Context) ([]*SSHKey, error) { + return c.AllWithOpts(ctx, SSHKeyListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all SSH keys with the given options. +func (c *SSHKeyClient) AllWithOpts(ctx context.Context, opts SSHKeyListOpts) ([]*SSHKey, error) { + allSSHKeys := []*SSHKey{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + sshKeys, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allSSHKeys = append(allSSHKeys, sshKeys...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allSSHKeys, nil +} + +// SSHKeyCreateOpts specifies parameters for creating a SSH key. +type SSHKeyCreateOpts struct { + Name string + PublicKey string + Labels map[string]string +} + +// Validate checks if options are valid. +func (o SSHKeyCreateOpts) Validate() error { + if o.Name == "" { + return errors.New("missing name") + } + if o.PublicKey == "" { + return errors.New("missing public key") + } + return nil +} + +// Create creates a new SSH key with the given options. +func (c *SSHKeyClient) Create(ctx context.Context, opts SSHKeyCreateOpts) (*SSHKey, *Response, error) { + if err := opts.Validate(); err != nil { + return nil, nil, err + } + reqBody := schema.SSHKeyCreateRequest{ + Name: opts.Name, + PublicKey: opts.PublicKey, + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + req, err := c.client.NewRequest(ctx, "POST", "/ssh_keys", bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.SSHKeyCreateResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return SSHKeyFromSchema(respBody.SSHKey), resp, nil +} + +// Delete deletes a SSH key. +func (c *SSHKeyClient) Delete(ctx context.Context, sshKey *SSHKey) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/ssh_keys/%d", sshKey.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// SSHKeyUpdateOpts specifies options for updating a SSH key. +type SSHKeyUpdateOpts struct { + Name string + Labels map[string]string +} + +// Update updates a SSH key. +func (c *SSHKeyClient) Update(ctx context.Context, sshKey *SSHKey, opts SSHKeyUpdateOpts) (*SSHKey, *Response, error) { + reqBody := schema.SSHKeyUpdateRequest{ + Name: opts.Name, + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/ssh_keys/%d", sshKey.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.SSHKeyUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return SSHKeyFromSchema(respBody.SSHKey), resp, nil +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/testing.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/testing.go new file mode 100644 index 000000000..63cd92f7b --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/testing.go @@ -0,0 +1,16 @@ +package hcloud + +import ( + "testing" + "time" +) + +func mustParseTime(t *testing.T, value string) time.Time { + t.Helper() + + ts, err := time.Parse(time.RFC3339, value) + if err != nil { + t.Fatalf("parse time: value %v: %v", value, err) + } + return ts +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/volume.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/volume.go new file mode 100644 index 000000000..3f23c6da7 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/volume.go @@ -0,0 +1,404 @@ +package hcloud + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "strconv" + "time" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" +) + +// Volume represents a volume in the Hetzner Cloud. +type Volume struct { + ID int64 + Name string + Status VolumeStatus + Server *Server + Location *Location + Size int + Protection VolumeProtection + Labels map[string]string + LinuxDevice string + Created time.Time +} + +// VolumeProtection represents the protection level of a volume. +type VolumeProtection struct { + Delete bool +} + +// VolumeClient is a client for the volume API. +type VolumeClient struct { + client *Client + Action *ResourceActionClient +} + +// VolumeStatus specifies a volume's status. +type VolumeStatus string + +const ( + // VolumeStatusCreating is the status when a volume is being created. + VolumeStatusCreating VolumeStatus = "creating" + + // VolumeStatusAvailable is the status when a volume is available. + VolumeStatusAvailable VolumeStatus = "available" +) + +// GetByID retrieves a volume by its ID. If the volume does not exist, nil is returned. +func (c *VolumeClient) GetByID(ctx context.Context, id int64) (*Volume, *Response, error) { + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/volumes/%d", id), nil) + if err != nil { + return nil, nil, err + } + + var body schema.VolumeGetResponse + resp, err := c.client.Do(req, &body) + if err != nil { + if IsError(err, ErrorCodeNotFound) { + return nil, resp, nil + } + return nil, nil, err + } + return VolumeFromSchema(body.Volume), resp, nil +} + +// GetByName retrieves a volume by its name. If the volume does not exist, nil is returned. +func (c *VolumeClient) GetByName(ctx context.Context, name string) (*Volume, *Response, error) { + if name == "" { + return nil, nil, nil + } + volumes, response, err := c.List(ctx, VolumeListOpts{Name: name}) + if len(volumes) == 0 { + return nil, response, err + } + return volumes[0], response, err +} + +// Get retrieves a volume by its ID if the input can be parsed as an integer, otherwise it +// retrieves a volume by its name. If the volume does not exist, nil is returned. +func (c *VolumeClient) Get(ctx context.Context, idOrName string) (*Volume, *Response, error) { + if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil { + return c.GetByID(ctx, id) + } + return c.GetByName(ctx, idOrName) +} + +// VolumeListOpts specifies options for listing volumes. +type VolumeListOpts struct { + ListOpts + Name string + Status []VolumeStatus + Sort []string +} + +func (l VolumeListOpts) values() url.Values { + vals := l.ListOpts.Values() + if l.Name != "" { + vals.Add("name", l.Name) + } + for _, status := range l.Status { + vals.Add("status", string(status)) + } + for _, sort := range l.Sort { + vals.Add("sort", sort) + } + return vals +} + +// List returns a list of volumes for a specific page. +// +// Please note that filters specified in opts are not taken into account +// when their value corresponds to their zero value or when they are empty. +func (c *VolumeClient) List(ctx context.Context, opts VolumeListOpts) ([]*Volume, *Response, error) { + path := "/volumes?" + opts.values().Encode() + req, err := c.client.NewRequest(ctx, "GET", path, nil) + if err != nil { + return nil, nil, err + } + + var body schema.VolumeListResponse + resp, err := c.client.Do(req, &body) + if err != nil { + return nil, nil, err + } + volumes := make([]*Volume, 0, len(body.Volumes)) + for _, s := range body.Volumes { + volumes = append(volumes, VolumeFromSchema(s)) + } + return volumes, resp, nil +} + +// All returns all volumes. +func (c *VolumeClient) All(ctx context.Context) ([]*Volume, error) { + return c.AllWithOpts(ctx, VolumeListOpts{ListOpts: ListOpts{PerPage: 50}}) +} + +// AllWithOpts returns all volumes with the given options. +func (c *VolumeClient) AllWithOpts(ctx context.Context, opts VolumeListOpts) ([]*Volume, error) { + allVolumes := []*Volume{} + + err := c.client.all(func(page int) (*Response, error) { + opts.Page = page + volumes, resp, err := c.List(ctx, opts) + if err != nil { + return resp, err + } + allVolumes = append(allVolumes, volumes...) + return resp, nil + }) + if err != nil { + return nil, err + } + + return allVolumes, nil +} + +// VolumeCreateOpts specifies parameters for creating a volume. +type VolumeCreateOpts struct { + Name string + Size int + Server *Server + Location *Location + Labels map[string]string + Automount *bool + Format *string +} + +// Validate checks if options are valid. +func (o VolumeCreateOpts) Validate() error { + if o.Name == "" { + return errors.New("missing name") + } + if o.Size <= 0 { + return errors.New("size must be greater than 0") + } + if o.Server == nil && o.Location == nil { + return errors.New("one of server or location must be provided") + } + if o.Server != nil && o.Location != nil { + return errors.New("only one of server or location must be provided") + } + if o.Server == nil && (o.Automount != nil && *o.Automount) { + return errors.New("server must be provided when automount is true") + } + return nil +} + +// VolumeCreateResult is the result of creating a volume. +type VolumeCreateResult struct { + Volume *Volume + Action *Action + NextActions []*Action +} + +// Create creates a new volume with the given options. +func (c *VolumeClient) Create(ctx context.Context, opts VolumeCreateOpts) (VolumeCreateResult, *Response, error) { + if err := opts.Validate(); err != nil { + return VolumeCreateResult{}, nil, err + } + reqBody := schema.VolumeCreateRequest{ + Name: opts.Name, + Size: opts.Size, + Automount: opts.Automount, + Format: opts.Format, + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + if opts.Server != nil { + reqBody.Server = Ptr(opts.Server.ID) + } + if opts.Location != nil { + if opts.Location.ID != 0 { + reqBody.Location = opts.Location.ID + } else { + reqBody.Location = opts.Location.Name + } + } + + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return VolumeCreateResult{}, nil, err + } + + req, err := c.client.NewRequest(ctx, "POST", "/volumes", bytes.NewReader(reqBodyData)) + if err != nil { + return VolumeCreateResult{}, nil, err + } + + var respBody schema.VolumeCreateResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return VolumeCreateResult{}, resp, err + } + + var action *Action + if respBody.Action != nil { + action = ActionFromSchema(*respBody.Action) + } + + return VolumeCreateResult{ + Volume: VolumeFromSchema(respBody.Volume), + Action: action, + NextActions: ActionsFromSchema(respBody.NextActions), + }, resp, nil +} + +// Delete deletes a volume. +func (c *VolumeClient) Delete(ctx context.Context, volume *Volume) (*Response, error) { + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/volumes/%d", volume.ID), nil) + if err != nil { + return nil, err + } + return c.client.Do(req, nil) +} + +// VolumeUpdateOpts specifies options for updating a volume. +type VolumeUpdateOpts struct { + Name string + Labels map[string]string +} + +// Update updates a volume. +func (c *VolumeClient) Update(ctx context.Context, volume *Volume, opts VolumeUpdateOpts) (*Volume, *Response, error) { + reqBody := schema.VolumeUpdateRequest{ + Name: opts.Name, + } + if opts.Labels != nil { + reqBody.Labels = &opts.Labels + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/volumes/%d", volume.ID) + req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.VolumeUpdateResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return VolumeFromSchema(respBody.Volume), resp, nil +} + +// VolumeAttachOpts specifies options for attaching a volume. +type VolumeAttachOpts struct { + Server *Server + Automount *bool +} + +// AttachWithOpts attaches a volume to a server. +func (c *VolumeClient) AttachWithOpts(ctx context.Context, volume *Volume, opts VolumeAttachOpts) (*Action, *Response, error) { + reqBody := schema.VolumeActionAttachVolumeRequest{ + Server: opts.Server.ID, + Automount: opts.Automount, + } + + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/volumes/%d/actions/attach", volume.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.VolumeActionAttachVolumeResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// Attach attaches a volume to a server. +func (c *VolumeClient) Attach(ctx context.Context, volume *Volume, server *Server) (*Action, *Response, error) { + return c.AttachWithOpts(ctx, volume, VolumeAttachOpts{Server: server}) +} + +// Detach detaches a volume from a server. +func (c *VolumeClient) Detach(ctx context.Context, volume *Volume) (*Action, *Response, error) { + var reqBody schema.VolumeActionDetachVolumeRequest + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/volumes/%d/actions/detach", volume.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody schema.VolumeActionDetachVolumeResponse + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + +// VolumeChangeProtectionOpts specifies options for changing the resource protection level of a volume. +type VolumeChangeProtectionOpts struct { + Delete *bool +} + +// ChangeProtection changes the resource protection level of a volume. +func (c *VolumeClient) ChangeProtection(ctx context.Context, volume *Volume, opts VolumeChangeProtectionOpts) (*Action, *Response, error) { + reqBody := schema.VolumeActionChangeProtectionRequest{ + Delete: opts.Delete, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/volumes/%d/actions/change_protection", volume.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.VolumeActionChangeProtectionResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} + +// Resize changes the size of a volume. +func (c *VolumeClient) Resize(ctx context.Context, volume *Volume, size int) (*Action, *Response, error) { + reqBody := schema.VolumeActionResizeVolumeRequest{ + Size: size, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/volumes/%d/actions/resize", volume.ID) + req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + respBody := schema.VolumeActionResizeVolumeResponse{} + resp, err := c.client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, err +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_action_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_action_client_iface.go new file mode 100644 index 000000000..1917574a9 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_action_client_iface.go @@ -0,0 +1,60 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IActionClient ... +type IActionClient interface { + // GetByID retrieves an action by its ID. If the action does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Action, *Response, error) + // List returns a list of actions for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts ActionListOpts) ([]*Action, *Response, error) + // All returns all actions. + All(ctx context.Context) ([]*Action, error) + // AllWithOpts returns all actions for the given options. + AllWithOpts(ctx context.Context, opts ActionListOpts) ([]*Action, error) + // WatchOverallProgress watches several actions' progress until they complete + // with success or error. This watching happens in a goroutine and updates are + // provided through the two returned channels: + // + // - The first channel receives percentage updates of the progress, based on + // the number of completed versus total watched actions. The return value + // is an int between 0 and 100. + // - The second channel returned receives errors for actions that did not + // complete successfully, as well as any errors that happened while + // querying the API. + // + // By default, the method keeps watching until all actions have finished + // processing. If you want to be able to cancel the method or configure a + // timeout, use the [context.Context]. Once the method has stopped watching, + // both returned channels are closed. + // + // WatchOverallProgress uses the [WithPollBackoffFunc] of the [Client] to wait + // until sending the next request. + WatchOverallProgress(ctx context.Context, actions []*Action) (<-chan int, <-chan error) + // WatchProgress watches one action's progress until it completes with success + // or error. This watching happens in a goroutine and updates are provided + // through the two returned channels: + // + // - The first channel receives percentage updates of the progress, based on + // the progress percentage indicated by the API. The return value is an int + // between 0 and 100. + // - The second channel receives any errors that happened while querying the + // API, as well as the error of the action if it did not complete + // successfully, or nil if it did. + // + // By default, the method keeps watching until the action has finished + // processing. If you want to be able to cancel the method or configure a + // timeout, use the [context.Context]. Once the method has stopped watching, + // both returned channels are closed. + // + // WatchProgress uses the [WithPollBackoffFunc] of the [Client] to wait until + // sending the next request. + WatchProgress(ctx context.Context, action *Action) (<-chan int, <-chan error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_certificate_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_certificate_client_iface.go new file mode 100644 index 000000000..94583925f --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_certificate_client_iface.go @@ -0,0 +1,40 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// ICertificateClient ... +type ICertificateClient interface { + // GetByID retrieves a Certificate by its ID. If the Certificate does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Certificate, *Response, error) + // GetByName retrieves a Certificate by its name. If the Certificate does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*Certificate, *Response, error) + // Get retrieves a Certificate by its ID if the input can be parsed as an integer, otherwise it + // retrieves a Certificate by its name. If the Certificate does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*Certificate, *Response, error) + // List returns a list of Certificates for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts CertificateListOpts) ([]*Certificate, *Response, error) + // All returns all Certificates. + All(ctx context.Context) ([]*Certificate, error) + // AllWithOpts returns all Certificates for the given options. + AllWithOpts(ctx context.Context, opts CertificateListOpts) ([]*Certificate, error) + // Create creates a new uploaded certificate. + // + // Create returns an error for certificates of any other type. Use + // CreateCertificate to create such certificates. + Create(ctx context.Context, opts CertificateCreateOpts) (*Certificate, *Response, error) + // CreateCertificate creates a new certificate of any type. + CreateCertificate(ctx context.Context, opts CertificateCreateOpts) (CertificateCreateResult, *Response, error) + // Update updates a Certificate. + Update(ctx context.Context, certificate *Certificate, opts CertificateUpdateOpts) (*Certificate, *Response, error) + // Delete deletes a certificate. + Delete(ctx context.Context, certificate *Certificate) (*Response, error) + // RetryIssuance retries the issuance of a failed managed certificate. + RetryIssuance(ctx context.Context, certificate *Certificate) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_datacenter_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_datacenter_client_iface.go new file mode 100644 index 000000000..f93767567 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_datacenter_client_iface.go @@ -0,0 +1,27 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IDatacenterClient ... +type IDatacenterClient interface { + // GetByID retrieves a datacenter by its ID. If the datacenter does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Datacenter, *Response, error) + // GetByName retrieves a datacenter by its name. If the datacenter does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*Datacenter, *Response, error) + // Get retrieves a datacenter by its ID if the input can be parsed as an integer, otherwise it + // retrieves a datacenter by its name. If the datacenter does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*Datacenter, *Response, error) + // List returns a list of datacenters for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts DatacenterListOpts) ([]*Datacenter, *Response, error) + // All returns all datacenters. + All(ctx context.Context) ([]*Datacenter, error) + // AllWithOpts returns all datacenters for the given options. + AllWithOpts(ctx context.Context, opts DatacenterListOpts) ([]*Datacenter, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_firewall_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_firewall_client_iface.go new file mode 100644 index 000000000..ce6481158 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_firewall_client_iface.go @@ -0,0 +1,37 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IFirewallClient ... +type IFirewallClient interface { + // GetByID retrieves a Firewall by its ID. If the Firewall does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Firewall, *Response, error) + // GetByName retrieves a Firewall by its name. If the Firewall does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*Firewall, *Response, error) + // Get retrieves a Firewall by its ID if the input can be parsed as an integer, otherwise it + // retrieves a Firewall by its name. If the Firewall does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*Firewall, *Response, error) + // List returns a list of Firewalls for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts FirewallListOpts) ([]*Firewall, *Response, error) + // All returns all Firewalls. + All(ctx context.Context) ([]*Firewall, error) + // AllWithOpts returns all Firewalls for the given options. + AllWithOpts(ctx context.Context, opts FirewallListOpts) ([]*Firewall, error) + // Create creates a new Firewall. + Create(ctx context.Context, opts FirewallCreateOpts) (FirewallCreateResult, *Response, error) + // Update updates a Firewall. + Update(ctx context.Context, firewall *Firewall, opts FirewallUpdateOpts) (*Firewall, *Response, error) + // Delete deletes a Firewall. + Delete(ctx context.Context, firewall *Firewall) (*Response, error) + // SetRules sets the rules of a Firewall. + SetRules(ctx context.Context, firewall *Firewall, opts FirewallSetRulesOpts) ([]*Action, *Response, error) + ApplyResources(ctx context.Context, firewall *Firewall, resources []FirewallResource) ([]*Action, *Response, error) + RemoveResources(ctx context.Context, firewall *Firewall, resources []FirewallResource) ([]*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_floating_ip_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_floating_ip_client_iface.go new file mode 100644 index 000000000..4d71be269 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_floating_ip_client_iface.go @@ -0,0 +1,43 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IFloatingIPClient ... +type IFloatingIPClient interface { + // GetByID retrieves a Floating IP by its ID. If the Floating IP does not exist, + // nil is returned. + GetByID(ctx context.Context, id int64) (*FloatingIP, *Response, error) + // GetByName retrieves a Floating IP by its name. If the Floating IP does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*FloatingIP, *Response, error) + // Get retrieves a Floating IP by its ID if the input can be parsed as an integer, otherwise it + // retrieves a Floating IP by its name. If the Floating IP does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*FloatingIP, *Response, error) + // List returns a list of Floating IPs for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts FloatingIPListOpts) ([]*FloatingIP, *Response, error) + // All returns all Floating IPs. + All(ctx context.Context) ([]*FloatingIP, error) + // AllWithOpts returns all Floating IPs for the given options. + AllWithOpts(ctx context.Context, opts FloatingIPListOpts) ([]*FloatingIP, error) + // Create creates a Floating IP. + Create(ctx context.Context, opts FloatingIPCreateOpts) (FloatingIPCreateResult, *Response, error) + // Delete deletes a Floating IP. + Delete(ctx context.Context, floatingIP *FloatingIP) (*Response, error) + // Update updates a Floating IP. + Update(ctx context.Context, floatingIP *FloatingIP, opts FloatingIPUpdateOpts) (*FloatingIP, *Response, error) + // Assign assigns a Floating IP to a server. + Assign(ctx context.Context, floatingIP *FloatingIP, server *Server) (*Action, *Response, error) + // Unassign unassigns a Floating IP from the currently assigned server. + Unassign(ctx context.Context, floatingIP *FloatingIP) (*Action, *Response, error) + // ChangeDNSPtr changes or resets the reverse DNS pointer for a Floating IP address. + // Pass a nil ptr to reset the reverse DNS pointer to its default value. + ChangeDNSPtr(ctx context.Context, floatingIP *FloatingIP, ip string, ptr *string) (*Action, *Response, error) + // ChangeProtection changes the resource protection level of a Floating IP. + ChangeProtection(ctx context.Context, floatingIP *FloatingIP, opts FloatingIPChangeProtectionOpts) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_image_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_image_client_iface.go new file mode 100644 index 000000000..17fbcd929 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_image_client_iface.go @@ -0,0 +1,48 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IImageClient ... +type IImageClient interface { + // GetByID retrieves an image by its ID. If the image does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Image, *Response, error) + // GetByName retrieves an image by its name. If the image does not exist, nil is returned. + // + // Deprecated: Use [ImageClient.GetByNameAndArchitecture] instead. + GetByName(ctx context.Context, name string) (*Image, *Response, error) + // GetByNameAndArchitecture retrieves an image by its name and architecture. If the image does not exist, + // nil is returned. + // In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should + // check for this in your calling method. + GetByNameAndArchitecture(ctx context.Context, name string, architecture Architecture) (*Image, *Response, error) + // Get retrieves an image by its ID if the input can be parsed as an integer, otherwise it + // retrieves an image by its name. If the image does not exist, nil is returned. + // + // Deprecated: Use [ImageClient.GetForArchitecture] instead. + Get(ctx context.Context, idOrName string) (*Image, *Response, error) + // GetForArchitecture retrieves an image by its ID if the input can be parsed as an integer, otherwise it + // retrieves an image by its name and architecture. If the image does not exist, nil is returned. + // + // In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should + // check for this in your calling method. + GetForArchitecture(ctx context.Context, idOrName string, architecture Architecture) (*Image, *Response, error) + // List returns a list of images for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts ImageListOpts) ([]*Image, *Response, error) + // All returns all images. + All(ctx context.Context) ([]*Image, error) + // AllWithOpts returns all images for the given options. + AllWithOpts(ctx context.Context, opts ImageListOpts) ([]*Image, error) + // Delete deletes an image. + Delete(ctx context.Context, image *Image) (*Response, error) + // Update updates an image. + Update(ctx context.Context, image *Image, opts ImageUpdateOpts) (*Image, *Response, error) + // ChangeProtection changes the resource protection level of an image. + ChangeProtection(ctx context.Context, image *Image, opts ImageChangeProtectionOpts) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_iso_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_iso_client_iface.go new file mode 100644 index 000000000..aff450edf --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_iso_client_iface.go @@ -0,0 +1,26 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IISOClient ... +type IISOClient interface { + // GetByID retrieves an ISO by its ID. + GetByID(ctx context.Context, id int64) (*ISO, *Response, error) + // GetByName retrieves an ISO by its name. + GetByName(ctx context.Context, name string) (*ISO, *Response, error) + // Get retrieves an ISO by its ID if the input can be parsed as an integer, otherwise it retrieves an ISO by its name. + Get(ctx context.Context, idOrName string) (*ISO, *Response, error) + // List returns a list of ISOs for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts ISOListOpts) ([]*ISO, *Response, error) + // All returns all ISOs. + All(ctx context.Context) ([]*ISO, error) + // AllWithOpts returns all ISOs for the given options. + AllWithOpts(ctx context.Context, opts ISOListOpts) ([]*ISO, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_load_balancer_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_load_balancer_client_iface.go new file mode 100644 index 000000000..2665f22b0 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_load_balancer_client_iface.go @@ -0,0 +1,71 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" + "net" +) + +// ILoadBalancerClient ... +type ILoadBalancerClient interface { + // GetByID retrieves a Load Balancer by its ID. If the Load Balancer does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*LoadBalancer, *Response, error) + // GetByName retrieves a Load Balancer by its name. If the Load Balancer does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*LoadBalancer, *Response, error) + // Get retrieves a Load Balancer by its ID if the input can be parsed as an integer, otherwise it + // retrieves a Load Balancer by its name. If the Load Balancer does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*LoadBalancer, *Response, error) + // List returns a list of Load Balancers for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts LoadBalancerListOpts) ([]*LoadBalancer, *Response, error) + // All returns all Load Balancers. + All(ctx context.Context) ([]*LoadBalancer, error) + // AllWithOpts returns all Load Balancers for the given options. + AllWithOpts(ctx context.Context, opts LoadBalancerListOpts) ([]*LoadBalancer, error) + // Update updates a Load Balancer. + Update(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerUpdateOpts) (*LoadBalancer, *Response, error) + // Create creates a new Load Balancer. + Create(ctx context.Context, opts LoadBalancerCreateOpts) (LoadBalancerCreateResult, *Response, error) + // Delete deletes a Load Balancer. + Delete(ctx context.Context, loadBalancer *LoadBalancer) (*Response, error) + // AddServerTarget adds a server target to a Load Balancer. + AddServerTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddServerTargetOpts) (*Action, *Response, error) + // RemoveServerTarget removes a server target from a Load Balancer. + RemoveServerTarget(ctx context.Context, loadBalancer *LoadBalancer, server *Server) (*Action, *Response, error) + // AddLabelSelectorTarget adds a label selector target to a Load Balancer. + AddLabelSelectorTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddLabelSelectorTargetOpts) (*Action, *Response, error) + // RemoveLabelSelectorTarget removes a label selector target from a Load Balancer. + RemoveLabelSelectorTarget(ctx context.Context, loadBalancer *LoadBalancer, labelSelector string) (*Action, *Response, error) + // AddIPTarget adds an IP target to a Load Balancer. + AddIPTarget(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddIPTargetOpts) (*Action, *Response, error) + // RemoveIPTarget removes an IP target from a Load Balancer. + RemoveIPTarget(ctx context.Context, loadBalancer *LoadBalancer, ip net.IP) (*Action, *Response, error) + // AddService adds a service to a Load Balancer. + AddService(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAddServiceOpts) (*Action, *Response, error) + // UpdateService updates a Load Balancer service. + UpdateService(ctx context.Context, loadBalancer *LoadBalancer, listenPort int, opts LoadBalancerUpdateServiceOpts) (*Action, *Response, error) + // DeleteService deletes a Load Balancer service. + DeleteService(ctx context.Context, loadBalancer *LoadBalancer, listenPort int) (*Action, *Response, error) + // ChangeProtection changes the resource protection level of a Load Balancer. + ChangeProtection(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeProtectionOpts) (*Action, *Response, error) + // ChangeAlgorithm changes the algorithm of a Load Balancer. + ChangeAlgorithm(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeAlgorithmOpts) (*Action, *Response, error) + // AttachToNetwork attaches a Load Balancer to a network. + AttachToNetwork(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerAttachToNetworkOpts) (*Action, *Response, error) + // DetachFromNetwork detaches a Load Balancer from a network. + DetachFromNetwork(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerDetachFromNetworkOpts) (*Action, *Response, error) + // EnablePublicInterface enables the Load Balancer's public network interface. + EnablePublicInterface(ctx context.Context, loadBalancer *LoadBalancer) (*Action, *Response, error) + // DisablePublicInterface disables the Load Balancer's public network interface. + DisablePublicInterface(ctx context.Context, loadBalancer *LoadBalancer) (*Action, *Response, error) + // ChangeType changes a Load Balancer's type. + ChangeType(ctx context.Context, loadBalancer *LoadBalancer, opts LoadBalancerChangeTypeOpts) (*Action, *Response, error) + // GetMetrics obtains metrics for a Load Balancer. + GetMetrics(ctx context.Context, lb *LoadBalancer, opts LoadBalancerGetMetricsOpts) (*LoadBalancerMetrics, *Response, error) + // ChangeDNSPtr changes or resets the reverse DNS pointer for a Load Balancer. + // Pass a nil ptr to reset the reverse DNS pointer to its default value. + ChangeDNSPtr(ctx context.Context, lb *LoadBalancer, ip string, ptr *string) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_load_balancer_type_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_load_balancer_type_client_iface.go new file mode 100644 index 000000000..fd3289d4d --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_load_balancer_type_client_iface.go @@ -0,0 +1,27 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// ILoadBalancerTypeClient ... +type ILoadBalancerTypeClient interface { + // GetByID retrieves a Load Balancer type by its ID. If the Load Balancer type does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*LoadBalancerType, *Response, error) + // GetByName retrieves a Load Balancer type by its name. If the Load Balancer type does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*LoadBalancerType, *Response, error) + // Get retrieves a Load Balancer type by its ID if the input can be parsed as an integer, otherwise it + // retrieves a Load Balancer type by its name. If the Load Balancer type does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*LoadBalancerType, *Response, error) + // List returns a list of Load Balancer types for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts LoadBalancerTypeListOpts) ([]*LoadBalancerType, *Response, error) + // All returns all Load Balancer types. + All(ctx context.Context) ([]*LoadBalancerType, error) + // AllWithOpts returns all Load Balancer types for the given options. + AllWithOpts(ctx context.Context, opts LoadBalancerTypeListOpts) ([]*LoadBalancerType, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_location_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_location_client_iface.go new file mode 100644 index 000000000..9da4d5f6b --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_location_client_iface.go @@ -0,0 +1,27 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// ILocationClient ... +type ILocationClient interface { + // GetByID retrieves a location by its ID. If the location does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Location, *Response, error) + // GetByName retrieves an location by its name. If the location does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*Location, *Response, error) + // Get retrieves a location by its ID if the input can be parsed as an integer, otherwise it + // retrieves a location by its name. If the location does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*Location, *Response, error) + // List returns a list of locations for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts LocationListOpts) ([]*Location, *Response, error) + // All returns all locations. + All(ctx context.Context) ([]*Location, error) + // AllWithOpts returns all locations for the given options. + AllWithOpts(ctx context.Context, opts LocationListOpts) ([]*Location, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_network_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_network_client_iface.go new file mode 100644 index 000000000..f8b752e34 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_network_client_iface.go @@ -0,0 +1,45 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// INetworkClient ... +type INetworkClient interface { + // GetByID retrieves a network by its ID. If the network does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Network, *Response, error) + // GetByName retrieves a network by its name. If the network does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*Network, *Response, error) + // Get retrieves a network by its ID if the input can be parsed as an integer, otherwise it + // retrieves a network by its name. If the network does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*Network, *Response, error) + // List returns a list of networks for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts NetworkListOpts) ([]*Network, *Response, error) + // All returns all networks. + All(ctx context.Context) ([]*Network, error) + // AllWithOpts returns all networks for the given options. + AllWithOpts(ctx context.Context, opts NetworkListOpts) ([]*Network, error) + // Delete deletes a network. + Delete(ctx context.Context, network *Network) (*Response, error) + // Update updates a network. + Update(ctx context.Context, network *Network, opts NetworkUpdateOpts) (*Network, *Response, error) + // Create creates a new network. + Create(ctx context.Context, opts NetworkCreateOpts) (*Network, *Response, error) + // ChangeIPRange changes the IP range of a network. + ChangeIPRange(ctx context.Context, network *Network, opts NetworkChangeIPRangeOpts) (*Action, *Response, error) + // AddSubnet adds a subnet to a network. + AddSubnet(ctx context.Context, network *Network, opts NetworkAddSubnetOpts) (*Action, *Response, error) + // DeleteSubnet deletes a subnet from a network. + DeleteSubnet(ctx context.Context, network *Network, opts NetworkDeleteSubnetOpts) (*Action, *Response, error) + // AddRoute adds a route to a network. + AddRoute(ctx context.Context, network *Network, opts NetworkAddRouteOpts) (*Action, *Response, error) + // DeleteRoute deletes a route from a network. + DeleteRoute(ctx context.Context, network *Network, opts NetworkDeleteRouteOpts) (*Action, *Response, error) + // ChangeProtection changes the resource protection level of a network. + ChangeProtection(ctx context.Context, network *Network, opts NetworkChangeProtectionOpts) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_placement_group_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_placement_group_client_iface.go new file mode 100644 index 000000000..9fadd4f2c --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_placement_group_client_iface.go @@ -0,0 +1,33 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IPlacementGroupClient ... +type IPlacementGroupClient interface { + // GetByID retrieves a PlacementGroup by its ID. If the PlacementGroup does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*PlacementGroup, *Response, error) + // GetByName retrieves a PlacementGroup by its name. If the PlacementGroup does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*PlacementGroup, *Response, error) + // Get retrieves a PlacementGroup by its ID if the input can be parsed as an integer, otherwise it + // retrieves a PlacementGroup by its name. If the PlacementGroup does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*PlacementGroup, *Response, error) + // List returns a list of PlacementGroups for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts PlacementGroupListOpts) ([]*PlacementGroup, *Response, error) + // All returns all PlacementGroups. + All(ctx context.Context) ([]*PlacementGroup, error) + // AllWithOpts returns all PlacementGroups for the given options. + AllWithOpts(ctx context.Context, opts PlacementGroupListOpts) ([]*PlacementGroup, error) + // Create creates a new PlacementGroup. + Create(ctx context.Context, opts PlacementGroupCreateOpts) (PlacementGroupCreateResult, *Response, error) + // Update updates a PlacementGroup. + Update(ctx context.Context, placementGroup *PlacementGroup, opts PlacementGroupUpdateOpts) (*PlacementGroup, *Response, error) + // Delete deletes a PlacementGroup. + Delete(ctx context.Context, placementGroup *PlacementGroup) (*Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_pricing_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_pricing_client_iface.go new file mode 100644 index 000000000..cd4068c62 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_pricing_client_iface.go @@ -0,0 +1,13 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IPricingClient ... +type IPricingClient interface { + // Get retrieves pricing information. + Get(ctx context.Context) (Pricing, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_primary_ip_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_primary_ip_client_iface.go new file mode 100644 index 000000000..6b8e617e2 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_primary_ip_client_iface.go @@ -0,0 +1,43 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IPrimaryIPClient ... +type IPrimaryIPClient interface { + // GetByID retrieves a Primary IP by its ID. If the Primary IP does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*PrimaryIP, *Response, error) + // GetByIP retrieves a Primary IP by its IP Address. If the Primary IP does not exist, nil is returned. + GetByIP(ctx context.Context, ip string) (*PrimaryIP, *Response, error) + // GetByName retrieves a Primary IP by its name. If the Primary IP does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*PrimaryIP, *Response, error) + // Get retrieves a Primary IP by its ID if the input can be parsed as an integer, otherwise it + // retrieves a Primary IP by its name. If the Primary IP does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*PrimaryIP, *Response, error) + // List returns a list of Primary IPs for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts PrimaryIPListOpts) ([]*PrimaryIP, *Response, error) + // All returns all Primary IPs. + All(ctx context.Context) ([]*PrimaryIP, error) + // AllWithOpts returns all Primary IPs for the given options. + AllWithOpts(ctx context.Context, opts PrimaryIPListOpts) ([]*PrimaryIP, error) + // Create creates a Primary IP. + Create(ctx context.Context, reqBody PrimaryIPCreateOpts) (*PrimaryIPCreateResult, *Response, error) + // Delete deletes a Primary IP. + Delete(ctx context.Context, primaryIP *PrimaryIP) (*Response, error) + // Update updates a Primary IP. + Update(ctx context.Context, primaryIP *PrimaryIP, reqBody PrimaryIPUpdateOpts) (*PrimaryIP, *Response, error) + // Assign a Primary IP to a resource. + Assign(ctx context.Context, opts PrimaryIPAssignOpts) (*Action, *Response, error) + // Unassign a Primary IP from a resource. + Unassign(ctx context.Context, id int64) (*Action, *Response, error) + // ChangeDNSPtr Change the reverse DNS from a Primary IP. + ChangeDNSPtr(ctx context.Context, opts PrimaryIPChangeDNSPtrOpts) (*Action, *Response, error) + // ChangeProtection Changes the protection configuration of a Primary IP. + ChangeProtection(ctx context.Context, opts PrimaryIPChangeProtectionOpts) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_rdns_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_rdns_client_iface.go new file mode 100644 index 000000000..f92f18677 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_rdns_client_iface.go @@ -0,0 +1,15 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" + "net" +) + +// IRDNSClient ... +type IRDNSClient interface { + // ChangeDNSPtr changes or resets the reverse DNS pointer for a IP address. + // Pass a nil ptr to reset the reverse DNS pointer to its default value. + ChangeDNSPtr(ctx context.Context, rdns RDNSSupporter, ip net.IP, ptr *string) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_resource_action_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_resource_action_client_iface.go new file mode 100644 index 000000000..67910ab22 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_resource_action_client_iface.go @@ -0,0 +1,20 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IResourceActionClient ... +type IResourceActionClient interface { + // GetByID retrieves an action by its ID. If the action does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Action, *Response, error) + // List returns a list of actions for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts ActionListOpts) ([]*Action, *Response, error) + // All returns all actions for the given options. + All(ctx context.Context, opts ActionListOpts) ([]*Action, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_schema.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_schema.go new file mode 100644 index 000000000..a908ab360 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_schema.go @@ -0,0 +1,2476 @@ +// Code generated by github.com/jmattheis/goverter, DO NOT EDIT. +//go:build !goverter + +package hcloud + +import ( + schema "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" + "net" + "time" +) + +type converterImpl struct{} + +func (c *converterImpl) ActionFromSchema(source schema.Action) *Action { + var hcloudAction Action + hcloudAction.ID = source.ID + hcloudAction.Status = ActionStatus(source.Status) + hcloudAction.Command = source.Command + hcloudAction.Progress = source.Progress + hcloudAction.Started = source.Started + hcloudAction.Finished = c.pTimeTimeToTimeTime(source.Finished) + var pString *string + if source.Error != nil { + pString = &source.Error.Code + } + var xstring string + if pString != nil { + xstring = *pString + } + hcloudAction.ErrorCode = xstring + var pString2 *string + if source.Error != nil { + pString2 = &source.Error.Message + } + var xstring2 string + if pString2 != nil { + xstring2 = *pString2 + } + hcloudAction.ErrorMessage = xstring2 + var pHcloudActionResourceList []*ActionResource + if source.Resources != nil { + pHcloudActionResourceList = make([]*ActionResource, len(source.Resources)) + for i := 0; i < len(source.Resources); i++ { + pHcloudActionResourceList[i] = c.schemaActionResourceReferenceToPHcloudActionResource(source.Resources[i]) + } + } + hcloudAction.Resources = pHcloudActionResourceList + return &hcloudAction +} +func (c *converterImpl) ActionsFromSchema(source []schema.Action) []*Action { + var pHcloudActionList []*Action + if source != nil { + pHcloudActionList = make([]*Action, len(source)) + for i := 0; i < len(source); i++ { + pHcloudActionList[i] = c.ActionFromSchema(source[i]) + } + } + return pHcloudActionList +} +func (c *converterImpl) CertificateFromSchema(source schema.Certificate) *Certificate { + var hcloudCertificate Certificate + hcloudCertificate.ID = source.ID + hcloudCertificate.Name = source.Name + hcloudCertificate.Labels = source.Labels + hcloudCertificate.Type = CertificateType(source.Type) + hcloudCertificate.Certificate = source.Certificate + hcloudCertificate.Created = c.timeTimeToTimeTime(source.Created) + hcloudCertificate.NotValidBefore = c.timeTimeToTimeTime(source.NotValidBefore) + hcloudCertificate.NotValidAfter = c.timeTimeToTimeTime(source.NotValidAfter) + hcloudCertificate.DomainNames = source.DomainNames + hcloudCertificate.Fingerprint = source.Fingerprint + hcloudCertificate.Status = c.pSchemaCertificateStatusRefToPHcloudCertificateStatus(source.Status) + var hcloudCertificateUsedByRefList []CertificateUsedByRef + if source.UsedBy != nil { + hcloudCertificateUsedByRefList = make([]CertificateUsedByRef, len(source.UsedBy)) + for i := 0; i < len(source.UsedBy); i++ { + hcloudCertificateUsedByRefList[i] = c.schemaCertificateUsedByRefToHcloudCertificateUsedByRef(source.UsedBy[i]) + } + } + hcloudCertificate.UsedBy = hcloudCertificateUsedByRefList + return &hcloudCertificate +} +func (c *converterImpl) DatacenterFromSchema(source schema.Datacenter) *Datacenter { + var hcloudDatacenter Datacenter + hcloudDatacenter.ID = source.ID + hcloudDatacenter.Name = source.Name + hcloudDatacenter.Description = source.Description + hcloudDatacenter.Location = c.LocationFromSchema(source.Location) + hcloudDatacenter.ServerTypes = c.schemaDatacenterServerTypesToHcloudDatacenterServerTypes(source.ServerTypes) + return &hcloudDatacenter +} +func (c *converterImpl) DeprecationFromSchema(source *schema.DeprecationInfo) *DeprecationInfo { + var pHcloudDeprecationInfo *DeprecationInfo + if source != nil { + var hcloudDeprecationInfo DeprecationInfo + hcloudDeprecationInfo.Announced = c.timeTimeToTimeTime((*source).Announced) + hcloudDeprecationInfo.UnavailableAfter = c.timeTimeToTimeTime((*source).UnavailableAfter) + pHcloudDeprecationInfo = &hcloudDeprecationInfo + } + return pHcloudDeprecationInfo +} +func (c *converterImpl) ErrorFromSchema(source schema.Error) Error { + var hcloudError Error + hcloudError.Code = ErrorCode(source.Code) + hcloudError.Message = source.Message + hcloudError.Details = errorDetailsFromSchema(source.Details) + return hcloudError +} +func (c *converterImpl) FirewallFromSchema(source schema.Firewall) *Firewall { + var hcloudFirewall Firewall + hcloudFirewall.ID = source.ID + hcloudFirewall.Name = source.Name + hcloudFirewall.Labels = source.Labels + hcloudFirewall.Created = c.timeTimeToTimeTime(source.Created) + var hcloudFirewallRuleList []FirewallRule + if source.Rules != nil { + hcloudFirewallRuleList = make([]FirewallRule, len(source.Rules)) + for i := 0; i < len(source.Rules); i++ { + hcloudFirewallRuleList[i] = c.schemaFirewallRuleToHcloudFirewallRule(source.Rules[i]) + } + } + hcloudFirewall.Rules = hcloudFirewallRuleList + var hcloudFirewallResourceList []FirewallResource + if source.AppliedTo != nil { + hcloudFirewallResourceList = make([]FirewallResource, len(source.AppliedTo)) + for j := 0; j < len(source.AppliedTo); j++ { + hcloudFirewallResourceList[j] = c.schemaFirewallResourceToHcloudFirewallResource(source.AppliedTo[j]) + } + } + hcloudFirewall.AppliedTo = hcloudFirewallResourceList + return &hcloudFirewall +} +func (c *converterImpl) FloatingIPFromSchema(source schema.FloatingIP) *FloatingIP { + var hcloudFloatingIP FloatingIP + hcloudFloatingIP.ID = source.ID + var xstring string + if source.Description != nil { + xstring = *source.Description + } + hcloudFloatingIP.Description = xstring + hcloudFloatingIP.Created = c.timeTimeToTimeTime(source.Created) + hcloudFloatingIP.IP = ipFromFloatingIPSchema(source) + hcloudFloatingIP.Network = networkFromFloatingIPSchema(source) + hcloudFloatingIP.Type = FloatingIPType(source.Type) + var pHcloudServer *Server + if source.Server != nil { + hcloudServer := serverFromInt64(*source.Server) + pHcloudServer = &hcloudServer + } + hcloudFloatingIP.Server = pHcloudServer + hcloudFloatingIP.DNSPtr = mapFromFloatingIPDNSPtrSchema(source.DNSPtr) + hcloudFloatingIP.HomeLocation = c.LocationFromSchema(source.HomeLocation) + hcloudFloatingIP.Blocked = source.Blocked + hcloudFloatingIP.Protection = c.schemaFloatingIPProtectionToHcloudFloatingIPProtection(source.Protection) + hcloudFloatingIP.Labels = source.Labels + hcloudFloatingIP.Name = source.Name + return &hcloudFloatingIP +} +func (c *converterImpl) ISOFromSchema(source schema.ISO) *ISO { + hcloudISO := c.intISOFromSchema(source) + return &hcloudISO +} +func (c *converterImpl) ImageFromSchema(source schema.Image) *Image { + var hcloudImage Image + hcloudImage.ID = source.ID + var xstring string + if source.Name != nil { + xstring = *source.Name + } + hcloudImage.Name = xstring + hcloudImage.Type = ImageType(source.Type) + hcloudImage.Status = ImageStatus(source.Status) + hcloudImage.Description = source.Description + var xfloat32 float32 + if source.ImageSize != nil { + xfloat32 = *source.ImageSize + } + hcloudImage.ImageSize = xfloat32 + hcloudImage.DiskSize = source.DiskSize + hcloudImage.Created = c.pTimeTimeToTimeTime(source.Created) + hcloudImage.CreatedFrom = c.pSchemaImageCreatedFromToPHcloudServer(source.CreatedFrom) + var pHcloudServer *Server + if source.BoundTo != nil { + hcloudServer := serverFromInt64(*source.BoundTo) + pHcloudServer = &hcloudServer + } + hcloudImage.BoundTo = pHcloudServer + hcloudImage.RapidDeploy = source.RapidDeploy + hcloudImage.OSFlavor = source.OSFlavor + var xstring2 string + if source.OSVersion != nil { + xstring2 = *source.OSVersion + } + hcloudImage.OSVersion = xstring2 + hcloudImage.Architecture = Architecture(source.Architecture) + hcloudImage.Protection = c.schemaImageProtectionToHcloudImageProtection(source.Protection) + hcloudImage.Deprecated = c.pTimeTimeToTimeTime(source.Deprecated) + hcloudImage.Labels = source.Labels + hcloudImage.Deleted = c.pTimeTimeToTimeTime(source.Deleted) + return &hcloudImage +} +func (c *converterImpl) LoadBalancerFromSchema(source schema.LoadBalancer) *LoadBalancer { + var hcloudLoadBalancer LoadBalancer + hcloudLoadBalancer.ID = source.ID + hcloudLoadBalancer.Name = source.Name + hcloudLoadBalancer.PublicNet = c.schemaLoadBalancerPublicNetToHcloudLoadBalancerPublicNet(source.PublicNet) + var hcloudLoadBalancerPrivateNetList []LoadBalancerPrivateNet + if source.PrivateNet != nil { + hcloudLoadBalancerPrivateNetList = make([]LoadBalancerPrivateNet, len(source.PrivateNet)) + for i := 0; i < len(source.PrivateNet); i++ { + hcloudLoadBalancerPrivateNetList[i] = c.schemaLoadBalancerPrivateNetToHcloudLoadBalancerPrivateNet(source.PrivateNet[i]) + } + } + hcloudLoadBalancer.PrivateNet = hcloudLoadBalancerPrivateNetList + hcloudLoadBalancer.Location = c.LocationFromSchema(source.Location) + hcloudLoadBalancer.LoadBalancerType = c.LoadBalancerTypeFromSchema(source.LoadBalancerType) + hcloudLoadBalancer.Algorithm = c.schemaLoadBalancerAlgorithmToHcloudLoadBalancerAlgorithm(source.Algorithm) + var hcloudLoadBalancerServiceList []LoadBalancerService + if source.Services != nil { + hcloudLoadBalancerServiceList = make([]LoadBalancerService, len(source.Services)) + for j := 0; j < len(source.Services); j++ { + hcloudLoadBalancerServiceList[j] = c.LoadBalancerServiceFromSchema(source.Services[j]) + } + } + hcloudLoadBalancer.Services = hcloudLoadBalancerServiceList + var hcloudLoadBalancerTargetList []LoadBalancerTarget + if source.Targets != nil { + hcloudLoadBalancerTargetList = make([]LoadBalancerTarget, len(source.Targets)) + for k := 0; k < len(source.Targets); k++ { + hcloudLoadBalancerTargetList[k] = c.LoadBalancerTargetFromSchema(source.Targets[k]) + } + } + hcloudLoadBalancer.Targets = hcloudLoadBalancerTargetList + hcloudLoadBalancer.Protection = c.schemaLoadBalancerProtectionToHcloudLoadBalancerProtection(source.Protection) + hcloudLoadBalancer.Labels = source.Labels + hcloudLoadBalancer.Created = c.timeTimeToTimeTime(source.Created) + hcloudLoadBalancer.IncludedTraffic = source.IncludedTraffic + var xuint64 uint64 + if source.OutgoingTraffic != nil { + xuint64 = *source.OutgoingTraffic + } + hcloudLoadBalancer.OutgoingTraffic = xuint64 + var xuint642 uint64 + if source.IngoingTraffic != nil { + xuint642 = *source.IngoingTraffic + } + hcloudLoadBalancer.IngoingTraffic = xuint642 + return &hcloudLoadBalancer +} +func (c *converterImpl) LoadBalancerMetricsFromSchema(source *schema.LoadBalancerGetMetricsResponse) (*LoadBalancerMetrics, error) { + var pHcloudLoadBalancerMetrics *LoadBalancerMetrics + if source != nil { + var hcloudLoadBalancerMetrics LoadBalancerMetrics + hcloudLoadBalancerMetrics.Start = c.timeTimeToTimeTime((*source).Metrics.Start) + hcloudLoadBalancerMetrics.End = c.timeTimeToTimeTime((*source).Metrics.End) + hcloudLoadBalancerMetrics.Step = (*source).Metrics.Step + mapStringHcloudLoadBalancerMetricsValueList := make(map[string][]LoadBalancerMetricsValue, len((*source).Metrics.TimeSeries)) + for key, value := range (*source).Metrics.TimeSeries { + hcloudLoadBalancerMetricsValueList, err := loadBalancerMetricsTimeSeriesFromSchema(value) + if err != nil { + return nil, err + } + mapStringHcloudLoadBalancerMetricsValueList[key] = hcloudLoadBalancerMetricsValueList + } + hcloudLoadBalancerMetrics.TimeSeries = mapStringHcloudLoadBalancerMetricsValueList + pHcloudLoadBalancerMetrics = &hcloudLoadBalancerMetrics + } + return pHcloudLoadBalancerMetrics, nil +} +func (c *converterImpl) LoadBalancerServiceFromSchema(source schema.LoadBalancerService) LoadBalancerService { + var hcloudLoadBalancerService LoadBalancerService + hcloudLoadBalancerService.Protocol = LoadBalancerServiceProtocol(source.Protocol) + hcloudLoadBalancerService.ListenPort = source.ListenPort + hcloudLoadBalancerService.DestinationPort = source.DestinationPort + hcloudLoadBalancerService.Proxyprotocol = source.Proxyprotocol + hcloudLoadBalancerService.HTTP = c.pSchemaLoadBalancerServiceHTTPToHcloudLoadBalancerServiceHTTP(source.HTTP) + hcloudLoadBalancerService.HealthCheck = c.LoadBalancerServiceHealthCheckFromSchema(source.HealthCheck) + return hcloudLoadBalancerService +} +func (c *converterImpl) LoadBalancerServiceHealthCheckFromSchema(source *schema.LoadBalancerServiceHealthCheck) LoadBalancerServiceHealthCheck { + var hcloudLoadBalancerServiceHealthCheck LoadBalancerServiceHealthCheck + if source != nil { + var hcloudLoadBalancerServiceHealthCheck2 LoadBalancerServiceHealthCheck + hcloudLoadBalancerServiceHealthCheck2.Protocol = LoadBalancerServiceProtocol((*source).Protocol) + hcloudLoadBalancerServiceHealthCheck2.Port = (*source).Port + hcloudLoadBalancerServiceHealthCheck2.Interval = durationFromIntSeconds((*source).Interval) + hcloudLoadBalancerServiceHealthCheck2.Timeout = durationFromIntSeconds((*source).Timeout) + hcloudLoadBalancerServiceHealthCheck2.Retries = (*source).Retries + hcloudLoadBalancerServiceHealthCheck2.HTTP = c.pSchemaLoadBalancerServiceHealthCheckHTTPToPHcloudLoadBalancerServiceHealthCheckHTTP((*source).HTTP) + hcloudLoadBalancerServiceHealthCheck = hcloudLoadBalancerServiceHealthCheck2 + } + return hcloudLoadBalancerServiceHealthCheck +} +func (c *converterImpl) LoadBalancerTargetFromSchema(source schema.LoadBalancerTarget) LoadBalancerTarget { + var hcloudLoadBalancerTarget LoadBalancerTarget + hcloudLoadBalancerTarget.Type = LoadBalancerTargetType(source.Type) + hcloudLoadBalancerTarget.Server = c.pSchemaLoadBalancerTargetServerToPHcloudLoadBalancerTargetServer(source.Server) + hcloudLoadBalancerTarget.LabelSelector = c.pSchemaLoadBalancerTargetLabelSelectorToPHcloudLoadBalancerTargetLabelSelector(source.LabelSelector) + hcloudLoadBalancerTarget.IP = c.pSchemaLoadBalancerTargetIPToPHcloudLoadBalancerTargetIP(source.IP) + var hcloudLoadBalancerTargetHealthStatusList []LoadBalancerTargetHealthStatus + if source.HealthStatus != nil { + hcloudLoadBalancerTargetHealthStatusList = make([]LoadBalancerTargetHealthStatus, len(source.HealthStatus)) + for i := 0; i < len(source.HealthStatus); i++ { + hcloudLoadBalancerTargetHealthStatusList[i] = c.LoadBalancerTargetHealthStatusFromSchema(source.HealthStatus[i]) + } + } + hcloudLoadBalancerTarget.HealthStatus = hcloudLoadBalancerTargetHealthStatusList + var hcloudLoadBalancerTargetList []LoadBalancerTarget + if source.Targets != nil { + hcloudLoadBalancerTargetList = make([]LoadBalancerTarget, len(source.Targets)) + for j := 0; j < len(source.Targets); j++ { + hcloudLoadBalancerTargetList[j] = c.LoadBalancerTargetFromSchema(source.Targets[j]) + } + } + hcloudLoadBalancerTarget.Targets = hcloudLoadBalancerTargetList + hcloudLoadBalancerTarget.UsePrivateIP = source.UsePrivateIP + return hcloudLoadBalancerTarget +} +func (c *converterImpl) LoadBalancerTargetHealthStatusFromSchema(source schema.LoadBalancerTargetHealthStatus) LoadBalancerTargetHealthStatus { + var hcloudLoadBalancerTargetHealthStatus LoadBalancerTargetHealthStatus + hcloudLoadBalancerTargetHealthStatus.ListenPort = source.ListenPort + hcloudLoadBalancerTargetHealthStatus.Status = LoadBalancerTargetHealthStatusStatus(source.Status) + return hcloudLoadBalancerTargetHealthStatus +} +func (c *converterImpl) LoadBalancerTargetServerFromSchema(source schema.LoadBalancerTargetServer) LoadBalancerTargetServer { + var hcloudLoadBalancerTargetServer LoadBalancerTargetServer + hcloudServer := serverFromInt64(source.ID) + hcloudLoadBalancerTargetServer.Server = &hcloudServer + return hcloudLoadBalancerTargetServer +} +func (c *converterImpl) LoadBalancerTypeFromSchema(source schema.LoadBalancerType) *LoadBalancerType { + var hcloudLoadBalancerType LoadBalancerType + hcloudLoadBalancerType.ID = source.ID + hcloudLoadBalancerType.Name = source.Name + hcloudLoadBalancerType.Description = source.Description + hcloudLoadBalancerType.MaxConnections = source.MaxConnections + hcloudLoadBalancerType.MaxServices = source.MaxServices + hcloudLoadBalancerType.MaxTargets = source.MaxTargets + hcloudLoadBalancerType.MaxAssignedCertificates = source.MaxAssignedCertificates + var hcloudLoadBalancerTypeLocationPricingList []LoadBalancerTypeLocationPricing + if source.Prices != nil { + hcloudLoadBalancerTypeLocationPricingList = make([]LoadBalancerTypeLocationPricing, len(source.Prices)) + for i := 0; i < len(source.Prices); i++ { + hcloudLoadBalancerTypeLocationPricingList[i] = c.LoadBalancerTypeLocationPricingFromSchema(source.Prices[i]) + } + } + hcloudLoadBalancerType.Pricings = hcloudLoadBalancerTypeLocationPricingList + hcloudLoadBalancerType.Deprecated = source.Deprecated + return &hcloudLoadBalancerType +} +func (c *converterImpl) LoadBalancerTypeLocationPricingFromSchema(source schema.PricingLoadBalancerTypePrice) LoadBalancerTypeLocationPricing { + var hcloudLoadBalancerTypeLocationPricing LoadBalancerTypeLocationPricing + hcloudLocation := locationFromString(source.Location) + hcloudLoadBalancerTypeLocationPricing.Location = &hcloudLocation + hcloudLoadBalancerTypeLocationPricing.Hourly = c.PriceFromSchema(source.PriceHourly) + hcloudLoadBalancerTypeLocationPricing.Monthly = c.PriceFromSchema(source.PriceMonthly) + return hcloudLoadBalancerTypeLocationPricing +} +func (c *converterImpl) LocationFromSchema(source schema.Location) *Location { + var hcloudLocation Location + hcloudLocation.ID = source.ID + hcloudLocation.Name = source.Name + hcloudLocation.Description = source.Description + hcloudLocation.Country = source.Country + hcloudLocation.City = source.City + hcloudLocation.Latitude = source.Latitude + hcloudLocation.Longitude = source.Longitude + hcloudLocation.NetworkZone = NetworkZone(source.NetworkZone) + return &hcloudLocation +} +func (c *converterImpl) NetworkFromSchema(source schema.Network) *Network { + var hcloudNetwork Network + hcloudNetwork.ID = source.ID + hcloudNetwork.Name = source.Name + hcloudNetwork.Created = c.timeTimeToTimeTime(source.Created) + netIPNet := ipNetFromString(source.IPRange) + hcloudNetwork.IPRange = &netIPNet + var hcloudNetworkSubnetList []NetworkSubnet + if source.Subnets != nil { + hcloudNetworkSubnetList = make([]NetworkSubnet, len(source.Subnets)) + for i := 0; i < len(source.Subnets); i++ { + hcloudNetworkSubnetList[i] = c.NetworkSubnetFromSchema(source.Subnets[i]) + } + } + hcloudNetwork.Subnets = hcloudNetworkSubnetList + var hcloudNetworkRouteList []NetworkRoute + if source.Routes != nil { + hcloudNetworkRouteList = make([]NetworkRoute, len(source.Routes)) + for j := 0; j < len(source.Routes); j++ { + hcloudNetworkRouteList[j] = c.NetworkRouteFromSchema(source.Routes[j]) + } + } + hcloudNetwork.Routes = hcloudNetworkRouteList + var pHcloudServerList []*Server + if source.Servers != nil { + pHcloudServerList = make([]*Server, len(source.Servers)) + for k := 0; k < len(source.Servers); k++ { + hcloudServer := serverFromInt64(source.Servers[k]) + pHcloudServerList[k] = &hcloudServer + } + } + hcloudNetwork.Servers = pHcloudServerList + hcloudNetwork.Protection = c.schemaNetworkProtectionToHcloudNetworkProtection(source.Protection) + hcloudNetwork.Labels = source.Labels + hcloudNetwork.ExposeRoutesToVSwitch = source.ExposeRoutesToVSwitch + return &hcloudNetwork +} +func (c *converterImpl) NetworkRouteFromSchema(source schema.NetworkRoute) NetworkRoute { + var hcloudNetworkRoute NetworkRoute + netIPNet := ipNetFromString(source.Destination) + hcloudNetworkRoute.Destination = &netIPNet + hcloudNetworkRoute.Gateway = ipFromString(source.Gateway) + return hcloudNetworkRoute +} +func (c *converterImpl) NetworkSubnetFromSchema(source schema.NetworkSubnet) NetworkSubnet { + var hcloudNetworkSubnet NetworkSubnet + hcloudNetworkSubnet.Type = NetworkSubnetType(source.Type) + netIPNet := ipNetFromString(source.IPRange) + hcloudNetworkSubnet.IPRange = &netIPNet + hcloudNetworkSubnet.NetworkZone = NetworkZone(source.NetworkZone) + hcloudNetworkSubnet.Gateway = ipFromString(source.Gateway) + hcloudNetworkSubnet.VSwitchID = source.VSwitchID + return hcloudNetworkSubnet +} +func (c *converterImpl) PaginationFromSchema(source schema.MetaPagination) Pagination { + var hcloudPagination Pagination + hcloudPagination.Page = source.Page + hcloudPagination.PerPage = source.PerPage + hcloudPagination.PreviousPage = source.PreviousPage + hcloudPagination.NextPage = source.NextPage + hcloudPagination.LastPage = source.LastPage + hcloudPagination.TotalEntries = source.TotalEntries + return hcloudPagination +} +func (c *converterImpl) PlacementGroupFromSchema(source schema.PlacementGroup) *PlacementGroup { + var hcloudPlacementGroup PlacementGroup + hcloudPlacementGroup.ID = source.ID + hcloudPlacementGroup.Name = source.Name + hcloudPlacementGroup.Labels = source.Labels + hcloudPlacementGroup.Created = c.timeTimeToTimeTime(source.Created) + hcloudPlacementGroup.Servers = source.Servers + hcloudPlacementGroup.Type = PlacementGroupType(source.Type) + return &hcloudPlacementGroup +} +func (c *converterImpl) PriceFromSchema(source schema.Price) Price { + var hcloudPrice Price + hcloudPrice.Net = source.Net + hcloudPrice.Gross = source.Gross + return hcloudPrice +} +func (c *converterImpl) PricingFromSchema(source schema.Pricing) Pricing { + var hcloudPricing Pricing + hcloudPricing.Image = imagePricingFromSchema(source) + hcloudPricing.FloatingIP = floatingIPPricingFromSchema(source) + hcloudPricing.FloatingIPs = floatingIPTypePricingFromSchema(source) + hcloudPricing.PrimaryIPs = primaryIPPricingFromSchema(source) + hcloudPricing.Traffic = trafficPricingFromSchema(source) + hcloudPricing.ServerBackup = c.schemaPricingServerBackupToHcloudServerBackupPricing(source.ServerBackup) + hcloudPricing.ServerTypes = serverTypePricingFromSchema(source) + hcloudPricing.LoadBalancerTypes = loadBalancerTypePricingFromSchema(source) + hcloudPricing.Volume = volumePricingFromSchema(source) + return hcloudPricing +} +func (c *converterImpl) PrimaryIPFromSchema(source schema.PrimaryIP) *PrimaryIP { + var hcloudPrimaryIP PrimaryIP + hcloudPrimaryIP.ID = source.ID + hcloudPrimaryIP.IP = ipFromPrimaryIPSchema(source) + hcloudPrimaryIP.Network = networkFromPrimaryIPSchema(source) + hcloudPrimaryIP.Labels = source.Labels + hcloudPrimaryIP.Name = source.Name + hcloudPrimaryIP.Type = PrimaryIPType(source.Type) + hcloudPrimaryIP.Protection = c.schemaPrimaryIPProtectionToHcloudPrimaryIPProtection(source.Protection) + hcloudPrimaryIP.DNSPtr = mapFromPrimaryIPDNSPtrSchema(source.DNSPtr) + hcloudPrimaryIP.AssigneeID = source.AssigneeID + hcloudPrimaryIP.AssigneeType = source.AssigneeType + hcloudPrimaryIP.AutoDelete = source.AutoDelete + hcloudPrimaryIP.Blocked = source.Blocked + hcloudPrimaryIP.Created = c.timeTimeToTimeTime(source.Created) + hcloudPrimaryIP.Datacenter = c.DatacenterFromSchema(source.Datacenter) + return &hcloudPrimaryIP +} +func (c *converterImpl) SSHKeyFromSchema(source schema.SSHKey) *SSHKey { + var hcloudSSHKey SSHKey + hcloudSSHKey.ID = source.ID + hcloudSSHKey.Name = source.Name + hcloudSSHKey.Fingerprint = source.Fingerprint + hcloudSSHKey.PublicKey = source.PublicKey + hcloudSSHKey.Labels = source.Labels + hcloudSSHKey.Created = c.timeTimeToTimeTime(source.Created) + return &hcloudSSHKey +} +func (c *converterImpl) SchemaFromAction(source *Action) schema.Action { + var schemaAction schema.Action + if source != nil { + var schemaAction2 schema.Action + schemaAction2.ID = (*source).ID + schemaAction2.Status = string((*source).Status) + schemaAction2.Command = (*source).Command + schemaAction2.Progress = (*source).Progress + schemaAction2.Started = c.timeTimeToTimeTime((*source).Started) + schemaAction2.Finished = timeToTimePtr((*source).Finished) + schemaAction2.Error = schemaActionErrorFromAction((*source)) + var schemaActionResourceReferenceList []schema.ActionResourceReference + if (*source).Resources != nil { + schemaActionResourceReferenceList = make([]schema.ActionResourceReference, len((*source).Resources)) + for i := 0; i < len((*source).Resources); i++ { + schemaActionResourceReferenceList[i] = c.pHcloudActionResourceToSchemaActionResourceReference((*source).Resources[i]) + } + } + schemaAction2.Resources = schemaActionResourceReferenceList + schemaAction = schemaAction2 + } + return schemaAction +} +func (c *converterImpl) SchemaFromActions(source []*Action) []schema.Action { + var schemaActionList []schema.Action + if source != nil { + schemaActionList = make([]schema.Action, len(source)) + for i := 0; i < len(source); i++ { + schemaActionList[i] = c.SchemaFromAction(source[i]) + } + } + return schemaActionList +} +func (c *converterImpl) SchemaFromCertificate(source *Certificate) schema.Certificate { + var schemaCertificate schema.Certificate + if source != nil { + var schemaCertificate2 schema.Certificate + schemaCertificate2.ID = (*source).ID + schemaCertificate2.Name = (*source).Name + schemaCertificate2.Labels = (*source).Labels + schemaCertificate2.Type = string((*source).Type) + schemaCertificate2.Certificate = (*source).Certificate + schemaCertificate2.Created = c.timeTimeToTimeTime((*source).Created) + schemaCertificate2.NotValidBefore = c.timeTimeToTimeTime((*source).NotValidBefore) + schemaCertificate2.NotValidAfter = c.timeTimeToTimeTime((*source).NotValidAfter) + schemaCertificate2.DomainNames = (*source).DomainNames + schemaCertificate2.Fingerprint = (*source).Fingerprint + schemaCertificate2.Status = c.pHcloudCertificateStatusToPSchemaCertificateStatusRef((*source).Status) + var schemaCertificateUsedByRefList []schema.CertificateUsedByRef + if (*source).UsedBy != nil { + schemaCertificateUsedByRefList = make([]schema.CertificateUsedByRef, len((*source).UsedBy)) + for i := 0; i < len((*source).UsedBy); i++ { + schemaCertificateUsedByRefList[i] = c.hcloudCertificateUsedByRefToSchemaCertificateUsedByRef((*source).UsedBy[i]) + } + } + schemaCertificate2.UsedBy = schemaCertificateUsedByRefList + schemaCertificate = schemaCertificate2 + } + return schemaCertificate +} +func (c *converterImpl) SchemaFromDatacenter(source *Datacenter) schema.Datacenter { + var schemaDatacenter schema.Datacenter + if source != nil { + var schemaDatacenter2 schema.Datacenter + schemaDatacenter2.ID = (*source).ID + schemaDatacenter2.Name = (*source).Name + schemaDatacenter2.Description = (*source).Description + schemaDatacenter2.Location = c.SchemaFromLocation((*source).Location) + schemaDatacenter2.ServerTypes = c.hcloudDatacenterServerTypesToSchemaDatacenterServerTypes((*source).ServerTypes) + schemaDatacenter = schemaDatacenter2 + } + return schemaDatacenter +} +func (c *converterImpl) SchemaFromDeprecation(source *DeprecationInfo) *schema.DeprecationInfo { + var pSchemaDeprecationInfo *schema.DeprecationInfo + if source != nil { + var schemaDeprecationInfo schema.DeprecationInfo + schemaDeprecationInfo.Announced = c.timeTimeToTimeTime((*source).Announced) + schemaDeprecationInfo.UnavailableAfter = c.timeTimeToTimeTime((*source).UnavailableAfter) + pSchemaDeprecationInfo = &schemaDeprecationInfo + } + return pSchemaDeprecationInfo +} +func (c *converterImpl) SchemaFromError(source Error) schema.Error { + var schemaError schema.Error + schemaError.Code = string(source.Code) + schemaError.Message = source.Message + schemaError.DetailsRaw = rawSchemaFromErrorDetails(source.Details) + schemaError.Details = schemaFromErrorDetails(source.Details) + return schemaError +} +func (c *converterImpl) SchemaFromFirewall(source *Firewall) schema.Firewall { + var schemaFirewall schema.Firewall + if source != nil { + var schemaFirewall2 schema.Firewall + schemaFirewall2.ID = (*source).ID + schemaFirewall2.Name = (*source).Name + schemaFirewall2.Labels = (*source).Labels + schemaFirewall2.Created = c.timeTimeToTimeTime((*source).Created) + var schemaFirewallRuleList []schema.FirewallRule + if (*source).Rules != nil { + schemaFirewallRuleList = make([]schema.FirewallRule, len((*source).Rules)) + for i := 0; i < len((*source).Rules); i++ { + schemaFirewallRuleList[i] = c.hcloudFirewallRuleToSchemaFirewallRule((*source).Rules[i]) + } + } + schemaFirewall2.Rules = schemaFirewallRuleList + var schemaFirewallResourceList []schema.FirewallResource + if (*source).AppliedTo != nil { + schemaFirewallResourceList = make([]schema.FirewallResource, len((*source).AppliedTo)) + for j := 0; j < len((*source).AppliedTo); j++ { + schemaFirewallResourceList[j] = c.SchemaFromFirewallResource((*source).AppliedTo[j]) + } + } + schemaFirewall2.AppliedTo = schemaFirewallResourceList + schemaFirewall = schemaFirewall2 + } + return schemaFirewall +} +func (c *converterImpl) SchemaFromFirewallCreateOpts(source FirewallCreateOpts) schema.FirewallCreateRequest { + var schemaFirewallCreateRequest schema.FirewallCreateRequest + schemaFirewallCreateRequest.Name = source.Name + schemaFirewallCreateRequest.Labels = stringMapToStringMapPtr(source.Labels) + var schemaFirewallRuleList []schema.FirewallRule + if source.Rules != nil { + schemaFirewallRuleList = make([]schema.FirewallRule, len(source.Rules)) + for i := 0; i < len(source.Rules); i++ { + schemaFirewallRuleList[i] = c.hcloudFirewallRuleToSchemaFirewallRule(source.Rules[i]) + } + } + schemaFirewallCreateRequest.Rules = schemaFirewallRuleList + var schemaFirewallResourceList []schema.FirewallResource + if source.ApplyTo != nil { + schemaFirewallResourceList = make([]schema.FirewallResource, len(source.ApplyTo)) + for j := 0; j < len(source.ApplyTo); j++ { + schemaFirewallResourceList[j] = c.SchemaFromFirewallResource(source.ApplyTo[j]) + } + } + schemaFirewallCreateRequest.ApplyTo = schemaFirewallResourceList + return schemaFirewallCreateRequest +} +func (c *converterImpl) SchemaFromFirewallResource(source FirewallResource) schema.FirewallResource { + var schemaFirewallResource schema.FirewallResource + schemaFirewallResource.Type = string(source.Type) + schemaFirewallResource.Server = c.pHcloudFirewallResourceServerToPSchemaFirewallResourceServer(source.Server) + schemaFirewallResource.LabelSelector = c.pHcloudFirewallResourceLabelSelectorToPSchemaFirewallResourceLabelSelector(source.LabelSelector) + return schemaFirewallResource +} +func (c *converterImpl) SchemaFromFirewallSetRulesOpts(source FirewallSetRulesOpts) schema.FirewallActionSetRulesRequest { + var schemaFirewallActionSetRulesRequest schema.FirewallActionSetRulesRequest + var schemaFirewallRuleList []schema.FirewallRule + if source.Rules != nil { + schemaFirewallRuleList = make([]schema.FirewallRule, len(source.Rules)) + for i := 0; i < len(source.Rules); i++ { + schemaFirewallRuleList[i] = c.hcloudFirewallRuleToSchemaFirewallRule(source.Rules[i]) + } + } + schemaFirewallActionSetRulesRequest.Rules = schemaFirewallRuleList + return schemaFirewallActionSetRulesRequest +} +func (c *converterImpl) SchemaFromFloatingIP(source *FloatingIP) schema.FloatingIP { + var schemaFloatingIP schema.FloatingIP + if source != nil { + var schemaFloatingIP2 schema.FloatingIP + schemaFloatingIP2.ID = (*source).ID + pString := (*source).Description + schemaFloatingIP2.Description = &pString + schemaFloatingIP2.Created = c.timeTimeToTimeTime((*source).Created) + schemaFloatingIP2.IP = floatingIPToIPString((*source)) + schemaFloatingIP2.Type = string((*source).Type) + schemaFloatingIP2.Server = c.pHcloudServerToPInt64((*source).Server) + schemaFloatingIP2.DNSPtr = floatingIPDNSPtrSchemaFromMap((*source).DNSPtr) + schemaFloatingIP2.HomeLocation = c.SchemaFromLocation((*source).HomeLocation) + schemaFloatingIP2.Blocked = (*source).Blocked + schemaFloatingIP2.Protection = c.hcloudFloatingIPProtectionToSchemaFloatingIPProtection((*source).Protection) + schemaFloatingIP2.Labels = (*source).Labels + schemaFloatingIP2.Name = (*source).Name + schemaFloatingIP = schemaFloatingIP2 + } + return schemaFloatingIP +} +func (c *converterImpl) SchemaFromISO(source *ISO) schema.ISO { + var schemaISO schema.ISO + if source != nil { + var schemaISO2 schema.ISO + schemaISO2.ID = (*source).ID + schemaISO2.Name = (*source).Name + schemaISO2.Description = (*source).Description + schemaISO2.Type = string((*source).Type) + var pString *string + if (*source).Architecture != nil { + xstring := string(*(*source).Architecture) + pString = &xstring + } + schemaISO2.Architecture = pString + schemaISO2.DeprecatableResource = c.hcloudDeprecatableResourceToSchemaDeprecatableResource((*source).DeprecatableResource) + schemaISO = schemaISO2 + } + return schemaISO +} +func (c *converterImpl) SchemaFromImage(source *Image) schema.Image { + var schemaImage schema.Image + if source != nil { + schemaImage = c.intSchemaFromImage((*source)) + } + return schemaImage +} +func (c *converterImpl) SchemaFromLoadBalancer(source *LoadBalancer) schema.LoadBalancer { + var schemaLoadBalancer schema.LoadBalancer + if source != nil { + var schemaLoadBalancer2 schema.LoadBalancer + schemaLoadBalancer2.ID = (*source).ID + schemaLoadBalancer2.Name = (*source).Name + schemaLoadBalancer2.PublicNet = c.hcloudLoadBalancerPublicNetToSchemaLoadBalancerPublicNet((*source).PublicNet) + var schemaLoadBalancerPrivateNetList []schema.LoadBalancerPrivateNet + if (*source).PrivateNet != nil { + schemaLoadBalancerPrivateNetList = make([]schema.LoadBalancerPrivateNet, len((*source).PrivateNet)) + for i := 0; i < len((*source).PrivateNet); i++ { + schemaLoadBalancerPrivateNetList[i] = c.hcloudLoadBalancerPrivateNetToSchemaLoadBalancerPrivateNet((*source).PrivateNet[i]) + } + } + schemaLoadBalancer2.PrivateNet = schemaLoadBalancerPrivateNetList + schemaLoadBalancer2.Location = c.SchemaFromLocation((*source).Location) + schemaLoadBalancer2.LoadBalancerType = c.SchemaFromLoadBalancerType((*source).LoadBalancerType) + schemaLoadBalancer2.Protection = c.hcloudLoadBalancerProtectionToSchemaLoadBalancerProtection((*source).Protection) + schemaLoadBalancer2.Labels = (*source).Labels + schemaLoadBalancer2.Created = c.timeTimeToTimeTime((*source).Created) + var schemaLoadBalancerServiceList []schema.LoadBalancerService + if (*source).Services != nil { + schemaLoadBalancerServiceList = make([]schema.LoadBalancerService, len((*source).Services)) + for j := 0; j < len((*source).Services); j++ { + schemaLoadBalancerServiceList[j] = c.SchemaFromLoadBalancerService((*source).Services[j]) + } + } + schemaLoadBalancer2.Services = schemaLoadBalancerServiceList + var schemaLoadBalancerTargetList []schema.LoadBalancerTarget + if (*source).Targets != nil { + schemaLoadBalancerTargetList = make([]schema.LoadBalancerTarget, len((*source).Targets)) + for k := 0; k < len((*source).Targets); k++ { + schemaLoadBalancerTargetList[k] = c.SchemaFromLoadBalancerTarget((*source).Targets[k]) + } + } + schemaLoadBalancer2.Targets = schemaLoadBalancerTargetList + schemaLoadBalancer2.Algorithm = c.hcloudLoadBalancerAlgorithmToSchemaLoadBalancerAlgorithm((*source).Algorithm) + schemaLoadBalancer2.IncludedTraffic = (*source).IncludedTraffic + schemaLoadBalancer2.OutgoingTraffic = mapZeroUint64ToNil((*source).OutgoingTraffic) + schemaLoadBalancer2.IngoingTraffic = mapZeroUint64ToNil((*source).IngoingTraffic) + schemaLoadBalancer = schemaLoadBalancer2 + } + return schemaLoadBalancer +} +func (c *converterImpl) SchemaFromLoadBalancerAddServiceOpts(source LoadBalancerAddServiceOpts) schema.LoadBalancerActionAddServiceRequest { + var schemaLoadBalancerActionAddServiceRequest schema.LoadBalancerActionAddServiceRequest + schemaLoadBalancerActionAddServiceRequest.Protocol = string(source.Protocol) + schemaLoadBalancerActionAddServiceRequest.ListenPort = source.ListenPort + schemaLoadBalancerActionAddServiceRequest.DestinationPort = source.DestinationPort + schemaLoadBalancerActionAddServiceRequest.Proxyprotocol = source.Proxyprotocol + schemaLoadBalancerActionAddServiceRequest.HTTP = c.pHcloudLoadBalancerAddServiceOptsHTTPToPSchemaLoadBalancerActionAddServiceRequestHTTP(source.HTTP) + schemaLoadBalancerActionAddServiceRequest.HealthCheck = c.pHcloudLoadBalancerAddServiceOptsHealthCheckToPSchemaLoadBalancerActionAddServiceRequestHealthCheck(source.HealthCheck) + return schemaLoadBalancerActionAddServiceRequest +} +func (c *converterImpl) SchemaFromLoadBalancerCreateOpts(source LoadBalancerCreateOpts) schema.LoadBalancerCreateRequest { + var schemaLoadBalancerCreateRequest schema.LoadBalancerCreateRequest + schemaLoadBalancerCreateRequest.Name = source.Name + schemaLoadBalancerCreateRequest.LoadBalancerType = anyFromLoadBalancerType(source.LoadBalancerType) + schemaLoadBalancerCreateRequest.Algorithm = c.pHcloudLoadBalancerAlgorithmToPSchemaLoadBalancerCreateRequestAlgorithm(source.Algorithm) + schemaLoadBalancerCreateRequest.Location = c.pHcloudLocationToPString(source.Location) + schemaLoadBalancerCreateRequest.NetworkZone = stringPtrFromNetworkZone(source.NetworkZone) + schemaLoadBalancerCreateRequest.Labels = stringMapToStringMapPtr(source.Labels) + var schemaLoadBalancerCreateRequestTargetList []schema.LoadBalancerCreateRequestTarget + if source.Targets != nil { + schemaLoadBalancerCreateRequestTargetList = make([]schema.LoadBalancerCreateRequestTarget, len(source.Targets)) + for i := 0; i < len(source.Targets); i++ { + schemaLoadBalancerCreateRequestTargetList[i] = c.hcloudLoadBalancerCreateOptsTargetToSchemaLoadBalancerCreateRequestTarget(source.Targets[i]) + } + } + schemaLoadBalancerCreateRequest.Targets = schemaLoadBalancerCreateRequestTargetList + var schemaLoadBalancerCreateRequestServiceList []schema.LoadBalancerCreateRequestService + if source.Services != nil { + schemaLoadBalancerCreateRequestServiceList = make([]schema.LoadBalancerCreateRequestService, len(source.Services)) + for j := 0; j < len(source.Services); j++ { + schemaLoadBalancerCreateRequestServiceList[j] = c.hcloudLoadBalancerCreateOptsServiceToSchemaLoadBalancerCreateRequestService(source.Services[j]) + } + } + schemaLoadBalancerCreateRequest.Services = schemaLoadBalancerCreateRequestServiceList + schemaLoadBalancerCreateRequest.PublicInterface = source.PublicInterface + schemaLoadBalancerCreateRequest.Network = c.pHcloudNetworkToPInt64(source.Network) + return schemaLoadBalancerCreateRequest +} +func (c *converterImpl) SchemaFromLoadBalancerCreateOptsTargetServer(source LoadBalancerCreateOptsTargetServer) schema.LoadBalancerCreateRequestTargetServer { + var schemaLoadBalancerCreateRequestTargetServer schema.LoadBalancerCreateRequestTargetServer + var pInt64 *int64 + if source.Server != nil { + pInt64 = &source.Server.ID + } + var xint64 int64 + if pInt64 != nil { + xint64 = *pInt64 + } + schemaLoadBalancerCreateRequestTargetServer.ID = xint64 + return schemaLoadBalancerCreateRequestTargetServer +} +func (c *converterImpl) SchemaFromLoadBalancerServerTarget(source LoadBalancerTargetServer) schema.LoadBalancerTargetServer { + var schemaLoadBalancerTargetServer schema.LoadBalancerTargetServer + schemaLoadBalancerTargetServer.ID = c.pHcloudServerToInt64(source.Server) + return schemaLoadBalancerTargetServer +} +func (c *converterImpl) SchemaFromLoadBalancerService(source LoadBalancerService) schema.LoadBalancerService { + var schemaLoadBalancerService schema.LoadBalancerService + schemaLoadBalancerService.Protocol = string(source.Protocol) + schemaLoadBalancerService.ListenPort = source.ListenPort + schemaLoadBalancerService.DestinationPort = source.DestinationPort + schemaLoadBalancerService.Proxyprotocol = source.Proxyprotocol + schemaLoadBalancerService.HTTP = c.hcloudLoadBalancerServiceHTTPToPSchemaLoadBalancerServiceHTTP(source.HTTP) + schemaLoadBalancerService.HealthCheck = c.SchemaFromLoadBalancerServiceHealthCheck(source.HealthCheck) + return schemaLoadBalancerService +} +func (c *converterImpl) SchemaFromLoadBalancerServiceHealthCheck(source LoadBalancerServiceHealthCheck) *schema.LoadBalancerServiceHealthCheck { + var schemaLoadBalancerServiceHealthCheck schema.LoadBalancerServiceHealthCheck + schemaLoadBalancerServiceHealthCheck.Protocol = string(source.Protocol) + schemaLoadBalancerServiceHealthCheck.Port = source.Port + schemaLoadBalancerServiceHealthCheck.Interval = intSecondsFromDuration(source.Interval) + schemaLoadBalancerServiceHealthCheck.Timeout = intSecondsFromDuration(source.Timeout) + schemaLoadBalancerServiceHealthCheck.Retries = source.Retries + schemaLoadBalancerServiceHealthCheck.HTTP = c.pHcloudLoadBalancerServiceHealthCheckHTTPToPSchemaLoadBalancerServiceHealthCheckHTTP(source.HTTP) + return &schemaLoadBalancerServiceHealthCheck +} +func (c *converterImpl) SchemaFromLoadBalancerTarget(source LoadBalancerTarget) schema.LoadBalancerTarget { + var schemaLoadBalancerTarget schema.LoadBalancerTarget + schemaLoadBalancerTarget.Type = string(source.Type) + schemaLoadBalancerTarget.Server = c.pHcloudLoadBalancerTargetServerToPSchemaLoadBalancerTargetServer(source.Server) + schemaLoadBalancerTarget.LabelSelector = c.pHcloudLoadBalancerTargetLabelSelectorToPSchemaLoadBalancerTargetLabelSelector(source.LabelSelector) + schemaLoadBalancerTarget.IP = c.pHcloudLoadBalancerTargetIPToPSchemaLoadBalancerTargetIP(source.IP) + var schemaLoadBalancerTargetHealthStatusList []schema.LoadBalancerTargetHealthStatus + if source.HealthStatus != nil { + schemaLoadBalancerTargetHealthStatusList = make([]schema.LoadBalancerTargetHealthStatus, len(source.HealthStatus)) + for i := 0; i < len(source.HealthStatus); i++ { + schemaLoadBalancerTargetHealthStatusList[i] = c.SchemaFromLoadBalancerTargetHealthStatus(source.HealthStatus[i]) + } + } + schemaLoadBalancerTarget.HealthStatus = schemaLoadBalancerTargetHealthStatusList + schemaLoadBalancerTarget.UsePrivateIP = source.UsePrivateIP + var schemaLoadBalancerTargetList []schema.LoadBalancerTarget + if source.Targets != nil { + schemaLoadBalancerTargetList = make([]schema.LoadBalancerTarget, len(source.Targets)) + for j := 0; j < len(source.Targets); j++ { + schemaLoadBalancerTargetList[j] = c.SchemaFromLoadBalancerTarget(source.Targets[j]) + } + } + schemaLoadBalancerTarget.Targets = schemaLoadBalancerTargetList + return schemaLoadBalancerTarget +} +func (c *converterImpl) SchemaFromLoadBalancerTargetHealthStatus(source LoadBalancerTargetHealthStatus) schema.LoadBalancerTargetHealthStatus { + var schemaLoadBalancerTargetHealthStatus schema.LoadBalancerTargetHealthStatus + schemaLoadBalancerTargetHealthStatus.ListenPort = source.ListenPort + schemaLoadBalancerTargetHealthStatus.Status = string(source.Status) + return schemaLoadBalancerTargetHealthStatus +} +func (c *converterImpl) SchemaFromLoadBalancerType(source *LoadBalancerType) schema.LoadBalancerType { + var schemaLoadBalancerType schema.LoadBalancerType + if source != nil { + var schemaLoadBalancerType2 schema.LoadBalancerType + schemaLoadBalancerType2.ID = (*source).ID + schemaLoadBalancerType2.Name = (*source).Name + schemaLoadBalancerType2.Description = (*source).Description + schemaLoadBalancerType2.MaxConnections = (*source).MaxConnections + schemaLoadBalancerType2.MaxServices = (*source).MaxServices + schemaLoadBalancerType2.MaxTargets = (*source).MaxTargets + schemaLoadBalancerType2.MaxAssignedCertificates = (*source).MaxAssignedCertificates + var schemaPricingLoadBalancerTypePriceList []schema.PricingLoadBalancerTypePrice + if (*source).Pricings != nil { + schemaPricingLoadBalancerTypePriceList = make([]schema.PricingLoadBalancerTypePrice, len((*source).Pricings)) + for i := 0; i < len((*source).Pricings); i++ { + schemaPricingLoadBalancerTypePriceList[i] = c.SchemaFromLoadBalancerTypeLocationPricing((*source).Pricings[i]) + } + } + schemaLoadBalancerType2.Prices = schemaPricingLoadBalancerTypePriceList + schemaLoadBalancerType2.Deprecated = (*source).Deprecated + schemaLoadBalancerType = schemaLoadBalancerType2 + } + return schemaLoadBalancerType +} +func (c *converterImpl) SchemaFromLoadBalancerTypeLocationPricing(source LoadBalancerTypeLocationPricing) schema.PricingLoadBalancerTypePrice { + var schemaPricingLoadBalancerTypePrice schema.PricingLoadBalancerTypePrice + schemaPricingLoadBalancerTypePrice.Location = c.pHcloudLocationToString(source.Location) + schemaPricingLoadBalancerTypePrice.PriceHourly = c.hcloudPriceToSchemaPrice(source.Hourly) + schemaPricingLoadBalancerTypePrice.PriceMonthly = c.hcloudPriceToSchemaPrice(source.Monthly) + return schemaPricingLoadBalancerTypePrice +} +func (c *converterImpl) SchemaFromLoadBalancerUpdateServiceOpts(source LoadBalancerUpdateServiceOpts) schema.LoadBalancerActionUpdateServiceRequest { + var schemaLoadBalancerActionUpdateServiceRequest schema.LoadBalancerActionUpdateServiceRequest + schemaLoadBalancerActionUpdateServiceRequest.Protocol = stringPtrFromLoadBalancerServiceProtocol(source.Protocol) + schemaLoadBalancerActionUpdateServiceRequest.DestinationPort = source.DestinationPort + schemaLoadBalancerActionUpdateServiceRequest.Proxyprotocol = source.Proxyprotocol + schemaLoadBalancerActionUpdateServiceRequest.HTTP = c.pHcloudLoadBalancerUpdateServiceOptsHTTPToPSchemaLoadBalancerActionUpdateServiceRequestHTTP(source.HTTP) + schemaLoadBalancerActionUpdateServiceRequest.HealthCheck = c.pHcloudLoadBalancerUpdateServiceOptsHealthCheckToPSchemaLoadBalancerActionUpdateServiceRequestHealthCheck(source.HealthCheck) + return schemaLoadBalancerActionUpdateServiceRequest +} +func (c *converterImpl) SchemaFromLocation(source *Location) schema.Location { + var schemaLocation schema.Location + if source != nil { + var schemaLocation2 schema.Location + schemaLocation2.ID = (*source).ID + schemaLocation2.Name = (*source).Name + schemaLocation2.Description = (*source).Description + schemaLocation2.Country = (*source).Country + schemaLocation2.City = (*source).City + schemaLocation2.Latitude = (*source).Latitude + schemaLocation2.Longitude = (*source).Longitude + schemaLocation2.NetworkZone = string((*source).NetworkZone) + schemaLocation = schemaLocation2 + } + return schemaLocation +} +func (c *converterImpl) SchemaFromNetwork(source *Network) schema.Network { + var schemaNetwork schema.Network + if source != nil { + var schemaNetwork2 schema.Network + schemaNetwork2.ID = (*source).ID + schemaNetwork2.Name = (*source).Name + schemaNetwork2.Created = c.timeTimeToTimeTime((*source).Created) + schemaNetwork2.IPRange = c.pNetIPNetToString((*source).IPRange) + var schemaNetworkSubnetList []schema.NetworkSubnet + if (*source).Subnets != nil { + schemaNetworkSubnetList = make([]schema.NetworkSubnet, len((*source).Subnets)) + for i := 0; i < len((*source).Subnets); i++ { + schemaNetworkSubnetList[i] = c.SchemaFromNetworkSubnet((*source).Subnets[i]) + } + } + schemaNetwork2.Subnets = schemaNetworkSubnetList + var schemaNetworkRouteList []schema.NetworkRoute + if (*source).Routes != nil { + schemaNetworkRouteList = make([]schema.NetworkRoute, len((*source).Routes)) + for j := 0; j < len((*source).Routes); j++ { + schemaNetworkRouteList[j] = c.SchemaFromNetworkRoute((*source).Routes[j]) + } + } + schemaNetwork2.Routes = schemaNetworkRouteList + var int64List []int64 + if (*source).Servers != nil { + int64List = make([]int64, len((*source).Servers)) + for k := 0; k < len((*source).Servers); k++ { + int64List[k] = c.pHcloudServerToInt64((*source).Servers[k]) + } + } + schemaNetwork2.Servers = int64List + schemaNetwork2.Protection = c.hcloudNetworkProtectionToSchemaNetworkProtection((*source).Protection) + schemaNetwork2.Labels = (*source).Labels + schemaNetwork2.ExposeRoutesToVSwitch = (*source).ExposeRoutesToVSwitch + schemaNetwork = schemaNetwork2 + } + return schemaNetwork +} +func (c *converterImpl) SchemaFromNetworkRoute(source NetworkRoute) schema.NetworkRoute { + var schemaNetworkRoute schema.NetworkRoute + schemaNetworkRoute.Destination = c.pNetIPNetToString(source.Destination) + schemaNetworkRoute.Gateway = stringFromIP(source.Gateway) + return schemaNetworkRoute +} +func (c *converterImpl) SchemaFromNetworkSubnet(source NetworkSubnet) schema.NetworkSubnet { + var schemaNetworkSubnet schema.NetworkSubnet + schemaNetworkSubnet.Type = string(source.Type) + schemaNetworkSubnet.IPRange = c.pNetIPNetToString(source.IPRange) + schemaNetworkSubnet.NetworkZone = string(source.NetworkZone) + schemaNetworkSubnet.Gateway = stringFromIP(source.Gateway) + schemaNetworkSubnet.VSwitchID = source.VSwitchID + return schemaNetworkSubnet +} +func (c *converterImpl) SchemaFromPagination(source Pagination) schema.MetaPagination { + var schemaMetaPagination schema.MetaPagination + schemaMetaPagination.Page = source.Page + schemaMetaPagination.PerPage = source.PerPage + schemaMetaPagination.PreviousPage = source.PreviousPage + schemaMetaPagination.NextPage = source.NextPage + schemaMetaPagination.LastPage = source.LastPage + schemaMetaPagination.TotalEntries = source.TotalEntries + return schemaMetaPagination +} +func (c *converterImpl) SchemaFromPlacementGroup(source *PlacementGroup) schema.PlacementGroup { + var schemaPlacementGroup schema.PlacementGroup + if source != nil { + var schemaPlacementGroup2 schema.PlacementGroup + schemaPlacementGroup2.ID = (*source).ID + schemaPlacementGroup2.Name = (*source).Name + schemaPlacementGroup2.Labels = (*source).Labels + schemaPlacementGroup2.Created = c.timeTimeToTimeTime((*source).Created) + schemaPlacementGroup2.Servers = (*source).Servers + schemaPlacementGroup2.Type = string((*source).Type) + schemaPlacementGroup = schemaPlacementGroup2 + } + return schemaPlacementGroup +} +func (c *converterImpl) SchemaFromPlacementGroupCreateOpts(source PlacementGroupCreateOpts) schema.PlacementGroupCreateRequest { + var schemaPlacementGroupCreateRequest schema.PlacementGroupCreateRequest + schemaPlacementGroupCreateRequest.Name = source.Name + schemaPlacementGroupCreateRequest.Labels = stringMapToStringMapPtr(source.Labels) + schemaPlacementGroupCreateRequest.Type = string(source.Type) + return schemaPlacementGroupCreateRequest +} +func (c *converterImpl) SchemaFromPricing(source Pricing) schema.Pricing { + var schemaPricing schema.Pricing + schemaPricing.Currency = source.Image.PerGBMonth.Currency + schemaPricing.VATRate = source.Image.PerGBMonth.VATRate + schemaPricing.Image = c.schemaFromImagePricing(source.Image) + schemaPricing.FloatingIP = c.schemaFromFloatingIPPricing(source.FloatingIP) + var schemaPricingFloatingIPTypeList []schema.PricingFloatingIPType + if source.FloatingIPs != nil { + schemaPricingFloatingIPTypeList = make([]schema.PricingFloatingIPType, len(source.FloatingIPs)) + for i := 0; i < len(source.FloatingIPs); i++ { + schemaPricingFloatingIPTypeList[i] = c.schemaFromFloatingIPTypePricing(source.FloatingIPs[i]) + } + } + schemaPricing.FloatingIPs = schemaPricingFloatingIPTypeList + var schemaPricingPrimaryIPList []schema.PricingPrimaryIP + if source.PrimaryIPs != nil { + schemaPricingPrimaryIPList = make([]schema.PricingPrimaryIP, len(source.PrimaryIPs)) + for j := 0; j < len(source.PrimaryIPs); j++ { + schemaPricingPrimaryIPList[j] = c.schemaFromPrimaryIPPricing(source.PrimaryIPs[j]) + } + } + schemaPricing.PrimaryIPs = schemaPricingPrimaryIPList + schemaPricing.Traffic = c.schemaFromTrafficPricing(source.Traffic) + schemaPricing.ServerBackup = c.hcloudServerBackupPricingToSchemaPricingServerBackup(source.ServerBackup) + var schemaPricingServerTypeList []schema.PricingServerType + if source.ServerTypes != nil { + schemaPricingServerTypeList = make([]schema.PricingServerType, len(source.ServerTypes)) + for k := 0; k < len(source.ServerTypes); k++ { + schemaPricingServerTypeList[k] = c.schemaFromServerTypePricing(source.ServerTypes[k]) + } + } + schemaPricing.ServerTypes = schemaPricingServerTypeList + var schemaPricingLoadBalancerTypeList []schema.PricingLoadBalancerType + if source.LoadBalancerTypes != nil { + schemaPricingLoadBalancerTypeList = make([]schema.PricingLoadBalancerType, len(source.LoadBalancerTypes)) + for l := 0; l < len(source.LoadBalancerTypes); l++ { + schemaPricingLoadBalancerTypeList[l] = c.schemaFromLoadBalancerTypePricing(source.LoadBalancerTypes[l]) + } + } + schemaPricing.LoadBalancerTypes = schemaPricingLoadBalancerTypeList + schemaPricing.Volume = c.schemaFromVolumePricing(source.Volume) + return schemaPricing +} +func (c *converterImpl) SchemaFromPrimaryIP(source *PrimaryIP) schema.PrimaryIP { + var schemaPrimaryIP schema.PrimaryIP + if source != nil { + var schemaPrimaryIP2 schema.PrimaryIP + schemaPrimaryIP2.ID = (*source).ID + schemaPrimaryIP2.IP = primaryIPToIPString((*source)) + schemaPrimaryIP2.Labels = (*source).Labels + schemaPrimaryIP2.Name = (*source).Name + schemaPrimaryIP2.Type = string((*source).Type) + schemaPrimaryIP2.Protection = c.hcloudPrimaryIPProtectionToSchemaPrimaryIPProtection((*source).Protection) + schemaPrimaryIP2.DNSPtr = primaryIPDNSPtrSchemaFromMap((*source).DNSPtr) + schemaPrimaryIP2.AssigneeID = (*source).AssigneeID + schemaPrimaryIP2.AssigneeType = (*source).AssigneeType + schemaPrimaryIP2.AutoDelete = (*source).AutoDelete + schemaPrimaryIP2.Blocked = (*source).Blocked + schemaPrimaryIP2.Created = c.timeTimeToTimeTime((*source).Created) + schemaPrimaryIP2.Datacenter = c.SchemaFromDatacenter((*source).Datacenter) + schemaPrimaryIP = schemaPrimaryIP2 + } + return schemaPrimaryIP +} +func (c *converterImpl) SchemaFromSSHKey(source *SSHKey) schema.SSHKey { + var schemaSSHKey schema.SSHKey + if source != nil { + var schemaSSHKey2 schema.SSHKey + schemaSSHKey2.ID = (*source).ID + schemaSSHKey2.Name = (*source).Name + schemaSSHKey2.Fingerprint = (*source).Fingerprint + schemaSSHKey2.PublicKey = (*source).PublicKey + schemaSSHKey2.Labels = (*source).Labels + schemaSSHKey2.Created = c.timeTimeToTimeTime((*source).Created) + schemaSSHKey = schemaSSHKey2 + } + return schemaSSHKey +} +func (c *converterImpl) SchemaFromServer(source *Server) schema.Server { + var schemaServer schema.Server + if source != nil { + var schemaServer2 schema.Server + schemaServer2.ID = (*source).ID + schemaServer2.Name = (*source).Name + schemaServer2.Status = string((*source).Status) + schemaServer2.Created = c.timeTimeToTimeTime((*source).Created) + schemaServer2.PublicNet = c.SchemaFromServerPublicNet((*source).PublicNet) + var schemaServerPrivateNetList []schema.ServerPrivateNet + if (*source).PrivateNet != nil { + schemaServerPrivateNetList = make([]schema.ServerPrivateNet, len((*source).PrivateNet)) + for i := 0; i < len((*source).PrivateNet); i++ { + schemaServerPrivateNetList[i] = c.SchemaFromServerPrivateNet((*source).PrivateNet[i]) + } + } + schemaServer2.PrivateNet = schemaServerPrivateNetList + schemaServer2.ServerType = c.SchemaFromServerType((*source).ServerType) + schemaServer2.IncludedTraffic = (*source).IncludedTraffic + schemaServer2.OutgoingTraffic = mapZeroUint64ToNil((*source).OutgoingTraffic) + schemaServer2.IngoingTraffic = mapZeroUint64ToNil((*source).IngoingTraffic) + schemaServer2.BackupWindow = mapEmptyStringToNil((*source).BackupWindow) + schemaServer2.RescueEnabled = (*source).RescueEnabled + schemaServer2.ISO = c.pHcloudISOToPSchemaISO((*source).ISO) + schemaServer2.Locked = (*source).Locked + schemaServer2.Datacenter = c.SchemaFromDatacenter((*source).Datacenter) + schemaServer2.Image = c.pHcloudImageToPSchemaImage((*source).Image) + schemaServer2.Protection = c.hcloudServerProtectionToSchemaServerProtection((*source).Protection) + schemaServer2.Labels = (*source).Labels + var int64List []int64 + if (*source).Volumes != nil { + int64List = make([]int64, len((*source).Volumes)) + for j := 0; j < len((*source).Volumes); j++ { + int64List[j] = int64FromVolume((*source).Volumes[j]) + } + } + schemaServer2.Volumes = int64List + schemaServer2.PrimaryDiskSize = (*source).PrimaryDiskSize + schemaServer2.PlacementGroup = c.pHcloudPlacementGroupToPSchemaPlacementGroup((*source).PlacementGroup) + var int64List2 []int64 + if (*source).LoadBalancers != nil { + int64List2 = make([]int64, len((*source).LoadBalancers)) + for k := 0; k < len((*source).LoadBalancers); k++ { + int64List2[k] = c.pHcloudLoadBalancerToInt64((*source).LoadBalancers[k]) + } + } + schemaServer2.LoadBalancers = int64List2 + schemaServer = schemaServer2 + } + return schemaServer +} +func (c *converterImpl) SchemaFromServerPrivateNet(source ServerPrivateNet) schema.ServerPrivateNet { + var schemaServerPrivateNet schema.ServerPrivateNet + schemaServerPrivateNet.Network = c.pHcloudNetworkToInt64(source.Network) + schemaServerPrivateNet.IP = stringFromIP(source.IP) + var stringList []string + if source.Aliases != nil { + stringList = make([]string, len(source.Aliases)) + for i := 0; i < len(source.Aliases); i++ { + stringList[i] = stringFromIP(source.Aliases[i]) + } + } + schemaServerPrivateNet.AliasIPs = stringList + schemaServerPrivateNet.MACAddress = source.MACAddress + return schemaServerPrivateNet +} +func (c *converterImpl) SchemaFromServerPublicNet(source ServerPublicNet) schema.ServerPublicNet { + var schemaServerPublicNet schema.ServerPublicNet + schemaServerPublicNet.IPv4 = c.SchemaFromServerPublicNetIPv4(source.IPv4) + schemaServerPublicNet.IPv6 = c.SchemaFromServerPublicNetIPv6(source.IPv6) + var int64List []int64 + if source.FloatingIPs != nil { + int64List = make([]int64, len(source.FloatingIPs)) + for i := 0; i < len(source.FloatingIPs); i++ { + int64List[i] = int64FromFloatingIP(source.FloatingIPs[i]) + } + } + schemaServerPublicNet.FloatingIPs = int64List + var schemaServerFirewallList []schema.ServerFirewall + if source.Firewalls != nil { + schemaServerFirewallList = make([]schema.ServerFirewall, len(source.Firewalls)) + for j := 0; j < len(source.Firewalls); j++ { + schemaServerFirewallList[j] = serverFirewallSchemaFromFirewallStatus(source.Firewalls[j]) + } + } + schemaServerPublicNet.Firewalls = schemaServerFirewallList + return schemaServerPublicNet +} +func (c *converterImpl) SchemaFromServerPublicNetIPv4(source ServerPublicNetIPv4) schema.ServerPublicNetIPv4 { + var schemaServerPublicNetIPv4 schema.ServerPublicNetIPv4 + schemaServerPublicNetIPv4.ID = source.ID + schemaServerPublicNetIPv4.IP = stringFromIP(source.IP) + schemaServerPublicNetIPv4.Blocked = source.Blocked + schemaServerPublicNetIPv4.DNSPtr = source.DNSPtr + return schemaServerPublicNetIPv4 +} +func (c *converterImpl) SchemaFromServerPublicNetIPv6(source ServerPublicNetIPv6) schema.ServerPublicNetIPv6 { + var schemaServerPublicNetIPv6 schema.ServerPublicNetIPv6 + schemaServerPublicNetIPv6.ID = source.ID + schemaServerPublicNetIPv6.IP = c.pNetIPNetToString(source.Network) + schemaServerPublicNetIPv6.Blocked = source.Blocked + schemaServerPublicNetIPv6.DNSPtr = serverPublicNetIPv6DNSPtrSchemaFromMap(source.DNSPtr) + return schemaServerPublicNetIPv6 +} +func (c *converterImpl) SchemaFromServerType(source *ServerType) schema.ServerType { + var schemaServerType schema.ServerType + if source != nil { + var schemaServerType2 schema.ServerType + schemaServerType2.ID = (*source).ID + schemaServerType2.Name = (*source).Name + schemaServerType2.Description = (*source).Description + schemaServerType2.Cores = (*source).Cores + schemaServerType2.Memory = (*source).Memory + schemaServerType2.Disk = (*source).Disk + schemaServerType2.StorageType = string((*source).StorageType) + schemaServerType2.CPUType = string((*source).CPUType) + schemaServerType2.Architecture = string((*source).Architecture) + schemaServerType2.IncludedTraffic = (*source).IncludedTraffic + var schemaPricingServerTypePriceList []schema.PricingServerTypePrice + if (*source).Pricings != nil { + schemaPricingServerTypePriceList = make([]schema.PricingServerTypePrice, len((*source).Pricings)) + for i := 0; i < len((*source).Pricings); i++ { + schemaPricingServerTypePriceList[i] = c.schemaFromServerTypeLocationPricing((*source).Pricings[i]) + } + } + schemaServerType2.Prices = schemaPricingServerTypePriceList + schemaServerType2.Deprecated = isDeprecationNotNil((*source).DeprecatableResource.Deprecation) + schemaServerType2.DeprecatableResource = c.hcloudDeprecatableResourceToSchemaDeprecatableResource((*source).DeprecatableResource) + schemaServerType = schemaServerType2 + } + return schemaServerType +} +func (c *converterImpl) SchemaFromVolume(source *Volume) schema.Volume { + var schemaVolume schema.Volume + if source != nil { + var schemaVolume2 schema.Volume + schemaVolume2.ID = (*source).ID + schemaVolume2.Name = (*source).Name + schemaVolume2.Server = c.pHcloudServerToPInt64((*source).Server) + schemaVolume2.Status = string((*source).Status) + schemaVolume2.Location = c.SchemaFromLocation((*source).Location) + schemaVolume2.Size = (*source).Size + schemaVolume2.Protection = c.hcloudVolumeProtectionToSchemaVolumeProtection((*source).Protection) + schemaVolume2.Labels = (*source).Labels + schemaVolume2.LinuxDevice = (*source).LinuxDevice + schemaVolume2.Created = c.timeTimeToTimeTime((*source).Created) + schemaVolume = schemaVolume2 + } + return schemaVolume +} +func (c *converterImpl) ServerFromSchema(source schema.Server) *Server { + var hcloudServer Server + hcloudServer.ID = source.ID + hcloudServer.Name = source.Name + hcloudServer.Status = ServerStatus(source.Status) + hcloudServer.Created = c.timeTimeToTimeTime(source.Created) + hcloudServer.PublicNet = c.ServerPublicNetFromSchema(source.PublicNet) + var hcloudServerPrivateNetList []ServerPrivateNet + if source.PrivateNet != nil { + hcloudServerPrivateNetList = make([]ServerPrivateNet, len(source.PrivateNet)) + for i := 0; i < len(source.PrivateNet); i++ { + hcloudServerPrivateNetList[i] = c.ServerPrivateNetFromSchema(source.PrivateNet[i]) + } + } + hcloudServer.PrivateNet = hcloudServerPrivateNetList + hcloudServer.ServerType = c.ServerTypeFromSchema(source.ServerType) + hcloudServer.Datacenter = c.DatacenterFromSchema(source.Datacenter) + hcloudServer.IncludedTraffic = source.IncludedTraffic + var xuint64 uint64 + if source.OutgoingTraffic != nil { + xuint64 = *source.OutgoingTraffic + } + hcloudServer.OutgoingTraffic = xuint64 + var xuint642 uint64 + if source.IngoingTraffic != nil { + xuint642 = *source.IngoingTraffic + } + hcloudServer.IngoingTraffic = xuint642 + var xstring string + if source.BackupWindow != nil { + xstring = *source.BackupWindow + } + hcloudServer.BackupWindow = xstring + hcloudServer.RescueEnabled = source.RescueEnabled + hcloudServer.Locked = source.Locked + hcloudServer.ISO = c.pSchemaISOToPHcloudISO(source.ISO) + hcloudServer.Image = c.pSchemaImageToPHcloudImage(source.Image) + hcloudServer.Protection = c.schemaServerProtectionToHcloudServerProtection(source.Protection) + hcloudServer.Labels = source.Labels + var pHcloudVolumeList []*Volume + if source.Volumes != nil { + pHcloudVolumeList = make([]*Volume, len(source.Volumes)) + for j := 0; j < len(source.Volumes); j++ { + pHcloudVolumeList[j] = volumeFromInt64(source.Volumes[j]) + } + } + hcloudServer.Volumes = pHcloudVolumeList + hcloudServer.PrimaryDiskSize = source.PrimaryDiskSize + hcloudServer.PlacementGroup = c.pSchemaPlacementGroupToPHcloudPlacementGroup(source.PlacementGroup) + var pHcloudLoadBalancerList []*LoadBalancer + if source.LoadBalancers != nil { + pHcloudLoadBalancerList = make([]*LoadBalancer, len(source.LoadBalancers)) + for k := 0; k < len(source.LoadBalancers); k++ { + hcloudLoadBalancer := loadBalancerFromInt64(source.LoadBalancers[k]) + pHcloudLoadBalancerList[k] = &hcloudLoadBalancer + } + } + hcloudServer.LoadBalancers = pHcloudLoadBalancerList + return &hcloudServer +} +func (c *converterImpl) ServerMetricsFromSchema(source *schema.ServerGetMetricsResponse) (*ServerMetrics, error) { + var pHcloudServerMetrics *ServerMetrics + if source != nil { + var hcloudServerMetrics ServerMetrics + hcloudServerMetrics.Start = c.timeTimeToTimeTime((*source).Metrics.Start) + hcloudServerMetrics.End = c.timeTimeToTimeTime((*source).Metrics.End) + hcloudServerMetrics.Step = (*source).Metrics.Step + mapStringHcloudServerMetricsValueList := make(map[string][]ServerMetricsValue, len((*source).Metrics.TimeSeries)) + for key, value := range (*source).Metrics.TimeSeries { + hcloudServerMetricsValueList, err := serverMetricsTimeSeriesFromSchema(value) + if err != nil { + return nil, err + } + mapStringHcloudServerMetricsValueList[key] = hcloudServerMetricsValueList + } + hcloudServerMetrics.TimeSeries = mapStringHcloudServerMetricsValueList + pHcloudServerMetrics = &hcloudServerMetrics + } + return pHcloudServerMetrics, nil +} +func (c *converterImpl) ServerPrivateNetFromSchema(source schema.ServerPrivateNet) ServerPrivateNet { + var hcloudServerPrivateNet ServerPrivateNet + hcloudNetwork := networkFromInt64(source.Network) + hcloudServerPrivateNet.Network = &hcloudNetwork + hcloudServerPrivateNet.IP = ipFromString(source.IP) + var netIPList []net.IP + if source.AliasIPs != nil { + netIPList = make([]net.IP, len(source.AliasIPs)) + for i := 0; i < len(source.AliasIPs); i++ { + netIPList[i] = ipFromString(source.AliasIPs[i]) + } + } + hcloudServerPrivateNet.Aliases = netIPList + hcloudServerPrivateNet.MACAddress = source.MACAddress + return hcloudServerPrivateNet +} +func (c *converterImpl) ServerPublicNetFromSchema(source schema.ServerPublicNet) ServerPublicNet { + var hcloudServerPublicNet ServerPublicNet + hcloudServerPublicNet.IPv4 = c.ServerPublicNetIPv4FromSchema(source.IPv4) + hcloudServerPublicNet.IPv6 = c.ServerPublicNetIPv6FromSchema(source.IPv6) + var pHcloudFloatingIPList []*FloatingIP + if source.FloatingIPs != nil { + pHcloudFloatingIPList = make([]*FloatingIP, len(source.FloatingIPs)) + for i := 0; i < len(source.FloatingIPs); i++ { + pHcloudFloatingIPList[i] = floatingIPFromInt64(source.FloatingIPs[i]) + } + } + hcloudServerPublicNet.FloatingIPs = pHcloudFloatingIPList + var pHcloudServerFirewallStatusList []*ServerFirewallStatus + if source.Firewalls != nil { + pHcloudServerFirewallStatusList = make([]*ServerFirewallStatus, len(source.Firewalls)) + for j := 0; j < len(source.Firewalls); j++ { + pHcloudServerFirewallStatusList[j] = firewallStatusFromSchemaServerFirewall(source.Firewalls[j]) + } + } + hcloudServerPublicNet.Firewalls = pHcloudServerFirewallStatusList + return hcloudServerPublicNet +} +func (c *converterImpl) ServerPublicNetIPv4FromSchema(source schema.ServerPublicNetIPv4) ServerPublicNetIPv4 { + var hcloudServerPublicNetIPv4 ServerPublicNetIPv4 + hcloudServerPublicNetIPv4.ID = source.ID + hcloudServerPublicNetIPv4.IP = ipFromString(source.IP) + hcloudServerPublicNetIPv4.Blocked = source.Blocked + hcloudServerPublicNetIPv4.DNSPtr = source.DNSPtr + return hcloudServerPublicNetIPv4 +} +func (c *converterImpl) ServerPublicNetIPv6FromSchema(source schema.ServerPublicNetIPv6) ServerPublicNetIPv6 { + var hcloudServerPublicNetIPv6 ServerPublicNetIPv6 + hcloudServerPublicNetIPv6.ID = source.ID + hcloudServerPublicNetIPv6.IP = ipFromServerPublicNetIPv6Schema(source) + hcloudServerPublicNetIPv6.Network = ipNetFromServerPublicNetIPv6Schema(source) + hcloudServerPublicNetIPv6.Blocked = source.Blocked + hcloudServerPublicNetIPv6.DNSPtr = mapFromServerPublicNetIPv6DNSPtrSchema(source.DNSPtr) + return hcloudServerPublicNetIPv6 +} +func (c *converterImpl) ServerTypeFromSchema(source schema.ServerType) *ServerType { + var hcloudServerType ServerType + hcloudServerType.ID = source.ID + hcloudServerType.Name = source.Name + hcloudServerType.Description = source.Description + hcloudServerType.Cores = source.Cores + hcloudServerType.Memory = source.Memory + hcloudServerType.Disk = source.Disk + hcloudServerType.StorageType = StorageType(source.StorageType) + hcloudServerType.CPUType = CPUType(source.CPUType) + hcloudServerType.Architecture = Architecture(source.Architecture) + hcloudServerType.IncludedTraffic = source.IncludedTraffic + var hcloudServerTypeLocationPricingList []ServerTypeLocationPricing + if source.Prices != nil { + hcloudServerTypeLocationPricingList = make([]ServerTypeLocationPricing, len(source.Prices)) + for i := 0; i < len(source.Prices); i++ { + hcloudServerTypeLocationPricingList[i] = c.serverTypePricingFromSchema(source.Prices[i]) + } + } + hcloudServerType.Pricings = hcloudServerTypeLocationPricingList + hcloudServerType.DeprecatableResource = c.schemaDeprecatableResourceToHcloudDeprecatableResource(source.DeprecatableResource) + return &hcloudServerType +} +func (c *converterImpl) VolumeFromSchema(source schema.Volume) *Volume { + var hcloudVolume Volume + hcloudVolume.ID = source.ID + hcloudVolume.Name = source.Name + hcloudVolume.Status = VolumeStatus(source.Status) + var pHcloudServer *Server + if source.Server != nil { + hcloudServer := serverFromInt64(*source.Server) + pHcloudServer = &hcloudServer + } + hcloudVolume.Server = pHcloudServer + hcloudVolume.Location = c.LocationFromSchema(source.Location) + hcloudVolume.Size = source.Size + hcloudVolume.Protection = c.schemaVolumeProtectionToHcloudVolumeProtection(source.Protection) + hcloudVolume.Labels = source.Labels + hcloudVolume.LinuxDevice = source.LinuxDevice + hcloudVolume.Created = c.timeTimeToTimeTime(source.Created) + return &hcloudVolume +} +func (c *converterImpl) hcloudCertificateStatusTypeToString(source CertificateStatusType) string { + return string(source) +} +func (c *converterImpl) hcloudCertificateUsedByRefToSchemaCertificateUsedByRef(source CertificateUsedByRef) schema.CertificateUsedByRef { + var schemaCertificateUsedByRef schema.CertificateUsedByRef + schemaCertificateUsedByRef.ID = source.ID + schemaCertificateUsedByRef.Type = string(source.Type) + return schemaCertificateUsedByRef +} +func (c *converterImpl) hcloudDatacenterServerTypesToSchemaDatacenterServerTypes(source DatacenterServerTypes) schema.DatacenterServerTypes { + var schemaDatacenterServerTypes schema.DatacenterServerTypes + var int64List []int64 + if source.Supported != nil { + int64List = make([]int64, len(source.Supported)) + for i := 0; i < len(source.Supported); i++ { + int64List[i] = int64FromServerType(source.Supported[i]) + } + } + schemaDatacenterServerTypes.Supported = int64List + var int64List2 []int64 + if source.AvailableForMigration != nil { + int64List2 = make([]int64, len(source.AvailableForMigration)) + for j := 0; j < len(source.AvailableForMigration); j++ { + int64List2[j] = int64FromServerType(source.AvailableForMigration[j]) + } + } + schemaDatacenterServerTypes.AvailableForMigration = int64List2 + var int64List3 []int64 + if source.Available != nil { + int64List3 = make([]int64, len(source.Available)) + for k := 0; k < len(source.Available); k++ { + int64List3[k] = int64FromServerType(source.Available[k]) + } + } + schemaDatacenterServerTypes.Available = int64List3 + return schemaDatacenterServerTypes +} +func (c *converterImpl) hcloudDeprecatableResourceToSchemaDeprecatableResource(source DeprecatableResource) schema.DeprecatableResource { + var schemaDeprecatableResource schema.DeprecatableResource + schemaDeprecatableResource.Deprecation = c.SchemaFromDeprecation(source.Deprecation) + return schemaDeprecatableResource +} +func (c *converterImpl) hcloudFirewallRuleToSchemaFirewallRule(source FirewallRule) schema.FirewallRule { + var schemaFirewallRule schema.FirewallRule + schemaFirewallRule.Direction = string(source.Direction) + var stringList []string + if source.SourceIPs != nil { + stringList = make([]string, len(source.SourceIPs)) + for i := 0; i < len(source.SourceIPs); i++ { + stringList[i] = stringFromIPNet(source.SourceIPs[i]) + } + } + schemaFirewallRule.SourceIPs = stringList + var stringList2 []string + if source.DestinationIPs != nil { + stringList2 = make([]string, len(source.DestinationIPs)) + for j := 0; j < len(source.DestinationIPs); j++ { + stringList2[j] = stringFromIPNet(source.DestinationIPs[j]) + } + } + schemaFirewallRule.DestinationIPs = stringList2 + schemaFirewallRule.Protocol = string(source.Protocol) + schemaFirewallRule.Port = source.Port + schemaFirewallRule.Description = source.Description + return schemaFirewallRule +} +func (c *converterImpl) hcloudFloatingIPProtectionToSchemaFloatingIPProtection(source FloatingIPProtection) schema.FloatingIPProtection { + var schemaFloatingIPProtection schema.FloatingIPProtection + schemaFloatingIPProtection.Delete = source.Delete + return schemaFloatingIPProtection +} +func (c *converterImpl) hcloudImageProtectionToSchemaImageProtection(source ImageProtection) schema.ImageProtection { + var schemaImageProtection schema.ImageProtection + schemaImageProtection.Delete = source.Delete + return schemaImageProtection +} +func (c *converterImpl) hcloudLoadBalancerAlgorithmToSchemaLoadBalancerAlgorithm(source LoadBalancerAlgorithm) schema.LoadBalancerAlgorithm { + var schemaLoadBalancerAlgorithm schema.LoadBalancerAlgorithm + schemaLoadBalancerAlgorithm.Type = string(source.Type) + return schemaLoadBalancerAlgorithm +} +func (c *converterImpl) hcloudLoadBalancerCreateOptsServiceToSchemaLoadBalancerCreateRequestService(source LoadBalancerCreateOptsService) schema.LoadBalancerCreateRequestService { + var schemaLoadBalancerCreateRequestService schema.LoadBalancerCreateRequestService + schemaLoadBalancerCreateRequestService.Protocol = string(source.Protocol) + schemaLoadBalancerCreateRequestService.ListenPort = source.ListenPort + schemaLoadBalancerCreateRequestService.DestinationPort = source.DestinationPort + schemaLoadBalancerCreateRequestService.Proxyprotocol = source.Proxyprotocol + schemaLoadBalancerCreateRequestService.HTTP = c.pHcloudLoadBalancerCreateOptsServiceHTTPToPSchemaLoadBalancerCreateRequestServiceHTTP(source.HTTP) + schemaLoadBalancerCreateRequestService.HealthCheck = c.pHcloudLoadBalancerCreateOptsServiceHealthCheckToPSchemaLoadBalancerCreateRequestServiceHealthCheck(source.HealthCheck) + return schemaLoadBalancerCreateRequestService +} +func (c *converterImpl) hcloudLoadBalancerCreateOptsTargetToSchemaLoadBalancerCreateRequestTarget(source LoadBalancerCreateOptsTarget) schema.LoadBalancerCreateRequestTarget { + var schemaLoadBalancerCreateRequestTarget schema.LoadBalancerCreateRequestTarget + schemaLoadBalancerCreateRequestTarget.Type = string(source.Type) + schemaLoadBalancerCreateRequestTarget.Server = schemaFromLoadBalancerCreateOptsTargetServer(source.Server) + schemaLoadBalancerCreateRequestTarget.LabelSelector = schemaFromLoadBalancerCreateOptsTargetLabelSelector(source.LabelSelector) + schemaLoadBalancerCreateRequestTarget.IP = schemaFromLoadBalancerCreateOptsTargetIP(source.IP) + schemaLoadBalancerCreateRequestTarget.UsePrivateIP = source.UsePrivateIP + return schemaLoadBalancerCreateRequestTarget +} +func (c *converterImpl) hcloudLoadBalancerPrivateNetToSchemaLoadBalancerPrivateNet(source LoadBalancerPrivateNet) schema.LoadBalancerPrivateNet { + var schemaLoadBalancerPrivateNet schema.LoadBalancerPrivateNet + schemaLoadBalancerPrivateNet.Network = c.pHcloudNetworkToInt64(source.Network) + schemaLoadBalancerPrivateNet.IP = stringFromIP(source.IP) + return schemaLoadBalancerPrivateNet +} +func (c *converterImpl) hcloudLoadBalancerProtectionToSchemaLoadBalancerProtection(source LoadBalancerProtection) schema.LoadBalancerProtection { + var schemaLoadBalancerProtection schema.LoadBalancerProtection + schemaLoadBalancerProtection.Delete = source.Delete + return schemaLoadBalancerProtection +} +func (c *converterImpl) hcloudLoadBalancerPublicNetIPv4ToSchemaLoadBalancerPublicNetIPv4(source LoadBalancerPublicNetIPv4) schema.LoadBalancerPublicNetIPv4 { + var schemaLoadBalancerPublicNetIPv4 schema.LoadBalancerPublicNetIPv4 + schemaLoadBalancerPublicNetIPv4.IP = stringFromIP(source.IP) + schemaLoadBalancerPublicNetIPv4.DNSPtr = source.DNSPtr + return schemaLoadBalancerPublicNetIPv4 +} +func (c *converterImpl) hcloudLoadBalancerPublicNetIPv6ToSchemaLoadBalancerPublicNetIPv6(source LoadBalancerPublicNetIPv6) schema.LoadBalancerPublicNetIPv6 { + var schemaLoadBalancerPublicNetIPv6 schema.LoadBalancerPublicNetIPv6 + schemaLoadBalancerPublicNetIPv6.IP = stringFromIP(source.IP) + schemaLoadBalancerPublicNetIPv6.DNSPtr = source.DNSPtr + return schemaLoadBalancerPublicNetIPv6 +} +func (c *converterImpl) hcloudLoadBalancerPublicNetToSchemaLoadBalancerPublicNet(source LoadBalancerPublicNet) schema.LoadBalancerPublicNet { + var schemaLoadBalancerPublicNet schema.LoadBalancerPublicNet + schemaLoadBalancerPublicNet.Enabled = source.Enabled + schemaLoadBalancerPublicNet.IPv4 = c.hcloudLoadBalancerPublicNetIPv4ToSchemaLoadBalancerPublicNetIPv4(source.IPv4) + schemaLoadBalancerPublicNet.IPv6 = c.hcloudLoadBalancerPublicNetIPv6ToSchemaLoadBalancerPublicNetIPv6(source.IPv6) + return schemaLoadBalancerPublicNet +} +func (c *converterImpl) hcloudLoadBalancerServiceHTTPToPSchemaLoadBalancerServiceHTTP(source LoadBalancerServiceHTTP) *schema.LoadBalancerServiceHTTP { + var schemaLoadBalancerServiceHTTP schema.LoadBalancerServiceHTTP + schemaLoadBalancerServiceHTTP.CookieName = source.CookieName + schemaLoadBalancerServiceHTTP.CookieLifetime = intSecondsFromDuration(source.CookieLifetime) + var int64List []int64 + if source.Certificates != nil { + int64List = make([]int64, len(source.Certificates)) + for i := 0; i < len(source.Certificates); i++ { + int64List[i] = int64FromCertificate(source.Certificates[i]) + } + } + schemaLoadBalancerServiceHTTP.Certificates = int64List + schemaLoadBalancerServiceHTTP.RedirectHTTP = source.RedirectHTTP + schemaLoadBalancerServiceHTTP.StickySessions = source.StickySessions + return &schemaLoadBalancerServiceHTTP +} +func (c *converterImpl) hcloudNetworkProtectionToSchemaNetworkProtection(source NetworkProtection) schema.NetworkProtection { + var schemaNetworkProtection schema.NetworkProtection + schemaNetworkProtection.Delete = source.Delete + return schemaNetworkProtection +} +func (c *converterImpl) hcloudPriceToSchemaPrice(source Price) schema.Price { + var schemaPrice schema.Price + schemaPrice.Net = source.Net + schemaPrice.Gross = source.Gross + return schemaPrice +} +func (c *converterImpl) hcloudPrimaryIPPriceToSchemaPrice(source PrimaryIPPrice) schema.Price { + var schemaPrice schema.Price + schemaPrice.Net = source.Net + schemaPrice.Gross = source.Gross + return schemaPrice +} +func (c *converterImpl) hcloudPrimaryIPProtectionToSchemaPrimaryIPProtection(source PrimaryIPProtection) schema.PrimaryIPProtection { + var schemaPrimaryIPProtection schema.PrimaryIPProtection + schemaPrimaryIPProtection.Delete = source.Delete + return schemaPrimaryIPProtection +} +func (c *converterImpl) hcloudServerBackupPricingToSchemaPricingServerBackup(source ServerBackupPricing) schema.PricingServerBackup { + var schemaPricingServerBackup schema.PricingServerBackup + schemaPricingServerBackup.Percentage = source.Percentage + return schemaPricingServerBackup +} +func (c *converterImpl) hcloudServerProtectionToSchemaServerProtection(source ServerProtection) schema.ServerProtection { + var schemaServerProtection schema.ServerProtection + schemaServerProtection.Delete = source.Delete + schemaServerProtection.Rebuild = source.Rebuild + return schemaServerProtection +} +func (c *converterImpl) hcloudVolumeProtectionToSchemaVolumeProtection(source VolumeProtection) schema.VolumeProtection { + var schemaVolumeProtection schema.VolumeProtection + schemaVolumeProtection.Delete = source.Delete + return schemaVolumeProtection +} +func (c *converterImpl) intISOFromSchema(source schema.ISO) ISO { + var hcloudISO ISO + hcloudISO.ID = source.ID + hcloudISO.Name = source.Name + hcloudISO.Description = source.Description + hcloudISO.Type = ISOType(source.Type) + var pHcloudArchitecture *Architecture + if source.Architecture != nil { + hcloudArchitecture := Architecture(*source.Architecture) + pHcloudArchitecture = &hcloudArchitecture + } + hcloudISO.Architecture = pHcloudArchitecture + var pTimeTime *time.Time + if source.DeprecatableResource.Deprecation != nil { + pTimeTime = &source.DeprecatableResource.Deprecation.UnavailableAfter + } + hcloudISO.Deprecated = c.pTimeTimeToTimeTime(pTimeTime) + hcloudISO.DeprecatableResource = c.schemaDeprecatableResourceToHcloudDeprecatableResource(source.DeprecatableResource) + return hcloudISO +} +func (c *converterImpl) intSchemaFromImage(source Image) schema.Image { + var schemaImage schema.Image + schemaImage.ID = source.ID + schemaImage.Status = string(source.Status) + schemaImage.Type = string(source.Type) + pString := source.Name + schemaImage.Name = &pString + schemaImage.Description = source.Description + schemaImage.ImageSize = mapZeroFloat32ToNil(source.ImageSize) + schemaImage.DiskSize = source.DiskSize + schemaImage.Created = timeToTimePtr(source.Created) + schemaImage.CreatedFrom = c.pHcloudServerToPSchemaImageCreatedFrom(source.CreatedFrom) + schemaImage.BoundTo = c.pHcloudServerToPInt64(source.BoundTo) + schemaImage.OSFlavor = source.OSFlavor + pString2 := source.OSVersion + schemaImage.OSVersion = &pString2 + schemaImage.Architecture = string(source.Architecture) + schemaImage.RapidDeploy = source.RapidDeploy + schemaImage.Protection = c.hcloudImageProtectionToSchemaImageProtection(source.Protection) + schemaImage.Deprecated = timeToTimePtr(source.Deprecated) + schemaImage.Deleted = timeToTimePtr(source.Deleted) + schemaImage.Labels = source.Labels + return schemaImage +} +func (c *converterImpl) pHcloudActionResourceToSchemaActionResourceReference(source *ActionResource) schema.ActionResourceReference { + var schemaActionResourceReference schema.ActionResourceReference + if source != nil { + var schemaActionResourceReference2 schema.ActionResourceReference + schemaActionResourceReference2.ID = (*source).ID + schemaActionResourceReference2.Type = string((*source).Type) + schemaActionResourceReference = schemaActionResourceReference2 + } + return schemaActionResourceReference +} +func (c *converterImpl) pHcloudCertificateStatusToPSchemaCertificateStatusRef(source *CertificateStatus) *schema.CertificateStatusRef { + var pSchemaCertificateStatusRef *schema.CertificateStatusRef + if source != nil { + var schemaCertificateStatusRef schema.CertificateStatusRef + schemaCertificateStatusRef.Issuance = c.hcloudCertificateStatusTypeToString((*source).Issuance) + schemaCertificateStatusRef.Renewal = c.hcloudCertificateStatusTypeToString((*source).Renewal) + schemaCertificateStatusRef.Error = c.pHcloudErrorToPSchemaError((*source).Error) + pSchemaCertificateStatusRef = &schemaCertificateStatusRef + } + return pSchemaCertificateStatusRef +} +func (c *converterImpl) pHcloudErrorToPSchemaError(source *Error) *schema.Error { + var pSchemaError *schema.Error + if source != nil { + schemaError := c.SchemaFromError((*source)) + pSchemaError = &schemaError + } + return pSchemaError +} +func (c *converterImpl) pHcloudFirewallResourceLabelSelectorToPSchemaFirewallResourceLabelSelector(source *FirewallResourceLabelSelector) *schema.FirewallResourceLabelSelector { + var pSchemaFirewallResourceLabelSelector *schema.FirewallResourceLabelSelector + if source != nil { + var schemaFirewallResourceLabelSelector schema.FirewallResourceLabelSelector + schemaFirewallResourceLabelSelector.Selector = (*source).Selector + pSchemaFirewallResourceLabelSelector = &schemaFirewallResourceLabelSelector + } + return pSchemaFirewallResourceLabelSelector +} +func (c *converterImpl) pHcloudFirewallResourceServerToPSchemaFirewallResourceServer(source *FirewallResourceServer) *schema.FirewallResourceServer { + var pSchemaFirewallResourceServer *schema.FirewallResourceServer + if source != nil { + var schemaFirewallResourceServer schema.FirewallResourceServer + schemaFirewallResourceServer.ID = (*source).ID + pSchemaFirewallResourceServer = &schemaFirewallResourceServer + } + return pSchemaFirewallResourceServer +} +func (c *converterImpl) pHcloudISOToPSchemaISO(source *ISO) *schema.ISO { + var pSchemaISO *schema.ISO + if source != nil { + var schemaISO schema.ISO + schemaISO.ID = (*source).ID + schemaISO.Name = (*source).Name + schemaISO.Description = (*source).Description + schemaISO.Type = string((*source).Type) + var pString *string + if (*source).Architecture != nil { + xstring := string(*(*source).Architecture) + pString = &xstring + } + schemaISO.Architecture = pString + schemaISO.DeprecatableResource = c.hcloudDeprecatableResourceToSchemaDeprecatableResource((*source).DeprecatableResource) + pSchemaISO = &schemaISO + } + return pSchemaISO +} +func (c *converterImpl) pHcloudImageToPSchemaImage(source *Image) *schema.Image { + var pSchemaImage *schema.Image + if source != nil { + schemaImage := c.intSchemaFromImage((*source)) + pSchemaImage = &schemaImage + } + return pSchemaImage +} +func (c *converterImpl) pHcloudLoadBalancerAddServiceOptsHTTPToPSchemaLoadBalancerActionAddServiceRequestHTTP(source *LoadBalancerAddServiceOptsHTTP) *schema.LoadBalancerActionAddServiceRequestHTTP { + var pSchemaLoadBalancerActionAddServiceRequestHTTP *schema.LoadBalancerActionAddServiceRequestHTTP + if source != nil { + var schemaLoadBalancerActionAddServiceRequestHTTP schema.LoadBalancerActionAddServiceRequestHTTP + schemaLoadBalancerActionAddServiceRequestHTTP.CookieName = (*source).CookieName + var pInt *int + if (*source).CookieLifetime != nil { + xint := intSecondsFromDuration(*(*source).CookieLifetime) + pInt = &xint + } + schemaLoadBalancerActionAddServiceRequestHTTP.CookieLifetime = pInt + var int64List []int64 + if (*source).Certificates != nil { + int64List = make([]int64, len((*source).Certificates)) + for i := 0; i < len((*source).Certificates); i++ { + int64List[i] = int64FromCertificate((*source).Certificates[i]) + } + } + schemaLoadBalancerActionAddServiceRequestHTTP.Certificates = &int64List + schemaLoadBalancerActionAddServiceRequestHTTP.RedirectHTTP = (*source).RedirectHTTP + schemaLoadBalancerActionAddServiceRequestHTTP.StickySessions = (*source).StickySessions + pSchemaLoadBalancerActionAddServiceRequestHTTP = &schemaLoadBalancerActionAddServiceRequestHTTP + } + return pSchemaLoadBalancerActionAddServiceRequestHTTP +} +func (c *converterImpl) pHcloudLoadBalancerAddServiceOptsHealthCheckHTTPToPSchemaLoadBalancerActionAddServiceRequestHealthCheckHTTP(source *LoadBalancerAddServiceOptsHealthCheckHTTP) *schema.LoadBalancerActionAddServiceRequestHealthCheckHTTP { + var pSchemaLoadBalancerActionAddServiceRequestHealthCheckHTTP *schema.LoadBalancerActionAddServiceRequestHealthCheckHTTP + if source != nil { + var schemaLoadBalancerActionAddServiceRequestHealthCheckHTTP schema.LoadBalancerActionAddServiceRequestHealthCheckHTTP + schemaLoadBalancerActionAddServiceRequestHealthCheckHTTP.Domain = (*source).Domain + schemaLoadBalancerActionAddServiceRequestHealthCheckHTTP.Path = (*source).Path + schemaLoadBalancerActionAddServiceRequestHealthCheckHTTP.Response = (*source).Response + schemaLoadBalancerActionAddServiceRequestHealthCheckHTTP.StatusCodes = &(*source).StatusCodes + schemaLoadBalancerActionAddServiceRequestHealthCheckHTTP.TLS = (*source).TLS + pSchemaLoadBalancerActionAddServiceRequestHealthCheckHTTP = &schemaLoadBalancerActionAddServiceRequestHealthCheckHTTP + } + return pSchemaLoadBalancerActionAddServiceRequestHealthCheckHTTP +} +func (c *converterImpl) pHcloudLoadBalancerAddServiceOptsHealthCheckToPSchemaLoadBalancerActionAddServiceRequestHealthCheck(source *LoadBalancerAddServiceOptsHealthCheck) *schema.LoadBalancerActionAddServiceRequestHealthCheck { + var pSchemaLoadBalancerActionAddServiceRequestHealthCheck *schema.LoadBalancerActionAddServiceRequestHealthCheck + if source != nil { + var schemaLoadBalancerActionAddServiceRequestHealthCheck schema.LoadBalancerActionAddServiceRequestHealthCheck + schemaLoadBalancerActionAddServiceRequestHealthCheck.Protocol = string((*source).Protocol) + schemaLoadBalancerActionAddServiceRequestHealthCheck.Port = (*source).Port + var pInt *int + if (*source).Interval != nil { + xint := intSecondsFromDuration(*(*source).Interval) + pInt = &xint + } + schemaLoadBalancerActionAddServiceRequestHealthCheck.Interval = pInt + var pInt2 *int + if (*source).Timeout != nil { + xint2 := intSecondsFromDuration(*(*source).Timeout) + pInt2 = &xint2 + } + schemaLoadBalancerActionAddServiceRequestHealthCheck.Timeout = pInt2 + schemaLoadBalancerActionAddServiceRequestHealthCheck.Retries = (*source).Retries + schemaLoadBalancerActionAddServiceRequestHealthCheck.HTTP = c.pHcloudLoadBalancerAddServiceOptsHealthCheckHTTPToPSchemaLoadBalancerActionAddServiceRequestHealthCheckHTTP((*source).HTTP) + pSchemaLoadBalancerActionAddServiceRequestHealthCheck = &schemaLoadBalancerActionAddServiceRequestHealthCheck + } + return pSchemaLoadBalancerActionAddServiceRequestHealthCheck +} +func (c *converterImpl) pHcloudLoadBalancerAlgorithmToPSchemaLoadBalancerCreateRequestAlgorithm(source *LoadBalancerAlgorithm) *schema.LoadBalancerCreateRequestAlgorithm { + var pSchemaLoadBalancerCreateRequestAlgorithm *schema.LoadBalancerCreateRequestAlgorithm + if source != nil { + var schemaLoadBalancerCreateRequestAlgorithm schema.LoadBalancerCreateRequestAlgorithm + schemaLoadBalancerCreateRequestAlgorithm.Type = string((*source).Type) + pSchemaLoadBalancerCreateRequestAlgorithm = &schemaLoadBalancerCreateRequestAlgorithm + } + return pSchemaLoadBalancerCreateRequestAlgorithm +} +func (c *converterImpl) pHcloudLoadBalancerCreateOptsServiceHTTPToPSchemaLoadBalancerCreateRequestServiceHTTP(source *LoadBalancerCreateOptsServiceHTTP) *schema.LoadBalancerCreateRequestServiceHTTP { + var pSchemaLoadBalancerCreateRequestServiceHTTP *schema.LoadBalancerCreateRequestServiceHTTP + if source != nil { + var schemaLoadBalancerCreateRequestServiceHTTP schema.LoadBalancerCreateRequestServiceHTTP + schemaLoadBalancerCreateRequestServiceHTTP.CookieName = (*source).CookieName + var pInt *int + if (*source).CookieLifetime != nil { + xint := intSecondsFromDuration(*(*source).CookieLifetime) + pInt = &xint + } + schemaLoadBalancerCreateRequestServiceHTTP.CookieLifetime = pInt + var int64List []int64 + if (*source).Certificates != nil { + int64List = make([]int64, len((*source).Certificates)) + for i := 0; i < len((*source).Certificates); i++ { + int64List[i] = int64FromCertificate((*source).Certificates[i]) + } + } + schemaLoadBalancerCreateRequestServiceHTTP.Certificates = &int64List + schemaLoadBalancerCreateRequestServiceHTTP.RedirectHTTP = (*source).RedirectHTTP + schemaLoadBalancerCreateRequestServiceHTTP.StickySessions = (*source).StickySessions + pSchemaLoadBalancerCreateRequestServiceHTTP = &schemaLoadBalancerCreateRequestServiceHTTP + } + return pSchemaLoadBalancerCreateRequestServiceHTTP +} +func (c *converterImpl) pHcloudLoadBalancerCreateOptsServiceHealthCheckHTTPToPSchemaLoadBalancerCreateRequestServiceHealthCheckHTTP(source *LoadBalancerCreateOptsServiceHealthCheckHTTP) *schema.LoadBalancerCreateRequestServiceHealthCheckHTTP { + var pSchemaLoadBalancerCreateRequestServiceHealthCheckHTTP *schema.LoadBalancerCreateRequestServiceHealthCheckHTTP + if source != nil { + var schemaLoadBalancerCreateRequestServiceHealthCheckHTTP schema.LoadBalancerCreateRequestServiceHealthCheckHTTP + schemaLoadBalancerCreateRequestServiceHealthCheckHTTP.Domain = (*source).Domain + schemaLoadBalancerCreateRequestServiceHealthCheckHTTP.Path = (*source).Path + schemaLoadBalancerCreateRequestServiceHealthCheckHTTP.Response = (*source).Response + schemaLoadBalancerCreateRequestServiceHealthCheckHTTP.StatusCodes = &(*source).StatusCodes + schemaLoadBalancerCreateRequestServiceHealthCheckHTTP.TLS = (*source).TLS + pSchemaLoadBalancerCreateRequestServiceHealthCheckHTTP = &schemaLoadBalancerCreateRequestServiceHealthCheckHTTP + } + return pSchemaLoadBalancerCreateRequestServiceHealthCheckHTTP +} +func (c *converterImpl) pHcloudLoadBalancerCreateOptsServiceHealthCheckToPSchemaLoadBalancerCreateRequestServiceHealthCheck(source *LoadBalancerCreateOptsServiceHealthCheck) *schema.LoadBalancerCreateRequestServiceHealthCheck { + var pSchemaLoadBalancerCreateRequestServiceHealthCheck *schema.LoadBalancerCreateRequestServiceHealthCheck + if source != nil { + var schemaLoadBalancerCreateRequestServiceHealthCheck schema.LoadBalancerCreateRequestServiceHealthCheck + schemaLoadBalancerCreateRequestServiceHealthCheck.Protocol = string((*source).Protocol) + schemaLoadBalancerCreateRequestServiceHealthCheck.Port = (*source).Port + var pInt *int + if (*source).Interval != nil { + xint := intSecondsFromDuration(*(*source).Interval) + pInt = &xint + } + schemaLoadBalancerCreateRequestServiceHealthCheck.Interval = pInt + var pInt2 *int + if (*source).Timeout != nil { + xint2 := intSecondsFromDuration(*(*source).Timeout) + pInt2 = &xint2 + } + schemaLoadBalancerCreateRequestServiceHealthCheck.Timeout = pInt2 + schemaLoadBalancerCreateRequestServiceHealthCheck.Retries = (*source).Retries + schemaLoadBalancerCreateRequestServiceHealthCheck.HTTP = c.pHcloudLoadBalancerCreateOptsServiceHealthCheckHTTPToPSchemaLoadBalancerCreateRequestServiceHealthCheckHTTP((*source).HTTP) + pSchemaLoadBalancerCreateRequestServiceHealthCheck = &schemaLoadBalancerCreateRequestServiceHealthCheck + } + return pSchemaLoadBalancerCreateRequestServiceHealthCheck +} +func (c *converterImpl) pHcloudLoadBalancerServiceHealthCheckHTTPToPSchemaLoadBalancerServiceHealthCheckHTTP(source *LoadBalancerServiceHealthCheckHTTP) *schema.LoadBalancerServiceHealthCheckHTTP { + var pSchemaLoadBalancerServiceHealthCheckHTTP *schema.LoadBalancerServiceHealthCheckHTTP + if source != nil { + var schemaLoadBalancerServiceHealthCheckHTTP schema.LoadBalancerServiceHealthCheckHTTP + schemaLoadBalancerServiceHealthCheckHTTP.Domain = (*source).Domain + schemaLoadBalancerServiceHealthCheckHTTP.Path = (*source).Path + schemaLoadBalancerServiceHealthCheckHTTP.Response = (*source).Response + schemaLoadBalancerServiceHealthCheckHTTP.StatusCodes = (*source).StatusCodes + schemaLoadBalancerServiceHealthCheckHTTP.TLS = (*source).TLS + pSchemaLoadBalancerServiceHealthCheckHTTP = &schemaLoadBalancerServiceHealthCheckHTTP + } + return pSchemaLoadBalancerServiceHealthCheckHTTP +} +func (c *converterImpl) pHcloudLoadBalancerTargetIPToPSchemaLoadBalancerTargetIP(source *LoadBalancerTargetIP) *schema.LoadBalancerTargetIP { + var pSchemaLoadBalancerTargetIP *schema.LoadBalancerTargetIP + if source != nil { + var schemaLoadBalancerTargetIP schema.LoadBalancerTargetIP + schemaLoadBalancerTargetIP.IP = (*source).IP + pSchemaLoadBalancerTargetIP = &schemaLoadBalancerTargetIP + } + return pSchemaLoadBalancerTargetIP +} +func (c *converterImpl) pHcloudLoadBalancerTargetLabelSelectorToPSchemaLoadBalancerTargetLabelSelector(source *LoadBalancerTargetLabelSelector) *schema.LoadBalancerTargetLabelSelector { + var pSchemaLoadBalancerTargetLabelSelector *schema.LoadBalancerTargetLabelSelector + if source != nil { + var schemaLoadBalancerTargetLabelSelector schema.LoadBalancerTargetLabelSelector + schemaLoadBalancerTargetLabelSelector.Selector = (*source).Selector + pSchemaLoadBalancerTargetLabelSelector = &schemaLoadBalancerTargetLabelSelector + } + return pSchemaLoadBalancerTargetLabelSelector +} +func (c *converterImpl) pHcloudLoadBalancerTargetServerToPSchemaLoadBalancerTargetServer(source *LoadBalancerTargetServer) *schema.LoadBalancerTargetServer { + var pSchemaLoadBalancerTargetServer *schema.LoadBalancerTargetServer + if source != nil { + schemaLoadBalancerTargetServer := c.SchemaFromLoadBalancerServerTarget((*source)) + pSchemaLoadBalancerTargetServer = &schemaLoadBalancerTargetServer + } + return pSchemaLoadBalancerTargetServer +} +func (c *converterImpl) pHcloudLoadBalancerToInt64(source *LoadBalancer) int64 { + var xint64 int64 + if source != nil { + xint64 = int64FromLoadBalancer((*source)) + } + return xint64 +} +func (c *converterImpl) pHcloudLoadBalancerUpdateServiceOptsHTTPToPSchemaLoadBalancerActionUpdateServiceRequestHTTP(source *LoadBalancerUpdateServiceOptsHTTP) *schema.LoadBalancerActionUpdateServiceRequestHTTP { + var pSchemaLoadBalancerActionUpdateServiceRequestHTTP *schema.LoadBalancerActionUpdateServiceRequestHTTP + if source != nil { + var schemaLoadBalancerActionUpdateServiceRequestHTTP schema.LoadBalancerActionUpdateServiceRequestHTTP + schemaLoadBalancerActionUpdateServiceRequestHTTP.CookieName = (*source).CookieName + var pInt *int + if (*source).CookieLifetime != nil { + xint := intSecondsFromDuration(*(*source).CookieLifetime) + pInt = &xint + } + schemaLoadBalancerActionUpdateServiceRequestHTTP.CookieLifetime = pInt + var int64List []int64 + if (*source).Certificates != nil { + int64List = make([]int64, len((*source).Certificates)) + for i := 0; i < len((*source).Certificates); i++ { + int64List[i] = int64FromCertificate((*source).Certificates[i]) + } + } + schemaLoadBalancerActionUpdateServiceRequestHTTP.Certificates = &int64List + schemaLoadBalancerActionUpdateServiceRequestHTTP.RedirectHTTP = (*source).RedirectHTTP + schemaLoadBalancerActionUpdateServiceRequestHTTP.StickySessions = (*source).StickySessions + pSchemaLoadBalancerActionUpdateServiceRequestHTTP = &schemaLoadBalancerActionUpdateServiceRequestHTTP + } + return pSchemaLoadBalancerActionUpdateServiceRequestHTTP +} +func (c *converterImpl) pHcloudLoadBalancerUpdateServiceOptsHealthCheckHTTPToPSchemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP(source *LoadBalancerUpdateServiceOptsHealthCheckHTTP) *schema.LoadBalancerActionUpdateServiceRequestHealthCheckHTTP { + var pSchemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP *schema.LoadBalancerActionUpdateServiceRequestHealthCheckHTTP + if source != nil { + var schemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP schema.LoadBalancerActionUpdateServiceRequestHealthCheckHTTP + schemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP.Domain = (*source).Domain + schemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP.Path = (*source).Path + schemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP.Response = (*source).Response + schemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP.StatusCodes = &(*source).StatusCodes + schemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP.TLS = (*source).TLS + pSchemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP = &schemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP + } + return pSchemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP +} +func (c *converterImpl) pHcloudLoadBalancerUpdateServiceOptsHealthCheckToPSchemaLoadBalancerActionUpdateServiceRequestHealthCheck(source *LoadBalancerUpdateServiceOptsHealthCheck) *schema.LoadBalancerActionUpdateServiceRequestHealthCheck { + var pSchemaLoadBalancerActionUpdateServiceRequestHealthCheck *schema.LoadBalancerActionUpdateServiceRequestHealthCheck + if source != nil { + var schemaLoadBalancerActionUpdateServiceRequestHealthCheck schema.LoadBalancerActionUpdateServiceRequestHealthCheck + schemaLoadBalancerActionUpdateServiceRequestHealthCheck.Protocol = stringPtrFromLoadBalancerServiceProtocol((*source).Protocol) + schemaLoadBalancerActionUpdateServiceRequestHealthCheck.Port = (*source).Port + var pInt *int + if (*source).Interval != nil { + xint := intSecondsFromDuration(*(*source).Interval) + pInt = &xint + } + schemaLoadBalancerActionUpdateServiceRequestHealthCheck.Interval = pInt + var pInt2 *int + if (*source).Timeout != nil { + xint2 := intSecondsFromDuration(*(*source).Timeout) + pInt2 = &xint2 + } + schemaLoadBalancerActionUpdateServiceRequestHealthCheck.Timeout = pInt2 + schemaLoadBalancerActionUpdateServiceRequestHealthCheck.Retries = (*source).Retries + schemaLoadBalancerActionUpdateServiceRequestHealthCheck.HTTP = c.pHcloudLoadBalancerUpdateServiceOptsHealthCheckHTTPToPSchemaLoadBalancerActionUpdateServiceRequestHealthCheckHTTP((*source).HTTP) + pSchemaLoadBalancerActionUpdateServiceRequestHealthCheck = &schemaLoadBalancerActionUpdateServiceRequestHealthCheck + } + return pSchemaLoadBalancerActionUpdateServiceRequestHealthCheck +} +func (c *converterImpl) pHcloudLocationToPString(source *Location) *string { + var pString *string + if source != nil { + xstring := stringFromLocation((*source)) + pString = &xstring + } + return pString +} +func (c *converterImpl) pHcloudLocationToString(source *Location) string { + var xstring string + if source != nil { + xstring = stringFromLocation((*source)) + } + return xstring +} +func (c *converterImpl) pHcloudNetworkToInt64(source *Network) int64 { + var xint64 int64 + if source != nil { + xint64 = int64FromNetwork((*source)) + } + return xint64 +} +func (c *converterImpl) pHcloudNetworkToPInt64(source *Network) *int64 { + var pInt64 *int64 + if source != nil { + xint64 := int64FromNetwork((*source)) + pInt64 = &xint64 + } + return pInt64 +} +func (c *converterImpl) pHcloudPlacementGroupToPSchemaPlacementGroup(source *PlacementGroup) *schema.PlacementGroup { + var pSchemaPlacementGroup *schema.PlacementGroup + if source != nil { + var schemaPlacementGroup schema.PlacementGroup + schemaPlacementGroup.ID = (*source).ID + schemaPlacementGroup.Name = (*source).Name + schemaPlacementGroup.Labels = (*source).Labels + schemaPlacementGroup.Created = c.timeTimeToTimeTime((*source).Created) + schemaPlacementGroup.Servers = (*source).Servers + schemaPlacementGroup.Type = string((*source).Type) + pSchemaPlacementGroup = &schemaPlacementGroup + } + return pSchemaPlacementGroup +} +func (c *converterImpl) pHcloudServerToInt64(source *Server) int64 { + var xint64 int64 + if source != nil { + xint64 = int64FromServer((*source)) + } + return xint64 +} +func (c *converterImpl) pHcloudServerToPInt64(source *Server) *int64 { + var pInt64 *int64 + if source != nil { + xint64 := int64FromServer((*source)) + pInt64 = &xint64 + } + return pInt64 +} +func (c *converterImpl) pHcloudServerToPSchemaImageCreatedFrom(source *Server) *schema.ImageCreatedFrom { + var pSchemaImageCreatedFrom *schema.ImageCreatedFrom + if source != nil { + var schemaImageCreatedFrom schema.ImageCreatedFrom + schemaImageCreatedFrom.ID = (*source).ID + schemaImageCreatedFrom.Name = (*source).Name + pSchemaImageCreatedFrom = &schemaImageCreatedFrom + } + return pSchemaImageCreatedFrom +} +func (c *converterImpl) pNetIPNetToString(source *net.IPNet) string { + var xstring string + if source != nil { + xstring = stringFromIPNet((*source)) + } + return xstring +} +func (c *converterImpl) pSchemaCertificateStatusRefToPHcloudCertificateStatus(source *schema.CertificateStatusRef) *CertificateStatus { + var pHcloudCertificateStatus *CertificateStatus + if source != nil { + var hcloudCertificateStatus CertificateStatus + hcloudCertificateStatus.Issuance = CertificateStatusType((*source).Issuance) + hcloudCertificateStatus.Renewal = CertificateStatusType((*source).Renewal) + hcloudCertificateStatus.Error = c.pSchemaErrorToPHcloudError((*source).Error) + pHcloudCertificateStatus = &hcloudCertificateStatus + } + return pHcloudCertificateStatus +} +func (c *converterImpl) pSchemaErrorToPHcloudError(source *schema.Error) *Error { + var pHcloudError *Error + if source != nil { + hcloudError := c.ErrorFromSchema((*source)) + pHcloudError = &hcloudError + } + return pHcloudError +} +func (c *converterImpl) pSchemaFirewallResourceLabelSelectorToPHcloudFirewallResourceLabelSelector(source *schema.FirewallResourceLabelSelector) *FirewallResourceLabelSelector { + var pHcloudFirewallResourceLabelSelector *FirewallResourceLabelSelector + if source != nil { + var hcloudFirewallResourceLabelSelector FirewallResourceLabelSelector + hcloudFirewallResourceLabelSelector.Selector = (*source).Selector + pHcloudFirewallResourceLabelSelector = &hcloudFirewallResourceLabelSelector + } + return pHcloudFirewallResourceLabelSelector +} +func (c *converterImpl) pSchemaFirewallResourceServerToPHcloudFirewallResourceServer(source *schema.FirewallResourceServer) *FirewallResourceServer { + var pHcloudFirewallResourceServer *FirewallResourceServer + if source != nil { + var hcloudFirewallResourceServer FirewallResourceServer + hcloudFirewallResourceServer.ID = (*source).ID + pHcloudFirewallResourceServer = &hcloudFirewallResourceServer + } + return pHcloudFirewallResourceServer +} +func (c *converterImpl) pSchemaISOToPHcloudISO(source *schema.ISO) *ISO { + var pHcloudISO *ISO + if source != nil { + hcloudISO := c.intISOFromSchema((*source)) + pHcloudISO = &hcloudISO + } + return pHcloudISO +} +func (c *converterImpl) pSchemaImageCreatedFromToPHcloudServer(source *schema.ImageCreatedFrom) *Server { + var pHcloudServer *Server + if source != nil { + hcloudServer := serverFromImageCreatedFromSchema((*source)) + pHcloudServer = &hcloudServer + } + return pHcloudServer +} +func (c *converterImpl) pSchemaImageToPHcloudImage(source *schema.Image) *Image { + var pHcloudImage *Image + if source != nil { + var hcloudImage Image + hcloudImage.ID = (*source).ID + var xstring string + if (*source).Name != nil { + xstring = *(*source).Name + } + hcloudImage.Name = xstring + hcloudImage.Type = ImageType((*source).Type) + hcloudImage.Status = ImageStatus((*source).Status) + hcloudImage.Description = (*source).Description + var xfloat32 float32 + if (*source).ImageSize != nil { + xfloat32 = *(*source).ImageSize + } + hcloudImage.ImageSize = xfloat32 + hcloudImage.DiskSize = (*source).DiskSize + hcloudImage.Created = c.pTimeTimeToTimeTime((*source).Created) + hcloudImage.CreatedFrom = c.pSchemaImageCreatedFromToPHcloudServer((*source).CreatedFrom) + var pHcloudServer *Server + if (*source).BoundTo != nil { + hcloudServer := serverFromInt64(*(*source).BoundTo) + pHcloudServer = &hcloudServer + } + hcloudImage.BoundTo = pHcloudServer + hcloudImage.RapidDeploy = (*source).RapidDeploy + hcloudImage.OSFlavor = (*source).OSFlavor + var xstring2 string + if (*source).OSVersion != nil { + xstring2 = *(*source).OSVersion + } + hcloudImage.OSVersion = xstring2 + hcloudImage.Architecture = Architecture((*source).Architecture) + hcloudImage.Protection = c.schemaImageProtectionToHcloudImageProtection((*source).Protection) + hcloudImage.Deprecated = c.pTimeTimeToTimeTime((*source).Deprecated) + hcloudImage.Labels = (*source).Labels + hcloudImage.Deleted = c.pTimeTimeToTimeTime((*source).Deleted) + pHcloudImage = &hcloudImage + } + return pHcloudImage +} +func (c *converterImpl) pSchemaLoadBalancerServiceHTTPToHcloudLoadBalancerServiceHTTP(source *schema.LoadBalancerServiceHTTP) LoadBalancerServiceHTTP { + var hcloudLoadBalancerServiceHTTP LoadBalancerServiceHTTP + if source != nil { + var hcloudLoadBalancerServiceHTTP2 LoadBalancerServiceHTTP + hcloudLoadBalancerServiceHTTP2.CookieName = (*source).CookieName + hcloudLoadBalancerServiceHTTP2.CookieLifetime = durationFromIntSeconds((*source).CookieLifetime) + var pHcloudCertificateList []*Certificate + if (*source).Certificates != nil { + pHcloudCertificateList = make([]*Certificate, len((*source).Certificates)) + for i := 0; i < len((*source).Certificates); i++ { + pHcloudCertificateList[i] = certificateFromInt64((*source).Certificates[i]) + } + } + hcloudLoadBalancerServiceHTTP2.Certificates = pHcloudCertificateList + hcloudLoadBalancerServiceHTTP2.RedirectHTTP = (*source).RedirectHTTP + hcloudLoadBalancerServiceHTTP2.StickySessions = (*source).StickySessions + hcloudLoadBalancerServiceHTTP = hcloudLoadBalancerServiceHTTP2 + } + return hcloudLoadBalancerServiceHTTP +} +func (c *converterImpl) pSchemaLoadBalancerServiceHealthCheckHTTPToPHcloudLoadBalancerServiceHealthCheckHTTP(source *schema.LoadBalancerServiceHealthCheckHTTP) *LoadBalancerServiceHealthCheckHTTP { + var pHcloudLoadBalancerServiceHealthCheckHTTP *LoadBalancerServiceHealthCheckHTTP + if source != nil { + var hcloudLoadBalancerServiceHealthCheckHTTP LoadBalancerServiceHealthCheckHTTP + hcloudLoadBalancerServiceHealthCheckHTTP.Domain = (*source).Domain + hcloudLoadBalancerServiceHealthCheckHTTP.Path = (*source).Path + hcloudLoadBalancerServiceHealthCheckHTTP.Response = (*source).Response + hcloudLoadBalancerServiceHealthCheckHTTP.StatusCodes = (*source).StatusCodes + hcloudLoadBalancerServiceHealthCheckHTTP.TLS = (*source).TLS + pHcloudLoadBalancerServiceHealthCheckHTTP = &hcloudLoadBalancerServiceHealthCheckHTTP + } + return pHcloudLoadBalancerServiceHealthCheckHTTP +} +func (c *converterImpl) pSchemaLoadBalancerTargetIPToPHcloudLoadBalancerTargetIP(source *schema.LoadBalancerTargetIP) *LoadBalancerTargetIP { + var pHcloudLoadBalancerTargetIP *LoadBalancerTargetIP + if source != nil { + var hcloudLoadBalancerTargetIP LoadBalancerTargetIP + hcloudLoadBalancerTargetIP.IP = (*source).IP + pHcloudLoadBalancerTargetIP = &hcloudLoadBalancerTargetIP + } + return pHcloudLoadBalancerTargetIP +} +func (c *converterImpl) pSchemaLoadBalancerTargetLabelSelectorToPHcloudLoadBalancerTargetLabelSelector(source *schema.LoadBalancerTargetLabelSelector) *LoadBalancerTargetLabelSelector { + var pHcloudLoadBalancerTargetLabelSelector *LoadBalancerTargetLabelSelector + if source != nil { + var hcloudLoadBalancerTargetLabelSelector LoadBalancerTargetLabelSelector + hcloudLoadBalancerTargetLabelSelector.Selector = (*source).Selector + pHcloudLoadBalancerTargetLabelSelector = &hcloudLoadBalancerTargetLabelSelector + } + return pHcloudLoadBalancerTargetLabelSelector +} +func (c *converterImpl) pSchemaLoadBalancerTargetServerToPHcloudLoadBalancerTargetServer(source *schema.LoadBalancerTargetServer) *LoadBalancerTargetServer { + var pHcloudLoadBalancerTargetServer *LoadBalancerTargetServer + if source != nil { + hcloudLoadBalancerTargetServer := c.LoadBalancerTargetServerFromSchema((*source)) + pHcloudLoadBalancerTargetServer = &hcloudLoadBalancerTargetServer + } + return pHcloudLoadBalancerTargetServer +} +func (c *converterImpl) pSchemaPlacementGroupToPHcloudPlacementGroup(source *schema.PlacementGroup) *PlacementGroup { + var pHcloudPlacementGroup *PlacementGroup + if source != nil { + var hcloudPlacementGroup PlacementGroup + hcloudPlacementGroup.ID = (*source).ID + hcloudPlacementGroup.Name = (*source).Name + hcloudPlacementGroup.Labels = (*source).Labels + hcloudPlacementGroup.Created = c.timeTimeToTimeTime((*source).Created) + hcloudPlacementGroup.Servers = (*source).Servers + hcloudPlacementGroup.Type = PlacementGroupType((*source).Type) + pHcloudPlacementGroup = &hcloudPlacementGroup + } + return pHcloudPlacementGroup +} +func (c *converterImpl) pTimeTimeToTimeTime(source *time.Time) time.Time { + var timeTime time.Time + if source != nil { + timeTime = (*source) + } + return timeTime +} +func (c *converterImpl) schemaActionResourceReferenceToPHcloudActionResource(source schema.ActionResourceReference) *ActionResource { + var hcloudActionResource ActionResource + hcloudActionResource.ID = source.ID + hcloudActionResource.Type = ActionResourceType(source.Type) + return &hcloudActionResource +} +func (c *converterImpl) schemaCertificateUsedByRefToHcloudCertificateUsedByRef(source schema.CertificateUsedByRef) CertificateUsedByRef { + var hcloudCertificateUsedByRef CertificateUsedByRef + hcloudCertificateUsedByRef.ID = source.ID + hcloudCertificateUsedByRef.Type = CertificateUsedByRefType(source.Type) + return hcloudCertificateUsedByRef +} +func (c *converterImpl) schemaDatacenterServerTypesToHcloudDatacenterServerTypes(source schema.DatacenterServerTypes) DatacenterServerTypes { + var hcloudDatacenterServerTypes DatacenterServerTypes + var pHcloudServerTypeList []*ServerType + if source.Supported != nil { + pHcloudServerTypeList = make([]*ServerType, len(source.Supported)) + for i := 0; i < len(source.Supported); i++ { + pHcloudServerTypeList[i] = serverTypeFromInt64(source.Supported[i]) + } + } + hcloudDatacenterServerTypes.Supported = pHcloudServerTypeList + var pHcloudServerTypeList2 []*ServerType + if source.AvailableForMigration != nil { + pHcloudServerTypeList2 = make([]*ServerType, len(source.AvailableForMigration)) + for j := 0; j < len(source.AvailableForMigration); j++ { + pHcloudServerTypeList2[j] = serverTypeFromInt64(source.AvailableForMigration[j]) + } + } + hcloudDatacenterServerTypes.AvailableForMigration = pHcloudServerTypeList2 + var pHcloudServerTypeList3 []*ServerType + if source.Available != nil { + pHcloudServerTypeList3 = make([]*ServerType, len(source.Available)) + for k := 0; k < len(source.Available); k++ { + pHcloudServerTypeList3[k] = serverTypeFromInt64(source.Available[k]) + } + } + hcloudDatacenterServerTypes.Available = pHcloudServerTypeList3 + return hcloudDatacenterServerTypes +} +func (c *converterImpl) schemaDeprecatableResourceToHcloudDeprecatableResource(source schema.DeprecatableResource) DeprecatableResource { + var hcloudDeprecatableResource DeprecatableResource + hcloudDeprecatableResource.Deprecation = c.DeprecationFromSchema(source.Deprecation) + return hcloudDeprecatableResource +} +func (c *converterImpl) schemaFirewallResourceToHcloudFirewallResource(source schema.FirewallResource) FirewallResource { + var hcloudFirewallResource FirewallResource + hcloudFirewallResource.Type = FirewallResourceType(source.Type) + hcloudFirewallResource.Server = c.pSchemaFirewallResourceServerToPHcloudFirewallResourceServer(source.Server) + hcloudFirewallResource.LabelSelector = c.pSchemaFirewallResourceLabelSelectorToPHcloudFirewallResourceLabelSelector(source.LabelSelector) + return hcloudFirewallResource +} +func (c *converterImpl) schemaFirewallRuleToHcloudFirewallRule(source schema.FirewallRule) FirewallRule { + var hcloudFirewallRule FirewallRule + hcloudFirewallRule.Direction = FirewallRuleDirection(source.Direction) + var netIPNetList []net.IPNet + if source.SourceIPs != nil { + netIPNetList = make([]net.IPNet, len(source.SourceIPs)) + for i := 0; i < len(source.SourceIPs); i++ { + netIPNetList[i] = ipNetFromString(source.SourceIPs[i]) + } + } + hcloudFirewallRule.SourceIPs = netIPNetList + var netIPNetList2 []net.IPNet + if source.DestinationIPs != nil { + netIPNetList2 = make([]net.IPNet, len(source.DestinationIPs)) + for j := 0; j < len(source.DestinationIPs); j++ { + netIPNetList2[j] = ipNetFromString(source.DestinationIPs[j]) + } + } + hcloudFirewallRule.DestinationIPs = netIPNetList2 + hcloudFirewallRule.Protocol = FirewallRuleProtocol(source.Protocol) + hcloudFirewallRule.Port = source.Port + hcloudFirewallRule.Description = source.Description + return hcloudFirewallRule +} +func (c *converterImpl) schemaFloatingIPProtectionToHcloudFloatingIPProtection(source schema.FloatingIPProtection) FloatingIPProtection { + var hcloudFloatingIPProtection FloatingIPProtection + hcloudFloatingIPProtection.Delete = source.Delete + return hcloudFloatingIPProtection +} +func (c *converterImpl) schemaFromFloatingIPPricing(source FloatingIPPricing) schema.PricingFloatingIP { + var schemaPricingFloatingIP schema.PricingFloatingIP + schemaPricingFloatingIP.PriceMonthly = c.hcloudPriceToSchemaPrice(source.Monthly) + return schemaPricingFloatingIP +} +func (c *converterImpl) schemaFromFloatingIPTypeLocationPricing(source FloatingIPTypeLocationPricing) schema.PricingFloatingIPTypePrice { + var schemaPricingFloatingIPTypePrice schema.PricingFloatingIPTypePrice + schemaPricingFloatingIPTypePrice.Location = c.pHcloudLocationToString(source.Location) + schemaPricingFloatingIPTypePrice.PriceMonthly = c.hcloudPriceToSchemaPrice(source.Monthly) + return schemaPricingFloatingIPTypePrice +} +func (c *converterImpl) schemaFromFloatingIPTypePricing(source FloatingIPTypePricing) schema.PricingFloatingIPType { + var schemaPricingFloatingIPType schema.PricingFloatingIPType + schemaPricingFloatingIPType.Type = string(source.Type) + var schemaPricingFloatingIPTypePriceList []schema.PricingFloatingIPTypePrice + if source.Pricings != nil { + schemaPricingFloatingIPTypePriceList = make([]schema.PricingFloatingIPTypePrice, len(source.Pricings)) + for i := 0; i < len(source.Pricings); i++ { + schemaPricingFloatingIPTypePriceList[i] = c.schemaFromFloatingIPTypeLocationPricing(source.Pricings[i]) + } + } + schemaPricingFloatingIPType.Prices = schemaPricingFloatingIPTypePriceList + return schemaPricingFloatingIPType +} +func (c *converterImpl) schemaFromImagePricing(source ImagePricing) schema.PricingImage { + var schemaPricingImage schema.PricingImage + schemaPricingImage.PricePerGBMonth = c.hcloudPriceToSchemaPrice(source.PerGBMonth) + return schemaPricingImage +} +func (c *converterImpl) schemaFromLoadBalancerTypePricing(source LoadBalancerTypePricing) schema.PricingLoadBalancerType { + var schemaPricingLoadBalancerType schema.PricingLoadBalancerType + var pInt64 *int64 + if source.LoadBalancerType != nil { + pInt64 = &source.LoadBalancerType.ID + } + var xint64 int64 + if pInt64 != nil { + xint64 = *pInt64 + } + schemaPricingLoadBalancerType.ID = xint64 + var pString *string + if source.LoadBalancerType != nil { + pString = &source.LoadBalancerType.Name + } + var xstring string + if pString != nil { + xstring = *pString + } + schemaPricingLoadBalancerType.Name = xstring + var schemaPricingLoadBalancerTypePriceList []schema.PricingLoadBalancerTypePrice + if source.Pricings != nil { + schemaPricingLoadBalancerTypePriceList = make([]schema.PricingLoadBalancerTypePrice, len(source.Pricings)) + for i := 0; i < len(source.Pricings); i++ { + schemaPricingLoadBalancerTypePriceList[i] = c.SchemaFromLoadBalancerTypeLocationPricing(source.Pricings[i]) + } + } + schemaPricingLoadBalancerType.Prices = schemaPricingLoadBalancerTypePriceList + return schemaPricingLoadBalancerType +} +func (c *converterImpl) schemaFromPrimaryIPPricing(source PrimaryIPPricing) schema.PricingPrimaryIP { + var schemaPricingPrimaryIP schema.PricingPrimaryIP + schemaPricingPrimaryIP.Type = source.Type + var schemaPricingPrimaryIPTypePriceList []schema.PricingPrimaryIPTypePrice + if source.Pricings != nil { + schemaPricingPrimaryIPTypePriceList = make([]schema.PricingPrimaryIPTypePrice, len(source.Pricings)) + for i := 0; i < len(source.Pricings); i++ { + schemaPricingPrimaryIPTypePriceList[i] = c.schemaFromPrimaryIPTypePricing(source.Pricings[i]) + } + } + schemaPricingPrimaryIP.Prices = schemaPricingPrimaryIPTypePriceList + return schemaPricingPrimaryIP +} +func (c *converterImpl) schemaFromPrimaryIPTypePricing(source PrimaryIPTypePricing) schema.PricingPrimaryIPTypePrice { + var schemaPricingPrimaryIPTypePrice schema.PricingPrimaryIPTypePrice + schemaPricingPrimaryIPTypePrice.Datacenter = source.Datacenter + schemaPricingPrimaryIPTypePrice.Location = source.Location + schemaPricingPrimaryIPTypePrice.PriceHourly = c.hcloudPrimaryIPPriceToSchemaPrice(source.Hourly) + schemaPricingPrimaryIPTypePrice.PriceMonthly = c.hcloudPrimaryIPPriceToSchemaPrice(source.Monthly) + return schemaPricingPrimaryIPTypePrice +} +func (c *converterImpl) schemaFromServerTypeLocationPricing(source ServerTypeLocationPricing) schema.PricingServerTypePrice { + var schemaPricingServerTypePrice schema.PricingServerTypePrice + schemaPricingServerTypePrice.Location = c.pHcloudLocationToString(source.Location) + schemaPricingServerTypePrice.PriceHourly = c.hcloudPriceToSchemaPrice(source.Hourly) + schemaPricingServerTypePrice.PriceMonthly = c.hcloudPriceToSchemaPrice(source.Monthly) + return schemaPricingServerTypePrice +} +func (c *converterImpl) schemaFromServerTypePricing(source ServerTypePricing) schema.PricingServerType { + var schemaPricingServerType schema.PricingServerType + var pInt64 *int64 + if source.ServerType != nil { + pInt64 = &source.ServerType.ID + } + var xint64 int64 + if pInt64 != nil { + xint64 = *pInt64 + } + schemaPricingServerType.ID = xint64 + var pString *string + if source.ServerType != nil { + pString = &source.ServerType.Name + } + var xstring string + if pString != nil { + xstring = *pString + } + schemaPricingServerType.Name = xstring + var schemaPricingServerTypePriceList []schema.PricingServerTypePrice + if source.Pricings != nil { + schemaPricingServerTypePriceList = make([]schema.PricingServerTypePrice, len(source.Pricings)) + for i := 0; i < len(source.Pricings); i++ { + schemaPricingServerTypePriceList[i] = c.schemaFromServerTypeLocationPricing(source.Pricings[i]) + } + } + schemaPricingServerType.Prices = schemaPricingServerTypePriceList + return schemaPricingServerType +} +func (c *converterImpl) schemaFromTrafficPricing(source TrafficPricing) schema.PricingTraffic { + var schemaPricingTraffic schema.PricingTraffic + schemaPricingTraffic.PricePerTB = c.hcloudPriceToSchemaPrice(source.PerTB) + return schemaPricingTraffic +} +func (c *converterImpl) schemaFromVolumePricing(source VolumePricing) schema.PricingVolume { + var schemaPricingVolume schema.PricingVolume + schemaPricingVolume.PricePerGBPerMonth = c.hcloudPriceToSchemaPrice(source.PerGBMonthly) + return schemaPricingVolume +} +func (c *converterImpl) schemaImageProtectionToHcloudImageProtection(source schema.ImageProtection) ImageProtection { + var hcloudImageProtection ImageProtection + hcloudImageProtection.Delete = source.Delete + return hcloudImageProtection +} +func (c *converterImpl) schemaLoadBalancerAlgorithmToHcloudLoadBalancerAlgorithm(source schema.LoadBalancerAlgorithm) LoadBalancerAlgorithm { + var hcloudLoadBalancerAlgorithm LoadBalancerAlgorithm + hcloudLoadBalancerAlgorithm.Type = LoadBalancerAlgorithmType(source.Type) + return hcloudLoadBalancerAlgorithm +} +func (c *converterImpl) schemaLoadBalancerPrivateNetToHcloudLoadBalancerPrivateNet(source schema.LoadBalancerPrivateNet) LoadBalancerPrivateNet { + var hcloudLoadBalancerPrivateNet LoadBalancerPrivateNet + hcloudNetwork := networkFromInt64(source.Network) + hcloudLoadBalancerPrivateNet.Network = &hcloudNetwork + hcloudLoadBalancerPrivateNet.IP = ipFromString(source.IP) + return hcloudLoadBalancerPrivateNet +} +func (c *converterImpl) schemaLoadBalancerProtectionToHcloudLoadBalancerProtection(source schema.LoadBalancerProtection) LoadBalancerProtection { + var hcloudLoadBalancerProtection LoadBalancerProtection + hcloudLoadBalancerProtection.Delete = source.Delete + return hcloudLoadBalancerProtection +} +func (c *converterImpl) schemaLoadBalancerPublicNetIPv4ToHcloudLoadBalancerPublicNetIPv4(source schema.LoadBalancerPublicNetIPv4) LoadBalancerPublicNetIPv4 { + var hcloudLoadBalancerPublicNetIPv4 LoadBalancerPublicNetIPv4 + hcloudLoadBalancerPublicNetIPv4.IP = ipFromString(source.IP) + hcloudLoadBalancerPublicNetIPv4.DNSPtr = source.DNSPtr + return hcloudLoadBalancerPublicNetIPv4 +} +func (c *converterImpl) schemaLoadBalancerPublicNetIPv6ToHcloudLoadBalancerPublicNetIPv6(source schema.LoadBalancerPublicNetIPv6) LoadBalancerPublicNetIPv6 { + var hcloudLoadBalancerPublicNetIPv6 LoadBalancerPublicNetIPv6 + hcloudLoadBalancerPublicNetIPv6.IP = ipFromString(source.IP) + hcloudLoadBalancerPublicNetIPv6.DNSPtr = source.DNSPtr + return hcloudLoadBalancerPublicNetIPv6 +} +func (c *converterImpl) schemaLoadBalancerPublicNetToHcloudLoadBalancerPublicNet(source schema.LoadBalancerPublicNet) LoadBalancerPublicNet { + var hcloudLoadBalancerPublicNet LoadBalancerPublicNet + hcloudLoadBalancerPublicNet.Enabled = source.Enabled + hcloudLoadBalancerPublicNet.IPv4 = c.schemaLoadBalancerPublicNetIPv4ToHcloudLoadBalancerPublicNetIPv4(source.IPv4) + hcloudLoadBalancerPublicNet.IPv6 = c.schemaLoadBalancerPublicNetIPv6ToHcloudLoadBalancerPublicNetIPv6(source.IPv6) + return hcloudLoadBalancerPublicNet +} +func (c *converterImpl) schemaNetworkProtectionToHcloudNetworkProtection(source schema.NetworkProtection) NetworkProtection { + var hcloudNetworkProtection NetworkProtection + hcloudNetworkProtection.Delete = source.Delete + return hcloudNetworkProtection +} +func (c *converterImpl) schemaPricingServerBackupToHcloudServerBackupPricing(source schema.PricingServerBackup) ServerBackupPricing { + var hcloudServerBackupPricing ServerBackupPricing + hcloudServerBackupPricing.Percentage = source.Percentage + return hcloudServerBackupPricing +} +func (c *converterImpl) schemaPrimaryIPProtectionToHcloudPrimaryIPProtection(source schema.PrimaryIPProtection) PrimaryIPProtection { + var hcloudPrimaryIPProtection PrimaryIPProtection + hcloudPrimaryIPProtection.Delete = source.Delete + return hcloudPrimaryIPProtection +} +func (c *converterImpl) schemaServerProtectionToHcloudServerProtection(source schema.ServerProtection) ServerProtection { + var hcloudServerProtection ServerProtection + hcloudServerProtection.Delete = source.Delete + hcloudServerProtection.Rebuild = source.Rebuild + return hcloudServerProtection +} +func (c *converterImpl) schemaVolumeProtectionToHcloudVolumeProtection(source schema.VolumeProtection) VolumeProtection { + var hcloudVolumeProtection VolumeProtection + hcloudVolumeProtection.Delete = source.Delete + return hcloudVolumeProtection +} +func (c *converterImpl) serverTypePricingFromSchema(source schema.PricingServerTypePrice) ServerTypeLocationPricing { + var hcloudServerTypeLocationPricing ServerTypeLocationPricing + hcloudLocation := locationFromString(source.Location) + hcloudServerTypeLocationPricing.Location = &hcloudLocation + hcloudServerTypeLocationPricing.Hourly = c.PriceFromSchema(source.PriceHourly) + hcloudServerTypeLocationPricing.Monthly = c.PriceFromSchema(source.PriceMonthly) + return hcloudServerTypeLocationPricing +} +func (c *converterImpl) timeTimeToTimeTime(source time.Time) time.Time { + return source +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_server_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_server_client_iface.go new file mode 100644 index 000000000..82038a30c --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_server_client_iface.go @@ -0,0 +1,90 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IServerClient ... +type IServerClient interface { + // GetByID retrieves a server by its ID. If the server does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Server, *Response, error) + // GetByName retrieves a server by its name. If the server does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*Server, *Response, error) + // Get retrieves a server by its ID if the input can be parsed as an integer, otherwise it + // retrieves a server by its name. If the server does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*Server, *Response, error) + // List returns a list of servers for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts ServerListOpts) ([]*Server, *Response, error) + // All returns all servers. + All(ctx context.Context) ([]*Server, error) + // AllWithOpts returns all servers for the given options. + AllWithOpts(ctx context.Context, opts ServerListOpts) ([]*Server, error) + // Create creates a new server. + Create(ctx context.Context, opts ServerCreateOpts) (ServerCreateResult, *Response, error) + // Delete deletes a server. + // + // Deprecated: Use [ServerClient.DeleteWithResult] instead. + Delete(ctx context.Context, server *Server) (*Response, error) + // DeleteWithResult deletes a server and returns the parsed response containing the action. + DeleteWithResult(ctx context.Context, server *Server) (*ServerDeleteResult, *Response, error) + // Update updates a server. + Update(ctx context.Context, server *Server, opts ServerUpdateOpts) (*Server, *Response, error) + // Poweron starts a server. + Poweron(ctx context.Context, server *Server) (*Action, *Response, error) + // Reboot reboots a server. + Reboot(ctx context.Context, server *Server) (*Action, *Response, error) + // Reset resets a server. + Reset(ctx context.Context, server *Server) (*Action, *Response, error) + // Shutdown shuts down a server. + Shutdown(ctx context.Context, server *Server) (*Action, *Response, error) + // Poweroff stops a server. + Poweroff(ctx context.Context, server *Server) (*Action, *Response, error) + // ResetPassword resets a server's password. + ResetPassword(ctx context.Context, server *Server) (ServerResetPasswordResult, *Response, error) + // CreateImage creates an image from a server. + CreateImage(ctx context.Context, server *Server, opts *ServerCreateImageOpts) (ServerCreateImageResult, *Response, error) + // EnableRescue enables rescue mode for a server. + EnableRescue(ctx context.Context, server *Server, opts ServerEnableRescueOpts) (ServerEnableRescueResult, *Response, error) + // DisableRescue disables rescue mode for a server. + DisableRescue(ctx context.Context, server *Server) (*Action, *Response, error) + // Rebuild rebuilds a server. + // + // Deprecated: Use [ServerClient.RebuildWithResult] instead. + Rebuild(ctx context.Context, server *Server, opts ServerRebuildOpts) (*Action, *Response, error) + // RebuildWithResult rebuilds a server. + RebuildWithResult(ctx context.Context, server *Server, opts ServerRebuildOpts) (ServerRebuildResult, *Response, error) + // AttachISO attaches an ISO to a server. + AttachISO(ctx context.Context, server *Server, iso *ISO) (*Action, *Response, error) + // DetachISO detaches the currently attached ISO from a server. + DetachISO(ctx context.Context, server *Server) (*Action, *Response, error) + // EnableBackup enables backup for a server. Pass in an empty backup window to let the + // API pick a window for you. See the API documentation at docs.hetzner.cloud for a list + // of valid backup windows. + EnableBackup(ctx context.Context, server *Server, window string) (*Action, *Response, error) + // DisableBackup disables backup for a server. + DisableBackup(ctx context.Context, server *Server) (*Action, *Response, error) + // ChangeType changes a server's type. + ChangeType(ctx context.Context, server *Server, opts ServerChangeTypeOpts) (*Action, *Response, error) + // ChangeDNSPtr changes or resets the reverse DNS pointer for a server IP address. + // Pass a nil ptr to reset the reverse DNS pointer to its default value. + ChangeDNSPtr(ctx context.Context, server *Server, ip string, ptr *string) (*Action, *Response, error) + // ChangeProtection changes the resource protection level of a server. + ChangeProtection(ctx context.Context, server *Server, opts ServerChangeProtectionOpts) (*Action, *Response, error) + // RequestConsole requests a WebSocket VNC console. + RequestConsole(ctx context.Context, server *Server) (ServerRequestConsoleResult, *Response, error) + // AttachToNetwork attaches a server to a network. + AttachToNetwork(ctx context.Context, server *Server, opts ServerAttachToNetworkOpts) (*Action, *Response, error) + // DetachFromNetwork detaches a server from a network. + DetachFromNetwork(ctx context.Context, server *Server, opts ServerDetachFromNetworkOpts) (*Action, *Response, error) + // ChangeAliasIPs changes a server's alias IPs in a network. + ChangeAliasIPs(ctx context.Context, server *Server, opts ServerChangeAliasIPsOpts) (*Action, *Response, error) + // GetMetrics obtains metrics for Server. + GetMetrics(ctx context.Context, server *Server, opts ServerGetMetricsOpts) (*ServerMetrics, *Response, error) + AddToPlacementGroup(ctx context.Context, server *Server, placementGroup *PlacementGroup) (*Action, *Response, error) + RemoveFromPlacementGroup(ctx context.Context, server *Server) (*Action, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_server_type_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_server_type_client_iface.go new file mode 100644 index 000000000..57c57afa0 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_server_type_client_iface.go @@ -0,0 +1,27 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IServerTypeClient ... +type IServerTypeClient interface { + // GetByID retrieves a server type by its ID. If the server type does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*ServerType, *Response, error) + // GetByName retrieves a server type by its name. If the server type does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*ServerType, *Response, error) + // Get retrieves a server type by its ID if the input can be parsed as an integer, otherwise it + // retrieves a server type by its name. If the server type does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*ServerType, *Response, error) + // List returns a list of server types for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts ServerTypeListOpts) ([]*ServerType, *Response, error) + // All returns all server types. + All(ctx context.Context) ([]*ServerType, error) + // AllWithOpts returns all server types for the given options. + AllWithOpts(ctx context.Context, opts ServerTypeListOpts) ([]*ServerType, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_ssh_key_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_ssh_key_client_iface.go new file mode 100644 index 000000000..d2c6988d9 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_ssh_key_client_iface.go @@ -0,0 +1,35 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// ISSHKeyClient ... +type ISSHKeyClient interface { + // GetByID retrieves a SSH key by its ID. If the SSH key does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*SSHKey, *Response, error) + // GetByName retrieves a SSH key by its name. If the SSH key does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*SSHKey, *Response, error) + // GetByFingerprint retreives a SSH key by its fingerprint. If the SSH key does not exist, nil is returned. + GetByFingerprint(ctx context.Context, fingerprint string) (*SSHKey, *Response, error) + // Get retrieves a SSH key by its ID if the input can be parsed as an integer, otherwise it + // retrieves a SSH key by its name. If the SSH key does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*SSHKey, *Response, error) + // List returns a list of SSH keys for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts SSHKeyListOpts) ([]*SSHKey, *Response, error) + // All returns all SSH keys. + All(ctx context.Context) ([]*SSHKey, error) + // AllWithOpts returns all SSH keys with the given options. + AllWithOpts(ctx context.Context, opts SSHKeyListOpts) ([]*SSHKey, error) + // Create creates a new SSH key with the given options. + Create(ctx context.Context, opts SSHKeyCreateOpts) (*SSHKey, *Response, error) + // Delete deletes a SSH key. + Delete(ctx context.Context, sshKey *SSHKey) (*Response, error) + // Update updates a SSH key. + Update(ctx context.Context, sshKey *SSHKey, opts SSHKeyUpdateOpts) (*SSHKey, *Response, error) +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_volume_client_iface.go b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_volume_client_iface.go new file mode 100644 index 000000000..28edb7a27 --- /dev/null +++ b/vendor/github.com/hetznercloud/hcloud-go/v2/hcloud/zz_volume_client_iface.go @@ -0,0 +1,43 @@ +// Code generated by ifacemaker; DO NOT EDIT. + +package hcloud + +import ( + "context" +) + +// IVolumeClient ... +type IVolumeClient interface { + // GetByID retrieves a volume by its ID. If the volume does not exist, nil is returned. + GetByID(ctx context.Context, id int64) (*Volume, *Response, error) + // GetByName retrieves a volume by its name. If the volume does not exist, nil is returned. + GetByName(ctx context.Context, name string) (*Volume, *Response, error) + // Get retrieves a volume by its ID if the input can be parsed as an integer, otherwise it + // retrieves a volume by its name. If the volume does not exist, nil is returned. + Get(ctx context.Context, idOrName string) (*Volume, *Response, error) + // List returns a list of volumes for a specific page. + // + // Please note that filters specified in opts are not taken into account + // when their value corresponds to their zero value or when they are empty. + List(ctx context.Context, opts VolumeListOpts) ([]*Volume, *Response, error) + // All returns all volumes. + All(ctx context.Context) ([]*Volume, error) + // AllWithOpts returns all volumes with the given options. + AllWithOpts(ctx context.Context, opts VolumeListOpts) ([]*Volume, error) + // Create creates a new volume with the given options. + Create(ctx context.Context, opts VolumeCreateOpts) (VolumeCreateResult, *Response, error) + // Delete deletes a volume. + Delete(ctx context.Context, volume *Volume) (*Response, error) + // Update updates a volume. + Update(ctx context.Context, volume *Volume, opts VolumeUpdateOpts) (*Volume, *Response, error) + // AttachWithOpts attaches a volume to a server. + AttachWithOpts(ctx context.Context, volume *Volume, opts VolumeAttachOpts) (*Action, *Response, error) + // Attach attaches a volume to a server. + Attach(ctx context.Context, volume *Volume, server *Server) (*Action, *Response, error) + // Detach detaches a volume from a server. + Detach(ctx context.Context, volume *Volume) (*Action, *Response, error) + // ChangeProtection changes the resource protection level of a volume. + ChangeProtection(ctx context.Context, volume *Volume, opts VolumeChangeProtectionOpts) (*Action, *Response, error) + // Resize changes the size of a volume. + Resize(ctx context.Context, volume *Volume, size int) (*Action, *Response, error) +} diff --git a/vendor/github.com/imdario/mergo/CONTRIBUTING.md b/vendor/github.com/imdario/mergo/CONTRIBUTING.md new file mode 100644 index 000000000..0a1ff9f94 --- /dev/null +++ b/vendor/github.com/imdario/mergo/CONTRIBUTING.md @@ -0,0 +1,112 @@ + +# Contributing to mergo + +First off, thanks for taking the time to contribute! â¤ï¸ + +All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 + +> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: +> - Star the project +> - Tweet about it +> - Refer this project in your project's readme +> - Mention the project at local meetups and tell your friends/colleagues + + +## Table of Contents + +- [Code of Conduct](#code-of-conduct) +- [I Have a Question](#i-have-a-question) +- [I Want To Contribute](#i-want-to-contribute) +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) + +## Code of Conduct + +This project and everyone participating in it is governed by the +[mergo Code of Conduct](https://github.com/imdario/mergoblob/master/CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. Please report unacceptable behavior +to <>. + + +## I Have a Question + +> If you want to ask a question, we assume that you have read the available [Documentation](https://pkg.go.dev/github.com/imdario/mergo). + +Before you ask a question, it is best to search for existing [Issues](https://github.com/imdario/mergo/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. + +If you then still feel the need to ask a question and need clarification, we recommend the following: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). +- Provide as much context as you can about what you're running into. +- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. + +We will then take care of the issue as soon as possible. + +## I Want To Contribute + +> ### Legal Notice +> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. + +### Reporting Bugs + + +#### Before Submitting a Bug Report + +A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. + +- Make sure that you are using the latest version. +- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). +- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/imdario/mergoissues?q=label%3Abug). +- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. +- Collect information about the bug: +- Stack trace (Traceback) +- OS, Platform and Version (Windows, Linux, macOS, x86, ARM) +- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. +- Possibly your input and the output +- Can you reliably reproduce the issue? And can you also reproduce it with older versions? + + +#### How Do I Submit a Good Bug Report? + +> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . + + +We use GitHub issues to track bugs and errors. If you run into an issue with the project: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) +- Explain the behavior you would expect and the actual behavior. +- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. +- Provide the information you collected in the previous section. + +Once it's filed: + +- The project team will label the issue accordingly. +- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. +- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be implemented by someone. + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion for mergo, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. + + +#### Before Submitting an Enhancement + +- Make sure that you are using the latest version. +- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. +- Perform a [search](https://github.com/imdario/mergo/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. +- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. + + +#### How Do I Submit a Good Enhancement Suggestion? + +Enhancement suggestions are tracked as [GitHub issues](https://github.com/imdario/mergo/issues). + +- Use a **clear and descriptive title** for the issue to identify the suggestion. +- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. +- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +- **Explain why this enhancement would be useful** to most mergo users. You may also want to point out the other projects that solved it better and which could serve as inspiration. + + +## Attribution +This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! diff --git a/vendor/github.com/imdario/mergo/README.md b/vendor/github.com/imdario/mergo/README.md index 7e6f7aeee..ffbbb62c7 100644 --- a/vendor/github.com/imdario/mergo/README.md +++ b/vendor/github.com/imdario/mergo/README.md @@ -1,17 +1,20 @@ # Mergo - -[![GoDoc][3]][4] [![GitHub release][5]][6] [![GoCard][7]][8] -[![Build Status][1]][2] -[![Coverage Status][9]][10] +[![Test status][1]][2] +[![OpenSSF Scorecard][21]][22] +[![OpenSSF Best Practices][19]][20] +[![Coverage status][9]][10] [![Sourcegraph][11]][12] -[![FOSSA Status][13]][14] +[![FOSSA status][13]][14] + +[![GoDoc][3]][4] [![Become my sponsor][15]][16] +[![Tidelift][17]][18] -[1]: https://travis-ci.org/imdario/mergo.png -[2]: https://travis-ci.org/imdario/mergo +[1]: https://github.com/imdario/mergo/workflows/tests/badge.svg?branch=master +[2]: https://github.com/imdario/mergo/actions/workflows/tests.yml [3]: https://godoc.org/github.com/imdario/mergo?status.svg [4]: https://godoc.org/github.com/imdario/mergo [5]: https://img.shields.io/github/release/imdario/mergo.svg @@ -26,6 +29,12 @@ [14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield [15]: https://img.shields.io/github/sponsors/imdario [16]: https://github.com/sponsors/imdario +[17]: https://tidelift.com/badges/package/go/github.com%2Fimdario%2Fmergo +[18]: https://tidelift.com/subscription/pkg/go-github.com-imdario-mergo +[19]: https://bestpractices.coreinfrastructure.org/projects/7177/badge +[20]: https://bestpractices.coreinfrastructure.org/projects/7177 +[21]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo/badge +[22]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. @@ -55,7 +64,6 @@ If Mergo is useful to you, consider buying me a coffee, a beer, or making a mont ### Mergo in the wild -- [cli/cli](https://github.com/cli/cli) - [moby/moby](https://github.com/moby/moby) - [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) - [vmware/dispatch](https://github.com/vmware/dispatch) @@ -231,5 +239,4 @@ Written by [Dario Castañé](http://dario.im). [BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). - [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large) diff --git a/vendor/github.com/imdario/mergo/SECURITY.md b/vendor/github.com/imdario/mergo/SECURITY.md new file mode 100644 index 000000000..a5de61f77 --- /dev/null +++ b/vendor/github.com/imdario/mergo/SECURITY.md @@ -0,0 +1,14 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.3.x | :white_check_mark: | +| < 0.3 | :x: | + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/vendor/github.com/imdario/mergo/map.go b/vendor/github.com/imdario/mergo/map.go index a13a7ee46..b50d5c2a4 100644 --- a/vendor/github.com/imdario/mergo/map.go +++ b/vendor/github.com/imdario/mergo/map.go @@ -44,7 +44,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} + visited[h] = &visit{typ, seen, addr} } zeroValue := reflect.Value{} switch dst.Kind() { @@ -58,7 +58,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf } fieldName := field.Name fieldName = changeInitialCase(fieldName, unicode.ToLower) - if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v)) || overwrite) { + if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v), !config.ShouldNotDereference) || overwrite) { dstMap[fieldName] = src.Field(i).Interface() } } @@ -142,7 +142,7 @@ func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { func _map(dst, src interface{}, opts ...func(*Config)) error { if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { - return ErrNonPointerAgument + return ErrNonPointerArgument } var ( vDst, vSrc reflect.Value diff --git a/vendor/github.com/imdario/mergo/merge.go b/vendor/github.com/imdario/mergo/merge.go index 8b4e2f47a..0ef9b2138 100644 --- a/vendor/github.com/imdario/mergo/merge.go +++ b/vendor/github.com/imdario/mergo/merge.go @@ -38,10 +38,11 @@ func isExportedComponent(field *reflect.StructField) bool { } type Config struct { + Transformers Transformers Overwrite bool + ShouldNotDereference bool AppendSlice bool TypeCheck bool - Transformers Transformers overwriteWithEmptyValue bool overwriteSliceWithEmptyValue bool sliceDeepCopy bool @@ -76,7 +77,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} + visited[h] = &visit{typ, seen, addr} } if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { @@ -95,7 +96,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } } } else { - if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) { + if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) { dst.Set(src) } } @@ -110,7 +111,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } if src.Kind() != reflect.Map { - if overwrite { + if overwrite && dst.CanSet() { dst.Set(src) } return @@ -162,7 +163,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co dstSlice = reflect.ValueOf(dstElement.Interface()) } - if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy { + if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { if typeCheck && srcSlice.Type() != dstSlice.Type() { return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) } @@ -194,22 +195,38 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co dst.SetMapIndex(key, dstSlice) } } - if dstElement.IsValid() && !isEmptyValue(dstElement) && (reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map || reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice) { - continue + + if dstElement.IsValid() && !isEmptyValue(dstElement, !config.ShouldNotDereference) { + if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice { + continue + } + if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map && reflect.TypeOf(dstElement.Interface()).Kind() == reflect.Map { + continue + } } - if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement)) { + if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement, !config.ShouldNotDereference)) { if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } dst.SetMapIndex(key, srcElement) } } + + // Ensure that all keys in dst are deleted if they are not in src. + if overwriteWithEmptySrc { + for _, key := range dst.MapKeys() { + srcElement := src.MapIndex(key) + if !srcElement.IsValid() { + dst.SetMapIndex(key, reflect.Value{}) + } + } + } case reflect.Slice: if !dst.CanSet() { break } - if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy { + if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { dst.Set(src) } else if config.AppendSlice { if src.Type() != dst.Type() { @@ -244,12 +261,18 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co if src.Kind() != reflect.Interface { if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { - if dst.CanSet() && (overwrite || isEmptyValue(dst)) { + if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { dst.Set(src) } } else if src.Kind() == reflect.Ptr { - if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { - return + if !config.ShouldNotDereference { + if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { + return + } + } else { + if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() { + dst.Set(src) + } } } else if dst.Elem().Type() == src.Type() { if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { @@ -262,7 +285,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } if dst.IsNil() || overwrite { - if dst.CanSet() && (overwrite || isEmptyValue(dst)) { + if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { dst.Set(src) } break @@ -275,7 +298,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co break } default: - mustSet := (isEmptyValue(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) + mustSet := (isEmptyValue(dst, !config.ShouldNotDereference) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) if mustSet { if dst.CanSet() { dst.Set(src) @@ -326,6 +349,12 @@ func WithOverrideEmptySlice(config *Config) { config.overwriteSliceWithEmptyValue = true } +// WithoutDereference prevents dereferencing pointers when evaluating whether they are empty +// (i.e. a non-nil pointer is never considered empty). +func WithoutDereference(config *Config) { + config.ShouldNotDereference = true +} + // WithAppendSlice will make merge append slices instead of overwriting it. func WithAppendSlice(config *Config) { config.AppendSlice = true @@ -344,7 +373,7 @@ func WithSliceDeepCopy(config *Config) { func merge(dst, src interface{}, opts ...func(*Config)) error { if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { - return ErrNonPointerAgument + return ErrNonPointerArgument } var ( vDst, vSrc reflect.Value diff --git a/vendor/github.com/imdario/mergo/mergo.go b/vendor/github.com/imdario/mergo/mergo.go index 9fe362d47..0a721e2d8 100644 --- a/vendor/github.com/imdario/mergo/mergo.go +++ b/vendor/github.com/imdario/mergo/mergo.go @@ -20,7 +20,7 @@ var ( ErrNotSupported = errors.New("only structs, maps, and slices are supported") ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") - ErrNonPointerAgument = errors.New("dst must be a pointer") + ErrNonPointerArgument = errors.New("dst must be a pointer") ) // During deepMerge, must keep track of checks that are @@ -28,13 +28,13 @@ var ( // checks in progress are true when it reencounters them. // Visited are stored in a map indexed by 17 * a1 + a2; type visit struct { - ptr uintptr typ reflect.Type next *visit + ptr uintptr } // From src/pkg/encoding/json/encode.go. -func isEmptyValue(v reflect.Value) bool { +func isEmptyValue(v reflect.Value, shouldDereference bool) bool { switch v.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 @@ -50,7 +50,10 @@ func isEmptyValue(v reflect.Value) bool { if v.IsNil() { return true } - return isEmptyValue(v.Elem()) + if shouldDereference { + return isEmptyValue(v.Elem(), shouldDereference) + } + return false case reflect.Func: return v.IsNil() case reflect.Invalid: diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/README.md b/vendor/github.com/ionos-cloud/sdk-go/v6/README.md index f020bdf43..06910ecf6 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/README.md +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/README.md @@ -47,14 +47,15 @@ go get github.com/ionos-cloud/sdk-go/v6@latest ## Environment Variables -| Environment Variable | Description | -|----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `IONOS_USERNAME` | Specify the username used to login, to authenticate against the IONOS Cloud API | -| `IONOS_PASSWORD` | Specify the password used to login, to authenticate against the IONOS Cloud API | -| `IONOS_TOKEN` | Specify the token used to login, if a token is being used instead of username and password | -| `IONOS_API_URL` | Specify the API URL. It will overwrite the API endpoint default value `api.ionos.com`. Note: the host URL does not contain the `/cloudapi/v6` path, so it should _not_ be included in the `IONOS_API_URL` environment variable | -| `IONOS_LOG_LEVEL` | Specify the Log Level used to log messages. Possible values: Off, Debug, Trace | -| `IONOS_PINNED_CERT` | Specify the SHA-256 public fingerprint here, enables certificate pinning | +| Environment Variable | Description | +|-------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `IONOS_USERNAME` | Specify the username used to login, to authenticate against the IONOS Cloud API | +| `IONOS_PASSWORD` | Specify the password used to login, to authenticate against the IONOS Cloud API | +| `IONOS_TOKEN` | Specify the token used to login, if a token is being used instead of username and password | +| `IONOS_API_URL` | Specify the API URL. It will overwrite the API endpoint default value `api.ionos.com`. Note: the host URL does not contain the `/cloudapi/v6` path, so it should _not_ be included in the `IONOS_API_URL` environment variable | +| `IONOS_LOG_LEVEL` | Specify the Log Level used to log messages. Possible values: Off, Debug, Trace | +| `IONOS_PINNED_CERT` | Specify the SHA-256 public fingerprint here, enables certificate pinning | +| `IONOS_CONTRACT_NUMBER` | Specify the contract number on which you wish to provision. Only valid for reseller accounts, for other types of accounts the header will be ignored | âš ï¸ **_Note: To overwrite the api endpoint - `api.ionos.com`, the environment variable `$IONOS_API_URL` can be set, and used with `NewConfigurationFromEnv()` function._** @@ -352,7 +353,6 @@ KubernetesApi | [**K8sPut**](docs/api/KubernetesApi.md#k8sput) | **Put** /k8s/{k KubernetesApi | [**K8sVersionsDefaultGet**](docs/api/KubernetesApi.md#k8sversionsdefaultget) | **Get** /k8s/versions/default | Get Default Kubernetes Version KubernetesApi | [**K8sVersionsGet**](docs/api/KubernetesApi.md#k8sversionsget) | **Get** /k8s/versions | Get Kubernetes Versions LANsApi | [**DatacentersLansDelete**](docs/api/LANsApi.md#datacenterslansdelete) | **Delete** /datacenters/{datacenterId}/lans/{lanId} | Delete LANs -LANsApi | [**DatacentersLansEnableIpv6**](docs/api/LANsApi.md#datacenterslansenableipv6) | **Post** /datacenters/{datacenterId}/lans/enable-ipv6 | Enable IPv6 in the current Virtual Datacenter LANsApi | [**DatacentersLansFindById**](docs/api/LANsApi.md#datacenterslansfindbyid) | **Get** /datacenters/{datacenterId}/lans/{lanId} | Retrieve LANs LANsApi | [**DatacentersLansGet**](docs/api/LANsApi.md#datacenterslansget) | **Get** /datacenters/{datacenterId}/lans | List LANs LANsApi | [**DatacentersLansNicsFindById**](docs/api/LANsApi.md#datacenterslansnicsfindbyid) | **Get** /datacenters/{datacenterId}/lans/{lanId}/nics/{nicId} | Retrieve attached NICs @@ -620,7 +620,9 @@ All URIs are relative to *https://api.ionos.com/cloudapi/v6* - [Lan](docs/models/Lan) - [LanEntities](docs/models/LanEntities) - [LanNics](docs/models/LanNics) + - [LanPost](docs/models/LanPost) - [LanProperties](docs/models/LanProperties) + - [LanPropertiesPost](docs/models/LanPropertiesPost) - [Lans](docs/models/Lans) - [Loadbalancer](docs/models/Loadbalancer) - [LoadbalancerEntities](docs/models/LoadbalancerEntities) diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_.go index 3db9ea5cc..999b9d56f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" ) @@ -181,7 +181,7 @@ func (a *DefaultApiService) ApiInfoGetExecute(r ApiApiInfoGetRequest) (Info, *AP return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_application_load_balancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_application_load_balancers.go index e651c73e9..edbabd25d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_application_load_balancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_application_load_balancers.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -166,7 +166,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -333,7 +333,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -512,7 +512,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -683,7 +683,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -896,7 +896,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1087,7 +1087,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1274,7 +1274,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1465,7 +1465,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1644,7 +1644,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1815,7 +1815,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2028,7 +2028,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2219,7 +2219,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2406,7 +2406,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2597,7 +2597,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2832,7 +2832,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3019,7 +3019,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3202,7 +3202,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3389,7 +3389,7 @@ func (a *ApplicationLoadBalancersApiService) DatacentersApplicationloadbalancers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_backup_units.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_backup_units.go index 9c4470fdb..8337e9d1a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_backup_units.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_backup_units.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -168,7 +168,7 @@ func (a *BackupUnitsApiService) BackupunitsDeleteExecute(r ApiBackupunitsDeleteR return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -331,7 +331,7 @@ func (a *BackupUnitsApiService) BackupunitsFindByIdExecute(r ApiBackupunitsFindB return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -536,7 +536,7 @@ func (a *BackupUnitsApiService) BackupunitsGetExecute(r ApiBackupunitsGetRequest return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -719,7 +719,7 @@ func (a *BackupUnitsApiService) BackupunitsPatchExecute(r ApiBackupunitsPatchReq return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -898,7 +898,7 @@ func (a *BackupUnitsApiService) BackupunitsPostExecute(r ApiBackupunitsPostReque return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1081,7 +1081,7 @@ func (a *BackupUnitsApiService) BackupunitsPutExecute(r ApiBackupunitsPutRequest return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1277,7 +1277,7 @@ func (a *BackupUnitsApiService) BackupunitsSsourlGetExecute(r ApiBackupunitsSsou return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_contract_resources.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_contract_resources.go index 7285d83ba..ef19e758f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_contract_resources.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_contract_resources.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" ) @@ -195,7 +195,7 @@ func (a *ContractResourcesApiService) ContractsGetExecute(r ApiContractsGetReque return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_data_centers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_data_centers.go index 20a650699..33eb56488 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_data_centers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_data_centers.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *DataCentersApiService) DatacentersDeleteExecute(r ApiDatacentersDeleteR return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *DataCentersApiService) DatacentersFindByIdExecute(r ApiDatacentersFindB return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -556,7 +556,7 @@ func (a *DataCentersApiService) DatacentersGetExecute(r ApiDatacentersGetRequest return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -739,7 +739,7 @@ func (a *DataCentersApiService) DatacentersPatchExecute(r ApiDatacentersPatchReq return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -920,7 +920,7 @@ func (a *DataCentersApiService) DatacentersPostExecute(r ApiDatacentersPostReque return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1103,7 +1103,7 @@ func (a *DataCentersApiService) DatacentersPutExecute(r ApiDatacentersPutRequest return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_firewall_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_firewall_rules.go index bd3c896dd..1e0354a73 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_firewall_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_firewall_rules.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -174,7 +174,7 @@ func (a *FirewallRulesApiService) DatacentersServersNicsFirewallrulesDeleteExecu return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -349,7 +349,7 @@ func (a *FirewallRulesApiService) DatacentersServersNicsFirewallrulesFindByIdExe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -592,7 +592,7 @@ func (a *FirewallRulesApiService) DatacentersServersNicsFirewallrulesGetExecute( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -787,7 +787,7 @@ func (a *FirewallRulesApiService) DatacentersServersNicsFirewallrulesPatchExecut return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -978,7 +978,7 @@ func (a *FirewallRulesApiService) DatacentersServersNicsFirewallrulesPostExecute return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1173,7 +1173,7 @@ func (a *FirewallRulesApiService) DatacentersServersNicsFirewallrulesPutExecute( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_flow_logs.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_flow_logs.go index 1bdd3107b..6518b7451 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_flow_logs.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_flow_logs.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -166,7 +166,7 @@ func (a *FlowLogsApiService) DatacentersServersNicsFlowlogsDeleteExecute(r ApiDa return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -333,7 +333,7 @@ func (a *FlowLogsApiService) DatacentersServersNicsFlowlogsFindByIdExecute(r Api return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -568,7 +568,7 @@ func (a *FlowLogsApiService) DatacentersServersNicsFlowlogsGetExecute(r ApiDatac return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -755,7 +755,7 @@ func (a *FlowLogsApiService) DatacentersServersNicsFlowlogsPatchExecute(r ApiDat return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -938,7 +938,7 @@ func (a *FlowLogsApiService) DatacentersServersNicsFlowlogsPostExecute(r ApiData return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1125,7 +1125,7 @@ func (a *FlowLogsApiService) DatacentersServersNicsFlowlogsPutExecute(r ApiDatac return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_images.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_images.go index 25fd2e838..479f353ea 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_images.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_images.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *ImagesApiService) ImagesDeleteExecute(r ApiImagesDeleteRequest) (*APIRe return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *ImagesApiService) ImagesFindByIdExecute(r ApiImagesFindByIdRequest) (Im return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -530,7 +530,7 @@ func (a *ImagesApiService) ImagesGetExecute(r ApiImagesGetRequest) (Images, *API return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -713,7 +713,7 @@ func (a *ImagesApiService) ImagesPatchExecute(r ApiImagesPatchRequest) (Image, * return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -896,7 +896,7 @@ func (a *ImagesApiService) ImagesPutExecute(r ApiImagesPutRequest) (Image, *APIR return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_ip_blocks.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_ip_blocks.go index 820c73d16..f5269e97a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_ip_blocks.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_ip_blocks.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *IPBlocksApiService) IpblocksDeleteExecute(r ApiIpblocksDeleteRequest) ( return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *IPBlocksApiService) IpblocksFindByIdExecute(r ApiIpblocksFindByIdReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -556,7 +556,7 @@ func (a *IPBlocksApiService) IpblocksGetExecute(r ApiIpblocksGetRequest) (IpBloc return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -739,7 +739,7 @@ func (a *IPBlocksApiService) IpblocksPatchExecute(r ApiIpblocksPatchRequest) (Ip return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -918,7 +918,7 @@ func (a *IPBlocksApiService) IpblocksPostExecute(r ApiIpblocksPostRequest) (IpBl return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1101,7 +1101,7 @@ func (a *IPBlocksApiService) IpblocksPutExecute(r ApiIpblocksPutRequest) (IpBloc return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_kubernetes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_kubernetes.go index b5a54c544..8deae22fe 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_kubernetes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_kubernetes.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *KubernetesApiService) K8sDeleteExecute(r ApiK8sDeleteRequest) (*APIResp return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *KubernetesApiService) K8sFindByClusterIdExecute(r ApiK8sFindByClusterId return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -530,7 +530,7 @@ func (a *KubernetesApiService) K8sGetExecute(r ApiK8sGetRequest) (KubernetesClus return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -739,7 +739,7 @@ func (a *KubernetesApiService) K8sKubeconfigGetExecute(r ApiK8sKubeconfigGetRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -914,7 +914,7 @@ func (a *KubernetesApiService) K8sNodepoolsDeleteExecute(r ApiK8sNodepoolsDelete return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1081,7 +1081,7 @@ func (a *KubernetesApiService) K8sNodepoolsFindByIdExecute(r ApiK8sNodepoolsFind return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1290,7 +1290,7 @@ func (a *KubernetesApiService) K8sNodepoolsGetExecute(r ApiK8sNodepoolsGetReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1469,7 +1469,7 @@ func (a *KubernetesApiService) K8sNodepoolsNodesDeleteExecute(r ApiK8sNodepoolsN return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1640,7 +1640,7 @@ func (a *KubernetesApiService) K8sNodepoolsNodesFindByIdExecute(r ApiK8sNodepool return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1853,7 +1853,7 @@ func (a *KubernetesApiService) K8sNodepoolsNodesGetExecute(r ApiK8sNodepoolsNode return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2034,7 +2034,7 @@ func (a *KubernetesApiService) K8sNodepoolsNodesReplacePostExecute(r ApiK8sNodep return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2207,7 +2207,7 @@ func (a *KubernetesApiService) K8sNodepoolsPostExecute(r ApiK8sNodepoolsPostRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2394,7 +2394,7 @@ func (a *KubernetesApiService) K8sNodepoolsPutExecute(r ApiK8sNodepoolsPutReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2573,7 +2573,7 @@ func (a *KubernetesApiService) K8sPostExecute(r ApiK8sPostRequest) (KubernetesCl return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2756,7 +2756,7 @@ func (a *KubernetesApiService) K8sPutExecute(r ApiK8sPutRequest) (KubernetesClus return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2926,7 +2926,7 @@ func (a *KubernetesApiService) K8sVersionsDefaultGetExecute(r ApiK8sVersionsDefa return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3096,7 +3096,7 @@ func (a *KubernetesApiService) K8sVersionsGetExecute(r ApiK8sVersionsGetRequest) return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_labels.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_labels.go index bfeb50565..e39480b31 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_labels.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_labels.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -166,7 +166,7 @@ func (a *LabelsApiService) DatacentersLabelsDeleteExecute(r ApiDatacentersLabels return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -333,7 +333,7 @@ func (a *LabelsApiService) DatacentersLabelsFindByKeyExecute(r ApiDatacentersLab return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -542,7 +542,7 @@ func (a *LabelsApiService) DatacentersLabelsGetExecute(r ApiDatacentersLabelsGet return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -725,7 +725,7 @@ func (a *LabelsApiService) DatacentersLabelsPostExecute(r ApiDatacentersLabelsPo return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -912,7 +912,7 @@ func (a *LabelsApiService) DatacentersLabelsPutExecute(r ApiDatacentersLabelsPut return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1091,7 +1091,7 @@ func (a *LabelsApiService) DatacentersServersLabelsDeleteExecute(r ApiDatacenter return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1262,7 +1262,7 @@ func (a *LabelsApiService) DatacentersServersLabelsFindByKeyExecute(r ApiDatacen return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1475,7 +1475,7 @@ func (a *LabelsApiService) DatacentersServersLabelsGetExecute(r ApiDatacentersSe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1662,7 +1662,7 @@ func (a *LabelsApiService) DatacentersServersLabelsPostExecute(r ApiDatacentersS return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1853,7 +1853,7 @@ func (a *LabelsApiService) DatacentersServersLabelsPutExecute(r ApiDatacentersSe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2032,7 +2032,7 @@ func (a *LabelsApiService) DatacentersVolumesLabelsDeleteExecute(r ApiDatacenter return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2203,7 +2203,7 @@ func (a *LabelsApiService) DatacentersVolumesLabelsFindByKeyExecute(r ApiDatacen return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2416,7 +2416,7 @@ func (a *LabelsApiService) DatacentersVolumesLabelsGetExecute(r ApiDatacentersVo return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2603,7 +2603,7 @@ func (a *LabelsApiService) DatacentersVolumesLabelsPostExecute(r ApiDatacentersV return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2794,7 +2794,7 @@ func (a *LabelsApiService) DatacentersVolumesLabelsPutExecute(r ApiDatacentersVo return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2969,7 +2969,7 @@ func (a *LabelsApiService) IpblocksLabelsDeleteExecute(r ApiIpblocksLabelsDelete return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3136,7 +3136,7 @@ func (a *LabelsApiService) IpblocksLabelsFindByKeyExecute(r ApiIpblocksLabelsFin return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3345,7 +3345,7 @@ func (a *LabelsApiService) IpblocksLabelsGetExecute(r ApiIpblocksLabelsGetReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3528,7 +3528,7 @@ func (a *LabelsApiService) IpblocksLabelsPostExecute(r ApiIpblocksLabelsPostRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3715,7 +3715,7 @@ func (a *LabelsApiService) IpblocksLabelsPutExecute(r ApiIpblocksLabelsPutReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3892,7 +3892,7 @@ func (a *LabelsApiService) LabelsFindByUrnExecute(r ApiLabelsFindByUrnRequest) ( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4097,7 +4097,7 @@ func (a *LabelsApiService) LabelsGetExecute(r ApiLabelsGetRequest) (Labels, *API return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4272,7 +4272,7 @@ func (a *LabelsApiService) SnapshotsLabelsDeleteExecute(r ApiSnapshotsLabelsDele return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4439,7 +4439,7 @@ func (a *LabelsApiService) SnapshotsLabelsFindByKeyExecute(r ApiSnapshotsLabelsF return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4648,7 +4648,7 @@ func (a *LabelsApiService) SnapshotsLabelsGetExecute(r ApiSnapshotsLabelsGetRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4831,7 +4831,7 @@ func (a *LabelsApiService) SnapshotsLabelsPostExecute(r ApiSnapshotsLabelsPostRe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -5018,7 +5018,7 @@ func (a *LabelsApiService) SnapshotsLabelsPutExecute(r ApiSnapshotsLabelsPutRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go index 07560c528..9eeb39d32 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -166,168 +166,7 @@ func (a *LANsApiService) DatacentersLansDeleteExecute(r ApiDatacentersLansDelete return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarAPIResponse.Payload = localVarBody - if err != nil { - return localVarAPIResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := GenericOpenAPIError{ - statusCode: localVarHTTPResponse.StatusCode, - body: localVarBody, - error: fmt.Sprintf(FormatStringErr, localVarHTTPResponse.Status, string(localVarBody)), - } - var v Error - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = fmt.Sprintf(FormatStringErr, localVarHTTPResponse.Status, err.Error()) - return localVarAPIResponse, newErr - } - newErr.model = v - return localVarAPIResponse, newErr - } - - return localVarAPIResponse, nil -} - -type ApiDatacentersLansEnableIpv6Request struct { - ctx _context.Context - ApiService *LANsApiService - datacenterId string - pretty *bool - depth *int32 - xContractNumber *int32 -} - -func (r ApiDatacentersLansEnableIpv6Request) Pretty(pretty bool) ApiDatacentersLansEnableIpv6Request { - r.pretty = &pretty - return r -} -func (r ApiDatacentersLansEnableIpv6Request) Depth(depth int32) ApiDatacentersLansEnableIpv6Request { - r.depth = &depth - return r -} -func (r ApiDatacentersLansEnableIpv6Request) XContractNumber(xContractNumber int32) ApiDatacentersLansEnableIpv6Request { - r.xContractNumber = &xContractNumber - return r -} - -func (r ApiDatacentersLansEnableIpv6Request) Execute() (*APIResponse, error) { - return r.ApiService.DatacentersLansEnableIpv6Execute(r) -} - -/* - * DatacentersLansEnableIpv6 Enable IPv6 in the current Virtual Datacenter - * Enable IPv6 for all NICs in the current Virtual Datacenter. - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param datacenterId The unique ID of the data center. - * @return ApiDatacentersLansEnableIpv6Request - */ -func (a *LANsApiService) DatacentersLansEnableIpv6(ctx _context.Context, datacenterId string) ApiDatacentersLansEnableIpv6Request { - return ApiDatacentersLansEnableIpv6Request{ - ApiService: a, - ctx: ctx, - datacenterId: datacenterId, - } -} - -/* - * Execute executes the request - */ -func (a *LANsApiService) DatacentersLansEnableIpv6Execute(r ApiDatacentersLansEnableIpv6Request) (*APIResponse, error) { - var ( - localVarHTTPMethod = _nethttp.MethodPost - localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "LANsApiService.DatacentersLansEnableIpv6") - if err != nil { - return nil, GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/datacenters/{datacenterId}/lans/enable-ipv6" - localVarPath = strings.Replace(localVarPath, "{"+"datacenterId"+"}", _neturl.PathEscape(parameterToString(r.datacenterId, "")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := _neturl.Values{} - localVarFormParams := _neturl.Values{} - - if r.pretty != nil { - localVarQueryParams.Add("pretty", parameterToString(*r.pretty, "")) - } else { - defaultQueryParam := a.client.cfg.DefaultQueryParams.Get("pretty") - if defaultQueryParam == "" { - localVarQueryParams.Add("pretty", parameterToString(true, "")) - } - } - if r.depth != nil { - localVarQueryParams.Add("depth", parameterToString(*r.depth, "")) - } else { - defaultQueryParam := a.client.cfg.DefaultQueryParams.Get("depth") - if defaultQueryParam == "" { - localVarQueryParams.Add("depth", parameterToString(0, "")) - } - } - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"*/*"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - if r.xContractNumber != nil { - localVarHeaderParams["X-Contract-Number"] = parameterToString(*r.xContractNumber, "") - } - if r.ctx != nil { - // API Key Authentication - if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if apiKey, ok := auth["Token Authentication"]; ok { - var key string - if apiKey.Prefix != "" { - key = apiKey.Prefix + " " + apiKey.Key - } else { - key = apiKey.Key - } - localVarHeaderParams["Authorization"] = key - } - } - } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) - if err != nil { - return nil, err - } - - localVarHTTPResponse, httpRequestTime, err := a.client.callAPI(req) - - localVarAPIResponse := &APIResponse{ - Response: localVarHTTPResponse, - Method: localVarHTTPMethod, - RequestURL: localVarPath, - RequestTime: httpRequestTime, - Operation: "DatacentersLansEnableIpv6", - } - - if err != nil || localVarHTTPResponse == nil { - return localVarAPIResponse, err - } - - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -494,7 +333,7 @@ func (a *LANsApiService) DatacentersLansFindByIdExecute(r ApiDatacentersLansFind return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -729,7 +568,7 @@ func (a *LANsApiService) DatacentersLansGetExecute(r ApiDatacentersLansGetReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -910,7 +749,7 @@ func (a *LANsApiService) DatacentersLansNicsFindByIdExecute(r ApiDatacentersLans return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1149,7 +988,7 @@ func (a *LANsApiService) DatacentersLansNicsGetExecute(r ApiDatacentersLansNicsG return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1336,7 +1175,7 @@ func (a *LANsApiService) DatacentersLansNicsPostExecute(r ApiDatacentersLansNics return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1523,7 +1362,7 @@ func (a *LANsApiService) DatacentersLansPatchExecute(r ApiDatacentersLansPatchRe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1563,13 +1402,13 @@ type ApiDatacentersLansPostRequest struct { ctx _context.Context ApiService *LANsApiService datacenterId string - lan *Lan + lan *LanPost pretty *bool depth *int32 xContractNumber *int32 } -func (r ApiDatacentersLansPostRequest) Lan(lan Lan) ApiDatacentersLansPostRequest { +func (r ApiDatacentersLansPostRequest) Lan(lan LanPost) ApiDatacentersLansPostRequest { r.lan = &lan return r } @@ -1586,7 +1425,7 @@ func (r ApiDatacentersLansPostRequest) XContractNumber(xContractNumber int32) Ap return r } -func (r ApiDatacentersLansPostRequest) Execute() (Lan, *APIResponse, error) { +func (r ApiDatacentersLansPostRequest) Execute() (LanPost, *APIResponse, error) { return r.ApiService.DatacentersLansPostExecute(r) } @@ -1607,16 +1446,16 @@ func (a *LANsApiService) DatacentersLansPost(ctx _context.Context, datacenterId /* * Execute executes the request - * @return Lan + * @return LanPost */ -func (a *LANsApiService) DatacentersLansPostExecute(r ApiDatacentersLansPostRequest) (Lan, *APIResponse, error) { +func (a *LANsApiService) DatacentersLansPostExecute(r ApiDatacentersLansPostRequest) (LanPost, *APIResponse, error) { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte - localVarReturnValue Lan + localVarReturnValue LanPost ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "LANsApiService.DatacentersLansPost") @@ -1706,7 +1545,7 @@ func (a *LANsApiService) DatacentersLansPostExecute(r ApiDatacentersLansPostRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1893,7 +1732,7 @@ func (a *LANsApiService) DatacentersLansPutExecute(r ApiDatacentersLansPutReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_load_balancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_load_balancers.go index 3dbc558d6..bf9142fa8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_load_balancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_load_balancers.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -170,7 +170,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersBalancednicsDeleteExec return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -341,7 +341,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersBalancednicsFindByNicI return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -554,7 +554,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersBalancednicsGetExecute return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -741,7 +741,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersBalancednicsPostExecut return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -916,7 +916,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersDeleteExecute(r ApiDat return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1083,7 +1083,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersFindByIdExecute(r ApiD return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1318,7 +1318,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersGetExecute(r ApiDatace return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1505,7 +1505,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersPatchExecute(r ApiData return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1688,7 +1688,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersPostExecute(r ApiDatac return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1875,7 +1875,7 @@ func (a *LoadBalancersApiService) DatacentersLoadbalancersPutExecute(r ApiDatace return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_locations.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_locations.go index 687d5b515..960bbede7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_locations.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_locations.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -164,7 +164,7 @@ func (a *LocationsApiService) LocationsFindByRegionIdExecute(r ApiLocationsFindB return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -341,7 +341,7 @@ func (a *LocationsApiService) LocationsFindByRegionIdAndIdExecute(r ApiLocations return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -554,7 +554,7 @@ func (a *LocationsApiService) LocationsGetExecute(r ApiLocationsGetRequest) (Loc return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_nat_gateways.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_nat_gateways.go index 28677e79d..265502007 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_nat_gateways.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_nat_gateways.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -166,7 +166,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysDeleteExecute(r ApiDatacen return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -333,7 +333,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysFindByNatGatewayIdExecute( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -504,7 +504,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysFlowlogsDeleteExecute(r Ap return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -667,7 +667,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysFlowlogsFindByFlowLogIdExe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -898,7 +898,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysFlowlogsGetExecute(r ApiDa return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1081,7 +1081,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysFlowlogsPatchExecute(r Api return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1260,7 +1260,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysFlowlogsPostExecute(r ApiD return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1443,7 +1443,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysFlowlogsPutExecute(r ApiDa return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1652,7 +1652,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysGetExecute(r ApiDatacenter return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1839,7 +1839,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysPatchExecute(r ApiDatacent return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2024,7 +2024,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysPostExecute(r ApiDatacente return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2211,7 +2211,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysPutExecute(r ApiDatacenter return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2390,7 +2390,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysRulesDeleteExecute(r ApiDa return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2561,7 +2561,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysRulesFindByNatGatewayRuleI return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2774,7 +2774,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysRulesGetExecute(r ApiDatac return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2965,7 +2965,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysRulesPatchExecute(r ApiDat return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3152,7 +3152,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysRulesPostExecute(r ApiData return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3343,7 +3343,7 @@ func (a *NATGatewaysApiService) DatacentersNatgatewaysRulesPutExecute(r ApiDatac return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_interfaces.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_interfaces.go index af7adb740..8ba4b06c3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_interfaces.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_interfaces.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -170,7 +170,7 @@ func (a *NetworkInterfacesApiService) DatacentersServersNicsDeleteExecute(r ApiD return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -341,7 +341,7 @@ func (a *NetworkInterfacesApiService) DatacentersServersNicsFindByIdExecute(r Ap return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -580,7 +580,7 @@ func (a *NetworkInterfacesApiService) DatacentersServersNicsGetExecute(r ApiData return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -771,7 +771,7 @@ func (a *NetworkInterfacesApiService) DatacentersServersNicsPatchExecute(r ApiDa return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -958,7 +958,7 @@ func (a *NetworkInterfacesApiService) DatacentersServersNicsPostExecute(r ApiDat return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1149,7 +1149,7 @@ func (a *NetworkInterfacesApiService) DatacentersServersNicsPutExecute(r ApiData return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_load_balancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_load_balancers.go index 5fc162e1d..6e5b317d1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_load_balancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_network_load_balancers.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -166,7 +166,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersDeleteEx return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -333,7 +333,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersFindByNe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -512,7 +512,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersFlowlogs return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -683,7 +683,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersFlowlogs return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -896,7 +896,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersFlowlogs return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1087,7 +1087,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersFlowlogs return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1274,7 +1274,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersFlowlogs return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1465,7 +1465,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersFlowlogs return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1644,7 +1644,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersForwardi return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1815,7 +1815,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersForwardi return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2028,7 +2028,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersForwardi return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2219,7 +2219,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersForwardi return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2406,7 +2406,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersForwardi return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2597,7 +2597,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersForwardi return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2832,7 +2832,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersGetExecu return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3019,7 +3019,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersPatchExe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3202,7 +3202,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersPostExec return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3389,7 +3389,7 @@ func (a *NetworkLoadBalancersApiService) DatacentersNetworkloadbalancersPutExecu return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_private_cross_connects.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_private_cross_connects.go index d3d382f9c..8f02a0971 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_private_cross_connects.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_private_cross_connects.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *PrivateCrossConnectsApiService) PccsDeleteExecute(r ApiPccsDeleteReques return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *PrivateCrossConnectsApiService) PccsFindByIdExecute(r ApiPccsFindByIdRe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -530,7 +530,7 @@ func (a *PrivateCrossConnectsApiService) PccsGetExecute(r ApiPccsGetRequest) (Pr return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -713,7 +713,7 @@ func (a *PrivateCrossConnectsApiService) PccsPatchExecute(r ApiPccsPatchRequest) return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -892,7 +892,7 @@ func (a *PrivateCrossConnectsApiService) PccsPostExecute(r ApiPccsPostRequest) ( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_requests.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_requests.go index caef490fe..42de45c21 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_requests.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_requests.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -164,7 +164,7 @@ func (a *RequestsApiService) RequestsFindByIdExecute(r ApiRequestsFindByIdReques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -483,7 +483,7 @@ func (a *RequestsApiService) RequestsGetExecute(r ApiRequestsGetRequest) (Reques return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -692,7 +692,7 @@ func (a *RequestsApiService) RequestsStatusGetExecute(r ApiRequestsStatusGetRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_servers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_servers.go index 75ae6b688..e3716f10a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_servers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_servers.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -174,7 +174,7 @@ func (a *ServersApiService) DatacentersServersCdromsDeleteExecute(r ApiDatacente return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -345,7 +345,7 @@ func (a *ServersApiService) DatacentersServersCdromsFindByIdExecute(r ApiDatacen return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -584,7 +584,7 @@ func (a *ServersApiService) DatacentersServersCdromsGetExecute(r ApiDatacentersS return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -775,7 +775,7 @@ func (a *ServersApiService) DatacentersServersCdromsPostExecute(r ApiDatacenters return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -958,7 +958,7 @@ func (a *ServersApiService) DatacentersServersDeleteExecute(r ApiDatacentersServ return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1125,7 +1125,7 @@ func (a *ServersApiService) DatacentersServersFindByIdExecute(r ApiDatacentersSe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1368,7 +1368,7 @@ func (a *ServersApiService) DatacentersServersGetExecute(r ApiDatacentersServers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1555,7 +1555,7 @@ func (a *ServersApiService) DatacentersServersPatchExecute(r ApiDatacentersServe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1738,7 +1738,7 @@ func (a *ServersApiService) DatacentersServersPostExecute(r ApiDatacentersServer return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1927,7 +1927,7 @@ func (a *ServersApiService) DatacentersServersPutExecute(r ApiDatacentersServers return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2102,7 +2102,7 @@ func (a *ServersApiService) DatacentersServersRebootPostExecute(r ApiDatacenters return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2305,7 +2305,7 @@ func (a *ServersApiService) DatacentersServersRemoteConsoleGetExecute(r ApiDatac return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2484,7 +2484,7 @@ func (a *ServersApiService) DatacentersServersResumePostExecute(r ApiDatacenters return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2657,7 +2657,7 @@ func (a *ServersApiService) DatacentersServersStartPostExecute(r ApiDatacentersS return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2830,7 +2830,7 @@ func (a *ServersApiService) DatacentersServersStopPostExecute(r ApiDatacentersSe return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2999,7 +2999,7 @@ func (a *ServersApiService) DatacentersServersSuspendPostExecute(r ApiDatacenter return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3202,7 +3202,7 @@ func (a *ServersApiService) DatacentersServersTokenGetExecute(r ApiDatacentersSe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3377,7 +3377,7 @@ func (a *ServersApiService) DatacentersServersUpgradePostExecute(r ApiDatacenter return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3548,7 +3548,7 @@ func (a *ServersApiService) DatacentersServersVolumesDeleteExecute(r ApiDatacent return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3719,7 +3719,7 @@ func (a *ServersApiService) DatacentersServersVolumesFindByIdExecute(r ApiDatace return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3958,7 +3958,7 @@ func (a *ServersApiService) DatacentersServersVolumesGetExecute(r ApiDatacenters return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4151,7 +4151,7 @@ func (a *ServersApiService) DatacentersServersVolumesPostExecute(r ApiDatacenter return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_snapshots.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_snapshots.go index 2a6302b8a..1595da3a3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_snapshots.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_snapshots.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *SnapshotsApiService) SnapshotsDeleteExecute(r ApiSnapshotsDeleteRequest return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *SnapshotsApiService) SnapshotsFindByIdExecute(r ApiSnapshotsFindByIdReq return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -530,7 +530,7 @@ func (a *SnapshotsApiService) SnapshotsGetExecute(r ApiSnapshotsGetRequest) (Sna return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -713,7 +713,7 @@ func (a *SnapshotsApiService) SnapshotsPatchExecute(r ApiSnapshotsPatchRequest) return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -896,7 +896,7 @@ func (a *SnapshotsApiService) SnapshotsPutExecute(r ApiSnapshotsPutRequest) (Sna return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_target_groups.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_target_groups.go index 0e111462f..6b5bd8feb 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_target_groups.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_target_groups.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *TargetGroupsApiService) TargetGroupsDeleteExecute(r ApiTargetGroupsDele return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *TargetGroupsApiService) TargetgroupsFindByTargetGroupIdExecute(r ApiTar return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -558,7 +558,7 @@ func (a *TargetGroupsApiService) TargetgroupsGetExecute(r ApiTargetgroupsGetRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -741,7 +741,7 @@ func (a *TargetGroupsApiService) TargetgroupsPatchExecute(r ApiTargetgroupsPatch return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -920,7 +920,7 @@ func (a *TargetGroupsApiService) TargetgroupsPostExecute(r ApiTargetgroupsPostRe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1103,7 +1103,7 @@ func (a *TargetGroupsApiService) TargetgroupsPutExecute(r ApiTargetgroupsPutRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_templates.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_templates.go index 31823f0e5..63451fc8e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_templates.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_templates.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -143,7 +143,7 @@ func (a *TemplatesApiService) TemplatesFindByIdExecute(r ApiTemplatesFindByIdReq return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -331,7 +331,7 @@ func (a *TemplatesApiService) TemplatesGetExecute(r ApiTemplatesGetRequest) (Tem return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_management.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_management.go index e159bd5ad..f27c5a280 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_management.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_management.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -162,7 +162,7 @@ func (a *UserManagementApiService) UmGroupsDeleteExecute(r ApiUmGroupsDeleteRequ return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -325,7 +325,7 @@ func (a *UserManagementApiService) UmGroupsFindByIdExecute(r ApiUmGroupsFindById return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -530,7 +530,7 @@ func (a *UserManagementApiService) UmGroupsGetExecute(r ApiUmGroupsGetRequest) ( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -709,7 +709,7 @@ func (a *UserManagementApiService) UmGroupsPostExecute(r ApiUmGroupsPostRequest) return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -892,7 +892,7 @@ func (a *UserManagementApiService) UmGroupsPutExecute(r ApiUmGroupsPutRequest) ( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1101,7 +1101,7 @@ func (a *UserManagementApiService) UmGroupsResourcesGetExecute(r ApiUmGroupsReso return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1276,7 +1276,7 @@ func (a *UserManagementApiService) UmGroupsSharesDeleteExecute(r ApiUmGroupsShar return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1443,7 +1443,7 @@ func (a *UserManagementApiService) UmGroupsSharesFindByResourceIdExecute(r ApiUm return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1652,7 +1652,7 @@ func (a *UserManagementApiService) UmGroupsSharesGetExecute(r ApiUmGroupsSharesG return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1839,7 +1839,7 @@ func (a *UserManagementApiService) UmGroupsSharesPostExecute(r ApiUmGroupsShares return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2026,7 +2026,7 @@ func (a *UserManagementApiService) UmGroupsSharesPutExecute(r ApiUmGroupsSharesP return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2201,7 +2201,7 @@ func (a *UserManagementApiService) UmGroupsUsersDeleteExecute(r ApiUmGroupsUsers return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2400,7 +2400,7 @@ func (a *UserManagementApiService) UmGroupsUsersGetExecute(r ApiUmGroupsUsersGet return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2583,7 +2583,7 @@ func (a *UserManagementApiService) UmGroupsUsersPostExecute(r ApiUmGroupsUsersPo return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2760,7 +2760,7 @@ func (a *UserManagementApiService) UmResourcesFindByTypeExecute(r ApiUmResources return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -2941,7 +2941,7 @@ func (a *UserManagementApiService) UmResourcesFindByTypeAndIdExecute(r ApiUmReso return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3146,7 +3146,7 @@ func (a *UserManagementApiService) UmResourcesGetExecute(r ApiUmResourcesGetRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3317,7 +3317,7 @@ func (a *UserManagementApiService) UmUsersDeleteExecute(r ApiUmUsersDeleteReques return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3480,7 +3480,7 @@ func (a *UserManagementApiService) UmUsersFindByIdExecute(r ApiUmUsersFindByIdRe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3711,7 +3711,7 @@ func (a *UserManagementApiService) UmUsersGetExecute(r ApiUmUsersGetRequest) (Us return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -3920,7 +3920,7 @@ func (a *UserManagementApiService) UmUsersGroupsGetExecute(r ApiUmUsersGroupsGet return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4129,7 +4129,7 @@ func (a *UserManagementApiService) UmUsersOwnsGetExecute(r ApiUmUsersOwnsGetRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4308,7 +4308,7 @@ func (a *UserManagementApiService) UmUsersPostExecute(r ApiUmUsersPostRequest) ( return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -4491,7 +4491,7 @@ func (a *UserManagementApiService) UmUsersPutExecute(r ApiUmUsersPutRequest) (Us return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_s3_keys.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_s3_keys.go index e46bbd737..c8302e01e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_s3_keys.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_user_s3_keys.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -166,7 +166,7 @@ func (a *UserS3KeysApiService) UmUsersS3keysDeleteExecute(r ApiUmUsersS3keysDele return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -333,7 +333,7 @@ func (a *UserS3KeysApiService) UmUsersS3keysFindByKeyIdExecute(r ApiUmUsersS3key return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -542,7 +542,7 @@ func (a *UserS3KeysApiService) UmUsersS3keysGetExecute(r ApiUmUsersS3keysGetRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -715,7 +715,7 @@ func (a *UserS3KeysApiService) UmUsersS3keysPostExecute(r ApiUmUsersS3keysPostRe return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -902,7 +902,7 @@ func (a *UserS3KeysApiService) UmUsersS3keysPutExecute(r ApiUmUsersS3keysPutRequ return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1098,7 +1098,7 @@ func (a *UserS3KeysApiService) UmUsersS3ssourlGetExecute(r ApiUmUsersS3ssourlGet return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_volumes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_volumes.go index b869d7fff..d7f5e3778 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_volumes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_volumes.go @@ -13,7 +13,7 @@ package ionoscloud import ( _context "context" "fmt" - _ioutil "io/ioutil" + "io" _nethttp "net/http" _neturl "net/url" "strings" @@ -200,7 +200,7 @@ func (a *VolumesApiService) DatacentersVolumesCreateSnapshotPostExecute(r ApiDat return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -375,7 +375,7 @@ func (a *VolumesApiService) DatacentersVolumesDeleteExecute(r ApiDatacentersVolu return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -542,7 +542,7 @@ func (a *VolumesApiService) DatacentersVolumesFindByIdExecute(r ApiDatacentersVo return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -777,7 +777,7 @@ func (a *VolumesApiService) DatacentersVolumesGetExecute(r ApiDatacentersVolumes return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -964,7 +964,7 @@ func (a *VolumesApiService) DatacentersVolumesPatchExecute(r ApiDatacentersVolum return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1147,7 +1147,7 @@ func (a *VolumesApiService) DatacentersVolumesPostExecute(r ApiDatacentersVolume return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1334,7 +1334,7 @@ func (a *VolumesApiService) DatacentersVolumesPutExecute(r ApiDatacentersVolumes return localVarReturnValue, localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { @@ -1517,7 +1517,7 @@ func (a *VolumesApiService) DatacentersVolumesRestoreSnapshotPostExecute(r ApiDa return localVarAPIResponse, err } - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarAPIResponse.Payload = localVarBody if err != nil { diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/client.go b/vendor/github.com/ionos-cloud/sdk-go/v6/client.go index 0bbdf2a6d..fe8471d96 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/client.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/client.go @@ -22,7 +22,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime/multipart" "net" "net/http" @@ -53,7 +52,7 @@ const ( RequestStatusFailed = "FAILED" RequestStatusDone = "DONE" - Version = "6.1.6" + Version = "6.1.11" ) // Constants for APIs @@ -370,6 +369,9 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, time.Duratio case http.StatusServiceUnavailable, http.StatusGatewayTimeout, http.StatusBadGateway: + if request.Method == http.MethodPost { + return resp, httpRequestTime, err + } backoffTime = c.GetConfig().WaitTime case http.StatusTooManyRequests: @@ -393,21 +395,32 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, time.Duratio } break } else { - c.backOff(backoffTime) + c.backOff(request.Context(), backoffTime) } } return resp, httpRequestTime, err } -func (c *APIClient) backOff(t time.Duration) { +func (c *APIClient) backOff(ctx context.Context, t time.Duration) { if t > c.GetConfig().MaxWaitTime { t = c.GetConfig().MaxWaitTime } if c.cfg.Debug || c.cfg.LogLevel.Satisfies(Debug) { c.cfg.Logger.Printf(" sleeping %s before retrying request\n", t.String()) } - time.Sleep(t) + + if t <= 0 { + return + } + + timer := time.NewTimer(t) + defer timer.Stop() + + select { + case <-ctx.Done(): + case <-timer.C: + } } // Allow modification of underlying config for alternate implementations and testing @@ -430,6 +443,15 @@ func (c *APIClient) prepareRequest( var body *bytes.Buffer + val, isSetInEnv := os.LookupEnv(IonosContractNumber) + _, isSetInMap := headerParams["X-Contract-Number"] + if headerParams == nil { + headerParams = make(map[string]string) + } + if !isSetInMap && isSetInEnv { + headerParams["X-Contract-Number"] = val + } + // Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] @@ -636,7 +658,7 @@ func (c *APIClient) GetRequestStatus(ctx context.Context, path string) (*Request var responseBody = make([]byte, 0) if resp != nil { var errRead error - responseBody, errRead = ioutil.ReadAll(resp.Body) + responseBody, errRead = io.ReadAll(resp.Body) _ = resp.Body.Close() if errRead != nil { return nil, nil, errRead @@ -906,7 +928,7 @@ func (c *APIClient) WaitForRequest(ctx context.Context, path string) (*APIRespon var localVarBody = make([]byte, 0) if resp != nil { var errRead error - localVarBody, errRead = ioutil.ReadAll(resp.Body) + localVarBody, errRead = io.ReadAll(resp.Body) _ = resp.Body.Close() if errRead != nil { return nil, errRead @@ -935,7 +957,8 @@ func (c *APIClient) WaitForRequest(ctx context.Context, path string) (*APIRespon } if resp.StatusCode != http.StatusOK { - return localVarAPIResponse, fmt.Errorf("WaitForRequest failed; received status code %d from API", resp.StatusCode) + msg := fmt.Sprintf("WaitForRequest failed; received status code %d from API", resp.StatusCode) + return localVarAPIResponse, NewGenericOpenAPIError(msg, localVarBody, nil, resp.StatusCode) } if status.Metadata != nil && status.Metadata.Status != nil { switch *status.Metadata.Status { @@ -950,9 +973,7 @@ func (c *APIClient) WaitForRequest(ctx context.Context, path string) (*APIRespon if status.Metadata.Message != nil { message = *status.Metadata.Message } - return localVarAPIResponse, errors.New( - fmt.Sprintf("Request %s failed: %s", id, message), - ) + return localVarAPIResponse, fmt.Errorf("Request %s failed: %s", id, message) } } select { @@ -1092,7 +1113,7 @@ func strlen(s string) int { return utf8.RuneCountInString(s) } -// GenericOpenAPIError Provides access to the body, error and model on returned errors. +// GenericOpenAPIError provides access to the body, error and model on returned errors. type GenericOpenAPIError struct { statusCode int body []byte diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go b/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go index d6ef150c2..cb0488ae0 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go @@ -28,6 +28,7 @@ const ( IonosApiUrlEnvVar = "IONOS_API_URL" IonosPinnedCertEnvVar = "IONOS_PINNED_CERT" IonosLogLevelEnvVar = "IONOS_LOG_LEVEL" + IonosContractNumber = "IONOS_CONTRACT_NUMBER" DefaultIonosServerUrl = "https://api.ionos.com/cloudapi/v6" DefaultIonosBasePath = "/cloudapi/v6" defaultMaxRetries = 3 @@ -130,7 +131,7 @@ func NewConfiguration(username, password, token, hostUrl string) *Configuration cfg := &Configuration{ DefaultHeader: make(map[string]string), DefaultQueryParams: url.Values{}, - UserAgent: "ionos-cloud-sdk-go/v6.1.6", + UserAgent: "ionos-cloud-sdk-go/v6.1.11", Debug: false, Username: username, Password: password, @@ -140,6 +141,8 @@ func NewConfiguration(username, password, token, hostUrl string) *Configuration WaitTime: defaultWaitTime, Logger: NewDefaultLogger(), LogLevel: getLogLevelFromEnv(), + Host: getHost(hostUrl), + Scheme: getScheme(hostUrl), Servers: ServerConfigurations{ { URL: getServerUrl(hostUrl), @@ -267,6 +270,26 @@ func getServerUrl(serverUrl string) string { return serverUrl } +func getHost(serverUrl string) string { + // url.Parse only interprets the host correctly when the scheme is set, so we prepend one here if needed + if !strings.HasPrefix(serverUrl, "https://") && !strings.HasPrefix(serverUrl, "http://") { + serverUrl = "http://" + serverUrl + } + url, err := url.Parse(serverUrl) + if err != nil { + return "" + } + return url.Host +} + +func getScheme(serverUrl string) string { + url, err := url.Parse(serverUrl) + if err != nil { + return "" + } + return url.Scheme +} + // ServerURLWithContext returns a new server URL given an endpoint func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { sc, ok := c.OperationServers[endpoint] diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go index a63fe3431..61cf51188 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go @@ -16,15 +16,15 @@ import ( // ApplicationLoadBalancer struct for ApplicationLoadBalancer type ApplicationLoadBalancer struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *ApplicationLoadBalancerEntities `json:"entities,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ApplicationLoadBalancerProperties `json:"properties"` - Entities *ApplicationLoadBalancerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancer instantiates a new ApplicationLoadBalancer object @@ -47,114 +47,114 @@ func NewApplicationLoadBalancerWithDefaults() *ApplicationLoadBalancer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancer) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetEntities() *ApplicationLoadBalancerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancer) GetEntitiesOk() (*ApplicationLoadBalancerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *ApplicationLoadBalancer) SetId(v string) { +// SetEntities sets field value +func (o *ApplicationLoadBalancer) SetEntities(v ApplicationLoadBalancerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancer) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancer) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *ApplicationLoadBalancer) SetType(v Type) { +// SetHref sets field value +func (o *ApplicationLoadBalancer) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancer) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *ApplicationLoadBalancer) SetHref(v string) { +// SetId sets field value +func (o *ApplicationLoadBalancer) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *ApplicationLoadBalancer) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancer) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *ApplicationLoadBalancer) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerProperties will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancer) GetProperties() *ApplicationLoadBalancerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *ApplicationLoadBalancer) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerEntities will be returned -func (o *ApplicationLoadBalancer) GetEntities() *ApplicationLoadBalancerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetEntitiesOk() (*ApplicationLoadBalancerEntities, bool) { +func (o *ApplicationLoadBalancer) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *ApplicationLoadBalancer) SetEntities(v ApplicationLoadBalancerEntities) { +// SetType sets field value +func (o *ApplicationLoadBalancer) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *ApplicationLoadBalancer) HasEntities() bool { func (o ApplicationLoadBalancer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go index d8cd1a152..425fceaa1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go @@ -38,7 +38,7 @@ func NewApplicationLoadBalancerEntitiesWithDefaults() *ApplicationLoadBalancerEn } // GetForwardingrules returns the Forwardingrules field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerForwardingRules will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerEntities) GetForwardingrules() *ApplicationLoadBalancerForwardingRules { if o == nil { return nil @@ -80,6 +80,7 @@ func (o ApplicationLoadBalancerEntities) MarshalJSON() ([]byte, error) { if o.Forwardingrules != nil { toSerialize["forwardingrules"] = o.Forwardingrules } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go index 34c30dfc6..e9e1bd5c9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go @@ -16,14 +16,14 @@ import ( // ApplicationLoadBalancerForwardingRule struct for ApplicationLoadBalancerForwardingRule type ApplicationLoadBalancerForwardingRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ApplicationLoadBalancerForwardingRuleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancerForwardingRule instantiates a new ApplicationLoadBalancerForwardingRule object @@ -46,190 +46,190 @@ func NewApplicationLoadBalancerForwardingRuleWithDefaults() *ApplicationLoadBala return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetId(v string) { +// SetHref sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetType(v Type) { +// SetId sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetHref(v string) { +// SetMetadata sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerForwardingRuleProperties will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *ApplicationLoadBalancerForwardingRule) HasProperties() bool { func (o ApplicationLoadBalancerForwardingRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go index f73da694f..b5adc750a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go @@ -16,33 +16,33 @@ import ( // ApplicationLoadBalancerForwardingRuleProperties struct for ApplicationLoadBalancerForwardingRuleProperties type ApplicationLoadBalancerForwardingRuleProperties struct { - // The name of the Application Load Balancer forwarding rule. - Name *string `json:"name"` - // The balancing protocol. - Protocol *string `json:"protocol"` + // The maximum time in milliseconds to wait for the client to acknowledge or send data; default is 50,000 (50 seconds). + ClientTimeout *int32 `json:"clientTimeout,omitempty"` + // An array of items in the collection. The original order of rules is preserved during processing, except that rules of the 'FORWARD' type are processed after the rules with other defined actions. The relative order of the 'FORWARD' type rules is also preserved during the processing. + HttpRules *[]ApplicationLoadBalancerHttpRule `json:"httpRules,omitempty"` // The listening (inbound) IP. ListenerIp *string `json:"listenerIp"` // The listening (inbound) port number; the valid range is 1 to 65535. ListenerPort *int32 `json:"listenerPort"` - // The maximum time in milliseconds to wait for the client to acknowledge or send data; default is 50,000 (50 seconds). - ClientTimeout *int32 `json:"clientTimeout,omitempty"` + // The name of the Application Load Balancer forwarding rule. + Name *string `json:"name"` + // The balancing protocol. + Protocol *string `json:"protocol"` // Array of items in the collection. ServerCertificates *[]string `json:"serverCertificates,omitempty"` - // An array of items in the collection. The original order of rules is preserved during processing, except that rules of the 'FORWARD' type are processed after the rules with other defined actions. The relative order of the 'FORWARD' type rules is also preserved during the processing. - HttpRules *[]ApplicationLoadBalancerHttpRule `json:"httpRules,omitempty"` } // NewApplicationLoadBalancerForwardingRuleProperties instantiates a new ApplicationLoadBalancerForwardingRuleProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewApplicationLoadBalancerForwardingRuleProperties(name string, protocol string, listenerIp string, listenerPort int32) *ApplicationLoadBalancerForwardingRuleProperties { +func NewApplicationLoadBalancerForwardingRuleProperties(listenerIp string, listenerPort int32, name string, protocol string) *ApplicationLoadBalancerForwardingRuleProperties { this := ApplicationLoadBalancerForwardingRuleProperties{} - this.Name = &name - this.Protocol = &protocol this.ListenerIp = &listenerIp this.ListenerPort = &listenerPort + this.Name = &name + this.Protocol = &protocol return &this } @@ -55,76 +55,76 @@ func NewApplicationLoadBalancerForwardingRulePropertiesWithDefaults() *Applicati return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetName() *string { +// GetClientTimeout returns the ClientTimeout field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeout() *int32 { if o == nil { return nil } - return o.Name + return o.ClientTimeout } -// GetNameOk returns a tuple with the Name field value +// GetClientTimeoutOk returns a tuple with the ClientTimeout field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeoutOk() (*int32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ClientTimeout, true } -// SetName sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetName(v string) { +// SetClientTimeout sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetClientTimeout(v int32) { - o.Name = &v + o.ClientTimeout = &v } -// HasName returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasClientTimeout returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasClientTimeout() bool { + if o != nil && o.ClientTimeout != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocol() *string { +// GetHttpRules returns the HttpRules field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRules() *[]ApplicationLoadBalancerHttpRule { if o == nil { return nil } - return o.Protocol + return o.HttpRules } -// GetProtocolOk returns a tuple with the Protocol field value +// GetHttpRulesOk returns a tuple with the HttpRules field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRulesOk() (*[]ApplicationLoadBalancerHttpRule, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.HttpRules, true } -// SetProtocol sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetProtocol(v string) { +// SetHttpRules sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetHttpRules(v []ApplicationLoadBalancerHttpRule) { - o.Protocol = &v + o.HttpRules = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasHttpRules returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasHttpRules() bool { + if o != nil && o.HttpRules != nil { return true } @@ -132,7 +132,7 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasProtocol() bool { } // GetListenerIp returns the ListenerIp field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerForwardingRuleProperties) GetListenerIp() *string { if o == nil { return nil @@ -170,7 +170,7 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasListenerIp() bool { } // GetListenerPort returns the ListenerPort field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerForwardingRuleProperties) GetListenerPort() *int32 { if o == nil { return nil @@ -207,114 +207,114 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasListenerPort() bool return false } -// GetClientTimeout returns the ClientTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeout() *int32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetName() *string { if o == nil { return nil } - return o.ClientTimeout + return o.Name } -// GetClientTimeoutOk returns a tuple with the ClientTimeout field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeoutOk() (*int32, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ClientTimeout, true + return o.Name, true } -// SetClientTimeout sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetClientTimeout(v int32) { +// SetName sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetName(v string) { - o.ClientTimeout = &v + o.Name = &v } -// HasClientTimeout returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasClientTimeout() bool { - if o != nil && o.ClientTimeout != nil { +// HasName returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetServerCertificates returns the ServerCertificates field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificates() *[]string { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocol() *string { if o == nil { return nil } - return o.ServerCertificates + return o.Protocol } -// GetServerCertificatesOk returns a tuple with the ServerCertificates field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificatesOk() (*[]string, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.ServerCertificates, true + return o.Protocol, true } -// SetServerCertificates sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetServerCertificates(v []string) { +// SetProtocol sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetProtocol(v string) { - o.ServerCertificates = &v + o.Protocol = &v } -// HasServerCertificates returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasServerCertificates() bool { - if o != nil && o.ServerCertificates != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetHttpRules returns the HttpRules field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancerHttpRule will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRules() *[]ApplicationLoadBalancerHttpRule { +// GetServerCertificates returns the ServerCertificates field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificates() *[]string { if o == nil { return nil } - return o.HttpRules + return o.ServerCertificates } -// GetHttpRulesOk returns a tuple with the HttpRules field value +// GetServerCertificatesOk returns a tuple with the ServerCertificates field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRulesOk() (*[]ApplicationLoadBalancerHttpRule, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificatesOk() (*[]string, bool) { if o == nil { return nil, false } - return o.HttpRules, true + return o.ServerCertificates, true } -// SetHttpRules sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetHttpRules(v []ApplicationLoadBalancerHttpRule) { +// SetServerCertificates sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetServerCertificates(v []string) { - o.HttpRules = &v + o.ServerCertificates = &v } -// HasHttpRules returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasHttpRules() bool { - if o != nil && o.HttpRules != nil { +// HasServerCertificates returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasServerCertificates() bool { + if o != nil && o.ServerCertificates != nil { return true } @@ -323,27 +323,34 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasHttpRules() bool { func (o ApplicationLoadBalancerForwardingRuleProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ClientTimeout != nil { + toSerialize["clientTimeout"] = o.ClientTimeout } - if o.Protocol != nil { - toSerialize["protocol"] = o.Protocol + + if o.HttpRules != nil { + toSerialize["httpRules"] = o.HttpRules } + if o.ListenerIp != nil { toSerialize["listenerIp"] = o.ListenerIp } + if o.ListenerPort != nil { toSerialize["listenerPort"] = o.ListenerPort } - if o.ClientTimeout != nil { - toSerialize["clientTimeout"] = o.ClientTimeout + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.Protocol != nil { + toSerialize["protocol"] = o.Protocol } + if o.ServerCertificates != nil { toSerialize["serverCertificates"] = o.ServerCertificates } - if o.HttpRules != nil { - toSerialize["httpRules"] = o.HttpRules - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go index 0328b229c..d5e6f649a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go @@ -16,13 +16,13 @@ import ( // ApplicationLoadBalancerForwardingRulePut struct for ApplicationLoadBalancerForwardingRulePut type ApplicationLoadBalancerForwardingRulePut struct { + // The URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *ApplicationLoadBalancerForwardingRuleProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *ApplicationLoadBalancerForwardingRuleProperties `json:"properties"` } // NewApplicationLoadBalancerForwardingRulePut instantiates a new ApplicationLoadBalancerForwardingRulePut object @@ -45,152 +45,152 @@ func NewApplicationLoadBalancerForwardingRulePutWithDefaults() *ApplicationLoadB return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetId(v string) { +// SetHref sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetType(v Type) { +// SetId sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetHref(v string) { +// SetProperties sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerForwardingRuleProperties will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *ApplicationLoadBalancerForwardingRulePut) HasProperties() bool { func (o ApplicationLoadBalancerForwardingRulePut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go index 14b1f86e5..aae71997f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go @@ -16,19 +16,19 @@ import ( // ApplicationLoadBalancerForwardingRules struct for ApplicationLoadBalancerForwardingRules type ApplicationLoadBalancerForwardingRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]ApplicationLoadBalancerForwardingRule `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancerForwardingRules instantiates a new ApplicationLoadBalancerForwardingRules object @@ -49,114 +49,114 @@ func NewApplicationLoadBalancerForwardingRulesWithDefaults() *ApplicationLoadBal return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetId(v string) { +// SetLinks sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetType(v Type) { +// SetHref sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetHref(v string) { +// SetId sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *ApplicationLoadBalancerForwardingRules) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancerForwardingRule will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerForwardingRules) GetItems() *[]ApplicationLoadBalancerForwardingRule { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *ApplicationLoadBalancerForwardingRules) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetOffset(v float32) { +// SetLimit sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetLimit(v float32) { +// SetOffset sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *ApplicationLoadBalancerForwardingRules) HasLinks() bool { func (o ApplicationLoadBalancerForwardingRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go index 9c117202e..1d52893f5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go @@ -16,24 +16,24 @@ import ( // ApplicationLoadBalancerHttpRule struct for ApplicationLoadBalancerHttpRule type ApplicationLoadBalancerHttpRule struct { - // The unique name of the Application Load Balancer HTTP rule. - Name *string `json:"name"` - // The HTTP rule type. - Type *string `json:"type"` - // The ID of the target group; this parameter is mandatory and is valid only for 'FORWARD' actions. - TargetGroup *string `json:"targetGroup,omitempty"` + // An array of items in the collection. The action will be executed only if each condition is met; the rule will always be applied if no conditions are set. + Conditions *[]ApplicationLoadBalancerHttpRuleCondition `json:"conditions,omitempty"` + // Specifies the content type and is valid only for 'STATIC' actions. + ContentType *string `json:"contentType,omitempty"` // Indicates whether the query part of the URI should be dropped and is valid only for 'REDIRECT' actions. Default value is 'FALSE', the redirect URI does not contain any query parameters. DropQuery *bool `json:"dropQuery,omitempty"` // The location for the redirection; this parameter is mandatory and valid only for 'REDIRECT' actions. Location *string `json:"location,omitempty"` - // The status code is for 'REDIRECT' and 'STATIC' actions only. If the HTTP rule is 'REDIRECT' the valid values are: 301, 302, 303, 307, 308; default value is '301'. If the HTTP rule is 'STATIC' the valid values are from the range 200-599; default value is '503'. - StatusCode *int32 `json:"statusCode,omitempty"` + // The unique name of the Application Load Balancer HTTP rule. + Name *string `json:"name"` // The response message of the request; this parameter is mandatory for 'STATIC' actions. ResponseMessage *string `json:"responseMessage,omitempty"` - // Specifies the content type and is valid only for 'STATIC' actions. - ContentType *string `json:"contentType,omitempty"` - // An array of items in the collection. The action will be executed only if each condition is met; the rule will always be applied if no conditions are set. - Conditions *[]ApplicationLoadBalancerHttpRuleCondition `json:"conditions,omitempty"` + // The status code is for 'REDIRECT' and 'STATIC' actions only. If the HTTP rule is 'REDIRECT' the valid values are: 301, 302, 303, 307, 308; default value is '301'. If the HTTP rule is 'STATIC' the valid values are from the range 200-599; default value is '503'. + StatusCode *int32 `json:"statusCode,omitempty"` + // The ID of the target group; this parameter is mandatory and is valid only for 'FORWARD' actions. + TargetGroup *string `json:"targetGroup,omitempty"` + // The HTTP rule type. + Type *string `json:"type"` } // NewApplicationLoadBalancerHttpRule instantiates a new ApplicationLoadBalancerHttpRule object @@ -57,114 +57,76 @@ func NewApplicationLoadBalancerHttpRuleWithDefaults() *ApplicationLoadBalancerHt return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetName() *string { - if o == nil { - return nil - } - - return o.Name - -} - -// GetNameOk returns a tuple with the Name field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetNameOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Name, true -} - -// SetName sets field value -func (o *ApplicationLoadBalancerHttpRule) SetName(v string) { - - o.Name = &v - -} - -// HasName returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasName() bool { - if o != nil && o.Name != nil { - return true - } - - return false -} - -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetType() *string { +// GetConditions returns the Conditions field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetConditions() *[]ApplicationLoadBalancerHttpRuleCondition { if o == nil { return nil } - return o.Type + return o.Conditions } -// GetTypeOk returns a tuple with the Type field value +// GetConditionsOk returns a tuple with the Conditions field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetTypeOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetConditionsOk() (*[]ApplicationLoadBalancerHttpRuleCondition, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Conditions, true } -// SetType sets field value -func (o *ApplicationLoadBalancerHttpRule) SetType(v string) { +// SetConditions sets field value +func (o *ApplicationLoadBalancerHttpRule) SetConditions(v []ApplicationLoadBalancerHttpRuleCondition) { - o.Type = &v + o.Conditions = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasType() bool { - if o != nil && o.Type != nil { +// HasConditions returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasConditions() bool { + if o != nil && o.Conditions != nil { return true } return false } -// GetTargetGroup returns the TargetGroup field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetTargetGroup() *string { +// GetContentType returns the ContentType field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetContentType() *string { if o == nil { return nil } - return o.TargetGroup + return o.ContentType } -// GetTargetGroupOk returns a tuple with the TargetGroup field value +// GetContentTypeOk returns a tuple with the ContentType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetTargetGroupOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetContentTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.TargetGroup, true + return o.ContentType, true } -// SetTargetGroup sets field value -func (o *ApplicationLoadBalancerHttpRule) SetTargetGroup(v string) { +// SetContentType sets field value +func (o *ApplicationLoadBalancerHttpRule) SetContentType(v string) { - o.TargetGroup = &v + o.ContentType = &v } -// HasTargetGroup returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasTargetGroup() bool { - if o != nil && o.TargetGroup != nil { +// HasContentType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasContentType() bool { + if o != nil && o.ContentType != nil { return true } @@ -172,7 +134,7 @@ func (o *ApplicationLoadBalancerHttpRule) HasTargetGroup() bool { } // GetDropQuery returns the DropQuery field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRule) GetDropQuery() *bool { if o == nil { return nil @@ -210,7 +172,7 @@ func (o *ApplicationLoadBalancerHttpRule) HasDropQuery() bool { } // GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRule) GetLocation() *string { if o == nil { return nil @@ -247,38 +209,38 @@ func (o *ApplicationLoadBalancerHttpRule) HasLocation() bool { return false } -// GetStatusCode returns the StatusCode field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ApplicationLoadBalancerHttpRule) GetStatusCode() *int32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetName() *string { if o == nil { return nil } - return o.StatusCode + return o.Name } -// GetStatusCodeOk returns a tuple with the StatusCode field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetStatusCodeOk() (*int32, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.StatusCode, true + return o.Name, true } -// SetStatusCode sets field value -func (o *ApplicationLoadBalancerHttpRule) SetStatusCode(v int32) { +// SetName sets field value +func (o *ApplicationLoadBalancerHttpRule) SetName(v string) { - o.StatusCode = &v + o.Name = &v } -// HasStatusCode returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasStatusCode() bool { - if o != nil && o.StatusCode != nil { +// HasName returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -286,7 +248,7 @@ func (o *ApplicationLoadBalancerHttpRule) HasStatusCode() bool { } // GetResponseMessage returns the ResponseMessage field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRule) GetResponseMessage() *string { if o == nil { return nil @@ -323,76 +285,114 @@ func (o *ApplicationLoadBalancerHttpRule) HasResponseMessage() bool { return false } -// GetContentType returns the ContentType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetContentType() *string { +// GetStatusCode returns the StatusCode field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetStatusCode() *int32 { if o == nil { return nil } - return o.ContentType + return o.StatusCode } -// GetContentTypeOk returns a tuple with the ContentType field value +// GetStatusCodeOk returns a tuple with the StatusCode field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetContentTypeOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetStatusCodeOk() (*int32, bool) { if o == nil { return nil, false } - return o.ContentType, true + return o.StatusCode, true } -// SetContentType sets field value -func (o *ApplicationLoadBalancerHttpRule) SetContentType(v string) { +// SetStatusCode sets field value +func (o *ApplicationLoadBalancerHttpRule) SetStatusCode(v int32) { - o.ContentType = &v + o.StatusCode = &v } -// HasContentType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasContentType() bool { - if o != nil && o.ContentType != nil { +// HasStatusCode returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasStatusCode() bool { + if o != nil && o.StatusCode != nil { return true } return false } -// GetConditions returns the Conditions field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancerHttpRuleCondition will be returned -func (o *ApplicationLoadBalancerHttpRule) GetConditions() *[]ApplicationLoadBalancerHttpRuleCondition { +// GetTargetGroup returns the TargetGroup field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetTargetGroup() *string { if o == nil { return nil } - return o.Conditions + return o.TargetGroup } -// GetConditionsOk returns a tuple with the Conditions field value +// GetTargetGroupOk returns a tuple with the TargetGroup field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetConditionsOk() (*[]ApplicationLoadBalancerHttpRuleCondition, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetTargetGroupOk() (*string, bool) { if o == nil { return nil, false } - return o.Conditions, true + return o.TargetGroup, true } -// SetConditions sets field value -func (o *ApplicationLoadBalancerHttpRule) SetConditions(v []ApplicationLoadBalancerHttpRuleCondition) { +// SetTargetGroup sets field value +func (o *ApplicationLoadBalancerHttpRule) SetTargetGroup(v string) { - o.Conditions = &v + o.TargetGroup = &v } -// HasConditions returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasConditions() bool { - if o != nil && o.Conditions != nil { +// HasTargetGroup returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasTargetGroup() bool { + if o != nil && o.TargetGroup != nil { + return true + } + + return false +} + +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetType() *string { + if o == nil { + return nil + } + + return o.Type + +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *ApplicationLoadBalancerHttpRule) GetTypeOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Type, true +} + +// SetType sets field value +func (o *ApplicationLoadBalancerHttpRule) SetType(v string) { + + o.Type = &v + +} + +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -401,33 +401,42 @@ func (o *ApplicationLoadBalancerHttpRule) HasConditions() bool { func (o ApplicationLoadBalancerHttpRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Conditions != nil { + toSerialize["conditions"] = o.Conditions } - if o.TargetGroup != nil { - toSerialize["targetGroup"] = o.TargetGroup + + if o.ContentType != nil { + toSerialize["contentType"] = o.ContentType } + if o.DropQuery != nil { toSerialize["dropQuery"] = o.DropQuery } + if o.Location != nil { toSerialize["location"] = o.Location } - if o.StatusCode != nil { - toSerialize["statusCode"] = o.StatusCode + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.ResponseMessage != nil { toSerialize["responseMessage"] = o.ResponseMessage } - if o.ContentType != nil { - toSerialize["contentType"] = o.ContentType + + if o.StatusCode != nil { + toSerialize["statusCode"] = o.StatusCode } - if o.Conditions != nil { - toSerialize["conditions"] = o.Conditions + + if o.TargetGroup != nil { + toSerialize["targetGroup"] = o.TargetGroup } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go index a61e46532..a2b12adfd 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go @@ -16,14 +16,14 @@ import ( // ApplicationLoadBalancerHttpRuleCondition struct for ApplicationLoadBalancerHttpRuleCondition type ApplicationLoadBalancerHttpRuleCondition struct { - // The HTTP rule condition type. - Type *string `json:"type"` // The matching rule for the HTTP rule condition attribute; this parameter is mandatory for 'HEADER', 'PATH', 'QUERY', 'METHOD', 'HOST', and 'COOKIE' types. It must be 'null' if the type is 'SOURCE_IP'. Condition *string `json:"condition"` - // Specifies whether the condition should be negated; the default value is 'FALSE'. - Negate *bool `json:"negate,omitempty"` // The key can only be set when the HTTP rule condition type is 'COOKIES', 'HEADER', or 'QUERY'. For the type 'PATH', 'METHOD', 'HOST', or 'SOURCE_IP' the value must be 'null'. Key *string `json:"key,omitempty"` + // Specifies whether the condition should be negated; the default value is 'FALSE'. + Negate *bool `json:"negate,omitempty"` + // The HTTP rule condition type. + Type *string `json:"type"` // This parameter is mandatory for the conditions 'CONTAINS', 'EQUALS', 'MATCHES', 'STARTS_WITH', 'ENDS_WITH', or if the type is 'SOURCE_IP'. Specify a valid CIDR. If the condition is 'EXISTS', the value must be 'null'. Value *string `json:"value,omitempty"` } @@ -32,11 +32,11 @@ type ApplicationLoadBalancerHttpRuleCondition struct { // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewApplicationLoadBalancerHttpRuleCondition(type_ string, condition string) *ApplicationLoadBalancerHttpRuleCondition { +func NewApplicationLoadBalancerHttpRuleCondition(condition string, type_ string) *ApplicationLoadBalancerHttpRuleCondition { this := ApplicationLoadBalancerHttpRuleCondition{} - this.Type = &type_ this.Condition = &condition + this.Type = &type_ return &this } @@ -49,76 +49,76 @@ func NewApplicationLoadBalancerHttpRuleConditionWithDefaults() *ApplicationLoadB return &this } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetType() *string { +// GetCondition returns the Condition field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRuleCondition) GetCondition() *string { if o == nil { return nil } - return o.Type + return o.Condition } -// GetTypeOk returns a tuple with the Type field value +// GetConditionOk returns a tuple with the Condition field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetTypeOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRuleCondition) GetConditionOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Condition, true } -// SetType sets field value -func (o *ApplicationLoadBalancerHttpRuleCondition) SetType(v string) { +// SetCondition sets field value +func (o *ApplicationLoadBalancerHttpRuleCondition) SetCondition(v string) { - o.Type = &v + o.Condition = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRuleCondition) HasType() bool { - if o != nil && o.Type != nil { +// HasCondition returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRuleCondition) HasCondition() bool { + if o != nil && o.Condition != nil { return true } return false } -// GetCondition returns the Condition field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetCondition() *string { +// GetKey returns the Key field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRuleCondition) GetKey() *string { if o == nil { return nil } - return o.Condition + return o.Key } -// GetConditionOk returns a tuple with the Condition field value +// GetKeyOk returns a tuple with the Key field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetConditionOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRuleCondition) GetKeyOk() (*string, bool) { if o == nil { return nil, false } - return o.Condition, true + return o.Key, true } -// SetCondition sets field value -func (o *ApplicationLoadBalancerHttpRuleCondition) SetCondition(v string) { +// SetKey sets field value +func (o *ApplicationLoadBalancerHttpRuleCondition) SetKey(v string) { - o.Condition = &v + o.Key = &v } -// HasCondition returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRuleCondition) HasCondition() bool { - if o != nil && o.Condition != nil { +// HasKey returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRuleCondition) HasKey() bool { + if o != nil && o.Key != nil { return true } @@ -126,7 +126,7 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasCondition() bool { } // GetNegate returns the Negate field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRuleCondition) GetNegate() *bool { if o == nil { return nil @@ -163,38 +163,38 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasNegate() bool { return false } -// GetKey returns the Key field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetKey() *string { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRuleCondition) GetType() *string { if o == nil { return nil } - return o.Key + return o.Type } -// GetKeyOk returns a tuple with the Key field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetKeyOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRuleCondition) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Key, true + return o.Type, true } -// SetKey sets field value -func (o *ApplicationLoadBalancerHttpRuleCondition) SetKey(v string) { +// SetType sets field value +func (o *ApplicationLoadBalancerHttpRuleCondition) SetType(v string) { - o.Key = &v + o.Type = &v } -// HasKey returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRuleCondition) HasKey() bool { - if o != nil && o.Key != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRuleCondition) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -202,7 +202,7 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasKey() bool { } // GetValue returns the Value field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRuleCondition) GetValue() *string { if o == nil { return nil @@ -241,21 +241,26 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasValue() bool { func (o ApplicationLoadBalancerHttpRuleCondition) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Condition != nil { toSerialize["condition"] = o.Condition } + + if o.Key != nil { + toSerialize["key"] = o.Key + } + if o.Negate != nil { toSerialize["negate"] = o.Negate } - if o.Key != nil { - toSerialize["key"] = o.Key + + if o.Type != nil { + toSerialize["type"] = o.Type } + if o.Value != nil { toSerialize["value"] = o.Value } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go index 5055570bd..8c62ecc10 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go @@ -16,27 +16,27 @@ import ( // ApplicationLoadBalancerProperties struct for ApplicationLoadBalancerProperties type ApplicationLoadBalancerProperties struct { - // The Application Load Balancer name. - Name *string `json:"name"` - // The ID of the listening (inbound) LAN. - ListenerLan *int32 `json:"listenerLan"` // Collection of the Application Load Balancer IP addresses. (Inbound and outbound) IPs of the 'listenerLan' are customer-reserved public IPs for the public load balancers, and private IPs for the private load balancers. Ips *[]string `json:"ips,omitempty"` - // The ID of the balanced private target LAN (outbound). - TargetLan *int32 `json:"targetLan"` // Collection of private IP addresses with the subnet mask of the Application Load Balancer. IPs must contain valid a subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. LbPrivateIps *[]string `json:"lbPrivateIps,omitempty"` + // The ID of the listening (inbound) LAN. + ListenerLan *int32 `json:"listenerLan"` + // The Application Load Balancer name. + Name *string `json:"name"` + // The ID of the balanced private target LAN (outbound). + TargetLan *int32 `json:"targetLan"` } // NewApplicationLoadBalancerProperties instantiates a new ApplicationLoadBalancerProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewApplicationLoadBalancerProperties(name string, listenerLan int32, targetLan int32) *ApplicationLoadBalancerProperties { +func NewApplicationLoadBalancerProperties(listenerLan int32, name string, targetLan int32) *ApplicationLoadBalancerProperties { this := ApplicationLoadBalancerProperties{} - this.Name = &name this.ListenerLan = &listenerLan + this.Name = &name this.TargetLan = &targetLan return &this @@ -50,38 +50,76 @@ func NewApplicationLoadBalancerPropertiesWithDefaults() *ApplicationLoadBalancer return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerProperties) GetName() *string { +// GetIps returns the Ips field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerProperties) GetIps() *[]string { if o == nil { return nil } - return o.Name + return o.Ips } -// GetNameOk returns a tuple with the Name field value +// GetIpsOk returns a tuple with the Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerProperties) GetNameOk() (*string, bool) { +func (o *ApplicationLoadBalancerProperties) GetIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Ips, true } -// SetName sets field value -func (o *ApplicationLoadBalancerProperties) SetName(v string) { +// SetIps sets field value +func (o *ApplicationLoadBalancerProperties) SetIps(v []string) { - o.Name = &v + o.Ips = &v } -// HasName returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasIps returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerProperties) HasIps() bool { + if o != nil && o.Ips != nil { + return true + } + + return false +} + +// GetLbPrivateIps returns the LbPrivateIps field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerProperties) GetLbPrivateIps() *[]string { + if o == nil { + return nil + } + + return o.LbPrivateIps + +} + +// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *ApplicationLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { + if o == nil { + return nil, false + } + + return o.LbPrivateIps, true +} + +// SetLbPrivateIps sets field value +func (o *ApplicationLoadBalancerProperties) SetLbPrivateIps(v []string) { + + o.LbPrivateIps = &v + +} + +// HasLbPrivateIps returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerProperties) HasLbPrivateIps() bool { + if o != nil && o.LbPrivateIps != nil { return true } @@ -89,7 +127,7 @@ func (o *ApplicationLoadBalancerProperties) HasName() bool { } // GetListenerLan returns the ListenerLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerProperties) GetListenerLan() *int32 { if o == nil { return nil @@ -126,38 +164,38 @@ func (o *ApplicationLoadBalancerProperties) HasListenerLan() bool { return false } -// GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ApplicationLoadBalancerProperties) GetIps() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerProperties) GetName() *string { if o == nil { return nil } - return o.Ips + return o.Name } -// GetIpsOk returns a tuple with the Ips field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerProperties) GetIpsOk() (*[]string, bool) { +func (o *ApplicationLoadBalancerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Ips, true + return o.Name, true } -// SetIps sets field value -func (o *ApplicationLoadBalancerProperties) SetIps(v []string) { +// SetName sets field value +func (o *ApplicationLoadBalancerProperties) SetName(v string) { - o.Ips = &v + o.Name = &v } -// HasIps returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerProperties) HasIps() bool { - if o != nil && o.Ips != nil { +// HasName returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -165,7 +203,7 @@ func (o *ApplicationLoadBalancerProperties) HasIps() bool { } // GetTargetLan returns the TargetLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerProperties) GetTargetLan() *int32 { if o == nil { return nil @@ -202,61 +240,28 @@ func (o *ApplicationLoadBalancerProperties) HasTargetLan() bool { return false } -// GetLbPrivateIps returns the LbPrivateIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ApplicationLoadBalancerProperties) GetLbPrivateIps() *[]string { - if o == nil { - return nil +func (o ApplicationLoadBalancerProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.Ips != nil { + toSerialize["ips"] = o.Ips } - return o.LbPrivateIps - -} - -// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { - if o == nil { - return nil, false + if o.LbPrivateIps != nil { + toSerialize["lbPrivateIps"] = o.LbPrivateIps } - return o.LbPrivateIps, true -} - -// SetLbPrivateIps sets field value -func (o *ApplicationLoadBalancerProperties) SetLbPrivateIps(v []string) { - - o.LbPrivateIps = &v - -} - -// HasLbPrivateIps returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerProperties) HasLbPrivateIps() bool { - if o != nil && o.LbPrivateIps != nil { - return true + if o.ListenerLan != nil { + toSerialize["listenerLan"] = o.ListenerLan } - return false -} - -func (o ApplicationLoadBalancerProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} if o.Name != nil { toSerialize["name"] = o.Name } - if o.ListenerLan != nil { - toSerialize["listenerLan"] = o.ListenerLan - } - if o.Ips != nil { - toSerialize["ips"] = o.Ips - } + if o.TargetLan != nil { toSerialize["targetLan"] = o.TargetLan } - if o.LbPrivateIps != nil { - toSerialize["lbPrivateIps"] = o.LbPrivateIps - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go index ce188b2d8..79a5fa1c7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go @@ -16,13 +16,13 @@ import ( // ApplicationLoadBalancerPut struct for ApplicationLoadBalancerPut type ApplicationLoadBalancerPut struct { + // The URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *ApplicationLoadBalancerProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *ApplicationLoadBalancerProperties `json:"properties"` } // NewApplicationLoadBalancerPut instantiates a new ApplicationLoadBalancerPut object @@ -45,152 +45,152 @@ func NewApplicationLoadBalancerPutWithDefaults() *ApplicationLoadBalancerPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ApplicationLoadBalancerPut) SetId(v string) { +// SetHref sets field value +func (o *ApplicationLoadBalancerPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ApplicationLoadBalancerPut) SetType(v Type) { +// SetId sets field value +func (o *ApplicationLoadBalancerPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetProperties() *ApplicationLoadBalancerProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerPut) GetPropertiesOk() (*ApplicationLoadBalancerProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerPut) SetHref(v string) { +// SetProperties sets field value +func (o *ApplicationLoadBalancerPut) SetProperties(v ApplicationLoadBalancerProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerProperties will be returned -func (o *ApplicationLoadBalancerPut) GetProperties() *ApplicationLoadBalancerProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetPropertiesOk() (*ApplicationLoadBalancerProperties, bool) { +func (o *ApplicationLoadBalancerPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *ApplicationLoadBalancerPut) SetProperties(v ApplicationLoadBalancerProperties) { +// SetType sets field value +func (o *ApplicationLoadBalancerPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *ApplicationLoadBalancerPut) HasProperties() bool { func (o ApplicationLoadBalancerPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go index a3eff3d6a..a2f3a9e04 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go @@ -16,19 +16,19 @@ import ( // ApplicationLoadBalancers struct for ApplicationLoadBalancers type ApplicationLoadBalancers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]ApplicationLoadBalancer `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancers instantiates a new ApplicationLoadBalancers object @@ -49,114 +49,114 @@ func NewApplicationLoadBalancersWithDefaults() *ApplicationLoadBalancers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *ApplicationLoadBalancers) SetId(v string) { +// SetLinks sets field value +func (o *ApplicationLoadBalancers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *ApplicationLoadBalancers) SetType(v Type) { +// SetHref sets field value +func (o *ApplicationLoadBalancers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *ApplicationLoadBalancers) SetHref(v string) { +// SetId sets field value +func (o *ApplicationLoadBalancers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *ApplicationLoadBalancers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancer will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancers) GetItems() *[]ApplicationLoadBalancer { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *ApplicationLoadBalancers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetOffsetOk() (*float32, bool) { +func (o *ApplicationLoadBalancers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *ApplicationLoadBalancers) SetOffset(v float32) { +// SetLimit sets field value +func (o *ApplicationLoadBalancers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetLimitOk() (*float32, bool) { +func (o *ApplicationLoadBalancers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *ApplicationLoadBalancers) SetLimit(v float32) { +// SetOffset sets field value +func (o *ApplicationLoadBalancers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *ApplicationLoadBalancers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { +func (o *ApplicationLoadBalancers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *ApplicationLoadBalancers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *ApplicationLoadBalancers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *ApplicationLoadBalancers) HasLinks() bool { func (o ApplicationLoadBalancers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go index 3791f488e..fdd81e425 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go @@ -16,19 +16,19 @@ import ( // AttachedVolumes struct for AttachedVolumes type AttachedVolumes struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Volume `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewAttachedVolumes instantiates a new AttachedVolumes object @@ -49,114 +49,114 @@ func NewAttachedVolumesWithDefaults() *AttachedVolumes { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *AttachedVolumes) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetIdOk() (*string, bool) { +func (o *AttachedVolumes) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *AttachedVolumes) SetId(v string) { +// SetLinks sets field value +func (o *AttachedVolumes) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *AttachedVolumes) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *AttachedVolumes) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *AttachedVolumes) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetTypeOk() (*Type, bool) { +func (o *AttachedVolumes) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *AttachedVolumes) SetType(v Type) { +// SetHref sets field value +func (o *AttachedVolumes) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *AttachedVolumes) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *AttachedVolumes) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *AttachedVolumes) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetHrefOk() (*string, bool) { +func (o *AttachedVolumes) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *AttachedVolumes) SetHref(v string) { +// SetId sets field value +func (o *AttachedVolumes) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *AttachedVolumes) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *AttachedVolumes) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *AttachedVolumes) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Volume will be returned +// If the value is explicit nil, nil is returned func (o *AttachedVolumes) GetItems() *[]Volume { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *AttachedVolumes) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *AttachedVolumes) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetOffsetOk() (*float32, bool) { +func (o *AttachedVolumes) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *AttachedVolumes) SetOffset(v float32) { +// SetLimit sets field value +func (o *AttachedVolumes) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *AttachedVolumes) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *AttachedVolumes) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *AttachedVolumes) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetLimitOk() (*float32, bool) { +func (o *AttachedVolumes) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *AttachedVolumes) SetLimit(v float32) { +// SetOffset sets field value +func (o *AttachedVolumes) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *AttachedVolumes) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *AttachedVolumes) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *AttachedVolumes) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetLinksOk() (*PaginationLinks, bool) { +func (o *AttachedVolumes) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *AttachedVolumes) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *AttachedVolumes) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *AttachedVolumes) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *AttachedVolumes) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *AttachedVolumes) HasLinks() bool { func (o AttachedVolumes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go index bc9197db9..6f1ff7c47 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go @@ -16,14 +16,14 @@ import ( // BackupUnit struct for BackupUnit type BackupUnit struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *BackupUnitProperties `json:"properties"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewBackupUnit instantiates a new BackupUnit object @@ -46,190 +46,190 @@ func NewBackupUnitWithDefaults() *BackupUnit { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnit) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetIdOk() (*string, bool) { +func (o *BackupUnit) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *BackupUnit) SetId(v string) { +// SetHref sets field value +func (o *BackupUnit) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *BackupUnit) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *BackupUnit) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnit) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetTypeOk() (*string, bool) { +func (o *BackupUnit) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *BackupUnit) SetType(v string) { +// SetId sets field value +func (o *BackupUnit) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *BackupUnit) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *BackupUnit) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnit) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetHrefOk() (*string, bool) { +func (o *BackupUnit) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *BackupUnit) SetHref(v string) { +// SetMetadata sets field value +func (o *BackupUnit) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *BackupUnit) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *BackupUnit) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *BackupUnit) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetProperties() *BackupUnitProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *BackupUnit) GetPropertiesOk() (*BackupUnitProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *BackupUnit) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *BackupUnit) SetProperties(v BackupUnitProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *BackupUnit) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *BackupUnit) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for BackupUnitProperties will be returned -func (o *BackupUnit) GetProperties() *BackupUnitProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetPropertiesOk() (*BackupUnitProperties, bool) { +func (o *BackupUnit) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *BackupUnit) SetProperties(v BackupUnitProperties) { +// SetType sets field value +func (o *BackupUnit) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *BackupUnit) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *BackupUnit) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *BackupUnit) HasProperties() bool { func (o BackupUnit) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go index 45b5584e2..64698d356 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go @@ -16,12 +16,12 @@ import ( // BackupUnitProperties struct for BackupUnitProperties type BackupUnitProperties struct { + // The email associated with the backup unit. Bear in mind that this email does not be the same email as of the user. + Email *string `json:"email,omitempty"` // The name of the resource (alphanumeric characters only). Name *string `json:"name"` // The password associated with that resource. Password *string `json:"password,omitempty"` - // The email associated with the backup unit. Bear in mind that this email does not be the same email as of the user. - Email *string `json:"email,omitempty"` } // NewBackupUnitProperties instantiates a new BackupUnitProperties object @@ -44,114 +44,114 @@ func NewBackupUnitPropertiesWithDefaults() *BackupUnitProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnitProperties) GetName() *string { +// GetEmail returns the Email field value +// If the value is explicit nil, nil is returned +func (o *BackupUnitProperties) GetEmail() *string { if o == nil { return nil } - return o.Name + return o.Email } -// GetNameOk returns a tuple with the Name field value +// GetEmailOk returns a tuple with the Email field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnitProperties) GetNameOk() (*string, bool) { +func (o *BackupUnitProperties) GetEmailOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Email, true } -// SetName sets field value -func (o *BackupUnitProperties) SetName(v string) { +// SetEmail sets field value +func (o *BackupUnitProperties) SetEmail(v string) { - o.Name = &v + o.Email = &v } -// HasName returns a boolean if a field has been set. -func (o *BackupUnitProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasEmail returns a boolean if a field has been set. +func (o *BackupUnitProperties) HasEmail() bool { + if o != nil && o.Email != nil { return true } return false } -// GetPassword returns the Password field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnitProperties) GetPassword() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *BackupUnitProperties) GetName() *string { if o == nil { return nil } - return o.Password + return o.Name } -// GetPasswordOk returns a tuple with the Password field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnitProperties) GetPasswordOk() (*string, bool) { +func (o *BackupUnitProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Password, true + return o.Name, true } -// SetPassword sets field value -func (o *BackupUnitProperties) SetPassword(v string) { +// SetName sets field value +func (o *BackupUnitProperties) SetName(v string) { - o.Password = &v + o.Name = &v } -// HasPassword returns a boolean if a field has been set. -func (o *BackupUnitProperties) HasPassword() bool { - if o != nil && o.Password != nil { +// HasName returns a boolean if a field has been set. +func (o *BackupUnitProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnitProperties) GetEmail() *string { +// GetPassword returns the Password field value +// If the value is explicit nil, nil is returned +func (o *BackupUnitProperties) GetPassword() *string { if o == nil { return nil } - return o.Email + return o.Password } -// GetEmailOk returns a tuple with the Email field value +// GetPasswordOk returns a tuple with the Password field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnitProperties) GetEmailOk() (*string, bool) { +func (o *BackupUnitProperties) GetPasswordOk() (*string, bool) { if o == nil { return nil, false } - return o.Email, true + return o.Password, true } -// SetEmail sets field value -func (o *BackupUnitProperties) SetEmail(v string) { +// SetPassword sets field value +func (o *BackupUnitProperties) SetPassword(v string) { - o.Email = &v + o.Password = &v } -// HasEmail returns a boolean if a field has been set. -func (o *BackupUnitProperties) HasEmail() bool { - if o != nil && o.Email != nil { +// HasPassword returns a boolean if a field has been set. +func (o *BackupUnitProperties) HasPassword() bool { + if o != nil && o.Password != nil { return true } @@ -160,15 +160,18 @@ func (o *BackupUnitProperties) HasEmail() bool { func (o BackupUnitProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Email != nil { + toSerialize["email"] = o.Email + } + if o.Name != nil { toSerialize["name"] = o.Name } + if o.Password != nil { toSerialize["password"] = o.Password } - if o.Email != nil { - toSerialize["email"] = o.Email - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go index f493bf950..ea6ba4159 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go @@ -39,7 +39,7 @@ func NewBackupUnitSSOWithDefaults() *BackupUnitSSO { } // GetSsoUrl returns the SsoUrl field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *BackupUnitSSO) GetSsoUrl() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o BackupUnitSSO) MarshalJSON() ([]byte, error) { if o.SsoUrl != nil { toSerialize["ssoUrl"] = o.SsoUrl } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go index 6023f94e1..280d50c61 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go @@ -16,14 +16,14 @@ import ( // BackupUnits struct for BackupUnits type BackupUnits struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]BackupUnit `json:"items,omitempty"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewBackupUnits instantiates a new BackupUnits object @@ -44,152 +44,152 @@ func NewBackupUnitsWithDefaults() *BackupUnits { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnits) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetIdOk() (*string, bool) { +func (o *BackupUnits) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *BackupUnits) SetId(v string) { +// SetHref sets field value +func (o *BackupUnits) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *BackupUnits) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *BackupUnits) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnits) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetTypeOk() (*string, bool) { +func (o *BackupUnits) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *BackupUnits) SetType(v string) { +// SetId sets field value +func (o *BackupUnits) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *BackupUnits) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *BackupUnits) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnits) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetItems() *[]BackupUnit { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetHrefOk() (*string, bool) { +func (o *BackupUnits) GetItemsOk() (*[]BackupUnit, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *BackupUnits) SetHref(v string) { +// SetItems sets field value +func (o *BackupUnits) SetItems(v []BackupUnit) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *BackupUnits) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *BackupUnits) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []BackupUnit will be returned -func (o *BackupUnits) GetItems() *[]BackupUnit { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetItemsOk() (*[]BackupUnit, bool) { +func (o *BackupUnits) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *BackupUnits) SetItems(v []BackupUnit) { +// SetType sets field value +func (o *BackupUnits) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *BackupUnits) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *BackupUnits) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *BackupUnits) HasItems() bool { func (o BackupUnits) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go index feef17f62..f9338b578 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go @@ -16,19 +16,19 @@ import ( // BalancedNics struct for BalancedNics type BalancedNics struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Nic `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewBalancedNics instantiates a new BalancedNics object @@ -49,114 +49,114 @@ func NewBalancedNicsWithDefaults() *BalancedNics { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BalancedNics) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetIdOk() (*string, bool) { +func (o *BalancedNics) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *BalancedNics) SetId(v string) { +// SetLinks sets field value +func (o *BalancedNics) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *BalancedNics) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *BalancedNics) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *BalancedNics) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetTypeOk() (*Type, bool) { +func (o *BalancedNics) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *BalancedNics) SetType(v Type) { +// SetHref sets field value +func (o *BalancedNics) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *BalancedNics) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *BalancedNics) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BalancedNics) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetHrefOk() (*string, bool) { +func (o *BalancedNics) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *BalancedNics) SetHref(v string) { +// SetId sets field value +func (o *BalancedNics) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *BalancedNics) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *BalancedNics) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *BalancedNics) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Nic will be returned +// If the value is explicit nil, nil is returned func (o *BalancedNics) GetItems() *[]Nic { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *BalancedNics) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *BalancedNics) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetOffsetOk() (*float32, bool) { +func (o *BalancedNics) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *BalancedNics) SetOffset(v float32) { +// SetLimit sets field value +func (o *BalancedNics) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *BalancedNics) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *BalancedNics) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *BalancedNics) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetLimitOk() (*float32, bool) { +func (o *BalancedNics) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *BalancedNics) SetLimit(v float32) { +// SetOffset sets field value +func (o *BalancedNics) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *BalancedNics) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *BalancedNics) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *BalancedNics) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetLinksOk() (*PaginationLinks, bool) { +func (o *BalancedNics) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *BalancedNics) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *BalancedNics) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *BalancedNics) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *BalancedNics) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *BalancedNics) HasLinks() bool { func (o BalancedNics) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go index 4d2bb9a85..86289fa1d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go @@ -16,19 +16,19 @@ import ( // Cdroms struct for Cdroms type Cdroms struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Image `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewCdroms instantiates a new Cdroms object @@ -49,114 +49,114 @@ func NewCdromsWithDefaults() *Cdroms { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Cdroms) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetIdOk() (*string, bool) { +func (o *Cdroms) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Cdroms) SetId(v string) { +// SetLinks sets field value +func (o *Cdroms) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Cdroms) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Cdroms) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Cdroms) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetTypeOk() (*Type, bool) { +func (o *Cdroms) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Cdroms) SetType(v Type) { +// SetHref sets field value +func (o *Cdroms) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Cdroms) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Cdroms) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Cdroms) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetHrefOk() (*string, bool) { +func (o *Cdroms) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Cdroms) SetHref(v string) { +// SetId sets field value +func (o *Cdroms) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Cdroms) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Cdroms) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Cdroms) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Image will be returned +// If the value is explicit nil, nil is returned func (o *Cdroms) GetItems() *[]Image { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Cdroms) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Cdroms) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetOffsetOk() (*float32, bool) { +func (o *Cdroms) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Cdroms) SetOffset(v float32) { +// SetLimit sets field value +func (o *Cdroms) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Cdroms) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Cdroms) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Cdroms) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetLimitOk() (*float32, bool) { +func (o *Cdroms) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Cdroms) SetLimit(v float32) { +// SetOffset sets field value +func (o *Cdroms) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Cdroms) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Cdroms) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Cdroms) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetLinksOk() (*PaginationLinks, bool) { +func (o *Cdroms) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Cdroms) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Cdroms) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Cdroms) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Cdroms) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Cdroms) HasLinks() bool { func (o Cdroms) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go index 6b8a5f4cd..778a5bdd0 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go @@ -17,8 +17,8 @@ import ( // ConnectableDatacenter struct for ConnectableDatacenter type ConnectableDatacenter struct { Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` } // NewConnectableDatacenter instantiates a new ConnectableDatacenter object @@ -40,7 +40,7 @@ func NewConnectableDatacenterWithDefaults() *ConnectableDatacenter { } // GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ConnectableDatacenter) GetId() *string { if o == nil { return nil @@ -77,76 +77,76 @@ func (o *ConnectableDatacenter) HasId() bool { return false } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ConnectableDatacenter) GetName() *string { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *ConnectableDatacenter) GetLocation() *string { if o == nil { return nil } - return o.Name + return o.Location } -// GetNameOk returns a tuple with the Name field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ConnectableDatacenter) GetNameOk() (*string, bool) { +func (o *ConnectableDatacenter) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Location, true } -// SetName sets field value -func (o *ConnectableDatacenter) SetName(v string) { +// SetLocation sets field value +func (o *ConnectableDatacenter) SetLocation(v string) { - o.Name = &v + o.Location = &v } -// HasName returns a boolean if a field has been set. -func (o *ConnectableDatacenter) HasName() bool { - if o != nil && o.Name != nil { +// HasLocation returns a boolean if a field has been set. +func (o *ConnectableDatacenter) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ConnectableDatacenter) GetLocation() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ConnectableDatacenter) GetName() *string { if o == nil { return nil } - return o.Location + return o.Name } -// GetLocationOk returns a tuple with the Location field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ConnectableDatacenter) GetLocationOk() (*string, bool) { +func (o *ConnectableDatacenter) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Name, true } -// SetLocation sets field value -func (o *ConnectableDatacenter) SetLocation(v string) { +// SetName sets field value +func (o *ConnectableDatacenter) SetName(v string) { - o.Location = &v + o.Name = &v } -// HasLocation returns a boolean if a field has been set. -func (o *ConnectableDatacenter) HasLocation() bool { - if o != nil && o.Location != nil { +// HasName returns a boolean if a field has been set. +func (o *ConnectableDatacenter) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -158,12 +158,15 @@ func (o ConnectableDatacenter) MarshalJSON() ([]byte, error) { if o.Id != nil { toSerialize["id"] = o.Id } - if o.Name != nil { - toSerialize["name"] = o.Name - } + if o.Location != nil { toSerialize["location"] = o.Location } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go index e1e05792e..d3ce413e1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go @@ -16,9 +16,9 @@ import ( // Contract struct for Contract type Contract struct { - // The type of the resource. - Type *Type `json:"type,omitempty"` Properties *ContractProperties `json:"properties"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewContract instantiates a new Contract object @@ -41,76 +41,76 @@ func NewContractWithDefaults() *Contract { return &this } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Contract) GetType() *Type { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Contract) GetProperties() *ContractProperties { if o == nil { return nil } - return o.Type + return o.Properties } -// GetTypeOk returns a tuple with the Type field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contract) GetTypeOk() (*Type, bool) { +func (o *Contract) GetPropertiesOk() (*ContractProperties, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Properties, true } -// SetType sets field value -func (o *Contract) SetType(v Type) { +// SetProperties sets field value +func (o *Contract) SetProperties(v ContractProperties) { - o.Type = &v + o.Properties = &v } -// HasType returns a boolean if a field has been set. -func (o *Contract) HasType() bool { - if o != nil && o.Type != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Contract) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ContractProperties will be returned -func (o *Contract) GetProperties() *ContractProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Contract) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contract) GetPropertiesOk() (*ContractProperties, bool) { +func (o *Contract) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Contract) SetProperties(v ContractProperties) { +// SetType sets field value +func (o *Contract) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Contract) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Contract) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -119,12 +119,14 @@ func (o *Contract) HasProperties() bool { func (o Contract) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go index 522f61829..a579ea3b7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go @@ -20,11 +20,11 @@ type ContractProperties struct { ContractNumber *int64 `json:"contractNumber,omitempty"` // The contract owner's user name. Owner *string `json:"owner,omitempty"` - // The contract status. - Status *string `json:"status,omitempty"` // The registration domain of the contract. RegDomain *string `json:"regDomain,omitempty"` ResourceLimits *ResourceLimits `json:"resourceLimits,omitempty"` + // The contract status. + Status *string `json:"status,omitempty"` } // NewContractProperties instantiates a new ContractProperties object @@ -46,7 +46,7 @@ func NewContractPropertiesWithDefaults() *ContractProperties { } // GetContractNumber returns the ContractNumber field value -// If the value is explicit nil, the zero value for int64 will be returned +// If the value is explicit nil, nil is returned func (o *ContractProperties) GetContractNumber() *int64 { if o == nil { return nil @@ -84,7 +84,7 @@ func (o *ContractProperties) HasContractNumber() bool { } // GetOwner returns the Owner field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ContractProperties) GetOwner() *string { if o == nil { return nil @@ -121,114 +121,114 @@ func (o *ContractProperties) HasOwner() bool { return false } -// GetStatus returns the Status field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ContractProperties) GetStatus() *string { +// GetRegDomain returns the RegDomain field value +// If the value is explicit nil, nil is returned +func (o *ContractProperties) GetRegDomain() *string { if o == nil { return nil } - return o.Status + return o.RegDomain } -// GetStatusOk returns a tuple with the Status field value +// GetRegDomainOk returns a tuple with the RegDomain field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ContractProperties) GetStatusOk() (*string, bool) { +func (o *ContractProperties) GetRegDomainOk() (*string, bool) { if o == nil { return nil, false } - return o.Status, true + return o.RegDomain, true } -// SetStatus sets field value -func (o *ContractProperties) SetStatus(v string) { +// SetRegDomain sets field value +func (o *ContractProperties) SetRegDomain(v string) { - o.Status = &v + o.RegDomain = &v } -// HasStatus returns a boolean if a field has been set. -func (o *ContractProperties) HasStatus() bool { - if o != nil && o.Status != nil { +// HasRegDomain returns a boolean if a field has been set. +func (o *ContractProperties) HasRegDomain() bool { + if o != nil && o.RegDomain != nil { return true } return false } -// GetRegDomain returns the RegDomain field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ContractProperties) GetRegDomain() *string { +// GetResourceLimits returns the ResourceLimits field value +// If the value is explicit nil, nil is returned +func (o *ContractProperties) GetResourceLimits() *ResourceLimits { if o == nil { return nil } - return o.RegDomain + return o.ResourceLimits } -// GetRegDomainOk returns a tuple with the RegDomain field value +// GetResourceLimitsOk returns a tuple with the ResourceLimits field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ContractProperties) GetRegDomainOk() (*string, bool) { +func (o *ContractProperties) GetResourceLimitsOk() (*ResourceLimits, bool) { if o == nil { return nil, false } - return o.RegDomain, true + return o.ResourceLimits, true } -// SetRegDomain sets field value -func (o *ContractProperties) SetRegDomain(v string) { +// SetResourceLimits sets field value +func (o *ContractProperties) SetResourceLimits(v ResourceLimits) { - o.RegDomain = &v + o.ResourceLimits = &v } -// HasRegDomain returns a boolean if a field has been set. -func (o *ContractProperties) HasRegDomain() bool { - if o != nil && o.RegDomain != nil { +// HasResourceLimits returns a boolean if a field has been set. +func (o *ContractProperties) HasResourceLimits() bool { + if o != nil && o.ResourceLimits != nil { return true } return false } -// GetResourceLimits returns the ResourceLimits field value -// If the value is explicit nil, the zero value for ResourceLimits will be returned -func (o *ContractProperties) GetResourceLimits() *ResourceLimits { +// GetStatus returns the Status field value +// If the value is explicit nil, nil is returned +func (o *ContractProperties) GetStatus() *string { if o == nil { return nil } - return o.ResourceLimits + return o.Status } -// GetResourceLimitsOk returns a tuple with the ResourceLimits field value +// GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ContractProperties) GetResourceLimitsOk() (*ResourceLimits, bool) { +func (o *ContractProperties) GetStatusOk() (*string, bool) { if o == nil { return nil, false } - return o.ResourceLimits, true + return o.Status, true } -// SetResourceLimits sets field value -func (o *ContractProperties) SetResourceLimits(v ResourceLimits) { +// SetStatus sets field value +func (o *ContractProperties) SetStatus(v string) { - o.ResourceLimits = &v + o.Status = &v } -// HasResourceLimits returns a boolean if a field has been set. -func (o *ContractProperties) HasResourceLimits() bool { - if o != nil && o.ResourceLimits != nil { +// HasStatus returns a boolean if a field has been set. +func (o *ContractProperties) HasStatus() bool { + if o != nil && o.Status != nil { return true } @@ -240,18 +240,23 @@ func (o ContractProperties) MarshalJSON() ([]byte, error) { if o.ContractNumber != nil { toSerialize["contractNumber"] = o.ContractNumber } + if o.Owner != nil { toSerialize["owner"] = o.Owner } - if o.Status != nil { - toSerialize["status"] = o.Status - } + if o.RegDomain != nil { toSerialize["regDomain"] = o.RegDomain } + if o.ResourceLimits != nil { toSerialize["resourceLimits"] = o.ResourceLimits } + + if o.Status != nil { + toSerialize["status"] = o.Status + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go index c6fc46e31..61e2f9aa9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go @@ -16,14 +16,14 @@ import ( // Contracts struct for Contracts type Contracts struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Contract `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewContracts instantiates a new Contracts object @@ -44,152 +44,152 @@ func NewContractsWithDefaults() *Contracts { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Contracts) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetIdOk() (*string, bool) { +func (o *Contracts) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Contracts) SetId(v string) { +// SetHref sets field value +func (o *Contracts) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Contracts) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Contracts) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Contracts) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetTypeOk() (*Type, bool) { +func (o *Contracts) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Contracts) SetType(v Type) { +// SetId sets field value +func (o *Contracts) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Contracts) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Contracts) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Contracts) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetItems() *[]Contract { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetHrefOk() (*string, bool) { +func (o *Contracts) GetItemsOk() (*[]Contract, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Contracts) SetHref(v string) { +// SetItems sets field value +func (o *Contracts) SetItems(v []Contract) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Contracts) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Contracts) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Contract will be returned -func (o *Contracts) GetItems() *[]Contract { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetItemsOk() (*[]Contract, bool) { +func (o *Contracts) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Contracts) SetItems(v []Contract) { +// SetType sets field value +func (o *Contracts) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Contracts) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Contracts) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Contracts) HasItems() bool { func (o Contracts) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go index 80c6b6c24..c86a3899d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go @@ -45,7 +45,7 @@ func NewCpuArchitecturePropertiesWithDefaults() *CpuArchitectureProperties { } // GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetCpuFamily() *string { if o == nil { return nil @@ -83,7 +83,7 @@ func (o *CpuArchitectureProperties) HasCpuFamily() bool { } // GetMaxCores returns the MaxCores field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetMaxCores() *int32 { if o == nil { return nil @@ -121,7 +121,7 @@ func (o *CpuArchitectureProperties) HasMaxCores() bool { } // GetMaxRam returns the MaxRam field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetMaxRam() *int32 { if o == nil { return nil @@ -159,7 +159,7 @@ func (o *CpuArchitectureProperties) HasMaxRam() bool { } // GetVendor returns the Vendor field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetVendor() *string { if o == nil { return nil @@ -201,15 +201,19 @@ func (o CpuArchitectureProperties) MarshalJSON() ([]byte, error) { if o.CpuFamily != nil { toSerialize["cpuFamily"] = o.CpuFamily } + if o.MaxCores != nil { toSerialize["maxCores"] = o.MaxCores } + if o.MaxRam != nil { toSerialize["maxRam"] = o.MaxRam } + if o.Vendor != nil { toSerialize["vendor"] = o.Vendor } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go index 65fa3ee3d..2ac821f85 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go @@ -16,12 +16,12 @@ import ( // DataCenterEntities struct for DataCenterEntities type DataCenterEntities struct { - Servers *Servers `json:"servers,omitempty"` - Volumes *Volumes `json:"volumes,omitempty"` - Loadbalancers *Loadbalancers `json:"loadbalancers,omitempty"` Lans *Lans `json:"lans,omitempty"` - Networkloadbalancers *NetworkLoadBalancers `json:"networkloadbalancers,omitempty"` + Loadbalancers *Loadbalancers `json:"loadbalancers,omitempty"` Natgateways *NatGateways `json:"natgateways,omitempty"` + Networkloadbalancers *NetworkLoadBalancers `json:"networkloadbalancers,omitempty"` + Servers *Servers `json:"servers,omitempty"` + Volumes *Volumes `json:"volumes,omitempty"` } // NewDataCenterEntities instantiates a new DataCenterEntities object @@ -42,228 +42,228 @@ func NewDataCenterEntitiesWithDefaults() *DataCenterEntities { return &this } -// GetServers returns the Servers field value -// If the value is explicit nil, the zero value for Servers will be returned -func (o *DataCenterEntities) GetServers() *Servers { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetLans() *Lans { if o == nil { return nil } - return o.Servers + return o.Lans } -// GetServersOk returns a tuple with the Servers field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetServersOk() (*Servers, bool) { +func (o *DataCenterEntities) GetLansOk() (*Lans, bool) { if o == nil { return nil, false } - return o.Servers, true + return o.Lans, true } -// SetServers sets field value -func (o *DataCenterEntities) SetServers(v Servers) { +// SetLans sets field value +func (o *DataCenterEntities) SetLans(v Lans) { - o.Servers = &v + o.Lans = &v } -// HasServers returns a boolean if a field has been set. -func (o *DataCenterEntities) HasServers() bool { - if o != nil && o.Servers != nil { +// HasLans returns a boolean if a field has been set. +func (o *DataCenterEntities) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetVolumes returns the Volumes field value -// If the value is explicit nil, the zero value for Volumes will be returned -func (o *DataCenterEntities) GetVolumes() *Volumes { +// GetLoadbalancers returns the Loadbalancers field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetLoadbalancers() *Loadbalancers { if o == nil { return nil } - return o.Volumes + return o.Loadbalancers } -// GetVolumesOk returns a tuple with the Volumes field value +// GetLoadbalancersOk returns a tuple with the Loadbalancers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetVolumesOk() (*Volumes, bool) { +func (o *DataCenterEntities) GetLoadbalancersOk() (*Loadbalancers, bool) { if o == nil { return nil, false } - return o.Volumes, true + return o.Loadbalancers, true } -// SetVolumes sets field value -func (o *DataCenterEntities) SetVolumes(v Volumes) { +// SetLoadbalancers sets field value +func (o *DataCenterEntities) SetLoadbalancers(v Loadbalancers) { - o.Volumes = &v + o.Loadbalancers = &v } -// HasVolumes returns a boolean if a field has been set. -func (o *DataCenterEntities) HasVolumes() bool { - if o != nil && o.Volumes != nil { +// HasLoadbalancers returns a boolean if a field has been set. +func (o *DataCenterEntities) HasLoadbalancers() bool { + if o != nil && o.Loadbalancers != nil { return true } return false } -// GetLoadbalancers returns the Loadbalancers field value -// If the value is explicit nil, the zero value for Loadbalancers will be returned -func (o *DataCenterEntities) GetLoadbalancers() *Loadbalancers { +// GetNatgateways returns the Natgateways field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetNatgateways() *NatGateways { if o == nil { return nil } - return o.Loadbalancers + return o.Natgateways } -// GetLoadbalancersOk returns a tuple with the Loadbalancers field value +// GetNatgatewaysOk returns a tuple with the Natgateways field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetLoadbalancersOk() (*Loadbalancers, bool) { +func (o *DataCenterEntities) GetNatgatewaysOk() (*NatGateways, bool) { if o == nil { return nil, false } - return o.Loadbalancers, true + return o.Natgateways, true } -// SetLoadbalancers sets field value -func (o *DataCenterEntities) SetLoadbalancers(v Loadbalancers) { +// SetNatgateways sets field value +func (o *DataCenterEntities) SetNatgateways(v NatGateways) { - o.Loadbalancers = &v + o.Natgateways = &v } -// HasLoadbalancers returns a boolean if a field has been set. -func (o *DataCenterEntities) HasLoadbalancers() bool { - if o != nil && o.Loadbalancers != nil { +// HasNatgateways returns a boolean if a field has been set. +func (o *DataCenterEntities) HasNatgateways() bool { + if o != nil && o.Natgateways != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for Lans will be returned -func (o *DataCenterEntities) GetLans() *Lans { +// GetNetworkloadbalancers returns the Networkloadbalancers field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetNetworkloadbalancers() *NetworkLoadBalancers { if o == nil { return nil } - return o.Lans + return o.Networkloadbalancers } -// GetLansOk returns a tuple with the Lans field value +// GetNetworkloadbalancersOk returns a tuple with the Networkloadbalancers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetLansOk() (*Lans, bool) { +func (o *DataCenterEntities) GetNetworkloadbalancersOk() (*NetworkLoadBalancers, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.Networkloadbalancers, true } -// SetLans sets field value -func (o *DataCenterEntities) SetLans(v Lans) { +// SetNetworkloadbalancers sets field value +func (o *DataCenterEntities) SetNetworkloadbalancers(v NetworkLoadBalancers) { - o.Lans = &v + o.Networkloadbalancers = &v } -// HasLans returns a boolean if a field has been set. -func (o *DataCenterEntities) HasLans() bool { - if o != nil && o.Lans != nil { +// HasNetworkloadbalancers returns a boolean if a field has been set. +func (o *DataCenterEntities) HasNetworkloadbalancers() bool { + if o != nil && o.Networkloadbalancers != nil { return true } return false } -// GetNetworkloadbalancers returns the Networkloadbalancers field value -// If the value is explicit nil, the zero value for NetworkLoadBalancers will be returned -func (o *DataCenterEntities) GetNetworkloadbalancers() *NetworkLoadBalancers { +// GetServers returns the Servers field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetServers() *Servers { if o == nil { return nil } - return o.Networkloadbalancers + return o.Servers } -// GetNetworkloadbalancersOk returns a tuple with the Networkloadbalancers field value +// GetServersOk returns a tuple with the Servers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetNetworkloadbalancersOk() (*NetworkLoadBalancers, bool) { +func (o *DataCenterEntities) GetServersOk() (*Servers, bool) { if o == nil { return nil, false } - return o.Networkloadbalancers, true + return o.Servers, true } -// SetNetworkloadbalancers sets field value -func (o *DataCenterEntities) SetNetworkloadbalancers(v NetworkLoadBalancers) { +// SetServers sets field value +func (o *DataCenterEntities) SetServers(v Servers) { - o.Networkloadbalancers = &v + o.Servers = &v } -// HasNetworkloadbalancers returns a boolean if a field has been set. -func (o *DataCenterEntities) HasNetworkloadbalancers() bool { - if o != nil && o.Networkloadbalancers != nil { +// HasServers returns a boolean if a field has been set. +func (o *DataCenterEntities) HasServers() bool { + if o != nil && o.Servers != nil { return true } return false } -// GetNatgateways returns the Natgateways field value -// If the value is explicit nil, the zero value for NatGateways will be returned -func (o *DataCenterEntities) GetNatgateways() *NatGateways { +// GetVolumes returns the Volumes field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetVolumes() *Volumes { if o == nil { return nil } - return o.Natgateways + return o.Volumes } -// GetNatgatewaysOk returns a tuple with the Natgateways field value +// GetVolumesOk returns a tuple with the Volumes field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetNatgatewaysOk() (*NatGateways, bool) { +func (o *DataCenterEntities) GetVolumesOk() (*Volumes, bool) { if o == nil { return nil, false } - return o.Natgateways, true + return o.Volumes, true } -// SetNatgateways sets field value -func (o *DataCenterEntities) SetNatgateways(v NatGateways) { +// SetVolumes sets field value +func (o *DataCenterEntities) SetVolumes(v Volumes) { - o.Natgateways = &v + o.Volumes = &v } -// HasNatgateways returns a boolean if a field has been set. -func (o *DataCenterEntities) HasNatgateways() bool { - if o != nil && o.Natgateways != nil { +// HasVolumes returns a boolean if a field has been set. +func (o *DataCenterEntities) HasVolumes() bool { + if o != nil && o.Volumes != nil { return true } @@ -272,24 +272,30 @@ func (o *DataCenterEntities) HasNatgateways() bool { func (o DataCenterEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Servers != nil { - toSerialize["servers"] = o.Servers - } - if o.Volumes != nil { - toSerialize["volumes"] = o.Volumes + if o.Lans != nil { + toSerialize["lans"] = o.Lans } + if o.Loadbalancers != nil { toSerialize["loadbalancers"] = o.Loadbalancers } - if o.Lans != nil { - toSerialize["lans"] = o.Lans + + if o.Natgateways != nil { + toSerialize["natgateways"] = o.Natgateways } + if o.Networkloadbalancers != nil { toSerialize["networkloadbalancers"] = o.Networkloadbalancers } - if o.Natgateways != nil { - toSerialize["natgateways"] = o.Natgateways + + if o.Servers != nil { + toSerialize["servers"] = o.Servers } + + if o.Volumes != nil { + toSerialize["volumes"] = o.Volumes + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go index 45a4e9d7d..9b53f656c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go @@ -16,15 +16,15 @@ import ( // Datacenter struct for Datacenter type Datacenter struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *DataCenterEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *DatacenterProperties `json:"properties"` - Entities *DataCenterEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewDatacenter instantiates a new Datacenter object @@ -47,114 +47,114 @@ func NewDatacenterWithDefaults() *Datacenter { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenter) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetEntities() *DataCenterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetIdOk() (*string, bool) { +func (o *Datacenter) GetEntitiesOk() (*DataCenterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Datacenter) SetId(v string) { +// SetEntities sets field value +func (o *Datacenter) SetEntities(v DataCenterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Datacenter) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Datacenter) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Datacenter) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetTypeOk() (*Type, bool) { +func (o *Datacenter) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Datacenter) SetType(v Type) { +// SetHref sets field value +func (o *Datacenter) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Datacenter) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Datacenter) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenter) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetHrefOk() (*string, bool) { +func (o *Datacenter) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Datacenter) SetHref(v string) { +// SetId sets field value +func (o *Datacenter) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Datacenter) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Datacenter) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Datacenter) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Datacenter) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Datacenter) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for DatacenterProperties will be returned +// If the value is explicit nil, nil is returned func (o *Datacenter) GetProperties() *DatacenterProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Datacenter) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for DataCenterEntities will be returned -func (o *Datacenter) GetEntities() *DataCenterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetEntitiesOk() (*DataCenterEntities, bool) { +func (o *Datacenter) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Datacenter) SetEntities(v DataCenterEntities) { +// SetType sets field value +func (o *Datacenter) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Datacenter) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Datacenter) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Datacenter) HasEntities() bool { func (o Datacenter) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go index 3034ac67d..d0d262ff5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go @@ -17,20 +17,20 @@ import ( // DatacenterElementMetadata struct for DatacenterElementMetadata type DatacenterElementMetadata struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` - // The last time the resource was created. - CreatedDate *IonosTime // The user who created the resource. CreatedBy *string `json:"createdBy,omitempty"` // The unique ID of the user who created the resource. CreatedByUserId *string `json:"createdByUserId,omitempty"` - // The last time the resource was modified. - LastModifiedDate *IonosTime + // The last time the resource was created. + CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The user who last modified the resource. LastModifiedBy *string `json:"lastModifiedBy,omitempty"` // The unique ID of the user who last modified the resource. LastModifiedByUserId *string `json:"lastModifiedByUserId,omitempty"` + // The last time the resource was modified. + LastModifiedDate *IonosTime // State of the resource. *AVAILABLE* There are no pending modification requests for this item; *BUSY* There is at least one modification request pending and all following requests will be queued; *INACTIVE* Resource has been de-provisioned; *DEPLOYING* Resource state DEPLOYING - relevant for Kubernetes cluster/nodepool; *ACTIVE* Resource state ACTIVE - relevant for Kubernetes cluster/nodepool; *FAILED* Resource state FAILED - relevant for Kubernetes cluster/nodepool; *SUSPENDED* Resource state SUSPENDED - relevant for Kubernetes cluster/nodepool; *FAILED_SUSPENDED* Resource state FAILED_SUSPENDED - relevant for Kubernetes cluster; *UPDATING* Resource state UPDATING - relevant for Kubernetes cluster/nodepool; *FAILED_UPDATING* Resource state FAILED_UPDATING - relevant for Kubernetes cluster/nodepool; *DESTROYING* Resource state DESTROYING - relevant for Kubernetes cluster; *FAILED_DESTROYING* Resource state FAILED_DESTROYING - relevant for Kubernetes cluster/nodepool; *TERMINATED* Resource state TERMINATED - relevant for Kubernetes cluster/nodepool; *HIBERNATING* Resource state HIBERNATING - relevant for Kubernetes cluster/nodepool; *FAILED_HIBERNATING* Resource state FAILED_HIBERNATING - relevant for Kubernetes cluster/nodepool; *MAINTENANCE* Resource state MAINTENANCE - relevant for Kubernetes cluster/nodepool; *FAILED_HIBERNATING* Resource state FAILED_HIBERNATING - relevant for Kubernetes cluster/nodepool. State *string `json:"state,omitempty"` } @@ -53,91 +53,8 @@ func NewDatacenterElementMetadataWithDefaults() *DatacenterElementMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *DatacenterElementMetadata) GetEtag() *string { - if o == nil { - return nil - } - - return o.Etag - -} - -// GetEtagOk returns a tuple with the Etag field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterElementMetadata) GetEtagOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Etag, true -} - -// SetEtag sets field value -func (o *DatacenterElementMetadata) SetEtag(v string) { - - o.Etag = &v - -} - -// HasEtag returns a boolean if a field has been set. -func (o *DatacenterElementMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { - return true - } - - return false -} - -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *DatacenterElementMetadata) GetCreatedDate() *time.Time { - if o == nil { - return nil - } - - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time - -} - -// GetCreatedDateOk returns a tuple with the CreatedDate field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterElementMetadata) GetCreatedDateOk() (*time.Time, bool) { - if o == nil { - return nil, false - } - - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - -} - -// SetCreatedDate sets field value -func (o *DatacenterElementMetadata) SetCreatedDate(v time.Time) { - - o.CreatedDate = &IonosTime{v} - -} - -// HasCreatedDate returns a boolean if a field has been set. -func (o *DatacenterElementMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { - return true - } - - return false -} - // GetCreatedBy returns the CreatedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetCreatedBy() *string { if o == nil { return nil @@ -175,7 +92,7 @@ func (o *DatacenterElementMetadata) HasCreatedBy() bool { } // GetCreatedByUserId returns the CreatedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetCreatedByUserId() *string { if o == nil { return nil @@ -212,45 +129,83 @@ func (o *DatacenterElementMetadata) HasCreatedByUserId() bool { return false } -// GetLastModifiedDate returns the LastModifiedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *DatacenterElementMetadata) GetLastModifiedDate() *time.Time { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *DatacenterElementMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil } - return &o.LastModifiedDate.Time + return &o.CreatedDate.Time } -// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterElementMetadata) GetLastModifiedDateOk() (*time.Time, bool) { +func (o *DatacenterElementMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil, false } - return &o.LastModifiedDate.Time, true + return &o.CreatedDate.Time, true } -// SetLastModifiedDate sets field value -func (o *DatacenterElementMetadata) SetLastModifiedDate(v time.Time) { +// SetCreatedDate sets field value +func (o *DatacenterElementMetadata) SetCreatedDate(v time.Time) { - o.LastModifiedDate = &IonosTime{v} + o.CreatedDate = &IonosTime{v} } -// HasLastModifiedDate returns a boolean if a field has been set. -func (o *DatacenterElementMetadata) HasLastModifiedDate() bool { - if o != nil && o.LastModifiedDate != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *DatacenterElementMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { + return true + } + + return false +} + +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *DatacenterElementMetadata) GetEtag() *string { + if o == nil { + return nil + } + + return o.Etag + +} + +// GetEtagOk returns a tuple with the Etag field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *DatacenterElementMetadata) GetEtagOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Etag, true +} + +// SetEtag sets field value +func (o *DatacenterElementMetadata) SetEtag(v string) { + + o.Etag = &v + +} + +// HasEtag returns a boolean if a field has been set. +func (o *DatacenterElementMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -258,7 +213,7 @@ func (o *DatacenterElementMetadata) HasLastModifiedDate() bool { } // GetLastModifiedBy returns the LastModifiedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetLastModifiedBy() *string { if o == nil { return nil @@ -296,7 +251,7 @@ func (o *DatacenterElementMetadata) HasLastModifiedBy() bool { } // GetLastModifiedByUserId returns the LastModifiedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetLastModifiedByUserId() *string { if o == nil { return nil @@ -333,8 +288,53 @@ func (o *DatacenterElementMetadata) HasLastModifiedByUserId() bool { return false } +// GetLastModifiedDate returns the LastModifiedDate field value +// If the value is explicit nil, nil is returned +func (o *DatacenterElementMetadata) GetLastModifiedDate() *time.Time { + if o == nil { + return nil + } + + if o.LastModifiedDate == nil { + return nil + } + return &o.LastModifiedDate.Time + +} + +// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *DatacenterElementMetadata) GetLastModifiedDateOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + + if o.LastModifiedDate == nil { + return nil, false + } + return &o.LastModifiedDate.Time, true + +} + +// SetLastModifiedDate sets field value +func (o *DatacenterElementMetadata) SetLastModifiedDate(v time.Time) { + + o.LastModifiedDate = &IonosTime{v} + +} + +// HasLastModifiedDate returns a boolean if a field has been set. +func (o *DatacenterElementMetadata) HasLastModifiedDate() bool { + if o != nil && o.LastModifiedDate != nil { + return true + } + + return false +} + // GetState returns the State field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetState() *string { if o == nil { return nil @@ -373,30 +373,38 @@ func (o *DatacenterElementMetadata) HasState() bool { func (o DatacenterElementMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } - if o.CreatedDate != nil { - toSerialize["createdDate"] = o.CreatedDate - } if o.CreatedBy != nil { toSerialize["createdBy"] = o.CreatedBy } + if o.CreatedByUserId != nil { toSerialize["createdByUserId"] = o.CreatedByUserId } - if o.LastModifiedDate != nil { - toSerialize["lastModifiedDate"] = o.LastModifiedDate + + if o.CreatedDate != nil { + toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + if o.LastModifiedBy != nil { toSerialize["lastModifiedBy"] = o.LastModifiedBy } + if o.LastModifiedByUserId != nil { toSerialize["lastModifiedByUserId"] = o.LastModifiedByUserId } + + if o.LastModifiedDate != nil { + toSerialize["lastModifiedDate"] = o.LastModifiedDate + } + if o.State != nil { toSerialize["state"] = o.State } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go index 7ea457242..454fd4962 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go @@ -16,20 +16,23 @@ import ( // DatacenterProperties struct for DatacenterProperties type DatacenterProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` + // Array of features and CPU families available in a location + CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` // A description for the datacenter, such as staging, production. Description *string `json:"description,omitempty"` - // The physical location where the datacenter will be created. This will be where all of your servers live. Property cannot be modified after datacenter creation (disallowed in update requests). - Location *string `json:"location"` - // The version of the data center; incremented with every change. - Version *int32 `json:"version,omitempty"` // List of features supported by the location where this data center is provisioned. Features *[]string `json:"features,omitempty"` + // This value is either 'null' or contains an automatically-assigned /56 IPv6 CIDR block if IPv6 is enabled on this virtual data center. It can neither be changed nor removed. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpv6CidrBlockNil` + Ipv6CidrBlock *string `json:"ipv6CidrBlock,omitempty"` + // The physical location where the datacenter will be created. This will be where all of your servers live. Property cannot be modified after datacenter creation (disallowed in update requests). + Location *string `json:"location"` + // The name of the resource. + Name *string `json:"name,omitempty"` // Boolean value representing if the data center requires extra protection, such as two-step verification. SecAuthProtection *bool `json:"secAuthProtection,omitempty"` - // Array of features and CPU families available in a location - CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` + // The version of the data center; incremented with every change. + Version *int32 `json:"version,omitempty"` } // NewDatacenterProperties instantiates a new DatacenterProperties object @@ -52,38 +55,38 @@ func NewDatacenterPropertiesWithDefaults() *DatacenterProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *DatacenterProperties) GetName() *string { +// GetCpuArchitecture returns the CpuArchitecture field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { if o == nil { return nil } - return o.Name + return o.CpuArchitecture } -// GetNameOk returns a tuple with the Name field value +// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetNameOk() (*string, bool) { +func (o *DatacenterProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CpuArchitecture, true } -// SetName sets field value -func (o *DatacenterProperties) SetName(v string) { +// SetCpuArchitecture sets field value +func (o *DatacenterProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { - o.Name = &v + o.CpuArchitecture = &v } -// HasName returns a boolean if a field has been set. -func (o *DatacenterProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCpuArchitecture returns a boolean if a field has been set. +func (o *DatacenterProperties) HasCpuArchitecture() bool { + if o != nil && o.CpuArchitecture != nil { return true } @@ -91,7 +94,7 @@ func (o *DatacenterProperties) HasName() bool { } // GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterProperties) GetDescription() *string { if o == nil { return nil @@ -128,114 +131,157 @@ func (o *DatacenterProperties) HasDescription() bool { return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *DatacenterProperties) GetLocation() *string { +// GetFeatures returns the Features field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetFeatures() *[]string { if o == nil { return nil } - return o.Location + return o.Features } -// GetLocationOk returns a tuple with the Location field value +// GetFeaturesOk returns a tuple with the Features field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetLocationOk() (*string, bool) { +func (o *DatacenterProperties) GetFeaturesOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Features, true } -// SetLocation sets field value -func (o *DatacenterProperties) SetLocation(v string) { +// SetFeatures sets field value +func (o *DatacenterProperties) SetFeatures(v []string) { - o.Location = &v + o.Features = &v } -// HasLocation returns a boolean if a field has been set. -func (o *DatacenterProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasFeatures returns a boolean if a field has been set. +func (o *DatacenterProperties) HasFeatures() bool { + if o != nil && o.Features != nil { return true } return false } -// GetVersion returns the Version field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *DatacenterProperties) GetVersion() *int32 { +// GetIpv6CidrBlock returns the Ipv6CidrBlock field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetIpv6CidrBlock() *string { if o == nil { return nil } - return o.Version + return o.Ipv6CidrBlock } -// GetVersionOk returns a tuple with the Version field value +// GetIpv6CidrBlockOk returns a tuple with the Ipv6CidrBlock field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetVersionOk() (*int32, bool) { +func (o *DatacenterProperties) GetIpv6CidrBlockOk() (*string, bool) { if o == nil { return nil, false } - return o.Version, true + return o.Ipv6CidrBlock, true } -// SetVersion sets field value -func (o *DatacenterProperties) SetVersion(v int32) { +// SetIpv6CidrBlock sets field value +func (o *DatacenterProperties) SetIpv6CidrBlock(v string) { - o.Version = &v + o.Ipv6CidrBlock = &v } -// HasVersion returns a boolean if a field has been set. -func (o *DatacenterProperties) HasVersion() bool { - if o != nil && o.Version != nil { +// sets Ipv6CidrBlock to the explicit address that will be encoded as nil when marshaled +func (o *DatacenterProperties) SetIpv6CidrBlockNil() { + o.Ipv6CidrBlock = &Nilstring +} + +// HasIpv6CidrBlock returns a boolean if a field has been set. +func (o *DatacenterProperties) HasIpv6CidrBlock() bool { + if o != nil && o.Ipv6CidrBlock != nil { return true } return false } -// GetFeatures returns the Features field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *DatacenterProperties) GetFeatures() *[]string { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetLocation() *string { if o == nil { return nil } - return o.Features + return o.Location } -// GetFeaturesOk returns a tuple with the Features field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetFeaturesOk() (*[]string, bool) { +func (o *DatacenterProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.Features, true + return o.Location, true } -// SetFeatures sets field value -func (o *DatacenterProperties) SetFeatures(v []string) { +// SetLocation sets field value +func (o *DatacenterProperties) SetLocation(v string) { - o.Features = &v + o.Location = &v } -// HasFeatures returns a boolean if a field has been set. -func (o *DatacenterProperties) HasFeatures() bool { - if o != nil && o.Features != nil { +// HasLocation returns a boolean if a field has been set. +func (o *DatacenterProperties) HasLocation() bool { + if o != nil && o.Location != nil { + return true + } + + return false +} + +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetName() *string { + if o == nil { + return nil + } + + return o.Name + +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *DatacenterProperties) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Name, true +} + +// SetName sets field value +func (o *DatacenterProperties) SetName(v string) { + + o.Name = &v + +} + +// HasName returns a boolean if a field has been set. +func (o *DatacenterProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -243,7 +289,7 @@ func (o *DatacenterProperties) HasFeatures() bool { } // GetSecAuthProtection returns the SecAuthProtection field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterProperties) GetSecAuthProtection() *bool { if o == nil { return nil @@ -280,38 +326,38 @@ func (o *DatacenterProperties) HasSecAuthProtection() bool { return false } -// GetCpuArchitecture returns the CpuArchitecture field value -// If the value is explicit nil, the zero value for []CpuArchitectureProperties will be returned -func (o *DatacenterProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { +// GetVersion returns the Version field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetVersion() *int32 { if o == nil { return nil } - return o.CpuArchitecture + return o.Version } -// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value +// GetVersionOk returns a tuple with the Version field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { +func (o *DatacenterProperties) GetVersionOk() (*int32, bool) { if o == nil { return nil, false } - return o.CpuArchitecture, true + return o.Version, true } -// SetCpuArchitecture sets field value -func (o *DatacenterProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { +// SetVersion sets field value +func (o *DatacenterProperties) SetVersion(v int32) { - o.CpuArchitecture = &v + o.Version = &v } -// HasCpuArchitecture returns a boolean if a field has been set. -func (o *DatacenterProperties) HasCpuArchitecture() bool { - if o != nil && o.CpuArchitecture != nil { +// HasVersion returns a boolean if a field has been set. +func (o *DatacenterProperties) HasVersion() bool { + if o != nil && o.Version != nil { return true } @@ -320,27 +366,39 @@ func (o *DatacenterProperties) HasCpuArchitecture() bool { func (o DatacenterProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.CpuArchitecture != nil { + toSerialize["cpuArchitecture"] = o.CpuArchitecture } + if o.Description != nil { toSerialize["description"] = o.Description } + + if o.Features != nil { + toSerialize["features"] = o.Features + } + + if o.Ipv6CidrBlock == &Nilstring { + toSerialize["ipv6CidrBlock"] = nil + } else if o.Ipv6CidrBlock != nil { + toSerialize["ipv6CidrBlock"] = o.Ipv6CidrBlock + } if o.Location != nil { toSerialize["location"] = o.Location } - if o.Version != nil { - toSerialize["version"] = o.Version - } - if o.Features != nil { - toSerialize["features"] = o.Features + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.SecAuthProtection != nil { toSerialize["secAuthProtection"] = o.SecAuthProtection } - if o.CpuArchitecture != nil { - toSerialize["cpuArchitecture"] = o.CpuArchitecture + + if o.Version != nil { + toSerialize["version"] = o.Version } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go index 28911601f..43c00c3c7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go @@ -16,19 +16,19 @@ import ( // Datacenters struct for Datacenters type Datacenters struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Datacenter `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewDatacenters instantiates a new Datacenters object @@ -49,114 +49,114 @@ func NewDatacentersWithDefaults() *Datacenters { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenters) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetIdOk() (*string, bool) { +func (o *Datacenters) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Datacenters) SetId(v string) { +// SetLinks sets field value +func (o *Datacenters) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Datacenters) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Datacenters) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Datacenters) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetTypeOk() (*Type, bool) { +func (o *Datacenters) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Datacenters) SetType(v Type) { +// SetHref sets field value +func (o *Datacenters) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Datacenters) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Datacenters) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenters) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetHrefOk() (*string, bool) { +func (o *Datacenters) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Datacenters) SetHref(v string) { +// SetId sets field value +func (o *Datacenters) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Datacenters) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Datacenters) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Datacenters) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Datacenter will be returned +// If the value is explicit nil, nil is returned func (o *Datacenters) GetItems() *[]Datacenter { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Datacenters) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Datacenters) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetOffsetOk() (*float32, bool) { +func (o *Datacenters) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Datacenters) SetOffset(v float32) { +// SetLimit sets field value +func (o *Datacenters) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Datacenters) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Datacenters) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Datacenters) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetLimitOk() (*float32, bool) { +func (o *Datacenters) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Datacenters) SetLimit(v float32) { +// SetOffset sets field value +func (o *Datacenters) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Datacenters) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Datacenters) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Datacenters) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetLinksOk() (*PaginationLinks, bool) { +func (o *Datacenters) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Datacenters) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Datacenters) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Datacenters) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Datacenters) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Datacenters) HasLinks() bool { func (o Datacenters) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go index a383952b7..d5e52dd39 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go @@ -40,7 +40,7 @@ func NewErrorWithDefaults() *Error { } // GetHttpStatus returns the HttpStatus field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *Error) GetHttpStatus() *int32 { if o == nil { return nil @@ -78,7 +78,7 @@ func (o *Error) HasHttpStatus() bool { } // GetMessages returns the Messages field value -// If the value is explicit nil, the zero value for []ErrorMessage will be returned +// If the value is explicit nil, nil is returned func (o *Error) GetMessages() *[]ErrorMessage { if o == nil { return nil @@ -120,9 +120,11 @@ func (o Error) MarshalJSON() ([]byte, error) { if o.HttpStatus != nil { toSerialize["httpStatus"] = o.HttpStatus } + if o.Messages != nil { toSerialize["messages"] = o.Messages } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go index f3044d977..d567be376 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go @@ -41,7 +41,7 @@ func NewErrorMessageWithDefaults() *ErrorMessage { } // GetErrorCode returns the ErrorCode field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ErrorMessage) GetErrorCode() *string { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *ErrorMessage) HasErrorCode() bool { } // GetMessage returns the Message field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ErrorMessage) GetMessage() *string { if o == nil { return nil @@ -121,9 +121,11 @@ func (o ErrorMessage) MarshalJSON() ([]byte, error) { if o.ErrorCode != nil { toSerialize["errorCode"] = o.ErrorCode } + if o.Message != nil { toSerialize["message"] = o.Message } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go index 6b472e4e9..88f0f5ead 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go @@ -16,14 +16,14 @@ import ( // FirewallRule struct for FirewallRule type FirewallRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *FirewallruleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFirewallRule instantiates a new FirewallRule object @@ -46,190 +46,190 @@ func NewFirewallRuleWithDefaults() *FirewallRule { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetIdOk() (*string, bool) { +func (o *FirewallRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *FirewallRule) SetId(v string) { +// SetHref sets field value +func (o *FirewallRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *FirewallRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *FirewallRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FirewallRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetTypeOk() (*Type, bool) { +func (o *FirewallRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *FirewallRule) SetType(v Type) { +// SetId sets field value +func (o *FirewallRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *FirewallRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *FirewallRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetHrefOk() (*string, bool) { +func (o *FirewallRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *FirewallRule) SetHref(v string) { +// SetMetadata sets field value +func (o *FirewallRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *FirewallRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *FirewallRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *FirewallRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetProperties() *FirewallruleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *FirewallRule) GetPropertiesOk() (*FirewallruleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *FirewallRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *FirewallRule) SetProperties(v FirewallruleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *FirewallRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *FirewallRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for FirewallruleProperties will be returned -func (o *FirewallRule) GetProperties() *FirewallruleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetPropertiesOk() (*FirewallruleProperties, bool) { +func (o *FirewallRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *FirewallRule) SetProperties(v FirewallruleProperties) { +// SetType sets field value +func (o *FirewallRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *FirewallRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *FirewallRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *FirewallRule) HasProperties() bool { func (o FirewallRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go index f3b572931..5701dda12 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go @@ -16,19 +16,19 @@ import ( // FirewallRules struct for FirewallRules type FirewallRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]FirewallRule `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFirewallRules instantiates a new FirewallRules object @@ -49,114 +49,114 @@ func NewFirewallRulesWithDefaults() *FirewallRules { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRules) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetIdOk() (*string, bool) { +func (o *FirewallRules) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *FirewallRules) SetId(v string) { +// SetLinks sets field value +func (o *FirewallRules) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *FirewallRules) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *FirewallRules) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FirewallRules) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetTypeOk() (*Type, bool) { +func (o *FirewallRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *FirewallRules) SetType(v Type) { +// SetHref sets field value +func (o *FirewallRules) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *FirewallRules) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *FirewallRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRules) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetHrefOk() (*string, bool) { +func (o *FirewallRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *FirewallRules) SetHref(v string) { +// SetId sets field value +func (o *FirewallRules) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *FirewallRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *FirewallRules) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *FirewallRules) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []FirewallRule will be returned +// If the value is explicit nil, nil is returned func (o *FirewallRules) GetItems() *[]FirewallRule { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *FirewallRules) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FirewallRules) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetOffsetOk() (*float32, bool) { +func (o *FirewallRules) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *FirewallRules) SetOffset(v float32) { +// SetLimit sets field value +func (o *FirewallRules) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *FirewallRules) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *FirewallRules) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FirewallRules) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetLimitOk() (*float32, bool) { +func (o *FirewallRules) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *FirewallRules) SetLimit(v float32) { +// SetOffset sets field value +func (o *FirewallRules) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *FirewallRules) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *FirewallRules) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *FirewallRules) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetLinksOk() (*PaginationLinks, bool) { +func (o *FirewallRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *FirewallRules) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *FirewallRules) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *FirewallRules) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *FirewallRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *FirewallRules) HasLinks() bool { func (o FirewallRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go index 640cd23fb..0e5de49b3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go @@ -16,26 +16,32 @@ import ( // FirewallruleProperties struct for FirewallruleProperties type FirewallruleProperties struct { + // Defines the allowed code (from 0 to 254) if protocol ICMP or ICMPv6 is chosen. Value null allows all codes. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilint32` can be used, or the setter `SetIcmpCodeNil` + IcmpCode *int32 `json:"icmpCode,omitempty"` + // Defines the allowed type (from 0 to 254) if the protocol ICMP or ICMPv6 is chosen. Value null allows all types. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilint32` can be used, or the setter `SetIcmpTypeNil` + IcmpType *int32 `json:"icmpType,omitempty"` + // The IP version for this rule. If sourceIp or targetIp are specified, you can omit this value - the IP version will then be deduced from the IP address(es) used; if you specify it anyway, it must match the specified IP address(es). If neither sourceIp nor targetIp are specified, this rule allows traffic only for the specified IP version. If neither sourceIp, targetIp nor ipVersion are specified, this rule will only allow IPv4 traffic. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpVersionNil` + IpVersion *string `json:"ipVersion,omitempty"` // The name of the resource. Name *string `json:"name,omitempty"` + // Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd null to allow all ports. + PortRangeEnd *int32 `json:"portRangeEnd,omitempty"` + // Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd value null to allow all ports. + PortRangeStart *int32 `json:"portRangeStart,omitempty"` // The protocol for the rule. Property cannot be modified after it is created (disallowed in update requests). Protocol *string `json:"protocol"` - // Only traffic originating from the respective MAC address is allowed. Valid format: aa:bb:cc:dd:ee:ff. Value null allows traffic from any MAC address. - SourceMac *string `json:"sourceMac,omitempty"` - // The IP version for this rule. If sourceIp or targetIp are specified, you can omit this value - the IP version will then be deduced from the IP address(es) used; if you specify it anyway, it must match the specified IP address(es). If neither sourceIp nor targetIp are specified, this rule allows traffic only for the specified IP version. If neither sourceIp, targetIp nor ipVersion are specified, this rule will only allow IPv4 traffic. - IpVersion *string `json:"ipVersion,omitempty"` // Only traffic originating from the respective IP address (or CIDR block) is allowed. Value null allows traffic from any IP address (according to the selected ipVersion). + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetSourceIpNil` SourceIp *string `json:"sourceIp,omitempty"` + // Only traffic originating from the respective MAC address is allowed. Valid format: aa:bb:cc:dd:ee:ff. Value null allows traffic from any MAC address. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetSourceMacNil` + SourceMac *string `json:"sourceMac,omitempty"` // If the target NIC has multiple IP addresses, only the traffic directed to the respective IP address (or CIDR block) of the NIC is allowed. Value null allows traffic to any target IP address (according to the selected ipVersion). + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetTargetIpNil` TargetIp *string `json:"targetIp,omitempty"` - // Defines the allowed code (from 0 to 254) if protocol ICMP or ICMPv6 is chosen. Value null allows all codes. - IcmpCode *int32 `json:"icmpCode,omitempty"` - // Defines the allowed type (from 0 to 254) if the protocol ICMP or ICMPv6 is chosen. Value null allows all types. - IcmpType *int32 `json:"icmpType,omitempty"` - // Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd value null to allow all ports. - PortRangeStart *int32 `json:"portRangeStart,omitempty"` - // Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd null to allow all ports. - PortRangeEnd *int32 `json:"portRangeEnd,omitempty"` // The type of the firewall rule. If not specified, the default INGRESS value is used. Type *string `json:"type,omitempty"` } @@ -60,380 +66,410 @@ func NewFirewallrulePropertiesWithDefaults() *FirewallruleProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetName() *string { +// GetIcmpCode returns the IcmpCode field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetIcmpCode() *int32 { if o == nil { return nil } - return o.Name + return o.IcmpCode } -// GetNameOk returns a tuple with the Name field value +// GetIcmpCodeOk returns a tuple with the IcmpCode field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetNameOk() (*string, bool) { +func (o *FirewallruleProperties) GetIcmpCodeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.IcmpCode, true } -// SetName sets field value -func (o *FirewallruleProperties) SetName(v string) { +// SetIcmpCode sets field value +func (o *FirewallruleProperties) SetIcmpCode(v int32) { - o.Name = &v + o.IcmpCode = &v } -// HasName returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasName() bool { - if o != nil && o.Name != nil { +// sets IcmpCode to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetIcmpCodeNil() { + o.IcmpCode = &Nilint32 +} + +// HasIcmpCode returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasIcmpCode() bool { + if o != nil && o.IcmpCode != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetProtocol() *string { +// GetIcmpType returns the IcmpType field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetIcmpType() *int32 { if o == nil { return nil } - return o.Protocol + return o.IcmpType } -// GetProtocolOk returns a tuple with the Protocol field value +// GetIcmpTypeOk returns a tuple with the IcmpType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetProtocolOk() (*string, bool) { +func (o *FirewallruleProperties) GetIcmpTypeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.IcmpType, true } -// SetProtocol sets field value -func (o *FirewallruleProperties) SetProtocol(v string) { +// SetIcmpType sets field value +func (o *FirewallruleProperties) SetIcmpType(v int32) { - o.Protocol = &v + o.IcmpType = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// sets IcmpType to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetIcmpTypeNil() { + o.IcmpType = &Nilint32 +} + +// HasIcmpType returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasIcmpType() bool { + if o != nil && o.IcmpType != nil { return true } return false } -// GetSourceMac returns the SourceMac field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetSourceMac() *string { +// GetIpVersion returns the IpVersion field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetIpVersion() *string { if o == nil { return nil } - return o.SourceMac + return o.IpVersion } -// GetSourceMacOk returns a tuple with the SourceMac field value +// GetIpVersionOk returns a tuple with the IpVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetSourceMacOk() (*string, bool) { +func (o *FirewallruleProperties) GetIpVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.SourceMac, true + return o.IpVersion, true } -// SetSourceMac sets field value -func (o *FirewallruleProperties) SetSourceMac(v string) { +// SetIpVersion sets field value +func (o *FirewallruleProperties) SetIpVersion(v string) { - o.SourceMac = &v + o.IpVersion = &v } -// HasSourceMac returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasSourceMac() bool { - if o != nil && o.SourceMac != nil { +// sets IpVersion to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetIpVersionNil() { + o.IpVersion = &Nilstring +} + +// HasIpVersion returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasIpVersion() bool { + if o != nil && o.IpVersion != nil { return true } return false } -// GetIpVersion returns the IpVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetIpVersion() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetName() *string { if o == nil { return nil } - return o.IpVersion + return o.Name } -// GetIpVersionOk returns a tuple with the IpVersion field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetIpVersionOk() (*string, bool) { +func (o *FirewallruleProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.IpVersion, true + return o.Name, true } -// SetIpVersion sets field value -func (o *FirewallruleProperties) SetIpVersion(v string) { +// SetName sets field value +func (o *FirewallruleProperties) SetName(v string) { - o.IpVersion = &v + o.Name = &v } -// HasIpVersion returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasIpVersion() bool { - if o != nil && o.IpVersion != nil { +// HasName returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetSourceIp returns the SourceIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetSourceIp() *string { +// GetPortRangeEnd returns the PortRangeEnd field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetPortRangeEnd() *int32 { if o == nil { return nil } - return o.SourceIp + return o.PortRangeEnd } -// GetSourceIpOk returns a tuple with the SourceIp field value +// GetPortRangeEndOk returns a tuple with the PortRangeEnd field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetSourceIpOk() (*string, bool) { +func (o *FirewallruleProperties) GetPortRangeEndOk() (*int32, bool) { if o == nil { return nil, false } - return o.SourceIp, true + return o.PortRangeEnd, true } -// SetSourceIp sets field value -func (o *FirewallruleProperties) SetSourceIp(v string) { +// SetPortRangeEnd sets field value +func (o *FirewallruleProperties) SetPortRangeEnd(v int32) { - o.SourceIp = &v + o.PortRangeEnd = &v } -// HasSourceIp returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasSourceIp() bool { - if o != nil && o.SourceIp != nil { +// HasPortRangeEnd returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasPortRangeEnd() bool { + if o != nil && o.PortRangeEnd != nil { return true } return false } -// GetTargetIp returns the TargetIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetTargetIp() *string { +// GetPortRangeStart returns the PortRangeStart field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetPortRangeStart() *int32 { if o == nil { return nil } - return o.TargetIp + return o.PortRangeStart } -// GetTargetIpOk returns a tuple with the TargetIp field value +// GetPortRangeStartOk returns a tuple with the PortRangeStart field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetTargetIpOk() (*string, bool) { +func (o *FirewallruleProperties) GetPortRangeStartOk() (*int32, bool) { if o == nil { return nil, false } - return o.TargetIp, true + return o.PortRangeStart, true } -// SetTargetIp sets field value -func (o *FirewallruleProperties) SetTargetIp(v string) { +// SetPortRangeStart sets field value +func (o *FirewallruleProperties) SetPortRangeStart(v int32) { - o.TargetIp = &v + o.PortRangeStart = &v } -// HasTargetIp returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasTargetIp() bool { - if o != nil && o.TargetIp != nil { +// HasPortRangeStart returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasPortRangeStart() bool { + if o != nil && o.PortRangeStart != nil { return true } return false } -// GetIcmpCode returns the IcmpCode field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetIcmpCode() *int32 { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetProtocol() *string { if o == nil { return nil } - return o.IcmpCode + return o.Protocol } -// GetIcmpCodeOk returns a tuple with the IcmpCode field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetIcmpCodeOk() (*int32, bool) { +func (o *FirewallruleProperties) GetProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.IcmpCode, true + return o.Protocol, true } -// SetIcmpCode sets field value -func (o *FirewallruleProperties) SetIcmpCode(v int32) { +// SetProtocol sets field value +func (o *FirewallruleProperties) SetProtocol(v string) { - o.IcmpCode = &v + o.Protocol = &v } -// HasIcmpCode returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasIcmpCode() bool { - if o != nil && o.IcmpCode != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetIcmpType returns the IcmpType field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetIcmpType() *int32 { +// GetSourceIp returns the SourceIp field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetSourceIp() *string { if o == nil { return nil } - return o.IcmpType + return o.SourceIp } -// GetIcmpTypeOk returns a tuple with the IcmpType field value +// GetSourceIpOk returns a tuple with the SourceIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetIcmpTypeOk() (*int32, bool) { +func (o *FirewallruleProperties) GetSourceIpOk() (*string, bool) { if o == nil { return nil, false } - return o.IcmpType, true + return o.SourceIp, true } -// SetIcmpType sets field value -func (o *FirewallruleProperties) SetIcmpType(v int32) { +// SetSourceIp sets field value +func (o *FirewallruleProperties) SetSourceIp(v string) { - o.IcmpType = &v + o.SourceIp = &v } -// HasIcmpType returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasIcmpType() bool { - if o != nil && o.IcmpType != nil { +// sets SourceIp to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetSourceIpNil() { + o.SourceIp = &Nilstring +} + +// HasSourceIp returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasSourceIp() bool { + if o != nil && o.SourceIp != nil { return true } return false } -// GetPortRangeStart returns the PortRangeStart field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetPortRangeStart() *int32 { +// GetSourceMac returns the SourceMac field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetSourceMac() *string { if o == nil { return nil } - return o.PortRangeStart + return o.SourceMac } -// GetPortRangeStartOk returns a tuple with the PortRangeStart field value +// GetSourceMacOk returns a tuple with the SourceMac field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetPortRangeStartOk() (*int32, bool) { +func (o *FirewallruleProperties) GetSourceMacOk() (*string, bool) { if o == nil { return nil, false } - return o.PortRangeStart, true + return o.SourceMac, true } -// SetPortRangeStart sets field value -func (o *FirewallruleProperties) SetPortRangeStart(v int32) { +// SetSourceMac sets field value +func (o *FirewallruleProperties) SetSourceMac(v string) { - o.PortRangeStart = &v + o.SourceMac = &v } -// HasPortRangeStart returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasPortRangeStart() bool { - if o != nil && o.PortRangeStart != nil { +// sets SourceMac to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetSourceMacNil() { + o.SourceMac = &Nilstring +} + +// HasSourceMac returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasSourceMac() bool { + if o != nil && o.SourceMac != nil { return true } return false } -// GetPortRangeEnd returns the PortRangeEnd field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetPortRangeEnd() *int32 { +// GetTargetIp returns the TargetIp field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetTargetIp() *string { if o == nil { return nil } - return o.PortRangeEnd + return o.TargetIp } -// GetPortRangeEndOk returns a tuple with the PortRangeEnd field value +// GetTargetIpOk returns a tuple with the TargetIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetPortRangeEndOk() (*int32, bool) { +func (o *FirewallruleProperties) GetTargetIpOk() (*string, bool) { if o == nil { return nil, false } - return o.PortRangeEnd, true + return o.TargetIp, true } -// SetPortRangeEnd sets field value -func (o *FirewallruleProperties) SetPortRangeEnd(v int32) { +// SetTargetIp sets field value +func (o *FirewallruleProperties) SetTargetIp(v string) { - o.PortRangeEnd = &v + o.TargetIp = &v } -// HasPortRangeEnd returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasPortRangeEnd() bool { - if o != nil && o.PortRangeEnd != nil { +// sets TargetIp to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetTargetIpNil() { + o.TargetIp = &Nilstring +} + +// HasTargetIp returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasTargetIp() bool { + if o != nil && o.TargetIp != nil { return true } @@ -441,7 +477,7 @@ func (o *FirewallruleProperties) HasPortRangeEnd() bool { } // GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *FirewallruleProperties) GetType() *string { if o == nil { return nil @@ -480,29 +516,61 @@ func (o *FirewallruleProperties) HasType() bool { func (o FirewallruleProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + + if o.IcmpCode == &Nilint32 { + toSerialize["icmpCode"] = nil + } else if o.IcmpCode != nil { + toSerialize["icmpCode"] = o.IcmpCode + } + + if o.IcmpType == &Nilint32 { + toSerialize["icmpType"] = nil + } else if o.IcmpType != nil { + toSerialize["icmpType"] = o.IcmpType + } + + if o.IpVersion == &Nilstring { + toSerialize["ipVersion"] = nil + } else if o.IpVersion != nil { + toSerialize["ipVersion"] = o.IpVersion + } if o.Name != nil { toSerialize["name"] = o.Name } + + if o.PortRangeEnd != nil { + toSerialize["portRangeEnd"] = o.PortRangeEnd + } + + if o.PortRangeStart != nil { + toSerialize["portRangeStart"] = o.PortRangeStart + } + if o.Protocol != nil { toSerialize["protocol"] = o.Protocol } - toSerialize["sourceMac"] = o.SourceMac - if o.IpVersion != nil { - toSerialize["ipVersion"] = o.IpVersion + + if o.SourceIp == &Nilstring { + toSerialize["sourceIp"] = nil + } else if o.SourceIp != nil { + toSerialize["sourceIp"] = o.SourceIp } - toSerialize["sourceIp"] = o.SourceIp - toSerialize["targetIp"] = o.TargetIp - toSerialize["icmpCode"] = o.IcmpCode - toSerialize["icmpType"] = o.IcmpType - if o.PortRangeStart != nil { - toSerialize["portRangeStart"] = o.PortRangeStart + + if o.SourceMac == &Nilstring { + toSerialize["sourceMac"] = nil + } else if o.SourceMac != nil { + toSerialize["sourceMac"] = o.SourceMac } - if o.PortRangeEnd != nil { - toSerialize["portRangeEnd"] = o.PortRangeEnd + + if o.TargetIp == &Nilstring { + toSerialize["targetIp"] = nil + } else if o.TargetIp != nil { + toSerialize["targetIp"] = o.TargetIp } if o.Type != nil { toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go index e8d74517f..6e4412408 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go @@ -16,14 +16,14 @@ import ( // FlowLog struct for FlowLog type FlowLog struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *FlowLogProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFlowLog instantiates a new FlowLog object @@ -46,190 +46,190 @@ func NewFlowLogWithDefaults() *FlowLog { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLog) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetIdOk() (*string, bool) { +func (o *FlowLog) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *FlowLog) SetId(v string) { +// SetHref sets field value +func (o *FlowLog) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *FlowLog) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *FlowLog) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FlowLog) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetTypeOk() (*Type, bool) { +func (o *FlowLog) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *FlowLog) SetType(v Type) { +// SetId sets field value +func (o *FlowLog) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *FlowLog) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *FlowLog) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLog) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetHrefOk() (*string, bool) { +func (o *FlowLog) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *FlowLog) SetHref(v string) { +// SetMetadata sets field value +func (o *FlowLog) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *FlowLog) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *FlowLog) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *FlowLog) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetProperties() *FlowLogProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *FlowLog) GetPropertiesOk() (*FlowLogProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *FlowLog) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *FlowLog) SetProperties(v FlowLogProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *FlowLog) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *FlowLog) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for FlowLogProperties will be returned -func (o *FlowLog) GetProperties() *FlowLogProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetPropertiesOk() (*FlowLogProperties, bool) { +func (o *FlowLog) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *FlowLog) SetProperties(v FlowLogProperties) { +// SetType sets field value +func (o *FlowLog) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *FlowLog) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *FlowLog) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *FlowLog) HasProperties() bool { func (o FlowLog) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go index dca17c214..0f2a3b202 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go @@ -16,27 +16,27 @@ import ( // FlowLogProperties struct for FlowLogProperties type FlowLogProperties struct { - // The resource name. - Name *string `json:"name"` // Specifies the traffic action pattern. Action *string `json:"action"` - // Specifies the traffic direction pattern. - Direction *string `json:"direction"` // The S3 bucket name of an existing IONOS Cloud S3 bucket. Bucket *string `json:"bucket"` + // Specifies the traffic direction pattern. + Direction *string `json:"direction"` + // The resource name. + Name *string `json:"name"` } // NewFlowLogProperties instantiates a new FlowLogProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewFlowLogProperties(name string, action string, direction string, bucket string) *FlowLogProperties { +func NewFlowLogProperties(action string, bucket string, direction string, name string) *FlowLogProperties { this := FlowLogProperties{} - this.Name = &name this.Action = &action - this.Direction = &direction this.Bucket = &bucket + this.Direction = &direction + this.Name = &name return &this } @@ -49,76 +49,76 @@ func NewFlowLogPropertiesWithDefaults() *FlowLogProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogProperties) GetName() *string { +// GetAction returns the Action field value +// If the value is explicit nil, nil is returned +func (o *FlowLogProperties) GetAction() *string { if o == nil { return nil } - return o.Name + return o.Action } -// GetNameOk returns a tuple with the Name field value +// GetActionOk returns a tuple with the Action field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogProperties) GetNameOk() (*string, bool) { +func (o *FlowLogProperties) GetActionOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Action, true } -// SetName sets field value -func (o *FlowLogProperties) SetName(v string) { +// SetAction sets field value +func (o *FlowLogProperties) SetAction(v string) { - o.Name = &v + o.Action = &v } -// HasName returns a boolean if a field has been set. -func (o *FlowLogProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAction returns a boolean if a field has been set. +func (o *FlowLogProperties) HasAction() bool { + if o != nil && o.Action != nil { return true } return false } -// GetAction returns the Action field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogProperties) GetAction() *string { +// GetBucket returns the Bucket field value +// If the value is explicit nil, nil is returned +func (o *FlowLogProperties) GetBucket() *string { if o == nil { return nil } - return o.Action + return o.Bucket } -// GetActionOk returns a tuple with the Action field value +// GetBucketOk returns a tuple with the Bucket field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogProperties) GetActionOk() (*string, bool) { +func (o *FlowLogProperties) GetBucketOk() (*string, bool) { if o == nil { return nil, false } - return o.Action, true + return o.Bucket, true } -// SetAction sets field value -func (o *FlowLogProperties) SetAction(v string) { +// SetBucket sets field value +func (o *FlowLogProperties) SetBucket(v string) { - o.Action = &v + o.Bucket = &v } -// HasAction returns a boolean if a field has been set. -func (o *FlowLogProperties) HasAction() bool { - if o != nil && o.Action != nil { +// HasBucket returns a boolean if a field has been set. +func (o *FlowLogProperties) HasBucket() bool { + if o != nil && o.Bucket != nil { return true } @@ -126,7 +126,7 @@ func (o *FlowLogProperties) HasAction() bool { } // GetDirection returns the Direction field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *FlowLogProperties) GetDirection() *string { if o == nil { return nil @@ -163,38 +163,38 @@ func (o *FlowLogProperties) HasDirection() bool { return false } -// GetBucket returns the Bucket field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogProperties) GetBucket() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *FlowLogProperties) GetName() *string { if o == nil { return nil } - return o.Bucket + return o.Name } -// GetBucketOk returns a tuple with the Bucket field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogProperties) GetBucketOk() (*string, bool) { +func (o *FlowLogProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Bucket, true + return o.Name, true } -// SetBucket sets field value -func (o *FlowLogProperties) SetBucket(v string) { +// SetName sets field value +func (o *FlowLogProperties) SetName(v string) { - o.Bucket = &v + o.Name = &v } -// HasBucket returns a boolean if a field has been set. -func (o *FlowLogProperties) HasBucket() bool { - if o != nil && o.Bucket != nil { +// HasName returns a boolean if a field has been set. +func (o *FlowLogProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -203,18 +203,22 @@ func (o *FlowLogProperties) HasBucket() bool { func (o FlowLogProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Action != nil { toSerialize["action"] = o.Action } + + if o.Bucket != nil { + toSerialize["bucket"] = o.Bucket + } + if o.Direction != nil { toSerialize["direction"] = o.Direction } - if o.Bucket != nil { - toSerialize["bucket"] = o.Bucket + + if o.Name != nil { + toSerialize["name"] = o.Name } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go index 8f9b7f777..7fe84d71f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go @@ -16,13 +16,13 @@ import ( // FlowLogPut struct for FlowLogPut type FlowLogPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *FlowLogProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *FlowLogProperties `json:"properties"` } // NewFlowLogPut instantiates a new FlowLogPut object @@ -45,152 +45,152 @@ func NewFlowLogPutWithDefaults() *FlowLogPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetIdOk() (*string, bool) { +func (o *FlowLogPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *FlowLogPut) SetId(v string) { +// SetHref sets field value +func (o *FlowLogPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *FlowLogPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *FlowLogPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FlowLogPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetTypeOk() (*Type, bool) { +func (o *FlowLogPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *FlowLogPut) SetType(v Type) { +// SetId sets field value +func (o *FlowLogPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *FlowLogPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *FlowLogPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetProperties() *FlowLogProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetHrefOk() (*string, bool) { +func (o *FlowLogPut) GetPropertiesOk() (*FlowLogProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *FlowLogPut) SetHref(v string) { +// SetProperties sets field value +func (o *FlowLogPut) SetProperties(v FlowLogProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *FlowLogPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *FlowLogPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for FlowLogProperties will be returned -func (o *FlowLogPut) GetProperties() *FlowLogProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetPropertiesOk() (*FlowLogProperties, bool) { +func (o *FlowLogPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *FlowLogPut) SetProperties(v FlowLogProperties) { +// SetType sets field value +func (o *FlowLogPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *FlowLogPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *FlowLogPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *FlowLogPut) HasProperties() bool { func (o FlowLogPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go index 48f070e31..653d925ab 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go @@ -16,19 +16,19 @@ import ( // FlowLogs struct for FlowLogs type FlowLogs struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]FlowLog `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFlowLogs instantiates a new FlowLogs object @@ -49,114 +49,114 @@ func NewFlowLogsWithDefaults() *FlowLogs { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogs) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetIdOk() (*string, bool) { +func (o *FlowLogs) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *FlowLogs) SetId(v string) { +// SetLinks sets field value +func (o *FlowLogs) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *FlowLogs) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *FlowLogs) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FlowLogs) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetTypeOk() (*Type, bool) { +func (o *FlowLogs) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *FlowLogs) SetType(v Type) { +// SetHref sets field value +func (o *FlowLogs) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *FlowLogs) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *FlowLogs) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogs) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetHrefOk() (*string, bool) { +func (o *FlowLogs) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *FlowLogs) SetHref(v string) { +// SetId sets field value +func (o *FlowLogs) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *FlowLogs) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *FlowLogs) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *FlowLogs) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []FlowLog will be returned +// If the value is explicit nil, nil is returned func (o *FlowLogs) GetItems() *[]FlowLog { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *FlowLogs) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FlowLogs) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetOffsetOk() (*float32, bool) { +func (o *FlowLogs) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *FlowLogs) SetOffset(v float32) { +// SetLimit sets field value +func (o *FlowLogs) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *FlowLogs) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *FlowLogs) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FlowLogs) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetLimitOk() (*float32, bool) { +func (o *FlowLogs) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *FlowLogs) SetLimit(v float32) { +// SetOffset sets field value +func (o *FlowLogs) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *FlowLogs) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *FlowLogs) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *FlowLogs) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetLinksOk() (*PaginationLinks, bool) { +func (o *FlowLogs) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *FlowLogs) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *FlowLogs) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *FlowLogs) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *FlowLogs) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *FlowLogs) HasLinks() bool { func (o FlowLogs) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go index a1e9b6781..1509dd460 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go @@ -16,14 +16,14 @@ import ( // Group struct for Group type Group struct { + Entities *GroupEntities `json:"entities,omitempty"` + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *GroupProperties `json:"properties"` // The type of the resource. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *GroupProperties `json:"properties"` - Entities *GroupEntities `json:"entities,omitempty"` } // NewGroup instantiates a new Group object @@ -46,114 +46,114 @@ func NewGroupWithDefaults() *Group { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Group) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Group) GetEntities() *GroupEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetIdOk() (*string, bool) { +func (o *Group) GetEntitiesOk() (*GroupEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Group) SetId(v string) { +// SetEntities sets field value +func (o *Group) SetEntities(v GroupEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Group) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Group) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Group) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Group) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetTypeOk() (*Type, bool) { +func (o *Group) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Group) SetType(v Type) { +// SetHref sets field value +func (o *Group) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Group) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Group) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Group) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Group) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetHrefOk() (*string, bool) { +func (o *Group) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Group) SetHref(v string) { +// SetId sets field value +func (o *Group) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Group) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Group) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -161,7 +161,7 @@ func (o *Group) HasHref() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for GroupProperties will be returned +// If the value is explicit nil, nil is returned func (o *Group) GetProperties() *GroupProperties { if o == nil { return nil @@ -198,38 +198,38 @@ func (o *Group) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for GroupEntities will be returned -func (o *Group) GetEntities() *GroupEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Group) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetEntitiesOk() (*GroupEntities, bool) { +func (o *Group) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Group) SetEntities(v GroupEntities) { +// SetType sets field value +func (o *Group) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Group) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Group) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Group) HasEntities() bool { func (o Group) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go index 067e84cac..f9e914622 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go @@ -16,8 +16,8 @@ import ( // GroupEntities struct for GroupEntities type GroupEntities struct { - Users *GroupMembers `json:"users,omitempty"` Resources *ResourceGroups `json:"resources,omitempty"` + Users *GroupMembers `json:"users,omitempty"` } // NewGroupEntities instantiates a new GroupEntities object @@ -38,76 +38,76 @@ func NewGroupEntitiesWithDefaults() *GroupEntities { return &this } -// GetUsers returns the Users field value -// If the value is explicit nil, the zero value for GroupMembers will be returned -func (o *GroupEntities) GetUsers() *GroupMembers { +// GetResources returns the Resources field value +// If the value is explicit nil, nil is returned +func (o *GroupEntities) GetResources() *ResourceGroups { if o == nil { return nil } - return o.Users + return o.Resources } -// GetUsersOk returns a tuple with the Users field value +// GetResourcesOk returns a tuple with the Resources field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupEntities) GetUsersOk() (*GroupMembers, bool) { +func (o *GroupEntities) GetResourcesOk() (*ResourceGroups, bool) { if o == nil { return nil, false } - return o.Users, true + return o.Resources, true } -// SetUsers sets field value -func (o *GroupEntities) SetUsers(v GroupMembers) { +// SetResources sets field value +func (o *GroupEntities) SetResources(v ResourceGroups) { - o.Users = &v + o.Resources = &v } -// HasUsers returns a boolean if a field has been set. -func (o *GroupEntities) HasUsers() bool { - if o != nil && o.Users != nil { +// HasResources returns a boolean if a field has been set. +func (o *GroupEntities) HasResources() bool { + if o != nil && o.Resources != nil { return true } return false } -// GetResources returns the Resources field value -// If the value is explicit nil, the zero value for ResourceGroups will be returned -func (o *GroupEntities) GetResources() *ResourceGroups { +// GetUsers returns the Users field value +// If the value is explicit nil, nil is returned +func (o *GroupEntities) GetUsers() *GroupMembers { if o == nil { return nil } - return o.Resources + return o.Users } -// GetResourcesOk returns a tuple with the Resources field value +// GetUsersOk returns a tuple with the Users field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupEntities) GetResourcesOk() (*ResourceGroups, bool) { +func (o *GroupEntities) GetUsersOk() (*GroupMembers, bool) { if o == nil { return nil, false } - return o.Resources, true + return o.Users, true } -// SetResources sets field value -func (o *GroupEntities) SetResources(v ResourceGroups) { +// SetUsers sets field value +func (o *GroupEntities) SetUsers(v GroupMembers) { - o.Resources = &v + o.Users = &v } -// HasResources returns a boolean if a field has been set. -func (o *GroupEntities) HasResources() bool { - if o != nil && o.Resources != nil { +// HasUsers returns a boolean if a field has been set. +func (o *GroupEntities) HasUsers() bool { + if o != nil && o.Users != nil { return true } @@ -116,12 +116,14 @@ func (o *GroupEntities) HasResources() bool { func (o GroupEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Users != nil { - toSerialize["users"] = o.Users - } if o.Resources != nil { toSerialize["resources"] = o.Resources } + + if o.Users != nil { + toSerialize["users"] = o.Users + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go index c38d7c018..a4a750e78 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go @@ -16,14 +16,14 @@ import ( // GroupMembers struct for GroupMembers type GroupMembers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]User `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewGroupMembers instantiates a new GroupMembers object @@ -44,152 +44,152 @@ func NewGroupMembersWithDefaults() *GroupMembers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupMembers) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetIdOk() (*string, bool) { +func (o *GroupMembers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupMembers) SetId(v string) { +// SetHref sets field value +func (o *GroupMembers) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupMembers) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupMembers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupMembers) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetTypeOk() (*Type, bool) { +func (o *GroupMembers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupMembers) SetType(v Type) { +// SetId sets field value +func (o *GroupMembers) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupMembers) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupMembers) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupMembers) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetItems() *[]User { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetHrefOk() (*string, bool) { +func (o *GroupMembers) GetItemsOk() (*[]User, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *GroupMembers) SetHref(v string) { +// SetItems sets field value +func (o *GroupMembers) SetItems(v []User) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupMembers) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *GroupMembers) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []User will be returned -func (o *GroupMembers) GetItems() *[]User { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetItemsOk() (*[]User, bool) { +func (o *GroupMembers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *GroupMembers) SetItems(v []User) { +// SetType sets field value +func (o *GroupMembers) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *GroupMembers) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupMembers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *GroupMembers) HasItems() bool { func (o GroupMembers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go index c4c55d9b1..d73cb668b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go @@ -16,40 +16,40 @@ import ( // GroupProperties struct for GroupProperties type GroupProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // Create data center privilege. - CreateDataCenter *bool `json:"createDataCenter,omitempty"` - // Create snapshot privilege. - CreateSnapshot *bool `json:"createSnapshot,omitempty"` - // Reserve IP block privilege. - ReserveIp *bool `json:"reserveIp,omitempty"` // Activity log access privilege. AccessActivityLog *bool `json:"accessActivityLog,omitempty"` - // Create pcc privilege. - CreatePcc *bool `json:"createPcc,omitempty"` - // S3 privilege. - S3Privilege *bool `json:"s3Privilege,omitempty"` + // Privilege for a group to access and manage certificates. + AccessAndManageCertificates *bool `json:"accessAndManageCertificates,omitempty"` + // Privilege for a group to access and manage dns records. + AccessAndManageDns *bool `json:"accessAndManageDns,omitempty"` + // Privilege for a group to access and manage monitoring related functionality (access metrics, CRUD on alarms, alarm-actions etc) using Monotoring-as-a-Service (MaaS). + AccessAndManageMonitoring *bool `json:"accessAndManageMonitoring,omitempty"` // Create backup unit privilege. CreateBackupUnit *bool `json:"createBackupUnit,omitempty"` + // Create data center privilege. + CreateDataCenter *bool `json:"createDataCenter,omitempty"` + // Create Flow Logs privilege. + CreateFlowLog *bool `json:"createFlowLog,omitempty"` // Create internet access privilege. CreateInternetAccess *bool `json:"createInternetAccess,omitempty"` // Create Kubernetes cluster privilege. CreateK8sCluster *bool `json:"createK8sCluster,omitempty"` - // Create Flow Logs privilege. - CreateFlowLog *bool `json:"createFlowLog,omitempty"` - // Privilege for a group to access and manage monitoring related functionality (access metrics, CRUD on alarms, alarm-actions etc) using Monotoring-as-a-Service (MaaS). - AccessAndManageMonitoring *bool `json:"accessAndManageMonitoring,omitempty"` - // Privilege for a group to access and manage certificates. - AccessAndManageCertificates *bool `json:"accessAndManageCertificates,omitempty"` + // Create pcc privilege. + CreatePcc *bool `json:"createPcc,omitempty"` + // Create snapshot privilege. + CreateSnapshot *bool `json:"createSnapshot,omitempty"` // Privilege for a group to manage DBaaS related functionality. ManageDBaaS *bool `json:"manageDBaaS,omitempty"` - // Privilege for a group to access and manage dns records. - AccessAndManageDns *bool `json:"accessAndManageDns,omitempty"` + // Privilege for a group to access and manage the Data Platform. + ManageDataplatform *bool `json:"manageDataplatform,omitempty"` // Privilege for group accessing container registry related functionality. ManageRegistry *bool `json:"manageRegistry,omitempty"` - // Privilege for a group to access and manage Data Platform. - ManageDataplatform *bool `json:"manageDataplatform,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` + // Reserve IP block privilege. + ReserveIp *bool `json:"reserveIp,omitempty"` + // S3 privilege. + S3Privilege *bool `json:"s3Privilege,omitempty"` } // NewGroupProperties instantiates a new GroupProperties object @@ -70,304 +70,266 @@ func NewGroupPropertiesWithDefaults() *GroupProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupProperties) GetName() *string { - if o == nil { - return nil - } - - return o.Name - -} - -// GetNameOk returns a tuple with the Name field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetNameOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Name, true -} - -// SetName sets field value -func (o *GroupProperties) SetName(v string) { - - o.Name = &v - -} - -// HasName returns a boolean if a field has been set. -func (o *GroupProperties) HasName() bool { - if o != nil && o.Name != nil { - return true - } - - return false -} - -// GetCreateDataCenter returns the CreateDataCenter field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateDataCenter() *bool { +// GetAccessActivityLog returns the AccessActivityLog field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessActivityLog() *bool { if o == nil { return nil } - return o.CreateDataCenter + return o.AccessActivityLog } -// GetCreateDataCenterOk returns a tuple with the CreateDataCenter field value +// GetAccessActivityLogOk returns a tuple with the AccessActivityLog field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateDataCenterOk() (*bool, bool) { +func (o *GroupProperties) GetAccessActivityLogOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreateDataCenter, true + return o.AccessActivityLog, true } -// SetCreateDataCenter sets field value -func (o *GroupProperties) SetCreateDataCenter(v bool) { +// SetAccessActivityLog sets field value +func (o *GroupProperties) SetAccessActivityLog(v bool) { - o.CreateDataCenter = &v + o.AccessActivityLog = &v } -// HasCreateDataCenter returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateDataCenter() bool { - if o != nil && o.CreateDataCenter != nil { +// HasAccessActivityLog returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessActivityLog() bool { + if o != nil && o.AccessActivityLog != nil { return true } return false } -// GetCreateSnapshot returns the CreateSnapshot field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateSnapshot() *bool { +// GetAccessAndManageCertificates returns the AccessAndManageCertificates field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessAndManageCertificates() *bool { if o == nil { return nil } - return o.CreateSnapshot + return o.AccessAndManageCertificates } -// GetCreateSnapshotOk returns a tuple with the CreateSnapshot field value +// GetAccessAndManageCertificatesOk returns a tuple with the AccessAndManageCertificates field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateSnapshotOk() (*bool, bool) { +func (o *GroupProperties) GetAccessAndManageCertificatesOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreateSnapshot, true + return o.AccessAndManageCertificates, true } -// SetCreateSnapshot sets field value -func (o *GroupProperties) SetCreateSnapshot(v bool) { +// SetAccessAndManageCertificates sets field value +func (o *GroupProperties) SetAccessAndManageCertificates(v bool) { - o.CreateSnapshot = &v + o.AccessAndManageCertificates = &v } -// HasCreateSnapshot returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateSnapshot() bool { - if o != nil && o.CreateSnapshot != nil { +// HasAccessAndManageCertificates returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessAndManageCertificates() bool { + if o != nil && o.AccessAndManageCertificates != nil { return true } return false } -// GetReserveIp returns the ReserveIp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetReserveIp() *bool { +// GetAccessAndManageDns returns the AccessAndManageDns field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessAndManageDns() *bool { if o == nil { return nil } - return o.ReserveIp + return o.AccessAndManageDns } -// GetReserveIpOk returns a tuple with the ReserveIp field value +// GetAccessAndManageDnsOk returns a tuple with the AccessAndManageDns field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetReserveIpOk() (*bool, bool) { +func (o *GroupProperties) GetAccessAndManageDnsOk() (*bool, bool) { if o == nil { return nil, false } - return o.ReserveIp, true + return o.AccessAndManageDns, true } -// SetReserveIp sets field value -func (o *GroupProperties) SetReserveIp(v bool) { +// SetAccessAndManageDns sets field value +func (o *GroupProperties) SetAccessAndManageDns(v bool) { - o.ReserveIp = &v + o.AccessAndManageDns = &v } -// HasReserveIp returns a boolean if a field has been set. -func (o *GroupProperties) HasReserveIp() bool { - if o != nil && o.ReserveIp != nil { +// HasAccessAndManageDns returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessAndManageDns() bool { + if o != nil && o.AccessAndManageDns != nil { return true } return false } -// GetAccessActivityLog returns the AccessActivityLog field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessActivityLog() *bool { +// GetAccessAndManageMonitoring returns the AccessAndManageMonitoring field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessAndManageMonitoring() *bool { if o == nil { return nil } - return o.AccessActivityLog + return o.AccessAndManageMonitoring } -// GetAccessActivityLogOk returns a tuple with the AccessActivityLog field value +// GetAccessAndManageMonitoringOk returns a tuple with the AccessAndManageMonitoring field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessActivityLogOk() (*bool, bool) { +func (o *GroupProperties) GetAccessAndManageMonitoringOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessActivityLog, true + return o.AccessAndManageMonitoring, true } -// SetAccessActivityLog sets field value -func (o *GroupProperties) SetAccessActivityLog(v bool) { +// SetAccessAndManageMonitoring sets field value +func (o *GroupProperties) SetAccessAndManageMonitoring(v bool) { - o.AccessActivityLog = &v + o.AccessAndManageMonitoring = &v } -// HasAccessActivityLog returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessActivityLog() bool { - if o != nil && o.AccessActivityLog != nil { +// HasAccessAndManageMonitoring returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessAndManageMonitoring() bool { + if o != nil && o.AccessAndManageMonitoring != nil { return true } return false } -// GetCreatePcc returns the CreatePcc field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreatePcc() *bool { +// GetCreateBackupUnit returns the CreateBackupUnit field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateBackupUnit() *bool { if o == nil { return nil } - return o.CreatePcc + return o.CreateBackupUnit } -// GetCreatePccOk returns a tuple with the CreatePcc field value +// GetCreateBackupUnitOk returns a tuple with the CreateBackupUnit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreatePccOk() (*bool, bool) { +func (o *GroupProperties) GetCreateBackupUnitOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreatePcc, true + return o.CreateBackupUnit, true } -// SetCreatePcc sets field value -func (o *GroupProperties) SetCreatePcc(v bool) { +// SetCreateBackupUnit sets field value +func (o *GroupProperties) SetCreateBackupUnit(v bool) { - o.CreatePcc = &v + o.CreateBackupUnit = &v } -// HasCreatePcc returns a boolean if a field has been set. -func (o *GroupProperties) HasCreatePcc() bool { - if o != nil && o.CreatePcc != nil { +// HasCreateBackupUnit returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateBackupUnit() bool { + if o != nil && o.CreateBackupUnit != nil { return true } return false } -// GetS3Privilege returns the S3Privilege field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetS3Privilege() *bool { +// GetCreateDataCenter returns the CreateDataCenter field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateDataCenter() *bool { if o == nil { return nil } - return o.S3Privilege + return o.CreateDataCenter } -// GetS3PrivilegeOk returns a tuple with the S3Privilege field value +// GetCreateDataCenterOk returns a tuple with the CreateDataCenter field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetS3PrivilegeOk() (*bool, bool) { +func (o *GroupProperties) GetCreateDataCenterOk() (*bool, bool) { if o == nil { return nil, false } - return o.S3Privilege, true + return o.CreateDataCenter, true } -// SetS3Privilege sets field value -func (o *GroupProperties) SetS3Privilege(v bool) { +// SetCreateDataCenter sets field value +func (o *GroupProperties) SetCreateDataCenter(v bool) { - o.S3Privilege = &v + o.CreateDataCenter = &v } -// HasS3Privilege returns a boolean if a field has been set. -func (o *GroupProperties) HasS3Privilege() bool { - if o != nil && o.S3Privilege != nil { +// HasCreateDataCenter returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateDataCenter() bool { + if o != nil && o.CreateDataCenter != nil { return true } return false } -// GetCreateBackupUnit returns the CreateBackupUnit field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateBackupUnit() *bool { +// GetCreateFlowLog returns the CreateFlowLog field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateFlowLog() *bool { if o == nil { return nil } - return o.CreateBackupUnit + return o.CreateFlowLog } -// GetCreateBackupUnitOk returns a tuple with the CreateBackupUnit field value +// GetCreateFlowLogOk returns a tuple with the CreateFlowLog field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateBackupUnitOk() (*bool, bool) { +func (o *GroupProperties) GetCreateFlowLogOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreateBackupUnit, true + return o.CreateFlowLog, true } -// SetCreateBackupUnit sets field value -func (o *GroupProperties) SetCreateBackupUnit(v bool) { +// SetCreateFlowLog sets field value +func (o *GroupProperties) SetCreateFlowLog(v bool) { - o.CreateBackupUnit = &v + o.CreateFlowLog = &v } -// HasCreateBackupUnit returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateBackupUnit() bool { - if o != nil && o.CreateBackupUnit != nil { +// HasCreateFlowLog returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateFlowLog() bool { + if o != nil && o.CreateFlowLog != nil { return true } @@ -375,7 +337,7 @@ func (o *GroupProperties) HasCreateBackupUnit() bool { } // GetCreateInternetAccess returns the CreateInternetAccess field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetCreateInternetAccess() *bool { if o == nil { return nil @@ -413,7 +375,7 @@ func (o *GroupProperties) HasCreateInternetAccess() bool { } // GetCreateK8sCluster returns the CreateK8sCluster field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetCreateK8sCluster() *bool { if o == nil { return nil @@ -450,114 +412,76 @@ func (o *GroupProperties) HasCreateK8sCluster() bool { return false } -// GetCreateFlowLog returns the CreateFlowLog field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateFlowLog() *bool { +// GetCreatePcc returns the CreatePcc field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreatePcc() *bool { if o == nil { return nil } - return o.CreateFlowLog + return o.CreatePcc } -// GetCreateFlowLogOk returns a tuple with the CreateFlowLog field value +// GetCreatePccOk returns a tuple with the CreatePcc field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateFlowLogOk() (*bool, bool) { - if o == nil { - return nil, false - } - - return o.CreateFlowLog, true -} - -// SetCreateFlowLog sets field value -func (o *GroupProperties) SetCreateFlowLog(v bool) { - - o.CreateFlowLog = &v - -} - -// HasCreateFlowLog returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateFlowLog() bool { - if o != nil && o.CreateFlowLog != nil { - return true - } - - return false -} - -// GetAccessAndManageMonitoring returns the AccessAndManageMonitoring field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessAndManageMonitoring() *bool { - if o == nil { - return nil - } - - return o.AccessAndManageMonitoring - -} - -// GetAccessAndManageMonitoringOk returns a tuple with the AccessAndManageMonitoring field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessAndManageMonitoringOk() (*bool, bool) { +func (o *GroupProperties) GetCreatePccOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessAndManageMonitoring, true + return o.CreatePcc, true } -// SetAccessAndManageMonitoring sets field value -func (o *GroupProperties) SetAccessAndManageMonitoring(v bool) { +// SetCreatePcc sets field value +func (o *GroupProperties) SetCreatePcc(v bool) { - o.AccessAndManageMonitoring = &v + o.CreatePcc = &v } -// HasAccessAndManageMonitoring returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessAndManageMonitoring() bool { - if o != nil && o.AccessAndManageMonitoring != nil { +// HasCreatePcc returns a boolean if a field has been set. +func (o *GroupProperties) HasCreatePcc() bool { + if o != nil && o.CreatePcc != nil { return true } return false } -// GetAccessAndManageCertificates returns the AccessAndManageCertificates field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessAndManageCertificates() *bool { +// GetCreateSnapshot returns the CreateSnapshot field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateSnapshot() *bool { if o == nil { return nil } - return o.AccessAndManageCertificates + return o.CreateSnapshot } -// GetAccessAndManageCertificatesOk returns a tuple with the AccessAndManageCertificates field value +// GetCreateSnapshotOk returns a tuple with the CreateSnapshot field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessAndManageCertificatesOk() (*bool, bool) { +func (o *GroupProperties) GetCreateSnapshotOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessAndManageCertificates, true + return o.CreateSnapshot, true } -// SetAccessAndManageCertificates sets field value -func (o *GroupProperties) SetAccessAndManageCertificates(v bool) { +// SetCreateSnapshot sets field value +func (o *GroupProperties) SetCreateSnapshot(v bool) { - o.AccessAndManageCertificates = &v + o.CreateSnapshot = &v } -// HasAccessAndManageCertificates returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessAndManageCertificates() bool { - if o != nil && o.AccessAndManageCertificates != nil { +// HasCreateSnapshot returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateSnapshot() bool { + if o != nil && o.CreateSnapshot != nil { return true } @@ -565,7 +489,7 @@ func (o *GroupProperties) HasAccessAndManageCertificates() bool { } // GetManageDBaaS returns the ManageDBaaS field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetManageDBaaS() *bool { if o == nil { return nil @@ -602,38 +526,38 @@ func (o *GroupProperties) HasManageDBaaS() bool { return false } -// GetAccessAndManageDns returns the AccessAndManageDns field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessAndManageDns() *bool { +// GetManageDataplatform returns the ManageDataplatform field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetManageDataplatform() *bool { if o == nil { return nil } - return o.AccessAndManageDns + return o.ManageDataplatform } -// GetAccessAndManageDnsOk returns a tuple with the AccessAndManageDns field value +// GetManageDataplatformOk returns a tuple with the ManageDataplatform field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessAndManageDnsOk() (*bool, bool) { +func (o *GroupProperties) GetManageDataplatformOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessAndManageDns, true + return o.ManageDataplatform, true } -// SetAccessAndManageDns sets field value -func (o *GroupProperties) SetAccessAndManageDns(v bool) { +// SetManageDataplatform sets field value +func (o *GroupProperties) SetManageDataplatform(v bool) { - o.AccessAndManageDns = &v + o.ManageDataplatform = &v } -// HasAccessAndManageDns returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessAndManageDns() bool { - if o != nil && o.AccessAndManageDns != nil { +// HasManageDataplatform returns a boolean if a field has been set. +func (o *GroupProperties) HasManageDataplatform() bool { + if o != nil && o.ManageDataplatform != nil { return true } @@ -641,7 +565,7 @@ func (o *GroupProperties) HasAccessAndManageDns() bool { } // GetManageRegistry returns the ManageRegistry field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetManageRegistry() *bool { if o == nil { return nil @@ -678,97 +602,190 @@ func (o *GroupProperties) HasManageRegistry() bool { return false } -// GetManageDataplatform returns the ManageDataplatform field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetManageDataplatform() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetName() *string { if o == nil { return nil } - return o.ManageDataplatform + return o.Name } -// GetManageDataplatformOk returns a tuple with the ManageDataplatform field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetManageDataplatformOk() (*bool, bool) { +func (o *GroupProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ManageDataplatform, true + return o.Name, true } -// SetManageDataplatform sets field value -func (o *GroupProperties) SetManageDataplatform(v bool) { +// SetName sets field value +func (o *GroupProperties) SetName(v string) { - o.ManageDataplatform = &v + o.Name = &v } -// HasManageDataplatform returns a boolean if a field has been set. -func (o *GroupProperties) HasManageDataplatform() bool { - if o != nil && o.ManageDataplatform != nil { +// HasName returns a boolean if a field has been set. +func (o *GroupProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -func (o GroupProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name +// GetReserveIp returns the ReserveIp field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetReserveIp() *bool { + if o == nil { + return nil } - if o.CreateDataCenter != nil { - toSerialize["createDataCenter"] = o.CreateDataCenter + + return o.ReserveIp + +} + +// GetReserveIpOk returns a tuple with the ReserveIp field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *GroupProperties) GetReserveIpOk() (*bool, bool) { + if o == nil { + return nil, false } - if o.CreateSnapshot != nil { - toSerialize["createSnapshot"] = o.CreateSnapshot + + return o.ReserveIp, true +} + +// SetReserveIp sets field value +func (o *GroupProperties) SetReserveIp(v bool) { + + o.ReserveIp = &v + +} + +// HasReserveIp returns a boolean if a field has been set. +func (o *GroupProperties) HasReserveIp() bool { + if o != nil && o.ReserveIp != nil { + return true } - if o.ReserveIp != nil { - toSerialize["reserveIp"] = o.ReserveIp + + return false +} + +// GetS3Privilege returns the S3Privilege field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetS3Privilege() *bool { + if o == nil { + return nil + } + + return o.S3Privilege + +} + +// GetS3PrivilegeOk returns a tuple with the S3Privilege field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *GroupProperties) GetS3PrivilegeOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.S3Privilege, true +} + +// SetS3Privilege sets field value +func (o *GroupProperties) SetS3Privilege(v bool) { + + o.S3Privilege = &v + +} + +// HasS3Privilege returns a boolean if a field has been set. +func (o *GroupProperties) HasS3Privilege() bool { + if o != nil && o.S3Privilege != nil { + return true } + + return false +} + +func (o GroupProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} if o.AccessActivityLog != nil { toSerialize["accessActivityLog"] = o.AccessActivityLog } - if o.CreatePcc != nil { - toSerialize["createPcc"] = o.CreatePcc + + if o.AccessAndManageCertificates != nil { + toSerialize["accessAndManageCertificates"] = o.AccessAndManageCertificates } - if o.S3Privilege != nil { - toSerialize["s3Privilege"] = o.S3Privilege + + if o.AccessAndManageDns != nil { + toSerialize["accessAndManageDns"] = o.AccessAndManageDns } + + if o.AccessAndManageMonitoring != nil { + toSerialize["accessAndManageMonitoring"] = o.AccessAndManageMonitoring + } + if o.CreateBackupUnit != nil { toSerialize["createBackupUnit"] = o.CreateBackupUnit } + + if o.CreateDataCenter != nil { + toSerialize["createDataCenter"] = o.CreateDataCenter + } + + if o.CreateFlowLog != nil { + toSerialize["createFlowLog"] = o.CreateFlowLog + } + if o.CreateInternetAccess != nil { toSerialize["createInternetAccess"] = o.CreateInternetAccess } + if o.CreateK8sCluster != nil { toSerialize["createK8sCluster"] = o.CreateK8sCluster } - if o.CreateFlowLog != nil { - toSerialize["createFlowLog"] = o.CreateFlowLog - } - if o.AccessAndManageMonitoring != nil { - toSerialize["accessAndManageMonitoring"] = o.AccessAndManageMonitoring + + if o.CreatePcc != nil { + toSerialize["createPcc"] = o.CreatePcc } - if o.AccessAndManageCertificates != nil { - toSerialize["accessAndManageCertificates"] = o.AccessAndManageCertificates + + if o.CreateSnapshot != nil { + toSerialize["createSnapshot"] = o.CreateSnapshot } + if o.ManageDBaaS != nil { toSerialize["manageDBaaS"] = o.ManageDBaaS } - if o.AccessAndManageDns != nil { - toSerialize["accessAndManageDns"] = o.AccessAndManageDns + + if o.ManageDataplatform != nil { + toSerialize["manageDataplatform"] = o.ManageDataplatform } + if o.ManageRegistry != nil { toSerialize["manageRegistry"] = o.ManageRegistry } - if o.ManageDataplatform != nil { - toSerialize["manageDataplatform"] = o.ManageDataplatform + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.ReserveIp != nil { + toSerialize["reserveIp"] = o.ReserveIp + } + + if o.S3Privilege != nil { + toSerialize["s3Privilege"] = o.S3Privilege } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go index a25a874a3..ae84478aa 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go @@ -16,13 +16,13 @@ import ( // GroupShare struct for GroupShare type GroupShare struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *GroupShareProperties `json:"properties"` // resource as generic type Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *GroupShareProperties `json:"properties"` } // NewGroupShare instantiates a new GroupShare object @@ -45,152 +45,152 @@ func NewGroupShareWithDefaults() *GroupShare { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShare) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetIdOk() (*string, bool) { +func (o *GroupShare) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupShare) SetId(v string) { +// SetHref sets field value +func (o *GroupShare) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupShare) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupShare) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupShare) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetTypeOk() (*Type, bool) { +func (o *GroupShare) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupShare) SetType(v Type) { +// SetId sets field value +func (o *GroupShare) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupShare) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupShare) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShare) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetProperties() *GroupShareProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetHrefOk() (*string, bool) { +func (o *GroupShare) GetPropertiesOk() (*GroupShareProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *GroupShare) SetHref(v string) { +// SetProperties sets field value +func (o *GroupShare) SetProperties(v GroupShareProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupShare) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *GroupShare) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for GroupShareProperties will be returned -func (o *GroupShare) GetProperties() *GroupShareProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetPropertiesOk() (*GroupShareProperties, bool) { +func (o *GroupShare) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *GroupShare) SetProperties(v GroupShareProperties) { +// SetType sets field value +func (o *GroupShare) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *GroupShare) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupShare) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *GroupShare) HasProperties() bool { func (o GroupShare) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go index 5e356c127..1ca06267f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go @@ -41,7 +41,7 @@ func NewGroupSharePropertiesWithDefaults() *GroupShareProperties { } // GetEditPrivilege returns the EditPrivilege field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupShareProperties) GetEditPrivilege() *bool { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *GroupShareProperties) HasEditPrivilege() bool { } // GetSharePrivilege returns the SharePrivilege field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupShareProperties) GetSharePrivilege() *bool { if o == nil { return nil @@ -121,9 +121,11 @@ func (o GroupShareProperties) MarshalJSON() ([]byte, error) { if o.EditPrivilege != nil { toSerialize["editPrivilege"] = o.EditPrivilege } + if o.SharePrivilege != nil { toSerialize["sharePrivilege"] = o.SharePrivilege } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go index 6735473c8..091da39c5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go @@ -16,14 +16,14 @@ import ( // GroupShares struct for GroupShares type GroupShares struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // Share representing groups and resource relationship - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]GroupShare `json:"items,omitempty"` + // Share representing groups and resource relationship + Type *Type `json:"type,omitempty"` } // NewGroupShares instantiates a new GroupShares object @@ -44,152 +44,152 @@ func NewGroupSharesWithDefaults() *GroupShares { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShares) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetIdOk() (*string, bool) { +func (o *GroupShares) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupShares) SetId(v string) { +// SetHref sets field value +func (o *GroupShares) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupShares) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupShares) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupShares) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetTypeOk() (*Type, bool) { +func (o *GroupShares) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupShares) SetType(v Type) { +// SetId sets field value +func (o *GroupShares) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupShares) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupShares) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShares) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetItems() *[]GroupShare { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetHrefOk() (*string, bool) { +func (o *GroupShares) GetItemsOk() (*[]GroupShare, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *GroupShares) SetHref(v string) { +// SetItems sets field value +func (o *GroupShares) SetItems(v []GroupShare) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupShares) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *GroupShares) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []GroupShare will be returned -func (o *GroupShares) GetItems() *[]GroupShare { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetItemsOk() (*[]GroupShare, bool) { +func (o *GroupShares) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *GroupShares) SetItems(v []GroupShare) { +// SetType sets field value +func (o *GroupShares) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *GroupShares) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupShares) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *GroupShares) HasItems() bool { func (o GroupShares) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go index a2fb51bc2..4a4f075c1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go @@ -16,14 +16,14 @@ import ( // GroupUsers Collection of the groups the user is a member of. type GroupUsers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Group `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewGroupUsers instantiates a new GroupUsers object @@ -44,152 +44,152 @@ func NewGroupUsersWithDefaults() *GroupUsers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupUsers) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetIdOk() (*string, bool) { +func (o *GroupUsers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupUsers) SetId(v string) { +// SetHref sets field value +func (o *GroupUsers) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupUsers) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupUsers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupUsers) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetTypeOk() (*Type, bool) { +func (o *GroupUsers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupUsers) SetType(v Type) { +// SetId sets field value +func (o *GroupUsers) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupUsers) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupUsers) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupUsers) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetItems() *[]Group { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetHrefOk() (*string, bool) { +func (o *GroupUsers) GetItemsOk() (*[]Group, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *GroupUsers) SetHref(v string) { +// SetItems sets field value +func (o *GroupUsers) SetItems(v []Group) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupUsers) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *GroupUsers) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Group will be returned -func (o *GroupUsers) GetItems() *[]Group { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetItemsOk() (*[]Group, bool) { +func (o *GroupUsers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *GroupUsers) SetItems(v []Group) { +// SetType sets field value +func (o *GroupUsers) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *GroupUsers) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupUsers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *GroupUsers) HasItems() bool { func (o GroupUsers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go index 85df0a37d..578d27c1c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go @@ -16,14 +16,14 @@ import ( // Groups struct for Groups type Groups struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Group `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewGroups instantiates a new Groups object @@ -44,152 +44,152 @@ func NewGroupsWithDefaults() *Groups { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Groups) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetIdOk() (*string, bool) { +func (o *Groups) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Groups) SetId(v string) { +// SetHref sets field value +func (o *Groups) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Groups) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Groups) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Groups) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetTypeOk() (*Type, bool) { +func (o *Groups) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Groups) SetType(v Type) { +// SetId sets field value +func (o *Groups) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Groups) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Groups) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Groups) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetItems() *[]Group { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetHrefOk() (*string, bool) { +func (o *Groups) GetItemsOk() (*[]Group, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Groups) SetHref(v string) { +// SetItems sets field value +func (o *Groups) SetItems(v []Group) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Groups) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Groups) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Group will be returned -func (o *Groups) GetItems() *[]Group { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetItemsOk() (*[]Group, bool) { +func (o *Groups) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Groups) SetItems(v []Group) { +// SetType sets field value +func (o *Groups) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Groups) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Groups) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Groups) HasItems() bool { func (o Groups) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go index 747a0e949..962c8e2e8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go @@ -16,14 +16,14 @@ import ( // Image struct for Image type Image struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ImageProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewImage instantiates a new Image object @@ -46,190 +46,190 @@ func NewImageWithDefaults() *Image { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Image) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Image) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetIdOk() (*string, bool) { +func (o *Image) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Image) SetId(v string) { +// SetHref sets field value +func (o *Image) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Image) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Image) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Image) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Image) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetTypeOk() (*Type, bool) { +func (o *Image) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Image) SetType(v Type) { +// SetId sets field value +func (o *Image) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Image) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Image) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Image) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Image) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetHrefOk() (*string, bool) { +func (o *Image) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Image) SetHref(v string) { +// SetMetadata sets field value +func (o *Image) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Image) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Image) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Image) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Image) GetProperties() *ImageProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Image) GetPropertiesOk() (*ImageProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Image) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Image) SetProperties(v ImageProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Image) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Image) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ImageProperties will be returned -func (o *Image) GetProperties() *ImageProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Image) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetPropertiesOk() (*ImageProperties, bool) { +func (o *Image) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Image) SetProperties(v ImageProperties) { +// SetType sets field value +func (o *Image) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Image) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Image) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Image) HasProperties() bool { func (o Image) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go index 2ab0f5a65..f6059779e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go @@ -16,44 +16,44 @@ import ( // ImageProperties struct for ImageProperties type ImageProperties struct { - // The resource name. - Name *string `json:"name,omitempty"` - // Human-readable description. - Description *string `json:"description,omitempty"` - // The location of this image/snapshot. - Location *string `json:"location,omitempty"` - // The image size in GB. - Size *float32 `json:"size,omitempty"` + // Cloud init compatibility. + CloudInit *string `json:"cloudInit,omitempty"` // Hot-plug capable CPU (no reboot required). CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` // Hot-unplug capable CPU (no reboot required). CpuHotUnplug *bool `json:"cpuHotUnplug,omitempty"` - // Hot-plug capable RAM (no reboot required). - RamHotPlug *bool `json:"ramHotPlug,omitempty"` - // Hot-unplug capable RAM (no reboot required). - RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` - // Hot-plug capable NIC (no reboot required). - NicHotPlug *bool `json:"nicHotPlug,omitempty"` - // Hot-unplug capable NIC (no reboot required). - NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` - // Hot-plug capable Virt-IO drive (no reboot required). - DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` - // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. - DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` + // Human-readable description. + Description *string `json:"description,omitempty"` // Hot-plug capable SCSI drive (no reboot required). DiscScsiHotPlug *bool `json:"discScsiHotPlug,omitempty"` // Hot-unplug capable SCSI drive (no reboot required). Not supported with Windows VMs. DiscScsiHotUnplug *bool `json:"discScsiHotUnplug,omitempty"` - // The OS type of this image. - LicenceType *string `json:"licenceType"` + // Hot-plug capable Virt-IO drive (no reboot required). + DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` + // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. + DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` + // List of image aliases mapped for this image + ImageAliases *[]string `json:"imageAliases,omitempty"` // The image type. ImageType *string `json:"imageType,omitempty"` + // The OS type of this image. + LicenceType *string `json:"licenceType"` + // The location of this image/snapshot. + Location *string `json:"location,omitempty"` + // The resource name. + Name *string `json:"name,omitempty"` + // Hot-plug capable NIC (no reboot required). + NicHotPlug *bool `json:"nicHotPlug,omitempty"` + // Hot-unplug capable NIC (no reboot required). + NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` // Indicates whether the image is part of a public repository. Public *bool `json:"public,omitempty"` - // List of image aliases mapped for this image - ImageAliases *[]string `json:"imageAliases,omitempty"` - // Cloud init compatibility. - CloudInit *string `json:"cloudInit,omitempty"` + // Hot-plug capable RAM (no reboot required). + RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // Hot-unplug capable RAM (no reboot required). + RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` + // The image size in GB. + Size *float32 `json:"size,omitempty"` } // NewImageProperties instantiates a new ImageProperties object @@ -76,722 +76,722 @@ func NewImagePropertiesWithDefaults() *ImageProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetName() *string { +// GetCloudInit returns the CloudInit field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetCloudInit() *string { if o == nil { return nil } - return o.Name + return o.CloudInit } -// GetNameOk returns a tuple with the Name field value +// GetCloudInitOk returns a tuple with the CloudInit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetNameOk() (*string, bool) { +func (o *ImageProperties) GetCloudInitOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CloudInit, true } -// SetName sets field value -func (o *ImageProperties) SetName(v string) { +// SetCloudInit sets field value +func (o *ImageProperties) SetCloudInit(v string) { - o.Name = &v + o.CloudInit = &v } -// HasName returns a boolean if a field has been set. -func (o *ImageProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCloudInit returns a boolean if a field has been set. +func (o *ImageProperties) HasCloudInit() bool { + if o != nil && o.CloudInit != nil { return true } return false } -// GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetDescription() *string { +// GetCpuHotPlug returns the CpuHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetCpuHotPlug() *bool { if o == nil { return nil } - return o.Description + return o.CpuHotPlug } -// GetDescriptionOk returns a tuple with the Description field value +// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDescriptionOk() (*string, bool) { +func (o *ImageProperties) GetCpuHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Description, true + return o.CpuHotPlug, true } -// SetDescription sets field value -func (o *ImageProperties) SetDescription(v string) { +// SetCpuHotPlug sets field value +func (o *ImageProperties) SetCpuHotPlug(v bool) { - o.Description = &v + o.CpuHotPlug = &v } -// HasDescription returns a boolean if a field has been set. -func (o *ImageProperties) HasDescription() bool { - if o != nil && o.Description != nil { +// HasCpuHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasCpuHotPlug() bool { + if o != nil && o.CpuHotPlug != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetLocation() *string { +// GetCpuHotUnplug returns the CpuHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetCpuHotUnplug() *bool { if o == nil { return nil } - return o.Location + return o.CpuHotUnplug } -// GetLocationOk returns a tuple with the Location field value +// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetLocationOk() (*string, bool) { +func (o *ImageProperties) GetCpuHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Location, true + return o.CpuHotUnplug, true } -// SetLocation sets field value -func (o *ImageProperties) SetLocation(v string) { +// SetCpuHotUnplug sets field value +func (o *ImageProperties) SetCpuHotUnplug(v bool) { - o.Location = &v + o.CpuHotUnplug = &v } -// HasLocation returns a boolean if a field has been set. -func (o *ImageProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasCpuHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasCpuHotUnplug() bool { + if o != nil && o.CpuHotUnplug != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ImageProperties) GetSize() *float32 { +// GetDescription returns the Description field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDescription() *string { if o == nil { return nil } - return o.Size + return o.Description } -// GetSizeOk returns a tuple with the Size field value +// GetDescriptionOk returns a tuple with the Description field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetSizeOk() (*float32, bool) { +func (o *ImageProperties) GetDescriptionOk() (*string, bool) { if o == nil { return nil, false } - return o.Size, true + return o.Description, true } -// SetSize sets field value -func (o *ImageProperties) SetSize(v float32) { +// SetDescription sets field value +func (o *ImageProperties) SetDescription(v string) { - o.Size = &v + o.Description = &v } -// HasSize returns a boolean if a field has been set. -func (o *ImageProperties) HasSize() bool { - if o != nil && o.Size != nil { +// HasDescription returns a boolean if a field has been set. +func (o *ImageProperties) HasDescription() bool { + if o != nil && o.Description != nil { return true } return false } -// GetCpuHotPlug returns the CpuHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetCpuHotPlug() *bool { +// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscScsiHotPlug() *bool { if o == nil { return nil } - return o.CpuHotPlug + return o.DiscScsiHotPlug } -// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value +// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetCpuHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscScsiHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.CpuHotPlug, true + return o.DiscScsiHotPlug, true } -// SetCpuHotPlug sets field value -func (o *ImageProperties) SetCpuHotPlug(v bool) { +// SetDiscScsiHotPlug sets field value +func (o *ImageProperties) SetDiscScsiHotPlug(v bool) { - o.CpuHotPlug = &v + o.DiscScsiHotPlug = &v } -// HasCpuHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasCpuHotPlug() bool { - if o != nil && o.CpuHotPlug != nil { +// HasDiscScsiHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscScsiHotPlug() bool { + if o != nil && o.DiscScsiHotPlug != nil { return true } return false } -// GetCpuHotUnplug returns the CpuHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetCpuHotUnplug() *bool { +// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscScsiHotUnplug() *bool { if o == nil { return nil } - return o.CpuHotUnplug + return o.DiscScsiHotUnplug } -// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value +// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetCpuHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.CpuHotUnplug, true + return o.DiscScsiHotUnplug, true } -// SetCpuHotUnplug sets field value -func (o *ImageProperties) SetCpuHotUnplug(v bool) { +// SetDiscScsiHotUnplug sets field value +func (o *ImageProperties) SetDiscScsiHotUnplug(v bool) { - o.CpuHotUnplug = &v + o.DiscScsiHotUnplug = &v } -// HasCpuHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasCpuHotUnplug() bool { - if o != nil && o.CpuHotUnplug != nil { +// HasDiscScsiHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscScsiHotUnplug() bool { + if o != nil && o.DiscScsiHotUnplug != nil { return true } return false } -// GetRamHotPlug returns the RamHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetRamHotPlug() *bool { +// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscVirtioHotPlug() *bool { if o == nil { return nil } - return o.RamHotPlug + return o.DiscVirtioHotPlug } -// GetRamHotPlugOk returns a tuple with the RamHotPlug field value +// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetRamHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.RamHotPlug, true + return o.DiscVirtioHotPlug, true } -// SetRamHotPlug sets field value -func (o *ImageProperties) SetRamHotPlug(v bool) { +// SetDiscVirtioHotPlug sets field value +func (o *ImageProperties) SetDiscVirtioHotPlug(v bool) { - o.RamHotPlug = &v + o.DiscVirtioHotPlug = &v } -// HasRamHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasRamHotPlug() bool { - if o != nil && o.RamHotPlug != nil { +// HasDiscVirtioHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscVirtioHotPlug() bool { + if o != nil && o.DiscVirtioHotPlug != nil { return true } return false } -// GetRamHotUnplug returns the RamHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetRamHotUnplug() *bool { +// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscVirtioHotUnplug() *bool { if o == nil { return nil } - return o.RamHotUnplug + return o.DiscVirtioHotUnplug } -// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value +// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetRamHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.RamHotUnplug, true + return o.DiscVirtioHotUnplug, true } -// SetRamHotUnplug sets field value -func (o *ImageProperties) SetRamHotUnplug(v bool) { +// SetDiscVirtioHotUnplug sets field value +func (o *ImageProperties) SetDiscVirtioHotUnplug(v bool) { - o.RamHotUnplug = &v + o.DiscVirtioHotUnplug = &v } -// HasRamHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasRamHotUnplug() bool { - if o != nil && o.RamHotUnplug != nil { +// HasDiscVirtioHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscVirtioHotUnplug() bool { + if o != nil && o.DiscVirtioHotUnplug != nil { return true } return false } -// GetNicHotPlug returns the NicHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetNicHotPlug() *bool { +// GetImageAliases returns the ImageAliases field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetImageAliases() *[]string { if o == nil { return nil } - return o.NicHotPlug + return o.ImageAliases } -// GetNicHotPlugOk returns a tuple with the NicHotPlug field value +// GetImageAliasesOk returns a tuple with the ImageAliases field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetNicHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetImageAliasesOk() (*[]string, bool) { if o == nil { return nil, false } - return o.NicHotPlug, true + return o.ImageAliases, true } -// SetNicHotPlug sets field value -func (o *ImageProperties) SetNicHotPlug(v bool) { +// SetImageAliases sets field value +func (o *ImageProperties) SetImageAliases(v []string) { - o.NicHotPlug = &v + o.ImageAliases = &v } -// HasNicHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasNicHotPlug() bool { - if o != nil && o.NicHotPlug != nil { +// HasImageAliases returns a boolean if a field has been set. +func (o *ImageProperties) HasImageAliases() bool { + if o != nil && o.ImageAliases != nil { return true } return false } -// GetNicHotUnplug returns the NicHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetNicHotUnplug() *bool { +// GetImageType returns the ImageType field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetImageType() *string { if o == nil { return nil } - return o.NicHotUnplug + return o.ImageType } -// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value +// GetImageTypeOk returns a tuple with the ImageType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetNicHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetImageTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.NicHotUnplug, true + return o.ImageType, true } -// SetNicHotUnplug sets field value -func (o *ImageProperties) SetNicHotUnplug(v bool) { +// SetImageType sets field value +func (o *ImageProperties) SetImageType(v string) { - o.NicHotUnplug = &v + o.ImageType = &v } -// HasNicHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasNicHotUnplug() bool { - if o != nil && o.NicHotUnplug != nil { +// HasImageType returns a boolean if a field has been set. +func (o *ImageProperties) HasImageType() bool { + if o != nil && o.ImageType != nil { return true } return false } -// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscVirtioHotPlug() *bool { +// GetLicenceType returns the LicenceType field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetLicenceType() *string { if o == nil { return nil } - return o.DiscVirtioHotPlug + return o.LicenceType } -// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value +// GetLicenceTypeOk returns a tuple with the LicenceType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetLicenceTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotPlug, true + return o.LicenceType, true } -// SetDiscVirtioHotPlug sets field value -func (o *ImageProperties) SetDiscVirtioHotPlug(v bool) { +// SetLicenceType sets field value +func (o *ImageProperties) SetLicenceType(v string) { - o.DiscVirtioHotPlug = &v + o.LicenceType = &v } -// HasDiscVirtioHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscVirtioHotPlug() bool { - if o != nil && o.DiscVirtioHotPlug != nil { +// HasLicenceType returns a boolean if a field has been set. +func (o *ImageProperties) HasLicenceType() bool { + if o != nil && o.LicenceType != nil { return true } return false } -// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscVirtioHotUnplug() *bool { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetLocation() *string { if o == nil { return nil } - return o.DiscVirtioHotUnplug + return o.Location } -// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotUnplug, true + return o.Location, true } -// SetDiscVirtioHotUnplug sets field value -func (o *ImageProperties) SetDiscVirtioHotUnplug(v bool) { +// SetLocation sets field value +func (o *ImageProperties) SetLocation(v string) { - o.DiscVirtioHotUnplug = &v + o.Location = &v } -// HasDiscVirtioHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscVirtioHotUnplug() bool { - if o != nil && o.DiscVirtioHotUnplug != nil { +// HasLocation returns a boolean if a field has been set. +func (o *ImageProperties) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscScsiHotPlug() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetName() *string { if o == nil { return nil } - return o.DiscScsiHotPlug + return o.Name } -// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscScsiHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.DiscScsiHotPlug, true + return o.Name, true } -// SetDiscScsiHotPlug sets field value -func (o *ImageProperties) SetDiscScsiHotPlug(v bool) { +// SetName sets field value +func (o *ImageProperties) SetName(v string) { - o.DiscScsiHotPlug = &v + o.Name = &v } -// HasDiscScsiHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscScsiHotPlug() bool { - if o != nil && o.DiscScsiHotPlug != nil { +// HasName returns a boolean if a field has been set. +func (o *ImageProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscScsiHotUnplug() *bool { +// GetNicHotPlug returns the NicHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetNicHotPlug() *bool { if o == nil { return nil } - return o.DiscScsiHotUnplug + return o.NicHotPlug } -// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value +// GetNicHotPlugOk returns a tuple with the NicHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetNicHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscScsiHotUnplug, true + return o.NicHotPlug, true } -// SetDiscScsiHotUnplug sets field value -func (o *ImageProperties) SetDiscScsiHotUnplug(v bool) { +// SetNicHotPlug sets field value +func (o *ImageProperties) SetNicHotPlug(v bool) { - o.DiscScsiHotUnplug = &v + o.NicHotPlug = &v } -// HasDiscScsiHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscScsiHotUnplug() bool { - if o != nil && o.DiscScsiHotUnplug != nil { +// HasNicHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasNicHotPlug() bool { + if o != nil && o.NicHotPlug != nil { return true } return false } -// GetLicenceType returns the LicenceType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetLicenceType() *string { +// GetNicHotUnplug returns the NicHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetNicHotUnplug() *bool { if o == nil { return nil } - return o.LicenceType + return o.NicHotUnplug } -// GetLicenceTypeOk returns a tuple with the LicenceType field value +// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetLicenceTypeOk() (*string, bool) { +func (o *ImageProperties) GetNicHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.LicenceType, true + return o.NicHotUnplug, true } -// SetLicenceType sets field value -func (o *ImageProperties) SetLicenceType(v string) { +// SetNicHotUnplug sets field value +func (o *ImageProperties) SetNicHotUnplug(v bool) { - o.LicenceType = &v + o.NicHotUnplug = &v } -// HasLicenceType returns a boolean if a field has been set. -func (o *ImageProperties) HasLicenceType() bool { - if o != nil && o.LicenceType != nil { +// HasNicHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasNicHotUnplug() bool { + if o != nil && o.NicHotUnplug != nil { return true } return false } -// GetImageType returns the ImageType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetImageType() *string { +// GetPublic returns the Public field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetPublic() *bool { if o == nil { return nil } - return o.ImageType + return o.Public } -// GetImageTypeOk returns a tuple with the ImageType field value +// GetPublicOk returns a tuple with the Public field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetImageTypeOk() (*string, bool) { +func (o *ImageProperties) GetPublicOk() (*bool, bool) { if o == nil { return nil, false } - return o.ImageType, true + return o.Public, true } -// SetImageType sets field value -func (o *ImageProperties) SetImageType(v string) { +// SetPublic sets field value +func (o *ImageProperties) SetPublic(v bool) { - o.ImageType = &v + o.Public = &v } -// HasImageType returns a boolean if a field has been set. -func (o *ImageProperties) HasImageType() bool { - if o != nil && o.ImageType != nil { +// HasPublic returns a boolean if a field has been set. +func (o *ImageProperties) HasPublic() bool { + if o != nil && o.Public != nil { return true } return false } -// GetPublic returns the Public field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetPublic() *bool { +// GetRamHotPlug returns the RamHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetRamHotPlug() *bool { if o == nil { return nil } - return o.Public + return o.RamHotPlug } -// GetPublicOk returns a tuple with the Public field value +// GetRamHotPlugOk returns a tuple with the RamHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetPublicOk() (*bool, bool) { +func (o *ImageProperties) GetRamHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Public, true + return o.RamHotPlug, true } -// SetPublic sets field value -func (o *ImageProperties) SetPublic(v bool) { +// SetRamHotPlug sets field value +func (o *ImageProperties) SetRamHotPlug(v bool) { - o.Public = &v + o.RamHotPlug = &v } -// HasPublic returns a boolean if a field has been set. -func (o *ImageProperties) HasPublic() bool { - if o != nil && o.Public != nil { +// HasRamHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasRamHotPlug() bool { + if o != nil && o.RamHotPlug != nil { return true } return false } -// GetImageAliases returns the ImageAliases field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ImageProperties) GetImageAliases() *[]string { +// GetRamHotUnplug returns the RamHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetRamHotUnplug() *bool { if o == nil { return nil } - return o.ImageAliases + return o.RamHotUnplug } -// GetImageAliasesOk returns a tuple with the ImageAliases field value +// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetImageAliasesOk() (*[]string, bool) { +func (o *ImageProperties) GetRamHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.ImageAliases, true + return o.RamHotUnplug, true } -// SetImageAliases sets field value -func (o *ImageProperties) SetImageAliases(v []string) { +// SetRamHotUnplug sets field value +func (o *ImageProperties) SetRamHotUnplug(v bool) { - o.ImageAliases = &v + o.RamHotUnplug = &v } -// HasImageAliases returns a boolean if a field has been set. -func (o *ImageProperties) HasImageAliases() bool { - if o != nil && o.ImageAliases != nil { +// HasRamHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasRamHotUnplug() bool { + if o != nil && o.RamHotUnplug != nil { return true } return false } -// GetCloudInit returns the CloudInit field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetCloudInit() *string { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetSize() *float32 { if o == nil { return nil } - return o.CloudInit + return o.Size } -// GetCloudInitOk returns a tuple with the CloudInit field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetCloudInitOk() (*string, bool) { +func (o *ImageProperties) GetSizeOk() (*float32, bool) { if o == nil { return nil, false } - return o.CloudInit, true + return o.Size, true } -// SetCloudInit sets field value -func (o *ImageProperties) SetCloudInit(v string) { +// SetSize sets field value +func (o *ImageProperties) SetSize(v float32) { - o.CloudInit = &v + o.Size = &v } -// HasCloudInit returns a boolean if a field has been set. -func (o *ImageProperties) HasCloudInit() bool { - if o != nil && o.CloudInit != nil { +// HasSize returns a boolean if a field has been set. +func (o *ImageProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } @@ -800,63 +800,82 @@ func (o *ImageProperties) HasCloudInit() bool { func (o ImageProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.Description != nil { - toSerialize["description"] = o.Description - } - if o.Location != nil { - toSerialize["location"] = o.Location - } - if o.Size != nil { - toSerialize["size"] = o.Size + if o.CloudInit != nil { + toSerialize["cloudInit"] = o.CloudInit } + if o.CpuHotPlug != nil { toSerialize["cpuHotPlug"] = o.CpuHotPlug } + if o.CpuHotUnplug != nil { toSerialize["cpuHotUnplug"] = o.CpuHotUnplug } - if o.RamHotPlug != nil { - toSerialize["ramHotPlug"] = o.RamHotPlug - } - if o.RamHotUnplug != nil { - toSerialize["ramHotUnplug"] = o.RamHotUnplug + + if o.Description != nil { + toSerialize["description"] = o.Description } - if o.NicHotPlug != nil { - toSerialize["nicHotPlug"] = o.NicHotPlug + + if o.DiscScsiHotPlug != nil { + toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug } - if o.NicHotUnplug != nil { - toSerialize["nicHotUnplug"] = o.NicHotUnplug + + if o.DiscScsiHotUnplug != nil { + toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug } + if o.DiscVirtioHotPlug != nil { toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug } + if o.DiscVirtioHotUnplug != nil { toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug } - if o.DiscScsiHotPlug != nil { - toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug + + if o.ImageAliases != nil { + toSerialize["imageAliases"] = o.ImageAliases } - if o.DiscScsiHotUnplug != nil { - toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug + + if o.ImageType != nil { + toSerialize["imageType"] = o.ImageType } + if o.LicenceType != nil { toSerialize["licenceType"] = o.LicenceType } - if o.ImageType != nil { - toSerialize["imageType"] = o.ImageType + + if o.Location != nil { + toSerialize["location"] = o.Location + } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.NicHotPlug != nil { + toSerialize["nicHotPlug"] = o.NicHotPlug } + + if o.NicHotUnplug != nil { + toSerialize["nicHotUnplug"] = o.NicHotUnplug + } + if o.Public != nil { toSerialize["public"] = o.Public } - if o.ImageAliases != nil { - toSerialize["imageAliases"] = o.ImageAliases + + if o.RamHotPlug != nil { + toSerialize["ramHotPlug"] = o.RamHotPlug } - if o.CloudInit != nil { - toSerialize["cloudInit"] = o.CloudInit + + if o.RamHotUnplug != nil { + toSerialize["ramHotUnplug"] = o.RamHotUnplug } + + if o.Size != nil { + toSerialize["size"] = o.Size + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go index ff496fb19..1cec4020e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go @@ -16,14 +16,14 @@ import ( // Images struct for Images type Images struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Image `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewImages instantiates a new Images object @@ -44,152 +44,152 @@ func NewImagesWithDefaults() *Images { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Images) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Images) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetIdOk() (*string, bool) { +func (o *Images) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Images) SetId(v string) { +// SetHref sets field value +func (o *Images) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Images) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Images) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Images) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Images) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetTypeOk() (*Type, bool) { +func (o *Images) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Images) SetType(v Type) { +// SetId sets field value +func (o *Images) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Images) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Images) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Images) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Images) GetItems() *[]Image { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetHrefOk() (*string, bool) { +func (o *Images) GetItemsOk() (*[]Image, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Images) SetHref(v string) { +// SetItems sets field value +func (o *Images) SetItems(v []Image) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Images) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Images) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Image will be returned -func (o *Images) GetItems() *[]Image { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Images) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetItemsOk() (*[]Image, bool) { +func (o *Images) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Images) SetItems(v []Image) { +// SetType sets field value +func (o *Images) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Images) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Images) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Images) HasItems() bool { func (o Images) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go index 19f4a1467..2ada276b5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go @@ -43,7 +43,7 @@ func NewInfoWithDefaults() *Info { } // GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Info) GetHref() *string { if o == nil { return nil @@ -81,7 +81,7 @@ func (o *Info) HasHref() bool { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Info) GetName() *string { if o == nil { return nil @@ -119,7 +119,7 @@ func (o *Info) HasName() bool { } // GetVersion returns the Version field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Info) GetVersion() *string { if o == nil { return nil @@ -161,12 +161,15 @@ func (o Info) MarshalJSON() ([]byte, error) { if o.Href != nil { toSerialize["href"] = o.Href } + if o.Name != nil { toSerialize["name"] = o.Name } + if o.Version != nil { toSerialize["version"] = o.Version } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go index af07f6fb1..c7e16a0f2 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go @@ -16,14 +16,14 @@ import ( // IpBlock struct for IpBlock type IpBlock struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *IpBlockProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewIpBlock instantiates a new IpBlock object @@ -46,190 +46,190 @@ func NewIpBlockWithDefaults() *IpBlock { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlock) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetIdOk() (*string, bool) { +func (o *IpBlock) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *IpBlock) SetId(v string) { +// SetHref sets field value +func (o *IpBlock) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *IpBlock) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *IpBlock) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *IpBlock) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetTypeOk() (*Type, bool) { +func (o *IpBlock) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *IpBlock) SetType(v Type) { +// SetId sets field value +func (o *IpBlock) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *IpBlock) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *IpBlock) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlock) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetHrefOk() (*string, bool) { +func (o *IpBlock) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *IpBlock) SetHref(v string) { +// SetMetadata sets field value +func (o *IpBlock) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *IpBlock) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *IpBlock) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *IpBlock) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetProperties() *IpBlockProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *IpBlock) GetPropertiesOk() (*IpBlockProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *IpBlock) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *IpBlock) SetProperties(v IpBlockProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *IpBlock) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *IpBlock) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for IpBlockProperties will be returned -func (o *IpBlock) GetProperties() *IpBlockProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetPropertiesOk() (*IpBlockProperties, bool) { +func (o *IpBlock) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *IpBlock) SetProperties(v IpBlockProperties) { +// SetType sets field value +func (o *IpBlock) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *IpBlock) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *IpBlock) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *IpBlock) HasProperties() bool { func (o IpBlock) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go index 4f732b53b..19c3ed757 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go @@ -16,16 +16,16 @@ import ( // IpBlockProperties struct for IpBlockProperties type IpBlockProperties struct { + // Read-Only attribute. Lists consumption detail for an individual IP + IpConsumers *[]IpConsumer `json:"ipConsumers,omitempty"` // Collection of IPs, associated with the IP Block. Ips *[]string `json:"ips,omitempty"` // Location of that IP block. Property cannot be modified after it is created (disallowed in update requests). Location *string `json:"location"` - // The size of the IP block. - Size *int32 `json:"size"` // The name of the resource. Name *string `json:"name,omitempty"` - // Read-Only attribute. Lists consumption detail for an individual IP - IpConsumers *[]IpConsumer `json:"ipConsumers,omitempty"` + // The size of the IP block. + Size *int32 `json:"size"` } // NewIpBlockProperties instantiates a new IpBlockProperties object @@ -49,114 +49,114 @@ func NewIpBlockPropertiesWithDefaults() *IpBlockProperties { return &this } -// GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *IpBlockProperties) GetIps() *[]string { +// GetIpConsumers returns the IpConsumers field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetIpConsumers() *[]IpConsumer { if o == nil { return nil } - return o.Ips + return o.IpConsumers } -// GetIpsOk returns a tuple with the Ips field value +// GetIpConsumersOk returns a tuple with the IpConsumers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetIpsOk() (*[]string, bool) { +func (o *IpBlockProperties) GetIpConsumersOk() (*[]IpConsumer, bool) { if o == nil { return nil, false } - return o.Ips, true + return o.IpConsumers, true } -// SetIps sets field value -func (o *IpBlockProperties) SetIps(v []string) { +// SetIpConsumers sets field value +func (o *IpBlockProperties) SetIpConsumers(v []IpConsumer) { - o.Ips = &v + o.IpConsumers = &v } -// HasIps returns a boolean if a field has been set. -func (o *IpBlockProperties) HasIps() bool { - if o != nil && o.Ips != nil { +// HasIpConsumers returns a boolean if a field has been set. +func (o *IpBlockProperties) HasIpConsumers() bool { + if o != nil && o.IpConsumers != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlockProperties) GetLocation() *string { +// GetIps returns the Ips field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetIps() *[]string { if o == nil { return nil } - return o.Location + return o.Ips } -// GetLocationOk returns a tuple with the Location field value +// GetIpsOk returns a tuple with the Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetLocationOk() (*string, bool) { +func (o *IpBlockProperties) GetIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Ips, true } -// SetLocation sets field value -func (o *IpBlockProperties) SetLocation(v string) { +// SetIps sets field value +func (o *IpBlockProperties) SetIps(v []string) { - o.Location = &v + o.Ips = &v } -// HasLocation returns a boolean if a field has been set. -func (o *IpBlockProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasIps returns a boolean if a field has been set. +func (o *IpBlockProperties) HasIps() bool { + if o != nil && o.Ips != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *IpBlockProperties) GetSize() *int32 { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetLocation() *string { if o == nil { return nil } - return o.Size + return o.Location } -// GetSizeOk returns a tuple with the Size field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetSizeOk() (*int32, bool) { +func (o *IpBlockProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.Size, true + return o.Location, true } -// SetSize sets field value -func (o *IpBlockProperties) SetSize(v int32) { +// SetLocation sets field value +func (o *IpBlockProperties) SetLocation(v string) { - o.Size = &v + o.Location = &v } -// HasSize returns a boolean if a field has been set. -func (o *IpBlockProperties) HasSize() bool { - if o != nil && o.Size != nil { +// HasLocation returns a boolean if a field has been set. +func (o *IpBlockProperties) HasLocation() bool { + if o != nil && o.Location != nil { return true } @@ -164,7 +164,7 @@ func (o *IpBlockProperties) HasSize() bool { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *IpBlockProperties) GetName() *string { if o == nil { return nil @@ -201,38 +201,38 @@ func (o *IpBlockProperties) HasName() bool { return false } -// GetIpConsumers returns the IpConsumers field value -// If the value is explicit nil, the zero value for []IpConsumer will be returned -func (o *IpBlockProperties) GetIpConsumers() *[]IpConsumer { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetSize() *int32 { if o == nil { return nil } - return o.IpConsumers + return o.Size } -// GetIpConsumersOk returns a tuple with the IpConsumers field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetIpConsumersOk() (*[]IpConsumer, bool) { +func (o *IpBlockProperties) GetSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.IpConsumers, true + return o.Size, true } -// SetIpConsumers sets field value -func (o *IpBlockProperties) SetIpConsumers(v []IpConsumer) { +// SetSize sets field value +func (o *IpBlockProperties) SetSize(v int32) { - o.IpConsumers = &v + o.Size = &v } -// HasIpConsumers returns a boolean if a field has been set. -func (o *IpBlockProperties) HasIpConsumers() bool { - if o != nil && o.IpConsumers != nil { +// HasSize returns a boolean if a field has been set. +func (o *IpBlockProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } @@ -241,21 +241,26 @@ func (o *IpBlockProperties) HasIpConsumers() bool { func (o IpBlockProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.IpConsumers != nil { + toSerialize["ipConsumers"] = o.IpConsumers + } + if o.Ips != nil { toSerialize["ips"] = o.Ips } + if o.Location != nil { toSerialize["location"] = o.Location } - if o.Size != nil { - toSerialize["size"] = o.Size - } + if o.Name != nil { toSerialize["name"] = o.Name } - if o.IpConsumers != nil { - toSerialize["ipConsumers"] = o.IpConsumers + + if o.Size != nil { + toSerialize["size"] = o.Size } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go index 010dc17fe..117235c82 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go @@ -16,19 +16,19 @@ import ( // IpBlocks struct for IpBlocks type IpBlocks struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]IpBlock `json:"items,omitempty"` + // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). + Limit *float32 `json:"limit,omitempty"` // The offset, specified in the request (if not is specified, 0 is used by default). Offset *float32 `json:"offset,omitempty"` - // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewIpBlocks instantiates a new IpBlocks object @@ -49,114 +49,114 @@ func NewIpBlocksWithDefaults() *IpBlocks { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlocks) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetIdOk() (*string, bool) { +func (o *IpBlocks) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *IpBlocks) SetId(v string) { +// SetLinks sets field value +func (o *IpBlocks) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *IpBlocks) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *IpBlocks) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *IpBlocks) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetTypeOk() (*Type, bool) { +func (o *IpBlocks) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *IpBlocks) SetType(v Type) { +// SetHref sets field value +func (o *IpBlocks) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *IpBlocks) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *IpBlocks) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlocks) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetHrefOk() (*string, bool) { +func (o *IpBlocks) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *IpBlocks) SetHref(v string) { +// SetId sets field value +func (o *IpBlocks) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *IpBlocks) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *IpBlocks) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *IpBlocks) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []IpBlock will be returned +// If the value is explicit nil, nil is returned func (o *IpBlocks) GetItems() *[]IpBlock { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *IpBlocks) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *IpBlocks) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetOffsetOk() (*float32, bool) { +func (o *IpBlocks) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *IpBlocks) SetOffset(v float32) { +// SetLimit sets field value +func (o *IpBlocks) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *IpBlocks) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *IpBlocks) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *IpBlocks) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetLimitOk() (*float32, bool) { +func (o *IpBlocks) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *IpBlocks) SetLimit(v float32) { +// SetOffset sets field value +func (o *IpBlocks) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *IpBlocks) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *IpBlocks) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *IpBlocks) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetLinksOk() (*PaginationLinks, bool) { +func (o *IpBlocks) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *IpBlocks) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *IpBlocks) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *IpBlocks) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *IpBlocks) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *IpBlocks) HasLinks() bool { func (o IpBlocks) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go index a0e9e55c6..e405979fe 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go @@ -16,15 +16,15 @@ import ( // IpConsumer struct for IpConsumer type IpConsumer struct { + DatacenterId *string `json:"datacenterId,omitempty"` + DatacenterName *string `json:"datacenterName,omitempty"` Ip *string `json:"ip,omitempty"` + K8sClusterUuid *string `json:"k8sClusterUuid,omitempty"` + K8sNodePoolUuid *string `json:"k8sNodePoolUuid,omitempty"` Mac *string `json:"mac,omitempty"` NicId *string `json:"nicId,omitempty"` ServerId *string `json:"serverId,omitempty"` ServerName *string `json:"serverName,omitempty"` - DatacenterId *string `json:"datacenterId,omitempty"` - DatacenterName *string `json:"datacenterName,omitempty"` - K8sNodePoolUuid *string `json:"k8sNodePoolUuid,omitempty"` - K8sClusterUuid *string `json:"k8sClusterUuid,omitempty"` } // NewIpConsumer instantiates a new IpConsumer object @@ -45,342 +45,342 @@ func NewIpConsumerWithDefaults() *IpConsumer { return &this } -// GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetIp() *string { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetDatacenterId() *string { if o == nil { return nil } - return o.Ip + return o.DatacenterId } -// GetIpOk returns a tuple with the Ip field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetIpOk() (*string, bool) { +func (o *IpConsumer) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Ip, true + return o.DatacenterId, true } -// SetIp sets field value -func (o *IpConsumer) SetIp(v string) { +// SetDatacenterId sets field value +func (o *IpConsumer) SetDatacenterId(v string) { - o.Ip = &v + o.DatacenterId = &v } -// HasIp returns a boolean if a field has been set. -func (o *IpConsumer) HasIp() bool { - if o != nil && o.Ip != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *IpConsumer) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetMac returns the Mac field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetMac() *string { +// GetDatacenterName returns the DatacenterName field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetDatacenterName() *string { if o == nil { return nil } - return o.Mac + return o.DatacenterName } -// GetMacOk returns a tuple with the Mac field value +// GetDatacenterNameOk returns a tuple with the DatacenterName field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetMacOk() (*string, bool) { +func (o *IpConsumer) GetDatacenterNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Mac, true + return o.DatacenterName, true } -// SetMac sets field value -func (o *IpConsumer) SetMac(v string) { +// SetDatacenterName sets field value +func (o *IpConsumer) SetDatacenterName(v string) { - o.Mac = &v + o.DatacenterName = &v } -// HasMac returns a boolean if a field has been set. -func (o *IpConsumer) HasMac() bool { - if o != nil && o.Mac != nil { +// HasDatacenterName returns a boolean if a field has been set. +func (o *IpConsumer) HasDatacenterName() bool { + if o != nil && o.DatacenterName != nil { return true } return false } -// GetNicId returns the NicId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetNicId() *string { +// GetIp returns the Ip field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetIp() *string { if o == nil { return nil } - return o.NicId + return o.Ip } -// GetNicIdOk returns a tuple with the NicId field value +// GetIpOk returns a tuple with the Ip field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetNicIdOk() (*string, bool) { +func (o *IpConsumer) GetIpOk() (*string, bool) { if o == nil { return nil, false } - return o.NicId, true + return o.Ip, true } -// SetNicId sets field value -func (o *IpConsumer) SetNicId(v string) { +// SetIp sets field value +func (o *IpConsumer) SetIp(v string) { - o.NicId = &v + o.Ip = &v } -// HasNicId returns a boolean if a field has been set. -func (o *IpConsumer) HasNicId() bool { - if o != nil && o.NicId != nil { +// HasIp returns a boolean if a field has been set. +func (o *IpConsumer) HasIp() bool { + if o != nil && o.Ip != nil { return true } return false } -// GetServerId returns the ServerId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetServerId() *string { +// GetK8sClusterUuid returns the K8sClusterUuid field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetK8sClusterUuid() *string { if o == nil { return nil } - return o.ServerId + return o.K8sClusterUuid } -// GetServerIdOk returns a tuple with the ServerId field value +// GetK8sClusterUuidOk returns a tuple with the K8sClusterUuid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetServerIdOk() (*string, bool) { +func (o *IpConsumer) GetK8sClusterUuidOk() (*string, bool) { if o == nil { return nil, false } - return o.ServerId, true + return o.K8sClusterUuid, true } -// SetServerId sets field value -func (o *IpConsumer) SetServerId(v string) { +// SetK8sClusterUuid sets field value +func (o *IpConsumer) SetK8sClusterUuid(v string) { - o.ServerId = &v + o.K8sClusterUuid = &v } -// HasServerId returns a boolean if a field has been set. -func (o *IpConsumer) HasServerId() bool { - if o != nil && o.ServerId != nil { +// HasK8sClusterUuid returns a boolean if a field has been set. +func (o *IpConsumer) HasK8sClusterUuid() bool { + if o != nil && o.K8sClusterUuid != nil { return true } return false } -// GetServerName returns the ServerName field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetServerName() *string { +// GetK8sNodePoolUuid returns the K8sNodePoolUuid field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetK8sNodePoolUuid() *string { if o == nil { return nil } - return o.ServerName + return o.K8sNodePoolUuid } -// GetServerNameOk returns a tuple with the ServerName field value +// GetK8sNodePoolUuidOk returns a tuple with the K8sNodePoolUuid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetServerNameOk() (*string, bool) { +func (o *IpConsumer) GetK8sNodePoolUuidOk() (*string, bool) { if o == nil { return nil, false } - return o.ServerName, true + return o.K8sNodePoolUuid, true } -// SetServerName sets field value -func (o *IpConsumer) SetServerName(v string) { +// SetK8sNodePoolUuid sets field value +func (o *IpConsumer) SetK8sNodePoolUuid(v string) { - o.ServerName = &v + o.K8sNodePoolUuid = &v } -// HasServerName returns a boolean if a field has been set. -func (o *IpConsumer) HasServerName() bool { - if o != nil && o.ServerName != nil { +// HasK8sNodePoolUuid returns a boolean if a field has been set. +func (o *IpConsumer) HasK8sNodePoolUuid() bool { + if o != nil && o.K8sNodePoolUuid != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetDatacenterId() *string { +// GetMac returns the Mac field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetMac() *string { if o == nil { return nil } - return o.DatacenterId + return o.Mac } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetMacOk returns a tuple with the Mac field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetDatacenterIdOk() (*string, bool) { +func (o *IpConsumer) GetMacOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.Mac, true } -// SetDatacenterId sets field value -func (o *IpConsumer) SetDatacenterId(v string) { +// SetMac sets field value +func (o *IpConsumer) SetMac(v string) { - o.DatacenterId = &v + o.Mac = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *IpConsumer) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasMac returns a boolean if a field has been set. +func (o *IpConsumer) HasMac() bool { + if o != nil && o.Mac != nil { return true } return false } -// GetDatacenterName returns the DatacenterName field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetDatacenterName() *string { +// GetNicId returns the NicId field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetNicId() *string { if o == nil { return nil } - return o.DatacenterName + return o.NicId } -// GetDatacenterNameOk returns a tuple with the DatacenterName field value +// GetNicIdOk returns a tuple with the NicId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetDatacenterNameOk() (*string, bool) { +func (o *IpConsumer) GetNicIdOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterName, true + return o.NicId, true } -// SetDatacenterName sets field value -func (o *IpConsumer) SetDatacenterName(v string) { +// SetNicId sets field value +func (o *IpConsumer) SetNicId(v string) { - o.DatacenterName = &v + o.NicId = &v } -// HasDatacenterName returns a boolean if a field has been set. -func (o *IpConsumer) HasDatacenterName() bool { - if o != nil && o.DatacenterName != nil { +// HasNicId returns a boolean if a field has been set. +func (o *IpConsumer) HasNicId() bool { + if o != nil && o.NicId != nil { return true } return false } -// GetK8sNodePoolUuid returns the K8sNodePoolUuid field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetK8sNodePoolUuid() *string { +// GetServerId returns the ServerId field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetServerId() *string { if o == nil { return nil } - return o.K8sNodePoolUuid + return o.ServerId } -// GetK8sNodePoolUuidOk returns a tuple with the K8sNodePoolUuid field value +// GetServerIdOk returns a tuple with the ServerId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetK8sNodePoolUuidOk() (*string, bool) { +func (o *IpConsumer) GetServerIdOk() (*string, bool) { if o == nil { return nil, false } - return o.K8sNodePoolUuid, true + return o.ServerId, true } -// SetK8sNodePoolUuid sets field value -func (o *IpConsumer) SetK8sNodePoolUuid(v string) { +// SetServerId sets field value +func (o *IpConsumer) SetServerId(v string) { - o.K8sNodePoolUuid = &v + o.ServerId = &v } -// HasK8sNodePoolUuid returns a boolean if a field has been set. -func (o *IpConsumer) HasK8sNodePoolUuid() bool { - if o != nil && o.K8sNodePoolUuid != nil { +// HasServerId returns a boolean if a field has been set. +func (o *IpConsumer) HasServerId() bool { + if o != nil && o.ServerId != nil { return true } return false } -// GetK8sClusterUuid returns the K8sClusterUuid field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetK8sClusterUuid() *string { +// GetServerName returns the ServerName field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetServerName() *string { if o == nil { return nil } - return o.K8sClusterUuid + return o.ServerName } -// GetK8sClusterUuidOk returns a tuple with the K8sClusterUuid field value +// GetServerNameOk returns a tuple with the ServerName field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetK8sClusterUuidOk() (*string, bool) { +func (o *IpConsumer) GetServerNameOk() (*string, bool) { if o == nil { return nil, false } - return o.K8sClusterUuid, true + return o.ServerName, true } -// SetK8sClusterUuid sets field value -func (o *IpConsumer) SetK8sClusterUuid(v string) { +// SetServerName sets field value +func (o *IpConsumer) SetServerName(v string) { - o.K8sClusterUuid = &v + o.ServerName = &v } -// HasK8sClusterUuid returns a boolean if a field has been set. -func (o *IpConsumer) HasK8sClusterUuid() bool { - if o != nil && o.K8sClusterUuid != nil { +// HasServerName returns a boolean if a field has been set. +func (o *IpConsumer) HasServerName() bool { + if o != nil && o.ServerName != nil { return true } @@ -389,33 +389,42 @@ func (o *IpConsumer) HasK8sClusterUuid() bool { func (o IpConsumer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.DatacenterId != nil { + toSerialize["datacenterId"] = o.DatacenterId + } + + if o.DatacenterName != nil { + toSerialize["datacenterName"] = o.DatacenterName + } + if o.Ip != nil { toSerialize["ip"] = o.Ip } + + if o.K8sClusterUuid != nil { + toSerialize["k8sClusterUuid"] = o.K8sClusterUuid + } + + if o.K8sNodePoolUuid != nil { + toSerialize["k8sNodePoolUuid"] = o.K8sNodePoolUuid + } + if o.Mac != nil { toSerialize["mac"] = o.Mac } + if o.NicId != nil { toSerialize["nicId"] = o.NicId } + if o.ServerId != nil { toSerialize["serverId"] = o.ServerId } + if o.ServerName != nil { toSerialize["serverName"] = o.ServerName } - if o.DatacenterId != nil { - toSerialize["datacenterId"] = o.DatacenterId - } - if o.DatacenterName != nil { - toSerialize["datacenterName"] = o.DatacenterName - } - if o.K8sNodePoolUuid != nil { - toSerialize["k8sNodePoolUuid"] = o.K8sNodePoolUuid - } - if o.K8sClusterUuid != nil { - toSerialize["k8sClusterUuid"] = o.K8sClusterUuid - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go index 16677e73e..60c902a97 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go @@ -39,7 +39,7 @@ func NewIPFailoverWithDefaults() *IPFailover { } // GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *IPFailover) GetIp() *string { if o == nil { return nil @@ -77,7 +77,7 @@ func (o *IPFailover) HasIp() bool { } // GetNicUuid returns the NicUuid field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *IPFailover) GetNicUuid() *string { if o == nil { return nil @@ -119,9 +119,11 @@ func (o IPFailover) MarshalJSON() ([]byte, error) { if o.Ip != nil { toSerialize["ip"] = o.Ip } + if o.NicUuid != nil { toSerialize["nicUuid"] = o.NicUuid } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go index 24f95d7b3..49d9b3e86 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go @@ -16,21 +16,21 @@ import ( // KubernetesAutoScaling struct for KubernetesAutoScaling type KubernetesAutoScaling struct { - // The minimum number of working nodes that the managed node pool can scale must be >= 1 and >= nodeCount. Required if autoScaling is specified. - MinNodeCount *int32 `json:"minNodeCount"` // The maximum number of worker nodes that the managed node pool can scale in. Must be >= minNodeCount and must be >= nodeCount. Required if autoScaling is specified. MaxNodeCount *int32 `json:"maxNodeCount"` + // The minimum number of working nodes that the managed node pool can scale must be >= 1 and >= nodeCount. Required if autoScaling is specified. + MinNodeCount *int32 `json:"minNodeCount"` } // NewKubernetesAutoScaling instantiates a new KubernetesAutoScaling object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesAutoScaling(minNodeCount int32, maxNodeCount int32) *KubernetesAutoScaling { +func NewKubernetesAutoScaling(maxNodeCount int32, minNodeCount int32) *KubernetesAutoScaling { this := KubernetesAutoScaling{} - this.MinNodeCount = &minNodeCount this.MaxNodeCount = &maxNodeCount + this.MinNodeCount = &minNodeCount return &this } @@ -43,76 +43,76 @@ func NewKubernetesAutoScalingWithDefaults() *KubernetesAutoScaling { return &this } -// GetMinNodeCount returns the MinNodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesAutoScaling) GetMinNodeCount() *int32 { +// GetMaxNodeCount returns the MaxNodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesAutoScaling) GetMaxNodeCount() *int32 { if o == nil { return nil } - return o.MinNodeCount + return o.MaxNodeCount } -// GetMinNodeCountOk returns a tuple with the MinNodeCount field value +// GetMaxNodeCountOk returns a tuple with the MaxNodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesAutoScaling) GetMinNodeCountOk() (*int32, bool) { +func (o *KubernetesAutoScaling) GetMaxNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.MinNodeCount, true + return o.MaxNodeCount, true } -// SetMinNodeCount sets field value -func (o *KubernetesAutoScaling) SetMinNodeCount(v int32) { +// SetMaxNodeCount sets field value +func (o *KubernetesAutoScaling) SetMaxNodeCount(v int32) { - o.MinNodeCount = &v + o.MaxNodeCount = &v } -// HasMinNodeCount returns a boolean if a field has been set. -func (o *KubernetesAutoScaling) HasMinNodeCount() bool { - if o != nil && o.MinNodeCount != nil { +// HasMaxNodeCount returns a boolean if a field has been set. +func (o *KubernetesAutoScaling) HasMaxNodeCount() bool { + if o != nil && o.MaxNodeCount != nil { return true } return false } -// GetMaxNodeCount returns the MaxNodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesAutoScaling) GetMaxNodeCount() *int32 { +// GetMinNodeCount returns the MinNodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesAutoScaling) GetMinNodeCount() *int32 { if o == nil { return nil } - return o.MaxNodeCount + return o.MinNodeCount } -// GetMaxNodeCountOk returns a tuple with the MaxNodeCount field value +// GetMinNodeCountOk returns a tuple with the MinNodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesAutoScaling) GetMaxNodeCountOk() (*int32, bool) { +func (o *KubernetesAutoScaling) GetMinNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.MaxNodeCount, true + return o.MinNodeCount, true } -// SetMaxNodeCount sets field value -func (o *KubernetesAutoScaling) SetMaxNodeCount(v int32) { +// SetMinNodeCount sets field value +func (o *KubernetesAutoScaling) SetMinNodeCount(v int32) { - o.MaxNodeCount = &v + o.MinNodeCount = &v } -// HasMaxNodeCount returns a boolean if a field has been set. -func (o *KubernetesAutoScaling) HasMaxNodeCount() bool { - if o != nil && o.MaxNodeCount != nil { +// HasMinNodeCount returns a boolean if a field has been set. +func (o *KubernetesAutoScaling) HasMinNodeCount() bool { + if o != nil && o.MinNodeCount != nil { return true } @@ -121,12 +121,14 @@ func (o *KubernetesAutoScaling) HasMaxNodeCount() bool { func (o KubernetesAutoScaling) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.MinNodeCount != nil { - toSerialize["minNodeCount"] = o.MinNodeCount - } if o.MaxNodeCount != nil { toSerialize["maxNodeCount"] = o.MaxNodeCount } + + if o.MinNodeCount != nil { + toSerialize["minNodeCount"] = o.MinNodeCount + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go index 631bda922..994a6ac28 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go @@ -16,15 +16,15 @@ import ( // KubernetesCluster struct for KubernetesCluster type KubernetesCluster struct { - // The resource unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` + Entities *KubernetesClusterEntities `json:"entities,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesClusterProperties `json:"properties"` - Entities *KubernetesClusterEntities `json:"entities,omitempty"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesCluster instantiates a new KubernetesCluster object @@ -47,114 +47,114 @@ func NewKubernetesClusterWithDefaults() *KubernetesCluster { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesCluster) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetEntities() *KubernetesClusterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetIdOk() (*string, bool) { +func (o *KubernetesCluster) GetEntitiesOk() (*KubernetesClusterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *KubernetesCluster) SetId(v string) { +// SetEntities sets field value +func (o *KubernetesCluster) SetEntities(v KubernetesClusterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesCluster) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *KubernetesCluster) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesCluster) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetTypeOk() (*string, bool) { +func (o *KubernetesCluster) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *KubernetesCluster) SetType(v string) { +// SetHref sets field value +func (o *KubernetesCluster) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesCluster) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesCluster) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesCluster) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetHrefOk() (*string, bool) { +func (o *KubernetesCluster) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *KubernetesCluster) SetHref(v string) { +// SetId sets field value +func (o *KubernetesCluster) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesCluster) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesCluster) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *KubernetesCluster) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesCluster) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *KubernetesCluster) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesClusterProperties will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesCluster) GetProperties() *KubernetesClusterProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *KubernetesCluster) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for KubernetesClusterEntities will be returned -func (o *KubernetesCluster) GetEntities() *KubernetesClusterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetType() *string { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetEntitiesOk() (*KubernetesClusterEntities, bool) { +func (o *KubernetesCluster) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *KubernetesCluster) SetEntities(v KubernetesClusterEntities) { +// SetType sets field value +func (o *KubernetesCluster) SetType(v string) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *KubernetesCluster) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesCluster) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *KubernetesCluster) HasEntities() bool { func (o KubernetesCluster) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go index 3e5dbaf4d..0e7daca34 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go @@ -38,7 +38,7 @@ func NewKubernetesClusterEntitiesWithDefaults() *KubernetesClusterEntities { } // GetNodepools returns the Nodepools field value -// If the value is explicit nil, the zero value for KubernetesNodePools will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterEntities) GetNodepools() *KubernetesNodePools { if o == nil { return nil @@ -80,6 +80,7 @@ func (o KubernetesClusterEntities) MarshalJSON() ([]byte, error) { if o.Nodepools != nil { toSerialize["nodepools"] = o.Nodepools } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go index 1fbe331ad..cf2d02e62 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go @@ -16,15 +16,15 @@ import ( // KubernetesClusterForPost struct for KubernetesClusterForPost type KubernetesClusterForPost struct { - // The resource unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` + Entities *KubernetesClusterEntities `json:"entities,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesClusterPropertiesForPost `json:"properties"` - Entities *KubernetesClusterEntities `json:"entities,omitempty"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesClusterForPost instantiates a new KubernetesClusterForPost object @@ -47,114 +47,114 @@ func NewKubernetesClusterForPostWithDefaults() *KubernetesClusterForPost { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPost) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetEntities() *KubernetesClusterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetIdOk() (*string, bool) { +func (o *KubernetesClusterForPost) GetEntitiesOk() (*KubernetesClusterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *KubernetesClusterForPost) SetId(v string) { +// SetEntities sets field value +func (o *KubernetesClusterForPost) SetEntities(v KubernetesClusterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPost) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetTypeOk() (*string, bool) { +func (o *KubernetesClusterForPost) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *KubernetesClusterForPost) SetType(v string) { +// SetHref sets field value +func (o *KubernetesClusterForPost) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPost) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetHrefOk() (*string, bool) { +func (o *KubernetesClusterForPost) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *KubernetesClusterForPost) SetHref(v string) { +// SetId sets field value +func (o *KubernetesClusterForPost) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *KubernetesClusterForPost) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPost) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *KubernetesClusterForPost) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesClusterPropertiesForPost will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPost) GetProperties() *KubernetesClusterPropertiesForPost { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *KubernetesClusterForPost) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for KubernetesClusterEntities will be returned -func (o *KubernetesClusterForPost) GetEntities() *KubernetesClusterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetType() *string { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetEntitiesOk() (*KubernetesClusterEntities, bool) { +func (o *KubernetesClusterForPost) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *KubernetesClusterForPost) SetEntities(v KubernetesClusterEntities) { +// SetType sets field value +func (o *KubernetesClusterForPost) SetType(v string) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *KubernetesClusterForPost) HasEntities() bool { func (o KubernetesClusterForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go index 2873bf5c8..6edf7ca5f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go @@ -16,15 +16,15 @@ import ( // KubernetesClusterForPut struct for KubernetesClusterForPut type KubernetesClusterForPut struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object. - Type *string `json:"type,omitempty"` + Entities *KubernetesClusterEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesClusterPropertiesForPut `json:"properties"` - Entities *KubernetesClusterEntities `json:"entities,omitempty"` + // The type of object. + Type *string `json:"type,omitempty"` } // NewKubernetesClusterForPut instantiates a new KubernetesClusterForPut object @@ -47,114 +47,114 @@ func NewKubernetesClusterForPutWithDefaults() *KubernetesClusterForPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPut) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetEntities() *KubernetesClusterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetIdOk() (*string, bool) { +func (o *KubernetesClusterForPut) GetEntitiesOk() (*KubernetesClusterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *KubernetesClusterForPut) SetId(v string) { +// SetEntities sets field value +func (o *KubernetesClusterForPut) SetEntities(v KubernetesClusterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPut) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetTypeOk() (*string, bool) { +func (o *KubernetesClusterForPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *KubernetesClusterForPut) SetType(v string) { +// SetHref sets field value +func (o *KubernetesClusterForPut) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPut) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetHrefOk() (*string, bool) { +func (o *KubernetesClusterForPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *KubernetesClusterForPut) SetHref(v string) { +// SetId sets field value +func (o *KubernetesClusterForPut) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *KubernetesClusterForPut) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPut) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *KubernetesClusterForPut) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesClusterPropertiesForPut will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPut) GetProperties() *KubernetesClusterPropertiesForPut { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *KubernetesClusterForPut) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for KubernetesClusterEntities will be returned -func (o *KubernetesClusterForPut) GetEntities() *KubernetesClusterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetType() *string { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetEntitiesOk() (*KubernetesClusterEntities, bool) { +func (o *KubernetesClusterForPut) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *KubernetesClusterForPut) SetEntities(v KubernetesClusterEntities) { +// SetType sets field value +func (o *KubernetesClusterForPut) SetType(v string) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *KubernetesClusterForPut) HasEntities() bool { func (o KubernetesClusterForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go index d88717362..ed0629c7f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go @@ -16,19 +16,27 @@ import ( // KubernetesClusterProperties struct for KubernetesClusterProperties type KubernetesClusterProperties struct { - // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` - // The Kubernetes version the cluster is running. This imposes restrictions on what Kubernetes versions can be run in a cluster's nodepools. Additionally, not all Kubernetes versions are viable upgrade targets for all prior versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - // List of available versions for upgrading the cluster - AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` - // List of versions that may be used for node pools under this cluster - ViableNodePoolVersions *[]string `json:"viableNodePoolVersions,omitempty"` // Access to the K8s API server is restricted to these CIDRs. Traffic, internal to the cluster, is not affected by this restriction. If no allowlist is specified, access is not restricted. If an IP without subnet mask is provided, the default value is used: 32 for IPv4 and 128 for IPv6. ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` + // List of available versions for upgrading the cluster + AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` + // The Kubernetes version the cluster is running. This imposes restrictions on what Kubernetes versions can be run in a cluster's nodepools. Additionally, not all Kubernetes versions are viable upgrade targets for all prior versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // The location of the cluster if the cluster is private. This property is immutable. The location must be enabled for your contract or you must have a Datacenter within that location. This attribute is mandatory if the cluster is private. + Location *string `json:"location,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` + // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` + // The nat gateway IP of the cluster if the cluster is private. This property is immutable. Must be a reserved IP in the same location as the cluster's location. This attribute is mandatory if the cluster is private. + NatGatewayIp *string `json:"natGatewayIp,omitempty"` + // The node subnet of the cluster, if the cluster is private. This property is optional and immutable. Must be a valid CIDR notation for an IPv4 network prefix of 16 bits length. + NodeSubnet *string `json:"nodeSubnet,omitempty"` + // The indicator if the cluster is public or private. Be aware that setting it to false is currently in beta phase. + Public *bool `json:"public,omitempty"` // List of S3 bucket configured for K8s usage. For now it contains only an S3 bucket used to store K8s API audit logs S3Buckets *[]S3Bucket `json:"s3Buckets,omitempty"` + // List of versions that may be used for node pools under this cluster + ViableNodePoolVersions *[]string `json:"viableNodePoolVersions,omitempty"` } // NewKubernetesClusterProperties instantiates a new KubernetesClusterProperties object @@ -39,6 +47,8 @@ func NewKubernetesClusterProperties(name string) *KubernetesClusterProperties { this := KubernetesClusterProperties{} this.Name = &name + var public bool = true + this.Public = &public return &this } @@ -48,41 +58,81 @@ func NewKubernetesClusterProperties(name string) *KubernetesClusterProperties { // but it doesn't guarantee that properties required by API are set func NewKubernetesClusterPropertiesWithDefaults() *KubernetesClusterProperties { this := KubernetesClusterProperties{} + var public bool = true + this.Public = &public return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterProperties) GetName() *string { +// GetApiSubnetAllowList returns the ApiSubnetAllowList field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetApiSubnetAllowList() *[]string { if o == nil { return nil } - return o.Name + return o.ApiSubnetAllowList } -// GetNameOk returns a tuple with the Name field value +// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetNameOk() (*string, bool) { +func (o *KubernetesClusterProperties) GetApiSubnetAllowListOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ApiSubnetAllowList, true } -// SetName sets field value -func (o *KubernetesClusterProperties) SetName(v string) { +// SetApiSubnetAllowList sets field value +func (o *KubernetesClusterProperties) SetApiSubnetAllowList(v []string) { - o.Name = &v + o.ApiSubnetAllowList = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasApiSubnetAllowList returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasApiSubnetAllowList() bool { + if o != nil && o.ApiSubnetAllowList != nil { + return true + } + + return false +} + +// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetAvailableUpgradeVersions() *[]string { + if o == nil { + return nil + } + + return o.AvailableUpgradeVersions + +} + +// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { + if o == nil { + return nil, false + } + + return o.AvailableUpgradeVersions, true +} + +// SetAvailableUpgradeVersions sets field value +func (o *KubernetesClusterProperties) SetAvailableUpgradeVersions(v []string) { + + o.AvailableUpgradeVersions = &v + +} + +// HasAvailableUpgradeVersions returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasAvailableUpgradeVersions() bool { + if o != nil && o.AvailableUpgradeVersions != nil { return true } @@ -90,7 +140,7 @@ func (o *KubernetesClusterProperties) HasName() bool { } // GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterProperties) GetK8sVersion() *string { if o == nil { return nil @@ -127,8 +177,46 @@ func (o *KubernetesClusterProperties) HasK8sVersion() bool { return false } +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetLocation() *string { + if o == nil { + return nil + } + + return o.Location + +} + +// GetLocationOk returns a tuple with the Location field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterProperties) GetLocationOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Location, true +} + +// SetLocation sets field value +func (o *KubernetesClusterProperties) SetLocation(v string) { + + o.Location = &v + +} + +// HasLocation returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasLocation() bool { + if o != nil && o.Location != nil { + return true + } + + return false +} + // GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterProperties) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil @@ -165,114 +253,152 @@ func (o *KubernetesClusterProperties) HasMaintenanceWindow() bool { return false } -// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterProperties) GetAvailableUpgradeVersions() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetName() *string { if o == nil { return nil } - return o.AvailableUpgradeVersions + return o.Name } -// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { +func (o *KubernetesClusterProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailableUpgradeVersions, true + return o.Name, true } -// SetAvailableUpgradeVersions sets field value -func (o *KubernetesClusterProperties) SetAvailableUpgradeVersions(v []string) { +// SetName sets field value +func (o *KubernetesClusterProperties) SetName(v string) { - o.AvailableUpgradeVersions = &v + o.Name = &v } -// HasAvailableUpgradeVersions returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasAvailableUpgradeVersions() bool { - if o != nil && o.AvailableUpgradeVersions != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetViableNodePoolVersions returns the ViableNodePoolVersions field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterProperties) GetViableNodePoolVersions() *[]string { +// GetNatGatewayIp returns the NatGatewayIp field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetNatGatewayIp() *string { if o == nil { return nil } - return o.ViableNodePoolVersions + return o.NatGatewayIp } -// GetViableNodePoolVersionsOk returns a tuple with the ViableNodePoolVersions field value +// GetNatGatewayIpOk returns a tuple with the NatGatewayIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetViableNodePoolVersionsOk() (*[]string, bool) { +func (o *KubernetesClusterProperties) GetNatGatewayIpOk() (*string, bool) { if o == nil { return nil, false } - return o.ViableNodePoolVersions, true + return o.NatGatewayIp, true } -// SetViableNodePoolVersions sets field value -func (o *KubernetesClusterProperties) SetViableNodePoolVersions(v []string) { +// SetNatGatewayIp sets field value +func (o *KubernetesClusterProperties) SetNatGatewayIp(v string) { - o.ViableNodePoolVersions = &v + o.NatGatewayIp = &v } -// HasViableNodePoolVersions returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasViableNodePoolVersions() bool { - if o != nil && o.ViableNodePoolVersions != nil { +// HasNatGatewayIp returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasNatGatewayIp() bool { + if o != nil && o.NatGatewayIp != nil { return true } return false } -// GetApiSubnetAllowList returns the ApiSubnetAllowList field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterProperties) GetApiSubnetAllowList() *[]string { +// GetNodeSubnet returns the NodeSubnet field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetNodeSubnet() *string { if o == nil { return nil } - return o.ApiSubnetAllowList + return o.NodeSubnet } -// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value +// GetNodeSubnetOk returns a tuple with the NodeSubnet field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetApiSubnetAllowListOk() (*[]string, bool) { +func (o *KubernetesClusterProperties) GetNodeSubnetOk() (*string, bool) { if o == nil { return nil, false } - return o.ApiSubnetAllowList, true + return o.NodeSubnet, true } -// SetApiSubnetAllowList sets field value -func (o *KubernetesClusterProperties) SetApiSubnetAllowList(v []string) { +// SetNodeSubnet sets field value +func (o *KubernetesClusterProperties) SetNodeSubnet(v string) { - o.ApiSubnetAllowList = &v + o.NodeSubnet = &v } -// HasApiSubnetAllowList returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasApiSubnetAllowList() bool { - if o != nil && o.ApiSubnetAllowList != nil { +// HasNodeSubnet returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasNodeSubnet() bool { + if o != nil && o.NodeSubnet != nil { + return true + } + + return false +} + +// GetPublic returns the Public field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetPublic() *bool { + if o == nil { + return nil + } + + return o.Public + +} + +// GetPublicOk returns a tuple with the Public field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterProperties) GetPublicOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.Public, true +} + +// SetPublic sets field value +func (o *KubernetesClusterProperties) SetPublic(v bool) { + + o.Public = &v + +} + +// HasPublic returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasPublic() bool { + if o != nil && o.Public != nil { return true } @@ -280,7 +406,7 @@ func (o *KubernetesClusterProperties) HasApiSubnetAllowList() bool { } // GetS3Buckets returns the S3Buckets field value -// If the value is explicit nil, the zero value for []S3Bucket will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterProperties) GetS3Buckets() *[]S3Bucket { if o == nil { return nil @@ -317,29 +443,90 @@ func (o *KubernetesClusterProperties) HasS3Buckets() bool { return false } +// GetViableNodePoolVersions returns the ViableNodePoolVersions field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetViableNodePoolVersions() *[]string { + if o == nil { + return nil + } + + return o.ViableNodePoolVersions + +} + +// GetViableNodePoolVersionsOk returns a tuple with the ViableNodePoolVersions field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterProperties) GetViableNodePoolVersionsOk() (*[]string, bool) { + if o == nil { + return nil, false + } + + return o.ViableNodePoolVersions, true +} + +// SetViableNodePoolVersions sets field value +func (o *KubernetesClusterProperties) SetViableNodePoolVersions(v []string) { + + o.ViableNodePoolVersions = &v + +} + +// HasViableNodePoolVersions returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasViableNodePoolVersions() bool { + if o != nil && o.ViableNodePoolVersions != nil { + return true + } + + return false +} + func (o KubernetesClusterProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ApiSubnetAllowList != nil { + toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + } + + if o.AvailableUpgradeVersions != nil { + toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } + + if o.Location != nil { + toSerialize["location"] = o.Location + } + if o.MaintenanceWindow != nil { toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.AvailableUpgradeVersions != nil { - toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions + + if o.Name != nil { + toSerialize["name"] = o.Name } - if o.ViableNodePoolVersions != nil { - toSerialize["viableNodePoolVersions"] = o.ViableNodePoolVersions + + if o.NatGatewayIp != nil { + toSerialize["natGatewayIp"] = o.NatGatewayIp } - if o.ApiSubnetAllowList != nil { - toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + + if o.NodeSubnet != nil { + toSerialize["nodeSubnet"] = o.NodeSubnet } + + if o.Public != nil { + toSerialize["public"] = o.Public + } + if o.S3Buckets != nil { toSerialize["s3Buckets"] = o.S3Buckets } + + if o.ViableNodePoolVersions != nil { + toSerialize["viableNodePoolVersions"] = o.ViableNodePoolVersions + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go index b44a3227a..14c2b97b9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go @@ -16,13 +16,21 @@ import ( // KubernetesClusterPropertiesForPost struct for KubernetesClusterPropertiesForPost type KubernetesClusterPropertiesForPost struct { - // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` - // The Kubernetes version that the cluster is running. This limits which Kubernetes versions can run in a cluster's node pools. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` // Access to the K8s API server is restricted to these CIDRs. Intra-cluster traffic is not affected by this restriction. If no AllowList is specified, access is not limited. If an IP is specified without a subnet mask, the default value is 32 for IPv4 and 128 for IPv6. ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` + // The Kubernetes version that the cluster is running. This limits which Kubernetes versions can run in a cluster's node pools. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // This attribute is mandatory if the cluster is private. The location must be enabled for your contract, or you must have a data center at that location. This property is not adjustable. + Location *string `json:"location,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` + // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` + // The nat gateway IP of the cluster if the cluster is private. This property is immutable. Must be a reserved IP in the same location as the cluster's location. This attribute is mandatory if the cluster is private. + NatGatewayIp *string `json:"natGatewayIp,omitempty"` + // The node subnet of the cluster, if the cluster is private. This property is optional and immutable. Must be a valid CIDR notation for an IPv4 network prefix of 16 bits length. + NodeSubnet *string `json:"nodeSubnet,omitempty"` + // The indicator whether the cluster is public or private. Note that the status FALSE is still in the beta phase. + Public *bool `json:"public,omitempty"` // List of S3 buckets configured for K8s usage. At the moment, it contains only one S3 bucket that is used to store K8s API audit logs. S3Buckets *[]S3Bucket `json:"s3Buckets,omitempty"` } @@ -35,6 +43,8 @@ func NewKubernetesClusterPropertiesForPost(name string) *KubernetesClusterProper this := KubernetesClusterPropertiesForPost{} this.Name = &name + var public bool = true + this.Public = &public return &this } @@ -44,41 +54,43 @@ func NewKubernetesClusterPropertiesForPost(name string) *KubernetesClusterProper // but it doesn't guarantee that properties required by API are set func NewKubernetesClusterPropertiesForPostWithDefaults() *KubernetesClusterPropertiesForPost { this := KubernetesClusterPropertiesForPost{} + var public bool = true + this.Public = &public return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterPropertiesForPost) GetName() *string { +// GetApiSubnetAllowList returns the ApiSubnetAllowList field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowList() *[]string { if o == nil { return nil } - return o.Name + return o.ApiSubnetAllowList } -// GetNameOk returns a tuple with the Name field value +// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPost) GetNameOk() (*string, bool) { +func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowListOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ApiSubnetAllowList, true } -// SetName sets field value -func (o *KubernetesClusterPropertiesForPost) SetName(v string) { +// SetApiSubnetAllowList sets field value +func (o *KubernetesClusterPropertiesForPost) SetApiSubnetAllowList(v []string) { - o.Name = &v + o.ApiSubnetAllowList = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPost) HasName() bool { - if o != nil && o.Name != nil { +// HasApiSubnetAllowList returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasApiSubnetAllowList() bool { + if o != nil && o.ApiSubnetAllowList != nil { return true } @@ -86,7 +98,7 @@ func (o *KubernetesClusterPropertiesForPost) HasName() bool { } // GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPost) GetK8sVersion() *string { if o == nil { return nil @@ -123,8 +135,46 @@ func (o *KubernetesClusterPropertiesForPost) HasK8sVersion() bool { return false } +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetLocation() *string { + if o == nil { + return nil + } + + return o.Location + +} + +// GetLocationOk returns a tuple with the Location field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterPropertiesForPost) GetLocationOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Location, true +} + +// SetLocation sets field value +func (o *KubernetesClusterPropertiesForPost) SetLocation(v string) { + + o.Location = &v + +} + +// HasLocation returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasLocation() bool { + if o != nil && o.Location != nil { + return true + } + + return false +} + // GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPost) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil @@ -161,38 +211,152 @@ func (o *KubernetesClusterPropertiesForPost) HasMaintenanceWindow() bool { return false } -// GetApiSubnetAllowList returns the ApiSubnetAllowList field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowList() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetName() *string { if o == nil { return nil } - return o.ApiSubnetAllowList + return o.Name } -// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowListOk() (*[]string, bool) { +func (o *KubernetesClusterPropertiesForPost) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ApiSubnetAllowList, true + return o.Name, true } -// SetApiSubnetAllowList sets field value -func (o *KubernetesClusterPropertiesForPost) SetApiSubnetAllowList(v []string) { +// SetName sets field value +func (o *KubernetesClusterPropertiesForPost) SetName(v string) { - o.ApiSubnetAllowList = &v + o.Name = &v } -// HasApiSubnetAllowList returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPost) HasApiSubnetAllowList() bool { - if o != nil && o.ApiSubnetAllowList != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasName() bool { + if o != nil && o.Name != nil { + return true + } + + return false +} + +// GetNatGatewayIp returns the NatGatewayIp field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetNatGatewayIp() *string { + if o == nil { + return nil + } + + return o.NatGatewayIp + +} + +// GetNatGatewayIpOk returns a tuple with the NatGatewayIp field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterPropertiesForPost) GetNatGatewayIpOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.NatGatewayIp, true +} + +// SetNatGatewayIp sets field value +func (o *KubernetesClusterPropertiesForPost) SetNatGatewayIp(v string) { + + o.NatGatewayIp = &v + +} + +// HasNatGatewayIp returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasNatGatewayIp() bool { + if o != nil && o.NatGatewayIp != nil { + return true + } + + return false +} + +// GetNodeSubnet returns the NodeSubnet field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetNodeSubnet() *string { + if o == nil { + return nil + } + + return o.NodeSubnet + +} + +// GetNodeSubnetOk returns a tuple with the NodeSubnet field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterPropertiesForPost) GetNodeSubnetOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.NodeSubnet, true +} + +// SetNodeSubnet sets field value +func (o *KubernetesClusterPropertiesForPost) SetNodeSubnet(v string) { + + o.NodeSubnet = &v + +} + +// HasNodeSubnet returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasNodeSubnet() bool { + if o != nil && o.NodeSubnet != nil { + return true + } + + return false +} + +// GetPublic returns the Public field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetPublic() *bool { + if o == nil { + return nil + } + + return o.Public + +} + +// GetPublicOk returns a tuple with the Public field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *KubernetesClusterPropertiesForPost) GetPublicOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.Public, true +} + +// SetPublic sets field value +func (o *KubernetesClusterPropertiesForPost) SetPublic(v bool) { + + o.Public = &v + +} + +// HasPublic returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasPublic() bool { + if o != nil && o.Public != nil { return true } @@ -200,7 +364,7 @@ func (o *KubernetesClusterPropertiesForPost) HasApiSubnetAllowList() bool { } // GetS3Buckets returns the S3Buckets field value -// If the value is explicit nil, the zero value for []S3Bucket will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPost) GetS3Buckets() *[]S3Bucket { if o == nil { return nil @@ -239,21 +403,42 @@ func (o *KubernetesClusterPropertiesForPost) HasS3Buckets() bool { func (o KubernetesClusterPropertiesForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ApiSubnetAllowList != nil { + toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } + + if o.Location != nil { + toSerialize["location"] = o.Location + } + if o.MaintenanceWindow != nil { toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.ApiSubnetAllowList != nil { - toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + + if o.Name != nil { + toSerialize["name"] = o.Name } + + if o.NatGatewayIp != nil { + toSerialize["natGatewayIp"] = o.NatGatewayIp + } + + if o.NodeSubnet != nil { + toSerialize["nodeSubnet"] = o.NodeSubnet + } + + if o.Public != nil { + toSerialize["public"] = o.Public + } + if o.S3Buckets != nil { toSerialize["s3Buckets"] = o.S3Buckets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go index c2b9d44cd..b2bc4980d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go @@ -16,13 +16,13 @@ import ( // KubernetesClusterPropertiesForPut struct for KubernetesClusterPropertiesForPut type KubernetesClusterPropertiesForPut struct { - // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // Access to the K8s API server is restricted to these CIDRs. Intra-cluster traffic is not affected by this restriction. If no AllowList is specified, access is not limited. If an IP is specified without a subnet mask, the default value is 32 for IPv4 and 128 for IPv6. + ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` // The Kubernetes version that the cluster is running. This limits which Kubernetes versions can run in a cluster's node pools. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. K8sVersion *string `json:"k8sVersion,omitempty"` MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - // Access to the K8s API server is restricted to these CIDRs. Intra-cluster traffic is not affected by this restriction. If no AllowList is specified, access is not limited. If an IP is specified without a subnet mask, the default value is 32 for IPv4 and 128 for IPv6. - ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` + // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // List of S3 buckets configured for K8s usage. At the moment, it contains only one S3 bucket that is used to store K8s API audit logs. S3Buckets *[]S3Bucket `json:"s3Buckets,omitempty"` } @@ -47,38 +47,38 @@ func NewKubernetesClusterPropertiesForPutWithDefaults() *KubernetesClusterProper return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterPropertiesForPut) GetName() *string { +// GetApiSubnetAllowList returns the ApiSubnetAllowList field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowList() *[]string { if o == nil { return nil } - return o.Name + return o.ApiSubnetAllowList } -// GetNameOk returns a tuple with the Name field value +// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPut) GetNameOk() (*string, bool) { +func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowListOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ApiSubnetAllowList, true } -// SetName sets field value -func (o *KubernetesClusterPropertiesForPut) SetName(v string) { +// SetApiSubnetAllowList sets field value +func (o *KubernetesClusterPropertiesForPut) SetApiSubnetAllowList(v []string) { - o.Name = &v + o.ApiSubnetAllowList = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPut) HasName() bool { - if o != nil && o.Name != nil { +// HasApiSubnetAllowList returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPut) HasApiSubnetAllowList() bool { + if o != nil && o.ApiSubnetAllowList != nil { return true } @@ -86,7 +86,7 @@ func (o *KubernetesClusterPropertiesForPut) HasName() bool { } // GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPut) GetK8sVersion() *string { if o == nil { return nil @@ -124,7 +124,7 @@ func (o *KubernetesClusterPropertiesForPut) HasK8sVersion() bool { } // GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPut) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil @@ -161,38 +161,38 @@ func (o *KubernetesClusterPropertiesForPut) HasMaintenanceWindow() bool { return false } -// GetApiSubnetAllowList returns the ApiSubnetAllowList field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowList() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPut) GetName() *string { if o == nil { return nil } - return o.ApiSubnetAllowList + return o.Name } -// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowListOk() (*[]string, bool) { +func (o *KubernetesClusterPropertiesForPut) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ApiSubnetAllowList, true + return o.Name, true } -// SetApiSubnetAllowList sets field value -func (o *KubernetesClusterPropertiesForPut) SetApiSubnetAllowList(v []string) { +// SetName sets field value +func (o *KubernetesClusterPropertiesForPut) SetName(v string) { - o.ApiSubnetAllowList = &v + o.Name = &v } -// HasApiSubnetAllowList returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPut) HasApiSubnetAllowList() bool { - if o != nil && o.ApiSubnetAllowList != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPut) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -200,7 +200,7 @@ func (o *KubernetesClusterPropertiesForPut) HasApiSubnetAllowList() bool { } // GetS3Buckets returns the S3Buckets field value -// If the value is explicit nil, the zero value for []S3Bucket will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPut) GetS3Buckets() *[]S3Bucket { if o == nil { return nil @@ -239,21 +239,26 @@ func (o *KubernetesClusterPropertiesForPut) HasS3Buckets() bool { func (o KubernetesClusterPropertiesForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ApiSubnetAllowList != nil { + toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } + if o.MaintenanceWindow != nil { toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.ApiSubnetAllowList != nil { - toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.S3Buckets != nil { toSerialize["s3Buckets"] = o.S3Buckets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go index f1416d0eb..84f19c35c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go @@ -16,14 +16,14 @@ import ( // KubernetesClusters struct for KubernetesClusters type KubernetesClusters struct { - // The unique representation of the K8s cluster as a resource collection. - Id *string `json:"id,omitempty"` - // The resource type within a collection. - Type *string `json:"type,omitempty"` // The URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // The unique representation of the K8s cluster as a resource collection. + Id *string `json:"id,omitempty"` // Array of K8s clusters in the collection. Items *[]KubernetesCluster `json:"items,omitempty"` + // The resource type within a collection. + Type *string `json:"type,omitempty"` } // NewKubernetesClusters instantiates a new KubernetesClusters object @@ -44,152 +44,152 @@ func NewKubernetesClustersWithDefaults() *KubernetesClusters { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusters) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetIdOk() (*string, bool) { +func (o *KubernetesClusters) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesClusters) SetId(v string) { +// SetHref sets field value +func (o *KubernetesClusters) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesClusters) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesClusters) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusters) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetTypeOk() (*string, bool) { +func (o *KubernetesClusters) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesClusters) SetType(v string) { +// SetId sets field value +func (o *KubernetesClusters) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesClusters) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesClusters) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusters) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetItems() *[]KubernetesCluster { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetHrefOk() (*string, bool) { +func (o *KubernetesClusters) GetItemsOk() (*[]KubernetesCluster, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *KubernetesClusters) SetHref(v string) { +// SetItems sets field value +func (o *KubernetesClusters) SetItems(v []KubernetesCluster) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesClusters) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *KubernetesClusters) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []KubernetesCluster will be returned -func (o *KubernetesClusters) GetItems() *[]KubernetesCluster { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetItemsOk() (*[]KubernetesCluster, bool) { +func (o *KubernetesClusters) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *KubernetesClusters) SetItems(v []KubernetesCluster) { +// SetType sets field value +func (o *KubernetesClusters) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *KubernetesClusters) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesClusters) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *KubernetesClusters) HasItems() bool { func (o KubernetesClusters) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go index d5decee54..86d576253 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go @@ -44,7 +44,7 @@ func NewKubernetesMaintenanceWindowWithDefaults() *KubernetesMaintenanceWindow { } // GetDayOfTheWeek returns the DayOfTheWeek field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesMaintenanceWindow) GetDayOfTheWeek() *string { if o == nil { return nil @@ -82,7 +82,7 @@ func (o *KubernetesMaintenanceWindow) HasDayOfTheWeek() bool { } // GetTime returns the Time field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesMaintenanceWindow) GetTime() *string { if o == nil { return nil @@ -124,9 +124,11 @@ func (o KubernetesMaintenanceWindow) MarshalJSON() ([]byte, error) { if o.DayOfTheWeek != nil { toSerialize["dayOfTheWeek"] = o.DayOfTheWeek } + if o.Time != nil { toSerialize["time"] = o.Time } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go index 936864aec..512c52312 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go @@ -16,14 +16,14 @@ import ( // KubernetesNode struct for KubernetesNode type KubernetesNode struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *KubernetesNodeMetadata `json:"metadata,omitempty"` Properties *KubernetesNodeProperties `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNode instantiates a new KubernetesNode object @@ -46,190 +46,190 @@ func NewKubernetesNodeWithDefaults() *KubernetesNode { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNode) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetIdOk() (*string, bool) { +func (o *KubernetesNode) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNode) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNode) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNode) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNode) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNode) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetTypeOk() (*string, bool) { +func (o *KubernetesNode) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNode) SetType(v string) { +// SetId sets field value +func (o *KubernetesNode) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNode) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNode) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNode) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetMetadata() *KubernetesNodeMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetHrefOk() (*string, bool) { +func (o *KubernetesNode) GetMetadataOk() (*KubernetesNodeMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNode) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNode) SetMetadata(v KubernetesNodeMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNode) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNode) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for KubernetesNodeMetadata will be returned -func (o *KubernetesNode) GetMetadata() *KubernetesNodeMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetProperties() *KubernetesNodeProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetMetadataOk() (*KubernetesNodeMetadata, bool) { +func (o *KubernetesNode) GetPropertiesOk() (*KubernetesNodeProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNode) SetMetadata(v KubernetesNodeMetadata) { +// SetProperties sets field value +func (o *KubernetesNode) SetProperties(v KubernetesNodeProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNode) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNode) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodeProperties will be returned -func (o *KubernetesNode) GetProperties() *KubernetesNodeProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetPropertiesOk() (*KubernetesNodeProperties, bool) { +func (o *KubernetesNode) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNode) SetProperties(v KubernetesNodeProperties) { +// SetType sets field value +func (o *KubernetesNode) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNode) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNode) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNode) HasProperties() bool { func (o KubernetesNode) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go index 8110ddd61..3915ed803 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go @@ -17,16 +17,16 @@ import ( // KubernetesNodeMetadata struct for KubernetesNodeMetadata type KubernetesNodeMetadata struct { - // The resource entity tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity tags are also added as 'ETag' response headers to requests that do not use the 'depth' parameter. - Etag *string `json:"etag,omitempty"` // The date the resource was created. CreatedDate *IonosTime + // The resource entity tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity tags are also added as 'ETag' response headers to requests that do not use the 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The date the resource was last modified. LastModifiedDate *IonosTime - // The resource state. - State *string `json:"state,omitempty"` // The date when the software on the node was last updated. LastSoftwareUpdatedDate *IonosTime + // The resource state. + State *string `json:"state,omitempty"` } // NewKubernetesNodeMetadata instantiates a new KubernetesNodeMetadata object @@ -47,83 +47,83 @@ func NewKubernetesNodeMetadataWithDefaults() *KubernetesNodeMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeMetadata) GetEtag() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.Etag + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetEtagOk returns a tuple with the Etag field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetEtagOk() (*string, bool) { +func (o *KubernetesNodeMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.Etag, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetEtag sets field value -func (o *KubernetesNodeMetadata) SetEtag(v string) { +// SetCreatedDate sets field value +func (o *KubernetesNodeMetadata) SetCreatedDate(v time.Time) { - o.Etag = &v + o.CreatedDate = &IonosTime{v} } -// HasEtag returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } return false } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *KubernetesNodeMetadata) GetCreatedDate() *time.Time { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetEtag() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.Etag } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *KubernetesNodeMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.Etag, true } -// SetCreatedDate sets field value -func (o *KubernetesNodeMetadata) SetCreatedDate(v time.Time) { +// SetEtag sets field value +func (o *KubernetesNodeMetadata) SetEtag(v string) { - o.CreatedDate = &IonosTime{v} + o.Etag = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasEtag returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -131,7 +131,7 @@ func (o *KubernetesNodeMetadata) HasCreatedDate() bool { } // GetLastModifiedDate returns the LastModifiedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodeMetadata) GetLastModifiedDate() *time.Time { if o == nil { return nil @@ -175,83 +175,83 @@ func (o *KubernetesNodeMetadata) HasLastModifiedDate() bool { return false } -// GetState returns the State field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeMetadata) GetState() *string { +// GetLastSoftwareUpdatedDate returns the LastSoftwareUpdatedDate field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDate() *time.Time { if o == nil { return nil } - return o.State + if o.LastSoftwareUpdatedDate == nil { + return nil + } + return &o.LastSoftwareUpdatedDate.Time } -// GetStateOk returns a tuple with the State field value +// GetLastSoftwareUpdatedDateOk returns a tuple with the LastSoftwareUpdatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetStateOk() (*string, bool) { +func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.State, true + if o.LastSoftwareUpdatedDate == nil { + return nil, false + } + return &o.LastSoftwareUpdatedDate.Time, true + } -// SetState sets field value -func (o *KubernetesNodeMetadata) SetState(v string) { +// SetLastSoftwareUpdatedDate sets field value +func (o *KubernetesNodeMetadata) SetLastSoftwareUpdatedDate(v time.Time) { - o.State = &v + o.LastSoftwareUpdatedDate = &IonosTime{v} } -// HasState returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasState() bool { - if o != nil && o.State != nil { +// HasLastSoftwareUpdatedDate returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasLastSoftwareUpdatedDate() bool { + if o != nil && o.LastSoftwareUpdatedDate != nil { return true } return false } -// GetLastSoftwareUpdatedDate returns the LastSoftwareUpdatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDate() *time.Time { +// GetState returns the State field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetState() *string { if o == nil { return nil } - if o.LastSoftwareUpdatedDate == nil { - return nil - } - return &o.LastSoftwareUpdatedDate.Time + return o.State } -// GetLastSoftwareUpdatedDateOk returns a tuple with the LastSoftwareUpdatedDate field value +// GetStateOk returns a tuple with the State field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDateOk() (*time.Time, bool) { +func (o *KubernetesNodeMetadata) GetStateOk() (*string, bool) { if o == nil { return nil, false } - if o.LastSoftwareUpdatedDate == nil { - return nil, false - } - return &o.LastSoftwareUpdatedDate.Time, true - + return o.State, true } -// SetLastSoftwareUpdatedDate sets field value -func (o *KubernetesNodeMetadata) SetLastSoftwareUpdatedDate(v time.Time) { +// SetState sets field value +func (o *KubernetesNodeMetadata) SetState(v string) { - o.LastSoftwareUpdatedDate = &IonosTime{v} + o.State = &v } -// HasLastSoftwareUpdatedDate returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasLastSoftwareUpdatedDate() bool { - if o != nil && o.LastSoftwareUpdatedDate != nil { +// HasState returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasState() bool { + if o != nil && o.State != nil { return true } @@ -260,21 +260,26 @@ func (o *KubernetesNodeMetadata) HasLastSoftwareUpdatedDate() bool { func (o KubernetesNodeMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } if o.CreatedDate != nil { toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + if o.LastModifiedDate != nil { toSerialize["lastModifiedDate"] = o.LastModifiedDate } - if o.State != nil { - toSerialize["state"] = o.State - } + if o.LastSoftwareUpdatedDate != nil { toSerialize["lastSoftwareUpdatedDate"] = o.LastSoftwareUpdatedDate } + + if o.State != nil { + toSerialize["state"] = o.State + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go index a634f0a8b..9649a8ad8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePool struct for KubernetesNodePool type KubernetesNodePool struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesNodePoolProperties `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePool instantiates a new KubernetesNodePool object @@ -46,190 +46,190 @@ func NewKubernetesNodePoolWithDefaults() *KubernetesNodePool { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePool) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetIdOk() (*string, bool) { +func (o *KubernetesNodePool) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePool) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePool) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePool) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePool) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePool) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePool) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePool) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePool) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNodePool) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNodePool) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *KubernetesNodePool) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetProperties() *KubernetesNodePoolProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *KubernetesNodePool) GetPropertiesOk() (*KubernetesNodePoolProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNodePool) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *KubernetesNodePool) SetProperties(v KubernetesNodePoolProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodePoolProperties will be returned -func (o *KubernetesNodePool) GetProperties() *KubernetesNodePoolProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetPropertiesOk() (*KubernetesNodePoolProperties, bool) { +func (o *KubernetesNodePool) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNodePool) SetProperties(v KubernetesNodePoolProperties) { +// SetType sets field value +func (o *KubernetesNodePool) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNodePool) HasProperties() bool { func (o KubernetesNodePool) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go index 9a89d3d18..afeef99c7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePoolForPost struct for KubernetesNodePoolForPost type KubernetesNodePoolForPost struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesNodePoolPropertiesForPost `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePoolForPost instantiates a new KubernetesNodePoolForPost object @@ -46,190 +46,190 @@ func NewKubernetesNodePoolForPostWithDefaults() *KubernetesNodePoolForPost { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPost) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetIdOk() (*string, bool) { +func (o *KubernetesNodePoolForPost) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePoolForPost) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePoolForPost) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPost) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePoolForPost) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePoolForPost) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePoolForPost) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPost) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePoolForPost) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNodePoolForPost) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNodePoolForPost) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *KubernetesNodePoolForPost) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetProperties() *KubernetesNodePoolPropertiesForPost { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *KubernetesNodePoolForPost) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPost, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNodePoolForPost) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *KubernetesNodePoolForPost) SetProperties(v KubernetesNodePoolPropertiesForPost) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodePoolPropertiesForPost will be returned -func (o *KubernetesNodePoolForPost) GetProperties() *KubernetesNodePoolPropertiesForPost { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPost, bool) { +func (o *KubernetesNodePoolForPost) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNodePoolForPost) SetProperties(v KubernetesNodePoolPropertiesForPost) { +// SetType sets field value +func (o *KubernetesNodePoolForPost) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNodePoolForPost) HasProperties() bool { func (o KubernetesNodePoolForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go index 10fa4f290..94df03dd9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePoolForPut struct for KubernetesNodePoolForPut type KubernetesNodePoolForPut struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesNodePoolPropertiesForPut `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePoolForPut instantiates a new KubernetesNodePoolForPut object @@ -46,190 +46,190 @@ func NewKubernetesNodePoolForPutWithDefaults() *KubernetesNodePoolForPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetIdOk() (*string, bool) { +func (o *KubernetesNodePoolForPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePoolForPut) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePoolForPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPut) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePoolForPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePoolForPut) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePoolForPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPut) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePoolForPut) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNodePoolForPut) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNodePoolForPut) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *KubernetesNodePoolForPut) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetProperties() *KubernetesNodePoolPropertiesForPut { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *KubernetesNodePoolForPut) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPut, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNodePoolForPut) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *KubernetesNodePoolForPut) SetProperties(v KubernetesNodePoolPropertiesForPut) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodePoolPropertiesForPut will be returned -func (o *KubernetesNodePoolForPut) GetProperties() *KubernetesNodePoolPropertiesForPut { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPut, bool) { +func (o *KubernetesNodePoolForPut) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNodePoolForPut) SetProperties(v KubernetesNodePoolPropertiesForPut) { +// SetType sets field value +func (o *KubernetesNodePoolForPut) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNodePoolForPut) HasProperties() bool { func (o KubernetesNodePoolForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go index 012c0f4b7..926f1498a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go @@ -18,10 +18,10 @@ import ( type KubernetesNodePoolLan struct { // The datacenter ID, requires system privileges, for internal usage only DatacenterId *string `json:"datacenterId,omitempty"` - // The LAN ID of an existing LAN at the related data center - Id *int32 `json:"id"` // Specifies whether the Kubernetes node pool LAN reserves an IP with DHCP. Dhcp *bool `json:"dhcp,omitempty"` + // The LAN ID of an existing LAN at the related data center + Id *int32 `json:"id"` // The array of additional LANs attached to worker nodes. Routes *[]KubernetesNodePoolLanRoutes `json:"routes,omitempty"` } @@ -47,7 +47,7 @@ func NewKubernetesNodePoolLanWithDefaults() *KubernetesNodePoolLan { } // GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolLan) GetDatacenterId() *string { if o == nil { return nil @@ -84,76 +84,76 @@ func (o *KubernetesNodePoolLan) HasDatacenterId() bool { return false } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolLan) GetId() *int32 { +// GetDhcp returns the Dhcp field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLan) GetDhcp() *bool { if o == nil { return nil } - return o.Id + return o.Dhcp } -// GetIdOk returns a tuple with the Id field value +// GetDhcpOk returns a tuple with the Dhcp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLan) GetIdOk() (*int32, bool) { +func (o *KubernetesNodePoolLan) GetDhcpOk() (*bool, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Dhcp, true } -// SetId sets field value -func (o *KubernetesNodePoolLan) SetId(v int32) { +// SetDhcp sets field value +func (o *KubernetesNodePoolLan) SetDhcp(v bool) { - o.Id = &v + o.Dhcp = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePoolLan) HasId() bool { - if o != nil && o.Id != nil { +// HasDhcp returns a boolean if a field has been set. +func (o *KubernetesNodePoolLan) HasDhcp() bool { + if o != nil && o.Dhcp != nil { return true } return false } -// GetDhcp returns the Dhcp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *KubernetesNodePoolLan) GetDhcp() *bool { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLan) GetId() *int32 { if o == nil { return nil } - return o.Dhcp + return o.Id } -// GetDhcpOk returns a tuple with the Dhcp field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLan) GetDhcpOk() (*bool, bool) { +func (o *KubernetesNodePoolLan) GetIdOk() (*int32, bool) { if o == nil { return nil, false } - return o.Dhcp, true + return o.Id, true } -// SetDhcp sets field value -func (o *KubernetesNodePoolLan) SetDhcp(v bool) { +// SetId sets field value +func (o *KubernetesNodePoolLan) SetId(v int32) { - o.Dhcp = &v + o.Id = &v } -// HasDhcp returns a boolean if a field has been set. -func (o *KubernetesNodePoolLan) HasDhcp() bool { - if o != nil && o.Dhcp != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePoolLan) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -161,7 +161,7 @@ func (o *KubernetesNodePoolLan) HasDhcp() bool { } // GetRoutes returns the Routes field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLanRoutes will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolLan) GetRoutes() *[]KubernetesNodePoolLanRoutes { if o == nil { return nil @@ -203,15 +203,19 @@ func (o KubernetesNodePoolLan) MarshalJSON() ([]byte, error) { if o.DatacenterId != nil { toSerialize["datacenterId"] = o.DatacenterId } - if o.Id != nil { - toSerialize["id"] = o.Id - } + if o.Dhcp != nil { toSerialize["dhcp"] = o.Dhcp } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Routes != nil { toSerialize["routes"] = o.Routes } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go index 0d57c4592..7ba035e44 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go @@ -16,10 +16,10 @@ import ( // KubernetesNodePoolLanRoutes struct for KubernetesNodePoolLanRoutes type KubernetesNodePoolLanRoutes struct { - // IPv4 or IPv6 CIDR to be routed via the interface. - Network *string `json:"network,omitempty"` // IPv4 or IPv6 Gateway IP for the route. GatewayIp *string `json:"gatewayIp,omitempty"` + // IPv4 or IPv6 CIDR to be routed via the interface. + Network *string `json:"network,omitempty"` } // NewKubernetesNodePoolLanRoutes instantiates a new KubernetesNodePoolLanRoutes object @@ -40,76 +40,76 @@ func NewKubernetesNodePoolLanRoutesWithDefaults() *KubernetesNodePoolLanRoutes { return &this } -// GetNetwork returns the Network field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolLanRoutes) GetNetwork() *string { +// GetGatewayIp returns the GatewayIp field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLanRoutes) GetGatewayIp() *string { if o == nil { return nil } - return o.Network + return o.GatewayIp } -// GetNetworkOk returns a tuple with the Network field value +// GetGatewayIpOk returns a tuple with the GatewayIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLanRoutes) GetNetworkOk() (*string, bool) { +func (o *KubernetesNodePoolLanRoutes) GetGatewayIpOk() (*string, bool) { if o == nil { return nil, false } - return o.Network, true + return o.GatewayIp, true } -// SetNetwork sets field value -func (o *KubernetesNodePoolLanRoutes) SetNetwork(v string) { +// SetGatewayIp sets field value +func (o *KubernetesNodePoolLanRoutes) SetGatewayIp(v string) { - o.Network = &v + o.GatewayIp = &v } -// HasNetwork returns a boolean if a field has been set. -func (o *KubernetesNodePoolLanRoutes) HasNetwork() bool { - if o != nil && o.Network != nil { +// HasGatewayIp returns a boolean if a field has been set. +func (o *KubernetesNodePoolLanRoutes) HasGatewayIp() bool { + if o != nil && o.GatewayIp != nil { return true } return false } -// GetGatewayIp returns the GatewayIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolLanRoutes) GetGatewayIp() *string { +// GetNetwork returns the Network field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLanRoutes) GetNetwork() *string { if o == nil { return nil } - return o.GatewayIp + return o.Network } -// GetGatewayIpOk returns a tuple with the GatewayIp field value +// GetNetworkOk returns a tuple with the Network field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLanRoutes) GetGatewayIpOk() (*string, bool) { +func (o *KubernetesNodePoolLanRoutes) GetNetworkOk() (*string, bool) { if o == nil { return nil, false } - return o.GatewayIp, true + return o.Network, true } -// SetGatewayIp sets field value -func (o *KubernetesNodePoolLanRoutes) SetGatewayIp(v string) { +// SetNetwork sets field value +func (o *KubernetesNodePoolLanRoutes) SetNetwork(v string) { - o.GatewayIp = &v + o.Network = &v } -// HasGatewayIp returns a boolean if a field has been set. -func (o *KubernetesNodePoolLanRoutes) HasGatewayIp() bool { - if o != nil && o.GatewayIp != nil { +// HasNetwork returns a boolean if a field has been set. +func (o *KubernetesNodePoolLanRoutes) HasNetwork() bool { + if o != nil && o.Network != nil { return true } @@ -118,12 +118,14 @@ func (o *KubernetesNodePoolLanRoutes) HasGatewayIp() bool { func (o KubernetesNodePoolLanRoutes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Network != nil { - toSerialize["network"] = o.Network - } if o.GatewayIp != nil { toSerialize["gatewayIp"] = o.GatewayIp } + + if o.Network != nil { + toSerialize["network"] = o.Network + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go index 5e18701de..376120c0c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go @@ -16,56 +16,56 @@ import ( // KubernetesNodePoolProperties struct for KubernetesNodePoolProperties type KubernetesNodePoolProperties struct { - // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // The annotations attached to the node pool. + Annotations *map[string]string `json:"annotations,omitempty"` + AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` + // The availability zone in which the target VM should be provisioned. + AvailabilityZone *string `json:"availabilityZone"` + // The list of available versions for upgrading the node pool. + AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` + // The total number of cores for the nodes. + CoresCount *int32 `json:"coresCount"` + // The CPU type for the nodes. + CpuFamily *string `json:"cpuFamily"` // The unique identifier of the VDC where the worker nodes of the node pool are provisioned.Note that the data center is located in the exact place where the parent cluster of the node pool is located. DatacenterId *string `json:"datacenterId"` + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // The labels attached to the node pool. + Labels *map[string]string `json:"labels,omitempty"` + // The array of existing private LANs to attach to worker nodes. + Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` + // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // The number of worker nodes of the node pool. NodeCount *int32 `json:"nodeCount"` - // The CPU type for the nodes. - CpuFamily *string `json:"cpuFamily"` - // The total number of cores for the nodes. - CoresCount *int32 `json:"coresCount"` + // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. + PublicIps *[]string `json:"publicIps,omitempty"` // The RAM size for the nodes. Must be specified in multiples of 1024 MB, with a minimum size of 2048 MB. RamSize *int32 `json:"ramSize"` - // The availability zone in which the target VM should be provisioned. - AvailabilityZone *string `json:"availabilityZone"` - // The storage type for the nodes. - StorageType *string `json:"storageType"` // The allocated volume size in GB. The allocated volume size in GB. To achieve good performance, we recommend a size greater than 100GB for SSD. StorageSize *int32 `json:"storageSize"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` - // The array of existing private LANs to attach to worker nodes. - Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` - // The labels attached to the node pool. - Labels *map[string]string `json:"labels,omitempty"` - // The annotations attached to the node pool. - Annotations *map[string]string `json:"annotations,omitempty"` - // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. - PublicIps *[]string `json:"publicIps,omitempty"` - // The list of available versions for upgrading the node pool. - AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` + // The storage type for the nodes. + StorageType *string `json:"storageType"` } // NewKubernetesNodePoolProperties instantiates a new KubernetesNodePoolProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesNodePoolProperties(name string, datacenterId string, nodeCount int32, cpuFamily string, coresCount int32, ramSize int32, availabilityZone string, storageType string, storageSize int32) *KubernetesNodePoolProperties { +func NewKubernetesNodePoolProperties(availabilityZone string, coresCount int32, cpuFamily string, datacenterId string, name string, nodeCount int32, ramSize int32, storageSize int32, storageType string) *KubernetesNodePoolProperties { this := KubernetesNodePoolProperties{} - this.Name = &name + this.AvailabilityZone = &availabilityZone + this.CoresCount = &coresCount + this.CpuFamily = &cpuFamily this.DatacenterId = &datacenterId + this.Name = &name this.NodeCount = &nodeCount - this.CpuFamily = &cpuFamily - this.CoresCount = &coresCount this.RamSize = &ramSize - this.AvailabilityZone = &availabilityZone - this.StorageType = &storageType this.StorageSize = &storageSize + this.StorageType = &storageType return &this } @@ -78,152 +78,152 @@ func NewKubernetesNodePoolPropertiesWithDefaults() *KubernetesNodePoolProperties return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetName() *string { +// GetAnnotations returns the Annotations field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAnnotations() *map[string]string { if o == nil { return nil } - return o.Name + return o.Annotations } -// GetNameOk returns a tuple with the Name field value +// GetAnnotationsOk returns a tuple with the Annotations field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetNameOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetAnnotationsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Annotations, true } -// SetName sets field value -func (o *KubernetesNodePoolProperties) SetName(v string) { +// SetAnnotations sets field value +func (o *KubernetesNodePoolProperties) SetAnnotations(v map[string]string) { - o.Name = &v + o.Annotations = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAnnotations returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAnnotations() bool { + if o != nil && o.Annotations != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetDatacenterId() *string { +// GetAutoScaling returns the AutoScaling field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAutoScaling() *KubernetesAutoScaling { if o == nil { return nil } - return o.DatacenterId + return o.AutoScaling } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetAutoScalingOk returns a tuple with the AutoScaling field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetDatacenterIdOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.AutoScaling, true } -// SetDatacenterId sets field value -func (o *KubernetesNodePoolProperties) SetDatacenterId(v string) { +// SetAutoScaling sets field value +func (o *KubernetesNodePoolProperties) SetAutoScaling(v KubernetesAutoScaling) { - o.DatacenterId = &v + o.AutoScaling = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasAutoScaling returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAutoScaling() bool { + if o != nil && o.AutoScaling != nil { return true } return false } -// GetNodeCount returns the NodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolProperties) GetNodeCount() *int32 { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAvailabilityZone() *string { if o == nil { return nil } - return o.NodeCount + return o.AvailabilityZone } -// GetNodeCountOk returns a tuple with the NodeCount field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetNodeCountOk() (*int32, bool) { +func (o *KubernetesNodePoolProperties) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.NodeCount, true + return o.AvailabilityZone, true } -// SetNodeCount sets field value -func (o *KubernetesNodePoolProperties) SetNodeCount(v int32) { +// SetAvailabilityZone sets field value +func (o *KubernetesNodePoolProperties) SetAvailabilityZone(v string) { - o.NodeCount = &v + o.AvailabilityZone = &v } -// HasNodeCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasNodeCount() bool { - if o != nil && o.NodeCount != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetCpuFamily() *string { +// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersions() *[]string { if o == nil { return nil } - return o.CpuFamily + return o.AvailableUpgradeVersions } -// GetCpuFamilyOk returns a tuple with the CpuFamily field value +// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetCpuFamilyOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.CpuFamily, true + return o.AvailableUpgradeVersions, true } -// SetCpuFamily sets field value -func (o *KubernetesNodePoolProperties) SetCpuFamily(v string) { +// SetAvailableUpgradeVersions sets field value +func (o *KubernetesNodePoolProperties) SetAvailableUpgradeVersions(v []string) { - o.CpuFamily = &v + o.AvailableUpgradeVersions = &v } -// HasCpuFamily returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasCpuFamily() bool { - if o != nil && o.CpuFamily != nil { +// HasAvailableUpgradeVersions returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAvailableUpgradeVersions() bool { + if o != nil && o.AvailableUpgradeVersions != nil { return true } @@ -231,7 +231,7 @@ func (o *KubernetesNodePoolProperties) HasCpuFamily() bool { } // GetCoresCount returns the CoresCount field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolProperties) GetCoresCount() *int32 { if o == nil { return nil @@ -268,190 +268,190 @@ func (o *KubernetesNodePoolProperties) HasCoresCount() bool { return false } -// GetRamSize returns the RamSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolProperties) GetRamSize() *int32 { +// GetCpuFamily returns the CpuFamily field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetCpuFamily() *string { if o == nil { return nil } - return o.RamSize + return o.CpuFamily } -// GetRamSizeOk returns a tuple with the RamSize field value +// GetCpuFamilyOk returns a tuple with the CpuFamily field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetRamSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolProperties) GetCpuFamilyOk() (*string, bool) { if o == nil { return nil, false } - return o.RamSize, true + return o.CpuFamily, true } -// SetRamSize sets field value -func (o *KubernetesNodePoolProperties) SetRamSize(v int32) { +// SetCpuFamily sets field value +func (o *KubernetesNodePoolProperties) SetCpuFamily(v string) { - o.RamSize = &v + o.CpuFamily = &v } -// HasRamSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasRamSize() bool { - if o != nil && o.RamSize != nil { +// HasCpuFamily returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasCpuFamily() bool { + if o != nil && o.CpuFamily != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetAvailabilityZone() *string { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetDatacenterId() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.DatacenterId } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAvailabilityZoneOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.DatacenterId, true } -// SetAvailabilityZone sets field value -func (o *KubernetesNodePoolProperties) SetAvailabilityZone(v string) { +// SetDatacenterId sets field value +func (o *KubernetesNodePoolProperties) SetDatacenterId(v string) { - o.AvailabilityZone = &v + o.DatacenterId = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetStorageType returns the StorageType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetStorageType() *string { +// GetK8sVersion returns the K8sVersion field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetK8sVersion() *string { if o == nil { return nil } - return o.StorageType + return o.K8sVersion } -// GetStorageTypeOk returns a tuple with the StorageType field value +// GetK8sVersionOk returns a tuple with the K8sVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetStorageTypeOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetK8sVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.StorageType, true + return o.K8sVersion, true } -// SetStorageType sets field value -func (o *KubernetesNodePoolProperties) SetStorageType(v string) { +// SetK8sVersion sets field value +func (o *KubernetesNodePoolProperties) SetK8sVersion(v string) { - o.StorageType = &v + o.K8sVersion = &v } -// HasStorageType returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasStorageType() bool { - if o != nil && o.StorageType != nil { +// HasK8sVersion returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasK8sVersion() bool { + if o != nil && o.K8sVersion != nil { return true } return false } -// GetStorageSize returns the StorageSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolProperties) GetStorageSize() *int32 { +// GetLabels returns the Labels field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetLabels() *map[string]string { if o == nil { return nil } - return o.StorageSize + return o.Labels } -// GetStorageSizeOk returns a tuple with the StorageSize field value +// GetLabelsOk returns a tuple with the Labels field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetStorageSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolProperties) GetLabelsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.StorageSize, true + return o.Labels, true } -// SetStorageSize sets field value -func (o *KubernetesNodePoolProperties) SetStorageSize(v int32) { +// SetLabels sets field value +func (o *KubernetesNodePoolProperties) SetLabels(v map[string]string) { - o.StorageSize = &v + o.Labels = &v } -// HasStorageSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasStorageSize() bool { - if o != nil && o.StorageSize != nil { +// HasLabels returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasLabels() bool { + if o != nil && o.Labels != nil { return true } return false } -// GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetK8sVersion() *string { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetLans() *[]KubernetesNodePoolLan { if o == nil { return nil } - return o.K8sVersion + return o.Lans } -// GetK8sVersionOk returns a tuple with the K8sVersion field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetK8sVersionOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetLansOk() (*[]KubernetesNodePoolLan, bool) { if o == nil { return nil, false } - return o.K8sVersion, true + return o.Lans, true } -// SetK8sVersion sets field value -func (o *KubernetesNodePoolProperties) SetK8sVersion(v string) { +// SetLans sets field value +func (o *KubernetesNodePoolProperties) SetLans(v []KubernetesNodePoolLan) { - o.K8sVersion = &v + o.Lans = &v } -// HasK8sVersion returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasK8sVersion() bool { - if o != nil && o.K8sVersion != nil { +// HasLans returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasLans() bool { + if o != nil && o.Lans != nil { return true } @@ -459,7 +459,7 @@ func (o *KubernetesNodePoolProperties) HasK8sVersion() bool { } // GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolProperties) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil @@ -496,228 +496,228 @@ func (o *KubernetesNodePoolProperties) HasMaintenanceWindow() bool { return false } -// GetAutoScaling returns the AutoScaling field value -// If the value is explicit nil, the zero value for KubernetesAutoScaling will be returned -func (o *KubernetesNodePoolProperties) GetAutoScaling() *KubernetesAutoScaling { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetName() *string { if o == nil { return nil } - return o.AutoScaling + return o.Name } -// GetAutoScalingOk returns a tuple with the AutoScaling field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { +func (o *KubernetesNodePoolProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.AutoScaling, true + return o.Name, true } -// SetAutoScaling sets field value -func (o *KubernetesNodePoolProperties) SetAutoScaling(v KubernetesAutoScaling) { +// SetName sets field value +func (o *KubernetesNodePoolProperties) SetName(v string) { - o.AutoScaling = &v + o.Name = &v } -// HasAutoScaling returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAutoScaling() bool { - if o != nil && o.AutoScaling != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLan will be returned -func (o *KubernetesNodePoolProperties) GetLans() *[]KubernetesNodePoolLan { +// GetNodeCount returns the NodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetNodeCount() *int32 { if o == nil { return nil } - return o.Lans + return o.NodeCount } -// GetLansOk returns a tuple with the Lans field value +// GetNodeCountOk returns a tuple with the NodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetLansOk() (*[]KubernetesNodePoolLan, bool) { +func (o *KubernetesNodePoolProperties) GetNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.NodeCount, true } -// SetLans sets field value -func (o *KubernetesNodePoolProperties) SetLans(v []KubernetesNodePoolLan) { +// SetNodeCount sets field value +func (o *KubernetesNodePoolProperties) SetNodeCount(v int32) { - o.Lans = &v + o.NodeCount = &v } -// HasLans returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasLans() bool { - if o != nil && o.Lans != nil { +// HasNodeCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasNodeCount() bool { + if o != nil && o.NodeCount != nil { return true } return false } -// GetLabels returns the Labels field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolProperties) GetLabels() *map[string]string { +// GetPublicIps returns the PublicIps field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetPublicIps() *[]string { if o == nil { return nil } - return o.Labels + return o.PublicIps } -// GetLabelsOk returns a tuple with the Labels field value +// GetPublicIpsOk returns a tuple with the PublicIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetLabelsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolProperties) GetPublicIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Labels, true + return o.PublicIps, true } -// SetLabels sets field value -func (o *KubernetesNodePoolProperties) SetLabels(v map[string]string) { +// SetPublicIps sets field value +func (o *KubernetesNodePoolProperties) SetPublicIps(v []string) { - o.Labels = &v + o.PublicIps = &v } -// HasLabels returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasLabels() bool { - if o != nil && o.Labels != nil { +// HasPublicIps returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasPublicIps() bool { + if o != nil && o.PublicIps != nil { return true } return false } -// GetAnnotations returns the Annotations field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolProperties) GetAnnotations() *map[string]string { +// GetRamSize returns the RamSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetRamSize() *int32 { if o == nil { return nil } - return o.Annotations + return o.RamSize } -// GetAnnotationsOk returns a tuple with the Annotations field value +// GetRamSizeOk returns a tuple with the RamSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAnnotationsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolProperties) GetRamSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Annotations, true + return o.RamSize, true } -// SetAnnotations sets field value -func (o *KubernetesNodePoolProperties) SetAnnotations(v map[string]string) { +// SetRamSize sets field value +func (o *KubernetesNodePoolProperties) SetRamSize(v int32) { - o.Annotations = &v + o.RamSize = &v } -// HasAnnotations returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAnnotations() bool { - if o != nil && o.Annotations != nil { +// HasRamSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasRamSize() bool { + if o != nil && o.RamSize != nil { return true } return false } -// GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesNodePoolProperties) GetPublicIps() *[]string { +// GetStorageSize returns the StorageSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetStorageSize() *int32 { if o == nil { return nil } - return o.PublicIps + return o.StorageSize } -// GetPublicIpsOk returns a tuple with the PublicIps field value +// GetStorageSizeOk returns a tuple with the StorageSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetPublicIpsOk() (*[]string, bool) { +func (o *KubernetesNodePoolProperties) GetStorageSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.PublicIps, true + return o.StorageSize, true } -// SetPublicIps sets field value -func (o *KubernetesNodePoolProperties) SetPublicIps(v []string) { +// SetStorageSize sets field value +func (o *KubernetesNodePoolProperties) SetStorageSize(v int32) { - o.PublicIps = &v + o.StorageSize = &v } -// HasPublicIps returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasPublicIps() bool { - if o != nil && o.PublicIps != nil { +// HasStorageSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasStorageSize() bool { + if o != nil && o.StorageSize != nil { return true } return false } -// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersions() *[]string { +// GetStorageType returns the StorageType field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetStorageType() *string { if o == nil { return nil } - return o.AvailableUpgradeVersions + return o.StorageType } -// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value +// GetStorageTypeOk returns a tuple with the StorageType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { +func (o *KubernetesNodePoolProperties) GetStorageTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailableUpgradeVersions, true + return o.StorageType, true } -// SetAvailableUpgradeVersions sets field value -func (o *KubernetesNodePoolProperties) SetAvailableUpgradeVersions(v []string) { +// SetStorageType sets field value +func (o *KubernetesNodePoolProperties) SetStorageType(v string) { - o.AvailableUpgradeVersions = &v + o.StorageType = &v } -// HasAvailableUpgradeVersions returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAvailableUpgradeVersions() bool { - if o != nil && o.AvailableUpgradeVersions != nil { +// HasStorageType returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasStorageType() bool { + if o != nil && o.StorageType != nil { return true } @@ -726,57 +726,74 @@ func (o *KubernetesNodePoolProperties) HasAvailableUpgradeVersions() bool { func (o KubernetesNodePoolProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.Annotations != nil { + toSerialize["annotations"] = o.Annotations } - if o.DatacenterId != nil { - toSerialize["datacenterId"] = o.DatacenterId + + if o.AutoScaling != nil { + toSerialize["autoScaling"] = o.AutoScaling } - if o.NodeCount != nil { - toSerialize["nodeCount"] = o.NodeCount + + if o.AvailabilityZone != nil { + toSerialize["availabilityZone"] = o.AvailabilityZone } - if o.CpuFamily != nil { - toSerialize["cpuFamily"] = o.CpuFamily + + if o.AvailableUpgradeVersions != nil { + toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions } + if o.CoresCount != nil { toSerialize["coresCount"] = o.CoresCount } - if o.RamSize != nil { - toSerialize["ramSize"] = o.RamSize - } - if o.AvailabilityZone != nil { - toSerialize["availabilityZone"] = o.AvailabilityZone - } - if o.StorageType != nil { - toSerialize["storageType"] = o.StorageType + + if o.CpuFamily != nil { + toSerialize["cpuFamily"] = o.CpuFamily } - if o.StorageSize != nil { - toSerialize["storageSize"] = o.StorageSize + + if o.DatacenterId != nil { + toSerialize["datacenterId"] = o.DatacenterId } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } - if o.MaintenanceWindow != nil { - toSerialize["maintenanceWindow"] = o.MaintenanceWindow - } - if o.AutoScaling != nil { - toSerialize["autoScaling"] = o.AutoScaling + + if o.Labels != nil { + toSerialize["labels"] = o.Labels } + if o.Lans != nil { toSerialize["lans"] = o.Lans } - if o.Labels != nil { - toSerialize["labels"] = o.Labels + + if o.MaintenanceWindow != nil { + toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.Annotations != nil { - toSerialize["annotations"] = o.Annotations + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.NodeCount != nil { + toSerialize["nodeCount"] = o.NodeCount } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } - if o.AvailableUpgradeVersions != nil { - toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions + + if o.RamSize != nil { + toSerialize["ramSize"] = o.RamSize } + + if o.StorageSize != nil { + toSerialize["storageSize"] = o.StorageSize + } + + if o.StorageType != nil { + toSerialize["storageType"] = o.StorageType + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go index dff10d338..c55191cfa 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go @@ -16,54 +16,54 @@ import ( // KubernetesNodePoolPropertiesForPost struct for KubernetesNodePoolPropertiesForPost type KubernetesNodePoolPropertiesForPost struct { - // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // The annotations attached to the node pool. + Annotations *map[string]string `json:"annotations,omitempty"` + AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` + // The availability zone in which the target VM should be provisioned. + AvailabilityZone *string `json:"availabilityZone"` + // The total number of cores for the nodes. + CoresCount *int32 `json:"coresCount"` + // The CPU type for the nodes. + CpuFamily *string `json:"cpuFamily"` // The unique identifier of the VDC where the worker nodes of the node pool are provisioned.Note that the data center is located in the exact place where the parent cluster of the node pool is located. DatacenterId *string `json:"datacenterId"` + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // The labels attached to the node pool. + Labels *map[string]string `json:"labels,omitempty"` + // The array of existing private LANs to attach to worker nodes. + Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` + // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // The number of worker nodes of the node pool. NodeCount *int32 `json:"nodeCount"` - // The CPU type for the nodes. - CpuFamily *string `json:"cpuFamily"` - // The total number of cores for the nodes. - CoresCount *int32 `json:"coresCount"` + // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. + PublicIps *[]string `json:"publicIps,omitempty"` // The RAM size for the nodes. Must be specified in multiples of 1024 MB, with a minimum size of 2048 MB. RamSize *int32 `json:"ramSize"` - // The availability zone in which the target VM should be provisioned. - AvailabilityZone *string `json:"availabilityZone"` - // The storage type for the nodes. - StorageType *string `json:"storageType"` // The allocated volume size in GB. The allocated volume size in GB. To achieve good performance, we recommend a size greater than 100GB for SSD. StorageSize *int32 `json:"storageSize"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` - // The array of existing private LANs to attach to worker nodes. - Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` - // The labels attached to the node pool. - Labels *map[string]string `json:"labels,omitempty"` - // The annotations attached to the node pool. - Annotations *map[string]string `json:"annotations,omitempty"` - // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. - PublicIps *[]string `json:"publicIps,omitempty"` + // The storage type for the nodes. + StorageType *string `json:"storageType"` } // NewKubernetesNodePoolPropertiesForPost instantiates a new KubernetesNodePoolPropertiesForPost object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesNodePoolPropertiesForPost(name string, datacenterId string, nodeCount int32, cpuFamily string, coresCount int32, ramSize int32, availabilityZone string, storageType string, storageSize int32) *KubernetesNodePoolPropertiesForPost { +func NewKubernetesNodePoolPropertiesForPost(availabilityZone string, coresCount int32, cpuFamily string, datacenterId string, name string, nodeCount int32, ramSize int32, storageSize int32, storageType string) *KubernetesNodePoolPropertiesForPost { this := KubernetesNodePoolPropertiesForPost{} - this.Name = &name + this.AvailabilityZone = &availabilityZone + this.CoresCount = &coresCount + this.CpuFamily = &cpuFamily this.DatacenterId = &datacenterId + this.Name = &name this.NodeCount = &nodeCount - this.CpuFamily = &cpuFamily - this.CoresCount = &coresCount this.RamSize = &ramSize - this.AvailabilityZone = &availabilityZone - this.StorageType = &storageType this.StorageSize = &storageSize + this.StorageType = &storageType return &this } @@ -76,608 +76,608 @@ func NewKubernetesNodePoolPropertiesForPostWithDefaults() *KubernetesNodePoolPro return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetName() *string { +// GetAnnotations returns the Annotations field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetAnnotations() *map[string]string { if o == nil { return nil } - return o.Name + return o.Annotations } -// GetNameOk returns a tuple with the Name field value +// GetAnnotationsOk returns a tuple with the Annotations field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetNameOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetAnnotationsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Annotations, true } -// SetName sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetName(v string) { +// SetAnnotations sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetAnnotations(v map[string]string) { - o.Name = &v + o.Annotations = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasName() bool { - if o != nil && o.Name != nil { +// HasAnnotations returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasAnnotations() bool { + if o != nil && o.Annotations != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterId() *string { +// GetAutoScaling returns the AutoScaling field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetAutoScaling() *KubernetesAutoScaling { if o == nil { return nil } - return o.DatacenterId + return o.AutoScaling } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetAutoScalingOk returns a tuple with the AutoScaling field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterIdOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.AutoScaling, true } -// SetDatacenterId sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetDatacenterId(v string) { +// SetAutoScaling sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetAutoScaling(v KubernetesAutoScaling) { - o.DatacenterId = &v + o.AutoScaling = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasAutoScaling returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasAutoScaling() bool { + if o != nil && o.AutoScaling != nil { return true } return false } -// GetNodeCount returns the NodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetNodeCount() *int32 { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZone() *string { if o == nil { return nil } - return o.NodeCount + return o.AvailabilityZone } -// GetNodeCountOk returns a tuple with the NodeCount field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetNodeCountOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.NodeCount, true + return o.AvailabilityZone, true } -// SetNodeCount sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetNodeCount(v int32) { +// SetAvailabilityZone sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetAvailabilityZone(v string) { - o.NodeCount = &v + o.AvailabilityZone = &v } -// HasNodeCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasNodeCount() bool { - if o != nil && o.NodeCount != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamily() *string { +// GetCoresCount returns the CoresCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetCoresCount() *int32 { if o == nil { return nil } - return o.CpuFamily + return o.CoresCount } -// GetCpuFamilyOk returns a tuple with the CpuFamily field value +// GetCoresCountOk returns a tuple with the CoresCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamilyOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetCoresCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.CpuFamily, true + return o.CoresCount, true } -// SetCpuFamily sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetCpuFamily(v string) { +// SetCoresCount sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetCoresCount(v int32) { - o.CpuFamily = &v + o.CoresCount = &v } -// HasCpuFamily returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasCpuFamily() bool { - if o != nil && o.CpuFamily != nil { +// HasCoresCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasCoresCount() bool { + if o != nil && o.CoresCount != nil { return true } return false } -// GetCoresCount returns the CoresCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCoresCount() *int32 { +// GetCpuFamily returns the CpuFamily field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamily() *string { if o == nil { return nil } - return o.CoresCount + return o.CpuFamily } -// GetCoresCountOk returns a tuple with the CoresCount field value +// GetCpuFamilyOk returns a tuple with the CpuFamily field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCoresCountOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamilyOk() (*string, bool) { if o == nil { return nil, false } - return o.CoresCount, true + return o.CpuFamily, true } -// SetCoresCount sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetCoresCount(v int32) { +// SetCpuFamily sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetCpuFamily(v string) { - o.CoresCount = &v + o.CpuFamily = &v } -// HasCoresCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasCoresCount() bool { - if o != nil && o.CoresCount != nil { +// HasCpuFamily returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasCpuFamily() bool { + if o != nil && o.CpuFamily != nil { return true } return false } -// GetRamSize returns the RamSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetRamSize() *int32 { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterId() *string { if o == nil { return nil } - return o.RamSize + return o.DatacenterId } -// GetRamSizeOk returns a tuple with the RamSize field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetRamSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.RamSize, true + return o.DatacenterId, true } -// SetRamSize sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetRamSize(v int32) { +// SetDatacenterId sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetDatacenterId(v string) { - o.RamSize = &v + o.DatacenterId = &v } -// HasRamSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasRamSize() bool { - if o != nil && o.RamSize != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZone() *string { +// GetK8sVersion returns the K8sVersion field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersion() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.K8sVersion } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetK8sVersionOk returns a tuple with the K8sVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZoneOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.K8sVersion, true } -// SetAvailabilityZone sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetAvailabilityZone(v string) { +// SetK8sVersion sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetK8sVersion(v string) { - o.AvailabilityZone = &v + o.K8sVersion = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasK8sVersion returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasK8sVersion() bool { + if o != nil && o.K8sVersion != nil { return true } return false } -// GetStorageType returns the StorageType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageType() *string { +// GetLabels returns the Labels field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetLabels() *map[string]string { if o == nil { return nil } - return o.StorageType + return o.Labels } -// GetStorageTypeOk returns a tuple with the StorageType field value +// GetLabelsOk returns a tuple with the Labels field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageTypeOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetLabelsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.StorageType, true + return o.Labels, true } -// SetStorageType sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetStorageType(v string) { +// SetLabels sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetLabels(v map[string]string) { - o.StorageType = &v + o.Labels = &v } -// HasStorageType returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasStorageType() bool { - if o != nil && o.StorageType != nil { +// HasLabels returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasLabels() bool { + if o != nil && o.Labels != nil { return true } return false } -// GetStorageSize returns the StorageSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageSize() *int32 { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetLans() *[]KubernetesNodePoolLan { if o == nil { return nil } - return o.StorageSize + return o.Lans } -// GetStorageSizeOk returns a tuple with the StorageSize field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetLansOk() (*[]KubernetesNodePoolLan, bool) { if o == nil { return nil, false } - return o.StorageSize, true + return o.Lans, true } -// SetStorageSize sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetStorageSize(v int32) { +// SetLans sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetLans(v []KubernetesNodePoolLan) { - o.StorageSize = &v + o.Lans = &v } -// HasStorageSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasStorageSize() bool { - if o != nil && o.StorageSize != nil { +// HasLans returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersion() *string { +// GetMaintenanceWindow returns the MaintenanceWindow field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil } - return o.K8sVersion + return o.MaintenanceWindow } -// GetK8sVersionOk returns a tuple with the K8sVersion field value +// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersionOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { if o == nil { return nil, false } - return o.K8sVersion, true + return o.MaintenanceWindow, true } -// SetK8sVersion sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetK8sVersion(v string) { +// SetMaintenanceWindow sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { - o.K8sVersion = &v + o.MaintenanceWindow = &v } -// HasK8sVersion returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasK8sVersion() bool { - if o != nil && o.K8sVersion != nil { +// HasMaintenanceWindow returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasMaintenanceWindow() bool { + if o != nil && o.MaintenanceWindow != nil { return true } return false } -// GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindow() *KubernetesMaintenanceWindow { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetName() *string { if o == nil { return nil } - return o.MaintenanceWindow + return o.Name } -// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.MaintenanceWindow, true + return o.Name, true } -// SetMaintenanceWindow sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { +// SetName sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetName(v string) { - o.MaintenanceWindow = &v + o.Name = &v } -// HasMaintenanceWindow returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasMaintenanceWindow() bool { - if o != nil && o.MaintenanceWindow != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetAutoScaling returns the AutoScaling field value -// If the value is explicit nil, the zero value for KubernetesAutoScaling will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAutoScaling() *KubernetesAutoScaling { +// GetNodeCount returns the NodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetNodeCount() *int32 { if o == nil { return nil } - return o.AutoScaling + return o.NodeCount } -// GetAutoScalingOk returns a tuple with the AutoScaling field value +// GetNodeCountOk returns a tuple with the NodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.AutoScaling, true + return o.NodeCount, true } -// SetAutoScaling sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetAutoScaling(v KubernetesAutoScaling) { +// SetNodeCount sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetNodeCount(v int32) { - o.AutoScaling = &v + o.NodeCount = &v } -// HasAutoScaling returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasAutoScaling() bool { - if o != nil && o.AutoScaling != nil { +// HasNodeCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasNodeCount() bool { + if o != nil && o.NodeCount != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLan will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLans() *[]KubernetesNodePoolLan { +// GetPublicIps returns the PublicIps field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetPublicIps() *[]string { if o == nil { return nil } - return o.Lans + return o.PublicIps } -// GetLansOk returns a tuple with the Lans field value +// GetPublicIpsOk returns a tuple with the PublicIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLansOk() (*[]KubernetesNodePoolLan, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetPublicIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.PublicIps, true } -// SetLans sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetLans(v []KubernetesNodePoolLan) { +// SetPublicIps sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetPublicIps(v []string) { - o.Lans = &v + o.PublicIps = &v } -// HasLans returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasLans() bool { - if o != nil && o.Lans != nil { +// HasPublicIps returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasPublicIps() bool { + if o != nil && o.PublicIps != nil { return true } return false } -// GetLabels returns the Labels field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLabels() *map[string]string { +// GetRamSize returns the RamSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetRamSize() *int32 { if o == nil { return nil } - return o.Labels + return o.RamSize } -// GetLabelsOk returns a tuple with the Labels field value +// GetRamSizeOk returns a tuple with the RamSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLabelsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetRamSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Labels, true + return o.RamSize, true } -// SetLabels sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetLabels(v map[string]string) { +// SetRamSize sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetRamSize(v int32) { - o.Labels = &v + o.RamSize = &v } -// HasLabels returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasLabels() bool { - if o != nil && o.Labels != nil { +// HasRamSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasRamSize() bool { + if o != nil && o.RamSize != nil { return true } return false } -// GetAnnotations returns the Annotations field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAnnotations() *map[string]string { +// GetStorageSize returns the StorageSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetStorageSize() *int32 { if o == nil { return nil } - return o.Annotations + return o.StorageSize } -// GetAnnotationsOk returns a tuple with the Annotations field value +// GetStorageSizeOk returns a tuple with the StorageSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAnnotationsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetStorageSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Annotations, true + return o.StorageSize, true } -// SetAnnotations sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetAnnotations(v map[string]string) { +// SetStorageSize sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetStorageSize(v int32) { - o.Annotations = &v + o.StorageSize = &v } -// HasAnnotations returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasAnnotations() bool { - if o != nil && o.Annotations != nil { +// HasStorageSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasStorageSize() bool { + if o != nil && o.StorageSize != nil { return true } return false } -// GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetPublicIps() *[]string { +// GetStorageType returns the StorageType field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetStorageType() *string { if o == nil { return nil } - return o.PublicIps + return o.StorageType } -// GetPublicIpsOk returns a tuple with the PublicIps field value +// GetStorageTypeOk returns a tuple with the StorageType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetPublicIpsOk() (*[]string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetStorageTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.PublicIps, true + return o.StorageType, true } -// SetPublicIps sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetPublicIps(v []string) { +// SetStorageType sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetStorageType(v string) { - o.PublicIps = &v + o.StorageType = &v } -// HasPublicIps returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasPublicIps() bool { - if o != nil && o.PublicIps != nil { +// HasStorageType returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasStorageType() bool { + if o != nil && o.StorageType != nil { return true } @@ -686,54 +686,70 @@ func (o *KubernetesNodePoolPropertiesForPost) HasPublicIps() bool { func (o KubernetesNodePoolPropertiesForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.DatacenterId != nil { - toSerialize["datacenterId"] = o.DatacenterId + if o.Annotations != nil { + toSerialize["annotations"] = o.Annotations } - if o.NodeCount != nil { - toSerialize["nodeCount"] = o.NodeCount + + if o.AutoScaling != nil { + toSerialize["autoScaling"] = o.AutoScaling } - if o.CpuFamily != nil { - toSerialize["cpuFamily"] = o.CpuFamily + + if o.AvailabilityZone != nil { + toSerialize["availabilityZone"] = o.AvailabilityZone } + if o.CoresCount != nil { toSerialize["coresCount"] = o.CoresCount } - if o.RamSize != nil { - toSerialize["ramSize"] = o.RamSize - } - if o.AvailabilityZone != nil { - toSerialize["availabilityZone"] = o.AvailabilityZone - } - if o.StorageType != nil { - toSerialize["storageType"] = o.StorageType + + if o.CpuFamily != nil { + toSerialize["cpuFamily"] = o.CpuFamily } - if o.StorageSize != nil { - toSerialize["storageSize"] = o.StorageSize + + if o.DatacenterId != nil { + toSerialize["datacenterId"] = o.DatacenterId } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } - if o.MaintenanceWindow != nil { - toSerialize["maintenanceWindow"] = o.MaintenanceWindow - } - if o.AutoScaling != nil { - toSerialize["autoScaling"] = o.AutoScaling + + if o.Labels != nil { + toSerialize["labels"] = o.Labels } + if o.Lans != nil { toSerialize["lans"] = o.Lans } - if o.Labels != nil { - toSerialize["labels"] = o.Labels + + if o.MaintenanceWindow != nil { + toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.Annotations != nil { - toSerialize["annotations"] = o.Annotations + + if o.Name != nil { + toSerialize["name"] = o.Name } + + if o.NodeCount != nil { + toSerialize["nodeCount"] = o.NodeCount + } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } + + if o.RamSize != nil { + toSerialize["ramSize"] = o.RamSize + } + + if o.StorageSize != nil { + toSerialize["storageSize"] = o.StorageSize + } + + if o.StorageType != nil { + toSerialize["storageType"] = o.StorageType + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go index 88c31def6..3e82ea9c4 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go @@ -16,20 +16,20 @@ import ( // KubernetesNodePoolPropertiesForPut struct for KubernetesNodePoolPropertiesForPut type KubernetesNodePoolPropertiesForPut struct { + // The annotations attached to the node pool. + Annotations *map[string]string `json:"annotations,omitempty"` + AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // The labels attached to the node pool. + Labels *map[string]string `json:"labels,omitempty"` + // The array of existing private LANs to attach to worker nodes. + Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. Name *string `json:"name,omitempty"` // The number of worker nodes of the node pool. NodeCount *int32 `json:"nodeCount"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` - // The array of existing private LANs to attach to worker nodes. - Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` - // The labels attached to the node pool. - Labels *map[string]string `json:"labels,omitempty"` - // The annotations attached to the node pool. - Annotations *map[string]string `json:"annotations,omitempty"` // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. PublicIps *[]string `json:"publicIps,omitempty"` } @@ -54,76 +54,76 @@ func NewKubernetesNodePoolPropertiesForPutWithDefaults() *KubernetesNodePoolProp return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetName() *string { +// GetAnnotations returns the Annotations field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetAnnotations() *map[string]string { if o == nil { return nil } - return o.Name + return o.Annotations } -// GetNameOk returns a tuple with the Name field value +// GetAnnotationsOk returns a tuple with the Annotations field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetNameOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetAnnotationsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Annotations, true } -// SetName sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetName(v string) { +// SetAnnotations sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetAnnotations(v map[string]string) { - o.Name = &v + o.Annotations = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasName() bool { - if o != nil && o.Name != nil { +// HasAnnotations returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasAnnotations() bool { + if o != nil && o.Annotations != nil { return true } return false } -// GetNodeCount returns the NodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetNodeCount() *int32 { +// GetAutoScaling returns the AutoScaling field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetAutoScaling() *KubernetesAutoScaling { if o == nil { return nil } - return o.NodeCount + return o.AutoScaling } -// GetNodeCountOk returns a tuple with the NodeCount field value +// GetAutoScalingOk returns a tuple with the AutoScaling field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetNodeCountOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { if o == nil { return nil, false } - return o.NodeCount, true + return o.AutoScaling, true } -// SetNodeCount sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetNodeCount(v int32) { +// SetAutoScaling sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetAutoScaling(v KubernetesAutoScaling) { - o.NodeCount = &v + o.AutoScaling = &v } -// HasNodeCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasNodeCount() bool { - if o != nil && o.NodeCount != nil { +// HasAutoScaling returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasAutoScaling() bool { + if o != nil && o.AutoScaling != nil { return true } @@ -131,7 +131,7 @@ func (o *KubernetesNodePoolPropertiesForPut) HasNodeCount() bool { } // GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolPropertiesForPut) GetK8sVersion() *string { if o == nil { return nil @@ -168,190 +168,190 @@ func (o *KubernetesNodePoolPropertiesForPut) HasK8sVersion() bool { return false } -// GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindow() *KubernetesMaintenanceWindow { +// GetLabels returns the Labels field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetLabels() *map[string]string { if o == nil { return nil } - return o.MaintenanceWindow + return o.Labels } -// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value +// GetLabelsOk returns a tuple with the Labels field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetLabelsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.MaintenanceWindow, true + return o.Labels, true } -// SetMaintenanceWindow sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { +// SetLabels sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetLabels(v map[string]string) { - o.MaintenanceWindow = &v + o.Labels = &v } -// HasMaintenanceWindow returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasMaintenanceWindow() bool { - if o != nil && o.MaintenanceWindow != nil { +// HasLabels returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasLabels() bool { + if o != nil && o.Labels != nil { return true } return false } -// GetAutoScaling returns the AutoScaling field value -// If the value is explicit nil, the zero value for KubernetesAutoScaling will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAutoScaling() *KubernetesAutoScaling { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetLans() *[]KubernetesNodePoolLan { if o == nil { return nil } - return o.AutoScaling + return o.Lans } -// GetAutoScalingOk returns a tuple with the AutoScaling field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetLansOk() (*[]KubernetesNodePoolLan, bool) { if o == nil { return nil, false } - return o.AutoScaling, true + return o.Lans, true } -// SetAutoScaling sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetAutoScaling(v KubernetesAutoScaling) { +// SetLans sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetLans(v []KubernetesNodePoolLan) { - o.AutoScaling = &v + o.Lans = &v } -// HasAutoScaling returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasAutoScaling() bool { - if o != nil && o.AutoScaling != nil { +// HasLans returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLan will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLans() *[]KubernetesNodePoolLan { +// GetMaintenanceWindow returns the MaintenanceWindow field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil } - return o.Lans + return o.MaintenanceWindow } -// GetLansOk returns a tuple with the Lans field value +// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLansOk() (*[]KubernetesNodePoolLan, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.MaintenanceWindow, true } -// SetLans sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetLans(v []KubernetesNodePoolLan) { +// SetMaintenanceWindow sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { - o.Lans = &v + o.MaintenanceWindow = &v } -// HasLans returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasLans() bool { - if o != nil && o.Lans != nil { +// HasMaintenanceWindow returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasMaintenanceWindow() bool { + if o != nil && o.MaintenanceWindow != nil { return true } return false } -// GetLabels returns the Labels field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLabels() *map[string]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetName() *string { if o == nil { return nil } - return o.Labels + return o.Name } -// GetLabelsOk returns a tuple with the Labels field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLabelsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Labels, true + return o.Name, true } -// SetLabels sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetLabels(v map[string]string) { +// SetName sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetName(v string) { - o.Labels = &v + o.Name = &v } -// HasLabels returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasLabels() bool { - if o != nil && o.Labels != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetAnnotations returns the Annotations field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAnnotations() *map[string]string { +// GetNodeCount returns the NodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetNodeCount() *int32 { if o == nil { return nil } - return o.Annotations + return o.NodeCount } -// GetAnnotationsOk returns a tuple with the Annotations field value +// GetNodeCountOk returns a tuple with the NodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAnnotationsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.Annotations, true + return o.NodeCount, true } -// SetAnnotations sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetAnnotations(v map[string]string) { +// SetNodeCount sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetNodeCount(v int32) { - o.Annotations = &v + o.NodeCount = &v } -// HasAnnotations returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasAnnotations() bool { - if o != nil && o.Annotations != nil { +// HasNodeCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasNodeCount() bool { + if o != nil && o.NodeCount != nil { return true } @@ -359,7 +359,7 @@ func (o *KubernetesNodePoolPropertiesForPut) HasAnnotations() bool { } // GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolPropertiesForPut) GetPublicIps() *[]string { if o == nil { return nil @@ -398,33 +398,42 @@ func (o *KubernetesNodePoolPropertiesForPut) HasPublicIps() bool { func (o KubernetesNodePoolPropertiesForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.Annotations != nil { + toSerialize["annotations"] = o.Annotations } - if o.NodeCount != nil { - toSerialize["nodeCount"] = o.NodeCount + + if o.AutoScaling != nil { + toSerialize["autoScaling"] = o.AutoScaling } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } - if o.MaintenanceWindow != nil { - toSerialize["maintenanceWindow"] = o.MaintenanceWindow - } - if o.AutoScaling != nil { - toSerialize["autoScaling"] = o.AutoScaling + + if o.Labels != nil { + toSerialize["labels"] = o.Labels } + if o.Lans != nil { toSerialize["lans"] = o.Lans } - if o.Labels != nil { - toSerialize["labels"] = o.Labels + + if o.MaintenanceWindow != nil { + toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.Annotations != nil { - toSerialize["annotations"] = o.Annotations + + if o.Name != nil { + toSerialize["name"] = o.Name } + + if o.NodeCount != nil { + toSerialize["nodeCount"] = o.NodeCount + } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go index 61df80e6d..50ebf5568 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePools struct for KubernetesNodePools type KubernetesNodePools struct { - // A unique representation of the Kubernetes node pool as a resource collection. - Id *string `json:"id,omitempty"` - // The resource type within a collection. - Type *string `json:"type,omitempty"` // The URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the Kubernetes node pool as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]KubernetesNodePool `json:"items,omitempty"` + // The resource type within a collection. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePools instantiates a new KubernetesNodePools object @@ -44,152 +44,152 @@ func NewKubernetesNodePoolsWithDefaults() *KubernetesNodePools { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePools) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetIdOk() (*string, bool) { +func (o *KubernetesNodePools) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePools) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePools) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePools) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePools) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePools) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePools) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePools) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetItems() *[]KubernetesNodePool { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePools) GetItemsOk() (*[]KubernetesNodePool, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *KubernetesNodePools) SetHref(v string) { +// SetItems sets field value +func (o *KubernetesNodePools) SetItems(v []KubernetesNodePool) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []KubernetesNodePool will be returned -func (o *KubernetesNodePools) GetItems() *[]KubernetesNodePool { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetItemsOk() (*[]KubernetesNodePool, bool) { +func (o *KubernetesNodePools) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *KubernetesNodePools) SetItems(v []KubernetesNodePool) { +// SetType sets field value +func (o *KubernetesNodePools) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *KubernetesNodePools) HasItems() bool { func (o KubernetesNodePools) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go index 652521484..e5f67c963 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go @@ -16,25 +16,25 @@ import ( // KubernetesNodeProperties struct for KubernetesNodeProperties type KubernetesNodeProperties struct { + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion"` // The Kubernetes node name. Name *string `json:"name"` - // The public IP associated with the node. - PublicIP *string `json:"publicIP,omitempty"` // The private IP associated with the node. PrivateIP *string `json:"privateIP,omitempty"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion"` + // The public IP associated with the node. + PublicIP *string `json:"publicIP,omitempty"` } // NewKubernetesNodeProperties instantiates a new KubernetesNodeProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesNodeProperties(name string, k8sVersion string) *KubernetesNodeProperties { +func NewKubernetesNodeProperties(k8sVersion string, name string) *KubernetesNodeProperties { this := KubernetesNodeProperties{} - this.Name = &name this.K8sVersion = &k8sVersion + this.Name = &name return &this } @@ -47,76 +47,76 @@ func NewKubernetesNodePropertiesWithDefaults() *KubernetesNodeProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeProperties) GetName() *string { +// GetK8sVersion returns the K8sVersion field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeProperties) GetK8sVersion() *string { if o == nil { return nil } - return o.Name + return o.K8sVersion } -// GetNameOk returns a tuple with the Name field value +// GetK8sVersionOk returns a tuple with the K8sVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeProperties) GetNameOk() (*string, bool) { +func (o *KubernetesNodeProperties) GetK8sVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.K8sVersion, true } -// SetName sets field value -func (o *KubernetesNodeProperties) SetName(v string) { +// SetK8sVersion sets field value +func (o *KubernetesNodeProperties) SetK8sVersion(v string) { - o.Name = &v + o.K8sVersion = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodeProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasK8sVersion returns a boolean if a field has been set. +func (o *KubernetesNodeProperties) HasK8sVersion() bool { + if o != nil && o.K8sVersion != nil { return true } return false } -// GetPublicIP returns the PublicIP field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeProperties) GetPublicIP() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeProperties) GetName() *string { if o == nil { return nil } - return o.PublicIP + return o.Name } -// GetPublicIPOk returns a tuple with the PublicIP field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeProperties) GetPublicIPOk() (*string, bool) { +func (o *KubernetesNodeProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.PublicIP, true + return o.Name, true } -// SetPublicIP sets field value -func (o *KubernetesNodeProperties) SetPublicIP(v string) { +// SetName sets field value +func (o *KubernetesNodeProperties) SetName(v string) { - o.PublicIP = &v + o.Name = &v } -// HasPublicIP returns a boolean if a field has been set. -func (o *KubernetesNodeProperties) HasPublicIP() bool { - if o != nil && o.PublicIP != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodeProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -124,7 +124,7 @@ func (o *KubernetesNodeProperties) HasPublicIP() bool { } // GetPrivateIP returns the PrivateIP field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodeProperties) GetPrivateIP() *string { if o == nil { return nil @@ -161,38 +161,38 @@ func (o *KubernetesNodeProperties) HasPrivateIP() bool { return false } -// GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeProperties) GetK8sVersion() *string { +// GetPublicIP returns the PublicIP field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeProperties) GetPublicIP() *string { if o == nil { return nil } - return o.K8sVersion + return o.PublicIP } -// GetK8sVersionOk returns a tuple with the K8sVersion field value +// GetPublicIPOk returns a tuple with the PublicIP field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeProperties) GetK8sVersionOk() (*string, bool) { +func (o *KubernetesNodeProperties) GetPublicIPOk() (*string, bool) { if o == nil { return nil, false } - return o.K8sVersion, true + return o.PublicIP, true } -// SetK8sVersion sets field value -func (o *KubernetesNodeProperties) SetK8sVersion(v string) { +// SetPublicIP sets field value +func (o *KubernetesNodeProperties) SetPublicIP(v string) { - o.K8sVersion = &v + o.PublicIP = &v } -// HasK8sVersion returns a boolean if a field has been set. -func (o *KubernetesNodeProperties) HasK8sVersion() bool { - if o != nil && o.K8sVersion != nil { +// HasPublicIP returns a boolean if a field has been set. +func (o *KubernetesNodeProperties) HasPublicIP() bool { + if o != nil && o.PublicIP != nil { return true } @@ -201,18 +201,22 @@ func (o *KubernetesNodeProperties) HasK8sVersion() bool { func (o KubernetesNodeProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.K8sVersion != nil { + toSerialize["k8sVersion"] = o.K8sVersion + } + if o.Name != nil { toSerialize["name"] = o.Name } - if o.PublicIP != nil { - toSerialize["publicIP"] = o.PublicIP - } + if o.PrivateIP != nil { toSerialize["privateIP"] = o.PrivateIP } - if o.K8sVersion != nil { - toSerialize["k8sVersion"] = o.K8sVersion + + if o.PublicIP != nil { + toSerialize["publicIP"] = o.PublicIP } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go index e54f0c8d0..a96c03848 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go @@ -16,14 +16,14 @@ import ( // KubernetesNodes struct for KubernetesNodes type KubernetesNodes struct { - // A unique representation of the Kubernetes node pool as a resource collection. - Id *string `json:"id,omitempty"` - // The resource type within a collection. - Type *string `json:"type,omitempty"` // The URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the Kubernetes node pool as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]KubernetesNode `json:"items,omitempty"` + // The resource type within a collection. + Type *string `json:"type,omitempty"` } // NewKubernetesNodes instantiates a new KubernetesNodes object @@ -44,152 +44,152 @@ func NewKubernetesNodesWithDefaults() *KubernetesNodes { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodes) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetIdOk() (*string, bool) { +func (o *KubernetesNodes) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodes) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodes) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodes) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodes) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodes) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetTypeOk() (*string, bool) { +func (o *KubernetesNodes) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodes) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodes) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodes) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodes) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodes) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetItems() *[]KubernetesNode { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetHrefOk() (*string, bool) { +func (o *KubernetesNodes) GetItemsOk() (*[]KubernetesNode, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *KubernetesNodes) SetHref(v string) { +// SetItems sets field value +func (o *KubernetesNodes) SetItems(v []KubernetesNode) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodes) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *KubernetesNodes) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []KubernetesNode will be returned -func (o *KubernetesNodes) GetItems() *[]KubernetesNode { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetItemsOk() (*[]KubernetesNode, bool) { +func (o *KubernetesNodes) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *KubernetesNodes) SetItems(v []KubernetesNode) { +// SetType sets field value +func (o *KubernetesNodes) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *KubernetesNodes) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodes) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *KubernetesNodes) HasItems() bool { func (o KubernetesNodes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go index c162e6763..f28f2af59 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go @@ -16,14 +16,14 @@ import ( // Label struct for Label type Label struct { - // Label is identified using standard URN. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // Label is identified using standard URN. + Id *string `json:"id,omitempty"` Metadata *NoStateMetaData `json:"metadata,omitempty"` Properties *LabelProperties `json:"properties"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewLabel instantiates a new Label object @@ -46,190 +46,190 @@ func NewLabelWithDefaults() *Label { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Label) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Label) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetIdOk() (*string, bool) { +func (o *Label) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Label) SetId(v string) { +// SetHref sets field value +func (o *Label) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Label) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Label) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Label) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Label) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetTypeOk() (*string, bool) { +func (o *Label) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Label) SetType(v string) { +// SetId sets field value +func (o *Label) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Label) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Label) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Label) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Label) GetMetadata() *NoStateMetaData { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetHrefOk() (*string, bool) { +func (o *Label) GetMetadataOk() (*NoStateMetaData, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Label) SetHref(v string) { +// SetMetadata sets field value +func (o *Label) SetMetadata(v NoStateMetaData) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Label) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Label) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for NoStateMetaData will be returned -func (o *Label) GetMetadata() *NoStateMetaData { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Label) GetProperties() *LabelProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetMetadataOk() (*NoStateMetaData, bool) { +func (o *Label) GetPropertiesOk() (*LabelProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Label) SetMetadata(v NoStateMetaData) { +// SetProperties sets field value +func (o *Label) SetProperties(v LabelProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Label) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Label) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LabelProperties will be returned -func (o *Label) GetProperties() *LabelProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Label) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetPropertiesOk() (*LabelProperties, bool) { +func (o *Label) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Label) SetProperties(v LabelProperties) { +// SetType sets field value +func (o *Label) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Label) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Label) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Label) HasProperties() bool { func (o Label) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go index a7a0d794c..f561a5fb7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go @@ -18,14 +18,14 @@ import ( type LabelProperties struct { // A label key Key *string `json:"key,omitempty"` - // A label value - Value *string `json:"value,omitempty"` + // URL to the Resource (absolute path) on which the label is applied. + ResourceHref *string `json:"resourceHref,omitempty"` // The ID of the resource. ResourceId *string `json:"resourceId,omitempty"` // The type of the resource on which the label is applied. ResourceType *string `json:"resourceType,omitempty"` - // URL to the Resource (absolute path) on which the label is applied. - ResourceHref *string `json:"resourceHref,omitempty"` + // A label value + Value *string `json:"value,omitempty"` } // NewLabelProperties instantiates a new LabelProperties object @@ -47,7 +47,7 @@ func NewLabelPropertiesWithDefaults() *LabelProperties { } // GetKey returns the Key field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelProperties) GetKey() *string { if o == nil { return nil @@ -84,38 +84,38 @@ func (o *LabelProperties) HasKey() bool { return false } -// GetValue returns the Value field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelProperties) GetValue() *string { +// GetResourceHref returns the ResourceHref field value +// If the value is explicit nil, nil is returned +func (o *LabelProperties) GetResourceHref() *string { if o == nil { return nil } - return o.Value + return o.ResourceHref } -// GetValueOk returns a tuple with the Value field value +// GetResourceHrefOk returns a tuple with the ResourceHref field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelProperties) GetValueOk() (*string, bool) { +func (o *LabelProperties) GetResourceHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Value, true + return o.ResourceHref, true } -// SetValue sets field value -func (o *LabelProperties) SetValue(v string) { +// SetResourceHref sets field value +func (o *LabelProperties) SetResourceHref(v string) { - o.Value = &v + o.ResourceHref = &v } -// HasValue returns a boolean if a field has been set. -func (o *LabelProperties) HasValue() bool { - if o != nil && o.Value != nil { +// HasResourceHref returns a boolean if a field has been set. +func (o *LabelProperties) HasResourceHref() bool { + if o != nil && o.ResourceHref != nil { return true } @@ -123,7 +123,7 @@ func (o *LabelProperties) HasValue() bool { } // GetResourceId returns the ResourceId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelProperties) GetResourceId() *string { if o == nil { return nil @@ -161,7 +161,7 @@ func (o *LabelProperties) HasResourceId() bool { } // GetResourceType returns the ResourceType field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelProperties) GetResourceType() *string { if o == nil { return nil @@ -198,38 +198,38 @@ func (o *LabelProperties) HasResourceType() bool { return false } -// GetResourceHref returns the ResourceHref field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelProperties) GetResourceHref() *string { +// GetValue returns the Value field value +// If the value is explicit nil, nil is returned +func (o *LabelProperties) GetValue() *string { if o == nil { return nil } - return o.ResourceHref + return o.Value } -// GetResourceHrefOk returns a tuple with the ResourceHref field value +// GetValueOk returns a tuple with the Value field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelProperties) GetResourceHrefOk() (*string, bool) { +func (o *LabelProperties) GetValueOk() (*string, bool) { if o == nil { return nil, false } - return o.ResourceHref, true + return o.Value, true } -// SetResourceHref sets field value -func (o *LabelProperties) SetResourceHref(v string) { +// SetValue sets field value +func (o *LabelProperties) SetValue(v string) { - o.ResourceHref = &v + o.Value = &v } -// HasResourceHref returns a boolean if a field has been set. -func (o *LabelProperties) HasResourceHref() bool { - if o != nil && o.ResourceHref != nil { +// HasValue returns a boolean if a field has been set. +func (o *LabelProperties) HasValue() bool { + if o != nil && o.Value != nil { return true } @@ -241,18 +241,23 @@ func (o LabelProperties) MarshalJSON() ([]byte, error) { if o.Key != nil { toSerialize["key"] = o.Key } - if o.Value != nil { - toSerialize["value"] = o.Value + + if o.ResourceHref != nil { + toSerialize["resourceHref"] = o.ResourceHref } + if o.ResourceId != nil { toSerialize["resourceId"] = o.ResourceId } + if o.ResourceType != nil { toSerialize["resourceType"] = o.ResourceType } - if o.ResourceHref != nil { - toSerialize["resourceHref"] = o.ResourceHref + + if o.Value != nil { + toSerialize["value"] = o.Value } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go index 29ebef96d..9963122ac 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go @@ -16,14 +16,14 @@ import ( // LabelResource struct for LabelResource type LabelResource struct { - // Label on a resource is identified using label key. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // Label on a resource is identified using label key. + Id *string `json:"id,omitempty"` Metadata *NoStateMetaData `json:"metadata,omitempty"` Properties *LabelResourceProperties `json:"properties"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewLabelResource instantiates a new LabelResource object @@ -46,190 +46,190 @@ func NewLabelResourceWithDefaults() *LabelResource { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResource) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetIdOk() (*string, bool) { +func (o *LabelResource) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *LabelResource) SetId(v string) { +// SetHref sets field value +func (o *LabelResource) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *LabelResource) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *LabelResource) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResource) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetTypeOk() (*string, bool) { +func (o *LabelResource) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *LabelResource) SetType(v string) { +// SetId sets field value +func (o *LabelResource) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *LabelResource) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *LabelResource) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResource) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetMetadata() *NoStateMetaData { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetHrefOk() (*string, bool) { +func (o *LabelResource) GetMetadataOk() (*NoStateMetaData, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *LabelResource) SetHref(v string) { +// SetMetadata sets field value +func (o *LabelResource) SetMetadata(v NoStateMetaData) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *LabelResource) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *LabelResource) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for NoStateMetaData will be returned -func (o *LabelResource) GetMetadata() *NoStateMetaData { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetProperties() *LabelResourceProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetMetadataOk() (*NoStateMetaData, bool) { +func (o *LabelResource) GetPropertiesOk() (*LabelResourceProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *LabelResource) SetMetadata(v NoStateMetaData) { +// SetProperties sets field value +func (o *LabelResource) SetProperties(v LabelResourceProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *LabelResource) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *LabelResource) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LabelResourceProperties will be returned -func (o *LabelResource) GetProperties() *LabelResourceProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetPropertiesOk() (*LabelResourceProperties, bool) { +func (o *LabelResource) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *LabelResource) SetProperties(v LabelResourceProperties) { +// SetType sets field value +func (o *LabelResource) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *LabelResource) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *LabelResource) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *LabelResource) HasProperties() bool { func (o LabelResource) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go index ef0836dff..e83bc0c9f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go @@ -41,7 +41,7 @@ func NewLabelResourcePropertiesWithDefaults() *LabelResourceProperties { } // GetKey returns the Key field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelResourceProperties) GetKey() *string { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *LabelResourceProperties) HasKey() bool { } // GetValue returns the Value field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelResourceProperties) GetValue() *string { if o == nil { return nil @@ -121,9 +121,11 @@ func (o LabelResourceProperties) MarshalJSON() ([]byte, error) { if o.Key != nil { toSerialize["key"] = o.Key } + if o.Value != nil { toSerialize["value"] = o.Value } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go index 673f4f328..43bf07e05 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go @@ -16,19 +16,19 @@ import ( // LabelResources struct for LabelResources type LabelResources struct { - // A unique representation of the label as a resource collection. - Id *string `json:"id,omitempty"` - // The type of resource within a collection. - Type *string `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the label as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]LabelResource `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of resource within a collection. + Type *string `json:"type,omitempty"` } // NewLabelResources instantiates a new LabelResources object @@ -49,114 +49,114 @@ func NewLabelResourcesWithDefaults() *LabelResources { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResources) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetIdOk() (*string, bool) { +func (o *LabelResources) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *LabelResources) SetId(v string) { +// SetLinks sets field value +func (o *LabelResources) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *LabelResources) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *LabelResources) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResources) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetTypeOk() (*string, bool) { +func (o *LabelResources) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *LabelResources) SetType(v string) { +// SetHref sets field value +func (o *LabelResources) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *LabelResources) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *LabelResources) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResources) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetHrefOk() (*string, bool) { +func (o *LabelResources) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *LabelResources) SetHref(v string) { +// SetId sets field value +func (o *LabelResources) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *LabelResources) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *LabelResources) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *LabelResources) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []LabelResource will be returned +// If the value is explicit nil, nil is returned func (o *LabelResources) GetItems() *[]LabelResource { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *LabelResources) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LabelResources) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetOffsetOk() (*float32, bool) { +func (o *LabelResources) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *LabelResources) SetOffset(v float32) { +// SetLimit sets field value +func (o *LabelResources) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *LabelResources) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *LabelResources) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LabelResources) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetLimitOk() (*float32, bool) { +func (o *LabelResources) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *LabelResources) SetLimit(v float32) { +// SetOffset sets field value +func (o *LabelResources) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *LabelResources) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *LabelResources) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *LabelResources) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetType() *string { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetLinksOk() (*PaginationLinks, bool) { +func (o *LabelResources) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *LabelResources) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *LabelResources) SetType(v string) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *LabelResources) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *LabelResources) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *LabelResources) HasLinks() bool { func (o LabelResources) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go index d83bdbcfc..f2be7da33 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go @@ -16,14 +16,14 @@ import ( // Labels struct for Labels type Labels struct { - // A unique representation of the label as a resource collection. - Id *string `json:"id,omitempty"` - // The type of resource within a collection. - Type *string `json:"type,omitempty"` // URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the label as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Label `json:"items,omitempty"` + // The type of resource within a collection. + Type *string `json:"type,omitempty"` } // NewLabels instantiates a new Labels object @@ -44,152 +44,152 @@ func NewLabelsWithDefaults() *Labels { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Labels) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetIdOk() (*string, bool) { +func (o *Labels) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Labels) SetId(v string) { +// SetHref sets field value +func (o *Labels) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Labels) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Labels) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Labels) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetTypeOk() (*string, bool) { +func (o *Labels) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Labels) SetType(v string) { +// SetId sets field value +func (o *Labels) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Labels) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Labels) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Labels) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetItems() *[]Label { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetHrefOk() (*string, bool) { +func (o *Labels) GetItemsOk() (*[]Label, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Labels) SetHref(v string) { +// SetItems sets field value +func (o *Labels) SetItems(v []Label) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Labels) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Labels) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Label will be returned -func (o *Labels) GetItems() *[]Label { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetItemsOk() (*[]Label, bool) { +func (o *Labels) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Labels) SetItems(v []Label) { +// SetType sets field value +func (o *Labels) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Labels) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Labels) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Labels) HasItems() bool { func (o Labels) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go index 120c2f17f..09a44f4e3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go @@ -16,15 +16,15 @@ import ( // Lan struct for Lan type Lan struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *LanEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *LanProperties `json:"properties"` - Entities *LanEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLan instantiates a new Lan object @@ -47,114 +47,114 @@ func NewLanWithDefaults() *Lan { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lan) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetEntities() *LanEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetIdOk() (*string, bool) { +func (o *Lan) GetEntitiesOk() (*LanEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Lan) SetId(v string) { +// SetEntities sets field value +func (o *Lan) SetEntities(v LanEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Lan) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Lan) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Lan) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetTypeOk() (*Type, bool) { +func (o *Lan) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Lan) SetType(v Type) { +// SetHref sets field value +func (o *Lan) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Lan) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Lan) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lan) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetHrefOk() (*string, bool) { +func (o *Lan) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Lan) SetHref(v string) { +// SetId sets field value +func (o *Lan) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Lan) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Lan) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Lan) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Lan) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Lan) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LanProperties will be returned +// If the value is explicit nil, nil is returned func (o *Lan) GetProperties() *LanProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Lan) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for LanEntities will be returned -func (o *Lan) GetEntities() *LanEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetEntitiesOk() (*LanEntities, bool) { +func (o *Lan) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Lan) SetEntities(v LanEntities) { +// SetType sets field value +func (o *Lan) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Lan) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Lan) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Lan) HasEntities() bool { func (o Lan) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go index f4d242ac8..368746a43 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go @@ -38,7 +38,7 @@ func NewLanEntitiesWithDefaults() *LanEntities { } // GetNics returns the Nics field value -// If the value is explicit nil, the zero value for LanNics will be returned +// If the value is explicit nil, nil is returned func (o *LanEntities) GetNics() *LanNics { if o == nil { return nil @@ -80,6 +80,7 @@ func (o LanEntities) MarshalJSON() ([]byte, error) { if o.Nics != nil { toSerialize["nics"] = o.Nics } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go index f348c1458..06cc683fe 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go @@ -16,19 +16,19 @@ import ( // LanNics struct for LanNics type LanNics struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Nic `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLanNics instantiates a new LanNics object @@ -49,114 +49,114 @@ func NewLanNicsWithDefaults() *LanNics { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LanNics) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetIdOk() (*string, bool) { +func (o *LanNics) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *LanNics) SetId(v string) { +// SetLinks sets field value +func (o *LanNics) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *LanNics) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *LanNics) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *LanNics) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetTypeOk() (*Type, bool) { +func (o *LanNics) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *LanNics) SetType(v Type) { +// SetHref sets field value +func (o *LanNics) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *LanNics) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *LanNics) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LanNics) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetHrefOk() (*string, bool) { +func (o *LanNics) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *LanNics) SetHref(v string) { +// SetId sets field value +func (o *LanNics) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *LanNics) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *LanNics) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *LanNics) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Nic will be returned +// If the value is explicit nil, nil is returned func (o *LanNics) GetItems() *[]Nic { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *LanNics) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LanNics) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetOffsetOk() (*float32, bool) { +func (o *LanNics) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *LanNics) SetOffset(v float32) { +// SetLimit sets field value +func (o *LanNics) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *LanNics) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *LanNics) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LanNics) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetLimitOk() (*float32, bool) { +func (o *LanNics) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *LanNics) SetLimit(v float32) { +// SetOffset sets field value +func (o *LanNics) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *LanNics) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *LanNics) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *LanNics) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetLinksOk() (*PaginationLinks, bool) { +func (o *LanNics) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *LanNics) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *LanNics) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *LanNics) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *LanNics) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *LanNics) HasLinks() bool { func (o LanNics) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_post.go new file mode 100644 index 000000000..ce97f15f0 --- /dev/null +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_post.go @@ -0,0 +1,341 @@ +/* + * CLOUD API + * + * IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and flexibility, and can be used to perform a multitude of management tasks, including adding servers, volumes, configuring networks, and so on. + * + * API version: 6.0 + */ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package ionoscloud + +import ( + "encoding/json" +) + +// LanPost struct for LanPost +type LanPost struct { + Entities *LanEntities `json:"entities,omitempty"` + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties *LanPropertiesPost `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` +} + +// NewLanPost instantiates a new LanPost object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLanPost(properties LanPropertiesPost) *LanPost { + this := LanPost{} + + this.Properties = &properties + + return &this +} + +// NewLanPostWithDefaults instantiates a new LanPost object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLanPostWithDefaults() *LanPost { + this := LanPost{} + return &this +} + +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetEntities() *LanEntities { + if o == nil { + return nil + } + + return o.Entities + +} + +// GetEntitiesOk returns a tuple with the Entities field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetEntitiesOk() (*LanEntities, bool) { + if o == nil { + return nil, false + } + + return o.Entities, true +} + +// SetEntities sets field value +func (o *LanPost) SetEntities(v LanEntities) { + + o.Entities = &v + +} + +// HasEntities returns a boolean if a field has been set. +func (o *LanPost) HasEntities() bool { + if o != nil && o.Entities != nil { + return true + } + + return false +} + +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetHref() *string { + if o == nil { + return nil + } + + return o.Href + +} + +// GetHrefOk returns a tuple with the Href field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetHrefOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Href, true +} + +// SetHref sets field value +func (o *LanPost) SetHref(v string) { + + o.Href = &v + +} + +// HasHref returns a boolean if a field has been set. +func (o *LanPost) HasHref() bool { + if o != nil && o.Href != nil { + return true + } + + return false +} + +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetId() *string { + if o == nil { + return nil + } + + return o.Id + +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Id, true +} + +// SetId sets field value +func (o *LanPost) SetId(v string) { + + o.Id = &v + +} + +// HasId returns a boolean if a field has been set. +func (o *LanPost) HasId() bool { + if o != nil && o.Id != nil { + return true + } + + return false +} + +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetMetadata() *DatacenterElementMetadata { + if o == nil { + return nil + } + + return o.Metadata + +} + +// GetMetadataOk returns a tuple with the Metadata field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetMetadataOk() (*DatacenterElementMetadata, bool) { + if o == nil { + return nil, false + } + + return o.Metadata, true +} + +// SetMetadata sets field value +func (o *LanPost) SetMetadata(v DatacenterElementMetadata) { + + o.Metadata = &v + +} + +// HasMetadata returns a boolean if a field has been set. +func (o *LanPost) HasMetadata() bool { + if o != nil && o.Metadata != nil { + return true + } + + return false +} + +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetProperties() *LanPropertiesPost { + if o == nil { + return nil + } + + return o.Properties + +} + +// GetPropertiesOk returns a tuple with the Properties field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetPropertiesOk() (*LanPropertiesPost, bool) { + if o == nil { + return nil, false + } + + return o.Properties, true +} + +// SetProperties sets field value +func (o *LanPost) SetProperties(v LanPropertiesPost) { + + o.Properties = &v + +} + +// HasProperties returns a boolean if a field has been set. +func (o *LanPost) HasProperties() bool { + if o != nil && o.Properties != nil { + return true + } + + return false +} + +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetType() *Type { + if o == nil { + return nil + } + + return o.Type + +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetTypeOk() (*Type, bool) { + if o == nil { + return nil, false + } + + return o.Type, true +} + +// SetType sets field value +func (o *LanPost) SetType(v Type) { + + o.Type = &v + +} + +// HasType returns a boolean if a field has been set. +func (o *LanPost) HasType() bool { + if o != nil && o.Type != nil { + return true + } + + return false +} + +func (o LanPost) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.Entities != nil { + toSerialize["entities"] = o.Entities + } + + if o.Href != nil { + toSerialize["href"] = o.Href + } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + + if o.Metadata != nil { + toSerialize["metadata"] = o.Metadata + } + + if o.Properties != nil { + toSerialize["properties"] = o.Properties + } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + + return json.Marshal(toSerialize) +} + +type NullableLanPost struct { + value *LanPost + isSet bool +} + +func (v NullableLanPost) Get() *LanPost { + return v.value +} + +func (v *NullableLanPost) Set(val *LanPost) { + v.value = val + v.isSet = true +} + +func (v NullableLanPost) IsSet() bool { + return v.isSet +} + +func (v *NullableLanPost) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLanPost(val *LanPost) *NullableLanPost { + return &NullableLanPost{value: val, isSet: true} +} + +func (v NullableLanPost) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLanPost) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go index 763ced62b..141f0e1d1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go @@ -16,10 +16,13 @@ import ( // LanProperties struct for LanProperties type LanProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` // IP failover configurations for lan IpFailover *[]IPFailover `json:"ipFailover,omitempty"` + // For a GET request, this value is either 'null' or contains the LAN's /64 IPv6 CIDR block if this LAN is IPv6 enabled. For POST/PUT/PATCH requests, 'AUTO' will result in enabling this LAN for IPv6 and automatically assign a /64 IPv6 CIDR block to this LAN and /80 IPv6 CIDR blocks to the NICs and one /128 IPv6 address to each connected NIC. If you choose the IPv6 CIDR block for the LAN on your own, then you must provide a /64 block, which is inside the IPv6 CIDR block of the virtual datacenter and unique inside all LANs from this virtual datacenter. If you enable IPv6 on a LAN with NICs, those NICs will get a /80 IPv6 CIDR block and one IPv6 address assigned to each automatically, unless you specify them explicitly on the LAN and on the NICs. A virtual data center is limited to a maximum of 256 IPv6-enabled LANs. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpv6CidrBlockNil` + Ipv6CidrBlock *string `json:"ipv6CidrBlock,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // The unique identifier of the private Cross-Connect the LAN is connected to, if any. Pcc *string `json:"pcc,omitempty"` // This LAN faces the public Internet. @@ -44,76 +47,119 @@ func NewLanPropertiesWithDefaults() *LanProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LanProperties) GetName() *string { +// GetIpFailover returns the IpFailover field value +// If the value is explicit nil, nil is returned +func (o *LanProperties) GetIpFailover() *[]IPFailover { if o == nil { return nil } - return o.Name + return o.IpFailover } -// GetNameOk returns a tuple with the Name field value +// GetIpFailoverOk returns a tuple with the IpFailover field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanProperties) GetNameOk() (*string, bool) { +func (o *LanProperties) GetIpFailoverOk() (*[]IPFailover, bool) { if o == nil { return nil, false } - return o.Name, true + return o.IpFailover, true } -// SetName sets field value -func (o *LanProperties) SetName(v string) { +// SetIpFailover sets field value +func (o *LanProperties) SetIpFailover(v []IPFailover) { - o.Name = &v + o.IpFailover = &v } -// HasName returns a boolean if a field has been set. -func (o *LanProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasIpFailover returns a boolean if a field has been set. +func (o *LanProperties) HasIpFailover() bool { + if o != nil && o.IpFailover != nil { return true } return false } -// GetIpFailover returns the IpFailover field value -// If the value is explicit nil, the zero value for []IPFailover will be returned -func (o *LanProperties) GetIpFailover() *[]IPFailover { +// GetIpv6CidrBlock returns the Ipv6CidrBlock field value +// If the value is explicit nil, nil is returned +func (o *LanProperties) GetIpv6CidrBlock() *string { if o == nil { return nil } - return o.IpFailover + return o.Ipv6CidrBlock } -// GetIpFailoverOk returns a tuple with the IpFailover field value +// GetIpv6CidrBlockOk returns a tuple with the Ipv6CidrBlock field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanProperties) GetIpFailoverOk() (*[]IPFailover, bool) { +func (o *LanProperties) GetIpv6CidrBlockOk() (*string, bool) { if o == nil { return nil, false } - return o.IpFailover, true + return o.Ipv6CidrBlock, true } -// SetIpFailover sets field value -func (o *LanProperties) SetIpFailover(v []IPFailover) { +// SetIpv6CidrBlock sets field value +func (o *LanProperties) SetIpv6CidrBlock(v string) { - o.IpFailover = &v + o.Ipv6CidrBlock = &v } -// HasIpFailover returns a boolean if a field has been set. -func (o *LanProperties) HasIpFailover() bool { - if o != nil && o.IpFailover != nil { +// sets Ipv6CidrBlock to the explicit address that will be encoded as nil when marshaled +func (o *LanProperties) SetIpv6CidrBlockNil() { + o.Ipv6CidrBlock = &Nilstring +} + +// HasIpv6CidrBlock returns a boolean if a field has been set. +func (o *LanProperties) HasIpv6CidrBlock() bool { + if o != nil && o.Ipv6CidrBlock != nil { + return true + } + + return false +} + +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LanProperties) GetName() *string { + if o == nil { + return nil + } + + return o.Name + +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanProperties) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Name, true +} + +// SetName sets field value +func (o *LanProperties) SetName(v string) { + + o.Name = &v + +} + +// HasName returns a boolean if a field has been set. +func (o *LanProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -121,7 +167,7 @@ func (o *LanProperties) HasIpFailover() bool { } // GetPcc returns the Pcc field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LanProperties) GetPcc() *string { if o == nil { return nil @@ -159,7 +205,7 @@ func (o *LanProperties) HasPcc() bool { } // GetPublic returns the Public field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *LanProperties) GetPublic() *bool { if o == nil { return nil @@ -198,18 +244,27 @@ func (o *LanProperties) HasPublic() bool { func (o LanProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.IpFailover != nil { toSerialize["ipFailover"] = o.IpFailover } + + if o.Ipv6CidrBlock == &Nilstring { + toSerialize["ipv6CidrBlock"] = nil + } else if o.Ipv6CidrBlock != nil { + toSerialize["ipv6CidrBlock"] = o.Ipv6CidrBlock + } + if o.Name != nil { + toSerialize["name"] = o.Name + } + if o.Pcc != nil { toSerialize["pcc"] = o.Pcc } + if o.Public != nil { toSerialize["public"] = o.Public } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties_post.go new file mode 100644 index 000000000..a7da1b9f7 --- /dev/null +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties_post.go @@ -0,0 +1,305 @@ +/* + * CLOUD API + * + * IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and flexibility, and can be used to perform a multitude of management tasks, including adding servers, volumes, configuring networks, and so on. + * + * API version: 6.0 + */ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package ionoscloud + +import ( + "encoding/json" +) + +// LanPropertiesPost struct for LanPropertiesPost +type LanPropertiesPost struct { + // IP failover configurations for lan + IpFailover *[]IPFailover `json:"ipFailover,omitempty"` + // For a GET request, this value is either 'null' or contains the LAN's /64 IPv6 CIDR block if this LAN is IPv6-enabled. For POST/PUT/PATCH requests, 'AUTO' will result in enabling this LAN for IPv6 and automatically assign a /64 IPv6 CIDR block to this LAN. If you choose the IPv6 CIDR block on your own, then you must provide a /64 block, which is inside the IPv6 CIDR block of the virtual datacenter and unique inside all LANs from this virtual datacenter. If you enable IPv6 on a LAN with NICs, those NICs will get a /80 IPv6 CIDR block and one IPv6 address assigned to each automatically, unless you specify them explicitly on the NICs. A virtual data center is limited to a maximum of 256 IPv6-enabled LANs. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpv6CidrBlockNil` + Ipv6CidrBlock *string `json:"ipv6CidrBlock,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` + // The unique identifier of the private Cross-Connect the LAN is connected to, if any. + Pcc *string `json:"pcc,omitempty"` + // This LAN faces the public Internet. + Public *bool `json:"public,omitempty"` +} + +// NewLanPropertiesPost instantiates a new LanPropertiesPost object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLanPropertiesPost() *LanPropertiesPost { + this := LanPropertiesPost{} + + return &this +} + +// NewLanPropertiesPostWithDefaults instantiates a new LanPropertiesPost object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLanPropertiesPostWithDefaults() *LanPropertiesPost { + this := LanPropertiesPost{} + return &this +} + +// GetIpFailover returns the IpFailover field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetIpFailover() *[]IPFailover { + if o == nil { + return nil + } + + return o.IpFailover + +} + +// GetIpFailoverOk returns a tuple with the IpFailover field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetIpFailoverOk() (*[]IPFailover, bool) { + if o == nil { + return nil, false + } + + return o.IpFailover, true +} + +// SetIpFailover sets field value +func (o *LanPropertiesPost) SetIpFailover(v []IPFailover) { + + o.IpFailover = &v + +} + +// HasIpFailover returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasIpFailover() bool { + if o != nil && o.IpFailover != nil { + return true + } + + return false +} + +// GetIpv6CidrBlock returns the Ipv6CidrBlock field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetIpv6CidrBlock() *string { + if o == nil { + return nil + } + + return o.Ipv6CidrBlock + +} + +// GetIpv6CidrBlockOk returns a tuple with the Ipv6CidrBlock field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetIpv6CidrBlockOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Ipv6CidrBlock, true +} + +// SetIpv6CidrBlock sets field value +func (o *LanPropertiesPost) SetIpv6CidrBlock(v string) { + + o.Ipv6CidrBlock = &v + +} + +// sets Ipv6CidrBlock to the explicit address that will be encoded as nil when marshaled +func (o *LanPropertiesPost) SetIpv6CidrBlockNil() { + o.Ipv6CidrBlock = &Nilstring +} + +// HasIpv6CidrBlock returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasIpv6CidrBlock() bool { + if o != nil && o.Ipv6CidrBlock != nil { + return true + } + + return false +} + +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetName() *string { + if o == nil { + return nil + } + + return o.Name + +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Name, true +} + +// SetName sets field value +func (o *LanPropertiesPost) SetName(v string) { + + o.Name = &v + +} + +// HasName returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasName() bool { + if o != nil && o.Name != nil { + return true + } + + return false +} + +// GetPcc returns the Pcc field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetPcc() *string { + if o == nil { + return nil + } + + return o.Pcc + +} + +// GetPccOk returns a tuple with the Pcc field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetPccOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Pcc, true +} + +// SetPcc sets field value +func (o *LanPropertiesPost) SetPcc(v string) { + + o.Pcc = &v + +} + +// HasPcc returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasPcc() bool { + if o != nil && o.Pcc != nil { + return true + } + + return false +} + +// GetPublic returns the Public field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetPublic() *bool { + if o == nil { + return nil + } + + return o.Public + +} + +// GetPublicOk returns a tuple with the Public field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetPublicOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.Public, true +} + +// SetPublic sets field value +func (o *LanPropertiesPost) SetPublic(v bool) { + + o.Public = &v + +} + +// HasPublic returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasPublic() bool { + if o != nil && o.Public != nil { + return true + } + + return false +} + +func (o LanPropertiesPost) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.IpFailover != nil { + toSerialize["ipFailover"] = o.IpFailover + } + + if o.Ipv6CidrBlock == &Nilstring { + toSerialize["ipv6CidrBlock"] = nil + } else if o.Ipv6CidrBlock != nil { + toSerialize["ipv6CidrBlock"] = o.Ipv6CidrBlock + } + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.Pcc != nil { + toSerialize["pcc"] = o.Pcc + } + + if o.Public != nil { + toSerialize["public"] = o.Public + } + + return json.Marshal(toSerialize) +} + +type NullableLanPropertiesPost struct { + value *LanPropertiesPost + isSet bool +} + +func (v NullableLanPropertiesPost) Get() *LanPropertiesPost { + return v.value +} + +func (v *NullableLanPropertiesPost) Set(val *LanPropertiesPost) { + v.value = val + v.isSet = true +} + +func (v NullableLanPropertiesPost) IsSet() bool { + return v.isSet +} + +func (v *NullableLanPropertiesPost) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLanPropertiesPost(val *LanPropertiesPost) *NullableLanPropertiesPost { + return &NullableLanPropertiesPost{value: val, isSet: true} +} + +func (v NullableLanPropertiesPost) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLanPropertiesPost) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go index 361b3809f..b0ee52ca2 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go @@ -16,19 +16,19 @@ import ( // Lans struct for Lans type Lans struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Lan `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLans instantiates a new Lans object @@ -49,114 +49,114 @@ func NewLansWithDefaults() *Lans { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lans) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetIdOk() (*string, bool) { +func (o *Lans) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Lans) SetId(v string) { +// SetLinks sets field value +func (o *Lans) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Lans) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Lans) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Lans) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetTypeOk() (*Type, bool) { +func (o *Lans) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Lans) SetType(v Type) { +// SetHref sets field value +func (o *Lans) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Lans) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Lans) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lans) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetHrefOk() (*string, bool) { +func (o *Lans) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Lans) SetHref(v string) { +// SetId sets field value +func (o *Lans) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Lans) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Lans) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Lans) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Lan will be returned +// If the value is explicit nil, nil is returned func (o *Lans) GetItems() *[]Lan { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Lans) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Lans) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetOffsetOk() (*float32, bool) { +func (o *Lans) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Lans) SetOffset(v float32) { +// SetLimit sets field value +func (o *Lans) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Lans) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Lans) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Lans) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetLimitOk() (*float32, bool) { +func (o *Lans) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Lans) SetLimit(v float32) { +// SetOffset sets field value +func (o *Lans) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Lans) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Lans) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Lans) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetLinksOk() (*PaginationLinks, bool) { +func (o *Lans) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Lans) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Lans) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Lans) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Lans) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Lans) HasLinks() bool { func (o Lans) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go index 822d7f1c3..064e5eb99 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go @@ -16,15 +16,15 @@ import ( // Loadbalancer struct for Loadbalancer type Loadbalancer struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *LoadbalancerEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *LoadbalancerProperties `json:"properties"` - Entities *LoadbalancerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLoadbalancer instantiates a new Loadbalancer object @@ -47,114 +47,114 @@ func NewLoadbalancerWithDefaults() *Loadbalancer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancer) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetEntities() *LoadbalancerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetIdOk() (*string, bool) { +func (o *Loadbalancer) GetEntitiesOk() (*LoadbalancerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Loadbalancer) SetId(v string) { +// SetEntities sets field value +func (o *Loadbalancer) SetEntities(v LoadbalancerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Loadbalancer) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Loadbalancer) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Loadbalancer) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetTypeOk() (*Type, bool) { +func (o *Loadbalancer) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Loadbalancer) SetType(v Type) { +// SetHref sets field value +func (o *Loadbalancer) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Loadbalancer) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Loadbalancer) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancer) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetHrefOk() (*string, bool) { +func (o *Loadbalancer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Loadbalancer) SetHref(v string) { +// SetId sets field value +func (o *Loadbalancer) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Loadbalancer) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Loadbalancer) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Loadbalancer) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Loadbalancer) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Loadbalancer) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LoadbalancerProperties will be returned +// If the value is explicit nil, nil is returned func (o *Loadbalancer) GetProperties() *LoadbalancerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Loadbalancer) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for LoadbalancerEntities will be returned -func (o *Loadbalancer) GetEntities() *LoadbalancerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetEntitiesOk() (*LoadbalancerEntities, bool) { +func (o *Loadbalancer) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Loadbalancer) SetEntities(v LoadbalancerEntities) { +// SetType sets field value +func (o *Loadbalancer) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Loadbalancer) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Loadbalancer) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Loadbalancer) HasEntities() bool { func (o Loadbalancer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go index 129844dcb..8a4c5049c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go @@ -38,7 +38,7 @@ func NewLoadbalancerEntitiesWithDefaults() *LoadbalancerEntities { } // GetBalancednics returns the Balancednics field value -// If the value is explicit nil, the zero value for BalancedNics will be returned +// If the value is explicit nil, nil is returned func (o *LoadbalancerEntities) GetBalancednics() *BalancedNics { if o == nil { return nil @@ -80,6 +80,7 @@ func (o LoadbalancerEntities) MarshalJSON() ([]byte, error) { if o.Balancednics != nil { toSerialize["balancednics"] = o.Balancednics } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go index e6b9b02fb..9d1f3cee7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go @@ -16,12 +16,13 @@ import ( // LoadbalancerProperties struct for LoadbalancerProperties type LoadbalancerProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // IPv4 address of the loadbalancer. All attached NICs will inherit this IP. Leaving value null will assign IP automatically. - Ip *string `json:"ip,omitempty"` // Indicates if the loadbalancer will reserve an IP using DHCP. Dhcp *bool `json:"dhcp,omitempty"` + // IPv4 address of the loadbalancer. All attached NICs will inherit this IP. Leaving value null will assign IP automatically. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpNil` + Ip *string `json:"ip,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` } // NewLoadbalancerProperties instantiates a new LoadbalancerProperties object @@ -42,38 +43,38 @@ func NewLoadbalancerPropertiesWithDefaults() *LoadbalancerProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LoadbalancerProperties) GetName() *string { +// GetDhcp returns the Dhcp field value +// If the value is explicit nil, nil is returned +func (o *LoadbalancerProperties) GetDhcp() *bool { if o == nil { return nil } - return o.Name + return o.Dhcp } -// GetNameOk returns a tuple with the Name field value +// GetDhcpOk returns a tuple with the Dhcp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LoadbalancerProperties) GetNameOk() (*string, bool) { +func (o *LoadbalancerProperties) GetDhcpOk() (*bool, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Dhcp, true } -// SetName sets field value -func (o *LoadbalancerProperties) SetName(v string) { +// SetDhcp sets field value +func (o *LoadbalancerProperties) SetDhcp(v bool) { - o.Name = &v + o.Dhcp = &v } -// HasName returns a boolean if a field has been set. -func (o *LoadbalancerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasDhcp returns a boolean if a field has been set. +func (o *LoadbalancerProperties) HasDhcp() bool { + if o != nil && o.Dhcp != nil { return true } @@ -81,7 +82,7 @@ func (o *LoadbalancerProperties) HasName() bool { } // GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LoadbalancerProperties) GetIp() *string { if o == nil { return nil @@ -109,6 +110,11 @@ func (o *LoadbalancerProperties) SetIp(v string) { } +// sets Ip to the explicit address that will be encoded as nil when marshaled +func (o *LoadbalancerProperties) SetIpNil() { + o.Ip = &Nilstring +} + // HasIp returns a boolean if a field has been set. func (o *LoadbalancerProperties) HasIp() bool { if o != nil && o.Ip != nil { @@ -118,38 +124,38 @@ func (o *LoadbalancerProperties) HasIp() bool { return false } -// GetDhcp returns the Dhcp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *LoadbalancerProperties) GetDhcp() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LoadbalancerProperties) GetName() *string { if o == nil { return nil } - return o.Dhcp + return o.Name } -// GetDhcpOk returns a tuple with the Dhcp field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LoadbalancerProperties) GetDhcpOk() (*bool, bool) { +func (o *LoadbalancerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Dhcp, true + return o.Name, true } -// SetDhcp sets field value -func (o *LoadbalancerProperties) SetDhcp(v bool) { +// SetName sets field value +func (o *LoadbalancerProperties) SetName(v string) { - o.Dhcp = &v + o.Name = &v } -// HasDhcp returns a boolean if a field has been set. -func (o *LoadbalancerProperties) HasDhcp() bool { - if o != nil && o.Dhcp != nil { +// HasName returns a boolean if a field has been set. +func (o *LoadbalancerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -158,13 +164,19 @@ func (o *LoadbalancerProperties) HasDhcp() bool { func (o LoadbalancerProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - toSerialize["ip"] = o.Ip if o.Dhcp != nil { toSerialize["dhcp"] = o.Dhcp } + + if o.Ip == &Nilstring { + toSerialize["ip"] = nil + } else if o.Ip != nil { + toSerialize["ip"] = o.Ip + } + if o.Name != nil { + toSerialize["name"] = o.Name + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go index 166560f99..267eba36f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go @@ -16,19 +16,19 @@ import ( // Loadbalancers struct for Loadbalancers type Loadbalancers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Loadbalancer `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLoadbalancers instantiates a new Loadbalancers object @@ -49,114 +49,114 @@ func NewLoadbalancersWithDefaults() *Loadbalancers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetIdOk() (*string, bool) { +func (o *Loadbalancers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Loadbalancers) SetId(v string) { +// SetLinks sets field value +func (o *Loadbalancers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Loadbalancers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Loadbalancers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Loadbalancers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetTypeOk() (*Type, bool) { +func (o *Loadbalancers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Loadbalancers) SetType(v Type) { +// SetHref sets field value +func (o *Loadbalancers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Loadbalancers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Loadbalancers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetHrefOk() (*string, bool) { +func (o *Loadbalancers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Loadbalancers) SetHref(v string) { +// SetId sets field value +func (o *Loadbalancers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Loadbalancers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Loadbalancers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Loadbalancers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Loadbalancer will be returned +// If the value is explicit nil, nil is returned func (o *Loadbalancers) GetItems() *[]Loadbalancer { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Loadbalancers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Loadbalancers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetOffsetOk() (*float32, bool) { +func (o *Loadbalancers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Loadbalancers) SetOffset(v float32) { +// SetLimit sets field value +func (o *Loadbalancers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Loadbalancers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Loadbalancers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Loadbalancers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetLimitOk() (*float32, bool) { +func (o *Loadbalancers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Loadbalancers) SetLimit(v float32) { +// SetOffset sets field value +func (o *Loadbalancers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Loadbalancers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Loadbalancers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Loadbalancers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetLinksOk() (*PaginationLinks, bool) { +func (o *Loadbalancers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Loadbalancers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Loadbalancers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Loadbalancers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Loadbalancers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Loadbalancers) HasLinks() bool { func (o Loadbalancers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go index 59a250d45..379723ff1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go @@ -16,14 +16,14 @@ import ( // Location struct for Location type Location struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *LocationProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLocation instantiates a new Location object @@ -46,190 +46,190 @@ func NewLocationWithDefaults() *Location { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Location) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Location) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetIdOk() (*string, bool) { +func (o *Location) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Location) SetId(v string) { +// SetHref sets field value +func (o *Location) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Location) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Location) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Location) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Location) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetTypeOk() (*Type, bool) { +func (o *Location) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Location) SetType(v Type) { +// SetId sets field value +func (o *Location) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Location) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Location) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Location) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Location) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetHrefOk() (*string, bool) { +func (o *Location) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Location) SetHref(v string) { +// SetMetadata sets field value +func (o *Location) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Location) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Location) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Location) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Location) GetProperties() *LocationProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Location) GetPropertiesOk() (*LocationProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Location) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Location) SetProperties(v LocationProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Location) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Location) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LocationProperties will be returned -func (o *Location) GetProperties() *LocationProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Location) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetPropertiesOk() (*LocationProperties, bool) { +func (o *Location) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Location) SetProperties(v LocationProperties) { +// SetType sets field value +func (o *Location) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Location) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Location) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Location) HasProperties() bool { func (o Location) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go index 9e8e623b6..95da4abb3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go @@ -16,14 +16,14 @@ import ( // LocationProperties struct for LocationProperties type LocationProperties struct { - // The location name. - Name *string `json:"name,omitempty"` + // A list of available CPU types and related resources available in the location. + CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` // A list of available features in the location. Features *[]string `json:"features,omitempty"` // A list of image aliases available in the location. ImageAliases *[]string `json:"imageAliases,omitempty"` - // A list of available CPU types and related resources available in the location. - CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` + // The location name. + Name *string `json:"name,omitempty"` } // NewLocationProperties instantiates a new LocationProperties object @@ -44,38 +44,38 @@ func NewLocationPropertiesWithDefaults() *LocationProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LocationProperties) GetName() *string { +// GetCpuArchitecture returns the CpuArchitecture field value +// If the value is explicit nil, nil is returned +func (o *LocationProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { if o == nil { return nil } - return o.Name + return o.CpuArchitecture } -// GetNameOk returns a tuple with the Name field value +// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LocationProperties) GetNameOk() (*string, bool) { +func (o *LocationProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CpuArchitecture, true } -// SetName sets field value -func (o *LocationProperties) SetName(v string) { +// SetCpuArchitecture sets field value +func (o *LocationProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { - o.Name = &v + o.CpuArchitecture = &v } -// HasName returns a boolean if a field has been set. -func (o *LocationProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCpuArchitecture returns a boolean if a field has been set. +func (o *LocationProperties) HasCpuArchitecture() bool { + if o != nil && o.CpuArchitecture != nil { return true } @@ -83,7 +83,7 @@ func (o *LocationProperties) HasName() bool { } // GetFeatures returns the Features field value -// If the value is explicit nil, the zero value for []string will be returned +// If the value is explicit nil, nil is returned func (o *LocationProperties) GetFeatures() *[]string { if o == nil { return nil @@ -121,7 +121,7 @@ func (o *LocationProperties) HasFeatures() bool { } // GetImageAliases returns the ImageAliases field value -// If the value is explicit nil, the zero value for []string will be returned +// If the value is explicit nil, nil is returned func (o *LocationProperties) GetImageAliases() *[]string { if o == nil { return nil @@ -158,38 +158,38 @@ func (o *LocationProperties) HasImageAliases() bool { return false } -// GetCpuArchitecture returns the CpuArchitecture field value -// If the value is explicit nil, the zero value for []CpuArchitectureProperties will be returned -func (o *LocationProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LocationProperties) GetName() *string { if o == nil { return nil } - return o.CpuArchitecture + return o.Name } -// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LocationProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { +func (o *LocationProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuArchitecture, true + return o.Name, true } -// SetCpuArchitecture sets field value -func (o *LocationProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { +// SetName sets field value +func (o *LocationProperties) SetName(v string) { - o.CpuArchitecture = &v + o.Name = &v } -// HasCpuArchitecture returns a boolean if a field has been set. -func (o *LocationProperties) HasCpuArchitecture() bool { - if o != nil && o.CpuArchitecture != nil { +// HasName returns a boolean if a field has been set. +func (o *LocationProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -198,18 +198,22 @@ func (o *LocationProperties) HasCpuArchitecture() bool { func (o LocationProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.CpuArchitecture != nil { + toSerialize["cpuArchitecture"] = o.CpuArchitecture } + if o.Features != nil { toSerialize["features"] = o.Features } + if o.ImageAliases != nil { toSerialize["imageAliases"] = o.ImageAliases } - if o.CpuArchitecture != nil { - toSerialize["cpuArchitecture"] = o.CpuArchitecture + + if o.Name != nil { + toSerialize["name"] = o.Name } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go index ba9354ace..d3311051b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go @@ -16,14 +16,14 @@ import ( // Locations struct for Locations type Locations struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Location `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLocations instantiates a new Locations object @@ -44,152 +44,152 @@ func NewLocationsWithDefaults() *Locations { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Locations) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetIdOk() (*string, bool) { +func (o *Locations) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Locations) SetId(v string) { +// SetHref sets field value +func (o *Locations) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Locations) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Locations) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Locations) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetTypeOk() (*Type, bool) { +func (o *Locations) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Locations) SetType(v Type) { +// SetId sets field value +func (o *Locations) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Locations) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Locations) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Locations) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetItems() *[]Location { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetHrefOk() (*string, bool) { +func (o *Locations) GetItemsOk() (*[]Location, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Locations) SetHref(v string) { +// SetItems sets field value +func (o *Locations) SetItems(v []Location) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Locations) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Locations) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Location will be returned -func (o *Locations) GetItems() *[]Location { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetItemsOk() (*[]Location, bool) { +func (o *Locations) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Locations) SetItems(v []Location) { +// SetType sets field value +func (o *Locations) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Locations) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Locations) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Locations) HasItems() bool { func (o Locations) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go index 70f8e92a9..2feaa609f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go @@ -16,15 +16,15 @@ import ( // NatGateway struct for NatGateway type NatGateway struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *NatGatewayEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NatGatewayProperties `json:"properties"` - Entities *NatGatewayEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGateway instantiates a new NatGateway object @@ -47,114 +47,114 @@ func NewNatGatewayWithDefaults() *NatGateway { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateway) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetEntities() *NatGatewayEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetIdOk() (*string, bool) { +func (o *NatGateway) GetEntitiesOk() (*NatGatewayEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *NatGateway) SetId(v string) { +// SetEntities sets field value +func (o *NatGateway) SetEntities(v NatGatewayEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGateway) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *NatGateway) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGateway) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetTypeOk() (*Type, bool) { +func (o *NatGateway) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NatGateway) SetType(v Type) { +// SetHref sets field value +func (o *NatGateway) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGateway) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGateway) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateway) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetHrefOk() (*string, bool) { +func (o *NatGateway) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NatGateway) SetHref(v string) { +// SetId sets field value +func (o *NatGateway) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGateway) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGateway) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *NatGateway) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *NatGateway) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *NatGateway) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayProperties will be returned +// If the value is explicit nil, nil is returned func (o *NatGateway) GetProperties() *NatGatewayProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *NatGateway) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for NatGatewayEntities will be returned -func (o *NatGateway) GetEntities() *NatGatewayEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetEntitiesOk() (*NatGatewayEntities, bool) { +func (o *NatGateway) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *NatGateway) SetEntities(v NatGatewayEntities) { +// SetType sets field value +func (o *NatGateway) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *NatGateway) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGateway) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *NatGateway) HasEntities() bool { func (o NatGateway) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go index d51cb9543..94fae49c4 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go @@ -16,8 +16,8 @@ import ( // NatGatewayEntities struct for NatGatewayEntities type NatGatewayEntities struct { - Rules *NatGatewayRules `json:"rules,omitempty"` Flowlogs *FlowLogs `json:"flowlogs,omitempty"` + Rules *NatGatewayRules `json:"rules,omitempty"` } // NewNatGatewayEntities instantiates a new NatGatewayEntities object @@ -38,76 +38,76 @@ func NewNatGatewayEntitiesWithDefaults() *NatGatewayEntities { return &this } -// GetRules returns the Rules field value -// If the value is explicit nil, the zero value for NatGatewayRules will be returned -func (o *NatGatewayEntities) GetRules() *NatGatewayRules { +// GetFlowlogs returns the Flowlogs field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayEntities) GetFlowlogs() *FlowLogs { if o == nil { return nil } - return o.Rules + return o.Flowlogs } -// GetRulesOk returns a tuple with the Rules field value +// GetFlowlogsOk returns a tuple with the Flowlogs field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayEntities) GetRulesOk() (*NatGatewayRules, bool) { +func (o *NatGatewayEntities) GetFlowlogsOk() (*FlowLogs, bool) { if o == nil { return nil, false } - return o.Rules, true + return o.Flowlogs, true } -// SetRules sets field value -func (o *NatGatewayEntities) SetRules(v NatGatewayRules) { +// SetFlowlogs sets field value +func (o *NatGatewayEntities) SetFlowlogs(v FlowLogs) { - o.Rules = &v + o.Flowlogs = &v } -// HasRules returns a boolean if a field has been set. -func (o *NatGatewayEntities) HasRules() bool { - if o != nil && o.Rules != nil { +// HasFlowlogs returns a boolean if a field has been set. +func (o *NatGatewayEntities) HasFlowlogs() bool { + if o != nil && o.Flowlogs != nil { return true } return false } -// GetFlowlogs returns the Flowlogs field value -// If the value is explicit nil, the zero value for FlowLogs will be returned -func (o *NatGatewayEntities) GetFlowlogs() *FlowLogs { +// GetRules returns the Rules field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayEntities) GetRules() *NatGatewayRules { if o == nil { return nil } - return o.Flowlogs + return o.Rules } -// GetFlowlogsOk returns a tuple with the Flowlogs field value +// GetRulesOk returns a tuple with the Rules field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayEntities) GetFlowlogsOk() (*FlowLogs, bool) { +func (o *NatGatewayEntities) GetRulesOk() (*NatGatewayRules, bool) { if o == nil { return nil, false } - return o.Flowlogs, true + return o.Rules, true } -// SetFlowlogs sets field value -func (o *NatGatewayEntities) SetFlowlogs(v FlowLogs) { +// SetRules sets field value +func (o *NatGatewayEntities) SetRules(v NatGatewayRules) { - o.Flowlogs = &v + o.Rules = &v } -// HasFlowlogs returns a boolean if a field has been set. -func (o *NatGatewayEntities) HasFlowlogs() bool { - if o != nil && o.Flowlogs != nil { +// HasRules returns a boolean if a field has been set. +func (o *NatGatewayEntities) HasRules() bool { + if o != nil && o.Rules != nil { return true } @@ -116,12 +116,14 @@ func (o *NatGatewayEntities) HasFlowlogs() bool { func (o NatGatewayEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Rules != nil { - toSerialize["rules"] = o.Rules - } if o.Flowlogs != nil { toSerialize["flowlogs"] = o.Flowlogs } + + if o.Rules != nil { + toSerialize["rules"] = o.Rules + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go index 007a57d69..068b141be 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go @@ -16,10 +16,10 @@ import ( // NatGatewayLanProperties struct for NatGatewayLanProperties type NatGatewayLanProperties struct { - // Id for the LAN connected to the NAT Gateway - Id *int32 `json:"id"` // Collection of gateway IP addresses of the NAT Gateway. Will be auto-generated if not provided. Should ideally be an IP belonging to the same subnet as the LAN GatewayIps *[]string `json:"gatewayIps,omitempty"` + // Id for the LAN connected to the NAT Gateway + Id *int32 `json:"id"` } // NewNatGatewayLanProperties instantiates a new NatGatewayLanProperties object @@ -42,76 +42,76 @@ func NewNatGatewayLanPropertiesWithDefaults() *NatGatewayLanProperties { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NatGatewayLanProperties) GetId() *int32 { +// GetGatewayIps returns the GatewayIps field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayLanProperties) GetGatewayIps() *[]string { if o == nil { return nil } - return o.Id + return o.GatewayIps } -// GetIdOk returns a tuple with the Id field value +// GetGatewayIpsOk returns a tuple with the GatewayIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayLanProperties) GetIdOk() (*int32, bool) { +func (o *NatGatewayLanProperties) GetGatewayIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.GatewayIps, true } -// SetId sets field value -func (o *NatGatewayLanProperties) SetId(v int32) { +// SetGatewayIps sets field value +func (o *NatGatewayLanProperties) SetGatewayIps(v []string) { - o.Id = &v + o.GatewayIps = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayLanProperties) HasId() bool { - if o != nil && o.Id != nil { +// HasGatewayIps returns a boolean if a field has been set. +func (o *NatGatewayLanProperties) HasGatewayIps() bool { + if o != nil && o.GatewayIps != nil { return true } return false } -// GetGatewayIps returns the GatewayIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NatGatewayLanProperties) GetGatewayIps() *[]string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayLanProperties) GetId() *int32 { if o == nil { return nil } - return o.GatewayIps + return o.Id } -// GetGatewayIpsOk returns a tuple with the GatewayIps field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayLanProperties) GetGatewayIpsOk() (*[]string, bool) { +func (o *NatGatewayLanProperties) GetIdOk() (*int32, bool) { if o == nil { return nil, false } - return o.GatewayIps, true + return o.Id, true } -// SetGatewayIps sets field value -func (o *NatGatewayLanProperties) SetGatewayIps(v []string) { +// SetId sets field value +func (o *NatGatewayLanProperties) SetId(v int32) { - o.GatewayIps = &v + o.Id = &v } -// HasGatewayIps returns a boolean if a field has been set. -func (o *NatGatewayLanProperties) HasGatewayIps() bool { - if o != nil && o.GatewayIps != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayLanProperties) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -120,12 +120,14 @@ func (o *NatGatewayLanProperties) HasGatewayIps() bool { func (o NatGatewayLanProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } if o.GatewayIps != nil { toSerialize["gatewayIps"] = o.GatewayIps } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go index 6eea997ef..ad784ad9f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go @@ -16,12 +16,12 @@ import ( // NatGatewayProperties struct for NatGatewayProperties type NatGatewayProperties struct { + // Collection of LANs connected to the NAT Gateway. IPs must contain a valid subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. + Lans *[]NatGatewayLanProperties `json:"lans,omitempty"` // Name of the NAT Gateway. Name *string `json:"name"` // Collection of public IP addresses of the NAT Gateway. Should be customer reserved IP addresses in that location. PublicIps *[]string `json:"publicIps"` - // Collection of LANs connected to the NAT Gateway. IPs must contain a valid subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. - Lans *[]NatGatewayLanProperties `json:"lans,omitempty"` } // NewNatGatewayProperties instantiates a new NatGatewayProperties object @@ -45,114 +45,114 @@ func NewNatGatewayPropertiesWithDefaults() *NatGatewayProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayProperties) GetName() *string { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayProperties) GetLans() *[]NatGatewayLanProperties { if o == nil { return nil } - return o.Name + return o.Lans } -// GetNameOk returns a tuple with the Name field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayProperties) GetNameOk() (*string, bool) { +func (o *NatGatewayProperties) GetLansOk() (*[]NatGatewayLanProperties, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Lans, true } -// SetName sets field value -func (o *NatGatewayProperties) SetName(v string) { +// SetLans sets field value +func (o *NatGatewayProperties) SetLans(v []NatGatewayLanProperties) { - o.Name = &v + o.Lans = &v } -// HasName returns a boolean if a field has been set. -func (o *NatGatewayProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasLans returns a boolean if a field has been set. +func (o *NatGatewayProperties) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NatGatewayProperties) GetPublicIps() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayProperties) GetName() *string { if o == nil { return nil } - return o.PublicIps + return o.Name } -// GetPublicIpsOk returns a tuple with the PublicIps field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayProperties) GetPublicIpsOk() (*[]string, bool) { +func (o *NatGatewayProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.PublicIps, true + return o.Name, true } -// SetPublicIps sets field value -func (o *NatGatewayProperties) SetPublicIps(v []string) { +// SetName sets field value +func (o *NatGatewayProperties) SetName(v string) { - o.PublicIps = &v + o.Name = &v } -// HasPublicIps returns a boolean if a field has been set. -func (o *NatGatewayProperties) HasPublicIps() bool { - if o != nil && o.PublicIps != nil { +// HasName returns a boolean if a field has been set. +func (o *NatGatewayProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []NatGatewayLanProperties will be returned -func (o *NatGatewayProperties) GetLans() *[]NatGatewayLanProperties { +// GetPublicIps returns the PublicIps field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayProperties) GetPublicIps() *[]string { if o == nil { return nil } - return o.Lans + return o.PublicIps } -// GetLansOk returns a tuple with the Lans field value +// GetPublicIpsOk returns a tuple with the PublicIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayProperties) GetLansOk() (*[]NatGatewayLanProperties, bool) { +func (o *NatGatewayProperties) GetPublicIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.PublicIps, true } -// SetLans sets field value -func (o *NatGatewayProperties) SetLans(v []NatGatewayLanProperties) { +// SetPublicIps sets field value +func (o *NatGatewayProperties) SetPublicIps(v []string) { - o.Lans = &v + o.PublicIps = &v } -// HasLans returns a boolean if a field has been set. -func (o *NatGatewayProperties) HasLans() bool { - if o != nil && o.Lans != nil { +// HasPublicIps returns a boolean if a field has been set. +func (o *NatGatewayProperties) HasPublicIps() bool { + if o != nil && o.PublicIps != nil { return true } @@ -161,15 +161,18 @@ func (o *NatGatewayProperties) HasLans() bool { func (o NatGatewayProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Lans != nil { + toSerialize["lans"] = o.Lans + } + if o.Name != nil { toSerialize["name"] = o.Name } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } - if o.Lans != nil { - toSerialize["lans"] = o.Lans - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go index cf9a8a048..5bd37720e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go @@ -16,13 +16,13 @@ import ( // NatGatewayPut struct for NatGatewayPut type NatGatewayPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NatGatewayProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NatGatewayProperties `json:"properties"` } // NewNatGatewayPut instantiates a new NatGatewayPut object @@ -45,152 +45,152 @@ func NewNatGatewayPutWithDefaults() *NatGatewayPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetIdOk() (*string, bool) { +func (o *NatGatewayPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayPut) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetTypeOk() (*Type, bool) { +func (o *NatGatewayPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayPut) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetProperties() *NatGatewayProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetHrefOk() (*string, bool) { +func (o *NatGatewayPut) GetPropertiesOk() (*NatGatewayProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NatGatewayPut) SetHref(v string) { +// SetProperties sets field value +func (o *NatGatewayPut) SetProperties(v NatGatewayProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NatGatewayPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayProperties will be returned -func (o *NatGatewayPut) GetProperties() *NatGatewayProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetPropertiesOk() (*NatGatewayProperties, bool) { +func (o *NatGatewayPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NatGatewayPut) SetProperties(v NatGatewayProperties) { +// SetType sets field value +func (o *NatGatewayPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NatGatewayPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NatGatewayPut) HasProperties() bool { func (o NatGatewayPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go index 42d20aac8..4693555ca 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go @@ -16,14 +16,14 @@ import ( // NatGatewayRule struct for NatGatewayRule type NatGatewayRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NatGatewayRuleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGatewayRule instantiates a new NatGatewayRule object @@ -46,190 +46,190 @@ func NewNatGatewayRuleWithDefaults() *NatGatewayRule { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetIdOk() (*string, bool) { +func (o *NatGatewayRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayRule) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetTypeOk() (*Type, bool) { +func (o *NatGatewayRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayRule) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetHrefOk() (*string, bool) { +func (o *NatGatewayRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *NatGatewayRule) SetHref(v string) { +// SetMetadata sets field value +func (o *NatGatewayRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *NatGatewayRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *NatGatewayRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetProperties() *NatGatewayRuleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *NatGatewayRule) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *NatGatewayRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *NatGatewayRule) SetProperties(v NatGatewayRuleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *NatGatewayRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NatGatewayRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayRuleProperties will be returned -func (o *NatGatewayRule) GetProperties() *NatGatewayRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { +func (o *NatGatewayRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NatGatewayRule) SetProperties(v NatGatewayRuleProperties) { +// SetType sets field value +func (o *NatGatewayRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NatGatewayRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *NatGatewayRule) HasProperties() bool { func (o NatGatewayRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go index 8b3da441e..32330acee 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go @@ -18,29 +18,29 @@ import ( type NatGatewayRuleProperties struct { // The name of the NAT Gateway rule. Name *string `json:"name"` - // Type of the NAT Gateway rule. - Type *NatGatewayRuleType `json:"type,omitempty"` // Protocol of the NAT Gateway rule. Defaults to ALL. If protocol is 'ICMP' then targetPortRange start and end cannot be set. Protocol *NatGatewayRuleProtocol `json:"protocol,omitempty"` - // Source subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets source IP address. - SourceSubnet *string `json:"sourceSubnet"` // Public IP address of the NAT Gateway rule. Specifies the address used for masking outgoing packets source address field. Should be one of the customer reserved IP address already configured on the NAT Gateway resource PublicIp *string `json:"publicIp"` - // Target or destination subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets destination IP address. If none is provided, rule will match any address. - TargetSubnet *string `json:"targetSubnet,omitempty"` + // Source subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets source IP address. + SourceSubnet *string `json:"sourceSubnet"` TargetPortRange *TargetPortRange `json:"targetPortRange,omitempty"` + // Target or destination subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets destination IP address. If none is provided, rule will match any address. + TargetSubnet *string `json:"targetSubnet,omitempty"` + // Type of the NAT Gateway rule. + Type *NatGatewayRuleType `json:"type,omitempty"` } // NewNatGatewayRuleProperties instantiates a new NatGatewayRuleProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewNatGatewayRuleProperties(name string, sourceSubnet string, publicIp string) *NatGatewayRuleProperties { +func NewNatGatewayRuleProperties(name string, publicIp string, sourceSubnet string) *NatGatewayRuleProperties { this := NatGatewayRuleProperties{} this.Name = &name - this.SourceSubnet = &sourceSubnet this.PublicIp = &publicIp + this.SourceSubnet = &sourceSubnet return &this } @@ -54,7 +54,7 @@ func NewNatGatewayRulePropertiesWithDefaults() *NatGatewayRuleProperties { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NatGatewayRuleProperties) GetName() *string { if o == nil { return nil @@ -91,76 +91,76 @@ func (o *NatGatewayRuleProperties) HasName() bool { return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for NatGatewayRuleType will be returned -func (o *NatGatewayRuleProperties) GetType() *NatGatewayRuleType { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetProtocol() *NatGatewayRuleProtocol { if o == nil { return nil } - return o.Type + return o.Protocol } -// GetTypeOk returns a tuple with the Type field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetTypeOk() (*NatGatewayRuleType, bool) { +func (o *NatGatewayRuleProperties) GetProtocolOk() (*NatGatewayRuleProtocol, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Protocol, true } -// SetType sets field value -func (o *NatGatewayRuleProperties) SetType(v NatGatewayRuleType) { +// SetProtocol sets field value +func (o *NatGatewayRuleProperties) SetProtocol(v NatGatewayRuleProtocol) { - o.Type = &v + o.Protocol = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasType() bool { - if o != nil && o.Type != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for NatGatewayRuleProtocol will be returned -func (o *NatGatewayRuleProperties) GetProtocol() *NatGatewayRuleProtocol { +// GetPublicIp returns the PublicIp field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetPublicIp() *string { if o == nil { return nil } - return o.Protocol + return o.PublicIp } -// GetProtocolOk returns a tuple with the Protocol field value +// GetPublicIpOk returns a tuple with the PublicIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetProtocolOk() (*NatGatewayRuleProtocol, bool) { +func (o *NatGatewayRuleProperties) GetPublicIpOk() (*string, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.PublicIp, true } -// SetProtocol sets field value -func (o *NatGatewayRuleProperties) SetProtocol(v NatGatewayRuleProtocol) { +// SetPublicIp sets field value +func (o *NatGatewayRuleProperties) SetPublicIp(v string) { - o.Protocol = &v + o.PublicIp = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasPublicIp returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasPublicIp() bool { + if o != nil && o.PublicIp != nil { return true } @@ -168,7 +168,7 @@ func (o *NatGatewayRuleProperties) HasProtocol() bool { } // GetSourceSubnet returns the SourceSubnet field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NatGatewayRuleProperties) GetSourceSubnet() *string { if o == nil { return nil @@ -205,38 +205,38 @@ func (o *NatGatewayRuleProperties) HasSourceSubnet() bool { return false } -// GetPublicIp returns the PublicIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRuleProperties) GetPublicIp() *string { +// GetTargetPortRange returns the TargetPortRange field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetTargetPortRange() *TargetPortRange { if o == nil { return nil } - return o.PublicIp + return o.TargetPortRange } -// GetPublicIpOk returns a tuple with the PublicIp field value +// GetTargetPortRangeOk returns a tuple with the TargetPortRange field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetPublicIpOk() (*string, bool) { +func (o *NatGatewayRuleProperties) GetTargetPortRangeOk() (*TargetPortRange, bool) { if o == nil { return nil, false } - return o.PublicIp, true + return o.TargetPortRange, true } -// SetPublicIp sets field value -func (o *NatGatewayRuleProperties) SetPublicIp(v string) { +// SetTargetPortRange sets field value +func (o *NatGatewayRuleProperties) SetTargetPortRange(v TargetPortRange) { - o.PublicIp = &v + o.TargetPortRange = &v } -// HasPublicIp returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasPublicIp() bool { - if o != nil && o.PublicIp != nil { +// HasTargetPortRange returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasTargetPortRange() bool { + if o != nil && o.TargetPortRange != nil { return true } @@ -244,7 +244,7 @@ func (o *NatGatewayRuleProperties) HasPublicIp() bool { } // GetTargetSubnet returns the TargetSubnet field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NatGatewayRuleProperties) GetTargetSubnet() *string { if o == nil { return nil @@ -281,38 +281,38 @@ func (o *NatGatewayRuleProperties) HasTargetSubnet() bool { return false } -// GetTargetPortRange returns the TargetPortRange field value -// If the value is explicit nil, the zero value for TargetPortRange will be returned -func (o *NatGatewayRuleProperties) GetTargetPortRange() *TargetPortRange { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetType() *NatGatewayRuleType { if o == nil { return nil } - return o.TargetPortRange + return o.Type } -// GetTargetPortRangeOk returns a tuple with the TargetPortRange field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetTargetPortRangeOk() (*TargetPortRange, bool) { +func (o *NatGatewayRuleProperties) GetTypeOk() (*NatGatewayRuleType, bool) { if o == nil { return nil, false } - return o.TargetPortRange, true + return o.Type, true } -// SetTargetPortRange sets field value -func (o *NatGatewayRuleProperties) SetTargetPortRange(v TargetPortRange) { +// SetType sets field value +func (o *NatGatewayRuleProperties) SetType(v NatGatewayRuleType) { - o.TargetPortRange = &v + o.Type = &v } -// HasTargetPortRange returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasTargetPortRange() bool { - if o != nil && o.TargetPortRange != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -324,24 +324,31 @@ func (o NatGatewayRuleProperties) MarshalJSON() ([]byte, error) { if o.Name != nil { toSerialize["name"] = o.Name } - if o.Type != nil { - toSerialize["type"] = o.Type - } + if o.Protocol != nil { toSerialize["protocol"] = o.Protocol } + + if o.PublicIp != nil { + toSerialize["publicIp"] = o.PublicIp + } + if o.SourceSubnet != nil { toSerialize["sourceSubnet"] = o.SourceSubnet } - if o.PublicIp != nil { - toSerialize["publicIp"] = o.PublicIp + + if o.TargetPortRange != nil { + toSerialize["targetPortRange"] = o.TargetPortRange } + if o.TargetSubnet != nil { toSerialize["targetSubnet"] = o.TargetSubnet } - if o.TargetPortRange != nil { - toSerialize["targetPortRange"] = o.TargetPortRange + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go index 2f709351b..e0f92b409 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go @@ -16,13 +16,13 @@ import ( // NatGatewayRulePut struct for NatGatewayRulePut type NatGatewayRulePut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NatGatewayRuleProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NatGatewayRuleProperties `json:"properties"` } // NewNatGatewayRulePut instantiates a new NatGatewayRulePut object @@ -45,152 +45,152 @@ func NewNatGatewayRulePutWithDefaults() *NatGatewayRulePut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRulePut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetIdOk() (*string, bool) { +func (o *NatGatewayRulePut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayRulePut) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayRulePut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayRulePut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetTypeOk() (*Type, bool) { +func (o *NatGatewayRulePut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayRulePut) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayRulePut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRulePut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetProperties() *NatGatewayRuleProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetHrefOk() (*string, bool) { +func (o *NatGatewayRulePut) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NatGatewayRulePut) SetHref(v string) { +// SetProperties sets field value +func (o *NatGatewayRulePut) SetProperties(v NatGatewayRuleProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayRuleProperties will be returned -func (o *NatGatewayRulePut) GetProperties() *NatGatewayRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { +func (o *NatGatewayRulePut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NatGatewayRulePut) SetProperties(v NatGatewayRuleProperties) { +// SetType sets field value +func (o *NatGatewayRulePut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NatGatewayRulePut) HasProperties() bool { func (o NatGatewayRulePut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go index 780bef1f9..9d3d41353 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go @@ -16,14 +16,14 @@ import ( // NatGatewayRules struct for NatGatewayRules type NatGatewayRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NatGatewayRule `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGatewayRules instantiates a new NatGatewayRules object @@ -44,152 +44,152 @@ func NewNatGatewayRulesWithDefaults() *NatGatewayRules { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRules) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetIdOk() (*string, bool) { +func (o *NatGatewayRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayRules) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayRules) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayRules) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayRules) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetTypeOk() (*Type, bool) { +func (o *NatGatewayRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayRules) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayRules) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRules) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayRules) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRules) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetItems() *[]NatGatewayRule { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetHrefOk() (*string, bool) { +func (o *NatGatewayRules) GetItemsOk() (*[]NatGatewayRule, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *NatGatewayRules) SetHref(v string) { +// SetItems sets field value +func (o *NatGatewayRules) SetItems(v []NatGatewayRule) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *NatGatewayRules) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NatGatewayRule will be returned -func (o *NatGatewayRules) GetItems() *[]NatGatewayRule { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetItemsOk() (*[]NatGatewayRule, bool) { +func (o *NatGatewayRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *NatGatewayRules) SetItems(v []NatGatewayRule) { +// SetType sets field value +func (o *NatGatewayRules) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *NatGatewayRules) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *NatGatewayRules) HasItems() bool { func (o NatGatewayRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go index ea80671fe..2139508cc 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go @@ -16,19 +16,19 @@ import ( // NatGateways struct for NatGateways type NatGateways struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NatGateway `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGateways instantiates a new NatGateways object @@ -49,114 +49,114 @@ func NewNatGatewaysWithDefaults() *NatGateways { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateways) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetIdOk() (*string, bool) { +func (o *NatGateways) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *NatGateways) SetId(v string) { +// SetLinks sets field value +func (o *NatGateways) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGateways) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *NatGateways) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGateways) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetTypeOk() (*Type, bool) { +func (o *NatGateways) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NatGateways) SetType(v Type) { +// SetHref sets field value +func (o *NatGateways) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGateways) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGateways) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateways) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetHrefOk() (*string, bool) { +func (o *NatGateways) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NatGateways) SetHref(v string) { +// SetId sets field value +func (o *NatGateways) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGateways) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGateways) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *NatGateways) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NatGateway will be returned +// If the value is explicit nil, nil is returned func (o *NatGateways) GetItems() *[]NatGateway { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *NatGateways) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NatGateways) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetOffsetOk() (*float32, bool) { +func (o *NatGateways) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *NatGateways) SetOffset(v float32) { +// SetLimit sets field value +func (o *NatGateways) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *NatGateways) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *NatGateways) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NatGateways) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetLimitOk() (*float32, bool) { +func (o *NatGateways) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *NatGateways) SetLimit(v float32) { +// SetOffset sets field value +func (o *NatGateways) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *NatGateways) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *NatGateways) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *NatGateways) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetLinksOk() (*PaginationLinks, bool) { +func (o *NatGateways) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *NatGateways) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *NatGateways) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *NatGateways) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGateways) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *NatGateways) HasLinks() bool { func (o NatGateways) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go index 265e075fa..efaed067d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go @@ -16,15 +16,15 @@ import ( // NetworkLoadBalancer struct for NetworkLoadBalancer type NetworkLoadBalancer struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *NetworkLoadBalancerEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NetworkLoadBalancerProperties `json:"properties"` - Entities *NetworkLoadBalancerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancer instantiates a new NetworkLoadBalancer object @@ -47,114 +47,114 @@ func NewNetworkLoadBalancerWithDefaults() *NetworkLoadBalancer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancer) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetEntities() *NetworkLoadBalancerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancer) GetEntitiesOk() (*NetworkLoadBalancerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *NetworkLoadBalancer) SetId(v string) { +// SetEntities sets field value +func (o *NetworkLoadBalancer) SetEntities(v NetworkLoadBalancerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancer) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancer) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NetworkLoadBalancer) SetType(v Type) { +// SetHref sets field value +func (o *NetworkLoadBalancer) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancer) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NetworkLoadBalancer) SetHref(v string) { +// SetId sets field value +func (o *NetworkLoadBalancer) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *NetworkLoadBalancer) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancer) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *NetworkLoadBalancer) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerProperties will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancer) GetProperties() *NetworkLoadBalancerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *NetworkLoadBalancer) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerEntities will be returned -func (o *NetworkLoadBalancer) GetEntities() *NetworkLoadBalancerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetEntitiesOk() (*NetworkLoadBalancerEntities, bool) { +func (o *NetworkLoadBalancer) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *NetworkLoadBalancer) SetEntities(v NetworkLoadBalancerEntities) { +// SetType sets field value +func (o *NetworkLoadBalancer) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *NetworkLoadBalancer) HasEntities() bool { func (o NetworkLoadBalancer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go index 85dd3bbd6..cdd74071c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go @@ -39,7 +39,7 @@ func NewNetworkLoadBalancerEntitiesWithDefaults() *NetworkLoadBalancerEntities { } // GetFlowlogs returns the Flowlogs field value -// If the value is explicit nil, the zero value for FlowLogs will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerEntities) GetFlowlogs() *FlowLogs { if o == nil { return nil @@ -77,7 +77,7 @@ func (o *NetworkLoadBalancerEntities) HasFlowlogs() bool { } // GetForwardingrules returns the Forwardingrules field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRules will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerEntities) GetForwardingrules() *NetworkLoadBalancerForwardingRules { if o == nil { return nil @@ -119,9 +119,11 @@ func (o NetworkLoadBalancerEntities) MarshalJSON() ([]byte, error) { if o.Flowlogs != nil { toSerialize["flowlogs"] = o.Flowlogs } + if o.Forwardingrules != nil { toSerialize["forwardingrules"] = o.Forwardingrules } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go index 8f054c885..d5018315f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go @@ -16,14 +16,14 @@ import ( // NetworkLoadBalancerForwardingRule struct for NetworkLoadBalancerForwardingRule type NetworkLoadBalancerForwardingRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NetworkLoadBalancerForwardingRuleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancerForwardingRule instantiates a new NetworkLoadBalancerForwardingRule object @@ -46,190 +46,190 @@ func NewNetworkLoadBalancerForwardingRuleWithDefaults() *NetworkLoadBalancerForw return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NetworkLoadBalancerForwardingRule) SetId(v string) { +// SetHref sets field value +func (o *NetworkLoadBalancerForwardingRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerForwardingRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NetworkLoadBalancerForwardingRule) SetType(v Type) { +// SetId sets field value +func (o *NetworkLoadBalancerForwardingRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *NetworkLoadBalancerForwardingRule) SetHref(v string) { +// SetMetadata sets field value +func (o *NetworkLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *NetworkLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *NetworkLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *NetworkLoadBalancerForwardingRule) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleProperties will be returned -func (o *NetworkLoadBalancerForwardingRule) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NetworkLoadBalancerForwardingRule) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *NetworkLoadBalancerForwardingRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *NetworkLoadBalancerForwardingRule) HasProperties() bool { func (o NetworkLoadBalancerForwardingRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go index 3fa9df4f4..cd16a13ef 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go @@ -20,10 +20,10 @@ type NetworkLoadBalancerForwardingRuleHealthCheck struct { ClientTimeout *int32 `json:"clientTimeout,omitempty"` // The maximum time in milliseconds to wait for a connection attempt to a target to succeed; default is 5000 (five seconds). ConnectTimeout *int32 `json:"connectTimeout,omitempty"` - // The maximum time in milliseconds that a target can remain inactive; default is 50,000 (50 seconds). - TargetTimeout *int32 `json:"targetTimeout,omitempty"` // The maximum number of attempts to reconnect to a target after a connection failure. Valid range is 0 to 65535 and default is three reconnection attempts. Retries *int32 `json:"retries,omitempty"` + // The maximum time in milliseconds that a target can remain inactive; default is 50,000 (50 seconds). + TargetTimeout *int32 `json:"targetTimeout,omitempty"` } // NewNetworkLoadBalancerForwardingRuleHealthCheck instantiates a new NetworkLoadBalancerForwardingRuleHealthCheck object @@ -45,7 +45,7 @@ func NewNetworkLoadBalancerForwardingRuleHealthCheckWithDefaults() *NetworkLoadB } // GetClientTimeout returns the ClientTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetClientTimeout() *int32 { if o == nil { return nil @@ -83,7 +83,7 @@ func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasClientTimeout() bool { } // GetConnectTimeout returns the ConnectTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetConnectTimeout() *int32 { if o == nil { return nil @@ -120,76 +120,76 @@ func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasConnectTimeout() bool return false } -// GetTargetTimeout returns the TargetTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeout() *int32 { +// GetRetries returns the Retries field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetries() *int32 { if o == nil { return nil } - return o.TargetTimeout + return o.Retries } -// GetTargetTimeoutOk returns a tuple with the TargetTimeout field value +// GetRetriesOk returns a tuple with the Retries field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeoutOk() (*int32, bool) { +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetriesOk() (*int32, bool) { if o == nil { return nil, false } - return o.TargetTimeout, true + return o.Retries, true } -// SetTargetTimeout sets field value -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetTargetTimeout(v int32) { +// SetRetries sets field value +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetRetries(v int32) { - o.TargetTimeout = &v + o.Retries = &v } -// HasTargetTimeout returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasTargetTimeout() bool { - if o != nil && o.TargetTimeout != nil { +// HasRetries returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasRetries() bool { + if o != nil && o.Retries != nil { return true } return false } -// GetRetries returns the Retries field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetries() *int32 { +// GetTargetTimeout returns the TargetTimeout field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeout() *int32 { if o == nil { return nil } - return o.Retries + return o.TargetTimeout } -// GetRetriesOk returns a tuple with the Retries field value +// GetTargetTimeoutOk returns a tuple with the TargetTimeout field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetriesOk() (*int32, bool) { +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeoutOk() (*int32, bool) { if o == nil { return nil, false } - return o.Retries, true + return o.TargetTimeout, true } -// SetRetries sets field value -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetRetries(v int32) { +// SetTargetTimeout sets field value +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetTargetTimeout(v int32) { - o.Retries = &v + o.TargetTimeout = &v } -// HasRetries returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasRetries() bool { - if o != nil && o.Retries != nil { +// HasTargetTimeout returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasTargetTimeout() bool { + if o != nil && o.TargetTimeout != nil { return true } @@ -201,15 +201,19 @@ func (o NetworkLoadBalancerForwardingRuleHealthCheck) MarshalJSON() ([]byte, err if o.ClientTimeout != nil { toSerialize["clientTimeout"] = o.ClientTimeout } + if o.ConnectTimeout != nil { toSerialize["connectTimeout"] = o.ConnectTimeout } - if o.TargetTimeout != nil { - toSerialize["targetTimeout"] = o.TargetTimeout - } + if o.Retries != nil { toSerialize["retries"] = o.Retries } + + if o.TargetTimeout != nil { + toSerialize["targetTimeout"] = o.TargetTimeout + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go index 35e452787..c3131afa1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go @@ -16,17 +16,17 @@ import ( // NetworkLoadBalancerForwardingRuleProperties struct for NetworkLoadBalancerForwardingRuleProperties type NetworkLoadBalancerForwardingRuleProperties struct { - // The name of the Network Load Balancer forwarding rule. - Name *string `json:"name"` // Balancing algorithm - Algorithm *string `json:"algorithm"` - // Balancing protocol - Protocol *string `json:"protocol"` + Algorithm *string `json:"algorithm"` + HealthCheck *NetworkLoadBalancerForwardingRuleHealthCheck `json:"healthCheck,omitempty"` // Listening (inbound) IP. ListenerIp *string `json:"listenerIp"` // Listening (inbound) port number; valid range is 1 to 65535. - ListenerPort *int32 `json:"listenerPort"` - HealthCheck *NetworkLoadBalancerForwardingRuleHealthCheck `json:"healthCheck,omitempty"` + ListenerPort *int32 `json:"listenerPort"` + // The name of the Network Load Balancer forwarding rule. + Name *string `json:"name"` + // Balancing protocol + Protocol *string `json:"protocol"` // Array of items in the collection. Targets *[]NetworkLoadBalancerForwardingRuleTarget `json:"targets"` } @@ -35,14 +35,14 @@ type NetworkLoadBalancerForwardingRuleProperties struct { // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewNetworkLoadBalancerForwardingRuleProperties(name string, algorithm string, protocol string, listenerIp string, listenerPort int32, targets []NetworkLoadBalancerForwardingRuleTarget) *NetworkLoadBalancerForwardingRuleProperties { +func NewNetworkLoadBalancerForwardingRuleProperties(algorithm string, listenerIp string, listenerPort int32, name string, protocol string, targets []NetworkLoadBalancerForwardingRuleTarget) *NetworkLoadBalancerForwardingRuleProperties { this := NetworkLoadBalancerForwardingRuleProperties{} - this.Name = &name this.Algorithm = &algorithm - this.Protocol = &protocol this.ListenerIp = &listenerIp this.ListenerPort = &listenerPort + this.Name = &name + this.Protocol = &protocol this.Targets = &targets return &this @@ -56,46 +56,8 @@ func NewNetworkLoadBalancerForwardingRulePropertiesWithDefaults() *NetworkLoadBa return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetName() *string { - if o == nil { - return nil - } - - return o.Name - -} - -// GetNameOk returns a tuple with the Name field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Name, true -} - -// SetName sets field value -func (o *NetworkLoadBalancerForwardingRuleProperties) SetName(v string) { - - o.Name = &v - -} - -// HasName returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleProperties) HasName() bool { - if o != nil && o.Name != nil { - return true - } - - return false -} - // GetAlgorithm returns the Algorithm field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetAlgorithm() *string { if o == nil { return nil @@ -132,38 +94,38 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasAlgorithm() bool { return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocol() *string { +// GetHealthCheck returns the HealthCheck field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheck() *NetworkLoadBalancerForwardingRuleHealthCheck { if o == nil { return nil } - return o.Protocol + return o.HealthCheck } -// GetProtocolOk returns a tuple with the Protocol field value +// GetHealthCheckOk returns a tuple with the HealthCheck field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleHealthCheck, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.HealthCheck, true } -// SetProtocol sets field value -func (o *NetworkLoadBalancerForwardingRuleProperties) SetProtocol(v string) { +// SetHealthCheck sets field value +func (o *NetworkLoadBalancerForwardingRuleProperties) SetHealthCheck(v NetworkLoadBalancerForwardingRuleHealthCheck) { - o.Protocol = &v + o.HealthCheck = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasHealthCheck returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleProperties) HasHealthCheck() bool { + if o != nil && o.HealthCheck != nil { return true } @@ -171,7 +133,7 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasProtocol() bool { } // GetListenerIp returns the ListenerIp field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetListenerIp() *string { if o == nil { return nil @@ -209,7 +171,7 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasListenerIp() bool { } // GetListenerPort returns the ListenerPort field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetListenerPort() *int32 { if o == nil { return nil @@ -246,38 +208,76 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasListenerPort() bool { return false } -// GetHealthCheck returns the HealthCheck field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleHealthCheck will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheck() *NetworkLoadBalancerForwardingRuleHealthCheck { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetName() *string { if o == nil { return nil } - return o.HealthCheck + return o.Name } -// GetHealthCheckOk returns a tuple with the HealthCheck field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleHealthCheck, bool) { +func (o *NetworkLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.HealthCheck, true + return o.Name, true } -// SetHealthCheck sets field value -func (o *NetworkLoadBalancerForwardingRuleProperties) SetHealthCheck(v NetworkLoadBalancerForwardingRuleHealthCheck) { +// SetName sets field value +func (o *NetworkLoadBalancerForwardingRuleProperties) SetName(v string) { - o.HealthCheck = &v + o.Name = &v } -// HasHealthCheck returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleProperties) HasHealthCheck() bool { - if o != nil && o.HealthCheck != nil { +// HasName returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleProperties) HasName() bool { + if o != nil && o.Name != nil { + return true + } + + return false +} + +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocol() *string { + if o == nil { + return nil + } + + return o.Protocol + +} + +// GetProtocolOk returns a tuple with the Protocol field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Protocol, true +} + +// SetProtocol sets field value +func (o *NetworkLoadBalancerForwardingRuleProperties) SetProtocol(v string) { + + o.Protocol = &v + +} + +// HasProtocol returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } @@ -285,7 +285,7 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasHealthCheck() bool { } // GetTargets returns the Targets field value -// If the value is explicit nil, the zero value for []NetworkLoadBalancerForwardingRuleTarget will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetTargets() *[]NetworkLoadBalancerForwardingRuleTarget { if o == nil { return nil @@ -324,27 +324,34 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasTargets() bool { func (o NetworkLoadBalancerForwardingRuleProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Algorithm != nil { toSerialize["algorithm"] = o.Algorithm } - if o.Protocol != nil { - toSerialize["protocol"] = o.Protocol + + if o.HealthCheck != nil { + toSerialize["healthCheck"] = o.HealthCheck } + if o.ListenerIp != nil { toSerialize["listenerIp"] = o.ListenerIp } + if o.ListenerPort != nil { toSerialize["listenerPort"] = o.ListenerPort } - if o.HealthCheck != nil { - toSerialize["healthCheck"] = o.HealthCheck + + if o.Name != nil { + toSerialize["name"] = o.Name } + + if o.Protocol != nil { + toSerialize["protocol"] = o.Protocol + } + if o.Targets != nil { toSerialize["targets"] = o.Targets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go index ee8f95aea..16c6e39bb 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go @@ -16,13 +16,13 @@ import ( // NetworkLoadBalancerForwardingRulePut struct for NetworkLoadBalancerForwardingRulePut type NetworkLoadBalancerForwardingRulePut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NetworkLoadBalancerForwardingRuleProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NetworkLoadBalancerForwardingRuleProperties `json:"properties"` } // NewNetworkLoadBalancerForwardingRulePut instantiates a new NetworkLoadBalancerForwardingRulePut object @@ -45,152 +45,152 @@ func NewNetworkLoadBalancerForwardingRulePutWithDefaults() *NetworkLoadBalancerF return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetId(v string) { +// SetHref sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetType(v Type) { +// SetId sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetHref(v string) { +// SetProperties sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleProperties will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NetworkLoadBalancerForwardingRulePut) HasProperties() bool { func (o NetworkLoadBalancerForwardingRulePut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go index 502d5bda8..f02e7608c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go @@ -16,13 +16,15 @@ import ( // NetworkLoadBalancerForwardingRuleTarget struct for NetworkLoadBalancerForwardingRuleTarget type NetworkLoadBalancerForwardingRuleTarget struct { + HealthCheck *NetworkLoadBalancerForwardingRuleTargetHealthCheck `json:"healthCheck,omitempty"` // The IP of the balanced target VM. Ip *string `json:"ip"` // The port of the balanced target service; valid range is 1 to 65535. Port *int32 `json:"port"` // Traffic is distributed in proportion to target weight, relative to the combined weight of all targets. A target with higher weight receives a greater share of traffic. Valid range is 0 to 256 and default is 1. Targets with weight of 0 do not participate in load balancing but still accept persistent connections. It is best to assign weights in the middle of the range to leave room for later adjustments. - Weight *int32 `json:"weight"` - HealthCheck *NetworkLoadBalancerForwardingRuleTargetHealthCheck `json:"healthCheck,omitempty"` + Weight *int32 `json:"weight"` + // ProxyProtocol is used to set the proxy protocol version. + ProxyProtocol *string `json:"proxyProtocol,omitempty"` } // NewNetworkLoadBalancerForwardingRuleTarget instantiates a new NetworkLoadBalancerForwardingRuleTarget object @@ -35,6 +37,8 @@ func NewNetworkLoadBalancerForwardingRuleTarget(ip string, port int32, weight in this.Ip = &ip this.Port = &port this.Weight = &weight + var proxyProtocol string = "none" + this.ProxyProtocol = &proxyProtocol return &this } @@ -44,11 +48,51 @@ func NewNetworkLoadBalancerForwardingRuleTarget(ip string, port int32, weight in // but it doesn't guarantee that properties required by API are set func NewNetworkLoadBalancerForwardingRuleTargetWithDefaults() *NetworkLoadBalancerForwardingRuleTarget { this := NetworkLoadBalancerForwardingRuleTarget{} + var proxyProtocol string = "none" + this.ProxyProtocol = &proxyProtocol return &this } +// GetHealthCheck returns the HealthCheck field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheck() *NetworkLoadBalancerForwardingRuleTargetHealthCheck { + if o == nil { + return nil + } + + return o.HealthCheck + +} + +// GetHealthCheckOk returns a tuple with the HealthCheck field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleTargetHealthCheck, bool) { + if o == nil { + return nil, false + } + + return o.HealthCheck, true +} + +// SetHealthCheck sets field value +func (o *NetworkLoadBalancerForwardingRuleTarget) SetHealthCheck(v NetworkLoadBalancerForwardingRuleTargetHealthCheck) { + + o.HealthCheck = &v + +} + +// HasHealthCheck returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleTarget) HasHealthCheck() bool { + if o != nil && o.HealthCheck != nil { + return true + } + + return false +} + // GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTarget) GetIp() *string { if o == nil { return nil @@ -86,7 +130,7 @@ func (o *NetworkLoadBalancerForwardingRuleTarget) HasIp() bool { } // GetPort returns the Port field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTarget) GetPort() *int32 { if o == nil { return nil @@ -124,7 +168,7 @@ func (o *NetworkLoadBalancerForwardingRuleTarget) HasPort() bool { } // GetWeight returns the Weight field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTarget) GetWeight() *int32 { if o == nil { return nil @@ -161,38 +205,38 @@ func (o *NetworkLoadBalancerForwardingRuleTarget) HasWeight() bool { return false } -// GetHealthCheck returns the HealthCheck field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleTargetHealthCheck will be returned -func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheck() *NetworkLoadBalancerForwardingRuleTargetHealthCheck { +// GetProxyProtocol returns the ProxyProtocol field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleTarget) GetProxyProtocol() *string { if o == nil { return nil } - return o.HealthCheck + return o.ProxyProtocol } -// GetHealthCheckOk returns a tuple with the HealthCheck field value +// GetProxyProtocolOk returns a tuple with the ProxyProtocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleTargetHealthCheck, bool) { +func (o *NetworkLoadBalancerForwardingRuleTarget) GetProxyProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.HealthCheck, true + return o.ProxyProtocol, true } -// SetHealthCheck sets field value -func (o *NetworkLoadBalancerForwardingRuleTarget) SetHealthCheck(v NetworkLoadBalancerForwardingRuleTargetHealthCheck) { +// SetProxyProtocol sets field value +func (o *NetworkLoadBalancerForwardingRuleTarget) SetProxyProtocol(v string) { - o.HealthCheck = &v + o.ProxyProtocol = &v } -// HasHealthCheck returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleTarget) HasHealthCheck() bool { - if o != nil && o.HealthCheck != nil { +// HasProxyProtocol returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleTarget) HasProxyProtocol() bool { + if o != nil && o.ProxyProtocol != nil { return true } @@ -201,18 +245,26 @@ func (o *NetworkLoadBalancerForwardingRuleTarget) HasHealthCheck() bool { func (o NetworkLoadBalancerForwardingRuleTarget) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.HealthCheck != nil { + toSerialize["healthCheck"] = o.HealthCheck + } + if o.Ip != nil { toSerialize["ip"] = o.Ip } + if o.Port != nil { toSerialize["port"] = o.Port } + if o.Weight != nil { toSerialize["weight"] = o.Weight } - if o.HealthCheck != nil { - toSerialize["healthCheck"] = o.HealthCheck + + if o.ProxyProtocol != nil { + toSerialize["proxyProtocol"] = o.ProxyProtocol } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go index 8fac2b6db..8d7e994a3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go @@ -43,7 +43,7 @@ func NewNetworkLoadBalancerForwardingRuleTargetHealthCheckWithDefaults() *Networ } // GetCheck returns the Check field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) GetCheck() *bool { if o == nil { return nil @@ -81,7 +81,7 @@ func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) HasCheck() bool { } // GetCheckInterval returns the CheckInterval field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) GetCheckInterval() *int32 { if o == nil { return nil @@ -119,7 +119,7 @@ func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) HasCheckInterval() } // GetMaintenance returns the Maintenance field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) GetMaintenance() *bool { if o == nil { return nil @@ -161,12 +161,15 @@ func (o NetworkLoadBalancerForwardingRuleTargetHealthCheck) MarshalJSON() ([]byt if o.Check != nil { toSerialize["check"] = o.Check } + if o.CheckInterval != nil { toSerialize["checkInterval"] = o.CheckInterval } + if o.Maintenance != nil { toSerialize["maintenance"] = o.Maintenance } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go index a23c77408..2668d6328 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go @@ -16,19 +16,19 @@ import ( // NetworkLoadBalancerForwardingRules struct for NetworkLoadBalancerForwardingRules type NetworkLoadBalancerForwardingRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NetworkLoadBalancerForwardingRule `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancerForwardingRules instantiates a new NetworkLoadBalancerForwardingRules object @@ -49,114 +49,114 @@ func NewNetworkLoadBalancerForwardingRulesWithDefaults() *NetworkLoadBalancerFor return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRules) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *NetworkLoadBalancerForwardingRules) SetId(v string) { +// SetLinks sets field value +func (o *NetworkLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerForwardingRules) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NetworkLoadBalancerForwardingRules) SetType(v Type) { +// SetHref sets field value +func (o *NetworkLoadBalancerForwardingRules) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRules) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NetworkLoadBalancerForwardingRules) SetHref(v string) { +// SetId sets field value +func (o *NetworkLoadBalancerForwardingRules) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *NetworkLoadBalancerForwardingRules) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NetworkLoadBalancerForwardingRule will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRules) GetItems() *[]NetworkLoadBalancerForwardingRule { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *NetworkLoadBalancerForwardingRules) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancerForwardingRules) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *NetworkLoadBalancerForwardingRules) SetOffset(v float32) { +// SetLimit sets field value +func (o *NetworkLoadBalancerForwardingRules) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *NetworkLoadBalancerForwardingRules) SetLimit(v float32) { +// SetOffset sets field value +func (o *NetworkLoadBalancerForwardingRules) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *NetworkLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *NetworkLoadBalancerForwardingRules) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *NetworkLoadBalancerForwardingRules) HasLinks() bool { func (o NetworkLoadBalancerForwardingRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go index 94170d456..114b8b08a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go @@ -16,27 +16,27 @@ import ( // NetworkLoadBalancerProperties struct for NetworkLoadBalancerProperties type NetworkLoadBalancerProperties struct { - // The name of the Network Load Balancer. - Name *string `json:"name"` - // ID of the listening LAN (inbound). - ListenerLan *int32 `json:"listenerLan"` // Collection of the Network Load Balancer IP addresses. (Inbound and outbound) IPs of the listenerLan must be customer-reserved IPs for public Load Balancers, and private IPs for private Load Balancers. Ips *[]string `json:"ips,omitempty"` - // ID of the balanced private target LAN (outbound). - TargetLan *int32 `json:"targetLan"` // Collection of private IP addresses with subnet mask of the Network Load Balancer. IPs must contain a valid subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. LbPrivateIps *[]string `json:"lbPrivateIps,omitempty"` + // ID of the listening LAN (inbound). + ListenerLan *int32 `json:"listenerLan"` + // The name of the Network Load Balancer. + Name *string `json:"name"` + // ID of the balanced private target LAN (outbound). + TargetLan *int32 `json:"targetLan"` } // NewNetworkLoadBalancerProperties instantiates a new NetworkLoadBalancerProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewNetworkLoadBalancerProperties(name string, listenerLan int32, targetLan int32) *NetworkLoadBalancerProperties { +func NewNetworkLoadBalancerProperties(listenerLan int32, name string, targetLan int32) *NetworkLoadBalancerProperties { this := NetworkLoadBalancerProperties{} - this.Name = &name this.ListenerLan = &listenerLan + this.Name = &name this.TargetLan = &targetLan return &this @@ -50,38 +50,76 @@ func NewNetworkLoadBalancerPropertiesWithDefaults() *NetworkLoadBalancerProperti return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerProperties) GetName() *string { +// GetIps returns the Ips field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerProperties) GetIps() *[]string { if o == nil { return nil } - return o.Name + return o.Ips } -// GetNameOk returns a tuple with the Name field value +// GetIpsOk returns a tuple with the Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerProperties) GetNameOk() (*string, bool) { +func (o *NetworkLoadBalancerProperties) GetIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Ips, true } -// SetName sets field value -func (o *NetworkLoadBalancerProperties) SetName(v string) { +// SetIps sets field value +func (o *NetworkLoadBalancerProperties) SetIps(v []string) { - o.Name = &v + o.Ips = &v } -// HasName returns a boolean if a field has been set. -func (o *NetworkLoadBalancerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasIps returns a boolean if a field has been set. +func (o *NetworkLoadBalancerProperties) HasIps() bool { + if o != nil && o.Ips != nil { + return true + } + + return false +} + +// GetLbPrivateIps returns the LbPrivateIps field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerProperties) GetLbPrivateIps() *[]string { + if o == nil { + return nil + } + + return o.LbPrivateIps + +} + +// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NetworkLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { + if o == nil { + return nil, false + } + + return o.LbPrivateIps, true +} + +// SetLbPrivateIps sets field value +func (o *NetworkLoadBalancerProperties) SetLbPrivateIps(v []string) { + + o.LbPrivateIps = &v + +} + +// HasLbPrivateIps returns a boolean if a field has been set. +func (o *NetworkLoadBalancerProperties) HasLbPrivateIps() bool { + if o != nil && o.LbPrivateIps != nil { return true } @@ -89,7 +127,7 @@ func (o *NetworkLoadBalancerProperties) HasName() bool { } // GetListenerLan returns the ListenerLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerProperties) GetListenerLan() *int32 { if o == nil { return nil @@ -126,38 +164,38 @@ func (o *NetworkLoadBalancerProperties) HasListenerLan() bool { return false } -// GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NetworkLoadBalancerProperties) GetIps() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerProperties) GetName() *string { if o == nil { return nil } - return o.Ips + return o.Name } -// GetIpsOk returns a tuple with the Ips field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerProperties) GetIpsOk() (*[]string, bool) { +func (o *NetworkLoadBalancerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Ips, true + return o.Name, true } -// SetIps sets field value -func (o *NetworkLoadBalancerProperties) SetIps(v []string) { +// SetName sets field value +func (o *NetworkLoadBalancerProperties) SetName(v string) { - o.Ips = &v + o.Name = &v } -// HasIps returns a boolean if a field has been set. -func (o *NetworkLoadBalancerProperties) HasIps() bool { - if o != nil && o.Ips != nil { +// HasName returns a boolean if a field has been set. +func (o *NetworkLoadBalancerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -165,7 +203,7 @@ func (o *NetworkLoadBalancerProperties) HasIps() bool { } // GetTargetLan returns the TargetLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerProperties) GetTargetLan() *int32 { if o == nil { return nil @@ -202,61 +240,28 @@ func (o *NetworkLoadBalancerProperties) HasTargetLan() bool { return false } -// GetLbPrivateIps returns the LbPrivateIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NetworkLoadBalancerProperties) GetLbPrivateIps() *[]string { - if o == nil { - return nil +func (o NetworkLoadBalancerProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.Ips != nil { + toSerialize["ips"] = o.Ips } - return o.LbPrivateIps - -} - -// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { - if o == nil { - return nil, false + if o.LbPrivateIps != nil { + toSerialize["lbPrivateIps"] = o.LbPrivateIps } - return o.LbPrivateIps, true -} - -// SetLbPrivateIps sets field value -func (o *NetworkLoadBalancerProperties) SetLbPrivateIps(v []string) { - - o.LbPrivateIps = &v - -} - -// HasLbPrivateIps returns a boolean if a field has been set. -func (o *NetworkLoadBalancerProperties) HasLbPrivateIps() bool { - if o != nil && o.LbPrivateIps != nil { - return true + if o.ListenerLan != nil { + toSerialize["listenerLan"] = o.ListenerLan } - return false -} - -func (o NetworkLoadBalancerProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} if o.Name != nil { toSerialize["name"] = o.Name } - if o.ListenerLan != nil { - toSerialize["listenerLan"] = o.ListenerLan - } - if o.Ips != nil { - toSerialize["ips"] = o.Ips - } + if o.TargetLan != nil { toSerialize["targetLan"] = o.TargetLan } - if o.LbPrivateIps != nil { - toSerialize["lbPrivateIps"] = o.LbPrivateIps - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go index 05bde508c..ec4deb54b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go @@ -16,13 +16,13 @@ import ( // NetworkLoadBalancerPut struct for NetworkLoadBalancerPut type NetworkLoadBalancerPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NetworkLoadBalancerProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NetworkLoadBalancerProperties `json:"properties"` } // NewNetworkLoadBalancerPut instantiates a new NetworkLoadBalancerPut object @@ -45,152 +45,152 @@ func NewNetworkLoadBalancerPutWithDefaults() *NetworkLoadBalancerPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NetworkLoadBalancerPut) SetId(v string) { +// SetHref sets field value +func (o *NetworkLoadBalancerPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NetworkLoadBalancerPut) SetType(v Type) { +// SetId sets field value +func (o *NetworkLoadBalancerPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetProperties() *NetworkLoadBalancerProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerPut) GetPropertiesOk() (*NetworkLoadBalancerProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NetworkLoadBalancerPut) SetHref(v string) { +// SetProperties sets field value +func (o *NetworkLoadBalancerPut) SetProperties(v NetworkLoadBalancerProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerProperties will be returned -func (o *NetworkLoadBalancerPut) GetProperties() *NetworkLoadBalancerProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetPropertiesOk() (*NetworkLoadBalancerProperties, bool) { +func (o *NetworkLoadBalancerPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NetworkLoadBalancerPut) SetProperties(v NetworkLoadBalancerProperties) { +// SetType sets field value +func (o *NetworkLoadBalancerPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NetworkLoadBalancerPut) HasProperties() bool { func (o NetworkLoadBalancerPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go index 91bbe63e1..b4ccbbc87 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go @@ -16,19 +16,19 @@ import ( // NetworkLoadBalancers struct for NetworkLoadBalancers type NetworkLoadBalancers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NetworkLoadBalancer `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancers instantiates a new NetworkLoadBalancers object @@ -49,114 +49,114 @@ func NewNetworkLoadBalancersWithDefaults() *NetworkLoadBalancers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *NetworkLoadBalancers) SetId(v string) { +// SetLinks sets field value +func (o *NetworkLoadBalancers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NetworkLoadBalancers) SetType(v Type) { +// SetHref sets field value +func (o *NetworkLoadBalancers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NetworkLoadBalancers) SetHref(v string) { +// SetId sets field value +func (o *NetworkLoadBalancers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *NetworkLoadBalancers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NetworkLoadBalancer will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancers) GetItems() *[]NetworkLoadBalancer { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *NetworkLoadBalancers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetOffsetOk() (*float32, bool) { +func (o *NetworkLoadBalancers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *NetworkLoadBalancers) SetOffset(v float32) { +// SetLimit sets field value +func (o *NetworkLoadBalancers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetLimitOk() (*float32, bool) { +func (o *NetworkLoadBalancers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *NetworkLoadBalancers) SetLimit(v float32) { +// SetOffset sets field value +func (o *NetworkLoadBalancers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *NetworkLoadBalancers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { +func (o *NetworkLoadBalancers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *NetworkLoadBalancers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *NetworkLoadBalancers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *NetworkLoadBalancers) HasLinks() bool { func (o NetworkLoadBalancers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go index 9d8378c6f..6a9c05537 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go @@ -16,15 +16,15 @@ import ( // Nic struct for Nic type Nic struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *NicEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NicProperties `json:"properties"` - Entities *NicEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNic instantiates a new Nic object @@ -47,114 +47,114 @@ func NewNicWithDefaults() *Nic { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nic) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetEntities() *NicEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetIdOk() (*string, bool) { +func (o *Nic) GetEntitiesOk() (*NicEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Nic) SetId(v string) { +// SetEntities sets field value +func (o *Nic) SetEntities(v NicEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Nic) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Nic) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Nic) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetTypeOk() (*Type, bool) { +func (o *Nic) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Nic) SetType(v Type) { +// SetHref sets field value +func (o *Nic) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Nic) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Nic) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nic) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetHrefOk() (*string, bool) { +func (o *Nic) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Nic) SetHref(v string) { +// SetId sets field value +func (o *Nic) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Nic) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Nic) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Nic) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Nic) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Nic) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NicProperties will be returned +// If the value is explicit nil, nil is returned func (o *Nic) GetProperties() *NicProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Nic) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for NicEntities will be returned -func (o *Nic) GetEntities() *NicEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetEntitiesOk() (*NicEntities, bool) { +func (o *Nic) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Nic) SetEntities(v NicEntities) { +// SetType sets field value +func (o *Nic) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Nic) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Nic) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Nic) HasEntities() bool { func (o Nic) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go index b1a5553a7..ab19ab4ac 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go @@ -16,8 +16,8 @@ import ( // NicEntities struct for NicEntities type NicEntities struct { - Flowlogs *FlowLogs `json:"flowlogs,omitempty"` Firewallrules *FirewallRules `json:"firewallrules,omitempty"` + Flowlogs *FlowLogs `json:"flowlogs,omitempty"` } // NewNicEntities instantiates a new NicEntities object @@ -38,76 +38,76 @@ func NewNicEntitiesWithDefaults() *NicEntities { return &this } -// GetFlowlogs returns the Flowlogs field value -// If the value is explicit nil, the zero value for FlowLogs will be returned -func (o *NicEntities) GetFlowlogs() *FlowLogs { +// GetFirewallrules returns the Firewallrules field value +// If the value is explicit nil, nil is returned +func (o *NicEntities) GetFirewallrules() *FirewallRules { if o == nil { return nil } - return o.Flowlogs + return o.Firewallrules } -// GetFlowlogsOk returns a tuple with the Flowlogs field value +// GetFirewallrulesOk returns a tuple with the Firewallrules field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicEntities) GetFlowlogsOk() (*FlowLogs, bool) { +func (o *NicEntities) GetFirewallrulesOk() (*FirewallRules, bool) { if o == nil { return nil, false } - return o.Flowlogs, true + return o.Firewallrules, true } -// SetFlowlogs sets field value -func (o *NicEntities) SetFlowlogs(v FlowLogs) { +// SetFirewallrules sets field value +func (o *NicEntities) SetFirewallrules(v FirewallRules) { - o.Flowlogs = &v + o.Firewallrules = &v } -// HasFlowlogs returns a boolean if a field has been set. -func (o *NicEntities) HasFlowlogs() bool { - if o != nil && o.Flowlogs != nil { +// HasFirewallrules returns a boolean if a field has been set. +func (o *NicEntities) HasFirewallrules() bool { + if o != nil && o.Firewallrules != nil { return true } return false } -// GetFirewallrules returns the Firewallrules field value -// If the value is explicit nil, the zero value for FirewallRules will be returned -func (o *NicEntities) GetFirewallrules() *FirewallRules { +// GetFlowlogs returns the Flowlogs field value +// If the value is explicit nil, nil is returned +func (o *NicEntities) GetFlowlogs() *FlowLogs { if o == nil { return nil } - return o.Firewallrules + return o.Flowlogs } -// GetFirewallrulesOk returns a tuple with the Firewallrules field value +// GetFlowlogsOk returns a tuple with the Flowlogs field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicEntities) GetFirewallrulesOk() (*FirewallRules, bool) { +func (o *NicEntities) GetFlowlogsOk() (*FlowLogs, bool) { if o == nil { return nil, false } - return o.Firewallrules, true + return o.Flowlogs, true } -// SetFirewallrules sets field value -func (o *NicEntities) SetFirewallrules(v FirewallRules) { +// SetFlowlogs sets field value +func (o *NicEntities) SetFlowlogs(v FlowLogs) { - o.Firewallrules = &v + o.Flowlogs = &v } -// HasFirewallrules returns a boolean if a field has been set. -func (o *NicEntities) HasFirewallrules() bool { - if o != nil && o.Firewallrules != nil { +// HasFlowlogs returns a boolean if a field has been set. +func (o *NicEntities) HasFlowlogs() bool { + if o != nil && o.Flowlogs != nil { return true } @@ -116,12 +116,14 @@ func (o *NicEntities) HasFirewallrules() bool { func (o NicEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Flowlogs != nil { - toSerialize["flowlogs"] = o.Flowlogs - } if o.Firewallrules != nil { toSerialize["firewallrules"] = o.Firewallrules } + + if o.Flowlogs != nil { + toSerialize["flowlogs"] = o.Flowlogs + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go index 20d0323ac..c24c1a4ca 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go @@ -16,24 +16,36 @@ import ( // NicProperties struct for NicProperties type NicProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // The MAC address of the NIC. - Mac *string `json:"mac,omitempty"` - // Collection of IP addresses, assigned to the NIC. Explicitly assigned public IPs need to come from reserved IP blocks. Passing value null or empty array will assign an IP address automatically. - Ips *[]string `json:"ips,omitempty"` + // The Logical Unit Number (LUN) of the storage volume. Null if this NIC was created using Cloud API and no DCD changes were performed on the Datacenter. + DeviceNumber *int32 `json:"deviceNumber,omitempty"` // Indicates if the NIC will reserve an IP using DHCP. Dhcp *bool `json:"dhcp,omitempty"` - // The LAN ID the NIC will be on. If the LAN ID does not exist, it will be implicitly created. - Lan *int32 `json:"lan"` + // Indicates if the NIC will receive an IPv6 using DHCP. It can be set to 'true' or 'false' only if this NIC is connected to an IPv6 enabled LAN. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilbool` can be used, or the setter `SetDhcpv6Nil` + Dhcpv6 *bool `json:"dhcpv6,omitempty"` // Activate or deactivate the firewall. By default, an active firewall without any defined rules will block all incoming network traffic except for the firewall rules that explicitly allows certain protocols, IP addresses and ports. FirewallActive *bool `json:"firewallActive,omitempty"` // The type of firewall rules that will be allowed on the NIC. If not specified, the default INGRESS value is used. FirewallType *string `json:"firewallType,omitempty"` - // The Logical Unit Number (LUN) of the storage volume. Null if this NIC was created using Cloud API and no DCD changes were performed on the Datacenter. - DeviceNumber *int32 `json:"deviceNumber,omitempty"` + // Collection of IP addresses, assigned to the NIC. Explicitly assigned public IPs need to come from reserved IP blocks. Passing value null or empty array will assign an IP address automatically. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nil[]string` can be used, or the setter `SetIpsNil` + Ips *[]string `json:"ips,omitempty"` + // If this NIC is connected to an IPv6 enabled LAN then this property contains the /80 IPv6 CIDR block of the NIC. If you leave this property 'null' when adding a NIC to an IPv6-enabled LAN, then an IPv6 CIDR block will automatically be assigned to the NIC, but you can also specify an /80 IPv6 CIDR block for the NIC on your own, which must be inside the /64 IPv6 CIDR block of the LAN and unique. This value can only be set, if the LAN already has an IPv6 CIDR block assigned. An IPv6-enabled LAN is limited to a maximum of 65,536 NICs. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpv6CidrBlockNil` + Ipv6CidrBlock *string `json:"ipv6CidrBlock,omitempty"` + // If this NIC is connected to an IPv6 enabled LAN then this property contains the IPv6 IP addresses of the NIC. The maximum number of IPv6 IP addresses per NIC is 50, if you need more, contact support. If you leave this property 'null' when adding a NIC, when changing the NIC's IPv6 CIDR block, when changing the LAN's IPv6 CIDR block or when moving the NIC to a different IPv6 enabled LAN, then we will automatically assign the same number of IPv6 addresses which you had before from the NICs new CIDR block. If you leave this property 'null' while not changing the CIDR block, the IPv6 IP addresses won't be changed either. You can also provide your own self choosen IPv6 addresses, which then must be inside the IPv6 CIDR block of this NIC. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nil[]string` can be used, or the setter `SetIpv6IpsNil` + Ipv6Ips *[]string `json:"ipv6Ips,omitempty"` + // The LAN ID the NIC will be on. If the LAN ID does not exist, it will be implicitly created. + Lan *int32 `json:"lan"` + // The MAC address of the NIC. + Mac *string `json:"mac,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // The PCI slot number for the NIC. PciSlot *int32 `json:"pciSlot,omitempty"` + // The vnet ID that belongs to this NIC; Requires system privileges + Vnet *string `json:"vnet,omitempty"` } // NewNicProperties instantiates a new NicProperties object @@ -60,76 +72,195 @@ func NewNicPropertiesWithDefaults() *NicProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicProperties) GetName() *string { +// GetDeviceNumber returns the DeviceNumber field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetDeviceNumber() *int32 { if o == nil { return nil } - return o.Name + return o.DeviceNumber } -// GetNameOk returns a tuple with the Name field value +// GetDeviceNumberOk returns a tuple with the DeviceNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetNameOk() (*string, bool) { +func (o *NicProperties) GetDeviceNumberOk() (*int32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.DeviceNumber, true } -// SetName sets field value -func (o *NicProperties) SetName(v string) { +// SetDeviceNumber sets field value +func (o *NicProperties) SetDeviceNumber(v int32) { - o.Name = &v + o.DeviceNumber = &v } -// HasName returns a boolean if a field has been set. -func (o *NicProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasDeviceNumber returns a boolean if a field has been set. +func (o *NicProperties) HasDeviceNumber() bool { + if o != nil && o.DeviceNumber != nil { return true } return false } -// GetMac returns the Mac field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicProperties) GetMac() *string { +// GetDhcp returns the Dhcp field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetDhcp() *bool { if o == nil { return nil } - return o.Mac + return o.Dhcp } -// GetMacOk returns a tuple with the Mac field value +// GetDhcpOk returns a tuple with the Dhcp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetMacOk() (*string, bool) { +func (o *NicProperties) GetDhcpOk() (*bool, bool) { if o == nil { return nil, false } - return o.Mac, true + return o.Dhcp, true } -// SetMac sets field value -func (o *NicProperties) SetMac(v string) { +// SetDhcp sets field value +func (o *NicProperties) SetDhcp(v bool) { - o.Mac = &v + o.Dhcp = &v } -// HasMac returns a boolean if a field has been set. -func (o *NicProperties) HasMac() bool { - if o != nil && o.Mac != nil { +// HasDhcp returns a boolean if a field has been set. +func (o *NicProperties) HasDhcp() bool { + if o != nil && o.Dhcp != nil { + return true + } + + return false +} + +// GetDhcpv6 returns the Dhcpv6 field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetDhcpv6() *bool { + if o == nil { + return nil + } + + return o.Dhcpv6 + +} + +// GetDhcpv6Ok returns a tuple with the Dhcpv6 field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NicProperties) GetDhcpv6Ok() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.Dhcpv6, true +} + +// SetDhcpv6 sets field value +func (o *NicProperties) SetDhcpv6(v bool) { + + o.Dhcpv6 = &v + +} + +// sets Dhcpv6 to the explicit address that will be encoded as nil when marshaled +func (o *NicProperties) SetDhcpv6Nil() { + o.Dhcpv6 = &Nilbool +} + +// HasDhcpv6 returns a boolean if a field has been set. +func (o *NicProperties) HasDhcpv6() bool { + if o != nil && o.Dhcpv6 != nil { + return true + } + + return false +} + +// GetFirewallActive returns the FirewallActive field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetFirewallActive() *bool { + if o == nil { + return nil + } + + return o.FirewallActive + +} + +// GetFirewallActiveOk returns a tuple with the FirewallActive field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NicProperties) GetFirewallActiveOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.FirewallActive, true +} + +// SetFirewallActive sets field value +func (o *NicProperties) SetFirewallActive(v bool) { + + o.FirewallActive = &v + +} + +// HasFirewallActive returns a boolean if a field has been set. +func (o *NicProperties) HasFirewallActive() bool { + if o != nil && o.FirewallActive != nil { + return true + } + + return false +} + +// GetFirewallType returns the FirewallType field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetFirewallType() *string { + if o == nil { + return nil + } + + return o.FirewallType + +} + +// GetFirewallTypeOk returns a tuple with the FirewallType field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NicProperties) GetFirewallTypeOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.FirewallType, true +} + +// SetFirewallType sets field value +func (o *NicProperties) SetFirewallType(v string) { + + o.FirewallType = &v + +} + +// HasFirewallType returns a boolean if a field has been set. +func (o *NicProperties) HasFirewallType() bool { + if o != nil && o.FirewallType != nil { return true } @@ -137,7 +268,7 @@ func (o *NicProperties) HasMac() bool { } // GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned +// If the value is explicit nil, nil is returned func (o *NicProperties) GetIps() *[]string { if o == nil { return nil @@ -174,190 +305,195 @@ func (o *NicProperties) HasIps() bool { return false } -// GetDhcp returns the Dhcp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *NicProperties) GetDhcp() *bool { +// GetIpv6CidrBlock returns the Ipv6CidrBlock field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetIpv6CidrBlock() *string { if o == nil { return nil } - return o.Dhcp + return o.Ipv6CidrBlock } -// GetDhcpOk returns a tuple with the Dhcp field value +// GetIpv6CidrBlockOk returns a tuple with the Ipv6CidrBlock field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetDhcpOk() (*bool, bool) { +func (o *NicProperties) GetIpv6CidrBlockOk() (*string, bool) { if o == nil { return nil, false } - return o.Dhcp, true + return o.Ipv6CidrBlock, true } -// SetDhcp sets field value -func (o *NicProperties) SetDhcp(v bool) { +// SetIpv6CidrBlock sets field value +func (o *NicProperties) SetIpv6CidrBlock(v string) { - o.Dhcp = &v + o.Ipv6CidrBlock = &v } -// HasDhcp returns a boolean if a field has been set. -func (o *NicProperties) HasDhcp() bool { - if o != nil && o.Dhcp != nil { +// sets Ipv6CidrBlock to the explicit address that will be encoded as nil when marshaled +func (o *NicProperties) SetIpv6CidrBlockNil() { + o.Ipv6CidrBlock = &Nilstring +} + +// HasIpv6CidrBlock returns a boolean if a field has been set. +func (o *NicProperties) HasIpv6CidrBlock() bool { + if o != nil && o.Ipv6CidrBlock != nil { return true } return false } -// GetLan returns the Lan field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NicProperties) GetLan() *int32 { +// GetIpv6Ips returns the Ipv6Ips field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetIpv6Ips() *[]string { if o == nil { return nil } - return o.Lan + return o.Ipv6Ips } -// GetLanOk returns a tuple with the Lan field value +// GetIpv6IpsOk returns a tuple with the Ipv6Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetLanOk() (*int32, bool) { +func (o *NicProperties) GetIpv6IpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Lan, true + return o.Ipv6Ips, true } -// SetLan sets field value -func (o *NicProperties) SetLan(v int32) { +// SetIpv6Ips sets field value +func (o *NicProperties) SetIpv6Ips(v []string) { - o.Lan = &v + o.Ipv6Ips = &v } -// HasLan returns a boolean if a field has been set. -func (o *NicProperties) HasLan() bool { - if o != nil && o.Lan != nil { +// HasIpv6Ips returns a boolean if a field has been set. +func (o *NicProperties) HasIpv6Ips() bool { + if o != nil && o.Ipv6Ips != nil { return true } return false } -// GetFirewallActive returns the FirewallActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *NicProperties) GetFirewallActive() *bool { +// GetLan returns the Lan field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetLan() *int32 { if o == nil { return nil } - return o.FirewallActive + return o.Lan } -// GetFirewallActiveOk returns a tuple with the FirewallActive field value +// GetLanOk returns a tuple with the Lan field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetFirewallActiveOk() (*bool, bool) { +func (o *NicProperties) GetLanOk() (*int32, bool) { if o == nil { return nil, false } - return o.FirewallActive, true + return o.Lan, true } -// SetFirewallActive sets field value -func (o *NicProperties) SetFirewallActive(v bool) { +// SetLan sets field value +func (o *NicProperties) SetLan(v int32) { - o.FirewallActive = &v + o.Lan = &v } -// HasFirewallActive returns a boolean if a field has been set. -func (o *NicProperties) HasFirewallActive() bool { - if o != nil && o.FirewallActive != nil { +// HasLan returns a boolean if a field has been set. +func (o *NicProperties) HasLan() bool { + if o != nil && o.Lan != nil { return true } return false } -// GetFirewallType returns the FirewallType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicProperties) GetFirewallType() *string { +// GetMac returns the Mac field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetMac() *string { if o == nil { return nil } - return o.FirewallType + return o.Mac } -// GetFirewallTypeOk returns a tuple with the FirewallType field value +// GetMacOk returns a tuple with the Mac field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetFirewallTypeOk() (*string, bool) { +func (o *NicProperties) GetMacOk() (*string, bool) { if o == nil { return nil, false } - return o.FirewallType, true + return o.Mac, true } -// SetFirewallType sets field value -func (o *NicProperties) SetFirewallType(v string) { +// SetMac sets field value +func (o *NicProperties) SetMac(v string) { - o.FirewallType = &v + o.Mac = &v } -// HasFirewallType returns a boolean if a field has been set. -func (o *NicProperties) HasFirewallType() bool { - if o != nil && o.FirewallType != nil { +// HasMac returns a boolean if a field has been set. +func (o *NicProperties) HasMac() bool { + if o != nil && o.Mac != nil { return true } return false } -// GetDeviceNumber returns the DeviceNumber field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NicProperties) GetDeviceNumber() *int32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetName() *string { if o == nil { return nil } - return o.DeviceNumber + return o.Name } -// GetDeviceNumberOk returns a tuple with the DeviceNumber field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetDeviceNumberOk() (*int32, bool) { +func (o *NicProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.DeviceNumber, true + return o.Name, true } -// SetDeviceNumber sets field value -func (o *NicProperties) SetDeviceNumber(v int32) { +// SetName sets field value +func (o *NicProperties) SetName(v string) { - o.DeviceNumber = &v + o.Name = &v } -// HasDeviceNumber returns a boolean if a field has been set. -func (o *NicProperties) HasDeviceNumber() bool { - if o != nil && o.DeviceNumber != nil { +// HasName returns a boolean if a field has been set. +func (o *NicProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -365,7 +501,7 @@ func (o *NicProperties) HasDeviceNumber() bool { } // GetPciSlot returns the PciSlot field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NicProperties) GetPciSlot() *int32 { if o == nil { return nil @@ -402,33 +538,100 @@ func (o *NicProperties) HasPciSlot() bool { return false } +// GetVnet returns the Vnet field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetVnet() *string { + if o == nil { + return nil + } + + return o.Vnet + +} + +// GetVnetOk returns a tuple with the Vnet field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NicProperties) GetVnetOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Vnet, true +} + +// SetVnet sets field value +func (o *NicProperties) SetVnet(v string) { + + o.Vnet = &v + +} + +// HasVnet returns a boolean if a field has been set. +func (o *NicProperties) HasVnet() bool { + if o != nil && o.Vnet != nil { + return true + } + + return false +} + func (o NicProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.Mac != nil { - toSerialize["mac"] = o.Mac + if o.DeviceNumber != nil { + toSerialize["deviceNumber"] = o.DeviceNumber } - toSerialize["ips"] = o.Ips + if o.Dhcp != nil { toSerialize["dhcp"] = o.Dhcp } - if o.Lan != nil { - toSerialize["lan"] = o.Lan + + if o.Dhcpv6 == &Nilbool { + toSerialize["dhcpv6"] = nil + } else if o.Dhcpv6 != nil { + toSerialize["dhcpv6"] = o.Dhcpv6 } if o.FirewallActive != nil { toSerialize["firewallActive"] = o.FirewallActive } + if o.FirewallType != nil { toSerialize["firewallType"] = o.FirewallType } - if o.DeviceNumber != nil { - toSerialize["deviceNumber"] = o.DeviceNumber + + if o.Ips != nil { + toSerialize["ips"] = o.Ips + } + + if o.Ipv6CidrBlock == &Nilstring { + toSerialize["ipv6CidrBlock"] = nil + } else if o.Ipv6CidrBlock != nil { + toSerialize["ipv6CidrBlock"] = o.Ipv6CidrBlock + } + + if o.Ipv6Ips != nil { + toSerialize["ipv6Ips"] = o.Ipv6Ips + } + if o.Lan != nil { + toSerialize["lan"] = o.Lan + } + + if o.Mac != nil { + toSerialize["mac"] = o.Mac + } + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.PciSlot != nil { toSerialize["pciSlot"] = o.PciSlot } + + if o.Vnet != nil { + toSerialize["vnet"] = o.Vnet + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go index e37c81075..0029a6eab 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go @@ -16,13 +16,13 @@ import ( // NicPut struct for NicPut type NicPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NicProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NicProperties `json:"properties"` } // NewNicPut instantiates a new NicPut object @@ -45,152 +45,152 @@ func NewNicPutWithDefaults() *NicPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetIdOk() (*string, bool) { +func (o *NicPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NicPut) SetId(v string) { +// SetHref sets field value +func (o *NicPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NicPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NicPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NicPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetTypeOk() (*Type, bool) { +func (o *NicPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NicPut) SetType(v Type) { +// SetId sets field value +func (o *NicPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NicPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NicPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetProperties() *NicProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetHrefOk() (*string, bool) { +func (o *NicPut) GetPropertiesOk() (*NicProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NicPut) SetHref(v string) { +// SetProperties sets field value +func (o *NicPut) SetProperties(v NicProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NicPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NicPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NicProperties will be returned -func (o *NicPut) GetProperties() *NicProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetPropertiesOk() (*NicProperties, bool) { +func (o *NicPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NicPut) SetProperties(v NicProperties) { +// SetType sets field value +func (o *NicPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NicPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NicPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NicPut) HasProperties() bool { func (o NicPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go index 80ff9957f..6fe1220a4 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go @@ -16,19 +16,19 @@ import ( // Nics struct for Nics type Nics struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Nic `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNics instantiates a new Nics object @@ -49,114 +49,114 @@ func NewNicsWithDefaults() *Nics { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nics) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetIdOk() (*string, bool) { +func (o *Nics) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Nics) SetId(v string) { +// SetLinks sets field value +func (o *Nics) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Nics) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Nics) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Nics) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetTypeOk() (*Type, bool) { +func (o *Nics) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Nics) SetType(v Type) { +// SetHref sets field value +func (o *Nics) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Nics) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Nics) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nics) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetHrefOk() (*string, bool) { +func (o *Nics) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Nics) SetHref(v string) { +// SetId sets field value +func (o *Nics) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Nics) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Nics) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Nics) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Nic will be returned +// If the value is explicit nil, nil is returned func (o *Nics) GetItems() *[]Nic { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Nics) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Nics) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetOffsetOk() (*float32, bool) { +func (o *Nics) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Nics) SetOffset(v float32) { +// SetLimit sets field value +func (o *Nics) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Nics) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Nics) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Nics) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetLimitOk() (*float32, bool) { +func (o *Nics) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Nics) SetLimit(v float32) { +// SetOffset sets field value +func (o *Nics) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Nics) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Nics) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Nics) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetLinksOk() (*PaginationLinks, bool) { +func (o *Nics) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Nics) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Nics) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Nics) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Nics) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Nics) HasLinks() bool { func (o Nics) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go index 4d1488a1d..bf6d643dd 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go @@ -17,20 +17,20 @@ import ( // NoStateMetaData struct for NoStateMetaData type NoStateMetaData struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` - // The time when the resource was created. - CreatedDate *IonosTime // The user who has created the resource. CreatedBy *string `json:"createdBy,omitempty"` // The unique ID of the user who created the resource. CreatedByUserId *string `json:"createdByUserId,omitempty"` - // The last time the resource was modified. - LastModifiedDate *IonosTime + // The time when the resource was created. + CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The user who last modified the resource. LastModifiedBy *string `json:"lastModifiedBy,omitempty"` // The unique ID of the user who last modified the resource. LastModifiedByUserId *string `json:"lastModifiedByUserId,omitempty"` + // The last time the resource was modified. + LastModifiedDate *IonosTime } // NewNoStateMetaData instantiates a new NoStateMetaData object @@ -51,91 +51,8 @@ func NewNoStateMetaDataWithDefaults() *NoStateMetaData { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NoStateMetaData) GetEtag() *string { - if o == nil { - return nil - } - - return o.Etag - -} - -// GetEtagOk returns a tuple with the Etag field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NoStateMetaData) GetEtagOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Etag, true -} - -// SetEtag sets field value -func (o *NoStateMetaData) SetEtag(v string) { - - o.Etag = &v - -} - -// HasEtag returns a boolean if a field has been set. -func (o *NoStateMetaData) HasEtag() bool { - if o != nil && o.Etag != nil { - return true - } - - return false -} - -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *NoStateMetaData) GetCreatedDate() *time.Time { - if o == nil { - return nil - } - - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time - -} - -// GetCreatedDateOk returns a tuple with the CreatedDate field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NoStateMetaData) GetCreatedDateOk() (*time.Time, bool) { - if o == nil { - return nil, false - } - - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - -} - -// SetCreatedDate sets field value -func (o *NoStateMetaData) SetCreatedDate(v time.Time) { - - o.CreatedDate = &IonosTime{v} - -} - -// HasCreatedDate returns a boolean if a field has been set. -func (o *NoStateMetaData) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { - return true - } - - return false -} - // GetCreatedBy returns the CreatedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetCreatedBy() *string { if o == nil { return nil @@ -173,7 +90,7 @@ func (o *NoStateMetaData) HasCreatedBy() bool { } // GetCreatedByUserId returns the CreatedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetCreatedByUserId() *string { if o == nil { return nil @@ -210,45 +127,83 @@ func (o *NoStateMetaData) HasCreatedByUserId() bool { return false } -// GetLastModifiedDate returns the LastModifiedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *NoStateMetaData) GetLastModifiedDate() *time.Time { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *NoStateMetaData) GetCreatedDate() *time.Time { if o == nil { return nil } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil } - return &o.LastModifiedDate.Time + return &o.CreatedDate.Time } -// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NoStateMetaData) GetLastModifiedDateOk() (*time.Time, bool) { +func (o *NoStateMetaData) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil, false } - return &o.LastModifiedDate.Time, true + return &o.CreatedDate.Time, true } -// SetLastModifiedDate sets field value -func (o *NoStateMetaData) SetLastModifiedDate(v time.Time) { +// SetCreatedDate sets field value +func (o *NoStateMetaData) SetCreatedDate(v time.Time) { - o.LastModifiedDate = &IonosTime{v} + o.CreatedDate = &IonosTime{v} } -// HasLastModifiedDate returns a boolean if a field has been set. -func (o *NoStateMetaData) HasLastModifiedDate() bool { - if o != nil && o.LastModifiedDate != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *NoStateMetaData) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { + return true + } + + return false +} + +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *NoStateMetaData) GetEtag() *string { + if o == nil { + return nil + } + + return o.Etag + +} + +// GetEtagOk returns a tuple with the Etag field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NoStateMetaData) GetEtagOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Etag, true +} + +// SetEtag sets field value +func (o *NoStateMetaData) SetEtag(v string) { + + o.Etag = &v + +} + +// HasEtag returns a boolean if a field has been set. +func (o *NoStateMetaData) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -256,7 +211,7 @@ func (o *NoStateMetaData) HasLastModifiedDate() bool { } // GetLastModifiedBy returns the LastModifiedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetLastModifiedBy() *string { if o == nil { return nil @@ -294,7 +249,7 @@ func (o *NoStateMetaData) HasLastModifiedBy() bool { } // GetLastModifiedByUserId returns the LastModifiedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetLastModifiedByUserId() *string { if o == nil { return nil @@ -331,29 +286,81 @@ func (o *NoStateMetaData) HasLastModifiedByUserId() bool { return false } -func (o NoStateMetaData) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag +// GetLastModifiedDate returns the LastModifiedDate field value +// If the value is explicit nil, nil is returned +func (o *NoStateMetaData) GetLastModifiedDate() *time.Time { + if o == nil { + return nil } - if o.CreatedDate != nil { - toSerialize["createdDate"] = o.CreatedDate + + if o.LastModifiedDate == nil { + return nil + } + return &o.LastModifiedDate.Time + +} + +// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NoStateMetaData) GetLastModifiedDateOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + + if o.LastModifiedDate == nil { + return nil, false + } + return &o.LastModifiedDate.Time, true + +} + +// SetLastModifiedDate sets field value +func (o *NoStateMetaData) SetLastModifiedDate(v time.Time) { + + o.LastModifiedDate = &IonosTime{v} + +} + +// HasLastModifiedDate returns a boolean if a field has been set. +func (o *NoStateMetaData) HasLastModifiedDate() bool { + if o != nil && o.LastModifiedDate != nil { + return true } + + return false +} + +func (o NoStateMetaData) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} if o.CreatedBy != nil { toSerialize["createdBy"] = o.CreatedBy } + if o.CreatedByUserId != nil { toSerialize["createdByUserId"] = o.CreatedByUserId } - if o.LastModifiedDate != nil { - toSerialize["lastModifiedDate"] = o.LastModifiedDate + + if o.CreatedDate != nil { + toSerialize["createdDate"] = o.CreatedDate + } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag } + if o.LastModifiedBy != nil { toSerialize["lastModifiedBy"] = o.LastModifiedBy } + if o.LastModifiedByUserId != nil { toSerialize["lastModifiedByUserId"] = o.LastModifiedByUserId } + + if o.LastModifiedDate != nil { + toSerialize["lastModifiedDate"] = o.LastModifiedDate + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go index fa3c76dee..5b8bef304 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go @@ -16,12 +16,12 @@ import ( // PaginationLinks struct for PaginationLinks type PaginationLinks struct { + // URL (with offset and limit parameters) of the next page; only present if offset + limit is less than the total number of elements. + Next *string `json:"next,omitempty"` // URL (with offset and limit parameters) of the previous page; only present if offset is greater than 0. Prev *string `json:"prev,omitempty"` // URL (with offset and limit parameters) of the current page. Self *string `json:"self,omitempty"` - // URL (with offset and limit parameters) of the next page; only present if offset + limit is less than the total number of elements. - Next *string `json:"next,omitempty"` } // NewPaginationLinks instantiates a new PaginationLinks object @@ -42,114 +42,114 @@ func NewPaginationLinksWithDefaults() *PaginationLinks { return &this } -// GetPrev returns the Prev field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PaginationLinks) GetPrev() *string { +// GetNext returns the Next field value +// If the value is explicit nil, nil is returned +func (o *PaginationLinks) GetNext() *string { if o == nil { return nil } - return o.Prev + return o.Next } -// GetPrevOk returns a tuple with the Prev field value +// GetNextOk returns a tuple with the Next field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PaginationLinks) GetPrevOk() (*string, bool) { +func (o *PaginationLinks) GetNextOk() (*string, bool) { if o == nil { return nil, false } - return o.Prev, true + return o.Next, true } -// SetPrev sets field value -func (o *PaginationLinks) SetPrev(v string) { +// SetNext sets field value +func (o *PaginationLinks) SetNext(v string) { - o.Prev = &v + o.Next = &v } -// HasPrev returns a boolean if a field has been set. -func (o *PaginationLinks) HasPrev() bool { - if o != nil && o.Prev != nil { +// HasNext returns a boolean if a field has been set. +func (o *PaginationLinks) HasNext() bool { + if o != nil && o.Next != nil { return true } return false } -// GetSelf returns the Self field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PaginationLinks) GetSelf() *string { +// GetPrev returns the Prev field value +// If the value is explicit nil, nil is returned +func (o *PaginationLinks) GetPrev() *string { if o == nil { return nil } - return o.Self + return o.Prev } -// GetSelfOk returns a tuple with the Self field value +// GetPrevOk returns a tuple with the Prev field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PaginationLinks) GetSelfOk() (*string, bool) { +func (o *PaginationLinks) GetPrevOk() (*string, bool) { if o == nil { return nil, false } - return o.Self, true + return o.Prev, true } -// SetSelf sets field value -func (o *PaginationLinks) SetSelf(v string) { +// SetPrev sets field value +func (o *PaginationLinks) SetPrev(v string) { - o.Self = &v + o.Prev = &v } -// HasSelf returns a boolean if a field has been set. -func (o *PaginationLinks) HasSelf() bool { - if o != nil && o.Self != nil { +// HasPrev returns a boolean if a field has been set. +func (o *PaginationLinks) HasPrev() bool { + if o != nil && o.Prev != nil { return true } return false } -// GetNext returns the Next field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PaginationLinks) GetNext() *string { +// GetSelf returns the Self field value +// If the value is explicit nil, nil is returned +func (o *PaginationLinks) GetSelf() *string { if o == nil { return nil } - return o.Next + return o.Self } -// GetNextOk returns a tuple with the Next field value +// GetSelfOk returns a tuple with the Self field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PaginationLinks) GetNextOk() (*string, bool) { +func (o *PaginationLinks) GetSelfOk() (*string, bool) { if o == nil { return nil, false } - return o.Next, true + return o.Self, true } -// SetNext sets field value -func (o *PaginationLinks) SetNext(v string) { +// SetSelf sets field value +func (o *PaginationLinks) SetSelf(v string) { - o.Next = &v + o.Self = &v } -// HasNext returns a boolean if a field has been set. -func (o *PaginationLinks) HasNext() bool { - if o != nil && o.Next != nil { +// HasSelf returns a boolean if a field has been set. +func (o *PaginationLinks) HasSelf() bool { + if o != nil && o.Self != nil { return true } @@ -158,15 +158,18 @@ func (o *PaginationLinks) HasNext() bool { func (o PaginationLinks) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Next != nil { + toSerialize["next"] = o.Next + } + if o.Prev != nil { toSerialize["prev"] = o.Prev } + if o.Self != nil { toSerialize["self"] = o.Self } - if o.Next != nil { - toSerialize["next"] = o.Next - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go index db7c562be..582ff98a9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go @@ -16,11 +16,11 @@ import ( // Peer struct for Peer type Peer struct { - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` DatacenterId *string `json:"datacenterId,omitempty"` DatacenterName *string `json:"datacenterName,omitempty"` + Id *string `json:"id,omitempty"` Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` } // NewPeer instantiates a new Peer object @@ -41,190 +41,190 @@ func NewPeerWithDefaults() *Peer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetId() *string { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetDatacenterId() *string { if o == nil { return nil } - return o.Id + return o.DatacenterId } -// GetIdOk returns a tuple with the Id field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetIdOk() (*string, bool) { +func (o *Peer) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.DatacenterId, true } -// SetId sets field value -func (o *Peer) SetId(v string) { +// SetDatacenterId sets field value +func (o *Peer) SetDatacenterId(v string) { - o.Id = &v + o.DatacenterId = &v } -// HasId returns a boolean if a field has been set. -func (o *Peer) HasId() bool { - if o != nil && o.Id != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *Peer) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetName() *string { +// GetDatacenterName returns the DatacenterName field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetDatacenterName() *string { if o == nil { return nil } - return o.Name + return o.DatacenterName } -// GetNameOk returns a tuple with the Name field value +// GetDatacenterNameOk returns a tuple with the DatacenterName field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetNameOk() (*string, bool) { +func (o *Peer) GetDatacenterNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.DatacenterName, true } -// SetName sets field value -func (o *Peer) SetName(v string) { +// SetDatacenterName sets field value +func (o *Peer) SetDatacenterName(v string) { - o.Name = &v + o.DatacenterName = &v } -// HasName returns a boolean if a field has been set. -func (o *Peer) HasName() bool { - if o != nil && o.Name != nil { +// HasDatacenterName returns a boolean if a field has been set. +func (o *Peer) HasDatacenterName() bool { + if o != nil && o.DatacenterName != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetDatacenterId() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetId() *string { if o == nil { return nil } - return o.DatacenterId + return o.Id } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetDatacenterIdOk() (*string, bool) { +func (o *Peer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.Id, true } -// SetDatacenterId sets field value -func (o *Peer) SetDatacenterId(v string) { +// SetId sets field value +func (o *Peer) SetId(v string) { - o.DatacenterId = &v + o.Id = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *Peer) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasId returns a boolean if a field has been set. +func (o *Peer) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetDatacenterName returns the DatacenterName field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetDatacenterName() *string { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetLocation() *string { if o == nil { return nil } - return o.DatacenterName + return o.Location } -// GetDatacenterNameOk returns a tuple with the DatacenterName field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetDatacenterNameOk() (*string, bool) { +func (o *Peer) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterName, true + return o.Location, true } -// SetDatacenterName sets field value -func (o *Peer) SetDatacenterName(v string) { +// SetLocation sets field value +func (o *Peer) SetLocation(v string) { - o.DatacenterName = &v + o.Location = &v } -// HasDatacenterName returns a boolean if a field has been set. -func (o *Peer) HasDatacenterName() bool { - if o != nil && o.DatacenterName != nil { +// HasLocation returns a boolean if a field has been set. +func (o *Peer) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetLocation() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetName() *string { if o == nil { return nil } - return o.Location + return o.Name } -// GetLocationOk returns a tuple with the Location field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetLocationOk() (*string, bool) { +func (o *Peer) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Name, true } -// SetLocation sets field value -func (o *Peer) SetLocation(v string) { +// SetName sets field value +func (o *Peer) SetName(v string) { - o.Location = &v + o.Name = &v } -// HasLocation returns a boolean if a field has been set. -func (o *Peer) HasLocation() bool { - if o != nil && o.Location != nil { +// HasName returns a boolean if a field has been set. +func (o *Peer) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -233,21 +233,26 @@ func (o *Peer) HasLocation() bool { func (o Peer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.DatacenterId != nil { toSerialize["datacenterId"] = o.DatacenterId } + if o.DatacenterName != nil { toSerialize["datacenterName"] = o.DatacenterName } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Location != nil { toSerialize["location"] = o.Location } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go index f0aa7eb8f..1a417e85c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go @@ -16,14 +16,14 @@ import ( // PrivateCrossConnect struct for PrivateCrossConnect type PrivateCrossConnect struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *PrivateCrossConnectProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewPrivateCrossConnect instantiates a new PrivateCrossConnect object @@ -46,190 +46,190 @@ func NewPrivateCrossConnectWithDefaults() *PrivateCrossConnect { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnect) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetIdOk() (*string, bool) { +func (o *PrivateCrossConnect) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *PrivateCrossConnect) SetId(v string) { +// SetHref sets field value +func (o *PrivateCrossConnect) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *PrivateCrossConnect) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetTypeOk() (*Type, bool) { +func (o *PrivateCrossConnect) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *PrivateCrossConnect) SetType(v Type) { +// SetId sets field value +func (o *PrivateCrossConnect) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnect) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetHrefOk() (*string, bool) { +func (o *PrivateCrossConnect) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *PrivateCrossConnect) SetHref(v string) { +// SetMetadata sets field value +func (o *PrivateCrossConnect) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *PrivateCrossConnect) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetProperties() *PrivateCrossConnectProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *PrivateCrossConnect) GetPropertiesOk() (*PrivateCrossConnectProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *PrivateCrossConnect) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *PrivateCrossConnect) SetProperties(v PrivateCrossConnectProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for PrivateCrossConnectProperties will be returned -func (o *PrivateCrossConnect) GetProperties() *PrivateCrossConnectProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetPropertiesOk() (*PrivateCrossConnectProperties, bool) { +func (o *PrivateCrossConnect) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *PrivateCrossConnect) SetProperties(v PrivateCrossConnectProperties) { +// SetType sets field value +func (o *PrivateCrossConnect) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *PrivateCrossConnect) HasProperties() bool { func (o PrivateCrossConnect) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go index a92dc8098..864e5ada1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go @@ -16,14 +16,14 @@ import ( // PrivateCrossConnectProperties struct for PrivateCrossConnectProperties type PrivateCrossConnectProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` + // Read-Only attribute. Lists data centers that can be joined to this private Cross-Connect. + ConnectableDatacenters *[]ConnectableDatacenter `json:"connectableDatacenters,omitempty"` // Human-readable description. Description *string `json:"description,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // Read-Only attribute. Lists LAN's joined to this private Cross-Connect. Peers *[]Peer `json:"peers,omitempty"` - // Read-Only attribute. Lists data centers that can be joined to this private Cross-Connect. - ConnectableDatacenters *[]ConnectableDatacenter `json:"connectableDatacenters,omitempty"` } // NewPrivateCrossConnectProperties instantiates a new PrivateCrossConnectProperties object @@ -44,38 +44,38 @@ func NewPrivateCrossConnectPropertiesWithDefaults() *PrivateCrossConnectProperti return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnectProperties) GetName() *string { +// GetConnectableDatacenters returns the ConnectableDatacenters field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnectProperties) GetConnectableDatacenters() *[]ConnectableDatacenter { if o == nil { return nil } - return o.Name + return o.ConnectableDatacenters } -// GetNameOk returns a tuple with the Name field value +// GetConnectableDatacentersOk returns a tuple with the ConnectableDatacenters field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnectProperties) GetNameOk() (*string, bool) { +func (o *PrivateCrossConnectProperties) GetConnectableDatacentersOk() (*[]ConnectableDatacenter, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ConnectableDatacenters, true } -// SetName sets field value -func (o *PrivateCrossConnectProperties) SetName(v string) { +// SetConnectableDatacenters sets field value +func (o *PrivateCrossConnectProperties) SetConnectableDatacenters(v []ConnectableDatacenter) { - o.Name = &v + o.ConnectableDatacenters = &v } -// HasName returns a boolean if a field has been set. -func (o *PrivateCrossConnectProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasConnectableDatacenters returns a boolean if a field has been set. +func (o *PrivateCrossConnectProperties) HasConnectableDatacenters() bool { + if o != nil && o.ConnectableDatacenters != nil { return true } @@ -83,7 +83,7 @@ func (o *PrivateCrossConnectProperties) HasName() bool { } // GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *PrivateCrossConnectProperties) GetDescription() *string { if o == nil { return nil @@ -120,76 +120,76 @@ func (o *PrivateCrossConnectProperties) HasDescription() bool { return false } -// GetPeers returns the Peers field value -// If the value is explicit nil, the zero value for []Peer will be returned -func (o *PrivateCrossConnectProperties) GetPeers() *[]Peer { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnectProperties) GetName() *string { if o == nil { return nil } - return o.Peers + return o.Name } -// GetPeersOk returns a tuple with the Peers field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnectProperties) GetPeersOk() (*[]Peer, bool) { +func (o *PrivateCrossConnectProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Peers, true + return o.Name, true } -// SetPeers sets field value -func (o *PrivateCrossConnectProperties) SetPeers(v []Peer) { +// SetName sets field value +func (o *PrivateCrossConnectProperties) SetName(v string) { - o.Peers = &v + o.Name = &v } -// HasPeers returns a boolean if a field has been set. -func (o *PrivateCrossConnectProperties) HasPeers() bool { - if o != nil && o.Peers != nil { +// HasName returns a boolean if a field has been set. +func (o *PrivateCrossConnectProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetConnectableDatacenters returns the ConnectableDatacenters field value -// If the value is explicit nil, the zero value for []ConnectableDatacenter will be returned -func (o *PrivateCrossConnectProperties) GetConnectableDatacenters() *[]ConnectableDatacenter { +// GetPeers returns the Peers field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnectProperties) GetPeers() *[]Peer { if o == nil { return nil } - return o.ConnectableDatacenters + return o.Peers } -// GetConnectableDatacentersOk returns a tuple with the ConnectableDatacenters field value +// GetPeersOk returns a tuple with the Peers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnectProperties) GetConnectableDatacentersOk() (*[]ConnectableDatacenter, bool) { +func (o *PrivateCrossConnectProperties) GetPeersOk() (*[]Peer, bool) { if o == nil { return nil, false } - return o.ConnectableDatacenters, true + return o.Peers, true } -// SetConnectableDatacenters sets field value -func (o *PrivateCrossConnectProperties) SetConnectableDatacenters(v []ConnectableDatacenter) { +// SetPeers sets field value +func (o *PrivateCrossConnectProperties) SetPeers(v []Peer) { - o.ConnectableDatacenters = &v + o.Peers = &v } -// HasConnectableDatacenters returns a boolean if a field has been set. -func (o *PrivateCrossConnectProperties) HasConnectableDatacenters() bool { - if o != nil && o.ConnectableDatacenters != nil { +// HasPeers returns a boolean if a field has been set. +func (o *PrivateCrossConnectProperties) HasPeers() bool { + if o != nil && o.Peers != nil { return true } @@ -198,18 +198,22 @@ func (o *PrivateCrossConnectProperties) HasConnectableDatacenters() bool { func (o PrivateCrossConnectProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ConnectableDatacenters != nil { + toSerialize["connectableDatacenters"] = o.ConnectableDatacenters } + if o.Description != nil { toSerialize["description"] = o.Description } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + if o.Peers != nil { toSerialize["peers"] = o.Peers } - if o.ConnectableDatacenters != nil { - toSerialize["connectableDatacenters"] = o.ConnectableDatacenters - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go index 7112f9a35..3c82ad39f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go @@ -16,14 +16,14 @@ import ( // PrivateCrossConnects struct for PrivateCrossConnects type PrivateCrossConnects struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]PrivateCrossConnect `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewPrivateCrossConnects instantiates a new PrivateCrossConnects object @@ -44,152 +44,152 @@ func NewPrivateCrossConnectsWithDefaults() *PrivateCrossConnects { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnects) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetIdOk() (*string, bool) { +func (o *PrivateCrossConnects) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *PrivateCrossConnects) SetId(v string) { +// SetHref sets field value +func (o *PrivateCrossConnects) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *PrivateCrossConnects) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetTypeOk() (*Type, bool) { +func (o *PrivateCrossConnects) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *PrivateCrossConnects) SetType(v Type) { +// SetId sets field value +func (o *PrivateCrossConnects) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnects) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetItems() *[]PrivateCrossConnect { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetHrefOk() (*string, bool) { +func (o *PrivateCrossConnects) GetItemsOk() (*[]PrivateCrossConnect, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *PrivateCrossConnects) SetHref(v string) { +// SetItems sets field value +func (o *PrivateCrossConnects) SetItems(v []PrivateCrossConnect) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []PrivateCrossConnect will be returned -func (o *PrivateCrossConnects) GetItems() *[]PrivateCrossConnect { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetItemsOk() (*[]PrivateCrossConnect, bool) { +func (o *PrivateCrossConnects) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *PrivateCrossConnects) SetItems(v []PrivateCrossConnect) { +// SetType sets field value +func (o *PrivateCrossConnects) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *PrivateCrossConnects) HasItems() bool { func (o PrivateCrossConnects) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go index 4088c7a8c..74f96ce38 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go @@ -39,7 +39,7 @@ func NewRemoteConsoleUrlWithDefaults() *RemoteConsoleUrl { } // GetUrl returns the Url field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RemoteConsoleUrl) GetUrl() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o RemoteConsoleUrl) MarshalJSON() ([]byte, error) { if o.Url != nil { toSerialize["url"] = o.Url } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go index 5ac4f4851..adc351ff9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go @@ -16,14 +16,14 @@ import ( // Request struct for Request type Request struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *RequestMetadata `json:"metadata,omitempty"` Properties *RequestProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewRequest instantiates a new Request object @@ -46,190 +46,190 @@ func NewRequestWithDefaults() *Request { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Request) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Request) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetIdOk() (*string, bool) { +func (o *Request) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Request) SetId(v string) { +// SetHref sets field value +func (o *Request) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Request) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Request) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Request) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Request) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetTypeOk() (*Type, bool) { +func (o *Request) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Request) SetType(v Type) { +// SetId sets field value +func (o *Request) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Request) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Request) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Request) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Request) GetMetadata() *RequestMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetHrefOk() (*string, bool) { +func (o *Request) GetMetadataOk() (*RequestMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Request) SetHref(v string) { +// SetMetadata sets field value +func (o *Request) SetMetadata(v RequestMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Request) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Request) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for RequestMetadata will be returned -func (o *Request) GetMetadata() *RequestMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Request) GetProperties() *RequestProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetMetadataOk() (*RequestMetadata, bool) { +func (o *Request) GetPropertiesOk() (*RequestProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Request) SetMetadata(v RequestMetadata) { +// SetProperties sets field value +func (o *Request) SetProperties(v RequestProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Request) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Request) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for RequestProperties will be returned -func (o *Request) GetProperties() *RequestProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Request) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetPropertiesOk() (*RequestProperties, bool) { +func (o *Request) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Request) SetProperties(v RequestProperties) { +// SetType sets field value +func (o *Request) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Request) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Request) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Request) HasProperties() bool { func (o Request) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go index 3ea319b31..1b634615e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go @@ -17,10 +17,10 @@ import ( // RequestMetadata struct for RequestMetadata type RequestMetadata struct { - // The last time the resource was created. - CreatedDate *IonosTime // The user who created the resource. CreatedBy *string `json:"createdBy,omitempty"` + // The last time the resource was created. + CreatedDate *IonosTime // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. Etag *string `json:"etag,omitempty"` RequestStatus *RequestStatus `json:"requestStatus,omitempty"` @@ -44,83 +44,83 @@ func NewRequestMetadataWithDefaults() *RequestMetadata { return &this } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *RequestMetadata) GetCreatedDate() *time.Time { +// GetCreatedBy returns the CreatedBy field value +// If the value is explicit nil, nil is returned +func (o *RequestMetadata) GetCreatedBy() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.CreatedBy } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetCreatedByOk returns a tuple with the CreatedBy field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *RequestMetadata) GetCreatedByOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.CreatedBy, true } -// SetCreatedDate sets field value -func (o *RequestMetadata) SetCreatedDate(v time.Time) { +// SetCreatedBy sets field value +func (o *RequestMetadata) SetCreatedBy(v string) { - o.CreatedDate = &IonosTime{v} + o.CreatedBy = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *RequestMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasCreatedBy returns a boolean if a field has been set. +func (o *RequestMetadata) HasCreatedBy() bool { + if o != nil && o.CreatedBy != nil { return true } return false } -// GetCreatedBy returns the CreatedBy field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestMetadata) GetCreatedBy() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *RequestMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.CreatedBy + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetCreatedByOk returns a tuple with the CreatedBy field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestMetadata) GetCreatedByOk() (*string, bool) { +func (o *RequestMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.CreatedBy, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetCreatedBy sets field value -func (o *RequestMetadata) SetCreatedBy(v string) { +// SetCreatedDate sets field value +func (o *RequestMetadata) SetCreatedDate(v time.Time) { - o.CreatedBy = &v + o.CreatedDate = &IonosTime{v} } -// HasCreatedBy returns a boolean if a field has been set. -func (o *RequestMetadata) HasCreatedBy() bool { - if o != nil && o.CreatedBy != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *RequestMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } @@ -128,7 +128,7 @@ func (o *RequestMetadata) HasCreatedBy() bool { } // GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RequestMetadata) GetEtag() *string { if o == nil { return nil @@ -166,7 +166,7 @@ func (o *RequestMetadata) HasEtag() bool { } // GetRequestStatus returns the RequestStatus field value -// If the value is explicit nil, the zero value for RequestStatus will be returned +// If the value is explicit nil, nil is returned func (o *RequestMetadata) GetRequestStatus() *RequestStatus { if o == nil { return nil @@ -205,18 +205,22 @@ func (o *RequestMetadata) HasRequestStatus() bool { func (o RequestMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.CreatedDate != nil { - toSerialize["createdDate"] = o.CreatedDate - } if o.CreatedBy != nil { toSerialize["createdBy"] = o.CreatedBy } + + if o.CreatedDate != nil { + toSerialize["createdDate"] = o.CreatedDate + } + if o.Etag != nil { toSerialize["etag"] = o.Etag } + if o.RequestStatus != nil { toSerialize["requestStatus"] = o.RequestStatus } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go index 94d040939..e43b39d98 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go @@ -16,9 +16,9 @@ import ( // RequestProperties struct for RequestProperties type RequestProperties struct { - Method *string `json:"method,omitempty"` - Headers *map[string]string `json:"headers,omitempty"` Body *string `json:"body,omitempty"` + Headers *map[string]string `json:"headers,omitempty"` + Method *string `json:"method,omitempty"` Url *string `json:"url,omitempty"` } @@ -40,38 +40,38 @@ func NewRequestPropertiesWithDefaults() *RequestProperties { return &this } -// GetMethod returns the Method field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestProperties) GetMethod() *string { +// GetBody returns the Body field value +// If the value is explicit nil, nil is returned +func (o *RequestProperties) GetBody() *string { if o == nil { return nil } - return o.Method + return o.Body } -// GetMethodOk returns a tuple with the Method field value +// GetBodyOk returns a tuple with the Body field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestProperties) GetMethodOk() (*string, bool) { +func (o *RequestProperties) GetBodyOk() (*string, bool) { if o == nil { return nil, false } - return o.Method, true + return o.Body, true } -// SetMethod sets field value -func (o *RequestProperties) SetMethod(v string) { +// SetBody sets field value +func (o *RequestProperties) SetBody(v string) { - o.Method = &v + o.Body = &v } -// HasMethod returns a boolean if a field has been set. -func (o *RequestProperties) HasMethod() bool { - if o != nil && o.Method != nil { +// HasBody returns a boolean if a field has been set. +func (o *RequestProperties) HasBody() bool { + if o != nil && o.Body != nil { return true } @@ -79,7 +79,7 @@ func (o *RequestProperties) HasMethod() bool { } // GetHeaders returns the Headers field value -// If the value is explicit nil, the zero value for map[string]string will be returned +// If the value is explicit nil, nil is returned func (o *RequestProperties) GetHeaders() *map[string]string { if o == nil { return nil @@ -116,38 +116,38 @@ func (o *RequestProperties) HasHeaders() bool { return false } -// GetBody returns the Body field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestProperties) GetBody() *string { +// GetMethod returns the Method field value +// If the value is explicit nil, nil is returned +func (o *RequestProperties) GetMethod() *string { if o == nil { return nil } - return o.Body + return o.Method } -// GetBodyOk returns a tuple with the Body field value +// GetMethodOk returns a tuple with the Method field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestProperties) GetBodyOk() (*string, bool) { +func (o *RequestProperties) GetMethodOk() (*string, bool) { if o == nil { return nil, false } - return o.Body, true + return o.Method, true } -// SetBody sets field value -func (o *RequestProperties) SetBody(v string) { +// SetMethod sets field value +func (o *RequestProperties) SetMethod(v string) { - o.Body = &v + o.Method = &v } -// HasBody returns a boolean if a field has been set. -func (o *RequestProperties) HasBody() bool { - if o != nil && o.Body != nil { +// HasMethod returns a boolean if a field has been set. +func (o *RequestProperties) HasMethod() bool { + if o != nil && o.Method != nil { return true } @@ -155,7 +155,7 @@ func (o *RequestProperties) HasBody() bool { } // GetUrl returns the Url field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RequestProperties) GetUrl() *string { if o == nil { return nil @@ -194,18 +194,22 @@ func (o *RequestProperties) HasUrl() bool { func (o RequestProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Method != nil { - toSerialize["method"] = o.Method + if o.Body != nil { + toSerialize["body"] = o.Body } + if o.Headers != nil { toSerialize["headers"] = o.Headers } - if o.Body != nil { - toSerialize["body"] = o.Body + + if o.Method != nil { + toSerialize["method"] = o.Method } + if o.Url != nil { toSerialize["url"] = o.Url } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go index e772df8e6..f4ca3ceef 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go @@ -16,13 +16,13 @@ import ( // RequestStatus struct for RequestStatus type RequestStatus struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Metadata *RequestStatusMetadata `json:"metadata,omitempty"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Metadata *RequestStatusMetadata `json:"metadata,omitempty"` } // NewRequestStatus instantiates a new RequestStatus object @@ -43,152 +43,152 @@ func NewRequestStatusWithDefaults() *RequestStatus { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatus) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetIdOk() (*string, bool) { +func (o *RequestStatus) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *RequestStatus) SetId(v string) { +// SetHref sets field value +func (o *RequestStatus) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *RequestStatus) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *RequestStatus) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *RequestStatus) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetTypeOk() (*Type, bool) { +func (o *RequestStatus) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *RequestStatus) SetType(v Type) { +// SetId sets field value +func (o *RequestStatus) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *RequestStatus) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *RequestStatus) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatus) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetMetadata() *RequestStatusMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetHrefOk() (*string, bool) { +func (o *RequestStatus) GetMetadataOk() (*RequestStatusMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *RequestStatus) SetHref(v string) { +// SetMetadata sets field value +func (o *RequestStatus) SetMetadata(v RequestStatusMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *RequestStatus) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *RequestStatus) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for RequestStatusMetadata will be returned -func (o *RequestStatus) GetMetadata() *RequestStatusMetadata { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetType() *Type { if o == nil { return nil } - return o.Metadata + return o.Type } -// GetMetadataOk returns a tuple with the Metadata field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetMetadataOk() (*RequestStatusMetadata, bool) { +func (o *RequestStatus) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Type, true } -// SetMetadata sets field value -func (o *RequestStatus) SetMetadata(v RequestStatusMetadata) { +// SetType sets field value +func (o *RequestStatus) SetType(v Type) { - o.Metadata = &v + o.Type = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *RequestStatus) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasType returns a boolean if a field has been set. +func (o *RequestStatus) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -197,18 +197,22 @@ func (o *RequestStatus) HasMetadata() bool { func (o RequestStatus) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go index ef97dbedb..29b9967c8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go @@ -16,10 +16,10 @@ import ( // RequestStatusMetadata struct for RequestStatusMetadata type RequestStatusMetadata struct { - Status *string `json:"status,omitempty"` - Message *string `json:"message,omitempty"` // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. Etag *string `json:"etag,omitempty"` + Message *string `json:"message,omitempty"` + Status *string `json:"status,omitempty"` Targets *[]RequestTarget `json:"targets,omitempty"` } @@ -41,38 +41,38 @@ func NewRequestStatusMetadataWithDefaults() *RequestStatusMetadata { return &this } -// GetStatus returns the Status field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatusMetadata) GetStatus() *string { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *RequestStatusMetadata) GetEtag() *string { if o == nil { return nil } - return o.Status + return o.Etag } -// GetStatusOk returns a tuple with the Status field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatusMetadata) GetStatusOk() (*string, bool) { +func (o *RequestStatusMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - return o.Status, true + return o.Etag, true } -// SetStatus sets field value -func (o *RequestStatusMetadata) SetStatus(v string) { +// SetEtag sets field value +func (o *RequestStatusMetadata) SetEtag(v string) { - o.Status = &v + o.Etag = &v } -// HasStatus returns a boolean if a field has been set. -func (o *RequestStatusMetadata) HasStatus() bool { - if o != nil && o.Status != nil { +// HasEtag returns a boolean if a field has been set. +func (o *RequestStatusMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -80,7 +80,7 @@ func (o *RequestStatusMetadata) HasStatus() bool { } // GetMessage returns the Message field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RequestStatusMetadata) GetMessage() *string { if o == nil { return nil @@ -117,38 +117,38 @@ func (o *RequestStatusMetadata) HasMessage() bool { return false } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatusMetadata) GetEtag() *string { +// GetStatus returns the Status field value +// If the value is explicit nil, nil is returned +func (o *RequestStatusMetadata) GetStatus() *string { if o == nil { return nil } - return o.Etag + return o.Status } -// GetEtagOk returns a tuple with the Etag field value +// GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatusMetadata) GetEtagOk() (*string, bool) { +func (o *RequestStatusMetadata) GetStatusOk() (*string, bool) { if o == nil { return nil, false } - return o.Etag, true + return o.Status, true } -// SetEtag sets field value -func (o *RequestStatusMetadata) SetEtag(v string) { +// SetStatus sets field value +func (o *RequestStatusMetadata) SetStatus(v string) { - o.Etag = &v + o.Status = &v } -// HasEtag returns a boolean if a field has been set. -func (o *RequestStatusMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasStatus returns a boolean if a field has been set. +func (o *RequestStatusMetadata) HasStatus() bool { + if o != nil && o.Status != nil { return true } @@ -156,7 +156,7 @@ func (o *RequestStatusMetadata) HasEtag() bool { } // GetTargets returns the Targets field value -// If the value is explicit nil, the zero value for []RequestTarget will be returned +// If the value is explicit nil, nil is returned func (o *RequestStatusMetadata) GetTargets() *[]RequestTarget { if o == nil { return nil @@ -195,18 +195,22 @@ func (o *RequestStatusMetadata) HasTargets() bool { func (o RequestStatusMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Status != nil { - toSerialize["status"] = o.Status + if o.Etag != nil { + toSerialize["etag"] = o.Etag } + if o.Message != nil { toSerialize["message"] = o.Message } - if o.Etag != nil { - toSerialize["etag"] = o.Etag + + if o.Status != nil { + toSerialize["status"] = o.Status } + if o.Targets != nil { toSerialize["targets"] = o.Targets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go index 590a5dfae..dc56f80ab 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go @@ -16,8 +16,8 @@ import ( // RequestTarget struct for RequestTarget type RequestTarget struct { - Target *ResourceReference `json:"target,omitempty"` Status *string `json:"status,omitempty"` + Target *ResourceReference `json:"target,omitempty"` } // NewRequestTarget instantiates a new RequestTarget object @@ -38,76 +38,76 @@ func NewRequestTargetWithDefaults() *RequestTarget { return &this } -// GetTarget returns the Target field value -// If the value is explicit nil, the zero value for ResourceReference will be returned -func (o *RequestTarget) GetTarget() *ResourceReference { +// GetStatus returns the Status field value +// If the value is explicit nil, nil is returned +func (o *RequestTarget) GetStatus() *string { if o == nil { return nil } - return o.Target + return o.Status } -// GetTargetOk returns a tuple with the Target field value +// GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestTarget) GetTargetOk() (*ResourceReference, bool) { +func (o *RequestTarget) GetStatusOk() (*string, bool) { if o == nil { return nil, false } - return o.Target, true + return o.Status, true } -// SetTarget sets field value -func (o *RequestTarget) SetTarget(v ResourceReference) { +// SetStatus sets field value +func (o *RequestTarget) SetStatus(v string) { - o.Target = &v + o.Status = &v } -// HasTarget returns a boolean if a field has been set. -func (o *RequestTarget) HasTarget() bool { - if o != nil && o.Target != nil { +// HasStatus returns a boolean if a field has been set. +func (o *RequestTarget) HasStatus() bool { + if o != nil && o.Status != nil { return true } return false } -// GetStatus returns the Status field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestTarget) GetStatus() *string { +// GetTarget returns the Target field value +// If the value is explicit nil, nil is returned +func (o *RequestTarget) GetTarget() *ResourceReference { if o == nil { return nil } - return o.Status + return o.Target } -// GetStatusOk returns a tuple with the Status field value +// GetTargetOk returns a tuple with the Target field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestTarget) GetStatusOk() (*string, bool) { +func (o *RequestTarget) GetTargetOk() (*ResourceReference, bool) { if o == nil { return nil, false } - return o.Status, true + return o.Target, true } -// SetStatus sets field value -func (o *RequestTarget) SetStatus(v string) { +// SetTarget sets field value +func (o *RequestTarget) SetTarget(v ResourceReference) { - o.Status = &v + o.Target = &v } -// HasStatus returns a boolean if a field has been set. -func (o *RequestTarget) HasStatus() bool { - if o != nil && o.Status != nil { +// HasTarget returns a boolean if a field has been set. +func (o *RequestTarget) HasTarget() bool { + if o != nil && o.Target != nil { return true } @@ -116,12 +116,14 @@ func (o *RequestTarget) HasStatus() bool { func (o RequestTarget) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Target != nil { - toSerialize["target"] = o.Target - } if o.Status != nil { toSerialize["status"] = o.Status } + + if o.Target != nil { + toSerialize["target"] = o.Target + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go index 3d67bdc81..0bf44ade8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go @@ -16,31 +16,31 @@ import ( // Requests struct for Requests type Requests struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Request `json:"items,omitempty"` + // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). + Limit *float32 `json:"limit"` // The offset, specified in the request (if not is specified, 0 is used by default). Offset *float32 `json:"offset"` - // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). - Limit *float32 `json:"limit"` - Links *PaginationLinks `json:"_links"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewRequests instantiates a new Requests object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewRequests(offset float32, limit float32, links PaginationLinks) *Requests { +func NewRequests(links PaginationLinks, limit float32, offset float32) *Requests { this := Requests{} - this.Offset = &offset - this.Limit = &limit this.Links = &links + this.Limit = &limit + this.Offset = &offset return &this } @@ -53,114 +53,114 @@ func NewRequestsWithDefaults() *Requests { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Requests) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetIdOk() (*string, bool) { +func (o *Requests) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Requests) SetId(v string) { +// SetLinks sets field value +func (o *Requests) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Requests) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Requests) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Requests) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetTypeOk() (*Type, bool) { +func (o *Requests) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Requests) SetType(v Type) { +// SetHref sets field value +func (o *Requests) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Requests) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Requests) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Requests) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetHrefOk() (*string, bool) { +func (o *Requests) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Requests) SetHref(v string) { +// SetId sets field value +func (o *Requests) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Requests) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Requests) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -168,7 +168,7 @@ func (o *Requests) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Request will be returned +// If the value is explicit nil, nil is returned func (o *Requests) GetItems() *[]Request { if o == nil { return nil @@ -205,114 +205,114 @@ func (o *Requests) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Requests) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetOffsetOk() (*float32, bool) { +func (o *Requests) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Requests) SetOffset(v float32) { +// SetLimit sets field value +func (o *Requests) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Requests) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Requests) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Requests) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetLimitOk() (*float32, bool) { +func (o *Requests) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Requests) SetLimit(v float32) { +// SetOffset sets field value +func (o *Requests) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Requests) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Requests) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Requests) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetLinksOk() (*PaginationLinks, bool) { +func (o *Requests) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Requests) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Requests) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Requests) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Requests) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -321,27 +321,34 @@ func (o *Requests) HasLinks() bool { func (o Requests) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go index 1d370ce22..82b8f739d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go @@ -16,15 +16,15 @@ import ( // Resource datacenter resource representation type Resource struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` + Entities *ResourceEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ResourceProperties `json:"properties,omitempty"` - Entities *ResourceEntities `json:"entities,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResource instantiates a new Resource object @@ -45,114 +45,114 @@ func NewResourceWithDefaults() *Resource { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resource) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetEntities() *ResourceEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetIdOk() (*string, bool) { +func (o *Resource) GetEntitiesOk() (*ResourceEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Resource) SetId(v string) { +// SetEntities sets field value +func (o *Resource) SetEntities(v ResourceEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Resource) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Resource) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Resource) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetTypeOk() (*Type, bool) { +func (o *Resource) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Resource) SetType(v Type) { +// SetHref sets field value +func (o *Resource) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Resource) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Resource) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resource) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetHrefOk() (*string, bool) { +func (o *Resource) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Resource) SetHref(v string) { +// SetId sets field value +func (o *Resource) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Resource) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Resource) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -160,7 +160,7 @@ func (o *Resource) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Resource) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -198,7 +198,7 @@ func (o *Resource) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ResourceProperties will be returned +// If the value is explicit nil, nil is returned func (o *Resource) GetProperties() *ResourceProperties { if o == nil { return nil @@ -235,38 +235,38 @@ func (o *Resource) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for ResourceEntities will be returned -func (o *Resource) GetEntities() *ResourceEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetEntitiesOk() (*ResourceEntities, bool) { +func (o *Resource) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Resource) SetEntities(v ResourceEntities) { +// SetType sets field value +func (o *Resource) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Resource) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Resource) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -275,24 +275,30 @@ func (o *Resource) HasEntities() bool { func (o Resource) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go index cc9f26acb..735ffe73b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go @@ -38,7 +38,7 @@ func NewResourceEntitiesWithDefaults() *ResourceEntities { } // GetGroups returns the Groups field value -// If the value is explicit nil, the zero value for ResourceGroups will be returned +// If the value is explicit nil, nil is returned func (o *ResourceEntities) GetGroups() *ResourceGroups { if o == nil { return nil @@ -80,6 +80,7 @@ func (o ResourceEntities) MarshalJSON() ([]byte, error) { if o.Groups != nil { toSerialize["groups"] = o.Groups } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go index ae8939261..8d0a2a1a6 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go @@ -16,14 +16,14 @@ import ( // ResourceGroups Resources assigned to this group. type ResourceGroups struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Resource `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResourceGroups instantiates a new ResourceGroups object @@ -44,152 +44,152 @@ func NewResourceGroupsWithDefaults() *ResourceGroups { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceGroups) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetIdOk() (*string, bool) { +func (o *ResourceGroups) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ResourceGroups) SetId(v string) { +// SetHref sets field value +func (o *ResourceGroups) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ResourceGroups) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ResourceGroups) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ResourceGroups) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetTypeOk() (*Type, bool) { +func (o *ResourceGroups) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ResourceGroups) SetType(v Type) { +// SetId sets field value +func (o *ResourceGroups) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ResourceGroups) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ResourceGroups) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceGroups) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetItems() *[]Resource { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetHrefOk() (*string, bool) { +func (o *ResourceGroups) GetItemsOk() (*[]Resource, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *ResourceGroups) SetHref(v string) { +// SetItems sets field value +func (o *ResourceGroups) SetItems(v []Resource) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *ResourceGroups) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *ResourceGroups) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Resource will be returned -func (o *ResourceGroups) GetItems() *[]Resource { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetItemsOk() (*[]Resource, bool) { +func (o *ResourceGroups) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *ResourceGroups) SetItems(v []Resource) { +// SetType sets field value +func (o *ResourceGroups) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *ResourceGroups) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *ResourceGroups) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *ResourceGroups) HasItems() bool { func (o ResourceGroups) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go index 8dbbe386e..ca9ee8400 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go @@ -16,81 +16,81 @@ import ( // ResourceLimits struct for ResourceLimits type ResourceLimits struct { - // The maximum number of CPU cores per server. - CoresPerServer *int32 `json:"coresPerServer"` // The maximum number of CPU cores per contract. CoresPerContract *int32 `json:"coresPerContract"` + // The maximum number of CPU cores per server. + CoresPerServer *int32 `json:"coresPerServer"` // The number of CPU cores provisioned. CoresProvisioned *int32 `json:"coresProvisioned"` - // The maximum amount of RAM (in MB) that can be provisioned for a particular server under this contract. - RamPerServer *int32 `json:"ramPerServer"` - // The maximum amount of RAM (in MB) that can be provisioned under this contract. - RamPerContract *int32 `json:"ramPerContract"` - // The amount of RAM (in MB) provisioned under this contract. - RamProvisioned *int32 `json:"ramProvisioned"` - // The maximum size (in MB) of an idividual hard disk volume. - HddLimitPerVolume *int64 `json:"hddLimitPerVolume"` + // The amount of DAS disk space (in MB) in a Cube server that is currently provisioned. + DasVolumeProvisioned *int64 `json:"dasVolumeProvisioned"` // The maximum amount of disk space (in MB) that can be provided under this contract. HddLimitPerContract *int64 `json:"hddLimitPerContract"` + // The maximum size (in MB) of an idividual hard disk volume. + HddLimitPerVolume *int64 `json:"hddLimitPerVolume"` // The amount of hard disk space (in MB) that is currently provisioned. HddVolumeProvisioned *int64 `json:"hddVolumeProvisioned"` - // The maximum size (in MB) of an individual solid state disk volume. - SsdLimitPerVolume *int64 `json:"ssdLimitPerVolume"` - // The maximum amount of solid state disk space (in MB) that can be provisioned under this contract. - SsdLimitPerContract *int64 `json:"ssdLimitPerContract"` - // The amount of solid state disk space (in MB) that is currently provisioned. - SsdVolumeProvisioned *int64 `json:"ssdVolumeProvisioned"` - // The amount of DAS disk space (in MB) in a Cube server that is currently provisioned. - DasVolumeProvisioned *int64 `json:"dasVolumeProvisioned"` - // The maximum number of static public IP addresses that can be reserved by this customer across contracts. - ReservableIps *int32 `json:"reservableIps"` - // The maximum number of static public IP addresses that can be reserved for this contract. - ReservedIpsOnContract *int32 `json:"reservedIpsOnContract"` - // The number of static public IP addresses in use. - ReservedIpsInUse *int32 `json:"reservedIpsInUse"` // The maximum number of Kubernetes clusters that can be created under this contract. K8sClusterLimitTotal *int32 `json:"k8sClusterLimitTotal"` // The amount of Kubernetes clusters that is currently provisioned. K8sClustersProvisioned *int32 `json:"k8sClustersProvisioned"` - // The NLB total limit. - NlbLimitTotal *int32 `json:"nlbLimitTotal"` - // The NLBs provisioned. - NlbProvisioned *int32 `json:"nlbProvisioned"` // The NAT Gateway total limit. NatGatewayLimitTotal *int32 `json:"natGatewayLimitTotal"` // The NAT Gateways provisioned. NatGatewayProvisioned *int32 `json:"natGatewayProvisioned"` + // The NLB total limit. + NlbLimitTotal *int32 `json:"nlbLimitTotal"` + // The NLBs provisioned. + NlbProvisioned *int32 `json:"nlbProvisioned"` + // The maximum amount of RAM (in MB) that can be provisioned under this contract. + RamPerContract *int32 `json:"ramPerContract"` + // The maximum amount of RAM (in MB) that can be provisioned for a particular server under this contract. + RamPerServer *int32 `json:"ramPerServer"` + // The amount of RAM (in MB) provisioned under this contract. + RamProvisioned *int32 `json:"ramProvisioned"` + // The maximum number of static public IP addresses that can be reserved by this customer across contracts. + ReservableIps *int32 `json:"reservableIps"` + // The number of static public IP addresses in use. + ReservedIpsInUse *int32 `json:"reservedIpsInUse"` + // The maximum number of static public IP addresses that can be reserved for this contract. + ReservedIpsOnContract *int32 `json:"reservedIpsOnContract"` + // The maximum amount of solid state disk space (in MB) that can be provisioned under this contract. + SsdLimitPerContract *int64 `json:"ssdLimitPerContract"` + // The maximum size (in MB) of an individual solid state disk volume. + SsdLimitPerVolume *int64 `json:"ssdLimitPerVolume"` + // The amount of solid state disk space (in MB) that is currently provisioned. + SsdVolumeProvisioned *int64 `json:"ssdVolumeProvisioned"` } // NewResourceLimits instantiates a new ResourceLimits object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewResourceLimits(coresPerServer int32, coresPerContract int32, coresProvisioned int32, ramPerServer int32, ramPerContract int32, ramProvisioned int32, hddLimitPerVolume int64, hddLimitPerContract int64, hddVolumeProvisioned int64, ssdLimitPerVolume int64, ssdLimitPerContract int64, ssdVolumeProvisioned int64, dasVolumeProvisioned int64, reservableIps int32, reservedIpsOnContract int32, reservedIpsInUse int32, k8sClusterLimitTotal int32, k8sClustersProvisioned int32, nlbLimitTotal int32, nlbProvisioned int32, natGatewayLimitTotal int32, natGatewayProvisioned int32) *ResourceLimits { +func NewResourceLimits(coresPerContract int32, coresPerServer int32, coresProvisioned int32, dasVolumeProvisioned int64, hddLimitPerContract int64, hddLimitPerVolume int64, hddVolumeProvisioned int64, k8sClusterLimitTotal int32, k8sClustersProvisioned int32, natGatewayLimitTotal int32, natGatewayProvisioned int32, nlbLimitTotal int32, nlbProvisioned int32, ramPerContract int32, ramPerServer int32, ramProvisioned int32, reservableIps int32, reservedIpsInUse int32, reservedIpsOnContract int32, ssdLimitPerContract int64, ssdLimitPerVolume int64, ssdVolumeProvisioned int64) *ResourceLimits { this := ResourceLimits{} - this.CoresPerServer = &coresPerServer this.CoresPerContract = &coresPerContract + this.CoresPerServer = &coresPerServer this.CoresProvisioned = &coresProvisioned - this.RamPerServer = &ramPerServer - this.RamPerContract = &ramPerContract - this.RamProvisioned = &ramProvisioned - this.HddLimitPerVolume = &hddLimitPerVolume + this.DasVolumeProvisioned = &dasVolumeProvisioned this.HddLimitPerContract = &hddLimitPerContract + this.HddLimitPerVolume = &hddLimitPerVolume this.HddVolumeProvisioned = &hddVolumeProvisioned - this.SsdLimitPerVolume = &ssdLimitPerVolume - this.SsdLimitPerContract = &ssdLimitPerContract - this.SsdVolumeProvisioned = &ssdVolumeProvisioned - this.DasVolumeProvisioned = &dasVolumeProvisioned - this.ReservableIps = &reservableIps - this.ReservedIpsOnContract = &reservedIpsOnContract - this.ReservedIpsInUse = &reservedIpsInUse this.K8sClusterLimitTotal = &k8sClusterLimitTotal this.K8sClustersProvisioned = &k8sClustersProvisioned - this.NlbLimitTotal = &nlbLimitTotal - this.NlbProvisioned = &nlbProvisioned this.NatGatewayLimitTotal = &natGatewayLimitTotal this.NatGatewayProvisioned = &natGatewayProvisioned + this.NlbLimitTotal = &nlbLimitTotal + this.NlbProvisioned = &nlbProvisioned + this.RamPerContract = &ramPerContract + this.RamPerServer = &ramPerServer + this.RamProvisioned = &ramProvisioned + this.ReservableIps = &reservableIps + this.ReservedIpsInUse = &reservedIpsInUse + this.ReservedIpsOnContract = &reservedIpsOnContract + this.SsdLimitPerContract = &ssdLimitPerContract + this.SsdLimitPerVolume = &ssdLimitPerVolume + this.SsdVolumeProvisioned = &ssdVolumeProvisioned return &this } @@ -103,76 +103,76 @@ func NewResourceLimitsWithDefaults() *ResourceLimits { return &this } -// GetCoresPerServer returns the CoresPerServer field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetCoresPerServer() *int32 { +// GetCoresPerContract returns the CoresPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetCoresPerContract() *int32 { if o == nil { return nil } - return o.CoresPerServer + return o.CoresPerContract } -// GetCoresPerServerOk returns a tuple with the CoresPerServer field value +// GetCoresPerContractOk returns a tuple with the CoresPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetCoresPerServerOk() (*int32, bool) { +func (o *ResourceLimits) GetCoresPerContractOk() (*int32, bool) { if o == nil { return nil, false } - return o.CoresPerServer, true + return o.CoresPerContract, true } -// SetCoresPerServer sets field value -func (o *ResourceLimits) SetCoresPerServer(v int32) { +// SetCoresPerContract sets field value +func (o *ResourceLimits) SetCoresPerContract(v int32) { - o.CoresPerServer = &v + o.CoresPerContract = &v } -// HasCoresPerServer returns a boolean if a field has been set. -func (o *ResourceLimits) HasCoresPerServer() bool { - if o != nil && o.CoresPerServer != nil { +// HasCoresPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasCoresPerContract() bool { + if o != nil && o.CoresPerContract != nil { return true } return false } -// GetCoresPerContract returns the CoresPerContract field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetCoresPerContract() *int32 { +// GetCoresPerServer returns the CoresPerServer field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetCoresPerServer() *int32 { if o == nil { return nil } - return o.CoresPerContract + return o.CoresPerServer } -// GetCoresPerContractOk returns a tuple with the CoresPerContract field value +// GetCoresPerServerOk returns a tuple with the CoresPerServer field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetCoresPerContractOk() (*int32, bool) { +func (o *ResourceLimits) GetCoresPerServerOk() (*int32, bool) { if o == nil { return nil, false } - return o.CoresPerContract, true + return o.CoresPerServer, true } -// SetCoresPerContract sets field value -func (o *ResourceLimits) SetCoresPerContract(v int32) { +// SetCoresPerServer sets field value +func (o *ResourceLimits) SetCoresPerServer(v int32) { - o.CoresPerContract = &v + o.CoresPerServer = &v } -// HasCoresPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasCoresPerContract() bool { - if o != nil && o.CoresPerContract != nil { +// HasCoresPerServer returns a boolean if a field has been set. +func (o *ResourceLimits) HasCoresPerServer() bool { + if o != nil && o.CoresPerServer != nil { return true } @@ -180,7 +180,7 @@ func (o *ResourceLimits) HasCoresPerContract() bool { } // GetCoresProvisioned returns the CoresProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ResourceLimits) GetCoresProvisioned() *int32 { if o == nil { return nil @@ -217,722 +217,722 @@ func (o *ResourceLimits) HasCoresProvisioned() bool { return false } -// GetRamPerServer returns the RamPerServer field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetRamPerServer() *int32 { +// GetDasVolumeProvisioned returns the DasVolumeProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetDasVolumeProvisioned() *int64 { if o == nil { return nil } - return o.RamPerServer + return o.DasVolumeProvisioned } -// GetRamPerServerOk returns a tuple with the RamPerServer field value +// GetDasVolumeProvisionedOk returns a tuple with the DasVolumeProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetRamPerServerOk() (*int32, bool) { +func (o *ResourceLimits) GetDasVolumeProvisionedOk() (*int64, bool) { if o == nil { return nil, false } - return o.RamPerServer, true + return o.DasVolumeProvisioned, true } -// SetRamPerServer sets field value -func (o *ResourceLimits) SetRamPerServer(v int32) { +// SetDasVolumeProvisioned sets field value +func (o *ResourceLimits) SetDasVolumeProvisioned(v int64) { - o.RamPerServer = &v + o.DasVolumeProvisioned = &v } -// HasRamPerServer returns a boolean if a field has been set. -func (o *ResourceLimits) HasRamPerServer() bool { - if o != nil && o.RamPerServer != nil { +// HasDasVolumeProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasDasVolumeProvisioned() bool { + if o != nil && o.DasVolumeProvisioned != nil { return true } return false } -// GetRamPerContract returns the RamPerContract field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetRamPerContract() *int32 { +// GetHddLimitPerContract returns the HddLimitPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetHddLimitPerContract() *int64 { if o == nil { return nil } - return o.RamPerContract + return o.HddLimitPerContract } -// GetRamPerContractOk returns a tuple with the RamPerContract field value +// GetHddLimitPerContractOk returns a tuple with the HddLimitPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetRamPerContractOk() (*int32, bool) { +func (o *ResourceLimits) GetHddLimitPerContractOk() (*int64, bool) { if o == nil { return nil, false } - return o.RamPerContract, true + return o.HddLimitPerContract, true } -// SetRamPerContract sets field value -func (o *ResourceLimits) SetRamPerContract(v int32) { +// SetHddLimitPerContract sets field value +func (o *ResourceLimits) SetHddLimitPerContract(v int64) { - o.RamPerContract = &v + o.HddLimitPerContract = &v } -// HasRamPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasRamPerContract() bool { - if o != nil && o.RamPerContract != nil { +// HasHddLimitPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasHddLimitPerContract() bool { + if o != nil && o.HddLimitPerContract != nil { return true } return false } -// GetRamProvisioned returns the RamProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetRamProvisioned() *int32 { +// GetHddLimitPerVolume returns the HddLimitPerVolume field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetHddLimitPerVolume() *int64 { if o == nil { return nil } - return o.RamProvisioned + return o.HddLimitPerVolume } -// GetRamProvisionedOk returns a tuple with the RamProvisioned field value +// GetHddLimitPerVolumeOk returns a tuple with the HddLimitPerVolume field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetRamProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetHddLimitPerVolumeOk() (*int64, bool) { if o == nil { return nil, false } - return o.RamProvisioned, true + return o.HddLimitPerVolume, true } -// SetRamProvisioned sets field value -func (o *ResourceLimits) SetRamProvisioned(v int32) { +// SetHddLimitPerVolume sets field value +func (o *ResourceLimits) SetHddLimitPerVolume(v int64) { - o.RamProvisioned = &v + o.HddLimitPerVolume = &v } -// HasRamProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasRamProvisioned() bool { - if o != nil && o.RamProvisioned != nil { +// HasHddLimitPerVolume returns a boolean if a field has been set. +func (o *ResourceLimits) HasHddLimitPerVolume() bool { + if o != nil && o.HddLimitPerVolume != nil { return true } return false } -// GetHddLimitPerVolume returns the HddLimitPerVolume field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetHddLimitPerVolume() *int64 { +// GetHddVolumeProvisioned returns the HddVolumeProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetHddVolumeProvisioned() *int64 { if o == nil { return nil } - return o.HddLimitPerVolume + return o.HddVolumeProvisioned } -// GetHddLimitPerVolumeOk returns a tuple with the HddLimitPerVolume field value +// GetHddVolumeProvisionedOk returns a tuple with the HddVolumeProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetHddLimitPerVolumeOk() (*int64, bool) { +func (o *ResourceLimits) GetHddVolumeProvisionedOk() (*int64, bool) { if o == nil { return nil, false } - return o.HddLimitPerVolume, true + return o.HddVolumeProvisioned, true } -// SetHddLimitPerVolume sets field value -func (o *ResourceLimits) SetHddLimitPerVolume(v int64) { +// SetHddVolumeProvisioned sets field value +func (o *ResourceLimits) SetHddVolumeProvisioned(v int64) { - o.HddLimitPerVolume = &v + o.HddVolumeProvisioned = &v } -// HasHddLimitPerVolume returns a boolean if a field has been set. -func (o *ResourceLimits) HasHddLimitPerVolume() bool { - if o != nil && o.HddLimitPerVolume != nil { +// HasHddVolumeProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasHddVolumeProvisioned() bool { + if o != nil && o.HddVolumeProvisioned != nil { return true } return false } -// GetHddLimitPerContract returns the HddLimitPerContract field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetHddLimitPerContract() *int64 { +// GetK8sClusterLimitTotal returns the K8sClusterLimitTotal field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetK8sClusterLimitTotal() *int32 { if o == nil { return nil } - return o.HddLimitPerContract + return o.K8sClusterLimitTotal } -// GetHddLimitPerContractOk returns a tuple with the HddLimitPerContract field value +// GetK8sClusterLimitTotalOk returns a tuple with the K8sClusterLimitTotal field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetHddLimitPerContractOk() (*int64, bool) { +func (o *ResourceLimits) GetK8sClusterLimitTotalOk() (*int32, bool) { if o == nil { return nil, false } - return o.HddLimitPerContract, true + return o.K8sClusterLimitTotal, true } -// SetHddLimitPerContract sets field value -func (o *ResourceLimits) SetHddLimitPerContract(v int64) { +// SetK8sClusterLimitTotal sets field value +func (o *ResourceLimits) SetK8sClusterLimitTotal(v int32) { - o.HddLimitPerContract = &v + o.K8sClusterLimitTotal = &v } -// HasHddLimitPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasHddLimitPerContract() bool { - if o != nil && o.HddLimitPerContract != nil { +// HasK8sClusterLimitTotal returns a boolean if a field has been set. +func (o *ResourceLimits) HasK8sClusterLimitTotal() bool { + if o != nil && o.K8sClusterLimitTotal != nil { return true } return false } -// GetHddVolumeProvisioned returns the HddVolumeProvisioned field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetHddVolumeProvisioned() *int64 { +// GetK8sClustersProvisioned returns the K8sClustersProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetK8sClustersProvisioned() *int32 { if o == nil { return nil } - return o.HddVolumeProvisioned + return o.K8sClustersProvisioned } -// GetHddVolumeProvisionedOk returns a tuple with the HddVolumeProvisioned field value +// GetK8sClustersProvisionedOk returns a tuple with the K8sClustersProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetHddVolumeProvisionedOk() (*int64, bool) { +func (o *ResourceLimits) GetK8sClustersProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.HddVolumeProvisioned, true + return o.K8sClustersProvisioned, true } -// SetHddVolumeProvisioned sets field value -func (o *ResourceLimits) SetHddVolumeProvisioned(v int64) { +// SetK8sClustersProvisioned sets field value +func (o *ResourceLimits) SetK8sClustersProvisioned(v int32) { - o.HddVolumeProvisioned = &v + o.K8sClustersProvisioned = &v } -// HasHddVolumeProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasHddVolumeProvisioned() bool { - if o != nil && o.HddVolumeProvisioned != nil { +// HasK8sClustersProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasK8sClustersProvisioned() bool { + if o != nil && o.K8sClustersProvisioned != nil { return true } return false } -// GetSsdLimitPerVolume returns the SsdLimitPerVolume field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetSsdLimitPerVolume() *int64 { +// GetNatGatewayLimitTotal returns the NatGatewayLimitTotal field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNatGatewayLimitTotal() *int32 { if o == nil { return nil } - return o.SsdLimitPerVolume + return o.NatGatewayLimitTotal } -// GetSsdLimitPerVolumeOk returns a tuple with the SsdLimitPerVolume field value +// GetNatGatewayLimitTotalOk returns a tuple with the NatGatewayLimitTotal field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetSsdLimitPerVolumeOk() (*int64, bool) { +func (o *ResourceLimits) GetNatGatewayLimitTotalOk() (*int32, bool) { if o == nil { return nil, false } - return o.SsdLimitPerVolume, true + return o.NatGatewayLimitTotal, true } -// SetSsdLimitPerVolume sets field value -func (o *ResourceLimits) SetSsdLimitPerVolume(v int64) { +// SetNatGatewayLimitTotal sets field value +func (o *ResourceLimits) SetNatGatewayLimitTotal(v int32) { - o.SsdLimitPerVolume = &v + o.NatGatewayLimitTotal = &v } -// HasSsdLimitPerVolume returns a boolean if a field has been set. -func (o *ResourceLimits) HasSsdLimitPerVolume() bool { - if o != nil && o.SsdLimitPerVolume != nil { +// HasNatGatewayLimitTotal returns a boolean if a field has been set. +func (o *ResourceLimits) HasNatGatewayLimitTotal() bool { + if o != nil && o.NatGatewayLimitTotal != nil { return true } return false } -// GetSsdLimitPerContract returns the SsdLimitPerContract field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetSsdLimitPerContract() *int64 { +// GetNatGatewayProvisioned returns the NatGatewayProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNatGatewayProvisioned() *int32 { if o == nil { return nil } - return o.SsdLimitPerContract + return o.NatGatewayProvisioned } -// GetSsdLimitPerContractOk returns a tuple with the SsdLimitPerContract field value +// GetNatGatewayProvisionedOk returns a tuple with the NatGatewayProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetSsdLimitPerContractOk() (*int64, bool) { +func (o *ResourceLimits) GetNatGatewayProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.SsdLimitPerContract, true + return o.NatGatewayProvisioned, true } -// SetSsdLimitPerContract sets field value -func (o *ResourceLimits) SetSsdLimitPerContract(v int64) { +// SetNatGatewayProvisioned sets field value +func (o *ResourceLimits) SetNatGatewayProvisioned(v int32) { - o.SsdLimitPerContract = &v + o.NatGatewayProvisioned = &v } -// HasSsdLimitPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasSsdLimitPerContract() bool { - if o != nil && o.SsdLimitPerContract != nil { +// HasNatGatewayProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasNatGatewayProvisioned() bool { + if o != nil && o.NatGatewayProvisioned != nil { return true } return false } -// GetSsdVolumeProvisioned returns the SsdVolumeProvisioned field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetSsdVolumeProvisioned() *int64 { +// GetNlbLimitTotal returns the NlbLimitTotal field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNlbLimitTotal() *int32 { if o == nil { return nil } - return o.SsdVolumeProvisioned + return o.NlbLimitTotal } -// GetSsdVolumeProvisionedOk returns a tuple with the SsdVolumeProvisioned field value +// GetNlbLimitTotalOk returns a tuple with the NlbLimitTotal field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetSsdVolumeProvisionedOk() (*int64, bool) { +func (o *ResourceLimits) GetNlbLimitTotalOk() (*int32, bool) { if o == nil { return nil, false } - return o.SsdVolumeProvisioned, true + return o.NlbLimitTotal, true } -// SetSsdVolumeProvisioned sets field value -func (o *ResourceLimits) SetSsdVolumeProvisioned(v int64) { +// SetNlbLimitTotal sets field value +func (o *ResourceLimits) SetNlbLimitTotal(v int32) { - o.SsdVolumeProvisioned = &v + o.NlbLimitTotal = &v } -// HasSsdVolumeProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasSsdVolumeProvisioned() bool { - if o != nil && o.SsdVolumeProvisioned != nil { +// HasNlbLimitTotal returns a boolean if a field has been set. +func (o *ResourceLimits) HasNlbLimitTotal() bool { + if o != nil && o.NlbLimitTotal != nil { return true } return false } -// GetDasVolumeProvisioned returns the DasVolumeProvisioned field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetDasVolumeProvisioned() *int64 { +// GetNlbProvisioned returns the NlbProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNlbProvisioned() *int32 { if o == nil { return nil } - return o.DasVolumeProvisioned + return o.NlbProvisioned } -// GetDasVolumeProvisionedOk returns a tuple with the DasVolumeProvisioned field value +// GetNlbProvisionedOk returns a tuple with the NlbProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetDasVolumeProvisionedOk() (*int64, bool) { +func (o *ResourceLimits) GetNlbProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.DasVolumeProvisioned, true + return o.NlbProvisioned, true } -// SetDasVolumeProvisioned sets field value -func (o *ResourceLimits) SetDasVolumeProvisioned(v int64) { +// SetNlbProvisioned sets field value +func (o *ResourceLimits) SetNlbProvisioned(v int32) { - o.DasVolumeProvisioned = &v + o.NlbProvisioned = &v } -// HasDasVolumeProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasDasVolumeProvisioned() bool { - if o != nil && o.DasVolumeProvisioned != nil { +// HasNlbProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasNlbProvisioned() bool { + if o != nil && o.NlbProvisioned != nil { return true } return false } -// GetReservableIps returns the ReservableIps field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetReservableIps() *int32 { +// GetRamPerContract returns the RamPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetRamPerContract() *int32 { if o == nil { return nil } - return o.ReservableIps + return o.RamPerContract } -// GetReservableIpsOk returns a tuple with the ReservableIps field value +// GetRamPerContractOk returns a tuple with the RamPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetReservableIpsOk() (*int32, bool) { +func (o *ResourceLimits) GetRamPerContractOk() (*int32, bool) { if o == nil { return nil, false } - return o.ReservableIps, true + return o.RamPerContract, true } -// SetReservableIps sets field value -func (o *ResourceLimits) SetReservableIps(v int32) { +// SetRamPerContract sets field value +func (o *ResourceLimits) SetRamPerContract(v int32) { - o.ReservableIps = &v + o.RamPerContract = &v } -// HasReservableIps returns a boolean if a field has been set. -func (o *ResourceLimits) HasReservableIps() bool { - if o != nil && o.ReservableIps != nil { +// HasRamPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasRamPerContract() bool { + if o != nil && o.RamPerContract != nil { return true } return false } -// GetReservedIpsOnContract returns the ReservedIpsOnContract field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetReservedIpsOnContract() *int32 { +// GetRamPerServer returns the RamPerServer field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetRamPerServer() *int32 { if o == nil { return nil } - return o.ReservedIpsOnContract + return o.RamPerServer } -// GetReservedIpsOnContractOk returns a tuple with the ReservedIpsOnContract field value +// GetRamPerServerOk returns a tuple with the RamPerServer field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetReservedIpsOnContractOk() (*int32, bool) { +func (o *ResourceLimits) GetRamPerServerOk() (*int32, bool) { if o == nil { return nil, false } - return o.ReservedIpsOnContract, true + return o.RamPerServer, true } -// SetReservedIpsOnContract sets field value -func (o *ResourceLimits) SetReservedIpsOnContract(v int32) { +// SetRamPerServer sets field value +func (o *ResourceLimits) SetRamPerServer(v int32) { - o.ReservedIpsOnContract = &v + o.RamPerServer = &v } -// HasReservedIpsOnContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasReservedIpsOnContract() bool { - if o != nil && o.ReservedIpsOnContract != nil { +// HasRamPerServer returns a boolean if a field has been set. +func (o *ResourceLimits) HasRamPerServer() bool { + if o != nil && o.RamPerServer != nil { return true } return false } -// GetReservedIpsInUse returns the ReservedIpsInUse field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetReservedIpsInUse() *int32 { +// GetRamProvisioned returns the RamProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetRamProvisioned() *int32 { if o == nil { return nil } - return o.ReservedIpsInUse + return o.RamProvisioned } -// GetReservedIpsInUseOk returns a tuple with the ReservedIpsInUse field value +// GetRamProvisionedOk returns a tuple with the RamProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetReservedIpsInUseOk() (*int32, bool) { +func (o *ResourceLimits) GetRamProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.ReservedIpsInUse, true + return o.RamProvisioned, true } -// SetReservedIpsInUse sets field value -func (o *ResourceLimits) SetReservedIpsInUse(v int32) { +// SetRamProvisioned sets field value +func (o *ResourceLimits) SetRamProvisioned(v int32) { - o.ReservedIpsInUse = &v + o.RamProvisioned = &v } -// HasReservedIpsInUse returns a boolean if a field has been set. -func (o *ResourceLimits) HasReservedIpsInUse() bool { - if o != nil && o.ReservedIpsInUse != nil { +// HasRamProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasRamProvisioned() bool { + if o != nil && o.RamProvisioned != nil { return true } return false } -// GetK8sClusterLimitTotal returns the K8sClusterLimitTotal field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetK8sClusterLimitTotal() *int32 { +// GetReservableIps returns the ReservableIps field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetReservableIps() *int32 { if o == nil { return nil } - return o.K8sClusterLimitTotal + return o.ReservableIps } -// GetK8sClusterLimitTotalOk returns a tuple with the K8sClusterLimitTotal field value +// GetReservableIpsOk returns a tuple with the ReservableIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetK8sClusterLimitTotalOk() (*int32, bool) { +func (o *ResourceLimits) GetReservableIpsOk() (*int32, bool) { if o == nil { return nil, false } - return o.K8sClusterLimitTotal, true + return o.ReservableIps, true } -// SetK8sClusterLimitTotal sets field value -func (o *ResourceLimits) SetK8sClusterLimitTotal(v int32) { +// SetReservableIps sets field value +func (o *ResourceLimits) SetReservableIps(v int32) { - o.K8sClusterLimitTotal = &v + o.ReservableIps = &v } -// HasK8sClusterLimitTotal returns a boolean if a field has been set. -func (o *ResourceLimits) HasK8sClusterLimitTotal() bool { - if o != nil && o.K8sClusterLimitTotal != nil { +// HasReservableIps returns a boolean if a field has been set. +func (o *ResourceLimits) HasReservableIps() bool { + if o != nil && o.ReservableIps != nil { return true } return false } -// GetK8sClustersProvisioned returns the K8sClustersProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetK8sClustersProvisioned() *int32 { +// GetReservedIpsInUse returns the ReservedIpsInUse field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetReservedIpsInUse() *int32 { if o == nil { return nil } - return o.K8sClustersProvisioned + return o.ReservedIpsInUse } -// GetK8sClustersProvisionedOk returns a tuple with the K8sClustersProvisioned field value +// GetReservedIpsInUseOk returns a tuple with the ReservedIpsInUse field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetK8sClustersProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetReservedIpsInUseOk() (*int32, bool) { if o == nil { return nil, false } - return o.K8sClustersProvisioned, true + return o.ReservedIpsInUse, true } -// SetK8sClustersProvisioned sets field value -func (o *ResourceLimits) SetK8sClustersProvisioned(v int32) { +// SetReservedIpsInUse sets field value +func (o *ResourceLimits) SetReservedIpsInUse(v int32) { - o.K8sClustersProvisioned = &v + o.ReservedIpsInUse = &v } -// HasK8sClustersProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasK8sClustersProvisioned() bool { - if o != nil && o.K8sClustersProvisioned != nil { +// HasReservedIpsInUse returns a boolean if a field has been set. +func (o *ResourceLimits) HasReservedIpsInUse() bool { + if o != nil && o.ReservedIpsInUse != nil { return true } return false } -// GetNlbLimitTotal returns the NlbLimitTotal field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNlbLimitTotal() *int32 { +// GetReservedIpsOnContract returns the ReservedIpsOnContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetReservedIpsOnContract() *int32 { if o == nil { return nil } - return o.NlbLimitTotal + return o.ReservedIpsOnContract } -// GetNlbLimitTotalOk returns a tuple with the NlbLimitTotal field value +// GetReservedIpsOnContractOk returns a tuple with the ReservedIpsOnContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNlbLimitTotalOk() (*int32, bool) { +func (o *ResourceLimits) GetReservedIpsOnContractOk() (*int32, bool) { if o == nil { return nil, false } - return o.NlbLimitTotal, true + return o.ReservedIpsOnContract, true } -// SetNlbLimitTotal sets field value -func (o *ResourceLimits) SetNlbLimitTotal(v int32) { +// SetReservedIpsOnContract sets field value +func (o *ResourceLimits) SetReservedIpsOnContract(v int32) { - o.NlbLimitTotal = &v + o.ReservedIpsOnContract = &v } -// HasNlbLimitTotal returns a boolean if a field has been set. -func (o *ResourceLimits) HasNlbLimitTotal() bool { - if o != nil && o.NlbLimitTotal != nil { +// HasReservedIpsOnContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasReservedIpsOnContract() bool { + if o != nil && o.ReservedIpsOnContract != nil { return true } return false } -// GetNlbProvisioned returns the NlbProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNlbProvisioned() *int32 { +// GetSsdLimitPerContract returns the SsdLimitPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetSsdLimitPerContract() *int64 { if o == nil { return nil } - return o.NlbProvisioned + return o.SsdLimitPerContract } -// GetNlbProvisionedOk returns a tuple with the NlbProvisioned field value +// GetSsdLimitPerContractOk returns a tuple with the SsdLimitPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNlbProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetSsdLimitPerContractOk() (*int64, bool) { if o == nil { return nil, false } - return o.NlbProvisioned, true + return o.SsdLimitPerContract, true } -// SetNlbProvisioned sets field value -func (o *ResourceLimits) SetNlbProvisioned(v int32) { +// SetSsdLimitPerContract sets field value +func (o *ResourceLimits) SetSsdLimitPerContract(v int64) { - o.NlbProvisioned = &v + o.SsdLimitPerContract = &v } -// HasNlbProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasNlbProvisioned() bool { - if o != nil && o.NlbProvisioned != nil { +// HasSsdLimitPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasSsdLimitPerContract() bool { + if o != nil && o.SsdLimitPerContract != nil { return true } return false } -// GetNatGatewayLimitTotal returns the NatGatewayLimitTotal field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNatGatewayLimitTotal() *int32 { +// GetSsdLimitPerVolume returns the SsdLimitPerVolume field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetSsdLimitPerVolume() *int64 { if o == nil { return nil } - return o.NatGatewayLimitTotal + return o.SsdLimitPerVolume } -// GetNatGatewayLimitTotalOk returns a tuple with the NatGatewayLimitTotal field value +// GetSsdLimitPerVolumeOk returns a tuple with the SsdLimitPerVolume field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNatGatewayLimitTotalOk() (*int32, bool) { +func (o *ResourceLimits) GetSsdLimitPerVolumeOk() (*int64, bool) { if o == nil { return nil, false } - return o.NatGatewayLimitTotal, true + return o.SsdLimitPerVolume, true } -// SetNatGatewayLimitTotal sets field value -func (o *ResourceLimits) SetNatGatewayLimitTotal(v int32) { +// SetSsdLimitPerVolume sets field value +func (o *ResourceLimits) SetSsdLimitPerVolume(v int64) { - o.NatGatewayLimitTotal = &v + o.SsdLimitPerVolume = &v } -// HasNatGatewayLimitTotal returns a boolean if a field has been set. -func (o *ResourceLimits) HasNatGatewayLimitTotal() bool { - if o != nil && o.NatGatewayLimitTotal != nil { +// HasSsdLimitPerVolume returns a boolean if a field has been set. +func (o *ResourceLimits) HasSsdLimitPerVolume() bool { + if o != nil && o.SsdLimitPerVolume != nil { return true } return false } -// GetNatGatewayProvisioned returns the NatGatewayProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNatGatewayProvisioned() *int32 { +// GetSsdVolumeProvisioned returns the SsdVolumeProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetSsdVolumeProvisioned() *int64 { if o == nil { return nil } - return o.NatGatewayProvisioned + return o.SsdVolumeProvisioned } -// GetNatGatewayProvisionedOk returns a tuple with the NatGatewayProvisioned field value +// GetSsdVolumeProvisionedOk returns a tuple with the SsdVolumeProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNatGatewayProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetSsdVolumeProvisionedOk() (*int64, bool) { if o == nil { return nil, false } - return o.NatGatewayProvisioned, true + return o.SsdVolumeProvisioned, true } -// SetNatGatewayProvisioned sets field value -func (o *ResourceLimits) SetNatGatewayProvisioned(v int32) { +// SetSsdVolumeProvisioned sets field value +func (o *ResourceLimits) SetSsdVolumeProvisioned(v int64) { - o.NatGatewayProvisioned = &v + o.SsdVolumeProvisioned = &v } -// HasNatGatewayProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasNatGatewayProvisioned() bool { - if o != nil && o.NatGatewayProvisioned != nil { +// HasSsdVolumeProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasSsdVolumeProvisioned() bool { + if o != nil && o.SsdVolumeProvisioned != nil { return true } @@ -941,72 +941,94 @@ func (o *ResourceLimits) HasNatGatewayProvisioned() bool { func (o ResourceLimits) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.CoresPerServer != nil { - toSerialize["coresPerServer"] = o.CoresPerServer - } if o.CoresPerContract != nil { toSerialize["coresPerContract"] = o.CoresPerContract } + + if o.CoresPerServer != nil { + toSerialize["coresPerServer"] = o.CoresPerServer + } + if o.CoresProvisioned != nil { toSerialize["coresProvisioned"] = o.CoresProvisioned } - if o.RamPerServer != nil { - toSerialize["ramPerServer"] = o.RamPerServer - } - if o.RamPerContract != nil { - toSerialize["ramPerContract"] = o.RamPerContract + + if o.DasVolumeProvisioned != nil { + toSerialize["dasVolumeProvisioned"] = o.DasVolumeProvisioned } - if o.RamProvisioned != nil { - toSerialize["ramProvisioned"] = o.RamProvisioned + + if o.HddLimitPerContract != nil { + toSerialize["hddLimitPerContract"] = o.HddLimitPerContract } + if o.HddLimitPerVolume != nil { toSerialize["hddLimitPerVolume"] = o.HddLimitPerVolume } - if o.HddLimitPerContract != nil { - toSerialize["hddLimitPerContract"] = o.HddLimitPerContract - } + if o.HddVolumeProvisioned != nil { toSerialize["hddVolumeProvisioned"] = o.HddVolumeProvisioned } - if o.SsdLimitPerVolume != nil { - toSerialize["ssdLimitPerVolume"] = o.SsdLimitPerVolume - } - if o.SsdLimitPerContract != nil { - toSerialize["ssdLimitPerContract"] = o.SsdLimitPerContract - } - if o.SsdVolumeProvisioned != nil { - toSerialize["ssdVolumeProvisioned"] = o.SsdVolumeProvisioned - } - if o.DasVolumeProvisioned != nil { - toSerialize["dasVolumeProvisioned"] = o.DasVolumeProvisioned - } - if o.ReservableIps != nil { - toSerialize["reservableIps"] = o.ReservableIps - } - if o.ReservedIpsOnContract != nil { - toSerialize["reservedIpsOnContract"] = o.ReservedIpsOnContract - } - if o.ReservedIpsInUse != nil { - toSerialize["reservedIpsInUse"] = o.ReservedIpsInUse - } + if o.K8sClusterLimitTotal != nil { toSerialize["k8sClusterLimitTotal"] = o.K8sClusterLimitTotal } + if o.K8sClustersProvisioned != nil { toSerialize["k8sClustersProvisioned"] = o.K8sClustersProvisioned } + + if o.NatGatewayLimitTotal != nil { + toSerialize["natGatewayLimitTotal"] = o.NatGatewayLimitTotal + } + + if o.NatGatewayProvisioned != nil { + toSerialize["natGatewayProvisioned"] = o.NatGatewayProvisioned + } + if o.NlbLimitTotal != nil { toSerialize["nlbLimitTotal"] = o.NlbLimitTotal } + if o.NlbProvisioned != nil { toSerialize["nlbProvisioned"] = o.NlbProvisioned } - if o.NatGatewayLimitTotal != nil { - toSerialize["natGatewayLimitTotal"] = o.NatGatewayLimitTotal + + if o.RamPerContract != nil { + toSerialize["ramPerContract"] = o.RamPerContract } - if o.NatGatewayProvisioned != nil { - toSerialize["natGatewayProvisioned"] = o.NatGatewayProvisioned + + if o.RamPerServer != nil { + toSerialize["ramPerServer"] = o.RamPerServer } + + if o.RamProvisioned != nil { + toSerialize["ramProvisioned"] = o.RamProvisioned + } + + if o.ReservableIps != nil { + toSerialize["reservableIps"] = o.ReservableIps + } + + if o.ReservedIpsInUse != nil { + toSerialize["reservedIpsInUse"] = o.ReservedIpsInUse + } + + if o.ReservedIpsOnContract != nil { + toSerialize["reservedIpsOnContract"] = o.ReservedIpsOnContract + } + + if o.SsdLimitPerContract != nil { + toSerialize["ssdLimitPerContract"] = o.SsdLimitPerContract + } + + if o.SsdLimitPerVolume != nil { + toSerialize["ssdLimitPerVolume"] = o.SsdLimitPerVolume + } + + if o.SsdVolumeProvisioned != nil { + toSerialize["ssdVolumeProvisioned"] = o.SsdVolumeProvisioned + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go index b5b274a28..224350ec5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go @@ -41,7 +41,7 @@ func NewResourcePropertiesWithDefaults() *ResourceProperties { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ResourceProperties) GetName() *string { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *ResourceProperties) HasName() bool { } // GetSecAuthProtection returns the SecAuthProtection field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *ResourceProperties) GetSecAuthProtection() *bool { if o == nil { return nil @@ -121,9 +121,11 @@ func (o ResourceProperties) MarshalJSON() ([]byte, error) { if o.Name != nil { toSerialize["name"] = o.Name } + if o.SecAuthProtection != nil { toSerialize["secAuthProtection"] = o.SecAuthProtection } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go index 5732ab570..6b58f76a3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go @@ -16,12 +16,12 @@ import ( // ResourceReference struct for ResourceReference type ResourceReference struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. Id *string `json:"id"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` } // NewResourceReference instantiates a new ResourceReference object @@ -44,114 +44,114 @@ func NewResourceReferenceWithDefaults() *ResourceReference { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceReference) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ResourceReference) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceReference) GetIdOk() (*string, bool) { +func (o *ResourceReference) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ResourceReference) SetId(v string) { +// SetHref sets field value +func (o *ResourceReference) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ResourceReference) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ResourceReference) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ResourceReference) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ResourceReference) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceReference) GetTypeOk() (*Type, bool) { +func (o *ResourceReference) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ResourceReference) SetType(v Type) { +// SetId sets field value +func (o *ResourceReference) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ResourceReference) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ResourceReference) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceReference) GetHref() *string { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ResourceReference) GetType() *Type { if o == nil { return nil } - return o.Href + return o.Type } -// GetHrefOk returns a tuple with the Href field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceReference) GetHrefOk() (*string, bool) { +func (o *ResourceReference) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Type, true } -// SetHref sets field value -func (o *ResourceReference) SetHref(v string) { +// SetType sets field value +func (o *ResourceReference) SetType(v Type) { - o.Href = &v + o.Type = &v } -// HasHref returns a boolean if a field has been set. -func (o *ResourceReference) HasHref() bool { - if o != nil && o.Href != nil { +// HasType returns a boolean if a field has been set. +func (o *ResourceReference) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -160,15 +160,18 @@ func (o *ResourceReference) HasHref() bool { func (o ResourceReference) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Href != nil { + toSerialize["href"] = o.Href + } + if o.Id != nil { toSerialize["id"] = o.Id } + if o.Type != nil { toSerialize["type"] = o.Type } - if o.Href != nil { - toSerialize["href"] = o.Href - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go index 36b8beeab..9db504339 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go @@ -16,14 +16,14 @@ import ( // Resources Collection to represent the resource. type Resources struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Resource `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResources instantiates a new Resources object @@ -44,152 +44,152 @@ func NewResourcesWithDefaults() *Resources { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resources) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetIdOk() (*string, bool) { +func (o *Resources) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Resources) SetId(v string) { +// SetHref sets field value +func (o *Resources) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Resources) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Resources) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Resources) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetTypeOk() (*Type, bool) { +func (o *Resources) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Resources) SetType(v Type) { +// SetId sets field value +func (o *Resources) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Resources) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Resources) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resources) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetItems() *[]Resource { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetHrefOk() (*string, bool) { +func (o *Resources) GetItemsOk() (*[]Resource, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Resources) SetHref(v string) { +// SetItems sets field value +func (o *Resources) SetItems(v []Resource) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Resources) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Resources) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Resource will be returned -func (o *Resources) GetItems() *[]Resource { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetItemsOk() (*[]Resource, bool) { +func (o *Resources) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Resources) SetItems(v []Resource) { +// SetType sets field value +func (o *Resources) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Resources) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Resources) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Resources) HasItems() bool { func (o Resources) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go index 18de5cf52..e8772006c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go @@ -16,14 +16,14 @@ import ( // ResourcesUsers Resources owned by a user. type ResourcesUsers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Resource `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResourcesUsers instantiates a new ResourcesUsers object @@ -44,152 +44,152 @@ func NewResourcesUsersWithDefaults() *ResourcesUsers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourcesUsers) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetIdOk() (*string, bool) { +func (o *ResourcesUsers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ResourcesUsers) SetId(v string) { +// SetHref sets field value +func (o *ResourcesUsers) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ResourcesUsers) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ResourcesUsers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ResourcesUsers) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetTypeOk() (*Type, bool) { +func (o *ResourcesUsers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ResourcesUsers) SetType(v Type) { +// SetId sets field value +func (o *ResourcesUsers) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ResourcesUsers) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ResourcesUsers) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourcesUsers) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetItems() *[]Resource { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetHrefOk() (*string, bool) { +func (o *ResourcesUsers) GetItemsOk() (*[]Resource, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *ResourcesUsers) SetHref(v string) { +// SetItems sets field value +func (o *ResourcesUsers) SetItems(v []Resource) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *ResourcesUsers) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *ResourcesUsers) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Resource will be returned -func (o *ResourcesUsers) GetItems() *[]Resource { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetItemsOk() (*[]Resource, bool) { +func (o *ResourcesUsers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *ResourcesUsers) SetItems(v []Resource) { +// SetType sets field value +func (o *ResourcesUsers) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *ResourcesUsers) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *ResourcesUsers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *ResourcesUsers) HasItems() bool { func (o ResourcesUsers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go index bede84667..5e263873c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go @@ -41,7 +41,7 @@ func NewS3BucketWithDefaults() *S3Bucket { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *S3Bucket) GetName() *string { if o == nil { return nil @@ -83,6 +83,7 @@ func (o S3Bucket) MarshalJSON() ([]byte, error) { if o.Name != nil { toSerialize["name"] = o.Name } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go index 5febf4192..ae9f00908 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go @@ -16,14 +16,14 @@ import ( // S3Key struct for S3Key type S3Key struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *S3KeyMetadata `json:"metadata,omitempty"` Properties *S3KeyProperties `json:"properties"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewS3Key instantiates a new S3Key object @@ -46,190 +46,190 @@ func NewS3KeyWithDefaults() *S3Key { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Key) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetIdOk() (*string, bool) { +func (o *S3Key) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *S3Key) SetId(v string) { +// SetHref sets field value +func (o *S3Key) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *S3Key) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *S3Key) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *S3Key) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetTypeOk() (*Type, bool) { +func (o *S3Key) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *S3Key) SetType(v Type) { +// SetId sets field value +func (o *S3Key) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *S3Key) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *S3Key) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Key) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetMetadata() *S3KeyMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetHrefOk() (*string, bool) { +func (o *S3Key) GetMetadataOk() (*S3KeyMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *S3Key) SetHref(v string) { +// SetMetadata sets field value +func (o *S3Key) SetMetadata(v S3KeyMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *S3Key) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *S3Key) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for S3KeyMetadata will be returned -func (o *S3Key) GetMetadata() *S3KeyMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetProperties() *S3KeyProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetMetadataOk() (*S3KeyMetadata, bool) { +func (o *S3Key) GetPropertiesOk() (*S3KeyProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *S3Key) SetMetadata(v S3KeyMetadata) { +// SetProperties sets field value +func (o *S3Key) SetProperties(v S3KeyProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *S3Key) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *S3Key) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for S3KeyProperties will be returned -func (o *S3Key) GetProperties() *S3KeyProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetPropertiesOk() (*S3KeyProperties, bool) { +func (o *S3Key) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *S3Key) SetProperties(v S3KeyProperties) { +// SetType sets field value +func (o *S3Key) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *S3Key) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *S3Key) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *S3Key) HasProperties() bool { func (o S3Key) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go index 83ecc8b46..f090555e7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go @@ -17,10 +17,10 @@ import ( // S3KeyMetadata struct for S3KeyMetadata type S3KeyMetadata struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` // The time when the S3 key was created. CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` } // NewS3KeyMetadata instantiates a new S3KeyMetadata object @@ -41,83 +41,83 @@ func NewS3KeyMetadataWithDefaults() *S3KeyMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3KeyMetadata) GetEtag() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *S3KeyMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.Etag + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetEtagOk returns a tuple with the Etag field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyMetadata) GetEtagOk() (*string, bool) { +func (o *S3KeyMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.Etag, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetEtag sets field value -func (o *S3KeyMetadata) SetEtag(v string) { +// SetCreatedDate sets field value +func (o *S3KeyMetadata) SetCreatedDate(v time.Time) { - o.Etag = &v + o.CreatedDate = &IonosTime{v} } -// HasEtag returns a boolean if a field has been set. -func (o *S3KeyMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *S3KeyMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } return false } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *S3KeyMetadata) GetCreatedDate() *time.Time { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *S3KeyMetadata) GetEtag() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.Etag } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *S3KeyMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.Etag, true } -// SetCreatedDate sets field value -func (o *S3KeyMetadata) SetCreatedDate(v time.Time) { +// SetEtag sets field value +func (o *S3KeyMetadata) SetEtag(v string) { - o.CreatedDate = &IonosTime{v} + o.Etag = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *S3KeyMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasEtag returns a boolean if a field has been set. +func (o *S3KeyMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -126,12 +126,14 @@ func (o *S3KeyMetadata) HasCreatedDate() bool { func (o S3KeyMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } if o.CreatedDate != nil { toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go index a3204d717..0cf12e771 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go @@ -16,10 +16,10 @@ import ( // S3KeyProperties struct for S3KeyProperties type S3KeyProperties struct { - // Secret of the S3 key. - SecretKey *string `json:"secretKey,omitempty"` // Denotes weather the S3 key is active. Active *bool `json:"active,omitempty"` + // Secret of the S3 key. + SecretKey *string `json:"secretKey,omitempty"` } // NewS3KeyProperties instantiates a new S3KeyProperties object @@ -40,76 +40,76 @@ func NewS3KeyPropertiesWithDefaults() *S3KeyProperties { return &this } -// GetSecretKey returns the SecretKey field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3KeyProperties) GetSecretKey() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *S3KeyProperties) GetActive() *bool { if o == nil { return nil } - return o.SecretKey + return o.Active } -// GetSecretKeyOk returns a tuple with the SecretKey field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyProperties) GetSecretKeyOk() (*string, bool) { +func (o *S3KeyProperties) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.SecretKey, true + return o.Active, true } -// SetSecretKey sets field value -func (o *S3KeyProperties) SetSecretKey(v string) { +// SetActive sets field value +func (o *S3KeyProperties) SetActive(v bool) { - o.SecretKey = &v + o.Active = &v } -// HasSecretKey returns a boolean if a field has been set. -func (o *S3KeyProperties) HasSecretKey() bool { - if o != nil && o.SecretKey != nil { +// HasActive returns a boolean if a field has been set. +func (o *S3KeyProperties) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *S3KeyProperties) GetActive() *bool { +// GetSecretKey returns the SecretKey field value +// If the value is explicit nil, nil is returned +func (o *S3KeyProperties) GetSecretKey() *string { if o == nil { return nil } - return o.Active + return o.SecretKey } -// GetActiveOk returns a tuple with the Active field value +// GetSecretKeyOk returns a tuple with the SecretKey field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyProperties) GetActiveOk() (*bool, bool) { +func (o *S3KeyProperties) GetSecretKeyOk() (*string, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecretKey, true } -// SetActive sets field value -func (o *S3KeyProperties) SetActive(v bool) { +// SetSecretKey sets field value +func (o *S3KeyProperties) SetSecretKey(v string) { - o.Active = &v + o.SecretKey = &v } -// HasActive returns a boolean if a field has been set. -func (o *S3KeyProperties) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecretKey returns a boolean if a field has been set. +func (o *S3KeyProperties) HasSecretKey() bool { + if o != nil && o.SecretKey != nil { return true } @@ -118,12 +118,14 @@ func (o *S3KeyProperties) HasActive() bool { func (o S3KeyProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.SecretKey != nil { - toSerialize["secretKey"] = o.SecretKey - } if o.Active != nil { toSerialize["active"] = o.Active } + + if o.SecretKey != nil { + toSerialize["secretKey"] = o.SecretKey + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go index a87bc2f76..d0ed78cc6 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go @@ -16,14 +16,14 @@ import ( // S3Keys struct for S3Keys type S3Keys struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]S3Key `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewS3Keys instantiates a new S3Keys object @@ -44,152 +44,152 @@ func NewS3KeysWithDefaults() *S3Keys { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Keys) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetIdOk() (*string, bool) { +func (o *S3Keys) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *S3Keys) SetId(v string) { +// SetHref sets field value +func (o *S3Keys) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *S3Keys) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *S3Keys) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *S3Keys) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetTypeOk() (*Type, bool) { +func (o *S3Keys) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *S3Keys) SetType(v Type) { +// SetId sets field value +func (o *S3Keys) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *S3Keys) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *S3Keys) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Keys) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetItems() *[]S3Key { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetHrefOk() (*string, bool) { +func (o *S3Keys) GetItemsOk() (*[]S3Key, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *S3Keys) SetHref(v string) { +// SetItems sets field value +func (o *S3Keys) SetItems(v []S3Key) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *S3Keys) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *S3Keys) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []S3Key will be returned -func (o *S3Keys) GetItems() *[]S3Key { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetItemsOk() (*[]S3Key, bool) { +func (o *S3Keys) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *S3Keys) SetItems(v []S3Key) { +// SetType sets field value +func (o *S3Keys) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *S3Keys) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *S3Keys) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *S3Keys) HasItems() bool { func (o S3Keys) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go index 48eb4b166..809410a04 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go @@ -39,7 +39,7 @@ func NewS3ObjectStorageSSOWithDefaults() *S3ObjectStorageSSO { } // GetSsoUrl returns the SsoUrl field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *S3ObjectStorageSSO) GetSsoUrl() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o S3ObjectStorageSSO) MarshalJSON() ([]byte, error) { if o.SsoUrl != nil { toSerialize["ssoUrl"] = o.SsoUrl } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go index ad75b98a1..4002c4bda 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go @@ -16,15 +16,15 @@ import ( // Server struct for Server type Server struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *ServerEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ServerProperties `json:"properties"` - Entities *ServerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewServer instantiates a new Server object @@ -47,114 +47,114 @@ func NewServerWithDefaults() *Server { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Server) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Server) GetEntities() *ServerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetIdOk() (*string, bool) { +func (o *Server) GetEntitiesOk() (*ServerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Server) SetId(v string) { +// SetEntities sets field value +func (o *Server) SetEntities(v ServerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Server) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Server) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Server) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Server) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetTypeOk() (*Type, bool) { +func (o *Server) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Server) SetType(v Type) { +// SetHref sets field value +func (o *Server) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Server) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Server) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Server) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Server) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetHrefOk() (*string, bool) { +func (o *Server) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Server) SetHref(v string) { +// SetId sets field value +func (o *Server) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Server) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Server) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Server) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Server) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Server) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ServerProperties will be returned +// If the value is explicit nil, nil is returned func (o *Server) GetProperties() *ServerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Server) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for ServerEntities will be returned -func (o *Server) GetEntities() *ServerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Server) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetEntitiesOk() (*ServerEntities, bool) { +func (o *Server) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Server) SetEntities(v ServerEntities) { +// SetType sets field value +func (o *Server) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Server) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Server) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Server) HasEntities() bool { func (o Server) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go index fcb42fdb2..a2a8b8912 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go @@ -17,8 +17,8 @@ import ( // ServerEntities struct for ServerEntities type ServerEntities struct { Cdroms *Cdroms `json:"cdroms,omitempty"` - Volumes *AttachedVolumes `json:"volumes,omitempty"` Nics *Nics `json:"nics,omitempty"` + Volumes *AttachedVolumes `json:"volumes,omitempty"` } // NewServerEntities instantiates a new ServerEntities object @@ -40,7 +40,7 @@ func NewServerEntitiesWithDefaults() *ServerEntities { } // GetCdroms returns the Cdroms field value -// If the value is explicit nil, the zero value for Cdroms will be returned +// If the value is explicit nil, nil is returned func (o *ServerEntities) GetCdroms() *Cdroms { if o == nil { return nil @@ -77,76 +77,76 @@ func (o *ServerEntities) HasCdroms() bool { return false } -// GetVolumes returns the Volumes field value -// If the value is explicit nil, the zero value for AttachedVolumes will be returned -func (o *ServerEntities) GetVolumes() *AttachedVolumes { +// GetNics returns the Nics field value +// If the value is explicit nil, nil is returned +func (o *ServerEntities) GetNics() *Nics { if o == nil { return nil } - return o.Volumes + return o.Nics } -// GetVolumesOk returns a tuple with the Volumes field value +// GetNicsOk returns a tuple with the Nics field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerEntities) GetVolumesOk() (*AttachedVolumes, bool) { +func (o *ServerEntities) GetNicsOk() (*Nics, bool) { if o == nil { return nil, false } - return o.Volumes, true + return o.Nics, true } -// SetVolumes sets field value -func (o *ServerEntities) SetVolumes(v AttachedVolumes) { +// SetNics sets field value +func (o *ServerEntities) SetNics(v Nics) { - o.Volumes = &v + o.Nics = &v } -// HasVolumes returns a boolean if a field has been set. -func (o *ServerEntities) HasVolumes() bool { - if o != nil && o.Volumes != nil { +// HasNics returns a boolean if a field has been set. +func (o *ServerEntities) HasNics() bool { + if o != nil && o.Nics != nil { return true } return false } -// GetNics returns the Nics field value -// If the value is explicit nil, the zero value for Nics will be returned -func (o *ServerEntities) GetNics() *Nics { +// GetVolumes returns the Volumes field value +// If the value is explicit nil, nil is returned +func (o *ServerEntities) GetVolumes() *AttachedVolumes { if o == nil { return nil } - return o.Nics + return o.Volumes } -// GetNicsOk returns a tuple with the Nics field value +// GetVolumesOk returns a tuple with the Volumes field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerEntities) GetNicsOk() (*Nics, bool) { +func (o *ServerEntities) GetVolumesOk() (*AttachedVolumes, bool) { if o == nil { return nil, false } - return o.Nics, true + return o.Volumes, true } -// SetNics sets field value -func (o *ServerEntities) SetNics(v Nics) { +// SetVolumes sets field value +func (o *ServerEntities) SetVolumes(v AttachedVolumes) { - o.Nics = &v + o.Volumes = &v } -// HasNics returns a boolean if a field has been set. -func (o *ServerEntities) HasNics() bool { - if o != nil && o.Nics != nil { +// HasVolumes returns a boolean if a field has been set. +func (o *ServerEntities) HasVolumes() bool { + if o != nil && o.Volumes != nil { return true } @@ -158,12 +158,15 @@ func (o ServerEntities) MarshalJSON() ([]byte, error) { if o.Cdroms != nil { toSerialize["cdroms"] = o.Cdroms } - if o.Volumes != nil { - toSerialize["volumes"] = o.Volumes - } + if o.Nics != nil { toSerialize["nics"] = o.Nics } + + if o.Volumes != nil { + toSerialize["volumes"] = o.Volumes + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go index 4f292cde9..5b81d9551 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go @@ -16,24 +16,26 @@ import ( // ServerProperties struct for ServerProperties type ServerProperties struct { - // The ID of the template for creating a CUBE server; the available templates for CUBE servers can be found on the templates resource. - TemplateUuid *string `json:"templateUuid,omitempty"` - // The name of the resource. - Name *string `json:"name,omitempty"` + // The availability zone in which the server should be provisioned. + AvailabilityZone *string `json:"availabilityZone,omitempty"` + BootCdrom *ResourceReference `json:"bootCdrom,omitempty"` + BootVolume *ResourceReference `json:"bootVolume,omitempty"` // The total number of cores for the enterprise server. Cores *int32 `json:"cores,omitempty"` - // The memory size for the enterprise server in MB, such as 2048. Size must be specified in multiples of 256 MB with a minimum of 256 MB; however, if you set ramHotPlug to TRUE then you must use a minimum of 1024 MB. If you set the RAM size more than 240GB, then ramHotPlug will be set to FALSE and can not be set to TRUE unless RAM size not set to less than 240GB. - Ram *int32 `json:"ram,omitempty"` - // The availability zone in which the server should be provisioned. - AvailabilityZone *string `json:"availabilityZone,omitempty"` - // Status of the virtual machine. - VmState *string `json:"vmState,omitempty"` - BootCdrom *ResourceReference `json:"bootCdrom,omitempty"` - BootVolume *ResourceReference `json:"bootVolume,omitempty"` // CPU architecture on which server gets provisioned; not all CPU architectures are available in all datacenter regions; available CPU architectures can be retrieved from the datacenter resource; must not be provided for CUBE servers. CpuFamily *string `json:"cpuFamily,omitempty"` - // Server type. + // The name of the resource. + Name *string `json:"name,omitempty"` + // The placement group ID that belongs to this server; Requires system privileges + PlacementGroupId *string `json:"placementGroupId,omitempty"` + // The memory size for the enterprise server in MB, such as 2048. Size must be specified in multiples of 256 MB with a minimum of 256 MB; however, if you set ramHotPlug to TRUE then you must use a minimum of 1024 MB. If you set the RAM size more than 240GB, then ramHotPlug will be set to FALSE and can not be set to TRUE unless RAM size not set to less than 240GB. + Ram *int32 `json:"ram,omitempty"` + // The ID of the template for creating a CUBE server; the available templates for CUBE servers can be found on the templates resource. + TemplateUuid *string `json:"templateUuid,omitempty"` + // Server type: CUBE or ENTERPRISE. Type *string `json:"type,omitempty"` + // Status of the virtual machine. + VmState *string `json:"vmState,omitempty"` } // NewServerProperties instantiates a new ServerProperties object @@ -54,342 +56,342 @@ func NewServerPropertiesWithDefaults() *ServerProperties { return &this } -// GetTemplateUuid returns the TemplateUuid field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetTemplateUuid() *string { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetAvailabilityZone() *string { if o == nil { return nil } - return o.TemplateUuid + return o.AvailabilityZone } -// GetTemplateUuidOk returns a tuple with the TemplateUuid field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetTemplateUuidOk() (*string, bool) { +func (o *ServerProperties) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.TemplateUuid, true + return o.AvailabilityZone, true } -// SetTemplateUuid sets field value -func (o *ServerProperties) SetTemplateUuid(v string) { +// SetAvailabilityZone sets field value +func (o *ServerProperties) SetAvailabilityZone(v string) { - o.TemplateUuid = &v + o.AvailabilityZone = &v } -// HasTemplateUuid returns a boolean if a field has been set. -func (o *ServerProperties) HasTemplateUuid() bool { - if o != nil && o.TemplateUuid != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *ServerProperties) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetName() *string { +// GetBootCdrom returns the BootCdrom field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetBootCdrom() *ResourceReference { if o == nil { return nil } - return o.Name + return o.BootCdrom } -// GetNameOk returns a tuple with the Name field value +// GetBootCdromOk returns a tuple with the BootCdrom field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetNameOk() (*string, bool) { +func (o *ServerProperties) GetBootCdromOk() (*ResourceReference, bool) { if o == nil { return nil, false } - return o.Name, true + return o.BootCdrom, true } -// SetName sets field value -func (o *ServerProperties) SetName(v string) { +// SetBootCdrom sets field value +func (o *ServerProperties) SetBootCdrom(v ResourceReference) { - o.Name = &v + o.BootCdrom = &v } -// HasName returns a boolean if a field has been set. -func (o *ServerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasBootCdrom returns a boolean if a field has been set. +func (o *ServerProperties) HasBootCdrom() bool { + if o != nil && o.BootCdrom != nil { return true } return false } -// GetCores returns the Cores field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ServerProperties) GetCores() *int32 { +// GetBootVolume returns the BootVolume field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetBootVolume() *ResourceReference { if o == nil { return nil } - return o.Cores + return o.BootVolume } -// GetCoresOk returns a tuple with the Cores field value +// GetBootVolumeOk returns a tuple with the BootVolume field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetCoresOk() (*int32, bool) { +func (o *ServerProperties) GetBootVolumeOk() (*ResourceReference, bool) { if o == nil { return nil, false } - return o.Cores, true + return o.BootVolume, true } -// SetCores sets field value -func (o *ServerProperties) SetCores(v int32) { +// SetBootVolume sets field value +func (o *ServerProperties) SetBootVolume(v ResourceReference) { - o.Cores = &v + o.BootVolume = &v } -// HasCores returns a boolean if a field has been set. -func (o *ServerProperties) HasCores() bool { - if o != nil && o.Cores != nil { +// HasBootVolume returns a boolean if a field has been set. +func (o *ServerProperties) HasBootVolume() bool { + if o != nil && o.BootVolume != nil { return true } return false } -// GetRam returns the Ram field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ServerProperties) GetRam() *int32 { +// GetCores returns the Cores field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetCores() *int32 { if o == nil { return nil } - return o.Ram + return o.Cores } -// GetRamOk returns a tuple with the Ram field value +// GetCoresOk returns a tuple with the Cores field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetRamOk() (*int32, bool) { +func (o *ServerProperties) GetCoresOk() (*int32, bool) { if o == nil { return nil, false } - return o.Ram, true + return o.Cores, true } -// SetRam sets field value -func (o *ServerProperties) SetRam(v int32) { +// SetCores sets field value +func (o *ServerProperties) SetCores(v int32) { - o.Ram = &v + o.Cores = &v } -// HasRam returns a boolean if a field has been set. -func (o *ServerProperties) HasRam() bool { - if o != nil && o.Ram != nil { +// HasCores returns a boolean if a field has been set. +func (o *ServerProperties) HasCores() bool { + if o != nil && o.Cores != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetAvailabilityZone() *string { +// GetCpuFamily returns the CpuFamily field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetCpuFamily() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.CpuFamily } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetCpuFamilyOk returns a tuple with the CpuFamily field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetAvailabilityZoneOk() (*string, bool) { +func (o *ServerProperties) GetCpuFamilyOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.CpuFamily, true } -// SetAvailabilityZone sets field value -func (o *ServerProperties) SetAvailabilityZone(v string) { +// SetCpuFamily sets field value +func (o *ServerProperties) SetCpuFamily(v string) { - o.AvailabilityZone = &v + o.CpuFamily = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *ServerProperties) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasCpuFamily returns a boolean if a field has been set. +func (o *ServerProperties) HasCpuFamily() bool { + if o != nil && o.CpuFamily != nil { return true } return false } -// GetVmState returns the VmState field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetVmState() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetName() *string { if o == nil { return nil } - return o.VmState + return o.Name } -// GetVmStateOk returns a tuple with the VmState field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetVmStateOk() (*string, bool) { +func (o *ServerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.VmState, true + return o.Name, true } -// SetVmState sets field value -func (o *ServerProperties) SetVmState(v string) { +// SetName sets field value +func (o *ServerProperties) SetName(v string) { - o.VmState = &v + o.Name = &v } -// HasVmState returns a boolean if a field has been set. -func (o *ServerProperties) HasVmState() bool { - if o != nil && o.VmState != nil { +// HasName returns a boolean if a field has been set. +func (o *ServerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetBootCdrom returns the BootCdrom field value -// If the value is explicit nil, the zero value for ResourceReference will be returned -func (o *ServerProperties) GetBootCdrom() *ResourceReference { +// GetPlacementGroupId returns the PlacementGroupId field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetPlacementGroupId() *string { if o == nil { return nil } - return o.BootCdrom + return o.PlacementGroupId } -// GetBootCdromOk returns a tuple with the BootCdrom field value +// GetPlacementGroupIdOk returns a tuple with the PlacementGroupId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetBootCdromOk() (*ResourceReference, bool) { +func (o *ServerProperties) GetPlacementGroupIdOk() (*string, bool) { if o == nil { return nil, false } - return o.BootCdrom, true + return o.PlacementGroupId, true } -// SetBootCdrom sets field value -func (o *ServerProperties) SetBootCdrom(v ResourceReference) { +// SetPlacementGroupId sets field value +func (o *ServerProperties) SetPlacementGroupId(v string) { - o.BootCdrom = &v + o.PlacementGroupId = &v } -// HasBootCdrom returns a boolean if a field has been set. -func (o *ServerProperties) HasBootCdrom() bool { - if o != nil && o.BootCdrom != nil { +// HasPlacementGroupId returns a boolean if a field has been set. +func (o *ServerProperties) HasPlacementGroupId() bool { + if o != nil && o.PlacementGroupId != nil { return true } return false } -// GetBootVolume returns the BootVolume field value -// If the value is explicit nil, the zero value for ResourceReference will be returned -func (o *ServerProperties) GetBootVolume() *ResourceReference { +// GetRam returns the Ram field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetRam() *int32 { if o == nil { return nil } - return o.BootVolume + return o.Ram } -// GetBootVolumeOk returns a tuple with the BootVolume field value +// GetRamOk returns a tuple with the Ram field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetBootVolumeOk() (*ResourceReference, bool) { +func (o *ServerProperties) GetRamOk() (*int32, bool) { if o == nil { return nil, false } - return o.BootVolume, true + return o.Ram, true } -// SetBootVolume sets field value -func (o *ServerProperties) SetBootVolume(v ResourceReference) { +// SetRam sets field value +func (o *ServerProperties) SetRam(v int32) { - o.BootVolume = &v + o.Ram = &v } -// HasBootVolume returns a boolean if a field has been set. -func (o *ServerProperties) HasBootVolume() bool { - if o != nil && o.BootVolume != nil { +// HasRam returns a boolean if a field has been set. +func (o *ServerProperties) HasRam() bool { + if o != nil && o.Ram != nil { return true } return false } -// GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetCpuFamily() *string { +// GetTemplateUuid returns the TemplateUuid field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetTemplateUuid() *string { if o == nil { return nil } - return o.CpuFamily + return o.TemplateUuid } -// GetCpuFamilyOk returns a tuple with the CpuFamily field value +// GetTemplateUuidOk returns a tuple with the TemplateUuid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetCpuFamilyOk() (*string, bool) { +func (o *ServerProperties) GetTemplateUuidOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuFamily, true + return o.TemplateUuid, true } -// SetCpuFamily sets field value -func (o *ServerProperties) SetCpuFamily(v string) { +// SetTemplateUuid sets field value +func (o *ServerProperties) SetTemplateUuid(v string) { - o.CpuFamily = &v + o.TemplateUuid = &v } -// HasCpuFamily returns a boolean if a field has been set. -func (o *ServerProperties) HasCpuFamily() bool { - if o != nil && o.CpuFamily != nil { +// HasTemplateUuid returns a boolean if a field has been set. +func (o *ServerProperties) HasTemplateUuid() bool { + if o != nil && o.TemplateUuid != nil { return true } @@ -397,7 +399,7 @@ func (o *ServerProperties) HasCpuFamily() bool { } // GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ServerProperties) GetType() *string { if o == nil { return nil @@ -434,38 +436,90 @@ func (o *ServerProperties) HasType() bool { return false } -func (o ServerProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.TemplateUuid != nil { - toSerialize["templateUuid"] = o.TemplateUuid - } - if o.Name != nil { - toSerialize["name"] = o.Name +// GetVmState returns the VmState field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetVmState() *string { + if o == nil { + return nil } - if o.Cores != nil { - toSerialize["cores"] = o.Cores + + return o.VmState + +} + +// GetVmStateOk returns a tuple with the VmState field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *ServerProperties) GetVmStateOk() (*string, bool) { + if o == nil { + return nil, false } - if o.Ram != nil { - toSerialize["ram"] = o.Ram + + return o.VmState, true +} + +// SetVmState sets field value +func (o *ServerProperties) SetVmState(v string) { + + o.VmState = &v + +} + +// HasVmState returns a boolean if a field has been set. +func (o *ServerProperties) HasVmState() bool { + if o != nil && o.VmState != nil { + return true } + + return false +} + +func (o ServerProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} if o.AvailabilityZone != nil { toSerialize["availabilityZone"] = o.AvailabilityZone } - if o.VmState != nil { - toSerialize["vmState"] = o.VmState - } + if o.BootCdrom != nil { toSerialize["bootCdrom"] = o.BootCdrom } + if o.BootVolume != nil { toSerialize["bootVolume"] = o.BootVolume } + + if o.Cores != nil { + toSerialize["cores"] = o.Cores + } + if o.CpuFamily != nil { toSerialize["cpuFamily"] = o.CpuFamily } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.PlacementGroupId != nil { + toSerialize["placementGroupId"] = o.PlacementGroupId + } + + if o.Ram != nil { + toSerialize["ram"] = o.Ram + } + + if o.TemplateUuid != nil { + toSerialize["templateUuid"] = o.TemplateUuid + } + if o.Type != nil { toSerialize["type"] = o.Type } + + if o.VmState != nil { + toSerialize["vmState"] = o.VmState + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go index 86fe0d2de..789aeaeb5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go @@ -16,19 +16,19 @@ import ( // Servers struct for Servers type Servers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Server `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewServers instantiates a new Servers object @@ -49,114 +49,114 @@ func NewServersWithDefaults() *Servers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Servers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetIdOk() (*string, bool) { +func (o *Servers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Servers) SetId(v string) { +// SetLinks sets field value +func (o *Servers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Servers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Servers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Servers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetTypeOk() (*Type, bool) { +func (o *Servers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Servers) SetType(v Type) { +// SetHref sets field value +func (o *Servers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Servers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Servers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Servers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetHrefOk() (*string, bool) { +func (o *Servers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Servers) SetHref(v string) { +// SetId sets field value +func (o *Servers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Servers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Servers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Servers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Server will be returned +// If the value is explicit nil, nil is returned func (o *Servers) GetItems() *[]Server { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Servers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Servers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetOffsetOk() (*float32, bool) { +func (o *Servers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Servers) SetOffset(v float32) { +// SetLimit sets field value +func (o *Servers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Servers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Servers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Servers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetLimitOk() (*float32, bool) { +func (o *Servers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Servers) SetLimit(v float32) { +// SetOffset sets field value +func (o *Servers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Servers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Servers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Servers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetLinksOk() (*PaginationLinks, bool) { +func (o *Servers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Servers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Servers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Servers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Servers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Servers) HasLinks() bool { func (o Servers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go index 56ebb960d..c42cc0546 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go @@ -16,14 +16,14 @@ import ( // Snapshot struct for Snapshot type Snapshot struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *SnapshotProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewSnapshot instantiates a new Snapshot object @@ -46,190 +46,190 @@ func NewSnapshotWithDefaults() *Snapshot { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshot) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetIdOk() (*string, bool) { +func (o *Snapshot) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Snapshot) SetId(v string) { +// SetHref sets field value +func (o *Snapshot) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Snapshot) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Snapshot) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Snapshot) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetTypeOk() (*Type, bool) { +func (o *Snapshot) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Snapshot) SetType(v Type) { +// SetId sets field value +func (o *Snapshot) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Snapshot) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Snapshot) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshot) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetHrefOk() (*string, bool) { +func (o *Snapshot) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Snapshot) SetHref(v string) { +// SetMetadata sets field value +func (o *Snapshot) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Snapshot) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Snapshot) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Snapshot) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetProperties() *SnapshotProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Snapshot) GetPropertiesOk() (*SnapshotProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Snapshot) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Snapshot) SetProperties(v SnapshotProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Snapshot) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Snapshot) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for SnapshotProperties will be returned -func (o *Snapshot) GetProperties() *SnapshotProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetPropertiesOk() (*SnapshotProperties, bool) { +func (o *Snapshot) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Snapshot) SetProperties(v SnapshotProperties) { +// SetType sets field value +func (o *Snapshot) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Snapshot) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Snapshot) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Snapshot) HasProperties() bool { func (o Snapshot) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go index b42dca20c..5eb8cea6e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go @@ -16,38 +16,38 @@ import ( // SnapshotProperties struct for SnapshotProperties type SnapshotProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // Human-readable description. - Description *string `json:"description,omitempty"` - // Location of that image/snapshot. - Location *string `json:"location,omitempty"` - // The size of the image in GB. - Size *float32 `json:"size,omitempty"` - // Boolean value representing if the snapshot requires extra protection, such as two-step verification. - SecAuthProtection *bool `json:"secAuthProtection,omitempty"` // Hot-plug capable CPU (no reboot required). CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` // Hot-unplug capable CPU (no reboot required). CpuHotUnplug *bool `json:"cpuHotUnplug,omitempty"` - // Hot-plug capable RAM (no reboot required). - RamHotPlug *bool `json:"ramHotPlug,omitempty"` - // Hot-unplug capable RAM (no reboot required). - RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` - // Hot-plug capable NIC (no reboot required). - NicHotPlug *bool `json:"nicHotPlug,omitempty"` - // Hot-unplug capable NIC (no reboot required). - NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` - // Hot-plug capable Virt-IO drive (no reboot required). - DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` - // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. - DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` + // Human-readable description. + Description *string `json:"description,omitempty"` // Hot-plug capable SCSI drive (no reboot required). DiscScsiHotPlug *bool `json:"discScsiHotPlug,omitempty"` // Is capable of SCSI drive hot unplug (no reboot required). This works only for non-Windows virtual Machines. DiscScsiHotUnplug *bool `json:"discScsiHotUnplug,omitempty"` + // Hot-plug capable Virt-IO drive (no reboot required). + DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` + // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. + DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` // OS type of this snapshot LicenceType *string `json:"licenceType,omitempty"` + // Location of that image/snapshot. + Location *string `json:"location,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` + // Hot-plug capable NIC (no reboot required). + NicHotPlug *bool `json:"nicHotPlug,omitempty"` + // Hot-unplug capable NIC (no reboot required). + NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` + // Hot-plug capable RAM (no reboot required). + RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // Hot-unplug capable RAM (no reboot required). + RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` + // Boolean value representing if the snapshot requires extra protection, such as two-step verification. + SecAuthProtection *bool `json:"secAuthProtection,omitempty"` + // The size of the image in GB. + Size *float32 `json:"size,omitempty"` } // NewSnapshotProperties instantiates a new SnapshotProperties object @@ -68,38 +68,76 @@ func NewSnapshotPropertiesWithDefaults() *SnapshotProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *SnapshotProperties) GetName() *string { +// GetCpuHotPlug returns the CpuHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetCpuHotPlug() *bool { if o == nil { return nil } - return o.Name + return o.CpuHotPlug } -// GetNameOk returns a tuple with the Name field value +// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetNameOk() (*string, bool) { +func (o *SnapshotProperties) GetCpuHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CpuHotPlug, true } -// SetName sets field value -func (o *SnapshotProperties) SetName(v string) { +// SetCpuHotPlug sets field value +func (o *SnapshotProperties) SetCpuHotPlug(v bool) { - o.Name = &v + o.CpuHotPlug = &v } -// HasName returns a boolean if a field has been set. -func (o *SnapshotProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCpuHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasCpuHotPlug() bool { + if o != nil && o.CpuHotPlug != nil { + return true + } + + return false +} + +// GetCpuHotUnplug returns the CpuHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetCpuHotUnplug() *bool { + if o == nil { + return nil + } + + return o.CpuHotUnplug + +} + +// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *SnapshotProperties) GetCpuHotUnplugOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.CpuHotUnplug, true +} + +// SetCpuHotUnplug sets field value +func (o *SnapshotProperties) SetCpuHotUnplug(v bool) { + + o.CpuHotUnplug = &v + +} + +// HasCpuHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasCpuHotUnplug() bool { + if o != nil && o.CpuHotUnplug != nil { return true } @@ -107,7 +145,7 @@ func (o *SnapshotProperties) HasName() bool { } // GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *SnapshotProperties) GetDescription() *string { if o == nil { return nil @@ -144,266 +182,266 @@ func (o *SnapshotProperties) HasDescription() bool { return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *SnapshotProperties) GetLocation() *string { +// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscScsiHotPlug() *bool { if o == nil { return nil } - return o.Location + return o.DiscScsiHotPlug } -// GetLocationOk returns a tuple with the Location field value +// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetLocationOk() (*string, bool) { +func (o *SnapshotProperties) GetDiscScsiHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Location, true + return o.DiscScsiHotPlug, true } -// SetLocation sets field value -func (o *SnapshotProperties) SetLocation(v string) { +// SetDiscScsiHotPlug sets field value +func (o *SnapshotProperties) SetDiscScsiHotPlug(v bool) { - o.Location = &v + o.DiscScsiHotPlug = &v } -// HasLocation returns a boolean if a field has been set. -func (o *SnapshotProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasDiscScsiHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscScsiHotPlug() bool { + if o != nil && o.DiscScsiHotPlug != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *SnapshotProperties) GetSize() *float32 { +// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscScsiHotUnplug() *bool { if o == nil { return nil } - return o.Size + return o.DiscScsiHotUnplug } -// GetSizeOk returns a tuple with the Size field value +// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetSizeOk() (*float32, bool) { +func (o *SnapshotProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Size, true + return o.DiscScsiHotUnplug, true } -// SetSize sets field value -func (o *SnapshotProperties) SetSize(v float32) { +// SetDiscScsiHotUnplug sets field value +func (o *SnapshotProperties) SetDiscScsiHotUnplug(v bool) { - o.Size = &v + o.DiscScsiHotUnplug = &v } -// HasSize returns a boolean if a field has been set. -func (o *SnapshotProperties) HasSize() bool { - if o != nil && o.Size != nil { +// HasDiscScsiHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscScsiHotUnplug() bool { + if o != nil && o.DiscScsiHotUnplug != nil { return true } return false } -// GetSecAuthProtection returns the SecAuthProtection field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetSecAuthProtection() *bool { +// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscVirtioHotPlug() *bool { if o == nil { return nil } - return o.SecAuthProtection + return o.DiscVirtioHotPlug } -// GetSecAuthProtectionOk returns a tuple with the SecAuthProtection field value +// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetSecAuthProtectionOk() (*bool, bool) { +func (o *SnapshotProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.SecAuthProtection, true + return o.DiscVirtioHotPlug, true } -// SetSecAuthProtection sets field value -func (o *SnapshotProperties) SetSecAuthProtection(v bool) { +// SetDiscVirtioHotPlug sets field value +func (o *SnapshotProperties) SetDiscVirtioHotPlug(v bool) { - o.SecAuthProtection = &v + o.DiscVirtioHotPlug = &v } -// HasSecAuthProtection returns a boolean if a field has been set. -func (o *SnapshotProperties) HasSecAuthProtection() bool { - if o != nil && o.SecAuthProtection != nil { +// HasDiscVirtioHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscVirtioHotPlug() bool { + if o != nil && o.DiscVirtioHotPlug != nil { return true } return false } -// GetCpuHotPlug returns the CpuHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetCpuHotPlug() *bool { +// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscVirtioHotUnplug() *bool { if o == nil { return nil } - return o.CpuHotPlug + return o.DiscVirtioHotUnplug } -// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value +// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetCpuHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.CpuHotPlug, true + return o.DiscVirtioHotUnplug, true } -// SetCpuHotPlug sets field value -func (o *SnapshotProperties) SetCpuHotPlug(v bool) { +// SetDiscVirtioHotUnplug sets field value +func (o *SnapshotProperties) SetDiscVirtioHotUnplug(v bool) { - o.CpuHotPlug = &v + o.DiscVirtioHotUnplug = &v } -// HasCpuHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasCpuHotPlug() bool { - if o != nil && o.CpuHotPlug != nil { +// HasDiscVirtioHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscVirtioHotUnplug() bool { + if o != nil && o.DiscVirtioHotUnplug != nil { return true } return false } -// GetCpuHotUnplug returns the CpuHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetCpuHotUnplug() *bool { +// GetLicenceType returns the LicenceType field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetLicenceType() *string { if o == nil { return nil } - return o.CpuHotUnplug + return o.LicenceType } -// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value +// GetLicenceTypeOk returns a tuple with the LicenceType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetCpuHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetLicenceTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuHotUnplug, true + return o.LicenceType, true } -// SetCpuHotUnplug sets field value -func (o *SnapshotProperties) SetCpuHotUnplug(v bool) { +// SetLicenceType sets field value +func (o *SnapshotProperties) SetLicenceType(v string) { - o.CpuHotUnplug = &v + o.LicenceType = &v } -// HasCpuHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasCpuHotUnplug() bool { - if o != nil && o.CpuHotUnplug != nil { +// HasLicenceType returns a boolean if a field has been set. +func (o *SnapshotProperties) HasLicenceType() bool { + if o != nil && o.LicenceType != nil { return true } return false } -// GetRamHotPlug returns the RamHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetRamHotPlug() *bool { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetLocation() *string { if o == nil { return nil } - return o.RamHotPlug + return o.Location } -// GetRamHotPlugOk returns a tuple with the RamHotPlug field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetRamHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.RamHotPlug, true + return o.Location, true } -// SetRamHotPlug sets field value -func (o *SnapshotProperties) SetRamHotPlug(v bool) { +// SetLocation sets field value +func (o *SnapshotProperties) SetLocation(v string) { - o.RamHotPlug = &v + o.Location = &v } -// HasRamHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasRamHotPlug() bool { - if o != nil && o.RamHotPlug != nil { +// HasLocation returns a boolean if a field has been set. +func (o *SnapshotProperties) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetRamHotUnplug returns the RamHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetRamHotUnplug() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetName() *string { if o == nil { return nil } - return o.RamHotUnplug + return o.Name } -// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetRamHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.RamHotUnplug, true + return o.Name, true } -// SetRamHotUnplug sets field value -func (o *SnapshotProperties) SetRamHotUnplug(v bool) { +// SetName sets field value +func (o *SnapshotProperties) SetName(v string) { - o.RamHotUnplug = &v + o.Name = &v } -// HasRamHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasRamHotUnplug() bool { - if o != nil && o.RamHotUnplug != nil { +// HasName returns a boolean if a field has been set. +func (o *SnapshotProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -411,7 +449,7 @@ func (o *SnapshotProperties) HasRamHotUnplug() bool { } // GetNicHotPlug returns the NicHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *SnapshotProperties) GetNicHotPlug() *bool { if o == nil { return nil @@ -449,7 +487,7 @@ func (o *SnapshotProperties) HasNicHotPlug() bool { } // GetNicHotUnplug returns the NicHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *SnapshotProperties) GetNicHotUnplug() *bool { if o == nil { return nil @@ -486,246 +524,224 @@ func (o *SnapshotProperties) HasNicHotUnplug() bool { return false } -// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscVirtioHotPlug() *bool { +// GetRamHotPlug returns the RamHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetRamHotPlug() *bool { if o == nil { return nil } - return o.DiscVirtioHotPlug + return o.RamHotPlug } -// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value +// GetRamHotPlugOk returns a tuple with the RamHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetRamHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotPlug, true + return o.RamHotPlug, true } -// SetDiscVirtioHotPlug sets field value -func (o *SnapshotProperties) SetDiscVirtioHotPlug(v bool) { +// SetRamHotPlug sets field value +func (o *SnapshotProperties) SetRamHotPlug(v bool) { - o.DiscVirtioHotPlug = &v + o.RamHotPlug = &v } -// HasDiscVirtioHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscVirtioHotPlug() bool { - if o != nil && o.DiscVirtioHotPlug != nil { +// HasRamHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasRamHotPlug() bool { + if o != nil && o.RamHotPlug != nil { return true } return false } -// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscVirtioHotUnplug() *bool { +// GetRamHotUnplug returns the RamHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetRamHotUnplug() *bool { if o == nil { return nil } - return o.DiscVirtioHotUnplug + return o.RamHotUnplug } -// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value +// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetRamHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotUnplug, true + return o.RamHotUnplug, true } -// SetDiscVirtioHotUnplug sets field value -func (o *SnapshotProperties) SetDiscVirtioHotUnplug(v bool) { +// SetRamHotUnplug sets field value +func (o *SnapshotProperties) SetRamHotUnplug(v bool) { - o.DiscVirtioHotUnplug = &v + o.RamHotUnplug = &v } -// HasDiscVirtioHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscVirtioHotUnplug() bool { - if o != nil && o.DiscVirtioHotUnplug != nil { +// HasRamHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasRamHotUnplug() bool { + if o != nil && o.RamHotUnplug != nil { return true } return false } -// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscScsiHotPlug() *bool { +// GetSecAuthProtection returns the SecAuthProtection field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetSecAuthProtection() *bool { if o == nil { return nil } - return o.DiscScsiHotPlug + return o.SecAuthProtection } -// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value +// GetSecAuthProtectionOk returns a tuple with the SecAuthProtection field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscScsiHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetSecAuthProtectionOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscScsiHotPlug, true + return o.SecAuthProtection, true } -// SetDiscScsiHotPlug sets field value -func (o *SnapshotProperties) SetDiscScsiHotPlug(v bool) { +// SetSecAuthProtection sets field value +func (o *SnapshotProperties) SetSecAuthProtection(v bool) { - o.DiscScsiHotPlug = &v + o.SecAuthProtection = &v } -// HasDiscScsiHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscScsiHotPlug() bool { - if o != nil && o.DiscScsiHotPlug != nil { +// HasSecAuthProtection returns a boolean if a field has been set. +func (o *SnapshotProperties) HasSecAuthProtection() bool { + if o != nil && o.SecAuthProtection != nil { return true } return false } -// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscScsiHotUnplug() *bool { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetSize() *float32 { if o == nil { return nil } - return o.DiscScsiHotUnplug + return o.Size } -// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetSizeOk() (*float32, bool) { if o == nil { return nil, false } - return o.DiscScsiHotUnplug, true + return o.Size, true } -// SetDiscScsiHotUnplug sets field value -func (o *SnapshotProperties) SetDiscScsiHotUnplug(v bool) { +// SetSize sets field value +func (o *SnapshotProperties) SetSize(v float32) { - o.DiscScsiHotUnplug = &v + o.Size = &v } -// HasDiscScsiHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscScsiHotUnplug() bool { - if o != nil && o.DiscScsiHotUnplug != nil { +// HasSize returns a boolean if a field has been set. +func (o *SnapshotProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } return false } -// GetLicenceType returns the LicenceType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *SnapshotProperties) GetLicenceType() *string { - if o == nil { - return nil +func (o SnapshotProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.CpuHotPlug != nil { + toSerialize["cpuHotPlug"] = o.CpuHotPlug } - return o.LicenceType - -} - -// GetLicenceTypeOk returns a tuple with the LicenceType field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetLicenceTypeOk() (*string, bool) { - if o == nil { - return nil, false + if o.CpuHotUnplug != nil { + toSerialize["cpuHotUnplug"] = o.CpuHotUnplug } - return o.LicenceType, true -} - -// SetLicenceType sets field value -func (o *SnapshotProperties) SetLicenceType(v string) { - - o.LicenceType = &v + if o.Description != nil { + toSerialize["description"] = o.Description + } -} + if o.DiscScsiHotPlug != nil { + toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug + } -// HasLicenceType returns a boolean if a field has been set. -func (o *SnapshotProperties) HasLicenceType() bool { - if o != nil && o.LicenceType != nil { - return true + if o.DiscScsiHotUnplug != nil { + toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug } - return false -} + if o.DiscVirtioHotPlug != nil { + toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug + } -func (o SnapshotProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.DiscVirtioHotUnplug != nil { + toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug } - if o.Description != nil { - toSerialize["description"] = o.Description + + if o.LicenceType != nil { + toSerialize["licenceType"] = o.LicenceType } + if o.Location != nil { toSerialize["location"] = o.Location } - if o.Size != nil { - toSerialize["size"] = o.Size - } - if o.SecAuthProtection != nil { - toSerialize["secAuthProtection"] = o.SecAuthProtection - } - if o.CpuHotPlug != nil { - toSerialize["cpuHotPlug"] = o.CpuHotPlug - } - if o.CpuHotUnplug != nil { - toSerialize["cpuHotUnplug"] = o.CpuHotUnplug - } - if o.RamHotPlug != nil { - toSerialize["ramHotPlug"] = o.RamHotPlug - } - if o.RamHotUnplug != nil { - toSerialize["ramHotUnplug"] = o.RamHotUnplug + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.NicHotPlug != nil { toSerialize["nicHotPlug"] = o.NicHotPlug } + if o.NicHotUnplug != nil { toSerialize["nicHotUnplug"] = o.NicHotUnplug } - if o.DiscVirtioHotPlug != nil { - toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug - } - if o.DiscVirtioHotUnplug != nil { - toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug + + if o.RamHotPlug != nil { + toSerialize["ramHotPlug"] = o.RamHotPlug } - if o.DiscScsiHotPlug != nil { - toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug + + if o.RamHotUnplug != nil { + toSerialize["ramHotUnplug"] = o.RamHotUnplug } - if o.DiscScsiHotUnplug != nil { - toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug + + if o.SecAuthProtection != nil { + toSerialize["secAuthProtection"] = o.SecAuthProtection } - if o.LicenceType != nil { - toSerialize["licenceType"] = o.LicenceType + + if o.Size != nil { + toSerialize["size"] = o.Size } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go index 8578d03dd..313d03e09 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go @@ -16,14 +16,14 @@ import ( // Snapshots struct for Snapshots type Snapshots struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Snapshot `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewSnapshots instantiates a new Snapshots object @@ -44,152 +44,152 @@ func NewSnapshotsWithDefaults() *Snapshots { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshots) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetIdOk() (*string, bool) { +func (o *Snapshots) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Snapshots) SetId(v string) { +// SetHref sets field value +func (o *Snapshots) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Snapshots) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Snapshots) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Snapshots) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetTypeOk() (*Type, bool) { +func (o *Snapshots) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Snapshots) SetType(v Type) { +// SetId sets field value +func (o *Snapshots) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Snapshots) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Snapshots) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshots) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetItems() *[]Snapshot { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetHrefOk() (*string, bool) { +func (o *Snapshots) GetItemsOk() (*[]Snapshot, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Snapshots) SetHref(v string) { +// SetItems sets field value +func (o *Snapshots) SetItems(v []Snapshot) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Snapshots) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Snapshots) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Snapshot will be returned -func (o *Snapshots) GetItems() *[]Snapshot { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetItemsOk() (*[]Snapshot, bool) { +func (o *Snapshots) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Snapshots) SetItems(v []Snapshot) { +// SetType sets field value +func (o *Snapshots) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Snapshots) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Snapshots) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Snapshots) HasItems() bool { func (o Snapshots) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go index 95d71efea..cbfb0271f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go @@ -16,14 +16,14 @@ import ( // TargetGroup struct for TargetGroup type TargetGroup struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *TargetGroupProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTargetGroup instantiates a new TargetGroup object @@ -46,190 +46,190 @@ func NewTargetGroupWithDefaults() *TargetGroup { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroup) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetIdOk() (*string, bool) { +func (o *TargetGroup) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *TargetGroup) SetId(v string) { +// SetHref sets field value +func (o *TargetGroup) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *TargetGroup) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *TargetGroup) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *TargetGroup) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetTypeOk() (*Type, bool) { +func (o *TargetGroup) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *TargetGroup) SetType(v Type) { +// SetId sets field value +func (o *TargetGroup) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *TargetGroup) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *TargetGroup) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroup) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetHrefOk() (*string, bool) { +func (o *TargetGroup) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *TargetGroup) SetHref(v string) { +// SetMetadata sets field value +func (o *TargetGroup) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *TargetGroup) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *TargetGroup) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *TargetGroup) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetProperties() *TargetGroupProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *TargetGroup) GetPropertiesOk() (*TargetGroupProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *TargetGroup) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *TargetGroup) SetProperties(v TargetGroupProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *TargetGroup) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *TargetGroup) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for TargetGroupProperties will be returned -func (o *TargetGroup) GetProperties() *TargetGroupProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetPropertiesOk() (*TargetGroupProperties, bool) { +func (o *TargetGroup) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *TargetGroup) SetProperties(v TargetGroupProperties) { +// SetType sets field value +func (o *TargetGroup) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *TargetGroup) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *TargetGroup) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *TargetGroup) HasProperties() bool { func (o TargetGroup) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go index 5c8dfdfc6..70ca3dc63 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go @@ -16,10 +16,10 @@ import ( // TargetGroupHealthCheck struct for TargetGroupHealthCheck type TargetGroupHealthCheck struct { - // The maximum time in milliseconds is to wait for a target to respond to a check. For target VMs with a 'Check Interval' set, the smaller of the two values is used once the TCP connection is established. - CheckTimeout *int32 `json:"checkTimeout,omitempty"` // The interval in milliseconds between consecutive health checks; the default value is '2000'. CheckInterval *int32 `json:"checkInterval,omitempty"` + // The maximum time in milliseconds is to wait for a target to respond to a check. For target VMs with a 'Check Interval' set, the smaller of the two values is used once the TCP connection is established. + CheckTimeout *int32 `json:"checkTimeout,omitempty"` // The maximum number of attempts to reconnect to a target after a connection failure. The valid range is '0 to 65535'; the default value is '3'. Retries *int32 `json:"retries,omitempty"` } @@ -42,76 +42,76 @@ func NewTargetGroupHealthCheckWithDefaults() *TargetGroupHealthCheck { return &this } -// GetCheckTimeout returns the CheckTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupHealthCheck) GetCheckTimeout() *int32 { +// GetCheckInterval returns the CheckInterval field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHealthCheck) GetCheckInterval() *int32 { if o == nil { return nil } - return o.CheckTimeout + return o.CheckInterval } -// GetCheckTimeoutOk returns a tuple with the CheckTimeout field value +// GetCheckIntervalOk returns a tuple with the CheckInterval field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHealthCheck) GetCheckTimeoutOk() (*int32, bool) { +func (o *TargetGroupHealthCheck) GetCheckIntervalOk() (*int32, bool) { if o == nil { return nil, false } - return o.CheckTimeout, true + return o.CheckInterval, true } -// SetCheckTimeout sets field value -func (o *TargetGroupHealthCheck) SetCheckTimeout(v int32) { +// SetCheckInterval sets field value +func (o *TargetGroupHealthCheck) SetCheckInterval(v int32) { - o.CheckTimeout = &v + o.CheckInterval = &v } -// HasCheckTimeout returns a boolean if a field has been set. -func (o *TargetGroupHealthCheck) HasCheckTimeout() bool { - if o != nil && o.CheckTimeout != nil { +// HasCheckInterval returns a boolean if a field has been set. +func (o *TargetGroupHealthCheck) HasCheckInterval() bool { + if o != nil && o.CheckInterval != nil { return true } return false } -// GetCheckInterval returns the CheckInterval field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupHealthCheck) GetCheckInterval() *int32 { +// GetCheckTimeout returns the CheckTimeout field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHealthCheck) GetCheckTimeout() *int32 { if o == nil { return nil } - return o.CheckInterval + return o.CheckTimeout } -// GetCheckIntervalOk returns a tuple with the CheckInterval field value +// GetCheckTimeoutOk returns a tuple with the CheckTimeout field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHealthCheck) GetCheckIntervalOk() (*int32, bool) { +func (o *TargetGroupHealthCheck) GetCheckTimeoutOk() (*int32, bool) { if o == nil { return nil, false } - return o.CheckInterval, true + return o.CheckTimeout, true } -// SetCheckInterval sets field value -func (o *TargetGroupHealthCheck) SetCheckInterval(v int32) { +// SetCheckTimeout sets field value +func (o *TargetGroupHealthCheck) SetCheckTimeout(v int32) { - o.CheckInterval = &v + o.CheckTimeout = &v } -// HasCheckInterval returns a boolean if a field has been set. -func (o *TargetGroupHealthCheck) HasCheckInterval() bool { - if o != nil && o.CheckInterval != nil { +// HasCheckTimeout returns a boolean if a field has been set. +func (o *TargetGroupHealthCheck) HasCheckTimeout() bool { + if o != nil && o.CheckTimeout != nil { return true } @@ -119,7 +119,7 @@ func (o *TargetGroupHealthCheck) HasCheckInterval() bool { } // GetRetries returns the Retries field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroupHealthCheck) GetRetries() *int32 { if o == nil { return nil @@ -158,15 +158,18 @@ func (o *TargetGroupHealthCheck) HasRetries() bool { func (o TargetGroupHealthCheck) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.CheckTimeout != nil { - toSerialize["checkTimeout"] = o.CheckTimeout - } if o.CheckInterval != nil { toSerialize["checkInterval"] = o.CheckInterval } + + if o.CheckTimeout != nil { + toSerialize["checkTimeout"] = o.CheckTimeout + } + if o.Retries != nil { toSerialize["retries"] = o.Retries } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go index 274f7b911..dc31f4950 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go @@ -16,18 +16,18 @@ import ( // TargetGroupHttpHealthCheck struct for TargetGroupHttpHealthCheck type TargetGroupHttpHealthCheck struct { - // The destination URL for HTTP the health check; the default is '/'. - Path *string `json:"path,omitempty"` - // The method used for the health check request. - Method *string `json:"method,omitempty"` // Specify the target's response type to match ALB's request. MatchType *string `json:"matchType"` - // The response returned by the request. It can be a status code or a response body depending on the definition of 'matchType'. - Response *string `json:"response"` - // Specifies whether to use a regular expression to parse the response body; the default value is 'FALSE'. By using regular expressions, you can flexibly customize the expected response from a healthy server. - Regex *bool `json:"regex,omitempty"` + // The method used for the health check request. + Method *string `json:"method,omitempty"` // Specifies whether to negate an individual entry; the default value is 'FALSE'. Negate *bool `json:"negate,omitempty"` + // The destination URL for HTTP the health check; the default is '/'. + Path *string `json:"path,omitempty"` + // Specifies whether to use a regular expression to parse the response body; the default value is 'FALSE'. By using regular expressions, you can flexibly customize the expected response from a healthy server. + Regex *bool `json:"regex,omitempty"` + // The response returned by the request. It can be a status code or a response body depending on the definition of 'matchType'. + Response *string `json:"response"` } // NewTargetGroupHttpHealthCheck instantiates a new TargetGroupHttpHealthCheck object @@ -51,38 +51,38 @@ func NewTargetGroupHttpHealthCheckWithDefaults() *TargetGroupHttpHealthCheck { return &this } -// GetPath returns the Path field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupHttpHealthCheck) GetPath() *string { +// GetMatchType returns the MatchType field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetMatchType() *string { if o == nil { return nil } - return o.Path + return o.MatchType } -// GetPathOk returns a tuple with the Path field value +// GetMatchTypeOk returns a tuple with the MatchType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetPathOk() (*string, bool) { +func (o *TargetGroupHttpHealthCheck) GetMatchTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Path, true + return o.MatchType, true } -// SetPath sets field value -func (o *TargetGroupHttpHealthCheck) SetPath(v string) { +// SetMatchType sets field value +func (o *TargetGroupHttpHealthCheck) SetMatchType(v string) { - o.Path = &v + o.MatchType = &v } -// HasPath returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasPath() bool { - if o != nil && o.Path != nil { +// HasMatchType returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasMatchType() bool { + if o != nil && o.MatchType != nil { return true } @@ -90,7 +90,7 @@ func (o *TargetGroupHttpHealthCheck) HasPath() bool { } // GetMethod returns the Method field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroupHttpHealthCheck) GetMethod() *string { if o == nil { return nil @@ -127,76 +127,76 @@ func (o *TargetGroupHttpHealthCheck) HasMethod() bool { return false } -// GetMatchType returns the MatchType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupHttpHealthCheck) GetMatchType() *string { +// GetNegate returns the Negate field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetNegate() *bool { if o == nil { return nil } - return o.MatchType + return o.Negate } -// GetMatchTypeOk returns a tuple with the MatchType field value +// GetNegateOk returns a tuple with the Negate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetMatchTypeOk() (*string, bool) { +func (o *TargetGroupHttpHealthCheck) GetNegateOk() (*bool, bool) { if o == nil { return nil, false } - return o.MatchType, true + return o.Negate, true } -// SetMatchType sets field value -func (o *TargetGroupHttpHealthCheck) SetMatchType(v string) { +// SetNegate sets field value +func (o *TargetGroupHttpHealthCheck) SetNegate(v bool) { - o.MatchType = &v + o.Negate = &v } -// HasMatchType returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasMatchType() bool { - if o != nil && o.MatchType != nil { +// HasNegate returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasNegate() bool { + if o != nil && o.Negate != nil { return true } return false } -// GetResponse returns the Response field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupHttpHealthCheck) GetResponse() *string { +// GetPath returns the Path field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetPath() *string { if o == nil { return nil } - return o.Response + return o.Path } -// GetResponseOk returns a tuple with the Response field value +// GetPathOk returns a tuple with the Path field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetResponseOk() (*string, bool) { +func (o *TargetGroupHttpHealthCheck) GetPathOk() (*string, bool) { if o == nil { return nil, false } - return o.Response, true + return o.Path, true } -// SetResponse sets field value -func (o *TargetGroupHttpHealthCheck) SetResponse(v string) { +// SetPath sets field value +func (o *TargetGroupHttpHealthCheck) SetPath(v string) { - o.Response = &v + o.Path = &v } -// HasResponse returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasResponse() bool { - if o != nil && o.Response != nil { +// HasPath returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasPath() bool { + if o != nil && o.Path != nil { return true } @@ -204,7 +204,7 @@ func (o *TargetGroupHttpHealthCheck) HasResponse() bool { } // GetRegex returns the Regex field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroupHttpHealthCheck) GetRegex() *bool { if o == nil { return nil @@ -241,38 +241,38 @@ func (o *TargetGroupHttpHealthCheck) HasRegex() bool { return false } -// GetNegate returns the Negate field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *TargetGroupHttpHealthCheck) GetNegate() *bool { +// GetResponse returns the Response field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetResponse() *string { if o == nil { return nil } - return o.Negate + return o.Response } -// GetNegateOk returns a tuple with the Negate field value +// GetResponseOk returns a tuple with the Response field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetNegateOk() (*bool, bool) { +func (o *TargetGroupHttpHealthCheck) GetResponseOk() (*string, bool) { if o == nil { return nil, false } - return o.Negate, true + return o.Response, true } -// SetNegate sets field value -func (o *TargetGroupHttpHealthCheck) SetNegate(v bool) { +// SetResponse sets field value +func (o *TargetGroupHttpHealthCheck) SetResponse(v string) { - o.Negate = &v + o.Response = &v } -// HasNegate returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasNegate() bool { - if o != nil && o.Negate != nil { +// HasResponse returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasResponse() bool { + if o != nil && o.Response != nil { return true } @@ -281,24 +281,30 @@ func (o *TargetGroupHttpHealthCheck) HasNegate() bool { func (o TargetGroupHttpHealthCheck) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Path != nil { - toSerialize["path"] = o.Path + if o.MatchType != nil { + toSerialize["matchType"] = o.MatchType } + if o.Method != nil { toSerialize["method"] = o.Method } - if o.MatchType != nil { - toSerialize["matchType"] = o.MatchType + + if o.Negate != nil { + toSerialize["negate"] = o.Negate } - if o.Response != nil { - toSerialize["response"] = o.Response + + if o.Path != nil { + toSerialize["path"] = o.Path } + if o.Regex != nil { toSerialize["regex"] = o.Regex } - if o.Negate != nil { - toSerialize["negate"] = o.Negate + + if o.Response != nil { + toSerialize["response"] = o.Response } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go index 3a79b8bc7..f14f3486f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go @@ -16,27 +16,27 @@ import ( // TargetGroupProperties struct for TargetGroupProperties type TargetGroupProperties struct { + // The balancing algorithm. A balancing algorithm consists of predefined rules with the logic that a load balancer uses to distribute network traffic between servers. - **Round Robin**: Targets are served alternately according to their weighting. - **Least Connection**: The target with the least active connection is served. - **Random**: The targets are served based on a consistent pseudorandom algorithm. - **Source IP**: It is ensured that the same client IP address reaches the same target. + Algorithm *string `json:"algorithm"` + HealthCheck *TargetGroupHealthCheck `json:"healthCheck,omitempty"` + HttpHealthCheck *TargetGroupHttpHealthCheck `json:"httpHealthCheck,omitempty"` // The target group name. Name *string `json:"name"` - // The balancing algorithm. A balancing algorithm consists of predefined rules with the logic that a load balancer uses to distribute network traffic between servers. - **Round Robin**: Targets are served alternately according to their weighting. - **Least Connection**: The target with the least active connection is served. - **Random**: The targets are served based on a consistent pseudorandom algorithm. - **Source IP**: It is ensured that the same client IP address reaches the same target. - Algorithm *string `json:"algorithm"` // The forwarding protocol. Only the value 'HTTP' is allowed. Protocol *string `json:"protocol"` // Array of items in the collection. - Targets *[]TargetGroupTarget `json:"targets,omitempty"` - HealthCheck *TargetGroupHealthCheck `json:"healthCheck,omitempty"` - HttpHealthCheck *TargetGroupHttpHealthCheck `json:"httpHealthCheck,omitempty"` + Targets *[]TargetGroupTarget `json:"targets,omitempty"` } // NewTargetGroupProperties instantiates a new TargetGroupProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewTargetGroupProperties(name string, algorithm string, protocol string) *TargetGroupProperties { +func NewTargetGroupProperties(algorithm string, name string, protocol string) *TargetGroupProperties { this := TargetGroupProperties{} - this.Name = &name this.Algorithm = &algorithm + this.Name = &name this.Protocol = &protocol return &this @@ -50,228 +50,228 @@ func NewTargetGroupPropertiesWithDefaults() *TargetGroupProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupProperties) GetName() *string { +// GetAlgorithm returns the Algorithm field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetAlgorithm() *string { if o == nil { return nil } - return o.Name + return o.Algorithm } -// GetNameOk returns a tuple with the Name field value +// GetAlgorithmOk returns a tuple with the Algorithm field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetNameOk() (*string, bool) { +func (o *TargetGroupProperties) GetAlgorithmOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Algorithm, true } -// SetName sets field value -func (o *TargetGroupProperties) SetName(v string) { +// SetAlgorithm sets field value +func (o *TargetGroupProperties) SetAlgorithm(v string) { - o.Name = &v + o.Algorithm = &v } -// HasName returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAlgorithm returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasAlgorithm() bool { + if o != nil && o.Algorithm != nil { return true } return false } -// GetAlgorithm returns the Algorithm field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupProperties) GetAlgorithm() *string { +// GetHealthCheck returns the HealthCheck field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetHealthCheck() *TargetGroupHealthCheck { if o == nil { return nil } - return o.Algorithm + return o.HealthCheck } -// GetAlgorithmOk returns a tuple with the Algorithm field value +// GetHealthCheckOk returns a tuple with the HealthCheck field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetAlgorithmOk() (*string, bool) { +func (o *TargetGroupProperties) GetHealthCheckOk() (*TargetGroupHealthCheck, bool) { if o == nil { return nil, false } - return o.Algorithm, true + return o.HealthCheck, true } -// SetAlgorithm sets field value -func (o *TargetGroupProperties) SetAlgorithm(v string) { +// SetHealthCheck sets field value +func (o *TargetGroupProperties) SetHealthCheck(v TargetGroupHealthCheck) { - o.Algorithm = &v + o.HealthCheck = &v } -// HasAlgorithm returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasAlgorithm() bool { - if o != nil && o.Algorithm != nil { +// HasHealthCheck returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasHealthCheck() bool { + if o != nil && o.HealthCheck != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupProperties) GetProtocol() *string { +// GetHttpHealthCheck returns the HttpHealthCheck field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetHttpHealthCheck() *TargetGroupHttpHealthCheck { if o == nil { return nil } - return o.Protocol + return o.HttpHealthCheck } -// GetProtocolOk returns a tuple with the Protocol field value +// GetHttpHealthCheckOk returns a tuple with the HttpHealthCheck field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetProtocolOk() (*string, bool) { +func (o *TargetGroupProperties) GetHttpHealthCheckOk() (*TargetGroupHttpHealthCheck, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.HttpHealthCheck, true } -// SetProtocol sets field value -func (o *TargetGroupProperties) SetProtocol(v string) { +// SetHttpHealthCheck sets field value +func (o *TargetGroupProperties) SetHttpHealthCheck(v TargetGroupHttpHealthCheck) { - o.Protocol = &v + o.HttpHealthCheck = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasHttpHealthCheck returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasHttpHealthCheck() bool { + if o != nil && o.HttpHealthCheck != nil { return true } return false } -// GetTargets returns the Targets field value -// If the value is explicit nil, the zero value for []TargetGroupTarget will be returned -func (o *TargetGroupProperties) GetTargets() *[]TargetGroupTarget { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetName() *string { if o == nil { return nil } - return o.Targets + return o.Name } -// GetTargetsOk returns a tuple with the Targets field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetTargetsOk() (*[]TargetGroupTarget, bool) { +func (o *TargetGroupProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Targets, true + return o.Name, true } -// SetTargets sets field value -func (o *TargetGroupProperties) SetTargets(v []TargetGroupTarget) { +// SetName sets field value +func (o *TargetGroupProperties) SetName(v string) { - o.Targets = &v + o.Name = &v } -// HasTargets returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasTargets() bool { - if o != nil && o.Targets != nil { +// HasName returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetHealthCheck returns the HealthCheck field value -// If the value is explicit nil, the zero value for TargetGroupHealthCheck will be returned -func (o *TargetGroupProperties) GetHealthCheck() *TargetGroupHealthCheck { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetProtocol() *string { if o == nil { return nil } - return o.HealthCheck + return o.Protocol } -// GetHealthCheckOk returns a tuple with the HealthCheck field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetHealthCheckOk() (*TargetGroupHealthCheck, bool) { +func (o *TargetGroupProperties) GetProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.HealthCheck, true + return o.Protocol, true } -// SetHealthCheck sets field value -func (o *TargetGroupProperties) SetHealthCheck(v TargetGroupHealthCheck) { +// SetProtocol sets field value +func (o *TargetGroupProperties) SetProtocol(v string) { - o.HealthCheck = &v + o.Protocol = &v } -// HasHealthCheck returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasHealthCheck() bool { - if o != nil && o.HealthCheck != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetHttpHealthCheck returns the HttpHealthCheck field value -// If the value is explicit nil, the zero value for TargetGroupHttpHealthCheck will be returned -func (o *TargetGroupProperties) GetHttpHealthCheck() *TargetGroupHttpHealthCheck { +// GetTargets returns the Targets field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetTargets() *[]TargetGroupTarget { if o == nil { return nil } - return o.HttpHealthCheck + return o.Targets } -// GetHttpHealthCheckOk returns a tuple with the HttpHealthCheck field value +// GetTargetsOk returns a tuple with the Targets field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetHttpHealthCheckOk() (*TargetGroupHttpHealthCheck, bool) { +func (o *TargetGroupProperties) GetTargetsOk() (*[]TargetGroupTarget, bool) { if o == nil { return nil, false } - return o.HttpHealthCheck, true + return o.Targets, true } -// SetHttpHealthCheck sets field value -func (o *TargetGroupProperties) SetHttpHealthCheck(v TargetGroupHttpHealthCheck) { +// SetTargets sets field value +func (o *TargetGroupProperties) SetTargets(v []TargetGroupTarget) { - o.HttpHealthCheck = &v + o.Targets = &v } -// HasHttpHealthCheck returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasHttpHealthCheck() bool { - if o != nil && o.HttpHealthCheck != nil { +// HasTargets returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasTargets() bool { + if o != nil && o.Targets != nil { return true } @@ -280,24 +280,30 @@ func (o *TargetGroupProperties) HasHttpHealthCheck() bool { func (o TargetGroupProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Algorithm != nil { toSerialize["algorithm"] = o.Algorithm } - if o.Protocol != nil { - toSerialize["protocol"] = o.Protocol - } - if o.Targets != nil { - toSerialize["targets"] = o.Targets - } + if o.HealthCheck != nil { toSerialize["healthCheck"] = o.HealthCheck } + if o.HttpHealthCheck != nil { toSerialize["httpHealthCheck"] = o.HttpHealthCheck } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.Protocol != nil { + toSerialize["protocol"] = o.Protocol + } + + if o.Targets != nil { + toSerialize["targets"] = o.Targets + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go index e5f5afd56..b5f93b565 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go @@ -16,13 +16,13 @@ import ( // TargetGroupPut struct for TargetGroupPut type TargetGroupPut struct { + // The URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *TargetGroupProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *TargetGroupProperties `json:"properties"` } // NewTargetGroupPut instantiates a new TargetGroupPut object @@ -45,152 +45,152 @@ func NewTargetGroupPutWithDefaults() *TargetGroupPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetIdOk() (*string, bool) { +func (o *TargetGroupPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *TargetGroupPut) SetId(v string) { +// SetHref sets field value +func (o *TargetGroupPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *TargetGroupPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *TargetGroupPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *TargetGroupPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetTypeOk() (*Type, bool) { +func (o *TargetGroupPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *TargetGroupPut) SetType(v Type) { +// SetId sets field value +func (o *TargetGroupPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *TargetGroupPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *TargetGroupPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetProperties() *TargetGroupProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetHrefOk() (*string, bool) { +func (o *TargetGroupPut) GetPropertiesOk() (*TargetGroupProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *TargetGroupPut) SetHref(v string) { +// SetProperties sets field value +func (o *TargetGroupPut) SetProperties(v TargetGroupProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *TargetGroupPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *TargetGroupPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for TargetGroupProperties will be returned -func (o *TargetGroupPut) GetProperties() *TargetGroupProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetPropertiesOk() (*TargetGroupProperties, bool) { +func (o *TargetGroupPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *TargetGroupPut) SetProperties(v TargetGroupProperties) { +// SetType sets field value +func (o *TargetGroupPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *TargetGroupPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *TargetGroupPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *TargetGroupPut) HasProperties() bool { func (o TargetGroupPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go index bad8c42d5..6681dd257 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go @@ -16,16 +16,18 @@ import ( // TargetGroupTarget struct for TargetGroupTarget type TargetGroupTarget struct { + // When the health check is enabled, the target is available only when it accepts regular TCP or HTTP connection attempts for state checking. The state check consists of one connection attempt with the target's address and port. The default value is 'TRUE'. + HealthCheckEnabled *bool `json:"healthCheckEnabled,omitempty"` // The IP address of the balanced target. Ip *string `json:"ip"` + // When the maintenance mode is enabled, the target is prevented from receiving traffic; the default value is 'FALSE'. + MaintenanceEnabled *bool `json:"maintenanceEnabled,omitempty"` // The port of the balanced target service; the valid range is 1 to 65535. Port *int32 `json:"port"` // The traffic is distributed proportionally to target weight, which is the ratio of the total weight of all targets. A target with higher weight receives a larger share of traffic. The valid range is from 0 to 256; the default value is '1'. Targets with a weight of '0' do not participate in load balancing but still accept persistent connections. We recommend using values in the middle range to leave room for later adjustments. Weight *int32 `json:"weight"` - // When the health check is enabled, the target is available only when it accepts regular TCP or HTTP connection attempts for state checking. The state check consists of one connection attempt with the target's address and port. The default value is 'TRUE'. - HealthCheckEnabled *bool `json:"healthCheckEnabled,omitempty"` - // When the maintenance mode is enabled, the target is prevented from receiving traffic; the default value is 'FALSE'. - MaintenanceEnabled *bool `json:"maintenanceEnabled,omitempty"` + // ProxyProtocol is used to set the proxy protocol version. + ProxyProtocol *string `json:"proxyProtocol,omitempty"` } // NewTargetGroupTarget instantiates a new TargetGroupTarget object @@ -38,6 +40,8 @@ func NewTargetGroupTarget(ip string, port int32, weight int32) *TargetGroupTarge this.Ip = &ip this.Port = &port this.Weight = &weight + var proxyProtocol string = "none" + this.ProxyProtocol = &proxyProtocol return &this } @@ -47,11 +51,51 @@ func NewTargetGroupTarget(ip string, port int32, weight int32) *TargetGroupTarge // but it doesn't guarantee that properties required by API are set func NewTargetGroupTargetWithDefaults() *TargetGroupTarget { this := TargetGroupTarget{} + var proxyProtocol string = "none" + this.ProxyProtocol = &proxyProtocol return &this } +// GetHealthCheckEnabled returns the HealthCheckEnabled field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetHealthCheckEnabled() *bool { + if o == nil { + return nil + } + + return o.HealthCheckEnabled + +} + +// GetHealthCheckEnabledOk returns a tuple with the HealthCheckEnabled field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *TargetGroupTarget) GetHealthCheckEnabledOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.HealthCheckEnabled, true +} + +// SetHealthCheckEnabled sets field value +func (o *TargetGroupTarget) SetHealthCheckEnabled(v bool) { + + o.HealthCheckEnabled = &v + +} + +// HasHealthCheckEnabled returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasHealthCheckEnabled() bool { + if o != nil && o.HealthCheckEnabled != nil { + return true + } + + return false +} + // GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroupTarget) GetIp() *string { if o == nil { return nil @@ -88,152 +132,152 @@ func (o *TargetGroupTarget) HasIp() bool { return false } -// GetPort returns the Port field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupTarget) GetPort() *int32 { +// GetMaintenanceEnabled returns the MaintenanceEnabled field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetMaintenanceEnabled() *bool { if o == nil { return nil } - return o.Port + return o.MaintenanceEnabled } -// GetPortOk returns a tuple with the Port field value +// GetMaintenanceEnabledOk returns a tuple with the MaintenanceEnabled field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetPortOk() (*int32, bool) { +func (o *TargetGroupTarget) GetMaintenanceEnabledOk() (*bool, bool) { if o == nil { return nil, false } - return o.Port, true + return o.MaintenanceEnabled, true } -// SetPort sets field value -func (o *TargetGroupTarget) SetPort(v int32) { +// SetMaintenanceEnabled sets field value +func (o *TargetGroupTarget) SetMaintenanceEnabled(v bool) { - o.Port = &v + o.MaintenanceEnabled = &v } -// HasPort returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasPort() bool { - if o != nil && o.Port != nil { +// HasMaintenanceEnabled returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasMaintenanceEnabled() bool { + if o != nil && o.MaintenanceEnabled != nil { return true } return false } -// GetWeight returns the Weight field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupTarget) GetWeight() *int32 { +// GetPort returns the Port field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetPort() *int32 { if o == nil { return nil } - return o.Weight + return o.Port } -// GetWeightOk returns a tuple with the Weight field value +// GetPortOk returns a tuple with the Port field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetWeightOk() (*int32, bool) { +func (o *TargetGroupTarget) GetPortOk() (*int32, bool) { if o == nil { return nil, false } - return o.Weight, true + return o.Port, true } -// SetWeight sets field value -func (o *TargetGroupTarget) SetWeight(v int32) { +// SetPort sets field value +func (o *TargetGroupTarget) SetPort(v int32) { - o.Weight = &v + o.Port = &v } -// HasWeight returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasWeight() bool { - if o != nil && o.Weight != nil { +// HasPort returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasPort() bool { + if o != nil && o.Port != nil { return true } return false } -// GetHealthCheckEnabled returns the HealthCheckEnabled field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *TargetGroupTarget) GetHealthCheckEnabled() *bool { +// GetWeight returns the Weight field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetWeight() *int32 { if o == nil { return nil } - return o.HealthCheckEnabled + return o.Weight } -// GetHealthCheckEnabledOk returns a tuple with the HealthCheckEnabled field value +// GetWeightOk returns a tuple with the Weight field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetHealthCheckEnabledOk() (*bool, bool) { +func (o *TargetGroupTarget) GetWeightOk() (*int32, bool) { if o == nil { return nil, false } - return o.HealthCheckEnabled, true + return o.Weight, true } -// SetHealthCheckEnabled sets field value -func (o *TargetGroupTarget) SetHealthCheckEnabled(v bool) { +// SetWeight sets field value +func (o *TargetGroupTarget) SetWeight(v int32) { - o.HealthCheckEnabled = &v + o.Weight = &v } -// HasHealthCheckEnabled returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasHealthCheckEnabled() bool { - if o != nil && o.HealthCheckEnabled != nil { +// HasWeight returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasWeight() bool { + if o != nil && o.Weight != nil { return true } return false } -// GetMaintenanceEnabled returns the MaintenanceEnabled field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *TargetGroupTarget) GetMaintenanceEnabled() *bool { +// GetProxyProtocol returns the ProxyProtocol field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetProxyProtocol() *string { if o == nil { return nil } - return o.MaintenanceEnabled + return o.ProxyProtocol } -// GetMaintenanceEnabledOk returns a tuple with the MaintenanceEnabled field value +// GetProxyProtocolOk returns a tuple with the ProxyProtocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetMaintenanceEnabledOk() (*bool, bool) { +func (o *TargetGroupTarget) GetProxyProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.MaintenanceEnabled, true + return o.ProxyProtocol, true } -// SetMaintenanceEnabled sets field value -func (o *TargetGroupTarget) SetMaintenanceEnabled(v bool) { +// SetProxyProtocol sets field value +func (o *TargetGroupTarget) SetProxyProtocol(v string) { - o.MaintenanceEnabled = &v + o.ProxyProtocol = &v } -// HasMaintenanceEnabled returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasMaintenanceEnabled() bool { - if o != nil && o.MaintenanceEnabled != nil { +// HasProxyProtocol returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasProxyProtocol() bool { + if o != nil && o.ProxyProtocol != nil { return true } @@ -242,21 +286,30 @@ func (o *TargetGroupTarget) HasMaintenanceEnabled() bool { func (o TargetGroupTarget) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.HealthCheckEnabled != nil { + toSerialize["healthCheckEnabled"] = o.HealthCheckEnabled + } + if o.Ip != nil { toSerialize["ip"] = o.Ip } + + if o.MaintenanceEnabled != nil { + toSerialize["maintenanceEnabled"] = o.MaintenanceEnabled + } + if o.Port != nil { toSerialize["port"] = o.Port } + if o.Weight != nil { toSerialize["weight"] = o.Weight } - if o.HealthCheckEnabled != nil { - toSerialize["healthCheckEnabled"] = o.HealthCheckEnabled - } - if o.MaintenanceEnabled != nil { - toSerialize["maintenanceEnabled"] = o.MaintenanceEnabled + + if o.ProxyProtocol != nil { + toSerialize["proxyProtocol"] = o.ProxyProtocol } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go index ca5778f54..521ca7b3f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go @@ -16,19 +16,19 @@ import ( // TargetGroups struct for TargetGroups type TargetGroups struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]TargetGroup `json:"items,omitempty"` + // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). + Limit *float32 `json:"limit,omitempty"` // The offset, specified in the request (if not is specified, 0 is used by default). Offset *float32 `json:"offset,omitempty"` - // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTargetGroups instantiates a new TargetGroups object @@ -49,114 +49,114 @@ func NewTargetGroupsWithDefaults() *TargetGroups { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroups) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetIdOk() (*string, bool) { +func (o *TargetGroups) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *TargetGroups) SetId(v string) { +// SetLinks sets field value +func (o *TargetGroups) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *TargetGroups) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *TargetGroups) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *TargetGroups) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetTypeOk() (*Type, bool) { +func (o *TargetGroups) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *TargetGroups) SetType(v Type) { +// SetHref sets field value +func (o *TargetGroups) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *TargetGroups) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *TargetGroups) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroups) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetHrefOk() (*string, bool) { +func (o *TargetGroups) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *TargetGroups) SetHref(v string) { +// SetId sets field value +func (o *TargetGroups) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *TargetGroups) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *TargetGroups) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *TargetGroups) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []TargetGroup will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroups) GetItems() *[]TargetGroup { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *TargetGroups) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *TargetGroups) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetOffsetOk() (*float32, bool) { +func (o *TargetGroups) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *TargetGroups) SetOffset(v float32) { +// SetLimit sets field value +func (o *TargetGroups) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *TargetGroups) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *TargetGroups) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *TargetGroups) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetLimitOk() (*float32, bool) { +func (o *TargetGroups) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *TargetGroups) SetLimit(v float32) { +// SetOffset sets field value +func (o *TargetGroups) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *TargetGroups) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *TargetGroups) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *TargetGroups) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetLinksOk() (*PaginationLinks, bool) { +func (o *TargetGroups) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *TargetGroups) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *TargetGroups) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *TargetGroups) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *TargetGroups) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *TargetGroups) HasLinks() bool { func (o TargetGroups) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go index 9a1c39ea5..8c5281ed8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go @@ -16,10 +16,10 @@ import ( // TargetPortRange struct for TargetPortRange type TargetPortRange struct { - // Target port range start associated with the NAT Gateway rule. - Start *int32 `json:"start,omitempty"` // Target port range end associated with the NAT Gateway rule. End *int32 `json:"end,omitempty"` + // Target port range start associated with the NAT Gateway rule. + Start *int32 `json:"start,omitempty"` } // NewTargetPortRange instantiates a new TargetPortRange object @@ -40,76 +40,76 @@ func NewTargetPortRangeWithDefaults() *TargetPortRange { return &this } -// GetStart returns the Start field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetPortRange) GetStart() *int32 { +// GetEnd returns the End field value +// If the value is explicit nil, nil is returned +func (o *TargetPortRange) GetEnd() *int32 { if o == nil { return nil } - return o.Start + return o.End } -// GetStartOk returns a tuple with the Start field value +// GetEndOk returns a tuple with the End field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetPortRange) GetStartOk() (*int32, bool) { +func (o *TargetPortRange) GetEndOk() (*int32, bool) { if o == nil { return nil, false } - return o.Start, true + return o.End, true } -// SetStart sets field value -func (o *TargetPortRange) SetStart(v int32) { +// SetEnd sets field value +func (o *TargetPortRange) SetEnd(v int32) { - o.Start = &v + o.End = &v } -// HasStart returns a boolean if a field has been set. -func (o *TargetPortRange) HasStart() bool { - if o != nil && o.Start != nil { +// HasEnd returns a boolean if a field has been set. +func (o *TargetPortRange) HasEnd() bool { + if o != nil && o.End != nil { return true } return false } -// GetEnd returns the End field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetPortRange) GetEnd() *int32 { +// GetStart returns the Start field value +// If the value is explicit nil, nil is returned +func (o *TargetPortRange) GetStart() *int32 { if o == nil { return nil } - return o.End + return o.Start } -// GetEndOk returns a tuple with the End field value +// GetStartOk returns a tuple with the Start field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetPortRange) GetEndOk() (*int32, bool) { +func (o *TargetPortRange) GetStartOk() (*int32, bool) { if o == nil { return nil, false } - return o.End, true + return o.Start, true } -// SetEnd sets field value -func (o *TargetPortRange) SetEnd(v int32) { +// SetStart sets field value +func (o *TargetPortRange) SetStart(v int32) { - o.End = &v + o.Start = &v } -// HasEnd returns a boolean if a field has been set. -func (o *TargetPortRange) HasEnd() bool { - if o != nil && o.End != nil { +// HasStart returns a boolean if a field has been set. +func (o *TargetPortRange) HasStart() bool { + if o != nil && o.Start != nil { return true } @@ -118,12 +118,14 @@ func (o *TargetPortRange) HasEnd() bool { func (o TargetPortRange) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Start != nil { - toSerialize["start"] = o.Start - } if o.End != nil { toSerialize["end"] = o.End } + + if o.Start != nil { + toSerialize["start"] = o.Start + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go index 48156f106..ad290d409 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go @@ -16,14 +16,14 @@ import ( // Template struct for Template type Template struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *TemplateProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTemplate instantiates a new Template object @@ -46,190 +46,190 @@ func NewTemplateWithDefaults() *Template { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Template) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Template) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetIdOk() (*string, bool) { +func (o *Template) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Template) SetId(v string) { +// SetHref sets field value +func (o *Template) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Template) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Template) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Template) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Template) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetTypeOk() (*Type, bool) { +func (o *Template) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Template) SetType(v Type) { +// SetId sets field value +func (o *Template) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Template) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Template) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Template) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Template) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetHrefOk() (*string, bool) { +func (o *Template) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Template) SetHref(v string) { +// SetMetadata sets field value +func (o *Template) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Template) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Template) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Template) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Template) GetProperties() *TemplateProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Template) GetPropertiesOk() (*TemplateProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Template) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Template) SetProperties(v TemplateProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Template) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Template) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for TemplateProperties will be returned -func (o *Template) GetProperties() *TemplateProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Template) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetPropertiesOk() (*TemplateProperties, bool) { +func (o *Template) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Template) SetProperties(v TemplateProperties) { +// SetType sets field value +func (o *Template) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Template) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Template) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Template) HasProperties() bool { func (o Template) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go index 5d661eee2..98d115011 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go @@ -16,10 +16,10 @@ import ( // TemplateProperties struct for TemplateProperties type TemplateProperties struct { - // The resource name. - Name *string `json:"name"` // The CPU cores count. Cores *float32 `json:"cores"` + // The resource name. + Name *string `json:"name"` // The RAM size in MB. Ram *float32 `json:"ram"` // The storage size in GB. @@ -30,11 +30,11 @@ type TemplateProperties struct { // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewTemplateProperties(name string, cores float32, ram float32, storageSize float32) *TemplateProperties { +func NewTemplateProperties(cores float32, name string, ram float32, storageSize float32) *TemplateProperties { this := TemplateProperties{} - this.Name = &name this.Cores = &cores + this.Name = &name this.Ram = &ram this.StorageSize = &storageSize @@ -49,76 +49,76 @@ func NewTemplatePropertiesWithDefaults() *TemplateProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TemplateProperties) GetName() *string { +// GetCores returns the Cores field value +// If the value is explicit nil, nil is returned +func (o *TemplateProperties) GetCores() *float32 { if o == nil { return nil } - return o.Name + return o.Cores } -// GetNameOk returns a tuple with the Name field value +// GetCoresOk returns a tuple with the Cores field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TemplateProperties) GetNameOk() (*string, bool) { +func (o *TemplateProperties) GetCoresOk() (*float32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Cores, true } -// SetName sets field value -func (o *TemplateProperties) SetName(v string) { +// SetCores sets field value +func (o *TemplateProperties) SetCores(v float32) { - o.Name = &v + o.Cores = &v } -// HasName returns a boolean if a field has been set. -func (o *TemplateProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCores returns a boolean if a field has been set. +func (o *TemplateProperties) HasCores() bool { + if o != nil && o.Cores != nil { return true } return false } -// GetCores returns the Cores field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *TemplateProperties) GetCores() *float32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *TemplateProperties) GetName() *string { if o == nil { return nil } - return o.Cores + return o.Name } -// GetCoresOk returns a tuple with the Cores field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TemplateProperties) GetCoresOk() (*float32, bool) { +func (o *TemplateProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Cores, true + return o.Name, true } -// SetCores sets field value -func (o *TemplateProperties) SetCores(v float32) { +// SetName sets field value +func (o *TemplateProperties) SetName(v string) { - o.Cores = &v + o.Name = &v } -// HasCores returns a boolean if a field has been set. -func (o *TemplateProperties) HasCores() bool { - if o != nil && o.Cores != nil { +// HasName returns a boolean if a field has been set. +func (o *TemplateProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -126,7 +126,7 @@ func (o *TemplateProperties) HasCores() bool { } // GetRam returns the Ram field value -// If the value is explicit nil, the zero value for float32 will be returned +// If the value is explicit nil, nil is returned func (o *TemplateProperties) GetRam() *float32 { if o == nil { return nil @@ -164,7 +164,7 @@ func (o *TemplateProperties) HasRam() bool { } // GetStorageSize returns the StorageSize field value -// If the value is explicit nil, the zero value for float32 will be returned +// If the value is explicit nil, nil is returned func (o *TemplateProperties) GetStorageSize() *float32 { if o == nil { return nil @@ -203,18 +203,22 @@ func (o *TemplateProperties) HasStorageSize() bool { func (o TemplateProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Cores != nil { toSerialize["cores"] = o.Cores } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + if o.Ram != nil { toSerialize["ram"] = o.Ram } + if o.StorageSize != nil { toSerialize["storageSize"] = o.StorageSize } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go index 1d6e9640c..c66eac10c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go @@ -16,14 +16,14 @@ import ( // Templates struct for Templates type Templates struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Template `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTemplates instantiates a new Templates object @@ -44,152 +44,152 @@ func NewTemplatesWithDefaults() *Templates { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Templates) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetIdOk() (*string, bool) { +func (o *Templates) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Templates) SetId(v string) { +// SetHref sets field value +func (o *Templates) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Templates) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Templates) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Templates) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetTypeOk() (*Type, bool) { +func (o *Templates) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Templates) SetType(v Type) { +// SetId sets field value +func (o *Templates) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Templates) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Templates) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Templates) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetItems() *[]Template { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetHrefOk() (*string, bool) { +func (o *Templates) GetItemsOk() (*[]Template, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Templates) SetHref(v string) { +// SetItems sets field value +func (o *Templates) SetItems(v []Template) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Templates) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Templates) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Template will be returned -func (o *Templates) GetItems() *[]Template { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetItemsOk() (*[]Template, bool) { +func (o *Templates) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Templates) SetItems(v []Template) { +// SetType sets field value +func (o *Templates) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Templates) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Templates) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Templates) HasItems() bool { func (o Templates) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go index 074e07ad6..c886b2680 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go @@ -39,7 +39,7 @@ func NewTokenWithDefaults() *Token { } // GetToken returns the Token field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Token) GetToken() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o Token) MarshalJSON() ([]byte, error) { if o.Token != nil { toSerialize["token"] = o.Token } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go index 14864be69..38d1a9b06 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go @@ -16,15 +16,15 @@ import ( // User struct for User type User struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *UsersEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *UserMetadata `json:"metadata,omitempty"` Properties *UserProperties `json:"properties"` - Entities *UsersEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewUser instantiates a new User object @@ -47,114 +47,114 @@ func NewUserWithDefaults() *User { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *User) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *User) GetEntities() *UsersEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetIdOk() (*string, bool) { +func (o *User) GetEntitiesOk() (*UsersEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *User) SetId(v string) { +// SetEntities sets field value +func (o *User) SetEntities(v UsersEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *User) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *User) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *User) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *User) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetTypeOk() (*Type, bool) { +func (o *User) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *User) SetType(v Type) { +// SetHref sets field value +func (o *User) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *User) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *User) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *User) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *User) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetHrefOk() (*string, bool) { +func (o *User) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *User) SetHref(v string) { +// SetId sets field value +func (o *User) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *User) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *User) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *User) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for UserMetadata will be returned +// If the value is explicit nil, nil is returned func (o *User) GetMetadata() *UserMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *User) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for UserProperties will be returned +// If the value is explicit nil, nil is returned func (o *User) GetProperties() *UserProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *User) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for UsersEntities will be returned -func (o *User) GetEntities() *UsersEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *User) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetEntitiesOk() (*UsersEntities, bool) { +func (o *User) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *User) SetEntities(v UsersEntities) { +// SetType sets field value +func (o *User) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *User) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *User) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *User) HasEntities() bool { func (o User) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go index da90dc00b..de6738d71 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go @@ -17,10 +17,10 @@ import ( // UserMetadata struct for UserMetadata type UserMetadata struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` // The time the user was created. CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The time of the last login by the user. LastLogin *IonosTime } @@ -43,83 +43,83 @@ func NewUserMetadataWithDefaults() *UserMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserMetadata) GetEtag() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *UserMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.Etag + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetEtagOk returns a tuple with the Etag field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserMetadata) GetEtagOk() (*string, bool) { +func (o *UserMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.Etag, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetEtag sets field value -func (o *UserMetadata) SetEtag(v string) { +// SetCreatedDate sets field value +func (o *UserMetadata) SetCreatedDate(v time.Time) { - o.Etag = &v + o.CreatedDate = &IonosTime{v} } -// HasEtag returns a boolean if a field has been set. -func (o *UserMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *UserMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } return false } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *UserMetadata) GetCreatedDate() *time.Time { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *UserMetadata) GetEtag() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.Etag } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *UserMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.Etag, true } -// SetCreatedDate sets field value -func (o *UserMetadata) SetCreatedDate(v time.Time) { +// SetEtag sets field value +func (o *UserMetadata) SetEtag(v string) { - o.CreatedDate = &IonosTime{v} + o.Etag = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *UserMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasEtag returns a boolean if a field has been set. +func (o *UserMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -127,7 +127,7 @@ func (o *UserMetadata) HasCreatedDate() bool { } // GetLastLogin returns the LastLogin field value -// If the value is explicit nil, the zero value for time.Time will be returned +// If the value is explicit nil, nil is returned func (o *UserMetadata) GetLastLogin() *time.Time { if o == nil { return nil @@ -173,15 +173,18 @@ func (o *UserMetadata) HasLastLogin() bool { func (o UserMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } if o.CreatedDate != nil { toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + if o.LastLogin != nil { toSerialize["lastLogin"] = o.LastLogin } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go index 912dc3391..cfbe91439 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go @@ -40,7 +40,7 @@ func NewUserPostWithDefaults() *UserPost { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for UserPropertiesPost will be returned +// If the value is explicit nil, nil is returned func (o *UserPost) GetProperties() *UserPropertiesPost { if o == nil { return nil @@ -82,6 +82,7 @@ func (o UserPost) MarshalJSON() ([]byte, error) { if o.Properties != nil { toSerialize["properties"] = o.Properties } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go index 6ff0ff0f0..7fadd2b43 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go @@ -16,22 +16,22 @@ import ( // UserProperties struct for UserProperties type UserProperties struct { - // The first name of the user. - Firstname *string `json:"firstname,omitempty"` - // The last name of the user. - Lastname *string `json:"lastname,omitempty"` - // The email address of the user. - Email *string `json:"email,omitempty"` + // Indicates if the user is active. + Active *bool `json:"active,omitempty"` // Indicates if the user has admin rights. Administrator *bool `json:"administrator,omitempty"` + // The email address of the user. + Email *string `json:"email,omitempty"` + // The first name of the user. + Firstname *string `json:"firstname,omitempty"` // Indicates if secure authentication should be forced on the user. ForceSecAuth *bool `json:"forceSecAuth,omitempty"` - // Indicates if secure authentication is active for the user. - SecAuthActive *bool `json:"secAuthActive,omitempty"` + // The last name of the user. + Lastname *string `json:"lastname,omitempty"` // Canonical (S3) ID of the user for a given identity. S3CanonicalUserId *string `json:"s3CanonicalUserId,omitempty"` - // Indicates if the user is active. - Active *bool `json:"active,omitempty"` + // Indicates if secure authentication is active for the user. + SecAuthActive *bool `json:"secAuthActive,omitempty"` } // NewUserProperties instantiates a new UserProperties object @@ -52,76 +52,76 @@ func NewUserPropertiesWithDefaults() *UserProperties { return &this } -// GetFirstname returns the Firstname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserProperties) GetFirstname() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetActive() *bool { if o == nil { return nil } - return o.Firstname + return o.Active } -// GetFirstnameOk returns a tuple with the Firstname field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetFirstnameOk() (*string, bool) { +func (o *UserProperties) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Firstname, true + return o.Active, true } -// SetFirstname sets field value -func (o *UserProperties) SetFirstname(v string) { +// SetActive sets field value +func (o *UserProperties) SetActive(v bool) { - o.Firstname = &v + o.Active = &v } -// HasFirstname returns a boolean if a field has been set. -func (o *UserProperties) HasFirstname() bool { - if o != nil && o.Firstname != nil { +// HasActive returns a boolean if a field has been set. +func (o *UserProperties) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetLastname returns the Lastname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserProperties) GetLastname() *string { +// GetAdministrator returns the Administrator field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetAdministrator() *bool { if o == nil { return nil } - return o.Lastname + return o.Administrator } -// GetLastnameOk returns a tuple with the Lastname field value +// GetAdministratorOk returns a tuple with the Administrator field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetLastnameOk() (*string, bool) { +func (o *UserProperties) GetAdministratorOk() (*bool, bool) { if o == nil { return nil, false } - return o.Lastname, true + return o.Administrator, true } -// SetLastname sets field value -func (o *UserProperties) SetLastname(v string) { +// SetAdministrator sets field value +func (o *UserProperties) SetAdministrator(v bool) { - o.Lastname = &v + o.Administrator = &v } -// HasLastname returns a boolean if a field has been set. -func (o *UserProperties) HasLastname() bool { - if o != nil && o.Lastname != nil { +// HasAdministrator returns a boolean if a field has been set. +func (o *UserProperties) HasAdministrator() bool { + if o != nil && o.Administrator != nil { return true } @@ -129,7 +129,7 @@ func (o *UserProperties) HasLastname() bool { } // GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserProperties) GetEmail() *string { if o == nil { return nil @@ -166,38 +166,38 @@ func (o *UserProperties) HasEmail() bool { return false } -// GetAdministrator returns the Administrator field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserProperties) GetAdministrator() *bool { +// GetFirstname returns the Firstname field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetFirstname() *string { if o == nil { return nil } - return o.Administrator + return o.Firstname } -// GetAdministratorOk returns a tuple with the Administrator field value +// GetFirstnameOk returns a tuple with the Firstname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetAdministratorOk() (*bool, bool) { +func (o *UserProperties) GetFirstnameOk() (*string, bool) { if o == nil { return nil, false } - return o.Administrator, true + return o.Firstname, true } -// SetAdministrator sets field value -func (o *UserProperties) SetAdministrator(v bool) { +// SetFirstname sets field value +func (o *UserProperties) SetFirstname(v string) { - o.Administrator = &v + o.Firstname = &v } -// HasAdministrator returns a boolean if a field has been set. -func (o *UserProperties) HasAdministrator() bool { - if o != nil && o.Administrator != nil { +// HasFirstname returns a boolean if a field has been set. +func (o *UserProperties) HasFirstname() bool { + if o != nil && o.Firstname != nil { return true } @@ -205,7 +205,7 @@ func (o *UserProperties) HasAdministrator() bool { } // GetForceSecAuth returns the ForceSecAuth field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *UserProperties) GetForceSecAuth() *bool { if o == nil { return nil @@ -242,38 +242,38 @@ func (o *UserProperties) HasForceSecAuth() bool { return false } -// GetSecAuthActive returns the SecAuthActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserProperties) GetSecAuthActive() *bool { +// GetLastname returns the Lastname field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetLastname() *string { if o == nil { return nil } - return o.SecAuthActive + return o.Lastname } -// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value +// GetLastnameOk returns a tuple with the Lastname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetSecAuthActiveOk() (*bool, bool) { +func (o *UserProperties) GetLastnameOk() (*string, bool) { if o == nil { return nil, false } - return o.SecAuthActive, true + return o.Lastname, true } -// SetSecAuthActive sets field value -func (o *UserProperties) SetSecAuthActive(v bool) { +// SetLastname sets field value +func (o *UserProperties) SetLastname(v string) { - o.SecAuthActive = &v + o.Lastname = &v } -// HasSecAuthActive returns a boolean if a field has been set. -func (o *UserProperties) HasSecAuthActive() bool { - if o != nil && o.SecAuthActive != nil { +// HasLastname returns a boolean if a field has been set. +func (o *UserProperties) HasLastname() bool { + if o != nil && o.Lastname != nil { return true } @@ -281,7 +281,7 @@ func (o *UserProperties) HasSecAuthActive() bool { } // GetS3CanonicalUserId returns the S3CanonicalUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserProperties) GetS3CanonicalUserId() *string { if o == nil { return nil @@ -318,38 +318,38 @@ func (o *UserProperties) HasS3CanonicalUserId() bool { return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserProperties) GetActive() *bool { +// GetSecAuthActive returns the SecAuthActive field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetSecAuthActive() *bool { if o == nil { return nil } - return o.Active + return o.SecAuthActive } -// GetActiveOk returns a tuple with the Active field value +// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetActiveOk() (*bool, bool) { +func (o *UserProperties) GetSecAuthActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecAuthActive, true } -// SetActive sets field value -func (o *UserProperties) SetActive(v bool) { +// SetSecAuthActive sets field value +func (o *UserProperties) SetSecAuthActive(v bool) { - o.Active = &v + o.SecAuthActive = &v } -// HasActive returns a boolean if a field has been set. -func (o *UserProperties) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecAuthActive returns a boolean if a field has been set. +func (o *UserProperties) HasSecAuthActive() bool { + if o != nil && o.SecAuthActive != nil { return true } @@ -358,30 +358,38 @@ func (o *UserProperties) HasActive() bool { func (o UserProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Firstname != nil { - toSerialize["firstname"] = o.Firstname + if o.Active != nil { + toSerialize["active"] = o.Active } - if o.Lastname != nil { - toSerialize["lastname"] = o.Lastname + + if o.Administrator != nil { + toSerialize["administrator"] = o.Administrator } + if o.Email != nil { toSerialize["email"] = o.Email } - if o.Administrator != nil { - toSerialize["administrator"] = o.Administrator + + if o.Firstname != nil { + toSerialize["firstname"] = o.Firstname } + if o.ForceSecAuth != nil { toSerialize["forceSecAuth"] = o.ForceSecAuth } - if o.SecAuthActive != nil { - toSerialize["secAuthActive"] = o.SecAuthActive + + if o.Lastname != nil { + toSerialize["lastname"] = o.Lastname } + if o.S3CanonicalUserId != nil { toSerialize["s3CanonicalUserId"] = o.S3CanonicalUserId } - if o.Active != nil { - toSerialize["active"] = o.Active + + if o.SecAuthActive != nil { + toSerialize["secAuthActive"] = o.SecAuthActive } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go index 463eb6dc3..fb4e9026f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go @@ -16,22 +16,22 @@ import ( // UserPropertiesPost struct for UserPropertiesPost type UserPropertiesPost struct { - // The first name of the user. - Firstname *string `json:"firstname,omitempty"` - // The last name of the user. - Lastname *string `json:"lastname,omitempty"` - // The email address of the user. - Email *string `json:"email,omitempty"` + // Indicates if the user is active. + Active *bool `json:"active,omitempty"` // Indicates if the user has admin rights. Administrator *bool `json:"administrator,omitempty"` + // The email address of the user. + Email *string `json:"email,omitempty"` + // The first name of the user. + Firstname *string `json:"firstname,omitempty"` // Indicates if secure authentication should be forced on the user. ForceSecAuth *bool `json:"forceSecAuth,omitempty"` - // Indicates if secure authentication is active for the user. - SecAuthActive *bool `json:"secAuthActive,omitempty"` + // The last name of the user. + Lastname *string `json:"lastname,omitempty"` // User password. Password *string `json:"password,omitempty"` - // Indicates if the user is active. - Active *bool `json:"active,omitempty"` + // Indicates if secure authentication is active for the user. + SecAuthActive *bool `json:"secAuthActive,omitempty"` } // NewUserPropertiesPost instantiates a new UserPropertiesPost object @@ -52,76 +52,76 @@ func NewUserPropertiesPostWithDefaults() *UserPropertiesPost { return &this } -// GetFirstname returns the Firstname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPost) GetFirstname() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetActive() *bool { if o == nil { return nil } - return o.Firstname + return o.Active } -// GetFirstnameOk returns a tuple with the Firstname field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetFirstnameOk() (*string, bool) { +func (o *UserPropertiesPost) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Firstname, true + return o.Active, true } -// SetFirstname sets field value -func (o *UserPropertiesPost) SetFirstname(v string) { +// SetActive sets field value +func (o *UserPropertiesPost) SetActive(v bool) { - o.Firstname = &v + o.Active = &v } -// HasFirstname returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasFirstname() bool { - if o != nil && o.Firstname != nil { +// HasActive returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetLastname returns the Lastname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPost) GetLastname() *string { +// GetAdministrator returns the Administrator field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetAdministrator() *bool { if o == nil { return nil } - return o.Lastname + return o.Administrator } -// GetLastnameOk returns a tuple with the Lastname field value +// GetAdministratorOk returns a tuple with the Administrator field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetLastnameOk() (*string, bool) { +func (o *UserPropertiesPost) GetAdministratorOk() (*bool, bool) { if o == nil { return nil, false } - return o.Lastname, true + return o.Administrator, true } -// SetLastname sets field value -func (o *UserPropertiesPost) SetLastname(v string) { +// SetAdministrator sets field value +func (o *UserPropertiesPost) SetAdministrator(v bool) { - o.Lastname = &v + o.Administrator = &v } -// HasLastname returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasLastname() bool { - if o != nil && o.Lastname != nil { +// HasAdministrator returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasAdministrator() bool { + if o != nil && o.Administrator != nil { return true } @@ -129,7 +129,7 @@ func (o *UserPropertiesPost) HasLastname() bool { } // GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPost) GetEmail() *string { if o == nil { return nil @@ -166,38 +166,38 @@ func (o *UserPropertiesPost) HasEmail() bool { return false } -// GetAdministrator returns the Administrator field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPost) GetAdministrator() *bool { +// GetFirstname returns the Firstname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetFirstname() *string { if o == nil { return nil } - return o.Administrator + return o.Firstname } -// GetAdministratorOk returns a tuple with the Administrator field value +// GetFirstnameOk returns a tuple with the Firstname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetAdministratorOk() (*bool, bool) { +func (o *UserPropertiesPost) GetFirstnameOk() (*string, bool) { if o == nil { return nil, false } - return o.Administrator, true + return o.Firstname, true } -// SetAdministrator sets field value -func (o *UserPropertiesPost) SetAdministrator(v bool) { +// SetFirstname sets field value +func (o *UserPropertiesPost) SetFirstname(v string) { - o.Administrator = &v + o.Firstname = &v } -// HasAdministrator returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasAdministrator() bool { - if o != nil && o.Administrator != nil { +// HasFirstname returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasFirstname() bool { + if o != nil && o.Firstname != nil { return true } @@ -205,7 +205,7 @@ func (o *UserPropertiesPost) HasAdministrator() bool { } // GetForceSecAuth returns the ForceSecAuth field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPost) GetForceSecAuth() *bool { if o == nil { return nil @@ -242,38 +242,38 @@ func (o *UserPropertiesPost) HasForceSecAuth() bool { return false } -// GetSecAuthActive returns the SecAuthActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPost) GetSecAuthActive() *bool { +// GetLastname returns the Lastname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetLastname() *string { if o == nil { return nil } - return o.SecAuthActive + return o.Lastname } -// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value +// GetLastnameOk returns a tuple with the Lastname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetSecAuthActiveOk() (*bool, bool) { +func (o *UserPropertiesPost) GetLastnameOk() (*string, bool) { if o == nil { return nil, false } - return o.SecAuthActive, true + return o.Lastname, true } -// SetSecAuthActive sets field value -func (o *UserPropertiesPost) SetSecAuthActive(v bool) { +// SetLastname sets field value +func (o *UserPropertiesPost) SetLastname(v string) { - o.SecAuthActive = &v + o.Lastname = &v } -// HasSecAuthActive returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasSecAuthActive() bool { - if o != nil && o.SecAuthActive != nil { +// HasLastname returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasLastname() bool { + if o != nil && o.Lastname != nil { return true } @@ -281,7 +281,7 @@ func (o *UserPropertiesPost) HasSecAuthActive() bool { } // GetPassword returns the Password field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPost) GetPassword() *string { if o == nil { return nil @@ -318,38 +318,38 @@ func (o *UserPropertiesPost) HasPassword() bool { return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPost) GetActive() *bool { +// GetSecAuthActive returns the SecAuthActive field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetSecAuthActive() *bool { if o == nil { return nil } - return o.Active + return o.SecAuthActive } -// GetActiveOk returns a tuple with the Active field value +// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetActiveOk() (*bool, bool) { +func (o *UserPropertiesPost) GetSecAuthActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecAuthActive, true } -// SetActive sets field value -func (o *UserPropertiesPost) SetActive(v bool) { +// SetSecAuthActive sets field value +func (o *UserPropertiesPost) SetSecAuthActive(v bool) { - o.Active = &v + o.SecAuthActive = &v } -// HasActive returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecAuthActive returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasSecAuthActive() bool { + if o != nil && o.SecAuthActive != nil { return true } @@ -358,30 +358,38 @@ func (o *UserPropertiesPost) HasActive() bool { func (o UserPropertiesPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Firstname != nil { - toSerialize["firstname"] = o.Firstname + if o.Active != nil { + toSerialize["active"] = o.Active } - if o.Lastname != nil { - toSerialize["lastname"] = o.Lastname + + if o.Administrator != nil { + toSerialize["administrator"] = o.Administrator } + if o.Email != nil { toSerialize["email"] = o.Email } - if o.Administrator != nil { - toSerialize["administrator"] = o.Administrator + + if o.Firstname != nil { + toSerialize["firstname"] = o.Firstname } + if o.ForceSecAuth != nil { toSerialize["forceSecAuth"] = o.ForceSecAuth } - if o.SecAuthActive != nil { - toSerialize["secAuthActive"] = o.SecAuthActive + + if o.Lastname != nil { + toSerialize["lastname"] = o.Lastname } + if o.Password != nil { toSerialize["password"] = o.Password } - if o.Active != nil { - toSerialize["active"] = o.Active + + if o.SecAuthActive != nil { + toSerialize["secAuthActive"] = o.SecAuthActive } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go index 778c3b0cf..d0ad92946 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go @@ -16,22 +16,22 @@ import ( // UserPropertiesPut struct for UserPropertiesPut type UserPropertiesPut struct { + // Indicates if the user is active. + Active *bool `json:"active,omitempty"` + // Indicates if the user has admin rights. + Administrator *bool `json:"administrator,omitempty"` + // The email address of the user. + Email *string `json:"email,omitempty"` // The first name of the user. Firstname *string `json:"firstname,omitempty"` + // Indicates if secure authentication should be forced on the user. + ForceSecAuth *bool `json:"forceSecAuth,omitempty"` // The last name of the user. Lastname *string `json:"lastname,omitempty"` - // The email address of the user. - Email *string `json:"email,omitempty"` // password of the user Password *string `json:"password,omitempty"` - // Indicates if the user has admin rights. - Administrator *bool `json:"administrator,omitempty"` - // Indicates if secure authentication should be forced on the user. - ForceSecAuth *bool `json:"forceSecAuth,omitempty"` // Indicates if secure authentication is active for the user. SecAuthActive *bool `json:"secAuthActive,omitempty"` - // Indicates if the user is active. - Active *bool `json:"active,omitempty"` } // NewUserPropertiesPut instantiates a new UserPropertiesPut object @@ -52,76 +52,76 @@ func NewUserPropertiesPutWithDefaults() *UserPropertiesPut { return &this } -// GetFirstname returns the Firstname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPut) GetFirstname() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetActive() *bool { if o == nil { return nil } - return o.Firstname + return o.Active } -// GetFirstnameOk returns a tuple with the Firstname field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetFirstnameOk() (*string, bool) { +func (o *UserPropertiesPut) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Firstname, true + return o.Active, true } -// SetFirstname sets field value -func (o *UserPropertiesPut) SetFirstname(v string) { +// SetActive sets field value +func (o *UserPropertiesPut) SetActive(v bool) { - o.Firstname = &v + o.Active = &v } -// HasFirstname returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasFirstname() bool { - if o != nil && o.Firstname != nil { +// HasActive returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetLastname returns the Lastname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPut) GetLastname() *string { +// GetAdministrator returns the Administrator field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetAdministrator() *bool { if o == nil { return nil } - return o.Lastname + return o.Administrator } -// GetLastnameOk returns a tuple with the Lastname field value +// GetAdministratorOk returns a tuple with the Administrator field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetLastnameOk() (*string, bool) { +func (o *UserPropertiesPut) GetAdministratorOk() (*bool, bool) { if o == nil { return nil, false } - return o.Lastname, true + return o.Administrator, true } -// SetLastname sets field value -func (o *UserPropertiesPut) SetLastname(v string) { +// SetAdministrator sets field value +func (o *UserPropertiesPut) SetAdministrator(v bool) { - o.Lastname = &v + o.Administrator = &v } -// HasLastname returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasLastname() bool { - if o != nil && o.Lastname != nil { +// HasAdministrator returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasAdministrator() bool { + if o != nil && o.Administrator != nil { return true } @@ -129,7 +129,7 @@ func (o *UserPropertiesPut) HasLastname() bool { } // GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPut) GetEmail() *string { if o == nil { return nil @@ -166,190 +166,190 @@ func (o *UserPropertiesPut) HasEmail() bool { return false } -// GetPassword returns the Password field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPut) GetPassword() *string { +// GetFirstname returns the Firstname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetFirstname() *string { if o == nil { return nil } - return o.Password + return o.Firstname } -// GetPasswordOk returns a tuple with the Password field value +// GetFirstnameOk returns a tuple with the Firstname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetPasswordOk() (*string, bool) { +func (o *UserPropertiesPut) GetFirstnameOk() (*string, bool) { if o == nil { return nil, false } - return o.Password, true + return o.Firstname, true } -// SetPassword sets field value -func (o *UserPropertiesPut) SetPassword(v string) { +// SetFirstname sets field value +func (o *UserPropertiesPut) SetFirstname(v string) { - o.Password = &v + o.Firstname = &v } -// HasPassword returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasPassword() bool { - if o != nil && o.Password != nil { +// HasFirstname returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasFirstname() bool { + if o != nil && o.Firstname != nil { return true } return false } -// GetAdministrator returns the Administrator field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetAdministrator() *bool { +// GetForceSecAuth returns the ForceSecAuth field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetForceSecAuth() *bool { if o == nil { return nil } - return o.Administrator + return o.ForceSecAuth } -// GetAdministratorOk returns a tuple with the Administrator field value +// GetForceSecAuthOk returns a tuple with the ForceSecAuth field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetAdministratorOk() (*bool, bool) { +func (o *UserPropertiesPut) GetForceSecAuthOk() (*bool, bool) { if o == nil { return nil, false } - return o.Administrator, true + return o.ForceSecAuth, true } -// SetAdministrator sets field value -func (o *UserPropertiesPut) SetAdministrator(v bool) { +// SetForceSecAuth sets field value +func (o *UserPropertiesPut) SetForceSecAuth(v bool) { - o.Administrator = &v + o.ForceSecAuth = &v } -// HasAdministrator returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasAdministrator() bool { - if o != nil && o.Administrator != nil { +// HasForceSecAuth returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasForceSecAuth() bool { + if o != nil && o.ForceSecAuth != nil { return true } return false } -// GetForceSecAuth returns the ForceSecAuth field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetForceSecAuth() *bool { +// GetLastname returns the Lastname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetLastname() *string { if o == nil { return nil } - return o.ForceSecAuth + return o.Lastname } -// GetForceSecAuthOk returns a tuple with the ForceSecAuth field value +// GetLastnameOk returns a tuple with the Lastname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetForceSecAuthOk() (*bool, bool) { +func (o *UserPropertiesPut) GetLastnameOk() (*string, bool) { if o == nil { return nil, false } - return o.ForceSecAuth, true + return o.Lastname, true } -// SetForceSecAuth sets field value -func (o *UserPropertiesPut) SetForceSecAuth(v bool) { +// SetLastname sets field value +func (o *UserPropertiesPut) SetLastname(v string) { - o.ForceSecAuth = &v + o.Lastname = &v } -// HasForceSecAuth returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasForceSecAuth() bool { - if o != nil && o.ForceSecAuth != nil { +// HasLastname returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasLastname() bool { + if o != nil && o.Lastname != nil { return true } return false } -// GetSecAuthActive returns the SecAuthActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetSecAuthActive() *bool { +// GetPassword returns the Password field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetPassword() *string { if o == nil { return nil } - return o.SecAuthActive + return o.Password } -// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value +// GetPasswordOk returns a tuple with the Password field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetSecAuthActiveOk() (*bool, bool) { +func (o *UserPropertiesPut) GetPasswordOk() (*string, bool) { if o == nil { return nil, false } - return o.SecAuthActive, true + return o.Password, true } -// SetSecAuthActive sets field value -func (o *UserPropertiesPut) SetSecAuthActive(v bool) { +// SetPassword sets field value +func (o *UserPropertiesPut) SetPassword(v string) { - o.SecAuthActive = &v + o.Password = &v } -// HasSecAuthActive returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasSecAuthActive() bool { - if o != nil && o.SecAuthActive != nil { +// HasPassword returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasPassword() bool { + if o != nil && o.Password != nil { return true } return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetActive() *bool { +// GetSecAuthActive returns the SecAuthActive field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetSecAuthActive() *bool { if o == nil { return nil } - return o.Active + return o.SecAuthActive } -// GetActiveOk returns a tuple with the Active field value +// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetActiveOk() (*bool, bool) { +func (o *UserPropertiesPut) GetSecAuthActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecAuthActive, true } -// SetActive sets field value -func (o *UserPropertiesPut) SetActive(v bool) { +// SetSecAuthActive sets field value +func (o *UserPropertiesPut) SetSecAuthActive(v bool) { - o.Active = &v + o.SecAuthActive = &v } -// HasActive returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecAuthActive returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasSecAuthActive() bool { + if o != nil && o.SecAuthActive != nil { return true } @@ -358,30 +358,38 @@ func (o *UserPropertiesPut) HasActive() bool { func (o UserPropertiesPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Firstname != nil { - toSerialize["firstname"] = o.Firstname + if o.Active != nil { + toSerialize["active"] = o.Active } - if o.Lastname != nil { - toSerialize["lastname"] = o.Lastname + + if o.Administrator != nil { + toSerialize["administrator"] = o.Administrator } + if o.Email != nil { toSerialize["email"] = o.Email } - if o.Password != nil { - toSerialize["password"] = o.Password - } - if o.Administrator != nil { - toSerialize["administrator"] = o.Administrator + + if o.Firstname != nil { + toSerialize["firstname"] = o.Firstname } + if o.ForceSecAuth != nil { toSerialize["forceSecAuth"] = o.ForceSecAuth } + + if o.Lastname != nil { + toSerialize["lastname"] = o.Lastname + } + + if o.Password != nil { + toSerialize["password"] = o.Password + } + if o.SecAuthActive != nil { toSerialize["secAuthActive"] = o.SecAuthActive } - if o.Active != nil { - toSerialize["active"] = o.Active - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go index b45261f2f..9e0c992c9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go @@ -42,7 +42,7 @@ func NewUserPutWithDefaults() *UserPut { } // GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPut) GetId() *string { if o == nil { return nil @@ -80,7 +80,7 @@ func (o *UserPut) HasId() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for UserPropertiesPut will be returned +// If the value is explicit nil, nil is returned func (o *UserPut) GetProperties() *UserPropertiesPut { if o == nil { return nil @@ -122,9 +122,11 @@ func (o UserPut) MarshalJSON() ([]byte, error) { if o.Id != nil { toSerialize["id"] = o.Id } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go index 0107d029b..e67610e19 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go @@ -16,19 +16,19 @@ import ( // Users struct for Users type Users struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]User `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewUsers instantiates a new Users object @@ -49,114 +49,114 @@ func NewUsersWithDefaults() *Users { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Users) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Users) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetIdOk() (*string, bool) { +func (o *Users) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Users) SetId(v string) { +// SetLinks sets field value +func (o *Users) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Users) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Users) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Users) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Users) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetTypeOk() (*Type, bool) { +func (o *Users) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Users) SetType(v Type) { +// SetHref sets field value +func (o *Users) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Users) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Users) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Users) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Users) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetHrefOk() (*string, bool) { +func (o *Users) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Users) SetHref(v string) { +// SetId sets field value +func (o *Users) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Users) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Users) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Users) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []User will be returned +// If the value is explicit nil, nil is returned func (o *Users) GetItems() *[]User { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Users) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Users) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Users) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetOffsetOk() (*float32, bool) { +func (o *Users) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Users) SetOffset(v float32) { +// SetLimit sets field value +func (o *Users) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Users) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Users) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Users) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Users) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetLimitOk() (*float32, bool) { +func (o *Users) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Users) SetLimit(v float32) { +// SetOffset sets field value +func (o *Users) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Users) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Users) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Users) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Users) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetLinksOk() (*PaginationLinks, bool) { +func (o *Users) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Users) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Users) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Users) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Users) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Users) HasLinks() bool { func (o Users) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go index 6c10d5a04..7619f6611 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go @@ -16,8 +16,8 @@ import ( // UsersEntities struct for UsersEntities type UsersEntities struct { - Owns *ResourcesUsers `json:"owns,omitempty"` Groups *GroupUsers `json:"groups,omitempty"` + Owns *ResourcesUsers `json:"owns,omitempty"` } // NewUsersEntities instantiates a new UsersEntities object @@ -38,76 +38,76 @@ func NewUsersEntitiesWithDefaults() *UsersEntities { return &this } -// GetOwns returns the Owns field value -// If the value is explicit nil, the zero value for ResourcesUsers will be returned -func (o *UsersEntities) GetOwns() *ResourcesUsers { +// GetGroups returns the Groups field value +// If the value is explicit nil, nil is returned +func (o *UsersEntities) GetGroups() *GroupUsers { if o == nil { return nil } - return o.Owns + return o.Groups } -// GetOwnsOk returns a tuple with the Owns field value +// GetGroupsOk returns a tuple with the Groups field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UsersEntities) GetOwnsOk() (*ResourcesUsers, bool) { +func (o *UsersEntities) GetGroupsOk() (*GroupUsers, bool) { if o == nil { return nil, false } - return o.Owns, true + return o.Groups, true } -// SetOwns sets field value -func (o *UsersEntities) SetOwns(v ResourcesUsers) { +// SetGroups sets field value +func (o *UsersEntities) SetGroups(v GroupUsers) { - o.Owns = &v + o.Groups = &v } -// HasOwns returns a boolean if a field has been set. -func (o *UsersEntities) HasOwns() bool { - if o != nil && o.Owns != nil { +// HasGroups returns a boolean if a field has been set. +func (o *UsersEntities) HasGroups() bool { + if o != nil && o.Groups != nil { return true } return false } -// GetGroups returns the Groups field value -// If the value is explicit nil, the zero value for GroupUsers will be returned -func (o *UsersEntities) GetGroups() *GroupUsers { +// GetOwns returns the Owns field value +// If the value is explicit nil, nil is returned +func (o *UsersEntities) GetOwns() *ResourcesUsers { if o == nil { return nil } - return o.Groups + return o.Owns } -// GetGroupsOk returns a tuple with the Groups field value +// GetOwnsOk returns a tuple with the Owns field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UsersEntities) GetGroupsOk() (*GroupUsers, bool) { +func (o *UsersEntities) GetOwnsOk() (*ResourcesUsers, bool) { if o == nil { return nil, false } - return o.Groups, true + return o.Owns, true } -// SetGroups sets field value -func (o *UsersEntities) SetGroups(v GroupUsers) { +// SetOwns sets field value +func (o *UsersEntities) SetOwns(v ResourcesUsers) { - o.Groups = &v + o.Owns = &v } -// HasGroups returns a boolean if a field has been set. -func (o *UsersEntities) HasGroups() bool { - if o != nil && o.Groups != nil { +// HasOwns returns a boolean if a field has been set. +func (o *UsersEntities) HasOwns() bool { + if o != nil && o.Owns != nil { return true } @@ -116,12 +116,14 @@ func (o *UsersEntities) HasGroups() bool { func (o UsersEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Owns != nil { - toSerialize["owns"] = o.Owns - } if o.Groups != nil { toSerialize["groups"] = o.Groups } + + if o.Owns != nil { + toSerialize["owns"] = o.Owns + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go index d0b7b862e..59bf03f02 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go @@ -16,14 +16,14 @@ import ( // Volume struct for Volume type Volume struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *VolumeProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewVolume instantiates a new Volume object @@ -46,190 +46,190 @@ func NewVolumeWithDefaults() *Volume { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volume) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetIdOk() (*string, bool) { +func (o *Volume) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Volume) SetId(v string) { +// SetHref sets field value +func (o *Volume) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Volume) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Volume) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Volume) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetTypeOk() (*Type, bool) { +func (o *Volume) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Volume) SetType(v Type) { +// SetId sets field value +func (o *Volume) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Volume) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Volume) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volume) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetHrefOk() (*string, bool) { +func (o *Volume) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Volume) SetHref(v string) { +// SetMetadata sets field value +func (o *Volume) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Volume) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Volume) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Volume) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetProperties() *VolumeProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Volume) GetPropertiesOk() (*VolumeProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Volume) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Volume) SetProperties(v VolumeProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Volume) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Volume) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for VolumeProperties will be returned -func (o *Volume) GetProperties() *VolumeProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetPropertiesOk() (*VolumeProperties, bool) { +func (o *Volume) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Volume) SetProperties(v VolumeProperties) { +// SetType sets field value +func (o *Volume) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Volume) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Volume) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Volume) HasProperties() bool { func (o Volume) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go index 15ed6a148..6f6bc6b96 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go @@ -16,49 +16,50 @@ import ( // VolumeProperties struct for VolumeProperties type VolumeProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // Hardware type of the volume. DAS (Direct Attached Storage) could be used only in a composite call with a Cube server. - Type *string `json:"type,omitempty"` - // The size of the volume in GB. - Size *float32 `json:"size"` // The availability zone in which the volume should be provisioned. The storage volume will be provisioned on as few physical storage devices as possible, but this cannot be guaranteed upfront. This is uavailable for DAS (Direct Attached Storage), and subject to availability for SSD. AvailabilityZone *string `json:"availabilityZone,omitempty"` + // The ID of the backup unit that the user has access to. The property is immutable and is only allowed to be set on creation of a new a volume. It is mandatory to provide either 'public image' or 'imageAlias' in conjunction with this property. + BackupunitId *string `json:"backupunitId,omitempty"` + // Determines whether the volume will be used as a boot volume. Set to `NONE`, the volume will not be used as boot volume. Set to `PRIMARY`, the volume will be used as boot volume and all other volumes must be set to `NONE`. Set to `AUTO` or `null` requires all volumes to be set to `AUTO` or `null`; this will use the legacy behavior, which is to use the volume as a boot volume only if there are no other volumes or cdrom devices. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetBootOrderNil` + BootOrder *string `json:"bootOrder,omitempty"` + // The UUID of the attached server. + BootServer *string `json:"bootServer,omitempty"` + // The bus type for this volume; default is VIRTIO. + Bus *string `json:"bus,omitempty"` + // Hot-plug capable CPU (no reboot required). + CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` + // The Logical Unit Number of the storage volume. Null for volumes, not mounted to a VM. + DeviceNumber *int64 `json:"deviceNumber,omitempty"` + // Hot-plug capable Virt-IO drive (no reboot required). + DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` + // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. + DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` // Image or snapshot ID to be used as template for this volume. - Image *string `json:"image,omitempty"` + Image *string `json:"image,omitempty"` + ImageAlias *string `json:"imageAlias,omitempty"` // Initial password to be set for installed OS. Works with public images only. Not modifiable, forbidden in update requests. Password rules allows all characters from a-z, A-Z, 0-9. ImagePassword *string `json:"imagePassword,omitempty"` - ImageAlias *string `json:"imageAlias,omitempty"` - // Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation. - SshKeys *[]string `json:"sshKeys,omitempty"` - // The bus type for this volume; default is VIRTIO. - Bus *string `json:"bus,omitempty"` // OS type for this volume. LicenceType *string `json:"licenceType,omitempty"` - // Hot-plug capable CPU (no reboot required). - CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` - // Hot-plug capable RAM (no reboot required). - RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // Hot-plug capable NIC (no reboot required). NicHotPlug *bool `json:"nicHotPlug,omitempty"` // Hot-unplug capable NIC (no reboot required). NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` - // Hot-plug capable Virt-IO drive (no reboot required). - DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` - // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. - DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` - // The Logical Unit Number of the storage volume. Null for volumes, not mounted to a VM. - DeviceNumber *int64 `json:"deviceNumber,omitempty"` // The PCI slot number of the storage volume. Null for volumes, not mounted to a VM. PciSlot *int32 `json:"pciSlot,omitempty"` - // The ID of the backup unit that the user has access to. The property is immutable and is only allowed to be set on creation of a new a volume. It is mandatory to provide either 'public image' or 'imageAlias' in conjunction with this property. - BackupunitId *string `json:"backupunitId,omitempty"` + // Hot-plug capable RAM (no reboot required). + RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // The size of the volume in GB. + Size *float32 `json:"size"` + // Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation. + SshKeys *[]string `json:"sshKeys,omitempty"` + // Hardware type of the volume. DAS (Direct Attached Storage) could be used only in a composite call with a Cube server. + Type *string `json:"type,omitempty"` // The cloud-init configuration for the volume as base64 encoded string. The property is immutable and is only allowed to be set on creation of a new a volume. It is mandatory to provide either 'public image' or 'imageAlias' that has cloud-init compatibility in conjunction with this property. UserData *string `json:"userData,omitempty"` - // The UUID of the attached server. - BootServer *string `json:"bootServer,omitempty"` - // Determines whether the volume will be used as a boot volume. Set to `NONE`, the volume will not be used as boot volume. Set to `PRIMARY`, the volume will be used as boot volume and all other volumes must be set to `NONE`. Set to `AUTO` or `null` requires all volumes to be set to `AUTO` or `null`; this will use the legacy behavior, which is to use the volume as a boot volume only if there are no other volumes or cdrom devices. - BootOrder *string `json:"bootOrder,omitempty"` } // NewVolumeProperties instantiates a new VolumeProperties object @@ -68,9 +69,9 @@ type VolumeProperties struct { func NewVolumeProperties(size float32) *VolumeProperties { this := VolumeProperties{} - this.Size = &size var bootOrder = "AUTO" this.BootOrder = &bootOrder + this.Size = &size return &this } @@ -85,836 +86,841 @@ func NewVolumePropertiesWithDefaults() *VolumeProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetName() *string { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetAvailabilityZone() *string { if o == nil { return nil } - return o.Name + return o.AvailabilityZone } -// GetNameOk returns a tuple with the Name field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetNameOk() (*string, bool) { +func (o *VolumeProperties) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.AvailabilityZone, true } -// SetName sets field value -func (o *VolumeProperties) SetName(v string) { +// SetAvailabilityZone sets field value +func (o *VolumeProperties) SetAvailabilityZone(v string) { - o.Name = &v + o.AvailabilityZone = &v } -// HasName returns a boolean if a field has been set. -func (o *VolumeProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *VolumeProperties) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetType() *string { +// GetBackupunitId returns the BackupunitId field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBackupunitId() *string { if o == nil { return nil } - return o.Type + return o.BackupunitId } -// GetTypeOk returns a tuple with the Type field value +// GetBackupunitIdOk returns a tuple with the BackupunitId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetTypeOk() (*string, bool) { +func (o *VolumeProperties) GetBackupunitIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.BackupunitId, true } -// SetType sets field value -func (o *VolumeProperties) SetType(v string) { +// SetBackupunitId sets field value +func (o *VolumeProperties) SetBackupunitId(v string) { - o.Type = &v + o.BackupunitId = &v } -// HasType returns a boolean if a field has been set. -func (o *VolumeProperties) HasType() bool { - if o != nil && o.Type != nil { +// HasBackupunitId returns a boolean if a field has been set. +func (o *VolumeProperties) HasBackupunitId() bool { + if o != nil && o.BackupunitId != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *VolumeProperties) GetSize() *float32 { +// GetBootOrder returns the BootOrder field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBootOrder() *string { if o == nil { return nil } - return o.Size + return o.BootOrder } -// GetSizeOk returns a tuple with the Size field value +// GetBootOrderOk returns a tuple with the BootOrder field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetSizeOk() (*float32, bool) { +func (o *VolumeProperties) GetBootOrderOk() (*string, bool) { if o == nil { return nil, false } - return o.Size, true + return o.BootOrder, true } -// SetSize sets field value -func (o *VolumeProperties) SetSize(v float32) { +// SetBootOrder sets field value +func (o *VolumeProperties) SetBootOrder(v string) { - o.Size = &v + o.BootOrder = &v } -// HasSize returns a boolean if a field has been set. -func (o *VolumeProperties) HasSize() bool { - if o != nil && o.Size != nil { +// sets BootOrder to the explicit address that will be encoded as nil when marshaled +func (o *VolumeProperties) SetBootOrderNil() { + o.BootOrder = &Nilstring +} + +// HasBootOrder returns a boolean if a field has been set. +func (o *VolumeProperties) HasBootOrder() bool { + if o != nil && o.BootOrder != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetAvailabilityZone() *string { +// GetBootServer returns the BootServer field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBootServer() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.BootServer } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetBootServerOk returns a tuple with the BootServer field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetAvailabilityZoneOk() (*string, bool) { +func (o *VolumeProperties) GetBootServerOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.BootServer, true } -// SetAvailabilityZone sets field value -func (o *VolumeProperties) SetAvailabilityZone(v string) { +// SetBootServer sets field value +func (o *VolumeProperties) SetBootServer(v string) { - o.AvailabilityZone = &v + o.BootServer = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *VolumeProperties) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasBootServer returns a boolean if a field has been set. +func (o *VolumeProperties) HasBootServer() bool { + if o != nil && o.BootServer != nil { return true } return false } -// GetImage returns the Image field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetImage() *string { +// GetBus returns the Bus field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBus() *string { if o == nil { return nil } - return o.Image + return o.Bus } -// GetImageOk returns a tuple with the Image field value +// GetBusOk returns a tuple with the Bus field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetImageOk() (*string, bool) { +func (o *VolumeProperties) GetBusOk() (*string, bool) { if o == nil { return nil, false } - return o.Image, true + return o.Bus, true } -// SetImage sets field value -func (o *VolumeProperties) SetImage(v string) { +// SetBus sets field value +func (o *VolumeProperties) SetBus(v string) { - o.Image = &v + o.Bus = &v } -// HasImage returns a boolean if a field has been set. -func (o *VolumeProperties) HasImage() bool { - if o != nil && o.Image != nil { +// HasBus returns a boolean if a field has been set. +func (o *VolumeProperties) HasBus() bool { + if o != nil && o.Bus != nil { return true } return false } -// GetImagePassword returns the ImagePassword field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetImagePassword() *string { +// GetCpuHotPlug returns the CpuHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetCpuHotPlug() *bool { if o == nil { return nil } - return o.ImagePassword + return o.CpuHotPlug } -// GetImagePasswordOk returns a tuple with the ImagePassword field value +// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetImagePasswordOk() (*string, bool) { +func (o *VolumeProperties) GetCpuHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.ImagePassword, true + return o.CpuHotPlug, true } -// SetImagePassword sets field value -func (o *VolumeProperties) SetImagePassword(v string) { +// SetCpuHotPlug sets field value +func (o *VolumeProperties) SetCpuHotPlug(v bool) { - o.ImagePassword = &v + o.CpuHotPlug = &v } -// HasImagePassword returns a boolean if a field has been set. -func (o *VolumeProperties) HasImagePassword() bool { - if o != nil && o.ImagePassword != nil { +// HasCpuHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasCpuHotPlug() bool { + if o != nil && o.CpuHotPlug != nil { return true } return false } -// GetImageAlias returns the ImageAlias field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetImageAlias() *string { +// GetDeviceNumber returns the DeviceNumber field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetDeviceNumber() *int64 { if o == nil { return nil } - return o.ImageAlias + return o.DeviceNumber } -// GetImageAliasOk returns a tuple with the ImageAlias field value +// GetDeviceNumberOk returns a tuple with the DeviceNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetImageAliasOk() (*string, bool) { +func (o *VolumeProperties) GetDeviceNumberOk() (*int64, bool) { if o == nil { return nil, false } - return o.ImageAlias, true + return o.DeviceNumber, true } -// SetImageAlias sets field value -func (o *VolumeProperties) SetImageAlias(v string) { +// SetDeviceNumber sets field value +func (o *VolumeProperties) SetDeviceNumber(v int64) { - o.ImageAlias = &v + o.DeviceNumber = &v } -// HasImageAlias returns a boolean if a field has been set. -func (o *VolumeProperties) HasImageAlias() bool { - if o != nil && o.ImageAlias != nil { +// HasDeviceNumber returns a boolean if a field has been set. +func (o *VolumeProperties) HasDeviceNumber() bool { + if o != nil && o.DeviceNumber != nil { return true } return false } -// GetSshKeys returns the SshKeys field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *VolumeProperties) GetSshKeys() *[]string { +// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetDiscVirtioHotPlug() *bool { if o == nil { return nil } - return o.SshKeys + return o.DiscVirtioHotPlug } -// GetSshKeysOk returns a tuple with the SshKeys field value +// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetSshKeysOk() (*[]string, bool) { +func (o *VolumeProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.SshKeys, true + return o.DiscVirtioHotPlug, true } -// SetSshKeys sets field value -func (o *VolumeProperties) SetSshKeys(v []string) { +// SetDiscVirtioHotPlug sets field value +func (o *VolumeProperties) SetDiscVirtioHotPlug(v bool) { - o.SshKeys = &v + o.DiscVirtioHotPlug = &v } -// HasSshKeys returns a boolean if a field has been set. -func (o *VolumeProperties) HasSshKeys() bool { - if o != nil && o.SshKeys != nil { +// HasDiscVirtioHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasDiscVirtioHotPlug() bool { + if o != nil && o.DiscVirtioHotPlug != nil { return true } return false } -// GetBus returns the Bus field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBus() *string { +// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetDiscVirtioHotUnplug() *bool { if o == nil { return nil } - return o.Bus + return o.DiscVirtioHotUnplug } -// GetBusOk returns a tuple with the Bus field value +// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBusOk() (*string, bool) { +func (o *VolumeProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Bus, true + return o.DiscVirtioHotUnplug, true } -// SetBus sets field value -func (o *VolumeProperties) SetBus(v string) { +// SetDiscVirtioHotUnplug sets field value +func (o *VolumeProperties) SetDiscVirtioHotUnplug(v bool) { - o.Bus = &v + o.DiscVirtioHotUnplug = &v } -// HasBus returns a boolean if a field has been set. -func (o *VolumeProperties) HasBus() bool { - if o != nil && o.Bus != nil { +// HasDiscVirtioHotUnplug returns a boolean if a field has been set. +func (o *VolumeProperties) HasDiscVirtioHotUnplug() bool { + if o != nil && o.DiscVirtioHotUnplug != nil { return true } return false } -// GetLicenceType returns the LicenceType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetLicenceType() *string { +// GetImage returns the Image field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetImage() *string { if o == nil { return nil } - return o.LicenceType + return o.Image } -// GetLicenceTypeOk returns a tuple with the LicenceType field value +// GetImageOk returns a tuple with the Image field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetLicenceTypeOk() (*string, bool) { +func (o *VolumeProperties) GetImageOk() (*string, bool) { if o == nil { return nil, false } - return o.LicenceType, true + return o.Image, true } -// SetLicenceType sets field value -func (o *VolumeProperties) SetLicenceType(v string) { +// SetImage sets field value +func (o *VolumeProperties) SetImage(v string) { - o.LicenceType = &v + o.Image = &v } -// HasLicenceType returns a boolean if a field has been set. -func (o *VolumeProperties) HasLicenceType() bool { - if o != nil && o.LicenceType != nil { +// HasImage returns a boolean if a field has been set. +func (o *VolumeProperties) HasImage() bool { + if o != nil && o.Image != nil { return true } return false } -// GetCpuHotPlug returns the CpuHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetCpuHotPlug() *bool { +// GetImageAlias returns the ImageAlias field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetImageAlias() *string { if o == nil { return nil } - return o.CpuHotPlug + return o.ImageAlias } -// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value +// GetImageAliasOk returns a tuple with the ImageAlias field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetCpuHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetImageAliasOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuHotPlug, true + return o.ImageAlias, true } -// SetCpuHotPlug sets field value -func (o *VolumeProperties) SetCpuHotPlug(v bool) { +// SetImageAlias sets field value +func (o *VolumeProperties) SetImageAlias(v string) { - o.CpuHotPlug = &v + o.ImageAlias = &v } -// HasCpuHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasCpuHotPlug() bool { - if o != nil && o.CpuHotPlug != nil { +// HasImageAlias returns a boolean if a field has been set. +func (o *VolumeProperties) HasImageAlias() bool { + if o != nil && o.ImageAlias != nil { return true } return false } -// GetRamHotPlug returns the RamHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetRamHotPlug() *bool { +// GetImagePassword returns the ImagePassword field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetImagePassword() *string { if o == nil { return nil } - return o.RamHotPlug + return o.ImagePassword } -// GetRamHotPlugOk returns a tuple with the RamHotPlug field value +// GetImagePasswordOk returns a tuple with the ImagePassword field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetRamHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetImagePasswordOk() (*string, bool) { if o == nil { return nil, false } - return o.RamHotPlug, true + return o.ImagePassword, true } -// SetRamHotPlug sets field value -func (o *VolumeProperties) SetRamHotPlug(v bool) { +// SetImagePassword sets field value +func (o *VolumeProperties) SetImagePassword(v string) { - o.RamHotPlug = &v + o.ImagePassword = &v } -// HasRamHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasRamHotPlug() bool { - if o != nil && o.RamHotPlug != nil { +// HasImagePassword returns a boolean if a field has been set. +func (o *VolumeProperties) HasImagePassword() bool { + if o != nil && o.ImagePassword != nil { return true } return false } -// GetNicHotPlug returns the NicHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetNicHotPlug() *bool { +// GetLicenceType returns the LicenceType field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetLicenceType() *string { if o == nil { return nil } - return o.NicHotPlug + return o.LicenceType } -// GetNicHotPlugOk returns a tuple with the NicHotPlug field value +// GetLicenceTypeOk returns a tuple with the LicenceType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetNicHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetLicenceTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.NicHotPlug, true + return o.LicenceType, true } -// SetNicHotPlug sets field value -func (o *VolumeProperties) SetNicHotPlug(v bool) { +// SetLicenceType sets field value +func (o *VolumeProperties) SetLicenceType(v string) { - o.NicHotPlug = &v + o.LicenceType = &v } -// HasNicHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasNicHotPlug() bool { - if o != nil && o.NicHotPlug != nil { +// HasLicenceType returns a boolean if a field has been set. +func (o *VolumeProperties) HasLicenceType() bool { + if o != nil && o.LicenceType != nil { return true } return false } -// GetNicHotUnplug returns the NicHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetNicHotUnplug() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetName() *string { if o == nil { return nil } - return o.NicHotUnplug + return o.Name } -// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetNicHotUnplugOk() (*bool, bool) { +func (o *VolumeProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.NicHotUnplug, true + return o.Name, true } -// SetNicHotUnplug sets field value -func (o *VolumeProperties) SetNicHotUnplug(v bool) { +// SetName sets field value +func (o *VolumeProperties) SetName(v string) { - o.NicHotUnplug = &v + o.Name = &v } -// HasNicHotUnplug returns a boolean if a field has been set. -func (o *VolumeProperties) HasNicHotUnplug() bool { - if o != nil && o.NicHotUnplug != nil { +// HasName returns a boolean if a field has been set. +func (o *VolumeProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetDiscVirtioHotPlug() *bool { +// GetNicHotPlug returns the NicHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetNicHotPlug() *bool { if o == nil { return nil } - return o.DiscVirtioHotPlug + return o.NicHotPlug } -// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value +// GetNicHotPlugOk returns a tuple with the NicHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetNicHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotPlug, true + return o.NicHotPlug, true } -// SetDiscVirtioHotPlug sets field value -func (o *VolumeProperties) SetDiscVirtioHotPlug(v bool) { +// SetNicHotPlug sets field value +func (o *VolumeProperties) SetNicHotPlug(v bool) { - o.DiscVirtioHotPlug = &v + o.NicHotPlug = &v } -// HasDiscVirtioHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasDiscVirtioHotPlug() bool { - if o != nil && o.DiscVirtioHotPlug != nil { +// HasNicHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasNicHotPlug() bool { + if o != nil && o.NicHotPlug != nil { return true } return false } -// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetDiscVirtioHotUnplug() *bool { +// GetNicHotUnplug returns the NicHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetNicHotUnplug() *bool { if o == nil { return nil } - return o.DiscVirtioHotUnplug + return o.NicHotUnplug } -// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value +// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { +func (o *VolumeProperties) GetNicHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotUnplug, true + return o.NicHotUnplug, true } -// SetDiscVirtioHotUnplug sets field value -func (o *VolumeProperties) SetDiscVirtioHotUnplug(v bool) { +// SetNicHotUnplug sets field value +func (o *VolumeProperties) SetNicHotUnplug(v bool) { - o.DiscVirtioHotUnplug = &v + o.NicHotUnplug = &v } -// HasDiscVirtioHotUnplug returns a boolean if a field has been set. -func (o *VolumeProperties) HasDiscVirtioHotUnplug() bool { - if o != nil && o.DiscVirtioHotUnplug != nil { +// HasNicHotUnplug returns a boolean if a field has been set. +func (o *VolumeProperties) HasNicHotUnplug() bool { + if o != nil && o.NicHotUnplug != nil { return true } return false } -// GetDeviceNumber returns the DeviceNumber field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *VolumeProperties) GetDeviceNumber() *int64 { +// GetPciSlot returns the PciSlot field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetPciSlot() *int32 { if o == nil { return nil } - return o.DeviceNumber + return o.PciSlot } -// GetDeviceNumberOk returns a tuple with the DeviceNumber field value +// GetPciSlotOk returns a tuple with the PciSlot field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetDeviceNumberOk() (*int64, bool) { +func (o *VolumeProperties) GetPciSlotOk() (*int32, bool) { if o == nil { return nil, false } - return o.DeviceNumber, true + return o.PciSlot, true } -// SetDeviceNumber sets field value -func (o *VolumeProperties) SetDeviceNumber(v int64) { +// SetPciSlot sets field value +func (o *VolumeProperties) SetPciSlot(v int32) { - o.DeviceNumber = &v + o.PciSlot = &v } -// HasDeviceNumber returns a boolean if a field has been set. -func (o *VolumeProperties) HasDeviceNumber() bool { - if o != nil && o.DeviceNumber != nil { +// HasPciSlot returns a boolean if a field has been set. +func (o *VolumeProperties) HasPciSlot() bool { + if o != nil && o.PciSlot != nil { return true } return false } -// GetPciSlot returns the PciSlot field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *VolumeProperties) GetPciSlot() *int32 { +// GetRamHotPlug returns the RamHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetRamHotPlug() *bool { if o == nil { return nil } - return o.PciSlot + return o.RamHotPlug } -// GetPciSlotOk returns a tuple with the PciSlot field value +// GetRamHotPlugOk returns a tuple with the RamHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetPciSlotOk() (*int32, bool) { +func (o *VolumeProperties) GetRamHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.PciSlot, true + return o.RamHotPlug, true } -// SetPciSlot sets field value -func (o *VolumeProperties) SetPciSlot(v int32) { +// SetRamHotPlug sets field value +func (o *VolumeProperties) SetRamHotPlug(v bool) { - o.PciSlot = &v + o.RamHotPlug = &v } -// HasPciSlot returns a boolean if a field has been set. -func (o *VolumeProperties) HasPciSlot() bool { - if o != nil && o.PciSlot != nil { +// HasRamHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasRamHotPlug() bool { + if o != nil && o.RamHotPlug != nil { return true } return false } -// GetBackupunitId returns the BackupunitId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBackupunitId() *string { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetSize() *float32 { if o == nil { return nil } - return o.BackupunitId + return o.Size } -// GetBackupunitIdOk returns a tuple with the BackupunitId field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBackupunitIdOk() (*string, bool) { +func (o *VolumeProperties) GetSizeOk() (*float32, bool) { if o == nil { return nil, false } - return o.BackupunitId, true + return o.Size, true } -// SetBackupunitId sets field value -func (o *VolumeProperties) SetBackupunitId(v string) { +// SetSize sets field value +func (o *VolumeProperties) SetSize(v float32) { - o.BackupunitId = &v + o.Size = &v } -// HasBackupunitId returns a boolean if a field has been set. -func (o *VolumeProperties) HasBackupunitId() bool { - if o != nil && o.BackupunitId != nil { +// HasSize returns a boolean if a field has been set. +func (o *VolumeProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } return false } -// GetUserData returns the UserData field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetUserData() *string { +// GetSshKeys returns the SshKeys field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetSshKeys() *[]string { if o == nil { return nil } - return o.UserData + return o.SshKeys } -// GetUserDataOk returns a tuple with the UserData field value +// GetSshKeysOk returns a tuple with the SshKeys field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetUserDataOk() (*string, bool) { +func (o *VolumeProperties) GetSshKeysOk() (*[]string, bool) { if o == nil { return nil, false } - return o.UserData, true + return o.SshKeys, true } -// SetUserData sets field value -func (o *VolumeProperties) SetUserData(v string) { +// SetSshKeys sets field value +func (o *VolumeProperties) SetSshKeys(v []string) { - o.UserData = &v + o.SshKeys = &v } -// HasUserData returns a boolean if a field has been set. -func (o *VolumeProperties) HasUserData() bool { - if o != nil && o.UserData != nil { +// HasSshKeys returns a boolean if a field has been set. +func (o *VolumeProperties) HasSshKeys() bool { + if o != nil && o.SshKeys != nil { return true } return false } -// GetBootServer returns the BootServer field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBootServer() *string { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetType() *string { if o == nil { return nil } - return o.BootServer + return o.Type } -// GetBootServerOk returns a tuple with the BootServer field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBootServerOk() (*string, bool) { +func (o *VolumeProperties) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.BootServer, true + return o.Type, true } -// SetBootServer sets field value -func (o *VolumeProperties) SetBootServer(v string) { +// SetType sets field value +func (o *VolumeProperties) SetType(v string) { - o.BootServer = &v + o.Type = &v } -// HasBootServer returns a boolean if a field has been set. -func (o *VolumeProperties) HasBootServer() bool { - if o != nil && o.BootServer != nil { +// HasType returns a boolean if a field has been set. +func (o *VolumeProperties) HasType() bool { + if o != nil && o.Type != nil { return true } return false } -// GetBootOrder returns the BootOrder field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBootOrder() *string { +// GetUserData returns the UserData field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetUserData() *string { if o == nil { return nil } - return o.BootOrder + return o.UserData } -// GetBootOrderOk returns a tuple with the BootOrder field value +// GetUserDataOk returns a tuple with the UserData field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBootOrderOk() (*string, bool) { +func (o *VolumeProperties) GetUserDataOk() (*string, bool) { if o == nil { return nil, false } - return o.BootOrder, true + return o.UserData, true } -// SetBootOrder sets field value -func (o *VolumeProperties) SetBootOrder(v string) { +// SetUserData sets field value +func (o *VolumeProperties) SetUserData(v string) { - o.BootOrder = &v + o.UserData = &v } -// HasBootOrder returns a boolean if a field has been set. -func (o *VolumeProperties) HasBootOrder() bool { - if o != nil && o.BootOrder != nil { +// HasUserData returns a boolean if a field has been set. +func (o *VolumeProperties) HasUserData() bool { + if o != nil && o.UserData != nil { return true } @@ -923,70 +929,95 @@ func (o *VolumeProperties) HasBootOrder() bool { func (o VolumeProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.AvailabilityZone != nil { + toSerialize["availabilityZone"] = o.AvailabilityZone } - if o.Type != nil { - toSerialize["type"] = o.Type + + if o.BackupunitId != nil { + toSerialize["backupunitId"] = o.BackupunitId } - if o.Size != nil { - toSerialize["size"] = o.Size + + if o.BootOrder == &Nilstring { + toSerialize["bootOrder"] = nil + } else if o.BootOrder != nil { + toSerialize["bootOrder"] = o.BootOrder } - if o.AvailabilityZone != nil { - toSerialize["availabilityZone"] = o.AvailabilityZone + if o.BootServer != nil { + toSerialize["bootServer"] = o.BootServer + } + + if o.Bus != nil { + toSerialize["bus"] = o.Bus + } + + if o.CpuHotPlug != nil { + toSerialize["cpuHotPlug"] = o.CpuHotPlug + } + + if o.DeviceNumber != nil { + toSerialize["deviceNumber"] = o.DeviceNumber + } + + if o.DiscVirtioHotPlug != nil { + toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug } + + if o.DiscVirtioHotUnplug != nil { + toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug + } + if o.Image != nil { toSerialize["image"] = o.Image } - if o.ImagePassword != nil { - toSerialize["imagePassword"] = o.ImagePassword - } + if o.ImageAlias != nil { toSerialize["imageAlias"] = o.ImageAlias } - if o.SshKeys != nil { - toSerialize["sshKeys"] = o.SshKeys - } - if o.Bus != nil { - toSerialize["bus"] = o.Bus + + if o.ImagePassword != nil { + toSerialize["imagePassword"] = o.ImagePassword } + if o.LicenceType != nil { toSerialize["licenceType"] = o.LicenceType } - if o.CpuHotPlug != nil { - toSerialize["cpuHotPlug"] = o.CpuHotPlug - } - if o.RamHotPlug != nil { - toSerialize["ramHotPlug"] = o.RamHotPlug + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.NicHotPlug != nil { toSerialize["nicHotPlug"] = o.NicHotPlug } + if o.NicHotUnplug != nil { toSerialize["nicHotUnplug"] = o.NicHotUnplug } - if o.DiscVirtioHotPlug != nil { - toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug + + if o.PciSlot != nil { + toSerialize["pciSlot"] = o.PciSlot } - if o.DiscVirtioHotUnplug != nil { - toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug + + if o.RamHotPlug != nil { + toSerialize["ramHotPlug"] = o.RamHotPlug } - if o.DeviceNumber != nil { - toSerialize["deviceNumber"] = o.DeviceNumber + + if o.Size != nil { + toSerialize["size"] = o.Size } - if o.PciSlot != nil { - toSerialize["pciSlot"] = o.PciSlot + + if o.SshKeys != nil { + toSerialize["sshKeys"] = o.SshKeys } - if o.BackupunitId != nil { - toSerialize["backupunitId"] = o.BackupunitId + + if o.Type != nil { + toSerialize["type"] = o.Type } + if o.UserData != nil { toSerialize["userData"] = o.UserData } - if o.BootServer != nil { - toSerialize["bootServer"] = o.BootServer - } - toSerialize["bootOrder"] = o.BootOrder + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go index dfe753d8e..ec795374f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go @@ -16,19 +16,19 @@ import ( // Volumes struct for Volumes type Volumes struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Volume `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewVolumes instantiates a new Volumes object @@ -49,114 +49,114 @@ func NewVolumesWithDefaults() *Volumes { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volumes) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetIdOk() (*string, bool) { +func (o *Volumes) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Volumes) SetId(v string) { +// SetLinks sets field value +func (o *Volumes) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Volumes) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Volumes) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Volumes) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetTypeOk() (*Type, bool) { +func (o *Volumes) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Volumes) SetType(v Type) { +// SetHref sets field value +func (o *Volumes) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Volumes) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Volumes) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volumes) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetHrefOk() (*string, bool) { +func (o *Volumes) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Volumes) SetHref(v string) { +// SetId sets field value +func (o *Volumes) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Volumes) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Volumes) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Volumes) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Volume will be returned +// If the value is explicit nil, nil is returned func (o *Volumes) GetItems() *[]Volume { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Volumes) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Volumes) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetOffsetOk() (*float32, bool) { +func (o *Volumes) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Volumes) SetOffset(v float32) { +// SetLimit sets field value +func (o *Volumes) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Volumes) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Volumes) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Volumes) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetLimitOk() (*float32, bool) { +func (o *Volumes) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Volumes) SetLimit(v float32) { +// SetOffset sets field value +func (o *Volumes) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Volumes) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Volumes) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Volumes) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetLinksOk() (*PaginationLinks, bool) { +func (o *Volumes) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Volumes) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Volumes) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Volumes) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Volumes) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Volumes) HasLinks() bool { func (o Volumes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go b/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go index ee096c731..08c0967d4 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go @@ -17,6 +17,14 @@ import ( "time" ) +var ( + // used to set a nullable field to nil. This is a sentinel address that will be checked in the MarshalJson function. + // if set to this address, a nil value will be marshalled + Nilstring string = "<>" + Nilint32 int32 = -334455 + Nilbool bool = false +) + // ToPtr - returns a pointer to the given value. func ToPtr[T any](v T) *T { return &v diff --git a/vendor/github.com/klauspost/compress/.gitattributes b/vendor/github.com/klauspost/compress/.gitattributes new file mode 100644 index 000000000..402433593 --- /dev/null +++ b/vendor/github.com/klauspost/compress/.gitattributes @@ -0,0 +1,2 @@ +* -text +*.bin -text -diff diff --git a/vendor/github.com/klauspost/compress/.gitignore b/vendor/github.com/klauspost/compress/.gitignore new file mode 100644 index 000000000..d31b37815 --- /dev/null +++ b/vendor/github.com/klauspost/compress/.gitignore @@ -0,0 +1,32 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof +/s2/cmd/_s2sx/sfx-exe + +# Linux perf files +perf.data +perf.data.old + +# gdb history +.gdb_history diff --git a/vendor/github.com/klauspost/compress/.goreleaser.yml b/vendor/github.com/klauspost/compress/.goreleaser.yml new file mode 100644 index 000000000..4c28dff46 --- /dev/null +++ b/vendor/github.com/klauspost/compress/.goreleaser.yml @@ -0,0 +1,127 @@ +# This is an example goreleaser.yaml file with some sane defaults. +# Make sure to check the documentation at http://goreleaser.com +before: + hooks: + - ./gen.sh + - go install mvdan.cc/garble@v0.10.1 + +builds: + - + id: "s2c" + binary: s2c + main: ./s2/cmd/s2c/main.go + flags: + - -trimpath + env: + - CGO_ENABLED=0 + goos: + - aix + - linux + - freebsd + - netbsd + - windows + - darwin + goarch: + - 386 + - amd64 + - arm + - arm64 + - ppc64 + - ppc64le + - mips64 + - mips64le + goarm: + - 7 + gobinary: garble + - + id: "s2d" + binary: s2d + main: ./s2/cmd/s2d/main.go + flags: + - -trimpath + env: + - CGO_ENABLED=0 + goos: + - aix + - linux + - freebsd + - netbsd + - windows + - darwin + goarch: + - 386 + - amd64 + - arm + - arm64 + - ppc64 + - ppc64le + - mips64 + - mips64le + goarm: + - 7 + gobinary: garble + - + id: "s2sx" + binary: s2sx + main: ./s2/cmd/_s2sx/main.go + flags: + - -modfile=s2sx.mod + - -trimpath + env: + - CGO_ENABLED=0 + goos: + - aix + - linux + - freebsd + - netbsd + - windows + - darwin + goarch: + - 386 + - amd64 + - arm + - arm64 + - ppc64 + - ppc64le + - mips64 + - mips64le + goarm: + - 7 + gobinary: garble + +archives: + - + id: s2-binaries + name_template: "s2-{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" + format_overrides: + - goos: windows + format: zip + files: + - unpack/* + - s2/LICENSE + - s2/README.md +checksum: + name_template: 'checksums.txt' +snapshot: + name_template: "{{ .Tag }}-next" +changelog: + sort: asc + filters: + exclude: + - '^doc:' + - '^docs:' + - '^test:' + - '^tests:' + - '^Update\sREADME.md' + +nfpms: + - + file_name_template: "s2_package__{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" + vendor: Klaus Post + homepage: https://github.com/klauspost/compress + maintainer: Klaus Post + description: S2 Compression Tool + license: BSD 3-Clause + formats: + - deb + - rpm diff --git a/vendor/github.com/klauspost/compress/LICENSE b/vendor/github.com/klauspost/compress/LICENSE new file mode 100644 index 000000000..87d557477 --- /dev/null +++ b/vendor/github.com/klauspost/compress/LICENSE @@ -0,0 +1,304 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. +Copyright (c) 2019 Klaus Post. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------ + +Files: gzhttp/* + + 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 2016-2017 The New York Times Company + + 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. + +------------------ + +Files: s2/cmd/internal/readahead/* + +The MIT License (MIT) + +Copyright (c) 2015 Klaus Post + +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. + +--------------------- +Files: snappy/* +Files: internal/snapref/* + +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----------------- + +Files: s2/cmd/internal/filepathx/* + +Copyright 2016 The filepathx Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md new file mode 100644 index 000000000..7e83f583c --- /dev/null +++ b/vendor/github.com/klauspost/compress/README.md @@ -0,0 +1,669 @@ +# compress + +This package provides various compression algorithms. + +* [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and decompression in pure Go. +* [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) is a high performance replacement for Snappy. +* Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). +* [snappy](https://github.com/klauspost/compress/tree/master/snappy) is a drop-in replacement for `github.com/golang/snappy` offering better compression and concurrent streams. +* [huff0](https://github.com/klauspost/compress/tree/master/huff0) and [FSE](https://github.com/klauspost/compress/tree/master/fse) implementations for raw entropy encoding. +* [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp) Provides client and server wrappers for handling gzipped requests efficiently. +* [pgzip](https://github.com/klauspost/pgzip) is a separate package that provides a very fast parallel gzip implementation. + +[![Go Reference](https://pkg.go.dev/badge/klauspost/compress.svg)](https://pkg.go.dev/github.com/klauspost/compress?tab=subdirectories) +[![Go](https://github.com/klauspost/compress/actions/workflows/go.yml/badge.svg)](https://github.com/klauspost/compress/actions/workflows/go.yml) +[![Sourcegraph Badge](https://sourcegraph.com/github.com/klauspost/compress/-/badge.svg)](https://sourcegraph.com/github.com/klauspost/compress?badge) + +# changelog + +* Oct 22nd, 2023 - [v1.17.2](https://github.com/klauspost/compress/releases/tag/v1.17.2) + * zstd: Fix rare *CORRUPTION* output in "best" mode. See https://github.com/klauspost/compress/pull/876 + +* Oct 14th, 2023 - [v1.17.1](https://github.com/klauspost/compress/releases/tag/v1.17.1) + * s2: Fix S2 "best" dictionary wrong encoding by @klauspost in https://github.com/klauspost/compress/pull/871 + * flate: Reduce allocations in decompressor and minor code improvements by @fakefloordiv in https://github.com/klauspost/compress/pull/869 + * s2: Fix EstimateBlockSize on 6&7 length input by @klauspost in https://github.com/klauspost/compress/pull/867 + +* Sept 19th, 2023 - [v1.17.0](https://github.com/klauspost/compress/releases/tag/v1.17.0) + * Add experimental dictionary builder https://github.com/klauspost/compress/pull/853 + * Add xerial snappy read/writer https://github.com/klauspost/compress/pull/838 + * flate: Add limited window compression https://github.com/klauspost/compress/pull/843 + * s2: Do 2 overlapping match checks https://github.com/klauspost/compress/pull/839 + * flate: Add amd64 assembly matchlen https://github.com/klauspost/compress/pull/837 + * gzip: Copy bufio.Reader on Reset by @thatguystone in https://github.com/klauspost/compress/pull/860 + +* July 1st, 2023 - [v1.16.7](https://github.com/klauspost/compress/releases/tag/v1.16.7) + * zstd: Fix default level first dictionary encode https://github.com/klauspost/compress/pull/829 + * s2: add GetBufferCapacity() method by @GiedriusS in https://github.com/klauspost/compress/pull/832 + +* June 13, 2023 - [v1.16.6](https://github.com/klauspost/compress/releases/tag/v1.16.6) + * zstd: correctly ignore WithEncoderPadding(1) by @ianlancetaylor in https://github.com/klauspost/compress/pull/806 + * zstd: Add amd64 match length assembly https://github.com/klauspost/compress/pull/824 + * gzhttp: Handle informational headers by @rtribotte in https://github.com/klauspost/compress/pull/815 + * s2: Improve Better compression slightly https://github.com/klauspost/compress/pull/663 + +* Apr 16, 2023 - [v1.16.5](https://github.com/klauspost/compress/releases/tag/v1.16.5) + * zstd: readByte needs to use io.ReadFull by @jnoxon in https://github.com/klauspost/compress/pull/802 + * gzip: Fix WriterTo after initial read https://github.com/klauspost/compress/pull/804 + +* Apr 5, 2023 - [v1.16.4](https://github.com/klauspost/compress/releases/tag/v1.16.4) + * zstd: Improve zstd best efficiency by @greatroar and @klauspost in https://github.com/klauspost/compress/pull/784 + * zstd: Respect WithAllLitEntropyCompression https://github.com/klauspost/compress/pull/792 + * zstd: Fix amd64 not always detecting corrupt data https://github.com/klauspost/compress/pull/785 + * zstd: Various minor improvements by @greatroar in https://github.com/klauspost/compress/pull/788 https://github.com/klauspost/compress/pull/794 https://github.com/klauspost/compress/pull/795 + * s2: Fix huge block overflow https://github.com/klauspost/compress/pull/779 + * s2: Allow CustomEncoder fallback https://github.com/klauspost/compress/pull/780 + * gzhttp: Suppport ResponseWriter Unwrap() in gzhttp handler by @jgimenez in https://github.com/klauspost/compress/pull/799 + +* Mar 13, 2023 - [v1.16.1](https://github.com/klauspost/compress/releases/tag/v1.16.1) + * zstd: Speed up + improve best encoder by @greatroar in https://github.com/klauspost/compress/pull/776 + * gzhttp: Add optional [BREACH mitigation](https://github.com/klauspost/compress/tree/master/gzhttp#breach-mitigation). https://github.com/klauspost/compress/pull/762 https://github.com/klauspost/compress/pull/768 https://github.com/klauspost/compress/pull/769 https://github.com/klauspost/compress/pull/770 https://github.com/klauspost/compress/pull/767 + * s2: Add Intel LZ4s converter https://github.com/klauspost/compress/pull/766 + * zstd: Minor bug fixes https://github.com/klauspost/compress/pull/771 https://github.com/klauspost/compress/pull/772 https://github.com/klauspost/compress/pull/773 + * huff0: Speed up compress1xDo by @greatroar in https://github.com/klauspost/compress/pull/774 + +* Feb 26, 2023 - [v1.16.0](https://github.com/klauspost/compress/releases/tag/v1.16.0) + * s2: Add [Dictionary](https://github.com/klauspost/compress/tree/master/s2#dictionaries) support. https://github.com/klauspost/compress/pull/685 + * s2: Add Compression Size Estimate. https://github.com/klauspost/compress/pull/752 + * s2: Add support for custom stream encoder. https://github.com/klauspost/compress/pull/755 + * s2: Add LZ4 block converter. https://github.com/klauspost/compress/pull/748 + * s2: Support io.ReaderAt in ReadSeeker. https://github.com/klauspost/compress/pull/747 + * s2c/s2sx: Use concurrent decoding. https://github.com/klauspost/compress/pull/746 + +
      + See changes to v1.15.x + +* Jan 21st, 2023 (v1.15.15) + * deflate: Improve level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/739 + * zstd: Add delta encoding support by @greatroar in https://github.com/klauspost/compress/pull/728 + * zstd: Various speed improvements by @greatroar https://github.com/klauspost/compress/pull/741 https://github.com/klauspost/compress/pull/734 https://github.com/klauspost/compress/pull/736 https://github.com/klauspost/compress/pull/744 https://github.com/klauspost/compress/pull/743 https://github.com/klauspost/compress/pull/745 + * gzhttp: Add SuffixETag() and DropETag() options to prevent ETag collisions on compressed responses by @willbicks in https://github.com/klauspost/compress/pull/740 + +* Jan 3rd, 2023 (v1.15.14) + + * flate: Improve speed in big stateless blocks https://github.com/klauspost/compress/pull/718 + * zstd: Minor speed tweaks by @greatroar in https://github.com/klauspost/compress/pull/716 https://github.com/klauspost/compress/pull/720 + * export NoGzipResponseWriter for custom ResponseWriter wrappers by @harshavardhana in https://github.com/klauspost/compress/pull/722 + * s2: Add example for indexing and existing stream https://github.com/klauspost/compress/pull/723 + +* Dec 11, 2022 (v1.15.13) + * zstd: Add [MaxEncodedSize](https://pkg.go.dev/github.com/klauspost/compress@v1.15.13/zstd#Encoder.MaxEncodedSize) to encoder https://github.com/klauspost/compress/pull/691 + * zstd: Various tweaks and improvements https://github.com/klauspost/compress/pull/693 https://github.com/klauspost/compress/pull/695 https://github.com/klauspost/compress/pull/696 https://github.com/klauspost/compress/pull/701 https://github.com/klauspost/compress/pull/702 https://github.com/klauspost/compress/pull/703 https://github.com/klauspost/compress/pull/704 https://github.com/klauspost/compress/pull/705 https://github.com/klauspost/compress/pull/706 https://github.com/klauspost/compress/pull/707 https://github.com/klauspost/compress/pull/708 + +* Oct 26, 2022 (v1.15.12) + + * zstd: Tweak decoder allocs. https://github.com/klauspost/compress/pull/680 + * gzhttp: Always delete `HeaderNoCompression` https://github.com/klauspost/compress/pull/683 + +* Sept 26, 2022 (v1.15.11) + + * flate: Improve level 1-3 compression https://github.com/klauspost/compress/pull/678 + * zstd: Improve "best" compression by @nightwolfz in https://github.com/klauspost/compress/pull/677 + * zstd: Fix+reduce decompression allocations https://github.com/klauspost/compress/pull/668 + * zstd: Fix non-effective noescape tag https://github.com/klauspost/compress/pull/667 + +* Sept 16, 2022 (v1.15.10) + + * zstd: Add [WithDecodeAllCapLimit](https://pkg.go.dev/github.com/klauspost/compress@v1.15.10/zstd#WithDecodeAllCapLimit) https://github.com/klauspost/compress/pull/649 + * Add Go 1.19 - deprecate Go 1.16 https://github.com/klauspost/compress/pull/651 + * flate: Improve level 5+6 compression https://github.com/klauspost/compress/pull/656 + * zstd: Improve "better" compresssion https://github.com/klauspost/compress/pull/657 + * s2: Improve "best" compression https://github.com/klauspost/compress/pull/658 + * s2: Improve "better" compression. https://github.com/klauspost/compress/pull/635 + * s2: Slightly faster non-assembly decompression https://github.com/klauspost/compress/pull/646 + * Use arrays for constant size copies https://github.com/klauspost/compress/pull/659 + +* July 21, 2022 (v1.15.9) + + * zstd: Fix decoder crash on amd64 (no BMI) on invalid input https://github.com/klauspost/compress/pull/645 + * zstd: Disable decoder extended memory copies (amd64) due to possible crashes https://github.com/klauspost/compress/pull/644 + * zstd: Allow single segments up to "max decoded size" by @klauspost in https://github.com/klauspost/compress/pull/643 + +* July 13, 2022 (v1.15.8) + + * gzip: fix stack exhaustion bug in Reader.Read https://github.com/klauspost/compress/pull/641 + * s2: Add Index header trim/restore https://github.com/klauspost/compress/pull/638 + * zstd: Optimize seqdeq amd64 asm by @greatroar in https://github.com/klauspost/compress/pull/636 + * zstd: Improve decoder memcopy https://github.com/klauspost/compress/pull/637 + * huff0: Pass a single bitReader pointer to asm by @greatroar in https://github.com/klauspost/compress/pull/634 + * zstd: Branchless getBits for amd64 w/o BMI2 by @greatroar in https://github.com/klauspost/compress/pull/640 + * gzhttp: Remove header before writing https://github.com/klauspost/compress/pull/639 + +* June 29, 2022 (v1.15.7) + + * s2: Fix absolute forward seeks https://github.com/klauspost/compress/pull/633 + * zip: Merge upstream https://github.com/klauspost/compress/pull/631 + * zip: Re-add zip64 fix https://github.com/klauspost/compress/pull/624 + * zstd: translate fseDecoder.buildDtable into asm by @WojciechMula in https://github.com/klauspost/compress/pull/598 + * flate: Faster histograms https://github.com/klauspost/compress/pull/620 + * deflate: Use compound hcode https://github.com/klauspost/compress/pull/622 + +* June 3, 2022 (v1.15.6) + * s2: Improve coding for long, close matches https://github.com/klauspost/compress/pull/613 + * s2c: Add Snappy/S2 stream recompression https://github.com/klauspost/compress/pull/611 + * zstd: Always use configured block size https://github.com/klauspost/compress/pull/605 + * zstd: Fix incorrect hash table placement for dict encoding in default https://github.com/klauspost/compress/pull/606 + * zstd: Apply default config to ZipDecompressor without options https://github.com/klauspost/compress/pull/608 + * gzhttp: Exclude more common archive formats https://github.com/klauspost/compress/pull/612 + * s2: Add ReaderIgnoreCRC https://github.com/klauspost/compress/pull/609 + * s2: Remove sanity load on index creation https://github.com/klauspost/compress/pull/607 + * snappy: Use dedicated function for scoring https://github.com/klauspost/compress/pull/614 + * s2c+s2d: Use official snappy framed extension https://github.com/klauspost/compress/pull/610 + +* May 25, 2022 (v1.15.5) + * s2: Add concurrent stream decompression https://github.com/klauspost/compress/pull/602 + * s2: Fix final emit oob read crash on amd64 https://github.com/klauspost/compress/pull/601 + * huff0: asm implementation of Decompress1X by @WojciechMula https://github.com/klauspost/compress/pull/596 + * zstd: Use 1 less goroutine for stream decoding https://github.com/klauspost/compress/pull/588 + * zstd: Copy literal in 16 byte blocks when possible https://github.com/klauspost/compress/pull/592 + * zstd: Speed up when WithDecoderLowmem(false) https://github.com/klauspost/compress/pull/599 + * zstd: faster next state update in BMI2 version of decode by @WojciechMula in https://github.com/klauspost/compress/pull/593 + * huff0: Do not check max size when reading table. https://github.com/klauspost/compress/pull/586 + * flate: Inplace hashing for level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/590 + + +* May 11, 2022 (v1.15.4) + * huff0: decompress directly into output by @WojciechMula in [#577](https://github.com/klauspost/compress/pull/577) + * inflate: Keep dict on stack [#581](https://github.com/klauspost/compress/pull/581) + * zstd: Faster decoding memcopy in asm [#583](https://github.com/klauspost/compress/pull/583) + * zstd: Fix ignored crc [#580](https://github.com/klauspost/compress/pull/580) + +* May 5, 2022 (v1.15.3) + * zstd: Allow to ignore checksum checking by @WojciechMula [#572](https://github.com/klauspost/compress/pull/572) + * s2: Fix incorrect seek for io.SeekEnd in [#575](https://github.com/klauspost/compress/pull/575) + +* Apr 26, 2022 (v1.15.2) + * zstd: Add x86-64 assembly for decompression on streams and blocks. Contributed by [@WojciechMula](https://github.com/WojciechMula). Typically 2x faster. [#528](https://github.com/klauspost/compress/pull/528) [#531](https://github.com/klauspost/compress/pull/531) [#545](https://github.com/klauspost/compress/pull/545) [#537](https://github.com/klauspost/compress/pull/537) + * zstd: Add options to ZipDecompressor and fixes [#539](https://github.com/klauspost/compress/pull/539) + * s2: Use sorted search for index [#555](https://github.com/klauspost/compress/pull/555) + * Minimum version is Go 1.16, added CI test on 1.18. + +* Mar 11, 2022 (v1.15.1) + * huff0: Add x86 assembly of Decode4X by @WojciechMula in [#512](https://github.com/klauspost/compress/pull/512) + * zstd: Reuse zip decoders in [#514](https://github.com/klauspost/compress/pull/514) + * zstd: Detect extra block data and report as corrupted in [#520](https://github.com/klauspost/compress/pull/520) + * zstd: Handle zero sized frame content size stricter in [#521](https://github.com/klauspost/compress/pull/521) + * zstd: Add stricter block size checks in [#523](https://github.com/klauspost/compress/pull/523) + +* Mar 3, 2022 (v1.15.0) + * zstd: Refactor decoder by @klauspost in [#498](https://github.com/klauspost/compress/pull/498) + * zstd: Add stream encoding without goroutines by @klauspost in [#505](https://github.com/klauspost/compress/pull/505) + * huff0: Prevent single blocks exceeding 16 bits by @klauspost in[#507](https://github.com/klauspost/compress/pull/507) + * flate: Inline literal emission by @klauspost in [#509](https://github.com/klauspost/compress/pull/509) + * gzhttp: Add zstd to transport by @klauspost in [#400](https://github.com/klauspost/compress/pull/400) + * gzhttp: Make content-type optional by @klauspost in [#510](https://github.com/klauspost/compress/pull/510) + +Both compression and decompression now supports "synchronous" stream operations. This means that whenever "concurrency" is set to 1, they will operate without spawning goroutines. + +Stream decompression is now faster on asynchronous, since the goroutine allocation much more effectively splits the workload. On typical streams this will typically use 2 cores fully for decompression. When a stream has finished decoding no goroutines will be left over, so decoders can now safely be pooled and still be garbage collected. + +While the release has been extensively tested, it is recommended to testing when upgrading. + +
      + +
      + See changes to v1.14.x + +* Feb 22, 2022 (v1.14.4) + * flate: Fix rare huffman only (-2) corruption. [#503](https://github.com/klauspost/compress/pull/503) + * zip: Update deprecated CreateHeaderRaw to correctly call CreateRaw by @saracen in [#502](https://github.com/klauspost/compress/pull/502) + * zip: don't read data descriptor early by @saracen in [#501](https://github.com/klauspost/compress/pull/501) #501 + * huff0: Use static decompression buffer up to 30% faster by @klauspost in [#499](https://github.com/klauspost/compress/pull/499) [#500](https://github.com/klauspost/compress/pull/500) + +* Feb 17, 2022 (v1.14.3) + * flate: Improve fastest levels compression speed ~10% more throughput. [#482](https://github.com/klauspost/compress/pull/482) [#489](https://github.com/klauspost/compress/pull/489) [#490](https://github.com/klauspost/compress/pull/490) [#491](https://github.com/klauspost/compress/pull/491) [#494](https://github.com/klauspost/compress/pull/494) [#478](https://github.com/klauspost/compress/pull/478) + * flate: Faster decompression speed, ~5-10%. [#483](https://github.com/klauspost/compress/pull/483) + * s2: Faster compression with Go v1.18 and amd64 microarch level 3+. [#484](https://github.com/klauspost/compress/pull/484) [#486](https://github.com/klauspost/compress/pull/486) + +* Jan 25, 2022 (v1.14.2) + * zstd: improve header decoder by @dsnet [#476](https://github.com/klauspost/compress/pull/476) + * zstd: Add bigger default blocks [#469](https://github.com/klauspost/compress/pull/469) + * zstd: Remove unused decompression buffer [#470](https://github.com/klauspost/compress/pull/470) + * zstd: Fix logically dead code by @ningmingxiao [#472](https://github.com/klauspost/compress/pull/472) + * flate: Improve level 7-9 [#471](https://github.com/klauspost/compress/pull/471) [#473](https://github.com/klauspost/compress/pull/473) + * zstd: Add noasm tag for xxhash [#475](https://github.com/klauspost/compress/pull/475) + +* Jan 11, 2022 (v1.14.1) + * s2: Add stream index in [#462](https://github.com/klauspost/compress/pull/462) + * flate: Speed and efficiency improvements in [#439](https://github.com/klauspost/compress/pull/439) [#461](https://github.com/klauspost/compress/pull/461) [#455](https://github.com/klauspost/compress/pull/455) [#452](https://github.com/klauspost/compress/pull/452) [#458](https://github.com/klauspost/compress/pull/458) + * zstd: Performance improvement in [#420]( https://github.com/klauspost/compress/pull/420) [#456](https://github.com/klauspost/compress/pull/456) [#437](https://github.com/klauspost/compress/pull/437) [#467](https://github.com/klauspost/compress/pull/467) [#468](https://github.com/klauspost/compress/pull/468) + * zstd: add arm64 xxhash assembly in [#464](https://github.com/klauspost/compress/pull/464) + * Add garbled for binaries for s2 in [#445](https://github.com/klauspost/compress/pull/445) +
      + +
      + See changes to v1.13.x + +* Aug 30, 2021 (v1.13.5) + * gz/zlib/flate: Alias stdlib errors [#425](https://github.com/klauspost/compress/pull/425) + * s2: Add block support to commandline tools [#413](https://github.com/klauspost/compress/pull/413) + * zstd: pooledZipWriter should return Writers to the same pool [#426](https://github.com/klauspost/compress/pull/426) + * Removed golang/snappy as external dependency for tests [#421](https://github.com/klauspost/compress/pull/421) + +* Aug 12, 2021 (v1.13.4) + * Add [snappy replacement package](https://github.com/klauspost/compress/tree/master/snappy). + * zstd: Fix incorrect encoding in "best" mode [#415](https://github.com/klauspost/compress/pull/415) + +* Aug 3, 2021 (v1.13.3) + * zstd: Improve Best compression [#404](https://github.com/klauspost/compress/pull/404) + * zstd: Fix WriteTo error forwarding [#411](https://github.com/klauspost/compress/pull/411) + * gzhttp: Return http.HandlerFunc instead of http.Handler. Unlikely breaking change. [#406](https://github.com/klauspost/compress/pull/406) + * s2sx: Fix max size error [#399](https://github.com/klauspost/compress/pull/399) + * zstd: Add optional stream content size on reset [#401](https://github.com/klauspost/compress/pull/401) + * zstd: use SpeedBestCompression for level >= 10 [#410](https://github.com/klauspost/compress/pull/410) + +* Jun 14, 2021 (v1.13.1) + * s2: Add full Snappy output support [#396](https://github.com/klauspost/compress/pull/396) + * zstd: Add configurable [Decoder window](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithDecoderMaxWindow) size [#394](https://github.com/klauspost/compress/pull/394) + * gzhttp: Add header to skip compression [#389](https://github.com/klauspost/compress/pull/389) + * s2: Improve speed with bigger output margin [#395](https://github.com/klauspost/compress/pull/395) + +* Jun 3, 2021 (v1.13.0) + * Added [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp#gzip-handler) which allows wrapping HTTP servers and clients with GZIP compressors. + * zstd: Detect short invalid signatures [#382](https://github.com/klauspost/compress/pull/382) + * zstd: Spawn decoder goroutine only if needed. [#380](https://github.com/klauspost/compress/pull/380) +
      + + +
      + See changes to v1.12.x + +* May 25, 2021 (v1.12.3) + * deflate: Better/faster Huffman encoding [#374](https://github.com/klauspost/compress/pull/374) + * deflate: Allocate less for history. [#375](https://github.com/klauspost/compress/pull/375) + * zstd: Forward read errors [#373](https://github.com/klauspost/compress/pull/373) + +* Apr 27, 2021 (v1.12.2) + * zstd: Improve better/best compression [#360](https://github.com/klauspost/compress/pull/360) [#364](https://github.com/klauspost/compress/pull/364) [#365](https://github.com/klauspost/compress/pull/365) + * zstd: Add helpers to compress/decompress zstd inside zip files [#363](https://github.com/klauspost/compress/pull/363) + * deflate: Improve level 5+6 compression [#367](https://github.com/klauspost/compress/pull/367) + * s2: Improve better/best compression [#358](https://github.com/klauspost/compress/pull/358) [#359](https://github.com/klauspost/compress/pull/358) + * s2: Load after checking src limit on amd64. [#362](https://github.com/klauspost/compress/pull/362) + * s2sx: Limit max executable size [#368](https://github.com/klauspost/compress/pull/368) + +* Apr 14, 2021 (v1.12.1) + * snappy package removed. Upstream added as dependency. + * s2: Better compression in "best" mode [#353](https://github.com/klauspost/compress/pull/353) + * s2sx: Add stdin input and detect pre-compressed from signature [#352](https://github.com/klauspost/compress/pull/352) + * s2c/s2d: Add http as possible input [#348](https://github.com/klauspost/compress/pull/348) + * s2c/s2d/s2sx: Always truncate when writing files [#352](https://github.com/klauspost/compress/pull/352) + * zstd: Reduce memory usage further when using [WithLowerEncoderMem](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithLowerEncoderMem) [#346](https://github.com/klauspost/compress/pull/346) + * s2: Fix potential problem with amd64 assembly and profilers [#349](https://github.com/klauspost/compress/pull/349) +
      + +
      + See changes to v1.11.x + +* Mar 26, 2021 (v1.11.13) + * zstd: Big speedup on small dictionary encodes [#344](https://github.com/klauspost/compress/pull/344) [#345](https://github.com/klauspost/compress/pull/345) + * zstd: Add [WithLowerEncoderMem](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithLowerEncoderMem) encoder option [#336](https://github.com/klauspost/compress/pull/336) + * deflate: Improve entropy compression [#338](https://github.com/klauspost/compress/pull/338) + * s2: Clean up and minor performance improvement in best [#341](https://github.com/klauspost/compress/pull/341) + +* Mar 5, 2021 (v1.11.12) + * s2: Add `s2sx` binary that creates [self extracting archives](https://github.com/klauspost/compress/tree/master/s2#s2sx-self-extracting-archives). + * s2: Speed up decompression on non-assembly platforms [#328](https://github.com/klauspost/compress/pull/328) + +* Mar 1, 2021 (v1.11.9) + * s2: Add ARM64 decompression assembly. Around 2x output speed. [#324](https://github.com/klauspost/compress/pull/324) + * s2: Improve "better" speed and efficiency. [#325](https://github.com/klauspost/compress/pull/325) + * s2: Fix binaries. + +* Feb 25, 2021 (v1.11.8) + * s2: Fixed occational out-of-bounds write on amd64. Upgrade recommended. + * s2: Add AMD64 assembly for better mode. 25-50% faster. [#315](https://github.com/klauspost/compress/pull/315) + * s2: Less upfront decoder allocation. [#322](https://github.com/klauspost/compress/pull/322) + * zstd: Faster "compression" of incompressible data. [#314](https://github.com/klauspost/compress/pull/314) + * zip: Fix zip64 headers. [#313](https://github.com/klauspost/compress/pull/313) + +* Jan 14, 2021 (v1.11.7) + * Use Bytes() interface to get bytes across packages. [#309](https://github.com/klauspost/compress/pull/309) + * s2: Add 'best' compression option. [#310](https://github.com/klauspost/compress/pull/310) + * s2: Add ReaderMaxBlockSize, changes `s2.NewReader` signature to include varargs. [#311](https://github.com/klauspost/compress/pull/311) + * s2: Fix crash on small better buffers. [#308](https://github.com/klauspost/compress/pull/308) + * s2: Clean up decoder. [#312](https://github.com/klauspost/compress/pull/312) + +* Jan 7, 2021 (v1.11.6) + * zstd: Make decoder allocations smaller [#306](https://github.com/klauspost/compress/pull/306) + * zstd: Free Decoder resources when Reset is called with a nil io.Reader [#305](https://github.com/klauspost/compress/pull/305) + +* Dec 20, 2020 (v1.11.4) + * zstd: Add Best compression mode [#304](https://github.com/klauspost/compress/pull/304) + * Add header decoder [#299](https://github.com/klauspost/compress/pull/299) + * s2: Add uncompressed stream option [#297](https://github.com/klauspost/compress/pull/297) + * Simplify/speed up small blocks with known max size. [#300](https://github.com/klauspost/compress/pull/300) + * zstd: Always reset literal dict encoder [#303](https://github.com/klauspost/compress/pull/303) + +* Nov 15, 2020 (v1.11.3) + * inflate: 10-15% faster decompression [#293](https://github.com/klauspost/compress/pull/293) + * zstd: Tweak DecodeAll default allocation [#295](https://github.com/klauspost/compress/pull/295) + +* Oct 11, 2020 (v1.11.2) + * s2: Fix out of bounds read in "better" block compression [#291](https://github.com/klauspost/compress/pull/291) + +* Oct 1, 2020 (v1.11.1) + * zstd: Set allLitEntropy true in default configuration [#286](https://github.com/klauspost/compress/pull/286) + +* Sept 8, 2020 (v1.11.0) + * zstd: Add experimental compression [dictionaries](https://github.com/klauspost/compress/tree/master/zstd#dictionaries) [#281](https://github.com/klauspost/compress/pull/281) + * zstd: Fix mixed Write and ReadFrom calls [#282](https://github.com/klauspost/compress/pull/282) + * inflate/gz: Limit variable shifts, ~5% faster decompression [#274](https://github.com/klauspost/compress/pull/274) +
      + +
      + See changes to v1.10.x + +* July 8, 2020 (v1.10.11) + * zstd: Fix extra block when compressing with ReadFrom. [#278](https://github.com/klauspost/compress/pull/278) + * huff0: Also populate compression table when reading decoding table. [#275](https://github.com/klauspost/compress/pull/275) + +* June 23, 2020 (v1.10.10) + * zstd: Skip entropy compression in fastest mode when no matches. [#270](https://github.com/klauspost/compress/pull/270) + +* June 16, 2020 (v1.10.9): + * zstd: API change for specifying dictionaries. See [#268](https://github.com/klauspost/compress/pull/268) + * zip: update CreateHeaderRaw to handle zip64 fields. [#266](https://github.com/klauspost/compress/pull/266) + * Fuzzit tests removed. The service has been purchased and is no longer available. + +* June 5, 2020 (v1.10.8): + * 1.15x faster zstd block decompression. [#265](https://github.com/klauspost/compress/pull/265) + +* June 1, 2020 (v1.10.7): + * Added zstd decompression [dictionary support](https://github.com/klauspost/compress/tree/master/zstd#dictionaries) + * Increase zstd decompression speed up to 1.19x. [#259](https://github.com/klauspost/compress/pull/259) + * Remove internal reset call in zstd compression and reduce allocations. [#263](https://github.com/klauspost/compress/pull/263) + +* May 21, 2020: (v1.10.6) + * zstd: Reduce allocations while decoding. [#258](https://github.com/klauspost/compress/pull/258), [#252](https://github.com/klauspost/compress/pull/252) + * zstd: Stricter decompression checks. + +* April 12, 2020: (v1.10.5) + * s2-commands: Flush output when receiving SIGINT. [#239](https://github.com/klauspost/compress/pull/239) + +* Apr 8, 2020: (v1.10.4) + * zstd: Minor/special case optimizations. [#251](https://github.com/klauspost/compress/pull/251), [#250](https://github.com/klauspost/compress/pull/250), [#249](https://github.com/klauspost/compress/pull/249), [#247](https://github.com/klauspost/compress/pull/247) +* Mar 11, 2020: (v1.10.3) + * s2: Use S2 encoder in pure Go mode for Snappy output as well. [#245](https://github.com/klauspost/compress/pull/245) + * s2: Fix pure Go block encoder. [#244](https://github.com/klauspost/compress/pull/244) + * zstd: Added "better compression" mode. [#240](https://github.com/klauspost/compress/pull/240) + * zstd: Improve speed of fastest compression mode by 5-10% [#241](https://github.com/klauspost/compress/pull/241) + * zstd: Skip creating encoders when not needed. [#238](https://github.com/klauspost/compress/pull/238) + +* Feb 27, 2020: (v1.10.2) + * Close to 50% speedup in inflate (gzip/zip decompression). [#236](https://github.com/klauspost/compress/pull/236) [#234](https://github.com/klauspost/compress/pull/234) [#232](https://github.com/klauspost/compress/pull/232) + * Reduce deflate level 1-6 memory usage up to 59%. [#227](https://github.com/klauspost/compress/pull/227) + +* Feb 18, 2020: (v1.10.1) + * Fix zstd crash when resetting multiple times without sending data. [#226](https://github.com/klauspost/compress/pull/226) + * deflate: Fix dictionary use on level 1-6. [#224](https://github.com/klauspost/compress/pull/224) + * Remove deflate writer reference when closing. [#224](https://github.com/klauspost/compress/pull/224) + +* Feb 4, 2020: (v1.10.0) + * Add optional dictionary to [stateless deflate](https://pkg.go.dev/github.com/klauspost/compress/flate?tab=doc#StatelessDeflate). Breaking change, send `nil` for previous behaviour. [#216](https://github.com/klauspost/compress/pull/216) + * Fix buffer overflow on repeated small block deflate. [#218](https://github.com/klauspost/compress/pull/218) + * Allow copying content from an existing ZIP file without decompressing+compressing. [#214](https://github.com/klauspost/compress/pull/214) + * Added [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) AMD64 assembler and various optimizations. Stream speed >10GB/s. [#186](https://github.com/klauspost/compress/pull/186) + +
      + +
      + See changes prior to v1.10.0 + +* Jan 20,2020 (v1.9.8) Optimize gzip/deflate with better size estimates and faster table generation. [#207](https://github.com/klauspost/compress/pull/207) by [luyu6056](https://github.com/luyu6056), [#206](https://github.com/klauspost/compress/pull/206). +* Jan 11, 2020: S2 Encode/Decode will use provided buffer if capacity is big enough. [#204](https://github.com/klauspost/compress/pull/204) +* Jan 5, 2020: (v1.9.7) Fix another zstd regression in v1.9.5 - v1.9.6 removed. +* Jan 4, 2020: (v1.9.6) Regression in v1.9.5 fixed causing corrupt zstd encodes in rare cases. +* Jan 4, 2020: Faster IO in [s2c + s2d commandline tools](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) compression/decompression. [#192](https://github.com/klauspost/compress/pull/192) +* Dec 29, 2019: Removed v1.9.5 since fuzz tests showed a compatibility problem with the reference zstandard decoder. +* Dec 29, 2019: (v1.9.5) zstd: 10-20% faster block compression. [#199](https://github.com/klauspost/compress/pull/199) +* Dec 29, 2019: [zip](https://godoc.org/github.com/klauspost/compress/zip) package updated with latest Go features +* Dec 29, 2019: zstd: Single segment flag condintions tweaked. [#197](https://github.com/klauspost/compress/pull/197) +* Dec 18, 2019: s2: Faster compression when ReadFrom is used. [#198](https://github.com/klauspost/compress/pull/198) +* Dec 10, 2019: s2: Fix repeat length output when just above at 16MB limit. +* Dec 10, 2019: zstd: Add function to get decoder as io.ReadCloser. [#191](https://github.com/klauspost/compress/pull/191) +* Dec 3, 2019: (v1.9.4) S2: limit max repeat length. [#188](https://github.com/klauspost/compress/pull/188) +* Dec 3, 2019: Add [WithNoEntropyCompression](https://godoc.org/github.com/klauspost/compress/zstd#WithNoEntropyCompression) to zstd [#187](https://github.com/klauspost/compress/pull/187) +* Dec 3, 2019: Reduce memory use for tests. Check for leaked goroutines. +* Nov 28, 2019 (v1.9.3) Less allocations in stateless deflate. +* Nov 28, 2019: 5-20% Faster huff0 decode. Impacts zstd as well. [#184](https://github.com/klauspost/compress/pull/184) +* Nov 12, 2019 (v1.9.2) Added [Stateless Compression](#stateless-compression) for gzip/deflate. +* Nov 12, 2019: Fixed zstd decompression of large single blocks. [#180](https://github.com/klauspost/compress/pull/180) +* Nov 11, 2019: Set default [s2c](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) block size to 4MB. +* Nov 11, 2019: Reduce inflate memory use by 1KB. +* Nov 10, 2019: Less allocations in deflate bit writer. +* Nov 10, 2019: Fix inconsistent error returned by zstd decoder. +* Oct 28, 2019 (v1.9.1) ztsd: Fix crash when compressing blocks. [#174](https://github.com/klauspost/compress/pull/174) +* Oct 24, 2019 (v1.9.0) zstd: Fix rare data corruption [#173](https://github.com/klauspost/compress/pull/173) +* Oct 24, 2019 zstd: Fix huff0 out of buffer write [#171](https://github.com/klauspost/compress/pull/171) and always return errors [#172](https://github.com/klauspost/compress/pull/172) +* Oct 10, 2019: Big deflate rewrite, 30-40% faster with better compression [#105](https://github.com/klauspost/compress/pull/105) + +
      + +
      + See changes prior to v1.9.0 + +* Oct 10, 2019: (v1.8.6) zstd: Allow partial reads to get flushed data. [#169](https://github.com/klauspost/compress/pull/169) +* Oct 3, 2019: Fix inconsistent results on broken zstd streams. +* Sep 25, 2019: Added `-rm` (remove source files) and `-q` (no output except errors) to `s2c` and `s2d` [commands](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) +* Sep 16, 2019: (v1.8.4) Add `s2c` and `s2d` [commandline tools](https://github.com/klauspost/compress/tree/master/s2#commandline-tools). +* Sep 10, 2019: (v1.8.3) Fix s2 decoder [Skip](https://godoc.org/github.com/klauspost/compress/s2#Reader.Skip). +* Sep 7, 2019: zstd: Added [WithWindowSize](https://godoc.org/github.com/klauspost/compress/zstd#WithWindowSize), contributed by [ianwilkes](https://github.com/ianwilkes). +* Sep 5, 2019: (v1.8.2) Add [WithZeroFrames](https://godoc.org/github.com/klauspost/compress/zstd#WithZeroFrames) which adds full zero payload block encoding option. +* Sep 5, 2019: Lazy initialization of zstandard predefined en/decoder tables. +* Aug 26, 2019: (v1.8.1) S2: 1-2% compression increase in "better" compression mode. +* Aug 26, 2019: zstd: Check maximum size of Huffman 1X compressed literals while decoding. +* Aug 24, 2019: (v1.8.0) Added [S2 compression](https://github.com/klauspost/compress/tree/master/s2#s2-compression), a high performance replacement for Snappy. +* Aug 21, 2019: (v1.7.6) Fixed minor issues found by fuzzer. One could lead to zstd not decompressing. +* Aug 18, 2019: Add [fuzzit](https://fuzzit.dev/) continuous fuzzing. +* Aug 14, 2019: zstd: Skip incompressible data 2x faster. [#147](https://github.com/klauspost/compress/pull/147) +* Aug 4, 2019 (v1.7.5): Better literal compression. [#146](https://github.com/klauspost/compress/pull/146) +* Aug 4, 2019: Faster zstd compression. [#143](https://github.com/klauspost/compress/pull/143) [#144](https://github.com/klauspost/compress/pull/144) +* Aug 4, 2019: Faster zstd decompression. [#145](https://github.com/klauspost/compress/pull/145) [#143](https://github.com/klauspost/compress/pull/143) [#142](https://github.com/klauspost/compress/pull/142) +* July 15, 2019 (v1.7.4): Fix double EOF block in rare cases on zstd encoder. +* July 15, 2019 (v1.7.3): Minor speedup/compression increase in default zstd encoder. +* July 14, 2019: zstd decoder: Fix decompression error on multiple uses with mixed content. +* July 7, 2019 (v1.7.2): Snappy update, zstd decoder potential race fix. +* June 17, 2019: zstd decompression bugfix. +* June 17, 2019: fix 32 bit builds. +* June 17, 2019: Easier use in modules (less dependencies). +* June 9, 2019: New stronger "default" [zstd](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression mode. Matches zstd default compression ratio. +* June 5, 2019: 20-40% throughput in [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and better compression. +* June 5, 2019: deflate/gzip compression: Reduce memory usage of lower compression levels. +* June 2, 2019: Added [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression! +* May 25, 2019: deflate/gzip: 10% faster bit writer, mostly visible in lower levels. +* Apr 22, 2019: [zstd](https://github.com/klauspost/compress/tree/master/zstd#zstd) decompression added. +* Aug 1, 2018: Added [huff0 README](https://github.com/klauspost/compress/tree/master/huff0#huff0-entropy-compression). +* Jul 8, 2018: Added [Performance Update 2018](#performance-update-2018) below. +* Jun 23, 2018: Merged [Go 1.11 inflate optimizations](https://go-review.googlesource.com/c/go/+/102235). Go 1.9 is now required. Backwards compatible version tagged with [v1.3.0](https://github.com/klauspost/compress/releases/tag/v1.3.0). +* Apr 2, 2018: Added [huff0](https://godoc.org/github.com/klauspost/compress/huff0) en/decoder. Experimental for now, API may change. +* Mar 4, 2018: Added [FSE Entropy](https://godoc.org/github.com/klauspost/compress/fse) en/decoder. Experimental for now, API may change. +* Nov 3, 2017: Add compression [Estimate](https://godoc.org/github.com/klauspost/compress#Estimate) function. +* May 28, 2017: Reduce allocations when resetting decoder. +* Apr 02, 2017: Change back to official crc32, since changes were merged in Go 1.7. +* Jan 14, 2017: Reduce stack pressure due to array copies. See [Issue #18625](https://github.com/golang/go/issues/18625). +* Oct 25, 2016: Level 2-4 have been rewritten and now offers significantly better performance than before. +* Oct 20, 2016: Port zlib changes from Go 1.7 to fix zlib writer issue. Please update. +* Oct 16, 2016: Go 1.7 changes merged. Apples to apples this package is a few percent faster, but has a significantly better balance between speed and compression per level. +* Mar 24, 2016: Always attempt Huffman encoding on level 4-7. This improves base 64 encoded data compression. +* Mar 24, 2016: Small speedup for level 1-3. +* Feb 19, 2016: Faster bit writer, level -2 is 15% faster, level 1 is 4% faster. +* Feb 19, 2016: Handle small payloads faster in level 1-3. +* Feb 19, 2016: Added faster level 2 + 3 compression modes. +* Feb 19, 2016: [Rebalanced compression levels](https://blog.klauspost.com/rebalancing-deflate-compression-levels/), so there is a more even progresssion in terms of compression. New default level is 5. +* Feb 14, 2016: Snappy: Merge upstream changes. +* Feb 14, 2016: Snappy: Fix aggressive skipping. +* Feb 14, 2016: Snappy: Update benchmark. +* Feb 13, 2016: Deflate: Fixed assembler problem that could lead to sub-optimal compression. +* Feb 12, 2016: Snappy: Added AMD64 SSE 4.2 optimizations to matching, which makes easy to compress material run faster. Typical speedup is around 25%. +* Feb 9, 2016: Added Snappy package fork. This version is 5-7% faster, much more on hard to compress content. +* Jan 30, 2016: Optimize level 1 to 3 by not considering static dictionary or storing uncompressed. ~4-5% speedup. +* Jan 16, 2016: Optimization on deflate level 1,2,3 compression. +* Jan 8 2016: Merge [CL 18317](https://go-review.googlesource.com/#/c/18317): fix reading, writing of zip64 archives. +* Dec 8 2015: Make level 1 and -2 deterministic even if write size differs. +* Dec 8 2015: Split encoding functions, so hashing and matching can potentially be inlined. 1-3% faster on AMD64. 5% faster on other platforms. +* Dec 8 2015: Fixed rare [one byte out-of bounds read](https://github.com/klauspost/compress/issues/20). Please update! +* Nov 23 2015: Optimization on token writer. ~2-4% faster. Contributed by [@dsnet](https://github.com/dsnet). +* Nov 20 2015: Small optimization to bit writer on 64 bit systems. +* Nov 17 2015: Fixed out-of-bound errors if the underlying Writer returned an error. See [#15](https://github.com/klauspost/compress/issues/15). +* Nov 12 2015: Added [io.WriterTo](https://golang.org/pkg/io/#WriterTo) support to gzip/inflate. +* Nov 11 2015: Merged [CL 16669](https://go-review.googlesource.com/#/c/16669/4): archive/zip: enable overriding (de)compressors per file +* Oct 15 2015: Added skipping on uncompressible data. Random data speed up >5x. + +
      + +# deflate usage + +The packages are drop-in replacements for standard libraries. Simply replace the import path to use them: + +| old import | new import | Documentation +|--------------------|-----------------------------------------|--------------------| +| `compress/gzip` | `github.com/klauspost/compress/gzip` | [gzip](https://pkg.go.dev/github.com/klauspost/compress/gzip?tab=doc) +| `compress/zlib` | `github.com/klauspost/compress/zlib` | [zlib](https://pkg.go.dev/github.com/klauspost/compress/zlib?tab=doc) +| `archive/zip` | `github.com/klauspost/compress/zip` | [zip](https://pkg.go.dev/github.com/klauspost/compress/zip?tab=doc) +| `compress/flate` | `github.com/klauspost/compress/flate` | [flate](https://pkg.go.dev/github.com/klauspost/compress/flate?tab=doc) + +* Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). + +You may also be interested in [pgzip](https://github.com/klauspost/pgzip), which is a drop in replacement for gzip, which support multithreaded compression on big files and the optimized [crc32](https://github.com/klauspost/crc32) package used by these packages. + +The packages contains the same as the standard library, so you can use the godoc for that: [gzip](http://golang.org/pkg/compress/gzip/), [zip](http://golang.org/pkg/archive/zip/), [zlib](http://golang.org/pkg/compress/zlib/), [flate](http://golang.org/pkg/compress/flate/). + +Currently there is only minor speedup on decompression (mostly CRC32 calculation). + +Memory usage is typically 1MB for a Writer. stdlib is in the same range. +If you expect to have a lot of concurrently allocated Writers consider using +the stateless compress described below. + +For compression performance, see: [this spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing). + +# Stateless compression + +This package offers stateless compression as a special option for gzip/deflate. +It will do compression but without maintaining any state between Write calls. + +This means there will be no memory kept between Write calls, but compression and speed will be suboptimal. + +This is only relevant in cases where you expect to run many thousands of compressors concurrently, +but with very little activity. This is *not* intended for regular web servers serving individual requests. + +Because of this, the size of actual Write calls will affect output size. + +In gzip, specify level `-3` / `gzip.StatelessCompression` to enable. + +For direct deflate use, NewStatelessWriter and StatelessDeflate are available. See [documentation](https://godoc.org/github.com/klauspost/compress/flate#NewStatelessWriter) + +A `bufio.Writer` can of course be used to control write sizes. For example, to use a 4KB buffer: + +``` + // replace 'ioutil.Discard' with your output. + gzw, err := gzip.NewWriterLevel(ioutil.Discard, gzip.StatelessCompression) + if err != nil { + return err + } + defer gzw.Close() + + w := bufio.NewWriterSize(gzw, 4096) + defer w.Flush() + + // Write to 'w' +``` + +This will only use up to 4KB in memory when the writer is idle. + +Compression is almost always worse than the fastest compression level +and each write will allocate (a little) memory. + +# Performance Update 2018 + +It has been a while since we have been looking at the speed of this package compared to the standard library, so I thought I would re-do my tests and give some overall recommendations based on the current state. All benchmarks have been performed with Go 1.10 on my Desktop Intel(R) Core(TM) i7-2600 CPU @3.40GHz. Since I last ran the tests, I have gotten more RAM, which means tests with big files are no longer limited by my SSD. + +The raw results are in my [updated spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing). Due to cgo changes and upstream updates i could not get the cgo version of gzip to compile. Instead I included the [zstd](https://github.com/datadog/zstd) cgo implementation. If I get cgo gzip to work again, I might replace the results in the sheet. + +The columns to take note of are: *MB/s* - the throughput. *Reduction* - the data size reduction in percent of the original. *Rel Speed* relative speed compared to the standard library at the same level. *Smaller* - how many percent smaller is the compressed output compared to stdlib. Negative means the output was bigger. *Loss* means the loss (or gain) in compression as a percentage difference of the input. + +The `gzstd` (standard library gzip) and `gzkp` (this package gzip) only uses one CPU core. [`pgzip`](https://github.com/klauspost/pgzip), [`bgzf`](https://github.com/biogo/hts/tree/master/bgzf) uses all 4 cores. [`zstd`](https://github.com/DataDog/zstd) uses one core, and is a beast (but not Go, yet). + + +## Overall differences. + +There appears to be a roughly 5-10% speed advantage over the standard library when comparing at similar compression levels. + +The biggest difference you will see is the result of [re-balancing](https://blog.klauspost.com/rebalancing-deflate-compression-levels/) the compression levels. I wanted by library to give a smoother transition between the compression levels than the standard library. + +This package attempts to provide a more smooth transition, where "1" is taking a lot of shortcuts, "5" is the reasonable trade-off and "9" is the "give me the best compression", and the values in between gives something reasonable in between. The standard library has big differences in levels 1-4, but levels 5-9 having no significant gains - often spending a lot more time than can be justified by the achieved compression. + +There are links to all the test data in the [spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing) in the top left field on each tab. + +## Web Content + +This test set aims to emulate typical use in a web server. The test-set is 4GB data in 53k files, and is a mixture of (mostly) HTML, JS, CSS. + +Since level 1 and 9 are close to being the same code, they are quite close. But looking at the levels in-between the differences are quite big. + +Looking at level 6, this package is 88% faster, but will output about 6% more data. For a web server, this means you can serve 88% more data, but have to pay for 6% more bandwidth. You can draw your own conclusions on what would be the most expensive for your case. + +## Object files + +This test is for typical data files stored on a server. In this case it is a collection of Go precompiled objects. They are very compressible. + +The picture is similar to the web content, but with small differences since this is very compressible. Levels 2-3 offer good speed, but is sacrificing quite a bit of compression. + +The standard library seems suboptimal on level 3 and 4 - offering both worse compression and speed than level 6 & 7 of this package respectively. + +## Highly Compressible File + +This is a JSON file with very high redundancy. The reduction starts at 95% on level 1, so in real life terms we are dealing with something like a highly redundant stream of data, etc. + +It is definitely visible that we are dealing with specialized content here, so the results are very scattered. This package does not do very well at levels 1-4, but picks up significantly at level 5 and levels 7 and 8 offering great speed for the achieved compression. + +So if you know you content is extremely compressible you might want to go slightly higher than the defaults. The standard library has a huge gap between levels 3 and 4 in terms of speed (2.75x slowdown), so it offers little "middle ground". + +## Medium-High Compressible + +This is a pretty common test corpus: [enwik9](http://mattmahoney.net/dc/textdata.html). It contains the first 10^9 bytes of the English Wikipedia dump on Mar. 3, 2006. This is a very good test of typical text based compression and more data heavy streams. + +We see a similar picture here as in "Web Content". On equal levels some compression is sacrificed for more speed. Level 5 seems to be the best trade-off between speed and size, beating stdlib level 3 in both. + +## Medium Compressible + +I will combine two test sets, one [10GB file set](http://mattmahoney.net/dc/10gb.html) and a VM disk image (~8GB). Both contain different data types and represent a typical backup scenario. + +The most notable thing is how quickly the standard library drops to very low compression speeds around level 5-6 without any big gains in compression. Since this type of data is fairly common, this does not seem like good behavior. + + +## Un-compressible Content + +This is mainly a test of how good the algorithms are at detecting un-compressible input. The standard library only offers this feature with very conservative settings at level 1. Obviously there is no reason for the algorithms to try to compress input that cannot be compressed. The only downside is that it might skip some compressible data on false detections. + + +## Huffman only compression + +This compression library adds a special compression level, named `HuffmanOnly`, which allows near linear time compression. This is done by completely disabling matching of previous data, and only reduce the number of bits to represent each character. + +This means that often used characters, like 'e' and ' ' (space) in text use the fewest bits to represent, and rare characters like '¤' takes more bits to represent. For more information see [wikipedia](https://en.wikipedia.org/wiki/Huffman_coding) or this nice [video](https://youtu.be/ZdooBTdW5bM). + +Since this type of compression has much less variance, the compression speed is mostly unaffected by the input data, and is usually more than *180MB/s* for a single core. + +The downside is that the compression ratio is usually considerably worse than even the fastest conventional compression. The compression ratio can never be better than 8:1 (12.5%). + +The linear time compression can be used as a "better than nothing" mode, where you cannot risk the encoder to slow down on some content. For comparison, the size of the "Twain" text is *233460 bytes* (+29% vs. level 1) and encode speed is 144MB/s (4.5x level 1). So in this case you trade a 30% size increase for a 4 times speedup. + +For more information see my blog post on [Fast Linear Time Compression](http://blog.klauspost.com/constant-time-gzipzip-compression/). + +This is implemented on Go 1.7 as "Huffman Only" mode, though not exposed for gzip. + +# Other packages + +Here are other packages of good quality and pure Go (no cgo wrappers or autoconverted code): + +* [github.com/pierrec/lz4](https://github.com/pierrec/lz4) - strong multithreaded LZ4 compression. +* [github.com/cosnicolaou/pbzip2](https://github.com/cosnicolaou/pbzip2) - multithreaded bzip2 decompression. +* [github.com/dsnet/compress](https://github.com/dsnet/compress) - brotli decompression, bzip2 writer. +* [github.com/ronanh/intcomp](https://github.com/ronanh/intcomp) - Integer compression. +* [github.com/spenczar/fpc](https://github.com/spenczar/fpc) - Float compression. +* [github.com/minio/zipindex](https://github.com/minio/zipindex) - External ZIP directory index. +* [github.com/ybirader/pzip](https://github.com/ybirader/pzip) - Fast concurrent zip archiver and extractor. + +# license + +This code is licensed under the same conditions as the original Go code. See LICENSE file. diff --git a/vendor/github.com/klauspost/compress/SECURITY.md b/vendor/github.com/klauspost/compress/SECURITY.md new file mode 100644 index 000000000..ca6685e2b --- /dev/null +++ b/vendor/github.com/klauspost/compress/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Vulnerability Definition + +A security vulnerability is a bug that with certain input triggers a crash or an infinite loop. Most calls will have varying execution time and only in rare cases will slow operation be considered a security vulnerability. + +Corrupted output generally is not considered a security vulnerability, unless independent operations are able to affect each other. Note that not all functionality is re-entrant and safe to use concurrently. + +Out-of-memory crashes only applies if the en/decoder uses an abnormal amount of memory, with appropriate options applied, to limit maximum window size, concurrency, etc. However, if you are in doubt you are welcome to file a security issue. + +It is assumed that all callers are trusted, meaning internal data exposed through reflection or inspection of returned data structures is not considered a vulnerability. + +Vulnerabilities resulting from compiler/assembler errors should be reported upstream. Depending on the severity this package may or may not implement a workaround. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please disclose it at [security advisory](https://github.com/klauspost/compress/security/advisories/new). If possible please provide a minimal reproducer. If the issue only applies to a single platform, it would be helpful to provide access to that. + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, vulnerabilities will be disclosed in a best effort base. diff --git a/vendor/github.com/klauspost/compress/compressible.go b/vendor/github.com/klauspost/compress/compressible.go new file mode 100644 index 000000000..ea5a692d5 --- /dev/null +++ b/vendor/github.com/klauspost/compress/compressible.go @@ -0,0 +1,85 @@ +package compress + +import "math" + +// Estimate returns a normalized compressibility estimate of block b. +// Values close to zero are likely uncompressible. +// Values above 0.1 are likely to be compressible. +// Values above 0.5 are very compressible. +// Very small lengths will return 0. +func Estimate(b []byte) float64 { + if len(b) < 16 { + return 0 + } + + // Correctly predicted order 1 + hits := 0 + lastMatch := false + var o1 [256]byte + var hist [256]int + c1 := byte(0) + for _, c := range b { + if c == o1[c1] { + // We only count a hit if there was two correct predictions in a row. + if lastMatch { + hits++ + } + lastMatch = true + } else { + lastMatch = false + } + o1[c1] = c + c1 = c + hist[c]++ + } + + // Use x^0.6 to give better spread + prediction := math.Pow(float64(hits)/float64(len(b)), 0.6) + + // Calculate histogram distribution + variance := float64(0) + avg := float64(len(b)) / 256 + + for _, v := range hist { + Δ := float64(v) - avg + variance += Δ * Δ + } + + stddev := math.Sqrt(float64(variance)) / float64(len(b)) + exp := math.Sqrt(1 / float64(len(b))) + + // Subtract expected stddev + stddev -= exp + if stddev < 0 { + stddev = 0 + } + stddev *= 1 + exp + + // Use x^0.4 to give better spread + entropy := math.Pow(stddev, 0.4) + + // 50/50 weight between prediction and histogram distribution + return math.Pow((prediction+entropy)/2, 0.9) +} + +// ShannonEntropyBits returns the number of bits minimum required to represent +// an entropy encoding of the input bytes. +// https://en.wiktionary.org/wiki/Shannon_entropy +func ShannonEntropyBits(b []byte) int { + if len(b) == 0 { + return 0 + } + var hist [256]int + for _, c := range b { + hist[c]++ + } + shannon := float64(0) + invTotal := 1.0 / float64(len(b)) + for _, v := range hist[:] { + if v > 0 { + n := float64(v) + shannon += math.Ceil(-math.Log2(n*invTotal) * n) + } + } + return int(math.Ceil(shannon)) +} diff --git a/vendor/github.com/klauspost/compress/fse/README.md b/vendor/github.com/klauspost/compress/fse/README.md new file mode 100644 index 000000000..ea7324da6 --- /dev/null +++ b/vendor/github.com/klauspost/compress/fse/README.md @@ -0,0 +1,79 @@ +# Finite State Entropy + +This package provides Finite State Entropy encoding and decoding. + +Finite State Entropy (also referenced as [tANS](https://en.wikipedia.org/wiki/Asymmetric_numeral_systems#tANS)) +encoding provides a fast near-optimal symbol encoding/decoding +for byte blocks as implemented in [zstandard](https://github.com/facebook/zstd). + +This can be used for compressing input with a lot of similar input values to the smallest number of bytes. +This does not perform any multi-byte [dictionary coding](https://en.wikipedia.org/wiki/Dictionary_coder) as LZ coders, +but it can be used as a secondary step to compressors (like Snappy) that does not do entropy encoding. + +* [Godoc documentation](https://godoc.org/github.com/klauspost/compress/fse) + +## News + + * Feb 2018: First implementation released. Consider this beta software for now. + +# Usage + +This package provides a low level interface that allows to compress single independent blocks. + +Each block is separate, and there is no built in integrity checks. +This means that the caller should keep track of block sizes and also do checksums if needed. + +Compressing a block is done via the [`Compress`](https://godoc.org/github.com/klauspost/compress/fse#Compress) function. +You must provide input and will receive the output and maybe an error. + +These error values can be returned: + +| Error | Description | +|---------------------|-----------------------------------------------------------------------------| +| `` | Everything ok, output is returned | +| `ErrIncompressible` | Returned when input is judged to be too hard to compress | +| `ErrUseRLE` | Returned from the compressor when the input is a single byte value repeated | +| `(error)` | An internal error occurred. | + +As can be seen above there are errors that will be returned even under normal operation so it is important to handle these. + +To reduce allocations you can provide a [`Scratch`](https://godoc.org/github.com/klauspost/compress/fse#Scratch) object +that can be re-used for successive calls. Both compression and decompression accepts a `Scratch` object, and the same +object can be used for both. + +Be aware, that when re-using a `Scratch` object that the *output* buffer is also re-used, so if you are still using this +you must set the `Out` field in the scratch to nil. The same buffer is used for compression and decompression output. + +Decompressing is done by calling the [`Decompress`](https://godoc.org/github.com/klauspost/compress/fse#Decompress) function. +You must provide the output from the compression stage, at exactly the size you got back. If you receive an error back +your input was likely corrupted. + +It is important to note that a successful decoding does *not* mean your output matches your original input. +There are no integrity checks, so relying on errors from the decompressor does not assure your data is valid. + +For more detailed usage, see examples in the [godoc documentation](https://godoc.org/github.com/klauspost/compress/fse#pkg-examples). + +# Performance + +A lot of factors are affecting speed. Block sizes and compressibility of the material are primary factors. +All compression functions are currently only running on the calling goroutine so only one core will be used per block. + +The compressor is significantly faster if symbols are kept as small as possible. The highest byte value of the input +is used to reduce some of the processing, so if all your input is above byte value 64 for instance, it may be +beneficial to transpose all your input values down by 64. + +With moderate block sizes around 64k speed are typically 200MB/s per core for compression and +around 300MB/s decompression speed. + +The same hardware typically does Huffman (deflate) encoding at 125MB/s and decompression at 100MB/s. + +# Plans + +At one point, more internals will be exposed to facilitate more "expert" usage of the components. + +A streaming interface is also likely to be implemented. Likely compatible with [FSE stream format](https://github.com/Cyan4973/FiniteStateEntropy/blob/dev/programs/fileio.c#L261). + +# Contributing + +Contributions are always welcome. Be aware that adding public functions will require good justification and breaking +changes will likely not be accepted. If in doubt open an issue before writing the PR. \ No newline at end of file diff --git a/vendor/github.com/klauspost/compress/fse/bitreader.go b/vendor/github.com/klauspost/compress/fse/bitreader.go new file mode 100644 index 000000000..f65eb3909 --- /dev/null +++ b/vendor/github.com/klauspost/compress/fse/bitreader.go @@ -0,0 +1,122 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package fse + +import ( + "encoding/binary" + "errors" + "io" +) + +// bitReader reads a bitstream in reverse. +// The last set bit indicates the start of the stream and is used +// for aligning the input. +type bitReader struct { + in []byte + off uint // next byte to read is at in[off - 1] + value uint64 + bitsRead uint8 +} + +// init initializes and resets the bit reader. +func (b *bitReader) init(in []byte) error { + if len(in) < 1 { + return errors.New("corrupt stream: too short") + } + b.in = in + b.off = uint(len(in)) + // The highest bit of the last byte indicates where to start + v := in[len(in)-1] + if v == 0 { + return errors.New("corrupt stream, did not find end of stream") + } + b.bitsRead = 64 + b.value = 0 + if len(in) >= 8 { + b.fillFastStart() + } else { + b.fill() + b.fill() + } + b.bitsRead += 8 - uint8(highBits(uint32(v))) + return nil +} + +// getBits will return n bits. n can be 0. +func (b *bitReader) getBits(n uint8) uint16 { + if n == 0 || b.bitsRead >= 64 { + return 0 + } + return b.getBitsFast(n) +} + +// getBitsFast requires that at least one bit is requested every time. +// There are no checks if the buffer is filled. +func (b *bitReader) getBitsFast(n uint8) uint16 { + const regMask = 64 - 1 + v := uint16((b.value << (b.bitsRead & regMask)) >> ((regMask + 1 - n) & regMask)) + b.bitsRead += n + return v +} + +// fillFast() will make sure at least 32 bits are available. +// There must be at least 4 bytes available. +func (b *bitReader) fillFast() { + if b.bitsRead < 32 { + return + } + // 2 bounds checks. + v := b.in[b.off-4:] + v = v[:4] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value = (b.value << 32) | uint64(low) + b.bitsRead -= 32 + b.off -= 4 +} + +// fill() will make sure at least 32 bits are available. +func (b *bitReader) fill() { + if b.bitsRead < 32 { + return + } + if b.off > 4 { + v := b.in[b.off-4:] + v = v[:4] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value = (b.value << 32) | uint64(low) + b.bitsRead -= 32 + b.off -= 4 + return + } + for b.off > 0 { + b.value = (b.value << 8) | uint64(b.in[b.off-1]) + b.bitsRead -= 8 + b.off-- + } +} + +// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. +func (b *bitReader) fillFastStart() { + // Do single re-slice to avoid bounds checks. + b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) + b.bitsRead = 0 + b.off -= 8 +} + +// finished returns true if all bits have been read from the bit stream. +func (b *bitReader) finished() bool { + return b.bitsRead >= 64 && b.off == 0 +} + +// close the bitstream and returns an error if out-of-buffer reads occurred. +func (b *bitReader) close() error { + // Release reference. + b.in = nil + if b.bitsRead > 64 { + return io.ErrUnexpectedEOF + } + return nil +} diff --git a/vendor/github.com/klauspost/compress/fse/bitwriter.go b/vendor/github.com/klauspost/compress/fse/bitwriter.go new file mode 100644 index 000000000..e82fa3bb7 --- /dev/null +++ b/vendor/github.com/klauspost/compress/fse/bitwriter.go @@ -0,0 +1,167 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package fse + +import "fmt" + +// bitWriter will write bits. +// First bit will be LSB of the first byte of output. +type bitWriter struct { + bitContainer uint64 + nBits uint8 + out []byte +} + +// bitMask16 is bitmasks. Has extra to avoid bounds check. +var bitMask16 = [32]uint16{ + 0, 1, 3, 7, 0xF, 0x1F, + 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, + 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF} /* up to 16 bits */ + +// addBits16NC will add up to 16 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16NC(value uint16, bits uint8) { + b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) + b.nBits += bits +} + +// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// addBits16ZeroNC will add up to 16 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +// This is fastest if bits can be zero. +func (b *bitWriter) addBits16ZeroNC(value uint16, bits uint8) { + if bits == 0 { + return + } + value <<= (16 - bits) & 15 + value >>= (16 - bits) & 15 + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// flush will flush all pending full bytes. +// There will be at least 56 bits available for writing when this has been called. +// Using flush32 is faster, but leaves less space for writing. +func (b *bitWriter) flush() { + v := b.nBits >> 3 + switch v { + case 0: + case 1: + b.out = append(b.out, + byte(b.bitContainer), + ) + case 2: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + ) + case 3: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + ) + case 4: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + ) + case 5: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + ) + case 6: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + byte(b.bitContainer>>40), + ) + case 7: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + byte(b.bitContainer>>40), + byte(b.bitContainer>>48), + ) + case 8: + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24), + byte(b.bitContainer>>32), + byte(b.bitContainer>>40), + byte(b.bitContainer>>48), + byte(b.bitContainer>>56), + ) + default: + panic(fmt.Errorf("bits (%d) > 64", b.nBits)) + } + b.bitContainer >>= v << 3 + b.nBits &= 7 +} + +// flush32 will flush out, so there are at least 32 bits available for writing. +func (b *bitWriter) flush32() { + if b.nBits < 32 { + return + } + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24)) + b.nBits -= 32 + b.bitContainer >>= 32 +} + +// flushAlign will flush remaining full bytes and align to next byte boundary. +func (b *bitWriter) flushAlign() { + nbBytes := (b.nBits + 7) >> 3 + for i := uint8(0); i < nbBytes; i++ { + b.out = append(b.out, byte(b.bitContainer>>(i*8))) + } + b.nBits = 0 + b.bitContainer = 0 +} + +// close will write the alignment bit and write the final byte(s) +// to the output. +func (b *bitWriter) close() { + // End mark + b.addBits16Clean(1, 1) + // flush until next byte. + b.flushAlign() +} + +// reset and continue writing by appending to out. +func (b *bitWriter) reset(out []byte) { + b.bitContainer = 0 + b.nBits = 0 + b.out = out +} diff --git a/vendor/github.com/klauspost/compress/fse/bytereader.go b/vendor/github.com/klauspost/compress/fse/bytereader.go new file mode 100644 index 000000000..abade2d60 --- /dev/null +++ b/vendor/github.com/klauspost/compress/fse/bytereader.go @@ -0,0 +1,47 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package fse + +// byteReader provides a byte reader that reads +// little endian values from a byte stream. +// The input stream is manually advanced. +// The reader performs no bounds checks. +type byteReader struct { + b []byte + off int +} + +// init will initialize the reader and set the input. +func (b *byteReader) init(in []byte) { + b.b = in + b.off = 0 +} + +// advance the stream b n bytes. +func (b *byteReader) advance(n uint) { + b.off += int(n) +} + +// Uint32 returns a little endian uint32 starting at current offset. +func (b byteReader) Uint32() uint32 { + b2 := b.b[b.off:] + b2 = b2[:4] + v3 := uint32(b2[3]) + v2 := uint32(b2[2]) + v1 := uint32(b2[1]) + v0 := uint32(b2[0]) + return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) +} + +// unread returns the unread portion of the input. +func (b byteReader) unread() []byte { + return b.b[b.off:] +} + +// remain will return the number of bytes remaining. +func (b byteReader) remain() int { + return len(b.b) - b.off +} diff --git a/vendor/github.com/klauspost/compress/fse/compress.go b/vendor/github.com/klauspost/compress/fse/compress.go new file mode 100644 index 000000000..074018d8f --- /dev/null +++ b/vendor/github.com/klauspost/compress/fse/compress.go @@ -0,0 +1,683 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package fse + +import ( + "errors" + "fmt" +) + +// Compress the input bytes. Input must be < 2GB. +// Provide a Scratch buffer to avoid memory allocations. +// Note that the output is also kept in the scratch buffer. +// If input is too hard to compress, ErrIncompressible is returned. +// If input is a single byte value repeated ErrUseRLE is returned. +func Compress(in []byte, s *Scratch) ([]byte, error) { + if len(in) <= 1 { + return nil, ErrIncompressible + } + if len(in) > (2<<30)-1 { + return nil, errors.New("input too big, must be < 2GB") + } + s, err := s.prepare(in) + if err != nil { + return nil, err + } + + // Create histogram, if none was provided. + maxCount := s.maxCount + if maxCount == 0 { + maxCount = s.countSimple(in) + } + // Reset for next run. + s.clearCount = true + s.maxCount = 0 + if maxCount == len(in) { + // One symbol, use RLE + return nil, ErrUseRLE + } + if maxCount == 1 || maxCount < (len(in)>>7) { + // Each symbol present maximum once or too well distributed. + return nil, ErrIncompressible + } + s.optimalTableLog() + err = s.normalizeCount() + if err != nil { + return nil, err + } + err = s.writeCount() + if err != nil { + return nil, err + } + + if false { + err = s.validateNorm() + if err != nil { + return nil, err + } + } + + err = s.buildCTable() + if err != nil { + return nil, err + } + err = s.compress(in) + if err != nil { + return nil, err + } + s.Out = s.bw.out + // Check if we compressed. + if len(s.Out) >= len(in) { + return nil, ErrIncompressible + } + return s.Out, nil +} + +// cState contains the compression state of a stream. +type cState struct { + bw *bitWriter + stateTable []uint16 + state uint16 +} + +// init will initialize the compression state to the first symbol of the stream. +func (c *cState) init(bw *bitWriter, ct *cTable, tableLog uint8, first symbolTransform) { + c.bw = bw + c.stateTable = ct.stateTable + + nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 + im := int32((nbBitsOut << 16) - first.deltaNbBits) + lu := (im >> nbBitsOut) + first.deltaFindState + c.state = c.stateTable[lu] +} + +// encode the output symbol provided and write it to the bitstream. +func (c *cState) encode(symbolTT symbolTransform) { + nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 + dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState + c.bw.addBits16NC(c.state, uint8(nbBitsOut)) + c.state = c.stateTable[dstState] +} + +// encode the output symbol provided and write it to the bitstream. +func (c *cState) encodeZero(symbolTT symbolTransform) { + nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 + dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState + c.bw.addBits16ZeroNC(c.state, uint8(nbBitsOut)) + c.state = c.stateTable[dstState] +} + +// flush will write the tablelog to the output and flush the remaining full bytes. +func (c *cState) flush(tableLog uint8) { + c.bw.flush32() + c.bw.addBits16NC(c.state, tableLog) + c.bw.flush() +} + +// compress is the main compression loop that will encode the input from the last byte to the first. +func (s *Scratch) compress(src []byte) error { + if len(src) <= 2 { + return errors.New("compress: src too small") + } + tt := s.ct.symbolTT[:256] + s.bw.reset(s.Out) + + // Our two states each encodes every second byte. + // Last byte encoded (first byte decoded) will always be encoded by c1. + var c1, c2 cState + + // Encode so remaining size is divisible by 4. + ip := len(src) + if ip&1 == 1 { + c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) + c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) + c1.encodeZero(tt[src[ip-3]]) + ip -= 3 + } else { + c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) + c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) + ip -= 2 + } + if ip&2 != 0 { + c2.encodeZero(tt[src[ip-1]]) + c1.encodeZero(tt[src[ip-2]]) + ip -= 2 + } + src = src[:ip] + + // Main compression loop. + switch { + case !s.zeroBits && s.actualTableLog <= 8: + // We can encode 4 symbols without requiring a flush. + // We do not need to check if any output is 0 bits. + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encode(tt[v0]) + c1.encode(tt[v1]) + c2.encode(tt[v2]) + c1.encode(tt[v3]) + } + case !s.zeroBits: + // We do not need to check if any output is 0 bits. + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encode(tt[v0]) + c1.encode(tt[v1]) + s.bw.flush32() + c2.encode(tt[v2]) + c1.encode(tt[v3]) + } + case s.actualTableLog <= 8: + // We can encode 4 symbols without requiring a flush + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encodeZero(tt[v0]) + c1.encodeZero(tt[v1]) + c2.encodeZero(tt[v2]) + c1.encodeZero(tt[v3]) + } + default: + for ; len(src) >= 4; src = src[:len(src)-4] { + s.bw.flush32() + v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] + c2.encodeZero(tt[v0]) + c1.encodeZero(tt[v1]) + s.bw.flush32() + c2.encodeZero(tt[v2]) + c1.encodeZero(tt[v3]) + } + } + + // Flush final state. + // Used to initialize state when decoding. + c2.flush(s.actualTableLog) + c1.flush(s.actualTableLog) + + s.bw.close() + return nil +} + +// writeCount will write the normalized histogram count to header. +// This is read back by readNCount. +func (s *Scratch) writeCount() error { + var ( + tableLog = s.actualTableLog + tableSize = 1 << tableLog + previous0 bool + charnum uint16 + + maxHeaderSize = ((int(s.symbolLen)*int(tableLog) + 4 + 2) >> 3) + 3 + + // Write Table Size + bitStream = uint32(tableLog - minTablelog) + bitCount = uint(4) + remaining = int16(tableSize + 1) /* +1 for extra accuracy */ + threshold = int16(tableSize) + nbBits = uint(tableLog + 1) + ) + if cap(s.Out) < maxHeaderSize { + s.Out = make([]byte, 0, s.br.remain()+maxHeaderSize) + } + outP := uint(0) + out := s.Out[:maxHeaderSize] + + // stops at 1 + for remaining > 1 { + if previous0 { + start := charnum + for s.norm[charnum] == 0 { + charnum++ + } + for charnum >= start+24 { + start += 24 + bitStream += uint32(0xFFFF) << bitCount + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + } + for charnum >= start+3 { + start += 3 + bitStream += 3 << bitCount + bitCount += 2 + } + bitStream += uint32(charnum-start) << bitCount + bitCount += 2 + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + count := s.norm[charnum] + charnum++ + max := (2*threshold - 1) - remaining + if count < 0 { + remaining += count + } else { + remaining -= count + } + count++ // +1 for extra accuracy + if count >= threshold { + count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ + } + bitStream += uint32(count) << bitCount + bitCount += nbBits + if count < max { + bitCount-- + } + + previous0 = count == 1 + if remaining < 1 { + return errors.New("internal error: remaining<1") + } + for remaining < threshold { + nbBits-- + threshold >>= 1 + } + + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += (bitCount + 7) / 8 + + if charnum > s.symbolLen { + return errors.New("internal error: charnum > s.symbolLen") + } + s.Out = out[:outP] + return nil +} + +// symbolTransform contains the state transform for a symbol. +type symbolTransform struct { + deltaFindState int32 + deltaNbBits uint32 +} + +// String prints values as a human readable string. +func (s symbolTransform) String() string { + return fmt.Sprintf("dnbits: %08x, fs:%d", s.deltaNbBits, s.deltaFindState) +} + +// cTable contains tables used for compression. +type cTable struct { + tableSymbol []byte + stateTable []uint16 + symbolTT []symbolTransform +} + +// allocCtable will allocate tables needed for compression. +// If existing tables a re big enough, they are simply re-used. +func (s *Scratch) allocCtable() { + tableSize := 1 << s.actualTableLog + // get tableSymbol that is big enough. + if cap(s.ct.tableSymbol) < tableSize { + s.ct.tableSymbol = make([]byte, tableSize) + } + s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] + + ctSize := tableSize + if cap(s.ct.stateTable) < ctSize { + s.ct.stateTable = make([]uint16, ctSize) + } + s.ct.stateTable = s.ct.stateTable[:ctSize] + + if cap(s.ct.symbolTT) < 256 { + s.ct.symbolTT = make([]symbolTransform, 256) + } + s.ct.symbolTT = s.ct.symbolTT[:256] +} + +// buildCTable will populate the compression table so it is ready to be used. +func (s *Scratch) buildCTable() error { + tableSize := uint32(1 << s.actualTableLog) + highThreshold := tableSize - 1 + var cumul [maxSymbolValue + 2]int16 + + s.allocCtable() + tableSymbol := s.ct.tableSymbol[:tableSize] + // symbol start positions + { + cumul[0] = 0 + for ui, v := range s.norm[:s.symbolLen-1] { + u := byte(ui) // one less than reference + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = u + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + } + // Encode last symbol separately to avoid overflowing u + u := int(s.symbolLen - 1) + v := s.norm[s.symbolLen-1] + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = byte(u) + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + if uint32(cumul[s.symbolLen]) != tableSize { + return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) + } + cumul[s.symbolLen] = int16(tableSize) + 1 + } + // Spread symbols + s.zeroBits = false + { + step := tableStep(tableSize) + tableMask := tableSize - 1 + var position uint32 + // if any symbol > largeLimit, we may have 0 bits output. + largeLimit := int16(1 << (s.actualTableLog - 1)) + for ui, v := range s.norm[:s.symbolLen] { + symbol := byte(ui) + if v > largeLimit { + s.zeroBits = true + } + for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { + tableSymbol[position] = symbol + position = (position + step) & tableMask + for position > highThreshold { + position = (position + step) & tableMask + } /* Low proba area */ + } + } + + // Check if we have gone through all positions + if position != 0 { + return errors.New("position!=0") + } + } + + // Build table + table := s.ct.stateTable + { + tsi := int(tableSize) + for u, v := range tableSymbol { + // TableU16 : sorted by symbol order; gives next state value + table[cumul[v]] = uint16(tsi + u) + cumul[v]++ + } + } + + // Build Symbol Transformation Table + { + total := int16(0) + symbolTT := s.ct.symbolTT[:s.symbolLen] + tableLog := s.actualTableLog + tl := (uint32(tableLog) << 16) - (1 << tableLog) + for i, v := range s.norm[:s.symbolLen] { + switch v { + case 0: + case -1, 1: + symbolTT[i].deltaNbBits = tl + symbolTT[i].deltaFindState = int32(total - 1) + total++ + default: + maxBitsOut := uint32(tableLog) - highBits(uint32(v-1)) + minStatePlus := uint32(v) << maxBitsOut + symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus + symbolTT[i].deltaFindState = int32(total - v) + total += v + } + } + if total != int16(tableSize) { + return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) + } + } + return nil +} + +// countSimple will create a simple histogram in s.count. +// Returns the biggest count. +// Does not update s.clearCount. +func (s *Scratch) countSimple(in []byte) (max int) { + for _, v := range in { + s.count[v]++ + } + m, symlen := uint32(0), s.symbolLen + for i, v := range s.count[:] { + if v == 0 { + continue + } + if v > m { + m = v + } + symlen = uint16(i) + 1 + } + s.symbolLen = symlen + return int(m) +} + +// minTableLog provides the minimum logSize to safely represent a distribution. +func (s *Scratch) minTableLog() uint8 { + minBitsSrc := highBits(uint32(s.br.remain()-1)) + 1 + minBitsSymbols := highBits(uint32(s.symbolLen-1)) + 2 + if minBitsSrc < minBitsSymbols { + return uint8(minBitsSrc) + } + return uint8(minBitsSymbols) +} + +// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog +func (s *Scratch) optimalTableLog() { + tableLog := s.TableLog + minBits := s.minTableLog() + maxBitsSrc := uint8(highBits(uint32(s.br.remain()-1))) - 2 + if maxBitsSrc < tableLog { + // Accuracy can be reduced + tableLog = maxBitsSrc + } + if minBits > tableLog { + tableLog = minBits + } + // Need a minimum to safely represent all symbol values + if tableLog < minTablelog { + tableLog = minTablelog + } + if tableLog > maxTableLog { + tableLog = maxTableLog + } + s.actualTableLog = tableLog +} + +var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} + +// normalizeCount will normalize the count of the symbols so +// the total is equal to the table size. +func (s *Scratch) normalizeCount() error { + var ( + tableLog = s.actualTableLog + scale = 62 - uint64(tableLog) + step = (1 << 62) / uint64(s.br.remain()) + vStep = uint64(1) << (scale - 20) + stillToDistribute = int16(1 << tableLog) + largest int + largestP int16 + lowThreshold = (uint32)(s.br.remain() >> tableLog) + ) + + for i, cnt := range s.count[:s.symbolLen] { + // already handled + // if (count[s] == s.length) return 0; /* rle special case */ + + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + stillToDistribute-- + } else { + proba := (int16)((uint64(cnt) * step) >> scale) + if proba < 8 { + restToBeat := vStep * uint64(rtbTable[proba]) + v := uint64(cnt)*step - (uint64(proba) << scale) + if v > restToBeat { + proba++ + } + } + if proba > largestP { + largestP = proba + largest = i + } + s.norm[i] = proba + stillToDistribute -= proba + } + } + + if -stillToDistribute >= (s.norm[largest] >> 1) { + // corner case, need another normalization method + return s.normalizeCount2() + } + s.norm[largest] += stillToDistribute + return nil +} + +// Secondary normalization method. +// To be used when primary method fails. +func (s *Scratch) normalizeCount2() error { + const notYetAssigned = -2 + var ( + distributed uint32 + total = uint32(s.br.remain()) + tableLog = s.actualTableLog + lowThreshold = total >> tableLog + lowOne = (total * 3) >> (tableLog + 1) + ) + for i, cnt := range s.count[:s.symbolLen] { + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + distributed++ + total -= cnt + continue + } + if cnt <= lowOne { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + s.norm[i] = notYetAssigned + } + toDistribute := (1 << tableLog) - distributed + + if (total / toDistribute) > lowOne { + // risk of rounding to zero + lowOne = (total * 3) / (toDistribute * 2) + for i, cnt := range s.count[:s.symbolLen] { + if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + } + toDistribute = (1 << tableLog) - distributed + } + if distributed == uint32(s.symbolLen)+1 { + // all values are pretty poor; + // probably incompressible data (should have already been detected); + // find max, then give all remaining points to max + var maxV int + var maxC uint32 + for i, cnt := range s.count[:s.symbolLen] { + if cnt > maxC { + maxV = i + maxC = cnt + } + } + s.norm[maxV] += int16(toDistribute) + return nil + } + + if total == 0 { + // all of the symbols were low enough for the lowOne or lowThreshold + for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { + if s.norm[i] > 0 { + toDistribute-- + s.norm[i]++ + } + } + return nil + } + + var ( + vStepLog = 62 - uint64(tableLog) + mid = uint64((1 << (vStepLog - 1)) - 1) + rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining + tmpTotal = mid + ) + for i, cnt := range s.count[:s.symbolLen] { + if s.norm[i] == notYetAssigned { + var ( + end = tmpTotal + uint64(cnt)*rStep + sStart = uint32(tmpTotal >> vStepLog) + sEnd = uint32(end >> vStepLog) + weight = sEnd - sStart + ) + if weight < 1 { + return errors.New("weight < 1") + } + s.norm[i] = int16(weight) + tmpTotal = end + } + } + return nil +} + +// validateNorm validates the normalized histogram table. +func (s *Scratch) validateNorm() (err error) { + var total int + for _, v := range s.norm[:s.symbolLen] { + if v >= 0 { + total += int(v) + } else { + total -= int(v) + } + } + defer func() { + if err == nil { + return + } + fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen) + for i, v := range s.norm[:s.symbolLen] { + fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v) + } + }() + if total != (1 << s.actualTableLog) { + return fmt.Errorf("warning: Total == %d != %d", total, 1< tablelogAbsoluteMax { + return errors.New("tableLog too large") + } + bitStream >>= 4 + bitCount := uint(4) + + s.actualTableLog = uint8(nbBits) + remaining := int32((1 << nbBits) + 1) + threshold := int32(1 << nbBits) + gotTotal := int32(0) + nbBits++ + + for remaining > 1 { + if previous0 { + n0 := charnum + for (bitStream & 0xFFFF) == 0xFFFF { + n0 += 24 + if b.off < iend-5 { + b.advance(2) + bitStream = b.Uint32() >> bitCount + } else { + bitStream >>= 16 + bitCount += 16 + } + } + for (bitStream & 3) == 3 { + n0 += 3 + bitStream >>= 2 + bitCount += 2 + } + n0 += uint16(bitStream & 3) + bitCount += 2 + if n0 > maxSymbolValue { + return errors.New("maxSymbolValue too small") + } + for charnum < n0 { + s.norm[charnum&0xff] = 0 + charnum++ + } + + if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 { + b.advance(bitCount >> 3) + bitCount &= 7 + bitStream = b.Uint32() >> bitCount + } else { + bitStream >>= 2 + } + } + + max := (2*(threshold) - 1) - (remaining) + var count int32 + + if (int32(bitStream) & (threshold - 1)) < max { + count = int32(bitStream) & (threshold - 1) + bitCount += nbBits - 1 + } else { + count = int32(bitStream) & (2*threshold - 1) + if count >= threshold { + count -= max + } + bitCount += nbBits + } + + count-- // extra accuracy + if count < 0 { + // -1 means +1 + remaining += count + gotTotal -= count + } else { + remaining -= count + gotTotal += count + } + s.norm[charnum&0xff] = int16(count) + charnum++ + previous0 = count == 0 + for remaining < threshold { + nbBits-- + threshold >>= 1 + } + if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 { + b.advance(bitCount >> 3) + bitCount &= 7 + } else { + bitCount -= (uint)(8 * (len(b.b) - 4 - b.off)) + b.off = len(b.b) - 4 + } + bitStream = b.Uint32() >> (bitCount & 31) + } + s.symbolLen = charnum + + if s.symbolLen <= 1 { + return fmt.Errorf("symbolLen (%d) too small", s.symbolLen) + } + if s.symbolLen > maxSymbolValue+1 { + return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) + } + if remaining != 1 { + return fmt.Errorf("corruption detected (remaining %d != 1)", remaining) + } + if bitCount > 32 { + return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount) + } + if gotTotal != 1<> 3) + return nil +} + +// decSymbol contains information about a state entry, +// Including the state offset base, the output symbol and +// the number of bits to read for the low part of the destination state. +type decSymbol struct { + newState uint16 + symbol uint8 + nbBits uint8 +} + +// allocDtable will allocate decoding tables if they are not big enough. +func (s *Scratch) allocDtable() { + tableSize := 1 << s.actualTableLog + if cap(s.decTable) < tableSize { + s.decTable = make([]decSymbol, tableSize) + } + s.decTable = s.decTable[:tableSize] + + if cap(s.ct.tableSymbol) < 256 { + s.ct.tableSymbol = make([]byte, 256) + } + s.ct.tableSymbol = s.ct.tableSymbol[:256] + + if cap(s.ct.stateTable) < 256 { + s.ct.stateTable = make([]uint16, 256) + } + s.ct.stateTable = s.ct.stateTable[:256] +} + +// buildDtable will build the decoding table. +func (s *Scratch) buildDtable() error { + tableSize := uint32(1 << s.actualTableLog) + highThreshold := tableSize - 1 + s.allocDtable() + symbolNext := s.ct.stateTable[:256] + + // Init, lay down lowprob symbols + s.zeroBits = false + { + largeLimit := int16(1 << (s.actualTableLog - 1)) + for i, v := range s.norm[:s.symbolLen] { + if v == -1 { + s.decTable[highThreshold].symbol = uint8(i) + highThreshold-- + symbolNext[i] = 1 + } else { + if v >= largeLimit { + s.zeroBits = true + } + symbolNext[i] = uint16(v) + } + } + } + // Spread symbols + { + tableMask := tableSize - 1 + step := tableStep(tableSize) + position := uint32(0) + for ss, v := range s.norm[:s.symbolLen] { + for i := 0; i < int(v); i++ { + s.decTable[position].symbol = uint8(ss) + position = (position + step) & tableMask + for position > highThreshold { + // lowprob area + position = (position + step) & tableMask + } + } + } + if position != 0 { + // position must reach all cells once, otherwise normalizedCounter is incorrect + return errors.New("corrupted input (position != 0)") + } + } + + // Build Decoding table + { + tableSize := uint16(1 << s.actualTableLog) + for u, v := range s.decTable { + symbol := v.symbol + nextState := symbolNext[symbol] + symbolNext[symbol] = nextState + 1 + nBits := s.actualTableLog - byte(highBits(uint32(nextState))) + s.decTable[u].nbBits = nBits + newState := (nextState << nBits) - tableSize + if newState >= tableSize { + return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize) + } + if newState == uint16(u) && nBits == 0 { + // Seems weird that this is possible with nbits > 0. + return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u) + } + s.decTable[u].newState = newState + } + } + return nil +} + +// decompress will decompress the bitstream. +// If the buffer is over-read an error is returned. +func (s *Scratch) decompress() error { + br := &s.bits + if err := br.init(s.br.unread()); err != nil { + return err + } + + var s1, s2 decoder + // Initialize and decode first state and symbol. + s1.init(br, s.decTable, s.actualTableLog) + s2.init(br, s.decTable, s.actualTableLog) + + // Use temp table to avoid bound checks/append penalty. + var tmp = s.ct.tableSymbol[:256] + var off uint8 + + // Main part + if !s.zeroBits { + for br.off >= 8 { + br.fillFast() + tmp[off+0] = s1.nextFast() + tmp[off+1] = s2.nextFast() + br.fillFast() + tmp[off+2] = s1.nextFast() + tmp[off+3] = s2.nextFast() + off += 4 + // When off is 0, we have overflowed and should write. + if off == 0 { + s.Out = append(s.Out, tmp...) + if len(s.Out) >= s.DecompressLimit { + return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) + } + } + } + } else { + for br.off >= 8 { + br.fillFast() + tmp[off+0] = s1.next() + tmp[off+1] = s2.next() + br.fillFast() + tmp[off+2] = s1.next() + tmp[off+3] = s2.next() + off += 4 + if off == 0 { + s.Out = append(s.Out, tmp...) + // When off is 0, we have overflowed and should write. + if len(s.Out) >= s.DecompressLimit { + return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) + } + } + } + } + s.Out = append(s.Out, tmp[:off]...) + + // Final bits, a bit more expensive check + for { + if s1.finished() { + s.Out = append(s.Out, s1.final(), s2.final()) + break + } + br.fill() + s.Out = append(s.Out, s1.next()) + if s2.finished() { + s.Out = append(s.Out, s2.final(), s1.final()) + break + } + s.Out = append(s.Out, s2.next()) + if len(s.Out) >= s.DecompressLimit { + return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) + } + } + return br.close() +} + +// decoder keeps track of the current state and updates it from the bitstream. +type decoder struct { + state uint16 + br *bitReader + dt []decSymbol +} + +// init will initialize the decoder and read the first state from the stream. +func (d *decoder) init(in *bitReader, dt []decSymbol, tableLog uint8) { + d.dt = dt + d.br = in + d.state = in.getBits(tableLog) +} + +// next returns the next symbol and sets the next state. +// At least tablelog bits must be available in the bit reader. +func (d *decoder) next() uint8 { + n := &d.dt[d.state] + lowBits := d.br.getBits(n.nbBits) + d.state = n.newState + lowBits + return n.symbol +} + +// finished returns true if all bits have been read from the bitstream +// and the next state would require reading bits from the input. +func (d *decoder) finished() bool { + return d.br.finished() && d.dt[d.state].nbBits > 0 +} + +// final returns the current state symbol without decoding the next. +func (d *decoder) final() uint8 { + return d.dt[d.state].symbol +} + +// nextFast returns the next symbol and sets the next state. +// This can only be used if no symbols are 0 bits. +// At least tablelog bits must be available in the bit reader. +func (d *decoder) nextFast() uint8 { + n := d.dt[d.state] + lowBits := d.br.getBitsFast(n.nbBits) + d.state = n.newState + lowBits + return n.symbol +} diff --git a/vendor/github.com/klauspost/compress/fse/fse.go b/vendor/github.com/klauspost/compress/fse/fse.go new file mode 100644 index 000000000..535cbadfd --- /dev/null +++ b/vendor/github.com/klauspost/compress/fse/fse.go @@ -0,0 +1,144 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +// Package fse provides Finite State Entropy encoding and decoding. +// +// Finite State Entropy encoding provides a fast near-optimal symbol encoding/decoding +// for byte blocks as implemented in zstd. +// +// See https://github.com/klauspost/compress/tree/master/fse for more information. +package fse + +import ( + "errors" + "fmt" + "math/bits" +) + +const ( + /*!MEMORY_USAGE : + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) + * Increasing memory usage improves compression ratio + * Reduced memory usage can improve speed, due to cache effect + * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ + maxMemoryUsage = 14 + defaultMemoryUsage = 13 + + maxTableLog = maxMemoryUsage - 2 + maxTablesize = 1 << maxTableLog + defaultTablelog = defaultMemoryUsage - 2 + minTablelog = 5 + maxSymbolValue = 255 +) + +var ( + // ErrIncompressible is returned when input is judged to be too hard to compress. + ErrIncompressible = errors.New("input is not compressible") + + // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. + ErrUseRLE = errors.New("input is single value repeated") +) + +// Scratch provides temporary storage for compression and decompression. +type Scratch struct { + // Private + count [maxSymbolValue + 1]uint32 + norm [maxSymbolValue + 1]int16 + br byteReader + bits bitReader + bw bitWriter + ct cTable // Compression tables. + decTable []decSymbol // Decompression table. + maxCount int // count of the most probable symbol + + // Per block parameters. + // These can be used to override compression parameters of the block. + // Do not touch, unless you know what you are doing. + + // Out is output buffer. + // If the scratch is re-used before the caller is done processing the output, + // set this field to nil. + // Otherwise the output buffer will be re-used for next Compression/Decompression step + // and allocation will be avoided. + Out []byte + + // DecompressLimit limits the maximum decoded size acceptable. + // If > 0 decompression will stop when approximately this many bytes + // has been decoded. + // If 0, maximum size will be 2GB. + DecompressLimit int + + symbolLen uint16 // Length of active part of the symbol table. + actualTableLog uint8 // Selected tablelog. + zeroBits bool // no bits has prob > 50%. + clearCount bool // clear count + + // MaxSymbolValue will override the maximum symbol value of the next block. + MaxSymbolValue uint8 + + // TableLog will attempt to override the tablelog for the next block. + TableLog uint8 +} + +// Histogram allows to populate the histogram and skip that step in the compression, +// It otherwise allows to inspect the histogram when compression is done. +// To indicate that you have populated the histogram call HistogramFinished +// with the value of the highest populated symbol, as well as the number of entries +// in the most populated entry. These are accepted at face value. +// The returned slice will always be length 256. +func (s *Scratch) Histogram() []uint32 { + return s.count[:] +} + +// HistogramFinished can be called to indicate that the histogram has been populated. +// maxSymbol is the index of the highest set symbol of the next data segment. +// maxCount is the number of entries in the most populated entry. +// These are accepted at face value. +func (s *Scratch) HistogramFinished(maxSymbol uint8, maxCount int) { + s.maxCount = maxCount + s.symbolLen = uint16(maxSymbol) + 1 + s.clearCount = maxCount != 0 +} + +// prepare will prepare and allocate scratch tables used for both compression and decompression. +func (s *Scratch) prepare(in []byte) (*Scratch, error) { + if s == nil { + s = &Scratch{} + } + if s.MaxSymbolValue == 0 { + s.MaxSymbolValue = 255 + } + if s.TableLog == 0 { + s.TableLog = defaultTablelog + } + if s.TableLog > maxTableLog { + return nil, fmt.Errorf("tableLog (%d) > maxTableLog (%d)", s.TableLog, maxTableLog) + } + if cap(s.Out) == 0 { + s.Out = make([]byte, 0, len(in)) + } + if s.clearCount && s.maxCount == 0 { + for i := range s.count { + s.count[i] = 0 + } + s.clearCount = false + } + s.br.init(in) + if s.DecompressLimit == 0 { + // Max size 2GB. + s.DecompressLimit = (2 << 30) - 1 + } + + return s, nil +} + +// tableStep returns the next table index. +func tableStep(tableSize uint32) uint32 { + return (tableSize >> 1) + (tableSize >> 3) + 3 +} + +func highBits(val uint32) (n uint32) { + return uint32(bits.Len32(val) - 1) +} diff --git a/vendor/github.com/klauspost/compress/gen.sh b/vendor/github.com/klauspost/compress/gen.sh new file mode 100644 index 000000000..aff942205 --- /dev/null +++ b/vendor/github.com/klauspost/compress/gen.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +cd s2/cmd/_s2sx/ || exit 1 +go generate . diff --git a/vendor/github.com/klauspost/compress/huff0/.gitignore b/vendor/github.com/klauspost/compress/huff0/.gitignore new file mode 100644 index 000000000..b3d262958 --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/.gitignore @@ -0,0 +1 @@ +/huff0-fuzz.zip diff --git a/vendor/github.com/klauspost/compress/huff0/README.md b/vendor/github.com/klauspost/compress/huff0/README.md new file mode 100644 index 000000000..8b6e5c663 --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/README.md @@ -0,0 +1,89 @@ +# Huff0 entropy compression + +This package provides Huff0 encoding and decoding as used in zstd. + +[Huff0](https://github.com/Cyan4973/FiniteStateEntropy#new-generation-entropy-coders), +a Huffman codec designed for modern CPU, featuring OoO (Out of Order) operations on multiple ALU +(Arithmetic Logic Unit), achieving extremely fast compression and decompression speeds. + +This can be used for compressing input with a lot of similar input values to the smallest number of bytes. +This does not perform any multi-byte [dictionary coding](https://en.wikipedia.org/wiki/Dictionary_coder) as LZ coders, +but it can be used as a secondary step to compressors (like Snappy) that does not do entropy encoding. + +* [Godoc documentation](https://godoc.org/github.com/klauspost/compress/huff0) + +## News + +This is used as part of the [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and decompression package. + +This ensures that most functionality is well tested. + +# Usage + +This package provides a low level interface that allows to compress single independent blocks. + +Each block is separate, and there is no built in integrity checks. +This means that the caller should keep track of block sizes and also do checksums if needed. + +Compressing a block is done via the [`Compress1X`](https://godoc.org/github.com/klauspost/compress/huff0#Compress1X) and +[`Compress4X`](https://godoc.org/github.com/klauspost/compress/huff0#Compress4X) functions. +You must provide input and will receive the output and maybe an error. + +These error values can be returned: + +| Error | Description | +|---------------------|-----------------------------------------------------------------------------| +| `` | Everything ok, output is returned | +| `ErrIncompressible` | Returned when input is judged to be too hard to compress | +| `ErrUseRLE` | Returned from the compressor when the input is a single byte value repeated | +| `ErrTooBig` | Returned if the input block exceeds the maximum allowed size (128 Kib) | +| `(error)` | An internal error occurred. | + + +As can be seen above some of there are errors that will be returned even under normal operation so it is important to handle these. + +To reduce allocations you can provide a [`Scratch`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch) object +that can be re-used for successive calls. Both compression and decompression accepts a `Scratch` object, and the same +object can be used for both. + +Be aware, that when re-using a `Scratch` object that the *output* buffer is also re-used, so if you are still using this +you must set the `Out` field in the scratch to nil. The same buffer is used for compression and decompression output. + +The `Scratch` object will retain state that allows to re-use previous tables for encoding and decoding. + +## Tables and re-use + +Huff0 allows for reusing tables from the previous block to save space if that is expected to give better/faster results. + +The Scratch object allows you to set a [`ReusePolicy`](https://godoc.org/github.com/klauspost/compress/huff0#ReusePolicy) +that controls this behaviour. See the documentation for details. This can be altered between each block. + +Do however note that this information is *not* stored in the output block and it is up to the users of the package to +record whether [`ReadTable`](https://godoc.org/github.com/klauspost/compress/huff0#ReadTable) should be called, +based on the boolean reported back from the CompressXX call. + +If you want to store the table separate from the data, you can access them as `OutData` and `OutTable` on the +[`Scratch`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch) object. + +## Decompressing + +The first part of decoding is to initialize the decoding table through [`ReadTable`](https://godoc.org/github.com/klauspost/compress/huff0#ReadTable). +This will initialize the decoding tables. +You can supply the complete block to `ReadTable` and it will return the data part of the block +which can be given to the decompressor. + +Decompressing is done by calling the [`Decompress1X`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch.Decompress1X) +or [`Decompress4X`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch.Decompress4X) function. + +For concurrently decompressing content with a fixed table a stateless [`Decoder`](https://godoc.org/github.com/klauspost/compress/huff0#Decoder) can be requested which will remain correct as long as the scratch is unchanged. The capacity of the provided slice indicates the expected output size. + +You must provide the output from the compression stage, at exactly the size you got back. If you receive an error back +your input was likely corrupted. + +It is important to note that a successful decoding does *not* mean your output matches your original input. +There are no integrity checks, so relying on errors from the decompressor does not assure your data is valid. + +# Contributing + +Contributions are always welcome. Be aware that adding public functions will require good justification and breaking +changes will likely not be accepted. If in doubt open an issue before writing the PR. diff --git a/vendor/github.com/klauspost/compress/huff0/bitreader.go b/vendor/github.com/klauspost/compress/huff0/bitreader.go new file mode 100644 index 000000000..e36d9742f --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/bitreader.go @@ -0,0 +1,229 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package huff0 + +import ( + "encoding/binary" + "errors" + "fmt" + "io" +) + +// bitReader reads a bitstream in reverse. +// The last set bit indicates the start of the stream and is used +// for aligning the input. +type bitReaderBytes struct { + in []byte + off uint // next byte to read is at in[off - 1] + value uint64 + bitsRead uint8 +} + +// init initializes and resets the bit reader. +func (b *bitReaderBytes) init(in []byte) error { + if len(in) < 1 { + return errors.New("corrupt stream: too short") + } + b.in = in + b.off = uint(len(in)) + // The highest bit of the last byte indicates where to start + v := in[len(in)-1] + if v == 0 { + return errors.New("corrupt stream, did not find end of stream") + } + b.bitsRead = 64 + b.value = 0 + if len(in) >= 8 { + b.fillFastStart() + } else { + b.fill() + b.fill() + } + b.advance(8 - uint8(highBit32(uint32(v)))) + return nil +} + +// peekBitsFast requires that at least one bit is requested every time. +// There are no checks if the buffer is filled. +func (b *bitReaderBytes) peekByteFast() uint8 { + got := uint8(b.value >> 56) + return got +} + +func (b *bitReaderBytes) advance(n uint8) { + b.bitsRead += n + b.value <<= n & 63 +} + +// fillFast() will make sure at least 32 bits are available. +// There must be at least 4 bytes available. +func (b *bitReaderBytes) fillFast() { + if b.bitsRead < 32 { + return + } + + // 2 bounds checks. + v := b.in[b.off-4 : b.off] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value |= uint64(low) << (b.bitsRead - 32) + b.bitsRead -= 32 + b.off -= 4 +} + +// fillFastStart() assumes the bitReaderBytes is empty and there is at least 8 bytes to read. +func (b *bitReaderBytes) fillFastStart() { + // Do single re-slice to avoid bounds checks. + b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) + b.bitsRead = 0 + b.off -= 8 +} + +// fill() will make sure at least 32 bits are available. +func (b *bitReaderBytes) fill() { + if b.bitsRead < 32 { + return + } + if b.off > 4 { + v := b.in[b.off-4 : b.off] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value |= uint64(low) << (b.bitsRead - 32) + b.bitsRead -= 32 + b.off -= 4 + return + } + for b.off > 0 { + b.value |= uint64(b.in[b.off-1]) << (b.bitsRead - 8) + b.bitsRead -= 8 + b.off-- + } +} + +// finished returns true if all bits have been read from the bit stream. +func (b *bitReaderBytes) finished() bool { + return b.off == 0 && b.bitsRead >= 64 +} + +func (b *bitReaderBytes) remaining() uint { + return b.off*8 + uint(64-b.bitsRead) +} + +// close the bitstream and returns an error if out-of-buffer reads occurred. +func (b *bitReaderBytes) close() error { + // Release reference. + b.in = nil + if b.remaining() > 0 { + return fmt.Errorf("corrupt input: %d bits remain on stream", b.remaining()) + } + if b.bitsRead > 64 { + return io.ErrUnexpectedEOF + } + return nil +} + +// bitReaderShifted reads a bitstream in reverse. +// The last set bit indicates the start of the stream and is used +// for aligning the input. +type bitReaderShifted struct { + in []byte + off uint // next byte to read is at in[off - 1] + value uint64 + bitsRead uint8 +} + +// init initializes and resets the bit reader. +func (b *bitReaderShifted) init(in []byte) error { + if len(in) < 1 { + return errors.New("corrupt stream: too short") + } + b.in = in + b.off = uint(len(in)) + // The highest bit of the last byte indicates where to start + v := in[len(in)-1] + if v == 0 { + return errors.New("corrupt stream, did not find end of stream") + } + b.bitsRead = 64 + b.value = 0 + if len(in) >= 8 { + b.fillFastStart() + } else { + b.fill() + b.fill() + } + b.advance(8 - uint8(highBit32(uint32(v)))) + return nil +} + +// peekBitsFast requires that at least one bit is requested every time. +// There are no checks if the buffer is filled. +func (b *bitReaderShifted) peekBitsFast(n uint8) uint16 { + return uint16(b.value >> ((64 - n) & 63)) +} + +func (b *bitReaderShifted) advance(n uint8) { + b.bitsRead += n + b.value <<= n & 63 +} + +// fillFast() will make sure at least 32 bits are available. +// There must be at least 4 bytes available. +func (b *bitReaderShifted) fillFast() { + if b.bitsRead < 32 { + return + } + + // 2 bounds checks. + v := b.in[b.off-4 : b.off] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value |= uint64(low) << ((b.bitsRead - 32) & 63) + b.bitsRead -= 32 + b.off -= 4 +} + +// fillFastStart() assumes the bitReaderShifted is empty and there is at least 8 bytes to read. +func (b *bitReaderShifted) fillFastStart() { + // Do single re-slice to avoid bounds checks. + b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) + b.bitsRead = 0 + b.off -= 8 +} + +// fill() will make sure at least 32 bits are available. +func (b *bitReaderShifted) fill() { + if b.bitsRead < 32 { + return + } + if b.off > 4 { + v := b.in[b.off-4 : b.off] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value |= uint64(low) << ((b.bitsRead - 32) & 63) + b.bitsRead -= 32 + b.off -= 4 + return + } + for b.off > 0 { + b.value |= uint64(b.in[b.off-1]) << ((b.bitsRead - 8) & 63) + b.bitsRead -= 8 + b.off-- + } +} + +func (b *bitReaderShifted) remaining() uint { + return b.off*8 + uint(64-b.bitsRead) +} + +// close the bitstream and returns an error if out-of-buffer reads occurred. +func (b *bitReaderShifted) close() error { + // Release reference. + b.in = nil + if b.remaining() > 0 { + return fmt.Errorf("corrupt input: %d bits remain on stream", b.remaining()) + } + if b.bitsRead > 64 { + return io.ErrUnexpectedEOF + } + return nil +} diff --git a/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/vendor/github.com/klauspost/compress/huff0/bitwriter.go new file mode 100644 index 000000000..0ebc9aaac --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/bitwriter.go @@ -0,0 +1,102 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package huff0 + +// bitWriter will write bits. +// First bit will be LSB of the first byte of output. +type bitWriter struct { + bitContainer uint64 + nBits uint8 + out []byte +} + +// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// encSymbol will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) encSymbol(ct cTable, symbol byte) { + enc := ct[symbol] + b.bitContainer |= uint64(enc.val) << (b.nBits & 63) + if false { + if enc.nBits == 0 { + panic("nbits 0") + } + } + b.nBits += enc.nBits +} + +// encTwoSymbols will add up to 32 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) encTwoSymbols(ct cTable, av, bv byte) { + encA := ct[av] + encB := ct[bv] + sh := b.nBits & 63 + combined := uint64(encA.val) | (uint64(encB.val) << (encA.nBits & 63)) + b.bitContainer |= combined << sh + if false { + if encA.nBits == 0 { + panic("nbitsA 0") + } + if encB.nBits == 0 { + panic("nbitsB 0") + } + } + b.nBits += encA.nBits + encB.nBits +} + +// encFourSymbols adds up to 32 bits from four symbols. +// It will not check if there is space for them, +// so the caller must ensure that b has been flushed recently. +func (b *bitWriter) encFourSymbols(encA, encB, encC, encD cTableEntry) { + bitsA := encA.nBits + bitsB := bitsA + encB.nBits + bitsC := bitsB + encC.nBits + bitsD := bitsC + encD.nBits + combined := uint64(encA.val) | + (uint64(encB.val) << (bitsA & 63)) | + (uint64(encC.val) << (bitsB & 63)) | + (uint64(encD.val) << (bitsC & 63)) + b.bitContainer |= combined << (b.nBits & 63) + b.nBits += bitsD +} + +// flush32 will flush out, so there are at least 32 bits available for writing. +func (b *bitWriter) flush32() { + if b.nBits < 32 { + return + } + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24)) + b.nBits -= 32 + b.bitContainer >>= 32 +} + +// flushAlign will flush remaining full bytes and align to next byte boundary. +func (b *bitWriter) flushAlign() { + nbBytes := (b.nBits + 7) >> 3 + for i := uint8(0); i < nbBytes; i++ { + b.out = append(b.out, byte(b.bitContainer>>(i*8))) + } + b.nBits = 0 + b.bitContainer = 0 +} + +// close will write the alignment bit and write the final byte(s) +// to the output. +func (b *bitWriter) close() { + // End mark + b.addBits16Clean(1, 1) + // flush until next byte. + b.flushAlign() +} diff --git a/vendor/github.com/klauspost/compress/huff0/compress.go b/vendor/github.com/klauspost/compress/huff0/compress.go new file mode 100644 index 000000000..84aa3d12f --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/compress.go @@ -0,0 +1,742 @@ +package huff0 + +import ( + "fmt" + "math" + "runtime" + "sync" +) + +// Compress1X will compress the input. +// The output can be decoded using Decompress1X. +// Supply a Scratch object. The scratch object contains state about re-use, +// So when sharing across independent encodes, be sure to set the re-use policy. +func Compress1X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { + s, err = s.prepare(in) + if err != nil { + return nil, false, err + } + return compress(in, s, s.compress1X) +} + +// Compress4X will compress the input. The input is split into 4 independent blocks +// and compressed similar to Compress1X. +// The output can be decoded using Decompress4X. +// Supply a Scratch object. The scratch object contains state about re-use, +// So when sharing across independent encodes, be sure to set the re-use policy. +func Compress4X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { + s, err = s.prepare(in) + if err != nil { + return nil, false, err + } + if false { + // TODO: compress4Xp only slightly faster. + const parallelThreshold = 8 << 10 + if len(in) < parallelThreshold || runtime.GOMAXPROCS(0) == 1 { + return compress(in, s, s.compress4X) + } + return compress(in, s, s.compress4Xp) + } + return compress(in, s, s.compress4X) +} + +func compress(in []byte, s *Scratch, compressor func(src []byte) ([]byte, error)) (out []byte, reUsed bool, err error) { + // Nuke previous table if we cannot reuse anyway. + if s.Reuse == ReusePolicyNone { + s.prevTable = s.prevTable[:0] + } + + // Create histogram, if none was provided. + maxCount := s.maxCount + var canReuse = false + if maxCount == 0 { + maxCount, canReuse = s.countSimple(in) + } else { + canReuse = s.canUseTable(s.prevTable) + } + + // We want the output size to be less than this: + wantSize := len(in) + if s.WantLogLess > 0 { + wantSize -= wantSize >> s.WantLogLess + } + + // Reset for next run. + s.clearCount = true + s.maxCount = 0 + if maxCount >= len(in) { + if maxCount > len(in) { + return nil, false, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in)) + } + if len(in) == 1 { + return nil, false, ErrIncompressible + } + // One symbol, use RLE + return nil, false, ErrUseRLE + } + if maxCount == 1 || maxCount < (len(in)>>7) { + // Each symbol present maximum once or too well distributed. + return nil, false, ErrIncompressible + } + if s.Reuse == ReusePolicyMust && !canReuse { + // We must reuse, but we can't. + return nil, false, ErrIncompressible + } + if (s.Reuse == ReusePolicyPrefer || s.Reuse == ReusePolicyMust) && canReuse { + keepTable := s.cTable + keepTL := s.actualTableLog + s.cTable = s.prevTable + s.actualTableLog = s.prevTableLog + s.Out, err = compressor(in) + s.cTable = keepTable + s.actualTableLog = keepTL + if err == nil && len(s.Out) < wantSize { + s.OutData = s.Out + return s.Out, true, nil + } + if s.Reuse == ReusePolicyMust { + return nil, false, ErrIncompressible + } + // Do not attempt to re-use later. + s.prevTable = s.prevTable[:0] + } + + // Calculate new table. + err = s.buildCTable() + if err != nil { + return nil, false, err + } + + if false && !s.canUseTable(s.cTable) { + panic("invalid table generated") + } + + if s.Reuse == ReusePolicyAllow && canReuse { + hSize := len(s.Out) + oldSize := s.prevTable.estimateSize(s.count[:s.symbolLen]) + newSize := s.cTable.estimateSize(s.count[:s.symbolLen]) + if oldSize <= hSize+newSize || hSize+12 >= wantSize { + // Retain cTable even if we re-use. + keepTable := s.cTable + keepTL := s.actualTableLog + + s.cTable = s.prevTable + s.actualTableLog = s.prevTableLog + s.Out, err = compressor(in) + + // Restore ctable. + s.cTable = keepTable + s.actualTableLog = keepTL + if err != nil { + return nil, false, err + } + if len(s.Out) >= wantSize { + return nil, false, ErrIncompressible + } + s.OutData = s.Out + return s.Out, true, nil + } + } + + // Use new table + err = s.cTable.write(s) + if err != nil { + s.OutTable = nil + return nil, false, err + } + s.OutTable = s.Out + + // Compress using new table + s.Out, err = compressor(in) + if err != nil { + s.OutTable = nil + return nil, false, err + } + if len(s.Out) >= wantSize { + s.OutTable = nil + return nil, false, ErrIncompressible + } + // Move current table into previous. + s.prevTable, s.prevTableLog, s.cTable = s.cTable, s.actualTableLog, s.prevTable[:0] + s.OutData = s.Out[len(s.OutTable):] + return s.Out, false, nil +} + +// EstimateSizes will estimate the data sizes +func EstimateSizes(in []byte, s *Scratch) (tableSz, dataSz, reuseSz int, err error) { + s, err = s.prepare(in) + if err != nil { + return 0, 0, 0, err + } + + // Create histogram, if none was provided. + tableSz, dataSz, reuseSz = -1, -1, -1 + maxCount := s.maxCount + var canReuse = false + if maxCount == 0 { + maxCount, canReuse = s.countSimple(in) + } else { + canReuse = s.canUseTable(s.prevTable) + } + + // We want the output size to be less than this: + wantSize := len(in) + if s.WantLogLess > 0 { + wantSize -= wantSize >> s.WantLogLess + } + + // Reset for next run. + s.clearCount = true + s.maxCount = 0 + if maxCount >= len(in) { + if maxCount > len(in) { + return 0, 0, 0, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in)) + } + if len(in) == 1 { + return 0, 0, 0, ErrIncompressible + } + // One symbol, use RLE + return 0, 0, 0, ErrUseRLE + } + if maxCount == 1 || maxCount < (len(in)>>7) { + // Each symbol present maximum once or too well distributed. + return 0, 0, 0, ErrIncompressible + } + + // Calculate new table. + err = s.buildCTable() + if err != nil { + return 0, 0, 0, err + } + + if false && !s.canUseTable(s.cTable) { + panic("invalid table generated") + } + + tableSz, err = s.cTable.estTableSize(s) + if err != nil { + return 0, 0, 0, err + } + if canReuse { + reuseSz = s.prevTable.estimateSize(s.count[:s.symbolLen]) + } + dataSz = s.cTable.estimateSize(s.count[:s.symbolLen]) + + // Restore + return tableSz, dataSz, reuseSz, nil +} + +func (s *Scratch) compress1X(src []byte) ([]byte, error) { + return s.compress1xDo(s.Out, src), nil +} + +func (s *Scratch) compress1xDo(dst, src []byte) []byte { + var bw = bitWriter{out: dst} + + // N is length divisible by 4. + n := len(src) + n -= n & 3 + cTable := s.cTable[:256] + + // Encode last bytes. + for i := len(src) & 3; i > 0; i-- { + bw.encSymbol(cTable, src[n+i-1]) + } + n -= 4 + if s.actualTableLog <= 8 { + for ; n >= 0; n -= 4 { + tmp := src[n : n+4] + // tmp should be len 4 + bw.flush32() + bw.encFourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]]) + } + } else { + for ; n >= 0; n -= 4 { + tmp := src[n : n+4] + // tmp should be len 4 + bw.flush32() + bw.encTwoSymbols(cTable, tmp[3], tmp[2]) + bw.flush32() + bw.encTwoSymbols(cTable, tmp[1], tmp[0]) + } + } + bw.close() + return bw.out +} + +var sixZeros [6]byte + +func (s *Scratch) compress4X(src []byte) ([]byte, error) { + if len(src) < 12 { + return nil, ErrIncompressible + } + segmentSize := (len(src) + 3) / 4 + + // Add placeholder for output length + offsetIdx := len(s.Out) + s.Out = append(s.Out, sixZeros[:]...) + + for i := 0; i < 4; i++ { + toDo := src + if len(toDo) > segmentSize { + toDo = toDo[:segmentSize] + } + src = src[len(toDo):] + + idx := len(s.Out) + s.Out = s.compress1xDo(s.Out, toDo) + if len(s.Out)-idx > math.MaxUint16 { + // We cannot store the size in the jump table + return nil, ErrIncompressible + } + // Write compressed length as little endian before block. + if i < 3 { + // Last length is not written. + length := len(s.Out) - idx + s.Out[i*2+offsetIdx] = byte(length) + s.Out[i*2+offsetIdx+1] = byte(length >> 8) + } + } + + return s.Out, nil +} + +// compress4Xp will compress 4 streams using separate goroutines. +func (s *Scratch) compress4Xp(src []byte) ([]byte, error) { + if len(src) < 12 { + return nil, ErrIncompressible + } + // Add placeholder for output length + s.Out = s.Out[:6] + + segmentSize := (len(src) + 3) / 4 + var wg sync.WaitGroup + wg.Add(4) + for i := 0; i < 4; i++ { + toDo := src + if len(toDo) > segmentSize { + toDo = toDo[:segmentSize] + } + src = src[len(toDo):] + + // Separate goroutine for each block. + go func(i int) { + s.tmpOut[i] = s.compress1xDo(s.tmpOut[i][:0], toDo) + wg.Done() + }(i) + } + wg.Wait() + for i := 0; i < 4; i++ { + o := s.tmpOut[i] + if len(o) > math.MaxUint16 { + // We cannot store the size in the jump table + return nil, ErrIncompressible + } + // Write compressed length as little endian before block. + if i < 3 { + // Last length is not written. + s.Out[i*2] = byte(len(o)) + s.Out[i*2+1] = byte(len(o) >> 8) + } + + // Write output. + s.Out = append(s.Out, o...) + } + return s.Out, nil +} + +// countSimple will create a simple histogram in s.count. +// Returns the biggest count. +// Does not update s.clearCount. +func (s *Scratch) countSimple(in []byte) (max int, reuse bool) { + reuse = true + _ = s.count // Assert that s != nil to speed up the following loop. + for _, v := range in { + s.count[v]++ + } + m := uint32(0) + if len(s.prevTable) > 0 { + for i, v := range s.count[:] { + if v == 0 { + continue + } + if v > m { + m = v + } + s.symbolLen = uint16(i) + 1 + if i >= len(s.prevTable) { + reuse = false + } else if s.prevTable[i].nBits == 0 { + reuse = false + } + } + return int(m), reuse + } + for i, v := range s.count[:] { + if v == 0 { + continue + } + if v > m { + m = v + } + s.symbolLen = uint16(i) + 1 + } + return int(m), false +} + +func (s *Scratch) canUseTable(c cTable) bool { + if len(c) < int(s.symbolLen) { + return false + } + for i, v := range s.count[:s.symbolLen] { + if v != 0 && c[i].nBits == 0 { + return false + } + } + return true +} + +//lint:ignore U1000 used for debugging +func (s *Scratch) validateTable(c cTable) bool { + if len(c) < int(s.symbolLen) { + return false + } + for i, v := range s.count[:s.symbolLen] { + if v != 0 { + if c[i].nBits == 0 { + return false + } + if c[i].nBits > s.actualTableLog { + return false + } + } + } + return true +} + +// minTableLog provides the minimum logSize to safely represent a distribution. +func (s *Scratch) minTableLog() uint8 { + minBitsSrc := highBit32(uint32(s.srcLen)) + 1 + minBitsSymbols := highBit32(uint32(s.symbolLen-1)) + 2 + if minBitsSrc < minBitsSymbols { + return uint8(minBitsSrc) + } + return uint8(minBitsSymbols) +} + +// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog +func (s *Scratch) optimalTableLog() { + tableLog := s.TableLog + minBits := s.minTableLog() + maxBitsSrc := uint8(highBit32(uint32(s.srcLen-1))) - 1 + if maxBitsSrc < tableLog { + // Accuracy can be reduced + tableLog = maxBitsSrc + } + if minBits > tableLog { + tableLog = minBits + } + // Need a minimum to safely represent all symbol values + if tableLog < minTablelog { + tableLog = minTablelog + } + if tableLog > tableLogMax { + tableLog = tableLogMax + } + s.actualTableLog = tableLog +} + +type cTableEntry struct { + val uint16 + nBits uint8 + // We have 8 bits extra +} + +const huffNodesMask = huffNodesLen - 1 + +func (s *Scratch) buildCTable() error { + s.optimalTableLog() + s.huffSort() + if cap(s.cTable) < maxSymbolValue+1 { + s.cTable = make([]cTableEntry, s.symbolLen, maxSymbolValue+1) + } else { + s.cTable = s.cTable[:s.symbolLen] + for i := range s.cTable { + s.cTable[i] = cTableEntry{} + } + } + + var startNode = int16(s.symbolLen) + nonNullRank := s.symbolLen - 1 + + nodeNb := startNode + huffNode := s.nodes[1 : huffNodesLen+1] + + // This overlays the slice above, but allows "-1" index lookups. + // Different from reference implementation. + huffNode0 := s.nodes[0 : huffNodesLen+1] + + for huffNode[nonNullRank].count() == 0 { + nonNullRank-- + } + + lowS := int16(nonNullRank) + nodeRoot := nodeNb + lowS - 1 + lowN := nodeNb + huffNode[nodeNb].setCount(huffNode[lowS].count() + huffNode[lowS-1].count()) + huffNode[lowS].setParent(nodeNb) + huffNode[lowS-1].setParent(nodeNb) + nodeNb++ + lowS -= 2 + for n := nodeNb; n <= nodeRoot; n++ { + huffNode[n].setCount(1 << 30) + } + // fake entry, strong barrier + huffNode0[0].setCount(1 << 31) + + // create parents + for nodeNb <= nodeRoot { + var n1, n2 int16 + if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { + n1 = lowS + lowS-- + } else { + n1 = lowN + lowN++ + } + if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { + n2 = lowS + lowS-- + } else { + n2 = lowN + lowN++ + } + + huffNode[nodeNb].setCount(huffNode0[n1+1].count() + huffNode0[n2+1].count()) + huffNode0[n1+1].setParent(nodeNb) + huffNode0[n2+1].setParent(nodeNb) + nodeNb++ + } + + // distribute weights (unlimited tree height) + huffNode[nodeRoot].setNbBits(0) + for n := nodeRoot - 1; n >= startNode; n-- { + huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) + } + for n := uint16(0); n <= nonNullRank; n++ { + huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) + } + s.actualTableLog = s.setMaxHeight(int(nonNullRank)) + maxNbBits := s.actualTableLog + + // fill result into tree (val, nbBits) + if maxNbBits > tableLogMax { + return fmt.Errorf("internal error: maxNbBits (%d) > tableLogMax (%d)", maxNbBits, tableLogMax) + } + var nbPerRank [tableLogMax + 1]uint16 + var valPerRank [16]uint16 + for _, v := range huffNode[:nonNullRank+1] { + nbPerRank[v.nbBits()]++ + } + // determine stating value per rank + { + min := uint16(0) + for n := maxNbBits; n > 0; n-- { + // get starting value within each rank + valPerRank[n] = min + min += nbPerRank[n] + min >>= 1 + } + } + + // push nbBits per symbol, symbol order + for _, v := range huffNode[:nonNullRank+1] { + s.cTable[v.symbol()].nBits = v.nbBits() + } + + // assign value within rank, symbol order + t := s.cTable[:s.symbolLen] + for n, val := range t { + nbits := val.nBits & 15 + v := valPerRank[nbits] + t[n].val = v + valPerRank[nbits] = v + 1 + } + + return nil +} + +// huffSort will sort symbols, decreasing order. +func (s *Scratch) huffSort() { + type rankPos struct { + base uint32 + current uint32 + } + + // Clear nodes + nodes := s.nodes[:huffNodesLen+1] + s.nodes = nodes + nodes = nodes[1 : huffNodesLen+1] + + // Sort into buckets based on length of symbol count. + var rank [32]rankPos + for _, v := range s.count[:s.symbolLen] { + r := highBit32(v+1) & 31 + rank[r].base++ + } + // maxBitLength is log2(BlockSizeMax) + 1 + const maxBitLength = 18 + 1 + for n := maxBitLength; n > 0; n-- { + rank[n-1].base += rank[n].base + } + for n := range rank[:maxBitLength] { + rank[n].current = rank[n].base + } + for n, c := range s.count[:s.symbolLen] { + r := (highBit32(c+1) + 1) & 31 + pos := rank[r].current + rank[r].current++ + prev := nodes[(pos-1)&huffNodesMask] + for pos > rank[r].base && c > prev.count() { + nodes[pos&huffNodesMask] = prev + pos-- + prev = nodes[(pos-1)&huffNodesMask] + } + nodes[pos&huffNodesMask] = makeNodeElt(c, byte(n)) + } +} + +func (s *Scratch) setMaxHeight(lastNonNull int) uint8 { + maxNbBits := s.actualTableLog + huffNode := s.nodes[1 : huffNodesLen+1] + //huffNode = huffNode[: huffNodesLen] + + largestBits := huffNode[lastNonNull].nbBits() + + // early exit : no elt > maxNbBits + if largestBits <= maxNbBits { + return largestBits + } + totalCost := int(0) + baseCost := int(1) << (largestBits - maxNbBits) + n := uint32(lastNonNull) + + for huffNode[n].nbBits() > maxNbBits { + totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits())) + huffNode[n].setNbBits(maxNbBits) + n-- + } + // n stops at huffNode[n].nbBits <= maxNbBits + + for huffNode[n].nbBits() == maxNbBits { + n-- + } + // n end at index of smallest symbol using < maxNbBits + + // renorm totalCost + totalCost >>= largestBits - maxNbBits /* note : totalCost is necessarily a multiple of baseCost */ + + // repay normalized cost + { + const noSymbol = 0xF0F0F0F0 + var rankLast [tableLogMax + 2]uint32 + + for i := range rankLast[:] { + rankLast[i] = noSymbol + } + + // Get pos of last (smallest) symbol per rank + { + currentNbBits := maxNbBits + for pos := int(n); pos >= 0; pos-- { + if huffNode[pos].nbBits() >= currentNbBits { + continue + } + currentNbBits = huffNode[pos].nbBits() // < maxNbBits + rankLast[maxNbBits-currentNbBits] = uint32(pos) + } + } + + for totalCost > 0 { + nBitsToDecrease := uint8(highBit32(uint32(totalCost))) + 1 + + for ; nBitsToDecrease > 1; nBitsToDecrease-- { + highPos := rankLast[nBitsToDecrease] + lowPos := rankLast[nBitsToDecrease-1] + if highPos == noSymbol { + continue + } + if lowPos == noSymbol { + break + } + highTotal := huffNode[highPos].count() + lowTotal := 2 * huffNode[lowPos].count() + if highTotal <= lowTotal { + break + } + } + // only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) + // HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary + // FIXME: try to remove + for (nBitsToDecrease <= tableLogMax) && (rankLast[nBitsToDecrease] == noSymbol) { + nBitsToDecrease++ + } + totalCost -= 1 << (nBitsToDecrease - 1) + if rankLast[nBitsToDecrease-1] == noSymbol { + // this rank is no longer empty + rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease] + } + huffNode[rankLast[nBitsToDecrease]].setNbBits(1 + + huffNode[rankLast[nBitsToDecrease]].nbBits()) + if rankLast[nBitsToDecrease] == 0 { + /* special case, reached largest symbol */ + rankLast[nBitsToDecrease] = noSymbol + } else { + rankLast[nBitsToDecrease]-- + if huffNode[rankLast[nBitsToDecrease]].nbBits() != maxNbBits-nBitsToDecrease { + rankLast[nBitsToDecrease] = noSymbol /* this rank is now empty */ + } + } + } + + for totalCost < 0 { /* Sometimes, cost correction overshoot */ + if rankLast[1] == noSymbol { /* special case : no rank 1 symbol (using maxNbBits-1); let's create one from largest rank 0 (using maxNbBits) */ + for huffNode[n].nbBits() == maxNbBits { + n-- + } + huffNode[n+1].setNbBits(huffNode[n+1].nbBits() - 1) + rankLast[1] = n + 1 + totalCost++ + continue + } + huffNode[rankLast[1]+1].setNbBits(huffNode[rankLast[1]+1].nbBits() - 1) + rankLast[1]++ + totalCost++ + } + } + return maxNbBits +} + +// A nodeElt is the fields +// +// count uint32 +// parent uint16 +// symbol byte +// nbBits uint8 +// +// in some order, all squashed into an integer so that the compiler +// always loads and stores entire nodeElts instead of separate fields. +type nodeElt uint64 + +func makeNodeElt(count uint32, symbol byte) nodeElt { + return nodeElt(count) | nodeElt(symbol)<<48 +} + +func (e *nodeElt) count() uint32 { return uint32(*e) } +func (e *nodeElt) parent() uint16 { return uint16(*e >> 32) } +func (e *nodeElt) symbol() byte { return byte(*e >> 48) } +func (e *nodeElt) nbBits() uint8 { return uint8(*e >> 56) } + +func (e *nodeElt) setCount(c uint32) { *e = (*e)&0xffffffff00000000 | nodeElt(c) } +func (e *nodeElt) setParent(p int16) { *e = (*e)&0xffff0000ffffffff | nodeElt(uint16(p))<<32 } +func (e *nodeElt) setNbBits(n uint8) { *e = (*e)&0x00ffffffffffffff | nodeElt(n)<<56 } diff --git a/vendor/github.com/klauspost/compress/huff0/decompress.go b/vendor/github.com/klauspost/compress/huff0/decompress.go new file mode 100644 index 000000000..54bd08b25 --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/decompress.go @@ -0,0 +1,1167 @@ +package huff0 + +import ( + "errors" + "fmt" + "io" + "sync" + + "github.com/klauspost/compress/fse" +) + +type dTable struct { + single []dEntrySingle +} + +// single-symbols decoding +type dEntrySingle struct { + entry uint16 +} + +// Uses special code for all tables that are < 8 bits. +const use8BitTables = true + +// ReadTable will read a table from the input. +// The size of the input may be larger than the table definition. +// Any content remaining after the table definition will be returned. +// If no Scratch is provided a new one is allocated. +// The returned Scratch can be used for encoding or decoding input using this table. +func ReadTable(in []byte, s *Scratch) (s2 *Scratch, remain []byte, err error) { + s, err = s.prepare(nil) + if err != nil { + return s, nil, err + } + if len(in) <= 1 { + return s, nil, errors.New("input too small for table") + } + iSize := in[0] + in = in[1:] + if iSize >= 128 { + // Uncompressed + oSize := iSize - 127 + iSize = (oSize + 1) / 2 + if int(iSize) > len(in) { + return s, nil, errors.New("input too small for table") + } + for n := uint8(0); n < oSize; n += 2 { + v := in[n/2] + s.huffWeight[n] = v >> 4 + s.huffWeight[n+1] = v & 15 + } + s.symbolLen = uint16(oSize) + in = in[iSize:] + } else { + if len(in) < int(iSize) { + return s, nil, fmt.Errorf("input too small for table, want %d bytes, have %d", iSize, len(in)) + } + // FSE compressed weights + s.fse.DecompressLimit = 255 + hw := s.huffWeight[:] + s.fse.Out = hw + b, err := fse.Decompress(in[:iSize], s.fse) + s.fse.Out = nil + if err != nil { + return s, nil, fmt.Errorf("fse decompress returned: %w", err) + } + if len(b) > 255 { + return s, nil, errors.New("corrupt input: output table too large") + } + s.symbolLen = uint16(len(b)) + in = in[iSize:] + } + + // collect weight stats + var rankStats [16]uint32 + weightTotal := uint32(0) + for _, v := range s.huffWeight[:s.symbolLen] { + if v > tableLogMax { + return s, nil, errors.New("corrupt input: weight too large") + } + v2 := v & 15 + rankStats[v2]++ + // (1 << (v2-1)) is slower since the compiler cannot prove that v2 isn't 0. + weightTotal += (1 << v2) >> 1 + } + if weightTotal == 0 { + return s, nil, errors.New("corrupt input: weights zero") + } + + // get last non-null symbol weight (implied, total must be 2^n) + { + tableLog := highBit32(weightTotal) + 1 + if tableLog > tableLogMax { + return s, nil, errors.New("corrupt input: tableLog too big") + } + s.actualTableLog = uint8(tableLog) + // determine last weight + { + total := uint32(1) << tableLog + rest := total - weightTotal + verif := uint32(1) << highBit32(rest) + lastWeight := highBit32(rest) + 1 + if verif != rest { + // last value must be a clean power of 2 + return s, nil, errors.New("corrupt input: last value not power of two") + } + s.huffWeight[s.symbolLen] = uint8(lastWeight) + s.symbolLen++ + rankStats[lastWeight]++ + } + } + + if (rankStats[1] < 2) || (rankStats[1]&1 != 0) { + // by construction : at least 2 elts of rank 1, must be even + return s, nil, errors.New("corrupt input: min elt size, even check failed ") + } + + // TODO: Choose between single/double symbol decoding + + // Calculate starting value for each rank + { + var nextRankStart uint32 + for n := uint8(1); n < s.actualTableLog+1; n++ { + current := nextRankStart + nextRankStart += rankStats[n] << (n - 1) + rankStats[n] = current + } + } + + // fill DTable (always full size) + tSize := 1 << tableLogMax + if len(s.dt.single) != tSize { + s.dt.single = make([]dEntrySingle, tSize) + } + cTable := s.prevTable + if cap(cTable) < maxSymbolValue+1 { + cTable = make([]cTableEntry, 0, maxSymbolValue+1) + } + cTable = cTable[:maxSymbolValue+1] + s.prevTable = cTable[:s.symbolLen] + s.prevTableLog = s.actualTableLog + + for n, w := range s.huffWeight[:s.symbolLen] { + if w == 0 { + cTable[n] = cTableEntry{ + val: 0, + nBits: 0, + } + continue + } + length := (uint32(1) << w) >> 1 + d := dEntrySingle{ + entry: uint16(s.actualTableLog+1-w) | (uint16(n) << 8), + } + + rank := &rankStats[w] + cTable[n] = cTableEntry{ + val: uint16(*rank >> (w - 1)), + nBits: uint8(d.entry), + } + + single := s.dt.single[*rank : *rank+length] + for i := range single { + single[i] = d + } + *rank += length + } + + return s, in, nil +} + +// Decompress1X will decompress a 1X encoded stream. +// The length of the supplied input must match the end of a block exactly. +// Before this is called, the table must be initialized with ReadTable unless +// the encoder re-used the table. +// deprecated: Use the stateless Decoder() to get a concurrent version. +func (s *Scratch) Decompress1X(in []byte) (out []byte, err error) { + if cap(s.Out) < s.MaxDecodedSize { + s.Out = make([]byte, s.MaxDecodedSize) + } + s.Out = s.Out[:0:s.MaxDecodedSize] + s.Out, err = s.Decoder().Decompress1X(s.Out, in) + return s.Out, err +} + +// Decompress4X will decompress a 4X encoded stream. +// Before this is called, the table must be initialized with ReadTable unless +// the encoder re-used the table. +// The length of the supplied input must match the end of a block exactly. +// The destination size of the uncompressed data must be known and provided. +// deprecated: Use the stateless Decoder() to get a concurrent version. +func (s *Scratch) Decompress4X(in []byte, dstSize int) (out []byte, err error) { + if dstSize > s.MaxDecodedSize { + return nil, ErrMaxDecodedSizeExceeded + } + if cap(s.Out) < dstSize { + s.Out = make([]byte, s.MaxDecodedSize) + } + s.Out = s.Out[:0:dstSize] + s.Out, err = s.Decoder().Decompress4X(s.Out, in) + return s.Out, err +} + +// Decoder will return a stateless decoder that can be used by multiple +// decompressors concurrently. +// Before this is called, the table must be initialized with ReadTable. +// The Decoder is still linked to the scratch buffer so that cannot be reused. +// However, it is safe to discard the scratch. +func (s *Scratch) Decoder() *Decoder { + return &Decoder{ + dt: s.dt, + actualTableLog: s.actualTableLog, + bufs: &s.decPool, + } +} + +// Decoder provides stateless decoding. +type Decoder struct { + dt dTable + actualTableLog uint8 + bufs *sync.Pool +} + +func (d *Decoder) buffer() *[4][256]byte { + buf, ok := d.bufs.Get().(*[4][256]byte) + if ok { + return buf + } + return &[4][256]byte{} +} + +// decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. +// The cap of the output buffer will be the maximum decompressed size. +// The length of the supplied input must match the end of a block exactly. +func (d *Decoder) decompress1X8Bit(dst, src []byte) ([]byte, error) { + if d.actualTableLog == 8 { + return d.decompress1X8BitExactly(dst, src) + } + var br bitReaderBytes + err := br.init(src) + if err != nil { + return dst, err + } + maxDecodedSize := cap(dst) + dst = dst[:0] + + // Avoid bounds check by always having full sized table. + dt := d.dt.single[:256] + + // Use temp table to avoid bound checks/append penalty. + bufs := d.buffer() + buf := &bufs[0] + var off uint8 + + switch d.actualTableLog { + case 8: + const shift = 0 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + br.close() + d.bufs.Put(bufs) + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + case 7: + const shift = 8 - 7 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + br.close() + d.bufs.Put(bufs) + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + case 6: + const shift = 8 - 6 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + case 5: + const shift = 8 - 5 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + case 4: + const shift = 8 - 4 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + case 3: + const shift = 8 - 3 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + case 2: + const shift = 8 - 2 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + case 1: + const shift = 8 - 1 + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>(56+shift))] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + default: + d.bufs.Put(bufs) + return nil, fmt.Errorf("invalid tablelog: %d", d.actualTableLog) + } + + if len(dst)+int(off) > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:off]...) + + // br < 4, so uint8 is fine + bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) + shift := (8 - d.actualTableLog) & 7 + + for bitsLeft > 0 { + if br.bitsRead >= 64-8 { + for br.off > 0 { + br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) + br.bitsRead -= 8 + br.off-- + } + } + if len(dst) >= maxDecodedSize { + br.close() + d.bufs.Put(bufs) + return nil, ErrMaxDecodedSizeExceeded + } + v := dt[br.peekByteFast()>>shift] + nBits := uint8(v.entry) + br.advance(nBits) + bitsLeft -= int8(nBits) + dst = append(dst, uint8(v.entry>>8)) + } + d.bufs.Put(bufs) + return dst, br.close() +} + +// decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. +// The cap of the output buffer will be the maximum decompressed size. +// The length of the supplied input must match the end of a block exactly. +func (d *Decoder) decompress1X8BitExactly(dst, src []byte) ([]byte, error) { + var br bitReaderBytes + err := br.init(src) + if err != nil { + return dst, err + } + maxDecodedSize := cap(dst) + dst = dst[:0] + + // Avoid bounds check by always having full sized table. + dt := d.dt.single[:256] + + // Use temp table to avoid bound checks/append penalty. + bufs := d.buffer() + buf := &bufs[0] + var off uint8 + + const shift = 56 + + //fmt.Printf("mask: %b, tl:%d\n", mask, d.actualTableLog) + for br.off >= 4 { + br.fillFast() + v := dt[uint8(br.value>>shift)] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>shift)] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>shift)] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[uint8(br.value>>shift)] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + + if len(dst)+int(off) > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:off]...) + + // br < 4, so uint8 is fine + bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) + for bitsLeft > 0 { + if br.bitsRead >= 64-8 { + for br.off > 0 { + br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) + br.bitsRead -= 8 + br.off-- + } + } + if len(dst) >= maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + v := dt[br.peekByteFast()] + nBits := uint8(v.entry) + br.advance(nBits) + bitsLeft -= int8(nBits) + dst = append(dst, uint8(v.entry>>8)) + } + d.bufs.Put(bufs) + return dst, br.close() +} + +// Decompress4X will decompress a 4X encoded stream. +// The length of the supplied input must match the end of a block exactly. +// The *capacity* of the dst slice must match the destination size of +// the uncompressed data exactly. +func (d *Decoder) decompress4X8bit(dst, src []byte) ([]byte, error) { + if d.actualTableLog == 8 { + return d.decompress4X8bitExactly(dst, src) + } + + var br [4]bitReaderBytes + start := 6 + for i := 0; i < 3; i++ { + length := int(src[i*2]) | (int(src[i*2+1]) << 8) + if start+length >= len(src) { + return nil, errors.New("truncated input (or invalid offset)") + } + err := br[i].init(src[start : start+length]) + if err != nil { + return nil, err + } + start += length + } + err := br[3].init(src[start:]) + if err != nil { + return nil, err + } + + // destination, offset to match first output + dstSize := cap(dst) + dst = dst[:dstSize] + out := dst + dstEvery := (dstSize + 3) / 4 + + shift := (56 + (8 - d.actualTableLog)) & 63 + + const tlSize = 1 << 8 + single := d.dt.single[:tlSize] + + // Use temp table to avoid bound checks/append penalty. + buf := d.buffer() + var off uint8 + var decoded int + + // Decode 4 values from each decoder/loop. + const bufoff = 256 + for { + if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { + break + } + + { + // Interleave 2 decodes. + const stream = 0 + const stream2 = 1 + br1 := &br[stream] + br2 := &br[stream2] + br1.fillFast() + br2.fillFast() + + v := single[uint8(br1.value>>shift)].entry + v2 := single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off] = uint8(v >> 8) + buf[stream2][off] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+1] = uint8(v >> 8) + buf[stream2][off+1] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+2] = uint8(v >> 8) + buf[stream2][off+2] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+3] = uint8(v >> 8) + buf[stream2][off+3] = uint8(v2 >> 8) + } + + { + const stream = 2 + const stream2 = 3 + br1 := &br[stream] + br2 := &br[stream2] + br1.fillFast() + br2.fillFast() + + v := single[uint8(br1.value>>shift)].entry + v2 := single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off] = uint8(v >> 8) + buf[stream2][off] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+1] = uint8(v >> 8) + buf[stream2][off+1] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+2] = uint8(v >> 8) + buf[stream2][off+2] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+3] = uint8(v >> 8) + buf[stream2][off+3] = uint8(v2 >> 8) + } + + off += 4 + + if off == 0 { + if bufoff > dstEvery { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 1") + } + // There must at least be 3 buffers left. + if len(out)-bufoff < dstEvery*3 { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 2") + } + //copy(out, buf[0][:]) + //copy(out[dstEvery:], buf[1][:]) + //copy(out[dstEvery*2:], buf[2][:]) + *(*[bufoff]byte)(out) = buf[0] + *(*[bufoff]byte)(out[dstEvery:]) = buf[1] + *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] + *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] + out = out[bufoff:] + decoded += bufoff * 4 + } + } + if off > 0 { + ioff := int(off) + if len(out) < dstEvery*3+ioff { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 3") + } + copy(out, buf[0][:off]) + copy(out[dstEvery:], buf[1][:off]) + copy(out[dstEvery*2:], buf[2][:off]) + copy(out[dstEvery*3:], buf[3][:off]) + decoded += int(off) * 4 + out = out[off:] + } + + // Decode remaining. + // Decode remaining. + remainBytes := dstEvery - (decoded / 4) + for i := range br { + offset := dstEvery * i + endsAt := offset + remainBytes + if endsAt > len(out) { + endsAt = len(out) + } + br := &br[i] + bitsLeft := br.remaining() + for bitsLeft > 0 { + if br.finished() { + d.bufs.Put(buf) + return nil, io.ErrUnexpectedEOF + } + if br.bitsRead >= 56 { + if br.off >= 4 { + v := br.in[br.off-4:] + v = v[:4] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + br.value |= uint64(low) << (br.bitsRead - 32) + br.bitsRead -= 32 + br.off -= 4 + } else { + for br.off > 0 { + br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) + br.bitsRead -= 8 + br.off-- + } + } + } + // end inline... + if offset >= endsAt { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 4") + } + + // Read value and increment offset. + v := single[uint8(br.value>>shift)].entry + nBits := uint8(v) + br.advance(nBits) + bitsLeft -= uint(nBits) + out[offset] = uint8(v >> 8) + offset++ + } + if offset != endsAt { + d.bufs.Put(buf) + return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) + } + decoded += offset - dstEvery*i + err = br.close() + if err != nil { + d.bufs.Put(buf) + return nil, err + } + } + d.bufs.Put(buf) + if dstSize != decoded { + return nil, errors.New("corruption detected: short output block") + } + return dst, nil +} + +// Decompress4X will decompress a 4X encoded stream. +// The length of the supplied input must match the end of a block exactly. +// The *capacity* of the dst slice must match the destination size of +// the uncompressed data exactly. +func (d *Decoder) decompress4X8bitExactly(dst, src []byte) ([]byte, error) { + var br [4]bitReaderBytes + start := 6 + for i := 0; i < 3; i++ { + length := int(src[i*2]) | (int(src[i*2+1]) << 8) + if start+length >= len(src) { + return nil, errors.New("truncated input (or invalid offset)") + } + err := br[i].init(src[start : start+length]) + if err != nil { + return nil, err + } + start += length + } + err := br[3].init(src[start:]) + if err != nil { + return nil, err + } + + // destination, offset to match first output + dstSize := cap(dst) + dst = dst[:dstSize] + out := dst + dstEvery := (dstSize + 3) / 4 + + const shift = 56 + const tlSize = 1 << 8 + single := d.dt.single[:tlSize] + + // Use temp table to avoid bound checks/append penalty. + buf := d.buffer() + var off uint8 + var decoded int + + // Decode 4 values from each decoder/loop. + const bufoff = 256 + for { + if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { + break + } + + { + // Interleave 2 decodes. + const stream = 0 + const stream2 = 1 + br1 := &br[stream] + br2 := &br[stream2] + br1.fillFast() + br2.fillFast() + + v := single[uint8(br1.value>>shift)].entry + v2 := single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off] = uint8(v >> 8) + buf[stream2][off] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+1] = uint8(v >> 8) + buf[stream2][off+1] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+2] = uint8(v >> 8) + buf[stream2][off+2] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+3] = uint8(v >> 8) + buf[stream2][off+3] = uint8(v2 >> 8) + } + + { + const stream = 2 + const stream2 = 3 + br1 := &br[stream] + br2 := &br[stream2] + br1.fillFast() + br2.fillFast() + + v := single[uint8(br1.value>>shift)].entry + v2 := single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off] = uint8(v >> 8) + buf[stream2][off] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+1] = uint8(v >> 8) + buf[stream2][off+1] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+2] = uint8(v >> 8) + buf[stream2][off+2] = uint8(v2 >> 8) + + v = single[uint8(br1.value>>shift)].entry + v2 = single[uint8(br2.value>>shift)].entry + br1.bitsRead += uint8(v) + br1.value <<= v & 63 + br2.bitsRead += uint8(v2) + br2.value <<= v2 & 63 + buf[stream][off+3] = uint8(v >> 8) + buf[stream2][off+3] = uint8(v2 >> 8) + } + + off += 4 + + if off == 0 { + if bufoff > dstEvery { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 1") + } + // There must at least be 3 buffers left. + if len(out)-bufoff < dstEvery*3 { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 2") + } + + //copy(out, buf[0][:]) + //copy(out[dstEvery:], buf[1][:]) + //copy(out[dstEvery*2:], buf[2][:]) + // copy(out[dstEvery*3:], buf[3][:]) + *(*[bufoff]byte)(out) = buf[0] + *(*[bufoff]byte)(out[dstEvery:]) = buf[1] + *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] + *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] + out = out[bufoff:] + decoded += bufoff * 4 + } + } + if off > 0 { + ioff := int(off) + if len(out) < dstEvery*3+ioff { + return nil, errors.New("corruption detected: stream overrun 3") + } + copy(out, buf[0][:off]) + copy(out[dstEvery:], buf[1][:off]) + copy(out[dstEvery*2:], buf[2][:off]) + copy(out[dstEvery*3:], buf[3][:off]) + decoded += int(off) * 4 + out = out[off:] + } + + // Decode remaining. + remainBytes := dstEvery - (decoded / 4) + for i := range br { + offset := dstEvery * i + endsAt := offset + remainBytes + if endsAt > len(out) { + endsAt = len(out) + } + br := &br[i] + bitsLeft := br.remaining() + for bitsLeft > 0 { + if br.finished() { + d.bufs.Put(buf) + return nil, io.ErrUnexpectedEOF + } + if br.bitsRead >= 56 { + if br.off >= 4 { + v := br.in[br.off-4:] + v = v[:4] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + br.value |= uint64(low) << (br.bitsRead - 32) + br.bitsRead -= 32 + br.off -= 4 + } else { + for br.off > 0 { + br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) + br.bitsRead -= 8 + br.off-- + } + } + } + // end inline... + if offset >= endsAt { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 4") + } + + // Read value and increment offset. + v := single[br.peekByteFast()].entry + nBits := uint8(v) + br.advance(nBits) + bitsLeft -= uint(nBits) + out[offset] = uint8(v >> 8) + offset++ + } + if offset != endsAt { + d.bufs.Put(buf) + return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) + } + + decoded += offset - dstEvery*i + err = br.close() + if err != nil { + d.bufs.Put(buf) + return nil, err + } + } + d.bufs.Put(buf) + if dstSize != decoded { + return nil, errors.New("corruption detected: short output block") + } + return dst, nil +} + +// matches will compare a decoding table to a coding table. +// Errors are written to the writer. +// Nothing will be written if table is ok. +func (s *Scratch) matches(ct cTable, w io.Writer) { + if s == nil || len(s.dt.single) == 0 { + return + } + dt := s.dt.single[:1<>8) == byte(sym) { + fmt.Fprintf(w, "symbol %x has decoder, but no encoder\n", sym) + errs++ + break + } + } + if errs == 0 { + broken-- + } + continue + } + // Unused bits in input + ub := tablelog - enc.nBits + top := enc.val << ub + // decoder looks at top bits. + dec := dt[top] + if uint8(dec.entry) != enc.nBits { + fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", sym, enc.nBits, uint8(dec.entry)) + errs++ + } + if uint8(dec.entry>>8) != uint8(sym) { + fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", sym, sym, uint8(dec.entry>>8)) + errs++ + } + if errs > 0 { + fmt.Fprintf(w, "%d errros in base, stopping\n", errs) + continue + } + // Ensure that all combinations are covered. + for i := uint16(0); i < (1 << ub); i++ { + vval := top | i + dec := dt[vval] + if uint8(dec.entry) != enc.nBits { + fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", vval, enc.nBits, uint8(dec.entry)) + errs++ + } + if uint8(dec.entry>>8) != uint8(sym) { + fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", vval, sym, uint8(dec.entry>>8)) + errs++ + } + if errs > 20 { + fmt.Fprintf(w, "%d errros, stopping\n", errs) + break + } + } + if errs == 0 { + ok++ + broken-- + } + } + if broken > 0 { + fmt.Fprintf(w, "%d broken, %d ok\n", broken, ok) + } +} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go new file mode 100644 index 000000000..ba7e8e6b0 --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go @@ -0,0 +1,226 @@ +//go:build amd64 && !appengine && !noasm && gc +// +build amd64,!appengine,!noasm,gc + +// This file contains the specialisation of Decoder.Decompress4X +// and Decoder.Decompress1X that use an asm implementation of thir main loops. +package huff0 + +import ( + "errors" + "fmt" + + "github.com/klauspost/compress/internal/cpuinfo" +) + +// decompress4x_main_loop_x86 is an x86 assembler implementation +// of Decompress4X when tablelog > 8. +// +//go:noescape +func decompress4x_main_loop_amd64(ctx *decompress4xContext) + +// decompress4x_8b_loop_x86 is an x86 assembler implementation +// of Decompress4X when tablelog <= 8 which decodes 4 entries +// per loop. +// +//go:noescape +func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) + +// fallback8BitSize is the size where using Go version is faster. +const fallback8BitSize = 800 + +type decompress4xContext struct { + pbr *[4]bitReaderShifted + peekBits uint8 + out *byte + dstEvery int + tbl *dEntrySingle + decoded int + limit *byte +} + +// Decompress4X will decompress a 4X encoded stream. +// The length of the supplied input must match the end of a block exactly. +// The *capacity* of the dst slice must match the destination size of +// the uncompressed data exactly. +func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { + if len(d.dt.single) == 0 { + return nil, errors.New("no table loaded") + } + if len(src) < 6+(4*1) { + return nil, errors.New("input too small") + } + + use8BitTables := d.actualTableLog <= 8 + if cap(dst) < fallback8BitSize && use8BitTables { + return d.decompress4X8bit(dst, src) + } + + var br [4]bitReaderShifted + // Decode "jump table" + start := 6 + for i := 0; i < 3; i++ { + length := int(src[i*2]) | (int(src[i*2+1]) << 8) + if start+length >= len(src) { + return nil, errors.New("truncated input (or invalid offset)") + } + err := br[i].init(src[start : start+length]) + if err != nil { + return nil, err + } + start += length + } + err := br[3].init(src[start:]) + if err != nil { + return nil, err + } + + // destination, offset to match first output + dstSize := cap(dst) + dst = dst[:dstSize] + out := dst + dstEvery := (dstSize + 3) / 4 + + const tlSize = 1 << tableLogMax + const tlMask = tlSize - 1 + single := d.dt.single[:tlSize] + + var decoded int + + if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) { + ctx := decompress4xContext{ + pbr: &br, + peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() + out: &out[0], + dstEvery: dstEvery, + tbl: &single[0], + limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last. + } + if use8BitTables { + decompress4x_8b_main_loop_amd64(&ctx) + } else { + decompress4x_main_loop_amd64(&ctx) + } + + decoded = ctx.decoded + out = out[decoded/4:] + } + + // Decode remaining. + remainBytes := dstEvery - (decoded / 4) + for i := range br { + offset := dstEvery * i + endsAt := offset + remainBytes + if endsAt > len(out) { + endsAt = len(out) + } + br := &br[i] + bitsLeft := br.remaining() + for bitsLeft > 0 { + br.fill() + if offset >= endsAt { + return nil, errors.New("corruption detected: stream overrun 4") + } + + // Read value and increment offset. + val := br.peekBitsFast(d.actualTableLog) + v := single[val&tlMask].entry + nBits := uint8(v) + br.advance(nBits) + bitsLeft -= uint(nBits) + out[offset] = uint8(v >> 8) + offset++ + } + if offset != endsAt { + return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) + } + decoded += offset - dstEvery*i + err = br.close() + if err != nil { + return nil, err + } + } + if dstSize != decoded { + return nil, errors.New("corruption detected: short output block") + } + return dst, nil +} + +// decompress4x_main_loop_x86 is an x86 assembler implementation +// of Decompress1X when tablelog > 8. +// +//go:noescape +func decompress1x_main_loop_amd64(ctx *decompress1xContext) + +// decompress4x_main_loop_x86 is an x86 with BMI2 assembler implementation +// of Decompress1X when tablelog > 8. +// +//go:noescape +func decompress1x_main_loop_bmi2(ctx *decompress1xContext) + +type decompress1xContext struct { + pbr *bitReaderShifted + peekBits uint8 + out *byte + outCap int + tbl *dEntrySingle + decoded int +} + +// Error reported by asm implementations +const error_max_decoded_size_exeeded = -1 + +// Decompress1X will decompress a 1X encoded stream. +// The cap of the output buffer will be the maximum decompressed size. +// The length of the supplied input must match the end of a block exactly. +func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { + if len(d.dt.single) == 0 { + return nil, errors.New("no table loaded") + } + var br bitReaderShifted + err := br.init(src) + if err != nil { + return dst, err + } + maxDecodedSize := cap(dst) + dst = dst[:maxDecodedSize] + + const tlSize = 1 << tableLogMax + const tlMask = tlSize - 1 + + if maxDecodedSize >= 4 { + ctx := decompress1xContext{ + pbr: &br, + out: &dst[0], + outCap: maxDecodedSize, + peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() + tbl: &d.dt.single[0], + } + + if cpuinfo.HasBMI2() { + decompress1x_main_loop_bmi2(&ctx) + } else { + decompress1x_main_loop_amd64(&ctx) + } + if ctx.decoded == error_max_decoded_size_exeeded { + return nil, ErrMaxDecodedSizeExceeded + } + + dst = dst[:ctx.decoded] + } + + // br < 8, so uint8 is fine + bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead + for bitsLeft > 0 { + br.fill() + if len(dst) >= maxDecodedSize { + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] + nBits := uint8(v.entry) + br.advance(nBits) + bitsLeft -= nBits + dst = append(dst, uint8(v.entry>>8)) + } + return dst, br.close() +} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s new file mode 100644 index 000000000..c4c7ab2d1 --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s @@ -0,0 +1,830 @@ +// Code generated by command: go run gen.go -out ../decompress_amd64.s -pkg=huff0. DO NOT EDIT. + +//go:build amd64 && !appengine && !noasm && gc + +// func decompress4x_main_loop_amd64(ctx *decompress4xContext) +TEXT ·decompress4x_main_loop_amd64(SB), $0-8 + // Preload values + MOVQ ctx+0(FP), AX + MOVBQZX 8(AX), DI + MOVQ 16(AX), BX + MOVQ 48(AX), SI + MOVQ 24(AX), R8 + MOVQ 32(AX), R9 + MOVQ (AX), R10 + + // Main loop +main_loop: + XORL DX, DX + CMPQ BX, SI + SETGE DL + + // br0.fillFast32() + MOVQ 32(R10), R11 + MOVBQZX 40(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill0 + MOVQ 24(R10), AX + SUBQ $0x20, R12 + SUBQ $0x04, AX + MOVQ (R10), R13 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (AX)(R13*1), R13 + MOVQ R12, CX + SHLQ CL, R13 + MOVQ AX, 24(R10) + ORQ R13, R11 + + // exhausted += (br0.off < 4) + CMPQ AX, $0x04 + ADCB $+0, DL + +skip_fill0: + // val0 := br0.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br0.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br0.peekTopBits(peekBits) + MOVQ DI, CX + MOVQ R11, R13 + SHRQ CL, R13 + + // v1 := table[val1&mask] + MOVW (R9)(R13*2), CX + + // br0.advance(uint8(v1.entry)) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // these two writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + MOVW AX, (BX) + + // update the bitreader structure + MOVQ R11, 32(R10) + MOVB R12, 40(R10) + + // br1.fillFast32() + MOVQ 80(R10), R11 + MOVBQZX 88(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill1 + MOVQ 72(R10), AX + SUBQ $0x20, R12 + SUBQ $0x04, AX + MOVQ 48(R10), R13 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (AX)(R13*1), R13 + MOVQ R12, CX + SHLQ CL, R13 + MOVQ AX, 72(R10) + ORQ R13, R11 + + // exhausted += (br1.off < 4) + CMPQ AX, $0x04 + ADCB $+0, DL + +skip_fill1: + // val0 := br1.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br1.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br1.peekTopBits(peekBits) + MOVQ DI, CX + MOVQ R11, R13 + SHRQ CL, R13 + + // v1 := table[val1&mask] + MOVW (R9)(R13*2), CX + + // br1.advance(uint8(v1.entry)) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // these two writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + MOVW AX, (BX)(R8*1) + + // update the bitreader structure + MOVQ R11, 80(R10) + MOVB R12, 88(R10) + + // br2.fillFast32() + MOVQ 128(R10), R11 + MOVBQZX 136(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill2 + MOVQ 120(R10), AX + SUBQ $0x20, R12 + SUBQ $0x04, AX + MOVQ 96(R10), R13 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (AX)(R13*1), R13 + MOVQ R12, CX + SHLQ CL, R13 + MOVQ AX, 120(R10) + ORQ R13, R11 + + // exhausted += (br2.off < 4) + CMPQ AX, $0x04 + ADCB $+0, DL + +skip_fill2: + // val0 := br2.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br2.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br2.peekTopBits(peekBits) + MOVQ DI, CX + MOVQ R11, R13 + SHRQ CL, R13 + + // v1 := table[val1&mask] + MOVW (R9)(R13*2), CX + + // br2.advance(uint8(v1.entry)) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // these two writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + MOVW AX, (BX)(R8*2) + + // update the bitreader structure + MOVQ R11, 128(R10) + MOVB R12, 136(R10) + + // br3.fillFast32() + MOVQ 176(R10), R11 + MOVBQZX 184(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill3 + MOVQ 168(R10), AX + SUBQ $0x20, R12 + SUBQ $0x04, AX + MOVQ 144(R10), R13 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (AX)(R13*1), R13 + MOVQ R12, CX + SHLQ CL, R13 + MOVQ AX, 168(R10) + ORQ R13, R11 + + // exhausted += (br3.off < 4) + CMPQ AX, $0x04 + ADCB $+0, DL + +skip_fill3: + // val0 := br3.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br3.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br3.peekTopBits(peekBits) + MOVQ DI, CX + MOVQ R11, R13 + SHRQ CL, R13 + + // v1 := table[val1&mask] + MOVW (R9)(R13*2), CX + + // br3.advance(uint8(v1.entry)) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // these two writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + LEAQ (R8)(R8*2), CX + MOVW AX, (BX)(CX*1) + + // update the bitreader structure + MOVQ R11, 176(R10) + MOVB R12, 184(R10) + ADDQ $0x02, BX + TESTB DL, DL + JZ main_loop + MOVQ ctx+0(FP), AX + SUBQ 16(AX), BX + SHLQ $0x02, BX + MOVQ BX, 40(AX) + RET + +// func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) +TEXT ·decompress4x_8b_main_loop_amd64(SB), $0-8 + // Preload values + MOVQ ctx+0(FP), CX + MOVBQZX 8(CX), DI + MOVQ 16(CX), BX + MOVQ 48(CX), SI + MOVQ 24(CX), R8 + MOVQ 32(CX), R9 + MOVQ (CX), R10 + + // Main loop +main_loop: + XORL DX, DX + CMPQ BX, SI + SETGE DL + + // br0.fillFast32() + MOVQ 32(R10), R11 + MOVBQZX 40(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill0 + MOVQ 24(R10), R13 + SUBQ $0x20, R12 + SUBQ $0x04, R13 + MOVQ (R10), R14 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (R13)(R14*1), R14 + MOVQ R12, CX + SHLQ CL, R14 + MOVQ R13, 24(R10) + ORQ R14, R11 + + // exhausted += (br0.off < 4) + CMPQ R13, $0x04 + ADCB $+0, DL + +skip_fill0: + // val0 := br0.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br0.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br0.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v1 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br0.advance(uint8(v1.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // val2 := br0.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v2 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br0.advance(uint8(v2.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // val3 := br0.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v3 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br0.advance(uint8(v3.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // these four writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + // out[id * dstEvery + 3] = uint8(v2.entry >> 8) + // out[id * dstEvery + 4] = uint8(v3.entry >> 8) + MOVL AX, (BX) + + // update the bitreader structure + MOVQ R11, 32(R10) + MOVB R12, 40(R10) + + // br1.fillFast32() + MOVQ 80(R10), R11 + MOVBQZX 88(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill1 + MOVQ 72(R10), R13 + SUBQ $0x20, R12 + SUBQ $0x04, R13 + MOVQ 48(R10), R14 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (R13)(R14*1), R14 + MOVQ R12, CX + SHLQ CL, R14 + MOVQ R13, 72(R10) + ORQ R14, R11 + + // exhausted += (br1.off < 4) + CMPQ R13, $0x04 + ADCB $+0, DL + +skip_fill1: + // val0 := br1.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br1.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br1.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v1 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br1.advance(uint8(v1.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // val2 := br1.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v2 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br1.advance(uint8(v2.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // val3 := br1.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v3 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br1.advance(uint8(v3.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // these four writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + // out[id * dstEvery + 3] = uint8(v2.entry >> 8) + // out[id * dstEvery + 4] = uint8(v3.entry >> 8) + MOVL AX, (BX)(R8*1) + + // update the bitreader structure + MOVQ R11, 80(R10) + MOVB R12, 88(R10) + + // br2.fillFast32() + MOVQ 128(R10), R11 + MOVBQZX 136(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill2 + MOVQ 120(R10), R13 + SUBQ $0x20, R12 + SUBQ $0x04, R13 + MOVQ 96(R10), R14 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (R13)(R14*1), R14 + MOVQ R12, CX + SHLQ CL, R14 + MOVQ R13, 120(R10) + ORQ R14, R11 + + // exhausted += (br2.off < 4) + CMPQ R13, $0x04 + ADCB $+0, DL + +skip_fill2: + // val0 := br2.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br2.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br2.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v1 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br2.advance(uint8(v1.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // val2 := br2.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v2 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br2.advance(uint8(v2.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // val3 := br2.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v3 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br2.advance(uint8(v3.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // these four writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + // out[id * dstEvery + 3] = uint8(v2.entry >> 8) + // out[id * dstEvery + 4] = uint8(v3.entry >> 8) + MOVL AX, (BX)(R8*2) + + // update the bitreader structure + MOVQ R11, 128(R10) + MOVB R12, 136(R10) + + // br3.fillFast32() + MOVQ 176(R10), R11 + MOVBQZX 184(R10), R12 + CMPQ R12, $0x20 + JBE skip_fill3 + MOVQ 168(R10), R13 + SUBQ $0x20, R12 + SUBQ $0x04, R13 + MOVQ 144(R10), R14 + + // b.value |= uint64(low) << (b.bitsRead & 63) + MOVL (R13)(R14*1), R14 + MOVQ R12, CX + SHLQ CL, R14 + MOVQ R13, 168(R10) + ORQ R14, R11 + + // exhausted += (br3.off < 4) + CMPQ R13, $0x04 + ADCB $+0, DL + +skip_fill3: + // val0 := br3.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v0 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br3.advance(uint8(v0.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + + // val1 := br3.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v1 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br3.advance(uint8(v1.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // val2 := br3.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v2 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br3.advance(uint8(v2.entry) + MOVB CH, AH + SHLQ CL, R11 + ADDB CL, R12 + + // val3 := br3.peekTopBits(peekBits) + MOVQ R11, R13 + MOVQ DI, CX + SHRQ CL, R13 + + // v3 := table[val0&mask] + MOVW (R9)(R13*2), CX + + // br3.advance(uint8(v3.entry) + MOVB CH, AL + SHLQ CL, R11 + ADDB CL, R12 + BSWAPL AX + + // these four writes get coalesced + // out[id * dstEvery + 0] = uint8(v0.entry >> 8) + // out[id * dstEvery + 1] = uint8(v1.entry >> 8) + // out[id * dstEvery + 3] = uint8(v2.entry >> 8) + // out[id * dstEvery + 4] = uint8(v3.entry >> 8) + LEAQ (R8)(R8*2), CX + MOVL AX, (BX)(CX*1) + + // update the bitreader structure + MOVQ R11, 176(R10) + MOVB R12, 184(R10) + ADDQ $0x04, BX + TESTB DL, DL + JZ main_loop + MOVQ ctx+0(FP), AX + SUBQ 16(AX), BX + SHLQ $0x02, BX + MOVQ BX, 40(AX) + RET + +// func decompress1x_main_loop_amd64(ctx *decompress1xContext) +TEXT ·decompress1x_main_loop_amd64(SB), $0-8 + MOVQ ctx+0(FP), CX + MOVQ 16(CX), DX + MOVQ 24(CX), BX + CMPQ BX, $0x04 + JB error_max_decoded_size_exceeded + LEAQ (DX)(BX*1), BX + MOVQ (CX), SI + MOVQ (SI), R8 + MOVQ 24(SI), R9 + MOVQ 32(SI), R10 + MOVBQZX 40(SI), R11 + MOVQ 32(CX), SI + MOVBQZX 8(CX), DI + JMP loop_condition + +main_loop: + // Check if we have room for 4 bytes in the output buffer + LEAQ 4(DX), CX + CMPQ CX, BX + JGE error_max_decoded_size_exceeded + + // Decode 4 values + CMPQ R11, $0x20 + JL bitReader_fillFast_1_end + SUBQ $0x20, R11 + SUBQ $0x04, R9 + MOVL (R8)(R9*1), R12 + MOVQ R11, CX + SHLQ CL, R12 + ORQ R12, R10 + +bitReader_fillFast_1_end: + MOVQ DI, CX + MOVQ R10, R12 + SHRQ CL, R12 + MOVW (SI)(R12*2), CX + MOVB CH, AL + MOVBQZX CL, CX + ADDQ CX, R11 + SHLQ CL, R10 + MOVQ DI, CX + MOVQ R10, R12 + SHRQ CL, R12 + MOVW (SI)(R12*2), CX + MOVB CH, AH + MOVBQZX CL, CX + ADDQ CX, R11 + SHLQ CL, R10 + BSWAPL AX + CMPQ R11, $0x20 + JL bitReader_fillFast_2_end + SUBQ $0x20, R11 + SUBQ $0x04, R9 + MOVL (R8)(R9*1), R12 + MOVQ R11, CX + SHLQ CL, R12 + ORQ R12, R10 + +bitReader_fillFast_2_end: + MOVQ DI, CX + MOVQ R10, R12 + SHRQ CL, R12 + MOVW (SI)(R12*2), CX + MOVB CH, AH + MOVBQZX CL, CX + ADDQ CX, R11 + SHLQ CL, R10 + MOVQ DI, CX + MOVQ R10, R12 + SHRQ CL, R12 + MOVW (SI)(R12*2), CX + MOVB CH, AL + MOVBQZX CL, CX + ADDQ CX, R11 + SHLQ CL, R10 + BSWAPL AX + + // Store the decoded values + MOVL AX, (DX) + ADDQ $0x04, DX + +loop_condition: + CMPQ R9, $0x08 + JGE main_loop + + // Update ctx structure + MOVQ ctx+0(FP), AX + SUBQ 16(AX), DX + MOVQ DX, 40(AX) + MOVQ (AX), AX + MOVQ R9, 24(AX) + MOVQ R10, 32(AX) + MOVB R11, 40(AX) + RET + + // Report error +error_max_decoded_size_exceeded: + MOVQ ctx+0(FP), AX + MOVQ $-1, CX + MOVQ CX, 40(AX) + RET + +// func decompress1x_main_loop_bmi2(ctx *decompress1xContext) +// Requires: BMI2 +TEXT ·decompress1x_main_loop_bmi2(SB), $0-8 + MOVQ ctx+0(FP), CX + MOVQ 16(CX), DX + MOVQ 24(CX), BX + CMPQ BX, $0x04 + JB error_max_decoded_size_exceeded + LEAQ (DX)(BX*1), BX + MOVQ (CX), SI + MOVQ (SI), R8 + MOVQ 24(SI), R9 + MOVQ 32(SI), R10 + MOVBQZX 40(SI), R11 + MOVQ 32(CX), SI + MOVBQZX 8(CX), DI + JMP loop_condition + +main_loop: + // Check if we have room for 4 bytes in the output buffer + LEAQ 4(DX), CX + CMPQ CX, BX + JGE error_max_decoded_size_exceeded + + // Decode 4 values + CMPQ R11, $0x20 + JL bitReader_fillFast_1_end + SUBQ $0x20, R11 + SUBQ $0x04, R9 + MOVL (R8)(R9*1), CX + SHLXQ R11, CX, CX + ORQ CX, R10 + +bitReader_fillFast_1_end: + SHRXQ DI, R10, CX + MOVW (SI)(CX*2), CX + MOVB CH, AL + MOVBQZX CL, CX + ADDQ CX, R11 + SHLXQ CX, R10, R10 + SHRXQ DI, R10, CX + MOVW (SI)(CX*2), CX + MOVB CH, AH + MOVBQZX CL, CX + ADDQ CX, R11 + SHLXQ CX, R10, R10 + BSWAPL AX + CMPQ R11, $0x20 + JL bitReader_fillFast_2_end + SUBQ $0x20, R11 + SUBQ $0x04, R9 + MOVL (R8)(R9*1), CX + SHLXQ R11, CX, CX + ORQ CX, R10 + +bitReader_fillFast_2_end: + SHRXQ DI, R10, CX + MOVW (SI)(CX*2), CX + MOVB CH, AH + MOVBQZX CL, CX + ADDQ CX, R11 + SHLXQ CX, R10, R10 + SHRXQ DI, R10, CX + MOVW (SI)(CX*2), CX + MOVB CH, AL + MOVBQZX CL, CX + ADDQ CX, R11 + SHLXQ CX, R10, R10 + BSWAPL AX + + // Store the decoded values + MOVL AX, (DX) + ADDQ $0x04, DX + +loop_condition: + CMPQ R9, $0x08 + JGE main_loop + + // Update ctx structure + MOVQ ctx+0(FP), AX + SUBQ 16(AX), DX + MOVQ DX, 40(AX) + MOVQ (AX), AX + MOVQ R9, 24(AX) + MOVQ R10, 32(AX) + MOVB R11, 40(AX) + RET + + // Report error +error_max_decoded_size_exceeded: + MOVQ ctx+0(FP), AX + MOVQ $-1, CX + MOVQ CX, 40(AX) + RET diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go new file mode 100644 index 000000000..908c17de6 --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go @@ -0,0 +1,299 @@ +//go:build !amd64 || appengine || !gc || noasm +// +build !amd64 appengine !gc noasm + +// This file contains a generic implementation of Decoder.Decompress4X. +package huff0 + +import ( + "errors" + "fmt" +) + +// Decompress4X will decompress a 4X encoded stream. +// The length of the supplied input must match the end of a block exactly. +// The *capacity* of the dst slice must match the destination size of +// the uncompressed data exactly. +func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { + if len(d.dt.single) == 0 { + return nil, errors.New("no table loaded") + } + if len(src) < 6+(4*1) { + return nil, errors.New("input too small") + } + if use8BitTables && d.actualTableLog <= 8 { + return d.decompress4X8bit(dst, src) + } + + var br [4]bitReaderShifted + // Decode "jump table" + start := 6 + for i := 0; i < 3; i++ { + length := int(src[i*2]) | (int(src[i*2+1]) << 8) + if start+length >= len(src) { + return nil, errors.New("truncated input (or invalid offset)") + } + err := br[i].init(src[start : start+length]) + if err != nil { + return nil, err + } + start += length + } + err := br[3].init(src[start:]) + if err != nil { + return nil, err + } + + // destination, offset to match first output + dstSize := cap(dst) + dst = dst[:dstSize] + out := dst + dstEvery := (dstSize + 3) / 4 + + const tlSize = 1 << tableLogMax + const tlMask = tlSize - 1 + single := d.dt.single[:tlSize] + + // Use temp table to avoid bound checks/append penalty. + buf := d.buffer() + var off uint8 + var decoded int + + // Decode 2 values from each decoder/loop. + const bufoff = 256 + for { + if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { + break + } + + { + const stream = 0 + const stream2 = 1 + br[stream].fillFast() + br[stream2].fillFast() + + val := br[stream].peekBitsFast(d.actualTableLog) + val2 := br[stream2].peekBitsFast(d.actualTableLog) + v := single[val&tlMask] + v2 := single[val2&tlMask] + br[stream].advance(uint8(v.entry)) + br[stream2].advance(uint8(v2.entry)) + buf[stream][off] = uint8(v.entry >> 8) + buf[stream2][off] = uint8(v2.entry >> 8) + + val = br[stream].peekBitsFast(d.actualTableLog) + val2 = br[stream2].peekBitsFast(d.actualTableLog) + v = single[val&tlMask] + v2 = single[val2&tlMask] + br[stream].advance(uint8(v.entry)) + br[stream2].advance(uint8(v2.entry)) + buf[stream][off+1] = uint8(v.entry >> 8) + buf[stream2][off+1] = uint8(v2.entry >> 8) + } + + { + const stream = 2 + const stream2 = 3 + br[stream].fillFast() + br[stream2].fillFast() + + val := br[stream].peekBitsFast(d.actualTableLog) + val2 := br[stream2].peekBitsFast(d.actualTableLog) + v := single[val&tlMask] + v2 := single[val2&tlMask] + br[stream].advance(uint8(v.entry)) + br[stream2].advance(uint8(v2.entry)) + buf[stream][off] = uint8(v.entry >> 8) + buf[stream2][off] = uint8(v2.entry >> 8) + + val = br[stream].peekBitsFast(d.actualTableLog) + val2 = br[stream2].peekBitsFast(d.actualTableLog) + v = single[val&tlMask] + v2 = single[val2&tlMask] + br[stream].advance(uint8(v.entry)) + br[stream2].advance(uint8(v2.entry)) + buf[stream][off+1] = uint8(v.entry >> 8) + buf[stream2][off+1] = uint8(v2.entry >> 8) + } + + off += 2 + + if off == 0 { + if bufoff > dstEvery { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 1") + } + // There must at least be 3 buffers left. + if len(out)-bufoff < dstEvery*3 { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 2") + } + //copy(out, buf[0][:]) + //copy(out[dstEvery:], buf[1][:]) + //copy(out[dstEvery*2:], buf[2][:]) + //copy(out[dstEvery*3:], buf[3][:]) + *(*[bufoff]byte)(out) = buf[0] + *(*[bufoff]byte)(out[dstEvery:]) = buf[1] + *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] + *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] + out = out[bufoff:] + decoded += bufoff * 4 + } + } + if off > 0 { + ioff := int(off) + if len(out) < dstEvery*3+ioff { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 3") + } + copy(out, buf[0][:off]) + copy(out[dstEvery:], buf[1][:off]) + copy(out[dstEvery*2:], buf[2][:off]) + copy(out[dstEvery*3:], buf[3][:off]) + decoded += int(off) * 4 + out = out[off:] + } + + // Decode remaining. + remainBytes := dstEvery - (decoded / 4) + for i := range br { + offset := dstEvery * i + endsAt := offset + remainBytes + if endsAt > len(out) { + endsAt = len(out) + } + br := &br[i] + bitsLeft := br.remaining() + for bitsLeft > 0 { + br.fill() + if offset >= endsAt { + d.bufs.Put(buf) + return nil, errors.New("corruption detected: stream overrun 4") + } + + // Read value and increment offset. + val := br.peekBitsFast(d.actualTableLog) + v := single[val&tlMask].entry + nBits := uint8(v) + br.advance(nBits) + bitsLeft -= uint(nBits) + out[offset] = uint8(v >> 8) + offset++ + } + if offset != endsAt { + d.bufs.Put(buf) + return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) + } + decoded += offset - dstEvery*i + err = br.close() + if err != nil { + return nil, err + } + } + d.bufs.Put(buf) + if dstSize != decoded { + return nil, errors.New("corruption detected: short output block") + } + return dst, nil +} + +// Decompress1X will decompress a 1X encoded stream. +// The cap of the output buffer will be the maximum decompressed size. +// The length of the supplied input must match the end of a block exactly. +func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { + if len(d.dt.single) == 0 { + return nil, errors.New("no table loaded") + } + if use8BitTables && d.actualTableLog <= 8 { + return d.decompress1X8Bit(dst, src) + } + var br bitReaderShifted + err := br.init(src) + if err != nil { + return dst, err + } + maxDecodedSize := cap(dst) + dst = dst[:0] + + // Avoid bounds check by always having full sized table. + const tlSize = 1 << tableLogMax + const tlMask = tlSize - 1 + dt := d.dt.single[:tlSize] + + // Use temp table to avoid bound checks/append penalty. + bufs := d.buffer() + buf := &bufs[0] + var off uint8 + + for br.off >= 8 { + br.fillFast() + v := dt[br.peekBitsFast(d.actualTableLog)&tlMask] + br.advance(uint8(v.entry)) + buf[off+0] = uint8(v.entry >> 8) + + v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] + br.advance(uint8(v.entry)) + buf[off+1] = uint8(v.entry >> 8) + + // Refill + br.fillFast() + + v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] + br.advance(uint8(v.entry)) + buf[off+2] = uint8(v.entry >> 8) + + v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] + br.advance(uint8(v.entry)) + buf[off+3] = uint8(v.entry >> 8) + + off += 4 + if off == 0 { + if len(dst)+256 > maxDecodedSize { + br.close() + d.bufs.Put(bufs) + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:]...) + } + } + + if len(dst)+int(off) > maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + dst = append(dst, buf[:off]...) + + // br < 8, so uint8 is fine + bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead + for bitsLeft > 0 { + br.fill() + if false && br.bitsRead >= 32 { + if br.off >= 4 { + v := br.in[br.off-4:] + v = v[:4] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + br.value = (br.value << 32) | uint64(low) + br.bitsRead -= 32 + br.off -= 4 + } else { + for br.off > 0 { + br.value = (br.value << 8) | uint64(br.in[br.off-1]) + br.bitsRead -= 8 + br.off-- + } + } + } + if len(dst) >= maxDecodedSize { + d.bufs.Put(bufs) + br.close() + return nil, ErrMaxDecodedSizeExceeded + } + v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] + nBits := uint8(v.entry) + br.advance(nBits) + bitsLeft -= nBits + dst = append(dst, uint8(v.entry>>8)) + } + d.bufs.Put(bufs) + return dst, br.close() +} diff --git a/vendor/github.com/klauspost/compress/huff0/huff0.go b/vendor/github.com/klauspost/compress/huff0/huff0.go new file mode 100644 index 000000000..77ecd68e0 --- /dev/null +++ b/vendor/github.com/klauspost/compress/huff0/huff0.go @@ -0,0 +1,337 @@ +// Package huff0 provides fast huffman encoding as used in zstd. +// +// See README.md at https://github.com/klauspost/compress/tree/master/huff0 for details. +package huff0 + +import ( + "errors" + "fmt" + "math" + "math/bits" + "sync" + + "github.com/klauspost/compress/fse" +) + +const ( + maxSymbolValue = 255 + + // zstandard limits tablelog to 11, see: + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#huffman-tree-description + tableLogMax = 11 + tableLogDefault = 11 + minTablelog = 5 + huffNodesLen = 512 + + // BlockSizeMax is maximum input size for a single block uncompressed. + BlockSizeMax = 1<<18 - 1 +) + +var ( + // ErrIncompressible is returned when input is judged to be too hard to compress. + ErrIncompressible = errors.New("input is not compressible") + + // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. + ErrUseRLE = errors.New("input is single value repeated") + + // ErrTooBig is return if input is too large for a single block. + ErrTooBig = errors.New("input too big") + + // ErrMaxDecodedSizeExceeded is return if input is too large for a single block. + ErrMaxDecodedSizeExceeded = errors.New("maximum output size exceeded") +) + +type ReusePolicy uint8 + +const ( + // ReusePolicyAllow will allow reuse if it produces smaller output. + ReusePolicyAllow ReusePolicy = iota + + // ReusePolicyPrefer will re-use aggressively if possible. + // This will not check if a new table will produce smaller output, + // except if the current table is impossible to use or + // compressed output is bigger than input. + ReusePolicyPrefer + + // ReusePolicyNone will disable re-use of tables. + // This is slightly faster than ReusePolicyAllow but may produce larger output. + ReusePolicyNone + + // ReusePolicyMust must allow reuse and produce smaller output. + ReusePolicyMust +) + +type Scratch struct { + count [maxSymbolValue + 1]uint32 + + // Per block parameters. + // These can be used to override compression parameters of the block. + // Do not touch, unless you know what you are doing. + + // Out is output buffer. + // If the scratch is re-used before the caller is done processing the output, + // set this field to nil. + // Otherwise the output buffer will be re-used for next Compression/Decompression step + // and allocation will be avoided. + Out []byte + + // OutTable will contain the table data only, if a new table has been generated. + // Slice of the returned data. + OutTable []byte + + // OutData will contain the compressed data. + // Slice of the returned data. + OutData []byte + + // MaxDecodedSize will set the maximum allowed output size. + // This value will automatically be set to BlockSizeMax if not set. + // Decoders will return ErrMaxDecodedSizeExceeded is this limit is exceeded. + MaxDecodedSize int + + srcLen int + + // MaxSymbolValue will override the maximum symbol value of the next block. + MaxSymbolValue uint8 + + // TableLog will attempt to override the tablelog for the next block. + // Must be <= 11 and >= 5. + TableLog uint8 + + // Reuse will specify the reuse policy + Reuse ReusePolicy + + // WantLogLess allows to specify a log 2 reduction that should at least be achieved, + // otherwise the block will be returned as incompressible. + // The reduction should then at least be (input size >> WantLogLess) + // If WantLogLess == 0 any improvement will do. + WantLogLess uint8 + + symbolLen uint16 // Length of active part of the symbol table. + maxCount int // count of the most probable symbol + clearCount bool // clear count + actualTableLog uint8 // Selected tablelog. + prevTableLog uint8 // Tablelog for previous table + prevTable cTable // Table used for previous compression. + cTable cTable // compression table + dt dTable // decompression table + nodes []nodeElt + tmpOut [4][]byte + fse *fse.Scratch + decPool sync.Pool // *[4][256]byte buffers. + huffWeight [maxSymbolValue + 1]byte +} + +// TransferCTable will transfer the previously used compression table. +func (s *Scratch) TransferCTable(src *Scratch) { + if cap(s.prevTable) < len(src.prevTable) { + s.prevTable = make(cTable, 0, maxSymbolValue+1) + } + s.prevTable = s.prevTable[:len(src.prevTable)] + copy(s.prevTable, src.prevTable) + s.prevTableLog = src.prevTableLog +} + +func (s *Scratch) prepare(in []byte) (*Scratch, error) { + if len(in) > BlockSizeMax { + return nil, ErrTooBig + } + if s == nil { + s = &Scratch{} + } + if s.MaxSymbolValue == 0 { + s.MaxSymbolValue = maxSymbolValue + } + if s.TableLog == 0 { + s.TableLog = tableLogDefault + } + if s.TableLog > tableLogMax || s.TableLog < minTablelog { + return nil, fmt.Errorf(" invalid tableLog %d (%d -> %d)", s.TableLog, minTablelog, tableLogMax) + } + if s.MaxDecodedSize <= 0 || s.MaxDecodedSize > BlockSizeMax { + s.MaxDecodedSize = BlockSizeMax + } + if s.clearCount && s.maxCount == 0 { + for i := range s.count { + s.count[i] = 0 + } + s.clearCount = false + } + if cap(s.Out) == 0 { + s.Out = make([]byte, 0, len(in)) + } + s.Out = s.Out[:0] + + s.OutTable = nil + s.OutData = nil + if cap(s.nodes) < huffNodesLen+1 { + s.nodes = make([]nodeElt, 0, huffNodesLen+1) + } + s.nodes = s.nodes[:0] + if s.fse == nil { + s.fse = &fse.Scratch{} + } + s.srcLen = len(in) + + return s, nil +} + +type cTable []cTableEntry + +func (c cTable) write(s *Scratch) error { + var ( + // precomputed conversion table + bitsToWeight [tableLogMax + 1]byte + huffLog = s.actualTableLog + // last weight is not saved. + maxSymbolValue = uint8(s.symbolLen - 1) + huffWeight = s.huffWeight[:256] + ) + const ( + maxFSETableLog = 6 + ) + // convert to weight + bitsToWeight[0] = 0 + for n := uint8(1); n < huffLog+1; n++ { + bitsToWeight[n] = huffLog + 1 - n + } + + // Acquire histogram for FSE. + hist := s.fse.Histogram() + hist = hist[:256] + for i := range hist[:16] { + hist[i] = 0 + } + for n := uint8(0); n < maxSymbolValue; n++ { + v := bitsToWeight[c[n].nBits] & 15 + huffWeight[n] = v + hist[v]++ + } + + // FSE compress if feasible. + if maxSymbolValue >= 2 { + huffMaxCnt := uint32(0) + huffMax := uint8(0) + for i, v := range hist[:16] { + if v == 0 { + continue + } + huffMax = byte(i) + if v > huffMaxCnt { + huffMaxCnt = v + } + } + s.fse.HistogramFinished(huffMax, int(huffMaxCnt)) + s.fse.TableLog = maxFSETableLog + b, err := fse.Compress(huffWeight[:maxSymbolValue], s.fse) + if err == nil && len(b) < int(s.symbolLen>>1) { + s.Out = append(s.Out, uint8(len(b))) + s.Out = append(s.Out, b...) + return nil + } + // Unable to compress (RLE/uncompressible) + } + // write raw values as 4-bits (max : 15) + if maxSymbolValue > (256 - 128) { + // should not happen : likely means source cannot be compressed + return ErrIncompressible + } + op := s.Out + // special case, pack weights 4 bits/weight. + op = append(op, 128|(maxSymbolValue-1)) + // be sure it doesn't cause msan issue in final combination + huffWeight[maxSymbolValue] = 0 + for n := uint16(0); n < uint16(maxSymbolValue); n += 2 { + op = append(op, (huffWeight[n]<<4)|huffWeight[n+1]) + } + s.Out = op + return nil +} + +func (c cTable) estTableSize(s *Scratch) (sz int, err error) { + var ( + // precomputed conversion table + bitsToWeight [tableLogMax + 1]byte + huffLog = s.actualTableLog + // last weight is not saved. + maxSymbolValue = uint8(s.symbolLen - 1) + huffWeight = s.huffWeight[:256] + ) + const ( + maxFSETableLog = 6 + ) + // convert to weight + bitsToWeight[0] = 0 + for n := uint8(1); n < huffLog+1; n++ { + bitsToWeight[n] = huffLog + 1 - n + } + + // Acquire histogram for FSE. + hist := s.fse.Histogram() + hist = hist[:256] + for i := range hist[:16] { + hist[i] = 0 + } + for n := uint8(0); n < maxSymbolValue; n++ { + v := bitsToWeight[c[n].nBits] & 15 + huffWeight[n] = v + hist[v]++ + } + + // FSE compress if feasible. + if maxSymbolValue >= 2 { + huffMaxCnt := uint32(0) + huffMax := uint8(0) + for i, v := range hist[:16] { + if v == 0 { + continue + } + huffMax = byte(i) + if v > huffMaxCnt { + huffMaxCnt = v + } + } + s.fse.HistogramFinished(huffMax, int(huffMaxCnt)) + s.fse.TableLog = maxFSETableLog + b, err := fse.Compress(huffWeight[:maxSymbolValue], s.fse) + if err == nil && len(b) < int(s.symbolLen>>1) { + sz += 1 + len(b) + return sz, nil + } + // Unable to compress (RLE/uncompressible) + } + // write raw values as 4-bits (max : 15) + if maxSymbolValue > (256 - 128) { + // should not happen : likely means source cannot be compressed + return 0, ErrIncompressible + } + // special case, pack weights 4 bits/weight. + sz += 1 + int(maxSymbolValue/2) + return sz, nil +} + +// estimateSize returns the estimated size in bytes of the input represented in the +// histogram supplied. +func (c cTable) estimateSize(hist []uint32) int { + nbBits := uint32(7) + for i, v := range c[:len(hist)] { + nbBits += uint32(v.nBits) * hist[i] + } + return int(nbBits >> 3) +} + +// minSize returns the minimum possible size considering the shannon limit. +func (s *Scratch) minSize(total int) int { + nbBits := float64(7) + fTotal := float64(total) + for _, v := range s.count[:s.symbolLen] { + n := float64(v) + if n > 0 { + nbBits += math.Log2(fTotal/n) * n + } + } + return int(nbBits) >> 3 +} + +func highBit32(val uint32) (n uint32) { + return uint32(bits.Len32(val) - 1) +} diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go new file mode 100644 index 000000000..3954c5121 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go @@ -0,0 +1,34 @@ +// Package cpuinfo gives runtime info about the current CPU. +// +// This is a very limited module meant for use internally +// in this project. For more versatile solution check +// https://github.com/klauspost/cpuid. +package cpuinfo + +// HasBMI1 checks whether an x86 CPU supports the BMI1 extension. +func HasBMI1() bool { + return hasBMI1 +} + +// HasBMI2 checks whether an x86 CPU supports the BMI2 extension. +func HasBMI2() bool { + return hasBMI2 +} + +// DisableBMI2 will disable BMI2, for testing purposes. +// Call returned function to restore previous state. +func DisableBMI2() func() { + old := hasBMI2 + hasBMI2 = false + return func() { + hasBMI2 = old + } +} + +// HasBMI checks whether an x86 CPU supports both BMI1 and BMI2 extensions. +func HasBMI() bool { + return HasBMI1() && HasBMI2() +} + +var hasBMI1 bool +var hasBMI2 bool diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go new file mode 100644 index 000000000..e802579c4 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go @@ -0,0 +1,11 @@ +//go:build amd64 && !appengine && !noasm && gc +// +build amd64,!appengine,!noasm,gc + +package cpuinfo + +// go:noescape +func x86extensions() (bmi1, bmi2 bool) + +func init() { + hasBMI1, hasBMI2 = x86extensions() +} diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s new file mode 100644 index 000000000..4465fbe9e --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s @@ -0,0 +1,36 @@ +// +build !appengine +// +build gc +// +build !noasm + +#include "textflag.h" +#include "funcdata.h" +#include "go_asm.h" + +TEXT ·x86extensions(SB), NOSPLIT, $0 + // 1. determine max EAX value + XORQ AX, AX + CPUID + + CMPQ AX, $7 + JB unsupported + + // 2. EAX = 7, ECX = 0 --- see Table 3-8 "Information Returned by CPUID Instruction" + MOVQ $7, AX + MOVQ $0, CX + CPUID + + BTQ $3, BX // bit 3 = BMI1 + SETCS AL + + BTQ $8, BX // bit 8 = BMI2 + SETCS AH + + MOVB AL, bmi1+0(FP) + MOVB AH, bmi2+1(FP) + RET + +unsupported: + XORQ AX, AX + MOVB AL, bmi1+0(FP) + MOVB AL, bmi2+1(FP) + RET diff --git a/vendor/github.com/klauspost/compress/internal/snapref/LICENSE b/vendor/github.com/klauspost/compress/internal/snapref/LICENSE new file mode 100644 index 000000000..6050c10f4 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/snapref/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/klauspost/compress/internal/snapref/decode.go b/vendor/github.com/klauspost/compress/internal/snapref/decode.go new file mode 100644 index 000000000..40796a49d --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/snapref/decode.go @@ -0,0 +1,264 @@ +// Copyright 2011 The Snappy-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 snapref + +import ( + "encoding/binary" + "errors" + "io" +) + +var ( + // ErrCorrupt reports that the input is invalid. + ErrCorrupt = errors.New("snappy: corrupt input") + // ErrTooLarge reports that the uncompressed length is too large. + ErrTooLarge = errors.New("snappy: decoded block is too large") + // ErrUnsupported reports that the input isn't supported. + ErrUnsupported = errors.New("snappy: unsupported input") + + errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") +) + +// DecodedLen returns the length of the decoded block. +func DecodedLen(src []byte) (int, error) { + v, _, err := decodedLen(src) + return v, err +} + +// decodedLen returns the length of the decoded block and the number of bytes +// that the length header occupied. +func decodedLen(src []byte) (blockLen, headerLen int, err error) { + v, n := binary.Uvarint(src) + if n <= 0 || v > 0xffffffff { + return 0, 0, ErrCorrupt + } + + const wordSize = 32 << (^uint(0) >> 32 & 1) + if wordSize == 32 && v > 0x7fffffff { + return 0, 0, ErrTooLarge + } + return int(v), n, nil +} + +const ( + decodeErrCodeCorrupt = 1 + decodeErrCodeUnsupportedLiteralLength = 2 +) + +// Decode returns the decoded form of src. The returned slice may be a sub- +// slice of dst if dst was large enough to hold the entire decoded block. +// Otherwise, a newly allocated slice will be returned. +// +// The dst and src must not overlap. It is valid to pass a nil dst. +// +// Decode handles the Snappy block format, not the Snappy stream format. +func Decode(dst, src []byte) ([]byte, error) { + dLen, s, err := decodedLen(src) + if err != nil { + return nil, err + } + if dLen <= len(dst) { + dst = dst[:dLen] + } else { + dst = make([]byte, dLen) + } + switch decode(dst, src[s:]) { + case 0: + return dst, nil + case decodeErrCodeUnsupportedLiteralLength: + return nil, errUnsupportedLiteralLength + } + return nil, ErrCorrupt +} + +// NewReader returns a new Reader that decompresses from r, using the framing +// format described at +// https://github.com/google/snappy/blob/master/framing_format.txt +func NewReader(r io.Reader) *Reader { + return &Reader{ + r: r, + decoded: make([]byte, maxBlockSize), + buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize), + } +} + +// Reader is an io.Reader that can read Snappy-compressed bytes. +// +// Reader handles the Snappy stream format, not the Snappy block format. +type Reader struct { + r io.Reader + err error + decoded []byte + buf []byte + // decoded[i:j] contains decoded bytes that have not yet been passed on. + i, j int + readHeader bool +} + +// Reset discards any buffered data, resets all state, and switches the Snappy +// reader to read from r. This permits reusing a Reader rather than allocating +// a new one. +func (r *Reader) Reset(reader io.Reader) { + r.r = reader + r.err = nil + r.i = 0 + r.j = 0 + r.readHeader = false +} + +func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) { + if _, r.err = io.ReadFull(r.r, p); r.err != nil { + if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { + r.err = ErrCorrupt + } + return false + } + return true +} + +func (r *Reader) fill() error { + for r.i >= r.j { + if !r.readFull(r.buf[:4], true) { + return r.err + } + chunkType := r.buf[0] + if !r.readHeader { + if chunkType != chunkTypeStreamIdentifier { + r.err = ErrCorrupt + return r.err + } + r.readHeader = true + } + chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 + if chunkLen > len(r.buf) { + r.err = ErrUnsupported + return r.err + } + + // The chunk types are specified at + // https://github.com/google/snappy/blob/master/framing_format.txt + switch chunkType { + case chunkTypeCompressedData: + // Section 4.2. Compressed data (chunk type 0x00). + if chunkLen < checksumSize { + r.err = ErrCorrupt + return r.err + } + buf := r.buf[:chunkLen] + if !r.readFull(buf, false) { + return r.err + } + checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 + buf = buf[checksumSize:] + + n, err := DecodedLen(buf) + if err != nil { + r.err = err + return r.err + } + if n > len(r.decoded) { + r.err = ErrCorrupt + return r.err + } + if _, err := Decode(r.decoded, buf); err != nil { + r.err = err + return r.err + } + if crc(r.decoded[:n]) != checksum { + r.err = ErrCorrupt + return r.err + } + r.i, r.j = 0, n + continue + + case chunkTypeUncompressedData: + // Section 4.3. Uncompressed data (chunk type 0x01). + if chunkLen < checksumSize { + r.err = ErrCorrupt + return r.err + } + buf := r.buf[:checksumSize] + if !r.readFull(buf, false) { + return r.err + } + checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 + // Read directly into r.decoded instead of via r.buf. + n := chunkLen - checksumSize + if n > len(r.decoded) { + r.err = ErrCorrupt + return r.err + } + if !r.readFull(r.decoded[:n], false) { + return r.err + } + if crc(r.decoded[:n]) != checksum { + r.err = ErrCorrupt + return r.err + } + r.i, r.j = 0, n + continue + + case chunkTypeStreamIdentifier: + // Section 4.1. Stream identifier (chunk type 0xff). + if chunkLen != len(magicBody) { + r.err = ErrCorrupt + return r.err + } + if !r.readFull(r.buf[:len(magicBody)], false) { + return r.err + } + for i := 0; i < len(magicBody); i++ { + if r.buf[i] != magicBody[i] { + r.err = ErrCorrupt + return r.err + } + } + continue + } + + if chunkType <= 0x7f { + // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). + r.err = ErrUnsupported + return r.err + } + // Section 4.4 Padding (chunk type 0xfe). + // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). + if !r.readFull(r.buf[:chunkLen], false) { + return r.err + } + } + + return nil +} + +// Read satisfies the io.Reader interface. +func (r *Reader) Read(p []byte) (int, error) { + if r.err != nil { + return 0, r.err + } + + if err := r.fill(); err != nil { + return 0, err + } + + n := copy(p, r.decoded[r.i:r.j]) + r.i += n + return n, nil +} + +// ReadByte satisfies the io.ByteReader interface. +func (r *Reader) ReadByte() (byte, error) { + if r.err != nil { + return 0, r.err + } + + if err := r.fill(); err != nil { + return 0, err + } + + c := r.decoded[r.i] + r.i++ + return c, nil +} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go b/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go new file mode 100644 index 000000000..77395a6b8 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go @@ -0,0 +1,113 @@ +// Copyright 2016 The Snappy-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 snapref + +// decode writes the decoding of src to dst. It assumes that the varint-encoded +// length of the decompressed bytes has already been read, and that len(dst) +// equals that length. +// +// It returns 0 on success or a decodeErrCodeXxx error code on failure. +func decode(dst, src []byte) int { + var d, s, offset, length int + for s < len(src) { + switch src[s] & 0x03 { + case tagLiteral: + x := uint32(src[s] >> 2) + switch { + case x < 60: + s++ + case x == 60: + s += 2 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-1]) + case x == 61: + s += 3 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-2]) | uint32(src[s-1])<<8 + case x == 62: + s += 4 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 + case x == 63: + s += 5 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 + } + length = int(x) + 1 + if length <= 0 { + return decodeErrCodeUnsupportedLiteralLength + } + if length > len(dst)-d || length > len(src)-s { + return decodeErrCodeCorrupt + } + copy(dst[d:], src[s:s+length]) + d += length + s += length + continue + + case tagCopy1: + s += 2 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + length = 4 + int(src[s-2])>>2&0x7 + offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) + + case tagCopy2: + s += 3 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + length = 1 + int(src[s-3])>>2 + offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) + + case tagCopy4: + s += 5 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + length = 1 + int(src[s-5])>>2 + offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) + } + + if offset <= 0 || d < offset || length > len(dst)-d { + return decodeErrCodeCorrupt + } + // Copy from an earlier sub-slice of dst to a later sub-slice. + // If no overlap, use the built-in copy: + if offset >= length { + copy(dst[d:d+length], dst[d-offset:]) + d += length + continue + } + + // Unlike the built-in copy function, this byte-by-byte copy always runs + // forwards, even if the slices overlap. Conceptually, this is: + // + // d += forwardCopy(dst[d:d+length], dst[d-offset:]) + // + // We align the slices into a and b and show the compiler they are the same size. + // This allows the loop to run without bounds checks. + a := dst[d : d+length] + b := dst[d-offset:] + b = b[:len(a)] + for i := range a { + a[i] = b[i] + } + d += length + } + if d != len(dst) { + return decodeErrCodeCorrupt + } + return 0 +} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/encode.go b/vendor/github.com/klauspost/compress/internal/snapref/encode.go new file mode 100644 index 000000000..13c6040a5 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/snapref/encode.go @@ -0,0 +1,289 @@ +// Copyright 2011 The Snappy-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 snapref + +import ( + "encoding/binary" + "errors" + "io" +) + +// Encode returns the encoded form of src. The returned slice may be a sub- +// slice of dst if dst was large enough to hold the entire encoded block. +// Otherwise, a newly allocated slice will be returned. +// +// The dst and src must not overlap. It is valid to pass a nil dst. +// +// Encode handles the Snappy block format, not the Snappy stream format. +func Encode(dst, src []byte) []byte { + if n := MaxEncodedLen(len(src)); n < 0 { + panic(ErrTooLarge) + } else if len(dst) < n { + dst = make([]byte, n) + } + + // The block starts with the varint-encoded length of the decompressed bytes. + d := binary.PutUvarint(dst, uint64(len(src))) + + for len(src) > 0 { + p := src + src = nil + if len(p) > maxBlockSize { + p, src = p[:maxBlockSize], p[maxBlockSize:] + } + if len(p) < minNonLiteralBlockSize { + d += emitLiteral(dst[d:], p) + } else { + d += encodeBlock(dst[d:], p) + } + } + return dst[:d] +} + +// inputMargin is the minimum number of extra input bytes to keep, inside +// encodeBlock's inner loop. On some architectures, this margin lets us +// implement a fast path for emitLiteral, where the copy of short (<= 16 byte) +// literals can be implemented as a single load to and store from a 16-byte +// register. That literal's actual length can be as short as 1 byte, so this +// can copy up to 15 bytes too much, but that's OK as subsequent iterations of +// the encoding loop will fix up the copy overrun, and this inputMargin ensures +// that we don't overrun the dst and src buffers. +const inputMargin = 16 - 1 + +// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that +// could be encoded with a copy tag. This is the minimum with respect to the +// algorithm used by encodeBlock, not a minimum enforced by the file format. +// +// The encoded output must start with at least a 1 byte literal, as there are +// no previous bytes to copy. A minimal (1 byte) copy after that, generated +// from an emitCopy call in encodeBlock's main loop, would require at least +// another inputMargin bytes, for the reason above: we want any emitLiteral +// calls inside encodeBlock's main loop to use the fast path if possible, which +// requires being able to overrun by inputMargin bytes. Thus, +// minNonLiteralBlockSize equals 1 + 1 + inputMargin. +// +// The C++ code doesn't use this exact threshold, but it could, as discussed at +// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion +// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an +// optimization. It should not affect the encoded form. This is tested by +// TestSameEncodingAsCppShortCopies. +const minNonLiteralBlockSize = 1 + 1 + inputMargin + +// MaxEncodedLen returns the maximum length of a snappy block, given its +// uncompressed length. +// +// It will return a negative value if srcLen is too large to encode. +func MaxEncodedLen(srcLen int) int { + n := uint64(srcLen) + if n > 0xffffffff { + return -1 + } + // Compressed data can be defined as: + // compressed := item* literal* + // item := literal* copy + // + // The trailing literal sequence has a space blowup of at most 62/60 + // since a literal of length 60 needs one tag byte + one extra byte + // for length information. + // + // Item blowup is trickier to measure. Suppose the "copy" op copies + // 4 bytes of data. Because of a special check in the encoding code, + // we produce a 4-byte copy only if the offset is < 65536. Therefore + // the copy op takes 3 bytes to encode, and this type of item leads + // to at most the 62/60 blowup for representing literals. + // + // Suppose the "copy" op copies 5 bytes of data. If the offset is big + // enough, it will take 5 bytes to encode the copy op. Therefore the + // worst case here is a one-byte literal followed by a five-byte copy. + // That is, 6 bytes of input turn into 7 bytes of "compressed" data. + // + // This last factor dominates the blowup, so the final estimate is: + n = 32 + n + n/6 + if n > 0xffffffff { + return -1 + } + return int(n) +} + +var errClosed = errors.New("snappy: Writer is closed") + +// NewWriter returns a new Writer that compresses to w. +// +// The Writer returned does not buffer writes. There is no need to Flush or +// Close such a Writer. +// +// Deprecated: the Writer returned is not suitable for many small writes, only +// for few large writes. Use NewBufferedWriter instead, which is efficient +// regardless of the frequency and shape of the writes, and remember to Close +// that Writer when done. +func NewWriter(w io.Writer) *Writer { + return &Writer{ + w: w, + obuf: make([]byte, obufLen), + } +} + +// NewBufferedWriter returns a new Writer that compresses to w, using the +// framing format described at +// https://github.com/google/snappy/blob/master/framing_format.txt +// +// The Writer returned buffers writes. Users must call Close to guarantee all +// data has been forwarded to the underlying io.Writer. They may also call +// Flush zero or more times before calling Close. +func NewBufferedWriter(w io.Writer) *Writer { + return &Writer{ + w: w, + ibuf: make([]byte, 0, maxBlockSize), + obuf: make([]byte, obufLen), + } +} + +// Writer is an io.Writer that can write Snappy-compressed bytes. +// +// Writer handles the Snappy stream format, not the Snappy block format. +type Writer struct { + w io.Writer + err error + + // ibuf is a buffer for the incoming (uncompressed) bytes. + // + // Its use is optional. For backwards compatibility, Writers created by the + // NewWriter function have ibuf == nil, do not buffer incoming bytes, and + // therefore do not need to be Flush'ed or Close'd. + ibuf []byte + + // obuf is a buffer for the outgoing (compressed) bytes. + obuf []byte + + // wroteStreamHeader is whether we have written the stream header. + wroteStreamHeader bool +} + +// Reset discards the writer's state and switches the Snappy writer to write to +// w. This permits reusing a Writer rather than allocating a new one. +func (w *Writer) Reset(writer io.Writer) { + w.w = writer + w.err = nil + if w.ibuf != nil { + w.ibuf = w.ibuf[:0] + } + w.wroteStreamHeader = false +} + +// Write satisfies the io.Writer interface. +func (w *Writer) Write(p []byte) (nRet int, errRet error) { + if w.ibuf == nil { + // Do not buffer incoming bytes. This does not perform or compress well + // if the caller of Writer.Write writes many small slices. This + // behavior is therefore deprecated, but still supported for backwards + // compatibility with code that doesn't explicitly Flush or Close. + return w.write(p) + } + + // The remainder of this method is based on bufio.Writer.Write from the + // standard library. + + for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { + var n int + if len(w.ibuf) == 0 { + // Large write, empty buffer. + // Write directly from p to avoid copy. + n, _ = w.write(p) + } else { + n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) + w.ibuf = w.ibuf[:len(w.ibuf)+n] + w.Flush() + } + nRet += n + p = p[n:] + } + if w.err != nil { + return nRet, w.err + } + n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) + w.ibuf = w.ibuf[:len(w.ibuf)+n] + nRet += n + return nRet, nil +} + +func (w *Writer) write(p []byte) (nRet int, errRet error) { + if w.err != nil { + return 0, w.err + } + for len(p) > 0 { + obufStart := len(magicChunk) + if !w.wroteStreamHeader { + w.wroteStreamHeader = true + copy(w.obuf, magicChunk) + obufStart = 0 + } + + var uncompressed []byte + if len(p) > maxBlockSize { + uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] + } else { + uncompressed, p = p, nil + } + checksum := crc(uncompressed) + + // Compress the buffer, discarding the result if the improvement + // isn't at least 12.5%. + compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) + chunkType := uint8(chunkTypeCompressedData) + chunkLen := 4 + len(compressed) + obufEnd := obufHeaderLen + len(compressed) + if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { + chunkType = chunkTypeUncompressedData + chunkLen = 4 + len(uncompressed) + obufEnd = obufHeaderLen + } + + // Fill in the per-chunk header that comes before the body. + w.obuf[len(magicChunk)+0] = chunkType + w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) + w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) + w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) + w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) + w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) + w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) + w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) + + if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { + w.err = err + return nRet, err + } + if chunkType == chunkTypeUncompressedData { + if _, err := w.w.Write(uncompressed); err != nil { + w.err = err + return nRet, err + } + } + nRet += len(uncompressed) + } + return nRet, nil +} + +// Flush flushes the Writer to its underlying io.Writer. +func (w *Writer) Flush() error { + if w.err != nil { + return w.err + } + if len(w.ibuf) == 0 { + return nil + } + w.write(w.ibuf) + w.ibuf = w.ibuf[:0] + return w.err +} + +// Close calls Flush and then closes the Writer. +func (w *Writer) Close() error { + w.Flush() + ret := w.err + if w.err == nil { + w.err = errClosed + } + return ret +} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go b/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go new file mode 100644 index 000000000..2aa6a95a0 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go @@ -0,0 +1,250 @@ +// Copyright 2016 The Snappy-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 snapref + +func load32(b []byte, i int) uint32 { + b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line. + return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 +} + +func load64(b []byte, i int) uint64 { + b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line. + return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | + uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 +} + +// emitLiteral writes a literal chunk and returns the number of bytes written. +// +// It assumes that: +// +// dst is long enough to hold the encoded bytes +// 1 <= len(lit) && len(lit) <= 65536 +func emitLiteral(dst, lit []byte) int { + i, n := 0, uint(len(lit)-1) + switch { + case n < 60: + dst[0] = uint8(n)<<2 | tagLiteral + i = 1 + case n < 1<<8: + dst[0] = 60<<2 | tagLiteral + dst[1] = uint8(n) + i = 2 + default: + dst[0] = 61<<2 | tagLiteral + dst[1] = uint8(n) + dst[2] = uint8(n >> 8) + i = 3 + } + return i + copy(dst[i:], lit) +} + +// emitCopy writes a copy chunk and returns the number of bytes written. +// +// It assumes that: +// +// dst is long enough to hold the encoded bytes +// 1 <= offset && offset <= 65535 +// 4 <= length && length <= 65535 +func emitCopy(dst []byte, offset, length int) int { + i := 0 + // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The + // threshold for this loop is a little higher (at 68 = 64 + 4), and the + // length emitted down below is is a little lower (at 60 = 64 - 4), because + // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed + // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as + // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as + // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a + // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an + // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1. + for length >= 68 { + // Emit a length 64 copy, encoded as 3 bytes. + dst[i+0] = 63<<2 | tagCopy2 + dst[i+1] = uint8(offset) + dst[i+2] = uint8(offset >> 8) + i += 3 + length -= 64 + } + if length > 64 { + // Emit a length 60 copy, encoded as 3 bytes. + dst[i+0] = 59<<2 | tagCopy2 + dst[i+1] = uint8(offset) + dst[i+2] = uint8(offset >> 8) + i += 3 + length -= 60 + } + if length >= 12 || offset >= 2048 { + // Emit the remaining copy, encoded as 3 bytes. + dst[i+0] = uint8(length-1)<<2 | tagCopy2 + dst[i+1] = uint8(offset) + dst[i+2] = uint8(offset >> 8) + return i + 3 + } + // Emit the remaining copy, encoded as 2 bytes. + dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 + dst[i+1] = uint8(offset) + return i + 2 +} + +func hash(u, shift uint32) uint32 { + return (u * 0x1e35a7bd) >> shift +} + +// EncodeBlockInto exposes encodeBlock but checks dst size. +func EncodeBlockInto(dst, src []byte) (d int) { + if MaxEncodedLen(len(src)) > len(dst) { + return 0 + } + + // encodeBlock breaks on too big blocks, so split. + for len(src) > 0 { + p := src + src = nil + if len(p) > maxBlockSize { + p, src = p[:maxBlockSize], p[maxBlockSize:] + } + if len(p) < minNonLiteralBlockSize { + d += emitLiteral(dst[d:], p) + } else { + d += encodeBlock(dst[d:], p) + } + } + return d +} + +// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It +// assumes that the varint-encoded length of the decompressed bytes has already +// been written. +// +// It also assumes that: +// +// len(dst) >= MaxEncodedLen(len(src)) && +// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize +func encodeBlock(dst, src []byte) (d int) { + // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. + // The table element type is uint16, as s < sLimit and sLimit < len(src) + // and len(src) <= maxBlockSize and maxBlockSize == 65536. + const ( + maxTableSize = 1 << 14 + // tableMask is redundant, but helps the compiler eliminate bounds + // checks. + tableMask = maxTableSize - 1 + ) + shift := uint32(32 - 8) + for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { + shift-- + } + // In Go, all array elements are zero-initialized, so there is no advantage + // to a smaller tableSize per se. However, it matches the C++ algorithm, + // and in the asm versions of this code, we can get away with zeroing only + // the first tableSize elements. + var table [maxTableSize]uint16 + + // sLimit is when to stop looking for offset/length copies. The inputMargin + // lets us use a fast path for emitLiteral in the main loop, while we are + // looking for copies. + sLimit := len(src) - inputMargin + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := 0 + + // The encoded form must start with a literal, as there are no previous + // bytes to copy, so we start looking for hash matches at s == 1. + s := 1 + nextHash := hash(load32(src, s), shift) + + for { + // Copied from the C++ snappy implementation: + // + // Heuristic match skipping: If 32 bytes are scanned with no matches + // found, start looking only at every other byte. If 32 more bytes are + // scanned (or skipped), look at every third byte, etc.. When a match + // is found, immediately go back to looking at every byte. This is a + // small loss (~5% performance, ~0.1% density) for compressible data + // due to more bookkeeping, but for non-compressible data (such as + // JPEG) it's a huge win since the compressor quickly "realizes" the + // data is incompressible and doesn't bother looking for matches + // everywhere. + // + // The "skip" variable keeps track of how many bytes there are since + // the last match; dividing it by 32 (ie. right-shifting by five) gives + // the number of bytes to move ahead for each iteration. + skip := 32 + + nextS := s + candidate := 0 + for { + s = nextS + bytesBetweenHashLookups := skip >> 5 + nextS = s + bytesBetweenHashLookups + skip += bytesBetweenHashLookups + if nextS > sLimit { + goto emitRemainder + } + candidate = int(table[nextHash&tableMask]) + table[nextHash&tableMask] = uint16(s) + nextHash = hash(load32(src, nextS), shift) + if load32(src, s) == load32(src, candidate) { + break + } + } + + // A 4-byte match has been found. We'll later see if more than 4 bytes + // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit + // them as literal bytes. + d += emitLiteral(dst[d:], src[nextEmit:s]) + + // Call emitCopy, and then see if another emitCopy could be our next + // move. Repeat until we find no match for the input immediately after + // what was consumed by the last emitCopy call. + // + // If we exit this loop normally then we need to call emitLiteral next, + // though we don't yet know how big the literal will be. We handle that + // by proceeding to the next iteration of the main loop. We also can + // exit this loop via goto if we get close to exhausting the input. + for { + // Invariant: we have a 4-byte match at s, and no need to emit any + // literal bytes prior to s. + base := s + + // Extend the 4-byte match as long as possible. + // + // This is an inlined version of: + // s = extendMatch(src, candidate+4, s+4) + s += 4 + for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { + } + + d += emitCopy(dst[d:], base-candidate, s-base) + nextEmit = s + if s >= sLimit { + goto emitRemainder + } + + // We could immediately start working at s now, but to improve + // compression we first update the hash table at s-1 and at s. If + // another emitCopy is not our next move, also calculate nextHash + // at s+1. At least on GOARCH=amd64, these three hash calculations + // are faster as one load64 call (with some shifts) instead of + // three load32 calls. + x := load64(src, s-1) + prevHash := hash(uint32(x>>0), shift) + table[prevHash&tableMask] = uint16(s - 1) + currHash := hash(uint32(x>>8), shift) + candidate = int(table[currHash&tableMask]) + table[currHash&tableMask] = uint16(s) + if uint32(x>>8) != load32(src, candidate) { + nextHash = hash(uint32(x>>16), shift) + s++ + break + } + } + } + +emitRemainder: + if nextEmit < len(src) { + d += emitLiteral(dst[d:], src[nextEmit:]) + } + return d +} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/snappy.go b/vendor/github.com/klauspost/compress/internal/snapref/snappy.go new file mode 100644 index 000000000..34d01f4aa --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/snapref/snappy.go @@ -0,0 +1,98 @@ +// Copyright 2011 The Snappy-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 snapref implements the Snappy compression format. It aims for very +// high speeds and reasonable compression. +// +// There are actually two Snappy formats: block and stream. They are related, +// but different: trying to decompress block-compressed data as a Snappy stream +// will fail, and vice versa. The block format is the Decode and Encode +// functions and the stream format is the Reader and Writer types. +// +// The block format, the more common case, is used when the complete size (the +// number of bytes) of the original data is known upfront, at the time +// compression starts. The stream format, also known as the framing format, is +// for when that isn't always true. +// +// The canonical, C++ implementation is at https://github.com/google/snappy and +// it only implements the block format. +package snapref + +import ( + "hash/crc32" +) + +/* +Each encoded block begins with the varint-encoded length of the decoded data, +followed by a sequence of chunks. Chunks begin and end on byte boundaries. The +first byte of each chunk is broken into its 2 least and 6 most significant bits +called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag. +Zero means a literal tag. All other values mean a copy tag. + +For literal tags: + - If m < 60, the next 1 + m bytes are literal bytes. + - Otherwise, let n be the little-endian unsigned integer denoted by the next + m - 59 bytes. The next 1 + n bytes after that are literal bytes. + +For copy tags, length bytes are copied from offset bytes ago, in the style of +Lempel-Ziv compression algorithms. In particular: + - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12). + The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10 + of the offset. The next byte is bits 0-7 of the offset. + - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65). + The length is 1 + m. The offset is the little-endian unsigned integer + denoted by the next 2 bytes. + - For l == 3, this tag is a legacy format that is no longer issued by most + encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in + [1, 65). The length is 1 + m. The offset is the little-endian unsigned + integer denoted by the next 4 bytes. +*/ +const ( + tagLiteral = 0x00 + tagCopy1 = 0x01 + tagCopy2 = 0x02 + tagCopy4 = 0x03 +) + +const ( + checksumSize = 4 + chunkHeaderSize = 4 + magicChunk = "\xff\x06\x00\x00" + magicBody + magicBody = "sNaPpY" + + // maxBlockSize is the maximum size of the input to encodeBlock. It is not + // part of the wire format per se, but some parts of the encoder assume + // that an offset fits into a uint16. + // + // Also, for the framing format (Writer type instead of Encode function), + // https://github.com/google/snappy/blob/master/framing_format.txt says + // that "the uncompressed data in a chunk must be no longer than 65536 + // bytes". + maxBlockSize = 65536 + + // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is + // hard coded to be a const instead of a variable, so that obufLen can also + // be a const. Their equivalence is confirmed by + // TestMaxEncodedLenOfMaxBlockSize. + maxEncodedLenOfMaxBlockSize = 76490 + + obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize + obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize +) + +const ( + chunkTypeCompressedData = 0x00 + chunkTypeUncompressedData = 0x01 + chunkTypePadding = 0xfe + chunkTypeStreamIdentifier = 0xff +) + +var crcTable = crc32.MakeTable(crc32.Castagnoli) + +// crc implements the checksum specified in section 3 of +// https://github.com/google/snappy/blob/master/framing_format.txt +func crc(b []byte) uint32 { + c := crc32.Update(0, crcTable, b) + return uint32(c>>15|c<<17) + 0xa282ead8 +} diff --git a/vendor/github.com/klauspost/compress/s2sx.mod b/vendor/github.com/klauspost/compress/s2sx.mod new file mode 100644 index 000000000..2263853fc --- /dev/null +++ b/vendor/github.com/klauspost/compress/s2sx.mod @@ -0,0 +1,4 @@ +module github.com/klauspost/compress + +go 1.16 + diff --git a/vendor/github.com/klauspost/compress/s2sx.sum b/vendor/github.com/klauspost/compress/s2sx.sum new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/github.com/klauspost/compress/zstd/README.md b/vendor/github.com/klauspost/compress/zstd/README.md new file mode 100644 index 000000000..92e2347bb --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/README.md @@ -0,0 +1,441 @@ +# zstd + +[Zstandard](https://facebook.github.io/zstd/) is a real-time compression algorithm, providing high compression ratios. +It offers a very wide range of compression / speed trade-off, while being backed by a very fast decoder. +A high performance compression algorithm is implemented. For now focused on speed. + +This package provides [compression](#Compressor) to and [decompression](#Decompressor) of Zstandard content. + +This package is pure Go and without use of "unsafe". + +The `zstd` package is provided as open source software using a Go standard license. + +Currently the package is heavily optimized for 64 bit processors and will be significantly slower on 32 bit processors. + +For seekable zstd streams, see [this excellent package](https://github.com/SaveTheRbtz/zstd-seekable-format-go). + +## Installation + +Install using `go get -u github.com/klauspost/compress`. The package is located in `github.com/klauspost/compress/zstd`. + +[![Go Reference](https://pkg.go.dev/badge/github.com/klauspost/compress/zstd.svg)](https://pkg.go.dev/github.com/klauspost/compress/zstd) + +## Compressor + +### Status: + +STABLE - there may always be subtle bugs, a wide variety of content has been tested and the library is actively +used by several projects. This library is being [fuzz-tested](https://github.com/klauspost/compress-fuzz) for all updates. + +There may still be specific combinations of data types/size/settings that could lead to edge cases, +so as always, testing is recommended. + +For now, a high speed (fastest) and medium-fast (default) compressor has been implemented. + +* The "Fastest" compression ratio is roughly equivalent to zstd level 1. +* The "Default" compression ratio is roughly equivalent to zstd level 3 (default). +* The "Better" compression ratio is roughly equivalent to zstd level 7. +* The "Best" compression ratio is roughly equivalent to zstd level 11. + +In terms of speed, it is typically 2x as fast as the stdlib deflate/gzip in its fastest mode. +The compression ratio compared to stdlib is around level 3, but usually 3x as fast. + + +### Usage + +An Encoder can be used for either compressing a stream via the +`io.WriteCloser` interface supported by the Encoder or as multiple independent +tasks via the `EncodeAll` function. +Smaller encodes are encouraged to use the EncodeAll function. +Use `NewWriter` to create a new instance that can be used for both. + +To create a writer with default options, do like this: + +```Go +// Compress input to output. +func Compress(in io.Reader, out io.Writer) error { + enc, err := zstd.NewWriter(out) + if err != nil { + return err + } + _, err = io.Copy(enc, in) + if err != nil { + enc.Close() + return err + } + return enc.Close() +} +``` + +Now you can encode by writing data to `enc`. The output will be finished writing when `Close()` is called. +Even if your encode fails, you should still call `Close()` to release any resources that may be held up. + +The above is fine for big encodes. However, whenever possible try to *reuse* the writer. + +To reuse the encoder, you can use the `Reset(io.Writer)` function to change to another output. +This will allow the encoder to reuse all resources and avoid wasteful allocations. + +Currently stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part +of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change +in the future. So if you want to limit concurrency for future updates, specify the concurrency +you would like. + +If you would like stream encoding to be done without spawning async goroutines, use `WithEncoderConcurrency(1)` +which will compress input as each block is completed, blocking on writes until each has completed. + +You can specify your desired compression level using `WithEncoderLevel()` option. Currently only pre-defined +compression settings can be specified. + +#### Future Compatibility Guarantees + +This will be an evolving project. When using this package it is important to note that both the compression efficiency and speed may change. + +The goal will be to keep the default efficiency at the default zstd (level 3). +However the encoding should never be assumed to remain the same, +and you should not use hashes of compressed output for similarity checks. + +The Encoder can be assumed to produce the same output from the exact same code version. +However, the may be modes in the future that break this, +although they will not be enabled without an explicit option. + +This encoder is not designed to (and will probably never) output the exact same bitstream as the reference encoder. + +Also note, that the cgo decompressor currently does not [report all errors on invalid input](https://github.com/DataDog/zstd/issues/59), +[omits error checks](https://github.com/DataDog/zstd/issues/61), [ignores checksums](https://github.com/DataDog/zstd/issues/43) +and seems to ignore concatenated streams, even though [it is part of the spec](https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frames). + +#### Blocks + +For compressing small blocks, the returned encoder has a function called `EncodeAll(src, dst []byte) []byte`. + +`EncodeAll` will encode all input in src and append it to dst. +This function can be called concurrently. +Each call will only run on a same goroutine as the caller. + +Encoded blocks can be concatenated and the result will be the combined input stream. +Data compressed with EncodeAll can be decoded with the Decoder, using either a stream or `DecodeAll`. + +Especially when encoding blocks you should take special care to reuse the encoder. +This will effectively make it run without allocations after a warmup period. +To make it run completely without allocations, supply a destination buffer with space for all content. + +```Go +import "github.com/klauspost/compress/zstd" + +// Create a writer that caches compressors. +// For this operation type we supply a nil Reader. +var encoder, _ = zstd.NewWriter(nil) + +// Compress a buffer. +// If you have a destination buffer, the allocation in the call can also be eliminated. +func Compress(src []byte) []byte { + return encoder.EncodeAll(src, make([]byte, 0, len(src))) +} +``` + +You can control the maximum number of concurrent encodes using the `WithEncoderConcurrency(n)` +option when creating the writer. + +Using the Encoder for both a stream and individual blocks concurrently is safe. + +### Performance + +I have collected some speed examples to compare speed and compression against other compressors. + +* `file` is the input file. +* `out` is the compressor used. `zskp` is this package. `zstd` is the Datadog cgo library. `gzstd/gzkp` is gzip standard and this library. +* `level` is the compression level used. For `zskp` level 1 is "fastest", level 2 is "default"; 3 is "better", 4 is "best". +* `insize`/`outsize` is the input/output size. +* `millis` is the number of milliseconds used for compression. +* `mb/s` is megabytes (2^20 bytes) per second. + +``` +Silesia Corpus: +http://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip + +This package: +file out level insize outsize millis mb/s +silesia.tar zskp 1 211947520 73821326 634 318.47 +silesia.tar zskp 2 211947520 67655404 1508 133.96 +silesia.tar zskp 3 211947520 64746933 3000 67.37 +silesia.tar zskp 4 211947520 60073508 16926 11.94 + +cgo zstd: +silesia.tar zstd 1 211947520 73605392 543 371.56 +silesia.tar zstd 3 211947520 66793289 864 233.68 +silesia.tar zstd 6 211947520 62916450 1913 105.66 +silesia.tar zstd 9 211947520 60212393 5063 39.92 + +gzip, stdlib/this package: +silesia.tar gzstd 1 211947520 80007735 1498 134.87 +silesia.tar gzkp 1 211947520 80088272 1009 200.31 + +GOB stream of binary data. Highly compressible. +https://files.klauspost.com/compress/gob-stream.7z + +file out level insize outsize millis mb/s +gob-stream zskp 1 1911399616 233948096 3230 564.34 +gob-stream zskp 2 1911399616 203997694 4997 364.73 +gob-stream zskp 3 1911399616 173526523 13435 135.68 +gob-stream zskp 4 1911399616 162195235 47559 38.33 + +gob-stream zstd 1 1911399616 249810424 2637 691.26 +gob-stream zstd 3 1911399616 208192146 3490 522.31 +gob-stream zstd 6 1911399616 193632038 6687 272.56 +gob-stream zstd 9 1911399616 177620386 16175 112.70 + +gob-stream gzstd 1 1911399616 357382013 9046 201.49 +gob-stream gzkp 1 1911399616 359136669 4885 373.08 + +The test data for the Large Text Compression Benchmark is the first +10^9 bytes of the English Wikipedia dump on Mar. 3, 2006. +http://mattmahoney.net/dc/textdata.html + +file out level insize outsize millis mb/s +enwik9 zskp 1 1000000000 343833605 3687 258.64 +enwik9 zskp 2 1000000000 317001237 7672 124.29 +enwik9 zskp 3 1000000000 291915823 15923 59.89 +enwik9 zskp 4 1000000000 261710291 77697 12.27 + +enwik9 zstd 1 1000000000 358072021 3110 306.65 +enwik9 zstd 3 1000000000 313734672 4784 199.35 +enwik9 zstd 6 1000000000 295138875 10290 92.68 +enwik9 zstd 9 1000000000 278348700 28549 33.40 + +enwik9 gzstd 1 1000000000 382578136 8608 110.78 +enwik9 gzkp 1 1000000000 382781160 5628 169.45 + +Highly compressible JSON file. +https://files.klauspost.com/compress/github-june-2days-2019.json.zst + +file out level insize outsize millis mb/s +github-june-2days-2019.json zskp 1 6273951764 697439532 9789 611.17 +github-june-2days-2019.json zskp 2 6273951764 610876538 18553 322.49 +github-june-2days-2019.json zskp 3 6273951764 517662858 44186 135.41 +github-june-2days-2019.json zskp 4 6273951764 464617114 165373 36.18 + +github-june-2days-2019.json zstd 1 6273951764 766284037 8450 708.00 +github-june-2days-2019.json zstd 3 6273951764 661889476 10927 547.57 +github-june-2days-2019.json zstd 6 6273951764 642756859 22996 260.18 +github-june-2days-2019.json zstd 9 6273951764 601974523 52413 114.16 + +github-june-2days-2019.json gzstd 1 6273951764 1164397768 26793 223.32 +github-june-2days-2019.json gzkp 1 6273951764 1120631856 17693 338.16 + +VM Image, Linux mint with a few installed applications: +https://files.klauspost.com/compress/rawstudio-mint14.7z + +file out level insize outsize millis mb/s +rawstudio-mint14.tar zskp 1 8558382592 3718400221 18206 448.29 +rawstudio-mint14.tar zskp 2 8558382592 3326118337 37074 220.15 +rawstudio-mint14.tar zskp 3 8558382592 3163842361 87306 93.49 +rawstudio-mint14.tar zskp 4 8558382592 2970480650 783862 10.41 + +rawstudio-mint14.tar zstd 1 8558382592 3609250104 17136 476.27 +rawstudio-mint14.tar zstd 3 8558382592 3341679997 29262 278.92 +rawstudio-mint14.tar zstd 6 8558382592 3235846406 77904 104.77 +rawstudio-mint14.tar zstd 9 8558382592 3160778861 140946 57.91 + +rawstudio-mint14.tar gzstd 1 8558382592 3926234992 51345 158.96 +rawstudio-mint14.tar gzkp 1 8558382592 3960117298 36722 222.26 + +CSV data: +https://files.klauspost.com/compress/nyc-taxi-data-10M.csv.zst + +file out level insize outsize millis mb/s +nyc-taxi-data-10M.csv zskp 1 3325605752 641319332 9462 335.17 +nyc-taxi-data-10M.csv zskp 2 3325605752 588976126 17570 180.50 +nyc-taxi-data-10M.csv zskp 3 3325605752 529329260 32432 97.79 +nyc-taxi-data-10M.csv zskp 4 3325605752 474949772 138025 22.98 + +nyc-taxi-data-10M.csv zstd 1 3325605752 687399637 8233 385.18 +nyc-taxi-data-10M.csv zstd 3 3325605752 598514411 10065 315.07 +nyc-taxi-data-10M.csv zstd 6 3325605752 570522953 20038 158.27 +nyc-taxi-data-10M.csv zstd 9 3325605752 517554797 64565 49.12 + +nyc-taxi-data-10M.csv gzstd 1 3325605752 928654908 21270 149.11 +nyc-taxi-data-10M.csv gzkp 1 3325605752 922273214 13929 227.68 +``` + +## Decompressor + +Status: STABLE - there may still be subtle bugs, but a wide variety of content has been tested. + +This library is being continuously [fuzz-tested](https://github.com/klauspost/compress-fuzz), +kindly supplied by [fuzzit.dev](https://fuzzit.dev/). +The main purpose of the fuzz testing is to ensure that it is not possible to crash the decoder, +or run it past its limits with ANY input provided. + +### Usage + +The package has been designed for two main usages, big streams of data and smaller in-memory buffers. +There are two main usages of the package for these. Both of them are accessed by creating a `Decoder`. + +For streaming use a simple setup could look like this: + +```Go +import "github.com/klauspost/compress/zstd" + +func Decompress(in io.Reader, out io.Writer) error { + d, err := zstd.NewReader(in) + if err != nil { + return err + } + defer d.Close() + + // Copy content... + _, err = io.Copy(out, d) + return err +} +``` + +It is important to use the "Close" function when you no longer need the Reader to stop running goroutines, +when running with default settings. +Goroutines will exit once an error has been returned, including `io.EOF` at the end of a stream. + +Streams are decoded concurrently in 4 asynchronous stages to give the best possible throughput. +However, if you prefer synchronous decompression, use `WithDecoderConcurrency(1)` which will decompress data +as it is being requested only. + +For decoding buffers, it could look something like this: + +```Go +import "github.com/klauspost/compress/zstd" + +// Create a reader that caches decompressors. +// For this operation type we supply a nil Reader. +var decoder, _ = zstd.NewReader(nil, zstd.WithDecoderConcurrency(0)) + +// Decompress a buffer. We don't supply a destination buffer, +// so it will be allocated by the decoder. +func Decompress(src []byte) ([]byte, error) { + return decoder.DecodeAll(src, nil) +} +``` + +Both of these cases should provide the functionality needed. +The decoder can be used for *concurrent* decompression of multiple buffers. +By default 4 decompressors will be created. + +It will only allow a certain number of concurrent operations to run. +To tweak that yourself use the `WithDecoderConcurrency(n)` option when creating the decoder. +It is possible to use `WithDecoderConcurrency(0)` to create GOMAXPROCS decoders. + +### Dictionaries + +Data compressed with [dictionaries](https://github.com/facebook/zstd#the-case-for-small-data-compression) can be decompressed. + +Dictionaries are added individually to Decoders. +Dictionaries are generated by the `zstd --train` command and contains an initial state for the decoder. +To add a dictionary use the `WithDecoderDicts(dicts ...[]byte)` option with the dictionary data. +Several dictionaries can be added at once. + +The dictionary will be used automatically for the data that specifies them. +A re-used Decoder will still contain the dictionaries registered. + +When registering multiple dictionaries with the same ID, the last one will be used. + +It is possible to use dictionaries when compressing data. + +To enable a dictionary use `WithEncoderDict(dict []byte)`. Here only one dictionary will be used +and it will likely be used even if it doesn't improve compression. + +The used dictionary must be used to decompress the content. + +For any real gains, the dictionary should be built with similar data. +If an unsuitable dictionary is used the output may be slightly larger than using no dictionary. +Use the [zstd commandline tool](https://github.com/facebook/zstd/releases) to build a dictionary from sample data. +For information see [zstd dictionary information](https://github.com/facebook/zstd#the-case-for-small-data-compression). + +For now there is a fixed startup performance penalty for compressing content with dictionaries. +This will likely be improved over time. Just be aware to test performance when implementing. + +### Allocation-less operation + +The decoder has been designed to operate without allocations after a warmup. + +This means that you should *store* the decoder for best performance. +To re-use a stream decoder, use the `Reset(r io.Reader) error` to switch to another stream. +A decoder can safely be re-used even if the previous stream failed. + +To release the resources, you must call the `Close()` function on a decoder. +After this it can *no longer be reused*, but all running goroutines will be stopped. +So you *must* use this if you will no longer need the Reader. + +For decompressing smaller buffers a single decoder can be used. +When decoding buffers, you can supply a destination slice with length 0 and your expected capacity. +In this case no unneeded allocations should be made. + +### Concurrency + +The buffer decoder does everything on the same goroutine and does nothing concurrently. +It can however decode several buffers concurrently. Use `WithDecoderConcurrency(n)` to limit that. + +The stream decoder will create goroutines that: + +1) Reads input and splits the input into blocks. +2) Decompression of literals. +3) Decompression of sequences. +4) Reconstruction of output stream. + +So effectively this also means the decoder will "read ahead" and prepare data to always be available for output. + +The concurrency level will, for streams, determine how many blocks ahead the compression will start. + +Since "blocks" are quite dependent on the output of the previous block stream decoding will only have limited concurrency. + +In practice this means that concurrency is often limited to utilizing about 3 cores effectively. + +### Benchmarks + +The first two are streaming decodes and the last are smaller inputs. + +Running on AMD Ryzen 9 3950X 16-Core Processor. AMD64 assembly used. + +``` +BenchmarkDecoderSilesia-32 5 206878840 ns/op 1024.50 MB/s 49808 B/op 43 allocs/op +BenchmarkDecoderEnwik9-32 1 1271809000 ns/op 786.28 MB/s 72048 B/op 52 allocs/op + +Concurrent blocks, performance: + +BenchmarkDecoder_DecodeAllParallel/kppkn.gtb.zst-32 67356 17857 ns/op 10321.96 MB/s 22.48 pct 102 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/geo.protodata.zst-32 266656 4421 ns/op 26823.21 MB/s 11.89 pct 19 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/plrabn12.txt.zst-32 20992 56842 ns/op 8477.17 MB/s 39.90 pct 754 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/lcet10.txt.zst-32 27456 43932 ns/op 9714.01 MB/s 33.27 pct 524 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/asyoulik.txt.zst-32 78432 15047 ns/op 8319.15 MB/s 40.34 pct 66 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/alice29.txt.zst-32 65800 18436 ns/op 8249.63 MB/s 37.75 pct 88 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/html_x_4.zst-32 102993 11523 ns/op 35546.09 MB/s 3.637 pct 143 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/paper-100k.pdf.zst-32 1000000 1070 ns/op 95720.98 MB/s 80.53 pct 3 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/fireworks.jpeg.zst-32 749802 1752 ns/op 70272.35 MB/s 100.0 pct 5 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/urls.10K.zst-32 22640 52934 ns/op 13263.37 MB/s 26.25 pct 1014 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/html.zst-32 226412 5232 ns/op 19572.27 MB/s 14.49 pct 20 B/op 0 allocs/op +BenchmarkDecoder_DecodeAllParallel/comp-data.bin.zst-32 923041 1276 ns/op 3194.71 MB/s 31.26 pct 0 B/op 0 allocs/op +``` + +This reflects the performance around May 2022, but this may be out of date. + +## Zstd inside ZIP files + +It is possible to use zstandard to compress individual files inside zip archives. +While this isn't widely supported it can be useful for internal files. + +To support the compression and decompression of these files you must register a compressor and decompressor. + +It is highly recommended registering the (de)compressors on individual zip Reader/Writer and NOT +use the global registration functions. The main reason for this is that 2 registrations from +different packages will result in a panic. + +It is a good idea to only have a single compressor and decompressor, since they can be used for multiple zip +files concurrently, and using a single instance will allow reusing some resources. + +See [this example](https://pkg.go.dev/github.com/klauspost/compress/zstd#example-ZipCompressor) for +how to compress and decompress files inside zip archives. + +# Contributions + +Contributions are always welcome. +For new features/fixes, remember to add tests and for performance enhancements include benchmarks. + +For general feedback and experience reports, feel free to open an issue or write me on [Twitter](https://twitter.com/sh0dan). + +This package includes the excellent [`github.com/cespare/xxhash`](https://github.com/cespare/xxhash) package Copyright (c) 2016 Caleb Spare. diff --git a/vendor/github.com/klauspost/compress/zstd/bitreader.go b/vendor/github.com/klauspost/compress/zstd/bitreader.go new file mode 100644 index 000000000..25ca98394 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/bitreader.go @@ -0,0 +1,136 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "encoding/binary" + "errors" + "fmt" + "io" + "math/bits" +) + +// bitReader reads a bitstream in reverse. +// The last set bit indicates the start of the stream and is used +// for aligning the input. +type bitReader struct { + in []byte + value uint64 // Maybe use [16]byte, but shifting is awkward. + bitsRead uint8 +} + +// init initializes and resets the bit reader. +func (b *bitReader) init(in []byte) error { + if len(in) < 1 { + return errors.New("corrupt stream: too short") + } + b.in = in + // The highest bit of the last byte indicates where to start + v := in[len(in)-1] + if v == 0 { + return errors.New("corrupt stream, did not find end of stream") + } + b.bitsRead = 64 + b.value = 0 + if len(in) >= 8 { + b.fillFastStart() + } else { + b.fill() + b.fill() + } + b.bitsRead += 8 - uint8(highBits(uint32(v))) + return nil +} + +// getBits will return n bits. n can be 0. +func (b *bitReader) getBits(n uint8) int { + if n == 0 /*|| b.bitsRead >= 64 */ { + return 0 + } + return int(b.get32BitsFast(n)) +} + +// get32BitsFast requires that at least one bit is requested every time. +// There are no checks if the buffer is filled. +func (b *bitReader) get32BitsFast(n uint8) uint32 { + const regMask = 64 - 1 + v := uint32((b.value << (b.bitsRead & regMask)) >> ((regMask + 1 - n) & regMask)) + b.bitsRead += n + return v +} + +// fillFast() will make sure at least 32 bits are available. +// There must be at least 4 bytes available. +func (b *bitReader) fillFast() { + if b.bitsRead < 32 { + return + } + v := b.in[len(b.in)-4:] + b.in = b.in[:len(b.in)-4] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value = (b.value << 32) | uint64(low) + b.bitsRead -= 32 +} + +// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. +func (b *bitReader) fillFastStart() { + v := b.in[len(b.in)-8:] + b.in = b.in[:len(b.in)-8] + b.value = binary.LittleEndian.Uint64(v) + b.bitsRead = 0 +} + +// fill() will make sure at least 32 bits are available. +func (b *bitReader) fill() { + if b.bitsRead < 32 { + return + } + if len(b.in) >= 4 { + v := b.in[len(b.in)-4:] + b.in = b.in[:len(b.in)-4] + low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) + b.value = (b.value << 32) | uint64(low) + b.bitsRead -= 32 + return + } + + b.bitsRead -= uint8(8 * len(b.in)) + for len(b.in) > 0 { + b.value = (b.value << 8) | uint64(b.in[len(b.in)-1]) + b.in = b.in[:len(b.in)-1] + } +} + +// finished returns true if all bits have been read from the bit stream. +func (b *bitReader) finished() bool { + return len(b.in) == 0 && b.bitsRead >= 64 +} + +// overread returns true if more bits have been requested than is on the stream. +func (b *bitReader) overread() bool { + return b.bitsRead > 64 +} + +// remain returns the number of bits remaining. +func (b *bitReader) remain() uint { + return 8*uint(len(b.in)) + 64 - uint(b.bitsRead) +} + +// close the bitstream and returns an error if out-of-buffer reads occurred. +func (b *bitReader) close() error { + // Release reference. + b.in = nil + if !b.finished() { + return fmt.Errorf("%d extra bits on block, should be 0", b.remain()) + } + if b.bitsRead > 64 { + return io.ErrUnexpectedEOF + } + return nil +} + +func highBits(val uint32) (n uint32) { + return uint32(bits.Len32(val) - 1) +} diff --git a/vendor/github.com/klauspost/compress/zstd/bitwriter.go b/vendor/github.com/klauspost/compress/zstd/bitwriter.go new file mode 100644 index 000000000..1952f175b --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/bitwriter.go @@ -0,0 +1,112 @@ +// Copyright 2018 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. + +package zstd + +// bitWriter will write bits. +// First bit will be LSB of the first byte of output. +type bitWriter struct { + bitContainer uint64 + nBits uint8 + out []byte +} + +// bitMask16 is bitmasks. Has extra to avoid bounds check. +var bitMask16 = [32]uint16{ + 0, 1, 3, 7, 0xF, 0x1F, + 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, + 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, + 0xFFFF, 0xFFFF} /* up to 16 bits */ + +var bitMask32 = [32]uint32{ + 0, 1, 3, 7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, + 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, + 0x1ffff, 0x3ffff, 0x7FFFF, 0xfFFFF, 0x1fFFFF, 0x3fFFFF, 0x7fFFFF, 0xffFFFF, + 0x1ffFFFF, 0x3ffFFFF, 0x7ffFFFF, 0xfffFFFF, 0x1fffFFFF, 0x3fffFFFF, 0x7fffFFFF, +} // up to 32 bits + +// addBits16NC will add up to 16 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16NC(value uint16, bits uint8) { + b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) + b.nBits += bits +} + +// addBits32NC will add up to 31 bits. +// It will not check if there is space for them, +// so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits32NC(value uint32, bits uint8) { + b.bitContainer |= uint64(value&bitMask32[bits&31]) << (b.nBits & 63) + b.nBits += bits +} + +// addBits64NC will add up to 64 bits. +// There must be space for 32 bits. +func (b *bitWriter) addBits64NC(value uint64, bits uint8) { + if bits <= 31 { + b.addBits32Clean(uint32(value), bits) + return + } + b.addBits32Clean(uint32(value), 32) + b.flush32() + b.addBits32Clean(uint32(value>>32), bits-32) +} + +// addBits32Clean will add up to 32 bits. +// It will not check if there is space for them. +// The input must not contain more bits than specified. +func (b *bitWriter) addBits32Clean(value uint32, bits uint8) { + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. +// It will not check if there is space for them, so the caller must ensure that it has flushed recently. +func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { + b.bitContainer |= uint64(value) << (b.nBits & 63) + b.nBits += bits +} + +// flush32 will flush out, so there are at least 32 bits available for writing. +func (b *bitWriter) flush32() { + if b.nBits < 32 { + return + } + b.out = append(b.out, + byte(b.bitContainer), + byte(b.bitContainer>>8), + byte(b.bitContainer>>16), + byte(b.bitContainer>>24)) + b.nBits -= 32 + b.bitContainer >>= 32 +} + +// flushAlign will flush remaining full bytes and align to next byte boundary. +func (b *bitWriter) flushAlign() { + nbBytes := (b.nBits + 7) >> 3 + for i := uint8(0); i < nbBytes; i++ { + b.out = append(b.out, byte(b.bitContainer>>(i*8))) + } + b.nBits = 0 + b.bitContainer = 0 +} + +// close will write the alignment bit and write the final byte(s) +// to the output. +func (b *bitWriter) close() { + // End mark + b.addBits16Clean(1, 1) + // flush until next byte. + b.flushAlign() +} + +// reset and continue writing by appending to out. +func (b *bitWriter) reset(out []byte) { + b.bitContainer = 0 + b.nBits = 0 + b.out = out +} diff --git a/vendor/github.com/klauspost/compress/zstd/blockdec.go b/vendor/github.com/klauspost/compress/zstd/blockdec.go new file mode 100644 index 000000000..9f17ce601 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/blockdec.go @@ -0,0 +1,726 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "io" + "os" + "path/filepath" + "sync" + + "github.com/klauspost/compress/huff0" + "github.com/klauspost/compress/zstd/internal/xxhash" +) + +type blockType uint8 + +//go:generate stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex + +const ( + blockTypeRaw blockType = iota + blockTypeRLE + blockTypeCompressed + blockTypeReserved +) + +type literalsBlockType uint8 + +const ( + literalsBlockRaw literalsBlockType = iota + literalsBlockRLE + literalsBlockCompressed + literalsBlockTreeless +) + +const ( + // maxCompressedBlockSize is the biggest allowed compressed block size (128KB) + maxCompressedBlockSize = 128 << 10 + + compressedBlockOverAlloc = 16 + maxCompressedBlockSizeAlloc = 128<<10 + compressedBlockOverAlloc + + // Maximum possible block size (all Raw+Uncompressed). + maxBlockSize = (1 << 21) - 1 + + maxMatchLen = 131074 + maxSequences = 0x7f00 + 0xffff + + // We support slightly less than the reference decoder to be able to + // use ints on 32 bit archs. + maxOffsetBits = 30 +) + +var ( + huffDecoderPool = sync.Pool{New: func() interface{} { + return &huff0.Scratch{} + }} + + fseDecoderPool = sync.Pool{New: func() interface{} { + return &fseDecoder{} + }} +) + +type blockDec struct { + // Raw source data of the block. + data []byte + dataStorage []byte + + // Destination of the decoded data. + dst []byte + + // Buffer for literals data. + literalBuf []byte + + // Window size of the block. + WindowSize uint64 + + err error + + // Check against this crc, if hasCRC is true. + checkCRC uint32 + hasCRC bool + + // Frame to use for singlethreaded decoding. + // Should not be used by the decoder itself since parent may be another frame. + localFrame *frameDec + + sequence []seqVals + + async struct { + newHist *history + literals []byte + seqData []byte + seqSize int // Size of uncompressed sequences + fcs uint64 + } + + // Block is RLE, this is the size. + RLESize uint32 + + Type blockType + + // Is this the last block of a frame? + Last bool + + // Use less memory + lowMem bool +} + +func (b *blockDec) String() string { + if b == nil { + return "" + } + return fmt.Sprintf("Steam Size: %d, Type: %v, Last: %t, Window: %d", len(b.data), b.Type, b.Last, b.WindowSize) +} + +func newBlockDec(lowMem bool) *blockDec { + b := blockDec{ + lowMem: lowMem, + } + return &b +} + +// reset will reset the block. +// Input must be a start of a block and will be at the end of the block when returned. +func (b *blockDec) reset(br byteBuffer, windowSize uint64) error { + b.WindowSize = windowSize + tmp, err := br.readSmall(3) + if err != nil { + println("Reading block header:", err) + return err + } + bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16) + b.Last = bh&1 != 0 + b.Type = blockType((bh >> 1) & 3) + // find size. + cSize := int(bh >> 3) + maxSize := maxCompressedBlockSizeAlloc + switch b.Type { + case blockTypeReserved: + return ErrReservedBlockType + case blockTypeRLE: + if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) { + if debugDecoder { + printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b) + } + return ErrWindowSizeExceeded + } + b.RLESize = uint32(cSize) + if b.lowMem { + maxSize = cSize + } + cSize = 1 + case blockTypeCompressed: + if debugDecoder { + println("Data size on stream:", cSize) + } + b.RLESize = 0 + maxSize = maxCompressedBlockSizeAlloc + if windowSize < maxCompressedBlockSize && b.lowMem { + maxSize = int(windowSize) + compressedBlockOverAlloc + } + if cSize > maxCompressedBlockSize || uint64(cSize) > b.WindowSize { + if debugDecoder { + printf("compressed block too big: csize:%d block: %+v\n", uint64(cSize), b) + } + return ErrCompressedSizeTooBig + } + // Empty compressed blocks must at least be 2 bytes + // for Literals_Block_Type and one for Sequences_Section_Header. + if cSize < 2 { + return ErrBlockTooSmall + } + case blockTypeRaw: + if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) { + if debugDecoder { + printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b) + } + return ErrWindowSizeExceeded + } + + b.RLESize = 0 + // We do not need a destination for raw blocks. + maxSize = -1 + default: + panic("Invalid block type") + } + + // Read block data. + if _, ok := br.(*byteBuf); !ok && cap(b.dataStorage) < cSize { + // byteBuf doesn't need a destination buffer. + if b.lowMem || cSize > maxCompressedBlockSize { + b.dataStorage = make([]byte, 0, cSize+compressedBlockOverAlloc) + } else { + b.dataStorage = make([]byte, 0, maxCompressedBlockSizeAlloc) + } + } + b.data, err = br.readBig(cSize, b.dataStorage) + if err != nil { + if debugDecoder { + println("Reading block:", err, "(", cSize, ")", len(b.data)) + printf("%T", br) + } + return err + } + if cap(b.dst) <= maxSize { + b.dst = make([]byte, 0, maxSize+1) + } + return nil +} + +// sendEOF will make the decoder send EOF on this frame. +func (b *blockDec) sendErr(err error) { + b.Last = true + b.Type = blockTypeReserved + b.err = err +} + +// Close will release resources. +// Closed blockDec cannot be reset. +func (b *blockDec) Close() { +} + +// decodeBuf +func (b *blockDec) decodeBuf(hist *history) error { + switch b.Type { + case blockTypeRLE: + if cap(b.dst) < int(b.RLESize) { + if b.lowMem { + b.dst = make([]byte, b.RLESize) + } else { + b.dst = make([]byte, maxCompressedBlockSize) + } + } + b.dst = b.dst[:b.RLESize] + v := b.data[0] + for i := range b.dst { + b.dst[i] = v + } + hist.appendKeep(b.dst) + return nil + case blockTypeRaw: + hist.appendKeep(b.data) + return nil + case blockTypeCompressed: + saved := b.dst + // Append directly to history + if hist.ignoreBuffer == 0 { + b.dst = hist.b + hist.b = nil + } else { + b.dst = b.dst[:0] + } + err := b.decodeCompressed(hist) + if debugDecoder { + println("Decompressed to total", len(b.dst), "bytes, hash:", xxhash.Sum64(b.dst), "error:", err) + } + if hist.ignoreBuffer == 0 { + hist.b = b.dst + b.dst = saved + } else { + hist.appendKeep(b.dst) + } + return err + case blockTypeReserved: + // Used for returning errors. + return b.err + default: + panic("Invalid block type") + } +} + +func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err error) { + // There must be at least one byte for Literals_Block_Type and one for Sequences_Section_Header + if len(in) < 2 { + return in, ErrBlockTooSmall + } + + litType := literalsBlockType(in[0] & 3) + var litRegenSize int + var litCompSize int + sizeFormat := (in[0] >> 2) & 3 + var fourStreams bool + var literals []byte + switch litType { + case literalsBlockRaw, literalsBlockRLE: + switch sizeFormat { + case 0, 2: + // Regenerated_Size uses 5 bits (0-31). Literals_Section_Header uses 1 byte. + litRegenSize = int(in[0] >> 3) + in = in[1:] + case 1: + // Regenerated_Size uses 12 bits (0-4095). Literals_Section_Header uses 2 bytes. + litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) + in = in[2:] + case 3: + // Regenerated_Size uses 20 bits (0-1048575). Literals_Section_Header uses 3 bytes. + if len(in) < 3 { + println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) + return in, ErrBlockTooSmall + } + litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) + (int(in[2]) << 12) + in = in[3:] + } + case literalsBlockCompressed, literalsBlockTreeless: + switch sizeFormat { + case 0, 1: + // Both Regenerated_Size and Compressed_Size use 10 bits (0-1023). + if len(in) < 3 { + println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) + return in, ErrBlockTooSmall + } + n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + litRegenSize = int(n & 1023) + litCompSize = int(n >> 10) + fourStreams = sizeFormat == 1 + in = in[3:] + case 2: + fourStreams = true + if len(in) < 4 { + println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) + return in, ErrBlockTooSmall + } + n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) + litRegenSize = int(n & 16383) + litCompSize = int(n >> 14) + in = in[4:] + case 3: + fourStreams = true + if len(in) < 5 { + println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) + return in, ErrBlockTooSmall + } + n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) + (uint64(in[4]) << 28) + litRegenSize = int(n & 262143) + litCompSize = int(n >> 18) + in = in[5:] + } + } + if debugDecoder { + println("literals type:", litType, "litRegenSize:", litRegenSize, "litCompSize:", litCompSize, "sizeFormat:", sizeFormat, "4X:", fourStreams) + } + if litRegenSize > int(b.WindowSize) || litRegenSize > maxCompressedBlockSize { + return in, ErrWindowSizeExceeded + } + + switch litType { + case literalsBlockRaw: + if len(in) < litRegenSize { + println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litRegenSize) + return in, ErrBlockTooSmall + } + literals = in[:litRegenSize] + in = in[litRegenSize:] + //printf("Found %d uncompressed literals\n", litRegenSize) + case literalsBlockRLE: + if len(in) < 1 { + println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", 1) + return in, ErrBlockTooSmall + } + if cap(b.literalBuf) < litRegenSize { + if b.lowMem { + b.literalBuf = make([]byte, litRegenSize, litRegenSize+compressedBlockOverAlloc) + } else { + b.literalBuf = make([]byte, litRegenSize, maxCompressedBlockSize+compressedBlockOverAlloc) + } + } + literals = b.literalBuf[:litRegenSize] + v := in[0] + for i := range literals { + literals[i] = v + } + in = in[1:] + if debugDecoder { + printf("Found %d RLE compressed literals\n", litRegenSize) + } + case literalsBlockTreeless: + if len(in) < litCompSize { + println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize) + return in, ErrBlockTooSmall + } + // Store compressed literals, so we defer decoding until we get history. + literals = in[:litCompSize] + in = in[litCompSize:] + if debugDecoder { + printf("Found %d compressed literals\n", litCompSize) + } + huff := hist.huffTree + if huff == nil { + return in, errors.New("literal block was treeless, but no history was defined") + } + // Ensure we have space to store it. + if cap(b.literalBuf) < litRegenSize { + if b.lowMem { + b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc) + } else { + b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc) + } + } + var err error + // Use our out buffer. + huff.MaxDecodedSize = litRegenSize + if fourStreams { + literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals) + } else { + literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals) + } + // Make sure we don't leak our literals buffer + if err != nil { + println("decompressing literals:", err) + return in, err + } + if len(literals) != litRegenSize { + return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals)) + } + + case literalsBlockCompressed: + if len(in) < litCompSize { + println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize) + return in, ErrBlockTooSmall + } + literals = in[:litCompSize] + in = in[litCompSize:] + // Ensure we have space to store it. + if cap(b.literalBuf) < litRegenSize { + if b.lowMem { + b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc) + } else { + b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc) + } + } + huff := hist.huffTree + if huff == nil || (hist.dict != nil && huff == hist.dict.litEnc) { + huff = huffDecoderPool.Get().(*huff0.Scratch) + if huff == nil { + huff = &huff0.Scratch{} + } + } + var err error + if debugDecoder { + println("huff table input:", len(literals), "CRC:", crc32.ChecksumIEEE(literals)) + } + huff, literals, err = huff0.ReadTable(literals, huff) + if err != nil { + println("reading huffman table:", err) + return in, err + } + hist.huffTree = huff + huff.MaxDecodedSize = litRegenSize + // Use our out buffer. + if fourStreams { + literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals) + } else { + literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals) + } + if err != nil { + println("decoding compressed literals:", err) + return in, err + } + // Make sure we don't leak our literals buffer + if len(literals) != litRegenSize { + return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals)) + } + // Re-cap to get extra size. + literals = b.literalBuf[:len(literals)] + if debugDecoder { + printf("Decompressed %d literals into %d bytes\n", litCompSize, litRegenSize) + } + } + hist.decoders.literals = literals + return in, nil +} + +// decodeCompressed will start decompressing a block. +func (b *blockDec) decodeCompressed(hist *history) error { + in := b.data + in, err := b.decodeLiterals(in, hist) + if err != nil { + return err + } + err = b.prepareSequences(in, hist) + if err != nil { + return err + } + if hist.decoders.nSeqs == 0 { + b.dst = append(b.dst, hist.decoders.literals...) + return nil + } + before := len(hist.decoders.out) + err = hist.decoders.decodeSync(hist.b[hist.ignoreBuffer:]) + if err != nil { + return err + } + if hist.decoders.maxSyncLen > 0 { + hist.decoders.maxSyncLen += uint64(before) + hist.decoders.maxSyncLen -= uint64(len(hist.decoders.out)) + } + b.dst = hist.decoders.out + hist.recentOffsets = hist.decoders.prevOffset + return nil +} + +func (b *blockDec) prepareSequences(in []byte, hist *history) (err error) { + if debugDecoder { + printf("prepareSequences: %d byte(s) input\n", len(in)) + } + // Decode Sequences + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#sequences-section + if len(in) < 1 { + return ErrBlockTooSmall + } + var nSeqs int + seqHeader := in[0] + switch { + case seqHeader < 128: + nSeqs = int(seqHeader) + in = in[1:] + case seqHeader < 255: + if len(in) < 2 { + return ErrBlockTooSmall + } + nSeqs = int(seqHeader-128)<<8 | int(in[1]) + in = in[2:] + case seqHeader == 255: + if len(in) < 3 { + return ErrBlockTooSmall + } + nSeqs = 0x7f00 + int(in[1]) + (int(in[2]) << 8) + in = in[3:] + } + if nSeqs == 0 && len(in) != 0 { + // When no sequences, there should not be any more data... + if debugDecoder { + printf("prepareSequences: 0 sequences, but %d byte(s) left on stream\n", len(in)) + } + return ErrUnexpectedBlockSize + } + + var seqs = &hist.decoders + seqs.nSeqs = nSeqs + if nSeqs > 0 { + if len(in) < 1 { + return ErrBlockTooSmall + } + br := byteReader{b: in, off: 0} + compMode := br.Uint8() + br.advance(1) + if debugDecoder { + printf("Compression modes: 0b%b", compMode) + } + for i := uint(0); i < 3; i++ { + mode := seqCompMode((compMode >> (6 - i*2)) & 3) + if debugDecoder { + println("Table", tableIndex(i), "is", mode) + } + var seq *sequenceDec + switch tableIndex(i) { + case tableLiteralLengths: + seq = &seqs.litLengths + case tableOffsets: + seq = &seqs.offsets + case tableMatchLengths: + seq = &seqs.matchLengths + default: + panic("unknown table") + } + switch mode { + case compModePredefined: + if seq.fse != nil && !seq.fse.preDefined { + fseDecoderPool.Put(seq.fse) + } + seq.fse = &fsePredef[i] + case compModeRLE: + if br.remain() < 1 { + return ErrBlockTooSmall + } + v := br.Uint8() + br.advance(1) + if seq.fse == nil || seq.fse.preDefined { + seq.fse = fseDecoderPool.Get().(*fseDecoder) + } + symb, err := decSymbolValue(v, symbolTableX[i]) + if err != nil { + printf("RLE Transform table (%v) error: %v", tableIndex(i), err) + return err + } + seq.fse.setRLE(symb) + if debugDecoder { + printf("RLE set to 0x%x, code: %v", symb, v) + } + case compModeFSE: + println("Reading table for", tableIndex(i)) + if seq.fse == nil || seq.fse.preDefined { + seq.fse = fseDecoderPool.Get().(*fseDecoder) + } + err := seq.fse.readNCount(&br, uint16(maxTableSymbol[i])) + if err != nil { + println("Read table error:", err) + return err + } + err = seq.fse.transform(symbolTableX[i]) + if err != nil { + println("Transform table error:", err) + return err + } + if debugDecoder { + println("Read table ok", "symbolLen:", seq.fse.symbolLen) + } + case compModeRepeat: + seq.repeat = true + } + if br.overread() { + return io.ErrUnexpectedEOF + } + } + in = br.unread() + } + if debugDecoder { + println("Literals:", len(seqs.literals), "hash:", xxhash.Sum64(seqs.literals), "and", seqs.nSeqs, "sequences.") + } + + if nSeqs == 0 { + if len(b.sequence) > 0 { + b.sequence = b.sequence[:0] + } + return nil + } + br := seqs.br + if br == nil { + br = &bitReader{} + } + if err := br.init(in); err != nil { + return err + } + + if err := seqs.initialize(br, hist, b.dst); err != nil { + println("initializing sequences:", err) + return err + } + // Extract blocks... + if false && hist.dict == nil { + fatalErr := func(err error) { + if err != nil { + panic(err) + } + } + fn := fmt.Sprintf("n-%d-lits-%d-prev-%d-%d-%d-win-%d.blk", hist.decoders.nSeqs, len(hist.decoders.literals), hist.recentOffsets[0], hist.recentOffsets[1], hist.recentOffsets[2], hist.windowSize) + var buf bytes.Buffer + fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.litLengths.fse)) + fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.matchLengths.fse)) + fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.offsets.fse)) + buf.Write(in) + os.WriteFile(filepath.Join("testdata", "seqs", fn), buf.Bytes(), os.ModePerm) + } + + return nil +} + +func (b *blockDec) decodeSequences(hist *history) error { + if cap(b.sequence) < hist.decoders.nSeqs { + if b.lowMem { + b.sequence = make([]seqVals, 0, hist.decoders.nSeqs) + } else { + b.sequence = make([]seqVals, 0, 0x7F00+0xffff) + } + } + b.sequence = b.sequence[:hist.decoders.nSeqs] + if hist.decoders.nSeqs == 0 { + hist.decoders.seqSize = len(hist.decoders.literals) + return nil + } + hist.decoders.windowSize = hist.windowSize + hist.decoders.prevOffset = hist.recentOffsets + + err := hist.decoders.decode(b.sequence) + hist.recentOffsets = hist.decoders.prevOffset + return err +} + +func (b *blockDec) executeSequences(hist *history) error { + hbytes := hist.b + if len(hbytes) > hist.windowSize { + hbytes = hbytes[len(hbytes)-hist.windowSize:] + // We do not need history anymore. + if hist.dict != nil { + hist.dict.content = nil + } + } + hist.decoders.windowSize = hist.windowSize + hist.decoders.out = b.dst[:0] + err := hist.decoders.execute(b.sequence, hbytes) + if err != nil { + return err + } + return b.updateHistory(hist) +} + +func (b *blockDec) updateHistory(hist *history) error { + if len(b.data) > maxCompressedBlockSize { + return fmt.Errorf("compressed block size too large (%d)", len(b.data)) + } + // Set output and release references. + b.dst = hist.decoders.out + hist.recentOffsets = hist.decoders.prevOffset + + if b.Last { + // if last block we don't care about history. + println("Last block, no history returned") + hist.b = hist.b[:0] + return nil + } else { + hist.append(b.dst) + if debugDecoder { + println("Finished block with ", len(b.sequence), "sequences. Added", len(b.dst), "to history, now length", len(hist.b)) + } + } + hist.decoders.out, hist.decoders.literals = nil, nil + + return nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/blockenc.go b/vendor/github.com/klauspost/compress/zstd/blockenc.go new file mode 100644 index 000000000..2cfe925ad --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/blockenc.go @@ -0,0 +1,889 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "errors" + "fmt" + "math" + "math/bits" + + "github.com/klauspost/compress/huff0" +) + +type blockEnc struct { + size int + literals []byte + sequences []seq + coders seqCoders + litEnc *huff0.Scratch + dictLitEnc *huff0.Scratch + wr bitWriter + + extraLits int + output []byte + recentOffsets [3]uint32 + prevRecentOffsets [3]uint32 + + last bool + lowMem bool +} + +// init should be used once the block has been created. +// If called more than once, the effect is the same as calling reset. +func (b *blockEnc) init() { + if b.lowMem { + // 1K literals + if cap(b.literals) < 1<<10 { + b.literals = make([]byte, 0, 1<<10) + } + const defSeqs = 20 + if cap(b.sequences) < defSeqs { + b.sequences = make([]seq, 0, defSeqs) + } + // 1K + if cap(b.output) < 1<<10 { + b.output = make([]byte, 0, 1<<10) + } + } else { + if cap(b.literals) < maxCompressedBlockSize { + b.literals = make([]byte, 0, maxCompressedBlockSize) + } + const defSeqs = 2000 + if cap(b.sequences) < defSeqs { + b.sequences = make([]seq, 0, defSeqs) + } + if cap(b.output) < maxCompressedBlockSize { + b.output = make([]byte, 0, maxCompressedBlockSize) + } + } + + if b.coders.mlEnc == nil { + b.coders.mlEnc = &fseEncoder{} + b.coders.mlPrev = &fseEncoder{} + b.coders.ofEnc = &fseEncoder{} + b.coders.ofPrev = &fseEncoder{} + b.coders.llEnc = &fseEncoder{} + b.coders.llPrev = &fseEncoder{} + } + b.litEnc = &huff0.Scratch{WantLogLess: 4} + b.reset(nil) +} + +// initNewEncode can be used to reset offsets and encoders to the initial state. +func (b *blockEnc) initNewEncode() { + b.recentOffsets = [3]uint32{1, 4, 8} + b.litEnc.Reuse = huff0.ReusePolicyNone + b.coders.setPrev(nil, nil, nil) +} + +// reset will reset the block for a new encode, but in the same stream, +// meaning that state will be carried over, but the block content is reset. +// If a previous block is provided, the recent offsets are carried over. +func (b *blockEnc) reset(prev *blockEnc) { + b.extraLits = 0 + b.literals = b.literals[:0] + b.size = 0 + b.sequences = b.sequences[:0] + b.output = b.output[:0] + b.last = false + if prev != nil { + b.recentOffsets = prev.prevRecentOffsets + } + b.dictLitEnc = nil +} + +// reset will reset the block for a new encode, but in the same stream, +// meaning that state will be carried over, but the block content is reset. +// If a previous block is provided, the recent offsets are carried over. +func (b *blockEnc) swapEncoders(prev *blockEnc) { + b.coders.swap(&prev.coders) + b.litEnc, prev.litEnc = prev.litEnc, b.litEnc +} + +// blockHeader contains the information for a block header. +type blockHeader uint32 + +// setLast sets the 'last' indicator on a block. +func (h *blockHeader) setLast(b bool) { + if b { + *h = *h | 1 + } else { + const mask = (1 << 24) - 2 + *h = *h & mask + } +} + +// setSize will store the compressed size of a block. +func (h *blockHeader) setSize(v uint32) { + const mask = 7 + *h = (*h)&mask | blockHeader(v<<3) +} + +// setType sets the block type. +func (h *blockHeader) setType(t blockType) { + const mask = 1 | (((1 << 24) - 1) ^ 7) + *h = (*h & mask) | blockHeader(t<<1) +} + +// appendTo will append the block header to a slice. +func (h blockHeader) appendTo(b []byte) []byte { + return append(b, uint8(h), uint8(h>>8), uint8(h>>16)) +} + +// String returns a string representation of the block. +func (h blockHeader) String() string { + return fmt.Sprintf("Type: %d, Size: %d, Last:%t", (h>>1)&3, h>>3, h&1 == 1) +} + +// literalsHeader contains literals header information. +type literalsHeader uint64 + +// setType can be used to set the type of literal block. +func (h *literalsHeader) setType(t literalsBlockType) { + const mask = math.MaxUint64 - 3 + *h = (*h & mask) | literalsHeader(t) +} + +// setSize can be used to set a single size, for uncompressed and RLE content. +func (h *literalsHeader) setSize(regenLen int) { + inBits := bits.Len32(uint32(regenLen)) + // Only retain 2 bits + const mask = 3 + lh := uint64(*h & mask) + switch { + case inBits < 5: + lh |= (uint64(regenLen) << 3) | (1 << 60) + if debugEncoder { + got := int(lh>>3) & 0xff + if got != regenLen { + panic(fmt.Sprint("litRegenSize = ", regenLen, "(want) != ", got, "(got)")) + } + } + case inBits < 12: + lh |= (1 << 2) | (uint64(regenLen) << 4) | (2 << 60) + case inBits < 20: + lh |= (3 << 2) | (uint64(regenLen) << 4) | (3 << 60) + default: + panic(fmt.Errorf("internal error: block too big (%d)", regenLen)) + } + *h = literalsHeader(lh) +} + +// setSizes will set the size of a compressed literals section and the input length. +func (h *literalsHeader) setSizes(compLen, inLen int, single bool) { + compBits, inBits := bits.Len32(uint32(compLen)), bits.Len32(uint32(inLen)) + // Only retain 2 bits + const mask = 3 + lh := uint64(*h & mask) + switch { + case compBits <= 10 && inBits <= 10: + if !single { + lh |= 1 << 2 + } + lh |= (uint64(inLen) << 4) | (uint64(compLen) << (10 + 4)) | (3 << 60) + if debugEncoder { + const mmask = (1 << 24) - 1 + n := (lh >> 4) & mmask + if int(n&1023) != inLen { + panic(fmt.Sprint("regensize:", int(n&1023), "!=", inLen, inBits)) + } + if int(n>>10) != compLen { + panic(fmt.Sprint("compsize:", int(n>>10), "!=", compLen, compBits)) + } + } + case compBits <= 14 && inBits <= 14: + lh |= (2 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (14 + 4)) | (4 << 60) + if single { + panic("single stream used with more than 10 bits length.") + } + case compBits <= 18 && inBits <= 18: + lh |= (3 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (18 + 4)) | (5 << 60) + if single { + panic("single stream used with more than 10 bits length.") + } + default: + panic("internal error: block too big") + } + *h = literalsHeader(lh) +} + +// appendTo will append the literals header to a byte slice. +func (h literalsHeader) appendTo(b []byte) []byte { + size := uint8(h >> 60) + switch size { + case 1: + b = append(b, uint8(h)) + case 2: + b = append(b, uint8(h), uint8(h>>8)) + case 3: + b = append(b, uint8(h), uint8(h>>8), uint8(h>>16)) + case 4: + b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24)) + case 5: + b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24), uint8(h>>32)) + default: + panic(fmt.Errorf("internal error: literalsHeader has invalid size (%d)", size)) + } + return b +} + +// size returns the output size with currently set values. +func (h literalsHeader) size() int { + return int(h >> 60) +} + +func (h literalsHeader) String() string { + return fmt.Sprintf("Type: %d, SizeFormat: %d, Size: 0x%d, Bytes:%d", literalsBlockType(h&3), (h>>2)&3, h&((1<<60)-1)>>4, h>>60) +} + +// pushOffsets will push the recent offsets to the backup store. +func (b *blockEnc) pushOffsets() { + b.prevRecentOffsets = b.recentOffsets +} + +// pushOffsets will push the recent offsets to the backup store. +func (b *blockEnc) popOffsets() { + b.recentOffsets = b.prevRecentOffsets +} + +// matchOffset will adjust recent offsets and return the adjusted one, +// if it matches a previous offset. +func (b *blockEnc) matchOffset(offset, lits uint32) uint32 { + // Check if offset is one of the recent offsets. + // Adjusts the output offset accordingly. + // Gives a tiny bit of compression, typically around 1%. + if true { + if lits > 0 { + switch offset { + case b.recentOffsets[0]: + offset = 1 + case b.recentOffsets[1]: + b.recentOffsets[1] = b.recentOffsets[0] + b.recentOffsets[0] = offset + offset = 2 + case b.recentOffsets[2]: + b.recentOffsets[2] = b.recentOffsets[1] + b.recentOffsets[1] = b.recentOffsets[0] + b.recentOffsets[0] = offset + offset = 3 + default: + b.recentOffsets[2] = b.recentOffsets[1] + b.recentOffsets[1] = b.recentOffsets[0] + b.recentOffsets[0] = offset + offset += 3 + } + } else { + switch offset { + case b.recentOffsets[1]: + b.recentOffsets[1] = b.recentOffsets[0] + b.recentOffsets[0] = offset + offset = 1 + case b.recentOffsets[2]: + b.recentOffsets[2] = b.recentOffsets[1] + b.recentOffsets[1] = b.recentOffsets[0] + b.recentOffsets[0] = offset + offset = 2 + case b.recentOffsets[0] - 1: + b.recentOffsets[2] = b.recentOffsets[1] + b.recentOffsets[1] = b.recentOffsets[0] + b.recentOffsets[0] = offset + offset = 3 + default: + b.recentOffsets[2] = b.recentOffsets[1] + b.recentOffsets[1] = b.recentOffsets[0] + b.recentOffsets[0] = offset + offset += 3 + } + } + } else { + offset += 3 + } + return offset +} + +// encodeRaw can be used to set the output to a raw representation of supplied bytes. +func (b *blockEnc) encodeRaw(a []byte) { + var bh blockHeader + bh.setLast(b.last) + bh.setSize(uint32(len(a))) + bh.setType(blockTypeRaw) + b.output = bh.appendTo(b.output[:0]) + b.output = append(b.output, a...) + if debugEncoder { + println("Adding RAW block, length", len(a), "last:", b.last) + } +} + +// encodeRaw can be used to set the output to a raw representation of supplied bytes. +func (b *blockEnc) encodeRawTo(dst, src []byte) []byte { + var bh blockHeader + bh.setLast(b.last) + bh.setSize(uint32(len(src))) + bh.setType(blockTypeRaw) + dst = bh.appendTo(dst) + dst = append(dst, src...) + if debugEncoder { + println("Adding RAW block, length", len(src), "last:", b.last) + } + return dst +} + +// encodeLits can be used if the block is only litLen. +func (b *blockEnc) encodeLits(lits []byte, raw bool) error { + var bh blockHeader + bh.setLast(b.last) + bh.setSize(uint32(len(lits))) + + // Don't compress extremely small blocks + if len(lits) < 8 || (len(lits) < 32 && b.dictLitEnc == nil) || raw { + if debugEncoder { + println("Adding RAW block, length", len(lits), "last:", b.last) + } + bh.setType(blockTypeRaw) + b.output = bh.appendTo(b.output) + b.output = append(b.output, lits...) + return nil + } + + var ( + out []byte + reUsed, single bool + err error + ) + if b.dictLitEnc != nil { + b.litEnc.TransferCTable(b.dictLitEnc) + b.litEnc.Reuse = huff0.ReusePolicyAllow + b.dictLitEnc = nil + } + if len(lits) >= 1024 { + // Use 4 Streams. + out, reUsed, err = huff0.Compress4X(lits, b.litEnc) + } else if len(lits) > 16 { + // Use 1 stream + single = true + out, reUsed, err = huff0.Compress1X(lits, b.litEnc) + } else { + err = huff0.ErrIncompressible + } + if err == nil && len(out)+5 > len(lits) { + // If we are close, we may still be worse or equal to raw. + var lh literalsHeader + lh.setSizes(len(out), len(lits), single) + if len(out)+lh.size() >= len(lits) { + err = huff0.ErrIncompressible + } + } + switch err { + case huff0.ErrIncompressible: + if debugEncoder { + println("Adding RAW block, length", len(lits), "last:", b.last) + } + bh.setType(blockTypeRaw) + b.output = bh.appendTo(b.output) + b.output = append(b.output, lits...) + return nil + case huff0.ErrUseRLE: + if debugEncoder { + println("Adding RLE block, length", len(lits)) + } + bh.setType(blockTypeRLE) + b.output = bh.appendTo(b.output) + b.output = append(b.output, lits[0]) + return nil + case nil: + default: + return err + } + // Compressed... + // Now, allow reuse + b.litEnc.Reuse = huff0.ReusePolicyAllow + bh.setType(blockTypeCompressed) + var lh literalsHeader + if reUsed { + if debugEncoder { + println("Reused tree, compressed to", len(out)) + } + lh.setType(literalsBlockTreeless) + } else { + if debugEncoder { + println("New tree, compressed to", len(out), "tree size:", len(b.litEnc.OutTable)) + } + lh.setType(literalsBlockCompressed) + } + // Set sizes + lh.setSizes(len(out), len(lits), single) + bh.setSize(uint32(len(out) + lh.size() + 1)) + + // Write block headers. + b.output = bh.appendTo(b.output) + b.output = lh.appendTo(b.output) + // Add compressed data. + b.output = append(b.output, out...) + // No sequences. + b.output = append(b.output, 0) + return nil +} + +// fuzzFseEncoder can be used to fuzz the FSE encoder. +func fuzzFseEncoder(data []byte) int { + if len(data) > maxSequences || len(data) < 2 { + return 0 + } + enc := fseEncoder{} + hist := enc.Histogram() + maxSym := uint8(0) + for i, v := range data { + v = v & 63 + data[i] = v + hist[v]++ + if v > maxSym { + maxSym = v + } + } + if maxSym == 0 { + // All 0 + return 0 + } + maxCount := func(a []uint32) int { + var max uint32 + for _, v := range a { + if v > max { + max = v + } + } + return int(max) + } + cnt := maxCount(hist[:maxSym]) + if cnt == len(data) { + // RLE + return 0 + } + enc.HistogramFinished(maxSym, cnt) + err := enc.normalizeCount(len(data)) + if err != nil { + return 0 + } + _, err = enc.writeCount(nil) + if err != nil { + panic(err) + } + return 1 +} + +// encode will encode the block and append the output in b.output. +// Previous offset codes must be pushed if more blocks are expected. +func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { + if len(b.sequences) == 0 { + return b.encodeLits(b.literals, rawAllLits) + } + // We want some difference to at least account for the headers. + saved := b.size - len(b.literals) - (b.size >> 6) + if saved < 16 { + if org == nil { + return errIncompressible + } + b.popOffsets() + return b.encodeLits(org, rawAllLits) + } + + var bh blockHeader + var lh literalsHeader + bh.setLast(b.last) + bh.setType(blockTypeCompressed) + // Store offset of the block header. Needed when we know the size. + bhOffset := len(b.output) + b.output = bh.appendTo(b.output) + + var ( + out []byte + reUsed, single bool + err error + ) + if b.dictLitEnc != nil { + b.litEnc.TransferCTable(b.dictLitEnc) + b.litEnc.Reuse = huff0.ReusePolicyAllow + b.dictLitEnc = nil + } + if len(b.literals) >= 1024 && !raw { + // Use 4 Streams. + out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc) + } else if len(b.literals) > 16 && !raw { + // Use 1 stream + single = true + out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc) + } else { + err = huff0.ErrIncompressible + } + + if err == nil && len(out)+5 > len(b.literals) { + // If we are close, we may still be worse or equal to raw. + var lh literalsHeader + lh.setSize(len(b.literals)) + szRaw := lh.size() + lh.setSizes(len(out), len(b.literals), single) + szComp := lh.size() + if len(out)+szComp >= len(b.literals)+szRaw { + err = huff0.ErrIncompressible + } + } + switch err { + case huff0.ErrIncompressible: + lh.setType(literalsBlockRaw) + lh.setSize(len(b.literals)) + b.output = lh.appendTo(b.output) + b.output = append(b.output, b.literals...) + if debugEncoder { + println("Adding literals RAW, length", len(b.literals)) + } + case huff0.ErrUseRLE: + lh.setType(literalsBlockRLE) + lh.setSize(len(b.literals)) + b.output = lh.appendTo(b.output) + b.output = append(b.output, b.literals[0]) + if debugEncoder { + println("Adding literals RLE") + } + case nil: + // Compressed litLen... + if reUsed { + if debugEncoder { + println("reused tree") + } + lh.setType(literalsBlockTreeless) + } else { + if debugEncoder { + println("new tree, size:", len(b.litEnc.OutTable)) + } + lh.setType(literalsBlockCompressed) + if debugEncoder { + _, _, err := huff0.ReadTable(out, nil) + if err != nil { + panic(err) + } + } + } + lh.setSizes(len(out), len(b.literals), single) + if debugEncoder { + printf("Compressed %d literals to %d bytes", len(b.literals), len(out)) + println("Adding literal header:", lh) + } + b.output = lh.appendTo(b.output) + b.output = append(b.output, out...) + b.litEnc.Reuse = huff0.ReusePolicyAllow + if debugEncoder { + println("Adding literals compressed") + } + default: + if debugEncoder { + println("Adding literals ERROR:", err) + } + return err + } + // Sequence compression + + // Write the number of sequences + switch { + case len(b.sequences) < 128: + b.output = append(b.output, uint8(len(b.sequences))) + case len(b.sequences) < 0x7f00: // TODO: this could be wrong + n := len(b.sequences) + b.output = append(b.output, 128+uint8(n>>8), uint8(n)) + default: + n := len(b.sequences) - 0x7f00 + b.output = append(b.output, 255, uint8(n), uint8(n>>8)) + } + if debugEncoder { + println("Encoding", len(b.sequences), "sequences") + } + b.genCodes() + llEnc := b.coders.llEnc + ofEnc := b.coders.ofEnc + mlEnc := b.coders.mlEnc + err = llEnc.normalizeCount(len(b.sequences)) + if err != nil { + return err + } + err = ofEnc.normalizeCount(len(b.sequences)) + if err != nil { + return err + } + err = mlEnc.normalizeCount(len(b.sequences)) + if err != nil { + return err + } + + // Choose the best compression mode for each type. + // Will evaluate the new vs predefined and previous. + chooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) { + // See if predefined/previous is better + hist := cur.count[:cur.symbolLen] + nSize := cur.approxSize(hist) + cur.maxHeaderSize() + predefSize := preDef.approxSize(hist) + prevSize := prev.approxSize(hist) + + // Add a small penalty for new encoders. + // Don't bother with extremely small (<2 byte gains). + nSize = nSize + (nSize+2*8*16)>>4 + switch { + case predefSize <= prevSize && predefSize <= nSize || forcePreDef: + if debugEncoder { + println("Using predefined", predefSize>>3, "<=", nSize>>3) + } + return preDef, compModePredefined + case prevSize <= nSize: + if debugEncoder { + println("Using previous", prevSize>>3, "<=", nSize>>3) + } + return prev, compModeRepeat + default: + if debugEncoder { + println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes") + println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen]) + } + return cur, compModeFSE + } + } + + // Write compression mode + var mode uint8 + if llEnc.useRLE { + mode |= uint8(compModeRLE) << 6 + llEnc.setRLE(b.sequences[0].llCode) + if debugEncoder { + println("llEnc.useRLE") + } + } else { + var m seqCompMode + llEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths]) + mode |= uint8(m) << 6 + } + if ofEnc.useRLE { + mode |= uint8(compModeRLE) << 4 + ofEnc.setRLE(b.sequences[0].ofCode) + if debugEncoder { + println("ofEnc.useRLE") + } + } else { + var m seqCompMode + ofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets]) + mode |= uint8(m) << 4 + } + + if mlEnc.useRLE { + mode |= uint8(compModeRLE) << 2 + mlEnc.setRLE(b.sequences[0].mlCode) + if debugEncoder { + println("mlEnc.useRLE, code: ", b.sequences[0].mlCode, "value", b.sequences[0].matchLen) + } + } else { + var m seqCompMode + mlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths]) + mode |= uint8(m) << 2 + } + b.output = append(b.output, mode) + if debugEncoder { + printf("Compression modes: 0b%b", mode) + } + b.output, err = llEnc.writeCount(b.output) + if err != nil { + return err + } + start := len(b.output) + b.output, err = ofEnc.writeCount(b.output) + if err != nil { + return err + } + if false { + println("block:", b.output[start:], "tablelog", ofEnc.actualTableLog, "maxcount:", ofEnc.maxCount) + fmt.Printf("selected TableLog: %d, Symbol length: %d\n", ofEnc.actualTableLog, ofEnc.symbolLen) + for i, v := range ofEnc.norm[:ofEnc.symbolLen] { + fmt.Printf("%3d: %5d -> %4d \n", i, ofEnc.count[i], v) + } + } + b.output, err = mlEnc.writeCount(b.output) + if err != nil { + return err + } + + // Maybe in block? + wr := &b.wr + wr.reset(b.output) + + var ll, of, ml cState + + // Current sequence + seq := len(b.sequences) - 1 + s := b.sequences[seq] + llEnc.setBits(llBitsTable[:]) + mlEnc.setBits(mlBitsTable[:]) + ofEnc.setBits(nil) + + llTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256] + + // We have 3 bounds checks here (and in the loop). + // Since we are iterating backwards it is kinda hard to avoid. + llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode] + ll.init(wr, &llEnc.ct, llB) + of.init(wr, &ofEnc.ct, ofB) + wr.flush32() + ml.init(wr, &mlEnc.ct, mlB) + + // Each of these lookups also generates a bounds check. + wr.addBits32NC(s.litLen, llB.outBits) + wr.addBits32NC(s.matchLen, mlB.outBits) + wr.flush32() + wr.addBits32NC(s.offset, ofB.outBits) + if debugSequences { + println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB) + } + seq-- + // Store sequences in reverse... + for seq >= 0 { + s = b.sequences[seq] + + ofB := ofTT[s.ofCode] + wr.flush32() // tablelog max is below 8 for each, so it will fill max 24 bits. + //of.encode(ofB) + nbBitsOut := (uint32(of.state) + ofB.deltaNbBits) >> 16 + dstState := int32(of.state>>(nbBitsOut&15)) + int32(ofB.deltaFindState) + wr.addBits16NC(of.state, uint8(nbBitsOut)) + of.state = of.stateTable[dstState] + + // Accumulate extra bits. + outBits := ofB.outBits & 31 + extraBits := uint64(s.offset & bitMask32[outBits]) + extraBitsN := outBits + + mlB := mlTT[s.mlCode] + //ml.encode(mlB) + nbBitsOut = (uint32(ml.state) + mlB.deltaNbBits) >> 16 + dstState = int32(ml.state>>(nbBitsOut&15)) + int32(mlB.deltaFindState) + wr.addBits16NC(ml.state, uint8(nbBitsOut)) + ml.state = ml.stateTable[dstState] + + outBits = mlB.outBits & 31 + extraBits = extraBits<> 16 + dstState = int32(ll.state>>(nbBitsOut&15)) + int32(llB.deltaFindState) + wr.addBits16NC(ll.state, uint8(nbBitsOut)) + ll.state = ll.stateTable[dstState] + + outBits = llB.outBits & 31 + extraBits = extraBits<= b.size { + // Discard and encode as raw block. + b.output = b.encodeRawTo(b.output[:bhOffset], org) + b.popOffsets() + b.litEnc.Reuse = huff0.ReusePolicyNone + return nil + } + + // Size is output minus block header. + bh.setSize(uint32(len(b.output)-bhOffset) - 3) + if debugEncoder { + println("Rewriting block header", bh) + } + _ = bh.appendTo(b.output[bhOffset:bhOffset]) + b.coders.setPrev(llEnc, mlEnc, ofEnc) + return nil +} + +var errIncompressible = errors.New("incompressible") + +func (b *blockEnc) genCodes() { + if len(b.sequences) == 0 { + // nothing to do + return + } + if len(b.sequences) > math.MaxUint16 { + panic("can only encode up to 64K sequences") + } + // No bounds checks after here: + llH := b.coders.llEnc.Histogram() + ofH := b.coders.ofEnc.Histogram() + mlH := b.coders.mlEnc.Histogram() + for i := range llH { + llH[i] = 0 + } + for i := range ofH { + ofH[i] = 0 + } + for i := range mlH { + mlH[i] = 0 + } + + var llMax, ofMax, mlMax uint8 + for i := range b.sequences { + seq := &b.sequences[i] + v := llCode(seq.litLen) + seq.llCode = v + llH[v]++ + if v > llMax { + llMax = v + } + + v = ofCode(seq.offset) + seq.ofCode = v + ofH[v]++ + if v > ofMax { + ofMax = v + } + + v = mlCode(seq.matchLen) + seq.mlCode = v + mlH[v]++ + if v > mlMax { + mlMax = v + if debugAsserts && mlMax > maxMatchLengthSymbol { + panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d), matchlen: %d", mlMax, seq.matchLen)) + } + } + } + maxCount := func(a []uint32) int { + var max uint32 + for _, v := range a { + if v > max { + max = v + } + } + return int(max) + } + if debugAsserts && mlMax > maxMatchLengthSymbol { + panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d)", mlMax)) + } + if debugAsserts && ofMax > maxOffsetBits { + panic(fmt.Errorf("ofMax > maxOffsetBits (%d)", ofMax)) + } + if debugAsserts && llMax > maxLiteralLengthSymbol { + panic(fmt.Errorf("llMax > maxLiteralLengthSymbol (%d)", llMax)) + } + + b.coders.mlEnc.HistogramFinished(mlMax, maxCount(mlH[:mlMax+1])) + b.coders.ofEnc.HistogramFinished(ofMax, maxCount(ofH[:ofMax+1])) + b.coders.llEnc.HistogramFinished(llMax, maxCount(llH[:llMax+1])) +} diff --git a/vendor/github.com/klauspost/compress/zstd/blocktype_string.go b/vendor/github.com/klauspost/compress/zstd/blocktype_string.go new file mode 100644 index 000000000..01a01e486 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/blocktype_string.go @@ -0,0 +1,85 @@ +// Code generated by "stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex"; DO NOT EDIT. + +package zstd + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[blockTypeRaw-0] + _ = x[blockTypeRLE-1] + _ = x[blockTypeCompressed-2] + _ = x[blockTypeReserved-3] +} + +const _blockType_name = "blockTypeRawblockTypeRLEblockTypeCompressedblockTypeReserved" + +var _blockType_index = [...]uint8{0, 12, 24, 43, 60} + +func (i blockType) String() string { + if i >= blockType(len(_blockType_index)-1) { + return "blockType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _blockType_name[_blockType_index[i]:_blockType_index[i+1]] +} +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[literalsBlockRaw-0] + _ = x[literalsBlockRLE-1] + _ = x[literalsBlockCompressed-2] + _ = x[literalsBlockTreeless-3] +} + +const _literalsBlockType_name = "literalsBlockRawliteralsBlockRLEliteralsBlockCompressedliteralsBlockTreeless" + +var _literalsBlockType_index = [...]uint8{0, 16, 32, 55, 76} + +func (i literalsBlockType) String() string { + if i >= literalsBlockType(len(_literalsBlockType_index)-1) { + return "literalsBlockType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _literalsBlockType_name[_literalsBlockType_index[i]:_literalsBlockType_index[i+1]] +} +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[compModePredefined-0] + _ = x[compModeRLE-1] + _ = x[compModeFSE-2] + _ = x[compModeRepeat-3] +} + +const _seqCompMode_name = "compModePredefinedcompModeRLEcompModeFSEcompModeRepeat" + +var _seqCompMode_index = [...]uint8{0, 18, 29, 40, 54} + +func (i seqCompMode) String() string { + if i >= seqCompMode(len(_seqCompMode_index)-1) { + return "seqCompMode(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _seqCompMode_name[_seqCompMode_index[i]:_seqCompMode_index[i+1]] +} +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[tableLiteralLengths-0] + _ = x[tableOffsets-1] + _ = x[tableMatchLengths-2] +} + +const _tableIndex_name = "tableLiteralLengthstableOffsetstableMatchLengths" + +var _tableIndex_index = [...]uint8{0, 19, 31, 48} + +func (i tableIndex) String() string { + if i >= tableIndex(len(_tableIndex_index)-1) { + return "tableIndex(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _tableIndex_name[_tableIndex_index[i]:_tableIndex_index[i+1]] +} diff --git a/vendor/github.com/klauspost/compress/zstd/bytebuf.go b/vendor/github.com/klauspost/compress/zstd/bytebuf.go new file mode 100644 index 000000000..55a388553 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/bytebuf.go @@ -0,0 +1,131 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "fmt" + "io" +) + +type byteBuffer interface { + // Read up to 8 bytes. + // Returns io.ErrUnexpectedEOF if this cannot be satisfied. + readSmall(n int) ([]byte, error) + + // Read >8 bytes. + // MAY use the destination slice. + readBig(n int, dst []byte) ([]byte, error) + + // Read a single byte. + readByte() (byte, error) + + // Skip n bytes. + skipN(n int64) error +} + +// in-memory buffer +type byteBuf []byte + +func (b *byteBuf) readSmall(n int) ([]byte, error) { + if debugAsserts && n > 8 { + panic(fmt.Errorf("small read > 8 (%d). use readBig", n)) + } + bb := *b + if len(bb) < n { + return nil, io.ErrUnexpectedEOF + } + r := bb[:n] + *b = bb[n:] + return r, nil +} + +func (b *byteBuf) readBig(n int, dst []byte) ([]byte, error) { + bb := *b + if len(bb) < n { + return nil, io.ErrUnexpectedEOF + } + r := bb[:n] + *b = bb[n:] + return r, nil +} + +func (b *byteBuf) readByte() (byte, error) { + bb := *b + if len(bb) < 1 { + return 0, io.ErrUnexpectedEOF + } + r := bb[0] + *b = bb[1:] + return r, nil +} + +func (b *byteBuf) skipN(n int64) error { + bb := *b + if n < 0 { + return fmt.Errorf("negative skip (%d) requested", n) + } + if int64(len(bb)) < n { + return io.ErrUnexpectedEOF + } + *b = bb[n:] + return nil +} + +// wrapper around a reader. +type readerWrapper struct { + r io.Reader + tmp [8]byte +} + +func (r *readerWrapper) readSmall(n int) ([]byte, error) { + if debugAsserts && n > 8 { + panic(fmt.Errorf("small read > 8 (%d). use readBig", n)) + } + n2, err := io.ReadFull(r.r, r.tmp[:n]) + // We only really care about the actual bytes read. + if err != nil { + if err == io.EOF { + return nil, io.ErrUnexpectedEOF + } + if debugDecoder { + println("readSmall: got", n2, "want", n, "err", err) + } + return nil, err + } + return r.tmp[:n], nil +} + +func (r *readerWrapper) readBig(n int, dst []byte) ([]byte, error) { + if cap(dst) < n { + dst = make([]byte, n) + } + n2, err := io.ReadFull(r.r, dst[:n]) + if err == io.EOF && n > 0 { + err = io.ErrUnexpectedEOF + } + return dst[:n2], err +} + +func (r *readerWrapper) readByte() (byte, error) { + n2, err := io.ReadFull(r.r, r.tmp[:1]) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + if n2 != 1 { + return 0, io.ErrUnexpectedEOF + } + return r.tmp[0], nil +} + +func (r *readerWrapper) skipN(n int64) error { + n2, err := io.CopyN(io.Discard, r.r, n) + if n2 != n { + err = io.ErrUnexpectedEOF + } + return err +} diff --git a/vendor/github.com/klauspost/compress/zstd/bytereader.go b/vendor/github.com/klauspost/compress/zstd/bytereader.go new file mode 100644 index 000000000..0e59a242d --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/bytereader.go @@ -0,0 +1,82 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +// byteReader provides a byte reader that reads +// little endian values from a byte stream. +// The input stream is manually advanced. +// The reader performs no bounds checks. +type byteReader struct { + b []byte + off int +} + +// advance the stream b n bytes. +func (b *byteReader) advance(n uint) { + b.off += int(n) +} + +// overread returns whether we have advanced too far. +func (b *byteReader) overread() bool { + return b.off > len(b.b) +} + +// Int32 returns a little endian int32 starting at current offset. +func (b byteReader) Int32() int32 { + b2 := b.b[b.off:] + b2 = b2[:4] + v3 := int32(b2[3]) + v2 := int32(b2[2]) + v1 := int32(b2[1]) + v0 := int32(b2[0]) + return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) +} + +// Uint8 returns the next byte +func (b *byteReader) Uint8() uint8 { + v := b.b[b.off] + return v +} + +// Uint32 returns a little endian uint32 starting at current offset. +func (b byteReader) Uint32() uint32 { + if r := b.remain(); r < 4 { + // Very rare + v := uint32(0) + for i := 1; i <= r; i++ { + v = (v << 8) | uint32(b.b[len(b.b)-i]) + } + return v + } + b2 := b.b[b.off:] + b2 = b2[:4] + v3 := uint32(b2[3]) + v2 := uint32(b2[2]) + v1 := uint32(b2[1]) + v0 := uint32(b2[0]) + return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) +} + +// Uint32NC returns a little endian uint32 starting at current offset. +// The caller must be sure if there are at least 4 bytes left. +func (b byteReader) Uint32NC() uint32 { + b2 := b.b[b.off:] + b2 = b2[:4] + v3 := uint32(b2[3]) + v2 := uint32(b2[2]) + v1 := uint32(b2[1]) + v0 := uint32(b2[0]) + return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) +} + +// unread returns the unread portion of the input. +func (b byteReader) unread() []byte { + return b.b[b.off:] +} + +// remain will return the number of bytes remaining. +func (b byteReader) remain() int { + return len(b.b) - b.off +} diff --git a/vendor/github.com/klauspost/compress/zstd/decodeheader.go b/vendor/github.com/klauspost/compress/zstd/decodeheader.go new file mode 100644 index 000000000..f6a240970 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/decodeheader.go @@ -0,0 +1,229 @@ +// Copyright 2020+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. + +package zstd + +import ( + "encoding/binary" + "errors" + "io" +) + +// HeaderMaxSize is the maximum size of a Frame and Block Header. +// If less is sent to Header.Decode it *may* still contain enough information. +const HeaderMaxSize = 14 + 3 + +// Header contains information about the first frame and block within that. +type Header struct { + // SingleSegment specifies whether the data is to be decompressed into a + // single contiguous memory segment. + // It implies that WindowSize is invalid and that FrameContentSize is valid. + SingleSegment bool + + // WindowSize is the window of data to keep while decoding. + // Will only be set if SingleSegment is false. + WindowSize uint64 + + // Dictionary ID. + // If 0, no dictionary. + DictionaryID uint32 + + // HasFCS specifies whether FrameContentSize has a valid value. + HasFCS bool + + // FrameContentSize is the expected uncompressed size of the entire frame. + FrameContentSize uint64 + + // Skippable will be true if the frame is meant to be skipped. + // This implies that FirstBlock.OK is false. + Skippable bool + + // SkippableID is the user-specific ID for the skippable frame. + // Valid values are between 0 to 15, inclusive. + SkippableID int + + // SkippableSize is the length of the user data to skip following + // the header. + SkippableSize uint32 + + // HeaderSize is the raw size of the frame header. + // + // For normal frames, it includes the size of the magic number and + // the size of the header (per section 3.1.1.1). + // It does not include the size for any data blocks (section 3.1.1.2) nor + // the size for the trailing content checksum. + // + // For skippable frames, this counts the size of the magic number + // along with the size of the size field of the payload. + // It does not include the size of the skippable payload itself. + // The total frame size is the HeaderSize plus the SkippableSize. + HeaderSize int + + // First block information. + FirstBlock struct { + // OK will be set if first block could be decoded. + OK bool + + // Is this the last block of a frame? + Last bool + + // Is the data compressed? + // If true CompressedSize will be populated. + // Unfortunately DecompressedSize cannot be determined + // without decoding the blocks. + Compressed bool + + // DecompressedSize is the expected decompressed size of the block. + // Will be 0 if it cannot be determined. + DecompressedSize int + + // CompressedSize of the data in the block. + // Does not include the block header. + // Will be equal to DecompressedSize if not Compressed. + CompressedSize int + } + + // If set there is a checksum present for the block content. + // The checksum field at the end is always 4 bytes long. + HasCheckSum bool +} + +// Decode the header from the beginning of the stream. +// This will decode the frame header and the first block header if enough bytes are provided. +// It is recommended to provide at least HeaderMaxSize bytes. +// If the frame header cannot be read an error will be returned. +// If there isn't enough input, io.ErrUnexpectedEOF is returned. +// The FirstBlock.OK will indicate if enough information was available to decode the first block header. +func (h *Header) Decode(in []byte) error { + *h = Header{} + if len(in) < 4 { + return io.ErrUnexpectedEOF + } + h.HeaderSize += 4 + b, in := in[:4], in[4:] + if string(b) != frameMagic { + if string(b[1:4]) != skippableFrameMagic || b[0]&0xf0 != 0x50 { + return ErrMagicMismatch + } + if len(in) < 4 { + return io.ErrUnexpectedEOF + } + h.HeaderSize += 4 + h.Skippable = true + h.SkippableID = int(b[0] & 0xf) + h.SkippableSize = binary.LittleEndian.Uint32(in) + return nil + } + + // Read Window_Descriptor + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#window_descriptor + if len(in) < 1 { + return io.ErrUnexpectedEOF + } + fhd, in := in[0], in[1:] + h.HeaderSize++ + h.SingleSegment = fhd&(1<<5) != 0 + h.HasCheckSum = fhd&(1<<2) != 0 + if fhd&(1<<3) != 0 { + return errors.New("reserved bit set on frame header") + } + + if !h.SingleSegment { + if len(in) < 1 { + return io.ErrUnexpectedEOF + } + var wd byte + wd, in = in[0], in[1:] + h.HeaderSize++ + windowLog := 10 + (wd >> 3) + windowBase := uint64(1) << windowLog + windowAdd := (windowBase / 8) * uint64(wd&0x7) + h.WindowSize = windowBase + windowAdd + } + + // Read Dictionary_ID + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary_id + if size := fhd & 3; size != 0 { + if size == 3 { + size = 4 + } + if len(in) < int(size) { + return io.ErrUnexpectedEOF + } + b, in = in[:size], in[size:] + h.HeaderSize += int(size) + switch len(b) { + case 1: + h.DictionaryID = uint32(b[0]) + case 2: + h.DictionaryID = uint32(b[0]) | (uint32(b[1]) << 8) + case 4: + h.DictionaryID = uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) + } + } + + // Read Frame_Content_Size + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_content_size + var fcsSize int + v := fhd >> 6 + switch v { + case 0: + if h.SingleSegment { + fcsSize = 1 + } + default: + fcsSize = 1 << v + } + + if fcsSize > 0 { + h.HasFCS = true + if len(in) < fcsSize { + return io.ErrUnexpectedEOF + } + b, in = in[:fcsSize], in[fcsSize:] + h.HeaderSize += int(fcsSize) + switch len(b) { + case 1: + h.FrameContentSize = uint64(b[0]) + case 2: + // When FCS_Field_Size is 2, the offset of 256 is added. + h.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) + 256 + case 4: + h.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) | (uint64(b[2]) << 16) | (uint64(b[3]) << 24) + case 8: + d1 := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) + d2 := uint32(b[4]) | (uint32(b[5]) << 8) | (uint32(b[6]) << 16) | (uint32(b[7]) << 24) + h.FrameContentSize = uint64(d1) | (uint64(d2) << 32) + } + } + + // Frame Header done, we will not fail from now on. + if len(in) < 3 { + return nil + } + tmp := in[:3] + bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16) + h.FirstBlock.Last = bh&1 != 0 + blockType := blockType((bh >> 1) & 3) + // find size. + cSize := int(bh >> 3) + switch blockType { + case blockTypeReserved: + return nil + case blockTypeRLE: + h.FirstBlock.Compressed = true + h.FirstBlock.DecompressedSize = cSize + h.FirstBlock.CompressedSize = 1 + case blockTypeCompressed: + h.FirstBlock.Compressed = true + h.FirstBlock.CompressedSize = cSize + case blockTypeRaw: + h.FirstBlock.DecompressedSize = cSize + h.FirstBlock.CompressedSize = cSize + default: + panic("Invalid block type") + } + + h.FirstBlock.OK = true + return nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/decoder.go b/vendor/github.com/klauspost/compress/zstd/decoder.go new file mode 100644 index 000000000..f04aaa21e --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/decoder.go @@ -0,0 +1,948 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "context" + "encoding/binary" + "io" + "sync" + + "github.com/klauspost/compress/zstd/internal/xxhash" +) + +// Decoder provides decoding of zstandard streams. +// The decoder has been designed to operate without allocations after a warmup. +// This means that you should store the decoder for best performance. +// To re-use a stream decoder, use the Reset(r io.Reader) error to switch to another stream. +// A decoder can safely be re-used even if the previous stream failed. +// To release the resources, you must call the Close() function on a decoder. +type Decoder struct { + o decoderOptions + + // Unreferenced decoders, ready for use. + decoders chan *blockDec + + // Current read position used for Reader functionality. + current decoderState + + // sync stream decoding + syncStream struct { + decodedFrame uint64 + br readerWrapper + enabled bool + inFrame bool + dstBuf []byte + } + + frame *frameDec + + // Custom dictionaries. + dicts map[uint32]*dict + + // streamWg is the waitgroup for all streams + streamWg sync.WaitGroup +} + +// decoderState is used for maintaining state when the decoder +// is used for streaming. +type decoderState struct { + // current block being written to stream. + decodeOutput + + // output in order to be written to stream. + output chan decodeOutput + + // cancel remaining output. + cancel context.CancelFunc + + // crc of current frame + crc *xxhash.Digest + + flushed bool +} + +var ( + // Check the interfaces we want to support. + _ = io.WriterTo(&Decoder{}) + _ = io.Reader(&Decoder{}) +) + +// NewReader creates a new decoder. +// A nil Reader can be provided in which case Reset can be used to start a decode. +// +// A Decoder can be used in two modes: +// +// 1) As a stream, or +// 2) For stateless decoding using DecodeAll. +// +// Only a single stream can be decoded concurrently, but the same decoder +// can run multiple concurrent stateless decodes. It is even possible to +// use stateless decodes while a stream is being decoded. +// +// The Reset function can be used to initiate a new stream, which is will considerably +// reduce the allocations normally caused by NewReader. +func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { + initPredefined() + var d Decoder + d.o.setDefault() + for _, o := range opts { + err := o(&d.o) + if err != nil { + return nil, err + } + } + d.current.crc = xxhash.New() + d.current.flushed = true + + if r == nil { + d.current.err = ErrDecoderNilInput + } + + // Transfer option dicts. + d.dicts = make(map[uint32]*dict, len(d.o.dicts)) + for _, dc := range d.o.dicts { + d.dicts[dc.id] = dc + } + d.o.dicts = nil + + // Create decoders + d.decoders = make(chan *blockDec, d.o.concurrent) + for i := 0; i < d.o.concurrent; i++ { + dec := newBlockDec(d.o.lowMem) + dec.localFrame = newFrameDec(d.o) + d.decoders <- dec + } + + if r == nil { + return &d, nil + } + return &d, d.Reset(r) +} + +// Read bytes from the decompressed stream into p. +// Returns the number of bytes written and any error that occurred. +// When the stream is done, io.EOF will be returned. +func (d *Decoder) Read(p []byte) (int, error) { + var n int + for { + if len(d.current.b) > 0 { + filled := copy(p, d.current.b) + p = p[filled:] + d.current.b = d.current.b[filled:] + n += filled + } + if len(p) == 0 { + break + } + if len(d.current.b) == 0 { + // We have an error and no more data + if d.current.err != nil { + break + } + if !d.nextBlock(n == 0) { + return n, d.current.err + } + } + } + if len(d.current.b) > 0 { + if debugDecoder { + println("returning", n, "still bytes left:", len(d.current.b)) + } + // Only return error at end of block + return n, nil + } + if d.current.err != nil { + d.drainOutput() + } + if debugDecoder { + println("returning", n, d.current.err, len(d.decoders)) + } + return n, d.current.err +} + +// Reset will reset the decoder the supplied stream after the current has finished processing. +// Note that this functionality cannot be used after Close has been called. +// Reset can be called with a nil reader to release references to the previous reader. +// After being called with a nil reader, no other operations than Reset or DecodeAll or Close +// should be used. +func (d *Decoder) Reset(r io.Reader) error { + if d.current.err == ErrDecoderClosed { + return d.current.err + } + + d.drainOutput() + + d.syncStream.br.r = nil + if r == nil { + d.current.err = ErrDecoderNilInput + if len(d.current.b) > 0 { + d.current.b = d.current.b[:0] + } + d.current.flushed = true + return nil + } + + // If bytes buffer and < 5MB, do sync decoding anyway. + if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap { + bb2 := bb + if debugDecoder { + println("*bytes.Buffer detected, doing sync decode, len:", bb.Len()) + } + b := bb2.Bytes() + var dst []byte + if cap(d.syncStream.dstBuf) > 0 { + dst = d.syncStream.dstBuf[:0] + } + + dst, err := d.DecodeAll(b, dst) + if err == nil { + err = io.EOF + } + // Save output buffer + d.syncStream.dstBuf = dst + d.current.b = dst + d.current.err = err + d.current.flushed = true + if debugDecoder { + println("sync decode to", len(dst), "bytes, err:", err) + } + return nil + } + // Remove current block. + d.stashDecoder() + d.current.decodeOutput = decodeOutput{} + d.current.err = nil + d.current.flushed = false + d.current.d = nil + d.syncStream.dstBuf = nil + + // Ensure no-one else is still running... + d.streamWg.Wait() + if d.frame == nil { + d.frame = newFrameDec(d.o) + } + + if d.o.concurrent == 1 { + return d.startSyncDecoder(r) + } + + d.current.output = make(chan decodeOutput, d.o.concurrent) + ctx, cancel := context.WithCancel(context.Background()) + d.current.cancel = cancel + d.streamWg.Add(1) + go d.startStreamDecoder(ctx, r, d.current.output) + + return nil +} + +// drainOutput will drain the output until errEndOfStream is sent. +func (d *Decoder) drainOutput() { + if d.current.cancel != nil { + if debugDecoder { + println("cancelling current") + } + d.current.cancel() + d.current.cancel = nil + } + if d.current.d != nil { + if debugDecoder { + printf("re-adding current decoder %p, decoders: %d", d.current.d, len(d.decoders)) + } + d.decoders <- d.current.d + d.current.d = nil + d.current.b = nil + } + if d.current.output == nil || d.current.flushed { + println("current already flushed") + return + } + for v := range d.current.output { + if v.d != nil { + if debugDecoder { + printf("re-adding decoder %p", v.d) + } + d.decoders <- v.d + } + } + d.current.output = nil + d.current.flushed = true +} + +// WriteTo writes data to w until there's no more data to write or when an error occurs. +// The return value n is the number of bytes written. +// Any error encountered during the write is also returned. +func (d *Decoder) WriteTo(w io.Writer) (int64, error) { + var n int64 + for { + if len(d.current.b) > 0 { + n2, err2 := w.Write(d.current.b) + n += int64(n2) + if err2 != nil && (d.current.err == nil || d.current.err == io.EOF) { + d.current.err = err2 + } else if n2 != len(d.current.b) { + d.current.err = io.ErrShortWrite + } + } + if d.current.err != nil { + break + } + d.nextBlock(true) + } + err := d.current.err + if err != nil { + d.drainOutput() + } + if err == io.EOF { + err = nil + } + return n, err +} + +// DecodeAll allows stateless decoding of a blob of bytes. +// Output will be appended to dst, so if the destination size is known +// you can pre-allocate the destination slice to avoid allocations. +// DecodeAll can be used concurrently. +// The Decoder concurrency limits will be respected. +func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { + if d.decoders == nil { + return dst, ErrDecoderClosed + } + + // Grab a block decoder and frame decoder. + block := <-d.decoders + frame := block.localFrame + initialSize := len(dst) + defer func() { + if debugDecoder { + printf("re-adding decoder: %p", block) + } + frame.rawInput = nil + frame.bBuf = nil + if frame.history.decoders.br != nil { + frame.history.decoders.br.in = nil + } + d.decoders <- block + }() + frame.bBuf = input + + for { + frame.history.reset() + err := frame.reset(&frame.bBuf) + if err != nil { + if err == io.EOF { + if debugDecoder { + println("frame reset return EOF") + } + return dst, nil + } + return dst, err + } + if err = d.setDict(frame); err != nil { + return nil, err + } + if frame.WindowSize > d.o.maxWindowSize { + if debugDecoder { + println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize) + } + return dst, ErrWindowSizeExceeded + } + if frame.FrameContentSize != fcsUnknown { + if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) { + if debugDecoder { + println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst)) + } + return dst, ErrDecoderSizeExceeded + } + if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) { + if debugDecoder { + println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst)) + } + return dst, ErrDecoderSizeExceeded + } + if cap(dst)-len(dst) < int(frame.FrameContentSize) { + dst2 := make([]byte, len(dst), len(dst)+int(frame.FrameContentSize)+compressedBlockOverAlloc) + copy(dst2, dst) + dst = dst2 + } + } + + if cap(dst) == 0 && !d.o.limitToCap { + // Allocate len(input) * 2 by default if nothing is provided + // and we didn't get frame content size. + size := len(input) * 2 + // Cap to 1 MB. + if size > 1<<20 { + size = 1 << 20 + } + if uint64(size) > d.o.maxDecodedSize { + size = int(d.o.maxDecodedSize) + } + dst = make([]byte, 0, size) + } + + dst, err = frame.runDecoder(dst, block) + if err != nil { + return dst, err + } + if uint64(len(dst)-initialSize) > d.o.maxDecodedSize { + return dst, ErrDecoderSizeExceeded + } + if len(frame.bBuf) == 0 { + if debugDecoder { + println("frame dbuf empty") + } + break + } + } + return dst, nil +} + +// nextBlock returns the next block. +// If an error occurs d.err will be set. +// Optionally the function can block for new output. +// If non-blocking mode is used the returned boolean will be false +// if no data was available without blocking. +func (d *Decoder) nextBlock(blocking bool) (ok bool) { + if d.current.err != nil { + // Keep error state. + return false + } + d.current.b = d.current.b[:0] + + // SYNC: + if d.syncStream.enabled { + if !blocking { + return false + } + ok = d.nextBlockSync() + if !ok { + d.stashDecoder() + } + return ok + } + + //ASYNC: + d.stashDecoder() + if blocking { + d.current.decodeOutput, ok = <-d.current.output + } else { + select { + case d.current.decodeOutput, ok = <-d.current.output: + default: + return false + } + } + if !ok { + // This should not happen, so signal error state... + d.current.err = io.ErrUnexpectedEOF + return false + } + next := d.current.decodeOutput + if next.d != nil && next.d.async.newHist != nil { + d.current.crc.Reset() + } + if debugDecoder { + var tmp [4]byte + binary.LittleEndian.PutUint32(tmp[:], uint32(xxhash.Sum64(next.b))) + println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp) + } + + if d.o.ignoreChecksum { + return true + } + + if len(next.b) > 0 { + d.current.crc.Write(next.b) + } + if next.err == nil && next.d != nil && next.d.hasCRC { + got := uint32(d.current.crc.Sum64()) + if got != next.d.checkCRC { + if debugDecoder { + printf("CRC Check Failed: %08x (got) != %08x (on stream)\n", got, next.d.checkCRC) + } + d.current.err = ErrCRCMismatch + } else { + if debugDecoder { + printf("CRC ok %08x\n", got) + } + } + } + + return true +} + +func (d *Decoder) nextBlockSync() (ok bool) { + if d.current.d == nil { + d.current.d = <-d.decoders + } + for len(d.current.b) == 0 { + if !d.syncStream.inFrame { + d.frame.history.reset() + d.current.err = d.frame.reset(&d.syncStream.br) + if d.current.err == nil { + d.current.err = d.setDict(d.frame) + } + if d.current.err != nil { + return false + } + if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize { + d.current.err = ErrDecoderSizeExceeded + return false + } + + d.syncStream.decodedFrame = 0 + d.syncStream.inFrame = true + } + d.current.err = d.frame.next(d.current.d) + if d.current.err != nil { + return false + } + d.frame.history.ensureBlock() + if debugDecoder { + println("History trimmed:", len(d.frame.history.b), "decoded already:", d.syncStream.decodedFrame) + } + histBefore := len(d.frame.history.b) + d.current.err = d.current.d.decodeBuf(&d.frame.history) + + if d.current.err != nil { + println("error after:", d.current.err) + return false + } + d.current.b = d.frame.history.b[histBefore:] + if debugDecoder { + println("history after:", len(d.frame.history.b)) + } + + // Check frame size (before CRC) + d.syncStream.decodedFrame += uint64(len(d.current.b)) + if d.syncStream.decodedFrame > d.frame.FrameContentSize { + if debugDecoder { + printf("DecodedFrame (%d) > FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize) + } + d.current.err = ErrFrameSizeExceeded + return false + } + + // Check FCS + if d.current.d.Last && d.frame.FrameContentSize != fcsUnknown && d.syncStream.decodedFrame != d.frame.FrameContentSize { + if debugDecoder { + printf("DecodedFrame (%d) != FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize) + } + d.current.err = ErrFrameSizeMismatch + return false + } + + // Update/Check CRC + if d.frame.HasCheckSum { + if !d.o.ignoreChecksum { + d.frame.crc.Write(d.current.b) + } + if d.current.d.Last { + if !d.o.ignoreChecksum { + d.current.err = d.frame.checkCRC() + } else { + d.current.err = d.frame.consumeCRC() + } + if d.current.err != nil { + println("CRC error:", d.current.err) + return false + } + } + } + d.syncStream.inFrame = !d.current.d.Last + } + return true +} + +func (d *Decoder) stashDecoder() { + if d.current.d != nil { + if debugDecoder { + printf("re-adding current decoder %p", d.current.d) + } + d.decoders <- d.current.d + d.current.d = nil + } +} + +// Close will release all resources. +// It is NOT possible to reuse the decoder after this. +func (d *Decoder) Close() { + if d.current.err == ErrDecoderClosed { + return + } + d.drainOutput() + if d.current.cancel != nil { + d.current.cancel() + d.streamWg.Wait() + d.current.cancel = nil + } + if d.decoders != nil { + close(d.decoders) + for dec := range d.decoders { + dec.Close() + } + d.decoders = nil + } + if d.current.d != nil { + d.current.d.Close() + d.current.d = nil + } + d.current.err = ErrDecoderClosed +} + +// IOReadCloser returns the decoder as an io.ReadCloser for convenience. +// Any changes to the decoder will be reflected, so the returned ReadCloser +// can be reused along with the decoder. +// io.WriterTo is also supported by the returned ReadCloser. +func (d *Decoder) IOReadCloser() io.ReadCloser { + return closeWrapper{d: d} +} + +// closeWrapper wraps a function call as a closer. +type closeWrapper struct { + d *Decoder +} + +// WriteTo forwards WriteTo calls to the decoder. +func (c closeWrapper) WriteTo(w io.Writer) (n int64, err error) { + return c.d.WriteTo(w) +} + +// Read forwards read calls to the decoder. +func (c closeWrapper) Read(p []byte) (n int, err error) { + return c.d.Read(p) +} + +// Close closes the decoder. +func (c closeWrapper) Close() error { + c.d.Close() + return nil +} + +type decodeOutput struct { + d *blockDec + b []byte + err error +} + +func (d *Decoder) startSyncDecoder(r io.Reader) error { + d.frame.history.reset() + d.syncStream.br = readerWrapper{r: r} + d.syncStream.inFrame = false + d.syncStream.enabled = true + d.syncStream.decodedFrame = 0 + return nil +} + +// Create Decoder: +// ASYNC: +// Spawn 3 go routines. +// 0: Read frames and decode block literals. +// 1: Decode sequences. +// 2: Execute sequences, send to output. +func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output chan decodeOutput) { + defer d.streamWg.Done() + br := readerWrapper{r: r} + + var seqDecode = make(chan *blockDec, d.o.concurrent) + var seqExecute = make(chan *blockDec, d.o.concurrent) + + // Async 1: Decode sequences... + go func() { + var hist history + var hasErr bool + + for block := range seqDecode { + if hasErr { + if block != nil { + seqExecute <- block + } + continue + } + if block.async.newHist != nil { + if debugDecoder { + println("Async 1: new history, recent:", block.async.newHist.recentOffsets) + } + hist.reset() + hist.decoders = block.async.newHist.decoders + hist.recentOffsets = block.async.newHist.recentOffsets + hist.windowSize = block.async.newHist.windowSize + if block.async.newHist.dict != nil { + hist.setDict(block.async.newHist.dict) + } + } + if block.err != nil || block.Type != blockTypeCompressed { + hasErr = block.err != nil + seqExecute <- block + continue + } + + hist.decoders.literals = block.async.literals + block.err = block.prepareSequences(block.async.seqData, &hist) + if debugDecoder && block.err != nil { + println("prepareSequences returned:", block.err) + } + hasErr = block.err != nil + if block.err == nil { + block.err = block.decodeSequences(&hist) + if debugDecoder && block.err != nil { + println("decodeSequences returned:", block.err) + } + hasErr = block.err != nil + // block.async.sequence = hist.decoders.seq[:hist.decoders.nSeqs] + block.async.seqSize = hist.decoders.seqSize + } + seqExecute <- block + } + close(seqExecute) + hist.reset() + }() + + var wg sync.WaitGroup + wg.Add(1) + + // Async 3: Execute sequences... + frameHistCache := d.frame.history.b + go func() { + var hist history + var decodedFrame uint64 + var fcs uint64 + var hasErr bool + for block := range seqExecute { + out := decodeOutput{err: block.err, d: block} + if block.err != nil || hasErr { + hasErr = true + output <- out + continue + } + if block.async.newHist != nil { + if debugDecoder { + println("Async 2: new history") + } + hist.reset() + hist.windowSize = block.async.newHist.windowSize + hist.allocFrameBuffer = block.async.newHist.allocFrameBuffer + if block.async.newHist.dict != nil { + hist.setDict(block.async.newHist.dict) + } + + if cap(hist.b) < hist.allocFrameBuffer { + if cap(frameHistCache) >= hist.allocFrameBuffer { + hist.b = frameHistCache + } else { + hist.b = make([]byte, 0, hist.allocFrameBuffer) + println("Alloc history sized", hist.allocFrameBuffer) + } + } + hist.b = hist.b[:0] + fcs = block.async.fcs + decodedFrame = 0 + } + do := decodeOutput{err: block.err, d: block} + switch block.Type { + case blockTypeRLE: + if debugDecoder { + println("add rle block length:", block.RLESize) + } + + if cap(block.dst) < int(block.RLESize) { + if block.lowMem { + block.dst = make([]byte, block.RLESize) + } else { + block.dst = make([]byte, maxCompressedBlockSize) + } + } + block.dst = block.dst[:block.RLESize] + v := block.data[0] + for i := range block.dst { + block.dst[i] = v + } + hist.append(block.dst) + do.b = block.dst + case blockTypeRaw: + if debugDecoder { + println("add raw block length:", len(block.data)) + } + hist.append(block.data) + do.b = block.data + case blockTypeCompressed: + if debugDecoder { + println("execute with history length:", len(hist.b), "window:", hist.windowSize) + } + hist.decoders.seqSize = block.async.seqSize + hist.decoders.literals = block.async.literals + do.err = block.executeSequences(&hist) + hasErr = do.err != nil + if debugDecoder && hasErr { + println("executeSequences returned:", do.err) + } + do.b = block.dst + } + if !hasErr { + decodedFrame += uint64(len(do.b)) + if decodedFrame > fcs { + println("fcs exceeded", block.Last, fcs, decodedFrame) + do.err = ErrFrameSizeExceeded + hasErr = true + } else if block.Last && fcs != fcsUnknown && decodedFrame != fcs { + do.err = ErrFrameSizeMismatch + hasErr = true + } else { + if debugDecoder { + println("fcs ok", block.Last, fcs, decodedFrame) + } + } + } + output <- do + } + close(output) + frameHistCache = hist.b + wg.Done() + if debugDecoder { + println("decoder goroutines finished") + } + hist.reset() + }() + + var hist history +decodeStream: + for { + var hasErr bool + hist.reset() + decodeBlock := func(block *blockDec) { + if hasErr { + if block != nil { + seqDecode <- block + } + return + } + if block.err != nil || block.Type != blockTypeCompressed { + hasErr = block.err != nil + seqDecode <- block + return + } + + remain, err := block.decodeLiterals(block.data, &hist) + block.err = err + hasErr = block.err != nil + if err == nil { + block.async.literals = hist.decoders.literals + block.async.seqData = remain + } else if debugDecoder { + println("decodeLiterals error:", err) + } + seqDecode <- block + } + frame := d.frame + if debugDecoder { + println("New frame...") + } + var historySent bool + frame.history.reset() + err := frame.reset(&br) + if debugDecoder && err != nil { + println("Frame decoder returned", err) + } + if err == nil { + err = d.setDict(frame) + } + if err == nil && d.frame.WindowSize > d.o.maxWindowSize { + if debugDecoder { + println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize) + } + + err = ErrDecoderSizeExceeded + } + if err != nil { + select { + case <-ctx.Done(): + case dec := <-d.decoders: + dec.sendErr(err) + decodeBlock(dec) + } + break decodeStream + } + + // Go through all blocks of the frame. + for { + var dec *blockDec + select { + case <-ctx.Done(): + break decodeStream + case dec = <-d.decoders: + // Once we have a decoder, we MUST return it. + } + err := frame.next(dec) + if !historySent { + h := frame.history + if debugDecoder { + println("Alloc History:", h.allocFrameBuffer) + } + hist.reset() + if h.dict != nil { + hist.setDict(h.dict) + } + dec.async.newHist = &h + dec.async.fcs = frame.FrameContentSize + historySent = true + } else { + dec.async.newHist = nil + } + if debugDecoder && err != nil { + println("next block returned error:", err) + } + dec.err = err + dec.hasCRC = false + if dec.Last && frame.HasCheckSum && err == nil { + crc, err := frame.rawInput.readSmall(4) + if len(crc) < 4 { + if err == nil { + err = io.ErrUnexpectedEOF + + } + println("CRC missing?", err) + dec.err = err + } else { + dec.checkCRC = binary.LittleEndian.Uint32(crc) + dec.hasCRC = true + if debugDecoder { + printf("found crc to check: %08x\n", dec.checkCRC) + } + } + } + err = dec.err + last := dec.Last + decodeBlock(dec) + if err != nil { + break decodeStream + } + if last { + break + } + } + } + close(seqDecode) + wg.Wait() + hist.reset() + d.frame.history.b = frameHistCache +} + +func (d *Decoder) setDict(frame *frameDec) (err error) { + dict, ok := d.dicts[frame.DictionaryID] + if ok { + if debugDecoder { + println("setting dict", frame.DictionaryID) + } + frame.history.setDict(dict) + } else if frame.DictionaryID != 0 { + // A zero or missing dictionary id is ambiguous: + // either dictionary zero, or no dictionary. In particular, + // zstd --patch-from uses this id for the source file, + // so only return an error if the dictionary id is not zero. + err = ErrUnknownDictionary + } + return err +} diff --git a/vendor/github.com/klauspost/compress/zstd/decoder_options.go b/vendor/github.com/klauspost/compress/zstd/decoder_options.go new file mode 100644 index 000000000..774c5f00f --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/decoder_options.go @@ -0,0 +1,169 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "errors" + "fmt" + "math/bits" + "runtime" +) + +// DOption is an option for creating a decoder. +type DOption func(*decoderOptions) error + +// options retains accumulated state of multiple options. +type decoderOptions struct { + lowMem bool + concurrent int + maxDecodedSize uint64 + maxWindowSize uint64 + dicts []*dict + ignoreChecksum bool + limitToCap bool + decodeBufsBelow int +} + +func (o *decoderOptions) setDefault() { + *o = decoderOptions{ + // use less ram: true for now, but may change. + lowMem: true, + concurrent: runtime.GOMAXPROCS(0), + maxWindowSize: MaxWindowSize, + decodeBufsBelow: 128 << 10, + } + if o.concurrent > 4 { + o.concurrent = 4 + } + o.maxDecodedSize = 64 << 30 +} + +// WithDecoderLowmem will set whether to use a lower amount of memory, +// but possibly have to allocate more while running. +func WithDecoderLowmem(b bool) DOption { + return func(o *decoderOptions) error { o.lowMem = b; return nil } +} + +// WithDecoderConcurrency sets the number of created decoders. +// When decoding block with DecodeAll, this will limit the number +// of possible concurrently running decodes. +// When decoding streams, this will limit the number of +// inflight blocks. +// When decoding streams and setting maximum to 1, +// no async decoding will be done. +// When a value of 0 is provided GOMAXPROCS will be used. +// By default this will be set to 4 or GOMAXPROCS, whatever is lower. +func WithDecoderConcurrency(n int) DOption { + return func(o *decoderOptions) error { + if n < 0 { + return errors.New("concurrency must be at least 1") + } + if n == 0 { + o.concurrent = runtime.GOMAXPROCS(0) + } else { + o.concurrent = n + } + return nil + } +} + +// WithDecoderMaxMemory allows to set a maximum decoded size for in-memory +// non-streaming operations or maximum window size for streaming operations. +// This can be used to control memory usage of potentially hostile content. +// Maximum is 1 << 63 bytes. Default is 64GiB. +func WithDecoderMaxMemory(n uint64) DOption { + return func(o *decoderOptions) error { + if n == 0 { + return errors.New("WithDecoderMaxMemory must be at least 1") + } + if n > 1<<63 { + return errors.New("WithDecoderMaxmemory must be less than 1 << 63") + } + o.maxDecodedSize = n + return nil + } +} + +// WithDecoderDicts allows to register one or more dictionaries for the decoder. +// +// Each slice in dict must be in the [dictionary format] produced by +// "zstd --train" from the Zstandard reference implementation. +// +// If several dictionaries with the same ID are provided, the last one will be used. +// +// [dictionary format]: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format +func WithDecoderDicts(dicts ...[]byte) DOption { + return func(o *decoderOptions) error { + for _, b := range dicts { + d, err := loadDict(b) + if err != nil { + return err + } + o.dicts = append(o.dicts, d) + } + return nil + } +} + +// WithDecoderDictRaw registers a dictionary that may be used by the decoder. +// The slice content can be arbitrary data. +func WithDecoderDictRaw(id uint32, content []byte) DOption { + return func(o *decoderOptions) error { + if bits.UintSize > 32 && uint(len(content)) > dictMaxLength { + return fmt.Errorf("dictionary of size %d > 2GiB too large", len(content)) + } + o.dicts = append(o.dicts, &dict{id: id, content: content, offsets: [3]int{1, 4, 8}}) + return nil + } +} + +// WithDecoderMaxWindow allows to set a maximum window size for decodes. +// This allows rejecting packets that will cause big memory usage. +// The Decoder will likely allocate more memory based on the WithDecoderLowmem setting. +// If WithDecoderMaxMemory is set to a lower value, that will be used. +// Default is 512MB, Maximum is ~3.75 TB as per zstandard spec. +func WithDecoderMaxWindow(size uint64) DOption { + return func(o *decoderOptions) error { + if size < MinWindowSize { + return errors.New("WithMaxWindowSize must be at least 1KB, 1024 bytes") + } + if size > (1<<41)+7*(1<<38) { + return errors.New("WithMaxWindowSize must be less than (1<<41) + 7*(1<<38) ~ 3.75TB") + } + o.maxWindowSize = size + return nil + } +} + +// WithDecodeAllCapLimit will limit DecodeAll to decoding cap(dst)-len(dst) bytes, +// or any size set in WithDecoderMaxMemory. +// This can be used to limit decoding to a specific maximum output size. +// Disabled by default. +func WithDecodeAllCapLimit(b bool) DOption { + return func(o *decoderOptions) error { + o.limitToCap = b + return nil + } +} + +// WithDecodeBuffersBelow will fully decode readers that have a +// `Bytes() []byte` and `Len() int` interface similar to bytes.Buffer. +// This typically uses less allocations but will have the full decompressed object in memory. +// Note that DecodeAllCapLimit will disable this, as well as giving a size of 0 or less. +// Default is 128KiB. +func WithDecodeBuffersBelow(size int) DOption { + return func(o *decoderOptions) error { + o.decodeBufsBelow = size + return nil + } +} + +// IgnoreChecksum allows to forcibly ignore checksum checking. +func IgnoreChecksum(b bool) DOption { + return func(o *decoderOptions) error { + o.ignoreChecksum = b + return nil + } +} diff --git a/vendor/github.com/klauspost/compress/zstd/dict.go b/vendor/github.com/klauspost/compress/zstd/dict.go new file mode 100644 index 000000000..8d5567fe6 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/dict.go @@ -0,0 +1,534 @@ +package zstd + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "sort" + + "github.com/klauspost/compress/huff0" +) + +type dict struct { + id uint32 + + litEnc *huff0.Scratch + llDec, ofDec, mlDec sequenceDec + offsets [3]int + content []byte +} + +const dictMagic = "\x37\xa4\x30\xec" + +// Maximum dictionary size for the reference implementation (1.5.3) is 2 GiB. +const dictMaxLength = 1 << 31 + +// ID returns the dictionary id or 0 if d is nil. +func (d *dict) ID() uint32 { + if d == nil { + return 0 + } + return d.id +} + +// ContentSize returns the dictionary content size or 0 if d is nil. +func (d *dict) ContentSize() int { + if d == nil { + return 0 + } + return len(d.content) +} + +// Content returns the dictionary content. +func (d *dict) Content() []byte { + if d == nil { + return nil + } + return d.content +} + +// Offsets returns the initial offsets. +func (d *dict) Offsets() [3]int { + if d == nil { + return [3]int{} + } + return d.offsets +} + +// LitEncoder returns the literal encoder. +func (d *dict) LitEncoder() *huff0.Scratch { + if d == nil { + return nil + } + return d.litEnc +} + +// Load a dictionary as described in +// https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format +func loadDict(b []byte) (*dict, error) { + // Check static field size. + if len(b) <= 8+(3*4) { + return nil, io.ErrUnexpectedEOF + } + d := dict{ + llDec: sequenceDec{fse: &fseDecoder{}}, + ofDec: sequenceDec{fse: &fseDecoder{}}, + mlDec: sequenceDec{fse: &fseDecoder{}}, + } + if string(b[:4]) != dictMagic { + return nil, ErrMagicMismatch + } + d.id = binary.LittleEndian.Uint32(b[4:8]) + if d.id == 0 { + return nil, errors.New("dictionaries cannot have ID 0") + } + + // Read literal table + var err error + d.litEnc, b, err = huff0.ReadTable(b[8:], nil) + if err != nil { + return nil, fmt.Errorf("loading literal table: %w", err) + } + d.litEnc.Reuse = huff0.ReusePolicyMust + + br := byteReader{ + b: b, + off: 0, + } + readDec := func(i tableIndex, dec *fseDecoder) error { + if err := dec.readNCount(&br, uint16(maxTableSymbol[i])); err != nil { + return err + } + if br.overread() { + return io.ErrUnexpectedEOF + } + err = dec.transform(symbolTableX[i]) + if err != nil { + println("Transform table error:", err) + return err + } + if debugDecoder || debugEncoder { + println("Read table ok", "symbolLen:", dec.symbolLen) + } + // Set decoders as predefined so they aren't reused. + dec.preDefined = true + return nil + } + + if err := readDec(tableOffsets, d.ofDec.fse); err != nil { + return nil, err + } + if err := readDec(tableMatchLengths, d.mlDec.fse); err != nil { + return nil, err + } + if err := readDec(tableLiteralLengths, d.llDec.fse); err != nil { + return nil, err + } + if br.remain() < 12 { + return nil, io.ErrUnexpectedEOF + } + + d.offsets[0] = int(br.Uint32()) + br.advance(4) + d.offsets[1] = int(br.Uint32()) + br.advance(4) + d.offsets[2] = int(br.Uint32()) + br.advance(4) + if d.offsets[0] <= 0 || d.offsets[1] <= 0 || d.offsets[2] <= 0 { + return nil, errors.New("invalid offset in dictionary") + } + d.content = make([]byte, br.remain()) + copy(d.content, br.unread()) + if d.offsets[0] > len(d.content) || d.offsets[1] > len(d.content) || d.offsets[2] > len(d.content) { + return nil, fmt.Errorf("initial offset bigger than dictionary content size %d, offsets: %v", len(d.content), d.offsets) + } + + return &d, nil +} + +// InspectDictionary loads a zstd dictionary and provides functions to inspect the content. +func InspectDictionary(b []byte) (interface { + ID() uint32 + ContentSize() int + Content() []byte + Offsets() [3]int + LitEncoder() *huff0.Scratch +}, error) { + initPredefined() + d, err := loadDict(b) + return d, err +} + +type BuildDictOptions struct { + // Dictionary ID. + ID uint32 + + // Content to use to create dictionary tables. + Contents [][]byte + + // History to use for all blocks. + History []byte + + // Offsets to use. + Offsets [3]int + + // CompatV155 will make the dictionary compatible with Zstd v1.5.5 and earlier. + // See https://github.com/facebook/zstd/issues/3724 + CompatV155 bool + + // Use the specified encoder level. + // The dictionary will be built using the specified encoder level, + // which will reflect speed and make the dictionary tailored for that level. + // If not set SpeedBestCompression will be used. + Level EncoderLevel + + // DebugOut will write stats and other details here if set. + DebugOut io.Writer +} + +func BuildDict(o BuildDictOptions) ([]byte, error) { + initPredefined() + hist := o.History + contents := o.Contents + debug := o.DebugOut != nil + println := func(args ...interface{}) { + if o.DebugOut != nil { + fmt.Fprintln(o.DebugOut, args...) + } + } + printf := func(s string, args ...interface{}) { + if o.DebugOut != nil { + fmt.Fprintf(o.DebugOut, s, args...) + } + } + print := func(args ...interface{}) { + if o.DebugOut != nil { + fmt.Fprint(o.DebugOut, args...) + } + } + + if int64(len(hist)) > dictMaxLength { + return nil, fmt.Errorf("dictionary of size %d > %d", len(hist), int64(dictMaxLength)) + } + if len(hist) < 8 { + return nil, fmt.Errorf("dictionary of size %d < %d", len(hist), 8) + } + if len(contents) == 0 { + return nil, errors.New("no content provided") + } + d := dict{ + id: o.ID, + litEnc: nil, + llDec: sequenceDec{}, + ofDec: sequenceDec{}, + mlDec: sequenceDec{}, + offsets: o.Offsets, + content: hist, + } + block := blockEnc{lowMem: false} + block.init() + enc := encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}}) + if o.Level != 0 { + eOpts := encoderOptions{ + level: o.Level, + blockSize: maxMatchLen, + windowSize: maxMatchLen, + dict: &d, + lowMem: false, + } + enc = eOpts.encoder() + } else { + o.Level = SpeedBestCompression + } + var ( + remain [256]int + ll [256]int + ml [256]int + of [256]int + ) + addValues := func(dst *[256]int, src []byte) { + for _, v := range src { + dst[v]++ + } + } + addHist := func(dst *[256]int, src *[256]uint32) { + for i, v := range src { + dst[i] += int(v) + } + } + seqs := 0 + nUsed := 0 + litTotal := 0 + newOffsets := make(map[uint32]int, 1000) + for _, b := range contents { + block.reset(nil) + if len(b) < 8 { + continue + } + nUsed++ + enc.Reset(&d, true) + enc.Encode(&block, b) + addValues(&remain, block.literals) + litTotal += len(block.literals) + seqs += len(block.sequences) + block.genCodes() + addHist(&ll, block.coders.llEnc.Histogram()) + addHist(&ml, block.coders.mlEnc.Histogram()) + addHist(&of, block.coders.ofEnc.Histogram()) + for i, seq := range block.sequences { + if i > 3 { + break + } + offset := seq.offset + if offset == 0 { + continue + } + if offset > 3 { + newOffsets[offset-3]++ + } else { + newOffsets[uint32(o.Offsets[offset-1])]++ + } + } + } + // Find most used offsets. + var sortedOffsets []uint32 + for k := range newOffsets { + sortedOffsets = append(sortedOffsets, k) + } + sort.Slice(sortedOffsets, func(i, j int) bool { + a, b := sortedOffsets[i], sortedOffsets[j] + if a == b { + // Prefer the longer offset + return sortedOffsets[i] > sortedOffsets[j] + } + return newOffsets[sortedOffsets[i]] > newOffsets[sortedOffsets[j]] + }) + if len(sortedOffsets) > 3 { + if debug { + print("Offsets:") + for i, v := range sortedOffsets { + if i > 20 { + break + } + printf("[%d: %d],", v, newOffsets[v]) + } + println("") + } + + sortedOffsets = sortedOffsets[:3] + } + for i, v := range sortedOffsets { + o.Offsets[i] = int(v) + } + if debug { + println("New repeat offsets", o.Offsets) + } + + if nUsed == 0 || seqs == 0 { + return nil, fmt.Errorf("%d blocks, %d sequences found", nUsed, seqs) + } + if debug { + println("Sequences:", seqs, "Blocks:", nUsed, "Literals:", litTotal) + } + if seqs/nUsed < 512 { + // Use 512 as minimum. + nUsed = seqs / 512 + } + copyHist := func(dst *fseEncoder, src *[256]int) ([]byte, error) { + hist := dst.Histogram() + var maxSym uint8 + var maxCount int + var fakeLength int + for i, v := range src { + if v > 0 { + v = v / nUsed + if v == 0 { + v = 1 + } + } + if v > maxCount { + maxCount = v + } + if v != 0 { + maxSym = uint8(i) + } + fakeLength += v + hist[i] = uint32(v) + } + dst.HistogramFinished(maxSym, maxCount) + dst.reUsed = false + dst.useRLE = false + err := dst.normalizeCount(fakeLength) + if err != nil { + return nil, err + } + if debug { + println("RAW:", dst.count[:maxSym+1], "NORM:", dst.norm[:maxSym+1], "LEN:", fakeLength) + } + return dst.writeCount(nil) + } + if debug { + print("Literal lengths: ") + } + llTable, err := copyHist(block.coders.llEnc, &ll) + if err != nil { + return nil, err + } + if debug { + print("Match lengths: ") + } + mlTable, err := copyHist(block.coders.mlEnc, &ml) + if err != nil { + return nil, err + } + if debug { + print("Offsets: ") + } + ofTable, err := copyHist(block.coders.ofEnc, &of) + if err != nil { + return nil, err + } + + // Literal table + avgSize := litTotal + if avgSize > huff0.BlockSizeMax/2 { + avgSize = huff0.BlockSizeMax / 2 + } + huffBuff := make([]byte, 0, avgSize) + // Target size + div := litTotal / avgSize + if div < 1 { + div = 1 + } + if debug { + println("Huffman weights:") + } + for i, n := range remain[:] { + if n > 0 { + n = n / div + // Allow all entries to be represented. + if n == 0 { + n = 1 + } + huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) + if debug { + printf("[%d: %d], ", i, n) + } + } + } + if o.CompatV155 && remain[255]/div == 0 { + huffBuff = append(huffBuff, 255) + } + scratch := &huff0.Scratch{TableLog: 11} + for tries := 0; tries < 255; tries++ { + scratch = &huff0.Scratch{TableLog: 11} + _, _, err = huff0.Compress1X(huffBuff, scratch) + if err == nil { + break + } + if debug { + printf("Try %d: Huffman error: %v\n", tries+1, err) + } + huffBuff = huffBuff[:0] + if tries == 250 { + if debug { + println("Huffman: Bailing out with predefined table") + } + + // Bail out.... Just generate something + huffBuff = append(huffBuff, bytes.Repeat([]byte{255}, 10000)...) + for i := 0; i < 128; i++ { + huffBuff = append(huffBuff, byte(i)) + } + continue + } + if errors.Is(err, huff0.ErrIncompressible) { + // Try truncating least common. + for i, n := range remain[:] { + if n > 0 { + n = n / (div * (i + 1)) + if n > 0 { + huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) + } + } + } + if o.CompatV155 && len(huffBuff) > 0 && huffBuff[len(huffBuff)-1] != 255 { + huffBuff = append(huffBuff, 255) + } + if len(huffBuff) == 0 { + huffBuff = append(huffBuff, 0, 255) + } + } + if errors.Is(err, huff0.ErrUseRLE) { + for i, n := range remain[:] { + n = n / (div * (i + 1)) + // Allow all entries to be represented. + if n == 0 { + n = 1 + } + huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) + } + } + } + + var out bytes.Buffer + out.Write([]byte(dictMagic)) + out.Write(binary.LittleEndian.AppendUint32(nil, o.ID)) + out.Write(scratch.OutTable) + if debug { + println("huff table:", len(scratch.OutTable), "bytes") + println("of table:", len(ofTable), "bytes") + println("ml table:", len(mlTable), "bytes") + println("ll table:", len(llTable), "bytes") + } + out.Write(ofTable) + out.Write(mlTable) + out.Write(llTable) + out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[0]))) + out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[1]))) + out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[2]))) + out.Write(hist) + if debug { + _, err := loadDict(out.Bytes()) + if err != nil { + panic(err) + } + i, err := InspectDictionary(out.Bytes()) + if err != nil { + panic(err) + } + println("ID:", i.ID()) + println("Content size:", i.ContentSize()) + println("Encoder:", i.LitEncoder() != nil) + println("Offsets:", i.Offsets()) + var totalSize int + for _, b := range contents { + totalSize += len(b) + } + + encWith := func(opts ...EOption) int { + enc, err := NewWriter(nil, opts...) + if err != nil { + panic(err) + } + defer enc.Close() + var dst []byte + var totalSize int + for _, b := range contents { + dst = enc.EncodeAll(b, dst[:0]) + totalSize += len(dst) + } + return totalSize + } + plain := encWith(WithEncoderLevel(o.Level)) + withDict := encWith(WithEncoderLevel(o.Level), WithEncoderDict(out.Bytes())) + println("Input size:", totalSize) + println("Plain Compressed:", plain) + println("Dict Compressed:", withDict) + println("Saved:", plain-withDict, (plain-withDict)/len(contents), "bytes per input (rounded down)") + } + return out.Bytes(), nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_base.go b/vendor/github.com/klauspost/compress/zstd/enc_base.go new file mode 100644 index 000000000..5ca46038a --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/enc_base.go @@ -0,0 +1,173 @@ +package zstd + +import ( + "fmt" + "math/bits" + + "github.com/klauspost/compress/zstd/internal/xxhash" +) + +const ( + dictShardBits = 6 +) + +type fastBase struct { + // cur is the offset at the start of hist + cur int32 + // maximum offset. Should be at least 2x block size. + maxMatchOff int32 + bufferReset int32 + hist []byte + crc *xxhash.Digest + tmp [8]byte + blk *blockEnc + lastDictID uint32 + lowMem bool +} + +// CRC returns the underlying CRC writer. +func (e *fastBase) CRC() *xxhash.Digest { + return e.crc +} + +// AppendCRC will append the CRC to the destination slice and return it. +func (e *fastBase) AppendCRC(dst []byte) []byte { + crc := e.crc.Sum(e.tmp[:0]) + dst = append(dst, crc[7], crc[6], crc[5], crc[4]) + return dst +} + +// WindowSize returns the window size of the encoder, +// or a window size small enough to contain the input size, if > 0. +func (e *fastBase) WindowSize(size int64) int32 { + if size > 0 && size < int64(e.maxMatchOff) { + b := int32(1) << uint(bits.Len(uint(size))) + // Keep minimum window. + if b < 1024 { + b = 1024 + } + return b + } + return e.maxMatchOff +} + +// Block returns the current block. +func (e *fastBase) Block() *blockEnc { + return e.blk +} + +func (e *fastBase) addBlock(src []byte) int32 { + if debugAsserts && e.cur > e.bufferReset { + panic(fmt.Sprintf("ecur (%d) > buffer reset (%d)", e.cur, e.bufferReset)) + } + // check if we have space already + if len(e.hist)+len(src) > cap(e.hist) { + if cap(e.hist) == 0 { + e.ensureHist(len(src)) + } else { + if cap(e.hist) < int(e.maxMatchOff+maxCompressedBlockSize) { + panic(fmt.Errorf("unexpected buffer cap %d, want at least %d with window %d", cap(e.hist), e.maxMatchOff+maxCompressedBlockSize, e.maxMatchOff)) + } + // Move down + offset := int32(len(e.hist)) - e.maxMatchOff + copy(e.hist[0:e.maxMatchOff], e.hist[offset:]) + e.cur += offset + e.hist = e.hist[:e.maxMatchOff] + } + } + s := int32(len(e.hist)) + e.hist = append(e.hist, src...) + return s +} + +// ensureHist will ensure that history can keep at least this many bytes. +func (e *fastBase) ensureHist(n int) { + if cap(e.hist) >= n { + return + } + l := e.maxMatchOff + if (e.lowMem && e.maxMatchOff > maxCompressedBlockSize) || e.maxMatchOff <= maxCompressedBlockSize { + l += maxCompressedBlockSize + } else { + l += e.maxMatchOff + } + // Make it at least 1MB. + if l < 1<<20 && !e.lowMem { + l = 1 << 20 + } + // Make it at least the requested size. + if l < int32(n) { + l = int32(n) + } + e.hist = make([]byte, 0, l) +} + +// useBlock will replace the block with the provided one, +// but transfer recent offsets from the previous. +func (e *fastBase) UseBlock(enc *blockEnc) { + enc.reset(e.blk) + e.blk = enc +} + +func (e *fastBase) matchlen(s, t int32, src []byte) int32 { + if debugAsserts { + if s < 0 { + err := fmt.Sprintf("s (%d) < 0", s) + panic(err) + } + if t < 0 { + err := fmt.Sprintf("s (%d) < 0", s) + panic(err) + } + if s-t > e.maxMatchOff { + err := fmt.Sprintf("s (%d) - t (%d) > maxMatchOff (%d)", s, t, e.maxMatchOff) + panic(err) + } + if len(src)-int(s) > maxCompressedBlockSize { + panic(fmt.Sprintf("len(src)-s (%d) > maxCompressedBlockSize (%d)", len(src)-int(s), maxCompressedBlockSize)) + } + } + return int32(matchLen(src[s:], src[t:])) +} + +// Reset the encoding table. +func (e *fastBase) resetBase(d *dict, singleBlock bool) { + if e.blk == nil { + e.blk = &blockEnc{lowMem: e.lowMem} + e.blk.init() + } else { + e.blk.reset(nil) + } + e.blk.initNewEncode() + if e.crc == nil { + e.crc = xxhash.New() + } else { + e.crc.Reset() + } + e.blk.dictLitEnc = nil + if d != nil { + low := e.lowMem + if singleBlock { + e.lowMem = true + } + e.ensureHist(d.ContentSize() + maxCompressedBlockSize) + e.lowMem = low + } + + // We offset current position so everything will be out of reach. + // If above reset line, history will be purged. + if e.cur < e.bufferReset { + e.cur += e.maxMatchOff + int32(len(e.hist)) + } + e.hist = e.hist[:0] + if d != nil { + // Set offsets (currently not used) + for i, off := range d.offsets { + e.blk.recentOffsets[i] = uint32(off) + e.blk.prevRecentOffsets[i] = e.blk.recentOffsets[i] + } + // Transfer litenc. + e.blk.dictLitEnc = d.litEnc + e.hist = append(e.hist, d.content...) + } +} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_best.go b/vendor/github.com/klauspost/compress/zstd/enc_best.go new file mode 100644 index 000000000..c81a15357 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/enc_best.go @@ -0,0 +1,541 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "bytes" + "fmt" + + "github.com/klauspost/compress" +) + +const ( + bestLongTableBits = 22 // Bits used in the long match table + bestLongTableSize = 1 << bestLongTableBits // Size of the table + bestLongLen = 8 // Bytes used for table hash + + // Note: Increasing the short table bits or making the hash shorter + // can actually lead to compression degradation since it will 'steal' more from the + // long match table and match offsets are quite big. + // This greatly depends on the type of input. + bestShortTableBits = 18 // Bits used in the short match table + bestShortTableSize = 1 << bestShortTableBits // Size of the table + bestShortLen = 4 // Bytes used for table hash + +) + +type match struct { + offset int32 + s int32 + length int32 + rep int32 + est int32 +} + +const highScore = maxMatchLen * 8 + +// estBits will estimate output bits from predefined tables. +func (m *match) estBits(bitsPerByte int32) { + mlc := mlCode(uint32(m.length - zstdMinMatch)) + var ofc uint8 + if m.rep < 0 { + ofc = ofCode(uint32(m.s-m.offset) + 3) + } else { + ofc = ofCode(uint32(m.rep) & 3) + } + // Cost, excluding + ofTT, mlTT := fsePredefEnc[tableOffsets].ct.symbolTT[ofc], fsePredefEnc[tableMatchLengths].ct.symbolTT[mlc] + + // Add cost of match encoding... + m.est = int32(ofTT.outBits + mlTT.outBits) + m.est += int32(ofTT.deltaNbBits>>16 + mlTT.deltaNbBits>>16) + // Subtract savings compared to literal encoding... + m.est -= (m.length * bitsPerByte) >> 10 + if m.est > 0 { + // Unlikely gain.. + m.length = 0 + m.est = highScore + } +} + +// bestFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches. +// The long match table contains the previous entry with the same hash, +// effectively making it a "chain" of length 2. +// When we find a long match we choose between the two values and select the longest. +// When we find a short match, after checking the long, we check if we can find a long at n+1 +// and that it is longer (lazy matching). +type bestFastEncoder struct { + fastBase + table [bestShortTableSize]prevEntry + longTable [bestLongTableSize]prevEntry + dictTable []prevEntry + dictLongTable []prevEntry +} + +// Encode improves compression... +func (e *bestFastEncoder) Encode(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 4 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + e.table = [bestShortTableSize]prevEntry{} + e.longTable = [bestLongTableSize]prevEntry{} + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + v2 := e.table[i].prev + if v < minOff { + v = 0 + v2 = 0 + } else { + v = v - e.cur + e.maxMatchOff + if v2 < minOff { + v2 = 0 + } else { + v2 = v2 - e.cur + e.maxMatchOff + } + } + e.table[i] = prevEntry{ + offset: v, + prev: v2, + } + } + for i := range e.longTable[:] { + v := e.longTable[i].offset + v2 := e.longTable[i].prev + if v < minOff { + v = 0 + v2 = 0 + } else { + v = v - e.cur + e.maxMatchOff + if v2 < minOff { + v2 = 0 + } else { + v2 = v2 - e.cur + e.maxMatchOff + } + } + e.longTable[i] = prevEntry{ + offset: v, + prev: v2, + } + } + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Use this to estimate literal cost. + // Scaled by 10 bits. + bitsPerByte := int32((compress.ShannonEntropyBits(src) * 1024) / len(src)) + // Huffman can never go < 1 bit/byte + if bitsPerByte < 1024 { + bitsPerByte = 1024 + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + const kSearchStrength = 10 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + offset3 := int32(blk.recentOffsets[2]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + // We allow the encoder to optionally turn off repeat offsets across blocks + canRepeat := len(blk.sequences) > 2 + + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + const goodEnough = 250 + + cv := load6432(src, s) + + nextHashL := hashLen(cv, bestLongTableBits, bestLongLen) + nextHashS := hashLen(cv, bestShortTableBits, bestShortLen) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + // Set m to a match at offset if it looks like that will improve compression. + improve := func(m *match, offset int32, s int32, first uint32, rep int32) { + delta := s - offset + if delta >= e.maxMatchOff || delta <= 0 || load3232(src, offset) != first { + return + } + if debugAsserts { + if offset >= s { + panic(fmt.Sprintf("offset: %d - s:%d - rep: %d - cur :%d - max: %d", offset, s, rep, e.cur, e.maxMatchOff)) + } + if !bytes.Equal(src[s:s+4], src[offset:offset+4]) { + panic(fmt.Sprintf("first match mismatch: %v != %v, first: %08x", src[s:s+4], src[offset:offset+4], first)) + } + } + // Try to quick reject if we already have a long match. + if m.length > 16 { + left := len(src) - int(m.s+m.length) + // If we are too close to the end, keep as is. + if left <= 0 { + return + } + checkLen := m.length - (s - m.s) - 8 + if left > 2 && checkLen > 4 { + // Check 4 bytes, 4 bytes from the end of the current match. + a := load3232(src, offset+checkLen) + b := load3232(src, s+checkLen) + if a != b { + return + } + } + } + l := 4 + e.matchlen(s+4, offset+4, src) + if true { + // Extend candidate match backwards as far as possible. + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for offset > tMin && s > nextEmit && src[offset-1] == src[s-1] && l < maxMatchLength { + s-- + offset-- + l++ + } + } + + cand := match{offset: offset, s: s, length: l, rep: rep} + cand.estBits(bitsPerByte) + if m.est >= highScore || cand.est-m.est+(cand.s-m.s)*bitsPerByte>>10 < 0 { + *m = cand + } + } + + best := match{s: s, est: highScore} + improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.prev-e.cur, s, uint32(cv), -1) + + if canRepeat && best.length < goodEnough { + if s == nextEmit { + // Check repeats straight after a match. + improve(&best, s-offset2, s, uint32(cv), 1|4) + improve(&best, s-offset3, s, uint32(cv), 2|4) + if offset1 > 1 { + improve(&best, s-(offset1-1), s, uint32(cv), 3|4) + } + } + + // If either no match or a non-repeat match, check at + 1 + if best.rep <= 0 { + cv32 := uint32(cv >> 8) + spp := s + 1 + improve(&best, spp-offset1, spp, cv32, 1) + improve(&best, spp-offset2, spp, cv32, 2) + improve(&best, spp-offset3, spp, cv32, 3) + if best.rep < 0 { + cv32 = uint32(cv >> 24) + spp += 2 + improve(&best, spp-offset1, spp, cv32, 1) + improve(&best, spp-offset2, spp, cv32, 2) + improve(&best, spp-offset3, spp, cv32, 3) + } + } + } + // Load next and check... + e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: candidateL.offset} + e.table[nextHashS] = prevEntry{offset: s + e.cur, prev: candidateS.offset} + index0 := s + 1 + + // Look far ahead, unless we have a really long match already... + if best.length < goodEnough { + // No match found, move forward on input, no need to check forward... + if best.length < 4 { + s += 1 + (s-nextEmit)>>(kSearchStrength-1) + if s >= sLimit { + break encodeLoop + } + continue + } + + candidateS = e.table[hashLen(cv>>8, bestShortTableBits, bestShortLen)] + cv = load6432(src, s+1) + cv2 := load6432(src, s+2) + candidateL = e.longTable[hashLen(cv, bestLongTableBits, bestLongLen)] + candidateL2 := e.longTable[hashLen(cv2, bestLongTableBits, bestLongLen)] + + // Short at s+1 + improve(&best, candidateS.offset-e.cur, s+1, uint32(cv), -1) + // Long at s+1, s+2 + improve(&best, candidateL.offset-e.cur, s+1, uint32(cv), -1) + improve(&best, candidateL.prev-e.cur, s+1, uint32(cv), -1) + improve(&best, candidateL2.offset-e.cur, s+2, uint32(cv2), -1) + improve(&best, candidateL2.prev-e.cur, s+2, uint32(cv2), -1) + if false { + // Short at s+3. + // Too often worse... + improve(&best, e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+3, uint32(cv2>>8), -1) + } + + // Start check at a fixed offset to allow for a few mismatches. + // For this compression level 2 yields the best results. + // We cannot do this if we have already indexed this position. + const skipBeginning = 2 + if best.s > s-skipBeginning { + // See if we can find a better match by checking where the current best ends. + // Use that offset to see if we can find a better full match. + if sAt := best.s + best.length; sAt < sLimit { + nextHashL := hashLen(load6432(src, sAt), bestLongTableBits, bestLongLen) + candidateEnd := e.longTable[nextHashL] + + if off := candidateEnd.offset - e.cur - best.length + skipBeginning; off >= 0 { + improve(&best, off, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) + if off := candidateEnd.prev - e.cur - best.length + skipBeginning; off >= 0 { + improve(&best, off, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) + } + } + } + } + } + + if debugAsserts { + if !bytes.Equal(src[best.s:best.s+best.length], src[best.offset:best.offset+best.length]) { + panic(fmt.Sprintf("match mismatch: %v != %v", src[best.s:best.s+best.length], src[best.offset:best.offset+best.length])) + } + } + + // We have a match, we can store the forward value + if best.rep > 0 { + var seq seq + seq.matchLen = uint32(best.length - zstdMinMatch) + if debugAsserts && s < nextEmit { + panic("s < nextEmit") + } + addLiterals(&seq, best.s) + + // Repeat. If bit 4 is set, this is a non-lit repeat. + seq.offset = uint32(best.rep & 3) + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Index old s + 1 -> s - 1 + s = best.s + best.length + nextEmit = s + + // Index skipped... + end := s + if s > sLimit+4 { + end = sLimit + 4 + } + off := index0 + e.cur + for index0 < end { + cv0 := load6432(src, index0) + h0 := hashLen(cv0, bestLongTableBits, bestLongLen) + h1 := hashLen(cv0, bestShortTableBits, bestShortLen) + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset} + off++ + index0++ + } + + switch best.rep { + case 2, 4 | 1: + offset1, offset2 = offset2, offset1 + case 3, 4 | 2: + offset1, offset2, offset3 = offset3, offset1, offset2 + case 4 | 3: + offset1, offset2, offset3 = offset1-1, offset1, offset2 + } + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, best.length) + } + break encodeLoop + } + continue + } + + // A 4-byte match has been found. Update recent offsets. + // We'll later see if more than 4 bytes. + s = best.s + t := best.offset + offset1, offset2, offset3 = s-t, offset1, offset2 + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && int(offset1) > len(src) { + panic("invalid offset") + } + + // Write our sequence + var seq seq + l := best.length + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + + // Index old s + 1 -> s - 1 or sLimit + end := s + if s > sLimit-4 { + end = sLimit - 4 + } + + off := index0 + e.cur + for index0 < end { + cv0 := load6432(src, index0) + h0 := hashLen(cv0, bestLongTableBits, bestLongLen) + h1 := hashLen(cv0, bestShortTableBits, bestShortLen) + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset} + index0++ + off++ + } + if s >= sLimit { + break encodeLoop + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + blk.recentOffsets[2] = uint32(offset3) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// EncodeNoHist will encode a block with no history and no following blocks. +// Most notable difference is that src will not be copied for history and +// we do not need to check for max match length. +func (e *bestFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { + e.ensureHist(len(src)) + e.Encode(blk, src) +} + +// Reset will reset and set a dictionary if not nil +func (e *bestFastEncoder) Reset(d *dict, singleBlock bool) { + e.resetBase(d, singleBlock) + if d == nil { + return + } + // Init or copy dict table + if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { + if len(e.dictTable) != len(e.table) { + e.dictTable = make([]prevEntry, len(e.table)) + } + end := int32(len(d.content)) - 8 + e.maxMatchOff + for i := e.maxMatchOff; i < end; i += 4 { + const hashLog = bestShortTableBits + + cv := load6432(d.content, i-e.maxMatchOff) + nextHash := hashLen(cv, hashLog, bestShortLen) // 0 -> 4 + nextHash1 := hashLen(cv>>8, hashLog, bestShortLen) // 1 -> 5 + nextHash2 := hashLen(cv>>16, hashLog, bestShortLen) // 2 -> 6 + nextHash3 := hashLen(cv>>24, hashLog, bestShortLen) // 3 -> 7 + e.dictTable[nextHash] = prevEntry{ + prev: e.dictTable[nextHash].offset, + offset: i, + } + e.dictTable[nextHash1] = prevEntry{ + prev: e.dictTable[nextHash1].offset, + offset: i + 1, + } + e.dictTable[nextHash2] = prevEntry{ + prev: e.dictTable[nextHash2].offset, + offset: i + 2, + } + e.dictTable[nextHash3] = prevEntry{ + prev: e.dictTable[nextHash3].offset, + offset: i + 3, + } + } + e.lastDictID = d.id + } + + // Init or copy dict table + if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { + if len(e.dictLongTable) != len(e.longTable) { + e.dictLongTable = make([]prevEntry, len(e.longTable)) + } + if len(d.content) >= 8 { + cv := load6432(d.content, 0) + h := hashLen(cv, bestLongTableBits, bestLongLen) + e.dictLongTable[h] = prevEntry{ + offset: e.maxMatchOff, + prev: e.dictLongTable[h].offset, + } + + end := int32(len(d.content)) - 8 + e.maxMatchOff + off := 8 // First to read + for i := e.maxMatchOff + 1; i < end; i++ { + cv = cv>>8 | (uint64(d.content[off]) << 56) + h := hashLen(cv, bestLongTableBits, bestLongLen) + e.dictLongTable[h] = prevEntry{ + offset: i, + prev: e.dictLongTable[h].offset, + } + off++ + } + } + e.lastDictID = d.id + } + // Reset table to initial state + copy(e.longTable[:], e.dictLongTable) + + e.cur = e.maxMatchOff + // Reset table to initial state + copy(e.table[:], e.dictTable) +} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_better.go b/vendor/github.com/klauspost/compress/zstd/enc_better.go new file mode 100644 index 000000000..20d25b0e0 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/enc_better.go @@ -0,0 +1,1241 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import "fmt" + +const ( + betterLongTableBits = 19 // Bits used in the long match table + betterLongTableSize = 1 << betterLongTableBits // Size of the table + betterLongLen = 8 // Bytes used for table hash + + // Note: Increasing the short table bits or making the hash shorter + // can actually lead to compression degradation since it will 'steal' more from the + // long match table and match offsets are quite big. + // This greatly depends on the type of input. + betterShortTableBits = 13 // Bits used in the short match table + betterShortTableSize = 1 << betterShortTableBits // Size of the table + betterShortLen = 5 // Bytes used for table hash + + betterLongTableShardCnt = 1 << (betterLongTableBits - dictShardBits) // Number of shards in the table + betterLongTableShardSize = betterLongTableSize / betterLongTableShardCnt // Size of an individual shard + + betterShortTableShardCnt = 1 << (betterShortTableBits - dictShardBits) // Number of shards in the table + betterShortTableShardSize = betterShortTableSize / betterShortTableShardCnt // Size of an individual shard +) + +type prevEntry struct { + offset int32 + prev int32 +} + +// betterFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches. +// The long match table contains the previous entry with the same hash, +// effectively making it a "chain" of length 2. +// When we find a long match we choose between the two values and select the longest. +// When we find a short match, after checking the long, we check if we can find a long at n+1 +// and that it is longer (lazy matching). +type betterFastEncoder struct { + fastBase + table [betterShortTableSize]tableEntry + longTable [betterLongTableSize]prevEntry +} + +type betterFastEncoderDict struct { + betterFastEncoder + dictTable []tableEntry + dictLongTable []prevEntry + shortTableShardDirty [betterShortTableShardCnt]bool + longTableShardDirty [betterLongTableShardCnt]bool + allDirty bool +} + +// Encode improves compression... +func (e *betterFastEncoder) Encode(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 2 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + e.table = [betterShortTableSize]tableEntry{} + e.longTable = [betterLongTableSize]prevEntry{} + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + for i := range e.longTable[:] { + v := e.longTable[i].offset + v2 := e.longTable[i].prev + if v < minOff { + v = 0 + v2 = 0 + } else { + v = v - e.cur + e.maxMatchOff + if v2 < minOff { + v2 = 0 + } else { + v2 = v2 - e.cur + e.maxMatchOff + } + } + e.longTable[i] = prevEntry{ + offset: v, + prev: v2, + } + } + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 1. + const stepSize = 1 + + const kSearchStrength = 9 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + var t int32 + // We allow the encoder to optionally turn off repeat offsets across blocks + canRepeat := len(blk.sequences) > 2 + var matched, index0 int32 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) + nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + const repOff = 1 + repIndex := s - offset1 + repOff + off := s + e.cur + e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset} + e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)} + index0 = s + 1 + + if canRepeat { + if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { + // Consider history as well. + var seq seq + lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) + + seq.matchLen = uint32(lenght - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Index match start+1 (long) -> s - 1 + index0 := s + repOff + s += lenght + repOff + + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, lenght) + + } + break encodeLoop + } + // Index skipped... + for index0 < s-1 { + cv0 := load6432(src, index0) + cv1 := cv0 >> 8 + h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + off := index0 + e.cur + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} + index0 += 2 + } + cv = load6432(src, s) + continue + } + const repOff2 = 1 + + // We deviate from the reference encoder and also check offset 2. + // Still slower and not much better, so disabled. + // repIndex = s - offset2 + repOff2 + if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) { + // Consider history as well. + var seq seq + lenght := 8 + e.matchlen(s+8+repOff2, repIndex+8, src) + + seq.matchLen = uint32(lenght - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff2 + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 2 + seq.offset = 2 + if debugSequences { + println("repeat sequence 2", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + s += lenght + repOff2 + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, lenght) + + } + break encodeLoop + } + + // Index skipped... + for index0 < s-1 { + cv0 := load6432(src, index0) + cv1 := cv0 >> 8 + h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + off := index0 + e.cur + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} + index0 += 2 + } + cv = load6432(src, s) + // Swap offsets + offset1, offset2 = offset2, offset1 + continue + } + } + // Find the offsets of our two matches. + coffsetL := candidateL.offset - e.cur + coffsetLP := candidateL.prev - e.cur + + // Check if we have a long match. + if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { + // Found a long match, at least 8 bytes. + matched = e.matchlen(s+8, coffsetL+8, src) + 8 + t = coffsetL + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + + if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { + // Found a long match, at least 8 bytes. + prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8 + if prevMatch > matched { + matched = prevMatch + t = coffsetLP + } + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + } + break + } + + // Check if we have a long match on prev. + if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { + // Found a long match, at least 8 bytes. + matched = e.matchlen(s+8, coffsetLP+8, src) + 8 + t = coffsetLP + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + break + } + + coffsetS := candidateS.offset - e.cur + + // Check if we have a short match. + if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { + // found a regular match + matched = e.matchlen(s+4, coffsetS+4, src) + 4 + + // See if we can find a long match at s+1 + const checkAt = 1 + cv := load6432(src, s+checkAt) + nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) + candidateL = e.longTable[nextHashL] + coffsetL = candidateL.offset - e.cur + + // We can store it, since we have at least a 4 byte match. + e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset} + if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { + // Found a long match, at least 8 bytes. + matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 + if matchedNext > matched { + t = coffsetL + s += checkAt + matched = matchedNext + if debugMatches { + println("long match (after short)") + } + break + } + } + + // Check prev long... + coffsetL = candidateL.prev - e.cur + if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { + // Found a long match, at least 8 bytes. + matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 + if matchedNext > matched { + t = coffsetL + s += checkAt + matched = matchedNext + if debugMatches { + println("prev long match (after short)") + } + break + } + } + t = coffsetS + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + if debugMatches { + println("short match") + } + break + } + + // No match found, move forward in input. + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + + // Try to find a better match by searching for a long match at the end of the current best match + if s+matched < sLimit { + // Allow some bytes at the beginning to mismatch. + // Sweet spot is around 3 bytes, but depends on input. + // The skipped bytes are tested in Extend backwards, + // and still picked up as part of the match if they do. + const skipBeginning = 3 + + nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) + s2 := s + skipBeginning + cv := load3232(src, s2) + candidateL := e.longTable[nextHashL] + coffsetL := candidateL.offset - e.cur - matched + skipBeginning + if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { + // Found a long match, at least 4 bytes. + matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4 + if matchedNext > matched { + t = coffsetL + s = s2 + matched = matchedNext + if debugMatches { + println("long match at end-of-match") + } + } + } + + // Check prev long... + if true { + coffsetL = candidateL.prev - e.cur - matched + skipBeginning + if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { + // Found a long match, at least 4 bytes. + matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4 + if matchedNext > matched { + t = coffsetL + s = s2 + matched = matchedNext + if debugMatches { + println("prev long match at end-of-match") + } + } + } + } + } + // A match has been found. Update recent offsets. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the n-byte match as long as possible. + l := matched + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + + // Index match start+1 (long) -> s - 1 + off := index0 + e.cur + for index0 < s-1 { + cv0 := load6432(src, index0) + cv1 := cv0 >> 8 + h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} + index0 += 2 + off += 2 + } + + cv = load6432(src, s) + if !canRepeat { + continue + } + + // Check offset 2 + for { + o2 := s - offset2 + if load3232(src, o2) != uint32(cv) { + // Do regular search + break + } + + // Store this, since we have it. + nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) + nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset} + e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)} + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + // Finished + break encodeLoop + } + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// EncodeNoHist will encode a block with no history and no following blocks. +// Most notable difference is that src will not be copied for history and +// we do not need to check for max match length. +func (e *betterFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { + e.ensureHist(len(src)) + e.Encode(blk, src) +} + +// Encode improves compression... +func (e *betterFastEncoderDict) Encode(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 2 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + for i := range e.longTable[:] { + e.longTable[i] = prevEntry{} + } + e.cur = e.maxMatchOff + e.allDirty = true + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + for i := range e.longTable[:] { + v := e.longTable[i].offset + v2 := e.longTable[i].prev + if v < minOff { + v = 0 + v2 = 0 + } else { + v = v - e.cur + e.maxMatchOff + if v2 < minOff { + v2 = 0 + } else { + v2 = v2 - e.cur + e.maxMatchOff + } + } + e.longTable[i] = prevEntry{ + offset: v, + prev: v2, + } + } + e.allDirty = true + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 1. + const stepSize = 1 + + const kSearchStrength = 9 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + var t int32 + // We allow the encoder to optionally turn off repeat offsets across blocks + canRepeat := len(blk.sequences) > 2 + var matched, index0 int32 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) + nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + const repOff = 1 + repIndex := s - offset1 + repOff + off := s + e.cur + e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset} + e.markLongShardDirty(nextHashL) + e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)} + e.markShortShardDirty(nextHashS) + index0 = s + 1 + + if canRepeat { + if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { + // Consider history as well. + var seq seq + lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) + + seq.matchLen = uint32(lenght - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Index match start+1 (long) -> s - 1 + s += lenght + repOff + + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, lenght) + + } + break encodeLoop + } + // Index skipped... + for index0 < s-1 { + cv0 := load6432(src, index0) + cv1 := cv0 >> 8 + h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + off := index0 + e.cur + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.markLongShardDirty(h0) + h1 := hashLen(cv1, betterShortTableBits, betterShortLen) + e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} + e.markShortShardDirty(h1) + index0 += 2 + } + cv = load6432(src, s) + continue + } + const repOff2 = 1 + + // We deviate from the reference encoder and also check offset 2. + // Still slower and not much better, so disabled. + // repIndex = s - offset2 + repOff2 + if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) { + // Consider history as well. + var seq seq + lenght := 8 + e.matchlen(s+8+repOff2, repIndex+8, src) + + seq.matchLen = uint32(lenght - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff2 + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 2 + seq.offset = 2 + if debugSequences { + println("repeat sequence 2", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + s += lenght + repOff2 + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, lenght) + + } + break encodeLoop + } + + // Index skipped... + for index0 < s-1 { + cv0 := load6432(src, index0) + cv1 := cv0 >> 8 + h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + off := index0 + e.cur + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.markLongShardDirty(h0) + h1 := hashLen(cv1, betterShortTableBits, betterShortLen) + e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} + e.markShortShardDirty(h1) + index0 += 2 + } + cv = load6432(src, s) + // Swap offsets + offset1, offset2 = offset2, offset1 + continue + } + } + // Find the offsets of our two matches. + coffsetL := candidateL.offset - e.cur + coffsetLP := candidateL.prev - e.cur + + // Check if we have a long match. + if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { + // Found a long match, at least 8 bytes. + matched = e.matchlen(s+8, coffsetL+8, src) + 8 + t = coffsetL + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + + if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { + // Found a long match, at least 8 bytes. + prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8 + if prevMatch > matched { + matched = prevMatch + t = coffsetLP + } + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + } + break + } + + // Check if we have a long match on prev. + if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { + // Found a long match, at least 8 bytes. + matched = e.matchlen(s+8, coffsetLP+8, src) + 8 + t = coffsetLP + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + break + } + + coffsetS := candidateS.offset - e.cur + + // Check if we have a short match. + if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { + // found a regular match + matched = e.matchlen(s+4, coffsetS+4, src) + 4 + + // See if we can find a long match at s+1 + const checkAt = 1 + cv := load6432(src, s+checkAt) + nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) + candidateL = e.longTable[nextHashL] + coffsetL = candidateL.offset - e.cur + + // We can store it, since we have at least a 4 byte match. + e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset} + e.markLongShardDirty(nextHashL) + if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { + // Found a long match, at least 8 bytes. + matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 + if matchedNext > matched { + t = coffsetL + s += checkAt + matched = matchedNext + if debugMatches { + println("long match (after short)") + } + break + } + } + + // Check prev long... + coffsetL = candidateL.prev - e.cur + if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { + // Found a long match, at least 8 bytes. + matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 + if matchedNext > matched { + t = coffsetL + s += checkAt + matched = matchedNext + if debugMatches { + println("prev long match (after short)") + } + break + } + } + t = coffsetS + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + if debugMatches { + println("short match") + } + break + } + + // No match found, move forward in input. + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + // Try to find a better match by searching for a long match at the end of the current best match + if s+matched < sLimit { + nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) + cv := load3232(src, s) + candidateL := e.longTable[nextHashL] + coffsetL := candidateL.offset - e.cur - matched + if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { + // Found a long match, at least 4 bytes. + matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4 + if matchedNext > matched { + t = coffsetL + matched = matchedNext + if debugMatches { + println("long match at end-of-match") + } + } + } + + // Check prev long... + if true { + coffsetL = candidateL.prev - e.cur - matched + if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { + // Found a long match, at least 4 bytes. + matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4 + if matchedNext > matched { + t = coffsetL + matched = matchedNext + if debugMatches { + println("prev long match at end-of-match") + } + } + } + } + } + // A match has been found. Update recent offsets. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the n-byte match as long as possible. + l := matched + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + + // Index match start+1 (long) -> s - 1 + off := index0 + e.cur + for index0 < s-1 { + cv0 := load6432(src, index0) + cv1 := cv0 >> 8 + h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.markLongShardDirty(h0) + h1 := hashLen(cv1, betterShortTableBits, betterShortLen) + e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} + e.markShortShardDirty(h1) + index0 += 2 + off += 2 + } + + cv = load6432(src, s) + if !canRepeat { + continue + } + + // Check offset 2 + for { + o2 := s - offset2 + if load3232(src, o2) != uint32(cv) { + // Do regular search + break + } + + // Store this, since we have it. + nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) + nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset} + e.markLongShardDirty(nextHashL) + e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)} + e.markShortShardDirty(nextHashS) + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + // Finished + break encodeLoop + } + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *betterFastEncoder) Reset(d *dict, singleBlock bool) { + e.resetBase(d, singleBlock) + if d != nil { + panic("betterFastEncoder: Reset with dict") + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) { + e.resetBase(d, singleBlock) + if d == nil { + return + } + // Init or copy dict table + if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { + if len(e.dictTable) != len(e.table) { + e.dictTable = make([]tableEntry, len(e.table)) + } + end := int32(len(d.content)) - 8 + e.maxMatchOff + for i := e.maxMatchOff; i < end; i += 4 { + const hashLog = betterShortTableBits + + cv := load6432(d.content, i-e.maxMatchOff) + nextHash := hashLen(cv, hashLog, betterShortLen) // 0 -> 4 + nextHash1 := hashLen(cv>>8, hashLog, betterShortLen) // 1 -> 5 + nextHash2 := hashLen(cv>>16, hashLog, betterShortLen) // 2 -> 6 + nextHash3 := hashLen(cv>>24, hashLog, betterShortLen) // 3 -> 7 + e.dictTable[nextHash] = tableEntry{ + val: uint32(cv), + offset: i, + } + e.dictTable[nextHash1] = tableEntry{ + val: uint32(cv >> 8), + offset: i + 1, + } + e.dictTable[nextHash2] = tableEntry{ + val: uint32(cv >> 16), + offset: i + 2, + } + e.dictTable[nextHash3] = tableEntry{ + val: uint32(cv >> 24), + offset: i + 3, + } + } + e.lastDictID = d.id + e.allDirty = true + } + + // Init or copy dict table + if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { + if len(e.dictLongTable) != len(e.longTable) { + e.dictLongTable = make([]prevEntry, len(e.longTable)) + } + if len(d.content) >= 8 { + cv := load6432(d.content, 0) + h := hashLen(cv, betterLongTableBits, betterLongLen) + e.dictLongTable[h] = prevEntry{ + offset: e.maxMatchOff, + prev: e.dictLongTable[h].offset, + } + + end := int32(len(d.content)) - 8 + e.maxMatchOff + off := 8 // First to read + for i := e.maxMatchOff + 1; i < end; i++ { + cv = cv>>8 | (uint64(d.content[off]) << 56) + h := hashLen(cv, betterLongTableBits, betterLongLen) + e.dictLongTable[h] = prevEntry{ + offset: i, + prev: e.dictLongTable[h].offset, + } + off++ + } + } + e.lastDictID = d.id + e.allDirty = true + } + + // Reset table to initial state + { + dirtyShardCnt := 0 + if !e.allDirty { + for i := range e.shortTableShardDirty { + if e.shortTableShardDirty[i] { + dirtyShardCnt++ + } + } + } + const shardCnt = betterShortTableShardCnt + const shardSize = betterShortTableShardSize + if e.allDirty || dirtyShardCnt > shardCnt*4/6 { + copy(e.table[:], e.dictTable) + for i := range e.shortTableShardDirty { + e.shortTableShardDirty[i] = false + } + } else { + for i := range e.shortTableShardDirty { + if !e.shortTableShardDirty[i] { + continue + } + + copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize]) + e.shortTableShardDirty[i] = false + } + } + } + { + dirtyShardCnt := 0 + if !e.allDirty { + for i := range e.shortTableShardDirty { + if e.shortTableShardDirty[i] { + dirtyShardCnt++ + } + } + } + const shardCnt = betterLongTableShardCnt + const shardSize = betterLongTableShardSize + if e.allDirty || dirtyShardCnt > shardCnt*4/6 { + copy(e.longTable[:], e.dictLongTable) + for i := range e.longTableShardDirty { + e.longTableShardDirty[i] = false + } + } else { + for i := range e.longTableShardDirty { + if !e.longTableShardDirty[i] { + continue + } + + copy(e.longTable[i*shardSize:(i+1)*shardSize], e.dictLongTable[i*shardSize:(i+1)*shardSize]) + e.longTableShardDirty[i] = false + } + } + } + e.cur = e.maxMatchOff + e.allDirty = false +} + +func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) { + e.longTableShardDirty[entryNum/betterLongTableShardSize] = true +} + +func (e *betterFastEncoderDict) markShortShardDirty(entryNum uint32) { + e.shortTableShardDirty[entryNum/betterShortTableShardSize] = true +} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go new file mode 100644 index 000000000..a154c18f7 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go @@ -0,0 +1,1123 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import "fmt" + +const ( + dFastLongTableBits = 17 // Bits used in the long match table + dFastLongTableSize = 1 << dFastLongTableBits // Size of the table + dFastLongTableMask = dFastLongTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. + dFastLongLen = 8 // Bytes used for table hash + + dLongTableShardCnt = 1 << (dFastLongTableBits - dictShardBits) // Number of shards in the table + dLongTableShardSize = dFastLongTableSize / tableShardCnt // Size of an individual shard + + dFastShortTableBits = tableBits // Bits used in the short match table + dFastShortTableSize = 1 << dFastShortTableBits // Size of the table + dFastShortTableMask = dFastShortTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. + dFastShortLen = 5 // Bytes used for table hash + +) + +type doubleFastEncoder struct { + fastEncoder + longTable [dFastLongTableSize]tableEntry +} + +type doubleFastEncoderDict struct { + fastEncoderDict + longTable [dFastLongTableSize]tableEntry + dictLongTable []tableEntry + longTableShardDirty [dLongTableShardCnt]bool +} + +// Encode mimmics functionality in zstd_dfast.c +func (e *doubleFastEncoder) Encode(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 2 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + e.table = [dFastShortTableSize]tableEntry{} + e.longTable = [dFastLongTableSize]tableEntry{} + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + for i := range e.longTable[:] { + v := e.longTable[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.longTable[i].offset = v + } + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 1. + const stepSize = 1 + + const kSearchStrength = 8 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + var t int32 + // We allow the encoder to optionally turn off repeat offsets across blocks + canRepeat := len(blk.sequences) > 2 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + const repOff = 1 + repIndex := s - offset1 + repOff + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + + if canRepeat { + if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { + // Consider history as well. + var seq seq + lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) + + seq.matchLen = uint32(lenght - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += lenght + repOff + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, lenght) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + } + // Find the offsets of our two matches. + coffsetL := s - (candidateL.offset - e.cur) + coffsetS := s - (candidateS.offset - e.cur) + + // Check if we have a long match. + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + break + } + + // Check if we have a short match. + if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { + // found a regular match + // See if we can find a long match at s+1 + const checkAt = 1 + cv := load6432(src, s+checkAt) + nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) + candidateL = e.longTable[nextHashL] + coffsetL = s - (candidateL.offset - e.cur) + checkAt + + // We can store it, since we have at least a 4 byte match. + e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + s += checkAt + if debugMatches { + println("long match (after short)") + } + break + } + + t = candidateS.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + if debugMatches { + println("short match") + } + break + } + + // No match found, move forward in input. + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + + // A 4-byte match has been found. Update recent offsets. + // We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + + // Index match start+1 (long) and start+2 (short) + index0 := s - l + 1 + // Index match end-2 (long) and end-1 (short) + index1 := s - 2 + + cv0 := load6432(src, index0) + cv1 := load6432(src, index1) + te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} + te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} + e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 + e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 + cv0 >>= 8 + cv1 >>= 8 + te0.offset++ + te1.offset++ + te0.val = uint32(cv0) + te1.val = uint32(cv1) + e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 + e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 + + cv = load6432(src, s) + + if !canRepeat { + continue + } + + // Check offset 2 + for { + o2 := s - offset2 + if load3232(src, o2) != uint32(cv) { + // Do regular search + break + } + + // Store this, since we have it. + nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + // Finished + break encodeLoop + } + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// EncodeNoHist will encode a block with no history and no following blocks. +// Most notable difference is that src will not be copied for history and +// we do not need to check for max match length. +func (e *doubleFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 2 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + if e.cur >= e.bufferReset { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + for i := range e.longTable[:] { + e.longTable[i] = tableEntry{} + } + e.cur = e.maxMatchOff + } + + s := int32(0) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 1. + const stepSize = 1 + + const kSearchStrength = 8 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + var t int32 + for { + + nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + const repOff = 1 + repIndex := s - offset1 + repOff + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + + if len(blk.sequences) > 2 { + if load3232(src, repIndex) == uint32(cv>>(repOff*8)) { + // Consider history as well. + var seq seq + //length := 4 + e.matchlen(s+4+repOff, repIndex+4, src) + length := 4 + int32(matchLen(src[s+4+repOff:], src[repIndex+4:])) + + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + repOff + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + } + // Find the offsets of our two matches. + coffsetL := s - (candidateL.offset - e.cur) + coffsetS := s - (candidateS.offset - e.cur) + + // Check if we have a long match. + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d). cur: %d", s, t, e.cur)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + break + } + + // Check if we have a short match. + if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { + // found a regular match + // See if we can find a long match at s+1 + const checkAt = 1 + cv := load6432(src, s+checkAt) + nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) + candidateL = e.longTable[nextHashL] + coffsetL = s - (candidateL.offset - e.cur) + checkAt + + // We can store it, since we have at least a 4 byte match. + e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + s += checkAt + if debugMatches { + println("long match (after short)") + } + break + } + + t = candidateS.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + if debugMatches { + println("short match") + } + break + } + + // No match found, move forward in input. + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + + // A 4-byte match has been found. Update recent offsets. + // We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + // Extend the 4-byte match as long as possible. + //l := e.matchlen(s+4, t+4, src) + 4 + l := int32(matchLen(src[s+4:], src[t+4:])) + 4 + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] { + s-- + t-- + l++ + } + + // Write our sequence + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + + // Index match start+1 (long) and start+2 (short) + index0 := s - l + 1 + // Index match end-2 (long) and end-1 (short) + index1 := s - 2 + + cv0 := load6432(src, index0) + cv1 := load6432(src, index1) + te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} + te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} + e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 + e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 + cv0 >>= 8 + cv1 >>= 8 + te0.offset++ + te1.offset++ + te0.val = uint32(cv0) + te1.val = uint32(cv1) + e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 + e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 + + cv = load6432(src, s) + + if len(blk.sequences) <= 2 { + continue + } + + // Check offset 2 + for { + o2 := s - offset2 + if load3232(src, o2) != uint32(cv) { + // Do regular search + break + } + + // Store this, since we have it. + nextHashS := hashLen(cv1>>8, dFastShortTableBits, dFastShortLen) + nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + //l := 4 + e.matchlen(s+4, o2+4, src) + l := 4 + int32(matchLen(src[s+4:], src[o2+4:])) + + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.table[nextHashS] = entry + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + // Finished + break encodeLoop + } + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } + + // We do not store history, so we must offset e.cur to avoid false matches for next user. + if e.cur < e.bufferReset { + e.cur += int32(len(src)) + } +} + +// Encode will encode the content, with a dictionary if initialized for it. +func (e *doubleFastEncoderDict) Encode(blk *blockEnc, src []byte) { + const ( + // Input margin is the number of bytes we read (8) + // and the maximum we will read ahead (2) + inputMargin = 8 + 2 + minNonLiteralBlockSize = 16 + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + for i := range e.longTable[:] { + e.longTable[i] = tableEntry{} + } + e.markAllShardsDirty() + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + for i := range e.longTable[:] { + v := e.longTable[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.longTable[i].offset = v + } + e.markAllShardsDirty() + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 1. + const stepSize = 1 + + const kSearchStrength = 8 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + var t int32 + // We allow the encoder to optionally turn off repeat offsets across blocks + canRepeat := len(blk.sequences) > 2 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + candidateL := e.longTable[nextHashL] + candidateS := e.table[nextHashS] + + const repOff = 1 + repIndex := s - offset1 + repOff + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.markLongShardDirty(nextHashL) + e.table[nextHashS] = entry + e.markShardDirty(nextHashS) + + if canRepeat { + if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { + // Consider history as well. + var seq seq + lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) + + seq.matchLen = uint32(lenght - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + repOff + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += lenght + repOff + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, lenght) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + } + // Find the offsets of our two matches. + coffsetL := s - (candidateL.offset - e.cur) + coffsetS := s - (candidateS.offset - e.cur) + + // Check if we have a long match. + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugMatches { + println("long match") + } + break + } + + // Check if we have a short match. + if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { + // found a regular match + // See if we can find a long match at s+1 + const checkAt = 1 + cv := load6432(src, s+checkAt) + nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) + candidateL = e.longTable[nextHashL] + coffsetL = s - (candidateL.offset - e.cur) + checkAt + + // We can store it, since we have at least a 4 byte match. + e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} + e.markLongShardDirty(nextHashL) + if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { + // Found a long match, likely at least 8 bytes. + // Reference encoder checks all 8 bytes, we only check 4, + // but the likelihood of both the first 4 bytes and the hash matching should be enough. + t = candidateL.offset - e.cur + s += checkAt + if debugMatches { + println("long match (after short)") + } + break + } + + t = candidateS.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + if debugMatches { + println("short match") + } + break + } + + // No match found, move forward in input. + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + + // A 4-byte match has been found. Update recent offsets. + // We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + + // Index match start+1 (long) and start+2 (short) + index0 := s - l + 1 + // Index match end-2 (long) and end-1 (short) + index1 := s - 2 + + cv0 := load6432(src, index0) + cv1 := load6432(src, index1) + te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} + te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} + longHash1 := hashLen(cv0, dFastLongTableBits, dFastLongLen) + longHash2 := hashLen(cv1, dFastLongTableBits, dFastLongLen) + e.longTable[longHash1] = te0 + e.longTable[longHash2] = te1 + e.markLongShardDirty(longHash1) + e.markLongShardDirty(longHash2) + cv0 >>= 8 + cv1 >>= 8 + te0.offset++ + te1.offset++ + te0.val = uint32(cv0) + te1.val = uint32(cv1) + hashVal1 := hashLen(cv0, dFastShortTableBits, dFastShortLen) + hashVal2 := hashLen(cv1, dFastShortTableBits, dFastShortLen) + e.table[hashVal1] = te0 + e.markShardDirty(hashVal1) + e.table[hashVal2] = te1 + e.markShardDirty(hashVal2) + + cv = load6432(src, s) + + if !canRepeat { + continue + } + + // Check offset 2 + for { + o2 := s - offset2 + if load3232(src, o2) != uint32(cv) { + // Do regular search + break + } + + // Store this, since we have it. + nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + entry := tableEntry{offset: s + e.cur, val: uint32(cv)} + e.longTable[nextHashL] = entry + e.markLongShardDirty(nextHashL) + e.table[nextHashS] = entry + e.markShardDirty(nextHashS) + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + // Finished + break encodeLoop + } + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } + // If we encoded more than 64K mark all dirty. + if len(src) > 64<<10 { + e.markAllShardsDirty() + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) { + e.fastEncoder.Reset(d, singleBlock) + if d != nil { + panic("doubleFastEncoder: Reset with dict not supported") + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) { + allDirty := e.allDirty + e.fastEncoderDict.Reset(d, singleBlock) + if d == nil { + return + } + + // Init or copy dict table + if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { + if len(e.dictLongTable) != len(e.longTable) { + e.dictLongTable = make([]tableEntry, len(e.longTable)) + } + if len(d.content) >= 8 { + cv := load6432(d.content, 0) + e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{ + val: uint32(cv), + offset: e.maxMatchOff, + } + end := int32(len(d.content)) - 8 + e.maxMatchOff + for i := e.maxMatchOff + 1; i < end; i++ { + cv = cv>>8 | (uint64(d.content[i-e.maxMatchOff+7]) << 56) + e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{ + val: uint32(cv), + offset: i, + } + } + } + e.lastDictID = d.id + allDirty = true + } + // Reset table to initial state + e.cur = e.maxMatchOff + + dirtyShardCnt := 0 + if !allDirty { + for i := range e.longTableShardDirty { + if e.longTableShardDirty[i] { + dirtyShardCnt++ + } + } + } + + if allDirty || dirtyShardCnt > dLongTableShardCnt/2 { + //copy(e.longTable[:], e.dictLongTable) + e.longTable = *(*[dFastLongTableSize]tableEntry)(e.dictLongTable) + for i := range e.longTableShardDirty { + e.longTableShardDirty[i] = false + } + return + } + for i := range e.longTableShardDirty { + if !e.longTableShardDirty[i] { + continue + } + + // copy(e.longTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize], e.dictLongTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize]) + *(*[dLongTableShardSize]tableEntry)(e.longTable[i*dLongTableShardSize:]) = *(*[dLongTableShardSize]tableEntry)(e.dictLongTable[i*dLongTableShardSize:]) + + e.longTableShardDirty[i] = false + } +} + +func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) { + e.longTableShardDirty[entryNum/dLongTableShardSize] = true +} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_fast.go b/vendor/github.com/klauspost/compress/zstd/enc_fast.go new file mode 100644 index 000000000..f45a3da7d --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/enc_fast.go @@ -0,0 +1,891 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "fmt" +) + +const ( + tableBits = 15 // Bits used in the table + tableSize = 1 << tableBits // Size of the table + tableShardCnt = 1 << (tableBits - dictShardBits) // Number of shards in the table + tableShardSize = tableSize / tableShardCnt // Size of an individual shard + tableFastHashLen = 6 + tableMask = tableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. + maxMatchLength = 131074 +) + +type tableEntry struct { + val uint32 + offset int32 +} + +type fastEncoder struct { + fastBase + table [tableSize]tableEntry +} + +type fastEncoderDict struct { + fastEncoder + dictTable []tableEntry + tableShardDirty [tableShardCnt]bool + allDirty bool +} + +// Encode mimmics functionality in zstd_fast.c +func (e *fastEncoder) Encode(blk *blockEnc, src []byte) { + const ( + inputMargin = 8 + minNonLiteralBlockSize = 1 + 1 + inputMargin + ) + + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 2. + const stepSize = 2 + + // TEMPLATE + const hashLog = tableBits + // seems global, but would be nice to tweak. + const kSearchStrength = 6 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + // t will contain the match offset when we find one. + // When existing the search loop, we have already checked 4 bytes. + var t int32 + + // We will not use repeat offsets across blocks. + // By not using them for the first 3 matches + canRepeat := len(blk.sequences) > 2 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHash := hashLen(cv, hashLog, tableFastHashLen) + nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) + candidate := e.table[nextHash] + candidate2 := e.table[nextHash2] + repIndex := s - offset1 + 2 + + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} + + if canRepeat && repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>16) { + // Consider history as well. + var seq seq + length := 4 + e.matchlen(s+6, repIndex+4, src) + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + 2 + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + sMin := s - e.maxMatchOff + if sMin < 0 { + sMin = 0 + } + for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + 2 + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + coffset0 := s - (candidate.offset - e.cur) + coffset1 := s - (candidate2.offset - e.cur) + 1 + if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { + // found a regular match + t = candidate.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + break + } + + if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { + // found a regular match + t = candidate2.offset - e.cur + s++ + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + break + } + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + // A 4-byte match has been found. We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence. + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + // Don't use repeat offsets + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + + // Check offset 2 + if o2 := s - offset2; canRepeat && load3232(src, o2) == uint32(cv) { + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + // Store this, since we have it. + nextHash := hashLen(cv, hashLog, tableFastHashLen) + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + break encodeLoop + } + // Prepare next loop. + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// EncodeNoHist will encode a block with no history and no following blocks. +// Most notable difference is that src will not be copied for history and +// we do not need to check for max match length. +func (e *fastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { + const ( + inputMargin = 8 + minNonLiteralBlockSize = 1 + 1 + inputMargin + ) + if debugEncoder { + if len(src) > maxCompressedBlockSize { + panic("src too big") + } + } + + // Protect against e.cur wraparound. + if e.cur >= e.bufferReset { + for i := range e.table[:] { + e.table[i] = tableEntry{} + } + e.cur = e.maxMatchOff + } + + s := int32(0) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 2. + const stepSize = 2 + + // TEMPLATE + const hashLog = tableBits + // seems global, but would be nice to tweak. + const kSearchStrength = 6 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + // t will contain the match offset when we find one. + // When existing the search loop, we have already checked 4 bytes. + var t int32 + + // We will not use repeat offsets across blocks. + // By not using them for the first 3 matches + + for { + nextHash := hashLen(cv, hashLog, tableFastHashLen) + nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) + candidate := e.table[nextHash] + candidate2 := e.table[nextHash2] + repIndex := s - offset1 + 2 + + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} + + if len(blk.sequences) > 2 && load3232(src, repIndex) == uint32(cv>>16) { + // Consider history as well. + var seq seq + length := 4 + e.matchlen(s+6, repIndex+4, src) + + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + 2 + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + sMin := s - e.maxMatchOff + if sMin < 0 { + sMin = 0 + } + for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + 2 + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + coffset0 := s - (candidate.offset - e.cur) + coffset1 := s - (candidate2.offset - e.cur) + 1 + if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { + // found a regular match + t = candidate.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic(fmt.Sprintf("t (%d) < 0, candidate.offset: %d, e.cur: %d, coffset0: %d, e.maxMatchOff: %d", t, candidate.offset, e.cur, coffset0, e.maxMatchOff)) + } + break + } + + if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { + // found a regular match + t = candidate2.offset - e.cur + s++ + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + break + } + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + // A 4-byte match has been found. We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && t < 0 { + panic(fmt.Sprintf("t (%d) < 0 ", t)) + } + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] { + s-- + t-- + l++ + } + + // Write our sequence. + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + // Don't use repeat offsets + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + + // Check offset 2 + if o2 := s - offset2; len(blk.sequences) > 2 && load3232(src, o2) == uint32(cv) { + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + // Store this, since we have it. + nextHash := hashLen(cv, hashLog, tableFastHashLen) + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + break encodeLoop + } + // Prepare next loop. + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } + // We do not store history, so we must offset e.cur to avoid false matches for next user. + if e.cur < e.bufferReset { + e.cur += int32(len(src)) + } +} + +// Encode will encode the content, with a dictionary if initialized for it. +func (e *fastEncoderDict) Encode(blk *blockEnc, src []byte) { + const ( + inputMargin = 8 + minNonLiteralBlockSize = 1 + 1 + inputMargin + ) + if e.allDirty || len(src) > 32<<10 { + e.fastEncoder.Encode(blk, src) + e.allDirty = true + return + } + // Protect against e.cur wraparound. + for e.cur >= e.bufferReset-int32(len(e.hist)) { + if len(e.hist) == 0 { + e.table = [tableSize]tableEntry{} + e.cur = e.maxMatchOff + break + } + // Shift down everything in the table that isn't already too far away. + minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff + for i := range e.table[:] { + v := e.table[i].offset + if v < minOff { + v = 0 + } else { + v = v - e.cur + e.maxMatchOff + } + e.table[i].offset = v + } + e.cur = e.maxMatchOff + break + } + + s := e.addBlock(src) + blk.size = len(src) + if len(src) < minNonLiteralBlockSize { + blk.extraLits = len(src) + blk.literals = blk.literals[:len(src)] + copy(blk.literals, src) + return + } + + // Override src + src = e.hist + sLimit := int32(len(src)) - inputMargin + // stepSize is the number of bytes to skip on every main loop iteration. + // It should be >= 2. + const stepSize = 2 + + // TEMPLATE + const hashLog = tableBits + // seems global, but would be nice to tweak. + const kSearchStrength = 7 + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := s + cv := load6432(src, s) + + // Relative offsets + offset1 := int32(blk.recentOffsets[0]) + offset2 := int32(blk.recentOffsets[1]) + + addLiterals := func(s *seq, until int32) { + if until == nextEmit { + return + } + blk.literals = append(blk.literals, src[nextEmit:until]...) + s.litLen = uint32(until - nextEmit) + } + if debugEncoder { + println("recent offsets:", blk.recentOffsets) + } + +encodeLoop: + for { + // t will contain the match offset when we find one. + // When existing the search loop, we have already checked 4 bytes. + var t int32 + + // We will not use repeat offsets across blocks. + // By not using them for the first 3 matches + canRepeat := len(blk.sequences) > 2 + + for { + if debugAsserts && canRepeat && offset1 == 0 { + panic("offset0 was 0") + } + + nextHash := hashLen(cv, hashLog, tableFastHashLen) + nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) + candidate := e.table[nextHash] + candidate2 := e.table[nextHash2] + repIndex := s - offset1 + 2 + + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + e.markShardDirty(nextHash) + e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} + e.markShardDirty(nextHash2) + + if canRepeat && repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>16) { + // Consider history as well. + var seq seq + length := 4 + e.matchlen(s+6, repIndex+4, src) + + seq.matchLen = uint32(length - zstdMinMatch) + + // We might be able to match backwards. + // Extend as long as we can. + start := s + 2 + // We end the search early, so we don't risk 0 literals + // and have to do special offset treatment. + startLimit := nextEmit + 1 + + sMin := s - e.maxMatchOff + if sMin < 0 { + sMin = 0 + } + for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { + repIndex-- + start-- + seq.matchLen++ + } + addLiterals(&seq, start) + + // rep 0 + seq.offset = 1 + if debugSequences { + println("repeat sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + s += length + 2 + nextEmit = s + if s >= sLimit { + if debugEncoder { + println("repeat ended", s, length) + + } + break encodeLoop + } + cv = load6432(src, s) + continue + } + coffset0 := s - (candidate.offset - e.cur) + coffset1 := s - (candidate2.offset - e.cur) + 1 + if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { + // found a regular match + t = candidate.offset - e.cur + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + break + } + + if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { + // found a regular match + t = candidate2.offset - e.cur + s++ + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + if debugAsserts && s-t > e.maxMatchOff { + panic("s - t >e.maxMatchOff") + } + if debugAsserts && t < 0 { + panic("t<0") + } + break + } + s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + } + // A 4-byte match has been found. We'll later see if more than 4 bytes. + offset2 = offset1 + offset1 = s - t + + if debugAsserts && s <= t { + panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) + } + + if debugAsserts && canRepeat && int(offset1) > len(src) { + panic("invalid offset") + } + + // Extend the 4-byte match as long as possible. + l := e.matchlen(s+4, t+4, src) + 4 + + // Extend backwards + tMin := s - e.maxMatchOff + if tMin < 0 { + tMin = 0 + } + for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { + s-- + t-- + l++ + } + + // Write our sequence. + var seq seq + seq.litLen = uint32(s - nextEmit) + seq.matchLen = uint32(l - zstdMinMatch) + if seq.litLen > 0 { + blk.literals = append(blk.literals, src[nextEmit:s]...) + } + // Don't use repeat offsets + seq.offset = uint32(s-t) + 3 + s += l + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + nextEmit = s + if s >= sLimit { + break encodeLoop + } + cv = load6432(src, s) + + // Check offset 2 + if o2 := s - offset2; canRepeat && load3232(src, o2) == uint32(cv) { + // We have at least 4 byte match. + // No need to check backwards. We come straight from a match + l := 4 + e.matchlen(s+4, o2+4, src) + + // Store this, since we have it. + nextHash := hashLen(cv, hashLog, tableFastHashLen) + e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} + e.markShardDirty(nextHash) + seq.matchLen = uint32(l) - zstdMinMatch + seq.litLen = 0 + // Since litlen is always 0, this is offset 1. + seq.offset = 1 + s += l + nextEmit = s + if debugSequences { + println("sequence", seq, "next s:", s) + } + blk.sequences = append(blk.sequences, seq) + + // Swap offset 1 and 2. + offset1, offset2 = offset2, offset1 + if s >= sLimit { + break encodeLoop + } + // Prepare next loop. + cv = load6432(src, s) + } + } + + if int(nextEmit) < len(src) { + blk.literals = append(blk.literals, src[nextEmit:]...) + blk.extraLits = len(src) - int(nextEmit) + } + blk.recentOffsets[0] = uint32(offset1) + blk.recentOffsets[1] = uint32(offset2) + if debugEncoder { + println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *fastEncoder) Reset(d *dict, singleBlock bool) { + e.resetBase(d, singleBlock) + if d != nil { + panic("fastEncoder: Reset with dict") + } +} + +// ResetDict will reset and set a dictionary if not nil +func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) { + e.resetBase(d, singleBlock) + if d == nil { + return + } + + // Init or copy dict table + if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { + if len(e.dictTable) != len(e.table) { + e.dictTable = make([]tableEntry, len(e.table)) + } + if true { + end := e.maxMatchOff + int32(len(d.content)) - 8 + for i := e.maxMatchOff; i < end; i += 2 { + const hashLog = tableBits + + cv := load6432(d.content, i-e.maxMatchOff) + nextHash := hashLen(cv, hashLog, tableFastHashLen) // 0 -> 6 + nextHash1 := hashLen(cv>>8, hashLog, tableFastHashLen) // 1 -> 7 + e.dictTable[nextHash] = tableEntry{ + val: uint32(cv), + offset: i, + } + e.dictTable[nextHash1] = tableEntry{ + val: uint32(cv >> 8), + offset: i + 1, + } + } + } + e.lastDictID = d.id + e.allDirty = true + } + + e.cur = e.maxMatchOff + dirtyShardCnt := 0 + if !e.allDirty { + for i := range e.tableShardDirty { + if e.tableShardDirty[i] { + dirtyShardCnt++ + } + } + } + + const shardCnt = tableShardCnt + const shardSize = tableShardSize + if e.allDirty || dirtyShardCnt > shardCnt*4/6 { + //copy(e.table[:], e.dictTable) + e.table = *(*[tableSize]tableEntry)(e.dictTable) + for i := range e.tableShardDirty { + e.tableShardDirty[i] = false + } + e.allDirty = false + return + } + for i := range e.tableShardDirty { + if !e.tableShardDirty[i] { + continue + } + + //copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize]) + *(*[shardSize]tableEntry)(e.table[i*shardSize:]) = *(*[shardSize]tableEntry)(e.dictTable[i*shardSize:]) + e.tableShardDirty[i] = false + } + e.allDirty = false +} + +func (e *fastEncoderDict) markAllShardsDirty() { + e.allDirty = true +} + +func (e *fastEncoderDict) markShardDirty(entryNum uint32) { + e.tableShardDirty[entryNum/tableShardSize] = true +} diff --git a/vendor/github.com/klauspost/compress/zstd/encoder.go b/vendor/github.com/klauspost/compress/zstd/encoder.go new file mode 100644 index 000000000..72af7ef0f --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/encoder.go @@ -0,0 +1,619 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "crypto/rand" + "fmt" + "io" + "math" + rdebug "runtime/debug" + "sync" + + "github.com/klauspost/compress/zstd/internal/xxhash" +) + +// Encoder provides encoding to Zstandard. +// An Encoder can be used for either compressing a stream via the +// io.WriteCloser interface supported by the Encoder or as multiple independent +// tasks via the EncodeAll function. +// Smaller encodes are encouraged to use the EncodeAll function. +// Use NewWriter to create a new instance. +type Encoder struct { + o encoderOptions + encoders chan encoder + state encoderState + init sync.Once +} + +type encoder interface { + Encode(blk *blockEnc, src []byte) + EncodeNoHist(blk *blockEnc, src []byte) + Block() *blockEnc + CRC() *xxhash.Digest + AppendCRC([]byte) []byte + WindowSize(size int64) int32 + UseBlock(*blockEnc) + Reset(d *dict, singleBlock bool) +} + +type encoderState struct { + w io.Writer + filling []byte + current []byte + previous []byte + encoder encoder + writing *blockEnc + err error + writeErr error + nWritten int64 + nInput int64 + frameContentSize int64 + headerWritten bool + eofWritten bool + fullFrameWritten bool + + // This waitgroup indicates an encode is running. + wg sync.WaitGroup + // This waitgroup indicates we have a block encoding/writing. + wWg sync.WaitGroup +} + +// NewWriter will create a new Zstandard encoder. +// If the encoder will be used for encoding blocks a nil writer can be used. +func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) { + initPredefined() + var e Encoder + e.o.setDefault() + for _, o := range opts { + err := o(&e.o) + if err != nil { + return nil, err + } + } + if w != nil { + e.Reset(w) + } + return &e, nil +} + +func (e *Encoder) initialize() { + if e.o.concurrent == 0 { + e.o.setDefault() + } + e.encoders = make(chan encoder, e.o.concurrent) + for i := 0; i < e.o.concurrent; i++ { + enc := e.o.encoder() + e.encoders <- enc + } +} + +// Reset will re-initialize the writer and new writes will encode to the supplied writer +// as a new, independent stream. +func (e *Encoder) Reset(w io.Writer) { + s := &e.state + s.wg.Wait() + s.wWg.Wait() + if cap(s.filling) == 0 { + s.filling = make([]byte, 0, e.o.blockSize) + } + if e.o.concurrent > 1 { + if cap(s.current) == 0 { + s.current = make([]byte, 0, e.o.blockSize) + } + if cap(s.previous) == 0 { + s.previous = make([]byte, 0, e.o.blockSize) + } + s.current = s.current[:0] + s.previous = s.previous[:0] + if s.writing == nil { + s.writing = &blockEnc{lowMem: e.o.lowMem} + s.writing.init() + } + s.writing.initNewEncode() + } + if s.encoder == nil { + s.encoder = e.o.encoder() + } + s.filling = s.filling[:0] + s.encoder.Reset(e.o.dict, false) + s.headerWritten = false + s.eofWritten = false + s.fullFrameWritten = false + s.w = w + s.err = nil + s.nWritten = 0 + s.nInput = 0 + s.writeErr = nil + s.frameContentSize = 0 +} + +// ResetContentSize will reset and set a content size for the next stream. +// If the bytes written does not match the size given an error will be returned +// when calling Close(). +// This is removed when Reset is called. +// Sizes <= 0 results in no content size set. +func (e *Encoder) ResetContentSize(w io.Writer, size int64) { + e.Reset(w) + if size >= 0 { + e.state.frameContentSize = size + } +} + +// Write data to the encoder. +// Input data will be buffered and as the buffer fills up +// content will be compressed and written to the output. +// When done writing, use Close to flush the remaining output +// and write CRC if requested. +func (e *Encoder) Write(p []byte) (n int, err error) { + s := &e.state + for len(p) > 0 { + if len(p)+len(s.filling) < e.o.blockSize { + if e.o.crc { + _, _ = s.encoder.CRC().Write(p) + } + s.filling = append(s.filling, p...) + return n + len(p), nil + } + add := p + if len(p)+len(s.filling) > e.o.blockSize { + add = add[:e.o.blockSize-len(s.filling)] + } + if e.o.crc { + _, _ = s.encoder.CRC().Write(add) + } + s.filling = append(s.filling, add...) + p = p[len(add):] + n += len(add) + if len(s.filling) < e.o.blockSize { + return n, nil + } + err := e.nextBlock(false) + if err != nil { + return n, err + } + if debugAsserts && len(s.filling) > 0 { + panic(len(s.filling)) + } + } + return n, nil +} + +// nextBlock will synchronize and start compressing input in e.state.filling. +// If an error has occurred during encoding it will be returned. +func (e *Encoder) nextBlock(final bool) error { + s := &e.state + // Wait for current block. + s.wg.Wait() + if s.err != nil { + return s.err + } + if len(s.filling) > e.o.blockSize { + return fmt.Errorf("block > maxStoreBlockSize") + } + if !s.headerWritten { + // If we have a single block encode, do a sync compression. + if final && len(s.filling) == 0 && !e.o.fullZero { + s.headerWritten = true + s.fullFrameWritten = true + s.eofWritten = true + return nil + } + if final && len(s.filling) > 0 { + s.current = e.EncodeAll(s.filling, s.current[:0]) + var n2 int + n2, s.err = s.w.Write(s.current) + if s.err != nil { + return s.err + } + s.nWritten += int64(n2) + s.nInput += int64(len(s.filling)) + s.current = s.current[:0] + s.filling = s.filling[:0] + s.headerWritten = true + s.fullFrameWritten = true + s.eofWritten = true + return nil + } + + var tmp [maxHeaderSize]byte + fh := frameHeader{ + ContentSize: uint64(s.frameContentSize), + WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)), + SingleSegment: false, + Checksum: e.o.crc, + DictID: e.o.dict.ID(), + } + + dst := fh.appendTo(tmp[:0]) + s.headerWritten = true + s.wWg.Wait() + var n2 int + n2, s.err = s.w.Write(dst) + if s.err != nil { + return s.err + } + s.nWritten += int64(n2) + } + if s.eofWritten { + // Ensure we only write it once. + final = false + } + + if len(s.filling) == 0 { + // Final block, but no data. + if final { + enc := s.encoder + blk := enc.Block() + blk.reset(nil) + blk.last = true + blk.encodeRaw(nil) + s.wWg.Wait() + _, s.err = s.w.Write(blk.output) + s.nWritten += int64(len(blk.output)) + s.eofWritten = true + } + return s.err + } + + // SYNC: + if e.o.concurrent == 1 { + src := s.filling + s.nInput += int64(len(s.filling)) + if debugEncoder { + println("Adding sync block,", len(src), "bytes, final:", final) + } + enc := s.encoder + blk := enc.Block() + blk.reset(nil) + enc.Encode(blk, src) + blk.last = final + if final { + s.eofWritten = true + } + + s.err = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) + if s.err != nil { + return s.err + } + _, s.err = s.w.Write(blk.output) + s.nWritten += int64(len(blk.output)) + s.filling = s.filling[:0] + return s.err + } + + // Move blocks forward. + s.filling, s.current, s.previous = s.previous[:0], s.filling, s.current + s.nInput += int64(len(s.current)) + s.wg.Add(1) + go func(src []byte) { + if debugEncoder { + println("Adding block,", len(src), "bytes, final:", final) + } + defer func() { + if r := recover(); r != nil { + s.err = fmt.Errorf("panic while encoding: %v", r) + rdebug.PrintStack() + } + s.wg.Done() + }() + enc := s.encoder + blk := enc.Block() + enc.Encode(blk, src) + blk.last = final + if final { + s.eofWritten = true + } + // Wait for pending writes. + s.wWg.Wait() + if s.writeErr != nil { + s.err = s.writeErr + return + } + // Transfer encoders from previous write block. + blk.swapEncoders(s.writing) + // Transfer recent offsets to next. + enc.UseBlock(s.writing) + s.writing = blk + s.wWg.Add(1) + go func() { + defer func() { + if r := recover(); r != nil { + s.writeErr = fmt.Errorf("panic while encoding/writing: %v", r) + rdebug.PrintStack() + } + s.wWg.Done() + }() + s.writeErr = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) + if s.writeErr != nil { + return + } + _, s.writeErr = s.w.Write(blk.output) + s.nWritten += int64(len(blk.output)) + }() + }(s.current) + return nil +} + +// ReadFrom reads data from r until EOF or error. +// The return value n is the number of bytes read. +// Any error except io.EOF encountered during the read is also returned. +// +// The Copy function uses ReaderFrom if available. +func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) { + if debugEncoder { + println("Using ReadFrom") + } + + // Flush any current writes. + if len(e.state.filling) > 0 { + if err := e.nextBlock(false); err != nil { + return 0, err + } + } + e.state.filling = e.state.filling[:e.o.blockSize] + src := e.state.filling + for { + n2, err := r.Read(src) + if e.o.crc { + _, _ = e.state.encoder.CRC().Write(src[:n2]) + } + // src is now the unfilled part... + src = src[n2:] + n += int64(n2) + switch err { + case io.EOF: + e.state.filling = e.state.filling[:len(e.state.filling)-len(src)] + if debugEncoder { + println("ReadFrom: got EOF final block:", len(e.state.filling)) + } + return n, nil + case nil: + default: + if debugEncoder { + println("ReadFrom: got error:", err) + } + e.state.err = err + return n, err + } + if len(src) > 0 { + if debugEncoder { + println("ReadFrom: got space left in source:", len(src)) + } + continue + } + err = e.nextBlock(false) + if err != nil { + return n, err + } + e.state.filling = e.state.filling[:e.o.blockSize] + src = e.state.filling + } +} + +// Flush will send the currently written data to output +// and block until everything has been written. +// This should only be used on rare occasions where pushing the currently queued data is critical. +func (e *Encoder) Flush() error { + s := &e.state + if len(s.filling) > 0 { + err := e.nextBlock(false) + if err != nil { + return err + } + } + s.wg.Wait() + s.wWg.Wait() + if s.err != nil { + return s.err + } + return s.writeErr +} + +// Close will flush the final output and close the stream. +// The function will block until everything has been written. +// The Encoder can still be re-used after calling this. +func (e *Encoder) Close() error { + s := &e.state + if s.encoder == nil { + return nil + } + err := e.nextBlock(true) + if err != nil { + return err + } + if s.frameContentSize > 0 { + if s.nInput != s.frameContentSize { + return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput) + } + } + if e.state.fullFrameWritten { + return s.err + } + s.wg.Wait() + s.wWg.Wait() + + if s.err != nil { + return s.err + } + if s.writeErr != nil { + return s.writeErr + } + + // Write CRC + if e.o.crc && s.err == nil { + // heap alloc. + var tmp [4]byte + _, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0])) + s.nWritten += 4 + } + + // Add padding with content from crypto/rand.Reader + if s.err == nil && e.o.pad > 0 { + add := calcSkippableFrame(s.nWritten, int64(e.o.pad)) + frame, err := skippableFrame(s.filling[:0], add, rand.Reader) + if err != nil { + return err + } + _, s.err = s.w.Write(frame) + } + return s.err +} + +// EncodeAll will encode all input in src and append it to dst. +// This function can be called concurrently, but each call will only run on a single goroutine. +// If empty input is given, nothing is returned, unless WithZeroFrames is specified. +// Encoded blocks can be concatenated and the result will be the combined input stream. +// Data compressed with EncodeAll can be decoded with the Decoder, +// using either a stream or DecodeAll. +func (e *Encoder) EncodeAll(src, dst []byte) []byte { + if len(src) == 0 { + if e.o.fullZero { + // Add frame header. + fh := frameHeader{ + ContentSize: 0, + WindowSize: MinWindowSize, + SingleSegment: true, + // Adding a checksum would be a waste of space. + Checksum: false, + DictID: 0, + } + dst = fh.appendTo(dst) + + // Write raw block as last one only. + var blk blockHeader + blk.setSize(0) + blk.setType(blockTypeRaw) + blk.setLast(true) + dst = blk.appendTo(dst) + } + return dst + } + e.init.Do(e.initialize) + enc := <-e.encoders + defer func() { + // Release encoder reference to last block. + // If a non-single block is needed the encoder will reset again. + e.encoders <- enc + }() + // Use single segments when above minimum window and below window size. + single := len(src) <= e.o.windowSize && len(src) > MinWindowSize + if e.o.single != nil { + single = *e.o.single + } + fh := frameHeader{ + ContentSize: uint64(len(src)), + WindowSize: uint32(enc.WindowSize(int64(len(src)))), + SingleSegment: single, + Checksum: e.o.crc, + DictID: e.o.dict.ID(), + } + + // If less than 1MB, allocate a buffer up front. + if len(dst) == 0 && cap(dst) == 0 && len(src) < 1<<20 && !e.o.lowMem { + dst = make([]byte, 0, len(src)) + } + dst = fh.appendTo(dst) + + // If we can do everything in one block, prefer that. + if len(src) <= e.o.blockSize { + enc.Reset(e.o.dict, true) + // Slightly faster with no history and everything in one block. + if e.o.crc { + _, _ = enc.CRC().Write(src) + } + blk := enc.Block() + blk.last = true + if e.o.dict == nil { + enc.EncodeNoHist(blk, src) + } else { + enc.Encode(blk, src) + } + + // If we got the exact same number of literals as input, + // assume the literals cannot be compressed. + oldout := blk.output + // Output directly to dst + blk.output = dst + + err := blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) + if err != nil { + panic(err) + } + dst = blk.output + blk.output = oldout + } else { + enc.Reset(e.o.dict, false) + blk := enc.Block() + for len(src) > 0 { + todo := src + if len(todo) > e.o.blockSize { + todo = todo[:e.o.blockSize] + } + src = src[len(todo):] + if e.o.crc { + _, _ = enc.CRC().Write(todo) + } + blk.pushOffsets() + enc.Encode(blk, todo) + if len(src) == 0 { + blk.last = true + } + err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy) + if err != nil { + panic(err) + } + dst = append(dst, blk.output...) + blk.reset(nil) + } + } + if e.o.crc { + dst = enc.AppendCRC(dst) + } + // Add padding with content from crypto/rand.Reader + if e.o.pad > 0 { + add := calcSkippableFrame(int64(len(dst)), int64(e.o.pad)) + var err error + dst, err = skippableFrame(dst, add, rand.Reader) + if err != nil { + panic(err) + } + } + return dst +} + +// MaxEncodedSize returns the expected maximum +// size of an encoded block or stream. +func (e *Encoder) MaxEncodedSize(size int) int { + frameHeader := 4 + 2 // magic + frame header & window descriptor + if e.o.dict != nil { + frameHeader += 4 + } + // Frame content size: + if size < 256 { + frameHeader++ + } else if size < 65536+256 { + frameHeader += 2 + } else if size < math.MaxInt32 { + frameHeader += 4 + } else { + frameHeader += 8 + } + // Final crc + if e.o.crc { + frameHeader += 4 + } + + // Max overhead is 3 bytes/block. + // There cannot be 0 blocks. + blocks := (size + e.o.blockSize) / e.o.blockSize + + // Combine, add padding. + maxSz := frameHeader + 3*blocks + size + if e.o.pad > 1 { + maxSz += calcSkippableFrame(int64(maxSz), int64(e.o.pad)) + } + return maxSz +} diff --git a/vendor/github.com/klauspost/compress/zstd/encoder_options.go b/vendor/github.com/klauspost/compress/zstd/encoder_options.go new file mode 100644 index 000000000..faaf81921 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/encoder_options.go @@ -0,0 +1,339 @@ +package zstd + +import ( + "errors" + "fmt" + "math" + "math/bits" + "runtime" + "strings" +) + +// EOption is an option for creating a encoder. +type EOption func(*encoderOptions) error + +// options retains accumulated state of multiple options. +type encoderOptions struct { + concurrent int + level EncoderLevel + single *bool + pad int + blockSize int + windowSize int + crc bool + fullZero bool + noEntropy bool + allLitEntropy bool + customWindow bool + customALEntropy bool + customBlockSize bool + lowMem bool + dict *dict +} + +func (o *encoderOptions) setDefault() { + *o = encoderOptions{ + concurrent: runtime.GOMAXPROCS(0), + crc: true, + single: nil, + blockSize: maxCompressedBlockSize, + windowSize: 8 << 20, + level: SpeedDefault, + allLitEntropy: false, + lowMem: false, + } +} + +// encoder returns an encoder with the selected options. +func (o encoderOptions) encoder() encoder { + switch o.level { + case SpeedFastest: + if o.dict != nil { + return &fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} + } + return &fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} + + case SpeedDefault: + if o.dict != nil { + return &doubleFastEncoderDict{fastEncoderDict: fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}}} + } + return &doubleFastEncoder{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} + case SpeedBetterCompression: + if o.dict != nil { + return &betterFastEncoderDict{betterFastEncoder: betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} + } + return &betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} + case SpeedBestCompression: + return &bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} + } + panic("unknown compression level") +} + +// WithEncoderCRC will add CRC value to output. +// Output will be 4 bytes larger. +func WithEncoderCRC(b bool) EOption { + return func(o *encoderOptions) error { o.crc = b; return nil } +} + +// WithEncoderConcurrency will set the concurrency, +// meaning the maximum number of encoders to run concurrently. +// The value supplied must be at least 1. +// For streams, setting a value of 1 will disable async compression. +// By default this will be set to GOMAXPROCS. +func WithEncoderConcurrency(n int) EOption { + return func(o *encoderOptions) error { + if n <= 0 { + return fmt.Errorf("concurrency must be at least 1") + } + o.concurrent = n + return nil + } +} + +// WithWindowSize will set the maximum allowed back-reference distance. +// The value must be a power of two between MinWindowSize and MaxWindowSize. +// A larger value will enable better compression but allocate more memory and, +// for above-default values, take considerably longer. +// The default value is determined by the compression level. +func WithWindowSize(n int) EOption { + return func(o *encoderOptions) error { + switch { + case n < MinWindowSize: + return fmt.Errorf("window size must be at least %d", MinWindowSize) + case n > MaxWindowSize: + return fmt.Errorf("window size must be at most %d", MaxWindowSize) + case (n & (n - 1)) != 0: + return errors.New("window size must be a power of 2") + } + + o.windowSize = n + o.customWindow = true + if o.blockSize > o.windowSize { + o.blockSize = o.windowSize + o.customBlockSize = true + } + return nil + } +} + +// WithEncoderPadding will add padding to all output so the size will be a multiple of n. +// This can be used to obfuscate the exact output size or make blocks of a certain size. +// The contents will be a skippable frame, so it will be invisible by the decoder. +// n must be > 0 and <= 1GB, 1<<30 bytes. +// The padded area will be filled with data from crypto/rand.Reader. +// If `EncodeAll` is used with data already in the destination, the total size will be multiple of this. +func WithEncoderPadding(n int) EOption { + return func(o *encoderOptions) error { + if n <= 0 { + return fmt.Errorf("padding must be at least 1") + } + // No need to waste our time. + if n == 1 { + n = 0 + } + if n > 1<<30 { + return fmt.Errorf("padding must less than 1GB (1<<30 bytes) ") + } + o.pad = n + return nil + } +} + +// EncoderLevel predefines encoder compression levels. +// Only use the constants made available, since the actual mapping +// of these values are very likely to change and your compression could change +// unpredictably when upgrading the library. +type EncoderLevel int + +const ( + speedNotSet EncoderLevel = iota + + // SpeedFastest will choose the fastest reasonable compression. + // This is roughly equivalent to the fastest Zstandard mode. + SpeedFastest + + // SpeedDefault is the default "pretty fast" compression option. + // This is roughly equivalent to the default Zstandard mode (level 3). + SpeedDefault + + // SpeedBetterCompression will yield better compression than the default. + // Currently it is about zstd level 7-8 with ~ 2x-3x the default CPU usage. + // By using this, notice that CPU usage may go up in the future. + SpeedBetterCompression + + // SpeedBestCompression will choose the best available compression option. + // This will offer the best compression no matter the CPU cost. + SpeedBestCompression + + // speedLast should be kept as the last actual compression option. + // The is not for external usage, but is used to keep track of the valid options. + speedLast +) + +// EncoderLevelFromString will convert a string representation of an encoding level back +// to a compression level. The compare is not case sensitive. +// If the string wasn't recognized, (false, SpeedDefault) will be returned. +func EncoderLevelFromString(s string) (bool, EncoderLevel) { + for l := speedNotSet + 1; l < speedLast; l++ { + if strings.EqualFold(s, l.String()) { + return true, l + } + } + return false, SpeedDefault +} + +// EncoderLevelFromZstd will return an encoder level that closest matches the compression +// ratio of a specific zstd compression level. +// Many input values will provide the same compression level. +func EncoderLevelFromZstd(level int) EncoderLevel { + switch { + case level < 3: + return SpeedFastest + case level >= 3 && level < 6: + return SpeedDefault + case level >= 6 && level < 10: + return SpeedBetterCompression + default: + return SpeedBestCompression + } +} + +// String provides a string representation of the compression level. +func (e EncoderLevel) String() string { + switch e { + case SpeedFastest: + return "fastest" + case SpeedDefault: + return "default" + case SpeedBetterCompression: + return "better" + case SpeedBestCompression: + return "best" + default: + return "invalid" + } +} + +// WithEncoderLevel specifies a predefined compression level. +func WithEncoderLevel(l EncoderLevel) EOption { + return func(o *encoderOptions) error { + switch { + case l <= speedNotSet || l >= speedLast: + return fmt.Errorf("unknown encoder level") + } + o.level = l + if !o.customWindow { + switch o.level { + case SpeedFastest: + o.windowSize = 4 << 20 + if !o.customBlockSize { + o.blockSize = 1 << 16 + } + case SpeedDefault: + o.windowSize = 8 << 20 + case SpeedBetterCompression: + o.windowSize = 16 << 20 + case SpeedBestCompression: + o.windowSize = 32 << 20 + } + } + if !o.customALEntropy { + o.allLitEntropy = l > SpeedDefault + } + + return nil + } +} + +// WithZeroFrames will encode 0 length input as full frames. +// This can be needed for compatibility with zstandard usage, +// but is not needed for this package. +func WithZeroFrames(b bool) EOption { + return func(o *encoderOptions) error { + o.fullZero = b + return nil + } +} + +// WithAllLitEntropyCompression will apply entropy compression if no matches are found. +// Disabling this will skip incompressible data faster, but in cases with no matches but +// skewed character distribution compression is lost. +// Default value depends on the compression level selected. +func WithAllLitEntropyCompression(b bool) EOption { + return func(o *encoderOptions) error { + o.customALEntropy = true + o.allLitEntropy = b + return nil + } +} + +// WithNoEntropyCompression will always skip entropy compression of literals. +// This can be useful if content has matches, but unlikely to benefit from entropy +// compression. Usually the slight speed improvement is not worth enabling this. +func WithNoEntropyCompression(b bool) EOption { + return func(o *encoderOptions) error { + o.noEntropy = b + return nil + } +} + +// WithSingleSegment will set the "single segment" flag when EncodeAll is used. +// If this flag is set, data must be regenerated within a single continuous memory segment. +// In this case, Window_Descriptor byte is skipped, but Frame_Content_Size is necessarily present. +// As a consequence, the decoder must allocate a memory segment of size equal or larger than size of your content. +// In order to preserve the decoder from unreasonable memory requirements, +// a decoder is allowed to reject a compressed frame which requests a memory size beyond decoder's authorized range. +// For broader compatibility, decoders are recommended to support memory sizes of at least 8 MB. +// This is only a recommendation, each decoder is free to support higher or lower limits, depending on local limitations. +// If this is not specified, block encodes will automatically choose this based on the input size and the window size. +// This setting has no effect on streamed encodes. +func WithSingleSegment(b bool) EOption { + return func(o *encoderOptions) error { + o.single = &b + return nil + } +} + +// WithLowerEncoderMem will trade in some memory cases trade less memory usage for +// slower encoding speed. +// This will not change the window size which is the primary function for reducing +// memory usage. See WithWindowSize. +func WithLowerEncoderMem(b bool) EOption { + return func(o *encoderOptions) error { + o.lowMem = b + return nil + } +} + +// WithEncoderDict allows to register a dictionary that will be used for the encode. +// +// The slice dict must be in the [dictionary format] produced by +// "zstd --train" from the Zstandard reference implementation. +// +// The encoder *may* choose to use no dictionary instead for certain payloads. +// +// [dictionary format]: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format +func WithEncoderDict(dict []byte) EOption { + return func(o *encoderOptions) error { + d, err := loadDict(dict) + if err != nil { + return err + } + o.dict = d + return nil + } +} + +// WithEncoderDictRaw registers a dictionary that may be used by the encoder. +// +// The slice content may contain arbitrary data. It will be used as an initial +// history. +func WithEncoderDictRaw(id uint32, content []byte) EOption { + return func(o *encoderOptions) error { + if bits.UintSize > 32 && uint(len(content)) > dictMaxLength { + return fmt.Errorf("dictionary of size %d > 2GiB too large", len(content)) + } + o.dict = &dict{id: id, content: content, offsets: [3]int{1, 4, 8}} + return nil + } +} diff --git a/vendor/github.com/klauspost/compress/zstd/framedec.go b/vendor/github.com/klauspost/compress/zstd/framedec.go new file mode 100644 index 000000000..53e160f7e --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/framedec.go @@ -0,0 +1,413 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "encoding/binary" + "encoding/hex" + "errors" + "io" + + "github.com/klauspost/compress/zstd/internal/xxhash" +) + +type frameDec struct { + o decoderOptions + crc *xxhash.Digest + + WindowSize uint64 + + // Frame history passed between blocks + history history + + rawInput byteBuffer + + // Byte buffer that can be reused for small input blocks. + bBuf byteBuf + + FrameContentSize uint64 + + DictionaryID uint32 + HasCheckSum bool + SingleSegment bool +} + +const ( + // MinWindowSize is the minimum Window Size, which is 1 KB. + MinWindowSize = 1 << 10 + + // MaxWindowSize is the maximum encoder window size + // and the default decoder maximum window size. + MaxWindowSize = 1 << 29 +) + +const ( + frameMagic = "\x28\xb5\x2f\xfd" + skippableFrameMagic = "\x2a\x4d\x18" +) + +func newFrameDec(o decoderOptions) *frameDec { + if o.maxWindowSize > o.maxDecodedSize { + o.maxWindowSize = o.maxDecodedSize + } + d := frameDec{ + o: o, + } + return &d +} + +// reset will read the frame header and prepare for block decoding. +// If nothing can be read from the input, io.EOF will be returned. +// Any other error indicated that the stream contained data, but +// there was a problem. +func (d *frameDec) reset(br byteBuffer) error { + d.HasCheckSum = false + d.WindowSize = 0 + var signature [4]byte + for { + var err error + // Check if we can read more... + b, err := br.readSmall(1) + switch err { + case io.EOF, io.ErrUnexpectedEOF: + return io.EOF + case nil: + signature[0] = b[0] + default: + return err + } + // Read the rest, don't allow io.ErrUnexpectedEOF + b, err = br.readSmall(3) + switch err { + case io.EOF: + return io.EOF + case nil: + copy(signature[1:], b) + default: + return err + } + + if string(signature[1:4]) != skippableFrameMagic || signature[0]&0xf0 != 0x50 { + if debugDecoder { + println("Not skippable", hex.EncodeToString(signature[:]), hex.EncodeToString([]byte(skippableFrameMagic))) + } + // Break if not skippable frame. + break + } + // Read size to skip + b, err = br.readSmall(4) + if err != nil { + if debugDecoder { + println("Reading Frame Size", err) + } + return err + } + n := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) + println("Skipping frame with", n, "bytes.") + err = br.skipN(int64(n)) + if err != nil { + if debugDecoder { + println("Reading discarded frame", err) + } + return err + } + } + if string(signature[:]) != frameMagic { + if debugDecoder { + println("Got magic numbers: ", signature, "want:", []byte(frameMagic)) + } + return ErrMagicMismatch + } + + // Read Frame_Header_Descriptor + fhd, err := br.readByte() + if err != nil { + if debugDecoder { + println("Reading Frame_Header_Descriptor", err) + } + return err + } + d.SingleSegment = fhd&(1<<5) != 0 + + if fhd&(1<<3) != 0 { + return errors.New("reserved bit set on frame header") + } + + // Read Window_Descriptor + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#window_descriptor + d.WindowSize = 0 + if !d.SingleSegment { + wd, err := br.readByte() + if err != nil { + if debugDecoder { + println("Reading Window_Descriptor", err) + } + return err + } + printf("raw: %x, mantissa: %d, exponent: %d\n", wd, wd&7, wd>>3) + windowLog := 10 + (wd >> 3) + windowBase := uint64(1) << windowLog + windowAdd := (windowBase / 8) * uint64(wd&0x7) + d.WindowSize = windowBase + windowAdd + } + + // Read Dictionary_ID + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary_id + d.DictionaryID = 0 + if size := fhd & 3; size != 0 { + if size == 3 { + size = 4 + } + + b, err := br.readSmall(int(size)) + if err != nil { + println("Reading Dictionary_ID", err) + return err + } + var id uint32 + switch len(b) { + case 1: + id = uint32(b[0]) + case 2: + id = uint32(b[0]) | (uint32(b[1]) << 8) + case 4: + id = uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) + } + if debugDecoder { + println("Dict size", size, "ID:", id) + } + d.DictionaryID = id + } + + // Read Frame_Content_Size + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_content_size + var fcsSize int + v := fhd >> 6 + switch v { + case 0: + if d.SingleSegment { + fcsSize = 1 + } + default: + fcsSize = 1 << v + } + d.FrameContentSize = fcsUnknown + if fcsSize > 0 { + b, err := br.readSmall(fcsSize) + if err != nil { + println("Reading Frame content", err) + return err + } + switch len(b) { + case 1: + d.FrameContentSize = uint64(b[0]) + case 2: + // When FCS_Field_Size is 2, the offset of 256 is added. + d.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) + 256 + case 4: + d.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) | (uint64(b[2]) << 16) | (uint64(b[3]) << 24) + case 8: + d1 := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) + d2 := uint32(b[4]) | (uint32(b[5]) << 8) | (uint32(b[6]) << 16) | (uint32(b[7]) << 24) + d.FrameContentSize = uint64(d1) | (uint64(d2) << 32) + } + if debugDecoder { + println("Read FCS:", d.FrameContentSize) + } + } + + // Move this to shared. + d.HasCheckSum = fhd&(1<<2) != 0 + if d.HasCheckSum { + if d.crc == nil { + d.crc = xxhash.New() + } + d.crc.Reset() + } + + if d.WindowSize > d.o.maxWindowSize { + if debugDecoder { + printf("window size %d > max %d\n", d.WindowSize, d.o.maxWindowSize) + } + return ErrWindowSizeExceeded + } + + if d.WindowSize == 0 && d.SingleSegment { + // We may not need window in this case. + d.WindowSize = d.FrameContentSize + if d.WindowSize < MinWindowSize { + d.WindowSize = MinWindowSize + } + if d.WindowSize > d.o.maxDecodedSize { + if debugDecoder { + printf("window size %d > max %d\n", d.WindowSize, d.o.maxWindowSize) + } + return ErrDecoderSizeExceeded + } + } + + // The minimum Window_Size is 1 KB. + if d.WindowSize < MinWindowSize { + if debugDecoder { + println("got window size: ", d.WindowSize) + } + return ErrWindowSizeTooSmall + } + d.history.windowSize = int(d.WindowSize) + if !d.o.lowMem || d.history.windowSize < maxBlockSize { + // Alloc 2x window size if not low-mem, or window size below 2MB. + d.history.allocFrameBuffer = d.history.windowSize * 2 + } else { + if d.o.lowMem { + // Alloc with 1MB extra. + d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize/2 + } else { + // Alloc with 2MB extra. + d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize + } + } + + if debugDecoder { + println("Frame: Dict:", d.DictionaryID, "FrameContentSize:", d.FrameContentSize, "singleseg:", d.SingleSegment, "window:", d.WindowSize, "crc:", d.HasCheckSum) + } + + // history contains input - maybe we do something + d.rawInput = br + return nil +} + +// next will start decoding the next block from stream. +func (d *frameDec) next(block *blockDec) error { + if debugDecoder { + println("decoding new block") + } + err := block.reset(d.rawInput, d.WindowSize) + if err != nil { + println("block error:", err) + // Signal the frame decoder we have a problem. + block.sendErr(err) + return err + } + return nil +} + +// checkCRC will check the checksum, assuming the frame has one. +// Will return ErrCRCMismatch if crc check failed, otherwise nil. +func (d *frameDec) checkCRC() error { + // We can overwrite upper tmp now + buf, err := d.rawInput.readSmall(4) + if err != nil { + println("CRC missing?", err) + return err + } + + want := binary.LittleEndian.Uint32(buf[:4]) + got := uint32(d.crc.Sum64()) + + if got != want { + if debugDecoder { + printf("CRC check failed: got %08x, want %08x\n", got, want) + } + return ErrCRCMismatch + } + if debugDecoder { + printf("CRC ok %08x\n", got) + } + return nil +} + +// consumeCRC skips over the checksum, assuming the frame has one. +func (d *frameDec) consumeCRC() error { + _, err := d.rawInput.readSmall(4) + if err != nil { + println("CRC missing?", err) + } + return err +} + +// runDecoder will run the decoder for the remainder of the frame. +func (d *frameDec) runDecoder(dst []byte, dec *blockDec) ([]byte, error) { + saved := d.history.b + + // We use the history for output to avoid copying it. + d.history.b = dst + d.history.ignoreBuffer = len(dst) + // Store input length, so we only check new data. + crcStart := len(dst) + d.history.decoders.maxSyncLen = 0 + if d.o.limitToCap { + d.history.decoders.maxSyncLen = uint64(cap(dst) - len(dst)) + } + if d.FrameContentSize != fcsUnknown { + if !d.o.limitToCap || d.FrameContentSize+uint64(len(dst)) < d.history.decoders.maxSyncLen { + d.history.decoders.maxSyncLen = d.FrameContentSize + uint64(len(dst)) + } + if d.history.decoders.maxSyncLen > d.o.maxDecodedSize { + if debugDecoder { + println("maxSyncLen:", d.history.decoders.maxSyncLen, "> maxDecodedSize:", d.o.maxDecodedSize) + } + return dst, ErrDecoderSizeExceeded + } + if debugDecoder { + println("maxSyncLen:", d.history.decoders.maxSyncLen) + } + if !d.o.limitToCap && uint64(cap(dst)) < d.history.decoders.maxSyncLen { + // Alloc for output + dst2 := make([]byte, len(dst), d.history.decoders.maxSyncLen+compressedBlockOverAlloc) + copy(dst2, dst) + dst = dst2 + } + } + var err error + for { + err = dec.reset(d.rawInput, d.WindowSize) + if err != nil { + break + } + if debugDecoder { + println("next block:", dec) + } + err = dec.decodeBuf(&d.history) + if err != nil { + break + } + if uint64(len(d.history.b)-crcStart) > d.o.maxDecodedSize { + println("runDecoder: maxDecodedSize exceeded", uint64(len(d.history.b)-crcStart), ">", d.o.maxDecodedSize) + err = ErrDecoderSizeExceeded + break + } + if d.o.limitToCap && len(d.history.b) > cap(dst) { + println("runDecoder: cap exceeded", uint64(len(d.history.b)), ">", cap(dst)) + err = ErrDecoderSizeExceeded + break + } + if uint64(len(d.history.b)-crcStart) > d.FrameContentSize { + println("runDecoder: FrameContentSize exceeded", uint64(len(d.history.b)-crcStart), ">", d.FrameContentSize) + err = ErrFrameSizeExceeded + break + } + if dec.Last { + break + } + if debugDecoder { + println("runDecoder: FrameContentSize", uint64(len(d.history.b)-crcStart), "<=", d.FrameContentSize) + } + } + dst = d.history.b + if err == nil { + if d.FrameContentSize != fcsUnknown && uint64(len(d.history.b)-crcStart) != d.FrameContentSize { + err = ErrFrameSizeMismatch + } else if d.HasCheckSum { + if d.o.ignoreChecksum { + err = d.consumeCRC() + } else { + d.crc.Write(dst[crcStart:]) + err = d.checkCRC() + } + } + } + d.history.b = saved + return dst, err +} diff --git a/vendor/github.com/klauspost/compress/zstd/frameenc.go b/vendor/github.com/klauspost/compress/zstd/frameenc.go new file mode 100644 index 000000000..2f5d5ed45 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/frameenc.go @@ -0,0 +1,137 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "encoding/binary" + "fmt" + "io" + "math" + "math/bits" +) + +type frameHeader struct { + ContentSize uint64 + WindowSize uint32 + SingleSegment bool + Checksum bool + DictID uint32 +} + +const maxHeaderSize = 14 + +func (f frameHeader) appendTo(dst []byte) []byte { + dst = append(dst, frameMagic...) + var fhd uint8 + if f.Checksum { + fhd |= 1 << 2 + } + if f.SingleSegment { + fhd |= 1 << 5 + } + + var dictIDContent []byte + if f.DictID > 0 { + var tmp [4]byte + if f.DictID < 256 { + fhd |= 1 + tmp[0] = uint8(f.DictID) + dictIDContent = tmp[:1] + } else if f.DictID < 1<<16 { + fhd |= 2 + binary.LittleEndian.PutUint16(tmp[:2], uint16(f.DictID)) + dictIDContent = tmp[:2] + } else { + fhd |= 3 + binary.LittleEndian.PutUint32(tmp[:4], f.DictID) + dictIDContent = tmp[:4] + } + } + var fcs uint8 + if f.ContentSize >= 256 { + fcs++ + } + if f.ContentSize >= 65536+256 { + fcs++ + } + if f.ContentSize >= 0xffffffff { + fcs++ + } + + fhd |= fcs << 6 + + dst = append(dst, fhd) + if !f.SingleSegment { + const winLogMin = 10 + windowLog := (bits.Len32(f.WindowSize-1) - winLogMin) << 3 + dst = append(dst, uint8(windowLog)) + } + if f.DictID > 0 { + dst = append(dst, dictIDContent...) + } + switch fcs { + case 0: + if f.SingleSegment { + dst = append(dst, uint8(f.ContentSize)) + } + // Unless SingleSegment is set, framessizes < 256 are nto stored. + case 1: + f.ContentSize -= 256 + dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8)) + case 2: + dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24)) + case 3: + dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24), + uint8(f.ContentSize>>32), uint8(f.ContentSize>>40), uint8(f.ContentSize>>48), uint8(f.ContentSize>>56)) + default: + panic("invalid fcs") + } + return dst +} + +const skippableFrameHeader = 4 + 4 + +// calcSkippableFrame will return a total size to be added for written +// to be divisible by multiple. +// The value will always be > skippableFrameHeader. +// The function will panic if written < 0 or wantMultiple <= 0. +func calcSkippableFrame(written, wantMultiple int64) int { + if wantMultiple <= 0 { + panic("wantMultiple <= 0") + } + if written < 0 { + panic("written < 0") + } + leftOver := written % wantMultiple + if leftOver == 0 { + return 0 + } + toAdd := wantMultiple - leftOver + for toAdd < skippableFrameHeader { + toAdd += wantMultiple + } + return int(toAdd) +} + +// skippableFrame will add a skippable frame with a total size of bytes. +// total should be >= skippableFrameHeader and < math.MaxUint32. +func skippableFrame(dst []byte, total int, r io.Reader) ([]byte, error) { + if total == 0 { + return dst, nil + } + if total < skippableFrameHeader { + return dst, fmt.Errorf("requested skippable frame (%d) < 8", total) + } + if int64(total) > math.MaxUint32 { + return dst, fmt.Errorf("requested skippable frame (%d) > max uint32", total) + } + dst = append(dst, 0x50, 0x2a, 0x4d, 0x18) + f := uint32(total - skippableFrameHeader) + dst = append(dst, uint8(f), uint8(f>>8), uint8(f>>16), uint8(f>>24)) + start := len(dst) + dst = append(dst, make([]byte, f)...) + _, err := io.ReadFull(r, dst[start:]) + return dst, err +} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder.go new file mode 100644 index 000000000..2f8860a72 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder.go @@ -0,0 +1,307 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "encoding/binary" + "errors" + "fmt" + "io" +) + +const ( + tablelogAbsoluteMax = 9 +) + +const ( + /*!MEMORY_USAGE : + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) + * Increasing memory usage improves compression ratio + * Reduced memory usage can improve speed, due to cache effect + * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ + maxMemoryUsage = tablelogAbsoluteMax + 2 + + maxTableLog = maxMemoryUsage - 2 + maxTablesize = 1 << maxTableLog + maxTableMask = (1 << maxTableLog) - 1 + minTablelog = 5 + maxSymbolValue = 255 +) + +// fseDecoder provides temporary storage for compression and decompression. +type fseDecoder struct { + dt [maxTablesize]decSymbol // Decompression table. + symbolLen uint16 // Length of active part of the symbol table. + actualTableLog uint8 // Selected tablelog. + maxBits uint8 // Maximum number of additional bits + + // used for table creation to avoid allocations. + stateTable [256]uint16 + norm [maxSymbolValue + 1]int16 + preDefined bool +} + +// tableStep returns the next table index. +func tableStep(tableSize uint32) uint32 { + return (tableSize >> 1) + (tableSize >> 3) + 3 +} + +// readNCount will read the symbol distribution so decoding tables can be constructed. +func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error { + var ( + charnum uint16 + previous0 bool + ) + if b.remain() < 4 { + return errors.New("input too small") + } + bitStream := b.Uint32NC() + nbBits := uint((bitStream & 0xF) + minTablelog) // extract tableLog + if nbBits > tablelogAbsoluteMax { + println("Invalid tablelog:", nbBits) + return errors.New("tableLog too large") + } + bitStream >>= 4 + bitCount := uint(4) + + s.actualTableLog = uint8(nbBits) + remaining := int32((1 << nbBits) + 1) + threshold := int32(1 << nbBits) + gotTotal := int32(0) + nbBits++ + + for remaining > 1 && charnum <= maxSymbol { + if previous0 { + //println("prev0") + n0 := charnum + for (bitStream & 0xFFFF) == 0xFFFF { + //println("24 x 0") + n0 += 24 + if r := b.remain(); r > 5 { + b.advance(2) + // The check above should make sure we can read 32 bits + bitStream = b.Uint32NC() >> bitCount + } else { + // end of bit stream + bitStream >>= 16 + bitCount += 16 + } + } + //printf("bitstream: %d, 0b%b", bitStream&3, bitStream) + for (bitStream & 3) == 3 { + n0 += 3 + bitStream >>= 2 + bitCount += 2 + } + n0 += uint16(bitStream & 3) + bitCount += 2 + + if n0 > maxSymbolValue { + return errors.New("maxSymbolValue too small") + } + //println("inserting ", n0-charnum, "zeroes from idx", charnum, "ending before", n0) + for charnum < n0 { + s.norm[uint8(charnum)] = 0 + charnum++ + } + + if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 { + b.advance(bitCount >> 3) + bitCount &= 7 + // The check above should make sure we can read 32 bits + bitStream = b.Uint32NC() >> bitCount + } else { + bitStream >>= 2 + } + } + + max := (2*threshold - 1) - remaining + var count int32 + + if int32(bitStream)&(threshold-1) < max { + count = int32(bitStream) & (threshold - 1) + if debugAsserts && nbBits < 1 { + panic("nbBits underflow") + } + bitCount += nbBits - 1 + } else { + count = int32(bitStream) & (2*threshold - 1) + if count >= threshold { + count -= max + } + bitCount += nbBits + } + + // extra accuracy + count-- + if count < 0 { + // -1 means +1 + remaining += count + gotTotal -= count + } else { + remaining -= count + gotTotal += count + } + s.norm[charnum&0xff] = int16(count) + charnum++ + previous0 = count == 0 + for remaining < threshold { + nbBits-- + threshold >>= 1 + } + + if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 { + b.advance(bitCount >> 3) + bitCount &= 7 + // The check above should make sure we can read 32 bits + bitStream = b.Uint32NC() >> (bitCount & 31) + } else { + bitCount -= (uint)(8 * (len(b.b) - 4 - b.off)) + b.off = len(b.b) - 4 + bitStream = b.Uint32() >> (bitCount & 31) + } + } + s.symbolLen = charnum + if s.symbolLen <= 1 { + return fmt.Errorf("symbolLen (%d) too small", s.symbolLen) + } + if s.symbolLen > maxSymbolValue+1 { + return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) + } + if remaining != 1 { + return fmt.Errorf("corruption detected (remaining %d != 1)", remaining) + } + if bitCount > 32 { + return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount) + } + if gotTotal != 1<> 3) + return s.buildDtable() +} + +func (s *fseDecoder) mustReadFrom(r io.Reader) { + fatalErr := func(err error) { + if err != nil { + panic(err) + } + } + // dt [maxTablesize]decSymbol // Decompression table. + // symbolLen uint16 // Length of active part of the symbol table. + // actualTableLog uint8 // Selected tablelog. + // maxBits uint8 // Maximum number of additional bits + // // used for table creation to avoid allocations. + // stateTable [256]uint16 + // norm [maxSymbolValue + 1]int16 + // preDefined bool + fatalErr(binary.Read(r, binary.LittleEndian, &s.dt)) + fatalErr(binary.Read(r, binary.LittleEndian, &s.symbolLen)) + fatalErr(binary.Read(r, binary.LittleEndian, &s.actualTableLog)) + fatalErr(binary.Read(r, binary.LittleEndian, &s.maxBits)) + fatalErr(binary.Read(r, binary.LittleEndian, &s.stateTable)) + fatalErr(binary.Read(r, binary.LittleEndian, &s.norm)) + fatalErr(binary.Read(r, binary.LittleEndian, &s.preDefined)) +} + +// decSymbol contains information about a state entry, +// Including the state offset base, the output symbol and +// the number of bits to read for the low part of the destination state. +// Using a composite uint64 is faster than a struct with separate members. +type decSymbol uint64 + +func newDecSymbol(nbits, addBits uint8, newState uint16, baseline uint32) decSymbol { + return decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32) +} + +func (d decSymbol) nbBits() uint8 { + return uint8(d) +} + +func (d decSymbol) addBits() uint8 { + return uint8(d >> 8) +} + +func (d decSymbol) newState() uint16 { + return uint16(d >> 16) +} + +func (d decSymbol) baselineInt() int { + return int(d >> 32) +} + +func (d *decSymbol) setNBits(nBits uint8) { + const mask = 0xffffffffffffff00 + *d = (*d & mask) | decSymbol(nBits) +} + +func (d *decSymbol) setAddBits(addBits uint8) { + const mask = 0xffffffffffff00ff + *d = (*d & mask) | (decSymbol(addBits) << 8) +} + +func (d *decSymbol) setNewState(state uint16) { + const mask = 0xffffffff0000ffff + *d = (*d & mask) | decSymbol(state)<<16 +} + +func (d *decSymbol) setExt(addBits uint8, baseline uint32) { + const mask = 0xffff00ff + *d = (*d & mask) | (decSymbol(addBits) << 8) | (decSymbol(baseline) << 32) +} + +// decSymbolValue returns the transformed decSymbol for the given symbol. +func decSymbolValue(symb uint8, t []baseOffset) (decSymbol, error) { + if int(symb) >= len(t) { + return 0, fmt.Errorf("rle symbol %d >= max %d", symb, len(t)) + } + lu := t[symb] + return newDecSymbol(0, lu.addBits, 0, lu.baseLine), nil +} + +// setRLE will set the decoder til RLE mode. +func (s *fseDecoder) setRLE(symbol decSymbol) { + s.actualTableLog = 0 + s.maxBits = symbol.addBits() + s.dt[0] = symbol +} + +// transform will transform the decoder table into a table usable for +// decoding without having to apply the transformation while decoding. +// The state will contain the base value and the number of bits to read. +func (s *fseDecoder) transform(t []baseOffset) error { + tableSize := uint16(1 << s.actualTableLog) + s.maxBits = 0 + for i, v := range s.dt[:tableSize] { + add := v.addBits() + if int(add) >= len(t) { + return fmt.Errorf("invalid decoding table entry %d, symbol %d >= max (%d)", i, v.addBits(), len(t)) + } + lu := t[add] + if lu.addBits > s.maxBits { + s.maxBits = lu.addBits + } + v.setExt(lu.addBits, lu.baseLine) + s.dt[i] = v + } + return nil +} + +type fseState struct { + dt []decSymbol + state decSymbol +} + +// Initialize and decodeAsync first state and symbol. +func (s *fseState) init(br *bitReader, tableLog uint8, dt []decSymbol) { + s.dt = dt + br.fill() + s.state = dt[br.getBits(tableLog)] +} + +// final returns the current state symbol without decoding the next. +func (s decSymbol) final() (int, uint8) { + return s.baselineInt(), s.addBits() +} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go new file mode 100644 index 000000000..d04a829b0 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go @@ -0,0 +1,65 @@ +//go:build amd64 && !appengine && !noasm && gc +// +build amd64,!appengine,!noasm,gc + +package zstd + +import ( + "fmt" +) + +type buildDtableAsmContext struct { + // inputs + stateTable *uint16 + norm *int16 + dt *uint64 + + // outputs --- set by the procedure in the case of error; + // for interpretation please see the error handling part below + errParam1 uint64 + errParam2 uint64 +} + +// buildDtable_asm is an x86 assembly implementation of fseDecoder.buildDtable. +// Function returns non-zero exit code on error. +// +//go:noescape +func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int + +// please keep in sync with _generate/gen_fse.go +const ( + errorCorruptedNormalizedCounter = 1 + errorNewStateTooBig = 2 + errorNewStateNoBits = 3 +) + +// buildDtable will build the decoding table. +func (s *fseDecoder) buildDtable() error { + ctx := buildDtableAsmContext{ + stateTable: &s.stateTable[0], + norm: &s.norm[0], + dt: (*uint64)(&s.dt[0]), + } + code := buildDtable_asm(s, &ctx) + + if code != 0 { + switch code { + case errorCorruptedNormalizedCounter: + position := ctx.errParam1 + return fmt.Errorf("corrupted input (position=%d, expected 0)", position) + + case errorNewStateTooBig: + newState := decSymbol(ctx.errParam1) + size := ctx.errParam2 + return fmt.Errorf("newState (%d) outside table size (%d)", newState, size) + + case errorNewStateNoBits: + newState := decSymbol(ctx.errParam1) + oldState := decSymbol(ctx.errParam2) + return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, oldState) + + default: + return fmt.Errorf("buildDtable_asm returned unhandled nonzero code = %d", code) + } + } + return nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s new file mode 100644 index 000000000..bcde39869 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s @@ -0,0 +1,126 @@ +// Code generated by command: go run gen_fse.go -out ../fse_decoder_amd64.s -pkg=zstd. DO NOT EDIT. + +//go:build !appengine && !noasm && gc && !noasm + +// func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int +TEXT ·buildDtable_asm(SB), $0-24 + MOVQ ctx+8(FP), CX + MOVQ s+0(FP), DI + + // Load values + MOVBQZX 4098(DI), DX + XORQ AX, AX + BTSQ DX, AX + MOVQ (CX), BX + MOVQ 16(CX), SI + LEAQ -1(AX), R8 + MOVQ 8(CX), CX + MOVWQZX 4096(DI), DI + + // End load values + // Init, lay down lowprob symbols + XORQ R9, R9 + JMP init_main_loop_condition + +init_main_loop: + MOVWQSX (CX)(R9*2), R10 + CMPW R10, $-1 + JNE do_not_update_high_threshold + MOVB R9, 1(SI)(R8*8) + DECQ R8 + MOVQ $0x0000000000000001, R10 + +do_not_update_high_threshold: + MOVW R10, (BX)(R9*2) + INCQ R9 + +init_main_loop_condition: + CMPQ R9, DI + JL init_main_loop + + // Spread symbols + // Calculate table step + MOVQ AX, R9 + SHRQ $0x01, R9 + MOVQ AX, R10 + SHRQ $0x03, R10 + LEAQ 3(R9)(R10*1), R9 + + // Fill add bits values + LEAQ -1(AX), R10 + XORQ R11, R11 + XORQ R12, R12 + JMP spread_main_loop_condition + +spread_main_loop: + XORQ R13, R13 + MOVWQSX (CX)(R12*2), R14 + JMP spread_inner_loop_condition + +spread_inner_loop: + MOVB R12, 1(SI)(R11*8) + +adjust_position: + ADDQ R9, R11 + ANDQ R10, R11 + CMPQ R11, R8 + JG adjust_position + INCQ R13 + +spread_inner_loop_condition: + CMPQ R13, R14 + JL spread_inner_loop + INCQ R12 + +spread_main_loop_condition: + CMPQ R12, DI + JL spread_main_loop + TESTQ R11, R11 + JZ spread_check_ok + MOVQ ctx+8(FP), AX + MOVQ R11, 24(AX) + MOVQ $+1, ret+16(FP) + RET + +spread_check_ok: + // Build Decoding table + XORQ DI, DI + +build_table_main_table: + MOVBQZX 1(SI)(DI*8), CX + MOVWQZX (BX)(CX*2), R8 + LEAQ 1(R8), R9 + MOVW R9, (BX)(CX*2) + MOVQ R8, R9 + BSRQ R9, R9 + MOVQ DX, CX + SUBQ R9, CX + SHLQ CL, R8 + SUBQ AX, R8 + MOVB CL, (SI)(DI*8) + MOVW R8, 2(SI)(DI*8) + CMPQ R8, AX + JLE build_table_check1_ok + MOVQ ctx+8(FP), CX + MOVQ R8, 24(CX) + MOVQ AX, 32(CX) + MOVQ $+2, ret+16(FP) + RET + +build_table_check1_ok: + TESTB CL, CL + JNZ build_table_check2_ok + CMPW R8, DI + JNE build_table_check2_ok + MOVQ ctx+8(FP), AX + MOVQ R8, 24(AX) + MOVQ DI, 32(AX) + MOVQ $+3, ret+16(FP) + RET + +build_table_check2_ok: + INCQ DI + CMPQ DI, AX + JL build_table_main_table + MOVQ $+0, ret+16(FP) + RET diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go new file mode 100644 index 000000000..332e51fe4 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go @@ -0,0 +1,72 @@ +//go:build !amd64 || appengine || !gc || noasm +// +build !amd64 appengine !gc noasm + +package zstd + +import ( + "errors" + "fmt" +) + +// buildDtable will build the decoding table. +func (s *fseDecoder) buildDtable() error { + tableSize := uint32(1 << s.actualTableLog) + highThreshold := tableSize - 1 + symbolNext := s.stateTable[:256] + + // Init, lay down lowprob symbols + { + for i, v := range s.norm[:s.symbolLen] { + if v == -1 { + s.dt[highThreshold].setAddBits(uint8(i)) + highThreshold-- + symbolNext[i] = 1 + } else { + symbolNext[i] = uint16(v) + } + } + } + + // Spread symbols + { + tableMask := tableSize - 1 + step := tableStep(tableSize) + position := uint32(0) + for ss, v := range s.norm[:s.symbolLen] { + for i := 0; i < int(v); i++ { + s.dt[position].setAddBits(uint8(ss)) + position = (position + step) & tableMask + for position > highThreshold { + // lowprob area + position = (position + step) & tableMask + } + } + } + if position != 0 { + // position must reach all cells once, otherwise normalizedCounter is incorrect + return errors.New("corrupted input (position != 0)") + } + } + + // Build Decoding table + { + tableSize := uint16(1 << s.actualTableLog) + for u, v := range s.dt[:tableSize] { + symbol := v.addBits() + nextState := symbolNext[symbol] + symbolNext[symbol] = nextState + 1 + nBits := s.actualTableLog - byte(highBits(uint32(nextState))) + s.dt[u&maxTableMask].setNBits(nBits) + newState := (nextState << nBits) - tableSize + if newState > tableSize { + return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize) + } + if newState == uint16(u) && nBits == 0 { + // Seems weird that this is possible with nbits > 0. + return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u) + } + s.dt[u&maxTableMask].setNewState(newState) + } + } + return nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_encoder.go b/vendor/github.com/klauspost/compress/zstd/fse_encoder.go new file mode 100644 index 000000000..ab26326a8 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/fse_encoder.go @@ -0,0 +1,701 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "errors" + "fmt" + "math" +) + +const ( + // For encoding we only support up to + maxEncTableLog = 8 + maxEncTablesize = 1 << maxTableLog + maxEncTableMask = (1 << maxTableLog) - 1 + minEncTablelog = 5 + maxEncSymbolValue = maxMatchLengthSymbol +) + +// Scratch provides temporary storage for compression and decompression. +type fseEncoder struct { + symbolLen uint16 // Length of active part of the symbol table. + actualTableLog uint8 // Selected tablelog. + ct cTable // Compression tables. + maxCount int // count of the most probable symbol + zeroBits bool // no bits has prob > 50%. + clearCount bool // clear count + useRLE bool // This encoder is for RLE + preDefined bool // This encoder is predefined. + reUsed bool // Set to know when the encoder has been reused. + rleVal uint8 // RLE Symbol + maxBits uint8 // Maximum output bits after transform. + + // TODO: Technically zstd should be fine with 64 bytes. + count [256]uint32 + norm [256]int16 +} + +// cTable contains tables used for compression. +type cTable struct { + tableSymbol []byte + stateTable []uint16 + symbolTT []symbolTransform +} + +// symbolTransform contains the state transform for a symbol. +type symbolTransform struct { + deltaNbBits uint32 + deltaFindState int16 + outBits uint8 +} + +// String prints values as a human readable string. +func (s symbolTransform) String() string { + return fmt.Sprintf("{deltabits: %08x, findstate:%d outbits:%d}", s.deltaNbBits, s.deltaFindState, s.outBits) +} + +// Histogram allows to populate the histogram and skip that step in the compression, +// It otherwise allows to inspect the histogram when compression is done. +// To indicate that you have populated the histogram call HistogramFinished +// with the value of the highest populated symbol, as well as the number of entries +// in the most populated entry. These are accepted at face value. +func (s *fseEncoder) Histogram() *[256]uint32 { + return &s.count +} + +// HistogramFinished can be called to indicate that the histogram has been populated. +// maxSymbol is the index of the highest set symbol of the next data segment. +// maxCount is the number of entries in the most populated entry. +// These are accepted at face value. +func (s *fseEncoder) HistogramFinished(maxSymbol uint8, maxCount int) { + s.maxCount = maxCount + s.symbolLen = uint16(maxSymbol) + 1 + s.clearCount = maxCount != 0 +} + +// allocCtable will allocate tables needed for compression. +// If existing tables a re big enough, they are simply re-used. +func (s *fseEncoder) allocCtable() { + tableSize := 1 << s.actualTableLog + // get tableSymbol that is big enough. + if cap(s.ct.tableSymbol) < tableSize { + s.ct.tableSymbol = make([]byte, tableSize) + } + s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] + + ctSize := tableSize + if cap(s.ct.stateTable) < ctSize { + s.ct.stateTable = make([]uint16, ctSize) + } + s.ct.stateTable = s.ct.stateTable[:ctSize] + + if cap(s.ct.symbolTT) < 256 { + s.ct.symbolTT = make([]symbolTransform, 256) + } + s.ct.symbolTT = s.ct.symbolTT[:256] +} + +// buildCTable will populate the compression table so it is ready to be used. +func (s *fseEncoder) buildCTable() error { + tableSize := uint32(1 << s.actualTableLog) + highThreshold := tableSize - 1 + var cumul [256]int16 + + s.allocCtable() + tableSymbol := s.ct.tableSymbol[:tableSize] + // symbol start positions + { + cumul[0] = 0 + for ui, v := range s.norm[:s.symbolLen-1] { + u := byte(ui) // one less than reference + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = u + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + } + // Encode last symbol separately to avoid overflowing u + u := int(s.symbolLen - 1) + v := s.norm[s.symbolLen-1] + if v == -1 { + // Low proba symbol + cumul[u+1] = cumul[u] + 1 + tableSymbol[highThreshold] = byte(u) + highThreshold-- + } else { + cumul[u+1] = cumul[u] + v + } + if uint32(cumul[s.symbolLen]) != tableSize { + return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) + } + cumul[s.symbolLen] = int16(tableSize) + 1 + } + // Spread symbols + s.zeroBits = false + { + step := tableStep(tableSize) + tableMask := tableSize - 1 + var position uint32 + // if any symbol > largeLimit, we may have 0 bits output. + largeLimit := int16(1 << (s.actualTableLog - 1)) + for ui, v := range s.norm[:s.symbolLen] { + symbol := byte(ui) + if v > largeLimit { + s.zeroBits = true + } + for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { + tableSymbol[position] = symbol + position = (position + step) & tableMask + for position > highThreshold { + position = (position + step) & tableMask + } /* Low proba area */ + } + } + + // Check if we have gone through all positions + if position != 0 { + return errors.New("position!=0") + } + } + + // Build table + table := s.ct.stateTable + { + tsi := int(tableSize) + for u, v := range tableSymbol { + // TableU16 : sorted by symbol order; gives next state value + table[cumul[v]] = uint16(tsi + u) + cumul[v]++ + } + } + + // Build Symbol Transformation Table + { + total := int16(0) + symbolTT := s.ct.symbolTT[:s.symbolLen] + tableLog := s.actualTableLog + tl := (uint32(tableLog) << 16) - (1 << tableLog) + for i, v := range s.norm[:s.symbolLen] { + switch v { + case 0: + case -1, 1: + symbolTT[i].deltaNbBits = tl + symbolTT[i].deltaFindState = total - 1 + total++ + default: + maxBitsOut := uint32(tableLog) - highBit(uint32(v-1)) + minStatePlus := uint32(v) << maxBitsOut + symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus + symbolTT[i].deltaFindState = total - v + total += v + } + } + if total != int16(tableSize) { + return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) + } + } + return nil +} + +var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} + +func (s *fseEncoder) setRLE(val byte) { + s.allocCtable() + s.actualTableLog = 0 + s.ct.stateTable = s.ct.stateTable[:1] + s.ct.symbolTT[val] = symbolTransform{ + deltaFindState: 0, + deltaNbBits: 0, + } + if debugEncoder { + println("setRLE: val", val, "symbolTT", s.ct.symbolTT[val]) + } + s.rleVal = val + s.useRLE = true +} + +// setBits will set output bits for the transform. +// if nil is provided, the number of bits is equal to the index. +func (s *fseEncoder) setBits(transform []byte) { + if s.reUsed || s.preDefined { + return + } + if s.useRLE { + if transform == nil { + s.ct.symbolTT[s.rleVal].outBits = s.rleVal + s.maxBits = s.rleVal + return + } + s.maxBits = transform[s.rleVal] + s.ct.symbolTT[s.rleVal].outBits = s.maxBits + return + } + if transform == nil { + for i := range s.ct.symbolTT[:s.symbolLen] { + s.ct.symbolTT[i].outBits = uint8(i) + } + s.maxBits = uint8(s.symbolLen - 1) + return + } + s.maxBits = 0 + for i, v := range transform[:s.symbolLen] { + s.ct.symbolTT[i].outBits = v + if v > s.maxBits { + // We could assume bits always going up, but we play safe. + s.maxBits = v + } + } +} + +// normalizeCount will normalize the count of the symbols so +// the total is equal to the table size. +// If successful, compression tables will also be made ready. +func (s *fseEncoder) normalizeCount(length int) error { + if s.reUsed { + return nil + } + s.optimalTableLog(length) + var ( + tableLog = s.actualTableLog + scale = 62 - uint64(tableLog) + step = (1 << 62) / uint64(length) + vStep = uint64(1) << (scale - 20) + stillToDistribute = int16(1 << tableLog) + largest int + largestP int16 + lowThreshold = (uint32)(length >> tableLog) + ) + if s.maxCount == length { + s.useRLE = true + return nil + } + s.useRLE = false + for i, cnt := range s.count[:s.symbolLen] { + // already handled + // if (count[s] == s.length) return 0; /* rle special case */ + + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + stillToDistribute-- + } else { + proba := (int16)((uint64(cnt) * step) >> scale) + if proba < 8 { + restToBeat := vStep * uint64(rtbTable[proba]) + v := uint64(cnt)*step - (uint64(proba) << scale) + if v > restToBeat { + proba++ + } + } + if proba > largestP { + largestP = proba + largest = i + } + s.norm[i] = proba + stillToDistribute -= proba + } + } + + if -stillToDistribute >= (s.norm[largest] >> 1) { + // corner case, need another normalization method + err := s.normalizeCount2(length) + if err != nil { + return err + } + if debugAsserts { + err = s.validateNorm() + if err != nil { + return err + } + } + return s.buildCTable() + } + s.norm[largest] += stillToDistribute + if debugAsserts { + err := s.validateNorm() + if err != nil { + return err + } + } + return s.buildCTable() +} + +// Secondary normalization method. +// To be used when primary method fails. +func (s *fseEncoder) normalizeCount2(length int) error { + const notYetAssigned = -2 + var ( + distributed uint32 + total = uint32(length) + tableLog = s.actualTableLog + lowThreshold = total >> tableLog + lowOne = (total * 3) >> (tableLog + 1) + ) + for i, cnt := range s.count[:s.symbolLen] { + if cnt == 0 { + s.norm[i] = 0 + continue + } + if cnt <= lowThreshold { + s.norm[i] = -1 + distributed++ + total -= cnt + continue + } + if cnt <= lowOne { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + s.norm[i] = notYetAssigned + } + toDistribute := (1 << tableLog) - distributed + + if (total / toDistribute) > lowOne { + // risk of rounding to zero + lowOne = (total * 3) / (toDistribute * 2) + for i, cnt := range s.count[:s.symbolLen] { + if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { + s.norm[i] = 1 + distributed++ + total -= cnt + continue + } + } + toDistribute = (1 << tableLog) - distributed + } + if distributed == uint32(s.symbolLen)+1 { + // all values are pretty poor; + // probably incompressible data (should have already been detected); + // find max, then give all remaining points to max + var maxV int + var maxC uint32 + for i, cnt := range s.count[:s.symbolLen] { + if cnt > maxC { + maxV = i + maxC = cnt + } + } + s.norm[maxV] += int16(toDistribute) + return nil + } + + if total == 0 { + // all of the symbols were low enough for the lowOne or lowThreshold + for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { + if s.norm[i] > 0 { + toDistribute-- + s.norm[i]++ + } + } + return nil + } + + var ( + vStepLog = 62 - uint64(tableLog) + mid = uint64((1 << (vStepLog - 1)) - 1) + rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining + tmpTotal = mid + ) + for i, cnt := range s.count[:s.symbolLen] { + if s.norm[i] == notYetAssigned { + var ( + end = tmpTotal + uint64(cnt)*rStep + sStart = uint32(tmpTotal >> vStepLog) + sEnd = uint32(end >> vStepLog) + weight = sEnd - sStart + ) + if weight < 1 { + return errors.New("weight < 1") + } + s.norm[i] = int16(weight) + tmpTotal = end + } + } + return nil +} + +// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog +func (s *fseEncoder) optimalTableLog(length int) { + tableLog := uint8(maxEncTableLog) + minBitsSrc := highBit(uint32(length)) + 1 + minBitsSymbols := highBit(uint32(s.symbolLen-1)) + 2 + minBits := uint8(minBitsSymbols) + if minBitsSrc < minBitsSymbols { + minBits = uint8(minBitsSrc) + } + + maxBitsSrc := uint8(highBit(uint32(length-1))) - 2 + if maxBitsSrc < tableLog { + // Accuracy can be reduced + tableLog = maxBitsSrc + } + if minBits > tableLog { + tableLog = minBits + } + // Need a minimum to safely represent all symbol values + if tableLog < minEncTablelog { + tableLog = minEncTablelog + } + if tableLog > maxEncTableLog { + tableLog = maxEncTableLog + } + s.actualTableLog = tableLog +} + +// validateNorm validates the normalized histogram table. +func (s *fseEncoder) validateNorm() (err error) { + var total int + for _, v := range s.norm[:s.symbolLen] { + if v >= 0 { + total += int(v) + } else { + total -= int(v) + } + } + defer func() { + if err == nil { + return + } + fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen) + for i, v := range s.norm[:s.symbolLen] { + fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v) + } + }() + if total != (1 << s.actualTableLog) { + return fmt.Errorf("warning: Total == %d != %d", total, 1<> 3) + 3 + 2 + + // Write Table Size + bitStream = uint32(tableLog - minEncTablelog) + bitCount = uint(4) + remaining = int16(tableSize + 1) /* +1 for extra accuracy */ + threshold = int16(tableSize) + nbBits = uint(tableLog + 1) + outP = len(out) + ) + if cap(out) < outP+maxHeaderSize { + out = append(out, make([]byte, maxHeaderSize*3)...) + out = out[:len(out)-maxHeaderSize*3] + } + out = out[:outP+maxHeaderSize] + + // stops at 1 + for remaining > 1 { + if previous0 { + start := charnum + for s.norm[charnum] == 0 { + charnum++ + } + for charnum >= start+24 { + start += 24 + bitStream += uint32(0xFFFF) << bitCount + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + } + for charnum >= start+3 { + start += 3 + bitStream += 3 << bitCount + bitCount += 2 + } + bitStream += uint32(charnum-start) << bitCount + bitCount += 2 + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + count := s.norm[charnum] + charnum++ + max := (2*threshold - 1) - remaining + if count < 0 { + remaining += count + } else { + remaining -= count + } + count++ // +1 for extra accuracy + if count >= threshold { + count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ + } + bitStream += uint32(count) << bitCount + bitCount += nbBits + if count < max { + bitCount-- + } + + previous0 = count == 1 + if remaining < 1 { + return nil, errors.New("internal error: remaining < 1") + } + for remaining < threshold { + nbBits-- + threshold >>= 1 + } + + if bitCount > 16 { + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += 2 + bitStream >>= 16 + bitCount -= 16 + } + } + + if outP+2 > len(out) { + return nil, fmt.Errorf("internal error: %d > %d, maxheader: %d, sl: %d, tl: %d, normcount: %v", outP+2, len(out), maxHeaderSize, s.symbolLen, int(tableLog), s.norm[:s.symbolLen]) + } + out[outP] = byte(bitStream) + out[outP+1] = byte(bitStream >> 8) + outP += int((bitCount + 7) / 8) + + if charnum > s.symbolLen { + return nil, errors.New("internal error: charnum > s.symbolLen") + } + return out[:outP], nil +} + +// Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits) +// note 1 : assume symbolValue is valid (<= maxSymbolValue) +// note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits * +func (s *fseEncoder) bitCost(symbolValue uint8, accuracyLog uint32) uint32 { + minNbBits := s.ct.symbolTT[symbolValue].deltaNbBits >> 16 + threshold := (minNbBits + 1) << 16 + if debugAsserts { + if !(s.actualTableLog < 16) { + panic("!s.actualTableLog < 16") + } + // ensure enough room for renormalization double shift + if !(uint8(accuracyLog) < 31-s.actualTableLog) { + panic("!uint8(accuracyLog) < 31-s.actualTableLog") + } + } + tableSize := uint32(1) << s.actualTableLog + deltaFromThreshold := threshold - (s.ct.symbolTT[symbolValue].deltaNbBits + tableSize) + // linear interpolation (very approximate) + normalizedDeltaFromThreshold := (deltaFromThreshold << accuracyLog) >> s.actualTableLog + bitMultiplier := uint32(1) << accuracyLog + if debugAsserts { + if s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold { + panic("s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold") + } + if normalizedDeltaFromThreshold > bitMultiplier { + panic("normalizedDeltaFromThreshold > bitMultiplier") + } + } + return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold +} + +// Returns the cost in bits of encoding the distribution in count using ctable. +// Histogram should only be up to the last non-zero symbol. +// Returns an -1 if ctable cannot represent all the symbols in count. +func (s *fseEncoder) approxSize(hist []uint32) uint32 { + if int(s.symbolLen) < len(hist) { + // More symbols than we have. + return math.MaxUint32 + } + if s.useRLE { + // We will never reuse RLE encoders. + return math.MaxUint32 + } + const kAccuracyLog = 8 + badCost := (uint32(s.actualTableLog) + 1) << kAccuracyLog + var cost uint32 + for i, v := range hist { + if v == 0 { + continue + } + if s.norm[i] == 0 { + return math.MaxUint32 + } + bitCost := s.bitCost(uint8(i), kAccuracyLog) + if bitCost > badCost { + return math.MaxUint32 + } + cost += v * bitCost + } + return cost >> kAccuracyLog +} + +// maxHeaderSize returns the maximum header size in bits. +// This is not exact size, but we want a penalty for new tables anyway. +func (s *fseEncoder) maxHeaderSize() uint32 { + if s.preDefined { + return 0 + } + if s.useRLE { + return 8 + } + return (((uint32(s.symbolLen) * uint32(s.actualTableLog)) >> 3) + 3) * 8 +} + +// cState contains the compression state of a stream. +type cState struct { + bw *bitWriter + stateTable []uint16 + state uint16 +} + +// init will initialize the compression state to the first symbol of the stream. +func (c *cState) init(bw *bitWriter, ct *cTable, first symbolTransform) { + c.bw = bw + c.stateTable = ct.stateTable + if len(c.stateTable) == 1 { + // RLE + c.stateTable[0] = uint16(0) + c.state = 0 + return + } + nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 + im := int32((nbBitsOut << 16) - first.deltaNbBits) + lu := (im >> nbBitsOut) + int32(first.deltaFindState) + c.state = c.stateTable[lu] +} + +// flush will write the tablelog to the output and flush the remaining full bytes. +func (c *cState) flush(tableLog uint8) { + c.bw.flush32() + c.bw.addBits16NC(c.state, tableLog) +} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_predefined.go b/vendor/github.com/klauspost/compress/zstd/fse_predefined.go new file mode 100644 index 000000000..474cb77d2 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/fse_predefined.go @@ -0,0 +1,158 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "fmt" + "math" + "sync" +) + +var ( + // fsePredef are the predefined fse tables as defined here: + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions + // These values are already transformed. + fsePredef [3]fseDecoder + + // fsePredefEnc are the predefined encoder based on fse tables as defined here: + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions + // These values are already transformed. + fsePredefEnc [3]fseEncoder + + // symbolTableX contain the transformations needed for each type as defined in + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets + symbolTableX [3][]baseOffset + + // maxTableSymbol is the biggest supported symbol for each table type + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets + maxTableSymbol = [3]uint8{tableLiteralLengths: maxLiteralLengthSymbol, tableOffsets: maxOffsetLengthSymbol, tableMatchLengths: maxMatchLengthSymbol} + + // bitTables is the bits table for each table. + bitTables = [3][]byte{tableLiteralLengths: llBitsTable[:], tableOffsets: nil, tableMatchLengths: mlBitsTable[:]} +) + +type tableIndex uint8 + +const ( + // indexes for fsePredef and symbolTableX + tableLiteralLengths tableIndex = 0 + tableOffsets tableIndex = 1 + tableMatchLengths tableIndex = 2 + + maxLiteralLengthSymbol = 35 + maxOffsetLengthSymbol = 30 + maxMatchLengthSymbol = 52 +) + +// baseOffset is used for calculating transformations. +type baseOffset struct { + baseLine uint32 + addBits uint8 +} + +// fillBase will precalculate base offsets with the given bit distributions. +func fillBase(dst []baseOffset, base uint32, bits ...uint8) { + if len(bits) != len(dst) { + panic(fmt.Sprintf("len(dst) (%d) != len(bits) (%d)", len(dst), len(bits))) + } + for i, bit := range bits { + if base > math.MaxInt32 { + panic("invalid decoding table, base overflows int32") + } + + dst[i] = baseOffset{ + baseLine: base, + addBits: bit, + } + base += 1 << bit + } +} + +var predef sync.Once + +func initPredefined() { + predef.Do(func() { + // Literals length codes + tmp := make([]baseOffset, 36) + for i := range tmp[:16] { + tmp[i] = baseOffset{ + baseLine: uint32(i), + addBits: 0, + } + } + fillBase(tmp[16:], 16, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) + symbolTableX[tableLiteralLengths] = tmp + + // Match length codes + tmp = make([]baseOffset, 53) + for i := range tmp[:32] { + tmp[i] = baseOffset{ + // The transformation adds the 3 length. + baseLine: uint32(i) + 3, + addBits: 0, + } + } + fillBase(tmp[32:], 35, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) + symbolTableX[tableMatchLengths] = tmp + + // Offset codes + tmp = make([]baseOffset, maxOffsetBits+1) + tmp[1] = baseOffset{ + baseLine: 1, + addBits: 1, + } + fillBase(tmp[2:], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30) + symbolTableX[tableOffsets] = tmp + + // Fill predefined tables and transform them. + // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions + for i := range fsePredef[:] { + f := &fsePredef[i] + switch tableIndex(i) { + case tableLiteralLengths: + // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L243 + f.actualTableLog = 6 + copy(f.norm[:], []int16{4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, + -1, -1, -1, -1}) + f.symbolLen = 36 + case tableOffsets: + // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L281 + f.actualTableLog = 5 + copy(f.norm[:], []int16{ + 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}) + f.symbolLen = 29 + case tableMatchLengths: + //https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L304 + f.actualTableLog = 6 + copy(f.norm[:], []int16{ + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, + -1, -1, -1, -1, -1}) + f.symbolLen = 53 + } + if err := f.buildDtable(); err != nil { + panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) + } + if err := f.transform(symbolTableX[i]); err != nil { + panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) + } + f.preDefined = true + + // Create encoder as well + enc := &fsePredefEnc[i] + copy(enc.norm[:], f.norm[:]) + enc.symbolLen = f.symbolLen + enc.actualTableLog = f.actualTableLog + if err := enc.buildCTable(); err != nil { + panic(fmt.Errorf("building encoding table %v: %v", tableIndex(i), err)) + } + enc.setBits(bitTables[i]) + enc.preDefined = true + } + }) +} diff --git a/vendor/github.com/klauspost/compress/zstd/hash.go b/vendor/github.com/klauspost/compress/zstd/hash.go new file mode 100644 index 000000000..5d73c21eb --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/hash.go @@ -0,0 +1,35 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +const ( + prime3bytes = 506832829 + prime4bytes = 2654435761 + prime5bytes = 889523592379 + prime6bytes = 227718039650203 + prime7bytes = 58295818150454627 + prime8bytes = 0xcf1bbcdcb7a56463 +) + +// hashLen returns a hash of the lowest mls bytes of with length output bits. +// mls must be >=3 and <=8. Any other value will return hash for 4 bytes. +// length should always be < 32. +// Preferably length and mls should be a constant for inlining. +func hashLen(u uint64, length, mls uint8) uint32 { + switch mls { + case 3: + return (uint32(u<<8) * prime3bytes) >> (32 - length) + case 5: + return uint32(((u << (64 - 40)) * prime5bytes) >> (64 - length)) + case 6: + return uint32(((u << (64 - 48)) * prime6bytes) >> (64 - length)) + case 7: + return uint32(((u << (64 - 56)) * prime7bytes) >> (64 - length)) + case 8: + return uint32((u * prime8bytes) >> (64 - length)) + default: + return (uint32(u) * prime4bytes) >> (32 - length) + } +} diff --git a/vendor/github.com/klauspost/compress/zstd/history.go b/vendor/github.com/klauspost/compress/zstd/history.go new file mode 100644 index 000000000..09164856d --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/history.go @@ -0,0 +1,116 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "github.com/klauspost/compress/huff0" +) + +// history contains the information transferred between blocks. +type history struct { + // Literal decompression + huffTree *huff0.Scratch + + // Sequence decompression + decoders sequenceDecs + recentOffsets [3]int + + // History buffer... + b []byte + + // ignoreBuffer is meant to ignore a number of bytes + // when checking for matches in history + ignoreBuffer int + + windowSize int + allocFrameBuffer int // needed? + error bool + dict *dict +} + +// reset will reset the history to initial state of a frame. +// The history must already have been initialized to the desired size. +func (h *history) reset() { + h.b = h.b[:0] + h.ignoreBuffer = 0 + h.error = false + h.recentOffsets = [3]int{1, 4, 8} + h.decoders.freeDecoders() + h.decoders = sequenceDecs{br: h.decoders.br} + h.freeHuffDecoder() + h.huffTree = nil + h.dict = nil + //printf("history created: %+v (l: %d, c: %d)", *h, len(h.b), cap(h.b)) +} + +func (h *history) freeHuffDecoder() { + if h.huffTree != nil { + if h.dict == nil || h.dict.litEnc != h.huffTree { + huffDecoderPool.Put(h.huffTree) + h.huffTree = nil + } + } +} + +func (h *history) setDict(dict *dict) { + if dict == nil { + return + } + h.dict = dict + h.decoders.litLengths = dict.llDec + h.decoders.offsets = dict.ofDec + h.decoders.matchLengths = dict.mlDec + h.decoders.dict = dict.content + h.recentOffsets = dict.offsets + h.huffTree = dict.litEnc +} + +// append bytes to history. +// This function will make sure there is space for it, +// if the buffer has been allocated with enough extra space. +func (h *history) append(b []byte) { + if len(b) >= h.windowSize { + // Discard all history by simply overwriting + h.b = h.b[:h.windowSize] + copy(h.b, b[len(b)-h.windowSize:]) + return + } + + // If there is space, append it. + if len(b) < cap(h.b)-len(h.b) { + h.b = append(h.b, b...) + return + } + + // Move data down so we only have window size left. + // We know we have less than window size in b at this point. + discard := len(b) + len(h.b) - h.windowSize + copy(h.b, h.b[discard:]) + h.b = h.b[:h.windowSize] + copy(h.b[h.windowSize-len(b):], b) +} + +// ensureBlock will ensure there is space for at least one block... +func (h *history) ensureBlock() { + if cap(h.b) < h.allocFrameBuffer { + h.b = make([]byte, 0, h.allocFrameBuffer) + return + } + + avail := cap(h.b) - len(h.b) + if avail >= h.windowSize || avail > maxCompressedBlockSize { + return + } + // Move data down so we only have window size left. + // We know we have less than window size in b at this point. + discard := len(h.b) - h.windowSize + copy(h.b, h.b[discard:]) + h.b = h.b[:h.windowSize] +} + +// append bytes to history without ever discarding anything. +func (h *history) appendKeep(b []byte) { + h.b = append(h.b, b...) +} diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt new file mode 100644 index 000000000..24b53065f --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2016 Caleb Spare + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md new file mode 100644 index 000000000..777290d44 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md @@ -0,0 +1,71 @@ +# xxhash + +VENDORED: Go to [github.com/cespare/xxhash](https://github.com/cespare/xxhash) for original package. + +xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a +high-quality hashing algorithm that is much faster than anything in the Go +standard library. + +This package provides a straightforward API: + +``` +func Sum64(b []byte) uint64 +func Sum64String(s string) uint64 +type Digest struct{ ... } + func New() *Digest +``` + +The `Digest` type implements hash.Hash64. Its key methods are: + +``` +func (*Digest) Write([]byte) (int, error) +func (*Digest) WriteString(string) (int, error) +func (*Digest) Sum64() uint64 +``` + +The package is written with optimized pure Go and also contains even faster +assembly implementations for amd64 and arm64. If desired, the `purego` build tag +opts into using the Go code even on those architectures. + +[xxHash]: http://cyan4973.github.io/xxHash/ + +## Compatibility + +This package is in a module and the latest code is in version 2 of the module. +You need a version of Go with at least "minimal module compatibility" to use +github.com/cespare/xxhash/v2: + +* 1.9.7+ for Go 1.9 +* 1.10.3+ for Go 1.10 +* Go 1.11 or later + +I recommend using the latest release of Go. + +## Benchmarks + +Here are some quick benchmarks comparing the pure-Go and assembly +implementations of Sum64. + +| input size | purego | asm | +| ---------- | --------- | --------- | +| 4 B | 1.3 GB/s | 1.2 GB/s | +| 16 B | 2.9 GB/s | 3.5 GB/s | +| 100 B | 6.9 GB/s | 8.1 GB/s | +| 4 KB | 11.7 GB/s | 16.7 GB/s | +| 10 MB | 12.0 GB/s | 17.3 GB/s | + +These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C +CPU using the following commands under Go 1.19.2: + +``` +benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') +benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') +``` + +## Projects using this package + +- [InfluxDB](https://github.com/influxdata/influxdb) +- [Prometheus](https://github.com/prometheus/prometheus) +- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) +- [FreeCache](https://github.com/coocood/freecache) +- [FastCache](https://github.com/VictoriaMetrics/fastcache) diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go new file mode 100644 index 000000000..fc40c8200 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go @@ -0,0 +1,230 @@ +// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described +// at http://cyan4973.github.io/xxHash/. +// THIS IS VENDORED: Go to github.com/cespare/xxhash for original package. + +package xxhash + +import ( + "encoding/binary" + "errors" + "math/bits" +) + +const ( + prime1 uint64 = 11400714785074694791 + prime2 uint64 = 14029467366897019727 + prime3 uint64 = 1609587929392839161 + prime4 uint64 = 9650029242287828579 + prime5 uint64 = 2870177450012600261 +) + +// Store the primes in an array as well. +// +// The consts are used when possible in Go code to avoid MOVs but we need a +// contiguous array of the assembly code. +var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5} + +// Digest implements hash.Hash64. +type Digest struct { + v1 uint64 + v2 uint64 + v3 uint64 + v4 uint64 + total uint64 + mem [32]byte + n int // how much of mem is used +} + +// New creates a new Digest that computes the 64-bit xxHash algorithm. +func New() *Digest { + var d Digest + d.Reset() + return &d +} + +// Reset clears the Digest's state so that it can be reused. +func (d *Digest) Reset() { + d.v1 = primes[0] + prime2 + d.v2 = prime2 + d.v3 = 0 + d.v4 = -primes[0] + d.total = 0 + d.n = 0 +} + +// Size always returns 8 bytes. +func (d *Digest) Size() int { return 8 } + +// BlockSize always returns 32 bytes. +func (d *Digest) BlockSize() int { return 32 } + +// Write adds more data to d. It always returns len(b), nil. +func (d *Digest) Write(b []byte) (n int, err error) { + n = len(b) + d.total += uint64(n) + + memleft := d.mem[d.n&(len(d.mem)-1):] + + if d.n+n < 32 { + // This new data doesn't even fill the current block. + copy(memleft, b) + d.n += n + return + } + + if d.n > 0 { + // Finish off the partial block. + c := copy(memleft, b) + d.v1 = round(d.v1, u64(d.mem[0:8])) + d.v2 = round(d.v2, u64(d.mem[8:16])) + d.v3 = round(d.v3, u64(d.mem[16:24])) + d.v4 = round(d.v4, u64(d.mem[24:32])) + b = b[c:] + d.n = 0 + } + + if len(b) >= 32 { + // One or more full blocks left. + nw := writeBlocks(d, b) + b = b[nw:] + } + + // Store any remaining partial block. + copy(d.mem[:], b) + d.n = len(b) + + return +} + +// Sum appends the current hash to b and returns the resulting slice. +func (d *Digest) Sum(b []byte) []byte { + s := d.Sum64() + return append( + b, + byte(s>>56), + byte(s>>48), + byte(s>>40), + byte(s>>32), + byte(s>>24), + byte(s>>16), + byte(s>>8), + byte(s), + ) +} + +// Sum64 returns the current hash. +func (d *Digest) Sum64() uint64 { + var h uint64 + + if d.total >= 32 { + v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 + h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) + h = mergeRound(h, v1) + h = mergeRound(h, v2) + h = mergeRound(h, v3) + h = mergeRound(h, v4) + } else { + h = d.v3 + prime5 + } + + h += d.total + + b := d.mem[:d.n&(len(d.mem)-1)] + for ; len(b) >= 8; b = b[8:] { + k1 := round(0, u64(b[:8])) + h ^= k1 + h = rol27(h)*prime1 + prime4 + } + if len(b) >= 4 { + h ^= uint64(u32(b[:4])) * prime1 + h = rol23(h)*prime2 + prime3 + b = b[4:] + } + for ; len(b) > 0; b = b[1:] { + h ^= uint64(b[0]) * prime5 + h = rol11(h) * prime1 + } + + h ^= h >> 33 + h *= prime2 + h ^= h >> 29 + h *= prime3 + h ^= h >> 32 + + return h +} + +const ( + magic = "xxh\x06" + marshaledSize = len(magic) + 8*5 + 32 +) + +// MarshalBinary implements the encoding.BinaryMarshaler interface. +func (d *Digest) MarshalBinary() ([]byte, error) { + b := make([]byte, 0, marshaledSize) + b = append(b, magic...) + b = appendUint64(b, d.v1) + b = appendUint64(b, d.v2) + b = appendUint64(b, d.v3) + b = appendUint64(b, d.v4) + b = appendUint64(b, d.total) + b = append(b, d.mem[:d.n]...) + b = b[:len(b)+len(d.mem)-d.n] + return b, nil +} + +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +func (d *Digest) UnmarshalBinary(b []byte) error { + if len(b) < len(magic) || string(b[:len(magic)]) != magic { + return errors.New("xxhash: invalid hash state identifier") + } + if len(b) != marshaledSize { + return errors.New("xxhash: invalid hash state size") + } + b = b[len(magic):] + b, d.v1 = consumeUint64(b) + b, d.v2 = consumeUint64(b) + b, d.v3 = consumeUint64(b) + b, d.v4 = consumeUint64(b) + b, d.total = consumeUint64(b) + copy(d.mem[:], b) + d.n = int(d.total % uint64(len(d.mem))) + return nil +} + +func appendUint64(b []byte, x uint64) []byte { + var a [8]byte + binary.LittleEndian.PutUint64(a[:], x) + return append(b, a[:]...) +} + +func consumeUint64(b []byte) ([]byte, uint64) { + x := u64(b) + return b[8:], x +} + +func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } +func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } + +func round(acc, input uint64) uint64 { + acc += input * prime2 + acc = rol31(acc) + acc *= prime1 + return acc +} + +func mergeRound(acc, val uint64) uint64 { + val = round(0, val) + acc ^= val + acc = acc*prime1 + prime4 + return acc +} + +func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } +func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } +func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } +func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } +func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } +func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } +func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } +func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s new file mode 100644 index 000000000..ddb63aa91 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s @@ -0,0 +1,210 @@ +//go:build !appengine && gc && !purego && !noasm +// +build !appengine +// +build gc +// +build !purego +// +build !noasm + +#include "textflag.h" + +// Registers: +#define h AX +#define d AX +#define p SI // pointer to advance through b +#define n DX +#define end BX // loop end +#define v1 R8 +#define v2 R9 +#define v3 R10 +#define v4 R11 +#define x R12 +#define prime1 R13 +#define prime2 R14 +#define prime4 DI + +#define round(acc, x) \ + IMULQ prime2, x \ + ADDQ x, acc \ + ROLQ $31, acc \ + IMULQ prime1, acc + +// round0 performs the operation x = round(0, x). +#define round0(x) \ + IMULQ prime2, x \ + ROLQ $31, x \ + IMULQ prime1, x + +// mergeRound applies a merge round on the two registers acc and x. +// It assumes that prime1, prime2, and prime4 have been loaded. +#define mergeRound(acc, x) \ + round0(x) \ + XORQ x, acc \ + IMULQ prime1, acc \ + ADDQ prime4, acc + +// blockLoop processes as many 32-byte blocks as possible, +// updating v1, v2, v3, and v4. It assumes that there is at least one block +// to process. +#define blockLoop() \ +loop: \ + MOVQ +0(p), x \ + round(v1, x) \ + MOVQ +8(p), x \ + round(v2, x) \ + MOVQ +16(p), x \ + round(v3, x) \ + MOVQ +24(p), x \ + round(v4, x) \ + ADDQ $32, p \ + CMPQ p, end \ + JLE loop + +// func Sum64(b []byte) uint64 +TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 + // Load fixed primes. + MOVQ ·primes+0(SB), prime1 + MOVQ ·primes+8(SB), prime2 + MOVQ ·primes+24(SB), prime4 + + // Load slice. + MOVQ b_base+0(FP), p + MOVQ b_len+8(FP), n + LEAQ (p)(n*1), end + + // The first loop limit will be len(b)-32. + SUBQ $32, end + + // Check whether we have at least one block. + CMPQ n, $32 + JLT noBlocks + + // Set up initial state (v1, v2, v3, v4). + MOVQ prime1, v1 + ADDQ prime2, v1 + MOVQ prime2, v2 + XORQ v3, v3 + XORQ v4, v4 + SUBQ prime1, v4 + + blockLoop() + + MOVQ v1, h + ROLQ $1, h + MOVQ v2, x + ROLQ $7, x + ADDQ x, h + MOVQ v3, x + ROLQ $12, x + ADDQ x, h + MOVQ v4, x + ROLQ $18, x + ADDQ x, h + + mergeRound(h, v1) + mergeRound(h, v2) + mergeRound(h, v3) + mergeRound(h, v4) + + JMP afterBlocks + +noBlocks: + MOVQ ·primes+32(SB), h + +afterBlocks: + ADDQ n, h + + ADDQ $24, end + CMPQ p, end + JG try4 + +loop8: + MOVQ (p), x + ADDQ $8, p + round0(x) + XORQ x, h + ROLQ $27, h + IMULQ prime1, h + ADDQ prime4, h + + CMPQ p, end + JLE loop8 + +try4: + ADDQ $4, end + CMPQ p, end + JG try1 + + MOVL (p), x + ADDQ $4, p + IMULQ prime1, x + XORQ x, h + + ROLQ $23, h + IMULQ prime2, h + ADDQ ·primes+16(SB), h + +try1: + ADDQ $4, end + CMPQ p, end + JGE finalize + +loop1: + MOVBQZX (p), x + ADDQ $1, p + IMULQ ·primes+32(SB), x + XORQ x, h + ROLQ $11, h + IMULQ prime1, h + + CMPQ p, end + JL loop1 + +finalize: + MOVQ h, x + SHRQ $33, x + XORQ x, h + IMULQ prime2, h + MOVQ h, x + SHRQ $29, x + XORQ x, h + IMULQ ·primes+16(SB), h + MOVQ h, x + SHRQ $32, x + XORQ x, h + + MOVQ h, ret+24(FP) + RET + +// func writeBlocks(d *Digest, b []byte) int +TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 + // Load fixed primes needed for round. + MOVQ ·primes+0(SB), prime1 + MOVQ ·primes+8(SB), prime2 + + // Load slice. + MOVQ b_base+8(FP), p + MOVQ b_len+16(FP), n + LEAQ (p)(n*1), end + SUBQ $32, end + + // Load vN from d. + MOVQ s+0(FP), d + MOVQ 0(d), v1 + MOVQ 8(d), v2 + MOVQ 16(d), v3 + MOVQ 24(d), v4 + + // We don't need to check the loop condition here; this function is + // always called with at least one block of data to process. + blockLoop() + + // Copy vN back to d. + MOVQ v1, 0(d) + MOVQ v2, 8(d) + MOVQ v3, 16(d) + MOVQ v4, 24(d) + + // The number of bytes written is p minus the old base pointer. + SUBQ b_base+8(FP), p + MOVQ p, ret+32(FP) + + RET diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s new file mode 100644 index 000000000..17901e080 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s @@ -0,0 +1,184 @@ +//go:build !appengine && gc && !purego && !noasm +// +build !appengine +// +build gc +// +build !purego +// +build !noasm + +#include "textflag.h" + +// Registers: +#define digest R1 +#define h R2 // return value +#define p R3 // input pointer +#define n R4 // input length +#define nblocks R5 // n / 32 +#define prime1 R7 +#define prime2 R8 +#define prime3 R9 +#define prime4 R10 +#define prime5 R11 +#define v1 R12 +#define v2 R13 +#define v3 R14 +#define v4 R15 +#define x1 R20 +#define x2 R21 +#define x3 R22 +#define x4 R23 + +#define round(acc, x) \ + MADD prime2, acc, x, acc \ + ROR $64-31, acc \ + MUL prime1, acc + +// round0 performs the operation x = round(0, x). +#define round0(x) \ + MUL prime2, x \ + ROR $64-31, x \ + MUL prime1, x + +#define mergeRound(acc, x) \ + round0(x) \ + EOR x, acc \ + MADD acc, prime4, prime1, acc + +// blockLoop processes as many 32-byte blocks as possible, +// updating v1, v2, v3, and v4. It assumes that n >= 32. +#define blockLoop() \ + LSR $5, n, nblocks \ + PCALIGN $16 \ + loop: \ + LDP.P 16(p), (x1, x2) \ + LDP.P 16(p), (x3, x4) \ + round(v1, x1) \ + round(v2, x2) \ + round(v3, x3) \ + round(v4, x4) \ + SUB $1, nblocks \ + CBNZ nblocks, loop + +// func Sum64(b []byte) uint64 +TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 + LDP b_base+0(FP), (p, n) + + LDP ·primes+0(SB), (prime1, prime2) + LDP ·primes+16(SB), (prime3, prime4) + MOVD ·primes+32(SB), prime5 + + CMP $32, n + CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 } + BLT afterLoop + + ADD prime1, prime2, v1 + MOVD prime2, v2 + MOVD $0, v3 + NEG prime1, v4 + + blockLoop() + + ROR $64-1, v1, x1 + ROR $64-7, v2, x2 + ADD x1, x2 + ROR $64-12, v3, x3 + ROR $64-18, v4, x4 + ADD x3, x4 + ADD x2, x4, h + + mergeRound(h, v1) + mergeRound(h, v2) + mergeRound(h, v3) + mergeRound(h, v4) + +afterLoop: + ADD n, h + + TBZ $4, n, try8 + LDP.P 16(p), (x1, x2) + + round0(x1) + + // NOTE: here and below, sequencing the EOR after the ROR (using a + // rotated register) is worth a small but measurable speedup for small + // inputs. + ROR $64-27, h + EOR x1 @> 64-27, h, h + MADD h, prime4, prime1, h + + round0(x2) + ROR $64-27, h + EOR x2 @> 64-27, h, h + MADD h, prime4, prime1, h + +try8: + TBZ $3, n, try4 + MOVD.P 8(p), x1 + + round0(x1) + ROR $64-27, h + EOR x1 @> 64-27, h, h + MADD h, prime4, prime1, h + +try4: + TBZ $2, n, try2 + MOVWU.P 4(p), x2 + + MUL prime1, x2 + ROR $64-23, h + EOR x2 @> 64-23, h, h + MADD h, prime3, prime2, h + +try2: + TBZ $1, n, try1 + MOVHU.P 2(p), x3 + AND $255, x3, x1 + LSR $8, x3, x2 + + MUL prime5, x1 + ROR $64-11, h + EOR x1 @> 64-11, h, h + MUL prime1, h + + MUL prime5, x2 + ROR $64-11, h + EOR x2 @> 64-11, h, h + MUL prime1, h + +try1: + TBZ $0, n, finalize + MOVBU (p), x4 + + MUL prime5, x4 + ROR $64-11, h + EOR x4 @> 64-11, h, h + MUL prime1, h + +finalize: + EOR h >> 33, h + MUL prime2, h + EOR h >> 29, h + MUL prime3, h + EOR h >> 32, h + + MOVD h, ret+24(FP) + RET + +// func writeBlocks(d *Digest, b []byte) int +TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 + LDP ·primes+0(SB), (prime1, prime2) + + // Load state. Assume v[1-4] are stored contiguously. + MOVD d+0(FP), digest + LDP 0(digest), (v1, v2) + LDP 16(digest), (v3, v4) + + LDP b_base+8(FP), (p, n) + + blockLoop() + + // Store updated state. + STP (v1, v2), 0(digest) + STP (v3, v4), 16(digest) + + BIC $31, n + MOVD n, ret+32(FP) + RET diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go new file mode 100644 index 000000000..d4221edf4 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go @@ -0,0 +1,16 @@ +//go:build (amd64 || arm64) && !appengine && gc && !purego && !noasm +// +build amd64 arm64 +// +build !appengine +// +build gc +// +build !purego +// +build !noasm + +package xxhash + +// Sum64 computes the 64-bit xxHash digest of b. +// +//go:noescape +func Sum64(b []byte) uint64 + +//go:noescape +func writeBlocks(s *Digest, b []byte) int diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go new file mode 100644 index 000000000..0be16cefc --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go @@ -0,0 +1,76 @@ +//go:build (!amd64 && !arm64) || appengine || !gc || purego || noasm +// +build !amd64,!arm64 appengine !gc purego noasm + +package xxhash + +// Sum64 computes the 64-bit xxHash digest of b. +func Sum64(b []byte) uint64 { + // A simpler version would be + // d := New() + // d.Write(b) + // return d.Sum64() + // but this is faster, particularly for small inputs. + + n := len(b) + var h uint64 + + if n >= 32 { + v1 := primes[0] + prime2 + v2 := prime2 + v3 := uint64(0) + v4 := -primes[0] + for len(b) >= 32 { + v1 = round(v1, u64(b[0:8:len(b)])) + v2 = round(v2, u64(b[8:16:len(b)])) + v3 = round(v3, u64(b[16:24:len(b)])) + v4 = round(v4, u64(b[24:32:len(b)])) + b = b[32:len(b):len(b)] + } + h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) + h = mergeRound(h, v1) + h = mergeRound(h, v2) + h = mergeRound(h, v3) + h = mergeRound(h, v4) + } else { + h = prime5 + } + + h += uint64(n) + + for ; len(b) >= 8; b = b[8:] { + k1 := round(0, u64(b[:8])) + h ^= k1 + h = rol27(h)*prime1 + prime4 + } + if len(b) >= 4 { + h ^= uint64(u32(b[:4])) * prime1 + h = rol23(h)*prime2 + prime3 + b = b[4:] + } + for ; len(b) > 0; b = b[1:] { + h ^= uint64(b[0]) * prime5 + h = rol11(h) * prime1 + } + + h ^= h >> 33 + h *= prime2 + h ^= h >> 29 + h *= prime3 + h ^= h >> 32 + + return h +} + +func writeBlocks(d *Digest, b []byte) int { + v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 + n := len(b) + for len(b) >= 32 { + v1 = round(v1, u64(b[0:8:len(b)])) + v2 = round(v2, u64(b[8:16:len(b)])) + v3 = round(v3, u64(b[16:24:len(b)])) + v4 = round(v4, u64(b[24:32:len(b)])) + b = b[32:len(b):len(b)] + } + d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4 + return n - len(b) +} diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go new file mode 100644 index 000000000..6f3b0cb10 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go @@ -0,0 +1,11 @@ +package xxhash + +// Sum64String computes the 64-bit xxHash digest of s. +func Sum64String(s string) uint64 { + return Sum64([]byte(s)) +} + +// WriteString adds more data to d. It always returns len(s), nil. +func (d *Digest) WriteString(s string) (n int, err error) { + return d.Write([]byte(s)) +} diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go new file mode 100644 index 000000000..f41932b7a --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go @@ -0,0 +1,16 @@ +//go:build amd64 && !appengine && !noasm && gc +// +build amd64,!appengine,!noasm,gc + +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. + +package zstd + +// matchLen returns how many bytes match in a and b +// +// It assumes that: +// +// len(a) <= len(b) and len(a) > 0 +// +//go:noescape +func matchLen(a []byte, b []byte) int diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s new file mode 100644 index 000000000..9a7655c0f --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s @@ -0,0 +1,68 @@ +// Copied from S2 implementation. + +//go:build !appengine && !noasm && gc && !noasm + +#include "textflag.h" + +// func matchLen(a []byte, b []byte) int +// Requires: BMI +TEXT ·matchLen(SB), NOSPLIT, $0-56 + MOVQ a_base+0(FP), AX + MOVQ b_base+24(FP), CX + MOVQ a_len+8(FP), DX + + // matchLen + XORL SI, SI + CMPL DX, $0x08 + JB matchlen_match4_standalone + +matchlen_loopback_standalone: + MOVQ (AX)(SI*1), BX + XORQ (CX)(SI*1), BX + TESTQ BX, BX + JZ matchlen_loop_standalone + +#ifdef GOAMD64_v3 + TZCNTQ BX, BX +#else + BSFQ BX, BX +#endif + SARQ $0x03, BX + LEAL (SI)(BX*1), SI + JMP gen_match_len_end + +matchlen_loop_standalone: + LEAL -8(DX), DX + LEAL 8(SI), SI + CMPL DX, $0x08 + JAE matchlen_loopback_standalone + +matchlen_match4_standalone: + CMPL DX, $0x04 + JB matchlen_match2_standalone + MOVL (AX)(SI*1), BX + CMPL (CX)(SI*1), BX + JNE matchlen_match2_standalone + LEAL -4(DX), DX + LEAL 4(SI), SI + +matchlen_match2_standalone: + CMPL DX, $0x02 + JB matchlen_match1_standalone + MOVW (AX)(SI*1), BX + CMPW (CX)(SI*1), BX + JNE matchlen_match1_standalone + LEAL -2(DX), DX + LEAL 2(SI), SI + +matchlen_match1_standalone: + CMPL DX, $0x01 + JB gen_match_len_end + MOVB (AX)(SI*1), BL + CMPB (CX)(SI*1), BL + JNE gen_match_len_end + INCL SI + +gen_match_len_end: + MOVQ SI, ret+48(FP) + RET diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go b/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go new file mode 100644 index 000000000..57b9c31c0 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go @@ -0,0 +1,33 @@ +//go:build !amd64 || appengine || !gc || noasm +// +build !amd64 appengine !gc noasm + +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. + +package zstd + +import ( + "encoding/binary" + "math/bits" +) + +// matchLen returns the maximum common prefix length of a and b. +// a must be the shortest of the two. +func matchLen(a, b []byte) (n int) { + for ; len(a) >= 8 && len(b) >= 8; a, b = a[8:], b[8:] { + diff := binary.LittleEndian.Uint64(a) ^ binary.LittleEndian.Uint64(b) + if diff != 0 { + return n + bits.TrailingZeros64(diff)>>3 + } + n += 8 + } + + for i := range a { + if a[i] != b[i] { + break + } + n++ + } + return n + +} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go new file mode 100644 index 000000000..d7fe6d82d --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/seqdec.go @@ -0,0 +1,503 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "errors" + "fmt" + "io" +) + +type seq struct { + litLen uint32 + matchLen uint32 + offset uint32 + + // Codes are stored here for the encoder + // so they only have to be looked up once. + llCode, mlCode, ofCode uint8 +} + +type seqVals struct { + ll, ml, mo int +} + +func (s seq) String() string { + if s.offset <= 3 { + if s.offset == 0 { + return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset: INVALID (0)") + } + return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset, " (repeat)") + } + return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset-3, " (new)") +} + +type seqCompMode uint8 + +const ( + compModePredefined seqCompMode = iota + compModeRLE + compModeFSE + compModeRepeat +) + +type sequenceDec struct { + // decoder keeps track of the current state and updates it from the bitstream. + fse *fseDecoder + state fseState + repeat bool +} + +// init the state of the decoder with input from stream. +func (s *sequenceDec) init(br *bitReader) error { + if s.fse == nil { + return errors.New("sequence decoder not defined") + } + s.state.init(br, s.fse.actualTableLog, s.fse.dt[:1< cap(s.out) { + addBytes := s.seqSize + len(s.out) + s.out = append(s.out, make([]byte, addBytes)...) + s.out = s.out[:len(s.out)-addBytes] + } + + if debugDecoder { + printf("Execute %d seqs with hist %d, dict %d, literals: %d into %d bytes\n", len(seqs), len(hist), len(s.dict), len(s.literals), s.seqSize) + } + + var t = len(s.out) + out := s.out[:t+s.seqSize] + + for _, seq := range seqs { + // Add literals + copy(out[t:], s.literals[:seq.ll]) + t += seq.ll + s.literals = s.literals[seq.ll:] + + // Copy from dictionary... + if seq.mo > t+len(hist) || seq.mo > s.windowSize { + if len(s.dict) == 0 { + return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) + } + + // we may be in dictionary. + dictO := len(s.dict) - (seq.mo - (t + len(hist))) + if dictO < 0 || dictO >= len(s.dict) { + return fmt.Errorf("match offset (%d) bigger than current history+dict (%d)", seq.mo, t+len(hist)+len(s.dict)) + } + end := dictO + seq.ml + if end > len(s.dict) { + n := len(s.dict) - dictO + copy(out[t:], s.dict[dictO:]) + t += n + seq.ml -= n + } else { + copy(out[t:], s.dict[dictO:end]) + t += end - dictO + continue + } + } + + // Copy from history. + if v := seq.mo - t; v > 0 { + // v is the start position in history from end. + start := len(hist) - v + if seq.ml > v { + // Some goes into current block. + // Copy remainder of history + copy(out[t:], hist[start:]) + t += v + seq.ml -= v + } else { + copy(out[t:], hist[start:start+seq.ml]) + t += seq.ml + continue + } + } + // We must be in current buffer now + if seq.ml > 0 { + start := t - seq.mo + if seq.ml <= t-start { + // No overlap + copy(out[t:], out[start:start+seq.ml]) + t += seq.ml + continue + } else { + // Overlapping copy + // Extend destination slice and copy one byte at the time. + src := out[start : start+seq.ml] + dst := out[t:] + dst = dst[:len(src)] + t += len(src) + // Destination is the space we just added. + for i := range src { + dst[i] = src[i] + } + } + } + } + + // Add final literals + copy(out[t:], s.literals) + if debugDecoder { + t += len(s.literals) + if t != len(out) { + panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) + } + } + s.out = out + + return nil +} + +// decode sequences from the stream with the provided history. +func (s *sequenceDecs) decodeSync(hist []byte) error { + supported, err := s.decodeSyncSimple(hist) + if supported { + return err + } + + br := s.br + seqs := s.nSeqs + startSize := len(s.out) + // Grab full sizes tables, to avoid bounds checks. + llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] + llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state + out := s.out + maxBlockSize := maxCompressedBlockSize + if s.windowSize < maxBlockSize { + maxBlockSize = s.windowSize + } + + if debugDecoder { + println("decodeSync: decoding", seqs, "sequences", br.remain(), "bits remain on stream") + } + for i := seqs - 1; i >= 0; i-- { + if br.overread() { + printf("reading sequence %d, exceeded available data. Overread by %d\n", seqs-i, -br.remain()) + return io.ErrUnexpectedEOF + } + var ll, mo, ml int + if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { + // inlined function: + // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) + + // Final will not read from stream. + var llB, mlB, moB uint8 + ll, llB = llState.final() + ml, mlB = mlState.final() + mo, moB = ofState.final() + + // extra bits are stored in reverse order. + br.fillFast() + mo += br.getBits(moB) + if s.maxBits > 32 { + br.fillFast() + } + ml += br.getBits(mlB) + ll += br.getBits(llB) + + if moB > 1 { + s.prevOffset[2] = s.prevOffset[1] + s.prevOffset[1] = s.prevOffset[0] + s.prevOffset[0] = mo + } else { + // mo = s.adjustOffset(mo, ll, moB) + // Inlined for rather big speedup + if ll == 0 { + // There is an exception though, when current sequence's literals_length = 0. + // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, + // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. + mo++ + } + + if mo == 0 { + mo = s.prevOffset[0] + } else { + var temp int + if mo == 3 { + temp = s.prevOffset[0] - 1 + } else { + temp = s.prevOffset[mo] + } + + if temp == 0 { + // 0 is not valid; input is corrupted; force offset to 1 + println("WARNING: temp was 0") + temp = 1 + } + + if mo != 1 { + s.prevOffset[2] = s.prevOffset[1] + } + s.prevOffset[1] = s.prevOffset[0] + s.prevOffset[0] = temp + mo = temp + } + } + br.fillFast() + } else { + ll, mo, ml = s.next(br, llState, mlState, ofState) + br.fill() + } + + if debugSequences { + println("Seq", seqs-i-1, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) + } + + if ll > len(s.literals) { + return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, len(s.literals)) + } + size := ll + ml + len(out) + if size-startSize > maxBlockSize { + return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) + } + if size > cap(out) { + // Not enough size, which can happen under high volume block streaming conditions + // but could be if destination slice is too small for sync operations. + // over-allocating here can create a large amount of GC pressure so we try to keep + // it as contained as possible + used := len(out) - startSize + addBytes := 256 + ll + ml + used>>2 + // Clamp to max block size. + if used+addBytes > maxBlockSize { + addBytes = maxBlockSize - used + } + out = append(out, make([]byte, addBytes)...) + out = out[:len(out)-addBytes] + } + if ml > maxMatchLen { + return fmt.Errorf("match len (%d) bigger than max allowed length", ml) + } + + // Add literals + out = append(out, s.literals[:ll]...) + s.literals = s.literals[ll:] + + if mo == 0 && ml > 0 { + return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) + } + + if mo > len(out)+len(hist) || mo > s.windowSize { + if len(s.dict) == 0 { + return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) + } + + // we may be in dictionary. + dictO := len(s.dict) - (mo - (len(out) + len(hist))) + if dictO < 0 || dictO >= len(s.dict) { + return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) + } + end := dictO + ml + if end > len(s.dict) { + out = append(out, s.dict[dictO:]...) + ml -= len(s.dict) - dictO + } else { + out = append(out, s.dict[dictO:end]...) + mo = 0 + ml = 0 + } + } + + // Copy from history. + // TODO: Blocks without history could be made to ignore this completely. + if v := mo - len(out); v > 0 { + // v is the start position in history from end. + start := len(hist) - v + if ml > v { + // Some goes into current block. + // Copy remainder of history + out = append(out, hist[start:]...) + ml -= v + } else { + out = append(out, hist[start:start+ml]...) + ml = 0 + } + } + // We must be in current buffer now + if ml > 0 { + start := len(out) - mo + if ml <= len(out)-start { + // No overlap + out = append(out, out[start:start+ml]...) + } else { + // Overlapping copy + // Extend destination slice and copy one byte at the time. + out = out[:len(out)+ml] + src := out[start : start+ml] + // Destination is the space we just added. + dst := out[len(out)-ml:] + dst = dst[:len(src)] + for i := range src { + dst[i] = src[i] + } + } + } + if i == 0 { + // This is the last sequence, so we shouldn't update state. + break + } + + // Manually inlined, ~ 5-20% faster + // Update all 3 states at once. Approx 20% faster. + nBits := llState.nbBits() + mlState.nbBits() + ofState.nbBits() + if nBits == 0 { + llState = llTable[llState.newState()&maxTableMask] + mlState = mlTable[mlState.newState()&maxTableMask] + ofState = ofTable[ofState.newState()&maxTableMask] + } else { + bits := br.get32BitsFast(nBits) + + lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) + llState = llTable[(llState.newState()+lowBits)&maxTableMask] + + lowBits = uint16(bits >> (ofState.nbBits() & 31)) + lowBits &= bitMask[mlState.nbBits()&15] + mlState = mlTable[(mlState.newState()+lowBits)&maxTableMask] + + lowBits = uint16(bits) & bitMask[ofState.nbBits()&15] + ofState = ofTable[(ofState.newState()+lowBits)&maxTableMask] + } + } + + if size := len(s.literals) + len(out) - startSize; size > maxBlockSize { + return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) + } + + // Add final literals + s.out = append(out, s.literals...) + return br.close() +} + +var bitMask [16]uint16 + +func init() { + for i := range bitMask[:] { + bitMask[i] = uint16((1 << uint(i)) - 1) + } +} + +func (s *sequenceDecs) next(br *bitReader, llState, mlState, ofState decSymbol) (ll, mo, ml int) { + // Final will not read from stream. + ll, llB := llState.final() + ml, mlB := mlState.final() + mo, moB := ofState.final() + + // extra bits are stored in reverse order. + br.fill() + mo += br.getBits(moB) + if s.maxBits > 32 { + br.fill() + } + // matchlength+literal length, max 32 bits + ml += br.getBits(mlB) + ll += br.getBits(llB) + mo = s.adjustOffset(mo, ll, moB) + return +} + +func (s *sequenceDecs) adjustOffset(offset, litLen int, offsetB uint8) int { + if offsetB > 1 { + s.prevOffset[2] = s.prevOffset[1] + s.prevOffset[1] = s.prevOffset[0] + s.prevOffset[0] = offset + return offset + } + + if litLen == 0 { + // There is an exception though, when current sequence's literals_length = 0. + // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, + // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. + offset++ + } + + if offset == 0 { + return s.prevOffset[0] + } + var temp int + if offset == 3 { + temp = s.prevOffset[0] - 1 + } else { + temp = s.prevOffset[offset] + } + + if temp == 0 { + // 0 is not valid; input is corrupted; force offset to 1 + println("temp was 0") + temp = 1 + } + + if offset != 1 { + s.prevOffset[2] = s.prevOffset[1] + } + s.prevOffset[1] = s.prevOffset[0] + s.prevOffset[0] = temp + return temp +} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go new file mode 100644 index 000000000..8adabd828 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go @@ -0,0 +1,394 @@ +//go:build amd64 && !appengine && !noasm && gc +// +build amd64,!appengine,!noasm,gc + +package zstd + +import ( + "fmt" + "io" + + "github.com/klauspost/compress/internal/cpuinfo" +) + +type decodeSyncAsmContext struct { + llTable []decSymbol + mlTable []decSymbol + ofTable []decSymbol + llState uint64 + mlState uint64 + ofState uint64 + iteration int + litRemain int + out []byte + outPosition int + literals []byte + litPosition int + history []byte + windowSize int + ll int // set on error (not for all errors, please refer to _generate/gen.go) + ml int // set on error (not for all errors, please refer to _generate/gen.go) + mo int // set on error (not for all errors, please refer to _generate/gen.go) +} + +// sequenceDecs_decodeSync_amd64 implements the main loop of sequenceDecs.decodeSync in x86 asm. +// +// Please refer to seqdec_generic.go for the reference implementation. +// +//go:noescape +func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int + +// sequenceDecs_decodeSync_bmi2 implements the main loop of sequenceDecs.decodeSync in x86 asm with BMI2 extensions. +// +//go:noescape +func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int + +// sequenceDecs_decodeSync_safe_amd64 does the same as above, but does not write more than output buffer. +// +//go:noescape +func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int + +// sequenceDecs_decodeSync_safe_bmi2 does the same as above, but does not write more than output buffer. +// +//go:noescape +func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int + +// decode sequences from the stream with the provided history but without a dictionary. +func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { + if len(s.dict) > 0 { + return false, nil + } + if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize { + return false, nil + } + + // FIXME: Using unsafe memory copies leads to rare, random crashes + // with fuzz testing. It is therefore disabled for now. + const useSafe = true + /* + useSafe := false + if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc { + useSafe = true + } + if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) { + useSafe = true + } + if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { + useSafe = true + } + */ + + br := s.br + + maxBlockSize := maxCompressedBlockSize + if s.windowSize < maxBlockSize { + maxBlockSize = s.windowSize + } + + ctx := decodeSyncAsmContext{ + llTable: s.litLengths.fse.dt[:maxTablesize], + mlTable: s.matchLengths.fse.dt[:maxTablesize], + ofTable: s.offsets.fse.dt[:maxTablesize], + llState: uint64(s.litLengths.state.state), + mlState: uint64(s.matchLengths.state.state), + ofState: uint64(s.offsets.state.state), + iteration: s.nSeqs - 1, + litRemain: len(s.literals), + out: s.out, + outPosition: len(s.out), + literals: s.literals, + windowSize: s.windowSize, + history: hist, + } + + s.seqSize = 0 + startSize := len(s.out) + + var errCode int + if cpuinfo.HasBMI2() { + if useSafe { + errCode = sequenceDecs_decodeSync_safe_bmi2(s, br, &ctx) + } else { + errCode = sequenceDecs_decodeSync_bmi2(s, br, &ctx) + } + } else { + if useSafe { + errCode = sequenceDecs_decodeSync_safe_amd64(s, br, &ctx) + } else { + errCode = sequenceDecs_decodeSync_amd64(s, br, &ctx) + } + } + switch errCode { + case noError: + break + + case errorMatchLenOfsMismatch: + return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ctx.ml) + + case errorMatchLenTooBig: + return true, fmt.Errorf("match len (%d) bigger than max allowed length", ctx.ml) + + case errorMatchOffTooBig: + return true, fmt.Errorf("match offset (%d) bigger than current history (%d)", + ctx.mo, ctx.outPosition+len(hist)-startSize) + + case errorNotEnoughLiterals: + return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", + ctx.ll, ctx.litRemain+ctx.ll) + + case errorOverread: + return true, io.ErrUnexpectedEOF + + case errorNotEnoughSpace: + size := ctx.outPosition + ctx.ll + ctx.ml + if debugDecoder { + println("msl:", s.maxSyncLen, "cap", cap(s.out), "bef:", startSize, "sz:", size-startSize, "mbs:", maxBlockSize, "outsz:", cap(s.out)-startSize) + } + return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) + + default: + return true, fmt.Errorf("sequenceDecs_decode returned erronous code %d", errCode) + } + + s.seqSize += ctx.litRemain + if s.seqSize > maxBlockSize { + return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) + } + err := br.close() + if err != nil { + printf("Closing sequences: %v, %+v\n", err, *br) + return true, err + } + + s.literals = s.literals[ctx.litPosition:] + t := ctx.outPosition + s.out = s.out[:t] + + // Add final literals + s.out = append(s.out, s.literals...) + if debugDecoder { + t += len(s.literals) + if t != len(s.out) { + panic(fmt.Errorf("length mismatch, want %d, got %d", len(s.out), t)) + } + } + + return true, nil +} + +// -------------------------------------------------------------------------------- + +type decodeAsmContext struct { + llTable []decSymbol + mlTable []decSymbol + ofTable []decSymbol + llState uint64 + mlState uint64 + ofState uint64 + iteration int + seqs []seqVals + litRemain int +} + +const noError = 0 + +// error reported when mo == 0 && ml > 0 +const errorMatchLenOfsMismatch = 1 + +// error reported when ml > maxMatchLen +const errorMatchLenTooBig = 2 + +// error reported when mo > available history or mo > s.windowSize +const errorMatchOffTooBig = 3 + +// error reported when the sum of literal lengths exeeceds the literal buffer size +const errorNotEnoughLiterals = 4 + +// error reported when capacity of `out` is too small +const errorNotEnoughSpace = 5 + +// error reported when bits are overread. +const errorOverread = 6 + +// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm. +// +// Please refer to seqdec_generic.go for the reference implementation. +// +//go:noescape +func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int + +// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm. +// +// Please refer to seqdec_generic.go for the reference implementation. +// +//go:noescape +func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int + +// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions. +// +//go:noescape +func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int + +// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions. +// +//go:noescape +func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int + +// decode sequences from the stream without the provided history. +func (s *sequenceDecs) decode(seqs []seqVals) error { + br := s.br + + maxBlockSize := maxCompressedBlockSize + if s.windowSize < maxBlockSize { + maxBlockSize = s.windowSize + } + + ctx := decodeAsmContext{ + llTable: s.litLengths.fse.dt[:maxTablesize], + mlTable: s.matchLengths.fse.dt[:maxTablesize], + ofTable: s.offsets.fse.dt[:maxTablesize], + llState: uint64(s.litLengths.state.state), + mlState: uint64(s.matchLengths.state.state), + ofState: uint64(s.offsets.state.state), + seqs: seqs, + iteration: len(seqs) - 1, + litRemain: len(s.literals), + } + + if debugDecoder { + println("decode: decoding", len(seqs), "sequences", br.remain(), "bits remain on stream") + } + + s.seqSize = 0 + lte56bits := s.maxBits+s.offsets.fse.actualTableLog+s.matchLengths.fse.actualTableLog+s.litLengths.fse.actualTableLog <= 56 + var errCode int + if cpuinfo.HasBMI2() { + if lte56bits { + errCode = sequenceDecs_decode_56_bmi2(s, br, &ctx) + } else { + errCode = sequenceDecs_decode_bmi2(s, br, &ctx) + } + } else { + if lte56bits { + errCode = sequenceDecs_decode_56_amd64(s, br, &ctx) + } else { + errCode = sequenceDecs_decode_amd64(s, br, &ctx) + } + } + if errCode != 0 { + i := len(seqs) - ctx.iteration - 1 + switch errCode { + case errorMatchLenOfsMismatch: + ml := ctx.seqs[i].ml + return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) + + case errorMatchLenTooBig: + ml := ctx.seqs[i].ml + return fmt.Errorf("match len (%d) bigger than max allowed length", ml) + + case errorNotEnoughLiterals: + ll := ctx.seqs[i].ll + return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, ctx.litRemain+ll) + case errorOverread: + return io.ErrUnexpectedEOF + } + + return fmt.Errorf("sequenceDecs_decode_amd64 returned erronous code %d", errCode) + } + + if ctx.litRemain < 0 { + return fmt.Errorf("literal count is too big: total available %d, total requested %d", + len(s.literals), len(s.literals)-ctx.litRemain) + } + + s.seqSize += ctx.litRemain + if s.seqSize > maxBlockSize { + return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) + } + if debugDecoder { + println("decode: ", br.remain(), "bits remain on stream. code:", errCode) + } + err := br.close() + if err != nil { + printf("Closing sequences: %v, %+v\n", err, *br) + } + return err +} + +// -------------------------------------------------------------------------------- + +type executeAsmContext struct { + seqs []seqVals + seqIndex int + out []byte + history []byte + literals []byte + outPosition int + litPosition int + windowSize int +} + +// sequenceDecs_executeSimple_amd64 implements the main loop of sequenceDecs.executeSimple in x86 asm. +// +// Returns false if a match offset is too big. +// +// Please refer to seqdec_generic.go for the reference implementation. +// +//go:noescape +func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool + +// Same as above, but with safe memcopies +// +//go:noescape +func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool + +// executeSimple handles cases when dictionary is not used. +func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { + // Ensure we have enough output size... + if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) { + addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc + s.out = append(s.out, make([]byte, addBytes)...) + s.out = s.out[:len(s.out)-addBytes] + } + + if debugDecoder { + printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize) + } + + var t = len(s.out) + out := s.out[:t+s.seqSize] + + ctx := executeAsmContext{ + seqs: seqs, + seqIndex: 0, + out: out, + history: hist, + outPosition: t, + litPosition: 0, + literals: s.literals, + windowSize: s.windowSize, + } + var ok bool + if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { + ok = sequenceDecs_executeSimple_safe_amd64(&ctx) + } else { + ok = sequenceDecs_executeSimple_amd64(&ctx) + } + if !ok { + return fmt.Errorf("match offset (%d) bigger than current history (%d)", + seqs[ctx.seqIndex].mo, ctx.outPosition+len(hist)) + } + s.literals = s.literals[ctx.litPosition:] + t = ctx.outPosition + + // Add final literals + copy(out[t:], s.literals) + if debugDecoder { + t += len(s.literals) + if t != len(out) { + panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) + } + } + s.out = out + + return nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s new file mode 100644 index 000000000..974b99725 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s @@ -0,0 +1,4175 @@ +// Code generated by command: go run gen.go -out ../seqdec_amd64.s -pkg=zstd. DO NOT EDIT. + +//go:build !appengine && !noasm && gc && !noasm + +// func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int +// Requires: CMOV +TEXT ·sequenceDecs_decode_amd64(SB), $8-32 + MOVQ br+8(FP), CX + MOVQ 24(CX), DX + MOVBQZX 32(CX), BX + MOVQ (CX), AX + MOVQ 8(CX), SI + ADDQ SI, AX + MOVQ AX, (SP) + MOVQ ctx+16(FP), AX + MOVQ 72(AX), DI + MOVQ 80(AX), R8 + MOVQ 88(AX), R9 + MOVQ 104(AX), R10 + MOVQ s+0(FP), AX + MOVQ 144(AX), R11 + MOVQ 152(AX), R12 + MOVQ 160(AX), R13 + +sequenceDecs_decode_amd64_main_loop: + MOVQ (SP), R14 + + // Fill bitreader to have enough for the offset and match length. + CMPQ SI, $0x08 + JL sequenceDecs_decode_amd64_fill_byte_by_byte + MOVQ BX, AX + SHRQ $0x03, AX + SUBQ AX, R14 + MOVQ (R14), DX + SUBQ AX, SI + ANDQ $0x07, BX + JMP sequenceDecs_decode_amd64_fill_end + +sequenceDecs_decode_amd64_fill_byte_by_byte: + CMPQ SI, $0x00 + JLE sequenceDecs_decode_amd64_fill_check_overread + CMPQ BX, $0x07 + JLE sequenceDecs_decode_amd64_fill_end + SHLQ $0x08, DX + SUBQ $0x01, R14 + SUBQ $0x01, SI + SUBQ $0x08, BX + MOVBQZX (R14), AX + ORQ AX, DX + JMP sequenceDecs_decode_amd64_fill_byte_by_byte + +sequenceDecs_decode_amd64_fill_check_overread: + CMPQ BX, $0x40 + JA error_overread + +sequenceDecs_decode_amd64_fill_end: + // Update offset + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decode_amd64_of_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decode_amd64_of_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decode_amd64_of_update_zero + NEGQ CX + SHRQ CL, R15 + ADDQ R15, AX + +sequenceDecs_decode_amd64_of_update_zero: + MOVQ AX, 16(R10) + + // Update match length + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decode_amd64_ml_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decode_amd64_ml_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decode_amd64_ml_update_zero + NEGQ CX + SHRQ CL, R15 + ADDQ R15, AX + +sequenceDecs_decode_amd64_ml_update_zero: + MOVQ AX, 8(R10) + + // Fill bitreader to have enough for the remaining + CMPQ SI, $0x08 + JL sequenceDecs_decode_amd64_fill_2_byte_by_byte + MOVQ BX, AX + SHRQ $0x03, AX + SUBQ AX, R14 + MOVQ (R14), DX + SUBQ AX, SI + ANDQ $0x07, BX + JMP sequenceDecs_decode_amd64_fill_2_end + +sequenceDecs_decode_amd64_fill_2_byte_by_byte: + CMPQ SI, $0x00 + JLE sequenceDecs_decode_amd64_fill_2_check_overread + CMPQ BX, $0x07 + JLE sequenceDecs_decode_amd64_fill_2_end + SHLQ $0x08, DX + SUBQ $0x01, R14 + SUBQ $0x01, SI + SUBQ $0x08, BX + MOVBQZX (R14), AX + ORQ AX, DX + JMP sequenceDecs_decode_amd64_fill_2_byte_by_byte + +sequenceDecs_decode_amd64_fill_2_check_overread: + CMPQ BX, $0x40 + JA error_overread + +sequenceDecs_decode_amd64_fill_2_end: + // Update literal length + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decode_amd64_ll_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decode_amd64_ll_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decode_amd64_ll_update_zero + NEGQ CX + SHRQ CL, R15 + ADDQ R15, AX + +sequenceDecs_decode_amd64_ll_update_zero: + MOVQ AX, (R10) + + // Fill bitreader for state updates + MOVQ R14, (SP) + MOVQ R9, AX + SHRQ $0x08, AX + MOVBQZX AL, AX + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decode_amd64_skip_update + + // Update Literal Length State + MOVBQZX DI, R14 + SHRQ $0x10, DI + MOVWQZX DI, DI + LEAQ (BX)(R14*1), CX + MOVQ DX, R15 + MOVQ CX, BX + ROLQ CL, R15 + MOVL $0x00000001, BP + MOVB R14, CL + SHLL CL, BP + DECL BP + ANDQ BP, R15 + ADDQ R15, DI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(DI*8), DI + + // Update Match Length State + MOVBQZX R8, R14 + SHRQ $0x10, R8 + MOVWQZX R8, R8 + LEAQ (BX)(R14*1), CX + MOVQ DX, R15 + MOVQ CX, BX + ROLQ CL, R15 + MOVL $0x00000001, BP + MOVB R14, CL + SHLL CL, BP + DECL BP + ANDQ BP, R15 + ADDQ R15, R8 + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Offset State + MOVBQZX R9, R14 + SHRQ $0x10, R9 + MOVWQZX R9, R9 + LEAQ (BX)(R14*1), CX + MOVQ DX, R15 + MOVQ CX, BX + ROLQ CL, R15 + MOVL $0x00000001, BP + MOVB R14, CL + SHLL CL, BP + DECL BP + ANDQ BP, R15 + ADDQ R15, R9 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R9*8), R9 + +sequenceDecs_decode_amd64_skip_update: + // Adjust offset + MOVQ 16(R10), CX + CMPQ AX, $0x01 + JBE sequenceDecs_decode_amd64_adjust_offsetB_1_or_0 + MOVQ R12, R13 + MOVQ R11, R12 + MOVQ CX, R11 + JMP sequenceDecs_decode_amd64_after_adjust + +sequenceDecs_decode_amd64_adjust_offsetB_1_or_0: + CMPQ (R10), $0x00000000 + JNE sequenceDecs_decode_amd64_adjust_offset_maybezero + INCQ CX + JMP sequenceDecs_decode_amd64_adjust_offset_nonzero + +sequenceDecs_decode_amd64_adjust_offset_maybezero: + TESTQ CX, CX + JNZ sequenceDecs_decode_amd64_adjust_offset_nonzero + MOVQ R11, CX + JMP sequenceDecs_decode_amd64_after_adjust + +sequenceDecs_decode_amd64_adjust_offset_nonzero: + CMPQ CX, $0x01 + JB sequenceDecs_decode_amd64_adjust_zero + JEQ sequenceDecs_decode_amd64_adjust_one + CMPQ CX, $0x02 + JA sequenceDecs_decode_amd64_adjust_three + JMP sequenceDecs_decode_amd64_adjust_two + +sequenceDecs_decode_amd64_adjust_zero: + MOVQ R11, AX + JMP sequenceDecs_decode_amd64_adjust_test_temp_valid + +sequenceDecs_decode_amd64_adjust_one: + MOVQ R12, AX + JMP sequenceDecs_decode_amd64_adjust_test_temp_valid + +sequenceDecs_decode_amd64_adjust_two: + MOVQ R13, AX + JMP sequenceDecs_decode_amd64_adjust_test_temp_valid + +sequenceDecs_decode_amd64_adjust_three: + LEAQ -1(R11), AX + +sequenceDecs_decode_amd64_adjust_test_temp_valid: + TESTQ AX, AX + JNZ sequenceDecs_decode_amd64_adjust_temp_valid + MOVQ $0x00000001, AX + +sequenceDecs_decode_amd64_adjust_temp_valid: + CMPQ CX, $0x01 + CMOVQNE R12, R13 + MOVQ R11, R12 + MOVQ AX, R11 + MOVQ AX, CX + +sequenceDecs_decode_amd64_after_adjust: + MOVQ CX, 16(R10) + + // Check values + MOVQ 8(R10), AX + MOVQ (R10), R14 + LEAQ (AX)(R14*1), R15 + MOVQ s+0(FP), BP + ADDQ R15, 256(BP) + MOVQ ctx+16(FP), R15 + SUBQ R14, 128(R15) + JS error_not_enough_literals + CMPQ AX, $0x00020002 + JA sequenceDecs_decode_amd64_error_match_len_too_big + TESTQ CX, CX + JNZ sequenceDecs_decode_amd64_match_len_ofs_ok + TESTQ AX, AX + JNZ sequenceDecs_decode_amd64_error_match_len_ofs_mismatch + +sequenceDecs_decode_amd64_match_len_ofs_ok: + ADDQ $0x18, R10 + MOVQ ctx+16(FP), AX + DECQ 96(AX) + JNS sequenceDecs_decode_amd64_main_loop + MOVQ s+0(FP), AX + MOVQ R11, 144(AX) + MOVQ R12, 152(AX) + MOVQ R13, 160(AX) + MOVQ br+8(FP), AX + MOVQ DX, 24(AX) + MOVB BL, 32(AX) + MOVQ SI, 8(AX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decode_amd64_error_match_len_ofs_mismatch: + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decode_amd64_error_match_len_too_big: + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + +// func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int +// Requires: CMOV +TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 + MOVQ br+8(FP), CX + MOVQ 24(CX), DX + MOVBQZX 32(CX), BX + MOVQ (CX), AX + MOVQ 8(CX), SI + ADDQ SI, AX + MOVQ AX, (SP) + MOVQ ctx+16(FP), AX + MOVQ 72(AX), DI + MOVQ 80(AX), R8 + MOVQ 88(AX), R9 + MOVQ 104(AX), R10 + MOVQ s+0(FP), AX + MOVQ 144(AX), R11 + MOVQ 152(AX), R12 + MOVQ 160(AX), R13 + +sequenceDecs_decode_56_amd64_main_loop: + MOVQ (SP), R14 + + // Fill bitreader to have enough for the offset and match length. + CMPQ SI, $0x08 + JL sequenceDecs_decode_56_amd64_fill_byte_by_byte + MOVQ BX, AX + SHRQ $0x03, AX + SUBQ AX, R14 + MOVQ (R14), DX + SUBQ AX, SI + ANDQ $0x07, BX + JMP sequenceDecs_decode_56_amd64_fill_end + +sequenceDecs_decode_56_amd64_fill_byte_by_byte: + CMPQ SI, $0x00 + JLE sequenceDecs_decode_56_amd64_fill_check_overread + CMPQ BX, $0x07 + JLE sequenceDecs_decode_56_amd64_fill_end + SHLQ $0x08, DX + SUBQ $0x01, R14 + SUBQ $0x01, SI + SUBQ $0x08, BX + MOVBQZX (R14), AX + ORQ AX, DX + JMP sequenceDecs_decode_56_amd64_fill_byte_by_byte + +sequenceDecs_decode_56_amd64_fill_check_overread: + CMPQ BX, $0x40 + JA error_overread + +sequenceDecs_decode_56_amd64_fill_end: + // Update offset + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decode_56_amd64_of_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decode_56_amd64_of_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decode_56_amd64_of_update_zero + NEGQ CX + SHRQ CL, R15 + ADDQ R15, AX + +sequenceDecs_decode_56_amd64_of_update_zero: + MOVQ AX, 16(R10) + + // Update match length + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decode_56_amd64_ml_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decode_56_amd64_ml_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decode_56_amd64_ml_update_zero + NEGQ CX + SHRQ CL, R15 + ADDQ R15, AX + +sequenceDecs_decode_56_amd64_ml_update_zero: + MOVQ AX, 8(R10) + + // Update literal length + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decode_56_amd64_ll_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decode_56_amd64_ll_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decode_56_amd64_ll_update_zero + NEGQ CX + SHRQ CL, R15 + ADDQ R15, AX + +sequenceDecs_decode_56_amd64_ll_update_zero: + MOVQ AX, (R10) + + // Fill bitreader for state updates + MOVQ R14, (SP) + MOVQ R9, AX + SHRQ $0x08, AX + MOVBQZX AL, AX + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decode_56_amd64_skip_update + + // Update Literal Length State + MOVBQZX DI, R14 + SHRQ $0x10, DI + MOVWQZX DI, DI + LEAQ (BX)(R14*1), CX + MOVQ DX, R15 + MOVQ CX, BX + ROLQ CL, R15 + MOVL $0x00000001, BP + MOVB R14, CL + SHLL CL, BP + DECL BP + ANDQ BP, R15 + ADDQ R15, DI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(DI*8), DI + + // Update Match Length State + MOVBQZX R8, R14 + SHRQ $0x10, R8 + MOVWQZX R8, R8 + LEAQ (BX)(R14*1), CX + MOVQ DX, R15 + MOVQ CX, BX + ROLQ CL, R15 + MOVL $0x00000001, BP + MOVB R14, CL + SHLL CL, BP + DECL BP + ANDQ BP, R15 + ADDQ R15, R8 + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Offset State + MOVBQZX R9, R14 + SHRQ $0x10, R9 + MOVWQZX R9, R9 + LEAQ (BX)(R14*1), CX + MOVQ DX, R15 + MOVQ CX, BX + ROLQ CL, R15 + MOVL $0x00000001, BP + MOVB R14, CL + SHLL CL, BP + DECL BP + ANDQ BP, R15 + ADDQ R15, R9 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R9*8), R9 + +sequenceDecs_decode_56_amd64_skip_update: + // Adjust offset + MOVQ 16(R10), CX + CMPQ AX, $0x01 + JBE sequenceDecs_decode_56_amd64_adjust_offsetB_1_or_0 + MOVQ R12, R13 + MOVQ R11, R12 + MOVQ CX, R11 + JMP sequenceDecs_decode_56_amd64_after_adjust + +sequenceDecs_decode_56_amd64_adjust_offsetB_1_or_0: + CMPQ (R10), $0x00000000 + JNE sequenceDecs_decode_56_amd64_adjust_offset_maybezero + INCQ CX + JMP sequenceDecs_decode_56_amd64_adjust_offset_nonzero + +sequenceDecs_decode_56_amd64_adjust_offset_maybezero: + TESTQ CX, CX + JNZ sequenceDecs_decode_56_amd64_adjust_offset_nonzero + MOVQ R11, CX + JMP sequenceDecs_decode_56_amd64_after_adjust + +sequenceDecs_decode_56_amd64_adjust_offset_nonzero: + CMPQ CX, $0x01 + JB sequenceDecs_decode_56_amd64_adjust_zero + JEQ sequenceDecs_decode_56_amd64_adjust_one + CMPQ CX, $0x02 + JA sequenceDecs_decode_56_amd64_adjust_three + JMP sequenceDecs_decode_56_amd64_adjust_two + +sequenceDecs_decode_56_amd64_adjust_zero: + MOVQ R11, AX + JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid + +sequenceDecs_decode_56_amd64_adjust_one: + MOVQ R12, AX + JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid + +sequenceDecs_decode_56_amd64_adjust_two: + MOVQ R13, AX + JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid + +sequenceDecs_decode_56_amd64_adjust_three: + LEAQ -1(R11), AX + +sequenceDecs_decode_56_amd64_adjust_test_temp_valid: + TESTQ AX, AX + JNZ sequenceDecs_decode_56_amd64_adjust_temp_valid + MOVQ $0x00000001, AX + +sequenceDecs_decode_56_amd64_adjust_temp_valid: + CMPQ CX, $0x01 + CMOVQNE R12, R13 + MOVQ R11, R12 + MOVQ AX, R11 + MOVQ AX, CX + +sequenceDecs_decode_56_amd64_after_adjust: + MOVQ CX, 16(R10) + + // Check values + MOVQ 8(R10), AX + MOVQ (R10), R14 + LEAQ (AX)(R14*1), R15 + MOVQ s+0(FP), BP + ADDQ R15, 256(BP) + MOVQ ctx+16(FP), R15 + SUBQ R14, 128(R15) + JS error_not_enough_literals + CMPQ AX, $0x00020002 + JA sequenceDecs_decode_56_amd64_error_match_len_too_big + TESTQ CX, CX + JNZ sequenceDecs_decode_56_amd64_match_len_ofs_ok + TESTQ AX, AX + JNZ sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch + +sequenceDecs_decode_56_amd64_match_len_ofs_ok: + ADDQ $0x18, R10 + MOVQ ctx+16(FP), AX + DECQ 96(AX) + JNS sequenceDecs_decode_56_amd64_main_loop + MOVQ s+0(FP), AX + MOVQ R11, 144(AX) + MOVQ R12, 152(AX) + MOVQ R13, 160(AX) + MOVQ br+8(FP), AX + MOVQ DX, 24(AX) + MOVB BL, 32(AX) + MOVQ SI, 8(AX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch: + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decode_56_amd64_error_match_len_too_big: + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + +// func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int +// Requires: BMI, BMI2, CMOV +TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 + MOVQ br+8(FP), BX + MOVQ 24(BX), AX + MOVBQZX 32(BX), DX + MOVQ (BX), CX + MOVQ 8(BX), BX + ADDQ BX, CX + MOVQ CX, (SP) + MOVQ ctx+16(FP), CX + MOVQ 72(CX), SI + MOVQ 80(CX), DI + MOVQ 88(CX), R8 + MOVQ 104(CX), R9 + MOVQ s+0(FP), CX + MOVQ 144(CX), R10 + MOVQ 152(CX), R11 + MOVQ 160(CX), R12 + +sequenceDecs_decode_bmi2_main_loop: + MOVQ (SP), R13 + + // Fill bitreader to have enough for the offset and match length. + CMPQ BX, $0x08 + JL sequenceDecs_decode_bmi2_fill_byte_by_byte + MOVQ DX, CX + SHRQ $0x03, CX + SUBQ CX, R13 + MOVQ (R13), AX + SUBQ CX, BX + ANDQ $0x07, DX + JMP sequenceDecs_decode_bmi2_fill_end + +sequenceDecs_decode_bmi2_fill_byte_by_byte: + CMPQ BX, $0x00 + JLE sequenceDecs_decode_bmi2_fill_check_overread + CMPQ DX, $0x07 + JLE sequenceDecs_decode_bmi2_fill_end + SHLQ $0x08, AX + SUBQ $0x01, R13 + SUBQ $0x01, BX + SUBQ $0x08, DX + MOVBQZX (R13), CX + ORQ CX, AX + JMP sequenceDecs_decode_bmi2_fill_byte_by_byte + +sequenceDecs_decode_bmi2_fill_check_overread: + CMPQ DX, $0x40 + JA error_overread + +sequenceDecs_decode_bmi2_fill_end: + // Update offset + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R14 + MOVQ AX, R15 + LEAQ (DX)(R14*1), CX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + MOVQ CX, DX + MOVQ R8, CX + SHRQ $0x20, CX + ADDQ R15, CX + MOVQ CX, 16(R9) + + // Update match length + MOVQ $0x00000808, CX + BEXTRQ CX, DI, R14 + MOVQ AX, R15 + LEAQ (DX)(R14*1), CX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + MOVQ CX, DX + MOVQ DI, CX + SHRQ $0x20, CX + ADDQ R15, CX + MOVQ CX, 8(R9) + + // Fill bitreader to have enough for the remaining + CMPQ BX, $0x08 + JL sequenceDecs_decode_bmi2_fill_2_byte_by_byte + MOVQ DX, CX + SHRQ $0x03, CX + SUBQ CX, R13 + MOVQ (R13), AX + SUBQ CX, BX + ANDQ $0x07, DX + JMP sequenceDecs_decode_bmi2_fill_2_end + +sequenceDecs_decode_bmi2_fill_2_byte_by_byte: + CMPQ BX, $0x00 + JLE sequenceDecs_decode_bmi2_fill_2_check_overread + CMPQ DX, $0x07 + JLE sequenceDecs_decode_bmi2_fill_2_end + SHLQ $0x08, AX + SUBQ $0x01, R13 + SUBQ $0x01, BX + SUBQ $0x08, DX + MOVBQZX (R13), CX + ORQ CX, AX + JMP sequenceDecs_decode_bmi2_fill_2_byte_by_byte + +sequenceDecs_decode_bmi2_fill_2_check_overread: + CMPQ DX, $0x40 + JA error_overread + +sequenceDecs_decode_bmi2_fill_2_end: + // Update literal length + MOVQ $0x00000808, CX + BEXTRQ CX, SI, R14 + MOVQ AX, R15 + LEAQ (DX)(R14*1), CX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + MOVQ CX, DX + MOVQ SI, CX + SHRQ $0x20, CX + ADDQ R15, CX + MOVQ CX, (R9) + + // Fill bitreader for state updates + MOVQ R13, (SP) + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R13 + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decode_bmi2_skip_update + LEAQ (SI)(DI*1), R14 + ADDQ R8, R14 + MOVBQZX R14, R14 + LEAQ (DX)(R14*1), CX + MOVQ AX, R15 + MOVQ CX, DX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + + // Update Offset State + BZHIQ R8, R15, CX + SHRXQ R8, R15, R15 + MOVQ $0x00001010, R14 + BEXTRQ R14, R8, R8 + ADDQ CX, R8 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Match Length State + BZHIQ DI, R15, CX + SHRXQ DI, R15, R15 + MOVQ $0x00001010, R14 + BEXTRQ R14, DI, DI + ADDQ CX, DI + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(DI*8), DI + + // Update Literal Length State + BZHIQ SI, R15, CX + MOVQ $0x00001010, R14 + BEXTRQ R14, SI, SI + ADDQ CX, SI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(SI*8), SI + +sequenceDecs_decode_bmi2_skip_update: + // Adjust offset + MOVQ 16(R9), CX + CMPQ R13, $0x01 + JBE sequenceDecs_decode_bmi2_adjust_offsetB_1_or_0 + MOVQ R11, R12 + MOVQ R10, R11 + MOVQ CX, R10 + JMP sequenceDecs_decode_bmi2_after_adjust + +sequenceDecs_decode_bmi2_adjust_offsetB_1_or_0: + CMPQ (R9), $0x00000000 + JNE sequenceDecs_decode_bmi2_adjust_offset_maybezero + INCQ CX + JMP sequenceDecs_decode_bmi2_adjust_offset_nonzero + +sequenceDecs_decode_bmi2_adjust_offset_maybezero: + TESTQ CX, CX + JNZ sequenceDecs_decode_bmi2_adjust_offset_nonzero + MOVQ R10, CX + JMP sequenceDecs_decode_bmi2_after_adjust + +sequenceDecs_decode_bmi2_adjust_offset_nonzero: + CMPQ CX, $0x01 + JB sequenceDecs_decode_bmi2_adjust_zero + JEQ sequenceDecs_decode_bmi2_adjust_one + CMPQ CX, $0x02 + JA sequenceDecs_decode_bmi2_adjust_three + JMP sequenceDecs_decode_bmi2_adjust_two + +sequenceDecs_decode_bmi2_adjust_zero: + MOVQ R10, R13 + JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid + +sequenceDecs_decode_bmi2_adjust_one: + MOVQ R11, R13 + JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid + +sequenceDecs_decode_bmi2_adjust_two: + MOVQ R12, R13 + JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid + +sequenceDecs_decode_bmi2_adjust_three: + LEAQ -1(R10), R13 + +sequenceDecs_decode_bmi2_adjust_test_temp_valid: + TESTQ R13, R13 + JNZ sequenceDecs_decode_bmi2_adjust_temp_valid + MOVQ $0x00000001, R13 + +sequenceDecs_decode_bmi2_adjust_temp_valid: + CMPQ CX, $0x01 + CMOVQNE R11, R12 + MOVQ R10, R11 + MOVQ R13, R10 + MOVQ R13, CX + +sequenceDecs_decode_bmi2_after_adjust: + MOVQ CX, 16(R9) + + // Check values + MOVQ 8(R9), R13 + MOVQ (R9), R14 + LEAQ (R13)(R14*1), R15 + MOVQ s+0(FP), BP + ADDQ R15, 256(BP) + MOVQ ctx+16(FP), R15 + SUBQ R14, 128(R15) + JS error_not_enough_literals + CMPQ R13, $0x00020002 + JA sequenceDecs_decode_bmi2_error_match_len_too_big + TESTQ CX, CX + JNZ sequenceDecs_decode_bmi2_match_len_ofs_ok + TESTQ R13, R13 + JNZ sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch + +sequenceDecs_decode_bmi2_match_len_ofs_ok: + ADDQ $0x18, R9 + MOVQ ctx+16(FP), CX + DECQ 96(CX) + JNS sequenceDecs_decode_bmi2_main_loop + MOVQ s+0(FP), CX + MOVQ R10, 144(CX) + MOVQ R11, 152(CX) + MOVQ R12, 160(CX) + MOVQ br+8(FP), CX + MOVQ AX, 24(CX) + MOVB DL, 32(CX) + MOVQ BX, 8(CX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch: + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decode_bmi2_error_match_len_too_big: + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + +// func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int +// Requires: BMI, BMI2, CMOV +TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 + MOVQ br+8(FP), BX + MOVQ 24(BX), AX + MOVBQZX 32(BX), DX + MOVQ (BX), CX + MOVQ 8(BX), BX + ADDQ BX, CX + MOVQ CX, (SP) + MOVQ ctx+16(FP), CX + MOVQ 72(CX), SI + MOVQ 80(CX), DI + MOVQ 88(CX), R8 + MOVQ 104(CX), R9 + MOVQ s+0(FP), CX + MOVQ 144(CX), R10 + MOVQ 152(CX), R11 + MOVQ 160(CX), R12 + +sequenceDecs_decode_56_bmi2_main_loop: + MOVQ (SP), R13 + + // Fill bitreader to have enough for the offset and match length. + CMPQ BX, $0x08 + JL sequenceDecs_decode_56_bmi2_fill_byte_by_byte + MOVQ DX, CX + SHRQ $0x03, CX + SUBQ CX, R13 + MOVQ (R13), AX + SUBQ CX, BX + ANDQ $0x07, DX + JMP sequenceDecs_decode_56_bmi2_fill_end + +sequenceDecs_decode_56_bmi2_fill_byte_by_byte: + CMPQ BX, $0x00 + JLE sequenceDecs_decode_56_bmi2_fill_check_overread + CMPQ DX, $0x07 + JLE sequenceDecs_decode_56_bmi2_fill_end + SHLQ $0x08, AX + SUBQ $0x01, R13 + SUBQ $0x01, BX + SUBQ $0x08, DX + MOVBQZX (R13), CX + ORQ CX, AX + JMP sequenceDecs_decode_56_bmi2_fill_byte_by_byte + +sequenceDecs_decode_56_bmi2_fill_check_overread: + CMPQ DX, $0x40 + JA error_overread + +sequenceDecs_decode_56_bmi2_fill_end: + // Update offset + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R14 + MOVQ AX, R15 + LEAQ (DX)(R14*1), CX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + MOVQ CX, DX + MOVQ R8, CX + SHRQ $0x20, CX + ADDQ R15, CX + MOVQ CX, 16(R9) + + // Update match length + MOVQ $0x00000808, CX + BEXTRQ CX, DI, R14 + MOVQ AX, R15 + LEAQ (DX)(R14*1), CX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + MOVQ CX, DX + MOVQ DI, CX + SHRQ $0x20, CX + ADDQ R15, CX + MOVQ CX, 8(R9) + + // Update literal length + MOVQ $0x00000808, CX + BEXTRQ CX, SI, R14 + MOVQ AX, R15 + LEAQ (DX)(R14*1), CX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + MOVQ CX, DX + MOVQ SI, CX + SHRQ $0x20, CX + ADDQ R15, CX + MOVQ CX, (R9) + + // Fill bitreader for state updates + MOVQ R13, (SP) + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R13 + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decode_56_bmi2_skip_update + LEAQ (SI)(DI*1), R14 + ADDQ R8, R14 + MOVBQZX R14, R14 + LEAQ (DX)(R14*1), CX + MOVQ AX, R15 + MOVQ CX, DX + ROLQ CL, R15 + BZHIQ R14, R15, R15 + + // Update Offset State + BZHIQ R8, R15, CX + SHRXQ R8, R15, R15 + MOVQ $0x00001010, R14 + BEXTRQ R14, R8, R8 + ADDQ CX, R8 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Match Length State + BZHIQ DI, R15, CX + SHRXQ DI, R15, R15 + MOVQ $0x00001010, R14 + BEXTRQ R14, DI, DI + ADDQ CX, DI + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(DI*8), DI + + // Update Literal Length State + BZHIQ SI, R15, CX + MOVQ $0x00001010, R14 + BEXTRQ R14, SI, SI + ADDQ CX, SI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(SI*8), SI + +sequenceDecs_decode_56_bmi2_skip_update: + // Adjust offset + MOVQ 16(R9), CX + CMPQ R13, $0x01 + JBE sequenceDecs_decode_56_bmi2_adjust_offsetB_1_or_0 + MOVQ R11, R12 + MOVQ R10, R11 + MOVQ CX, R10 + JMP sequenceDecs_decode_56_bmi2_after_adjust + +sequenceDecs_decode_56_bmi2_adjust_offsetB_1_or_0: + CMPQ (R9), $0x00000000 + JNE sequenceDecs_decode_56_bmi2_adjust_offset_maybezero + INCQ CX + JMP sequenceDecs_decode_56_bmi2_adjust_offset_nonzero + +sequenceDecs_decode_56_bmi2_adjust_offset_maybezero: + TESTQ CX, CX + JNZ sequenceDecs_decode_56_bmi2_adjust_offset_nonzero + MOVQ R10, CX + JMP sequenceDecs_decode_56_bmi2_after_adjust + +sequenceDecs_decode_56_bmi2_adjust_offset_nonzero: + CMPQ CX, $0x01 + JB sequenceDecs_decode_56_bmi2_adjust_zero + JEQ sequenceDecs_decode_56_bmi2_adjust_one + CMPQ CX, $0x02 + JA sequenceDecs_decode_56_bmi2_adjust_three + JMP sequenceDecs_decode_56_bmi2_adjust_two + +sequenceDecs_decode_56_bmi2_adjust_zero: + MOVQ R10, R13 + JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid + +sequenceDecs_decode_56_bmi2_adjust_one: + MOVQ R11, R13 + JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid + +sequenceDecs_decode_56_bmi2_adjust_two: + MOVQ R12, R13 + JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid + +sequenceDecs_decode_56_bmi2_adjust_three: + LEAQ -1(R10), R13 + +sequenceDecs_decode_56_bmi2_adjust_test_temp_valid: + TESTQ R13, R13 + JNZ sequenceDecs_decode_56_bmi2_adjust_temp_valid + MOVQ $0x00000001, R13 + +sequenceDecs_decode_56_bmi2_adjust_temp_valid: + CMPQ CX, $0x01 + CMOVQNE R11, R12 + MOVQ R10, R11 + MOVQ R13, R10 + MOVQ R13, CX + +sequenceDecs_decode_56_bmi2_after_adjust: + MOVQ CX, 16(R9) + + // Check values + MOVQ 8(R9), R13 + MOVQ (R9), R14 + LEAQ (R13)(R14*1), R15 + MOVQ s+0(FP), BP + ADDQ R15, 256(BP) + MOVQ ctx+16(FP), R15 + SUBQ R14, 128(R15) + JS error_not_enough_literals + CMPQ R13, $0x00020002 + JA sequenceDecs_decode_56_bmi2_error_match_len_too_big + TESTQ CX, CX + JNZ sequenceDecs_decode_56_bmi2_match_len_ofs_ok + TESTQ R13, R13 + JNZ sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch + +sequenceDecs_decode_56_bmi2_match_len_ofs_ok: + ADDQ $0x18, R9 + MOVQ ctx+16(FP), CX + DECQ 96(CX) + JNS sequenceDecs_decode_56_bmi2_main_loop + MOVQ s+0(FP), CX + MOVQ R10, 144(CX) + MOVQ R11, 152(CX) + MOVQ R12, 160(CX) + MOVQ br+8(FP), CX + MOVQ AX, 24(CX) + MOVB DL, 32(CX) + MOVQ BX, 8(CX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch: + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decode_56_bmi2_error_match_len_too_big: + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + +// func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool +// Requires: SSE +TEXT ·sequenceDecs_executeSimple_amd64(SB), $8-9 + MOVQ ctx+0(FP), R10 + MOVQ 8(R10), CX + TESTQ CX, CX + JZ empty_seqs + MOVQ (R10), AX + MOVQ 24(R10), DX + MOVQ 32(R10), BX + MOVQ 80(R10), SI + MOVQ 104(R10), DI + MOVQ 120(R10), R8 + MOVQ 56(R10), R9 + MOVQ 64(R10), R10 + ADDQ R10, R9 + + // seqsBase += 24 * seqIndex + LEAQ (DX)(DX*2), R11 + SHLQ $0x03, R11 + ADDQ R11, AX + + // outBase += outPosition + ADDQ DI, BX + +main_loop: + MOVQ (AX), R11 + MOVQ 16(AX), R12 + MOVQ 8(AX), R13 + + // Copy literals + TESTQ R11, R11 + JZ check_offset + XORQ R14, R14 + +copy_1: + MOVUPS (SI)(R14*1), X0 + MOVUPS X0, (BX)(R14*1) + ADDQ $0x10, R14 + CMPQ R14, R11 + JB copy_1 + ADDQ R11, SI + ADDQ R11, BX + ADDQ R11, DI + + // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) +check_offset: + LEAQ (DI)(R10*1), R11 + CMPQ R12, R11 + JG error_match_off_too_big + CMPQ R12, R8 + JG error_match_off_too_big + + // Copy match from history + MOVQ R12, R11 + SUBQ DI, R11 + JLS copy_match + MOVQ R9, R14 + SUBQ R11, R14 + CMPQ R13, R11 + JG copy_all_from_history + MOVQ R13, R11 + SUBQ $0x10, R11 + JB copy_4_small + +copy_4_loop: + MOVUPS (R14), X0 + MOVUPS X0, (BX) + ADDQ $0x10, R14 + ADDQ $0x10, BX + SUBQ $0x10, R11 + JAE copy_4_loop + LEAQ 16(R14)(R11*1), R14 + LEAQ 16(BX)(R11*1), BX + MOVUPS -16(R14), X0 + MOVUPS X0, -16(BX) + JMP copy_4_end + +copy_4_small: + CMPQ R13, $0x03 + JE copy_4_move_3 + CMPQ R13, $0x08 + JB copy_4_move_4through7 + JMP copy_4_move_8through16 + +copy_4_move_3: + MOVW (R14), R11 + MOVB 2(R14), R12 + MOVW R11, (BX) + MOVB R12, 2(BX) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end + +copy_4_move_4through7: + MOVL (R14), R11 + MOVL -4(R14)(R13*1), R12 + MOVL R11, (BX) + MOVL R12, -4(BX)(R13*1) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end + +copy_4_move_8through16: + MOVQ (R14), R11 + MOVQ -8(R14)(R13*1), R12 + MOVQ R11, (BX) + MOVQ R12, -8(BX)(R13*1) + ADDQ R13, R14 + ADDQ R13, BX + +copy_4_end: + ADDQ R13, DI + ADDQ $0x18, AX + INCQ DX + CMPQ DX, CX + JB main_loop + JMP loop_finished + +copy_all_from_history: + MOVQ R11, R15 + SUBQ $0x10, R15 + JB copy_5_small + +copy_5_loop: + MOVUPS (R14), X0 + MOVUPS X0, (BX) + ADDQ $0x10, R14 + ADDQ $0x10, BX + SUBQ $0x10, R15 + JAE copy_5_loop + LEAQ 16(R14)(R15*1), R14 + LEAQ 16(BX)(R15*1), BX + MOVUPS -16(R14), X0 + MOVUPS X0, -16(BX) + JMP copy_5_end + +copy_5_small: + CMPQ R11, $0x03 + JE copy_5_move_3 + JB copy_5_move_1or2 + CMPQ R11, $0x08 + JB copy_5_move_4through7 + JMP copy_5_move_8through16 + +copy_5_move_1or2: + MOVB (R14), R15 + MOVB -1(R14)(R11*1), BP + MOVB R15, (BX) + MOVB BP, -1(BX)(R11*1) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end + +copy_5_move_3: + MOVW (R14), R15 + MOVB 2(R14), BP + MOVW R15, (BX) + MOVB BP, 2(BX) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end + +copy_5_move_4through7: + MOVL (R14), R15 + MOVL -4(R14)(R11*1), BP + MOVL R15, (BX) + MOVL BP, -4(BX)(R11*1) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end + +copy_5_move_8through16: + MOVQ (R14), R15 + MOVQ -8(R14)(R11*1), BP + MOVQ R15, (BX) + MOVQ BP, -8(BX)(R11*1) + ADDQ R11, R14 + ADDQ R11, BX + +copy_5_end: + ADDQ R11, DI + SUBQ R11, R13 + + // Copy match from the current buffer +copy_match: + MOVQ BX, R11 + SUBQ R12, R11 + + // ml <= mo + CMPQ R13, R12 + JA copy_overlapping_match + + // Copy non-overlapping match + ADDQ R13, DI + MOVQ BX, R12 + ADDQ R13, BX + +copy_2: + MOVUPS (R11), X0 + MOVUPS X0, (R12) + ADDQ $0x10, R11 + ADDQ $0x10, R12 + SUBQ $0x10, R13 + JHI copy_2 + JMP handle_loop + + // Copy overlapping match +copy_overlapping_match: + ADDQ R13, DI + +copy_slow_3: + MOVB (R11), R12 + MOVB R12, (BX) + INCQ R11 + INCQ BX + DECQ R13 + JNZ copy_slow_3 + +handle_loop: + ADDQ $0x18, AX + INCQ DX + CMPQ DX, CX + JB main_loop + +loop_finished: + // Return value + MOVB $0x01, ret+8(FP) + + // Update the context + MOVQ ctx+0(FP), AX + MOVQ DX, 24(AX) + MOVQ DI, 104(AX) + SUBQ 80(AX), SI + MOVQ SI, 112(AX) + RET + +error_match_off_too_big: + // Return value + MOVB $0x00, ret+8(FP) + + // Update the context + MOVQ ctx+0(FP), AX + MOVQ DX, 24(AX) + MOVQ DI, 104(AX) + SUBQ 80(AX), SI + MOVQ SI, 112(AX) + RET + +empty_seqs: + // Return value + MOVB $0x01, ret+8(FP) + RET + +// func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool +// Requires: SSE +TEXT ·sequenceDecs_executeSimple_safe_amd64(SB), $8-9 + MOVQ ctx+0(FP), R10 + MOVQ 8(R10), CX + TESTQ CX, CX + JZ empty_seqs + MOVQ (R10), AX + MOVQ 24(R10), DX + MOVQ 32(R10), BX + MOVQ 80(R10), SI + MOVQ 104(R10), DI + MOVQ 120(R10), R8 + MOVQ 56(R10), R9 + MOVQ 64(R10), R10 + ADDQ R10, R9 + + // seqsBase += 24 * seqIndex + LEAQ (DX)(DX*2), R11 + SHLQ $0x03, R11 + ADDQ R11, AX + + // outBase += outPosition + ADDQ DI, BX + +main_loop: + MOVQ (AX), R11 + MOVQ 16(AX), R12 + MOVQ 8(AX), R13 + + // Copy literals + TESTQ R11, R11 + JZ check_offset + MOVQ R11, R14 + SUBQ $0x10, R14 + JB copy_1_small + +copy_1_loop: + MOVUPS (SI), X0 + MOVUPS X0, (BX) + ADDQ $0x10, SI + ADDQ $0x10, BX + SUBQ $0x10, R14 + JAE copy_1_loop + LEAQ 16(SI)(R14*1), SI + LEAQ 16(BX)(R14*1), BX + MOVUPS -16(SI), X0 + MOVUPS X0, -16(BX) + JMP copy_1_end + +copy_1_small: + CMPQ R11, $0x03 + JE copy_1_move_3 + JB copy_1_move_1or2 + CMPQ R11, $0x08 + JB copy_1_move_4through7 + JMP copy_1_move_8through16 + +copy_1_move_1or2: + MOVB (SI), R14 + MOVB -1(SI)(R11*1), R15 + MOVB R14, (BX) + MOVB R15, -1(BX)(R11*1) + ADDQ R11, SI + ADDQ R11, BX + JMP copy_1_end + +copy_1_move_3: + MOVW (SI), R14 + MOVB 2(SI), R15 + MOVW R14, (BX) + MOVB R15, 2(BX) + ADDQ R11, SI + ADDQ R11, BX + JMP copy_1_end + +copy_1_move_4through7: + MOVL (SI), R14 + MOVL -4(SI)(R11*1), R15 + MOVL R14, (BX) + MOVL R15, -4(BX)(R11*1) + ADDQ R11, SI + ADDQ R11, BX + JMP copy_1_end + +copy_1_move_8through16: + MOVQ (SI), R14 + MOVQ -8(SI)(R11*1), R15 + MOVQ R14, (BX) + MOVQ R15, -8(BX)(R11*1) + ADDQ R11, SI + ADDQ R11, BX + +copy_1_end: + ADDQ R11, DI + + // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) +check_offset: + LEAQ (DI)(R10*1), R11 + CMPQ R12, R11 + JG error_match_off_too_big + CMPQ R12, R8 + JG error_match_off_too_big + + // Copy match from history + MOVQ R12, R11 + SUBQ DI, R11 + JLS copy_match + MOVQ R9, R14 + SUBQ R11, R14 + CMPQ R13, R11 + JG copy_all_from_history + MOVQ R13, R11 + SUBQ $0x10, R11 + JB copy_4_small + +copy_4_loop: + MOVUPS (R14), X0 + MOVUPS X0, (BX) + ADDQ $0x10, R14 + ADDQ $0x10, BX + SUBQ $0x10, R11 + JAE copy_4_loop + LEAQ 16(R14)(R11*1), R14 + LEAQ 16(BX)(R11*1), BX + MOVUPS -16(R14), X0 + MOVUPS X0, -16(BX) + JMP copy_4_end + +copy_4_small: + CMPQ R13, $0x03 + JE copy_4_move_3 + CMPQ R13, $0x08 + JB copy_4_move_4through7 + JMP copy_4_move_8through16 + +copy_4_move_3: + MOVW (R14), R11 + MOVB 2(R14), R12 + MOVW R11, (BX) + MOVB R12, 2(BX) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end + +copy_4_move_4through7: + MOVL (R14), R11 + MOVL -4(R14)(R13*1), R12 + MOVL R11, (BX) + MOVL R12, -4(BX)(R13*1) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end + +copy_4_move_8through16: + MOVQ (R14), R11 + MOVQ -8(R14)(R13*1), R12 + MOVQ R11, (BX) + MOVQ R12, -8(BX)(R13*1) + ADDQ R13, R14 + ADDQ R13, BX + +copy_4_end: + ADDQ R13, DI + ADDQ $0x18, AX + INCQ DX + CMPQ DX, CX + JB main_loop + JMP loop_finished + +copy_all_from_history: + MOVQ R11, R15 + SUBQ $0x10, R15 + JB copy_5_small + +copy_5_loop: + MOVUPS (R14), X0 + MOVUPS X0, (BX) + ADDQ $0x10, R14 + ADDQ $0x10, BX + SUBQ $0x10, R15 + JAE copy_5_loop + LEAQ 16(R14)(R15*1), R14 + LEAQ 16(BX)(R15*1), BX + MOVUPS -16(R14), X0 + MOVUPS X0, -16(BX) + JMP copy_5_end + +copy_5_small: + CMPQ R11, $0x03 + JE copy_5_move_3 + JB copy_5_move_1or2 + CMPQ R11, $0x08 + JB copy_5_move_4through7 + JMP copy_5_move_8through16 + +copy_5_move_1or2: + MOVB (R14), R15 + MOVB -1(R14)(R11*1), BP + MOVB R15, (BX) + MOVB BP, -1(BX)(R11*1) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end + +copy_5_move_3: + MOVW (R14), R15 + MOVB 2(R14), BP + MOVW R15, (BX) + MOVB BP, 2(BX) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end + +copy_5_move_4through7: + MOVL (R14), R15 + MOVL -4(R14)(R11*1), BP + MOVL R15, (BX) + MOVL BP, -4(BX)(R11*1) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end + +copy_5_move_8through16: + MOVQ (R14), R15 + MOVQ -8(R14)(R11*1), BP + MOVQ R15, (BX) + MOVQ BP, -8(BX)(R11*1) + ADDQ R11, R14 + ADDQ R11, BX + +copy_5_end: + ADDQ R11, DI + SUBQ R11, R13 + + // Copy match from the current buffer +copy_match: + MOVQ BX, R11 + SUBQ R12, R11 + + // ml <= mo + CMPQ R13, R12 + JA copy_overlapping_match + + // Copy non-overlapping match + ADDQ R13, DI + MOVQ R13, R12 + SUBQ $0x10, R12 + JB copy_2_small + +copy_2_loop: + MOVUPS (R11), X0 + MOVUPS X0, (BX) + ADDQ $0x10, R11 + ADDQ $0x10, BX + SUBQ $0x10, R12 + JAE copy_2_loop + LEAQ 16(R11)(R12*1), R11 + LEAQ 16(BX)(R12*1), BX + MOVUPS -16(R11), X0 + MOVUPS X0, -16(BX) + JMP copy_2_end + +copy_2_small: + CMPQ R13, $0x03 + JE copy_2_move_3 + JB copy_2_move_1or2 + CMPQ R13, $0x08 + JB copy_2_move_4through7 + JMP copy_2_move_8through16 + +copy_2_move_1or2: + MOVB (R11), R12 + MOVB -1(R11)(R13*1), R14 + MOVB R12, (BX) + MOVB R14, -1(BX)(R13*1) + ADDQ R13, R11 + ADDQ R13, BX + JMP copy_2_end + +copy_2_move_3: + MOVW (R11), R12 + MOVB 2(R11), R14 + MOVW R12, (BX) + MOVB R14, 2(BX) + ADDQ R13, R11 + ADDQ R13, BX + JMP copy_2_end + +copy_2_move_4through7: + MOVL (R11), R12 + MOVL -4(R11)(R13*1), R14 + MOVL R12, (BX) + MOVL R14, -4(BX)(R13*1) + ADDQ R13, R11 + ADDQ R13, BX + JMP copy_2_end + +copy_2_move_8through16: + MOVQ (R11), R12 + MOVQ -8(R11)(R13*1), R14 + MOVQ R12, (BX) + MOVQ R14, -8(BX)(R13*1) + ADDQ R13, R11 + ADDQ R13, BX + +copy_2_end: + JMP handle_loop + + // Copy overlapping match +copy_overlapping_match: + ADDQ R13, DI + +copy_slow_3: + MOVB (R11), R12 + MOVB R12, (BX) + INCQ R11 + INCQ BX + DECQ R13 + JNZ copy_slow_3 + +handle_loop: + ADDQ $0x18, AX + INCQ DX + CMPQ DX, CX + JB main_loop + +loop_finished: + // Return value + MOVB $0x01, ret+8(FP) + + // Update the context + MOVQ ctx+0(FP), AX + MOVQ DX, 24(AX) + MOVQ DI, 104(AX) + SUBQ 80(AX), SI + MOVQ SI, 112(AX) + RET + +error_match_off_too_big: + // Return value + MOVB $0x00, ret+8(FP) + + // Update the context + MOVQ ctx+0(FP), AX + MOVQ DX, 24(AX) + MOVQ DI, 104(AX) + SUBQ 80(AX), SI + MOVQ SI, 112(AX) + RET + +empty_seqs: + // Return value + MOVB $0x01, ret+8(FP) + RET + +// func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int +// Requires: CMOV, SSE +TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 + MOVQ br+8(FP), CX + MOVQ 24(CX), DX + MOVBQZX 32(CX), BX + MOVQ (CX), AX + MOVQ 8(CX), SI + ADDQ SI, AX + MOVQ AX, (SP) + MOVQ ctx+16(FP), AX + MOVQ 72(AX), DI + MOVQ 80(AX), R8 + MOVQ 88(AX), R9 + XORQ CX, CX + MOVQ CX, 8(SP) + MOVQ CX, 16(SP) + MOVQ CX, 24(SP) + MOVQ 112(AX), R10 + MOVQ 128(AX), CX + MOVQ CX, 32(SP) + MOVQ 144(AX), R11 + MOVQ 136(AX), R12 + MOVQ 200(AX), CX + MOVQ CX, 56(SP) + MOVQ 176(AX), CX + MOVQ CX, 48(SP) + MOVQ 184(AX), AX + MOVQ AX, 40(SP) + MOVQ 40(SP), AX + ADDQ AX, 48(SP) + + // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) + ADDQ R10, 32(SP) + + // outBase += outPosition + ADDQ R12, R10 + +sequenceDecs_decodeSync_amd64_main_loop: + MOVQ (SP), R13 + + // Fill bitreader to have enough for the offset and match length. + CMPQ SI, $0x08 + JL sequenceDecs_decodeSync_amd64_fill_byte_by_byte + MOVQ BX, AX + SHRQ $0x03, AX + SUBQ AX, R13 + MOVQ (R13), DX + SUBQ AX, SI + ANDQ $0x07, BX + JMP sequenceDecs_decodeSync_amd64_fill_end + +sequenceDecs_decodeSync_amd64_fill_byte_by_byte: + CMPQ SI, $0x00 + JLE sequenceDecs_decodeSync_amd64_fill_check_overread + CMPQ BX, $0x07 + JLE sequenceDecs_decodeSync_amd64_fill_end + SHLQ $0x08, DX + SUBQ $0x01, R13 + SUBQ $0x01, SI + SUBQ $0x08, BX + MOVBQZX (R13), AX + ORQ AX, DX + JMP sequenceDecs_decodeSync_amd64_fill_byte_by_byte + +sequenceDecs_decodeSync_amd64_fill_check_overread: + CMPQ BX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_amd64_fill_end: + // Update offset + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decodeSync_amd64_of_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decodeSync_amd64_of_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decodeSync_amd64_of_update_zero + NEGQ CX + SHRQ CL, R14 + ADDQ R14, AX + +sequenceDecs_decodeSync_amd64_of_update_zero: + MOVQ AX, 8(SP) + + // Update match length + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decodeSync_amd64_ml_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decodeSync_amd64_ml_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decodeSync_amd64_ml_update_zero + NEGQ CX + SHRQ CL, R14 + ADDQ R14, AX + +sequenceDecs_decodeSync_amd64_ml_update_zero: + MOVQ AX, 16(SP) + + // Fill bitreader to have enough for the remaining + CMPQ SI, $0x08 + JL sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte + MOVQ BX, AX + SHRQ $0x03, AX + SUBQ AX, R13 + MOVQ (R13), DX + SUBQ AX, SI + ANDQ $0x07, BX + JMP sequenceDecs_decodeSync_amd64_fill_2_end + +sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte: + CMPQ SI, $0x00 + JLE sequenceDecs_decodeSync_amd64_fill_2_check_overread + CMPQ BX, $0x07 + JLE sequenceDecs_decodeSync_amd64_fill_2_end + SHLQ $0x08, DX + SUBQ $0x01, R13 + SUBQ $0x01, SI + SUBQ $0x08, BX + MOVBQZX (R13), AX + ORQ AX, DX + JMP sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte + +sequenceDecs_decodeSync_amd64_fill_2_check_overread: + CMPQ BX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_amd64_fill_2_end: + // Update literal length + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decodeSync_amd64_ll_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decodeSync_amd64_ll_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decodeSync_amd64_ll_update_zero + NEGQ CX + SHRQ CL, R14 + ADDQ R14, AX + +sequenceDecs_decodeSync_amd64_ll_update_zero: + MOVQ AX, 24(SP) + + // Fill bitreader for state updates + MOVQ R13, (SP) + MOVQ R9, AX + SHRQ $0x08, AX + MOVBQZX AL, AX + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decodeSync_amd64_skip_update + + // Update Literal Length State + MOVBQZX DI, R13 + SHRQ $0x10, DI + MOVWQZX DI, DI + LEAQ (BX)(R13*1), CX + MOVQ DX, R14 + MOVQ CX, BX + ROLQ CL, R14 + MOVL $0x00000001, R15 + MOVB R13, CL + SHLL CL, R15 + DECL R15 + ANDQ R15, R14 + ADDQ R14, DI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(DI*8), DI + + // Update Match Length State + MOVBQZX R8, R13 + SHRQ $0x10, R8 + MOVWQZX R8, R8 + LEAQ (BX)(R13*1), CX + MOVQ DX, R14 + MOVQ CX, BX + ROLQ CL, R14 + MOVL $0x00000001, R15 + MOVB R13, CL + SHLL CL, R15 + DECL R15 + ANDQ R15, R14 + ADDQ R14, R8 + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Offset State + MOVBQZX R9, R13 + SHRQ $0x10, R9 + MOVWQZX R9, R9 + LEAQ (BX)(R13*1), CX + MOVQ DX, R14 + MOVQ CX, BX + ROLQ CL, R14 + MOVL $0x00000001, R15 + MOVB R13, CL + SHLL CL, R15 + DECL R15 + ANDQ R15, R14 + ADDQ R14, R9 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R9*8), R9 + +sequenceDecs_decodeSync_amd64_skip_update: + // Adjust offset + MOVQ s+0(FP), CX + MOVQ 8(SP), R13 + CMPQ AX, $0x01 + JBE sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 + MOVUPS 144(CX), X0 + MOVQ R13, 144(CX) + MOVUPS X0, 152(CX) + JMP sequenceDecs_decodeSync_amd64_after_adjust + +sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0: + CMPQ 24(SP), $0x00000000 + JNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero + INCQ R13 + JMP sequenceDecs_decodeSync_amd64_adjust_offset_nonzero + +sequenceDecs_decodeSync_amd64_adjust_offset_maybezero: + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_amd64_adjust_offset_nonzero + MOVQ 144(CX), R13 + JMP sequenceDecs_decodeSync_amd64_after_adjust + +sequenceDecs_decodeSync_amd64_adjust_offset_nonzero: + MOVQ R13, AX + XORQ R14, R14 + MOVQ $-1, R15 + CMPQ R13, $0x03 + CMOVQEQ R14, AX + CMOVQEQ R15, R14 + ADDQ 144(CX)(AX*8), R14 + JNZ sequenceDecs_decodeSync_amd64_adjust_temp_valid + MOVQ $0x00000001, R14 + +sequenceDecs_decodeSync_amd64_adjust_temp_valid: + CMPQ R13, $0x01 + JZ sequenceDecs_decodeSync_amd64_adjust_skip + MOVQ 152(CX), AX + MOVQ AX, 160(CX) + +sequenceDecs_decodeSync_amd64_adjust_skip: + MOVQ 144(CX), AX + MOVQ AX, 152(CX) + MOVQ R14, 144(CX) + MOVQ R14, R13 + +sequenceDecs_decodeSync_amd64_after_adjust: + MOVQ R13, 8(SP) + + // Check values + MOVQ 16(SP), AX + MOVQ 24(SP), CX + LEAQ (AX)(CX*1), R14 + MOVQ s+0(FP), R15 + ADDQ R14, 256(R15) + MOVQ ctx+16(FP), R14 + SUBQ CX, 104(R14) + JS error_not_enough_literals + CMPQ AX, $0x00020002 + JA sequenceDecs_decodeSync_amd64_error_match_len_too_big + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_amd64_match_len_ofs_ok + TESTQ AX, AX + JNZ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch + +sequenceDecs_decodeSync_amd64_match_len_ofs_ok: + MOVQ 24(SP), AX + MOVQ 8(SP), CX + MOVQ 16(SP), R13 + + // Check if we have enough space in s.out + LEAQ (AX)(R13*1), R14 + ADDQ R10, R14 + CMPQ R14, 32(SP) + JA error_not_enough_space + + // Copy literals + TESTQ AX, AX + JZ check_offset + XORQ R14, R14 + +copy_1: + MOVUPS (R11)(R14*1), X0 + MOVUPS X0, (R10)(R14*1) + ADDQ $0x10, R14 + CMPQ R14, AX + JB copy_1 + ADDQ AX, R11 + ADDQ AX, R10 + ADDQ AX, R12 + + // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) +check_offset: + MOVQ R12, AX + ADDQ 40(SP), AX + CMPQ CX, AX + JG error_match_off_too_big + CMPQ CX, 56(SP) + JG error_match_off_too_big + + // Copy match from history + MOVQ CX, AX + SUBQ R12, AX + JLS copy_match + MOVQ 48(SP), R14 + SUBQ AX, R14 + CMPQ R13, AX + JG copy_all_from_history + MOVQ R13, AX + SUBQ $0x10, AX + JB copy_4_small + +copy_4_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R10) + ADDQ $0x10, R14 + ADDQ $0x10, R10 + SUBQ $0x10, AX + JAE copy_4_loop + LEAQ 16(R14)(AX*1), R14 + LEAQ 16(R10)(AX*1), R10 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R10) + JMP copy_4_end + +copy_4_small: + CMPQ R13, $0x03 + JE copy_4_move_3 + CMPQ R13, $0x08 + JB copy_4_move_4through7 + JMP copy_4_move_8through16 + +copy_4_move_3: + MOVW (R14), AX + MOVB 2(R14), CL + MOVW AX, (R10) + MOVB CL, 2(R10) + ADDQ R13, R14 + ADDQ R13, R10 + JMP copy_4_end + +copy_4_move_4through7: + MOVL (R14), AX + MOVL -4(R14)(R13*1), CX + MOVL AX, (R10) + MOVL CX, -4(R10)(R13*1) + ADDQ R13, R14 + ADDQ R13, R10 + JMP copy_4_end + +copy_4_move_8through16: + MOVQ (R14), AX + MOVQ -8(R14)(R13*1), CX + MOVQ AX, (R10) + MOVQ CX, -8(R10)(R13*1) + ADDQ R13, R14 + ADDQ R13, R10 + +copy_4_end: + ADDQ R13, R12 + JMP handle_loop + JMP loop_finished + +copy_all_from_history: + MOVQ AX, R15 + SUBQ $0x10, R15 + JB copy_5_small + +copy_5_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R10) + ADDQ $0x10, R14 + ADDQ $0x10, R10 + SUBQ $0x10, R15 + JAE copy_5_loop + LEAQ 16(R14)(R15*1), R14 + LEAQ 16(R10)(R15*1), R10 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R10) + JMP copy_5_end + +copy_5_small: + CMPQ AX, $0x03 + JE copy_5_move_3 + JB copy_5_move_1or2 + CMPQ AX, $0x08 + JB copy_5_move_4through7 + JMP copy_5_move_8through16 + +copy_5_move_1or2: + MOVB (R14), R15 + MOVB -1(R14)(AX*1), BP + MOVB R15, (R10) + MOVB BP, -1(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_5_end + +copy_5_move_3: + MOVW (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R10) + MOVB BP, 2(R10) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_5_end + +copy_5_move_4through7: + MOVL (R14), R15 + MOVL -4(R14)(AX*1), BP + MOVL R15, (R10) + MOVL BP, -4(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_5_end + +copy_5_move_8through16: + MOVQ (R14), R15 + MOVQ -8(R14)(AX*1), BP + MOVQ R15, (R10) + MOVQ BP, -8(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 + +copy_5_end: + ADDQ AX, R12 + SUBQ AX, R13 + + // Copy match from the current buffer +copy_match: + MOVQ R10, AX + SUBQ CX, AX + + // ml <= mo + CMPQ R13, CX + JA copy_overlapping_match + + // Copy non-overlapping match + ADDQ R13, R12 + MOVQ R10, CX + ADDQ R13, R10 + +copy_2: + MOVUPS (AX), X0 + MOVUPS X0, (CX) + ADDQ $0x10, AX + ADDQ $0x10, CX + SUBQ $0x10, R13 + JHI copy_2 + JMP handle_loop + + // Copy overlapping match +copy_overlapping_match: + ADDQ R13, R12 + +copy_slow_3: + MOVB (AX), CL + MOVB CL, (R10) + INCQ AX + INCQ R10 + DECQ R13 + JNZ copy_slow_3 + +handle_loop: + MOVQ ctx+16(FP), AX + DECQ 96(AX) + JNS sequenceDecs_decodeSync_amd64_main_loop + +loop_finished: + MOVQ br+8(FP), AX + MOVQ DX, 24(AX) + MOVB BL, 32(AX) + MOVQ SI, 8(AX) + + // Update the context + MOVQ ctx+16(FP), AX + MOVQ R12, 136(AX) + MOVQ 144(AX), CX + SUBQ CX, R11 + MOVQ R11, 168(AX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: + MOVQ 16(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 216(CX) + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decodeSync_amd64_error_match_len_too_big: + MOVQ ctx+16(FP), AX + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error +error_match_off_too_big: + MOVQ ctx+16(FP), AX + MOVQ 8(SP), CX + MOVQ CX, 224(AX) + MOVQ R12, 136(AX) + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + + // Return with not enough output space error +error_not_enough_space: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ R12, 136(AX) + MOVQ $0x00000005, ret+24(FP) + RET + +// func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int +// Requires: BMI, BMI2, CMOV, SSE +TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 + MOVQ br+8(FP), BX + MOVQ 24(BX), AX + MOVBQZX 32(BX), DX + MOVQ (BX), CX + MOVQ 8(BX), BX + ADDQ BX, CX + MOVQ CX, (SP) + MOVQ ctx+16(FP), CX + MOVQ 72(CX), SI + MOVQ 80(CX), DI + MOVQ 88(CX), R8 + XORQ R9, R9 + MOVQ R9, 8(SP) + MOVQ R9, 16(SP) + MOVQ R9, 24(SP) + MOVQ 112(CX), R9 + MOVQ 128(CX), R10 + MOVQ R10, 32(SP) + MOVQ 144(CX), R10 + MOVQ 136(CX), R11 + MOVQ 200(CX), R12 + MOVQ R12, 56(SP) + MOVQ 176(CX), R12 + MOVQ R12, 48(SP) + MOVQ 184(CX), CX + MOVQ CX, 40(SP) + MOVQ 40(SP), CX + ADDQ CX, 48(SP) + + // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) + ADDQ R9, 32(SP) + + // outBase += outPosition + ADDQ R11, R9 + +sequenceDecs_decodeSync_bmi2_main_loop: + MOVQ (SP), R12 + + // Fill bitreader to have enough for the offset and match length. + CMPQ BX, $0x08 + JL sequenceDecs_decodeSync_bmi2_fill_byte_by_byte + MOVQ DX, CX + SHRQ $0x03, CX + SUBQ CX, R12 + MOVQ (R12), AX + SUBQ CX, BX + ANDQ $0x07, DX + JMP sequenceDecs_decodeSync_bmi2_fill_end + +sequenceDecs_decodeSync_bmi2_fill_byte_by_byte: + CMPQ BX, $0x00 + JLE sequenceDecs_decodeSync_bmi2_fill_check_overread + CMPQ DX, $0x07 + JLE sequenceDecs_decodeSync_bmi2_fill_end + SHLQ $0x08, AX + SUBQ $0x01, R12 + SUBQ $0x01, BX + SUBQ $0x08, DX + MOVBQZX (R12), CX + ORQ CX, AX + JMP sequenceDecs_decodeSync_bmi2_fill_byte_by_byte + +sequenceDecs_decodeSync_bmi2_fill_check_overread: + CMPQ DX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_bmi2_fill_end: + // Update offset + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R13 + MOVQ AX, R14 + LEAQ (DX)(R13*1), CX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + MOVQ CX, DX + MOVQ R8, CX + SHRQ $0x20, CX + ADDQ R14, CX + MOVQ CX, 8(SP) + + // Update match length + MOVQ $0x00000808, CX + BEXTRQ CX, DI, R13 + MOVQ AX, R14 + LEAQ (DX)(R13*1), CX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + MOVQ CX, DX + MOVQ DI, CX + SHRQ $0x20, CX + ADDQ R14, CX + MOVQ CX, 16(SP) + + // Fill bitreader to have enough for the remaining + CMPQ BX, $0x08 + JL sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte + MOVQ DX, CX + SHRQ $0x03, CX + SUBQ CX, R12 + MOVQ (R12), AX + SUBQ CX, BX + ANDQ $0x07, DX + JMP sequenceDecs_decodeSync_bmi2_fill_2_end + +sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte: + CMPQ BX, $0x00 + JLE sequenceDecs_decodeSync_bmi2_fill_2_check_overread + CMPQ DX, $0x07 + JLE sequenceDecs_decodeSync_bmi2_fill_2_end + SHLQ $0x08, AX + SUBQ $0x01, R12 + SUBQ $0x01, BX + SUBQ $0x08, DX + MOVBQZX (R12), CX + ORQ CX, AX + JMP sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte + +sequenceDecs_decodeSync_bmi2_fill_2_check_overread: + CMPQ DX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_bmi2_fill_2_end: + // Update literal length + MOVQ $0x00000808, CX + BEXTRQ CX, SI, R13 + MOVQ AX, R14 + LEAQ (DX)(R13*1), CX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + MOVQ CX, DX + MOVQ SI, CX + SHRQ $0x20, CX + ADDQ R14, CX + MOVQ CX, 24(SP) + + // Fill bitreader for state updates + MOVQ R12, (SP) + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R12 + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decodeSync_bmi2_skip_update + LEAQ (SI)(DI*1), R13 + ADDQ R8, R13 + MOVBQZX R13, R13 + LEAQ (DX)(R13*1), CX + MOVQ AX, R14 + MOVQ CX, DX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + + // Update Offset State + BZHIQ R8, R14, CX + SHRXQ R8, R14, R14 + MOVQ $0x00001010, R13 + BEXTRQ R13, R8, R8 + ADDQ CX, R8 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Match Length State + BZHIQ DI, R14, CX + SHRXQ DI, R14, R14 + MOVQ $0x00001010, R13 + BEXTRQ R13, DI, DI + ADDQ CX, DI + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(DI*8), DI + + // Update Literal Length State + BZHIQ SI, R14, CX + MOVQ $0x00001010, R13 + BEXTRQ R13, SI, SI + ADDQ CX, SI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(SI*8), SI + +sequenceDecs_decodeSync_bmi2_skip_update: + // Adjust offset + MOVQ s+0(FP), CX + MOVQ 8(SP), R13 + CMPQ R12, $0x01 + JBE sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0 + MOVUPS 144(CX), X0 + MOVQ R13, 144(CX) + MOVUPS X0, 152(CX) + JMP sequenceDecs_decodeSync_bmi2_after_adjust + +sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0: + CMPQ 24(SP), $0x00000000 + JNE sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero + INCQ R13 + JMP sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero + +sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero: + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero + MOVQ 144(CX), R13 + JMP sequenceDecs_decodeSync_bmi2_after_adjust + +sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero: + MOVQ R13, R12 + XORQ R14, R14 + MOVQ $-1, R15 + CMPQ R13, $0x03 + CMOVQEQ R14, R12 + CMOVQEQ R15, R14 + ADDQ 144(CX)(R12*8), R14 + JNZ sequenceDecs_decodeSync_bmi2_adjust_temp_valid + MOVQ $0x00000001, R14 + +sequenceDecs_decodeSync_bmi2_adjust_temp_valid: + CMPQ R13, $0x01 + JZ sequenceDecs_decodeSync_bmi2_adjust_skip + MOVQ 152(CX), R12 + MOVQ R12, 160(CX) + +sequenceDecs_decodeSync_bmi2_adjust_skip: + MOVQ 144(CX), R12 + MOVQ R12, 152(CX) + MOVQ R14, 144(CX) + MOVQ R14, R13 + +sequenceDecs_decodeSync_bmi2_after_adjust: + MOVQ R13, 8(SP) + + // Check values + MOVQ 16(SP), CX + MOVQ 24(SP), R12 + LEAQ (CX)(R12*1), R14 + MOVQ s+0(FP), R15 + ADDQ R14, 256(R15) + MOVQ ctx+16(FP), R14 + SUBQ R12, 104(R14) + JS error_not_enough_literals + CMPQ CX, $0x00020002 + JA sequenceDecs_decodeSync_bmi2_error_match_len_too_big + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_bmi2_match_len_ofs_ok + TESTQ CX, CX + JNZ sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch + +sequenceDecs_decodeSync_bmi2_match_len_ofs_ok: + MOVQ 24(SP), CX + MOVQ 8(SP), R12 + MOVQ 16(SP), R13 + + // Check if we have enough space in s.out + LEAQ (CX)(R13*1), R14 + ADDQ R9, R14 + CMPQ R14, 32(SP) + JA error_not_enough_space + + // Copy literals + TESTQ CX, CX + JZ check_offset + XORQ R14, R14 + +copy_1: + MOVUPS (R10)(R14*1), X0 + MOVUPS X0, (R9)(R14*1) + ADDQ $0x10, R14 + CMPQ R14, CX + JB copy_1 + ADDQ CX, R10 + ADDQ CX, R9 + ADDQ CX, R11 + + // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) +check_offset: + MOVQ R11, CX + ADDQ 40(SP), CX + CMPQ R12, CX + JG error_match_off_too_big + CMPQ R12, 56(SP) + JG error_match_off_too_big + + // Copy match from history + MOVQ R12, CX + SUBQ R11, CX + JLS copy_match + MOVQ 48(SP), R14 + SUBQ CX, R14 + CMPQ R13, CX + JG copy_all_from_history + MOVQ R13, CX + SUBQ $0x10, CX + JB copy_4_small + +copy_4_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R9) + ADDQ $0x10, R14 + ADDQ $0x10, R9 + SUBQ $0x10, CX + JAE copy_4_loop + LEAQ 16(R14)(CX*1), R14 + LEAQ 16(R9)(CX*1), R9 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R9) + JMP copy_4_end + +copy_4_small: + CMPQ R13, $0x03 + JE copy_4_move_3 + CMPQ R13, $0x08 + JB copy_4_move_4through7 + JMP copy_4_move_8through16 + +copy_4_move_3: + MOVW (R14), CX + MOVB 2(R14), R12 + MOVW CX, (R9) + MOVB R12, 2(R9) + ADDQ R13, R14 + ADDQ R13, R9 + JMP copy_4_end + +copy_4_move_4through7: + MOVL (R14), CX + MOVL -4(R14)(R13*1), R12 + MOVL CX, (R9) + MOVL R12, -4(R9)(R13*1) + ADDQ R13, R14 + ADDQ R13, R9 + JMP copy_4_end + +copy_4_move_8through16: + MOVQ (R14), CX + MOVQ -8(R14)(R13*1), R12 + MOVQ CX, (R9) + MOVQ R12, -8(R9)(R13*1) + ADDQ R13, R14 + ADDQ R13, R9 + +copy_4_end: + ADDQ R13, R11 + JMP handle_loop + JMP loop_finished + +copy_all_from_history: + MOVQ CX, R15 + SUBQ $0x10, R15 + JB copy_5_small + +copy_5_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R9) + ADDQ $0x10, R14 + ADDQ $0x10, R9 + SUBQ $0x10, R15 + JAE copy_5_loop + LEAQ 16(R14)(R15*1), R14 + LEAQ 16(R9)(R15*1), R9 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R9) + JMP copy_5_end + +copy_5_small: + CMPQ CX, $0x03 + JE copy_5_move_3 + JB copy_5_move_1or2 + CMPQ CX, $0x08 + JB copy_5_move_4through7 + JMP copy_5_move_8through16 + +copy_5_move_1or2: + MOVB (R14), R15 + MOVB -1(R14)(CX*1), BP + MOVB R15, (R9) + MOVB BP, -1(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_5_end + +copy_5_move_3: + MOVW (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R9) + MOVB BP, 2(R9) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_5_end + +copy_5_move_4through7: + MOVL (R14), R15 + MOVL -4(R14)(CX*1), BP + MOVL R15, (R9) + MOVL BP, -4(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_5_end + +copy_5_move_8through16: + MOVQ (R14), R15 + MOVQ -8(R14)(CX*1), BP + MOVQ R15, (R9) + MOVQ BP, -8(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 + +copy_5_end: + ADDQ CX, R11 + SUBQ CX, R13 + + // Copy match from the current buffer +copy_match: + MOVQ R9, CX + SUBQ R12, CX + + // ml <= mo + CMPQ R13, R12 + JA copy_overlapping_match + + // Copy non-overlapping match + ADDQ R13, R11 + MOVQ R9, R12 + ADDQ R13, R9 + +copy_2: + MOVUPS (CX), X0 + MOVUPS X0, (R12) + ADDQ $0x10, CX + ADDQ $0x10, R12 + SUBQ $0x10, R13 + JHI copy_2 + JMP handle_loop + + // Copy overlapping match +copy_overlapping_match: + ADDQ R13, R11 + +copy_slow_3: + MOVB (CX), R12 + MOVB R12, (R9) + INCQ CX + INCQ R9 + DECQ R13 + JNZ copy_slow_3 + +handle_loop: + MOVQ ctx+16(FP), CX + DECQ 96(CX) + JNS sequenceDecs_decodeSync_bmi2_main_loop + +loop_finished: + MOVQ br+8(FP), CX + MOVQ AX, 24(CX) + MOVB DL, 32(CX) + MOVQ BX, 8(CX) + + // Update the context + MOVQ ctx+16(FP), AX + MOVQ R11, 136(AX) + MOVQ 144(AX), CX + SUBQ CX, R10 + MOVQ R10, 168(AX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch: + MOVQ 16(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 216(CX) + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decodeSync_bmi2_error_match_len_too_big: + MOVQ ctx+16(FP), AX + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error +error_match_off_too_big: + MOVQ ctx+16(FP), AX + MOVQ 8(SP), CX + MOVQ CX, 224(AX) + MOVQ R11, 136(AX) + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + + // Return with not enough output space error +error_not_enough_space: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ R11, 136(AX) + MOVQ $0x00000005, ret+24(FP) + RET + +// func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int +// Requires: CMOV, SSE +TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 + MOVQ br+8(FP), CX + MOVQ 24(CX), DX + MOVBQZX 32(CX), BX + MOVQ (CX), AX + MOVQ 8(CX), SI + ADDQ SI, AX + MOVQ AX, (SP) + MOVQ ctx+16(FP), AX + MOVQ 72(AX), DI + MOVQ 80(AX), R8 + MOVQ 88(AX), R9 + XORQ CX, CX + MOVQ CX, 8(SP) + MOVQ CX, 16(SP) + MOVQ CX, 24(SP) + MOVQ 112(AX), R10 + MOVQ 128(AX), CX + MOVQ CX, 32(SP) + MOVQ 144(AX), R11 + MOVQ 136(AX), R12 + MOVQ 200(AX), CX + MOVQ CX, 56(SP) + MOVQ 176(AX), CX + MOVQ CX, 48(SP) + MOVQ 184(AX), AX + MOVQ AX, 40(SP) + MOVQ 40(SP), AX + ADDQ AX, 48(SP) + + // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) + ADDQ R10, 32(SP) + + // outBase += outPosition + ADDQ R12, R10 + +sequenceDecs_decodeSync_safe_amd64_main_loop: + MOVQ (SP), R13 + + // Fill bitreader to have enough for the offset and match length. + CMPQ SI, $0x08 + JL sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte + MOVQ BX, AX + SHRQ $0x03, AX + SUBQ AX, R13 + MOVQ (R13), DX + SUBQ AX, SI + ANDQ $0x07, BX + JMP sequenceDecs_decodeSync_safe_amd64_fill_end + +sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte: + CMPQ SI, $0x00 + JLE sequenceDecs_decodeSync_safe_amd64_fill_check_overread + CMPQ BX, $0x07 + JLE sequenceDecs_decodeSync_safe_amd64_fill_end + SHLQ $0x08, DX + SUBQ $0x01, R13 + SUBQ $0x01, SI + SUBQ $0x08, BX + MOVBQZX (R13), AX + ORQ AX, DX + JMP sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte + +sequenceDecs_decodeSync_safe_amd64_fill_check_overread: + CMPQ BX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_safe_amd64_fill_end: + // Update offset + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decodeSync_safe_amd64_of_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decodeSync_safe_amd64_of_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decodeSync_safe_amd64_of_update_zero + NEGQ CX + SHRQ CL, R14 + ADDQ R14, AX + +sequenceDecs_decodeSync_safe_amd64_of_update_zero: + MOVQ AX, 8(SP) + + // Update match length + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decodeSync_safe_amd64_ml_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decodeSync_safe_amd64_ml_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decodeSync_safe_amd64_ml_update_zero + NEGQ CX + SHRQ CL, R14 + ADDQ R14, AX + +sequenceDecs_decodeSync_safe_amd64_ml_update_zero: + MOVQ AX, 16(SP) + + // Fill bitreader to have enough for the remaining + CMPQ SI, $0x08 + JL sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte + MOVQ BX, AX + SHRQ $0x03, AX + SUBQ AX, R13 + MOVQ (R13), DX + SUBQ AX, SI + ANDQ $0x07, BX + JMP sequenceDecs_decodeSync_safe_amd64_fill_2_end + +sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte: + CMPQ SI, $0x00 + JLE sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread + CMPQ BX, $0x07 + JLE sequenceDecs_decodeSync_safe_amd64_fill_2_end + SHLQ $0x08, DX + SUBQ $0x01, R13 + SUBQ $0x01, SI + SUBQ $0x08, BX + MOVBQZX (R13), AX + ORQ AX, DX + JMP sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte + +sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread: + CMPQ BX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_safe_amd64_fill_2_end: + // Update literal length + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + MOVB AH, CL + SHRQ $0x20, AX + TESTQ CX, CX + JZ sequenceDecs_decodeSync_safe_amd64_ll_update_zero + ADDQ CX, BX + CMPQ BX, $0x40 + JA sequenceDecs_decodeSync_safe_amd64_ll_update_zero + CMPQ CX, $0x40 + JAE sequenceDecs_decodeSync_safe_amd64_ll_update_zero + NEGQ CX + SHRQ CL, R14 + ADDQ R14, AX + +sequenceDecs_decodeSync_safe_amd64_ll_update_zero: + MOVQ AX, 24(SP) + + // Fill bitreader for state updates + MOVQ R13, (SP) + MOVQ R9, AX + SHRQ $0x08, AX + MOVBQZX AL, AX + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decodeSync_safe_amd64_skip_update + + // Update Literal Length State + MOVBQZX DI, R13 + SHRQ $0x10, DI + MOVWQZX DI, DI + LEAQ (BX)(R13*1), CX + MOVQ DX, R14 + MOVQ CX, BX + ROLQ CL, R14 + MOVL $0x00000001, R15 + MOVB R13, CL + SHLL CL, R15 + DECL R15 + ANDQ R15, R14 + ADDQ R14, DI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(DI*8), DI + + // Update Match Length State + MOVBQZX R8, R13 + SHRQ $0x10, R8 + MOVWQZX R8, R8 + LEAQ (BX)(R13*1), CX + MOVQ DX, R14 + MOVQ CX, BX + ROLQ CL, R14 + MOVL $0x00000001, R15 + MOVB R13, CL + SHLL CL, R15 + DECL R15 + ANDQ R15, R14 + ADDQ R14, R8 + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Offset State + MOVBQZX R9, R13 + SHRQ $0x10, R9 + MOVWQZX R9, R9 + LEAQ (BX)(R13*1), CX + MOVQ DX, R14 + MOVQ CX, BX + ROLQ CL, R14 + MOVL $0x00000001, R15 + MOVB R13, CL + SHLL CL, R15 + DECL R15 + ANDQ R15, R14 + ADDQ R14, R9 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R9*8), R9 + +sequenceDecs_decodeSync_safe_amd64_skip_update: + // Adjust offset + MOVQ s+0(FP), CX + MOVQ 8(SP), R13 + CMPQ AX, $0x01 + JBE sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 + MOVUPS 144(CX), X0 + MOVQ R13, 144(CX) + MOVUPS X0, 152(CX) + JMP sequenceDecs_decodeSync_safe_amd64_after_adjust + +sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0: + CMPQ 24(SP), $0x00000000 + JNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero + INCQ R13 + JMP sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero + +sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero: + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero + MOVQ 144(CX), R13 + JMP sequenceDecs_decodeSync_safe_amd64_after_adjust + +sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero: + MOVQ R13, AX + XORQ R14, R14 + MOVQ $-1, R15 + CMPQ R13, $0x03 + CMOVQEQ R14, AX + CMOVQEQ R15, R14 + ADDQ 144(CX)(AX*8), R14 + JNZ sequenceDecs_decodeSync_safe_amd64_adjust_temp_valid + MOVQ $0x00000001, R14 + +sequenceDecs_decodeSync_safe_amd64_adjust_temp_valid: + CMPQ R13, $0x01 + JZ sequenceDecs_decodeSync_safe_amd64_adjust_skip + MOVQ 152(CX), AX + MOVQ AX, 160(CX) + +sequenceDecs_decodeSync_safe_amd64_adjust_skip: + MOVQ 144(CX), AX + MOVQ AX, 152(CX) + MOVQ R14, 144(CX) + MOVQ R14, R13 + +sequenceDecs_decodeSync_safe_amd64_after_adjust: + MOVQ R13, 8(SP) + + // Check values + MOVQ 16(SP), AX + MOVQ 24(SP), CX + LEAQ (AX)(CX*1), R14 + MOVQ s+0(FP), R15 + ADDQ R14, 256(R15) + MOVQ ctx+16(FP), R14 + SUBQ CX, 104(R14) + JS error_not_enough_literals + CMPQ AX, $0x00020002 + JA sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok + TESTQ AX, AX + JNZ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch + +sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok: + MOVQ 24(SP), AX + MOVQ 8(SP), CX + MOVQ 16(SP), R13 + + // Check if we have enough space in s.out + LEAQ (AX)(R13*1), R14 + ADDQ R10, R14 + CMPQ R14, 32(SP) + JA error_not_enough_space + + // Copy literals + TESTQ AX, AX + JZ check_offset + MOVQ AX, R14 + SUBQ $0x10, R14 + JB copy_1_small + +copy_1_loop: + MOVUPS (R11), X0 + MOVUPS X0, (R10) + ADDQ $0x10, R11 + ADDQ $0x10, R10 + SUBQ $0x10, R14 + JAE copy_1_loop + LEAQ 16(R11)(R14*1), R11 + LEAQ 16(R10)(R14*1), R10 + MOVUPS -16(R11), X0 + MOVUPS X0, -16(R10) + JMP copy_1_end + +copy_1_small: + CMPQ AX, $0x03 + JE copy_1_move_3 + JB copy_1_move_1or2 + CMPQ AX, $0x08 + JB copy_1_move_4through7 + JMP copy_1_move_8through16 + +copy_1_move_1or2: + MOVB (R11), R14 + MOVB -1(R11)(AX*1), R15 + MOVB R14, (R10) + MOVB R15, -1(R10)(AX*1) + ADDQ AX, R11 + ADDQ AX, R10 + JMP copy_1_end + +copy_1_move_3: + MOVW (R11), R14 + MOVB 2(R11), R15 + MOVW R14, (R10) + MOVB R15, 2(R10) + ADDQ AX, R11 + ADDQ AX, R10 + JMP copy_1_end + +copy_1_move_4through7: + MOVL (R11), R14 + MOVL -4(R11)(AX*1), R15 + MOVL R14, (R10) + MOVL R15, -4(R10)(AX*1) + ADDQ AX, R11 + ADDQ AX, R10 + JMP copy_1_end + +copy_1_move_8through16: + MOVQ (R11), R14 + MOVQ -8(R11)(AX*1), R15 + MOVQ R14, (R10) + MOVQ R15, -8(R10)(AX*1) + ADDQ AX, R11 + ADDQ AX, R10 + +copy_1_end: + ADDQ AX, R12 + + // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) +check_offset: + MOVQ R12, AX + ADDQ 40(SP), AX + CMPQ CX, AX + JG error_match_off_too_big + CMPQ CX, 56(SP) + JG error_match_off_too_big + + // Copy match from history + MOVQ CX, AX + SUBQ R12, AX + JLS copy_match + MOVQ 48(SP), R14 + SUBQ AX, R14 + CMPQ R13, AX + JG copy_all_from_history + MOVQ R13, AX + SUBQ $0x10, AX + JB copy_4_small + +copy_4_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R10) + ADDQ $0x10, R14 + ADDQ $0x10, R10 + SUBQ $0x10, AX + JAE copy_4_loop + LEAQ 16(R14)(AX*1), R14 + LEAQ 16(R10)(AX*1), R10 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R10) + JMP copy_4_end + +copy_4_small: + CMPQ R13, $0x03 + JE copy_4_move_3 + CMPQ R13, $0x08 + JB copy_4_move_4through7 + JMP copy_4_move_8through16 + +copy_4_move_3: + MOVW (R14), AX + MOVB 2(R14), CL + MOVW AX, (R10) + MOVB CL, 2(R10) + ADDQ R13, R14 + ADDQ R13, R10 + JMP copy_4_end + +copy_4_move_4through7: + MOVL (R14), AX + MOVL -4(R14)(R13*1), CX + MOVL AX, (R10) + MOVL CX, -4(R10)(R13*1) + ADDQ R13, R14 + ADDQ R13, R10 + JMP copy_4_end + +copy_4_move_8through16: + MOVQ (R14), AX + MOVQ -8(R14)(R13*1), CX + MOVQ AX, (R10) + MOVQ CX, -8(R10)(R13*1) + ADDQ R13, R14 + ADDQ R13, R10 + +copy_4_end: + ADDQ R13, R12 + JMP handle_loop + JMP loop_finished + +copy_all_from_history: + MOVQ AX, R15 + SUBQ $0x10, R15 + JB copy_5_small + +copy_5_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R10) + ADDQ $0x10, R14 + ADDQ $0x10, R10 + SUBQ $0x10, R15 + JAE copy_5_loop + LEAQ 16(R14)(R15*1), R14 + LEAQ 16(R10)(R15*1), R10 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R10) + JMP copy_5_end + +copy_5_small: + CMPQ AX, $0x03 + JE copy_5_move_3 + JB copy_5_move_1or2 + CMPQ AX, $0x08 + JB copy_5_move_4through7 + JMP copy_5_move_8through16 + +copy_5_move_1or2: + MOVB (R14), R15 + MOVB -1(R14)(AX*1), BP + MOVB R15, (R10) + MOVB BP, -1(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_5_end + +copy_5_move_3: + MOVW (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R10) + MOVB BP, 2(R10) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_5_end + +copy_5_move_4through7: + MOVL (R14), R15 + MOVL -4(R14)(AX*1), BP + MOVL R15, (R10) + MOVL BP, -4(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_5_end + +copy_5_move_8through16: + MOVQ (R14), R15 + MOVQ -8(R14)(AX*1), BP + MOVQ R15, (R10) + MOVQ BP, -8(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 + +copy_5_end: + ADDQ AX, R12 + SUBQ AX, R13 + + // Copy match from the current buffer +copy_match: + MOVQ R10, AX + SUBQ CX, AX + + // ml <= mo + CMPQ R13, CX + JA copy_overlapping_match + + // Copy non-overlapping match + ADDQ R13, R12 + MOVQ R13, CX + SUBQ $0x10, CX + JB copy_2_small + +copy_2_loop: + MOVUPS (AX), X0 + MOVUPS X0, (R10) + ADDQ $0x10, AX + ADDQ $0x10, R10 + SUBQ $0x10, CX + JAE copy_2_loop + LEAQ 16(AX)(CX*1), AX + LEAQ 16(R10)(CX*1), R10 + MOVUPS -16(AX), X0 + MOVUPS X0, -16(R10) + JMP copy_2_end + +copy_2_small: + CMPQ R13, $0x03 + JE copy_2_move_3 + JB copy_2_move_1or2 + CMPQ R13, $0x08 + JB copy_2_move_4through7 + JMP copy_2_move_8through16 + +copy_2_move_1or2: + MOVB (AX), CL + MOVB -1(AX)(R13*1), R14 + MOVB CL, (R10) + MOVB R14, -1(R10)(R13*1) + ADDQ R13, AX + ADDQ R13, R10 + JMP copy_2_end + +copy_2_move_3: + MOVW (AX), CX + MOVB 2(AX), R14 + MOVW CX, (R10) + MOVB R14, 2(R10) + ADDQ R13, AX + ADDQ R13, R10 + JMP copy_2_end + +copy_2_move_4through7: + MOVL (AX), CX + MOVL -4(AX)(R13*1), R14 + MOVL CX, (R10) + MOVL R14, -4(R10)(R13*1) + ADDQ R13, AX + ADDQ R13, R10 + JMP copy_2_end + +copy_2_move_8through16: + MOVQ (AX), CX + MOVQ -8(AX)(R13*1), R14 + MOVQ CX, (R10) + MOVQ R14, -8(R10)(R13*1) + ADDQ R13, AX + ADDQ R13, R10 + +copy_2_end: + JMP handle_loop + + // Copy overlapping match +copy_overlapping_match: + ADDQ R13, R12 + +copy_slow_3: + MOVB (AX), CL + MOVB CL, (R10) + INCQ AX + INCQ R10 + DECQ R13 + JNZ copy_slow_3 + +handle_loop: + MOVQ ctx+16(FP), AX + DECQ 96(AX) + JNS sequenceDecs_decodeSync_safe_amd64_main_loop + +loop_finished: + MOVQ br+8(FP), AX + MOVQ DX, 24(AX) + MOVB BL, 32(AX) + MOVQ SI, 8(AX) + + // Update the context + MOVQ ctx+16(FP), AX + MOVQ R12, 136(AX) + MOVQ 144(AX), CX + SUBQ CX, R11 + MOVQ R11, 168(AX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: + MOVQ 16(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 216(CX) + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: + MOVQ ctx+16(FP), AX + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error +error_match_off_too_big: + MOVQ ctx+16(FP), AX + MOVQ 8(SP), CX + MOVQ CX, 224(AX) + MOVQ R12, 136(AX) + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + + // Return with not enough output space error +error_not_enough_space: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ R12, 136(AX) + MOVQ $0x00000005, ret+24(FP) + RET + +// func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int +// Requires: BMI, BMI2, CMOV, SSE +TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 + MOVQ br+8(FP), BX + MOVQ 24(BX), AX + MOVBQZX 32(BX), DX + MOVQ (BX), CX + MOVQ 8(BX), BX + ADDQ BX, CX + MOVQ CX, (SP) + MOVQ ctx+16(FP), CX + MOVQ 72(CX), SI + MOVQ 80(CX), DI + MOVQ 88(CX), R8 + XORQ R9, R9 + MOVQ R9, 8(SP) + MOVQ R9, 16(SP) + MOVQ R9, 24(SP) + MOVQ 112(CX), R9 + MOVQ 128(CX), R10 + MOVQ R10, 32(SP) + MOVQ 144(CX), R10 + MOVQ 136(CX), R11 + MOVQ 200(CX), R12 + MOVQ R12, 56(SP) + MOVQ 176(CX), R12 + MOVQ R12, 48(SP) + MOVQ 184(CX), CX + MOVQ CX, 40(SP) + MOVQ 40(SP), CX + ADDQ CX, 48(SP) + + // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) + ADDQ R9, 32(SP) + + // outBase += outPosition + ADDQ R11, R9 + +sequenceDecs_decodeSync_safe_bmi2_main_loop: + MOVQ (SP), R12 + + // Fill bitreader to have enough for the offset and match length. + CMPQ BX, $0x08 + JL sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte + MOVQ DX, CX + SHRQ $0x03, CX + SUBQ CX, R12 + MOVQ (R12), AX + SUBQ CX, BX + ANDQ $0x07, DX + JMP sequenceDecs_decodeSync_safe_bmi2_fill_end + +sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte: + CMPQ BX, $0x00 + JLE sequenceDecs_decodeSync_safe_bmi2_fill_check_overread + CMPQ DX, $0x07 + JLE sequenceDecs_decodeSync_safe_bmi2_fill_end + SHLQ $0x08, AX + SUBQ $0x01, R12 + SUBQ $0x01, BX + SUBQ $0x08, DX + MOVBQZX (R12), CX + ORQ CX, AX + JMP sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte + +sequenceDecs_decodeSync_safe_bmi2_fill_check_overread: + CMPQ DX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_safe_bmi2_fill_end: + // Update offset + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R13 + MOVQ AX, R14 + LEAQ (DX)(R13*1), CX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + MOVQ CX, DX + MOVQ R8, CX + SHRQ $0x20, CX + ADDQ R14, CX + MOVQ CX, 8(SP) + + // Update match length + MOVQ $0x00000808, CX + BEXTRQ CX, DI, R13 + MOVQ AX, R14 + LEAQ (DX)(R13*1), CX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + MOVQ CX, DX + MOVQ DI, CX + SHRQ $0x20, CX + ADDQ R14, CX + MOVQ CX, 16(SP) + + // Fill bitreader to have enough for the remaining + CMPQ BX, $0x08 + JL sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte + MOVQ DX, CX + SHRQ $0x03, CX + SUBQ CX, R12 + MOVQ (R12), AX + SUBQ CX, BX + ANDQ $0x07, DX + JMP sequenceDecs_decodeSync_safe_bmi2_fill_2_end + +sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte: + CMPQ BX, $0x00 + JLE sequenceDecs_decodeSync_safe_bmi2_fill_2_check_overread + CMPQ DX, $0x07 + JLE sequenceDecs_decodeSync_safe_bmi2_fill_2_end + SHLQ $0x08, AX + SUBQ $0x01, R12 + SUBQ $0x01, BX + SUBQ $0x08, DX + MOVBQZX (R12), CX + ORQ CX, AX + JMP sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte + +sequenceDecs_decodeSync_safe_bmi2_fill_2_check_overread: + CMPQ DX, $0x40 + JA error_overread + +sequenceDecs_decodeSync_safe_bmi2_fill_2_end: + // Update literal length + MOVQ $0x00000808, CX + BEXTRQ CX, SI, R13 + MOVQ AX, R14 + LEAQ (DX)(R13*1), CX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + MOVQ CX, DX + MOVQ SI, CX + SHRQ $0x20, CX + ADDQ R14, CX + MOVQ CX, 24(SP) + + // Fill bitreader for state updates + MOVQ R12, (SP) + MOVQ $0x00000808, CX + BEXTRQ CX, R8, R12 + MOVQ ctx+16(FP), CX + CMPQ 96(CX), $0x00 + JZ sequenceDecs_decodeSync_safe_bmi2_skip_update + LEAQ (SI)(DI*1), R13 + ADDQ R8, R13 + MOVBQZX R13, R13 + LEAQ (DX)(R13*1), CX + MOVQ AX, R14 + MOVQ CX, DX + ROLQ CL, R14 + BZHIQ R13, R14, R14 + + // Update Offset State + BZHIQ R8, R14, CX + SHRXQ R8, R14, R14 + MOVQ $0x00001010, R13 + BEXTRQ R13, R8, R8 + ADDQ CX, R8 + + // Load ctx.ofTable + MOVQ ctx+16(FP), CX + MOVQ 48(CX), CX + MOVQ (CX)(R8*8), R8 + + // Update Match Length State + BZHIQ DI, R14, CX + SHRXQ DI, R14, R14 + MOVQ $0x00001010, R13 + BEXTRQ R13, DI, DI + ADDQ CX, DI + + // Load ctx.mlTable + MOVQ ctx+16(FP), CX + MOVQ 24(CX), CX + MOVQ (CX)(DI*8), DI + + // Update Literal Length State + BZHIQ SI, R14, CX + MOVQ $0x00001010, R13 + BEXTRQ R13, SI, SI + ADDQ CX, SI + + // Load ctx.llTable + MOVQ ctx+16(FP), CX + MOVQ (CX), CX + MOVQ (CX)(SI*8), SI + +sequenceDecs_decodeSync_safe_bmi2_skip_update: + // Adjust offset + MOVQ s+0(FP), CX + MOVQ 8(SP), R13 + CMPQ R12, $0x01 + JBE sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0 + MOVUPS 144(CX), X0 + MOVQ R13, 144(CX) + MOVUPS X0, 152(CX) + JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust + +sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0: + CMPQ 24(SP), $0x00000000 + JNE sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero + INCQ R13 + JMP sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero + +sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero: + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero + MOVQ 144(CX), R13 + JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust + +sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero: + MOVQ R13, R12 + XORQ R14, R14 + MOVQ $-1, R15 + CMPQ R13, $0x03 + CMOVQEQ R14, R12 + CMOVQEQ R15, R14 + ADDQ 144(CX)(R12*8), R14 + JNZ sequenceDecs_decodeSync_safe_bmi2_adjust_temp_valid + MOVQ $0x00000001, R14 + +sequenceDecs_decodeSync_safe_bmi2_adjust_temp_valid: + CMPQ R13, $0x01 + JZ sequenceDecs_decodeSync_safe_bmi2_adjust_skip + MOVQ 152(CX), R12 + MOVQ R12, 160(CX) + +sequenceDecs_decodeSync_safe_bmi2_adjust_skip: + MOVQ 144(CX), R12 + MOVQ R12, 152(CX) + MOVQ R14, 144(CX) + MOVQ R14, R13 + +sequenceDecs_decodeSync_safe_bmi2_after_adjust: + MOVQ R13, 8(SP) + + // Check values + MOVQ 16(SP), CX + MOVQ 24(SP), R12 + LEAQ (CX)(R12*1), R14 + MOVQ s+0(FP), R15 + ADDQ R14, 256(R15) + MOVQ ctx+16(FP), R14 + SUBQ R12, 104(R14) + JS error_not_enough_literals + CMPQ CX, $0x00020002 + JA sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big + TESTQ R13, R13 + JNZ sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok + TESTQ CX, CX + JNZ sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch + +sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok: + MOVQ 24(SP), CX + MOVQ 8(SP), R12 + MOVQ 16(SP), R13 + + // Check if we have enough space in s.out + LEAQ (CX)(R13*1), R14 + ADDQ R9, R14 + CMPQ R14, 32(SP) + JA error_not_enough_space + + // Copy literals + TESTQ CX, CX + JZ check_offset + MOVQ CX, R14 + SUBQ $0x10, R14 + JB copy_1_small + +copy_1_loop: + MOVUPS (R10), X0 + MOVUPS X0, (R9) + ADDQ $0x10, R10 + ADDQ $0x10, R9 + SUBQ $0x10, R14 + JAE copy_1_loop + LEAQ 16(R10)(R14*1), R10 + LEAQ 16(R9)(R14*1), R9 + MOVUPS -16(R10), X0 + MOVUPS X0, -16(R9) + JMP copy_1_end + +copy_1_small: + CMPQ CX, $0x03 + JE copy_1_move_3 + JB copy_1_move_1or2 + CMPQ CX, $0x08 + JB copy_1_move_4through7 + JMP copy_1_move_8through16 + +copy_1_move_1or2: + MOVB (R10), R14 + MOVB -1(R10)(CX*1), R15 + MOVB R14, (R9) + MOVB R15, -1(R9)(CX*1) + ADDQ CX, R10 + ADDQ CX, R9 + JMP copy_1_end + +copy_1_move_3: + MOVW (R10), R14 + MOVB 2(R10), R15 + MOVW R14, (R9) + MOVB R15, 2(R9) + ADDQ CX, R10 + ADDQ CX, R9 + JMP copy_1_end + +copy_1_move_4through7: + MOVL (R10), R14 + MOVL -4(R10)(CX*1), R15 + MOVL R14, (R9) + MOVL R15, -4(R9)(CX*1) + ADDQ CX, R10 + ADDQ CX, R9 + JMP copy_1_end + +copy_1_move_8through16: + MOVQ (R10), R14 + MOVQ -8(R10)(CX*1), R15 + MOVQ R14, (R9) + MOVQ R15, -8(R9)(CX*1) + ADDQ CX, R10 + ADDQ CX, R9 + +copy_1_end: + ADDQ CX, R11 + + // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) +check_offset: + MOVQ R11, CX + ADDQ 40(SP), CX + CMPQ R12, CX + JG error_match_off_too_big + CMPQ R12, 56(SP) + JG error_match_off_too_big + + // Copy match from history + MOVQ R12, CX + SUBQ R11, CX + JLS copy_match + MOVQ 48(SP), R14 + SUBQ CX, R14 + CMPQ R13, CX + JG copy_all_from_history + MOVQ R13, CX + SUBQ $0x10, CX + JB copy_4_small + +copy_4_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R9) + ADDQ $0x10, R14 + ADDQ $0x10, R9 + SUBQ $0x10, CX + JAE copy_4_loop + LEAQ 16(R14)(CX*1), R14 + LEAQ 16(R9)(CX*1), R9 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R9) + JMP copy_4_end + +copy_4_small: + CMPQ R13, $0x03 + JE copy_4_move_3 + CMPQ R13, $0x08 + JB copy_4_move_4through7 + JMP copy_4_move_8through16 + +copy_4_move_3: + MOVW (R14), CX + MOVB 2(R14), R12 + MOVW CX, (R9) + MOVB R12, 2(R9) + ADDQ R13, R14 + ADDQ R13, R9 + JMP copy_4_end + +copy_4_move_4through7: + MOVL (R14), CX + MOVL -4(R14)(R13*1), R12 + MOVL CX, (R9) + MOVL R12, -4(R9)(R13*1) + ADDQ R13, R14 + ADDQ R13, R9 + JMP copy_4_end + +copy_4_move_8through16: + MOVQ (R14), CX + MOVQ -8(R14)(R13*1), R12 + MOVQ CX, (R9) + MOVQ R12, -8(R9)(R13*1) + ADDQ R13, R14 + ADDQ R13, R9 + +copy_4_end: + ADDQ R13, R11 + JMP handle_loop + JMP loop_finished + +copy_all_from_history: + MOVQ CX, R15 + SUBQ $0x10, R15 + JB copy_5_small + +copy_5_loop: + MOVUPS (R14), X0 + MOVUPS X0, (R9) + ADDQ $0x10, R14 + ADDQ $0x10, R9 + SUBQ $0x10, R15 + JAE copy_5_loop + LEAQ 16(R14)(R15*1), R14 + LEAQ 16(R9)(R15*1), R9 + MOVUPS -16(R14), X0 + MOVUPS X0, -16(R9) + JMP copy_5_end + +copy_5_small: + CMPQ CX, $0x03 + JE copy_5_move_3 + JB copy_5_move_1or2 + CMPQ CX, $0x08 + JB copy_5_move_4through7 + JMP copy_5_move_8through16 + +copy_5_move_1or2: + MOVB (R14), R15 + MOVB -1(R14)(CX*1), BP + MOVB R15, (R9) + MOVB BP, -1(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_5_end + +copy_5_move_3: + MOVW (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R9) + MOVB BP, 2(R9) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_5_end + +copy_5_move_4through7: + MOVL (R14), R15 + MOVL -4(R14)(CX*1), BP + MOVL R15, (R9) + MOVL BP, -4(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_5_end + +copy_5_move_8through16: + MOVQ (R14), R15 + MOVQ -8(R14)(CX*1), BP + MOVQ R15, (R9) + MOVQ BP, -8(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 + +copy_5_end: + ADDQ CX, R11 + SUBQ CX, R13 + + // Copy match from the current buffer +copy_match: + MOVQ R9, CX + SUBQ R12, CX + + // ml <= mo + CMPQ R13, R12 + JA copy_overlapping_match + + // Copy non-overlapping match + ADDQ R13, R11 + MOVQ R13, R12 + SUBQ $0x10, R12 + JB copy_2_small + +copy_2_loop: + MOVUPS (CX), X0 + MOVUPS X0, (R9) + ADDQ $0x10, CX + ADDQ $0x10, R9 + SUBQ $0x10, R12 + JAE copy_2_loop + LEAQ 16(CX)(R12*1), CX + LEAQ 16(R9)(R12*1), R9 + MOVUPS -16(CX), X0 + MOVUPS X0, -16(R9) + JMP copy_2_end + +copy_2_small: + CMPQ R13, $0x03 + JE copy_2_move_3 + JB copy_2_move_1or2 + CMPQ R13, $0x08 + JB copy_2_move_4through7 + JMP copy_2_move_8through16 + +copy_2_move_1or2: + MOVB (CX), R12 + MOVB -1(CX)(R13*1), R14 + MOVB R12, (R9) + MOVB R14, -1(R9)(R13*1) + ADDQ R13, CX + ADDQ R13, R9 + JMP copy_2_end + +copy_2_move_3: + MOVW (CX), R12 + MOVB 2(CX), R14 + MOVW R12, (R9) + MOVB R14, 2(R9) + ADDQ R13, CX + ADDQ R13, R9 + JMP copy_2_end + +copy_2_move_4through7: + MOVL (CX), R12 + MOVL -4(CX)(R13*1), R14 + MOVL R12, (R9) + MOVL R14, -4(R9)(R13*1) + ADDQ R13, CX + ADDQ R13, R9 + JMP copy_2_end + +copy_2_move_8through16: + MOVQ (CX), R12 + MOVQ -8(CX)(R13*1), R14 + MOVQ R12, (R9) + MOVQ R14, -8(R9)(R13*1) + ADDQ R13, CX + ADDQ R13, R9 + +copy_2_end: + JMP handle_loop + + // Copy overlapping match +copy_overlapping_match: + ADDQ R13, R11 + +copy_slow_3: + MOVB (CX), R12 + MOVB R12, (R9) + INCQ CX + INCQ R9 + DECQ R13 + JNZ copy_slow_3 + +handle_loop: + MOVQ ctx+16(FP), CX + DECQ 96(CX) + JNS sequenceDecs_decodeSync_safe_bmi2_main_loop + +loop_finished: + MOVQ br+8(FP), CX + MOVQ AX, 24(CX) + MOVB DL, 32(CX) + MOVQ BX, 8(CX) + + // Update the context + MOVQ ctx+16(FP), AX + MOVQ R11, 136(AX) + MOVQ 144(AX), CX + SUBQ CX, R10 + MOVQ R10, 168(AX) + + // Return success + MOVQ $0x00000000, ret+24(FP) + RET + + // Return with match length error +sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch: + MOVQ 16(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 216(CX) + MOVQ $0x00000001, ret+24(FP) + RET + + // Return with match too long error +sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big: + MOVQ ctx+16(FP), AX + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ $0x00000002, ret+24(FP) + RET + + // Return with match offset too long error +error_match_off_too_big: + MOVQ ctx+16(FP), AX + MOVQ 8(SP), CX + MOVQ CX, 224(AX) + MOVQ R11, 136(AX) + MOVQ $0x00000003, ret+24(FP) + RET + + // Return with not enough literals error +error_not_enough_literals: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ $0x00000004, ret+24(FP) + RET + + // Return with overread error +error_overread: + MOVQ $0x00000006, ret+24(FP) + RET + + // Return with not enough output space error +error_not_enough_space: + MOVQ ctx+16(FP), AX + MOVQ 24(SP), CX + MOVQ CX, 208(AX) + MOVQ 16(SP), CX + MOVQ CX, 216(AX) + MOVQ R11, 136(AX) + MOVQ $0x00000005, ret+24(FP) + RET diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go new file mode 100644 index 000000000..2fb35b788 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go @@ -0,0 +1,237 @@ +//go:build !amd64 || appengine || !gc || noasm +// +build !amd64 appengine !gc noasm + +package zstd + +import ( + "fmt" + "io" +) + +// decode sequences from the stream with the provided history but without dictionary. +func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { + return false, nil +} + +// decode sequences from the stream without the provided history. +func (s *sequenceDecs) decode(seqs []seqVals) error { + br := s.br + + // Grab full sizes tables, to avoid bounds checks. + llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] + llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state + s.seqSize = 0 + litRemain := len(s.literals) + + maxBlockSize := maxCompressedBlockSize + if s.windowSize < maxBlockSize { + maxBlockSize = s.windowSize + } + for i := range seqs { + var ll, mo, ml int + if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { + // inlined function: + // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) + + // Final will not read from stream. + var llB, mlB, moB uint8 + ll, llB = llState.final() + ml, mlB = mlState.final() + mo, moB = ofState.final() + + // extra bits are stored in reverse order. + br.fillFast() + mo += br.getBits(moB) + if s.maxBits > 32 { + br.fillFast() + } + ml += br.getBits(mlB) + ll += br.getBits(llB) + + if moB > 1 { + s.prevOffset[2] = s.prevOffset[1] + s.prevOffset[1] = s.prevOffset[0] + s.prevOffset[0] = mo + } else { + // mo = s.adjustOffset(mo, ll, moB) + // Inlined for rather big speedup + if ll == 0 { + // There is an exception though, when current sequence's literals_length = 0. + // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, + // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. + mo++ + } + + if mo == 0 { + mo = s.prevOffset[0] + } else { + var temp int + if mo == 3 { + temp = s.prevOffset[0] - 1 + } else { + temp = s.prevOffset[mo] + } + + if temp == 0 { + // 0 is not valid; input is corrupted; force offset to 1 + println("WARNING: temp was 0") + temp = 1 + } + + if mo != 1 { + s.prevOffset[2] = s.prevOffset[1] + } + s.prevOffset[1] = s.prevOffset[0] + s.prevOffset[0] = temp + mo = temp + } + } + br.fillFast() + } else { + if br.overread() { + if debugDecoder { + printf("reading sequence %d, exceeded available data\n", i) + } + return io.ErrUnexpectedEOF + } + ll, mo, ml = s.next(br, llState, mlState, ofState) + br.fill() + } + + if debugSequences { + println("Seq", i, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) + } + // Evaluate. + // We might be doing this async, so do it early. + if mo == 0 && ml > 0 { + return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) + } + if ml > maxMatchLen { + return fmt.Errorf("match len (%d) bigger than max allowed length", ml) + } + s.seqSize += ll + ml + if s.seqSize > maxBlockSize { + return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) + } + litRemain -= ll + if litRemain < 0 { + return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, litRemain+ll) + } + seqs[i] = seqVals{ + ll: ll, + ml: ml, + mo: mo, + } + if i == len(seqs)-1 { + // This is the last sequence, so we shouldn't update state. + break + } + + // Manually inlined, ~ 5-20% faster + // Update all 3 states at once. Approx 20% faster. + nBits := llState.nbBits() + mlState.nbBits() + ofState.nbBits() + if nBits == 0 { + llState = llTable[llState.newState()&maxTableMask] + mlState = mlTable[mlState.newState()&maxTableMask] + ofState = ofTable[ofState.newState()&maxTableMask] + } else { + bits := br.get32BitsFast(nBits) + lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) + llState = llTable[(llState.newState()+lowBits)&maxTableMask] + + lowBits = uint16(bits >> (ofState.nbBits() & 31)) + lowBits &= bitMask[mlState.nbBits()&15] + mlState = mlTable[(mlState.newState()+lowBits)&maxTableMask] + + lowBits = uint16(bits) & bitMask[ofState.nbBits()&15] + ofState = ofTable[(ofState.newState()+lowBits)&maxTableMask] + } + } + s.seqSize += litRemain + if s.seqSize > maxBlockSize { + return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) + } + err := br.close() + if err != nil { + printf("Closing sequences: %v, %+v\n", err, *br) + } + return err +} + +// executeSimple handles cases when a dictionary is not used. +func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { + // Ensure we have enough output size... + if len(s.out)+s.seqSize > cap(s.out) { + addBytes := s.seqSize + len(s.out) + s.out = append(s.out, make([]byte, addBytes)...) + s.out = s.out[:len(s.out)-addBytes] + } + + if debugDecoder { + printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize) + } + + var t = len(s.out) + out := s.out[:t+s.seqSize] + + for _, seq := range seqs { + // Add literals + copy(out[t:], s.literals[:seq.ll]) + t += seq.ll + s.literals = s.literals[seq.ll:] + + // Malformed input + if seq.mo > t+len(hist) || seq.mo > s.windowSize { + return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) + } + + // Copy from history. + if v := seq.mo - t; v > 0 { + // v is the start position in history from end. + start := len(hist) - v + if seq.ml > v { + // Some goes into the current block. + // Copy remainder of history + copy(out[t:], hist[start:]) + t += v + seq.ml -= v + } else { + copy(out[t:], hist[start:start+seq.ml]) + t += seq.ml + continue + } + } + + // We must be in the current buffer now + if seq.ml > 0 { + start := t - seq.mo + if seq.ml <= t-start { + // No overlap + copy(out[t:], out[start:start+seq.ml]) + t += seq.ml + } else { + // Overlapping copy + // Extend destination slice and copy one byte at the time. + src := out[start : start+seq.ml] + dst := out[t:] + dst = dst[:len(src)] + t += len(src) + // Destination is the space we just added. + for i := range src { + dst[i] = src[i] + } + } + } + } + // Add final literals + copy(out[t:], s.literals) + if debugDecoder { + t += len(s.literals) + if t != len(out) { + panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) + } + } + s.out = out + + return nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/seqenc.go b/vendor/github.com/klauspost/compress/zstd/seqenc.go new file mode 100644 index 000000000..8014174a7 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/seqenc.go @@ -0,0 +1,114 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import "math/bits" + +type seqCoders struct { + llEnc, ofEnc, mlEnc *fseEncoder + llPrev, ofPrev, mlPrev *fseEncoder +} + +// swap coders with another (block). +func (s *seqCoders) swap(other *seqCoders) { + *s, *other = *other, *s +} + +// setPrev will update the previous encoders to the actually used ones +// and make sure a fresh one is in the main slot. +func (s *seqCoders) setPrev(ll, ml, of *fseEncoder) { + compareSwap := func(used *fseEncoder, current, prev **fseEncoder) { + // We used the new one, more current to history and reuse the previous history + if *current == used { + *prev, *current = *current, *prev + c := *current + p := *prev + c.reUsed = false + p.reUsed = true + return + } + if used == *prev { + return + } + // Ensure we cannot reuse by accident + prevEnc := *prev + prevEnc.symbolLen = 0 + } + compareSwap(ll, &s.llEnc, &s.llPrev) + compareSwap(ml, &s.mlEnc, &s.mlPrev) + compareSwap(of, &s.ofEnc, &s.ofPrev) +} + +func highBit(val uint32) (n uint32) { + return uint32(bits.Len32(val) - 1) +} + +var llCodeTable = [64]byte{0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 16, 17, 17, 18, 18, 19, 19, + 20, 20, 20, 20, 21, 21, 21, 21, + 22, 22, 22, 22, 22, 22, 22, 22, + 23, 23, 23, 23, 23, 23, 23, 23, + 24, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24} + +// Up to 6 bits +const maxLLCode = 35 + +// llBitsTable translates from ll code to number of bits. +var llBitsTable = [maxLLCode + 1]byte{ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, + 4, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16} + +// llCode returns the code that represents the literal length requested. +func llCode(litLength uint32) uint8 { + const llDeltaCode = 19 + if litLength <= 63 { + // Compiler insists on bounds check (Go 1.12) + return llCodeTable[litLength&63] + } + return uint8(highBit(litLength)) + llDeltaCode +} + +var mlCodeTable = [128]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, + 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42} + +// Up to 6 bits +const maxMLCode = 52 + +// mlBitsTable translates from ml code to number of bits. +var mlBitsTable = [maxMLCode + 1]byte{ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, + 4, 4, 5, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16} + +// note : mlBase = matchLength - MINMATCH; +// because it's the format it's stored in seqStore->sequences +func mlCode(mlBase uint32) uint8 { + const mlDeltaCode = 36 + if mlBase <= 127 { + // Compiler insists on bounds check (Go 1.12) + return mlCodeTable[mlBase&127] + } + return uint8(highBit(mlBase)) + mlDeltaCode +} + +func ofCode(offset uint32) uint8 { + // A valid offset will always be > 0. + return uint8(bits.Len32(offset) - 1) +} diff --git a/vendor/github.com/klauspost/compress/zstd/snappy.go b/vendor/github.com/klauspost/compress/zstd/snappy.go new file mode 100644 index 000000000..ec13594e8 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/snappy.go @@ -0,0 +1,434 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. +// Based on work by Yann Collet, released under BSD License. + +package zstd + +import ( + "encoding/binary" + "errors" + "hash/crc32" + "io" + + "github.com/klauspost/compress/huff0" + snappy "github.com/klauspost/compress/internal/snapref" +) + +const ( + snappyTagLiteral = 0x00 + snappyTagCopy1 = 0x01 + snappyTagCopy2 = 0x02 + snappyTagCopy4 = 0x03 +) + +const ( + snappyChecksumSize = 4 + snappyMagicBody = "sNaPpY" + + // snappyMaxBlockSize is the maximum size of the input to encodeBlock. It is not + // part of the wire format per se, but some parts of the encoder assume + // that an offset fits into a uint16. + // + // Also, for the framing format (Writer type instead of Encode function), + // https://github.com/google/snappy/blob/master/framing_format.txt says + // that "the uncompressed data in a chunk must be no longer than 65536 + // bytes". + snappyMaxBlockSize = 65536 + + // snappyMaxEncodedLenOfMaxBlockSize equals MaxEncodedLen(snappyMaxBlockSize), but is + // hard coded to be a const instead of a variable, so that obufLen can also + // be a const. Their equivalence is confirmed by + // TestMaxEncodedLenOfMaxBlockSize. + snappyMaxEncodedLenOfMaxBlockSize = 76490 +) + +const ( + chunkTypeCompressedData = 0x00 + chunkTypeUncompressedData = 0x01 + chunkTypePadding = 0xfe + chunkTypeStreamIdentifier = 0xff +) + +var ( + // ErrSnappyCorrupt reports that the input is invalid. + ErrSnappyCorrupt = errors.New("snappy: corrupt input") + // ErrSnappyTooLarge reports that the uncompressed length is too large. + ErrSnappyTooLarge = errors.New("snappy: decoded block is too large") + // ErrSnappyUnsupported reports that the input isn't supported. + ErrSnappyUnsupported = errors.New("snappy: unsupported input") + + errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") +) + +// SnappyConverter can read SnappyConverter-compressed streams and convert them to zstd. +// Conversion is done by converting the stream directly from Snappy without intermediate +// full decoding. +// Therefore the compression ratio is much less than what can be done by a full decompression +// and compression, and a faulty Snappy stream may lead to a faulty Zstandard stream without +// any errors being generated. +// No CRC value is being generated and not all CRC values of the Snappy stream are checked. +// However, it provides really fast recompression of Snappy streams. +// The converter can be reused to avoid allocations, even after errors. +type SnappyConverter struct { + r io.Reader + err error + buf []byte + block *blockEnc +} + +// Convert the Snappy stream supplied in 'in' and write the zStandard stream to 'w'. +// If any error is detected on the Snappy stream it is returned. +// The number of bytes written is returned. +func (r *SnappyConverter) Convert(in io.Reader, w io.Writer) (int64, error) { + initPredefined() + r.err = nil + r.r = in + if r.block == nil { + r.block = &blockEnc{} + r.block.init() + } + r.block.initNewEncode() + if len(r.buf) != snappyMaxEncodedLenOfMaxBlockSize+snappyChecksumSize { + r.buf = make([]byte, snappyMaxEncodedLenOfMaxBlockSize+snappyChecksumSize) + } + r.block.litEnc.Reuse = huff0.ReusePolicyNone + var written int64 + var readHeader bool + { + header := frameHeader{WindowSize: snappyMaxBlockSize}.appendTo(r.buf[:0]) + + var n int + n, r.err = w.Write(header) + if r.err != nil { + return written, r.err + } + written += int64(n) + } + + for { + if !r.readFull(r.buf[:4], true) { + // Add empty last block + r.block.reset(nil) + r.block.last = true + err := r.block.encodeLits(r.block.literals, false) + if err != nil { + return written, err + } + n, err := w.Write(r.block.output) + if err != nil { + return written, err + } + written += int64(n) + + return written, r.err + } + chunkType := r.buf[0] + if !readHeader { + if chunkType != chunkTypeStreamIdentifier { + println("chunkType != chunkTypeStreamIdentifier", chunkType) + r.err = ErrSnappyCorrupt + return written, r.err + } + readHeader = true + } + chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 + if chunkLen > len(r.buf) { + println("chunkLen > len(r.buf)", chunkType) + r.err = ErrSnappyUnsupported + return written, r.err + } + + // The chunk types are specified at + // https://github.com/google/snappy/blob/master/framing_format.txt + switch chunkType { + case chunkTypeCompressedData: + // Section 4.2. Compressed data (chunk type 0x00). + if chunkLen < snappyChecksumSize { + println("chunkLen < snappyChecksumSize", chunkLen, snappyChecksumSize) + r.err = ErrSnappyCorrupt + return written, r.err + } + buf := r.buf[:chunkLen] + if !r.readFull(buf, false) { + return written, r.err + } + //checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 + buf = buf[snappyChecksumSize:] + + n, hdr, err := snappyDecodedLen(buf) + if err != nil { + r.err = err + return written, r.err + } + buf = buf[hdr:] + if n > snappyMaxBlockSize { + println("n > snappyMaxBlockSize", n, snappyMaxBlockSize) + r.err = ErrSnappyCorrupt + return written, r.err + } + r.block.reset(nil) + r.block.pushOffsets() + if err := decodeSnappy(r.block, buf); err != nil { + r.err = err + return written, r.err + } + if r.block.size+r.block.extraLits != n { + printf("invalid size, want %d, got %d\n", n, r.block.size+r.block.extraLits) + r.err = ErrSnappyCorrupt + return written, r.err + } + err = r.block.encode(nil, false, false) + switch err { + case errIncompressible: + r.block.popOffsets() + r.block.reset(nil) + r.block.literals, err = snappy.Decode(r.block.literals[:n], r.buf[snappyChecksumSize:chunkLen]) + if err != nil { + return written, err + } + err = r.block.encodeLits(r.block.literals, false) + if err != nil { + return written, err + } + case nil: + default: + return written, err + } + + n, r.err = w.Write(r.block.output) + if r.err != nil { + return written, err + } + written += int64(n) + continue + case chunkTypeUncompressedData: + if debugEncoder { + println("Uncompressed, chunklen", chunkLen) + } + // Section 4.3. Uncompressed data (chunk type 0x01). + if chunkLen < snappyChecksumSize { + println("chunkLen < snappyChecksumSize", chunkLen, snappyChecksumSize) + r.err = ErrSnappyCorrupt + return written, r.err + } + r.block.reset(nil) + buf := r.buf[:snappyChecksumSize] + if !r.readFull(buf, false) { + return written, r.err + } + checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 + // Read directly into r.decoded instead of via r.buf. + n := chunkLen - snappyChecksumSize + if n > snappyMaxBlockSize { + println("n > snappyMaxBlockSize", n, snappyMaxBlockSize) + r.err = ErrSnappyCorrupt + return written, r.err + } + r.block.literals = r.block.literals[:n] + if !r.readFull(r.block.literals, false) { + return written, r.err + } + if snappyCRC(r.block.literals) != checksum { + println("literals crc mismatch") + r.err = ErrSnappyCorrupt + return written, r.err + } + err := r.block.encodeLits(r.block.literals, false) + if err != nil { + return written, err + } + n, r.err = w.Write(r.block.output) + if r.err != nil { + return written, err + } + written += int64(n) + continue + + case chunkTypeStreamIdentifier: + if debugEncoder { + println("stream id", chunkLen, len(snappyMagicBody)) + } + // Section 4.1. Stream identifier (chunk type 0xff). + if chunkLen != len(snappyMagicBody) { + println("chunkLen != len(snappyMagicBody)", chunkLen, len(snappyMagicBody)) + r.err = ErrSnappyCorrupt + return written, r.err + } + if !r.readFull(r.buf[:len(snappyMagicBody)], false) { + return written, r.err + } + for i := 0; i < len(snappyMagicBody); i++ { + if r.buf[i] != snappyMagicBody[i] { + println("r.buf[i] != snappyMagicBody[i]", r.buf[i], snappyMagicBody[i], i) + r.err = ErrSnappyCorrupt + return written, r.err + } + } + continue + } + + if chunkType <= 0x7f { + // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). + println("chunkType <= 0x7f") + r.err = ErrSnappyUnsupported + return written, r.err + } + // Section 4.4 Padding (chunk type 0xfe). + // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). + if !r.readFull(r.buf[:chunkLen], false) { + return written, r.err + } + } +} + +// decodeSnappy writes the decoding of src to dst. It assumes that the varint-encoded +// length of the decompressed bytes has already been read. +func decodeSnappy(blk *blockEnc, src []byte) error { + //decodeRef(make([]byte, snappyMaxBlockSize), src) + var s, length int + lits := blk.extraLits + var offset uint32 + for s < len(src) { + switch src[s] & 0x03 { + case snappyTagLiteral: + x := uint32(src[s] >> 2) + switch { + case x < 60: + s++ + case x == 60: + s += 2 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + println("uint(s) > uint(len(src)", s, src) + return ErrSnappyCorrupt + } + x = uint32(src[s-1]) + case x == 61: + s += 3 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + println("uint(s) > uint(len(src)", s, src) + return ErrSnappyCorrupt + } + x = uint32(src[s-2]) | uint32(src[s-1])<<8 + case x == 62: + s += 4 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + println("uint(s) > uint(len(src)", s, src) + return ErrSnappyCorrupt + } + x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 + case x == 63: + s += 5 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + println("uint(s) > uint(len(src)", s, src) + return ErrSnappyCorrupt + } + x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 + } + if x > snappyMaxBlockSize { + println("x > snappyMaxBlockSize", x, snappyMaxBlockSize) + return ErrSnappyCorrupt + } + length = int(x) + 1 + if length <= 0 { + println("length <= 0 ", length) + + return errUnsupportedLiteralLength + } + //if length > snappyMaxBlockSize-d || uint32(length) > len(src)-s { + // return ErrSnappyCorrupt + //} + + blk.literals = append(blk.literals, src[s:s+length]...) + //println(length, "litLen") + lits += length + s += length + continue + + case snappyTagCopy1: + s += 2 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + println("uint(s) > uint(len(src)", s, len(src)) + return ErrSnappyCorrupt + } + length = 4 + int(src[s-2])>>2&0x7 + offset = uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]) + + case snappyTagCopy2: + s += 3 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + println("uint(s) > uint(len(src)", s, len(src)) + return ErrSnappyCorrupt + } + length = 1 + int(src[s-3])>>2 + offset = uint32(src[s-2]) | uint32(src[s-1])<<8 + + case snappyTagCopy4: + s += 5 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + println("uint(s) > uint(len(src)", s, len(src)) + return ErrSnappyCorrupt + } + length = 1 + int(src[s-5])>>2 + offset = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 + } + + if offset <= 0 || blk.size+lits < int(offset) /*|| length > len(blk)-d */ { + println("offset <= 0 || blk.size+lits < int(offset)", offset, blk.size+lits, int(offset), blk.size, lits) + + return ErrSnappyCorrupt + } + + // Check if offset is one of the recent offsets. + // Adjusts the output offset accordingly. + // Gives a tiny bit of compression, typically around 1%. + if false { + offset = blk.matchOffset(offset, uint32(lits)) + } else { + offset += 3 + } + + blk.sequences = append(blk.sequences, seq{ + litLen: uint32(lits), + offset: offset, + matchLen: uint32(length) - zstdMinMatch, + }) + blk.size += length + lits + lits = 0 + } + blk.extraLits = lits + return nil +} + +func (r *SnappyConverter) readFull(p []byte, allowEOF bool) (ok bool) { + if _, r.err = io.ReadFull(r.r, p); r.err != nil { + if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { + r.err = ErrSnappyCorrupt + } + return false + } + return true +} + +var crcTable = crc32.MakeTable(crc32.Castagnoli) + +// crc implements the checksum specified in section 3 of +// https://github.com/google/snappy/blob/master/framing_format.txt +func snappyCRC(b []byte) uint32 { + c := crc32.Update(0, crcTable, b) + return c>>15 | c<<17 + 0xa282ead8 +} + +// snappyDecodedLen returns the length of the decoded block and the number of bytes +// that the length header occupied. +func snappyDecodedLen(src []byte) (blockLen, headerLen int, err error) { + v, n := binary.Uvarint(src) + if n <= 0 || v > 0xffffffff { + return 0, 0, ErrSnappyCorrupt + } + + const wordSize = 32 << (^uint(0) >> 32 & 1) + if wordSize == 32 && v > 0x7fffffff { + return 0, 0, ErrSnappyTooLarge + } + return int(v), n, nil +} diff --git a/vendor/github.com/klauspost/compress/zstd/zip.go b/vendor/github.com/klauspost/compress/zstd/zip.go new file mode 100644 index 000000000..29c15c8c4 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/zip.go @@ -0,0 +1,141 @@ +// Copyright 2019+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. + +package zstd + +import ( + "errors" + "io" + "sync" +) + +// ZipMethodWinZip is the method for Zstandard compressed data inside Zip files for WinZip. +// See https://www.winzip.com/win/en/comp_info.html +const ZipMethodWinZip = 93 + +// ZipMethodPKWare is the original method number used by PKWARE to indicate Zstandard compression. +// Deprecated: This has been deprecated by PKWARE, use ZipMethodWinZip instead for compression. +// See https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.9.TXT +const ZipMethodPKWare = 20 + +// zipReaderPool is the default reader pool. +var zipReaderPool = sync.Pool{New: func() interface{} { + z, err := NewReader(nil, WithDecoderLowmem(true), WithDecoderMaxWindow(128<<20), WithDecoderConcurrency(1)) + if err != nil { + panic(err) + } + return z +}} + +// newZipReader creates a pooled zip decompressor. +func newZipReader(opts ...DOption) func(r io.Reader) io.ReadCloser { + pool := &zipReaderPool + if len(opts) > 0 { + opts = append([]DOption{WithDecoderLowmem(true), WithDecoderMaxWindow(128 << 20)}, opts...) + // Force concurrency 1 + opts = append(opts, WithDecoderConcurrency(1)) + // Create our own pool + pool = &sync.Pool{} + } + return func(r io.Reader) io.ReadCloser { + dec, ok := pool.Get().(*Decoder) + if ok { + dec.Reset(r) + } else { + d, err := NewReader(r, opts...) + if err != nil { + panic(err) + } + dec = d + } + return &pooledZipReader{dec: dec, pool: pool} + } +} + +type pooledZipReader struct { + mu sync.Mutex // guards Close and Read + pool *sync.Pool + dec *Decoder +} + +func (r *pooledZipReader) Read(p []byte) (n int, err error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.dec == nil { + return 0, errors.New("read after close or EOF") + } + dec, err := r.dec.Read(p) + if err == io.EOF { + r.dec.Reset(nil) + r.pool.Put(r.dec) + r.dec = nil + } + return dec, err +} + +func (r *pooledZipReader) Close() error { + r.mu.Lock() + defer r.mu.Unlock() + var err error + if r.dec != nil { + err = r.dec.Reset(nil) + r.pool.Put(r.dec) + r.dec = nil + } + return err +} + +type pooledZipWriter struct { + mu sync.Mutex // guards Close and Read + enc *Encoder + pool *sync.Pool +} + +func (w *pooledZipWriter) Write(p []byte) (n int, err error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.enc == nil { + return 0, errors.New("Write after Close") + } + return w.enc.Write(p) +} + +func (w *pooledZipWriter) Close() error { + w.mu.Lock() + defer w.mu.Unlock() + var err error + if w.enc != nil { + err = w.enc.Close() + w.pool.Put(w.enc) + w.enc = nil + } + return err +} + +// ZipCompressor returns a compressor that can be registered with zip libraries. +// The provided encoder options will be used on all encodes. +func ZipCompressor(opts ...EOption) func(w io.Writer) (io.WriteCloser, error) { + var pool sync.Pool + return func(w io.Writer) (io.WriteCloser, error) { + enc, ok := pool.Get().(*Encoder) + if ok { + enc.Reset(w) + } else { + var err error + enc, err = NewWriter(w, opts...) + if err != nil { + return nil, err + } + } + return &pooledZipWriter{enc: enc, pool: &pool}, nil + } +} + +// ZipDecompressor returns a decompressor that can be registered with zip libraries. +// See ZipCompressor for example. +// Options can be specified. WithDecoderConcurrency(1) is forced, +// and by default a 128MB maximum decompression window is specified. +// The window size can be overridden if required. +func ZipDecompressor(opts ...DOption) func(r io.Reader) io.ReadCloser { + return newZipReader(opts...) +} diff --git a/vendor/github.com/klauspost/compress/zstd/zstd.go b/vendor/github.com/klauspost/compress/zstd/zstd.go new file mode 100644 index 000000000..4be7cc736 --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/zstd.go @@ -0,0 +1,121 @@ +// Package zstd provides decompression of zstandard files. +// +// For advanced usage and examples, go to the README: https://github.com/klauspost/compress/tree/master/zstd#zstd +package zstd + +import ( + "bytes" + "encoding/binary" + "errors" + "log" + "math" +) + +// enable debug printing +const debug = false + +// enable encoding debug printing +const debugEncoder = debug + +// enable decoding debug printing +const debugDecoder = debug + +// Enable extra assertions. +const debugAsserts = debug || false + +// print sequence details +const debugSequences = false + +// print detailed matching information +const debugMatches = false + +// force encoder to use predefined tables. +const forcePreDef = false + +// zstdMinMatch is the minimum zstd match length. +const zstdMinMatch = 3 + +// fcsUnknown is used for unknown frame content size. +const fcsUnknown = math.MaxUint64 + +var ( + // ErrReservedBlockType is returned when a reserved block type is found. + // Typically this indicates wrong or corrupted input. + ErrReservedBlockType = errors.New("invalid input: reserved block type encountered") + + // ErrCompressedSizeTooBig is returned when a block is bigger than allowed. + // Typically this indicates wrong or corrupted input. + ErrCompressedSizeTooBig = errors.New("invalid input: compressed size too big") + + // ErrBlockTooSmall is returned when a block is too small to be decoded. + // Typically returned on invalid input. + ErrBlockTooSmall = errors.New("block too small") + + // ErrUnexpectedBlockSize is returned when a block has unexpected size. + // Typically returned on invalid input. + ErrUnexpectedBlockSize = errors.New("unexpected block size") + + // ErrMagicMismatch is returned when a "magic" number isn't what is expected. + // Typically this indicates wrong or corrupted input. + ErrMagicMismatch = errors.New("invalid input: magic number mismatch") + + // ErrWindowSizeExceeded is returned when a reference exceeds the valid window size. + // Typically this indicates wrong or corrupted input. + ErrWindowSizeExceeded = errors.New("window size exceeded") + + // ErrWindowSizeTooSmall is returned when no window size is specified. + // Typically this indicates wrong or corrupted input. + ErrWindowSizeTooSmall = errors.New("invalid input: window size was too small") + + // ErrDecoderSizeExceeded is returned if decompressed size exceeds the configured limit. + ErrDecoderSizeExceeded = errors.New("decompressed size exceeds configured limit") + + // ErrUnknownDictionary is returned if the dictionary ID is unknown. + ErrUnknownDictionary = errors.New("unknown dictionary") + + // ErrFrameSizeExceeded is returned if the stated frame size is exceeded. + // This is only returned if SingleSegment is specified on the frame. + ErrFrameSizeExceeded = errors.New("frame size exceeded") + + // ErrFrameSizeMismatch is returned if the stated frame size does not match the expected size. + // This is only returned if SingleSegment is specified on the frame. + ErrFrameSizeMismatch = errors.New("frame size does not match size on stream") + + // ErrCRCMismatch is returned if CRC mismatches. + ErrCRCMismatch = errors.New("CRC check failed") + + // ErrDecoderClosed will be returned if the Decoder was used after + // Close has been called. + ErrDecoderClosed = errors.New("decoder used after Close") + + // ErrDecoderNilInput is returned when a nil Reader was provided + // and an operation other than Reset/DecodeAll/Close was attempted. + ErrDecoderNilInput = errors.New("nil input provided as reader") +) + +func println(a ...interface{}) { + if debug || debugDecoder || debugEncoder { + log.Println(a...) + } +} + +func printf(format string, a ...interface{}) { + if debug || debugDecoder || debugEncoder { + log.Printf(format, a...) + } +} + +func load3232(b []byte, i int32) uint32 { + return binary.LittleEndian.Uint32(b[:len(b):len(b)][i:]) +} + +func load6432(b []byte, i int32) uint64 { + return binary.LittleEndian.Uint64(b[:len(b):len(b)][i:]) +} + +type byter interface { + Bytes() []byte + Len() int +} + +var _ byter = &bytes.Buffer{} diff --git a/vendor/github.com/kylelemons/godebug/LICENSE b/vendor/github.com/kylelemons/godebug/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/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/github.com/kylelemons/godebug/diff/diff.go b/vendor/github.com/kylelemons/godebug/diff/diff.go new file mode 100644 index 000000000..200e596c6 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/diff/diff.go @@ -0,0 +1,186 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package diff implements a linewise diff algorithm. +package diff + +import ( + "bytes" + "fmt" + "strings" +) + +// Chunk represents a piece of the diff. A chunk will not have both added and +// deleted lines. Equal lines are always after any added or deleted lines. +// A Chunk may or may not have any lines in it, especially for the first or last +// chunk in a computation. +type Chunk struct { + Added []string + Deleted []string + Equal []string +} + +func (c *Chunk) empty() bool { + return len(c.Added) == 0 && len(c.Deleted) == 0 && len(c.Equal) == 0 +} + +// Diff returns a string containing a line-by-line unified diff of the linewise +// changes required to make A into B. Each line is prefixed with '+', '-', or +// ' ' to indicate if it should be added, removed, or is correct respectively. +func Diff(A, B string) string { + aLines := strings.Split(A, "\n") + bLines := strings.Split(B, "\n") + + chunks := DiffChunks(aLines, bLines) + + buf := new(bytes.Buffer) + for _, c := range chunks { + for _, line := range c.Added { + fmt.Fprintf(buf, "+%s\n", line) + } + for _, line := range c.Deleted { + fmt.Fprintf(buf, "-%s\n", line) + } + for _, line := range c.Equal { + fmt.Fprintf(buf, " %s\n", line) + } + } + return strings.TrimRight(buf.String(), "\n") +} + +// DiffChunks uses an O(D(N+M)) shortest-edit-script algorithm +// to compute the edits required from A to B and returns the +// edit chunks. +func DiffChunks(a, b []string) []Chunk { + // algorithm: http://www.xmailserver.org/diff2.pdf + + // We'll need these quantities a lot. + alen, blen := len(a), len(b) // M, N + + // At most, it will require len(a) deletions and len(b) additions + // to transform a into b. + maxPath := alen + blen // MAX + if maxPath == 0 { + // degenerate case: two empty lists are the same + return nil + } + + // Store the endpoint of the path for diagonals. + // We store only the a index, because the b index on any diagonal + // (which we know during the loop below) is aidx-diag. + // endpoint[maxPath] represents the 0 diagonal. + // + // Stated differently: + // endpoint[d] contains the aidx of a furthest reaching path in diagonal d + endpoint := make([]int, 2*maxPath+1) // V + + saved := make([][]int, 0, 8) // Vs + save := func() { + dup := make([]int, len(endpoint)) + copy(dup, endpoint) + saved = append(saved, dup) + } + + var editDistance int // D +dLoop: + for editDistance = 0; editDistance <= maxPath; editDistance++ { + // The 0 diag(onal) represents equality of a and b. Each diagonal to + // the left is numbered one lower, to the right is one higher, from + // -alen to +blen. Negative diagonals favor differences from a, + // positive diagonals favor differences from b. The edit distance to a + // diagonal d cannot be shorter than d itself. + // + // The iterations of this loop cover either odds or evens, but not both, + // If odd indices are inputs, even indices are outputs and vice versa. + for diag := -editDistance; diag <= editDistance; diag += 2 { // k + var aidx int // x + switch { + case diag == -editDistance: + // This is a new diagonal; copy from previous iter + aidx = endpoint[maxPath-editDistance+1] + 0 + case diag == editDistance: + // This is a new diagonal; copy from previous iter + aidx = endpoint[maxPath+editDistance-1] + 1 + case endpoint[maxPath+diag+1] > endpoint[maxPath+diag-1]: + // diagonal d+1 was farther along, so use that + aidx = endpoint[maxPath+diag+1] + 0 + default: + // diagonal d-1 was farther (or the same), so use that + aidx = endpoint[maxPath+diag-1] + 1 + } + // On diagonal d, we can compute bidx from aidx. + bidx := aidx - diag // y + // See how far we can go on this diagonal before we find a difference. + for aidx < alen && bidx < blen && a[aidx] == b[bidx] { + aidx++ + bidx++ + } + // Store the end of the current edit chain. + endpoint[maxPath+diag] = aidx + // If we've found the end of both inputs, we're done! + if aidx >= alen && bidx >= blen { + save() // save the final path + break dLoop + } + } + save() // save the current path + } + if editDistance == 0 { + return nil + } + chunks := make([]Chunk, editDistance+1) + + x, y := alen, blen + for d := editDistance; d > 0; d-- { + endpoint := saved[d] + diag := x - y + insert := diag == -d || (diag != d && endpoint[maxPath+diag-1] < endpoint[maxPath+diag+1]) + + x1 := endpoint[maxPath+diag] + var x0, xM, kk int + if insert { + kk = diag + 1 + x0 = endpoint[maxPath+kk] + xM = x0 + } else { + kk = diag - 1 + x0 = endpoint[maxPath+kk] + xM = x0 + 1 + } + y0 := x0 - kk + + var c Chunk + if insert { + c.Added = b[y0:][:1] + } else { + c.Deleted = a[x0:][:1] + } + if xM < x1 { + c.Equal = a[xM:][:x1-xM] + } + + x, y = x0, y0 + chunks[d] = c + } + if x > 0 { + chunks[0].Equal = a[:x] + } + if chunks[0].empty() { + chunks = chunks[1:] + } + if len(chunks) == 0 { + return nil + } + return chunks +} diff --git a/vendor/github.com/kylelemons/godebug/pretty/.gitignore b/vendor/github.com/kylelemons/godebug/pretty/.gitignore new file mode 100644 index 000000000..fa9a735da --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/.gitignore @@ -0,0 +1,5 @@ +*.test +*.bench +*.golden +*.txt +*.prof diff --git a/vendor/github.com/kylelemons/godebug/pretty/doc.go b/vendor/github.com/kylelemons/godebug/pretty/doc.go new file mode 100644 index 000000000..03b5718a7 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/doc.go @@ -0,0 +1,25 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package pretty pretty-prints Go structures. +// +// This package uses reflection to examine a Go value and can +// print out in a nice, aligned fashion. It supports three +// modes (normal, compact, and extended) for advanced use. +// +// See the Reflect and Print examples for what the output looks like. +package pretty + +// TODO: +// - Catch cycles diff --git a/vendor/github.com/kylelemons/godebug/pretty/public.go b/vendor/github.com/kylelemons/godebug/pretty/public.go new file mode 100644 index 000000000..fbc5d7abb --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/public.go @@ -0,0 +1,188 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package pretty + +import ( + "bytes" + "fmt" + "io" + "net" + "reflect" + "time" + + "github.com/kylelemons/godebug/diff" +) + +// A Config represents optional configuration parameters for formatting. +// +// Some options, notably ShortList, dramatically increase the overhead +// of pretty-printing a value. +type Config struct { + // Verbosity options + Compact bool // One-line output. Overrides Diffable. + Diffable bool // Adds extra newlines for more easily diffable output. + + // Field and value options + IncludeUnexported bool // Include unexported fields in output + PrintStringers bool // Call String on a fmt.Stringer + PrintTextMarshalers bool // Call MarshalText on an encoding.TextMarshaler + SkipZeroFields bool // Skip struct fields that have a zero value. + + // Output transforms + ShortList int // Maximum character length for short lists if nonzero. + + // Type-specific overrides + // + // Formatter maps a type to a function that will provide a one-line string + // representation of the input value. Conceptually: + // Formatter[reflect.TypeOf(v)](v) = "v as a string" + // + // Note that the first argument need not explicitly match the type, it must + // merely be callable with it. + // + // When processing an input value, if its type exists as a key in Formatter: + // 1) If the value is nil, no stringification is performed. + // This allows overriding of PrintStringers and PrintTextMarshalers. + // 2) The value will be called with the input as its only argument. + // The function must return a string as its first return value. + // + // In addition to func literals, two common values for this will be: + // fmt.Sprint (function) func Sprint(...interface{}) string + // Type.String (method) func (Type) String() string + // + // Note that neither of these work if the String method is a pointer + // method and the input will be provided as a value. In that case, + // use a function that calls .String on the formal value parameter. + Formatter map[reflect.Type]interface{} + + // If TrackCycles is enabled, pretty will detect and track + // self-referential structures. If a self-referential structure (aka a + // "recursive" value) is detected, numbered placeholders will be emitted. + // + // Pointer tracking is disabled by default for performance reasons. + TrackCycles bool +} + +// Default Config objects +var ( + // DefaultFormatter is the default set of overrides for stringification. + DefaultFormatter = map[reflect.Type]interface{}{ + reflect.TypeOf(time.Time{}): fmt.Sprint, + reflect.TypeOf(net.IP{}): fmt.Sprint, + reflect.TypeOf((*error)(nil)).Elem(): fmt.Sprint, + } + + // CompareConfig is the default configuration used for Compare. + CompareConfig = &Config{ + Diffable: true, + IncludeUnexported: true, + Formatter: DefaultFormatter, + } + + // DefaultConfig is the default configuration used for all other top-level functions. + DefaultConfig = &Config{ + Formatter: DefaultFormatter, + } + + // CycleTracker is a convenience config for formatting and comparing recursive structures. + CycleTracker = &Config{ + Diffable: true, + Formatter: DefaultFormatter, + TrackCycles: true, + } +) + +func (cfg *Config) fprint(buf *bytes.Buffer, vals ...interface{}) { + ref := &reflector{ + Config: cfg, + } + if cfg.TrackCycles { + ref.pointerTracker = new(pointerTracker) + } + for i, val := range vals { + if i > 0 { + buf.WriteByte('\n') + } + newFormatter(cfg, buf).write(ref.val2node(reflect.ValueOf(val))) + } +} + +// Print writes the DefaultConfig representation of the given values to standard output. +func Print(vals ...interface{}) { + DefaultConfig.Print(vals...) +} + +// Print writes the configured presentation of the given values to standard output. +func (cfg *Config) Print(vals ...interface{}) { + fmt.Println(cfg.Sprint(vals...)) +} + +// Sprint returns a string representation of the given value according to the DefaultConfig. +func Sprint(vals ...interface{}) string { + return DefaultConfig.Sprint(vals...) +} + +// Sprint returns a string representation of the given value according to cfg. +func (cfg *Config) Sprint(vals ...interface{}) string { + buf := new(bytes.Buffer) + cfg.fprint(buf, vals...) + return buf.String() +} + +// Fprint writes the representation of the given value to the writer according to the DefaultConfig. +func Fprint(w io.Writer, vals ...interface{}) (n int64, err error) { + return DefaultConfig.Fprint(w, vals...) +} + +// Fprint writes the representation of the given value to the writer according to the cfg. +func (cfg *Config) Fprint(w io.Writer, vals ...interface{}) (n int64, err error) { + buf := new(bytes.Buffer) + cfg.fprint(buf, vals...) + return buf.WriteTo(w) +} + +// Compare returns a string containing a line-by-line unified diff of the +// values in a and b, using the CompareConfig. +// +// Each line in the output is prefixed with '+', '-', or ' ' to indicate which +// side it's from. Lines from the a side are marked with '-', lines from the +// b side are marked with '+' and lines that are the same on both sides are +// marked with ' '. +// +// The comparison is based on the intentionally-untyped output of Print, and as +// such this comparison is pretty forviving. In particular, if the types of or +// types within in a and b are different but have the same representation, +// Compare will not indicate any differences between them. +func Compare(a, b interface{}) string { + return CompareConfig.Compare(a, b) +} + +// Compare returns a string containing a line-by-line unified diff of the +// values in got and want according to the cfg. +// +// Each line in the output is prefixed with '+', '-', or ' ' to indicate which +// side it's from. Lines from the a side are marked with '-', lines from the +// b side are marked with '+' and lines that are the same on both sides are +// marked with ' '. +// +// The comparison is based on the intentionally-untyped output of Print, and as +// such this comparison is pretty forviving. In particular, if the types of or +// types within in a and b are different but have the same representation, +// Compare will not indicate any differences between them. +func (cfg *Config) Compare(a, b interface{}) string { + diffCfg := *cfg + diffCfg.Diffable = true + return diff.Diff(cfg.Sprint(a), cfg.Sprint(b)) +} diff --git a/vendor/github.com/kylelemons/godebug/pretty/reflect.go b/vendor/github.com/kylelemons/godebug/pretty/reflect.go new file mode 100644 index 000000000..5cd30b7f0 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/reflect.go @@ -0,0 +1,241 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package pretty + +import ( + "encoding" + "fmt" + "reflect" + "sort" +) + +func isZeroVal(val reflect.Value) bool { + if !val.CanInterface() { + return false + } + z := reflect.Zero(val.Type()).Interface() + return reflect.DeepEqual(val.Interface(), z) +} + +// pointerTracker is a helper for tracking pointer chasing to detect cycles. +type pointerTracker struct { + addrs map[uintptr]int // addr[address] = seen count + + lastID int + ids map[uintptr]int // ids[address] = id +} + +// track tracks following a reference (pointer, slice, map, etc). Every call to +// track should be paired with a call to untrack. +func (p *pointerTracker) track(ptr uintptr) { + if p.addrs == nil { + p.addrs = make(map[uintptr]int) + } + p.addrs[ptr]++ +} + +// untrack registers that we have backtracked over the reference to the pointer. +func (p *pointerTracker) untrack(ptr uintptr) { + p.addrs[ptr]-- + if p.addrs[ptr] == 0 { + delete(p.addrs, ptr) + } +} + +// seen returns whether the pointer was previously seen along this path. +func (p *pointerTracker) seen(ptr uintptr) bool { + _, ok := p.addrs[ptr] + return ok +} + +// keep allocates an ID for the given address and returns it. +func (p *pointerTracker) keep(ptr uintptr) int { + if p.ids == nil { + p.ids = make(map[uintptr]int) + } + if _, ok := p.ids[ptr]; !ok { + p.lastID++ + p.ids[ptr] = p.lastID + } + return p.ids[ptr] +} + +// id returns the ID for the given address. +func (p *pointerTracker) id(ptr uintptr) (int, bool) { + if p.ids == nil { + p.ids = make(map[uintptr]int) + } + id, ok := p.ids[ptr] + return id, ok +} + +// reflector adds local state to the recursive reflection logic. +type reflector struct { + *Config + *pointerTracker +} + +// follow handles following a possiblly-recursive reference to the given value +// from the given ptr address. +func (r *reflector) follow(ptr uintptr, val reflect.Value) node { + if r.pointerTracker == nil { + // Tracking disabled + return r.val2node(val) + } + + // If a parent already followed this, emit a reference marker + if r.seen(ptr) { + id := r.keep(ptr) + return ref{id} + } + + // Track the pointer we're following while on this recursive branch + r.track(ptr) + defer r.untrack(ptr) + n := r.val2node(val) + + // If the recursion used this ptr, wrap it with a target marker + if id, ok := r.id(ptr); ok { + return target{id, n} + } + + // Otherwise, return the node unadulterated + return n +} + +func (r *reflector) val2node(val reflect.Value) node { + if !val.IsValid() { + return rawVal("nil") + } + + if val.CanInterface() { + v := val.Interface() + if formatter, ok := r.Formatter[val.Type()]; ok { + if formatter != nil { + res := reflect.ValueOf(formatter).Call([]reflect.Value{val}) + return rawVal(res[0].Interface().(string)) + } + } else { + if s, ok := v.(fmt.Stringer); ok && r.PrintStringers { + return stringVal(s.String()) + } + if t, ok := v.(encoding.TextMarshaler); ok && r.PrintTextMarshalers { + if raw, err := t.MarshalText(); err == nil { // if NOT an error + return stringVal(string(raw)) + } + } + } + } + + switch kind := val.Kind(); kind { + case reflect.Ptr: + if val.IsNil() { + return rawVal("nil") + } + return r.follow(val.Pointer(), val.Elem()) + case reflect.Interface: + if val.IsNil() { + return rawVal("nil") + } + return r.val2node(val.Elem()) + case reflect.String: + return stringVal(val.String()) + case reflect.Slice: + n := list{} + length := val.Len() + ptr := val.Pointer() + for i := 0; i < length; i++ { + n = append(n, r.follow(ptr, val.Index(i))) + } + return n + case reflect.Array: + n := list{} + length := val.Len() + for i := 0; i < length; i++ { + n = append(n, r.val2node(val.Index(i))) + } + return n + case reflect.Map: + // Extract the keys and sort them for stable iteration + keys := val.MapKeys() + pairs := make([]mapPair, 0, len(keys)) + for _, key := range keys { + pairs = append(pairs, mapPair{ + key: new(formatter).compactString(r.val2node(key)), // can't be cyclic + value: val.MapIndex(key), + }) + } + sort.Sort(byKey(pairs)) + + // Process the keys into the final representation + ptr, n := val.Pointer(), keyvals{} + for _, pair := range pairs { + n = append(n, keyval{ + key: pair.key, + val: r.follow(ptr, pair.value), + }) + } + return n + case reflect.Struct: + n := keyvals{} + typ := val.Type() + fields := typ.NumField() + for i := 0; i < fields; i++ { + sf := typ.Field(i) + if !r.IncludeUnexported && sf.PkgPath != "" { + continue + } + field := val.Field(i) + if r.SkipZeroFields && isZeroVal(field) { + continue + } + n = append(n, keyval{sf.Name, r.val2node(field)}) + } + return n + case reflect.Bool: + if val.Bool() { + return rawVal("true") + } + return rawVal("false") + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rawVal(fmt.Sprintf("%d", val.Int())) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return rawVal(fmt.Sprintf("%d", val.Uint())) + case reflect.Uintptr: + return rawVal(fmt.Sprintf("0x%X", val.Uint())) + case reflect.Float32, reflect.Float64: + return rawVal(fmt.Sprintf("%v", val.Float())) + case reflect.Complex64, reflect.Complex128: + return rawVal(fmt.Sprintf("%v", val.Complex())) + } + + // Fall back to the default %#v if we can + if val.CanInterface() { + return rawVal(fmt.Sprintf("%#v", val.Interface())) + } + + return rawVal(val.String()) +} + +type mapPair struct { + key string + value reflect.Value +} + +type byKey []mapPair + +func (v byKey) Len() int { return len(v) } +func (v byKey) Swap(i, j int) { v[i], v[j] = v[j], v[i] } +func (v byKey) Less(i, j int) bool { return v[i].key < v[j].key } diff --git a/vendor/github.com/kylelemons/godebug/pretty/structure.go b/vendor/github.com/kylelemons/godebug/pretty/structure.go new file mode 100644 index 000000000..d876f60ca --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/structure.go @@ -0,0 +1,223 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package pretty + +import ( + "bufio" + "bytes" + "fmt" + "io" + "strconv" + "strings" +) + +// a formatter stores stateful formatting information as well as being +// an io.Writer for simplicity. +type formatter struct { + *bufio.Writer + *Config + + // Self-referential structure tracking + tagNumbers map[int]int // tagNumbers[id] = <#n> +} + +// newFormatter creates a new buffered formatter. For the output to be written +// to the given writer, this must be accompanied by a call to write (or Flush). +func newFormatter(cfg *Config, w io.Writer) *formatter { + return &formatter{ + Writer: bufio.NewWriter(w), + Config: cfg, + tagNumbers: make(map[int]int), + } +} + +func (f *formatter) write(n node) { + defer f.Flush() + n.format(f, "") +} + +func (f *formatter) tagFor(id int) int { + if tag, ok := f.tagNumbers[id]; ok { + return tag + } + if f.tagNumbers == nil { + return 0 + } + tag := len(f.tagNumbers) + 1 + f.tagNumbers[id] = tag + return tag +} + +type node interface { + format(f *formatter, indent string) +} + +func (f *formatter) compactString(n node) string { + switch k := n.(type) { + case stringVal: + return string(k) + case rawVal: + return string(k) + } + + buf := new(bytes.Buffer) + f2 := newFormatter(&Config{Compact: true}, buf) + f2.tagNumbers = f.tagNumbers // reuse tagNumbers just in case + f2.write(n) + return buf.String() +} + +type stringVal string + +func (str stringVal) format(f *formatter, indent string) { + f.WriteString(strconv.Quote(string(str))) +} + +type rawVal string + +func (r rawVal) format(f *formatter, indent string) { + f.WriteString(string(r)) +} + +type keyval struct { + key string + val node +} + +type keyvals []keyval + +func (l keyvals) format(f *formatter, indent string) { + f.WriteByte('{') + + switch { + case f.Compact: + // All on one line: + for i, kv := range l { + if i > 0 { + f.WriteByte(',') + } + f.WriteString(kv.key) + f.WriteByte(':') + kv.val.format(f, indent) + } + case f.Diffable: + f.WriteByte('\n') + inner := indent + " " + // Each value gets its own line: + for _, kv := range l { + f.WriteString(inner) + f.WriteString(kv.key) + f.WriteString(": ") + kv.val.format(f, inner) + f.WriteString(",\n") + } + f.WriteString(indent) + default: + keyWidth := 0 + for _, kv := range l { + if kw := len(kv.key); kw > keyWidth { + keyWidth = kw + } + } + alignKey := indent + " " + alignValue := strings.Repeat(" ", keyWidth) + inner := alignKey + alignValue + " " + // First and last line shared with bracket: + for i, kv := range l { + if i > 0 { + f.WriteString(",\n") + f.WriteString(alignKey) + } + f.WriteString(kv.key) + f.WriteString(": ") + f.WriteString(alignValue[len(kv.key):]) + kv.val.format(f, inner) + } + } + + f.WriteByte('}') +} + +type list []node + +func (l list) format(f *formatter, indent string) { + if max := f.ShortList; max > 0 { + short := f.compactString(l) + if len(short) <= max { + f.WriteString(short) + return + } + } + + f.WriteByte('[') + + switch { + case f.Compact: + // All on one line: + for i, v := range l { + if i > 0 { + f.WriteByte(',') + } + v.format(f, indent) + } + case f.Diffable: + f.WriteByte('\n') + inner := indent + " " + // Each value gets its own line: + for _, v := range l { + f.WriteString(inner) + v.format(f, inner) + f.WriteString(",\n") + } + f.WriteString(indent) + default: + inner := indent + " " + // First and last line shared with bracket: + for i, v := range l { + if i > 0 { + f.WriteString(",\n") + f.WriteString(inner) + } + v.format(f, inner) + } + } + + f.WriteByte(']') +} + +type ref struct { + id int +} + +func (r ref) format(f *formatter, indent string) { + fmt.Fprintf(f, "", f.tagFor(r.id)) +} + +type target struct { + id int + value node +} + +func (t target) format(f *formatter, indent string) { + tag := fmt.Sprintf("<#%d> ", f.tagFor(t.id)) + switch { + case f.Diffable, f.Compact: + // no indent changes + default: + indent += strings.Repeat(" ", len(tag)) + } + f.WriteString(tag) + t.value.format(f, indent) +} diff --git a/vendor/github.com/linode/linodego/.gitignore b/vendor/github.com/linode/linodego/.gitignore index dcb4cc633..cec47a064 100644 --- a/vendor/github.com/linode/linodego/.gitignore +++ b/vendor/github.com/linode/linodego/.gitignore @@ -16,8 +16,8 @@ # Common IDE paths .vscode/ +.idea/ vendor/**/ .env coverage.txt - diff --git a/vendor/github.com/linode/linodego/.gitmodules b/vendor/github.com/linode/linodego/.gitmodules new file mode 100644 index 000000000..df7dc11d7 --- /dev/null +++ b/vendor/github.com/linode/linodego/.gitmodules @@ -0,0 +1,3 @@ +[submodule "tod_scripts"] + path = tod_scripts + url = https://github.com/linode/TOD-test-report-uploader.git diff --git a/vendor/github.com/linode/linodego/.golangci.yml b/vendor/github.com/linode/linodego/.golangci.yml index 40983e5b0..bc15e56d7 100644 --- a/vendor/github.com/linode/linodego/.golangci.yml +++ b/vendor/github.com/linode/linodego/.golangci.yml @@ -29,6 +29,19 @@ linters-settings: linters: enable-all: true disable: + # deprecated linters + - deadcode + - ifshort + - varcheck + - nosnakecase + #################### + + # conflicted with go fmt + - nolintlint + + # workaround to avoid linter failures of getting malformed json + - musttag + - bodyclose - contextcheck - nilerr @@ -71,4 +84,7 @@ linters: - cyclop - godot - exhaustive + - depguard + - tagalign + - inamedparam fast: false diff --git a/vendor/github.com/linode/linodego/CODEOWNERS b/vendor/github.com/linode/linodego/CODEOWNERS new file mode 100644 index 000000000..34864d6fc --- /dev/null +++ b/vendor/github.com/linode/linodego/CODEOWNERS @@ -0,0 +1 @@ +* @linode/dx diff --git a/vendor/github.com/linode/linodego/Makefile b/vendor/github.com/linode/linodego/Makefile index ebe4ecbc7..3597c2a7b 100644 --- a/vendor/github.com/linode/linodego/Makefile +++ b/vendor/github.com/linode/linodego/Makefile @@ -8,16 +8,16 @@ TEST_TIMEOUT := 5h SKIP_DOCKER ?= 0 GOLANGCILINT := golangci-lint -GOLANGCILINT_IMG := golangci/golangci-lint:v1.46.2-alpine +GOLANGCILINT_IMG := golangci/golangci-lint:latest GOLANGCILINT_ARGS := run -LINODE_URL := https://api.linode.com/ +LINODE_URL ?= https://api.linode.com/ PACKAGES := $(shell go list ./... | grep -v integration) SKIP_LINT ?= 0 -.PHONY: build vet test refresh-fixtures clean-fixtures lint run_fixtures sanitize fixtures godoc testint testunit tidy +.PHONY: build vet test refresh-fixtures clean clean-cov clean-fixtures lint run_fixtures sanitize fixtures godoc testint testunit testcov tidy test: build lint testunit testint @@ -29,6 +29,18 @@ testunit: testint: cd test && make test +testcov-func: + @go test -v -coverprofile="coverage.txt" . > /dev/null 2>&1 + @go tool cover -func coverage.txt + +# Note for WSL Users, set BROWSER=wslview +testcov-html: + @go test -v -coverprofile="coverage.txt" . > /dev/null 2>&1 + @go tool cover -html coverage.txt + +smoketest: + cd test && make smoketest + build: vet lint go build ./... cd k8s && go build ./... @@ -46,8 +58,13 @@ else docker run --rm -v $(shell pwd):/app -w /app $(GOLANGCILINT_IMG) $(GOLANGCILINT) $(GOLANGCILINT_ARGS) endif +clean: clean-cov + +clean-cov: + @-rm -f coverage.txt + clean-fixtures: - @-rm fixtures/*.yaml + @-rm -f fixtures/*.yaml refresh-fixtures: clean-fixtures fixtures diff --git a/vendor/github.com/linode/linodego/account_availability.go b/vendor/github.com/linode/linodego/account_availability.go new file mode 100644 index 000000000..9a846415c --- /dev/null +++ b/vendor/github.com/linode/linodego/account_availability.go @@ -0,0 +1,62 @@ +package linodego + +import ( + "context" + "fmt" + "net/url" + + "github.com/go-resty/resty/v2" +) + +// AccountAvailability returns the resources information in a region which are NOT available to an account. +type AccountAvailability struct { + // region id + Region string `json:"region"` + + // the unavailable resources in a region to the customer + Unavailable []string `json:"unavailable"` +} + +// AccountAvailabilityPagedResponse represents a paginated Account Availability API response +type AccountAvailabilityPagedResponse struct { + *PageOptions + Data []AccountAvailability `json:"data"` +} + +// endpoint gets the endpoint URL for AccountAvailability +func (AccountAvailabilityPagedResponse) endpoint(_ ...any) string { + return "/account/availability" +} + +func (resp *AccountAvailabilityPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(AccountAvailabilityPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*AccountAvailabilityPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +// ListAccountAvailabilities lists all available regions and the resources which are NOT available to the account. +func (c *Client) ListAccountAvailabilities(ctx context.Context, opts *ListOptions) ([]AccountAvailability, error) { + response := AccountAvailabilityPagedResponse{} + err := c.listHelper(ctx, &response, opts) + if err != nil { + return nil, err + } + return response.Data, nil +} + +// GetAccountAvailability gets the unavailable resources in a region to the customer. +func (c *Client) GetAccountAvailability(ctx context.Context, regionID string) (*AccountAvailability, error) { + req := c.R(ctx).SetResult(&AccountAvailability{}) + regionID = url.PathEscape(regionID) + b := fmt.Sprintf("account/availability/%s", regionID) + r, err := coupleAPIErrors(req.Get(b)) + if err != nil { + return nil, err + } + + return r.Result().(*AccountAvailability), nil +} diff --git a/vendor/github.com/linode/linodego/account_betas.go b/vendor/github.com/linode/linodego/account_betas.go new file mode 100644 index 000000000..0897a4a73 --- /dev/null +++ b/vendor/github.com/linode/linodego/account_betas.go @@ -0,0 +1,114 @@ +package linodego + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "time" + + "github.com/go-resty/resty/v2" + "github.com/linode/linodego/internal/parseabletime" +) + +// The details and enrollment information of a Beta program that an account is enrolled in. +type AccountBetaProgram struct { + Label string `json:"label"` + ID string `json:"id"` + Description string `json:"description"` + Started *time.Time `json:"-"` + Ended *time.Time `json:"-"` + + // Date the account was enrolled in the beta program + Enrolled *time.Time `json:"-"` +} + +// AccountBetaProgramCreateOpts fields are those accepted by JoinBetaProgram +type AccountBetaProgramCreateOpts struct { + ID string `json:"id"` +} + +// AccountBetasPagedResponse represents a paginated Account Beta Programs API response +type AccountBetasPagedResponse struct { + *PageOptions + Data []AccountBetaProgram `json:"data"` +} + +// endpoint gets the endpoint URL for AccountBetaProgram +func (AccountBetasPagedResponse) endpoint(_ ...any) string { + return "/account/betas" +} + +// UnmarshalJSON implements the json.Unmarshaler interface +func (cBeta *AccountBetaProgram) UnmarshalJSON(b []byte) error { + type Mask AccountBetaProgram + + p := struct { + *Mask + Started *parseabletime.ParseableTime `json:"started"` + Ended *parseabletime.ParseableTime `json:"ended"` + Enrolled *parseabletime.ParseableTime `json:"enrolled"` + }{ + Mask: (*Mask)(cBeta), + } + + if err := json.Unmarshal(b, &p); err != nil { + return err + } + + cBeta.Started = (*time.Time)(p.Started) + cBeta.Ended = (*time.Time)(p.Ended) + cBeta.Enrolled = (*time.Time)(p.Enrolled) + + return nil +} + +func (resp *AccountBetasPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(AccountBetasPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*AccountBetasPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +// ListAccountBetaPrograms lists all beta programs an account is enrolled in. +func (c *Client) ListAccountBetaPrograms(ctx context.Context, opts *ListOptions) ([]AccountBetaProgram, error) { + response := AccountBetasPagedResponse{} + err := c.listHelper(ctx, &response, opts) + if err != nil { + return nil, err + } + return response.Data, nil +} + +// GetAccountBetaProgram gets the details of a beta program an account is enrolled in. +func (c *Client) GetAccountBetaProgram(ctx context.Context, betaID string) (*AccountBetaProgram, error) { + req := c.R(ctx).SetResult(&AccountBetaProgram{}) + betaID = url.PathEscape(betaID) + b := fmt.Sprintf("/account/betas/%s", betaID) + r, err := coupleAPIErrors(req.Get(b)) + if err != nil { + return nil, err + } + + return r.Result().(*AccountBetaProgram), nil +} + +// JoinBetaProgram enrolls an account into a beta program. +func (c *Client) JoinBetaProgram(ctx context.Context, opts AccountBetaProgramCreateOpts) (*AccountBetaProgram, error) { + body, err := json.Marshal(opts) + if err != nil { + return nil, err + } + + e := "account/betas" + req := c.R(ctx).SetResult(&AccountBetaProgram{}).SetBody(string(body)) + r, err := coupleAPIErrors(req.Post(e)) + if err != nil { + return nil, err + } + + return r.Result().(*AccountBetaProgram), nil +} diff --git a/vendor/github.com/linode/linodego/account_events.go b/vendor/github.com/linode/linodego/account_events.go index e8306a1ba..8a9d9667f 100644 --- a/vendor/github.com/linode/linodego/account_events.go +++ b/vendor/github.com/linode/linodego/account_events.go @@ -55,100 +55,144 @@ type EventAction string // EventAction constants represent the actions that cause an Event. New actions may be added in the future. const ( - ActionAccountUpdate EventAction = "account_update" - ActionAccountSettingsUpdate EventAction = "account_settings_update" - ActionBackupsEnable EventAction = "backups_enable" - ActionBackupsCancel EventAction = "backups_cancel" - ActionBackupsRestore EventAction = "backups_restore" - ActionCommunityQuestionReply EventAction = "community_question_reply" - ActionCommunityLike EventAction = "community_like" - ActionCreateCardUpdated EventAction = "credit_card_updated" - ActionDatabaseCreate EventAction = "database_create" - ActionDatabaseDegraded EventAction = "database_degraded" - ActionDatabaseDelete EventAction = "database_delete" - ActionDatabaseFailed EventAction = "database_failed" - ActionDatabaseUpdate EventAction = "database_update" - ActionDatabaseCreateFailed EventAction = "database_create_failed" - ActionDatabaseUpdateFailed EventAction = "database_update_failed" - ActionDatabaseBackupCreate EventAction = "database_backup_create" - ActionDatabaseBackupRestore EventAction = "database_backup_restore" - ActionDatabaseCredentialsReset EventAction = "database_credentials_reset" - ActionDiskCreate EventAction = "disk_create" - ActionDiskDelete EventAction = "disk_delete" - ActionDiskUpdate EventAction = "disk_update" - ActionDiskDuplicate EventAction = "disk_duplicate" - ActionDiskImagize EventAction = "disk_imagize" - ActionDiskResize EventAction = "disk_resize" - ActionDNSRecordCreate EventAction = "dns_record_create" - ActionDNSRecordDelete EventAction = "dns_record_delete" - ActionDNSRecordUpdate EventAction = "dns_record_update" - ActionDNSZoneCreate EventAction = "dns_zone_create" - ActionDNSZoneDelete EventAction = "dns_zone_delete" - ActionDNSZoneUpdate EventAction = "dns_zone_update" - ActionFirewallCreate EventAction = "firewall_create" - ActionFirewallDelete EventAction = "firewall_delete" - ActionFirewallDisable EventAction = "firewall_disable" - ActionFirewallEnable EventAction = "firewall_enable" - ActionFirewallUpdate EventAction = "firewall_update" - ActionFirewallDeviceAdd EventAction = "firewall_device_add" - ActionFirewallDeviceRemove EventAction = "firewall_device_remove" - ActionHostReboot EventAction = "host_reboot" - ActionImageDelete EventAction = "image_delete" - ActionImageUpdate EventAction = "image_update" - ActionLassieReboot EventAction = "lassie_reboot" - ActionLinodeAddIP EventAction = "linode_addip" - ActionLinodeBoot EventAction = "linode_boot" - ActionLinodeClone EventAction = "linode_clone" - ActionLinodeCreate EventAction = "linode_create" - ActionLinodeDelete EventAction = "linode_delete" - ActionLinodeUpdate EventAction = "linode_update" - ActionLinodeDeleteIP EventAction = "linode_deleteip" - ActionLinodeMigrate EventAction = "linode_migrate" - ActionLinodeMutate EventAction = "linode_mutate" - ActionLinodeMutateCreate EventAction = "linode_mutate_create" - ActionLinodeReboot EventAction = "linode_reboot" - ActionLinodeRebuild EventAction = "linode_rebuild" - ActionLinodeResize EventAction = "linode_resize" - ActionLinodeResizeCreate EventAction = "linode_resize_create" - ActionLinodeShutdown EventAction = "linode_shutdown" - ActionLinodeSnapshot EventAction = "linode_snapshot" - ActionLinodeConfigCreate EventAction = "linode_config_create" - ActionLinodeConfigDelete EventAction = "linode_config_delete" - ActionLinodeConfigUpdate EventAction = "linode_config_update" - ActionLishBoot EventAction = "lish_boot" - ActionLKENodeCreate EventAction = "lke_node_create" - ActionLongviewClientCreate EventAction = "longviewclient_create" - ActionLongviewClientDelete EventAction = "longviewclient_delete" - ActionLongviewClientUpdate EventAction = "longviewclient_update" - ActionManagedDisabled EventAction = "managed_disabled" - ActionManagedEnabled EventAction = "managed_enabled" - ActionManagedServiceCreate EventAction = "managed_service_create" - ActionManagedServiceDelete EventAction = "managed_service_delete" - ActionNodebalancerCreate EventAction = "nodebalancer_create" - ActionNodebalancerDelete EventAction = "nodebalancer_delete" - ActionNodebalancerUpdate EventAction = "nodebalancer_update" - ActionNodebalancerConfigCreate EventAction = "nodebalancer_config_create" - ActionNodebalancerConfigDelete EventAction = "nodebalancer_config_delete" - ActionNodebalancerConfigUpdate EventAction = "nodebalancer_config_update" - ActionPasswordReset EventAction = "password_reset" - ActionPaymentSubmitted EventAction = "payment_submitted" - ActionStackScriptCreate EventAction = "stackscript_create" - ActionStackScriptDelete EventAction = "stackscript_delete" - ActionStackScriptUpdate EventAction = "stackscript_update" - ActionStackScriptPublicize EventAction = "stackscript_publicize" - ActionStackScriptRevise EventAction = "stackscript_revise" - ActionTFADisabled EventAction = "tfa_disabled" - ActionTFAEnabled EventAction = "tfa_enabled" - ActionTicketAttachmentUpload EventAction = "ticket_attachment_upload" - ActionTicketCreate EventAction = "ticket_create" - ActionTicketUpdate EventAction = "ticket_update" - ActionVolumeAttach EventAction = "volume_attach" - ActionVolumeClone EventAction = "volume_clone" - ActionVolumeCreate EventAction = "volume_create" - ActionVolumeDelte EventAction = "volume_delete" - ActionVolumeUpdate EventAction = "volume_update" - ActionVolumeDetach EventAction = "volume_detach" - ActionVolumeResize EventAction = "volume_resize" + ActionAccountUpdate EventAction = "account_update" + ActionAccountSettingsUpdate EventAction = "account_settings_update" + ActionBackupsEnable EventAction = "backups_enable" + ActionBackupsCancel EventAction = "backups_cancel" + ActionBackupsRestore EventAction = "backups_restore" + ActionCommunityQuestionReply EventAction = "community_question_reply" + ActionCommunityLike EventAction = "community_like" + ActionCreateCardUpdated EventAction = "credit_card_updated" + ActionDatabaseCreate EventAction = "database_create" + ActionDatabaseDegraded EventAction = "database_degraded" + ActionDatabaseDelete EventAction = "database_delete" + ActionDatabaseFailed EventAction = "database_failed" + ActionDatabaseUpdate EventAction = "database_update" + ActionDatabaseCreateFailed EventAction = "database_create_failed" + ActionDatabaseUpdateFailed EventAction = "database_update_failed" + ActionDatabaseBackupCreate EventAction = "database_backup_create" + ActionDatabaseBackupRestore EventAction = "database_backup_restore" + ActionDatabaseCredentialsReset EventAction = "database_credentials_reset" + ActionDiskCreate EventAction = "disk_create" + ActionDiskDelete EventAction = "disk_delete" + ActionDiskUpdate EventAction = "disk_update" + ActionDiskDuplicate EventAction = "disk_duplicate" + ActionDiskImagize EventAction = "disk_imagize" + ActionDiskResize EventAction = "disk_resize" + ActionDNSRecordCreate EventAction = "dns_record_create" + ActionDNSRecordDelete EventAction = "dns_record_delete" + ActionDNSRecordUpdate EventAction = "dns_record_update" + ActionDNSZoneCreate EventAction = "dns_zone_create" + ActionDNSZoneDelete EventAction = "dns_zone_delete" + ActionDNSZoneUpdate EventAction = "dns_zone_update" + ActionDNSZoneImport EventAction = "dns_zone_import" + ActionEntityTransferAccept EventAction = "entity_transfer_accept" + ActionEntityTransferCancel EventAction = "entity_transfer_cancel" + ActionEntityTransferCreate EventAction = "entity_transfer_create" + ActionEntityTransferFail EventAction = "entity_transfer_fail" + ActionEntityTransferStale EventAction = "entity_transfer_stale" + ActionFirewallCreate EventAction = "firewall_create" + ActionFirewallDelete EventAction = "firewall_delete" + ActionFirewallDisable EventAction = "firewall_disable" + ActionFirewallEnable EventAction = "firewall_enable" + ActionFirewallUpdate EventAction = "firewall_update" + ActionFirewallDeviceAdd EventAction = "firewall_device_add" + ActionFirewallDeviceRemove EventAction = "firewall_device_remove" + ActionHostReboot EventAction = "host_reboot" + ActionImageDelete EventAction = "image_delete" + ActionImageUpdate EventAction = "image_update" + ActionImageUpload EventAction = "image_upload" + ActionIPAddressUpdate EventAction = "ipaddress_update" + ActionLassieReboot EventAction = "lassie_reboot" + ActionLinodeAddIP EventAction = "linode_addip" + ActionLinodeBoot EventAction = "linode_boot" + ActionLinodeClone EventAction = "linode_clone" + ActionLinodeCreate EventAction = "linode_create" + ActionLinodeDelete EventAction = "linode_delete" + ActionLinodeUpdate EventAction = "linode_update" + ActionLinodeDeleteIP EventAction = "linode_deleteip" + ActionLinodeMigrate EventAction = "linode_migrate" + ActionLinodeMigrateDatacenter EventAction = "linode_migrate_datacenter" + ActionLinodeMigrateDatacenterCreate EventAction = "linode_migrate_datacenter_create" + ActionLinodeMutate EventAction = "linode_mutate" + ActionLinodeMutateCreate EventAction = "linode_mutate_create" + ActionLinodeReboot EventAction = "linode_reboot" + ActionLinodeRebuild EventAction = "linode_rebuild" + ActionLinodeResize EventAction = "linode_resize" + ActionLinodeResizeCreate EventAction = "linode_resize_create" + ActionLinodeShutdown EventAction = "linode_shutdown" + ActionLinodeSnapshot EventAction = "linode_snapshot" + ActionLinodeConfigCreate EventAction = "linode_config_create" + ActionLinodeConfigDelete EventAction = "linode_config_delete" + ActionLinodeConfigUpdate EventAction = "linode_config_update" + ActionLishBoot EventAction = "lish_boot" + ActionLKENodeCreate EventAction = "lke_node_create" + ActionLongviewClientCreate EventAction = "longviewclient_create" + ActionLongviewClientDelete EventAction = "longviewclient_delete" + ActionLongviewClientUpdate EventAction = "longviewclient_update" + ActionManagedDisabled EventAction = "managed_disabled" + ActionManagedEnabled EventAction = "managed_enabled" + ActionManagedServiceCreate EventAction = "managed_service_create" + ActionManagedServiceDelete EventAction = "managed_service_delete" + ActionNodebalancerCreate EventAction = "nodebalancer_create" + ActionNodebalancerDelete EventAction = "nodebalancer_delete" + ActionNodebalancerUpdate EventAction = "nodebalancer_update" + ActionNodebalancerConfigCreate EventAction = "nodebalancer_config_create" + ActionNodebalancerConfigDelete EventAction = "nodebalancer_config_delete" + ActionNodebalancerConfigUpdate EventAction = "nodebalancer_config_update" + ActionNodebalancerFirewallModificationSuccess EventAction = "nodebalancer_firewall_modification_success" + ActionNodebalancerFirewallModificationFailed EventAction = "nodebalancer_firewall_modification_failed" + ActionNodebalancerNodeCreate EventAction = "nodebalancer_node_create" + ActionNodebalancerNodeDelete EventAction = "nodebalancer_node_delete" + ActionNodebalancerNodeUpdate EventAction = "nodebalancer_node_update" + ActionOAuthClientCreate EventAction = "oauth_client_create" + ActionOAuthClientDelete EventAction = "oauth_client_delete" + ActionOAuthClientSecretReset EventAction = "oauth_client_secret_reset" //#nosec G101 + ActionOAuthClientUpdate EventAction = "oauth_client_update" + ActionPaymentMethodAdd EventAction = "payment_method_add" + ActionPaymentSubmitted EventAction = "payment_submitted" + ActionPasswordReset EventAction = "password_reset" + ActionProfileUpdate EventAction = "profile_update" + ActionStackScriptCreate EventAction = "stackscript_create" + ActionStackScriptDelete EventAction = "stackscript_delete" + ActionStackScriptUpdate EventAction = "stackscript_update" + ActionStackScriptPublicize EventAction = "stackscript_publicize" + ActionStackScriptRevise EventAction = "stackscript_revise" + ActionTagCreate EventAction = "tag_create" + ActionTagDelete EventAction = "tag_delete" + ActionTFADisabled EventAction = "tfa_disabled" + ActionTFAEnabled EventAction = "tfa_enabled" + ActionTicketAttachmentUpload EventAction = "ticket_attachment_upload" + ActionTicketCreate EventAction = "ticket_create" + ActionTicketUpdate EventAction = "ticket_update" + ActionTokenCreate EventAction = "token_create" + ActionTokenDelete EventAction = "token_delete" + ActionTokenUpdate EventAction = "token_update" + ActionUserCreate EventAction = "user_create" + ActionUserDelete EventAction = "user_delete" + ActionUserUpdate EventAction = "user_update" + ActionUserSSHKeyAdd EventAction = "user_ssh_key_add" + ActionUserSSHKeyDelete EventAction = "user_ssh_key_delete" + ActionUserSSHKeyUpdate EventAction = "user_ssh_key_update" + ActionVLANAttach EventAction = "vlan_attach" + ActionVLANDetach EventAction = "vlan_detach" + ActionVolumeAttach EventAction = "volume_attach" + ActionVolumeClone EventAction = "volume_clone" + ActionVolumeCreate EventAction = "volume_create" + ActionVolumeDelete EventAction = "volume_delete" + ActionVolumeUpdate EventAction = "volume_update" + ActionVolumeDetach EventAction = "volume_detach" + ActionVolumeResize EventAction = "volume_resize" + ActionVPCCreate EventAction = "vpc_create" + ActionVPCDelete EventAction = "vpc_delete" + ActionVPCUpdate EventAction = "vpc_update" + ActionVPCSubnetCreate EventAction = "subnet_create" + ActionVPCSubnetDelete EventAction = "subnet_delete" + ActionVPCSubnetUpdate EventAction = "subnet_update" + + // deprecated due to incorrect spelling, + // to be removed in the next major version release. + ActionVolumeDelte EventAction = "volume_delete" ) // EntityType constants start with Entity and include Linode API Event Entity Types @@ -162,6 +206,8 @@ const ( EntityDomain EntityType = "domain" EntityFirewall EntityType = "firewall" EntityNodebalancer EntityType = "nodebalancer" + EntityVPC EntityType = "vpc" + EntityVPCSubnet EntityType = "subnet" ) // EventStatus constants start with Event and include Linode API Event Status values diff --git a/vendor/github.com/linode/linodego/account_invoices.go b/vendor/github.com/linode/linodego/account_invoices.go index 26529aaa7..d068662fa 100644 --- a/vendor/github.com/linode/linodego/account_invoices.go +++ b/vendor/github.com/linode/linodego/account_invoices.go @@ -18,13 +18,15 @@ type Invoice struct { Date *time.Time `json:"-"` } -// InvoiceItem structs reflect an single billable activity associate with an Invoice +// InvoiceItem structs reflect a single billable activity associate with an Invoice type InvoiceItem struct { Label string `json:"label"` Type string `json:"type"` UnitPrice int `json:"unitprice"` Quantity int `json:"quantity"` Amount float32 `json:"amount"` + Tax float32 `json:"tax"` + Region *string `json:"region"` From *time.Time `json:"-"` To *time.Time `json:"-"` } @@ -103,7 +105,7 @@ func (i *InvoiceItem) UnmarshalJSON(b []byte) error { return nil } -// GetInvoice gets the a single Invoice matching the provided ID +// GetInvoice gets a single Invoice matching the provided ID func (c *Client) GetInvoice(ctx context.Context, invoiceID int) (*Invoice, error) { req := c.R(ctx).SetResult(&Invoice{}) e := fmt.Sprintf("account/invoices/%d", invoiceID) diff --git a/vendor/github.com/linode/linodego/account_oauth_client.go b/vendor/github.com/linode/linodego/account_oauth_client.go index 1a43b6083..dba898d29 100644 --- a/vendor/github.com/linode/linodego/account_oauth_client.go +++ b/vendor/github.com/linode/linodego/account_oauth_client.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) @@ -119,6 +120,7 @@ func (c *Client) ListOAuthClients(ctx context.Context, opts *ListOptions) ([]OAu // GetOAuthClient gets the OAuthClient with the provided ID func (c *Client) GetOAuthClient(ctx context.Context, clientID string) (*OAuthClient, error) { req := c.R(ctx).SetResult(&OAuthClient{}) + clientID = url.PathEscape(clientID) e := fmt.Sprintf("account/oauth-clients/%s", clientID) r, err := coupleAPIErrors(req.Get(e)) if err != nil { @@ -153,6 +155,9 @@ func (c *Client) UpdateOAuthClient(ctx context.Context, clientID string, opts OA } req := c.R(ctx).SetResult(&OAuthClient{}).SetBody(string(body)) + + clientID = url.PathEscape(clientID) + e := fmt.Sprintf("account/oauth-clients/%s", clientID) r, err := coupleAPIErrors(req.Put(e)) if err != nil { @@ -164,6 +169,7 @@ func (c *Client) UpdateOAuthClient(ctx context.Context, clientID string, opts OA // DeleteOAuthClient deletes the OAuthClient with the specified id func (c *Client) DeleteOAuthClient(ctx context.Context, clientID string) error { + clientID = url.PathEscape(clientID) e := fmt.Sprintf("account/oauth-clients/%s", clientID) _, err := coupleAPIErrors(c.R(ctx).Delete(e)) return err diff --git a/vendor/github.com/linode/linodego/account_settings.go b/vendor/github.com/linode/linodego/account_settings.go index bf60162d0..9a4b1362b 100644 --- a/vendor/github.com/linode/linodego/account_settings.go +++ b/vendor/github.com/linode/linodego/account_settings.go @@ -29,6 +29,7 @@ type AccountSettingsUpdateOptions struct { BackupsEnabled *bool `json:"backups_enabled,omitempty"` // A plan name like "longview-3"..."longview-100", or a nil value for to cancel any existing subscription plan. + // Deprecated: Use PUT /longview/plan instead to update the LongviewSubscription LongviewSubscription *string `json:"longview_subscription,omitempty"` // The default network helper setting for all new Linodes and Linode Configs for all users on the account. diff --git a/vendor/github.com/linode/linodego/account_transfer.go b/vendor/github.com/linode/linodego/account_transfer.go new file mode 100644 index 000000000..115573021 --- /dev/null +++ b/vendor/github.com/linode/linodego/account_transfer.go @@ -0,0 +1,33 @@ +package linodego + +import "context" + +// AccountTransfer represents an Account's network utilization for the current month. +type AccountTransfer struct { + Billable int `json:"billable"` + Quota int `json:"quota"` + Used int `json:"used"` + + RegionTransfers []AccountTransferRegion `json:"region_transfers"` +} + +// AccountTransferRegion represents an Account's network utilization for the current month +// in a given region. +type AccountTransferRegion struct { + ID string `json:"id"` + Billable int `json:"billable"` + Quota int `json:"quota"` + Used int `json:"used"` +} + +// GetAccountTransfer gets current Account's network utilization for the current month. +func (c *Client) GetAccountTransfer(ctx context.Context) (*AccountTransfer, error) { + req := c.R(ctx).SetResult(&AccountTransfer{}) + e := "account/transfer" + r, err := coupleAPIErrors(req.Get(e)) + if err != nil { + return nil, err + } + + return r.Result().(*AccountTransfer), nil +} diff --git a/vendor/github.com/linode/linodego/account_user_grants.go b/vendor/github.com/linode/linodego/account_user_grants.go index 33b8c15ea..221fb5f7b 100644 --- a/vendor/github.com/linode/linodego/account_user_grants.go +++ b/vendor/github.com/linode/linodego/account_user_grants.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" ) type GrantPermissionLevel string @@ -68,6 +69,7 @@ type UserGrantsUpdateOptions struct { } func (c *Client) GetUserGrants(ctx context.Context, username string) (*UserGrants, error) { + username = url.PathEscape(username) e := fmt.Sprintf("account/users/%s/grants", username) req := c.R(ctx).SetResult(&UserGrants{}) r, err := coupleAPIErrors(req.Get(e)) @@ -84,6 +86,7 @@ func (c *Client) UpdateUserGrants(ctx context.Context, username string, opts Use return nil, err } + username = url.PathEscape(username) e := fmt.Sprintf("account/users/%s/grants", username) req := c.R(ctx).SetResult(&UserGrants{}).SetBody(string(body)) r, err := coupleAPIErrors(req.Put(e)) diff --git a/vendor/github.com/linode/linodego/account_users.go b/vendor/github.com/linode/linodego/account_users.go index 4130163e1..d9633d881 100644 --- a/vendor/github.com/linode/linodego/account_users.go +++ b/vendor/github.com/linode/linodego/account_users.go @@ -4,17 +4,22 @@ import ( "context" "encoding/json" "fmt" + "net/url" + "time" "github.com/go-resty/resty/v2" + "github.com/linode/linodego/internal/parseabletime" ) // User represents a User object type User struct { - Username string `json:"username"` - Email string `json:"email"` - Restricted bool `json:"restricted"` - TFAEnabled bool `json:"tfa_enabled"` - SSHKeys []string `json:"ssh_keys"` + Username string `json:"username"` + Email string `json:"email"` + Restricted bool `json:"restricted"` + TFAEnabled bool `json:"tfa_enabled"` + SSHKeys []string `json:"ssh_keys"` + PasswordCreated *time.Time `json:"-"` + VerifiedPhoneNumber *string `json:"verified_phone_number"` } // UserCreateOptions fields are those accepted by CreateUser @@ -30,6 +35,26 @@ type UserUpdateOptions struct { Restricted *bool `json:"restricted,omitempty"` } +// UnmarshalJSON implements the json.Unmarshaler interface +func (i *User) UnmarshalJSON(b []byte) error { + type Mask User + + p := struct { + *Mask + PasswordCreated *parseabletime.ParseableTime `json:"password_created"` + }{ + Mask: (*Mask)(i), + } + + if err := json.Unmarshal(b, &p); err != nil { + return err + } + + i.PasswordCreated = (*time.Time)(p.PasswordCreated) + + return nil +} + // GetCreateOptions converts a User to UserCreateOptions for use in CreateUser func (i User) GetCreateOptions() (o UserCreateOptions) { o.Username = i.Username @@ -81,6 +106,7 @@ func (c *Client) ListUsers(ctx context.Context, opts *ListOptions) ([]User, erro // GetUser gets the user with the provided ID func (c *Client) GetUser(ctx context.Context, userID string) (*User, error) { + userID = url.PathEscape(userID) e := fmt.Sprintf("account/users/%s", userID) req := c.R(ctx).SetResult(&User{}) r, err := coupleAPIErrors(req.Get(e)) @@ -116,6 +142,7 @@ func (c *Client) UpdateUser(ctx context.Context, userID string, opts UserUpdateO return nil, err } + userID = url.PathEscape(userID) e := fmt.Sprintf("account/users/%s", userID) req := c.R(ctx).SetResult(&User{}).SetBody(string(body)) r, err := coupleAPIErrors(req.Put(e)) @@ -128,6 +155,7 @@ func (c *Client) UpdateUser(ctx context.Context, userID string, opts UserUpdateO // DeleteUser deletes the User with the specified id func (c *Client) DeleteUser(ctx context.Context, userID string) error { + userID = url.PathEscape(userID) e := fmt.Sprintf("account/users/%s", userID) _, err := coupleAPIErrors(c.R(ctx).Delete(e)) return err diff --git a/vendor/github.com/linode/linodego/betas.go b/vendor/github.com/linode/linodego/betas.go new file mode 100644 index 000000000..9cd84ad57 --- /dev/null +++ b/vendor/github.com/linode/linodego/betas.go @@ -0,0 +1,99 @@ +package linodego + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "time" + + "github.com/go-resty/resty/v2" + "github.com/linode/linodego/internal/parseabletime" +) + +// Beta Program is a new product or service that is not generally available to all Akamai customers. +// Users must enroll into a beta in order to access the functionality. +type BetaProgram struct { + Label string `json:"label"` + ID string `json:"id"` + Description string `json:"description"` + + // Start date of the beta program. + Started *time.Time `json:"-"` + + // End date of the beta program. + Ended *time.Time `json:"-"` + + // Greenlight is a program that allows customers to gain access to + // certain beta programs and to collect direct feedback from those customers. + GreenlightOnly bool `json:"greenlight_only"` + + // Link to product marketing page for the beta program. + MoreInfo string `json:"more_info"` +} + +// BetasPagedResponse represents a paginated Beta Programs API response +type BetasPagedResponse struct { + *PageOptions + Data []BetaProgram `json:"data"` +} + +// endpoint gets the endpoint URL for BetaProgram +func (BetasPagedResponse) endpoint(_ ...any) string { + return "/betas" +} + +// UnmarshalJSON implements the json.Unmarshaler interface +func (beta *BetaProgram) UnmarshalJSON(b []byte) error { + type Mask BetaProgram + + p := struct { + *Mask + Started *parseabletime.ParseableTime `json:"started"` + Ended *parseabletime.ParseableTime `json:"ended"` + }{ + Mask: (*Mask)(beta), + } + + if err := json.Unmarshal(b, &p); err != nil { + return err + } + + beta.Started = (*time.Time)(p.Started) + beta.Ended = (*time.Time)(p.Ended) + + return nil +} + +func (resp *BetasPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(BetasPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*BetasPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +// ListBetaPrograms lists active beta programs +func (c *Client) ListBetaPrograms(ctx context.Context, opts *ListOptions) ([]BetaProgram, error) { + response := BetasPagedResponse{} + err := c.listHelper(ctx, &response, opts) + if err != nil { + return nil, err + } + return response.Data, nil +} + +// GetBetaProgram gets the beta program's detail with the ID +func (c *Client) GetBetaProgram(ctx context.Context, betaID string) (*BetaProgram, error) { + req := c.R(ctx).SetResult(&BetaProgram{}) + betaID = url.PathEscape(betaID) + b := fmt.Sprintf("betas/%s", betaID) + r, err := coupleAPIErrors(req.Get(b)) + if err != nil { + return nil, err + } + + return r.Result().(*BetaProgram), nil +} diff --git a/vendor/github.com/linode/linodego/client.go b/vendor/github.com/linode/linodego/client.go index bb992ea12..a2d676f5e 100644 --- a/vendor/github.com/linode/linodego/client.go +++ b/vendor/github.com/linode/linodego/client.go @@ -3,7 +3,6 @@ package linodego import ( "context" "fmt" - "io/ioutil" "log" "net/http" "net/url" @@ -52,7 +51,7 @@ type Client struct { debug bool retryConditionals []RetryConditional - millisecondsPerPoll time.Duration + pollInterval time.Duration baseURL string apiVersion string @@ -82,7 +81,10 @@ type clientCacheEntry struct { ExpiryOverride *time.Duration } -type Request = resty.Request +type ( + Request = resty.Request + Logger = resty.Logger +) func init() { // Wether or not we will enable Resty debugging output @@ -121,6 +123,14 @@ func (c *Client) SetDebug(debug bool) *Client { return c } +// SetLogger allows the user to override the output +// logger for debug logs. +func (c *Client) SetLogger(logger Logger) *Client { + c.resty.SetLogger(logger) + + return c +} + // OnBeforeRequest adds a handler to the request body to run before the request is sent func (c *Client) OnBeforeRequest(m func(request *Request) error) { c.resty.OnBeforeRequest(func(client *resty.Client, req *resty.Request) error { @@ -166,7 +176,14 @@ func (c *Client) updateHostURL() { apiProto = c.apiProto } - c.resty.SetHostURL(fmt.Sprintf("%s://%s/%s", apiProto, baseURL, apiVersion)) + c.resty.SetBaseURL( + fmt.Sprintf( + "%s://%s/%s", + apiProto, + baseURL, + url.PathEscape(apiVersion), + ), + ) } // SetRootCertificate adds a root certificate to the underlying TLS client config @@ -176,7 +193,7 @@ func (c *Client) SetRootCertificate(path string) *Client { } // SetToken sets the API token for all requests from this client -// Only necessary if you haven't already provided an http client to NewClient() configured with the token. +// Only necessary if you haven't already provided the http client to NewClient() configured with the token. func (c *Client) SetToken(token string) *Client { c.resty.SetHeader("Authorization", fmt.Sprintf("Bearer %s", token)) return c @@ -344,14 +361,21 @@ func (c *Client) SetRetryCount(count int) *Client { // SetPollDelay sets the number of milliseconds to wait between events or status polls. // Affects all WaitFor* functions and retries. func (c *Client) SetPollDelay(delay time.Duration) *Client { - c.millisecondsPerPoll = delay + c.pollInterval = delay return c } // GetPollDelay gets the number of milliseconds to wait between events or status polls. // Affects all WaitFor* functions and retries. func (c *Client) GetPollDelay() time.Duration { - return c.millisecondsPerPoll + return c.pollInterval +} + +// SetHeader sets a custom header to be used in all API requests made with the current +// client. +// NOTE: Some headers may be overridden by the individual request functions. +func (c *Client) SetHeader(name, value string) { + c.resty.SetHeader(name, value) } // NewClient factory to create new Client struct @@ -384,7 +408,7 @@ func NewClient(hc *http.Client) (client Client) { certPath, certPathExists := os.LookupEnv(APIHostCert) if certPathExists { - cert, err := ioutil.ReadFile(filepath.Clean(certPath)) + cert, err := os.ReadFile(filepath.Clean(certPath)) if err != nil { log.Fatalf("[ERROR] Error when reading cert at %s: %s\n", certPath, err.Error()) } @@ -398,7 +422,7 @@ func NewClient(hc *http.Client) (client Client) { client. SetRetryWaitTime((1000 * APISecondsPerPoll) * time.Millisecond). - SetPollDelay(1000 * APISecondsPerPoll). + SetPollDelay(APISecondsPerPoll * time.Second). SetRetries(). SetDebug(envDebug) @@ -514,12 +538,12 @@ func copyTime(tPtr *time.Time) *time.Time { func generateListCacheURL(endpoint string, opts *ListOptions) (string, error) { if opts == nil { - return "", nil + return endpoint, nil } hashedOpts, err := opts.Hash() if err != nil { - return "", err + return endpoint, err } return fmt.Sprintf("%s:%s", endpoint, hashedOpts), nil diff --git a/vendor/github.com/linode/linodego/config.go b/vendor/github.com/linode/linodego/config.go index 0d0b2f507..6bccf83f7 100644 --- a/vendor/github.com/linode/linodego/config.go +++ b/vendor/github.com/linode/linodego/config.go @@ -29,7 +29,7 @@ type LoadConfigOptions struct { SkipLoadProfile bool } -// LoadConfig loads a Linode config according to the options argument. +// LoadConfig loads a Linode config according to the option's argument. // If no options are specified, the following defaults will be used: // Path: ~/.config/linode // Profile: default diff --git a/vendor/github.com/linode/linodego/databases.go b/vendor/github.com/linode/linodego/databases.go index eace5fdc9..50d752d51 100644 --- a/vendor/github.com/linode/linodego/databases.go +++ b/vendor/github.com/linode/linodego/databases.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" "time" "github.com/go-resty/resty/v2" @@ -18,13 +19,13 @@ type ( ) const ( - DatabaseMaintenanceDaySunday DatabaseDayOfWeek = iota + 1 - DatabaseMaintenanceDayMonday + DatabaseMaintenanceDayMonday DatabaseDayOfWeek = iota + 1 DatabaseMaintenanceDayTuesday DatabaseMaintenanceDayWednesday DatabaseMaintenanceDayThursday DatabaseMaintenanceDayFriday DatabaseMaintenanceDaySaturday + DatabaseMaintenanceDaySunday ) const ( @@ -34,7 +35,6 @@ const ( const ( DatabaseEngineTypeMySQL DatabaseEngineType = "mysql" - DatabaseEngineTypeMongo DatabaseEngineType = "mongodb" DatabaseEngineTypePostgres DatabaseEngineType = "postgresql" ) @@ -236,7 +236,8 @@ func (c *Client) ListDatabaseEngines(ctx context.Context, opts *ListOptions) ([] } // GetDatabaseEngine returns a specific Database Engine. This endpoint is cached by default. -func (c *Client) GetDatabaseEngine(ctx context.Context, opts *ListOptions, engineID string) (*DatabaseEngine, error) { +func (c *Client) GetDatabaseEngine(ctx context.Context, _ *ListOptions, engineID string) (*DatabaseEngine, error) { + engineID = url.PathEscape(engineID) e := fmt.Sprintf("databases/engines/%s", engineID) if result := c.getCachedResponse(e); result != nil { @@ -279,7 +280,8 @@ func (c *Client) ListDatabaseTypes(ctx context.Context, opts *ListOptions) ([]Da } // GetDatabaseType returns a specific Database Type. This endpoint is cached by default. -func (c *Client) GetDatabaseType(ctx context.Context, opts *ListOptions, typeID string) (*DatabaseType, error) { +func (c *Client) GetDatabaseType(ctx context.Context, _ *ListOptions, typeID string) (*DatabaseType, error) { + typeID = url.PathEscape(typeID) e := fmt.Sprintf("databases/types/%s", typeID) if result := c.getCachedResponse(e); result != nil { diff --git a/vendor/github.com/linode/linodego/errors.go b/vendor/github.com/linode/linodego/errors.go index d7e7ae291..fc3eb6547 100644 --- a/vendor/github.com/linode/linodego/errors.go +++ b/vendor/github.com/linode/linodego/errors.go @@ -1,21 +1,23 @@ package linodego import ( + "errors" "fmt" - "log" "net/http" + "reflect" "strings" "github.com/go-resty/resty/v2" ) const ( + ErrorUnsupported = iota // ErrorFromString is the Code identifying Errors created by string types - ErrorFromString = 1 + ErrorFromString // ErrorFromError is the Code identifying Errors created by error types - ErrorFromError = 2 + ErrorFromError // ErrorFromStringer is the Code identifying Errors created by fmt.Stringer types - ErrorFromStringer = 3 + ErrorFromStringer ) // Error wraps the LinodeGo error with the relevant http.Response @@ -46,41 +48,45 @@ type APIError struct { func coupleAPIErrors(r *resty.Response, err error) (*resty.Response, error) { if err != nil { + // an error was raised in go code, no need to check the resty Response return nil, NewError(err) } - if r.Error() != nil { - // Check that response is of the correct content-type before unmarshalling - expectedContentType := r.Request.Header.Get("Accept") - responseContentType := r.Header().Get("Content-Type") + if r.Error() == nil { + // no error in the resty Response + return r, nil + } - // If the upstream Linode API server being fronted fails to respond to the request, - // the http server will respond with a default "Bad Gateway" page with Content-Type - // "text/html". - if r.StatusCode() == http.StatusBadGateway && responseContentType == "text/html" { - return nil, Error{Code: http.StatusBadGateway, Message: http.StatusText(http.StatusBadGateway)} - } + // handle the resty Response errors - if responseContentType != expectedContentType { - msg := fmt.Sprintf( - "Unexpected Content-Type: Expected: %v, Received: %v\nResponse body: %s", - expectedContentType, - responseContentType, - string(r.Body()), - ) + // Check that response is of the correct content-type before unmarshalling + expectedContentType := r.Request.Header.Get("Accept") + responseContentType := r.Header().Get("Content-Type") - return nil, Error{Code: r.StatusCode(), Message: msg} - } + // If the upstream Linode API server being fronted fails to respond to the request, + // the http server will respond with a default "Bad Gateway" page with Content-Type + // "text/html". + if r.StatusCode() == http.StatusBadGateway && responseContentType == "text/html" { + return nil, Error{Code: http.StatusBadGateway, Message: http.StatusText(http.StatusBadGateway)} + } - apiError, ok := r.Error().(*APIError) - if !ok || (ok && len(apiError.Errors) == 0) { - return r, nil - } + if responseContentType != expectedContentType { + msg := fmt.Sprintf( + "Unexpected Content-Type: Expected: %v, Received: %v\nResponse body: %s", + expectedContentType, + responseContentType, + string(r.Body()), + ) + + return nil, Error{Code: r.StatusCode(), Message: msg} + } - return nil, NewError(r) + apiError, ok := r.Error().(*APIError) + if !ok || (ok && len(apiError.Errors) == 0) { + return r, nil } - return r, nil + return nil, NewError(r) } func (e APIError) Error() string { @@ -92,8 +98,20 @@ func (e APIError) Error() string { return strings.Join(x, "; ") } -func (g Error) Error() string { - return fmt.Sprintf("[%03d] %s", g.Code, g.Message) +func (err Error) Error() string { + return fmt.Sprintf("[%03d] %s", err.Code, err.Message) +} + +func (err Error) StatusCode() int { + return err.Code +} + +func (err Error) Is(target error) bool { + if x, ok := target.(interface{ StatusCode() int }); ok || errors.As(target, &x) { + return err.StatusCode() == x.StatusCode() + } + + return false } // NewError creates a linodego.Error with a Code identifying the source err type, @@ -113,7 +131,7 @@ func NewError(err any) *Error { apiError, ok := e.Error().(*APIError) if !ok { - log.Fatalln("Unexpected Resty Error Response") + return &Error{Code: ErrorUnsupported, Message: "Unexpected Resty Error Response, no error"} } return &Error{ @@ -128,7 +146,6 @@ func NewError(err any) *Error { case fmt.Stringer: return &Error{Code: ErrorFromStringer, Message: e.String()} default: - log.Fatalln("Unsupported type to linodego.NewError") - panic(err) + return &Error{Code: ErrorUnsupported, Message: fmt.Sprintf("Unsupported type to linodego.NewError: %s", reflect.TypeOf(e))} } } diff --git a/vendor/github.com/linode/linodego/go.work b/vendor/github.com/linode/linodego/go.work index 5f73bd211..db3a7dbc0 100644 --- a/vendor/github.com/linode/linodego/go.work +++ b/vendor/github.com/linode/linodego/go.work @@ -1,7 +1,7 @@ -go 1.19 +go 1.20 use ( - . - ./test - ./k8s -) \ No newline at end of file + . + ./k8s + ./test +) diff --git a/vendor/github.com/linode/linodego/go.work.sum b/vendor/github.com/linode/linodego/go.work.sum index ea20c135a..2a469314f 100644 --- a/vendor/github.com/linode/linodego/go.work.sum +++ b/vendor/github.com/linode/linodego/go.work.sum @@ -1,70 +1,201 @@ +cloud.google.com/go v0.81.0 h1:at8Tk2zUz63cLPR0JPWm5vp77pEZmzxEQBEfRKn1VV8= +cloud.google.com/go/bigquery v1.8.0 h1:PQcPefKFdaIzjQFbiyOgAqyx8q5djaE7x9Sqe712DPA= +cloud.google.com/go/compute/metadata v0.2.0 h1:nBbNSZyDpkNlo3DepaaLKVuO7ClyifSAmNloSCZrHnQ= +cloud.google.com/go/compute/metadata v0.2.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= +cloud.google.com/go/datastore v1.1.0 h1:/May9ojXjRkPBNVrq+oWLqmWCkr4OU5uRY29bu0mRyQ= +cloud.google.com/go/pubsub v1.3.1 h1:ukjixP1wl0LpnZ6LWtZJ0mX5tBmjp1f8Sqer8Z2OMUU= +cloud.google.com/go/storage v1.10.0 h1:STgFzyU5/8miMl0//zKh2aQeTyeaUH3WN9bSUiJ09bA= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9 h1:VpgP7xuJadIUuKccphEpTJnWhS2jkQyMt6Y7pJCD7fY= +github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest v0.11.18 h1:90Y4srNYrwOtAgVo3ndrQkTYn6kf1Eg/AjTFJ8Is2aM= github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/adal v0.9.13 h1:Mp5hbtOePIzM8pJVRa3YLrWWmZtoxRXqUEzCfJt3+/Q= github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.4.1 h1:K0laFcLE6VLTOwNgSxaGbUcLPuGXlNkbVvq4cW4nIHk= github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg= github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802 h1:1BDTz0u9nC3//pOCMdNH+CiXJVYJh5UQNCOBG7jbELc= +github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46 h1:lsxEuwrXEAokXB9qhlbKWPpo3KMLZQ5WB5WLQRW1uq0= +github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA= +github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= +github.com/census-instrumentation/opencensus-proto v0.2.1 h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk= +github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8= +github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403 h1:cqQfy1jclcSy/FwLjemeg3SR1yaINm74aQyupQ0Bl8M= +github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= +github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 h1:bWDMxwH3px2JBh6AyO7hdCn/PkvCZXii8TGj7sbtEbQ= +github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= +github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633 h1:H2pdYOb3KQ1/YsqVWoWNLQO+fusocsw354rqGTZtAgw= +github.com/emicklei/go-restful/v3 v3.8.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad h1:EmNYJhPYy0pOFjCx2PrgtaBXmee0iUX9hLlxE1xHOJE= +github.com/envoyproxy/protoc-gen-validate v0.1.0 h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A= github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch v4.12.0+incompatible h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84= +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/form3tech-oss/jwt-go v3.2.3+incompatible h1:7ZaBxOI7TMoYBfyA3cQHErNNyAWIKUMIwqxEtgHOs5c= +github.com/getkin/kin-openapi v0.76.0 h1:j77zg3Ec+k+r+GA3d8hBoXpAc6KX9TbBPrwQGBIy2sY= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1 h1:QbL/5oDUmRBzO9/Z7Seo6zf912W/a6Sr4Eu0G/3Jho0= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4 h1:WtGNWLvXpe6ZudgnXrq0barxBImvnnJoMEhXAzcbM0I= +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= github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= +github.com/go-openapi/jsonreference v0.19.3 h1:5cxNfTy0UVC3X8JL5ymxzyoUZmo8iZb+jeTWn7tUa8o= github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= +github.com/go-openapi/swag v0.19.5 h1:lTz6Ys4CmqqCQmZPBlbQENR1/GucA2bzYTE12Pw4tFY= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.5.0 h1:jlYHihg//f7RRwuPfptm04yp4s7O6Kw8EZiVYIGcH0g= github.com/golang/protobuf v0.0.0-20161109072736-4bd1920723d7/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= +github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= +github.com/google/martian/v3 v3.1.0 h1:wCKgOCHuUEVfsaQLpPSJb7VdYCdTVZQAuOdYm1yc/60= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5 h1:zIaiqGYDQwa4HVx5wGRTXbx38Pqxjemn4BP98wpzpXo= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= github.com/googleapis/gnostic v0.1.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= github.com/gophercloud/gophercloud v0.1.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639 h1:mV02weKRL81bEnm8A0HT1/CAelMQDBuQIfLw8n+d6xI= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/errcheck v1.5.0 h1:e8esj/e4R+SAOwFwN+n3zr0nYeCyeweozKfO23MvHzY= +github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= +github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw= github.com/linode/linodego v0.20.1 h1:Kw5Qes0E0wlKVx5EbITI+F/ambO6G+PQyK0Yi7i4EyQ= github.com/linode/linodego v0.20.1/go.mod h1:XOWXRHjqeU2uPS84tKLgfWIfTlv3TYzCS0io4GOQzEI= github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e h1:hB2xlXdHp/pmPZq0y3QnmWAArdw9PqbmotexnWx/FU8= +github.com/maxatome/go-testdeep v1.11.0/go.mod h1:011SgQ6efzZYAen6fDn4BqQ+lUR72ysdyKe7Dyogw70= +github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= +github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= +github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5 h1:8Q0qkMVC/MmWkpIdlvZgcv2o2jrlF6zqVOh7W5YHdMA= +github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d h1:7PxY7LVfSZm7PEeBTyK1rj1gABdCO2mbri6GKO1cMDs= +github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= +github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU= +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/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= +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/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= +github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM= +github.com/rogpeppe/go-internal v1.3.0 h1:RR9dF3JtopPvtkroDZuVD7qquD0bnHlKSqaQhgwt8yk= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU= +github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= +github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/yuin/goldmark v1.2.1 h1:ruQGxdhGHe7FWOJPT0mKs5+pD2Xs1Bm/kdGlHO04FmM= +github.com/yuin/goldmark v1.3.5 h1:dPmz1Snjq0kmkz159iL7S6WzdahUTHnHB5M56WFVifs= +github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= +go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= +golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= +golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g= +golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b h1:+qEpEAPhDZ1o0x3tHzZTQDArnOixOzGD9HUJfcg0mb4= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028 h1:4+4C/Iv2U4fMZBiMCc98MG1In4gJY5YRhtpDNeDeHWs= +golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= +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/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20220722155237-a158d28d115b h1:PxfKdU9lEEDYjdIzOtC4qFWgkU2rGHdKlKowJSMN9h0= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.13.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 h1:SQFwaSi55rU7vdNs9Yr0Z324VNlrF+0wMqRXT4St8ck= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -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.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= -golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -k8s.io/api v0.18.3/go.mod h1:UOaMwERbqJMfeeeHc8XJKawj4P9TgDRnViIqqBeH2QA= -k8s.io/apimachinery v0.18.3/go.mod h1:OaXp26zu/5J7p0f92ASynJa1pZo06YlV9fG7BoWbCko= -k8s.io/client-go v0.18.3/go.mod h1:4a/dpQEvzAhT1BbuWW09qvIaGw6Gbu1gZYiQZIi1DMw= -k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= -k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= -k8s.io/klog v0.3.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= -k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= -k8s.io/kube-openapi v0.0.0-20200410145947-61e04a5be9a6/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= -k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= -sigs.k8s.io/structured-merge-diff/v3 v3.0.0-20200116222232-67a7b8c61874/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= -sigs.k8s.io/structured-merge-diff/v3 v3.0.0/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= -sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= +golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +k8s.io/gengo v0.0.0-20210813121822-485abfe95c7c h1:GohjlNKauSai7gN4wsJkeZ3WAJx4Sh+oT/b5IYn5suA= +k8s.io/gengo v0.0.0-20210813121822-485abfe95c7c/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= diff --git a/vendor/github.com/linode/linodego/images.go b/vendor/github.com/linode/linodego/images.go index 46efc59db..7875d6fdc 100644 --- a/vendor/github.com/linode/linodego/images.go +++ b/vendor/github.com/linode/linodego/images.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io" + "net/url" "time" "github.com/go-resty/resty/v2" @@ -23,18 +24,19 @@ const ( // Image represents a deployable Image object for use with Linode Instances type Image struct { - ID string `json:"id"` - CreatedBy string `json:"created_by"` - Label string `json:"label"` - Description string `json:"description"` - Type string `json:"type"` - Vendor string `json:"vendor"` - Status ImageStatus `json:"status"` - Size int `json:"size"` - IsPublic bool `json:"is_public"` - Deprecated bool `json:"deprecated"` - Created *time.Time `json:"-"` - Expiry *time.Time `json:"-"` + ID string `json:"id"` + CreatedBy string `json:"created_by"` + Capabilities []string `json:"capabilities"` + Label string `json:"label"` + Description string `json:"description"` + Type string `json:"type"` + Vendor string `json:"vendor"` + Status ImageStatus `json:"status"` + Size int `json:"size"` + IsPublic bool `json:"is_public"` + Deprecated bool `json:"deprecated"` + Created *time.Time `json:"-"` + Expiry *time.Time `json:"-"` } // ImageCreateOptions fields are those accepted by CreateImage @@ -42,6 +44,7 @@ type ImageCreateOptions struct { DiskID int `json:"disk_id"` Label string `json:"label"` Description string `json:"description,omitempty"` + CloudInit bool `json:"cloud_init,omitempty"` } // ImageUpdateOptions fields are those accepted by UpdateImage @@ -61,6 +64,7 @@ type ImageCreateUploadOptions struct { Region string `json:"region"` Label string `json:"label"` Description string `json:"description,omitempty"` + CloudInit bool `json:"cloud_init,omitempty"` } // ImageUploadOptions fields are those accepted by UploadImage @@ -68,6 +72,7 @@ type ImageUploadOptions struct { Region string `json:"region"` Label string `json:"label"` Description string `json:"description,omitempty"` + CloudInit bool `json:"cloud_init"` Image io.Reader } @@ -132,6 +137,8 @@ func (c *Client) ListImages(ctx context.Context, opts *ListOptions) ([]Image, er // GetImage gets the Image with the provided ID func (c *Client) GetImage(ctx context.Context, imageID string) (*Image, error) { + imageID = url.PathEscape(imageID) + e := fmt.Sprintf("images/%s", imageID) req := c.R(ctx).SetResult(&Image{}) r, err := coupleAPIErrors(req.Get(e)) @@ -141,7 +148,7 @@ func (c *Client) GetImage(ctx context.Context, imageID string) (*Image, error) { return r.Result().(*Image), nil } -// CreateImage creates a Image +// CreateImage creates an Image func (c *Client) CreateImage(ctx context.Context, opts ImageCreateOptions) (*Image, error) { body, err := json.Marshal(opts) if err != nil { @@ -164,6 +171,8 @@ func (c *Client) UpdateImage(ctx context.Context, imageID string, opts ImageUpda return nil, err } + imageID = url.PathEscape(imageID) + e := fmt.Sprintf("images/%s", imageID) req := c.R(ctx).SetResult(&Image{}).SetBody(string(body)) r, err := coupleAPIErrors(req.Put(e)) @@ -175,6 +184,7 @@ func (c *Client) UpdateImage(ctx context.Context, imageID string, opts ImageUpda // DeleteImage deletes the Image with the specified id func (c *Client) DeleteImage(ctx context.Context, imageID string) error { + imageID = url.PathEscape(imageID) e := fmt.Sprintf("images/%s", imageID) _, err := coupleAPIErrors(c.R(ctx).Delete(e)) return err @@ -223,6 +233,7 @@ func (c *Client) UploadImage(ctx context.Context, opts ImageUploadOptions) (*Ima Label: opts.Label, Region: opts.Region, Description: opts.Description, + CloudInit: opts.CloudInit, }) if err != nil { return nil, err diff --git a/vendor/github.com/linode/linodego/instance_config_interfaces.go b/vendor/github.com/linode/linodego/instance_config_interfaces.go new file mode 100644 index 000000000..d975ddcbc --- /dev/null +++ b/vendor/github.com/linode/linodego/instance_config_interfaces.go @@ -0,0 +1,228 @@ +package linodego + +import ( + "context" + "encoding/json" + "fmt" +) + +// InstanceConfigInterface contains information about a configuration's network interface +type InstanceConfigInterface struct { + ID int `json:"id"` + IPAMAddress string `json:"ipam_address"` + Label string `json:"label"` + Purpose ConfigInterfacePurpose `json:"purpose"` + Primary bool `json:"primary"` + Active bool `json:"active"` + VPCID *int `json:"vpc_id"` + SubnetID *int `json:"subnet_id"` + IPv4 VPCIPv4 `json:"ipv4"` + IPRanges []string `json:"ip_ranges"` +} + +type VPCIPv4 struct { + VPC string `json:"vpc,omitempty"` + NAT1To1 string `json:"nat_1_1,omitempty"` +} + +type InstanceConfigInterfaceCreateOptions struct { + IPAMAddress string `json:"ipam_address,omitempty"` + Label string `json:"label,omitempty"` + Purpose ConfigInterfacePurpose `json:"purpose,omitempty"` + Primary bool `json:"primary,omitempty"` + SubnetID *int `json:"subnet_id,omitempty"` + IPv4 *VPCIPv4 `json:"ipv4,omitempty"` + IPRanges []string `json:"ip_ranges,omitempty"` +} + +type InstanceConfigInterfaceUpdateOptions struct { + Primary bool `json:"primary,omitempty"` + IPv4 *VPCIPv4 `json:"ipv4,omitempty"` + IPRanges []string `json:"ip_ranges,omitempty"` +} + +type InstanceConfigInterfacesReorderOptions struct { + IDs []int `json:"ids"` +} + +func getInstanceConfigInterfacesCreateOptionsList( + interfaces []InstanceConfigInterface, +) []InstanceConfigInterfaceCreateOptions { + interfaceOptsList := make([]InstanceConfigInterfaceCreateOptions, len(interfaces)) + for index, configInterface := range interfaces { + interfaceOptsList[index] = configInterface.GetCreateOptions() + } + return interfaceOptsList +} + +func (i InstanceConfigInterface) GetCreateOptions() InstanceConfigInterfaceCreateOptions { + opts := InstanceConfigInterfaceCreateOptions{ + Label: i.Label, + Purpose: i.Purpose, + Primary: i.Primary, + SubnetID: i.SubnetID, + } + + if len(i.IPRanges) > 0 { + opts.IPRanges = i.IPRanges + } + + if i.Purpose == InterfacePurposeVPC && + i.IPv4.NAT1To1 != "" && i.IPv4.VPC != "" { + opts.IPv4 = &VPCIPv4{ + VPC: i.IPv4.VPC, + NAT1To1: i.IPv4.NAT1To1, + } + } + + // workaround for API issue + if i.IPAMAddress == "222" { + opts.IPAMAddress = "" + } else { + opts.IPAMAddress = i.IPAMAddress + } + + return opts +} + +func (i InstanceConfigInterface) GetUpdateOptions() InstanceConfigInterfaceUpdateOptions { + opts := InstanceConfigInterfaceUpdateOptions{ + Primary: i.Primary, + } + + if i.Purpose == InterfacePurposeVPC { + opts.IPv4 = &VPCIPv4{ + VPC: i.IPv4.VPC, + NAT1To1: i.IPv4.NAT1To1, + } + } + + if len(i.IPRanges) > 0 { + opts.IPRanges = i.IPRanges + } + + return opts +} + +func (c *Client) AppendInstanceConfigInterface( + ctx context.Context, + linodeID int, + configID int, + opts InstanceConfigInterfaceCreateOptions, +) (*InstanceConfigInterface, error) { + body, err := json.Marshal(opts) + if err != nil { + return nil, err + } + + req := c.R(ctx).SetResult(&InstanceConfigInterface{}).SetBody(string(body)) + e := fmt.Sprintf("/linode/instances/%d/configs/%d/interfaces", linodeID, configID) + r, err := coupleAPIErrors(req.Post(e)) + if err != nil { + return nil, err + } + + return r.Result().(*InstanceConfigInterface), nil +} + +func (c *Client) GetInstanceConfigInterface( + ctx context.Context, + linodeID int, + configID int, + interfaceID int, +) (*InstanceConfigInterface, error) { + e := fmt.Sprintf( + "linode/instances/%d/configs/%d/interfaces/%d", + linodeID, + configID, + interfaceID, + ) + req := c.R(ctx).SetResult(&InstanceConfigInterface{}) + r, err := coupleAPIErrors(req.Get(e)) + if err != nil { + return nil, err + } + return r.Result().(*InstanceConfigInterface), nil +} + +func (c *Client) ListInstanceConfigInterfaces( + ctx context.Context, + linodeID int, + configID int, +) ([]InstanceConfigInterface, error) { + e := fmt.Sprintf( + "linode/instances/%d/configs/%d/interfaces", + linodeID, + configID, + ) + req := c.R(ctx).SetResult([]InstanceConfigInterface{}) + r, err := coupleAPIErrors(req.Get(e)) + if err != nil { + return nil, err + } + return *r.Result().(*[]InstanceConfigInterface), nil +} + +func (c *Client) UpdateInstanceConfigInterface( + ctx context.Context, + linodeID int, + configID int, + interfaceID int, + opts InstanceConfigInterfaceUpdateOptions, +) (*InstanceConfigInterface, error) { + body, err := json.Marshal(opts) + if err != nil { + return nil, err + } + + e := fmt.Sprintf( + "linode/instances/%d/configs/%d/interfaces/%d", + linodeID, + configID, + interfaceID, + ) + req := c.R(ctx).SetResult(&InstanceConfigInterface{}).SetBody(string(body)) + r, err := coupleAPIErrors(req.Put(e)) + if err != nil { + return nil, err + } + return r.Result().(*InstanceConfigInterface), nil +} + +func (c *Client) DeleteInstanceConfigInterface( + ctx context.Context, + linodeID int, + configID int, + interfaceID int, +) error { + e := fmt.Sprintf( + "linode/instances/%d/configs/%d/interfaces/%d", + linodeID, + configID, + interfaceID, + ) + _, err := coupleAPIErrors(c.R(ctx).Delete(e)) + return err +} + +func (c *Client) ReorderInstanceConfigInterfaces( + ctx context.Context, + linodeID int, + configID int, + opts InstanceConfigInterfacesReorderOptions, +) error { + body, err := json.Marshal(opts) + if err != nil { + return err + } + e := fmt.Sprintf( + "linode/instances/%d/configs/%d/interfaces/order", + linodeID, + configID, + ) + + req := c.R(ctx).SetBody(string(body)) + _, err = coupleAPIErrors(req.Post(e)) + + return err +} diff --git a/vendor/github.com/linode/linodego/instance_configs.go b/vendor/github.com/linode/linodego/instance_configs.go index 0a13acee2..0e155f71d 100644 --- a/vendor/github.com/linode/linodego/instance_configs.go +++ b/vendor/github.com/linode/linodego/instance_configs.go @@ -61,15 +61,9 @@ type ConfigInterfacePurpose string const ( InterfacePurposePublic ConfigInterfacePurpose = "public" InterfacePurposeVLAN ConfigInterfacePurpose = "vlan" + InterfacePurposeVPC ConfigInterfacePurpose = "vpc" ) -// InstanceConfigInterface contains information about a configuration's network interface -type InstanceConfigInterface struct { - IPAMAddress string `json:"ipam_address"` - Label string `json:"label"` - Purpose ConfigInterfacePurpose `json:"purpose"` -} - // InstanceConfigsPagedResponse represents a paginated InstanceConfig API response type InstanceConfigsPagedResponse struct { *PageOptions @@ -78,26 +72,26 @@ type InstanceConfigsPagedResponse struct { // InstanceConfigCreateOptions are InstanceConfig settings that can be used at creation type InstanceConfigCreateOptions struct { - Label string `json:"label,omitempty"` - Comments string `json:"comments,omitempty"` - Devices InstanceConfigDeviceMap `json:"devices"` - Helpers *InstanceConfigHelpers `json:"helpers,omitempty"` - Interfaces []InstanceConfigInterface `json:"interfaces"` - MemoryLimit int `json:"memory_limit,omitempty"` - Kernel string `json:"kernel,omitempty"` - InitRD int `json:"init_rd,omitempty"` - RootDevice *string `json:"root_device,omitempty"` - RunLevel string `json:"run_level,omitempty"` - VirtMode string `json:"virt_mode,omitempty"` + Label string `json:"label,omitempty"` + Comments string `json:"comments,omitempty"` + Devices InstanceConfigDeviceMap `json:"devices"` + Helpers *InstanceConfigHelpers `json:"helpers,omitempty"` + Interfaces []InstanceConfigInterfaceCreateOptions `json:"interfaces"` + MemoryLimit int `json:"memory_limit,omitempty"` + Kernel string `json:"kernel,omitempty"` + InitRD int `json:"init_rd,omitempty"` + RootDevice *string `json:"root_device,omitempty"` + RunLevel string `json:"run_level,omitempty"` + VirtMode string `json:"virt_mode,omitempty"` } // InstanceConfigUpdateOptions are InstanceConfig settings that can be used in updates type InstanceConfigUpdateOptions struct { - Label string `json:"label,omitempty"` - Comments string `json:"comments"` - Devices *InstanceConfigDeviceMap `json:"devices,omitempty"` - Helpers *InstanceConfigHelpers `json:"helpers,omitempty"` - Interfaces []InstanceConfigInterface `json:"interfaces"` + Label string `json:"label,omitempty"` + Comments string `json:"comments"` + Devices *InstanceConfigDeviceMap `json:"devices,omitempty"` + Helpers *InstanceConfigHelpers `json:"helpers,omitempty"` + Interfaces []InstanceConfigInterfaceCreateOptions `json:"interfaces"` // MemoryLimit 0 means unlimitted, this is not omitted MemoryLimit int `json:"memory_limit"` Kernel string `json:"kernel,omitempty"` @@ -141,7 +135,7 @@ func (i InstanceConfig) GetCreateOptions() InstanceConfigCreateOptions { Comments: i.Comments, Devices: *i.Devices, Helpers: i.Helpers, - Interfaces: i.Interfaces, + Interfaces: getInstanceConfigInterfacesCreateOptionsList(i.Interfaces), MemoryLimit: i.MemoryLimit, Kernel: i.Kernel, InitRD: initrd, @@ -158,7 +152,7 @@ func (i InstanceConfig) GetUpdateOptions() InstanceConfigUpdateOptions { Comments: i.Comments, Devices: i.Devices, Helpers: i.Helpers, - Interfaces: i.Interfaces, + Interfaces: getInstanceConfigInterfacesCreateOptionsList(i.Interfaces), MemoryLimit: i.MemoryLimit, Kernel: i.Kernel, InitRD: copyInt(i.InitRD), diff --git a/vendor/github.com/linode/linodego/instance_firewalls.go b/vendor/github.com/linode/linodego/instance_firewalls.go new file mode 100644 index 000000000..ffca799e1 --- /dev/null +++ b/vendor/github.com/linode/linodego/instance_firewalls.go @@ -0,0 +1,41 @@ +package linodego + +import ( + "context" + "fmt" + + "github.com/go-resty/resty/v2" +) + +// InstanceFirewallsPagedResponse represents a Linode API response for listing of Cloud Firewalls +type InstanceFirewallsPagedResponse struct { + *PageOptions + Data []Firewall `json:"data"` +} + +func (InstanceFirewallsPagedResponse) endpoint(ids ...any) string { + id := ids[0].(int) + return fmt.Sprintf("linode/instances/%d/firewalls", id) +} + +func (resp *InstanceFirewallsPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(InstanceFirewallsPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*InstanceFirewallsPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +// ListInstanceFirewalls returns a paginated list of Cloud Firewalls for linodeID +func (c *Client) ListInstanceFirewalls(ctx context.Context, linodeID int, opts *ListOptions) ([]Firewall, error) { + response := InstanceFirewallsPagedResponse{} + + err := c.listHelper(ctx, &response, opts, linodeID) + if err != nil { + return nil, err + } + + return response.Data, nil +} diff --git a/vendor/github.com/linode/linodego/instance_ips.go b/vendor/github.com/linode/linodego/instance_ips.go index 3e03310d5..beaeb0a21 100644 --- a/vendor/github.com/linode/linodego/instance_ips.go +++ b/vendor/github.com/linode/linodego/instance_ips.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" ) // InstanceIPAddressResponse contains the IPv4 and IPv6 details for an Instance @@ -22,15 +23,16 @@ type InstanceIPv4Response struct { // InstanceIP represents an Instance IP with additional DNS and networking details type InstanceIP struct { - Address string `json:"address"` - Gateway string `json:"gateway"` - SubnetMask string `json:"subnet_mask"` - Prefix int `json:"prefix"` - Type InstanceIPType `json:"type"` - Public bool `json:"public"` - RDNS string `json:"rdns"` - LinodeID int `json:"linode_id"` - Region string `json:"region"` + Address string `json:"address"` + Gateway string `json:"gateway"` + SubnetMask string `json:"subnet_mask"` + Prefix int `json:"prefix"` + Type InstanceIPType `json:"type"` + Public bool `json:"public"` + RDNS string `json:"rdns"` + LinodeID int `json:"linode_id"` + Region string `json:"region"` + VPCNAT1To1 *InstanceIPNAT1To1 `json:"vpc_nat_1_1"` } // InstanceIPv6Response contains the IPv6 addresses and ranges for an Instance @@ -40,6 +42,14 @@ type InstanceIPv6Response struct { Global []IPv6Range `json:"global"` } +// InstanceIPNAT1To1 contains information about the NAT 1:1 mapping +// of a public IP address to a VPC subnet. +type InstanceIPNAT1To1 struct { + Address string `json:"address"` + SubnetID int `json:"subnet_id"` + VPCID int `json:"vpc_id"` +} + // IPv6Range represents a range of IPv6 addresses routed to a single Linode in a given Region type IPv6Range struct { Range string `json:"range"` @@ -77,6 +87,7 @@ func (c *Client) GetInstanceIPAddresses(ctx context.Context, linodeID int) (*Ins // GetInstanceIPAddress gets the IPAddress for a Linode instance matching a supplied IP address func (c *Client) GetInstanceIPAddress(ctx context.Context, linodeID int, ipaddress string) (*InstanceIP, error) { + ipaddress = url.PathEscape(ipaddress) e := fmt.Sprintf("linode/instances/%d/ips/%s", linodeID, ipaddress) req := c.R(ctx).SetResult(&InstanceIP{}) r, err := coupleAPIErrors(req.Get(e)) @@ -116,6 +127,8 @@ func (c *Client) UpdateInstanceIPAddress(ctx context.Context, linodeID int, ipAd return nil, err } + ipAddress = url.PathEscape(ipAddress) + e := fmt.Sprintf("linode/instances/%d/ips/%s", linodeID, ipAddress) req := c.R(ctx).SetResult(&InstanceIP{}).SetBody(string(body)) r, err := coupleAPIErrors(req.Put(e)) @@ -126,6 +139,7 @@ func (c *Client) UpdateInstanceIPAddress(ctx context.Context, linodeID int, ipAd } func (c *Client) DeleteInstanceIPAddress(ctx context.Context, linodeID int, ipAddress string) error { + ipAddress = url.PathEscape(ipAddress) e := fmt.Sprintf("linode/instances/%d/ips/%s", linodeID, ipAddress) _, err := coupleAPIErrors(c.R(ctx).Delete(e)) return err diff --git a/vendor/github.com/linode/linodego/instances.go b/vendor/github.com/linode/linodego/instances.go index 7d6c7566e..f56597305 100644 --- a/vendor/github.com/linode/linodego/instances.go +++ b/vendor/github.com/linode/linodego/instances.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "net" + "net/url" "time" "github.com/go-resty/resty/v2" @@ -34,6 +35,13 @@ const ( InstanceResizing InstanceStatus = "resizing" ) +type InstanceMigrationType string + +const ( + WarmMigration InstanceMigrationType = "warm" + ColdMigration InstanceMigrationType = "cold" +) + // Instance represents a linode object type Instance struct { ID int `json:"id"` @@ -49,6 +57,7 @@ type Instance struct { Label string `json:"label"` Type string `json:"type"` Status InstanceStatus `json:"status"` + HasUserData bool `json:"has_user_data"` Hypervisor string `json:"hypervisor"` HostUUID string `json:"host_uuid"` Specs *InstanceSpec `json:"specs"` @@ -62,6 +71,7 @@ type InstanceSpec struct { Memory int `json:"memory"` VCPUs int `json:"vcpus"` Transfer int `json:"transfer"` + GPUs int `json:"gpus"` } // InstanceAlert represents a metric alert @@ -95,23 +105,32 @@ type InstanceTransfer struct { Quota int `json:"quota"` } +// InstanceMetadataOptions specifies various Instance creation fields +// that relate to the Linode Metadata service. +type InstanceMetadataOptions struct { + // UserData expects a Base64-encoded string + UserData string `json:"user_data,omitempty"` +} + // InstanceCreateOptions require only Region and Type type InstanceCreateOptions struct { - Region string `json:"region"` - Type string `json:"type"` - Label string `json:"label,omitempty"` - Group string `json:"group,omitempty"` - RootPass string `json:"root_pass,omitempty"` - AuthorizedKeys []string `json:"authorized_keys,omitempty"` - AuthorizedUsers []string `json:"authorized_users,omitempty"` - StackScriptID int `json:"stackscript_id,omitempty"` - StackScriptData map[string]string `json:"stackscript_data,omitempty"` - BackupID int `json:"backup_id,omitempty"` - Image string `json:"image,omitempty"` - Interfaces []InstanceConfigInterface `json:"interfaces,omitempty"` - BackupsEnabled bool `json:"backups_enabled,omitempty"` - PrivateIP bool `json:"private_ip,omitempty"` - Tags []string `json:"tags,omitempty"` + Region string `json:"region"` + Type string `json:"type"` + Label string `json:"label,omitempty"` + Group string `json:"group,omitempty"` + RootPass string `json:"root_pass,omitempty"` + AuthorizedKeys []string `json:"authorized_keys,omitempty"` + AuthorizedUsers []string `json:"authorized_users,omitempty"` + StackScriptID int `json:"stackscript_id,omitempty"` + StackScriptData map[string]string `json:"stackscript_data,omitempty"` + BackupID int `json:"backup_id,omitempty"` + Image string `json:"image,omitempty"` + Interfaces []InstanceConfigInterfaceCreateOptions `json:"interfaces,omitempty"` + BackupsEnabled bool `json:"backups_enabled,omitempty"` + PrivateIP bool `json:"private_ip,omitempty"` + Tags []string `json:"tags,omitempty"` + Metadata *InstanceMetadataOptions `json:"metadata,omitempty"` + FirewallID int `json:"firewall_id,omitempty"` // Creation fields that need to be set explicitly false, "", or 0 use pointers SwapSize *int `json:"swap_size,omitempty"` @@ -168,23 +187,31 @@ type InstanceCloneOptions struct { Type string `json:"type,omitempty"` // LinodeID is an optional existing instance to use as the target of the clone - LinodeID int `json:"linode_id,omitempty"` - Label string `json:"label,omitempty"` - Group string `json:"group,omitempty"` - BackupsEnabled bool `json:"backups_enabled"` - Disks []int `json:"disks,omitempty"` - Configs []int `json:"configs,omitempty"` - PrivateIP bool `json:"private_ip,omitempty"` + LinodeID int `json:"linode_id,omitempty"` + Label string `json:"label,omitempty"` + Group string `json:"group,omitempty"` + BackupsEnabled bool `json:"backups_enabled"` + Disks []int `json:"disks,omitempty"` + Configs []int `json:"configs,omitempty"` + PrivateIP bool `json:"private_ip,omitempty"` + Metadata *InstanceMetadataOptions `json:"metadata,omitempty"` } // InstanceResizeOptions is an options struct used when resizing an instance type InstanceResizeOptions struct { - Type string `json:"type"` + Type string `json:"type"` + MigrationType InstanceMigrationType `json:"migration_type,omitempty"` // When enabled, an instance resize will also resize a data disk if the instance has no more than one data disk and one swap disk AllowAutoDiskResize *bool `json:"allow_auto_disk_resize,omitempty"` } +// InstanceResizeOptions is an options struct used when resizing an instance +type InstanceMigrateOptions struct { + Type InstanceMigrationType `json:"type,omitempty"` + Region string `json:"region,omitempty"` +} + // InstancesPagedResponse represents a linode API response for listing type InstancesPagedResponse struct { *PageOptions @@ -336,13 +363,15 @@ func (c *Client) RebootInstance(ctx context.Context, linodeID int, configID int) // InstanceRebuildOptions is a struct representing the options to send to the rebuild linode endpoint type InstanceRebuildOptions struct { - Image string `json:"image,omitempty"` - RootPass string `json:"root_pass,omitempty"` - AuthorizedKeys []string `json:"authorized_keys,omitempty"` - AuthorizedUsers []string `json:"authorized_users,omitempty"` - StackScriptID int `json:"stackscript_id,omitempty"` - StackScriptData map[string]string `json:"stackscript_data,omitempty"` - Booted *bool `json:"booted,omitempty"` + Image string `json:"image,omitempty"` + RootPass string `json:"root_pass,omitempty"` + AuthorizedKeys []string `json:"authorized_keys,omitempty"` + AuthorizedUsers []string `json:"authorized_users,omitempty"` + StackScriptID int `json:"stackscript_id,omitempty"` + StackScriptData map[string]string `json:"stackscript_data,omitempty"` + Booted *bool `json:"booted,omitempty"` + Metadata *InstanceMetadataOptions `json:"metadata,omitempty"` + Type string `json:"type,omitempty"` } // RebuildInstance Deletes all Disks and Configs on this Linode, @@ -402,13 +431,20 @@ func (c *Client) MutateInstance(ctx context.Context, id int) error { } // MigrateInstance - Migrate an instance -func (c *Client) MigrateInstance(ctx context.Context, id int) error { - return c.simpleInstanceAction(ctx, "migrate", id) +func (c *Client) MigrateInstance(ctx context.Context, linodeID int, opts InstanceMigrateOptions) error { + body, err := json.Marshal(opts) + if err != nil { + return err + } + e := fmt.Sprintf("linode/instances/%d/migrate", linodeID) + _, err = coupleAPIErrors(c.R(ctx).SetBody(string(body)).Post(e)) + return err } // simpleInstanceAction is a helper for Instance actions that take no parameters // and return empty responses `{}` unless they return a standard error func (c *Client) simpleInstanceAction(ctx context.Context, action string, linodeID int) error { + action = url.PathEscape(action) e := fmt.Sprintf("linode/instances/%d/%s", linodeID, action) _, err := coupleAPIErrors(c.R(ctx).Post(e)) return err diff --git a/vendor/github.com/linode/linodego/internal/duration/duration.go b/vendor/github.com/linode/linodego/internal/duration/duration.go index 088f12f02..14d4f1365 100644 --- a/vendor/github.com/linode/linodego/internal/duration/duration.go +++ b/vendor/github.com/linode/linodego/internal/duration/duration.go @@ -20,16 +20,17 @@ func UnmarshalTimeRemaining(m json.RawMessage) *int { var timeStr string if err := json.Unmarshal(jsonBytes, &timeStr); err == nil && len(timeStr) > 0 { - if dur, err := durationToSeconds(timeStr); err != nil { + dur, err := durationToSeconds(timeStr) + if err != nil { panic(err) - } else { - return &dur - } - } else { - var intPtr int - if err := json.Unmarshal(jsonBytes, &intPtr); err == nil { - return &intPtr } + + return &dur + } + + var intPtr int + if err := json.Unmarshal(jsonBytes, &intPtr); err == nil { + return &intPtr } log.Println("[WARN] Unexpected unmarshalTimeRemaining value: ", jsonBytes) diff --git a/vendor/github.com/linode/linodego/kernels.go b/vendor/github.com/linode/linodego/kernels.go index 06c2fc600..26987a639 100644 --- a/vendor/github.com/linode/linodego/kernels.go +++ b/vendor/github.com/linode/linodego/kernels.go @@ -2,21 +2,26 @@ package linodego import ( "context" + "encoding/json" "fmt" + "net/url" + "time" "github.com/go-resty/resty/v2" + "github.com/linode/linodego/internal/parseabletime" ) // LinodeKernel represents a Linode Instance kernel object type LinodeKernel struct { - ID string `json:"id"` - Label string `json:"label"` - Version string `json:"version"` - Architecture string `json:"architecture"` - Deprecated bool `json:"deprecated"` - KVM bool `json:"kvm"` - XEN bool `json:"xen"` - PVOPS bool `json:"pvops"` + ID string `json:"id"` + Label string `json:"label"` + Version string `json:"version"` + Architecture string `json:"architecture"` + Deprecated bool `json:"deprecated"` + KVM bool `json:"kvm"` + XEN bool `json:"xen"` + PVOPS bool `json:"pvops"` + Built *time.Time `json:"-"` } // LinodeKernelsPagedResponse represents a Linode kernels API response for listing @@ -25,6 +30,26 @@ type LinodeKernelsPagedResponse struct { Data []LinodeKernel `json:"data"` } +// UnmarshalJSON implements the json.Unmarshaler interface +func (i *LinodeKernel) UnmarshalJSON(b []byte) error { + type Mask LinodeKernel + + p := struct { + *Mask + Built *parseabletime.ParseableTime `json:"built"` + }{ + Mask: (*Mask)(i), + } + + if err := json.Unmarshal(b, &p); err != nil { + return err + } + + i.Built = (*time.Time)(p.Built) + + return nil +} + func (LinodeKernelsPagedResponse) endpoint(_ ...any) string { return "linode/kernels" } @@ -64,6 +89,7 @@ func (c *Client) ListKernels(ctx context.Context, opts *ListOptions) ([]LinodeKe // GetKernel gets the kernel with the provided ID. This endpoint is cached by default. func (c *Client) GetKernel(ctx context.Context, kernelID string) (*LinodeKernel, error) { + kernelID = url.PathEscape(kernelID) e := fmt.Sprintf("linode/kernels/%s", kernelID) if result := c.getCachedResponse(e); result != nil { diff --git a/vendor/github.com/linode/linodego/lke_clusters.go b/vendor/github.com/linode/linodego/lke_clusters.go index f764c7c15..ff9b67659 100644 --- a/vendor/github.com/linode/linodego/lke_clusters.go +++ b/vendor/github.com/linode/linodego/lke_clusters.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" "time" "github.com/go-resty/resty/v2" @@ -169,6 +170,7 @@ func (c *Client) ListLKEVersions(ctx context.Context, opts *ListOptions) ([]LKEV // GetLKEVersion gets details about a specific LKE Version. This endpoint is cached by default. func (c *Client) GetLKEVersion(ctx context.Context, version string) (*LKEVersion, error) { + version = url.PathEscape(version) e := fmt.Sprintf("lke/versions/%s", version) if result := c.getCachedResponse(e); result != nil { diff --git a/vendor/github.com/linode/linodego/lke_node_pools.go b/vendor/github.com/linode/linodego/lke_node_pools.go index 42097f13d..b7e5bc0bb 100644 --- a/vendor/github.com/linode/linodego/lke_node_pools.go +++ b/vendor/github.com/linode/linodego/lke_node_pools.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) @@ -170,6 +171,7 @@ func (c *Client) DeleteLKENodePool(ctx context.Context, clusterID, poolID int) e // DeleteLKENodePoolNode deletes a given node from a node pool func (c *Client) DeleteLKENodePoolNode(ctx context.Context, clusterID int, nodeID string) error { + nodeID = url.PathEscape(nodeID) e := fmt.Sprintf("lke/clusters/%d/nodes/%s", clusterID, nodeID) _, err := coupleAPIErrors(c.R(ctx).Delete(e)) return err diff --git a/vendor/github.com/linode/linodego/longview_subscriptions.go b/vendor/github.com/linode/linodego/longview_subscriptions.go index 8b5c4e126..efb3ee126 100644 --- a/vendor/github.com/linode/linodego/longview_subscriptions.go +++ b/vendor/github.com/linode/linodego/longview_subscriptions.go @@ -3,6 +3,7 @@ package linodego import ( "context" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) @@ -50,6 +51,7 @@ func (c *Client) ListLongviewSubscriptions(ctx context.Context, opts *ListOption // GetLongviewSubscription gets the template with the provided ID func (c *Client) GetLongviewSubscription(ctx context.Context, templateID string) (*LongviewSubscription, error) { + templateID = url.PathEscape(templateID) e := fmt.Sprintf("longview/subscriptions/%s", templateID) req := c.R(ctx).SetResult(&LongviewSubscription{}) r, err := coupleAPIErrors(req.Get(e)) diff --git a/vendor/github.com/linode/linodego/mongo.go b/vendor/github.com/linode/linodego/mongo.go deleted file mode 100644 index 47b83fdc0..000000000 --- a/vendor/github.com/linode/linodego/mongo.go +++ /dev/null @@ -1,324 +0,0 @@ -package linodego - -import ( - "context" - "encoding/json" - "fmt" - "time" - - "github.com/go-resty/resty/v2" - "github.com/linode/linodego/internal/parseabletime" -) - -type MongoDatabaseTarget string - -const ( - MongoDatabaseTargetPrimary MongoDatabaseTarget = "primary" - MongoDatabaseTargetSecondary MongoDatabaseTarget = "secondary" -) - -type MongoCompressionType string - -const ( - MongoCompressionNone MongoCompressionType = "none" - MongoCompressionSnappy MongoCompressionType = "snappy" - MongoCompressionZlib MongoCompressionType = "zlib" -) - -type MongoStorageEngine string - -const ( - MongoStorageWiredTiger MongoStorageEngine = "wiredtiger" - MongoStorageMmapv1 MongoStorageEngine = "mmapv1" -) - -// A MongoDatabase is a instance of Linode Mongo Managed Databases -type MongoDatabase struct { - ID int `json:"id"` - Status DatabaseStatus `json:"status"` - Label string `json:"label"` - Region string `json:"region"` - Type string `json:"type"` - Engine string `json:"engine"` - Version string `json:"version"` - Encrypted bool `json:"encrypted"` - AllowList []string `json:"allow_list"` - Peers []string `json:"peers"` - Port int `json:"port"` - ReplicaSet string `json:"replica_set"` - SSLConnection bool `json:"ssl_connection"` - ClusterSize int `json:"cluster_size"` - Hosts DatabaseHost `json:"hosts"` - CompressionType MongoCompressionType `json:"compression_type"` - StorageEngine MongoStorageEngine `json:"storage_engine"` - Updates DatabaseMaintenanceWindow `json:"updates"` - Created *time.Time `json:"-"` - Updated *time.Time `json:"-"` -} - -func (d *MongoDatabase) UnmarshalJSON(b []byte) error { - type Mask MongoDatabase - - p := struct { - *Mask - Created *parseabletime.ParseableTime `json:"created"` - Updated *parseabletime.ParseableTime `json:"updated"` - }{ - Mask: (*Mask)(d), - } - - if err := json.Unmarshal(b, &p); err != nil { - return err - } - - d.Created = (*time.Time)(p.Created) - d.Updated = (*time.Time)(p.Updated) - return nil -} - -// MongoCreateOptions fields are used when creating a new Mongo Database -type MongoCreateOptions struct { - Label string `json:"label"` - Region string `json:"region"` - Type string `json:"type"` - Engine string `json:"engine"` - AllowList []string `json:"allow_list,omitempty"` - ClusterSize int `json:"cluster_size,omitempty"` - Encrypted bool `json:"encrypted,omitempty"` - SSLConnection bool `json:"ssl_connection,omitempty"` - CompressionType MongoCompressionType `json:"compression_type,omitempty"` - StorageEngine MongoStorageEngine `json:"storage_engine,omitempty"` -} - -// MongoUpdateOptions fields are used when altering the existing Mongo Database -type MongoUpdateOptions struct { - Label string `json:"label,omitempty"` - AllowList *[]string `json:"allow_list,omitempty"` - Updates *DatabaseMaintenanceWindow `json:"updates,omitempty"` -} - -// MongoDatabaseSSL is the SSL Certificate to access the Linode Managed Mongo Database -type MongoDatabaseSSL struct { - CACertificate []byte `json:"ca_certificate"` -} - -// MongoDatabaseCredential is the Root Credentials to access the Linode Managed Database -type MongoDatabaseCredential struct { - Username string `json:"username"` - Password string `json:"password"` -} - -type MongoDatabasesPagedResponse struct { - *PageOptions - Data []MongoDatabase `json:"data"` -} - -func (MongoDatabasesPagedResponse) endpoint(_ ...any) string { - return "databases/mongodb/instances" -} - -func (resp *MongoDatabasesPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { - res, err := coupleAPIErrors(r.SetResult(MongoDatabasesPagedResponse{}).Get(e)) - if err != nil { - return 0, 0, err - } - castedRes := res.Result().(*MongoDatabasesPagedResponse) - resp.Data = append(resp.Data, castedRes.Data...) - return castedRes.Pages, castedRes.Results, nil -} - -// ListMongoDatabases lists all Mongo Databases associated with the account -func (c *Client) ListMongoDatabases(ctx context.Context, opts *ListOptions) ([]MongoDatabase, error) { - response := MongoDatabasesPagedResponse{} - - err := c.listHelper(ctx, &response, opts) - if err != nil { - return nil, err - } - - return response.Data, nil -} - -// MongoDatabaseBackup is information for interacting with a backup for the existing Mongo Database -type MongoDatabaseBackup struct { - ID int `json:"id"` - Label string `json:"label"` - Type string `json:"type"` - Created *time.Time `json:"-"` -} - -func (d *MongoDatabaseBackup) UnmarshalJSON(b []byte) error { - type Mask MongoDatabaseBackup - - p := struct { - *Mask - Created *parseabletime.ParseableTime `json:"created"` - }{ - Mask: (*Mask)(d), - } - - if err := json.Unmarshal(b, &p); err != nil { - return err - } - - d.Created = (*time.Time)(p.Created) - return nil -} - -// MongoBackupCreateOptions are options used for CreateMongoDatabaseBackup(...) -type MongoBackupCreateOptions struct { - Label string `json:"label"` - Target MongoDatabaseTarget `json:"target"` -} - -type MongoDatabaseBackupsPagedResponse struct { - *PageOptions - Data []MongoDatabaseBackup `json:"data"` -} - -func (MongoDatabaseBackupsPagedResponse) endpoint(ids ...any) string { - id := ids[0].(int) - return fmt.Sprintf("databases/mongodb/instances/%d/backups", id) -} - -func (resp *MongoDatabaseBackupsPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { - res, err := coupleAPIErrors(r.SetResult(MongoDatabaseBackupsPagedResponse{}).Get(e)) - if err != nil { - return 0, 0, err - } - castedRes := res.Result().(*MongoDatabaseBackupsPagedResponse) - resp.Data = append(resp.Data, castedRes.Data...) - return castedRes.Pages, castedRes.Results, nil -} - -// ListMongoDatabaseBackups lists all Mongo Database Backups associated with the given Mongo Database -func (c *Client) ListMongoDatabaseBackups(ctx context.Context, databaseID int, opts *ListOptions) ([]MongoDatabaseBackup, error) { - response := MongoDatabaseBackupsPagedResponse{} - - err := c.listHelper(ctx, &response, opts, databaseID) - if err != nil { - return nil, err - } - - return response.Data, nil -} - -// GetMongoDatabase returns a single Mongo Database matching the id -func (c *Client) GetMongoDatabase(ctx context.Context, databaseID int) (*MongoDatabase, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d", databaseID) - req := c.R(ctx).SetResult(&MongoDatabase{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabase), nil -} - -// CreateMongoDatabase creates a new Mongo Database using the createOpts as configuration, returns the new Mongo Database -func (c *Client) CreateMongoDatabase(ctx context.Context, opts MongoCreateOptions) (*MongoDatabase, error) { - body, err := json.Marshal(opts) - if err != nil { - return nil, err - } - - e := "databases/mongodb/instances" - req := c.R(ctx).SetResult(&MongoDatabase{}).SetBody(string(body)) - r, err := coupleAPIErrors(req.Post(e)) - if err != nil { - return nil, err - } - return r.Result().(*MongoDatabase), nil -} - -// DeleteMongoDatabase deletes an existing Mongo Database with the given id -func (c *Client) DeleteMongoDatabase(ctx context.Context, databaseID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d", databaseID) - _, err := coupleAPIErrors(c.R(ctx).Delete(e)) - return err -} - -// UpdateMongoDatabase updates the given Mongo Database with the provided opts, returns the MongoDatabase with the new settings -func (c *Client) UpdateMongoDatabase(ctx context.Context, databaseID int, opts MongoUpdateOptions) (*MongoDatabase, error) { - body, err := json.Marshal(opts) - if err != nil { - return nil, err - } - - e := fmt.Sprintf("databases/mongodb/instances/%d", databaseID) - req := c.R(ctx).SetResult(&MongoDatabase{}).SetBody(string(body)) - r, err := coupleAPIErrors(req.Put(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabase), nil -} - -// PatchMongoDatabase applies security patches and updates to the underlying operating system of the Managed Mongo Database -func (c *Client) PatchMongoDatabase(ctx context.Context, databaseID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d/patch", databaseID) - _, err := coupleAPIErrors(c.R(ctx).Post(e)) - return err -} - -// GetMongoDatabaseCredentials returns the Root Credentials for the given Mongo Database -func (c *Client) GetMongoDatabaseCredentials(ctx context.Context, databaseID int) (*MongoDatabaseCredential, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d/credentials", databaseID) - req := c.R(ctx).SetResult(&MongoDatabaseCredential{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabaseCredential), nil -} - -// ResetMongoDatabaseCredentials returns the Root Credentials for the given Mongo Database (may take a few seconds to work) -func (c *Client) ResetMongoDatabaseCredentials(ctx context.Context, databaseID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d/credentials/reset", databaseID) - _, err := coupleAPIErrors(c.R(ctx).Post(e)) - return err -} - -// GetMongoDatabaseSSL returns the SSL Certificate for the given Mongo Database -func (c *Client) GetMongoDatabaseSSL(ctx context.Context, databaseID int) (*MongoDatabaseSSL, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d/ssl", databaseID) - req := c.R(ctx).SetResult(&MongoDatabaseSSL{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabaseSSL), nil -} - -// GetMongoDatabaseBackup returns a specific Mongo Database Backup with the given ids -func (c *Client) GetMongoDatabaseBackup(ctx context.Context, databaseID int, backupID int) (*MongoDatabaseBackup, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d/backups/%d", databaseID, backupID) - req := c.R(ctx).SetResult(&MongoDatabaseBackup{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabaseBackup), nil -} - -// RestoreMongoDatabaseBackup returns the given Mongo Database with the given Backup -func (c *Client) RestoreMongoDatabaseBackup(ctx context.Context, databaseID int, backupID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d/backups/%d/restore", databaseID, backupID) - _, err := coupleAPIErrors(c.R(ctx).Post(e)) - return err -} - -// CreateMongoDatabaseBackup creates a snapshot for the given Mongo database -func (c *Client) CreateMongoDatabaseBackup(ctx context.Context, databaseID int, opts MongoBackupCreateOptions) error { - body, err := json.Marshal(opts) - if err != nil { - return err - } - e := fmt.Sprintf("databases/mongodb/instances/%d/backups", databaseID) - _, err = coupleAPIErrors(c.R(ctx).SetBody(string(body)).Post(e)) - return err -} diff --git a/vendor/github.com/linode/linodego/mysql.go b/vendor/github.com/linode/linodego/mysql.go index 52161bb65..575d0b27b 100644 --- a/vendor/github.com/linode/linodego/mysql.go +++ b/vendor/github.com/linode/linodego/mysql.go @@ -19,7 +19,7 @@ const ( MySQLDatabaseTargetSecondary MySQLDatabaseTarget = "secondary" ) -// A MySQLDatabase is a instance of Linode MySQL Managed Databases +// A MySQLDatabase is an instance of Linode MySQL Managed Databases type MySQLDatabase struct { ID int `json:"id"` Status DatabaseStatus `json:"status"` diff --git a/vendor/github.com/linode/linodego/network_ips.go b/vendor/github.com/linode/linodego/network_ips.go index c22f72da5..5b86883e9 100644 --- a/vendor/github.com/linode/linodego/network_ips.go +++ b/vendor/github.com/linode/linodego/network_ips.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) @@ -39,6 +40,12 @@ type IPAddressesShareOptions struct { LinodeID int `json:"linode_id"` } +// ListIPAddressesQuery fields are those accepted as query params for the +// ListIPAddresses function. +type ListIPAddressesQuery struct { + SkipIPv6RDNS bool `query:"skip_ipv6_rdns"` +} + // GetUpdateOptions converts a IPAddress to IPAddressUpdateOptions for use in UpdateIPAddress func (i InstanceIP) GetUpdateOptions() (o IPAddressUpdateOptions) { o.RDNS = copyString(&i.RDNS) @@ -72,6 +79,7 @@ func (c *Client) ListIPAddresses(ctx context.Context, opts *ListOptions) ([]Inst // GetIPAddress gets the template with the provided ID func (c *Client) GetIPAddress(ctx context.Context, id string) (*InstanceIP, error) { + id = url.PathEscape(id) e := fmt.Sprintf("networking/ips/%s", id) req := c.R(ctx).SetResult(&InstanceIP{}) r, err := coupleAPIErrors(req.Get(e)) @@ -88,6 +96,7 @@ func (c *Client) UpdateIPAddress(ctx context.Context, id string, opts IPAddressU return nil, err } + id = url.PathEscape(id) e := fmt.Sprintf("networking/ips/%s", id) req := c.R(ctx).SetResult(&InstanceIP{}).SetBody(string(body)) r, err := coupleAPIErrors(req.Put(e)) diff --git a/vendor/github.com/linode/linodego/network_pools.go b/vendor/github.com/linode/linodego/network_pools.go index 06c13c4bd..36f8b8f99 100644 --- a/vendor/github.com/linode/linodego/network_pools.go +++ b/vendor/github.com/linode/linodego/network_pools.go @@ -3,6 +3,7 @@ package linodego import ( "context" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) @@ -40,6 +41,7 @@ func (c *Client) ListIPv6Pools(ctx context.Context, opts *ListOptions) ([]IPv6Ra // GetIPv6Pool gets the template with the provided ID func (c *Client) GetIPv6Pool(ctx context.Context, id string) (*IPv6Range, error) { + id = url.PathEscape(id) e := fmt.Sprintf("networking/ipv6/pools/%s", id) req := c.R(ctx).SetResult(&IPv6Range{}) r, err := coupleAPIErrors(req.Get(e)) diff --git a/vendor/github.com/linode/linodego/network_ranges.go b/vendor/github.com/linode/linodego/network_ranges.go index 3caa714c7..6a0122372 100644 --- a/vendor/github.com/linode/linodego/network_ranges.go +++ b/vendor/github.com/linode/linodego/network_ranges.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) @@ -48,6 +49,7 @@ func (c *Client) ListIPv6Ranges(ctx context.Context, opts *ListOptions) ([]IPv6R // GetIPv6Range gets details about an IPv6 range func (c *Client) GetIPv6Range(ctx context.Context, ipRange string) (*IPv6Range, error) { + ipRange = url.PathEscape(ipRange) e := fmt.Sprintf("networking/ipv6/ranges/%s", ipRange) req := c.R(ctx).SetResult(&IPv6Range{}) r, err := coupleAPIErrors(req.Get(e)) @@ -75,6 +77,7 @@ func (c *Client) CreateIPv6Range(ctx context.Context, opts IPv6RangeCreateOption // DeleteIPv6Range deletes an IPv6 Range. func (c *Client) DeleteIPv6Range(ctx context.Context, ipRange string) error { + ipRange = url.PathEscape(ipRange) e := fmt.Sprintf("networking/ipv6/ranges/%s", ipRange) _, err := coupleAPIErrors(c.R(ctx).Delete(e)) return err diff --git a/vendor/github.com/linode/linodego/nodebalancer.go b/vendor/github.com/linode/linodego/nodebalancer.go index da6c5274b..f7ec8e275 100644 --- a/vendor/github.com/linode/linodego/nodebalancer.go +++ b/vendor/github.com/linode/linodego/nodebalancer.go @@ -53,6 +53,7 @@ type NodeBalancerCreateOptions struct { ClientConnThrottle *int `json:"client_conn_throttle,omitempty"` Configs []*NodeBalancerConfigCreateOptions `json:"configs,omitempty"` Tags []string `json:"tags"` + FirewallID int `json:"firewall_id,omitempty"` } // NodeBalancerUpdateOptions are the options permitted for UpdateNodeBalancer diff --git a/vendor/github.com/linode/linodego/nodebalancer_firewalls.go b/vendor/github.com/linode/linodego/nodebalancer_firewalls.go new file mode 100644 index 000000000..d2b339c7d --- /dev/null +++ b/vendor/github.com/linode/linodego/nodebalancer_firewalls.go @@ -0,0 +1,41 @@ +package linodego + +import ( + "context" + "fmt" + + "github.com/go-resty/resty/v2" +) + +// NodeBalancerFirewallsPagedResponse represents a Linode API response for listing of Cloud Firewalls +type NodeBalancerFirewallsPagedResponse struct { + *PageOptions + Data []Firewall `json:"data"` +} + +func (NodeBalancerFirewallsPagedResponse) endpoint(ids ...any) string { + id := ids[0].(int) + return fmt.Sprintf("nodebalancers/%d/firewalls", id) +} + +func (resp *NodeBalancerFirewallsPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(NodeBalancerFirewallsPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*NodeBalancerFirewallsPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +// ListNodeBalancerFirewalls returns a paginated list of Cloud Firewalls for nodebalancerID +func (c *Client) ListNodeBalancerFirewalls(ctx context.Context, nodebalancerID int, opts *ListOptions) ([]Firewall, error) { + response := NodeBalancerFirewallsPagedResponse{} + + err := c.listHelper(ctx, &response, opts, nodebalancerID) + if err != nil { + return nil, err + } + + return response.Data, nil +} diff --git a/vendor/github.com/linode/linodego/object_storage_bucket_certs.go b/vendor/github.com/linode/linodego/object_storage_bucket_certs.go index e8cca26f5..904f2dcda 100644 --- a/vendor/github.com/linode/linodego/object_storage_bucket_certs.go +++ b/vendor/github.com/linode/linodego/object_storage_bucket_certs.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/url" ) type ObjectStorageBucketCert struct { @@ -22,6 +23,8 @@ func (c *Client) UploadObjectStorageBucketCert(ctx context.Context, clusterID, b return nil, err } + clusterID = url.PathEscape(clusterID) + bucket = url.PathEscape(bucket) e := fmt.Sprintf("object-storage/buckets/%s/%s/ssl", clusterID, bucket) req := c.R(ctx).SetResult(&ObjectStorageBucketCert{}).SetBody(string(body)) r, err := coupleAPIErrors(req.Post(e)) @@ -33,6 +36,8 @@ func (c *Client) UploadObjectStorageBucketCert(ctx context.Context, clusterID, b // GetObjectStorageBucketCert gets an ObjectStorageBucketCert func (c *Client) GetObjectStorageBucketCert(ctx context.Context, clusterID, bucket string) (*ObjectStorageBucketCert, error) { + clusterID = url.PathEscape(clusterID) + bucket = url.PathEscape(bucket) e := fmt.Sprintf("object-storage/buckets/%s/%s/ssl", clusterID, bucket) req := c.R(ctx).SetResult(&ObjectStorageBucketCert{}) r, err := coupleAPIErrors(req.Get(e)) @@ -44,6 +49,8 @@ func (c *Client) GetObjectStorageBucketCert(ctx context.Context, clusterID, buck // DeleteObjectStorageBucketCert deletes an ObjectStorageBucketCert func (c *Client) DeleteObjectStorageBucketCert(ctx context.Context, clusterID, bucket string) error { + clusterID = url.PathEscape(clusterID) + bucket = url.PathEscape(bucket) e := fmt.Sprintf("object-storage/buckets/%s/%s/ssl", clusterID, bucket) _, err := coupleAPIErrors(c.R(ctx).Delete(e)) return err diff --git a/vendor/github.com/linode/linodego/object_storage_buckets.go b/vendor/github.com/linode/linodego/object_storage_buckets.go index 9567eac66..060ec985d 100644 --- a/vendor/github.com/linode/linodego/object_storage_buckets.go +++ b/vendor/github.com/linode/linodego/object_storage_buckets.go @@ -84,7 +84,7 @@ type ObjectStorageBucketsPagedResponse struct { func (ObjectStorageBucketsPagedResponse) endpoint(args ...any) string { endpoint := "object-storage/buckets" if len(args) > 0 { - endpoint = fmt.Sprintf(endpoint+"/%s", args[0]) + endpoint = fmt.Sprintf(endpoint+"/%s", url.PathEscape(args[0].(string))) } return endpoint } @@ -122,6 +122,7 @@ func (c *Client) ListObjectStorageBucketsInCluster(ctx context.Context, opts *Li // GetObjectStorageBucket gets the ObjectStorageBucket with the provided label func (c *Client) GetObjectStorageBucket(ctx context.Context, clusterID, label string) (*ObjectStorageBucket, error) { label = url.PathEscape(label) + clusterID = url.PathEscape(clusterID) e := fmt.Sprintf("object-storage/buckets/%s/%s", clusterID, label) req := c.R(ctx).SetResult(&ObjectStorageBucket{}) r, err := coupleAPIErrors(req.Get(e)) @@ -150,6 +151,7 @@ func (c *Client) CreateObjectStorageBucket(ctx context.Context, opts ObjectStora // GetObjectStorageBucketAccess gets the current access config for a bucket func (c *Client) GetObjectStorageBucketAccess(ctx context.Context, clusterID, label string) (*ObjectStorageBucketAccess, error) { label = url.PathEscape(label) + clusterID = url.PathEscape(clusterID) e := fmt.Sprintf("object-storage/buckets/%s/%s/access", clusterID, label) req := c.R(ctx).SetResult(&ObjectStorageBucketAccess{}) r, err := coupleAPIErrors(req.Get(e)) @@ -168,6 +170,7 @@ func (c *Client) UpdateObjectStorageBucketAccess(ctx context.Context, clusterID, } label = url.PathEscape(label) + clusterID = url.PathEscape(clusterID) e := fmt.Sprintf("object-storage/buckets/%s/%s/access", clusterID, label) _, err = coupleAPIErrors(c.R(ctx).SetBody(string(body)).Post(e)) if err != nil { diff --git a/vendor/github.com/linode/linodego/object_storage_clusters.go b/vendor/github.com/linode/linodego/object_storage_clusters.go index c5fbeb587..4e4e3e267 100644 --- a/vendor/github.com/linode/linodego/object_storage_clusters.go +++ b/vendor/github.com/linode/linodego/object_storage_clusters.go @@ -3,6 +3,7 @@ package linodego import ( "context" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) @@ -49,6 +50,7 @@ func (c *Client) ListObjectStorageClusters(ctx context.Context, opts *ListOption // GetObjectStorageCluster gets the template with the provided ID func (c *Client) GetObjectStorageCluster(ctx context.Context, clusterID string) (*ObjectStorageCluster, error) { + clusterID = url.PathEscape(clusterID) e := fmt.Sprintf("object-storage/clusters/%s", clusterID) req := c.R(ctx).SetResult(&ObjectStorageCluster{}) r, err := coupleAPIErrors(req.Get(e)) diff --git a/vendor/github.com/linode/linodego/object_storage_object.go b/vendor/github.com/linode/linodego/object_storage_object.go index f18f03688..4d262f40e 100644 --- a/vendor/github.com/linode/linodego/object_storage_object.go +++ b/vendor/github.com/linode/linodego/object_storage_object.go @@ -37,6 +37,7 @@ func (c *Client) CreateObjectStorageObjectURL(ctx context.Context, objectID, lab } label = url.PathEscape(label) + objectID = url.PathEscape(objectID) e := fmt.Sprintf("object-storage/buckets/%s/%s/object-url", objectID, label) req := c.R(ctx).SetResult(&ObjectStorageObjectURL{}).SetBody(string(body)) r, err := coupleAPIErrors(req.Post(e)) @@ -45,6 +46,7 @@ func (c *Client) CreateObjectStorageObjectURL(ctx context.Context, objectID, lab func (c *Client) GetObjectStorageObjectACLConfig(ctx context.Context, objectID, label, object string) (*ObjectStorageObjectACLConfig, error) { label = url.PathEscape(label) + object = url.QueryEscape(object) e := fmt.Sprintf("object-storage/buckets/%s/%s/object-acl?name=%s", objectID, label, object) req := c.R(ctx).SetResult(&ObjectStorageObjectACLConfig{}) r, err := coupleAPIErrors(req.Get(e)) diff --git a/vendor/github.com/linode/linodego/pagination.go b/vendor/github.com/linode/linodego/pagination.go index 2de2cfe32..671ef602f 100644 --- a/vendor/github.com/linode/linodego/pagination.go +++ b/vendor/github.com/linode/linodego/pagination.go @@ -7,8 +7,10 @@ package linodego import ( "context" "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" + "reflect" "strconv" "github.com/go-resty/resty/v2" @@ -16,16 +18,22 @@ import ( // PageOptions are the pagination parameters for List endpoints type PageOptions struct { - Page int `url:"page,omitempty" json:"page"` - Pages int `url:"pages,omitempty" json:"pages"` - Results int `url:"results,omitempty" json:"results"` + Page int `json:"page" url:"page,omitempty"` + Pages int `json:"pages" url:"pages,omitempty"` + Results int `json:"results" url:"results,omitempty"` } // ListOptions are the pagination and filtering (TODO) parameters for endpoints +// nolint type ListOptions struct { *PageOptions - PageSize int - Filter string + PageSize int `json:"page_size"` + Filter string `json:"filter"` + + // QueryParams allows for specifying custom query parameters on list endpoint + // calls. QueryParams should be an instance of a struct containing fields with + // the `query` tag. + QueryParams any } // NewListOptions simplified construction of ListOptions using only @@ -46,23 +54,36 @@ func (l ListOptions) Hash() (string, error) { h.Write(data) - return fmt.Sprintf("%x", h.Sum(nil)), nil + return hex.EncodeToString(h.Sum(nil)), nil } -func applyListOptionsToRequest(opts *ListOptions, req *resty.Request) { - if opts != nil { - if opts.PageOptions != nil && opts.Page > 0 { - req.SetQueryParam("page", strconv.Itoa(opts.Page)) - } +func applyListOptionsToRequest(opts *ListOptions, req *resty.Request) error { + if opts == nil { + return nil + } - if opts.PageSize > 0 { - req.SetQueryParam("page_size", strconv.Itoa(opts.PageSize)) + if opts.QueryParams != nil { + params, err := flattenQueryStruct(opts.QueryParams) + if err != nil { + return fmt.Errorf("failed to apply list options: %w", err) } - if len(opts.Filter) > 0 { - req.SetHeader("X-Filter", opts.Filter) - } + req.SetQueryParams(params) + } + + if opts.PageOptions != nil && opts.Page > 0 { + req.SetQueryParam("page", strconv.Itoa(opts.Page)) + } + + if opts.PageSize > 0 { + req.SetQueryParam("page_size", strconv.Itoa(opts.PageSize)) + } + + if len(opts.Filter) > 0 { + req.SetHeader("X-Filter", opts.Filter) } + + return nil } type PagedResponse interface { @@ -77,7 +98,9 @@ type PagedResponse interface { // opts.results and opts.pages will be updated from the API response func (c *Client) listHelper(ctx context.Context, pager PagedResponse, opts *ListOptions, ids ...any) error { req := c.R(ctx) - applyListOptionsToRequest(opts, req) + if err := applyListOptionsToRequest(opts, req); err != nil { + return err + } pages, results, err := pager.castResult(req, pager.endpoint(ids...)) if err != nil { @@ -102,3 +125,75 @@ func (c *Client) listHelper(ctx context.Context, pager PagedResponse, opts *List opts.Pages = pages return nil } + +// flattenQueryStruct flattens a structure into a Resty-compatible query param map. +// Fields are mapped using the `query` struct tag. +func flattenQueryStruct(val any) (map[string]string, error) { + result := make(map[string]string) + + reflectVal := reflect.ValueOf(val) + + // Deref pointer if necessary + if reflectVal.Kind() == reflect.Pointer { + if reflectVal.IsNil() { + return nil, fmt.Errorf("QueryParams is a nil pointer") + } + reflectVal = reflect.Indirect(reflectVal) + } + + if reflectVal.Kind() != reflect.Struct { + return nil, fmt.Errorf( + "expected struct type for the QueryParams but got: %s", + reflectVal.Kind().String(), + ) + } + + valType := reflectVal.Type() + + for i := 0; i < valType.NumField(); i++ { + currentField := valType.Field(i) + + queryTag, ok := currentField.Tag.Lookup("query") + // Skip untagged fields + if !ok { + continue + } + + valField := reflectVal.FieldByName(currentField.Name) + if !valField.IsValid() { + return nil, fmt.Errorf("invalid query param tag: %s", currentField.Name) + } + + // Skip if it's a zero value + if valField.IsZero() { + continue + } + + // Deref the pointer is necessary + if valField.Kind() == reflect.Pointer { + valField = reflect.Indirect(valField) + } + + fieldString, err := queryFieldToString(valField) + if err != nil { + return nil, err + } + + result[queryTag] = fieldString + } + + return result, nil +} + +func queryFieldToString(value reflect.Value) (string, error) { + switch value.Kind() { + case reflect.String: + return value.String(), nil + case reflect.Int64, reflect.Int32, reflect.Int: + return strconv.FormatInt(value.Int(), 10), nil + case reflect.Bool: + return strconv.FormatBool(value.Bool()), nil + default: + return "", fmt.Errorf("unsupported query param type: %s", value.Type().Name()) + } +} diff --git a/vendor/github.com/linode/linodego/postgres.go b/vendor/github.com/linode/linodego/postgres.go index 2484ecdf9..35158b6e5 100644 --- a/vendor/github.com/linode/linodego/postgres.go +++ b/vendor/github.com/linode/linodego/postgres.go @@ -35,7 +35,7 @@ const ( PostgresReplicationSemiSynch PostgresReplicationType = "semi_synch" ) -// A PostgresDatabase is a instance of Linode Postgres Managed Databases +// A PostgresDatabase is an instance of Linode Postgres Managed Databases type PostgresDatabase struct { ID int `json:"id"` Status DatabaseStatus `json:"status"` diff --git a/vendor/github.com/linode/linodego/regions.go b/vendor/github.com/linode/linodego/regions.go index 24970dd4f..f4210383e 100644 --- a/vendor/github.com/linode/linodego/regions.go +++ b/vendor/github.com/linode/linodego/regions.go @@ -3,6 +3,7 @@ package linodego import ( "context" "fmt" + "net/url" "time" "github.com/go-resty/resty/v2" @@ -74,7 +75,7 @@ func (c *Client) ListRegions(ctx context.Context, opts *ListOptions) ([]Region, // GetRegion gets the template with the provided ID. This endpoint is cached by default. func (c *Client) GetRegion(ctx context.Context, regionID string) (*Region, error) { - e := fmt.Sprintf("regions/%s", regionID) + e := fmt.Sprintf("regions/%s", url.PathEscape(regionID)) if result := c.getCachedResponse(e); result != nil { result := result.(Region) diff --git a/vendor/github.com/linode/linodego/regions_availability.go b/vendor/github.com/linode/linodego/regions_availability.go new file mode 100644 index 000000000..d4510dd3d --- /dev/null +++ b/vendor/github.com/linode/linodego/regions_availability.go @@ -0,0 +1,80 @@ +package linodego + +import ( + "context" + "fmt" + "net/url" + + "github.com/go-resty/resty/v2" +) + +// Region represents a linode region object +type RegionAvailability struct { + Region string `json:"region"` + Plan string `json:"plan"` + Available bool `json:"available"` +} + +// RegionsAvailabilityPagedResponse represents a linode API response for listing +type RegionsAvailabilityPagedResponse struct { + *PageOptions + Data []RegionAvailability `json:"data"` +} + +// endpoint gets the endpoint URL for Region +func (RegionsAvailabilityPagedResponse) endpoint(_ ...any) string { + return "regions/availability" +} + +func (resp *RegionsAvailabilityPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(RegionsAvailabilityPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*RegionsAvailabilityPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +// ListRegionsAvailability lists Regions. This endpoint is cached by default. +func (c *Client) ListRegionsAvailability(ctx context.Context, opts *ListOptions) ([]RegionAvailability, error) { + response := RegionsAvailabilityPagedResponse{} + + endpoint, err := generateListCacheURL(response.endpoint(), opts) + if err != nil { + return nil, err + } + + if result := c.getCachedResponse(endpoint); result != nil { + return result.([]RegionAvailability), nil + } + + err = c.listHelper(ctx, &response, opts) + if err != nil { + return nil, err + } + + c.addCachedResponse(endpoint, response.Data, &cacheExpiryTime) + + return response.Data, nil +} + +// GetRegionAvailability gets the template with the provided ID. This endpoint is cached by default. +func (c *Client) GetRegionAvailability(ctx context.Context, regionID string) (*RegionAvailability, error) { + e := fmt.Sprintf("regions/%s/availability", url.PathEscape(regionID)) + + if result := c.getCachedResponse(e); result != nil { + result := result.(RegionAvailability) + return &result, nil + } + + req := c.R(ctx).SetResult(&RegionAvailability{}) + r, err := coupleAPIErrors(req.Get(e)) + if err != nil { + return nil, err + } + + c.addCachedResponse(e, r.Result(), &cacheExpiryTime) + + return r.Result().(*RegionAvailability), nil +} diff --git a/vendor/github.com/linode/linodego/tags.go b/vendor/github.com/linode/linodego/tags.go index 396708e2f..f22208ec4 100644 --- a/vendor/github.com/linode/linodego/tags.go +++ b/vendor/github.com/linode/linodego/tags.go @@ -83,7 +83,7 @@ type TaggedObjectsPagedResponse struct { // endpoint gets the endpoint URL for Tag func (TaggedObjectsPagedResponse) endpoint(ids ...any) string { - id := ids[0].(string) + id := url.PathEscape(ids[0].(string)) return fmt.Sprintf("tags/%s", id) } diff --git a/vendor/github.com/linode/linodego/types.go b/vendor/github.com/linode/linodego/types.go index ee6e4c8ca..1d8341367 100644 --- a/vendor/github.com/linode/linodego/types.go +++ b/vendor/github.com/linode/linodego/types.go @@ -3,22 +3,26 @@ package linodego import ( "context" "fmt" + "net/url" "github.com/go-resty/resty/v2" ) // LinodeType represents a linode type object type LinodeType struct { - ID string `json:"id"` - Disk int `json:"disk"` - Class LinodeTypeClass `json:"class"` // enum: nanode, standard, highmem, dedicated - Price *LinodePrice `json:"price"` - Label string `json:"label"` - Addons *LinodeAddons `json:"addons"` - NetworkOut int `json:"network_out"` - Memory int `json:"memory"` - Transfer int `json:"transfer"` - VCPUs int `json:"vcpus"` + ID string `json:"id"` + Disk int `json:"disk"` + Class LinodeTypeClass `json:"class"` // enum: nanode, standard, highmem, dedicated, gpu + Price *LinodePrice `json:"price"` + Label string `json:"label"` + Addons *LinodeAddons `json:"addons"` + RegionPrices []LinodeRegionPrice `json:"region_prices"` + NetworkOut int `json:"network_out"` + Memory int `json:"memory"` + Transfer int `json:"transfer"` + VCPUs int `json:"vcpus"` + GPUs int `json:"gpus"` + Successor string `json:"successor"` } // LinodePrice represents a linode type price object @@ -29,7 +33,8 @@ type LinodePrice struct { // LinodeBackupsAddon represents a linode backups addon object type LinodeBackupsAddon struct { - Price *LinodePrice `json:"price"` + Price *LinodePrice `json:"price"` + RegionPrices []LinodeRegionPrice `json:"region_prices"` } // LinodeAddons represent the linode addons object @@ -37,6 +42,14 @@ type LinodeAddons struct { Backups *LinodeBackupsAddon `json:"backups"` } +// LinodeRegionPrice represents an individual type or addon +// price exception for a region. +type LinodeRegionPrice struct { + ID string `json:"id"` + Hourly float32 `json:"hourly"` + Monthly float32 `json:"monthly"` +} + // LinodeTypeClass constants start with Class and include Linode API Instance Type Classes type LinodeTypeClass string @@ -46,6 +59,7 @@ const ( ClassStandard LinodeTypeClass = "standard" ClassHighmem LinodeTypeClass = "highmem" ClassDedicated LinodeTypeClass = "dedicated" + ClassGPU LinodeTypeClass = "gpu" ) // LinodeTypesPagedResponse represents a linode types API response for listing @@ -93,7 +107,7 @@ func (c *Client) ListTypes(ctx context.Context, opts *ListOptions) ([]LinodeType // GetType gets the type with the provided ID. This endpoint is cached by default. func (c *Client) GetType(ctx context.Context, typeID string) (*LinodeType, error) { - e := fmt.Sprintf("linode/types/%s", typeID) + e := fmt.Sprintf("linode/types/%s", url.PathEscape(typeID)) if result := c.getCachedResponse(e); result != nil { result := result.(LinodeType) diff --git a/vendor/github.com/linode/linodego/vpc.go b/vendor/github.com/linode/linodego/vpc.go new file mode 100644 index 000000000..eb5aa1c1f --- /dev/null +++ b/vendor/github.com/linode/linodego/vpc.go @@ -0,0 +1,155 @@ +package linodego + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/go-resty/resty/v2" + "github.com/linode/linodego/internal/parseabletime" +) + +type VPC struct { + ID int `json:"id"` + Label string `json:"label"` + Description string `json:"description"` + Region string `json:"region"` + Subnets []VPCSubnet `json:"subnets"` + Created *time.Time `json:"-"` + Updated *time.Time `json:"-"` +} + +type VPCCreateOptions struct { + Label string `json:"label"` + Description string `json:"description,omitempty"` + Region string `json:"region"` + Subnets []VPCSubnetCreateOptions `json:"subnets,omitempty"` +} + +type VPCUpdateOptions struct { + Label string `json:"label,omitempty"` + Description string `json:"description,omitempty"` +} + +type VPCsPagedResponse struct { + *PageOptions + Data []VPC `json:"data"` +} + +func (VPCsPagedResponse) endpoint(_ ...any) string { + return "vpcs" +} + +func (resp *VPCsPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(VPCsPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*VPCsPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +func (v VPC) GetCreateOptions() VPCCreateOptions { + subnetCreations := make([]VPCSubnetCreateOptions, len(v.Subnets)) + for i, s := range v.Subnets { + subnetCreations[i] = s.GetCreateOptions() + } + + return VPCCreateOptions{ + Label: v.Label, + Description: v.Description, + Region: v.Region, + Subnets: subnetCreations, + } +} + +func (v VPC) GetUpdateOptions() VPCUpdateOptions { + return VPCUpdateOptions{ + Label: v.Label, + Description: v.Description, + } +} + +func (v *VPC) UnmarshalJSON(b []byte) error { + type Mask VPC + p := struct { + *Mask + Created *parseabletime.ParseableTime `json:"created"` + Updated *parseabletime.ParseableTime `json:"updated"` + }{ + Mask: (*Mask)(v), + } + if err := json.Unmarshal(b, &p); err != nil { + return err + } + + v.Created = (*time.Time)(p.Created) + v.Updated = (*time.Time)(p.Updated) + + return nil +} + +func (c *Client) CreateVPC( + ctx context.Context, + opts VPCCreateOptions, +) (*VPC, error) { + body, err := json.Marshal(opts) + if err != nil { + return nil, err + } + + req := c.R(ctx).SetResult(&VPC{}).SetBody(string(body)) + r, err := coupleAPIErrors(req.Post("vpcs")) + if err != nil { + return nil, err + } + + return r.Result().(*VPC), nil +} + +func (c *Client) GetVPC(ctx context.Context, vpcID int) (*VPC, error) { + e := fmt.Sprintf("/vpcs/%d", vpcID) + req := c.R(ctx).SetResult(&VPC{}) + r, err := coupleAPIErrors(req.Get(e)) + if err != nil { + return nil, err + } + return r.Result().(*VPC), nil +} + +func (c *Client) ListVPCs(ctx context.Context, opts *ListOptions) ([]VPC, error) { + response := VPCsPagedResponse{} + err := c.listHelper(ctx, &response, opts) + if err != nil { + return nil, err + } + return response.Data, nil +} + +func (c *Client) UpdateVPC( + ctx context.Context, + vpcID int, + opts VPCUpdateOptions, +) (*VPC, error) { + body, err := json.Marshal(opts) + if err != nil { + return nil, err + } + + e := fmt.Sprintf("vpcs/%d", vpcID) + req := c.R(ctx).SetResult(&VPC{}).SetBody(body) + r, err := coupleAPIErrors(req.Put(e)) + if err != nil { + return nil, err + } + + return r.Result().(*VPC), nil +} + +func (c *Client) DeleteVPC(ctx context.Context, vpcID int) error { + e := fmt.Sprintf("vpcs/%d", vpcID) + _, err := coupleAPIErrors(c.R(ctx).Delete(e)) + return err +} diff --git a/vendor/github.com/linode/linodego/vpc_subnet.go b/vendor/github.com/linode/linodego/vpc_subnet.go new file mode 100644 index 000000000..24582bb33 --- /dev/null +++ b/vendor/github.com/linode/linodego/vpc_subnet.go @@ -0,0 +1,170 @@ +package linodego + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/go-resty/resty/v2" + "github.com/linode/linodego/internal/parseabletime" +) + +// VPCSubnetLinodeInterface represents an interface on a Linode that is currently +// assigned to this VPC subnet. +type VPCSubnetLinodeInterface struct { + ID int `json:"id"` + Active bool `json:"active"` +} + +// VPCSubnetLinode represents a Linode currently assigned to a VPC subnet. +type VPCSubnetLinode struct { + ID int `json:"id"` + Interfaces []VPCSubnetLinodeInterface `json:"interfaces"` +} + +type VPCSubnet struct { + ID int `json:"id"` + Label string `json:"label"` + IPv4 string `json:"ipv4"` + Linodes []VPCSubnetLinode `json:"linodes"` + Created *time.Time `json:"-"` + Updated *time.Time `json:"-"` +} + +type VPCSubnetCreateOptions struct { + Label string `json:"label"` + IPv4 string `json:"ipv4"` +} + +type VPCSubnetUpdateOptions struct { + Label string `json:"label"` +} + +type VPCSubnetsPagedResponse struct { + *PageOptions + Data []VPCSubnet `json:"data"` +} + +func (VPCSubnetsPagedResponse) endpoint(ids ...any) string { + id := ids[0].(int) + return fmt.Sprintf("vpcs/%d/subnets", id) +} + +func (resp *VPCSubnetsPagedResponse) castResult( + r *resty.Request, + e string, +) (int, int, error) { + res, err := coupleAPIErrors(r.SetResult(VPCSubnetsPagedResponse{}).Get(e)) + if err != nil { + return 0, 0, err + } + castedRes := res.Result().(*VPCSubnetsPagedResponse) + resp.Data = append(resp.Data, castedRes.Data...) + return castedRes.Pages, castedRes.Results, nil +} + +func (v *VPCSubnet) UnmarshalJSON(b []byte) error { + type Mask VPCSubnet + p := struct { + *Mask + Created *parseabletime.ParseableTime `json:"created"` + Updated *parseabletime.ParseableTime `json:"updated"` + }{ + Mask: (*Mask)(v), + } + if err := json.Unmarshal(b, &p); err != nil { + return err + } + + v.Created = (*time.Time)(p.Created) + v.Updated = (*time.Time)(p.Updated) + + return nil +} + +func (v VPCSubnet) GetCreateOptions() VPCSubnetCreateOptions { + return VPCSubnetCreateOptions{ + Label: v.Label, + IPv4: v.IPv4, + } +} + +func (v VPCSubnet) GetUpdateOptions() VPCSubnetUpdateOptions { + return VPCSubnetUpdateOptions{Label: v.Label} +} + +func (c *Client) CreateVPCSubnet( + ctx context.Context, + opts VPCSubnetCreateOptions, + vpcID int, +) (*VPCSubnet, error) { + body, err := json.Marshal(opts) + if err != nil { + return nil, err + } + + req := c.R(ctx).SetResult(&VPCSubnet{}).SetBody(string(body)) + e := fmt.Sprintf("vpcs/%d/subnets", vpcID) + r, err := coupleAPIErrors(req.Post(e)) + if err != nil { + return nil, err + } + + return r.Result().(*VPCSubnet), nil +} + +func (c *Client) GetVPCSubnet( + ctx context.Context, + vpcID int, + subnetID int, +) (*VPCSubnet, error) { + req := c.R(ctx).SetResult(&VPCSubnet{}) + + e := fmt.Sprintf("vpcs/%d/subnets/%d", vpcID, subnetID) + r, err := coupleAPIErrors(req.Get(e)) + if err != nil { + return nil, err + } + return r.Result().(*VPCSubnet), nil +} + +func (c *Client) ListVPCSubnets( + ctx context.Context, + vpcID int, + opts *ListOptions, +) ([]VPCSubnet, error) { + response := VPCSubnetsPagedResponse{} + err := c.listHelper(ctx, &response, opts, vpcID) + if err != nil { + return nil, err + } + return response.Data, nil +} + +func (c *Client) UpdateVPCSubnet( + ctx context.Context, + vpcID int, + subnetID int, + opts VPCSubnetUpdateOptions, +) (*VPCSubnet, error) { + body, err := json.Marshal(opts) + if err != nil { + return nil, err + } + + req := c.R(ctx).SetResult(&VPCSubnet{}).SetBody(body) + e := fmt.Sprintf("vpcs/%d/subnets/%d", vpcID, subnetID) + r, err := coupleAPIErrors(req.Put(e)) + if err != nil { + return nil, err + } + + return r.Result().(*VPCSubnet), nil +} + +func (c *Client) DeleteVPCSubnet(ctx context.Context, vpcID int, subnetID int) error { + e := fmt.Sprintf("vpcs/%d/subnets/%d", vpcID, subnetID) + _, err := coupleAPIErrors(c.R(ctx).Delete(e)) + return err +} diff --git a/vendor/github.com/linode/linodego/waitfor.go b/vendor/github.com/linode/linodego/waitfor.go index 60fbf9ec3..0b4d6c7bd 100644 --- a/vendor/github.com/linode/linodego/waitfor.go +++ b/vendor/github.com/linode/linodego/waitfor.go @@ -6,14 +6,23 @@ import ( "log" "net/http" "strconv" - "strings" "time" + + "golang.org/x/text/cases" + "golang.org/x/text/language" ) +var englishTitle = cases.Title(language.English) + type EventPoller struct { EntityID any EntityType EntityType - Action EventAction + + // Type is excluded here because it is implicitly determined + // by the event action. + SecondaryEntityID any + + Action EventAction client Client previousEvents map[int]bool @@ -25,7 +34,7 @@ func (client Client) WaitForInstanceStatus(ctx context.Context, instanceID int, ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -52,7 +61,7 @@ func (client Client) WaitForInstanceDiskStatus(ctx context.Context, instanceID i ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -88,7 +97,7 @@ func (client Client) WaitForVolumeStatus(ctx context.Context, volumeID int, stat ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -115,7 +124,7 @@ func (client Client) WaitForSnapshotStatus(ctx context.Context, instanceID int, ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -144,7 +153,7 @@ func (client Client) WaitForVolumeLinodeID(ctx context.Context, volumeID int, li ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -175,7 +184,7 @@ func (client Client) WaitForLKEClusterStatus(ctx context.Context, clusterID int, ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -237,7 +246,7 @@ func (client Client) WaitForLKEClusterConditions( return fmt.Errorf("failed to get Kubeconfig for LKE cluster %d: %w", clusterID, err) } - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() conditionOptions := ClusterConditionOptions{LKEClusterKubeconfig: lkeKubeConfig, TransportWrapper: options.TransportWrapper} @@ -271,8 +280,15 @@ func (client Client) WaitForLKEClusterConditions( // before returning. It will timeout with an error after timeoutSeconds. // If the event indicates a failure both the failed event and the error will be returned. // nolint -func (client Client) WaitForEventFinished(ctx context.Context, id any, entityType EntityType, action EventAction, minStart time.Time, timeoutSeconds int) (*Event, error) { - titledEntityType := strings.Title(string(entityType)) +func (client Client) WaitForEventFinished( + ctx context.Context, + id any, + entityType EntityType, + action EventAction, + minStart time.Time, + timeoutSeconds int, +) (*Event, error) { + titledEntityType := englishTitle.String(string(entityType)) filter := Filter{ Order: Descending, OrderBy: "created", @@ -291,12 +307,11 @@ func (client Client) WaitForEventFinished(ctx context.Context, id any, entityTyp // All of the filter supported types have int ids filterableEntityID, err := strconv.Atoi(fmt.Sprintf("%v", id)) if err != nil { - return nil, fmt.Errorf("Error parsing Entity ID %q for optimized WaitForEventFinished EventType %q: %w", id, entityType, err) + return nil, fmt.Errorf("error parsing Entity ID %q for optimized "+ + "WaitForEventFinished EventType %q: %w", id, entityType, err) } filter.AddField(Eq, "entity.id", filterableEntityID) filter.AddField(Eq, "entity.type", entityType) - - // TODO: are we conformatable with pages = 0 with the event type and id filter? } ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) @@ -307,7 +322,7 @@ func (client Client) WaitForEventFinished(ctx context.Context, id any, entityTyp log.Printf("[INFO] Waiting %d seconds for %s events since %v for %s %v", int(duration.Seconds()), action, minStart, titledEntityType, id) } - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) // avoid repeating log messages nextLog := "" @@ -369,8 +384,6 @@ func (client Client) WaitForEventFinished(ctx context.Context, id any, entityTyp continue } - // @TODO(displague) This event.Created check shouldn't be needed, but it appears - // that the ListEvents method is not populating it correctly if event.Created == nil { log.Printf("[WARN] event.Created is nil when API returned: %#+v", event.Created) } @@ -387,7 +400,7 @@ func (client Client) WaitForEventFinished(ctx context.Context, id any, entityTyp log.Printf("[INFO] %s %v action %s is finished", titledEntityType, id, action) return &event, nil } - // TODO(displague) can we bump the ticker to TimeRemaining/2 (>=1) when non-nil? + nextLog = fmt.Sprintf("[INFO] %s %v action %s is %s", titledEntityType, id, action, event.Status) } @@ -408,7 +421,7 @@ func (client Client) WaitForImageStatus(ctx context.Context, imageID string, sta ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -434,7 +447,7 @@ func (client Client) WaitForMySQLDatabaseBackup(ctx context.Context, dbID int, l ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -456,39 +469,12 @@ func (client Client) WaitForMySQLDatabaseBackup(ctx context.Context, dbID int, l } } -// WaitForMongoDatabaseBackup waits for the backup with the given label to be available. -func (client Client) WaitForMongoDatabaseBackup(ctx context.Context, dbID int, label string, timeoutSeconds int) (*MongoDatabaseBackup, error) { - ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) - defer cancel() - - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) - defer ticker.Stop() - - for { - select { - case <-ticker.C: - backups, err := client.ListMongoDatabaseBackups(ctx, dbID, nil) - if err != nil { - return nil, err - } - - for _, backup := range backups { - if backup.Label == label { - return &backup, nil - } - } - case <-ctx.Done(): - return nil, fmt.Errorf("failed to wait for backup %s: %w", label, ctx.Err()) - } - } -} - // WaitForPostgresDatabaseBackup waits for the backup with the given label to be available. func (client Client) WaitForPostgresDatabaseBackup(ctx context.Context, dbID int, label string, timeoutSeconds int) (*PostgresDatabaseBackup, error) { ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -521,14 +507,6 @@ var databaseStatusHandlers = map[DatabaseEngineType]databaseStatusFunc{ return db.Status, nil }, - DatabaseEngineTypeMongo: func(ctx context.Context, client Client, dbID int) (DatabaseStatus, error) { - db, err := client.GetMongoDatabase(ctx, dbID) - if err != nil { - return "", err - } - - return db.Status, nil - }, DatabaseEngineTypePostgres: func(ctx context.Context, client Client, dbID int) (DatabaseStatus, error) { db, err := client.GetPostgresDatabase(ctx, dbID) if err != nil { @@ -546,7 +524,7 @@ func (client Client) WaitForDatabaseStatus( ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(client.pollInterval) defer ticker.Stop() for { @@ -591,6 +569,21 @@ func (client Client) NewEventPoller( return &result, nil } +// NewEventPollerWithSecondary initializes a new Linode event poller with for events with a +// specific secondary entity. +func (client Client) NewEventPollerWithSecondary( + ctx context.Context, id any, primaryEntityType EntityType, secondaryID int, action EventAction, +) (*EventPoller, error) { + poller, err := client.NewEventPoller(ctx, id, primaryEntityType, action) + if err != nil { + return nil, err + } + + poller.SecondaryEntityID = secondaryID + + return poller, nil +} + // NewEventPollerWithoutEntity initializes a new Linode event poller without a target entity ID. // This is useful for create events where the ID of the entity is not yet known. // For example: @@ -646,7 +639,7 @@ func (p *EventPoller) PreTask(ctx context.Context) error { } func (p *EventPoller) WaitForLatestUnknownEvent(ctx context.Context) (*Event, error) { - ticker := time.NewTicker(p.client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(p.client.pollInterval) defer ticker.Stop() f := Filter{ @@ -676,6 +669,10 @@ func (p *EventPoller) WaitForLatestUnknownEvent(ctx context.Context) (*Event, er } for _, event := range events { + if p.SecondaryEntityID != nil && !eventMatchesSecondary(p.SecondaryEntityID, event) { + continue + } + if _, ok := p.previousEvents[event.ID]; !ok { // Store this event so it is no longer picked up // on subsequent jobs @@ -697,7 +694,7 @@ func (p *EventPoller) WaitForFinished( ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) defer cancel() - ticker := time.NewTicker(p.client.millisecondsPerPoll * time.Millisecond) + ticker := time.NewTicker(p.client.pollInterval) defer ticker.Stop() event, err := p.WaitForLatestUnknownEvent(ctx) @@ -722,7 +719,80 @@ func (p *EventPoller) WaitForFinished( continue } case <-ctx.Done(): - return nil, fmt.Errorf("failed to wait for event: %w", ctx.Err()) + return nil, fmt.Errorf("failed to wait for event finished: %w", ctx.Err()) + } + } +} + +// WaitForResourceFree waits for a resource to have no running events. +func (client Client) WaitForResourceFree( + ctx context.Context, entityType EntityType, entityID any, timeoutSeconds int, +) error { + apiFilter := Filter{ + Order: Descending, + OrderBy: "created", + } + apiFilter.AddField(Eq, "entity.id", entityID) + apiFilter.AddField(Eq, "entity.type", entityType) + + filterStr, err := apiFilter.MarshalJSON() + if err != nil { + return fmt.Errorf("failed to create filter: %s", err) + } + + ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) + defer cancel() + + ticker := time.NewTicker(client.pollInterval) + defer ticker.Stop() + + // A helper function to determine whether a resource is busy + checkIsBusy := func(events []Event) bool { + for _, event := range events { + if event.Status == EventStarted || event.Status == EventScheduled { + return true + } + } + + return false + } + + for { + select { + case <-ticker.C: + events, err := client.ListEvents(ctx, &ListOptions{ + Filter: string(filterStr), + }) + if err != nil { + return fmt.Errorf("failed to list events: %s", err) + } + + if !checkIsBusy(events) { + return nil + } + + case <-ctx.Done(): + return fmt.Errorf("failed to wait for resource free: %s", ctx.Err()) } } } + +// eventMatchesSecondary returns whether the given event's secondary entity +// matches the configured secondary ID. +// This logic has been broken out to improve readability. +func eventMatchesSecondary(configuredID any, e Event) bool { + // We should return false if the event has no secondary entity. + // e.g. A previous disk deletion has completed. + if e.SecondaryEntity == nil { + return false + } + + secondaryID := e.SecondaryEntity.ID + + // Evil hack to correct IDs parsed as floats + if value, ok := secondaryID.(float64); ok { + secondaryID = int(value) + } + + return secondaryID == configuredID +} diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/LICENSE b/vendor/github.com/matttproud/golang_protobuf_extensions/v2/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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/github.com/matttproud/golang_protobuf_extensions/v2/NOTICE b/vendor/github.com/matttproud/golang_protobuf_extensions/v2/NOTICE deleted file mode 100644 index 5d8cb5b72..000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/NOTICE +++ /dev/null @@ -1 +0,0 @@ -Copyright 2012 Matt T. Proud (matt.proud@gmail.com) diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/.gitignore b/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/.gitignore deleted file mode 100644 index e16fb946b..000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/.gitignore +++ /dev/null @@ -1 +0,0 @@ -cover.dat diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/Makefile b/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/Makefile deleted file mode 100644 index 81be21437..000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -all: - -cover: - go test -cover -v -coverprofile=cover.dat ./... - go tool cover -func cover.dat - -.PHONY: cover diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/decode.go b/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/decode.go deleted file mode 100644 index 7c08e564f..000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/decode.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2013 Matt T. Proud -// -// 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 pbutil - -import ( - "encoding/binary" - "errors" - "io" - - "google.golang.org/protobuf/proto" -) - -// TODO: Give error package name prefix in next minor release. -var errInvalidVarint = errors.New("invalid varint32 encountered") - -// ReadDelimited decodes a message from the provided length-delimited stream, -// where the length is encoded as 32-bit varint prefix to the message body. -// It returns the total number of bytes read and any applicable error. This is -// roughly equivalent to the companion Java API's -// MessageLite#parseDelimitedFrom. As per the reader contract, this function -// calls r.Read repeatedly as required until exactly one message including its -// prefix is read and decoded (or an error has occurred). The function never -// reads more bytes from the stream than required. The function never returns -// an error if a message has been read and decoded correctly, even if the end -// of the stream has been reached in doing so. In that case, any subsequent -// calls return (0, io.EOF). -func ReadDelimited(r io.Reader, m proto.Message) (n int, err error) { - // TODO: Consider allowing the caller to specify a decode buffer in the - // next major version. - - // TODO: Consider using error wrapping to annotate error state in pass- - // through cases in the next minor version. - - // Per AbstractParser#parsePartialDelimitedFrom with - // CodedInputStream#readRawVarint32. - var headerBuf [binary.MaxVarintLen32]byte - var bytesRead, varIntBytes int - var messageLength uint64 - for varIntBytes == 0 { // i.e. no varint has been decoded yet. - if bytesRead >= len(headerBuf) { - return bytesRead, errInvalidVarint - } - // We have to read byte by byte here to avoid reading more bytes - // than required. Each read byte is appended to what we have - // read before. - newBytesRead, err := r.Read(headerBuf[bytesRead : bytesRead+1]) - if newBytesRead == 0 { - if err != nil { - return bytesRead, err - } - // A Reader should not return (0, nil); but if it does, it should - // be treated as no-op according to the Reader contract. - continue - } - bytesRead += newBytesRead - // Now present everything read so far to the varint decoder and - // see if a varint can be decoded already. - messageLength, varIntBytes = binary.Uvarint(headerBuf[:bytesRead]) - } - - messageBuf := make([]byte, messageLength) - newBytesRead, err := io.ReadFull(r, messageBuf) - bytesRead += newBytesRead - if err != nil { - return bytesRead, err - } - - return bytesRead, proto.Unmarshal(messageBuf, m) -} diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/doc.go b/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/doc.go deleted file mode 100644 index c318385cb..000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 Matt T. Proud -// -// 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 pbutil provides record length-delimited Protocol Buffer streaming. -package pbutil diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/encode.go b/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/encode.go deleted file mode 100644 index e58dd9d29..000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/v2/pbutil/encode.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2013 Matt T. Proud -// -// 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 pbutil - -import ( - "encoding/binary" - "io" - - "google.golang.org/protobuf/proto" -) - -// WriteDelimited encodes and dumps a message to the provided writer prefixed -// with a 32-bit varint indicating the length of the encoded message, producing -// a length-delimited record stream, which can be used to chain together -// encoded messages of the same type together in a file. It returns the total -// number of bytes written and any applicable error. This is roughly -// equivalent to the companion Java API's MessageLite#writeDelimitedTo. -func WriteDelimited(w io.Writer, m proto.Message) (n int, err error) { - // TODO: Consider allowing the caller to specify an encode buffer in the - // next major version. - - buffer, err := proto.Marshal(m) - if err != nil { - return 0, err - } - - var buf [binary.MaxVarintLen32]byte - encodedLength := binary.PutUvarint(buf[:], uint64(len(buffer))) - - sync, err := w.Write(buf[:encodedLength]) - if err != nil { - return sync, err - } - - n, err = w.Write(buffer) - return n + sync, err -} diff --git a/vendor/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md index 06bea9fab..e57d86afe 100644 --- a/vendor/github.com/miekg/dns/README.md +++ b/vendor/github.com/miekg/dns/README.md @@ -81,6 +81,8 @@ A not-so-up-to-date-list-that-may-be-actually-current: * https://addr.tools/ * https://dnscheck.tools/ * https://github.com/egbakou/domainverifier +* https://github.com/semihalev/sdns +* https://github.com/wintbiit/NineDNS Send pull request if you want to be listed here. @@ -124,6 +126,7 @@ Example programs can be found in the `github.com/miekg/exdns` repository. *all of them* * 103{4,5} - DNS standard +* 1183 - ISDN, X25 and other deprecated records * 1348 - NSAP record (removed the record) * 1982 - Serial Arithmetic * 1876 - LOC record diff --git a/vendor/github.com/miekg/dns/acceptfunc.go b/vendor/github.com/miekg/dns/acceptfunc.go index ab2812e33..1a59a854e 100644 --- a/vendor/github.com/miekg/dns/acceptfunc.go +++ b/vendor/github.com/miekg/dns/acceptfunc.go @@ -10,8 +10,6 @@ type MsgAcceptFunc func(dh Header) MsgAcceptAction // // * opcode isn't OpcodeQuery or OpcodeNotify // -// * Zero bit isn't zero -// // * does not have exactly 1 question in the question section // // * has more than 1 RR in the Answer section diff --git a/vendor/github.com/miekg/dns/client.go b/vendor/github.com/miekg/dns/client.go index 9051ae007..9549fa923 100644 --- a/vendor/github.com/miekg/dns/client.go +++ b/vendor/github.com/miekg/dns/client.go @@ -6,7 +6,6 @@ import ( "context" "crypto/tls" "encoding/binary" - "fmt" "io" "net" "strings" @@ -56,14 +55,20 @@ type Client struct { // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout, // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and // Client.Dialer) or context.Context.Deadline (see ExchangeContext) - Timeout time.Duration - DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero - ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero - WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero - TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2) - TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations. - SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass - group singleflight + Timeout time.Duration + DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero + ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero + WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero + TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2) + TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations. + + // SingleInflight previously serialised multiple concurrent queries for the + // same Qname, Qtype and Qclass to ensure only one would be in flight at a + // time. + // + // Deprecated: This is a no-op. Callers should implement their own in flight + // query caching if needed. See github.com/miekg/dns/issues/1449. + SingleInflight bool } // Exchange performs a synchronous UDP query. It sends the message m to the address @@ -178,33 +183,13 @@ func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, er // This allows users of the library to implement their own connection management, // as opposed to Exchange, which will always use new connections and incur the added overhead // that entails when using "tcp" and especially "tcp-tls" clients. -// -// When the singleflight is set for this client the context is _not_ forwarded to the (shared) exchange, to -// prevent one cancellation from canceling all outstanding requests. func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) { - return c.exchangeWithConnContext(context.Background(), m, conn) + return c.ExchangeWithConnContext(context.Background(), m, conn) } -func (c *Client) exchangeWithConnContext(ctx context.Context, m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) { - if !c.SingleInflight { - return c.exchangeContext(ctx, m, conn) - } - - q := m.Question[0] - key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass) - r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) { - // When we're doing singleflight we don't want one context cancellation, cancel _all_ outstanding queries. - // Hence we ignore the context and use Background(). - return c.exchangeContext(context.Background(), m, conn) - }) - if r != nil && shared { - r = r.Copy() - } - - return r, rtt, err -} - -func (c *Client) exchangeContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) { +// ExchangeWithConnContext has the same behaviour as ExchangeWithConn and +// additionally obeys deadlines from the passed Context. +func (c *Client) ExchangeWithConnContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) { opt := m.IsEdns0() // If EDNS0 is used use that for size. if opt != nil && opt.UDPSize() >= MinMsgSize { @@ -474,5 +459,5 @@ func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, } defer conn.Close() - return c.exchangeWithConnContext(ctx, m, conn) + return c.ExchangeWithConnContext(ctx, m, conn) } diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go index 75b17f0c1..02d9199a4 100644 --- a/vendor/github.com/miekg/dns/defaults.go +++ b/vendor/github.com/miekg/dns/defaults.go @@ -22,8 +22,7 @@ func (dns *Msg) SetReply(request *Msg) *Msg { } dns.Rcode = RcodeSuccess if len(request.Question) > 0 { - dns.Question = make([]Question, 1) - dns.Question[0] = request.Question[0] + dns.Question = []Question{request.Question[0]} } return dns } @@ -272,40 +271,39 @@ func IsMsg(buf []byte) error { // IsFqdn checks if a domain name is fully qualified. func IsFqdn(s string) bool { - s2 := strings.TrimSuffix(s, ".") - if s == s2 { + // Check for (and remove) a trailing dot, returning if there isn't one. + if s == "" || s[len(s)-1] != '.' { return false } + s = s[:len(s)-1] - i := strings.LastIndexFunc(s2, func(r rune) bool { + // If we don't have an escape sequence before the final dot, we know it's + // fully qualified and can return here. + if s == "" || s[len(s)-1] != '\\' { + return true + } + + // Otherwise we have to check if the dot is escaped or not by checking if + // there are an odd or even number of escape sequences before the dot. + i := strings.LastIndexFunc(s, func(r rune) bool { return r != '\\' }) - - // Test whether we have an even number of escape sequences before - // the dot or none. - return (len(s2)-i)%2 != 0 + return (len(s)-i)%2 != 0 } -// IsRRset checks if a set of RRs is a valid RRset as defined by RFC 2181. -// This means the RRs need to have the same type, name, and class. Returns true -// if the RR set is valid, otherwise false. +// IsRRset reports whether a set of RRs is a valid RRset as defined by RFC 2181. +// This means the RRs need to have the same type, name, and class. func IsRRset(rrset []RR) bool { if len(rrset) == 0 { return false } - if len(rrset) == 1 { - return true - } - rrHeader := rrset[0].Header() - rrType := rrHeader.Rrtype - rrClass := rrHeader.Class - rrName := rrHeader.Name + baseH := rrset[0].Header() for _, rr := range rrset[1:] { - curRRHeader := rr.Header() - if curRRHeader.Rrtype != rrType || curRRHeader.Class != rrClass || curRRHeader.Name != rrName { + curH := rr.Header() + if curH.Rrtype != baseH.Rrtype || curH.Class != baseH.Class || curH.Name != baseH.Name { // Mismatch between the records, so this is not a valid rrset for - //signing/verifying + // signing/verifying return false } } @@ -323,9 +321,15 @@ func Fqdn(s string) string { } // CanonicalName returns the domain name in canonical form. A name in canonical -// form is lowercase and fully qualified. See Section 6.2 in RFC 4034. +// form is lowercase and fully qualified. Only US-ASCII letters are affected. See +// Section 6.2 in RFC 4034. func CanonicalName(s string) string { - return strings.ToLower(Fqdn(s)) + return strings.Map(func(r rune) rune { + if r >= 'A' && r <= 'Z' { + r += 'a' - 'A' + } + return r + }, Fqdn(s)) } // Copied from the official Go code. diff --git a/vendor/github.com/miekg/dns/dnssec_keyscan.go b/vendor/github.com/miekg/dns/dnssec_keyscan.go index f79658169..9c9972db6 100644 --- a/vendor/github.com/miekg/dns/dnssec_keyscan.go +++ b/vendor/github.com/miekg/dns/dnssec_keyscan.go @@ -37,7 +37,8 @@ func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, er return nil, ErrPrivKey } // TODO(mg): check if the pubkey matches the private key - algo, err := strconv.ParseUint(strings.SplitN(m["algorithm"], " ", 2)[0], 10, 8) + algoStr, _, _ := strings.Cut(m["algorithm"], " ") + algo, err := strconv.ParseUint(algoStr, 10, 8) if err != nil { return nil, ErrPrivKey } @@ -159,7 +160,7 @@ func parseKey(r io.Reader, file string) (map[string]string, error) { k = l.token case zValue: if k == "" { - return nil, &ParseError{file, "no private key seen", l} + return nil, &ParseError{file: file, err: "no private key seen", lex: l} } m[strings.ToLower(k)] = l.token diff --git a/vendor/github.com/miekg/dns/edns.go b/vendor/github.com/miekg/dns/edns.go index b5bdac816..1b58e8f0a 100644 --- a/vendor/github.com/miekg/dns/edns.go +++ b/vendor/github.com/miekg/dns/edns.go @@ -185,7 +185,7 @@ func (rr *OPT) Do() bool { // SetDo sets the DO (DNSSEC OK) bit. // If we pass an argument, set the DO bit to that value. -// It is possible to pass 2 or more arguments. Any arguments after the 1st is silently ignored. +// It is possible to pass 2 or more arguments, but they will be ignored. func (rr *OPT) SetDo(do ...bool) { if len(do) == 1 { if do[0] { @@ -508,6 +508,7 @@ func (e *EDNS0_LLQ) String() string { " " + strconv.FormatUint(uint64(e.LeaseLife), 10) return s } + func (e *EDNS0_LLQ) copy() EDNS0 { return &EDNS0_LLQ{e.Code, e.Version, e.Opcode, e.Error, e.Id, e.LeaseLife} } diff --git a/vendor/github.com/miekg/dns/generate.go b/vendor/github.com/miekg/dns/generate.go index ac8df34dd..a81d2bc51 100644 --- a/vendor/github.com/miekg/dns/generate.go +++ b/vendor/github.com/miekg/dns/generate.go @@ -35,17 +35,17 @@ func (zp *ZoneParser) generate(l lex) (RR, bool) { token = token[:i] } - sx := strings.SplitN(token, "-", 2) - if len(sx) != 2 { + startStr, endStr, ok := strings.Cut(token, "-") + if !ok { return zp.setParseError("bad start-stop in $GENERATE range", l) } - start, err := strconv.ParseInt(sx[0], 10, 64) + start, err := strconv.ParseInt(startStr, 10, 64) if err != nil { return zp.setParseError("bad start in $GENERATE range", l) } - end, err := strconv.ParseInt(sx[1], 10, 64) + end, err := strconv.ParseInt(endStr, 10, 64) if err != nil { return zp.setParseError("bad stop in $GENERATE range", l) } @@ -54,7 +54,7 @@ func (zp *ZoneParser) generate(l lex) (RR, bool) { } // _BLANK - l, ok := zp.c.Next() + l, ok = zp.c.Next() if !ok || l.value != zBlank { return zp.setParseError("garbage after $GENERATE range", l) } @@ -116,7 +116,7 @@ func (r *generateReader) parseError(msg string, end int) *ParseError { l.token = r.s[r.si-1 : end] l.column += r.si // l.column starts one zBLANK before r.s - return &ParseError{r.file, msg, l} + return &ParseError{file: r.file, err: msg, lex: l} } func (r *generateReader) Read(p []byte) (int, error) { @@ -211,15 +211,16 @@ func (r *generateReader) ReadByte() (byte, error) { func modToPrintf(s string) (string, int64, string) { // Modifier is { offset [ ,width [ ,base ] ] } - provide default // values for optional width and type, if necessary. - var offStr, widthStr, base string - switch xs := strings.Split(s, ","); len(xs) { - case 1: - offStr, widthStr, base = xs[0], "0", "d" - case 2: - offStr, widthStr, base = xs[0], xs[1], "d" - case 3: - offStr, widthStr, base = xs[0], xs[1], xs[2] - default: + offStr, s, ok0 := strings.Cut(s, ",") + widthStr, s, ok1 := strings.Cut(s, ",") + base, _, ok2 := strings.Cut(s, ",") + if !ok0 { + widthStr = "0" + } + if !ok1 { + base = "d" + } + if ok2 { return "", 0, "bad modifier in $GENERATE" } @@ -234,8 +235,8 @@ func modToPrintf(s string) (string, int64, string) { return "", 0, "bad offset in $GENERATE" } - width, err := strconv.ParseInt(widthStr, 10, 64) - if err != nil || width < 0 || width > 255 { + width, err := strconv.ParseUint(widthStr, 10, 8) + if err != nil { return "", 0, "bad width in $GENERATE" } diff --git a/vendor/github.com/miekg/dns/listen_no_reuseport.go b/vendor/github.com/miekg/dns/listen_no_reuseport.go index 6ed50f86b..8cebb2f17 100644 --- a/vendor/github.com/miekg/dns/listen_no_reuseport.go +++ b/vendor/github.com/miekg/dns/listen_no_reuseport.go @@ -7,16 +7,18 @@ import "net" const supportsReusePort = false -func listenTCP(network, addr string, reuseport bool) (net.Listener, error) { - if reuseport { +func listenTCP(network, addr string, reuseport, reuseaddr bool) (net.Listener, error) { + if reuseport || reuseaddr { // TODO(tmthrgd): return an error? } return net.Listen(network, addr) } -func listenUDP(network, addr string, reuseport bool) (net.PacketConn, error) { - if reuseport { +const supportsReuseAddr = false + +func listenUDP(network, addr string, reuseport, reuseaddr bool) (net.PacketConn, error) { + if reuseport || reuseaddr { // TODO(tmthrgd): return an error? } diff --git a/vendor/github.com/miekg/dns/listen_reuseport.go b/vendor/github.com/miekg/dns/listen_reuseport.go index 89bac9034..41326f20b 100644 --- a/vendor/github.com/miekg/dns/listen_reuseport.go +++ b/vendor/github.com/miekg/dns/listen_reuseport.go @@ -25,19 +25,41 @@ func reuseportControl(network, address string, c syscall.RawConn) error { return opErr } -func listenTCP(network, addr string, reuseport bool) (net.Listener, error) { +const supportsReuseAddr = true + +func reuseaddrControl(network, address string, c syscall.RawConn) error { + var opErr error + err := c.Control(func(fd uintptr) { + opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) + }) + if err != nil { + return err + } + + return opErr +} + +func listenTCP(network, addr string, reuseport, reuseaddr bool) (net.Listener, error) { var lc net.ListenConfig - if reuseport { + switch { + case reuseaddr && reuseport: + case reuseport: lc.Control = reuseportControl + case reuseaddr: + lc.Control = reuseaddrControl } return lc.Listen(context.Background(), network, addr) } -func listenUDP(network, addr string, reuseport bool) (net.PacketConn, error) { +func listenUDP(network, addr string, reuseport, reuseaddr bool) (net.PacketConn, error) { var lc net.ListenConfig - if reuseport { + switch { + case reuseaddr && reuseport: + case reuseport: lc.Control = reuseportControl + case reuseaddr: + lc.Control = reuseaddrControl } return lc.ListenPacket(context.Background(), network, addr) diff --git a/vendor/github.com/miekg/dns/msg.go b/vendor/github.com/miekg/dns/msg.go index d5049a4f9..8294d0395 100644 --- a/vendor/github.com/miekg/dns/msg.go +++ b/vendor/github.com/miekg/dns/msg.go @@ -501,30 +501,28 @@ func packTxtString(s string, msg []byte, offset int) (int, error) { return offset, nil } -func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) { - if offset >= len(msg) || len(s) > len(tmp) { +func packOctetString(s string, msg []byte, offset int) (int, error) { + if offset >= len(msg) || len(s) > 256*4+1 { return offset, ErrBuf } - bs := tmp[:len(s)] - copy(bs, s) - for i := 0; i < len(bs); i++ { + for i := 0; i < len(s); i++ { if len(msg) <= offset { return offset, ErrBuf } - if bs[i] == '\\' { + if s[i] == '\\' { i++ - if i == len(bs) { + if i == len(s) { break } // check for \DDD - if isDDD(bs[i:]) { - msg[offset] = dddToByte(bs[i:]) + if isDDD(s[i:]) { + msg[offset] = dddToByte(s[i:]) i += 2 } else { - msg[offset] = bs[i] + msg[offset] = s[i] } } else { - msg[offset] = bs[i] + msg[offset] = s[i] } offset++ } @@ -896,23 +894,38 @@ func (dns *Msg) String() string { return " MsgHdr" } s := dns.MsgHdr.String() + " " - s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", " - s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", " - s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", " - s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n" + if dns.MsgHdr.Opcode == OpcodeUpdate { + s += "ZONE: " + strconv.Itoa(len(dns.Question)) + ", " + s += "PREREQ: " + strconv.Itoa(len(dns.Answer)) + ", " + s += "UPDATE: " + strconv.Itoa(len(dns.Ns)) + ", " + s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n" + } else { + s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", " + s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", " + s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", " + s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n" + } opt := dns.IsEdns0() if opt != nil { // OPT PSEUDOSECTION s += opt.String() + "\n" } if len(dns.Question) > 0 { - s += "\n;; QUESTION SECTION:\n" + if dns.MsgHdr.Opcode == OpcodeUpdate { + s += "\n;; ZONE SECTION:\n" + } else { + s += "\n;; QUESTION SECTION:\n" + } for _, r := range dns.Question { s += r.String() + "\n" } } if len(dns.Answer) > 0 { - s += "\n;; ANSWER SECTION:\n" + if dns.MsgHdr.Opcode == OpcodeUpdate { + s += "\n;; PREREQUISITE SECTION:\n" + } else { + s += "\n;; ANSWER SECTION:\n" + } for _, r := range dns.Answer { if r != nil { s += r.String() + "\n" @@ -920,7 +933,11 @@ func (dns *Msg) String() string { } } if len(dns.Ns) > 0 { - s += "\n;; AUTHORITY SECTION:\n" + if dns.MsgHdr.Opcode == OpcodeUpdate { + s += "\n;; UPDATE SECTION:\n" + } else { + s += "\n;; AUTHORITY SECTION:\n" + } for _, r := range dns.Ns { if r != nil { s += r.String() + "\n" diff --git a/vendor/github.com/miekg/dns/msg_helpers.go b/vendor/github.com/miekg/dns/msg_helpers.go index 8582fc0ad..acec21f7d 100644 --- a/vendor/github.com/miekg/dns/msg_helpers.go +++ b/vendor/github.com/miekg/dns/msg_helpers.go @@ -20,9 +20,7 @@ func unpackDataA(msg []byte, off int) (net.IP, int, error) { if off+net.IPv4len > len(msg) { return nil, len(msg), &Error{err: "overflow unpacking a"} } - a := append(make(net.IP, 0, net.IPv4len), msg[off:off+net.IPv4len]...) - off += net.IPv4len - return a, off, nil + return cloneSlice(msg[off : off+net.IPv4len]), off + net.IPv4len, nil } func packDataA(a net.IP, msg []byte, off int) (int, error) { @@ -47,9 +45,7 @@ func unpackDataAAAA(msg []byte, off int) (net.IP, int, error) { if off+net.IPv6len > len(msg) { return nil, len(msg), &Error{err: "overflow unpacking aaaa"} } - aaaa := append(make(net.IP, 0, net.IPv6len), msg[off:off+net.IPv6len]...) - off += net.IPv6len - return aaaa, off, nil + return cloneSlice(msg[off : off+net.IPv6len]), off + net.IPv6len, nil } func packDataAAAA(aaaa net.IP, msg []byte, off int) (int, error) { @@ -410,29 +406,24 @@ func packStringTxt(s []string, msg []byte, off int) (int, error) { func unpackDataOpt(msg []byte, off int) ([]EDNS0, int, error) { var edns []EDNS0 -Option: - var code uint16 - if off+4 > len(msg) { - return nil, len(msg), &Error{err: "overflow unpacking opt"} - } - code = binary.BigEndian.Uint16(msg[off:]) - off += 2 - optlen := binary.BigEndian.Uint16(msg[off:]) - off += 2 - if off+int(optlen) > len(msg) { - return nil, len(msg), &Error{err: "overflow unpacking opt"} - } - e := makeDataOpt(code) - if err := e.unpack(msg[off : off+int(optlen)]); err != nil { - return nil, len(msg), err - } - edns = append(edns, e) - off += int(optlen) - - if off < len(msg) { - goto Option + for off < len(msg) { + if off+4 > len(msg) { + return nil, len(msg), &Error{err: "overflow unpacking opt"} + } + code := binary.BigEndian.Uint16(msg[off:]) + off += 2 + optlen := binary.BigEndian.Uint16(msg[off:]) + off += 2 + if off+int(optlen) > len(msg) { + return nil, len(msg), &Error{err: "overflow unpacking opt"} + } + opt := makeDataOpt(code) + if err := opt.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, opt) + off += int(optlen) } - return edns, off, nil } @@ -461,8 +452,7 @@ func unpackStringOctet(msg []byte, off int) (string, int, error) { } func packStringOctet(s string, msg []byte, off int) (int, error) { - txtTmp := make([]byte, 256*4+1) - off, err := packOctetString(s, msg, off, txtTmp) + off, err := packOctetString(s, msg, off) if err != nil { return len(msg), err } diff --git a/vendor/github.com/miekg/dns/privaterr.go b/vendor/github.com/miekg/dns/privaterr.go index d256b652e..350ea5a47 100644 --- a/vendor/github.com/miekg/dns/privaterr.go +++ b/vendor/github.com/miekg/dns/privaterr.go @@ -84,7 +84,7 @@ Fetch: err := r.Data.Parse(text) if err != nil { - return &ParseError{"", err.Error(), l} + return &ParseError{wrappedErr: err, lex: l} } return nil diff --git a/vendor/github.com/miekg/dns/scan.go b/vendor/github.com/miekg/dns/scan.go index 57be98827..1f92ae421 100644 --- a/vendor/github.com/miekg/dns/scan.go +++ b/vendor/github.com/miekg/dns/scan.go @@ -4,19 +4,21 @@ import ( "bufio" "fmt" "io" + "io/fs" "os" + "path" "path/filepath" "strconv" "strings" ) -const maxTok = 2048 // Largest token we can return. +const maxTok = 512 // Token buffer start size, and growth size amount. // The maximum depth of $INCLUDE directives supported by the // ZoneParser API. const maxIncludeDepth = 7 -// Tokinize a RFC 1035 zone file. The tokenizer will normalize it: +// Tokenize a RFC 1035 zone file. The tokenizer will normalize it: // * Add ownernames if they are left blank; // * Suppress sequences of spaces; // * Make each RR fit on one line (_NEWLINE is send as last) @@ -64,20 +66,26 @@ const ( // ParseError is a parsing error. It contains the parse error and the location in the io.Reader // where the error occurred. type ParseError struct { - file string - err string - lex lex + file string + err string + wrappedErr error + lex lex } func (e *ParseError) Error() (s string) { if e.file != "" { s = e.file + ": " } + if e.err == "" && e.wrappedErr != nil { + e.err = e.wrappedErr.Error() + } s += "dns: " + e.err + ": " + strconv.QuoteToASCII(e.lex.token) + " at line: " + strconv.Itoa(e.lex.line) + ":" + strconv.Itoa(e.lex.column) return } +func (e *ParseError) Unwrap() error { return e.wrappedErr } + type lex struct { token string // text of the token err bool // when true, token text has lexer error @@ -168,8 +176,9 @@ type ZoneParser struct { // sub is used to parse $INCLUDE files and $GENERATE directives. // Next, by calling subNext, forwards the resulting RRs from this // sub parser to the calling code. - sub *ZoneParser - osFile *os.File + sub *ZoneParser + r io.Reader + fsys fs.FS includeDepth uint8 @@ -188,7 +197,7 @@ func NewZoneParser(r io.Reader, origin, file string) *ZoneParser { if origin != "" { origin = Fqdn(origin) if _, ok := IsDomainName(origin); !ok { - pe = &ParseError{file, "bad initial origin name", lex{}} + pe = &ParseError{file: file, err: "bad initial origin name"} } } @@ -220,6 +229,24 @@ func (zp *ZoneParser) SetIncludeAllowed(v bool) { zp.includeAllowed = v } +// SetIncludeFS provides an [fs.FS] to use when looking for the target of +// $INCLUDE directives. ($INCLUDE must still be enabled separately by calling +// [ZoneParser.SetIncludeAllowed].) If fsys is nil, [os.Open] will be used. +// +// When fsys is an on-disk FS, the ability of $INCLUDE to reach files from +// outside its root directory depends upon the FS implementation. For +// instance, [os.DirFS] will refuse to open paths like "../../etc/passwd", +// however it will still follow links which may point anywhere on the system. +// +// FS paths are slash-separated on all systems, even Windows. $INCLUDE paths +// containing other characters such as backslash and colon may be accepted as +// valid, but those characters will never be interpreted by an FS +// implementation as path element separators. See [fs.ValidPath] for more +// details. +func (zp *ZoneParser) SetIncludeFS(fsys fs.FS) { + zp.fsys = fsys +} + // Err returns the first non-EOF error that was encountered by the // ZoneParser. func (zp *ZoneParser) Err() error { @@ -237,7 +264,7 @@ func (zp *ZoneParser) Err() error { } func (zp *ZoneParser) setParseError(err string, l lex) (RR, bool) { - zp.parseErr = &ParseError{zp.file, err, l} + zp.parseErr = &ParseError{file: zp.file, err: err, lex: l} return nil, false } @@ -260,9 +287,11 @@ func (zp *ZoneParser) subNext() (RR, bool) { return rr, true } - if zp.sub.osFile != nil { - zp.sub.osFile.Close() - zp.sub.osFile = nil + if zp.sub.r != nil { + if c, ok := zp.sub.r.(io.Closer); ok { + c.Close() + } + zp.sub.r = nil } if zp.sub.Err() != nil { @@ -402,24 +431,44 @@ func (zp *ZoneParser) Next() (RR, bool) { // Start with the new file includePath := l.token - if !filepath.IsAbs(includePath) { - includePath = filepath.Join(filepath.Dir(zp.file), includePath) - } + var r1 io.Reader + var e1 error + if zp.fsys != nil { + // fs.FS always uses / as separator, even on Windows, so use + // path instead of filepath here: + if !path.IsAbs(includePath) { + includePath = path.Join(path.Dir(zp.file), includePath) + } - r1, e1 := os.Open(includePath) + // os.DirFS, and probably others, expect all paths to be + // relative, so clean the path and remove leading / if + // present: + includePath = strings.TrimLeft(path.Clean(includePath), "/") + + r1, e1 = zp.fsys.Open(includePath) + } else { + if !filepath.IsAbs(includePath) { + includePath = filepath.Join(filepath.Dir(zp.file), includePath) + } + r1, e1 = os.Open(includePath) + } if e1 != nil { var as string - if !filepath.IsAbs(l.token) { + if includePath != l.token { as = fmt.Sprintf(" as `%s'", includePath) } - - msg := fmt.Sprintf("failed to open `%s'%s: %v", l.token, as, e1) - return zp.setParseError(msg, l) + zp.parseErr = &ParseError{ + file: zp.file, + wrappedErr: fmt.Errorf("failed to open `%s'%s: %w", l.token, as, e1), + lex: l, + } + return nil, false } zp.sub = NewZoneParser(r1, neworigin, includePath) - zp.sub.defttl, zp.sub.includeDepth, zp.sub.osFile = zp.defttl, zp.includeDepth+1, r1 + zp.sub.defttl, zp.sub.includeDepth, zp.sub.r = zp.defttl, zp.includeDepth+1, r1 zp.sub.SetIncludeAllowed(true) + zp.sub.SetIncludeFS(zp.fsys) return zp.subNext() case zExpectDirTTLBl: if l.value != zBlank { @@ -605,8 +654,6 @@ func (zp *ZoneParser) Next() (RR, bool) { if !isPrivate && zp.c.Peek().token == "" { // This is a dynamic update rr. - // TODO(tmthrgd): Previously slurpRemainder was only called - // for certain RR types, which may have been important. if err := slurpRemainder(zp.c); err != nil { return zp.setParseError(err.err, err.lex) } @@ -765,8 +812,8 @@ func (zl *zlexer) Next() (lex, bool) { } var ( - str [maxTok]byte // Hold string text - com [maxTok]byte // Hold comment text + str = make([]byte, maxTok) // Hold string text + com = make([]byte, maxTok) // Hold comment text stri int // Offset in str (0 means empty) comi int // Offset in com (0 means empty) @@ -785,14 +832,12 @@ func (zl *zlexer) Next() (lex, bool) { l.line, l.column = zl.line, zl.column if stri >= len(str) { - l.token = "token length insufficient for parsing" - l.err = true - return *l, true + // if buffer length is insufficient, increase it. + str = append(str[:], make([]byte, maxTok)...) } if comi >= len(com) { - l.token = "comment length insufficient for parsing" - l.err = true - return *l, true + // if buffer length is insufficient, increase it. + com = append(com[:], make([]byte, maxTok)...) } switch x { @@ -816,7 +861,7 @@ func (zl *zlexer) Next() (lex, bool) { if stri == 0 { // Space directly in the beginning, handled in the grammar } else if zl.owner { - // If we have a string and its the first, make it an owner + // If we have a string and it's the first, make it an owner l.value = zOwner l.token = string(str[:stri]) @@ -1218,42 +1263,34 @@ func stringToCm(token string) (e, m uint8, ok bool) { if token[len(token)-1] == 'M' || token[len(token)-1] == 'm' { token = token[0 : len(token)-1] } - s := strings.SplitN(token, ".", 2) - var meters, cmeters, val int - var err error - switch len(s) { - case 2: - if cmeters, err = strconv.Atoi(s[1]); err != nil { - return - } + + var ( + meters, cmeters, val int + err error + ) + mStr, cmStr, hasCM := strings.Cut(token, ".") + if hasCM { // There's no point in having more than 2 digits in this part, and would rather make the implementation complicated ('123' should be treated as '12'). // So we simply reject it. // We also make sure the first character is a digit to reject '+-' signs. - if len(s[1]) > 2 || s[1][0] < '0' || s[1][0] > '9' { + cmeters, err = strconv.Atoi(cmStr) + if err != nil || len(cmStr) > 2 || cmStr[0] < '0' || cmStr[0] > '9' { return } - if len(s[1]) == 1 { + if len(cmStr) == 1 { // 'nn.1' must be treated as 'nn-meters and 10cm, not 1cm. cmeters *= 10 } - if s[0] == "" { - // This will allow omitting the 'meter' part, like .01 (meaning 0.01m = 1cm). - break - } - fallthrough - case 1: - if meters, err = strconv.Atoi(s[0]); err != nil { - return - } + } + // This slighly ugly condition will allow omitting the 'meter' part, like .01 (meaning 0.01m = 1cm). + if !hasCM || mStr != "" { + meters, err = strconv.Atoi(mStr) // RFC1876 states the max value is 90000000.00. The latter two conditions enforce it. - if s[0][0] < '0' || s[0][0] > '9' || meters > 90000000 || (meters == 90000000 && cmeters != 0) { + if err != nil || mStr[0] < '0' || mStr[0] > '9' || meters > 90000000 || (meters == 90000000 && cmeters != 0) { return } - case 0: - // huh? - return 0, 0, false } - ok = true + if meters > 0 { e = 2 val = meters @@ -1265,8 +1302,7 @@ func stringToCm(token string) (e, m uint8, ok bool) { e++ val /= 10 } - m = uint8(val) - return + return e, uint8(val), true } func toAbsoluteName(name, origin string) (absolute string, ok bool) { @@ -1339,12 +1375,12 @@ func slurpRemainder(c *zlexer) *ParseError { case zBlank: l, _ = c.Next() if l.value != zNewline && l.value != zEOF { - return &ParseError{"", "garbage after rdata", l} + return &ParseError{err: "garbage after rdata", lex: l} } case zNewline: case zEOF: default: - return &ParseError{"", "garbage after rdata", l} + return &ParseError{err: "garbage after rdata", lex: l} } return nil } @@ -1353,16 +1389,16 @@ func slurpRemainder(c *zlexer) *ParseError { // Used for NID and L64 record. func stringToNodeID(l lex) (uint64, *ParseError) { if len(l.token) < 19 { - return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l} + return 0, &ParseError{file: l.token, err: "bad NID/L64 NodeID/Locator64", lex: l} } // There must be three colons at fixes positions, if not its a parse error if l.token[4] != ':' && l.token[9] != ':' && l.token[14] != ':' { - return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l} + return 0, &ParseError{file: l.token, err: "bad NID/L64 NodeID/Locator64", lex: l} } s := l.token[0:4] + l.token[5:9] + l.token[10:14] + l.token[15:19] u, err := strconv.ParseUint(s, 16, 64) if err != nil { - return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l} + return 0, &ParseError{file: l.token, err: "bad NID/L64 NodeID/Locator64", lex: l} } return u, nil } diff --git a/vendor/github.com/miekg/dns/scan_rr.go b/vendor/github.com/miekg/dns/scan_rr.go index 2d44a3987..1a90c61f8 100644 --- a/vendor/github.com/miekg/dns/scan_rr.go +++ b/vendor/github.com/miekg/dns/scan_rr.go @@ -1,9 +1,9 @@ package dns import ( - "bytes" "encoding/base64" "errors" + "fmt" "net" "strconv" "strings" @@ -12,23 +12,23 @@ import ( // A remainder of the rdata with embedded spaces, return the parsed string (sans the spaces) // or an error func endingToString(c *zlexer, errstr string) (string, *ParseError) { - var buffer bytes.Buffer + var s strings.Builder l, _ := c.Next() // zString for l.value != zNewline && l.value != zEOF { if l.err { - return buffer.String(), &ParseError{"", errstr, l} + return s.String(), &ParseError{err: errstr, lex: l} } switch l.value { case zString: - buffer.WriteString(l.token) + s.WriteString(l.token) case zBlank: // Ok default: - return "", &ParseError{"", errstr, l} + return "", &ParseError{err: errstr, lex: l} } l, _ = c.Next() } - return buffer.String(), nil + return s.String(), nil } // A remainder of the rdata with embedded spaces, split on unquoted whitespace @@ -37,7 +37,7 @@ func endingToTxtSlice(c *zlexer, errstr string) ([]string, *ParseError) { // Get the remaining data until we see a zNewline l, _ := c.Next() if l.err { - return nil, &ParseError{"", errstr, l} + return nil, &ParseError{err: errstr, lex: l} } // Build the slice @@ -46,7 +46,7 @@ func endingToTxtSlice(c *zlexer, errstr string) ([]string, *ParseError) { empty := false for l.value != zNewline && l.value != zEOF { if l.err { - return nil, &ParseError{"", errstr, l} + return nil, &ParseError{err: errstr, lex: l} } switch l.value { case zString: @@ -73,7 +73,7 @@ func endingToTxtSlice(c *zlexer, errstr string) ([]string, *ParseError) { case zBlank: if quote { // zBlank can only be seen in between txt parts. - return nil, &ParseError{"", errstr, l} + return nil, &ParseError{err: errstr, lex: l} } case zQuote: if empty && quote { @@ -82,13 +82,13 @@ func endingToTxtSlice(c *zlexer, errstr string) ([]string, *ParseError) { quote = !quote empty = true default: - return nil, &ParseError{"", errstr, l} + return nil, &ParseError{err: errstr, lex: l} } l, _ = c.Next() } if quote { - return nil, &ParseError{"", errstr, l} + return nil, &ParseError{err: errstr, lex: l} } return s, nil @@ -103,7 +103,7 @@ func (rr *A) parse(c *zlexer, o string) *ParseError { // IPv4. isIPv4 := !strings.Contains(l.token, ":") if rr.A == nil || !isIPv4 || l.err { - return &ParseError{"", "bad A A", l} + return &ParseError{err: "bad A A", lex: l} } return slurpRemainder(c) } @@ -115,7 +115,7 @@ func (rr *AAAA) parse(c *zlexer, o string) *ParseError { // addresses cannot include ":". isIPv6 := strings.Contains(l.token, ":") if rr.AAAA == nil || !isIPv6 || l.err { - return &ParseError{"", "bad AAAA AAAA", l} + return &ParseError{err: "bad AAAA AAAA", lex: l} } return slurpRemainder(c) } @@ -124,7 +124,7 @@ func (rr *NS) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad NS Ns", l} + return &ParseError{err: "bad NS Ns", lex: l} } rr.Ns = name return slurpRemainder(c) @@ -134,7 +134,7 @@ func (rr *PTR) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad PTR Ptr", l} + return &ParseError{err: "bad PTR Ptr", lex: l} } rr.Ptr = name return slurpRemainder(c) @@ -144,7 +144,7 @@ func (rr *NSAPPTR) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad NSAP-PTR Ptr", l} + return &ParseError{err: "bad NSAP-PTR Ptr", lex: l} } rr.Ptr = name return slurpRemainder(c) @@ -154,7 +154,7 @@ func (rr *RP) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() mbox, mboxOk := toAbsoluteName(l.token, o) if l.err || !mboxOk { - return &ParseError{"", "bad RP Mbox", l} + return &ParseError{err: "bad RP Mbox", lex: l} } rr.Mbox = mbox @@ -164,7 +164,7 @@ func (rr *RP) parse(c *zlexer, o string) *ParseError { txt, txtOk := toAbsoluteName(l.token, o) if l.err || !txtOk { - return &ParseError{"", "bad RP Txt", l} + return &ParseError{err: "bad RP Txt", lex: l} } rr.Txt = txt @@ -175,7 +175,7 @@ func (rr *MR) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad MR Mr", l} + return &ParseError{err: "bad MR Mr", lex: l} } rr.Mr = name return slurpRemainder(c) @@ -185,7 +185,7 @@ func (rr *MB) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad MB Mb", l} + return &ParseError{err: "bad MB Mb", lex: l} } rr.Mb = name return slurpRemainder(c) @@ -195,7 +195,7 @@ func (rr *MG) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad MG Mg", l} + return &ParseError{err: "bad MG Mg", lex: l} } rr.Mg = name return slurpRemainder(c) @@ -220,6 +220,29 @@ func (rr *HINFO) parse(c *zlexer, o string) *ParseError { rr.Cpu = chunks[0] rr.Os = strings.Join(chunks[1:], " ") + return nil +} + +// according to RFC 1183 the parsing is identical to HINFO, so just use that code. +func (rr *ISDN) parse(c *zlexer, o string) *ParseError { + chunks, e := endingToTxtSlice(c, "bad ISDN Fields") + if e != nil { + return e + } + + if ln := len(chunks); ln == 0 { + return nil + } else if ln == 1 { + // Can we split it? + if out := strings.Fields(chunks[0]); len(out) > 1 { + chunks = out + } else { + chunks = append(chunks, "") + } + } + + rr.Address = chunks[0] + rr.SubAddress = strings.Join(chunks[1:], " ") return nil } @@ -228,7 +251,7 @@ func (rr *MINFO) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() rmail, rmailOk := toAbsoluteName(l.token, o) if l.err || !rmailOk { - return &ParseError{"", "bad MINFO Rmail", l} + return &ParseError{err: "bad MINFO Rmail", lex: l} } rr.Rmail = rmail @@ -238,7 +261,7 @@ func (rr *MINFO) parse(c *zlexer, o string) *ParseError { email, emailOk := toAbsoluteName(l.token, o) if l.err || !emailOk { - return &ParseError{"", "bad MINFO Email", l} + return &ParseError{err: "bad MINFO Email", lex: l} } rr.Email = email @@ -249,7 +272,7 @@ func (rr *MF) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad MF Mf", l} + return &ParseError{err: "bad MF Mf", lex: l} } rr.Mf = name return slurpRemainder(c) @@ -259,7 +282,7 @@ func (rr *MD) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad MD Md", l} + return &ParseError{err: "bad MD Md", lex: l} } rr.Md = name return slurpRemainder(c) @@ -269,7 +292,7 @@ func (rr *MX) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad MX Pref", l} + return &ParseError{err: "bad MX Pref", lex: l} } rr.Preference = uint16(i) @@ -279,7 +302,7 @@ func (rr *MX) parse(c *zlexer, o string) *ParseError { name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad MX Mx", l} + return &ParseError{err: "bad MX Mx", lex: l} } rr.Mx = name @@ -290,7 +313,7 @@ func (rr *RT) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil { - return &ParseError{"", "bad RT Preference", l} + return &ParseError{err: "bad RT Preference", lex: l} } rr.Preference = uint16(i) @@ -300,7 +323,7 @@ func (rr *RT) parse(c *zlexer, o string) *ParseError { name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad RT Host", l} + return &ParseError{err: "bad RT Host", lex: l} } rr.Host = name @@ -311,7 +334,7 @@ func (rr *AFSDB) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad AFSDB Subtype", l} + return &ParseError{err: "bad AFSDB Subtype", lex: l} } rr.Subtype = uint16(i) @@ -321,7 +344,7 @@ func (rr *AFSDB) parse(c *zlexer, o string) *ParseError { name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad AFSDB Hostname", l} + return &ParseError{err: "bad AFSDB Hostname", lex: l} } rr.Hostname = name return slurpRemainder(c) @@ -330,7 +353,7 @@ func (rr *AFSDB) parse(c *zlexer, o string) *ParseError { func (rr *X25) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() if l.err { - return &ParseError{"", "bad X25 PSDNAddress", l} + return &ParseError{err: "bad X25 PSDNAddress", lex: l} } rr.PSDNAddress = l.token return slurpRemainder(c) @@ -340,7 +363,7 @@ func (rr *KX) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad KX Pref", l} + return &ParseError{err: "bad KX Pref", lex: l} } rr.Preference = uint16(i) @@ -350,7 +373,7 @@ func (rr *KX) parse(c *zlexer, o string) *ParseError { name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad KX Exchanger", l} + return &ParseError{err: "bad KX Exchanger", lex: l} } rr.Exchanger = name return slurpRemainder(c) @@ -360,7 +383,7 @@ func (rr *CNAME) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad CNAME Target", l} + return &ParseError{err: "bad CNAME Target", lex: l} } rr.Target = name return slurpRemainder(c) @@ -370,7 +393,7 @@ func (rr *DNAME) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad DNAME Target", l} + return &ParseError{err: "bad DNAME Target", lex: l} } rr.Target = name return slurpRemainder(c) @@ -380,7 +403,7 @@ func (rr *SOA) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() ns, nsOk := toAbsoluteName(l.token, o) if l.err || !nsOk { - return &ParseError{"", "bad SOA Ns", l} + return &ParseError{err: "bad SOA Ns", lex: l} } rr.Ns = ns @@ -390,7 +413,7 @@ func (rr *SOA) parse(c *zlexer, o string) *ParseError { mbox, mboxOk := toAbsoluteName(l.token, o) if l.err || !mboxOk { - return &ParseError{"", "bad SOA Mbox", l} + return &ParseError{err: "bad SOA Mbox", lex: l} } rr.Mbox = mbox @@ -403,16 +426,16 @@ func (rr *SOA) parse(c *zlexer, o string) *ParseError { for i := 0; i < 5; i++ { l, _ = c.Next() if l.err { - return &ParseError{"", "bad SOA zone parameter", l} + return &ParseError{err: "bad SOA zone parameter", lex: l} } if j, err := strconv.ParseUint(l.token, 10, 32); err != nil { if i == 0 { // Serial must be a number - return &ParseError{"", "bad SOA zone parameter", l} + return &ParseError{err: "bad SOA zone parameter", lex: l} } // We allow other fields to be unitful duration strings if v, ok = stringToTTL(l.token); !ok { - return &ParseError{"", "bad SOA zone parameter", l} + return &ParseError{err: "bad SOA zone parameter", lex: l} } } else { @@ -442,7 +465,7 @@ func (rr *SRV) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad SRV Priority", l} + return &ParseError{err: "bad SRV Priority", lex: l} } rr.Priority = uint16(i) @@ -450,7 +473,7 @@ func (rr *SRV) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() // zString i, e1 := strconv.ParseUint(l.token, 10, 16) if e1 != nil || l.err { - return &ParseError{"", "bad SRV Weight", l} + return &ParseError{err: "bad SRV Weight", lex: l} } rr.Weight = uint16(i) @@ -458,7 +481,7 @@ func (rr *SRV) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() // zString i, e2 := strconv.ParseUint(l.token, 10, 16) if e2 != nil || l.err { - return &ParseError{"", "bad SRV Port", l} + return &ParseError{err: "bad SRV Port", lex: l} } rr.Port = uint16(i) @@ -468,7 +491,7 @@ func (rr *SRV) parse(c *zlexer, o string) *ParseError { name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad SRV Target", l} + return &ParseError{err: "bad SRV Target", lex: l} } rr.Target = name return slurpRemainder(c) @@ -478,7 +501,7 @@ func (rr *NAPTR) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad NAPTR Order", l} + return &ParseError{err: "bad NAPTR Order", lex: l} } rr.Order = uint16(i) @@ -486,7 +509,7 @@ func (rr *NAPTR) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() // zString i, e1 := strconv.ParseUint(l.token, 10, 16) if e1 != nil || l.err { - return &ParseError{"", "bad NAPTR Preference", l} + return &ParseError{err: "bad NAPTR Preference", lex: l} } rr.Preference = uint16(i) @@ -494,57 +517,57 @@ func (rr *NAPTR) parse(c *zlexer, o string) *ParseError { c.Next() // zBlank l, _ = c.Next() // _QUOTE if l.value != zQuote { - return &ParseError{"", "bad NAPTR Flags", l} + return &ParseError{err: "bad NAPTR Flags", lex: l} } l, _ = c.Next() // Either String or Quote if l.value == zString { rr.Flags = l.token l, _ = c.Next() // _QUOTE if l.value != zQuote { - return &ParseError{"", "bad NAPTR Flags", l} + return &ParseError{err: "bad NAPTR Flags", lex: l} } } else if l.value == zQuote { rr.Flags = "" } else { - return &ParseError{"", "bad NAPTR Flags", l} + return &ParseError{err: "bad NAPTR Flags", lex: l} } // Service c.Next() // zBlank l, _ = c.Next() // _QUOTE if l.value != zQuote { - return &ParseError{"", "bad NAPTR Service", l} + return &ParseError{err: "bad NAPTR Service", lex: l} } l, _ = c.Next() // Either String or Quote if l.value == zString { rr.Service = l.token l, _ = c.Next() // _QUOTE if l.value != zQuote { - return &ParseError{"", "bad NAPTR Service", l} + return &ParseError{err: "bad NAPTR Service", lex: l} } } else if l.value == zQuote { rr.Service = "" } else { - return &ParseError{"", "bad NAPTR Service", l} + return &ParseError{err: "bad NAPTR Service", lex: l} } // Regexp c.Next() // zBlank l, _ = c.Next() // _QUOTE if l.value != zQuote { - return &ParseError{"", "bad NAPTR Regexp", l} + return &ParseError{err: "bad NAPTR Regexp", lex: l} } l, _ = c.Next() // Either String or Quote if l.value == zString { rr.Regexp = l.token l, _ = c.Next() // _QUOTE if l.value != zQuote { - return &ParseError{"", "bad NAPTR Regexp", l} + return &ParseError{err: "bad NAPTR Regexp", lex: l} } } else if l.value == zQuote { rr.Regexp = "" } else { - return &ParseError{"", "bad NAPTR Regexp", l} + return &ParseError{err: "bad NAPTR Regexp", lex: l} } // After quote no space?? @@ -554,7 +577,7 @@ func (rr *NAPTR) parse(c *zlexer, o string) *ParseError { name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad NAPTR Replacement", l} + return &ParseError{err: "bad NAPTR Replacement", lex: l} } rr.Replacement = name return slurpRemainder(c) @@ -564,7 +587,7 @@ func (rr *TALINK) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() previousName, previousNameOk := toAbsoluteName(l.token, o) if l.err || !previousNameOk { - return &ParseError{"", "bad TALINK PreviousName", l} + return &ParseError{err: "bad TALINK PreviousName", lex: l} } rr.PreviousName = previousName @@ -574,7 +597,7 @@ func (rr *TALINK) parse(c *zlexer, o string) *ParseError { nextName, nextNameOk := toAbsoluteName(l.token, o) if l.err || !nextNameOk { - return &ParseError{"", "bad TALINK NextName", l} + return &ParseError{err: "bad TALINK NextName", lex: l} } rr.NextName = nextName @@ -592,7 +615,7 @@ func (rr *LOC) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 32) if e != nil || l.err || i > 90 { - return &ParseError{"", "bad LOC Latitude", l} + return &ParseError{err: "bad LOC Latitude", lex: l} } rr.Latitude = 1000 * 60 * 60 * uint32(i) @@ -603,7 +626,7 @@ func (rr *LOC) parse(c *zlexer, o string) *ParseError { goto East } if i, err := strconv.ParseUint(l.token, 10, 32); err != nil || l.err || i > 59 { - return &ParseError{"", "bad LOC Latitude minutes", l} + return &ParseError{err: "bad LOC Latitude minutes", lex: l} } else { rr.Latitude += 1000 * 60 * uint32(i) } @@ -611,7 +634,7 @@ func (rr *LOC) parse(c *zlexer, o string) *ParseError { c.Next() // zBlank l, _ = c.Next() if i, err := strconv.ParseFloat(l.token, 64); err != nil || l.err || i < 0 || i >= 60 { - return &ParseError{"", "bad LOC Latitude seconds", l} + return &ParseError{err: "bad LOC Latitude seconds", lex: l} } else { rr.Latitude += uint32(1000 * i) } @@ -622,14 +645,14 @@ func (rr *LOC) parse(c *zlexer, o string) *ParseError { goto East } // If still alive, flag an error - return &ParseError{"", "bad LOC Latitude North/South", l} + return &ParseError{err: "bad LOC Latitude North/South", lex: l} East: // East c.Next() // zBlank l, _ = c.Next() if i, err := strconv.ParseUint(l.token, 10, 32); err != nil || l.err || i > 180 { - return &ParseError{"", "bad LOC Longitude", l} + return &ParseError{err: "bad LOC Longitude", lex: l} } else { rr.Longitude = 1000 * 60 * 60 * uint32(i) } @@ -640,14 +663,14 @@ East: goto Altitude } if i, err := strconv.ParseUint(l.token, 10, 32); err != nil || l.err || i > 59 { - return &ParseError{"", "bad LOC Longitude minutes", l} + return &ParseError{err: "bad LOC Longitude minutes", lex: l} } else { rr.Longitude += 1000 * 60 * uint32(i) } c.Next() // zBlank l, _ = c.Next() if i, err := strconv.ParseFloat(l.token, 64); err != nil || l.err || i < 0 || i >= 60 { - return &ParseError{"", "bad LOC Longitude seconds", l} + return &ParseError{err: "bad LOC Longitude seconds", lex: l} } else { rr.Longitude += uint32(1000 * i) } @@ -658,19 +681,19 @@ East: goto Altitude } // If still alive, flag an error - return &ParseError{"", "bad LOC Longitude East/West", l} + return &ParseError{err: "bad LOC Longitude East/West", lex: l} Altitude: c.Next() // zBlank l, _ = c.Next() if l.token == "" || l.err { - return &ParseError{"", "bad LOC Altitude", l} + return &ParseError{err: "bad LOC Altitude", lex: l} } if l.token[len(l.token)-1] == 'M' || l.token[len(l.token)-1] == 'm' { l.token = l.token[0 : len(l.token)-1] } if i, err := strconv.ParseFloat(l.token, 64); err != nil { - return &ParseError{"", "bad LOC Altitude", l} + return &ParseError{err: "bad LOC Altitude", lex: l} } else { rr.Altitude = uint32(i*100.0 + 10000000.0 + 0.5) } @@ -685,19 +708,19 @@ Altitude: case 0: // Size exp, m, ok := stringToCm(l.token) if !ok { - return &ParseError{"", "bad LOC Size", l} + return &ParseError{err: "bad LOC Size", lex: l} } rr.Size = exp&0x0f | m<<4&0xf0 case 1: // HorizPre exp, m, ok := stringToCm(l.token) if !ok { - return &ParseError{"", "bad LOC HorizPre", l} + return &ParseError{err: "bad LOC HorizPre", lex: l} } rr.HorizPre = exp&0x0f | m<<4&0xf0 case 2: // VertPre exp, m, ok := stringToCm(l.token) if !ok { - return &ParseError{"", "bad LOC VertPre", l} + return &ParseError{err: "bad LOC VertPre", lex: l} } rr.VertPre = exp&0x0f | m<<4&0xf0 } @@ -705,7 +728,7 @@ Altitude: case zBlank: // Ok default: - return &ParseError{"", "bad LOC Size, HorizPre or VertPre", l} + return &ParseError{err: "bad LOC Size, HorizPre or VertPre", lex: l} } l, _ = c.Next() } @@ -717,14 +740,14 @@ func (rr *HIP) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad HIP PublicKeyAlgorithm", l} + return &ParseError{err: "bad HIP PublicKeyAlgorithm", lex: l} } rr.PublicKeyAlgorithm = uint8(i) c.Next() // zBlank l, _ = c.Next() // zString if l.token == "" || l.err { - return &ParseError{"", "bad HIP Hit", l} + return &ParseError{err: "bad HIP Hit", lex: l} } rr.Hit = l.token // This can not contain spaces, see RFC 5205 Section 6. rr.HitLength = uint8(len(rr.Hit)) / 2 @@ -732,12 +755,12 @@ func (rr *HIP) parse(c *zlexer, o string) *ParseError { c.Next() // zBlank l, _ = c.Next() // zString if l.token == "" || l.err { - return &ParseError{"", "bad HIP PublicKey", l} + return &ParseError{err: "bad HIP PublicKey", lex: l} } rr.PublicKey = l.token // This cannot contain spaces decodedPK, decodedPKerr := base64.StdEncoding.DecodeString(rr.PublicKey) if decodedPKerr != nil { - return &ParseError{"", "bad HIP PublicKey", l} + return &ParseError{err: "bad HIP PublicKey", lex: l} } rr.PublicKeyLength = uint16(len(decodedPK)) @@ -749,13 +772,13 @@ func (rr *HIP) parse(c *zlexer, o string) *ParseError { case zString: name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad HIP RendezvousServers", l} + return &ParseError{err: "bad HIP RendezvousServers", lex: l} } xs = append(xs, name) case zBlank: // Ok default: - return &ParseError{"", "bad HIP RendezvousServers", l} + return &ParseError{err: "bad HIP RendezvousServers", lex: l} } l, _ = c.Next() } @@ -769,7 +792,7 @@ func (rr *CERT) parse(c *zlexer, o string) *ParseError { if v, ok := StringToCertType[l.token]; ok { rr.Type = v } else if i, err := strconv.ParseUint(l.token, 10, 16); err != nil { - return &ParseError{"", "bad CERT Type", l} + return &ParseError{err: "bad CERT Type", lex: l} } else { rr.Type = uint16(i) } @@ -777,7 +800,7 @@ func (rr *CERT) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() // zString i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad CERT KeyTag", l} + return &ParseError{err: "bad CERT KeyTag", lex: l} } rr.KeyTag = uint16(i) c.Next() // zBlank @@ -785,7 +808,7 @@ func (rr *CERT) parse(c *zlexer, o string) *ParseError { if v, ok := StringToAlgorithm[l.token]; ok { rr.Algorithm = v } else if i, err := strconv.ParseUint(l.token, 10, 8); err != nil { - return &ParseError{"", "bad CERT Algorithm", l} + return &ParseError{err: "bad CERT Algorithm", lex: l} } else { rr.Algorithm = uint8(i) } @@ -811,7 +834,7 @@ func (rr *CSYNC) parse(c *zlexer, o string) *ParseError { j, e := strconv.ParseUint(l.token, 10, 32) if e != nil { // Serial must be a number - return &ParseError{"", "bad CSYNC serial", l} + return &ParseError{err: "bad CSYNC serial", lex: l} } rr.Serial = uint32(j) @@ -821,7 +844,7 @@ func (rr *CSYNC) parse(c *zlexer, o string) *ParseError { j, e1 := strconv.ParseUint(l.token, 10, 16) if e1 != nil { // Serial must be a number - return &ParseError{"", "bad CSYNC flags", l} + return &ParseError{err: "bad CSYNC flags", lex: l} } rr.Flags = uint16(j) @@ -839,12 +862,12 @@ func (rr *CSYNC) parse(c *zlexer, o string) *ParseError { tokenUpper := strings.ToUpper(l.token) if k, ok = StringToType[tokenUpper]; !ok { if k, ok = typeToInt(l.token); !ok { - return &ParseError{"", "bad CSYNC TypeBitMap", l} + return &ParseError{err: "bad CSYNC TypeBitMap", lex: l} } } rr.TypeBitMap = append(rr.TypeBitMap, k) default: - return &ParseError{"", "bad CSYNC TypeBitMap", l} + return &ParseError{err: "bad CSYNC TypeBitMap", lex: l} } l, _ = c.Next() } @@ -855,7 +878,7 @@ func (rr *ZONEMD) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 32) if e != nil || l.err { - return &ParseError{"", "bad ZONEMD Serial", l} + return &ParseError{err: "bad ZONEMD Serial", lex: l} } rr.Serial = uint32(i) @@ -863,7 +886,7 @@ func (rr *ZONEMD) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad ZONEMD Scheme", l} + return &ParseError{err: "bad ZONEMD Scheme", lex: l} } rr.Scheme = uint8(i) @@ -871,7 +894,7 @@ func (rr *ZONEMD) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() i, err := strconv.ParseUint(l.token, 10, 8) if err != nil || l.err { - return &ParseError{"", "bad ZONEMD Hash Algorithm", l} + return &ParseError{err: "bad ZONEMD Hash Algorithm", lex: l} } rr.Hash = uint8(i) @@ -892,11 +915,11 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { if strings.HasPrefix(tokenUpper, "TYPE") { t, ok = typeToInt(l.token) if !ok { - return &ParseError{"", "bad RRSIG Typecovered", l} + return &ParseError{err: "bad RRSIG Typecovered", lex: l} } rr.TypeCovered = t } else { - return &ParseError{"", "bad RRSIG Typecovered", l} + return &ParseError{err: "bad RRSIG Typecovered", lex: l} } } else { rr.TypeCovered = t @@ -904,17 +927,24 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { c.Next() // zBlank l, _ = c.Next() + if l.err { + return &ParseError{err: "bad RRSIG Algorithm", lex: l} + } i, e := strconv.ParseUint(l.token, 10, 8) - if e != nil || l.err { - return &ParseError{"", "bad RRSIG Algorithm", l} + rr.Algorithm = uint8(i) // if 0 we'll check the mnemonic in the if + if e != nil { + v, ok := StringToAlgorithm[l.token] + if !ok { + return &ParseError{err: "bad RRSIG Algorithm", lex: l} + } + rr.Algorithm = v } - rr.Algorithm = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad RRSIG Labels", l} + return &ParseError{err: "bad RRSIG Labels", lex: l} } rr.Labels = uint8(i) @@ -922,7 +952,7 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() i, e2 := strconv.ParseUint(l.token, 10, 32) if e2 != nil || l.err { - return &ParseError{"", "bad RRSIG OrigTtl", l} + return &ParseError{err: "bad RRSIG OrigTtl", lex: l} } rr.OrigTtl = uint32(i) @@ -933,7 +963,7 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { if i, err := strconv.ParseUint(l.token, 10, 32); err == nil { rr.Expiration = uint32(i) } else { - return &ParseError{"", "bad RRSIG Expiration", l} + return &ParseError{err: "bad RRSIG Expiration", lex: l} } } else { rr.Expiration = i @@ -945,7 +975,7 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { if i, err := strconv.ParseUint(l.token, 10, 32); err == nil { rr.Inception = uint32(i) } else { - return &ParseError{"", "bad RRSIG Inception", l} + return &ParseError{err: "bad RRSIG Inception", lex: l} } } else { rr.Inception = i @@ -955,7 +985,7 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() i, e3 := strconv.ParseUint(l.token, 10, 16) if e3 != nil || l.err { - return &ParseError{"", "bad RRSIG KeyTag", l} + return &ParseError{err: "bad RRSIG KeyTag", lex: l} } rr.KeyTag = uint16(i) @@ -964,7 +994,7 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { rr.SignerName = l.token name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad RRSIG SignerName", l} + return &ParseError{err: "bad RRSIG SignerName", lex: l} } rr.SignerName = name @@ -977,11 +1007,13 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { return nil } +func (rr *NXT) parse(c *zlexer, o string) *ParseError { return rr.NSEC.parse(c, o) } + func (rr *NSEC) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad NSEC NextDomain", l} + return &ParseError{err: "bad NSEC NextDomain", lex: l} } rr.NextDomain = name @@ -999,12 +1031,12 @@ func (rr *NSEC) parse(c *zlexer, o string) *ParseError { tokenUpper := strings.ToUpper(l.token) if k, ok = StringToType[tokenUpper]; !ok { if k, ok = typeToInt(l.token); !ok { - return &ParseError{"", "bad NSEC TypeBitMap", l} + return &ParseError{err: "bad NSEC TypeBitMap", lex: l} } } rr.TypeBitMap = append(rr.TypeBitMap, k) default: - return &ParseError{"", "bad NSEC TypeBitMap", l} + return &ParseError{err: "bad NSEC TypeBitMap", lex: l} } l, _ = c.Next() } @@ -1015,27 +1047,27 @@ func (rr *NSEC3) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad NSEC3 Hash", l} + return &ParseError{err: "bad NSEC3 Hash", lex: l} } rr.Hash = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad NSEC3 Flags", l} + return &ParseError{err: "bad NSEC3 Flags", lex: l} } rr.Flags = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e2 := strconv.ParseUint(l.token, 10, 16) if e2 != nil || l.err { - return &ParseError{"", "bad NSEC3 Iterations", l} + return &ParseError{err: "bad NSEC3 Iterations", lex: l} } rr.Iterations = uint16(i) c.Next() l, _ = c.Next() if l.token == "" || l.err { - return &ParseError{"", "bad NSEC3 Salt", l} + return &ParseError{err: "bad NSEC3 Salt", lex: l} } if l.token != "-" { rr.SaltLength = uint8(len(l.token)) / 2 @@ -1045,7 +1077,7 @@ func (rr *NSEC3) parse(c *zlexer, o string) *ParseError { c.Next() l, _ = c.Next() if l.token == "" || l.err { - return &ParseError{"", "bad NSEC3 NextDomain", l} + return &ParseError{err: "bad NSEC3 NextDomain", lex: l} } rr.HashLength = 20 // Fix for NSEC3 (sha1 160 bits) rr.NextDomain = l.token @@ -1064,12 +1096,12 @@ func (rr *NSEC3) parse(c *zlexer, o string) *ParseError { tokenUpper := strings.ToUpper(l.token) if k, ok = StringToType[tokenUpper]; !ok { if k, ok = typeToInt(l.token); !ok { - return &ParseError{"", "bad NSEC3 TypeBitMap", l} + return &ParseError{err: "bad NSEC3 TypeBitMap", lex: l} } } rr.TypeBitMap = append(rr.TypeBitMap, k) default: - return &ParseError{"", "bad NSEC3 TypeBitMap", l} + return &ParseError{err: "bad NSEC3 TypeBitMap", lex: l} } l, _ = c.Next() } @@ -1080,21 +1112,21 @@ func (rr *NSEC3PARAM) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad NSEC3PARAM Hash", l} + return &ParseError{err: "bad NSEC3PARAM Hash", lex: l} } rr.Hash = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad NSEC3PARAM Flags", l} + return &ParseError{err: "bad NSEC3PARAM Flags", lex: l} } rr.Flags = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e2 := strconv.ParseUint(l.token, 10, 16) if e2 != nil || l.err { - return &ParseError{"", "bad NSEC3PARAM Iterations", l} + return &ParseError{err: "bad NSEC3PARAM Iterations", lex: l} } rr.Iterations = uint16(i) c.Next() @@ -1109,7 +1141,7 @@ func (rr *NSEC3PARAM) parse(c *zlexer, o string) *ParseError { func (rr *EUI48) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() if len(l.token) != 17 || l.err { - return &ParseError{"", "bad EUI48 Address", l} + return &ParseError{err: "bad EUI48 Address", lex: l} } addr := make([]byte, 12) dash := 0 @@ -1118,7 +1150,7 @@ func (rr *EUI48) parse(c *zlexer, o string) *ParseError { addr[i+1] = l.token[i+1+dash] dash++ if l.token[i+1+dash] != '-' { - return &ParseError{"", "bad EUI48 Address", l} + return &ParseError{err: "bad EUI48 Address", lex: l} } } addr[10] = l.token[15] @@ -1126,7 +1158,7 @@ func (rr *EUI48) parse(c *zlexer, o string) *ParseError { i, e := strconv.ParseUint(string(addr), 16, 48) if e != nil { - return &ParseError{"", "bad EUI48 Address", l} + return &ParseError{err: "bad EUI48 Address", lex: l} } rr.Address = i return slurpRemainder(c) @@ -1135,7 +1167,7 @@ func (rr *EUI48) parse(c *zlexer, o string) *ParseError { func (rr *EUI64) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() if len(l.token) != 23 || l.err { - return &ParseError{"", "bad EUI64 Address", l} + return &ParseError{err: "bad EUI64 Address", lex: l} } addr := make([]byte, 16) dash := 0 @@ -1144,7 +1176,7 @@ func (rr *EUI64) parse(c *zlexer, o string) *ParseError { addr[i+1] = l.token[i+1+dash] dash++ if l.token[i+1+dash] != '-' { - return &ParseError{"", "bad EUI64 Address", l} + return &ParseError{err: "bad EUI64 Address", lex: l} } } addr[14] = l.token[21] @@ -1152,7 +1184,7 @@ func (rr *EUI64) parse(c *zlexer, o string) *ParseError { i, e := strconv.ParseUint(string(addr), 16, 64) if e != nil { - return &ParseError{"", "bad EUI68 Address", l} + return &ParseError{err: "bad EUI68 Address", lex: l} } rr.Address = i return slurpRemainder(c) @@ -1162,14 +1194,14 @@ func (rr *SSHFP) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad SSHFP Algorithm", l} + return &ParseError{err: "bad SSHFP Algorithm", lex: l} } rr.Algorithm = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad SSHFP Type", l} + return &ParseError{err: "bad SSHFP Type", lex: l} } rr.Type = uint8(i) c.Next() // zBlank @@ -1185,21 +1217,21 @@ func (rr *DNSKEY) parseDNSKEY(c *zlexer, o, typ string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad " + typ + " Flags", l} + return &ParseError{err: "bad " + typ + " Flags", lex: l} } rr.Flags = uint16(i) c.Next() // zBlank l, _ = c.Next() // zString i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad " + typ + " Protocol", l} + return &ParseError{err: "bad " + typ + " Protocol", lex: l} } rr.Protocol = uint8(i) c.Next() // zBlank l, _ = c.Next() // zString i, e2 := strconv.ParseUint(l.token, 10, 8) if e2 != nil || l.err { - return &ParseError{"", "bad " + typ + " Algorithm", l} + return &ParseError{err: "bad " + typ + " Algorithm", lex: l} } rr.Algorithm = uint8(i) s, e3 := endingToString(c, "bad "+typ+" PublicKey") @@ -1221,7 +1253,7 @@ func (rr *IPSECKEY) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() num, err := strconv.ParseUint(l.token, 10, 8) if err != nil || l.err { - return &ParseError{"", "bad IPSECKEY value", l} + return &ParseError{err: "bad IPSECKEY value", lex: l} } rr.Precedence = uint8(num) c.Next() // zBlank @@ -1229,7 +1261,7 @@ func (rr *IPSECKEY) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() num, err = strconv.ParseUint(l.token, 10, 8) if err != nil || l.err { - return &ParseError{"", "bad IPSECKEY value", l} + return &ParseError{err: "bad IPSECKEY value", lex: l} } rr.GatewayType = uint8(num) c.Next() // zBlank @@ -1237,19 +1269,19 @@ func (rr *IPSECKEY) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() num, err = strconv.ParseUint(l.token, 10, 8) if err != nil || l.err { - return &ParseError{"", "bad IPSECKEY value", l} + return &ParseError{err: "bad IPSECKEY value", lex: l} } rr.Algorithm = uint8(num) c.Next() // zBlank l, _ = c.Next() if l.err { - return &ParseError{"", "bad IPSECKEY gateway", l} + return &ParseError{err: "bad IPSECKEY gateway", lex: l} } rr.GatewayAddr, rr.GatewayHost, err = parseAddrHostUnion(l.token, o, rr.GatewayType) if err != nil { - return &ParseError{"", "IPSECKEY " + err.Error(), l} + return &ParseError{wrappedErr: fmt.Errorf("IPSECKEY %w", err), lex: l} } c.Next() // zBlank @@ -1266,14 +1298,14 @@ func (rr *AMTRELAY) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() num, err := strconv.ParseUint(l.token, 10, 8) if err != nil || l.err { - return &ParseError{"", "bad AMTRELAY value", l} + return &ParseError{err: "bad AMTRELAY value", lex: l} } rr.Precedence = uint8(num) c.Next() // zBlank l, _ = c.Next() if l.err || !(l.token == "0" || l.token == "1") { - return &ParseError{"", "bad discovery value", l} + return &ParseError{err: "bad discovery value", lex: l} } if l.token == "1" { rr.GatewayType = 0x80 @@ -1284,19 +1316,19 @@ func (rr *AMTRELAY) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() num, err = strconv.ParseUint(l.token, 10, 8) if err != nil || l.err { - return &ParseError{"", "bad AMTRELAY value", l} + return &ParseError{err: "bad AMTRELAY value", lex: l} } rr.GatewayType |= uint8(num) c.Next() // zBlank l, _ = c.Next() if l.err { - return &ParseError{"", "bad AMTRELAY gateway", l} + return &ParseError{err: "bad AMTRELAY gateway", lex: l} } rr.GatewayAddr, rr.GatewayHost, err = parseAddrHostUnion(l.token, o, rr.GatewayType&0x7f) if err != nil { - return &ParseError{"", "AMTRELAY " + err.Error(), l} + return &ParseError{wrappedErr: fmt.Errorf("AMTRELAY %w", err), lex: l} } return slurpRemainder(c) @@ -1332,21 +1364,21 @@ func (rr *RKEY) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad RKEY Flags", l} + return &ParseError{err: "bad RKEY Flags", lex: l} } rr.Flags = uint16(i) c.Next() // zBlank l, _ = c.Next() // zString i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad RKEY Protocol", l} + return &ParseError{err: "bad RKEY Protocol", lex: l} } rr.Protocol = uint8(i) c.Next() // zBlank l, _ = c.Next() // zString i, e2 := strconv.ParseUint(l.token, 10, 8) if e2 != nil || l.err { - return &ParseError{"", "bad RKEY Algorithm", l} + return &ParseError{err: "bad RKEY Algorithm", lex: l} } rr.Algorithm = uint8(i) s, e3 := endingToString(c, "bad RKEY PublicKey") @@ -1379,21 +1411,21 @@ func (rr *GPOS) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() _, e := strconv.ParseFloat(l.token, 64) if e != nil || l.err { - return &ParseError{"", "bad GPOS Longitude", l} + return &ParseError{err: "bad GPOS Longitude", lex: l} } rr.Longitude = l.token c.Next() // zBlank l, _ = c.Next() _, e1 := strconv.ParseFloat(l.token, 64) if e1 != nil || l.err { - return &ParseError{"", "bad GPOS Latitude", l} + return &ParseError{err: "bad GPOS Latitude", lex: l} } rr.Latitude = l.token c.Next() // zBlank l, _ = c.Next() _, e2 := strconv.ParseFloat(l.token, 64) if e2 != nil || l.err { - return &ParseError{"", "bad GPOS Altitude", l} + return &ParseError{err: "bad GPOS Altitude", lex: l} } rr.Altitude = l.token return slurpRemainder(c) @@ -1403,7 +1435,7 @@ func (rr *DS) parseDS(c *zlexer, o, typ string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad " + typ + " KeyTag", l} + return &ParseError{err: "bad " + typ + " KeyTag", lex: l} } rr.KeyTag = uint16(i) c.Next() // zBlank @@ -1412,7 +1444,7 @@ func (rr *DS) parseDS(c *zlexer, o, typ string) *ParseError { tokenUpper := strings.ToUpper(l.token) i, ok := StringToAlgorithm[tokenUpper] if !ok || l.err { - return &ParseError{"", "bad " + typ + " Algorithm", l} + return &ParseError{err: "bad " + typ + " Algorithm", lex: l} } rr.Algorithm = i } else { @@ -1422,7 +1454,7 @@ func (rr *DS) parseDS(c *zlexer, o, typ string) *ParseError { l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad " + typ + " DigestType", l} + return &ParseError{err: "bad " + typ + " DigestType", lex: l} } rr.DigestType = uint8(i) s, e2 := endingToString(c, "bad "+typ+" Digest") @@ -1437,7 +1469,7 @@ func (rr *TA) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad TA KeyTag", l} + return &ParseError{err: "bad TA KeyTag", lex: l} } rr.KeyTag = uint16(i) c.Next() // zBlank @@ -1446,7 +1478,7 @@ func (rr *TA) parse(c *zlexer, o string) *ParseError { tokenUpper := strings.ToUpper(l.token) i, ok := StringToAlgorithm[tokenUpper] if !ok || l.err { - return &ParseError{"", "bad TA Algorithm", l} + return &ParseError{err: "bad TA Algorithm", lex: l} } rr.Algorithm = i } else { @@ -1456,7 +1488,7 @@ func (rr *TA) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad TA DigestType", l} + return &ParseError{err: "bad TA DigestType", lex: l} } rr.DigestType = uint8(i) s, e2 := endingToString(c, "bad TA Digest") @@ -1471,21 +1503,21 @@ func (rr *TLSA) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad TLSA Usage", l} + return &ParseError{err: "bad TLSA Usage", lex: l} } rr.Usage = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad TLSA Selector", l} + return &ParseError{err: "bad TLSA Selector", lex: l} } rr.Selector = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e2 := strconv.ParseUint(l.token, 10, 8) if e2 != nil || l.err { - return &ParseError{"", "bad TLSA MatchingType", l} + return &ParseError{err: "bad TLSA MatchingType", lex: l} } rr.MatchingType = uint8(i) // So this needs be e2 (i.e. different than e), because...??t @@ -1501,21 +1533,21 @@ func (rr *SMIMEA) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad SMIMEA Usage", l} + return &ParseError{err: "bad SMIMEA Usage", lex: l} } rr.Usage = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad SMIMEA Selector", l} + return &ParseError{err: "bad SMIMEA Selector", lex: l} } rr.Selector = uint8(i) c.Next() // zBlank l, _ = c.Next() i, e2 := strconv.ParseUint(l.token, 10, 8) if e2 != nil || l.err { - return &ParseError{"", "bad SMIMEA MatchingType", l} + return &ParseError{err: "bad SMIMEA MatchingType", lex: l} } rr.MatchingType = uint8(i) // So this needs be e2 (i.e. different than e), because...??t @@ -1530,14 +1562,14 @@ func (rr *SMIMEA) parse(c *zlexer, o string) *ParseError { func (rr *RFC3597) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() if l.token != "\\#" { - return &ParseError{"", "bad RFC3597 Rdata", l} + return &ParseError{err: "bad RFC3597 Rdata", lex: l} } c.Next() // zBlank l, _ = c.Next() rdlength, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad RFC3597 Rdata ", l} + return &ParseError{err: "bad RFC3597 Rdata ", lex: l} } s, e1 := endingToString(c, "bad RFC3597 Rdata") @@ -1545,7 +1577,7 @@ func (rr *RFC3597) parse(c *zlexer, o string) *ParseError { return e1 } if int(rdlength)*2 != len(s) { - return &ParseError{"", "bad RFC3597 Rdata", l} + return &ParseError{err: "bad RFC3597 Rdata", lex: l} } rr.Rdata = s return nil @@ -1593,14 +1625,14 @@ func (rr *URI) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad URI Priority", l} + return &ParseError{err: "bad URI Priority", lex: l} } rr.Priority = uint16(i) c.Next() // zBlank l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 16) if e1 != nil || l.err { - return &ParseError{"", "bad URI Weight", l} + return &ParseError{err: "bad URI Weight", lex: l} } rr.Weight = uint16(i) @@ -1610,7 +1642,7 @@ func (rr *URI) parse(c *zlexer, o string) *ParseError { return e2 } if len(s) != 1 { - return &ParseError{"", "bad URI Target", l} + return &ParseError{err: "bad URI Target", lex: l} } rr.Target = s[0] return nil @@ -1630,7 +1662,7 @@ func (rr *NID) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad NID Preference", l} + return &ParseError{err: "bad NID Preference", lex: l} } rr.Preference = uint16(i) c.Next() // zBlank @@ -1647,14 +1679,14 @@ func (rr *L32) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad L32 Preference", l} + return &ParseError{err: "bad L32 Preference", lex: l} } rr.Preference = uint16(i) c.Next() // zBlank l, _ = c.Next() // zString rr.Locator32 = net.ParseIP(l.token) if rr.Locator32 == nil || l.err { - return &ParseError{"", "bad L32 Locator", l} + return &ParseError{err: "bad L32 Locator", lex: l} } return slurpRemainder(c) } @@ -1663,7 +1695,7 @@ func (rr *LP) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad LP Preference", l} + return &ParseError{err: "bad LP Preference", lex: l} } rr.Preference = uint16(i) @@ -1672,7 +1704,7 @@ func (rr *LP) parse(c *zlexer, o string) *ParseError { rr.Fqdn = l.token name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{"", "bad LP Fqdn", l} + return &ParseError{err: "bad LP Fqdn", lex: l} } rr.Fqdn = name return slurpRemainder(c) @@ -1682,7 +1714,7 @@ func (rr *L64) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad L64 Preference", l} + return &ParseError{err: "bad L64 Preference", lex: l} } rr.Preference = uint16(i) c.Next() // zBlank @@ -1699,7 +1731,7 @@ func (rr *UID) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 32) if e != nil || l.err { - return &ParseError{"", "bad UID Uid", l} + return &ParseError{err: "bad UID Uid", lex: l} } rr.Uid = uint32(i) return slurpRemainder(c) @@ -1709,7 +1741,7 @@ func (rr *GID) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 32) if e != nil || l.err { - return &ParseError{"", "bad GID Gid", l} + return &ParseError{err: "bad GID Gid", lex: l} } rr.Gid = uint32(i) return slurpRemainder(c) @@ -1731,7 +1763,7 @@ func (rr *PX) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{"", "bad PX Preference", l} + return &ParseError{err: "bad PX Preference", lex: l} } rr.Preference = uint16(i) @@ -1740,7 +1772,7 @@ func (rr *PX) parse(c *zlexer, o string) *ParseError { rr.Map822 = l.token map822, map822Ok := toAbsoluteName(l.token, o) if l.err || !map822Ok { - return &ParseError{"", "bad PX Map822", l} + return &ParseError{err: "bad PX Map822", lex: l} } rr.Map822 = map822 @@ -1749,7 +1781,7 @@ func (rr *PX) parse(c *zlexer, o string) *ParseError { rr.Mapx400 = l.token mapx400, mapx400Ok := toAbsoluteName(l.token, o) if l.err || !mapx400Ok { - return &ParseError{"", "bad PX Mapx400", l} + return &ParseError{err: "bad PX Mapx400", lex: l} } rr.Mapx400 = mapx400 return slurpRemainder(c) @@ -1759,14 +1791,14 @@ func (rr *CAA) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad CAA Flag", l} + return &ParseError{err: "bad CAA Flag", lex: l} } rr.Flag = uint8(i) c.Next() // zBlank l, _ = c.Next() // zString if l.value != zString { - return &ParseError{"", "bad CAA Tag", l} + return &ParseError{err: "bad CAA Tag", lex: l} } rr.Tag = l.token @@ -1776,7 +1808,7 @@ func (rr *CAA) parse(c *zlexer, o string) *ParseError { return e1 } if len(s) != 1 { - return &ParseError{"", "bad CAA Value", l} + return &ParseError{err: "bad CAA Value", lex: l} } rr.Value = s[0] return nil @@ -1787,7 +1819,7 @@ func (rr *TKEY) parse(c *zlexer, o string) *ParseError { // Algorithm if l.value != zString { - return &ParseError{"", "bad TKEY algorithm", l} + return &ParseError{err: "bad TKEY algorithm", lex: l} } rr.Algorithm = l.token c.Next() // zBlank @@ -1796,13 +1828,13 @@ func (rr *TKEY) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() i, e := strconv.ParseUint(l.token, 10, 8) if e != nil || l.err { - return &ParseError{"", "bad TKEY key length", l} + return &ParseError{err: "bad TKEY key length", lex: l} } rr.KeySize = uint16(i) c.Next() // zBlank l, _ = c.Next() if l.value != zString { - return &ParseError{"", "bad TKEY key", l} + return &ParseError{err: "bad TKEY key", lex: l} } rr.Key = l.token c.Next() // zBlank @@ -1811,13 +1843,13 @@ func (rr *TKEY) parse(c *zlexer, o string) *ParseError { l, _ = c.Next() i, e1 := strconv.ParseUint(l.token, 10, 8) if e1 != nil || l.err { - return &ParseError{"", "bad TKEY otherdata length", l} + return &ParseError{err: "bad TKEY otherdata length", lex: l} } rr.OtherLen = uint16(i) c.Next() // zBlank l, _ = c.Next() if l.value != zString { - return &ParseError{"", "bad TKEY otherday", l} + return &ParseError{err: "bad TKEY otherday", lex: l} } rr.OtherData = l.token return nil @@ -1835,14 +1867,14 @@ func (rr *APL) parse(c *zlexer, o string) *ParseError { continue } if l.value != zString { - return &ParseError{"", "unexpected APL field", l} + return &ParseError{err: "unexpected APL field", lex: l} } // Expected format: [!]afi:address/prefix colon := strings.IndexByte(l.token, ':') if colon == -1 { - return &ParseError{"", "missing colon in APL field", l} + return &ParseError{err: "missing colon in APL field", lex: l} } family, cidr := l.token[:colon], l.token[colon+1:] @@ -1855,7 +1887,7 @@ func (rr *APL) parse(c *zlexer, o string) *ParseError { afi, e := strconv.ParseUint(family, 10, 16) if e != nil { - return &ParseError{"", "failed to parse APL family: " + e.Error(), l} + return &ParseError{wrappedErr: fmt.Errorf("failed to parse APL family: %w", e), lex: l} } var addrLen int switch afi { @@ -1864,19 +1896,19 @@ func (rr *APL) parse(c *zlexer, o string) *ParseError { case 2: addrLen = net.IPv6len default: - return &ParseError{"", "unrecognized APL family", l} + return &ParseError{err: "unrecognized APL family", lex: l} } ip, subnet, e1 := net.ParseCIDR(cidr) if e1 != nil { - return &ParseError{"", "failed to parse APL address: " + e1.Error(), l} + return &ParseError{wrappedErr: fmt.Errorf("failed to parse APL address: %w", e1), lex: l} } if !ip.Equal(subnet.IP) { - return &ParseError{"", "extra bits in APL address", l} + return &ParseError{err: "extra bits in APL address", lex: l} } if len(subnet.IP) != addrLen { - return &ParseError{"", "address mismatch with the APL family", l} + return &ParseError{err: "address mismatch with the APL family", lex: l} } prefixes = append(prefixes, APLPrefix{ diff --git a/vendor/github.com/miekg/dns/server.go b/vendor/github.com/miekg/dns/server.go index 64e388546..0207d6da2 100644 --- a/vendor/github.com/miekg/dns/server.go +++ b/vendor/github.com/miekg/dns/server.go @@ -226,6 +226,10 @@ type Server struct { // Whether to set the SO_REUSEPORT socket option, allowing multiple listeners to be bound to a single address. // It is only supported on certain GOOSes and when using ListenAndServe. ReusePort bool + // Whether to set the SO_REUSEADDR socket option, allowing multiple listeners to be bound to a single address. + // Crucially this allows binding when an existing server is listening on `0.0.0.0` or `::`. + // It is only supported on certain GOOSes and when using ListenAndServe. + ReuseAddr bool // AcceptMsgFunc will check the incoming message and will reject it early in the process. // By default DefaultMsgAcceptFunc will be used. MsgAcceptFunc MsgAcceptFunc @@ -304,7 +308,7 @@ func (srv *Server) ListenAndServe() error { switch srv.Net { case "tcp", "tcp4", "tcp6": - l, err := listenTCP(srv.Net, addr, srv.ReusePort) + l, err := listenTCP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr) if err != nil { return err } @@ -317,7 +321,7 @@ func (srv *Server) ListenAndServe() error { return errors.New("dns: neither Certificates nor GetCertificate set in Config") } network := strings.TrimSuffix(srv.Net, "-tls") - l, err := listenTCP(network, addr, srv.ReusePort) + l, err := listenTCP(network, addr, srv.ReusePort, srv.ReuseAddr) if err != nil { return err } @@ -327,7 +331,7 @@ func (srv *Server) ListenAndServe() error { unlock() return srv.serveTCP(l) case "udp", "udp4", "udp6": - l, err := listenUDP(srv.Net, addr, srv.ReusePort) + l, err := listenUDP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr) if err != nil { return err } diff --git a/vendor/github.com/miekg/dns/singleinflight.go b/vendor/github.com/miekg/dns/singleinflight.go deleted file mode 100644 index febcc300f..000000000 --- a/vendor/github.com/miekg/dns/singleinflight.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2013 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. - -// Adapted for dns package usage by Miek Gieben. - -package dns - -import "sync" -import "time" - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - val *Msg - rtt time.Duration - err error - dups int -} - -// singleflight represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type singleflight struct { - sync.Mutex // protects m - m map[string]*call // lazily initialized - - dontDeleteForTesting bool // this is only to be used by TestConcurrentExchanges -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *singleflight) Do(key string, fn func() (*Msg, time.Duration, error)) (v *Msg, rtt time.Duration, err error, shared bool) { - g.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.Unlock() - c.wg.Wait() - return c.val, c.rtt, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.Unlock() - - c.val, c.rtt, c.err = fn() - c.wg.Done() - - if !g.dontDeleteForTesting { - g.Lock() - delete(g.m, key) - g.Unlock() - } - - return c.val, c.rtt, c.err, c.dups > 0 -} diff --git a/vendor/github.com/miekg/dns/svcb.go b/vendor/github.com/miekg/dns/svcb.go index 6d496d74d..c1a740b68 100644 --- a/vendor/github.com/miekg/dns/svcb.go +++ b/vendor/github.com/miekg/dns/svcb.go @@ -85,7 +85,7 @@ func (rr *SVCB) parse(c *zlexer, o string) *ParseError { l, _ := c.Next() i, e := strconv.ParseUint(l.token, 10, 16) if e != nil || l.err { - return &ParseError{l.token, "bad SVCB priority", l} + return &ParseError{file: l.token, err: "bad SVCB priority", lex: l} } rr.Priority = uint16(i) @@ -95,7 +95,7 @@ func (rr *SVCB) parse(c *zlexer, o string) *ParseError { name, nameOk := toAbsoluteName(l.token, o) if l.err || !nameOk { - return &ParseError{l.token, "bad SVCB Target", l} + return &ParseError{file: l.token, err: "bad SVCB Target", lex: l} } rr.Target = name @@ -111,7 +111,7 @@ func (rr *SVCB) parse(c *zlexer, o string) *ParseError { if !canHaveNextKey { // The key we can now read was probably meant to be // a part of the last value. - return &ParseError{l.token, "bad SVCB value quotation", l} + return &ParseError{file: l.token, err: "bad SVCB value quotation", lex: l} } // In key=value pairs, value does not have to be quoted unless value @@ -124,7 +124,7 @@ func (rr *SVCB) parse(c *zlexer, o string) *ParseError { // Key with no value and no equality sign key = l.token } else if idx == 0 { - return &ParseError{l.token, "bad SVCB key", l} + return &ParseError{file: l.token, err: "bad SVCB key", lex: l} } else { key, value = l.token[:idx], l.token[idx+1:] @@ -144,30 +144,30 @@ func (rr *SVCB) parse(c *zlexer, o string) *ParseError { value = l.token l, _ = c.Next() if l.value != zQuote { - return &ParseError{l.token, "SVCB unterminated value", l} + return &ParseError{file: l.token, err: "SVCB unterminated value", lex: l} } case zQuote: // There's nothing in double quotes. default: - return &ParseError{l.token, "bad SVCB value", l} + return &ParseError{file: l.token, err: "bad SVCB value", lex: l} } } } } kv := makeSVCBKeyValue(svcbStringToKey(key)) if kv == nil { - return &ParseError{l.token, "bad SVCB key", l} + return &ParseError{file: l.token, err: "bad SVCB key", lex: l} } if err := kv.parse(value); err != nil { - return &ParseError{l.token, err.Error(), l} + return &ParseError{file: l.token, wrappedErr: err, lex: l} } xs = append(xs, kv) case zQuote: - return &ParseError{l.token, "SVCB key can't contain double quotes", l} + return &ParseError{file: l.token, err: "SVCB key can't contain double quotes", lex: l} case zBlank: canHaveNextKey = true default: - return &ParseError{l.token, "bad SVCB values", l} + return &ParseError{file: l.token, err: "bad SVCB values", lex: l} } l, _ = c.Next() } @@ -314,10 +314,11 @@ func (s *SVCBMandatory) unpack(b []byte) error { } func (s *SVCBMandatory) parse(b string) error { - str := strings.Split(b, ",") - codes := make([]SVCBKey, 0, len(str)) - for _, e := range str { - codes = append(codes, svcbStringToKey(e)) + codes := make([]SVCBKey, 0, strings.Count(b, ",")+1) + for len(b) > 0 { + var key string + key, b, _ = strings.Cut(b, ",") + codes = append(codes, svcbStringToKey(key)) } s.Code = codes return nil @@ -613,19 +614,24 @@ func (s *SVCBIPv4Hint) String() string { } func (s *SVCBIPv4Hint) parse(b string) error { + if b == "" { + return errors.New("dns: svcbipv4hint: empty hint") + } if strings.Contains(b, ":") { return errors.New("dns: svcbipv4hint: expected ipv4, got ipv6") } - str := strings.Split(b, ",") - dst := make([]net.IP, len(str)) - for i, e := range str { + + hint := make([]net.IP, 0, strings.Count(b, ",")+1) + for len(b) > 0 { + var e string + e, b, _ = strings.Cut(b, ",") ip := net.ParseIP(e).To4() if ip == nil { return errors.New("dns: svcbipv4hint: bad ip") } - dst[i] = ip + hint = append(hint, ip) } - s.Hint = dst + s.Hint = hint return nil } @@ -733,9 +739,14 @@ func (s *SVCBIPv6Hint) String() string { } func (s *SVCBIPv6Hint) parse(b string) error { - str := strings.Split(b, ",") - dst := make([]net.IP, len(str)) - for i, e := range str { + if b == "" { + return errors.New("dns: svcbipv6hint: empty hint") + } + + hint := make([]net.IP, 0, strings.Count(b, ",")+1) + for len(b) > 0 { + var e string + e, b, _ = strings.Cut(b, ",") ip := net.ParseIP(e) if ip == nil { return errors.New("dns: svcbipv6hint: bad ip") @@ -743,9 +754,9 @@ func (s *SVCBIPv6Hint) parse(b string) error { if ip.To4() != nil { return errors.New("dns: svcbipv6hint: expected ipv6, got ipv4-mapped-ipv6") } - dst[i] = ip + hint = append(hint, ip) } - s.Hint = dst + s.Hint = hint return nil } diff --git a/vendor/github.com/miekg/dns/types.go b/vendor/github.com/miekg/dns/types.go index 03afeccda..8e3129cbd 100644 --- a/vendor/github.com/miekg/dns/types.go +++ b/vendor/github.com/miekg/dns/types.go @@ -135,8 +135,8 @@ const ( RcodeNXRrset = 8 // NXRRSet - RR Set that should exist does not [DNS Update] RcodeNotAuth = 9 // NotAuth - Server Not Authoritative for zone [DNS Update] RcodeNotZone = 10 // NotZone - Name not contained in zone [DNS Update/TSIG] - RcodeBadSig = 16 // BADSIG - TSIG Signature Failure [TSIG] - RcodeBadVers = 16 // BADVERS - Bad OPT Version [EDNS0] + RcodeBadSig = 16 // BADSIG - TSIG Signature Failure [TSIG] https://www.rfc-editor.org/rfc/rfc6895.html#section-2.3 + RcodeBadVers = 16 // BADVERS - Bad OPT Version [EDNS0] https://www.rfc-editor.org/rfc/rfc6895.html#section-2.3 RcodeBadKey = 17 // BADKEY - Key not recognized [TSIG] RcodeBadTime = 18 // BADTIME - Signature out of time window [TSIG] RcodeBadMode = 19 // BADMODE - Bad TKEY Mode [TKEY] @@ -236,6 +236,9 @@ var CertTypeToString = map[uint16]string{ CertOID: "OID", } +// Prefix for IPv4 encoded as IPv6 address +const ipv4InIPv6Prefix = "::ffff:" + //go:generate go run types_generate.go // Question holds a DNS question. Usually there is just one. While the @@ -399,6 +402,17 @@ func (rr *X25) String() string { return rr.Hdr.String() + rr.PSDNAddress } +// ISDN RR. See RFC 1183, Section 3.2. +type ISDN struct { + Hdr RR_Header + Address string + SubAddress string +} + +func (rr *ISDN) String() string { + return rr.Hdr.String() + sprintTxt([]string{rr.Address, rr.SubAddress}) +} + // RT RR. See RFC 1183, Section 3.3. type RT struct { Hdr RR_Header @@ -751,6 +765,11 @@ func (rr *AAAA) String() string { if rr.AAAA == nil { return rr.Hdr.String() } + + if rr.AAAA.To4() != nil { + return rr.Hdr.String() + ipv4InIPv6Prefix + rr.AAAA.String() + } + return rr.Hdr.String() + rr.AAAA.String() } @@ -778,7 +797,7 @@ func (rr *GPOS) String() string { return rr.Hdr.String() + rr.Longitude + " " + rr.Latitude + " " + rr.Altitude } -// LOC RR. See RFC RFC 1876. +// LOC RR. See RFC 1876. type LOC struct { Hdr RR_Header Version uint8 @@ -890,6 +909,11 @@ func (rr *RRSIG) String() string { return s } +// NXT RR. See RFC 2535. +type NXT struct { + NSEC +} + // NSEC RR. See RFC 4034 and RFC 3755. type NSEC struct { Hdr RR_Header @@ -974,7 +998,7 @@ func (rr *TALINK) String() string { sprintName(rr.PreviousName) + " " + sprintName(rr.NextName) } -// SSHFP RR. See RFC RFC 4255. +// SSHFP RR. See RFC 4255. type SSHFP struct { Hdr RR_Header Algorithm uint8 @@ -988,7 +1012,7 @@ func (rr *SSHFP) String() string { " " + strings.ToUpper(rr.FingerPrint) } -// KEY RR. See RFC RFC 2535. +// KEY RR. See RFC 2535. type KEY struct { DNSKEY } @@ -1298,7 +1322,7 @@ type NINFO struct { func (rr *NINFO) String() string { return rr.Hdr.String() + sprintTxt(rr.ZSData) } -// NID RR. See RFC RFC 6742. +// NID RR. See RFC 6742. type NID struct { Hdr RR_Header Preference uint16 @@ -1517,7 +1541,7 @@ func (a *APLPrefix) str() string { case net.IPv6len: // add prefix for IPv4-mapped IPv6 if v4 := a.Network.IP.To4(); v4 != nil { - sb.WriteString("::ffff:") + sb.WriteString(ipv4InIPv6Prefix) } sb.WriteString(a.Network.IP.String()) } diff --git a/vendor/github.com/miekg/dns/version.go b/vendor/github.com/miekg/dns/version.go index f03a169c2..dc34e5902 100644 --- a/vendor/github.com/miekg/dns/version.go +++ b/vendor/github.com/miekg/dns/version.go @@ -3,7 +3,7 @@ package dns import "fmt" // Version is current version of this library. -var Version = v{1, 1, 53} +var Version = v{1, 1, 58} // v holds the version of this library. type v struct { diff --git a/vendor/github.com/miekg/dns/xfr.go b/vendor/github.com/miekg/dns/xfr.go index 0a831c880..05b3c5add 100644 --- a/vendor/github.com/miekg/dns/xfr.go +++ b/vendor/github.com/miekg/dns/xfr.go @@ -80,8 +80,13 @@ func (t *Transfer) In(q *Msg, a string) (env chan *Envelope, err error) { func (t *Transfer) inAxfr(q *Msg, c chan *Envelope) { first := true - defer t.Close() - defer close(c) + defer func() { + // First close the connection, then the channel. This allows functions blocked on + // the channel to assume that the connection is closed and no further operations are + // pending when they resume. + t.Close() + close(c) + }() timeout := dnsTimeout if t.ReadTimeout != 0 { timeout = t.ReadTimeout @@ -131,8 +136,13 @@ func (t *Transfer) inIxfr(q *Msg, c chan *Envelope) { axfr := true n := 0 qser := q.Ns[0].(*SOA).Serial - defer t.Close() - defer close(c) + defer func() { + // First close the connection, then the channel. This allows functions blocked on + // the channel to assume that the connection is closed and no further operations are + // pending when they resume. + t.Close() + close(c) + }() timeout := dnsTimeout if t.ReadTimeout != 0 { timeout = t.ReadTimeout diff --git a/vendor/github.com/miekg/dns/zduplicate.go b/vendor/github.com/miekg/dns/zduplicate.go index 450bbbc29..03029fb3e 100644 --- a/vendor/github.com/miekg/dns/zduplicate.go +++ b/vendor/github.com/miekg/dns/zduplicate.go @@ -481,6 +481,21 @@ func (r1 *IPSECKEY) isDuplicate(_r2 RR) bool { return true } +func (r1 *ISDN) isDuplicate(_r2 RR) bool { + r2, ok := _r2.(*ISDN) + if !ok { + return false + } + _ = r2 + if r1.Address != r2.Address { + return false + } + if r1.SubAddress != r2.SubAddress { + return false + } + return true +} + func (r1 *KEY) isDuplicate(_r2 RR) bool { r2, ok := _r2.(*KEY) if !ok { @@ -871,6 +886,26 @@ func (r1 *NULL) isDuplicate(_r2 RR) bool { return true } +func (r1 *NXT) isDuplicate(_r2 RR) bool { + r2, ok := _r2.(*NXT) + if !ok { + return false + } + _ = r2 + if !isDuplicateName(r1.NextDomain, r2.NextDomain) { + return false + } + if len(r1.TypeBitMap) != len(r2.TypeBitMap) { + return false + } + for i := 0; i < len(r1.TypeBitMap); i++ { + if r1.TypeBitMap[i] != r2.TypeBitMap[i] { + return false + } + } + return true +} + func (r1 *OPENPGPKEY) isDuplicate(_r2 RR) bool { r2, ok := _r2.(*OPENPGPKEY) if !ok { diff --git a/vendor/github.com/miekg/dns/zmsg.go b/vendor/github.com/miekg/dns/zmsg.go index 3ea0eb423..39b3bc810 100644 --- a/vendor/github.com/miekg/dns/zmsg.go +++ b/vendor/github.com/miekg/dns/zmsg.go @@ -372,6 +372,18 @@ func (rr *IPSECKEY) pack(msg []byte, off int, compression compressionMap, compre return off, nil } +func (rr *ISDN) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) { + off, err = packString(rr.Address, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.SubAddress, msg, off) + if err != nil { + return off, err + } + return off, nil +} + func (rr *KEY) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) { off, err = packUint16(rr.Flags, msg, off) if err != nil { @@ -694,6 +706,18 @@ func (rr *NULL) pack(msg []byte, off int, compression compressionMap, compress b return off, nil } +func (rr *NXT) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) { + off, err = packDomainName(rr.NextDomain, msg, off, compression, false) + if err != nil { + return off, err + } + off, err = packDataNsec(rr.TypeBitMap, msg, off) + if err != nil { + return off, err + } + return off, nil +} + func (rr *OPENPGPKEY) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) { off, err = packStringBase64(rr.PublicKey, msg, off) if err != nil { @@ -1746,6 +1770,24 @@ func (rr *IPSECKEY) unpack(msg []byte, off int) (off1 int, err error) { return off, nil } +func (rr *ISDN) unpack(msg []byte, off int) (off1 int, err error) { + rdStart := off + _ = rdStart + + rr.Address, off, err = unpackString(msg, off) + if err != nil { + return off, err + } + if off == len(msg) { + return off, nil + } + rr.SubAddress, off, err = unpackString(msg, off) + if err != nil { + return off, err + } + return off, nil +} + func (rr *KEY) unpack(msg []byte, off int) (off1 int, err error) { rdStart := off _ = rdStart @@ -2224,6 +2266,24 @@ func (rr *NULL) unpack(msg []byte, off int) (off1 int, err error) { return off, nil } +func (rr *NXT) unpack(msg []byte, off int) (off1 int, err error) { + rdStart := off + _ = rdStart + + rr.NextDomain, off, err = UnpackDomainName(msg, off) + if err != nil { + return off, err + } + if off == len(msg) { + return off, nil + } + rr.TypeBitMap, off, err = unpackDataNsec(msg, off) + if err != nil { + return off, err + } + return off, nil +} + func (rr *OPENPGPKEY) unpack(msg []byte, off int) (off1 int, err error) { rdStart := off _ = rdStart diff --git a/vendor/github.com/miekg/dns/ztypes.go b/vendor/github.com/miekg/dns/ztypes.go index 1b6f43200..2c70fc44d 100644 --- a/vendor/github.com/miekg/dns/ztypes.go +++ b/vendor/github.com/miekg/dns/ztypes.go @@ -36,6 +36,7 @@ var TypeToRR = map[uint16]func() RR{ TypeHIP: func() RR { return new(HIP) }, TypeHTTPS: func() RR { return new(HTTPS) }, TypeIPSECKEY: func() RR { return new(IPSECKEY) }, + TypeISDN: func() RR { return new(ISDN) }, TypeKEY: func() RR { return new(KEY) }, TypeKX: func() RR { return new(KX) }, TypeL32: func() RR { return new(L32) }, @@ -59,6 +60,7 @@ var TypeToRR = map[uint16]func() RR{ TypeNSEC3: func() RR { return new(NSEC3) }, TypeNSEC3PARAM: func() RR { return new(NSEC3PARAM) }, TypeNULL: func() RR { return new(NULL) }, + TypeNXT: func() RR { return new(NXT) }, TypeOPENPGPKEY: func() RR { return new(OPENPGPKEY) }, TypeOPT: func() RR { return new(OPT) }, TypePTR: func() RR { return new(PTR) }, @@ -204,6 +206,7 @@ func (rr *HINFO) Header() *RR_Header { return &rr.Hdr } func (rr *HIP) Header() *RR_Header { return &rr.Hdr } func (rr *HTTPS) Header() *RR_Header { return &rr.Hdr } func (rr *IPSECKEY) Header() *RR_Header { return &rr.Hdr } +func (rr *ISDN) Header() *RR_Header { return &rr.Hdr } func (rr *KEY) Header() *RR_Header { return &rr.Hdr } func (rr *KX) Header() *RR_Header { return &rr.Hdr } func (rr *L32) Header() *RR_Header { return &rr.Hdr } @@ -227,6 +230,7 @@ func (rr *NSEC) Header() *RR_Header { return &rr.Hdr } func (rr *NSEC3) Header() *RR_Header { return &rr.Hdr } func (rr *NSEC3PARAM) Header() *RR_Header { return &rr.Hdr } func (rr *NULL) Header() *RR_Header { return &rr.Hdr } +func (rr *NXT) Header() *RR_Header { return &rr.Hdr } func (rr *OPENPGPKEY) Header() *RR_Header { return &rr.Hdr } func (rr *OPT) Header() *RR_Header { return &rr.Hdr } func (rr *PTR) Header() *RR_Header { return &rr.Hdr } @@ -437,6 +441,13 @@ func (rr *IPSECKEY) len(off int, compression map[string]struct{}) int { return l } +func (rr *ISDN) len(off int, compression map[string]struct{}) int { + l := rr.Hdr.len(off, compression) + l += len(rr.Address) + 1 + l += len(rr.SubAddress) + 1 + return l +} + func (rr *KX) len(off int, compression map[string]struct{}) int { l := rr.Hdr.len(off, compression) l += 2 // Preference @@ -966,6 +977,10 @@ func (rr *IPSECKEY) copy() RR { } } +func (rr *ISDN) copy() RR { + return &ISDN{rr.Hdr, rr.Address, rr.SubAddress} +} + func (rr *KEY) copy() RR { return &KEY{*rr.DNSKEY.copy().(*DNSKEY)} } @@ -1092,6 +1107,10 @@ func (rr *NULL) copy() RR { return &NULL{rr.Hdr, rr.Data} } +func (rr *NXT) copy() RR { + return &NXT{*rr.NSEC.copy().(*NSEC)} +} + func (rr *OPENPGPKEY) copy() RR { return &OPENPGPKEY{rr.Hdr, rr.PublicKey} } diff --git a/vendor/github.com/ovh/go-ovh/ovh/configuration.go b/vendor/github.com/ovh/go-ovh/ovh/configuration.go index b648c0f9b..7dbea7a23 100644 --- a/vendor/github.com/ovh/go-ovh/ovh/configuration.go +++ b/vendor/github.com/ovh/go-ovh/ovh/configuration.go @@ -11,7 +11,7 @@ import ( var configPaths = []string{ // System wide configuration - "/etc/ovh.com", + "/etc/ovh.conf", // Configuration in user's home "~/.ovh.conf", // Configuration in local folder diff --git a/vendor/github.com/ovh/go-ovh/ovh/ovh.go b/vendor/github.com/ovh/go-ovh/ovh/ovh.go index 9c47e436c..950fd3756 100644 --- a/vendor/github.com/ovh/go-ovh/ovh/ovh.go +++ b/vendor/github.com/ovh/go-ovh/ovh/ovh.go @@ -114,6 +114,10 @@ func NewDefaultClient() (*Client, error) { return NewClient("", "", "", "") } +func (c *Client) Endpoint() string { + return c.endpoint +} + // // High level helpers // diff --git a/vendor/github.com/pkg/browser/LICENSE b/vendor/github.com/pkg/browser/LICENSE new file mode 100644 index 000000000..65f78fb62 --- /dev/null +++ b/vendor/github.com/pkg/browser/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2014, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/browser/README.md b/vendor/github.com/pkg/browser/README.md new file mode 100644 index 000000000..72b1976e3 --- /dev/null +++ b/vendor/github.com/pkg/browser/README.md @@ -0,0 +1,55 @@ + +# browser + import "github.com/pkg/browser" + +Package browser provides helpers to open files, readers, and urls in a browser window. + +The choice of which browser is started is entirely client dependant. + + + + + +## Variables +``` go +var Stderr io.Writer = os.Stderr +``` +Stderr is the io.Writer to which executed commands write standard error. + +``` go +var Stdout io.Writer = os.Stdout +``` +Stdout is the io.Writer to which executed commands write standard output. + + +## func OpenFile +``` go +func OpenFile(path string) error +``` +OpenFile opens new browser window for the file path. + + +## func OpenReader +``` go +func OpenReader(r io.Reader) error +``` +OpenReader consumes the contents of r and presents the +results in a new browser window. + + +## func OpenURL +``` go +func OpenURL(url string) error +``` +OpenURL opens a new browser window pointing to url. + + + + + + + + + +- - - +Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md) diff --git a/vendor/github.com/pkg/browser/browser.go b/vendor/github.com/pkg/browser/browser.go new file mode 100644 index 000000000..d7969d74d --- /dev/null +++ b/vendor/github.com/pkg/browser/browser.go @@ -0,0 +1,57 @@ +// Package browser provides helpers to open files, readers, and urls in a browser window. +// +// The choice of which browser is started is entirely client dependant. +package browser + +import ( + "fmt" + "io" + "io/ioutil" + "os" + "os/exec" + "path/filepath" +) + +// Stdout is the io.Writer to which executed commands write standard output. +var Stdout io.Writer = os.Stdout + +// Stderr is the io.Writer to which executed commands write standard error. +var Stderr io.Writer = os.Stderr + +// OpenFile opens new browser window for the file path. +func OpenFile(path string) error { + path, err := filepath.Abs(path) + if err != nil { + return err + } + return OpenURL("file://" + path) +} + +// OpenReader consumes the contents of r and presents the +// results in a new browser window. +func OpenReader(r io.Reader) error { + f, err := ioutil.TempFile("", "browser.*.html") + if err != nil { + return fmt.Errorf("browser: could not create temporary file: %v", err) + } + if _, err := io.Copy(f, r); err != nil { + f.Close() + return fmt.Errorf("browser: caching temporary file failed: %v", err) + } + if err := f.Close(); err != nil { + return fmt.Errorf("browser: caching temporary file failed: %v", err) + } + return OpenFile(f.Name()) +} + +// OpenURL opens a new browser window pointing to url. +func OpenURL(url string) error { + return openBrowser(url) +} + +func runCmd(prog string, args ...string) error { + cmd := exec.Command(prog, args...) + cmd.Stdout = Stdout + cmd.Stderr = Stderr + return cmd.Run() +} diff --git a/vendor/github.com/pkg/browser/browser_darwin.go b/vendor/github.com/pkg/browser/browser_darwin.go new file mode 100644 index 000000000..8507cf7c2 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_darwin.go @@ -0,0 +1,5 @@ +package browser + +func openBrowser(url string) error { + return runCmd("open", url) +} diff --git a/vendor/github.com/pkg/browser/browser_freebsd.go b/vendor/github.com/pkg/browser/browser_freebsd.go new file mode 100644 index 000000000..4fc7ff076 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_freebsd.go @@ -0,0 +1,14 @@ +package browser + +import ( + "errors" + "os/exec" +) + +func openBrowser(url string) error { + err := runCmd("xdg-open", url) + if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound { + return errors.New("xdg-open: command not found - install xdg-utils from ports(8)") + } + return err +} diff --git a/vendor/github.com/pkg/browser/browser_linux.go b/vendor/github.com/pkg/browser/browser_linux.go new file mode 100644 index 000000000..d26cdddf9 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_linux.go @@ -0,0 +1,21 @@ +package browser + +import ( + "os/exec" + "strings" +) + +func openBrowser(url string) error { + providers := []string{"xdg-open", "x-www-browser", "www-browser"} + + // There are multiple possible providers to open a browser on linux + // One of them is xdg-open, another is x-www-browser, then there's www-browser, etc. + // Look for one that exists and run it + for _, provider := range providers { + if _, err := exec.LookPath(provider); err == nil { + return runCmd(provider, url) + } + } + + return &exec.Error{Name: strings.Join(providers, ","), Err: exec.ErrNotFound} +} diff --git a/vendor/github.com/pkg/browser/browser_netbsd.go b/vendor/github.com/pkg/browser/browser_netbsd.go new file mode 100644 index 000000000..65a5e5a29 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_netbsd.go @@ -0,0 +1,14 @@ +package browser + +import ( + "errors" + "os/exec" +) + +func openBrowser(url string) error { + err := runCmd("xdg-open", url) + if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound { + return errors.New("xdg-open: command not found - install xdg-utils from pkgsrc(7)") + } + return err +} diff --git a/vendor/github.com/pkg/browser/browser_openbsd.go b/vendor/github.com/pkg/browser/browser_openbsd.go new file mode 100644 index 000000000..4fc7ff076 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_openbsd.go @@ -0,0 +1,14 @@ +package browser + +import ( + "errors" + "os/exec" +) + +func openBrowser(url string) error { + err := runCmd("xdg-open", url) + if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound { + return errors.New("xdg-open: command not found - install xdg-utils from ports(8)") + } + return err +} diff --git a/vendor/github.com/pkg/browser/browser_unsupported.go b/vendor/github.com/pkg/browser/browser_unsupported.go new file mode 100644 index 000000000..7c5c17d34 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_unsupported.go @@ -0,0 +1,12 @@ +// +build !linux,!windows,!darwin,!openbsd,!freebsd,!netbsd + +package browser + +import ( + "fmt" + "runtime" +) + +func openBrowser(url string) error { + return fmt.Errorf("openBrowser: unsupported operating system: %v", runtime.GOOS) +} diff --git a/vendor/github.com/pkg/browser/browser_windows.go b/vendor/github.com/pkg/browser/browser_windows.go new file mode 100644 index 000000000..63e192959 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_windows.go @@ -0,0 +1,7 @@ +package browser + +import "golang.org/x/sys/windows" + +func openBrowser(url string) error { + return windows.ShellExecute(0, nil, windows.StringToUTF16Ptr(url), nil, nil, windows.SW_SHOWNORMAL) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go index 1feba62c6..b5c8bcb39 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go @@ -475,6 +475,9 @@ type HistogramOpts struct { // now is for testing purposes, by default it's time.Now. now func() time.Time + + // afterFunc is for testing purposes, by default it's time.AfterFunc. + afterFunc func(time.Duration, func()) *time.Timer } // HistogramVecOpts bundles the options to create a HistogramVec metric. @@ -526,7 +529,9 @@ func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogr if opts.now == nil { opts.now = time.Now } - + if opts.afterFunc == nil { + opts.afterFunc = time.AfterFunc + } h := &histogram{ desc: desc, upperBounds: opts.Buckets, @@ -536,6 +541,7 @@ func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogr nativeHistogramMinResetDuration: opts.NativeHistogramMinResetDuration, lastResetTime: opts.now(), now: opts.now, + afterFunc: opts.afterFunc, } if len(h.upperBounds) == 0 && opts.NativeHistogramBucketFactor <= 1 { h.upperBounds = DefBuckets @@ -716,9 +722,16 @@ type histogram struct { nativeHistogramMinResetDuration time.Duration // lastResetTime is protected by mtx. It is also used as created timestamp. lastResetTime time.Time + // resetScheduled is protected by mtx. It is true if a reset is + // scheduled for a later time (when nativeHistogramMinResetDuration has + // passed). + resetScheduled bool // now is for testing purposes, by default it's time.Now. now func() time.Time + + // afterFunc is for testing purposes, by default it's time.AfterFunc. + afterFunc func(time.Duration, func()) *time.Timer } func (h *histogram) Desc() *Desc { @@ -874,21 +887,31 @@ func (h *histogram) limitBuckets(counts *histogramCounts, value float64, bucket if h.maybeReset(hotCounts, coldCounts, coldIdx, value, bucket) { return } + // One of the other strategies will happen. To undo what they will do as + // soon as enough time has passed to satisfy + // h.nativeHistogramMinResetDuration, schedule a reset at the right time + // if we haven't done so already. + if h.nativeHistogramMinResetDuration > 0 && !h.resetScheduled { + h.resetScheduled = true + h.afterFunc(h.nativeHistogramMinResetDuration-h.now().Sub(h.lastResetTime), h.reset) + } + if h.maybeWidenZeroBucket(hotCounts, coldCounts) { return } h.doubleBucketWidth(hotCounts, coldCounts) } -// maybeReset resets the whole histogram if at least h.nativeHistogramMinResetDuration -// has been passed. It returns true if the histogram has been reset. The caller -// must have locked h.mtx. +// maybeReset resets the whole histogram if at least +// h.nativeHistogramMinResetDuration has been passed. It returns true if the +// histogram has been reset. The caller must have locked h.mtx. func (h *histogram) maybeReset( hot, cold *histogramCounts, coldIdx uint64, value float64, bucket int, ) bool { // We are using the possibly mocked h.now() rather than // time.Since(h.lastResetTime) to enable testing. - if h.nativeHistogramMinResetDuration == 0 || + if h.nativeHistogramMinResetDuration == 0 || // No reset configured. + h.resetScheduled || // Do not interefere if a reset is already scheduled. h.now().Sub(h.lastResetTime) < h.nativeHistogramMinResetDuration { return false } @@ -906,6 +929,29 @@ func (h *histogram) maybeReset( return true } +// reset resets the whole histogram. It locks h.mtx itself, i.e. it has to be +// called without having locked h.mtx. +func (h *histogram) reset() { + h.mtx.Lock() + defer h.mtx.Unlock() + + n := atomic.LoadUint64(&h.countAndHotIdx) + hotIdx := n >> 63 + coldIdx := (^n) >> 63 + hot := h.counts[hotIdx] + cold := h.counts[coldIdx] + // Completely reset coldCounts. + h.resetCounts(cold) + // Make coldCounts the new hot counts while resetting countAndHotIdx. + n = atomic.SwapUint64(&h.countAndHotIdx, coldIdx<<63) + count := n & ((1 << 63) - 1) + waitForCooldown(count, hot) + // Finally, reset the formerly hot counts, too. + h.resetCounts(hot) + h.lastResetTime = h.now() + h.resetScheduled = false +} + // maybeWidenZeroBucket widens the zero bucket until it includes the existing // buckets closest to the zero bucket (which could be two, if an equidistant // negative and a positive bucket exists, but usually it's only one bucket to be diff --git a/vendor/github.com/prometheus/client_golang/prometheus/labels.go b/vendor/github.com/prometheus/client_golang/prometheus/labels.go index b3c4eca2b..c21911f29 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/labels.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/labels.go @@ -165,6 +165,8 @@ func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error { func validateLabelValues(vals []string, expectedNumberOfValues int) error { if len(vals) != expectedNumberOfValues { + // The call below makes vals escape, copy them to avoid that. + vals := append([]string(nil), vals...) return fmt.Errorf( "%w: expected %d label values but got %d in %#v", errInconsistentCardinality, expectedNumberOfValues, diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go index c0152cdb6..8c1136cee 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build !windows && !js -// +build !windows,!js +//go:build !windows && !js && !wasip1 +// +build !windows,!js,!wasip1 package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go new file mode 100644 index 000000000..d8d9a6d7a --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go @@ -0,0 +1,26 @@ +// Copyright 2023 The Prometheus 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. + +//go:build wasip1 +// +build wasip1 + +package prometheus + +func canCollectProcess() bool { + return false +} + +func (*processCollector) processCollect(chan<- Metric) { + // noop on this platform + return +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/problem.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/problem.go new file mode 100644 index 000000000..9ba42826a --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/problem.go @@ -0,0 +1,33 @@ +// Copyright 2020 The Prometheus 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 promlint + +import dto "github.com/prometheus/client_model/go" + +// A Problem is an issue detected by a linter. +type Problem struct { + // The name of the metric indicated by this Problem. + Metric string + + // A description of the issue for this Problem. + Text string +} + +// newProblem is helper function to create a Problem. +func newProblem(mf *dto.MetricFamily, text string) Problem { + return Problem{ + Metric: mf.GetName(), + Text: text, + } +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/promlint.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/promlint.go index c8864b6c3..dd29cccc3 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/promlint.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/promlint.go @@ -16,15 +16,11 @@ package promlint import ( "errors" - "fmt" "io" - "regexp" "sort" - "strings" - - "github.com/prometheus/common/expfmt" dto "github.com/prometheus/client_model/go" + "github.com/prometheus/common/expfmt" ) // A Linter is a Prometheus metrics linter. It identifies issues with metric @@ -37,23 +33,8 @@ type Linter struct { // of them. r io.Reader mfs []*dto.MetricFamily -} -// A Problem is an issue detected by a Linter. -type Problem struct { - // The name of the metric indicated by this Problem. - Metric string - - // A description of the issue for this Problem. - Text string -} - -// newProblem is helper function to create a Problem. -func newProblem(mf *dto.MetricFamily, text string) Problem { - return Problem{ - Metric: mf.GetName(), - Text: text, - } + customValidations []Validation } // New creates a new Linter that reads an input stream of Prometheus metrics in @@ -72,6 +53,14 @@ func NewWithMetricFamilies(mfs []*dto.MetricFamily) *Linter { } } +// AddCustomValidations adds custom validations to the linter. +func (l *Linter) AddCustomValidations(vs ...Validation) { + if l.customValidations == nil { + l.customValidations = make([]Validation, 0, len(vs)) + } + l.customValidations = append(l.customValidations, vs...) +} + // Lint performs a linting pass, returning a slice of Problems indicating any // issues found in the metrics stream. The slice is sorted by metric name // and issue description. @@ -91,11 +80,11 @@ func (l *Linter) Lint() ([]Problem, error) { return nil, err } - problems = append(problems, lint(mf)...) + problems = append(problems, l.lint(mf)...) } } for _, mf := range l.mfs { - problems = append(problems, lint(mf)...) + problems = append(problems, l.lint(mf)...) } // Ensure deterministic output. @@ -110,276 +99,25 @@ func (l *Linter) Lint() ([]Problem, error) { } // lint is the entry point for linting a single metric. -func lint(mf *dto.MetricFamily) []Problem { - fns := []func(mf *dto.MetricFamily) []Problem{ - lintHelp, - lintMetricUnits, - lintCounter, - lintHistogramSummaryReserved, - lintMetricTypeInName, - lintReservedChars, - lintCamelCase, - lintUnitAbbreviations, - } - - var problems []Problem - for _, fn := range fns { - problems = append(problems, fn(mf)...) - } - - // TODO(mdlayher): lint rules for specific metrics types. - return problems -} - -// lintHelp detects issues related to the help text for a metric. -func lintHelp(mf *dto.MetricFamily) []Problem { +func (l *Linter) lint(mf *dto.MetricFamily) []Problem { var problems []Problem - // Expect all metrics to have help text available. - if mf.Help == nil { - problems = append(problems, newProblem(mf, "no help text")) - } - - return problems -} - -// lintMetricUnits detects issues with metric unit names. -func lintMetricUnits(mf *dto.MetricFamily) []Problem { - var problems []Problem - - unit, base, ok := metricUnits(*mf.Name) - if !ok { - // No known units detected. - return nil - } - - // Unit is already a base unit. - if unit == base { - return nil - } - - problems = append(problems, newProblem(mf, fmt.Sprintf("use base unit %q instead of %q", base, unit))) - - return problems -} - -// lintCounter detects issues specific to counters, as well as patterns that should -// only be used with counters. -func lintCounter(mf *dto.MetricFamily) []Problem { - var problems []Problem - - isCounter := mf.GetType() == dto.MetricType_COUNTER - isUntyped := mf.GetType() == dto.MetricType_UNTYPED - hasTotalSuffix := strings.HasSuffix(mf.GetName(), "_total") - - switch { - case isCounter && !hasTotalSuffix: - problems = append(problems, newProblem(mf, `counter metrics should have "_total" suffix`)) - case !isUntyped && !isCounter && hasTotalSuffix: - problems = append(problems, newProblem(mf, `non-counter metrics should not have "_total" suffix`)) - } - - return problems -} - -// lintHistogramSummaryReserved detects when other types of metrics use names or labels -// reserved for use by histograms and/or summaries. -func lintHistogramSummaryReserved(mf *dto.MetricFamily) []Problem { - // These rules do not apply to untyped metrics. - t := mf.GetType() - if t == dto.MetricType_UNTYPED { - return nil - } - - var problems []Problem - - isHistogram := t == dto.MetricType_HISTOGRAM - isSummary := t == dto.MetricType_SUMMARY - - n := mf.GetName() - - if !isHistogram && strings.HasSuffix(n, "_bucket") { - problems = append(problems, newProblem(mf, `non-histogram metrics should not have "_bucket" suffix`)) - } - if !isHistogram && !isSummary && strings.HasSuffix(n, "_count") { - problems = append(problems, newProblem(mf, `non-histogram and non-summary metrics should not have "_count" suffix`)) - } - if !isHistogram && !isSummary && strings.HasSuffix(n, "_sum") { - problems = append(problems, newProblem(mf, `non-histogram and non-summary metrics should not have "_sum" suffix`)) - } - - for _, m := range mf.GetMetric() { - for _, l := range m.GetLabel() { - ln := l.GetName() - - if !isHistogram && ln == "le" { - problems = append(problems, newProblem(mf, `non-histogram metrics should not have "le" label`)) - } - if !isSummary && ln == "quantile" { - problems = append(problems, newProblem(mf, `non-summary metrics should not have "quantile" label`)) - } - } - } - - return problems -} - -// lintMetricTypeInName detects when metric types are included in the metric name. -func lintMetricTypeInName(mf *dto.MetricFamily) []Problem { - var problems []Problem - n := strings.ToLower(mf.GetName()) - - for i, t := range dto.MetricType_name { - if i == int32(dto.MetricType_UNTYPED) { - continue + for _, fn := range defaultValidations { + errs := fn(mf) + for _, err := range errs { + problems = append(problems, newProblem(mf, err.Error())) } - - typename := strings.ToLower(t) - if strings.Contains(n, "_"+typename+"_") || strings.HasSuffix(n, "_"+typename) { - problems = append(problems, newProblem(mf, fmt.Sprintf(`metric name should not include type '%s'`, typename))) - } - } - return problems -} - -// lintReservedChars detects colons in metric names. -func lintReservedChars(mf *dto.MetricFamily) []Problem { - var problems []Problem - if strings.Contains(mf.GetName(), ":") { - problems = append(problems, newProblem(mf, "metric names should not contain ':'")) - } - return problems -} - -var camelCase = regexp.MustCompile(`[a-z][A-Z]`) - -// lintCamelCase detects metric names and label names written in camelCase. -func lintCamelCase(mf *dto.MetricFamily) []Problem { - var problems []Problem - if camelCase.FindString(mf.GetName()) != "" { - problems = append(problems, newProblem(mf, "metric names should be written in 'snake_case' not 'camelCase'")) } - for _, m := range mf.GetMetric() { - for _, l := range m.GetLabel() { - if camelCase.FindString(l.GetName()) != "" { - problems = append(problems, newProblem(mf, "label names should be written in 'snake_case' not 'camelCase'")) + if l.customValidations != nil { + for _, fn := range l.customValidations { + errs := fn(mf) + for _, err := range errs { + problems = append(problems, newProblem(mf, err.Error())) } } } - return problems -} -// lintUnitAbbreviations detects abbreviated units in the metric name. -func lintUnitAbbreviations(mf *dto.MetricFamily) []Problem { - var problems []Problem - n := strings.ToLower(mf.GetName()) - for _, s := range unitAbbreviations { - if strings.Contains(n, "_"+s+"_") || strings.HasSuffix(n, "_"+s) { - problems = append(problems, newProblem(mf, "metric names should not contain abbreviated units")) - } - } + // TODO(mdlayher): lint rules for specific metrics types. return problems } - -// metricUnits attempts to detect known unit types used as part of a metric name, -// e.g. "foo_bytes_total" or "bar_baz_milligrams". -func metricUnits(m string) (unit, base string, ok bool) { - ss := strings.Split(m, "_") - - for _, s := range ss { - if base, found := units[s]; found { - return s, base, true - } - - for _, p := range unitPrefixes { - if strings.HasPrefix(s, p) { - if base, found := units[s[len(p):]]; found { - return s, base, true - } - } - } - } - - return "", "", false -} - -// Units and their possible prefixes recognized by this library. More can be -// added over time as needed. -var ( - // map a unit to the appropriate base unit. - units = map[string]string{ - // Base units. - "amperes": "amperes", - "bytes": "bytes", - "celsius": "celsius", // Also allow Celsius because it is common in typical Prometheus use cases. - "grams": "grams", - "joules": "joules", - "kelvin": "kelvin", // SI base unit, used in special cases (e.g. color temperature, scientific measurements). - "meters": "meters", // Both American and international spelling permitted. - "metres": "metres", - "seconds": "seconds", - "volts": "volts", - - // Non base units. - // Time. - "minutes": "seconds", - "hours": "seconds", - "days": "seconds", - "weeks": "seconds", - // Temperature. - "kelvins": "kelvin", - "fahrenheit": "celsius", - "rankine": "celsius", - // Length. - "inches": "meters", - "yards": "meters", - "miles": "meters", - // Bytes. - "bits": "bytes", - // Energy. - "calories": "joules", - // Mass. - "pounds": "grams", - "ounces": "grams", - } - - unitPrefixes = []string{ - "pico", - "nano", - "micro", - "milli", - "centi", - "deci", - "deca", - "hecto", - "kilo", - "kibi", - "mega", - "mibi", - "giga", - "gibi", - "tera", - "tebi", - "peta", - "pebi", - } - - // Common abbreviations that we'd like to discourage. - unitAbbreviations = []string{ - "s", - "ms", - "us", - "ns", - "sec", - "b", - "kb", - "mb", - "gb", - "tb", - "pb", - "m", - "h", - "d", - } -) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validation.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validation.go new file mode 100644 index 000000000..f52ad9eab --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validation.go @@ -0,0 +1,33 @@ +// Copyright 2020 The Prometheus 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 promlint + +import ( + dto "github.com/prometheus/client_model/go" + + "github.com/prometheus/client_golang/prometheus/testutil/promlint/validations" +) + +type Validation = func(mf *dto.MetricFamily) []error + +var defaultValidations = []Validation{ + validations.LintHelp, + validations.LintMetricUnits, + validations.LintCounter, + validations.LintHistogramSummaryReserved, + validations.LintMetricTypeInName, + validations.LintReservedChars, + validations.LintCamelCase, + validations.LintUnitAbbreviations, +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/counter_validations.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/counter_validations.go new file mode 100644 index 000000000..f2c2c3905 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/counter_validations.go @@ -0,0 +1,40 @@ +// Copyright 2020 The Prometheus 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 validations + +import ( + "errors" + "strings" + + dto "github.com/prometheus/client_model/go" +) + +// LintCounter detects issues specific to counters, as well as patterns that should +// only be used with counters. +func LintCounter(mf *dto.MetricFamily) []error { + var problems []error + + isCounter := mf.GetType() == dto.MetricType_COUNTER + isUntyped := mf.GetType() == dto.MetricType_UNTYPED + hasTotalSuffix := strings.HasSuffix(mf.GetName(), "_total") + + switch { + case isCounter && !hasTotalSuffix: + problems = append(problems, errors.New(`counter metrics should have "_total" suffix`)) + case !isUntyped && !isCounter && hasTotalSuffix: + problems = append(problems, errors.New(`non-counter metrics should not have "_total" suffix`)) + } + + return problems +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/generic_name_validations.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/generic_name_validations.go new file mode 100644 index 000000000..bc8dbd1e1 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/generic_name_validations.go @@ -0,0 +1,101 @@ +// Copyright 2020 The Prometheus 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 validations + +import ( + "errors" + "fmt" + "regexp" + "strings" + + dto "github.com/prometheus/client_model/go" +) + +var camelCase = regexp.MustCompile(`[a-z][A-Z]`) + +// LintMetricUnits detects issues with metric unit names. +func LintMetricUnits(mf *dto.MetricFamily) []error { + var problems []error + + unit, base, ok := metricUnits(*mf.Name) + if !ok { + // No known units detected. + return nil + } + + // Unit is already a base unit. + if unit == base { + return nil + } + + problems = append(problems, fmt.Errorf("use base unit %q instead of %q", base, unit)) + + return problems +} + +// LintMetricTypeInName detects when metric types are included in the metric name. +func LintMetricTypeInName(mf *dto.MetricFamily) []error { + var problems []error + n := strings.ToLower(mf.GetName()) + + for i, t := range dto.MetricType_name { + if i == int32(dto.MetricType_UNTYPED) { + continue + } + + typename := strings.ToLower(t) + if strings.Contains(n, "_"+typename+"_") || strings.HasSuffix(n, "_"+typename) { + problems = append(problems, fmt.Errorf(`metric name should not include type '%s'`, typename)) + } + } + return problems +} + +// LintReservedChars detects colons in metric names. +func LintReservedChars(mf *dto.MetricFamily) []error { + var problems []error + if strings.Contains(mf.GetName(), ":") { + problems = append(problems, errors.New("metric names should not contain ':'")) + } + return problems +} + +// LintCamelCase detects metric names and label names written in camelCase. +func LintCamelCase(mf *dto.MetricFamily) []error { + var problems []error + if camelCase.FindString(mf.GetName()) != "" { + problems = append(problems, errors.New("metric names should be written in 'snake_case' not 'camelCase'")) + } + + for _, m := range mf.GetMetric() { + for _, l := range m.GetLabel() { + if camelCase.FindString(l.GetName()) != "" { + problems = append(problems, errors.New("label names should be written in 'snake_case' not 'camelCase'")) + } + } + } + return problems +} + +// LintUnitAbbreviations detects abbreviated units in the metric name. +func LintUnitAbbreviations(mf *dto.MetricFamily) []error { + var problems []error + n := strings.ToLower(mf.GetName()) + for _, s := range unitAbbreviations { + if strings.Contains(n, "_"+s+"_") || strings.HasSuffix(n, "_"+s) { + problems = append(problems, errors.New("metric names should not contain abbreviated units")) + } + } + return problems +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/help_validations.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/help_validations.go new file mode 100644 index 000000000..1df294468 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/help_validations.go @@ -0,0 +1,32 @@ +// Copyright 2020 The Prometheus 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 validations + +import ( + "errors" + + dto "github.com/prometheus/client_model/go" +) + +// LintHelp detects issues related to the help text for a metric. +func LintHelp(mf *dto.MetricFamily) []error { + var problems []error + + // Expect all metrics to have help text available. + if mf.Help == nil { + problems = append(problems, errors.New("no help text")) + } + + return problems +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/histogram_validations.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/histogram_validations.go new file mode 100644 index 000000000..6564bdf36 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/histogram_validations.go @@ -0,0 +1,63 @@ +// Copyright 2020 The Prometheus 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 validations + +import ( + "errors" + "strings" + + dto "github.com/prometheus/client_model/go" +) + +// LintHistogramSummaryReserved detects when other types of metrics use names or labels +// reserved for use by histograms and/or summaries. +func LintHistogramSummaryReserved(mf *dto.MetricFamily) []error { + // These rules do not apply to untyped metrics. + t := mf.GetType() + if t == dto.MetricType_UNTYPED { + return nil + } + + var problems []error + + isHistogram := t == dto.MetricType_HISTOGRAM + isSummary := t == dto.MetricType_SUMMARY + + n := mf.GetName() + + if !isHistogram && strings.HasSuffix(n, "_bucket") { + problems = append(problems, errors.New(`non-histogram metrics should not have "_bucket" suffix`)) + } + if !isHistogram && !isSummary && strings.HasSuffix(n, "_count") { + problems = append(problems, errors.New(`non-histogram and non-summary metrics should not have "_count" suffix`)) + } + if !isHistogram && !isSummary && strings.HasSuffix(n, "_sum") { + problems = append(problems, errors.New(`non-histogram and non-summary metrics should not have "_sum" suffix`)) + } + + for _, m := range mf.GetMetric() { + for _, l := range m.GetLabel() { + ln := l.GetName() + + if !isHistogram && ln == "le" { + problems = append(problems, errors.New(`non-histogram metrics should not have "le" label`)) + } + if !isSummary && ln == "quantile" { + problems = append(problems, errors.New(`non-summary metrics should not have "quantile" label`)) + } + } + } + + return problems +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/units.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/units.go new file mode 100644 index 000000000..967977d2b --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/promlint/validations/units.go @@ -0,0 +1,118 @@ +// Copyright 2020 The Prometheus 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 validations + +import "strings" + +// Units and their possible prefixes recognized by this library. More can be +// added over time as needed. +var ( + // map a unit to the appropriate base unit. + units = map[string]string{ + // Base units. + "amperes": "amperes", + "bytes": "bytes", + "celsius": "celsius", // Also allow Celsius because it is common in typical Prometheus use cases. + "grams": "grams", + "joules": "joules", + "kelvin": "kelvin", // SI base unit, used in special cases (e.g. color temperature, scientific measurements). + "meters": "meters", // Both American and international spelling permitted. + "metres": "metres", + "seconds": "seconds", + "volts": "volts", + + // Non base units. + // Time. + "minutes": "seconds", + "hours": "seconds", + "days": "seconds", + "weeks": "seconds", + // Temperature. + "kelvins": "kelvin", + "fahrenheit": "celsius", + "rankine": "celsius", + // Length. + "inches": "meters", + "yards": "meters", + "miles": "meters", + // Bytes. + "bits": "bytes", + // Energy. + "calories": "joules", + // Mass. + "pounds": "grams", + "ounces": "grams", + } + + unitPrefixes = []string{ + "pico", + "nano", + "micro", + "milli", + "centi", + "deci", + "deca", + "hecto", + "kilo", + "kibi", + "mega", + "mibi", + "giga", + "gibi", + "tera", + "tebi", + "peta", + "pebi", + } + + // Common abbreviations that we'd like to discourage. + unitAbbreviations = []string{ + "s", + "ms", + "us", + "ns", + "sec", + "b", + "kb", + "mb", + "gb", + "tb", + "pb", + "m", + "h", + "d", + } +) + +// metricUnits attempts to detect known unit types used as part of a metric name, +// e.g. "foo_bytes_total" or "bar_baz_milligrams". +func metricUnits(m string) (unit, base string, ok bool) { + ss := strings.Split(m, "_") + + for _, s := range ss { + if base, found := units[s]; found { + return s, base, true + } + + for _, p := range unitPrefixes { + if strings.HasPrefix(s, p) { + if base, found := units[s[len(p):]]; found { + return s, base, true + } + } + } + } + + return "", "", false +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/testutil/testutil.go b/vendor/github.com/prometheus/client_golang/prometheus/testutil/testutil.go index 82d4a5436..269f56435 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/testutil/testutil.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/testutil/testutil.go @@ -47,6 +47,7 @@ import ( "github.com/davecgh/go-spew/spew" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" + "google.golang.org/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/internal" @@ -230,6 +231,20 @@ func convertReaderToMetricFamily(reader io.Reader) ([]*dto.MetricFamily, error) return nil, fmt.Errorf("converting reader to metric families failed: %w", err) } + // The text protocol handles empty help fields inconsistently. When + // encoding, any non-nil value, include the empty string, produces a + // "# HELP" line. But when decoding, the help field is only set to a + // non-nil value if the "# HELP" line contains a non-empty value. + // + // Because metrics in a registry always have non-nil help fields, populate + // any nil help fields in the parsed metrics with the empty string so that + // when we compare text encodings, the results are consistent. + for _, metric := range notNormalized { + if metric.Help == nil { + metric.Help = proto.String("") + } + } + return internal.NormalizeMetricFamilies(notNormalized), nil } diff --git a/vendor/github.com/prometheus/client_model/go/metrics.pb.go b/vendor/github.com/prometheus/client_model/go/metrics.pb.go index 84946b270..cee360db7 100644 --- a/vendor/github.com/prometheus/client_model/go/metrics.pb.go +++ b/vendor/github.com/prometheus/client_model/go/metrics.pb.go @@ -474,6 +474,9 @@ type Histogram struct { NegativeDelta []int64 `protobuf:"zigzag64,10,rep,name=negative_delta,json=negativeDelta" json:"negative_delta,omitempty"` // Count delta of each bucket compared to previous one (or to zero for 1st bucket). NegativeCount []float64 `protobuf:"fixed64,11,rep,name=negative_count,json=negativeCount" json:"negative_count,omitempty"` // Absolute count of each bucket. // Positive buckets for the native histogram. + // Use a no-op span (offset 0, length 0) for a native histogram without any + // observations yet and with a zero_threshold of 0. Otherwise, it would be + // indistinguishable from a classic histogram. PositiveSpan []*BucketSpan `protobuf:"bytes,12,rep,name=positive_span,json=positiveSpan" json:"positive_span,omitempty"` // Use either "positive_delta" or "positive_count", the former for // regular histograms with integer counts, the latter for float diff --git a/vendor/github.com/prometheus/common/config/http_config.go b/vendor/github.com/prometheus/common/config/http_config.go index 4763549b8..4a926e8d0 100644 --- a/vendor/github.com/prometheus/common/config/http_config.go +++ b/vendor/github.com/prometheus/common/config/http_config.go @@ -546,10 +546,10 @@ func NewRoundTripperFromConfig(cfg HTTPClientConfig, name string, optFuncs ...HT // If a authorization_credentials is provided, create a round tripper that will set the // Authorization header correctly on each request. - if cfg.Authorization != nil && len(cfg.Authorization.Credentials) > 0 { - rt = NewAuthorizationCredentialsRoundTripper(cfg.Authorization.Type, cfg.Authorization.Credentials, rt) - } else if cfg.Authorization != nil && len(cfg.Authorization.CredentialsFile) > 0 { + if cfg.Authorization != nil && len(cfg.Authorization.CredentialsFile) > 0 { rt = NewAuthorizationCredentialsFileRoundTripper(cfg.Authorization.Type, cfg.Authorization.CredentialsFile, rt) + } else if cfg.Authorization != nil { + rt = NewAuthorizationCredentialsRoundTripper(cfg.Authorization.Type, cfg.Authorization.Credentials, rt) } // Backwards compatibility, be nice with importers who would not have // called Validate(). @@ -630,7 +630,7 @@ func (rt *authorizationCredentialsFileRoundTripper) RoundTrip(req *http.Request) if len(req.Header.Get("Authorization")) == 0 { b, err := os.ReadFile(rt.authCredentialsFile) if err != nil { - return nil, fmt.Errorf("unable to read authorization credentials file %s: %s", rt.authCredentialsFile, err) + return nil, fmt.Errorf("unable to read authorization credentials file %s: %w", rt.authCredentialsFile, err) } authCredentials := strings.TrimSpace(string(b)) @@ -670,7 +670,7 @@ func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, e if rt.usernameFile != "" { usernameBytes, err := os.ReadFile(rt.usernameFile) if err != nil { - return nil, fmt.Errorf("unable to read basic auth username file %s: %s", rt.usernameFile, err) + return nil, fmt.Errorf("unable to read basic auth username file %s: %w", rt.usernameFile, err) } username = strings.TrimSpace(string(usernameBytes)) } else { @@ -679,7 +679,7 @@ func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, e if rt.passwordFile != "" { passwordBytes, err := os.ReadFile(rt.passwordFile) if err != nil { - return nil, fmt.Errorf("unable to read basic auth password file %s: %s", rt.passwordFile, err) + return nil, fmt.Errorf("unable to read basic auth password file %s: %w", rt.passwordFile, err) } password = strings.TrimSpace(string(passwordBytes)) } else { @@ -723,7 +723,7 @@ func (rt *oauth2RoundTripper) RoundTrip(req *http.Request) (*http.Response, erro if rt.config.ClientSecretFile != "" { data, err := os.ReadFile(rt.config.ClientSecretFile) if err != nil { - return nil, fmt.Errorf("unable to read oauth2 client secret file %s: %s", rt.config.ClientSecretFile, err) + return nil, fmt.Errorf("unable to read oauth2 client secret file %s: %w", rt.config.ClientSecretFile, err) } secret = strings.TrimSpace(string(data)) rt.mtx.RLock() @@ -977,7 +977,7 @@ func (c *TLSConfig) getClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Ce if c.CertFile != "" { certData, err = os.ReadFile(c.CertFile) if err != nil { - return nil, fmt.Errorf("unable to read specified client cert (%s): %s", c.CertFile, err) + return nil, fmt.Errorf("unable to read specified client cert (%s): %w", c.CertFile, err) } } else { certData = []byte(c.Cert) @@ -986,7 +986,7 @@ func (c *TLSConfig) getClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Ce if c.KeyFile != "" { keyData, err = os.ReadFile(c.KeyFile) if err != nil { - return nil, fmt.Errorf("unable to read specified client key (%s): %s", c.KeyFile, err) + return nil, fmt.Errorf("unable to read specified client key (%s): %w", c.KeyFile, err) } } else { keyData = []byte(c.Key) @@ -994,7 +994,7 @@ func (c *TLSConfig) getClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Ce cert, err := tls.X509KeyPair(certData, keyData) if err != nil { - return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %s", c.CertFile, c.KeyFile, err) + return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %w", c.CertFile, c.KeyFile, err) } return &cert, nil @@ -1004,7 +1004,7 @@ func (c *TLSConfig) getClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Ce func readCAFile(f string) ([]byte, error) { data, err := os.ReadFile(f) if err != nil { - return nil, fmt.Errorf("unable to load specified CA cert %s: %s", f, err) + return nil, fmt.Errorf("unable to load specified CA cert %s: %w", f, err) } return data, nil } diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index 0ca86a3dc..a909b171c 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -14,6 +14,7 @@ package expfmt import ( + "bufio" "fmt" "io" "math" @@ -21,8 +22,8 @@ import ( "net/http" dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/encoding/protodelim" - "github.com/matttproud/golang_protobuf_extensions/v2/pbutil" "github.com/prometheus/common/model" ) @@ -86,8 +87,10 @@ type protoDecoder struct { // Decode implements the Decoder interface. func (d *protoDecoder) Decode(v *dto.MetricFamily) error { - _, err := pbutil.ReadDelimited(d.r, v) - if err != nil { + opts := protodelim.UnmarshalOptions{ + MaxSize: -1, + } + if err := opts.UnmarshalFrom(bufio.NewReader(d.r), v); err != nil { return err } if !model.IsValidMetricName(model.LabelValue(v.GetName())) { diff --git a/vendor/github.com/prometheus/common/expfmt/encode.go b/vendor/github.com/prometheus/common/expfmt/encode.go index ca2140600..02b7a5e81 100644 --- a/vendor/github.com/prometheus/common/expfmt/encode.go +++ b/vendor/github.com/prometheus/common/expfmt/encode.go @@ -18,10 +18,11 @@ import ( "io" "net/http" - "github.com/matttproud/golang_protobuf_extensions/v2/pbutil" - "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg" + "google.golang.org/protobuf/encoding/protodelim" "google.golang.org/protobuf/encoding/prototext" + "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg" + dto "github.com/prometheus/client_model/go" ) @@ -120,7 +121,7 @@ func NewEncoder(w io.Writer, format Format) Encoder { case FmtProtoDelim: return encoderCloser{ encode: func(v *dto.MetricFamily) error { - _, err := pbutil.WriteDelimited(w, v) + _, err := protodelim.MarshalTo(w, v) return err }, close: func() error { return nil }, diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go index 35db1cc9d..26490211a 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_parse.go +++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go @@ -16,6 +16,7 @@ package expfmt import ( "bufio" "bytes" + "errors" "fmt" "io" "math" @@ -24,8 +25,9 @@ import ( dto "github.com/prometheus/client_model/go" - "github.com/prometheus/common/model" "google.golang.org/protobuf/proto" + + "github.com/prometheus/common/model" ) // A stateFn is a function that represents a state in a state machine. By @@ -112,7 +114,7 @@ func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricF // stream. Turn this error into something nicer and more // meaningful. (io.EOF is often used as a signal for the legitimate end // of an input stream.) - if p.err == io.EOF { + if p.err != nil && errors.Is(p.err, io.EOF) { p.parseError("unexpected end of input stream") } return p.metricFamiliesByName, p.err @@ -146,7 +148,7 @@ func (p *TextParser) startOfLine() stateFn { // which is not an error but the signal that we are done. // Any other error that happens to align with the start of // a line is still an error. - if p.err == io.EOF { + if errors.Is(p.err, io.EOF) { p.err = nil } return nil diff --git a/vendor/github.com/prometheus/common/model/alert.go b/vendor/github.com/prometheus/common/model/alert.go index 35e739c7a..178fdbaf6 100644 --- a/vendor/github.com/prometheus/common/model/alert.go +++ b/vendor/github.com/prometheus/common/model/alert.go @@ -90,13 +90,13 @@ func (a *Alert) Validate() error { return fmt.Errorf("start time must be before end time") } if err := a.Labels.Validate(); err != nil { - return fmt.Errorf("invalid label set: %s", err) + return fmt.Errorf("invalid label set: %w", err) } if len(a.Labels) == 0 { return fmt.Errorf("at least one label pair required") } if err := a.Annotations.Validate(); err != nil { - return fmt.Errorf("invalid annotations: %s", err) + return fmt.Errorf("invalid annotations: %w", err) } return nil } diff --git a/vendor/github.com/prometheus/common/model/metadata.go b/vendor/github.com/prometheus/common/model/metadata.go new file mode 100644 index 000000000..447ab8ad6 --- /dev/null +++ b/vendor/github.com/prometheus/common/model/metadata.go @@ -0,0 +1,28 @@ +// Copyright 2023 The Prometheus 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 model + +// MetricType represents metric type values. +type MetricType string + +const ( + MetricTypeCounter = MetricType("counter") + MetricTypeGauge = MetricType("gauge") + MetricTypeHistogram = MetricType("histogram") + MetricTypeGaugeHistogram = MetricType("gaugehistogram") + MetricTypeSummary = MetricType("summary") + MetricTypeInfo = MetricType("info") + MetricTypeStateset = MetricType("stateset") + MetricTypeUnknown = MetricType("unknown") +) diff --git a/vendor/github.com/prometheus/common/model/metric.go b/vendor/github.com/prometheus/common/model/metric.go index 00804b7fe..f8c5eabaa 100644 --- a/vendor/github.com/prometheus/common/model/metric.go +++ b/vendor/github.com/prometheus/common/model/metric.go @@ -20,12 +20,10 @@ import ( "strings" ) -var ( - // MetricNameRE is a regular expression matching valid metric - // names. Note that the IsValidMetricName function performs the same - // check but faster than a match with this regular expression. - MetricNameRE = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`) -) +// MetricNameRE is a regular expression matching valid metric +// names. Note that the IsValidMetricName function performs the same +// check but faster than a match with this regular expression. +var MetricNameRE = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`) // A Metric is similar to a LabelSet, but the key difference is that a Metric is // a singleton and refers to one and only one stream of samples. diff --git a/vendor/github.com/prometheus/common/model/signature.go b/vendor/github.com/prometheus/common/model/signature.go index 8762b13c6..dc8a0026c 100644 --- a/vendor/github.com/prometheus/common/model/signature.go +++ b/vendor/github.com/prometheus/common/model/signature.go @@ -22,10 +22,8 @@ import ( // when calculating their combined hash value (aka signature aka fingerprint). const SeparatorByte byte = 255 -var ( - // cache the signature of an empty label set. - emptyLabelSignature = hashNew() -) +// cache the signature of an empty label set. +var emptyLabelSignature = hashNew() // LabelsToSignature returns a quasi-unique signature (i.e., fingerprint) for a // given label set. (Collisions are possible but unlikely if the number of label diff --git a/vendor/github.com/prometheus/common/model/silence.go b/vendor/github.com/prometheus/common/model/silence.go index bb99889d2..910b0b71f 100644 --- a/vendor/github.com/prometheus/common/model/silence.go +++ b/vendor/github.com/prometheus/common/model/silence.go @@ -81,7 +81,7 @@ func (s *Silence) Validate() error { } for _, m := range s.Matchers { if err := m.Validate(); err != nil { - return fmt.Errorf("invalid matcher: %s", err) + return fmt.Errorf("invalid matcher: %w", err) } } if s.StartsAt.IsZero() { diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go index 9eb440413..8050637d8 100644 --- a/vendor/github.com/prometheus/common/model/value.go +++ b/vendor/github.com/prometheus/common/model/value.go @@ -21,14 +21,12 @@ import ( "strings" ) -var ( - // ZeroSample is the pseudo zero-value of Sample used to signal a - // non-existing sample. It is a Sample with timestamp Earliest, value 0.0, - // and metric nil. Note that the natural zero value of Sample has a timestamp - // of 0, which is possible to appear in a real Sample and thus not suitable - // to signal a non-existing Sample. - ZeroSample = Sample{Timestamp: Earliest} -) +// ZeroSample is the pseudo zero-value of Sample used to signal a +// non-existing sample. It is a Sample with timestamp Earliest, value 0.0, +// and metric nil. Note that the natural zero value of Sample has a timestamp +// of 0, which is possible to appear in a real Sample and thus not suitable +// to signal a non-existing Sample. +var ZeroSample = Sample{Timestamp: Earliest} // Sample is a sample pair associated with a metric. A single sample must either // define Value or Histogram but not both. Histogram == nil implies the Value @@ -274,7 +272,7 @@ func (s *Scalar) UnmarshalJSON(b []byte) error { value, err := strconv.ParseFloat(f, 64) if err != nil { - return fmt.Errorf("error parsing sample value: %s", err) + return fmt.Errorf("error parsing sample value: %w", err) } s.Value = SampleValue(value) return nil diff --git a/vendor/github.com/prometheus/common/model/value_float.go b/vendor/github.com/prometheus/common/model/value_float.go index 0f615a705..ae35cc2ab 100644 --- a/vendor/github.com/prometheus/common/model/value_float.go +++ b/vendor/github.com/prometheus/common/model/value_float.go @@ -20,14 +20,12 @@ import ( "strconv" ) -var ( - // ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a - // non-existing sample pair. It is a SamplePair with timestamp Earliest and - // value 0.0. Note that the natural zero value of SamplePair has a timestamp - // of 0, which is possible to appear in a real SamplePair and thus not - // suitable to signal a non-existing SamplePair. - ZeroSamplePair = SamplePair{Timestamp: Earliest} -) +// ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a +// non-existing sample pair. It is a SamplePair with timestamp Earliest and +// value 0.0. Note that the natural zero value of SamplePair has a timestamp +// of 0, which is possible to appear in a real SamplePair and thus not +// suitable to signal a non-existing SamplePair. +var ZeroSamplePair = SamplePair{Timestamp: Earliest} // A SampleValue is a representation of a value for a given sample at a given // time. diff --git a/vendor/github.com/prometheus/common/version/info.go b/vendor/github.com/prometheus/common/version/info.go index 00caa0ba4..28884dbc3 100644 --- a/vendor/github.com/prometheus/common/version/info.go +++ b/vendor/github.com/prometheus/common/version/info.go @@ -48,12 +48,12 @@ func NewCollector(program string) prometheus.Collector { ), ConstLabels: prometheus.Labels{ "version": Version, - "revision": getRevision(), + "revision": GetRevision(), "branch": Branch, "goversion": GoVersion, "goos": GoOS, "goarch": GoArch, - "tags": getTags(), + "tags": GetTags(), }, }, func() float64 { return 1 }, @@ -75,13 +75,13 @@ func Print(program string) string { m := map[string]string{ "program": program, "version": Version, - "revision": getRevision(), + "revision": GetRevision(), "branch": Branch, "buildUser": BuildUser, "buildDate": BuildDate, "goVersion": GoVersion, "platform": GoOS + "/" + GoArch, - "tags": getTags(), + "tags": GetTags(), } t := template.Must(template.New("version").Parse(versionInfoTmpl)) @@ -94,10 +94,10 @@ func Print(program string) string { // Info returns version, branch and revision information. func Info() string { - return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, getRevision()) + return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, GetRevision()) } // BuildContext returns goVersion, platform, buildUser and buildDate information. func BuildContext() string { - return fmt.Sprintf("(go=%s, platform=%s, user=%s, date=%s, tags=%s)", GoVersion, GoOS+"/"+GoArch, BuildUser, BuildDate, getTags()) + return fmt.Sprintf("(go=%s, platform=%s, user=%s, date=%s, tags=%s)", GoVersion, GoOS+"/"+GoArch, BuildUser, BuildDate, GetTags()) } diff --git a/vendor/github.com/prometheus/common/version/info_default.go b/vendor/github.com/prometheus/common/version/info_default.go index 8eb3a0bf1..684996f10 100644 --- a/vendor/github.com/prometheus/common/version/info_default.go +++ b/vendor/github.com/prometheus/common/version/info_default.go @@ -16,7 +16,7 @@ package version -func getRevision() string { +func GetRevision() string { return Revision } diff --git a/vendor/github.com/prometheus/common/version/info_go118.go b/vendor/github.com/prometheus/common/version/info_go118.go index bfc7d4103..992623c6c 100644 --- a/vendor/github.com/prometheus/common/version/info_go118.go +++ b/vendor/github.com/prometheus/common/version/info_go118.go @@ -18,17 +18,19 @@ package version import "runtime/debug" -var computedRevision string -var computedTags string +var ( + computedRevision string + computedTags string +) -func getRevision() string { +func GetRevision() string { if Revision != "" { return Revision } return computedRevision } -func getTags() string { +func GetTags() string { return computedTags } diff --git a/vendor/github.com/prometheus/procfs/Makefile.common b/vendor/github.com/prometheus/procfs/Makefile.common index 0ce7ea461..062a28185 100644 --- a/vendor/github.com/prometheus/procfs/Makefile.common +++ b/vendor/github.com/prometheus/procfs/Makefile.common @@ -61,7 +61,7 @@ PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_ SKIP_GOLANGCI_LINT := GOLANGCI_LINT := GOLANGCI_LINT_OPTS ?= -GOLANGCI_LINT_VERSION ?= v1.53.3 +GOLANGCI_LINT_VERSION ?= v1.54.2 # golangci-lint only supports linux, darwin and windows platforms on i386/amd64. # windows isn't included here because of the path separator being different. ifeq ($(GOHOSTOS),$(filter $(GOHOSTOS),linux darwin)) diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go index 13d74e395..134767d69 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build netbsd || openbsd || solaris || windows || nostatfs -// +build netbsd openbsd solaris windows nostatfs +//go:build !freebsd && !linux +// +build !freebsd,!linux package procfs diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_type.go b/vendor/github.com/prometheus/procfs/fs_statfs_type.go index bee151445..80df79c31 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_type.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_type.go @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build !netbsd && !openbsd && !solaris && !windows && !nostatfs -// +build !netbsd,!openbsd,!solaris,!windows,!nostatfs +//go:build freebsd || linux +// +build freebsd linux package procfs diff --git a/vendor/github.com/prometheus/procfs/mountstats.go b/vendor/github.com/prometheus/procfs/mountstats.go index 852c8c4a0..9d8af6db7 100644 --- a/vendor/github.com/prometheus/procfs/mountstats.go +++ b/vendor/github.com/prometheus/procfs/mountstats.go @@ -44,6 +44,14 @@ const ( fieldTransport11TCPLen = 13 fieldTransport11UDPLen = 10 + + // kernel version >= 4.14 MaxLen + // See: https://elixir.bootlin.com/linux/v6.4.8/source/net/sunrpc/xprtrdma/xprt_rdma.h#L393 + fieldTransport11RDMAMaxLen = 28 + + // kernel version <= 4.2 MinLen + // See: https://elixir.bootlin.com/linux/v4.2.8/source/net/sunrpc/xprtrdma/xprt_rdma.h#L331 + fieldTransport11RDMAMinLen = 20 ) // A Mount is a device mount parsed from /proc/[pid]/mountstats. @@ -233,6 +241,33 @@ type NFSTransportStats struct { // A running counter, incremented on each request as the current size of the // pending queue. CumulativePendingQueue uint64 + + // Stats below only available with stat version 1.1. + // Transport over RDMA + + // accessed when sending a call + ReadChunkCount uint64 + WriteChunkCount uint64 + ReplyChunkCount uint64 + TotalRdmaRequest uint64 + + // rarely accessed error counters + PullupCopyCount uint64 + HardwayRegisterCount uint64 + FailedMarshalCount uint64 + BadReplyCount uint64 + MrsRecovered uint64 + MrsOrphaned uint64 + MrsAllocated uint64 + EmptySendctxQ uint64 + + // accessed when receiving a reply + TotalRdmaReply uint64 + FixupCopyCount uint64 + ReplyWaitsForSend uint64 + LocalInvNeeded uint64 + NomsgCallCount uint64 + BcallCount uint64 } // parseMountStats parses a /proc/[pid]/mountstats file and returns a slice @@ -587,14 +622,17 @@ func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats expectedLength = fieldTransport11TCPLen } else if protocol == "udp" { expectedLength = fieldTransport11UDPLen + } else if protocol == "rdma" { + expectedLength = fieldTransport11RDMAMinLen } else { return nil, fmt.Errorf("%w: invalid NFS protocol \"%s\" in stats 1.1 statement: %v", ErrFileParse, protocol, ss) } - if len(ss) != expectedLength { - return nil, fmt.Errorf("%w: invalid NFS transport stats 1.1 statement: %v", ErrFileParse, ss) + if (len(ss) != expectedLength && (protocol == "tcp" || protocol == "udp")) || + (protocol == "rdma" && len(ss) < expectedLength) { + return nil, fmt.Errorf("%w: invalid NFS transport stats 1.1 statement: %v, protocol: %v", ErrFileParse, ss, protocol) } default: - return nil, fmt.Errorf("%s: Unrecognized NFS transport stats version: %q", ErrFileParse, statVersion) + return nil, fmt.Errorf("%s: Unrecognized NFS transport stats version: %q, protocol: %v", ErrFileParse, statVersion, protocol) } // Allocate enough for v1.1 stats since zero value for v1.1 stats will be okay @@ -604,7 +642,9 @@ func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats // Note: slice length must be set to length of v1.1 stats to avoid a panic when // only v1.0 stats are present. // See: https://github.com/prometheus/node_exporter/issues/571. - ns := make([]uint64, fieldTransport11TCPLen) + // + // Note: NFS Over RDMA slice length is fieldTransport11RDMAMaxLen + ns := make([]uint64, fieldTransport11RDMAMaxLen+3) for i, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { @@ -622,9 +662,14 @@ func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats // we set them to 0 here. if protocol == "udp" { ns = append(ns[:2], append(make([]uint64, 3), ns[2:]...)...) + } else if protocol == "tcp" { + ns = append(ns[:fieldTransport11TCPLen], make([]uint64, fieldTransport11RDMAMaxLen-fieldTransport11TCPLen+3)...) + } else if protocol == "rdma" { + ns = append(ns[:fieldTransport10TCPLen], append(make([]uint64, 3), ns[fieldTransport10TCPLen:]...)...) } return &NFSTransportStats{ + // NFS xprt over tcp or udp Protocol: protocol, Port: ns[0], Bind: ns[1], @@ -636,8 +681,32 @@ func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats BadTransactionIDs: ns[7], CumulativeActiveRequests: ns[8], CumulativeBacklog: ns[9], - MaximumRPCSlotsUsed: ns[10], - CumulativeSendingQueue: ns[11], - CumulativePendingQueue: ns[12], + + // NFS xprt over tcp or udp + // And statVersion 1.1 + MaximumRPCSlotsUsed: ns[10], + CumulativeSendingQueue: ns[11], + CumulativePendingQueue: ns[12], + + // NFS xprt over rdma + // And stat Version 1.1 + ReadChunkCount: ns[13], + WriteChunkCount: ns[14], + ReplyChunkCount: ns[15], + TotalRdmaRequest: ns[16], + PullupCopyCount: ns[17], + HardwayRegisterCount: ns[18], + FailedMarshalCount: ns[19], + BadReplyCount: ns[20], + MrsRecovered: ns[21], + MrsOrphaned: ns[22], + MrsAllocated: ns[23], + EmptySendctxQ: ns[24], + TotalRdmaReply: ns[25], + FixupCopyCount: ns[26], + ReplyWaitsForSend: ns[27], + LocalInvNeeded: ns[28], + NomsgCallCount: ns[29], + BcallCount: ns[30], }, nil } diff --git a/vendor/github.com/prometheus/procfs/proc_fdinfo.go b/vendor/github.com/prometheus/procfs/proc_fdinfo.go index 4b7933e4f..fa761b352 100644 --- a/vendor/github.com/prometheus/procfs/proc_fdinfo.go +++ b/vendor/github.com/prometheus/procfs/proc_fdinfo.go @@ -26,6 +26,7 @@ var ( rPos = regexp.MustCompile(`^pos:\s+(\d+)$`) rFlags = regexp.MustCompile(`^flags:\s+(\d+)$`) rMntID = regexp.MustCompile(`^mnt_id:\s+(\d+)$`) + rIno = regexp.MustCompile(`^ino:\s+(\d+)$`) rInotify = regexp.MustCompile(`^inotify`) rInotifyParts = regexp.MustCompile(`^inotify\s+wd:([0-9a-f]+)\s+ino:([0-9a-f]+)\s+sdev:([0-9a-f]+)(?:\s+mask:([0-9a-f]+))?`) ) @@ -40,6 +41,8 @@ type ProcFDInfo struct { Flags string // Mount point ID MntID string + // Inode number + Ino string // List of inotify lines (structured) in the fdinfo file (kernel 3.8+ only) InotifyInfos []InotifyInfo } @@ -51,7 +54,7 @@ func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { return nil, err } - var text, pos, flags, mntid string + var text, pos, flags, mntid, ino string var inotify []InotifyInfo scanner := bufio.NewScanner(bytes.NewReader(data)) @@ -63,6 +66,8 @@ func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { flags = rFlags.FindStringSubmatch(text)[1] } else if rMntID.MatchString(text) { mntid = rMntID.FindStringSubmatch(text)[1] + } else if rIno.MatchString(text) { + ino = rIno.FindStringSubmatch(text)[1] } else if rInotify.MatchString(text) { newInotify, err := parseInotifyInfo(text) if err != nil { @@ -77,6 +82,7 @@ func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { Pos: pos, Flags: flags, MntID: mntid, + Ino: ino, InotifyInfos: inotify, } diff --git a/vendor/github.com/prometheus/procfs/proc_maps.go b/vendor/github.com/prometheus/procfs/proc_maps.go index 727549a13..7e75c286b 100644 --- a/vendor/github.com/prometheus/procfs/proc_maps.go +++ b/vendor/github.com/prometheus/procfs/proc_maps.go @@ -63,17 +63,17 @@ type ProcMap struct { // parseDevice parses the device token of a line and converts it to a dev_t // (mkdev) like structure. func parseDevice(s string) (uint64, error) { - toks := strings.Split(s, ":") - if len(toks) < 2 { - return 0, fmt.Errorf("%w: unexpected number of fields, expected: 2, got: %q", ErrFileParse, len(toks)) + i := strings.Index(s, ":") + if i == -1 { + return 0, fmt.Errorf("%w: expected separator `:` in %s", ErrFileParse, s) } - major, err := strconv.ParseUint(toks[0], 16, 0) + major, err := strconv.ParseUint(s[0:i], 16, 0) if err != nil { return 0, err } - minor, err := strconv.ParseUint(toks[1], 16, 0) + minor, err := strconv.ParseUint(s[i+1:], 16, 0) if err != nil { return 0, err } @@ -93,17 +93,17 @@ func parseAddress(s string) (uintptr, error) { // parseAddresses parses the start-end address. func parseAddresses(s string) (uintptr, uintptr, error) { - toks := strings.Split(s, "-") - if len(toks) < 2 { - return 0, 0, fmt.Errorf("%w: invalid address", ErrFileParse) + idx := strings.Index(s, "-") + if idx == -1 { + return 0, 0, fmt.Errorf("%w: expected separator `-` in %s", ErrFileParse, s) } - saddr, err := parseAddress(toks[0]) + saddr, err := parseAddress(s[0:idx]) if err != nil { return 0, 0, err } - eaddr, err := parseAddress(toks[1]) + eaddr, err := parseAddress(s[idx+1:]) if err != nil { return 0, 0, err } diff --git a/vendor/github.com/prometheus/procfs/proc_status.go b/vendor/github.com/prometheus/procfs/proc_status.go index c055d075d..46307f572 100644 --- a/vendor/github.com/prometheus/procfs/proc_status.go +++ b/vendor/github.com/prometheus/procfs/proc_status.go @@ -23,7 +23,7 @@ import ( ) // ProcStatus provides status information about the process, -// read from /proc/[pid]/stat. +// read from /proc/[pid]/status. type ProcStatus struct { // The process ID. PID int @@ -32,6 +32,8 @@ type ProcStatus struct { // Thread group ID. TGID int + // List of Pid namespace. + NSpids []uint64 // Peak virtual memory size. VmPeak uint64 // nolint:revive @@ -127,6 +129,8 @@ func (s *ProcStatus) fillStatus(k string, vString string, vUint uint64, vUintByt copy(s.UIDs[:], strings.Split(vString, "\t")) case "Gid": copy(s.GIDs[:], strings.Split(vString, "\t")) + case "NSpid": + s.NSpids = calcNSPidsList(vString) case "VmPeak": s.VmPeak = vUintBytes case "VmSize": @@ -200,3 +204,18 @@ func calcCpusAllowedList(cpuString string) []uint64 { sort.Slice(g, func(i, j int) bool { return g[i] < g[j] }) return g } + +func calcNSPidsList(nspidsString string) []uint64 { + s := strings.Split(nspidsString, " ") + var nspids []uint64 + + for _, nspid := range s { + nspid, _ := strconv.ParseUint(nspid, 10, 64) + if nspid == 0 { + continue + } + nspids = append(nspids, nspid) + } + + return nspids +} diff --git a/vendor/github.com/prometheus/prometheus/config/config.go b/vendor/github.com/prometheus/prometheus/config/config.go index 5c51d5a0d..7fa03a144 100644 --- a/vendor/github.com/prometheus/prometheus/config/config.go +++ b/vendor/github.com/prometheus/prometheus/config/config.go @@ -19,6 +19,7 @@ import ( "net/url" "os" "path/filepath" + "sort" "strings" "time" @@ -34,6 +35,7 @@ import ( "github.com/prometheus/prometheus/discovery" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/relabel" + "github.com/prometheus/prometheus/storage/remote/azuread" ) var ( @@ -142,17 +144,21 @@ var ( ScrapeInterval: model.Duration(1 * time.Minute), ScrapeTimeout: model.Duration(10 * time.Second), EvaluationInterval: model.Duration(1 * time.Minute), + // When native histogram feature flag is enabled, ScrapeProtocols default + // changes to DefaultNativeHistogramScrapeProtocols. + ScrapeProtocols: DefaultScrapeProtocols, } // DefaultScrapeConfig is the default scrape configuration. DefaultScrapeConfig = ScrapeConfig{ - // ScrapeTimeout and ScrapeInterval default to the - // configured globals. - MetricsPath: "/metrics", - Scheme: "http", - HonorLabels: false, - HonorTimestamps: true, - HTTPClientConfig: config.DefaultHTTPClientConfig, + // ScrapeTimeout, ScrapeInterval and ScrapeProtocols default to the configured globals. + ScrapeClassicHistograms: false, + MetricsPath: "/metrics", + Scheme: "http", + HonorLabels: false, + HonorTimestamps: true, + HTTPClientConfig: config.DefaultHTTPClientConfig, + EnableCompression: true, } // DefaultAlertmanagerConfig is the default alertmanager configuration. @@ -258,7 +264,7 @@ func (c Config) String() string { return string(b) } -// ScrapeConfigs returns the scrape configurations. +// GetScrapeConfigs returns the scrape configurations. func (c *Config) GetScrapeConfigs() ([]*ScrapeConfig, error) { scfgs := make([]*ScrapeConfig, len(c.ScrapeConfigs)) @@ -266,7 +272,7 @@ func (c *Config) GetScrapeConfigs() ([]*ScrapeConfig, error) { for i, scfg := range c.ScrapeConfigs { // We do these checks for library users that would not call Validate in // Unmarshal. - if err := scfg.Validate(c.GlobalConfig.ScrapeInterval, c.GlobalConfig.ScrapeTimeout); err != nil { + if err := scfg.Validate(c.GlobalConfig); err != nil { return nil, err } @@ -293,7 +299,7 @@ func (c *Config) GetScrapeConfigs() ([]*ScrapeConfig, error) { return nil, fileErr(filename, err) } for _, scfg := range cfg.ScrapeConfigs { - if err := scfg.Validate(c.GlobalConfig.ScrapeInterval, c.GlobalConfig.ScrapeTimeout); err != nil { + if err := scfg.Validate(c.GlobalConfig); err != nil { return nil, fileErr(filename, err) } @@ -342,7 +348,7 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { // Do global overrides and validate unique names. jobNames := map[string]struct{}{} for _, scfg := range c.ScrapeConfigs { - if err := scfg.Validate(c.GlobalConfig.ScrapeInterval, c.GlobalConfig.ScrapeTimeout); err != nil { + if err := scfg.Validate(c.GlobalConfig); err != nil { return err } @@ -383,12 +389,107 @@ type GlobalConfig struct { ScrapeInterval model.Duration `yaml:"scrape_interval,omitempty"` // The default timeout when scraping targets. ScrapeTimeout model.Duration `yaml:"scrape_timeout,omitempty"` + // The protocols to negotiate during a scrape. It tells clients what + // protocol are accepted by Prometheus and with what weight (most wanted is first). + // Supported values (case sensitive): PrometheusProto, OpenMetricsText0.0.1, + // OpenMetricsText1.0.0, PrometheusText0.0.4. + ScrapeProtocols []ScrapeProtocol `yaml:"scrape_protocols,omitempty"` // How frequently to evaluate rules by default. EvaluationInterval model.Duration `yaml:"evaluation_interval,omitempty"` // File to which PromQL queries are logged. QueryLogFile string `yaml:"query_log_file,omitempty"` // The labels to add to any timeseries that this Prometheus instance scrapes. ExternalLabels labels.Labels `yaml:"external_labels,omitempty"` + // An uncompressed response body larger than this many bytes will cause the + // scrape to fail. 0 means no limit. + BodySizeLimit units.Base2Bytes `yaml:"body_size_limit,omitempty"` + // More than this many samples post metric-relabeling will cause the scrape to + // fail. 0 means no limit. + SampleLimit uint `yaml:"sample_limit,omitempty"` + // More than this many targets after the target relabeling will cause the + // scrapes to fail. 0 means no limit. + TargetLimit uint `yaml:"target_limit,omitempty"` + // More than this many labels post metric-relabeling will cause the scrape to + // fail. 0 means no limit. + LabelLimit uint `yaml:"label_limit,omitempty"` + // More than this label name length post metric-relabeling will cause the + // scrape to fail. 0 means no limit. + LabelNameLengthLimit uint `yaml:"label_name_length_limit,omitempty"` + // More than this label value length post metric-relabeling will cause the + // scrape to fail. 0 means no limit. + LabelValueLengthLimit uint `yaml:"label_value_length_limit,omitempty"` + // Keep no more than this many dropped targets per job. + // 0 means no limit. + KeepDroppedTargets uint `yaml:"keep_dropped_targets,omitempty"` +} + +// ScrapeProtocol represents supported protocol for scraping metrics. +type ScrapeProtocol string + +// Validate returns error if given scrape protocol is not supported. +func (s ScrapeProtocol) Validate() error { + if _, ok := ScrapeProtocolsHeaders[s]; !ok { + return fmt.Errorf("unknown scrape protocol %v, supported: %v", + s, func() (ret []string) { + for k := range ScrapeProtocolsHeaders { + ret = append(ret, string(k)) + } + sort.Strings(ret) + return ret + }()) + } + return nil +} + +var ( + PrometheusProto ScrapeProtocol = "PrometheusProto" + PrometheusText0_0_4 ScrapeProtocol = "PrometheusText0.0.4" + OpenMetricsText0_0_1 ScrapeProtocol = "OpenMetricsText0.0.1" + OpenMetricsText1_0_0 ScrapeProtocol = "OpenMetricsText1.0.0" + + ScrapeProtocolsHeaders = map[ScrapeProtocol]string{ + PrometheusProto: "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", + PrometheusText0_0_4: "text/plain;version=0.0.4", + OpenMetricsText0_0_1: "application/openmetrics-text;version=0.0.1", + OpenMetricsText1_0_0: "application/openmetrics-text;version=1.0.0", + } + + // DefaultScrapeProtocols is the set of scrape protocols that will be proposed + // to scrape target, ordered by priority. + DefaultScrapeProtocols = []ScrapeProtocol{ + OpenMetricsText1_0_0, + OpenMetricsText0_0_1, + PrometheusText0_0_4, + } + + // DefaultProtoFirstScrapeProtocols is like DefaultScrapeProtocols, but it + // favors protobuf Prometheus exposition format. + // Used by default for certain feature-flags like + // "native-histograms" and "created-timestamp-zero-ingestion". + DefaultProtoFirstScrapeProtocols = []ScrapeProtocol{ + PrometheusProto, + OpenMetricsText1_0_0, + OpenMetricsText0_0_1, + PrometheusText0_0_4, + } +) + +// validateAcceptScrapeProtocols return errors if we see problems with accept scrape protocols option. +func validateAcceptScrapeProtocols(sps []ScrapeProtocol) error { + if len(sps) == 0 { + return errors.New("scrape_protocols cannot be empty") + } + dups := map[string]struct{}{} + for _, sp := range sps { + if _, ok := dups[strings.ToLower(string(sp))]; ok { + return fmt.Errorf("duplicated protocol in scrape_protocols, got %v", sps) + } + if err := sp.Validate(); err != nil { + return fmt.Errorf("scrape_protocols: %w", err) + } + dups[strings.ToLower(string(sp))] = struct{}{} + } + return nil } // SetDirectory joins any relative file paths with dir. @@ -436,6 +537,14 @@ func (c *GlobalConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if gc.EvaluationInterval == 0 { gc.EvaluationInterval = DefaultGlobalConfig.EvaluationInterval } + + if gc.ScrapeProtocols == nil { + gc.ScrapeProtocols = DefaultGlobalConfig.ScrapeProtocols + } + if err := validateAcceptScrapeProtocols(gc.ScrapeProtocols); err != nil { + return fmt.Errorf("%w for global config", err) + } + *c = *gc return nil } @@ -446,7 +555,8 @@ func (c *GlobalConfig) isZero() bool { c.ScrapeInterval == 0 && c.ScrapeTimeout == 0 && c.EvaluationInterval == 0 && - c.QueryLogFile == "" + c.QueryLogFile == "" && + c.ScrapeProtocols == nil } type ScrapeConfigs struct { @@ -461,34 +571,54 @@ type ScrapeConfig struct { HonorLabels bool `yaml:"honor_labels,omitempty"` // Indicator whether the scraped timestamps should be respected. HonorTimestamps bool `yaml:"honor_timestamps"` + // Indicator whether to track the staleness of the scraped timestamps. + TrackTimestampsStaleness bool `yaml:"track_timestamps_staleness"` // A set of query parameters with which the target is scraped. Params url.Values `yaml:"params,omitempty"` // How frequently to scrape the targets of this scrape config. ScrapeInterval model.Duration `yaml:"scrape_interval,omitempty"` // The timeout for scraping targets of this config. ScrapeTimeout model.Duration `yaml:"scrape_timeout,omitempty"` + // The protocols to negotiate during a scrape. It tells clients what + // protocol are accepted by Prometheus and with what preference (most wanted is first). + // Supported values (case sensitive): PrometheusProto, OpenMetricsText0.0.1, + // OpenMetricsText1.0.0, PrometheusText0.0.4. + ScrapeProtocols []ScrapeProtocol `yaml:"scrape_protocols,omitempty"` + // Whether to scrape a classic histogram that is also exposed as a native histogram. + ScrapeClassicHistograms bool `yaml:"scrape_classic_histograms,omitempty"` // The HTTP resource path on which to fetch metrics from targets. MetricsPath string `yaml:"metrics_path,omitempty"` // The URL scheme with which to fetch metrics from targets. Scheme string `yaml:"scheme,omitempty"` + // Indicator whether to request compressed response from the target. + EnableCompression bool `yaml:"enable_compression"` // An uncompressed response body larger than this many bytes will cause the // scrape to fail. 0 means no limit. BodySizeLimit units.Base2Bytes `yaml:"body_size_limit,omitempty"` // More than this many samples post metric-relabeling will cause the scrape to - // fail. + // fail. 0 means no limit. SampleLimit uint `yaml:"sample_limit,omitempty"` // More than this many targets after the target relabeling will cause the - // scrapes to fail. + // scrapes to fail. 0 means no limit. TargetLimit uint `yaml:"target_limit,omitempty"` // More than this many labels post metric-relabeling will cause the scrape to - // fail. + // fail. 0 means no limit. LabelLimit uint `yaml:"label_limit,omitempty"` // More than this label name length post metric-relabeling will cause the - // scrape to fail. + // scrape to fail. 0 means no limit. LabelNameLengthLimit uint `yaml:"label_name_length_limit,omitempty"` // More than this label value length post metric-relabeling will cause the - // scrape to fail. + // scrape to fail. 0 means no limit. LabelValueLengthLimit uint `yaml:"label_value_length_limit,omitempty"` + // If there are more than this many buckets in a native histogram, + // buckets will be merged to stay within the limit. + NativeHistogramBucketLimit uint `yaml:"native_histogram_bucket_limit,omitempty"` + // If the growth factor of one bucket to the next is smaller than this, + // buckets will be merged to increase the factor sufficiently. + NativeHistogramMinBucketFactor float64 `yaml:"native_histogram_min_bucket_factor,omitempty"` + // Keep no more than this many dropped targets per job. + // 0 means no limit. + KeepDroppedTargets uint `yaml:"keep_dropped_targets,omitempty"` // We cannot do proper Go type embedding below as the parser will then parse // values arbitrarily into the overflow maps of further-down types. @@ -546,25 +676,55 @@ func (c *ScrapeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return nil } -func (c *ScrapeConfig) Validate(defaultInterval, defaultTimeout model.Duration) error { +// Validate validates scrape config, but also fills relevant default values from global config if needed. +func (c *ScrapeConfig) Validate(globalConfig GlobalConfig) error { if c == nil { return errors.New("empty or null scrape config section") } // First set the correct scrape interval, then check that the timeout // (inferred or explicit) is not greater than that. if c.ScrapeInterval == 0 { - c.ScrapeInterval = defaultInterval + c.ScrapeInterval = globalConfig.ScrapeInterval } if c.ScrapeTimeout > c.ScrapeInterval { return fmt.Errorf("scrape timeout greater than scrape interval for scrape config with job name %q", c.JobName) } if c.ScrapeTimeout == 0 { - if defaultTimeout > c.ScrapeInterval { + if globalConfig.ScrapeTimeout > c.ScrapeInterval { c.ScrapeTimeout = c.ScrapeInterval } else { - c.ScrapeTimeout = defaultTimeout + c.ScrapeTimeout = globalConfig.ScrapeTimeout } } + if c.BodySizeLimit == 0 { + c.BodySizeLimit = globalConfig.BodySizeLimit + } + if c.SampleLimit == 0 { + c.SampleLimit = globalConfig.SampleLimit + } + if c.TargetLimit == 0 { + c.TargetLimit = globalConfig.TargetLimit + } + if c.LabelLimit == 0 { + c.LabelLimit = globalConfig.LabelLimit + } + if c.LabelNameLengthLimit == 0 { + c.LabelNameLengthLimit = globalConfig.LabelNameLengthLimit + } + if c.LabelValueLengthLimit == 0 { + c.LabelValueLengthLimit = globalConfig.LabelValueLengthLimit + } + if c.KeepDroppedTargets == 0 { + c.KeepDroppedTargets = globalConfig.KeepDroppedTargets + } + + if c.ScrapeProtocols == nil { + c.ScrapeProtocols = globalConfig.ScrapeProtocols + } + if err := validateAcceptScrapeProtocols(c.ScrapeProtocols); err != nil { + return fmt.Errorf("%w for scrape config with job name %q", err, c.JobName) + } + return nil } @@ -766,6 +926,7 @@ type AlertmanagerConfig struct { ServiceDiscoveryConfigs discovery.Configs `yaml:"-"` HTTPClientConfig config.HTTPClientConfig `yaml:",inline"` + SigV4Config *sigv4.SigV4Config `yaml:"sigv4,omitempty"` // The URL scheme to use when talking to Alertmanagers. Scheme string `yaml:"scheme,omitempty"` @@ -801,6 +962,13 @@ func (c *AlertmanagerConfig) UnmarshalYAML(unmarshal func(interface{}) error) er return err } + httpClientConfigAuthEnabled := c.HTTPClientConfig.BasicAuth != nil || + c.HTTPClientConfig.Authorization != nil || c.HTTPClientConfig.OAuth2 != nil + + if httpClientConfigAuthEnabled && c.SigV4Config != nil { + return fmt.Errorf("at most one of basic_auth, authorization, oauth2, & sigv4 must be configured") + } + // Check for users putting URLs in target groups. if len(c.RelabelConfigs) == 0 { if err := checkStaticTargets(c.ServiceDiscoveryConfigs); err != nil { @@ -864,6 +1032,7 @@ type RemoteWriteConfig struct { QueueConfig QueueConfig `yaml:"queue_config,omitempty"` MetadataConfig MetadataConfig `yaml:"metadata_config,omitempty"` SigV4Config *sigv4.SigV4Config `yaml:"sigv4,omitempty"` + AzureADConfig *azuread.AzureADConfig `yaml:"azuread,omitempty"` } // SetDirectory joins any relative file paths with dir. @@ -900,8 +1069,12 @@ func (c *RemoteWriteConfig) UnmarshalYAML(unmarshal func(interface{}) error) err httpClientConfigAuthEnabled := c.HTTPClientConfig.BasicAuth != nil || c.HTTPClientConfig.Authorization != nil || c.HTTPClientConfig.OAuth2 != nil - if httpClientConfigAuthEnabled && c.SigV4Config != nil { - return fmt.Errorf("at most one of basic_auth, authorization, oauth2, & sigv4 must be configured") + if httpClientConfigAuthEnabled && (c.SigV4Config != nil || c.AzureADConfig != nil) { + return fmt.Errorf("at most one of basic_auth, authorization, oauth2, sigv4, & azuread must be configured") + } + + if c.SigV4Config != nil && c.AzureADConfig != nil { + return fmt.Errorf("at most one of basic_auth, authorization, oauth2, sigv4, & azuread must be configured") } return nil @@ -922,7 +1095,7 @@ func validateHeadersForTracing(headers map[string]string) error { func validateHeaders(headers map[string]string) error { for header := range headers { if strings.ToLower(header) == "authorization" { - return errors.New("authorization header must be changed via the basic_auth, authorization, oauth2, or sigv4 parameter") + return errors.New("authorization header must be changed via the basic_auth, authorization, oauth2, sigv4, or azuread parameter") } if _, ok := reservedHeaders[strings.ToLower(header)]; ok { return fmt.Errorf("%s is a reserved header. It must not be changed", header) @@ -954,6 +1127,9 @@ type QueueConfig struct { MinBackoff model.Duration `yaml:"min_backoff,omitempty"` MaxBackoff model.Duration `yaml:"max_backoff,omitempty"` RetryOnRateLimit bool `yaml:"retry_on_http_429,omitempty"` + + // Samples older than the limit will be dropped. + SampleAgeLimit model.Duration `yaml:"sample_age_limit,omitempty"` } // MetadataConfig is the configuration for sending metadata to remote diff --git a/vendor/github.com/prometheus/prometheus/discovery/README.md b/vendor/github.com/prometheus/prometheus/discovery/README.md index 19b579b39..4c0660862 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/README.md +++ b/vendor/github.com/prometheus/prometheus/discovery/README.md @@ -234,6 +234,11 @@ type Config interface { type DiscovererOptions struct { Logger log.Logger + + // A registerer for the Discoverer's metrics. + Registerer prometheus.Registerer + + HTTPClientOptions []config.HTTPClientOption } ``` diff --git a/vendor/github.com/prometheus/prometheus/discovery/aws/ec2.go b/vendor/github.com/prometheus/prometheus/discovery/aws/ec2.go index 86d76627e..aa79fd9c6 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/aws/ec2.go +++ b/vendor/github.com/prometheus/prometheus/discovery/aws/ec2.go @@ -30,6 +30,7 @@ import ( "github.com/aws/aws-sdk-go/service/ec2" "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -96,12 +97,19 @@ type EC2SDConfig struct { HTTPClientConfig config.HTTPClientConfig `yaml:",inline"` } +// NewDiscovererMetrics implements discovery.Config. +func (*EC2SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &ec2Metrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the EC2 Config. func (*EC2SDConfig) Name() string { return "ec2" } // NewDiscoverer returns a Discoverer for the EC2 Config. func (c *EC2SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewEC2Discovery(c, opts.Logger), nil + return NewEC2Discovery(c, opts.Logger, opts.Metrics) } // UnmarshalYAML implements the yaml.Unmarshaler interface for the EC2 Config. @@ -129,7 +137,7 @@ func (c *EC2SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return errors.New("EC2 SD configuration filter values cannot be empty") } } - return nil + return c.HTTPClientConfig.Validate() } // EC2Discovery periodically performs EC2-SD requests. It implements @@ -147,7 +155,12 @@ type EC2Discovery struct { } // NewEC2Discovery returns a new EC2Discovery which periodically refreshes its targets. -func NewEC2Discovery(conf *EC2SDConfig, logger log.Logger) *EC2Discovery { +func NewEC2Discovery(conf *EC2SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*EC2Discovery, error) { + m, ok := metrics.(*ec2Metrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } @@ -156,12 +169,15 @@ func NewEC2Discovery(conf *EC2SDConfig, logger log.Logger) *EC2Discovery { cfg: conf, } d.Discovery = refresh.NewDiscovery( - logger, - "ec2", - time.Duration(d.cfg.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "ec2", + Interval: time.Duration(d.cfg.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) - return d + return d, nil } func (d *EC2Discovery) ec2Client(context.Context) (*ec2.EC2, error) { diff --git a/vendor/github.com/prometheus/prometheus/discovery/aws/lightsail.go b/vendor/github.com/prometheus/prometheus/discovery/aws/lightsail.go index e671769ca..86b138be5 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/aws/lightsail.go +++ b/vendor/github.com/prometheus/prometheus/discovery/aws/lightsail.go @@ -29,6 +29,7 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/lightsail" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -79,12 +80,19 @@ type LightsailSDConfig struct { HTTPClientConfig config.HTTPClientConfig `yaml:",inline"` } +// NewDiscovererMetrics implements discovery.Config. +func (*LightsailSDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &lightsailMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Lightsail Config. func (*LightsailSDConfig) Name() string { return "lightsail" } // NewDiscoverer returns a Discoverer for the Lightsail Config. func (c *LightsailSDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewLightsailDiscovery(c, opts.Logger), nil + return NewLightsailDiscovery(c, opts.Logger, opts.Metrics) } // UnmarshalYAML implements the yaml.Unmarshaler interface for the Lightsail Config. @@ -109,7 +117,7 @@ func (c *LightsailSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) err } c.Region = region } - return nil + return c.HTTPClientConfig.Validate() } // LightsailDiscovery periodically performs Lightsail-SD requests. It implements @@ -121,20 +129,29 @@ type LightsailDiscovery struct { } // NewLightsailDiscovery returns a new LightsailDiscovery which periodically refreshes its targets. -func NewLightsailDiscovery(conf *LightsailSDConfig, logger log.Logger) *LightsailDiscovery { +func NewLightsailDiscovery(conf *LightsailSDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*LightsailDiscovery, error) { + m, ok := metrics.(*lightsailMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } + d := &LightsailDiscovery{ cfg: conf, } d.Discovery = refresh.NewDiscovery( - logger, - "lightsail", - time.Duration(d.cfg.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "lightsail", + Interval: time.Duration(d.cfg.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) - return d + return d, nil } func (d *LightsailDiscovery) lightsailClient() (*lightsail.Lightsail, error) { diff --git a/vendor/github.com/prometheus/prometheus/discovery/aws/metrics_ec2.go b/vendor/github.com/prometheus/prometheus/discovery/aws/metrics_ec2.go new file mode 100644 index 000000000..73c061c3d --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/aws/metrics_ec2.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 aws + +import ( + "github.com/prometheus/prometheus/discovery" +) + +type ec2Metrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +var _ discovery.DiscovererMetrics = (*ec2Metrics)(nil) + +// Register implements discovery.DiscovererMetrics. +func (m *ec2Metrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *ec2Metrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/aws/metrics_lightsail.go b/vendor/github.com/prometheus/prometheus/discovery/aws/metrics_lightsail.go new file mode 100644 index 000000000..69593e701 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/aws/metrics_lightsail.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 aws + +import ( + "github.com/prometheus/prometheus/discovery" +) + +type lightsailMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +var _ discovery.DiscovererMetrics = (*lightsailMetrics)(nil) + +// Register implements discovery.DiscovererMetrics. +func (m *lightsailMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *lightsailMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/azure/azure.go b/vendor/github.com/prometheus/prometheus/discovery/azure/azure.go index 098fbb4c5..a5d81f4ff 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/azure/azure.go +++ b/vendor/github.com/prometheus/prometheus/discovery/azure/azure.go @@ -17,21 +17,28 @@ import ( "context" "errors" "fmt" + "math/rand" "net" "net/http" "strings" "sync" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" + "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/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4" + cache "github.com/Code-Hex/go-generics-cache" + "github.com/Code-Hex/go-generics-cache/policy/lru" "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" config_util "github.com/prometheus/common/config" + "github.com/prometheus/common/model" "github.com/prometheus/common/version" @@ -68,21 +75,34 @@ var ( DefaultSDConfig = SDConfig{ Port: 80, RefreshInterval: model.Duration(5 * time.Minute), - Environment: azure.PublicCloud.Name, + Environment: "AzurePublicCloud", AuthenticationMethod: authMethodOAuth, HTTPClientConfig: config_util.DefaultHTTPClientConfig, } - - failuresCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Name: "prometheus_sd_azure_failures_total", - Help: "Number of Azure service discovery refresh failures.", - }) ) +var environments = map[string]cloud.Configuration{ + "AZURECHINACLOUD": cloud.AzureChina, + "AZURECLOUD": cloud.AzurePublic, + "AZUREGERMANCLOUD": cloud.AzurePublic, + "AZUREPUBLICCLOUD": cloud.AzurePublic, + "AZUREUSGOVERNMENT": cloud.AzureGovernment, + "AZUREUSGOVERNMENTCLOUD": cloud.AzureGovernment, +} + +// CloudConfigurationFromName returns cloud configuration based on the common name specified. +func CloudConfigurationFromName(name string) (cloud.Configuration, error) { + name = strings.ToUpper(name) + env, ok := environments[name] + if !ok { + return env, fmt.Errorf("there is no cloud configuration matching the name %q", name) + } + + return env, nil +} + func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(failuresCount) } // SDConfig is the configuration for Azure based service discovery. @@ -100,12 +120,17 @@ type SDConfig struct { HTTPClientConfig config_util.HTTPClientConfig `yaml:",inline"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "azure" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger), nil + return NewDiscovery(c, opts.Logger, opts.Metrics) } func validateAuthParam(param, name string) error { @@ -123,7 +148,6 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if err != nil { return err } - if err = validateAuthParam(c.SubscriptionID, "subscription_id"); err != nil { return err } @@ -144,114 +168,137 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return fmt.Errorf("unknown authentication_type %q. Supported types are %q or %q", c.AuthenticationMethod, authMethodOAuth, authMethodManagedIdentity) } - return nil + return c.HTTPClientConfig.Validate() } type Discovery struct { *refresh.Discovery - logger log.Logger - cfg *SDConfig - port int + logger log.Logger + cfg *SDConfig + port int + cache *cache.Cache[string, *armnetwork.Interface] + metrics *azureMetrics } // NewDiscovery returns a new AzureDiscovery which periodically refreshes its targets. -func NewDiscovery(cfg *SDConfig, logger log.Logger) *Discovery { +func NewDiscovery(cfg *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*azureMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } + l := cache.New(cache.AsLRU[string, *armnetwork.Interface](lru.WithCapacity(5000))) d := &Discovery{ - cfg: cfg, - port: cfg.Port, - logger: logger, + cfg: cfg, + port: cfg.Port, + logger: logger, + cache: l, + metrics: m, } + d.Discovery = refresh.NewDiscovery( - logger, - "azure", - time.Duration(cfg.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "azure", + Interval: time.Duration(cfg.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) - return d + + return d, nil } // azureClient represents multiple Azure Resource Manager providers. type azureClient struct { - nic network.InterfacesClient - vm compute.VirtualMachinesClient - vmss compute.VirtualMachineScaleSetsClient - vmssvm compute.VirtualMachineScaleSetVMsClient + nic *armnetwork.InterfacesClient + vm *armcompute.VirtualMachinesClient + vmss *armcompute.VirtualMachineScaleSetsClient + vmssvm *armcompute.VirtualMachineScaleSetVMsClient + logger log.Logger } // createAzureClient is a helper function for creating an Azure compute client to ARM. func createAzureClient(cfg SDConfig) (azureClient, error) { - env, err := azure.EnvironmentFromName(cfg.Environment) + cloudConfiguration, err := CloudConfigurationFromName(cfg.Environment) if err != nil { return azureClient{}, err } - activeDirectoryEndpoint := env.ActiveDirectoryEndpoint - resourceManagerEndpoint := env.ResourceManagerEndpoint - var c azureClient - var spt *adal.ServicePrincipalToken - - switch cfg.AuthenticationMethod { - case authMethodManagedIdentity: - spt, err = adal.NewServicePrincipalTokenFromManagedIdentity(resourceManagerEndpoint, &adal.ManagedIdentityOptions{ClientID: cfg.ClientID}) - if err != nil { - return azureClient{}, err - } - case authMethodOAuth: - oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, cfg.TenantID) - if err != nil { - return azureClient{}, err - } + telemetry := policy.TelemetryOptions{ + ApplicationID: userAgent, + } - spt, err = adal.NewServicePrincipalToken(*oauthConfig, cfg.ClientID, string(cfg.ClientSecret), resourceManagerEndpoint) - if err != nil { - return azureClient{}, err - } + credential, err := newCredential(cfg, policy.ClientOptions{ + Cloud: cloudConfiguration, + Telemetry: telemetry, + }) + if err != nil { + return azureClient{}, err } client, err := config_util.NewClientFromConfig(cfg.HTTPClientConfig, "azure_sd") if err != nil { return azureClient{}, err } - sender := autorest.DecorateSender(client) - preparer := autorest.WithUserAgent(userAgent) - - bearerAuthorizer := autorest.NewBearerAuthorizer(spt) + options := &arm.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Transport: client, + Cloud: cloudConfiguration, + Telemetry: telemetry, + }, + } - c.vm = compute.NewVirtualMachinesClientWithBaseURI(resourceManagerEndpoint, cfg.SubscriptionID) - c.vm.Authorizer = bearerAuthorizer - c.vm.Sender = sender - c.vm.RequestInspector = preparer + c.vm, err = armcompute.NewVirtualMachinesClient(cfg.SubscriptionID, credential, options) + if err != nil { + return azureClient{}, err + } - c.nic = network.NewInterfacesClientWithBaseURI(resourceManagerEndpoint, cfg.SubscriptionID) - c.nic.Authorizer = bearerAuthorizer - c.nic.Sender = sender - c.nic.RequestInspector = preparer + c.nic, err = armnetwork.NewInterfacesClient(cfg.SubscriptionID, credential, options) + if err != nil { + return azureClient{}, err + } - c.vmss = compute.NewVirtualMachineScaleSetsClientWithBaseURI(resourceManagerEndpoint, cfg.SubscriptionID) - c.vmss.Authorizer = bearerAuthorizer - c.vmss.Sender = sender - c.vmss.RequestInspector = preparer + c.vmss, err = armcompute.NewVirtualMachineScaleSetsClient(cfg.SubscriptionID, credential, options) + if err != nil { + return azureClient{}, err + } - c.vmssvm = compute.NewVirtualMachineScaleSetVMsClientWithBaseURI(resourceManagerEndpoint, cfg.SubscriptionID) - c.vmssvm.Authorizer = bearerAuthorizer - c.vmssvm.Sender = sender - c.vmssvm.RequestInspector = preparer + c.vmssvm, err = armcompute.NewVirtualMachineScaleSetVMsClient(cfg.SubscriptionID, credential, options) + if err != nil { + return azureClient{}, err + } return c, nil } -// azureResource represents a resource identifier in Azure. -type azureResource struct { - Name string - ResourceGroup string +func newCredential(cfg SDConfig, policyClientOptions policy.ClientOptions) (azcore.TokenCredential, error) { + var credential azcore.TokenCredential + switch cfg.AuthenticationMethod { + case authMethodManagedIdentity: + options := &azidentity.ManagedIdentityCredentialOptions{ClientOptions: policyClientOptions, ID: azidentity.ClientID(cfg.ClientID)} + managedIdentityCredential, err := azidentity.NewManagedIdentityCredential(options) + if err != nil { + return nil, err + } + credential = azcore.TokenCredential(managedIdentityCredential) + case authMethodOAuth: + options := &azidentity.ClientSecretCredentialOptions{ClientOptions: policyClientOptions} + secretCredential, err := azidentity.NewClientSecretCredential(cfg.TenantID, cfg.ClientID, string(cfg.ClientSecret), options) + if err != nil { + return nil, err + } + credential = azcore.TokenCredential(secretCredential) + } + return credential, nil } -// virtualMachine represents an Azure virtual machine (which can also be created by a VMSS) +// virtualMachine represents an Azure virtual machine (which can also be created by a VMSS). type virtualMachine struct { ID string Name string @@ -260,28 +307,24 @@ type virtualMachine struct { Location string OsType string ScaleSet string + InstanceID string Tags map[string]*string NetworkInterfaces []string Size string } // Create a new azureResource object from an ID string. -func newAzureResourceFromID(id string, logger log.Logger) (azureResource, error) { - // Resource IDs have the following format. - // /subscriptions/SUBSCRIPTION_ID/resourceGroups/RESOURCE_GROUP/providers/PROVIDER/TYPE/NAME - // or if embedded resource then - // /subscriptions/SUBSCRIPTION_ID/resourceGroups/RESOURCE_GROUP/providers/PROVIDER/TYPE/NAME/TYPE/NAME - s := strings.Split(id, "/") - if len(s) != 9 && len(s) != 11 { - err := fmt.Errorf("invalid ID '%s'. Refusing to create azureResource", id) +func newAzureResourceFromID(id string, logger log.Logger) (*arm.ResourceID, error) { + if logger == nil { + logger = log.NewNopLogger() + } + resourceID, err := arm.ParseResourceID(id) + if err != nil { + err := fmt.Errorf("invalid ID '%s': %w", id, err) level.Error(logger).Log("err", err) - return azureResource{}, err + return &arm.ResourceID{}, err } - - return azureResource{ - Name: strings.ToLower(s[8]), - ResourceGroup: strings.ToLower(s[4]), - }, nil + return resourceID, nil } func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { @@ -289,13 +332,14 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { client, err := createAzureClient(*d.cfg) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("could not create Azure client: %w", err) } + client.logger = d.logger machines, err := client.getVMs(ctx, d.cfg.ResourceGroup) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("could not get virtual machines: %w", err) } @@ -304,14 +348,14 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { // Load the vms managed by scale sets. scaleSets, err := client.getScaleSets(ctx, d.cfg.ResourceGroup) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("could not get virtual machine scale sets: %w", err) } for _, scaleSet := range scaleSets { scaleSetVms, err := client.getScaleSetVMs(ctx, scaleSet) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("could not get virtual machine scale set vms: %w", err) } machines = append(machines, scaleSetVms...) @@ -344,7 +388,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { azureLabelMachineComputerName: model.LabelValue(vm.ComputerName), azureLabelMachineOSType: model.LabelValue(vm.OsType), azureLabelMachineLocation: model.LabelValue(vm.Location), - azureLabelMachineResourceGroup: model.LabelValue(r.ResourceGroup), + azureLabelMachineResourceGroup: model.LabelValue(r.ResourceGroupName), azureLabelMachineSize: model.LabelValue(vm.Size), } @@ -359,18 +403,39 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { // Get the IP address information via separate call to the network provider. for _, nicID := range vm.NetworkInterfaces { - networkInterface, err := client.getNetworkInterfaceByID(ctx, nicID) - if err != nil { - if errors.Is(err, errorNotFound) { - level.Warn(d.logger).Log("msg", "Network interface does not exist", "name", nicID, "err", err) + var networkInterface *armnetwork.Interface + if v, ok := d.getFromCache(nicID); ok { + networkInterface = v + d.metrics.cacheHitCount.Add(1) + } else { + if vm.ScaleSet == "" { + networkInterface, err = client.getVMNetworkInterfaceByID(ctx, nicID) } else { - ch <- target{labelSet: nil, err: err} + networkInterface, err = client.getVMScaleSetVMNetworkInterfaceByID(ctx, nicID, vm.ScaleSet, vm.InstanceID) + } + if err != nil { + if errors.Is(err, errorNotFound) { + level.Warn(d.logger).Log("msg", "Network interface does not exist", "name", nicID, "err", err) + } else { + ch <- target{labelSet: nil, err: err} + } + d.addToCache(nicID, networkInterface) + } else { + networkInterface, err = client.getVMScaleSetVMNetworkInterfaceByID(ctx, nicID, vm.ScaleSet, vm.InstanceID) + if err != nil { + if errors.Is(err, errorNotFound) { + level.Warn(d.logger).Log("msg", "Network interface does not exist", "name", nicID, "err", err) + } else { + ch <- target{labelSet: nil, err: err} + } + // Get out of this routine because we cannot continue without a network interface. + return + } + d.addToCache(nicID, networkInterface) } - // Get out of this routine because we cannot continue without a network interface. - return } - if networkInterface.InterfacePropertiesFormat == nil { + if networkInterface.Properties == nil { continue } @@ -378,21 +443,21 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { // This information is available via another API call however the Go SDK does not // yet support this. On deallocated machines, this value happens to be nil so it // is a cheap and easy way to determine if a machine is allocated or not. - if networkInterface.Primary == nil { + if networkInterface.Properties.Primary == nil { level.Debug(d.logger).Log("msg", "Skipping deallocated virtual machine", "machine", vm.Name) return } - if *networkInterface.Primary { - for _, ip := range *networkInterface.IPConfigurations { + if *networkInterface.Properties.Primary { + for _, ip := range networkInterface.Properties.IPConfigurations { // IPAddress is a field defined in PublicIPAddressPropertiesFormat, // therefore we need to validate that both are not nil. - if ip.PublicIPAddress != nil && ip.PublicIPAddress.PublicIPAddressPropertiesFormat != nil && ip.PublicIPAddress.IPAddress != nil { - labels[azureLabelMachinePublicIP] = model.LabelValue(*ip.PublicIPAddress.IPAddress) + if ip.Properties != nil && ip.Properties.PublicIPAddress != nil && ip.Properties.PublicIPAddress.Properties != nil && ip.Properties.PublicIPAddress.Properties.IPAddress != nil { + labels[azureLabelMachinePublicIP] = model.LabelValue(*ip.Properties.PublicIPAddress.Properties.IPAddress) } - if ip.PrivateIPAddress != nil { - labels[azureLabelMachinePrivateIP] = model.LabelValue(*ip.PrivateIPAddress) - address := net.JoinHostPort(*ip.PrivateIPAddress, fmt.Sprintf("%d", d.port)) + if ip.Properties != nil && ip.Properties.PrivateIPAddress != nil { + labels[azureLabelMachinePrivateIP] = model.LabelValue(*ip.Properties.PrivateIPAddress) + address := net.JoinHostPort(*ip.Properties.PrivateIPAddress, fmt.Sprintf("%d", d.port)) labels[model.AddressLabel] = model.LabelValue(address) ch <- target{labelSet: labels, err: nil} return @@ -414,7 +479,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { var tg targetgroup.Group for tgt := range ch { if tgt.err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("unable to complete Azure service discovery: %w", tgt.err) } if tgt.labelSet != nil { @@ -427,93 +492,84 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { func (client *azureClient) getVMs(ctx context.Context, resourceGroup string) ([]virtualMachine, error) { var vms []virtualMachine - var result compute.VirtualMachineListResultPage - var err error if len(resourceGroup) == 0 { - result, err = client.vm.ListAll(ctx) - } else { - result, err = client.vm.List(ctx, resourceGroup) - } - if err != nil { - return nil, fmt.Errorf("could not list virtual machines: %w", err) - } - for result.NotDone() { - for _, vm := range result.Values() { - vms = append(vms, mapFromVM(vm)) + pager := client.vm.NewListAllPager(nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, fmt.Errorf("could not list virtual machines: %w", err) + } + for _, vm := range nextResult.Value { + vms = append(vms, mapFromVM(*vm)) + } } - err = result.NextWithContext(ctx) - if err != nil { - return nil, fmt.Errorf("could not list virtual machines: %w", err) + } else { + pager := client.vm.NewListPager(resourceGroup, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, fmt.Errorf("could not list virtual machines: %w", err) + } + for _, vm := range nextResult.Value { + vms = append(vms, mapFromVM(*vm)) + } } } - return vms, nil } -type VmssListResultPage interface { - NextWithContext(ctx context.Context) (err error) - NotDone() bool - Values() []compute.VirtualMachineScaleSet -} - -func (client *azureClient) getScaleSets(ctx context.Context, resourceGroup string) ([]compute.VirtualMachineScaleSet, error) { - var scaleSets []compute.VirtualMachineScaleSet - var result VmssListResultPage - var err error +func (client *azureClient) getScaleSets(ctx context.Context, resourceGroup string) ([]armcompute.VirtualMachineScaleSet, error) { + var scaleSets []armcompute.VirtualMachineScaleSet if len(resourceGroup) == 0 { - var rtn compute.VirtualMachineScaleSetListWithLinkResultPage - rtn, err = client.vmss.ListAll(ctx) - if err != nil { - return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err) + pager := client.vmss.NewListAllPager(nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err) + } + for _, vmss := range nextResult.Value { + scaleSets = append(scaleSets, *vmss) + } } - result = &rtn } else { - var rtn compute.VirtualMachineScaleSetListResultPage - rtn, err = client.vmss.List(ctx, resourceGroup) - if err != nil { - return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err) - } - result = &rtn - } - - for result.NotDone() { - scaleSets = append(scaleSets, result.Values()...) - err = result.NextWithContext(ctx) - if err != nil { - return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err) + pager := client.vmss.NewListPager(resourceGroup, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err) + } + for _, vmss := range nextResult.Value { + scaleSets = append(scaleSets, *vmss) + } } } - return scaleSets, nil } -func (client *azureClient) getScaleSetVMs(ctx context.Context, scaleSet compute.VirtualMachineScaleSet) ([]virtualMachine, error) { +func (client *azureClient) getScaleSetVMs(ctx context.Context, scaleSet armcompute.VirtualMachineScaleSet) ([]virtualMachine, error) { var vms []virtualMachine // TODO do we really need to fetch the resourcegroup this way? - r, err := newAzureResourceFromID(*scaleSet.ID, nil) + r, err := newAzureResourceFromID(*scaleSet.ID, client.logger) if err != nil { return nil, fmt.Errorf("could not parse scale set ID: %w", err) } - result, err := client.vmssvm.List(ctx, r.ResourceGroup, *(scaleSet.Name), "", "", "") - if err != nil { - return nil, fmt.Errorf("could not list virtual machine scale set vms: %w", err) - } - for result.NotDone() { - for _, vm := range result.Values() { - vms = append(vms, mapFromVMScaleSetVM(vm, *scaleSet.Name)) - } - err = result.NextWithContext(ctx) + pager := client.vmssvm.NewListPager(r.ResourceGroupName, *(scaleSet.Name), nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) if err != nil { return nil, fmt.Errorf("could not list virtual machine scale set vms: %w", err) } + for _, vmssvm := range nextResult.Value { + vms = append(vms, mapFromVMScaleSetVM(*vmssvm, *scaleSet.Name)) + } } return vms, nil } -func mapFromVM(vm compute.VirtualMachine) virtualMachine { - osType := string(vm.StorageProfile.OsDisk.OsType) +func mapFromVM(vm armcompute.VirtualMachine) virtualMachine { + var osType string tags := map[string]*string{} networkInterfaces := []string{} var computerName string @@ -523,18 +579,23 @@ func mapFromVM(vm compute.VirtualMachine) virtualMachine { tags = vm.Tags } - if vm.NetworkProfile != nil { - for _, vmNIC := range *(vm.NetworkProfile.NetworkInterfaces) { - networkInterfaces = append(networkInterfaces, *vmNIC.ID) + if vm.Properties != nil { + if vm.Properties.StorageProfile != nil && + vm.Properties.StorageProfile.OSDisk != nil && + vm.Properties.StorageProfile.OSDisk.OSType != nil { + osType = string(*vm.Properties.StorageProfile.OSDisk.OSType) } - } - if vm.VirtualMachineProperties != nil { - if vm.VirtualMachineProperties.OsProfile != nil && vm.VirtualMachineProperties.OsProfile.ComputerName != nil { - computerName = *(vm.VirtualMachineProperties.OsProfile.ComputerName) + if vm.Properties.NetworkProfile != nil { + for _, vmNIC := range vm.Properties.NetworkProfile.NetworkInterfaces { + networkInterfaces = append(networkInterfaces, *vmNIC.ID) + } + } + if vm.Properties.OSProfile != nil && vm.Properties.OSProfile.ComputerName != nil { + computerName = *(vm.Properties.OSProfile.ComputerName) } - if vm.VirtualMachineProperties.HardwareProfile != nil { - size = string(vm.VirtualMachineProperties.HardwareProfile.VMSize) + if vm.Properties.HardwareProfile != nil { + size = string(*vm.Properties.HardwareProfile.VMSize) } } @@ -552,8 +613,8 @@ func mapFromVM(vm compute.VirtualMachine) virtualMachine { } } -func mapFromVMScaleSetVM(vm compute.VirtualMachineScaleSetVM, scaleSetName string) virtualMachine { - osType := string(vm.StorageProfile.OsDisk.OsType) +func mapFromVMScaleSetVM(vm armcompute.VirtualMachineScaleSetVM, scaleSetName string) virtualMachine { + var osType string tags := map[string]*string{} networkInterfaces := []string{} var computerName string @@ -563,18 +624,23 @@ func mapFromVMScaleSetVM(vm compute.VirtualMachineScaleSetVM, scaleSetName strin tags = vm.Tags } - if vm.NetworkProfile != nil { - for _, vmNIC := range *(vm.NetworkProfile.NetworkInterfaces) { - networkInterfaces = append(networkInterfaces, *vmNIC.ID) + if vm.Properties != nil { + if vm.Properties.StorageProfile != nil && + vm.Properties.StorageProfile.OSDisk != nil && + vm.Properties.StorageProfile.OSDisk.OSType != nil { + osType = string(*vm.Properties.StorageProfile.OSDisk.OSType) } - } - if vm.VirtualMachineScaleSetVMProperties != nil { - if vm.VirtualMachineScaleSetVMProperties.OsProfile != nil && vm.VirtualMachineScaleSetVMProperties.OsProfile.ComputerName != nil { - computerName = *(vm.VirtualMachineScaleSetVMProperties.OsProfile.ComputerName) + if vm.Properties.NetworkProfile != nil { + for _, vmNIC := range vm.Properties.NetworkProfile.NetworkInterfaces { + networkInterfaces = append(networkInterfaces, *vmNIC.ID) + } + } + if vm.Properties.OSProfile != nil && vm.Properties.OSProfile.ComputerName != nil { + computerName = *(vm.Properties.OSProfile.ComputerName) } - if vm.VirtualMachineScaleSetVMProperties.HardwareProfile != nil { - size = string(vm.VirtualMachineScaleSetVMProperties.HardwareProfile.VMSize) + if vm.Properties.HardwareProfile != nil { + size = string(*vm.Properties.HardwareProfile.VMSize) } } @@ -586,6 +652,7 @@ func mapFromVMScaleSetVM(vm compute.VirtualMachineScaleSetVM, scaleSetName strin Location: *(vm.Location), OsType: osType, ScaleSet: scaleSetName, + InstanceID: *(vm.InstanceID), Tags: tags, NetworkInterfaces: networkInterfaces, Size: size, @@ -594,38 +661,58 @@ func mapFromVMScaleSetVM(vm compute.VirtualMachineScaleSetVM, scaleSetName strin var errorNotFound = errors.New("network interface does not exist") -// getNetworkInterfaceByID gets the network interface. +// getVMNetworkInterfaceByID gets the network interface. // If a 404 is returned from the Azure API, `errorNotFound` is returned. -// On all other errors, an autorest.DetailedError is returned. -func (client *azureClient) getNetworkInterfaceByID(ctx context.Context, networkInterfaceID string) (*network.Interface, error) { - result := network.Interface{} - queryParameters := map[string]interface{}{ - "api-version": "2018-10-01", - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.nic.BaseURI), - autorest.WithPath(networkInterfaceID), - autorest.WithQueryParameters(queryParameters), - autorest.WithUserAgent(userAgent)) - req, err := preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (client *azureClient) getVMNetworkInterfaceByID(ctx context.Context, networkInterfaceID string) (*armnetwork.Interface, error) { + r, err := newAzureResourceFromID(networkInterfaceID, client.logger) if err != nil { - return nil, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", nil, "Failure preparing request") + return nil, fmt.Errorf("could not parse network interface ID: %w", err) + } + + resp, err := client.nic.Get(ctx, r.ResourceGroupName, r.Name, &armnetwork.InterfacesClientGetOptions{Expand: to.Ptr("IPConfigurations/PublicIPAddress")}) + if err != nil { + var responseError *azcore.ResponseError + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound { + return nil, errorNotFound + } + return nil, fmt.Errorf("failed to retrieve Interface %v with error: %w", networkInterfaceID, err) } - resp, err := client.nic.GetSender(req) + return &resp.Interface, nil +} + +// getVMScaleSetVMNetworkInterfaceByID gets the network interface. +// If a 404 is returned from the Azure API, `errorNotFound` is returned. +func (client *azureClient) getVMScaleSetVMNetworkInterfaceByID(ctx context.Context, networkInterfaceID, scaleSetName, instanceID string) (*armnetwork.Interface, error) { + r, err := newAzureResourceFromID(networkInterfaceID, client.logger) if err != nil { - return nil, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure sending request") + return nil, fmt.Errorf("could not parse network interface ID: %w", err) } - result, err = client.nic.GetResponder(resp) + resp, err := client.nic.GetVirtualMachineScaleSetNetworkInterface(ctx, r.ResourceGroupName, scaleSetName, instanceID, r.Name, &armnetwork.InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceOptions{Expand: to.Ptr("IPConfigurations/PublicIPAddress")}) if err != nil { - if resp.StatusCode == http.StatusNotFound { + var responseError *azcore.ResponseError + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound { return nil, errorNotFound } - return nil, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure responding to request") + return nil, fmt.Errorf("failed to retrieve Interface %v with error: %w", networkInterfaceID, err) } - return &result, nil + return &resp.Interface, nil +} + +// addToCache will add the network interface information for the specified nicID. +func (d *Discovery) addToCache(nicID string, netInt *armnetwork.Interface) { + random := rand.Int63n(int64(time.Duration(d.cfg.RefreshInterval * 3).Seconds())) + rs := time.Duration(random) * time.Second + exptime := time.Duration(d.cfg.RefreshInterval*10) + rs + d.cache.Set(nicID, netInt, cache.WithExpiration(exptime)) + level.Debug(d.logger).Log("msg", "Adding nic", "nic", nicID, "time", exptime.Seconds()) +} + +// getFromCache will get the network Interface for the specified nicID +// If the cache is disabled nothing will happen. +func (d *Discovery) getFromCache(nicID string) (*armnetwork.Interface, bool) { + net, found := d.cache.Get(nicID) + return net, found } diff --git a/vendor/github.com/prometheus/prometheus/discovery/azure/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/azure/metrics.go new file mode 100644 index 000000000..3e3dbdbfb --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/azure/metrics.go @@ -0,0 +1,64 @@ +// Copyright 2015 The Prometheus 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 azure + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*azureMetrics)(nil) + +type azureMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator + + failuresCount prometheus.Counter + cacheHitCount prometheus.Counter + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &azureMetrics{ + refreshMetrics: rmi, + failuresCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_azure_failures_total", + Help: "Number of Azure service discovery refresh failures.", + }), + cacheHitCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_azure_cache_hit_total", + Help: "Number of cache hit during refresh.", + }), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.failuresCount, + m.cacheHitCount, + }) + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *azureMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *azureMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/consul/consul.go b/vendor/github.com/prometheus/prometheus/discovery/consul/consul.go index c59bd1f5d..40eed7697 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/consul/consul.go +++ b/vendor/github.com/prometheus/prometheus/discovery/consul/consul.go @@ -50,7 +50,7 @@ const ( tagsLabel = model.MetaLabelPrefix + "consul_tags" // serviceLabel is the name of the label containing the service name. serviceLabel = model.MetaLabelPrefix + "consul_service" - // healthLabel is the name of the label containing the health of the service instance + // healthLabel is the name of the label containing the health of the service instance. healthLabel = model.MetaLabelPrefix + "consul_health" // serviceAddressLabel is the name of the label containing the (optional) service address. serviceAddressLabel = model.MetaLabelPrefix + "consul_service_address" @@ -71,46 +71,24 @@ const ( namespace = "prometheus" ) -var ( - rpcFailuresCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Namespace: namespace, - Name: "sd_consul_rpc_failures_total", - Help: "The number of Consul RPC call failures.", - }) - rpcDuration = prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Namespace: namespace, - Name: "sd_consul_rpc_duration_seconds", - Help: "The duration of a Consul RPC call in seconds.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - []string{"endpoint", "call"}, - ) - - // Initialize metric vectors. - servicesRPCDuration = rpcDuration.WithLabelValues("catalog", "services") - serviceRPCDuration = rpcDuration.WithLabelValues("catalog", "service") - - // DefaultSDConfig is the default Consul SD configuration. - DefaultSDConfig = SDConfig{ - TagSeparator: ",", - Scheme: "http", - Server: "localhost:8500", - AllowStale: true, - RefreshInterval: model.Duration(30 * time.Second), - HTTPClientConfig: config.DefaultHTTPClientConfig, - } -) +// DefaultSDConfig is the default Consul SD configuration. +var DefaultSDConfig = SDConfig{ + TagSeparator: ",", + Scheme: "http", + Server: "localhost:8500", + AllowStale: true, + RefreshInterval: model.Duration(30 * time.Second), + HTTPClientConfig: config.DefaultHTTPClientConfig, +} func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(rpcFailuresCount, rpcDuration) } // SDConfig is the configuration for Consul service discovery. type SDConfig struct { Server string `yaml:"server,omitempty"` + PathPrefix string `yaml:"path_prefix,omitempty"` Token config.Secret `yaml:"token,omitempty"` Datacenter string `yaml:"datacenter,omitempty"` Namespace string `yaml:"namespace,omitempty"` @@ -141,12 +119,17 @@ type SDConfig struct { HTTPClientConfig config.HTTPClientConfig `yaml:",inline"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "consul" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -195,10 +178,16 @@ type Discovery struct { refreshInterval time.Duration finalizer func() logger log.Logger + metrics *consulMetrics } // NewDiscovery returns a new Discovery for the given config. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*consulMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } @@ -211,6 +200,7 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { clientConf := &consul.Config{ Address: conf.Server, + PathPrefix: conf.PathPrefix, Scheme: conf.Scheme, Datacenter: conf.Datacenter, Namespace: conf.Namespace, @@ -235,7 +225,9 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { clientPartition: conf.Partition, finalizer: wrapper.CloseIdleConnections, logger: logger, + metrics: m, } + return cd, nil } @@ -291,7 +283,7 @@ func (d *Discovery) getDatacenter() error { info, err := d.client.Agent().Self() if err != nil { level.Error(d.logger).Log("msg", "Error retrieving datacenter name", "err", err) - rpcFailuresCount.Inc() + d.metrics.rpcFailuresCount.Inc() return err } @@ -380,7 +372,7 @@ func (d *Discovery) watchServices(ctx context.Context, ch chan<- []*targetgroup. t0 := time.Now() srvs, meta, err := catalog.Services(opts.WithContext(ctx)) elapsed := time.Since(t0) - servicesRPCDuration.Observe(elapsed.Seconds()) + d.metrics.servicesRPCDuration.Observe(elapsed.Seconds()) // Check the context before in order to exit early. select { @@ -391,7 +383,7 @@ func (d *Discovery) watchServices(ctx context.Context, ch chan<- []*targetgroup. if err != nil { level.Error(d.logger).Log("msg", "Error refreshing service list", "err", err) - rpcFailuresCount.Inc() + d.metrics.rpcFailuresCount.Inc() time.Sleep(retryInterval) return } @@ -447,13 +439,15 @@ func (d *Discovery) watchServices(ctx context.Context, ch chan<- []*targetgroup. // consulService contains data belonging to the same service. type consulService struct { - name string - tags []string - labels model.LabelSet - discovery *Discovery - client *consul.Client - tagSeparator string - logger log.Logger + name string + tags []string + labels model.LabelSet + discovery *Discovery + client *consul.Client + tagSeparator string + logger log.Logger + rpcFailuresCount prometheus.Counter + serviceRPCDuration prometheus.Observer } // Start watching a service. @@ -467,8 +461,10 @@ func (d *Discovery) watchService(ctx context.Context, ch chan<- []*targetgroup.G serviceLabel: model.LabelValue(name), datacenterLabel: model.LabelValue(d.clientDatacenter), }, - tagSeparator: d.tagSeparator, - logger: d.logger, + tagSeparator: d.tagSeparator, + logger: d.logger, + rpcFailuresCount: d.metrics.rpcFailuresCount, + serviceRPCDuration: d.metrics.serviceRPCDuration, } go func() { @@ -506,7 +502,7 @@ func (srv *consulService) watch(ctx context.Context, ch chan<- []*targetgroup.Gr t0 := time.Now() serviceNodes, meta, err := health.ServiceMultipleTags(srv.name, srv.tags, false, opts.WithContext(ctx)) elapsed := time.Since(t0) - serviceRPCDuration.Observe(elapsed.Seconds()) + srv.serviceRPCDuration.Observe(elapsed.Seconds()) // Check the context before in order to exit early. select { @@ -518,7 +514,7 @@ func (srv *consulService) watch(ctx context.Context, ch chan<- []*targetgroup.Gr if err != nil { level.Error(srv.logger).Log("msg", "Error refreshing service", "service", srv.name, "tags", strings.Join(srv.tags, ","), "err", err) - rpcFailuresCount.Inc() + srv.rpcFailuresCount.Inc() time.Sleep(retryInterval) return } diff --git a/vendor/github.com/prometheus/prometheus/discovery/consul/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/consul/metrics.go new file mode 100644 index 000000000..8266e7cc6 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/consul/metrics.go @@ -0,0 +1,73 @@ +// Copyright 2015 The Prometheus 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 consul + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*consulMetrics)(nil) + +type consulMetrics struct { + rpcFailuresCount prometheus.Counter + rpcDuration *prometheus.SummaryVec + + servicesRPCDuration prometheus.Observer + serviceRPCDuration prometheus.Observer + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &consulMetrics{ + rpcFailuresCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Namespace: namespace, + Name: "sd_consul_rpc_failures_total", + Help: "The number of Consul RPC call failures.", + }), + rpcDuration: prometheus.NewSummaryVec( + prometheus.SummaryOpts{ + Namespace: namespace, + Name: "sd_consul_rpc_duration_seconds", + Help: "The duration of a Consul RPC call in seconds.", + Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, + }, + []string{"endpoint", "call"}, + ), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.rpcFailuresCount, + m.rpcDuration, + }) + + // Initialize metric vectors. + m.servicesRPCDuration = m.rpcDuration.WithLabelValues("catalog", "services") + m.serviceRPCDuration = m.rpcDuration.WithLabelValues("catalog", "service") + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *consulMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *consulMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/digitalocean/digitalocean.go b/vendor/github.com/prometheus/prometheus/discovery/digitalocean/digitalocean.go index e207388b3..18380b729 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/digitalocean/digitalocean.go +++ b/vendor/github.com/prometheus/prometheus/discovery/digitalocean/digitalocean.go @@ -24,6 +24,7 @@ import ( "github.com/digitalocean/godo" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" "github.com/prometheus/common/version" @@ -62,6 +63,13 @@ func init() { discovery.RegisterConfig(&SDConfig{}) } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &digitaloceanMetrics{ + refreshMetrics: rmi, + } +} + // SDConfig is the configuration for DigitalOcean based service discovery. type SDConfig struct { HTTPClientConfig config.HTTPClientConfig `yaml:",inline"` @@ -75,7 +83,7 @@ func (*SDConfig) Name() string { return "digitalocean" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -103,7 +111,12 @@ type Discovery struct { } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*digitaloceanMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + d := &Discovery{ port: conf.Port, } @@ -125,10 +138,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { } d.Discovery = refresh.NewDiscovery( - logger, - "digitalocean", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "digitalocean", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/digitalocean/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/digitalocean/metrics.go new file mode 100644 index 000000000..91cfd9bf3 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/digitalocean/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 digitalocean + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*digitaloceanMetrics)(nil) + +type digitaloceanMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *digitaloceanMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *digitaloceanMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/discoverer_metrics_noop.go b/vendor/github.com/prometheus/prometheus/discovery/discoverer_metrics_noop.go new file mode 100644 index 000000000..638317ace --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/discoverer_metrics_noop.go @@ -0,0 +1,28 @@ +// Copyright 2015 The Prometheus 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 discovery + +// Create a dummy metrics struct, because this SD doesn't have any metrics. +type NoopDiscovererMetrics struct{} + +var _ DiscovererMetrics = (*NoopDiscovererMetrics)(nil) + +// Register implements discovery.DiscovererMetrics. +func (*NoopDiscovererMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (*NoopDiscovererMetrics) Unregister() { +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/discovery.go b/vendor/github.com/prometheus/prometheus/discovery/discovery.go index 9dc010a09..a5826f817 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/discovery.go +++ b/vendor/github.com/prometheus/prometheus/discovery/discovery.go @@ -18,6 +18,7 @@ import ( "reflect" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/prometheus/discovery/targetgroup" @@ -38,15 +39,47 @@ type Discoverer interface { Run(ctx context.Context, up chan<- []*targetgroup.Group) } +// Internal metrics of service discovery mechanisms. +type DiscovererMetrics interface { + Register() error + Unregister() +} + // DiscovererOptions provides options for a Discoverer. type DiscovererOptions struct { Logger log.Logger + Metrics DiscovererMetrics + // Extra HTTP client options to expose to Discoverers. This field may be // ignored; Discoverer implementations must opt-in to reading it. HTTPClientOptions []config.HTTPClientOption } +// Metrics used by the "refresh" package. +// We define them here in the "discovery" package in order to avoid a cyclic dependency between +// "discovery" and "refresh". +type RefreshMetrics struct { + Failures prometheus.Counter + Duration prometheus.Observer +} + +// Instantiate the metrics used by the "refresh" package. +type RefreshMetricsInstantiator interface { + Instantiate(mech string) *RefreshMetrics +} + +// An interface for registering, unregistering, and instantiating metrics for the "refresh" package. +// Refresh metrics are registered and unregistered outside of the service discovery mechanism. +// This is so that the same metrics can be reused across different service discovery mechanisms. +// To manage refresh metrics inside the SD mechanism, we'd need to use const labels which are +// specific to that SD. However, doing so would also expose too many unused metrics on +// the Prometheus /metrics endpoint. +type RefreshMetricsManager interface { + DiscovererMetrics + RefreshMetricsInstantiator +} + // A Config provides the configuration and constructor for a Discoverer. type Config interface { // Name returns the name of the discovery mechanism. @@ -55,6 +88,9 @@ type Config interface { // NewDiscoverer returns a Discoverer for the Config // with the given DiscovererOptions. NewDiscoverer(DiscovererOptions) (Discoverer, error) + + // NewDiscovererMetrics returns the metrics used by the service discovery. + NewDiscovererMetrics(prometheus.Registerer, RefreshMetricsInstantiator) DiscovererMetrics } // Configs is a slice of Config values that uses custom YAML marshaling and unmarshaling @@ -109,6 +145,11 @@ func (c StaticConfig) NewDiscoverer(DiscovererOptions) (Discoverer, error) { return staticDiscoverer(c), nil } +// No metrics are needed for this service discovery mechanism. +func (c StaticConfig) NewDiscovererMetrics(prometheus.Registerer, RefreshMetricsInstantiator) DiscovererMetrics { + return &NoopDiscovererMetrics{} +} + type staticDiscoverer []*targetgroup.Group func (c staticDiscoverer) Run(ctx context.Context, up chan<- []*targetgroup.Group) { diff --git a/vendor/github.com/prometheus/prometheus/discovery/dns/dns.go b/vendor/github.com/prometheus/prometheus/discovery/dns/dns.go index 96e07254f..cf56a2ad0 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/dns/dns.go +++ b/vendor/github.com/prometheus/prometheus/discovery/dns/dns.go @@ -42,35 +42,21 @@ const ( dnsSrvRecordPortLabel = dnsSrvRecordPrefix + "port" dnsMxRecordPrefix = model.MetaLabelPrefix + "dns_mx_record_" dnsMxRecordTargetLabel = dnsMxRecordPrefix + "target" + dnsNsRecordPrefix = model.MetaLabelPrefix + "dns_ns_record_" + dnsNsRecordTargetLabel = dnsNsRecordPrefix + "target" // Constants for instrumentation. namespace = "prometheus" ) -var ( - dnsSDLookupsCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Namespace: namespace, - Name: "sd_dns_lookups_total", - Help: "The number of DNS-SD lookups.", - }) - dnsSDLookupFailuresCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Namespace: namespace, - Name: "sd_dns_lookup_failures_total", - Help: "The number of DNS-SD lookup failures.", - }) - - // DefaultSDConfig is the default DNS SD configuration. - DefaultSDConfig = SDConfig{ - RefreshInterval: model.Duration(30 * time.Second), - Type: "SRV", - } -) +// DefaultSDConfig is the default DNS SD configuration. +var DefaultSDConfig = SDConfig{ + RefreshInterval: model.Duration(30 * time.Second), + Type: "SRV", +} func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(dnsSDLookupFailuresCount, dnsSDLookupsCount) } // SDConfig is the configuration for DNS based service discovery. @@ -81,12 +67,17 @@ type SDConfig struct { Port int `yaml:"port"` // Ignored for SRV records } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "dns" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(*c, opts.Logger), nil + return NewDiscovery(*c, opts.Logger, opts.Metrics) } // UnmarshalYAML implements the yaml.Unmarshaler interface. @@ -102,7 +93,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { } switch strings.ToUpper(c.Type) { case "SRV": - case "A", "AAAA", "MX": + case "A", "AAAA", "MX", "NS": if c.Port == 0 { return errors.New("a port is required in DNS-SD configs for all record types except SRV") } @@ -116,16 +107,22 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { // the Discoverer interface. type Discovery struct { *refresh.Discovery - names []string - port int - qtype uint16 - logger log.Logger + names []string + port int + qtype uint16 + logger log.Logger + metrics *dnsMetrics lookupFn func(name string, qtype uint16, logger log.Logger) (*dns.Msg, error) } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf SDConfig, logger log.Logger) *Discovery { +func NewDiscovery(conf SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*dnsMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } @@ -140,6 +137,8 @@ func NewDiscovery(conf SDConfig, logger log.Logger) *Discovery { qtype = dns.TypeSRV case "MX": qtype = dns.TypeMX + case "NS": + qtype = dns.TypeNS } d := &Discovery{ names: conf.Names, @@ -147,14 +146,20 @@ func NewDiscovery(conf SDConfig, logger log.Logger) *Discovery { port: conf.Port, logger: logger, lookupFn: lookupWithSearchPath, + metrics: m, } + d.Discovery = refresh.NewDiscovery( - logger, - "dns", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "dns", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) - return d + + return d, nil } func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { @@ -187,9 +192,9 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { func (d *Discovery) refreshOne(ctx context.Context, name string, ch chan<- *targetgroup.Group) error { response, err := d.lookupFn(name, d.qtype, d.logger) - dnsSDLookupsCount.Inc() + d.metrics.dnsSDLookupsCount.Inc() if err != nil { - dnsSDLookupFailuresCount.Inc() + d.metrics.dnsSDLookupFailuresCount.Inc() return err } @@ -199,7 +204,7 @@ func (d *Discovery) refreshOne(ctx context.Context, name string, ch chan<- *targ } for _, record := range response.Answer { - var target, dnsSrvRecordTarget, dnsSrvRecordPort, dnsMxRecordTarget model.LabelValue + var target, dnsSrvRecordTarget, dnsSrvRecordPort, dnsMxRecordTarget, dnsNsRecordTarget model.LabelValue switch addr := record.(type) { case *dns.SRV: @@ -217,6 +222,13 @@ func (d *Discovery) refreshOne(ctx context.Context, name string, ch chan<- *targ addr.Mx = strings.TrimRight(addr.Mx, ".") target = hostPort(addr.Mx, d.port) + case *dns.NS: + dnsNsRecordTarget = model.LabelValue(addr.Ns) + + // Remove the final dot from rooted DNS names to make them look more usual. + addr.Ns = strings.TrimRight(addr.Ns, ".") + + target = hostPort(addr.Ns, d.port) case *dns.A: target = hostPort(addr.A.String(), d.port) case *dns.AAAA: @@ -234,6 +246,7 @@ func (d *Discovery) refreshOne(ctx context.Context, name string, ch chan<- *targ dnsSrvRecordTargetLabel: dnsSrvRecordTarget, dnsSrvRecordPortLabel: dnsSrvRecordPort, dnsMxRecordTargetLabel: dnsMxRecordTarget, + dnsNsRecordTargetLabel: dnsNsRecordTarget, }) } diff --git a/vendor/github.com/prometheus/prometheus/discovery/dns/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/dns/metrics.go new file mode 100644 index 000000000..27c96b53e --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/dns/metrics.go @@ -0,0 +1,66 @@ +// Copyright 2015 The Prometheus 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 dns + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*dnsMetrics)(nil) + +type dnsMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator + + dnsSDLookupsCount prometheus.Counter + dnsSDLookupFailuresCount prometheus.Counter + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &dnsMetrics{ + refreshMetrics: rmi, + dnsSDLookupsCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Namespace: namespace, + Name: "sd_dns_lookups_total", + Help: "The number of DNS-SD lookups.", + }), + dnsSDLookupFailuresCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Namespace: namespace, + Name: "sd_dns_lookup_failures_total", + Help: "The number of DNS-SD lookup failures.", + }), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.dnsSDLookupsCount, + m.dnsSDLookupFailuresCount, + }) + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *dnsMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *dnsMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/eureka/eureka.go b/vendor/github.com/prometheus/prometheus/discovery/eureka/eureka.go index 5d9d8d552..deed89f6f 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/eureka/eureka.go +++ b/vendor/github.com/prometheus/prometheus/discovery/eureka/eureka.go @@ -16,6 +16,7 @@ package eureka import ( "context" "errors" + "fmt" "net" "net/http" "net/url" @@ -23,6 +24,7 @@ import ( "time" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -75,12 +77,19 @@ type SDConfig struct { RefreshInterval model.Duration `yaml:"refresh_interval,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &eurekaMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "eureka" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -117,7 +126,12 @@ type Discovery struct { } // NewDiscovery creates a new Eureka discovery for the given role. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*eurekaMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + rt, err := config.NewRoundTripperFromConfig(conf.HTTPClientConfig, "eureka_sd") if err != nil { return nil, err @@ -128,10 +142,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { server: conf.Server, } d.Discovery = refresh.NewDiscovery( - logger, - "eureka", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "eureka", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/eureka/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/eureka/metrics.go new file mode 100644 index 000000000..6d6463ccd --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/eureka/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 eureka + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*eurekaMetrics)(nil) + +type eurekaMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *eurekaMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *eurekaMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/file/file.go b/vendor/github.com/prometheus/prometheus/discovery/file/file.go index c45595c6d..e7e9d0870 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/file/file.go +++ b/vendor/github.com/prometheus/prometheus/discovery/file/file.go @@ -39,24 +39,6 @@ import ( ) var ( - fileSDReadErrorsCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Name: "prometheus_sd_file_read_errors_total", - Help: "The number of File-SD read errors.", - }) - fileSDScanDuration = prometheus.NewSummary( - prometheus.SummaryOpts{ - Name: "prometheus_sd_file_scan_duration_seconds", - Help: "The duration of the File-SD scan in seconds.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }) - fileSDTimeStamp = NewTimestampCollector() - fileWatcherErrorsCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Name: "prometheus_sd_file_watcher_errors_total", - Help: "The number of File-SD errors caused by filesystem watch failures.", - }) - patFileSDName = regexp.MustCompile(`^[^*]*(\*[^/]*)?\.(json|yml|yaml|JSON|YML|YAML)$`) // DefaultSDConfig is the default file SD configuration. @@ -67,7 +49,6 @@ var ( func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(fileSDReadErrorsCount, fileSDScanDuration, fileSDTimeStamp, fileWatcherErrorsCount) } // SDConfig is the configuration for file based discovery. @@ -76,12 +57,17 @@ type SDConfig struct { RefreshInterval model.Duration `yaml:"refresh_interval,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "file" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger), nil + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -113,6 +99,9 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { const fileSDFilepathLabel = model.MetaLabelPrefix + "filepath" // TimestampCollector is a Custom Collector for Timestamps of the files. +// TODO(ptodev): Now that each file SD has its own TimestampCollector +// inside discovery/file/metrics.go, we can refactor this collector +// (or get rid of it) as each TimestampCollector instance will only use one discoverer. type TimestampCollector struct { Description *prometheus.Desc discoverers map[*Discovery]struct{} @@ -187,10 +176,17 @@ type Discovery struct { // This is used to detect deleted target groups. lastRefresh map[string]int logger log.Logger + + metrics *fileMetrics } // NewDiscovery returns a new file discovery for the given paths. -func NewDiscovery(conf *SDConfig, logger log.Logger) *Discovery { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + fm, ok := metrics.(*fileMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } @@ -200,9 +196,12 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) *Discovery { interval: time.Duration(conf.RefreshInterval), timestamps: make(map[string]float64), logger: logger, + metrics: fm, } - fileSDTimeStamp.addDiscoverer(disc) - return disc + + fm.init(disc) + + return disc, nil } // listFiles returns a list of all files that match the configured patterns. @@ -226,8 +225,8 @@ func (d *Discovery) watchFiles() { panic("no watcher configured") } for _, p := range d.paths { - if idx := strings.LastIndex(p, "/"); idx > -1 { - p = p[:idx] + if dir, _ := filepath.Split(p); dir != "" { + p = dir } else { p = "./" } @@ -242,7 +241,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { watcher, err := fsnotify.NewWatcher() if err != nil { level.Error(d.logger).Log("msg", "Error adding file watcher", "err", err) - fileWatcherErrorsCount.Inc() + d.metrics.fileWatcherErrorsCount.Inc() return } d.watcher = watcher @@ -306,7 +305,7 @@ func (d *Discovery) stop() { done := make(chan struct{}) defer close(done) - fileSDTimeStamp.removeDiscoverer(d) + d.metrics.fileSDTimeStamp.removeDiscoverer(d) // Closing the watcher will deadlock unless all events and errors are drained. go func() { @@ -332,13 +331,13 @@ func (d *Discovery) stop() { func (d *Discovery) refresh(ctx context.Context, ch chan<- []*targetgroup.Group) { t0 := time.Now() defer func() { - fileSDScanDuration.Observe(time.Since(t0).Seconds()) + d.metrics.fileSDScanDuration.Observe(time.Since(t0).Seconds()) }() ref := map[string]int{} for _, p := range d.listFiles() { tgroups, err := d.readFile(p) if err != nil { - fileSDReadErrorsCount.Inc() + d.metrics.fileSDReadErrorsCount.Inc() level.Error(d.logger).Log("msg", "Error reading file", "path", p, "err", err) // Prevent deletion down below. diff --git a/vendor/github.com/prometheus/prometheus/discovery/file/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/file/metrics.go new file mode 100644 index 000000000..c01501e4e --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/file/metrics.go @@ -0,0 +1,76 @@ +// Copyright 2015 The Prometheus 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 file + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*fileMetrics)(nil) + +type fileMetrics struct { + fileSDReadErrorsCount prometheus.Counter + fileSDScanDuration prometheus.Summary + fileWatcherErrorsCount prometheus.Counter + fileSDTimeStamp *TimestampCollector + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + fm := &fileMetrics{ + fileSDReadErrorsCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_file_read_errors_total", + Help: "The number of File-SD read errors.", + }), + fileSDScanDuration: prometheus.NewSummary( + prometheus.SummaryOpts{ + Name: "prometheus_sd_file_scan_duration_seconds", + Help: "The duration of the File-SD scan in seconds.", + Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, + }), + fileWatcherErrorsCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_file_watcher_errors_total", + Help: "The number of File-SD errors caused by filesystem watch failures.", + }), + fileSDTimeStamp: NewTimestampCollector(), + } + + fm.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + fm.fileSDReadErrorsCount, + fm.fileSDScanDuration, + fm.fileWatcherErrorsCount, + fm.fileSDTimeStamp, + }) + + return fm +} + +// Register implements discovery.DiscovererMetrics. +func (fm *fileMetrics) Register() error { + return fm.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (fm *fileMetrics) Unregister() { + fm.metricRegisterer.UnregisterMetrics() +} + +func (fm *fileMetrics) init(disc *Discovery) { + fm.fileSDTimeStamp.addDiscoverer(disc) +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/gce/gce.go b/vendor/github.com/prometheus/prometheus/discovery/gce/gce.go index fa05fbbf3..15f32dd24 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/gce/gce.go +++ b/vendor/github.com/prometheus/prometheus/discovery/gce/gce.go @@ -23,6 +23,7 @@ import ( "time" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" "golang.org/x/oauth2/google" "google.golang.org/api/compute/v1" @@ -81,12 +82,19 @@ type SDConfig struct { TagSeparator string `yaml:"tag_separator,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &gceMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "gce" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(*c, opts.Logger) + return NewDiscovery(*c, opts.Logger, opts.Metrics) } // UnmarshalYAML implements the yaml.Unmarshaler interface. @@ -121,7 +129,12 @@ type Discovery struct { } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*gceMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + d := &Discovery{ project: conf.Project, zone: conf.Zone, @@ -141,10 +154,13 @@ func NewDiscovery(conf SDConfig, logger log.Logger) (*Discovery, error) { d.isvc = compute.NewInstancesService(d.svc) d.Discovery = refresh.NewDiscovery( - logger, - "gce", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "gce", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/gce/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/gce/metrics.go new file mode 100644 index 000000000..f53ea5a8c --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/gce/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 gce + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*gceMetrics)(nil) + +type gceMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *gceMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *gceMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/hetzner/hcloud.go b/vendor/github.com/prometheus/prometheus/discovery/hetzner/hcloud.go index 50afdc1ec..6d0599dfa 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/hetzner/hcloud.go +++ b/vendor/github.com/prometheus/prometheus/discovery/hetzner/hcloud.go @@ -22,7 +22,7 @@ import ( "time" "github.com/go-kit/log" - "github.com/hetznercloud/hcloud-go/hcloud" + "github.com/hetznercloud/hcloud-go/v2/hcloud" "github.com/prometheus/common/config" "github.com/prometheus/common/model" "github.com/prometheus/common/version" @@ -91,7 +91,7 @@ func (d *hcloudDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group, er targets := make([]model.LabelSet, len(servers)) for i, server := range servers { labels := model.LabelSet{ - hetznerLabelRole: model.LabelValue(hetznerRoleHcloud), + hetznerLabelRole: model.LabelValue(HetznerRoleHcloud), hetznerLabelServerID: model.LabelValue(fmt.Sprintf("%d", server.ID)), hetznerLabelServerName: model.LabelValue(server.Name), hetznerLabelDatacenter: model.LabelValue(server.Datacenter.Name), diff --git a/vendor/github.com/prometheus/prometheus/discovery/hetzner/hetzner.go b/vendor/github.com/prometheus/prometheus/discovery/hetzner/hetzner.go index 084319d95..69c823d38 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/hetzner/hetzner.go +++ b/vendor/github.com/prometheus/prometheus/discovery/hetzner/hetzner.go @@ -20,7 +20,8 @@ import ( "time" "github.com/go-kit/log" - "github.com/hetznercloud/hcloud-go/hcloud" + "github.com/hetznercloud/hcloud-go/v2/hcloud" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -57,43 +58,50 @@ type SDConfig struct { RefreshInterval model.Duration `yaml:"refresh_interval"` Port int `yaml:"port"` - Role role `yaml:"role"` + Role Role `yaml:"role"` hcloudEndpoint string // For tests only. robotEndpoint string // For tests only. } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &hetznerMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "hetzner" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } type refresher interface { refresh(context.Context) ([]*targetgroup.Group, error) } -// role is the role of the target within the Hetzner Ecosystem. -type role string +// Role is the Role of the target within the Hetzner Ecosystem. +type Role string // The valid options for role. const ( // Hetzner Robot Role (Dedicated Server) // https://robot.hetzner.com - hetznerRoleRobot role = "robot" + HetznerRoleRobot Role = "robot" // Hetzner Cloud Role // https://console.hetzner.cloud - hetznerRoleHcloud role = "hcloud" + HetznerRoleHcloud Role = "hcloud" ) // UnmarshalYAML implements the yaml.Unmarshaler interface. -func (c *role) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (c *Role) UnmarshalYAML(unmarshal func(interface{}) error) error { if err := unmarshal((*string)(c)); err != nil { return err } switch *c { - case hetznerRoleRobot, hetznerRoleHcloud: + case HetznerRoleRobot, HetznerRoleHcloud: return nil default: return fmt.Errorf("unknown role %q", *c) @@ -127,28 +135,36 @@ type Discovery struct { } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*refresh.Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*refresh.Discovery, error) { + m, ok := metrics.(*hetznerMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + r, err := newRefresher(conf, logger) if err != nil { return nil, err } return refresh.NewDiscovery( - logger, - "hetzner", - time.Duration(conf.RefreshInterval), - r.refresh, + refresh.Options{ + Logger: logger, + Mech: "hetzner", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: r.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ), nil } func newRefresher(conf *SDConfig, l log.Logger) (refresher, error) { switch conf.Role { - case hetznerRoleHcloud: + case HetznerRoleHcloud: if conf.hcloudEndpoint == "" { conf.hcloudEndpoint = hcloud.Endpoint } return newHcloudDiscovery(conf, l) - case hetznerRoleRobot: + case HetznerRoleRobot: if conf.robotEndpoint == "" { conf.robotEndpoint = "https://robot-ws.your-server.de" } diff --git a/vendor/github.com/prometheus/prometheus/discovery/hetzner/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/hetzner/metrics.go new file mode 100644 index 000000000..27361ee75 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/hetzner/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 hetzner + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*hetznerMetrics)(nil) + +type hetznerMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *hetznerMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *hetznerMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/hetzner/robot.go b/vendor/github.com/prometheus/prometheus/discovery/hetzner/robot.go index 496088028..1d8aa9302 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/hetzner/robot.go +++ b/vendor/github.com/prometheus/prometheus/discovery/hetzner/robot.go @@ -105,7 +105,7 @@ func (d *robotDiscovery) refresh(context.Context) ([]*targetgroup.Group, error) targets := make([]model.LabelSet, len(servers)) for i, server := range servers { labels := model.LabelSet{ - hetznerLabelRole: model.LabelValue(hetznerRoleRobot), + hetznerLabelRole: model.LabelValue(HetznerRoleRobot), hetznerLabelServerID: model.LabelValue(strconv.Itoa(server.Server.ServerNumber)), hetznerLabelServerName: model.LabelValue(server.Server.ServerName), hetznerLabelDatacenter: model.LabelValue(strings.ToLower(server.Server.Dc)), diff --git a/vendor/github.com/prometheus/prometheus/discovery/http/http.go b/vendor/github.com/prometheus/prometheus/discovery/http/http.go index ec958c614..8dd21ec9e 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/http/http.go +++ b/vendor/github.com/prometheus/prometheus/discovery/http/http.go @@ -45,17 +45,10 @@ var ( } userAgent = fmt.Sprintf("Prometheus/%s", version.Version) matchContentType = regexp.MustCompile(`^(?i:application\/json(;\s*charset=("utf-8"|utf-8))?)$`) - - failuresCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Name: "prometheus_sd_http_failures_total", - Help: "Number of HTTP service discovery refresh failures.", - }) ) func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(failuresCount) } // SDConfig is the configuration for HTTP based discovery. @@ -65,12 +58,17 @@ type SDConfig struct { URL string `yaml:"url"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "http" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger, opts.HTTPClientOptions) + return NewDiscovery(c, opts.Logger, opts.HTTPClientOptions, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -99,7 +97,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if parsedURL.Host == "" { return fmt.Errorf("host is missing in URL") } - return nil + return c.HTTPClientConfig.Validate() } const httpSDURLLabel = model.MetaLabelPrefix + "url" @@ -112,10 +110,16 @@ type Discovery struct { client *http.Client refreshInterval time.Duration tgLastLength int + metrics *httpMetrics } // NewDiscovery returns a new HTTP discovery for the given config. -func NewDiscovery(conf *SDConfig, logger log.Logger, clientOpts []config.HTTPClientOption) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, clientOpts []config.HTTPClientOption, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*httpMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } @@ -130,13 +134,17 @@ func NewDiscovery(conf *SDConfig, logger log.Logger, clientOpts []config.HTTPCli url: conf.URL, client: client, refreshInterval: time.Duration(conf.RefreshInterval), // Stored to be sent as headers. + metrics: m, } d.Discovery = refresh.NewDiscovery( - logger, - "http", - time.Duration(conf.RefreshInterval), - d.Refresh, + refresh.Options{ + Logger: logger, + Mech: "http", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.Refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } @@ -152,7 +160,7 @@ func (d *Discovery) Refresh(ctx context.Context) ([]*targetgroup.Group, error) { resp, err := d.client.Do(req.WithContext(ctx)) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, err } defer func() { @@ -161,31 +169,31 @@ func (d *Discovery) Refresh(ctx context.Context) ([]*targetgroup.Group, error) { }() if resp.StatusCode != http.StatusOK { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("server returned HTTP status %s", resp.Status) } if !matchContentType.MatchString(strings.TrimSpace(resp.Header.Get("Content-Type"))) { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("unsupported content type %q", resp.Header.Get("Content-Type")) } b, err := io.ReadAll(resp.Body) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, err } var targetGroups []*targetgroup.Group if err := json.Unmarshal(b, &targetGroups); err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, err } for i, tg := range targetGroups { if tg == nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() err = errors.New("nil target group item found") return nil, err } diff --git a/vendor/github.com/prometheus/prometheus/discovery/http/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/http/metrics.go new file mode 100644 index 000000000..b1f8b8443 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/http/metrics.go @@ -0,0 +1,57 @@ +// Copyright 2015 The Prometheus 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 http + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*httpMetrics)(nil) + +type httpMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator + + failuresCount prometheus.Counter + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &httpMetrics{ + refreshMetrics: rmi, + failuresCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_http_failures_total", + Help: "Number of HTTP service discovery refresh failures.", + }), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.failuresCount, + }) + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *httpMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *httpMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/ionos/ionos.go b/vendor/github.com/prometheus/prometheus/discovery/ionos/ionos.go index a13a00058..c8b4f7f8e 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/ionos/ionos.go +++ b/vendor/github.com/prometheus/prometheus/discovery/ionos/ionos.go @@ -14,10 +14,12 @@ package ionos import ( + "errors" + "fmt" "time" "github.com/go-kit/log" - "github.com/pkg/errors" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -41,7 +43,12 @@ func init() { type Discovery struct{} // NewDiscovery returns a new refresh.Discovery for IONOS Cloud. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*refresh.Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*refresh.Discovery, error) { + m, ok := metrics.(*ionosMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if conf.ionosEndpoint == "" { conf.ionosEndpoint = "https://api.ionos.com" } @@ -52,10 +59,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*refresh.Discovery, error) } return refresh.NewDiscovery( - logger, - "ionos", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "ionos", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ), nil } @@ -79,6 +89,13 @@ type SDConfig struct { ionosEndpoint string // For tests only. } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &ionosMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the IONOS Cloud service discovery. func (c SDConfig) Name() string { return "ionos" @@ -86,7 +103,7 @@ func (c SDConfig) Name() string { // NewDiscoverer returns a new discovery.Discoverer for IONOS Cloud. func (c SDConfig) NewDiscoverer(options discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(&c, options.Logger) + return NewDiscovery(&c, options.Logger, options.Metrics) } // UnmarshalYAML implements the yaml.Unmarshaler interface. diff --git a/vendor/github.com/prometheus/prometheus/discovery/ionos/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/ionos/metrics.go new file mode 100644 index 000000000..88e465acf --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/ionos/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 ionos + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*ionosMetrics)(nil) + +type ionosMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *ionosMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *ionosMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/client_metrics.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/client_metrics.go deleted file mode 100644 index b316f7d88..000000000 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/client_metrics.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2018 The Prometheus 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 kubernetes - -import ( - "context" - "net/url" - "time" - - "github.com/prometheus/client_golang/prometheus" - "k8s.io/client-go/tools/metrics" - "k8s.io/client-go/util/workqueue" -) - -const workqueueMetricsNamespace = metricsNamespace + "_workqueue" - -var ( - // Metrics for client-go's HTTP requests. - clientGoRequestResultMetricVec = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Namespace: metricsNamespace, - Name: "http_request_total", - Help: "Total number of HTTP requests to the Kubernetes API by status code.", - }, - []string{"status_code"}, - ) - clientGoRequestLatencyMetricVec = prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Namespace: metricsNamespace, - Name: "http_request_duration_seconds", - Help: "Summary of latencies for HTTP requests to the Kubernetes API by endpoint.", - Objectives: map[float64]float64{}, - }, - []string{"endpoint"}, - ) - - // Definition of metrics for client-go workflow metrics provider - clientGoWorkqueueDepthMetricVec = prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: workqueueMetricsNamespace, - Name: "depth", - Help: "Current depth of the work queue.", - }, - []string{"queue_name"}, - ) - clientGoWorkqueueAddsMetricVec = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Namespace: workqueueMetricsNamespace, - Name: "items_total", - Help: "Total number of items added to the work queue.", - }, - []string{"queue_name"}, - ) - clientGoWorkqueueLatencyMetricVec = prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Namespace: workqueueMetricsNamespace, - Name: "latency_seconds", - Help: "How long an item stays in the work queue.", - Objectives: map[float64]float64{}, - }, - []string{"queue_name"}, - ) - clientGoWorkqueueUnfinishedWorkSecondsMetricVec = prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: workqueueMetricsNamespace, - Name: "unfinished_work_seconds", - Help: "How long an item has remained unfinished in the work queue.", - }, - []string{"queue_name"}, - ) - clientGoWorkqueueLongestRunningProcessorMetricVec = prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: workqueueMetricsNamespace, - Name: "longest_running_processor_seconds", - Help: "Duration of the longest running processor in the work queue.", - }, - []string{"queue_name"}, - ) - clientGoWorkqueueWorkDurationMetricVec = prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Namespace: workqueueMetricsNamespace, - Name: "work_duration_seconds", - Help: "How long processing an item from the work queue takes.", - Objectives: map[float64]float64{}, - }, - []string{"queue_name"}, - ) -) - -// Definition of dummy metric used as a placeholder if we don't want to observe some data. -type noopMetric struct{} - -func (noopMetric) Inc() {} -func (noopMetric) Dec() {} -func (noopMetric) Observe(float64) {} -func (noopMetric) Set(float64) {} - -// Definition of client-go metrics adapters for HTTP requests observation -type clientGoRequestMetricAdapter struct{} - -func (f *clientGoRequestMetricAdapter) Register(registerer prometheus.Registerer) { - metrics.Register( - metrics.RegisterOpts{ - RequestLatency: f, - RequestResult: f, - }, - ) - registerer.MustRegister( - clientGoRequestResultMetricVec, - clientGoRequestLatencyMetricVec, - ) -} - -func (clientGoRequestMetricAdapter) Increment(_ context.Context, code, _, _ string) { - clientGoRequestResultMetricVec.WithLabelValues(code).Inc() -} - -func (clientGoRequestMetricAdapter) Observe(_ context.Context, _ string, u url.URL, latency time.Duration) { - clientGoRequestLatencyMetricVec.WithLabelValues(u.EscapedPath()).Observe(latency.Seconds()) -} - -// Definition of client-go workqueue metrics provider definition -type clientGoWorkqueueMetricsProvider struct{} - -func (f *clientGoWorkqueueMetricsProvider) Register(registerer prometheus.Registerer) { - workqueue.SetProvider(f) - registerer.MustRegister( - clientGoWorkqueueDepthMetricVec, - clientGoWorkqueueAddsMetricVec, - clientGoWorkqueueLatencyMetricVec, - clientGoWorkqueueWorkDurationMetricVec, - clientGoWorkqueueUnfinishedWorkSecondsMetricVec, - clientGoWorkqueueLongestRunningProcessorMetricVec, - ) -} - -func (f *clientGoWorkqueueMetricsProvider) NewDepthMetric(name string) workqueue.GaugeMetric { - return clientGoWorkqueueDepthMetricVec.WithLabelValues(name) -} - -func (f *clientGoWorkqueueMetricsProvider) NewAddsMetric(name string) workqueue.CounterMetric { - return clientGoWorkqueueAddsMetricVec.WithLabelValues(name) -} - -func (f *clientGoWorkqueueMetricsProvider) NewLatencyMetric(name string) workqueue.HistogramMetric { - return clientGoWorkqueueLatencyMetricVec.WithLabelValues(name) -} - -func (f *clientGoWorkqueueMetricsProvider) NewWorkDurationMetric(name string) workqueue.HistogramMetric { - return clientGoWorkqueueWorkDurationMetricVec.WithLabelValues(name) -} - -func (f *clientGoWorkqueueMetricsProvider) NewUnfinishedWorkSecondsMetric(name string) workqueue.SettableGaugeMetric { - return clientGoWorkqueueUnfinishedWorkSecondsMetricVec.WithLabelValues(name) -} - -func (f *clientGoWorkqueueMetricsProvider) NewLongestRunningProcessorSecondsMetric(name string) workqueue.SettableGaugeMetric { - return clientGoWorkqueueLongestRunningProcessorMetricVec.WithLabelValues(name) -} - -func (clientGoWorkqueueMetricsProvider) NewRetriesMetric(string) workqueue.CounterMetric { - // Retries are not used so the metric is omitted. - return noopMetric{} -} diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpoints.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpoints.go index 27742ab46..d8c9689ca 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpoints.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpoints.go @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -// nolint:revive // Many legitimately empty blocks in this file. package kubernetes import ( @@ -23,19 +22,13 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" apiv1 "k8s.io/api/core/v1" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "github.com/prometheus/prometheus/discovery/targetgroup" - "github.com/prometheus/prometheus/util/strutil" -) - -var ( - epAddCount = eventCount.WithLabelValues("endpoints", "add") - epUpdateCount = eventCount.WithLabelValues("endpoints", "update") - epDeleteCount = eventCount.WithLabelValues("endpoints", "delete") ) // Endpoints discovers new endpoint targets. @@ -56,10 +49,19 @@ type Endpoints struct { } // NewEndpoints returns a new endpoints discovery. -func NewEndpoints(l log.Logger, eps cache.SharedIndexInformer, svc, pod, node cache.SharedInformer) *Endpoints { +func NewEndpoints(l log.Logger, eps cache.SharedIndexInformer, svc, pod, node cache.SharedInformer, eventCount *prometheus.CounterVec) *Endpoints { if l == nil { l = log.NewNopLogger() } + + epAddCount := eventCount.WithLabelValues(RoleEndpoint.String(), MetricLabelRoleAdd) + epUpdateCount := eventCount.WithLabelValues(RoleEndpoint.String(), MetricLabelRoleUpdate) + epDeleteCount := eventCount.WithLabelValues(RoleEndpoint.String(), MetricLabelRoleDelete) + + svcAddCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleAdd) + svcUpdateCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleUpdate) + svcDeleteCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleDelete) + e := &Endpoints{ logger: l, endpointsInf: eps, @@ -70,7 +72,7 @@ func NewEndpoints(l log.Logger, eps cache.SharedIndexInformer, svc, pod, node ca podStore: pod.GetStore(), nodeInf: node, withNodeMetadata: node != nil, - queue: workqueue.NewNamed("endpoints"), + queue: workqueue.NewNamed(RoleEndpoint.String()), } _, err := e.endpointsInf.AddEventHandler(cache.ResourceEventHandlerFuncs{ @@ -248,9 +250,6 @@ func endpointsSourceFromNamespaceAndName(namespace, name string) string { } const ( - endpointsLabelPrefix = metaLabelPrefix + "endpoints_label_" - endpointsLabelPresentPrefix = metaLabelPrefix + "endpoints_labelpresent_" - endpointsNameLabel = metaLabelPrefix + "endpoints_name" endpointNodeName = metaLabelPrefix + "endpoint_node_name" endpointHostname = metaLabelPrefix + "endpoint_hostname" endpointReadyLabel = metaLabelPrefix + "endpoint_ready" @@ -265,16 +264,11 @@ func (e *Endpoints) buildEndpoints(eps *apiv1.Endpoints) *targetgroup.Group { Source: endpointsSource(eps), } tg.Labels = model.LabelSet{ - namespaceLabel: lv(eps.Namespace), - endpointsNameLabel: lv(eps.Name), + namespaceLabel: lv(eps.Namespace), } e.addServiceLabels(eps.Namespace, eps.Name, tg) // Add endpoints labels metadata. - for k, v := range eps.Labels { - ln := strutil.SanitizeLabelName(k) - tg.Labels[model.LabelName(endpointsLabelPrefix+ln)] = lv(v) - tg.Labels[model.LabelName(endpointsLabelPresentPrefix+ln)] = presentValue - } + addObjectMetaLabels(tg.Labels, eps.ObjectMeta, RoleEndpoint) type podEntry struct { pod *apiv1.Pod @@ -305,7 +299,11 @@ func (e *Endpoints) buildEndpoints(eps *apiv1.Endpoints) *targetgroup.Group { } if e.withNodeMetadata { - target = addNodeLabels(target, e.nodeInf, e.logger, addr.NodeName) + if addr.NodeName != nil { + target = addNodeLabels(target, e.nodeInf, e.logger, addr.NodeName) + } else if addr.TargetRef != nil && addr.TargetRef.Kind == "Node" { + target = addNodeLabels(target, e.nodeInf, e.logger, &addr.TargetRef.Name) + } } pod := e.resolvePodRef(addr.TargetRef) @@ -371,6 +369,11 @@ func (e *Endpoints) buildEndpoints(eps *apiv1.Endpoints) *targetgroup.Group { // For all seen pods, check all container ports. If they were not covered // by one of the service endpoints, generate targets for them. for _, pe := range seenPods { + // PodIP can be empty when a pod is starting or has been evicted. + if len(pe.pod.Status.PodIP) == 0 { + continue + } + for _, c := range pe.pod.Spec.Containers { for _, cport := range c.Ports { hasSeenPort := func() bool { @@ -458,13 +461,7 @@ func addNodeLabels(tg model.LabelSet, nodeInf cache.SharedInformer, logger log.L node := obj.(*apiv1.Node) // Allocate one target label for the node name, - // and two target labels for each node label. - nodeLabelset := make(model.LabelSet, 1+2*len(node.GetLabels())) - nodeLabelset[nodeNameLabel] = lv(*nodeName) - for k, v := range node.GetLabels() { - ln := strutil.SanitizeLabelName(k) - nodeLabelset[model.LabelName(nodeLabelPrefix+ln)] = lv(v) - nodeLabelset[model.LabelName(nodeLabelPresentPrefix+ln)] = presentValue - } + nodeLabelset := make(model.LabelSet) + addObjectMetaLabels(nodeLabelset, node.ObjectMeta, RoleNode) return tg.Merge(nodeLabelset) } diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice.go index 841b7d4f6..f977ce262 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice.go @@ -15,12 +15,14 @@ package kubernetes import ( "context" + "errors" "fmt" "net" "strconv" "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" apiv1 "k8s.io/api/core/v1" v1 "k8s.io/api/discovery/v1" @@ -32,12 +34,6 @@ import ( "github.com/prometheus/prometheus/util/strutil" ) -var ( - epslAddCount = eventCount.WithLabelValues("endpointslice", "add") - epslUpdateCount = eventCount.WithLabelValues("endpointslice", "update") - epslDeleteCount = eventCount.WithLabelValues("endpointslice", "delete") -) - // EndpointSlice discovers new endpoint targets. type EndpointSlice struct { logger log.Logger @@ -56,10 +52,19 @@ type EndpointSlice struct { } // NewEndpointSlice returns a new endpointslice discovery. -func NewEndpointSlice(l log.Logger, eps cache.SharedIndexInformer, svc, pod, node cache.SharedInformer) *EndpointSlice { +func NewEndpointSlice(l log.Logger, eps cache.SharedIndexInformer, svc, pod, node cache.SharedInformer, eventCount *prometheus.CounterVec) *EndpointSlice { if l == nil { l = log.NewNopLogger() } + + epslAddCount := eventCount.WithLabelValues(RoleEndpointSlice.String(), MetricLabelRoleAdd) + epslUpdateCount := eventCount.WithLabelValues(RoleEndpointSlice.String(), MetricLabelRoleUpdate) + epslDeleteCount := eventCount.WithLabelValues(RoleEndpointSlice.String(), MetricLabelRoleDelete) + + svcAddCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleAdd) + svcUpdateCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleUpdate) + svcDeleteCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleDelete) + e := &EndpointSlice{ logger: l, endpointSliceInf: eps, @@ -70,7 +75,7 @@ func NewEndpointSlice(l log.Logger, eps cache.SharedIndexInformer, svc, pod, nod podStore: pod.GetStore(), nodeInf: node, withNodeMetadata: node != nil, - queue: workqueue.NewNamed("endpointSlice"), + queue: workqueue.NewNamed(RoleEndpointSlice.String()), } _, err := e.endpointSliceInf.AddEventHandler(cache.ResourceEventHandlerFuncs{ @@ -183,14 +188,14 @@ func (e *EndpointSlice) Run(ctx context.Context, ch chan<- []*targetgroup.Group) cacheSyncs = append(cacheSyncs, e.nodeInf.HasSynced) } if !cache.WaitForCacheSync(ctx.Done(), cacheSyncs...) { - if ctx.Err() != context.Canceled { + if !errors.Is(ctx.Err(), context.Canceled) { level.Error(e.logger).Log("msg", "endpointslice informer unable to sync cache") } return } go func() { - for e.process(ctx, ch) { // nolint:revive + for e.process(ctx, ch) { } }() @@ -252,7 +257,6 @@ func endpointSliceSourceFromNamespaceAndName(namespace, name string) string { } const ( - endpointSliceNameLabel = metaLabelPrefix + "endpointslice_name" endpointSliceAddressTypeLabel = metaLabelPrefix + "endpointslice_address_type" endpointSlicePortNameLabel = metaLabelPrefix + "endpointslice_port_name" endpointSlicePortProtocolLabel = metaLabelPrefix + "endpointslice_port_protocol" @@ -274,9 +278,11 @@ func (e *EndpointSlice) buildEndpointSlice(eps endpointSliceAdaptor) *targetgrou } tg.Labels = model.LabelSet{ namespaceLabel: lv(eps.namespace()), - endpointSliceNameLabel: lv(eps.name()), endpointSliceAddressTypeLabel: lv(eps.addressType()), } + + addObjectMetaLabels(tg.Labels, eps.getObjectMeta(), RoleEndpointSlice) + e.addServiceLabels(eps, tg) type podEntry struct { @@ -339,7 +345,11 @@ func (e *EndpointSlice) buildEndpointSlice(eps endpointSliceAdaptor) *targetgrou } if e.withNodeMetadata { - target = addNodeLabels(target, e.nodeInf, e.logger, ep.nodename()) + if ep.targetRef() != nil && ep.targetRef().Kind == "Node" { + target = addNodeLabels(target, e.nodeInf, e.logger, &ep.targetRef().Name) + } else { + target = addNodeLabels(target, e.nodeInf, e.logger, ep.nodename()) + } } pod := e.resolvePodRef(ep.targetRef()) @@ -395,6 +405,11 @@ func (e *EndpointSlice) buildEndpointSlice(eps endpointSliceAdaptor) *targetgrou // For all seen pods, check all container ports. If they were not covered // by one of the service endpoints, generate targets for them. for _, pe := range seenPods { + // PodIP can be empty when a pod is starting or has been evicted. + if len(pe.pod.Status.PodIP) == 0 { + continue + } + for _, c := range pe.pod.Spec.Containers { for _, cport := range c.Ports { hasSeenPort := func() bool { diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice_adaptor.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice_adaptor.go index 5a21f1b89..6bd5f40b7 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice_adaptor.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpointslice_adaptor.go @@ -17,11 +17,13 @@ import ( corev1 "k8s.io/api/core/v1" v1 "k8s.io/api/discovery/v1" "k8s.io/api/discovery/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// endpointSliceAdaptor is an adaptor for the different EndpointSlice versions +// endpointSliceAdaptor is an adaptor for the different EndpointSlice versions. type endpointSliceAdaptor interface { get() interface{} + getObjectMeta() metav1.ObjectMeta name() string namespace() string addressType() string @@ -53,7 +55,7 @@ type endpointSliceEndpointConditionsAdaptor interface { terminating() *bool } -// Adaptor for k8s.io/api/discovery/v1 +// Adaptor for k8s.io/api/discovery/v1. type endpointSliceAdaptorV1 struct { endpointSlice *v1.EndpointSlice } @@ -66,6 +68,10 @@ func (e *endpointSliceAdaptorV1) get() interface{} { return e.endpointSlice } +func (e *endpointSliceAdaptorV1) getObjectMeta() metav1.ObjectMeta { + return e.endpointSlice.ObjectMeta +} + func (e *endpointSliceAdaptorV1) name() string { return e.endpointSlice.ObjectMeta.Name } @@ -102,7 +108,7 @@ func (e *endpointSliceAdaptorV1) labelServiceName() string { return v1.LabelServiceName } -// Adaptor for k8s.io/api/discovery/v1beta1 +// Adaptor for k8s.io/api/discovery/v1beta1. type endpointSliceAdaptorV1Beta1 struct { endpointSlice *v1beta1.EndpointSlice } @@ -115,6 +121,10 @@ func (e *endpointSliceAdaptorV1Beta1) get() interface{} { return e.endpointSlice } +func (e *endpointSliceAdaptorV1Beta1) getObjectMeta() metav1.ObjectMeta { + return e.endpointSlice.ObjectMeta +} + func (e *endpointSliceAdaptorV1Beta1) name() string { return e.endpointSlice.Name } diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress.go index ad47c341a..7b6366b25 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress.go @@ -21,6 +21,7 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" v1 "k8s.io/api/networking/v1" "k8s.io/api/networking/v1beta1" @@ -28,13 +29,6 @@ import ( "k8s.io/client-go/util/workqueue" "github.com/prometheus/prometheus/discovery/targetgroup" - "github.com/prometheus/prometheus/util/strutil" -) - -var ( - ingressAddCount = eventCount.WithLabelValues("ingress", "add") - ingressUpdateCount = eventCount.WithLabelValues("ingress", "update") - ingressDeleteCount = eventCount.WithLabelValues("ingress", "delete") ) // Ingress implements discovery of Kubernetes ingress. @@ -46,8 +40,18 @@ type Ingress struct { } // NewIngress returns a new ingress discovery. -func NewIngress(l log.Logger, inf cache.SharedInformer) *Ingress { - s := &Ingress{logger: l, informer: inf, store: inf.GetStore(), queue: workqueue.NewNamed("ingress")} +func NewIngress(l log.Logger, inf cache.SharedInformer, eventCount *prometheus.CounterVec) *Ingress { + ingressAddCount := eventCount.WithLabelValues(RoleIngress.String(), MetricLabelRoleAdd) + ingressUpdateCount := eventCount.WithLabelValues(RoleIngress.String(), MetricLabelRoleUpdate) + ingressDeleteCount := eventCount.WithLabelValues(RoleIngress.String(), MetricLabelRoleDelete) + + s := &Ingress{ + logger: l, + informer: inf, + store: inf.GetStore(), + queue: workqueue.NewNamed(RoleIngress.String()), + } + _, err := s.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(o interface{}) { ingressAddCount.Inc() @@ -89,7 +93,7 @@ func (i *Ingress) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { } go func() { - for i.process(ctx, ch) { // nolint:revive + for i.process(ctx, ch) { } }() @@ -143,37 +147,22 @@ func ingressSourceFromNamespaceAndName(namespace, name string) string { } const ( - ingressNameLabel = metaLabelPrefix + "ingress_name" - ingressLabelPrefix = metaLabelPrefix + "ingress_label_" - ingressLabelPresentPrefix = metaLabelPrefix + "ingress_labelpresent_" - ingressAnnotationPrefix = metaLabelPrefix + "ingress_annotation_" - ingressAnnotationPresentPrefix = metaLabelPrefix + "ingress_annotationpresent_" - ingressSchemeLabel = metaLabelPrefix + "ingress_scheme" - ingressHostLabel = metaLabelPrefix + "ingress_host" - ingressPathLabel = metaLabelPrefix + "ingress_path" - ingressClassNameLabel = metaLabelPrefix + "ingress_class_name" + ingressSchemeLabel = metaLabelPrefix + "ingress_scheme" + ingressHostLabel = metaLabelPrefix + "ingress_host" + ingressPathLabel = metaLabelPrefix + "ingress_path" + ingressClassNameLabel = metaLabelPrefix + "ingress_class_name" ) func ingressLabels(ingress ingressAdaptor) model.LabelSet { // Each label and annotation will create two key-value pairs in the map. - ls := make(model.LabelSet, 2*(len(ingress.labels())+len(ingress.annotations()))+2) - ls[ingressNameLabel] = lv(ingress.name()) + ls := make(model.LabelSet) ls[namespaceLabel] = lv(ingress.namespace()) if cls := ingress.ingressClassName(); cls != nil { ls[ingressClassNameLabel] = lv(*cls) } - for k, v := range ingress.labels() { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(ingressLabelPrefix+ln)] = lv(v) - ls[model.LabelName(ingressLabelPresentPrefix+ln)] = presentValue - } + addObjectMetaLabels(ls, ingress.getObjectMeta(), RoleIngress) - for k, v := range ingress.annotations() { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(ingressAnnotationPrefix+ln)] = lv(v) - ls[model.LabelName(ingressAnnotationPresentPrefix+ln)] = presentValue - } return ls } diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress_adaptor.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress_adaptor.go index 113a067ca..d1a7b7f2a 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress_adaptor.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress_adaptor.go @@ -16,10 +16,12 @@ package kubernetes import ( v1 "k8s.io/api/networking/v1" "k8s.io/api/networking/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// ingressAdaptor is an adaptor for the different Ingress versions +// ingressAdaptor is an adaptor for the different Ingress versions. type ingressAdaptor interface { + getObjectMeta() metav1.ObjectMeta name() string namespace() string labels() map[string]string @@ -34,7 +36,7 @@ type ingressRuleAdaptor interface { host() string } -// Adaptor for networking.k8s.io/v1 +// Adaptor for networking.k8s.io/v1. type ingressAdaptorV1 struct { ingress *v1.Ingress } @@ -43,11 +45,12 @@ func newIngressAdaptorFromV1(ingress *v1.Ingress) ingressAdaptor { return &ingressAdaptorV1{ingress: ingress} } -func (i *ingressAdaptorV1) name() string { return i.ingress.Name } -func (i *ingressAdaptorV1) namespace() string { return i.ingress.Namespace } -func (i *ingressAdaptorV1) labels() map[string]string { return i.ingress.Labels } -func (i *ingressAdaptorV1) annotations() map[string]string { return i.ingress.Annotations } -func (i *ingressAdaptorV1) ingressClassName() *string { return i.ingress.Spec.IngressClassName } +func (i *ingressAdaptorV1) getObjectMeta() metav1.ObjectMeta { return i.ingress.ObjectMeta } +func (i *ingressAdaptorV1) name() string { return i.ingress.Name } +func (i *ingressAdaptorV1) namespace() string { return i.ingress.Namespace } +func (i *ingressAdaptorV1) labels() map[string]string { return i.ingress.Labels } +func (i *ingressAdaptorV1) annotations() map[string]string { return i.ingress.Annotations } +func (i *ingressAdaptorV1) ingressClassName() *string { return i.ingress.Spec.IngressClassName } func (i *ingressAdaptorV1) tlsHosts() []string { var hosts []string @@ -87,7 +90,7 @@ func (i *ingressRuleAdaptorV1) paths() []string { func (i *ingressRuleAdaptorV1) host() string { return i.rule.Host } -// Adaptor for networking.k8s.io/v1beta1 +// Adaptor for networking.k8s.io/v1beta1. type ingressAdaptorV1Beta1 struct { ingress *v1beta1.Ingress } @@ -95,12 +98,12 @@ type ingressAdaptorV1Beta1 struct { func newIngressAdaptorFromV1beta1(ingress *v1beta1.Ingress) ingressAdaptor { return &ingressAdaptorV1Beta1{ingress: ingress} } - -func (i *ingressAdaptorV1Beta1) name() string { return i.ingress.Name } -func (i *ingressAdaptorV1Beta1) namespace() string { return i.ingress.Namespace } -func (i *ingressAdaptorV1Beta1) labels() map[string]string { return i.ingress.Labels } -func (i *ingressAdaptorV1Beta1) annotations() map[string]string { return i.ingress.Annotations } -func (i *ingressAdaptorV1Beta1) ingressClassName() *string { return i.ingress.Spec.IngressClassName } +func (i *ingressAdaptorV1Beta1) getObjectMeta() metav1.ObjectMeta { return i.ingress.ObjectMeta } +func (i *ingressAdaptorV1Beta1) name() string { return i.ingress.Name } +func (i *ingressAdaptorV1Beta1) namespace() string { return i.ingress.Namespace } +func (i *ingressAdaptorV1Beta1) labels() map[string]string { return i.ingress.Labels } +func (i *ingressAdaptorV1Beta1) annotations() map[string]string { return i.ingress.Annotations } +func (i *ingressAdaptorV1Beta1) ingressClassName() *string { return i.ingress.Spec.IngressClassName } func (i *ingressAdaptorV1Beta1) tlsHosts() []string { var hosts []string diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go index a44bd513c..362e05326 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go @@ -23,6 +23,8 @@ import ( "sync" "time" + "github.com/prometheus/prometheus/util/strutil" + disv1beta1 "k8s.io/api/discovery/v1beta1" "github.com/go-kit/log" @@ -56,25 +58,15 @@ import ( const ( // metaLabelPrefix is the meta prefix used for all meta labels. // in this discovery. - metaLabelPrefix = model.MetaLabelPrefix + "kubernetes_" - namespaceLabel = metaLabelPrefix + "namespace" - metricsNamespace = "prometheus_sd_kubernetes" - presentValue = model.LabelValue("true") + metaLabelPrefix = model.MetaLabelPrefix + "kubernetes_" + namespaceLabel = metaLabelPrefix + "namespace" + presentValue = model.LabelValue("true") ) var ( - // Http header + // Http header. userAgent = fmt.Sprintf("Prometheus/%s", version.Version) - // Custom events metric - eventCount = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Namespace: metricsNamespace, - Name: "events_total", - Help: "The number of Kubernetes events handled.", - }, - []string{"role", "event"}, - ) - // DefaultSDConfig is the default Kubernetes SD configuration + // DefaultSDConfig is the default Kubernetes SD configuration. DefaultSDConfig = SDConfig{ HTTPClientConfig: config.DefaultHTTPClientConfig, } @@ -82,15 +74,6 @@ var ( func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(eventCount) - // Initialize metric vectors. - for _, role := range []string{"endpointslice", "endpoints", "node", "pod", "service", "ingress"} { - for _, evt := range []string{"add", "delete", "update"} { - eventCount.WithLabelValues(role, evt) - } - } - (&clientGoRequestMetricAdapter{}).Register(prometheus.DefaultRegisterer) - (&clientGoWorkqueueMetricsProvider{}).Register(prometheus.DefaultRegisterer) } // Role is role of the service in Kubernetes. @@ -119,6 +102,16 @@ func (c *Role) UnmarshalYAML(unmarshal func(interface{}) error) error { } } +func (c Role) String() string { + return string(c) +} + +const ( + MetricLabelRoleAdd = "add" + MetricLabelRoleDelete = "delete" + MetricLabelRoleUpdate = "update" +) + // SDConfig is the configuration for Kubernetes service discovery. type SDConfig struct { APIServer config.URL `yaml:"api_server,omitempty"` @@ -130,12 +123,17 @@ type SDConfig struct { AttachMetadata AttachMetadataConfig `yaml:"attach_metadata,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "kubernetes" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return New(opts.Logger, c) + return New(opts.Logger, opts.Metrics, c) } // SetDirectory joins any relative file paths with dir. @@ -272,6 +270,7 @@ type Discovery struct { selectors roleSelector ownNamespace string attachMetadata AttachMetadataConfig + metrics *kubernetesMetrics } func (d *Discovery) getNamespaces() []string { @@ -290,7 +289,12 @@ func (d *Discovery) getNamespaces() []string { } // New creates a new Kubernetes discovery for the given role. -func New(l log.Logger, conf *SDConfig) (*Discovery, error) { +func New(l log.Logger, metrics discovery.DiscovererMetrics, conf *SDConfig) (*Discovery, error) { + m, ok := metrics.(*kubernetesMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if l == nil { l = log.NewNopLogger() } @@ -344,7 +348,7 @@ func New(l log.Logger, conf *SDConfig) (*Discovery, error) { return nil, err } - return &Discovery{ + d := &Discovery{ client: c, logger: l, role: conf.Role, @@ -353,7 +357,10 @@ func New(l log.Logger, conf *SDConfig) (*Discovery, error) { selectors: mapSelector(conf.Selectors), ownNamespace: ownNamespace, attachMetadata: conf.AttachMetadata, - }, nil + metrics: m, + } + + return d, nil } func mapSelector(rawSelector []SelectorConfig) roleSelector { @@ -389,6 +396,7 @@ const resyncDisabled = 0 // Run implements the discoverer interface. func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { d.Lock() + namespaces := d.getNamespaces() switch d.role { @@ -480,6 +488,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { cache.NewSharedInformer(slw, &apiv1.Service{}, resyncDisabled), cache.NewSharedInformer(plw, &apiv1.Pod{}, resyncDisabled), nodeInf, + d.metrics.eventCount, ) d.discoverers = append(d.discoverers, eps) go eps.endpointSliceInf.Run(ctx.Done()) @@ -539,6 +548,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { cache.NewSharedInformer(slw, &apiv1.Service{}, resyncDisabled), cache.NewSharedInformer(plw, &apiv1.Pod{}, resyncDisabled), nodeInf, + d.metrics.eventCount, ) d.discoverers = append(d.discoverers, eps) go eps.endpointsInf.Run(ctx.Done()) @@ -570,6 +580,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { log.With(d.logger, "role", "pod"), d.newPodsByNodeInformer(plw), nodeInformer, + d.metrics.eventCount, ) d.discoverers = append(d.discoverers, pod) go pod.podInf.Run(ctx.Done()) @@ -592,6 +603,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { svc := NewService( log.With(d.logger, "role", "service"), cache.NewSharedInformer(slw, &apiv1.Service{}, resyncDisabled), + d.metrics.eventCount, ) d.discoverers = append(d.discoverers, svc) go svc.informer.Run(ctx.Done()) @@ -649,13 +661,14 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { ingress := NewIngress( log.With(d.logger, "role", "ingress"), informer, + d.metrics.eventCount, ) d.discoverers = append(d.discoverers, ingress) go ingress.informer.Run(ctx.Done()) } case RoleNode: nodeInformer := d.newNodeInformer(ctx) - node := NewNode(log.With(d.logger, "role", "node"), nodeInformer) + node := NewNode(log.With(d.logger, "role", "node"), nodeInformer, d.metrics.eventCount) d.discoverers = append(d.discoverers, node) go node.informer.Run(ctx.Done()) default: @@ -761,15 +774,21 @@ func (d *Discovery) newEndpointsByNodeInformer(plw *cache.ListWatch) cache.Share indexers[nodeIndex] = func(obj interface{}) ([]string, error) { e, ok := obj.(*apiv1.Endpoints) if !ok { - return nil, fmt.Errorf("object is not a pod") + return nil, fmt.Errorf("object is not endpoints") } var nodes []string for _, target := range e.Subsets { for _, addr := range target.Addresses { - if addr.NodeName == nil { - continue + if addr.TargetRef != nil { + switch addr.TargetRef.Kind { + case "Pod": + if addr.NodeName != nil { + nodes = append(nodes, *addr.NodeName) + } + case "Node": + nodes = append(nodes, addr.TargetRef.Name) + } } - nodes = append(nodes, *addr.NodeName) } } return nodes, nil @@ -789,17 +808,29 @@ func (d *Discovery) newEndpointSlicesByNodeInformer(plw *cache.ListWatch, object switch e := obj.(type) { case *disv1.EndpointSlice: for _, target := range e.Endpoints { - if target.NodeName == nil { - continue + if target.TargetRef != nil { + switch target.TargetRef.Kind { + case "Pod": + if target.NodeName != nil { + nodes = append(nodes, *target.NodeName) + } + case "Node": + nodes = append(nodes, target.TargetRef.Name) + } } - nodes = append(nodes, *target.NodeName) } case *disv1beta1.EndpointSlice: for _, target := range e.Endpoints { - if target.NodeName == nil { - continue + if target.TargetRef != nil { + switch target.TargetRef.Kind { + case "Pod": + if target.NodeName != nil { + nodes = append(nodes, *target.NodeName) + } + case "Node": + nodes = append(nodes, target.TargetRef.Name) + } } - nodes = append(nodes, *target.NodeName) } default: return nil, fmt.Errorf("object is not an endpointslice") @@ -825,3 +856,19 @@ func checkDiscoveryV1Supported(client kubernetes.Interface) (bool, error) { // https://kubernetes.io/docs/reference/using-api/deprecation-guide/#v1-25 return semVer.Major() >= 1 && semVer.Minor() >= 21, nil } + +func addObjectMetaLabels(labelSet model.LabelSet, objectMeta metav1.ObjectMeta, role Role) { + labelSet[model.LabelName(metaLabelPrefix+string(role)+"_name")] = lv(objectMeta.Name) + + for k, v := range objectMeta.Labels { + ln := strutil.SanitizeLabelName(k) + labelSet[model.LabelName(metaLabelPrefix+string(role)+"_label_"+ln)] = lv(v) + labelSet[model.LabelName(metaLabelPrefix+string(role)+"_labelpresent_"+ln)] = presentValue + } + + for k, v := range objectMeta.Annotations { + ln := strutil.SanitizeLabelName(k) + labelSet[model.LabelName(metaLabelPrefix+string(role)+"_annotation_"+ln)] = lv(v) + labelSet[model.LabelName(metaLabelPrefix+string(role)+"_annotationpresent_"+ln)] = presentValue + } +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/metrics.go new file mode 100644 index 000000000..7d384fb96 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/metrics.go @@ -0,0 +1,75 @@ +// Copyright 2015 The Prometheus 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 kubernetes + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*kubernetesMetrics)(nil) + +type kubernetesMetrics struct { + eventCount *prometheus.CounterVec + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &kubernetesMetrics{ + eventCount: prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: discovery.KubernetesMetricsNamespace, + Name: "events_total", + Help: "The number of Kubernetes events handled.", + }, + []string{"role", "event"}, + ), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.eventCount, + }) + + // Initialize metric vectors. + for _, role := range []string{ + RoleEndpointSlice.String(), + RoleEndpoint.String(), + RoleNode.String(), + RolePod.String(), + RoleService.String(), + RoleIngress.String(), + } { + for _, evt := range []string{ + MetricLabelRoleAdd, + MetricLabelRoleDelete, + MetricLabelRoleUpdate, + } { + m.eventCount.WithLabelValues(role, evt) + } + } + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *kubernetesMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *kubernetesMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/node.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/node.go index 16a06e7a0..74d87e22c 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/node.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/node.go @@ -22,6 +22,7 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" apiv1 "k8s.io/api/core/v1" "k8s.io/client-go/tools/cache" @@ -35,12 +36,6 @@ const ( NodeLegacyHostIP = "LegacyHostIP" ) -var ( - nodeAddCount = eventCount.WithLabelValues("node", "add") - nodeUpdateCount = eventCount.WithLabelValues("node", "update") - nodeDeleteCount = eventCount.WithLabelValues("node", "delete") -) - // Node discovers Kubernetes nodes. type Node struct { logger log.Logger @@ -50,11 +45,22 @@ type Node struct { } // NewNode returns a new node discovery. -func NewNode(l log.Logger, inf cache.SharedInformer) *Node { +func NewNode(l log.Logger, inf cache.SharedInformer, eventCount *prometheus.CounterVec) *Node { if l == nil { l = log.NewNopLogger() } - n := &Node{logger: l, informer: inf, store: inf.GetStore(), queue: workqueue.NewNamed("node")} + + nodeAddCount := eventCount.WithLabelValues(RoleNode.String(), MetricLabelRoleAdd) + nodeUpdateCount := eventCount.WithLabelValues(RoleNode.String(), MetricLabelRoleUpdate) + nodeDeleteCount := eventCount.WithLabelValues(RoleNode.String(), MetricLabelRoleDelete) + + n := &Node{ + logger: l, + informer: inf, + store: inf.GetStore(), + queue: workqueue.NewNamed(RoleNode.String()), + } + _, err := n.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(o interface{}) { nodeAddCount.Inc() @@ -96,7 +102,7 @@ func (n *Node) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { } go func() { - for n.process(ctx, ch) { // nolint:revive + for n.process(ctx, ch) { } }() @@ -152,33 +158,18 @@ func nodeSourceFromName(name string) string { } const ( - nodeNameLabel = metaLabelPrefix + "node_name" - nodeProviderIDLabel = metaLabelPrefix + "node_provider_id" - nodeLabelPrefix = metaLabelPrefix + "node_label_" - nodeLabelPresentPrefix = metaLabelPrefix + "node_labelpresent_" - nodeAnnotationPrefix = metaLabelPrefix + "node_annotation_" - nodeAnnotationPresentPrefix = metaLabelPrefix + "node_annotationpresent_" - nodeAddressPrefix = metaLabelPrefix + "node_address_" + nodeProviderIDLabel = metaLabelPrefix + "node_provider_id" + nodeAddressPrefix = metaLabelPrefix + "node_address_" ) func nodeLabels(n *apiv1.Node) model.LabelSet { // Each label and annotation will create two key-value pairs in the map. - ls := make(model.LabelSet, 2*(len(n.Labels)+len(n.Annotations))+1) + ls := make(model.LabelSet) - ls[nodeNameLabel] = lv(n.Name) ls[nodeProviderIDLabel] = lv(n.Spec.ProviderID) - for k, v := range n.Labels { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(nodeLabelPrefix+ln)] = lv(v) - ls[model.LabelName(nodeLabelPresentPrefix+ln)] = presentValue - } + addObjectMetaLabels(ls, n.ObjectMeta, RoleNode) - for k, v := range n.Annotations { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(nodeAnnotationPrefix+ln)] = lv(v) - ls[model.LabelName(nodeAnnotationPresentPrefix+ln)] = presentValue - } return ls } @@ -209,7 +200,7 @@ func (n *Node) buildNode(node *apiv1.Node) *targetgroup.Group { return tg } -// nodeAddresses returns the provided node's address, based on the priority: +// nodeAddress returns the provided node's address, based on the priority: // 1. NodeInternalIP // 2. NodeInternalDNS // 3. NodeExternalIP @@ -217,7 +208,7 @@ func (n *Node) buildNode(node *apiv1.Node) *targetgroup.Group { // 5. NodeLegacyHostIP // 6. NodeHostName // -// Derived from k8s.io/kubernetes/pkg/util/node/node.go +// Derived from k8s.io/kubernetes/pkg/util/node/node.go. func nodeAddress(node *apiv1.Node) (string, map[apiv1.NodeAddressType][]string, error) { m := map[apiv1.NodeAddressType][]string{} for _, a := range node.Status.Addresses { diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/pod.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/pod.go index 732cf52ad..615717c13 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/pod.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/pod.go @@ -23,6 +23,7 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" apiv1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -30,17 +31,10 @@ import ( "k8s.io/client-go/util/workqueue" "github.com/prometheus/prometheus/discovery/targetgroup" - "github.com/prometheus/prometheus/util/strutil" ) const nodeIndex = "node" -var ( - podAddCount = eventCount.WithLabelValues("pod", "add") - podUpdateCount = eventCount.WithLabelValues("pod", "update") - podDeleteCount = eventCount.WithLabelValues("pod", "delete") -) - // Pod discovers new pod targets. type Pod struct { podInf cache.SharedIndexInformer @@ -52,18 +46,22 @@ type Pod struct { } // NewPod creates a new pod discovery. -func NewPod(l log.Logger, pods cache.SharedIndexInformer, nodes cache.SharedInformer) *Pod { +func NewPod(l log.Logger, pods cache.SharedIndexInformer, nodes cache.SharedInformer, eventCount *prometheus.CounterVec) *Pod { if l == nil { l = log.NewNopLogger() } + podAddCount := eventCount.WithLabelValues(RolePod.String(), MetricLabelRoleAdd) + podDeleteCount := eventCount.WithLabelValues(RolePod.String(), MetricLabelRoleDelete) + podUpdateCount := eventCount.WithLabelValues(RolePod.String(), MetricLabelRoleUpdate) + p := &Pod{ podInf: pods, nodeInf: nodes, withNodeMetadata: nodes != nil, store: pods.GetStore(), logger: l, - queue: workqueue.NewNamed("pod"), + queue: workqueue.NewNamed(RolePod.String()), } _, err := p.podInf.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(o interface{}) { @@ -132,7 +130,7 @@ func (p *Pod) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { } go func() { - for p.process(ctx, ch) { // nolint:revive + for p.process(ctx, ch) { } }() @@ -180,7 +178,6 @@ func convertToPod(o interface{}) (*apiv1.Pod, error) { } const ( - podNameLabel = metaLabelPrefix + "pod_name" podIPLabel = metaLabelPrefix + "pod_ip" podContainerNameLabel = metaLabelPrefix + "pod_container_name" podContainerIDLabel = metaLabelPrefix + "pod_container_id" @@ -191,10 +188,6 @@ const ( podContainerIsInit = metaLabelPrefix + "pod_container_init" podReadyLabel = metaLabelPrefix + "pod_ready" podPhaseLabel = metaLabelPrefix + "pod_phase" - podLabelPrefix = metaLabelPrefix + "pod_label_" - podLabelPresentPrefix = metaLabelPrefix + "pod_labelpresent_" - podAnnotationPrefix = metaLabelPrefix + "pod_annotation_" - podAnnotationPresentPrefix = metaLabelPrefix + "pod_annotationpresent_" podNodeNameLabel = metaLabelPrefix + "pod_node_name" podHostIPLabel = metaLabelPrefix + "pod_host_ip" podUID = metaLabelPrefix + "pod_uid" @@ -215,7 +208,6 @@ func GetControllerOf(controllee metav1.Object) *metav1.OwnerReference { func podLabels(pod *apiv1.Pod) model.LabelSet { ls := model.LabelSet{ - podNameLabel: lv(pod.ObjectMeta.Name), podIPLabel: lv(pod.Status.PodIP), podReadyLabel: podReady(pod), podPhaseLabel: lv(string(pod.Status.Phase)), @@ -224,6 +216,8 @@ func podLabels(pod *apiv1.Pod) model.LabelSet { podUID: lv(string(pod.ObjectMeta.UID)), } + addObjectMetaLabels(ls, pod.ObjectMeta, RolePod) + createdBy := GetControllerOf(pod) if createdBy != nil { if createdBy.Kind != "" { @@ -234,18 +228,6 @@ func podLabels(pod *apiv1.Pod) model.LabelSet { } } - for k, v := range pod.Labels { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(podLabelPrefix+ln)] = lv(v) - ls[model.LabelName(podLabelPresentPrefix+ln)] = presentValue - } - - for k, v := range pod.Annotations { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(podAnnotationPrefix+ln)] = lv(v) - ls[model.LabelName(podAnnotationPresentPrefix+ln)] = presentValue - } - return ls } diff --git a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/service.go b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/service.go index 40e17679e..51204a5a1 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/kubernetes/service.go +++ b/vendor/github.com/prometheus/prometheus/discovery/kubernetes/service.go @@ -22,19 +22,13 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" apiv1 "k8s.io/api/core/v1" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "github.com/prometheus/prometheus/discovery/targetgroup" - "github.com/prometheus/prometheus/util/strutil" -) - -var ( - svcAddCount = eventCount.WithLabelValues("service", "add") - svcUpdateCount = eventCount.WithLabelValues("service", "update") - svcDeleteCount = eventCount.WithLabelValues("service", "delete") ) // Service implements discovery of Kubernetes services. @@ -46,11 +40,22 @@ type Service struct { } // NewService returns a new service discovery. -func NewService(l log.Logger, inf cache.SharedInformer) *Service { +func NewService(l log.Logger, inf cache.SharedInformer, eventCount *prometheus.CounterVec) *Service { if l == nil { l = log.NewNopLogger() } - s := &Service{logger: l, informer: inf, store: inf.GetStore(), queue: workqueue.NewNamed("service")} + + svcAddCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleAdd) + svcUpdateCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleUpdate) + svcDeleteCount := eventCount.WithLabelValues(RoleService.String(), MetricLabelRoleDelete) + + s := &Service{ + logger: l, + informer: inf, + store: inf.GetStore(), + queue: workqueue.NewNamed(RoleService.String()), + } + _, err := s.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(o interface{}) { svcAddCount.Inc() @@ -92,7 +97,7 @@ func (s *Service) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { } go func() { - for s.process(ctx, ch) { // nolint:revive + for s.process(ctx, ch) { } }() @@ -147,38 +152,20 @@ func serviceSourceFromNamespaceAndName(namespace, name string) string { } const ( - serviceNameLabel = metaLabelPrefix + "service_name" - serviceLabelPrefix = metaLabelPrefix + "service_label_" - serviceLabelPresentPrefix = metaLabelPrefix + "service_labelpresent_" - serviceAnnotationPrefix = metaLabelPrefix + "service_annotation_" - serviceAnnotationPresentPrefix = metaLabelPrefix + "service_annotationpresent_" - servicePortNameLabel = metaLabelPrefix + "service_port_name" - servicePortNumberLabel = metaLabelPrefix + "service_port_number" - servicePortProtocolLabel = metaLabelPrefix + "service_port_protocol" - serviceClusterIPLabel = metaLabelPrefix + "service_cluster_ip" - serviceLoadBalancerIP = metaLabelPrefix + "service_loadbalancer_ip" - serviceExternalNameLabel = metaLabelPrefix + "service_external_name" - serviceType = metaLabelPrefix + "service_type" + servicePortNameLabel = metaLabelPrefix + "service_port_name" + servicePortNumberLabel = metaLabelPrefix + "service_port_number" + servicePortProtocolLabel = metaLabelPrefix + "service_port_protocol" + serviceClusterIPLabel = metaLabelPrefix + "service_cluster_ip" + serviceLoadBalancerIP = metaLabelPrefix + "service_loadbalancer_ip" + serviceExternalNameLabel = metaLabelPrefix + "service_external_name" + serviceType = metaLabelPrefix + "service_type" ) func serviceLabels(svc *apiv1.Service) model.LabelSet { - // Each label and annotation will create two key-value pairs in the map. - ls := make(model.LabelSet, 2*(len(svc.Labels)+len(svc.Annotations))+2) - - ls[serviceNameLabel] = lv(svc.Name) + ls := make(model.LabelSet) ls[namespaceLabel] = lv(svc.Namespace) + addObjectMetaLabels(ls, svc.ObjectMeta, RoleService) - for k, v := range svc.Labels { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(serviceLabelPrefix+ln)] = lv(v) - ls[model.LabelName(serviceLabelPresentPrefix+ln)] = presentValue - } - - for k, v := range svc.Annotations { - ln := strutil.SanitizeLabelName(k) - ls[model.LabelName(serviceAnnotationPrefix+ln)] = lv(v) - ls[model.LabelName(serviceAnnotationPresentPrefix+ln)] = presentValue - } return ls } diff --git a/vendor/github.com/prometheus/prometheus/discovery/linode/linode.go b/vendor/github.com/prometheus/prometheus/discovery/linode/linode.go index 12b957514..94f0a63bb 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/linode/linode.go +++ b/vendor/github.com/prometheus/prometheus/discovery/linode/linode.go @@ -51,6 +51,7 @@ const ( linodeLabelStatus = linodeLabel + "status" linodeLabelTags = linodeLabel + "tags" linodeLabelGroup = linodeLabel + "group" + linodeLabelGPUs = linodeLabel + "gpus" linodeLabelHypervisor = linodeLabel + "hypervisor" linodeLabelBackups = linodeLabel + "backups" linodeLabelSpecsDiskBytes = linodeLabel + "specs_disk_bytes" @@ -66,24 +67,15 @@ const ( ) // DefaultSDConfig is the default Linode SD configuration. -var ( - DefaultSDConfig = SDConfig{ - TagSeparator: ",", - Port: 80, - RefreshInterval: model.Duration(60 * time.Second), - HTTPClientConfig: config.DefaultHTTPClientConfig, - } - - failuresCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Name: "prometheus_sd_linode_failures_total", - Help: "Number of Linode service discovery refresh failures.", - }) -) +var DefaultSDConfig = SDConfig{ + TagSeparator: ",", + Port: 80, + RefreshInterval: model.Duration(60 * time.Second), + HTTPClientConfig: config.DefaultHTTPClientConfig, +} func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(failuresCount) } // SDConfig is the configuration for Linode based service discovery. @@ -95,12 +87,17 @@ type SDConfig struct { TagSeparator string `yaml:"tag_separator,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "linode" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -130,16 +127,23 @@ type Discovery struct { pollCount int lastResults []*targetgroup.Group eventPollingEnabled bool + metrics *linodeMetrics } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*linodeMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + d := &Discovery{ port: conf.Port, tagSeparator: conf.TagSeparator, pollCount: 0, lastRefreshTimestamp: time.Now().UTC(), eventPollingEnabled: true, + metrics: m, } rt, err := config.NewRoundTripperFromConfig(conf.HTTPClientConfig, "linode_sd") @@ -157,10 +161,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { d.client = &client d.Discovery = refresh.NewDiscovery( - logger, - "linode", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "linode", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } @@ -221,14 +228,14 @@ func (d *Discovery) refreshData(ctx context.Context) ([]*targetgroup.Group, erro // Gather all linode instances. instances, err := d.client.ListInstances(ctx, &linodego.ListOptions{PageSize: 500}) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, err } // Gather detailed IP address info for all IPs on all linode instances. detailedIPs, err := d.client.ListIPAddresses(ctx, &linodego.ListOptions{PageSize: 500}) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, err } @@ -302,12 +309,13 @@ func (d *Discovery) refreshData(ctx context.Context) ([]*targetgroup.Group, erro linodeLabelType: model.LabelValue(instance.Type), linodeLabelStatus: model.LabelValue(instance.Status), linodeLabelGroup: model.LabelValue(instance.Group), + linodeLabelGPUs: model.LabelValue(fmt.Sprintf("%d", instance.Specs.GPUs)), linodeLabelHypervisor: model.LabelValue(instance.Hypervisor), linodeLabelBackups: model.LabelValue(backupsStatus), - linodeLabelSpecsDiskBytes: model.LabelValue(fmt.Sprintf("%d", instance.Specs.Disk<<20)), - linodeLabelSpecsMemoryBytes: model.LabelValue(fmt.Sprintf("%d", instance.Specs.Memory<<20)), + linodeLabelSpecsDiskBytes: model.LabelValue(fmt.Sprintf("%d", int64(instance.Specs.Disk)<<20)), + linodeLabelSpecsMemoryBytes: model.LabelValue(fmt.Sprintf("%d", int64(instance.Specs.Memory)<<20)), linodeLabelSpecsVCPUs: model.LabelValue(fmt.Sprintf("%d", instance.Specs.VCPUs)), - linodeLabelSpecsTransferBytes: model.LabelValue(fmt.Sprintf("%d", instance.Specs.Transfer<<20)), + linodeLabelSpecsTransferBytes: model.LabelValue(fmt.Sprintf("%d", int64(instance.Specs.Transfer)<<20)), } addr := net.JoinHostPort(publicIPv4, strconv.FormatUint(uint64(d.port), 10)) diff --git a/vendor/github.com/prometheus/prometheus/discovery/linode/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/linode/metrics.go new file mode 100644 index 000000000..8f8138922 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/linode/metrics.go @@ -0,0 +1,57 @@ +// Copyright 2015 The Prometheus 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 linode + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*linodeMetrics)(nil) + +type linodeMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator + + failuresCount prometheus.Counter + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &linodeMetrics{ + refreshMetrics: rmi, + failuresCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_linode_failures_total", + Help: "Number of Linode service discovery refresh failures.", + }), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.failuresCount, + }) + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *linodeMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *linodeMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/manager.go b/vendor/github.com/prometheus/prometheus/discovery/manager.go index 8b304a0fa..e3a263557 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/manager.go +++ b/vendor/github.com/prometheus/prometheus/discovery/manager.go @@ -28,48 +28,6 @@ import ( "github.com/prometheus/prometheus/discovery/targetgroup" ) -var ( - failedConfigs = prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Name: "prometheus_sd_failed_configs", - Help: "Current number of service discovery configurations that failed to load.", - }, - []string{"name"}, - ) - discoveredTargets = prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Name: "prometheus_sd_discovered_targets", - Help: "Current number of discovered targets.", - }, - []string{"name", "config"}, - ) - receivedUpdates = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "prometheus_sd_received_updates_total", - Help: "Total number of update events received from the SD providers.", - }, - []string{"name"}, - ) - delayedUpdates = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "prometheus_sd_updates_delayed_total", - Help: "Total number of update events that couldn't be sent immediately.", - }, - []string{"name"}, - ) - sentUpdates = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "prometheus_sd_updates_total", - Help: "Total number of update events sent to the SD consumers.", - }, - []string{"name"}, - ) -) - -func RegisterMetrics() { - prometheus.MustRegister(failedConfigs, discoveredTargets, receivedUpdates, delayedUpdates, sentUpdates) -} - type poolKey struct { setName string provider string @@ -92,7 +50,7 @@ type Provider struct { newSubs map[string]struct{} } -// Discoverer return the Discoverer of the provider +// Discoverer return the Discoverer of the provider. func (p *Provider) Discoverer() Discoverer { return p.d } @@ -106,8 +64,24 @@ func (p *Provider) Config() interface{} { return p.config } +// Registers the metrics needed for SD mechanisms. +// Does not register the metrics for the Discovery Manager. +// TODO(ptodev): Add ability to unregister the metrics? +func CreateAndRegisterSDMetrics(reg prometheus.Registerer) (map[string]DiscovererMetrics, error) { + // Some SD mechanisms use the "refresh" package, which has its own metrics. + refreshSdMetrics := NewRefreshMetrics(reg) + + // Register the metrics specific for each SD mechanism, and the ones for the refresh package. + sdMetrics, err := RegisterSDMetrics(reg, refreshSdMetrics) + if err != nil { + return nil, fmt.Errorf("failed to register service discovery metrics: %w", err) + } + + return sdMetrics, nil +} + // NewManager is the Discovery Manager constructor. -func NewManager(ctx context.Context, logger log.Logger, options ...func(*Manager)) *Manager { +func NewManager(ctx context.Context, logger log.Logger, registerer prometheus.Registerer, sdMetrics map[string]DiscovererMetrics, options ...func(*Manager)) *Manager { if logger == nil { logger = log.NewNopLogger() } @@ -118,10 +92,22 @@ func NewManager(ctx context.Context, logger log.Logger, options ...func(*Manager ctx: ctx, updatert: 5 * time.Second, triggerSend: make(chan struct{}, 1), + registerer: registerer, + sdMetrics: sdMetrics, } for _, option := range options { option(mgr) } + + // Register the metrics. + // We have to do this after setting all options, so that the name of the Manager is set. + if metrics, err := NewManagerMetrics(registerer, mgr.name); err == nil { + mgr.metrics = metrics + } else { + level.Error(logger).Log("msg", "Failed to create discovery manager metrics", "manager", mgr.name, "err", err) + return nil + } + return mgr } @@ -170,6 +156,12 @@ type Manager struct { // lastProvider counts providers registered during Manager's lifetime. lastProvider uint + + // A registerer for all service discovery metrics. + registerer prometheus.Registerer + + metrics *Metrics + sdMetrics map[string]DiscovererMetrics } // Providers returns the currently configured SD providers. @@ -180,11 +172,9 @@ func (m *Manager) Providers() []*Provider { // Run starts the background processing. func (m *Manager) Run() error { go m.sender() - for range m.ctx.Done() { - m.cancelDiscoverers() - return m.ctx.Err() - } - return nil + <-m.ctx.Done() + m.cancelDiscoverers() + return m.ctx.Err() } // SyncCh returns a read only channel used by all the clients to receive target updates. @@ -202,7 +192,7 @@ func (m *Manager) ApplyConfig(cfg map[string]Configs) error { for name, scfg := range cfg { failedCount += m.registerProviders(scfg, name) } - failedConfigs.WithLabelValues(m.name).Set(float64(failedCount)) + m.metrics.FailedConfigs.Set(float64(failedCount)) var ( wg sync.WaitGroup @@ -232,13 +222,13 @@ func (m *Manager) ApplyConfig(cfg map[string]Configs) error { // Remove obsolete subs' targets. if _, ok := prov.newSubs[s]; !ok { delete(m.targets, poolKey{s, prov.name}) - discoveredTargets.DeleteLabelValues(m.name, s) + m.metrics.DiscoveredTargets.DeleteLabelValues(m.name, s) } } // Set metrics and targets for new subs. for s := range prov.newSubs { if _, ok := prov.subs[s]; !ok { - discoveredTargets.WithLabelValues(m.name, s).Set(0) + m.metrics.DiscoveredTargets.WithLabelValues(s).Set(0) } if l := len(refTargets); l > 0 { m.targets[poolKey{s, prov.name}] = make(map[string]*targetgroup.Group, l) @@ -318,7 +308,7 @@ func (m *Manager) updater(ctx context.Context, p *Provider, updates chan []*targ case <-ctx.Done(): return case tgs, ok := <-updates: - receivedUpdates.WithLabelValues(m.name).Inc() + m.metrics.ReceivedUpdates.Inc() if !ok { level.Debug(m.logger).Log("msg", "Discoverer channel closed", "provider", p.name) // Wait for provider cancellation to ensure targets are cleaned up when expected. @@ -351,11 +341,11 @@ func (m *Manager) sender() { case <-ticker.C: // Some discoverers send updates too often, so we throttle these with the ticker. select { case <-m.triggerSend: - sentUpdates.WithLabelValues(m.name).Inc() + m.metrics.SentUpdates.Inc() select { case m.syncCh <- m.allGroups(): default: - delayedUpdates.WithLabelValues(m.name).Inc() + m.metrics.DelayedUpdates.Inc() level.Debug(m.logger).Log("msg", "Discovery receiver's channel was full so will retry the next cycle") select { case m.triggerSend <- struct{}{}: @@ -407,7 +397,7 @@ func (m *Manager) allGroups() map[string][]*targetgroup.Group { } } for setName, v := range n { - discoveredTargets.WithLabelValues(m.name, setName).Set(float64(v)) + m.metrics.DiscoveredTargets.WithLabelValues(setName).Set(float64(v)) } return tSets } @@ -430,6 +420,7 @@ func (m *Manager) registerProviders(cfgs Configs, setName string) int { d, err := cfg.NewDiscoverer(DiscovererOptions{ Logger: log.With(m.logger, "discovery", typ, "config", setName), HTTPClientOptions: m.httpOpts, + Metrics: m.sdMetrics[typ], }) if err != nil { level.Error(m.logger).Log("msg", "Cannot create service discovery", "err", err, "type", typ, "config", setName) diff --git a/vendor/github.com/prometheus/prometheus/discovery/marathon/marathon.go b/vendor/github.com/prometheus/prometheus/discovery/marathon/marathon.go index cfd3e2c08..ecad108e4 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/marathon/marathon.go +++ b/vendor/github.com/prometheus/prometheus/discovery/marathon/marathon.go @@ -28,6 +28,7 @@ import ( "time" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -48,7 +49,7 @@ const ( // imageLabel is the label that is used for the docker image running the service. imageLabel model.LabelName = metaLabelPrefix + "image" // portIndexLabel is the integer port index when multiple ports are defined; - // e.g. PORT1 would have a value of '1' + // e.g. PORT1 would have a value of '1'. portIndexLabel model.LabelName = metaLabelPrefix + "port_index" // taskLabel contains the mesos task name of the app instance. taskLabel model.LabelName = metaLabelPrefix + "task" @@ -78,12 +79,19 @@ type SDConfig struct { HTTPClientConfig config.HTTPClientConfig `yaml:",inline"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &marathonMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "marathon" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(*c, opts.Logger) + return NewDiscovery(*c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -106,14 +114,16 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if len(c.AuthToken) > 0 && len(c.AuthTokenFile) > 0 { return errors.New("marathon_sd: at most one of auth_token & auth_token_file must be configured") } - if c.HTTPClientConfig.BasicAuth != nil && (len(c.AuthToken) > 0 || len(c.AuthTokenFile) > 0) { - return errors.New("marathon_sd: at most one of basic_auth, auth_token & auth_token_file must be configured") - } - if (len(c.HTTPClientConfig.BearerToken) > 0 || len(c.HTTPClientConfig.BearerTokenFile) > 0) && (len(c.AuthToken) > 0 || len(c.AuthTokenFile) > 0) { - return errors.New("marathon_sd: at most one of bearer_token, bearer_token_file, auth_token & auth_token_file must be configured") - } - if c.HTTPClientConfig.Authorization != nil && (len(c.AuthToken) > 0 || len(c.AuthTokenFile) > 0) { - return errors.New("marathon_sd: at most one of auth_token, auth_token_file & authorization must be configured") + + if len(c.AuthToken) > 0 || len(c.AuthTokenFile) > 0 { + switch { + case c.HTTPClientConfig.BasicAuth != nil: + return errors.New("marathon_sd: at most one of basic_auth, auth_token & auth_token_file must be configured") + case len(c.HTTPClientConfig.BearerToken) > 0 || len(c.HTTPClientConfig.BearerTokenFile) > 0: + return errors.New("marathon_sd: at most one of bearer_token, bearer_token_file, auth_token & auth_token_file must be configured") + case c.HTTPClientConfig.Authorization != nil: + return errors.New("marathon_sd: at most one of auth_token, auth_token_file & authorization must be configured") + } } return c.HTTPClientConfig.Validate() } @@ -130,7 +140,12 @@ type Discovery struct { } // NewDiscovery returns a new Marathon Discovery. -func NewDiscovery(conf SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*marathonMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + rt, err := config.NewRoundTripperFromConfig(conf.HTTPClientConfig, "marathon_sd") if err != nil { return nil, err @@ -152,10 +167,13 @@ func NewDiscovery(conf SDConfig, logger log.Logger) (*Discovery, error) { appsClient: fetchApps, } d.Discovery = refresh.NewDiscovery( - logger, - "marathon", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "marathon", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/marathon/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/marathon/metrics.go new file mode 100644 index 000000000..790c16747 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/marathon/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 marathon + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*marathonMetrics)(nil) + +type marathonMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *marathonMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *marathonMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/metrics.go new file mode 100644 index 000000000..a77b86d27 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/metrics.go @@ -0,0 +1,101 @@ +// Copyright 2016 The Prometheus 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 discovery + +import ( + "fmt" + + "github.com/prometheus/client_golang/prometheus" +) + +var ( + clientGoRequestMetrics = &clientGoRequestMetricAdapter{} + clientGoWorkloadMetrics = &clientGoWorkqueueMetricsProvider{} +) + +func init() { + clientGoRequestMetrics.RegisterWithK8sGoClient() + clientGoWorkloadMetrics.RegisterWithK8sGoClient() +} + +// Metrics to be used with a discovery manager. +type Metrics struct { + FailedConfigs prometheus.Gauge + DiscoveredTargets *prometheus.GaugeVec + ReceivedUpdates prometheus.Counter + DelayedUpdates prometheus.Counter + SentUpdates prometheus.Counter +} + +func NewManagerMetrics(registerer prometheus.Registerer, sdManagerName string) (*Metrics, error) { + m := &Metrics{} + + m.FailedConfigs = prometheus.NewGauge( + prometheus.GaugeOpts{ + Name: "prometheus_sd_failed_configs", + Help: "Current number of service discovery configurations that failed to load.", + ConstLabels: prometheus.Labels{"name": sdManagerName}, + }, + ) + + m.DiscoveredTargets = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "prometheus_sd_discovered_targets", + Help: "Current number of discovered targets.", + ConstLabels: prometheus.Labels{"name": sdManagerName}, + }, + []string{"config"}, + ) + + m.ReceivedUpdates = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_received_updates_total", + Help: "Total number of update events received from the SD providers.", + ConstLabels: prometheus.Labels{"name": sdManagerName}, + }, + ) + + m.DelayedUpdates = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_updates_delayed_total", + Help: "Total number of update events that couldn't be sent immediately.", + ConstLabels: prometheus.Labels{"name": sdManagerName}, + }, + ) + + m.SentUpdates = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_updates_total", + Help: "Total number of update events sent to the SD consumers.", + ConstLabels: prometheus.Labels{"name": sdManagerName}, + }, + ) + + metrics := []prometheus.Collector{ + m.FailedConfigs, + m.DiscoveredTargets, + m.ReceivedUpdates, + m.DelayedUpdates, + m.SentUpdates, + } + + for _, collector := range metrics { + err := registerer.Register(collector) + if err != nil { + return nil, fmt.Errorf("failed to register discovery manager metrics: %w", err) + } + } + + return m, nil +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/metrics_k8s_client.go b/vendor/github.com/prometheus/prometheus/discovery/metrics_k8s_client.go new file mode 100644 index 000000000..f16245684 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/metrics_k8s_client.go @@ -0,0 +1,198 @@ +// Copyright 2018 The Prometheus 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 discovery + +import ( + "context" + "fmt" + "net/url" + "time" + + "github.com/prometheus/client_golang/prometheus" + "k8s.io/client-go/tools/metrics" + "k8s.io/client-go/util/workqueue" +) + +// This file registers metrics used by the Kubernetes Go client (k8s.io/client-go). +// Unfortunately, k8s.io/client-go metrics are global. +// If we instantiate multiple k8s SD instances, their k8s/client-go metrics will overlap. +// To prevent us from displaying misleading metrics, we register k8s.io/client-go metrics +// outside of the Kubernetes SD. + +const ( + KubernetesMetricsNamespace = "prometheus_sd_kubernetes" + workqueueMetricsNamespace = KubernetesMetricsNamespace + "_workqueue" +) + +var ( + // Metrics for client-go's HTTP requests. + clientGoRequestResultMetricVec = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: KubernetesMetricsNamespace, + Name: "http_request_total", + Help: "Total number of HTTP requests to the Kubernetes API by status code.", + }, + []string{"status_code"}, + ) + clientGoRequestLatencyMetricVec = prometheus.NewSummaryVec( + prometheus.SummaryOpts{ + Namespace: KubernetesMetricsNamespace, + Name: "http_request_duration_seconds", + Help: "Summary of latencies for HTTP requests to the Kubernetes API by endpoint.", + Objectives: map[float64]float64{}, + }, + []string{"endpoint"}, + ) + + // Definition of metrics for client-go workflow metrics provider. + clientGoWorkqueueDepthMetricVec = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: workqueueMetricsNamespace, + Name: "depth", + Help: "Current depth of the work queue.", + }, + []string{"queue_name"}, + ) + clientGoWorkqueueAddsMetricVec = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: workqueueMetricsNamespace, + Name: "items_total", + Help: "Total number of items added to the work queue.", + }, + []string{"queue_name"}, + ) + clientGoWorkqueueLatencyMetricVec = prometheus.NewSummaryVec( + prometheus.SummaryOpts{ + Namespace: workqueueMetricsNamespace, + Name: "latency_seconds", + Help: "How long an item stays in the work queue.", + Objectives: map[float64]float64{}, + }, + []string{"queue_name"}, + ) + clientGoWorkqueueUnfinishedWorkSecondsMetricVec = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: workqueueMetricsNamespace, + Name: "unfinished_work_seconds", + Help: "How long an item has remained unfinished in the work queue.", + }, + []string{"queue_name"}, + ) + clientGoWorkqueueLongestRunningProcessorMetricVec = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: workqueueMetricsNamespace, + Name: "longest_running_processor_seconds", + Help: "Duration of the longest running processor in the work queue.", + }, + []string{"queue_name"}, + ) + clientGoWorkqueueWorkDurationMetricVec = prometheus.NewSummaryVec( + prometheus.SummaryOpts{ + Namespace: workqueueMetricsNamespace, + Name: "work_duration_seconds", + Help: "How long processing an item from the work queue takes.", + Objectives: map[float64]float64{}, + }, + []string{"queue_name"}, + ) +) + +// Definition of dummy metric used as a placeholder if we don't want to observe some data. +type noopMetric struct{} + +func (noopMetric) Inc() {} +func (noopMetric) Dec() {} +func (noopMetric) Observe(float64) {} +func (noopMetric) Set(float64) {} + +// Definition of client-go metrics adapters for HTTP requests observation. +type clientGoRequestMetricAdapter struct{} + +// Returns all of the Prometheus metrics derived from k8s.io/client-go. +// This may be used tu register and unregister the metrics. +func clientGoMetrics() []prometheus.Collector { + return []prometheus.Collector{ + clientGoRequestResultMetricVec, + clientGoRequestLatencyMetricVec, + clientGoWorkqueueDepthMetricVec, + clientGoWorkqueueAddsMetricVec, + clientGoWorkqueueLatencyMetricVec, + clientGoWorkqueueUnfinishedWorkSecondsMetricVec, + clientGoWorkqueueLongestRunningProcessorMetricVec, + clientGoWorkqueueWorkDurationMetricVec, + } +} + +func RegisterK8sClientMetricsWithPrometheus(registerer prometheus.Registerer) error { + for _, collector := range clientGoMetrics() { + err := registerer.Register(collector) + if err != nil { + return fmt.Errorf("failed to register Kubernetes Go Client metrics: %w", err) + } + } + return nil +} + +func (f *clientGoRequestMetricAdapter) RegisterWithK8sGoClient() { + metrics.Register( + metrics.RegisterOpts{ + RequestLatency: f, + RequestResult: f, + }, + ) +} + +func (clientGoRequestMetricAdapter) Increment(_ context.Context, code, _, _ string) { + clientGoRequestResultMetricVec.WithLabelValues(code).Inc() +} + +func (clientGoRequestMetricAdapter) Observe(_ context.Context, _ string, u url.URL, latency time.Duration) { + clientGoRequestLatencyMetricVec.WithLabelValues(u.EscapedPath()).Observe(latency.Seconds()) +} + +// Definition of client-go workqueue metrics provider definition. +type clientGoWorkqueueMetricsProvider struct{} + +func (f *clientGoWorkqueueMetricsProvider) RegisterWithK8sGoClient() { + workqueue.SetProvider(f) +} + +func (f *clientGoWorkqueueMetricsProvider) NewDepthMetric(name string) workqueue.GaugeMetric { + return clientGoWorkqueueDepthMetricVec.WithLabelValues(name) +} + +func (f *clientGoWorkqueueMetricsProvider) NewAddsMetric(name string) workqueue.CounterMetric { + return clientGoWorkqueueAddsMetricVec.WithLabelValues(name) +} + +func (f *clientGoWorkqueueMetricsProvider) NewLatencyMetric(name string) workqueue.HistogramMetric { + return clientGoWorkqueueLatencyMetricVec.WithLabelValues(name) +} + +func (f *clientGoWorkqueueMetricsProvider) NewWorkDurationMetric(name string) workqueue.HistogramMetric { + return clientGoWorkqueueWorkDurationMetricVec.WithLabelValues(name) +} + +func (f *clientGoWorkqueueMetricsProvider) NewUnfinishedWorkSecondsMetric(name string) workqueue.SettableGaugeMetric { + return clientGoWorkqueueUnfinishedWorkSecondsMetricVec.WithLabelValues(name) +} + +func (f *clientGoWorkqueueMetricsProvider) NewLongestRunningProcessorSecondsMetric(name string) workqueue.SettableGaugeMetric { + return clientGoWorkqueueLongestRunningProcessorMetricVec.WithLabelValues(name) +} + +func (clientGoWorkqueueMetricsProvider) NewRetriesMetric(string) workqueue.CounterMetric { + // Retries are not used so the metric is omitted. + return noopMetric{} +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/metrics_refresh.go b/vendor/github.com/prometheus/prometheus/discovery/metrics_refresh.go new file mode 100644 index 000000000..d621165ce --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/metrics_refresh.go @@ -0,0 +1,75 @@ +// Copyright 2015 The Prometheus 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 discovery + +import ( + "github.com/prometheus/client_golang/prometheus" +) + +// Metric vectors for the "refresh" package. +// We define them here in the "discovery" package in order to avoid a cyclic dependency between +// "discovery" and "refresh". +type RefreshMetricsVecs struct { + failuresVec *prometheus.CounterVec + durationVec *prometheus.SummaryVec + + metricRegisterer MetricRegisterer +} + +var _ RefreshMetricsManager = (*RefreshMetricsVecs)(nil) + +func NewRefreshMetrics(reg prometheus.Registerer) RefreshMetricsManager { + m := &RefreshMetricsVecs{ + failuresVec: prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "prometheus_sd_refresh_failures_total", + Help: "Number of refresh failures for the given SD mechanism.", + }, + []string{"mechanism"}), + durationVec: prometheus.NewSummaryVec( + prometheus.SummaryOpts{ + Name: "prometheus_sd_refresh_duration_seconds", + Help: "The duration of a refresh in seconds for the given SD mechanism.", + Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, + }, + []string{"mechanism"}), + } + + // The reason we register metric vectors instead of metrics is so that + // the metrics are not visible until they are recorded. + m.metricRegisterer = NewMetricRegisterer(reg, []prometheus.Collector{ + m.failuresVec, + m.durationVec, + }) + + return m +} + +// Instantiate returns metrics out of metric vectors. +func (m *RefreshMetricsVecs) Instantiate(mech string) *RefreshMetrics { + return &RefreshMetrics{ + Failures: m.failuresVec.WithLabelValues(mech), + Duration: m.durationVec.WithLabelValues(mech), + } +} + +// Register implements discovery.DiscovererMetrics. +func (m *RefreshMetricsVecs) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *RefreshMetricsVecs) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/moby/docker.go b/vendor/github.com/prometheus/prometheus/discovery/moby/docker.go index 162833ece..6a2b2d930 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/moby/docker.go +++ b/vendor/github.com/prometheus/prometheus/discovery/moby/docker.go @@ -22,10 +22,11 @@ import ( "strconv" "time" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -75,12 +76,19 @@ type DockerSDConfig struct { RefreshInterval model.Duration `yaml:"refresh_interval"` } +// NewDiscovererMetrics implements discovery.Config. +func (*DockerSDConfig) NewDiscovererMetrics(_ prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &dockerMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*DockerSDConfig) Name() string { return "docker" } // NewDiscoverer returns a Discoverer for the Config. func (c *DockerSDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDockerDiscovery(c, opts.Logger) + return NewDockerDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -114,8 +122,11 @@ type DockerDiscovery struct { } // NewDockerDiscovery returns a new DockerDiscovery which periodically refreshes its targets. -func NewDockerDiscovery(conf *DockerSDConfig, logger log.Logger) (*DockerDiscovery, error) { - var err error +func NewDockerDiscovery(conf *DockerSDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*DockerDiscovery, error) { + m, ok := metrics.(*dockerMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } d := &DockerDiscovery{ port: conf.Port, @@ -165,10 +176,13 @@ func NewDockerDiscovery(conf *DockerSDConfig, logger log.Logger) (*DockerDiscove } d.Discovery = refresh.NewDiscovery( - logger, - "docker", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "docker", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } @@ -178,7 +192,7 @@ func (d *DockerDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group, er Source: "Docker", } - containers, err := d.client.ContainerList(ctx, types.ContainerListOptions{Filters: d.filters}) + containers, err := d.client.ContainerList(ctx, container.ListOptions{Filters: d.filters}) if err != nil { return nil, fmt.Errorf("error while listing containers: %w", err) } diff --git a/vendor/github.com/prometheus/prometheus/discovery/moby/dockerswarm.go b/vendor/github.com/prometheus/prometheus/discovery/moby/dockerswarm.go index 371f9d5ed..b0147467d 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/moby/dockerswarm.go +++ b/vendor/github.com/prometheus/prometheus/discovery/moby/dockerswarm.go @@ -23,6 +23,7 @@ import ( "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" "github.com/prometheus/common/version" @@ -69,12 +70,19 @@ type Filter struct { Values []string `yaml:"values"` } +// NewDiscovererMetrics implements discovery.Config. +func (*DockerSwarmSDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &dockerswarmMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*DockerSwarmSDConfig) Name() string { return "dockerswarm" } // NewDiscoverer returns a Discoverer for the Config. func (c *DockerSwarmSDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -117,8 +125,11 @@ type Discovery struct { } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf *DockerSwarmSDConfig, logger log.Logger) (*Discovery, error) { - var err error +func NewDiscovery(conf *DockerSwarmSDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*dockerswarmMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } d := &Discovery{ port: conf.Port, @@ -168,10 +179,13 @@ func NewDiscovery(conf *DockerSwarmSDConfig, logger log.Logger) (*Discovery, err } d.Discovery = refresh.NewDiscovery( - logger, - "dockerswarm", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "dockerswarm", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/moby/metrics_docker.go b/vendor/github.com/prometheus/prometheus/discovery/moby/metrics_docker.go new file mode 100644 index 000000000..457d520a0 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/moby/metrics_docker.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 moby + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*dockerMetrics)(nil) + +type dockerMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *dockerMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *dockerMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/moby/metrics_dockerswarm.go b/vendor/github.com/prometheus/prometheus/discovery/moby/metrics_dockerswarm.go new file mode 100644 index 000000000..227ba6c2b --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/moby/metrics_dockerswarm.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 moby + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*dockerswarmMetrics)(nil) + +type dockerswarmMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *dockerswarmMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *dockerswarmMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/nomad/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/nomad/metrics.go new file mode 100644 index 000000000..9707153d9 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/nomad/metrics.go @@ -0,0 +1,57 @@ +// Copyright 2015 The Prometheus 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 nomad + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*nomadMetrics)(nil) + +type nomadMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator + + failuresCount prometheus.Counter + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &nomadMetrics{ + refreshMetrics: rmi, + failuresCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_sd_nomad_failures_total", + Help: "Number of nomad service discovery refresh failures.", + }), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.failuresCount, + }) + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *nomadMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *nomadMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/nomad/nomad.go b/vendor/github.com/prometheus/prometheus/discovery/nomad/nomad.go index 7013f0737..d9c48120a 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/nomad/nomad.go +++ b/vendor/github.com/prometheus/prometheus/discovery/nomad/nomad.go @@ -49,27 +49,18 @@ const ( ) // DefaultSDConfig is the default nomad SD configuration. -var ( - DefaultSDConfig = SDConfig{ - AllowStale: true, - HTTPClientConfig: config.DefaultHTTPClientConfig, - Namespace: "default", - RefreshInterval: model.Duration(60 * time.Second), - Region: "global", - Server: "http://localhost:4646", - TagSeparator: ",", - } - - failuresCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Name: "prometheus_sd_nomad_failures_total", - Help: "Number of nomad service discovery refresh failures.", - }) -) +var DefaultSDConfig = SDConfig{ + AllowStale: true, + HTTPClientConfig: config.DefaultHTTPClientConfig, + Namespace: "default", + RefreshInterval: model.Duration(60 * time.Second), + Region: "global", + Server: "http://localhost:4646", + TagSeparator: ",", +} func init() { discovery.RegisterConfig(&SDConfig{}) - prometheus.MustRegister(failuresCount) } // SDConfig is the configuration for nomad based service discovery. @@ -83,12 +74,17 @@ type SDConfig struct { TagSeparator string `yaml:"tag_separator,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "nomad" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -121,10 +117,16 @@ type Discovery struct { region string server string tagSeparator string + metrics *nomadMetrics } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*nomadMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + d := &Discovery{ allowStale: conf.AllowStale, namespace: conf.Namespace, @@ -132,6 +134,7 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { region: conf.Region, server: conf.Server, tagSeparator: conf.TagSeparator, + metrics: m, } HTTPClient, err := config.NewClientFromConfig(conf.HTTPClientConfig, "nomad_sd") @@ -153,10 +156,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { d.client = client d.Discovery = refresh.NewDiscovery( - logger, - "nomad", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "nomad", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } @@ -167,7 +173,7 @@ func (d *Discovery) refresh(context.Context) ([]*targetgroup.Group, error) { } stubs, _, err := d.client.Services().List(opts) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, err } @@ -179,7 +185,7 @@ func (d *Discovery) refresh(context.Context) ([]*targetgroup.Group, error) { for _, service := range stub.Services { instances, _, err := d.client.Services().Get(service.ServiceName, opts) if err != nil { - failuresCount.Inc() + d.metrics.failuresCount.Inc() return nil, fmt.Errorf("failed to fetch services: %w", err) } diff --git a/vendor/github.com/prometheus/prometheus/discovery/openstack/instance.go b/vendor/github.com/prometheus/prometheus/discovery/openstack/instance.go index 2f7e99a07..9b28c1d6e 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/openstack/instance.go +++ b/vendor/github.com/prometheus/prometheus/discovery/openstack/instance.go @@ -36,6 +36,7 @@ const ( openstackLabelAddressPool = openstackLabelPrefix + "address_pool" openstackLabelInstanceFlavor = openstackLabelPrefix + "instance_flavor" openstackLabelInstanceID = openstackLabelPrefix + "instance_id" + openstackLabelInstanceImage = openstackLabelPrefix + "instance_image" openstackLabelInstanceName = openstackLabelPrefix + "instance_name" openstackLabelInstanceStatus = openstackLabelPrefix + "instance_status" openstackLabelPrivateIP = openstackLabelPrefix + "private_ip" @@ -144,12 +145,18 @@ func (i *InstanceDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group, openstackLabelUserID: model.LabelValue(s.UserID), } - id, ok := s.Flavor["id"].(string) + flavorID, ok := s.Flavor["id"].(string) if !ok { level.Warn(i.logger).Log("msg", "Invalid type for flavor id, expected string") continue } - labels[openstackLabelInstanceFlavor] = model.LabelValue(id) + labels[openstackLabelInstanceFlavor] = model.LabelValue(flavorID) + + imageID, ok := s.Image["id"].(string) + if ok { + labels[openstackLabelInstanceImage] = model.LabelValue(imageID) + } + for k, v := range s.Metadata { name := strutil.SanitizeLabelName(k) labels[openstackLabelTagPrefix+model.LabelName(name)] = model.LabelValue(v) diff --git a/vendor/github.com/prometheus/prometheus/discovery/openstack/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/openstack/metrics.go new file mode 100644 index 000000000..a64c1a673 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/openstack/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 openstack + +import ( + "github.com/prometheus/prometheus/discovery" +) + +type openstackMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +var _ discovery.DiscovererMetrics = (*openstackMetrics)(nil) + +// Register implements discovery.DiscovererMetrics. +func (m *openstackMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *openstackMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/openstack/openstack.go b/vendor/github.com/prometheus/prometheus/discovery/openstack/openstack.go index 92c83a4cf..c98f78788 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/openstack/openstack.go +++ b/vendor/github.com/prometheus/prometheus/discovery/openstack/openstack.go @@ -24,6 +24,7 @@ import ( "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack" "github.com/mwitkow/go-conntrack" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -65,12 +66,19 @@ type SDConfig struct { Availability string `yaml:"availability,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &openstackMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "openstack" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -134,16 +142,24 @@ type refresher interface { } // NewDiscovery returns a new OpenStack Discoverer which periodically refreshes its targets. -func NewDiscovery(conf *SDConfig, l log.Logger) (*refresh.Discovery, error) { +func NewDiscovery(conf *SDConfig, l log.Logger, metrics discovery.DiscovererMetrics) (*refresh.Discovery, error) { + m, ok := metrics.(*openstackMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + r, err := newRefresher(conf, l) if err != nil { return nil, err } return refresh.NewDiscovery( - l, - "openstack", - time.Duration(conf.RefreshInterval), - r.refresh, + refresh.Options{ + Logger: l, + Mech: "openstack", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: r.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ), nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/ovhcloud/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/ovhcloud/metrics.go new file mode 100644 index 000000000..1c5170946 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/ovhcloud/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 ovhcloud + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*ovhcloudMetrics)(nil) + +type ovhcloudMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *ovhcloudMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *ovhcloudMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/ovhcloud/ovhcloud.go b/vendor/github.com/prometheus/prometheus/discovery/ovhcloud/ovhcloud.go index 535ade4df..988b4482f 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/ovhcloud/ovhcloud.go +++ b/vendor/github.com/prometheus/prometheus/discovery/ovhcloud/ovhcloud.go @@ -22,6 +22,7 @@ import ( "github.com/go-kit/log" "github.com/ovh/go-ovh/ovh" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -52,6 +53,13 @@ type SDConfig struct { Service string `yaml:"service"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &ovhcloudMetrics{ + refreshMetrics: rmi, + } +} + // Name implements the Discoverer interface. func (c SDConfig) Name() string { return "ovhcloud" @@ -93,7 +101,7 @@ func createClient(config *SDConfig) (*ovh.Client, error) { // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(options discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, options.Logger) + return NewDiscovery(c, options.Logger, options.Metrics) } func init() { @@ -140,16 +148,24 @@ func newRefresher(conf *SDConfig, logger log.Logger) (refresher, error) { } // NewDiscovery returns a new OVHcloud Discoverer which periodically refreshes its targets. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*refresh.Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*refresh.Discovery, error) { + m, ok := metrics.(*ovhcloudMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + r, err := newRefresher(conf, logger) if err != nil { return nil, err } return refresh.NewDiscovery( - logger, - "ovhcloud", - time.Duration(conf.RefreshInterval), - r.refresh, + refresh.Options{ + Logger: logger, + Mech: "ovhcloud", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: r.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ), nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/puppetdb/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/puppetdb/metrics.go new file mode 100644 index 000000000..2f5faa57c --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/puppetdb/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 puppetdb + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*puppetdbMetrics)(nil) + +type puppetdbMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *puppetdbMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *puppetdbMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/puppetdb/puppetdb.go b/vendor/github.com/prometheus/prometheus/discovery/puppetdb/puppetdb.go index f22a2e22b..3f9ad1f11 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/puppetdb/puppetdb.go +++ b/vendor/github.com/prometheus/prometheus/discovery/puppetdb/puppetdb.go @@ -29,6 +29,7 @@ import ( "github.com/go-kit/log" "github.com/grafana/regexp" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" "github.com/prometheus/common/version" @@ -78,12 +79,19 @@ type SDConfig struct { Port int `yaml:"port"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &puppetdbMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "puppetdb" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -115,7 +123,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if c.Query == "" { return fmt.Errorf("query missing") } - return nil + return c.HTTPClientConfig.Validate() } // Discovery provides service discovery functionality based @@ -130,7 +138,12 @@ type Discovery struct { } // NewDiscovery returns a new PuppetDB discovery for the given config. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*puppetdbMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + if logger == nil { logger = log.NewNopLogger() } @@ -156,10 +169,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { } d.Discovery = refresh.NewDiscovery( - logger, - "http", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "puppetdb", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/refresh/refresh.go b/vendor/github.com/prometheus/prometheus/discovery/refresh/refresh.go index 919567a53..f037a90cf 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/refresh/refresh.go +++ b/vendor/github.com/prometheus/prometheus/discovery/refresh/refresh.go @@ -20,31 +20,17 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" - "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/discovery" "github.com/prometheus/prometheus/discovery/targetgroup" ) -var ( - failuresCount = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "prometheus_sd_refresh_failures_total", - Help: "Number of refresh failures for the given SD mechanism.", - }, - []string{"mechanism"}, - ) - duration = prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "prometheus_sd_refresh_duration_seconds", - Help: "The duration of a refresh in seconds for the given SD mechanism.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - []string{"mechanism"}, - ) -) - -func init() { - prometheus.MustRegister(duration, failuresCount) +type Options struct { + Logger log.Logger + Mech string + Interval time.Duration + RefreshF func(ctx context.Context) ([]*targetgroup.Group, error) + MetricsInstantiator discovery.RefreshMetricsInstantiator } // Discovery implements the Discoverer interface. @@ -52,23 +38,28 @@ type Discovery struct { logger log.Logger interval time.Duration refreshf func(ctx context.Context) ([]*targetgroup.Group, error) - - failures prometheus.Counter - duration prometheus.Observer + metrics *discovery.RefreshMetrics } // NewDiscovery returns a Discoverer function that calls a refresh() function at every interval. -func NewDiscovery(l log.Logger, mech string, interval time.Duration, refreshf func(ctx context.Context) ([]*targetgroup.Group, error)) *Discovery { - if l == nil { - l = log.NewNopLogger() +func NewDiscovery(opts Options) *Discovery { + m := opts.MetricsInstantiator.Instantiate(opts.Mech) + + var logger log.Logger + if opts.Logger == nil { + logger = log.NewNopLogger() + } else { + logger = opts.Logger } - return &Discovery{ - logger: l, - interval: interval, - refreshf: refreshf, - failures: failuresCount.WithLabelValues(mech), - duration: duration.WithLabelValues(mech), + + d := Discovery{ + logger: logger, + interval: opts.Interval, + refreshf: opts.RefreshF, + metrics: m, } + + return &d } // Run implements the Discoverer interface. @@ -115,12 +106,12 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { now := time.Now() defer func() { - d.duration.Observe(time.Since(now).Seconds()) + d.metrics.Duration.Observe(time.Since(now).Seconds()) }() tgs, err := d.refreshf(ctx) if err != nil { - d.failures.Inc() + d.metrics.Failures.Inc() } return tgs, err } diff --git a/vendor/github.com/prometheus/prometheus/discovery/registry.go b/vendor/github.com/prometheus/prometheus/discovery/registry.go index 13168a07a..1f491d4ca 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/registry.go +++ b/vendor/github.com/prometheus/prometheus/discovery/registry.go @@ -24,6 +24,8 @@ import ( "gopkg.in/yaml.v2" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/discovery/targetgroup" ) @@ -258,3 +260,24 @@ func replaceYAMLTypeError(err error, oldTyp, newTyp reflect.Type) error { } return err } + +// RegisterSDMetrics registers the metrics used by service discovery mechanisms. +// RegisterSDMetrics should be called only once during the lifetime of the Prometheus process. +// There is no need for the Prometheus process to unregister the metrics. +func RegisterSDMetrics(registerer prometheus.Registerer, rmm RefreshMetricsManager) (map[string]DiscovererMetrics, error) { + err := rmm.Register() + if err != nil { + return nil, fmt.Errorf("failed to create service discovery refresh metrics") + } + + metrics := make(map[string]DiscovererMetrics) + for _, conf := range configNames { + currentSdMetrics := conf.NewDiscovererMetrics(registerer, rmm) + err = currentSdMetrics.Register() + if err != nil { + return nil, fmt.Errorf("failed to create service discovery metrics") + } + metrics[conf.Name()] = currentSdMetrics + } + return metrics, nil +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/scaleway/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/scaleway/metrics.go new file mode 100644 index 000000000..a8277d0fb --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/scaleway/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 scaleway + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*scalewayMetrics)(nil) + +type scalewayMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *scalewayMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *scalewayMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/scaleway/scaleway.go b/vendor/github.com/prometheus/prometheus/discovery/scaleway/scaleway.go index 90091b317..f8e1a83f5 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/scaleway/scaleway.go +++ b/vendor/github.com/prometheus/prometheus/discovery/scaleway/scaleway.go @@ -23,6 +23,7 @@ import ( "time" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" "github.com/scaleway/scaleway-sdk-go/scw" @@ -103,6 +104,13 @@ type SDConfig struct { Role role `yaml:"role"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &scalewayMetrics{ + refreshMetrics: rmi, + } +} + func (c SDConfig) Name() string { return "scaleway" } @@ -160,7 +168,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { } func (c SDConfig) NewDiscoverer(options discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(&c, options.Logger) + return NewDiscovery(&c, options.Logger, options.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -177,17 +185,25 @@ func init() { // the Discoverer interface. type Discovery struct{} -func NewDiscovery(conf *SDConfig, logger log.Logger) (*refresh.Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*refresh.Discovery, error) { + m, ok := metrics.(*scalewayMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + r, err := newRefresher(conf) if err != nil { return nil, err } return refresh.NewDiscovery( - logger, - "scaleway", - time.Duration(conf.RefreshInterval), - r.refresh, + refresh.Options{ + Logger: logger, + Mech: "scaleway", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: r.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ), nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/triton/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/triton/metrics.go new file mode 100644 index 000000000..3e34a840a --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/triton/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 triton + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*tritonMetrics)(nil) + +type tritonMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *tritonMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *tritonMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/triton/triton.go b/vendor/github.com/prometheus/prometheus/discovery/triton/triton.go index c83f3b34a..e56b7951b 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/triton/triton.go +++ b/vendor/github.com/prometheus/prometheus/discovery/triton/triton.go @@ -26,6 +26,7 @@ import ( "github.com/go-kit/log" "github.com/mwitkow/go-conntrack" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -69,12 +70,19 @@ type SDConfig struct { Version int `yaml:"version"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &tritonMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "triton" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return New(opts.Logger, c) + return New(opts.Logger, c, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -138,7 +146,12 @@ type Discovery struct { } // New returns a new Discovery which periodically refreshes its targets. -func New(logger log.Logger, conf *SDConfig) (*Discovery, error) { +func New(logger log.Logger, conf *SDConfig, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*tritonMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + tls, err := config.NewTLSConfig(&conf.TLSConfig) if err != nil { return nil, err @@ -159,10 +172,13 @@ func New(logger log.Logger, conf *SDConfig) (*Discovery, error) { sdConfig: conf, } d.Discovery = refresh.NewDiscovery( - logger, - "triton", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "triton", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/util.go b/vendor/github.com/prometheus/prometheus/discovery/util.go new file mode 100644 index 000000000..83cc640dd --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/util.go @@ -0,0 +1,72 @@ +// Copyright 2020 The Prometheus 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 discovery + +import ( + "fmt" + + "github.com/prometheus/client_golang/prometheus" +) + +// A utility to be used by implementations of discovery.Discoverer +// which need to manage the lifetime of their metrics. +type MetricRegisterer interface { + RegisterMetrics() error + UnregisterMetrics() +} + +// metricRegistererImpl is an implementation of MetricRegisterer. +type metricRegistererImpl struct { + reg prometheus.Registerer + metrics []prometheus.Collector +} + +var _ MetricRegisterer = &metricRegistererImpl{} + +// Creates an instance of a MetricRegisterer. +// Typically called inside the implementation of the NewDiscoverer() method. +func NewMetricRegisterer(reg prometheus.Registerer, metrics []prometheus.Collector) MetricRegisterer { + return &metricRegistererImpl{ + reg: reg, + metrics: metrics, + } +} + +// RegisterMetrics registers the metrics with a Prometheus registerer. +// If any metric fails to register, it will unregister all metrics that +// were registered so far, and return an error. +// Typically called at the start of the SD's Run() method. +func (rh *metricRegistererImpl) RegisterMetrics() error { + for _, collector := range rh.metrics { + err := rh.reg.Register(collector) + if err != nil { + // Unregister all metrics that were registered so far. + // This is so that if RegisterMetrics() gets called again, + // there will not be an error due to a duplicate registration. + rh.UnregisterMetrics() + + return fmt.Errorf("failed to register metric: %w", err) + } + } + return nil +} + +// UnregisterMetrics unregisters the metrics from the same Prometheus +// registerer which was used to register them. +// Typically called at the end of the SD's Run() method by a defer statement. +func (rh *metricRegistererImpl) UnregisterMetrics() { + for _, collector := range rh.metrics { + rh.reg.Unregister(collector) + } +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/uyuni/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/uyuni/metrics.go new file mode 100644 index 000000000..6793b5920 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/uyuni/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 uyuni + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*uyuniMetrics)(nil) + +type uyuniMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *uyuniMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *uyuniMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/uyuni/uyuni.go b/vendor/github.com/prometheus/prometheus/discovery/uyuni/uyuni.go index e37acbf98..e885ef2e8 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/uyuni/uyuni.go +++ b/vendor/github.com/prometheus/prometheus/discovery/uyuni/uyuni.go @@ -25,6 +25,7 @@ import ( "github.com/go-kit/log" "github.com/kolo/xmlrpc" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -110,12 +111,19 @@ type Discovery struct { logger log.Logger } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &uyuniMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "uyuni" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -146,7 +154,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if c.Password == "" { return errors.New("Uyuni SD configuration requires a password") } - return nil + return c.HTTPClientConfig.Validate() } func login(rpcclient *xmlrpc.Client, user, pass string, duration int) (string, error) { @@ -203,7 +211,12 @@ func getEndpointInfoForSystems( } // NewDiscovery returns a uyuni discovery for the given configuration. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*uyuniMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + apiURL, err := url.Parse(conf.Server) if err != nil { return nil, err @@ -227,10 +240,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { } d.Discovery = refresh.NewDiscovery( - logger, - "uyuni", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "uyuni", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/vultr/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/vultr/metrics.go new file mode 100644 index 000000000..193436aad --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/vultr/metrics.go @@ -0,0 +1,32 @@ +// Copyright 2015 The Prometheus 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 vultr + +import ( + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*vultrMetrics)(nil) + +type vultrMetrics struct { + refreshMetrics discovery.RefreshMetricsInstantiator +} + +// Register implements discovery.DiscovererMetrics. +func (m *vultrMetrics) Register() error { + return nil +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *vultrMetrics) Unregister() {} diff --git a/vendor/github.com/prometheus/prometheus/discovery/vultr/vultr.go b/vendor/github.com/prometheus/prometheus/discovery/vultr/vultr.go index 42881d3c1..aaa9c64e4 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/vultr/vultr.go +++ b/vendor/github.com/prometheus/prometheus/discovery/vultr/vultr.go @@ -23,6 +23,7 @@ import ( "time" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" "github.com/prometheus/common/version" @@ -73,12 +74,19 @@ type SDConfig struct { Port int `yaml:"port"` } +// NewDiscovererMetrics implements discovery.Config. +func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &vultrMetrics{ + refreshMetrics: rmi, + } +} + // Name returns the name of the Config. func (*SDConfig) Name() string { return "vultr" } // NewDiscoverer returns a Discoverer for the Config. func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) { - return NewDiscovery(c, opts.Logger) + return NewDiscovery(c, opts.Logger, opts.Metrics) } // SetDirectory joins any relative file paths with dir. @@ -106,7 +114,12 @@ type Discovery struct { } // NewDiscovery returns a new Discovery which periodically refreshes its targets. -func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { +func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*Discovery, error) { + m, ok := metrics.(*vultrMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + d := &Discovery{ port: conf.Port, } @@ -128,10 +141,13 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { } d.Discovery = refresh.NewDiscovery( - logger, - "vultr", - time.Duration(conf.RefreshInterval), - d.refresh, + refresh.Options{ + Logger: logger, + Mech: "vultr", + Interval: time.Duration(conf.RefreshInterval), + RefreshF: d.refresh, + MetricsInstantiator: m.refreshMetrics, + }, ) return d, nil } diff --git a/vendor/github.com/prometheus/prometheus/discovery/xds/kuma.go b/vendor/github.com/prometheus/prometheus/discovery/xds/kuma.go index bc88ba554..d1d540aaf 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/xds/kuma.go +++ b/vendor/github.com/prometheus/prometheus/discovery/xds/kuma.go @@ -30,35 +30,12 @@ import ( "github.com/prometheus/prometheus/util/strutil" ) -var ( - // DefaultKumaSDConfig is the default Kuma MADS SD configuration. - DefaultKumaSDConfig = KumaSDConfig{ - HTTPClientConfig: config.DefaultHTTPClientConfig, - RefreshInterval: model.Duration(15 * time.Second), - FetchTimeout: model.Duration(2 * time.Minute), - } - - kumaFetchFailuresCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Namespace: namespace, - Name: "sd_kuma_fetch_failures_total", - Help: "The number of Kuma MADS fetch call failures.", - }) - kumaFetchSkipUpdateCount = prometheus.NewCounter( - prometheus.CounterOpts{ - Namespace: namespace, - Name: "sd_kuma_fetch_skipped_updates_total", - Help: "The number of Kuma MADS fetch calls that result in no updates to the targets.", - }) - kumaFetchDuration = prometheus.NewSummary( - prometheus.SummaryOpts{ - Namespace: namespace, - Name: "sd_kuma_fetch_duration_seconds", - Help: "The duration of a Kuma MADS fetch call.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - ) -) +// DefaultKumaSDConfig is the default Kuma MADS SD configuration. +var DefaultKumaSDConfig = KumaSDConfig{ + HTTPClientConfig: config.DefaultHTTPClientConfig, + RefreshInterval: model.Duration(15 * time.Second), + FetchTimeout: model.Duration(2 * time.Minute), +} const ( // kumaMetaLabelPrefix is the meta prefix used for all kuma meta labels. @@ -81,6 +58,11 @@ const ( type KumaSDConfig = SDConfig +// NewDiscovererMetrics implements discovery.Config. +func (*KumaSDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return newDiscovererMetrics(reg, rmi) +} + // UnmarshalYAML implements the yaml.Unmarshaler interface. func (c *KumaSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { *c = DefaultKumaSDConfig @@ -120,7 +102,7 @@ func (c *KumaSDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discover logger = log.NewNopLogger() } - return NewKumaHTTPDiscovery(c, logger) + return NewKumaHTTPDiscovery(c, logger, opts.Metrics) } func convertKumaV1MonitoringAssignment(assignment *MonitoringAssignment) []model.LabelSet { @@ -176,12 +158,21 @@ func kumaMadsV1ResourceParser(resources []*anypb.Any, typeURL string) ([]model.L return targets, nil } -func NewKumaHTTPDiscovery(conf *KumaSDConfig, logger log.Logger) (discovery.Discoverer, error) { +func NewKumaHTTPDiscovery(conf *KumaSDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (discovery.Discoverer, error) { + m, ok := metrics.(*xdsMetrics) + if !ok { + return nil, fmt.Errorf("invalid discovery metrics type") + } + // Default to "prometheus" if hostname is unavailable. - clientID, err := osutil.GetFQDN() - if err != nil { - level.Debug(logger).Log("msg", "error getting FQDN", "err", err) - clientID = "prometheus" + clientID := conf.ClientID + if clientID == "" { + var err error + clientID, err = osutil.GetFQDN() + if err != nil { + level.Debug(logger).Log("msg", "error getting FQDN", "err", err) + clientID = "prometheus" + } } clientConfig := &HTTPResourceClientConfig{ @@ -203,14 +194,12 @@ func NewKumaHTTPDiscovery(conf *KumaSDConfig, logger log.Logger) (discovery.Disc } d := &fetchDiscovery{ - client: client, - logger: logger, - refreshInterval: time.Duration(conf.RefreshInterval), - source: "kuma", - parseResources: kumaMadsV1ResourceParser, - fetchFailuresCount: kumaFetchFailuresCount, - fetchSkipUpdateCount: kumaFetchSkipUpdateCount, - fetchDuration: kumaFetchDuration, + client: client, + logger: logger, + refreshInterval: time.Duration(conf.RefreshInterval), + source: "kuma", + parseResources: kumaMadsV1ResourceParser, + metrics: m, } return d, nil diff --git a/vendor/github.com/prometheus/prometheus/discovery/xds/metrics.go b/vendor/github.com/prometheus/prometheus/discovery/xds/metrics.go new file mode 100644 index 000000000..597d51656 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/discovery/xds/metrics.go @@ -0,0 +1,73 @@ +// Copyright 2015 The Prometheus 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 xds + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/discovery" +) + +var _ discovery.DiscovererMetrics = (*xdsMetrics)(nil) + +type xdsMetrics struct { + fetchDuration prometheus.Summary + fetchSkipUpdateCount prometheus.Counter + fetchFailuresCount prometheus.Counter + + metricRegisterer discovery.MetricRegisterer +} + +func newDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + m := &xdsMetrics{ + fetchFailuresCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Namespace: namespace, + Name: "sd_kuma_fetch_failures_total", + Help: "The number of Kuma MADS fetch call failures.", + }), + fetchSkipUpdateCount: prometheus.NewCounter( + prometheus.CounterOpts{ + Namespace: namespace, + Name: "sd_kuma_fetch_skipped_updates_total", + Help: "The number of Kuma MADS fetch calls that result in no updates to the targets.", + }), + fetchDuration: prometheus.NewSummary( + prometheus.SummaryOpts{ + Namespace: namespace, + Name: "sd_kuma_fetch_duration_seconds", + Help: "The duration of a Kuma MADS fetch call.", + Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, + }, + ), + } + + m.metricRegisterer = discovery.NewMetricRegisterer(reg, []prometheus.Collector{ + m.fetchFailuresCount, + m.fetchSkipUpdateCount, + m.fetchDuration, + }) + + return m +} + +// Register implements discovery.DiscovererMetrics. +func (m *xdsMetrics) Register() error { + return m.metricRegisterer.RegisterMetrics() +} + +// Unregister implements discovery.DiscovererMetrics. +func (m *xdsMetrics) Unregister() { + m.metricRegisterer.UnregisterMetrics() +} diff --git a/vendor/github.com/prometheus/prometheus/discovery/xds/xds.go b/vendor/github.com/prometheus/prometheus/discovery/xds/xds.go index 48bdbab02..8191d6be1 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/xds/xds.go +++ b/vendor/github.com/prometheus/prometheus/discovery/xds/xds.go @@ -20,7 +20,6 @@ import ( v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" "github.com/go-kit/log" "github.com/go-kit/log/level" - "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/config" "github.com/prometheus/common/model" "google.golang.org/protobuf/encoding/protojson" @@ -55,6 +54,7 @@ type SDConfig struct { RefreshInterval model.Duration `yaml:"refresh_interval,omitempty"` FetchTimeout model.Duration `yaml:"fetch_timeout,omitempty"` Server string `yaml:"server,omitempty"` + ClientID string `yaml:"client_id,omitempty"` } // mustRegisterMessage registers the provided message type in the typeRegistry, and panics @@ -69,9 +69,6 @@ func init() { // Register top-level SD Configs. discovery.RegisterConfig(&KumaSDConfig{}) - // Register metrics. - prometheus.MustRegister(kumaFetchDuration, kumaFetchSkipUpdateCount, kumaFetchFailuresCount) - // Register protobuf types that need to be marshalled/ unmarshalled. mustRegisterMessage(protoTypes, (&v3.DiscoveryRequest{}).ProtoReflect().Type()) mustRegisterMessage(protoTypes, (&v3.DiscoveryResponse{}).ProtoReflect().Type()) @@ -109,9 +106,7 @@ type fetchDiscovery struct { parseResources resourceParser logger log.Logger - fetchDuration prometheus.Observer - fetchSkipUpdateCount prometheus.Counter - fetchFailuresCount prometheus.Counter + metrics *xdsMetrics } func (d *fetchDiscovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { @@ -135,7 +130,7 @@ func (d *fetchDiscovery) poll(ctx context.Context, ch chan<- []*targetgroup.Grou t0 := time.Now() response, err := d.client.Fetch(ctx) elapsed := time.Since(t0) - d.fetchDuration.Observe(elapsed.Seconds()) + d.metrics.fetchDuration.Observe(elapsed.Seconds()) // Check the context before in order to exit early. select { @@ -146,20 +141,20 @@ func (d *fetchDiscovery) poll(ctx context.Context, ch chan<- []*targetgroup.Grou if err != nil { level.Error(d.logger).Log("msg", "error parsing resources", "err", err) - d.fetchFailuresCount.Inc() + d.metrics.fetchFailuresCount.Inc() return } if response == nil { // No update needed. - d.fetchSkipUpdateCount.Inc() + d.metrics.fetchSkipUpdateCount.Inc() return } parsedTargets, err := d.parseResources(response.Resources, response.TypeUrl) if err != nil { level.Error(d.logger).Log("msg", "error parsing resources", "err", err) - d.fetchFailuresCount.Inc() + d.metrics.fetchFailuresCount.Inc() return } diff --git a/vendor/github.com/prometheus/prometheus/discovery/zookeeper/zookeeper.go b/vendor/github.com/prometheus/prometheus/discovery/zookeeper/zookeeper.go index cadff5fd2..7d8761527 100644 --- a/vendor/github.com/prometheus/prometheus/discovery/zookeeper/zookeeper.go +++ b/vendor/github.com/prometheus/prometheus/discovery/zookeeper/zookeeper.go @@ -25,6 +25,7 @@ import ( "github.com/go-kit/log" "github.com/go-zookeeper/zk" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/discovery" @@ -56,6 +57,11 @@ type ServersetSDConfig struct { Timeout model.Duration `yaml:"timeout,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*ServersetSDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &discovery.NoopDiscovererMetrics{} +} + // Name returns the name of the Config. func (*ServersetSDConfig) Name() string { return "serverset" } @@ -93,6 +99,11 @@ type NerveSDConfig struct { Timeout model.Duration `yaml:"timeout,omitempty"` } +// NewDiscovererMetrics implements discovery.Config. +func (*NerveSDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics { + return &discovery.NoopDiscovererMetrics{} +} + // Name returns the name of the Config. func (*NerveSDConfig) Name() string { return "nerve" } @@ -193,7 +204,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { } for _, pathUpdate := range d.pathUpdates { // Drain event channel in case the treecache leaks goroutines otherwise. - for range pathUpdate { // nolint:revive + for range pathUpdate { } } d.conn.Close() diff --git a/vendor/github.com/prometheus/prometheus/model/exemplar/exemplar.go b/vendor/github.com/prometheus/prometheus/model/exemplar/exemplar.go index 2e39cf689..08f55374e 100644 --- a/vendor/github.com/prometheus/prometheus/model/exemplar/exemplar.go +++ b/vendor/github.com/prometheus/prometheus/model/exemplar/exemplar.go @@ -48,3 +48,18 @@ func (e Exemplar) Equals(e2 Exemplar) bool { return e.Value == e2.Value } + +// Sort first by timestamp, then value, then labels. +func Compare(a, b Exemplar) int { + if a.Ts < b.Ts { + return -1 + } else if a.Ts > b.Ts { + return 1 + } + if a.Value < b.Value { + return -1 + } else if a.Value > b.Value { + return 1 + } + return labels.Compare(a.Labels, b.Labels) +} diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go b/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go index f95f0051c..19a92b3d5 100644 --- a/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go +++ b/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go @@ -15,6 +15,7 @@ package histogram import ( "fmt" + "math" "strings" ) @@ -52,21 +53,28 @@ type FloatHistogram struct { // Copy returns a deep copy of the Histogram. func (h *FloatHistogram) Copy() *FloatHistogram { - c := *h + c := FloatHistogram{ + CounterResetHint: h.CounterResetHint, + Schema: h.Schema, + ZeroThreshold: h.ZeroThreshold, + ZeroCount: h.ZeroCount, + Count: h.Count, + Sum: h.Sum, + } - if h.PositiveSpans != nil { + if len(h.PositiveSpans) != 0 { c.PositiveSpans = make([]Span, len(h.PositiveSpans)) copy(c.PositiveSpans, h.PositiveSpans) } - if h.NegativeSpans != nil { + if len(h.NegativeSpans) != 0 { c.NegativeSpans = make([]Span, len(h.NegativeSpans)) copy(c.NegativeSpans, h.NegativeSpans) } - if h.PositiveBuckets != nil { + if len(h.PositiveBuckets) != 0 { c.PositiveBuckets = make([]float64, len(h.PositiveBuckets)) copy(c.PositiveBuckets, h.PositiveBuckets) } - if h.NegativeBuckets != nil { + if len(h.NegativeBuckets) != 0 { c.NegativeBuckets = make([]float64, len(h.NegativeBuckets)) copy(c.NegativeBuckets, h.NegativeBuckets) } @@ -74,6 +82,29 @@ func (h *FloatHistogram) Copy() *FloatHistogram { return &c } +// CopyTo makes a deep copy into the given FloatHistogram. +// The destination object has to be a non-nil pointer. +func (h *FloatHistogram) CopyTo(to *FloatHistogram) { + to.CounterResetHint = h.CounterResetHint + to.Schema = h.Schema + to.ZeroThreshold = h.ZeroThreshold + to.ZeroCount = h.ZeroCount + to.Count = h.Count + to.Sum = h.Sum + + to.PositiveSpans = resize(to.PositiveSpans, len(h.PositiveSpans)) + copy(to.PositiveSpans, h.PositiveSpans) + + to.NegativeSpans = resize(to.NegativeSpans, len(h.NegativeSpans)) + copy(to.NegativeSpans, h.NegativeSpans) + + to.PositiveBuckets = resize(to.PositiveBuckets, len(h.PositiveBuckets)) + copy(to.PositiveBuckets, h.PositiveBuckets) + + to.NegativeBuckets = resize(to.NegativeBuckets, len(h.NegativeBuckets)) + copy(to.NegativeBuckets, h.NegativeBuckets) +} + // CopyToSchema works like Copy, but the returned deep copy has the provided // target schema, which must be ≤ the original schema (i.e. it must have a lower // resolution). @@ -93,26 +124,8 @@ func (h *FloatHistogram) CopyToSchema(targetSchema int32) *FloatHistogram { Sum: h.Sum, } - // TODO(beorn7): This is a straight-forward implementation using merging - // iterators for the original buckets and then adding one merged bucket - // after another to the newly created FloatHistogram. It's well possible - // that a more involved implementation performs much better, which we - // could do if this code path turns out to be performance-critical. - var iInSpan, index int32 - for iSpan, iBucket, it := -1, -1, h.floatBucketIterator(true, 0, targetSchema); it.Next(); { - b := it.At() - c.PositiveSpans, c.PositiveBuckets, iSpan, iBucket, iInSpan = addBucket( - b, c.PositiveSpans, c.PositiveBuckets, iSpan, iBucket, iInSpan, index, - ) - index = b.Index - } - for iSpan, iBucket, it := -1, -1, h.floatBucketIterator(false, 0, targetSchema); it.Next(); { - b := it.At() - c.NegativeSpans, c.NegativeBuckets, iSpan, iBucket, iInSpan = addBucket( - b, c.NegativeSpans, c.NegativeBuckets, iSpan, iBucket, iInSpan, index, - ) - index = b.Index - } + c.PositiveSpans, c.PositiveBuckets = reduceResolution(h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, false, false) + c.NegativeSpans, c.NegativeBuckets = reduceResolution(h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, false, false) return &c } @@ -148,6 +161,55 @@ func (h *FloatHistogram) String() string { return sb.String() } +// TestExpression returns the string representation of this histogram as it is used in the internal PromQL testing +// framework as well as in promtool rules unit tests. +// The syntax is described in https://prometheus.io/docs/prometheus/latest/configuration/unit_testing_rules/#series +func (h *FloatHistogram) TestExpression() string { + var res []string + m := h.Copy() + + m.Compact(math.MaxInt) // Compact to reduce the number of positive and negative spans to 1. + + if m.Schema != 0 { + res = append(res, fmt.Sprintf("schema:%d", m.Schema)) + } + if m.Count != 0 { + res = append(res, fmt.Sprintf("count:%g", m.Count)) + } + if m.Sum != 0 { + res = append(res, fmt.Sprintf("sum:%g", m.Sum)) + } + if m.ZeroCount != 0 { + res = append(res, fmt.Sprintf("z_bucket:%g", m.ZeroCount)) + } + if m.ZeroThreshold != 0 { + res = append(res, fmt.Sprintf("z_bucket_w:%g", m.ZeroThreshold)) + } + + addBuckets := func(kind, bucketsKey, offsetKey string, buckets []float64, spans []Span) []string { + if len(spans) > 1 { + panic(fmt.Sprintf("histogram with multiple %s spans not supported", kind)) + } + for _, span := range spans { + if span.Offset != 0 { + res = append(res, fmt.Sprintf("%s:%d", offsetKey, span.Offset)) + } + } + + var bucketStr []string + for _, bucket := range buckets { + bucketStr = append(bucketStr, fmt.Sprintf("%g", bucket)) + } + if len(bucketStr) > 0 { + res = append(res, fmt.Sprintf("%s:[%s]", bucketsKey, strings.Join(bucketStr, " "))) + } + return res + } + res = addBuckets("positive", "buckets", "offset", m.PositiveBuckets, m.PositiveSpans) + res = addBuckets("negative", "n_buckets", "n_offset", m.NegativeBuckets, m.NegativeSpans) + return "{{" + strings.Join(res, " ") + "}}" +} + // ZeroBucket returns the zero bucket. func (h *FloatHistogram) ZeroBucket() Bucket[float64] { return Bucket[float64]{ @@ -159,12 +221,12 @@ func (h *FloatHistogram) ZeroBucket() Bucket[float64] { } } -// Scale scales the FloatHistogram by the provided factor, i.e. it scales all +// Mul multiplies the FloatHistogram by the provided factor, i.e. it scales all // bucket counts including the zero bucket and the count and the sum of // observations. The bucket layout stays the same. This method changes the // receiving histogram directly (rather than acting on a copy). It returns a // pointer to the receiving histogram for convenience. -func (h *FloatHistogram) Scale(factor float64) *FloatHistogram { +func (h *FloatHistogram) Mul(factor float64) *FloatHistogram { h.ZeroCount *= factor h.Count *= factor h.Sum *= factor @@ -177,6 +239,21 @@ func (h *FloatHistogram) Scale(factor float64) *FloatHistogram { return h } +// Div works like Mul but divides instead of multiplies. +// When dividing by 0, everything will be set to Inf. +func (h *FloatHistogram) Div(scalar float64) *FloatHistogram { + h.ZeroCount /= scalar + h.Count /= scalar + h.Sum /= scalar + for i := range h.PositiveBuckets { + h.PositiveBuckets[i] /= scalar + } + for i := range h.NegativeBuckets { + h.NegativeBuckets[i] /= scalar + } + return h +} + // Add adds the provided other histogram to the receiving histogram. Count, Sum, // and buckets from the other histogram are added to the corresponding // components of the receiving histogram. Buckets in the other histogram that do @@ -184,11 +261,8 @@ func (h *FloatHistogram) Scale(factor float64) *FloatHistogram { // resulting histogram might have buckets with a population of zero or directly // adjacent spans (offset=0). To normalize those, call the Compact method. // -// The method reconciles differences in the zero threshold and in the schema, -// but the schema of the other histogram must be ≥ the schema of the receiving -// histogram (i.e. must have an equal or higher resolution). This means that the -// schema of the receiving histogram won't change. Its zero threshold, however, -// will change if needed. The other histogram will not be modified in any case. +// The method reconciles differences in the zero threshold and in the schema, and +// changes them if needed. The other histogram will not be modified in any case. // // This method returns a pointer to the receiving histogram for convenience. func (h *FloatHistogram) Add(other *FloatHistogram) *FloatHistogram { @@ -221,23 +295,32 @@ func (h *FloatHistogram) Add(other *FloatHistogram) *FloatHistogram { h.Count += other.Count h.Sum += other.Sum - // TODO(beorn7): If needed, this can be optimized by inspecting the - // spans in other and create missing buckets in h in batches. - var iInSpan, index int32 - for iSpan, iBucket, it := -1, -1, other.floatBucketIterator(true, h.ZeroThreshold, h.Schema); it.Next(); { - b := it.At() - h.PositiveSpans, h.PositiveBuckets, iSpan, iBucket, iInSpan = addBucket( - b, h.PositiveSpans, h.PositiveBuckets, iSpan, iBucket, iInSpan, index, - ) - index = b.Index - } - for iSpan, iBucket, it := -1, -1, other.floatBucketIterator(false, h.ZeroThreshold, h.Schema); it.Next(); { - b := it.At() - h.NegativeSpans, h.NegativeBuckets, iSpan, iBucket, iInSpan = addBucket( - b, h.NegativeSpans, h.NegativeBuckets, iSpan, iBucket, iInSpan, index, - ) - index = b.Index + var ( + hPositiveSpans = h.PositiveSpans + hPositiveBuckets = h.PositiveBuckets + hNegativeSpans = h.NegativeSpans + hNegativeBuckets = h.NegativeBuckets + + otherPositiveSpans = other.PositiveSpans + otherPositiveBuckets = other.PositiveBuckets + otherNegativeSpans = other.NegativeSpans + otherNegativeBuckets = other.NegativeBuckets + ) + + switch { + case other.Schema < h.Schema: + hPositiveSpans, hPositiveBuckets = reduceResolution(hPositiveSpans, hPositiveBuckets, h.Schema, other.Schema, false, true) + hNegativeSpans, hNegativeBuckets = reduceResolution(hNegativeSpans, hNegativeBuckets, h.Schema, other.Schema, false, true) + h.Schema = other.Schema + + case other.Schema > h.Schema: + otherPositiveSpans, otherPositiveBuckets = reduceResolution(otherPositiveSpans, otherPositiveBuckets, other.Schema, h.Schema, false, false) + otherNegativeSpans, otherNegativeBuckets = reduceResolution(otherNegativeSpans, otherNegativeBuckets, other.Schema, h.Schema, false, false) } + + h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, false, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) + h.NegativeSpans, h.NegativeBuckets = addBuckets(h.Schema, h.ZeroThreshold, false, hNegativeSpans, hNegativeBuckets, otherNegativeSpans, otherNegativeBuckets) + return h } @@ -248,25 +331,31 @@ func (h *FloatHistogram) Sub(other *FloatHistogram) *FloatHistogram { h.Count -= other.Count h.Sum -= other.Sum - // TODO(beorn7): If needed, this can be optimized by inspecting the - // spans in other and create missing buckets in h in batches. - var iInSpan, index int32 - for iSpan, iBucket, it := -1, -1, other.floatBucketIterator(true, h.ZeroThreshold, h.Schema); it.Next(); { - b := it.At() - b.Count *= -1 - h.PositiveSpans, h.PositiveBuckets, iSpan, iBucket, iInSpan = addBucket( - b, h.PositiveSpans, h.PositiveBuckets, iSpan, iBucket, iInSpan, index, - ) - index = b.Index - } - for iSpan, iBucket, it := -1, -1, other.floatBucketIterator(false, h.ZeroThreshold, h.Schema); it.Next(); { - b := it.At() - b.Count *= -1 - h.NegativeSpans, h.NegativeBuckets, iSpan, iBucket, iInSpan = addBucket( - b, h.NegativeSpans, h.NegativeBuckets, iSpan, iBucket, iInSpan, index, - ) - index = b.Index + var ( + hPositiveSpans = h.PositiveSpans + hPositiveBuckets = h.PositiveBuckets + hNegativeSpans = h.NegativeSpans + hNegativeBuckets = h.NegativeBuckets + + otherPositiveSpans = other.PositiveSpans + otherPositiveBuckets = other.PositiveBuckets + otherNegativeSpans = other.NegativeSpans + otherNegativeBuckets = other.NegativeBuckets + ) + + switch { + case other.Schema < h.Schema: + hPositiveSpans, hPositiveBuckets = reduceResolution(hPositiveSpans, hPositiveBuckets, h.Schema, other.Schema, false, true) + hNegativeSpans, hNegativeBuckets = reduceResolution(hNegativeSpans, hNegativeBuckets, h.Schema, other.Schema, false, true) + h.Schema = other.Schema + case other.Schema > h.Schema: + otherPositiveSpans, otherPositiveBuckets = reduceResolution(otherPositiveSpans, otherPositiveBuckets, other.Schema, h.Schema, false, false) + otherNegativeSpans, otherNegativeBuckets = reduceResolution(otherNegativeSpans, otherNegativeBuckets, other.Schema, h.Schema, false, false) } + + h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, true, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) + h.NegativeSpans, h.NegativeBuckets = addBuckets(h.Schema, h.ZeroThreshold, true, hNegativeSpans, hNegativeBuckets, otherNegativeSpans, otherNegativeBuckets) + return h } @@ -274,13 +363,17 @@ func (h *FloatHistogram) Sub(other *FloatHistogram) *FloatHistogram { // Exact match is when there are no new buckets (even empty) and no missing buckets, // and all the bucket values match. Spans can have different empty length spans in between, // but they must represent the same bucket layout to match. +// Sum, Count, ZeroCount and bucket values are compared based on their bit patterns +// because this method is about data equality rather than mathematical equality. func (h *FloatHistogram) Equals(h2 *FloatHistogram) bool { if h2 == nil { return false } if h.Schema != h2.Schema || h.ZeroThreshold != h2.ZeroThreshold || - h.ZeroCount != h2.ZeroCount || h.Count != h2.Count || h.Sum != h2.Sum { + math.Float64bits(h.ZeroCount) != math.Float64bits(h2.ZeroCount) || + math.Float64bits(h.Count) != math.Float64bits(h2.Count) || + math.Float64bits(h.Sum) != math.Float64bits(h2.Sum) { return false } @@ -291,111 +384,42 @@ func (h *FloatHistogram) Equals(h2 *FloatHistogram) bool { return false } - if !bucketsMatch(h.PositiveBuckets, h2.PositiveBuckets) { + if !floatBucketsMatch(h.PositiveBuckets, h2.PositiveBuckets) { return false } - if !bucketsMatch(h.NegativeBuckets, h2.NegativeBuckets) { + if !floatBucketsMatch(h.NegativeBuckets, h2.NegativeBuckets) { return false } return true } -// addBucket takes the "coordinates" of the last bucket that was handled and -// adds the provided bucket after it. If a corresponding bucket exists, the -// count is added. If not, the bucket is inserted. The updated slices and the -// coordinates of the inserted or added-to bucket are returned. -func addBucket( - b Bucket[float64], - spans []Span, buckets []float64, - iSpan, iBucket int, - iInSpan, index int32, -) ( - newSpans []Span, newBuckets []float64, - newISpan, newIBucket int, newIInSpan int32, -) { - if iSpan == -1 { - // First add, check if it is before all spans. - if len(spans) == 0 || spans[0].Offset > b.Index { - // Add bucket before all others. - buckets = append(buckets, 0) - copy(buckets[1:], buckets) - buckets[0] = b.Count - if len(spans) > 0 && spans[0].Offset == b.Index+1 { - spans[0].Length++ - spans[0].Offset-- - return spans, buckets, 0, 0, 0 - } - spans = append(spans, Span{}) - copy(spans[1:], spans) - spans[0] = Span{Offset: b.Index, Length: 1} - if len(spans) > 1 { - // Convert the absolute offset in the formerly - // first span to a relative offset. - spans[1].Offset -= b.Index + 1 - } - return spans, buckets, 0, 0, 0 - } - if spans[0].Offset == b.Index { - // Just add to first bucket. - buckets[0] += b.Count - return spans, buckets, 0, 0, 0 - } - // We are behind the first bucket, so set everything to the - // first bucket and continue normally. - iSpan, iBucket, iInSpan = 0, 0, 0 - index = spans[0].Offset - } - deltaIndex := b.Index - index - for { - remainingInSpan := int32(spans[iSpan].Length) - iInSpan - if deltaIndex < remainingInSpan { - // Bucket is in current span. - iBucket += int(deltaIndex) - iInSpan += deltaIndex - buckets[iBucket] += b.Count - return spans, buckets, iSpan, iBucket, iInSpan - } - deltaIndex -= remainingInSpan - iBucket += int(remainingInSpan) - iSpan++ - if iSpan == len(spans) || deltaIndex < spans[iSpan].Offset { - // Bucket is in gap behind previous span (or there are no further spans). - buckets = append(buckets, 0) - copy(buckets[iBucket+1:], buckets[iBucket:]) - buckets[iBucket] = b.Count - if deltaIndex == 0 { - // Directly after previous span, extend previous span. - if iSpan < len(spans) { - spans[iSpan].Offset-- - } - iSpan-- - iInSpan = int32(spans[iSpan].Length) - spans[iSpan].Length++ - return spans, buckets, iSpan, iBucket, iInSpan - } - if iSpan < len(spans) && deltaIndex == spans[iSpan].Offset-1 { - // Directly before next span, extend next span. - iInSpan = 0 - spans[iSpan].Offset-- - spans[iSpan].Length++ - return spans, buckets, iSpan, iBucket, iInSpan - } - // No next span, or next span is not directly adjacent to new bucket. - // Add new span. - iInSpan = 0 - if iSpan < len(spans) { - spans[iSpan].Offset -= deltaIndex + 1 - } - spans = append(spans, Span{}) - copy(spans[iSpan+1:], spans[iSpan:]) - spans[iSpan] = Span{Length: 1, Offset: deltaIndex} - return spans, buckets, iSpan, iBucket, iInSpan - } - // Try start of next span. - deltaIndex -= spans[iSpan].Offset - iInSpan = 0 - } +// Size returns the total size of the FloatHistogram, which includes the size of the pointer +// to FloatHistogram, all its fields, and all elements contained in slices. +// NOTE: this is only valid for 64 bit architectures. +func (h *FloatHistogram) Size() int { + // Size of each slice separately. + posSpanSize := len(h.PositiveSpans) * 8 // 8 bytes (int32 + uint32). + negSpanSize := len(h.NegativeSpans) * 8 // 8 bytes (int32 + uint32). + posBucketSize := len(h.PositiveBuckets) * 8 // 8 bytes (float64). + negBucketSize := len(h.NegativeBuckets) * 8 // 8 bytes (float64). + + // Total size of the struct. + + // fh is 8 bytes. + // fh.CounterResetHint is 4 bytes (1 byte bool + 3 bytes padding). + // fh.Schema is 4 bytes. + // fh.ZeroThreshold is 8 bytes. + // fh.ZeroCount is 8 bytes. + // fh.Count is 8 bytes. + // fh.Sum is 8 bytes. + // fh.PositiveSpans is 24 bytes. + // fh.NegativeSpans is 24 bytes. + // fh.PositiveBuckets is 24 bytes. + // fh.NegativeBuckets is 24 bytes. + structSize := 144 + + return structSize + posSpanSize + negSpanSize + posBucketSize + negBucketSize } // Compact eliminates empty buckets at the beginning and end of each span, then @@ -406,7 +430,7 @@ func addBucket( // receiving histogram, but a pointer to it is returned for convenience. // // The ideal value for maxEmptyBuckets depends on circumstances. The motivation -// to set maxEmptyBuckets > 0 is the assumption that is is less overhead to +// to set maxEmptyBuckets > 0 is the assumption that is less overhead to // represent very few empty buckets explicitly within one span than cutting the // one span into two to treat the empty buckets as a gap between the two spans, // both in terms of storage requirement as well as in terms of encoding and @@ -475,8 +499,8 @@ func (h *FloatHistogram) DetectReset(previous *FloatHistogram) bool { // is a counter reset or not. // We do the same if the CounterResetHint is GaugeType, which should not happen, but PromQL still // allows the user to apply functions to gauge histograms that are only meant for counter histograms. - // In this case, we treat the gauge histograms as a counter histograms - // (and we plan to return a warning about it to the user). + // In this case, we treat the gauge histograms as counter histograms. A warning should be returned + // to the user in this case. if h.Count < previous.Count { return true } @@ -498,25 +522,25 @@ func (h *FloatHistogram) DetectReset(previous *FloatHistogram) bool { } currIt := h.floatBucketIterator(true, h.ZeroThreshold, h.Schema) prevIt := previous.floatBucketIterator(true, h.ZeroThreshold, h.Schema) - if detectReset(currIt, prevIt) { + if detectReset(&currIt, &prevIt) { return true } currIt = h.floatBucketIterator(false, h.ZeroThreshold, h.Schema) prevIt = previous.floatBucketIterator(false, h.ZeroThreshold, h.Schema) - return detectReset(currIt, prevIt) + return detectReset(&currIt, &prevIt) } -func detectReset(currIt, prevIt BucketIterator[float64]) bool { +func detectReset(currIt, prevIt *floatBucketIterator) bool { if !prevIt.Next() { return false // If no buckets in previous histogram, nothing can be reset. } - prevBucket := prevIt.At() + prevBucket := prevIt.strippedAt() if !currIt.Next() { // No bucket in current, but at least one in previous // histogram. Check if any of those are non-zero, in which case // this is a reset. for { - if prevBucket.Count != 0 { + if prevBucket.count != 0 { return true } if !prevIt.Next() { @@ -524,10 +548,10 @@ func detectReset(currIt, prevIt BucketIterator[float64]) bool { } } } - currBucket := currIt.At() + currBucket := currIt.strippedAt() for { // Forward currIt until we find the bucket corresponding to prevBucket. - for currBucket.Index < prevBucket.Index { + for currBucket.index < prevBucket.index { if !currIt.Next() { // Reached end of currIt early, therefore // previous histogram has a bucket that the @@ -535,7 +559,7 @@ func detectReset(currIt, prevIt BucketIterator[float64]) bool { // remaining buckets in the previous histogram // are unpopulated, this is a reset. for { - if prevBucket.Count != 0 { + if prevBucket.count != 0 { return true } if !prevIt.Next() { @@ -543,18 +567,18 @@ func detectReset(currIt, prevIt BucketIterator[float64]) bool { } } } - currBucket = currIt.At() + currBucket = currIt.strippedAt() } - if currBucket.Index > prevBucket.Index { + if currBucket.index > prevBucket.index { // Previous histogram has a bucket the current one does // not have. If it's populated, it's a reset. - if prevBucket.Count != 0 { + if prevBucket.count != 0 { return true } } else { // We have reached corresponding buckets in both iterators. // We can finally compare the counts. - if currBucket.Count < prevBucket.Count { + if currBucket.count < prevBucket.count { return true } } @@ -562,35 +586,39 @@ func detectReset(currIt, prevIt BucketIterator[float64]) bool { // Reached end of prevIt without finding offending buckets. return false } - prevBucket = prevIt.At() + prevBucket = prevIt.strippedAt() } } // PositiveBucketIterator returns a BucketIterator to iterate over all positive // buckets in ascending order (starting next to the zero bucket and going up). func (h *FloatHistogram) PositiveBucketIterator() BucketIterator[float64] { - return h.floatBucketIterator(true, 0, h.Schema) + it := h.floatBucketIterator(true, 0, h.Schema) + return &it } // NegativeBucketIterator returns a BucketIterator to iterate over all negative // buckets in descending order (starting next to the zero bucket and going // down). func (h *FloatHistogram) NegativeBucketIterator() BucketIterator[float64] { - return h.floatBucketIterator(false, 0, h.Schema) + it := h.floatBucketIterator(false, 0, h.Schema) + return &it } // PositiveReverseBucketIterator returns a BucketIterator to iterate over all // positive buckets in descending order (starting at the highest bucket and // going down towards the zero bucket). func (h *FloatHistogram) PositiveReverseBucketIterator() BucketIterator[float64] { - return newReverseFloatBucketIterator(h.PositiveSpans, h.PositiveBuckets, h.Schema, true) + it := newReverseFloatBucketIterator(h.PositiveSpans, h.PositiveBuckets, h.Schema, true) + return &it } // NegativeReverseBucketIterator returns a BucketIterator to iterate over all // negative buckets in ascending order (starting at the lowest bucket and going // up towards the zero bucket). func (h *FloatHistogram) NegativeReverseBucketIterator() BucketIterator[float64] { - return newReverseFloatBucketIterator(h.NegativeSpans, h.NegativeBuckets, h.Schema, false) + it := newReverseFloatBucketIterator(h.NegativeSpans, h.NegativeBuckets, h.Schema, false) + return &it } // AllBucketIterator returns a BucketIterator to iterate over all negative, @@ -600,11 +628,50 @@ func (h *FloatHistogram) NegativeReverseBucketIterator() BucketIterator[float64] // set to the zero threshold. func (h *FloatHistogram) AllBucketIterator() BucketIterator[float64] { return &allFloatBucketIterator{ - h: h, - negIter: h.NegativeReverseBucketIterator(), - posIter: h.PositiveBucketIterator(), - state: -1, + h: h, + leftIter: newReverseFloatBucketIterator(h.NegativeSpans, h.NegativeBuckets, h.Schema, false), + rightIter: h.floatBucketIterator(true, 0, h.Schema), + state: -1, + } +} + +// AllReverseBucketIterator returns a BucketIterator to iterate over all negative, +// zero, and positive buckets in descending order (starting at the lowest bucket +// and going up). If the highest negative bucket or the lowest positive bucket +// overlap with the zero bucket, their upper or lower boundary, respectively, is +// set to the zero threshold. +func (h *FloatHistogram) AllReverseBucketIterator() BucketIterator[float64] { + return &allFloatBucketIterator{ + h: h, + leftIter: newReverseFloatBucketIterator(h.PositiveSpans, h.PositiveBuckets, h.Schema, true), + rightIter: h.floatBucketIterator(false, 0, h.Schema), + state: -1, + } +} + +// Validate validates consistency between span and bucket slices. Also, buckets are checked +// against negative values. +// We do not check for h.Count being at least as large as the sum of the +// counts in the buckets because floating point precision issues can +// create false positives here. +func (h *FloatHistogram) Validate() error { + if err := checkHistogramSpans(h.NegativeSpans, len(h.NegativeBuckets)); err != nil { + return fmt.Errorf("negative side: %w", err) + } + if err := checkHistogramSpans(h.PositiveSpans, len(h.PositiveBuckets)); err != nil { + return fmt.Errorf("positive side: %w", err) + } + var nCount, pCount float64 + err := checkHistogramBuckets(h.NegativeBuckets, &nCount, false) + if err != nil { + return fmt.Errorf("negative side: %w", err) } + err = checkHistogramBuckets(h.PositiveBuckets, &pCount, false) + if err != nil { + return fmt.Errorf("positive side: %w", err) + } + + return nil } // zeroCountForLargerThreshold returns what the histogram's zero count would be @@ -733,17 +800,18 @@ func (h *FloatHistogram) reconcileZeroBuckets(other *FloatHistogram) float64 { // targetSchema prior to iterating (without mutating FloatHistogram). func (h *FloatHistogram) floatBucketIterator( positive bool, absoluteStartValue float64, targetSchema int32, -) *floatBucketIterator { +) floatBucketIterator { if targetSchema > h.Schema { panic(fmt.Errorf("cannot merge from schema %d to %d", h.Schema, targetSchema)) } - i := &floatBucketIterator{ + i := floatBucketIterator{ baseBucketIterator: baseBucketIterator[float64, float64]{ schema: h.Schema, positive: positive, }, - targetSchema: targetSchema, - absoluteStartValue: absoluteStartValue, + targetSchema: targetSchema, + absoluteStartValue: absoluteStartValue, + boundReachedStartValue: absoluteStartValue == 0, } if positive { i.spans = h.PositiveSpans @@ -755,11 +823,11 @@ func (h *FloatHistogram) floatBucketIterator( return i } -// reverseFloatbucketiterator is a low-level constructor for reverse bucket iterators. +// reverseFloatBucketIterator is a low-level constructor for reverse bucket iterators. func newReverseFloatBucketIterator( spans []Span, buckets []float64, schema int32, positive bool, -) *reverseFloatBucketIterator { - r := &reverseFloatBucketIterator{ +) reverseFloatBucketIterator { + r := reverseFloatBucketIterator{ baseBucketIterator: baseBucketIterator[float64, float64]{ schema: schema, spans: spans, @@ -787,6 +855,13 @@ type floatBucketIterator struct { targetSchema int32 // targetSchema is the schema to merge to and must be ≤ schema. origIdx int32 // The bucket index within the original schema. absoluteStartValue float64 // Never return buckets with an upper bound ≤ this value. + + boundReachedStartValue bool // Has getBound reached absoluteStartValue already? +} + +func (i *floatBucketIterator) At() Bucket[float64] { + // Need to use i.targetSchema rather than i.baseBucketIterator.schema. + return i.baseBucketIterator.at(i.targetSchema) } func (i *floatBucketIterator) Next() bool { @@ -794,74 +869,92 @@ func (i *floatBucketIterator) Next() bool { return false } - // Copy all of these into local variables so that we can forward to the - // next bucket and then roll back if needed. - origIdx, spansIdx, idxInSpan := i.origIdx, i.spansIdx, i.idxInSpan - span := i.spans[spansIdx] - firstPass := true - i.currCount = 0 - -mergeLoop: // Merge together all buckets from the original schema that fall into one bucket in the targetSchema. - for { + if i.schema == i.targetSchema { + // Fast path for the common case. + span := i.spans[i.spansIdx] if i.bucketsIdx == 0 { // Seed origIdx for the first bucket. - origIdx = span.Offset + i.currIdx = span.Offset } else { - origIdx++ + i.currIdx++ } - for idxInSpan >= span.Length { + + for i.idxInSpan >= span.Length { // We have exhausted the current span and have to find a new // one. We even handle pathologic spans of length 0 here. - idxInSpan = 0 - spansIdx++ - if spansIdx >= len(i.spans) { - if firstPass { - return false - } - break mergeLoop + i.idxInSpan = 0 + i.spansIdx++ + if i.spansIdx >= len(i.spans) { + return false } - span = i.spans[spansIdx] - origIdx += span.Offset - } - currIdx := i.targetIdx(origIdx) - switch { - case firstPass: - i.currIdx = currIdx - firstPass = false - case currIdx != i.currIdx: - // Reached next bucket in targetSchema. - // Do not actually forward to the next bucket, but break out. - break mergeLoop + span = i.spans[i.spansIdx] + i.currIdx += span.Offset } - i.currCount += i.buckets[i.bucketsIdx] - idxInSpan++ + + i.currCount = i.buckets[i.bucketsIdx] + i.idxInSpan++ i.bucketsIdx++ - i.origIdx, i.spansIdx, i.idxInSpan = origIdx, spansIdx, idxInSpan - if i.schema == i.targetSchema { - // Don't need to test the next bucket for mergeability - // if we have no schema change anyway. - break mergeLoop + } else { + // Copy all of these into local variables so that we can forward to the + // next bucket and then roll back if needed. + origIdx, spansIdx, idxInSpan := i.origIdx, i.spansIdx, i.idxInSpan + span := i.spans[spansIdx] + firstPass := true + i.currCount = 0 + + mergeLoop: // Merge together all buckets from the original schema that fall into one bucket in the targetSchema. + for { + if i.bucketsIdx == 0 { + // Seed origIdx for the first bucket. + origIdx = span.Offset + } else { + origIdx++ + } + for idxInSpan >= span.Length { + // We have exhausted the current span and have to find a new + // one. We even handle pathologic spans of length 0 here. + idxInSpan = 0 + spansIdx++ + if spansIdx >= len(i.spans) { + if firstPass { + return false + } + break mergeLoop + } + span = i.spans[spansIdx] + origIdx += span.Offset + } + currIdx := targetIdx(origIdx, i.schema, i.targetSchema) + switch { + case firstPass: + i.currIdx = currIdx + firstPass = false + case currIdx != i.currIdx: + // Reached next bucket in targetSchema. + // Do not actually forward to the next bucket, but break out. + break mergeLoop + } + i.currCount += i.buckets[i.bucketsIdx] + idxInSpan++ + i.bucketsIdx++ + i.origIdx, i.spansIdx, i.idxInSpan = origIdx, spansIdx, idxInSpan + if i.schema == i.targetSchema { + // Don't need to test the next bucket for mergeability + // if we have no schema change anyway. + break mergeLoop + } } } + // Skip buckets before absoluteStartValue. // TODO(beorn7): Maybe do something more efficient than this recursive call. - if getBound(i.currIdx, i.targetSchema) <= i.absoluteStartValue { + if !i.boundReachedStartValue && getBound(i.currIdx, i.targetSchema) <= i.absoluteStartValue { return i.Next() } + i.boundReachedStartValue = true return true } -// targetIdx returns the bucket index within i.targetSchema for the given bucket -// index within i.schema. -func (i *floatBucketIterator) targetIdx(idx int32) int32 { - if i.schema == i.targetSchema { - // Fast path for the common case. The below would yield the same - // result, just with more effort. - return idx - } - return ((idx - 1) >> (i.schema - i.targetSchema)) + 1 -} - type reverseFloatBucketIterator struct { baseBucketIterator[float64, float64] idxInSpan int32 // Changed from uint32 to allow negative values for exhaustion detection. @@ -888,8 +981,9 @@ func (i *reverseFloatBucketIterator) Next() bool { } type allFloatBucketIterator struct { - h *FloatHistogram - negIter, posIter BucketIterator[float64] + h *FloatHistogram + leftIter reverseFloatBucketIterator + rightIter floatBucketIterator // -1 means we are iterating negative buckets. // 0 means it is time for the zero bucket. // 1 means we are iterating positive buckets. @@ -901,10 +995,13 @@ type allFloatBucketIterator struct { func (i *allFloatBucketIterator) Next() bool { switch i.state { case -1: - if i.negIter.Next() { - i.currBucket = i.negIter.At() - if i.currBucket.Upper > -i.h.ZeroThreshold { + if i.leftIter.Next() { + i.currBucket = i.leftIter.At() + switch { + case i.currBucket.Upper < 0 && i.currBucket.Upper > -i.h.ZeroThreshold: i.currBucket.Upper = -i.h.ZeroThreshold + case i.currBucket.Lower > 0 && i.currBucket.Lower < i.h.ZeroThreshold: + i.currBucket.Lower = i.h.ZeroThreshold } return true } @@ -925,10 +1022,13 @@ func (i *allFloatBucketIterator) Next() bool { } return i.Next() case 1: - if i.posIter.Next() { - i.currBucket = i.posIter.At() - if i.currBucket.Lower < i.h.ZeroThreshold { + if i.rightIter.Next() { + i.currBucket = i.rightIter.At() + switch { + case i.currBucket.Lower > 0 && i.currBucket.Lower < i.h.ZeroThreshold: i.currBucket.Lower = i.h.ZeroThreshold + case i.currBucket.Upper < 0 && i.currBucket.Upper > -i.h.ZeroThreshold: + i.currBucket.Upper = -i.h.ZeroThreshold } return true } @@ -942,3 +1042,163 @@ func (i *allFloatBucketIterator) Next() bool { func (i *allFloatBucketIterator) At() Bucket[float64] { return i.currBucket } + +// targetIdx returns the bucket index in the target schema for the given bucket +// index idx in the original schema. +func targetIdx(idx, originSchema, targetSchema int32) int32 { + return ((idx - 1) >> (originSchema - targetSchema)) + 1 +} + +// addBuckets adds the buckets described by spansB/bucketsB to the buckets described by spansA/bucketsA, +// creating missing buckets in spansA/bucketsA as needed. +// It returns the resulting spans/buckets (which must be used instead of the original spansA/bucketsA, +// although spansA/bucketsA might get modified by this function). +// All buckets must use the same provided schema. +// Buckets in spansB/bucketsB with an absolute upper limit ≤ threshold are ignored. +// If negative is true, the buckets in spansB/bucketsB are subtracted rather than added. +func addBuckets( + schema int32, threshold float64, negative bool, + spansA []Span, bucketsA []float64, + spansB []Span, bucketsB []float64, +) ([]Span, []float64) { + var ( + iSpan = -1 + iBucket = -1 + iInSpan int32 + indexA int32 + indexB int32 + bIdxB int + bucketB float64 + deltaIndex int32 + lowerThanThreshold = true + ) + + for _, spanB := range spansB { + indexB += spanB.Offset + for j := 0; j < int(spanB.Length); j++ { + if lowerThanThreshold && getBound(indexB, schema) <= threshold { + goto nextLoop + } + lowerThanThreshold = false + + bucketB = bucketsB[bIdxB] + if negative { + bucketB *= -1 + } + + if iSpan == -1 { + if len(spansA) == 0 || spansA[0].Offset > indexB { + // Add bucket before all others. + bucketsA = append(bucketsA, 0) + copy(bucketsA[1:], bucketsA) + bucketsA[0] = bucketB + if len(spansA) > 0 && spansA[0].Offset == indexB+1 { + spansA[0].Length++ + spansA[0].Offset-- + goto nextLoop + } + spansA = append(spansA, Span{}) + copy(spansA[1:], spansA) + spansA[0] = Span{Offset: indexB, Length: 1} + if len(spansA) > 1 { + // Convert the absolute offset in the formerly + // first span to a relative offset. + spansA[1].Offset -= indexB + 1 + } + goto nextLoop + } else if spansA[0].Offset == indexB { + // Just add to first bucket. + bucketsA[0] += bucketB + goto nextLoop + } + iSpan, iBucket, iInSpan = 0, 0, 0 + indexA = spansA[0].Offset + } + deltaIndex = indexB - indexA + for { + remainingInSpan := int32(spansA[iSpan].Length) - iInSpan + if deltaIndex < remainingInSpan { + // Bucket is in current span. + iBucket += int(deltaIndex) + iInSpan += deltaIndex + bucketsA[iBucket] += bucketB + break + } + deltaIndex -= remainingInSpan + iBucket += int(remainingInSpan) + iSpan++ + if iSpan == len(spansA) || deltaIndex < spansA[iSpan].Offset { + // Bucket is in gap behind previous span (or there are no further spans). + bucketsA = append(bucketsA, 0) + copy(bucketsA[iBucket+1:], bucketsA[iBucket:]) + bucketsA[iBucket] = bucketB + switch { + case deltaIndex == 0: + // Directly after previous span, extend previous span. + if iSpan < len(spansA) { + spansA[iSpan].Offset-- + } + iSpan-- + iInSpan = int32(spansA[iSpan].Length) + spansA[iSpan].Length++ + goto nextLoop + case iSpan < len(spansA) && deltaIndex == spansA[iSpan].Offset-1: + // Directly before next span, extend next span. + iInSpan = 0 + spansA[iSpan].Offset-- + spansA[iSpan].Length++ + goto nextLoop + default: + // No next span, or next span is not directly adjacent to new bucket. + // Add new span. + iInSpan = 0 + if iSpan < len(spansA) { + spansA[iSpan].Offset -= deltaIndex + 1 + } + spansA = append(spansA, Span{}) + copy(spansA[iSpan+1:], spansA[iSpan:]) + spansA[iSpan] = Span{Length: 1, Offset: deltaIndex} + goto nextLoop + } + } else { + // Try start of next span. + deltaIndex -= spansA[iSpan].Offset + iInSpan = 0 + } + } + + nextLoop: + indexA = indexB + indexB++ + bIdxB++ + } + } + + return spansA, bucketsA +} + +func floatBucketsMatch(b1, b2 []float64) bool { + if len(b1) != len(b2) { + return false + } + for i, b := range b1 { + if math.Float64bits(b) != math.Float64bits(b2[i]) { + return false + } + } + return true +} + +// ReduceResolution reduces the float histogram's spans, buckets into target schema. +// The target schema must be smaller than the current float histogram's schema. +func (h *FloatHistogram) ReduceResolution(targetSchema int32) *FloatHistogram { + if targetSchema >= h.Schema { + panic(fmt.Errorf("cannot reduce resolution from schema %d to %d", h.Schema, targetSchema)) + } + + h.PositiveSpans, h.PositiveBuckets = reduceResolution(h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, false, true) + h.NegativeSpans, h.NegativeBuckets = reduceResolution(h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, false, true) + + h.Schema = targetSchema + return h +} diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/generic.go b/vendor/github.com/prometheus/prometheus/model/histogram/generic.go index e1de5ffb5..7e1cc4b60 100644 --- a/vendor/github.com/prometheus/prometheus/model/histogram/generic.go +++ b/vendor/github.com/prometheus/prometheus/model/histogram/generic.go @@ -14,11 +14,20 @@ package histogram import ( + "errors" "fmt" "math" "strings" ) +var ( + ErrHistogramCountNotBigEnough = errors.New("histogram's observation count should be at least the number of observations found in the buckets") + ErrHistogramCountMismatch = errors.New("histogram's observation count should equal the number of observations found in the buckets (in absence of NaN)") + ErrHistogramNegativeBucketCount = errors.New("histogram has a bucket whose observation count is negative") + ErrHistogramSpanNegativeOffset = errors.New("histogram has a span whose offset is negative") + ErrHistogramSpansBucketsMismatch = errors.New("histogram spans specify different number of buckets than provided") +) + // BucketCount is a type constraint for the count in a bucket, which can be // float64 (for type FloatHistogram) or uint64 (for type Histogram). type BucketCount interface { @@ -31,7 +40,7 @@ type BucketCount interface { // absolute counts directly). Go type parameters don't allow type // specialization. Therefore, where special treatment of deltas between buckets // vs. absolute counts is important, this information has to be provided as a -// separate boolean parameter "deltaBuckets" +// separate boolean parameter "deltaBuckets". type InternalBucketCount interface { float64 | int64 } @@ -53,6 +62,13 @@ type Bucket[BC BucketCount] struct { Index int32 } +// strippedBucket is Bucket without bound values (which are expensive to calculate +// and not used in certain use cases). +type strippedBucket[BC BucketCount] struct { + count BC + index int32 +} + // String returns a string representation of a Bucket, using the usual // mathematical notation of '['/']' for inclusive bounds and '('/')' for // non-inclusive bounds. @@ -101,23 +117,36 @@ type baseBucketIterator[BC BucketCount, IBC InternalBucketCount] struct { currIdx int32 // The actual bucket index. } -func (b baseBucketIterator[BC, IBC]) At() Bucket[BC] { +func (b *baseBucketIterator[BC, IBC]) At() Bucket[BC] { + return b.at(b.schema) +} + +// at is an internal version of the exported At to enable using a different schema. +func (b *baseBucketIterator[BC, IBC]) at(schema int32) Bucket[BC] { bucket := Bucket[BC]{ Count: BC(b.currCount), Index: b.currIdx, } if b.positive { - bucket.Upper = getBound(b.currIdx, b.schema) - bucket.Lower = getBound(b.currIdx-1, b.schema) + bucket.Upper = getBound(b.currIdx, schema) + bucket.Lower = getBound(b.currIdx-1, schema) } else { - bucket.Lower = -getBound(b.currIdx, b.schema) - bucket.Upper = -getBound(b.currIdx-1, b.schema) + bucket.Lower = -getBound(b.currIdx, schema) + bucket.Upper = -getBound(b.currIdx-1, schema) } bucket.LowerInclusive = bucket.Lower < 0 bucket.UpperInclusive = bucket.Upper > 0 return bucket } +// strippedAt returns current strippedBucket (which lacks bucket bounds but is cheaper to compute). +func (b *baseBucketIterator[BC, IBC]) strippedAt() strippedBucket[BC] { + return strippedBucket[BC]{ + count: BC(b.currCount), + index: b.currIdx, + } +} + // compactBuckets is a generic function used by both Histogram.Compact and // FloatHistogram.Compact. Set deltaBuckets to true if the provided buckets are // deltas. Set it to false if the buckets contain absolute counts. @@ -327,16 +356,41 @@ func compactBuckets[IBC InternalBucketCount](buckets []IBC, spans []Span, maxEmp return buckets, spans } -func bucketsMatch[IBC InternalBucketCount](b1, b2 []IBC) bool { - if len(b1) != len(b2) { - return false +func checkHistogramSpans(spans []Span, numBuckets int) error { + var spanBuckets int + for n, span := range spans { + if n > 0 && span.Offset < 0 { + return fmt.Errorf("span number %d with offset %d: %w", n+1, span.Offset, ErrHistogramSpanNegativeOffset) + } + spanBuckets += int(span.Length) + } + if spanBuckets != numBuckets { + return fmt.Errorf("spans need %d buckets, have %d buckets: %w", spanBuckets, numBuckets, ErrHistogramSpansBucketsMismatch) } - for i, b := range b1 { - if b != b2[i] { - return false + return nil +} + +func checkHistogramBuckets[BC BucketCount, IBC InternalBucketCount](buckets []IBC, count *BC, deltas bool) error { + if len(buckets) == 0 { + return nil + } + + var last IBC + for i := 0; i < len(buckets); i++ { + var c IBC + if deltas { + c = last + buckets[i] + } else { + c = buckets[i] } + if c < 0 { + return fmt.Errorf("bucket number %d has observation count of %v: %w", i+1, c, ErrHistogramNegativeBucketCount) + } + last = c + *count += BC(c) } - return true + + return nil } func getBound(idx, schema int32) float64 { @@ -546,3 +600,106 @@ var exponentialBounds = [][]float64{ 0.9892280131939752, 0.9919100824251095, 0.9945994234836328, 0.9972960560854698, }, } + +// reduceResolution reduces the input spans, buckets in origin schema to the spans, buckets in target schema. +// The target schema must be smaller than the original schema. +// Set deltaBuckets to true if the provided buckets are +// deltas. Set it to false if the buckets contain absolute counts. +// Set inplace to true to reuse input slices and avoid allocations (otherwise +// new slices will be allocated for result). +func reduceResolution[IBC InternalBucketCount]( + originSpans []Span, + originBuckets []IBC, + originSchema, + targetSchema int32, + deltaBuckets bool, + inplace bool, +) ([]Span, []IBC) { + var ( + targetSpans []Span // The spans in the target schema. + targetBuckets []IBC // The bucket counts in the target schema. + bucketIdx int32 // The index of bucket in the origin schema. + bucketCountIdx int // The position of a bucket in origin bucket count slice `originBuckets`. + targetBucketIdx int32 // The index of bucket in the target schema. + lastBucketCount IBC // The last visited bucket's count in the origin schema. + lastTargetBucketIdx int32 // The index of the last added target bucket. + lastTargetBucketCount IBC + ) + + if inplace { + // Slice reuse is safe because when reducing the resolution, + // target slices don't grow faster than origin slices are being read. + targetSpans = originSpans[:0] + targetBuckets = originBuckets[:0] + } + + for _, span := range originSpans { + // Determine the index of the first bucket in this span. + bucketIdx += span.Offset + for j := 0; j < int(span.Length); j++ { + // Determine the index of the bucket in the target schema from the index in the original schema. + targetBucketIdx = targetIdx(bucketIdx, originSchema, targetSchema) + + switch { + case len(targetSpans) == 0: + // This is the first span in the targetSpans. + span := Span{ + Offset: targetBucketIdx, + Length: 1, + } + targetSpans = append(targetSpans, span) + targetBuckets = append(targetBuckets, originBuckets[bucketCountIdx]) + lastTargetBucketIdx = targetBucketIdx + lastBucketCount = originBuckets[bucketCountIdx] + lastTargetBucketCount = originBuckets[bucketCountIdx] + + case lastTargetBucketIdx == targetBucketIdx: + // The current bucket has to be merged into the same target bucket as the previous bucket. + if deltaBuckets { + lastBucketCount += originBuckets[bucketCountIdx] + targetBuckets[len(targetBuckets)-1] += lastBucketCount + lastTargetBucketCount += lastBucketCount + } else { + targetBuckets[len(targetBuckets)-1] += originBuckets[bucketCountIdx] + } + + case (lastTargetBucketIdx + 1) == targetBucketIdx: + // The current bucket has to go into a new target bucket, + // and that bucket is next to the previous target bucket, + // so we add it to the current target span. + targetSpans[len(targetSpans)-1].Length++ + lastTargetBucketIdx++ + if deltaBuckets { + lastBucketCount += originBuckets[bucketCountIdx] + targetBuckets = append(targetBuckets, lastBucketCount-lastTargetBucketCount) + lastTargetBucketCount = lastBucketCount + } else { + targetBuckets = append(targetBuckets, originBuckets[bucketCountIdx]) + } + + case (lastTargetBucketIdx + 1) < targetBucketIdx: + // The current bucket has to go into a new target bucket, + // and that bucket is separated by a gap from the previous target bucket, + // so we need to add a new target span. + span := Span{ + Offset: targetBucketIdx - lastTargetBucketIdx - 1, + Length: 1, + } + targetSpans = append(targetSpans, span) + lastTargetBucketIdx = targetBucketIdx + if deltaBuckets { + lastBucketCount += originBuckets[bucketCountIdx] + targetBuckets = append(targetBuckets, lastBucketCount-lastTargetBucketCount) + lastTargetBucketCount = lastBucketCount + } else { + targetBuckets = append(targetBuckets, originBuckets[bucketCountIdx]) + } + } + + bucketIdx++ + bucketCountIdx++ + } + } + + return targetSpans, targetBuckets +} diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go b/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go index 6d425307c..d40adeb62 100644 --- a/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go +++ b/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go @@ -17,6 +17,8 @@ import ( "fmt" "math" "strings" + + "golang.org/x/exp/slices" ) // CounterResetHint contains the known information about a counter reset, @@ -81,7 +83,14 @@ type Span struct { // Copy returns a deep copy of the Histogram. func (h *Histogram) Copy() *Histogram { - c := *h + c := Histogram{ + CounterResetHint: h.CounterResetHint, + Schema: h.Schema, + ZeroThreshold: h.ZeroThreshold, + ZeroCount: h.ZeroCount, + Count: h.Count, + Sum: h.Sum, + } if len(h.PositiveSpans) != 0 { c.PositiveSpans = make([]Span, len(h.PositiveSpans)) @@ -103,6 +112,29 @@ func (h *Histogram) Copy() *Histogram { return &c } +// CopyTo makes a deep copy into the given Histogram object. +// The destination object has to be a non-nil pointer. +func (h *Histogram) CopyTo(to *Histogram) { + to.CounterResetHint = h.CounterResetHint + to.Schema = h.Schema + to.ZeroThreshold = h.ZeroThreshold + to.ZeroCount = h.ZeroCount + to.Count = h.Count + to.Sum = h.Sum + + to.PositiveSpans = resize(to.PositiveSpans, len(h.PositiveSpans)) + copy(to.PositiveSpans, h.PositiveSpans) + + to.NegativeSpans = resize(to.NegativeSpans, len(h.NegativeSpans)) + copy(to.NegativeSpans, h.NegativeSpans) + + to.PositiveBuckets = resize(to.PositiveBuckets, len(h.PositiveBuckets)) + copy(to.PositiveBuckets, h.PositiveBuckets) + + to.NegativeBuckets = resize(to.NegativeBuckets, len(h.NegativeBuckets)) + copy(to.NegativeBuckets, h.NegativeBuckets) +} + // String returns a string representation of the Histogram. func (h *Histogram) String() string { var sb strings.Builder @@ -148,13 +180,15 @@ func (h *Histogram) ZeroBucket() Bucket[uint64] { // PositiveBucketIterator returns a BucketIterator to iterate over all positive // buckets in ascending order (starting next to the zero bucket and going up). func (h *Histogram) PositiveBucketIterator() BucketIterator[uint64] { - return newRegularBucketIterator(h.PositiveSpans, h.PositiveBuckets, h.Schema, true) + it := newRegularBucketIterator(h.PositiveSpans, h.PositiveBuckets, h.Schema, true) + return &it } // NegativeBucketIterator returns a BucketIterator to iterate over all negative // buckets in descending order (starting next to the zero bucket and going down). func (h *Histogram) NegativeBucketIterator() BucketIterator[uint64] { - return newRegularBucketIterator(h.NegativeSpans, h.NegativeBuckets, h.Schema, false) + it := newRegularBucketIterator(h.NegativeSpans, h.NegativeBuckets, h.Schema, false) + return &it } // CumulativeBucketIterator returns a BucketIterator to iterate over a @@ -172,13 +206,16 @@ func (h *Histogram) CumulativeBucketIterator() BucketIterator[uint64] { // Exact match is when there are no new buckets (even empty) and no missing buckets, // and all the bucket values match. Spans can have different empty length spans in between, // but they must represent the same bucket layout to match. +// Sum is compared based on its bit pattern because this method +// is about data equality rather than mathematical equality. func (h *Histogram) Equals(h2 *Histogram) bool { if h2 == nil { return false } if h.Schema != h2.Schema || h.ZeroThreshold != h2.ZeroThreshold || - h.ZeroCount != h2.ZeroCount || h.Count != h2.Count || h.Sum != h2.Sum { + h.ZeroCount != h2.ZeroCount || h.Count != h2.Count || + math.Float64bits(h.Sum) != math.Float64bits(h2.Sum) { return false } @@ -189,10 +226,10 @@ func (h *Histogram) Equals(h2 *Histogram) bool { return false } - if !bucketsMatch(h.PositiveBuckets, h2.PositiveBuckets) { + if !slices.Equal(h.PositiveBuckets, h2.PositiveBuckets) { return false } - if !bucketsMatch(h.NegativeBuckets, h2.NegativeBuckets) { + if !slices.Equal(h.NegativeBuckets, h2.NegativeBuckets) { return false } @@ -275,64 +312,101 @@ func (h *Histogram) Compact(maxEmptyBuckets int) *Histogram { return h } -// ToFloat returns a FloatHistogram representation of the Histogram. It is a -// deep copy (e.g. spans are not shared). -func (h *Histogram) ToFloat() *FloatHistogram { - var ( - positiveSpans, negativeSpans []Span - positiveBuckets, negativeBuckets []float64 - ) - if len(h.PositiveSpans) != 0 { - positiveSpans = make([]Span, len(h.PositiveSpans)) - copy(positiveSpans, h.PositiveSpans) +// ToFloat returns a FloatHistogram representation of the Histogram. It is a deep +// copy (e.g. spans are not shared). The function accepts a FloatHistogram as an +// argument whose memory will be reused and overwritten if provided. If this +// argument is nil, a new FloatHistogram will be allocated. +func (h *Histogram) ToFloat(fh *FloatHistogram) *FloatHistogram { + if fh == nil { + fh = &FloatHistogram{} } - if len(h.NegativeSpans) != 0 { - negativeSpans = make([]Span, len(h.NegativeSpans)) - copy(negativeSpans, h.NegativeSpans) + fh.CounterResetHint = h.CounterResetHint + fh.Schema = h.Schema + fh.ZeroThreshold = h.ZeroThreshold + fh.ZeroCount = float64(h.ZeroCount) + fh.Count = float64(h.Count) + fh.Sum = h.Sum + + fh.PositiveSpans = resize(fh.PositiveSpans, len(h.PositiveSpans)) + copy(fh.PositiveSpans, h.PositiveSpans) + + fh.NegativeSpans = resize(fh.NegativeSpans, len(h.NegativeSpans)) + copy(fh.NegativeSpans, h.NegativeSpans) + + fh.PositiveBuckets = resize(fh.PositiveBuckets, len(h.PositiveBuckets)) + var currentPositive float64 + for i, b := range h.PositiveBuckets { + currentPositive += float64(b) + fh.PositiveBuckets[i] = currentPositive } - if len(h.PositiveBuckets) != 0 { - positiveBuckets = make([]float64, len(h.PositiveBuckets)) - var current float64 - for i, b := range h.PositiveBuckets { - current += float64(b) - positiveBuckets[i] = current - } + + fh.NegativeBuckets = resize(fh.NegativeBuckets, len(h.NegativeBuckets)) + var currentNegative float64 + for i, b := range h.NegativeBuckets { + currentNegative += float64(b) + fh.NegativeBuckets[i] = currentNegative } - if len(h.NegativeBuckets) != 0 { - negativeBuckets = make([]float64, len(h.NegativeBuckets)) - var current float64 - for i, b := range h.NegativeBuckets { - current += float64(b) - negativeBuckets[i] = current - } + + return fh +} + +func resize[T any](items []T, n int) []T { + if cap(items) < n { + return make([]T, n) } + return items[:n] +} - return &FloatHistogram{ - CounterResetHint: h.CounterResetHint, - Schema: h.Schema, - ZeroThreshold: h.ZeroThreshold, - ZeroCount: float64(h.ZeroCount), - Count: float64(h.Count), - Sum: h.Sum, - PositiveSpans: positiveSpans, - NegativeSpans: negativeSpans, - PositiveBuckets: positiveBuckets, - NegativeBuckets: negativeBuckets, +// Validate validates consistency between span and bucket slices. Also, buckets are checked +// against negative values. +// For histograms that have not observed any NaN values (based on IsNaN(h.Sum) check), a +// strict h.Count = nCount + pCount + h.ZeroCount check is performed. +// Otherwise, only a lower bound check will be done (h.Count >= nCount + pCount + h.ZeroCount), +// because NaN observations do not increment the values of buckets (but they do increment +// the total h.Count). +func (h *Histogram) Validate() error { + if err := checkHistogramSpans(h.NegativeSpans, len(h.NegativeBuckets)); err != nil { + return fmt.Errorf("negative side: %w", err) + } + if err := checkHistogramSpans(h.PositiveSpans, len(h.PositiveBuckets)); err != nil { + return fmt.Errorf("positive side: %w", err) + } + var nCount, pCount uint64 + err := checkHistogramBuckets(h.NegativeBuckets, &nCount, true) + if err != nil { + return fmt.Errorf("negative side: %w", err) + } + err = checkHistogramBuckets(h.PositiveBuckets, &pCount, true) + if err != nil { + return fmt.Errorf("positive side: %w", err) + } + + sumOfBuckets := nCount + pCount + h.ZeroCount + if math.IsNaN(h.Sum) { + if sumOfBuckets > h.Count { + return fmt.Errorf("%d observations found in buckets, but the Count field is %d: %w", sumOfBuckets, h.Count, ErrHistogramCountNotBigEnough) + } + } else { + if sumOfBuckets != h.Count { + return fmt.Errorf("%d observations found in buckets, but the Count field is %d: %w", sumOfBuckets, h.Count, ErrHistogramCountMismatch) + } } + + return nil } type regularBucketIterator struct { baseBucketIterator[uint64, int64] } -func newRegularBucketIterator(spans []Span, buckets []int64, schema int32, positive bool) *regularBucketIterator { +func newRegularBucketIterator(spans []Span, buckets []int64, schema int32, positive bool) regularBucketIterator { i := baseBucketIterator[uint64, int64]{ schema: schema, spans: spans, buckets: buckets, positive: positive, } - return ®ularBucketIterator{i} + return regularBucketIterator{i} } func (r *regularBucketIterator) Next() bool { @@ -448,3 +522,20 @@ func (c *cumulativeBucketIterator) At() Bucket[uint64] { Index: c.currIdx - 1, } } + +// ReduceResolution reduces the histogram's spans, buckets into target schema. +// The target schema must be smaller than the current histogram's schema. +func (h *Histogram) ReduceResolution(targetSchema int32) *Histogram { + if targetSchema >= h.Schema { + panic(fmt.Errorf("cannot reduce resolution from schema %d to %d", h.Schema, targetSchema)) + } + + h.PositiveSpans, h.PositiveBuckets = reduceResolution( + h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, true, true, + ) + h.NegativeSpans, h.NegativeBuckets = reduceResolution( + h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, true, true, + ) + h.Schema = targetSchema + return h +} diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/test_utils.go b/vendor/github.com/prometheus/prometheus/model/histogram/test_utils.go new file mode 100644 index 000000000..9e9a711c2 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/model/histogram/test_utils.go @@ -0,0 +1,52 @@ +// Copyright 2023 The Prometheus 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 histogram + +// GenerateBigTestHistograms generates a slice of histograms with given number of buckets each. +func GenerateBigTestHistograms(numHistograms, numBuckets int) []*Histogram { + numSpans := numBuckets / 10 + bucketsPerSide := numBuckets / 2 + spanLength := uint32(bucketsPerSide / numSpans) + // Given all bucket deltas are 1, sum bucketsPerSide + 1. + observationCount := bucketsPerSide * (1 + bucketsPerSide) + + var histograms []*Histogram + for i := 0; i < numHistograms; i++ { + h := &Histogram{ + Count: uint64(i + observationCount), + ZeroCount: uint64(i), + ZeroThreshold: 1e-128, + Sum: 18.4 * float64(i+1), + Schema: 2, + NegativeSpans: make([]Span, numSpans), + PositiveSpans: make([]Span, numSpans), + NegativeBuckets: make([]int64, bucketsPerSide), + PositiveBuckets: make([]int64, bucketsPerSide), + } + + for j := 0; j < numSpans; j++ { + s := Span{Offset: 1, Length: spanLength} + h.NegativeSpans[j] = s + h.PositiveSpans[j] = s + } + + for j := 0; j < bucketsPerSide; j++ { + h.NegativeBuckets[j] = 1 + h.PositiveBuckets[j] = 1 + } + + histograms = append(histograms, h) + } + return histograms +} diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels.go b/vendor/github.com/prometheus/prometheus/model/labels/labels.go index 9ac0e5b53..b6663dad2 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/labels.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/labels.go @@ -17,31 +17,12 @@ package labels import ( "bytes" - "encoding/json" - "strconv" + "strings" "github.com/cespare/xxhash/v2" - "github.com/prometheus/common/model" "golang.org/x/exp/slices" ) -// Well-known label names used by Prometheus components. -const ( - MetricName = "__name__" - AlertName = "alertname" - BucketLabel = "le" - InstanceName = "instance" - - labelSep = '\xfe' -) - -var seps = []byte{'\xff'} - -// Label is a key/value pair of strings. -type Label struct { - Name, Value string -} - // Labels is a sorted set of labels. Order has to be guaranteed upon // instantiation. type Labels []Label @@ -50,23 +31,6 @@ func (ls Labels) Len() int { return len(ls) } func (ls Labels) Swap(i, j int) { ls[i], ls[j] = ls[j], ls[i] } func (ls Labels) Less(i, j int) bool { return ls[i].Name < ls[j].Name } -func (ls Labels) String() string { - var b bytes.Buffer - - b.WriteByte('{') - for i, l := range ls { - if i > 0 { - b.WriteByte(',') - b.WriteByte(' ') - } - b.WriteString(l.Name) - b.WriteByte('=') - b.WriteString(strconv.Quote(l.Value)) - } - b.WriteByte('}') - return b.String() -} - // Bytes returns ls as a byte slice. // It uses an byte invalid character as a separator and so should not be used for printing. func (ls Labels) Bytes(buf []byte) []byte { @@ -83,40 +47,6 @@ func (ls Labels) Bytes(buf []byte) []byte { return b.Bytes() } -// MarshalJSON implements json.Marshaler. -func (ls Labels) MarshalJSON() ([]byte, error) { - return json.Marshal(ls.Map()) -} - -// UnmarshalJSON implements json.Unmarshaler. -func (ls *Labels) UnmarshalJSON(b []byte) error { - var m map[string]string - - if err := json.Unmarshal(b, &m); err != nil { - return err - } - - *ls = FromMap(m) - return nil -} - -// MarshalYAML implements yaml.Marshaler. -func (ls Labels) MarshalYAML() (interface{}, error) { - return ls.Map(), nil -} - -// UnmarshalYAML implements yaml.Unmarshaler. -func (ls *Labels) UnmarshalYAML(unmarshal func(interface{}) error) error { - var m map[string]string - - if err := unmarshal(&m); err != nil { - return err - } - - *ls = FromMap(m) - return nil -} - // MatchLabels returns a subset of Labels that matches/does not match with the provided label names based on the 'on' boolean. // If on is set to true, it returns the subset of labels that match with the provided label names and its inverse when 'on' is set to false. func (ls Labels) MatchLabels(on bool, names ...string) Labels { @@ -317,19 +247,6 @@ func (ls Labels) WithoutEmpty() Labels { return ls } -// IsValid checks if the metric name or label names are valid. -func (ls Labels) IsValid() bool { - for _, l := range ls { - if l.Name == model.MetricNameLabel && !model.IsValidMetricName(model.LabelValue(l.Value)) { - return false - } - if !model.LabelName(l.Name).IsValid() || !model.LabelValue(l.Value).IsValid() { - return false - } - } - return true -} - // Equal returns whether the two label sets are equal. func Equal(ls, o Labels) bool { if len(ls) != len(o) { @@ -343,15 +260,6 @@ func Equal(ls, o Labels) bool { return true } -// Map returns a string map of the labels. -func (ls Labels) Map() map[string]string { - m := make(map[string]string, len(ls)) - for _, l := range ls { - m[l.Name] = l.Value - } - return m -} - // EmptyLabels returns n empty Labels value, for convenience. func EmptyLabels() Labels { return Labels{} @@ -362,20 +270,11 @@ func EmptyLabels() Labels { func New(ls ...Label) Labels { set := make(Labels, 0, len(ls)) set = append(set, ls...) - slices.SortFunc(set, func(a, b Label) bool { return a.Name < b.Name }) + slices.SortFunc(set, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) return set } -// FromMap returns new sorted Labels from the given map. -func FromMap(m map[string]string) Labels { - l := make([]Label, 0, len(m)) - for k, v := range m { - l = append(l, Label{Name: k, Value: v}) - } - return New(l...) -} - // FromStrings creates new labels from pairs of strings. func FromStrings(ss ...string) Labels { if len(ss)%2 != 0 { @@ -386,7 +285,7 @@ func FromStrings(ss ...string) Labels { res = append(res, Label{Name: ss[i], Value: ss[i+1]}) } - slices.SortFunc(res, func(a, b Label) bool { return a.Name < b.Name }) + slices.SortFunc(res, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) return res } @@ -443,6 +342,19 @@ func (ls Labels) Validate(f func(l Label) error) error { return nil } +// DropMetricName returns Labels with "__name__" removed. +func (ls Labels) DropMetricName() Labels { + for i, l := range ls { + if l.Name == MetricName { + if i == 0 { // Make common case fast with no allocations. + return ls[1:] + } + return append(ls[:i], ls[i+1:]...) + } + } + return ls +} + // InternStrings calls intern on every string value inside ls, replacing them with what it returns. func (ls *Labels) InternStrings(intern func(string) string) { for i, l := range *ls { @@ -459,118 +371,6 @@ func (ls Labels) ReleaseStrings(release func(string)) { } } -// Builder allows modifying Labels. -type Builder struct { - base Labels - del []string - add []Label -} - -// NewBuilder returns a new LabelsBuilder. -func NewBuilder(base Labels) *Builder { - b := &Builder{ - del: make([]string, 0, 5), - add: make([]Label, 0, 5), - } - b.Reset(base) - return b -} - -// Reset clears all current state for the builder. -func (b *Builder) Reset(base Labels) { - b.base = base - b.del = b.del[:0] - b.add = b.add[:0] - for _, l := range b.base { - if l.Value == "" { - b.del = append(b.del, l.Name) - } - } -} - -// Del deletes the label of the given name. -func (b *Builder) Del(ns ...string) *Builder { - for _, n := range ns { - for i, a := range b.add { - if a.Name == n { - b.add = append(b.add[:i], b.add[i+1:]...) - } - } - b.del = append(b.del, n) - } - return b -} - -// Keep removes all labels from the base except those with the given names. -func (b *Builder) Keep(ns ...string) *Builder { -Outer: - for _, l := range b.base { - for _, n := range ns { - if l.Name == n { - continue Outer - } - } - b.del = append(b.del, l.Name) - } - return b -} - -// Set the name/value pair as a label. A value of "" means delete that label. -func (b *Builder) Set(n, v string) *Builder { - if v == "" { - // Empty labels are the same as missing labels. - return b.Del(n) - } - for i, a := range b.add { - if a.Name == n { - b.add[i].Value = v - return b - } - } - b.add = append(b.add, Label{Name: n, Value: v}) - - return b -} - -func (b *Builder) Get(n string) string { - // Del() removes entries from .add but Set() does not remove from .del, so check .add first. - for _, a := range b.add { - if a.Name == n { - return a.Value - } - } - if slices.Contains(b.del, n) { - return "" - } - return b.base.Get(n) -} - -// Range calls f on each label in the Builder. -func (b *Builder) Range(f func(l Label)) { - // Stack-based arrays to avoid heap allocation in most cases. - var addStack [128]Label - var delStack [128]string - // Take a copy of add and del, so they are unaffected by calls to Set() or Del(). - origAdd, origDel := append(addStack[:0], b.add...), append(delStack[:0], b.del...) - b.base.Range(func(l Label) { - if !slices.Contains(origDel, l.Name) && !contains(origAdd, l.Name) { - f(l) - } - }) - for _, a := range origAdd { - f(a) - } -} - -func contains(s []Label, n string) bool { - for _, a := range s { - if a.Name == n { - return true - } - } - return false -} - // Labels returns the labels from the builder. // If no modifications were made, the original labels are returned. func (b *Builder) Labels() Labels { @@ -591,7 +391,7 @@ func (b *Builder) Labels() Labels { } if len(b.add) > 0 { // Base is already in order, so we only need to sort if we add to it. res = append(res, b.add...) - slices.SortFunc(res, func(a, b Label) bool { return a.Name < b.Name }) + slices.SortFunc(res, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) } return res } @@ -616,12 +416,19 @@ func (b *ScratchBuilder) Add(name, value string) { b.add = append(b.add, Label{Name: name, Value: value}) } +// Add a name/value pair, using []byte instead of string. +// The '-tags stringlabels' version of this function is unsafe, hence the name. +// This version is safe - it copies the strings immediately - but we keep the same name so everything compiles. +func (b *ScratchBuilder) UnsafeAddBytes(name, value []byte) { + b.add = append(b.add, Label{Name: string(name), Value: string(value)}) +} + // Sort the labels added so far by name. func (b *ScratchBuilder) Sort() { - slices.SortFunc(b.add, func(a, b Label) bool { return a.Name < b.Name }) + slices.SortFunc(b.add, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) } -// Asssign is for when you already have a Labels which you want this ScratchBuilder to return. +// Assign is for when you already have a Labels which you want this ScratchBuilder to return. func (b *ScratchBuilder) Assign(ls Labels) { b.add = append(b.add[:0], ls...) // Copy on top of our slice, so we don't retain the input slice. } diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels_common.go b/vendor/github.com/prometheus/prometheus/model/labels/labels_common.go new file mode 100644 index 000000000..2a722b84c --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/model/labels/labels_common.go @@ -0,0 +1,235 @@ +// Copyright 2017 The Prometheus 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 labels + +import ( + "bytes" + "encoding/json" + "strconv" + + "github.com/prometheus/common/model" + "golang.org/x/exp/slices" +) + +const ( + MetricName = "__name__" + AlertName = "alertname" + BucketLabel = "le" + InstanceName = "instance" + + labelSep = '\xfe' +) + +var seps = []byte{'\xff'} + +// Label is a key/value pair of strings. +type Label struct { + Name, Value string +} + +func (ls Labels) String() string { + var b bytes.Buffer + + b.WriteByte('{') + i := 0 + ls.Range(func(l Label) { + if i > 0 { + b.WriteByte(',') + b.WriteByte(' ') + } + b.WriteString(l.Name) + b.WriteByte('=') + b.WriteString(strconv.Quote(l.Value)) + i++ + }) + b.WriteByte('}') + return b.String() +} + +// MarshalJSON implements json.Marshaler. +func (ls Labels) MarshalJSON() ([]byte, error) { + return json.Marshal(ls.Map()) +} + +// UnmarshalJSON implements json.Unmarshaler. +func (ls *Labels) UnmarshalJSON(b []byte) error { + var m map[string]string + + if err := json.Unmarshal(b, &m); err != nil { + return err + } + + *ls = FromMap(m) + return nil +} + +// MarshalYAML implements yaml.Marshaler. +func (ls Labels) MarshalYAML() (interface{}, error) { + return ls.Map(), nil +} + +// UnmarshalYAML implements yaml.Unmarshaler. +func (ls *Labels) UnmarshalYAML(unmarshal func(interface{}) error) error { + var m map[string]string + + if err := unmarshal(&m); err != nil { + return err + } + + *ls = FromMap(m) + return nil +} + +// IsValid checks if the metric name or label names are valid. +func (ls Labels) IsValid() bool { + err := ls.Validate(func(l Label) error { + if l.Name == model.MetricNameLabel && !model.IsValidMetricName(model.LabelValue(l.Value)) { + return strconv.ErrSyntax + } + if !model.LabelName(l.Name).IsValid() || !model.LabelValue(l.Value).IsValid() { + return strconv.ErrSyntax + } + return nil + }) + return err == nil +} + +// Map returns a string map of the labels. +func (ls Labels) Map() map[string]string { + m := make(map[string]string) + ls.Range(func(l Label) { + m[l.Name] = l.Value + }) + return m +} + +// FromMap returns new sorted Labels from the given map. +func FromMap(m map[string]string) Labels { + l := make([]Label, 0, len(m)) + for k, v := range m { + l = append(l, Label{Name: k, Value: v}) + } + return New(l...) +} + +// Builder allows modifying Labels. +type Builder struct { + base Labels + del []string + add []Label +} + +// NewBuilder returns a new LabelsBuilder. +func NewBuilder(base Labels) *Builder { + b := &Builder{ + del: make([]string, 0, 5), + add: make([]Label, 0, 5), + } + b.Reset(base) + return b +} + +// Reset clears all current state for the builder. +func (b *Builder) Reset(base Labels) { + b.base = base + b.del = b.del[:0] + b.add = b.add[:0] + b.base.Range(func(l Label) { + if l.Value == "" { + b.del = append(b.del, l.Name) + } + }) +} + +// Del deletes the label of the given name. +func (b *Builder) Del(ns ...string) *Builder { + for _, n := range ns { + for i, a := range b.add { + if a.Name == n { + b.add = append(b.add[:i], b.add[i+1:]...) + } + } + b.del = append(b.del, n) + } + return b +} + +// Keep removes all labels from the base except those with the given names. +func (b *Builder) Keep(ns ...string) *Builder { + b.base.Range(func(l Label) { + for _, n := range ns { + if l.Name == n { + return + } + } + b.del = append(b.del, l.Name) + }) + return b +} + +// Set the name/value pair as a label. A value of "" means delete that label. +func (b *Builder) Set(n, v string) *Builder { + if v == "" { + // Empty labels are the same as missing labels. + return b.Del(n) + } + for i, a := range b.add { + if a.Name == n { + b.add[i].Value = v + return b + } + } + b.add = append(b.add, Label{Name: n, Value: v}) + + return b +} + +func (b *Builder) Get(n string) string { + // Del() removes entries from .add but Set() does not remove from .del, so check .add first. + for _, a := range b.add { + if a.Name == n { + return a.Value + } + } + if slices.Contains(b.del, n) { + return "" + } + return b.base.Get(n) +} + +// Range calls f on each label in the Builder. +func (b *Builder) Range(f func(l Label)) { + // Stack-based arrays to avoid heap allocation in most cases. + var addStack [128]Label + var delStack [128]string + // Take a copy of add and del, so they are unaffected by calls to Set() or Del(). + origAdd, origDel := append(addStack[:0], b.add...), append(delStack[:0], b.del...) + b.base.Range(func(l Label) { + if !slices.Contains(origDel, l.Name) && !contains(origAdd, l.Name) { + f(l) + } + }) + for _, a := range origAdd { + f(a) + } +} + +func contains(s []Label, n string) bool { + for _, a := range s { + if a.Name == n { + return true + } + } + return false +} diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels_string.go b/vendor/github.com/prometheus/prometheus/model/labels/labels_string.go deleted file mode 100644 index 6d54e98ab..000000000 --- a/vendor/github.com/prometheus/prometheus/model/labels/labels_string.go +++ /dev/null @@ -1,831 +0,0 @@ -// Copyright 2017 The Prometheus 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. - -//go:build stringlabels - -package labels - -import ( - "bytes" - "encoding/json" - "reflect" - "strconv" - "unsafe" - - "github.com/cespare/xxhash/v2" - "github.com/prometheus/common/model" - "golang.org/x/exp/slices" -) - -// Well-known label names used by Prometheus components. -const ( - MetricName = "__name__" - AlertName = "alertname" - BucketLabel = "le" - InstanceName = "instance" -) - -var seps = []byte{'\xff'} - -// Label is a key/value pair of strings. -type Label struct { - Name, Value string -} - -// Labels is implemented by a single flat string holding name/value pairs. -// Each name and value is preceded by its length in varint encoding. -// Names are in order. -type Labels struct { - data string -} - -type labelSlice []Label - -func (ls labelSlice) Len() int { return len(ls) } -func (ls labelSlice) Swap(i, j int) { ls[i], ls[j] = ls[j], ls[i] } -func (ls labelSlice) Less(i, j int) bool { return ls[i].Name < ls[j].Name } - -func decodeSize(data string, index int) (int, int) { - // Fast-path for common case of a single byte, value 0..127. - b := data[index] - index++ - if b < 0x80 { - return int(b), index - } - size := int(b & 0x7F) - for shift := uint(7); ; shift += 7 { - // Just panic if we go of the end of data, since all Labels strings are constructed internally and - // malformed data indicates a bug, or memory corruption. - b := data[index] - index++ - size |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - return size, index -} - -func decodeString(data string, index int) (string, int) { - var size int - size, index = decodeSize(data, index) - return data[index : index+size], index + size -} - -func (ls Labels) String() string { - var b bytes.Buffer - - b.WriteByte('{') - for i := 0; i < len(ls.data); { - if i > 0 { - b.WriteByte(',') - b.WriteByte(' ') - } - var name, value string - name, i = decodeString(ls.data, i) - value, i = decodeString(ls.data, i) - b.WriteString(name) - b.WriteByte('=') - b.WriteString(strconv.Quote(value)) - } - b.WriteByte('}') - return b.String() -} - -// Bytes returns ls as a byte slice. -// It uses non-printing characters and so should not be used for printing. -func (ls Labels) Bytes(buf []byte) []byte { - if cap(buf) < len(ls.data) { - buf = make([]byte, len(ls.data)) - } else { - buf = buf[:len(ls.data)] - } - copy(buf, ls.data) - return buf -} - -// MarshalJSON implements json.Marshaler. -func (ls Labels) MarshalJSON() ([]byte, error) { - return json.Marshal(ls.Map()) -} - -// UnmarshalJSON implements json.Unmarshaler. -func (ls *Labels) UnmarshalJSON(b []byte) error { - var m map[string]string - - if err := json.Unmarshal(b, &m); err != nil { - return err - } - - *ls = FromMap(m) - return nil -} - -// MarshalYAML implements yaml.Marshaler. -func (ls Labels) MarshalYAML() (interface{}, error) { - return ls.Map(), nil -} - -// IsZero implements yaml.IsZeroer - if we don't have this then 'omitempty' fields are always omitted. -func (ls Labels) IsZero() bool { - return len(ls.data) == 0 -} - -// UnmarshalYAML implements yaml.Unmarshaler. -func (ls *Labels) UnmarshalYAML(unmarshal func(interface{}) error) error { - var m map[string]string - - if err := unmarshal(&m); err != nil { - return err - } - - *ls = FromMap(m) - return nil -} - -// MatchLabels returns a subset of Labels that matches/does not match with the provided label names based on the 'on' boolean. -// If on is set to true, it returns the subset of labels that match with the provided label names and its inverse when 'on' is set to false. -// TODO: This is only used in printing an error message -func (ls Labels) MatchLabels(on bool, names ...string) Labels { - b := NewBuilder(ls) - if on { - b.Keep(names...) - } else { - b.Del(MetricName) - b.Del(names...) - } - return b.Labels() -} - -// Hash returns a hash value for the label set. -// Note: the result is not guaranteed to be consistent across different runs of Prometheus. -func (ls Labels) Hash() uint64 { - return xxhash.Sum64(yoloBytes(ls.data)) -} - -// HashForLabels returns a hash value for the labels matching the provided names. -// 'names' have to be sorted in ascending order. -func (ls Labels) HashForLabels(b []byte, names ...string) (uint64, []byte) { - b = b[:0] - j := 0 - for i := 0; i < len(ls.data); { - var name, value string - name, i = decodeString(ls.data, i) - value, i = decodeString(ls.data, i) - for j < len(names) && names[j] < name { - j++ - } - if j == len(names) { - break - } - if name == names[j] { - b = append(b, name...) - b = append(b, seps[0]) - b = append(b, value...) - b = append(b, seps[0]) - } - } - - return xxhash.Sum64(b), b -} - -// HashWithoutLabels returns a hash value for all labels except those matching -// the provided names. -// 'names' have to be sorted in ascending order. -func (ls Labels) HashWithoutLabels(b []byte, names ...string) (uint64, []byte) { - b = b[:0] - j := 0 - for i := 0; i < len(ls.data); { - var name, value string - name, i = decodeString(ls.data, i) - value, i = decodeString(ls.data, i) - for j < len(names) && names[j] < name { - j++ - } - if name == MetricName || (j < len(names) && name == names[j]) { - continue - } - b = append(b, name...) - b = append(b, seps[0]) - b = append(b, value...) - b = append(b, seps[0]) - } - return xxhash.Sum64(b), b -} - -// BytesWithLabels is just as Bytes(), but only for labels matching names. -// 'names' have to be sorted in ascending order. -func (ls Labels) BytesWithLabels(buf []byte, names ...string) []byte { - b := buf[:0] - j := 0 - for pos := 0; pos < len(ls.data); { - lName, newPos := decodeString(ls.data, pos) - _, newPos = decodeString(ls.data, newPos) - for j < len(names) && names[j] < lName { - j++ - } - if j == len(names) { - break - } - if lName == names[j] { - b = append(b, ls.data[pos:newPos]...) - } - pos = newPos - } - return b -} - -// BytesWithoutLabels is just as Bytes(), but only for labels not matching names. -// 'names' have to be sorted in ascending order. -func (ls Labels) BytesWithoutLabels(buf []byte, names ...string) []byte { - b := buf[:0] - j := 0 - for pos := 0; pos < len(ls.data); { - lName, newPos := decodeString(ls.data, pos) - _, newPos = decodeString(ls.data, newPos) - for j < len(names) && names[j] < lName { - j++ - } - if j == len(names) || lName != names[j] { - b = append(b, ls.data[pos:newPos]...) - } - pos = newPos - } - return b -} - -// Copy returns a copy of the labels. -func (ls Labels) Copy() Labels { - buf := append([]byte{}, ls.data...) - return Labels{data: yoloString(buf)} -} - -// Get returns the value for the label with the given name. -// Returns an empty string if the label doesn't exist. -func (ls Labels) Get(name string) string { - for i := 0; i < len(ls.data); { - var lName, lValue string - lName, i = decodeString(ls.data, i) - lValue, i = decodeString(ls.data, i) - if lName == name { - return lValue - } - } - return "" -} - -// Has returns true if the label with the given name is present. -func (ls Labels) Has(name string) bool { - for i := 0; i < len(ls.data); { - var lName string - lName, i = decodeString(ls.data, i) - _, i = decodeString(ls.data, i) - if lName == name { - return true - } - } - return false -} - -// HasDuplicateLabelNames returns whether ls has duplicate label names. -// It assumes that the labelset is sorted. -func (ls Labels) HasDuplicateLabelNames() (string, bool) { - var lName, prevName string - for i := 0; i < len(ls.data); { - lName, i = decodeString(ls.data, i) - _, i = decodeString(ls.data, i) - if lName == prevName { - return lName, true - } - prevName = lName - } - return "", false -} - -// WithoutEmpty returns the labelset without empty labels. -// May return the same labelset. -func (ls Labels) WithoutEmpty() Labels { - for pos := 0; pos < len(ls.data); { - _, newPos := decodeString(ls.data, pos) - lValue, newPos := decodeString(ls.data, newPos) - if lValue != "" { - pos = newPos - continue - } - // Do not copy the slice until it's necessary. - // TODO: could optimise the case where all blanks are at the end. - // Note: we size the new buffer on the assumption there is exactly one blank value. - buf := make([]byte, pos, pos+(len(ls.data)-newPos)) - copy(buf, ls.data[:pos]) // copy the initial non-blank labels - pos = newPos // move past the first blank value - for pos < len(ls.data) { - var newPos int - _, newPos = decodeString(ls.data, pos) - lValue, newPos = decodeString(ls.data, newPos) - if lValue != "" { - buf = append(buf, ls.data[pos:newPos]...) - } - pos = newPos - } - return Labels{data: yoloString(buf)} - } - return ls -} - -// IsValid checks if the metric name or label names are valid. -func (ls Labels) IsValid() bool { - err := ls.Validate(func(l Label) error { - if l.Name == model.MetricNameLabel && !model.IsValidMetricName(model.LabelValue(l.Value)) { - return strconv.ErrSyntax - } - if !model.LabelName(l.Name).IsValid() || !model.LabelValue(l.Value).IsValid() { - return strconv.ErrSyntax - } - return nil - }) - return err == nil -} - -// Equal returns whether the two label sets are equal. -func Equal(ls, o Labels) bool { - return ls.data == o.data -} - -// Map returns a string map of the labels. -func (ls Labels) Map() map[string]string { - m := make(map[string]string, len(ls.data)/10) - for i := 0; i < len(ls.data); { - var lName, lValue string - lName, i = decodeString(ls.data, i) - lValue, i = decodeString(ls.data, i) - m[lName] = lValue - } - return m -} - -// EmptyLabels returns an empty Labels value, for convenience. -func EmptyLabels() Labels { - return Labels{} -} - -func yoloString(b []byte) string { - return *((*string)(unsafe.Pointer(&b))) -} - -func yoloBytes(s string) (b []byte) { - *(*string)(unsafe.Pointer(&b)) = s - (*reflect.SliceHeader)(unsafe.Pointer(&b)).Cap = len(s) - return -} - -// New returns a sorted Labels from the given labels. -// The caller has to guarantee that all label names are unique. -func New(ls ...Label) Labels { - slices.SortFunc(ls, func(a, b Label) bool { return a.Name < b.Name }) - size := labelsSize(ls) - buf := make([]byte, size) - marshalLabelsToSizedBuffer(ls, buf) - return Labels{data: yoloString(buf)} -} - -// FromMap returns new sorted Labels from the given map. -func FromMap(m map[string]string) Labels { - l := make([]Label, 0, len(m)) - for k, v := range m { - l = append(l, Label{Name: k, Value: v}) - } - return New(l...) -} - -// FromStrings creates new labels from pairs of strings. -func FromStrings(ss ...string) Labels { - if len(ss)%2 != 0 { - panic("invalid number of strings") - } - ls := make([]Label, 0, len(ss)/2) - for i := 0; i < len(ss); i += 2 { - ls = append(ls, Label{Name: ss[i], Value: ss[i+1]}) - } - - return New(ls...) -} - -// Compare compares the two label sets. -// The result will be 0 if a==b, <0 if a < b, and >0 if a > b. -// TODO: replace with Less function - Compare is never needed. -// TODO: just compare the underlying strings when we don't need alphanumeric sorting. -func Compare(a, b Labels) int { - l := len(a.data) - if len(b.data) < l { - l = len(b.data) - } - - ia, ib := 0, 0 - for ia < l { - var aName, bName string - aName, ia = decodeString(a.data, ia) - bName, ib = decodeString(b.data, ib) - if aName != bName { - if aName < bName { - return -1 - } - return 1 - } - var aValue, bValue string - aValue, ia = decodeString(a.data, ia) - bValue, ib = decodeString(b.data, ib) - if aValue != bValue { - if aValue < bValue { - return -1 - } - return 1 - } - } - // If all labels so far were in common, the set with fewer labels comes first. - return len(a.data) - len(b.data) -} - -// Copy labels from b on top of whatever was in ls previously, reusing memory or expanding if needed. -func (ls *Labels) CopyFrom(b Labels) { - ls.data = b.data // strings are immutable -} - -// IsEmpty returns true if ls represents an empty set of labels. -func (ls Labels) IsEmpty() bool { - return len(ls.data) == 0 -} - -// Len returns the number of labels; it is relatively slow. -func (ls Labels) Len() int { - count := 0 - for i := 0; i < len(ls.data); { - var size int - size, i = decodeSize(ls.data, i) - i += size - size, i = decodeSize(ls.data, i) - i += size - count++ - } - return count -} - -// Range calls f on each label. -func (ls Labels) Range(f func(l Label)) { - for i := 0; i < len(ls.data); { - var lName, lValue string - lName, i = decodeString(ls.data, i) - lValue, i = decodeString(ls.data, i) - f(Label{Name: lName, Value: lValue}) - } -} - -// Validate calls f on each label. If f returns a non-nil error, then it returns that error cancelling the iteration. -func (ls Labels) Validate(f func(l Label) error) error { - for i := 0; i < len(ls.data); { - var lName, lValue string - lName, i = decodeString(ls.data, i) - lValue, i = decodeString(ls.data, i) - err := f(Label{Name: lName, Value: lValue}) - if err != nil { - return err - } - } - return nil -} - -// InternStrings calls intern on every string value inside ls, replacing them with what it returns. -func (ls *Labels) InternStrings(intern func(string) string) { - ls.data = intern(ls.data) -} - -// ReleaseStrings calls release on every string value inside ls. -func (ls Labels) ReleaseStrings(release func(string)) { - release(ls.data) -} - -// Builder allows modifying Labels. -type Builder struct { - base Labels - del []string - add []Label -} - -// NewBuilder returns a new LabelsBuilder. -func NewBuilder(base Labels) *Builder { - b := &Builder{ - del: make([]string, 0, 5), - add: make([]Label, 0, 5), - } - b.Reset(base) - return b -} - -// Reset clears all current state for the builder. -func (b *Builder) Reset(base Labels) { - b.base = base - b.del = b.del[:0] - b.add = b.add[:0] - for i := 0; i < len(base.data); { - var lName, lValue string - lName, i = decodeString(base.data, i) - lValue, i = decodeString(base.data, i) - if lValue == "" { - b.del = append(b.del, lName) - } - } -} - -// Del deletes the label of the given name. -func (b *Builder) Del(ns ...string) *Builder { - for _, n := range ns { - for i, a := range b.add { - if a.Name == n { - b.add = append(b.add[:i], b.add[i+1:]...) - } - } - b.del = append(b.del, n) - } - return b -} - -// Keep removes all labels from the base except those with the given names. -func (b *Builder) Keep(ns ...string) *Builder { -Outer: - for i := 0; i < len(b.base.data); { - var lName string - lName, i = decodeString(b.base.data, i) - _, i = decodeString(b.base.data, i) - for _, n := range ns { - if lName == n { - continue Outer - } - } - b.del = append(b.del, lName) - } - return b -} - -// Set the name/value pair as a label. A value of "" means delete that label. -func (b *Builder) Set(n, v string) *Builder { - if v == "" { - // Empty labels are the same as missing labels. - return b.Del(n) - } - for i, a := range b.add { - if a.Name == n { - b.add[i].Value = v - return b - } - } - b.add = append(b.add, Label{Name: n, Value: v}) - - return b -} - -func (b *Builder) Get(n string) string { - // Del() removes entries from .add but Set() does not remove from .del, so check .add first. - for _, a := range b.add { - if a.Name == n { - return a.Value - } - } - if slices.Contains(b.del, n) { - return "" - } - return b.base.Get(n) -} - -// Range calls f on each label in the Builder. -func (b *Builder) Range(f func(l Label)) { - // Stack-based arrays to avoid heap allocation in most cases. - var addStack [128]Label - var delStack [128]string - // Take a copy of add and del, so they are unaffected by calls to Set() or Del(). - origAdd, origDel := append(addStack[:0], b.add...), append(delStack[:0], b.del...) - b.base.Range(func(l Label) { - if !slices.Contains(origDel, l.Name) && !contains(origAdd, l.Name) { - f(l) - } - }) - for _, a := range origAdd { - f(a) - } -} - -func contains(s []Label, n string) bool { - for _, a := range s { - if a.Name == n { - return true - } - } - return false -} - -// Labels returns the labels from the builder. -// If no modifications were made, the original labels are returned. -func (b *Builder) Labels() Labels { - if len(b.del) == 0 && len(b.add) == 0 { - return b.base - } - - slices.SortFunc(b.add, func(a, b Label) bool { return a.Name < b.Name }) - slices.Sort(b.del) - a, d := 0, 0 - - bufSize := len(b.base.data) + labelsSize(b.add) - buf := make([]byte, 0, bufSize) - for pos := 0; pos < len(b.base.data); { - oldPos := pos - var lName string - lName, pos = decodeString(b.base.data, pos) - _, pos = decodeString(b.base.data, pos) - for d < len(b.del) && b.del[d] < lName { - d++ - } - if d < len(b.del) && b.del[d] == lName { - continue // This label has been deleted. - } - for ; a < len(b.add) && b.add[a].Name < lName; a++ { - buf = appendLabelTo(buf, &b.add[a]) // Insert label that was not in the base set. - } - if a < len(b.add) && b.add[a].Name == lName { - buf = appendLabelTo(buf, &b.add[a]) - a++ - continue // This label has been replaced. - } - buf = append(buf, b.base.data[oldPos:pos]...) - } - // We have come to the end of the base set; add any remaining labels. - for ; a < len(b.add); a++ { - buf = appendLabelTo(buf, &b.add[a]) - } - return Labels{data: yoloString(buf)} -} - -func marshalLabelsToSizedBuffer(lbls []Label, data []byte) int { - i := len(data) - for index := len(lbls) - 1; index >= 0; index-- { - size := marshalLabelToSizedBuffer(&lbls[index], data[:i]) - i -= size - } - return len(data) - i -} - -func marshalLabelToSizedBuffer(m *Label, data []byte) int { - i := len(data) - i -= len(m.Value) - copy(data[i:], m.Value) - i = encodeSize(data, i, len(m.Value)) - i -= len(m.Name) - copy(data[i:], m.Name) - i = encodeSize(data, i, len(m.Name)) - return len(data) - i -} - -func sizeVarint(x uint64) (n int) { - // Most common case first - if x < 1<<7 { - return 1 - } - if x >= 1<<56 { - return 9 - } - if x >= 1<<28 { - x >>= 28 - n = 4 - } - if x >= 1<<14 { - x >>= 14 - n += 2 - } - if x >= 1<<7 { - n++ - } - return n + 1 -} - -func encodeVarint(data []byte, offset int, v uint64) int { - offset -= sizeVarint(v) - base := offset - for v >= 1<<7 { - data[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - data[offset] = uint8(v) - return base -} - -// Special code for the common case that a size is less than 128 -func encodeSize(data []byte, offset, v int) int { - if v < 1<<7 { - offset-- - data[offset] = uint8(v) - return offset - } - return encodeVarint(data, offset, uint64(v)) -} - -func labelsSize(lbls []Label) (n int) { - // we just encode name/value/name/value, without any extra tags or length bytes - for _, e := range lbls { - n += labelSize(&e) - } - return n -} - -func labelSize(m *Label) (n int) { - // strings are encoded as length followed by contents. - l := len(m.Name) - n += l + sizeVarint(uint64(l)) - l = len(m.Value) - n += l + sizeVarint(uint64(l)) - return n -} - -func appendLabelTo(buf []byte, m *Label) []byte { - size := labelSize(m) - sizeRequired := len(buf) + size - if cap(buf) >= sizeRequired { - buf = buf[:sizeRequired] - } else { - bufSize := cap(buf) - // Double size of buffer each time it needs to grow, to amortise copying cost. - for bufSize < sizeRequired { - bufSize = bufSize*2 + 1 - } - newBuf := make([]byte, sizeRequired, bufSize) - copy(newBuf, buf) - buf = newBuf - } - marshalLabelToSizedBuffer(m, buf) - return buf -} - -// ScratchBuilder allows efficient construction of a Labels from scratch. -type ScratchBuilder struct { - add []Label - output Labels - overwriteBuffer []byte -} - -// NewScratchBuilder creates a ScratchBuilder initialized for Labels with n entries. -func NewScratchBuilder(n int) ScratchBuilder { - return ScratchBuilder{add: make([]Label, 0, n)} -} - -func (b *ScratchBuilder) Reset() { - b.add = b.add[:0] - b.output = EmptyLabels() -} - -// Add a name/value pair. -// Note if you Add the same name twice you will get a duplicate label, which is invalid. -func (b *ScratchBuilder) Add(name, value string) { - b.add = append(b.add, Label{Name: name, Value: value}) -} - -// Sort the labels added so far by name. -func (b *ScratchBuilder) Sort() { - slices.SortFunc(b.add, func(a, b Label) bool { return a.Name < b.Name }) -} - -// Asssign is for when you already have a Labels which you want this ScratchBuilder to return. -func (b *ScratchBuilder) Assign(l Labels) { - b.output = l -} - -// Labels returns the name/value pairs added as a Labels object. Calling Add() after Labels() has no effect. -// Note: if you want them sorted, call Sort() first. -func (b *ScratchBuilder) Labels() Labels { - if b.output.IsEmpty() { - size := labelsSize(b.add) - buf := make([]byte, size) - marshalLabelsToSizedBuffer(b.add, buf) - b.output = Labels{data: yoloString(buf)} - } - return b.output -} - -// Write the newly-built Labels out to ls, reusing an internal buffer. -// Callers must ensure that there are no other references to ls, or any strings fetched from it. -func (b *ScratchBuilder) Overwrite(ls *Labels) { - size := labelsSize(b.add) - if size <= cap(b.overwriteBuffer) { - b.overwriteBuffer = b.overwriteBuffer[:size] - } else { - b.overwriteBuffer = make([]byte, size) - } - marshalLabelsToSizedBuffer(b.add, b.overwriteBuffer) - ls.data = yoloString(b.overwriteBuffer) -} diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels_stringlabels.go b/vendor/github.com/prometheus/prometheus/model/labels/labels_stringlabels.go new file mode 100644 index 000000000..f53c3b2d0 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/model/labels/labels_stringlabels.go @@ -0,0 +1,666 @@ +// Copyright 2017 The Prometheus 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. + +//go:build stringlabels + +package labels + +import ( + "reflect" + "strings" + "unsafe" + + "github.com/cespare/xxhash/v2" + "golang.org/x/exp/slices" +) + +// Labels is implemented by a single flat string holding name/value pairs. +// Each name and value is preceded by its length in varint encoding. +// Names are in order. +type Labels struct { + data string +} + +func decodeSize(data string, index int) (int, int) { + // Fast-path for common case of a single byte, value 0..127. + b := data[index] + index++ + if b < 0x80 { + return int(b), index + } + size := int(b & 0x7F) + for shift := uint(7); ; shift += 7 { + // Just panic if we go of the end of data, since all Labels strings are constructed internally and + // malformed data indicates a bug, or memory corruption. + b := data[index] + index++ + size |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + return size, index +} + +func decodeString(data string, index int) (string, int) { + var size int + size, index = decodeSize(data, index) + return data[index : index+size], index + size +} + +// Bytes returns ls as a byte slice. +// It uses non-printing characters and so should not be used for printing. +func (ls Labels) Bytes(buf []byte) []byte { + if cap(buf) < len(ls.data) { + buf = make([]byte, len(ls.data)) + } else { + buf = buf[:len(ls.data)] + } + copy(buf, ls.data) + return buf +} + +// IsZero implements yaml.IsZeroer - if we don't have this then 'omitempty' fields are always omitted. +func (ls Labels) IsZero() bool { + return len(ls.data) == 0 +} + +// MatchLabels returns a subset of Labels that matches/does not match with the provided label names based on the 'on' boolean. +// If on is set to true, it returns the subset of labels that match with the provided label names and its inverse when 'on' is set to false. +// TODO: This is only used in printing an error message +func (ls Labels) MatchLabels(on bool, names ...string) Labels { + b := NewBuilder(ls) + if on { + b.Keep(names...) + } else { + b.Del(MetricName) + b.Del(names...) + } + return b.Labels() +} + +// Hash returns a hash value for the label set. +// Note: the result is not guaranteed to be consistent across different runs of Prometheus. +func (ls Labels) Hash() uint64 { + return xxhash.Sum64(yoloBytes(ls.data)) +} + +// HashForLabels returns a hash value for the labels matching the provided names. +// 'names' have to be sorted in ascending order. +func (ls Labels) HashForLabels(b []byte, names ...string) (uint64, []byte) { + b = b[:0] + j := 0 + for i := 0; i < len(ls.data); { + var name, value string + name, i = decodeString(ls.data, i) + value, i = decodeString(ls.data, i) + for j < len(names) && names[j] < name { + j++ + } + if j == len(names) { + break + } + if name == names[j] { + b = append(b, name...) + b = append(b, seps[0]) + b = append(b, value...) + b = append(b, seps[0]) + } + } + + return xxhash.Sum64(b), b +} + +// HashWithoutLabels returns a hash value for all labels except those matching +// the provided names. +// 'names' have to be sorted in ascending order. +func (ls Labels) HashWithoutLabels(b []byte, names ...string) (uint64, []byte) { + b = b[:0] + j := 0 + for i := 0; i < len(ls.data); { + var name, value string + name, i = decodeString(ls.data, i) + value, i = decodeString(ls.data, i) + for j < len(names) && names[j] < name { + j++ + } + if name == MetricName || (j < len(names) && name == names[j]) { + continue + } + b = append(b, name...) + b = append(b, seps[0]) + b = append(b, value...) + b = append(b, seps[0]) + } + return xxhash.Sum64(b), b +} + +// BytesWithLabels is just as Bytes(), but only for labels matching names. +// 'names' have to be sorted in ascending order. +func (ls Labels) BytesWithLabels(buf []byte, names ...string) []byte { + b := buf[:0] + j := 0 + for pos := 0; pos < len(ls.data); { + lName, newPos := decodeString(ls.data, pos) + _, newPos = decodeString(ls.data, newPos) + for j < len(names) && names[j] < lName { + j++ + } + if j == len(names) { + break + } + if lName == names[j] { + b = append(b, ls.data[pos:newPos]...) + } + pos = newPos + } + return b +} + +// BytesWithoutLabels is just as Bytes(), but only for labels not matching names. +// 'names' have to be sorted in ascending order. +func (ls Labels) BytesWithoutLabels(buf []byte, names ...string) []byte { + b := buf[:0] + j := 0 + for pos := 0; pos < len(ls.data); { + lName, newPos := decodeString(ls.data, pos) + _, newPos = decodeString(ls.data, newPos) + for j < len(names) && names[j] < lName { + j++ + } + if j == len(names) || lName != names[j] { + b = append(b, ls.data[pos:newPos]...) + } + pos = newPos + } + return b +} + +// Copy returns a copy of the labels. +func (ls Labels) Copy() Labels { + buf := append([]byte{}, ls.data...) + return Labels{data: yoloString(buf)} +} + +// Get returns the value for the label with the given name. +// Returns an empty string if the label doesn't exist. +func (ls Labels) Get(name string) string { + if name == "" { // Avoid crash in loop if someone asks for "". + return "" // Prometheus does not store blank label names. + } + for i := 0; i < len(ls.data); { + var size int + size, i = decodeSize(ls.data, i) + if ls.data[i] == name[0] { + lName := ls.data[i : i+size] + i += size + if lName == name { + lValue, _ := decodeString(ls.data, i) + return lValue + } + } else { + if ls.data[i] > name[0] { // Stop looking if we've gone past. + break + } + i += size + } + size, i = decodeSize(ls.data, i) + i += size + } + return "" +} + +// Has returns true if the label with the given name is present. +func (ls Labels) Has(name string) bool { + if name == "" { // Avoid crash in loop if someone asks for "". + return false // Prometheus does not store blank label names. + } + for i := 0; i < len(ls.data); { + var size int + size, i = decodeSize(ls.data, i) + if ls.data[i] == name[0] { + lName := ls.data[i : i+size] + i += size + if lName == name { + return true + } + } else { + if ls.data[i] > name[0] { // Stop looking if we've gone past. + break + } + i += size + } + size, i = decodeSize(ls.data, i) + i += size + } + return false +} + +// HasDuplicateLabelNames returns whether ls has duplicate label names. +// It assumes that the labelset is sorted. +func (ls Labels) HasDuplicateLabelNames() (string, bool) { + var lName, prevName string + for i := 0; i < len(ls.data); { + lName, i = decodeString(ls.data, i) + _, i = decodeString(ls.data, i) + if lName == prevName { + return lName, true + } + prevName = lName + } + return "", false +} + +// WithoutEmpty returns the labelset without empty labels. +// May return the same labelset. +func (ls Labels) WithoutEmpty() Labels { + for pos := 0; pos < len(ls.data); { + _, newPos := decodeString(ls.data, pos) + lValue, newPos := decodeString(ls.data, newPos) + if lValue != "" { + pos = newPos + continue + } + // Do not copy the slice until it's necessary. + // TODO: could optimise the case where all blanks are at the end. + // Note: we size the new buffer on the assumption there is exactly one blank value. + buf := make([]byte, pos, pos+(len(ls.data)-newPos)) + copy(buf, ls.data[:pos]) // copy the initial non-blank labels + pos = newPos // move past the first blank value + for pos < len(ls.data) { + var newPos int + _, newPos = decodeString(ls.data, pos) + lValue, newPos = decodeString(ls.data, newPos) + if lValue != "" { + buf = append(buf, ls.data[pos:newPos]...) + } + pos = newPos + } + return Labels{data: yoloString(buf)} + } + return ls +} + +// Equal returns whether the two label sets are equal. +func Equal(ls, o Labels) bool { + return ls.data == o.data +} + +// EmptyLabels returns an empty Labels value, for convenience. +func EmptyLabels() Labels { + return Labels{} +} + +func yoloString(b []byte) string { + return *((*string)(unsafe.Pointer(&b))) +} + +func yoloBytes(s string) (b []byte) { + *(*string)(unsafe.Pointer(&b)) = s + (*reflect.SliceHeader)(unsafe.Pointer(&b)).Cap = len(s) + return +} + +// New returns a sorted Labels from the given labels. +// The caller has to guarantee that all label names are unique. +func New(ls ...Label) Labels { + slices.SortFunc(ls, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) + size := labelsSize(ls) + buf := make([]byte, size) + marshalLabelsToSizedBuffer(ls, buf) + return Labels{data: yoloString(buf)} +} + +// FromStrings creates new labels from pairs of strings. +func FromStrings(ss ...string) Labels { + if len(ss)%2 != 0 { + panic("invalid number of strings") + } + ls := make([]Label, 0, len(ss)/2) + for i := 0; i < len(ss); i += 2 { + ls = append(ls, Label{Name: ss[i], Value: ss[i+1]}) + } + + return New(ls...) +} + +// Compare compares the two label sets. +// The result will be 0 if a==b, <0 if a < b, and >0 if a > b. +func Compare(a, b Labels) int { + // Find the first byte in the string where a and b differ. + shorter, longer := a.data, b.data + if len(b.data) < len(a.data) { + shorter, longer = b.data, a.data + } + i := 0 + // First, go 8 bytes at a time. Data strings are expected to be 8-byte aligned. + sp := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&shorter)).Data) + lp := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&longer)).Data) + for ; i < len(shorter)-8; i += 8 { + if *(*uint64)(unsafe.Add(sp, i)) != *(*uint64)(unsafe.Add(lp, i)) { + break + } + } + // Now go 1 byte at a time. + for ; i < len(shorter); i++ { + if shorter[i] != longer[i] { + break + } + } + if i == len(shorter) { + // One Labels was a prefix of the other; the set with fewer labels compares lower. + return len(a.data) - len(b.data) + } + + // Now we know that there is some difference before the end of a and b. + // Go back through the fields and find which field that difference is in. + firstCharDifferent := i + for i = 0; ; { + size, nextI := decodeSize(a.data, i) + if nextI+size > firstCharDifferent { + break + } + i = nextI + size + } + // Difference is inside this entry. + aStr, _ := decodeString(a.data, i) + bStr, _ := decodeString(b.data, i) + if aStr < bStr { + return -1 + } + return +1 +} + +// Copy labels from b on top of whatever was in ls previously, reusing memory or expanding if needed. +func (ls *Labels) CopyFrom(b Labels) { + ls.data = b.data // strings are immutable +} + +// IsEmpty returns true if ls represents an empty set of labels. +func (ls Labels) IsEmpty() bool { + return len(ls.data) == 0 +} + +// Len returns the number of labels; it is relatively slow. +func (ls Labels) Len() int { + count := 0 + for i := 0; i < len(ls.data); { + var size int + size, i = decodeSize(ls.data, i) + i += size + size, i = decodeSize(ls.data, i) + i += size + count++ + } + return count +} + +// Range calls f on each label. +func (ls Labels) Range(f func(l Label)) { + for i := 0; i < len(ls.data); { + var lName, lValue string + lName, i = decodeString(ls.data, i) + lValue, i = decodeString(ls.data, i) + f(Label{Name: lName, Value: lValue}) + } +} + +// Validate calls f on each label. If f returns a non-nil error, then it returns that error cancelling the iteration. +func (ls Labels) Validate(f func(l Label) error) error { + for i := 0; i < len(ls.data); { + var lName, lValue string + lName, i = decodeString(ls.data, i) + lValue, i = decodeString(ls.data, i) + err := f(Label{Name: lName, Value: lValue}) + if err != nil { + return err + } + } + return nil +} + +// DropMetricName returns Labels with "__name__" removed. +func (ls Labels) DropMetricName() Labels { + for i := 0; i < len(ls.data); { + lName, i2 := decodeString(ls.data, i) + size, i2 := decodeSize(ls.data, i2) + i2 += size + if lName == MetricName { + if i == 0 { // Make common case fast with no allocations. + ls.data = ls.data[i2:] + } else { + ls.data = ls.data[:i] + ls.data[i2:] + } + break + } else if lName[0] > MetricName[0] { // Stop looking if we've gone past. + break + } + i = i2 + } + return ls +} + +// InternStrings calls intern on every string value inside ls, replacing them with what it returns. +func (ls *Labels) InternStrings(intern func(string) string) { + ls.data = intern(ls.data) +} + +// ReleaseStrings calls release on every string value inside ls. +func (ls Labels) ReleaseStrings(release func(string)) { + release(ls.data) +} + +// Labels returns the labels from the builder. +// If no modifications were made, the original labels are returned. +func (b *Builder) Labels() Labels { + if len(b.del) == 0 && len(b.add) == 0 { + return b.base + } + + slices.SortFunc(b.add, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) + slices.Sort(b.del) + a, d := 0, 0 + + bufSize := len(b.base.data) + labelsSize(b.add) + buf := make([]byte, 0, bufSize) + for pos := 0; pos < len(b.base.data); { + oldPos := pos + var lName string + lName, pos = decodeString(b.base.data, pos) + _, pos = decodeString(b.base.data, pos) + for d < len(b.del) && b.del[d] < lName { + d++ + } + if d < len(b.del) && b.del[d] == lName { + continue // This label has been deleted. + } + for ; a < len(b.add) && b.add[a].Name < lName; a++ { + buf = appendLabelTo(buf, &b.add[a]) // Insert label that was not in the base set. + } + if a < len(b.add) && b.add[a].Name == lName { + buf = appendLabelTo(buf, &b.add[a]) + a++ + continue // This label has been replaced. + } + buf = append(buf, b.base.data[oldPos:pos]...) + } + // We have come to the end of the base set; add any remaining labels. + for ; a < len(b.add); a++ { + buf = appendLabelTo(buf, &b.add[a]) + } + return Labels{data: yoloString(buf)} +} + +func marshalLabelsToSizedBuffer(lbls []Label, data []byte) int { + i := len(data) + for index := len(lbls) - 1; index >= 0; index-- { + size := marshalLabelToSizedBuffer(&lbls[index], data[:i]) + i -= size + } + return len(data) - i +} + +func marshalLabelToSizedBuffer(m *Label, data []byte) int { + i := len(data) + i -= len(m.Value) + copy(data[i:], m.Value) + i = encodeSize(data, i, len(m.Value)) + i -= len(m.Name) + copy(data[i:], m.Name) + i = encodeSize(data, i, len(m.Name)) + return len(data) - i +} + +func sizeVarint(x uint64) (n int) { + // Most common case first + if x < 1<<7 { + return 1 + } + if x >= 1<<56 { + return 9 + } + if x >= 1<<28 { + x >>= 28 + n = 4 + } + if x >= 1<<14 { + x >>= 14 + n += 2 + } + if x >= 1<<7 { + n++ + } + return n + 1 +} + +func encodeVarint(data []byte, offset int, v uint64) int { + offset -= sizeVarint(v) + base := offset + for v >= 1<<7 { + data[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + data[offset] = uint8(v) + return base +} + +// Special code for the common case that a size is less than 128 +func encodeSize(data []byte, offset, v int) int { + if v < 1<<7 { + offset-- + data[offset] = uint8(v) + return offset + } + return encodeVarint(data, offset, uint64(v)) +} + +func labelsSize(lbls []Label) (n int) { + // we just encode name/value/name/value, without any extra tags or length bytes + for _, e := range lbls { + n += labelSize(&e) + } + return n +} + +func labelSize(m *Label) (n int) { + // strings are encoded as length followed by contents. + l := len(m.Name) + n += l + sizeVarint(uint64(l)) + l = len(m.Value) + n += l + sizeVarint(uint64(l)) + return n +} + +func appendLabelTo(buf []byte, m *Label) []byte { + size := labelSize(m) + sizeRequired := len(buf) + size + if cap(buf) >= sizeRequired { + buf = buf[:sizeRequired] + } else { + bufSize := cap(buf) + // Double size of buffer each time it needs to grow, to amortise copying cost. + for bufSize < sizeRequired { + bufSize = bufSize*2 + 1 + } + newBuf := make([]byte, sizeRequired, bufSize) + copy(newBuf, buf) + buf = newBuf + } + marshalLabelToSizedBuffer(m, buf) + return buf +} + +// ScratchBuilder allows efficient construction of a Labels from scratch. +type ScratchBuilder struct { + add []Label + output Labels + overwriteBuffer []byte +} + +// NewScratchBuilder creates a ScratchBuilder initialized for Labels with n entries. +func NewScratchBuilder(n int) ScratchBuilder { + return ScratchBuilder{add: make([]Label, 0, n)} +} + +func (b *ScratchBuilder) Reset() { + b.add = b.add[:0] + b.output = EmptyLabels() +} + +// Add a name/value pair. +// Note if you Add the same name twice you will get a duplicate label, which is invalid. +func (b *ScratchBuilder) Add(name, value string) { + b.add = append(b.add, Label{Name: name, Value: value}) +} + +// Add a name/value pair, using []byte instead of string to reduce memory allocations. +// The values must remain live until Labels() is called. +func (b *ScratchBuilder) UnsafeAddBytes(name, value []byte) { + b.add = append(b.add, Label{Name: yoloString(name), Value: yoloString(value)}) +} + +// Sort the labels added so far by name. +func (b *ScratchBuilder) Sort() { + slices.SortFunc(b.add, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) +} + +// Assign is for when you already have a Labels which you want this ScratchBuilder to return. +func (b *ScratchBuilder) Assign(l Labels) { + b.output = l +} + +// Labels returns the name/value pairs added as a Labels object. Calling Add() after Labels() has no effect. +// Note: if you want them sorted, call Sort() first. +func (b *ScratchBuilder) Labels() Labels { + if b.output.IsEmpty() { + size := labelsSize(b.add) + buf := make([]byte, size) + marshalLabelsToSizedBuffer(b.add, buf) + b.output = Labels{data: yoloString(buf)} + } + return b.output +} + +// Write the newly-built Labels out to ls, reusing an internal buffer. +// Callers must ensure that there are no other references to ls, or any strings fetched from it. +func (b *ScratchBuilder) Overwrite(ls *Labels) { + size := labelsSize(b.add) + if size <= cap(b.overwriteBuffer) { + b.overwriteBuffer = b.overwriteBuffer[:size] + } else { + b.overwriteBuffer = make([]byte, size) + } + marshalLabelsToSizedBuffer(b.add, b.overwriteBuffer) + ls.data = yoloString(b.overwriteBuffer) +} diff --git a/vendor/github.com/prometheus/prometheus/model/labels/regexp.go b/vendor/github.com/prometheus/prometheus/model/labels/regexp.go index e09a63772..14319c7f7 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/regexp.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/regexp.go @@ -25,9 +25,16 @@ type FastRegexMatcher struct { prefix string suffix string contains string + + // shortcut for literals + literal bool + value string } func NewFastRegexMatcher(v string) (*FastRegexMatcher, error) { + if isLiteral(v) { + return &FastRegexMatcher{literal: true, value: v}, nil + } re, err := regexp.Compile("^(?:" + v + ")$") if err != nil { return nil, err @@ -50,6 +57,9 @@ func NewFastRegexMatcher(v string) (*FastRegexMatcher, error) { } func (m *FastRegexMatcher) MatchString(s string) bool { + if m.literal { + return s == m.value + } if m.prefix != "" && !strings.HasPrefix(s, m.prefix) { return false } @@ -63,9 +73,16 @@ func (m *FastRegexMatcher) MatchString(s string) bool { } func (m *FastRegexMatcher) GetRegexString() string { + if m.literal { + return m.value + } return m.re.String() } +func isLiteral(re string) bool { + return regexp.QuoteMeta(re) == re +} + // optimizeConcatRegex returns literal prefix/suffix text that can be safely // checked against the label value before running the regexp matcher. func optimizeConcatRegex(r *syntax.Regexp) (prefix, suffix, contains string) { diff --git a/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go b/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go index f227af0b9..1b7e63e0f 100644 --- a/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go +++ b/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go @@ -13,11 +13,11 @@ package metadata -import "github.com/prometheus/prometheus/model/textparse" +import "github.com/prometheus/common/model" // Metadata stores a series' metadata information. type Metadata struct { - Type textparse.MetricType - Unit string - Help string + Type model.MetricType `json:"type"` + Unit string `json:"unit"` + Help string `json:"help"` } diff --git a/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go b/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go index 5027c3963..d29c3d07a 100644 --- a/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go +++ b/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go @@ -108,6 +108,10 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { if c.Regex.Regexp == nil { c.Regex = MustNewRegexp("") } + return c.Validate() +} + +func (c *Config) Validate() error { if c.Action == "" { return fmt.Errorf("relabel action cannot be empty") } @@ -117,7 +121,13 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { if (c.Action == Replace || c.Action == HashMod || c.Action == Lowercase || c.Action == Uppercase || c.Action == KeepEqual || c.Action == DropEqual) && c.TargetLabel == "" { return fmt.Errorf("relabel configuration for %s action requires 'target_label' value", c.Action) } - if (c.Action == Replace || c.Action == Lowercase || c.Action == Uppercase || c.Action == KeepEqual || c.Action == DropEqual) && !relabelTarget.MatchString(c.TargetLabel) { + if c.Action == Replace && !strings.Contains(c.TargetLabel, "$") && !model.LabelName(c.TargetLabel).IsValid() { + return fmt.Errorf("%q is invalid 'target_label' for %s action", c.TargetLabel, c.Action) + } + if c.Action == Replace && strings.Contains(c.TargetLabel, "$") && !relabelTarget.MatchString(c.TargetLabel) { + return fmt.Errorf("%q is invalid 'target_label' for %s action", c.TargetLabel, c.Action) + } + if (c.Action == Lowercase || c.Action == Uppercase || c.Action == KeepEqual || c.Action == DropEqual) && !model.LabelName(c.TargetLabel).IsValid() { return fmt.Errorf("%q is invalid 'target_label' for %s action", c.TargetLabel, c.Action) } if (c.Action == Lowercase || c.Action == Uppercase || c.Action == KeepEqual || c.Action == DropEqual) && c.Replacement != DefaultRelabelConfig.Replacement { @@ -202,10 +212,12 @@ func (re Regexp) String() string { return str[4 : len(str)-2] } -// Process returns a relabeled copy of the given label set. The relabel configurations +// Process returns a relabeled version of the given label set. The relabel configurations // are applied in order of input. +// There are circumstances where Process will modify the input label. +// If you want to avoid issues with the input label set being modified, at the cost of +// higher memory usage, you can use lbls.Copy(). // If a label set is dropped, EmptyLabels and false is returned. -// May return the input labelSet modified. func Process(lbls labels.Labels, cfgs ...*Config) (ret labels.Labels, keep bool) { lb := labels.NewBuilder(lbls) if !ProcessBuilder(lb, cfgs...) { @@ -262,12 +274,11 @@ func relabel(cfg *Config, lb *labels.Builder) (keep bool) { } target := model.LabelName(cfg.Regex.ExpandString([]byte{}, cfg.TargetLabel, val, indexes)) if !target.IsValid() { - lb.Del(cfg.TargetLabel) break } res := cfg.Regex.ExpandString([]byte{}, cfg.Replacement, val, indexes) if len(res) == 0 { - lb.Del(cfg.TargetLabel) + lb.Del(string(target)) break } lb.Set(string(target), string(res)) diff --git a/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go b/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go index 30b3face0..03cbd8849 100644 --- a/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go +++ b/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go @@ -173,17 +173,11 @@ func (r *RuleNode) Validate() (nodes []WrappedError) { }) } if r.Record.Value == "" && r.Alert.Value == "" { - if r.Record.Value == "0" { - nodes = append(nodes, WrappedError{ - err: fmt.Errorf("one of 'record' or 'alert' must be set"), - node: &r.Alert, - }) - } else { - nodes = append(nodes, WrappedError{ - err: fmt.Errorf("one of 'record' or 'alert' must be set"), - node: &r.Record, - }) - } + nodes = append(nodes, WrappedError{ + err: fmt.Errorf("one of 'record' or 'alert' must be set"), + node: &r.Record, + nodeAlt: &r.Alert, + }) } if r.Expr.Value == "" { diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/interface.go b/vendor/github.com/prometheus/prometheus/model/textparse/interface.go index 9efd942e8..3a363ebfb 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/interface.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/interface.go @@ -16,6 +16,8 @@ package textparse import ( "mime" + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" @@ -42,7 +44,7 @@ type Parser interface { // Type returns the metric name and type in the current entry. // Must only be called after Next returned a type entry. // The returned byte slices become invalid after the next call to Next. - Type() ([]byte, MetricType) + Type() ([]byte, model.MetricType) // Unit returns the metric name and unit in the current entry. // Must only be called after Next returned a unit entry. @@ -59,9 +61,16 @@ type Parser interface { Metric(l *labels.Labels) string // Exemplar writes the exemplar of the current sample into the passed - // exemplar. It returns if an exemplar exists or not. + // exemplar. It can be called repeatedly to retrieve multiple exemplars + // for the same sample. It returns false once all exemplars are + // retrieved (including the case where no exemplars exist at all). Exemplar(l *exemplar.Exemplar) bool + // CreatedTimestamp returns the created timestamp (in milliseconds) for the + // current sample. It returns nil if it is unknown e.g. if it wasn't set, + // if the scrape protocol or metric type does not support created timestamps. + CreatedTimestamp() *int64 + // Next advances the parser to the next sample. It returns false if no // more samples were read or an error occurred. Next() (Entry, error) @@ -71,7 +80,7 @@ type Parser interface { // // This function always returns a valid parser, but might additionally // return an error if the content type cannot be parsed. -func New(b []byte, contentType string) (Parser, error) { +func New(b []byte, contentType string, parseClassicHistograms bool) (Parser, error) { if contentType == "" { return NewPromParser(b), nil } @@ -84,7 +93,7 @@ func New(b []byte, contentType string) (Parser, error) { case "application/openmetrics-text": return NewOpenMetricsParser(b), nil case "application/vnd.google.protobuf": - return NewProtobufParser(b), nil + return NewProtobufParser(b, parseClassicHistograms), nil default: return NewPromParser(b), nil } @@ -100,19 +109,5 @@ const ( EntrySeries Entry = 2 // A series with a simple float64 as value. EntryComment Entry = 3 EntryUnit Entry = 4 - EntryHistogram Entry = 5 // A series with a sparse histogram as a value. -) - -// MetricType represents metric type values. -type MetricType string - -const ( - MetricTypeCounter = MetricType("counter") - MetricTypeGauge = MetricType("gauge") - MetricTypeHistogram = MetricType("histogram") - MetricTypeGaugeHistogram = MetricType("gaugehistogram") - MetricTypeSummary = MetricType("summary") - MetricTypeInfo = MetricType("info") - MetricTypeStateset = MetricType("stateset") - MetricTypeUnknown = MetricType("unknown") + EntryHistogram Entry = 5 // A series with a native histogram as a value. ) diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go b/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go index c17d40020..4c15ff5fc 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go @@ -24,6 +24,8 @@ import ( "strings" "unicode/utf8" + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" @@ -74,7 +76,7 @@ type OpenMetricsParser struct { builder labels.ScratchBuilder series []byte text []byte - mtype MetricType + mtype model.MetricType val float64 ts int64 hasTS bool @@ -126,7 +128,7 @@ func (p *OpenMetricsParser) Help() ([]byte, []byte) { // Type returns the metric name and type in the current entry. // Must only be called after Next returned a type entry. // The returned byte slices become invalid after the next call to Next. -func (p *OpenMetricsParser) Type() ([]byte, MetricType) { +func (p *OpenMetricsParser) Type() ([]byte, model.MetricType) { return p.l.b[p.offsets[0]:p.offsets[1]], p.mtype } @@ -134,7 +136,6 @@ func (p *OpenMetricsParser) Type() ([]byte, MetricType) { // Must only be called after Next returned a unit entry. // The returned byte slices become invalid after the next call to Next. func (p *OpenMetricsParser) Unit() ([]byte, []byte) { - // The Prometheus format does not have units. return p.l.b[p.offsets[0]:p.offsets[1]], p.text } @@ -174,8 +175,10 @@ func (p *OpenMetricsParser) Metric(l *labels.Labels) string { return s } -// Exemplar writes the exemplar of the current sample into the passed -// exemplar. It returns the whether an exemplar exists. +// Exemplar writes the exemplar of the current sample into the passed exemplar. +// It returns whether an exemplar exists. As OpenMetrics only ever has one +// exemplar per sample, every call after the first (for the same sample) will +// always return false. func (p *OpenMetricsParser) Exemplar(e *exemplar.Exemplar) bool { if len(p.exemplar) == 0 { return false @@ -204,9 +207,17 @@ func (p *OpenMetricsParser) Exemplar(e *exemplar.Exemplar) bool { p.builder.Sort() e.Labels = p.builder.Labels() + // Wipe exemplar so that future calls return false. + p.exemplar = p.exemplar[:0] return true } +// CreatedTimestamp returns nil as it's not implemented yet. +// TODO(bwplotka): https://github.com/prometheus/prometheus/issues/12980 +func (p *OpenMetricsParser) CreatedTimestamp() *int64 { + return nil +} + // nextToken returns the next token from the openMetricsLexer. func (p *OpenMetricsParser) nextToken() token { tok := p.l.Lex() @@ -262,21 +273,21 @@ func (p *OpenMetricsParser) Next() (Entry, error) { case tType: switch s := yoloString(p.text); s { case "counter": - p.mtype = MetricTypeCounter + p.mtype = model.MetricTypeCounter case "gauge": - p.mtype = MetricTypeGauge + p.mtype = model.MetricTypeGauge case "histogram": - p.mtype = MetricTypeHistogram + p.mtype = model.MetricTypeHistogram case "gaugehistogram": - p.mtype = MetricTypeGaugeHistogram + p.mtype = model.MetricTypeGaugeHistogram case "summary": - p.mtype = MetricTypeSummary + p.mtype = model.MetricTypeSummary case "info": - p.mtype = MetricTypeInfo + p.mtype = model.MetricTypeInfo case "stateset": - p.mtype = MetricTypeStateset + p.mtype = model.MetricTypeStateset case "unknown": - p.mtype = MetricTypeUnknown + p.mtype = model.MetricTypeUnknown default: return EntryInvalid, fmt.Errorf("invalid metric type %q", s) } @@ -334,7 +345,7 @@ func (p *OpenMetricsParser) Next() (Entry, error) { var ts float64 // A float is enough to hold what we need for millisecond resolution. if ts, err = parseFloat(yoloString(p.l.buf()[1:])); err != nil { - return EntryInvalid, fmt.Errorf("%v while parsing: %q", err, p.l.b[p.start:p.l.i]) + return EntryInvalid, fmt.Errorf("%w while parsing: %q", err, p.l.b[p.start:p.l.i]) } if math.IsNaN(ts) || math.IsInf(ts, 0) { return EntryInvalid, fmt.Errorf("invalid timestamp %f", ts) @@ -387,7 +398,7 @@ func (p *OpenMetricsParser) parseComment() error { var ts float64 // A float is enough to hold what we need for millisecond resolution. if ts, err = parseFloat(yoloString(p.l.buf()[1:])); err != nil { - return fmt.Errorf("%v while parsing: %q", err, p.l.b[p.start:p.l.i]) + return fmt.Errorf("%w while parsing: %q", err, p.l.b[p.start:p.l.i]) } if math.IsNaN(ts) || math.IsInf(ts, 0) { return fmt.Errorf("invalid exemplar timestamp %f", ts) @@ -457,7 +468,7 @@ func (p *OpenMetricsParser) getFloatValue(t token, after string) (float64, error } val, err := parseFloat(yoloString(p.l.buf()[1:])) if err != nil { - return 0, fmt.Errorf("%v while parsing: %q", err, p.l.b[p.start:p.l.i]) + return 0, fmt.Errorf("%w while parsing: %q", err, p.l.b[p.start:p.l.i]) } // Ensure canonical NaN value. if math.IsNaN(p.exemplarVal) { diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go b/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go index 94338a666..7123e52c3 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go @@ -26,6 +26,8 @@ import ( "unicode/utf8" "unsafe" + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" @@ -146,7 +148,7 @@ type PromParser struct { builder labels.ScratchBuilder series []byte text []byte - mtype MetricType + mtype model.MetricType val float64 ts int64 hasTS bool @@ -190,7 +192,7 @@ func (p *PromParser) Help() ([]byte, []byte) { // Type returns the metric name and type in the current entry. // Must only be called after Next returned a type entry. // The returned byte slices become invalid after the next call to Next. -func (p *PromParser) Type() ([]byte, MetricType) { +func (p *PromParser) Type() ([]byte, model.MetricType) { return p.l.b[p.offsets[0]:p.offsets[1]], p.mtype } @@ -245,6 +247,12 @@ func (p *PromParser) Exemplar(*exemplar.Exemplar) bool { return false } +// CreatedTimestamp returns nil as it's not implemented yet. +// TODO(bwplotka): https://github.com/prometheus/prometheus/issues/12980 +func (p *PromParser) CreatedTimestamp() *int64 { + return nil +} + // nextToken returns the next token from the promlexer. It skips over tabs // and spaces. func (p *PromParser) nextToken() token { @@ -299,15 +307,15 @@ func (p *PromParser) Next() (Entry, error) { case tType: switch s := yoloString(p.text); s { case "counter": - p.mtype = MetricTypeCounter + p.mtype = model.MetricTypeCounter case "gauge": - p.mtype = MetricTypeGauge + p.mtype = model.MetricTypeGauge case "histogram": - p.mtype = MetricTypeHistogram + p.mtype = model.MetricTypeHistogram case "summary": - p.mtype = MetricTypeSummary + p.mtype = model.MetricTypeSummary case "untyped": - p.mtype = MetricTypeUnknown + p.mtype = model.MetricTypeUnknown default: return EntryInvalid, fmt.Errorf("invalid metric type %q", s) } @@ -348,7 +356,7 @@ func (p *PromParser) Next() (Entry, error) { return EntryInvalid, p.parseError("expected value after metric", t2) } if p.val, err = parseFloat(yoloString(p.l.buf())); err != nil { - return EntryInvalid, fmt.Errorf("%v while parsing: %q", err, p.l.b[p.start:p.l.i]) + return EntryInvalid, fmt.Errorf("%w while parsing: %q", err, p.l.b[p.start:p.l.i]) } // Ensure canonical NaN value. if math.IsNaN(p.val) { @@ -361,7 +369,7 @@ func (p *PromParser) Next() (Entry, error) { case tTimestamp: p.hasTS = true if p.ts, err = strconv.ParseInt(yoloString(p.l.buf()), 10, 64); err != nil { - return EntryInvalid, fmt.Errorf("%v while parsing: %q", err, p.l.b[p.start:p.l.i]) + return EntryInvalid, fmt.Errorf("%w while parsing: %q", err, p.l.b[p.start:p.l.i]) } if t2 := p.nextToken(); t2 != tLinebreak { return EntryInvalid, p.parseError("expected next entry after timestamp", t2) diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go b/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go index eca145955..2c9c384b6 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go @@ -16,6 +16,7 @@ package textparse import ( "bytes" "encoding/binary" + "errors" "fmt" "io" "math" @@ -23,7 +24,7 @@ import ( "unicode/utf8" "github.com/gogo/protobuf/proto" - "github.com/pkg/errors" + "github.com/gogo/protobuf/types" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/exemplar" @@ -52,8 +53,14 @@ type ProtobufParser struct { // fieldPos is the position within a Summary or (legacy) Histogram. -2 // is the count. -1 is the sum. Otherwise it is the index within // quantiles/buckets. - fieldPos int - fieldsDone bool // true if no more fields of a Summary or (legacy) Histogram to be processed. + fieldPos int + fieldsDone bool // true if no more fields of a Summary or (legacy) Histogram to be processed. + redoClassic bool // true after parsing a native histogram if we need to parse it again as a classic histogram. + + // exemplarReturned is set to true each time an exemplar has been + // returned, and set back to false upon each Next() call. + exemplarReturned bool + // state is marked by the entry we are processing. EntryInvalid implies // that we have to decode the next MetricFamily. state Entry @@ -62,17 +69,22 @@ type ProtobufParser struct { mf *dto.MetricFamily + // Wether to also parse a classic histogram that is also present as a + // native histogram. + parseClassicHistograms bool + // The following are just shenanigans to satisfy the Parser interface. metricBytes *bytes.Buffer // A somewhat fluid representation of the current metric. } // NewProtobufParser returns a parser for the payload in the byte slice. -func NewProtobufParser(b []byte) Parser { +func NewProtobufParser(b []byte, parseClassicHistograms bool) Parser { return &ProtobufParser{ - in: b, - state: EntryInvalid, - mf: &dto.MetricFamily{}, - metricBytes: &bytes.Buffer{}, + in: b, + state: EntryInvalid, + mf: &dto.MetricFamily{}, + metricBytes: &bytes.Buffer{}, + parseClassicHistograms: parseClassicHistograms, } } @@ -98,7 +110,7 @@ func (p *ProtobufParser) Series() ([]byte, *int64, float64) { v = float64(s.GetSampleCount()) case -1: v = s.GetSampleSum() - // Need to detect a summaries without quantile here. + // Need to detect summaries without quantile here. if len(s.GetQuantile()) == 0 { p.fieldsDone = true } @@ -106,19 +118,28 @@ func (p *ProtobufParser) Series() ([]byte, *int64, float64) { v = s.GetQuantile()[p.fieldPos].GetValue() } case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: - // This should only happen for a legacy histogram. + // This should only happen for a classic histogram. h := m.GetHistogram() switch p.fieldPos { case -2: - v = float64(h.GetSampleCount()) + v = h.GetSampleCountFloat() + if v == 0 { + v = float64(h.GetSampleCount()) + } case -1: v = h.GetSampleSum() default: bb := h.GetBucket() if p.fieldPos >= len(bb) { - v = float64(h.GetSampleCount()) + v = h.GetSampleCountFloat() + if v == 0 { + v = float64(h.GetSampleCount()) + } } else { - v = float64(bb[p.fieldPos].GetCumulativeCount()) + v = bb[p.fieldPos].GetCumulativeCountFloat() + if v == 0 { + v = float64(bb[p.fieldPos].GetCumulativeCount()) + } } } default: @@ -127,9 +148,15 @@ func (p *ProtobufParser) Series() ([]byte, *int64, float64) { if ts != 0 { return p.metricBytes.Bytes(), &ts, v } - // Nasty hack: Assume that ts==0 means no timestamp. That's not true in - // general, but proto3 has no distinction between unset and - // default. Need to avoid in the final format. + // TODO(beorn7): We assume here that ts==0 means no timestamp. That's + // not true in general, but proto3 originally has no distinction between + // unset and default. At a later stage, the `optional` keyword was + // (re-)introduced in proto3, but gogo-protobuf never got updated to + // support it. (Note that setting `[(gogoproto.nullable) = true]` for + // the `timestamp_ms` field doesn't help, either.) We plan to migrate + // away from gogo-protobuf to an actively maintained protobuf + // implementation. Once that's done, we can simply use the `optional` + // keyword and check for the unset state explicitly. return p.metricBytes.Bytes(), nil, v } @@ -149,6 +176,9 @@ func (p *ProtobufParser) Histogram() ([]byte, *int64, *histogram.Histogram, *his ts = m.GetTimestampMs() h = m.GetHistogram() ) + if p.parseClassicHistograms && len(h.GetBucket()) > 0 { + p.redoClassic = true + } if h.GetSampleCountFloat() > 0 || h.GetZeroCountFloat() > 0 { // It is a float histogram. fh := histogram.FloatHistogram{ @@ -222,27 +252,28 @@ func (p *ProtobufParser) Help() ([]byte, []byte) { // Type returns the metric name and type in the current entry. // Must only be called after Next returned a type entry. // The returned byte slices become invalid after the next call to Next. -func (p *ProtobufParser) Type() ([]byte, MetricType) { +func (p *ProtobufParser) Type() ([]byte, model.MetricType) { n := p.metricBytes.Bytes() switch p.mf.GetType() { case dto.MetricType_COUNTER: - return n, MetricTypeCounter + return n, model.MetricTypeCounter case dto.MetricType_GAUGE: - return n, MetricTypeGauge + return n, model.MetricTypeGauge case dto.MetricType_HISTOGRAM: - return n, MetricTypeHistogram + return n, model.MetricTypeHistogram case dto.MetricType_GAUGE_HISTOGRAM: - return n, MetricTypeGaugeHistogram + return n, model.MetricTypeGaugeHistogram case dto.MetricType_SUMMARY: - return n, MetricTypeSummary + return n, model.MetricTypeSummary } - return n, MetricTypeUnknown + return n, model.MetricTypeUnknown } -// Unit always returns (nil, nil) because units aren't supported by the protobuf -// format. +// Unit returns the metric unit in the current entry. +// Must only be called after Next returned a unit entry. +// The returned byte slices become invalid after the next call to Next. func (p *ProtobufParser) Unit() ([]byte, []byte) { - return nil, nil + return p.metricBytes.Bytes(), []byte(p.mf.GetUnit()) } // Comment always returns nil because comments aren't supported by the protobuf @@ -274,8 +305,12 @@ func (p *ProtobufParser) Metric(l *labels.Labels) string { // Exemplar writes the exemplar of the current sample into the passed // exemplar. It returns if an exemplar exists or not. In case of a native // histogram, the legacy bucket section is still used for exemplars. To ingest -// all examplars, call the Exemplar method repeatedly until it returns false. +// all exemplars, call the Exemplar method repeatedly until it returns false. func (p *ProtobufParser) Exemplar(ex *exemplar.Exemplar) bool { + if p.exemplarReturned && p.state == EntrySeries { + // We only ever return one exemplar per (non-native-histogram) series. + return false + } m := p.mf.GetMetric()[p.metricPos] var exProto *dto.Exemplar switch p.mf.GetType() { @@ -283,22 +318,28 @@ func (p *ProtobufParser) Exemplar(ex *exemplar.Exemplar) bool { exProto = m.GetCounter().GetExemplar() case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: bb := m.GetHistogram().GetBucket() + isClassic := p.state == EntrySeries if p.fieldPos < 0 { - if p.state == EntrySeries { + if isClassic { return false // At _count or _sum. } p.fieldPos = 0 // Start at 1st bucket for native histograms. } for p.fieldPos < len(bb) { exProto = bb[p.fieldPos].GetExemplar() - if p.state == EntrySeries { + if isClassic { break } p.fieldPos++ - if exProto != nil { - break + // We deliberately drop exemplars with no timestamp only for native histograms. + if exProto != nil && (isClassic || exProto.GetTimestamp() != nil) { + break // Found a classic histogram exemplar or a native histogram exemplar with a timestamp. } } + // If the last exemplar for native histograms has no timestamp, ignore it. + if !isClassic && exProto.GetTimestamp() == nil { + return false + } default: return false } @@ -316,13 +357,37 @@ func (p *ProtobufParser) Exemplar(ex *exemplar.Exemplar) bool { } p.builder.Sort() ex.Labels = p.builder.Labels() + p.exemplarReturned = true return true } +// CreatedTimestamp returns CT or nil if CT is not present or +// invalid (as timestamp e.g. negative value) on counters, summaries or histograms. +func (p *ProtobufParser) CreatedTimestamp() *int64 { + var ct *types.Timestamp + switch p.mf.GetType() { + case dto.MetricType_COUNTER: + ct = p.mf.GetMetric()[p.metricPos].GetCounter().GetCreatedTimestamp() + case dto.MetricType_SUMMARY: + ct = p.mf.GetMetric()[p.metricPos].GetSummary().GetCreatedTimestamp() + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: + ct = p.mf.GetMetric()[p.metricPos].GetHistogram().GetCreatedTimestamp() + default: + } + ctAsTime, err := types.TimestampFromProto(ct) + if err != nil { + // Errors means ct == nil or invalid timestamp, which we silently ignore. + return nil + } + ctMilis := ctAsTime.UnixMilli() + return &ctMilis +} + // Next advances the parser to the next "sample" (emulating the behavior of a // text format parser). It returns (EntryInvalid, io.EOF) if no samples were // read. func (p *ProtobufParser) Next() (Entry, error) { + p.exemplarReturned = false switch p.state { case EntryInvalid: p.metricPos = 0 @@ -342,10 +407,10 @@ func (p *ProtobufParser) Next() (Entry, error) { // into metricBytes and validate only name, help, and type for now. name := p.mf.GetName() if !model.IsValidMetricName(model.LabelValue(name)) { - return EntryInvalid, errors.Errorf("invalid metric name: %s", name) + return EntryInvalid, fmt.Errorf("invalid metric name: %s", name) } if help := p.mf.GetHelp(); !utf8.ValidString(help) { - return EntryInvalid, errors.Errorf("invalid help for metric %q: %s", name, help) + return EntryInvalid, fmt.Errorf("invalid help for metric %q: %s", name, help) } switch p.mf.GetType() { case dto.MetricType_COUNTER, @@ -356,7 +421,17 @@ func (p *ProtobufParser) Next() (Entry, error) { dto.MetricType_UNTYPED: // All good. default: - return EntryInvalid, errors.Errorf("unknown metric type for metric %q: %s", name, p.mf.GetType()) + return EntryInvalid, fmt.Errorf("unknown metric type for metric %q: %s", name, p.mf.GetType()) + } + unit := p.mf.GetUnit() + if len(unit) > 0 { + if p.mf.GetType() == dto.MetricType_COUNTER && strings.HasSuffix(name, "_total") { + if !strings.HasSuffix(name[:len(name)-6], unit) || len(name)-6 < len(unit)+1 || name[len(name)-6-len(unit)-1] != '_' { + return EntryInvalid, fmt.Errorf("unit %q not a suffix of counter %q", unit, name) + } + } else if !strings.HasSuffix(name, unit) || len(name) < len(unit)+1 || name[len(name)-len(unit)-1] != '_' { + return EntryInvalid, fmt.Errorf("unit %q not a suffix of metric %q", unit, name) + } } p.metricBytes.Reset() p.metricBytes.WriteString(name) @@ -376,6 +451,12 @@ func (p *ProtobufParser) Next() (Entry, error) { return EntryInvalid, err } case EntryHistogram, EntrySeries: + if p.redoClassic { + p.redoClassic = false + p.state = EntrySeries + p.fieldPos = -3 + p.fieldsDone = false + } t := p.mf.GetType() if p.state == EntrySeries && !p.fieldsDone && (t == dto.MetricType_SUMMARY || @@ -386,6 +467,14 @@ func (p *ProtobufParser) Next() (Entry, error) { p.metricPos++ p.fieldPos = -2 p.fieldsDone = false + // If this is a metric family containing native + // histograms, we have to switch back to native + // histograms after parsing a classic histogram. + if p.state == EntrySeries && + (t == dto.MetricType_HISTOGRAM || t == dto.MetricType_GAUGE_HISTOGRAM) && + isNativeHistogram(p.mf.GetMetric()[0].GetHistogram()) { + p.state = EntryHistogram + } } if p.metricPos >= len(p.mf.GetMetric()) { p.state = EntryInvalid @@ -395,7 +484,7 @@ func (p *ProtobufParser) Next() (Entry, error) { return EntryInvalid, err } default: - return EntryInvalid, errors.Errorf("invalid protobuf parsing state: %d", p.state) + return EntryInvalid, fmt.Errorf("invalid protobuf parsing state: %d", p.state) } return p.state, nil } @@ -408,13 +497,13 @@ func (p *ProtobufParser) updateMetricBytes() error { b.WriteByte(model.SeparatorByte) n := lp.GetName() if !model.LabelName(n).IsValid() { - return errors.Errorf("invalid label name: %s", n) + return fmt.Errorf("invalid label name: %s", n) } b.WriteString(n) b.WriteByte(model.SeparatorByte) v := lp.GetValue() if !utf8.ValidString(v) { - return errors.Errorf("invalid label value: %s", v) + return fmt.Errorf("invalid label value: %s", v) } b.WriteString(v) } @@ -432,7 +521,7 @@ func (p *ProtobufParser) updateMetricBytes() error { // state. func (p *ProtobufParser) getMagicName() string { t := p.mf.GetType() - if p.state == EntryHistogram || (t != dto.MetricType_HISTOGRAM && t != dto.MetricType_SUMMARY) { + if p.state == EntryHistogram || (t != dto.MetricType_HISTOGRAM && t != dto.MetricType_GAUGE_HISTOGRAM && t != dto.MetricType_SUMMARY) { return p.mf.GetName() } if p.fieldPos == -2 { @@ -489,7 +578,7 @@ func readDelimited(b []byte, mf *dto.MetricFamily) (n int, err error) { } totalLength := varIntLength + int(messageLength) if totalLength > len(b) { - return 0, errors.Errorf("protobufparse: insufficient length of buffer, expected at least %d bytes, got %d bytes", totalLength, len(b)) + return 0, fmt.Errorf("protobufparse: insufficient length of buffer, expected at least %d bytes, got %d bytes", totalLength, len(b)) } mf.Reset() return totalLength, mf.Unmarshal(b[varIntLength:totalLength]) @@ -521,18 +610,17 @@ func formatOpenMetricsFloat(f float64) string { return s + ".0" } -// isNativeHistogram returns false iff the provided histograms has no sparse -// buckets and a zero threshold of 0 and a zero count of 0. In principle, this -// could still be meant to be a native histogram (with a zero threshold of 0 and -// no observations yet), but for now, we'll treat this case as a conventional -// histogram. -// -// TODO(beorn7): In the final format, there should be an unambiguous way of -// deciding if a histogram should be ingested as a conventional one or a native -// one. +// isNativeHistogram returns false iff the provided histograms has no spans at +// all (neither positive nor negative) and a zero threshold of 0 and a zero +// count of 0. In principle, this could still be meant to be a native histogram +// with a zero threshold of 0 and no observations yet. In that case, +// instrumentation libraries should add a "no-op" span (e.g. length zero, offset +// zero) to signal that the histogram is meant to be parsed as a native +// histogram. Failing to do so will cause Prometheus to parse it as a classic +// histogram as long as no observations have happened. func isNativeHistogram(h *dto.Histogram) bool { - return len(h.GetNegativeDelta()) > 0 || - len(h.GetPositiveDelta()) > 0 || - h.GetZeroCount() > 0 || - h.GetZeroThreshold() > 0 + return len(h.GetPositiveSpan()) > 0 || + len(h.GetNegativeSpan()) > 0 || + h.GetZeroThreshold() > 0 || + h.GetZeroCount() > 0 } diff --git a/vendor/github.com/prometheus/prometheus/notifier/notifier.go b/vendor/github.com/prometheus/prometheus/notifier/notifier.go index c3b2e5c7e..af5579933 100644 --- a/vendor/github.com/prometheus/prometheus/notifier/notifier.go +++ b/vendor/github.com/prometheus/prometheus/notifier/notifier.go @@ -32,6 +32,7 @@ import ( "github.com/prometheus/client_golang/prometheus" config_util "github.com/prometheus/common/config" "github.com/prometheus/common/model" + "github.com/prometheus/common/sigv4" "github.com/prometheus/common/version" "go.uber.org/atomic" @@ -349,19 +350,6 @@ func (n *Manager) Send(alerts ...*Alert) { n.mtx.Lock() defer n.mtx.Unlock() - // Attach external labels before relabelling and sending. - for _, a := range alerts { - lb := labels.NewBuilder(a.Labels) - - n.opts.ExternalLabels.Range(func(l labels.Label) { - if a.Labels.Get(l.Name) == "" { - lb.Set(l.Name, l.Value) - } - }) - - a.Labels = lb.Labels() - } - alerts = n.relabelAlerts(alerts) if len(alerts) == 0 { return @@ -390,15 +378,25 @@ func (n *Manager) Send(alerts ...*Alert) { n.setMore() } +// Attach external labels and process relabelling rules. func (n *Manager) relabelAlerts(alerts []*Alert) []*Alert { + lb := labels.NewBuilder(labels.EmptyLabels()) var relabeledAlerts []*Alert - for _, alert := range alerts { - labels, keep := relabel.Process(alert.Labels, n.opts.RelabelConfigs...) - if keep { - alert.Labels = labels - relabeledAlerts = append(relabeledAlerts, alert) + for _, a := range alerts { + lb.Reset(a.Labels) + n.opts.ExternalLabels.Range(func(l labels.Label) { + if a.Labels.Get(l.Name) == "" { + lb.Set(l.Name, l.Value) + } + }) + + keep := relabel.ProcessBuilder(lb, n.opts.RelabelConfigs...) + if !keep { + continue } + a.Labels = lb.Labels() + relabeledAlerts = append(relabeledAlerts, a) } return relabeledAlerts } @@ -643,6 +641,17 @@ func newAlertmanagerSet(cfg *config.AlertmanagerConfig, logger log.Logger, metri if err != nil { return nil, err } + t := client.Transport + + if cfg.SigV4Config != nil { + t, err = sigv4.NewSigV4RoundTripper(cfg.SigV4Config, client.Transport) + if err != nil { + return nil, err + } + } + + client.Transport = t + s := &alertmanagerSet{ client: client, cfg: cfg, @@ -701,36 +710,38 @@ func postPath(pre string, v config.AlertmanagerAPIVersion) string { func AlertmanagerFromGroup(tg *targetgroup.Group, cfg *config.AlertmanagerConfig) ([]alertmanager, []alertmanager, error) { var res []alertmanager var droppedAlertManagers []alertmanager + lb := labels.NewBuilder(labels.EmptyLabels()) for _, tlset := range tg.Targets { - lbls := make([]labels.Label, 0, len(tlset)+2+len(tg.Labels)) + lb.Reset(labels.EmptyLabels()) for ln, lv := range tlset { - lbls = append(lbls, labels.Label{Name: string(ln), Value: string(lv)}) + lb.Set(string(ln), string(lv)) } // Set configured scheme as the initial scheme label for overwrite. - lbls = append(lbls, labels.Label{Name: model.SchemeLabel, Value: cfg.Scheme}) - lbls = append(lbls, labels.Label{Name: pathLabel, Value: postPath(cfg.PathPrefix, cfg.APIVersion)}) + lb.Set(model.SchemeLabel, cfg.Scheme) + lb.Set(pathLabel, postPath(cfg.PathPrefix, cfg.APIVersion)) // Combine target labels with target group labels. for ln, lv := range tg.Labels { if _, ok := tlset[ln]; !ok { - lbls = append(lbls, labels.Label{Name: string(ln), Value: string(lv)}) + lb.Set(string(ln), string(lv)) } } - lset, keep := relabel.Process(labels.New(lbls...), cfg.RelabelConfigs...) + preRelabel := lb.Labels() + keep := relabel.ProcessBuilder(lb, cfg.RelabelConfigs...) if !keep { - droppedAlertManagers = append(droppedAlertManagers, alertmanagerLabels{labels.New(lbls...)}) + droppedAlertManagers = append(droppedAlertManagers, alertmanagerLabels{preRelabel}) continue } - addr := lset.Get(model.AddressLabel) + addr := lb.Get(model.AddressLabel) if err := config.CheckTargetAddress(model.LabelValue(addr)); err != nil { return nil, nil, err } - res = append(res, alertmanagerLabels{lset}) + res = append(res, alertmanagerLabels{lb.Labels()}) } return res, droppedAlertManagers, nil } diff --git a/vendor/github.com/prometheus/prometheus/prompb/README.md b/vendor/github.com/prometheus/prometheus/prompb/README.md index 8c19b17e9..a33d7bfb8 100644 --- a/vendor/github.com/prometheus/prometheus/prompb/README.md +++ b/vendor/github.com/prometheus/prometheus/prompb/README.md @@ -4,6 +4,6 @@ re-compile them when building Prometheus. If however you have modified the defs and do need to re-compile, run `make proto` from the parent dir. -In order for the script to run, you'll need `protoc` (version 3.12.3) in your -PATH. +In order for the [script](../scripts/genproto.sh) to run, you'll need `protoc` (version 3.15.8) in +your PATH. diff --git a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.pb.go b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.pb.go index 3e4bc7df8..17cab6081 100644 --- a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.pb.go +++ b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.pb.go @@ -172,11 +172,12 @@ func (m *Gauge) GetValue() float64 { } type Counter struct { - Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` - Exemplar *Exemplar `protobuf:"bytes,2,opt,name=exemplar,proto3" json:"exemplar,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` + Exemplar *Exemplar `protobuf:"bytes,2,opt,name=exemplar,proto3" json:"exemplar,omitempty"` + CreatedTimestamp *types.Timestamp `protobuf:"bytes,3,opt,name=created_timestamp,json=createdTimestamp,proto3" json:"created_timestamp,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Counter) Reset() { *m = Counter{} } @@ -226,6 +227,13 @@ func (m *Counter) GetExemplar() *Exemplar { return nil } +func (m *Counter) GetCreatedTimestamp() *types.Timestamp { + if m != nil { + return m.CreatedTimestamp + } + return nil +} + type Quantile struct { Quantile float64 `protobuf:"fixed64,1,opt,name=quantile,proto3" json:"quantile,omitempty"` Value float64 `protobuf:"fixed64,2,opt,name=value,proto3" json:"value,omitempty"` @@ -282,12 +290,13 @@ func (m *Quantile) GetValue() float64 { } type Summary struct { - SampleCount uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount,proto3" json:"sample_count,omitempty"` - SampleSum float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum,proto3" json:"sample_sum,omitempty"` - Quantile []Quantile `protobuf:"bytes,3,rep,name=quantile,proto3" json:"quantile"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + SampleCount uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount,proto3" json:"sample_count,omitempty"` + SampleSum float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum,proto3" json:"sample_sum,omitempty"` + Quantile []Quantile `protobuf:"bytes,3,rep,name=quantile,proto3" json:"quantile"` + CreatedTimestamp *types.Timestamp `protobuf:"bytes,4,opt,name=created_timestamp,json=createdTimestamp,proto3" json:"created_timestamp,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Summary) Reset() { *m = Summary{} } @@ -344,6 +353,13 @@ func (m *Summary) GetQuantile() []Quantile { return nil } +func (m *Summary) GetCreatedTimestamp() *types.Timestamp { + if m != nil { + return m.CreatedTimestamp + } + return nil +} + type Untyped struct { Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` @@ -395,8 +411,9 @@ type Histogram struct { SampleCount uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount,proto3" json:"sample_count,omitempty"` SampleCountFloat float64 `protobuf:"fixed64,4,opt,name=sample_count_float,json=sampleCountFloat,proto3" json:"sample_count_float,omitempty"` SampleSum float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum,proto3" json:"sample_sum,omitempty"` - // Buckets for the conventional histogram. - Bucket []Bucket `protobuf:"bytes,3,rep,name=bucket,proto3" json:"bucket"` + // Buckets for the classic histogram. + Bucket []Bucket `protobuf:"bytes,3,rep,name=bucket,proto3" json:"bucket"` + CreatedTimestamp *types.Timestamp `protobuf:"bytes,15,opt,name=created_timestamp,json=createdTimestamp,proto3" json:"created_timestamp,omitempty"` // schema defines the bucket schema. Currently, valid numbers are -4 <= n <= 8. // They are all for base-2 bucket schemas, where 1 is a bucket boundary in each case, and // then each power of two is divided into 2^n logarithmic buckets. @@ -414,15 +431,20 @@ type Histogram struct { NegativeDelta []int64 `protobuf:"zigzag64,10,rep,packed,name=negative_delta,json=negativeDelta,proto3" json:"negative_delta,omitempty"` NegativeCount []float64 `protobuf:"fixed64,11,rep,packed,name=negative_count,json=negativeCount,proto3" json:"negative_count,omitempty"` // Positive buckets for the native histogram. + // Use a no-op span (offset 0, length 0) for a native histogram without any + // observations yet and with a zero_threshold of 0. Otherwise, it would be + // indistinguishable from a classic histogram. PositiveSpan []BucketSpan `protobuf:"bytes,12,rep,name=positive_span,json=positiveSpan,proto3" json:"positive_span"` // Use either "positive_delta" or "positive_count", the former for // regular histograms with integer counts, the latter for float // histograms. - PositiveDelta []int64 `protobuf:"zigzag64,13,rep,packed,name=positive_delta,json=positiveDelta,proto3" json:"positive_delta,omitempty"` - PositiveCount []float64 `protobuf:"fixed64,14,rep,packed,name=positive_count,json=positiveCount,proto3" json:"positive_count,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + PositiveDelta []int64 `protobuf:"zigzag64,13,rep,packed,name=positive_delta,json=positiveDelta,proto3" json:"positive_delta,omitempty"` + PositiveCount []float64 `protobuf:"fixed64,14,rep,packed,name=positive_count,json=positiveCount,proto3" json:"positive_count,omitempty"` + // Only used for native histograms. These exemplars MUST have a timestamp. + Exemplars []*Exemplar `protobuf:"bytes,16,rep,name=exemplars,proto3" json:"exemplars,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Histogram) Reset() { *m = Histogram{} } @@ -486,6 +508,13 @@ func (m *Histogram) GetBucket() []Bucket { return nil } +func (m *Histogram) GetCreatedTimestamp() *types.Timestamp { + if m != nil { + return m.CreatedTimestamp + } + return nil +} + func (m *Histogram) GetSchema() int32 { if m != nil { return m.Schema @@ -556,6 +585,13 @@ func (m *Histogram) GetPositiveCount() []float64 { return nil } +func (m *Histogram) GetExemplars() []*Exemplar { + if m != nil { + return m.Exemplars + } + return nil +} + type Bucket struct { CumulativeCount uint64 `protobuf:"varint,1,opt,name=cumulative_count,json=cumulativeCount,proto3" json:"cumulative_count,omitempty"` CumulativeCountFloat float64 `protobuf:"fixed64,4,opt,name=cumulative_count_float,json=cumulativeCountFloat,proto3" json:"cumulative_count_float,omitempty"` @@ -851,6 +887,7 @@ type MetricFamily struct { Help string `protobuf:"bytes,2,opt,name=help,proto3" json:"help,omitempty"` Type MetricType `protobuf:"varint,3,opt,name=type,proto3,enum=io.prometheus.client.MetricType" json:"type,omitempty"` Metric []Metric `protobuf:"bytes,4,rep,name=metric,proto3" json:"metric"` + Unit string `protobuf:"bytes,5,opt,name=unit,proto3" json:"unit,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` @@ -917,6 +954,13 @@ func (m *MetricFamily) GetMetric() []Metric { return nil } +func (m *MetricFamily) GetUnit() string { + if m != nil { + return m.Unit + } + return "" +} + func init() { proto.RegisterEnum("io.prometheus.client.MetricType", MetricType_name, MetricType_value) proto.RegisterType((*LabelPair)(nil), "io.prometheus.client.LabelPair") @@ -938,65 +982,69 @@ func init() { } var fileDescriptor_d1e5ddb18987a258 = []byte{ - // 923 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0xdd, 0x8e, 0xdb, 0x44, - 0x18, 0xad, 0x1b, 0xe7, 0xc7, 0x5f, 0x36, 0xdb, 0x74, 0x88, 0x2a, 0x6b, 0x61, 0x37, 0xc1, 0x12, - 0xd2, 0x82, 0x50, 0x22, 0xa0, 0x08, 0x54, 0x40, 0x62, 0xb7, 0xdd, 0x6e, 0x51, 0x49, 0x5b, 0x26, - 0xc9, 0x45, 0xe1, 0xc2, 0x9a, 0x64, 0x67, 0x1d, 0x0b, 0xdb, 0x63, 0xec, 0x71, 0xc5, 0x72, 0xcf, - 0x25, 0xd7, 0xbc, 0x02, 0x4f, 0x82, 0x7a, 0xc9, 0x13, 0x20, 0xb4, 0xef, 0xc0, 0x3d, 0x9a, 0x3f, - 0x3b, 0x5b, 0x39, 0x85, 0x15, 0x77, 0x33, 0xc7, 0xe7, 0xfb, 0xe6, 0x9c, 0x99, 0xc9, 0x99, 0x80, - 0x17, 0xb2, 0x49, 0x9a, 0xb1, 0x98, 0xf2, 0x35, 0x2d, 0xf2, 0xc9, 0x2a, 0x0a, 0x69, 0xc2, 0x27, - 0x31, 0xe5, 0x59, 0xb8, 0xca, 0xc7, 0x69, 0xc6, 0x38, 0x43, 0x83, 0x90, 0x8d, 0x2b, 0xce, 0x58, - 0x71, 0xf6, 0x06, 0x01, 0x0b, 0x98, 0x24, 0x4c, 0xc4, 0x48, 0x71, 0xf7, 0x86, 0x01, 0x63, 0x41, - 0x44, 0x27, 0x72, 0xb6, 0x2c, 0xce, 0x27, 0x3c, 0x8c, 0x69, 0xce, 0x49, 0x9c, 0x2a, 0x82, 0xf7, - 0x31, 0x38, 0x5f, 0x93, 0x25, 0x8d, 0x9e, 0x91, 0x30, 0x43, 0x08, 0xec, 0x84, 0xc4, 0xd4, 0xb5, - 0x46, 0xd6, 0xa1, 0x83, 0xe5, 0x18, 0x0d, 0xa0, 0xf9, 0x82, 0x44, 0x05, 0x75, 0x6f, 0x4a, 0x50, - 0x4d, 0xbc, 0x7d, 0x68, 0x9e, 0x92, 0x22, 0xd8, 0xf8, 0x2c, 0x6a, 0x2c, 0xf3, 0xf9, 0x3b, 0x68, - 0xdf, 0x67, 0x45, 0xc2, 0x69, 0x56, 0x4f, 0x40, 0xf7, 0xa0, 0x43, 0x7f, 0xa4, 0x71, 0x1a, 0x91, - 0x4c, 0x36, 0xee, 0x7e, 0x78, 0x30, 0xae, 0xb3, 0x35, 0x3e, 0xd1, 0x2c, 0x5c, 0xf2, 0xbd, 0xcf, - 0xa1, 0xf3, 0x4d, 0x41, 0x12, 0x1e, 0x46, 0x14, 0xed, 0x41, 0xe7, 0x07, 0x3d, 0xd6, 0x0b, 0x94, - 0xf3, 0xab, 0xca, 0x4b, 0x69, 0xbf, 0x58, 0xd0, 0x9e, 0x15, 0x71, 0x4c, 0xb2, 0x0b, 0xf4, 0x36, - 0xec, 0xe4, 0x24, 0x4e, 0x23, 0xea, 0xaf, 0x84, 0x5a, 0xd9, 0xc1, 0xc6, 0x5d, 0x85, 0x49, 0x03, - 0x68, 0x1f, 0x40, 0x53, 0xf2, 0x22, 0xd6, 0x9d, 0x1c, 0x85, 0xcc, 0x8a, 0x18, 0x7d, 0xb9, 0xb1, - 0x7e, 0x63, 0xd4, 0xd8, 0xee, 0xc3, 0x28, 0x3e, 0xb6, 0x5f, 0xfe, 0x39, 0xbc, 0x51, 0xa9, 0xf4, - 0x86, 0xd0, 0x5e, 0x24, 0xfc, 0x22, 0xa5, 0x67, 0x5b, 0xf6, 0xf2, 0x6f, 0x1b, 0x9c, 0x47, 0x61, - 0xce, 0x59, 0x90, 0x91, 0xf8, 0xbf, 0x48, 0x7e, 0x1f, 0xd0, 0x26, 0xc5, 0x3f, 0x8f, 0x18, 0xe1, - 0xae, 0x2d, 0x7b, 0xf6, 0x37, 0x88, 0x0f, 0x05, 0xfe, 0x6f, 0x06, 0xef, 0x41, 0x6b, 0x59, 0xac, - 0xbe, 0xa7, 0x5c, 0xdb, 0x7b, 0xab, 0xde, 0xde, 0xb1, 0xe4, 0x68, 0x73, 0xba, 0x02, 0xdd, 0x81, - 0x56, 0xbe, 0x5a, 0xd3, 0x98, 0xb8, 0xcd, 0x91, 0x75, 0x78, 0x1b, 0xeb, 0x19, 0x7a, 0x07, 0x76, - 0x7f, 0xa2, 0x19, 0xf3, 0xf9, 0x3a, 0xa3, 0xf9, 0x9a, 0x45, 0x67, 0x6e, 0x4b, 0x2e, 0xdb, 0x13, - 0xe8, 0xdc, 0x80, 0x42, 0x99, 0xa4, 0x29, 0xa3, 0x6d, 0x69, 0xd4, 0x11, 0x88, 0xb2, 0x79, 0x08, - 0xfd, 0xea, 0xb3, 0x36, 0xd9, 0x91, 0x7d, 0x76, 0x4b, 0x92, 0xb2, 0xf8, 0x18, 0x7a, 0x09, 0x0d, - 0x08, 0x0f, 0x5f, 0x50, 0x3f, 0x4f, 0x49, 0xe2, 0x3a, 0xd2, 0xca, 0xe8, 0x75, 0x56, 0x66, 0x29, - 0x49, 0xb4, 0x9d, 0x1d, 0x53, 0x2c, 0x30, 0x21, 0xbe, 0x6c, 0x76, 0x46, 0x23, 0x4e, 0x5c, 0x18, - 0x35, 0x0e, 0x11, 0x2e, 0x97, 0x78, 0x20, 0xc0, 0x2b, 0x34, 0x65, 0xa0, 0x3b, 0x6a, 0x08, 0x8f, - 0x06, 0x55, 0x26, 0x1e, 0x43, 0x2f, 0x65, 0x79, 0x58, 0x49, 0xdb, 0xb9, 0x9e, 0x34, 0x53, 0x6c, - 0xa4, 0x95, 0xcd, 0x94, 0xb4, 0x9e, 0x92, 0x66, 0xd0, 0x52, 0x5a, 0x49, 0x53, 0xd2, 0x76, 0x95, - 0x34, 0x83, 0x4a, 0x69, 0xde, 0xef, 0x16, 0xb4, 0xd4, 0x82, 0xe8, 0x5d, 0xe8, 0xaf, 0x8a, 0xb8, - 0x88, 0x36, 0xed, 0xa8, 0x8b, 0x77, 0xab, 0xc2, 0x95, 0xa1, 0xbb, 0x70, 0xe7, 0x55, 0xea, 0x95, - 0x0b, 0x38, 0x78, 0xa5, 0x40, 0x9d, 0xd0, 0x10, 0xba, 0x45, 0x9a, 0xd2, 0xcc, 0x5f, 0xb2, 0x22, - 0x39, 0xd3, 0xb7, 0x10, 0x24, 0x74, 0x2c, 0x90, 0x2b, 0x79, 0xd1, 0xb8, 0x76, 0x5e, 0x40, 0xb5, - 0x71, 0xe2, 0x52, 0xb2, 0xf3, 0xf3, 0x9c, 0x2a, 0x07, 0xb7, 0xb1, 0x9e, 0x09, 0x3c, 0xa2, 0x49, - 0xc0, 0xd7, 0x72, 0xf5, 0x1e, 0xd6, 0x33, 0xef, 0x57, 0x0b, 0x3a, 0xa6, 0x29, 0xfa, 0x0c, 0x9a, - 0x91, 0x48, 0x4b, 0xd7, 0x92, 0xc7, 0x34, 0xac, 0xd7, 0x50, 0x06, 0xaa, 0x3e, 0x25, 0x55, 0x53, - 0x9f, 0x47, 0xe8, 0x53, 0x70, 0xca, 0x4c, 0xd6, 0xd6, 0xf6, 0xc6, 0x2a, 0xb5, 0xc7, 0x26, 0xb5, - 0xc7, 0x73, 0xc3, 0xc0, 0x15, 0xd9, 0xfb, 0xb9, 0x01, 0xad, 0xa9, 0x7c, 0x19, 0xfe, 0x9f, 0xae, - 0x0f, 0xa0, 0x19, 0x88, 0x2c, 0xd7, 0x41, 0xfc, 0x66, 0x7d, 0xb1, 0x8c, 0x7b, 0xac, 0x98, 0xe8, - 0x13, 0x68, 0xaf, 0x54, 0xbe, 0x6b, 0xc9, 0xfb, 0xf5, 0x45, 0xfa, 0x11, 0xc0, 0x86, 0x2d, 0x0a, - 0x73, 0x15, 0xbe, 0xf2, 0x3e, 0x6c, 0x2d, 0xd4, 0x09, 0x8d, 0x0d, 0x5b, 0x14, 0x16, 0x2a, 0x26, - 0x65, 0x98, 0x6c, 0x2d, 0xd4, 0x59, 0x8a, 0x0d, 0x1b, 0x7d, 0x01, 0xce, 0xda, 0xa4, 0xa7, 0x0c, - 0x91, 0xad, 0xdb, 0x53, 0x86, 0x2c, 0xae, 0x2a, 0x44, 0xde, 0x96, 0x3b, 0xee, 0xc7, 0xb9, 0x4c, - 0xaa, 0x06, 0xee, 0x96, 0xd8, 0x34, 0xf7, 0x7e, 0xb3, 0x60, 0x47, 0x9d, 0xc3, 0x43, 0x12, 0x87, - 0xd1, 0x45, 0xed, 0x33, 0x8a, 0xc0, 0x5e, 0xd3, 0x28, 0xd5, 0xaf, 0xa8, 0x1c, 0xa3, 0xbb, 0x60, - 0x0b, 0x8d, 0x72, 0x0b, 0x77, 0xb7, 0xfd, 0xe6, 0x55, 0xe7, 0xf9, 0x45, 0x4a, 0xb1, 0x64, 0x8b, - 0x44, 0x56, 0xff, 0x07, 0x5c, 0xfb, 0x75, 0x89, 0xac, 0xea, 0x4c, 0x22, 0xab, 0x8a, 0xf7, 0x96, - 0x00, 0x55, 0x3f, 0xd4, 0x85, 0xf6, 0xfd, 0xa7, 0x8b, 0x27, 0xf3, 0x13, 0xdc, 0xbf, 0x81, 0x1c, - 0x68, 0x9e, 0x1e, 0x2d, 0x4e, 0x4f, 0xfa, 0x96, 0xc0, 0x67, 0x8b, 0xe9, 0xf4, 0x08, 0x3f, 0xef, - 0xdf, 0x14, 0x93, 0xc5, 0x93, 0xf9, 0xf3, 0x67, 0x27, 0x0f, 0xfa, 0x0d, 0xd4, 0x03, 0xe7, 0xd1, - 0x57, 0xb3, 0xf9, 0xd3, 0x53, 0x7c, 0x34, 0xed, 0xdb, 0xe8, 0x0d, 0xb8, 0x25, 0x6b, 0xfc, 0x0a, - 0x6c, 0x1e, 0x7b, 0x2f, 0x2f, 0x0f, 0xac, 0x3f, 0x2e, 0x0f, 0xac, 0xbf, 0x2e, 0x0f, 0xac, 0x6f, - 0x07, 0x21, 0xf3, 0x2b, 0x71, 0xbe, 0x12, 0xb7, 0x6c, 0xc9, 0x9b, 0xfd, 0xd1, 0x3f, 0x01, 0x00, - 0x00, 0xff, 0xff, 0x52, 0x2d, 0xb5, 0x31, 0xef, 0x08, 0x00, 0x00, + // 982 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0x4d, 0x8f, 0xdb, 0x44, + 0x18, 0xae, 0x9b, 0x4f, 0xbf, 0xd9, 0x6c, 0xbd, 0x43, 0x54, 0x59, 0x0b, 0xbb, 0x09, 0x96, 0x90, + 0x16, 0x84, 0x12, 0x01, 0x45, 0xa0, 0xb2, 0x48, 0xec, 0xb6, 0xdb, 0x14, 0x95, 0xb4, 0x65, 0x92, + 0x1c, 0xca, 0xc5, 0x9a, 0x24, 0xb3, 0x8e, 0x85, 0xbf, 0xb0, 0xc7, 0x15, 0xcb, 0x9d, 0xdf, 0xc0, + 0x1f, 0xe0, 0x67, 0x70, 0x46, 0x3d, 0x72, 0xe2, 0x88, 0xd0, 0xfe, 0x0e, 0x0e, 0x68, 0xbe, 0xec, + 0x6c, 0xe5, 0x2c, 0x2c, 0xdc, 0x3c, 0x8f, 0x9f, 0x67, 0xe6, 0x79, 0x1f, 0xdb, 0xef, 0x6b, 0x70, + 0xfc, 0x78, 0x94, 0xa4, 0x71, 0x48, 0xd9, 0x9a, 0xe6, 0xd9, 0x68, 0x19, 0xf8, 0x34, 0x62, 0xa3, + 0x90, 0xb2, 0xd4, 0x5f, 0x66, 0xc3, 0x24, 0x8d, 0x59, 0x8c, 0x7a, 0x7e, 0x3c, 0x2c, 0x39, 0x43, + 0xc9, 0xd9, 0xef, 0x79, 0xb1, 0x17, 0x0b, 0xc2, 0x88, 0x5f, 0x49, 0xee, 0x7e, 0xdf, 0x8b, 0x63, + 0x2f, 0xa0, 0x23, 0xb1, 0x5a, 0xe4, 0xe7, 0x23, 0xe6, 0x87, 0x34, 0x63, 0x24, 0x4c, 0x24, 0xc1, + 0xf9, 0x18, 0xcc, 0xaf, 0xc8, 0x82, 0x06, 0xcf, 0x89, 0x9f, 0x22, 0x04, 0xf5, 0x88, 0x84, 0xd4, + 0x36, 0x06, 0xc6, 0x91, 0x89, 0xc5, 0x35, 0xea, 0x41, 0xe3, 0x25, 0x09, 0x72, 0x6a, 0xdf, 0x16, + 0xa0, 0x5c, 0x38, 0x07, 0xd0, 0x18, 0x93, 0xdc, 0xdb, 0xb8, 0xcd, 0x35, 0x86, 0xbe, 0xfd, 0xb3, + 0x01, 0xad, 0x07, 0x71, 0x1e, 0x31, 0x9a, 0x56, 0x33, 0xd0, 0x7d, 0x68, 0xd3, 0xef, 0x69, 0x98, + 0x04, 0x24, 0x15, 0x3b, 0x77, 0x3e, 0x3c, 0x1c, 0x56, 0xd5, 0x35, 0x3c, 0x53, 0x2c, 0x5c, 0xf0, + 0xd1, 0x18, 0xf6, 0x96, 0x29, 0x25, 0x8c, 0xae, 0xdc, 0xa2, 0x1c, 0xbb, 0x26, 0x36, 0xd9, 0x1f, + 0xca, 0x82, 0x87, 0xba, 0xe0, 0xe1, 0x4c, 0x33, 0xb0, 0xa5, 0x44, 0x05, 0xe2, 0x1c, 0x43, 0xfb, + 0xeb, 0x9c, 0x44, 0xcc, 0x0f, 0x28, 0xda, 0x87, 0xf6, 0x77, 0xea, 0x5a, 0x39, 0x2d, 0xd6, 0x57, + 0x33, 0x28, 0x8a, 0xfc, 0xdd, 0x80, 0xd6, 0x34, 0x0f, 0x43, 0x92, 0x5e, 0xa0, 0xb7, 0x61, 0x27, + 0x23, 0x61, 0x12, 0x50, 0x77, 0xc9, 0xcb, 0x16, 0x3b, 0xd4, 0x71, 0x47, 0x62, 0x22, 0x09, 0x74, + 0x00, 0xa0, 0x28, 0x59, 0x1e, 0xaa, 0x9d, 0x4c, 0x89, 0x4c, 0xf3, 0x10, 0x7d, 0xb1, 0x71, 0x7e, + 0x6d, 0x50, 0xdb, 0x1e, 0x88, 0x76, 0x7c, 0x5a, 0x7f, 0xf5, 0x47, 0xff, 0xd6, 0x86, 0xcb, 0xca, + 0x58, 0xea, 0xff, 0x21, 0x96, 0x3e, 0xb4, 0xe6, 0x11, 0xbb, 0x48, 0xe8, 0x6a, 0xcb, 0xe3, 0xfd, + 0xab, 0x01, 0xe6, 0x63, 0x3f, 0x63, 0xb1, 0x97, 0x92, 0xf0, 0xdf, 0xd4, 0xfe, 0x3e, 0xa0, 0x4d, + 0x8a, 0x7b, 0x1e, 0xc4, 0x84, 0x09, 0x6f, 0x06, 0xb6, 0x36, 0x88, 0x8f, 0x38, 0xfe, 0x4f, 0x49, + 0xdd, 0x87, 0xe6, 0x22, 0x5f, 0x7e, 0x4b, 0x99, 0xca, 0xe9, 0xad, 0xea, 0x9c, 0x4e, 0x05, 0x47, + 0xa5, 0xa4, 0x14, 0xd5, 0x19, 0xdd, 0xb9, 0x79, 0x46, 0xe8, 0x2e, 0x34, 0xb3, 0xe5, 0x9a, 0x86, + 0xc4, 0x6e, 0x0c, 0x8c, 0xa3, 0x3d, 0xac, 0x56, 0xe8, 0x1d, 0xd8, 0xfd, 0x81, 0xa6, 0xb1, 0xcb, + 0xd6, 0x29, 0xcd, 0xd6, 0x71, 0xb0, 0xb2, 0x9b, 0xc2, 0x7f, 0x97, 0xa3, 0x33, 0x0d, 0xf2, 0x12, + 0x05, 0x4d, 0x26, 0xd6, 0x12, 0x89, 0x99, 0x1c, 0x91, 0x79, 0x1d, 0x81, 0x55, 0xde, 0x56, 0x69, + 0xb5, 0xc5, 0x3e, 0xbb, 0x05, 0x49, 0x66, 0xf5, 0x04, 0xba, 0x11, 0xf5, 0x08, 0xf3, 0x5f, 0x52, + 0x37, 0x4b, 0x48, 0x64, 0x9b, 0x22, 0x93, 0xc1, 0x75, 0x99, 0x4c, 0x13, 0x12, 0xa9, 0x5c, 0x76, + 0xb4, 0x98, 0x63, 0xdc, 0x7c, 0xb1, 0xd9, 0x8a, 0x06, 0x8c, 0xd8, 0x30, 0xa8, 0x1d, 0x21, 0x5c, + 0x1c, 0xf1, 0x90, 0x83, 0x57, 0x68, 0xb2, 0x80, 0xce, 0xa0, 0xc6, 0x6b, 0xd4, 0xa8, 0x2c, 0xe2, + 0x09, 0x74, 0x93, 0x38, 0xf3, 0x4b, 0x6b, 0x3b, 0x37, 0xb3, 0xa6, 0xc5, 0xda, 0x5a, 0xb1, 0x99, + 0xb4, 0xd6, 0x95, 0xd6, 0x34, 0x5a, 0x58, 0x2b, 0x68, 0xd2, 0xda, 0xae, 0xb4, 0xa6, 0x51, 0x69, + 0xed, 0x18, 0x4c, 0xdd, 0x4d, 0x32, 0xdb, 0xba, 0xee, 0x6b, 0x2b, 0xda, 0x4f, 0x29, 0x70, 0x7e, + 0x35, 0xa0, 0x29, 0xed, 0xa2, 0x77, 0xc1, 0x5a, 0xe6, 0x61, 0x1e, 0x6c, 0x86, 0x21, 0xdf, 0xff, + 0x3b, 0x25, 0x2e, 0xcf, 0xbc, 0x07, 0x77, 0x5f, 0xa7, 0x5e, 0xf9, 0x0e, 0x7a, 0xaf, 0x09, 0xe4, + 0xf3, 0xed, 0x43, 0x27, 0x4f, 0x12, 0x9a, 0xba, 0x8b, 0x38, 0x8f, 0x56, 0xea, 0x63, 0x00, 0x01, + 0x9d, 0x72, 0xe4, 0x4a, 0x23, 0xad, 0xdd, 0xac, 0x91, 0x3a, 0xc7, 0x00, 0x65, 0xec, 0xfc, 0x95, + 0x8e, 0xcf, 0xcf, 0x33, 0x2a, 0x2b, 0xd8, 0xc3, 0x6a, 0xc5, 0xf1, 0x80, 0x46, 0x1e, 0x5b, 0x8b, + 0xd3, 0xbb, 0x58, 0xad, 0x9c, 0x9f, 0x0c, 0x68, 0xeb, 0x4d, 0xd1, 0x67, 0xd0, 0x08, 0xf8, 0x1c, + 0xb1, 0x0d, 0x91, 0x66, 0xbf, 0xda, 0x43, 0x31, 0x6a, 0xd4, 0x33, 0x96, 0x9a, 0xea, 0xfe, 0x8a, + 0x3e, 0x05, 0xf3, 0x26, 0xed, 0xbd, 0x24, 0x3b, 0x3f, 0xd6, 0xa0, 0x39, 0x11, 0x33, 0xf3, 0xff, + 0xf9, 0xfa, 0x00, 0x1a, 0x1e, 0x9f, 0x72, 0x6a, 0x42, 0xbd, 0x59, 0x2d, 0x16, 0x83, 0x10, 0x4b, + 0x26, 0xfa, 0x04, 0x5a, 0x4b, 0x39, 0xf8, 0x94, 0xe5, 0x83, 0x6a, 0x91, 0x9a, 0x8e, 0x58, 0xb3, + 0xb9, 0x30, 0x93, 0xc3, 0x44, 0xf5, 0xec, 0x2d, 0x42, 0x35, 0x71, 0xb0, 0x66, 0x73, 0x61, 0x2e, + 0xbb, 0xb5, 0x68, 0x45, 0x5b, 0x85, 0xaa, 0xa5, 0x63, 0xcd, 0x46, 0x9f, 0x83, 0xb9, 0xd6, 0x4d, + 0x5c, 0xb4, 0xa0, 0xad, 0xf1, 0x14, 0xbd, 0x1e, 0x97, 0x0a, 0xde, 0xf6, 0x8b, 0xc4, 0xdd, 0x30, + 0x13, 0x7d, 0xae, 0x86, 0x3b, 0x05, 0x36, 0xc9, 0x9c, 0x5f, 0x0c, 0xd8, 0x91, 0xcf, 0xe1, 0x11, + 0x09, 0xfd, 0xe0, 0xa2, 0xf2, 0x07, 0x03, 0x41, 0x7d, 0x4d, 0x83, 0x44, 0xfd, 0x5f, 0x88, 0x6b, + 0x74, 0x0f, 0xea, 0xdc, 0xa3, 0x88, 0x70, 0x77, 0x5b, 0xc7, 0x90, 0x3b, 0xcf, 0x2e, 0x12, 0x8a, + 0x05, 0x9b, 0x0f, 0x06, 0xf9, 0xa7, 0x64, 0xd7, 0xaf, 0x1b, 0x0c, 0x52, 0xa7, 0x07, 0x83, 0x54, + 0x70, 0x17, 0x79, 0xe4, 0x33, 0x11, 0xa1, 0x89, 0xc5, 0xf5, 0x7b, 0x0b, 0x80, 0xf2, 0x0c, 0xd4, + 0x81, 0xd6, 0x83, 0x67, 0xf3, 0xa7, 0xb3, 0x33, 0x6c, 0xdd, 0x42, 0x26, 0x34, 0xc6, 0x27, 0xf3, + 0xf1, 0x99, 0x65, 0x70, 0x7c, 0x3a, 0x9f, 0x4c, 0x4e, 0xf0, 0x0b, 0xeb, 0x36, 0x5f, 0xcc, 0x9f, + 0xce, 0x5e, 0x3c, 0x3f, 0x7b, 0x68, 0xd5, 0x50, 0x17, 0xcc, 0xc7, 0x5f, 0x4e, 0x67, 0xcf, 0xc6, + 0xf8, 0x64, 0x62, 0xd5, 0xd1, 0x1b, 0x70, 0x47, 0x68, 0xdc, 0x12, 0x6c, 0x9c, 0x3a, 0xaf, 0x2e, + 0x0f, 0x8d, 0xdf, 0x2e, 0x0f, 0x8d, 0x3f, 0x2f, 0x0f, 0x8d, 0x6f, 0x7a, 0x7e, 0xec, 0x96, 0x86, + 0x5d, 0x69, 0x78, 0xd1, 0x14, 0x6f, 0xfb, 0x47, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0x1c, 0xe1, + 0xcf, 0xb8, 0x1d, 0x0a, 0x00, 0x00, } func (m *LabelPair) Marshal() (dAtA []byte, err error) { @@ -1097,6 +1145,18 @@ func (m *Counter) MarshalToSizedBuffer(dAtA []byte) (int, error) { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) } + if m.CreatedTimestamp != nil { + { + size, err := m.CreatedTimestamp.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMetrics(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } if m.Exemplar != nil { { size, err := m.Exemplar.MarshalToSizedBuffer(dAtA[:i]) @@ -1181,6 +1241,18 @@ func (m *Summary) MarshalToSizedBuffer(dAtA []byte) (int, error) { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) } + if m.CreatedTimestamp != nil { + { + size, err := m.CreatedTimestamp.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMetrics(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } if len(m.Quantile) > 0 { for iNdEx := len(m.Quantile) - 1; iNdEx >= 0; iNdEx-- { { @@ -1266,32 +1338,60 @@ func (m *Histogram) MarshalToSizedBuffer(dAtA []byte) (int, error) { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) } + if len(m.Exemplars) > 0 { + for iNdEx := len(m.Exemplars) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Exemplars[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMetrics(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x82 + } + } + if m.CreatedTimestamp != nil { + { + size, err := m.CreatedTimestamp.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMetrics(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x7a + } if len(m.PositiveCount) > 0 { for iNdEx := len(m.PositiveCount) - 1; iNdEx >= 0; iNdEx-- { - f2 := math.Float64bits(float64(m.PositiveCount[iNdEx])) + f5 := math.Float64bits(float64(m.PositiveCount[iNdEx])) i -= 8 - encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(f2)) + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(f5)) } i = encodeVarintMetrics(dAtA, i, uint64(len(m.PositiveCount)*8)) i-- dAtA[i] = 0x72 } if len(m.PositiveDelta) > 0 { - var j3 int - dAtA5 := make([]byte, len(m.PositiveDelta)*10) + var j6 int + dAtA8 := make([]byte, len(m.PositiveDelta)*10) for _, num := range m.PositiveDelta { - x4 := (uint64(num) << 1) ^ uint64((num >> 63)) - for x4 >= 1<<7 { - dAtA5[j3] = uint8(uint64(x4)&0x7f | 0x80) - j3++ - x4 >>= 7 - } - dAtA5[j3] = uint8(x4) - j3++ - } - i -= j3 - copy(dAtA[i:], dAtA5[:j3]) - i = encodeVarintMetrics(dAtA, i, uint64(j3)) + x7 := (uint64(num) << 1) ^ uint64((num >> 63)) + for x7 >= 1<<7 { + dAtA8[j6] = uint8(uint64(x7)&0x7f | 0x80) + j6++ + x7 >>= 7 + } + dAtA8[j6] = uint8(x7) + j6++ + } + i -= j6 + copy(dAtA[i:], dAtA8[:j6]) + i = encodeVarintMetrics(dAtA, i, uint64(j6)) i-- dAtA[i] = 0x6a } @@ -1311,30 +1411,30 @@ func (m *Histogram) MarshalToSizedBuffer(dAtA []byte) (int, error) { } if len(m.NegativeCount) > 0 { for iNdEx := len(m.NegativeCount) - 1; iNdEx >= 0; iNdEx-- { - f6 := math.Float64bits(float64(m.NegativeCount[iNdEx])) + f9 := math.Float64bits(float64(m.NegativeCount[iNdEx])) i -= 8 - encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(f6)) + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(f9)) } i = encodeVarintMetrics(dAtA, i, uint64(len(m.NegativeCount)*8)) i-- dAtA[i] = 0x5a } if len(m.NegativeDelta) > 0 { - var j7 int - dAtA9 := make([]byte, len(m.NegativeDelta)*10) + var j10 int + dAtA12 := make([]byte, len(m.NegativeDelta)*10) for _, num := range m.NegativeDelta { - x8 := (uint64(num) << 1) ^ uint64((num >> 63)) - for x8 >= 1<<7 { - dAtA9[j7] = uint8(uint64(x8)&0x7f | 0x80) - j7++ - x8 >>= 7 - } - dAtA9[j7] = uint8(x8) - j7++ - } - i -= j7 - copy(dAtA[i:], dAtA9[:j7]) - i = encodeVarintMetrics(dAtA, i, uint64(j7)) + x11 := (uint64(num) << 1) ^ uint64((num >> 63)) + for x11 >= 1<<7 { + dAtA12[j10] = uint8(uint64(x11)&0x7f | 0x80) + j10++ + x11 >>= 7 + } + dAtA12[j10] = uint8(x11) + j10++ + } + i -= j10 + copy(dAtA[i:], dAtA12[:j10]) + i = encodeVarintMetrics(dAtA, i, uint64(j10)) i-- dAtA[i] = 0x52 } @@ -1690,6 +1790,13 @@ func (m *MetricFamily) MarshalToSizedBuffer(dAtA []byte) (int, error) { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) } + if len(m.Unit) > 0 { + i -= len(m.Unit) + copy(dAtA[i:], m.Unit) + i = encodeVarintMetrics(dAtA, i, uint64(len(m.Unit))) + i-- + dAtA[i] = 0x2a + } if len(m.Metric) > 0 { for iNdEx := len(m.Metric) - 1; iNdEx >= 0; iNdEx-- { { @@ -1785,6 +1892,10 @@ func (m *Counter) Size() (n int) { l = m.Exemplar.Size() n += 1 + l + sovMetrics(uint64(l)) } + if m.CreatedTimestamp != nil { + l = m.CreatedTimestamp.Size() + n += 1 + l + sovMetrics(uint64(l)) + } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } @@ -1827,6 +1938,10 @@ func (m *Summary) Size() (n int) { n += 1 + l + sovMetrics(uint64(l)) } } + if m.CreatedTimestamp != nil { + l = m.CreatedTimestamp.Size() + n += 1 + l + sovMetrics(uint64(l)) + } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } @@ -1913,6 +2028,16 @@ func (m *Histogram) Size() (n int) { if len(m.PositiveCount) > 0 { n += 1 + sovMetrics(uint64(len(m.PositiveCount)*8)) + len(m.PositiveCount)*8 } + if m.CreatedTimestamp != nil { + l = m.CreatedTimestamp.Size() + n += 1 + l + sovMetrics(uint64(l)) + } + if len(m.Exemplars) > 0 { + for _, e := range m.Exemplars { + l = e.Size() + n += 2 + l + sovMetrics(uint64(l)) + } + } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } @@ -2051,6 +2176,10 @@ func (m *MetricFamily) Size() (n int) { n += 1 + l + sovMetrics(uint64(l)) } } + l = len(m.Unit) + if l > 0 { + n += 1 + l + sovMetrics(uint64(l)) + } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } @@ -2316,6 +2445,42 @@ func (m *Counter) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CreatedTimestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMetrics + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMetrics + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMetrics + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CreatedTimestamp == nil { + m.CreatedTimestamp = &types.Timestamp{} + } + if err := m.CreatedTimestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipMetrics(dAtA[iNdEx:]) @@ -2504,6 +2669,42 @@ func (m *Summary) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CreatedTimestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMetrics + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMetrics + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMetrics + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CreatedTimestamp == nil { + m.CreatedTimestamp = &types.Timestamp{} + } + if err := m.CreatedTimestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipMetrics(dAtA[iNdEx:]) @@ -3086,6 +3287,76 @@ func (m *Histogram) Unmarshal(dAtA []byte) error { } else { return fmt.Errorf("proto: wrong wireType = %d for field PositiveCount", wireType) } + case 15: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CreatedTimestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMetrics + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMetrics + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMetrics + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CreatedTimestamp == nil { + m.CreatedTimestamp = &types.Timestamp{} + } + if err := m.CreatedTimestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 16: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Exemplars", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMetrics + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMetrics + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMetrics + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Exemplars = append(m.Exemplars, &Exemplar{}) + if err := m.Exemplars[len(m.Exemplars)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipMetrics(dAtA[iNdEx:]) @@ -3889,6 +4160,38 @@ func (m *MetricFamily) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Unit", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMetrics + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthMetrics + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthMetrics + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Unit = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipMetrics(dAtA[iNdEx:]) diff --git a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto index 6bbea622f..fe55638bb 100644 --- a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto +++ b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto @@ -51,6 +51,8 @@ message Gauge { message Counter { double value = 1; Exemplar exemplar = 2; + + google.protobuf.Timestamp created_timestamp = 3; } message Quantile { @@ -62,6 +64,8 @@ message Summary { uint64 sample_count = 1; double sample_sum = 2; repeated Quantile quantile = 3 [(gogoproto.nullable) = false]; + + google.protobuf.Timestamp created_timestamp = 4; } message Untyped { @@ -72,9 +76,11 @@ message Histogram { uint64 sample_count = 1; double sample_count_float = 4; // Overrides sample_count if > 0. double sample_sum = 2; - // Buckets for the conventional histogram. + // Buckets for the classic histogram. repeated Bucket bucket = 3 [(gogoproto.nullable) = false]; // Ordered in increasing order of upper_bound, +Inf bucket is optional. + google.protobuf.Timestamp created_timestamp = 15; + // Everything below here is for native histograms (also known as sparse histograms). // Native histograms are an experimental feature without stability guarantees. @@ -97,12 +103,18 @@ message Histogram { repeated double negative_count = 11; // Absolute count of each bucket. // Positive buckets for the native histogram. + // Use a no-op span (offset 0, length 0) for a native histogram without any + // observations yet and with a zero_threshold of 0. Otherwise, it would be + // indistinguishable from a classic histogram. repeated BucketSpan positive_span = 12 [(gogoproto.nullable) = false]; // Use either "positive_delta" or "positive_count", the former for // regular histograms with integer counts, the latter for float // histograms. repeated sint64 positive_delta = 13; // Count delta of each bucket compared to previous one (or to zero for 1st bucket). repeated double positive_count = 14; // Absolute count of each bucket. + + // Only used for native histograms. These exemplars MUST have a timestamp. + repeated Exemplar exemplars = 16; } message Bucket { @@ -144,4 +156,5 @@ message MetricFamily { string help = 2; MetricType type = 3; repeated Metric metric = 4 [(gogoproto.nullable) = false]; + string unit = 5; } diff --git a/vendor/github.com/prometheus/prometheus/prompb/types.pb.go b/vendor/github.com/prometheus/prometheus/prompb/types.pb.go index 125f868e9..93883daa1 100644 --- a/vendor/github.com/prometheus/prometheus/prompb/types.pb.go +++ b/vendor/github.com/prometheus/prometheus/prompb/types.pb.go @@ -164,7 +164,7 @@ func (Chunk_Encoding) EnumDescriptor() ([]byte, []int) { type MetricMetadata struct { // Represents the metric type, these match the set from Prometheus. - // Refer to model/textparse/interface.go for details. + // Refer to github.com/prometheus/common/model/metadata.go for details. Type MetricMetadata_MetricType `protobuf:"varint,1,opt,name=type,proto3,enum=prometheus.MetricMetadata_MetricType" json:"type,omitempty"` MetricFamilyName string `protobuf:"bytes,2,opt,name=metric_family_name,json=metricFamilyName,proto3" json:"metric_family_name,omitempty"` Help string `protobuf:"bytes,4,opt,name=help,proto3" json:"help,omitempty"` diff --git a/vendor/github.com/prometheus/prometheus/prompb/types.proto b/vendor/github.com/prometheus/prometheus/prompb/types.proto index aa322515c..61fc1e014 100644 --- a/vendor/github.com/prometheus/prometheus/prompb/types.proto +++ b/vendor/github.com/prometheus/prometheus/prompb/types.proto @@ -31,7 +31,7 @@ message MetricMetadata { } // Represents the metric type, these match the set from Prometheus. - // Refer to model/textparse/interface.go for details. + // Refer to github.com/prometheus/common/model/metadata.go for details. MetricType type = 1; string metric_family_name = 2; string help = 4; diff --git a/vendor/github.com/prometheus/prometheus/promql/engine.go b/vendor/github.com/prometheus/prometheus/promql/engine.go index cbeeb82a1..786b76e1f 100644 --- a/vendor/github.com/prometheus/prometheus/promql/engine.go +++ b/vendor/github.com/prometheus/prometheus/promql/engine.go @@ -24,6 +24,7 @@ import ( "runtime" "sort" "strconv" + "strings" "sync" "time" @@ -44,6 +45,7 @@ import ( "github.com/prometheus/prometheus/promql/parser" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" + "github.com/prometheus/prometheus/util/annotations" "github.com/prometheus/prometheus/util/stats" "github.com/prometheus/prometheus/util/zeropool" ) @@ -59,6 +61,14 @@ const ( maxInt64 = 9223372036854774784 // The smallest SampleValue that can be converted to an int64 without underflow. minInt64 = -9223372036854775808 + + // Max initial size for the pooled points slices. + // The getHPointSlice and getFPointSlice functions are called with an estimated size which often can be + // over-estimated. + maxPointsSliceSize = 5000 + + // The default buffer size for points used by the matrix selector. + matrixSelectorSliceSize = 16 ) type engineMetrics struct { @@ -130,11 +140,35 @@ type Query interface { String() string } -type QueryOpts struct { +type PrometheusQueryOpts struct { // Enables recording per-step statistics if the engine has it enabled as well. Disabled by default. - EnablePerStepStats bool + enablePerStepStats bool // Lookback delta duration for this query. - LookbackDelta time.Duration + lookbackDelta time.Duration +} + +var _ QueryOpts = &PrometheusQueryOpts{} + +func NewPrometheusQueryOpts(enablePerStepStats bool, lookbackDelta time.Duration) QueryOpts { + return &PrometheusQueryOpts{ + enablePerStepStats: enablePerStepStats, + lookbackDelta: lookbackDelta, + } +} + +func (p *PrometheusQueryOpts) EnablePerStepStats() bool { + return p.enablePerStepStats +} + +func (p *PrometheusQueryOpts) LookbackDelta() time.Duration { + return p.lookbackDelta +} + +type QueryOpts interface { + // Enables recording per-step statistics if the engine has it enabled as well. Disabled by default. + EnablePerStepStats() bool + // Lookback delta duration for this query. + LookbackDelta() time.Duration } // query implements the Query interface. @@ -408,69 +442,74 @@ func (ng *Engine) SetQueryLogger(l QueryLogger) { } // NewInstantQuery returns an evaluation query for the given expression at the given time. -func (ng *Engine) NewInstantQuery(_ context.Context, q storage.Queryable, opts *QueryOpts, qs string, ts time.Time) (Query, error) { - expr, err := parser.ParseExpr(qs) +func (ng *Engine) NewInstantQuery(ctx context.Context, q storage.Queryable, opts QueryOpts, qs string, ts time.Time) (Query, error) { + pExpr, qry := ng.newQuery(q, qs, opts, ts, ts, 0) + finishQueue, err := ng.queueActive(ctx, qry) if err != nil { return nil, err } - qry, err := ng.newQuery(q, opts, expr, ts, ts, 0) + defer finishQueue() + expr, err := parser.ParseExpr(qs) if err != nil { return nil, err } - qry.q = qs + if err := ng.validateOpts(expr); err != nil { + return nil, err + } + *pExpr = PreprocessExpr(expr, ts, ts) return qry, nil } // NewRangeQuery returns an evaluation query for the given time range and with // the resolution set by the interval. -func (ng *Engine) NewRangeQuery(_ context.Context, q storage.Queryable, opts *QueryOpts, qs string, start, end time.Time, interval time.Duration) (Query, error) { +func (ng *Engine) NewRangeQuery(ctx context.Context, q storage.Queryable, opts QueryOpts, qs string, start, end time.Time, interval time.Duration) (Query, error) { + pExpr, qry := ng.newQuery(q, qs, opts, start, end, interval) + finishQueue, err := ng.queueActive(ctx, qry) + if err != nil { + return nil, err + } + defer finishQueue() expr, err := parser.ParseExpr(qs) if err != nil { return nil, err } + if err := ng.validateOpts(expr); err != nil { + return nil, err + } if expr.Type() != parser.ValueTypeVector && expr.Type() != parser.ValueTypeScalar { return nil, fmt.Errorf("invalid expression type %q for range query, must be Scalar or instant Vector", parser.DocumentedType(expr.Type())) } - qry, err := ng.newQuery(q, opts, expr, start, end, interval) - if err != nil { - return nil, err - } - qry.q = qs + *pExpr = PreprocessExpr(expr, start, end) return qry, nil } -func (ng *Engine) newQuery(q storage.Queryable, opts *QueryOpts, expr parser.Expr, start, end time.Time, interval time.Duration) (*query, error) { - if err := ng.validateOpts(expr); err != nil { - return nil, err - } - - // Default to empty QueryOpts if not provided. +func (ng *Engine) newQuery(q storage.Queryable, qs string, opts QueryOpts, start, end time.Time, interval time.Duration) (*parser.Expr, *query) { if opts == nil { - opts = &QueryOpts{} + opts = NewPrometheusQueryOpts(false, 0) } - lookbackDelta := opts.LookbackDelta + lookbackDelta := opts.LookbackDelta() if lookbackDelta <= 0 { lookbackDelta = ng.lookbackDelta } es := &parser.EvalStmt{ - Expr: PreprocessExpr(expr, start, end), Start: start, End: end, Interval: interval, LookbackDelta: lookbackDelta, } qry := &query{ + q: qs, stmt: es, ng: ng, stats: stats.NewQueryTimers(), - sampleStats: stats.NewQuerySamples(ng.enablePerStepStats && opts.EnablePerStepStats), + sampleStats: stats.NewQuerySamples(ng.enablePerStepStats && opts.EnablePerStepStats()), queryable: q, } - return qry, nil + return &es.Expr, qry } var ( @@ -544,7 +583,7 @@ func (ng *Engine) newTestQuery(f func(context.Context) error) Query { // // At this point per query only one EvalStmt is evaluated. Alert and record // statements are not handled by the Engine. -func (ng *Engine) exec(ctx context.Context, q *query) (v parser.Value, ws storage.Warnings, err error) { +func (ng *Engine) exec(ctx context.Context, q *query) (v parser.Value, ws annotations.Annotations, err error) { ng.metrics.currentQueries.Inc() defer func() { ng.metrics.currentQueries.Dec() @@ -589,18 +628,11 @@ func (ng *Engine) exec(ctx context.Context, q *query) (v parser.Value, ws storag execSpanTimer, ctx := q.stats.GetSpanTimer(ctx, stats.ExecTotalTime) defer execSpanTimer.Finish() - queueSpanTimer, _ := q.stats.GetSpanTimer(ctx, stats.ExecQueueTime, ng.metrics.queryQueueTime) - // Log query in active log. The active log guarantees that we don't run over - // MaxConcurrent queries. - if ng.activeQueryTracker != nil { - queryIndex, err := ng.activeQueryTracker.Insert(ctx, q.q) - if err != nil { - queueSpanTimer.Finish() - return nil, nil, contextErr(err, "query queue") - } - defer ng.activeQueryTracker.Delete(queryIndex) + finishQueue, err := ng.queueActive(ctx, q) + if err != nil { + return nil, nil, err } - queueSpanTimer.Finish() + defer finishQueue() // Cancel when execution is done or an error was raised. defer q.cancel() @@ -623,6 +655,18 @@ func (ng *Engine) exec(ctx context.Context, q *query) (v parser.Value, ws storag panic(fmt.Errorf("promql.Engine.exec: unhandled statement of type %T", q.Statement())) } +// Log query in active log. The active log guarantees that we don't run over +// MaxConcurrent queries. +func (ng *Engine) queueActive(ctx context.Context, q *query) (func(), error) { + if ng.activeQueryTracker == nil { + return func() {}, nil + } + queueSpanTimer, _ := q.stats.GetSpanTimer(ctx, stats.ExecQueueTime, ng.metrics.queryQueueTime) + queryIndex, err := ng.activeQueryTracker.Insert(ctx, q.q) + queueSpanTimer.Finish() + return func() { ng.activeQueryTracker.Delete(queryIndex) }, err +} + func timeMilliseconds(t time.Time) int64 { return t.UnixNano() / int64(time.Millisecond/time.Nanosecond) } @@ -632,17 +676,17 @@ func durationMilliseconds(d time.Duration) int64 { } // execEvalStmt evaluates the expression of an evaluation statement for the given time range. -func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.EvalStmt) (parser.Value, storage.Warnings, error) { +func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.EvalStmt) (parser.Value, annotations.Annotations, error) { prepareSpanTimer, ctxPrepare := query.stats.GetSpanTimer(ctx, stats.QueryPreparationTime, ng.metrics.queryPrepareTime) - mint, maxt := ng.findMinMaxTime(s) - querier, err := query.queryable.Querier(ctxPrepare, mint, maxt) + mint, maxt := FindMinMaxTime(s) + querier, err := query.queryable.Querier(mint, maxt) if err != nil { prepareSpanTimer.Finish() return nil, nil, err } defer querier.Close() - ng.populateSeries(querier, s) + ng.populateSeries(ctxPrepare, querier, s) prepareSpanTimer.Finish() // Modify the offset of vector and matrix selectors for the @ modifier @@ -776,7 +820,10 @@ func subqueryTimes(path []parser.Node) (time.Duration, time.Duration, *int64) { return subqOffset, subqRange, tsp } -func (ng *Engine) findMinMaxTime(s *parser.EvalStmt) (int64, int64) { +// FindMinMaxTime returns the time in milliseconds of the earliest and latest point in time the statement will try to process. +// This takes into account offsets, @ modifiers, and range selectors. +// If the statement does not select series, then FindMinMaxTime returns (0, 0). +func FindMinMaxTime(s *parser.EvalStmt) (int64, int64) { var minTimestamp, maxTimestamp int64 = math.MaxInt64, math.MinInt64 // Whenever a MatrixSelector is evaluated, evalRange is set to the corresponding range. // The evaluation of the VectorSelector inside then evaluates the given range and unsets @@ -785,7 +832,7 @@ func (ng *Engine) findMinMaxTime(s *parser.EvalStmt) (int64, int64) { parser.Inspect(s.Expr, func(node parser.Node, path []parser.Node) error { switch n := node.(type) { case *parser.VectorSelector: - start, end := ng.getTimeRangesForSelector(s, n, path, evalRange) + start, end := getTimeRangesForSelector(s, n, path, evalRange) if start < minTimestamp { minTimestamp = start } @@ -808,7 +855,7 @@ func (ng *Engine) findMinMaxTime(s *parser.EvalStmt) (int64, int64) { return minTimestamp, maxTimestamp } -func (ng *Engine) getTimeRangesForSelector(s *parser.EvalStmt, n *parser.VectorSelector, path []parser.Node, evalRange time.Duration) (int64, int64) { +func getTimeRangesForSelector(s *parser.EvalStmt, n *parser.VectorSelector, path []parser.Node, evalRange time.Duration) (int64, int64) { start, end := timestamp.FromTime(s.Start), timestamp.FromTime(s.End) subqOffset, subqRange, subqTs := subqueryTimes(path) @@ -856,7 +903,7 @@ func (ng *Engine) getLastSubqueryInterval(path []parser.Node) time.Duration { return interval } -func (ng *Engine) populateSeries(querier storage.Querier, s *parser.EvalStmt) { +func (ng *Engine) populateSeries(ctx context.Context, querier storage.Querier, s *parser.EvalStmt) { // Whenever a MatrixSelector is evaluated, evalRange is set to the corresponding range. // The evaluation of the VectorSelector inside then evaluates the given range and unsets // the variable. @@ -865,7 +912,7 @@ func (ng *Engine) populateSeries(querier storage.Querier, s *parser.EvalStmt) { parser.Inspect(s.Expr, func(node parser.Node, path []parser.Node) error { switch n := node.(type) { case *parser.VectorSelector: - start, end := ng.getTimeRangesForSelector(s, n, path, evalRange) + start, end := getTimeRangesForSelector(s, n, path, evalRange) interval := ng.getLastSubqueryInterval(path) if interval == 0 { interval = s.Interval @@ -879,7 +926,7 @@ func (ng *Engine) populateSeries(querier storage.Querier, s *parser.EvalStmt) { } evalRange = 0 hints.By, hints.Grouping = extractGroupsFromPath(path) - n.UnexpandedSeriesSet = querier.Select(false, hints, n.LabelMatchers...) + n.UnexpandedSeriesSet = querier.Select(ctx, false, hints, n.LabelMatchers...) case *parser.MatrixSelector: evalRange = n.Range @@ -918,7 +965,7 @@ func extractGroupsFromPath(p []parser.Node) (bool, []string) { return false, nil } -func checkAndExpandSeriesSet(ctx context.Context, expr parser.Expr) (storage.Warnings, error) { +func checkAndExpandSeriesSet(ctx context.Context, expr parser.Expr) (annotations.Annotations, error) { switch e := expr.(type) { case *parser.MatrixSelector: return checkAndExpandSeriesSet(ctx, e.VectorSelector) @@ -933,7 +980,7 @@ func checkAndExpandSeriesSet(ctx context.Context, expr parser.Expr) (storage.War return nil, nil } -func expandSeriesSet(ctx context.Context, it storage.SeriesSet) (res []storage.Series, ws storage.Warnings, err error) { +func expandSeriesSet(ctx context.Context, it storage.SeriesSet) (res []storage.Series, ws annotations.Annotations, err error) { for it.Next() { select { case <-ctx.Done(): @@ -947,7 +994,7 @@ func expandSeriesSet(ctx context.Context, it storage.SeriesSet) (res []storage.S type errWithWarnings struct { err error - warnings storage.Warnings + warnings annotations.Annotations } func (e errWithWarnings) Error() string { return e.err.Error() } @@ -982,7 +1029,7 @@ func (ev *evaluator) error(err error) { } // recover is the handler that turns panics into returns from the top level of evaluation. -func (ev *evaluator) recover(expr parser.Expr, ws *storage.Warnings, errp *error) { +func (ev *evaluator) recover(expr parser.Expr, ws *annotations.Annotations, errp *error) { e := recover() if e == nil { return @@ -998,7 +1045,7 @@ func (ev *evaluator) recover(expr parser.Expr, ws *storage.Warnings, errp *error *errp = fmt.Errorf("unexpected error: %w", err) case errWithWarnings: *errp = err.err - *ws = append(*ws, err.warnings...) + ws.Merge(err.warnings) case error: *errp = err default: @@ -1006,7 +1053,7 @@ func (ev *evaluator) recover(expr parser.Expr, ws *storage.Warnings, errp *error } } -func (ev *evaluator) Eval(expr parser.Expr) (v parser.Value, ws storage.Warnings, err error) { +func (ev *evaluator) Eval(expr parser.Expr) (v parser.Value, ws annotations.Annotations, err error) { defer ev.recover(expr, &ws, &err) v, ws = ev.eval(expr) @@ -1029,9 +1076,9 @@ type EvalNodeHelper struct { Out Vector // Caches. - // DropMetricName and label_*. + // label_*. Dmn map[uint64]labels.Labels - // funcHistogramQuantile for conventional histograms. + // funcHistogramQuantile for classic histograms. signatureToMetricWithBuckets map[string]*metricWithBuckets // label_replace. regex *regexp.Regexp @@ -1054,40 +1101,25 @@ func (enh *EvalNodeHelper) resetBuilder(lbls labels.Labels) { } } -// DropMetricName is a cached version of DropMetricName. -func (enh *EvalNodeHelper) DropMetricName(l labels.Labels) labels.Labels { - if enh.Dmn == nil { - enh.Dmn = make(map[uint64]labels.Labels, len(enh.Out)) - } - h := l.Hash() - ret, ok := enh.Dmn[h] - if ok { - return ret - } - ret = dropMetricName(l) - enh.Dmn[h] = ret - return ret -} - // rangeEval evaluates the given expressions, and then for each step calls // the given funcCall with the values computed for each expression at that // step. The return value is the combination into time series of all the // function call results. // The prepSeries function (if provided) can be used to prepare the helper // for each series, then passed to each call funcCall. -func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper), funcCall func([]parser.Value, [][]EvalSeriesHelper, *EvalNodeHelper) (Vector, storage.Warnings), exprs ...parser.Expr) (Matrix, storage.Warnings) { +func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper), funcCall func([]parser.Value, [][]EvalSeriesHelper, *EvalNodeHelper) (Vector, annotations.Annotations), exprs ...parser.Expr) (Matrix, annotations.Annotations) { numSteps := int((ev.endTimestamp-ev.startTimestamp)/ev.interval) + 1 matrixes := make([]Matrix, len(exprs)) origMatrixes := make([]Matrix, len(exprs)) originalNumSamples := ev.currentSamples - var warnings storage.Warnings + var warnings annotations.Annotations for i, e := range exprs { // Functions will take string arguments from the expressions, not the values. if e != nil && e.Type() != parser.ValueTypeString { // ev.currentSamples will be updated to the correct value within the ev.eval call. val, ws := ev.eval(e) - warnings = append(warnings, ws...) + warnings.Merge(ws) matrixes[i] = val.(Matrix) // Keep a copy of the original point slices so that they @@ -1109,7 +1141,11 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) } } enh := &EvalNodeHelper{Out: make(Vector, 0, biggestLen)} - seriess := make(map[uint64]Series, biggestLen) // Output series by series hash. + type seriesAndTimestamp struct { + Series + ts int64 + } + seriess := make(map[uint64]seriesAndTimestamp, biggestLen) // Output series by series hash. tempNumSamples := ev.currentSamples var ( @@ -1128,9 +1164,7 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) bufHelpers[i] = make([]EvalSeriesHelper, len(matrixes[i])) for si, series := range matrixes[i] { - h := seriesHelpers[i][si] - prepSeries(series.Metric, &h) - seriesHelpers[i][si] = h + prepSeries(series.Metric, &seriesHelpers[i][si]) } } } @@ -1150,41 +1184,24 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) } for si, series := range matrixes[i] { - for _, point := range series.Floats { - if point.T == ts { - if ev.currentSamples < ev.maxSamples { - vectors[i] = append(vectors[i], Sample{Metric: series.Metric, F: point.F, T: ts}) - if prepSeries != nil { - bufHelpers[i] = append(bufHelpers[i], seriesHelpers[i][si]) - } - - // Move input vectors forward so we don't have to re-scan the same - // past points at the next step. - matrixes[i][si].Floats = series.Floats[1:] - ev.currentSamples++ - } else { - ev.error(ErrTooManySamples(env)) - } - } - break + switch { + case len(series.Floats) > 0 && series.Floats[0].T == ts: + vectors[i] = append(vectors[i], Sample{Metric: series.Metric, F: series.Floats[0].F, T: ts}) + // Move input vectors forward so we don't have to re-scan the same + // past points at the next step. + matrixes[i][si].Floats = series.Floats[1:] + case len(series.Histograms) > 0 && series.Histograms[0].T == ts: + vectors[i] = append(vectors[i], Sample{Metric: series.Metric, H: series.Histograms[0].H, T: ts}) + matrixes[i][si].Histograms = series.Histograms[1:] + default: + continue } - for _, point := range series.Histograms { - if point.T == ts { - if ev.currentSamples < ev.maxSamples { - vectors[i] = append(vectors[i], Sample{Metric: series.Metric, H: point.H, T: ts}) - if prepSeries != nil { - bufHelpers[i] = append(bufHelpers[i], seriesHelpers[i][si]) - } - - // Move input vectors forward so we don't have to re-scan the same - // past points at the next step. - matrixes[i][si].Histograms = series.Histograms[1:] - ev.currentSamples++ - } else { - ev.error(ErrTooManySamples(env)) - } - } - break + if prepSeries != nil { + bufHelpers[i] = append(bufHelpers[i], seriesHelpers[i][si]) + } + ev.currentSamples++ + if ev.currentSamples > ev.maxSamples { + ev.error(ErrTooManySamples(env)) } } args[i] = vectors[i] @@ -1194,16 +1211,14 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) // Make the function call. enh.Ts = ts result, ws := funcCall(args, bufHelpers, enh) - if result.ContainsSameLabelset() { - ev.errorf("vector cannot contain metrics with the same labelset") - } enh.Out = result[:0] // Reuse result vector. - warnings = append(warnings, ws...) + warnings.Merge(ws) - ev.currentSamples += len(result) + vecNumSamples := result.TotalSamples() + ev.currentSamples += vecNumSamples // When we reset currentSamples to tempNumSamples during the next iteration of the loop it also // needs to include the samples from the result here, as they're still in memory. - tempNumSamples += len(result) + tempNumSamples += vecNumSamples ev.samplesStats.UpdatePeak(ev.currentSamples) if ev.currentSamples > ev.maxSamples { @@ -1213,6 +1228,9 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) // If this could be an instant query, shortcut so as not to change sort order. if ev.endTimestamp == ev.startTimestamp { + if result.ContainsSameLabelset() { + ev.errorf("vector cannot contain metrics with the same labelset") + } mat := make(Matrix, len(result)) for i, s := range result { if s.H == nil { @@ -1230,8 +1248,13 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) for _, sample := range result { h := sample.Metric.Hash() ss, ok := seriess[h] - if !ok { - ss = Series{Metric: sample.Metric} + if ok { + if ss.ts == ts { // If we've seen this output series before at this timestamp, it's a duplicate. + ev.errorf("vector cannot contain metrics with the same labelset") + } + ss.ts = ts + } else { + ss = seriesAndTimestamp{Series{Metric: sample.Metric}, ts} } if sample.H == nil { if ss.Floats == nil { @@ -1258,7 +1281,7 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) // Assemble the output matrix. By the time we get here we know we don't have too many samples. mat := make(Matrix, 0, len(seriess)) for _, ss := range seriess { - mat = append(mat, ss) + mat = append(mat, ss.Series) } ev.currentSamples = originalNumSamples + mat.TotalSamples() ev.samplesStats.UpdatePeak(ev.currentSamples) @@ -1267,7 +1290,7 @@ func (ev *evaluator) rangeEval(prepSeries func(labels.Labels, *EvalSeriesHelper) // evalSubquery evaluates given SubqueryExpr and returns an equivalent // evaluated MatrixSelector in its place. Note that the Name and LabelMatchers are not set. -func (ev *evaluator) evalSubquery(subq *parser.SubqueryExpr) (*parser.MatrixSelector, int, storage.Warnings) { +func (ev *evaluator) evalSubquery(subq *parser.SubqueryExpr) (*parser.MatrixSelector, int, annotations.Annotations) { samplesStats := ev.samplesStats // Avoid double counting samples when running a subquery, those samples will be counted in later stage. ev.samplesStats = ev.samplesStats.NewChild() @@ -1291,16 +1314,14 @@ func (ev *evaluator) evalSubquery(subq *parser.SubqueryExpr) (*parser.MatrixSele Range: subq.Range, VectorSelector: vs, } - totalSamples := 0 for _, s := range mat { - totalSamples += len(s.Floats) + len(s.Histograms) vs.Series = append(vs.Series, NewStorageSeries(s)) } - return ms, totalSamples, ws + return ms, mat.TotalSamples(), ws } // eval evaluates the given expression as the given AST expression node requires. -func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { +func (ev *evaluator) eval(expr parser.Expr) (parser.Value, annotations.Annotations) { // This is the top-level evaluation method. // Thus, we check for timeout/cancellation here. if err := contextDone(ev.ctx, "expression evaluation"); err != nil { @@ -1329,17 +1350,17 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { param := unwrapStepInvariantExpr(e.Param) unwrapParenExpr(¶m) if s, ok := param.(*parser.StringLiteral); ok { - return ev.rangeEval(initSeries, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { - return ev.aggregation(e.Op, sortedGrouping, e.Without, s.Val, v[0].(Vector), sh[0], enh), nil + return ev.rangeEval(initSeries, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return ev.aggregation(e, sortedGrouping, s.Val, v[0].(Vector), sh[0], enh) }, e.Expr) } - return ev.rangeEval(initSeries, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(initSeries, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { var param float64 if e.Param != nil { param = v[0].(Vector)[0].F } - return ev.aggregation(e.Op, sortedGrouping, e.Without, param, v[1].(Vector), sh[1], enh), nil + return ev.aggregation(e, sortedGrouping, param, v[1].(Vector), sh[1], enh) }, e.Param, e.Expr) case *parser.Call: @@ -1353,15 +1374,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { unwrapParenExpr(&arg) vs, ok := arg.(*parser.VectorSelector) if ok { - return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { - if vs.Timestamp != nil { - // This is a special case only for "timestamp" since the offset - // needs to be adjusted for every point. - vs.Offset = time.Duration(enh.Ts-*vs.Timestamp) * time.Millisecond - } - val, ws := ev.vectorSelector(vs, enh.Ts) - return call([]parser.Value{val}, e.Args, enh), ws - }) + return ev.rangeEvalTimestampFunctionOverVectorSelector(vs, call, e) } } @@ -1369,7 +1382,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { var ( matrixArgIndex int matrixArg bool - warnings storage.Warnings + warnings annotations.Annotations ) for i := range e.Args { unwrapParenExpr(&e.Args[i]) @@ -1387,7 +1400,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { // Replacing parser.SubqueryExpr with parser.MatrixSelector. val, totalSamples, ws := ev.evalSubquery(subq) e.Args[i] = val - warnings = append(warnings, ws...) + warnings.Merge(ws) defer func() { // subquery result takes space in the memory. Get rid of that at the end. val.VectorSelector.(*parser.VectorSelector).Series = nil @@ -1398,8 +1411,9 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { } if !matrixArg { // Does not have a matrix argument. - return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { - return call(v, e.Args, enh), warnings + return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + vec, annos := call(v, e.Args, enh) + return vec, warnings.Merge(annos) }, e.Args...) } @@ -1413,7 +1427,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { otherArgs[i] = val.(Matrix) otherInArgs[i] = Vector{Sample{}} inArgs[i] = otherInArgs[i] - warnings = append(warnings, ws...) + warnings.Merge(ws) } } @@ -1424,7 +1438,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { selVS := sel.VectorSelector.(*parser.VectorSelector) ws, err := checkAndExpandSeriesSet(ev.ctx, sel) - warnings = append(warnings, ws...) + warnings.Merge(ws) if err != nil { ev.error(errWithWarnings{fmt.Errorf("expanding series: %w", err), warnings}) } @@ -1445,7 +1459,10 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { it := storage.NewBuffer(selRange) var chkIter chunkenc.Iterator for i, s := range selVS.Series { - ev.currentSamples -= len(floats) + len(histograms) + if err := contextDone(ev.ctx, "expression evaluation"); err != nil { + ev.error(err) + } + ev.currentSamples -= len(floats) + totalHPointSize(histograms) if floats != nil { floats = floats[:0] } @@ -1460,7 +1477,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { // vector functions, the only change needed is to drop the // metric name in the output. if e.Func.Name != "last_over_time" { - metric = dropMetricName(metric) + metric = metric.DropMetricName() } ss := Series{ Metric: metric, @@ -1487,8 +1504,10 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { inMatrix[0].Histograms = histograms enh.Ts = ts // Make the function call. - outVec := call(inArgs, e.Args, enh) - ev.samplesStats.IncrementSamplesAtStep(step, int64(len(floats)+len(histograms))) + outVec, annos := call(inArgs, e.Args, enh) + warnings.Merge(annos) + ev.samplesStats.IncrementSamplesAtStep(step, int64(len(floats)+totalHPointSize(histograms))) + enh.Out = outVec[:0] if len(outVec) > 0 { if outVec[0].H == nil { @@ -1506,21 +1525,34 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { // Only buffer stepRange milliseconds from the second step on. it.ReduceDelta(stepRange) } - if len(ss.Floats)+len(ss.Histograms) > 0 { - if ev.currentSamples+len(ss.Floats)+len(ss.Histograms) <= ev.maxSamples { + histSamples := totalHPointSize(ss.Histograms) + if len(ss.Floats)+histSamples > 0 { + if ev.currentSamples+len(ss.Floats)+histSamples <= ev.maxSamples { mat = append(mat, ss) - ev.currentSamples += len(ss.Floats) + len(ss.Histograms) + ev.currentSamples += len(ss.Floats) + histSamples } else { ev.error(ErrTooManySamples(env)) } } ev.samplesStats.UpdatePeak(ev.currentSamples) + + if e.Func.Name == "rate" || e.Func.Name == "increase" { + samples := inMatrix[0] + metricName := samples.Metric.Get(labels.MetricName) + if metricName != "" && len(samples.Floats) > 0 && + !strings.HasSuffix(metricName, "_total") && + !strings.HasSuffix(metricName, "_sum") && + !strings.HasSuffix(metricName, "_count") && + !strings.HasSuffix(metricName, "_bucket") { + warnings.Add(annotations.NewPossibleNonCounterInfo(metricName, e.Args[0].PositionRange())) + } + } } ev.samplesStats.UpdatePeak(ev.currentSamples) - ev.currentSamples -= len(floats) + len(histograms) + ev.currentSamples -= len(floats) + totalHPointSize(histograms) putFPointSlice(floats) - putHPointSlice(histograms) + putMatrixSelectorHPointSlice(histograms) // The absent_over_time function returns 0 or 1 series. So far, the matrix // contains multiple series. The following code will create a new series @@ -1577,7 +1609,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { mat := val.(Matrix) if e.Op == parser.SUB { for i := range mat { - mat[i].Metric = dropMetricName(mat[i].Metric) + mat[i].Metric = mat[i].Metric.DropMetricName() for j := range mat[i].Floats { mat[i].Floats[j].F = -mat[i].Floats[j].F } @@ -1591,7 +1623,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { case *parser.BinaryExpr: switch lt, rt := e.LHS.Type(), e.RHS.Type(); { case lt == parser.ValueTypeScalar && rt == parser.ValueTypeScalar: - return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { val := scalarBinop(e.Op, v[0].(Vector)[0].F, v[1].(Vector)[0].F) return append(enh.Out, Sample{F: val}), nil }, e.LHS, e.RHS) @@ -1604,36 +1636,36 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { } switch e.Op { case parser.LAND: - return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorAnd(v[0].(Vector), v[1].(Vector), e.VectorMatching, sh[0], sh[1], enh), nil }, e.LHS, e.RHS) case parser.LOR: - return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorOr(v[0].(Vector), v[1].(Vector), e.VectorMatching, sh[0], sh[1], enh), nil }, e.LHS, e.RHS) case parser.LUNLESS: - return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorUnless(v[0].(Vector), v[1].(Vector), e.VectorMatching, sh[0], sh[1], enh), nil }, e.LHS, e.RHS) default: - return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(initSignatures, func(v []parser.Value, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorBinop(e.Op, v[0].(Vector), v[1].(Vector), e.VectorMatching, e.ReturnBool, sh[0], sh[1], enh), nil }, e.LHS, e.RHS) } case lt == parser.ValueTypeVector && rt == parser.ValueTypeScalar: - return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorscalarBinop(e.Op, v[0].(Vector), Scalar{V: v[1].(Vector)[0].F}, false, e.ReturnBool, enh), nil }, e.LHS, e.RHS) case lt == parser.ValueTypeScalar && rt == parser.ValueTypeVector: - return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorscalarBinop(e.Op, v[1].(Vector), Scalar{V: v[0].(Vector)[0].F}, true, e.ReturnBool, enh), nil }, e.LHS, e.RHS) } case *parser.NumberLiteral: - return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, storage.Warnings) { + return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return append(enh.Out, Sample{F: e.Val, Metric: labels.EmptyLabels()}), nil }) @@ -1649,6 +1681,9 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { it := storage.NewMemoizedEmptyIterator(durationMilliseconds(ev.lookbackDelta)) var chkIter chunkenc.Iterator for i, s := range e.Series { + if err := contextDone(ev.ctx, "expression evaluation"); err != nil { + ev.error(err) + } chkIter = s.Iterator(chkIter) it.Reset(chkIter) ss := Series{ @@ -1665,14 +1700,18 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { ss.Floats = getFPointSlice(numSteps) } ss.Floats = append(ss.Floats, FPoint{F: f, T: ts}) + ev.currentSamples++ + ev.samplesStats.IncrementSamplesAtStep(step, 1) } else { if ss.Histograms == nil { ss.Histograms = getHPointSlice(numSteps) } - ss.Histograms = append(ss.Histograms, HPoint{H: h, T: ts}) + point := HPoint{H: h, T: ts} + ss.Histograms = append(ss.Histograms, point) + histSize := point.size() + ev.currentSamples += histSize + ev.samplesStats.IncrementSamplesAtStep(step, int64(histSize)) } - ev.samplesStats.IncrementSamplesAtStep(step, 1) - ev.currentSamples++ } else { ev.error(ErrTooManySamples(env)) } @@ -1780,13 +1819,15 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { T: ts, F: mat[i].Floats[0].F, }) + ev.currentSamples++ } else { - mat[i].Histograms = append(mat[i].Histograms, HPoint{ + point := HPoint{ T: ts, H: mat[i].Histograms[0].H, - }) + } + mat[i].Histograms = append(mat[i].Histograms, point) + ev.currentSamples += point.size() } - ev.currentSamples++ if ev.currentSamples > ev.maxSamples { ev.error(ErrTooManySamples(env)) } @@ -1799,38 +1840,54 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { panic(fmt.Errorf("unhandled expression of type: %T", expr)) } -// vectorSelector evaluates a *parser.VectorSelector expression. -func (ev *evaluator) vectorSelector(node *parser.VectorSelector, ts int64) (Vector, storage.Warnings) { - ws, err := checkAndExpandSeriesSet(ev.ctx, node) +func (ev *evaluator) rangeEvalTimestampFunctionOverVectorSelector(vs *parser.VectorSelector, call FunctionCall, e *parser.Call) (parser.Value, annotations.Annotations) { + ws, err := checkAndExpandSeriesSet(ev.ctx, vs) if err != nil { ev.error(errWithWarnings{fmt.Errorf("expanding series: %w", err), ws}) } - vec := make(Vector, 0, len(node.Series)) - it := storage.NewMemoizedEmptyIterator(durationMilliseconds(ev.lookbackDelta)) - var chkIter chunkenc.Iterator - for i, s := range node.Series { - chkIter = s.Iterator(chkIter) - it.Reset(chkIter) - t, f, h, ok := ev.vectorSelectorSingle(it, node, ts) - if ok { - vec = append(vec, Sample{ - Metric: node.Series[i].Labels(), - T: t, - F: f, - H: h, - }) + seriesIterators := make([]*storage.MemoizedSeriesIterator, len(vs.Series)) + for i, s := range vs.Series { + it := s.Iterator(nil) + seriesIterators[i] = storage.NewMemoizedIterator(it, durationMilliseconds(ev.lookbackDelta)) + } - ev.currentSamples++ - ev.samplesStats.IncrementSamplesAtTimestamp(ts, 1) - if ev.currentSamples > ev.maxSamples { - ev.error(ErrTooManySamples(env)) - } + return ev.rangeEval(nil, func(v []parser.Value, _ [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + if vs.Timestamp != nil { + // This is a special case for "timestamp()" when the @ modifier is used, to ensure that + // we return a point for each time step in this case. + // See https://github.com/prometheus/prometheus/issues/8433. + vs.Offset = time.Duration(enh.Ts-*vs.Timestamp) * time.Millisecond } - } - ev.samplesStats.UpdatePeak(ev.currentSamples) - return vec, ws + vec := make(Vector, 0, len(vs.Series)) + for i, s := range vs.Series { + it := seriesIterators[i] + t, f, h, ok := ev.vectorSelectorSingle(it, vs, enh.Ts) + if ok { + vec = append(vec, Sample{ + Metric: s.Labels(), + T: t, + F: f, + H: h, + }) + histSize := 0 + if h != nil { + histSize := h.Size() / 16 // 16 bytes per sample. + ev.currentSamples += histSize + } + ev.currentSamples++ + + ev.samplesStats.IncrementSamplesAtTimestamp(enh.Ts, int64(1+histSize)) + if ev.currentSamples > ev.maxSamples { + ev.error(ErrTooManySamples(env)) + } + } + } + ev.samplesStats.UpdatePeak(ev.currentSamples) + vec, annos := call([]parser.Value{vec}, e.Args, enh) + return vec, ws.Merge(annos) + }) } // vectorSelectorSingle evaluates an instant vector for the iterator of one time series. @@ -1850,14 +1907,14 @@ func (ev *evaluator) vectorSelectorSingle(it *storage.MemoizedSeriesIterator, no } case chunkenc.ValFloat: t, v = it.At() - case chunkenc.ValHistogram, chunkenc.ValFloatHistogram: + case chunkenc.ValFloatHistogram: t, h = it.AtFloatHistogram() default: panic(fmt.Errorf("unknown value type %v", valueType)) } if valueType == chunkenc.ValNone || t > refTime { var ok bool - t, v, _, h, ok = it.PeekPrev() + t, v, h, ok = it.PeekPrev() if !ok || t < refTime-durationMilliseconds(ev.lookbackDelta) { return 0, 0, nil, false } @@ -1871,25 +1928,46 @@ func (ev *evaluator) vectorSelectorSingle(it *storage.MemoizedSeriesIterator, no var ( fPointPool zeropool.Pool[[]FPoint] hPointPool zeropool.Pool[[]HPoint] + + // matrixSelectorHPool holds reusable histogram slices used by the matrix + // selector. The key difference between this pool and the hPointPool is that + // slices returned by this pool should never hold multiple copies of the same + // histogram pointer since histogram objects are reused across query evaluation + // steps. + matrixSelectorHPool zeropool.Pool[[]HPoint] ) func getFPointSlice(sz int) []FPoint { if p := fPointPool.Get(); p != nil { return p } + + if sz > maxPointsSliceSize { + sz = maxPointsSliceSize + } + return make([]FPoint, 0, sz) } +// putFPointSlice will return a FPoint slice of size max(maxPointsSliceSize, sz). +// This function is called with an estimated size which often can be over-estimated. func putFPointSlice(p []FPoint) { if p != nil { fPointPool.Put(p[:0]) } } +// getHPointSlice will return a HPoint slice of size max(maxPointsSliceSize, sz). +// This function is called with an estimated size which often can be over-estimated. func getHPointSlice(sz int) []HPoint { if p := hPointPool.Get(); p != nil { return p } + + if sz > maxPointsSliceSize { + sz = maxPointsSliceSize + } + return make([]HPoint, 0, sz) } @@ -1899,8 +1977,22 @@ func putHPointSlice(p []HPoint) { } } +func getMatrixSelectorHPoints() []HPoint { + if p := matrixSelectorHPool.Get(); p != nil { + return p + } + + return make([]HPoint, 0, matrixSelectorSliceSize) +} + +func putMatrixSelectorHPointSlice(p []HPoint) { + if p != nil { + matrixSelectorHPool.Put(p[:0]) + } +} + // matrixSelector evaluates a *parser.MatrixSelector expression. -func (ev *evaluator) matrixSelector(node *parser.MatrixSelector) (Matrix, storage.Warnings) { +func (ev *evaluator) matrixSelector(node *parser.MatrixSelector) (Matrix, annotations.Annotations) { var ( vs = node.VectorSelector.(*parser.VectorSelector) @@ -1929,10 +2021,10 @@ func (ev *evaluator) matrixSelector(node *parser.MatrixSelector) (Matrix, storag } ss.Floats, ss.Histograms = ev.matrixIterSlice(it, mint, maxt, nil, nil) - totalLen := int64(len(ss.Floats)) + int64(len(ss.Histograms)) - ev.samplesStats.IncrementSamplesAtTimestamp(ev.startTimestamp, totalLen) + totalSize := int64(len(ss.Floats)) + int64(totalHPointSize(ss.Histograms)) + ev.samplesStats.IncrementSamplesAtTimestamp(ev.startTimestamp, totalSize) - if totalLen > 0 { + if totalSize > 0 { matrix = append(matrix, ss) } else { putFPointSlice(ss.Floats) @@ -1964,7 +2056,7 @@ func (ev *evaluator) matrixIterSlice( // (b) the number of samples is relatively small. // so a linear search will be as fast as a binary search. var drop int - for drop = 0; floats[drop].T < mint; drop++ { // nolint:revive + for drop = 0; floats[drop].T < mint; drop++ { } ev.currentSamples -= drop copy(floats, floats[drop:]) @@ -1986,15 +2078,20 @@ func (ev *evaluator) matrixIterSlice( // (b) the number of samples is relatively small. // so a linear search will be as fast as a binary search. var drop int - for drop = 0; histograms[drop].T < mint; drop++ { // nolint:revive + for drop = 0; histograms[drop].T < mint; drop++ { } - ev.currentSamples -= drop + // Rotate the buffer around the drop index so that points before mint can be + // reused to store new histograms. + tail := make([]HPoint, drop) + copy(tail, histograms[:drop]) copy(histograms, histograms[drop:]) + copy(histograms[len(histograms)-drop:], tail) histograms = histograms[:len(histograms)-drop] + ev.currentSamples -= totalHPointSize(histograms) // Only append points with timestamps after the last timestamp we have. mintHistograms = histograms[len(histograms)-1].T + 1 } else { - ev.currentSamples -= len(histograms) + ev.currentSamples -= totalHPointSize(histograms) if histograms != nil { histograms = histograms[:0] } @@ -2014,20 +2111,27 @@ loop: case chunkenc.ValNone: break loop case chunkenc.ValFloatHistogram, chunkenc.ValHistogram: - t, h := buf.AtFloatHistogram() - if value.IsStaleNaN(h.Sum) { - continue loop - } + t := buf.AtT() // Values in the buffer are guaranteed to be smaller than maxt. if t >= mintHistograms { + if histograms == nil { + histograms = getMatrixSelectorHPoints() + } + n := len(histograms) + if n < cap(histograms) { + histograms = histograms[:n+1] + } else { + histograms = append(histograms, HPoint{H: &histogram.FloatHistogram{}}) + } + histograms[n].T, histograms[n].H = buf.AtFloatHistogram(histograms[n].H) + if value.IsStaleNaN(histograms[n].H.Sum) { + histograms = histograms[:n] + continue loop + } if ev.currentSamples >= ev.maxSamples { ev.error(ErrTooManySamples(env)) } - ev.currentSamples++ - if histograms == nil { - histograms = getHPointSlice(16) - } - histograms = append(histograms, HPoint{T: t, H: h}) + ev.currentSamples += histograms[n].size() } case chunkenc.ValFloat: t, f := buf.At() @@ -2050,17 +2154,28 @@ loop: // The sought sample might also be in the range. switch soughtValueType { case chunkenc.ValFloatHistogram, chunkenc.ValHistogram: - t, h := it.AtFloatHistogram() - if t == maxt && !value.IsStaleNaN(h.Sum) { - if ev.currentSamples >= ev.maxSamples { - ev.error(ErrTooManySamples(env)) - } - if histograms == nil { - histograms = getHPointSlice(16) - } - histograms = append(histograms, HPoint{T: t, H: h}) - ev.currentSamples++ + if it.AtT() != maxt { + break + } + if histograms == nil { + histograms = getMatrixSelectorHPoints() + } + n := len(histograms) + if n < cap(histograms) { + histograms = histograms[:n+1] + } else { + histograms = append(histograms, HPoint{H: &histogram.FloatHistogram{}}) + } + histograms[n].T, histograms[n].H = it.AtFloatHistogram(histograms[n].H) + if value.IsStaleNaN(histograms[n].H.Sum) { + histograms = histograms[:n] + break } + if ev.currentSamples >= ev.maxSamples { + ev.error(ErrTooManySamples(env)) + } + ev.currentSamples += histograms[n].size() + case chunkenc.ValFloat: t, f := it.At() if t == maxt && !value.IsStaleNaN(f) { @@ -2240,7 +2355,7 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * } metric := resultMetric(ls.Metric, rs.Metric, op, matching, enh) if returnBool { - metric = enh.DropMetricName(metric) + metric = metric.DropMetricName() } insertedSigs, exists := matchedSigs[sig] if matching.Card == parser.CardOneToOne { @@ -2263,14 +2378,11 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * insertedSigs[insertSig] = struct{}{} } - if (hl != nil && hr != nil) || (hl == nil && hr == nil) { - // Both lhs and rhs are of same type. - enh.Out = append(enh.Out, Sample{ - Metric: metric, - F: floatValue, - H: histogramValue, - }) - } + enh.Out = append(enh.Out, Sample{ + Metric: metric, + F: floatValue, + H: histogramValue, + }) } return enh.Out } @@ -2337,30 +2449,35 @@ func resultMetric(lhs, rhs labels.Labels, op parser.ItemType, matching *parser.V // VectorscalarBinop evaluates a binary operation between a Vector and a Scalar. func (ev *evaluator) VectorscalarBinop(op parser.ItemType, lhs Vector, rhs Scalar, swap, returnBool bool, enh *EvalNodeHelper) Vector { for _, lhsSample := range lhs { - lv, rv := lhsSample.F, rhs.V + lf, rf := lhsSample.F, rhs.V + var rh *histogram.FloatHistogram + lh := lhsSample.H // lhs always contains the Vector. If the original position was different // swap for calculating the value. if swap { - lv, rv = rv, lv + lf, rf = rf, lf + lh, rh = rh, lh } - value, _, keep := vectorElemBinop(op, lv, rv, nil, nil) + float, histogram, keep := vectorElemBinop(op, lf, rf, lh, rh) // Catch cases where the scalar is the LHS in a scalar-vector comparison operation. // We want to always keep the vector element value as the output value, even if it's on the RHS. if op.IsComparisonOperator() && swap { - value = rv + float = rf + histogram = rh } if returnBool { if keep { - value = 1.0 + float = 1.0 } else { - value = 0.0 + float = 0.0 } keep = true } if keep { - lhsSample.F = value + lhsSample.F = float + lhsSample.H = histogram if shouldDropMetricName(op) || returnBool { - lhsSample.Metric = enh.DropMetricName(lhsSample.Metric) + lhsSample.Metric = lhsSample.Metric.DropMetricName() } enh.Out = append(enh.Out, lhsSample) } @@ -2368,10 +2485,6 @@ func (ev *evaluator) VectorscalarBinop(op parser.ItemType, lhs Vector, rhs Scala return enh.Out } -func dropMetricName(l labels.Labels) labels.Labels { - return labels.NewBuilder(l).Del(labels.MetricName).Labels() -} - // scalarBinop evaluates a binary operation between two Scalars. func scalarBinop(op parser.ItemType, lhs, rhs float64) float64 { switch op { @@ -2410,19 +2523,26 @@ func vectorElemBinop(op parser.ItemType, lhs, rhs float64, hlhs, hrhs *histogram switch op { case parser.ADD: if hlhs != nil && hrhs != nil { - // The histogram being added must have the larger schema - // code (i.e. the higher resolution). - if hrhs.Schema >= hlhs.Schema { - return 0, hlhs.Copy().Add(hrhs), true - } - return 0, hrhs.Copy().Add(hlhs), true + return 0, hlhs.Copy().Add(hrhs).Compact(0), true } return lhs + rhs, nil, true case parser.SUB: + if hlhs != nil && hrhs != nil { + return 0, hlhs.Copy().Sub(hrhs).Compact(0), true + } return lhs - rhs, nil, true case parser.MUL: + if hlhs != nil && hrhs == nil { + return 0, hlhs.Copy().Mul(rhs), true + } + if hlhs == nil && hrhs != nil { + return 0, hrhs.Copy().Mul(lhs), true + } return lhs * rhs, nil, true case parser.DIV: + if hlhs != nil && hrhs == nil { + return 0, hlhs.Copy().Div(rhs), true + } return lhs / rhs, nil, true case parser.POW: return math.Pow(lhs, rhs), nil, true @@ -2452,7 +2572,8 @@ type groupedAggregation struct { labels labels.Labels floatValue float64 histogramValue *histogram.FloatHistogram - mean float64 + floatMean float64 + histogramMean *histogram.FloatHistogram groupCount int heap vectorByValueHeap reverseHeap vectorByReverseValueHeap @@ -2460,7 +2581,10 @@ type groupedAggregation struct { // aggregation evaluates an aggregation operation on a Vector. The provided grouping labels // must be sorted. -func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without bool, param interface{}, vec Vector, seriesHelper []EvalSeriesHelper, enh *EvalNodeHelper) Vector { +func (ev *evaluator) aggregation(e *parser.AggregateExpr, grouping []string, param interface{}, vec Vector, seriesHelper []EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + op := e.Op + without := e.Without + var annos annotations.Annotations result := map[uint64]*groupedAggregation{} orderedResult := []*groupedAggregation{} var k int64 @@ -2471,7 +2595,7 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without } k = int64(f) if k < 1 { - return Vector{} + return Vector{}, annos } } var q float64 @@ -2536,7 +2660,7 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without newAgg := &groupedAggregation{ labels: m, floatValue: s.F, - mean: s.F, + floatMean: s.F, groupCount: 1, } switch { @@ -2545,6 +2669,11 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without case op == parser.SUM: newAgg.histogramValue = s.H.Copy() newAgg.hasHistogram = true + case op == parser.AVG: + newAgg.histogramMean = s.H.Copy() + newAgg.hasHistogram = true + case op == parser.STDVAR || op == parser.STDDEV: + newAgg.groupCount = 0 } result[groupingKey] = newAgg @@ -2584,15 +2713,7 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without if s.H != nil { group.hasHistogram = true if group.histogramValue != nil { - // The histogram being added must have - // an equal or larger schema. - if s.H.Schema >= group.histogramValue.Schema { - group.histogramValue.Add(s.H) - } else { - h := s.H.Copy() - h.Add(group.histogramValue) - group.histogramValue = h - } + group.histogramValue.Add(s.H) } // Otherwise the aggregation contained floats // previously and will be invalid anyway. No @@ -2604,25 +2725,39 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without case parser.AVG: group.groupCount++ - if math.IsInf(group.mean, 0) { - if math.IsInf(s.F, 0) && (group.mean > 0) == (s.F > 0) { - // The `mean` and `s.V` values are `Inf` of the same sign. They - // can't be subtracted, but the value of `mean` is correct - // already. - break + if s.H != nil { + group.hasHistogram = true + if group.histogramMean != nil { + left := s.H.Copy().Div(float64(group.groupCount)) + right := group.histogramMean.Copy().Div(float64(group.groupCount)) + toAdd := left.Sub(right) + group.histogramMean.Add(toAdd) } - if !math.IsInf(s.F, 0) && !math.IsNaN(s.F) { - // At this stage, the mean is an infinite. If the added - // value is neither an Inf or a Nan, we can keep that mean - // value. - // This is required because our calculation below removes - // the mean value, which would look like Inf += x - Inf and - // end up as a NaN. - break + // Otherwise the aggregation contained floats + // previously and will be invalid anyway. No + // point in copying the histogram in that case. + } else { + group.hasFloat = true + if math.IsInf(group.floatMean, 0) { + if math.IsInf(s.F, 0) && (group.floatMean > 0) == (s.F > 0) { + // The `floatMean` and `s.F` values are `Inf` of the same sign. They + // can't be subtracted, but the value of `floatMean` is correct + // already. + break + } + if !math.IsInf(s.F, 0) && !math.IsNaN(s.F) { + // At this stage, the mean is an infinite. If the added + // value is neither an Inf or a Nan, we can keep that mean + // value. + // This is required because our calculation below removes + // the mean value, which would look like Inf += x - Inf and + // end up as a NaN. + break + } } + // Divide each side of the `-` by `group.groupCount` to avoid float64 overflows. + group.floatMean += s.F/float64(group.groupCount) - group.floatMean/float64(group.groupCount) } - // Divide each side of the `-` by `group.groupCount` to avoid float64 overflows. - group.mean += s.F/float64(group.groupCount) - group.mean/float64(group.groupCount) case parser.GROUP: // Do nothing. Required to avoid the panic in `default:` below. @@ -2641,10 +2776,12 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without group.groupCount++ case parser.STDVAR, parser.STDDEV: - group.groupCount++ - delta := s.F - group.mean - group.mean += delta / float64(group.groupCount) - group.floatValue += delta * (s.F - group.mean) + if s.H == nil { // Ignore native histograms. + group.groupCount++ + delta := s.F - group.floatMean + group.floatMean += delta / float64(group.groupCount) + group.floatValue += delta * (s.F - group.floatMean) + } case parser.TOPK: // We build a heap of up to k elements, with the smallest element at heap[0]. @@ -2696,7 +2833,17 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without for _, aggr := range orderedResult { switch op { case parser.AVG: - aggr.floatValue = aggr.mean + if aggr.hasFloat && aggr.hasHistogram { + // We cannot aggregate histogram sample with a float64 sample. + metricName := aggr.labels.Get(labels.MetricName) + annos.Add(annotations.NewMixedFloatsHistogramsWarning(metricName, e.Expr.PositionRange())) + continue + } + if aggr.hasHistogram { + aggr.histogramValue = aggr.histogramMean.Compact(0) + } else { + aggr.floatValue = aggr.floatMean + } case parser.COUNT, parser.COUNT_VALUES: aggr.floatValue = float64(aggr.groupCount) @@ -2734,13 +2881,21 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without continue // Bypass default append. case parser.QUANTILE: + if math.IsNaN(q) || q < 0 || q > 1 { + annos.Add(annotations.NewInvalidQuantileWarning(q, e.Param.PositionRange())) + } aggr.floatValue = quantile(q, aggr.heap) case parser.SUM: if aggr.hasFloat && aggr.hasHistogram { // We cannot aggregate histogram sample with a float64 sample. + metricName := aggr.labels.Get(labels.MetricName) + annos.Add(annotations.NewMixedFloatsHistogramsWarning(metricName, e.Expr.PositionRange())) continue } + if aggr.hasHistogram { + aggr.histogramValue.Compact(0) + } default: // For other aggregations, we already have the right value. } @@ -2751,7 +2906,7 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without H: aggr.histogramValue, }) } - return enh.Out + return enh.Out, annos } // groupingKey builds and returns the grouping key for the given metric and @@ -2781,7 +2936,7 @@ func btos(b bool) float64 { // result of the op operation. func shouldDropMetricName(op parser.ItemType) bool { switch op { - case parser.ADD, parser.SUB, parser.DIV, parser.MUL, parser.POW, parser.MOD: + case parser.ADD, parser.SUB, parser.DIV, parser.MUL, parser.POW, parser.MOD, parser.ATAN2: return true default: return false diff --git a/vendor/github.com/prometheus/prometheus/promql/functions.go b/vendor/github.com/prometheus/prometheus/promql/functions.go index df29d6c5d..a0a118c11 100644 --- a/vendor/github.com/prometheus/prometheus/promql/functions.go +++ b/vendor/github.com/prometheus/prometheus/promql/functions.go @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -// nolint:revive // Many unsued function arguments in this file by design. package promql import ( @@ -22,12 +21,16 @@ import ( "strings" "time" + "github.com/facette/natsort" "github.com/grafana/regexp" "github.com/prometheus/common/model" + "golang.org/x/exp/slices" "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/promql/parser" + "github.com/prometheus/prometheus/promql/parser/posrange" + "github.com/prometheus/prometheus/util/annotations" ) // FunctionCall is the type of a PromQL function implementation @@ -51,20 +54,20 @@ import ( // metrics, the timestamp are not needed. // // Scalar results should be returned as the value of a sample in a Vector. -type FunctionCall func(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector +type FunctionCall func(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) // === time() float64 === -func funcTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return Vector{Sample{ F: float64(enh.Ts) / 1000, - }} + }}, nil } // extrapolatedRate is a utility function for rate/increase/delta. // It calculates the rate (allowing for counter resets if isCounter is true), // extrapolates if the first/last sample is close to the boundary, and returns // the result as either per-second (if isRate is true) or overall. -func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper, isCounter, isRate bool) Vector { +func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper, isCounter, isRate bool) (Vector, annotations.Annotations) { ms := args[0].(*parser.MatrixSelector) vs := ms.VectorSelector.(*parser.VectorSelector) var ( @@ -75,14 +78,15 @@ func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNod resultHistogram *histogram.FloatHistogram firstT, lastT int64 numSamplesMinusOne int + annos annotations.Annotations ) // We need either at least two Histograms and no Floats, or at least two // Floats and no Histograms to calculate a rate. Otherwise, drop this // Vector element. + metricName := samples.Metric.Get(labels.MetricName) if len(samples.Histograms) > 0 && len(samples.Floats) > 0 { - // Mix of histograms and floats. TODO(beorn7): Communicate this failure reason. - return enh.Out + return enh.Out, annos.Add(annotations.NewMixedFloatsHistogramsWarning(metricName, args[0].PositionRange())) } switch { @@ -90,11 +94,11 @@ func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNod numSamplesMinusOne = len(samples.Histograms) - 1 firstT = samples.Histograms[0].T lastT = samples.Histograms[numSamplesMinusOne].T - resultHistogram = histogramRate(samples.Histograms, isCounter) + var newAnnos annotations.Annotations + resultHistogram, newAnnos = histogramRate(samples.Histograms, isCounter, metricName, args[0].PositionRange()) if resultHistogram == nil { // The histograms are not compatible with each other. - // TODO(beorn7): Communicate this failure reason. - return enh.Out + return enh.Out, annos.Merge(newAnnos) } case len(samples.Floats) > 1: numSamplesMinusOne = len(samples.Floats) - 1 @@ -113,8 +117,8 @@ func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNod prevValue = currPoint.F } default: - // Not enough samples. TODO(beorn7): Communicate this failure reason. - return enh.Out + // TODO: add RangeTooShortWarning + return enh.Out, annos } // Duration between first/last samples and boundary of range. @@ -162,26 +166,29 @@ func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNod if resultHistogram == nil { resultFloat *= factor } else { - resultHistogram.Scale(factor) + resultHistogram.Mul(factor) } - return append(enh.Out, Sample{F: resultFloat, H: resultHistogram}) + return append(enh.Out, Sample{F: resultFloat, H: resultHistogram}), annos } // histogramRate is a helper function for extrapolatedRate. It requires // points[0] to be a histogram. It returns nil if any other Point in points is -// not a histogram. -func histogramRate(points []HPoint, isCounter bool) *histogram.FloatHistogram { +// not a histogram, and a warning wrapped in an annotation in that case. +// Otherwise, it returns the calculated histogram and an empty annotation. +func histogramRate(points []HPoint, isCounter bool, metricName string, pos posrange.PositionRange) (*histogram.FloatHistogram, annotations.Annotations) { prev := points[0].H last := points[len(points)-1].H if last == nil { - return nil // Range contains a mix of histograms and floats. + return nil, annotations.New().Add(annotations.NewMixedFloatsHistogramsWarning(metricName, pos)) } minSchema := prev.Schema if last.Schema < minSchema { minSchema = last.Schema } + var annos annotations.Annotations + // First iteration to find out two things: // - What's the smallest relevant schema? // - Are all data points histograms? @@ -190,12 +197,14 @@ func histogramRate(points []HPoint, isCounter bool) *histogram.FloatHistogram { for _, currPoint := range points[1 : len(points)-1] { curr := currPoint.H if curr == nil { - return nil // Range contains a mix of histograms and floats. + return nil, annotations.New().Add(annotations.NewMixedFloatsHistogramsWarning(metricName, pos)) } - // TODO(trevorwhitney): Check if isCounter is consistent with curr.CounterResetHint. if !isCounter { continue } + if curr.CounterResetHint == histogram.GaugeType { + annos.Add(annotations.NewNativeHistogramNotCounterWarning(metricName, pos)) + } if curr.Schema < minSchema { minSchema = curr.Schema } @@ -213,43 +222,46 @@ func histogramRate(points []HPoint, isCounter bool) *histogram.FloatHistogram { } prev = curr } + } else if points[0].H.CounterResetHint != histogram.GaugeType || points[len(points)-1].H.CounterResetHint != histogram.GaugeType { + annos.Add(annotations.NewNativeHistogramNotGaugeWarning(metricName, pos)) } h.CounterResetHint = histogram.GaugeType - return h.Compact(0) + return h.Compact(0), nil } -// === delta(Matrix parser.ValueTypeMatrix) Vector === -func funcDelta(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === delta(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcDelta(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return extrapolatedRate(vals, args, enh, false, false) } -// === rate(node parser.ValueTypeMatrix) Vector === -func funcRate(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === rate(node parser.ValueTypeMatrix) (Vector, Annotations) === +func funcRate(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return extrapolatedRate(vals, args, enh, true, true) } -// === increase(node parser.ValueTypeMatrix) Vector === -func funcIncrease(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === increase(node parser.ValueTypeMatrix) (Vector, Annotations) === +func funcIncrease(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return extrapolatedRate(vals, args, enh, true, false) } -// === irate(node parser.ValueTypeMatrix) Vector === -func funcIrate(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === irate(node parser.ValueTypeMatrix) (Vector, Annotations) === +func funcIrate(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return instantValue(vals, enh.Out, true) } -// === idelta(node model.ValMatrix) Vector === -func funcIdelta(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === idelta(node model.ValMatrix) (Vector, Annotations) === +func funcIdelta(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return instantValue(vals, enh.Out, false) } -func instantValue(vals []parser.Value, out Vector, isRate bool) Vector { +func instantValue(vals []parser.Value, out Vector, isRate bool) (Vector, annotations.Annotations) { samples := vals[0].(Matrix)[0] // No sense in trying to compute a rate without at least two points. Drop // this Vector element. + // TODO: add RangeTooShortWarning if len(samples.Floats) < 2 { - return out + return out, nil } lastSample := samples.Floats[len(samples.Floats)-1] @@ -266,7 +278,7 @@ func instantValue(vals []parser.Value, out Vector, isRate bool) Vector { sampledInterval := lastSample.T - previousSample.T if sampledInterval == 0 { // Avoid dividing by 0. - return out + return out, nil } if isRate { @@ -274,7 +286,7 @@ func instantValue(vals []parser.Value, out Vector, isRate bool) Vector { resultValue /= float64(sampledInterval) / 1000 } - return append(out, Sample{F: resultValue}) + return append(out, Sample{F: resultValue}), nil } // Calculate the trend value at the given index i in raw data d. @@ -299,7 +311,7 @@ func calcTrendValue(i int, tf, s0, s1, b float64) float64 { // data. A lower smoothing factor increases the influence of historical data. The trend factor (0 < tf < 1) affects // how trends in historical data will affect the current data. A higher trend factor increases the influence. // of trends. Algorithm taken from https://en.wikipedia.org/wiki/Exponential_smoothing titled: "Double exponential smoothing". -func funcHoltWinters(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcHoltWinters(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { samples := vals[0].(Matrix)[0] // The smoothing factor argument. @@ -320,7 +332,7 @@ func funcHoltWinters(vals []parser.Value, args parser.Expressions, enh *EvalNode // Can't do the smoothing operation with less than two points. if l < 2 { - return enh.Out + return enh.Out, nil } var s0, s1, b float64 @@ -342,72 +354,132 @@ func funcHoltWinters(vals []parser.Value, args parser.Expressions, enh *EvalNode s0, s1 = s1, x+y } - return append(enh.Out, Sample{F: s1}) + return append(enh.Out, Sample{F: s1}), nil } -// === sort(node parser.ValueTypeVector) Vector === -func funcSort(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === sort(node parser.ValueTypeVector) (Vector, Annotations) === +func funcSort(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { // NaN should sort to the bottom, so take descending sort with NaN first and // reverse it. byValueSorter := vectorByReverseValueHeap(vals[0].(Vector)) sort.Sort(sort.Reverse(byValueSorter)) - return Vector(byValueSorter) + return Vector(byValueSorter), nil } -// === sortDesc(node parser.ValueTypeVector) Vector === -func funcSortDesc(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === sortDesc(node parser.ValueTypeVector) (Vector, Annotations) === +func funcSortDesc(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { // NaN should sort to the bottom, so take ascending sort with NaN first and // reverse it. byValueSorter := vectorByValueHeap(vals[0].(Vector)) sort.Sort(sort.Reverse(byValueSorter)) - return Vector(byValueSorter) + return Vector(byValueSorter), nil +} + +// === sort_by_label(vector parser.ValueTypeVector, label parser.ValueTypeString...) (Vector, Annotations) === +func funcSortByLabel(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + // In case the labels are the same, NaN should sort to the bottom, so take + // ascending sort with NaN first and reverse it. + var anno annotations.Annotations + vals[0], anno = funcSort(vals, args, enh) + labels := stringSliceFromArgs(args[1:]) + slices.SortFunc(vals[0].(Vector), func(a, b Sample) int { + // Iterate over each given label + for _, label := range labels { + lv1 := a.Metric.Get(label) + lv2 := b.Metric.Get(label) + + if lv1 == lv2 { + continue + } + + if natsort.Compare(lv1, lv2) { + return -1 + } + + return +1 + } + + return 0 + }) + + return vals[0].(Vector), anno +} + +// === sort_by_label_desc(vector parser.ValueTypeVector, label parser.ValueTypeString...) (Vector, Annotations) === +func funcSortByLabelDesc(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + // In case the labels are the same, NaN should sort to the bottom, so take + // ascending sort with NaN first and reverse it. + var anno annotations.Annotations + vals[0], anno = funcSortDesc(vals, args, enh) + labels := stringSliceFromArgs(args[1:]) + slices.SortFunc(vals[0].(Vector), func(a, b Sample) int { + // Iterate over each given label + for _, label := range labels { + lv1 := a.Metric.Get(label) + lv2 := b.Metric.Get(label) + + if lv1 == lv2 { + continue + } + + if natsort.Compare(lv1, lv2) { + return +1 + } + + return -1 + } + + return 0 + }) + + return vals[0].(Vector), anno } -// === clamp(Vector parser.ValueTypeVector, min, max Scalar) Vector === -func funcClamp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === clamp(Vector parser.ValueTypeVector, min, max Scalar) (Vector, Annotations) === +func funcClamp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { vec := vals[0].(Vector) min := vals[1].(Vector)[0].F max := vals[2].(Vector)[0].F if max < min { - return enh.Out + return enh.Out, nil } for _, el := range vec { enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(el.Metric), + Metric: el.Metric.DropMetricName(), F: math.Max(min, math.Min(max, el.F)), }) } - return enh.Out + return enh.Out, nil } -// === clamp_max(Vector parser.ValueTypeVector, max Scalar) Vector === -func funcClampMax(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === clamp_max(Vector parser.ValueTypeVector, max Scalar) (Vector, Annotations) === +func funcClampMax(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { vec := vals[0].(Vector) max := vals[1].(Vector)[0].F for _, el := range vec { enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(el.Metric), + Metric: el.Metric.DropMetricName(), F: math.Min(max, el.F), }) } - return enh.Out + return enh.Out, nil } -// === clamp_min(Vector parser.ValueTypeVector, min Scalar) Vector === -func funcClampMin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === clamp_min(Vector parser.ValueTypeVector, min Scalar) (Vector, Annotations) === +func funcClampMin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { vec := vals[0].(Vector) min := vals[1].(Vector)[0].F for _, el := range vec { enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(el.Metric), + Metric: el.Metric.DropMetricName(), F: math.Max(min, el.F), }) } - return enh.Out + return enh.Out, nil } -// === round(Vector parser.ValueTypeVector, toNearest=1 Scalar) Vector === -func funcRound(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === round(Vector parser.ValueTypeVector, toNearest=1 Scalar) (Vector, Annotations) === +func funcRound(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { vec := vals[0].(Vector) // round returns a number rounded to toNearest. // Ties are solved by rounding up. @@ -421,20 +493,20 @@ func funcRound(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper for _, el := range vec { f := math.Floor(el.F*toNearestInverse+0.5) / toNearestInverse enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(el.Metric), + Metric: el.Metric.DropMetricName(), F: f, }) } - return enh.Out + return enh.Out, nil } // === Scalar(node parser.ValueTypeVector) Scalar === -func funcScalar(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcScalar(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { v := vals[0].(Vector) if len(v) != 1 { - return append(enh.Out, Sample{F: math.NaN()}) + return append(enh.Out, Sample{F: math.NaN()}), nil } - return append(enh.Out, Sample{F: v[0].F}) + return append(enh.Out, Sample{F: v[0].F}), nil } func aggrOverTime(vals []parser.Value, enh *EvalNodeHelper, aggrFn func(Series) float64) Vector { @@ -443,14 +515,33 @@ func aggrOverTime(vals []parser.Value, enh *EvalNodeHelper, aggrFn func(Series) return append(enh.Out, Sample{F: aggrFn(el)}) } -// === avg_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcAvgOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - if len(vals[0].(Matrix)[0].Floats) == 0 { - // TODO(beorn7): The passed values only contain - // histograms. avg_over_time ignores histograms for now. If - // there are only histograms, we have to return without adding - // anything to enh.Out. - return enh.Out +func aggrHistOverTime(vals []parser.Value, enh *EvalNodeHelper, aggrFn func(Series) *histogram.FloatHistogram) Vector { + el := vals[0].(Matrix)[0] + + return append(enh.Out, Sample{H: aggrFn(el)}) +} + +// === avg_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcAvgOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + firstSeries := vals[0].(Matrix)[0] + if len(firstSeries.Floats) > 0 && len(firstSeries.Histograms) > 0 { + metricName := firstSeries.Metric.Get(labels.MetricName) + return enh.Out, annotations.New().Add(annotations.NewMixedFloatsHistogramsWarning(metricName, args[0].PositionRange())) + } + if len(firstSeries.Floats) == 0 { + // The passed values only contain histograms. + return aggrHistOverTime(vals, enh, func(s Series) *histogram.FloatHistogram { + count := 1 + mean := s.Histograms[0].H.Copy() + for _, h := range s.Histograms[1:] { + count++ + left := h.H.Copy().Div(float64(count)) + right := mean.Copy().Div(float64(count)) + toAdd := left.Sub(right) + mean.Add(toAdd) + } + return mean + }), nil } return aggrOverTime(vals, enh, func(s Series) float64 { var mean, count, c float64 @@ -480,18 +571,18 @@ func funcAvgOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNode return mean } return mean + c - }) + }), nil } -// === count_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcCountOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === count_over_time(Matrix parser.ValueTypeMatrix) (Vector, Notes) === +func funcCountOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return aggrOverTime(vals, enh, func(s Series) float64 { return float64(len(s.Floats) + len(s.Histograms)) - }) + }), nil } -// === last_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcLastOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === last_over_time(Matrix parser.ValueTypeMatrix) (Vector, Notes) === +func funcLastOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { el := vals[0].(Matrix)[0] var f FPoint @@ -508,22 +599,41 @@ func funcLastOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNod return append(enh.Out, Sample{ Metric: el.Metric, F: f.F, - }) + }), nil } return append(enh.Out, Sample{ Metric: el.Metric, - H: h.H, - }) + H: h.H.Copy(), + }), nil +} + +// === mad_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcMadOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + if len(vals[0].(Matrix)[0].Floats) == 0 { + return enh.Out, nil + } + return aggrOverTime(vals, enh, func(s Series) float64 { + values := make(vectorByValueHeap, 0, len(s.Floats)) + for _, f := range s.Floats { + values = append(values, Sample{F: f.F}) + } + median := quantile(0.5, values) + values = make(vectorByValueHeap, 0, len(s.Floats)) + for _, f := range s.Floats { + values = append(values, Sample{F: math.Abs(f.F - median)}) + } + return quantile(0.5, values) + }), nil } -// === max_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcMaxOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === max_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcMaxOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { if len(vals[0].(Matrix)[0].Floats) == 0 { // TODO(beorn7): The passed values only contain // histograms. max_over_time ignores histograms for now. If // there are only histograms, we have to return without adding // anything to enh.Out. - return enh.Out + return enh.Out, nil } return aggrOverTime(vals, enh, func(s Series) float64 { max := s.Floats[0].F @@ -533,17 +643,17 @@ func funcMaxOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNode } } return max - }) + }), nil } -// === min_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcMinOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === min_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcMinOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { if len(vals[0].(Matrix)[0].Floats) == 0 { // TODO(beorn7): The passed values only contain // histograms. min_over_time ignores histograms for now. If // there are only histograms, we have to return without adding // anything to enh.Out. - return enh.Out + return enh.Out, nil } return aggrOverTime(vals, enh, func(s Series) float64 { min := s.Floats[0].F @@ -553,17 +663,25 @@ func funcMinOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNode } } return min - }) -} - -// === sum_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcSumOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - if len(vals[0].(Matrix)[0].Floats) == 0 { - // TODO(beorn7): The passed values only contain - // histograms. sum_over_time ignores histograms for now. If - // there are only histograms, we have to return without adding - // anything to enh.Out. - return enh.Out + }), nil +} + +// === sum_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcSumOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + firstSeries := vals[0].(Matrix)[0] + if len(firstSeries.Floats) > 0 && len(firstSeries.Histograms) > 0 { + metricName := firstSeries.Metric.Get(labels.MetricName) + return enh.Out, annotations.New().Add(annotations.NewMixedFloatsHistogramsWarning(metricName, args[0].PositionRange())) + } + if len(firstSeries.Floats) == 0 { + // The passed values only contain histograms. + return aggrHistOverTime(vals, enh, func(s Series) *histogram.FloatHistogram { + sum := s.Histograms[0].H.Copy() + for _, h := range s.Histograms[1:] { + sum.Add(h.H) + } + return sum + }), nil } return aggrOverTime(vals, enh, func(s Series) float64 { var sum, c float64 @@ -574,11 +692,11 @@ func funcSumOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNode return sum } return sum + c - }) + }), nil } -// === quantile_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcQuantileOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === quantile_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcQuantileOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { q := vals[0].(Vector)[0].F el := vals[1].(Matrix)[0] if len(el.Floats) == 0 { @@ -586,24 +704,29 @@ func funcQuantileOverTime(vals []parser.Value, args parser.Expressions, enh *Eva // histograms. quantile_over_time ignores histograms for now. If // there are only histograms, we have to return without adding // anything to enh.Out. - return enh.Out + return enh.Out, nil + } + + var annos annotations.Annotations + if math.IsNaN(q) || q < 0 || q > 1 { + annos.Add(annotations.NewInvalidQuantileWarning(q, args[0].PositionRange())) } values := make(vectorByValueHeap, 0, len(el.Floats)) for _, f := range el.Floats { values = append(values, Sample{F: f.F}) } - return append(enh.Out, Sample{F: quantile(q, values)}) + return append(enh.Out, Sample{F: quantile(q, values)}), annos } -// === stddev_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcStddevOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === stddev_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcStddevOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { if len(vals[0].(Matrix)[0].Floats) == 0 { // TODO(beorn7): The passed values only contain // histograms. stddev_over_time ignores histograms for now. If // there are only histograms, we have to return without adding // anything to enh.Out. - return enh.Out + return enh.Out, nil } return aggrOverTime(vals, enh, func(s Series) float64 { var count float64 @@ -616,17 +739,17 @@ func funcStddevOverTime(vals []parser.Value, args parser.Expressions, enh *EvalN aux, cAux = kahanSumInc(delta*(f.F-(mean+cMean)), aux, cAux) } return math.Sqrt((aux + cAux) / count) - }) + }), nil } -// === stdvar_over_time(Matrix parser.ValueTypeMatrix) Vector === -func funcStdvarOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === stdvar_over_time(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcStdvarOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { if len(vals[0].(Matrix)[0].Floats) == 0 { // TODO(beorn7): The passed values only contain // histograms. stdvar_over_time ignores histograms for now. If // there are only histograms, we have to return without adding // anything to enh.Out. - return enh.Out + return enh.Out, nil } return aggrOverTime(vals, enh, func(s Series) float64 { var count float64 @@ -639,42 +762,42 @@ func funcStdvarOverTime(vals []parser.Value, args parser.Expressions, enh *EvalN aux, cAux = kahanSumInc(delta*(f.F-(mean+cMean)), aux, cAux) } return (aux + cAux) / count - }) + }), nil } -// === absent(Vector parser.ValueTypeVector) Vector === -func funcAbsent(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === absent(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAbsent(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { if len(vals[0].(Vector)) > 0 { - return enh.Out + return enh.Out, nil } return append(enh.Out, Sample{ Metric: createLabelsForAbsentFunction(args[0]), F: 1, - }) + }), nil } -// === absent_over_time(Vector parser.ValueTypeMatrix) Vector === +// === absent_over_time(Vector parser.ValueTypeMatrix) (Vector, Annotations) === // As this function has a matrix as argument, it does not get all the Series. // This function will return 1 if the matrix has at least one element. // Due to engine optimization, this function is only called when this condition is true. // Then, the engine post-processes the results to get the expected output. -func funcAbsentOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return append(enh.Out, Sample{F: 1}) +func funcAbsentOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return append(enh.Out, Sample{F: 1}), nil } -// === present_over_time(Vector parser.ValueTypeMatrix) Vector === -func funcPresentOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === present_over_time(Vector parser.ValueTypeMatrix) (Vector, Annotations) === +func funcPresentOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return aggrOverTime(vals, enh, func(s Series) float64 { return 1 - }) + }), nil } func simpleFunc(vals []parser.Value, enh *EvalNodeHelper, f func(float64) float64) Vector { for _, el := range vals[0].(Vector) { if el.H == nil { // Process only float samples. enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(el.Metric), + Metric: el.Metric.DropMetricName(), F: f(el.F), }) } @@ -682,127 +805,127 @@ func simpleFunc(vals []parser.Value, enh *EvalNodeHelper, f func(float64) float6 return enh.Out } -// === abs(Vector parser.ValueTypeVector) Vector === -func funcAbs(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Abs) +// === abs(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAbs(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Abs), nil } -// === ceil(Vector parser.ValueTypeVector) Vector === -func funcCeil(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Ceil) +// === ceil(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcCeil(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Ceil), nil } -// === floor(Vector parser.ValueTypeVector) Vector === -func funcFloor(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Floor) +// === floor(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcFloor(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Floor), nil } -// === exp(Vector parser.ValueTypeVector) Vector === -func funcExp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Exp) +// === exp(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcExp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Exp), nil } -// === sqrt(Vector VectorNode) Vector === -func funcSqrt(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Sqrt) +// === sqrt(Vector VectorNode) (Vector, Annotations) === +func funcSqrt(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Sqrt), nil } -// === ln(Vector parser.ValueTypeVector) Vector === -func funcLn(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Log) +// === ln(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcLn(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Log), nil } -// === log2(Vector parser.ValueTypeVector) Vector === -func funcLog2(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Log2) +// === log2(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcLog2(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Log2), nil } -// === log10(Vector parser.ValueTypeVector) Vector === -func funcLog10(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Log10) +// === log10(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcLog10(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Log10), nil } -// === sin(Vector parser.ValueTypeVector) Vector === -func funcSin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Sin) +// === sin(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcSin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Sin), nil } -// === cos(Vector parser.ValueTypeVector) Vector === -func funcCos(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Cos) +// === cos(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcCos(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Cos), nil } -// === tan(Vector parser.ValueTypeVector) Vector === -func funcTan(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Tan) +// === tan(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcTan(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Tan), nil } -// == asin(Vector parser.ValueTypeVector) Vector === -func funcAsin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Asin) +// === asin(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAsin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Asin), nil } -// == acos(Vector parser.ValueTypeVector) Vector === -func funcAcos(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Acos) +// === acos(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAcos(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Acos), nil } -// == atan(Vector parser.ValueTypeVector) Vector === -func funcAtan(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Atan) +// === atan(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAtan(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Atan), nil } -// == sinh(Vector parser.ValueTypeVector) Vector === -func funcSinh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Sinh) +// === sinh(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcSinh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Sinh), nil } -// == cosh(Vector parser.ValueTypeVector) Vector === -func funcCosh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Cosh) +// === cosh(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcCosh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Cosh), nil } -// == tanh(Vector parser.ValueTypeVector) Vector === -func funcTanh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Tanh) +// === tanh(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcTanh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Tanh), nil } -// == asinh(Vector parser.ValueTypeVector) Vector === -func funcAsinh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Asinh) +// === asinh(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAsinh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Asinh), nil } -// == acosh(Vector parser.ValueTypeVector) Vector === -func funcAcosh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Acosh) +// === acosh(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAcosh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Acosh), nil } -// == atanh(Vector parser.ValueTypeVector) Vector === -func funcAtanh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return simpleFunc(vals, enh, math.Atanh) +// === atanh(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcAtanh(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return simpleFunc(vals, enh, math.Atanh), nil } -// === rad(Vector parser.ValueTypeVector) Vector === -func funcRad(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === rad(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcRad(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return simpleFunc(vals, enh, func(v float64) float64 { return v * math.Pi / 180 - }) + }), nil } -// === deg(Vector parser.ValueTypeVector) Vector === -func funcDeg(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === deg(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcDeg(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return simpleFunc(vals, enh, func(v float64) float64 { return v * 180 / math.Pi - }) + }), nil } // === pi() Scalar === -func funcPi(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - return Vector{Sample{F: math.Pi}} +func funcPi(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return Vector{Sample{F: math.Pi}}, nil } -// === sgn(Vector parser.ValueTypeVector) Vector === -func funcSgn(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === sgn(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcSgn(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return simpleFunc(vals, enh, func(v float64) float64 { switch { case v < 0: @@ -812,19 +935,19 @@ func funcSgn(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) default: return v } - }) + }), nil } -// === timestamp(Vector parser.ValueTypeVector) Vector === -func funcTimestamp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === timestamp(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcTimestamp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { vec := vals[0].(Vector) for _, el := range vec { enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(el.Metric), + Metric: el.Metric.DropMetricName(), F: float64(el.T) / 1000, }) } - return enh.Out + return enh.Out, nil } func kahanSum(samples []float64) float64 { @@ -893,39 +1016,39 @@ func linearRegression(samples []FPoint, interceptTime int64) (slope, intercept f return slope, intercept } -// === deriv(node parser.ValueTypeMatrix) Vector === -func funcDeriv(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === deriv(node parser.ValueTypeMatrix) (Vector, Annotations) === +func funcDeriv(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { samples := vals[0].(Matrix)[0] // No sense in trying to compute a derivative without at least two points. // Drop this Vector element. if len(samples.Floats) < 2 { - return enh.Out + return enh.Out, nil } // We pass in an arbitrary timestamp that is near the values in use // to avoid floating point accuracy issues, see // https://github.com/prometheus/prometheus/issues/2674 slope, _ := linearRegression(samples.Floats, samples.Floats[0].T) - return append(enh.Out, Sample{F: slope}) + return append(enh.Out, Sample{F: slope}), nil } -// === predict_linear(node parser.ValueTypeMatrix, k parser.ValueTypeScalar) Vector === -func funcPredictLinear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === predict_linear(node parser.ValueTypeMatrix, k parser.ValueTypeScalar) (Vector, Annotations) === +func funcPredictLinear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { samples := vals[0].(Matrix)[0] duration := vals[1].(Vector)[0].F // No sense in trying to predict anything without at least two points. // Drop this Vector element. if len(samples.Floats) < 2 { - return enh.Out + return enh.Out, nil } slope, intercept := linearRegression(samples.Floats, enh.Ts) - return append(enh.Out, Sample{F: slope*duration + intercept}) + return append(enh.Out, Sample{F: slope*duration + intercept}), nil } -// === histogram_count(Vector parser.ValueTypeVector) Vector === -func funcHistogramCount(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === histogram_count(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcHistogramCount(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { inVec := vals[0].(Vector) for _, sample := range inVec { @@ -934,15 +1057,15 @@ func funcHistogramCount(vals []parser.Value, args parser.Expressions, enh *EvalN continue } enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(sample.Metric), + Metric: sample.Metric.DropMetricName(), F: sample.H.Count, }) } - return enh.Out + return enh.Out, nil } -// === histogram_sum(Vector parser.ValueTypeVector) Vector === -func funcHistogramSum(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === histogram_sum(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcHistogramSum(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { inVec := vals[0].(Vector) for _, sample := range inVec { @@ -951,15 +1074,81 @@ func funcHistogramSum(vals []parser.Value, args parser.Expressions, enh *EvalNod continue } enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(sample.Metric), + Metric: sample.Metric.DropMetricName(), F: sample.H.Sum, }) } - return enh.Out + return enh.Out, nil +} + +// === histogram_stddev(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcHistogramStdDev(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + inVec := vals[0].(Vector) + + for _, sample := range inVec { + // Skip non-histogram samples. + if sample.H == nil { + continue + } + mean := sample.H.Sum / sample.H.Count + var variance, cVariance float64 + it := sample.H.AllBucketIterator() + for it.Next() { + bucket := it.At() + var val float64 + if bucket.Lower <= 0 && 0 <= bucket.Upper { + val = 0 + } else { + val = math.Sqrt(bucket.Upper * bucket.Lower) + } + delta := val - mean + variance, cVariance = kahanSumInc(bucket.Count*delta*delta, variance, cVariance) + } + variance += cVariance + variance /= sample.H.Count + enh.Out = append(enh.Out, Sample{ + Metric: sample.Metric.DropMetricName(), + F: math.Sqrt(variance), + }) + } + return enh.Out, nil } -// === histogram_fraction(lower, upper parser.ValueTypeScalar, Vector parser.ValueTypeVector) Vector === -func funcHistogramFraction(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === histogram_stdvar(Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcHistogramStdVar(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + inVec := vals[0].(Vector) + + for _, sample := range inVec { + // Skip non-histogram samples. + if sample.H == nil { + continue + } + mean := sample.H.Sum / sample.H.Count + var variance, cVariance float64 + it := sample.H.AllBucketIterator() + for it.Next() { + bucket := it.At() + var val float64 + if bucket.Lower <= 0 && 0 <= bucket.Upper { + val = 0 + } else { + val = math.Sqrt(bucket.Upper * bucket.Lower) + } + delta := val - mean + variance, cVariance = kahanSumInc(bucket.Count*delta*delta, variance, cVariance) + } + variance += cVariance + variance /= sample.H.Count + enh.Out = append(enh.Out, Sample{ + Metric: sample.Metric.DropMetricName(), + F: variance, + }) + } + return enh.Out, nil +} + +// === histogram_fraction(lower, upper parser.ValueTypeScalar, Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcHistogramFraction(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { lower := vals[0].(Vector)[0].F upper := vals[1].(Vector)[0].F inVec := vals[2].(Vector) @@ -970,17 +1159,22 @@ func funcHistogramFraction(vals []parser.Value, args parser.Expressions, enh *Ev continue } enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(sample.Metric), + Metric: sample.Metric.DropMetricName(), F: histogramFraction(lower, upper, sample.H), }) } - return enh.Out + return enh.Out, nil } -// === histogram_quantile(k parser.ValueTypeScalar, Vector parser.ValueTypeVector) Vector === -func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === histogram_quantile(k parser.ValueTypeScalar, Vector parser.ValueTypeVector) (Vector, Annotations) === +func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { q := vals[0].(Vector)[0].F inVec := vals[1].(Vector) + var annos annotations.Annotations + + if math.IsNaN(q) || q < 0 || q > 1 { + annos.Add(annotations.NewInvalidQuantileWarning(q, args[0].PositionRange())) + } if enh.signatureToMetricWithBuckets == nil { enh.signatureToMetricWithBuckets = map[string]*metricWithBuckets{} @@ -993,7 +1187,7 @@ func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *Ev var histogramSamples []Sample for _, sample := range inVec { - // We are only looking for conventional buckets here. Remember + // We are only looking for classic buckets here. Remember // the histograms for later treatment. if sample.H != nil { histogramSamples = append(histogramSamples, sample) @@ -1004,8 +1198,7 @@ func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *Ev sample.Metric.Get(model.BucketLabel), 64, ) if err != nil { - // Oops, no bucket label or malformed label value. Skip. - // TODO(beorn7): Issue a warning somehow. + annos.Add(annotations.NewBadBucketLabelWarning(sample.Metric.Get(labels.MetricName), sample.Metric.Get(model.BucketLabel), args[1].PositionRange())) continue } enh.lblBuf = sample.Metric.BytesWithoutLabels(enh.lblBuf, labels.BucketLabel) @@ -1025,37 +1218,41 @@ func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *Ev // Now deal with the histograms. for _, sample := range histogramSamples { // We have to reconstruct the exact same signature as above for - // a conventional histogram, just ignoring any le label. + // a classic histogram, just ignoring any le label. enh.lblBuf = sample.Metric.Bytes(enh.lblBuf) if mb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]; ok && len(mb.buckets) > 0 { - // At this data point, we have conventional histogram + // At this data point, we have classic histogram // buckets and a native histogram with the same name and // labels. Do not evaluate anything. - // TODO(beorn7): Issue a warning somehow. + annos.Add(annotations.NewMixedClassicNativeHistogramsWarning(sample.Metric.Get(labels.MetricName), args[1].PositionRange())) delete(enh.signatureToMetricWithBuckets, string(enh.lblBuf)) continue } enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(sample.Metric), + Metric: sample.Metric.DropMetricName(), F: histogramQuantile(q, sample.H), }) } for _, mb := range enh.signatureToMetricWithBuckets { if len(mb.buckets) > 0 { + res, forcedMonotonicity, _ := bucketQuantile(q, mb.buckets) enh.Out = append(enh.Out, Sample{ Metric: mb.metric, - F: bucketQuantile(q, mb.buckets), + F: res, }) + if forcedMonotonicity { + annos.Add(annotations.NewHistogramQuantileForcedMonotonicityInfo(mb.metric.Get(labels.MetricName), args[1].PositionRange())) + } } } - return enh.Out + return enh.Out, annos } -// === resets(Matrix parser.ValueTypeMatrix) Vector === -func funcResets(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === resets(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcResets(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { floats := vals[0].(Matrix)[0].Floats histograms := vals[0].(Matrix)[0].Histograms resets := 0 @@ -1082,17 +1279,17 @@ func funcResets(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelpe } } - return append(enh.Out, Sample{F: float64(resets)}) + return append(enh.Out, Sample{F: float64(resets)}), nil } -// === changes(Matrix parser.ValueTypeMatrix) Vector === -func funcChanges(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === changes(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === +func funcChanges(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { floats := vals[0].(Matrix)[0].Floats changes := 0 if len(floats) == 0 { // TODO(beorn7): Only histogram values, still need to add support. - return enh.Out + return enh.Out, nil } prev := floats[0].F @@ -1104,11 +1301,11 @@ func funcChanges(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelp prev = current } - return append(enh.Out, Sample{F: float64(changes)}) + return append(enh.Out, Sample{F: float64(changes)}), nil } -// === label_replace(Vector parser.ValueTypeVector, dst_label, replacement, src_labelname, regex parser.ValueTypeString) Vector === -func funcLabelReplace(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === label_replace(Vector parser.ValueTypeVector, dst_label, replacement, src_labelname, regex parser.ValueTypeString) (Vector, Annotations) === +func funcLabelReplace(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { var ( vector = vals[0].(Vector) dst = stringFromArg(args[1]) @@ -1159,20 +1356,20 @@ func funcLabelReplace(vals []parser.Value, args parser.Expressions, enh *EvalNod H: el.H, }) } - return enh.Out + return enh.Out, nil } -// === Vector(s Scalar) Vector === -func funcVector(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === Vector(s Scalar) (Vector, Annotations) === +func funcVector(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return append(enh.Out, Sample{ Metric: labels.Labels{}, F: vals[0].(Vector)[0].F, - }) + }), nil } -// === label_join(vector model.ValVector, dest_labelname, separator, src_labelname...) Vector === -func funcLabelJoin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +// === label_join(vector model.ValVector, dest_labelname, separator, src_labelname...) (Vector, Annotations) === +func funcLabelJoin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { var ( vector = vals[0].(Vector) dst = stringFromArg(args[1]) @@ -1227,7 +1424,7 @@ func funcLabelJoin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHe H: el.H, }) } - return enh.Out + return enh.Out, nil } // Common code for date related functions. @@ -1243,7 +1440,7 @@ func dateWrapper(vals []parser.Value, enh *EvalNodeHelper, f func(time.Time) flo for _, el := range vals[0].(Vector) { t := time.Unix(int64(el.F), 0).UTC() enh.Out = append(enh.Out, Sample{ - Metric: enh.DropMetricName(el.Metric), + Metric: el.Metric.DropMetricName(), F: f(t), }) } @@ -1251,59 +1448,59 @@ func dateWrapper(vals []parser.Value, enh *EvalNodeHelper, f func(time.Time) flo } // === days_in_month(v Vector) Scalar === -func funcDaysInMonth(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcDaysInMonth(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(32 - time.Date(t.Year(), t.Month(), 32, 0, 0, 0, 0, time.UTC).Day()) - }) + }), nil } // === day_of_month(v Vector) Scalar === -func funcDayOfMonth(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcDayOfMonth(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(t.Day()) - }) + }), nil } // === day_of_week(v Vector) Scalar === -func funcDayOfWeek(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcDayOfWeek(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(t.Weekday()) - }) + }), nil } // === day_of_year(v Vector) Scalar === -func funcDayOfYear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcDayOfYear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(t.YearDay()) - }) + }), nil } // === hour(v Vector) Scalar === -func funcHour(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcHour(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(t.Hour()) - }) + }), nil } // === minute(v Vector) Scalar === -func funcMinute(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcMinute(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(t.Minute()) - }) + }), nil } // === month(v Vector) Scalar === -func funcMonth(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcMonth(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(t.Month()) - }) + }), nil } // === year(v Vector) Scalar === -func funcYear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { +func funcYear(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return dateWrapper(vals, enh, func(t time.Time) float64 { return float64(t.Year()) - }) + }), nil } // FunctionCalls is a list of all functions supported by PromQL, including their types. @@ -1339,6 +1536,8 @@ var FunctionCalls = map[string]FunctionCall{ "histogram_fraction": funcHistogramFraction, "histogram_quantile": funcHistogramQuantile, "histogram_sum": funcHistogramSum, + "histogram_stddev": funcHistogramStdDev, + "histogram_stdvar": funcHistogramStdVar, "holt_winters": funcHoltWinters, "hour": funcHour, "idelta": funcIdelta, @@ -1350,6 +1549,7 @@ var FunctionCalls = map[string]FunctionCall{ "log10": funcLog10, "log2": funcLog2, "last_over_time": funcLastOverTime, + "mad_over_time": funcMadOverTime, "max_over_time": funcMaxOverTime, "min_over_time": funcMinOverTime, "minute": funcMinute, @@ -1368,6 +1568,8 @@ var FunctionCalls = map[string]FunctionCall{ "sinh": funcSinh, "sort": funcSort, "sort_desc": funcSortDesc, + "sort_by_label": funcSortByLabel, + "sort_by_label_desc": funcSortByLabelDesc, "sqrt": funcSqrt, "stddev_over_time": funcStddevOverTime, "stdvar_over_time": funcStdvarOverTime, @@ -1512,3 +1714,11 @@ func stringFromArg(e parser.Expr) string { unwrapParenExpr(&tmp) // Optionally unwrap ParenExpr return tmp.(*parser.StringLiteral).Val } + +func stringSliceFromArgs(args parser.Expressions) []string { + tmp := make([]string, len(args)) + for i := 0; i < len(args); i++ { + tmp[i] = stringFromArg(args[i]) + } + return tmp +} diff --git a/vendor/github.com/prometheus/prometheus/promql/fuzz.go b/vendor/github.com/prometheus/prometheus/promql/fuzz.go index 39933378e..d2e5925eb 100644 --- a/vendor/github.com/prometheus/prometheus/promql/fuzz.go +++ b/vendor/github.com/prometheus/prometheus/promql/fuzz.go @@ -13,7 +13,6 @@ // Only build when go-fuzz is in use //go:build gofuzz -// +build gofuzz package promql @@ -58,7 +57,7 @@ const ( ) func fuzzParseMetricWithContentType(in []byte, contentType string) int { - p, warning := textparse.New(in, contentType) + p, warning := textparse.New(in, contentType, false) if warning != nil { // An invalid content type is being passed, which should not happen // in this context. diff --git a/vendor/github.com/prometheus/prometheus/promql/parser/ast.go b/vendor/github.com/prometheus/prometheus/promql/parser/ast.go index 86f139499..379352599 100644 --- a/vendor/github.com/prometheus/prometheus/promql/parser/ast.go +++ b/vendor/github.com/prometheus/prometheus/promql/parser/ast.go @@ -20,6 +20,8 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/storage" + + "github.com/prometheus/prometheus/promql/parser/posrange" ) // Node is a generic interface for all nodes in an AST. @@ -45,7 +47,7 @@ type Node interface { Pretty(level int) string // PositionRange returns the position of the AST Node in the query string. - PositionRange() PositionRange + PositionRange() posrange.PositionRange } // Statement is a generic interface for all statements. @@ -53,7 +55,6 @@ type Statement interface { Node // PromQLStmt ensures that no other type accidentally implements the interface - // nolint:unused PromQLStmt() } @@ -94,7 +95,7 @@ type AggregateExpr struct { Param Expr // Parameter used by some aggregators. Grouping []string // The labels by which to group the Vector. Without bool // Whether to drop the given labels rather than keep them. - PosRange PositionRange + PosRange posrange.PositionRange } // BinaryExpr represents a binary expression between two child expressions. @@ -115,7 +116,7 @@ type Call struct { Func *Function // The function that was called. Args Expressions // Arguments used in the call. - PosRange PositionRange + PosRange posrange.PositionRange } // MatrixSelector represents a Matrix selection. @@ -125,7 +126,7 @@ type MatrixSelector struct { VectorSelector Expr Range time.Duration - EndPos Pos + EndPos posrange.Pos } // SubqueryExpr represents a subquery. @@ -143,27 +144,27 @@ type SubqueryExpr struct { StartOrEnd ItemType // Set when @ is used with start() or end() Step time.Duration - EndPos Pos + EndPos posrange.Pos } // NumberLiteral represents a number. type NumberLiteral struct { Val float64 - PosRange PositionRange + PosRange posrange.PositionRange } // ParenExpr wraps an expression so it cannot be disassembled as a consequence // of operator precedence. type ParenExpr struct { Expr Expr - PosRange PositionRange + PosRange posrange.PositionRange } // StringLiteral represents a string. type StringLiteral struct { Val string - PosRange PositionRange + PosRange posrange.PositionRange } // UnaryExpr represents a unary operation on another expression. @@ -172,7 +173,7 @@ type UnaryExpr struct { Op ItemType Expr Expr - StartPos Pos + StartPos posrange.Pos } // StepInvariantExpr represents a query which evaluates to the same result @@ -184,7 +185,9 @@ type StepInvariantExpr struct { func (e *StepInvariantExpr) String() string { return e.Expr.String() } -func (e *StepInvariantExpr) PositionRange() PositionRange { return e.Expr.PositionRange() } +func (e *StepInvariantExpr) PositionRange() posrange.PositionRange { + return e.Expr.PositionRange() +} // VectorSelector represents a Vector selection. type VectorSelector struct { @@ -204,7 +207,7 @@ type VectorSelector struct { UnexpandedSeriesSet storage.SeriesSet Series []storage.Series - PosRange PositionRange + PosRange posrange.PositionRange } // TestStmt is an internal helper statement that allows execution @@ -215,8 +218,8 @@ func (TestStmt) String() string { return "test statement" } func (TestStmt) PromQLStmt() {} func (t TestStmt) Pretty(int) string { return t.String() } -func (TestStmt) PositionRange() PositionRange { - return PositionRange{ +func (TestStmt) PositionRange() posrange.PositionRange { + return posrange.PositionRange{ Start: -1, End: -1, } @@ -405,17 +408,11 @@ func Children(node Node) []Node { } } -// PositionRange describes a position in the input string of the parser. -type PositionRange struct { - Start Pos - End Pos -} - // mergeRanges is a helper function to merge the PositionRanges of two Nodes. // Note that the arguments must be in the same order as they // occur in the input string. -func mergeRanges(first, last Node) PositionRange { - return PositionRange{ +func mergeRanges(first, last Node) posrange.PositionRange { + return posrange.PositionRange{ Start: first.PositionRange().Start, End: last.PositionRange().End, } @@ -423,33 +420,33 @@ func mergeRanges(first, last Node) PositionRange { // Item implements the Node interface. // This makes it possible to call mergeRanges on them. -func (i *Item) PositionRange() PositionRange { - return PositionRange{ +func (i *Item) PositionRange() posrange.PositionRange { + return posrange.PositionRange{ Start: i.Pos, - End: i.Pos + Pos(len(i.Val)), + End: i.Pos + posrange.Pos(len(i.Val)), } } -func (e *AggregateExpr) PositionRange() PositionRange { +func (e *AggregateExpr) PositionRange() posrange.PositionRange { return e.PosRange } -func (e *BinaryExpr) PositionRange() PositionRange { +func (e *BinaryExpr) PositionRange() posrange.PositionRange { return mergeRanges(e.LHS, e.RHS) } -func (e *Call) PositionRange() PositionRange { +func (e *Call) PositionRange() posrange.PositionRange { return e.PosRange } -func (e *EvalStmt) PositionRange() PositionRange { +func (e *EvalStmt) PositionRange() posrange.PositionRange { return e.Expr.PositionRange() } -func (e Expressions) PositionRange() PositionRange { +func (e Expressions) PositionRange() posrange.PositionRange { if len(e) == 0 { // Position undefined. - return PositionRange{ + return posrange.PositionRange{ Start: -1, End: -1, } @@ -457,39 +454,39 @@ func (e Expressions) PositionRange() PositionRange { return mergeRanges(e[0], e[len(e)-1]) } -func (e *MatrixSelector) PositionRange() PositionRange { - return PositionRange{ +func (e *MatrixSelector) PositionRange() posrange.PositionRange { + return posrange.PositionRange{ Start: e.VectorSelector.PositionRange().Start, End: e.EndPos, } } -func (e *SubqueryExpr) PositionRange() PositionRange { - return PositionRange{ +func (e *SubqueryExpr) PositionRange() posrange.PositionRange { + return posrange.PositionRange{ Start: e.Expr.PositionRange().Start, End: e.EndPos, } } -func (e *NumberLiteral) PositionRange() PositionRange { +func (e *NumberLiteral) PositionRange() posrange.PositionRange { return e.PosRange } -func (e *ParenExpr) PositionRange() PositionRange { +func (e *ParenExpr) PositionRange() posrange.PositionRange { return e.PosRange } -func (e *StringLiteral) PositionRange() PositionRange { +func (e *StringLiteral) PositionRange() posrange.PositionRange { return e.PosRange } -func (e *UnaryExpr) PositionRange() PositionRange { - return PositionRange{ +func (e *UnaryExpr) PositionRange() posrange.PositionRange { + return posrange.PositionRange{ Start: e.StartPos, End: e.Expr.PositionRange().End, } } -func (e *VectorSelector) PositionRange() PositionRange { +func (e *VectorSelector) PositionRange() posrange.PositionRange { return e.PosRange } diff --git a/vendor/github.com/prometheus/prometheus/promql/parser/functions.go b/vendor/github.com/prometheus/prometheus/promql/parser/functions.go index 450021328..46d50d547 100644 --- a/vendor/github.com/prometheus/prometheus/promql/parser/functions.go +++ b/vendor/github.com/prometheus/prometheus/promql/parser/functions.go @@ -16,12 +16,16 @@ package parser // Function represents a function of the expression language and is // used by function nodes. type Function struct { - Name string - ArgTypes []ValueType - Variadic int - ReturnType ValueType + Name string + ArgTypes []ValueType + Variadic int + ReturnType ValueType + Experimental bool } +// EnableExperimentalFunctions controls whether experimentalFunctions are enabled. +var EnableExperimentalFunctions bool + // Functions is a list of all functions supported by PromQL, including their types. var Functions = map[string]*Function{ "abs": { @@ -173,6 +177,16 @@ var Functions = map[string]*Function{ ArgTypes: []ValueType{ValueTypeVector}, ReturnType: ValueTypeVector, }, + "histogram_stddev": { + Name: "histogram_stddev", + ArgTypes: []ValueType{ValueTypeVector}, + ReturnType: ValueTypeVector, + }, + "histogram_stdvar": { + Name: "histogram_stdvar", + ArgTypes: []ValueType{ValueTypeVector}, + ReturnType: ValueTypeVector, + }, "histogram_fraction": { Name: "histogram_fraction", ArgTypes: []ValueType{ValueTypeScalar, ValueTypeScalar, ValueTypeVector}, @@ -240,6 +254,12 @@ var Functions = map[string]*Function{ ArgTypes: []ValueType{ValueTypeVector}, ReturnType: ValueTypeVector, }, + "mad_over_time": { + Name: "mad_over_time", + ArgTypes: []ValueType{ValueTypeMatrix}, + ReturnType: ValueTypeVector, + Experimental: true, + }, "max_over_time": { Name: "max_over_time", ArgTypes: []ValueType{ValueTypeMatrix}, @@ -333,6 +353,20 @@ var Functions = map[string]*Function{ ArgTypes: []ValueType{ValueTypeVector}, ReturnType: ValueTypeVector, }, + "sort_by_label": { + Name: "sort_by_label", + ArgTypes: []ValueType{ValueTypeVector, ValueTypeString}, + Variadic: -1, + ReturnType: ValueTypeVector, + Experimental: true, + }, + "sort_by_label_desc": { + Name: "sort_by_label_desc", + ArgTypes: []ValueType{ValueTypeVector, ValueTypeString}, + Variadic: -1, + ReturnType: ValueTypeVector, + Experimental: true, + }, "sqrt": { Name: "sqrt", ArgTypes: []ValueType{ValueTypeVector}, @@ -387,7 +421,7 @@ var Functions = map[string]*Function{ } // getFunction returns a predefined Function object for the given name. -func getFunction(name string) (*Function, bool) { - function, ok := Functions[name] +func getFunction(name string, functions map[string]*Function) (*Function, bool) { + function, ok := functions[name] return function, ok } diff --git a/vendor/github.com/prometheus/prometheus/promql/parser/generated_parser.y b/vendor/github.com/prometheus/prometheus/promql/parser/generated_parser.y index b1c604eec..dce79f769 100644 --- a/vendor/github.com/prometheus/prometheus/promql/parser/generated_parser.y +++ b/vendor/github.com/prometheus/prometheus/promql/parser/generated_parser.y @@ -21,23 +21,29 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/value" + "github.com/prometheus/prometheus/model/histogram" + "github.com/prometheus/prometheus/promql/parser/posrange" ) %} %union { - node Node - item Item - matchers []*labels.Matcher - matcher *labels.Matcher - label labels.Label - labels labels.Labels - lblList []labels.Label - strings []string - series []SequenceValue - uint uint64 - float float64 - duration time.Duration + node Node + item Item + matchers []*labels.Matcher + matcher *labels.Matcher + label labels.Label + labels labels.Labels + lblList []labels.Label + strings []string + series []SequenceValue + histogram *histogram.FloatHistogram + descriptors map[string]interface{} + bucket_set []float64 + int int64 + uint uint64 + float float64 + duration time.Duration } @@ -54,6 +60,8 @@ IDENTIFIER LEFT_BRACE LEFT_BRACKET LEFT_PAREN +OPEN_HIST +CLOSE_HIST METRIC_IDENTIFIER NUMBER RIGHT_BRACE @@ -64,6 +72,20 @@ SPACE STRING TIMES +// Histogram Descriptors. +%token histogramDescStart +%token +SUM_DESC +COUNT_DESC +SCHEMA_DESC +OFFSET_DESC +NEGATIVE_OFFSET_DESC +BUCKETS_DESC +NEGATIVE_BUCKETS_DESC +ZERO_BUCKET_DESC +ZERO_BUCKET_WIDTH_DESC +%token histogramDescEnd + // Operators. %token operatorsStart %token @@ -145,6 +167,10 @@ START_METRIC_SELECTOR %type